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