euv-core 0.42.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
use super::*;

/// Compact hot-geometry ray intersection kernel for `BvhGeomTri`.
impl BvhGeomTri {
    /// Extracts compact 36-byte hot geometry from a `BvhTriangle`.
    ///
    /// # Arguments
    ///
    /// - `&BvhTriangle` - Source world-space triangle.
    ///
    /// # Returns
    ///
    /// - `Self` - L1-cache-compact triangle geometry.
    #[must_use]
    pub(crate) fn from_triangle(tri: &BvhTriangle) -> Self {
        let v0: Vec3 = tri.get_v0();
        let e1: Vec3 = tri.get_edge1();
        let e2: Vec3 = tri.get_edge2();
        Self {
            v0: [v0.get_x(), v0.get_y(), v0.get_z()],
            e1: [e1.get_x(), e1.get_y(), e1.get_z()],
            e2: [e2.get_x(), e2.get_y(), e2.get_z()],
        }
    }

    /// Deferred-division Möller–Trumbore ray-triangle test avoiding division on rejected triangles.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Compact triangle geometry reference.
    /// - `Vec3` - Ray origin.
    /// - `Vec3` - Unit ray direction.
    /// - `f32` - Minimum valid distance.
    /// - `f32` - Maximum valid distance.
    ///
    /// # Returns
    ///
    /// - `Option<f32>` - Parametric hit distance if intersected.
    #[must_use]
    pub(crate) fn intersect_raw(
        &self,
        origin: Vec3,
        dir: Vec3,
        t_min: f32,
        t_max: f32,
    ) -> Option<f32> {
        let Self { v0, e1, e2 } = self;
        let dx: f32 = dir.get_x();
        let dy: f32 = dir.get_y();
        let dz: f32 = dir.get_z();
        let hx: f32 = dy * e2[2] - dz * e2[1];
        let hy: f32 = dz * e2[0] - dx * e2[2];
        let hz: f32 = dx * e2[1] - dy * e2[0];
        let det: f32 = e1[0] * hx + e1[1] * hy + e1[2] * hz;
        let sx: f32 = origin.get_x() - v0[0];
        let sy: f32 = origin.get_y() - v0[1];
        let sz: f32 = origin.get_z() - v0[2];
        if det > 1e-6 {
            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
            if u_raw < 0.0 || u_raw > det {
                return None;
            }
            let qx: f32 = sy * e1[2] - sz * e1[1];
            let qy: f32 = sz * e1[0] - sx * e1[2];
            let qz: f32 = sx * e1[1] - sy * e1[0];
            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
            if v_raw < 0.0 || u_raw + v_raw > det {
                return None;
            }
            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
            if t_raw <= t_min * det || t_raw >= t_max * det {
                return None;
            }
            Some(t_raw / det)
        } else if det < -1e-6 {
            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
            if u_raw > 0.0 || u_raw < det {
                return None;
            }
            let qx: f32 = sy * e1[2] - sz * e1[1];
            let qy: f32 = sz * e1[0] - sx * e1[2];
            let qz: f32 = sx * e1[1] - sy * e1[0];
            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
            if v_raw > 0.0 || u_raw + v_raw < det {
                return None;
            }
            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
            if t_raw >= t_min * det || t_raw <= t_max * det {
                return None;
            }
            Some(t_raw / det)
        } else {
            None
        }
    }

