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