Skip to content
1        10        20        30        40        50        60        70        801//! Small, deterministic building blocks used by the ray-tracing example.23/// A three-dimensional vector used for ray and sphere calculations.4#[derive(Clone, Copy, Debug, PartialEq)]5pub struct Vec3 {6    /// X component.7    pub x: f32,8    /// Y component.9    pub y: f32,10    /// Z component.11    pub z: f32,12}1314impl Vec3 {15    /// Creates a vector from its components.16    #[must_use]17    pub const fn new(x: f32, y: f32, z: f32) -> Self {18        Self { x, y, z }19    }2021    /// Returns the dot product with `other`.22    #[must_use]23    pub fn dot(self, other: Self) -> f32 {24        self.x25            .mul_add(other.x, self.y.mul_add(other.y, self.z * other.z))26    }2728    /// Returns the vector length.29    #[must_use]30    pub fn length(self) -> f32 {31        self.dot(self).sqrt()32    }3334    /// Returns a unit-length vector, or zero for a zero-length input.35    #[must_use]36    pub fn normalized(self) -> Self {37        let length = self.length();38        if length > f32::EPSILON {39            Self::new(self.x / length, self.y / length, self.z / length)40        } else {41            Self::new(0.0, 0.0, 0.0)42        }43    }4445    /// Adds two vectors component-wise.46    #[must_use]47    pub fn plus(self, other: Self) -> Self {48        Self::new(self.x + other.x, self.y + other.y, self.z + other.z)49    }5051    /// Subtracts `other` component-wise.52    #[must_use]53    pub fn minus(self, other: Self) -> Self {54        Self::new(self.x - other.x, self.y - other.y, self.z - other.z)55    }5657    /// Multiplies each component by `factor`.58    #[must_use]59    pub fn scaled(self, factor: f32) -> Self {60        Self::new(self.x * factor, self.y * factor, self.z * factor)61    }62}6364/// A ray with an origin and a direction.65#[derive(Clone, Copy, Debug, PartialEq)]66pub struct Ray {67    /// Ray origin.68    pub origin: Vec3,69    /// Ray direction; it need not be normalized.70    pub direction: Vec3,71}7273/// A sphere in the scene.74#[derive(Clone, Copy, Debug, PartialEq)]75pub struct Sphere {76    /// Sphere center.77    pub center: Vec3,78    /// Sphere radius, which must be positive.79    pub radius: f32,80}8182impl Sphere {83    /// Returns the nearest positive ray parameter where `ray` hits this sphere.84    #[must_use]85    pub fn hit(self, ray: Ray) -> Option<f32> {86        let offset = ray.origin.minus(self.center);87        let a = ray.direction.dot(ray.direction);88        let half_b = offset.dot(ray.direction);89        let c = offset.dot(offset) - self.radius * self.radius;90        let discriminant = half_b.mul_add(half_b, -a * c);91        if discriminant < 0.0 || a <= f32::EPSILON {92            return None;93        }9495        let root_delta = discriminant.sqrt();96        let near = (-half_b - root_delta) / a;97        if near > 0.0 {98            Some(near)99        } else {100            let far = (-half_b + root_delta) / a;101            (far > 0.0).then_some(far)102        }103    }104}105106/// Returns one of four fixed 2×2 subpixel sample positions.107///108/// The pattern repeats every four samples and does not depend on global state.109#[must_use]110pub const fn sample_offset(sample_index: u32) -> (f32, f32) {111    match sample_index % 4 {112        0 => (0.25, 0.25),113        1 => (0.75, 0.25),114        2 => (0.25, 0.75),115        _ => (0.75, 0.75),116    }117}118119#[cfg(test)]120mod tests {121    use super::{Ray, Sphere, Vec3, sample_offset};122123    #[test]124    fn sphere_hit_returns_nearest_positive_distance() {125        let sphere = Sphere {126            center: Vec3::new(0.0, 0.0, -3.0),127            radius: 1.0,128        };129        let ray = Ray {130            origin: Vec3::new(0.0, 0.0, 0.0),131            direction: Vec3::new(0.0, 0.0, -1.0),132        };133134        assert_eq!(sphere.hit(ray), Some(2.0));135    }136137    #[test]138    fn ray_from_inside_sphere_uses_far_root() {139        let sphere = Sphere {140            center: Vec3::new(0.0, 0.0, 0.0),141            radius: 2.0,142        };143        let ray = Ray {144            origin: Vec3::new(0.0, 0.0, 0.0),145            direction: Vec3::new(1.0, 0.0, 0.0),146        };147148        assert_eq!(sphere.hit(ray), Some(2.0));149    }150151    #[test]152    fn sphere_miss_and_degenerate_ray_are_safe() {153        let sphere = Sphere {154            center: Vec3::new(0.0, 0.0, -3.0),155            radius: 1.0,156        };157        let miss = Ray {158            origin: Vec3::new(0.0, 2.0, 0.0),159            direction: Vec3::new(0.0, 0.0, -1.0),160        };161        let degenerate = Ray {162            origin: Vec3::new(0.0, 0.0, 0.0),163            direction: Vec3::new(0.0, 0.0, 0.0),164        };165166        assert_eq!(sphere.hit(miss), None);167        assert_eq!(sphere.hit(degenerate), None);168    }169170    #[test]171    fn sample_pattern_is_stable_and_repeats() {172        let expected = [(0.25, 0.25), (0.75, 0.25), (0.25, 0.75), (0.75, 0.75)];173        for (index, offset) in expected.into_iter().enumerate() {174            assert_eq!(sample_offset(u32::try_from(index).unwrap()), offset);175            assert_eq!(sample_offset(u32::try_from(index + 4).unwrap()), offset);176        }177    }178179    #[test]180    fn zero_vector_normalizes_to_zero() {181        assert_eq!(182            Vec3::new(0.0, 0.0, 0.0).normalized(),183            Vec3::new(0.0, 0.0, 0.0)184        );185    }186}