Skip to main content

euv_core/game/engine3d/bvh/
impl.rs

1use super::*;
2
3/// Compact hot-geometry ray intersection kernel for `BvhGeomTri`.
4impl BvhGeomTri {
5    /// Extracts compact 36-byte hot geometry from a `BvhTriangle`.
6    ///
7    /// # Arguments
8    ///
9    /// - `&BvhTriangle` - Source world-space triangle.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - L1-cache-compact triangle geometry.
14    #[must_use]
15    pub(crate) fn from_triangle(tri: &BvhTriangle) -> Self {
16        let v0: Vec3 = tri.get_v0();
17        let e1: Vec3 = tri.get_edge1();
18        let e2: Vec3 = tri.get_edge2();
19        Self {
20            v0: [v0.get_x(), v0.get_y(), v0.get_z()],
21            e1: [e1.get_x(), e1.get_y(), e1.get_z()],
22            e2: [e2.get_x(), e2.get_y(), e2.get_z()],
23        }
24    }
25
26    /// Deferred-division Möller–Trumbore ray-triangle test avoiding division on rejected triangles.
27    ///
28    /// # Arguments
29    ///
30    /// - `&Self` - Compact triangle geometry reference.
31    /// - `Vec3` - Ray origin.
32    /// - `Vec3` - Unit ray direction.
33    /// - `f32` - Minimum valid distance.
34    /// - `f32` - Maximum valid distance.
35    ///
36    /// # Returns
37    ///
38    /// - `Option<f32>` - Parametric hit distance if intersected.
39    #[must_use]
40    pub(crate) fn intersect_raw(
41        &self,
42        origin: Vec3,
43        dir: Vec3,
44        t_min: f32,
45        t_max: f32,
46    ) -> Option<f32> {
47        let Self { v0, e1, e2 } = self;
48        let dx: f32 = dir.get_x();
49        let dy: f32 = dir.get_y();
50        let dz: f32 = dir.get_z();
51        let hx: f32 = dy * e2[2] - dz * e2[1];
52        let hy: f32 = dz * e2[0] - dx * e2[2];
53        let hz: f32 = dx * e2[1] - dy * e2[0];
54        let det: f32 = e1[0] * hx + e1[1] * hy + e1[2] * hz;
55        let sx: f32 = origin.get_x() - v0[0];
56        let sy: f32 = origin.get_y() - v0[1];
57        let sz: f32 = origin.get_z() - v0[2];
58        if det > 1e-6 {
59            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
60            if u_raw < 0.0 || u_raw > det {
61                return None;
62            }
63            let qx: f32 = sy * e1[2] - sz * e1[1];
64            let qy: f32 = sz * e1[0] - sx * e1[2];
65            let qz: f32 = sx * e1[1] - sy * e1[0];
66            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
67            if v_raw < 0.0 || u_raw + v_raw > det {
68                return None;
69            }
70            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
71            if t_raw <= t_min * det || t_raw >= t_max * det {
72                return None;
73            }
74            Some(t_raw / det)
75        } else if det < -1e-6 {
76            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
77            if u_raw > 0.0 || u_raw < det {
78                return None;
79            }
80            let qx: f32 = sy * e1[2] - sz * e1[1];
81            let qy: f32 = sz * e1[0] - sx * e1[2];
82            let qz: f32 = sx * e1[1] - sy * e1[0];
83            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
84            if v_raw > 0.0 || u_raw + v_raw < det {
85                return None;
86            }
87            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
88            if t_raw >= t_min * det || t_raw <= t_max * det {
89                return None;
90            }
91            Some(t_raw / det)
92        } else {
93            None
94        }
95    }
96
97    /// Zero-division occlusion-only Möller–Trumbore test for shadow rays within `(t_min, t_max)`.
98    ///
99    /// # Arguments
100    ///
101    /// - `&Self` - Compact triangle geometry reference.
102    /// - `Vec3` - Ray origin.
103    /// - `Vec3` - Unit ray direction.
104    /// - `f32` - Minimum valid distance.
105    /// - `f32` - Maximum valid distance.
106    ///
107    /// # Returns
108    ///
109    /// - `bool` - `true` when the ray intersects this triangle within `(t_min, t_max)`.
110    #[must_use]
111    pub(crate) fn intersect_any_raw(
112        &self,
113        origin: Vec3,
114        dir: Vec3,
115        t_min: f32,
116        t_max: f32,
117    ) -> bool {
118        let Self { v0, e1, e2 } = self;
119        let dx: f32 = dir.get_x();
120        let dy: f32 = dir.get_y();
121        let dz: f32 = dir.get_z();
122        let hx: f32 = dy * e2[2] - dz * e2[1];
123        let hy: f32 = dz * e2[0] - dx * e2[2];
124        let hz: f32 = dx * e2[1] - dy * e2[0];
125        let det: f32 = e1[0] * hx + e1[1] * hy + e1[2] * hz;
126        let sx: f32 = origin.get_x() - v0[0];
127        let sy: f32 = origin.get_y() - v0[1];
128        let sz: f32 = origin.get_z() - v0[2];
129        if det > 1e-6 {
130            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
131            if u_raw < 0.0 || u_raw > det {
132                return false;
133            }
134            let qx: f32 = sy * e1[2] - sz * e1[1];
135            let qy: f32 = sz * e1[0] - sx * e1[2];
136            let qz: f32 = sx * e1[1] - sy * e1[0];
137            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
138            if v_raw < 0.0 || u_raw + v_raw > det {
139                return false;
140            }
141            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
142            t_raw > t_min * det && t_raw < t_max * det
143        } else if det < -1e-6 {
144            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
145            if u_raw > 0.0 || u_raw < det {
146                return false;
147            }
148            let qx: f32 = sy * e1[2] - sz * e1[1];
149            let qy: f32 = sz * e1[0] - sx * e1[2];
150            let qz: f32 = sx * e1[1] - sy * e1[0];
151            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
152            if v_raw > 0.0 || u_raw + v_raw < det {
153                return false;
154            }
155            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
156            t_raw < t_min * det && t_raw > t_max * det
157        } else {
158            false
159        }
160    }
161}
162
163/// Scalar-register ray-box slab kernel for 32-byte `BvhFlatNode`.
164impl BvhFlatNode {
165    /// Computes branchless near-entry slab intersection distance, or `f32::INFINITY` on miss.
166    ///
167    /// # Arguments
168    ///
169    /// - `&Self` - Flat node reference.
170    /// - `[f32; 3]` - Ray origin `(ox, oy, oz)`.
171    /// - `[f32; 3]` - Precomputed safe reciprocal direction `(ix, iy, iz)`.
172    /// - `f32` - Minimum valid distance.
173    /// - `f32` - Maximum valid distance.
174    ///
175    /// # Returns
176    ///
177    /// - `f32` - Near intersection distance if hit, or `f32::INFINITY` on miss.
178    #[must_use]
179    pub(crate) fn intersect_near(
180        &self,
181        orig: [f32; 3],
182        inv: [f32; 3],
183        t_min: f32,
184        t_max: f32,
185    ) -> f32 {
186        let Self { min, max, .. } = self;
187        let tx1: f32 = (min[0] - orig[0]) * inv[0];
188        let tx2: f32 = (max[0] - orig[0]) * inv[0];
189        let mut tmin: f32 = t_min.max(tx1.min(tx2));
190        let mut tmax: f32 = t_max.min(tx1.max(tx2));
191        let ty1: f32 = (min[1] - orig[1]) * inv[1];
192        let ty2: f32 = (max[1] - orig[1]) * inv[1];
193        tmin = tmin.max(ty1.min(ty2));
194        tmax = tmax.min(ty1.max(ty2));
195        let tz1: f32 = (min[2] - orig[2]) * inv[2];
196        let tz2: f32 = (max[2] - orig[2]) * inv[2];
197        tmin = tmin.max(tz1.min(tz2));
198        tmax = tmax.min(tz1.max(tz2));
199        if tmax >= tmin && tmax >= 0.0 {
200            tmin
201        } else {
202            f32::INFINITY
203        }
204    }
205}
206
207/// Triangle construction and Möller–Trumbore ray intersection for `BvhTriangle`.
208impl BvhTriangle {
209    /// Creates a world-space `BvhTriangle` from three vertices and its surface `PbrMaterial`.
210    ///
211    /// # Arguments
212    ///
213    /// - `Vec3` - First vertex.
214    /// - `Vec3` - Second vertex.
215    /// - `Vec3` - Third vertex.
216    /// - `PbrMaterial` - Surface PBR material.
217    ///
218    /// # Returns
219    ///
220    /// - `Self` - Precomputed BVH triangle record.
221    #[must_use]
222    pub fn from_points(v0: Vec3, v1: Vec3, v2: Vec3, material: PbrMaterial) -> Self {
223        let edge1: Vec3 = v1.sub(v0);
224        let edge2: Vec3 = v2.sub(v0);
225        let normal: Vec3 = edge1.cross(edge2).normalize();
226        let centroid: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
227        let mut bounds: Aabb3D = Aabb3D::empty();
228        bounds.expand_point(v0);
229        bounds.expand_point(v1);
230        bounds.expand_point(v2);
231        Self {
232            v0,
233            edge1,
234            edge2,
235            normal,
236            centroid,
237            bounds,
238            material,
239        }
240    }
241
242    /// Tests `ray` against this triangle using Möller–Trumbore returning hit distance in `(t_min, t_max)`.
243    ///
244    /// # Arguments
245    ///
246    /// - `&Self` - Triangle reference.
247    /// - `&Ray3D` - Query ray.
248    /// - `f32` - Minimum valid distance.
249    /// - `f32` - Maximum valid distance.
250    ///
251    /// # Returns
252    ///
253    /// - `Option<f32>` - Parametric hit distance if intersected.
254    #[must_use]
255    pub fn intersect(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<f32> {
256        let g: BvhGeomTri = BvhGeomTri::from_triangle(self);
257        g.intersect_raw(ray.get_origin(), ray.get_direction(), t_min, t_max)
258    }
259}
260
261/// Binned Surface Area Heuristic (SAH) BVH construction and near-child-first ray traversal for `Bvh3D`.
262impl Bvh3D {
263    /// Builds a tight SAH flat BVH over `triangles` and populates its 32-byte DFS node and 36-byte geometry mirrors.
264    ///
265    /// # Arguments
266    ///
267    /// - `Vec<BvhTriangle>` - World-space triangles to index.
268    ///
269    /// # Returns
270    ///
271    /// - `Self` - Constructed SAH BVH acceleration structure.
272    #[must_use]
273    pub fn build(triangles: Vec<BvhTriangle>) -> Self {
274        let tri_len: usize = triangles.len();
275        let mut bvh: Self = Self {
276            nodes: Vec::with_capacity(tri_len * 2 + 1),
277            triangles,
278            geom: Vec::with_capacity(tri_len),
279            flat_nodes: Vec::with_capacity(tri_len * 2 + 1),
280        };
281        if !bvh.get_triangles().is_empty() {
282            let total: usize = bvh.get_triangles().len();
283            let _: u32 = bvh.build_node(0, total);
284            let Self {
285                nodes,
286                triangles,
287                geom,
288                flat_nodes,
289            } = &mut bvh;
290            geom.clear();
291            for tri in triangles.iter() {
292                geom.push(BvhGeomTri::from_triangle(tri));
293            }
294            flat_nodes.clear();
295            for n in nodes.iter() {
296                let mn: Vec3 = n.get_bounds().get_min();
297                let mx: Vec3 = n.get_bounds().get_max();
298                let tc: u32 = n.get_tri_count();
299                flat_nodes.push(BvhFlatNode {
300                    min: [mn.get_x(), mn.get_y(), mn.get_z()],
301                    right_or_first: if tc > 0 {
302                        n.get_first_tri()
303                    } else {
304                        n.get_right()
305                    },
306                    max: [mx.get_x(), mx.get_y(), mx.get_z()],
307                    tri_count: tc,
308                });
309            }
310        }
311        bvh
312    }
313
314    /// Extracts the `axis` coordinate (`0 = x`, `1 = y`, `2 = z`) from vector `v`.
315    ///
316    /// # Arguments
317    ///
318    /// - `Vec3` - Source 3D vector.
319    /// - `usize` - Axis index.
320    ///
321    /// # Returns
322    ///
323    /// - `f32` - Selected scalar component.
324    #[must_use]
325    fn vec_axis(v: Vec3, axis: usize) -> f32 {
326        match axis {
327            0 => v.get_x(),
328            1 => v.get_y(),
329            _ => v.get_z(),
330        }
331    }
332
333    /// Evaluates 12-bin Surface Area Heuristic splits across all three axes and returns `(best_axis, best_split_pos)`.
334    ///
335    /// # Arguments
336    ///
337    /// - `&[BvhTriangle]` - Active triangle range.
338    /// - `Aabb3D` - Centroid bounding box of the range.
339    /// - `f32` - Parent bounding-box surface area.
340    ///
341    /// # Returns
342    ///
343    /// - `Option<(usize, f32)>` - Optimal split axis and threshold if cheaper than forming a leaf.
344    #[must_use]
345    fn find_sah_split(
346        tris: &[BvhTriangle],
347        cent_bounds: Aabb3D,
348        parent_area: f32,
349    ) -> Option<(usize, f32)> {
350        let bins: usize = 12;
351        let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
352        let mut best_cost: f32 = (tris.len() as f32) * parent_area;
353        let mut best_split: Option<(usize, f32)> = None;
354        for axis in 0..3 {
355            let ext: f32 = Self::vec_axis(extent, axis);
356            if ext < 1e-5 {
357                continue;
358            }
359            let cmin: f32 = Self::vec_axis(cent_bounds.get_min(), axis);
360            let scale: f32 = (bins as f32) / ext;
361            let mut bin_bounds: [Aabb3D; 12] = [Aabb3D::empty(); 12];
362            let mut bin_counts: [u32; 12] = [0; 12];
363            for tri in tris.iter() {
364                let c: f32 = Self::vec_axis(tri.get_centroid(), axis);
365                let b_idx: usize = (((c - cmin) * scale) as usize).min(bins - 1);
366                bin_counts[b_idx] += 1;
367                bin_bounds[b_idx].expand_box(tri.get_bounds());
368            }
369            let mut left_area: [f32; 11] = [0.0; 11];
370            let mut left_count: [u32; 11] = [0; 11];
371            let mut acc_box: Aabb3D = Aabb3D::empty();
372            let mut acc_cnt: u32 = 0;
373            for i in 0..(bins - 1) {
374                acc_cnt += bin_counts[i];
375                if bin_counts[i] > 0 {
376                    acc_box.expand_box(bin_bounds[i]);
377                }
378                left_count[i] = acc_cnt;
379                left_area[i] = if acc_cnt > 0 {
380                    acc_box.surface_area()
381                } else {
382                    0.0
383                };
384            }
385            let mut r_box: Aabb3D = Aabb3D::empty();
386            let mut r_cnt: u32 = 0;
387            for i in (1..bins).rev() {
388                r_cnt += bin_counts[i];
389                if bin_counts[i] > 0 {
390                    r_box.expand_box(bin_bounds[i]);
391                }
392                let l_cnt: u32 = left_count[i - 1];
393                if l_cnt == 0 || r_cnt == 0 {
394                    continue;
395                }
396                let r_area: f32 = r_box.surface_area();
397                let cost: f32 =
398                    0.5 * parent_area + (l_cnt as f32) * left_area[i - 1] + (r_cnt as f32) * r_area;
399                if cost < best_cost {
400                    best_cost = cost;
401                    let split_pos: f32 = cmin + (i as f32) * (ext / (bins as f32));
402                    best_split = Some((axis, split_pos));
403                }
404            }
405        }
406        best_split
407    }
408
409    /// Recursively partitions `triangles[start..end]` via binned SAH in DFS pre-order and appends a `BvhNode3D`.
410    ///
411    /// # Arguments
412    ///
413    /// - `&Self` - Mutable BVH builder reference.
414    /// - `usize` - Inclusive start index.
415    /// - `usize` - Exclusive end index.
416    ///
417    /// # Returns
418    ///
419    /// - `u32` - Index of the created node in `self.nodes`.
420    fn build_node(&mut self, start: usize, end: usize) -> u32 {
421        let count: usize = end - start;
422        let mut bounds: Aabb3D = Aabb3D::empty();
423        let mut cent_bounds: Aabb3D = Aabb3D::empty();
424        for tri in self.get_triangles()[start..end].iter() {
425            bounds.expand_box(tri.get_bounds());
426            cent_bounds.expand_point(tri.get_centroid());
427        }
428        let node_idx: u32 = self.get_nodes().len() as u32;
429        self.get_mut_nodes().push(BvhNode3D {
430            bounds,
431            left: 0,
432            right: 0,
433            first_tri: start as u32,
434            tri_count: count as u32,
435        });
436        if count <= 3 {
437            return node_idx;
438        }
439        let parent_area: f32 = bounds.surface_area().max(1e-6);
440        let split_opt: Option<(usize, f32)> =
441            Self::find_sah_split(&self.get_triangles()[start..end], cent_bounds, parent_area);
442        let mid: usize = if let Some((axis, split_pos)) = split_opt {
443            let slice: &mut [BvhTriangle] = &mut self.get_mut_triangles()[start..end];
444            let mut i: usize = 0;
445            let mut j: usize = slice.len();
446            while i < j {
447                if Self::vec_axis(slice[i].get_centroid(), axis) < split_pos {
448                    i += 1;
449                } else {
450                    j -= 1;
451                    slice.swap(i, j);
452                }
453            }
454            if i == 0 || i == count {
455                start + count / 2
456            } else {
457                start + i
458            }
459        } else if count <= 6 {
460            return node_idx;
461        } else {
462            let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
463            let axis: usize =
464                if extent.get_x() >= extent.get_y() && extent.get_x() >= extent.get_z() {
465                    0
466                } else if extent.get_y() >= extent.get_z() {
467                    1
468                } else {
469                    2
470                };
471            let mid_pos: f32 =
472                Self::vec_axis(cent_bounds.get_min(), axis) + Self::vec_axis(extent, axis) * 0.5;
473            let slice: &mut [BvhTriangle] = &mut self.get_mut_triangles()[start..end];
474            let mut i: usize = 0;
475            let mut j: usize = slice.len();
476            while i < j {
477                if Self::vec_axis(slice[i].get_centroid(), axis) < mid_pos {
478                    i += 1;
479                } else {
480                    j -= 1;
481                    slice.swap(i, j);
482                }
483            }
484            if i == 0 || i == count {
485                start + count / 2
486            } else {
487                start + i
488            }
489        };
490        let left_idx: u32 = self.build_node(start, mid);
491        let right_idx: u32 = self.build_node(mid, end);
492        let node: &mut BvhNode3D = &mut self.get_mut_nodes()[node_idx as usize];
493        node.set_left(left_idx);
494        node.set_right(right_idx);
495        node.set_tri_count(0);
496        node_idx
497    }
498
499    /// Traces a shadow/occlusion ray using 32-byte DFS nodes, zero-division Möller–Trumbore, and a 1-triangle occluder cache.
500    ///
501    /// # Arguments
502    ///
503    /// - `&Self` - BVH reference.
504    /// - `Vec3` - Ray origin.
505    /// - `Vec3` - Unit ray direction.
506    /// - `Vec3` - Precomputed safe reciprocal ray direction.
507    /// - `f32` - Minimum offset (shadow bias).
508    /// - `f32` - Maximum trace distance.
509    /// - `&mut u32` - Per-thread last-occluding triangle index cache (`u32::MAX` if empty).
510    ///
511    /// # Returns
512    ///
513    /// - `bool` - `true` if occluded by scene geometry.
514    #[must_use]
515    pub fn trace_any_shadow_cached(
516        &self,
517        origin: Vec3,
518        dir: Vec3,
519        inv_dir: Vec3,
520        t_min: f32,
521        t_max: f32,
522        cached_tri: &mut u32,
523    ) -> bool {
524        let Self {
525            flat_nodes, geom, ..
526        } = self;
527        if flat_nodes.is_empty() || geom.is_empty() {
528            return false;
529        }
530        let hint: usize = *cached_tri as usize;
531        if hint < geom.len() && geom[hint].intersect_any_raw(origin, dir, t_min, t_max) {
532            return true;
533        }
534        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
535        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
536        if !flat_nodes[0]
537            .intersect_near(orig_arr, inv_arr, t_min, t_max)
538            .is_finite()
539        {
540            return false;
541        }
542        let mut stack: [u32; 64] = [0; 64];
543        let mut sp: usize = 1;
544        while sp > 0 {
545            sp -= 1;
546            let idx: u32 = stack[sp];
547            let n: &BvhFlatNode = &flat_nodes[idx as usize];
548            let count: usize = n.tri_count as usize;
549            if count > 0 {
550                let first: usize = n.right_or_first as usize;
551                for (off, tri) in geom[first..(first + count)].iter().enumerate() {
552                    if tri.intersect_any_raw(origin, dir, t_min, t_max) {
553                        *cached_tri = (first + off) as u32;
554                        return true;
555                    }
556                }
557            } else {
558                let left_idx: u32 = idx + 1;
559                let right_idx: u32 = n.right_or_first;
560                let tl: f32 =
561                    flat_nodes[left_idx as usize].intersect_near(orig_arr, inv_arr, t_min, t_max);
562                let tr: f32 =
563                    flat_nodes[right_idx as usize].intersect_near(orig_arr, inv_arr, t_min, t_max);
564                let hit_l: bool = tl.is_finite();
565                let hit_r: bool = tr.is_finite();
566                if hit_l && hit_r && sp + 2 <= 64 {
567                    if tl <= tr {
568                        stack[sp] = right_idx;
569                        stack[sp + 1] = left_idx;
570                    } else {
571                        stack[sp] = left_idx;
572                        stack[sp + 1] = right_idx;
573                    }
574                    sp += 2;
575                } else if hit_l && sp < 64 {
576                    stack[sp] = left_idx;
577                    sp += 1;
578                } else if hit_r && sp < 64 {
579                    stack[sp] = right_idx;
580                    sp += 1;
581                }
582            }
583        }
584        false
585    }
586
587    /// Traces a shadow/occlusion ray returning `true` immediately upon any hit within `(t_min, t_max)`.
588    ///
589    /// # Arguments
590    ///
591    /// - `&Self` - BVH reference.
592    /// - `&Ray3D` - Shadow ray.
593    /// - `f32` - Minimum offset (shadow bias).
594    /// - `f32` - Maximum trace distance.
595    ///
596    /// # Returns
597    ///
598    /// - `bool` - `true` if occluded by scene geometry.
599    #[must_use]
600    pub fn trace_any_shadow(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
601        let mut cache: u32 = u32::MAX;
602        self.trace_any_shadow_cached(
603            ray.get_origin(),
604            ray.get_direction(),
605            ray.get_inv_direction(),
606            t_min,
607            t_max,
608            &mut cache,
609        )
610    }
611
612    /// Traces a ray near-child-first against 32-byte DFS nodes and returns `(distance, tri_index)`.
613    ///
614    /// # Arguments
615    ///
616    /// - `&Self` - BVH reference.
617    /// - `Vec3` - Ray origin.
618    /// - `Vec3` - Unit ray direction.
619    /// - `Vec3` - Precomputed safe reciprocal ray direction.
620    /// - `f32` - Minimum offset bias.
621    /// - `f32` - Maximum trace distance.
622    ///
623    /// # Returns
624    ///
625    /// - `Option<(f32, usize)>` - Closest hit distance and triangle index into `self.triangles`.
626    #[must_use]
627    pub fn trace_closest_raw(
628        &self,
629        origin: Vec3,
630        dir: Vec3,
631        inv_dir: Vec3,
632        t_min: f32,
633        t_max: f32,
634    ) -> Option<(f32, usize)> {
635        let Self {
636            flat_nodes, geom, ..
637        } = self;
638        if flat_nodes.is_empty() || geom.is_empty() {
639            return None;
640        }
641        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
642        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
643        if !flat_nodes[0]
644            .intersect_near(orig_arr, inv_arr, t_min, t_max)
645            .is_finite()
646        {
647            return None;
648        }
649        let mut stack: [(u32, f32); 64] = [(0, 0.0); 64];
650        let mut sp: usize = 1;
651        let mut best_t: f32 = t_max;
652        let mut best_idx: usize = usize::MAX;
653        while sp > 0 {
654            sp -= 1;
655            let (node_id, node_tmin): (u32, f32) = stack[sp];
656            if node_tmin >= best_t {
657                continue;
658            }
659            let n: &BvhFlatNode = &flat_nodes[node_id as usize];
660            let count: usize = n.tri_count as usize;
661            if count > 0 {
662                let first: usize = n.right_or_first as usize;
663                for (off, tri) in geom[first..(first + count)].iter().enumerate() {
664                    if let Some(t) = tri.intersect_raw(origin, dir, t_min, best_t) {
665                        best_t = t;
666                        best_idx = first + off;
667                    }
668                }
669            } else {
670                let left_idx: u32 = node_id + 1;
671                let right_idx: u32 = n.right_or_first;
672                let tl: f32 =
673                    flat_nodes[left_idx as usize].intersect_near(orig_arr, inv_arr, t_min, best_t);
674                let tr: f32 =
675                    flat_nodes[right_idx as usize].intersect_near(orig_arr, inv_arr, t_min, best_t);
676                let hit_l: bool = tl < best_t;
677                let hit_r: bool = tr < best_t;
678                if hit_l && hit_r && sp + 2 <= 64 {
679                    if tl <= tr {
680                        stack[sp] = (right_idx, tr);
681                        stack[sp + 1] = (left_idx, tl);
682                    } else {
683                        stack[sp] = (left_idx, tl);
684                        stack[sp + 1] = (right_idx, tr);
685                    }
686                    sp += 2;
687                } else if hit_l && sp < 64 {
688                    stack[sp] = (left_idx, tl);
689                    sp += 1;
690                } else if hit_r && sp < 64 {
691                    stack[sp] = (right_idx, tr);
692                    sp += 1;
693                }
694            }
695        }
696        if best_idx == usize::MAX {
697            None
698        } else {
699            Some((best_t, best_idx))
700        }
701    }
702
703    /// Traces a reflection/GI ray and returns the closest hit surface within `(t_min, t_max)`.
704    ///
705    /// # Arguments
706    ///
707    /// - `&Self` - BVH reference.
708    /// - `&Ray3D` - Reflection or GI ray.
709    /// - `f32` - Minimum offset bias.
710    /// - `f32` - Maximum trace distance.
711    ///
712    /// # Returns
713    ///
714    /// - `Option<RayHit3D>` - Closest hit metadata if any geometry was struck.
715    #[must_use]
716    pub fn trace_closest(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<RayHit3D> {
717        let (t, idx): (f32, usize) = self.trace_closest_raw(
718            ray.get_origin(),
719            ray.get_direction(),
720            ray.get_inv_direction(),
721            t_min,
722            t_max,
723        )?;
724        let tri: &BvhTriangle = &self.get_triangles()[idx];
725        let pt: Vec3 = ray.get_origin().add(ray.get_direction().scale(t));
726        Some(RayHit3D {
727            distance: t,
728            point: pt,
729            normal: tri.get_normal(),
730            material: tri.get_material(),
731        })
732    }
733}