    /// Zero-division occlusion-only Möller–Trumbore test for shadow rays within `(t_min, t_max)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Compact triangle geometry reference.
    /// - `Vec3` - Ray origin.
    /// - `Vec3` - Unit ray direction.
    /// - `f32` - Minimum valid distance.
    /// - `f32` - Maximum valid distance.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the ray intersects this triangle within `(t_min, t_max)`.
    #[must_use]
    pub(crate) fn intersect_any_raw(
        &self,
        origin: Vec3,
        dir: Vec3,
        t_min: f32,
        t_max: f32,
    ) -> bool {
        let Self { v0, e1, e2 } = self;
        let dx: f32 = dir.get_x();
        let dy: f32 = dir.get_y();
        let dz: f32 = dir.get_z();
        let hx: f32 = dy * e2[2] - dz * e2[1];
        let hy: f32 = dz * e2[0] - dx * e2[2];
        let hz: f32 = dx * e2[1] - dy * e2[0];
        let det: f32 = e1[0] * hx + e1[1] * hy + e1[2] * hz;
        let sx: f32 = origin.get_x() - v0[0];
        let sy: f32 = origin.get_y() - v0[1];
        let sz: f32 = origin.get_z() - v0[2];
        if det > 1e-6 {
            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
            if u_raw < 0.0 || u_raw > det {
                return false;
            }
            let qx: f32 = sy * e1[2] - sz * e1[1];
            let qy: f32 = sz * e1[0] - sx * e1[2];
            let qz: f32 = sx * e1[1] - sy * e1[0];
            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
            if v_raw < 0.0 || u_raw + v_raw > det {
                return false;
            }
            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
            t_raw > t_min * det && t_raw < t_max * det
        } else if det < -1e-6 {
            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
            if u_raw > 0.0 || u_raw < det {
                return false;
            }
            let qx: f32 = sy * e1[2] - sz * e1[1];
            let qy: f32 = sz * e1[0] - sx * e1[2];
            let qz: f32 = sx * e1[1] - sy * e1[0];
            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
            if v_raw > 0.0 || u_raw + v_raw < det {
                return false;
            }
            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
            t_raw < t_min * det && t_raw > t_max * det
        } else {
            false
        }
    }
}

/// Scalar-register ray-box slab kernel for 32-byte `BvhFlatNode`.
impl BvhFlatNode {
    /// Computes branchless near-entry slab intersection distance, or `f32::INFINITY` on miss.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Flat node reference.
    /// - `[f32; 3]` - Ray origin `(ox, oy, oz)`.
    /// - `[f32; 3]` - Precomputed safe reciprocal direction `(ix, iy, iz)`.
    /// - `f32` - Minimum valid distance.
    /// - `f32` - Maximum valid distance.
    ///
    /// # Returns
    ///
    /// - `f32` - Near intersection distance if hit, or `f32::INFINITY` on miss.
    #[must_use]
    pub(crate) fn intersect_near(
        &self,
        orig: [f32; 3],
        inv: [f32; 3],
        t_min: f32,
        t_max: f32,
    ) -> f32 {
        let Self { min, max, .. } = self;
        let tx1: f32 = (min[0] - orig[0]) * inv[0];
        let tx2: f32 = (max[0] - orig[0]) * inv[0];
        let mut tmin: f32 = t_min.max(tx1.min(tx2));
        let mut tmax: f32 = t_max.min(tx1.max(tx2));
        let ty1: f32 = (min[1] - orig[1]) * inv[1];
        let ty2: f32 = (max[1] - orig[1]) * inv[1];
        tmin = tmin.max(ty1.min(ty2));
        tmax = tmax.min(ty1.max(ty2));
        let tz1: f32 = (min[2] - orig[2]) * inv[2];
        let tz2: f32 = (max[2] - orig[2]) * inv[2];
        tmin = tmin.max(tz1.min(tz2));
        tmax = tmax.min(tz1.max(tz2));
        if tmax >= tmin && tmax >= 0.0 {
            tmin
        } else {
            f32::INFINITY
        }
    }
}

/// Triangle construction and Möller–Trumbore ray intersection for `BvhTriangle`.
impl BvhTriangle {
    /// Creates a world-space `BvhTriangle` from three vertices and its surface `PbrMaterial`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - First vertex.
    /// - `Vec3` - Second vertex.
    /// - `Vec3` - Third vertex.
    /// - `PbrMaterial` - Surface PBR material.
    ///
    /// # Returns
    ///
    /// - `Self` - Precomputed BVH triangle record.
    #[must_use]
    pub fn from_points(v0: Vec3, v1: Vec3, v2: Vec3, material: PbrMaterial) -> Self {
        let edge1: Vec3 = v1.sub(v0);
        let edge2: Vec3 = v2.sub(v0);
        let normal: Vec3 = edge1.cross(edge2).normalize();
        let centroid: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
        let mut bounds: Aabb3D = Aabb3D::empty();
        bounds.expand_point(v0);
        bounds.expand_point(v1);
        bounds.expand_point(v2);
        Self {
            v0,
            edge1,
            edge2,
            normal,
            centroid,
            bounds,
            material,
        }
    }

