diff --git a/rtchallenge/src/tuples.rs b/rtchallenge/src/tuples.rs index 5c5f12e..681819f 100644 --- a/rtchallenge/src/tuples.rs +++ b/rtchallenge/src/tuples.rs @@ -46,6 +46,28 @@ impl Tuple { } } +/// Reflects vector v across normal n. +/// +/// # Examples +/// ``` +/// use rtchallenge::tuples::{reflect, Tuple}; +/// +/// // Reflecting a vector approaching at 45° +/// let v = Tuple::vector(1., -1., 0.); +/// let n = Tuple::vector(0., 1., 0.); +/// let r = reflect(v, n); +/// assert_eq!(r, Tuple::vector(1., 1., 0.)); +/// +/// // Reflecting off a slanted surface. +/// let v = Tuple::vector(0., -1., 0.); +/// let n = Tuple::vector(2_f32.sqrt() / 2., 2_f32.sqrt() / 2., 0.); +/// let r = reflect(v, n); +/// assert_eq!(r, Tuple::vector(1., 0., 0.)); +/// ``` +pub fn reflect(v: Tuple, n: Tuple) -> Tuple { + v - n * 2. * dot(v, n) +} + impl Add for Tuple { type Output = Self; fn add(self, other: Self) -> Self {