From 7c43c3fb82c2746e7da2da4c5f58fa057729d3b3 Mon Sep 17 00:00:00 2001 From: Robert Garrett Date: Sat, 23 Sep 2023 13:26:42 -0700 Subject: [PATCH] Rewrite hittable list hit method using iter magic The loop can go away completely and be replaced with an iterator. Yay for Rust iterators! --- src/scene.rs | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/src/scene.rs b/src/scene.rs index 81c7459..b44821a 100644 --- a/src/scene.rs +++ b/src/scene.rs @@ -30,19 +30,15 @@ impl Hittable { pub fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> Option { match self { Hittable::HittableList { hittables } => { - let mut might_return: Option = None; - let mut hit_anything = false; - let mut nearest_t = t_max; - for item in hittables { - if let Some(record) = item.hit(r, t_min, nearest_t){ - hit_anything = true; - nearest_t = record.t; - might_return = Some(record); - } - } - if hit_anything{ - return might_return; - } else { return None; } + hittables.iter() + .map( |obj| -> Option { + obj.hit(r, t_min, t_max) + }).filter(|obj| obj.is_some()) + .min_by(|lhs, rhs| { + let lhs = lhs.as_ref().unwrap(); + let rhs = rhs.as_ref().unwrap(); + lhs.t.partial_cmp(&rhs.t).expect("Couldn't compare??") + }).unwrap_or(None) } Hittable::Sphere { center, radius, material } => {