euv_core/game/engine3d/math/impl.rs
1use super::*;
2
3/// Vector arithmetic, normalization, dot/cross products, and reflection helpers for `Vec3`.
4impl Vec3 {
5 /// Zero vector `(0, 0, 0)`.
6 ///
7 /// # Returns
8 ///
9 /// - `Self` - Zero vector.
10 #[must_use]
11 pub const fn zero() -> Self {
12 Self {
13 x: 0.0,
14 y: 0.0,
15 z: 0.0,
16 }
17 }
18
19 /// Uniform vector `(v, v, v)`.
20 ///
21 /// # Arguments
22 ///
23 /// - `f32` - Scalar value replicated across all axes.
24 ///
25 /// # Returns
26 ///
27 /// - `Self` - Splat vector.
28 #[must_use]
29 pub const fn splat(v: f32) -> Self {
30 Self { x: v, y: v, z: v }
31 }
32
33 /// Scales `self` by scalar `s`.
34 ///
35 /// # Arguments
36 ///
37 /// - `Self` - Source vector.
38 /// - `f32` - Scalar multiplier.
39 ///
40 /// # Returns
41 ///
42 /// - `Self` - Scaled vector.
43 #[inline(always)]
44 #[must_use]
45 pub fn scale(self, s: f32) -> Self {
46 Self {
47 x: self.get_x() * s,
48 y: self.get_y() * s,
49 z: self.get_z() * s,
50 }
51 }
52
53 /// Computes the dot product `self · rhs`.
54 ///
55 /// # Arguments
56 ///
57 /// - `Self` - Left vector.
58 /// - `Self` - Right vector.
59 ///
60 /// # Returns
61 ///
62 /// - `f32` - Scalar dot product.
63 #[inline(always)]
64 #[must_use]
65 pub fn dot(self, rhs: Self) -> f32 {
66 self.get_x().mul_add(
67 rhs.get_x(),
68 self.get_y()
69 .mul_add(rhs.get_y(), self.get_z() * rhs.get_z()),
70 )
71 }
72
73 /// Computes the 3D cross product `self × rhs`.
74 ///
75 /// # Arguments
76 ///
77 /// - `Self` - Left vector.
78 /// - `Self` - Right vector.
79 ///
80 /// # Returns
81 ///
82 /// - `Self` - Orthogonal cross product vector.
83 #[inline(always)]
84 #[must_use]
85 pub fn cross(self, rhs: Self) -> Self {
86 Self {
87 x: self.get_y() * rhs.get_z() - self.get_z() * rhs.get_y(),
88 y: self.get_z() * rhs.get_x() - self.get_x() * rhs.get_z(),
89 z: self.get_x() * rhs.get_y() - self.get_y() * rhs.get_x(),
90 }
91 }
92
93 /// Computes squared Euclidean length.
94 ///
95 /// # Arguments
96 ///
97 /// - `Self` - Source vector.
98 ///
99 /// # Returns
100 ///
101 /// - `f32` - Squared magnitude.
102 #[inline(always)]
103 #[must_use]
104 pub fn length_sq(self) -> f32 {
105 self.dot(self)
106 }
107
108 /// Computes Euclidean length.
109 ///
110 /// # Arguments
111 ///
112 /// - `Self` - Source vector.
113 ///
114 /// # Returns
115 ///
116 /// - `f32` - Magnitude.
117 #[inline(always)]
118 #[must_use]
119 pub fn length(self) -> f32 {
120 self.length_sq().sqrt()
121 }
122
123 /// Returns a unit-length vector pointing along `self`, or `(0, 1, 0)` if degenerate.
124 ///
125 /// # Arguments
126 ///
127 /// - `Self` - Source vector.
128 ///
129 /// # Returns
130 ///
131 /// - `Self` - Normalized unit vector.
132 #[inline(always)]
133 #[must_use]
134 pub fn normalize(self) -> Self {
135 let len: f32 = self.length();
136 if len > 1e-6 {
137 self.scale(1.0 / len)
138 } else {
139 Self::new(0.0, 1.0, 0.0)
140 }
141 }
142
143 /// Linearly interpolates between `self` and `other` by `t`.
144 ///
145 /// # Arguments
146 ///
147 /// - `Self` - Start vector.
148 /// - `Self` - End vector.
149 /// - `f32` - Interpolation factor.
150 ///
151 /// # Returns
152 ///
153 /// - `Self` - Interpolated vector.
154 #[inline(always)]
155 #[must_use]
156 pub fn lerp(self, other: Self, t: f32) -> Self {
157 Self {
158 x: (other.get_x() - self.get_x()).mul_add(t, self.get_x()),
159 y: (other.get_y() - self.get_y()).mul_add(t, self.get_y()),
160 z: (other.get_z() - self.get_z()).mul_add(t, self.get_z()),
161 }
162 }
163
164 /// Reflects incident vector `self` across unit surface normal `normal`.
165 ///
166 /// # Arguments
167 ///
168 /// - `Self` - Incident vector.
169 /// - `Self` - Unit surface normal.
170 ///
171 /// # Returns
172 ///
173 /// - `Self` - Reflected direction vector.
174 #[inline(always)]
175 #[must_use]
176 pub fn reflect(self, normal: Self) -> Self {
177 self.sub(normal.scale(2.0 * self.dot(normal)))
178 }
179
180 /// Returns component-wise minimum of `self` and `rhs`.
181 ///
182 /// # Arguments
183 ///
184 /// - `Self` - Left vector.
185 /// - `Self` - Right vector.
186 ///
187 /// # Returns
188 ///
189 /// - `Self` - Component-wise minimum.
190 #[must_use]
191 pub fn min(self, rhs: Self) -> Self {
192 Self {
193 x: self.get_x().min(rhs.get_x()),
194 y: self.get_y().min(rhs.get_y()),
195 z: self.get_z().min(rhs.get_z()),
196 }
197 }
198
199 /// Returns component-wise maximum of `self` and `rhs`.
200 ///
201 /// # Arguments
202 ///
203 /// - `Self` - Left vector.
204 /// - `Self` - Right vector.
205 ///
206 /// # Returns
207 ///
208 /// - `Self` - Component-wise maximum.
209 #[must_use]
210 pub fn max(self, rhs: Self) -> Self {
211 Self {
212 x: self.get_x().max(rhs.get_x()),
213 y: self.get_y().max(rhs.get_y()),
214 z: self.get_z().max(rhs.get_z()),
215 }
216 }
217
218 /// Converts an sRGB `Color` into linear RGB `Vec3` radiance in `[0.0, 1.0]`.
219 ///
220 /// # Arguments
221 ///
222 /// - `Color` - Source RGBA color.
223 ///
224 /// # Returns
225 ///
226 /// - `Self` - Normalized linear RGB vector.
227 #[must_use]
228 pub fn from_color(c: Color) -> Self {
229 Self {
230 x: (c.get_r() as f32) / 255.0,
231 y: (c.get_g() as f32) / 255.0,
232 z: (c.get_b() as f32) / 255.0,
233 }
234 }
235
236 /// Maps a single HDR channel through the ACES filmic tone curve into sRGB byte space.
237 ///
238 /// # Arguments
239 ///
240 /// - `f32` - Linear HDR scalar.
241 ///
242 /// # Returns
243 ///
244 /// - `u8` - Gamma-encoded sRGB byte.
245 #[inline(always)]
246 #[must_use]
247 fn aces_channel(v: f32) -> u8 {
248 let x: f32 = v.max(0.0);
249 let num: f32 = x * x.mul_add(2.51, 0.03);
250 let den: f32 = x.mul_add(x.mul_add(2.43, 0.59), 0.14);
251 let mapped: f32 = num / den;
252 let idx: usize = mapped.clamp(0.0, 1.0).mul_add(1024.0, 0.5) as usize;
253 LINEAR_TO_SRGB_LUT[idx.min(1024)]
254 }
255
256 /// Applies ACES filmic tone mapping and converts linear radiance to RGBA8 `[r, g, b, 255]`.
257 ///
258 /// # Arguments
259 ///
260 /// - `Self` - Linear HDR RGB radiance.
261 ///
262 /// # Returns
263 ///
264 /// - `[u8; 4]` - Tone-mapped RGBA8 pixel bytes.
265 #[inline(always)]
266 #[must_use]
267 pub fn to_aces_rgba8(self) -> [u8; 4] {
268 [
269 Self::aces_channel(self.get_x()),
270 Self::aces_channel(self.get_y()),
271 Self::aces_channel(self.get_z()),
272 255,
273 ]
274 }
275}
276
277/// Component-wise vector addition for `Vec3`.
278impl Add for Vec3 {
279 type Output = Self;
280
281 /// Adds two vectors component-wise.
282 ///
283 /// # Arguments
284 ///
285 /// - `Self` - Left vector.
286 /// - `Self` - Right vector.
287 ///
288 /// # Returns
289 ///
290 /// - `Self` - Component-wise sum.
291 #[inline(always)]
292 fn add(self, rhs: Self) -> Self {
293 Self {
294 x: self.get_x() + rhs.get_x(),
295 y: self.get_y() + rhs.get_y(),
296 z: self.get_z() + rhs.get_z(),
297 }
298 }
299}
300
301/// Component-wise vector subtraction for `Vec3`.
302impl Sub for Vec3 {
303 type Output = Self;
304
305 /// Subtracts `rhs` from `self`.
306 ///
307 /// # Arguments
308 ///
309 /// - `Self` - Left vector.
310 /// - `Self` - Right vector.
311 ///
312 /// # Returns
313 ///
314 /// - `Self` - Component-wise difference.
315 #[inline(always)]
316 fn sub(self, rhs: Self) -> Self {
317 Self {
318 x: self.get_x() - rhs.get_x(),
319 y: self.get_y() - rhs.get_y(),
320 z: self.get_z() - rhs.get_z(),
321 }
322 }
323}
324
325/// Component-wise Hadamard vector multiplication for `Vec3`.
326impl Mul for Vec3 {
327 type Output = Self;
328
329 /// Multiplies two vectors component-wise.
330 ///
331 /// # Arguments
332 ///
333 /// - `Self` - Left vector.
334 /// - `Self` - Right vector.
335 ///
336 /// # Returns
337 ///
338 /// - `Self` - Component-wise product.
339 #[inline(always)]
340 fn mul(self, rhs: Self) -> Self {
341 Self {
342 x: self.get_x() * rhs.get_x(),
343 y: self.get_y() * rhs.get_y(),
344 z: self.get_z() * rhs.get_z(),
345 }
346 }
347}
348
349/// Matrix multiplication `self * rhs` for `Mat4`.
350impl Mul for Mat4 {
351 type Output = Self;
352
353 /// Multiplies `self * rhs`.
354 ///
355 /// # Arguments
356 ///
357 /// - `Self` - Left matrix.
358 /// - `Self` - Right matrix.
359 ///
360 /// # Returns
361 ///
362 /// - `Self` - Product matrix.
363 fn mul(self, rhs: Self) -> Self {
364 let a: [f32; 16] = self.get_m();
365 let b: [f32; 16] = rhs.get_m();
366 let mut out: [f32; 16] = [0.0; 16];
367 for col in 0..4 {
368 for row in 0..4 {
369 out[col * 4 + row] = a[row] * b[col * 4]
370 + a[4 + row] * b[col * 4 + 1]
371 + a[8 + row] * b[col * 4 + 2]
372 + a[12 + row] * b[col * 4 + 3];
373 }
374 }
375 Self { m: out }
376 }
377}
378
379/// Matrix constructors, projection, and point projection for `Mat4`.
380impl Mat4 {
381 /// Identity 4x4 matrix.
382 ///
383 /// # Returns
384 ///
385 /// - `Self` - Identity matrix.
386 #[must_use]
387 pub const fn identity() -> Self {
388 Self {
389 m: [
390 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,
391 ],
392 }
393 }
394
395 /// Builds a right-handed perspective projection matrix.
396 ///
397 /// # Arguments
398 ///
399 /// - `f32` - Vertical FOV in radians.
400 /// - `f32` - Viewport aspect ratio `width / height`.
401 /// - `f32` - Near plane distance.
402 /// - `f32` - Far plane distance.
403 ///
404 /// # Returns
405 ///
406 /// - `Self` - Perspective projection matrix.
407 #[must_use]
408 pub fn perspective(fov_rad: f32, aspect: f32, near: f32, far: f32) -> Self {
409 let f: f32 = 1.0 / (fov_rad * 0.5).tan().max(1e-4);
410 let nf: f32 = 1.0 / (near - far);
411 Self {
412 m: [
413 f / aspect.max(0.01),
414 0.0,
415 0.0,
416 0.0,
417 0.0,
418 f,
419 0.0,
420 0.0,
421 0.0,
422 0.0,
423 (far + near) * nf,
424 -1.0,
425 0.0,
426 0.0,
427 2.0 * far * near * nf,
428 0.0,
429 ],
430 }
431 }
432
433 /// Builds a right-handed look-at view matrix.
434 ///
435 /// # Arguments
436 ///
437 /// - `Vec3` - Camera eye position.
438 /// - `Vec3` - Target look-at position.
439 /// - `Vec3` - World up direction.
440 ///
441 /// # Returns
442 ///
443 /// - `Self` - View transformation matrix.
444 #[must_use]
445 pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self {
446 let f: Vec3 = target.sub(eye).normalize();
447 let s: Vec3 = f.cross(up).normalize();
448 let u: Vec3 = s.cross(f);
449 Self {
450 m: [
451 s.get_x(),
452 u.get_x(),
453 -f.get_x(),
454 0.0,
455 s.get_y(),
456 u.get_y(),
457 -f.get_y(),
458 0.0,
459 s.get_z(),
460 u.get_z(),
461 -f.get_z(),
462 0.0,
463 -s.dot(eye),
464 -u.dot(eye),
465 f.dot(eye),
466 1.0,
467 ],
468 }
469 }
470
471 /// Builds a TRS model matrix (`translate * rotate_y * scale`).
472 ///
473 /// # Arguments
474 ///
475 /// - `Vec3` - World translation.
476 /// - `f32` - Y-axis yaw rotation in radians.
477 /// - `Vec3` - Non-uniform scale.
478 ///
479 /// # Returns
480 ///
481 /// - `Self` - Composed model transform matrix.
482 #[must_use]
483 pub fn from_trs(position: Vec3, yaw_rad: f32, scale: Vec3) -> Self {
484 let c: f32 = yaw_rad.cos();
485 let s: f32 = yaw_rad.sin();
486 Self {
487 m: [
488 c * scale.get_x(),
489 0.0,
490 -s * scale.get_x(),
491 0.0,
492 0.0,
493 scale.get_y(),
494 0.0,
495 0.0,
496 s * scale.get_z(),
497 0.0,
498 c * scale.get_z(),
499 0.0,
500 position.get_x(),
501 position.get_y(),
502 position.get_z(),
503 1.0,
504 ],
505 }
506 }
507
508 /// Builds a full 3D Euler TRS model matrix (`translate * rotate_y(yaw) * rotate_x(pitch) * rotate_z(roll) * scale`).
509 ///
510 /// # Arguments
511 ///
512 /// - `Vec3` - World translation.
513 /// - `f32` - Y-axis yaw rotation in radians.
514 /// - `f32` - X-axis pitch rotation in radians.
515 /// - `f32` - Z-axis roll rotation in radians.
516 /// - `Vec3` - Non-uniform scale.
517 ///
518 /// # Returns
519 ///
520 /// - `Self` - Composed 3D model transform matrix.
521 #[must_use]
522 pub fn from_trs_euler(
523 position: Vec3,
524 yaw_rad: f32,
525 pitch_rad: f32,
526 roll_rad: f32,
527 scale: Vec3,
528 ) -> Self {
529 if pitch_rad.abs() < 1e-6 && roll_rad.abs() < 1e-6 {
530 return Self::from_trs(position, yaw_rad, scale);
531 }
532 let (cy, sy): (f32, f32) = (yaw_rad.cos(), yaw_rad.sin());
533 let (cp, sp): (f32, f32) = (pitch_rad.cos(), pitch_rad.sin());
534 let (cr, sr): (f32, f32) = (roll_rad.cos(), roll_rad.sin());
535 let r00: f32 = cy * cr + sy * sp * sr;
536 let r10: f32 = cp * sr;
537 let r20: f32 = -sy * cr + cy * sp * sr;
538 let r01: f32 = -cy * sr + sy * sp * cr;
539 let r11: f32 = cp * cr;
540 let r21: f32 = sy * sr + cy * sp * cr;
541 let r02: f32 = sy * cp;
542 let r12: f32 = -sp;
543 let r22: f32 = cy * cp;
544 let sx: f32 = scale.get_x();
545 let sy_sc: f32 = scale.get_y();
546 let sz: f32 = scale.get_z();
547 Self {
548 m: [
549 r00 * sx,
550 r10 * sx,
551 r20 * sx,
552 0.0,
553 r01 * sy_sc,
554 r11 * sy_sc,
555 r21 * sy_sc,
556 0.0,
557 r02 * sz,
558 r12 * sz,
559 r22 * sz,
560 0.0,
561 position.get_x(),
562 position.get_y(),
563 position.get_z(),
564 1.0,
565 ],
566 }
567 }
568
569 /// Transforms a 3D point returning homogeneous clip coordinates `(x, y, z, w)`.
570 ///
571 /// # Arguments
572 ///
573 /// - `&Self` - Transformation matrix.
574 /// - `Vec3` - Input 3D position.
575 ///
576 /// # Returns
577 ///
578 /// - `[f32; 4]` - Homogeneous clip-space coordinates.
579 #[must_use]
580 pub fn mul_point4(&self, p: Vec3) -> [f32; 4] {
581 let m: [f32; 16] = self.get_m();
582 [
583 m[0] * p.get_x() + m[4] * p.get_y() + m[8] * p.get_z() + m[12],
584 m[1] * p.get_x() + m[5] * p.get_y() + m[9] * p.get_z() + m[13],
585 m[2] * p.get_x() + m[6] * p.get_y() + m[10] * p.get_z() + m[14],
586 m[3] * p.get_x() + m[7] * p.get_y() + m[11] * p.get_z() + m[15],
587 ]
588 }
589}
590
591/// Bounding-box union, centroid, surface area, and ray-slab intersection for `Aabb3D`.
592impl Aabb3D {
593 /// Creates an inverted empty AABB ready to accumulate points via `expand_point`.
594 ///
595 /// # Returns
596 ///
597 /// - `Self` - Empty AABB.
598 #[must_use]
599 pub const fn empty() -> Self {
600 Self {
601 min: Vec3::splat(f32::INFINITY),
602 max: Vec3::splat(f32::NEG_INFINITY),
603 }
604 }
605
606 /// Expands this bounding box to include `point`.
607 ///
608 /// # Arguments
609 ///
610 /// - `&Self` - Mutable AABB.
611 /// - `Vec3` - Point to enclose.
612 pub fn expand_point(&mut self, point: Vec3) {
613 let mn: Vec3 = self.get_min().min(point);
614 let mx: Vec3 = self.get_max().max(point);
615 self.set_min(mn);
616 self.set_max(mx);
617 }
618
619 /// Expands this bounding box to include `other`.
620 ///
621 /// # Arguments
622 ///
623 /// - `&Self` - Mutable AABB.
624 /// - `Self` - Other bounding box.
625 pub fn expand_box(&mut self, other: Self) {
626 let mn: Vec3 = self.get_min().min(other.get_min());
627 let mx: Vec3 = self.get_max().max(other.get_max());
628 self.set_min(mn);
629 self.set_max(mx);
630 }
631
632 /// Returns the geometric center of the AABB.
633 ///
634 /// # Arguments
635 ///
636 /// - `&Self` - AABB reference.
637 ///
638 /// # Returns
639 ///
640 /// - `Vec3` - Box centroid.
641 #[must_use]
642 pub fn center(&self) -> Vec3 {
643 self.get_min().add(self.get_max()).scale(0.5)
644 }
645
646 /// Computes bounding-sphere radius enclosing this box.
647 ///
648 /// # Arguments
649 ///
650 /// - `&Self` - AABB reference.
651 ///
652 /// # Returns
653 ///
654 /// - `f32` - Enclosing radius.
655 #[must_use]
656 pub fn radius(&self) -> f32 {
657 self.get_max().sub(self.get_min()).length() * 0.5
658 }
659
660 /// Computes half surface area (`dx*dy + dy*dz + dz*dx`) for Surface Area Heuristic (SAH) BVH splits.
661 ///
662 /// # Arguments
663 ///
664 /// - `&Self` - AABB reference.
665 ///
666 /// # Returns
667 ///
668 /// - `f32` - Non-negative half surface area.
669 #[must_use]
670 pub fn surface_area(&self) -> f32 {
671 let d: Vec3 = self.get_max().sub(self.get_min());
672 let dx: f32 = d.get_x().max(0.0);
673 let dy: f32 = d.get_y().max(0.0);
674 let dz: f32 = d.get_z().max(0.0);
675 dx * dy + dy * dz + dz * dx
676 }
677
678 /// Branchless slab Ray-AABB intersection returning entry distance `tmin` or `f32::INFINITY` on miss.
679 ///
680 /// # Arguments
681 ///
682 /// - `&Self` - AABB reference.
683 /// - `Vec3` - Ray origin.
684 /// - `Vec3` - Precomputed safe reciprocal ray direction.
685 /// - `f32` - Minimum valid distance.
686 /// - `f32` - Maximum valid distance.
687 ///
688 /// # Returns
689 ///
690 /// - `f32` - Near intersection distance if hit, or `f32::INFINITY` if missed.
691 #[must_use]
692 pub fn intersect_ray_near(&self, origin: Vec3, inv_dir: Vec3, t_min: f32, t_max: f32) -> f32 {
693 let mn: Vec3 = self.get_min();
694 let mx: Vec3 = self.get_max();
695 let tx1: f32 = (mn.get_x() - origin.get_x()) * inv_dir.get_x();
696 let tx2: f32 = (mx.get_x() - origin.get_x()) * inv_dir.get_x();
697 let mut tmin: f32 = t_min.max(tx1.min(tx2));
698 let mut tmax: f32 = t_max.min(tx1.max(tx2));
699 let ty1: f32 = (mn.get_y() - origin.get_y()) * inv_dir.get_y();
700 let ty2: f32 = (mx.get_y() - origin.get_y()) * inv_dir.get_y();
701 tmin = tmin.max(ty1.min(ty2));
702 tmax = tmax.min(ty1.max(ty2));
703 let tz1: f32 = (mn.get_z() - origin.get_z()) * inv_dir.get_z();
704 let tz2: f32 = (mx.get_z() - origin.get_z()) * inv_dir.get_z();
705 tmin = tmin.max(tz1.min(tz2));
706 tmax = tmax.min(tz1.max(tz2));
707 if tmax >= tmin && tmax >= 0.0 {
708 tmin
709 } else {
710 f32::INFINITY
711 }
712 }
713
714 /// Branchless slab Ray-AABB intersection returning `true` when `ray` hits within `[t_min, t_max]`.
715 ///
716 /// # Arguments
717 ///
718 /// - `&Self` - AABB reference.
719 /// - `&Ray3D` - Ray with precomputed inverse direction.
720 /// - `f32` - Minimum valid distance.
721 /// - `f32` - Maximum valid distance.
722 ///
723 /// # Returns
724 ///
725 /// - `bool` - Whether the ray intersects this box.
726 #[must_use]
727 pub fn intersects_ray(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
728 self.intersect_ray_near(ray.get_origin(), ray.get_inv_direction(), t_min, t_max)
729 .is_finite()
730 }
731}
732
733/// Ray construction with safe reciprocal components for `Ray3D`.
734impl Ray3D {
735 /// Safe reciprocal scalar preventing division by zero in slab ray-box tests.
736 ///
737 /// # Arguments
738 ///
739 /// - `f32` - Component scalar.
740 ///
741 /// # Returns
742 ///
743 /// - `f32` - Clamped reciprocal value.
744 #[must_use]
745 fn safe_inv(v: f32) -> f32 {
746 if v.abs() < 1e-7 {
747 if v < 0.0 { -1e7 } else { 1e7 }
748 } else {
749 1.0 / v
750 }
751 }
752
753 /// Computes safe reciprocal vector for an already-normalized ray direction.
754 ///
755 /// # Arguments
756 ///
757 /// - `Vec3` - Unit ray direction.
758 ///
759 /// # Returns
760 ///
761 /// - `Vec3` - Reciprocal direction safe for slab ray-AABB intersection.
762 #[must_use]
763 pub fn safe_inv_vec(dir: Vec3) -> Vec3 {
764 Vec3::new(
765 Self::safe_inv(dir.get_x()),
766 Self::safe_inv(dir.get_y()),
767 Self::safe_inv(dir.get_z()),
768 )
769 }
770
771 /// Constructs a normalized `Ray3D` with safe reciprocal direction components.
772 ///
773 /// # Arguments
774 ///
775 /// - `Vec3` - Ray origin.
776 /// - `Vec3` - Ray direction (normalized internally).
777 ///
778 /// # Returns
779 ///
780 /// - `Self` - Ready BVH ray.
781 #[must_use]
782 pub fn new(origin: Vec3, direction: Vec3) -> Self {
783 let dir: Vec3 = direction.normalize();
784 Self {
785 origin,
786 direction: dir,
787 inv_direction: Vec3::new(
788 Self::safe_inv(dir.get_x()),
789 Self::safe_inv(dir.get_y()),
790 Self::safe_inv(dir.get_z()),
791 ),
792 }
793 }
794}
795
796/// Gribb-Hartmann 6-plane frustum extraction and AABB visibility testing for `Frustum3D`.
797impl Frustum3D {
798 /// Normalizes a 4-component plane equation `(a, b, c, d)`.
799 ///
800 /// # Arguments
801 ///
802 /// - `[f32; 4]` - Raw plane coefficients.
803 ///
804 /// # Returns
805 ///
806 /// - `[f32; 4]` - Unit-normal plane coefficients.
807 #[must_use]
808 fn normalize_plane(p: [f32; 4]) -> [f32; 4] {
809 let len: f32 = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt().max(1e-6);
810 [p[0] / len, p[1] / len, p[2] / len, p[3] / len]
811 }
812
813 /// Extracts the 6 normalized view-frustum planes from a column-major view-projection matrix.
814 ///
815 /// # Arguments
816 ///
817 /// - `&Mat4` - Combined `projection * view` matrix.
818 ///
819 /// # Returns
820 ///
821 /// - `Self` - Normalized 6-plane frustum.
822 #[must_use]
823 pub fn from_view_proj(vp: &Mat4) -> Self {
824 let m: [f32; 16] = vp.get_m();
825 let r0: [f32; 4] = [m[0], m[4], m[8], m[12]];
826 let r1: [f32; 4] = [m[1], m[5], m[9], m[13]];
827 let r2: [f32; 4] = [m[2], m[6], m[10], m[14]];
828 let r3: [f32; 4] = [m[3], m[7], m[11], m[15]];
829 Self {
830 planes: [
831 Self::normalize_plane([r3[0] + r0[0], r3[1] + r0[1], r3[2] + r0[2], r3[3] + r0[3]]),
832 Self::normalize_plane([r3[0] - r0[0], r3[1] - r0[1], r3[2] - r0[2], r3[3] - r0[3]]),
833 Self::normalize_plane([r3[0] + r1[0], r3[1] + r1[1], r3[2] + r1[2], r3[3] + r1[3]]),
834 Self::normalize_plane([r3[0] - r1[0], r3[1] - r1[1], r3[2] - r1[2], r3[3] - r1[3]]),
835 Self::normalize_plane([r3[0] + r2[0], r3[1] + r2[1], r3[2] + r2[2], r3[3] + r2[3]]),
836 Self::normalize_plane([r3[0] - r2[0], r3[1] - r2[1], r3[2] - r2[2], r3[3] - r2[3]]),
837 ],
838 }
839 }
840
841 /// Returns `true` when `aabb` is at least partially inside the view frustum.
842 ///
843 /// # Arguments
844 ///
845 /// - `&Self` - Frustum reference.
846 /// - `&Aabb3D` - World-space AABB to test.
847 ///
848 /// # Returns
849 ///
850 /// - `bool` - `true` if potentially visible, `false` if completely culled.
851 #[must_use]
852 pub fn intersects_aabb(&self, aabb: &Aabb3D) -> bool {
853 let mn: Vec3 = aabb.get_min();
854 let mx: Vec3 = aabb.get_max();
855 for p in self.get_planes().iter() {
856 let px: f32 = if p[0] >= 0.0 { mx.get_x() } else { mn.get_x() };
857 let py: f32 = if p[1] >= 0.0 { mx.get_y() } else { mn.get_y() };
858 let pz: f32 = if p[2] >= 0.0 { mx.get_z() } else { mn.get_z() };
859 if p[0] * px + p[1] * py + p[2] * pz + p[3] < 0.0 {
860 return false;
861 }
862 }
863 true
864 }
865}
866
867/// Default 3D camera framing an open-world street boulevard.
868impl Default for Camera3D {
869 /// Creates a default street-level perspective camera.
870 ///
871 /// # Returns
872 ///
873 /// - `Self` - Default `Camera3D`.
874 fn default() -> Self {
875 Self {
876 position: Vec3::new(0.0, 9.5, 28.0),
877 yaw: -FRAC_PI_2,
878 pitch: -0.22,
879 fov_deg: 60.0,
880 near: 0.3,
881 far: 450.0,
882 }
883 }
884}
885
886/// Orientation, movement, and view-projection helpers for `Camera3D`.
887impl Camera3D {
888 /// Returns the unit forward look vector derived from `(yaw, pitch)`.
889 ///
890 /// # Arguments
891 ///
892 /// - `&Self` - Camera reference.
893 ///
894 /// # Returns
895 ///
896 /// - `Vec3` - Forward unit vector.
897 #[must_use]
898 pub fn forward(&self) -> Vec3 {
899 let yaw: f32 = self.get_yaw();
900 let pitch: f32 = self.get_pitch();
901 let cp: f32 = pitch.cos();
902 Vec3::new(yaw.cos() * cp, pitch.sin(), yaw.sin() * cp).normalize()
903 }
904
905 /// Returns the unit right vector orthogonal to `forward()` and world up.
906 ///
907 /// # Arguments
908 ///
909 /// - `&Self` - Camera reference.
910 ///
911 /// # Returns
912 ///
913 /// - `Vec3` - Right unit vector.
914 #[must_use]
915 pub fn right(&self) -> Vec3 {
916 self.forward().cross(Vec3::new(0.0, 1.0, 0.0)).normalize()
917 }
918
919 /// Converts a physical camera focal length and full-frame sensor height in millimeters to vertical FOV degrees.
920 ///
921 /// # Arguments
922 ///
923 /// - `f32` - Lens focal length in millimeters (e.g., `24.0`, `35.0`, `50.0`, `85.0`).
924 /// - `f32` - Camera sensor height in millimeters (`24.0` for 35mm full-frame).
925 ///
926 /// # Returns
927 ///
928 /// - `f32` - Vertical field of view in degrees clamped to `[12.0, 120.0]`.
929 #[must_use]
930 pub fn focal_length_to_fov_deg(focal_length_mm: f32, sensor_height_mm: f32) -> f32 {
931 let f_mm: f32 = focal_length_mm.max(8.0);
932 let s_mm: f32 = sensor_height_mm.max(4.0);
933 (2.0 * (s_mm / (2.0 * f_mm)).atan().to_degrees()).clamp(12.0, 120.0)
934 }
935
936 /// Constructs a physically based 35mm full-frame `Camera3D` using lens focal length in millimeters.
937 ///
938 /// # Arguments
939 ///
940 /// - `Vec3` - World-space eye position.
941 /// - `f32` - Horizontal yaw angle in radians.
942 /// - `f32` - Vertical pitch angle in radians.
943 /// - `f32` - Lens focal length in millimeters.
944 ///
945 /// # Returns
946 ///
947 /// - `Self` - Physically configured perspective camera.
948 #[must_use]
949 pub fn from_lens(position: Vec3, yaw: f32, pitch: f32, focal_length_mm: f32) -> Self {
950 Self {
951 position,
952 yaw,
953 pitch: pitch.clamp(-1.4, 1.4),
954 fov_deg: Self::focal_length_to_fov_deg(focal_length_mm, 24.0),
955 near: 0.25,
956 far: 480.0,
957 }
958 }
959
960 /// Computes physical exposure value `EV100` from lens aperture (f-stop), shutter speed (seconds), and ISO.
961 ///
962 /// # Arguments
963 ///
964 /// - `f32` - Aperture f-number (e.g., `2.8`, `4.0`, `8.0`).
965 /// - `f32` - Shutter exposure time in seconds (e.g., `1.0 / 125.0`).
966 /// - `f32` - Sensor ISO sensitivity (e.g., `100.0`).
967 ///
968 /// # Returns
969 ///
970 /// - `f32` - Physical exposure value `EV100`.
971 #[must_use]
972 pub fn ev100(aperture_fstop: f32, shutter_seconds: f32, iso: f32) -> f32 {
973 let n: f32 = aperture_fstop.max(0.7);
974 let t: f32 = shutter_seconds.max(1e-5);
975 let s: f32 = iso.max(25.0);
976 ((n * n) / t * (100.0 / s)).log2()
977 }
978
979 /// Converts an `EV100` exposure value into a linear HDR scene exposure multiplier.
980 ///
981 /// # Arguments
982 ///
983 /// - `f32` - Physical exposure value `EV100`.
984 ///
985 /// # Returns
986 ///
987 /// - `f32` - Linear exposure multiplier clamped to `[0.05, 8.0]`.
988 #[must_use]
989 pub fn exposure_scale_from_ev100(ev100: f32) -> f32 {
990 let max_lum: f32 = 1.2 * 2.0_f32.powf(ev100);
991 (1.0 / max_lum.max(1e-4)).clamp(0.05, 8.0)
992 }
993
994 /// Orients this camera's yaw and pitch to aim directly at `target`.
995 ///
996 /// # Arguments
997 ///
998 /// - `&Self` - Mutable camera reference.
999 /// - `Vec3` - World-space look target.
1000 pub fn look_at(&mut self, target: Vec3) {
1001 let dir: Vec3 = target.sub(self.get_position()).normalize();
1002 self.set_yaw(dir.get_z().atan2(dir.get_x()));
1003 self.set_pitch(dir.get_y().clamp(-0.98, 0.98).asin());
1004 }
1005
1006 /// Linearly interpolates camera position, shortest-arc yaw, pitch, and lens parameters between `self` and `other`.
1007 ///
1008 /// # Arguments
1009 ///
1010 /// - `Self` - Previous fixed-step 3D camera state.
1011 /// - `Self` - Current fixed-step 3D camera state.
1012 /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
1013 ///
1014 /// # Returns
1015 ///
1016 /// - `Self` - Interpolated 3D camera.
1017 #[must_use]
1018 pub fn lerp(self, other: Self, alpha: f32) -> Self {
1019 let k: f32 = alpha.clamp(0.0, 1.0);
1020 let raw_yaw_delta: f32 = (other.get_yaw() - self.get_yaw()).rem_euclid(TAU);
1021 let shortest_yaw: f32 = if raw_yaw_delta > PI {
1022 raw_yaw_delta - TAU
1023 } else {
1024 raw_yaw_delta
1025 };
1026 Self {
1027 position: self.get_position().lerp(other.get_position(), k),
1028 yaw: self.get_yaw() + shortest_yaw * k,
1029 pitch: (self.get_pitch() + (other.get_pitch() - self.get_pitch()) * k).clamp(-1.4, 1.4),
1030 fov_deg: self.get_fov_deg() + (other.get_fov_deg() - self.get_fov_deg()) * k,
1031 near: self.get_near() + (other.get_near() - self.get_near()) * k,
1032 far: self.get_far() + (other.get_far() - self.get_far()) * k,
1033 }
1034 }
1035
1036 /// Computes the combined `projection * view` matrix for viewport `aspect`.
1037 ///
1038 /// # Arguments
1039 ///
1040 /// - `&Self` - Camera reference.
1041 /// - `f32` - Viewport aspect ratio `width / height`.
1042 ///
1043 /// # Returns
1044 ///
1045 /// - `Mat4` - View-projection matrix.
1046 #[must_use]
1047 pub fn view_projection(&self, aspect: f32) -> Mat4 {
1048 let pos: Vec3 = self.get_position();
1049 let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), Vec3::new(0.0, 1.0, 0.0));
1050 let proj: Mat4 = Mat4::perspective(
1051 self.get_fov_deg().to_radians(),
1052 aspect.max(0.1),
1053 self.get_near().max(0.05),
1054 self.get_far().max(10.0),
1055 );
1056 proj.mul(view)
1057 }
1058}