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