intersections: create inters module and initial functionality.

This commit is contained in:
Bill Thiede 2021-07-16 21:06:57 -07:00
parent 8b451a2395
commit 0ce1e8f7af
3 changed files with 68 additions and 3 deletions

View File

@ -0,0 +1,64 @@
use std::ops::Index;
use crate::spheres::Sphere;
pub struct Intersection<'i> {
pub t: f32,
pub object: &'i Sphere,
}
impl<'i> Intersection<'i> {
/// Create new `Intersection` at the given `t` that hits the given `object`.
///
/// # Examples
/// ```
/// use rtchallenge::{intersections::Intersection, spheres::Sphere};
///
/// // An intersection ecapsulates t and object.
/// let s = Sphere::default();
/// let i = Intersection::new(3.5, &s);
/// assert_eq!(i.t, 3.5);
/// assert_eq!(i.object, &s);
/// ```
pub fn new(t: f32, object: &Sphere) -> Intersection {
Intersection { t, object }
}
}
/// Aggregates `Intersection`s.
///
/// # Examples
/// ```
/// use rtchallenge::{
/// intersections::{Intersection, Intersections},
/// spheres::Sphere,
/// };
///
/// let s = Sphere::default();
/// let i1 = Intersection::new(1., &s);
/// let i2 = Intersection::new(2., &s);
/// let xs = Intersections::new(vec![i1, i2]);
/// assert_eq!(xs.len(), 2);
/// assert_eq!(xs[0].t, 1.);
/// assert_eq!(xs[1].t, 2.);
/// ```
pub struct Intersections<'i>(Vec<Intersection<'i>>);
impl<'i> Intersections<'i> {
pub fn new(xs: Vec<Intersection<'i>>) -> Intersections {
Intersections(xs)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn hit(&self) -> Option<&Intersection> {
todo!("Intersections::hit")
}
}
impl<'i> Index<usize> for Intersections<'i> {
type Output = Intersection<'i>;
fn index(&self, idx: usize) -> &Self::Output {
&self.0[idx]
}
}

View File

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

View File

@ -3,9 +3,9 @@ use crate::{
tuples::{dot, Tuple},
};
#[derive(Default)]
#[derive(Default, Debug, PartialEq)]
/// Sphere represents the unit-sphere (radius of unit 1.) at the origin 0., 0., 0.
pub struct Sphere {}
pub struct Intersection {}
/// Intersect a ray with a sphere.
///
@ -41,7 +41,6 @@ pub struct Intersection {}
/// let xs = intersect(&s, &r);
/// assert_eq!(xs, vec![-6., -4.]);
/// ```
pub fn intersect(_sphere: &Sphere, ray: &Ray) -> Vec<f32> {
let sphere_to_ray = ray.origin - Tuple::point(0., 0., 0.);
let a = dot(ray.direction, ray.direction);