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    /// - `usize` - Source index in `nodes`.
494    /// - `usize` - Pre-reserved destination index in `flat_nodes`.
495    fn flatten_sibling_pair(
496        nodes: &[BvhNode3D],
497        geom: &[BvhGeomTri],
498        leaf_packets: &mut Vec<BvhTri4>,
499        flat_nodes: &mut Vec<BvhFlatNode>,
500        src_idx: usize,
501        dst_idx: usize,
502    ) {
503        let n: &BvhNode3D = &nodes[src_idx];
504        let mn: Vec3 = n.get_bounds().get_min();
505        let mx: Vec3 = n.get_bounds().get_max();
506        let tc: u32 = n.get_tri_count();
507        if tc > 0 {
508            let first_tri: usize = n.get_first_tri() as usize;
509            let end_tri: usize = first_tri + (tc as usize);
510            let pkt_first: u32 = leaf_packets.len() as u32;
511            let mut cursor: usize = first_tri;
512            while cursor < end_tri {
513                let next_end: usize = (cursor + 4).min(end_tri);
514                leaf_packets.push(BvhTri4::from_geom_chunk(
515                    &geom[cursor..next_end],
516                    cursor as u32,
517                ));
518                cursor = next_end;
519            }
520            let pkt_count: u32 = (leaf_packets.len() as u32) - pkt_first;
521            flat_nodes[dst_idx] = BvhFlatNode {
522                min: [mn.get_x(), mn.get_y(), mn.get_z()],
523                child_or_first: pkt_first,
524                max: [mx.get_x(), mx.get_y(), mx.get_z()],
525                tri_count: pkt_count,
526            };
527        } else {
528            let first_child: usize = flat_nodes.len();
529            flat_nodes.push(BvhFlatNode::empty());
530            flat_nodes.push(BvhFlatNode::empty());
531            flat_nodes[dst_idx] = BvhFlatNode {
532                min: [mn.get_x(), mn.get_y(), mn.get_z()],
533                child_or_first: first_child as u32,
534                max: [mx.get_x(), mx.get_y(), mx.get_z()],
535                tri_count: 0,
536            };
537            Self::flatten_sibling_pair(
538                nodes,
539                geom,
540                leaf_packets,
541                flat_nodes,
542                n.get_left() as usize,
543                first_child,
544            );
545            Self::flatten_sibling_pair(
546                nodes,
547                geom,
548                leaf_packets,
549                flat_nodes,
550                n.get_right() as usize,
551                first_child + 1,
552            );
553        }
554    }
555
556    /// 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.
557    ///
558    /// # Arguments
559    ///
560    /// - `Vec<BvhTriangle>` - World-space triangles to index.
561    ///
562    /// # Returns
563    ///
564    /// - `Self` - Constructed SAH BVH acceleration structure.
565    #[must_use]
566    pub fn build(triangles: Vec<BvhTriangle>) -> Self {
567        let tri_len: usize = triangles.len();
568        let mut bvh: Self = Self {
569            nodes: Vec::with_capacity(tri_len * 2 + 1),
570            triangles,
571            geom: Vec::with_capacity(tri_len),
572            leaf_packets: Vec::with_capacity(tri_len.div_ceil(4) + 16),
573            flat_nodes: Vec::with_capacity(tri_len * 2 + 2),
574        };
575        if !bvh.get_triangles().is_empty() {
576            let total: usize = bvh.get_triangles().len();
577            let _: u32 = bvh.build_node(0, total);
578            let Self {
579                nodes,
580                triangles,
581                geom,
582                leaf_packets,
583                flat_nodes,
584            } = &mut bvh;
585            geom.clear();
586            for tri in triangles.iter() {
587                geom.push(BvhGeomTri::from_triangle(tri));
588            }
589            leaf_packets.clear();
590            flat_nodes.clear();
591            if !nodes.is_empty() {
592                // Slot 0 holds root; slot 1 pads so every sibling pair starts at an even 64-byte-aligned index.
593                flat_nodes.push(BvhFlatNode::empty());
594                flat_nodes.push(BvhFlatNode::empty());
595                Self::flatten_sibling_pair(nodes, geom, leaf_packets, flat_nodes, 0, 0);
596            }
597        }
598        bvh
599    }
600
601    /// Extracts the `axis` coordinate (`0 = x`, `1 = y`, `2 = z`) from vector `v`.
602    ///
603    /// # Arguments
604    ///
605    /// - `Vec3` - Source 3D vector.
606    /// - `usize` - Axis index.
607    ///
608    /// # Returns
609    ///
610    /// - `f32` - Selected scalar component.
611    #[must_use]
612    fn vec_axis(v: Vec3, axis: usize) -> f32 {
613        match axis {
614            0 => v.get_x(),
615            1 => v.get_y(),
616            _ => v.get_z(),
617        }
618    }
619
620    /// Evaluates 12-bin Surface Area Heuristic splits across all three axes and returns `(best_axis, best_split_pos)`.
621    ///
622    /// # Arguments
623    ///
624    /// - `&[BvhTriangle]` - Active triangle range.
625    /// - `Aabb3D` - Centroid bounding box of the range.
626    /// - `f32` - Parent bounding-box surface area.
627    ///
628    /// # Returns
629    ///
630    /// - `Option<(usize, f32)>` - Optimal split axis and threshold if cheaper than forming a leaf.
631    #[must_use]
632    fn find_sah_split(
633        tris: &[BvhTriangle],
634        cent_bounds: Aabb3D,
635        parent_area: f32,
636    ) -> Option<(usize, f32)> {
637        let bins: usize = 12;
638        let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
639        let exts: [f32; 3] = [extent.get_x(), extent.get_y(), extent.get_z()];
640        let cmins: [f32; 3] = [
641            cent_bounds.get_min().get_x(),
642            cent_bounds.get_min().get_y(),
643            cent_bounds.get_min().get_z(),
644        ];
645        let active: [bool; 3] = [exts[0] >= 1e-5, exts[1] >= 1e-5, exts[2] >= 1e-5];
646        let scales: [f32; 3] = [
647            if active[0] {
648                (bins as f32) / exts[0]
649            } else {
650                0.0
651            },
652            if active[1] {
653                (bins as f32) / exts[1]
654            } else {
655                0.0
656            },
657            if active[2] {
658                (bins as f32) / exts[2]
659            } else {
660                0.0
661            },
662        ];
663        let mut bin_bounds: [[Aabb3D; 12]; 3] = [[Aabb3D::empty(); 12]; 3];
664        let mut bin_counts: [[u32; 12]; 3] = [[0; 12]; 3];
665        for tri in tris.iter() {
666            let c: Vec3 = tri.get_centroid();
667            let tb: Aabb3D = tri.get_bounds();
668            if active[0] {
669                let b0: usize = (((c.get_x() - cmins[0]) * scales[0]) as usize).min(bins - 1);
670                bin_counts[0][b0] += 1;
671                bin_bounds[0][b0].expand_box(tb);
672            }
673            if active[1] {
674                let b1: usize = (((c.get_y() - cmins[1]) * scales[1]) as usize).min(bins - 1);
675                bin_counts[1][b1] += 1;
676                bin_bounds[1][b1].expand_box(tb);
677            }
678            if active[2] {
679                let b2: usize = (((c.get_z() - cmins[2]) * scales[2]) as usize).min(bins - 1);
680                bin_counts[2][b2] += 1;
681                bin_bounds[2][b2].expand_box(tb);
682            }
683        }
684        let mut best_cost: f32 = (tris.len() as f32) * parent_area;
685        let mut best_split: Option<(usize, f32)> = None;
686        for axis in 0..3 {
687            if !active[axis] {
688                continue;
689            }
690            let counts: &[u32; 12] = &bin_counts[axis];
691            let bounds_arr: &[Aabb3D; 12] = &bin_bounds[axis];
692            let mut left_area: [f32; 11] = [0.0; 11];
693            let mut left_count: [u32; 11] = [0; 11];
694            let mut acc_box: Aabb3D = Aabb3D::empty();
695            let mut acc_cnt: u32 = 0;
696            for i in 0..(bins - 1) {
697                acc_cnt += counts[i];
698                if counts[i] > 0 {
699                    acc_box.expand_box(bounds_arr[i]);
700                }
701                left_count[i] = acc_cnt;
702                left_area[i] = if acc_cnt > 0 {
703                    acc_box.surface_area()
704                } else {
705                    0.0
706                };
707            }
708            let mut r_box: Aabb3D = Aabb3D::empty();
709            let mut r_cnt: u32 = 0;
710            let step: f32 = exts[axis] / (bins as f32);
711            for i in (1..bins).rev() {
712                r_cnt += counts[i];
713                if counts[i] > 0 {
714                    r_box.expand_box(bounds_arr[i]);
715                }
716                let l_cnt: u32 = left_count[i - 1];
717                if l_cnt == 0 || r_cnt == 0 {
718                    continue;
719                }
720                let r_area: f32 = r_box.surface_area();
721                let cost: f32 =
722                    0.5 * parent_area + (l_cnt as f32) * left_area[i - 1] + (r_cnt as f32) * r_area;
723                if cost < best_cost {
724                    best_cost = cost;
725                    let split_pos: f32 = cmins[axis] + (i as f32) * step;
726                    best_split = Some((axis, split_pos));
727                }
728            }
729        }
730        best_split
731    }
732
733    /// Recursively partitions `triangles[start..end]` via binned SAH in DFS pre-order and appends a `BvhNode3D`.
734    ///
735    /// # Arguments
736    ///
737    /// - `&Self` - Mutable BVH builder reference.
738    /// - `usize` - Inclusive start index.
739    /// - `usize` - Exclusive end index.
740    ///
741    /// # Returns
742    ///
743    /// - `u32` - Index of the created node in `self.nodes`.
744    fn build_node(&mut self, start: usize, end: usize) -> u32 {
745        let count: usize = end - start;
746        let mut bounds: Aabb3D = Aabb3D::empty();
747        let mut cent_bounds: Aabb3D = Aabb3D::empty();
748        for tri in self.get_triangles()[start..end].iter() {
749            bounds.expand_box(tri.get_bounds());
750            cent_bounds.expand_point(tri.get_centroid());
751        }
752        let node_idx: u32 = self.get_nodes().len() as u32;
753        self.get_mut_nodes().push(BvhNode3D {
754            bounds,
755            left: 0,
756            right: 0,
757            first_tri: start as u32,
758            tri_count: count as u32,
759        });
760        if count <= 3 {
761            return node_idx;
762        }
763        let parent_area: f32 = bounds.surface_area().max(1e-6);
764        let split_opt: Option<(usize, f32)> =
765            Self::find_sah_split(&self.get_triangles()[start..end], cent_bounds, parent_area);
766        let mid: usize = if let Some((axis, split_pos)) = split_opt {
767            let slice: &mut [BvhTriangle] = &mut self.get_mut_triangles()[start..end];
768            let mut i: usize = 0;
769            let mut j: usize = slice.len();
770            while i < j {
771                if Self::vec_axis(slice[i].get_centroid(), axis) < split_pos {
772                    i += 1;
773                } else {
774                    j -= 1;
775                    slice.swap(i, j);
776                }
777            }
778            if i == 0 || i == count {
779                start + count / 2
780            } else {
781                start + i
782            }
783        } else if count <= 6 {
784            return node_idx;
785        } else {
786            let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
787            let axis: usize =
788                if extent.get_x() >= extent.get_y() && extent.get_x() >= extent.get_z() {
789                    0
790                } else if extent.get_y() >= extent.get_z() {
791                    1
792                } else {
793                    2
794                };
795            let mid_pos: f32 =
796                Self::vec_axis(cent_bounds.get_min(), axis) + Self::vec_axis(extent, axis) * 0.5;
797            let slice: &mut [BvhTriangle] = &mut self.get_mut_triangles()[start..end];
798            let mut i: usize = 0;
799            let mut j: usize = slice.len();
800            while i < j {
801                if Self::vec_axis(slice[i].get_centroid(), axis) < mid_pos {
802                    i += 1;
803                } else {
804                    j -= 1;
805                    slice.swap(i, j);
806                }
807            }
808            if i == 0 || i == count {
809                start + count / 2
810            } else {
811                start + i
812            }
813        };
814        let left_idx: u32 = self.build_node(start, mid);
815        let right_idx: u32 = self.build_node(mid, end);
816        let node: &mut BvhNode3D = &mut self.get_mut_nodes()[node_idx as usize];
817        node.set_left(left_idx);
818        node.set_right(right_idx);
819        node.set_tri_count(0);
820        node_idx
821    }
822
823    /// Traces a shadow/occlusion ray using 32-byte DFS nodes, zero-division Möller–Trumbore, and a 1-triangle occluder cache.
824    ///
825    /// # Arguments
826    ///
827    /// - `&Self` - BVH reference.
828    /// - `Vec3` - Ray origin.
829    /// - `Vec3` - Unit ray direction.
830    /// - `Vec3` - Precomputed safe reciprocal ray direction.
831    /// - `f32` - Minimum offset (shadow bias).
832    /// - `f32` - Maximum trace distance.
833    /// - `&mut u32` - Per-thread last-occluding triangle index cache (`u32::MAX` if empty).
834    ///
835    /// # Returns
836    ///
837    /// - `bool` - `true` if occluded by scene geometry.
838    #[must_use]
839    pub fn trace_any_shadow_cached(
840        &self,
841        origin: Vec3,
842        dir: Vec3,
843        inv_dir: Vec3,
844        t_min: f32,
845        t_max: f32,
846        cached_tri: &mut u32,
847    ) -> bool {
848        let Self {
849            flat_nodes,
850            geom,
851            leaf_packets,
852            ..
853        } = self;
854        if flat_nodes.is_empty() || leaf_packets.is_empty() {
855            return false;
856        }
857        let hint: usize = *cached_tri as usize;
858        if hint < geom.len() && geom[hint].intersect_any_raw(origin, dir, t_min, t_max) {
859            return true;
860        }
861        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
862        let dir_arr: [f32; 3] = [dir.get_x(), dir.get_y(), dir.get_z()];
863        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
864        let neg_orig_inv: [f32; 3] = [
865            -orig_arr[0] * inv_arr[0],
866            -orig_arr[1] * inv_arr[1],
867            -orig_arr[2] * inv_arr[2],
868        ];
869        if !flat_nodes[0]
870            .intersect_near_fma(inv_arr, neg_orig_inv, t_min, t_max)
871            .is_finite()
872        {
873            return false;
874        }
875        let mut stack: [core::mem::MaybeUninit<u32>; 32] =
876            [const { core::mem::MaybeUninit::uninit() }; 32];
877        let mut sp: usize = 0;
878        let mut cur_idx: u32 = 0;
879        loop {
880            let n: &BvhFlatNode = &flat_nodes[cur_idx as usize];
881            let pkt_count: usize = n.tri_count as usize;
882            if pkt_count > 0 {
883                let first_pkt: usize = n.child_or_first as usize;
884                for pkt in leaf_packets[first_pkt..(first_pkt + pkt_count)].iter() {
885                    let hit_tri: u32 = pkt.intersect_any_4(orig_arr, dir_arr, t_min, t_max);
886                    if hit_tri != u32::MAX {
887                        *cached_tri = hit_tri;
888                        return true;
889                    }
890                }
891            } else {
892                let left_idx: u32 = n.child_or_first;
893                let right_idx: u32 = left_idx + 1;
894                let pair_start: usize = left_idx as usize;
895                let pair: &[BvhFlatNode] = &flat_nodes[pair_start..(pair_start + 2)];
896                let tl: f32 = pair[0].intersect_near_fma(inv_arr, neg_orig_inv, t_min, t_max);
897                let tr: f32 = pair[1].intersect_near_fma(inv_arr, neg_orig_inv, t_min, t_max);
898                let hit_l: bool = tl.is_finite();
899                let hit_r: bool = tr.is_finite();
900                if hit_l && hit_r {
901                    let (near_idx, far_idx): (u32, u32) = if tl <= tr {
902                        (left_idx, right_idx)
903                    } else {
904                        (right_idx, left_idx)
905                    };
906                    if sp < 32 {
907                        let _: &mut u32 = stack[sp].write(far_idx);
908                        sp += 1;
909                    }
910                    cur_idx = near_idx;
911                    continue;
912                } else if hit_l {
913                    cur_idx = left_idx;
914                    continue;
915                } else if hit_r {
916                    cur_idx = right_idx;
917                    continue;
918                }
919            }
920            if sp == 0 {
921                break;
922            }
923            sp -= 1;
924            // SAFETY: `sp` is only incremented immediately after `stack[sp].write(...)`,
925            // guaranteeing `stack[sp]` is initialized prior to reading.
926            cur_idx = unsafe { stack[sp].assume_init() };
927        }
928        false
929    }
930
931    /// Traces a shadow/occlusion ray returning `true` immediately upon any hit within `(t_min, t_max)`.
932    ///
933    /// # Arguments
934    ///
935    /// - `&Self` - BVH reference.
936    /// - `&Ray3D` - Shadow ray.
937    /// - `f32` - Minimum offset (shadow bias).
938    /// - `f32` - Maximum trace distance.
939    ///
940    /// # Returns
941    ///
942    /// - `bool` - `true` if occluded by scene geometry.
943    #[must_use]
944    pub fn trace_any_shadow(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
945        let mut cache: u32 = u32::MAX;
946        self.trace_any_shadow_cached(
947            ray.get_origin(),
948            ray.get_direction(),
949            ray.get_inv_direction(),
950            t_min,
951            t_max,
952            &mut cache,
953        )
954    }
955
956    /// Traces a ray near-child-first against 32-byte DFS nodes and returns `(distance, tri_index)`.
957    ///
958    /// # Arguments
959    ///
960    /// - `&Self` - BVH reference.
961    /// - `Vec3` - Ray origin.
962    /// - `Vec3` - Unit ray direction.
963    /// - `Vec3` - Precomputed safe reciprocal ray direction.
964    /// - `f32` - Minimum offset bias.
965    /// - `f32` - Maximum trace distance.
966    ///
967    /// # Returns
968    ///
969    /// - `Option<(f32, usize)>` - Closest hit distance and triangle index into `self.triangles`.
970    #[must_use]
971    pub fn trace_closest_raw(
972        &self,
973        origin: Vec3,
974        dir: Vec3,
975        inv_dir: Vec3,
976        t_min: f32,
977        t_max: f32,
978    ) -> Option<(f32, usize)> {
979        let Self {
980            flat_nodes,
981            leaf_packets,
982            ..
983        } = self;
984        if flat_nodes.is_empty() || leaf_packets.is_empty() {
985            return None;
986        }
987        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
988        let dir_arr: [f32; 3] = [dir.get_x(), dir.get_y(), dir.get_z()];
989        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
990        let neg_orig_inv: [f32; 3] = [
991            -orig_arr[0] * inv_arr[0],
992            -orig_arr[1] * inv_arr[1],
993            -orig_arr[2] * inv_arr[2],
994        ];
995        if !flat_nodes[0]
996            .intersect_near_fma(inv_arr, neg_orig_inv, t_min, t_max)
997            .is_finite()
998        {
999            return None;
1000        }
1001        let mut stack: [core::mem::MaybeUninit<(u32, f32)>; 32] =
1002            [const { core::mem::MaybeUninit::uninit() }; 32];
1003        let mut sp: usize = 0;
1004        let mut cur_idx: u32 = 0;
1005        let mut best_t: f32 = t_max;
1006        let mut best_idx: usize = usize::MAX;
1007        loop {
1008            let n: &BvhFlatNode = &flat_nodes[cur_idx as usize];
1009            let pkt_count: usize = n.tri_count as usize;
1010            if pkt_count > 0 {
1011                let first_pkt: usize = n.child_or_first as usize;
1012                for pkt in leaf_packets[first_pkt..(first_pkt + pkt_count)].iter() {
1013                    pkt.intersect_closest_4(orig_arr, dir_arr, t_min, &mut best_t, &mut best_idx);
1014                }
1015            } else {
1016                let left_idx: u32 = n.child_or_first;
1017                let right_idx: u32 = left_idx + 1;
1018                let pair_start: usize = left_idx as usize;
1019                let pair: &[BvhFlatNode] = &flat_nodes[pair_start..(pair_start + 2)];
1020                let tl: f32 = pair[0].intersect_near_fma(inv_arr, neg_orig_inv, t_min, best_t);
1021                let tr: f32 = pair[1].intersect_near_fma(inv_arr, neg_orig_inv, t_min, best_t);
1022                let hit_l: bool = tl < best_t;
1023                let hit_r: bool = tr < best_t;
1024                if hit_l && hit_r {
1025                    let (near_idx, far_idx, far_t): (u32, u32, f32) = if tl <= tr {
1026                        (left_idx, right_idx, tr)
1027                    } else {
1028                        (right_idx, left_idx, tl)
1029                    };
1030                    if sp < 32 {
1031                        let _: &mut (u32, f32) = stack[sp].write((far_idx, far_t));
1032                        sp += 1;
1033                    }
1034                    cur_idx = near_idx;
1035                    continue;
1036                } else if hit_l {
1037                    cur_idx = left_idx;
1038                    continue;
1039                } else if hit_r {
1040                    cur_idx = right_idx;
1041                    continue;
1042                }
1043            }
1044            let mut found_next: bool = false;
1045            while sp > 0 {
1046                sp -= 1;
1047                // SAFETY: `sp` is only incremented immediately after `stack[sp].write(...)`,
1048                // guaranteeing `stack[sp]` is initialized prior to reading.
1049                let (next_id, next_tmin): (u32, f32) = unsafe { stack[sp].assume_init() };
1050                if next_tmin < best_t {
1051                    cur_idx = next_id;
1052                    found_next = true;
1053                    break;
1054                }
1055            }
1056            if !found_next {
1057                break;
1058            }
1059        }
1060        if best_idx == usize::MAX {
1061            None
1062        } else {
1063            Some((best_t, best_idx))
1064        }
1065    }
1066
1067    /// Traces a reflection/GI ray and returns the closest hit surface within `(t_min, t_max)`.
1068    ///
1069    /// # Arguments
1070    ///
1071    /// - `&Self` - BVH reference.
1072    /// - `&Ray3D` - Reflection or GI ray.
1073    /// - `f32` - Minimum offset bias.
1074    /// - `f32` - Maximum trace distance.
1075    ///
1076    /// # Returns
1077    ///
1078    /// - `Option<RayHit3D>` - Closest hit metadata if any geometry was struck.
1079    #[must_use]
1080    pub fn trace_closest(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<RayHit3D> {
1081        let (t, idx): (f32, usize) = self.trace_closest_raw(
1082            ray.get_origin(),
1083            ray.get_direction(),
1084            ray.get_inv_direction(),
1085            t_min,
1086            t_max,
1087        )?;
1088        let tri: &BvhTriangle = &self.get_triangles()[idx];
1089        let pt: Vec3 = ray.get_origin().add(ray.get_direction().scale(t));
1090        Some(RayHit3D {
1091            distance: t,
1092            point: pt,
1093            normal: tri.get_normal(),
1094            material: tri.get_material(),
1095        })
1096    }
1097}