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 aspect-aware vertical field of view in radians, clamping horizontal half-tangent on ultrawide viewports to prevent edge fisheye stretching.
1649    ///
1650    /// # Arguments
1651    ///
1652    /// - `f32` - Base vertical field of view in degrees.
1653    /// - `f32` - Viewport aspect ratio `width / height`.
1654    ///
1655    /// # Returns
1656    ///
1657    /// - `f32` - Effective vertical field of view in radians.
1658    #[must_use]
1659    pub fn effective_vertical_fov_rad(base_fov_deg: f32, aspect: f32) -> f32 {
1660        let base_rad: f32 = base_fov_deg.clamp(15.0, 115.0).to_radians();
1661        let safe_aspect: f32 = aspect.max(0.1);
1662        let base_tan_half_v: f32 = (base_rad * 0.5).tan();
1663        let min_tan_half_v: f32 = (42.0_f32.to_radians() * 0.5).tan().min(base_tan_half_v);
1664        let max_tan_half_h: f32 = 1.65;
1665        let effective_tan_half_v: f32 = if base_tan_half_v * safe_aspect > max_tan_half_h {
1666            (max_tan_half_h / safe_aspect).max(min_tan_half_v)
1667        } else {
1668            base_tan_half_v
1669        };
1670        2.0 * effective_tan_half_v.atan()
1671    }
1672
1673    /// Computes the combined `projection * view` matrix for viewport `aspect`.
1674    ///
1675    /// # Arguments
1676    ///
1677    /// - `&Self` - Camera reference.
1678    /// - `f32` - Viewport aspect ratio `width / height`.
1679    ///
1680    /// # Returns
1681    ///
1682    /// - `Mat4` - View-projection matrix.
1683    #[must_use]
1684    pub fn view_projection(&self, aspect: f32) -> Mat4 {
1685        let pos: Vec3 = self.get_position();
1686        let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), Vec3::new(0.0, 1.0, 0.0));
1687        let eff_fov_rad: f32 = Self::effective_vertical_fov_rad(self.get_fov_deg(), aspect);
1688        let proj: Mat4 = Mat4::perspective(
1689            eff_fov_rad,
1690            aspect.max(0.1),
1691            self.get_near().max(0.05),
1692            self.get_far().max(10.0),
1693        );
1694        proj.mul(view)
1695    }
1696}
1697
1698/// Coordinate-space conversions and array helpers for `Vec3`.
1699impl Vec3 {
1700    /// Constructs a `Vec3` from a `[f32; 3]` array.
1701    ///
1702    /// # Arguments
1703    ///
1704    /// - `[f32; 3]` - Array `[x, y, z]`.
1705    ///
1706    /// # Returns
1707    ///
1708    /// - `Self` - Constructed 3D vector.
1709    #[must_use]
1710    pub const fn from_array(values: [f32; 3]) -> Self {
1711        Self {
1712            x: values[0],
1713            y: values[1],
1714            z: values[2],
1715        }
1716    }
1717
1718    /// Packs this vector into `[x, y, z]`.
1719    ///
1720    /// # Arguments
1721    ///
1722    /// - `&Self` - Source vector reference.
1723    ///
1724    /// # Returns
1725    ///
1726    /// - `[f32; 3]` - Component array `[x, y, z]`.
1727    #[must_use]
1728    pub fn to_array(&self) -> [f32; 3] {
1729        [self.get_x(), self.get_y(), self.get_z()]
1730    }
1731
1732    /// Converts a Blender Z-up right-handed vector `(X right, Y forward, Z up)` into Engine/glTF Y-up `(X right, Y up, -Z forward)`.
1733    ///
1734    /// # Arguments
1735    ///
1736    /// - `Self` - Vector in Blender Z-up space.
1737    ///
1738    /// # Returns
1739    ///
1740    /// - `Self` - Equivalent vector in Engine Y-up space.
1741    #[must_use]
1742    pub fn blender_z_up_to_y_up(self) -> Self {
1743        Self::new(self.get_x(), self.get_z(), -self.get_y())
1744    }
1745
1746    /// Converts an Engine/glTF Y-up right-handed vector `(X right, Y up, -Z forward)` into Blender Z-up `(X right, Y forward, Z up)`.
1747    ///
1748    /// # Arguments
1749    ///
1750    /// - `Self` - Vector in Engine Y-up space.
1751    ///
1752    /// # Returns
1753    ///
1754    /// - `Self` - Equivalent vector in Blender Z-up space.
1755    #[must_use]
1756    pub fn y_up_to_blender_z_up(self) -> Self {
1757        Self::new(self.get_x(), -self.get_z(), self.get_y())
1758    }
1759}
1760
1761/// Arithmetic and interpolation helpers for `Vec2`.
1762impl Vec2 {
1763    /// Returns the zero 2D vector `(0.0, 0.0)`.
1764    ///
1765    /// # Returns
1766    ///
1767    /// - `Self` - Zero `Vec2`.
1768    #[must_use]
1769    pub const fn zero() -> Self {
1770        Self { x: 0.0, y: 0.0 }
1771    }
1772
1773    /// Creates a `Vec2` with both components set to `scalar`.
1774    ///
1775    /// # Arguments
1776    ///
1777    /// - `f32` - Component value.
1778    ///
1779    /// # Returns
1780    ///
1781    /// - `Self` - Uniform 2D vector.
1782    #[must_use]
1783    pub const fn splat(scalar: f32) -> Self {
1784        Self {
1785            x: scalar,
1786            y: scalar,
1787        }
1788    }
1789
1790    /// Constructs a `Vec2` from `[x, y]`.
1791    ///
1792    /// # Arguments
1793    ///
1794    /// - `[f32; 2]` - Component array.
1795    ///
1796    /// # Returns
1797    ///
1798    /// - `Self` - Constructed `Vec2`.
1799    #[must_use]
1800    pub const fn from_array(values: [f32; 2]) -> Self {
1801        Self {
1802            x: values[0],
1803            y: values[1],
1804        }
1805    }
1806
1807    /// Converts this `Vec2` into `[x, y]`.
1808    ///
1809    /// # Arguments
1810    ///
1811    /// - `&Self` - Vector reference.
1812    ///
1813    /// # Returns
1814    ///
1815    /// - `[f32; 2]` - Component array.
1816    #[must_use]
1817    pub fn to_array(&self) -> [f32; 2] {
1818        [self.get_x(), self.get_y()]
1819    }
1820
1821    /// Computes component-wise dot product `self · rhs`.
1822    ///
1823    /// # Arguments
1824    ///
1825    /// - `Self` - Left vector.
1826    /// - `Self` - Right vector.
1827    ///
1828    /// # Returns
1829    ///
1830    /// - `f32` - Scalar dot product.
1831    #[must_use]
1832    pub fn dot(self, rhs: Self) -> f32 {
1833        self.get_x()
1834            .mul_add(rhs.get_x(), self.get_y() * rhs.get_y())
1835    }
1836
1837    /// Linearly interpolates between `self` and `other` by `alpha`.
1838    ///
1839    /// # Arguments
1840    ///
1841    /// - `Self` - Start vector.
1842    /// - `Self` - End vector.
1843    /// - `f32` - Interpolation factor.
1844    ///
1845    /// # Returns
1846    ///
1847    /// - `Self` - Interpolated vector.
1848    #[must_use]
1849    pub fn lerp(self, other: Self, alpha: f32) -> Self {
1850        Self::new(
1851            (other.get_x() - self.get_x()).mul_add(alpha, self.get_x()),
1852            (other.get_y() - self.get_y()).mul_add(alpha, self.get_y()),
1853        )
1854    }
1855}
1856
1857/// Arithmetic and conversion helpers for `Vec4`.
1858impl Vec4 {
1859    /// Returns the zero 4D vector `(0, 0, 0, 0)`.
1860    ///
1861    /// # Returns
1862    ///
1863    /// - `Self` - Zero `Vec4`.
1864    #[must_use]
1865    pub const fn zero() -> Self {
1866        Self {
1867            x: 0.0,
1868            y: 0.0,
1869            z: 0.0,
1870            w: 0.0,
1871        }
1872    }
1873
1874    /// Constructs a `Vec4` from `[x, y, z, w]`.
1875    ///
1876    /// # Arguments
1877    ///
1878    /// - `[f32; 4]` - Component array.
1879    ///
1880    /// # Returns
1881    ///
1882    /// - `Self` - Constructed `Vec4`.
1883    #[must_use]
1884    pub const fn from_array(values: [f32; 4]) -> Self {
1885        Self {
1886            x: values[0],
1887            y: values[1],
1888            z: values[2],
1889            w: values[3],
1890        }
1891    }
1892
1893    /// Converts this `Vec4` into `[x, y, z, w]`.
1894    ///
1895    /// # Arguments
1896    ///
1897    /// - `&Self` - Vector reference.
1898    ///
1899    /// # Returns
1900    ///
1901    /// - `[f32; 4]` - Component array.
1902    #[must_use]
1903    pub fn to_array(&self) -> [f32; 4] {
1904        [self.get_x(), self.get_y(), self.get_z(), self.get_w()]
1905    }
1906
1907    /// Extracts the leading three components `(x, y, z)` as a `Vec3`.
1908    ///
1909    /// # Arguments
1910    ///
1911    /// - `&Self` - Vector reference.
1912    ///
1913    /// # Returns
1914    ///
1915    /// - `Vec3` - Three-component vector.
1916    #[must_use]
1917    pub fn xyz(&self) -> Vec3 {
1918        Vec3::new(self.get_x(), self.get_y(), self.get_z())
1919    }
1920
1921    /// Linearly interpolates between `self` and `other` by `alpha`.
1922    ///
1923    /// # Arguments
1924    ///
1925    /// - `Self` - Start vector.
1926    /// - `Self` - End vector.
1927    /// - `f32` - Interpolation factor.
1928    ///
1929    /// # Returns
1930    ///
1931    /// - `Self` - Interpolated vector.
1932    #[must_use]
1933    pub fn lerp(self, other: Self, alpha: f32) -> Self {
1934        Self::new(
1935            (other.get_x() - self.get_x()).mul_add(alpha, self.get_x()),
1936            (other.get_y() - self.get_y()).mul_add(alpha, self.get_y()),
1937            (other.get_z() - self.get_z()).mul_add(alpha, self.get_z()),
1938            (other.get_w() - self.get_w()).mul_add(alpha, self.get_w()),
1939        )
1940    }
1941}
1942
1943/// Default identity quaternion for `Quat`.
1944impl Default for Quat {
1945    /// Returns the identity rotation quaternion `(0, 0, 0, 1)`.
1946    ///
1947    /// # Returns
1948    ///
1949    /// - `Self` - Identity quaternion.
1950    fn default() -> Self {
1951        Self::identity()
1952    }
1953}
1954
1955/// Hamilton quaternion algebra, Euler/matrix conversions, SLERP/NLERP, and Blender basis conversion for `Quat`.
1956impl Quat {
1957    /// Returns the identity quaternion `(0, 0, 0, 1)`.
1958    ///
1959    /// # Returns
1960    ///
1961    /// - `Self` - Identity quaternion.
1962    #[must_use]
1963    pub const fn identity() -> Self {
1964        Self {
1965            x: 0.0,
1966            y: 0.0,
1967            z: 0.0,
1968            w: 1.0,
1969        }
1970    }
1971
1972    /// Constructs a quaternion from raw `(x, y, z, w)` components.
1973    ///
1974    /// # Arguments
1975    ///
1976    /// - `f32` - Imaginary X component.
1977    /// - `f32` - Imaginary Y component.
1978    /// - `f32` - Imaginary Z component.
1979    /// - `f32` - Real W component.
1980    ///
1981    /// # Returns
1982    ///
1983    /// - `Self` - Constructed quaternion.
1984    #[must_use]
1985    pub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self {
1986        Self { x, y, z, w }
1987    }
1988
1989    /// Constructs a quaternion from glTF `[x, y, z, w]` ordering.
1990    ///
1991    /// # Arguments
1992    ///
1993    /// - `[f32; 4]` - Array `[x, y, z, w]`.
1994    ///
1995    /// # Returns
1996    ///
1997    /// - `Self` - Constructed quaternion.
1998    #[must_use]
1999    pub const fn from_array(values: [f32; 4]) -> Self {
2000        Self {
2001            x: values[0],
2002            y: values[1],
2003            z: values[2],
2004            w: values[3],
2005        }
2006    }
2007
2008    /// Packs this quaternion into glTF `[x, y, z, w]` ordering.
2009    ///
2010    /// # Arguments
2011    ///
2012    /// - `&Self` - Quaternion reference.
2013    ///
2014    /// # Returns
2015    ///
2016    /// - `[f32; 4]` - Component array `[x, y, z, w]`.
2017    #[must_use]
2018    pub fn to_array(&self) -> [f32; 4] {
2019        [self.get_x(), self.get_y(), self.get_z(), self.get_w()]
2020    }
2021
2022    /// Computes the 4D dot product between two quaternions.
2023    ///
2024    /// # Arguments
2025    ///
2026    /// - `Self` - Left quaternion.
2027    /// - `Self` - Right quaternion.
2028    ///
2029    /// # Returns
2030    ///
2031    /// - `f32` - Dot product scalar.
2032    #[must_use]
2033    pub fn dot(self, rhs: Self) -> f32 {
2034        self.get_x() * rhs.get_x()
2035            + self.get_y() * rhs.get_y()
2036            + self.get_z() * rhs.get_z()
2037            + self.get_w() * rhs.get_w()
2038    }
2039
2040    /// Returns the unit-length normalized quaternion (or identity when degenerate).
2041    ///
2042    /// # Arguments
2043    ///
2044    /// - `Self` - Source quaternion.
2045    ///
2046    /// # Returns
2047    ///
2048    /// - `Self` - Normalized unit quaternion.
2049    #[must_use]
2050    pub fn normalize(self) -> Self {
2051        let len_sq: f32 = self.dot(self);
2052        if len_sq > 1e-12 {
2053            let inv: f32 = 1.0 / len_sq.sqrt();
2054            Self::from_xyzw(
2055                self.get_x() * inv,
2056                self.get_y() * inv,
2057                self.get_z() * inv,
2058                self.get_w() * inv,
2059            )
2060        } else {
2061            Self::identity()
2062        }
2063    }
2064
2065    /// Returns the quaternion conjugate `(-x, -y, -z, w)` (inverse for unit quaternions).
2066    ///
2067    /// # Arguments
2068    ///
2069    /// - `Self` - Source quaternion.
2070    ///
2071    /// # Returns
2072    ///
2073    /// - `Self` - Conjugated quaternion.
2074    #[must_use]
2075    pub fn conjugate(self) -> Self {
2076        Self::from_xyzw(-self.get_x(), -self.get_y(), -self.get_z(), self.get_w())
2077    }
2078
2079    /// Composes two rotations via Hamilton multiplication `self * rhs`.
2080    ///
2081    /// # Arguments
2082    ///
2083    /// - `Self` - Outer rotation quaternion.
2084    /// - `Self` - Inner rotation quaternion.
2085    ///
2086    /// # Returns
2087    ///
2088    /// - `Self` - Product quaternion.
2089    #[must_use]
2090    pub fn mul_quat(self, rhs: Self) -> Self {
2091        let ax: f32 = self.get_x();
2092        let ay: f32 = self.get_y();
2093        let az: f32 = self.get_z();
2094        let aw: f32 = self.get_w();
2095        let bx: f32 = rhs.get_x();
2096        let by: f32 = rhs.get_y();
2097        let bz: f32 = rhs.get_z();
2098        let bw: f32 = rhs.get_w();
2099        Self::from_xyzw(
2100            aw * bx + ax * bw + ay * bz - az * by,
2101            aw * by - ax * bz + ay * bw + az * bx,
2102            aw * bz + ax * by - ay * bx + az * bw,
2103            aw * bw - ax * bx - ay * by - az * bz,
2104        )
2105    }
2106
2107    /// Rotates a 3D vector by this unit quaternion (`q * v * q^-1`).
2108    ///
2109    /// # Arguments
2110    ///
2111    /// - `Self` - Unit rotation quaternion.
2112    /// - `Vec3` - Input 3D vector.
2113    ///
2114    /// # Returns
2115    ///
2116    /// - `Vec3` - Rotated 3D vector.
2117    #[must_use]
2118    pub fn rotate_vec3(self, vec_val: Vec3) -> Vec3 {
2119        let qv: Vec3 = Vec3::new(self.get_x(), self.get_y(), self.get_z());
2120        let uv: Vec3 = qv.cross(vec_val);
2121        let uuv: Vec3 = qv.cross(uv);
2122        vec_val
2123            .add(uv.scale(2.0 * self.get_w()))
2124            .add(uuv.scale(2.0))
2125    }
2126
2127    /// Builds a unit quaternion rotating by `angle_rad` around `axis`.
2128    ///
2129    /// # Arguments
2130    ///
2131    /// - `Vec3` - Rotation axis (normalized internally).
2132    /// - `f32` - Right-handed rotation angle in radians.
2133    ///
2134    /// # Returns
2135    ///
2136    /// - `Self` - Unit axis-angle quaternion.
2137    #[must_use]
2138    pub fn from_axis_angle(axis: Vec3, angle_rad: f32) -> Self {
2139        let unit: Vec3 = axis.normalize();
2140        let half: f32 = angle_rad * 0.5;
2141        let sin_h: f32 = half.sin();
2142        let cos_h: f32 = half.cos();
2143        Self::from_xyzw(
2144            unit.get_x() * sin_h,
2145            unit.get_y() * sin_h,
2146            unit.get_z() * sin_h,
2147            cos_h,
2148        )
2149        .normalize()
2150    }
2151
2152    /// Builds a unit quaternion from Euler angles `rotate_y(yaw) * rotate_x(pitch) * rotate_z(roll)`.
2153    ///
2154    /// # Arguments
2155    ///
2156    /// - `f32` - Y-axis yaw in radians.
2157    /// - `f32` - X-axis pitch in radians.
2158    /// - `f32` - Z-axis roll in radians.
2159    ///
2160    /// # Returns
2161    ///
2162    /// - `Self` - Unit rotation quaternion matching `Mat4::from_trs_euler`.
2163    #[must_use]
2164    pub fn from_euler_yxz(yaw_rad: f32, pitch_rad: f32, roll_rad: f32) -> Self {
2165        let qy: Self = Self::from_axis_angle(Vec3::new(0.0, 1.0, 0.0), yaw_rad);
2166        let qx: Self = Self::from_axis_angle(Vec3::new(1.0, 0.0, 0.0), pitch_rad);
2167        let qz: Self = Self::from_axis_angle(Vec3::new(0.0, 0.0, 1.0), roll_rad);
2168        qy.mul_quat(qx).mul_quat(qz).normalize()
2169    }
2170
2171    /// Extracts a unit quaternion from an orthonormal 3x3 rotation basis `[col0, col1, col2]` using Shepperd's method.
2172    ///
2173    /// # Arguments
2174    ///
2175    /// - `Vec3` - First basis column (X axis).
2176    /// - `Vec3` - Second basis column (Y axis).
2177    /// - `Vec3` - Third basis column (Z axis).
2178    ///
2179    /// # Returns
2180    ///
2181    /// - `Self` - Equivalent unit quaternion.
2182    #[must_use]
2183    pub fn from_mat3(col0: Vec3, col1: Vec3, col2: Vec3) -> Self {
2184        let m00: f32 = col0.get_x();
2185        let m10: f32 = col0.get_y();
2186        let m20: f32 = col0.get_z();
2187        let m01: f32 = col1.get_x();
2188        let m11: f32 = col1.get_y();
2189        let m21: f32 = col1.get_z();
2190        let m02: f32 = col2.get_x();
2191        let m12: f32 = col2.get_y();
2192        let m22: f32 = col2.get_z();
2193        let trace: f32 = m00 + m11 + m22;
2194        if trace > 0.0 {
2195            let s: f32 = (trace + 1.0).sqrt() * 2.0;
2196            Self::from_xyzw((m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s, 0.25 * s).normalize()
2197        } else if m00 > m11 && m00 > m22 {
2198            let s: f32 = (1.0 + m00 - m11 - m22).max(1e-12).sqrt() * 2.0;
2199            Self::from_xyzw(0.25 * s, (m01 + m10) / s, (m02 + m20) / s, (m21 - m12) / s).normalize()
2200        } else if m11 > m22 {
2201            let s: f32 = (1.0 + m11 - m00 - m22).max(1e-12).sqrt() * 2.0;
2202            Self::from_xyzw((m01 + m10) / s, 0.25 * s, (m12 + m21) / s, (m02 - m20) / s).normalize()
2203        } else {
2204            let s: f32 = (1.0 + m22 - m00 - m11).max(1e-12).sqrt() * 2.0;
2205            Self::from_xyzw((m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s).normalize()
2206        }
2207    }
2208
2209    /// Converts this unit quaternion to a column-major 4x4 rotation matrix.
2210    ///
2211    /// # Arguments
2212    ///
2213    /// - `Self` - Unit rotation quaternion.
2214    ///
2215    /// # Returns
2216    ///
2217    /// - `Mat4` - Equivalent 4x4 rotation matrix.
2218    #[must_use]
2219    pub fn to_mat4(self) -> Mat4 {
2220        let q: Self = self.normalize();
2221        let x: f32 = q.get_x();
2222        let y: f32 = q.get_y();
2223        let z: f32 = q.get_z();
2224        let w: f32 = q.get_w();
2225        let xx: f32 = x * x;
2226        let yy: f32 = y * y;
2227        let zz: f32 = z * z;
2228        let xy: f32 = x * y;
2229        let xz: f32 = x * z;
2230        let yz: f32 = y * z;
2231        let wx: f32 = w * x;
2232        let wy: f32 = w * y;
2233        let wz: f32 = w * z;
2234        Mat4 {
2235            elements: [
2236                1.0 - 2.0 * (yy + zz),
2237                2.0 * (xy + wz),
2238                2.0 * (xz - wy),
2239                0.0,
2240                2.0 * (xy - wz),
2241                1.0 - 2.0 * (xx + zz),
2242                2.0 * (yz + wx),
2243                0.0,
2244                2.0 * (xz + wy),
2245                2.0 * (yz - wx),
2246                1.0 - 2.0 * (xx + yy),
2247                0.0,
2248                0.0,
2249                0.0,
2250                0.0,
2251                1.0,
2252            ],
2253        }
2254    }
2255
2256    /// Normalized shortest-arc linear interpolation (NLERP) between `self` and `other`.
2257    ///
2258    /// # Arguments
2259    ///
2260    /// - `Self` - Start unit quaternion.
2261    /// - `Self` - End unit quaternion.
2262    /// - `f32` - Interpolation factor in `[0.0, 1.0]`.
2263    ///
2264    /// # Returns
2265    ///
2266    /// - `Self` - Normalized interpolated quaternion.
2267    #[must_use]
2268    pub fn nlerp(self, other: Self, alpha: f32) -> Self {
2269        let t: f32 = alpha.clamp(0.0, 1.0);
2270        let sign: f32 = if self.dot(other) < 0.0 { -1.0 } else { 1.0 };
2271        let inv_t: f32 = 1.0 - t;
2272        Self::from_xyzw(
2273            self.get_x() * inv_t + other.get_x() * sign * t,
2274            self.get_y() * inv_t + other.get_y() * sign * t,
2275            self.get_z() * inv_t + other.get_z() * sign * t,
2276            self.get_w() * inv_t + other.get_w() * sign * t,
2277        )
2278        .normalize()
2279    }
2280
2281    /// Shortest-arc spherical linear interpolation (SLERP) between `self` and `other`.
2282    ///
2283    /// # Arguments
2284    ///
2285    /// - `Self` - Start unit quaternion.
2286    /// - `Self` - End unit quaternion.
2287    /// - `f32` - Interpolation factor in `[0.0, 1.0]`.
2288    ///
2289    /// # Returns
2290    ///
2291    /// - `Self` - Constant-angular-velocity interpolated unit quaternion.
2292    #[must_use]
2293    pub fn slerp(self, other: Self, alpha: f32) -> Self {
2294        let t: f32 = alpha.clamp(0.0, 1.0);
2295        let mut dot_val: f32 = self.dot(other);
2296        let mut target: Self = other;
2297        if dot_val < 0.0 {
2298            dot_val = -dot_val;
2299            target = Self::from_xyzw(
2300                -other.get_x(),
2301                -other.get_y(),
2302                -other.get_z(),
2303                -other.get_w(),
2304            );
2305        }
2306        if dot_val > 0.9995 {
2307            return self.nlerp(target, t);
2308        }
2309        let theta: f32 = dot_val.clamp(-1.0, 1.0).acos();
2310        let sin_theta: f32 = theta.sin().max(1e-6);
2311        let w0: f32 = ((1.0 - t) * theta).sin() / sin_theta;
2312        let w1: f32 = (t * theta).sin() / sin_theta;
2313        Self::from_xyzw(
2314            self.get_x() * w0 + target.get_x() * w1,
2315            self.get_y() * w0 + target.get_y() * w1,
2316            self.get_z() * w0 + target.get_z() * w1,
2317            self.get_w() * w0 + target.get_w() * w1,
2318        )
2319        .normalize()
2320    }
2321
2322    /// Converts a Blender Z-up quaternion `(x, y, z, w)` into Engine/glTF Y-up space via basis conjugation.
2323    ///
2324    /// # Arguments
2325    ///
2326    /// - `Self` - Quaternion in Blender Z-up space.
2327    ///
2328    /// # Returns
2329    ///
2330    /// - `Self` - Equivalent unit quaternion in Engine Y-up space.
2331    #[must_use]
2332    pub fn blender_z_up_to_y_up(self) -> Self {
2333        Self::from_xyzw(self.get_x(), self.get_z(), -self.get_y(), self.get_w()).normalize()
2334    }
2335
2336    /// Converts an Engine/glTF Y-up quaternion into Blender Z-up space via basis conjugation.
2337    ///
2338    /// # Arguments
2339    ///
2340    /// - `Self` - Quaternion in Engine Y-up space.
2341    ///
2342    /// # Returns
2343    ///
2344    /// - `Self` - Equivalent unit quaternion in Blender Z-up space.
2345    #[must_use]
2346    pub fn y_up_to_blender_z_up(self) -> Self {
2347        Self::from_xyzw(self.get_x(), -self.get_z(), self.get_y(), self.get_w()).normalize()
2348    }
2349}
2350
2351/// Default identity dual quaternion for `DualQuat`.
2352impl Default for DualQuat {
2353    /// Returns the identity rigid dual quaternion.
2354    ///
2355    /// # Returns
2356    ///
2357    /// - `Self` - Identity `DualQuat`.
2358    fn default() -> Self {
2359        Self::identity()
2360    }
2361}
2362
2363/// Rigid-body dual-quaternion algebra and hemisphere-aligned blending for `DualQuat`.
2364impl DualQuat {
2365    /// Returns the identity dual quaternion (no rotation, zero translation).
2366    ///
2367    /// # Returns
2368    ///
2369    /// - `Self` - Identity `DualQuat`.
2370    #[must_use]
2371    pub const fn identity() -> Self {
2372        Self {
2373            real: Quat::identity(),
2374            dual: Quat::from_xyzw(0.0, 0.0, 0.0, 0.0),
2375        }
2376    }
2377
2378    /// Builds a unit dual quaternion from rotation `rotation` and translation `translation`.
2379    ///
2380    /// # Arguments
2381    ///
2382    /// - `Quat` - Unit rotation quaternion.
2383    /// - `Vec3` - Translation vector.
2384    ///
2385    /// # Returns
2386    ///
2387    /// - `Self` - Unit rigid dual quaternion.
2388    #[must_use]
2389    pub fn from_rotation_translation(rotation: Quat, translation: Vec3) -> Self {
2390        let real: Quat = rotation.normalize();
2391        let t_quat: Quat = Quat::from_xyzw(
2392            translation.get_x(),
2393            translation.get_y(),
2394            translation.get_z(),
2395            0.0,
2396        );
2397        let prod: Quat = t_quat.mul_quat(real);
2398        let dual: Quat = Quat::from_xyzw(
2399            prod.get_x() * 0.5,
2400            prod.get_y() * 0.5,
2401            prod.get_z() * 0.5,
2402            prod.get_w() * 0.5,
2403        );
2404        Self { real, dual }
2405    }
2406
2407    /// Normalizes this dual quaternion so `|real| == 1` and `real · dual == 0`.
2408    ///
2409    /// # Arguments
2410    ///
2411    /// - `Self` - Input dual quaternion.
2412    ///
2413    /// # Returns
2414    ///
2415    /// - `Self` - Normalized unit dual quaternion.
2416    #[must_use]
2417    pub fn normalize(self) -> Self {
2418        let r: Quat = self.get_real();
2419        let d: Quat = self.get_dual();
2420        let norm_sq: f32 = r.dot(r);
2421        if norm_sq <= 1e-12 {
2422            return Self::identity();
2423        }
2424        let inv_norm: f32 = 1.0 / norm_sq.sqrt();
2425        let real_unit: Quat = Quat::from_xyzw(
2426            r.get_x() * inv_norm,
2427            r.get_y() * inv_norm,
2428            r.get_z() * inv_norm,
2429            r.get_w() * inv_norm,
2430        );
2431        let dual_scaled: Quat = Quat::from_xyzw(
2432            d.get_x() * inv_norm,
2433            d.get_y() * inv_norm,
2434            d.get_z() * inv_norm,
2435            d.get_w() * inv_norm,
2436        );
2437        let proj: f32 = real_unit.dot(dual_scaled);
2438        let dual_ortho: Quat = Quat::from_xyzw(
2439            dual_scaled.get_x() - real_unit.get_x() * proj,
2440            dual_scaled.get_y() - real_unit.get_y() * proj,
2441            dual_scaled.get_z() - real_unit.get_z() * proj,
2442            dual_scaled.get_w() - real_unit.get_w() * proj,
2443        );
2444        Self {
2445            real: real_unit,
2446            dual: dual_ortho,
2447        }
2448    }
2449
2450    /// Extracts the rigid translation vector `2 * dual * conjugate(real)`.
2451    ///
2452    /// # Arguments
2453    ///
2454    /// - `&Self` - Unit dual quaternion reference.
2455    ///
2456    /// # Returns
2457    ///
2458    /// - `Vec3` - Extracted translation vector.
2459    #[must_use]
2460    pub fn translation(&self) -> Vec3 {
2461        let prod: Quat = self.get_dual().mul_quat(self.get_real().conjugate());
2462        Vec3::new(prod.get_x() * 2.0, prod.get_y() * 2.0, prod.get_z() * 2.0)
2463    }
2464
2465    /// Blends up to arbitrary weighted dual quaternions with shortest-hemisphere sign alignment (DLB).
2466    ///
2467    /// # Arguments
2468    ///
2469    /// - `&[Self]` - Influencing bone dual quaternions.
2470    /// - `&[f32]` - Corresponding skinning weights.
2471    ///
2472    /// # Returns
2473    ///
2474    /// - `Self` - Normalized blended dual quaternion.
2475    #[must_use]
2476    pub fn blend_weighted(duals: &[Self], weights: &[f32]) -> Self {
2477        let count: usize = duals.len().min(weights.len());
2478        if count == 0 {
2479            return Self::identity();
2480        }
2481        let mut pivot: Option<Quat> = None;
2482        let mut sum_rx: f32 = 0.0;
2483        let mut sum_ry: f32 = 0.0;
2484        let mut sum_rz: f32 = 0.0;
2485        let mut sum_rw: f32 = 0.0;
2486        let mut sum_dx: f32 = 0.0;
2487        let mut sum_dy: f32 = 0.0;
2488        let mut sum_dz: f32 = 0.0;
2489        let mut sum_dw: f32 = 0.0;
2490        for idx in 0..count {
2491            let weight: f32 = weights[idx];
2492            if weight.abs() <= 1e-6 {
2493                continue;
2494            }
2495            let r: Quat = duals[idx].get_real();
2496            let d: Quat = duals[idx].get_dual();
2497            let sign: f32 = match pivot {
2498                Some(ref_q) => {
2499                    if ref_q.dot(r) < 0.0 {
2500                        -1.0
2501                    } else {
2502                        1.0
2503                    }
2504                }
2505                None => {
2506                    pivot = Some(r);
2507                    1.0
2508                }
2509            };
2510            let sw: f32 = weight * sign;
2511            sum_rx += r.get_x() * sw;
2512            sum_ry += r.get_y() * sw;
2513            sum_rz += r.get_z() * sw;
2514            sum_rw += r.get_w() * sw;
2515            sum_dx += d.get_x() * sw;
2516            sum_dy += d.get_y() * sw;
2517            sum_dz += d.get_z() * sw;
2518            sum_dw += d.get_w() * sw;
2519        }
2520        Self {
2521            real: Quat::from_xyzw(sum_rx, sum_ry, sum_rz, sum_rw),
2522            dual: Quat::from_xyzw(sum_dx, sum_dy, sum_dz, sum_dw),
2523        }
2524        .normalize()
2525    }
2526
2527    /// Transforms a 3D point by this unit dual quaternion.
2528    ///
2529    /// # Arguments
2530    ///
2531    /// - `Self` - Unit dual quaternion.
2532    /// - `Vec3` - Input 3D position.
2533    ///
2534    /// # Returns
2535    ///
2536    /// - `Vec3` - Transformed 3D position.
2537    #[must_use]
2538    pub fn transform_point(self, point: Vec3) -> Vec3 {
2539        self.get_real().rotate_vec3(point).add(self.translation())
2540    }
2541
2542    /// Transforms a 3D direction/normal vector by the rotational component of this dual quaternion.
2543    ///
2544    /// # Arguments
2545    ///
2546    /// - `Self` - Unit dual quaternion.
2547    /// - `Vec3` - Input 3D direction or normal.
2548    ///
2549    /// # Returns
2550    ///
2551    /// - `Vec3` - Rotated 3D vector.
2552    #[must_use]
2553    pub fn transform_vector(self, vector: Vec3) -> Vec3 {
2554        self.get_real().rotate_vec3(vector)
2555    }
2556}
2557
2558/// Extended quaternion TRS, orthographic projection, full 4x4 inversion, decomposition, and Blender basis conversions for `Mat4`.
2559impl Mat4 {
2560    /// Constructs a column-major `Mat4` directly from 16 elements.
2561    ///
2562    /// # Arguments
2563    ///
2564    /// - `[f32; 16]` - Column-major elements.
2565    ///
2566    /// # Returns
2567    ///
2568    /// - `Self` - Constructed 4x4 matrix.
2569    #[must_use]
2570    pub const fn from_cols_array(elements: [f32; 16]) -> Self {
2571        Self { elements }
2572    }
2573
2574    /// Returns the matrix transpose `M^T`.
2575    ///
2576    /// # Arguments
2577    ///
2578    /// - `&Self` - Source matrix.
2579    ///
2580    /// # Returns
2581    ///
2582    /// - `Self` - Transposed matrix.
2583    #[must_use]
2584    pub fn transpose(&self) -> Self {
2585        let e: [f32; 16] = self.get_elements();
2586        Self {
2587            elements: [
2588                e[0], e[4], e[8], e[12], e[1], e[5], e[9], e[13], e[2], e[6], e[10], e[14], e[3],
2589                e[7], e[11], e[15],
2590            ],
2591        }
2592    }
2593
2594    /// Builds a right-handed orthographic projection matrix matching OpenGL/glTF clip depth `[-1, 1]`.
2595    ///
2596    /// # Arguments
2597    ///
2598    /// - `f32` - Left frustum bound.
2599    /// - `f32` - Right frustum bound.
2600    /// - `f32` - Bottom frustum bound.
2601    /// - `f32` - Top frustum bound.
2602    /// - `f32` - Near clipping plane distance.
2603    /// - `f32` - Far clipping plane distance.
2604    ///
2605    /// # Returns
2606    ///
2607    /// - `Self` - Orthographic projection matrix.
2608    #[must_use]
2609    pub fn orthographic(left: f32, right: f32, bottom: f32, top: f32, near: f32, far: f32) -> Self {
2610        let rl: f32 = (right - left).max(1e-5);
2611        let tb: f32 = (top - bottom).max(1e-5);
2612        let fn_span: f32 = (far - near).max(1e-5);
2613        Self {
2614            elements: [
2615                2.0 / rl,
2616                0.0,
2617                0.0,
2618                0.0,
2619                0.0,
2620                2.0 / tb,
2621                0.0,
2622                0.0,
2623                0.0,
2624                0.0,
2625                -2.0 / fn_span,
2626                0.0,
2627                -(right + left) / rl,
2628                -(top + bottom) / tb,
2629                -(far + near) / fn_span,
2630                1.0,
2631            ],
2632        }
2633    }
2634
2635    /// Builds a symmetric glTF 2.0 orthographic projection matrix from half-extents `(xmag, ymag)` and `(near, far)`.
2636    ///
2637    /// # Arguments
2638    ///
2639    /// - `f32` - Horizontal magnification half-width.
2640    /// - `f32` - Vertical magnification half-height.
2641    /// - `f32` - Near clipping distance.
2642    /// - `f32` - Far clipping distance.
2643    ///
2644    /// # Returns
2645    ///
2646    /// - `Self` - Symmetric orthographic projection matrix.
2647    #[must_use]
2648    pub fn orthographic_mag(xmag: f32, ymag: f32, near: f32, far: f32) -> Self {
2649        let xm: f32 = xmag.abs().max(1e-4);
2650        let ym: f32 = ymag.abs().max(1e-4);
2651        Self::orthographic(-xm, xm, -ym, ym, near, far)
2652    }
2653
2654    /// Composes a column-major TRS model matrix `T * R(quat) * S`.
2655    ///
2656    /// # Arguments
2657    ///
2658    /// - `Vec3` - Translation vector.
2659    /// - `Quat` - Unit rotation quaternion.
2660    /// - `Vec3` - Non-uniform scale vector.
2661    ///
2662    /// # Returns
2663    ///
2664    /// - `Self` - Composed 4x4 transformation matrix.
2665    #[must_use]
2666    pub fn from_trs_quat(translation: Vec3, rotation: Quat, scale: Vec3) -> Self {
2667        let rot_elems: [f32; 16] = rotation.to_mat4().get_elements();
2668        let sx: f32 = scale.get_x();
2669        let sy: f32 = scale.get_y();
2670        let sz: f32 = scale.get_z();
2671        Self {
2672            elements: [
2673                rot_elems[0] * sx,
2674                rot_elems[1] * sx,
2675                rot_elems[2] * sx,
2676                0.0,
2677                rot_elems[4] * sy,
2678                rot_elems[5] * sy,
2679                rot_elems[6] * sy,
2680                0.0,
2681                rot_elems[8] * sz,
2682                rot_elems[9] * sz,
2683                rot_elems[10] * sz,
2684                0.0,
2685                translation.get_x(),
2686                translation.get_y(),
2687                translation.get_z(),
2688                1.0,
2689            ],
2690        }
2691    }
2692
2693    /// Decomposes an affine 4x4 transformation matrix into `(translation, rotation, scale)`.
2694    ///
2695    /// # Arguments
2696    ///
2697    /// - `&Self` - Affine 4x4 matrix reference.
2698    ///
2699    /// # Returns
2700    ///
2701    /// - `(Vec3, Quat, Vec3)` - Extracted translation, unit rotation quaternion, and signed scale.
2702    #[must_use]
2703    pub fn decompose_trs(&self) -> (Vec3, Quat, Vec3) {
2704        let e: [f32; 16] = self.get_elements();
2705        let translation: Vec3 = Vec3::new(e[12], e[13], e[14]);
2706        let col0: Vec3 = Vec3::new(e[0], e[1], e[2]);
2707        let col1: Vec3 = Vec3::new(e[4], e[5], e[6]);
2708        let col2: Vec3 = Vec3::new(e[8], e[9], e[10]);
2709        let mut sx: f32 = col0.length();
2710        let sy: f32 = col1.length();
2711        let sz: f32 = col2.length();
2712        let det3: f32 = col0.dot(col1.cross(col2));
2713        if det3 < 0.0 {
2714            sx = -sx;
2715        }
2716        let r0: Vec3 = if sx.abs() > 1e-6 {
2717            col0.scale(1.0 / sx)
2718        } else {
2719            Vec3::new(1.0, 0.0, 0.0)
2720        };
2721        let r1: Vec3 = if sy.abs() > 1e-6 {
2722            col1.scale(1.0 / sy)
2723        } else {
2724            Vec3::new(0.0, 1.0, 0.0)
2725        };
2726        let r2: Vec3 = if sz.abs() > 1e-6 {
2727            col2.scale(1.0 / sz)
2728        } else {
2729            Vec3::new(0.0, 0.0, 1.0)
2730        };
2731        let rotation: Quat = Quat::from_mat3(r0, r1, r2);
2732        (translation, rotation, Vec3::new(sx, sy, sz))
2733    }
2734
2735    /// Computes the exact general 4x4 matrix inverse via cofactor expansion, returning `None` if singular.
2736    ///
2737    /// # Arguments
2738    ///
2739    /// - `&Self` - Matrix to invert.
2740    ///
2741    /// # Returns
2742    ///
2743    /// - `Option<Self>` - Exact inverse matrix, or `None` when determinant is near zero.
2744    #[must_use]
2745    pub fn inverse(&self) -> Option<Self> {
2746        let m: [f32; 16] = self.get_elements();
2747        let s0: f32 = m[0] * m[5] - m[4] * m[1];
2748        let s1: f32 = m[0] * m[6] - m[4] * m[2];
2749        let s2: f32 = m[0] * m[7] - m[4] * m[3];
2750        let s3: f32 = m[1] * m[6] - m[5] * m[2];
2751        let s4: f32 = m[1] * m[7] - m[5] * m[3];
2752        let s5: f32 = m[2] * m[7] - m[6] * m[3];
2753        let c5: f32 = m[10] * m[15] - m[14] * m[11];
2754        let c4: f32 = m[9] * m[15] - m[13] * m[11];
2755        let c3: f32 = m[9] * m[14] - m[13] * m[10];
2756        let c2: f32 = m[8] * m[15] - m[12] * m[11];
2757        let c1: f32 = m[8] * m[14] - m[12] * m[10];
2758        let c0: f32 = m[8] * m[13] - m[12] * m[9];
2759        let det: f32 = s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0;
2760        if det.abs() < 1e-12 {
2761            return None;
2762        }
2763        let inv_det: f32 = 1.0 / det;
2764        Some(Self {
2765            elements: [
2766                (m[5] * c5 - m[6] * c4 + m[7] * c3) * inv_det,
2767                (-m[1] * c5 + m[2] * c4 - m[3] * c3) * inv_det,
2768                (m[13] * s5 - m[14] * s4 + m[15] * s3) * inv_det,
2769                (-m[9] * s5 + m[10] * s4 - m[11] * s3) * inv_det,
2770                (-m[4] * c5 + m[6] * c2 - m[7] * c1) * inv_det,
2771                (m[0] * c5 - m[2] * c2 + m[3] * c1) * inv_det,
2772                (-m[12] * s5 + m[14] * s2 - m[15] * s1) * inv_det,
2773                (m[8] * s5 - m[10] * s2 + m[11] * s1) * inv_det,
2774                (m[4] * c4 - m[5] * c2 + m[7] * c0) * inv_det,
2775                (-m[0] * c4 + m[1] * c2 - m[3] * c0) * inv_det,
2776                (m[12] * s4 - m[13] * s2 + m[15] * s0) * inv_det,
2777                (-m[8] * s4 + m[9] * s2 - m[11] * s0) * inv_det,
2778                (-m[4] * c3 + m[5] * c1 - m[6] * c0) * inv_det,
2779                (m[0] * c3 - m[1] * c1 + m[2] * c0) * inv_det,
2780                (-m[12] * s3 + m[13] * s1 - m[14] * s0) * inv_det,
2781                (m[8] * s3 - m[9] * s1 + m[10] * s0) * inv_det,
2782            ],
2783        })
2784    }
2785
2786    /// Computes the exact cofactor-transpose 3x3 normal matrix `[col0, col1, col2]` valid under non-uniform scale, shear, and reflections.
2787    ///
2788    /// # Arguments
2789    ///
2790    /// - `&Self` - Source model matrix.
2791    ///
2792    /// # Returns
2793    ///
2794    /// - `[Vec3; 3]` - Column vectors transforming local normals into world space.
2795    #[must_use]
2796    pub fn normal_matrix_3x3(&self) -> [Vec3; 3] {
2797        let e: [f32; 16] = self.get_elements();
2798        let c0: Vec3 = Vec3::new(e[0], e[1], e[2]);
2799        let c1: Vec3 = Vec3::new(e[4], e[5], e[6]);
2800        let c2: Vec3 = Vec3::new(e[8], e[9], e[10]);
2801        let n0: Vec3 = c1.cross(c2);
2802        let n1: Vec3 = c2.cross(c0);
2803        let n2: Vec3 = c0.cross(c1);
2804        let det: f32 = c0.dot(n0);
2805        if det.abs() > 1e-10 {
2806            let inv_det: f32 = 1.0 / det;
2807            [n0.scale(inv_det), n1.scale(inv_det), n2.scale(inv_det)]
2808        } else {
2809            [
2810                Vec3::new(1.0, 0.0, 0.0),
2811                Vec3::new(0.0, 1.0, 0.0),
2812                Vec3::new(0.0, 0.0, 1.0),
2813            ]
2814        }
2815    }
2816
2817    /// Returns the orthogonal change-of-basis matrix mapping Blender Z-up coordinates to Engine/glTF Y-up coordinates.
2818    ///
2819    /// # Returns
2820    ///
2821    /// - `Self` - Basis conversion matrix `(x, y, z) -> (x, z, -y)`.
2822    #[must_use]
2823    pub const fn blender_z_up_to_y_up() -> Self {
2824        Self {
2825            elements: [
2826                1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
2827            ],
2828        }
2829    }
2830
2831    /// Returns the inverse basis matrix mapping Engine/glTF Y-up coordinates back to Blender Z-up coordinates.
2832    ///
2833    /// # Returns
2834    ///
2835    /// - `Self` - Basis conversion matrix `(x, y, z) -> (x, -z, y)`.
2836    #[must_use]
2837    pub const fn y_up_to_blender_z_up() -> Self {
2838        Self {
2839            elements: [
2840                1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
2841            ],
2842        }
2843    }
2844}