6.3.An Abstraction for Hittable Objects

This commit is contained in:
dengqn 2025-08-03 01:33:15 +08:00
parent 3fbe40c149
commit 63ccb552fd
2 changed files with 46 additions and 0 deletions

5
src/hittable.rs Normal file
View File

@ -0,0 +1,5 @@
use crate::types_defined::{HitRecord, Ray};
pub trait Hittable {
fn hit(self, r: &Ray, t_min: f32, t_max: f32) -> HitRecord;
}

41
src/sphere.rs Normal file
View File

@ -0,0 +1,41 @@
use crate::hittable;
use crate::types_defined::{HitRecord, Point, Ray, Sphere};
impl Sphere {
pub fn new(c: Point, r: f32) -> Self {
Self {
center: c,
radius: r,
}
}
}
impl hittable::Hittable for Sphere {
fn hit(self, r: &Ray, t_min: f32, t_max: f32) -> HitRecord {
let a: f32 = r.direction.length_squared();
let h = r.direction.dot(self.center - r.point);
// let b = -2.0 * r.direction.dot(sphere_center - r.point);
let c = (self.center - r.point).length_squared() - self.radius * self.radius;
let discriminant = h * h - a * c;
// // 两个焦点
let disc_sqrt = discriminant.sqrt();
let near = (h - disc_sqrt) / a;
let far = (h + disc_sqrt) / a;
let mut root = near;
if root <= t_min || root >= t_max {
root = far;
if root <= t_min || root >= t_max {
root = -1.0;
}
}
HitRecord {
t: root,
p: r.at(root),
normal: r.at(root) - self.center,
}
}
}