    /// Tests `ray` against this triangle using Möller–Trumbore returning hit distance in `(t_min, t_max)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Triangle reference.
    /// - `&Ray3D` - Query ray.
    /// - `f32` - Minimum valid distance.
    /// - `f32` - Maximum valid distance.
    ///
    /// # Returns
    ///
    /// - `Option<f32>` - Parametric hit distance if intersected.
    #[must_use]
    pub fn intersect(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<f32> {
        let g: BvhGeomTri = BvhGeomTri::from_triangle(self);
        g.intersect_raw(ray.get_origin(), ray.get_direction(), t_min, t_max)
    }
}

/// Binned Surface Area Heuristic (SAH) BVH construction and near-child-first ray traversal for `Bvh3D`.
impl Bvh3D {
    /// Builds a tight SAH flat BVH over `triangles` and populates its 32-byte DFS node and 36-byte geometry mirrors.
    ///
    /// # Arguments
    ///
    /// - `Vec<BvhTriangle>` - World-space triangles to index.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed SAH BVH acceleration structure.
    #[must_use]
    pub fn build(triangles: Vec<BvhTriangle>) -> Self {
        let tri_len: usize = triangles.len();
        let mut bvh: Self = Self {
            nodes: Vec::with_capacity(tri_len * 2 + 1),
            triangles,
            geom: Vec::with_capacity(tri_len),
            flat_nodes: Vec::with_capacity(tri_len * 2 + 1),
        };
        if !bvh.get_triangles().is_empty() {
            let total: usize = bvh.get_triangles().len();
            let _: u32 = bvh.build_node(0, total);
            let Self {
                nodes,
                triangles,
                geom,
                flat_nodes,
            } = &mut bvh;
            geom.clear();
            for tri in triangles.iter() {
                geom.push(BvhGeomTri::from_triangle(tri));
            }
            flat_nodes.clear();
            for n in nodes.iter() {
                let mn: Vec3 = n.get_bounds().get_min();
                let mx: Vec3 = n.get_bounds().get_max();
                let tc: u32 = n.get_tri_count();
                flat_nodes.push(BvhFlatNode {
                    min: [mn.get_x(), mn.get_y(), mn.get_z()],
                    right_or_first: if tc > 0 {
                        n.get_first_tri()
                    } else {
                        n.get_right()
                    },
                    max: [mx.get_x(), mx.get_y(), mx.get_z()],
                    tri_count: tc,
                });
            }
        }
        bvh
    }

    /// Extracts the `axis` coordinate (`0 = x`, `1 = y`, `2 = z`) from vector `v`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Source 3D vector.
    /// - `usize` - Axis index.
    ///
    /// # Returns
    ///
    /// - `f32` - Selected scalar component.
    #[must_use]
    fn vec_axis(v: Vec3, axis: usize) -> f32 {
        match axis {
            0 => v.get_x(),
            1 => v.get_y(),
            _ => v.get_z(),
        }
    }

