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    #[inline(always)]
40    #[must_use]
41    pub(crate) fn intersect_raw(
42        &self,
43        origin: Vec3,
44        dir: Vec3,
45        t_min: f32,
46        t_max: f32,
47    ) -> Option<f32> {
48        let Self { v0, e1, e2 } = self;
49        let dx: f32 = dir.get_x();
50        let dy: f32 = dir.get_y();
51        let dz: f32 = dir.get_z();
52        let hx: f32 = dy * e2[2] - dz * e2[1];
53        let hy: f32 = dz * e2[0] - dx * e2[2];
54        let hz: f32 = dx * e2[1] - dy * e2[0];
55        let det: f32 = e1[0] * hx + e1[1] * hy + e1[2] * hz;
56        let sx: f32 = origin.get_x() - v0[0];
57        let sy: f32 = origin.get_y() - v0[1];
58        let sz: f32 = origin.get_z() - v0[2];
59        if det > 1e-6 {
60            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
61            if u_raw < 0.0 || u_raw > det {
62                return None;
63            }
64            let qx: f32 = sy * e1[2] - sz * e1[1];
65            let qy: f32 = sz * e1[0] - sx * e1[2];
66            let qz: f32 = sx * e1[1] - sy * e1[0];
67            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
68            if v_raw < 0.0 || u_raw + v_raw > det {
69                return None;
70            }
71            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
72            if t_raw <= t_min * det || t_raw >= t_max * det {
73                return None;
74            }
75            Some(t_raw / det)
76        } else if det < -1e-6 {
77            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
78            if u_raw > 0.0 || u_raw < det {
79                return None;
80            }
81            let qx: f32 = sy * e1[2] - sz * e1[1];
82            let qy: f32 = sz * e1[0] - sx * e1[2];
83            let qz: f32 = sx * e1[1] - sy * e1[0];
84            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
85            if v_raw > 0.0 || u_raw + v_raw < det {
86                return None;
87            }
88            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
89            if t_raw >= t_min * det || t_raw <= t_max * det {
90                return None;
91            }
92            Some(t_raw / det)
93        } else {
94            None
95        }
96    }
97
98    /// Zero-division occlusion-only Möller–Trumbore test for shadow rays within `(t_min, t_max)`.
99    ///
100    /// # Arguments
101    ///
102    /// - `&Self` - Compact triangle geometry reference.
103    /// - `Vec3` - Ray origin.
104    /// - `Vec3` - Unit ray direction.
105    /// - `f32` - Minimum valid distance.
106    /// - `f32` - Maximum valid distance.
107    ///
108    /// # Returns
109    ///
110    /// - `bool` - `true` when the ray intersects this triangle within `(t_min, t_max)`.
111    #[inline(always)]
112    #[must_use]
113    pub(crate) fn intersect_any_raw(
114        &self,
115        origin: Vec3,
116        dir: Vec3,
117        t_min: f32,
118        t_max: f32,
119    ) -> bool {
120        let Self { v0, e1, e2 } = self;
121        let dx: f32 = dir.get_x();
122        let dy: f32 = dir.get_y();
123        let dz: f32 = dir.get_z();
124        let hx: f32 = dy * e2[2] - dz * e2[1];
125        let hy: f32 = dz * e2[0] - dx * e2[2];
126        let hz: f32 = dx * e2[1] - dy * e2[0];
127        let det: f32 = e1[0] * hx + e1[1] * hy + e1[2] * hz;
128        let sx: f32 = origin.get_x() - v0[0];
129        let sy: f32 = origin.get_y() - v0[1];
130        let sz: f32 = origin.get_z() - v0[2];
131        if det > 1e-6 {
132            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
133            if u_raw < 0.0 || u_raw > det {
134                return false;
135            }
136            let qx: f32 = sy * e1[2] - sz * e1[1];
137            let qy: f32 = sz * e1[0] - sx * e1[2];
138            let qz: f32 = sx * e1[1] - sy * e1[0];
139            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
140            if v_raw < 0.0 || u_raw + v_raw > det {
141                return false;
142            }
143            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
144            t_raw > t_min * det && t_raw < t_max * det
145        } else if det < -1e-6 {
146            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
147            if u_raw > 0.0 || u_raw < det {
148                return false;
149            }
150            let qx: f32 = sy * e1[2] - sz * e1[1];
151            let qy: f32 = sz * e1[0] - sx * e1[2];
152            let qz: f32 = sx * e1[1] - sy * e1[0];
153            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
154            if v_raw > 0.0 || u_raw + v_raw < det {
155                return false;
156            }
157            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
158            t_raw < t_min * det && t_raw > t_max * det
159        } else {
160            false
161        }
162    }
163}
164
165/// 4-wide Structure-of-Arrays SIMD-friendly Möller–Trumbore kernels for `BvhTri4`.
166impl BvhTri4 {
167    /// Packs up to 4 contiguous `BvhGeomTri` entries starting at `base_tri_idx` into one `BvhTri4` packet.
168    ///
169    /// # Arguments
170    ///
171    /// - `&[BvhGeomTri]` - Slice of 1..=4 source triangles.
172    /// - `u32` - Global triangle index of `slice[0]` inside `Bvh3D::triangles`.
173    ///
174    /// # Returns
175    ///
176    /// - `Self` - Packed 4-wide SoA packet with zero-edge sentinel padding for trailing lanes.
177    #[must_use]
178    pub(crate) fn from_geom_chunk(slice: &[BvhGeomTri], base_tri_idx: u32) -> Self {
179        let mut v0x: [f32; 4] = [0.0; 4];
180        let mut v0y: [f32; 4] = [0.0; 4];
181        let mut v0z: [f32; 4] = [0.0; 4];
182        let mut e1x: [f32; 4] = [0.0; 4];
183        let mut e1y: [f32; 4] = [0.0; 4];
184        let mut e1z: [f32; 4] = [0.0; 4];
185        let mut e2x: [f32; 4] = [0.0; 4];
186        let mut e2y: [f32; 4] = [0.0; 4];
187        let mut e2z: [f32; 4] = [0.0; 4];
188        let mut tri_indices: [u32; 4] = [u32::MAX; 4];
189        for (lane, tri) in slice.iter().take(4).enumerate() {
190            v0x[lane] = tri.v0[0];
191            v0y[lane] = tri.v0[1];
192            v0z[lane] = tri.v0[2];
193            e1x[lane] = tri.e1[0];
194            e1y[lane] = tri.e1[1];
195            e1z[lane] = tri.e1[2];
196            e2x[lane] = tri.e2[0];
197            e2y[lane] = tri.e2[1];
198            e2z[lane] = tri.e2[2];
199            tri_indices[lane] = base_tri_idx.wrapping_add(lane as u32);
200        }
201        Self {
202            v0x,
203            v0y,
204            v0z,
205            e1x,
206            e1y,
207            e1z,
208            e2x,
209            e2y,
210            e2z,
211            tri_indices,
212        }
213    }
214
215    /// Tests all 4 triangles in parallel for any shadow/occlusion hit within `(t_min, t_max)`.
216    ///
217    /// # Arguments
218    ///
219    /// - `&Self` - 4-wide SoA triangle packet.
220    /// - `[f32; 3]` - Ray origin `(ox, oy, oz)`.
221    /// - `[f32; 3]` - Unit ray direction `(dx, dy, dz)`.
222    /// - `f32` - Minimum valid distance.
223    /// - `f32` - Maximum valid distance.
224    ///
225    /// # Returns
226    ///
227    /// - `u32` - Global triangle index of the first occluding lane, or `u32::MAX` on miss.
228    #[inline(always)]
229    #[must_use]
230    pub(crate) fn intersect_any_4(
231        &self,
232        orig: [f32; 3],
233        dir: [f32; 3],
234        t_min: f32,
235        t_max: f32,
236    ) -> u32 {
237        let Self {
238            v0x,
239            v0y,
240            v0z,
241            e1x,
242            e1y,
243            e1z,
244            e2x,
245            e2y,
246            e2z,
247            tri_indices,
248        } = self;
249        let ox: f32 = orig[0];
250        let oy: f32 = orig[1];
251        let oz: f32 = orig[2];
252        let dx: f32 = dir[0];
253        let dy: f32 = dir[1];
254        let dz: f32 = dir[2];
255        let mut hits: [bool; 4] = [false; 4];
256        for i in 0..4 {
257            let hx: f32 = dy.mul_add(e2z[i], -(dz * e2y[i]));
258            let hy: f32 = dz.mul_add(e2x[i], -(dx * e2z[i]));
259            let hz: f32 = dx.mul_add(e2y[i], -(dy * e2x[i]));
260            let det: f32 = e1x[i].mul_add(hx, e1y[i].mul_add(hy, e1z[i] * hz));
261            let sign: f32 = 1.0_f32.copysign(det);
262            let ad: f32 = det.abs();
263            let sx: f32 = ox - v0x[i];
264            let sy: f32 = oy - v0y[i];
265            let sz: f32 = oz - v0z[i];
266            let su: f32 = sx.mul_add(hx, sy.mul_add(hy, sz * hz)) * sign;
267            let qx: f32 = sy.mul_add(e1z[i], -(sz * e1y[i]));
268            let qy: f32 = sz.mul_add(e1x[i], -(sx * e1z[i]));
269            let qz: f32 = sx.mul_add(e1y[i], -(sy * e1x[i]));
270            let sv: f32 = dx.mul_add(qx, dy.mul_add(qy, dz * qz)) * sign;
271            let st: f32 = e2x[i].mul_add(qx, e2y[i].mul_add(qy, e2z[i] * qz)) * sign;
272            let uv_ok: bool = su >= 0.0 && sv >= 0.0 && (su + sv) <= ad;
273            let t_ok: bool = st > t_min * ad && st < t_max * ad;
274            hits[i] = ad > 1e-6 && uv_ok && t_ok;
275        }
276        if hits[0] {
277            tri_indices[0]
278        } else if hits[1] {
279            tri_indices[1]
280        } else if hits[2] {
281            tri_indices[2]
282        } else if hits[3] {
283            tri_indices[3]
284        } else {
285            u32::MAX
286        }
287    }
288
289    /// Tests all 4 triangles in parallel and updates `(best_t, best_idx)` on any closer hit within `(t_min, *best_t)`.
290    ///
291    /// # Arguments
292    ///
293    /// - `&Self` - 4-wide SoA triangle packet.
294    /// - `[f32; 3]` - Ray origin `(ox, oy, oz)`.
295    /// - `[f32; 3]` - Unit ray direction `(dx, dy, dz)`.
296    /// - `f32` - Minimum valid distance.
297    /// - `&mut f32` - Closest hit distance tightened on hit.
298    /// - `&mut usize` - Closest hit triangle index updated on hit.
299    #[inline(always)]
300    pub(crate) fn intersect_closest_4(
301        &self,
302        orig: [f32; 3],
303        dir: [f32; 3],
304        t_min: f32,
305        best_t: &mut f32,
306        best_idx: &mut usize,
307    ) {
308        let Self {
309            v0x,
310            v0y,
311            v0z,
312            e1x,
313            e1y,
314            e1z,
315            e2x,
316            e2y,
317            e2z,
318            tri_indices,
319        } = self;
320        let ox: f32 = orig[0];
321        let oy: f32 = orig[1];
322        let oz: f32 = orig[2];
323        let dx: f32 = dir[0];
324        let dy: f32 = dir[1];
325        let dz: f32 = dir[2];
326        let cur_max: f32 = *best_t;
327        let mut ad_arr: [f32; 4] = [0.0; 4];
328        let mut st_arr: [f32; 4] = [0.0; 4];
329        let mut hits: [bool; 4] = [false; 4];
330        for i in 0..4 {
331            let hx: f32 = dy.mul_add(e2z[i], -(dz * e2y[i]));
332            let hy: f32 = dz.mul_add(e2x[i], -(dx * e2z[i]));
333            let hz: f32 = dx.mul_add(e2y[i], -(dy * e2x[i]));
334            let det: f32 = e1x[i].mul_add(hx, e1y[i].mul_add(hy, e1z[i] * hz));
335            let sign: f32 = 1.0_f32.copysign(det);
336            let ad: f32 = det.abs();
337            let sx: f32 = ox - v0x[i];
338            let sy: f32 = oy - v0y[i];
339            let sz: f32 = oz - v0z[i];
340            let su: f32 = sx.mul_add(hx, sy.mul_add(hy, sz * hz)) * sign;
341            let qx: f32 = sy.mul_add(e1z[i], -(sz * e1y[i]));
342            let qy: f32 = sz.mul_add(e1x[i], -(sx * e1z[i]));
343            let qz: f32 = sx.mul_add(e1y[i], -(sy * e1x[i]));
344            let sv: f32 = dx.mul_add(qx, dy.mul_add(qy, dz * qz)) * sign;
345            let st: f32 = e2x[i].mul_add(qx, e2y[i].mul_add(qy, e2z[i] * qz)) * sign;
346            ad_arr[i] = ad;
347            st_arr[i] = st;
348            let uv_ok: bool = su >= 0.0 && sv >= 0.0 && (su + sv) <= ad;
349            let t_ok: bool = st > t_min * ad && st < cur_max * ad;
350            hits[i] = ad > 1e-6 && uv_ok && t_ok;
351        }
352        let any_01: bool = hits[0] || hits[1];
353        let any_23: bool = hits[2] || hits[3];
354        if any_01 || any_23 {
355            for i in 0..4 {
356                if hits[i] {
357                    let t: f32 = st_arr[i] / ad_arr[i];
358                    if t < *best_t {
359                        *best_t = t;
360                        *best_idx = tri_indices[i] as usize;
361                    }
362                }
363            }
364        }
365    }
366}
367
368/// Scalar-register FMA ray-box slab kernel for 32-byte `BvhFlatNode`.
369impl BvhFlatNode {
370    /// Constructs a zeroed placeholder 32-byte flat node for sibling-pair slot reservation.
371    ///
372    /// # Returns
373    ///
374    /// - `Self` - Empty placeholder flat node.
375    #[inline(always)]
376    #[must_use]
377    pub(crate) const fn empty() -> Self {
378        Self {
379            min: [0.0; 3],
380            child_or_first: 0,
381            max: [0.0; 3],
382            tri_count: 0,
383        }
384    }
385
386    /// Computes branchless FMA near-entry slab intersection distance, or `f32::INFINITY` on miss.
387    ///
388    /// # Arguments
389    ///
390    /// - `&Self` - Flat node reference.
391    /// - `[f32; 3]` - Precomputed safe reciprocal direction `(ix, iy, iz)`.
392    /// - `[f32; 3]` - Precomputed negated origin-times-inverse `(-ox * ix, -oy * iy, -oz * iz)`.
393    /// - `f32` - Minimum valid distance.
394    /// - `f32` - Maximum valid distance.
395    ///
396    /// # Returns
397    ///
398    /// - `f32` - Near intersection distance if hit, or `f32::INFINITY` on miss.
399    #[inline(always)]
400    #[must_use]
401    pub(crate) fn intersect_near_fma(
402        &self,
403        inv: [f32; 3],
404        neg_orig_inv: [f32; 3],
405        t_min: f32,
406        t_max: f32,
407    ) -> f32 {
408        let Self { min, max, .. } = self;
409        let tx1: f32 = min[0].mul_add(inv[0], neg_orig_inv[0]);
410        let tx2: f32 = max[0].mul_add(inv[0], neg_orig_inv[0]);
411        let mut tmin: f32 = t_min.max(tx1.min(tx2));
412        let mut tmax: f32 = t_max.min(tx1.max(tx2));
413        let ty1: f32 = min[1].mul_add(inv[1], neg_orig_inv[1]);
414        let ty2: f32 = max[1].mul_add(inv[1], neg_orig_inv[1]);
415        tmin = tmin.max(ty1.min(ty2));
416        tmax = tmax.min(ty1.max(ty2));
417        let tz1: f32 = min[2].mul_add(inv[2], neg_orig_inv[2]);
418        let tz2: f32 = max[2].mul_add(inv[2], neg_orig_inv[2]);
419        tmin = tmin.max(tz1.min(tz2));
420        tmax = tmax.min(tz1.max(tz2));
421        if tmax >= tmin && tmax >= 0.0 {
422            tmin
423        } else {
424            f32::INFINITY
425        }
426    }
427}
428
429/// Triangle construction and Möller–Trumbore ray intersection for `BvhTriangle`.
430impl BvhTriangle {
431    /// Creates a world-space `BvhTriangle` from three vertices and its surface `PbrMaterial`.
432    ///
433    /// # Arguments
434    ///
435    /// - `Vec3` - First vertex.
436    /// - `Vec3` - Second vertex.
437    /// - `Vec3` - Third vertex.
438    /// - `PbrMaterial` - Surface PBR material.
439    ///
440    /// # Returns
441    ///
442    /// - `Self` - Precomputed BVH triangle record.
443    #[must_use]
444    pub fn from_points(v0: Vec3, v1: Vec3, v2: Vec3, material: PbrMaterial) -> Self {
445        let edge1: Vec3 = v1.sub(v0);
446        let edge2: Vec3 = v2.sub(v0);
447        let normal: Vec3 = edge1.cross(edge2).normalize();
448        let centroid: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
449        let mut bounds: Aabb3D = Aabb3D::empty();
450        bounds.expand_point(v0);
451        bounds.expand_point(v1);
452        bounds.expand_point(v2);
453        Self {
454            v0,
455            edge1,
456            edge2,
457            normal,
458            centroid,
459            bounds,
460            material,
461        }
462    }
463
464    /// Tests `ray` against this triangle using Möller–Trumbore returning hit distance in `(t_min, t_max)`.
465    ///
466    /// # Arguments
467    ///
468    /// - `&Self` - Triangle reference.
469    /// - `&Ray3D` - Query ray.
470    /// - `f32` - Minimum valid distance.
471    /// - `f32` - Maximum valid distance.
472    ///
473    /// # Returns
474    ///
475    /// - `Option<f32>` - Parametric hit distance if intersected.
476    #[must_use]
477    pub fn intersect(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<f32> {
478        let g: BvhGeomTri = BvhGeomTri::from_triangle(self);
479        g.intersect_raw(ray.get_origin(), ray.get_direction(), t_min, t_max)
480    }
481}
482
483/// Binned Surface Area Heuristic (SAH) BVH construction and near-child-first ray traversal for `Bvh3D`.
484impl Bvh3D {
485    /// Recursively flattens `nodes[src_idx]` into `flat_nodes[dst_idx]` with sibling pairs laid out at contiguous even indices `(2k, 2k + 1)`.
486    ///
487    /// # Arguments
488    ///
489    /// - `&[BvhNode3D]` - Source hierarchical BVH nodes.
490    /// - `&[BvhGeomTri]` - Partitioned 36-byte triangle geometry array.
491    /// - `&mut Vec<BvhTri4>` - Destination 4-wide SoA leaf packet buffer.
492    /// - `&mut Vec<BvhFlatNode>` - Destination 32-byte sibling-paired flat node buffer.
493    /// - `&mut [u32]` - Mapping from source BVH node index to flat node index for incremental refit.
494    /// - `usize` - Source index in `nodes`.
495    /// - `usize` - Pre-reserved destination index in `flat_nodes`.
496    fn flatten_sibling_pair(
497        nodes: &[BvhNode3D],
498        geom: &[BvhGeomTri],
499        leaf_packets: &mut Vec<BvhTri4>,
500        flat_nodes: &mut Vec<BvhFlatNode>,
501        node_to_flat: &mut [u32],
502        src_idx: usize,
503        dst_idx: usize,
504    ) {
505        if src_idx < node_to_flat.len() {
506            node_to_flat[src_idx] = dst_idx as u32;
507        }
508        let n: &BvhNode3D = &nodes[src_idx];
509        let mn: Vec3 = n.get_bounds().get_min();
510        let mx: Vec3 = n.get_bounds().get_max();
511        let tc: u32 = n.get_tri_count();
512        if tc > 0 {
513            let first_tri: usize = n.get_first_tri() as usize;
514            let end_tri: usize = first_tri + (tc as usize);
515            let pkt_first: u32 = leaf_packets.len() as u32;
516            let mut cursor: usize = first_tri;
517            while cursor < end_tri {
518                let next_end: usize = (cursor + 4).min(end_tri);
519                leaf_packets.push(BvhTri4::from_geom_chunk(
520                    &geom[cursor..next_end],
521                    cursor as u32,
522                ));
523                cursor = next_end;
524            }
525            let pkt_count: u32 = (leaf_packets.len() as u32) - pkt_first;
526            flat_nodes[dst_idx] = BvhFlatNode {
527                min: [mn.get_x(), mn.get_y(), mn.get_z()],
528                child_or_first: pkt_first,
529                max: [mx.get_x(), mx.get_y(), mx.get_z()],
530                tri_count: pkt_count,
531            };
532        } else {
533            let first_child: usize = flat_nodes.len();
534            flat_nodes.push(BvhFlatNode::empty());
535            flat_nodes.push(BvhFlatNode::empty());
536            flat_nodes[dst_idx] = BvhFlatNode {
537                min: [mn.get_x(), mn.get_y(), mn.get_z()],
538                child_or_first: first_child as u32,
539                max: [mx.get_x(), mx.get_y(), mx.get_z()],
540                tri_count: 0,
541            };
542            Self::flatten_sibling_pair(
543                nodes,
544                geom,
545                leaf_packets,
546                flat_nodes,
547                node_to_flat,
548                n.get_left() as usize,
549                first_child,
550            );
551            Self::flatten_sibling_pair(
552                nodes,
553                geom,
554                leaf_packets,
555                flat_nodes,
556                node_to_flat,
557                n.get_right() as usize,
558                first_child + 1,
559            );
560        }
561    }
562
563    /// Builds a tight SAH flat BVH over `triangles` and populates its 32-byte sibling-paired flat nodes, 4-wide SoA leaf packets, and 36-byte geometry mirror.
564    ///
565    /// # Arguments
566    ///
567    /// - `Vec<BvhTriangle>` - World-space triangles to index.
568    ///
569    /// # Returns
570    ///
571    /// - `Self` - Constructed SAH BVH acceleration structure.
572    #[must_use]
573    pub fn build(triangles: Vec<BvhTriangle>) -> Self {
574        let tri_len: usize = triangles.len();
575        if tri_len == 0 {
576            return Self::default();
577        }
578        let mut orig_indices: Vec<u32> = Vec::with_capacity(tri_len);
579        for idx in 0..tri_len {
580            orig_indices.push(idx as u32);
581        }
582        let mut bvh: Self = Self {
583            nodes: Vec::with_capacity(tri_len * 2 + 1),
584            triangles,
585            geom: Vec::with_capacity(tri_len),
586            leaf_packets: Vec::with_capacity(tri_len.div_ceil(4) + 16),
587            flat_nodes: Vec::with_capacity(tri_len * 2 + 2),
588            orig_indices,
589            node_to_flat: Vec::new(),
590            build_sah_cost: 0.0,
591        };
592        if !bvh.get_triangles().is_empty() {
593            let total: usize = bvh.get_triangles().len();
594            let _: u32 = bvh.build_node(0, total);
595            let Self {
596                nodes,
597                triangles,
598                geom,
599                leaf_packets,
600                flat_nodes,
601                node_to_flat,
602                build_sah_cost,
603                ..
604            } = &mut bvh;
605            geom.clear();
606            for tri in triangles.iter() {
607                geom.push(BvhGeomTri::from_triangle(tri));
608            }
609            leaf_packets.clear();
610            flat_nodes.clear();
611            node_to_flat.resize(nodes.len(), 0);
612            if !nodes.is_empty() {
613                flat_nodes.push(BvhFlatNode::empty());
614                flat_nodes.push(BvhFlatNode::empty());
615                Self::flatten_sibling_pair(
616                    nodes,
617                    geom,
618                    leaf_packets,
619                    flat_nodes,
620                    node_to_flat,
621                    0,
622                    0,
623                );
624                let mut sah_sum: f32 = 0.0;
625                for n in nodes.iter() {
626                    let area: f32 = n.get_bounds().surface_area();
627                    if n.get_tri_count() > 0 {
628                        sah_sum += area * (n.get_tri_count() as f32);
629                    } else {
630                        sah_sum += area * 0.5;
631                    }
632                }
633                *build_sah_cost = sah_sum.max(1e-5);
634            }
635        }
636        bvh
637    }
638
639    /// Returns `true` when this BVH contains zero indexed triangles.
640    ///
641    /// # Arguments
642    ///
643    /// - `&Self` - BVH reference.
644    ///
645    /// # Returns
646    ///
647    /// - `bool` - `true` if empty.
648    #[must_use]
649    pub fn is_empty(&self) -> bool {
650        self.get_triangles().is_empty()
651    }
652
653    /// Computes the current SAH surface-area traversal cost across all BVH nodes.
654    ///
655    /// # Arguments
656    ///
657    /// - `&Self` - BVH reference.
658    ///
659    /// # Returns
660    ///
661    /// - `f32` - Current weighted surface-area cost.
662    #[must_use]
663    pub fn surface_area_cost(&self) -> f32 {
664        let mut cost: f32 = 0.0;
665        for n in self.get_nodes().iter() {
666            let area: f32 = n.get_bounds().surface_area();
667            if n.get_tri_count() > 0 {
668                cost += area * (n.get_tri_count() as f32);
669            } else {
670                cost += area * 0.5;
671            }
672        }
673        cost
674    }
675
676    /// Returns `true` when incremental refits have inflated node bounds past `max_cost_ratio * build_sah_cost` and warrant a fresh SAH rebuild.
677    ///
678    /// # Arguments
679    ///
680    /// - `&Self` - BVH reference.
681    /// - `f32` - Maximum acceptable SAH cost ratio (e.g. `1.65`).
682    ///
683    /// # Returns
684    ///
685    /// - `bool` - `true` when a full rebuild should replace incremental refitting.
686    #[must_use]
687    pub fn needs_rebuild_after_refit(&self, max_cost_ratio: f32) -> bool {
688        if self.is_empty() {
689            return false;
690        }
691        let base: f32 = self.get_build_sah_cost().max(1e-5);
692        self.surface_area_cost() > base * max_cost_ratio.max(1.05)
693    }
694
695    /// Performs an O(N) zero-allocation bottom-up BVH refit from `source_triangles` when dynamic triangle topology is unchanged.
696    ///
697    /// # Arguments
698    ///
699    /// - `&Self` - Mutable BVH instance.
700    /// - `&[BvhTriangle]` - Updated world-space triangles in original submission order.
701    ///
702    /// # Returns
703    ///
704    /// - `bool` - `true` when refit succeeded in place; `false` when triangle count or structure requires a full rebuild.
705    pub fn refit_from_source(&mut self, source_triangles: &[BvhTriangle]) -> bool {
706        let Self {
707            nodes,
708            triangles,
709            geom,
710            leaf_packets,
711            flat_nodes,
712            orig_indices,
713            node_to_flat,
714            ..
715        } = self;
716        let count: usize = source_triangles.len();
717        if count == 0
718            || triangles.len() != count
719            || orig_indices.len() != count
720            || nodes.is_empty()
721            || node_to_flat.len() != nodes.len()
722        {
723            return false;
724        }
725        for slot in 0..count {
726            let src_idx: usize = orig_indices[slot] as usize;
727            if src_idx >= count {
728                return false;
729            }
730            let updated: BvhTriangle = source_triangles[src_idx];
731            triangles[slot] = updated;
732            geom[slot] = BvhGeomTri::from_triangle(&updated);
733        }
734        for node_idx in (0..nodes.len()).rev() {
735            let tc: u32 = nodes[node_idx].get_tri_count();
736            let flat_idx: usize = node_to_flat[node_idx] as usize;
737            if tc > 0 {
738                let first: usize = nodes[node_idx].get_first_tri() as usize;
739                let end: usize = (first + (tc as usize)).min(count);
740                let mut bounds: Aabb3D = Aabb3D::empty();
741                for tri in triangles[first..end].iter() {
742                    bounds.expand_box(tri.get_bounds());
743                }
744                nodes[node_idx].set_bounds(bounds);
745                if let Some(flat_node) = flat_nodes.get_mut(flat_idx) {
746                    let mn: Vec3 = bounds.get_min();
747                    let mx: Vec3 = bounds.get_max();
748                    flat_node.min = [mn.get_x(), mn.get_y(), mn.get_z()];
749                    flat_node.max = [mx.get_x(), mx.get_y(), mx.get_z()];
750                    let mut pkt_idx: usize = flat_node.child_or_first as usize;
751                    let mut cursor: usize = first;
752                    while cursor < end && pkt_idx < leaf_packets.len() {
753                        let next_end: usize = (cursor + 4).min(end);
754                        leaf_packets[pkt_idx] =
755                            BvhTri4::from_geom_chunk(&geom[cursor..next_end], cursor as u32);
756                        cursor = next_end;
757                        pkt_idx += 1;
758                    }
759                }
760            } else {
761                let left_idx: usize = nodes[node_idx].get_left() as usize;
762                let right_idx: usize = nodes[node_idx].get_right() as usize;
763                let mut bounds: Aabb3D = nodes[left_idx].get_bounds();
764                bounds.expand_box(nodes[right_idx].get_bounds());
765                nodes[node_idx].set_bounds(bounds);
766                if let Some(flat_node) = flat_nodes.get_mut(flat_idx) {
767                    let mn: Vec3 = bounds.get_min();
768                    let mx: Vec3 = bounds.get_max();
769                    flat_node.min = [mn.get_x(), mn.get_y(), mn.get_z()];
770                    flat_node.max = [mx.get_x(), mx.get_y(), mx.get_z()];
771                }
772            }
773        }
774        true
775    }
776
777    /// Extracts the `axis` coordinate (`0 = x`, `1 = y`, `2 = z`) from vector `v`.
778    ///
779    /// # Arguments
780    ///
781    /// - `Vec3` - Source 3D vector.
782    /// - `usize` - Axis index.
783    ///
784    /// # Returns
785    ///
786    /// - `f32` - Selected scalar component.
787    #[must_use]
788    fn vec_axis(v: Vec3, axis: usize) -> f32 {
789        match axis {
790            0 => v.get_x(),
791            1 => v.get_y(),
792            _ => v.get_z(),
793        }
794    }
795
796    /// Evaluates 12-bin Surface Area Heuristic splits across all three axes and returns `(best_axis, best_split_pos)`.
797    ///
798    /// # Arguments
799    ///
800    /// - `&[BvhTriangle]` - Active triangle range.
801    /// - `Aabb3D` - Centroid bounding box of the range.
802    /// - `f32` - Parent bounding-box surface area.
803    ///
804    /// # Returns
805    ///
806    /// - `Option<(usize, f32)>` - Optimal split axis and threshold if cheaper than forming a leaf.
807    #[must_use]
808    fn find_sah_split(
809        tris: &[BvhTriangle],
810        cent_bounds: Aabb3D,
811        parent_area: f32,
812    ) -> Option<(usize, f32)> {
813        let bins: usize = 12;
814        let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
815        let exts: [f32; 3] = [extent.get_x(), extent.get_y(), extent.get_z()];
816        let cmins: [f32; 3] = [
817            cent_bounds.get_min().get_x(),
818            cent_bounds.get_min().get_y(),
819            cent_bounds.get_min().get_z(),
820        ];
821        let active: [bool; 3] = [exts[0] >= 1e-5, exts[1] >= 1e-5, exts[2] >= 1e-5];
822        let scales: [f32; 3] = [
823            if active[0] {
824                (bins as f32) / exts[0]
825            } else {
826                0.0
827            },
828            if active[1] {
829                (bins as f32) / exts[1]
830            } else {
831                0.0
832            },
833            if active[2] {
834                (bins as f32) / exts[2]
835            } else {
836                0.0
837            },
838        ];
839        let mut bin_bounds: [[Aabb3D; 12]; 3] = [[Aabb3D::empty(); 12]; 3];
840        let mut bin_counts: [[u32; 12]; 3] = [[0; 12]; 3];
841        for tri in tris.iter() {
842            let c: Vec3 = tri.get_centroid();
843            let tb: Aabb3D = tri.get_bounds();
844            if active[0] {
845                let b0: usize = (((c.get_x() - cmins[0]) * scales[0]) as usize).min(bins - 1);
846                bin_counts[0][b0] += 1;
847                bin_bounds[0][b0].expand_box(tb);
848            }
849            if active[1] {
850                let b1: usize = (((c.get_y() - cmins[1]) * scales[1]) as usize).min(bins - 1);
851                bin_counts[1][b1] += 1;
852                bin_bounds[1][b1].expand_box(tb);
853            }
854            if active[2] {
855                let b2: usize = (((c.get_z() - cmins[2]) * scales[2]) as usize).min(bins - 1);
856                bin_counts[2][b2] += 1;
857                bin_bounds[2][b2].expand_box(tb);
858            }
859        }
860        let mut best_cost: f32 = (tris.len() as f32) * parent_area;
861        let mut best_split: Option<(usize, f32)> = None;
862        for axis in 0..3 {
863            if !active[axis] {
864                continue;
865            }
866            let counts: &[u32; 12] = &bin_counts[axis];
867            let bounds_arr: &[Aabb3D; 12] = &bin_bounds[axis];
868            let mut left_area: [f32; 11] = [0.0; 11];
869            let mut left_count: [u32; 11] = [0; 11];
870            let mut acc_box: Aabb3D = Aabb3D::empty();
871            let mut acc_cnt: u32 = 0;
872            for i in 0..(bins - 1) {
873                acc_cnt += counts[i];
874                if counts[i] > 0 {
875                    acc_box.expand_box(bounds_arr[i]);
876                }
877                left_count[i] = acc_cnt;
878                left_area[i] = if acc_cnt > 0 {
879                    acc_box.surface_area()
880                } else {
881                    0.0
882                };
883            }
884            let mut r_box: Aabb3D = Aabb3D::empty();
885            let mut r_cnt: u32 = 0;
886            let step: f32 = exts[axis] / (bins as f32);
887            for i in (1..bins).rev() {
888                r_cnt += counts[i];
889                if counts[i] > 0 {
890                    r_box.expand_box(bounds_arr[i]);
891                }
892                let l_cnt: u32 = left_count[i - 1];
893                if l_cnt == 0 || r_cnt == 0 {
894                    continue;
895                }
896                let r_area: f32 = r_box.surface_area();
897                let cost: f32 =
898                    0.5 * parent_area + (l_cnt as f32) * left_area[i - 1] + (r_cnt as f32) * r_area;
899                if cost < best_cost {
900                    best_cost = cost;
901                    let split_pos: f32 = cmins[axis] + (i as f32) * step;
902                    best_split = Some((axis, split_pos));
903                }
904            }
905        }
906        best_split
907    }
908
909    /// Recursively partitions `triangles[start..end]` via binned SAH in DFS pre-order and appends a `BvhNode3D`.
910    ///
911    /// # Arguments
912    ///
913    /// - `&Self` - Mutable BVH builder reference.
914    /// - `usize` - Inclusive start index.
915    /// - `usize` - Exclusive end index.
916    ///
917    /// # Returns
918    ///
919    /// - `u32` - Index of the created node in `self.nodes`.
920    fn build_node(&mut self, start: usize, end: usize) -> u32 {
921        let count: usize = end - start;
922        let mut bounds: Aabb3D = Aabb3D::empty();
923        let mut cent_bounds: Aabb3D = Aabb3D::empty();
924        for tri in self.get_triangles()[start..end].iter() {
925            bounds.expand_box(tri.get_bounds());
926            cent_bounds.expand_point(tri.get_centroid());
927        }
928        let node_idx: u32 = self.get_nodes().len() as u32;
929        self.get_mut_nodes().push(BvhNode3D {
930            bounds,
931            left: 0,
932            right: 0,
933            first_tri: start as u32,
934            tri_count: count as u32,
935        });
936        if count <= 3 {
937            return node_idx;
938        }
939        let parent_area: f32 = bounds.surface_area().max(1e-6);
940        let split_opt: Option<(usize, f32)> =
941            Self::find_sah_split(&self.get_triangles()[start..end], cent_bounds, parent_area);
942        let mid: usize = if let Some((axis, split_pos)) = split_opt {
943            let Self {
944                triangles,
945                orig_indices,
946                ..
947            } = self;
948            let slice: &mut [BvhTriangle] = &mut triangles[start..end];
949            let idx_slice: &mut [u32] = &mut orig_indices[start..end];
950            let mut i: usize = 0;
951            let mut j: usize = slice.len();
952            while i < j {
953                if Self::vec_axis(slice[i].get_centroid(), axis) < split_pos {
954                    i += 1;
955                } else {
956                    j -= 1;
957                    slice.swap(i, j);
958                    idx_slice.swap(i, j);
959                }
960            }
961            if i == 0 || i == count {
962                start + count / 2
963            } else {
964                start + i
965            }
966        } else if count <= 6 {
967            return node_idx;
968        } else {
969            let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
970            let axis: usize =
971                if extent.get_x() >= extent.get_y() && extent.get_x() >= extent.get_z() {
972                    0
973                } else if extent.get_y() >= extent.get_z() {
974                    1
975                } else {
976                    2
977                };
978            let mid_pos: f32 =
979                Self::vec_axis(cent_bounds.get_min(), axis) + Self::vec_axis(extent, axis) * 0.5;
980            let Self {
981                triangles,
982                orig_indices,
983                ..
984            } = self;
985            let slice: &mut [BvhTriangle] = &mut triangles[start..end];
986            let idx_slice: &mut [u32] = &mut orig_indices[start..end];
987            let mut i: usize = 0;
988            let mut j: usize = slice.len();
989            while i < j {
990                if Self::vec_axis(slice[i].get_centroid(), axis) < mid_pos {
991                    i += 1;
992                } else {
993                    j -= 1;
994                    slice.swap(i, j);
995                    idx_slice.swap(i, j);
996                }
997            }
998            if i == 0 || i == count {
999                start + count / 2
1000            } else {
1001                start + i
1002            }
1003        };
1004        let left_idx: u32 = self.build_node(start, mid);
1005        let right_idx: u32 = self.build_node(mid, end);
1006        let node: &mut BvhNode3D = &mut self.get_mut_nodes()[node_idx as usize];
1007        node.set_left(left_idx);
1008        node.set_right(right_idx);
1009        node.set_tri_count(0);
1010        node_idx
1011    }
1012
1013    /// Traces a shadow/occlusion ray using 32-byte DFS nodes, zero-division Möller–Trumbore, and a 1-triangle occluder cache.
1014    ///
1015    /// # Arguments
1016    ///
1017    /// - `&Self` - BVH reference.
1018    /// - `Vec3` - Ray origin.
1019    /// - `Vec3` - Unit ray direction.
1020    /// - `Vec3` - Precomputed safe reciprocal ray direction.
1021    /// - `f32` - Minimum offset (shadow bias).
1022    /// - `f32` - Maximum trace distance.
1023    /// - `&mut u32` - Per-thread last-occluding triangle index cache (`u32::MAX` if empty).
1024    ///
1025    /// # Returns
1026    ///
1027    /// - `bool` - `true` if occluded by scene geometry.
1028    #[must_use]
1029    pub fn trace_any_shadow_cached(
1030        &self,
1031        origin: Vec3,
1032        dir: Vec3,
1033        inv_dir: Vec3,
1034        t_min: f32,
1035        t_max: f32,
1036        cached_tri: &mut u32,
1037    ) -> bool {
1038        let Self {
1039            flat_nodes,
1040            geom,
1041            leaf_packets,
1042            ..
1043        } = self;
1044        if flat_nodes.is_empty() || leaf_packets.is_empty() {
1045            return false;
1046        }
1047        let hint: usize = *cached_tri as usize;
1048        if hint < geom.len() && geom[hint].intersect_any_raw(origin, dir, t_min, t_max) {
1049            return true;
1050        }
1051        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
1052        let dir_arr: [f32; 3] = [dir.get_x(), dir.get_y(), dir.get_z()];
1053        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
1054        let neg_orig_inv: [f32; 3] = [
1055            -orig_arr[0] * inv_arr[0],
1056            -orig_arr[1] * inv_arr[1],
1057            -orig_arr[2] * inv_arr[2],
1058        ];
1059        if !flat_nodes[0]
1060            .intersect_near_fma(inv_arr, neg_orig_inv, t_min, t_max)
1061            .is_finite()
1062        {
1063            return false;
1064        }
1065        let mut stack: [core::mem::MaybeUninit<u32>; 32] =
1066            [const { core::mem::MaybeUninit::uninit() }; 32];
1067        let mut sp: usize = 0;
1068        let mut cur_idx: u32 = 0;
1069        loop {
1070            let n: &BvhFlatNode = &flat_nodes[cur_idx as usize];
1071            let pkt_count: usize = n.tri_count as usize;
1072            if pkt_count > 0 {
1073                let first_pkt: usize = n.child_or_first as usize;
1074                for pkt in leaf_packets[first_pkt..(first_pkt + pkt_count)].iter() {
1075                    let hit_tri: u32 = pkt.intersect_any_4(orig_arr, dir_arr, t_min, t_max);
1076                    if hit_tri != u32::MAX {
1077                        *cached_tri = hit_tri;
1078                        return true;
1079                    }
1080                }
1081            } else {
1082                let left_idx: u32 = n.child_or_first;
1083                let right_idx: u32 = left_idx + 1;
1084                let pair_start: usize = left_idx as usize;
1085                let pair: &[BvhFlatNode] = &flat_nodes[pair_start..(pair_start + 2)];
1086                let tl: f32 = pair[0].intersect_near_fma(inv_arr, neg_orig_inv, t_min, t_max);
1087                let tr: f32 = pair[1].intersect_near_fma(inv_arr, neg_orig_inv, t_min, t_max);
1088                let hit_l: bool = tl.is_finite();
1089                let hit_r: bool = tr.is_finite();
1090                if hit_l && hit_r {
1091                    let (near_idx, far_idx): (u32, u32) = if tl <= tr {
1092                        (left_idx, right_idx)
1093                    } else {
1094                        (right_idx, left_idx)
1095                    };
1096                    if sp < 32 {
1097                        let _: &mut u32 = stack[sp].write(far_idx);
1098                        sp += 1;
1099                    }
1100                    cur_idx = near_idx;
1101                    continue;
1102                } else if hit_l {
1103                    cur_idx = left_idx;
1104                    continue;
1105                } else if hit_r {
1106                    cur_idx = right_idx;
1107                    continue;
1108                }
1109            }
1110            if sp == 0 {
1111                break;
1112            }
1113            sp -= 1;
1114            // SAFETY: `sp` is only incremented immediately after `stack[sp].write(...)`,
1115            // guaranteeing `stack[sp]` is initialized prior to reading.
1116            cur_idx = unsafe { stack[sp].assume_init() };
1117        }
1118        false
1119    }
1120
1121    /// Traces a shadow/occlusion ray returning `true` immediately upon any hit within `(t_min, t_max)`.
1122    ///
1123    /// # Arguments
1124    ///
1125    /// - `&Self` - BVH reference.
1126    /// - `&Ray3D` - Shadow ray.
1127    /// - `f32` - Minimum offset (shadow bias).
1128    /// - `f32` - Maximum trace distance.
1129    ///
1130    /// # Returns
1131    ///
1132    /// - `bool` - `true` if occluded by scene geometry.
1133    #[must_use]
1134    pub fn trace_any_shadow(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1135        let mut cache: u32 = u32::MAX;
1136        self.trace_any_shadow_cached(
1137            ray.get_origin(),
1138            ray.get_direction(),
1139            ray.get_inv_direction(),
1140            t_min,
1141            t_max,
1142            &mut cache,
1143        )
1144    }
1145
1146    /// Traces a ray near-child-first against 32-byte DFS nodes and returns `(distance, tri_index)`.
1147    ///
1148    /// # Arguments
1149    ///
1150    /// - `&Self` - BVH reference.
1151    /// - `Vec3` - Ray origin.
1152    /// - `Vec3` - Unit ray direction.
1153    /// - `Vec3` - Precomputed safe reciprocal ray direction.
1154    /// - `f32` - Minimum offset bias.
1155    /// - `f32` - Maximum trace distance.
1156    ///
1157    /// # Returns
1158    ///
1159    /// - `Option<(f32, usize)>` - Closest hit distance and triangle index into `self.triangles`.
1160    #[must_use]
1161    pub fn trace_closest_raw(
1162        &self,
1163        origin: Vec3,
1164        dir: Vec3,
1165        inv_dir: Vec3,
1166        t_min: f32,
1167        t_max: f32,
1168    ) -> Option<(f32, usize)> {
1169        let Self {
1170            flat_nodes,
1171            leaf_packets,
1172            ..
1173        } = self;
1174        if flat_nodes.is_empty() || leaf_packets.is_empty() {
1175            return None;
1176        }
1177        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
1178        let dir_arr: [f32; 3] = [dir.get_x(), dir.get_y(), dir.get_z()];
1179        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
1180        let neg_orig_inv: [f32; 3] = [
1181            -orig_arr[0] * inv_arr[0],
1182            -orig_arr[1] * inv_arr[1],
1183            -orig_arr[2] * inv_arr[2],
1184        ];
1185        if !flat_nodes[0]
1186            .intersect_near_fma(inv_arr, neg_orig_inv, t_min, t_max)
1187            .is_finite()
1188        {
1189            return None;
1190        }
1191        let mut stack: [core::mem::MaybeUninit<(u32, f32)>; 32] =
1192            [const { core::mem::MaybeUninit::uninit() }; 32];
1193        let mut sp: usize = 0;
1194        let mut cur_idx: u32 = 0;
1195        let mut best_t: f32 = t_max;
1196        let mut best_idx: usize = usize::MAX;
1197        loop {
1198            let n: &BvhFlatNode = &flat_nodes[cur_idx as usize];
1199            let pkt_count: usize = n.tri_count as usize;
1200            if pkt_count > 0 {
1201                let first_pkt: usize = n.child_or_first as usize;
1202                for pkt in leaf_packets[first_pkt..(first_pkt + pkt_count)].iter() {
1203                    pkt.intersect_closest_4(orig_arr, dir_arr, t_min, &mut best_t, &mut best_idx);
1204                }
1205            } else {
1206                let left_idx: u32 = n.child_or_first;
1207                let right_idx: u32 = left_idx + 1;
1208                let pair_start: usize = left_idx as usize;
1209                let pair: &[BvhFlatNode] = &flat_nodes[pair_start..(pair_start + 2)];
1210                let tl: f32 = pair[0].intersect_near_fma(inv_arr, neg_orig_inv, t_min, best_t);
1211                let tr: f32 = pair[1].intersect_near_fma(inv_arr, neg_orig_inv, t_min, best_t);
1212                let hit_l: bool = tl < best_t;
1213                let hit_r: bool = tr < best_t;
1214                if hit_l && hit_r {
1215                    let (near_idx, far_idx, far_t): (u32, u32, f32) = if tl <= tr {
1216                        (left_idx, right_idx, tr)
1217                    } else {
1218                        (right_idx, left_idx, tl)
1219                    };
1220                    if sp < 32 {
1221                        let _: &mut (u32, f32) = stack[sp].write((far_idx, far_t));
1222                        sp += 1;
1223                    }
1224                    cur_idx = near_idx;
1225                    continue;
1226                } else if hit_l {
1227                    cur_idx = left_idx;
1228                    continue;
1229                } else if hit_r {
1230                    cur_idx = right_idx;
1231                    continue;
1232                }
1233            }
1234            let mut found_next: bool = false;
1235            while sp > 0 {
1236                sp -= 1;
1237                // SAFETY: `sp` is only incremented immediately after `stack[sp].write(...)`,
1238                // guaranteeing `stack[sp]` is initialized prior to reading.
1239                let (next_id, next_tmin): (u32, f32) = unsafe { stack[sp].assume_init() };
1240                if next_tmin < best_t {
1241                    cur_idx = next_id;
1242                    found_next = true;
1243                    break;
1244                }
1245            }
1246            if !found_next {
1247                break;
1248            }
1249        }
1250        if best_idx == usize::MAX {
1251            None
1252        } else {
1253            Some((best_t, best_idx))
1254        }
1255    }
1256
1257    /// Traces a reflection/GI ray and returns the closest hit surface within `(t_min, t_max)`.
1258    ///
1259    /// # Arguments
1260    ///
1261    /// - `&Self` - BVH reference.
1262    /// - `&Ray3D` - Reflection or GI ray.
1263    /// - `f32` - Minimum offset bias.
1264    /// - `f32` - Maximum trace distance.
1265    ///
1266    /// # Returns
1267    ///
1268    /// - `Option<RayHit3D>` - Closest hit metadata if any geometry was struck.
1269    #[must_use]
1270    pub fn trace_closest(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<RayHit3D> {
1271        let (t, idx): (f32, usize) = self.trace_closest_raw(
1272            ray.get_origin(),
1273            ray.get_direction(),
1274            ray.get_inv_direction(),
1275            t_min,
1276            t_max,
1277        )?;
1278        let tri: &BvhTriangle = &self.get_triangles()[idx];
1279        let pt: Vec3 = ray.get_origin().add(ray.get_direction().scale(t));
1280        Some(RayHit3D {
1281            distance: t,
1282            point: pt,
1283            normal: tri.get_normal(),
1284            material: tri.get_material(),
1285        })
1286    }
1287}