sphere: use Intersections as the return type from intersect.

This commit is contained in:
Bill Thiede 2021-07-16 22:25:26 -07:00
parent ad7b10322f
commit cb1b3ec801
2 changed files with 11 additions and 10 deletions

View File

@ -51,6 +51,7 @@ impl<'i> Intersection<'i> {
/// assert_eq!(xs[0].object, &s);
/// assert_eq!(xs[1].object, &s);
/// ```
#[derive(Debug, Default, PartialEq)]
pub struct Intersections<'i>(Vec<Intersection<'i>>);
impl<'i> Intersections<'i> {

View File

@ -1,5 +1,5 @@
use crate::{
intersections::Intersection,
intersections::{Intersection, Intersections},
matrices::Matrix4x4,
rays::Ray,
tuples::{dot, Tuple},
@ -39,7 +39,7 @@ impl Default for Sphere {
/// # Examples
/// ```
/// use rtchallenge::{
/// intersections::Intersection,
/// intersections::{Intersection, Intersections},
/// matrices::Matrix4x4,
/// rays::Ray,
/// spheres::{intersect, Sphere},
@ -52,14 +52,14 @@ impl Default for Sphere {
/// let xs = intersect(&s, &r);
/// assert_eq!(
/// xs,
/// vec![Intersection::new(4., &s), Intersection::new(6., &s)]
/// Intersections::new(vec![Intersection::new(4., &s), Intersection::new(6., &s)])
/// );
///
/// // A ray intersects a sphere at a tangent.
/// let r = Ray::new(Tuple::point(0., 2., -5.), Tuple::vector(0., 0., 1.));
/// let s = Sphere::default();
/// let xs = intersect(&s, &r);
/// assert_eq!(xs, vec![]);
/// assert_eq!(xs, Intersections::default());
///
/// // A ray originates inside a sphere.
/// let r = Ray::new(Tuple::point(0., 0., 0.), Tuple::vector(0., 0., 1.));
@ -67,7 +67,7 @@ impl Default for Sphere {
/// let xs = intersect(&s, &r);
/// assert_eq!(
/// xs,
/// vec![Intersection::new(-1., &s), Intersection::new(1., &s)]
/// Intersections::new(vec![Intersection::new(-1., &s), Intersection::new(1., &s)])
/// );
///
/// // A sphere is behind a ray.
@ -76,7 +76,7 @@ impl Default for Sphere {
/// let xs = intersect(&s, &r);
/// assert_eq!(
/// xs,
/// vec![Intersection::new(-6., &s), Intersection::new(-4., &s)]
/// Intersections::new(vec![Intersection::new(-6., &s), Intersection::new(-4., &s)])
/// );
///
/// // Intersect a scaled sphere with a ray.
@ -95,7 +95,7 @@ impl Default for Sphere {
/// let xs = intersect(&s, &r);
/// assert_eq!(xs.len(), 0);
/// ```
pub fn intersect<'s>(sphere: &'s Sphere, ray: &Ray) -> Vec<Intersection<'s>> {
pub fn intersect<'s>(sphere: &'s Sphere, ray: &Ray) -> Intersections<'s> {
let ray = ray.transform(sphere.transform.inverse());
let sphere_to_ray = ray.origin - Tuple::point(0., 0., 0.);
let a = dot(ray.direction, ray.direction);
@ -103,11 +103,11 @@ pub fn intersect<'s>(sphere: &'s Sphere, ray: &Ray) -> Vec<Intersection<'s>> {
let c = dot(sphere_to_ray, sphere_to_ray) - 1.;
let discriminant = b * b - 4. * a * c;
if discriminant < 0. {
vec![]
Intersections::default()
} else {
vec![
Intersections::new(vec![
Intersection::new((-b - discriminant.sqrt()) / (2. * a), &sphere),
Intersection::new((-b + discriminant.sqrt()) / (2. * a), &sphere),
]
])
}
}