    /// Evaluates 12-bin Surface Area Heuristic splits across all three axes and returns `(best_axis, best_split_pos)`.
    ///
    /// # Arguments
    ///
    /// - `&[BvhTriangle]` - Active triangle range.
    /// - `Aabb3D` - Centroid bounding box of the range.
    /// - `f32` - Parent bounding-box surface area.
    ///
    /// # Returns
    ///
    /// - `Option<(usize, f32)>` - Optimal split axis and threshold if cheaper than forming a leaf.
    #[must_use]
    fn find_sah_split(
        tris: &[BvhTriangle],
        cent_bounds: Aabb3D,
        parent_area: f32,
    ) -> Option<(usize, f32)> {
        let bins: usize = 12;
        let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
        let mut best_cost: f32 = (tris.len() as f32) * parent_area;
        let mut best_split: Option<(usize, f32)> = None;
        for axis in 0..3 {
            let ext: f32 = Self::vec_axis(extent, axis);
            if ext < 1e-5 {
                continue;
            }
            let cmin: f32 = Self::vec_axis(cent_bounds.get_min(), axis);
            let scale: f32 = (bins as f32) / ext;
            let mut bin_bounds: [Aabb3D; 12] = [Aabb3D::empty(); 12];
            let mut bin_counts: [u32; 12] = [0; 12];
            for tri in tris.iter() {
                let c: f32 = Self::vec_axis(tri.get_centroid(), axis);
                let b_idx: usize = (((c - cmin) * scale) as usize).min(bins - 1);
                bin_counts[b_idx] += 1;
                bin_bounds[b_idx].expand_box(tri.get_bounds());
            }
            let mut left_area: [f32; 11] = [0.0; 11];
            let mut left_count: [u32; 11] = [0; 11];
            let mut acc_box: Aabb3D = Aabb3D::empty();
            let mut acc_cnt: u32 = 0;
            for i in 0..(bins - 1) {
                acc_cnt += bin_counts[i];
                if bin_counts[i] > 0 {
                    acc_box.expand_box(bin_bounds[i]);
                }
                left_count[i] = acc_cnt;
                left_area[i] = if acc_cnt > 0 {
                    acc_box.surface_area()
                } else {
                    0.0
                };
            }
            let mut r_box: Aabb3D = Aabb3D::empty();
            let mut r_cnt: u32 = 0;
            for i in (1..bins).rev() {
                r_cnt += bin_counts[i];
                if bin_counts[i] > 0 {
                    r_box.expand_box(bin_bounds[i]);
                }
                let l_cnt: u32 = left_count[i - 1];
                if l_cnt == 0 || r_cnt == 0 {
                    continue;
                }
                let r_area: f32 = r_box.surface_area();
                let cost: f32 =
                    0.5 * parent_area + (l_cnt as f32) * left_area[i - 1] + (r_cnt as f32) * r_area;
                if cost < best_cost {
                    best_cost = cost;
                    let split_pos: f32 = cmin + (i as f32) * (ext / (bins as f32));
                    best_split = Some((axis, split_pos));
                }
            }
        }
        best_split
    }

    /// Recursively partitions `triangles[start..end]` via binned SAH in DFS pre-order and appends a `BvhNode3D`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable BVH builder reference.
    /// - `usize` - Inclusive start index.
    /// - `usize` - Exclusive end index.
    ///
    /// # Returns
    ///
    /// - `u32` - Index of the created node in `self.nodes`.
    fn build_node(&mut self, start: usize, end: usize) -> u32 {
        let count: usize = end - start;
        let mut bounds: Aabb3D = Aabb3D::empty();
        let mut cent_bounds: Aabb3D = Aabb3D::empty();
        for tri in self.get_triangles()[start..end].iter() {
            bounds.expand_box(tri.get_bounds());
            cent_bounds.expand_point(tri.get_centroid());
        }
        let node_idx: u32 = self.get_nodes().len() as u32;
        self.get_mut_nodes().push(BvhNode3D {
            bounds,
            left: 0,
            right: 0,
            first_tri: start as u32,
            tri_count: count as u32,
        });
        if count <= 3 {
            return node_idx;
        }
        let parent_area: f32 = bounds.surface_area().max(1e-6);
        let split_opt: Option<(usize, f32)> =
            Self::find_sah_split(&self.get_triangles()[start..end], cent_bounds, parent_area);
        let mid: usize = if let Some((axis, split_pos)) = split_opt {
            let slice: &mut [BvhTriangle] = &mut self.get_mut_triangles()[start..end];
            let mut i: usize = 0;
            let mut j: usize = slice.len();
            while i < j {
                if Self::vec_axis(slice[i].get_centroid(), axis) < split_pos {
                    i += 1;
                } else {
                    j -= 1;
                    slice.swap(i, j);
                }
            }
            if i == 0 || i == count {
                start + count / 2
            } else {
                start + i
            }
        } else if count <= 6 {
            return node_idx;
        } else {
            let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
            let axis: usize =
                if extent.get_x() >= extent.get_y() && extent.get_x() >= extent.get_z() {
                    0
                } else if extent.get_y() >= extent.get_z() {
                    1
                } else {
                    2
                };
            let mid_pos: f32 =
                Self::vec_axis(cent_bounds.get_min(), axis) + Self::vec_axis(extent, axis) * 0.5;
            let slice: &mut [BvhTriangle] = &mut self.get_mut_triangles()[start..end];
            let mut i: usize = 0;
            let mut j: usize = slice.len();
            while i < j {
                if Self::vec_axis(slice[i].get_centroid(), axis) < mid_pos {
                    i += 1;
                } else {
                    j -= 1;
                    slice.swap(i, j);
                }
            }
            if i == 0 || i == count {
                start + count / 2
            } else {
                start + i
            }
        };
        let left_idx: u32 = self.build_node(start, mid);
        let right_idx: u32 = self.build_node(mid, end);
        let node: &mut BvhNode3D = &mut self.get_mut_nodes()[node_idx as usize];
        node.set_left(left_idx);
        node.set_right(right_idx);
        node.set_tri_count(0);
        node_idx
    }

