Skip to main content

euv_core/game/engine3d/math/
impl.rs

1use super::*;
2
3/// Vector arithmetic, normalization, dot/cross products, and reflection helpers for `Vec3`.
4impl Vec3 {
5    /// Zero vector `(0, 0, 0)`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Zero vector.
10    #[must_use]
11    pub const fn zero() -> Self {
12        Self {
13            x: 0.0,
14            y: 0.0,
15            z: 0.0,
16        }
17    }
18
19    /// Uniform vector `(v, v, v)`.
20    ///
21    /// # Arguments
22    ///
23    /// - `f32` - Scalar value replicated across all axes.
24    ///
25    /// # Returns
26    ///
27    /// - `Self` - Splat vector.
28    #[must_use]
29    pub const fn splat(item_val: f32) -> Self {
30        Self {
31            x: item_val,
32            y: item_val,
33            z: item_val,
34        }
35    }
36
37    /// Scales `self` by scalar `s`.
38    ///
39    /// # Arguments
40    ///
41    /// - `Self` - Source vector.
42    /// - `f32` - Scalar multiplier.
43    ///
44    /// # Returns
45    ///
46    /// - `Self` - Scaled vector.
47    #[inline(always)]
48    #[must_use]
49    pub fn scale(self, source_val: f32) -> Self {
50        Self {
51            x: self.get_x() * source_val,
52            y: self.get_y() * source_val,
53            z: self.get_z() * source_val,
54        }
55    }
56
57    /// Computes the dot product `self · rhs`.
58    ///
59    /// # Arguments
60    ///
61    /// - `Self` - Left vector.
62    /// - `Self` - Right vector.
63    ///
64    /// # Returns
65    ///
66    /// - `f32` - Scalar dot product.
67    #[inline(always)]
68    #[must_use]
69    pub fn dot(self, rhs: Self) -> f32 {
70        self.get_x().mul_add(
71            rhs.get_x(),
72            self.get_y()
73                .mul_add(rhs.get_y(), self.get_z() * rhs.get_z()),
74        )
75    }
76
77    /// Computes the 3D cross product `self × rhs`.
78    ///
79    /// # Arguments
80    ///
81    /// - `Self` - Left vector.
82    /// - `Self` - Right vector.
83    ///
84    /// # Returns
85    ///
86    /// - `Self` - Orthogonal cross product vector.
87    #[inline(always)]
88    #[must_use]
89    pub fn cross(self, rhs: Self) -> Self {
90        Self {
91            x: self.get_y() * rhs.get_z() - self.get_z() * rhs.get_y(),
92            y: self.get_z() * rhs.get_x() - self.get_x() * rhs.get_z(),
93            z: self.get_x() * rhs.get_y() - self.get_y() * rhs.get_x(),
94        }
95    }
96
97    /// Computes squared Euclidean length.
98    ///
99    /// # Arguments
100    ///
101    /// - `Self` - Source vector.
102    ///
103    /// # Returns
104    ///
105    /// - `f32` - Squared magnitude.
106    #[inline(always)]
107    #[must_use]
108    pub fn length_sq(self) -> f32 {
109        self.dot(self)
110    }
111
112    /// Computes Euclidean length.
113    ///
114    /// # Arguments
115    ///
116    /// - `Self` - Source vector.
117    ///
118    /// # Returns
119    ///
120    /// - `f32` - Magnitude.
121    #[inline(always)]
122    #[must_use]
123    pub fn length(self) -> f32 {
124        self.length_sq().sqrt()
125    }
126
127    /// Returns a unit-length vector pointing along `self`, or `(0, 1, 0)` if degenerate.
128    ///
129    /// # Arguments
130    ///
131    /// - `Self` - Source vector.
132    ///
133    /// # Returns
134    ///
135    /// - `Self` - Normalized unit vector.
136    #[inline(always)]
137    #[must_use]
138    pub fn normalize(self) -> Self {
139        let len: f32 = self.length();
140        if len > 1e-6 {
141            self.scale(1.0 / len)
142        } else {
143            Self::new(0.0, 1.0, 0.0)
144        }
145    }
146
147    /// Linearly interpolates between `self` and `other` by `t`.
148    ///
149    /// # Arguments
150    ///
151    /// - `Self` - Start vector.
152    /// - `Self` - End vector.
153    /// - `f32` - Interpolation factor.
154    ///
155    /// # Returns
156    ///
157    /// - `Self` - Interpolated vector.
158    #[inline(always)]
159    #[must_use]
160    pub fn lerp(self, other: Self, blend_factor: f32) -> Self {
161        Self {
162            x: (other.get_x() - self.get_x()).mul_add(blend_factor, self.get_x()),
163            y: (other.get_y() - self.get_y()).mul_add(blend_factor, self.get_y()),
164            z: (other.get_z() - self.get_z()).mul_add(blend_factor, self.get_z()),
165        }
166    }
167
168    /// Reflects incident vector `self` across unit surface normal `normal`.
169    ///
170    /// # Arguments
171    ///
172    /// - `Self` - Incident vector.
173    /// - `Self` - Unit surface normal.
174    ///
175    /// # Returns
176    ///
177    /// - `Self` - Reflected direction vector.
178    #[inline(always)]
179    #[must_use]
180    pub fn reflect(self, normal: Self) -> Self {
181        self.sub(normal.scale(2.0 * self.dot(normal)))
182    }
183
184    /// Returns component-wise minimum of `self` and `rhs`.
185    ///
186    /// # Arguments
187    ///
188    /// - `Self` - Left vector.
189    /// - `Self` - Right vector.
190    ///
191    /// # Returns
192    ///
193    /// - `Self` - Component-wise minimum.
194    #[must_use]
195    pub fn min(self, rhs: Self) -> Self {
196        Self {
197            x: self.get_x().min(rhs.get_x()),
198            y: self.get_y().min(rhs.get_y()),
199            z: self.get_z().min(rhs.get_z()),
200        }
201    }
202
203    /// Returns component-wise maximum of `self` and `rhs`.
204    ///
205    /// # Arguments
206    ///
207    /// - `Self` - Left vector.
208    /// - `Self` - Right vector.
209    ///
210    /// # Returns
211    ///
212    /// - `Self` - Component-wise maximum.
213    #[must_use]
214    pub fn max(self, rhs: Self) -> Self {
215        Self {
216            x: self.get_x().max(rhs.get_x()),
217            y: self.get_y().max(rhs.get_y()),
218            z: self.get_z().max(rhs.get_z()),
219        }
220    }
221
222    /// Converts an sRGB `Color` into linear RGB `Vec3` radiance in `[0.0, 1.0]`.
223    ///
224    /// # Arguments
225    ///
226    /// - `Color` - Source RGBA color.
227    ///
228    /// # Returns
229    ///
230    /// - `Self` - Normalized linear RGB vector.
231    #[must_use]
232    pub fn from_color(color_value: Color) -> Self {
233        Self {
234            x: (color_value.get_red() as f32) / 255.0,
235            y: (color_value.get_green() as f32) / 255.0,
236            z: (color_value.get_blue() as f32) / 255.0,
237        }
238    }
239
240    /// Maps a single HDR channel through the ACES filmic tone curve into sRGB byte space.
241    ///
242    /// # Arguments
243    ///
244    /// - `f32` - Linear HDR scalar.
245    ///
246    /// # Returns
247    ///
248    /// - `u8` - Gamma-encoded sRGB byte.
249    #[inline(always)]
250    #[must_use]
251    fn aces_channel(item_val: f32) -> u8 {
252        let pos_x: f32 = item_val.max(0.0);
253        let num: f32 = pos_x * pos_x.mul_add(2.51, 0.03);
254        let den: f32 = pos_x.mul_add(pos_x.mul_add(2.43, 0.59), 0.14);
255        let mapped: f32 = num / den;
256        let idx: usize = mapped.clamp(0.0, 1.0).mul_add(1024.0, 0.5) as usize;
257        LINEAR_TO_SRGB_LUT[idx.min(1024)]
258    }
259
260    /// Applies ACES filmic tone mapping and converts linear radiance to RGBA8 `[r, g, b, 255]`.
261    ///
262    /// # Arguments
263    ///
264    /// - `Self` - Linear HDR RGB radiance.
265    ///
266    /// # Returns
267    ///
268    /// - `[u8; 4]` - Tone-mapped RGBA8 pixel bytes.
269    #[inline(always)]
270    #[must_use]
271    pub fn to_aces_rgba8(self) -> [u8; 4] {
272        [
273            Self::aces_channel(self.get_x()),
274            Self::aces_channel(self.get_y()),
275            Self::aces_channel(self.get_z()),
276            255,
277        ]
278    }
279
280    /// Maps four HDR scalar values through the ACES filmic tone curve into 10-bit LUT indices `[0..=1024]`.
281    ///
282    /// # Arguments
283    ///
284    /// - `[f32; 4]` - Four linear HDR channel scalars.
285    ///
286    /// # Returns
287    ///
288    /// - `[u32; 4]` - Clamped LUT indices into `LINEAR_TO_SRGB_LUT`.
289    #[inline(always)]
290    #[must_use]
291    fn aces_indices_4x(vals: [f32; 4]) -> [u32; 4] {
292        #[cfg(target_arch = "aarch64")]
293        {
294            let mut out: [u32; 4] = [0; 4];
295            // SAFETY: `vals` and `out` are valid 16-byte stack arrays; NEON is mandatory on `aarch64`.
296            unsafe {
297                let zero: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(0.0);
298                let one: core::arch::aarch64::float32x4_t = core::arch::aarch64::vdupq_n_f32(1.0);
299                let pos_x: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmaxq_f32(
300                    core::arch::aarch64::vld1q_f32(vals.as_ptr()),
301                    zero,
302                );
303                let num: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
304                    pos_x,
305                    core::arch::aarch64::vfmaq_f32(
306                        core::arch::aarch64::vdupq_n_f32(0.03),
307                        pos_x,
308                        core::arch::aarch64::vdupq_n_f32(2.51),
309                    ),
310                );
311                let den_inner: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
312                    core::arch::aarch64::vdupq_n_f32(0.59),
313                    pos_x,
314                    core::arch::aarch64::vdupq_n_f32(2.43),
315                );
316                let den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vfmaq_f32(
317                    core::arch::aarch64::vdupq_n_f32(0.14),
318                    pos_x,
319                    den_inner,
320                );
321                let den_est: core::arch::aarch64::float32x4_t =
322                    core::arch::aarch64::vrecpeq_f32(den);
323                let inv_den: core::arch::aarch64::float32x4_t = core::arch::aarch64::vmulq_f32(
324                    den_est,
325                    core::arch::aarch64::vrecpsq_f32(den, den_est),
326                );
327                let mapped: core::arch::aarch64::float32x4_t = core::arch::aarch64::vminq_f32(
328                    core::arch::aarch64::vmaxq_f32(
329                        core::arch::aarch64::vmulq_f32(num, inv_den),
330                        zero,
331                    ),
332                    one,
333                );
334                let scaled: core::arch::aarch64::float32x4_t = core::arch::aarch64::vaddq_f32(
335                    core::arch::aarch64::vmulq_f32(
336                        mapped,
337                        core::arch::aarch64::vdupq_n_f32(1024.0),
338                    ),
339                    core::arch::aarch64::vdupq_n_f32(0.5),
340                );
341                let idx_u32: core::arch::aarch64::uint32x4_t =
342                    core::arch::aarch64::vcvtq_u32_f32(scaled);
343                core::arch::aarch64::vst1q_u32(out.as_mut_ptr(), idx_u32);
344            }
345            [
346                out[0].min(1024),
347                out[1].min(1024),
348                out[2].min(1024),
349                out[3].min(1024),
350            ]
351        }
352        #[cfg(target_arch = "x86_64")]
353        {
354            let mut out: [i32; 4] = [0; 4];
355            // SAFETY: `vals` and `out` are valid 16-byte stack arrays; SSE2 is mandatory on `x86_64`.
356            unsafe {
357                let zero: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(0.0);
358                let one: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_set1_ps(1.0);
359                let coord_x: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_max_ps(
360                    core::arch::x86_64::_mm_loadu_ps(vals.as_ptr()),
361                    zero,
362                );
363                let num: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_mul_ps(
364                    coord_x,
365                    core::arch::x86_64::_mm_add_ps(
366                        core::arch::x86_64::_mm_mul_ps(
367                            coord_x,
368                            core::arch::x86_64::_mm_set1_ps(2.51),
369                        ),
370                        core::arch::x86_64::_mm_set1_ps(0.03),
371                    ),
372                );
373                let den: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
374                    core::arch::x86_64::_mm_mul_ps(
375                        coord_x,
376                        core::arch::x86_64::_mm_add_ps(
377                            core::arch::x86_64::_mm_mul_ps(
378                                coord_x,
379                                core::arch::x86_64::_mm_set1_ps(2.43),
380                            ),
381                            core::arch::x86_64::_mm_set1_ps(0.59),
382                        ),
383                    ),
384                    core::arch::x86_64::_mm_set1_ps(0.14),
385                );
386                let mapped: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_min_ps(
387                    core::arch::x86_64::_mm_max_ps(core::arch::x86_64::_mm_div_ps(num, den), zero),
388                    one,
389                );
390                let scaled: core::arch::x86_64::__m128 = core::arch::x86_64::_mm_add_ps(
391                    core::arch::x86_64::_mm_mul_ps(mapped, core::arch::x86_64::_mm_set1_ps(1024.0)),
392                    core::arch::x86_64::_mm_set1_ps(0.5),
393                );
394                core::arch::x86_64::_mm_storeu_si128(
395                    out.as_mut_ptr().cast::<core::arch::x86_64::__m128i>(),
396                    core::arch::x86_64::_mm_cvttps_epi32(scaled),
397                );
398            }
399            [
400                (out[0].clamp(0, 1024)) as u32,
401                (out[1].clamp(0, 1024)) as u32,
402                (out[2].clamp(0, 1024)) as u32,
403                (out[3].clamp(0, 1024)) as u32,
404            ]
405        }
406        #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
407        {
408            let mut out: [u32; 4] = [0; 4];
409            // SAFETY: `vals` and `out` are valid 16-byte stack arrays; `simd128` is enabled on `wasm32`.
410            unsafe {
411                let zero: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(0.0);
412                let one: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_splat(1.0);
413                let sample_x: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmax(
414                    core::arch::wasm32::v128_load(vals.as_ptr().cast()),
415                    zero,
416                );
417                let num: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_mul(
418                    sample_x,
419                    core::arch::wasm32::f32x4_add(
420                        core::arch::wasm32::f32x4_mul(
421                            sample_x,
422                            core::arch::wasm32::f32x4_splat(2.51),
423                        ),
424                        core::arch::wasm32::f32x4_splat(0.03),
425                    ),
426                );
427                let den: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
428                    core::arch::wasm32::f32x4_mul(
429                        sample_x,
430                        core::arch::wasm32::f32x4_add(
431                            core::arch::wasm32::f32x4_mul(
432                                sample_x,
433                                core::arch::wasm32::f32x4_splat(2.43),
434                            ),
435                            core::arch::wasm32::f32x4_splat(0.59),
436                        ),
437                    ),
438                    core::arch::wasm32::f32x4_splat(0.14),
439                );
440                let mapped: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_pmin(
441                    core::arch::wasm32::f32x4_pmax(core::arch::wasm32::f32x4_div(num, den), zero),
442                    one,
443                );
444                let scaled: core::arch::wasm32::v128 = core::arch::wasm32::f32x4_add(
445                    core::arch::wasm32::f32x4_mul(mapped, core::arch::wasm32::f32x4_splat(1024.0)),
446                    core::arch::wasm32::f32x4_splat(0.5),
447                );
448                core::arch::wasm32::v128_store(
449                    out.as_mut_ptr().cast(),
450                    core::arch::wasm32::u32x4_trunc_sat_f32x4(scaled),
451                );
452            }
453            [
454                out[0].min(1024),
455                out[1].min(1024),
456                out[2].min(1024),
457                out[3].min(1024),
458            ]
459        }
460        #[cfg(not(target_arch = "aarch64"))]
461        #[cfg(not(target_arch = "x86_64"))]
462        #[cfg(not(all(target_arch = "wasm32", target_feature = "simd128")))]
463        {
464            let mut out: [u32; 4] = [0; 4];
465            for item_index in 0..4 {
466                let value_x: f32 = vals[item_index].max(0.0);
467                let num: f32 = value_x * value_x.mul_add(2.51, 0.03);
468                let den: f32 = value_x.mul_add(value_x.mul_add(2.43, 0.59), 0.14);
469                let idx: u32 = ((num / den).clamp(0.0, 1.0).mul_add(1024.0, 0.5)) as u32;
470                out[item_index] = idx.min(1024);
471            }
472            out
473        }
474    }
475
476    /// Vectorized 4-pixel ACES filmic tone mapper returning RGBA8 pixels and Rec.601 luma bytes.
477    ///
478    /// # Arguments
479    ///
480    /// - `[f32; 4]` - Four linear HDR red channel values.
481    /// - `[f32; 4]` - Four linear HDR green channel values.
482    /// - `[f32; 4]` - Four linear HDR blue channel values.
483    ///
484    /// # Returns
485    ///
486    /// - `([[u8; 4]; 4], [u8; 4])` - Tone-mapped RGBA8 pixels and corresponding Rec.601 luma values.
487    #[inline(always)]
488    #[must_use]
489    pub fn aces_rgba8_luma_4x(
490        red_val: [f32; 4],
491        green_val: [f32; 4],
492        blue_val: [f32; 4],
493    ) -> ([[u8; 4]; 4], [u8; 4]) {
494        let ir: [u32; 4] = Self::aces_indices_4x(red_val);
495        let ig: [u32; 4] = Self::aces_indices_4x(green_val);
496        let ib: [u32; 4] = Self::aces_indices_4x(blue_val);
497        let mut rgba: [[u8; 4]; 4] = [[0, 0, 0, 255]; 4];
498        let mut luma: [u8; 4] = [0; 4];
499        for item_index in 0..4 {
500            let rv: u8 = LINEAR_TO_SRGB_LUT[ir[item_index] as usize];
501            let gv: u8 = LINEAR_TO_SRGB_LUT[ig[item_index] as usize];
502            let bv: u8 = LINEAR_TO_SRGB_LUT[ib[item_index] as usize];
503            rgba[item_index] = [rv, gv, bv, 255];
504            luma[item_index] =
505                (((rv as u32) * 77 + (gv as u32) * 150 + (bv as u32) * 29) >> 8) as u8;
506        }
507        (rgba, luma)
508    }
509}
510
511/// Component-wise vector addition for `Vec3`.
512impl Add for Vec3 {
513    type Output = Self;
514
515    /// Adds two vectors component-wise.
516    ///
517    /// # Arguments
518    ///
519    /// - `Self` - Left vector.
520    /// - `Self` - Right vector.
521    ///
522    /// # Returns
523    ///
524    /// - `Self` - Component-wise sum.
525    #[inline(always)]
526    fn add(self, rhs: Self) -> Self {
527        Self {
528            x: self.get_x() + rhs.get_x(),
529            y: self.get_y() + rhs.get_y(),
530            z: self.get_z() + rhs.get_z(),
531        }
532    }
533}
534
535/// Component-wise vector subtraction for `Vec3`.
536impl Sub for Vec3 {
537    type Output = Self;
538
539    /// Subtracts `rhs` from `self`.
540    ///
541    /// # Arguments
542    ///
543    /// - `Self` - Left vector.
544    /// - `Self` - Right vector.
545    ///
546    /// # Returns
547    ///
548    /// - `Self` - Component-wise difference.
549    #[inline(always)]
550    fn sub(self, rhs: Self) -> Self {
551        Self {
552            x: self.get_x() - rhs.get_x(),
553            y: self.get_y() - rhs.get_y(),
554            z: self.get_z() - rhs.get_z(),
555        }
556    }
557}
558
559/// Component-wise Hadamard vector multiplication for `Vec3`.
560impl Mul for Vec3 {
561    type Output = Self;
562
563    /// Multiplies two vectors component-wise.
564    ///
565    /// # Arguments
566    ///
567    /// - `Self` - Left vector.
568    /// - `Self` - Right vector.
569    ///
570    /// # Returns
571    ///
572    /// - `Self` - Component-wise product.
573    #[inline(always)]
574    fn mul(self, rhs: Self) -> Self {
575        Self {
576            x: self.get_x() * rhs.get_x(),
577            y: self.get_y() * rhs.get_y(),
578            z: self.get_z() * rhs.get_z(),
579        }
580    }
581}
582
583/// Matrix multiplication `self * rhs` for `Mat4`.
584impl Mul for Mat4 {
585    type Output = Self;
586
587    /// Multiplies `self * rhs`.
588    ///
589    /// # Arguments
590    ///
591    /// - `Self` - Left matrix.
592    /// - `Self` - Right matrix.
593    ///
594    /// # Returns
595    ///
596    /// - `Self` - Product matrix.
597    fn mul(self, rhs: Self) -> Self {
598        let alpha_val: [f32; 16] = self.get_elements();
599        let blue_val: [f32; 16] = rhs.get_elements();
600        let mut out: [f32; 16] = [0.0; 16];
601        for col in 0..4 {
602            for row in 0..4 {
603                out[col * 4 + row] = alpha_val[row] * blue_val[col * 4]
604                    + alpha_val[4 + row] * blue_val[col * 4 + 1]
605                    + alpha_val[8 + row] * blue_val[col * 4 + 2]
606                    + alpha_val[12 + row] * blue_val[col * 4 + 3];
607            }
608        }
609        Self { elements: out }
610    }
611}
612
613/// Matrix constructors, projection, and point projection for `Mat4`.
614impl Mat4 {
615    /// Identity 4x4 matrix.
616    ///
617    /// # Returns
618    ///
619    /// - `Self` - Identity matrix.
620    #[must_use]
621    pub const fn identity() -> Self {
622        Self {
623            elements: [
624                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
625            ],
626        }
627    }
628
629    /// Builds a right-handed perspective projection matrix.
630    ///
631    /// # Arguments
632    ///
633    /// - `f32` - Vertical FOV in radians.
634    /// - `f32` - Viewport aspect ratio `width / height`.
635    /// - `f32` - Near plane distance.
636    /// - `f32` - Far plane distance.
637    ///
638    /// # Returns
639    ///
640    /// - `Self` - Perspective projection matrix.
641    #[must_use]
642    pub fn perspective(fov_rad: f32, aspect: f32, near: f32, far: f32) -> Self {
643        let factor_val: f32 = 1.0 / (fov_rad * 0.5).tan().max(1e-4);
644        let nf: f32 = 1.0 / (near - far);
645        Self {
646            elements: [
647                factor_val / aspect.max(0.01),
648                0.0,
649                0.0,
650                0.0,
651                0.0,
652                factor_val,
653                0.0,
654                0.0,
655                0.0,
656                0.0,
657                (far + near) * nf,
658                -1.0,
659                0.0,
660                0.0,
661                2.0 * far * near * nf,
662                0.0,
663            ],
664        }
665    }
666
667    /// Builds a right-handed look-at view matrix.
668    ///
669    /// # Arguments
670    ///
671    /// - `Vec3` - Camera eye position.
672    /// - `Vec3` - Target look-at position.
673    /// - `Vec3` - World up direction.
674    ///
675    /// # Returns
676    ///
677    /// - `Self` - View transformation matrix.
678    #[must_use]
679    pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self {
680        let vec_value: Vec3 = target.sub(eye).normalize();
681        let direction_vec: Vec3 = vec_value.cross(up).normalize();
682        let position_vec: Vec3 = direction_vec.cross(vec_value);
683        Self {
684            elements: [
685                direction_vec.get_x(),
686                position_vec.get_x(),
687                -vec_value.get_x(),
688                0.0,
689                direction_vec.get_y(),
690                position_vec.get_y(),
691                -vec_value.get_y(),
692                0.0,
693                direction_vec.get_z(),
694                position_vec.get_z(),
695                -vec_value.get_z(),
696                0.0,
697                -direction_vec.dot(eye),
698                -position_vec.dot(eye),
699                vec_value.dot(eye),
700                1.0,
701            ],
702        }
703    }
704
705    /// Builds a TRS model matrix (`translate * rotate_y * scale`).
706    ///
707    /// # Arguments
708    ///
709    /// - `Vec3` - World translation.
710    /// - `f32` - Y-axis yaw rotation in radians.
711    /// - `Vec3` - Non-uniform scale.
712    ///
713    /// # Returns
714    ///
715    /// - `Self` - Composed model transform matrix.
716    #[must_use]
717    pub fn from_trs(position: Vec3, yaw_rad: f32, scale: Vec3) -> Self {
718        let char_item: f32 = yaw_rad.cos();
719        let source_val: f32 = yaw_rad.sin();
720        Self {
721            elements: [
722                char_item * scale.get_x(),
723                0.0,
724                -source_val * scale.get_x(),
725                0.0,
726                0.0,
727                scale.get_y(),
728                0.0,
729                0.0,
730                source_val * scale.get_z(),
731                0.0,
732                char_item * scale.get_z(),
733                0.0,
734                position.get_x(),
735                position.get_y(),
736                position.get_z(),
737                1.0,
738            ],
739        }
740    }
741
742    /// Builds a full 3D Euler TRS model matrix (`translate * rotate_y(yaw) * rotate_x(pitch) * rotate_z(roll) * scale`).
743    ///
744    /// # Arguments
745    ///
746    /// - `Vec3` - World translation.
747    /// - `f32` - Y-axis yaw rotation in radians.
748    /// - `f32` - X-axis pitch rotation in radians.
749    /// - `f32` - Z-axis roll rotation in radians.
750    /// - `Vec3` - Non-uniform scale.
751    ///
752    /// # Returns
753    ///
754    /// - `Self` - Composed 3D model transform matrix.
755    #[must_use]
756    pub fn from_trs_euler(
757        position: Vec3,
758        yaw_rad: f32,
759        pitch_rad: f32,
760        roll_rad: f32,
761        scale: Vec3,
762    ) -> Self {
763        if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
764            return Self::from_trs(position, yaw_rad, scale);
765        }
766        let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
767        let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
768        let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
769        let r00: f32 = cy * cr + sy * sp * sr;
770        let r10: f32 = cp * sr;
771        let r20: f32 = -sy * cr + cy * sp * sr;
772        let r01: f32 = -cy * sr + sy * sp * cr;
773        let r11: f32 = cp * cr;
774        let r21: f32 = sy * sr + cy * sp * cr;
775        let r02: f32 = sy * cp;
776        let r12: f32 = -sp;
777        let r22: f32 = cy * cp;
778        let sx: f32 = scale.get_x();
779        let sy_sc: f32 = scale.get_y();
780        let sz: f32 = scale.get_z();
781        Self {
782            elements: [
783                r00 * sx,
784                r10 * sx,
785                r20 * sx,
786                0.0,
787                r01 * sy_sc,
788                r11 * sy_sc,
789                r21 * sy_sc,
790                0.0,
791                r02 * sz,
792                r12 * sz,
793                r22 * sz,
794                0.0,
795                position.get_x(),
796                position.get_y(),
797                position.get_z(),
798                1.0,
799            ],
800        }
801    }
802
803    /// Transforms a 3D point returning homogeneous clip coordinates `(x, y, z, w)`.
804    ///
805    /// # Arguments
806    ///
807    /// - `&Self` - Transformation matrix.
808    /// - `Vec3` - Input 3D position.
809    ///
810    /// # Returns
811    ///
812    /// - `[f32; 4]` - Homogeneous clip-space coordinates.
813    #[inline(always)]
814    #[must_use]
815    pub fn mul_point4(&self, vec_value: Vec3) -> [f32; 4] {
816        let matrix_elems: [f32; 16] = self.get_elements();
817        let px: f32 = vec_value.get_x();
818        let py: f32 = vec_value.get_y();
819        let pz: f32 = vec_value.get_z();
820        [
821            px.mul_add(
822                matrix_elems[0],
823                py.mul_add(
824                    matrix_elems[4],
825                    pz.mul_add(matrix_elems[8], matrix_elems[12]),
826                ),
827            ),
828            px.mul_add(
829                matrix_elems[1],
830                py.mul_add(
831                    matrix_elems[5],
832                    pz.mul_add(matrix_elems[9], matrix_elems[13]),
833                ),
834            ),
835            px.mul_add(
836                matrix_elems[2],
837                py.mul_add(
838                    matrix_elems[6],
839                    pz.mul_add(matrix_elems[10], matrix_elems[14]),
840                ),
841            ),
842            px.mul_add(
843                matrix_elems[3],
844                py.mul_add(
845                    matrix_elems[7],
846                    pz.mul_add(matrix_elems[11], matrix_elems[15]),
847                ),
848            ),
849        ]
850    }
851
852    /// Transforms a 3D point by the upper 3x4 affine portion of `self`.
853    ///
854    /// # Arguments
855    ///
856    /// - `&Self` - Affine transformation matrix.
857    /// - `Vec3` - Input 3D position.
858    ///
859    /// # Returns
860    ///
861    /// - `Vec3` - Transformed 3D position.
862    #[inline(always)]
863    #[must_use]
864    pub fn mul_point3(&self, vec_value: Vec3) -> Vec3 {
865        let matrix_elems: [f32; 16] = self.get_elements();
866        let px: f32 = vec_value.get_x();
867        let py: f32 = vec_value.get_y();
868        let pz: f32 = vec_value.get_z();
869        Vec3::new(
870            px.mul_add(
871                matrix_elems[0],
872                py.mul_add(
873                    matrix_elems[4],
874                    pz.mul_add(matrix_elems[8], matrix_elems[12]),
875                ),
876            ),
877            px.mul_add(
878                matrix_elems[1],
879                py.mul_add(
880                    matrix_elems[5],
881                    pz.mul_add(matrix_elems[9], matrix_elems[13]),
882                ),
883            ),
884            px.mul_add(
885                matrix_elems[2],
886                py.mul_add(
887                    matrix_elems[6],
888                    pz.mul_add(matrix_elems[10], matrix_elems[14]),
889                ),
890            ),
891        )
892    }
893
894    /// Transforms a 3D direction vector by the upper-left 3x3 linear portion of `self` (no translation).
895    ///
896    /// # Arguments
897    ///
898    /// - `&Self` - Transformation matrix.
899    /// - `Vec3` - Input 3D vector.
900    ///
901    /// # Returns
902    ///
903    /// - `Vec3` - Linearly transformed 3D vector.
904    #[inline(always)]
905    #[must_use]
906    pub fn mul_vec3(&self, vec_value: Vec3) -> Vec3 {
907        let matrix_elems: [f32; 16] = self.get_elements();
908        let vx: f32 = vec_value.get_x();
909        let vy: f32 = vec_value.get_y();
910        let vz: f32 = vec_value.get_z();
911        Vec3::new(
912            vx.mul_add(
913                matrix_elems[0],
914                vy.mul_add(matrix_elems[4], vz * matrix_elems[8]),
915            ),
916            vx.mul_add(
917                matrix_elems[1],
918                vy.mul_add(matrix_elems[5], vz * matrix_elems[9]),
919            ),
920            vx.mul_add(
921                matrix_elems[2],
922                vy.mul_add(matrix_elems[6], vz * matrix_elems[10]),
923            ),
924        )
925    }
926
927    /// Transforms a local `AxisAlignedBox3D` into an enclosing world-space `AxisAlignedBox3D` via Arvo's 18-multiply method (zero corner loop, zero trigonometry).
928    ///
929    /// # Arguments
930    ///
931    /// - `&Self` - Affine model transformation matrix.
932    /// - `AxisAlignedBox3D` - Local-space bounding box.
933    ///
934    /// # Returns
935    ///
936    /// - `AxisAlignedBox3D` - Tight world-space enclosing axis-aligned bounding box.
937    #[inline(always)]
938    #[must_use]
939    pub fn transform_bounds(&self, local: AxisAlignedBox3D) -> AxisAlignedBox3D {
940        let matrix_elems: [f32; 16] = self.get_elements();
941        let lmin: Vec3 = local.get_min();
942        let lmax: Vec3 = local.get_max();
943        let lx0: f32 = lmin.get_x();
944        let ly0: f32 = lmin.get_y();
945        let lz0: f32 = lmin.get_z();
946        let lx1: f32 = lmax.get_x();
947        let ly1: f32 = lmax.get_y();
948        let lz1: f32 = lmax.get_z();
949        let ax0: f32 = matrix_elems[0] * lx0;
950        let ax1: f32 = matrix_elems[0] * lx1;
951        let ay0: f32 = matrix_elems[4] * ly0;
952        let ay1: f32 = matrix_elems[4] * ly1;
953        let az0: f32 = matrix_elems[8] * lz0;
954        let az1: f32 = matrix_elems[8] * lz1;
955        let out_min_x: f32 = matrix_elems[12] + ax0.min(ax1) + ay0.min(ay1) + az0.min(az1);
956        let out_max_x: f32 = matrix_elems[12] + ax0.max(ax1) + ay0.max(ay1) + az0.max(az1);
957        let bx0: f32 = matrix_elems[1] * lx0;
958        let bx1: f32 = matrix_elems[1] * lx1;
959        let by0: f32 = matrix_elems[5] * ly0;
960        let by1: f32 = matrix_elems[5] * ly1;
961        let bz0: f32 = matrix_elems[9] * lz0;
962        let bz1: f32 = matrix_elems[9] * lz1;
963        let out_min_y: f32 = matrix_elems[13] + bx0.min(bx1) + by0.min(by1) + bz0.min(bz1);
964        let out_max_y: f32 = matrix_elems[13] + bx0.max(bx1) + by0.max(by1) + bz0.max(bz1);
965        let cx0: f32 = matrix_elems[2] * lx0;
966        let cx1: f32 = matrix_elems[2] * lx1;
967        let cy0: f32 = matrix_elems[6] * ly0;
968        let cy1: f32 = matrix_elems[6] * ly1;
969        let cz0: f32 = matrix_elems[10] * lz0;
970        let cz1: f32 = matrix_elems[10] * lz1;
971        let out_min_z: f32 = matrix_elems[14] + cx0.min(cx1) + cy0.min(cy1) + cz0.min(cz1);
972        let out_max_z: f32 = matrix_elems[14] + cx0.max(cx1) + cy0.max(cy1) + cz0.max(cz1);
973        AxisAlignedBox3D::new(
974            Vec3::new(out_min_x, out_min_y, out_min_z),
975            Vec3::new(out_max_x, out_max_y, out_max_z),
976        )
977    }
978
979    /// Computes the exact analytical inverse of a TRS Euler matrix (`S^-1 * R^T * T^-1`) for object-space raytracing.
980    ///
981    /// # Arguments
982    ///
983    /// - `Vec3` - World translation.
984    /// - `f32` - Y-axis yaw rotation in radians.
985    /// - `f32` - X-axis pitch rotation in radians.
986    /// - `f32` - Z-axis roll rotation in radians.
987    /// - `Vec3` - Non-uniform scale.
988    ///
989    /// # Returns
990    ///
991    /// - `Self` - Exact inverse model matrix mapping world space back to local object space.
992    #[must_use]
993    pub fn inverse_trs_euler(
994        position: Vec3,
995        yaw_rad: f32,
996        pitch_rad: f32,
997        roll_rad: f32,
998        scale: Vec3,
999    ) -> Self {
1000        let isx: f32 = if scale.get_x().abs() > 1e-6 {
1001            1.0 / scale.get_x()
1002        } else {
1003            1.0
1004        };
1005        let isy: f32 = if scale.get_y().abs() > 1e-6 {
1006            1.0 / scale.get_y()
1007        } else {
1008            1.0
1009        };
1010        let isz: f32 = if scale.get_z().abs() > 1e-6 {
1011            1.0 / scale.get_z()
1012        } else {
1013            1.0
1014        };
1015        let (r00, r10, r20, r01, r11, r21, r02, r12, r22): (
1016            f32,
1017            f32,
1018            f32,
1019            f32,
1020            f32,
1021            f32,
1022            f32,
1023            f32,
1024            f32,
1025        ) = if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
1026            let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
1027            (cy, 0.0, -sy, 0.0, 1.0, 0.0, sy, 0.0, cy)
1028        } else {
1029            let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
1030            let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
1031            let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
1032            (
1033                cy * cr + sy * sp * sr,
1034                cp * sr,
1035                -sy * cr + cy * sp * sr,
1036                -cy * sr + sy * sp * cr,
1037                cp * cr,
1038                sy * sr + cy * sp * cr,
1039                sy * cp,
1040                -sp,
1041                cy * cp,
1042            )
1043        };
1044        let m00: f32 = r00 * isx;
1045        let m01: f32 = r10 * isx;
1046        let m02: f32 = r20 * isx;
1047        let m10: f32 = r01 * isy;
1048        let m11: f32 = r11 * isy;
1049        let m12: f32 = r21 * isy;
1050        let m20: f32 = r02 * isz;
1051        let m21: f32 = r12 * isz;
1052        let m22: f32 = r22 * isz;
1053        let px: f32 = position.get_x();
1054        let py: f32 = position.get_y();
1055        let pz: f32 = position.get_z();
1056        let tx: f32 = -(m00 * px + m01 * py + m02 * pz);
1057        let ty: f32 = -(m10 * px + m11 * py + m12 * pz);
1058        let tz: f32 = -(m20 * px + m21 * py + m22 * pz);
1059        Self {
1060            elements: [
1061                m00, m10, m20, 0.0, m01, m11, m21, 0.0, m02, m12, m22, 0.0, tx, ty, tz, 1.0,
1062            ],
1063        }
1064    }
1065
1066    /// Computes the inverse-transpose 3x3 normal transformation basis `[col_x, col_y, col_z]` (`R * S^-1`) once per object.
1067    ///
1068    /// # Arguments
1069    ///
1070    /// - `f32` - Y-axis yaw rotation in radians.
1071    /// - `f32` - X-axis pitch rotation in radians.
1072    /// - `f32` - Z-axis roll rotation in radians.
1073    /// - `Vec3` - Non-uniform scale.
1074    ///
1075    /// # Returns
1076    ///
1077    /// - `[Vec3; 3]` - Three column vectors transforming local normals into world space.
1078    #[must_use]
1079    pub fn normal_basis_from_euler_scale(
1080        yaw_rad: f32,
1081        pitch_rad: f32,
1082        roll_rad: f32,
1083        scale: Vec3,
1084    ) -> [Vec3; 3] {
1085        let isx: f32 = if scale.get_x().abs() > 1e-6 {
1086            1.0 / scale.get_x()
1087        } else {
1088            1.0
1089        };
1090        let isy: f32 = if scale.get_y().abs() > 1e-6 {
1091            1.0 / scale.get_y()
1092        } else {
1093            1.0
1094        };
1095        let isz: f32 = if scale.get_z().abs() > 1e-6 {
1096            1.0 / scale.get_z()
1097        } else {
1098            1.0
1099        };
1100        if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
1101            let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
1102            return [
1103                Vec3::new(cy * isx, 0.0, -sy * isx),
1104                Vec3::new(0.0, isy, 0.0),
1105                Vec3::new(sy * isz, 0.0, cy * isz),
1106            ];
1107        }
1108        let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
1109        let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
1110        let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
1111        [
1112            Vec3::new(
1113                (cy * cr + sy * sp * sr) * isx,
1114                (cp * sr) * isx,
1115                (-sy * cr + cy * sp * sr) * isx,
1116            ),
1117            Vec3::new(
1118                (-cy * sr + sy * sp * cr) * isy,
1119                (cp * cr) * isy,
1120                (sy * sr + cy * sp * cr) * isy,
1121            ),
1122            Vec3::new((sy * cp) * isz, (-sp) * isz, (cy * cp) * isz),
1123        ]
1124    }
1125
1126    /// Transforms a local surface normal using a precomputed 3x3 `normal_basis` without trigonometry.
1127    ///
1128    /// # Arguments
1129    ///
1130    /// - `Vec3` - Local-space normal vector.
1131    /// - `[Vec3; 3]` - Precomputed inverse-transpose 3x3 normal basis `[col_x, col_y, col_z]`.
1132    ///
1133    /// # Returns
1134    ///
1135    /// - `Vec3` - Normalized world-space surface normal.
1136    #[inline(always)]
1137    #[must_use]
1138    pub fn transform_normal_with_basis(vec_value: Vec3, basis: [Vec3; 3]) -> Vec3 {
1139        let nx: f32 = vec_value.get_x();
1140        let ny: f32 = vec_value.get_y();
1141        let nz: f32 = vec_value.get_z();
1142        Vec3::new(
1143            nx.mul_add(
1144                basis[0].get_x(),
1145                ny.mul_add(basis[1].get_x(), nz * basis[2].get_x()),
1146            ),
1147            nx.mul_add(
1148                basis[0].get_y(),
1149                ny.mul_add(basis[1].get_y(), nz * basis[2].get_y()),
1150            ),
1151            nx.mul_add(
1152                basis[0].get_z(),
1153                ny.mul_add(basis[1].get_z(), nz * basis[2].get_z()),
1154            ),
1155        )
1156        .normalize()
1157    }
1158}
1159
1160/// Bounding-box union, centroid, surface area, and ray-slab intersection for `AxisAlignedBox3D`.
1161impl AxisAlignedBox3D {
1162    /// Creates an inverted empty axis-aligned bounding box ready to accumulate points via `expand_point`.
1163    ///
1164    /// # Returns
1165    ///
1166    /// - `Self` - Empty axis-aligned bounding box.
1167    #[must_use]
1168    pub const fn empty() -> Self {
1169        Self {
1170            min: Vec3::splat(f32::INFINITY),
1171            max: Vec3::splat(f32::NEG_INFINITY),
1172        }
1173    }
1174
1175    /// Expands this bounding box to include `point`.
1176    ///
1177    /// # Arguments
1178    ///
1179    /// - `&Self` - Mutable axis-aligned bounding box.
1180    /// - `Vec3` - Point to enclose.
1181    pub fn expand_point(&mut self, point: Vec3) {
1182        let mn: Vec3 = self.get_min().min(point);
1183        let mx: Vec3 = self.get_max().max(point);
1184        self.set_min(mn);
1185        self.set_max(mx);
1186    }
1187
1188    /// Expands this bounding box to include `other`.
1189    ///
1190    /// # Arguments
1191    ///
1192    /// - `&Self` - Mutable axis-aligned bounding box.
1193    /// - `Self` - Other bounding box.
1194    pub fn expand_box(&mut self, other: Self) {
1195        let mn: Vec3 = self.get_min().min(other.get_min());
1196        let mx: Vec3 = self.get_max().max(other.get_max());
1197        self.set_min(mn);
1198        self.set_max(mx);
1199    }
1200
1201    /// Returns the geometric center of the axis-aligned bounding box.
1202    ///
1203    /// # Arguments
1204    ///
1205    /// - `&Self` - axis-aligned bounding box reference.
1206    ///
1207    /// # Returns
1208    ///
1209    /// - `Vec3` - Box centroid.
1210    #[must_use]
1211    pub fn center(&self) -> Vec3 {
1212        self.get_min().add(self.get_max()).scale(0.5)
1213    }
1214
1215    /// Computes bounding-sphere radius enclosing this box.
1216    ///
1217    /// # Arguments
1218    ///
1219    /// - `&Self` - axis-aligned bounding box reference.
1220    ///
1221    /// # Returns
1222    ///
1223    /// - `f32` - Enclosing radius.
1224    #[must_use]
1225    pub fn radius(&self) -> f32 {
1226        self.get_max().sub(self.get_min()).length() * 0.5
1227    }
1228
1229    /// Computes half surface area (`dx*dy + dy*dz + dz*dx`) for Surface Area Heuristic (SAH) BVH splits.
1230    ///
1231    /// # Arguments
1232    ///
1233    /// - `&Self` - axis-aligned bounding box reference.
1234    ///
1235    /// # Returns
1236    ///
1237    /// - `f32` - Non-negative half surface area.
1238    #[must_use]
1239    pub fn surface_area(&self) -> f32 {
1240        let vec_value: Vec3 = self.get_max().sub(self.get_min());
1241        let dx: f32 = vec_value.get_x().max(0.0);
1242        let dy: f32 = vec_value.get_y().max(0.0);
1243        let dz: f32 = vec_value.get_z().max(0.0);
1244        dx * dy + dy * dz + dz * dx
1245    }
1246
1247    /// Branchless slab Ray-axis-aligned bounding box intersection returning entry distance `tmin` or `f32::INFINITY` on miss.
1248    ///
1249    /// # Arguments
1250    ///
1251    /// - `&Self` - axis-aligned bounding box reference.
1252    /// - `Vec3` - Ray origin.
1253    /// - `Vec3` - Precomputed safe reciprocal ray direction.
1254    /// - `f32` - Minimum valid distance.
1255    /// - `f32` - Maximum valid distance.
1256    ///
1257    /// # Returns
1258    ///
1259    /// - `f32` - Near intersection distance if hit, or `f32::INFINITY` if missed.
1260    #[must_use]
1261    pub fn intersect_ray_near(&self, origin: Vec3, inv_dir: Vec3, t_min: f32, t_max: f32) -> f32 {
1262        let mn: Vec3 = self.get_min();
1263        let mx: Vec3 = self.get_max();
1264        let tx1: f32 = (mn.get_x() - origin.get_x()) * inv_dir.get_x();
1265        let tx2: f32 = (mx.get_x() - origin.get_x()) * inv_dir.get_x();
1266        let mut tmin: f32 = t_min.max(tx1.min(tx2));
1267        let mut tmax: f32 = t_max.min(tx1.max(tx2));
1268        let ty1: f32 = (mn.get_y() - origin.get_y()) * inv_dir.get_y();
1269        let ty2: f32 = (mx.get_y() - origin.get_y()) * inv_dir.get_y();
1270        tmin = tmin.max(ty1.min(ty2));
1271        tmax = tmax.min(ty1.max(ty2));
1272        let tz1: f32 = (mn.get_z() - origin.get_z()) * inv_dir.get_z();
1273        let tz2: f32 = (mx.get_z() - origin.get_z()) * inv_dir.get_z();
1274        tmin = tmin.max(tz1.min(tz2));
1275        tmax = tmax.min(tz1.max(tz2));
1276        if tmax >= tmin && tmax >= 0.0 {
1277            tmin
1278        } else {
1279            f32::INFINITY
1280        }
1281    }
1282
1283    /// Branchless slab Ray-axis-aligned bounding box intersection returning `true` when `ray` hits within `[t_min, t_max]`.
1284    ///
1285    /// # Arguments
1286    ///
1287    /// - `&Self` - axis-aligned bounding box reference.
1288    /// - `&Ray3D` - Ray with precomputed inverse direction.
1289    /// - `f32` - Minimum valid distance.
1290    /// - `f32` - Maximum valid distance.
1291    ///
1292    /// # Returns
1293    ///
1294    /// - `bool` - Whether the ray intersects this box.
1295    #[must_use]
1296    pub fn intersects_ray(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1297        self.intersect_ray_near(ray.get_origin(), ray.get_inv_direction(), t_min, t_max)
1298            .is_finite()
1299    }
1300}
1301
1302/// Ray construction with safe reciprocal components for `Ray3D`.
1303impl Ray3D {
1304    /// Safe reciprocal scalar preventing division by zero in slab ray-box tests.
1305    ///
1306    /// # Arguments
1307    ///
1308    /// - `f32` - Component scalar.
1309    ///
1310    /// # Returns
1311    ///
1312    /// - `f32` - Clamped reciprocal value.
1313    #[must_use]
1314    fn safe_inv(item_val: f32) -> f32 {
1315        if item_val.abs() < 1e-7 {
1316            if item_val < 0.0 { -1e7 } else { 1e7 }
1317        } else {
1318            1.0 / item_val
1319        }
1320    }
1321
1322    /// Computes safe reciprocal vector for an already-normalized ray direction.
1323    ///
1324    /// # Arguments
1325    ///
1326    /// - `Vec3` - Unit ray direction.
1327    ///
1328    /// # Returns
1329    ///
1330    /// - `Vec3` - Reciprocal direction safe for slab ray-axis-aligned bounding box intersection.
1331    #[must_use]
1332    pub fn safe_inv_vec(dir: Vec3) -> Vec3 {
1333        Vec3::new(
1334            Self::safe_inv(dir.get_x()),
1335            Self::safe_inv(dir.get_y()),
1336            Self::safe_inv(dir.get_z()),
1337        )
1338    }
1339
1340    /// Constructs a normalized `Ray3D` with safe reciprocal direction components.
1341    ///
1342    /// # Arguments
1343    ///
1344    /// - `Vec3` - Ray origin.
1345    /// - `Vec3` - Ray direction (normalized internally).
1346    ///
1347    /// # Returns
1348    ///
1349    /// - `Self` - Ready BVH ray.
1350    #[must_use]
1351    pub fn new(origin: Vec3, direction: Vec3) -> Self {
1352        let dir: Vec3 = direction.normalize();
1353        Self {
1354            origin,
1355            direction: dir,
1356            inv_direction: Vec3::new(
1357                Self::safe_inv(dir.get_x()),
1358                Self::safe_inv(dir.get_y()),
1359                Self::safe_inv(dir.get_z()),
1360            ),
1361        }
1362    }
1363}
1364
1365/// Gribb-Hartmann 6-plane frustum extraction and axis-aligned bounding box visibility testing for `Frustum3D`.
1366impl Frustum3D {
1367    /// Normalizes a 4-component plane equation `(a, b, c, d)`.
1368    ///
1369    /// # Arguments
1370    ///
1371    /// - `[f32; 4]` - Raw plane coefficients.
1372    ///
1373    /// # Returns
1374    ///
1375    /// - `[f32; 4]` - Unit-normal plane coefficients.
1376    #[must_use]
1377    fn normalize_plane(point_val: [f32; 4]) -> [f32; 4] {
1378        let len: f32 = (point_val[0] * point_val[0]
1379            + point_val[1] * point_val[1]
1380            + point_val[2] * point_val[2])
1381            .sqrt()
1382            .max(1e-6);
1383        [
1384            point_val[0] / len,
1385            point_val[1] / len,
1386            point_val[2] / len,
1387            point_val[3] / len,
1388        ]
1389    }
1390
1391    /// Extracts the 6 normalized view-frustum planes from a column-major view-projection matrix.
1392    ///
1393    /// # Arguments
1394    ///
1395    /// - `&Mat4` - Combined `projection * view` matrix.
1396    ///
1397    /// # Returns
1398    ///
1399    /// - `Self` - Normalized 6-plane frustum.
1400    #[must_use]
1401    pub fn from_view_proj(matrix_value: &Mat4) -> Self {
1402        let matrix_elems: [f32; 16] = matrix_value.get_elements();
1403        let r0: [f32; 4] = [
1404            matrix_elems[0],
1405            matrix_elems[4],
1406            matrix_elems[8],
1407            matrix_elems[12],
1408        ];
1409        let r1: [f32; 4] = [
1410            matrix_elems[1],
1411            matrix_elems[5],
1412            matrix_elems[9],
1413            matrix_elems[13],
1414        ];
1415        let r2: [f32; 4] = [
1416            matrix_elems[2],
1417            matrix_elems[6],
1418            matrix_elems[10],
1419            matrix_elems[14],
1420        ];
1421        let r3: [f32; 4] = [
1422            matrix_elems[3],
1423            matrix_elems[7],
1424            matrix_elems[11],
1425            matrix_elems[15],
1426        ];
1427        Self {
1428            planes: [
1429                Self::normalize_plane([r3[0] + r0[0], r3[1] + r0[1], r3[2] + r0[2], r3[3] + r0[3]]),
1430                Self::normalize_plane([r3[0] - r0[0], r3[1] - r0[1], r3[2] - r0[2], r3[3] - r0[3]]),
1431                Self::normalize_plane([r3[0] + r1[0], r3[1] + r1[1], r3[2] + r1[2], r3[3] + r1[3]]),
1432                Self::normalize_plane([r3[0] - r1[0], r3[1] - r1[1], r3[2] - r1[2], r3[3] - r1[3]]),
1433                Self::normalize_plane([r3[0] + r2[0], r3[1] + r2[1], r3[2] + r2[2], r3[3] + r2[3]]),
1434                Self::normalize_plane([r3[0] - r2[0], r3[1] - r2[1], r3[2] - r2[2], r3[3] - r2[3]]),
1435            ],
1436        }
1437    }
1438
1439    /// Returns `true` when `bounds_rect` is at least partially inside the view frustum.
1440    ///
1441    /// # Arguments
1442    ///
1443    /// - `&Self` - Frustum reference.
1444    /// - `&AxisAlignedBox3D` - World-space axis-aligned bounding box to test.
1445    ///
1446    /// # Returns
1447    ///
1448    /// - `bool` - `true` if potentially visible, `false` if completely culled.
1449    #[must_use]
1450    pub fn intersects_bounds(&self, bounds_rect: &AxisAlignedBox3D) -> bool {
1451        let mn: Vec3 = bounds_rect.get_min();
1452        let mx: Vec3 = bounds_rect.get_max();
1453        for point_val in self.get_planes().iter() {
1454            let px: f32 = if point_val[0] >= 0.0 {
1455                mx.get_x()
1456            } else {
1457                mn.get_x()
1458            };
1459            let py: f32 = if point_val[1] >= 0.0 {
1460                mx.get_y()
1461            } else {
1462                mn.get_y()
1463            };
1464            let pz: f32 = if point_val[2] >= 0.0 {
1465                mx.get_z()
1466            } else {
1467                mn.get_z()
1468            };
1469            if point_val[0] * px + point_val[1] * py + point_val[2] * pz + point_val[3] < 0.0 {
1470                return false;
1471            }
1472        }
1473        true
1474    }
1475}
1476
1477/// Default 3D camera framing an open-world street boulevard.
1478impl Default for Camera3D {
1479    /// Creates a default street-level perspective camera.
1480    ///
1481    /// # Returns
1482    ///
1483    /// - `Self` - Default `Camera3D`.
1484    fn default() -> Self {
1485        Self {
1486            position: Vec3::new(0.0, 9.5, 28.0),
1487            yaw: -FRAC_PI_2,
1488            pitch: -0.22,
1489            fov_deg: 60.0,
1490            near: 0.3,
1491            far: 450.0,
1492        }
1493    }
1494}
1495
1496/// Orientation, movement, and view-projection helpers for `Camera3D`.
1497impl Camera3D {
1498    /// Returns the unit forward look vector derived from `(yaw, pitch)`.
1499    ///
1500    /// # Arguments
1501    ///
1502    /// - `&Self` - Camera reference.
1503    ///
1504    /// # Returns
1505    ///
1506    /// - `Vec3` - Forward unit vector.
1507    #[must_use]
1508    pub fn forward(&self) -> Vec3 {
1509        let yaw: f32 = self.get_yaw();
1510        let pitch: f32 = self.get_pitch();
1511        let cp: f32 = pitch.cos();
1512        Vec3::new(yaw.cos() * cp, pitch.sin(), yaw.sin() * cp).normalize()
1513    }
1514
1515    /// Returns the unit right vector orthogonal to `forward()` and world up.
1516    ///
1517    /// # Arguments
1518    ///
1519    /// - `&Self` - Camera reference.
1520    ///
1521    /// # Returns
1522    ///
1523    /// - `Vec3` - Right unit vector.
1524    #[must_use]
1525    pub fn right(&self) -> Vec3 {
1526        self.forward().cross(Vec3::new(0.0, 1.0, 0.0)).normalize()
1527    }
1528
1529    /// Converts a physical camera focal length and full-frame sensor height in millimeters to vertical FOV degrees.
1530    ///
1531    /// # Arguments
1532    ///
1533    /// - `f32` - Lens focal length in millimeters (e.g., `24.0`, `35.0`, `50.0`, `85.0`).
1534    /// - `f32` - Camera sensor height in millimeters (`24.0` for 35mm full-frame).
1535    ///
1536    /// # Returns
1537    ///
1538    /// - `f32` - Vertical field of view in degrees clamped to `[12.0, 120.0]`.
1539    #[must_use]
1540    pub fn focal_length_to_fov_deg(focal_length_mm: f32, sensor_height_mm: f32) -> f32 {
1541        let f_mm: f32 = focal_length_mm.max(8.0);
1542        let s_mm: f32 = sensor_height_mm.max(4.0);
1543        (2.0 * (s_mm / (2.0 * f_mm)).atan().to_degrees()).clamp(12.0, 120.0)
1544    }
1545
1546    /// Constructs a physically based 35mm full-frame `Camera3D` using lens focal length in millimeters.
1547    ///
1548    /// # Arguments
1549    ///
1550    /// - `Vec3` - World-space eye position.
1551    /// - `f32` - Horizontal yaw angle in radians.
1552    /// - `f32` - Vertical pitch angle in radians.
1553    /// - `f32` - Lens focal length in millimeters.
1554    ///
1555    /// # Returns
1556    ///
1557    /// - `Self` - Physically configured perspective camera.
1558    #[must_use]
1559    pub fn from_lens(position: Vec3, yaw: f32, pitch: f32, focal_length_mm: f32) -> Self {
1560        Self {
1561            position,
1562            yaw,
1563            pitch: pitch.clamp(-1.4, 1.4),
1564            fov_deg: Self::focal_length_to_fov_deg(focal_length_mm, 24.0),
1565            near: 0.25,
1566            far: 480.0,
1567        }
1568    }
1569
1570    /// Computes physical exposure value `EV100` from lens aperture (f-stop), shutter speed (seconds), and ISO.
1571    ///
1572    /// # Arguments
1573    ///
1574    /// - `f32` - Aperture f-number (e.g., `2.8`, `4.0`, `8.0`).
1575    /// - `f32` - Shutter exposure time in seconds (e.g., `1.0 / 125.0`).
1576    /// - `f32` - Sensor ISO sensitivity (e.g., `100.0`).
1577    ///
1578    /// # Returns
1579    ///
1580    /// - `f32` - Physical exposure value `EV100`.
1581    #[must_use]
1582    pub fn ev100(aperture_fstop: f32, shutter_seconds: f32, iso: f32) -> f32 {
1583        let item_count: f32 = aperture_fstop.max(0.7);
1584        let blend_factor: f32 = shutter_seconds.max(1e-5);
1585        let source_val: f32 = iso.max(25.0);
1586        ((item_count * item_count) / blend_factor * (100.0 / source_val)).log2()
1587    }
1588
1589    /// Converts an `EV100` exposure value into a linear HDR scene exposure multiplier.
1590    ///
1591    /// # Arguments
1592    ///
1593    /// - `f32` - Physical exposure value `EV100`.
1594    ///
1595    /// # Returns
1596    ///
1597    /// - `f32` - Linear exposure multiplier clamped to `[0.05, 8.0]`.
1598    #[must_use]
1599    pub fn exposure_scale_from_ev100(ev100: f32) -> f32 {
1600        let max_lum: f32 = 1.2 * 2.0_f32.powf(ev100);
1601        (1.0 / max_lum.max(1e-4)).clamp(0.05, 8.0)
1602    }
1603
1604    /// Orients this camera's yaw and pitch to aim directly at `target`.
1605    ///
1606    /// # Arguments
1607    ///
1608    /// - `&Self` - Mutable camera reference.
1609    /// - `Vec3` - World-space look target.
1610    pub fn look_at(&mut self, target: Vec3) {
1611        let dir: Vec3 = target.sub(self.get_position()).normalize();
1612        self.set_yaw(dir.get_z().atan2(dir.get_x()));
1613        self.set_pitch(dir.get_y().clamp(-0.98, 0.98).asin());
1614    }
1615
1616    /// Linearly interpolates camera position, shortest-arc yaw, pitch, and lens parameters between `self` and `other`.
1617    ///
1618    /// # Arguments
1619    ///
1620    /// - `Self` - Previous fixed-step 3D camera state.
1621    /// - `Self` - Current fixed-step 3D camera state.
1622    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
1623    ///
1624    /// # Returns
1625    ///
1626    /// - `Self` - Interpolated 3D camera.
1627    #[must_use]
1628    pub fn lerp(self, other: Self, alpha: f32) -> Self {
1629        let entry_index: f32 = alpha.clamp(0.0, 1.0);
1630        let diff: f32 = other.get_yaw() - self.get_yaw();
1631        let raw_yaw_delta: f32 = diff - (diff / TAU).floor() * TAU;
1632        let shortest_yaw: f32 = if raw_yaw_delta > PI {
1633            raw_yaw_delta - TAU
1634        } else {
1635            raw_yaw_delta
1636        };
1637        Self {
1638            position: self.get_position().lerp(other.get_position(), entry_index),
1639            yaw: self.get_yaw() + shortest_yaw * entry_index,
1640            pitch: (self.get_pitch() + (other.get_pitch() - self.get_pitch()) * entry_index)
1641                .clamp(-1.4, 1.4),
1642            fov_deg: self.get_fov_deg() + (other.get_fov_deg() - self.get_fov_deg()) * entry_index,
1643            near: self.get_near() + (other.get_near() - self.get_near()) * entry_index,
1644            far: self.get_far() + (other.get_far() - self.get_far()) * entry_index,
1645        }
1646    }
1647
1648    /// Computes the combined `projection * view` matrix for viewport `aspect`.
1649    ///
1650    /// # Arguments
1651    ///
1652    /// - `&Self` - Camera reference.
1653    /// - `f32` - Viewport aspect ratio `width / height`.
1654    ///
1655    /// # Returns
1656    ///
1657    /// - `Mat4` - View-projection matrix.
1658    #[must_use]
1659    pub fn view_projection(&self, aspect: f32) -> Mat4 {
1660        let pos: Vec3 = self.get_position();
1661        let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), Vec3::new(0.0, 1.0, 0.0));
1662        let proj: Mat4 = Mat4::perspective(
1663            self.get_fov_deg().to_radians(),
1664            aspect.max(0.1),
1665            self.get_near().max(0.05),
1666            self.get_far().max(10.0),
1667        );
1668        proj.mul(view)
1669    }
1670}