rays: basic ray with construction and position methods

This commit is contained in:
Bill Thiede 2021-07-16 20:13:20 -07:00
parent 191760fa13
commit f44d671573
2 changed files with 44 additions and 0 deletions

View File

@ -1,5 +1,6 @@
pub mod canvas; pub mod canvas;
pub mod matrices; pub mod matrices;
pub mod rays;
pub mod tuples; pub mod tuples;
/// Value considered close enough for PartialEq implementations. /// Value considered close enough for PartialEq implementations.

43
rtchallenge/src/rays.rs Normal file
View File

@ -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
}
}