    /// Traces a shadow/occlusion ray using 32-byte DFS nodes, zero-division Möller–Trumbore, and a 1-triangle occluder cache.
    ///
    /// # Arguments
    ///
    /// - `&Self` - BVH reference.
    /// - `Vec3` - Ray origin.
    /// - `Vec3` - Unit ray direction.
    /// - `Vec3` - Precomputed safe reciprocal ray direction.
    /// - `f32` - Minimum offset (shadow bias).
    /// - `f32` - Maximum trace distance.
    /// - `&mut u32` - Per-thread last-occluding triangle index cache (`u32::MAX` if empty).
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if occluded by scene geometry.
    #[must_use]
    pub fn trace_any_shadow_cached(
        &self,
        origin: Vec3,
        dir: Vec3,
        inv_dir: Vec3,
        t_min: f32,
        t_max: f32,
        cached_tri: &mut u32,
    ) -> bool {
        let Self {
            flat_nodes, geom, ..
        } = self;
        if flat_nodes.is_empty() || geom.is_empty() {
            return false;
        }
        let hint: usize = *cached_tri as usize;
        if hint < geom.len() && geom[hint].intersect_any_raw(origin, dir, t_min, t_max) {
            return true;
        }
        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
        if !flat_nodes[0]
            .intersect_near(orig_arr, inv_arr, t_min, t_max)
            .is_finite()
        {
            return false;
        }
        let mut stack: [u32; 64] = [0; 64];
        let mut sp: usize = 1;
        while sp > 0 {
            sp -= 1;
            let idx: u32 = stack[sp];
            let n: &BvhFlatNode = &flat_nodes[idx as usize];
            let count: usize = n.tri_count as usize;
            if count > 0 {
                let first: usize = n.right_or_first as usize;
                for (off, tri) in geom[first..(first + count)].iter().enumerate() {
                    if tri.intersect_any_raw(origin, dir, t_min, t_max) {
                        *cached_tri = (first + off) as u32;
                        return true;
                    }
                }
            } else {
                let left_idx: u32 = idx + 1;
                let right_idx: u32 = n.right_or_first;
                let tl: f32 =
                    flat_nodes[left_idx as usize].intersect_near(orig_arr, inv_arr, t_min, t_max);
                let tr: f32 =
                    flat_nodes[right_idx as usize].intersect_near(orig_arr, inv_arr, t_min, t_max);
                let hit_l: bool = tl.is_finite();
                let hit_r: bool = tr.is_finite();
                if hit_l && hit_r && sp + 2 <= 64 {
                    if tl <= tr {
                        stack[sp] = right_idx;
                        stack[sp + 1] = left_idx;
                    } else {
                        stack[sp] = left_idx;
                        stack[sp + 1] = right_idx;
                    }
                    sp += 2;
                } else if hit_l && sp < 64 {
                    stack[sp] = left_idx;
                    sp += 1;
                } else if hit_r && sp < 64 {
                    stack[sp] = right_idx;
                    sp += 1;
                }
            }
        }
        false
    }

    /// Traces a shadow/occlusion ray returning `true` immediately upon any hit within `(t_min, t_max)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - BVH reference.
    /// - `&Ray3D` - Shadow ray.
    /// - `f32` - Minimum offset (shadow bias).
    /// - `f32` - Maximum trace distance.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if occluded by scene geometry.
    #[must_use]
    pub fn trace_any_shadow(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
        let mut cache: u32 = u32::MAX;
        self.trace_any_shadow_cached(
            ray.get_origin(),
            ray.get_direction(),
            ray.get_inv_direction(),
            t_min,
            t_max,
            &mut cache,
        )
    }

