Skip to main content

euv_core/game/engine3d/raytrace/accel/
impl.rs

1use super::*;
2
3/// Constructors and barycentric attribute interpolation helpers for `RtTriangle`.
4impl RtTriangle {
5    /// Constructs a local-space triangle with explicit positions, smooth vertex normals, UVs, and material slot.
6    ///
7    /// # Arguments
8    ///
9    /// - `[Vec3; 3]` - Triangle vertex positions `[v0, v1, v2]`.
10    /// - `[Vec3; 3]` - Smooth vertex normals `[n0, n1, n2]`.
11    /// - `[Vec2; 3]` - Primary texture coordinates `[uv0, uv1, uv2]`.
12    /// - `u16` - Sub-material slot index.
13    ///
14    /// # Returns
15    ///
16    /// - `Self` - Precomputed ray-traceable triangle.
17    #[must_use]
18    pub fn from_vertices(
19        positions: [Vec3; 3],
20        normals: [Vec3; 3],
21        uvs: [Vec2; 3],
22        material_slot: u16,
23    ) -> Self {
24        let v0: Vec3 = positions[0];
25        let v1: Vec3 = positions[1];
26        let v2: Vec3 = positions[2];
27        let edge1: Vec3 = v1.sub(v0);
28        let edge2: Vec3 = v2.sub(v0);
29        let geometric_normal: Vec3 = edge1.cross(edge2).normalize();
30        let mut bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
31        bounds.expand_point(v0);
32        bounds.expand_point(v1);
33        bounds.expand_point(v2);
34        let centroid: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
35        Self {
36            v0,
37            edge1,
38            edge2,
39            n0: if normals[0].length_sq() > RT_EPSILON {
40                normals[0].normalize()
41            } else {
42                geometric_normal
43            },
44            n1: if normals[1].length_sq() > RT_EPSILON {
45                normals[1].normalize()
46            } else {
47                geometric_normal
48            },
49            n2: if normals[2].length_sq() > RT_EPSILON {
50                normals[2].normalize()
51            } else {
52                geometric_normal
53            },
54            uv0: uvs[0],
55            uv1: uvs[1],
56            uv2: uvs[2],
57            geometric_normal,
58            bounds,
59            centroid,
60            material_slot,
61        }
62    }
63
64    /// Constructs a flat-shaded triangle directly from three vertex positions.
65    ///
66    /// # Arguments
67    ///
68    /// - `Vec3` - First vertex position.
69    /// - `Vec3` - Second vertex position.
70    /// - `Vec3` - Third vertex position.
71    ///
72    /// # Returns
73    ///
74    /// - `Self` - Flat-shaded ray-traceable triangle.
75    #[must_use]
76    pub fn from_positions(v0: Vec3, v1: Vec3, v2: Vec3) -> Self {
77        let face_normal: Vec3 = v1.sub(v0).cross(v2.sub(v0)).normalize();
78        Self::from_vertices(
79            [v0, v1, v2],
80            [face_normal, face_normal, face_normal],
81            [
82                Vec2::new(0.0, 0.0),
83                Vec2::new(1.0, 0.0),
84                Vec2::new(0.0, 1.0),
85            ],
86            0,
87        )
88    }
89
90    /// Interpolates the unit shading normal at barycentric coordinates `(u, v)`.
91    ///
92    /// # Arguments
93    ///
94    /// - `&Self` - Triangle reference.
95    /// - `f32` - Barycentric coordinate `u` for vertex 1.
96    /// - `f32` - Barycentric coordinate `v` for vertex 2.
97    ///
98    /// # Returns
99    ///
100    /// - `Vec3` - Interpolated unit shading normal.
101    #[must_use]
102    pub fn interpolate_normal(&self, bary_u: f32, bary_v: f32) -> Vec3 {
103        let w: f32 = (1.0 - bary_u - bary_v).max(0.0);
104        let blended: Vec3 = self
105            .get_n0()
106            .scale(w)
107            .add(self.get_n1().scale(bary_u))
108            .add(self.get_n2().scale(bary_v));
109        if blended.length_sq() > RT_EPSILON {
110            blended.normalize()
111        } else {
112            self.get_geometric_normal()
113        }
114    }
115
116    /// Interpolates the texture coordinate at barycentric coordinates `(u, v)`.
117    ///
118    /// # Arguments
119    ///
120    /// - `&Self` - Triangle reference.
121    /// - `f32` - Barycentric coordinate `u` for vertex 1.
122    /// - `f32` - Barycentric coordinate `v` for vertex 2.
123    ///
124    /// # Returns
125    ///
126    /// - `Vec2` - Interpolated `(u, v)` texture coordinate.
127    #[must_use]
128    pub fn interpolate_uv(&self, bary_u: f32, bary_v: f32) -> Vec2 {
129        let w: f32 = (1.0 - bary_u - bary_v).max(0.0);
130        let uv0: Vec2 = self.get_uv0();
131        let uv1: Vec2 = self.get_uv1();
132        let uv2: Vec2 = self.get_uv2();
133        Vec2::new(
134            uv0.get_x() * w + uv1.get_x() * bary_u + uv2.get_x() * bary_v,
135            uv0.get_y() * w + uv1.get_y() * bary_u + uv2.get_y() * bary_v,
136        )
137    }
138}
139
140/// Default empty bucket constructor for `SahBin`.
141impl Default for SahBin {
142    /// Creates an empty SAH bucket with inverted bounds and zero primitive count.
143    ///
144    /// # Returns
145    ///
146    /// - `Self` - Empty SAH bin.
147    fn default() -> Self {
148        Self {
149            bounds: AxisAlignedBox3D::empty(),
150            count: 0,
151        }
152    }
153}
154
155/// Default empty bottom-level acceleration structure constructor for `Blas3D`.
156impl Default for Blas3D {
157    /// Creates an empty `Blas3D` with inverted empty bounds.
158    ///
159    /// # Returns
160    ///
161    /// - `Self` - Empty BLAS.
162    fn default() -> Self {
163        Self {
164            nodes: Vec::new(),
165            triangles: Vec::new(),
166            bounds: AxisAlignedBox3D::empty(),
167        }
168    }
169}
170
171/// SAH-binned construction, iterative zero-alloc traversal, and parity testing for `Blas3D`.
172impl Blas3D {
173    /// Builds a SAH-binned triangle BVH from a flat list of local-space triangles.
174    ///
175    /// # Arguments
176    ///
177    /// - `Vec<RtTriangle>` - Local-space triangles to partition.
178    ///
179    /// # Returns
180    ///
181    /// - `Self` - Built bottom-level acceleration structure.
182    #[must_use]
183    pub fn from_triangles(mut triangles: Vec<RtTriangle>) -> Self {
184        if triangles.is_empty() {
185            return Self {
186                nodes: Vec::new(),
187                triangles,
188                bounds: AxisAlignedBox3D::empty(),
189            };
190        }
191        let tri_count: usize = triangles.len();
192        let mut nodes: Vec<BlasNode3D> = Vec::with_capacity(tri_count * 2);
193        let root_idx: u32 = Self::build_recursive(&mut nodes, &mut triangles, 0, tri_count);
194        let root_bounds: AxisAlignedBox3D = nodes
195            .get(root_idx as usize)
196            .map_or(AxisAlignedBox3D::empty(), |node: &BlasNode3D| {
197                node.get_bounds()
198            });
199        Self {
200            nodes,
201            triangles,
202            bounds: root_bounds,
203        }
204    }
205
206    /// Builds a `Blas3D` directly from an existing `euv-core` `Mesh3D`.
207    ///
208    /// # Arguments
209    ///
210    /// - `&Mesh3D` - Source indexed 3D mesh.
211    ///
212    /// # Returns
213    ///
214    /// - `Self` - Local-space BLAS over all valid mesh triangles.
215    #[must_use]
216    pub fn from_mesh(mesh: &Mesh3D) -> Self {
217        let vertices: &[Vertex3D] = mesh.get_vertices().as_slice();
218        let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
219        let tri_mats: &[u16] = mesh.get_tri_materials().as_slice();
220        let mut triangles: Vec<RtTriangle> = Vec::with_capacity(indices.len());
221        for (tri_idx, tri) in indices.iter().enumerate() {
222            let i0: usize = tri[0] as usize;
223            let i1: usize = tri[1] as usize;
224            let i2: usize = tri[2] as usize;
225            if i0 >= vertices.len() || i1 >= vertices.len() || i2 >= vertices.len() {
226                continue;
227            }
228            let vert0: Vertex3D = vertices[i0];
229            let vert1: Vertex3D = vertices[i1];
230            let vert2: Vertex3D = vertices[i2];
231            let slot: u16 = tri_mats.get(tri_idx).copied().unwrap_or(0);
232            let uv0_arr: [f32; 2] = vert0.get_uv0();
233            let uv1_arr: [f32; 2] = vert1.get_uv0();
234            let uv2_arr: [f32; 2] = vert2.get_uv0();
235            triangles.push(RtTriangle::from_vertices(
236                [
237                    vert0.get_position(),
238                    vert1.get_position(),
239                    vert2.get_position(),
240                ],
241                [vert0.get_normal(), vert1.get_normal(), vert2.get_normal()],
242                [
243                    Vec2::new(uv0_arr[0], uv0_arr[1]),
244                    Vec2::new(uv1_arr[0], uv1_arr[1]),
245                    Vec2::new(uv2_arr[0], uv2_arr[1]),
246                ],
247                slot,
248            ));
249        }
250        Self::from_triangles(triangles)
251    }
252
253    /// Recursively constructs a SAH-binned BLAS subtree over `triangles[start..end]`.
254    ///
255    /// # Arguments
256    ///
257    /// - `&mut Vec<BlasNode3D>` - Destination node pool.
258    /// - `&mut [RtTriangle]` - Mutable triangle array partitioned in place.
259    /// - `usize` - Inclusive starting triangle index.
260    /// - `usize` - Exclusive ending triangle index.
261    ///
262    /// # Returns
263    ///
264    /// - `u32` - Index of the created `BlasNode3D`.
265    fn build_recursive(
266        nodes: &mut Vec<BlasNode3D>,
267        triangles: &mut [RtTriangle],
268        start: usize,
269        end: usize,
270    ) -> u32 {
271        let mut node_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
272        let mut centroid_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
273        for tri in &triangles[start..end] {
274            node_bounds.expand_box(tri.get_bounds());
275            centroid_bounds.expand_point(tri.get_centroid());
276        }
277        let node_idx: u32 = nodes.len() as u32;
278        let count: usize = end - start;
279        nodes.push(BlasNode3D {
280            bounds: node_bounds,
281            left: 0,
282            right: 0,
283            first_tri: start as u32,
284            tri_count: count as u32,
285        });
286        if count <= RT_BLAS_LEAF_MAX_TRIS {
287            return node_idx;
288        }
289        let parent_area: f32 = node_bounds.surface_area().max(RT_EPSILON);
290        let leaf_cost: f32 = count as f32;
291        let mut best_cost: f32 = f32::INFINITY;
292        let mut best_axis: usize = 0;
293        let mut best_split_pos: f32 = 0.0;
294        let mut found_sah_split: bool = false;
295        for axis in 0..3 {
296            let c_min: f32 = vec3_axis(centroid_bounds.get_min(), axis);
297            let c_max: f32 = vec3_axis(centroid_bounds.get_max(), axis);
298            let span: f32 = c_max - c_min;
299            if span <= RT_EPSILON {
300                continue;
301            }
302            let mut bins: [SahBin; RT_SAH_BIN_COUNT] = [SahBin::default(); RT_SAH_BIN_COUNT];
303            let scale: f32 = (RT_SAH_BIN_COUNT as f32) / span;
304            for tri in &triangles[start..end] {
305                let raw_bin: usize =
306                    ((vec3_axis(tri.get_centroid(), axis) - c_min) * scale) as usize;
307                let bin_idx: usize = raw_bin.min(RT_SAH_BIN_COUNT - 1);
308                let mut bin_bounds: AxisAlignedBox3D = bins[bin_idx].get_bounds();
309                bin_bounds.expand_box(tri.get_bounds());
310                bins[bin_idx].set_bounds(bin_bounds);
311                let next_count: u32 = bins[bin_idx].get_count() + 1;
312                bins[bin_idx].set_count(next_count);
313            }
314            let mut left_area: [f32; RT_SAH_BIN_COUNT - 1] = [0.0; RT_SAH_BIN_COUNT - 1];
315            let mut left_count: [u32; RT_SAH_BIN_COUNT - 1] = [0; RT_SAH_BIN_COUNT - 1];
316            let mut acc_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
317            let mut acc_count: u32 = 0;
318            for split_idx in 0..(RT_SAH_BIN_COUNT - 1) {
319                acc_bounds.expand_box(bins[split_idx].get_bounds());
320                acc_count += bins[split_idx].get_count();
321                left_area[split_idx] = acc_bounds.surface_area();
322                left_count[split_idx] = acc_count;
323            }
324            let mut right_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
325            let mut right_count: u32 = 0;
326            for split_idx in (0..(RT_SAH_BIN_COUNT - 1)).rev() {
327                right_bounds.expand_box(bins[split_idx + 1].get_bounds());
328                right_count += bins[split_idx + 1].get_count();
329                let l_cnt: u32 = left_count[split_idx];
330                if l_cnt == 0 || right_count == 0 {
331                    continue;
332                }
333                let cost: f32 = 0.5
334                    + ((left_area[split_idx] * (l_cnt as f32))
335                        + (right_bounds.surface_area() * (right_count as f32)))
336                        / parent_area;
337                if cost < best_cost {
338                    best_cost = cost;
339                    best_axis = axis;
340                    best_split_pos =
341                        c_min + ((split_idx + 1) as f32) * (span / (RT_SAH_BIN_COUNT as f32));
342                    found_sah_split = true;
343                }
344            }
345        }
346        let mut mid: usize = if found_sah_split && best_cost < leaf_cost {
347            Self::partition_triangles(triangles, start, end, best_axis, best_split_pos)
348        } else {
349            let extent: Vec3 = centroid_bounds.get_max().sub(centroid_bounds.get_min());
350            let fallback_axis: usize =
351                if extent.get_x() >= extent.get_y() && extent.get_x() >= extent.get_z() {
352                    0
353                } else if extent.get_y() >= extent.get_z() {
354                    1
355                } else {
356                    2
357                };
358            let split_mid: f32 = (vec3_axis(centroid_bounds.get_min(), fallback_axis)
359                + vec3_axis(centroid_bounds.get_max(), fallback_axis))
360                * 0.5;
361            Self::partition_triangles(triangles, start, end, fallback_axis, split_mid)
362        };
363        if mid == start || mid == end {
364            mid = start + count / 2;
365        }
366        let left_idx: u32 = Self::build_recursive(nodes, triangles, start, mid);
367        let right_idx: u32 = Self::build_recursive(nodes, triangles, mid, end);
368        if let Some(node_ref) = nodes.get_mut(node_idx as usize) {
369            node_ref.set_left(left_idx);
370            node_ref.set_right(right_idx);
371            node_ref.set_tri_count(0);
372        }
373        node_idx
374    }
375
376    /// Partitions `triangles[start..end]` in place around `split_pos` along `axis`.
377    ///
378    /// # Arguments
379    ///
380    /// - `&mut [RtTriangle]` - Mutable triangle slice.
381    /// - `usize` - Inclusive start index.
382    /// - `usize` - Exclusive end index.
383    /// - `usize` - Split axis (`0`, `1`, or `2`).
384    /// - `f32` - Split coordinate along `axis`.
385    ///
386    /// # Returns
387    ///
388    /// - `usize` - Partition midpoint index.
389    fn partition_triangles(
390        triangles: &mut [RtTriangle],
391        start: usize,
392        end: usize,
393        axis: usize,
394        split_pos: f32,
395    ) -> usize {
396        let mut left: usize = start;
397        let mut right: usize = end;
398        while left < right {
399            if vec3_axis(triangles[left].get_centroid(), axis) < split_pos {
400                left += 1;
401            } else {
402                right -= 1;
403                triangles.swap(left, right);
404            }
405        }
406        left
407    }
408
409    /// Returns the number of triangles stored in this BLAS.
410    ///
411    /// # Arguments
412    ///
413    /// - `&Self` - BLAS reference.
414    ///
415    /// # Returns
416    ///
417    /// - `usize` - Triangle count.
418    #[must_use]
419    pub fn triangle_count(&self) -> usize {
420        self.get_triangles().len()
421    }
422
423    /// Returns the number of BVH nodes stored in this BLAS.
424    ///
425    /// # Arguments
426    ///
427    /// - `&Self` - BLAS reference.
428    ///
429    /// # Returns
430    ///
431    /// - `usize` - Node count.
432    #[must_use]
433    pub fn node_count(&self) -> usize {
434        self.get_nodes().len()
435    }
436
437    /// Returns `true` when this BLAS contains no triangles.
438    ///
439    /// # Arguments
440    ///
441    /// - `&Self` - BLAS reference.
442    ///
443    /// # Returns
444    ///
445    /// - `bool` - Whether the BLAS is empty.
446    #[must_use]
447    pub fn is_empty(&self) -> bool {
448        self.get_triangles().is_empty()
449    }
450
451    /// Traces a normalized local-space `Ray3D` against the BLAS using zero-allocation front-to-back traversal.
452    ///
453    /// # Arguments
454    ///
455    /// - `&Self` - BLAS reference.
456    /// - `&Ray3D` - Local-space ray.
457    /// - `f32` - Minimum accepted hit distance.
458    /// - `f32` - Maximum accepted hit distance.
459    ///
460    /// # Returns
461    ///
462    /// - `Option<RtLocalHit>` - Closest local-space triangle hit if any.
463    #[must_use]
464    pub fn trace_closest(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<RtLocalHit> {
465        self.trace_closest_unnormalized(
466            ray.get_origin(),
467            ray.get_direction(),
468            ray.get_inv_direction(),
469            t_min,
470            t_max,
471        )
472    }
473
474    /// Traces a possibly unnormalized local-space ray against the BLAS preserving parametric `t` across non-uniform instance transforms.
475    ///
476    /// # Arguments
477    ///
478    /// - `&Self` - BLAS reference.
479    /// - `Vec3` - Ray origin in local BLAS space.
480    /// - `Vec3` - Ray direction in local BLAS space.
481    /// - `Vec3` - Safe reciprocal ray direction for slab AABB testing.
482    /// - `f32` - Minimum accepted parametric hit distance.
483    /// - `f32` - Maximum accepted parametric hit distance.
484    ///
485    /// # Returns
486    ///
487    /// - `Option<RtLocalHit>` - Closest local-space triangle intersection if any.
488    #[must_use]
489    pub fn trace_closest_unnormalized(
490        &self,
491        origin: Vec3,
492        direction: Vec3,
493        inv_dir: Vec3,
494        t_min: f32,
495        t_max: f32,
496    ) -> Option<RtLocalHit> {
497        let nodes: &[BlasNode3D] = self.get_nodes().as_slice();
498        let triangles: &[RtTriangle] = self.get_triangles().as_slice();
499        if nodes.is_empty() {
500            return None;
501        }
502        let root_near: f32 = nodes[0]
503            .get_bounds()
504            .intersect_ray_near(origin, inv_dir, t_min, t_max);
505        if !root_near.is_finite() {
506            return None;
507        }
508        let mut stack: [u32; RT_BVH_STACK_CAPACITY] = [0; RT_BVH_STACK_CAPACITY];
509        let mut stack_len: usize = 1;
510        let mut best_t: f32 = t_max;
511        let mut best_tri_idx: u32 = u32::MAX;
512        let mut best_u: f32 = 0.0;
513        let mut best_v: f32 = 0.0;
514        while stack_len > 0 {
515            stack_len -= 1;
516            let node: BlasNode3D = nodes[stack[stack_len] as usize];
517            let tri_count: u32 = node.get_tri_count();
518            if tri_count > 0 {
519                let first: usize = node.get_first_tri() as usize;
520                let last: usize = first + (tri_count as usize);
521                for (offset, tri) in triangles[first..last].iter().enumerate() {
522                    if let Some((hit_t, bary_u, bary_v)) =
523                        intersect_triangle_moller_trumbore(origin, direction, tri, t_min, best_t)
524                    {
525                        best_t = hit_t;
526                        best_tri_idx = (first + offset) as u32;
527                        best_u = bary_u;
528                        best_v = bary_v;
529                    }
530                }
531            } else {
532                let left_idx: u32 = node.get_left();
533                let right_idx: u32 = node.get_right();
534                let t_left: f32 = nodes[left_idx as usize]
535                    .get_bounds()
536                    .intersect_ray_near(origin, inv_dir, t_min, best_t);
537                let t_right: f32 = nodes[right_idx as usize]
538                    .get_bounds()
539                    .intersect_ray_near(origin, inv_dir, t_min, best_t);
540                let hit_left: bool = t_left.is_finite() && t_left <= best_t;
541                let hit_right: bool = t_right.is_finite() && t_right <= best_t;
542                if hit_left && hit_right {
543                    let (near_idx, far_idx): (u32, u32) = if t_left <= t_right {
544                        (left_idx, right_idx)
545                    } else {
546                        (right_idx, left_idx)
547                    };
548                    if stack_len + 2 <= RT_BVH_STACK_CAPACITY {
549                        stack[stack_len] = far_idx;
550                        stack[stack_len + 1] = near_idx;
551                        stack_len += 2;
552                    }
553                } else if hit_left && stack_len < RT_BVH_STACK_CAPACITY {
554                    stack[stack_len] = left_idx;
555                    stack_len += 1;
556                } else if hit_right && stack_len < RT_BVH_STACK_CAPACITY {
557                    stack[stack_len] = right_idx;
558                    stack_len += 1;
559                }
560            }
561        }
562        if best_tri_idx == u32::MAX {
563            return None;
564        }
565        let tri: RtTriangle = triangles[best_tri_idx as usize];
566        let position: Vec3 = origin.add(direction.scale(best_t));
567        Some(RtLocalHit {
568            distance: best_t,
569            barycentric_u: best_u,
570            barycentric_v: best_v,
571            position,
572            geometric_normal: tri.get_geometric_normal(),
573            shading_normal: tri.interpolate_normal(best_u, best_v),
574            uv: tri.interpolate_uv(best_u, best_v),
575            triangle_index: best_tri_idx,
576            material_slot: tri.get_material_slot(),
577        })
578    }
579
580    /// Tests whether a normalized local-space ray intersects any triangle in `[t_min, t_max]` with early termination.
581    ///
582    /// # Arguments
583    ///
584    /// - `&Self` - BLAS reference.
585    /// - `&Ray3D` - Local-space shadow or occlusion ray.
586    /// - `f32` - Minimum accepted hit distance.
587    /// - `f32` - Maximum accepted hit distance.
588    ///
589    /// # Returns
590    ///
591    /// - `bool` - `true` if any triangle occludes the ray interval.
592    #[must_use]
593    pub fn trace_any_hit(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
594        self.trace_any_hit_unnormalized(
595            ray.get_origin(),
596            ray.get_direction(),
597            ray.get_inv_direction(),
598            t_min,
599            t_max,
600        )
601    }
602
603    /// Tests whether an unnormalized local-space ray intersects any triangle in `[t_min, t_max]` with immediate exit.
604    ///
605    /// # Arguments
606    ///
607    /// - `&Self` - BLAS reference.
608    /// - `Vec3` - Ray origin in local space.
609    /// - `Vec3` - Ray direction in local space.
610    /// - `Vec3` - Safe reciprocal ray direction.
611    /// - `f32` - Minimum accepted parametric distance.
612    /// - `f32` - Maximum accepted parametric distance.
613    ///
614    /// # Returns
615    ///
616    /// - `bool` - `true` if any triangle intersects the ray segment.
617    #[must_use]
618    pub fn trace_any_hit_unnormalized(
619        &self,
620        origin: Vec3,
621        direction: Vec3,
622        inv_dir: Vec3,
623        t_min: f32,
624        t_max: f32,
625    ) -> bool {
626        let nodes: &[BlasNode3D] = self.get_nodes().as_slice();
627        let triangles: &[RtTriangle] = self.get_triangles().as_slice();
628        if nodes.is_empty() {
629            return false;
630        }
631        if !nodes[0]
632            .get_bounds()
633            .intersect_ray_near(origin, inv_dir, t_min, t_max)
634            .is_finite()
635        {
636            return false;
637        }
638        let mut stack: [u32; RT_BVH_STACK_CAPACITY] = [0; RT_BVH_STACK_CAPACITY];
639        let mut stack_len: usize = 1;
640        while stack_len > 0 {
641            stack_len -= 1;
642            let node: BlasNode3D = nodes[stack[stack_len] as usize];
643            let tri_count: u32 = node.get_tri_count();
644            if tri_count > 0 {
645                let first: usize = node.get_first_tri() as usize;
646                let last: usize = first + (tri_count as usize);
647                for tri in &triangles[first..last] {
648                    if intersect_triangle_moller_trumbore(origin, direction, tri, t_min, t_max)
649                        .is_some()
650                    {
651                        return true;
652                    }
653                }
654            } else {
655                let left_idx: u32 = node.get_left();
656                let right_idx: u32 = node.get_right();
657                if nodes[left_idx as usize]
658                    .get_bounds()
659                    .intersect_ray_near(origin, inv_dir, t_min, t_max)
660                    .is_finite()
661                    && stack_len < RT_BVH_STACK_CAPACITY
662                {
663                    stack[stack_len] = left_idx;
664                    stack_len += 1;
665                }
666                if nodes[right_idx as usize]
667                    .get_bounds()
668                    .intersect_ray_near(origin, inv_dir, t_min, t_max)
669                    .is_finite()
670                    && stack_len < RT_BVH_STACK_CAPACITY
671                {
672                    stack[stack_len] = right_idx;
673                    stack_len += 1;
674                }
675            }
676        }
677        false
678    }
679
680    /// Reference O(N) brute-force triangle intersection scanning every triangle linearly for exact BVH parity verification.
681    ///
682    /// # Arguments
683    ///
684    /// - `&Self` - BLAS reference.
685    /// - `&Ray3D` - Local-space ray.
686    /// - `f32` - Minimum accepted hit distance.
687    /// - `f32` - Maximum accepted hit distance.
688    ///
689    /// # Returns
690    ///
691    /// - `Option<RtLocalHit>` - Exact closest local-space triangle intersection.
692    #[must_use]
693    pub fn trace_closest_brute_force(
694        &self,
695        ray: &Ray3D,
696        t_min: f32,
697        t_max: f32,
698    ) -> Option<RtLocalHit> {
699        self.trace_closest_brute_force_unnormalized(
700            ray.get_origin(),
701            ray.get_direction(),
702            t_min,
703            t_max,
704        )
705    }
706
707    /// Reference O(N) brute-force unnormalized-ray triangle intersection for instanced TLAS parity verification.
708    ///
709    /// # Arguments
710    ///
711    /// - `&Self` - BLAS reference.
712    /// - `Vec3` - Ray origin in local space.
713    /// - `Vec3` - Ray direction in local space.
714    /// - `f32` - Minimum accepted parametric distance.
715    /// - `f32` - Maximum accepted parametric distance.
716    ///
717    /// # Returns
718    ///
719    /// - `Option<RtLocalHit>` - Exact closest local-space triangle intersection.
720    #[must_use]
721    pub fn trace_closest_brute_force_unnormalized(
722        &self,
723        origin: Vec3,
724        direction: Vec3,
725        t_min: f32,
726        t_max: f32,
727    ) -> Option<RtLocalHit> {
728        let triangles: &[RtTriangle] = self.get_triangles().as_slice();
729        let mut best_t: f32 = t_max;
730        let mut best_tri_idx: u32 = u32::MAX;
731        let mut best_u: f32 = 0.0;
732        let mut best_v: f32 = 0.0;
733        for (idx, tri) in triangles.iter().enumerate() {
734            if let Some((hit_t, bary_u, bary_v)) =
735                intersect_triangle_moller_trumbore(origin, direction, tri, t_min, best_t)
736            {
737                best_t = hit_t;
738                best_tri_idx = idx as u32;
739                best_u = bary_u;
740                best_v = bary_v;
741            }
742        }
743        if best_tri_idx == u32::MAX {
744            return None;
745        }
746        let tri: RtTriangle = triangles[best_tri_idx as usize];
747        let position: Vec3 = origin.add(direction.scale(best_t));
748        Some(RtLocalHit {
749            distance: best_t,
750            barycentric_u: best_u,
751            barycentric_v: best_v,
752            position,
753            geometric_normal: tri.get_geometric_normal(),
754            shading_normal: tri.interpolate_normal(best_u, best_v),
755            uv: tri.interpolate_uv(best_u, best_v),
756            triangle_index: best_tri_idx,
757            material_slot: tri.get_material_slot(),
758        })
759    }
760}
761
762/// Transform precomputation and update helpers for `RtInstance`.
763impl RtInstance {
764    /// Creates an instanced BLAS reference with precomputed inverse matrix, normal matrix, and world bounding box.
765    ///
766    /// # Arguments
767    ///
768    /// - `u32` - Index of the referenced `Blas3D`.
769    /// - `Mat4` - Local-to-world affine transform matrix.
770    /// - `u32` - Bound material index.
771    /// - `AxisAlignedBox3D` - Local-space bounding box of the referenced `Blas3D`.
772    ///
773    /// # Returns
774    ///
775    /// - `Self` - Ready-to-trace scene instance.
776    #[must_use]
777    pub fn new(
778        blas_id: u32,
779        transform: Mat4,
780        material_id: u32,
781        local_bounds: AxisAlignedBox3D,
782    ) -> Self {
783        let inv_transform: Mat4 = transform.inverse().unwrap_or(Mat4::identity());
784        let normal_matrix: [Vec3; 3] = transform.normal_matrix_3x3();
785        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
786        let det: f32 = mat4_linear_determinant(&transform);
787        let determinant_sign: f32 = if det < 0.0 { -1.0 } else { 1.0 };
788        Self {
789            blas_id,
790            transform,
791            inv_transform,
792            normal_matrix,
793            material_id,
794            world_bounds,
795            visible: true,
796            determinant_sign,
797        }
798    }
799
800    /// Recomputes the inverse transform, normal matrix, and world bounding box for a moved or scaled instance.
801    ///
802    /// # Arguments
803    ///
804    /// - `&Self` - Mutable instance reference.
805    /// - `Mat4` - Updated local-to-world affine transform matrix.
806    /// - `AxisAlignedBox3D` - Local-space bounding box of the referenced `Blas3D`.
807    pub fn update_transform(&mut self, transform: Mat4, local_bounds: AxisAlignedBox3D) {
808        let inv_transform: Mat4 = transform.inverse().unwrap_or(Mat4::identity());
809        let normal_matrix: [Vec3; 3] = transform.normal_matrix_3x3();
810        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
811        let det: f32 = mat4_linear_determinant(&transform);
812        self.set_transform(transform);
813        self.set_inv_transform(inv_transform);
814        self.set_normal_matrix(normal_matrix);
815        self.set_world_bounds(world_bounds);
816        self.set_determinant_sign(if det < 0.0 { -1.0 } else { 1.0 });
817    }
818}
819
820/// Default empty top-level acceleration structure constructor for `Tlas3D`.
821impl Default for Tlas3D {
822    /// Creates an empty `Tlas3D`.
823    ///
824    /// # Returns
825    ///
826    /// - `Self` - Empty TLAS.
827    fn default() -> Self {
828        Self::new()
829    }
830}
831
832/// SAH construction, zero-alloc bottom-up refit, and instanced traversal for `Tlas3D`.
833impl Tlas3D {
834    /// Creates an empty top-level acceleration structure.
835    ///
836    /// # Returns
837    ///
838    /// - `Self` - Empty TLAS.
839    #[must_use]
840    pub fn new() -> Self {
841        Self {
842            nodes: Vec::new(),
843            instances: Vec::new(),
844            instance_order: Vec::new(),
845            bounds: AxisAlignedBox3D::empty(),
846            refit_count: 0,
847            rebuild_count: 0,
848        }
849    }
850
851    /// Registers a new `RtInstance` and returns its stable caller-facing instance identifier.
852    ///
853    /// # Arguments
854    ///
855    /// - `&Self` - Mutable TLAS reference.
856    /// - `RtInstance` - Instance descriptor to append.
857    ///
858    /// # Returns
859    ///
860    /// - `usize` - Stable `instance_id` index.
861    pub fn add_instance(&mut self, instance: RtInstance) -> usize {
862        let id: usize = self.get_instances().len();
863        self.get_mut_instances().push(instance);
864        id
865    }
866
867    /// Updates an existing instance's transform in place so `refit()` can update bounds without rebuilding BLAS geometry.
868    ///
869    /// # Arguments
870    ///
871    /// - `&Self` - Mutable TLAS reference.
872    /// - `usize` - Stable instance identifier.
873    /// - `Mat4` - New local-to-world affine transform.
874    /// - `AxisAlignedBox3D` - Local bounding box of the instance's BLAS.
875    ///
876    /// # Returns
877    ///
878    /// - `bool` - `true` when `instance_id` exists and was updated.
879    pub fn update_instance_transform(
880        &mut self,
881        instance_id: usize,
882        transform: Mat4,
883        local_bounds: AxisAlignedBox3D,
884    ) -> bool {
885        if let Some(instance) = self.get_mut_instances().get_mut(instance_id) {
886            instance.update_transform(transform, local_bounds);
887            true
888        } else {
889            false
890        }
891    }
892
893    /// Returns the number of registered instances.
894    ///
895    /// # Arguments
896    ///
897    /// - `&Self` - TLAS reference.
898    ///
899    /// # Returns
900    ///
901    /// - `usize` - Instance count.
902    #[must_use]
903    pub fn instance_count(&self) -> usize {
904        self.get_instances().len()
905    }
906
907    /// Returns the number of built TLAS BVH nodes.
908    ///
909    /// # Arguments
910    ///
911    /// - `&Self` - TLAS reference.
912    ///
913    /// # Returns
914    ///
915    /// - `usize` - Node count.
916    #[must_use]
917    pub fn node_count(&self) -> usize {
918        self.get_nodes().len()
919    }
920
921    /// Returns `true` when the TLAS contains no built nodes.
922    ///
923    /// # Arguments
924    ///
925    /// - `&Self` - TLAS reference.
926    ///
927    /// # Returns
928    ///
929    /// - `bool` - Whether the TLAS is empty.
930    #[must_use]
931    pub fn is_empty(&self) -> bool {
932        self.get_nodes().is_empty()
933    }
934
935    /// Rebuilds the SAH top-level BVH over all visible instances while keeping `instances` indices stable.
936    ///
937    /// # Arguments
938    ///
939    /// - `&Self` - Mutable TLAS reference.
940    pub fn rebuild(&mut self) {
941        let Self {
942            nodes,
943            instances,
944            instance_order,
945            bounds,
946            rebuild_count,
947            ..
948        } = self;
949        nodes.clear();
950        instance_order.clear();
951        for (idx, inst) in instances.iter().enumerate() {
952            if inst.get_visible() {
953                instance_order.push(idx as u32);
954            }
955        }
956        if instance_order.is_empty() {
957            *bounds = AxisAlignedBox3D::empty();
958            *rebuild_count += 1;
959            return;
960        }
961        let order_len: usize = instance_order.len();
962        nodes.reserve(order_len * 2);
963        let root_idx: u32 =
964            Self::build_tlas_recursive(nodes, instances, instance_order, 0, order_len);
965        *bounds = nodes
966            .get(root_idx as usize)
967            .map_or(AxisAlignedBox3D::empty(), |node: &TlasNode3D| {
968                node.get_bounds()
969            });
970        *rebuild_count += 1;
971    }
972
973    /// Performs an O(N) zero-allocation bottom-up bounding box refit over the existing TLAS topology.
974    ///
975    /// # Arguments
976    ///
977    /// - `&Self` - Mutable TLAS reference.
978    pub fn refit(&mut self) {
979        let visible_count: usize = self
980            .get_instances()
981            .iter()
982            .filter(|inst: &&RtInstance| inst.get_visible())
983            .count();
984        if self.get_nodes().is_empty() || self.get_instance_order().len() != visible_count {
985            self.rebuild();
986            return;
987        }
988        let Self {
989            nodes,
990            instances,
991            instance_order,
992            bounds,
993            refit_count,
994            ..
995        } = self;
996        let node_count: usize = nodes.len();
997        for idx in (0..node_count).rev() {
998            let inst_count: u32 = nodes[idx].get_instance_count();
999            if inst_count > 0 {
1000                let first: usize = nodes[idx].get_first_instance() as usize;
1001                let last: usize = first + (inst_count as usize);
1002                let mut leaf_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1003                for &inst_id in &instance_order[first..last] {
1004                    leaf_bounds.expand_box(instances[inst_id as usize].get_world_bounds());
1005                }
1006                nodes[idx].set_bounds(leaf_bounds);
1007            } else {
1008                let left_idx: usize = nodes[idx].get_left() as usize;
1009                let right_idx: usize = nodes[idx].get_right() as usize;
1010                let mut merged: AxisAlignedBox3D = nodes[left_idx].get_bounds();
1011                merged.expand_box(nodes[right_idx].get_bounds());
1012                nodes[idx].set_bounds(merged);
1013            }
1014        }
1015        *bounds = nodes[0].get_bounds();
1016        *refit_count += 1;
1017    }
1018
1019    /// Recursively constructs a SAH-binned TLAS subtree partitioning `instance_order[start..end]`.
1020    ///
1021    /// # Arguments
1022    ///
1023    /// - `&mut Vec<TlasNode3D>` - Destination TLAS node buffer.
1024    /// - `&[RtInstance]` - Stable instance array.
1025    /// - `&mut [u32]` - Mutable instance index indirection slice.
1026    /// - `usize` - Inclusive start index.
1027    /// - `usize` - Exclusive end index.
1028    ///
1029    /// # Returns
1030    ///
1031    /// - `u32` - Index of the created `TlasNode3D`.
1032    fn build_tlas_recursive(
1033        nodes: &mut Vec<TlasNode3D>,
1034        instances: &[RtInstance],
1035        instance_order: &mut [u32],
1036        start: usize,
1037        end: usize,
1038    ) -> u32 {
1039        let mut node_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1040        let mut centroid_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1041        for &inst_id in &instance_order[start..end] {
1042            let wb: AxisAlignedBox3D = instances[inst_id as usize].get_world_bounds();
1043            node_bounds.expand_box(wb);
1044            centroid_bounds.expand_point(wb.center());
1045        }
1046        let node_idx: u32 = nodes.len() as u32;
1047        let count: usize = end - start;
1048        nodes.push(TlasNode3D {
1049            bounds: node_bounds,
1050            left: 0,
1051            right: 0,
1052            first_instance: start as u32,
1053            instance_count: count as u32,
1054        });
1055        if count <= RT_TLAS_LEAF_MAX_INSTANCES {
1056            return node_idx;
1057        }
1058        let parent_area: f32 = node_bounds.surface_area().max(RT_EPSILON);
1059        let leaf_cost: f32 = count as f32;
1060        let mut best_cost: f32 = f32::INFINITY;
1061        let mut best_axis: usize = 0;
1062        let mut best_split_pos: f32 = 0.0;
1063        let mut found_sah: bool = false;
1064        for axis in 0..3 {
1065            let c_min: f32 = vec3_axis(centroid_bounds.get_min(), axis);
1066            let c_max: f32 = vec3_axis(centroid_bounds.get_max(), axis);
1067            let span: f32 = c_max - c_min;
1068            if span <= RT_EPSILON {
1069                continue;
1070            }
1071            let mut bins: [SahBin; RT_SAH_BIN_COUNT] = [SahBin::default(); RT_SAH_BIN_COUNT];
1072            let scale: f32 = (RT_SAH_BIN_COUNT as f32) / span;
1073            for &inst_id in &instance_order[start..end] {
1074                let wb: AxisAlignedBox3D = instances[inst_id as usize].get_world_bounds();
1075                let raw_bin: usize = ((vec3_axis(wb.center(), axis) - c_min) * scale) as usize;
1076                let bin_idx: usize = raw_bin.min(RT_SAH_BIN_COUNT - 1);
1077                let mut bin_bounds: AxisAlignedBox3D = bins[bin_idx].get_bounds();
1078                bin_bounds.expand_box(wb);
1079                bins[bin_idx].set_bounds(bin_bounds);
1080                let next_count: u32 = bins[bin_idx].get_count() + 1;
1081                bins[bin_idx].set_count(next_count);
1082            }
1083            let mut left_area: [f32; RT_SAH_BIN_COUNT - 1] = [0.0; RT_SAH_BIN_COUNT - 1];
1084            let mut left_count: [u32; RT_SAH_BIN_COUNT - 1] = [0; RT_SAH_BIN_COUNT - 1];
1085            let mut acc_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1086            let mut acc_count: u32 = 0;
1087            for split_idx in 0..(RT_SAH_BIN_COUNT - 1) {
1088                acc_bounds.expand_box(bins[split_idx].get_bounds());
1089                acc_count += bins[split_idx].get_count();
1090                left_area[split_idx] = acc_bounds.surface_area();
1091                left_count[split_idx] = acc_count;
1092            }
1093            let mut right_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1094            let mut right_count: u32 = 0;
1095            for split_idx in (0..(RT_SAH_BIN_COUNT - 1)).rev() {
1096                right_bounds.expand_box(bins[split_idx + 1].get_bounds());
1097                right_count += bins[split_idx + 1].get_count();
1098                let l_cnt: u32 = left_count[split_idx];
1099                if l_cnt == 0 || right_count == 0 {
1100                    continue;
1101                }
1102                let cost: f32 = 0.5
1103                    + ((left_area[split_idx] * (l_cnt as f32))
1104                        + (right_bounds.surface_area() * (right_count as f32)))
1105                        / parent_area;
1106                if cost < best_cost {
1107                    best_cost = cost;
1108                    best_axis = axis;
1109                    best_split_pos =
1110                        c_min + ((split_idx + 1) as f32) * (span / (RT_SAH_BIN_COUNT as f32));
1111                    found_sah = true;
1112                }
1113            }
1114        }
1115        let mut mid: usize = if found_sah && best_cost < leaf_cost {
1116            Self::partition_instances(
1117                instances,
1118                instance_order,
1119                start,
1120                end,
1121                best_axis,
1122                best_split_pos,
1123            )
1124        } else {
1125            let extent: Vec3 = centroid_bounds.get_max().sub(centroid_bounds.get_min());
1126            let fallback_axis: usize =
1127                if extent.get_x() >= extent.get_y() && extent.get_x() >= extent.get_z() {
1128                    0
1129                } else if extent.get_y() >= extent.get_z() {
1130                    1
1131                } else {
1132                    2
1133                };
1134            let split_mid: f32 = (vec3_axis(centroid_bounds.get_min(), fallback_axis)
1135                + vec3_axis(centroid_bounds.get_max(), fallback_axis))
1136                * 0.5;
1137            Self::partition_instances(
1138                instances,
1139                instance_order,
1140                start,
1141                end,
1142                fallback_axis,
1143                split_mid,
1144            )
1145        };
1146        if mid == start || mid == end {
1147            mid = start + count / 2;
1148        }
1149        let left_idx: u32 =
1150            Self::build_tlas_recursive(nodes, instances, instance_order, start, mid);
1151        let right_idx: u32 = Self::build_tlas_recursive(nodes, instances, instance_order, mid, end);
1152        if let Some(node_ref) = nodes.get_mut(node_idx as usize) {
1153            node_ref.set_left(left_idx);
1154            node_ref.set_right(right_idx);
1155            node_ref.set_instance_count(0);
1156        }
1157        node_idx
1158    }
1159
1160    /// Partitions `instance_order[start..end]` in place around `split_pos` along `axis`.
1161    ///
1162    /// # Arguments
1163    ///
1164    /// - `&[RtInstance]` - Stable instance array.
1165    /// - `&mut [u32]` - Mutable instance index indirection slice.
1166    /// - `usize` - Inclusive start index.
1167    /// - `usize` - Exclusive end index.
1168    /// - `usize` - Split axis (`0`, `1`, or `2`).
1169    /// - `f32` - Split coordinate along `axis`.
1170    ///
1171    /// # Returns
1172    ///
1173    /// - `usize` - Partition midpoint index.
1174    fn partition_instances(
1175        instances: &[RtInstance],
1176        instance_order: &mut [u32],
1177        start: usize,
1178        end: usize,
1179        axis: usize,
1180        split_pos: f32,
1181    ) -> usize {
1182        let mut left: usize = start;
1183        let mut right: usize = end;
1184        while left < right {
1185            let center: Vec3 = instances[instance_order[left] as usize]
1186                .get_world_bounds()
1187                .center();
1188            if vec3_axis(center, axis) < split_pos {
1189                left += 1;
1190            } else {
1191                right -= 1;
1192                instance_order.swap(left, right);
1193            }
1194        }
1195        left
1196    }
1197
1198    /// Intersects a single instanced BLAS and transforms the closest hit back into world space.
1199    ///
1200    /// # Arguments
1201    ///
1202    /// - `u32` - Instance index.
1203    /// - `RtInstance` - Instance descriptor.
1204    /// - `&[Blas3D]` - Scene BLAS table.
1205    /// - `&Ray3D` - World-space ray.
1206    /// - `f32` - Minimum accepted distance.
1207    /// - `f32` - Maximum accepted distance.
1208    ///
1209    /// # Returns
1210    ///
1211    /// - `Option<RtHit>` - World-space intersection if hit.
1212    fn intersect_instance(
1213        instance_id: u32,
1214        instance: RtInstance,
1215        blas_list: &[Blas3D],
1216        ray: &Ray3D,
1217        t_min: f32,
1218        t_max: f32,
1219    ) -> Option<RtHit> {
1220        if !instance.get_visible() {
1221            return None;
1222        }
1223        let blas: &Blas3D = blas_list.get(instance.get_blas_id() as usize)?;
1224        let inv: Mat4 = instance.get_inv_transform();
1225        let local_origin: Vec3 = inv.mul_point3(ray.get_origin());
1226        let local_dir: Vec3 = inv.mul_vec3(ray.get_direction());
1227        let local_inv_dir: Vec3 = Ray3D::safe_inv_vec(local_dir);
1228        let local_hit: RtLocalHit =
1229            blas.trace_closest_unnormalized(local_origin, local_dir, local_inv_dir, t_min, t_max)?;
1230        let normal_mat: [Vec3; 3] = instance.get_normal_matrix();
1231        let world_geom_n: Vec3 =
1232            Mat4::transform_normal_with_basis(local_hit.get_geometric_normal(), normal_mat);
1233        let world_shade_n: Vec3 =
1234            Mat4::transform_normal_with_basis(local_hit.get_shading_normal(), normal_mat);
1235        let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1236            orient_hit_normals(ray.get_direction(), world_geom_n, world_shade_n);
1237        let world_point: Vec3 = ray
1238            .get_origin()
1239            .add(ray.get_direction().scale(local_hit.get_distance()));
1240        Some(RtHit {
1241            distance: local_hit.get_distance(),
1242            point: world_point,
1243            geometric_normal: geom_n,
1244            shading_normal: shade_n,
1245            uv: local_hit.get_uv(),
1246            material_id: instance.get_material_id(),
1247            instance_id,
1248            primitive_index: local_hit.get_triangle_index(),
1249            front_face,
1250        })
1251    }
1252
1253    /// Traces a world-space ray through the TLAS and referenced `Blas3D` structures using zero-alloc iterative traversal.
1254    ///
1255    /// # Arguments
1256    ///
1257    /// - `&Self` - TLAS reference.
1258    /// - `&[Blas3D]` - Scene BLAS array indexed by `RtInstance::blas_id`.
1259    /// - `&Ray3D` - World-space normalized ray.
1260    /// - `f32` - Minimum accepted hit distance.
1261    /// - `f32` - Maximum accepted hit distance.
1262    ///
1263    /// # Returns
1264    ///
1265    /// - `Option<RtHit>` - Closest world-space hit across all visible instances.
1266    #[must_use]
1267    pub fn trace_closest(
1268        &self,
1269        blas_list: &[Blas3D],
1270        ray: &Ray3D,
1271        t_min: f32,
1272        t_max: f32,
1273    ) -> Option<RtHit> {
1274        let nodes: &[TlasNode3D] = self.get_nodes().as_slice();
1275        let instances: &[RtInstance] = self.get_instances().as_slice();
1276        let order: &[u32] = self.get_instance_order().as_slice();
1277        if nodes.is_empty() {
1278            return None;
1279        }
1280        let origin: Vec3 = ray.get_origin();
1281        let inv_dir: Vec3 = ray.get_inv_direction();
1282        if !nodes[0]
1283            .get_bounds()
1284            .intersect_ray_near(origin, inv_dir, t_min, t_max)
1285            .is_finite()
1286        {
1287            return None;
1288        }
1289        let mut stack: [u32; RT_BVH_STACK_CAPACITY] = [0; RT_BVH_STACK_CAPACITY];
1290        let mut stack_len: usize = 1;
1291        let mut best_t: f32 = t_max;
1292        let mut best_hit: Option<RtHit> = None;
1293        while stack_len > 0 {
1294            stack_len -= 1;
1295            let node: TlasNode3D = nodes[stack[stack_len] as usize];
1296            let inst_count: u32 = node.get_instance_count();
1297            if inst_count > 0 {
1298                let first: usize = node.get_first_instance() as usize;
1299                let last: usize = first + (inst_count as usize);
1300                for &inst_id in &order[first..last] {
1301                    let inst: RtInstance = instances[inst_id as usize];
1302                    if !inst
1303                        .get_world_bounds()
1304                        .intersect_ray_near(origin, inv_dir, t_min, best_t)
1305                        .is_finite()
1306                    {
1307                        continue;
1308                    }
1309                    if let Some(hit) =
1310                        Self::intersect_instance(inst_id, inst, blas_list, ray, t_min, best_t)
1311                    {
1312                        best_t = hit.get_distance();
1313                        best_hit = Some(hit);
1314                    }
1315                }
1316            } else {
1317                let left_idx: u32 = node.get_left();
1318                let right_idx: u32 = node.get_right();
1319                let t_left: f32 = nodes[left_idx as usize]
1320                    .get_bounds()
1321                    .intersect_ray_near(origin, inv_dir, t_min, best_t);
1322                let t_right: f32 = nodes[right_idx as usize]
1323                    .get_bounds()
1324                    .intersect_ray_near(origin, inv_dir, t_min, best_t);
1325                let hit_left: bool = t_left.is_finite() && t_left <= best_t;
1326                let hit_right: bool = t_right.is_finite() && t_right <= best_t;
1327                if hit_left && hit_right {
1328                    let (near_idx, far_idx): (u32, u32) = if t_left <= t_right {
1329                        (left_idx, right_idx)
1330                    } else {
1331                        (right_idx, left_idx)
1332                    };
1333                    if stack_len + 2 <= RT_BVH_STACK_CAPACITY {
1334                        stack[stack_len] = far_idx;
1335                        stack[stack_len + 1] = near_idx;
1336                        stack_len += 2;
1337                    }
1338                } else if hit_left && stack_len < RT_BVH_STACK_CAPACITY {
1339                    stack[stack_len] = left_idx;
1340                    stack_len += 1;
1341                } else if hit_right && stack_len < RT_BVH_STACK_CAPACITY {
1342                    stack[stack_len] = right_idx;
1343                    stack_len += 1;
1344                }
1345            }
1346        }
1347        best_hit
1348    }
1349
1350    /// Tests whether a world-space shadow or occlusion ray hits any visible instance in `[t_min, t_max]` with early exit.
1351    ///
1352    /// # Arguments
1353    ///
1354    /// - `&Self` - TLAS reference.
1355    /// - `&[Blas3D]` - Scene BLAS table.
1356    /// - `&Ray3D` - World-space ray.
1357    /// - `f32` - Minimum accepted hit distance.
1358    /// - `f32` - Maximum accepted hit distance.
1359    ///
1360    /// # Returns
1361    ///
1362    /// - `bool` - `true` if any triangle in any visible instance occludes the ray.
1363    #[must_use]
1364    pub fn trace_any_hit(&self, blas_list: &[Blas3D], ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1365        let nodes: &[TlasNode3D] = self.get_nodes().as_slice();
1366        let instances: &[RtInstance] = self.get_instances().as_slice();
1367        let order: &[u32] = self.get_instance_order().as_slice();
1368        if nodes.is_empty() {
1369            return false;
1370        }
1371        let origin: Vec3 = ray.get_origin();
1372        let inv_dir: Vec3 = ray.get_inv_direction();
1373        if !nodes[0]
1374            .get_bounds()
1375            .intersect_ray_near(origin, inv_dir, t_min, t_max)
1376            .is_finite()
1377        {
1378            return false;
1379        }
1380        let mut stack: [u32; RT_BVH_STACK_CAPACITY] = [0; RT_BVH_STACK_CAPACITY];
1381        let mut stack_len: usize = 1;
1382        while stack_len > 0 {
1383            stack_len -= 1;
1384            let node: TlasNode3D = nodes[stack[stack_len] as usize];
1385            let inst_count: u32 = node.get_instance_count();
1386            if inst_count > 0 {
1387                let first: usize = node.get_first_instance() as usize;
1388                let last: usize = first + (inst_count as usize);
1389                for &inst_id in &order[first..last] {
1390                    let inst: RtInstance = instances[inst_id as usize];
1391                    if !inst.get_visible() {
1392                        continue;
1393                    }
1394                    if !inst
1395                        .get_world_bounds()
1396                        .intersect_ray_near(origin, inv_dir, t_min, t_max)
1397                        .is_finite()
1398                    {
1399                        continue;
1400                    }
1401                    if let Some(blas) = blas_list.get(inst.get_blas_id() as usize) {
1402                        let inv: Mat4 = inst.get_inv_transform();
1403                        let local_origin: Vec3 = inv.mul_point3(origin);
1404                        let local_dir: Vec3 = inv.mul_vec3(ray.get_direction());
1405                        let local_inv_dir: Vec3 = Ray3D::safe_inv_vec(local_dir);
1406                        if blas.trace_any_hit_unnormalized(
1407                            local_origin,
1408                            local_dir,
1409                            local_inv_dir,
1410                            t_min,
1411                            t_max,
1412                        ) {
1413                            return true;
1414                        }
1415                    }
1416                }
1417            } else {
1418                let left_idx: u32 = node.get_left();
1419                let right_idx: u32 = node.get_right();
1420                if nodes[left_idx as usize]
1421                    .get_bounds()
1422                    .intersect_ray_near(origin, inv_dir, t_min, t_max)
1423                    .is_finite()
1424                    && stack_len < RT_BVH_STACK_CAPACITY
1425                {
1426                    stack[stack_len] = left_idx;
1427                    stack_len += 1;
1428                }
1429                if nodes[right_idx as usize]
1430                    .get_bounds()
1431                    .intersect_ray_near(origin, inv_dir, t_min, t_max)
1432                    .is_finite()
1433                    && stack_len < RT_BVH_STACK_CAPACITY
1434                {
1435                    stack[stack_len] = right_idx;
1436                    stack_len += 1;
1437                }
1438            }
1439        }
1440        false
1441    }
1442
1443    /// Reference O(N * M) brute-force intersection scanning every visible instance and triangle for exact TLAS/BLAS parity testing.
1444    ///
1445    /// # Arguments
1446    ///
1447    /// - `&Self` - TLAS reference.
1448    /// - `&[Blas3D]` - Scene BLAS table.
1449    /// - `&Ray3D` - World-space ray.
1450    /// - `f32` - Minimum accepted hit distance.
1451    /// - `f32` - Maximum accepted hit distance.
1452    ///
1453    /// # Returns
1454    ///
1455    /// - `Option<RtHit>` - Exact closest world-space hit.
1456    #[must_use]
1457    pub fn trace_closest_brute_force(
1458        &self,
1459        blas_list: &[Blas3D],
1460        ray: &Ray3D,
1461        t_min: f32,
1462        t_max: f32,
1463    ) -> Option<RtHit> {
1464        let mut best_t: f32 = t_max;
1465        let mut best_hit: Option<RtHit> = None;
1466        for (inst_idx, &inst) in self.get_instances().iter().enumerate() {
1467            if !inst.get_visible() {
1468                continue;
1469            }
1470            let blas: &Blas3D = match blas_list.get(inst.get_blas_id() as usize) {
1471                Some(b) => b,
1472                None => continue,
1473            };
1474            let inv: Mat4 = inst.get_inv_transform();
1475            let local_origin: Vec3 = inv.mul_point3(ray.get_origin());
1476            let local_dir: Vec3 = inv.mul_vec3(ray.get_direction());
1477            if let Some(local_hit) =
1478                blas.trace_closest_brute_force_unnormalized(local_origin, local_dir, t_min, best_t)
1479            {
1480                let normal_mat: [Vec3; 3] = inst.get_normal_matrix();
1481                let world_geom_n: Vec3 =
1482                    Mat4::transform_normal_with_basis(local_hit.get_geometric_normal(), normal_mat);
1483                let world_shade_n: Vec3 =
1484                    Mat4::transform_normal_with_basis(local_hit.get_shading_normal(), normal_mat);
1485                let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1486                    orient_hit_normals(ray.get_direction(), world_geom_n, world_shade_n);
1487                let world_point: Vec3 = ray
1488                    .get_origin()
1489                    .add(ray.get_direction().scale(local_hit.get_distance()));
1490                best_t = local_hit.get_distance();
1491                best_hit = Some(RtHit {
1492                    distance: local_hit.get_distance(),
1493                    point: world_point,
1494                    geometric_normal: geom_n,
1495                    shading_normal: shade_n,
1496                    uv: local_hit.get_uv(),
1497                    material_id: inst.get_material_id(),
1498                    instance_id: inst_idx as u32,
1499                    primitive_index: local_hit.get_triangle_index(),
1500                    front_face,
1501                });
1502            }
1503        }
1504        best_hit
1505    }
1506}
1507
1508/// Analytic ray-primitive intersection and bounding box evaluation for `RtPrimitive`.
1509impl RtPrimitive {
1510    /// Intersects a world-space ray against this analytic primitive within `[t_min, t_max]`.
1511    ///
1512    /// # Arguments
1513    ///
1514    /// - `&Self` - Primitive reference.
1515    /// - `&Ray3D` - World-space normalized ray.
1516    /// - `f32` - Minimum accepted hit distance.
1517    /// - `f32` - Maximum accepted hit distance.
1518    /// - `u32` - Primitive table index recorded on the hit.
1519    ///
1520    /// # Returns
1521    ///
1522    /// - `Option<RtHit>` - Analytic intersection hit if any.
1523    #[must_use]
1524    pub fn intersect(
1525        &self,
1526        ray: &Ray3D,
1527        t_min: f32,
1528        t_max: f32,
1529        primitive_index: u32,
1530    ) -> Option<RtHit> {
1531        let origin: Vec3 = ray.get_origin();
1532        let dir: Vec3 = ray.get_direction();
1533        let mat_id: u32 = self.get_material_id();
1534        match self.get_shape() {
1535            RtPrimitiveShape::Sphere { center, radius } => {
1536                let r: f32 = radius.abs();
1537                if r <= RT_EPSILON {
1538                    return None;
1539                }
1540                let oc: Vec3 = origin.sub(center);
1541                let b: f32 = oc.dot(dir);
1542                let c: f32 = oc.dot(oc) - r * r;
1543                let disc: f32 = b * b - c;
1544                if disc < 0.0 {
1545                    return None;
1546                }
1547                let sqrt_d: f32 = disc.sqrt();
1548                let mut root: f32 = -b - sqrt_d;
1549                if root < t_min || root > t_max {
1550                    root = -b + sqrt_d;
1551                    if root < t_min || root > t_max {
1552                        return None;
1553                    }
1554                }
1555                let point: Vec3 = origin.add(dir.scale(root));
1556                let outward: Vec3 = point.sub(center).scale(1.0 / r).normalize();
1557                let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1558                    orient_hit_normals(dir, outward, outward);
1559                let u: f32 = 0.5 + outward.get_z().atan2(outward.get_x()) / TAU;
1560                let v: f32 = 0.5 - outward.get_y().clamp(-1.0, 1.0).asin() / PI;
1561                Some(RtHit {
1562                    distance: root,
1563                    point,
1564                    geometric_normal: geom_n,
1565                    shading_normal: shade_n,
1566                    uv: Vec2::new(u, v),
1567                    material_id: mat_id,
1568                    instance_id: RT_PRIMITIVE_INSTANCE_ID,
1569                    primitive_index,
1570                    front_face,
1571                })
1572            }
1573            RtPrimitiveShape::Plane {
1574                point: plane_pt,
1575                normal,
1576            } => {
1577                let n: Vec3 = normal.normalize();
1578                let denom: f32 = n.dot(dir);
1579                if denom.abs() < RT_EPSILON {
1580                    return None;
1581                }
1582                let dist: f32 = plane_pt.sub(origin).dot(n) / denom;
1583                if !dist.is_finite() {
1584                    return None;
1585                }
1586                if dist < t_min || dist > t_max {
1587                    return None;
1588                }
1589                let hit_pt: Vec3 = origin.add(dir.scale(dist));
1590                let (tangent, bitangent): (Vec3, Vec3) = build_orthonormal_basis(n);
1591                let rel: Vec3 = hit_pt.sub(plane_pt);
1592                let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1593                    orient_hit_normals(dir, n, n);
1594                Some(RtHit {
1595                    distance: dist,
1596                    point: hit_pt,
1597                    geometric_normal: geom_n,
1598                    shading_normal: shade_n,
1599                    uv: Vec2::new(rel.dot(tangent), rel.dot(bitangent)),
1600                    material_id: mat_id,
1601                    instance_id: RT_PRIMITIVE_INSTANCE_ID,
1602                    primitive_index,
1603                    front_face,
1604                })
1605            }
1606            RtPrimitiveShape::Box { min, max } => {
1607                let inv: Vec3 = ray.get_inv_direction();
1608                let tx1: f32 = (min.get_x() - origin.get_x()) * inv.get_x();
1609                let tx2: f32 = (max.get_x() - origin.get_x()) * inv.get_x();
1610                let tx_min: f32 = tx1.min(tx2);
1611                let tx_max: f32 = tx1.max(tx2);
1612                let ty1: f32 = (min.get_y() - origin.get_y()) * inv.get_y();
1613                let ty2: f32 = (max.get_y() - origin.get_y()) * inv.get_y();
1614                let ty_min: f32 = ty1.min(ty2);
1615                let ty_max: f32 = ty1.max(ty2);
1616                let tz1: f32 = (min.get_z() - origin.get_z()) * inv.get_z();
1617                let tz2: f32 = (max.get_z() - origin.get_z()) * inv.get_z();
1618                let tz_min: f32 = tz1.min(tz2);
1619                let tz_max: f32 = tz1.max(tz2);
1620                let t_enter: f32 = tx_min.max(ty_min).max(tz_min);
1621                let t_exit: f32 = tx_max.min(ty_max).min(tz_max);
1622                if t_exit < t_enter {
1623                    return None;
1624                }
1625                if t_exit < t_min || t_enter > t_max {
1626                    return None;
1627                }
1628                let (hit_t, is_enter): (f32, bool) = if t_enter >= t_min {
1629                    (t_enter, true)
1630                } else if t_exit <= t_max {
1631                    (t_exit, false)
1632                } else {
1633                    return None;
1634                };
1635                let hit_pt: Vec3 = origin.add(dir.scale(hit_t));
1636                let size: Vec3 = max.sub(min);
1637                let sx: f32 = size.get_x().max(RT_EPSILON);
1638                let sy: f32 = size.get_y().max(RT_EPSILON);
1639                let sz: f32 = size.get_z().max(RT_EPSILON);
1640                let outward: Vec3 = if is_enter {
1641                    if t_enter == tx_min {
1642                        Vec3::new(if dir.get_x() > 0.0 { -1.0 } else { 1.0 }, 0.0, 0.0)
1643                    } else if t_enter == ty_min {
1644                        Vec3::new(0.0, if dir.get_y() > 0.0 { -1.0 } else { 1.0 }, 0.0)
1645                    } else {
1646                        Vec3::new(0.0, 0.0, if dir.get_z() > 0.0 { -1.0 } else { 1.0 })
1647                    }
1648                } else if t_exit == tx_max {
1649                    Vec3::new(if dir.get_x() > 0.0 { 1.0 } else { -1.0 }, 0.0, 0.0)
1650                } else if t_exit == ty_max {
1651                    Vec3::new(0.0, if dir.get_y() > 0.0 { 1.0 } else { -1.0 }, 0.0)
1652                } else {
1653                    Vec3::new(0.0, 0.0, if dir.get_z() > 0.0 { 1.0 } else { -1.0 })
1654                };
1655                let (u, v): (f32, f32) = if outward.get_x().abs() > 0.5 {
1656                    (
1657                        (hit_pt.get_z() - min.get_z()) / sz,
1658                        (hit_pt.get_y() - min.get_y()) / sy,
1659                    )
1660                } else if outward.get_y().abs() > 0.5 {
1661                    (
1662                        (hit_pt.get_x() - min.get_x()) / sx,
1663                        (hit_pt.get_z() - min.get_z()) / sz,
1664                    )
1665                } else {
1666                    (
1667                        (hit_pt.get_x() - min.get_x()) / sx,
1668                        (hit_pt.get_y() - min.get_y()) / sy,
1669                    )
1670                };
1671                let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1672                    orient_hit_normals(dir, outward, outward);
1673                Some(RtHit {
1674                    distance: hit_t,
1675                    point: hit_pt,
1676                    geometric_normal: geom_n,
1677                    shading_normal: shade_n,
1678                    uv: Vec2::new(u.clamp(0.0, 1.0), v.clamp(0.0, 1.0)),
1679                    material_id: mat_id,
1680                    instance_id: RT_PRIMITIVE_INSTANCE_ID,
1681                    primitive_index,
1682                    front_face,
1683                })
1684            }
1685            RtPrimitiveShape::Disk {
1686                center,
1687                normal,
1688                radius,
1689            } => {
1690                let r: f32 = radius.abs();
1691                if r <= RT_EPSILON {
1692                    return None;
1693                }
1694                let n: Vec3 = normal.normalize();
1695                let denom: f32 = n.dot(dir);
1696                if denom.abs() < RT_EPSILON {
1697                    return None;
1698                }
1699                let dist: f32 = center.sub(origin).dot(n) / denom;
1700                if !dist.is_finite() {
1701                    return None;
1702                }
1703                if dist < t_min || dist > t_max {
1704                    return None;
1705                }
1706                let hit_pt: Vec3 = origin.add(dir.scale(dist));
1707                let offset: Vec3 = hit_pt.sub(center);
1708                if offset.length_sq() > r * r {
1709                    return None;
1710                }
1711                let (tangent, bitangent): (Vec3, Vec3) = build_orthonormal_basis(n);
1712                let u: f32 = (offset.dot(tangent) / (2.0 * r) + 0.5).clamp(0.0, 1.0);
1713                let v: f32 = (offset.dot(bitangent) / (2.0 * r) + 0.5).clamp(0.0, 1.0);
1714                let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1715                    orient_hit_normals(dir, n, n);
1716                Some(RtHit {
1717                    distance: dist,
1718                    point: hit_pt,
1719                    geometric_normal: geom_n,
1720                    shading_normal: shade_n,
1721                    uv: Vec2::new(u, v),
1722                    material_id: mat_id,
1723                    instance_id: RT_PRIMITIVE_INSTANCE_ID,
1724                    primitive_index,
1725                    front_face,
1726                })
1727            }
1728            RtPrimitiveShape::Quad {
1729                corner,
1730                edge_u,
1731                edge_v,
1732            } => {
1733                let cross_uv: Vec3 = edge_u.cross(edge_v);
1734                let area_sq: f32 = cross_uv.length_sq();
1735                if area_sq <= RT_EPSILON * RT_EPSILON {
1736                    return None;
1737                }
1738                let n: Vec3 = cross_uv.scale(1.0 / area_sq.sqrt());
1739                let denom: f32 = n.dot(dir);
1740                if denom.abs() < RT_EPSILON {
1741                    return None;
1742                }
1743                let dist: f32 = corner.sub(origin).dot(n) / denom;
1744                if !dist.is_finite() {
1745                    return None;
1746                }
1747                if dist < t_min || dist > t_max {
1748                    return None;
1749                }
1750                let hit_pt: Vec3 = origin.add(dir.scale(dist));
1751                let rel: Vec3 = hit_pt.sub(corner);
1752                let w_vec: Vec3 = cross_uv.scale(1.0 / area_sq);
1753                let alpha: f32 = w_vec.dot(rel.cross(edge_v));
1754                let beta: f32 = w_vec.dot(edge_u.cross(rel));
1755                if !(0.0..=1.0).contains(&alpha) || !(0.0..=1.0).contains(&beta) {
1756                    return None;
1757                }
1758                let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1759                    orient_hit_normals(dir, n, n);
1760                Some(RtHit {
1761                    distance: dist,
1762                    point: hit_pt,
1763                    geometric_normal: geom_n,
1764                    shading_normal: shade_n,
1765                    uv: Vec2::new(alpha, beta),
1766                    material_id: mat_id,
1767                    instance_id: RT_PRIMITIVE_INSTANCE_ID,
1768                    primitive_index,
1769                    front_face,
1770                })
1771            }
1772            RtPrimitiveShape::Cylinder {
1773                center,
1774                radius,
1775                half_height,
1776                capped,
1777            } => {
1778                let r: f32 = radius.abs();
1779                let hh: f32 = half_height.abs();
1780                if r <= RT_EPSILON || hh <= RT_EPSILON {
1781                    return None;
1782                }
1783                let rel_o: Vec3 = origin.sub(center);
1784                let ox: f32 = rel_o.get_x();
1785                let oy: f32 = rel_o.get_y();
1786                let oz: f32 = rel_o.get_z();
1787                let dx: f32 = dir.get_x();
1788                let dy: f32 = dir.get_y();
1789                let dz: f32 = dir.get_z();
1790                let mut best_t: f32 = t_max;
1791                let mut best_outward: Vec3 = Vec3::new(0.0, 1.0, 0.0);
1792                let mut best_uv: Vec2 = Vec2::zero();
1793                let mut found: bool = false;
1794                let a: f32 = dx * dx + dz * dz;
1795                if a > RT_EPSILON {
1796                    let half_b: f32 = ox * dx + oz * dz;
1797                    let c: f32 = ox * ox + oz * oz - r * r;
1798                    let disc: f32 = half_b * half_b - a * c;
1799                    if disc >= 0.0 {
1800                        let sqrt_d: f32 = disc.sqrt();
1801                        let roots: [f32; 2] = [(-half_b - sqrt_d) / a, (-half_b + sqrt_d) / a];
1802                        for root in roots {
1803                            if root >= t_min && root < best_t {
1804                                let y_local: f32 = oy + root * dy;
1805                                if y_local >= -hh && y_local <= hh {
1806                                    let hx: f32 = ox + root * dx;
1807                                    let hz: f32 = oz + root * dz;
1808                                    best_t = root;
1809                                    best_outward = Vec3::new(hx / r, 0.0, hz / r).normalize();
1810                                    let u: f32 = 0.5 + hz.atan2(hx) / TAU;
1811                                    let v: f32 = ((y_local + hh) / (2.0 * hh)).clamp(0.0, 1.0);
1812                                    best_uv = Vec2::new(u, v);
1813                                    found = true;
1814                                }
1815                            }
1816                        }
1817                    }
1818                }
1819                if capped && dy.abs() > RT_EPSILON {
1820                    let cap_planes: [(f32, f32); 2] = [(hh, 1.0), (-hh, -1.0)];
1821                    for (cap_y, sign_y) in cap_planes {
1822                        let cap_t: f32 = (cap_y - oy) / dy;
1823                        if cap_t >= t_min && cap_t < best_t {
1824                            let hx: f32 = ox + cap_t * dx;
1825                            let hz: f32 = oz + cap_t * dz;
1826                            if hx * hx + hz * hz <= r * r {
1827                                best_t = cap_t;
1828                                best_outward = Vec3::new(0.0, sign_y, 0.0);
1829                                best_uv = Vec2::new(
1830                                    (hx / (2.0 * r) + 0.5).clamp(0.0, 1.0),
1831                                    (hz / (2.0 * r) + 0.5).clamp(0.0, 1.0),
1832                                );
1833                                found = true;
1834                            }
1835                        }
1836                    }
1837                }
1838                if !found {
1839                    return None;
1840                }
1841                let hit_pt: Vec3 = origin.add(dir.scale(best_t));
1842                let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
1843                    orient_hit_normals(dir, best_outward, best_outward);
1844                Some(RtHit {
1845                    distance: best_t,
1846                    point: hit_pt,
1847                    geometric_normal: geom_n,
1848                    shading_normal: shade_n,
1849                    uv: best_uv,
1850                    material_id: mat_id,
1851                    instance_id: RT_PRIMITIVE_INSTANCE_ID,
1852                    primitive_index,
1853                    front_face,
1854                })
1855            }
1856        }
1857    }
1858
1859    /// Tests whether a world-space ray intersects this analytic primitive within `[t_min, t_max]`.
1860    ///
1861    /// # Arguments
1862    ///
1863    /// - `&Self` - Primitive reference.
1864    /// - `&Ray3D` - World-space ray.
1865    /// - `f32` - Minimum accepted distance.
1866    /// - `f32` - Maximum accepted distance.
1867    ///
1868    /// # Returns
1869    ///
1870    /// - `bool` - `true` when the primitive occludes the ray interval.
1871    #[must_use]
1872    pub fn any_hit(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1873        self.intersect(ray, t_min, t_max, 0).is_some()
1874    }
1875
1876    /// Computes a conservative world-space bounding box enclosing this analytic primitive.
1877    ///
1878    /// # Arguments
1879    ///
1880    /// - `&Self` - Primitive reference.
1881    ///
1882    /// # Returns
1883    ///
1884    /// - `AxisAlignedBox3D` - Enclosing world-space bounding box.
1885    #[must_use]
1886    pub fn bounds(&self) -> AxisAlignedBox3D {
1887        match self.get_shape() {
1888            RtPrimitiveShape::Sphere { center, radius } => {
1889                let r: Vec3 = Vec3::splat(radius.abs());
1890                AxisAlignedBox3D::new(center.sub(r), center.add(r))
1891            }
1892            RtPrimitiveShape::Plane { .. } => {
1893                AxisAlignedBox3D::new(Vec3::splat(-1e5), Vec3::splat(1e5))
1894            }
1895            RtPrimitiveShape::Box { min, max } => AxisAlignedBox3D::new(min.min(max), min.max(max)),
1896            RtPrimitiveShape::Disk { center, radius, .. } => {
1897                let r: Vec3 = Vec3::splat(radius.abs());
1898                AxisAlignedBox3D::new(center.sub(r), center.add(r))
1899            }
1900            RtPrimitiveShape::Quad {
1901                corner,
1902                edge_u,
1903                edge_v,
1904            } => {
1905                let mut bbox: AxisAlignedBox3D = AxisAlignedBox3D::empty();
1906                bbox.expand_point(corner);
1907                bbox.expand_point(corner.add(edge_u));
1908                bbox.expand_point(corner.add(edge_v));
1909                bbox.expand_point(corner.add(edge_u).add(edge_v));
1910                bbox
1911            }
1912            RtPrimitiveShape::Cylinder {
1913                center,
1914                radius,
1915                half_height,
1916                ..
1917            } => {
1918                let r: f32 = radius.abs();
1919                let hh: f32 = half_height.abs();
1920                let ext: Vec3 = Vec3::new(r, hh, r);
1921                AxisAlignedBox3D::new(center.sub(ext), center.add(ext))
1922            }
1923        }
1924    }
1925}
1926
1927/// Default empty SDF sphere tracer constructor for `SdfSphereTracer`.
1928impl Default for SdfSphereTracer {
1929    /// Creates an empty `SdfSphereTracer` with empty bounds and default marching parameters.
1930    ///
1931    /// # Returns
1932    ///
1933    /// - `Self` - Empty sphere tracer.
1934    fn default() -> Self {
1935        Self::new(0, AxisAlignedBox3D::empty())
1936    }
1937}
1938
1939/// Lipschitz sphere-tracing, CSG evaluation, and central-difference normal estimation for `SdfSphereTracer`.
1940impl SdfSphereTracer {
1941    /// Creates an empty `SdfSphereTracer` bound to `material_id` and culling `bounds`.
1942    ///
1943    /// # Arguments
1944    ///
1945    /// - `u32` - Material index assigned to hits on this implicit surface.
1946    /// - `AxisAlignedBox3D` - Conservative world-space bounding box enclosing the SDF.
1947    ///
1948    /// # Returns
1949    ///
1950    /// - `Self` - Configured sphere tracer ready for SDF ops.
1951    #[must_use]
1952    pub fn new(material_id: u32, bounds: AxisAlignedBox3D) -> Self {
1953        Self {
1954            ops: Vec::new(),
1955            root_index: 0,
1956            material_id,
1957            bounds,
1958            max_steps: RT_SDF_DEFAULT_MAX_STEPS,
1959            hit_epsilon: RT_SDF_DEFAULT_EPSILON,
1960            normal_epsilon: RT_SDF_NORMAL_EPSILON,
1961            max_distance: RT_SDF_DEFAULT_MAX_DISTANCE,
1962            lipschitz_factor: 1.0,
1963        }
1964    }
1965
1966    /// Appends an `RtSdfOp` node, updates `root_index` to the new node, and returns its node index.
1967    ///
1968    /// # Arguments
1969    ///
1970    /// - `&Self` - Mutable sphere tracer reference.
1971    /// - `RtSdfOp` - SDF primitive or CSG combinator node.
1972    ///
1973    /// # Returns
1974    ///
1975    /// - `u32` - Node index inside `ops`.
1976    pub fn push_op(&mut self, op: RtSdfOp) -> u32 {
1977        let idx: u32 = self.get_ops().len() as u32;
1978        self.get_mut_ops().push(op);
1979        self.set_root_index(idx);
1980        idx
1981    }
1982
1983    /// Evaluates the signed distance field at `point` using a zero-allocation iterative fixed-stack evaluator.
1984    ///
1985    /// # Arguments
1986    ///
1987    /// - `&Self` - Sphere tracer reference.
1988    /// - `Vec3` - Query position in world space.
1989    ///
1990    /// # Returns
1991    ///
1992    /// - `f32` - Signed distance (`< 0` inside, `0` on surface, `> 0` outside).
1993    #[must_use]
1994    pub fn evaluate_distance(&self, point: Vec3) -> f32 {
1995        let ops: &[RtSdfOp] = self.get_ops().as_slice();
1996        let root: usize = self.get_root_index() as usize;
1997        if root >= ops.len() {
1998            return f32::INFINITY;
1999        }
2000        let mut visit_stack: [(u32, bool); RT_SDF_EVAL_STACK_CAPACITY] =
2001            [(0, false); RT_SDF_EVAL_STACK_CAPACITY];
2002        let mut visit_len: usize = 1;
2003        visit_stack[0] = (root as u32, false);
2004        let mut val_stack: [f32; RT_SDF_EVAL_STACK_CAPACITY] = [0.0; RT_SDF_EVAL_STACK_CAPACITY];
2005        let mut val_len: usize = 0;
2006        while visit_len > 0 {
2007            visit_len -= 1;
2008            let (node_idx, expanded): (u32, bool) = visit_stack[visit_len];
2009            let op: RtSdfOp = match ops.get(node_idx as usize) {
2010                Some(&found) => found,
2011                None => return f32::INFINITY,
2012            };
2013            match op {
2014                RtSdfOp::Sphere { center, radius } => {
2015                    if val_len < RT_SDF_EVAL_STACK_CAPACITY {
2016                        val_stack[val_len] = point.sub(center).length() - radius.abs();
2017                        val_len += 1;
2018                    }
2019                }
2020                RtSdfOp::Box {
2021                    center,
2022                    half_extents,
2023                    rounding,
2024                } => {
2025                    let rel: Vec3 = point.sub(center);
2026                    let qx: f32 = rel.get_x().abs() - half_extents.get_x().abs();
2027                    let qy: f32 = rel.get_y().abs() - half_extents.get_y().abs();
2028                    let qz: f32 = rel.get_z().abs() - half_extents.get_z().abs();
2029                    let out_len: f32 = Vec3::new(qx.max(0.0), qy.max(0.0), qz.max(0.0)).length();
2030                    let in_dist: f32 = qx.max(qy.max(qz)).min(0.0);
2031                    if val_len < RT_SDF_EVAL_STACK_CAPACITY {
2032                        val_stack[val_len] = out_len + in_dist - rounding.max(0.0);
2033                        val_len += 1;
2034                    }
2035                }
2036                RtSdfOp::Torus {
2037                    center,
2038                    major_radius,
2039                    minor_radius,
2040                } => {
2041                    let rel: Vec3 = point.sub(center);
2042                    let qx: f32 = (rel.get_x() * rel.get_x() + rel.get_z() * rel.get_z()).sqrt()
2043                        - major_radius.abs();
2044                    let qy: f32 = rel.get_y();
2045                    if val_len < RT_SDF_EVAL_STACK_CAPACITY {
2046                        val_stack[val_len] = (qx * qx + qy * qy).sqrt() - minor_radius.abs();
2047                        val_len += 1;
2048                    }
2049                }
2050                RtSdfOp::Capsule { start, end, radius } => {
2051                    let pa: Vec3 = point.sub(start);
2052                    let ba: Vec3 = end.sub(start);
2053                    let denom: f32 = ba.dot(ba).max(RT_EPSILON);
2054                    let h: f32 = (pa.dot(ba) / denom).clamp(0.0, 1.0);
2055                    if val_len < RT_SDF_EVAL_STACK_CAPACITY {
2056                        val_stack[val_len] = pa.sub(ba.scale(h)).length() - radius.abs();
2057                        val_len += 1;
2058                    }
2059                }
2060                RtSdfOp::Union { left, right }
2061                | RtSdfOp::Subtract {
2062                    base: left,
2063                    cutout: right,
2064                }
2065                | RtSdfOp::Intersect { left, right }
2066                | RtSdfOp::SmoothUnion { left, right, .. }
2067                | RtSdfOp::SmoothSubtract {
2068                    base: left,
2069                    cutout: right,
2070                    ..
2071                } => {
2072                    if !expanded {
2073                        if visit_len + 3 <= RT_SDF_EVAL_STACK_CAPACITY {
2074                            visit_stack[visit_len] = (node_idx, true);
2075                            visit_stack[visit_len + 1] = (right, false);
2076                            visit_stack[visit_len + 2] = (left, false);
2077                            visit_len += 3;
2078                        }
2079                    } else if val_len >= 2 {
2080                        let rhs_val: f32 = val_stack[val_len - 1];
2081                        let lhs_val: f32 = val_stack[val_len - 2];
2082                        val_len -= 1;
2083                        let combined: f32 = match op {
2084                            RtSdfOp::Union { .. } => lhs_val.min(rhs_val),
2085                            RtSdfOp::Subtract { .. } => lhs_val.max(-rhs_val),
2086                            RtSdfOp::Intersect { .. } => lhs_val.max(rhs_val),
2087                            RtSdfOp::SmoothUnion { smoothness, .. } => {
2088                                sdf_smooth_min(lhs_val, rhs_val, smoothness)
2089                            }
2090                            RtSdfOp::SmoothSubtract { smoothness, .. } => {
2091                                sdf_smooth_subtract(lhs_val, rhs_val, smoothness)
2092                            }
2093                            _ => lhs_val,
2094                        };
2095                        val_stack[val_len - 1] = combined;
2096                    }
2097                }
2098            }
2099        }
2100        if val_len > 0 {
2101            val_stack[val_len - 1]
2102        } else {
2103            f32::INFINITY
2104        }
2105    }
2106
2107    /// Computes the unit surface normal at `point` using a 4-sample tetrahedral central-difference gradient.
2108    ///
2109    /// # Arguments
2110    ///
2111    /// - `&Self` - Sphere tracer reference.
2112    /// - `Vec3` - Surface point in world space.
2113    ///
2114    /// # Returns
2115    ///
2116    /// - `Vec3` - Outward unit normal vector.
2117    #[must_use]
2118    pub fn evaluate_normal(&self, point: Vec3) -> Vec3 {
2119        let eps: f32 = self.get_normal_epsilon().max(1e-5);
2120        let k0: Vec3 = Vec3::new(1.0, -1.0, -1.0);
2121        let k1: Vec3 = Vec3::new(-1.0, -1.0, 1.0);
2122        let k2: Vec3 = Vec3::new(-1.0, 1.0, -1.0);
2123        let k3: Vec3 = Vec3::new(1.0, 1.0, 1.0);
2124        let d0: f32 = self.evaluate_distance(point.add(k0.scale(eps)));
2125        let d1: f32 = self.evaluate_distance(point.add(k1.scale(eps)));
2126        let d2: f32 = self.evaluate_distance(point.add(k2.scale(eps)));
2127        let d3: f32 = self.evaluate_distance(point.add(k3.scale(eps)));
2128        k0.scale(d0)
2129            .add(k1.scale(d1))
2130            .add(k2.scale(d2))
2131            .add(k3.scale(d3))
2132            .normalize()
2133    }
2134
2135    /// Sphere-traces a world-space ray against this implicit SDF volume within `[t_min, t_max]`.
2136    ///
2137    /// # Arguments
2138    ///
2139    /// - `&Self` - Sphere tracer reference.
2140    /// - `&Ray3D` - World-space normalized ray.
2141    /// - `f32` - Minimum accepted hit distance.
2142    /// - `f32` - Maximum accepted hit distance.
2143    /// - `u32` - SDF primitive table index.
2144    ///
2145    /// # Returns
2146    ///
2147    /// - `Option<RtHit>` - Surface hit with analytic tetrahedral normal if intersected.
2148    #[must_use]
2149    pub fn trace(
2150        &self,
2151        ray: &Ray3D,
2152        t_min: f32,
2153        t_max: f32,
2154        primitive_index: u32,
2155    ) -> Option<RtHit> {
2156        if self.get_ops().is_empty() {
2157            return None;
2158        }
2159        let bounds: AxisAlignedBox3D = self.get_bounds();
2160        let origin: Vec3 = ray.get_origin();
2161        let dir: Vec3 = ray.get_direction();
2162        let inv_dir: Vec3 = ray.get_inv_direction();
2163        let tx1: f32 = (bounds.get_min().get_x() - origin.get_x()) * inv_dir.get_x();
2164        let tx2: f32 = (bounds.get_max().get_x() - origin.get_x()) * inv_dir.get_x();
2165        let ty1: f32 = (bounds.get_min().get_y() - origin.get_y()) * inv_dir.get_y();
2166        let ty2: f32 = (bounds.get_max().get_y() - origin.get_y()) * inv_dir.get_y();
2167        let tz1: f32 = (bounds.get_min().get_z() - origin.get_z()) * inv_dir.get_z();
2168        let tz2: f32 = (bounds.get_max().get_z() - origin.get_z()) * inv_dir.get_z();
2169        let march_start: f32 = t_min.max(tx1.min(tx2).max(ty1.min(ty2)).max(tz1.min(tz2)));
2170        let march_end: f32 = t_max
2171            .min(self.get_max_distance())
2172            .min(tx1.max(tx2).min(ty1.max(ty2)).min(tz1.max(tz2)));
2173        if march_end < march_start {
2174            return None;
2175        }
2176        let max_steps: u32 = self.get_max_steps().max(1);
2177        let hit_eps: f32 = self.get_hit_epsilon().max(1e-6);
2178        let lip: f32 = self.get_lipschitz_factor().clamp(0.1, 1.0);
2179        let mut t: f32 = march_start;
2180        for _ in 0..max_steps {
2181            if t > march_end {
2182                break;
2183            }
2184            let pos: Vec3 = origin.add(dir.scale(t));
2185            let signed_dist: f32 = self.evaluate_distance(pos);
2186            let abs_dist: f32 = signed_dist.abs();
2187            if abs_dist <= hit_eps {
2188                let outward: Vec3 = self.evaluate_normal(pos);
2189                let (geom_n, shade_n, front_face): (Vec3, Vec3, bool) =
2190                    orient_hit_normals(dir, outward, outward);
2191                let rel: Vec3 = pos.sub(bounds.get_min());
2192                let ext: Vec3 = bounds.get_max().sub(bounds.get_min());
2193                let uv: Vec2 = Vec2::new(
2194                    (rel.get_x() / ext.get_x().max(RT_EPSILON)).clamp(0.0, 1.0),
2195                    (rel.get_z() / ext.get_z().max(RT_EPSILON)).clamp(0.0, 1.0),
2196                );
2197                return Some(RtHit {
2198                    distance: t,
2199                    point: pos,
2200                    geometric_normal: geom_n,
2201                    shading_normal: shade_n,
2202                    uv,
2203                    material_id: self.get_material_id(),
2204                    instance_id: RT_PRIMITIVE_INSTANCE_ID,
2205                    primitive_index,
2206                    front_face,
2207                });
2208            }
2209            t += abs_dist * lip;
2210        }
2211        None
2212    }
2213
2214    /// Tests whether a world-space ray hits this implicit SDF surface within `[t_min, t_max]`.
2215    ///
2216    /// # Arguments
2217    ///
2218    /// - `&Self` - Sphere tracer reference.
2219    /// - `&Ray3D` - World-space normalized ray.
2220    /// - `f32` - Minimum accepted hit distance.
2221    /// - `f32` - Maximum accepted hit distance.
2222    ///
2223    /// # Returns
2224    ///
2225    /// - `bool` - `true` if the ray strikes the implicit surface.
2226    #[must_use]
2227    pub fn any_hit(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
2228        self.trace(ray, t_min, t_max, 0).is_some()
2229    }
2230}