From f44d671573c2f910b6e5eeef7b39cb26e02d98b4 Mon Sep 17 00:00:00 2001 From: Bill Thiede Date: Fri, 16 Jul 2021 20:13:20 -0700 Subject: [PATCH] rays: basic ray with construction and position methods --- rtchallenge/src/lib.rs | 1 + rtchallenge/src/rays.rs | 43 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 rtchallenge/src/rays.rs diff --git a/rtchallenge/src/lib.rs b/rtchallenge/src/lib.rs index 303381b..b443f53 100644 --- a/rtchallenge/src/lib.rs +++ b/rtchallenge/src/lib.rs @@ -1,5 +1,6 @@ pub mod canvas; pub mod matrices; +pub mod rays; pub mod tuples; /// Value considered close enough for PartialEq implementations. diff --git a/rtchallenge/src/rays.rs b/rtchallenge/src/rays.rs new file mode 100644 index 0000000..27c401f --- /dev/null +++ b/rtchallenge/src/rays.rs @@ -0,0 +1,43 @@ +use crate::{matrices::Matrix4x4, tuples::Tuple}; + +pub struct Ray { + pub origin: Tuple, + pub direction: Tuple, +} + +impl Ray { + /// Create a ray with the given origin point and direction vector. + /// Will panic if origin not a point or direction not a vector. + /// + /// # Examples + /// ``` + /// use rtchallenge::{rays::Ray, tuples::Tuple}; + /// + /// let origin = Tuple::point(1., 2., 3.); + /// let direction = Tuple::vector(4., 5., 6.); + /// let r = Ray::new(origin, direction); + /// assert_eq!(r.origin, origin); + /// assert_eq!(r.direction, direction); + /// ``` + pub fn new(origin: Tuple, direction: Tuple) -> Ray { + assert!(origin.is_point(), "Ray origin must be a point"); + assert!(direction.is_vector(), "Ray direction must be a vector"); + Ray { origin, direction } + } + + /// Compute a point from the given distance along the `Ray`. + /// + /// # Examples + /// ``` + /// use rtchallenge::{rays::Ray, tuples::Tuple}; + /// + /// let r = Ray::new(Tuple::point(2., 3., 4.), Tuple::vector(1., 0., 0.)); + /// assert_eq!(r.position(0.), Tuple::point(2., 3., 4.)); + /// assert_eq!(r.position(1.), Tuple::point(3., 3., 4.)); + /// assert_eq!(r.position(-1.), Tuple::point(1., 3., 4.)); + /// assert_eq!(r.position(2.5), Tuple::point(4.5, 3., 4.)); + /// ``` + pub fn position(&self, t: f32) -> Tuple { + self.origin + self.direction * t + } +}