Skip to content

Commit

Permalink
Added bounding box to Hittable trait
Browse files Browse the repository at this point in the history
  • Loading branch information
Red-Rapious committed Sep 7, 2023
1 parent 2f82787 commit 40a9510
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/aabb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl AABB {
Self { x, y, z }
}

pub fn from_points(a: &Point3<f64>, b: &Point3<f64>) -> Self {
pub fn from_points(a: Point3<f64>, b: Point3<f64>) -> Self {
Self {
x: RealInterval {
min: a.x.min(b.x) as f32,
Expand All @@ -33,6 +33,23 @@ impl AABB {
}
}

pub fn from_boxes(box0: AABB, box1: AABB) -> Self {
Self {
x: RealInterval {
min: box0.x.min.min(box0.x.min),
max: box1.x.max.max(box1.x.max),
},
y: RealInterval {
min: box0.y.min.min(box0.y.min),
max: box1.y.max.max(box1.y.max),
},
z: RealInterval {
min: box0.z.min.min(box0.z.min),
max: box1.z.max.max(box1.z.max),
}
}
}

fn axis(&self, axis: usize) -> &RealInterval {
match axis {
0 => &self.x,
Expand Down
14 changes: 14 additions & 0 deletions src/geometry.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::material::Material;
use crate::ray::Ray;
use crate::world::HitRecord;
use crate::aabb::AABB;

use nalgebra::{Point3, Vector3};
use real_interval::RealInterval;
Expand All @@ -9,6 +10,7 @@ use real_interval::RealInterval;
pub trait Hittable {
/// Check if the given ray hits the hittable. If so, it adds informations about the hit to `hit_record`.
fn hit(&self, ray: &Ray, t_interval: RealInterval, hit_record: &mut HitRecord) -> bool;
fn bounding_box(&self) -> &AABB;
}

/// A basic Sphere geometry.
Expand All @@ -18,16 +20,19 @@ pub struct Sphere {
material: Material,
is_moving: bool,
center_vec: Vector3<f64>,
bbox: AABB,
}

impl Sphere {
pub fn stationary(center: Point3<f64>, radius: f64, material: Material) -> Self {
let radius_vector = Vector3::new(radius, radius, radius);
Self {
center1: center,
radius,
material,
is_moving: false,
center_vec: Vector3::zeros(),
bbox: AABB::from_points(center - radius_vector, center + radius_vector)
}
}

Expand All @@ -37,12 +42,17 @@ impl Sphere {
radius: f64,
material: Material,
) -> Self {
let radius_vector = Vector3::new(radius, radius, radius);
let bbox1 = AABB::from_points(center1 - radius_vector, center1 + radius_vector);
let bbox2 = AABB::from_points(center2 - radius_vector, center2 + radius_vector);

Self {
center1,
radius,
material,
is_moving: true,
center_vec: center2 - center1,
bbox: AABB::from_boxes(bbox1, bbox2)
}
}

Expand Down Expand Up @@ -92,4 +102,8 @@ impl Hittable for Sphere {

true // there's a hit
}

fn bounding_box(&self) -> &AABB {
&self.bbox
}
}

0 comments on commit 40a9510

Please sign in to comment.