    /// Traces a ray near-child-first against 32-byte DFS nodes and returns `(distance, tri_index)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - BVH reference.
    /// - `Vec3` - Ray origin.
    /// - `Vec3` - Unit ray direction.
    /// - `Vec3` - Precomputed safe reciprocal ray direction.
    /// - `f32` - Minimum offset bias.
    /// - `f32` - Maximum trace distance.
    ///
    /// # Returns
    ///
    /// - `Option<(f32, usize)>` - Closest hit distance and triangle index into `self.triangles`.
    #[must_use]
    pub fn trace_closest_raw(
        &self,
        origin: Vec3,
        dir: Vec3,
        inv_dir: Vec3,
        t_min: f32,
        t_max: f32,
    ) -> Option<(f32, usize)> {
        let Self {
            flat_nodes, geom, ..
        } = self;
        if flat_nodes.is_empty() || geom.is_empty() {
            return None;
        }
        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
        if !flat_nodes[0]
            .intersect_near(orig_arr, inv_arr, t_min, t_max)
            .is_finite()
        {
            return None;
        }
        let mut stack: [(u32, f32); 64] = [(0, 0.0); 64];
        let mut sp: usize = 1;
        let mut best_t: f32 = t_max;
        let mut best_idx: usize = usize::MAX;
        while sp > 0 {
            sp -= 1;
            let (node_id, node_tmin): (u32, f32) = stack[sp];
            if node_tmin >= best_t {
                continue;
            }
            let n: &BvhFlatNode = &flat_nodes[node_id as usize];
            let count: usize = n.tri_count as usize;
            if count > 0 {
                let first: usize = n.right_or_first as usize;
                for (off, tri) in geom[first..(first + count)].iter().enumerate() {
                    if let Some(t) = tri.intersect_raw(origin, dir, t_min, best_t) {
                        best_t = t;
                        best_idx = first + off;
                    }
                }
            } else {
                let left_idx: u32 = node_id + 1;
                let right_idx: u32 = n.right_or_first;
                let tl: f32 =
                    flat_nodes[left_idx as usize].intersect_near(orig_arr, inv_arr, t_min, best_t);
                let tr: f32 =
                    flat_nodes[right_idx as usize].intersect_near(orig_arr, inv_arr, t_min, best_t);
                let hit_l: bool = tl < best_t;
                let hit_r: bool = tr < best_t;
                if hit_l && hit_r && sp + 2 <= 64 {
                    if tl <= tr {
                        stack[sp] = (right_idx, tr);
                        stack[sp + 1] = (left_idx, tl);
                    } else {
                        stack[sp] = (left_idx, tl);
                        stack[sp + 1] = (right_idx, tr);
                    }
                    sp += 2;
                } else if hit_l && sp < 64 {
                    stack[sp] = (left_idx, tl);
                    sp += 1;
                } else if hit_r && sp < 64 {
                    stack[sp] = (right_idx, tr);
                    sp += 1;
                }
            }
        }
        if best_idx == usize::MAX {
            None
        } else {
            Some((best_t, best_idx))
        }
    }

    /// Traces a reflection/GI ray and returns the closest hit surface within `(t_min, t_max)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - BVH reference.
    /// - `&Ray3D` - Reflection or GI ray.
    /// - `f32` - Minimum offset bias.
    /// - `f32` - Maximum trace distance.
    ///
    /// # Returns
    ///
    /// - `Option<RayHit3D>` - Closest hit metadata if any geometry was struck.
    #[must_use]
    pub fn trace_closest(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<RayHit3D> {
        let (t, idx): (f32, usize) = self.trace_closest_raw(
            ray.get_origin(),
            ray.get_direction(),
            ray.get_inv_direction(),
            t_min,
            t_max,
        )?;
        let tri: &BvhTriangle = &self.get_triangles()[idx];
        let pt: Vec3 = ray.get_origin().add(ray.get_direction().scale(t));
        Some(RayHit3D {
            distance: t,
            point: pt,
            normal: tri.get_normal(),
            material: tri.get_material(),
        })
    }
}