Skip to main content

euv_core/game/engine3d/bvh/
impl.rs

1use super::*;
2
3/// Compact hot-geometry ray intersection kernel for `BvhGeomTri`.
4impl BvhGeomTri {
5    /// Extracts compact 36-byte hot geometry from a `BvhTriangle`.
6    ///
7    /// # Arguments
8    ///
9    /// - `&BvhTriangle` - Source world-space triangle.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - L1-cache-compact triangle geometry.
14    #[must_use]
15    pub(crate) fn from_triangle(tri: &BvhTriangle) -> Self {
16        let v0: Vec3 = tri.get_v0();
17        let e1: Vec3 = tri.get_edge1();
18        let e2: Vec3 = tri.get_edge2();
19        Self {
20            v0: [v0.get_x(), v0.get_y(), v0.get_z()],
21            e1: [e1.get_x(), e1.get_y(), e1.get_z()],
22            e2: [e2.get_x(), e2.get_y(), e2.get_z()],
23        }
24    }
25
26    /// Deferred-division Möller–Trumbore ray-triangle test avoiding division on rejected triangles.
27    ///
28    /// # Arguments
29    ///
30    /// - `&Self` - Compact triangle geometry reference.
31    /// - `Vec3` - Ray origin.
32    /// - `Vec3` - Unit ray direction.
33    /// - `f32` - Minimum valid distance.
34    /// - `f32` - Maximum valid distance.
35    ///
36    /// # Returns
37    ///
38    /// - `Option<f32>` - Parametric hit distance if intersected.
39    #[inline(always)]
40    #[must_use]
41    pub(crate) fn intersect_raw(
42        &self,
43        origin: Vec3,
44        dir: Vec3,
45        t_min: f32,
46        t_max: f32,
47    ) -> Option<f32> {
48        let Self { v0, e1, e2 } = self;
49        let dx: f32 = dir.get_x();
50        let dy: f32 = dir.get_y();
51        let dz: f32 = dir.get_z();
52        let hx: f32 = dy * e2[2] - dz * e2[1];
53        let hy: f32 = dz * e2[0] - dx * e2[2];
54        let hz: f32 = dx * e2[1] - dy * e2[0];
55        let det: f32 = e1[0] * hx + e1[1] * hy + e1[2] * hz;
56        let sx: f32 = origin.get_x() - v0[0];
57        let sy: f32 = origin.get_y() - v0[1];
58        let sz: f32 = origin.get_z() - v0[2];
59        if det > 1e-6 {
60            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
61            if u_raw < 0.0 || u_raw > det {
62                return None;
63            }
64            let qx: f32 = sy * e1[2] - sz * e1[1];
65            let qy: f32 = sz * e1[0] - sx * e1[2];
66            let qz: f32 = sx * e1[1] - sy * e1[0];
67            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
68            if v_raw < 0.0 || u_raw + v_raw > det {
69                return None;
70            }
71            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
72            if t_raw <= t_min * det || t_raw >= t_max * det {
73                return None;
74            }
75            Some(t_raw / det)
76        } else if det < -1e-6 {
77            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
78            if u_raw > 0.0 || u_raw < det {
79                return None;
80            }
81            let qx: f32 = sy * e1[2] - sz * e1[1];
82            let qy: f32 = sz * e1[0] - sx * e1[2];
83            let qz: f32 = sx * e1[1] - sy * e1[0];
84            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
85            if v_raw > 0.0 || u_raw + v_raw < det {
86                return None;
87            }
88            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
89            if t_raw >= t_min * det || t_raw <= t_max * det {
90                return None;
91            }
92            Some(t_raw / det)
93        } else {
94            None
95        }
96    }
97
98    /// Zero-division occlusion-only Möller–Trumbore test for shadow rays within `(t_min, t_max)`.
99    ///
100    /// # Arguments
101    ///
102    /// - `&Self` - Compact triangle geometry reference.
103    /// - `Vec3` - Ray origin.
104    /// - `Vec3` - Unit ray direction.
105    /// - `f32` - Minimum valid distance.
106    /// - `f32` - Maximum valid distance.
107    ///
108    /// # Returns
109    ///
110    /// - `bool` - `true` when the ray intersects this triangle within `(t_min, t_max)`.
111    #[inline(always)]
112    #[must_use]
113    pub(crate) fn intersect_any_raw(
114        &self,
115        origin: Vec3,
116        dir: Vec3,
117        t_min: f32,
118        t_max: f32,
119    ) -> bool {
120        let Self { v0, e1, e2 } = self;
121        let dx: f32 = dir.get_x();
122        let dy: f32 = dir.get_y();
123        let dz: f32 = dir.get_z();
124        let hx: f32 = dy * e2[2] - dz * e2[1];
125        let hy: f32 = dz * e2[0] - dx * e2[2];
126        let hz: f32 = dx * e2[1] - dy * e2[0];
127        let det: f32 = e1[0] * hx + e1[1] * hy + e1[2] * hz;
128        let sx: f32 = origin.get_x() - v0[0];
129        let sy: f32 = origin.get_y() - v0[1];
130        let sz: f32 = origin.get_z() - v0[2];
131        if det > 1e-6 {
132            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
133            if u_raw < 0.0 || u_raw > det {
134                return false;
135            }
136            let qx: f32 = sy * e1[2] - sz * e1[1];
137            let qy: f32 = sz * e1[0] - sx * e1[2];
138            let qz: f32 = sx * e1[1] - sy * e1[0];
139            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
140            if v_raw < 0.0 || u_raw + v_raw > det {
141                return false;
142            }
143            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
144            t_raw > t_min * det && t_raw < t_max * det
145        } else if det < -1e-6 {
146            let u_raw: f32 = sx * hx + sy * hy + sz * hz;
147            if u_raw > 0.0 || u_raw < det {
148                return false;
149            }
150            let qx: f32 = sy * e1[2] - sz * e1[1];
151            let qy: f32 = sz * e1[0] - sx * e1[2];
152            let qz: f32 = sx * e1[1] - sy * e1[0];
153            let v_raw: f32 = dx * qx + dy * qy + dz * qz;
154            if v_raw > 0.0 || u_raw + v_raw < det {
155                return false;
156            }
157            let t_raw: f32 = e2[0] * qx + e2[1] * qy + e2[2] * qz;
158            t_raw < t_min * det && t_raw > t_max * det
159        } else {
160            false
161        }
162    }
163
164    /// Tests a 4-ray coherent packet simultaneously against this single occluder triangle, returning a 4-bit hit mask.
165    ///
166    /// # Arguments
167    ///
168    /// - `&Self` - Single triangle geometry reference.
169    /// - `&RayPacket4` - Coherent 4-ray packet.
170    /// - `f32` - Minimum valid distance.
171    /// - `f32` - Maximum valid distance.
172    ///
173    /// # Returns
174    ///
175    /// - `u8` - Bitmask of lanes `0..4` occluded by this triangle.
176    #[inline(always)]
177    #[must_use]
178    pub(crate) fn intersect_any_packet4(&self, pkt: &RayPacket4, t_min: f32, t_max: f32) -> u8 {
179        #[cfg(target_arch = "aarch64")]
180        {
181            let Self { v0, e1, e2 } = self;
182            // SAFETY: NEON is mandatory on `aarch64`, and all inputs are valid 16-byte stack arrays.
183            unsafe {
184                let ox: core::arch::aarch64::float32x4_t =
185                    core::arch::aarch64::vld1q_f32(pkt.ox.as_ptr());
186                let oy: core::arch::aarch64::float32x4_t =
187                    core::arch::aarch64::vld1q_f32(pkt.oy.as_ptr());
188                let oz: core::arch::aarch64::float32x4_t =
189                    core::arch::aarch64::vld1q_f32(pkt.oz.as_ptr());
190                let dx: core::arch::aarch64::float32x4_t =
191                    core::arch::aarch64::vld1q_f32(pkt.dx.as_ptr());
192                let dy: core::arch::aarch64::float32x4_t =
193                    core::arch::aarch64::vld1q_f32(pkt.dy.as_ptr());
194                let dz: core::arch::aarch64::float32x4_t =
195                    core::arch::aarch64::vld1q_f32(pkt.dz.as_ptr());
196                let e1x: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(e1[0]);
197                let e1y: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(e1[1]);
198                let e1z: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(e1[2]);
199                let e2x: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(e2[0]);
200                let e2y: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(e2[1]);
201                let e2z: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(e2[2]);
202                let hx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
203                    core::arch::aarch64::vmulq_f32(dy, e2z),
204                    dz,
205                    e2y,
206                );
207                let hy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
208                    core::arch::aarch64::vmulq_f32(dz, e2x),
209                    dx,
210                    e2z,
211                );
212                let hz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
213                    core::arch::aarch64::vmulq_f32(dx, e2y),
214                    dy,
215                    e2x,
216                );
217                let det: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
218                    core::arch::aarch64::vfmaq_f32(
219                        core::arch::aarch64::vmulq_f32(e1z, hz),
220                        e1y,
221                        hy,
222                    ),
223                    e1x,
224                    hx,
225                );
226                let sign_bits: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
227                    core::arch::aarch64::vreinterpretq_u32_f32(det),
228                    core::arch::aarch64::vdupq_n_u32(0x8000_0000),
229                );
230                let ad: core::arch::aarch64::float32x4_t = core::arch::aarch64::vabsq_f32(det);
231                let sx: core::arch::aarch64::float32x4_t =
232                    core::arch::aarch64::vsubq_f32(ox, core::arch::aarch64::vdupq_n_f32(v0[0]));
233                let sy: core::arch::aarch64::float32x4_t =
234                    core::arch::aarch64::vsubq_f32(oy, core::arch::aarch64::vdupq_n_f32(v0[1]));
235                let sz: core::arch::aarch64::float32x4_t =
236                    core::arch::aarch64::vsubq_f32(oz, core::arch::aarch64::vdupq_n_f32(v0[2]));
237                let u_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
238                    core::arch::aarch64::vfmaq_f32(core::arch::aarch64::vmulq_f32(sz, hz), sy, hy),
239                    sx,
240                    hx,
241                );
242                let su: core::arch::aarch64::float32x4_t =
243                    core::arch::aarch64::vreinterpretq_f32_u32(core::arch::aarch64::veorq_u32(
244                        core::arch::aarch64::vreinterpretq_u32_f32(u_raw),
245                        sign_bits,
246                    ));
247                let qx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
248                    core::arch::aarch64::vmulq_f32(sy, e1z),
249                    sz,
250                    e1y,
251                );
252                let qy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
253                    core::arch::aarch64::vmulq_f32(sz, e1x),
254                    sx,
255                    e1z,
256                );
257                let qz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
258                    core::arch::aarch64::vmulq_f32(sx, e1y),
259                    sy,
260                    e1x,
261                );
262                let v_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
263                    core::arch::aarch64::vfmaq_f32(core::arch::aarch64::vmulq_f32(dz, qz), dy, qy),
264                    dx,
265                    qx,
266                );
267                let sv: core::arch::aarch64::float32x4_t =
268                    core::arch::aarch64::vreinterpretq_f32_u32(core::arch::aarch64::veorq_u32(
269                        core::arch::aarch64::vreinterpretq_u32_f32(v_raw),
270                        sign_bits,
271                    ));
272                let t_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
273                    core::arch::aarch64::vfmaq_f32(
274                        core::arch::aarch64::vmulq_f32(e2z, qz),
275                        e2y,
276                        qy,
277                    ),
278                    e2x,
279                    qx,
280                );
281                let st: core::arch::aarch64::float32x4_t =
282                    core::arch::aarch64::vreinterpretq_f32_u32(core::arch::aarch64::veorq_u32(
283                        core::arch::aarch64::vreinterpretq_u32_f32(t_raw),
284                        sign_bits,
285                    ));
286                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
287                let m0: core::arch::aarch64::uint32x4_t =
288                    core::arch::aarch64::vcgtq_f32(ad, core::arch::aarch64::vdupq_n_f32(1e-6));
289                let m1: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcgeq_f32(su, zero);
290                let m2: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcgeq_f32(sv, zero);
291                let m3: core::arch::aarch64::uint32x4_t =
292                    core::arch::aarch64::vcleq_f32(core::arch::aarch64::vaddq_f32(su, sv), ad);
293                let m4: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcgtq_f32(
294                    st,
295                    core::arch::aarch64::vmulq_f32(core::arch::aarch64::vdupq_n_f32(t_min), ad),
296                );
297                let m5: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcltq_f32(
298                    st,
299                    core::arch::aarch64::vmulq_f32(core::arch::aarch64::vdupq_n_f32(t_max), ad),
300                );
301                let hit_v: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
302                    core::arch::aarch64::vandq_u32(
303                        core::arch::aarch64::vandq_u32(m0, m1),
304                        core::arch::aarch64::vandq_u32(m2, m3),
305                    ),
306                    core::arch::aarch64::vandq_u32(m4, m5),
307                );
308                let lane_bits: [u32; 4] = [1, 2, 4, 8];
309                let mask: u32 = core::arch::aarch64::vaddvq_u32(core::arch::aarch64::vandq_u32(
310                    hit_v,
311                    core::arch::aarch64::vld1q_u32(lane_bits.as_ptr()),
312                ));
313                mask as u8
314            }
315        }
316        #[cfg(target_arch = "x86_64")]
317        {
318            let Self { v0, e1, e2 } = self;
319            // SAFETY: SSE2 is mandatory on `x86_64`, and all inputs are valid 16-byte stack arrays.
320            unsafe {
321                let ox: core::arch::x86_64::__m128 =
322                    core::arch::x86_64::_mm_loadu_ps(pkt.ox.as_ptr());
323                let oy: core::arch::x86_64::__m128 =
324                    core::arch::x86_64::_mm_loadu_ps(pkt.oy.as_ptr());
325                let oz: core::arch::x86_64::__m128 =
326                    core::arch::x86_64::_mm_loadu_ps(pkt.oz.as_ptr());
327                let dx: core::arch::x86_64::__m128 =
328                    core::arch::x86_64::_mm_loadu_ps(pkt.dx.as_ptr());
329                let dy: core::arch::x86_64::__m128 =
330                    core::arch::x86_64::_mm_loadu_ps(pkt.dy.as_ptr());
331                let dz: core::arch::x86_64::__m128 =
332                    core::arch::x86_64::_mm_loadu_ps(pkt.dz.as_ptr());
333                let e1x: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(e1[0]);
334                let e1y: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(e1[1]);
335                let e1z: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(e1[2]);
336                let e2x: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(e2[0]);
337                let e2y: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(e2[1]);
338                let e2z: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(e2[2]);
339                let hx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
340                    core::arch::x86_64::_mm_mul_ps(dy, e2z),
341                    core::arch::x86_64::_mm_mul_ps(dz, e2y),
342                );
343                let hy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
344                    core::arch::x86_64::_mm_mul_ps(dz, e2x),
345                    core::arch::x86_64::_mm_mul_ps(dx, e2z),
346                );
347                let hz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
348                    core::arch::x86_64::_mm_mul_ps(dx, e2y),
349                    core::arch::x86_64::_mm_mul_ps(dy, e2x),
350                );
351                let det: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
352                    core::arch::x86_64::_mm_add_ps(
353                        core::arch::x86_64::_mm_mul_ps(e1x, hx),
354                        core::arch::x86_64::_mm_mul_ps(e1y, hy),
355                    ),
356                    core::arch::x86_64::_mm_mul_ps(e1z, hz),
357                );
358                let sign_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
359                let sign_bits: core::arch::x86_64::__m128 =
360                    core::arch::x86_64::_mm_and_ps(det, sign_mask);
361                let ad: core::arch::x86_64::__m128 =
362                    core::arch::x86_64::_mm_andnot_ps(sign_mask, det);
363                let sx: core::arch::x86_64::__m128 =
364                    core::arch::x86_64::_mm_sub_ps(ox, core::arch::x86_64::_mm_set1_ps(v0[0]));
365                let sy: core::arch::x86_64::__m128 =
366                    core::arch::x86_64::_mm_sub_ps(oy, core::arch::x86_64::_mm_set1_ps(v0[1]));
367                let sz: core::arch::x86_64::__m128 =
368                    core::arch::x86_64::_mm_sub_ps(oz, core::arch::x86_64::_mm_set1_ps(v0[2]));
369                let u_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
370                    core::arch::x86_64::_mm_add_ps(
371                        core::arch::x86_64::_mm_mul_ps(sx, hx),
372                        core::arch::x86_64::_mm_mul_ps(sy, hy),
373                    ),
374                    core::arch::x86_64::_mm_mul_ps(sz, hz),
375                );
376                let su: core::arch::x86_64::__m128 =
377                    core::arch::x86_64::_mm_xor_ps(u_raw, sign_bits);
378                let qx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
379                    core::arch::x86_64::_mm_mul_ps(sy, e1z),
380                    core::arch::x86_64::_mm_mul_ps(sz, e1y),
381                );
382                let qy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
383                    core::arch::x86_64::_mm_mul_ps(sz, e1x),
384                    core::arch::x86_64::_mm_mul_ps(sx, e1z),
385                );
386                let qz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
387                    core::arch::x86_64::_mm_mul_ps(sx, e1y),
388                    core::arch::x86_64::_mm_mul_ps(sy, e1x),
389                );
390                let v_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
391                    core::arch::x86_64::_mm_add_ps(
392                        core::arch::x86_64::_mm_mul_ps(dx, qx),
393                        core::arch::x86_64::_mm_mul_ps(dy, qy),
394                    ),
395                    core::arch::x86_64::_mm_mul_ps(dz, qz),
396                );
397                let sv: core::arch::x86_64::__m128 =
398                    core::arch::x86_64::_mm_xor_ps(v_raw, sign_bits);
399                let t_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
400                    core::arch::x86_64::_mm_add_ps(
401                        core::arch::x86_64::_mm_mul_ps(e2x, qx),
402                        core::arch::x86_64::_mm_mul_ps(e2y, qy),
403                    ),
404                    core::arch::x86_64::_mm_mul_ps(e2z, qz),
405                );
406                let st: core::arch::x86_64::__m128 =
407                    core::arch::x86_64::_mm_xor_ps(t_raw, sign_bits);
408                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_setzero_ps();
409                let m0: core::arch::x86_64::__m128 =
410                    core::arch::x86_64::_mm_cmpgt_ps(ad, core::arch::x86_64::_mm_set1_ps(1e-6));
411                let m1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmpge_ps(su, zero);
412                let m2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmpge_ps(sv, zero);
413                let m3: core::arch::x86_64::__m128 =
414                    core::arch::x86_64::_mm_cmple_ps(core::arch::x86_64::_mm_add_ps(su, sv), ad);
415                let m4: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmpgt_ps(
416                    st,
417                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(t_min), ad),
418                );
419                let m5: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmplt_ps(
420                    st,
421                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(t_max), ad),
422                );
423                let hit_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
424                    core::arch::x86_64::_mm_and_ps(
425                        core::arch::x86_64::_mm_and_ps(m0, m1),
426                        core::arch::x86_64::_mm_and_ps(m2, m3),
427                    ),
428                    core::arch::x86_64::_mm_and_ps(m4, m5),
429                );
430                core::arch::x86_64::_mm_movemask_ps(hit_v) as u8
431            }
432        }
433        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
434        {
435            let Self { v0, e1, e2 } = self;
436            // SAFETY: `wasm32` `simd128` is enabled at compile time, and all inputs are valid 16-byte stack arrays.
437            unsafe {
438                let ox: core::arch::wasm32::v128 =
439                    core::arch::wasm32::v128_load(pkt.ox.as_ptr().cast());
440                let oy: core::arch::wasm32::v128 =
441                    core::arch::wasm32::v128_load(pkt.oy.as_ptr().cast());
442                let oz: core::arch::wasm32::v128 =
443                    core::arch::wasm32::v128_load(pkt.oz.as_ptr().cast());
444                let dx: core::arch::wasm32::v128 =
445                    core::arch::wasm32::v128_load(pkt.dx.as_ptr().cast());
446                let dy: core::arch::wasm32::v128 =
447                    core::arch::wasm32::v128_load(pkt.dy.as_ptr().cast());
448                let dz: core::arch::wasm32::v128 =
449                    core::arch::wasm32::v128_load(pkt.dz.as_ptr().cast());
450                let e1x: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(e1[0]);
451                let e1y: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(e1[1]);
452                let e1z: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(e1[2]);
453                let e2x: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(e2[0]);
454                let e2y: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(e2[1]);
455                let e2z: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(e2[2]);
456                let hx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
457                    core::arch::wasm32::f32x4_mul(dy, e2z),
458                    core::arch::wasm32::f32x4_mul(dz, e2y),
459                );
460                let hy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
461                    core::arch::wasm32::f32x4_mul(dz, e2x),
462                    core::arch::wasm32::f32x4_mul(dx, e2z),
463                );
464                let hz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
465                    core::arch::wasm32::f32x4_mul(dx, e2y),
466                    core::arch::wasm32::f32x4_mul(dy, e2x),
467                );
468                let det: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
469                    core::arch::wasm32::f32x4_add(
470                        core::arch::wasm32::f32x4_mul(e1x, hx),
471                        core::arch::wasm32::f32x4_mul(e1y, hy),
472                    ),
473                    core::arch::wasm32::f32x4_mul(e1z, hz),
474                );
475                let sign_bits: core::arch::wasm32::v128 =
476                    core::arch::wasm32::v128_and(det, core::arch::wasm32::u32x4_splat(0x8000_0000));
477                let ad: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_abs(det);
478                let sx: core::arch::wasm32::v128 =
479                    core::arch::wasm32::f32x4_sub(ox, core::arch::wasm32::f32x4_splat(v0[0]));
480                let sy: core::arch::wasm32::v128 =
481                    core::arch::wasm32::f32x4_sub(oy, core::arch::wasm32::f32x4_splat(v0[1]));
482                let sz: core::arch::wasm32::v128 =
483                    core::arch::wasm32::f32x4_sub(oz, core::arch::wasm32::f32x4_splat(v0[2]));
484                let u_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
485                    core::arch::wasm32::f32x4_add(
486                        core::arch::wasm32::f32x4_mul(sx, hx),
487                        core::arch::wasm32::f32x4_mul(sy, hy),
488                    ),
489                    core::arch::wasm32::f32x4_mul(sz, hz),
490                );
491                let su: core::arch::wasm32::v128 = core::arch::wasm32::v128_xor(u_raw, sign_bits);
492                let qx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
493                    core::arch::wasm32::f32x4_mul(sy, e1z),
494                    core::arch::wasm32::f32x4_mul(sz, e1y),
495                );
496                let qy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
497                    core::arch::wasm32::f32x4_mul(sz, e1x),
498                    core::arch::wasm32::f32x4_mul(sx, e1z),
499                );
500                let qz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
501                    core::arch::wasm32::f32x4_mul(sx, e1y),
502                    core::arch::wasm32::f32x4_mul(sy, e1x),
503                );
504                let v_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
505                    core::arch::wasm32::f32x4_add(
506                        core::arch::wasm32::f32x4_mul(dx, qx),
507                        core::arch::wasm32::f32x4_mul(dy, qy),
508                    ),
509                    core::arch::wasm32::f32x4_mul(dz, qz),
510                );
511                let sv: core::arch::wasm32::v128 = core::arch::wasm32::v128_xor(v_raw, sign_bits);
512                let t_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
513                    core::arch::wasm32::f32x4_add(
514                        core::arch::wasm32::f32x4_mul(e2x, qx),
515                        core::arch::wasm32::f32x4_mul(e2y, qy),
516                    ),
517                    core::arch::wasm32::f32x4_mul(e2z, qz),
518                );
519                let st: core::arch::wasm32::v128 = core::arch::wasm32::v128_xor(t_raw, sign_bits);
520                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
521                let m0: core::arch::wasm32::v128 =
522                    core::arch::wasm32::f32x4_gt(ad, core::arch::wasm32::f32x4_splat(1e-6));
523                let m1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_ge(su, zero);
524                let m2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_ge(sv, zero);
525                let m3: core::arch::wasm32::v128 =
526                    core::arch::wasm32::f32x4_le(core::arch::wasm32::f32x4_add(su, sv), ad);
527                let m4: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_gt(
528                    st,
529                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(t_min), ad),
530                );
531                let m5: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_lt(
532                    st,
533                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(t_max), ad),
534                );
535                let hit_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
536                    core::arch::wasm32::v128_and(
537                        core::arch::wasm32::v128_and(m0, m1),
538                        core::arch::wasm32::v128_and(m2, m3),
539                    ),
540                    core::arch::wasm32::v128_and(m4, m5),
541                );
542                core::arch::wasm32::i32x4_bitmask(hit_v) as u8
543            }
544        }
545        #[cfg(not(target_arch = "aarch64"))]
546        #[cfg(not(target_arch = "x86_64"))]
547        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
548        {
549            let mut mask: u8 = 0;
550            for lane in 0..4 {
551                if self.intersect_any_raw(
552                    Vec3::new(pkt.ox[lane], pkt.oy[lane], pkt.oz[lane]),
553                    Vec3::new(pkt.dx[lane], pkt.dy[lane], pkt.dz[lane]),
554                    t_min,
555                    t_max,
556                ) {
557                    mask |= 1_u8 << lane;
558                }
559            }
560            mask
561        }
562    }
563}
564
565/// 4-wide Structure-of-Arrays SIMD Möller–Trumbore kernels for `BvhTri4`.
566impl BvhTri4 {
567    /// Packs up to 4 contiguous `BvhGeomTri` entries starting at `base_tri_idx` into one `BvhTri4` packet.
568    ///
569    /// # Arguments
570    ///
571    /// - `&[BvhGeomTri]` - Slice of 1..=4 source triangles.
572    /// - `u32` - Global triangle index of `slice[0]` inside `Bvh3D::triangles`.
573    ///
574    /// # Returns
575    ///
576    /// - `Self` - Packed 4-wide SoA packet with zero-edge sentinel padding for trailing lanes.
577    #[must_use]
578    pub(crate) fn from_geom_chunk(slice: &[BvhGeomTri], base_tri_idx: u32) -> Self {
579        let mut v0x: [f32; 4] = [0.0; 4];
580        let mut v0y: [f32; 4] = [0.0; 4];
581        let mut v0z: [f32; 4] = [0.0; 4];
582        let mut e1x: [f32; 4] = [0.0; 4];
583        let mut e1y: [f32; 4] = [0.0; 4];
584        let mut e1z: [f32; 4] = [0.0; 4];
585        let mut e2x: [f32; 4] = [0.0; 4];
586        let mut e2y: [f32; 4] = [0.0; 4];
587        let mut e2z: [f32; 4] = [0.0; 4];
588        let mut tri_indices: [u32; 4] = [u32::MAX; 4];
589        for (lane, tri) in slice.iter().take(4).enumerate() {
590            v0x[lane] = tri.v0[0];
591            v0y[lane] = tri.v0[1];
592            v0z[lane] = tri.v0[2];
593            e1x[lane] = tri.e1[0];
594            e1y[lane] = tri.e1[1];
595            e1z[lane] = tri.e1[2];
596            e2x[lane] = tri.e2[0];
597            e2y[lane] = tri.e2[1];
598            e2z[lane] = tri.e2[2];
599            tri_indices[lane] = base_tri_idx.wrapping_add(lane as u32);
600        }
601        Self {
602            v0x,
603            v0y,
604            v0z,
605            e1x,
606            e1y,
607            e1z,
608            e2x,
609            e2y,
610            e2z,
611            tri_indices,
612        }
613    }
614
615    /// Tests all 4 triangles in parallel via explicit NEON/SSE2 SIMD (with scalar fallback) for any shadow/occlusion hit within `(t_min, t_max)`.
616    ///
617    /// # Arguments
618    ///
619    /// - `&Self` - 4-wide SoA triangle packet.
620    /// - `[f32; 3]` - Ray origin `(ox, oy, oz)`.
621    /// - `[f32; 3]` - Unit ray direction `(dx, dy, dz)`.
622    /// - `f32` - Minimum valid distance.
623    /// - `f32` - Maximum valid distance.
624    ///
625    /// # Returns
626    ///
627    /// - `u32` - Global triangle index of the first occluding lane, or `u32::MAX` on miss.
628    #[inline(always)]
629    #[must_use]
630    pub(crate) fn intersect_any_4(
631        &self,
632        orig: [f32; 3],
633        dir: [f32; 3],
634        t_min: f32,
635        t_max: f32,
636    ) -> u32 {
637        let Self {
638            v0x,
639            v0y,
640            v0z,
641            e1x,
642            e1y,
643            e1z,
644            e2x,
645            e2y,
646            e2z,
647            tri_indices,
648        } = self;
649        #[cfg(target_arch = "aarch64")]
650        {
651            // SAFETY: `BvhTri4` is `#[repr(C, align(16))]` and NEON is mandatory on `aarch64`.
652            let mask: u32 = unsafe {
653                let ox: core::arch::aarch64::float32x4_t =
654                    core::arch::aarch64::vdupq_n_f32(orig[0]);
655                let oy: core::arch::aarch64::float32x4_t =
656                    core::arch::aarch64::vdupq_n_f32(orig[1]);
657                let oz: core::arch::aarch64::float32x4_t =
658                    core::arch::aarch64::vdupq_n_f32(orig[2]);
659                let dx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(dir[0]);
660                let dy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(dir[1]);
661                let dz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(dir[2]);
662                let ve2x: core::arch::aarch64::float32x4_t =
663                    core::arch::aarch64::vld1q_f32(e2x.as_ptr());
664                let ve2y: core::arch::aarch64::float32x4_t =
665                    core::arch::aarch64::vld1q_f32(e2y.as_ptr());
666                let ve2z: core::arch::aarch64::float32x4_t =
667                    core::arch::aarch64::vld1q_f32(e2z.as_ptr());
668                let hx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
669                    core::arch::aarch64::vmulq_f32(dy, ve2z),
670                    dz,
671                    ve2y,
672                );
673                let hy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
674                    core::arch::aarch64::vmulq_f32(dz, ve2x),
675                    dx,
676                    ve2z,
677                );
678                let hz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
679                    core::arch::aarch64::vmulq_f32(dx, ve2y),
680                    dy,
681                    ve2x,
682                );
683                let ve1x: core::arch::aarch64::float32x4_t =
684                    core::arch::aarch64::vld1q_f32(e1x.as_ptr());
685                let ve1y: core::arch::aarch64::float32x4_t =
686                    core::arch::aarch64::vld1q_f32(e1y.as_ptr());
687                let ve1z: core::arch::aarch64::float32x4_t =
688                    core::arch::aarch64::vld1q_f32(e1z.as_ptr());
689                let det: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
690                    core::arch::aarch64::vfmaq_f32(
691                        core::arch::aarch64::vmulq_f32(ve1z, hz),
692                        ve1y,
693                        hy,
694                    ),
695                    ve1x,
696                    hx,
697                );
698                let sign_bits: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
699                    core::arch::aarch64::vreinterpretq_u32_f32(det),
700                    core::arch::aarch64::vdupq_n_u32(0x8000_0000),
701                );
702                let ad: core::arch::aarch64::float32x4_t = core::arch::aarch64::vabsq_f32(det);
703                let sx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vsubq_f32(
704                    ox,
705                    core::arch::aarch64::vld1q_f32(v0x.as_ptr()),
706                );
707                let sy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vsubq_f32(
708                    oy,
709                    core::arch::aarch64::vld1q_f32(v0y.as_ptr()),
710                );
711                let sz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vsubq_f32(
712                    oz,
713                    core::arch::aarch64::vld1q_f32(v0z.as_ptr()),
714                );
715                let u_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
716                    core::arch::aarch64::vfmaq_f32(core::arch::aarch64::vmulq_f32(sz, hz), sy, hy),
717                    sx,
718                    hx,
719                );
720                let su: core::arch::aarch64::float32x4_t =
721                    core::arch::aarch64::vreinterpretq_f32_u32(core::arch::aarch64::veorq_u32(
722                        core::arch::aarch64::vreinterpretq_u32_f32(u_raw),
723                        sign_bits,
724                    ));
725                let qx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
726                    core::arch::aarch64::vmulq_f32(sy, ve1z),
727                    sz,
728                    ve1y,
729                );
730                let qy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
731                    core::arch::aarch64::vmulq_f32(sz, ve1x),
732                    sx,
733                    ve1z,
734                );
735                let qz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
736                    core::arch::aarch64::vmulq_f32(sx, ve1y),
737                    sy,
738                    ve1x,
739                );
740                let v_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
741                    core::arch::aarch64::vfmaq_f32(core::arch::aarch64::vmulq_f32(dz, qz), dy, qy),
742                    dx,
743                    qx,
744                );
745                let sv: core::arch::aarch64::float32x4_t =
746                    core::arch::aarch64::vreinterpretq_f32_u32(core::arch::aarch64::veorq_u32(
747                        core::arch::aarch64::vreinterpretq_u32_f32(v_raw),
748                        sign_bits,
749                    ));
750                let t_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
751                    core::arch::aarch64::vfmaq_f32(
752                        core::arch::aarch64::vmulq_f32(ve2z, qz),
753                        ve2y,
754                        qy,
755                    ),
756                    ve2x,
757                    qx,
758                );
759                let st: core::arch::aarch64::float32x4_t =
760                    core::arch::aarch64::vreinterpretq_f32_u32(core::arch::aarch64::veorq_u32(
761                        core::arch::aarch64::vreinterpretq_u32_f32(t_raw),
762                        sign_bits,
763                    ));
764                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
765                let m0: core::arch::aarch64::uint32x4_t =
766                    core::arch::aarch64::vcgtq_f32(ad, core::arch::aarch64::vdupq_n_f32(1e-6));
767                let m1: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcgeq_f32(su, zero);
768                let m2: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcgeq_f32(sv, zero);
769                let m3: core::arch::aarch64::uint32x4_t =
770                    core::arch::aarch64::vcleq_f32(core::arch::aarch64::vaddq_f32(su, sv), ad);
771                let m4: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcgtq_f32(
772                    st,
773                    core::arch::aarch64::vmulq_f32(core::arch::aarch64::vdupq_n_f32(t_min), ad),
774                );
775                let m5: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcltq_f32(
776                    st,
777                    core::arch::aarch64::vmulq_f32(core::arch::aarch64::vdupq_n_f32(t_max), ad),
778                );
779                let hit_v: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
780                    core::arch::aarch64::vandq_u32(
781                        core::arch::aarch64::vandq_u32(m0, m1),
782                        core::arch::aarch64::vandq_u32(m2, m3),
783                    ),
784                    core::arch::aarch64::vandq_u32(m4, m5),
785                );
786                let lane_bits: [u32; 4] = [1, 2, 4, 8];
787                core::arch::aarch64::vaddvq_u32(core::arch::aarch64::vandq_u32(
788                    hit_v,
789                    core::arch::aarch64::vld1q_u32(lane_bits.as_ptr()),
790                ))
791            };
792            if mask != 0 {
793                tri_indices[mask.trailing_zeros() as usize]
794            } else {
795                u32::MAX
796            }
797        }
798        #[cfg(target_arch = "x86_64")]
799        {
800            // SAFETY: SSE2 is mandatory on `x86_64` and `BvhTri4` is 16-byte aligned.
801            let mask: i32 = unsafe {
802                let ox: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(orig[0]);
803                let oy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(orig[1]);
804                let oz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(orig[2]);
805                let dx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(dir[0]);
806                let dy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(dir[1]);
807                let dz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(dir[2]);
808                let ve2x: core::arch::x86_64::__m128 =
809                    core::arch::x86_64::_mm_load_ps(e2x.as_ptr());
810                let ve2y: core::arch::x86_64::__m128 =
811                    core::arch::x86_64::_mm_load_ps(e2y.as_ptr());
812                let ve2z: core::arch::x86_64::__m128 =
813                    core::arch::x86_64::_mm_load_ps(e2z.as_ptr());
814                let hx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
815                    core::arch::x86_64::_mm_mul_ps(dy, ve2z),
816                    core::arch::x86_64::_mm_mul_ps(dz, ve2y),
817                );
818                let hy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
819                    core::arch::x86_64::_mm_mul_ps(dz, ve2x),
820                    core::arch::x86_64::_mm_mul_ps(dx, ve2z),
821                );
822                let hz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
823                    core::arch::x86_64::_mm_mul_ps(dx, ve2y),
824                    core::arch::x86_64::_mm_mul_ps(dy, ve2x),
825                );
826                let ve1x: core::arch::x86_64::__m128 =
827                    core::arch::x86_64::_mm_load_ps(e1x.as_ptr());
828                let ve1y: core::arch::x86_64::__m128 =
829                    core::arch::x86_64::_mm_load_ps(e1y.as_ptr());
830                let ve1z: core::arch::x86_64::__m128 =
831                    core::arch::x86_64::_mm_load_ps(e1z.as_ptr());
832                let det: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
833                    core::arch::x86_64::_mm_add_ps(
834                        core::arch::x86_64::_mm_mul_ps(ve1x, hx),
835                        core::arch::x86_64::_mm_mul_ps(ve1y, hy),
836                    ),
837                    core::arch::x86_64::_mm_mul_ps(ve1z, hz),
838                );
839                let sign_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
840                let sign_bits: core::arch::x86_64::__m128 =
841                    core::arch::x86_64::_mm_and_ps(det, sign_mask);
842                let ad: core::arch::x86_64::__m128 =
843                    core::arch::x86_64::_mm_andnot_ps(sign_mask, det);
844                let sx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
845                    ox,
846                    core::arch::x86_64::_mm_load_ps(v0x.as_ptr()),
847                );
848                let sy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
849                    oy,
850                    core::arch::x86_64::_mm_load_ps(v0y.as_ptr()),
851                );
852                let sz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
853                    oz,
854                    core::arch::x86_64::_mm_load_ps(v0z.as_ptr()),
855                );
856                let u_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
857                    core::arch::x86_64::_mm_add_ps(
858                        core::arch::x86_64::_mm_mul_ps(sx, hx),
859                        core::arch::x86_64::_mm_mul_ps(sy, hy),
860                    ),
861                    core::arch::x86_64::_mm_mul_ps(sz, hz),
862                );
863                let su: core::arch::x86_64::__m128 =
864                    core::arch::x86_64::_mm_xor_ps(u_raw, sign_bits);
865                let qx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
866                    core::arch::x86_64::_mm_mul_ps(sy, ve1z),
867                    core::arch::x86_64::_mm_mul_ps(sz, ve1y),
868                );
869                let qy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
870                    core::arch::x86_64::_mm_mul_ps(sz, ve1x),
871                    core::arch::x86_64::_mm_mul_ps(sx, ve1z),
872                );
873                let qz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
874                    core::arch::x86_64::_mm_mul_ps(sx, ve1y),
875                    core::arch::x86_64::_mm_mul_ps(sy, ve1x),
876                );
877                let v_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
878                    core::arch::x86_64::_mm_add_ps(
879                        core::arch::x86_64::_mm_mul_ps(dx, qx),
880                        core::arch::x86_64::_mm_mul_ps(dy, qy),
881                    ),
882                    core::arch::x86_64::_mm_mul_ps(dz, qz),
883                );
884                let sv: core::arch::x86_64::__m128 =
885                    core::arch::x86_64::_mm_xor_ps(v_raw, sign_bits);
886                let t_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
887                    core::arch::x86_64::_mm_add_ps(
888                        core::arch::x86_64::_mm_mul_ps(ve2x, qx),
889                        core::arch::x86_64::_mm_mul_ps(ve2y, qy),
890                    ),
891                    core::arch::x86_64::_mm_mul_ps(ve2z, qz),
892                );
893                let st: core::arch::x86_64::__m128 =
894                    core::arch::x86_64::_mm_xor_ps(t_raw, sign_bits);
895                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_setzero_ps();
896                let m0: core::arch::x86_64::__m128 =
897                    core::arch::x86_64::_mm_cmpgt_ps(ad, core::arch::x86_64::_mm_set1_ps(1e-6));
898                let m1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmpge_ps(su, zero);
899                let m2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmpge_ps(sv, zero);
900                let m3: core::arch::x86_64::__m128 =
901                    core::arch::x86_64::_mm_cmple_ps(core::arch::x86_64::_mm_add_ps(su, sv), ad);
902                let m4: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmpgt_ps(
903                    st,
904                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(t_min), ad),
905                );
906                let m5: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmplt_ps(
907                    st,
908                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(t_max), ad),
909                );
910                let hit_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
911                    core::arch::x86_64::_mm_and_ps(
912                        core::arch::x86_64::_mm_and_ps(m0, m1),
913                        core::arch::x86_64::_mm_and_ps(m2, m3),
914                    ),
915                    core::arch::x86_64::_mm_and_ps(m4, m5),
916                );
917                core::arch::x86_64::_mm_movemask_ps(hit_v)
918            };
919            if mask != 0 {
920                tri_indices[(mask as u32).trailing_zeros() as usize]
921            } else {
922                u32::MAX
923            }
924        }
925        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
926        {
927            // SAFETY: `wasm32` `simd128` is enabled at compile time and `BvhTri4` is 16-byte aligned.
928            let mask: u32 = unsafe {
929                let ox: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(orig[0]);
930                let oy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(orig[1]);
931                let oz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(orig[2]);
932                let dx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(dir[0]);
933                let dy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(dir[1]);
934                let dz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(dir[2]);
935                let ve2x: core::arch::wasm32::v128 =
936                    core::arch::wasm32::v128_load(e2x.as_ptr().cast());
937                let ve2y: core::arch::wasm32::v128 =
938                    core::arch::wasm32::v128_load(e2y.as_ptr().cast());
939                let ve2z: core::arch::wasm32::v128 =
940                    core::arch::wasm32::v128_load(e2z.as_ptr().cast());
941                let hx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
942                    core::arch::wasm32::f32x4_mul(dy, ve2z),
943                    core::arch::wasm32::f32x4_mul(dz, ve2y),
944                );
945                let hy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
946                    core::arch::wasm32::f32x4_mul(dz, ve2x),
947                    core::arch::wasm32::f32x4_mul(dx, ve2z),
948                );
949                let hz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
950                    core::arch::wasm32::f32x4_mul(dx, ve2y),
951                    core::arch::wasm32::f32x4_mul(dy, ve2x),
952                );
953                let ve1x: core::arch::wasm32::v128 =
954                    core::arch::wasm32::v128_load(e1x.as_ptr().cast());
955                let ve1y: core::arch::wasm32::v128 =
956                    core::arch::wasm32::v128_load(e1y.as_ptr().cast());
957                let ve1z: core::arch::wasm32::v128 =
958                    core::arch::wasm32::v128_load(e1z.as_ptr().cast());
959                let det: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
960                    core::arch::wasm32::f32x4_add(
961                        core::arch::wasm32::f32x4_mul(ve1x, hx),
962                        core::arch::wasm32::f32x4_mul(ve1y, hy),
963                    ),
964                    core::arch::wasm32::f32x4_mul(ve1z, hz),
965                );
966                let sign_bits: core::arch::wasm32::v128 =
967                    core::arch::wasm32::v128_and(det, core::arch::wasm32::u32x4_splat(0x8000_0000));
968                let ad: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_abs(det);
969                let sx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
970                    ox,
971                    core::arch::wasm32::v128_load(v0x.as_ptr().cast()),
972                );
973                let sy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
974                    oy,
975                    core::arch::wasm32::v128_load(v0y.as_ptr().cast()),
976                );
977                let sz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
978                    oz,
979                    core::arch::wasm32::v128_load(v0z.as_ptr().cast()),
980                );
981                let u_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
982                    core::arch::wasm32::f32x4_add(
983                        core::arch::wasm32::f32x4_mul(sx, hx),
984                        core::arch::wasm32::f32x4_mul(sy, hy),
985                    ),
986                    core::arch::wasm32::f32x4_mul(sz, hz),
987                );
988                let su: core::arch::wasm32::v128 = core::arch::wasm32::v128_xor(u_raw, sign_bits);
989                let qx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
990                    core::arch::wasm32::f32x4_mul(sy, ve1z),
991                    core::arch::wasm32::f32x4_mul(sz, ve1y),
992                );
993                let qy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
994                    core::arch::wasm32::f32x4_mul(sz, ve1x),
995                    core::arch::wasm32::f32x4_mul(sx, ve1z),
996                );
997                let qz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
998                    core::arch::wasm32::f32x4_mul(sx, ve1y),
999                    core::arch::wasm32::f32x4_mul(sy, ve1x),
1000                );
1001                let v_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1002                    core::arch::wasm32::f32x4_add(
1003                        core::arch::wasm32::f32x4_mul(dx, qx),
1004                        core::arch::wasm32::f32x4_mul(dy, qy),
1005                    ),
1006                    core::arch::wasm32::f32x4_mul(dz, qz),
1007                );
1008                let sv: core::arch::wasm32::v128 = core::arch::wasm32::v128_xor(v_raw, sign_bits);
1009                let t_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1010                    core::arch::wasm32::f32x4_add(
1011                        core::arch::wasm32::f32x4_mul(ve2x, qx),
1012                        core::arch::wasm32::f32x4_mul(ve2y, qy),
1013                    ),
1014                    core::arch::wasm32::f32x4_mul(ve2z, qz),
1015                );
1016                let st: core::arch::wasm32::v128 = core::arch::wasm32::v128_xor(t_raw, sign_bits);
1017                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
1018                let m0: core::arch::wasm32::v128 =
1019                    core::arch::wasm32::f32x4_gt(ad, core::arch::wasm32::f32x4_splat(1e-6));
1020                let m1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_ge(su, zero);
1021                let m2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_ge(sv, zero);
1022                let m3: core::arch::wasm32::v128 =
1023                    core::arch::wasm32::f32x4_le(core::arch::wasm32::f32x4_add(su, sv), ad);
1024                let m4: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_gt(
1025                    st,
1026                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(t_min), ad),
1027                );
1028                let m5: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_lt(
1029                    st,
1030                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(t_max), ad),
1031                );
1032                let hit_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
1033                    core::arch::wasm32::v128_and(
1034                        core::arch::wasm32::v128_and(m0, m1),
1035                        core::arch::wasm32::v128_and(m2, m3),
1036                    ),
1037                    core::arch::wasm32::v128_and(m4, m5),
1038                );
1039                core::arch::wasm32::i32x4_bitmask(hit_v) as u32
1040            };
1041            if mask != 0 {
1042                tri_indices[mask.trailing_zeros() as usize]
1043            } else {
1044                u32::MAX
1045            }
1046        }
1047        #[cfg(not(target_arch = "aarch64"))]
1048        #[cfg(not(target_arch = "x86_64"))]
1049        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
1050        {
1051            let ox: f32 = orig[0];
1052            let oy: f32 = orig[1];
1053            let oz: f32 = orig[2];
1054            let dx: f32 = dir[0];
1055            let dy: f32 = dir[1];
1056            let dz: f32 = dir[2];
1057            for i in 0..4 {
1058                let hx: f32 = dy.mul_add(e2z[i], -(dz * e2y[i]));
1059                let hy: f32 = dz.mul_add(e2x[i], -(dx * e2z[i]));
1060                let hz: f32 = dx.mul_add(e2y[i], -(dy * e2x[i]));
1061                let det: f32 = e1x[i].mul_add(hx, e1y[i].mul_add(hy, e1z[i] * hz));
1062                let sign: f32 = 1.0_f32.copysign(det);
1063                let ad: f32 = det.abs();
1064                let sx: f32 = ox - v0x[i];
1065                let sy: f32 = oy - v0y[i];
1066                let sz: f32 = oz - v0z[i];
1067                let su: f32 = sx.mul_add(hx, sy.mul_add(hy, sz * hz)) * sign;
1068                let qx: f32 = sy.mul_add(e1z[i], -(sz * e1y[i]));
1069                let qy: f32 = sz.mul_add(e1x[i], -(sx * e1z[i]));
1070                let qz: f32 = sx.mul_add(e1y[i], -(sy * e1x[i]));
1071                let sv: f32 = dx.mul_add(qx, dy.mul_add(qy, dz * qz)) * sign;
1072                let st: f32 = e2x[i].mul_add(qx, e2y[i].mul_add(qy, e2z[i] * qz)) * sign;
1073                let uv_ok: bool = su >= 0.0 && sv >= 0.0 && (su + sv) <= ad;
1074                let t_ok: bool = st > t_min * ad && st < t_max * ad;
1075                if ad > 1e-6 && uv_ok && t_ok {
1076                    return tri_indices[i];
1077                }
1078            }
1079            u32::MAX
1080        }
1081    }
1082
1083    /// Tests all 4 triangles in parallel via explicit NEON/SSE2 SIMD (with scalar fallback) and updates `(best_t, best_idx)` on any closer hit.
1084    ///
1085    /// # Arguments
1086    ///
1087    /// - `&Self` - 4-wide SoA triangle packet.
1088    /// - `[f32; 3]` - Ray origin `(ox, oy, oz)`.
1089    /// - `[f32; 3]` - Unit ray direction `(dx, dy, dz)`.
1090    /// - `f32` - Minimum valid distance.
1091    /// - `&mut f32` - Closest hit distance tightened on hit.
1092    /// - `&mut usize` - Closest hit triangle index updated on hit.
1093    #[inline(always)]
1094    pub(crate) fn intersect_closest_4(
1095        &self,
1096        orig: [f32; 3],
1097        dir: [f32; 3],
1098        t_min: f32,
1099        best_t: &mut f32,
1100        best_idx: &mut usize,
1101    ) {
1102        let Self {
1103            v0x,
1104            v0y,
1105            v0z,
1106            e1x,
1107            e1y,
1108            e1z,
1109            e2x,
1110            e2y,
1111            e2z,
1112            tri_indices,
1113        } = self;
1114        let cur_max: f32 = *best_t;
1115        #[cfg(target_arch = "aarch64")]
1116        {
1117            let mut ad_arr: [f32; 4] = [0.0; 4];
1118            let mut st_arr: [f32; 4] = [0.0; 4];
1119            // SAFETY: `BvhTri4` is 16-byte aligned and NEON is mandatory on `aarch64`.
1120            let mask: u32 = unsafe {
1121                let ox: core::arch::aarch64::float32x4_t =
1122                    core::arch::aarch64::vdupq_n_f32(orig[0]);
1123                let oy: core::arch::aarch64::float32x4_t =
1124                    core::arch::aarch64::vdupq_n_f32(orig[1]);
1125                let oz: core::arch::aarch64::float32x4_t =
1126                    core::arch::aarch64::vdupq_n_f32(orig[2]);
1127                let dx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(dir[0]);
1128                let dy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(dir[1]);
1129                let dz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(dir[2]);
1130                let ve2x: core::arch::aarch64::float32x4_t =
1131                    core::arch::aarch64::vld1q_f32(e2x.as_ptr());
1132                let ve2y: core::arch::aarch64::float32x4_t =
1133                    core::arch::aarch64::vld1q_f32(e2y.as_ptr());
1134                let ve2z: core::arch::aarch64::float32x4_t =
1135                    core::arch::aarch64::vld1q_f32(e2z.as_ptr());
1136                let hx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
1137                    core::arch::aarch64::vmulq_f32(dy, ve2z),
1138                    dz,
1139                    ve2y,
1140                );
1141                let hy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
1142                    core::arch::aarch64::vmulq_f32(dz, ve2x),
1143                    dx,
1144                    ve2z,
1145                );
1146                let hz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
1147                    core::arch::aarch64::vmulq_f32(dx, ve2y),
1148                    dy,
1149                    ve2x,
1150                );
1151                let ve1x: core::arch::aarch64::float32x4_t =
1152                    core::arch::aarch64::vld1q_f32(e1x.as_ptr());
1153                let ve1y: core::arch::aarch64::float32x4_t =
1154                    core::arch::aarch64::vld1q_f32(e1y.as_ptr());
1155                let ve1z: core::arch::aarch64::float32x4_t =
1156                    core::arch::aarch64::vld1q_f32(e1z.as_ptr());
1157                let det: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1158                    core::arch::aarch64::vfmaq_f32(
1159                        core::arch::aarch64::vmulq_f32(ve1z, hz),
1160                        ve1y,
1161                        hy,
1162                    ),
1163                    ve1x,
1164                    hx,
1165                );
1166                let sign_bits: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
1167                    core::arch::aarch64::vreinterpretq_u32_f32(det),
1168                    core::arch::aarch64::vdupq_n_u32(0x8000_0000),
1169                );
1170                let ad: core::arch::aarch64::float32x4_t = core::arch::aarch64::vabsq_f32(det);
1171                let sx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vsubq_f32(
1172                    ox,
1173                    core::arch::aarch64::vld1q_f32(v0x.as_ptr()),
1174                );
1175                let sy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vsubq_f32(
1176                    oy,
1177                    core::arch::aarch64::vld1q_f32(v0y.as_ptr()),
1178                );
1179                let sz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vsubq_f32(
1180                    oz,
1181                    core::arch::aarch64::vld1q_f32(v0z.as_ptr()),
1182                );
1183                let u_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1184                    core::arch::aarch64::vfmaq_f32(core::arch::aarch64::vmulq_f32(sz, hz), sy, hy),
1185                    sx,
1186                    hx,
1187                );
1188                let su: core::arch::aarch64::float32x4_t =
1189                    core::arch::aarch64::vreinterpretq_f32_u32(core::arch::aarch64::veorq_u32(
1190                        core::arch::aarch64::vreinterpretq_u32_f32(u_raw),
1191                        sign_bits,
1192                    ));
1193                let qx: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
1194                    core::arch::aarch64::vmulq_f32(sy, ve1z),
1195                    sz,
1196                    ve1y,
1197                );
1198                let qy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
1199                    core::arch::aarch64::vmulq_f32(sz, ve1x),
1200                    sx,
1201                    ve1z,
1202                );
1203                let qz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmsq_f32(
1204                    core::arch::aarch64::vmulq_f32(sx, ve1y),
1205                    sy,
1206                    ve1x,
1207                );
1208                let v_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1209                    core::arch::aarch64::vfmaq_f32(core::arch::aarch64::vmulq_f32(dz, qz), dy, qy),
1210                    dx,
1211                    qx,
1212                );
1213                let sv: core::arch::aarch64::float32x4_t =
1214                    core::arch::aarch64::vreinterpretq_f32_u32(core::arch::aarch64::veorq_u32(
1215                        core::arch::aarch64::vreinterpretq_u32_f32(v_raw),
1216                        sign_bits,
1217                    ));
1218                let t_raw: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1219                    core::arch::aarch64::vfmaq_f32(
1220                        core::arch::aarch64::vmulq_f32(ve2z, qz),
1221                        ve2y,
1222                        qy,
1223                    ),
1224                    ve2x,
1225                    qx,
1226                );
1227                let st: core::arch::aarch64::float32x4_t =
1228                    core::arch::aarch64::vreinterpretq_f32_u32(core::arch::aarch64::veorq_u32(
1229                        core::arch::aarch64::vreinterpretq_u32_f32(t_raw),
1230                        sign_bits,
1231                    ));
1232                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
1233                let m0: core::arch::aarch64::uint32x4_t =
1234                    core::arch::aarch64::vcgtq_f32(ad, core::arch::aarch64::vdupq_n_f32(1e-6));
1235                let m1: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcgeq_f32(su, zero);
1236                let m2: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcgeq_f32(sv, zero);
1237                let m3: core::arch::aarch64::uint32x4_t =
1238                    core::arch::aarch64::vcleq_f32(core::arch::aarch64::vaddq_f32(su, sv), ad);
1239                let m4: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcgtq_f32(
1240                    st,
1241                    core::arch::aarch64::vmulq_f32(core::arch::aarch64::vdupq_n_f32(t_min), ad),
1242                );
1243                let m5: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vcltq_f32(
1244                    st,
1245                    core::arch::aarch64::vmulq_f32(core::arch::aarch64::vdupq_n_f32(cur_max), ad),
1246                );
1247                let hit_v: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
1248                    core::arch::aarch64::vandq_u32(
1249                        core::arch::aarch64::vandq_u32(m0, m1),
1250                        core::arch::aarch64::vandq_u32(m2, m3),
1251                    ),
1252                    core::arch::aarch64::vandq_u32(m4, m5),
1253                );
1254                let lane_bits: [u32; 4] = [1, 2, 4, 8];
1255                let hmask: u32 = core::arch::aarch64::vaddvq_u32(core::arch::aarch64::vandq_u32(
1256                    hit_v,
1257                    core::arch::aarch64::vld1q_u32(lane_bits.as_ptr()),
1258                ));
1259                if hmask != 0 {
1260                    core::arch::aarch64::vst1q_f32(ad_arr.as_mut_ptr(), ad);
1261                    core::arch::aarch64::vst1q_f32(st_arr.as_mut_ptr(), st);
1262                }
1263                hmask
1264            };
1265            let mut rem: u32 = mask;
1266            while rem != 0 {
1267                let i: usize = rem.trailing_zeros() as usize;
1268                rem &= rem - 1;
1269                let t: f32 = st_arr[i] / ad_arr[i];
1270                if t < *best_t {
1271                    *best_t = t;
1272                    *best_idx = tri_indices[i] as usize;
1273                }
1274            }
1275        }
1276        #[cfg(target_arch = "x86_64")]
1277        {
1278            let mut ad_arr: [f32; 4] = [0.0; 4];
1279            let mut st_arr: [f32; 4] = [0.0; 4];
1280            // SAFETY: SSE2 is mandatory on `x86_64` and `BvhTri4` is 16-byte aligned.
1281            let mask: i32 = unsafe {
1282                let ox: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(orig[0]);
1283                let oy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(orig[1]);
1284                let oz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(orig[2]);
1285                let dx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(dir[0]);
1286                let dy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(dir[1]);
1287                let dz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(dir[2]);
1288                let ve2x: core::arch::x86_64::__m128 =
1289                    core::arch::x86_64::_mm_load_ps(e2x.as_ptr());
1290                let ve2y: core::arch::x86_64::__m128 =
1291                    core::arch::x86_64::_mm_load_ps(e2y.as_ptr());
1292                let ve2z: core::arch::x86_64::__m128 =
1293                    core::arch::x86_64::_mm_load_ps(e2z.as_ptr());
1294                let hx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
1295                    core::arch::x86_64::_mm_mul_ps(dy, ve2z),
1296                    core::arch::x86_64::_mm_mul_ps(dz, ve2y),
1297                );
1298                let hy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
1299                    core::arch::x86_64::_mm_mul_ps(dz, ve2x),
1300                    core::arch::x86_64::_mm_mul_ps(dx, ve2z),
1301                );
1302                let hz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
1303                    core::arch::x86_64::_mm_mul_ps(dx, ve2y),
1304                    core::arch::x86_64::_mm_mul_ps(dy, ve2x),
1305                );
1306                let ve1x: core::arch::x86_64::__m128 =
1307                    core::arch::x86_64::_mm_load_ps(e1x.as_ptr());
1308                let ve1y: core::arch::x86_64::__m128 =
1309                    core::arch::x86_64::_mm_load_ps(e1y.as_ptr());
1310                let ve1z: core::arch::x86_64::__m128 =
1311                    core::arch::x86_64::_mm_load_ps(e1z.as_ptr());
1312                let det: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1313                    core::arch::x86_64::_mm_add_ps(
1314                        core::arch::x86_64::_mm_mul_ps(ve1x, hx),
1315                        core::arch::x86_64::_mm_mul_ps(ve1y, hy),
1316                    ),
1317                    core::arch::x86_64::_mm_mul_ps(ve1z, hz),
1318                );
1319                let sign_mask: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(-0.0);
1320                let sign_bits: core::arch::x86_64::__m128 =
1321                    core::arch::x86_64::_mm_and_ps(det, sign_mask);
1322                let ad: core::arch::x86_64::__m128 =
1323                    core::arch::x86_64::_mm_andnot_ps(sign_mask, det);
1324                let sx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
1325                    ox,
1326                    core::arch::x86_64::_mm_load_ps(v0x.as_ptr()),
1327                );
1328                let sy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
1329                    oy,
1330                    core::arch::x86_64::_mm_load_ps(v0y.as_ptr()),
1331                );
1332                let sz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
1333                    oz,
1334                    core::arch::x86_64::_mm_load_ps(v0z.as_ptr()),
1335                );
1336                let u_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1337                    core::arch::x86_64::_mm_add_ps(
1338                        core::arch::x86_64::_mm_mul_ps(sx, hx),
1339                        core::arch::x86_64::_mm_mul_ps(sy, hy),
1340                    ),
1341                    core::arch::x86_64::_mm_mul_ps(sz, hz),
1342                );
1343                let su: core::arch::x86_64::__m128 =
1344                    core::arch::x86_64::_mm_xor_ps(u_raw, sign_bits);
1345                let qx: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
1346                    core::arch::x86_64::_mm_mul_ps(sy, ve1z),
1347                    core::arch::x86_64::_mm_mul_ps(sz, ve1y),
1348                );
1349                let qy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
1350                    core::arch::x86_64::_mm_mul_ps(sz, ve1x),
1351                    core::arch::x86_64::_mm_mul_ps(sx, ve1z),
1352                );
1353                let qz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_sub_ps(
1354                    core::arch::x86_64::_mm_mul_ps(sx, ve1y),
1355                    core::arch::x86_64::_mm_mul_ps(sy, ve1x),
1356                );
1357                let v_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1358                    core::arch::x86_64::_mm_add_ps(
1359                        core::arch::x86_64::_mm_mul_ps(dx, qx),
1360                        core::arch::x86_64::_mm_mul_ps(dy, qy),
1361                    ),
1362                    core::arch::x86_64::_mm_mul_ps(dz, qz),
1363                );
1364                let sv: core::arch::x86_64::__m128 =
1365                    core::arch::x86_64::_mm_xor_ps(v_raw, sign_bits);
1366                let t_raw: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1367                    core::arch::x86_64::_mm_add_ps(
1368                        core::arch::x86_64::_mm_mul_ps(ve2x, qx),
1369                        core::arch::x86_64::_mm_mul_ps(ve2y, qy),
1370                    ),
1371                    core::arch::x86_64::_mm_mul_ps(ve2z, qz),
1372                );
1373                let st: core::arch::x86_64::__m128 =
1374                    core::arch::x86_64::_mm_xor_ps(t_raw, sign_bits);
1375                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_setzero_ps();
1376                let m0: core::arch::x86_64::__m128 =
1377                    core::arch::x86_64::_mm_cmpgt_ps(ad, core::arch::x86_64::_mm_set1_ps(1e-6));
1378                let m1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmpge_ps(su, zero);
1379                let m2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmpge_ps(sv, zero);
1380                let m3: core::arch::x86_64::__m128 =
1381                    core::arch::x86_64::_mm_cmple_ps(core::arch::x86_64::_mm_add_ps(su, sv), ad);
1382                let m4: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmpgt_ps(
1383                    st,
1384                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(t_min), ad),
1385                );
1386                let m5: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_cmplt_ps(
1387                    st,
1388                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(cur_max), ad),
1389                );
1390                let hit_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
1391                    core::arch::x86_64::_mm_and_ps(
1392                        core::arch::x86_64::_mm_and_ps(m0, m1),
1393                        core::arch::x86_64::_mm_and_ps(m2, m3),
1394                    ),
1395                    core::arch::x86_64::_mm_and_ps(m4, m5),
1396                );
1397                let hmask: i32 = core::arch::x86_64::_mm_movemask_ps(hit_v);
1398                if hmask != 0 {
1399                    core::arch::x86_64::_mm_storeu_ps(ad_arr.as_mut_ptr(), ad);
1400                    core::arch::x86_64::_mm_storeu_ps(st_arr.as_mut_ptr(), st);
1401                }
1402                hmask
1403            };
1404            let mut rem: u32 = mask as u32;
1405            while rem != 0 {
1406                let i: usize = rem.trailing_zeros() as usize;
1407                rem &= rem - 1;
1408                let t: f32 = st_arr[i] / ad_arr[i];
1409                if t < *best_t {
1410                    *best_t = t;
1411                    *best_idx = tri_indices[i] as usize;
1412                }
1413            }
1414        }
1415        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
1416        {
1417            let mut ad_arr: [f32; 4] = [0.0; 4];
1418            let mut st_arr: [f32; 4] = [0.0; 4];
1419            // SAFETY: `wasm32` `simd128` is enabled at compile time and `BvhTri4` is 16-byte aligned.
1420            let mask: u32 = unsafe {
1421                let ox: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(orig[0]);
1422                let oy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(orig[1]);
1423                let oz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(orig[2]);
1424                let dx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(dir[0]);
1425                let dy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(dir[1]);
1426                let dz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(dir[2]);
1427                let ve2x: core::arch::wasm32::v128 =
1428                    core::arch::wasm32::v128_load(e2x.as_ptr().cast());
1429                let ve2y: core::arch::wasm32::v128 =
1430                    core::arch::wasm32::v128_load(e2y.as_ptr().cast());
1431                let ve2z: core::arch::wasm32::v128 =
1432                    core::arch::wasm32::v128_load(e2z.as_ptr().cast());
1433                let hx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
1434                    core::arch::wasm32::f32x4_mul(dy, ve2z),
1435                    core::arch::wasm32::f32x4_mul(dz, ve2y),
1436                );
1437                let hy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
1438                    core::arch::wasm32::f32x4_mul(dz, ve2x),
1439                    core::arch::wasm32::f32x4_mul(dx, ve2z),
1440                );
1441                let hz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
1442                    core::arch::wasm32::f32x4_mul(dx, ve2y),
1443                    core::arch::wasm32::f32x4_mul(dy, ve2x),
1444                );
1445                let ve1x: core::arch::wasm32::v128 =
1446                    core::arch::wasm32::v128_load(e1x.as_ptr().cast());
1447                let ve1y: core::arch::wasm32::v128 =
1448                    core::arch::wasm32::v128_load(e1y.as_ptr().cast());
1449                let ve1z: core::arch::wasm32::v128 =
1450                    core::arch::wasm32::v128_load(e1z.as_ptr().cast());
1451                let det: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1452                    core::arch::wasm32::f32x4_add(
1453                        core::arch::wasm32::f32x4_mul(ve1x, hx),
1454                        core::arch::wasm32::f32x4_mul(ve1y, hy),
1455                    ),
1456                    core::arch::wasm32::f32x4_mul(ve1z, hz),
1457                );
1458                let sign_bits: core::arch::wasm32::v128 =
1459                    core::arch::wasm32::v128_and(det, core::arch::wasm32::u32x4_splat(0x8000_0000));
1460                let ad: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_abs(det);
1461                let sx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
1462                    ox,
1463                    core::arch::wasm32::v128_load(v0x.as_ptr().cast()),
1464                );
1465                let sy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
1466                    oy,
1467                    core::arch::wasm32::v128_load(v0y.as_ptr().cast()),
1468                );
1469                let sz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
1470                    oz,
1471                    core::arch::wasm32::v128_load(v0z.as_ptr().cast()),
1472                );
1473                let u_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1474                    core::arch::wasm32::f32x4_add(
1475                        core::arch::wasm32::f32x4_mul(sx, hx),
1476                        core::arch::wasm32::f32x4_mul(sy, hy),
1477                    ),
1478                    core::arch::wasm32::f32x4_mul(sz, hz),
1479                );
1480                let su: core::arch::wasm32::v128 = core::arch::wasm32::v128_xor(u_raw, sign_bits);
1481                let qx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
1482                    core::arch::wasm32::f32x4_mul(sy, ve1z),
1483                    core::arch::wasm32::f32x4_mul(sz, ve1y),
1484                );
1485                let qy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
1486                    core::arch::wasm32::f32x4_mul(sz, ve1x),
1487                    core::arch::wasm32::f32x4_mul(sx, ve1z),
1488                );
1489                let qz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_sub(
1490                    core::arch::wasm32::f32x4_mul(sx, ve1y),
1491                    core::arch::wasm32::f32x4_mul(sy, ve1x),
1492                );
1493                let v_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1494                    core::arch::wasm32::f32x4_add(
1495                        core::arch::wasm32::f32x4_mul(dx, qx),
1496                        core::arch::wasm32::f32x4_mul(dy, qy),
1497                    ),
1498                    core::arch::wasm32::f32x4_mul(dz, qz),
1499                );
1500                let sv: core::arch::wasm32::v128 = core::arch::wasm32::v128_xor(v_raw, sign_bits);
1501                let t_raw: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1502                    core::arch::wasm32::f32x4_add(
1503                        core::arch::wasm32::f32x4_mul(ve2x, qx),
1504                        core::arch::wasm32::f32x4_mul(ve2y, qy),
1505                    ),
1506                    core::arch::wasm32::f32x4_mul(ve2z, qz),
1507                );
1508                let st: core::arch::wasm32::v128 = core::arch::wasm32::v128_xor(t_raw, sign_bits);
1509                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
1510                let m0: core::arch::wasm32::v128 =
1511                    core::arch::wasm32::f32x4_gt(ad, core::arch::wasm32::f32x4_splat(1e-6));
1512                let m1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_ge(su, zero);
1513                let m2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_ge(sv, zero);
1514                let m3: core::arch::wasm32::v128 =
1515                    core::arch::wasm32::f32x4_le(core::arch::wasm32::f32x4_add(su, sv), ad);
1516                let m4: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_gt(
1517                    st,
1518                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(t_min), ad),
1519                );
1520                let m5: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_lt(
1521                    st,
1522                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(cur_max), ad),
1523                );
1524                let hit_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
1525                    core::arch::wasm32::v128_and(
1526                        core::arch::wasm32::v128_and(m0, m1),
1527                        core::arch::wasm32::v128_and(m2, m3),
1528                    ),
1529                    core::arch::wasm32::v128_and(m4, m5),
1530                );
1531                let hmask: u32 = core::arch::wasm32::i32x4_bitmask(hit_v) as u32;
1532                if hmask != 0 {
1533                    core::arch::wasm32::v128_store(ad_arr.as_mut_ptr().cast(), ad);
1534                    core::arch::wasm32::v128_store(st_arr.as_mut_ptr().cast(), st);
1535                }
1536                hmask
1537            };
1538            let mut rem: u32 = mask;
1539            while rem != 0 {
1540                let i: usize = rem.trailing_zeros() as usize;
1541                rem &= rem - 1;
1542                let t: f32 = st_arr[i] / ad_arr[i];
1543                if t < *best_t {
1544                    *best_t = t;
1545                    *best_idx = tri_indices[i] as usize;
1546                }
1547            }
1548        }
1549        #[cfg(not(target_arch = "aarch64"))]
1550        #[cfg(not(target_arch = "x86_64"))]
1551        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
1552        {
1553            let ox: f32 = orig[0];
1554            let oy: f32 = orig[1];
1555            let oz: f32 = orig[2];
1556            let dx: f32 = dir[0];
1557            let dy: f32 = dir[1];
1558            let dz: f32 = dir[2];
1559            let mut ad_arr: [f32; 4] = [0.0; 4];
1560            let mut st_arr: [f32; 4] = [0.0; 4];
1561            let mut hits: [bool; 4] = [false; 4];
1562            for i in 0..4 {
1563                let hx: f32 = dy.mul_add(e2z[i], -(dz * e2y[i]));
1564                let hy: f32 = dz.mul_add(e2x[i], -(dx * e2z[i]));
1565                let hz: f32 = dx.mul_add(e2y[i], -(dy * e2x[i]));
1566                let det: f32 = e1x[i].mul_add(hx, e1y[i].mul_add(hy, e1z[i] * hz));
1567                let sign: f32 = 1.0_f32.copysign(det);
1568                let ad: f32 = det.abs();
1569                let sx: f32 = ox - v0x[i];
1570                let sy: f32 = oy - v0y[i];
1571                let sz: f32 = oz - v0z[i];
1572                let su: f32 = sx.mul_add(hx, sy.mul_add(hy, sz * hz)) * sign;
1573                let qx: f32 = sy.mul_add(e1z[i], -(sz * e1y[i]));
1574                let qy: f32 = sz.mul_add(e1x[i], -(sx * e1z[i]));
1575                let qz: f32 = sx.mul_add(e1y[i], -(sy * e1x[i]));
1576                let sv: f32 = dx.mul_add(qx, dy.mul_add(qy, dz * qz)) * sign;
1577                let st: f32 = e2x[i].mul_add(qx, e2y[i].mul_add(qy, e2z[i] * qz)) * sign;
1578                ad_arr[i] = ad;
1579                st_arr[i] = st;
1580                let uv_ok: bool = su >= 0.0 && sv >= 0.0 && (su + sv) <= ad;
1581                let t_ok: bool = st > t_min * ad && st < cur_max * ad;
1582                hits[i] = ad > 1e-6 && uv_ok && t_ok;
1583            }
1584            for i in 0..4 {
1585                if hits[i] {
1586                    let t: f32 = st_arr[i] / ad_arr[i];
1587                    if t < *best_t {
1588                        *best_t = t;
1589                        *best_idx = tri_indices[i] as usize;
1590                    }
1591                }
1592            }
1593        }
1594    }
1595}
1596
1597/// Scalar-register FMA ray-box slab kernel for 32-byte `BvhFlatNode`.
1598impl BvhFlatNode {
1599    /// Constructs a zeroed placeholder 32-byte flat node for sibling-pair slot reservation.
1600    ///
1601    /// # Returns
1602    ///
1603    /// - `Self` - Empty placeholder flat node.
1604    #[inline(always)]
1605    #[must_use]
1606    pub(crate) const fn empty() -> Self {
1607        Self {
1608            min: [0.0; 3],
1609            child_or_first: 0,
1610            max: [0.0; 3],
1611            tri_count: 0,
1612        }
1613    }
1614
1615    /// Computes branchless FMA near-entry slab intersection distance, or `f32::INFINITY` on miss.
1616    ///
1617    /// # Arguments
1618    ///
1619    /// - `[f32; 3]` - Minimum AABB corner.
1620    /// - `[f32; 3]` - Maximum AABB corner.
1621    /// - `[f32; 3]` - Precomputed safe reciprocal direction `(ix, iy, iz)`.
1622    /// - `[f32; 3]` - Precomputed negated origin-times-inverse `(-ox * ix, -oy * iy, -oz * iz)`.
1623    /// - `f32` - Minimum valid distance.
1624    /// - `f32` - Maximum valid distance.
1625    ///
1626    /// # Returns
1627    ///
1628    /// - `f32` - Near intersection distance if hit, or `f32::INFINITY` on miss.
1629    #[inline(always)]
1630    #[must_use]
1631    pub(crate) fn intersect_box_fma(
1632        min: [f32; 3],
1633        max: [f32; 3],
1634        inv: [f32; 3],
1635        neg_orig_inv: [f32; 3],
1636        t_min: f32,
1637        t_max: f32,
1638    ) -> f32 {
1639        let tx1: f32 = min[0].mul_add(inv[0], neg_orig_inv[0]);
1640        let tx2: f32 = max[0].mul_add(inv[0], neg_orig_inv[0]);
1641        let mut tmin: f32 = t_min.max(tx1.min(tx2));
1642        let mut tmax: f32 = t_max.min(tx1.max(tx2));
1643        let ty1: f32 = min[1].mul_add(inv[1], neg_orig_inv[1]);
1644        let ty2: f32 = max[1].mul_add(inv[1], neg_orig_inv[1]);
1645        tmin = tmin.max(ty1.min(ty2));
1646        tmax = tmax.min(ty1.max(ty2));
1647        let tz1: f32 = min[2].mul_add(inv[2], neg_orig_inv[2]);
1648        let tz2: f32 = max[2].mul_add(inv[2], neg_orig_inv[2]);
1649        tmin = tmin.max(tz1.min(tz2));
1650        tmax = tmax.min(tz1.max(tz2));
1651        if tmax >= tmin && tmax >= 0.0 {
1652            tmin
1653        } else {
1654            f32::INFINITY
1655        }
1656    }
1657}
1658
1659/// 4-wide SoA SIMD slab kernels for `Bvh4Node`.
1660impl Bvh4Node {
1661    /// Creates an empty placeholder `Bvh4Node` with degenerate bounds that never hit.
1662    ///
1663    /// # Returns
1664    ///
1665    /// - `Self` - Empty 4-wide node.
1666    #[inline(always)]
1667    #[must_use]
1668    pub(crate) const fn empty() -> Self {
1669        Self {
1670            min_x: [f32::INFINITY; 4],
1671            min_y: [f32::INFINITY; 4],
1672            min_z: [f32::INFINITY; 4],
1673            max_x: [f32::INFINITY; 4],
1674            max_y: [f32::INFINITY; 4],
1675            max_z: [f32::INFINITY; 4],
1676            child: [u32::MAX; 4],
1677            leaf_count: [0; 4],
1678            valid_count: 0,
1679            _pad: [0; 11],
1680        }
1681    }
1682
1683    /// Tests a single ray simultaneously against all 4 child AABBs via NEON/SSE2 SIMD (with scalar fallback), returning `(t_near_4, 4_bit_hit_mask)`.
1684    ///
1685    /// # Arguments
1686    ///
1687    /// - `&Self` - 4-wide BVH node.
1688    /// - `[f32; 3]` - Precomputed safe reciprocal direction.
1689    /// - `[f32; 3]` - Precomputed `-origin * inv_dir`.
1690    /// - `f32` - Minimum valid distance.
1691    /// - `f32` - Maximum valid distance.
1692    ///
1693    /// # Returns
1694    ///
1695    /// - `([f32; 4], u32)` - Entry distances for all 4 children and a 4-bit hit mask masked by `valid_count`.
1696    #[inline(always)]
1697    #[must_use]
1698    pub(crate) fn intersect_4(
1699        &self,
1700        inv: [f32; 3],
1701        neg_orig_inv: [f32; 3],
1702        t_min: f32,
1703        t_max: f32,
1704    ) -> ([f32; 4], u32) {
1705        let Self {
1706            min_x,
1707            min_y,
1708            min_z,
1709            max_x,
1710            max_y,
1711            max_z,
1712            valid_count,
1713            ..
1714        } = self;
1715        let valid_mask: u32 = (1_u32 << (*valid_count as u32)) - 1;
1716        #[cfg(target_arch = "aarch64")]
1717        {
1718            let mut t_out: [f32; 4] = [f32::INFINITY; 4];
1719            // SAFETY: `Bvh4Node` is 64-byte aligned and NEON is mandatory on `aarch64`.
1720            let mask: u32 = unsafe {
1721                let ix: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(inv[0]);
1722                let iy: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(inv[1]);
1723                let iz: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(inv[2]);
1724                let nx: core::arch::aarch64::float32x4_t =
1725                    core::arch::aarch64::vdupq_n_f32(neg_orig_inv[0]);
1726                let ny: core::arch::aarch64::float32x4_t =
1727                    core::arch::aarch64::vdupq_n_f32(neg_orig_inv[1]);
1728                let nz: core::arch::aarch64::float32x4_t =
1729                    core::arch::aarch64::vdupq_n_f32(neg_orig_inv[2]);
1730                let tx1: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1731                    nx,
1732                    core::arch::aarch64::vld1q_f32(min_x.as_ptr()),
1733                    ix,
1734                );
1735                let tx2: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1736                    nx,
1737                    core::arch::aarch64::vld1q_f32(max_x.as_ptr()),
1738                    ix,
1739                );
1740                let mut vmin: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
1741                    core::arch::aarch64::vdupq_n_f32(t_min),
1742                    core::arch::aarch64::vminq_f32(tx1, tx2),
1743                );
1744                let mut vmax: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
1745                    core::arch::aarch64::vdupq_n_f32(t_max),
1746                    core::arch::aarch64::vmaxq_f32(tx1, tx2),
1747                );
1748                let ty1: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1749                    ny,
1750                    core::arch::aarch64::vld1q_f32(min_y.as_ptr()),
1751                    iy,
1752                );
1753                let ty2: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1754                    ny,
1755                    core::arch::aarch64::vld1q_f32(max_y.as_ptr()),
1756                    iy,
1757                );
1758                vmin =
1759                    core::arch::aarch64::vmaxq_f32(vmin, core::arch::aarch64::vminq_f32(ty1, ty2));
1760                vmax =
1761                    core::arch::aarch64::vminq_f32(vmax, core::arch::aarch64::vmaxq_f32(ty1, ty2));
1762                let tz1: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1763                    nz,
1764                    core::arch::aarch64::vld1q_f32(min_z.as_ptr()),
1765                    iz,
1766                );
1767                let tz2: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
1768                    nz,
1769                    core::arch::aarch64::vld1q_f32(max_z.as_ptr()),
1770                    iz,
1771                );
1772                vmin =
1773                    core::arch::aarch64::vmaxq_f32(vmin, core::arch::aarch64::vminq_f32(tz1, tz2));
1774                vmax =
1775                    core::arch::aarch64::vminq_f32(vmax, core::arch::aarch64::vmaxq_f32(tz1, tz2));
1776                core::arch::aarch64::vst1q_f32(t_out.as_mut_ptr(), vmin);
1777                let hit_v: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
1778                    core::arch::aarch64::vcgeq_f32(vmax, vmin),
1779                    core::arch::aarch64::vcgeq_f32(vmax, core::arch::aarch64::vdupq_n_f32(0.0)),
1780                );
1781                let lane_bits: [u32; 4] = [1, 2, 4, 8];
1782                core::arch::aarch64::vaddvq_u32(core::arch::aarch64::vandq_u32(
1783                    hit_v,
1784                    core::arch::aarch64::vld1q_u32(lane_bits.as_ptr()),
1785                ))
1786            };
1787            (t_out, mask & valid_mask)
1788        }
1789        #[cfg(target_arch = "x86_64")]
1790        {
1791            let mut t_out: [f32; 4] = [f32::INFINITY; 4];
1792            // SAFETY: SSE2 is mandatory on `x86_64` and `Bvh4Node` is 64-byte aligned.
1793            let mask: i32 = unsafe {
1794                let ix: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(inv[0]);
1795                let iy: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(inv[1]);
1796                let iz: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(inv[2]);
1797                let nx: core::arch::x86_64::__m128 =
1798                    core::arch::x86_64::_mm_set1_ps(neg_orig_inv[0]);
1799                let ny: core::arch::x86_64::__m128 =
1800                    core::arch::x86_64::_mm_set1_ps(neg_orig_inv[1]);
1801                let nz: core::arch::x86_64::__m128 =
1802                    core::arch::x86_64::_mm_set1_ps(neg_orig_inv[2]);
1803                let tx1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1804                    core::arch::x86_64::_mm_mul_ps(
1805                        core::arch::x86_64::_mm_load_ps(min_x.as_ptr()),
1806                        ix,
1807                    ),
1808                    nx,
1809                );
1810                let tx2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1811                    core::arch::x86_64::_mm_mul_ps(
1812                        core::arch::x86_64::_mm_load_ps(max_x.as_ptr()),
1813                        ix,
1814                    ),
1815                    nx,
1816                );
1817                let mut vmin: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
1818                    core::arch::x86_64::_mm_set1_ps(t_min),
1819                    core::arch::x86_64::_mm_min_ps(tx1, tx2),
1820                );
1821                let mut vmax: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
1822                    core::arch::x86_64::_mm_set1_ps(t_max),
1823                    core::arch::x86_64::_mm_max_ps(tx1, tx2),
1824                );
1825                let ty1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1826                    core::arch::x86_64::_mm_mul_ps(
1827                        core::arch::x86_64::_mm_load_ps(min_y.as_ptr()),
1828                        iy,
1829                    ),
1830                    ny,
1831                );
1832                let ty2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1833                    core::arch::x86_64::_mm_mul_ps(
1834                        core::arch::x86_64::_mm_load_ps(max_y.as_ptr()),
1835                        iy,
1836                    ),
1837                    ny,
1838                );
1839                vmin =
1840                    core::arch::x86_64::_mm_max_ps(vmin, core::arch::x86_64::_mm_min_ps(ty1, ty2));
1841                vmax =
1842                    core::arch::x86_64::_mm_min_ps(vmax, core::arch::x86_64::_mm_max_ps(ty1, ty2));
1843                let tz1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1844                    core::arch::x86_64::_mm_mul_ps(
1845                        core::arch::x86_64::_mm_load_ps(min_z.as_ptr()),
1846                        iz,
1847                    ),
1848                    nz,
1849                );
1850                let tz2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
1851                    core::arch::x86_64::_mm_mul_ps(
1852                        core::arch::x86_64::_mm_load_ps(max_z.as_ptr()),
1853                        iz,
1854                    ),
1855                    nz,
1856                );
1857                vmin =
1858                    core::arch::x86_64::_mm_max_ps(vmin, core::arch::x86_64::_mm_min_ps(tz1, tz2));
1859                vmax =
1860                    core::arch::x86_64::_mm_min_ps(vmax, core::arch::x86_64::_mm_max_ps(tz1, tz2));
1861                core::arch::x86_64::_mm_storeu_ps(t_out.as_mut_ptr(), vmin);
1862                let hit_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
1863                    core::arch::x86_64::_mm_cmpge_ps(vmax, vmin),
1864                    core::arch::x86_64::_mm_cmpge_ps(vmax, core::arch::x86_64::_mm_setzero_ps()),
1865                );
1866                core::arch::x86_64::_mm_movemask_ps(hit_v)
1867            };
1868            (t_out, (mask as u32) & valid_mask)
1869        }
1870        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
1871        {
1872            let mut t_out: [f32; 4] = [f32::INFINITY; 4];
1873            // SAFETY: `wasm32` `simd128` is enabled at compile time and `Bvh4Node` is 64-byte aligned.
1874            let mask: u32 = unsafe {
1875                let ix: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(inv[0]);
1876                let iy: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(inv[1]);
1877                let iz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(inv[2]);
1878                let nx: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(neg_orig_inv[0]);
1879                let ny: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(neg_orig_inv[1]);
1880                let nz: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(neg_orig_inv[2]);
1881                let tx1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1882                    core::arch::wasm32::f32x4_mul(
1883                        core::arch::wasm32::v128_load(min_x.as_ptr().cast()),
1884                        ix,
1885                    ),
1886                    nx,
1887                );
1888                let tx2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1889                    core::arch::wasm32::f32x4_mul(
1890                        core::arch::wasm32::v128_load(max_x.as_ptr().cast()),
1891                        ix,
1892                    ),
1893                    nx,
1894                );
1895                let mut vmin: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
1896                    core::arch::wasm32::f32x4_splat(t_min),
1897                    core::arch::wasm32::f32x4_pmin(tx1, tx2),
1898                );
1899                let mut vmax: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
1900                    core::arch::wasm32::f32x4_splat(t_max),
1901                    core::arch::wasm32::f32x4_pmax(tx1, tx2),
1902                );
1903                let ty1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1904                    core::arch::wasm32::f32x4_mul(
1905                        core::arch::wasm32::v128_load(min_y.as_ptr().cast()),
1906                        iy,
1907                    ),
1908                    ny,
1909                );
1910                let ty2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1911                    core::arch::wasm32::f32x4_mul(
1912                        core::arch::wasm32::v128_load(max_y.as_ptr().cast()),
1913                        iy,
1914                    ),
1915                    ny,
1916                );
1917                vmin =
1918                    core::arch::wasm32::f32x4_pmax(vmin, core::arch::wasm32::f32x4_pmin(ty1, ty2));
1919                vmax =
1920                    core::arch::wasm32::f32x4_pmin(vmax, core::arch::wasm32::f32x4_pmax(ty1, ty2));
1921                let tz1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1922                    core::arch::wasm32::f32x4_mul(
1923                        core::arch::wasm32::v128_load(min_z.as_ptr().cast()),
1924                        iz,
1925                    ),
1926                    nz,
1927                );
1928                let tz2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
1929                    core::arch::wasm32::f32x4_mul(
1930                        core::arch::wasm32::v128_load(max_z.as_ptr().cast()),
1931                        iz,
1932                    ),
1933                    nz,
1934                );
1935                vmin =
1936                    core::arch::wasm32::f32x4_pmax(vmin, core::arch::wasm32::f32x4_pmin(tz1, tz2));
1937                vmax =
1938                    core::arch::wasm32::f32x4_pmin(vmax, core::arch::wasm32::f32x4_pmax(tz1, tz2));
1939                core::arch::wasm32::v128_store(t_out.as_mut_ptr().cast(), vmin);
1940                let hit_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
1941                    core::arch::wasm32::f32x4_ge(vmax, vmin),
1942                    core::arch::wasm32::f32x4_ge(vmax, core::arch::wasm32::f32x4_splat(0.0)),
1943                );
1944                core::arch::wasm32::i32x4_bitmask(hit_v) as u32
1945            };
1946            (t_out, mask & valid_mask)
1947        }
1948        #[cfg(not(target_arch = "aarch64"))]
1949        #[cfg(not(target_arch = "x86_64"))]
1950        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
1951        {
1952            let mut t_out: [f32; 4] = [f32::INFINITY; 4];
1953            let mut mask: u32 = 0;
1954            let count: usize = *valid_count as usize;
1955            for c in 0..count {
1956                let t: f32 = BvhFlatNode::intersect_box_fma(
1957                    [min_x[c], min_y[c], min_z[c]],
1958                    [max_x[c], max_y[c], max_z[c]],
1959                    inv,
1960                    neg_orig_inv,
1961                    t_min,
1962                    t_max,
1963                );
1964                t_out[c] = t;
1965                if t.is_finite() {
1966                    mask |= 1_u32 << c;
1967                }
1968            }
1969            (t_out, mask & valid_mask)
1970        }
1971    }
1972
1973    /// Tests a coherent 4-ray packet against child slot `lane` simultaneously, returning a 4-bit hit mask across the 4 rays.
1974    ///
1975    /// # Arguments
1976    /// Tests all 4 packet rays against a single world/local AABB in one SIMD pass, returning a 4-bit hit mask.
1977    ///
1978    /// # Arguments
1979    ///
1980    /// - `[f32; 3]` - Minimum corner `[min_x, min_y, min_z]`.
1981    /// - `[f32; 3]` - Maximum corner `[max_x, max_y, max_z]`.
1982    /// - `&RayPacket4` - Coherent 4-ray packet.
1983    /// - `&[[f32; 4]; 3]` - Precomputed `-origin * inv_dir` across `[x, y, z]` for all 4 rays.
1984    /// - `f32` - Minimum valid distance.
1985    /// - `[f32; 4]` - Per-ray maximum valid distance.
1986    ///
1987    /// # Returns
1988    ///
1989    /// - `u8` - 4-bit mask of rays intersecting the AABB within `[t_min, t_max_4[r]]`.
1990    #[inline(always)]
1991    #[must_use]
1992    pub(crate) fn intersect_aabb_packet4(
1993        bmin: [f32; 3],
1994        bmax: [f32; 3],
1995        pkt: &RayPacket4,
1996        neg_oi: &[[f32; 4]; 3],
1997        t_min: f32,
1998        t_max_4: [f32; 4],
1999    ) -> u8 {
2000        let bx0: f32 = bmin[0];
2001        let by0: f32 = bmin[1];
2002        let bz0: f32 = bmin[2];
2003        let bx1: f32 = bmax[0];
2004        let by1: f32 = bmax[1];
2005        let bz1: f32 = bmax[2];
2006        #[cfg(target_arch = "aarch64")]
2007        {
2008            // SAFETY: NEON is mandatory on `aarch64` and all slices are valid 16-byte stack arrays.
2009            unsafe {
2010                let ix: core::arch::aarch64::float32x4_t =
2011                    core::arch::aarch64::vld1q_f32(pkt.ix.as_ptr());
2012                let iy: core::arch::aarch64::float32x4_t =
2013                    core::arch::aarch64::vld1q_f32(pkt.iy.as_ptr());
2014                let iz: core::arch::aarch64::float32x4_t =
2015                    core::arch::aarch64::vld1q_f32(pkt.iz.as_ptr());
2016                let nx: core::arch::aarch64::float32x4_t =
2017                    core::arch::aarch64::vld1q_f32(neg_oi[0].as_ptr());
2018                let ny: core::arch::aarch64::float32x4_t =
2019                    core::arch::aarch64::vld1q_f32(neg_oi[1].as_ptr());
2020                let nz: core::arch::aarch64::float32x4_t =
2021                    core::arch::aarch64::vld1q_f32(neg_oi[2].as_ptr());
2022                let tx1: core::arch::aarch64::float32x4_t =
2023                    core::arch::aarch64::vfmaq_f32(nx, core::arch::aarch64::vdupq_n_f32(bx0), ix);
2024                let tx2: core::arch::aarch64::float32x4_t =
2025                    core::arch::aarch64::vfmaq_f32(nx, core::arch::aarch64::vdupq_n_f32(bx1), ix);
2026                let mut vmin: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
2027                    core::arch::aarch64::vdupq_n_f32(t_min),
2028                    core::arch::aarch64::vminq_f32(tx1, tx2),
2029                );
2030                let mut vmax: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
2031                    core::arch::aarch64::vld1q_f32(t_max_4.as_ptr()),
2032                    core::arch::aarch64::vmaxq_f32(tx1, tx2),
2033                );
2034                let ty1: core::arch::aarch64::float32x4_t =
2035                    core::arch::aarch64::vfmaq_f32(ny, core::arch::aarch64::vdupq_n_f32(by0), iy);
2036                let ty2: core::arch::aarch64::float32x4_t =
2037                    core::arch::aarch64::vfmaq_f32(ny, core::arch::aarch64::vdupq_n_f32(by1), iy);
2038                vmin =
2039                    core::arch::aarch64::vmaxq_f32(vmin, core::arch::aarch64::vminq_f32(ty1, ty2));
2040                vmax =
2041                    core::arch::aarch64::vminq_f32(vmax, core::arch::aarch64::vmaxq_f32(ty1, ty2));
2042                let tz1: core::arch::aarch64::float32x4_t =
2043                    core::arch::aarch64::vfmaq_f32(nz, core::arch::aarch64::vdupq_n_f32(bz0), iz);
2044                let tz2: core::arch::aarch64::float32x4_t =
2045                    core::arch::aarch64::vfmaq_f32(nz, core::arch::aarch64::vdupq_n_f32(bz1), iz);
2046                vmin =
2047                    core::arch::aarch64::vmaxq_f32(vmin, core::arch::aarch64::vminq_f32(tz1, tz2));
2048                vmax =
2049                    core::arch::aarch64::vminq_f32(vmax, core::arch::aarch64::vmaxq_f32(tz1, tz2));
2050                let hit_v: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
2051                    core::arch::aarch64::vcgeq_f32(vmax, vmin),
2052                    core::arch::aarch64::vcgeq_f32(vmax, core::arch::aarch64::vdupq_n_f32(0.0)),
2053                );
2054                let lane_bits: [u32; 4] = [1, 2, 4, 8];
2055                core::arch::aarch64::vaddvq_u32(core::arch::aarch64::vandq_u32(
2056                    hit_v,
2057                    core::arch::aarch64::vld1q_u32(lane_bits.as_ptr()),
2058                )) as u8
2059            }
2060        }
2061        #[cfg(target_arch = "x86_64")]
2062        {
2063            // SAFETY: SSE2 is mandatory on `x86_64` and all slices are valid 16-byte stack arrays.
2064            unsafe {
2065                let ix: core::arch::x86_64::__m128 =
2066                    core::arch::x86_64::_mm_loadu_ps(pkt.ix.as_ptr());
2067                let iy: core::arch::x86_64::__m128 =
2068                    core::arch::x86_64::_mm_loadu_ps(pkt.iy.as_ptr());
2069                let iz: core::arch::x86_64::__m128 =
2070                    core::arch::x86_64::_mm_loadu_ps(pkt.iz.as_ptr());
2071                let nx: core::arch::x86_64::__m128 =
2072                    core::arch::x86_64::_mm_loadu_ps(neg_oi[0].as_ptr());
2073                let ny: core::arch::x86_64::__m128 =
2074                    core::arch::x86_64::_mm_loadu_ps(neg_oi[1].as_ptr());
2075                let nz: core::arch::x86_64::__m128 =
2076                    core::arch::x86_64::_mm_loadu_ps(neg_oi[2].as_ptr());
2077                let tx1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2078                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(bx0), ix),
2079                    nx,
2080                );
2081                let tx2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2082                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(bx1), ix),
2083                    nx,
2084                );
2085                let mut vmin: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
2086                    core::arch::x86_64::_mm_set1_ps(t_min),
2087                    core::arch::x86_64::_mm_min_ps(tx1, tx2),
2088                );
2089                let mut vmax: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
2090                    core::arch::x86_64::_mm_loadu_ps(t_max_4.as_ptr()),
2091                    core::arch::x86_64::_mm_max_ps(tx1, tx2),
2092                );
2093                let ty1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2094                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(by0), iy),
2095                    ny,
2096                );
2097                let ty2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2098                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(by1), iy),
2099                    ny,
2100                );
2101                vmin =
2102                    core::arch::x86_64::_mm_max_ps(vmin, core::arch::x86_64::_mm_min_ps(ty1, ty2));
2103                vmax =
2104                    core::arch::x86_64::_mm_min_ps(vmax, core::arch::x86_64::_mm_max_ps(ty1, ty2));
2105                let tz1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2106                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(bz0), iz),
2107                    nz,
2108                );
2109                let tz2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2110                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(bz1), iz),
2111                    nz,
2112                );
2113                vmin =
2114                    core::arch::x86_64::_mm_max_ps(vmin, core::arch::x86_64::_mm_min_ps(tz1, tz2));
2115                vmax =
2116                    core::arch::x86_64::_mm_min_ps(vmax, core::arch::x86_64::_mm_max_ps(tz1, tz2));
2117                let hit_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
2118                    core::arch::x86_64::_mm_cmpge_ps(vmax, vmin),
2119                    core::arch::x86_64::_mm_cmpge_ps(vmax, core::arch::x86_64::_mm_setzero_ps()),
2120                );
2121                core::arch::x86_64::_mm_movemask_ps(hit_v) as u8
2122            }
2123        }
2124        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
2125        {
2126            // SAFETY: `wasm32` `simd128` is enabled at compile time and all slices are valid 16-byte stack arrays.
2127            unsafe {
2128                let ix: core::arch::wasm32::v128 =
2129                    core::arch::wasm32::v128_load(pkt.ix.as_ptr().cast());
2130                let iy: core::arch::wasm32::v128 =
2131                    core::arch::wasm32::v128_load(pkt.iy.as_ptr().cast());
2132                let iz: core::arch::wasm32::v128 =
2133                    core::arch::wasm32::v128_load(pkt.iz.as_ptr().cast());
2134                let nx: core::arch::wasm32::v128 =
2135                    core::arch::wasm32::v128_load(neg_oi[0].as_ptr().cast());
2136                let ny: core::arch::wasm32::v128 =
2137                    core::arch::wasm32::v128_load(neg_oi[1].as_ptr().cast());
2138                let nz: core::arch::wasm32::v128 =
2139                    core::arch::wasm32::v128_load(neg_oi[2].as_ptr().cast());
2140                let tx1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2141                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(bx0), ix),
2142                    nx,
2143                );
2144                let tx2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2145                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(bx1), ix),
2146                    nx,
2147                );
2148                let mut vmin: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
2149                    core::arch::wasm32::f32x4_splat(t_min),
2150                    core::arch::wasm32::f32x4_pmin(tx1, tx2),
2151                );
2152                let mut vmax: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
2153                    core::arch::wasm32::v128_load(t_max_4.as_ptr().cast()),
2154                    core::arch::wasm32::f32x4_pmax(tx1, tx2),
2155                );
2156                let ty1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2157                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(by0), iy),
2158                    ny,
2159                );
2160                let ty2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2161                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(by1), iy),
2162                    ny,
2163                );
2164                vmin =
2165                    core::arch::wasm32::f32x4_pmax(vmin, core::arch::wasm32::f32x4_pmin(ty1, ty2));
2166                vmax =
2167                    core::arch::wasm32::f32x4_pmin(vmax, core::arch::wasm32::f32x4_pmax(ty1, ty2));
2168                let tz1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2169                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(bz0), iz),
2170                    nz,
2171                );
2172                let tz2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2173                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(bz1), iz),
2174                    nz,
2175                );
2176                vmin =
2177                    core::arch::wasm32::f32x4_pmax(vmin, core::arch::wasm32::f32x4_pmin(tz1, tz2));
2178                vmax =
2179                    core::arch::wasm32::f32x4_pmin(vmax, core::arch::wasm32::f32x4_pmax(tz1, tz2));
2180                let hit_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
2181                    core::arch::wasm32::f32x4_ge(vmax, vmin),
2182                    core::arch::wasm32::f32x4_ge(vmax, core::arch::wasm32::f32x4_splat(0.0)),
2183                );
2184                core::arch::wasm32::i32x4_bitmask(hit_v) as u8
2185            }
2186        }
2187        #[cfg(not(target_arch = "aarch64"))]
2188        #[cfg(not(target_arch = "x86_64"))]
2189        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
2190        {
2191            let mut mask: u8 = 0;
2192            for r in 0..4 {
2193                let t: f32 = BvhFlatNode::intersect_box_fma(
2194                    [bx0, by0, bz0],
2195                    [bx1, by1, bz1],
2196                    [pkt.ix[r], pkt.iy[r], pkt.iz[r]],
2197                    [neg_oi[0][r], neg_oi[1][r], neg_oi[2][r]],
2198                    t_min,
2199                    t_max_4[r],
2200                );
2201                if t.is_finite() {
2202                    mask |= 1_u8 << r;
2203                }
2204            }
2205            mask
2206        }
2207    }
2208
2209    /// Tests all 4 packet rays against child `lane` in a single SIMD pass, returning a 4-bit hit mask.
2210    ///
2211    /// # Arguments
2212    ///
2213    /// - `&Self` - 4-wide BVH node.
2214    /// - `usize` - Child lane index `0..4`.
2215    /// - `&RayPacket4` - Coherent 4-ray packet.
2216    /// - `&[[f32; 4]; 3]` - Precomputed `-origin * inv_dir` across `[x, y, z]` for all 4 rays.
2217    /// - `f32` - Minimum valid distance.
2218    /// - `[f32; 4]` - Per-ray maximum valid distance.
2219    ///
2220    /// # Returns
2221    ///
2222    /// - `u8` - 4-bit mask of rays intersecting child `lane`.
2223    #[inline(always)]
2224    #[must_use]
2225    pub(crate) fn intersect_child_packet4(
2226        &self,
2227        lane: usize,
2228        pkt: &RayPacket4,
2229        neg_oi: &[[f32; 4]; 3],
2230        t_min: f32,
2231        t_max_4: [f32; 4],
2232    ) -> u8 {
2233        let Self {
2234            min_x,
2235            min_y,
2236            min_z,
2237            max_x,
2238            max_y,
2239            max_z,
2240            ..
2241        } = self;
2242        Self::intersect_aabb_packet4(
2243            [min_x[lane], min_y[lane], min_z[lane]],
2244            [max_x[lane], max_y[lane], max_z[lane]],
2245            pkt,
2246            neg_oi,
2247            t_min,
2248            t_max_4,
2249        )
2250    }
2251
2252    /// Tests all 4 packet rays against child `lane` in a single SIMD pass, returning `(hit_mask, min_t_near)` for near-to-far BVH ordering and stack pruning.
2253    ///
2254    /// # Arguments
2255    ///
2256    /// - `&Self` - 4-wide BVH node.
2257    /// - `usize` - Child lane index `0..4`.
2258    /// - `&RayPacket4` - Coherent 4-ray packet.
2259    /// - `&[[f32; 4]; 3]` - Precomputed `-origin * inv_dir` across `[x, y, z]` for all 4 rays.
2260    /// - `f32` - Minimum valid distance.
2261    /// - `[f32; 4]` - Per-ray maximum valid distance.
2262    ///
2263    /// # Returns
2264    ///
2265    /// - `(u8, f32)` - 4-bit mask of intersecting rays and minimum entry `t_near` among hitting lanes.
2266    #[inline(always)]
2267    #[must_use]
2268    pub(crate) fn intersect_child_packet4_near(
2269        &self,
2270        lane: usize,
2271        pkt: &RayPacket4,
2272        neg_oi: &[[f32; 4]; 3],
2273        t_min: f32,
2274        t_max_4: [f32; 4],
2275    ) -> (u8, f32) {
2276        let Self {
2277            min_x,
2278            min_y,
2279            min_z,
2280            max_x,
2281            max_y,
2282            max_z,
2283            ..
2284        } = self;
2285        let bx0: f32 = min_x[lane];
2286        let by0: f32 = min_y[lane];
2287        let bz0: f32 = min_z[lane];
2288        let bx1: f32 = max_x[lane];
2289        let by1: f32 = max_y[lane];
2290        let bz1: f32 = max_z[lane];
2291        #[cfg(target_arch = "aarch64")]
2292        {
2293            // SAFETY: NEON is mandatory on `aarch64` and all slices are valid 16-byte stack arrays.
2294            unsafe {
2295                let ix: core::arch::aarch64::float32x4_t =
2296                    core::arch::aarch64::vld1q_f32(pkt.ix.as_ptr());
2297                let iy: core::arch::aarch64::float32x4_t =
2298                    core::arch::aarch64::vld1q_f32(pkt.iy.as_ptr());
2299                let iz: core::arch::aarch64::float32x4_t =
2300                    core::arch::aarch64::vld1q_f32(pkt.iz.as_ptr());
2301                let nx: core::arch::aarch64::float32x4_t =
2302                    core::arch::aarch64::vld1q_f32(neg_oi[0].as_ptr());
2303                let ny: core::arch::aarch64::float32x4_t =
2304                    core::arch::aarch64::vld1q_f32(neg_oi[1].as_ptr());
2305                let nz: core::arch::aarch64::float32x4_t =
2306                    core::arch::aarch64::vld1q_f32(neg_oi[2].as_ptr());
2307                let tx1: core::arch::aarch64::float32x4_t =
2308                    core::arch::aarch64::vfmaq_f32(nx, core::arch::aarch64::vdupq_n_f32(bx0), ix);
2309                let tx2: core::arch::aarch64::float32x4_t =
2310                    core::arch::aarch64::vfmaq_f32(nx, core::arch::aarch64::vdupq_n_f32(bx1), ix);
2311                let mut vmin: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
2312                    core::arch::aarch64::vdupq_n_f32(t_min),
2313                    core::arch::aarch64::vminq_f32(tx1, tx2),
2314                );
2315                let mut vmax: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
2316                    core::arch::aarch64::vld1q_f32(t_max_4.as_ptr()),
2317                    core::arch::aarch64::vmaxq_f32(tx1, tx2),
2318                );
2319                let ty1: core::arch::aarch64::float32x4_t =
2320                    core::arch::aarch64::vfmaq_f32(ny, core::arch::aarch64::vdupq_n_f32(by0), iy);
2321                let ty2: core::arch::aarch64::float32x4_t =
2322                    core::arch::aarch64::vfmaq_f32(ny, core::arch::aarch64::vdupq_n_f32(by1), iy);
2323                vmin =
2324                    core::arch::aarch64::vmaxq_f32(vmin, core::arch::aarch64::vminq_f32(ty1, ty2));
2325                vmax =
2326                    core::arch::aarch64::vminq_f32(vmax, core::arch::aarch64::vmaxq_f32(ty1, ty2));
2327                let tz1: core::arch::aarch64::float32x4_t =
2328                    core::arch::aarch64::vfmaq_f32(nz, core::arch::aarch64::vdupq_n_f32(bz0), iz);
2329                let tz2: core::arch::aarch64::float32x4_t =
2330                    core::arch::aarch64::vfmaq_f32(nz, core::arch::aarch64::vdupq_n_f32(bz1), iz);
2331                vmin =
2332                    core::arch::aarch64::vmaxq_f32(vmin, core::arch::aarch64::vminq_f32(tz1, tz2));
2333                vmax =
2334                    core::arch::aarch64::vminq_f32(vmax, core::arch::aarch64::vmaxq_f32(tz1, tz2));
2335                let hit_v: core::arch::aarch64::uint32x4_t = core::arch::aarch64::vandq_u32(
2336                    core::arch::aarch64::vcgeq_f32(vmax, vmin),
2337                    core::arch::aarch64::vcgeq_f32(vmax, core::arch::aarch64::vdupq_n_f32(0.0)),
2338                );
2339                let lane_bits: [u32; 4] = [1, 2, 4, 8];
2340                let mask: u8 = core::arch::aarch64::vaddvq_u32(core::arch::aarch64::vandq_u32(
2341                    hit_v,
2342                    core::arch::aarch64::vld1q_u32(lane_bits.as_ptr()),
2343                )) as u8;
2344                if mask == 0 {
2345                    return (0, f32::INFINITY);
2346                }
2347                let masked_t: core::arch::aarch64::float32x4_t = core::arch::aarch64::vbslq_f32(
2348                    hit_v,
2349                    vmin,
2350                    core::arch::aarch64::vdupq_n_f32(f32::INFINITY),
2351                );
2352                let min_t: f32 = core::arch::aarch64::vminvq_f32(masked_t);
2353                (mask, min_t)
2354            }
2355        }
2356        #[cfg(target_arch = "x86_64")]
2357        {
2358            // SAFETY: SSE2 is mandatory on `x86_64` and all slices are valid 16-byte stack arrays.
2359            unsafe {
2360                let ix: core::arch::x86_64::__m128 =
2361                    core::arch::x86_64::_mm_loadu_ps(pkt.ix.as_ptr());
2362                let iy: core::arch::x86_64::__m128 =
2363                    core::arch::x86_64::_mm_loadu_ps(pkt.iy.as_ptr());
2364                let iz: core::arch::x86_64::__m128 =
2365                    core::arch::x86_64::_mm_loadu_ps(pkt.iz.as_ptr());
2366                let nx: core::arch::x86_64::__m128 =
2367                    core::arch::x86_64::_mm_loadu_ps(neg_oi[0].as_ptr());
2368                let ny: core::arch::x86_64::__m128 =
2369                    core::arch::x86_64::_mm_loadu_ps(neg_oi[1].as_ptr());
2370                let nz: core::arch::x86_64::__m128 =
2371                    core::arch::x86_64::_mm_loadu_ps(neg_oi[2].as_ptr());
2372                let tx1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2373                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(bx0), ix),
2374                    nx,
2375                );
2376                let tx2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2377                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(bx1), ix),
2378                    nx,
2379                );
2380                let mut vmin: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
2381                    core::arch::x86_64::_mm_set1_ps(t_min),
2382                    core::arch::x86_64::_mm_min_ps(tx1, tx2),
2383                );
2384                let mut vmax: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
2385                    core::arch::x86_64::_mm_loadu_ps(t_max_4.as_ptr()),
2386                    core::arch::x86_64::_mm_max_ps(tx1, tx2),
2387                );
2388                let ty1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2389                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(by0), iy),
2390                    ny,
2391                );
2392                let ty2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2393                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(by1), iy),
2394                    ny,
2395                );
2396                vmin =
2397                    core::arch::x86_64::_mm_max_ps(vmin, core::arch::x86_64::_mm_min_ps(ty1, ty2));
2398                vmax =
2399                    core::arch::x86_64::_mm_min_ps(vmax, core::arch::x86_64::_mm_max_ps(ty1, ty2));
2400                let tz1: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2401                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(bz0), iz),
2402                    nz,
2403                );
2404                let tz2: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
2405                    core::arch::x86_64::_mm_mul_ps(core::arch::x86_64::_mm_set1_ps(bz1), iz),
2406                    nz,
2407                );
2408                vmin =
2409                    core::arch::x86_64::_mm_max_ps(vmin, core::arch::x86_64::_mm_min_ps(tz1, tz2));
2410                vmax =
2411                    core::arch::x86_64::_mm_min_ps(vmax, core::arch::x86_64::_mm_max_ps(tz1, tz2));
2412                let hit_v: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_and_ps(
2413                    core::arch::x86_64::_mm_cmpge_ps(vmax, vmin),
2414                    core::arch::x86_64::_mm_cmpge_ps(vmax, core::arch::x86_64::_mm_setzero_ps()),
2415                );
2416                let mask: u8 = core::arch::x86_64::_mm_movemask_ps(hit_v) as u8;
2417                if mask == 0 {
2418                    return (0, f32::INFINITY);
2419                }
2420                let mut t_arr: [f32; 4] = [0.0; 4];
2421                core::arch::x86_64::_mm_storeu_ps(t_arr.as_mut_ptr(), vmin);
2422                let mut min_t: f32 = f32::INFINITY;
2423                let mut m: u8 = mask;
2424                while m != 0 {
2425                    let r: usize = m.trailing_zeros() as usize;
2426                    m &= m - 1;
2427                    min_t = min_t.min(t_arr[r]);
2428                }
2429                (mask, min_t)
2430            }
2431        }
2432        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
2433        {
2434            // SAFETY: `wasm32` `simd128` is enabled at compile time and all slices are valid 16-byte stack arrays.
2435            unsafe {
2436                let ix: core::arch::wasm32::v128 =
2437                    core::arch::wasm32::v128_load(pkt.ix.as_ptr().cast());
2438                let iy: core::arch::wasm32::v128 =
2439                    core::arch::wasm32::v128_load(pkt.iy.as_ptr().cast());
2440                let iz: core::arch::wasm32::v128 =
2441                    core::arch::wasm32::v128_load(pkt.iz.as_ptr().cast());
2442                let nx: core::arch::wasm32::v128 =
2443                    core::arch::wasm32::v128_load(neg_oi[0].as_ptr().cast());
2444                let ny: core::arch::wasm32::v128 =
2445                    core::arch::wasm32::v128_load(neg_oi[1].as_ptr().cast());
2446                let nz: core::arch::wasm32::v128 =
2447                    core::arch::wasm32::v128_load(neg_oi[2].as_ptr().cast());
2448                let tx1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2449                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(bx0), ix),
2450                    nx,
2451                );
2452                let tx2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2453                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(bx1), ix),
2454                    nx,
2455                );
2456                let mut vmin: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
2457                    core::arch::wasm32::f32x4_splat(t_min),
2458                    core::arch::wasm32::f32x4_pmin(tx1, tx2),
2459                );
2460                let mut vmax: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
2461                    core::arch::wasm32::v128_load(t_max_4.as_ptr().cast()),
2462                    core::arch::wasm32::f32x4_pmax(tx1, tx2),
2463                );
2464                let ty1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2465                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(by0), iy),
2466                    ny,
2467                );
2468                let ty2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2469                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(by1), iy),
2470                    ny,
2471                );
2472                vmin =
2473                    core::arch::wasm32::f32x4_pmax(vmin, core::arch::wasm32::f32x4_pmin(ty1, ty2));
2474                vmax =
2475                    core::arch::wasm32::f32x4_pmin(vmax, core::arch::wasm32::f32x4_pmax(ty1, ty2));
2476                let tz1: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2477                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(bz0), iz),
2478                    nz,
2479                );
2480                let tz2: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
2481                    core::arch::wasm32::f32x4_mul(core::arch::wasm32::f32x4_splat(bz1), iz),
2482                    nz,
2483                );
2484                vmin =
2485                    core::arch::wasm32::f32x4_pmax(vmin, core::arch::wasm32::f32x4_pmin(tz1, tz2));
2486                vmax =
2487                    core::arch::wasm32::f32x4_pmin(vmax, core::arch::wasm32::f32x4_pmax(tz1, tz2));
2488                let hit_v: core::arch::wasm32::v128 = core::arch::wasm32::v128_and(
2489                    core::arch::wasm32::f32x4_ge(vmax, vmin),
2490                    core::arch::wasm32::f32x4_ge(vmax, core::arch::wasm32::f32x4_splat(0.0)),
2491                );
2492                let mask: u8 = core::arch::wasm32::i32x4_bitmask(hit_v) as u8;
2493                if mask == 0 {
2494                    return (0, f32::INFINITY);
2495                }
2496                let masked_t: core::arch::wasm32::v128 = core::arch::wasm32::v128_bitselect(
2497                    vmin,
2498                    core::arch::wasm32::f32x4_splat(f32::INFINITY),
2499                    hit_v,
2500                );
2501                let t0: f32 = core::arch::wasm32::f32x4_extract_lane::<0>(masked_t);
2502                let t1: f32 = core::arch::wasm32::f32x4_extract_lane::<1>(masked_t);
2503                let t2: f32 = core::arch::wasm32::f32x4_extract_lane::<2>(masked_t);
2504                let t3: f32 = core::arch::wasm32::f32x4_extract_lane::<3>(masked_t);
2505                (mask, t0.min(t1).min(t2.min(t3)))
2506            }
2507        }
2508        #[cfg(not(target_arch = "aarch64"))]
2509        #[cfg(not(target_arch = "x86_64"))]
2510        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
2511        {
2512            let mut mask: u8 = 0;
2513            let mut min_t: f32 = f32::INFINITY;
2514            for r in 0..4 {
2515                let t: f32 = BvhFlatNode::intersect_box_fma(
2516                    [bx0, by0, bz0],
2517                    [bx1, by1, bz1],
2518                    [pkt.ix[r], pkt.iy[r], pkt.iz[r]],
2519                    [neg_oi[0][r], neg_oi[1][r], neg_oi[2][r]],
2520                    t_min,
2521                    t_max_4[r],
2522                );
2523                if t.is_finite() {
2524                    mask |= 1_u8 << r;
2525                    min_t = min_t.min(t);
2526                }
2527            }
2528            (mask, min_t)
2529        }
2530    }
2531}
2532
2533/// 8-wide SoA AVX2 slab kernels for `Bvh8Node` on `x86_64`.
2534#[cfg(target_arch = "x86_64")]
2535impl Bvh8Node {
2536    /// Reads extended control register XCR0 via `XGETBV` after CPUID confirms `OSXSAVE`.
2537    ///
2538    /// # Returns
2539    ///
2540    /// - `u64` - XCR0 OS-enabled vector state mask.
2541    #[target_feature(enable = "xsave")]
2542    #[must_use]
2543    unsafe fn read_xcr0() -> u64 {
2544        // SAFETY: Caller verified CPUID leaf 1 ECX bit 27 (`OSXSAVE`) before invoking `XGETBV`.
2545        unsafe { core::arch::x86_64::_xgetbv(0) }
2546    }
2547
2548    /// Returns `true` when the active x86_64 CPU and OS kernel both support AVX2 and FMA.
2549    ///
2550    /// # Returns
2551    ///
2552    /// - `bool` - Cached runtime AVX2 + FMA availability flag.
2553    #[must_use]
2554    pub(crate) fn has_avx2_fma() -> bool {
2555        *X86_AVX2_FMA_AVAILABLE.get_or_init(|| -> bool {
2556            let max_leaf: u32 = core::arch::x86_64::__cpuid(0).eax;
2557            if max_leaf < 7 {
2558                return false;
2559            }
2560            let leaf1: core::arch::x86_64::CpuidResult = core::arch::x86_64::__cpuid(1);
2561            let req_ecx: u32 = (1_u32 << 27) | (1_u32 << 28) | (1_u32 << 12);
2562            if (leaf1.ecx & req_ecx) != req_ecx {
2563                return false;
2564            }
2565            // SAFETY: CPUID confirmed `OSXSAVE` bit 27, so `XGETBV` is enabled by the OS.
2566            let xcr0: u64 = unsafe { Self::read_xcr0() };
2567            if (xcr0 & 0x6) != 0x6 {
2568                return false;
2569            }
2570            let leaf7: core::arch::x86_64::CpuidResult = core::arch::x86_64::__cpuid_count(7, 0);
2571            (leaf7.ebx & (1_u32 << 5)) != 0
2572        })
2573    }
2574
2575    /// Creates an empty placeholder `Bvh8Node` with degenerate bounds that never hit.
2576    ///
2577    /// # Returns
2578    ///
2579    /// - `Self` - Empty 8-wide node.
2580    #[inline(always)]
2581    #[must_use]
2582    pub(crate) const fn empty() -> Self {
2583        Self {
2584            min_x: [f32::INFINITY; 8],
2585            min_y: [f32::INFINITY; 8],
2586            min_z: [f32::INFINITY; 8],
2587            max_x: [f32::INFINITY; 8],
2588            max_y: [f32::INFINITY; 8],
2589            max_z: [f32::INFINITY; 8],
2590            child: [u32::MAX; 8],
2591            leaf_count: [0; 8],
2592            valid_count: 0,
2593            _pad: [0; 23],
2594        }
2595    }
2596
2597    /// Tests a single ray simultaneously against all 8 child AABBs via x86_64 AVX2+FMA, returning `(t_near_8, 8_bit_hit_mask)`.
2598    ///
2599    /// # Arguments
2600    ///
2601    /// - `&Self` - 8-wide BVH node.
2602    /// - `[f32; 3]` - Precomputed safe reciprocal direction.
2603    /// - `[f32; 3]` - Precomputed `-origin * inv_dir`.
2604    /// - `f32` - Minimum valid distance.
2605    /// - `f32` - Maximum valid distance.
2606    ///
2607    /// # Returns
2608    ///
2609    /// - `([f32; 8], u32)` - Entry distances for all 8 children and an 8-bit hit mask masked by `valid_count`.
2610    #[target_feature(enable = "avx2", enable = "fma")]
2611    #[must_use]
2612    pub(crate) unsafe fn intersect_8_avx2(
2613        &self,
2614        inv: [f32; 3],
2615        neg_orig_inv: [f32; 3],
2616        t_min: f32,
2617        t_max: f32,
2618    ) -> ([f32; 8], u32) {
2619        let Self {
2620            min_x,
2621            min_y,
2622            min_z,
2623            max_x,
2624            max_y,
2625            max_z,
2626            valid_count,
2627            ..
2628        } = self;
2629        let valid_mask: u32 = (1_u32 << (*valid_count as u32)) - 1;
2630        let mut t_out: [f32; 8] = [f32::INFINITY; 8];
2631        // SAFETY: `Bvh8Node` is `#[repr(C, align(64))]` so every 8-lane array is 32-byte aligned,
2632        // and caller guarantees AVX2 + FMA support via `#[target_feature]`.
2633        let mask: u32 = unsafe {
2634            let ix: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_set1_ps(inv[0]);
2635            let iy: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_set1_ps(inv[1]);
2636            let iz: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_set1_ps(inv[2]);
2637            let nx: core::arch::x86_64::__m256 =
2638                core::arch::x86_64::_mm256_set1_ps(neg_orig_inv[0]);
2639            let ny: core::arch::x86_64::__m256 =
2640                core::arch::x86_64::_mm256_set1_ps(neg_orig_inv[1]);
2641            let nz: core::arch::x86_64::__m256 =
2642                core::arch::x86_64::_mm256_set1_ps(neg_orig_inv[2]);
2643            let tx1: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_fmadd_ps(
2644                core::arch::x86_64::_mm256_load_ps(min_x.as_ptr()),
2645                ix,
2646                nx,
2647            );
2648            let tx2: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_fmadd_ps(
2649                core::arch::x86_64::_mm256_load_ps(max_x.as_ptr()),
2650                ix,
2651                nx,
2652            );
2653            let mut vmin: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_max_ps(
2654                core::arch::x86_64::_mm256_set1_ps(t_min),
2655                core::arch::x86_64::_mm256_min_ps(tx1, tx2),
2656            );
2657            let mut vmax: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_min_ps(
2658                core::arch::x86_64::_mm256_set1_ps(t_max),
2659                core::arch::x86_64::_mm256_max_ps(tx1, tx2),
2660            );
2661            let ty1: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_fmadd_ps(
2662                core::arch::x86_64::_mm256_load_ps(min_y.as_ptr()),
2663                iy,
2664                ny,
2665            );
2666            let ty2: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_fmadd_ps(
2667                core::arch::x86_64::_mm256_load_ps(max_y.as_ptr()),
2668                iy,
2669                ny,
2670            );
2671            vmin = core::arch::x86_64::_mm256_max_ps(
2672                vmin,
2673                core::arch::x86_64::_mm256_min_ps(ty1, ty2),
2674            );
2675            vmax = core::arch::x86_64::_mm256_min_ps(
2676                vmax,
2677                core::arch::x86_64::_mm256_max_ps(ty1, ty2),
2678            );
2679            let tz1: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_fmadd_ps(
2680                core::arch::x86_64::_mm256_load_ps(min_z.as_ptr()),
2681                iz,
2682                nz,
2683            );
2684            let tz2: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_fmadd_ps(
2685                core::arch::x86_64::_mm256_load_ps(max_z.as_ptr()),
2686                iz,
2687                nz,
2688            );
2689            vmin = core::arch::x86_64::_mm256_max_ps(
2690                vmin,
2691                core::arch::x86_64::_mm256_min_ps(tz1, tz2),
2692            );
2693            vmax = core::arch::x86_64::_mm256_min_ps(
2694                vmax,
2695                core::arch::x86_64::_mm256_max_ps(tz1, tz2),
2696            );
2697            core::arch::x86_64::_mm256_storeu_ps(t_out.as_mut_ptr(), vmin);
2698            let hit_v: core::arch::x86_64::__m256 = core::arch::x86_64::_mm256_and_ps(
2699                core::arch::x86_64::_mm256_cmp_ps::<{ core::arch::x86_64::_CMP_GE_OQ }>(vmax, vmin),
2700                core::arch::x86_64::_mm256_cmp_ps::<{ core::arch::x86_64::_CMP_GE_OQ }>(
2701                    vmax,
2702                    core::arch::x86_64::_mm256_setzero_ps(),
2703                ),
2704            );
2705            core::arch::x86_64::_mm256_movemask_ps(hit_v) as u32
2706        };
2707        (t_out, mask & valid_mask)
2708    }
2709}
2710
2711/// Triangle construction and Möller–Trumbore ray intersection for `BvhTriangle`.
2712impl BvhTriangle {
2713    /// Creates a world-space `BvhTriangle` from three vertices and its surface `PbrMaterial`.
2714    ///
2715    /// # Arguments
2716    ///
2717    /// - `Vec3` - First vertex.
2718    /// - `Vec3` - Second vertex.
2719    /// - `Vec3` - Third vertex.
2720    /// - `PbrMaterial` - Surface PBR material.
2721    ///
2722    /// # Returns
2723    ///
2724    /// - `Self` - Precomputed BVH triangle record.
2725    #[must_use]
2726    pub fn from_points(v0: Vec3, v1: Vec3, v2: Vec3, material: PbrMaterial) -> Self {
2727        let edge1: Vec3 = v1.sub(v0);
2728        let edge2: Vec3 = v2.sub(v0);
2729        let normal: Vec3 = edge1.cross(edge2).normalize();
2730        let centroid: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
2731        let mut bounds: Aabb3D = Aabb3D::empty();
2732        bounds.expand_point(v0);
2733        bounds.expand_point(v1);
2734        bounds.expand_point(v2);
2735        Self {
2736            v0,
2737            edge1,
2738            edge2,
2739            normal,
2740            centroid,
2741            bounds,
2742            material,
2743        }
2744    }
2745
2746    /// Tests `ray` against this triangle using Möller–Trumbore returning hit distance in `(t_min, t_max)`.
2747    ///
2748    /// # Arguments
2749    ///
2750    /// - `&Self` - Triangle reference.
2751    /// - `&Ray3D` - Query ray.
2752    /// - `f32` - Minimum valid distance.
2753    /// - `f32` - Maximum valid distance.
2754    ///
2755    /// # Returns
2756    ///
2757    /// - `Option<f32>` - Parametric hit distance if intersected.
2758    #[must_use]
2759    pub fn intersect(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<f32> {
2760        let g: BvhGeomTri = BvhGeomTri::from_triangle(self);
2761        g.intersect_raw(ray.get_origin(), ray.get_direction(), t_min, t_max)
2762    }
2763}
2764
2765/// Coherent 4-ray packet constructors for `RayPacket4`.
2766impl RayPacket4 {
2767    /// Packs four `Ray3D` instances into a Structure-of-Arrays `RayPacket4`.
2768    ///
2769    /// # Arguments
2770    ///
2771    /// - `&[Ray3D; 4]` - Four world-space or object-space rays.
2772    ///
2773    /// # Returns
2774    ///
2775    /// - `Self` - Populated 4-lane ray packet.
2776    #[must_use]
2777    pub fn from_rays(rays: &[Ray3D; 4]) -> Self {
2778        let o0: Vec3 = rays[0].get_origin();
2779        let o1: Vec3 = rays[1].get_origin();
2780        let o2: Vec3 = rays[2].get_origin();
2781        let o3: Vec3 = rays[3].get_origin();
2782        let d0: Vec3 = rays[0].get_direction();
2783        let d1: Vec3 = rays[1].get_direction();
2784        let d2: Vec3 = rays[2].get_direction();
2785        let d3: Vec3 = rays[3].get_direction();
2786        let i0: Vec3 = rays[0].get_inv_direction();
2787        let i1: Vec3 = rays[1].get_inv_direction();
2788        let i2: Vec3 = rays[2].get_inv_direction();
2789        let i3: Vec3 = rays[3].get_inv_direction();
2790        Self {
2791            ox: [o0.get_x(), o1.get_x(), o2.get_x(), o3.get_x()],
2792            oy: [o0.get_y(), o1.get_y(), o2.get_y(), o3.get_y()],
2793            oz: [o0.get_z(), o1.get_z(), o2.get_z(), o3.get_z()],
2794            dx: [d0.get_x(), d1.get_x(), d2.get_x(), d3.get_x()],
2795            dy: [d0.get_y(), d1.get_y(), d2.get_y(), d3.get_y()],
2796            dz: [d0.get_z(), d1.get_z(), d2.get_z(), d3.get_z()],
2797            ix: [i0.get_x(), i1.get_x(), i2.get_x(), i3.get_x()],
2798            iy: [i0.get_y(), i1.get_y(), i2.get_y(), i3.get_y()],
2799            iz: [i0.get_z(), i1.get_z(), i2.get_z(), i3.get_z()],
2800        }
2801    }
2802}
2803
2804/// Binned Surface Area Heuristic (SAH) BVH4/BVH8 construction and SIMD single-ray + 4-ray packet traversal for `Bvh3D`.
2805impl Bvh3D {
2806    /// Recursively flattens `nodes[src_idx]` into `flat_nodes[dst_idx]` and packs leaf `BvhTri4` packets.
2807    ///
2808    /// # Arguments
2809    ///
2810    /// - `&[BvhNode3D]` - Source hierarchical BVH nodes.
2811    /// - `&[BvhGeomTri]` - Partitioned 36-byte triangle geometry array.
2812    /// - `&mut Vec<BvhTri4>` - Destination 4-wide SoA leaf packet buffer.
2813    /// - `&mut Vec<BvhFlatNode>` - Destination 32-byte sibling-paired flat node buffer.
2814    /// - `&mut [u32]` - Mapping from source BVH node index to flat node index for incremental refit.
2815    /// - `usize` - Source index in `nodes`.
2816    /// - `usize` - Pre-reserved destination index in `flat_nodes`.
2817    fn flatten_sibling_pair(
2818        nodes: &[BvhNode3D],
2819        geom: &[BvhGeomTri],
2820        leaf_packets: &mut Vec<BvhTri4>,
2821        flat_nodes: &mut Vec<BvhFlatNode>,
2822        node_to_flat: &mut [u32],
2823        src_idx: usize,
2824        dst_idx: usize,
2825    ) {
2826        if src_idx < node_to_flat.len() {
2827            node_to_flat[src_idx] = dst_idx as u32;
2828        }
2829        let n: &BvhNode3D = &nodes[src_idx];
2830        let mn: Vec3 = n.get_bounds().get_min();
2831        let mx: Vec3 = n.get_bounds().get_max();
2832        let tc: u32 = n.get_tri_count();
2833        if tc > 0 {
2834            let first_tri: usize = n.get_first_tri() as usize;
2835            let end_tri: usize = first_tri + (tc as usize);
2836            let pkt_first: u32 = leaf_packets.len() as u32;
2837            let mut cursor: usize = first_tri;
2838            while cursor < end_tri {
2839                let next_end: usize = (cursor + 4).min(end_tri);
2840                leaf_packets.push(BvhTri4::from_geom_chunk(
2841                    &geom[cursor..next_end],
2842                    cursor as u32,
2843                ));
2844                cursor = next_end;
2845            }
2846            let pkt_count: u32 = (leaf_packets.len() as u32) - pkt_first;
2847            flat_nodes[dst_idx] = BvhFlatNode {
2848                min: [mn.get_x(), mn.get_y(), mn.get_z()],
2849                child_or_first: pkt_first,
2850                max: [mx.get_x(), mx.get_y(), mx.get_z()],
2851                tri_count: pkt_count,
2852            };
2853        } else {
2854            let first_child: usize = flat_nodes.len();
2855            flat_nodes.push(BvhFlatNode::empty());
2856            flat_nodes.push(BvhFlatNode::empty());
2857            flat_nodes[dst_idx] = BvhFlatNode {
2858                min: [mn.get_x(), mn.get_y(), mn.get_z()],
2859                child_or_first: first_child as u32,
2860                max: [mx.get_x(), mx.get_y(), mx.get_z()],
2861                tri_count: 0,
2862            };
2863            Self::flatten_sibling_pair(
2864                nodes,
2865                geom,
2866                leaf_packets,
2867                flat_nodes,
2868                node_to_flat,
2869                n.get_left() as usize,
2870                first_child,
2871            );
2872            Self::flatten_sibling_pair(
2873                nodes,
2874                geom,
2875                leaf_packets,
2876                flat_nodes,
2877                node_to_flat,
2878                n.get_right() as usize,
2879                first_child + 1,
2880            );
2881        }
2882    }
2883
2884    /// Recursively collapses the binary SAH tree `nodes` into compact 128-byte `Bvh4Node` entries reusing `leaf_packets`.
2885    ///
2886    /// # Arguments
2887    ///
2888    /// - `&[BvhNode3D]` - Source binary SAH nodes.
2889    /// - `&[BvhFlatNode]` - Flattened sibling nodes carrying packed leaf packet indices.
2890    /// - `&[u32]` - Mapping from `nodes[src_idx]` to `flat_nodes[flat_idx]`.
2891    /// - `&mut Vec<Bvh4Node>` - Destination compact 4-wide node array.
2892    /// - `&mut Vec<[u32; 4]>` - Destination source-node index map for zero-alloc O(N) refits.
2893    /// - `usize` - Binary source node index.
2894    /// - `usize` - Reserved destination index in `bvh4_nodes`.
2895    fn collapse_to_bvh4(
2896        nodes: &[BvhNode3D],
2897        flat_nodes: &[BvhFlatNode],
2898        node_to_flat: &[u32],
2899        bvh4_nodes: &mut Vec<Bvh4Node>,
2900        bvh4_src: &mut Vec<[u32; 4]>,
2901        src_idx: usize,
2902        dst_idx: usize,
2903    ) {
2904        let root_n: &BvhNode3D = &nodes[src_idx];
2905        let mut children: [usize; 4] = [0; 4];
2906        let mut len: usize;
2907        if root_n.get_tri_count() > 0 {
2908            children[0] = src_idx;
2909            len = 1;
2910        } else {
2911            children[0] = root_n.get_left() as usize;
2912            children[1] = root_n.get_right() as usize;
2913            len = 2;
2914            while len < 4 {
2915                let mut best_slot: Option<usize> = None;
2916                let mut best_area: f32 = -1.0;
2917                for (slot, &c_idx) in children.iter().take(len).enumerate() {
2918                    if nodes[c_idx].get_tri_count() == 0 {
2919                        let area: f32 = nodes[c_idx].get_bounds().surface_area();
2920                        if area > best_area {
2921                            best_area = area;
2922                            best_slot = Some(slot);
2923                        }
2924                    }
2925                }
2926                let Some(expand_slot) = best_slot else {
2927                    break;
2928                };
2929                let expand_node: &BvhNode3D = &nodes[children[expand_slot]];
2930                children[expand_slot] = expand_node.get_left() as usize;
2931                children[len] = expand_node.get_right() as usize;
2932                len += 1;
2933            }
2934        }
2935        let mut node4: Bvh4Node = Bvh4Node::empty();
2936        let mut src_ids: [u32; 4] = [u32::MAX; 4];
2937        node4.valid_count = len as u8;
2938        let mut interior_recur: [(usize, usize); 4] = [(0, 0); 4];
2939        let mut interior_len: usize = 0;
2940        for (lane, &c_idx) in children.iter().take(len).enumerate() {
2941            let cn: &BvhNode3D = &nodes[c_idx];
2942            let mn: Vec3 = cn.get_bounds().get_min();
2943            let mx: Vec3 = cn.get_bounds().get_max();
2944            node4.min_x[lane] = mn.get_x();
2945            node4.min_y[lane] = mn.get_y();
2946            node4.min_z[lane] = mn.get_z();
2947            node4.max_x[lane] = mx.get_x();
2948            node4.max_y[lane] = mx.get_y();
2949            node4.max_z[lane] = mx.get_z();
2950            src_ids[lane] = c_idx as u32;
2951            if cn.get_tri_count() > 0 {
2952                let flat: &BvhFlatNode = &flat_nodes[node_to_flat[c_idx] as usize];
2953                node4.child[lane] = flat.child_or_first;
2954                node4.leaf_count[lane] = flat.tri_count.min(255) as u8;
2955            } else {
2956                let next_dst: usize = bvh4_nodes.len();
2957                bvh4_nodes.push(Bvh4Node::empty());
2958                bvh4_src.push([u32::MAX; 4]);
2959                node4.child[lane] = next_dst as u32;
2960                node4.leaf_count[lane] = 0;
2961                interior_recur[interior_len] = (c_idx, next_dst);
2962                interior_len += 1;
2963            }
2964        }
2965        bvh4_nodes[dst_idx] = node4;
2966        bvh4_src[dst_idx] = src_ids;
2967        for &(c_src, c_dst) in interior_recur.iter().take(interior_len) {
2968            Self::collapse_to_bvh4(
2969                nodes,
2970                flat_nodes,
2971                node_to_flat,
2972                bvh4_nodes,
2973                bvh4_src,
2974                c_src,
2975                c_dst,
2976            );
2977        }
2978    }
2979
2980    /// Recursively collapses the binary SAH tree `nodes` into compact 256-byte `Bvh8Node` entries on `x86_64`.
2981    ///
2982    /// # Arguments
2983    ///
2984    /// - `&[BvhNode3D]` - Source binary SAH nodes.
2985    /// - `&[BvhFlatNode]` - Flattened sibling nodes carrying packed leaf packet indices.
2986    /// - `&[u32]` - Mapping from `nodes[src_idx]` to `flat_nodes[flat_idx]`.
2987    /// - `&mut Vec<Bvh8Node>` - Destination compact 8-wide node array.
2988    /// - `&mut Vec<[u32; 8]>` - Destination source-node index map for zero-alloc O(N) refits.
2989    /// - `usize` - Binary source node index.
2990    /// - `usize` - Reserved destination index in `bvh8_nodes`.
2991    #[cfg(target_arch = "x86_64")]
2992    fn collapse_to_bvh8(
2993        nodes: &[BvhNode3D],
2994        flat_nodes: &[BvhFlatNode],
2995        node_to_flat: &[u32],
2996        bvh8_nodes: &mut Vec<Bvh8Node>,
2997        bvh8_src: &mut Vec<[u32; 8]>,
2998        src_idx: usize,
2999        dst_idx: usize,
3000    ) {
3001        let root_n: &BvhNode3D = &nodes[src_idx];
3002        let mut children: [usize; 8] = [0; 8];
3003        let mut len: usize;
3004        if root_n.get_tri_count() > 0 {
3005            children[0] = src_idx;
3006            len = 1;
3007        } else {
3008            children[0] = root_n.get_left() as usize;
3009            children[1] = root_n.get_right() as usize;
3010            len = 2;
3011            while len < 8 {
3012                let mut best_slot: Option<usize> = None;
3013                let mut best_area: f32 = -1.0;
3014                for (slot, &c_idx) in children.iter().take(len).enumerate() {
3015                    if nodes[c_idx].get_tri_count() == 0 {
3016                        let area: f32 = nodes[c_idx].get_bounds().surface_area();
3017                        if area > best_area {
3018                            best_area = area;
3019                            best_slot = Some(slot);
3020                        }
3021                    }
3022                }
3023                let Some(expand_slot) = best_slot else {
3024                    break;
3025                };
3026                let expand_node: &BvhNode3D = &nodes[children[expand_slot]];
3027                children[expand_slot] = expand_node.get_left() as usize;
3028                children[len] = expand_node.get_right() as usize;
3029                len += 1;
3030            }
3031        }
3032        let mut node8: Bvh8Node = Bvh8Node::empty();
3033        let mut src_ids: [u32; 8] = [u32::MAX; 8];
3034        node8.valid_count = len as u8;
3035        let mut interior_recur: [(usize, usize); 8] = [(0, 0); 8];
3036        let mut interior_len: usize = 0;
3037        for (lane, &c_idx) in children.iter().take(len).enumerate() {
3038            let cn: &BvhNode3D = &nodes[c_idx];
3039            let mn: Vec3 = cn.get_bounds().get_min();
3040            let mx: Vec3 = cn.get_bounds().get_max();
3041            node8.min_x[lane] = mn.get_x();
3042            node8.min_y[lane] = mn.get_y();
3043            node8.min_z[lane] = mn.get_z();
3044            node8.max_x[lane] = mx.get_x();
3045            node8.max_y[lane] = mx.get_y();
3046            node8.max_z[lane] = mx.get_z();
3047            src_ids[lane] = c_idx as u32;
3048            if cn.get_tri_count() > 0 {
3049                let flat: &BvhFlatNode = &flat_nodes[node_to_flat[c_idx] as usize];
3050                node8.child[lane] = flat.child_or_first;
3051                node8.leaf_count[lane] = flat.tri_count.min(255) as u8;
3052            } else {
3053                let next_dst: usize = bvh8_nodes.len();
3054                bvh8_nodes.push(Bvh8Node::empty());
3055                bvh8_src.push([u32::MAX; 8]);
3056                node8.child[lane] = next_dst as u32;
3057                node8.leaf_count[lane] = 0;
3058                interior_recur[interior_len] = (c_idx, next_dst);
3059                interior_len += 1;
3060            }
3061        }
3062        bvh8_nodes[dst_idx] = node8;
3063        bvh8_src[dst_idx] = src_ids;
3064        for &(c_src, c_dst) in interior_recur.iter().take(interior_len) {
3065            Self::collapse_to_bvh8(
3066                nodes,
3067                flat_nodes,
3068                node_to_flat,
3069                bvh8_nodes,
3070                bvh8_src,
3071                c_src,
3072                c_dst,
3073            );
3074        }
3075    }
3076
3077    /// Builds a tight SAH flat BVH over `triangles` and populates compact BVH4/BVH8 SIMD trees and 4-wide SoA `BvhTri4` leaf packets.
3078    ///
3079    /// # Arguments
3080    ///
3081    /// - `Vec<BvhTriangle>` - World-space or local-space triangles to index.
3082    ///
3083    /// # Returns
3084    ///
3085    /// - `Self` - Constructed SAH BVH acceleration structure.
3086    #[must_use]
3087    pub fn build(triangles: Vec<BvhTriangle>) -> Self {
3088        let tri_len: usize = triangles.len();
3089        if tri_len == 0 {
3090            return Self::default();
3091        }
3092        let mut orig_indices: Vec<u32> = Vec::with_capacity(tri_len);
3093        for idx in 0..tri_len {
3094            orig_indices.push(idx as u32);
3095        }
3096        let mut bvh: Self = Self {
3097            nodes: Vec::with_capacity(tri_len * 2 + 1),
3098            triangles,
3099            geom: Vec::with_capacity(tri_len),
3100            leaf_packets: Vec::with_capacity(tri_len.div_ceil(4) + 16),
3101            flat_nodes: Vec::with_capacity(tri_len * 2 + 2),
3102            bvh4_nodes: Vec::with_capacity(tri_len.div_ceil(2) + 4),
3103            bvh4_src_children: Vec::with_capacity(tri_len.div_ceil(2) + 4),
3104            root_min: [0.0; 3],
3105            root_max: [0.0; 3],
3106            #[cfg(target_arch = "x86_64")]
3107            bvh8_nodes: Vec::with_capacity(tri_len.div_ceil(4) + 4),
3108            #[cfg(target_arch = "x86_64")]
3109            bvh8_src_children: Vec::with_capacity(tri_len.div_ceil(4) + 4),
3110            orig_indices,
3111            node_to_flat: Vec::new(),
3112            build_sah_cost: 0.0,
3113        };
3114        if !bvh.get_triangles().is_empty() {
3115            bvh.rebuild_current();
3116        }
3117        bvh
3118    }
3119
3120    /// Rebuilds the SAH BVH, flat nodes, BVH4/BVH8 SIMD nodes, and leaf packets in place from `source`, reusing existing capacities with zero heap allocations.
3121    ///
3122    /// # Arguments
3123    ///
3124    /// - `&Self` - Mutable BVH structure to rebuild in place.
3125    /// - `&[BvhTriangle]` - Replacement triangle slice.
3126    pub fn rebuild_in_place(&mut self, source: &[BvhTriangle]) {
3127        let tri_len: usize = source.len();
3128        let Self {
3129            nodes,
3130            triangles,
3131            geom,
3132            leaf_packets,
3133            flat_nodes,
3134            bvh4_nodes,
3135            bvh4_src_children,
3136            root_min,
3137            root_max,
3138            #[cfg(target_arch = "x86_64")]
3139            bvh8_nodes,
3140            #[cfg(target_arch = "x86_64")]
3141            bvh8_src_children,
3142            orig_indices,
3143            node_to_flat,
3144            build_sah_cost,
3145        } = self;
3146        nodes.clear();
3147        triangles.clear();
3148        geom.clear();
3149        leaf_packets.clear();
3150        flat_nodes.clear();
3151        bvh4_nodes.clear();
3152        bvh4_src_children.clear();
3153        #[cfg(target_arch = "x86_64")]
3154        {
3155            bvh8_nodes.clear();
3156            bvh8_src_children.clear();
3157        }
3158        orig_indices.clear();
3159        node_to_flat.clear();
3160        *root_min = [0.0; 3];
3161        *root_max = [0.0; 3];
3162        *build_sah_cost = 0.0;
3163        if tri_len == 0 {
3164            return;
3165        }
3166        triangles.extend_from_slice(source);
3167        let max_nodes: usize = tri_len.saturating_mul(2).saturating_add(8);
3168        if nodes.capacity() < max_nodes {
3169            nodes.reserve(max_nodes - nodes.capacity());
3170        }
3171        if geom.capacity() < tri_len {
3172            geom.reserve(tri_len - geom.capacity());
3173        }
3174        let max_leaves: usize = tri_len.div_ceil(4).saturating_add(16);
3175        if leaf_packets.capacity() < max_leaves {
3176            leaf_packets.reserve(max_leaves - leaf_packets.capacity());
3177        }
3178        if flat_nodes.capacity() < max_nodes {
3179            flat_nodes.reserve(max_nodes - flat_nodes.capacity());
3180        }
3181        let max_bvh4: usize = tri_len.div_ceil(2).saturating_add(8);
3182        if bvh4_nodes.capacity() < max_bvh4 {
3183            bvh4_nodes.reserve(max_bvh4 - bvh4_nodes.capacity());
3184        }
3185        if bvh4_src_children.capacity() < max_bvh4 {
3186            bvh4_src_children.reserve(max_bvh4 - bvh4_src_children.capacity());
3187        }
3188        if node_to_flat.capacity() < max_nodes {
3189            node_to_flat.reserve(max_nodes - node_to_flat.capacity());
3190        }
3191        if orig_indices.capacity() < tri_len {
3192            orig_indices.reserve(tri_len - orig_indices.capacity());
3193        }
3194        for idx in 0..tri_len {
3195            orig_indices.push(idx as u32);
3196        }
3197        self.rebuild_current();
3198    }
3199
3200    /// Reconstructs BVH hierarchy, flat nodes, SIMD BVH4/BVH8 nodes, and leaf packets in place from `self.triangles`.
3201    ///
3202    /// # Arguments
3203    ///
3204    /// - `&Self` - Mutable BVH with populated `triangles` and `orig_indices`.
3205    fn rebuild_current(&mut self) {
3206        let total: usize = self.get_triangles().len();
3207        if total == 0 {
3208            return;
3209        }
3210        let _: u32 = self.build_node(0, total);
3211        let Self {
3212            nodes,
3213            triangles,
3214            geom,
3215            leaf_packets,
3216            flat_nodes,
3217            bvh4_nodes,
3218            bvh4_src_children,
3219            root_min,
3220            root_max,
3221            #[cfg(target_arch = "x86_64")]
3222            bvh8_nodes,
3223            #[cfg(target_arch = "x86_64")]
3224            bvh8_src_children,
3225            node_to_flat,
3226            build_sah_cost,
3227            ..
3228        } = self;
3229        geom.clear();
3230        for tri in triangles.iter() {
3231            geom.push(BvhGeomTri::from_triangle(tri));
3232        }
3233        leaf_packets.clear();
3234        flat_nodes.clear();
3235        bvh4_nodes.clear();
3236        bvh4_src_children.clear();
3237        node_to_flat.clear();
3238        node_to_flat.resize(nodes.len(), 0);
3239        if !nodes.is_empty() {
3240            let rmin: Vec3 = nodes[0].get_bounds().get_min();
3241            let rmax: Vec3 = nodes[0].get_bounds().get_max();
3242            *root_min = [rmin.get_x(), rmin.get_y(), rmin.get_z()];
3243            *root_max = [rmax.get_x(), rmax.get_y(), rmax.get_z()];
3244            flat_nodes.push(BvhFlatNode::empty());
3245            flat_nodes.push(BvhFlatNode::empty());
3246            Self::flatten_sibling_pair(nodes, geom, leaf_packets, flat_nodes, node_to_flat, 0, 0);
3247            bvh4_nodes.push(Bvh4Node::empty());
3248            bvh4_src_children.push([u32::MAX; 4]);
3249            Self::collapse_to_bvh4(
3250                nodes,
3251                flat_nodes,
3252                node_to_flat,
3253                bvh4_nodes,
3254                bvh4_src_children,
3255                0,
3256                0,
3257            );
3258            #[cfg(target_arch = "x86_64")]
3259            {
3260                bvh8_nodes.clear();
3261                bvh8_src_children.clear();
3262                if Bvh8Node::has_avx2_fma() {
3263                    bvh8_nodes.push(Bvh8Node::empty());
3264                    bvh8_src_children.push([u32::MAX; 8]);
3265                    Self::collapse_to_bvh8(
3266                        nodes,
3267                        flat_nodes,
3268                        node_to_flat,
3269                        bvh8_nodes,
3270                        bvh8_src_children,
3271                        0,
3272                        0,
3273                    );
3274                }
3275            }
3276            let mut sah_sum: f32 = 0.0;
3277            for n in nodes.iter() {
3278                let area: f32 = n.get_bounds().surface_area();
3279                if n.get_tri_count() > 0 {
3280                    sah_sum += area * (n.get_tri_count() as f32);
3281                } else {
3282                    sah_sum += area * 0.5;
3283                }
3284            }
3285            *build_sah_cost = sah_sum.max(1e-5);
3286        }
3287    }
3288
3289    /// Returns `true` when this BVH contains zero indexed triangles.
3290    ///
3291    /// # Arguments
3292    ///
3293    /// - `&Self` - BVH reference.
3294    ///
3295    /// # Returns
3296    ///
3297    /// - `bool` - `true` if empty.
3298    #[must_use]
3299    pub fn is_empty(&self) -> bool {
3300        self.get_triangles().is_empty()
3301    }
3302
3303    /// Computes the current SAH surface-area traversal cost across all BVH nodes.
3304    ///
3305    /// # Arguments
3306    ///
3307    /// - `&Self` - BVH reference.
3308    ///
3309    /// # Returns
3310    ///
3311    /// - `f32` - Current weighted surface-area cost.
3312    #[must_use]
3313    pub fn surface_area_cost(&self) -> f32 {
3314        let mut cost: f32 = 0.0;
3315        for n in self.get_nodes().iter() {
3316            let area: f32 = n.get_bounds().surface_area();
3317            if n.get_tri_count() > 0 {
3318                cost += area * (n.get_tri_count() as f32);
3319            } else {
3320                cost += area * 0.5;
3321            }
3322        }
3323        cost
3324    }
3325
3326    /// Returns `true` when incremental refits have inflated node bounds past `max_cost_ratio * build_sah_cost` and warrant a fresh SAH rebuild.
3327    ///
3328    /// # Arguments
3329    ///
3330    /// - `&Self` - BVH reference.
3331    /// - `f32` - Maximum acceptable SAH cost ratio (e.g. `1.65`).
3332    ///
3333    /// # Returns
3334    ///
3335    /// - `bool` - `true` when a full rebuild should replace incremental refitting.
3336    #[must_use]
3337    pub fn needs_rebuild_after_refit(&self, max_cost_ratio: f32) -> bool {
3338        if self.is_empty() {
3339            return false;
3340        }
3341        let base: f32 = self.get_build_sah_cost().max(1e-5);
3342        self.surface_area_cost() > base * max_cost_ratio.max(1.05)
3343    }
3344
3345    /// Performs an O(N) zero-allocation bottom-up BVH refit from `source_triangles` updating binary, flat, BVH4, and BVH8 bounds in place.
3346    ///
3347    /// # Arguments
3348    ///
3349    /// - `&Self` - Mutable BVH instance.
3350    /// - `&[BvhTriangle]` - Updated world-space triangles in original submission order.
3351    ///
3352    /// # Returns
3353    ///
3354    /// - `bool` - `true` when refit succeeded in place; `false` when triangle count or structure requires a full rebuild.
3355    pub fn refit_from_source(&mut self, source_triangles: &[BvhTriangle]) -> bool {
3356        let Self {
3357            nodes,
3358            triangles,
3359            geom,
3360            leaf_packets,
3361            flat_nodes,
3362            bvh4_nodes,
3363            bvh4_src_children,
3364            root_min,
3365            root_max,
3366            #[cfg(target_arch = "x86_64")]
3367            bvh8_nodes,
3368            #[cfg(target_arch = "x86_64")]
3369            bvh8_src_children,
3370            orig_indices,
3371            node_to_flat,
3372            ..
3373        } = self;
3374        let count: usize = source_triangles.len();
3375        if count == 0
3376            || triangles.len() != count
3377            || orig_indices.len() != count
3378            || nodes.is_empty()
3379            || node_to_flat.len() != nodes.len()
3380        {
3381            return false;
3382        }
3383        for slot in 0..count {
3384            let src_idx: usize = orig_indices[slot] as usize;
3385            if src_idx >= count {
3386                return false;
3387            }
3388            let updated: BvhTriangle = source_triangles[src_idx];
3389            triangles[slot] = updated;
3390            geom[slot] = BvhGeomTri::from_triangle(&updated);
3391        }
3392        for node_idx in (0..nodes.len()).rev() {
3393            let tc: u32 = nodes[node_idx].get_tri_count();
3394            let flat_idx: usize = node_to_flat[node_idx] as usize;
3395            if tc > 0 {
3396                let first: usize = nodes[node_idx].get_first_tri() as usize;
3397                let end: usize = (first + (tc as usize)).min(count);
3398                let mut bounds: Aabb3D = Aabb3D::empty();
3399                for tri in triangles[first..end].iter() {
3400                    bounds.expand_box(tri.get_bounds());
3401                }
3402                nodes[node_idx].set_bounds(bounds);
3403                if let Some(flat_node) = flat_nodes.get_mut(flat_idx) {
3404                    let mn: Vec3 = bounds.get_min();
3405                    let mx: Vec3 = bounds.get_max();
3406                    flat_node.min = [mn.get_x(), mn.get_y(), mn.get_z()];
3407                    flat_node.max = [mx.get_x(), mx.get_y(), mx.get_z()];
3408                    let mut pkt_idx: usize = flat_node.child_or_first as usize;
3409                    let mut cursor: usize = first;
3410                    while cursor < end && pkt_idx < leaf_packets.len() {
3411                        let next_end: usize = (cursor + 4).min(end);
3412                        leaf_packets[pkt_idx] =
3413                            BvhTri4::from_geom_chunk(&geom[cursor..next_end], cursor as u32);
3414                        cursor = next_end;
3415                        pkt_idx += 1;
3416                    }
3417                }
3418            } else {
3419                let left_idx: usize = nodes[node_idx].get_left() as usize;
3420                let right_idx: usize = nodes[node_idx].get_right() as usize;
3421                let mut bounds: Aabb3D = nodes[left_idx].get_bounds();
3422                bounds.expand_box(nodes[right_idx].get_bounds());
3423                nodes[node_idx].set_bounds(bounds);
3424                if let Some(flat_node) = flat_nodes.get_mut(flat_idx) {
3425                    let mn: Vec3 = bounds.get_min();
3426                    let mx: Vec3 = bounds.get_max();
3427                    flat_node.min = [mn.get_x(), mn.get_y(), mn.get_z()];
3428                    flat_node.max = [mx.get_x(), mx.get_y(), mx.get_z()];
3429                }
3430            }
3431        }
3432        let rmin: Vec3 = nodes[0].get_bounds().get_min();
3433        let rmax: Vec3 = nodes[0].get_bounds().get_max();
3434        *root_min = [rmin.get_x(), rmin.get_y(), rmin.get_z()];
3435        *root_max = [rmax.get_x(), rmax.get_y(), rmax.get_z()];
3436        for (n4, srcs) in bvh4_nodes.iter_mut().zip(bvh4_src_children.iter()) {
3437            let vcnt: usize = n4.valid_count as usize;
3438            for lane in 0..vcnt {
3439                let sidx: usize = srcs[lane] as usize;
3440                if let Some(cn) = nodes.get(sidx) {
3441                    let mn: Vec3 = cn.get_bounds().get_min();
3442                    let mx: Vec3 = cn.get_bounds().get_max();
3443                    n4.min_x[lane] = mn.get_x();
3444                    n4.min_y[lane] = mn.get_y();
3445                    n4.min_z[lane] = mn.get_z();
3446                    n4.max_x[lane] = mx.get_x();
3447                    n4.max_y[lane] = mx.get_y();
3448                    n4.max_z[lane] = mx.get_z();
3449                }
3450            }
3451        }
3452        #[cfg(target_arch = "x86_64")]
3453        for (n8, srcs) in bvh8_nodes.iter_mut().zip(bvh8_src_children.iter()) {
3454            let vcnt: usize = n8.valid_count as usize;
3455            for lane in 0..vcnt {
3456                let sidx: usize = srcs[lane] as usize;
3457                if let Some(cn) = nodes.get(sidx) {
3458                    let mn: Vec3 = cn.get_bounds().get_min();
3459                    let mx: Vec3 = cn.get_bounds().get_max();
3460                    n8.min_x[lane] = mn.get_x();
3461                    n8.min_y[lane] = mn.get_y();
3462                    n8.min_z[lane] = mn.get_z();
3463                    n8.max_x[lane] = mx.get_x();
3464                    n8.max_y[lane] = mx.get_y();
3465                    n8.max_z[lane] = mx.get_z();
3466                }
3467            }
3468        }
3469        true
3470    }
3471
3472    /// Extracts the `axis` coordinate (`0 = x`, `1 = y`, `2 = z`) from vector `v`.
3473    ///
3474    /// # Arguments
3475    ///
3476    /// - `Vec3` - Source 3D vector.
3477    /// - `usize` - Axis index.
3478    ///
3479    /// # Returns
3480    ///
3481    /// - `f32` - Selected scalar component.
3482    #[must_use]
3483    fn vec_axis(v: Vec3, axis: usize) -> f32 {
3484        match axis {
3485            0 => v.get_x(),
3486            1 => v.get_y(),
3487            _ => v.get_z(),
3488        }
3489    }
3490
3491    /// Evaluates 12-bin Surface Area Heuristic splits across all three axes and returns `(best_axis, best_split_pos)`.
3492    ///
3493    /// # Arguments
3494    ///
3495    /// - `&[BvhTriangle]` - Active triangle range.
3496    /// - `Aabb3D` - Centroid bounding box of the range.
3497    /// - `f32` - Parent bounding-box surface area.
3498    ///
3499    /// # Returns
3500    ///
3501    /// - `Option<(usize, f32)>` - Optimal split axis and threshold if cheaper than forming a leaf.
3502    #[must_use]
3503    fn find_sah_split(
3504        tris: &[BvhTriangle],
3505        cent_bounds: Aabb3D,
3506        parent_area: f32,
3507    ) -> Option<(usize, f32)> {
3508        let bins: usize = 12;
3509        let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
3510        let exts: [f32; 3] = [extent.get_x(), extent.get_y(), extent.get_z()];
3511        let cmins: [f32; 3] = [
3512            cent_bounds.get_min().get_x(),
3513            cent_bounds.get_min().get_y(),
3514            cent_bounds.get_min().get_z(),
3515        ];
3516        let active: [bool; 3] = [exts[0] >= 1e-5, exts[1] >= 1e-5, exts[2] >= 1e-5];
3517        let scales: [f32; 3] = [
3518            if active[0] {
3519                (bins as f32) / exts[0]
3520            } else {
3521                0.0
3522            },
3523            if active[1] {
3524                (bins as f32) / exts[1]
3525            } else {
3526                0.0
3527            },
3528            if active[2] {
3529                (bins as f32) / exts[2]
3530            } else {
3531                0.0
3532            },
3533        ];
3534        let mut bin_bounds: [[Aabb3D; 12]; 3] = [[Aabb3D::empty(); 12]; 3];
3535        let mut bin_counts: [[u32; 12]; 3] = [[0; 12]; 3];
3536        for tri in tris.iter() {
3537            let c: Vec3 = tri.get_centroid();
3538            let tb: Aabb3D = tri.get_bounds();
3539            if active[0] {
3540                let b0: usize = (((c.get_x() - cmins[0]) * scales[0]) as usize).min(bins - 1);
3541                bin_counts[0][b0] += 1;
3542                bin_bounds[0][b0].expand_box(tb);
3543            }
3544            if active[1] {
3545                let b1: usize = (((c.get_y() - cmins[1]) * scales[1]) as usize).min(bins - 1);
3546                bin_counts[1][b1] += 1;
3547                bin_bounds[1][b1].expand_box(tb);
3548            }
3549            if active[2] {
3550                let b2: usize = (((c.get_z() - cmins[2]) * scales[2]) as usize).min(bins - 1);
3551                bin_counts[2][b2] += 1;
3552                bin_bounds[2][b2].expand_box(tb);
3553            }
3554        }
3555        let mut best_cost: f32 = (tris.len() as f32) * parent_area;
3556        let mut best_split: Option<(usize, f32)> = None;
3557        for axis in 0..3 {
3558            if !active[axis] {
3559                continue;
3560            }
3561            let counts: &[u32; 12] = &bin_counts[axis];
3562            let bounds_arr: &[Aabb3D; 12] = &bin_bounds[axis];
3563            let mut left_area: [f32; 11] = [0.0; 11];
3564            let mut left_count: [u32; 11] = [0; 11];
3565            let mut acc_box: Aabb3D = Aabb3D::empty();
3566            let mut acc_cnt: u32 = 0;
3567            for i in 0..(bins - 1) {
3568                acc_cnt += counts[i];
3569                if counts[i] > 0 {
3570                    acc_box.expand_box(bounds_arr[i]);
3571                }
3572                left_count[i] = acc_cnt;
3573                left_area[i] = if acc_cnt > 0 {
3574                    acc_box.surface_area()
3575                } else {
3576                    0.0
3577                };
3578            }
3579            let mut r_box: Aabb3D = Aabb3D::empty();
3580            let mut r_cnt: u32 = 0;
3581            let step: f32 = exts[axis] / (bins as f32);
3582            for i in (1..bins).rev() {
3583                r_cnt += counts[i];
3584                if counts[i] > 0 {
3585                    r_box.expand_box(bounds_arr[i]);
3586                }
3587                let l_cnt: u32 = left_count[i - 1];
3588                if l_cnt == 0 || r_cnt == 0 {
3589                    continue;
3590                }
3591                let r_area: f32 = r_box.surface_area();
3592                let cost: f32 =
3593                    0.5 * parent_area + (l_cnt as f32) * left_area[i - 1] + (r_cnt as f32) * r_area;
3594                if cost < best_cost {
3595                    best_cost = cost;
3596                    let split_pos: f32 = cmins[axis] + (i as f32) * step;
3597                    best_split = Some((axis, split_pos));
3598                }
3599            }
3600        }
3601        best_split
3602    }
3603
3604    /// Recursively partitions `triangles[start..end]` via binned SAH in DFS pre-order and appends a `BvhNode3D`.
3605    ///
3606    /// # Arguments
3607    ///
3608    /// - `&Self` - Mutable BVH builder reference.
3609    /// - `usize` - Inclusive start index.
3610    /// - `usize` - Exclusive end index.
3611    ///
3612    /// # Returns
3613    ///
3614    /// - `u32` - Index of the created node in `self.nodes`.
3615    fn build_node(&mut self, start: usize, end: usize) -> u32 {
3616        let count: usize = end - start;
3617        let mut bounds: Aabb3D = Aabb3D::empty();
3618        let mut cent_bounds: Aabb3D = Aabb3D::empty();
3619        for tri in self.get_triangles()[start..end].iter() {
3620            bounds.expand_box(tri.get_bounds());
3621            cent_bounds.expand_point(tri.get_centroid());
3622        }
3623        let node_idx: u32 = self.get_nodes().len() as u32;
3624        self.get_mut_nodes().push(BvhNode3D {
3625            bounds,
3626            left: 0,
3627            right: 0,
3628            first_tri: start as u32,
3629            tri_count: count as u32,
3630        });
3631        if count <= 4 {
3632            return node_idx;
3633        }
3634        let parent_area: f32 = bounds.surface_area().max(1e-6);
3635        let split_opt: Option<(usize, f32)> =
3636            Self::find_sah_split(&self.get_triangles()[start..end], cent_bounds, parent_area);
3637        let mid: usize = if let Some((axis, split_pos)) = split_opt {
3638            let Self {
3639                triangles,
3640                orig_indices,
3641                ..
3642            } = self;
3643            let slice: &mut [BvhTriangle] = &mut triangles[start..end];
3644            let idx_slice: &mut [u32] = &mut orig_indices[start..end];
3645            let mut i: usize = 0;
3646            let mut j: usize = slice.len();
3647            while i < j {
3648                if Self::vec_axis(slice[i].get_centroid(), axis) < split_pos {
3649                    i += 1;
3650                } else {
3651                    j -= 1;
3652                    slice.swap(i, j);
3653                    idx_slice.swap(i, j);
3654                }
3655            }
3656            if i == 0 || i == count {
3657                start + count / 2
3658            } else {
3659                start + i
3660            }
3661        } else if count <= 6 {
3662            return node_idx;
3663        } else {
3664            let extent: Vec3 = cent_bounds.get_max().sub(cent_bounds.get_min());
3665            let axis: usize =
3666                if extent.get_x() >= extent.get_y() && extent.get_x() >= extent.get_z() {
3667                    0
3668                } else if extent.get_y() >= extent.get_z() {
3669                    1
3670                } else {
3671                    2
3672                };
3673            let mid_pos: f32 =
3674                Self::vec_axis(cent_bounds.get_min(), axis) + Self::vec_axis(extent, axis) * 0.5;
3675            let Self {
3676                triangles,
3677                orig_indices,
3678                ..
3679            } = self;
3680            let slice: &mut [BvhTriangle] = &mut triangles[start..end];
3681            let idx_slice: &mut [u32] = &mut orig_indices[start..end];
3682            let mut i: usize = 0;
3683            let mut j: usize = slice.len();
3684            while i < j {
3685                if Self::vec_axis(slice[i].get_centroid(), axis) < mid_pos {
3686                    i += 1;
3687                } else {
3688                    j -= 1;
3689                    slice.swap(i, j);
3690                    idx_slice.swap(i, j);
3691                }
3692            }
3693            if i == 0 || i == count {
3694                start + count / 2
3695            } else {
3696                start + i
3697            }
3698        };
3699        let left_idx: u32 = self.build_node(start, mid);
3700        let right_idx: u32 = self.build_node(mid, end);
3701        let node: &mut BvhNode3D = &mut self.get_mut_nodes()[node_idx as usize];
3702        node.set_left(left_idx);
3703        node.set_right(right_idx);
3704        node.set_tri_count(0);
3705        node_idx
3706    }
3707
3708    /// Traces a shadow/occlusion ray using SIMD BVH4/BVH8 nodes, 4-wide SoA `BvhTri4` packets, and a 1-triangle occluder cache.
3709    ///
3710    /// # Arguments
3711    ///
3712    /// - `&Self` - BVH reference.
3713    /// - `Vec3` - Ray origin.
3714    /// - `Vec3` - Unit ray direction.
3715    /// - `Vec3` - Precomputed safe reciprocal ray direction.
3716    /// - `f32` - Minimum offset (shadow bias).
3717    /// - `f32` - Maximum trace distance.
3718    /// - `&mut u32` - Per-thread last-occluding triangle index cache (`u32::MAX` if empty).
3719    ///
3720    /// # Returns
3721    ///
3722    /// - `bool` - `true` if occluded by scene geometry.
3723    #[inline(always)]
3724    #[must_use]
3725    pub fn trace_any_shadow_cached(
3726        &self,
3727        origin: Vec3,
3728        dir: Vec3,
3729        inv_dir: Vec3,
3730        t_min: f32,
3731        t_max: f32,
3732        cached_tri: &mut u32,
3733    ) -> bool {
3734        let Self {
3735            bvh4_nodes,
3736            #[cfg(target_arch = "x86_64")]
3737            bvh8_nodes,
3738            root_min,
3739            root_max,
3740            geom,
3741            leaf_packets,
3742            ..
3743        } = self;
3744        if bvh4_nodes.is_empty() || leaf_packets.is_empty() {
3745            return false;
3746        }
3747        let hint: usize = *cached_tri as usize;
3748        if hint < geom.len() && geom[hint].intersect_any_raw(origin, dir, t_min, t_max) {
3749            return true;
3750        }
3751        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
3752        let dir_arr: [f32; 3] = [dir.get_x(), dir.get_y(), dir.get_z()];
3753        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
3754        let neg_orig_inv: [f32; 3] = [
3755            -orig_arr[0] * inv_arr[0],
3756            -orig_arr[1] * inv_arr[1],
3757            -orig_arr[2] * inv_arr[2],
3758        ];
3759        if !BvhFlatNode::intersect_box_fma(
3760            *root_min,
3761            *root_max,
3762            inv_arr,
3763            neg_orig_inv,
3764            t_min,
3765            t_max,
3766        )
3767        .is_finite()
3768        {
3769            return false;
3770        }
3771        #[cfg(target_arch = "x86_64")]
3772        if !bvh8_nodes.is_empty() && Bvh8Node::has_avx2_fma() {
3773            // SAFETY: Runtime CPU feature detection verified AVX2+FMA support.
3774            return unsafe {
3775                self.trace_any_shadow_bvh8_avx2(
3776                    orig_arr,
3777                    dir_arr,
3778                    inv_arr,
3779                    neg_orig_inv,
3780                    (t_min, t_max),
3781                    cached_tri,
3782                )
3783            };
3784        }
3785        let mut stack: [u32; 64] = [0; 64];
3786        let mut sp: usize = 0;
3787        let mut cur_idx: usize = 0;
3788        loop {
3789            // SAFETY: Every pushed or root index is a valid index inside `bvh4_nodes`.
3790            let n: &Bvh4Node = unsafe { bvh4_nodes.get_unchecked(cur_idx) };
3791            let (_, mut mask): ([f32; 4], u32) = n.intersect_4(inv_arr, neg_orig_inv, t_min, t_max);
3792            let mut next_interior: u32 = u32::MAX;
3793            while mask != 0 {
3794                let c: usize = mask.trailing_zeros() as usize;
3795                mask &= mask - 1;
3796                let lc: usize = n.leaf_count[c] as usize;
3797                if lc > 0 {
3798                    let first_pkt: usize = n.child[c] as usize;
3799                    for pkt_i in first_pkt..(first_pkt + lc) {
3800                        // SAFETY: Leaf packet ranges are validated during BVH build.
3801                        let pkt: &BvhTri4 = unsafe { leaf_packets.get_unchecked(pkt_i) };
3802                        let hit_tri: u32 = pkt.intersect_any_4(orig_arr, dir_arr, t_min, t_max);
3803                        if hit_tri != u32::MAX {
3804                            *cached_tri = hit_tri;
3805                            return true;
3806                        }
3807                    }
3808                } else if next_interior == u32::MAX {
3809                    next_interior = n.child[c];
3810                } else if sp < 64 {
3811                    stack[sp] = n.child[c];
3812                    sp += 1;
3813                }
3814            }
3815            if next_interior != u32::MAX {
3816                cur_idx = next_interior as usize;
3817                continue;
3818            }
3819            if sp == 0 {
3820                break;
3821            }
3822            sp -= 1;
3823            cur_idx = stack[sp] as usize;
3824        }
3825        false
3826    }
3827
3828    /// AVX2 8-wide BVH8 shadow traversal helper on `x86_64`.
3829    ///
3830    /// # Arguments
3831    ///
3832    /// - `&Self` - BVH reference.
3833    /// - `[f32; 3]` - Ray origin.
3834    /// - `[f32; 3]` - Unit ray direction.
3835    /// - `[f32; 3]` - Safe reciprocal direction.
3836    /// - `[f32; 3]` - Negated origin times reciprocal direction.
3837    /// - `(f32, f32)` - Minimum and maximum valid ray distance `(t_min, t_max)`.
3838    /// - `&mut u32` - Cached occluder triangle hint updated on hit.
3839    ///
3840    /// # Returns
3841    ///
3842    /// - `bool` - `true` when occluded.
3843    #[cfg(target_arch = "x86_64")]
3844    #[target_feature(enable = "avx2", enable = "fma")]
3845    #[must_use]
3846    unsafe fn trace_any_shadow_bvh8_avx2(
3847        &self,
3848        orig_arr: [f32; 3],
3849        dir_arr: [f32; 3],
3850        inv_arr: [f32; 3],
3851        neg_orig_inv: [f32; 3],
3852        t_range: (f32, f32),
3853        cached_tri: &mut u32,
3854    ) -> bool {
3855        let (t_min, t_max): (f32, f32) = t_range;
3856        let Self {
3857            bvh8_nodes,
3858            leaf_packets,
3859            ..
3860        } = self;
3861        if bvh8_nodes.is_empty() {
3862            return false;
3863        }
3864        let mut stack: [u32; 96] = [0; 96];
3865        let mut sp: usize = 0;
3866        let mut cur_idx: usize = 0;
3867        loop {
3868            // SAFETY: Every pushed or root index is a valid index inside `bvh8_nodes`.
3869            let n: &Bvh8Node = unsafe { bvh8_nodes.get_unchecked(cur_idx) };
3870            // SAFETY: Caller guarantees AVX2 + FMA target features.
3871            let (_, mut mask): ([f32; 8], u32) =
3872                unsafe { n.intersect_8_avx2(inv_arr, neg_orig_inv, t_min, t_max) };
3873            let mut next_interior: u32 = u32::MAX;
3874            while mask != 0 {
3875                let c: usize = mask.trailing_zeros() as usize;
3876                mask &= mask - 1;
3877                let lc: usize = n.leaf_count[c] as usize;
3878                if lc > 0 {
3879                    let first_pkt: usize = n.child[c] as usize;
3880                    for pkt_i in first_pkt..(first_pkt + lc) {
3881                        // SAFETY: Leaf packet ranges are validated during BVH build.
3882                        let pkt: &BvhTri4 = unsafe { leaf_packets.get_unchecked(pkt_i) };
3883                        let hit_tri: u32 = pkt.intersect_any_4(orig_arr, dir_arr, t_min, t_max);
3884                        if hit_tri != u32::MAX {
3885                            *cached_tri = hit_tri;
3886                            return true;
3887                        }
3888                    }
3889                } else if next_interior == u32::MAX {
3890                    next_interior = n.child[c];
3891                } else if sp < 96 {
3892                    stack[sp] = n.child[c];
3893                    sp += 1;
3894                }
3895            }
3896            if next_interior != u32::MAX {
3897                cur_idx = next_interior as usize;
3898                continue;
3899            }
3900            if sp == 0 {
3901                break;
3902            }
3903            sp -= 1;
3904            cur_idx = stack[sp] as usize;
3905        }
3906        false
3907    }
3908
3909    /// Traces a coherent 4-ray shadow packet simultaneously across BVH4 using shared node fetches and a 4-ray cached-triangle fast path.
3910    ///
3911    /// # Arguments
3912    ///
3913    /// - `&Self` - BVH reference.
3914    /// - `&RayPacket4` - Coherent 4-ray shadow packet.
3915    /// - `u8` - 4-bit mask of active rays to trace (`0..=15`).
3916    /// - `f32` - Minimum valid distance.
3917    /// - `f32` - Maximum valid distance.
3918    /// - `&mut u32` - Shared 1-triangle occluder cache updated on hits.
3919    ///
3920    /// # Returns
3921    ///
3922    /// - `u8` - 4-bit mask of occluded rays (subset of `active_mask`).
3923    #[inline(always)]
3924    #[must_use]
3925    pub fn trace_any_shadow_packet4(
3926        &self,
3927        pkt: &RayPacket4,
3928        mut active_mask: u8,
3929        t_min: f32,
3930        t_max: f32,
3931        cached_tri: &mut u32,
3932    ) -> u8 {
3933        let Self {
3934            bvh4_nodes,
3935            geom,
3936            leaf_packets,
3937            ..
3938        } = self;
3939        if active_mask == 0 || bvh4_nodes.is_empty() || leaf_packets.is_empty() {
3940            return 0;
3941        }
3942        let mut occluded: u8 = 0;
3943        let hint: usize = *cached_tri as usize;
3944        if hint < geom.len() {
3945            let hit_mask: u8 = geom[hint].intersect_any_packet4(pkt, t_min, t_max) & active_mask;
3946            occluded |= hit_mask;
3947            active_mask &= !hit_mask;
3948            if active_mask == 0 {
3949                return occluded;
3950            }
3951        }
3952        if active_mask.count_ones() == 1 {
3953            let lane: usize = active_mask.trailing_zeros() as usize;
3954            if self.trace_any_shadow_cached(
3955                Vec3::new(pkt.ox[lane], pkt.oy[lane], pkt.oz[lane]),
3956                Vec3::new(pkt.dx[lane], pkt.dy[lane], pkt.dz[lane]),
3957                Vec3::new(pkt.ix[lane], pkt.iy[lane], pkt.iz[lane]),
3958                t_min,
3959                t_max,
3960                cached_tri,
3961            ) {
3962                occluded |= 1_u8 << lane;
3963            }
3964            return occluded;
3965        }
3966        let neg_oi: [[f32; 4]; 3] = [
3967            [
3968                -pkt.ox[0] * pkt.ix[0],
3969                -pkt.ox[1] * pkt.ix[1],
3970                -pkt.ox[2] * pkt.ix[2],
3971                -pkt.ox[3] * pkt.ix[3],
3972            ],
3973            [
3974                -pkt.oy[0] * pkt.iy[0],
3975                -pkt.oy[1] * pkt.iy[1],
3976                -pkt.oy[2] * pkt.iy[2],
3977                -pkt.oy[3] * pkt.iy[3],
3978            ],
3979            [
3980                -pkt.oz[0] * pkt.iz[0],
3981                -pkt.oz[1] * pkt.iz[1],
3982                -pkt.oz[2] * pkt.iz[2],
3983                -pkt.oz[3] * pkt.iz[3],
3984            ],
3985        ];
3986        let t_max_4: [f32; 4] = [t_max; 4];
3987        let mut stack: [(u32, u8); 64] = [(0, 0); 64];
3988        let mut sp: usize = 0;
3989        let mut cur_idx: usize = 0;
3990        let mut cur_mask: u8 = active_mask;
3991        loop {
3992            cur_mask &= active_mask;
3993            if cur_mask != 0 {
3994                // SAFETY: Every root or pushed index lies within `bvh4_nodes`.
3995                let n: &Bvh4Node = unsafe { bvh4_nodes.get_unchecked(cur_idx) };
3996                let vcnt: usize = n.valid_count as usize;
3997                let mut next_interior: (u32, u8) = (u32::MAX, 0);
3998                for c in 0..vcnt {
3999                    let hit_rays: u8 =
4000                        n.intersect_child_packet4(c, pkt, &neg_oi, t_min, t_max_4) & cur_mask;
4001                    if hit_rays == 0 {
4002                        continue;
4003                    }
4004                    let lc: usize = n.leaf_count[c] as usize;
4005                    if lc > 0 {
4006                        let first_pkt: usize = n.child[c] as usize;
4007                        let mut rem_rays: u8 = hit_rays & active_mask;
4008                        while rem_rays != 0 {
4009                            let r: usize = rem_rays.trailing_zeros() as usize;
4010                            rem_rays &= rem_rays - 1;
4011                            let orig_r: [f32; 3] = [pkt.ox[r], pkt.oy[r], pkt.oz[r]];
4012                            let dir_r: [f32; 3] = [pkt.dx[r], pkt.dy[r], pkt.dz[r]];
4013                            for pkt_i in first_pkt..(first_pkt + lc) {
4014                                // SAFETY: Leaf packet ranges are validated during BVH build.
4015                                let tp: &BvhTri4 = unsafe { leaf_packets.get_unchecked(pkt_i) };
4016                                let hit_tri: u32 = tp.intersect_any_4(orig_r, dir_r, t_min, t_max);
4017                                if hit_tri != u32::MAX {
4018                                    *cached_tri = hit_tri;
4019                                    let bit: u8 = 1_u8 << r;
4020                                    occluded |= bit;
4021                                    active_mask &= !bit;
4022                                    cur_mask &= !bit;
4023                                    break;
4024                                }
4025                            }
4026                        }
4027                        if active_mask == 0 {
4028                            return occluded;
4029                        }
4030                    } else if next_interior.0 == u32::MAX {
4031                        next_interior = (n.child[c], hit_rays);
4032                    } else if sp < 64 {
4033                        stack[sp] = (n.child[c], hit_rays);
4034                        sp += 1;
4035                    }
4036                }
4037                if next_interior.0 != u32::MAX && (next_interior.1 & active_mask) != 0 {
4038                    cur_idx = next_interior.0 as usize;
4039                    cur_mask = next_interior.1 & active_mask;
4040                    continue;
4041                }
4042            }
4043            let mut popped: bool = false;
4044            while sp > 0 {
4045                sp -= 1;
4046                let (nid, nmask): (u32, u8) = stack[sp];
4047                let live: u8 = nmask & active_mask;
4048                if live != 0 {
4049                    cur_idx = nid as usize;
4050                    cur_mask = live;
4051                    popped = true;
4052                    break;
4053                }
4054            }
4055            if !popped {
4056                break;
4057            }
4058        }
4059        occluded
4060    }
4061
4062    /// Traces a coherent 4-ray closest-hit packet simultaneously across BVH4, tightening per-ray `(best_t, best_idx)`.
4063    ///
4064    /// # Arguments
4065    ///
4066    /// - `&Self` - BVH reference.
4067    /// - `&RayPacket4` - Coherent 4-ray reflection or GI packet.
4068    /// - `u8` - 4-bit mask of active rays to trace.
4069    /// - `f32` - Minimum valid distance.
4070    /// - `&mut [f32; 4]` - Per-ray maximum/best distance updated in place on closer hits.
4071    /// - `&mut [usize; 4]` - Per-ray winning triangle index updated in place (`usize::MAX` on miss).
4072    #[inline(always)]
4073    pub fn trace_closest_packet4(
4074        &self,
4075        pkt: &RayPacket4,
4076        active_mask: u8,
4077        t_min: f32,
4078        best_t: &mut [f32; 4],
4079        best_idx: &mut [usize; 4],
4080    ) {
4081        let Self {
4082            bvh4_nodes,
4083            leaf_packets,
4084            ..
4085        } = self;
4086        if active_mask == 0 || bvh4_nodes.is_empty() || leaf_packets.is_empty() {
4087            return;
4088        }
4089        if active_mask.count_ones() == 1 {
4090            let r: usize = active_mask.trailing_zeros() as usize;
4091            if let Some((t, idx)) = self.trace_closest_raw(
4092                Vec3::new(pkt.ox[r], pkt.oy[r], pkt.oz[r]),
4093                Vec3::new(pkt.dx[r], pkt.dy[r], pkt.dz[r]),
4094                Vec3::new(pkt.ix[r], pkt.iy[r], pkt.iz[r]),
4095                t_min,
4096                best_t[r],
4097            ) {
4098                best_t[r] = t;
4099                best_idx[r] = idx;
4100            }
4101            return;
4102        }
4103        let neg_oi: [[f32; 4]; 3] = [
4104            [
4105                -pkt.ox[0] * pkt.ix[0],
4106                -pkt.ox[1] * pkt.ix[1],
4107                -pkt.ox[2] * pkt.ix[2],
4108                -pkt.ox[3] * pkt.ix[3],
4109            ],
4110            [
4111                -pkt.oy[0] * pkt.iy[0],
4112                -pkt.oy[1] * pkt.iy[1],
4113                -pkt.oy[2] * pkt.iy[2],
4114                -pkt.oy[3] * pkt.iy[3],
4115            ],
4116            [
4117                -pkt.oz[0] * pkt.iz[0],
4118                -pkt.oz[1] * pkt.iz[1],
4119                -pkt.oz[2] * pkt.iz[2],
4120                -pkt.oz[3] * pkt.iz[3],
4121            ],
4122        ];
4123        let mut stack: [(u32, u8, f32); 64] = [(0, 0, 0.0); 64];
4124        let mut s_stack: [(u32, f32); 64] = [(0, 0.0); 64];
4125        let mut sp: usize = 0;
4126        let mut cur_idx: usize = 0;
4127        let mut cur_mask: u8 = active_mask;
4128        loop {
4129            if cur_mask.count_ones() == 1 {
4130                let r: usize = cur_mask.trailing_zeros() as usize;
4131                let orig_r: [f32; 3] = [pkt.ox[r], pkt.oy[r], pkt.oz[r]];
4132                let dir_r: [f32; 3] = [pkt.dx[r], pkt.dy[r], pkt.dz[r]];
4133                let inv_r: [f32; 3] = [pkt.ix[r], pkt.iy[r], pkt.iz[r]];
4134                let neg_r: [f32; 3] = [neg_oi[0][r], neg_oi[1][r], neg_oi[2][r]];
4135                let mut r_best_t: f32 = best_t[r];
4136                let mut r_best_idx: usize = best_idx[r];
4137                let mut s_sp: usize = 0;
4138                let mut s_cur: usize = cur_idx;
4139                loop {
4140                    // SAFETY: Every root or pushed index lies within `bvh4_nodes`.
4141                    let sn: &Bvh4Node = unsafe { bvh4_nodes.get_unchecked(s_cur) };
4142                    let (t_near, mut smask): ([f32; 4], u32) =
4143                        sn.intersect_4(inv_r, neg_r, t_min, r_best_t);
4144                    let mut sh_hits: [(u32, f32); 4] = [(0, 0.0); 4];
4145                    let mut sh_len: usize = 0;
4146                    while smask != 0 {
4147                        let c: usize = smask.trailing_zeros() as usize;
4148                        smask &= smask - 1;
4149                        let tc: f32 = t_near[c];
4150                        if tc >= r_best_t {
4151                            continue;
4152                        }
4153                        let lc: usize = sn.leaf_count[c] as usize;
4154                        if lc > 0 {
4155                            let first_pkt: usize = sn.child[c] as usize;
4156                            for pkt_i in first_pkt..(first_pkt + lc) {
4157                                // SAFETY: Leaf packet ranges are validated during BVH build.
4158                                let tp: &BvhTri4 = unsafe { leaf_packets.get_unchecked(pkt_i) };
4159                                tp.intersect_closest_4(
4160                                    orig_r,
4161                                    dir_r,
4162                                    t_min,
4163                                    &mut r_best_t,
4164                                    &mut r_best_idx,
4165                                );
4166                            }
4167                        } else {
4168                            sh_hits[sh_len] = (sn.child[c], tc);
4169                            sh_len += 1;
4170                        }
4171                    }
4172                    if sh_len > 0 {
4173                        if sh_len > 1 {
4174                            for i in 1..sh_len {
4175                                let key: (u32, f32) = sh_hits[i];
4176                                let mut j: usize = i;
4177                                while j > 0 && sh_hits[j - 1].1 < key.1 {
4178                                    sh_hits[j] = sh_hits[j - 1];
4179                                    j -= 1;
4180                                }
4181                                sh_hits[j] = key;
4182                            }
4183                        }
4184                        for hit in sh_hits.iter().take(sh_len - 1) {
4185                            if s_sp < 64 {
4186                                s_stack[s_sp] = *hit;
4187                                s_sp += 1;
4188                            }
4189                        }
4190                        s_cur = sh_hits[sh_len - 1].0 as usize;
4191                        continue;
4192                    }
4193                    let mut popped_single: bool = false;
4194                    while s_sp > 0 {
4195                        s_sp -= 1;
4196                        let (nid, nt): (u32, f32) = s_stack[s_sp];
4197                        if nt < r_best_t {
4198                            s_cur = nid as usize;
4199                            popped_single = true;
4200                            break;
4201                        }
4202                    }
4203                    if !popped_single {
4204                        break;
4205                    }
4206                }
4207                best_t[r] = r_best_t;
4208                best_idx[r] = r_best_idx;
4209            } else {
4210                // SAFETY: Every root or pushed index lies within `bvh4_nodes`.
4211                let n: &Bvh4Node = unsafe { bvh4_nodes.get_unchecked(cur_idx) };
4212                let vcnt: usize = n.valid_count as usize;
4213                let mut hits: [(u32, u8, f32); 4] = [(0, 0, 0.0); 4];
4214                let mut hit_len: usize = 0;
4215                for c in 0..vcnt {
4216                    let (raw_rays, min_t): (u8, f32) =
4217                        n.intersect_child_packet4_near(c, pkt, &neg_oi, t_min, *best_t);
4218                    let hit_rays: u8 = raw_rays & cur_mask;
4219                    if hit_rays == 0 {
4220                        continue;
4221                    }
4222                    let lc: usize = n.leaf_count[c] as usize;
4223                    if lc > 0 {
4224                        let first_pkt: usize = n.child[c] as usize;
4225                        let mut rem_rays: u8 = hit_rays;
4226                        while rem_rays != 0 {
4227                            let r: usize = rem_rays.trailing_zeros() as usize;
4228                            rem_rays &= rem_rays - 1;
4229                            let orig_r: [f32; 3] = [pkt.ox[r], pkt.oy[r], pkt.oz[r]];
4230                            let dir_r: [f32; 3] = [pkt.dx[r], pkt.dy[r], pkt.dz[r]];
4231                            for pkt_i in first_pkt..(first_pkt + lc) {
4232                                // SAFETY: Leaf packet ranges are validated during BVH build.
4233                                let tp: &BvhTri4 = unsafe { leaf_packets.get_unchecked(pkt_i) };
4234                                tp.intersect_closest_4(
4235                                    orig_r,
4236                                    dir_r,
4237                                    t_min,
4238                                    &mut best_t[r],
4239                                    &mut best_idx[r],
4240                                );
4241                            }
4242                        }
4243                    } else {
4244                        hits[hit_len] = (n.child[c], hit_rays, min_t);
4245                        hit_len += 1;
4246                    }
4247                }
4248                if hit_len > 0 {
4249                    if hit_len > 1 {
4250                        for i in 1..hit_len {
4251                            let key: (u32, u8, f32) = hits[i];
4252                            let mut j: usize = i;
4253                            while j > 0 && hits[j - 1].2 < key.2 {
4254                                hits[j] = hits[j - 1];
4255                                j -= 1;
4256                            }
4257                            hits[j] = key;
4258                        }
4259                    }
4260                    for hit in hits.iter().take(hit_len - 1) {
4261                        if sp < 64 {
4262                            stack[sp] = *hit;
4263                            sp += 1;
4264                        }
4265                    }
4266                    let nearest: (u32, u8, f32) = hits[hit_len - 1];
4267                    cur_idx = nearest.0 as usize;
4268                    cur_mask = nearest.1;
4269                    continue;
4270                }
4271            }
4272            let mut found_next: bool = false;
4273            while sp > 0 {
4274                sp -= 1;
4275                let (nid, nmask, nt): (u32, u8, f32) = stack[sp];
4276                let mut max_bt: f32 = 0.0;
4277                let mut m: u8 = nmask;
4278                while m != 0 {
4279                    let r: usize = m.trailing_zeros() as usize;
4280                    m &= m - 1;
4281                    max_bt = max_bt.max(best_t[r]);
4282                }
4283                if nt < max_bt {
4284                    cur_idx = nid as usize;
4285                    cur_mask = nmask;
4286                    found_next = true;
4287                    break;
4288                }
4289            }
4290            if !found_next {
4291                break;
4292            }
4293        }
4294    }
4295
4296    /// Traces a shadow/occlusion ray returning `true` immediately upon any hit within `(t_min, t_max)`.
4297    ///
4298    /// # Arguments
4299    ///
4300    /// - `&Self` - BVH reference.
4301    /// - `&Ray3D` - Shadow ray.
4302    /// - `f32` - Minimum offset (shadow bias).
4303    /// - `f32` - Maximum trace distance.
4304    ///
4305    /// # Returns
4306    ///
4307    /// - `bool` - `true` if occluded by scene geometry.
4308    #[must_use]
4309    pub fn trace_any_shadow(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
4310        let mut cache: u32 = u32::MAX;
4311        self.trace_any_shadow_cached(
4312            ray.get_origin(),
4313            ray.get_direction(),
4314            ray.get_inv_direction(),
4315            t_min,
4316            t_max,
4317            &mut cache,
4318        )
4319    }
4320
4321    /// Traces a ray near-child-first against SIMD BVH4/BVH8 nodes and returns `(distance, tri_index)`.
4322    ///
4323    /// # Arguments
4324    ///
4325    /// - `&Self` - BVH reference.
4326    /// - `Vec3` - Ray origin.
4327    /// - `Vec3` - Unit ray direction.
4328    /// - `Vec3` - Precomputed safe reciprocal ray direction.
4329    /// - `f32` - Minimum offset bias.
4330    /// - `f32` - Maximum trace distance.
4331    ///
4332    /// # Returns
4333    ///
4334    /// - `Option<(f32, usize)>` - Closest hit distance and triangle index into `self.triangles`.
4335    #[inline(always)]
4336    #[must_use]
4337    pub fn trace_closest_raw(
4338        &self,
4339        origin: Vec3,
4340        dir: Vec3,
4341        inv_dir: Vec3,
4342        t_min: f32,
4343        t_max: f32,
4344    ) -> Option<(f32, usize)> {
4345        let Self {
4346            bvh4_nodes,
4347            #[cfg(target_arch = "x86_64")]
4348            bvh8_nodes,
4349            root_min,
4350            root_max,
4351            leaf_packets,
4352            ..
4353        } = self;
4354        if bvh4_nodes.is_empty() || leaf_packets.is_empty() {
4355            return None;
4356        }
4357        let orig_arr: [f32; 3] = [origin.get_x(), origin.get_y(), origin.get_z()];
4358        let dir_arr: [f32; 3] = [dir.get_x(), dir.get_y(), dir.get_z()];
4359        let inv_arr: [f32; 3] = [inv_dir.get_x(), inv_dir.get_y(), inv_dir.get_z()];
4360        let neg_orig_inv: [f32; 3] = [
4361            -orig_arr[0] * inv_arr[0],
4362            -orig_arr[1] * inv_arr[1],
4363            -orig_arr[2] * inv_arr[2],
4364        ];
4365        if !BvhFlatNode::intersect_box_fma(
4366            *root_min,
4367            *root_max,
4368            inv_arr,
4369            neg_orig_inv,
4370            t_min,
4371            t_max,
4372        )
4373        .is_finite()
4374        {
4375            return None;
4376        }
4377        #[cfg(target_arch = "x86_64")]
4378        if !bvh8_nodes.is_empty() && Bvh8Node::has_avx2_fma() {
4379            // SAFETY: Runtime CPU feature detection verified AVX2+FMA support.
4380            return unsafe {
4381                self.trace_closest_bvh8_avx2(orig_arr, dir_arr, inv_arr, neg_orig_inv, t_min, t_max)
4382            };
4383        }
4384        let mut stack: [(u32, f32); 64] = [(0, 0.0); 64];
4385        let mut sp: usize = 0;
4386        let mut cur_idx: usize = 0;
4387        let mut best_t: f32 = t_max;
4388        let mut best_idx: usize = usize::MAX;
4389        loop {
4390            // SAFETY: Every root or pushed index lies within `bvh4_nodes`.
4391            let n: &Bvh4Node = unsafe { bvh4_nodes.get_unchecked(cur_idx) };
4392            let (t_near, mut mask): ([f32; 4], u32) =
4393                n.intersect_4(inv_arr, neg_orig_inv, t_min, best_t);
4394            let mut hits: [(u32, f32); 4] = [(0, 0.0); 4];
4395            let mut hit_len: usize = 0;
4396            while mask != 0 {
4397                let c: usize = mask.trailing_zeros() as usize;
4398                mask &= mask - 1;
4399                let tc: f32 = t_near[c];
4400                if tc >= best_t {
4401                    continue;
4402                }
4403                let lc: usize = n.leaf_count[c] as usize;
4404                if lc > 0 {
4405                    let first_pkt: usize = n.child[c] as usize;
4406                    for pkt_i in first_pkt..(first_pkt + lc) {
4407                        // SAFETY: Leaf packet ranges are validated during BVH build.
4408                        let pkt: &BvhTri4 = unsafe { leaf_packets.get_unchecked(pkt_i) };
4409                        pkt.intersect_closest_4(
4410                            orig_arr,
4411                            dir_arr,
4412                            t_min,
4413                            &mut best_t,
4414                            &mut best_idx,
4415                        );
4416                    }
4417                } else {
4418                    hits[hit_len] = (n.child[c], tc);
4419                    hit_len += 1;
4420                }
4421            }
4422            if hit_len > 0 {
4423                if hit_len > 1 {
4424                    for i in 1..hit_len {
4425                        let key: (u32, f32) = hits[i];
4426                        let mut j: usize = i;
4427                        while j > 0 && hits[j - 1].1 < key.1 {
4428                            hits[j] = hits[j - 1];
4429                            j -= 1;
4430                        }
4431                        hits[j] = key;
4432                    }
4433                }
4434                let near_last: usize = hit_len - 1;
4435                for item in hits.iter().take(near_last) {
4436                    if item.1 < best_t && sp < 64 {
4437                        stack[sp] = *item;
4438                        sp += 1;
4439                    }
4440                }
4441                if hits[near_last].1 < best_t {
4442                    cur_idx = hits[near_last].0 as usize;
4443                    continue;
4444                }
4445            }
4446            let mut found_next: bool = false;
4447            while sp > 0 {
4448                sp -= 1;
4449                let (next_id, next_tmin): (u32, f32) = stack[sp];
4450                if next_tmin < best_t {
4451                    cur_idx = next_id as usize;
4452                    found_next = true;
4453                    break;
4454                }
4455            }
4456            if !found_next {
4457                break;
4458            }
4459        }
4460        if best_idx == usize::MAX {
4461            None
4462        } else {
4463            Some((best_t, best_idx))
4464        }
4465    }
4466
4467    /// AVX2 8-wide BVH8 closest-hit traversal helper on `x86_64`.
4468    ///
4469    /// # Arguments
4470    ///
4471    /// - `&Self` - BVH reference.
4472    /// - `[f32; 3]` - Ray origin.
4473    /// - `[f32; 3]` - Unit ray direction.
4474    /// - `[f32; 3]` - Safe reciprocal direction.
4475    /// - `[f32; 3]` - Negated origin times reciprocal direction.
4476    /// - `f32` - Minimum valid distance.
4477    /// - `f32` - Maximum valid distance.
4478    ///
4479    /// # Returns
4480    ///
4481    /// - `Option<(f32, usize)>` - Closest hit distance and triangle index.
4482    #[cfg(target_arch = "x86_64")]
4483    #[target_feature(enable = "avx2", enable = "fma")]
4484    #[must_use]
4485    unsafe fn trace_closest_bvh8_avx2(
4486        &self,
4487        orig_arr: [f32; 3],
4488        dir_arr: [f32; 3],
4489        inv_arr: [f32; 3],
4490        neg_orig_inv: [f32; 3],
4491        t_min: f32,
4492        t_max: f32,
4493    ) -> Option<(f32, usize)> {
4494        let Self {
4495            bvh8_nodes,
4496            leaf_packets,
4497            ..
4498        } = self;
4499        if bvh8_nodes.is_empty() {
4500            return None;
4501        }
4502        let mut stack: [(u32, f32); 96] = [(0, 0.0); 96];
4503        let mut sp: usize = 0;
4504        let mut cur_idx: usize = 0;
4505        let mut best_t: f32 = t_max;
4506        let mut best_idx: usize = usize::MAX;
4507        loop {
4508            // SAFETY: Every root or pushed index lies within `bvh8_nodes`.
4509            let n: &Bvh8Node = unsafe { bvh8_nodes.get_unchecked(cur_idx) };
4510            // SAFETY: Caller guarantees AVX2 + FMA target features.
4511            let (t_near, mut mask): ([f32; 8], u32) =
4512                unsafe { n.intersect_8_avx2(inv_arr, neg_orig_inv, t_min, best_t) };
4513            let mut hits: [(u32, f32); 8] = [(0, 0.0); 8];
4514            let mut hit_len: usize = 0;
4515            while mask != 0 {
4516                let c: usize = mask.trailing_zeros() as usize;
4517                mask &= mask - 1;
4518                let tc: f32 = t_near[c];
4519                if tc >= best_t {
4520                    continue;
4521                }
4522                let lc: usize = n.leaf_count[c] as usize;
4523                if lc > 0 {
4524                    let first_pkt: usize = n.child[c] as usize;
4525                    for pkt_i in first_pkt..(first_pkt + lc) {
4526                        // SAFETY: Leaf packet ranges are validated during BVH build.
4527                        let pkt: &BvhTri4 = unsafe { leaf_packets.get_unchecked(pkt_i) };
4528                        pkt.intersect_closest_4(
4529                            orig_arr,
4530                            dir_arr,
4531                            t_min,
4532                            &mut best_t,
4533                            &mut best_idx,
4534                        );
4535                    }
4536                } else {
4537                    hits[hit_len] = (n.child[c], tc);
4538                    hit_len += 1;
4539                }
4540            }
4541            if hit_len > 0 {
4542                if hit_len > 1 {
4543                    for i in 1..hit_len {
4544                        let key: (u32, f32) = hits[i];
4545                        let mut j: usize = i;
4546                        while j > 0 && hits[j - 1].1 < key.1 {
4547                            hits[j] = hits[j - 1];
4548                            j -= 1;
4549                        }
4550                        hits[j] = key;
4551                    }
4552                }
4553                let near_last: usize = hit_len - 1;
4554                for item in hits.iter().take(near_last) {
4555                    if item.1 < best_t && sp < 96 {
4556                        stack[sp] = *item;
4557                        sp += 1;
4558                    }
4559                }
4560                if hits[near_last].1 < best_t {
4561                    cur_idx = hits[near_last].0 as usize;
4562                    continue;
4563                }
4564            }
4565            let mut found_next: bool = false;
4566            while sp > 0 {
4567                sp -= 1;
4568                let (next_id, next_tmin): (u32, f32) = stack[sp];
4569                if next_tmin < best_t {
4570                    cur_idx = next_id as usize;
4571                    found_next = true;
4572                    break;
4573                }
4574            }
4575            if !found_next {
4576                break;
4577            }
4578        }
4579        if best_idx == usize::MAX {
4580            None
4581        } else {
4582            Some((best_t, best_idx))
4583        }
4584    }
4585
4586    /// Traces a reflection/GI ray and returns the closest hit surface within `(t_min, t_max)`.
4587    ///
4588    /// # Arguments
4589    ///
4590    /// - `&Self` - BVH reference.
4591    /// - `&Ray3D` - Reflection or GI ray.
4592    /// - `f32` - Minimum offset bias.
4593    /// - `f32` - Maximum trace distance.
4594    ///
4595    /// # Returns
4596    ///
4597    /// - `Option<RayHit3D>` - Closest hit metadata if any geometry was struck.
4598    #[must_use]
4599    pub fn trace_closest(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> Option<RayHit3D> {
4600        let (t, idx): (f32, usize) = self.trace_closest_raw(
4601            ray.get_origin(),
4602            ray.get_direction(),
4603            ray.get_inv_direction(),
4604            t_min,
4605            t_max,
4606        )?;
4607        let tri: &BvhTriangle = &self.get_triangles()[idx];
4608        let pt: Vec3 = ray.get_origin().add(ray.get_direction().scale(t));
4609        Some(RayHit3D {
4610            distance: t,
4611            point: pt,
4612            normal: tri.get_normal(),
4613            material: tri.get_material(),
4614        })
4615    }
4616}