Skip to main content

euv_core/game/engine3d/world/
impl.rs

1use super::*;
2
3/// Default identity `Transform3D`.
4impl Default for Transform3D {
5    /// Returns identity transform at origin with unit quaternion rotation and unit scale.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Identity `Transform3D`.
10    fn default() -> Self {
11        Self {
12            position: Vec3::zero(),
13            rotation: Quat::identity(),
14            scale: Vec3::splat(1.0),
15        }
16    }
17}
18
19/// Quaternion-backed matrix, Euler compatibility, SLERP interpolation, and point transformation helpers for `Transform3D`.
20impl Transform3D {
21    /// Constructs a `Transform3D` from position, Y-axis yaw in radians, and non-uniform scale.
22    ///
23    /// # Arguments
24    ///
25    /// - `Vec3` - World-space translation.
26    /// - `f32` - Horizontal Y-axis yaw rotation in radians.
27    /// - `Vec3` - Non-uniform scale.
28    ///
29    /// # Returns
30    ///
31    /// - `Self` - Constructed quaternion-backed 3D transform.
32    #[must_use]
33    pub fn new(position: Vec3, yaw_rad: f32, scale: Vec3) -> Self {
34        Self {
35            position,
36            rotation: Quat::from_axis_angle(Vec3::new(0.0, 1.0, 0.0), yaw_rad),
37            scale,
38        }
39    }
40
41    /// Constructs a `Transform3D` directly from translation, unit quaternion rotation, and scale.
42    ///
43    /// # Arguments
44    ///
45    /// - `Vec3` - World-space translation.
46    /// - `Quat` - Orientation quaternion.
47    /// - `Vec3` - Non-uniform scale.
48    ///
49    /// # Returns
50    ///
51    /// - `Self` - Constructed 3D transform.
52    #[must_use]
53    pub fn from_trs(position: Vec3, rotation: Quat, scale: Vec3) -> Self {
54        Self {
55            position,
56            rotation: rotation.normalize(),
57            scale,
58        }
59    }
60
61    /// Decomposes an affine 4x4 matrix into a quaternion-backed `Transform3D`.
62    ///
63    /// # Arguments
64    ///
65    /// - `Mat4` - Column-major affine transformation matrix.
66    ///
67    /// # Returns
68    ///
69    /// - `Self` - Decomposed 3D transform.
70    #[must_use]
71    pub fn from_matrix(matrix: Mat4) -> Self {
72        let (position, rotation, scale): (Vec3, Quat, Vec3) = matrix.decompose_trs();
73        Self {
74            position,
75            rotation: rotation.normalize(),
76            scale,
77        }
78    }
79
80    /// Returns a copy of this transform rotated by `rotation`.
81    ///
82    /// # Arguments
83    ///
84    /// - `Self` - Source transform.
85    /// - `Quat` - Orientation quaternion.
86    ///
87    /// # Returns
88    ///
89    /// - `Self` - Updated transform.
90    #[must_use]
91    pub fn with_rotation(mut self, rotation: Quat) -> Self {
92        self.set_rotation(rotation.normalize());
93        self
94    }
95
96    /// Returns a copy of this transform with full yaw, pitch, and roll Euler rotation in radians (`Ry * Rx * Rz`).
97    ///
98    /// # Arguments
99    ///
100    /// - `Self` - Source transform.
101    /// - `f32` - Y-axis yaw in radians.
102    /// - `f32` - X-axis pitch in radians.
103    /// - `f32` - Z-axis roll in radians.
104    ///
105    /// # Returns
106    ///
107    /// - `Self` - Rotated 3D transform.
108    #[must_use]
109    pub fn with_euler(mut self, yaw_rad: f32, pitch_rad: f32, roll_rad: f32) -> Self {
110        self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
111        self
112    }
113
114    /// Extracts `(yaw_rad, pitch_rad, roll_rad)` Euler angles matching `Ry(yaw) * Rx(pitch) * Rz(roll)` from this transform's quaternion.
115    ///
116    /// # Returns
117    ///
118    /// - `(f32, f32, f32)` - Extracted `(yaw_rad, pitch_rad, roll_rad)` in radians.
119    #[must_use]
120    pub fn euler_yxz(&self) -> (f32, f32, f32) {
121        let elems: [f32; 16] = self.get_rotation().to_mat4().get_elements();
122        let rot00: f32 = elems[0];
123        let rot10: f32 = elems[1];
124        let rot20: f32 = elems[2];
125        let rot11: f32 = elems[5];
126        let rot02: f32 = elems[8];
127        let rot12: f32 = elems[9];
128        let rot22: f32 = elems[10];
129        let sin_pitch: f32 = (-rot12).clamp(-1.0, 1.0);
130        let pitch_rad: f32 = sin_pitch.asin();
131        if rot12.abs() < 0.99999 {
132            let yaw_rad: f32 = rot02.atan2(rot22);
133            let roll_rad: f32 = rot10.atan2(rot11);
134            (yaw_rad, pitch_rad, roll_rad)
135        } else {
136            let yaw_rad: f32 = (-rot20).atan2(rot00);
137            (yaw_rad, pitch_rad, 0.0)
138        }
139    }
140
141    /// Returns the horizontal Y-axis yaw angle extracted from this transform's quaternion.
142    ///
143    /// # Returns
144    ///
145    /// - `f32` - Yaw angle in radians.
146    #[must_use]
147    pub fn get_yaw_rad(&self) -> f32 {
148        self.euler_yxz().0
149    }
150
151    /// Returns the vertical X-axis pitch angle extracted from this transform's quaternion.
152    ///
153    /// # Returns
154    ///
155    /// - `f32` - Pitch angle in radians.
156    #[must_use]
157    pub fn get_pitch_rad(&self) -> f32 {
158        self.euler_yxz().1
159    }
160
161    /// Returns the longitudinal Z-axis roll angle extracted from this transform's quaternion.
162    ///
163    /// # Returns
164    ///
165    /// - `f32` - Roll angle in radians.
166    #[must_use]
167    pub fn get_roll_rad(&self) -> f32 {
168        self.euler_yxz().2
169    }
170
171    /// Updates horizontal Y-axis yaw while preserving current pitch and roll angles.
172    ///
173    /// # Arguments
174    ///
175    /// - `&Self` - Mutable transform.
176    /// - `f32` - New Y-axis yaw angle in radians.
177    pub fn set_yaw_rad(&mut self, yaw_rad: f32) {
178        let (_, pitch_rad, roll_rad): (f32, f32, f32) = self.euler_yxz();
179        self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
180    }
181
182    /// Updates vertical X-axis pitch while preserving current yaw and roll angles.
183    ///
184    /// # Arguments
185    ///
186    /// - `&Self` - Mutable transform.
187    /// - `f32` - New X-axis pitch angle in radians.
188    pub fn set_pitch_rad(&mut self, pitch_rad: f32) {
189        let (yaw_rad, _, roll_rad): (f32, f32, f32) = self.euler_yxz();
190        self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
191    }
192
193    /// Updates longitudinal Z-axis roll while preserving current yaw and pitch angles.
194    ///
195    /// # Arguments
196    ///
197    /// - `&Self` - Mutable transform.
198    /// - `f32` - New Z-axis roll angle in radians.
199    pub fn set_roll_rad(&mut self, roll_rad: f32) {
200        let (yaw_rad, pitch_rad, _): (f32, f32, f32) = self.euler_yxz();
201        self.set_rotation(Quat::from_euler_yxz(yaw_rad, pitch_rad, roll_rad));
202    }
203
204    /// Interpolates position, shortest-arc quaternion rotation (SLERP), and scale between `self` and `other`.
205    ///
206    /// # Arguments
207    ///
208    /// - `Self` - Start transform.
209    /// - `Self` - End transform.
210    /// - `f32` - Interpolation factor in `[0.0, 1.0]`.
211    ///
212    /// # Returns
213    ///
214    /// - `Self` - Smoothly interpolated transform.
215    #[must_use]
216    pub fn lerp(self, other: Self, blend_factor: f32) -> Self {
217        let clamped_t: f32 = blend_factor.clamp(0.0, 1.0);
218        Self {
219            position: self.get_position().lerp(other.get_position(), clamped_t),
220            rotation: self.get_rotation().slerp(other.get_rotation(), clamped_t),
221            scale: self.get_scale().lerp(other.get_scale(), clamped_t),
222        }
223    }
224
225    /// Interpolates position, scale, and shortest-arc quaternion rotation (SLERP) between `self` and `other` for render-time snapshot blending.
226    ///
227    /// # Arguments
228    ///
229    /// - `Self` - Previous fixed-step transform.
230    /// - `Self` - Current fixed-step transform.
231    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
232    ///
233    /// # Returns
234    ///
235    /// - `Self` - Shortest-arc SLERP interpolated transform.
236    #[must_use]
237    pub fn lerp_shortest_angle(self, other: Self, blend_factor: f32) -> Self {
238        self.lerp(other, blend_factor)
239    }
240
241    /// Converts this quaternion-backed TRS transform into a column-major `Mat4`.
242    ///
243    /// # Arguments
244    ///
245    /// - `&Self` - Transform reference.
246    ///
247    /// # Returns
248    ///
249    /// - `Mat4` - Model matrix.
250    #[must_use]
251    pub fn to_mat4(&self) -> Mat4 {
252        Mat4::from_trs_quat(self.get_position(), self.get_rotation(), self.get_scale())
253    }
254
255    /// Computes the exact inverse TRS matrix mapping world space back to local object space.
256    ///
257    /// # Arguments
258    ///
259    /// - `&Self` - Transform reference.
260    ///
261    /// # Returns
262    ///
263    /// - `Mat4` - Inverse model matrix.
264    #[must_use]
265    pub fn to_inv_mat4(&self) -> Mat4 {
266        self.to_mat4().inverse().unwrap_or_else(Mat4::identity)
267    }
268
269    /// Precomputes the exact cofactor-transpose 3x3 normal basis `[col_x, col_y, col_z]` valid under non-uniform and negative scale.
270    ///
271    /// # Arguments
272    ///
273    /// - `&Self` - Transform reference.
274    ///
275    /// # Returns
276    ///
277    /// - `[Vec3; 3]` - Cofactor 3x3 normal basis columns.
278    #[must_use]
279    pub fn normal_mat3(&self) -> [Vec3; 3] {
280        self.to_mat4().normal_matrix_3x3()
281    }
282
283    /// Rotates vector `vec_value` by this transform's unit quaternion orientation.
284    ///
285    /// # Arguments
286    ///
287    /// - `&Self` - Transform reference.
288    /// - `Vec3` - Input vector.
289    ///
290    /// # Returns
291    ///
292    /// - `Vec3` - Rotated vector.
293    #[must_use]
294    fn rotate_vec(&self, vec_value: Vec3) -> Vec3 {
295        self.get_rotation().rotate_vec3(vec_value)
296    }
297
298    /// Transforms a local-space 3D point into world space.
299    ///
300    /// # Arguments
301    ///
302    /// - `&Self` - Transform reference.
303    /// - `Vec3` - Local-space point.
304    ///
305    /// # Returns
306    ///
307    /// - `Vec3` - World-space point.
308    #[must_use]
309    pub fn transform_point(&self, vec_value: Vec3) -> Vec3 {
310        let direction_vec: Vec3 = self.get_scale();
311        let scaled: Vec3 = Vec3::new(
312            vec_value.get_x() * direction_vec.get_x(),
313            vec_value.get_y() * direction_vec.get_y(),
314            vec_value.get_z() * direction_vec.get_z(),
315        );
316        self.rotate_vec(scaled).add(self.get_position())
317    }
318
319    /// Rotates a local-space surface normal into world space.
320    ///
321    /// # Arguments
322    ///
323    /// - `&Self` - Transform reference.
324    /// - `Vec3` - Local normal.
325    ///
326    /// # Returns
327    ///
328    /// - `Vec3` - World-space unit normal.
329    #[must_use]
330    pub fn transform_normal(&self, vec_value: Vec3) -> Vec3 {
331        self.rotate_vec(vec_value).normalize()
332    }
333
334    /// Transforms a local `AxisAlignedBox3D` into an enclosing world-space `AxisAlignedBox3D` using Arvo's 18-multiply method (zero 8-corner loop, zero per-corner trigonometry).
335    ///
336    /// # Arguments
337    ///
338    /// - `&Self` - Transform reference.
339    /// - `AxisAlignedBox3D` - Local bounding box.
340    ///
341    /// # Returns
342    ///
343    /// - `AxisAlignedBox3D` - Enclosing world-space bounding box.
344    #[must_use]
345    pub fn transform_bounds(&self, local: AxisAlignedBox3D) -> AxisAlignedBox3D {
346        self.to_mat4().transform_bounds(local)
347    }
348
349    /// Converts a local-space `AxisAlignedBox3D` into a tight world-space oriented bounding box (`OrientedBox3D`) preserving rotation and non-uniform scale without axis-aligned bounding box corner inflation.
350    ///
351    /// # Arguments
352    ///
353    /// - `&Self` - Transform reference.
354    /// - `AxisAlignedBox3D` - Local-space bounding box.
355    ///
356    /// # Returns
357    ///
358    /// - `OrientedBox3D` - Oriented bounding box in world space.
359    #[must_use]
360    pub fn to_oriented_box(&self, local: AxisAlignedBox3D) -> OrientedBox3D {
361        let local_center: Vec3 = local.get_min().add(local.get_max()).scale(0.5);
362        let local_half: Vec3 = local.get_max().sub(local.get_min()).scale(0.5);
363        let vec_value: Vec3 = self.get_scale();
364        let center: Vec3 = self.transform_point(local_center);
365        let ax: Vec3 = self.rotate_vec(Vec3::new(1.0, 0.0, 0.0)).normalize();
366        let ay: Vec3 = self.rotate_vec(Vec3::new(0.0, 1.0, 0.0)).normalize();
367        let az: Vec3 = self.rotate_vec(Vec3::new(0.0, 0.0, 1.0)).normalize();
368        let half_extents: Vec3 = Vec3::new(
369            (local_half.get_x() * vec_value.get_x()).abs().max(1e-4),
370            (local_half.get_y() * vec_value.get_y()).abs().max(1e-4),
371            (local_half.get_z() * vec_value.get_z()).abs().max(1e-4),
372        );
373        OrientedBox3D::new(center, [ax, ay, az], half_extents)
374    }
375}
376
377/// Exact oriented bounding box and 13-axis SAT triangle intersection helpers for `OrientedBox3D`.
378impl OrientedBox3D {
379    /// Constructs an axis-aligned `OrientedBox3D` from a world-space `AxisAlignedBox3D`.
380    ///
381    /// # Arguments
382    ///
383    /// - `AxisAlignedBox3D` - World-space axis-aligned bounding box.
384    ///
385    /// # Returns
386    ///
387    /// - `Self` - Equivalent world-space `OrientedBox3D`.
388    #[must_use]
389    pub fn from_bounds(bounds_rect: AxisAlignedBox3D) -> Self {
390        let center: Vec3 = bounds_rect.get_min().add(bounds_rect.get_max()).scale(0.5);
391        let half: Vec3 = bounds_rect.get_max().sub(bounds_rect.get_min()).scale(0.5);
392        Self::new(
393            center,
394            [
395                Vec3::new(1.0, 0.0, 0.0),
396                Vec3::new(0.0, 1.0, 0.0),
397                Vec3::new(0.0, 0.0, 1.0),
398            ],
399            Vec3::new(
400                half.get_x().abs().max(1e-4),
401                half.get_y().abs().max(1e-4),
402                half.get_z().abs().max(1e-4),
403            ),
404        )
405    }
406
407    /// Computes the tightest enclosing world-space `AxisAlignedBox3D` for broadphase culling.
408    ///
409    /// # Arguments
410    ///
411    /// - `&Self` - Oriented bounding box reference.
412    ///
413    /// # Returns
414    ///
415    /// - `AxisAlignedBox3D` - Enclosing world-space axis-aligned bounding box.
416    #[must_use]
417    pub fn to_world_bounds(&self) -> AxisAlignedBox3D {
418        let vec_value: Vec3 = self.get_center();
419        let axes: [Vec3; 3] = self.get_axes();
420        let height_val: Vec3 = self.get_half_extents();
421        let ex: f32 = axes[0].get_x().abs() * height_val.get_x()
422            + axes[1].get_x().abs() * height_val.get_y()
423            + axes[2].get_x().abs() * height_val.get_z();
424        let ey: f32 = axes[0].get_y().abs() * height_val.get_x()
425            + axes[1].get_y().abs() * height_val.get_y()
426            + axes[2].get_y().abs() * height_val.get_z();
427        let ez: f32 = axes[0].get_z().abs() * height_val.get_x()
428            + axes[1].get_z().abs() * height_val.get_y()
429            + axes[2].get_z().abs() * height_val.get_z();
430        let ext: Vec3 = Vec3::new(ex, ey, ez);
431        AxisAlignedBox3D::new(vec_value.sub(ext), vec_value.add(ext))
432    }
433
434    /// Tests exact 13-axis Akenine-Möller SAT intersection between this `OrientedBox3D` and a world-space triangle `(w0, w1, w2)`.
435    ///
436    /// # Arguments
437    ///
438    /// - `&Self` - Oriented bounding box reference.
439    /// - `Vec3` - Triangle vertex 0 in world space.
440    /// - `Vec3` - Triangle vertex 1 in world space.
441    /// - `Vec3` - Triangle vertex 2 in world space.
442    ///
443    /// # Returns
444    ///
445    /// - `Option<(Vec3, f32, Vec3)>` - `(world_outward_normal, penetration_depth, world_contact_point)` when intersecting.
446    #[must_use]
447    pub fn intersect_triangle_world(
448        &self,
449        w0: Vec3,
450        w1: Vec3,
451        w2: Vec3,
452    ) -> Option<(Vec3, f32, Vec3)> {
453        let vec_value: Vec3 = self.get_center();
454        let axes: [Vec3; 3] = self.get_axes();
455        let height_val: Vec3 = self.get_half_extents();
456        let d0: Vec3 = w0.sub(vec_value);
457        let d1: Vec3 = w1.sub(vec_value);
458        let d2: Vec3 = w2.sub(vec_value);
459        let v0: Vec3 = Vec3::new(d0.dot(axes[0]), d0.dot(axes[1]), d0.dot(axes[2]));
460        let v1: Vec3 = Vec3::new(d1.dot(axes[0]), d1.dot(axes[1]), d1.dot(axes[2]));
461        let v2: Vec3 = Vec3::new(d2.dot(axes[0]), d2.dot(axes[1]), d2.dot(axes[2]));
462        let min_x: f32 = v0.get_x().min(v1.get_x()).min(v2.get_x());
463        let max_x: f32 = v0.get_x().max(v1.get_x()).max(v2.get_x());
464        if min_x >= height_val.get_x() || max_x <= -height_val.get_x() {
465            return None;
466        }
467        let min_y: f32 = v0.get_y().min(v1.get_y()).min(v2.get_y());
468        let max_y: f32 = v0.get_y().max(v1.get_y()).max(v2.get_y());
469        if min_y >= height_val.get_y() || max_y <= -height_val.get_y() {
470            return None;
471        }
472        let min_z: f32 = v0.get_z().min(v1.get_z()).min(v2.get_z());
473        let max_z: f32 = v0.get_z().max(v1.get_z()).max(v2.get_z());
474        if min_z >= height_val.get_z() || max_z <= -height_val.get_z() {
475            return None;
476        }
477        let mut best_pen: f32 = f32::INFINITY;
478        let mut best_local_n: Vec3 = Vec3::new(0.0, 1.0, 0.0);
479        let box_axes: [(f32, f32, f32, Vec3); 3] = [
480            (min_x, max_x, height_val.get_x(), Vec3::new(1.0, 0.0, 0.0)),
481            (min_y, max_y, height_val.get_y(), Vec3::new(0.0, 1.0, 0.0)),
482            (min_z, max_z, height_val.get_z(), Vec3::new(0.0, 0.0, 1.0)),
483        ];
484        for (t_min, t_max, half_e, axis) in box_axes {
485            let pen: f32 = (half_e - t_min).min(t_max + half_e);
486            if pen <= 1e-6 {
487                return None;
488            }
489            if pen < best_pen {
490                best_pen = pen;
491                best_local_n = if t_min + t_max > 0.0 {
492                    axis.scale(-1.0)
493                } else {
494                    axis
495                };
496            }
497        }
498        let e0: Vec3 = v1.sub(v0);
499        let e1: Vec3 = v2.sub(v1);
500        let e2: Vec3 = v0.sub(v2);
501        let face_raw: Vec3 = e0.cross(v2.sub(v0));
502        let face_len_sq: f32 = face_raw.length_sq();
503        if face_len_sq > 1e-12 {
504            let face_n: Vec3 = face_raw.scale(1.0 / face_len_sq.sqrt());
505            let dist: f32 = face_n.dot(v0);
506            let red_val: f32 = height_val.get_x() * face_n.get_x().abs()
507                + height_val.get_y() * face_n.get_y().abs()
508                + height_val.get_z() * face_n.get_z().abs();
509            let pen: f32 = red_val - dist.abs();
510            if pen <= 1e-6 {
511                return None;
512            }
513            if pen < best_pen {
514                best_pen = pen;
515                best_local_n = if dist > 0.0 {
516                    face_n.scale(-1.0)
517                } else {
518                    face_n
519                };
520            }
521        }
522        let edges: [Vec3; 3] = [e0, e1, e2];
523        let unit_axes: [Vec3; 3] = [
524            Vec3::new(1.0, 0.0, 0.0),
525            Vec3::new(0.0, 1.0, 0.0),
526            Vec3::new(0.0, 0.0, 1.0),
527        ];
528        for edge in edges {
529            for u_axis in unit_axes {
530                let raw_a: Vec3 = edge.cross(u_axis);
531                let len_sq: f32 = raw_a.length_sq();
532                if len_sq <= 1e-10 {
533                    continue;
534                }
535                let axis: Vec3 = raw_a.scale(1.0 / len_sq.sqrt());
536                let p0: f32 = v0.dot(axis);
537                let p1: f32 = v1.dot(axis);
538                let p2: f32 = v2.dot(axis);
539                let t_min: f32 = p0.min(p1).min(p2);
540                let t_max: f32 = p0.max(p1).max(p2);
541                let radius_val: f32 = height_val.get_x() * axis.get_x().abs()
542                    + height_val.get_y() * axis.get_y().abs()
543                    + height_val.get_z() * axis.get_z().abs();
544                if t_min >= radius_val || t_max <= -radius_val {
545                    return None;
546                }
547                let pen: f32 = (radius_val - t_min).min(t_max + radius_val);
548                if pen <= 1e-6 {
549                    return None;
550                }
551                if pen < best_pen {
552                    best_pen = pen;
553                    best_local_n = if t_min + t_max > 0.0 {
554                        axis.scale(-1.0)
555                    } else {
556                        axis
557                    };
558                }
559            }
560        }
561        let tri_center: Vec3 = v0.add(v1).add(v2).scale(1.0 / 3.0);
562        let local_contact: Vec3 = Vec3::new(
563            tri_center
564                .get_x()
565                .clamp(-height_val.get_x(), height_val.get_x()),
566            tri_center
567                .get_y()
568                .clamp(-height_val.get_y(), height_val.get_y()),
569            tri_center
570                .get_z()
571                .clamp(-height_val.get_z(), height_val.get_z()),
572        );
573        let world_n: Vec3 = axes[0]
574            .scale(best_local_n.get_x())
575            .add(axes[1].scale(best_local_n.get_y()))
576            .add(axes[2].scale(best_local_n.get_z()))
577            .normalize();
578        let world_contact: Vec3 = vec_value
579            .add(axes[0].scale(local_contact.get_x()))
580            .add(axes[1].scale(local_contact.get_y()))
581            .add(axes[2].scale(local_contact.get_z()));
582        Some((world_n, best_pen, world_contact))
583    }
584
585    /// Tests exact 15-axis Separating Axis Theorem intersection between two world-space `OrientedBox3D` volumes for symmetric vehicle-vs-vehicle collision checks.
586    ///
587    /// # Arguments
588    ///
589    /// - `&Self` - First oriented bounding box.
590    /// - `&Self` - Second oriented bounding box.
591    ///
592    /// # Returns
593    ///
594    /// - `bool` - `true` when the two oriented bounding boxes overlap.
595    #[must_use]
596    pub fn intersects_oriented_box(&self, other: &Self) -> bool {
597        let a_axes: [Vec3; 3] = self.get_axes();
598        let b_axes: [Vec3; 3] = other.get_axes();
599        let a_ext: [f32; 3] = [
600            self.get_half_extents().get_x(),
601            self.get_half_extents().get_y(),
602            self.get_half_extents().get_z(),
603        ];
604        let b_ext: [f32; 3] = [
605            other.get_half_extents().get_x(),
606            other.get_half_extents().get_y(),
607            other.get_half_extents().get_z(),
608        ];
609        let mut rot: [[f32; 3]; 3] = [[0.0; 3]; 3];
610        let mut abs_rot: [[f32; 3]; 3] = [[0.0; 3]; 3];
611        for row_idx in 0..3_usize {
612            for col_idx in 0..3_usize {
613                let dot_val: f32 = a_axes[row_idx].dot(b_axes[col_idx]);
614                rot[row_idx][col_idx] = dot_val;
615                abs_rot[row_idx][col_idx] = dot_val.abs() + 1.0e-5;
616            }
617        }
618        let delta_world: Vec3 = other.get_center().sub(self.get_center());
619        let trans: [f32; 3] = [
620            delta_world.dot(a_axes[0]),
621            delta_world.dot(a_axes[1]),
622            delta_world.dot(a_axes[2]),
623        ];
624        for row_idx in 0..3_usize {
625            let ra: f32 = a_ext[row_idx];
626            let rb: f32 = b_ext[0] * abs_rot[row_idx][0]
627                + b_ext[1] * abs_rot[row_idx][1]
628                + b_ext[2] * abs_rot[row_idx][2];
629            if trans[row_idx].abs() > ra + rb {
630                return false;
631            }
632        }
633        for col_idx in 0..3_usize {
634            let ra: f32 = a_ext[0] * abs_rot[0][col_idx]
635                + a_ext[1] * abs_rot[1][col_idx]
636                + a_ext[2] * abs_rot[2][col_idx];
637            let rb: f32 = b_ext[col_idx];
638            let proj: f32 = trans[0] * rot[0][col_idx]
639                + trans[1] * rot[1][col_idx]
640                + trans[2] * rot[2][col_idx];
641            if proj.abs() > ra + rb {
642                return false;
643            }
644        }
645        for row_idx in 0..3_usize {
646            let r1: usize = (row_idx + 1) % 3;
647            let r2: usize = (row_idx + 2) % 3;
648            for col_idx in 0..3_usize {
649                let c1: usize = (col_idx + 1) % 3;
650                let c2: usize = (col_idx + 2) % 3;
651                let ra: f32 = a_ext[r1] * abs_rot[r2][col_idx] + a_ext[r2] * abs_rot[r1][col_idx];
652                let rb: f32 = b_ext[c1] * abs_rot[row_idx][c2] + b_ext[c2] * abs_rot[row_idx][c1];
653                let proj: f32 = trans[r2] * rot[r1][col_idx] - trans[r1] * rot[r2][col_idx];
654                if proj.abs() > ra + rb {
655                    return false;
656                }
657            }
658        }
659        true
660    }
661
662    /// Computes the four horizontal XZ corner coordinates of an oriented box centered at `center`.
663    ///
664    /// # Arguments
665    ///
666    /// - `Vec3` - Box center position.
667    /// - `(f32, f32)` - Normalized horizontal local X axis `(ux, uz)`.
668    /// - `(f32, f32)` - Normalized horizontal local Z axis `(vx, vz)`.
669    /// - `(f32, f32)` - Positive horizontal half-extents `(hx, hz)`.
670    ///
671    /// # Returns
672    ///
673    /// - `[(f32, f32); 4]` - Four world-space XZ corners of the box.
674    #[inline]
675    #[must_use]
676    fn xz_corners(
677        center: Vec3,
678        u_vec: (f32, f32),
679        v_vec: (f32, f32),
680        half_xz: (f32, f32),
681    ) -> [(f32, f32); 4] {
682        let cx: f32 = center.get_x();
683        let cz: f32 = center.get_z();
684        let (hx, hz): (f32, f32) = half_xz;
685        [
686            (
687                cx + u_vec.0 * hx + v_vec.0 * hz,
688                cz + u_vec.1 * hx + v_vec.1 * hz,
689            ),
690            (
691                cx + u_vec.0 * hx - v_vec.0 * hz,
692                cz + u_vec.1 * hx - v_vec.1 * hz,
693            ),
694            (
695                cx - u_vec.0 * hx + v_vec.0 * hz,
696                cz - u_vec.1 * hx + v_vec.1 * hz,
697            ),
698            (
699                cx - u_vec.0 * hx - v_vec.0 * hz,
700                cz - u_vec.1 * hx - v_vec.1 * hz,
701            ),
702        ]
703    }
704
705    /// Computes an exact horizontal XZ Separating Axis Theorem contact manifold between two world-space `OrientedBox3D` vehicle volumes.
706    ///
707    /// # Arguments
708    ///
709    /// - `&Self` - Second oriented bounding box (`B`).
710    ///
711    /// # Returns
712    ///
713    /// - `Option<(Vec3, f32, Vec3)>` - `(unit_normal_b_to_a, penetration_m, world_contact_point)` when overlapping vertically and horizontally.
714    #[must_use]
715    pub fn intersect_oriented_box_xz(&self, other: &Self) -> Option<(Vec3, f32, Vec3)> {
716        let a_bounds: AxisAlignedBox3D = self.to_world_bounds();
717        let b_bounds: AxisAlignedBox3D = other.to_world_bounds();
718        if a_bounds.get_max().get_y() <= b_bounds.get_min().get_y()
719            || b_bounds.get_max().get_y() <= a_bounds.get_min().get_y()
720        {
721            return None;
722        }
723        let norm_xz: fn(Vec3, (f32, f32)) -> (f32, f32) =
724            |axis: Vec3, fallback: (f32, f32)| -> (f32, f32) {
725                let len: f32 = (axis.get_x() * axis.get_x() + axis.get_z() * axis.get_z()).sqrt();
726                if len > 1.0e-5 {
727                    (axis.get_x() / len, axis.get_z() / len)
728                } else {
729                    fallback
730                }
731            };
732        let a_axes: [Vec3; 3] = self.get_axes();
733        let b_axes: [Vec3; 3] = other.get_axes();
734        let ua: (f32, f32) = norm_xz(a_axes[0], (1.0, 0.0));
735        let va: (f32, f32) = norm_xz(a_axes[2], (0.0, 1.0));
736        let ub: (f32, f32) = norm_xz(b_axes[0], (1.0, 0.0));
737        let vb: (f32, f32) = norm_xz(b_axes[2], (0.0, 1.0));
738        let hxa: f32 = self.get_half_extents().get_x();
739        let hza: f32 = self.get_half_extents().get_z();
740        let hxb: f32 = other.get_half_extents().get_x();
741        let hzb: f32 = other.get_half_extents().get_z();
742        let ca: Vec3 = self.get_center();
743        let cb: Vec3 = other.get_center();
744        let dx: f32 = ca.get_x() - cb.get_x();
745        let dz: f32 = ca.get_z() - cb.get_z();
746        let sat_axes: [(f32, f32); 4] = [ua, va, ub, vb];
747        let mut best_pen: f32 = f32::INFINITY;
748        let mut best_nx: f32 = 1.0;
749        let mut best_nz: f32 = 0.0;
750        let mut best_idx: usize = 0;
751        for (axis_idx, &(ax, az)) in sat_axes.iter().enumerate() {
752            let ra: f32 = hxa * (ua.0 * ax + ua.1 * az).abs() + hza * (va.0 * ax + va.1 * az).abs();
753            let rb: f32 = hxb * (ub.0 * ax + ub.1 * az).abs() + hzb * (vb.0 * ax + vb.1 * az).abs();
754            let center_proj: f32 = dx * ax + dz * az;
755            let overlap: f32 = (ra + rb) - center_proj.abs();
756            if overlap <= 1.0e-5 {
757                return None;
758            }
759            if overlap < best_pen {
760                best_pen = overlap;
761                let sign: f32 = if center_proj >= 0.0 { 1.0 } else { -1.0 };
762                best_nx = ax * sign;
763                best_nz = az * sign;
764                best_idx = axis_idx;
765            }
766        }
767        let (inc_corners, dir_x, dir_z): ([(f32, f32); 4], f32, f32) = if best_idx < 2 {
768            (Self::xz_corners(cb, ub, vb, (hxb, hzb)), best_nx, best_nz)
769        } else {
770            (Self::xz_corners(ca, ua, va, (hxa, hza)), -best_nx, -best_nz)
771        };
772        let mut max_proj: f32 = f32::NEG_INFINITY;
773        for &(px, pz) in inc_corners.iter() {
774            let proj: f32 = px * dir_x + pz * dir_z;
775            if proj > max_proj {
776                max_proj = proj;
777            }
778        }
779        let mut sum_x: f32 = 0.0;
780        let mut sum_z: f32 = 0.0;
781        let mut count: f32 = 0.0;
782        for &(px, pz) in inc_corners.iter() {
783            let proj: f32 = px * dir_x + pz * dir_z;
784            if proj >= max_proj - 0.08 {
785                sum_x += px;
786                sum_z += pz;
787                count += 1.0;
788            }
789        }
790        let inv_cnt: f32 = if count > 0.0 { 1.0 / count } else { 1.0 };
791        let contact_y: f32 = (ca.get_y() + cb.get_y()) * 0.5;
792        let contact: Vec3 = Vec3::new(sum_x * inv_cnt, contact_y, sum_z * inv_cnt);
793        Some((Vec3::new(best_nx, 0.0, best_nz), best_pen, contact))
794    }
795}
796
797/// Default full-tank stationary player chassis dynamics state.
798impl Default for PlayerVehiclePhysics3D {
799    /// Initializes a stationary player vehicle with a full nitro boost tank.
800    ///
801    /// # Returns
802    ///
803    /// - `Self` - Stationary `PlayerVehiclePhysics3D` with `boost_charge = 1.0`.
804    fn default() -> Self {
805        Self {
806            vel: Vec3::zero(),
807            yaw_rate: 0.0,
808            body_roll_rad: 0.0,
809            body_pitch_rad: 0.0,
810            boost_active: false,
811            boost_charge: 1.0,
812            drift_active: false,
813            drift_slip_angle: 0.0,
814            drift_duration: 0.0,
815            drift_peak_slip: 0.0,
816            camera_fov_boost: 0.0,
817            camera_shake: 0.0,
818        }
819    }
820}
821
822/// Constructors and navigation route helpers for dynamic rigid-body `NpcVehicle3D` units.
823impl NpcVehicle3D {
824    /// Creates a rigid-body NPC vehicle initially cruising along the 962m boulevard loop with full freedom to be knocked off-road.
825    ///
826    /// # Arguments
827    ///
828    /// - `usize` - Owning scene object index.
829    /// - `f32` - Initial loop centerline arc progress in meters.
830    /// - `f32` - Initial lateral lane offset in meters.
831    /// - `f32` - Signed cruising speed in meters per second.
832    /// - `f32` - Initial facing yaw in radians.
833    ///
834    /// # Returns
835    ///
836    /// - `Self` - Initialized boulevard-cruising rigid-body NPC vehicle.
837    #[must_use]
838    pub(crate) fn new_boulevard(
839        object_index: usize,
840        start_s: f32,
841        lane_u: f32,
842        signed_speed_mps: f32,
843        face_yaw: f32,
844    ) -> Self {
845        let dir: f32 = if signed_speed_mps >= 0.0 { 1.0 } else { -1.0 };
846        let speed: f32 = signed_speed_mps.abs();
847        let fwd: Vec3 = Vec3::new(-face_yaw.sin(), 0.0, -face_yaw.cos());
848        let (target_pos, _): (Vec3, f32) = World3D::loop_pose_at(start_s + dir * 10.0, lane_u);
849        Self {
850            object_index,
851            vel: fwd.scale(speed),
852            yaw_rate: 0.0,
853            mass: VEHICLE_NPC_MASS_KG,
854            cruise_speed: speed,
855            recovery_timer: 0.0,
856            free_roam_mode: false,
857            loop_arc_s: start_s,
858            loop_lane_u: lane_u,
859            loop_dir: dir,
860            nav_target: target_pos,
861            waypoint_idx: 0,
862            route_id: 0,
863        }
864    }
865
866    /// Creates an unrestricted off-road free-roaming rigid-body NPC vehicle navigating open city plazas and courtyards.
867    ///
868    /// # Arguments
869    ///
870    /// - `usize` - Owning scene object index.
871    /// - `u8` - Assigned open-city waypoint route identifier.
872    /// - `usize` - Starting waypoint index along the route.
873    /// - `f32` - Target cruising speed in meters per second.
874    /// - `f32` - Initial facing yaw in radians.
875    ///
876    /// # Returns
877    ///
878    /// - `Self` - Initialized off-road free-roaming rigid-body NPC vehicle.
879    #[must_use]
880    pub(crate) fn new_free_roam(
881        object_index: usize,
882        route_id: u8,
883        waypoint_idx: usize,
884        cruise_speed: f32,
885        face_yaw: f32,
886    ) -> Self {
887        let waypoints: &[(f32, f32)] = Self::route_waypoints(route_id);
888        let safe_idx: usize = waypoint_idx % waypoints.len();
889        let (tx, tz): (f32, f32) = waypoints[safe_idx];
890        let fwd: Vec3 = Vec3::new(-face_yaw.sin(), 0.0, -face_yaw.cos());
891        Self {
892            object_index,
893            vel: fwd.scale(cruise_speed),
894            yaw_rate: 0.0,
895            mass: VEHICLE_NPC_MASS_KG,
896            cruise_speed,
897            recovery_timer: 0.0,
898            free_roam_mode: true,
899            loop_arc_s: 0.0,
900            loop_lane_u: 0.0,
901            loop_dir: 1.0,
902            nav_target: Vec3::new(tx, 0.0, tz),
903            waypoint_idx: safe_idx,
904            route_id,
905        }
906    }
907
908    /// Returns the static open-city off-road waypoint slice for `route_id`.
909    ///
910    /// # Arguments
911    ///
912    /// - `u8` - Open-city route identifier (`0..=2`).
913    ///
914    /// # Returns
915    ///
916    /// - `&'static [(f32, f32)]` - Ordered `(x, z)` waypoints outside the asphalt road.
917    #[must_use]
918    pub(crate) fn route_waypoints(route_id: u8) -> &'static [(f32, f32)] {
919        match route_id {
920            1 => &NPC_OUTER_PLAZA_WAYPOINTS,
921            2 => &NPC_COURTYARD_CROSS_WAYPOINTS,
922            _ => &NPC_INNER_PLAZA_WAYPOINTS,
923        }
924    }
925
926    /// Selects the closest off-road open-city route and waypoint to `pos` so knocked NPCs smoothly resume roaming without ever snapping back to a road lane.
927    ///
928    /// # Arguments
929    ///
930    /// - `Vec3` - Current world-space vehicle position.
931    ///
932    /// # Returns
933    ///
934    /// - `(u8, usize, Vec3)` - `(route_id, waypoint_idx, waypoint_pos)`.
935    #[must_use]
936    pub(crate) fn nearest_open_waypoint(pos: Vec3) -> (u8, usize, Vec3) {
937        let mut best_route: u8 = 0;
938        let mut best_idx: usize = 0;
939        let mut best_pos: Vec3 = Vec3::new(
940            NPC_INNER_PLAZA_WAYPOINTS[0].0,
941            0.0,
942            NPC_INNER_PLAZA_WAYPOINTS[0].1,
943        );
944        let mut best_dist_sq: f32 = f32::INFINITY;
945        for route_id in 0..3_u8 {
946            let pts: &[(f32, f32)] = Self::route_waypoints(route_id);
947            for (idx, &(wx, wz)) in pts.iter().enumerate() {
948                let dx: f32 = wx - pos.get_x();
949                let dz: f32 = wz - pos.get_z();
950                let dist_sq: f32 = dx * dx + dz * dz;
951                if dist_sq > 25.0 && dist_sq < best_dist_sq {
952                    best_dist_sq = dist_sq;
953                    best_route = route_id;
954                    best_idx = idx;
955                    best_pos = Vec3::new(wx, 0.0, wz);
956                }
957            }
958        }
959        (best_route, best_idx, best_pos)
960    }
961}
962
963/// Conversion helpers for `CameraMode3D`.
964impl CameraMode3D {
965    /// Converts a numeric mode index (`0..=5`) into a typed `CameraMode3D`.
966    ///
967    /// # Arguments
968    ///
969    /// - `u8` - Numeric camera mode index.
970    ///
971    /// # Returns
972    ///
973    /// - `Self` - Corresponding `CameraMode3D`.
974    #[must_use]
975    pub const fn from_u8(index: u8) -> Self {
976        match index {
977            1 => Self::Hood,
978            2 => Self::Orbit,
979            3 => Self::Aerial,
980            4 => Self::FreeFly,
981            5 => Self::CinematicDolly,
982            _ => Self::Chase,
983        }
984    }
985
986    /// Converts this `CameraMode3D` into its stable numeric index (`0..=5`).
987    ///
988    /// # Arguments
989    ///
990    /// - `Self` - Camera mode variant.
991    ///
992    /// # Returns
993    ///
994    /// - `u8` - Numeric mode index.
995    #[must_use]
996    pub const fn as_u8(self) -> u8 {
997        match self {
998            Self::Chase => 0,
999            Self::Hood => 1,
1000            Self::Orbit => 2,
1001            Self::Aerial => 3,
1002            Self::FreeFly => 4,
1003            Self::CinematicDolly => 5,
1004        }
1005    }
1006}
1007
1008/// Fluent builder helpers for `SpawnObjectDesc`.
1009impl SpawnObjectDesc {
1010    /// Creates an object spawn descriptor with identity transform, default PBR material, and BVH ray tracing enabled.
1011    ///
1012    /// # Arguments
1013    ///
1014    /// - `&str` - Human-readable object label.
1015    /// - `usize` - Registered mesh identifier.
1016    ///
1017    /// # Returns
1018    ///
1019    /// - `Self` - Ready spawn descriptor.
1020    #[must_use]
1021    pub fn new(name: &str, mesh_id: usize) -> Self {
1022        Self {
1023            name: name.to_string(),
1024            mesh_id,
1025            transform: Transform3D::default(),
1026            material: PbrMaterial::default(),
1027            ray_trace_caster: true,
1028            solid_collider: true,
1029            spin_speed: 0.0,
1030            is_dynamic: false,
1031        }
1032    }
1033
1034    /// Sets the world-space transform for the spawned object.
1035    ///
1036    /// # Arguments
1037    ///
1038    /// - `Self` - Base descriptor.
1039    /// - `Transform3D` - World-space transform.
1040    ///
1041    /// # Returns
1042    ///
1043    /// - `Self` - Updated descriptor.
1044    #[must_use]
1045    pub fn with_transform(mut self, transform: Transform3D) -> Self {
1046        self.set_transform(transform);
1047        self
1048    }
1049
1050    /// Sets the PBR surface material override for the spawned object.
1051    ///
1052    /// # Arguments
1053    ///
1054    /// - `Self` - Base descriptor.
1055    /// - `PbrMaterial` - PBR material.
1056    ///
1057    /// # Returns
1058    ///
1059    /// - `Self` - Updated descriptor.
1060    #[must_use]
1061    pub fn with_material(mut self, material: PbrMaterial) -> Self {
1062        self.set_material(material);
1063        self
1064    }
1065
1066    /// Sets whether this object casts BVH shadows and appears in reflections.
1067    ///
1068    /// # Arguments
1069    ///
1070    /// - `Self` - Base descriptor.
1071    /// - `bool` - Ray-trace caster toggle.
1072    ///
1073    /// # Returns
1074    ///
1075    /// - `Self` - Updated descriptor.
1076    #[must_use]
1077    pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
1078        self.set_ray_trace_caster(ray_trace_caster);
1079        self
1080    }
1081
1082    /// Sets whether this object participates in solid vehicle and camera collision detection.
1083    ///
1084    /// # Arguments
1085    ///
1086    /// - `Self` - Base descriptor.
1087    /// - `bool` - Solid collider toggle.
1088    ///
1089    /// # Returns
1090    ///
1091    /// - `Self` - Updated descriptor.
1092    #[must_use]
1093    pub fn with_solid_collider(mut self, solid_collider: bool) -> Self {
1094        self.set_solid_collider(solid_collider);
1095        self
1096    }
1097
1098    /// Sets continuous Y-axis spin speed in radians per second.
1099    ///
1100    /// # Arguments
1101    ///
1102    /// - `Self` - Base descriptor.
1103    /// - `f32` - Spin speed in radians/sec.
1104    ///
1105    /// # Returns
1106    ///
1107    /// - `Self` - Updated descriptor.
1108    #[must_use]
1109    pub fn with_spin(mut self, spin_speed: f32) -> Self {
1110        self.set_spin_speed(spin_speed);
1111        if spin_speed.abs() > 0.001 {
1112            self.set_is_dynamic(true);
1113        }
1114        self
1115    }
1116
1117    /// Explicitly marks whether this object belongs in the incrementally refitted dynamic BVH.
1118    ///
1119    /// # Arguments
1120    ///
1121    /// - `Self` - Base descriptor.
1122    /// - `bool` - Dynamic caster flag.
1123    ///
1124    /// # Returns
1125    ///
1126    /// - `Self` - Updated descriptor.
1127    #[must_use]
1128    pub fn with_dynamic(mut self, is_dynamic: bool) -> Self {
1129        self.set_is_dynamic(is_dynamic);
1130        self
1131    }
1132}
1133
1134/// Fluent builder helpers for `ImportModelDesc`.
1135impl ImportModelDesc {
1136    /// Creates an external model import descriptor with identity transform and default PBR fallback material.
1137    ///
1138    /// # Arguments
1139    ///
1140    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
1141    /// - `&str` - Raw model source text.
1142    ///
1143    /// # Returns
1144    ///
1145    /// - `Self` - Ready import descriptor.
1146    #[must_use]
1147    pub fn new(format: ModelFormat, source: &str) -> Self {
1148        Self {
1149            format,
1150            source: source.to_string(),
1151            transform: Transform3D::default(),
1152            fallback_material: PbrMaterial::default(),
1153            spin_speed: 0.0,
1154        }
1155    }
1156
1157    /// Sets the placement transform for the imported model.
1158    ///
1159    /// # Arguments
1160    ///
1161    /// - `Self` - Base descriptor.
1162    /// - `Transform3D` - Placement transform.
1163    ///
1164    /// # Returns
1165    ///
1166    /// - `Self` - Updated descriptor.
1167    #[must_use]
1168    pub fn with_transform(mut self, transform: Transform3D) -> Self {
1169        self.set_transform(transform);
1170        self
1171    }
1172
1173    /// Sets the fallback PBR material when source omits material metadata.
1174    ///
1175    /// # Arguments
1176    ///
1177    /// - `Self` - Base descriptor.
1178    /// - `PbrMaterial` - Fallback PBR material.
1179    ///
1180    /// # Returns
1181    ///
1182    /// - `Self` - Updated descriptor.
1183    #[must_use]
1184    pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
1185        self.set_fallback_material(fallback_material);
1186        self
1187    }
1188
1189    /// Sets continuous Y-axis turntable spin speed in radians per second.
1190    ///
1191    /// # Arguments
1192    ///
1193    /// - `Self` - Base descriptor.
1194    /// - `f32` - Spin speed in radians/sec.
1195    ///
1196    /// # Returns
1197    ///
1198    /// - `Self` - Updated descriptor.
1199    #[must_use]
1200    pub fn with_spin(mut self, spin_speed: f32) -> Self {
1201        self.set_spin_speed(spin_speed);
1202        self
1203    }
1204}
1205
1206/// Dynamic Time-of-Day sun and atmospheric sky lighting for `DirectionalLight3D`.
1207impl DirectionalLight3D {
1208    /// Computes physically inspired sun direction, sun color, and sky colors for `hour` in `[0.0, 24.0]`.
1209    ///
1210    /// # Arguments
1211    ///
1212    /// - `f32` - Hour of day (`6.0` dawn, `12.0` noon, `17.5` golden sunset, `22.0` neon night).
1213    ///
1214    /// # Returns
1215    ///
1216    /// - `Self` - Updated atmospheric directional light.
1217    #[must_use]
1218    pub fn from_time_of_day(hour: f32) -> Self {
1219        let height_val: f32 = hour.rem_euclid(24.0);
1220        let elev_angle: f32 = ((height_val - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
1221        let sun_y: f32 = elev_angle.sin();
1222        let sun_x: f32 = elev_angle.cos();
1223        let dir: Vec3 = Vec3::new(-sun_x * 0.62, sun_y.max(0.22), -0.78).normalize();
1224        if (7.5..=16.5).contains(&height_val) {
1225            Self {
1226                direction: dir,
1227                color: Vec3::new(2.35, 2.18, 1.96),
1228                sky_zenith: Vec3::new(0.08, 0.24, 0.64),
1229                sky_horizon: Vec3::new(0.46, 0.66, 0.88),
1230                time_of_day: height_val,
1231            }
1232        } else if (5.5..7.5).contains(&height_val) || (16.5..19.5).contains(&height_val) {
1233            Self {
1234                direction: Vec3::new(-0.14, 0.165, -0.976).normalize(),
1235                color: Vec3::new(2.85, 1.42, 0.66),
1236                sky_zenith: Vec3::new(0.028, 0.038, 0.155),
1237                sky_horizon: Vec3::new(0.62, 0.24, 0.22),
1238                time_of_day: height_val,
1239            }
1240        } else {
1241            Self {
1242                direction: Vec3::new(-0.36, 0.56, -0.74).normalize(),
1243                color: Vec3::new(0.52, 0.68, 1.22),
1244                sky_zenith: Vec3::new(0.012, 0.022, 0.068),
1245                sky_horizon: Vec3::new(0.068, 0.115, 0.235),
1246                time_of_day: height_val,
1247            }
1248        }
1249    }
1250}
1251
1252/// Default golden-sunset directional light.
1253impl Default for DirectionalLight3D {
1254    /// Creates a golden-hour sunset sun configuration.
1255    ///
1256    /// # Returns
1257    ///
1258    /// - `Self` - Sunset `DirectionalLight3D`.
1259    fn default() -> Self {
1260        Self::from_time_of_day(17.2)
1261    }
1262}
1263
1264/// Default empty 3D open world.
1265impl Default for World3D {
1266    /// Creates an empty `World3D` with 64m chunk streaming enabled.
1267    ///
1268    /// # Returns
1269    ///
1270    /// - `Self` - Empty `World3D`.
1271    fn default() -> Self {
1272        Self {
1273            mesh_library: Vec::new(),
1274            objects: Vec::new(),
1275            camera: Camera3D::default(),
1276            sun: DirectionalLight3D::default(),
1277            bvh: Bvh3D::default(),
1278            dynamic_bvh: Bvh3D::default(),
1279            mesh_local_bvhs: Vec::new(),
1280            dynamic_instances: Vec::new(),
1281            bvh_dirty: true,
1282            dynamic_bvh_dirty: true,
1283            dynamic_topology_dirty: true,
1284            static_bvh_rebuilds: 0,
1285            dynamic_bvh_refits: 0,
1286            dynamic_bvh_rebuilds: 0,
1287            world_revision: 1,
1288            sim_tick: 0,
1289            dynamic_tris_scratch: Vec::new(),
1290            chunk_size: 64.0,
1291            player_vehicle_index: None,
1292            hero_vehicle_style: HeroVehicleStyle::AventadorV12,
1293            hero_vehicle_meshes: [None, None],
1294            imported_model_count: 0,
1295            camera_mode: 0,
1296            camera_orbit_rad: 0.4,
1297            point_lights: Vec::new(),
1298            spot_lights: Vec::new(),
1299            niagara: NiagaraSystem3D::default(),
1300            atmosphere_preset: 0,
1301            traffic_vehicles: Vec::new(),
1302            player_physics: PlayerVehiclePhysics3D::default(),
1303            world_time_secs: 0.0,
1304            scene_graph: SceneGraph3D::default(),
1305            principled_materials: Vec::new(),
1306            textures: Vec::new(),
1307            skins: Vec::new(),
1308            animation_mixer: AnimationMixer3D::default(),
1309            environment_ibl: None,
1310            area_lights: Vec::new(),
1311            scene_cameras: Vec::new(),
1312            active_scene_camera: None,
1313            node_object_map: Vec::new(),
1314            skin_scratch: SkinPaletteScratch3D::default(),
1315            deformed_meshes: Vec::new(),
1316            use_agx_tonemap: false,
1317            gpu_pass_scratch: World3dGpuPassScratch::default(),
1318            pbr_pass_scratch: World3dPbrPassScratch::default(),
1319        }
1320    }
1321}
1322
1323/// Open-world construction, model importing, BVH rebuild, and live vehicle/camera simulation for `World3D`.
1324impl World3D {
1325    /// Registers a `MeshLodChain` in the instancing library and returns its `mesh_id`.
1326    ///
1327    /// # Arguments
1328    ///
1329    /// - `&Self` - Mutable world.
1330    /// - `MeshLodChain` - Multi-level LOD mesh chain.
1331    ///
1332    /// # Returns
1333    ///
1334    /// - `usize` - Assigned `mesh_id`.
1335    pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
1336        let id: usize = self.get_mesh_library().len();
1337        self.get_mut_mesh_library().push(chain);
1338        id
1339    }
1340
1341    /// Spawns an instanced `SceneObject3D` referencing `mesh_id` into its spatial world chunk.
1342    ///
1343    /// # Arguments
1344    ///
1345    /// - `&Self` - Mutable world.
1346    /// - `&str` - Object name.
1347    /// - `usize` - Registered `mesh_id`.
1348    /// - `Transform3D` - World transform.
1349    /// - `PbrMaterial` - Surface PBR material.
1350    /// - `bool` - Whether this object participates in BVH ray tracing.
1351    ///
1352    /// # Returns
1353    ///
1354    /// - `usize` - Index of the spawned `SceneObject3D`.
1355    pub fn spawn_object(
1356        &mut self,
1357        name: &str,
1358        mesh_id: usize,
1359        transform: Transform3D,
1360        material: PbrMaterial,
1361        ray_trace_caster: bool,
1362    ) -> usize {
1363        let local_bounds: AxisAlignedBox3D = self
1364            .get_mesh_library()
1365            .get(mesh_id)
1366            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1367            .map(Mesh3D::get_bounds)
1368            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1369        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1370        let cs: f32 = self.get_chunk_size().max(8.0);
1371        let pos: Vec3 = transform.get_position();
1372        let chunk_coord: (i32, i32) = (
1373            (pos.get_x() / cs).floor() as i32,
1374            (pos.get_z() / cs).floor() as i32,
1375        );
1376        let idx: usize = self.get_objects().len();
1377        self.get_mut_objects().push(SceneObject3D {
1378            name: name.to_string(),
1379            mesh_id,
1380            transform,
1381            material,
1382            world_bounds,
1383            chunk_coord,
1384            ray_trace_caster,
1385            solid_collider: ray_trace_caster,
1386            spin_speed: 0.0,
1387            is_dynamic: false,
1388            teleport_epoch: 0,
1389            node_id: None,
1390            principled_material_id: None,
1391            skin_id: None,
1392        });
1393        let Self {
1394            deformed_meshes, ..
1395        } = self;
1396        deformed_meshes.push(None);
1397        if ray_trace_caster {
1398            self.set_bvh_dirty(true);
1399        }
1400        self.bump_world_revision();
1401        idx
1402    }
1403
1404    /// Increments the 3D world revision counter so 3D render caches invalidate independently of UI HUD updates.
1405    ///
1406    /// # Arguments
1407    ///
1408    /// - `&Self` - Mutable world.
1409    pub fn bump_world_revision(&mut self) {
1410        let next: u64 = self.get_world_revision().wrapping_add(1);
1411        self.set_world_revision(next);
1412    }
1413
1414    /// Marks object `obj_idx` as solid or pass-through for real-mesh vehicle collision checks without altering BVH raytracing.
1415    ///
1416    /// # Arguments
1417    ///
1418    /// - `&Self` - Mutable world.
1419    /// - `usize` - Target object index in `objects`.
1420    /// - `bool` - `true` when vehicles must collide with this object's real triangles.
1421    ///
1422    /// # Returns
1423    ///
1424    /// - `bool` - `true` when `obj_idx` existed.
1425    pub fn set_object_collidable(&mut self, obj_idx: usize, solid_collider: bool) -> bool {
1426        if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1427            obj.set_solid_collider(solid_collider);
1428            true
1429        } else {
1430            false
1431        }
1432    }
1433
1434    /// Marks object `obj_idx` as static or dynamic, routing its triangles between the static BVH and incrementally refitted dynamic BVH.
1435    ///
1436    /// # Arguments
1437    ///
1438    /// - `&Self` - Mutable world.
1439    /// - `usize` - Target object index in `objects`.
1440    /// - `bool` - `true` for dynamic BVH routing, `false` for static BVH routing.
1441    ///
1442    /// # Returns
1443    ///
1444    /// - `bool` - `true` when `obj_idx` existed and was updated.
1445    pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
1446        let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
1447            return false;
1448        };
1449        if obj.get_is_dynamic() != is_dynamic {
1450            obj.set_is_dynamic(is_dynamic);
1451            if obj.get_ray_trace_caster() {
1452                self.set_bvh_dirty(true);
1453                self.set_dynamic_bvh_dirty(true);
1454                self.set_dynamic_topology_dirty(true);
1455            }
1456            self.bump_world_revision();
1457        }
1458        true
1459    }
1460
1461    /// Teleports object `obj_idx` to `transform`, incrementing `teleport_epoch` so snapshot interpolation snaps instead of sweeping.
1462    ///
1463    /// # Arguments
1464    ///
1465    /// - `&Self` - Mutable world.
1466    /// - `usize` - Target object index in `objects`.
1467    /// - `Transform3D` - Destination world transform.
1468    ///
1469    /// # Returns
1470    ///
1471    /// - `bool` - `true` when `obj_idx` existed and was teleported.
1472    pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
1473        let Some((mesh_id, ray_caster, is_dynamic)) =
1474            self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
1475                (
1476                    obj.get_mesh_id(),
1477                    obj.get_ray_trace_caster(),
1478                    obj.get_is_dynamic(),
1479                )
1480            })
1481        else {
1482            return false;
1483        };
1484        let local_bounds: AxisAlignedBox3D = self
1485            .get_mesh_library()
1486            .get(mesh_id)
1487            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1488            .map(Mesh3D::get_bounds)
1489            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1490        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1491        if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1492            obj.set_transform(transform);
1493            obj.set_world_bounds(world_bounds);
1494            let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
1495            obj.set_teleport_epoch(next_epoch);
1496        }
1497        if self.vehicle_index() == Some(obj_idx) {
1498            let Self { player_physics, .. } = self;
1499            let saved_charge: f32 = player_physics.get_boost_charge();
1500            *player_physics = PlayerVehiclePhysics3D::default();
1501            player_physics.set_boost_charge(saved_charge);
1502        } else {
1503            let Self {
1504                traffic_vehicles, ..
1505            } = self;
1506            for npc in traffic_vehicles.iter_mut() {
1507                if npc.get_object_index() == obj_idx {
1508                    npc.set_vel(Vec3::zero());
1509                    npc.set_yaw_rate(0.0);
1510                    npc.set_recovery_timer(0.0);
1511                    break;
1512                }
1513            }
1514        }
1515        if ray_caster {
1516            if is_dynamic {
1517                self.set_dynamic_bvh_dirty(true);
1518            } else {
1519                self.set_bvh_dirty(true);
1520            }
1521        }
1522        self.bump_world_revision();
1523        true
1524    }
1525
1526    /// Imports an external `.obj` or `.gltf` model directly into the live 3D world and returns import telemetry.
1527    ///
1528    /// # Arguments
1529    ///
1530    /// - `&Self` - Mutable world.
1531    /// - `ModelFormat` - Source model format.
1532    /// - `&str` - Raw `.obj` or `.gltf` text content.
1533    /// - `Transform3D` - Placement transform in the 3D scene.
1534    /// - `PbrMaterial` - Fallback PBR material.
1535    /// - `f32` - Optional continuous Y-spin speed in radians/sec.
1536    ///
1537    /// # Returns
1538    ///
1539    /// - `Result<ImportedModel3D, String>` - Imported model summary or parse error.
1540    pub fn import_model(
1541        &mut self,
1542        format: ModelFormat,
1543        source: &str,
1544        transform: Transform3D,
1545        fallback_material: PbrMaterial,
1546        spin_speed: f32,
1547    ) -> Result<ImportedModel3D, String> {
1548        let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
1549        let model_name: String = imported.get_name().clone();
1550        for (item_index, chain) in imported.get_meshes().iter().cloned().enumerate() {
1551            let mat: PbrMaterial = chain
1552                .get_levels()
1553                .first()
1554                .map(Mesh3D::get_material)
1555                .unwrap_or(fallback_material);
1556            let mid: usize = self.register_mesh(chain);
1557            let obj_idx: usize = self.spawn_object(
1558                &format!("{model_name}_{item_index}"),
1559                mid,
1560                transform,
1561                mat,
1562                true,
1563            );
1564            if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1565                obj.set_spin_speed(spin_speed);
1566            }
1567            if spin_speed.abs() > 0.001 {
1568                let _: bool = self.set_object_dynamic(obj_idx, true);
1569            }
1570        }
1571        let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
1572        self.set_imported_model_count(next_cnt);
1573        Ok(imported)
1574    }
1575
1576    /// Spawns an object from a fluent `SpawnObjectDesc`.
1577    ///
1578    /// # Arguments
1579    ///
1580    /// - `&Self` - Mutable world.
1581    /// - `&SpawnObjectDesc` - Spawn descriptor.
1582    ///
1583    /// # Returns
1584    ///
1585    /// - `usize` - Spawned object index.
1586    pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
1587        let idx: usize = self.spawn_object(
1588            desc.get_name(),
1589            desc.get_mesh_id(),
1590            desc.get_transform(),
1591            desc.get_material(),
1592            desc.get_ray_trace_caster(),
1593        );
1594        if let Some(obj) = self.get_mut_objects().get_mut(idx) {
1595            obj.set_solid_collider(desc.get_solid_collider());
1596            obj.set_spin_speed(desc.get_spin_speed());
1597        }
1598        if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
1599            let _: bool = self.set_object_dynamic(idx, true);
1600        }
1601        idx
1602    }
1603
1604    /// Imports an external `.obj` or `.gltf` model using a fluent `ImportModelDesc`.
1605    ///
1606    /// # Arguments
1607    ///
1608    /// - `&Self` - Mutable world.
1609    /// - `&ImportModelDesc` - Import descriptor.
1610    ///
1611    /// # Returns
1612    ///
1613    /// - `Result<ImportedModel3D, String>` - Imported model telemetry or parse error.
1614    pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
1615        self.import_model(
1616            desc.get_format(),
1617            desc.get_source(),
1618            desc.get_transform(),
1619            desc.get_fallback_material(),
1620            desc.get_spin_speed(),
1621        )
1622    }
1623
1624    /// Returns the typed `CameraMode3D` currently active in this world.
1625    ///
1626    /// # Arguments
1627    ///
1628    /// - `&Self` - World reference.
1629    ///
1630    /// # Returns
1631    ///
1632    /// - `CameraMode3D` - Active typed camera controller mode.
1633    #[must_use]
1634    pub fn active_camera_mode(&self) -> CameraMode3D {
1635        CameraMode3D::from_u8(self.get_camera_mode())
1636    }
1637
1638    /// Sets the active 3D camera controller using a typed `CameraMode3D`.
1639    ///
1640    /// # Arguments
1641    ///
1642    /// - `&Self` - Mutable world.
1643    /// - `CameraMode3D` - Desired camera controller mode.
1644    pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
1645        self.set_camera_mode(mode.as_u8());
1646    }
1647
1648    /// Collects world-space triangles for all ray-trace casters matching `dynamic_filter` into `out_tris`.
1649    ///
1650    /// # Arguments
1651    ///
1652    /// - `&[SceneObject3D]` - World object slice.
1653    /// - `&[MeshLodChain]` - Registered mesh library slice.
1654    /// - `bool` - `true` to gather dynamic casters, `false` to gather static casters.
1655    /// - `&mut Vec<BvhTriangle>` - Destination triangle buffer cleared and populated in place.
1656    fn collect_caster_triangles(
1657        objects: &[SceneObject3D],
1658        mesh_library: &[MeshLodChain],
1659        dynamic_filter: bool,
1660        out_tris: &mut Vec<BvhTriangle>,
1661    ) {
1662        out_tris.clear();
1663        for obj in objects.iter() {
1664            if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
1665                continue;
1666            }
1667            let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
1668                continue;
1669            };
1670            let Some(mesh) = chain.get_levels().first() else {
1671                continue;
1672            };
1673            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1674            let model_m: Mat4 = obj.get_transform().to_mat4();
1675            let mat: PbrMaterial = obj.get_material();
1676            for (tri_idx, tri) in mesh.get_indices().iter().enumerate() {
1677                let (i0, i1, i2): (usize, usize, usize) =
1678                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1679                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1680                    let p0: Vec3 = model_m.mul_point3(verts[i0].get_position());
1681                    let p1: Vec3 = model_m.mul_point3(verts[i1].get_position());
1682                    let p2: Vec3 = model_m.mul_point3(verts[i2].get_position());
1683                    let (tri_mat, mat_slot): (PbrMaterial, u16) =
1684                        mesh.resolve_triangle_material(tri_idx, mat);
1685                    out_tris.push(BvhTriangle::from_points_with_slot(
1686                        p0, p1, p2, tri_mat, mat_slot,
1687                    ));
1688                }
1689            }
1690        }
1691    }
1692
1693    /// Synchronizes the split static and dynamic BVH acceleration structures, refitting moving dynamic casters in O(N) without rebuilding static world geometry.
1694    ///
1695    /// # Arguments
1696    ///
1697    /// - `&Self` - Mutable world.
1698    pub fn ensure_bvh(&mut self) {
1699        if self.get_bvh_dirty() {
1700            let mut static_tris: Vec<BvhTriangle> = Vec::new();
1701            Self::collect_caster_triangles(
1702                self.get_objects().as_slice(),
1703                self.get_mesh_library().as_slice(),
1704                false,
1705                &mut static_tris,
1706            );
1707            self.set_bvh(Bvh3D::build(static_tris));
1708            self.set_bvh_dirty(false);
1709            let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
1710            self.set_static_bvh_rebuilds(next_static);
1711        }
1712        if self.get_dynamic_bvh_dirty() {
1713            let topology_dirty: bool = self.get_dynamic_topology_dirty();
1714            let Self {
1715                objects,
1716                mesh_library,
1717                dynamic_bvh,
1718                dynamic_tris_scratch,
1719                dynamic_bvh_dirty,
1720                dynamic_topology_dirty,
1721                dynamic_bvh_refits,
1722                dynamic_bvh_rebuilds,
1723                ..
1724            } = self;
1725            Self::collect_caster_triangles(
1726                objects.as_slice(),
1727                mesh_library.as_slice(),
1728                true,
1729                dynamic_tris_scratch,
1730            );
1731            if dynamic_tris_scratch.is_empty() {
1732                dynamic_bvh.rebuild_in_place(&[]);
1733            } else if !topology_dirty
1734                && dynamic_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
1735            {
1736                let check_degraded: bool = ((*dynamic_bvh_refits + 1) & 15) == 0;
1737                if check_degraded && dynamic_bvh.needs_rebuild_after_refit(3.5) {
1738                    dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1739                    *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1740                } else {
1741                    *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
1742                }
1743            } else {
1744                dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1745                *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1746            }
1747            *dynamic_bvh_dirty = false;
1748            *dynamic_topology_dirty = false;
1749        }
1750        self.sync_dynamic_ray_instances();
1751    }
1752
1753    /// Lazily constructs local-space BVH4/BVH8 trees for dynamic meshes and updates `dynamic_instances` from current object transforms with zero BVH rebuilds.
1754    ///
1755    /// # Arguments
1756    ///
1757    /// - `&Self` - Mutable world reference.
1758    pub fn sync_dynamic_ray_instances(&mut self) {
1759        let Self {
1760            mesh_library,
1761            objects,
1762            mesh_local_bvhs,
1763            dynamic_instances,
1764            ..
1765        } = self;
1766        if mesh_local_bvhs.len() < mesh_library.len() {
1767            mesh_local_bvhs.resize_with(mesh_library.len(), || None);
1768        }
1769        dynamic_instances.clear();
1770        for (obj_idx, obj) in objects.iter().enumerate() {
1771            if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
1772                continue;
1773            }
1774            let mesh_id: usize = obj.get_mesh_id();
1775            let Some(chain) = mesh_library.get(mesh_id) else {
1776                continue;
1777            };
1778            let Some(mesh) = chain.get_levels().first() else {
1779                continue;
1780            };
1781            if mesh_local_bvhs[mesh_id].is_none() {
1782                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1783                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1784                let mut local_tris: Vec<BvhTriangle> = Vec::with_capacity(indices.len());
1785                let neutral: PbrMaterial = PbrMaterial::default();
1786                for (tri_idx, tri) in indices.iter().enumerate() {
1787                    let (i0, i1, i2): (usize, usize, usize) =
1788                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1789                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1790                        let (tri_mat, mat_slot): (PbrMaterial, u16) =
1791                            mesh.resolve_triangle_material(tri_idx, neutral);
1792                        local_tris.push(BvhTriangle::from_points_with_slot(
1793                            verts[i0].get_position(),
1794                            verts[i1].get_position(),
1795                            verts[i2].get_position(),
1796                            tri_mat,
1797                            mat_slot,
1798                        ));
1799                    }
1800                }
1801                mesh_local_bvhs[mesh_id] = Some(Bvh3D::build(local_tris));
1802            }
1803            let transform_val: Transform3D = obj.get_transform();
1804            dynamic_instances.push(DynamicRayInstance {
1805                obj_idx,
1806                mesh_id,
1807                world_bounds: obj.get_world_bounds(),
1808                inv_model: transform_val.to_inv_mat4(),
1809                normal_basis: transform_val.normal_mat3(),
1810                material: obj.get_material(),
1811            });
1812        }
1813    }
1814
1815    /// Updates only the inverse-model transform, normal basis, and world axis-aligned bounding box of an existing dynamic instance without rebuilding any BVH.
1816    ///
1817    /// # Arguments
1818    ///
1819    /// - `&Self` - Mutable world reference.
1820    /// - `usize` - Scene object index.
1821    /// - `Transform3D` - Interpolated world transform.
1822    /// - `AxisAlignedBox3D` - Interpolated world axis-aligned bounding box.
1823    pub(crate) fn override_dynamic_instance_pose(
1824        &mut self,
1825        obj_idx: usize,
1826        transform: Transform3D,
1827        world_bounds: AxisAlignedBox3D,
1828    ) {
1829        let Self {
1830            dynamic_instances, ..
1831        } = self;
1832        for inst in dynamic_instances.iter_mut() {
1833            if inst.obj_idx == obj_idx {
1834                inst.world_bounds = world_bounds;
1835                inst.inv_model = transform.to_inv_mat4();
1836                inst.normal_basis = transform.normal_mat3();
1837                return;
1838            }
1839        }
1840    }
1841
1842    /// Traces a shadow ray against object-space dynamic instances via inverse interpolated `Mat4` with zero dynamic BVH rebuilds.
1843    ///
1844    /// # Arguments
1845    ///
1846    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1847    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1848    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1849    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1850    /// - `&mut u32` - Per-thread local occluder triangle hint.
1851    ///
1852    /// # Returns
1853    ///
1854    /// - `bool` - `true` if occluded by any dynamic object at its current or interpolated pose.
1855    #[inline(always)]
1856    #[must_use]
1857    pub(crate) fn trace_any_shadow_dynamic_instances(
1858        instances: &[DynamicRayInstance],
1859        local_bvhs: &[Option<Bvh3D>],
1860        ray: (Vec3, Vec3, Vec3),
1861        bounds: (f32, f32),
1862        dyn_cache: &mut u32,
1863    ) -> bool {
1864        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1865        let (t_min, t_max): (f32, f32) = bounds;
1866        for inst in instances.iter() {
1867            if !inst
1868                .world_bounds
1869                .intersect_ray_near(origin, inv_dir, t_min, t_max)
1870                .is_finite()
1871            {
1872                continue;
1873            }
1874            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1875                continue;
1876            };
1877            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1878            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1879            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1880            if local_bvh
1881                .trace_any_shadow_cached(local_orig, local_dir, local_inv, t_min, t_max, dyn_cache)
1882            {
1883                return true;
1884            }
1885        }
1886        false
1887    }
1888
1889    /// Traces a coherent 4-ray shadow packet against static BVH and object-space inverse-interpolated dynamic instances.
1890    ///
1891    /// # Arguments
1892    ///
1893    /// - `&Bvh3D` - Static world BVH4/BVH8.
1894    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1895    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1896    /// - `&RayPacket4` - Coherent 4-ray shadow packet.
1897    /// - `u8` - 4-bit mask of active rays to trace.
1898    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1899    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1900    ///
1901    /// # Returns
1902    ///
1903    /// - `u8` - 4-bit mask of occluded rays.
1904    #[inline(always)]
1905    #[must_use]
1906    pub(crate) fn trace_any_shadow_packet4_with_instances(
1907        static_bvh: &Bvh3D,
1908        instances: &[DynamicRayInstance],
1909        local_bvhs: &[Option<Bvh3D>],
1910        pkt: &RayPacket4,
1911        active_mask: u8,
1912        bounds: (f32, f32),
1913        caches: (&mut u32, &mut u32),
1914    ) -> u8 {
1915        let (t_min, t_max): (f32, f32) = bounds;
1916        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1917        let mut occluded: u8 =
1918            static_bvh.trace_any_shadow_packet4(pkt, active_mask, t_min, t_max, static_cache);
1919        let mut rem: u8 = active_mask & !occluded;
1920        if rem == 0 || instances.is_empty() {
1921            return occluded;
1922        }
1923        for inst in instances.iter() {
1924            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1925                continue;
1926            };
1927            let mut hit_box_mask: u8 = 0;
1928            let mut check: u8 = rem;
1929            while check != 0 {
1930                let red_val: usize = check.trailing_zeros() as usize;
1931                check &= check - 1;
1932                let orig_r: Vec3 = Vec3::new(pkt.ox[red_val], pkt.oy[red_val], pkt.oz[red_val]);
1933                let inv_r: Vec3 = Vec3::new(pkt.ix[red_val], pkt.iy[red_val], pkt.iz[red_val]);
1934                if inst
1935                    .world_bounds
1936                    .intersect_ray_near(orig_r, inv_r, t_min, t_max)
1937                    .is_finite()
1938                {
1939                    hit_box_mask |= 1_u8 << red_val;
1940                }
1941            }
1942            if hit_box_mask == 0 {
1943                continue;
1944            }
1945            let mut local_pkt: RayPacket4 = *pkt;
1946            let mut tr_mask: u8 = hit_box_mask;
1947            while tr_mask != 0 {
1948                let radius_val: usize = tr_mask.trailing_zeros() as usize;
1949                tr_mask &= tr_mask - 1;
1950                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1951                    pkt.ox[radius_val],
1952                    pkt.oy[radius_val],
1953                    pkt.oz[radius_val],
1954                ));
1955                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1956                    pkt.dx[radius_val],
1957                    pkt.dy[radius_val],
1958                    pkt.dz[radius_val],
1959                ));
1960                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1961                local_pkt.ox[radius_val] = lo.get_x();
1962                local_pkt.oy[radius_val] = lo.get_y();
1963                local_pkt.oz[radius_val] = lo.get_z();
1964                local_pkt.dx[radius_val] = ld.get_x();
1965                local_pkt.dy[radius_val] = ld.get_y();
1966                local_pkt.dz[radius_val] = ld.get_z();
1967                local_pkt.ix[radius_val] = li.get_x();
1968                local_pkt.iy[radius_val] = li.get_y();
1969                local_pkt.iz[radius_val] = li.get_z();
1970            }
1971            let dyn_occ: u8 = local_bvh.trace_any_shadow_packet4(
1972                &local_pkt,
1973                hit_box_mask,
1974                t_min,
1975                t_max,
1976                dyn_cache,
1977            );
1978            occluded |= dyn_occ;
1979            rem &= !dyn_occ;
1980            if rem == 0 {
1981                break;
1982            }
1983        }
1984        occluded
1985    }
1986
1987    /// Traces a shadow/occlusion ray across static BVH and object-space inverse-interpolated dynamic instances.
1988    ///
1989    /// # Arguments
1990    ///
1991    /// - `&Bvh3D` - Static world BVH.
1992    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1993    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1994    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1995    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1996    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1997    ///
1998    /// # Returns
1999    ///
2000    /// - `bool` - `true` when occluded by static or dynamic geometry.
2001    #[inline(always)]
2002    #[must_use]
2003    pub(crate) fn trace_any_shadow_with_instances(
2004        static_bvh: &Bvh3D,
2005        instances: &[DynamicRayInstance],
2006        local_bvhs: &[Option<Bvh3D>],
2007        ray: (Vec3, Vec3, Vec3),
2008        bounds: (f32, f32),
2009        caches: (&mut u32, &mut u32),
2010    ) -> bool {
2011        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2012        let (t_min, t_max): (f32, f32) = bounds;
2013        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
2014        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
2015            return true;
2016        }
2017        if !instances.is_empty() {
2018            return Self::trace_any_shadow_dynamic_instances(
2019                instances, local_bvhs, ray, bounds, dyn_cache,
2020            );
2021        }
2022        false
2023    }
2024
2025    /// Traces a reflection/GI ray across static BVH and object-space inverse-interpolated dynamic instances, returning `(distance, world_normal, material)`.
2026    ///
2027    /// # Arguments
2028    ///
2029    /// - `&Bvh3D` - Static world BVH.
2030    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
2031    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
2032    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
2033    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
2034    ///
2035    /// # Returns
2036    ///
2037    /// - `Option<(f32, Vec3, PbrMaterial)>` - Closest hit distance, world-space unit normal, and PBR material.
2038    #[inline(always)]
2039    #[must_use]
2040    pub(crate) fn trace_closest_with_instances(
2041        static_bvh: &Bvh3D,
2042        instances: &[DynamicRayInstance],
2043        local_bvhs: &[Option<Bvh3D>],
2044        ray: (Vec3, Vec3, Vec3),
2045        bounds: (f32, f32),
2046    ) -> Option<(f32, Vec3, PbrMaterial)> {
2047        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2048        let (t_min, t_max): (f32, f32) = bounds;
2049        let mut best_t: f32 = t_max;
2050        let mut best_hit: Option<(f32, Vec3, PbrMaterial)> = static_bvh
2051            .trace_closest_raw(origin, dir, inv_dir, t_min, t_max)
2052            .map(|(node_style, si): (f32, usize)| {
2053                let tri: &BvhTriangle = &static_bvh.get_triangles()[si];
2054                best_t = node_style;
2055                (node_style, tri.get_normal(), tri.get_material())
2056            });
2057        for inst in instances.iter() {
2058            if !inst
2059                .world_bounds
2060                .intersect_ray_near(origin, inv_dir, t_min, best_t)
2061                .is_finite()
2062            {
2063                continue;
2064            }
2065            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2066                continue;
2067            };
2068            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
2069            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
2070            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
2071            if let Some((dt, di)) =
2072                local_bvh.trace_closest_raw(local_orig, local_dir, local_inv, t_min, best_t)
2073            {
2074                best_t = dt;
2075                let hit_tri: &BvhTriangle = &local_bvh.get_triangles()[di];
2076                let local_n: Vec3 = hit_tri.get_normal();
2077                let world_n: Vec3 = Mat4::transform_normal_with_basis(local_n, inst.normal_basis);
2078                let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
2079                    inst.material
2080                } else {
2081                    hit_tri.get_material()
2082                };
2083                best_hit = Some((dt, world_n, hit_mat));
2084            }
2085        }
2086        best_hit
2087    }
2088
2089    /// Traces a coherent 4-ray closest-hit packet across static BVH and object-space inverse-interpolated dynamic instances.
2090    ///
2091    /// # Arguments
2092    ///
2093    /// - `&Bvh3D` - Static world BVH4/BVH8.
2094    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
2095    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
2096    /// - `&RayPacket4` - Coherent 4-ray reflection or GI packet.
2097    /// - `u8` - 4-bit mask of active rays.
2098    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
2099    ///
2100    /// # Returns
2101    ///
2102    /// - `[Option<(f32, Vec3, PbrMaterial)>; 4]` - Closest hit distance, world normal, and material per lane.
2103    #[inline(always)]
2104    #[must_use]
2105    pub(crate) fn trace_closest_packet4_with_instances(
2106        static_bvh: &Bvh3D,
2107        instances: &[DynamicRayInstance],
2108        local_bvhs: &[Option<Bvh3D>],
2109        pkt: &RayPacket4,
2110        active_mask: u8,
2111        bounds: (f32, f32),
2112    ) -> [Option<(f32, Vec3, PbrMaterial)>; 4] {
2113        let (t_min, t_max): (f32, f32) = bounds;
2114        let mut best_t: [f32; 4] = [t_max; 4];
2115        let mut best_static_idx: [usize; 4] = [usize::MAX; 4];
2116        static_bvh.trace_closest_packet4(
2117            pkt,
2118            active_mask,
2119            t_min,
2120            &mut best_t,
2121            &mut best_static_idx,
2122        );
2123        let static_tris: &[BvhTriangle] = static_bvh.get_triangles().as_slice();
2124        let mut out: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
2125        let mut matrix_elems: u8 = active_mask;
2126        while matrix_elems != 0 {
2127            let red_val: usize = matrix_elems.trailing_zeros() as usize;
2128            matrix_elems &= matrix_elems - 1;
2129            let sidx: usize = best_static_idx[red_val];
2130            if sidx != usize::MAX {
2131                let tri: &BvhTriangle = &static_tris[sidx];
2132                out[red_val] = Some((best_t[red_val], tri.get_normal(), tri.get_material()));
2133            }
2134        }
2135        for inst in instances.iter() {
2136            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
2137                continue;
2138            };
2139            let mut hit_box_mask: u8 = 0;
2140            let mut check: u8 = active_mask;
2141            while check != 0 {
2142                let radius_val: usize = check.trailing_zeros() as usize;
2143                check &= check - 1;
2144                if inst
2145                    .world_bounds
2146                    .intersect_ray_near(
2147                        Vec3::new(pkt.ox[radius_val], pkt.oy[radius_val], pkt.oz[radius_val]),
2148                        Vec3::new(pkt.ix[radius_val], pkt.iy[radius_val], pkt.iz[radius_val]),
2149                        t_min,
2150                        best_t[radius_val],
2151                    )
2152                    .is_finite()
2153                {
2154                    hit_box_mask |= 1_u8 << radius_val;
2155                }
2156            }
2157            if hit_box_mask == 0 {
2158                continue;
2159            }
2160            let mut local_pkt: RayPacket4 = *pkt;
2161            let mut tr_mask: u8 = hit_box_mask;
2162            while tr_mask != 0 {
2163                let rect_val: usize = tr_mask.trailing_zeros() as usize;
2164                tr_mask &= tr_mask - 1;
2165                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
2166                    pkt.ox[rect_val],
2167                    pkt.oy[rect_val],
2168                    pkt.oz[rect_val],
2169                ));
2170                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
2171                    pkt.dx[rect_val],
2172                    pkt.dy[rect_val],
2173                    pkt.dz[rect_val],
2174                ));
2175                let li: Vec3 = Ray3D::safe_inv_vec(ld);
2176                local_pkt.ox[rect_val] = lo.get_x();
2177                local_pkt.oy[rect_val] = lo.get_y();
2178                local_pkt.oz[rect_val] = lo.get_z();
2179                local_pkt.dx[rect_val] = ld.get_x();
2180                local_pkt.dy[rect_val] = ld.get_y();
2181                local_pkt.dz[rect_val] = ld.get_z();
2182                local_pkt.ix[rect_val] = li.get_x();
2183                local_pkt.iy[rect_val] = li.get_y();
2184                local_pkt.iz[rect_val] = li.get_z();
2185            }
2186            let mut dyn_idx: [usize; 4] = [usize::MAX; 4];
2187            local_bvh.trace_closest_packet4(
2188                &local_pkt,
2189                hit_box_mask,
2190                t_min,
2191                &mut best_t,
2192                &mut dyn_idx,
2193            );
2194            let local_tris: &[BvhTriangle] = local_bvh.get_triangles().as_slice();
2195            let mut upd: u8 = hit_box_mask;
2196            while upd != 0 {
2197                let row_val: usize = upd.trailing_zeros() as usize;
2198                upd &= upd - 1;
2199                let di: usize = dyn_idx[row_val];
2200                if di != usize::MAX {
2201                    let hit_tri: &BvhTriangle = &local_tris[di];
2202                    let wn: Vec3 =
2203                        Mat4::transform_normal_with_basis(hit_tri.get_normal(), inst.normal_basis);
2204                    let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
2205                        inst.material
2206                    } else {
2207                        hit_tri.get_material()
2208                    };
2209                    out[row_val] = Some((best_t[row_val], wn, hit_mat));
2210                }
2211            }
2212        }
2213        out
2214    }
2215
2216    /// Traces a shadow ray using static BVH plus object-space inverse-interpolated dynamic instances.
2217    ///
2218    /// # Arguments
2219    ///
2220    /// - `&Self` - World reference.
2221    /// - `&Ray3D` - World-space shadow ray.
2222    /// - `f32` - Minimum hit distance.
2223    /// - `f32` - Maximum hit distance.
2224    ///
2225    /// # Returns
2226    ///
2227    /// - `bool` - `true` when occluded by static or dynamic geometry at its current/interpolated pose.
2228    #[must_use]
2229    pub fn trace_any_shadow_object_space(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
2230        let Self {
2231            bvh,
2232            dynamic_instances,
2233            mesh_local_bvhs,
2234            ..
2235        } = self;
2236        let mut scale_factor: u32 = u32::MAX;
2237        let mut dc: u32 = u32::MAX;
2238        Self::trace_any_shadow_with_instances(
2239            bvh,
2240            dynamic_instances.as_slice(),
2241            mesh_local_bvhs.as_slice(),
2242            (
2243                ray.get_origin(),
2244                ray.get_direction(),
2245                ray.get_inv_direction(),
2246            ),
2247            (t_min, t_max),
2248            (&mut scale_factor, &mut dc),
2249        )
2250    }
2251
2252    /// Traces a coherent 4-ray closest-hit packet against both the static BVH4 and object-space inverse-interpolated dynamic instances.
2253    ///
2254    /// # Arguments
2255    ///
2256    /// - `&Self` - World reference.
2257    /// - `&RayPacket4` - Coherent 4-ray query packet.
2258    /// - `u8` - 4-bit mask of active rays (`0..=15`).
2259    /// - `f32` - Minimum hit distance.
2260    /// - `f32` - Maximum hit distance.
2261    ///
2262    /// # Returns
2263    ///
2264    /// - `[Option<RayHit3D>; 4]` - Closest hit surface with world normal and material per active lane.
2265    #[must_use]
2266    pub fn trace_closest_packet4(
2267        &self,
2268        pkt: &RayPacket4,
2269        active_mask: u8,
2270        t_min: f32,
2271        t_max: f32,
2272    ) -> [Option<RayHit3D>; 4] {
2273        let Self {
2274            bvh,
2275            dynamic_instances,
2276            mesh_local_bvhs,
2277            ..
2278        } = self;
2279        let raw: [Option<(f32, Vec3, PbrMaterial)>; 4] = Self::trace_closest_packet4_with_instances(
2280            bvh,
2281            dynamic_instances.as_slice(),
2282            mesh_local_bvhs.as_slice(),
2283            pkt,
2284            active_mask,
2285            (t_min, t_max),
2286        );
2287        let mut out: [Option<RayHit3D>; 4] = [None; 4];
2288        for lane in 0..4 {
2289            if let Some((blend_factor, normal, material)) = raw[lane] {
2290                let point: Vec3 = Vec3::new(
2291                    pkt.ox[lane] + pkt.dx[lane] * blend_factor,
2292                    pkt.oy[lane] + pkt.dy[lane] * blend_factor,
2293                    pkt.oz[lane] + pkt.dz[lane] * blend_factor,
2294                );
2295                out[lane] = Some(RayHit3D {
2296                    distance: blend_factor,
2297                    point,
2298                    normal,
2299                    material,
2300                });
2301            }
2302        }
2303        out
2304    }
2305
2306    /// Traces a closest-hit ray using static BVH plus object-space inverse-interpolated dynamic instances.
2307    ///
2308    /// # Arguments
2309    ///
2310    /// - `&Self` - World reference.
2311    /// - `&Ray3D` - World-space query ray.
2312    /// - `f32` - Minimum hit distance.
2313    /// - `f32` - Maximum hit distance.
2314    ///
2315    /// # Returns
2316    ///
2317    /// - `Option<RayHit3D>` - Closest hit surface with world-space normal and material.
2318    #[must_use]
2319    pub fn trace_closest_object_space(
2320        &self,
2321        ray: &Ray3D,
2322        t_min: f32,
2323        t_max: f32,
2324    ) -> Option<RayHit3D> {
2325        let Self {
2326            bvh,
2327            dynamic_instances,
2328            mesh_local_bvhs,
2329            ..
2330        } = self;
2331        let (blend_factor, normal, material): (f32, Vec3, PbrMaterial) =
2332            Self::trace_closest_with_instances(
2333                bvh,
2334                dynamic_instances.as_slice(),
2335                mesh_local_bvhs.as_slice(),
2336                (
2337                    ray.get_origin(),
2338                    ray.get_direction(),
2339                    ray.get_inv_direction(),
2340                ),
2341                (t_min, t_max),
2342            )?;
2343        Some(RayHit3D {
2344            distance: blend_factor,
2345            point: ray
2346                .get_origin()
2347                .add(ray.get_direction().scale(blend_factor)),
2348            normal,
2349            material,
2350        })
2351    }
2352
2353    /// Returns the combined node count across both static and dynamic BVH acceleration trees.
2354    ///
2355    /// # Arguments
2356    ///
2357    /// - `&Self` - World reference.
2358    ///
2359    /// # Returns
2360    ///
2361    /// - `usize` - Total active BVH nodes.
2362    #[must_use]
2363    pub fn total_bvh_nodes(&self) -> usize {
2364        self.get_bvh()
2365            .get_nodes()
2366            .len()
2367            .saturating_add(self.get_dynamic_bvh().get_nodes().len())
2368    }
2369
2370    /// Traces a shadow/occlusion ray across both static and dynamic BVHs using 1-triangle occluder caches.
2371    ///
2372    /// # Arguments
2373    ///
2374    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
2375    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
2376    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
2377    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder triangle hints.
2378    ///
2379    /// # Returns
2380    ///
2381    /// - `bool` - `true` if occluded by either static or dynamic geometry.
2382    #[must_use]
2383    pub fn trace_any_shadow_split(
2384        bvhs: (&Bvh3D, &Bvh3D),
2385        ray: (Vec3, Vec3, Vec3),
2386        bounds: (f32, f32),
2387        caches: (&mut u32, &mut u32),
2388    ) -> bool {
2389        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2390        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2391        let (t_min, t_max): (f32, f32) = bounds;
2392        let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
2393        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
2394            return true;
2395        }
2396        if !dynamic_bvh.is_empty() {
2397            return dynamic_bvh.trace_any_shadow_cached(
2398                origin,
2399                dir,
2400                inv_dir,
2401                t_min,
2402                t_max,
2403                dynamic_cache,
2404            );
2405        }
2406        false
2407    }
2408
2409    /// Traces a reflection/GI ray across both static and dynamic BVHs and returns `(distance, is_dynamic, tri_index)`.
2410    ///
2411    /// # Arguments
2412    ///
2413    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
2414    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
2415    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
2416    ///
2417    /// # Returns
2418    ///
2419    /// - `Option<(f32, bool, usize)>` - Closest `(t, hit_in_dynamic_bvh, triangle_index)`.
2420    #[must_use]
2421    pub fn trace_closest_split(
2422        bvhs: (&Bvh3D, &Bvh3D),
2423        ray: (Vec3, Vec3, Vec3),
2424        bounds: (f32, f32),
2425    ) -> Option<(f32, bool, usize)> {
2426        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2427        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2428        let (t_min, t_max): (f32, f32) = bounds;
2429        let static_hit: Option<(f32, usize)> =
2430            static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
2431        let dyn_limit: f32 =
2432            static_hit.map_or(t_max, |(blend_factor, _): (f32, usize)| blend_factor);
2433        let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
2434            dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
2435        } else {
2436            None
2437        };
2438        match (static_hit, dynamic_hit) {
2439            (_, Some((dt, di))) => Some((dt, true, di)),
2440            (Some((node_style, si)), None) => Some((node_style, false, si)),
2441            (None, None) => None,
2442        }
2443    }
2444
2445    /// Returns the optional player vehicle index.
2446    ///
2447    /// # Arguments
2448    ///
2449    /// - `&Self` - World reference.
2450    ///
2451    /// # Returns
2452    ///
2453    /// - `Option<usize>` - Vehicle index in `objects`.
2454    #[must_use]
2455    pub fn vehicle_index(&self) -> Option<usize> {
2456        let Self {
2457            player_vehicle_index,
2458            ..
2459        } = self;
2460        *player_vehicle_index
2461    }
2462
2463    /// Evaluates the closed-loop coastal circuit spine distance `d_spine` and signed lateral offset `road_u = d_spine - CITY_LOOP_RADIUS` for any horizontal world coordinate `(world_x, world_z)`.
2464    ///
2465    /// # Arguments
2466    ///
2467    /// - `f32` - World-space X coordinate in meters.
2468    /// - `f32` - World-space Z coordinate in meters.
2469    ///
2470    /// # Returns
2471    ///
2472    /// - `(f32, f32)` - `(d_spine, road_u)` in meters matching the GPU road/puddle/coastal-bay shader contract.
2473    #[must_use]
2474    pub fn loop_lateral_offset(world_x: f32, world_z: f32) -> (f32, f32) {
2475        let spine_z: f32 = world_z.clamp(-CITY_LOOP_STRAIGHT_HALF_Z, CITY_LOOP_STRAIGHT_HALF_Z);
2476        let dx: f32 = world_x - CITY_LOOP_CENTER_X;
2477        let dz: f32 = world_z - spine_z;
2478        let d_spine: f32 = dx.hypot(dz);
2479        (d_spine, d_spine - CITY_LOOP_RADIUS)
2480    }
2481
2482    /// Evaluates the world-space position and clockwise tangent yaw in radians along the 962m closed-loop stadium circuit at continuous arc-length `arc_s` and signed lateral lane offset `lateral_u`.
2483    ///
2484    /// # Arguments
2485    ///
2486    /// - `f32` - Continuous arc-length along the loop centerline in meters (wrapped modulo `CITY_LOOP_TOTAL_LENGTH`).
2487    /// - `f32` - Signed lateral offset from centerline in meters (`+` outward, `-` inward toward Inner Landmark Island).
2488    ///
2489    /// # Returns
2490    ///
2491    /// - `(Vec3, f32)` - `(world_position, clockwise_yaw_rad)` where car forward is `(-sin(yaw), 0, -cos(yaw))`.
2492    #[must_use]
2493    pub fn loop_pose_at(arc_s: f32, lateral_u: f32) -> (Vec3, f32) {
2494        let straight_len: f32 = 2.0 * CITY_LOOP_STRAIGHT_HALF_Z;
2495        let arc_len: f32 = PI * CITY_LOOP_RADIUS;
2496        let s: f32 = arc_s.rem_euclid(CITY_LOOP_TOTAL_LENGTH);
2497        if s < straight_len {
2498            let world_x: f32 = -lateral_u;
2499            let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z - s;
2500            (Vec3::new(world_x, 0.0, world_z), 0.0)
2501        } else if s < straight_len + arc_len {
2502            let alpha: f32 = (s - straight_len) / CITY_LOOP_RADIUS;
2503            let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2504            let (sin_a, cos_a): (f32, f32) = alpha.sin_cos();
2505            let world_x: f32 = CITY_LOOP_CENTER_X - radius * cos_a;
2506            let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z - radius * sin_a;
2507            (Vec3::new(world_x, 0.0, world_z), -alpha)
2508        } else if s < 2.0 * straight_len + arc_len {
2509            let east_s: f32 = s - (straight_len + arc_len);
2510            let world_x: f32 = CITY_LOOP_CENTER_X * 2.0 + lateral_u;
2511            let world_z: f32 = -CITY_LOOP_STRAIGHT_HALF_Z + east_s;
2512            (Vec3::new(world_x, 0.0, world_z), PI)
2513        } else {
2514            let beta: f32 = (s - (2.0 * straight_len + arc_len)) / CITY_LOOP_RADIUS;
2515            let radius: f32 = CITY_LOOP_RADIUS + lateral_u;
2516            let (sin_b, cos_b): (f32, f32) = beta.sin_cos();
2517            let world_x: f32 = CITY_LOOP_CENTER_X + radius * cos_b;
2518            let world_z: f32 = CITY_LOOP_STRAIGHT_HALF_Z + radius * sin_b;
2519            (Vec3::new(world_x, 0.0, world_z), PI - beta)
2520        }
2521    }
2522
2523    /// Returns the curated six-palette architectural facade PBR material library used across the metropolitan skyline.
2524    ///
2525    /// # Returns
2526    ///
2527    /// - `[PbrMaterial; 6]` - Six distinct architectural facade palettes with `SurfaceDetailMode::ArchitecturalFacade`.
2528    #[must_use]
2529    fn curated_skyline_palettes() -> [PbrMaterial; 6] {
2530        [
2531            PbrMaterial::pbr(Color::hex(0x9E8C73), 0.24, 0.36, 0.38)
2532                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2533            PbrMaterial::pbr(Color::hex(0x163C6B), 0.78, 0.12, 0.76)
2534                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2535            PbrMaterial::pbr(Color::hex(0x141D2D), 0.86, 0.10, 0.82)
2536                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2537            PbrMaterial::pbr(Color::hex(0x7B4232), 0.20, 0.42, 0.32)
2538                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2539            PbrMaterial::pbr(Color::hex(0x0E4B47), 0.74, 0.14, 0.72)
2540                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2541            PbrMaterial::pbr(Color::hex(0x64748B), 0.82, 0.18, 0.70)
2542                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2543        ]
2544    }
2545
2546    /// Registers all six distinct sculpted architectural building archetype meshes in `World3D::mesh_library`.
2547    ///
2548    /// # Returns
2549    ///
2550    /// - `[usize; 6]` - Registered mesh indices `[art_deco, chamfered, twisted, cantilever, cylinder, boutique]`.
2551    fn register_building_archetypes(&mut self) -> [usize; 6] {
2552        let base_mat: PbrMaterial = PbrMaterial::default();
2553        let art_deco: usize = self.register_mesh(MeshLodChain::from_mesh(
2554            Mesh3D::building_art_deco_tower(CITY_MESH_ART_DECO, base_mat),
2555        ));
2556        let chamfered: usize = self.register_mesh(MeshLodChain::from_mesh(
2557            Mesh3D::building_chamfered_glass_tower(CITY_MESH_CHAMFERED, base_mat),
2558        ));
2559        let twisted: usize = self.register_mesh(MeshLodChain::from_mesh(
2560            Mesh3D::building_twisted_spire_tower(CITY_MESH_TWISTED, base_mat),
2561        ));
2562        let cantilever: usize = self.register_mesh(MeshLodChain::from_mesh(
2563            Mesh3D::building_cantilever_tech_tower(CITY_MESH_CANTILEVER, base_mat),
2564        ));
2565        let cylinder: usize = self.register_mesh(MeshLodChain::from_mesh(
2566            Mesh3D::building_cylindrical_landmark(CITY_MESH_CYLINDER, base_mat),
2567        ));
2568        let boutique: usize = self.register_mesh(MeshLodChain::from_mesh(
2569            Mesh3D::building_boutique_podium_block(CITY_MESH_BOUTIQUE, base_mat),
2570        ));
2571        [art_deco, chamfered, twisted, cantilever, cylinder, boutique]
2572    }
2573
2574    /// Returns the signature metallic clearcoat paint material for a given `HeroVehicleStyle`.
2575    ///
2576    /// # Arguments
2577    ///
2578    /// - `HeroVehicleStyle` - Target hero supercar bodywork style.
2579    ///
2580    /// # Returns
2581    ///
2582    /// - `PbrMaterial` - Signature body clearcoat PBR material.
2583    #[must_use]
2584    pub fn hero_vehicle_material(style: HeroVehicleStyle) -> PbrMaterial {
2585        match style {
2586            HeroVehicleStyle::AventadorV12 => {
2587                PbrMaterial::pbr(Color::hex(0xFF4500), 0.30, 0.12, 0.42)
2588            }
2589            HeroVehicleStyle::ShelbyCobra => {
2590                PbrMaterial::pbr(Color::hex(0x0A3EC2), 0.30, 0.12, 0.40)
2591            }
2592        }
2593    }
2594
2595    /// Switches the active hero supercar live between `HeroVehicleStyle::AventadorV12` and `HeroVehicleStyle::ShelbyCobra`, seamlessly preserving live position, yaw, headlights, taillights, and solid collision OBB without reallocating or rebuilding static geometry.
2596    ///
2597    /// # Arguments
2598    ///
2599    /// - `&Self` - Mutable world reference.
2600    /// - `HeroVehicleStyle` - Target hero vehicle bodywork archetype.
2601    ///
2602    /// # Returns
2603    ///
2604    /// - `bool` - `true` when the active hero vehicle mesh was updated.
2605    pub fn set_hero_vehicle_style(&mut self, style: HeroVehicleStyle) -> bool {
2606        let Some(car_idx) = self.vehicle_index() else {
2607            self.set_hero_vehicle_style_raw(style);
2608            return false;
2609        };
2610        let slot_idx: usize = match style {
2611            HeroVehicleStyle::AventadorV12 => 0,
2612            HeroVehicleStyle::ShelbyCobra => 1,
2613        };
2614        let cached_entry: Option<(usize, PbrMaterial)> = {
2615            let Self {
2616                hero_vehicle_meshes,
2617                ..
2618            } = self;
2619            hero_vehicle_meshes[slot_idx]
2620        };
2621        let (target_mesh_id, target_mat): (usize, PbrMaterial) = if let Some(pair) = cached_entry {
2622            pair
2623        } else {
2624            let sig_mat: PbrMaterial = Self::hero_vehicle_material(style);
2625            let built_mesh: Mesh3D = match style {
2626                HeroVehicleStyle::AventadorV12 => {
2627                    Mesh3D::aventador_svj(CITY_MESH_AVENTADOR, sig_mat)
2628                }
2629                HeroVehicleStyle::ShelbyCobra => Mesh3D::shelby_cobra(CITY_MESH_SHELBY, sig_mat),
2630            };
2631            let new_mesh_id: usize = self.register_mesh(MeshLodChain::single_level(built_mesh));
2632            let Self {
2633                hero_vehicle_meshes,
2634                ..
2635            } = self;
2636            hero_vehicle_meshes[slot_idx] = Some((new_mesh_id, sig_mat));
2637            (new_mesh_id, sig_mat)
2638        };
2639        let already_active: bool = self.get_hero_vehicle_style() == style
2640            && self
2641                .get_objects()
2642                .get(car_idx)
2643                .is_some_and(|obj: &SceneObject3D| obj.get_mesh_id() == target_mesh_id);
2644        if already_active {
2645            return false;
2646        }
2647        let new_local_bounds: AxisAlignedBox3D = self
2648            .get_mesh_library()
2649            .get(target_mesh_id)
2650            .and_then(|chain: &MeshLodChain| chain.get_levels().first())
2651            .map(Mesh3D::get_bounds)
2652            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.2), Vec3::splat(1.2)));
2653        if let Some(car_obj) = self.get_mut_objects().get_mut(car_idx) {
2654            let live_tr: Transform3D = car_obj.get_transform();
2655            car_obj.set_mesh_id(target_mesh_id);
2656            car_obj.set_material(target_mat);
2657            car_obj.set_world_bounds(live_tr.transform_bounds(new_local_bounds));
2658        }
2659        self.set_hero_vehicle_style_raw(style);
2660        self.set_dynamic_topology_dirty(true);
2661        self.set_dynamic_bvh_dirty(true);
2662        self.sync_dynamic_ray_instances();
2663        self.bump_world_revision();
2664        true
2665    }
2666
2667    /// Updates the stored `hero_vehicle_style` enum tag cleanly via Lombok setter.
2668    ///
2669    /// # Arguments
2670    ///
2671    /// - `&Self` - Mutable world reference.
2672    /// - `HeroVehicleStyle` - New active hero vehicle style.
2673    fn set_hero_vehicle_style_raw(&mut self, style: HeroVehicleStyle) {
2674        let Self {
2675            hero_vehicle_style, ..
2676        } = self;
2677        *hero_vehicle_style = style;
2678    }
2679
2680    /// Constructs a fresh `OpenWorldCityTemplate3D` containing procedural meshes, BVHs, and pre-baked static GPU vertex buffers.
2681    ///
2682    /// # Returns
2683    ///
2684    /// - `OpenWorldCityTemplate3D` - Complete immutable open-world city prototype.
2685    #[must_use]
2686    fn build_open_world_city_template() -> OpenWorldCityTemplate3D {
2687        let world: Self = Self::build_open_world_city_uncached();
2688        let rev: u64 = Self::allocate_gpu_mesh_revision();
2689        let (gpu_mesh_buffer, gpu_mesh_ranges): (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) =
2690            world.build_gpu_mesh_buffer(rev);
2691        OpenWorldCityTemplate3D {
2692            world,
2693            gpu_mesh_buffer,
2694            gpu_mesh_ranges,
2695        }
2696    }
2697
2698    /// Invokes `visitor` with a shared reference to the cached Vice Boulevard city template, constructing procedural meshes, BVHs, and static GPU vertex buffers once on first call.
2699    ///
2700    /// # Arguments
2701    ///
2702    /// - `F` - Closure consuming `&OpenWorldCityTemplate3D`.
2703    ///
2704    /// # Returns
2705    ///
2706    /// - `R` - Value returned by `visitor`.
2707    fn with_open_world_city_template<F, R>(visitor: F) -> R
2708    where
2709        F: FnOnce(&OpenWorldCityTemplate3D) -> R,
2710    {
2711        #[cfg(not(target_arch = "wasm32"))]
2712        {
2713            let tpl: &OpenWorldCityTemplate3D =
2714                OPEN_WORLD_CITY_TEMPLATE.get_or_init(Self::build_open_world_city_template);
2715            visitor(tpl)
2716        }
2717        #[cfg(target_arch = "wasm32")]
2718        {
2719            OPEN_WORLD_CITY_TEMPLATE_WASM.with(
2720                |slot: &RefCell<Option<OpenWorldCityTemplate3D>>| -> R {
2721                    if let Ok(mut guard) = slot.try_borrow_mut() {
2722                        if guard.is_none() {
2723                            *guard = Some(Self::build_open_world_city_template());
2724                        }
2725                        if let Some(tpl) = guard.as_ref() {
2726                            return visitor(tpl);
2727                        }
2728                    }
2729                    let fallback: OpenWorldCityTemplate3D = Self::build_open_world_city_template();
2730                    visitor(&fallback)
2731                },
2732            )
2733        }
2734    }
2735
2736    /// Builds a coastal closed-loop 962m metropolitan open-world circuit featuring six sculpted architectural building archetypes, an inner landmark skyline island, an open sunlit eastern ocean waterfront promenade, dynamic rigid-body boulevard and off-road NPC traffic, and selectable Aventador SVJ / Shelby GT500 Cobra hero supercars.
2737    ///
2738    /// # Returns
2739    ///
2740    /// - `Self` - Populated open-world 3D coastal city ready for real-time PBR + Ray Tracing.
2741    #[must_use]
2742    pub fn create_open_world_city() -> Self {
2743        Self::with_open_world_city_template(|tpl: &OpenWorldCityTemplate3D| tpl.world.clone())
2744    }
2745
2746    /// Clones the cached Vice Boulevard open-world city together with its pre-baked static GPU vertex buffer in O(1) `Arc::clone`, avoiding main-thread vertex packing stutters on `/game3d` entry.
2747    ///
2748    /// # Returns
2749    ///
2750    /// - `(Self, Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>)` - Ready-to-render 3D city plus shared static GPU mesh buffer and per-mesh vertex ranges.
2751    #[must_use]
2752    pub fn create_open_world_city_with_gpu_cache()
2753    -> (Self, Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
2754        Self::with_open_world_city_template(|tpl: &OpenWorldCityTemplate3D| {
2755            (
2756                tpl.world.clone(),
2757                Arc::clone(&tpl.gpu_mesh_buffer),
2758                tpl.gpu_mesh_ranges.clone(),
2759            )
2760        })
2761    }
2762
2763    /// Constructs the procedural Vice Boulevard 3D city from scratch with pre-sized buffers for one-time initialization into `OPEN_WORLD_CITY_TEMPLATE`.
2764    ///
2765    /// # Returns
2766    ///
2767    /// - `Self` - Freshly assembled open-world 3D city with static and dynamic BVHs built.
2768    #[must_use]
2769    fn build_open_world_city_uncached() -> Self {
2770        let mut world: Self = Self::default();
2771        world.get_mut_mesh_library().reserve(16);
2772        world.get_mut_objects().reserve(144);
2773        world.get_mut_point_lights().reserve(16);
2774        world.get_mut_spot_lights().reserve(4);
2775        {
2776            let Self {
2777                traffic_vehicles, ..
2778            } = &mut world;
2779            traffic_vehicles.reserve(8);
2780        }
2781        let ground_w: f32 = CITY_GROUND_X_MAX - CITY_GROUND_X_MIN;
2782        let ground_d: f32 = CITY_GROUND_Z_MAX - CITY_GROUND_Z_MIN;
2783        let ground_cx: f32 = (CITY_GROUND_X_MIN + CITY_GROUND_X_MAX) * 0.5;
2784        let ground_cz: f32 = (CITY_GROUND_Z_MIN + CITY_GROUND_Z_MAX) * 0.5;
2785        let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0E131C), 0.08, 0.24, 0.62)
2786            .with_surface_detail(SurfaceDetailMode::RoadSurface);
2787        let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
2788            CITY_GROUND_MESH_NAME,
2789            ground_w,
2790            ground_d,
2791            24,
2792            asphalt_mat,
2793        )));
2794        let _: usize = world.spawn_object(
2795            CITY_GROUND_OBJ_NAME,
2796            road_mesh,
2797            Transform3D::new(Vec3::new(ground_cx, 0.0, ground_cz), 0.0, Vec3::splat(1.0)),
2798            asphalt_mat,
2799            false,
2800        );
2801        let ocean_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x063846), 0.05, 0.06, 0.86)
2802            .with_surface_detail(SurfaceDetailMode::OceanWater);
2803        let ocean_mesh: usize =
2804            world.register_mesh(MeshLodChain::from_mesh(Mesh3D::coastal_ocean_ring(
2805                CITY_OCEAN_MESH_NAME,
2806                CITY_OCEAN_SPAN_M,
2807                ground_w * 0.5,
2808                ground_d * 0.5,
2809                24,
2810                ocean_mat,
2811            )));
2812        let _: usize = world.spawn_object(
2813            CITY_OCEAN_MESH_NAME,
2814            ocean_mesh,
2815            Transform3D::new(
2816                Vec3::new(ground_cx, CITY_OCEAN_SURFACE_Y, ground_cz),
2817                0.0,
2818                Vec3::splat(1.0),
2819            ),
2820            ocean_mat,
2821            false,
2822        );
2823        let stud_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFBBF24), 0.90);
2824        let stud_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2825            CITY_LANE_STUD_MESH_NAME,
2826            0.10,
2827            0.018,
2828            0.16,
2829            true,
2830            stud_mat,
2831        )));
2832        for iz in -7..=0 {
2833            let _: usize = world.spawn_object(
2834                &format!("stripe_{iz}"),
2835                stud_mesh,
2836                Transform3D::new(
2837                    Vec3::new(0.0, 0.008, (iz as f32) * 14.0),
2838                    0.0,
2839                    Vec3::splat(1.0),
2840                ),
2841                stud_mat,
2842                false,
2843            );
2844        }
2845        let unit_box: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2846            CITY_UNIT_BOX_MESH_NAME,
2847            1.0,
2848            1.0,
2849            1.0,
2850            true,
2851            PbrMaterial::default(),
2852        )));
2853        let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2854            CITY_NEON_SIGN_MESH_NAME,
2855            1.0,
2856            1.0,
2857            1.0,
2858            true,
2859            PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
2860        )));
2861        let archetypes: [usize; 6] = world.register_building_archetypes();
2862        let palettes: [PbrMaterial; 6] = Self::curated_skyline_palettes();
2863        let neon_colors: [Color; 4] = [
2864            Color::hex(0x38BDF8),
2865            Color::hex(0xF43F5E),
2866            Color::hex(0xA855F7),
2867            Color::hex(0x34D399),
2868        ];
2869        let west_pattern: [(usize, f32, f32, f32); 9] = [
2870            (0, 46.0, 11.2, 12.0),
2871            (5, 20.0, 11.6, 12.4),
2872            (1, 38.0, 11.0, 11.8),
2873            (3, 34.0, 10.6, 11.8),
2874            (4, 48.0, 11.4, 11.4),
2875            (5, 22.0, 11.4, 12.2),
2876            (2, 54.0, 11.2, 11.2),
2877            (1, 40.0, 10.8, 12.0),
2878            (0, 44.0, 11.0, 11.6),
2879        ];
2880        let mut idx_counter: usize = 0;
2881        for side in [-1.0_f32, 1.0_f32] {
2882            for (row_i, row_z_idx) in (-4..=4_i32).enumerate() {
2883                let (base_arch, base_h, width_val, depth_val): (usize, f32, f32, f32) =
2884                    west_pattern[(row_i + if side > 0.0 { 2 } else { 0 }) % west_pattern.len()];
2885                let pos_z: f32 = (row_z_idx as f32) * 28.0 - 4.0;
2886                let pos_x: f32 = side * (22.0 + ((idx_counter % 3) as f32) * 1.1);
2887                let height_val: f32 = if side > 0.0 && base_arch != 5 {
2888                    base_h + 4.0
2889                } else {
2890                    base_h
2891                };
2892                let mat: PbrMaterial = palettes[(idx_counter * 5 + row_i) % palettes.len()];
2893                let _: usize = world.spawn_object(
2894                    &format!("tower_{idx_counter}"),
2895                    archetypes[base_arch],
2896                    Transform3D::new(
2897                        Vec3::new(pos_x, 0.0, pos_z),
2898                        0.0,
2899                        Vec3::new(width_val, height_val, depth_val),
2900                    ),
2901                    mat,
2902                    true,
2903                );
2904                idx_counter += 1;
2905            }
2906        }
2907        let inner_spine_specs: [(f32, f32, f32, f32, f32, usize, usize); 19] = [
2908            (64.0, -158.0, 14.0, 56.0, 14.0, 4, 1),
2909            (64.0, -116.0, 14.5, 68.0, 14.5, 0, 0),
2910            (54.0, -76.0, 13.0, 62.0, 13.0, 2, 2),
2911            (76.0, -76.0, 13.0, 52.0, 13.0, 1, 4),
2912            (64.0, -34.0, 15.0, 74.0, 15.0, 2, 5),
2913            (52.0, 10.0, 13.5, 58.0, 13.5, 3, 3),
2914            (78.0, 12.0, 13.5, 64.0, 13.5, 4, 1),
2915            (64.0, 56.0, 14.5, 70.0, 14.5, 0, 0),
2916            (54.0, 98.0, 13.0, 54.0, 13.0, 1, 2),
2917            (76.0, 100.0, 13.0, 48.0, 13.0, 3, 4),
2918            (64.0, 156.0, 14.0, 58.0, 14.0, 4, 5),
2919            (103.5, -112.0, 11.4, 34.0, 12.4, 5, 0),
2920            (103.5, -78.0, 11.6, 48.0, 11.6, 4, 4),
2921            (103.5, -44.0, 11.4, 24.0, 12.2, 5, 3),
2922            (103.5, -10.0, 11.8, 44.0, 12.0, 1, 1),
2923            (103.5, 24.0, 11.4, 38.0, 12.0, 3, 5),
2924            (103.5, 58.0, 11.6, 22.0, 12.2, 5, 0),
2925            (103.5, 92.0, 11.8, 46.0, 11.8, 0, 2),
2926            (103.5, 124.0, 11.4, 40.0, 11.4, 2, 4),
2927        ];
2928        for (l_idx, &(lx, lz, lw, lh, ld, l_arch, l_pal)) in inner_spine_specs.iter().enumerate() {
2929            let _: usize = world.spawn_object(
2930                &format!("landmark_tower_{l_idx}"),
2931                archetypes[l_arch],
2932                Transform3D::new(Vec3::new(lx, 0.0, lz), 0.0, Vec3::new(lw, lh, ld)),
2933                palettes[l_pal],
2934                true,
2935            );
2936        }
2937        let skyline_specs: [(f32, f32, f32, f32, usize, usize); 6] = [
2938            (-46.0, -96.0, 13.0, 56.0, 0, 2),
2939            (-46.0, -64.0, 12.5, 66.0, 2, 1),
2940            (-46.0, -32.0, 13.0, 52.0, 4, 4),
2941            (-46.0, 4.0, 12.5, 62.0, 1, 5),
2942            (-46.0, 40.0, 12.5, 50.0, 3, 3),
2943            (-46.0, 76.0, 13.0, 58.0, 0, 0),
2944        ];
2945        for (sky_idx, &(sx, sz, sw, sh, s_arch, s_pal)) in skyline_specs.iter().enumerate() {
2946            let _: usize = world.spawn_object(
2947                &format!("{CITY_SKYLINE_MESH_NAME}_{sky_idx}"),
2948                archetypes[s_arch],
2949                Transform3D::new(Vec3::new(sx, 0.0, sz), 0.0, Vec3::new(sw, sh, 13.0)),
2950                palettes[s_pal],
2951                true,
2952            );
2953        }
2954        let mut rim_serial: usize = 0;
2955        let rim_angles_deg: [f32; 7] = [44.0, 64.0, 84.0, 104.0, 124.0, 144.0, 164.0];
2956        for (turn_idx, &turn_sign_z) in [-1.0_f32, 1.0_f32].iter().enumerate() {
2957            let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
2958            for (ang_i, &deg) in rim_angles_deg.iter().enumerate() {
2959                let rad: f32 = deg.to_radians();
2960                let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
2961                let ring_r: f32 = 99.0 + ((ang_i % 2) as f32) * 3.5;
2962                let rx: f32 = CITY_LOOP_CENTER_X + ring_r * cos_a;
2963                let rz: f32 = center_z + turn_sign_z * ring_r * sin_a;
2964                let yaw_rim: f32 = if turn_sign_z < 0.0 {
2965                    rad - FRAC_PI_2
2966                } else {
2967                    FRAC_PI_2 - rad
2968                };
2969                let arch_i: usize = (rim_serial + turn_idx * 2) % archetypes.len();
2970                let height_m: f32 = if arch_i == 5 {
2971                    24.0
2972                } else {
2973                    36.0 + ((rim_serial * 7) % 4) as f32 * 8.0
2974                };
2975                let _: usize = world.spawn_object(
2976                    &format!("rim_tower_{rim_serial}"),
2977                    archetypes[arch_i],
2978                    Transform3D::new(
2979                        Vec3::new(rx, 0.0, rz),
2980                        yaw_rim,
2981                        Vec3::new(11.5, height_m, 11.5),
2982                    ),
2983                    palettes[(rim_serial + 1) % palettes.len()],
2984                    true,
2985                );
2986                rim_serial += 1;
2987            }
2988        }
2989        let seawall_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x475569), 0.14, 0.56, 0.22);
2990        let mut wall_serial: usize = 0;
2991        let _: usize = world.spawn_object(
2992            &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
2993            unit_box,
2994            Transform3D::new(
2995                Vec3::new(146.0, 0.0, 0.0),
2996                0.0,
2997                Vec3::new(2.4, 1.15, CITY_LOOP_STRAIGHT_HALF_Z * 2.0 + 4.0),
2998            ),
2999            seawall_mat,
3000            true,
3001        );
3002        wall_serial += 1;
3003        for &turn_sign_z in [-1.0_f32, 1.0_f32].iter() {
3004            let center_z: f32 = turn_sign_z * CITY_LOOP_STRAIGHT_HALF_Z;
3005            let seg_count: usize = 10;
3006            for seg_i in 0..seg_count {
3007                let deg: f32 = 3.0 + (seg_i as f32) * 6.0;
3008                let rad: f32 = deg.to_radians();
3009                let (sin_a, cos_a): (f32, f32) = rad.sin_cos();
3010                let wall_r: f32 = 79.0;
3011                let wx: f32 = CITY_LOOP_CENTER_X + wall_r * cos_a;
3012                let wz: f32 = center_z + turn_sign_z * wall_r * sin_a;
3013                let wall_yaw: f32 = if turn_sign_z < 0.0 { rad } else { -rad };
3014                let _: usize = world.spawn_object(
3015                    &format!("{CITY_SEAWALL_MESH_NAME}_{wall_serial}"),
3016                    unit_box,
3017                    Transform3D::new(Vec3::new(wx, 0.0, wz), wall_yaw, Vec3::new(2.2, 1.15, 10.6)),
3018                    seawall_mat,
3019                    true,
3020                );
3021                wall_serial += 1;
3022            }
3023        }
3024        let palm_mesh: usize = world.register_mesh(MeshLodChain::single_level(Mesh3D::palm_tree(
3025            CITY_PALM_MESH_NAME,
3026        )));
3027        let palm_bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
3028        let palm_z_positions: [f32; 6] = [-102.0, -74.0, -46.0, -18.0, 10.0, 38.0];
3029        for (palm_row, &palm_z) in palm_z_positions.iter().enumerate() {
3030            for side_idx in 0..2usize {
3031                let side_sign: f32 = if side_idx == 0 { -1.0 } else { 1.0 };
3032                let yaw_palm: f32 = (palm_row as f32) * 0.95
3033                    + (side_idx as f32) * 2.1
3034                    + if side_idx == 0 { 0.35 } else { -0.35 };
3035                let scale_palm: f32 = 0.94 + ((palm_row + side_idx) % 3) as f32 * 0.08;
3036                let _: usize = world.spawn_object(
3037                    &format!("palm_{palm_row}_{side_idx}"),
3038                    palm_mesh,
3039                    Transform3D::new(
3040                        Vec3::new(side_sign * 12.0, 0.0, palm_z),
3041                        yaw_palm,
3042                        Vec3::splat(scale_palm),
3043                    ),
3044                    palm_bark_mat,
3045                    true,
3046                );
3047            }
3048        }
3049        for coast_i in 0..10usize {
3050            let cz: f32 = -124.0 + (coast_i as f32) * 27.5;
3051            let yaw_p: f32 = (coast_i as f32) * 0.72 + 1.2;
3052            let scale_p: f32 = 0.96 + (coast_i % 3) as f32 * 0.07;
3053            let _: usize = world.spawn_object(
3054                &format!("waterfront_palm_{coast_i}"),
3055                palm_mesh,
3056                Transform3D::new(Vec3::new(139.8, 0.0, cz), yaw_p, Vec3::splat(scale_p)),
3057                palm_bark_mat,
3058                true,
3059            );
3060        }
3061        let arch_frame_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0F172A), 0.82, 0.18, 0.60);
3062        for (arch_idx, &arch_z) in [-36.0_f32, -80.0_f32, 48.0_f32].iter().enumerate() {
3063            let arch_neon: PbrMaterial =
3064                PbrMaterial::neon(neon_colors[arch_idx % neon_colors.len()], 2.1);
3065            let _: usize = world.spawn_object(
3066                &format!("arch_beam_{arch_idx}"),
3067                unit_box,
3068                Transform3D::new(
3069                    Vec3::new(0.0, 13.4, arch_z),
3070                    0.0,
3071                    Vec3::new(23.0, 0.58, 0.72),
3072                ),
3073                arch_frame_mat,
3074                true,
3075            );
3076            let _: usize = world.spawn_object(
3077                &format!("arch_glow_{arch_idx}"),
3078                neon_unit,
3079                Transform3D::new(
3080                    Vec3::new(0.0, 13.08, arch_z),
3081                    0.0,
3082                    Vec3::new(21.2, 0.24, 0.34),
3083                ),
3084                arch_neon,
3085                true,
3086            );
3087            for side in [-1.0_f32, 1.0_f32] {
3088                let _: usize = world.spawn_object(
3089                    &format!("arch_pillar_{arch_idx}_{}", if side < 0.0 { 0 } else { 1 }),
3090                    unit_box,
3091                    Transform3D::new(
3092                        Vec3::new(side * 11.2, 0.0, arch_z),
3093                        0.0,
3094                        Vec3::new(0.58, 13.4, 0.68),
3095                    ),
3096                    arch_frame_mat,
3097                    true,
3098                );
3099            }
3100        }
3101        let aventador_mat: PbrMaterial =
3102            Self::hero_vehicle_material(HeroVehicleStyle::AventadorV12);
3103        let shelby_mat: PbrMaterial = Self::hero_vehicle_material(HeroVehicleStyle::ShelbyCobra);
3104        let aventador_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3105            Mesh3D::aventador_svj(CITY_MESH_AVENTADOR, aventador_mat),
3106        ));
3107        let shelby_mesh: usize = world.register_mesh(MeshLodChain::single_level(
3108            Mesh3D::shelby_cobra(CITY_MESH_SHELBY, shelby_mat),
3109        ));
3110        {
3111            let Self {
3112                hero_vehicle_meshes,
3113                ..
3114            } = &mut world;
3115            hero_vehicle_meshes[0] = Some((aventador_mesh, aventador_mat));
3116            hero_vehicle_meshes[1] = Some((shelby_mesh, shelby_mat));
3117        }
3118        let car_idx: usize = world.spawn_object(
3119            CITY_OBJ_PLAYER_CAR,
3120            aventador_mesh,
3121            Transform3D::new(Vec3::new(0.0, 0.0, 0.0), 0.0, Vec3::splat(1.1)),
3122            aventador_mat,
3123            true,
3124        );
3125        let _: bool = world.set_object_dynamic(car_idx, true);
3126        world.set_player_vehicle_index(Some(car_idx));
3127        let _: usize = world.add_point_light(PointLight3D::new(
3128            Vec3::new(0.0, 0.95, 2.9),
3129            Color::hex(0xFF1744),
3130            1.85,
3131            8.5,
3132        ));
3133        let traffic_specs: [(f32, f32, f32, usize, Color); 4] = [
3134            (156.0, 5.6, -11.5, shelby_mesh, Color::hex(0x38BDF8)),
3135            (620.0, 5.6, -11.5, aventador_mesh, Color::hex(0xA855F7)),
3136            (164.0, -5.6, 13.0, aventador_mesh, Color::hex(0x22C55E)),
3137            (645.0, -5.6, 13.0, shelby_mesh, Color::hex(0xF59E0B)),
3138        ];
3139        for (t_idx, &(start_s, lane_u, speed_mps, t_mesh, t_col)) in
3140            traffic_specs.iter().enumerate()
3141        {
3142            let (t_pos, base_yaw): (Vec3, f32) = Self::loop_pose_at(start_s, lane_u);
3143            let face_yaw: f32 = if speed_mps >= 0.0 {
3144                base_yaw
3145            } else {
3146                base_yaw + PI
3147            };
3148            let tmat: PbrMaterial = PbrMaterial::pbr(t_col, 0.84, 0.13, 0.76);
3149            let obj_id: usize = world.spawn_object(
3150                &format!("ai_traffic_{t_idx}"),
3151                t_mesh,
3152                Transform3D::new(t_pos, face_yaw, Vec3::splat(1.04)),
3153                tmat,
3154                true,
3155            );
3156            let _: bool = world.set_object_dynamic(obj_id, true);
3157            let Self {
3158                traffic_vehicles, ..
3159            } = &mut world;
3160            traffic_vehicles.push(NpcVehicle3D::new_boulevard(
3161                obj_id, start_s, lane_u, speed_mps, face_yaw,
3162            ));
3163        }
3164        let offroad_specs: [(Vec3, f32, u8, usize, f32, usize, Color); 4] = [
3165            (
3166                Vec3::new(38.0, 0.0, -40.0),
3167                0.0,
3168                0,
3169                0,
3170                10.5,
3171                aventador_mesh,
3172                Color::hex(0x14B8A6),
3173            ),
3174            (
3175                Vec3::new(91.0, 0.0, 40.0),
3176                PI,
3177                0,
3178                3,
3179                10.0,
3180                shelby_mesh,
3181                Color::hex(0xFB7185),
3182            ),
3183            (
3184                Vec3::new(-72.0, 0.0, -30.0),
3185                PI,
3186                1,
3187                1,
3188                11.0,
3189                aventador_mesh,
3190                Color::hex(0xEAB308),
3191            ),
3192            (
3193                Vec3::new(38.0, 0.0, 78.0),
3194                -FRAC_PI_2,
3195                2,
3196                1,
3197                9.5,
3198                shelby_mesh,
3199                Color::hex(0x6366F1),
3200            ),
3201        ];
3202        for (o_idx, &(o_pos, o_yaw, route_id, wp_idx, o_speed, o_mesh, o_col)) in
3203            offroad_specs.iter().enumerate()
3204        {
3205            let traffic_serial: usize = traffic_specs.len() + o_idx;
3206            let omat: PbrMaterial = PbrMaterial::pbr(o_col, 0.84, 0.13, 0.76);
3207            let obj_id: usize = world.spawn_object(
3208                &format!("ai_traffic_{traffic_serial}"),
3209                o_mesh,
3210                Transform3D::new(o_pos, o_yaw, Vec3::splat(1.04)),
3211                omat,
3212                true,
3213            );
3214            let _: bool = world.set_object_dynamic(obj_id, true);
3215            let Self {
3216                traffic_vehicles, ..
3217            } = &mut world;
3218            traffic_vehicles.push(NpcVehicle3D::new_free_roam(
3219                obj_id, route_id, wp_idx, o_speed, o_yaw,
3220            ));
3221        }
3222        let lamp_palette: [Color; 4] = [
3223            Color::hex(0x38BDF8),
3224            Color::hex(0xF43F5E),
3225            Color::hex(0xA855F7),
3226            Color::hex(0x34D399),
3227        ];
3228        let lamp_z_rows: [f32; 4] = [-62.0, -26.0, 18.0, 66.0];
3229        for lamp_idx in 0..8usize {
3230            let side: f32 = if lamp_idx % 2 == 0 { -1.0 } else { 1.0 };
3231            let z_pos: f32 = lamp_z_rows[lamp_idx / 2];
3232            let lamp_color: Color = lamp_palette[lamp_idx % lamp_palette.len()];
3233            let _: usize = world.spawn_object(
3234                &format!("lamp_pole_{lamp_idx}"),
3235                unit_box,
3236                Transform3D::new(
3237                    Vec3::new(side * 10.65, 0.0, z_pos),
3238                    0.0,
3239                    Vec3::new(0.20, 6.2, 0.20),
3240                ),
3241                arch_frame_mat,
3242                true,
3243            );
3244            let _: usize = world.spawn_object(
3245                &format!("lamp_head_{lamp_idx}"),
3246                neon_unit,
3247                Transform3D::new(
3248                    Vec3::new(side * 10.15, 6.2, z_pos),
3249                    0.0,
3250                    Vec3::new(1.1, 0.18, 0.28),
3251                ),
3252                PbrMaterial::neon(lamp_color, 2.2),
3253                true,
3254            );
3255            let _: usize = world.add_point_light(PointLight3D::new(
3256                Vec3::new(side * 9.8, 6.2, z_pos),
3257                lamp_color,
3258                2.35,
3259                16.5,
3260            ));
3261        }
3262        let _: usize = world.add_spot_light(SpotLight3D::new(
3263            Vec3::new(-0.85, 0.95, -2.2),
3264            Vec3::new(0.0, -0.14, -1.0),
3265            Color::hex(0xFEF3C7),
3266            2.8,
3267            24.0,
3268            (14.0, 26.0),
3269        ));
3270        let _: usize = world.add_spot_light(SpotLight3D::new(
3271            Vec3::new(0.85, 0.95, -2.2),
3272            Vec3::new(0.0, -0.14, -1.0),
3273            Color::hex(0xFEF3C7),
3274            2.8,
3275            24.0,
3276            (14.0, 26.0),
3277        ));
3278        world.set_camera(Camera3D {
3279            position: Vec3::new(0.0, 4.15, 9.2),
3280            yaw: -FRAC_PI_2,
3281            pitch: -0.145,
3282            fov_deg: 60.0,
3283            near: 0.3,
3284            far: 560.0,
3285        });
3286        world.ensure_bvh();
3287        world
3288    }
3289
3290    /// Returns the number of autonomous rigid-body NPC vehicles registered in this world.
3291    ///
3292    /// # Returns
3293    ///
3294    /// - `usize` - Active autonomous NPC vehicle count.
3295    #[must_use]
3296    pub fn traffic_vehicle_count(&self) -> usize {
3297        let Self {
3298            traffic_vehicles, ..
3299        } = self;
3300        traffic_vehicles.len()
3301    }
3302
3303    /// Returns the scene object index for dynamic NPC vehicle `slot`.
3304    ///
3305    /// # Arguments
3306    ///
3307    /// - `usize` - NPC traffic slot index.
3308    ///
3309    /// # Returns
3310    ///
3311    /// - `Option<usize>` - Owning object index in `World3D::objects`, if `slot` is valid.
3312    #[must_use]
3313    pub fn traffic_vehicle_object_index(&self, slot: usize) -> Option<usize> {
3314        let Self {
3315            traffic_vehicles, ..
3316        } = self;
3317        traffic_vehicles
3318            .get(slot)
3319            .map(NpcVehicle3D::get_object_index)
3320    }
3321
3322    /// Returns the live rigid-body horizontal velocity of NPC vehicle `slot` in meters per second.
3323    ///
3324    /// # Arguments
3325    ///
3326    /// - `usize` - NPC traffic slot index.
3327    ///
3328    /// # Returns
3329    ///
3330    /// - `Option<Vec3>` - World-space velocity vector in meters per second.
3331    #[must_use]
3332    pub fn traffic_vehicle_velocity(&self, slot: usize) -> Option<Vec3> {
3333        let Self {
3334            traffic_vehicles, ..
3335        } = self;
3336        traffic_vehicles.get(slot).map(NpcVehicle3D::get_vel)
3337    }
3338
3339    /// Returns the active angular spin rate of NPC vehicle `slot` in radians per second.
3340    ///
3341    /// # Arguments
3342    ///
3343    /// - `usize` - NPC traffic slot index.
3344    ///
3345    /// # Returns
3346    ///
3347    /// - `Option<f32>` - Yaw spin rate in radians per second.
3348    #[must_use]
3349    pub fn traffic_vehicle_yaw_rate(&self, slot: usize) -> Option<f32> {
3350        let Self {
3351            traffic_vehicles, ..
3352        } = self;
3353        traffic_vehicles.get(slot).map(NpcVehicle3D::get_yaw_rate)
3354    }
3355
3356    /// Returns whether NPC vehicle `slot` is operating in unrestricted off-road free-roam mode.
3357    ///
3358    /// # Arguments
3359    ///
3360    /// - `usize` - NPC traffic slot index.
3361    ///
3362    /// # Returns
3363    ///
3364    /// - `Option<bool>` - `true` when freely roaming off-road plazas and city grounds.
3365    #[must_use]
3366    pub fn traffic_vehicle_is_free_roam(&self, slot: usize) -> Option<bool> {
3367        let Self {
3368            traffic_vehicles, ..
3369        } = self;
3370        traffic_vehicles
3371            .get(slot)
3372            .map(NpcVehicle3D::get_free_roam_mode)
3373    }
3374
3375    /// Returns the player vehicle's live world-space horizontal velocity vector in meters per second.
3376    ///
3377    /// # Returns
3378    ///
3379    /// - `Vec3` - Player vehicle velocity `(vx, 0.0, vz)` in meters per second.
3380    #[must_use]
3381    pub fn player_velocity(&self) -> Vec3 {
3382        let Self { player_physics, .. } = self;
3383        player_physics.get_vel()
3384    }
3385
3386    /// Returns the player vehicle's signed longitudinal velocity along its facing direction in meters per second (negative while reversing).
3387    ///
3388    /// # Returns
3389    ///
3390    /// - `f32` - Signed forward velocity in meters per second.
3391    #[must_use]
3392    pub fn player_forward_speed_mps(&self) -> f32 {
3393        let Some(car_idx) = self.vehicle_index() else {
3394            return 0.0;
3395        };
3396        let Some(car_obj) = self.get_objects().get(car_idx) else {
3397            return 0.0;
3398        };
3399        let yaw_rad: f32 = car_obj.get_transform().get_yaw_rad();
3400        let forward_dir: Vec3 = Vec3::new(-yaw_rad.sin(), 0.0, -yaw_rad.cos());
3401        self.player_velocity().dot(forward_dir)
3402    }
3403
3404    /// Resets the player hero vehicle to the coastal boulevard starting grid with full nitro charge and cleared particle trails.
3405    ///
3406    /// # Returns
3407    ///
3408    /// - `bool` - `true` when the player vehicle existed and was reset cleanly.
3409    pub fn reset_player_vehicle(&mut self) -> bool {
3410        let Some(car_idx) = self.vehicle_index() else {
3411            return false;
3412        };
3413        let spawn_transform: Transform3D =
3414            Transform3D::new(Vec3::new(0.0, 0.0, 0.0), 0.0, Vec3::splat(1.1));
3415        if !self.teleport_object(car_idx, spawn_transform) {
3416            return false;
3417        }
3418        {
3419            let Self { player_physics, .. } = self;
3420            player_physics.set_boost_charge(1.0);
3421        }
3422        self.get_mut_niagara().clear();
3423        let mut reset_cam: Camera3D = self.get_camera();
3424        let eye_pos: Vec3 = Vec3::new(0.0, 4.25, 9.8);
3425        let look_target: Vec3 = Vec3::new(0.0, 2.40, -16.0);
3426        let look_dir: Vec3 = look_target.sub(eye_pos).normalize();
3427        reset_cam.set_position(eye_pos);
3428        reset_cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
3429        reset_cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
3430        reset_cam.set_fov_deg(CAMERA_BASE_FOV_DEG);
3431        self.set_camera(reset_cam);
3432        self.bump_world_revision();
3433        true
3434    }
3435
3436    /// Returns the player vehicle's live horizontal speed in meters per second.
3437    ///
3438    /// # Returns
3439    ///
3440    /// - `f32` - Horizontal speed magnitude in meters per second.
3441    #[must_use]
3442    pub fn player_speed_mps(&self) -> f32 {
3443        let v: Vec3 = self.player_velocity();
3444        (v.get_x() * v.get_x() + v.get_z() * v.get_z()).sqrt()
3445    }
3446
3447    /// Returns the player vehicle's live speed in kilometers per hour.
3448    ///
3449    /// # Returns
3450    ///
3451    /// - `f32` - Speed in kilometers per hour.
3452    #[must_use]
3453    pub fn player_speed_kmh(&self) -> f32 {
3454        self.player_speed_mps() * 3.6
3455    }
3456
3457    /// Returns the player vehicle's active yaw angular velocity in radians per second.
3458    ///
3459    /// # Returns
3460    ///
3461    /// - `f32` - Active yaw rate in radians per second.
3462    #[must_use]
3463    pub fn player_yaw_rate(&self) -> f32 {
3464        let Self { player_physics, .. } = self;
3465        player_physics.get_yaw_rate()
3466    }
3467
3468    /// Returns `true` when Shift nitro boost is currently delivering extra thrust.
3469    ///
3470    /// # Returns
3471    ///
3472    /// - `bool` - Whether nitro boost is active.
3473    #[must_use]
3474    pub fn player_boost_active(&self) -> bool {
3475        let Self { player_physics, .. } = self;
3476        player_physics.get_boost_active()
3477    }
3478
3479    /// Returns the player vehicle's normalized remaining nitro boost charge in `[0.0, 1.0]`.
3480    ///
3481    /// # Returns
3482    ///
3483    /// - `f32` - Normalized boost charge in `[0.0, 1.0]`.
3484    #[must_use]
3485    pub fn player_boost_charge(&self) -> f32 {
3486        let Self { player_physics, .. } = self;
3487        player_physics.get_boost_charge()
3488    }
3489
3490    /// Returns `true` when Space handbrake powerslide drift is currently active.
3491    ///
3492    /// # Returns
3493    ///
3494    /// - `bool` - Whether handbrake drift is active.
3495    #[must_use]
3496    pub fn player_drift_active(&self) -> bool {
3497        let Self { player_physics, .. } = self;
3498        player_physics.get_drift_active()
3499    }
3500
3501    /// Returns the player vehicle's signed lateral slip angle in radians.
3502    ///
3503    /// # Returns
3504    ///
3505    /// - `f32` - Signed lateral slip angle `atan2(v_lateral, |v_forward|)` in radians.
3506    #[must_use]
3507    pub fn player_drift_slip_angle_rad(&self) -> f32 {
3508        let Self { player_physics, .. } = self;
3509        player_physics.get_drift_slip_angle()
3510    }
3511
3512    /// Returns the player vehicle's visual lateral chassis body roll angle in radians.
3513    ///
3514    /// # Returns
3515    ///
3516    /// - `f32` - Body roll angle in radians.
3517    #[must_use]
3518    pub fn player_body_roll_rad(&self) -> f32 {
3519        let Self { player_physics, .. } = self;
3520        player_physics.get_body_roll_rad()
3521    }
3522
3523    /// Returns the player vehicle's visual longitudinal chassis pitch angle in radians.
3524    ///
3525    /// # Returns
3526    ///
3527    /// - `f32` - Body pitch angle in radians.
3528    #[must_use]
3529    pub fn player_body_pitch_rad(&self) -> f32 {
3530        let Self { player_physics, .. } = self;
3531        player_physics.get_body_pitch_rad()
3532    }
3533
3534    /// Returns the player chase camera's active dynamic FOV boost offset in degrees.
3535    ///
3536    /// # Returns
3537    ///
3538    /// - `f32` - Dynamic FOV boost offset in degrees.
3539    #[must_use]
3540    pub fn player_camera_fov_boost(&self) -> f32 {
3541        let Self { player_physics, .. } = self;
3542        player_physics.get_camera_fov_boost()
3543    }
3544
3545    /// Returns the player camera's active impact shake intensity in `[0.0, 1.0]`.
3546    ///
3547    /// # Returns
3548    ///
3549    /// - `f32` - Camera impact shake amplitude.
3550    #[must_use]
3551    pub fn player_camera_shake(&self) -> f32 {
3552        let Self { player_physics, .. } = self;
3553        player_physics.get_camera_shake()
3554    }
3555
3556    /// Applies an atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`), updating sun lighting and ambient Niagara rain streaks.
3557    ///
3558    /// # Arguments
3559    ///
3560    /// - `u8` - Atmosphere preset index (`0..=3`).
3561    ///
3562    /// # Returns
3563    ///
3564    /// - `f32` - Corresponding time-of-day hour in `[0.0, 24.0]`.
3565    pub fn apply_atmosphere_preset(&mut self, preset: u8) -> f32 {
3566        let clamped: u8 = preset.min(3);
3567        let hour: f32 = match clamped {
3568            1 => ATMOSPHERE_HOUR_RAINY_NIGHT,
3569            2 => ATMOSPHERE_HOUR_NOON,
3570            3 => ATMOSPHERE_HOUR_MIDNIGHT,
3571            _ => ATMOSPHERE_HOUR_SUNSET,
3572        };
3573        self.set_atmosphere_preset(clamped);
3574        let sun_light: DirectionalLight3D = match clamped {
3575            1 => DirectionalLight3D {
3576                direction: Vec3::new(-0.32, 0.48, -0.82).normalize(),
3577                color: Vec3::new(0.56, 0.78, 1.24),
3578                sky_zenith: Vec3::new(0.015, 0.038, 0.105),
3579                sky_horizon: Vec3::new(0.078, 0.155, 0.275),
3580                time_of_day: hour,
3581            },
3582            3 => DirectionalLight3D {
3583                direction: Vec3::new(-0.42, 0.62, -0.66).normalize(),
3584                color: Vec3::new(0.36, 0.34, 0.88),
3585                sky_zenith: Vec3::new(0.007, 0.005, 0.024),
3586                sky_horizon: Vec3::new(0.135, 0.036, 0.215),
3587                time_of_day: hour,
3588            },
3589            _ => DirectionalLight3D::from_time_of_day(hour),
3590        };
3591        self.set_sun(sun_light);
3592        if clamped == 1 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES {
3593            let cam_pos: Vec3 = self.get_camera().get_position();
3594            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
3595            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 4.5, -14.0)));
3596            rain_cfg.set_base_velocity(Vec3::new(-0.4, -17.0, 0.3));
3597            rain_cfg.set_velocity_spread(2.4);
3598            rain_cfg.set_start_color(Color::rgba(175, 222, 255, 165));
3599            rain_cfg.set_end_color(Color::rgba(92, 162, 235, 42));
3600            rain_cfg.set_start_size_m(0.042);
3601            rain_cfg.set_end_size_m(0.016);
3602            rain_cfg.set_min_lifetime(0.55);
3603            rain_cfg.set_max_lifetime(0.95);
3604            rain_cfg.set_emissive_boost(0.85);
3605            self.get_mut_niagara().emit_burst(8, &rain_cfg);
3606        }
3607        self.bump_world_revision();
3608        hour
3609    }
3610
3611    /// Registers a dynamic `PointLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
3612    ///
3613    /// # Arguments
3614    ///
3615    /// - `PointLight3D` - World-space point light descriptor.
3616    ///
3617    /// # Returns
3618    ///
3619    /// - `usize` - Assigned point light index.
3620    pub fn add_point_light(&mut self, light: PointLight3D) -> usize {
3621        let light_idx: usize = self.get_point_lights().len();
3622        self.get_mut_point_lights().push(light);
3623        self.bump_world_revision();
3624        light_idx
3625    }
3626
3627    /// Registers a dynamic `SpotLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
3628    ///
3629    /// # Arguments
3630    ///
3631    /// - `SpotLight3D` - World-space spotlight descriptor.
3632    ///
3633    /// # Returns
3634    ///
3635    /// - `usize` - Assigned spotlight index.
3636    pub fn add_spot_light(&mut self, light: SpotLight3D) -> usize {
3637        let light_idx: usize = self.get_spot_lights().len();
3638        self.get_mut_spot_lights().push(light);
3639        self.bump_world_revision();
3640        light_idx
3641    }
3642
3643    /// Clears all dynamic local point and spot lights from this world.
3644    pub fn clear_local_lights(&mut self) {
3645        self.get_mut_point_lights().clear();
3646        self.get_mut_spot_lights().clear();
3647        self.bump_world_revision();
3648    }
3649
3650    /// Emits `count` 3D particles into the world's `NiagaraSystem3D` with zero heap allocations.
3651    ///
3652    /// # Arguments
3653    ///
3654    /// - `&NiagaraEmitterConfig3D` - Emitter properties.
3655    /// - `usize` - Number of particles to emit.
3656    ///
3657    /// # Returns
3658    ///
3659    /// - `usize` - Active particle count after emission.
3660    pub fn emit_particles_3d(&mut self, config: &NiagaraEmitterConfig3D, count: usize) -> usize {
3661        self.get_mut_niagara().emit_burst(count, config);
3662        let active: usize = self.get_niagara().get_active_count();
3663        if count > 0 {
3664            self.bump_world_revision();
3665        }
3666        active
3667    }
3668
3669    /// Builds a dense UE5-scale multi-block cyberpunk metropolis with hundreds of occluding towers, local neon lights, and dynamic vehicles for scalability and occlusion benchmarking.
3670    ///
3671    /// # Arguments
3672    ///
3673    /// - `i32` - City block half-radius (`1..=5`, producing `(2r+1)x(2r+1)` multi-tower blocks).
3674    ///
3675    /// # Returns
3676    ///
3677    /// - `Self` - Populated dense 3D open-world metropolis with built static/dynamic BVHs.
3678    #[must_use]
3679    pub fn create_dense_open_world_city(blocks_radius: i32) -> Self {
3680        let radius: i32 = blocks_radius.clamp(1, 5);
3681        let mut world: Self = Self::create_open_world_city();
3682        let dense_occluder: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
3683            DENSE_TOWER_MESH_NAME,
3684            1.0,
3685            1.0,
3686            1.0,
3687            true,
3688            PbrMaterial::default(),
3689        )));
3690        let archetypes: [usize; 6] = world.register_building_archetypes();
3691        let facades: [PbrMaterial; 6] = Self::curated_skyline_palettes();
3692        let neon_palette: [Color; 4] = [
3693            Color::hex(0x38BDF8),
3694            Color::hex(0xF43F5E),
3695            Color::hex(0xA855F7),
3696            Color::hex(0x34D399),
3697        ];
3698        let mut serial: usize = 0;
3699        for bx in -radius..=radius {
3700            for bz in -radius..=radius {
3701                if bx == 0 && (-3..=3).contains(&bz) {
3702                    continue;
3703                }
3704                let center_x: f32 = (bx as f32) * 26.0;
3705                let center_z: f32 = (bz as f32) * 24.0 - 16.0;
3706                for sub in 0..4usize {
3707                    let off_x: f32 = if (sub & 1) == 0 { -5.5 } else { 5.5 };
3708                    let off_z: f32 = if (sub & 2) == 0 { -5.5 } else { 5.5 };
3709                    let px: f32 = center_x + off_x;
3710                    let pz: f32 = center_z + off_z;
3711                    let (d_spine, _): (f32, f32) = Self::loop_lateral_offset(px, pz);
3712                    if (49.0..=79.0).contains(&d_spine) || px > 134.0 {
3713                        continue;
3714                    }
3715                    let height_m: f32 = 16.0 + (((serial * 11 + sub * 7) % 6) as f32) * 8.0;
3716                    let width_m: f32 = 8.0 + ((serial % 3) as f32) * 1.4;
3717                    let mat: PbrMaterial = facades[serial % facades.len()];
3718                    let mesh_id: usize = if sub % 2 == 0 {
3719                        dense_occluder
3720                    } else {
3721                        archetypes[(serial + sub) % archetypes.len()]
3722                    };
3723                    let _: usize = world.spawn_object(
3724                        &format!("dense_bldg_{serial}"),
3725                        mesh_id,
3726                        Transform3D::new(
3727                            Vec3::new(px, 0.0, pz),
3728                            0.0,
3729                            Vec3::new(width_m, height_m, 9.0),
3730                        ),
3731                        mat,
3732                        true,
3733                    );
3734                    serial += 1;
3735                }
3736                if (bx + bz).abs() <= 2 && world.get_point_lights().len() < 32 {
3737                    let _: usize = world.add_point_light(PointLight3D::new(
3738                        Vec3::new(center_x, 7.0, center_z),
3739                        neon_palette[serial % neon_palette.len()],
3740                        4.5,
3741                        22.0,
3742                    ));
3743                }
3744            }
3745        }
3746        world.ensure_bvh();
3747        world
3748    }
3749
3750    /// Cycles the active 3D camera perspective (`Chase` -> `Hood` -> `Orbit` -> `Aerial`) safely without clipping.
3751    ///
3752    /// # Arguments
3753    ///
3754    /// - `&Self` - Mutable world.
3755    ///
3756    /// # Returns
3757    ///
3758    /// - `u8` - New active camera mode index.
3759    pub fn cycle_camera_mode(&mut self) -> u8 {
3760        let next: u8 = (self.get_camera_mode() + 1) % 4;
3761        self.set_camera_mode(next);
3762        next
3763    }
3764
3765    /// Computes horizontal playable world bounds from non-solid ground meshes when present, preventing hardcoded invisible walls.
3766    ///
3767    /// # Arguments
3768    ///
3769    /// - `&Self` - World reference.
3770    ///
3771    /// # Returns
3772    ///
3773    /// - `Option<(f32, f32, f32, f32)>` - `(min_x, max_x, min_z, max_z)` horizontal ground limits.
3774    #[must_use]
3775    pub fn ground_play_bounds(&self) -> Option<(f32, f32, f32, f32)> {
3776        let mut found: bool = false;
3777        let mut min_x: f32 = f32::INFINITY;
3778        let mut max_x: f32 = f32::NEG_INFINITY;
3779        let mut min_z: f32 = f32::INFINITY;
3780        let mut max_z: f32 = f32::NEG_INFINITY;
3781        for obj in self.get_objects().iter() {
3782            if obj.get_ray_trace_caster()
3783                || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater
3784            {
3785                continue;
3786            }
3787            let blue_val: AxisAlignedBox3D = obj.get_world_bounds();
3788            let span_x: f32 = blue_val.get_max().get_x() - blue_val.get_min().get_x();
3789            let span_z: f32 = blue_val.get_max().get_z() - blue_val.get_min().get_z();
3790            if span_x >= 16.0 && span_z >= 16.0 {
3791                min_x = min_x.min(blue_val.get_min().get_x());
3792                max_x = max_x.max(blue_val.get_max().get_x());
3793                min_z = min_z.min(blue_val.get_min().get_z());
3794                max_z = max_z.max(blue_val.get_max().get_z());
3795                found = true;
3796            }
3797        }
3798        if found {
3799            Some((min_x, max_x, min_z, max_z))
3800        } else {
3801            None
3802        }
3803    }
3804
3805    /// Tests a world-space `OrientedBox3D` against every solid (`solid_collider || ray_trace_caster`) model's real mesh triangles and closed solid interiors (excluding `ignore_idx`), returning the deepest penetration hit.
3806    ///
3807    /// # Arguments
3808    ///
3809    /// - `&Self` - World reference.
3810    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
3811    /// - `Option<usize>` - Optional scene object index to exclude (self).
3812    ///
3813    /// # Returns
3814    ///
3815    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh triangle or closed-volume collision contact, or `None` when clear.
3816    #[must_use]
3817    pub fn mesh_oriented_box_collision(
3818        &self,
3819        candidate: OrientedBox3D,
3820        ignore_idx: Option<usize>,
3821    ) -> Option<MeshCollisionHit3D> {
3822        let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
3823        let mut deepest: Option<MeshCollisionHit3D> = None;
3824        let objects: &[SceneObject3D] = self.get_objects().as_slice();
3825        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
3826        for (idx, obj) in objects.iter().enumerate() {
3827            if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
3828            {
3829                continue;
3830            }
3831            let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
3832            if !Self::boxes_overlap(query_bounds, obj_bounds) {
3833                continue;
3834            }
3835            let Some(mesh) = mesh_lib
3836                .get(obj.get_mesh_id())
3837                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
3838            else {
3839                continue;
3840            };
3841            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
3842            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
3843            let obj_tr: Transform3D = obj.get_transform();
3844            let model_mat: Mat4 = obj_tr.to_mat4();
3845            let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
3846            let mut hit_this_obj: bool = false;
3847            if meshlets.is_empty() {
3848                for tri in indices.iter() {
3849                    let (i0, i1, i2): (usize, usize, usize) =
3850                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3851                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3852                        let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3853                        let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3854                        let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3855                        if let Some((normal, pen, contact)) =
3856                            candidate.intersect_triangle_world(w0, w1, w2)
3857                        {
3858                            hit_this_obj = true;
3859                            let replace: bool = deepest
3860                                .map(|delta_val: MeshCollisionHit3D| {
3861                                    pen > delta_val.get_penetration()
3862                                })
3863                                .unwrap_or(true);
3864                            if replace {
3865                                deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
3866                            }
3867                        }
3868                    }
3869                }
3870            } else {
3871                for ml in meshlets.iter() {
3872                    let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
3873                    if !Self::boxes_overlap(query_bounds, ml_bounds) {
3874                        continue;
3875                    }
3876                    let start: usize = ml.get_first_tri() as usize;
3877                    let end: usize = start
3878                        .saturating_add(ml.get_tri_count() as usize)
3879                        .min(indices.len());
3880                    for tri in indices[start..end].iter() {
3881                        let (i0, i1, i2): (usize, usize, usize) =
3882                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3883                        if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3884                            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3885                            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3886                            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3887                            if let Some((normal, pen, contact)) =
3888                                candidate.intersect_triangle_world(w0, w1, w2)
3889                            {
3890                                hit_this_obj = true;
3891                                let replace: bool = deepest
3892                                    .map(|distance_val: MeshCollisionHit3D| {
3893                                        pen > distance_val.get_penetration()
3894                                    })
3895                                    .unwrap_or(true);
3896                                if replace {
3897                                    deepest =
3898                                        Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
3899                                }
3900                            }
3901                        }
3902                    }
3903                }
3904            }
3905            if !hit_this_obj
3906                && mesh.get_is_closed()
3907                && Self::point_in_bounds(candidate.get_center(), obj_bounds)
3908                && let Some(inside_hit) =
3909                    Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
3910            {
3911                let replace: bool = deepest
3912                    .map(|prev_hit: MeshCollisionHit3D| {
3913                        inside_hit.get_penetration() > prev_hit.get_penetration()
3914                    })
3915                    .unwrap_or(true);
3916                if replace {
3917                    deepest = Some(inside_hit);
3918                }
3919            }
3920        }
3921        deepest
3922    }
3923
3924    /// Tests whether a world-space point lies strictly inside an axis-aligned bounding box.
3925    ///
3926    /// # Arguments
3927    ///
3928    /// - `Vec3` - Query point in world space.
3929    /// - `AxisAlignedBox3D` - World-space axis-aligned bounding box.
3930    ///
3931    /// # Returns
3932    ///
3933    /// - `bool` - `true` when the point lies inside the bounding box on all three axes.
3934    #[inline]
3935    #[must_use]
3936    fn point_in_bounds(point: Vec3, bounds: AxisAlignedBox3D) -> bool {
3937        let bmin: Vec3 = bounds.get_min();
3938        let bmax: Vec3 = bounds.get_max();
3939        point.get_x() >= bmin.get_x()
3940            && point.get_x() <= bmax.get_x()
3941            && point.get_y() >= bmin.get_y()
3942            && point.get_y() <= bmax.get_y()
3943            && point.get_z() >= bmin.get_z()
3944            && point.get_z() <= bmax.get_z()
3945    }
3946
3947    /// Computes the exact closest point on a 3D triangle `(v0, v1, v2)` to query point `point`.
3948    ///
3949    /// # Arguments
3950    ///
3951    /// - `Vec3` - Query point in world space.
3952    /// - `Vec3` - Triangle vertex 0.
3953    /// - `Vec3` - Triangle vertex 1.
3954    /// - `Vec3` - Triangle vertex 2.
3955    ///
3956    /// # Returns
3957    ///
3958    /// - `Vec3` - Closest point lying on or inside the triangle.
3959    #[inline]
3960    #[must_use]
3961    fn closest_point_on_triangle(point: Vec3, v0: Vec3, v1: Vec3, v2: Vec3) -> Vec3 {
3962        let ab: Vec3 = v1.sub(v0);
3963        let ac: Vec3 = v2.sub(v0);
3964        let ap: Vec3 = point.sub(v0);
3965        let d1: f32 = ab.dot(ap);
3966        let d2: f32 = ac.dot(ap);
3967        if d1 <= 0.0 && d2 <= 0.0 {
3968            return v0;
3969        }
3970        let bp: Vec3 = point.sub(v1);
3971        let d3: f32 = ab.dot(bp);
3972        let d4: f32 = ac.dot(bp);
3973        if d3 >= 0.0 && d4 <= d3 {
3974            return v1;
3975        }
3976        let vc: f32 = d1 * d4 - d3 * d2;
3977        if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
3978            let weight_v: f32 = d1 / (d1 - d3).max(1.0e-7);
3979            return v0.add(ab.scale(weight_v));
3980        }
3981        let cp: Vec3 = point.sub(v2);
3982        let d5: f32 = ab.dot(cp);
3983        let d6: f32 = ac.dot(cp);
3984        if d6 >= 0.0 && d5 <= d6 {
3985            return v2;
3986        }
3987        let vb: f32 = d5 * d2 - d1 * d6;
3988        if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
3989            let weight_w: f32 = d2 / (d2 - d6).max(1.0e-7);
3990            return v0.add(ac.scale(weight_w));
3991        }
3992        let va: f32 = d3 * d6 - d5 * d4;
3993        if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
3994            let denom_bc: f32 = ((d4 - d3) + (d5 - d6)).max(1.0e-7);
3995            let weight_w: f32 = (d4 - d3) / denom_bc;
3996            return v1.add(v2.sub(v1).scale(weight_w));
3997        }
3998        let denom: f32 = (va + vb + vc).max(1.0e-7);
3999        let weight_v: f32 = vb / denom;
4000        let weight_w: f32 = vc / denom;
4001        v0.add(ab.scale(weight_v)).add(ac.scale(weight_w))
4002    }
4003
4004    /// Detects whether an `OrientedBox3D` lies strictly inside a closed solid triangle mesh using odd-even ray parity and returns an outward MTV pushing the box out through the nearest exterior wall.
4005    ///
4006    /// # Arguments
4007    ///
4008    /// - `usize` - Solid scene object index in `World3D::objects`.
4009    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
4010    /// - `&[Vertex3D]` - Local mesh vertex buffer.
4011    /// - `&[[u32; 3]]` - Local mesh triangle index buffer.
4012    /// - `Mat4` - World model transform matrix of the solid mesh.
4013    ///
4014    /// # Returns
4015    ///
4016    /// - `Option<MeshCollisionHit3D>` - Outward minimum-translation-vector hit when strictly inside the closed solid, or `None` when outside (e.g. open archway tunnels).
4017    #[must_use]
4018    fn point_inside_closed_mesh_mtv(
4019        obj_idx: usize,
4020        candidate: OrientedBox3D,
4021        verts: &[Vertex3D],
4022        indices: &[[u32; 3]],
4023        model_mat: Mat4,
4024    ) -> Option<MeshCollisionHit3D> {
4025        let center: Vec3 = candidate.get_center();
4026        let parity_dir: Vec3 = Vec3::new(1.0, 1.37e-4, 2.71e-4).normalize();
4027        let mut crossings: u32 = 0;
4028        let mut best_horiz_dist_sq: f32 = f32::INFINITY;
4029        let mut best_horiz_cp: Vec3 = center;
4030        let mut best_horiz_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
4031        let mut best_any_dist_sq: f32 = f32::INFINITY;
4032        let mut best_any_cp: Vec3 = center;
4033        let mut best_any_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
4034        for tri in indices.iter() {
4035            let (i0, i1, i2): (usize, usize, usize) =
4036                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4037            if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
4038                continue;
4039            }
4040            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4041            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4042            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4043            if Self::ray_intersect_triangle(center, parity_dir, w0, w1, w2, 1.0e-5, f32::INFINITY)
4044                .is_some()
4045            {
4046                crossings = crossings.wrapping_add(1);
4047            }
4048            let cp: Vec3 = Self::closest_point_on_triangle(center, w0, w1, w2);
4049            let delta: Vec3 = cp.sub(center);
4050            let dist_sq: f32 = delta.length_sq();
4051            let raw_face_n: Vec3 = w1.sub(w0).cross(w2.sub(w0));
4052            let face_n: Vec3 = if raw_face_n.length_sq() > 1.0e-10 {
4053                raw_face_n.normalize()
4054            } else {
4055                Vec3::new(1.0, 0.0, 0.0)
4056            };
4057            if dist_sq < best_any_dist_sq {
4058                best_any_dist_sq = dist_sq;
4059                best_any_cp = cp;
4060                best_any_n = face_n;
4061            }
4062            let horiz_mag_sq: f32 =
4063                face_n.get_x() * face_n.get_x() + face_n.get_z() * face_n.get_z();
4064            if horiz_mag_sq > 0.25 && dist_sq < best_horiz_dist_sq {
4065                best_horiz_dist_sq = dist_sq;
4066                best_horiz_cp = cp;
4067                best_horiz_n = Vec3::new(face_n.get_x(), 0.0, face_n.get_z()).normalize();
4068            }
4069        }
4070        if (crossings & 1) == 0 {
4071            return None;
4072        }
4073        let (target_cp, fallback_n, target_dist_sq): (Vec3, Vec3, f32) =
4074            if best_horiz_dist_sq.is_finite() {
4075                (best_horiz_cp, best_horiz_n, best_horiz_dist_sq)
4076            } else if best_any_dist_sq.is_finite() {
4077                (best_any_cp, best_any_n, best_any_dist_sq)
4078            } else {
4079                return None;
4080            };
4081        let push_raw: Vec3 = target_cp.sub(center);
4082        let push_n: Vec3 = if push_raw.length_sq() > 1.0e-8 {
4083            push_raw.normalize()
4084        } else {
4085            fallback_n
4086        };
4087        let axes: [Vec3; 3] = candidate.get_axes();
4088        let half_extents: Vec3 = candidate.get_half_extents();
4089        let obb_proj: f32 = axes[0].dot(push_n).abs() * half_extents.get_x()
4090            + axes[1].dot(push_n).abs() * half_extents.get_y()
4091            + axes[2].dot(push_n).abs() * half_extents.get_z();
4092        let total_pen: f32 = target_dist_sq.sqrt() + obb_proj;
4093        Some(MeshCollisionHit3D::new(
4094            obj_idx, push_n, total_pen, target_cp,
4095        ))
4096    }
4097
4098    /// Resolves a unit horizontal separation normal against `obj_idx` so wall sliding and MTV push-out stay smooth even when contacting low curbs or seawalls whose top caps overlap vertically.
4099    ///
4100    /// # Arguments
4101    ///
4102    /// - `&Self` - World reference.
4103    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
4104    /// - `usize` - Colliding solid scene object index.
4105    ///
4106    /// # Returns
4107    ///
4108    /// - `Vec3` - Unit horizontal outward separation normal in the XZ plane, or `Vec3::zero()` if degenerate.
4109    #[must_use]
4110    fn horizontal_collision_normal(&self, candidate: OrientedBox3D, obj_idx: usize) -> Vec3 {
4111        let Some(obj) = self.get_objects().get(obj_idx) else {
4112            return Vec3::zero();
4113        };
4114        if let Some(mesh) = self
4115            .get_mesh_library()
4116            .get(obj.get_mesh_id())
4117            .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4118        {
4119            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4120            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
4121            let model_mat: Mat4 = obj.get_transform().to_mat4();
4122            let mut best_pen: f32 = f32::INFINITY;
4123            let mut best_hn: Vec3 = Vec3::zero();
4124            for tri in indices.iter() {
4125                let (i0, i1, i2): (usize, usize, usize) =
4126                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4127                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4128                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4129                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4130                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4131                    if let Some((normal, pen, _)) = candidate.intersect_triangle_world(w0, w1, w2) {
4132                        let hn: Vec3 = Vec3::new(normal.get_x(), 0.0, normal.get_z());
4133                        if hn.length_sq() > 0.25 && pen < best_pen {
4134                            best_pen = pen;
4135                            best_hn = hn.normalize();
4136                        }
4137                    }
4138                }
4139            }
4140            if best_hn.length_sq() > 1.0e-6 {
4141                return best_hn;
4142            }
4143        }
4144        let bounds: AxisAlignedBox3D = obj.get_world_bounds();
4145        let bcenter: Vec3 = bounds.get_min().add(bounds.get_max()).scale(0.5);
4146        let diff: Vec3 = candidate.get_center().sub(bcenter);
4147        let horiz: Vec3 = Vec3::new(diff.get_x(), 0.0, diff.get_z());
4148        if horiz.length_sq() > 1.0e-6 {
4149            horiz.normalize()
4150        } else {
4151            Vec3::new(1.0, 0.0, 0.0)
4152        }
4153    }
4154
4155    /// Clamps a horizontal world position to playable island ground limits when present.
4156    ///
4157    /// # Arguments
4158    ///
4159    /// - `Vec3` - Candidate world position.
4160    /// - `Option<(f32, f32, f32, f32)>` - Optional playable horizontal `(min_x, max_x, min_z, max_z)` bounds.
4161    /// - `f32` - Vehicle horizontal margin in meters.
4162    ///
4163    /// # Returns
4164    ///
4165    /// - `Vec3` - Ground-clamped world position.
4166    #[inline]
4167    #[must_use]
4168    fn clamp_horizontal_to_ground(
4169        mut pos: Vec3,
4170        ground_limits: Option<(f32, f32, f32, f32)>,
4171        ground_margin: f32,
4172    ) -> Vec3 {
4173        if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
4174            let lo_x: f32 = (gx0 + ground_margin).min(gx1);
4175            let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
4176            let lo_z: f32 = (gz0 + ground_margin).min(gz1);
4177            let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
4178            pos.set_x(pos.get_x().clamp(lo_x, hi_x));
4179            pos.set_z(pos.get_z().clamp(lo_z, hi_z));
4180        }
4181        pos
4182    }
4183
4184    /// Iteratively pushes a penetrating vehicle horizontally out of solid obstacles along the minimum-translation-vector normal until collision-free.
4185    ///
4186    /// # Arguments
4187    ///
4188    /// - `&Self` - World reference.
4189    /// - `&mut Transform3D` - Candidate vehicle transform adjusted in place when penetrating.
4190    /// - `AxisAlignedBox3D` - Vehicle local mesh bounds.
4191    /// - `usize` - Vehicle object index to ignore during self-test.
4192    /// - `Option<(f32, f32, f32, f32)>` - Optional playable ground bounds.
4193    /// - `f32` - Horizontal ground margin in meters.
4194    ///
4195    /// # Returns
4196    ///
4197    /// - `bool` - `true` when the transform was moved to resolve penetration.
4198    fn depenetrate_vehicle_horizontally(
4199        &self,
4200        transform_val: &mut Transform3D,
4201        mesh_bounds: AxisAlignedBox3D,
4202        vehicle_idx: usize,
4203        ground_limits: Option<(f32, f32, f32, f32)>,
4204        ground_margin: f32,
4205    ) -> bool {
4206        let mut adjusted: bool = false;
4207        for _ in 0..COLLISION_MTV_MAX_ITERS {
4208            let Some(hit) = self.collides_with_obstacles(*transform_val, mesh_bounds, vehicle_idx)
4209            else {
4210                break;
4211            };
4212            let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
4213            let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
4214                raw_hn.normalize()
4215            } else {
4216                self.horizontal_collision_normal(
4217                    transform_val.to_oriented_box(mesh_bounds),
4218                    hit.get_object_index(),
4219                )
4220            };
4221            if hn.length_sq() <= 1.0e-6 {
4222                break;
4223            }
4224            let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
4225            let cur_pos: Vec3 = transform_val.get_position();
4226            let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
4227                Vec3::new(
4228                    cur_pos.get_x() + hn.get_x() * push_dist,
4229                    cur_pos.get_y(),
4230                    cur_pos.get_z() + hn.get_z() * push_dist,
4231                ),
4232                ground_limits,
4233                ground_margin,
4234            );
4235            transform_val.set_position(pushed_pos);
4236            adjusted = true;
4237        }
4238        adjusted
4239    }
4240
4241    /// Casts a world-space ray against every solid (`ray_trace_caster == true`) model's real mesh triangles (excluding `ignore_idx`) up to `max_dist`.
4242    ///
4243    /// # Arguments
4244    ///
4245    /// - `&Self` - World reference.
4246    /// - `Vec3` - Ray origin in world space.
4247    /// - `Vec3` - Unit ray direction in world space.
4248    /// - `f32` - Maximum ray distance.
4249    /// - `Option<usize>` - Optional scene object index to exclude.
4250    ///
4251    /// # Returns
4252    ///
4253    /// - `Option<RayHit3D>` - Closest real-mesh triangle intersection within `(1e-4, max_dist]`.
4254    #[must_use]
4255    pub fn raycast_solid_meshes(
4256        &self,
4257        origin: Vec3,
4258        direction: Vec3,
4259        max_dist: f32,
4260        ignore_idx: Option<usize>,
4261    ) -> Option<RayHit3D> {
4262        let dir: Vec3 = direction.normalize();
4263        let inv_dir: Vec3 = Ray3D::safe_inv_vec(dir);
4264        let t_min: f32 = 1e-4;
4265        let mut best_t: f32 = max_dist;
4266        let mut best_hit: Option<RayHit3D> = None;
4267        let objects: &[SceneObject3D] = self.get_objects().as_slice();
4268        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
4269        let ignore_is_static_caster: bool = ignore_idx
4270            .and_then(|idx: usize| objects.get(idx))
4271            .is_some_and(|obj: &SceneObject3D| obj.get_ray_trace_caster() && !obj.get_is_dynamic());
4272        let use_static_bvh: bool =
4273            !self.get_bvh_dirty() && !self.get_bvh().is_empty() && !ignore_is_static_caster;
4274        if use_static_bvh
4275            && let Some((hit_dist, tri_idx)) = self
4276                .get_bvh()
4277                .trace_closest_raw(origin, dir, inv_dir, t_min, best_t)
4278        {
4279            let bvh_tris: &[BvhTriangle] = self.get_bvh().get_triangles().as_slice();
4280            if let Some(hit_tri) = bvh_tris.get(tri_idx) {
4281                let raw_normal: Vec3 = hit_tri.get_normal();
4282                let oriented_normal: Vec3 = if raw_normal.dot(dir) > 0.0 {
4283                    raw_normal.scale(-1.0)
4284                } else {
4285                    raw_normal
4286                };
4287                best_t = hit_dist;
4288                best_hit = Some(RayHit3D {
4289                    distance: hit_dist,
4290                    point: origin.add(dir.scale(hit_dist)),
4291                    normal: oriented_normal,
4292                    material: hit_tri.get_material(),
4293                });
4294            }
4295        }
4296        for (idx, obj) in objects.iter().enumerate() {
4297            if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
4298            {
4299                continue;
4300            }
4301            if use_static_bvh && obj.get_ray_trace_caster() && !obj.get_is_dynamic() {
4302                continue;
4303            }
4304            if !obj
4305                .get_world_bounds()
4306                .intersect_ray_near(origin, inv_dir, t_min, best_t)
4307                .is_finite()
4308            {
4309                continue;
4310            }
4311            let Some(mesh) = mesh_lib
4312                .get(obj.get_mesh_id())
4313                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
4314            else {
4315                continue;
4316            };
4317            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4318            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
4319            let model_mat: Mat4 = obj.get_transform().to_mat4();
4320            let mat: PbrMaterial = obj.get_material();
4321            for tri in indices.iter() {
4322                let (i0, i1, i2): (usize, usize, usize) =
4323                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4324                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4325                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4326                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4327                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4328                    if let Some((blend_factor, normal)) =
4329                        Self::ray_intersect_triangle(origin, dir, w0, w1, w2, t_min, best_t)
4330                    {
4331                        best_t = blend_factor;
4332                        best_hit = Some(RayHit3D {
4333                            distance: blend_factor,
4334                            point: origin.add(dir.scale(blend_factor)),
4335                            normal,
4336                            material: mat,
4337                        });
4338                    }
4339                }
4340            }
4341        }
4342        best_hit
4343    }
4344
4345    /// Tests whether two world-space `AxisAlignedBox3D` boxes overlap strictly.
4346    ///
4347    /// # Arguments
4348    ///
4349    /// - `AxisAlignedBox3D` - First bounding box.
4350    /// - `AxisAlignedBox3D` - Second bounding box.
4351    ///
4352    /// # Returns
4353    ///
4354    /// - `bool` - `true` when both axis-aligned bounding boxes overlap on all three axes.
4355    #[inline]
4356    #[must_use]
4357    fn boxes_overlap(alpha_val: AxisAlignedBox3D, blue_val: AxisAlignedBox3D) -> bool {
4358        let ox: bool = alpha_val.get_min().get_x() < blue_val.get_max().get_x()
4359            && alpha_val.get_max().get_x() > blue_val.get_min().get_x();
4360        let oy: bool = alpha_val.get_min().get_y() < blue_val.get_max().get_y()
4361            && alpha_val.get_max().get_y() > blue_val.get_min().get_y();
4362        let oz: bool = alpha_val.get_min().get_z() < blue_val.get_max().get_z()
4363            && alpha_val.get_max().get_z() > blue_val.get_min().get_z();
4364        ox && oy && oz
4365    }
4366
4367    /// Double-sided Möller-Trumbore ray-triangle intersection returning `(t, outward_unit_normal)`.
4368    ///
4369    /// # Arguments
4370    ///
4371    /// - `Vec3` - Ray origin.
4372    /// - `Vec3` - Unit ray direction.
4373    /// - `Vec3` - Triangle vertex 0.
4374    /// - `Vec3` - Triangle vertex 1.
4375    /// - `Vec3` - Triangle vertex 2.
4376    /// - `f32` - Minimum ray parameter `t`.
4377    /// - `f32` - Maximum ray parameter `t`.
4378    ///
4379    /// # Returns
4380    ///
4381    /// - `Option<(f32, Vec3)>` - Hit distance and facing unit normal.
4382    #[inline]
4383    #[must_use]
4384    fn ray_intersect_triangle(
4385        origin: Vec3,
4386        dir: Vec3,
4387        v0: Vec3,
4388        v1: Vec3,
4389        v2: Vec3,
4390        t_min: f32,
4391        t_max: f32,
4392    ) -> Option<(f32, Vec3)> {
4393        let e1: Vec3 = v1.sub(v0);
4394        let e2: Vec3 = v2.sub(v0);
4395        let pvec: Vec3 = dir.cross(e2);
4396        let det: f32 = e1.dot(pvec);
4397        if det.abs() < 1e-7 {
4398            return None;
4399        }
4400        let inv_det: f32 = 1.0 / det;
4401        let tvec: Vec3 = origin.sub(v0);
4402        let tex_u: f32 = tvec.dot(pvec) * inv_det;
4403        if !(0.0..=1.0).contains(&tex_u) {
4404            return None;
4405        }
4406        let qvec: Vec3 = tvec.cross(e1);
4407        let item_val: f32 = dir.dot(qvec) * inv_det;
4408        if item_val < 0.0 || tex_u + item_val > 1.0 {
4409            return None;
4410        }
4411        let blend_factor: f32 = e2.dot(qvec) * inv_det;
4412        if blend_factor <= t_min || blend_factor > t_max {
4413            return None;
4414        }
4415        let raw_n: Vec3 = e1.cross(e2).normalize();
4416        let normal: Vec3 = if raw_n.dot(dir) > 0.0 {
4417            raw_n.scale(-1.0)
4418        } else {
4419            raw_n
4420        };
4421        Some((blend_factor, normal))
4422    }
4423
4424    /// Tests whether a candidate transformed mesh collides with any solid obstacle's real triangles excluding `ignore_idx`.
4425    ///
4426    /// # Arguments
4427    ///
4428    /// - `&Self` - World reference.
4429    /// - `Transform3D` - Candidate object transform.
4430    /// - `AxisAlignedBox3D` - Candidate local mesh bounds.
4431    /// - `usize` - Self object index to skip.
4432    ///
4433    /// # Returns
4434    ///
4435    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh collision hit, or `None` when clear.
4436    #[must_use]
4437    fn collides_with_obstacles(
4438        &self,
4439        candidate_tr: Transform3D,
4440        local_bounds: AxisAlignedBox3D,
4441        ignore_idx: usize,
4442    ) -> Option<MeshCollisionHit3D> {
4443        let oriented_box: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
4444        self.mesh_oriented_box_collision(oriented_box, Some(ignore_idx))
4445    }
4446
4447    /// Tests a world-space `OrientedBox3D` against every static solid (`!is_dynamic && (solid_collider || ray_trace_caster)`) obstacle mesh, returning the deepest penetration contact.
4448    ///
4449    /// # Arguments
4450    ///
4451    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
4452    /// - `Option<usize>` - Optional scene object index to exclude.
4453    ///
4454    /// # Returns
4455    ///
4456    /// - `Option<MeshCollisionHit3D>` - Deepest static-world collision hit, or `None` when clear.
4457    #[must_use]
4458    fn mesh_oriented_box_static_collision(
4459        &self,
4460        candidate: OrientedBox3D,
4461        ignore_idx: Option<usize>,
4462    ) -> Option<MeshCollisionHit3D> {
4463        let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
4464        let mut deepest: Option<MeshCollisionHit3D> = None;
4465        let objects: &[SceneObject3D] = self.get_objects().as_slice();
4466        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
4467        for (idx, obj) in objects.iter().enumerate() {
4468            let is_solid: bool = obj.get_solid_collider() || obj.get_ray_trace_caster();
4469            if ignore_idx == Some(idx) || obj.get_is_dynamic() || !is_solid {
4470                continue;
4471            }
4472            let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
4473            if !Self::boxes_overlap(query_bounds, obj_bounds) {
4474                continue;
4475            }
4476            let Some(mesh) = mesh_lib
4477                .get(obj.get_mesh_id())
4478                .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4479            else {
4480                continue;
4481            };
4482            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
4483            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
4484            let model_mat: Mat4 = obj.get_transform().to_mat4();
4485            let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
4486            let mut hit_this_obj: bool = false;
4487            if meshlets.is_empty() {
4488                for tri in indices.iter() {
4489                    let (i0, i1, i2): (usize, usize, usize) =
4490                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4491                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4492                        let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4493                        let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4494                        let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4495                        if let Some((normal, pen, contact)) =
4496                            candidate.intersect_triangle_world(w0, w1, w2)
4497                        {
4498                            hit_this_obj = true;
4499                            let replace: bool = deepest
4500                                .map(|prev: MeshCollisionHit3D| pen > prev.get_penetration())
4501                                .unwrap_or(true);
4502                            if replace {
4503                                deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
4504                            }
4505                        }
4506                    }
4507                }
4508            } else {
4509                for ml in meshlets.iter() {
4510                    let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
4511                    if !Self::boxes_overlap(query_bounds, ml_bounds) {
4512                        continue;
4513                    }
4514                    let start: usize = ml.get_first_tri() as usize;
4515                    let end: usize = start
4516                        .saturating_add(ml.get_tri_count() as usize)
4517                        .min(indices.len());
4518                    for tri in indices[start..end].iter() {
4519                        let (i0, i1, i2): (usize, usize, usize) =
4520                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
4521                        if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
4522                            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
4523                            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
4524                            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
4525                            if let Some((normal, pen, contact)) =
4526                                candidate.intersect_triangle_world(w0, w1, w2)
4527                            {
4528                                hit_this_obj = true;
4529                                let replace: bool = deepest
4530                                    .map(|prev: MeshCollisionHit3D| pen > prev.get_penetration())
4531                                    .unwrap_or(true);
4532                                if replace {
4533                                    deepest =
4534                                        Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
4535                                }
4536                            }
4537                        }
4538                    }
4539                }
4540            }
4541            if !hit_this_obj
4542                && mesh.get_is_closed()
4543                && Self::point_in_bounds(candidate.get_center(), obj_bounds)
4544                && let Some(inside_hit) =
4545                    Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
4546            {
4547                let replace: bool = deepest
4548                    .map(|prev: MeshCollisionHit3D| {
4549                        inside_hit.get_penetration() > prev.get_penetration()
4550                    })
4551                    .unwrap_or(true);
4552                if replace {
4553                    deepest = Some(inside_hit);
4554                }
4555            }
4556        }
4557        deepest
4558    }
4559
4560    /// Iteratively pushes a penetrating vehicle horizontally out of static world obstacles along the minimum-translation-vector normal.
4561    ///
4562    /// # Arguments
4563    ///
4564    /// - `&mut Transform3D` - Candidate vehicle transform adjusted in place when penetrating.
4565    /// - `AxisAlignedBox3D` - Vehicle local mesh bounds.
4566    /// - `usize` - Vehicle object index to ignore.
4567    /// - `Option<(f32, f32, f32, f32)>` - Optional playable horizontal ground bounds.
4568    /// - `f32` - Horizontal ground margin in meters.
4569    ///
4570    /// # Returns
4571    ///
4572    /// - `bool` - `true` when the transform was moved to clear static penetration.
4573    fn depenetrate_vehicle_static_horizontally(
4574        &self,
4575        transform_val: &mut Transform3D,
4576        mesh_bounds: AxisAlignedBox3D,
4577        vehicle_idx: usize,
4578        ground_limits: Option<(f32, f32, f32, f32)>,
4579        ground_margin: f32,
4580    ) -> bool {
4581        let mut adjusted: bool = false;
4582        for _ in 0..COLLISION_MTV_MAX_ITERS {
4583            let Some(hit) = self.mesh_oriented_box_static_collision(
4584                transform_val.to_oriented_box(mesh_bounds),
4585                Some(vehicle_idx),
4586            ) else {
4587                break;
4588            };
4589            let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
4590            let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
4591                raw_hn.normalize()
4592            } else {
4593                self.horizontal_collision_normal(
4594                    transform_val.to_oriented_box(mesh_bounds),
4595                    hit.get_object_index(),
4596                )
4597            };
4598            if hn.length_sq() <= 1.0e-6 {
4599                break;
4600            }
4601            let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
4602            let cur_pos: Vec3 = transform_val.get_position();
4603            let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
4604                Vec3::new(
4605                    cur_pos.get_x() + hn.get_x() * push_dist,
4606                    cur_pos.get_y(),
4607                    cur_pos.get_z() + hn.get_z() * push_dist,
4608                ),
4609                ground_limits,
4610                ground_margin,
4611            );
4612            transform_val.set_position(pushed_pos);
4613            adjusted = true;
4614        }
4615        adjusted
4616    }
4617
4618    /// Wraps an angle in radians into `(-PI, PI]`.
4619    ///
4620    /// # Arguments
4621    ///
4622    /// - `f32` - Unwrapped angle in radians.
4623    ///
4624    /// # Returns
4625    ///
4626    /// - `f32` - Shortest signed equivalent angle in `(-PI, PI]`.
4627    #[inline]
4628    #[must_use]
4629    fn wrap_angle_rad(angle: f32) -> f32 {
4630        let two_pi: f32 = 2.0 * PI;
4631        let wrapped: f32 = (angle + PI).rem_euclid(two_pi) - PI;
4632        if wrapped <= -PI {
4633            wrapped + two_pi
4634        } else {
4635            wrapped
4636        }
4637    }
4638
4639    /// Returns the local mesh bounding box for `mesh_id`, falling back to a unit vehicle box.
4640    ///
4641    /// # Arguments
4642    ///
4643    /// - `usize` - Mesh identifier inside `World3D::mesh_library`.
4644    ///
4645    /// # Returns
4646    ///
4647    /// - `AxisAlignedBox3D` - Local mesh bounds.
4648    #[must_use]
4649    fn local_bounds_for_mesh(&self, mesh_id: usize) -> AxisAlignedBox3D {
4650        self.get_mesh_library()
4651            .get(mesh_id)
4652            .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
4653            .map(Mesh3D::get_bounds)
4654            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)))
4655    }
4656
4657    /// Computes the true physical XZ contact point between a vehicle OBB and a static obstacle face so head-on wall impacts resolve cleanly at bumper center while angled hits and off-center corner clips preserve their exact rotational lever arm.
4658    ///
4659    /// # Arguments
4660    ///
4661    /// - `OrientedBox3D` - Colliding vehicle oriented bounding box.
4662    /// - `Vec3` - Unit outward horizontal wall normal pointing from obstacle into vehicle.
4663    /// - `AxisAlignedBox3D` - World-space bounding box of the colliding static obstacle.
4664    /// - `Vec3` - Fallback triangle contact point.
4665    ///
4666    /// # Returns
4667    ///
4668    /// - `Vec3` - Physical world-space contact point on the colliding bumper or corner.
4669    #[must_use]
4670    fn compute_static_contact_point(
4671        obb: OrientedBox3D,
4672        hn: Vec3,
4673        obstacle_bounds: AxisAlignedBox3D,
4674        fallback_contact: Vec3,
4675    ) -> Vec3 {
4676        let axes: [Vec3; 3] = obb.get_axes();
4677        let half: Vec3 = obb.get_half_extents();
4678        let center: Vec3 = obb.get_center();
4679        let ux: f32 = axes[0].get_x() * half.get_x();
4680        let uz: f32 = axes[0].get_z() * half.get_x();
4681        let vx: f32 = axes[2].get_x() * half.get_z();
4682        let vz: f32 = axes[2].get_z() * half.get_z();
4683        let cx: f32 = center.get_x();
4684        let cz: f32 = center.get_z();
4685        let corners: [(f32, f32); 4] = [
4686            (cx + ux + vx, cz + uz + vz),
4687            (cx + ux - vx, cz + uz - vz),
4688            (cx - ux + vx, cz - uz + vz),
4689            (cx - ux - vx, cz - uz - vz),
4690        ];
4691        let bmin: Vec3 = obstacle_bounds.get_min();
4692        let bmax: Vec3 = obstacle_bounds.get_max();
4693        let pad: f32 = 0.15;
4694        let in_obstacle: fn(f32, f32, Vec3, Vec3, f32) -> bool =
4695            |px: f32, pz: f32, lo: Vec3, hi: Vec3, margin: f32| -> bool {
4696                px >= lo.get_x() - margin
4697                    && px <= hi.get_x() + margin
4698                    && pz >= lo.get_z() - margin
4699                    && pz <= hi.get_z() + margin
4700            };
4701        let mut best_in_proj: f32 = f32::NEG_INFINITY;
4702        let mut any_in: bool = false;
4703        let mut best_all_proj: f32 = f32::NEG_INFINITY;
4704        for &(px, pz) in corners.iter() {
4705            let proj: f32 = -(px * hn.get_x() + pz * hn.get_z());
4706            if proj > best_all_proj {
4707                best_all_proj = proj;
4708            }
4709            if in_obstacle(px, pz, bmin, bmax, pad) {
4710                any_in = true;
4711                if proj > best_in_proj {
4712                    best_in_proj = proj;
4713                }
4714            }
4715        }
4716        let target_proj: f32 = if any_in { best_in_proj } else { best_all_proj };
4717        let mut sum_x: f32 = 0.0;
4718        let mut sum_z: f32 = 0.0;
4719        let mut cnt: f32 = 0.0;
4720        for &(px, pz) in corners.iter() {
4721            if any_in && !in_obstacle(px, pz, bmin, bmax, pad) {
4722                continue;
4723            }
4724            let proj: f32 = -(px * hn.get_x() + pz * hn.get_z());
4725            if proj >= target_proj - 0.16 {
4726                sum_x += px;
4727                sum_z += pz;
4728                cnt += 1.0;
4729            }
4730        }
4731        if cnt > 0.0 {
4732            Vec3::new(sum_x / cnt, fallback_contact.get_y().max(0.45), sum_z / cnt)
4733        } else {
4734            fallback_contact
4735        }
4736    }
4737
4738    /// Applies a physically based rigid-body restitution, Coulomb wall-scrape friction, and off-center corner spin torque impulse against an immovable static wall.
4739    ///
4740    /// # Arguments
4741    ///
4742    /// - `Vec3` - Vehicle center position in world space.
4743    /// - `&mut Vec3` - Mutable vehicle horizontal velocity updated in place.
4744    /// - `&mut f32` - Mutable vehicle yaw angular velocity updated in place.
4745    /// - `(f32, f32)` - `(inv_mass, inv_inertia_yaw)` rigid-body inertial properties.
4746    /// - `Vec3` - Unit horizontal outward wall normal pointing into the vehicle.
4747    /// - `Vec3` - World-space contact point on the colliding wall surface.
4748    ///
4749    /// # Returns
4750    ///
4751    /// - `f32` - Positive normal impact approach speed in meters per second (`0.0` when separating).
4752    fn apply_static_wall_impulse(
4753        car_pos: Vec3,
4754        vel: &mut Vec3,
4755        yaw_rate: &mut f32,
4756        inertia_pair: (f32, f32),
4757        hn: Vec3,
4758        contact_point: Vec3,
4759    ) -> f32 {
4760        let (inv_m, inv_i): (f32, f32) = inertia_pair;
4761        let raw_rx: f32 = contact_point.get_x() - car_pos.get_x();
4762        let raw_rz: f32 = contact_point.get_z() - car_pos.get_z();
4763        let r_len: f32 = (raw_rx * raw_rx + raw_rz * raw_rz).sqrt();
4764        let (rx, rz): (f32, f32) = if r_len > 2.6 {
4765            let scale_r: f32 = 2.6 / r_len;
4766            (raw_rx * scale_r, raw_rz * scale_r)
4767        } else {
4768            (raw_rx, raw_rz)
4769        };
4770        let v_pt_x: f32 = vel.get_x() + (*yaw_rate) * rz;
4771        let v_pt_z: f32 = vel.get_z() - (*yaw_rate) * rx;
4772        let v_n: f32 = v_pt_x * hn.get_x() + v_pt_z * hn.get_z();
4773        if v_n >= 0.0 {
4774            return 0.0;
4775        }
4776        let approach_speed: f32 = -v_n;
4777        let restitution: f32 = if approach_speed > 1.2 {
4778            COLLISION_WALL_RESTITUTION
4779        } else {
4780            0.0
4781        };
4782        let r_cross_n: f32 = rz * hn.get_x() - rx * hn.get_z();
4783        let denom_n: f32 = inv_m + (r_cross_n * r_cross_n) * inv_i;
4784        let j_n: f32 = (-(1.0 + restitution) * v_n / denom_n.max(1.0e-6)).max(0.0);
4785        vel.set_x(vel.get_x() + hn.get_x() * j_n * inv_m);
4786        vel.set_z(vel.get_z() + hn.get_z() * j_n * inv_m);
4787        *yaw_rate = (*yaw_rate + r_cross_n * j_n * inv_i)
4788            .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
4789        let vt_x: f32 = v_pt_x - hn.get_x() * v_n;
4790        let vt_z: f32 = v_pt_z - hn.get_z() * v_n;
4791        let vt_len: f32 = (vt_x * vt_x + vt_z * vt_z).sqrt();
4792        if vt_len > 1.0e-4 && j_n > 0.0 {
4793            let tx: f32 = vt_x / vt_len;
4794            let tz: f32 = vt_z / vt_len;
4795            let r_cross_t: f32 = rz * tx - rx * tz;
4796            let denom_t: f32 = inv_m + (r_cross_t * r_cross_t) * inv_i;
4797            let max_jt: f32 = COLLISION_WALL_FRICTION * j_n;
4798            let j_t: f32 = (-vt_len / denom_t.max(1.0e-6)).clamp(-max_jt, max_jt);
4799            vel.set_x(vel.get_x() + tx * j_t * inv_m);
4800            vel.set_z(vel.get_z() + tz * j_t * inv_m);
4801            *yaw_rate = (*yaw_rate + r_cross_t * j_t * inv_i)
4802                .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
4803        }
4804        approach_speed
4805    }
4806
4807    /// Integrates a rigid-body vehicle over `sub_dt` with substepped continuous static-world collision detection, realistic bounce/scrape/spin impulses, and zero-penetration enforcement.
4808    ///
4809    /// # Arguments
4810    ///
4811    /// - `&mut Transform3D` - Flat horizontal vehicle transform updated in place.
4812    /// - `&mut Vec3` - Mutable horizontal vehicle velocity updated on wall impacts.
4813    /// - `&mut f32` - Mutable yaw spin rate updated on off-center impacts.
4814    /// - `(f32, f32)` - `(inv_mass, inv_inertia_yaw)` inertial properties.
4815    /// - `(usize, AxisAlignedBox3D)` - `(vehicle_obj_idx, local_mesh_bounds)`.
4816    /// - `VehicleCcdStepCtx3D` - Substep duration, optional playable ground bounds, and vehicle margin.
4817    ///
4818    /// # Returns
4819    ///
4820    /// - `(bool, f32, Vec3, Vec3)` - `(moved, peak_impact_mps, impact_contact, impact_normal)`.
4821    fn step_rigid_vehicle_static_ccd(
4822        &self,
4823        tr: &mut Transform3D,
4824        vel: &mut Vec3,
4825        yaw_rate: &mut f32,
4826        inertia_pair: (f32, f32),
4827        vehicle_spec: (usize, AxisAlignedBox3D),
4828        step_ctx: VehicleCcdStepCtx3D,
4829    ) -> (bool, f32, Vec3, Vec3) {
4830        let (vehicle_idx, mesh_bounds): (usize, AxisAlignedBox3D) = vehicle_spec;
4831        let VehicleCcdStepCtx3D {
4832            sub_dt,
4833            ground_limits,
4834            ground_margin,
4835        } = step_ctx;
4836        let mut moved: bool = self.depenetrate_vehicle_static_horizontally(
4837            tr,
4838            mesh_bounds,
4839            vehicle_idx,
4840            ground_limits,
4841            ground_margin,
4842        );
4843        let mut peak_impact: f32 = 0.0;
4844        let mut peak_contact: Vec3 = tr.get_position();
4845        let mut peak_normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
4846        let speed: f32 = (vel.get_x() * vel.get_x() + vel.get_z() * vel.get_z()).sqrt();
4847        let linear_dist: f32 = speed * sub_dt;
4848        let angular_dist: f32 = yaw_rate.abs() * sub_dt;
4849        if linear_dist <= 1.0e-6 && angular_dist <= 1.0e-6 {
4850            return (moved, peak_impact, peak_contact, peak_normal);
4851        }
4852        let obb_now: OrientedBox3D = tr.to_oriented_box(mesh_bounds);
4853        let min_half: f32 = obb_now
4854            .get_half_extents()
4855            .get_x()
4856            .min(obb_now.get_half_extents().get_z())
4857            .max(0.25);
4858        let max_lin_step: f32 = (min_half * 0.25).min(COLLISION_CCD_MAX_STEP_M);
4859        let lin_steps: usize =
4860            ((linear_dist / max_lin_step).ceil() as usize).clamp(1, COLLISION_CCD_MAX_SUBSTEPS);
4861        let rot_steps: usize = ((angular_dist / COLLISION_ROT_MAX_STEP_RAD).ceil() as usize)
4862            .clamp(1, COLLISION_ROT_MAX_SUBSTEPS);
4863        let substeps: usize = lin_steps.max(rot_steps);
4864        let step_dt: f32 = sub_dt / (substeps as f32);
4865        for _ in 0..substeps {
4866            let d_yaw: f32 = (*yaw_rate) * step_dt;
4867            if d_yaw.abs() > 1.0e-6 {
4868                let mut rotated: Transform3D = *tr;
4869                rotated.set_yaw_rad(tr.get_yaw_rad() + d_yaw);
4870                if let Some(rot_hit) = self.mesh_oriented_box_static_collision(
4871                    rotated.to_oriented_box(mesh_bounds),
4872                    Some(vehicle_idx),
4873                ) {
4874                    if rot_hit.get_penetration() <= COLLISION_ROT_MAX_PUSH_M {
4875                        let mut pushed_rot: Transform3D = rotated;
4876                        let _: bool = self.depenetrate_vehicle_static_horizontally(
4877                            &mut pushed_rot,
4878                            mesh_bounds,
4879                            vehicle_idx,
4880                            ground_limits,
4881                            ground_margin,
4882                        );
4883                        let shift_m: f32 = pushed_rot
4884                            .get_position()
4885                            .sub(rotated.get_position())
4886                            .length();
4887                        if shift_m <= COLLISION_ROT_MAX_PUSH_M
4888                            && self
4889                                .mesh_oriented_box_static_collision(
4890                                    pushed_rot.to_oriented_box(mesh_bounds),
4891                                    Some(vehicle_idx),
4892                                )
4893                                .is_none()
4894                        {
4895                            *tr = pushed_rot;
4896                            moved = true;
4897                        } else {
4898                            *yaw_rate *= -0.2;
4899                        }
4900                    } else {
4901                        *yaw_rate *= -0.2;
4902                    }
4903                } else {
4904                    *tr = rotated;
4905                    moved = true;
4906                }
4907            }
4908            let step_dx: f32 = vel.get_x() * step_dt;
4909            let step_dz: f32 = vel.get_z() * step_dt;
4910            if step_dx * step_dx + step_dz * step_dz <= 1.0e-12 {
4911                continue;
4912            }
4913            let cur_pos: Vec3 = tr.get_position();
4914            let raw_next: Vec3 = Vec3::new(
4915                cur_pos.get_x() + step_dx,
4916                cur_pos.get_y(),
4917                cur_pos.get_z() + step_dz,
4918            );
4919            let next_pos: Vec3 =
4920                Self::clamp_horizontal_to_ground(raw_next, ground_limits, ground_margin);
4921            if (next_pos.get_x() - raw_next.get_x()).abs() > 1.0e-4 {
4922                vel.set_x(-vel.get_x() * COLLISION_WALL_RESTITUTION);
4923            }
4924            if (next_pos.get_z() - raw_next.get_z()).abs() > 1.0e-4 {
4925                vel.set_z(-vel.get_z() * COLLISION_WALL_RESTITUTION);
4926            }
4927            let mut cand: Transform3D = *tr;
4928            cand.set_position(next_pos);
4929            if let Some(hit) = self.mesh_oriented_box_static_collision(
4930                cand.to_oriented_box(mesh_bounds),
4931                Some(vehicle_idx),
4932            ) {
4933                let raw_hn: Vec3 =
4934                    Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
4935                let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
4936                    raw_hn.normalize()
4937                } else {
4938                    self.horizontal_collision_normal(
4939                        cand.to_oriented_box(mesh_bounds),
4940                        hit.get_object_index(),
4941                    )
4942                };
4943                if hn.length_sq() > 1.0e-6 {
4944                    let obs_bounds: AxisAlignedBox3D = self
4945                        .get_objects()
4946                        .get(hit.get_object_index())
4947                        .map(SceneObject3D::get_world_bounds)
4948                        .unwrap_or_else(|| {
4949                            AxisAlignedBox3D::new(
4950                                hit.get_contact_point().sub(Vec3::splat(0.5)),
4951                                hit.get_contact_point().add(Vec3::splat(0.5)),
4952                            )
4953                        });
4954                    let phys_contact: Vec3 = Self::compute_static_contact_point(
4955                        cand.to_oriented_box(mesh_bounds),
4956                        hn,
4957                        obs_bounds,
4958                        hit.get_contact_point(),
4959                    );
4960                    let impact_v: f32 = Self::apply_static_wall_impulse(
4961                        cur_pos,
4962                        vel,
4963                        yaw_rate,
4964                        inertia_pair,
4965                        hn,
4966                        phys_contact,
4967                    );
4968                    if impact_v > peak_impact {
4969                        peak_impact = impact_v;
4970                        peak_contact = phys_contact;
4971                        peak_normal = hn;
4972                    }
4973                    let slide_dx: f32 = vel.get_x() * step_dt;
4974                    let slide_dz: f32 = vel.get_z() * step_dt;
4975                    let push_eps: f32 = COLLISION_MTV_PUSH_EPS;
4976                    let slide_pos: Vec3 = Self::clamp_horizontal_to_ground(
4977                        Vec3::new(
4978                            cur_pos.get_x() + slide_dx + hn.get_x() * push_eps,
4979                            cur_pos.get_y(),
4980                            cur_pos.get_z() + slide_dz + hn.get_z() * push_eps,
4981                        ),
4982                        ground_limits,
4983                        ground_margin,
4984                    );
4985                    let mut slide_tr: Transform3D = *tr;
4986                    slide_tr.set_position(slide_pos);
4987                    if self
4988                        .mesh_oriented_box_static_collision(
4989                            slide_tr.to_oriented_box(mesh_bounds),
4990                            Some(vehicle_idx),
4991                        )
4992                        .is_none()
4993                    {
4994                        *tr = slide_tr;
4995                        moved = true;
4996                        continue;
4997                    }
4998                }
4999                break;
5000            }
5001            *tr = cand;
5002            moved = true;
5003        }
5004        if self.depenetrate_vehicle_static_horizontally(
5005            tr,
5006            mesh_bounds,
5007            vehicle_idx,
5008            ground_limits,
5009            ground_margin,
5010        ) {
5011            moved = true;
5012        }
5013        (moved, peak_impact, peak_contact, peak_normal)
5014    }
5015
5016    /// Emits bright metallic collision sparks via `World3D::niagara` at a rigid-body impact point.
5017    ///
5018    /// # Arguments
5019    ///
5020    /// - `Vec3` - World-space contact point.
5021    /// - `Vec3` - Outward impact normal.
5022    /// - `f32` - Normalized impact intensity in `[0.0, 1.0]`.
5023    fn emit_collision_sparks(&mut self, contact: Vec3, normal: Vec3, intensity: f32) {
5024        if self.get_niagara().get_active_count() >= 56 {
5025            return;
5026        }
5027        let burst: usize = ((3.0 + intensity * 6.0).round() as usize).clamp(2, 9);
5028        let mut cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5029        cfg.set_origin(Vec3::new(
5030            contact.get_x(),
5031            contact.get_y().max(0.45),
5032            contact.get_z(),
5033        ));
5034        cfg.set_base_velocity(normal.scale(4.5 + intensity * 7.5).add(Vec3::new(
5035            0.0,
5036            2.8 + intensity * 2.5,
5037            0.0,
5038        )));
5039        cfg.set_velocity_spread(3.8 + intensity * 2.5);
5040        cfg.set_start_color(Color::rgba(255, 196, 36, 255));
5041        cfg.set_end_color(Color::rgba(255, 72, 0, 80));
5042        cfg.set_start_size_m(0.12);
5043        cfg.set_end_size_m(0.03);
5044        cfg.set_min_lifetime(0.22);
5045        cfg.set_max_lifetime(0.55);
5046        cfg.set_emissive_boost(1.75);
5047        self.get_mut_niagara().emit_burst(burst, &cfg);
5048    }
5049
5050    /// Emits dual rear-wheel tire smoke puffs via `World3D::niagara` while powersliding.
5051    ///
5052    /// # Arguments
5053    ///
5054    /// - `Vec3` - Player vehicle world position.
5055    /// - `Vec3` - Unit forward heading vector.
5056    /// - `Vec3` - Unit right lateral vector.
5057    /// - `f32` - Absolute slip angle in radians.
5058    fn emit_drift_smoke(
5059        &mut self,
5060        car_origin: Vec3,
5061        car_fwd: Vec3,
5062        car_right: Vec3,
5063        slip_abs: f32,
5064    ) {
5065        if self.get_niagara().get_active_count() >= 48 {
5066            return;
5067        }
5068        let intensity: f32 = ((slip_abs - 0.10) / 0.50).clamp(0.25, 1.0);
5069        let rear_center: Vec3 = car_origin
5070            .sub(car_fwd.scale(1.85))
5071            .add(Vec3::new(0.0, 0.22, 0.0));
5072        for side in [-0.88_f32, 0.88_f32] {
5073            let wheel_pos: Vec3 = rear_center.add(car_right.scale(side));
5074            let mut smoke_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5075            smoke_cfg.set_origin(wheel_pos);
5076            smoke_cfg.set_base_velocity(car_fwd.scale(-2.4).add(Vec3::new(
5077                0.0,
5078                0.85 + intensity * 0.5,
5079                0.0,
5080            )));
5081            smoke_cfg.set_velocity_spread(1.25);
5082            smoke_cfg.set_start_color(Color::rgba(226, 232, 240, 175));
5083            smoke_cfg.set_end_color(Color::rgba(148, 163, 184, 30));
5084            smoke_cfg.set_start_size_m(0.22 + intensity * 0.12);
5085            smoke_cfg.set_end_size_m(0.52 + intensity * 0.18);
5086            smoke_cfg.set_min_lifetime(0.35);
5087            smoke_cfg.set_max_lifetime(0.75);
5088            smoke_cfg.set_emissive_boost(0.35);
5089            self.get_mut_niagara().emit_burst(1, &smoke_cfg);
5090        }
5091    }
5092
5093    /// Emits luminous dual exhaust nitro boost flames via `World3D::niagara`.
5094    ///
5095    /// # Arguments
5096    ///
5097    /// - `Vec3` - Player vehicle world position.
5098    /// - `Vec3` - Unit forward heading vector.
5099    /// - `Vec3` - Unit right lateral vector.
5100    /// - `Vec3` - Current player vehicle world velocity in meters per second.
5101    fn emit_boost_flame(
5102        &mut self,
5103        car_origin: Vec3,
5104        car_fwd: Vec3,
5105        car_right: Vec3,
5106        car_vel: Vec3,
5107    ) {
5108        if self.get_niagara().get_active_count() >= 96 {
5109            return;
5110        }
5111        let exhaust_center: Vec3 = car_origin
5112            .sub(car_fwd.scale(2.35))
5113            .add(Vec3::new(0.0, 0.44, 0.0));
5114        let base_jet_vel: Vec3 = car_vel
5115            .scale(0.88)
5116            .add(car_fwd.scale(-5.5))
5117            .add(Vec3::new(0.0, 0.28, 0.0));
5118        for side in [-0.46_f32, 0.46_f32] {
5119            let pipe_pos: Vec3 = exhaust_center.add(car_right.scale(side));
5120            let mut flame_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
5121            flame_cfg.set_origin(pipe_pos);
5122            flame_cfg.set_base_velocity(base_jet_vel);
5123            flame_cfg.set_velocity_spread(0.75);
5124            flame_cfg.set_start_color(Color::rgba(0, 224, 255, 255));
5125            flame_cfg.set_end_color(Color::rgba(255, 104, 16, 110));
5126            flame_cfg.set_start_size_m(0.28);
5127            flame_cfg.set_end_size_m(0.10);
5128            flame_cfg.set_min_lifetime(0.12);
5129            flame_cfg.set_max_lifetime(0.26);
5130            flame_cfg.set_emissive_boost(2.15);
5131            self.get_mut_niagara().emit_burst(3, &flame_cfg);
5132        }
5133    }
5134
5135    /// Measures the closest slower or stationary dynamic vehicle directly ahead of `npc_idx` along its forward lane corridor for cautious AI braking.
5136    ///
5137    /// # Arguments
5138    ///
5139    /// - `usize` - Querying NPC scene object index.
5140    /// - `Vec3` - NPC world center position.
5141    /// - `Vec3` - Unit forward direction of the NPC.
5142    /// - `Vec3` - Unit right vector of the NPC.
5143    /// - `f32` - Current forward speed of the NPC in meters per second.
5144    ///
5145    /// # Returns
5146    ///
5147    /// - `Option<f32>` - Forward center-to-center distance in meters to the closest blocking vehicle ahead within `16.0m`.
5148    #[must_use]
5149    fn npc_forward_blocking_gap(
5150        &self,
5151        npc_idx: usize,
5152        pos: Vec3,
5153        fwd: Vec3,
5154        right: Vec3,
5155        npc_fwd_speed: f32,
5156    ) -> Option<f32> {
5157        let mut closest: Option<f32> = None;
5158        let objects: &[SceneObject3D] = self.get_objects().as_slice();
5159        let player_opt: Option<usize> = self.vehicle_index();
5160        let player_vel: Vec3 = self.player_velocity();
5161        let Self {
5162            traffic_vehicles, ..
5163        } = self;
5164        for (other_idx, other_obj) in objects.iter().enumerate() {
5165            let other_solid: bool =
5166                other_obj.get_solid_collider() || other_obj.get_ray_trace_caster();
5167            if other_idx == npc_idx || !other_obj.get_is_dynamic() || !other_solid {
5168                continue;
5169            }
5170            let other_pos: Vec3 = other_obj.get_transform().get_position();
5171            let diff: Vec3 = Vec3::new(
5172                other_pos.get_x() - pos.get_x(),
5173                0.0,
5174                other_pos.get_z() - pos.get_z(),
5175            );
5176            let fwd_d: f32 = diff.dot(fwd);
5177            if fwd_d <= 0.5 || fwd_d >= 16.0 {
5178                continue;
5179            }
5180            let lat_d: f32 = diff.dot(right).abs();
5181            if lat_d > 2.75 {
5182                continue;
5183            }
5184            let other_vel: Vec3 = if player_opt == Some(other_idx) {
5185                player_vel
5186            } else {
5187                traffic_vehicles
5188                    .iter()
5189                    .find(|n: &&NpcVehicle3D| n.get_object_index() == other_idx)
5190                    .map(NpcVehicle3D::get_vel)
5191                    .unwrap_or_else(Vec3::zero)
5192            };
5193            let other_fwd_speed: f32 = other_vel.dot(fwd);
5194            if other_fwd_speed < npc_fwd_speed - 0.5 || other_fwd_speed.abs() < 1.5 {
5195                closest = Some(closest.map(|prev: f32| prev.min(fwd_d)).unwrap_or(fwd_d));
5196            }
5197        }
5198        closest
5199    }
5200
5201    /// Resolves all dynamic vehicle-vs-vehicle rigid-body OBB SAT collisions (Player-vs-NPC and NPC-vs-NPC) with positional separation, momentum transfer, spin torque, off-road knockback, and collision sparks.
5202    ///
5203    /// # Arguments
5204    ///
5205    /// - `Option<(f32, f32, f32, f32)>` - Optional playable horizontal ground bounds.
5206    ///
5207    /// # Returns
5208    ///
5209    /// - `(bool, f32, Vec3, Vec3)` - `(any_moved, player_impact_mps, impact_contact, impact_normal)`.
5210    fn resolve_dynamic_vehicle_collisions(
5211        &mut self,
5212        ground_limits: Option<(f32, f32, f32, f32)>,
5213    ) -> (bool, f32, Vec3, Vec3) {
5214        let player_opt: Option<usize> = self.vehicle_index();
5215        let npc_count: usize = self.traffic_vehicle_count();
5216        let total_bodies: usize = npc_count + usize::from(player_opt.is_some());
5217        if total_bodies < 2 {
5218            return (false, 0.0, Vec3::zero(), Vec3::new(0.0, 0.0, 1.0));
5219        }
5220        let mut any_moved: bool = false;
5221        let mut player_peak_impact: f32 = 0.0;
5222        let mut player_peak_contact: Vec3 = Vec3::zero();
5223        let mut player_peak_normal: Vec3 = Vec3::new(0.0, 0.0, 1.0);
5224        let player_offset: usize = usize::from(player_opt.is_some());
5225        for _ in 0..2_usize {
5226            for idx_a in 0..total_bodies {
5227                for idx_b in (idx_a + 1)..total_bodies {
5228                    let is_a_player: bool = player_opt.is_some() && idx_a == 0;
5229                    let obj_a: usize = if is_a_player {
5230                        match player_opt {
5231                            Some(p_idx) => p_idx,
5232                            None => continue,
5233                        }
5234                    } else {
5235                        match self.traffic_vehicle_object_index(idx_a - player_offset) {
5236                            Some(n_idx) => n_idx,
5237                            None => continue,
5238                        }
5239                    };
5240                    let npc_slot_b: usize = idx_b - player_offset;
5241                    let Some(obj_b) = self.traffic_vehicle_object_index(npc_slot_b) else {
5242                        continue;
5243                    };
5244                    let Some((mut tr_a, mesh_a)) = self
5245                        .get_objects()
5246                        .get(obj_a)
5247                        .map(|o: &SceneObject3D| (o.get_transform(), o.get_mesh_id()))
5248                    else {
5249                        continue;
5250                    };
5251                    let Some((mut tr_b, mesh_b)) = self
5252                        .get_objects()
5253                        .get(obj_b)
5254                        .map(|o: &SceneObject3D| (o.get_transform(), o.get_mesh_id()))
5255                    else {
5256                        continue;
5257                    };
5258                    let bounds_a: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_a);
5259                    let bounds_b: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_b);
5260                    let obb_a: OrientedBox3D = tr_a.to_oriented_box(bounds_a);
5261                    let obb_b: OrientedBox3D = tr_b.to_oriented_box(bounds_b);
5262                    let Some((normal_ba, pen, contact)) = obb_a.intersect_oriented_box_xz(&obb_b)
5263                    else {
5264                        continue;
5265                    };
5266                    let (mut vel_a, mut omega_a, mass_a, inv_i_a): (Vec3, f32, f32, f32) =
5267                        if is_a_player {
5268                            (
5269                                self.player_velocity(),
5270                                self.player_yaw_rate(),
5271                                VEHICLE_PLAYER_MASS_KG,
5272                                1.0 / VEHICLE_PLAYER_INERTIA_YAW,
5273                            )
5274                        } else {
5275                            let Self {
5276                                traffic_vehicles, ..
5277                            } = self;
5278                            let npc_a: NpcVehicle3D = traffic_vehicles[idx_a - player_offset];
5279                            (
5280                                npc_a.get_vel(),
5281                                npc_a.get_yaw_rate(),
5282                                npc_a.get_mass(),
5283                                1.0 / VEHICLE_NPC_INERTIA_YAW,
5284                            )
5285                        };
5286                    let (mut vel_b, mut omega_b, mass_b, inv_i_b): (Vec3, f32, f32, f32) = {
5287                        let Self {
5288                            traffic_vehicles, ..
5289                        } = self;
5290                        let npc_b: NpcVehicle3D = traffic_vehicles[npc_slot_b];
5291                        (
5292                            npc_b.get_vel(),
5293                            npc_b.get_yaw_rate(),
5294                            npc_b.get_mass(),
5295                            1.0 / VEHICLE_NPC_INERTIA_YAW,
5296                        )
5297                    };
5298                    let inv_m_a: f32 = 1.0 / mass_a.max(100.0);
5299                    let inv_m_b: f32 = 1.0 / mass_b.max(100.0);
5300                    let inv_m_sum: f32 = inv_m_a + inv_m_b;
5301                    let total_push: f32 = pen + COLLISION_MTV_PUSH_EPS;
5302                    let share_a: f32 = total_push * (inv_m_a / inv_m_sum);
5303                    let share_b: f32 = total_push * (inv_m_b / inv_m_sum);
5304                    let margin_a: f32 = obb_a
5305                        .get_half_extents()
5306                        .get_x()
5307                        .max(obb_a.get_half_extents().get_z());
5308                    let margin_b: f32 = obb_b
5309                        .get_half_extents()
5310                        .get_x()
5311                        .max(obb_b.get_half_extents().get_z());
5312                    let cand_pos_a: Vec3 = Self::clamp_horizontal_to_ground(
5313                        tr_a.get_position().add(normal_ba.scale(share_a)),
5314                        ground_limits,
5315                        margin_a,
5316                    );
5317                    let cand_pos_b: Vec3 = Self::clamp_horizontal_to_ground(
5318                        tr_b.get_position().sub(normal_ba.scale(share_b)),
5319                        ground_limits,
5320                        margin_b,
5321                    );
5322                    let mut cand_tr_a: Transform3D = tr_a;
5323                    cand_tr_a.set_position(cand_pos_a);
5324                    let mut cand_tr_b: Transform3D = tr_b;
5325                    cand_tr_b.set_position(cand_pos_b);
5326                    let a_static_ok: bool = self
5327                        .mesh_oriented_box_static_collision(
5328                            cand_tr_a.to_oriented_box(bounds_a),
5329                            Some(obj_a),
5330                        )
5331                        .is_none();
5332                    let b_static_ok: bool = self
5333                        .mesh_oriented_box_static_collision(
5334                            cand_tr_b.to_oriented_box(bounds_b),
5335                            Some(obj_b),
5336                        )
5337                        .is_none();
5338                    if a_static_ok && b_static_ok {
5339                        tr_a = cand_tr_a;
5340                        tr_b = cand_tr_b;
5341                    } else if b_static_ok {
5342                        let full_b: Vec3 = Self::clamp_horizontal_to_ground(
5343                            tr_b.get_position().sub(normal_ba.scale(total_push)),
5344                            ground_limits,
5345                            margin_b,
5346                        );
5347                        tr_b.set_position(full_b);
5348                    } else if a_static_ok {
5349                        let full_a: Vec3 = Self::clamp_horizontal_to_ground(
5350                            tr_a.get_position().add(normal_ba.scale(total_push)),
5351                            ground_limits,
5352                            margin_a,
5353                        );
5354                        tr_a.set_position(full_a);
5355                    } else {
5356                        tr_a = cand_tr_a;
5357                        tr_b = cand_tr_b;
5358                        let _: bool = self.depenetrate_vehicle_static_horizontally(
5359                            &mut tr_a,
5360                            bounds_a,
5361                            obj_a,
5362                            ground_limits,
5363                            margin_a,
5364                        );
5365                        let _: bool = self.depenetrate_vehicle_static_horizontally(
5366                            &mut tr_b,
5367                            bounds_b,
5368                            obj_b,
5369                            ground_limits,
5370                            margin_b,
5371                        );
5372                    }
5373                    let pos_a: Vec3 = tr_a.get_position();
5374                    let pos_b: Vec3 = tr_b.get_position();
5375                    let ra_x: f32 = (contact.get_x() - pos_a.get_x()).clamp(-2.6, 2.6);
5376                    let ra_z: f32 = (contact.get_z() - pos_a.get_z()).clamp(-2.6, 2.6);
5377                    let rb_x: f32 = (contact.get_x() - pos_b.get_x()).clamp(-2.6, 2.6);
5378                    let rb_z: f32 = (contact.get_z() - pos_b.get_z()).clamp(-2.6, 2.6);
5379                    let va_pt_x: f32 = vel_a.get_x() + omega_a * ra_z;
5380                    let va_pt_z: f32 = vel_a.get_z() - omega_a * ra_x;
5381                    let vb_pt_x: f32 = vel_b.get_x() + omega_b * rb_z;
5382                    let vb_pt_z: f32 = vel_b.get_z() - omega_b * rb_x;
5383                    let vrel_x: f32 = va_pt_x - vb_pt_x;
5384                    let vrel_z: f32 = va_pt_z - vb_pt_z;
5385                    let vrel_n: f32 = vrel_x * normal_ba.get_x() + vrel_z * normal_ba.get_z();
5386                    let mut impact_dv_a: f32 = 0.0;
5387                    let mut impact_dv_b: f32 = 0.0;
5388                    if vrel_n < 0.0 {
5389                        let ra_cross_n: f32 = ra_z * normal_ba.get_x() - ra_x * normal_ba.get_z();
5390                        let rb_cross_n: f32 = rb_z * normal_ba.get_x() - rb_x * normal_ba.get_z();
5391                        let denom_n: f32 = inv_m_a
5392                            + inv_m_b
5393                            + (ra_cross_n * ra_cross_n) * inv_i_a
5394                            + (rb_cross_n * rb_cross_n) * inv_i_b;
5395                        let restitution: f32 = if -vrel_n > 1.5 {
5396                            COLLISION_CAR_RESTITUTION
5397                        } else {
5398                            0.05
5399                        };
5400                        let j_n: f32 =
5401                            (-(1.0 + restitution) * vrel_n / denom_n.max(1.0e-6)).max(0.0);
5402                        vel_a.set_x(vel_a.get_x() + normal_ba.get_x() * j_n * inv_m_a);
5403                        vel_a.set_z(vel_a.get_z() + normal_ba.get_z() * j_n * inv_m_a);
5404                        omega_a = (omega_a + ra_cross_n * j_n * inv_i_a)
5405                            .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5406                        vel_b.set_x(vel_b.get_x() - normal_ba.get_x() * j_n * inv_m_b);
5407                        vel_b.set_z(vel_b.get_z() - normal_ba.get_z() * j_n * inv_m_b);
5408                        omega_b = (omega_b - rb_cross_n * j_n * inv_i_b)
5409                            .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5410                        impact_dv_a = j_n * inv_m_a;
5411                        impact_dv_b = j_n * inv_m_b;
5412                        let vt_x: f32 = vrel_x - normal_ba.get_x() * vrel_n;
5413                        let vt_z: f32 = vrel_z - normal_ba.get_z() * vrel_n;
5414                        let vt_len: f32 = (vt_x * vt_x + vt_z * vt_z).sqrt();
5415                        if vt_len > 1.0e-4 && j_n > 0.0 {
5416                            let tx: f32 = vt_x / vt_len;
5417                            let tz: f32 = vt_z / vt_len;
5418                            let ra_cross_t: f32 = ra_z * tx - ra_x * tz;
5419                            let rb_cross_t: f32 = rb_z * tx - rb_x * tz;
5420                            let denom_t: f32 = inv_m_a
5421                                + inv_m_b
5422                                + (ra_cross_t * ra_cross_t) * inv_i_a
5423                                + (rb_cross_t * rb_cross_t) * inv_i_b;
5424                            let max_jt: f32 = COLLISION_CAR_FRICTION * j_n;
5425                            let j_t: f32 = (-vt_len / denom_t.max(1.0e-6)).clamp(-max_jt, max_jt);
5426                            vel_a.set_x(vel_a.get_x() + tx * j_t * inv_m_a);
5427                            vel_a.set_z(vel_a.get_z() + tz * j_t * inv_m_a);
5428                            omega_a = (omega_a + ra_cross_t * j_t * inv_i_a)
5429                                .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5430                            vel_b.set_x(vel_b.get_x() - tx * j_t * inv_m_b);
5431                            vel_b.set_z(vel_b.get_z() - tz * j_t * inv_m_b);
5432                            omega_b = (omega_b - rb_cross_t * j_t * inv_i_b)
5433                                .clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5434                        }
5435                        let closing: f32 = -vrel_n;
5436                        if is_a_player && closing > player_peak_impact {
5437                            player_peak_impact = closing;
5438                            player_peak_contact = contact;
5439                            player_peak_normal = normal_ba;
5440                        }
5441                        if closing > 2.5 {
5442                            let spark_int: f32 = ((closing - 2.0) / 24.0).clamp(0.15, 1.0);
5443                            self.emit_collision_sparks(contact, normal_ba, spark_int);
5444                        }
5445                    }
5446                    let wb_a: AxisAlignedBox3D = tr_a.transform_bounds(bounds_a);
5447                    let wb_b: AxisAlignedBox3D = tr_b.transform_bounds(bounds_b);
5448                    if let Some(o_a) = self.get_mut_objects().get_mut(obj_a) {
5449                        o_a.set_transform(tr_a);
5450                        o_a.set_world_bounds(wb_a);
5451                    }
5452                    if let Some(o_b) = self.get_mut_objects().get_mut(obj_b) {
5453                        o_b.set_transform(tr_b);
5454                        o_b.set_world_bounds(wb_b);
5455                    }
5456                    if is_a_player {
5457                        let Self { player_physics, .. } = self;
5458                        player_physics.set_vel(vel_a);
5459                        player_physics.set_yaw_rate(omega_a);
5460                    } else {
5461                        let slot_a: usize = idx_a - player_offset;
5462                        let Self {
5463                            traffic_vehicles, ..
5464                        } = self;
5465                        let npc_a: &mut NpcVehicle3D = &mut traffic_vehicles[slot_a];
5466                        npc_a.set_vel(vel_a);
5467                        npc_a.set_yaw_rate(omega_a);
5468                        if impact_dv_a > 1.5 {
5469                            let rec_s: f32 = (1.4 + impact_dv_a * 0.08).clamp(1.2, 2.8);
5470                            npc_a.set_recovery_timer(npc_a.get_recovery_timer().max(rec_s));
5471                            npc_a.set_free_roam_mode(true);
5472                        }
5473                    }
5474                    {
5475                        let Self {
5476                            traffic_vehicles, ..
5477                        } = self;
5478                        let npc_b: &mut NpcVehicle3D = &mut traffic_vehicles[npc_slot_b];
5479                        npc_b.set_vel(vel_b);
5480                        npc_b.set_yaw_rate(omega_b);
5481                        if impact_dv_b > 1.5 {
5482                            let rec_s: f32 = (1.4 + impact_dv_b * 0.08).clamp(1.2, 2.8);
5483                            npc_b.set_recovery_timer(npc_b.get_recovery_timer().max(rec_s));
5484                            npc_b.set_free_roam_mode(true);
5485                        }
5486                    }
5487                    any_moved = true;
5488                }
5489            }
5490        }
5491        (
5492            any_moved,
5493            player_peak_impact,
5494            player_peak_contact,
5495            player_peak_normal,
5496        )
5497    }
5498
5499    /// Advances drivable vehicle chassis dynamics (`Shift` boost, `Space` drift, Ackermann reverse), dynamic rigid-body NPC traffic, 2-body OBB SAT collisions, raycast chase camera, Niagara particles, and animations.
5500    ///
5501    /// # Arguments
5502    ///
5503    /// - `f32` - Delta time in seconds.
5504    /// - `&InputState` - Real-time polled keyboard/pointer input.
5505    /// - `&ActionMap` - Action bindings for WASD/Arrows, Boost, and Drift controls.
5506    pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
5507        if dt <= 0.0 || !dt.is_finite() {
5508            return;
5509        }
5510        self.set_world_time_secs(self.get_world_time_secs() + dt);
5511        let sim_tick: u64 = self.get_sim_tick().wrapping_add(1);
5512        self.set_sim_tick(sim_tick);
5513        let kb_steer: f32 = if actions.is_active(GameAction::MoveRight, input) {
5514            1.0
5515        } else {
5516            0.0
5517        } - if actions.is_active(GameAction::MoveLeft, input) {
5518            1.0
5519        } else {
5520            0.0
5521        };
5522        let kb_throttle: f32 = if actions.is_active(GameAction::MoveUp, input) {
5523            1.0
5524        } else {
5525            0.0
5526        } - if actions.is_active(GameAction::MoveDown, input) {
5527            1.0
5528        } else {
5529            0.0
5530        };
5531        let v_stick: Point = input.get_virtual_axis();
5532        let steer: f32 = (kb_steer + v_stick.get_x()).clamp(-1.0, 1.0);
5533        let throttle: f32 = (kb_throttle - v_stick.get_y()).clamp(-1.0, 1.0);
5534        let boost_pressed: bool = actions.is_active(GameAction::Boost, input)
5535            || input.get_modifiers().get_shift()
5536            || input.get_virtual_boost();
5537        let drift_pressed: bool = actions.is_active(GameAction::Drift, input)
5538            || input.is_key_down(KeyCode::Space)
5539            || input.get_virtual_drift();
5540        let mut any_dynamic_moved: bool = false;
5541        let mut any_static_moved: bool = false;
5542        let ground_limits: Option<(f32, f32, f32, f32)> = self.ground_play_bounds();
5543        let car_opt: Option<usize> = self.vehicle_index();
5544        let sim_substeps: usize = ((dt / 0.02).ceil() as usize).clamp(1, 6);
5545        let sub_dt: f32 = dt / (sim_substeps as f32);
5546        let mut player_moved_any: bool = false;
5547        for _ in 0..sim_substeps {
5548            if let Some(car_idx) = car_opt
5549                && let Some((cur_tr, mesh_id, car_is_dynamic)) =
5550                    self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
5551                        (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
5552                    })
5553            {
5554                let mesh_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
5555                let mut phys: PlayerVehiclePhysics3D = {
5556                    let Self { player_physics, .. } = self;
5557                    *player_physics
5558                };
5559                let mut flat_tr: Transform3D = Transform3D::new(
5560                    Vec3::new(
5561                        cur_tr.get_position().get_x(),
5562                        0.0,
5563                        cur_tr.get_position().get_z(),
5564                    ),
5565                    cur_tr.get_yaw_rad(),
5566                    cur_tr.get_scale(),
5567                );
5568                let flat_obb: OrientedBox3D = flat_tr.to_oriented_box(mesh_bounds);
5569                let ground_margin: f32 = flat_obb
5570                    .get_half_extents()
5571                    .get_x()
5572                    .max(flat_obb.get_half_extents().get_z());
5573                let yaw_now: f32 = flat_tr.get_yaw_rad();
5574                let fwd: Vec3 = Vec3::new(-yaw_now.sin(), 0.0, -yaw_now.cos());
5575                let right: Vec3 = Vec3::new(yaw_now.cos(), 0.0, -yaw_now.sin());
5576                let mut vel: Vec3 = phys.get_vel();
5577                let mut v_fwd: f32 = vel.dot(fwd);
5578                let mut v_lat: f32 = vel.dot(right);
5579                let speed_now: f32 = (v_fwd * v_fwd + v_lat * v_lat).sqrt();
5580                let was_boosting: bool = phys.get_boost_active();
5581                let mut boost_charge: f32 = phys.get_boost_charge();
5582                let can_boost: bool = if was_boosting {
5583                    boost_charge > 0.0
5584                } else {
5585                    boost_charge >= VEHICLE_BOOST_MIN_REIGNITE
5586                };
5587                let boost_active: bool = boost_pressed && can_boost && throttle >= -0.05;
5588                let was_drifting: bool = phys.get_drift_active();
5589                let drift_active: bool = drift_pressed
5590                    && speed_now > VEHICLE_DRIFT_MIN_SPEED_MPS
5591                    && v_fwd > VEHICLE_DRIFT_MIN_FWD_MPS;
5592                if boost_active {
5593                    boost_charge = (boost_charge - VEHICLE_BOOST_DRAIN_PER_SEC * sub_dt).max(0.0);
5594                } else {
5595                    let regen_rate: f32 = if drift_active {
5596                        VEHICLE_BOOST_DRIFT_REGEN_PER_SEC
5597                    } else {
5598                        VEHICLE_BOOST_REGEN_PER_SEC
5599                    };
5600                    boost_charge = (boost_charge + regen_rate * sub_dt).min(1.0);
5601                }
5602                let mut drift_duration: f32 = phys.get_drift_duration();
5603                let mut drift_peak_slip: f32 = phys.get_drift_peak_slip();
5604                let mut exit_kick_triggered: bool = false;
5605                if drift_active {
5606                    drift_duration += sub_dt;
5607                } else if was_drifting {
5608                    if drift_duration >= VEHICLE_DRIFT_EXIT_MIN_SECS
5609                        && drift_peak_slip >= VEHICLE_DRIFT_EXIT_MIN_SLIP_RAD
5610                        && v_fwd > 4.0
5611                    {
5612                        let slip_snap: f32 = v_lat.abs() * 0.45;
5613                        v_fwd = (v_fwd + VEHICLE_DRIFT_EXIT_KICK_MPS + slip_snap)
5614                            .min(VEHICLE_BOOST_TOP_SPEED_MPS);
5615                        exit_kick_triggered = true;
5616                    }
5617                    drift_duration = 0.0;
5618                    drift_peak_slip = 0.0;
5619                } else {
5620                    drift_duration = 0.0;
5621                    drift_peak_slip = 0.0;
5622                }
5623                let eff_throttle: f32 = if boost_active && throttle >= 0.0 {
5624                    throttle.max(1.0)
5625                } else {
5626                    throttle
5627                };
5628                let top_fwd: f32 = if boost_active {
5629                    VEHICLE_BOOST_TOP_SPEED_MPS
5630                } else {
5631                    VEHICLE_NORMAL_TOP_SPEED_MPS
5632                };
5633                let long_accel: f32 = if eff_throttle > 0.05 {
5634                    if v_fwd < -0.5 {
5635                        VEHICLE_BRAKE_DECEL_MPS2
5636                    } else {
5637                        let launch: f32 = VEHICLE_NORMAL_ACCEL_MPS2
5638                            + VEHICLE_LAUNCH_BONUS_MPS2
5639                                * (-(v_fwd.abs()) / VEHICLE_LAUNCH_TAPER_MPS).exp();
5640                        let mult: f32 = if boost_active {
5641                            VEHICLE_BOOST_THRUST_MULT
5642                        } else {
5643                            1.0
5644                        };
5645                        let speed_ratio: f32 = (v_fwd / top_fwd).clamp(0.0, 1.0);
5646                        let taper: f32 = (1.0 - speed_ratio * speed_ratio * 0.65).max(0.18);
5647                        eff_throttle * launch * mult * taper
5648                    }
5649                } else if eff_throttle < -0.05 {
5650                    if v_fwd > 0.5 {
5651                        -VEHICLE_BRAKE_DECEL_MPS2
5652                    } else {
5653                        let launch: f32 = VEHICLE_NORMAL_ACCEL_MPS2
5654                            + VEHICLE_LAUNCH_BONUS_MPS2
5655                                * (-(v_fwd.abs()) / VEHICLE_LAUNCH_TAPER_MPS).exp();
5656                        let speed_ratio: f32 =
5657                            ((-v_fwd) / VEHICLE_REVERSE_TOP_SPEED_MPS).clamp(0.0, 1.0);
5658                        let taper: f32 = (1.0 - speed_ratio * speed_ratio * 0.65).max(0.2);
5659                        eff_throttle * launch * taper
5660                    }
5661                } else {
5662                    let handbrake_drag: f32 = if drift_pressed { 4.5 } else { 0.0 };
5663                    let drag: f32 = (VEHICLE_ROLLING_DRAG + handbrake_drag) * v_fwd
5664                        + VEHICLE_AERO_DRAG * v_fwd * v_fwd.abs();
5665                    -drag
5666                };
5667                v_fwd += long_accel * sub_dt;
5668                if eff_throttle.abs() <= 0.05 && v_fwd.abs() < 0.08 && v_lat.abs() < 0.08 {
5669                    v_fwd = 0.0;
5670                    v_lat = 0.0;
5671                } else {
5672                    let max_allowed_fwd: f32 = if boost_active || exit_kick_triggered {
5673                        VEHICLE_BOOST_TOP_SPEED_MPS
5674                    } else if v_fwd > VEHICLE_NORMAL_TOP_SPEED_MPS {
5675                        (v_fwd - 10.0 * sub_dt).max(VEHICLE_NORMAL_TOP_SPEED_MPS)
5676                    } else {
5677                        VEHICLE_NORMAL_TOP_SPEED_MPS
5678                    };
5679                    v_fwd = v_fwd.clamp(-VEHICLE_REVERSE_TOP_SPEED_MPS, max_allowed_fwd);
5680                }
5681                let slip_before: f32 = v_lat.atan2(v_fwd.abs().max(1.0));
5682                let lat_grip: f32 = if drift_active {
5683                    let extra_scrub: f32 = ((slip_before.abs() - 0.66).max(0.0)) * 5.2;
5684                    VEHICLE_DRIFT_LAT_GRIP + extra_scrub
5685                } else {
5686                    VEHICLE_NORMAL_LAT_GRIP
5687                };
5688                v_lat *= (-lat_grip * sub_dt).exp();
5689                let mut yaw_rate: f32 = phys.get_yaw_rate();
5690                let steer_sign: f32 =
5691                    if v_fwd < -0.35 || (v_fwd.abs() <= 0.35 && eff_throttle < -0.05) {
5692                        -1.0
5693                    } else {
5694                        1.0
5695                    };
5696                let active_speed: f32 = (v_fwd * v_fwd + v_lat * v_lat).sqrt();
5697                let base_auth: f32 = (0.90 + 0.10 * (active_speed / 8.0).min(1.0)).min(1.0);
5698                let high_speed_calm: f32 = if drift_active {
5699                    1.0
5700                } else {
5701                    (1.0 - ((active_speed - 28.0).max(0.0) / 60.0)).clamp(0.72, 1.0)
5702                };
5703                let steer_authority: f32 = base_auth * high_speed_calm;
5704                let yaw_gain: f32 = if drift_active {
5705                    VEHICLE_DRIFT_YAW_GAIN
5706                } else {
5707                    VEHICLE_NORMAL_YAW_GAIN
5708                };
5709                let target_yaw_rate: f32 = if steer.abs() > 0.05 {
5710                    -steer * steer_sign * yaw_gain * steer_authority
5711                } else {
5712                    0.0
5713                };
5714                let yaw_resp: f32 = if drift_active { 12.0 } else { 32.0 };
5715                let yaw_blend: f32 = 1.0 - (-yaw_resp * sub_dt).exp();
5716                yaw_rate += (target_yaw_rate - yaw_rate) * yaw_blend;
5717                if drift_active {
5718                    let slip_excess: f32 = (slip_before.abs() - 0.56).max(0.0);
5719                    if slip_excess > 0.0 {
5720                        let align_torque: f32 = -slip_before.signum() * slip_excess * 5.8;
5721                        yaw_rate += align_torque * sub_dt;
5722                    }
5723                    if steer.abs() > 0.05 && slip_before.abs() < 0.28 {
5724                        let kick_dir: f32 = -steer.signum();
5725                        v_lat += -kick_dir * 6.5 * sub_dt;
5726                    }
5727                }
5728                if steer.abs() <= 0.05 && yaw_rate.abs() < 0.01 && active_speed < 0.1 {
5729                    yaw_rate = 0.0;
5730                }
5731                yaw_rate = yaw_rate.clamp(-VEHICLE_MAX_YAW_RATE_RAD_S, VEHICLE_MAX_YAW_RATE_RAD_S);
5732                vel = fwd.scale(v_fwd).add(right.scale(v_lat));
5733                let (ccd_moved, wall_impact, wall_contact, wall_normal): (bool, f32, Vec3, Vec3) =
5734                    self.step_rigid_vehicle_static_ccd(
5735                        &mut flat_tr,
5736                        &mut vel,
5737                        &mut yaw_rate,
5738                        (
5739                            1.0 / VEHICLE_PLAYER_MASS_KG,
5740                            1.0 / VEHICLE_PLAYER_INERTIA_YAW,
5741                        ),
5742                        (car_idx, mesh_bounds),
5743                        VehicleCcdStepCtx3D {
5744                            sub_dt,
5745                            ground_limits,
5746                            ground_margin,
5747                        },
5748                    );
5749                let final_yaw: f32 = flat_tr.get_yaw_rad();
5750                let final_fwd: Vec3 = Vec3::new(-final_yaw.sin(), 0.0, -final_yaw.cos());
5751                let final_right: Vec3 = Vec3::new(final_yaw.cos(), 0.0, -final_yaw.sin());
5752                let post_vfwd: f32 = vel.dot(final_fwd);
5753                let post_vlat: f32 = vel.dot(final_right);
5754                let post_slip: f32 = if post_vfwd.abs() + post_vlat.abs() > 1.0 {
5755                    post_vlat.atan2(post_vfwd.abs().max(1.0))
5756                } else {
5757                    0.0
5758                };
5759                if drift_active {
5760                    drift_peak_slip = drift_peak_slip.max(post_slip.abs());
5761                }
5762                let mut cam_shake: f32 = phys.get_camera_shake() * (-7.5 * sub_dt).exp();
5763                if cam_shake < 0.004 {
5764                    cam_shake = 0.0;
5765                }
5766                let mut body_pitch: f32 = phys.get_body_pitch_rad();
5767                if wall_impact > 2.8 {
5768                    let imp_norm: f32 = ((wall_impact - 2.0) / 26.0).clamp(0.0, 1.0);
5769                    cam_shake = cam_shake.max(imp_norm * 0.65);
5770                    if wall_normal.dot(final_fwd) < -0.35 {
5771                        body_pitch = (body_pitch - imp_norm * 0.055).clamp(-0.08, 0.06);
5772                    }
5773                    self.emit_collision_sparks(wall_contact, wall_normal, imp_norm);
5774                }
5775                let target_roll: f32 = if post_vlat.abs() > 0.25 {
5776                    (-post_vlat * 0.011).clamp(-0.085, 0.085)
5777                } else {
5778                    0.0
5779                };
5780                let target_pitch: f32 = if boost_active {
5781                    0.036
5782                } else if long_accel > 8.0 {
5783                    0.018
5784                } else if long_accel < -15.0 {
5785                    -0.028
5786                } else {
5787                    0.0
5788                };
5789                let susp_blend: f32 = 1.0 - (-10.0 * sub_dt).exp();
5790                let mut body_roll: f32 = phys.get_body_roll_rad()
5791                    + (target_roll - phys.get_body_roll_rad()) * susp_blend;
5792                body_pitch += (target_pitch - body_pitch) * susp_blend;
5793                if body_roll.abs() < 0.0005 && target_roll == 0.0 {
5794                    body_roll = 0.0;
5795                }
5796                if body_pitch.abs() < 0.0005 && target_pitch == 0.0 {
5797                    body_pitch = 0.0;
5798                }
5799                let target_fov_boost: f32 = if boost_active {
5800                    CAMERA_BOOST_FOV_MAX_DEG
5801                } else if exit_kick_triggered {
5802                    CAMERA_BOOST_FOV_MAX_DEG * 0.6
5803                } else if drift_active && post_slip.abs() > 0.18 {
5804                    3.2
5805                } else {
5806                    0.0
5807                };
5808                let fov_blend: f32 = 1.0 - (-5.5 * sub_dt).exp();
5809                let mut cam_fov_boost: f32 = phys.get_camera_fov_boost()
5810                    + (target_fov_boost - phys.get_camera_fov_boost()) * fov_blend;
5811                if cam_fov_boost < 0.02 && target_fov_boost == 0.0 {
5812                    cam_fov_boost = 0.0;
5813                }
5814                phys.set_vel(vel);
5815                phys.set_yaw_rate(yaw_rate);
5816                phys.set_body_roll_rad(body_roll);
5817                phys.set_body_pitch_rad(body_pitch);
5818                phys.set_boost_active(boost_active);
5819                phys.set_boost_charge(boost_charge);
5820                phys.set_drift_active(drift_active);
5821                phys.set_drift_slip_angle(post_slip);
5822                phys.set_drift_duration(drift_duration);
5823                phys.set_drift_peak_slip(drift_peak_slip);
5824                phys.set_camera_fov_boost(cam_fov_boost);
5825                phys.set_camera_shake(cam_shake);
5826                {
5827                    let Self { player_physics, .. } = self;
5828                    *player_physics = phys;
5829                }
5830                let lift_y: f32 = (body_roll.abs() * 0.55 + body_pitch.abs() * 0.95).min(0.06);
5831                let mut visual_tr: Transform3D = Transform3D {
5832                    position: Vec3::new(
5833                        flat_tr.get_position().get_x(),
5834                        lift_y,
5835                        flat_tr.get_position().get_z(),
5836                    ),
5837                    rotation: Quat::from_euler_yxz(final_yaw, body_pitch, body_roll),
5838                    scale: flat_tr.get_scale(),
5839                };
5840                if (body_roll != 0.0 || body_pitch != 0.0)
5841                    && self
5842                        .mesh_oriented_box_static_collision(
5843                            visual_tr.to_oriented_box(mesh_bounds),
5844                            Some(car_idx),
5845                        )
5846                        .is_some()
5847                {
5848                    visual_tr = flat_tr;
5849                }
5850                let tr_changed: bool = ccd_moved || visual_tr != cur_tr;
5851                if tr_changed {
5852                    let world_b: AxisAlignedBox3D = visual_tr.transform_bounds(mesh_bounds);
5853                    if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
5854                        car_mut.set_transform(visual_tr);
5855                        car_mut.set_world_bounds(world_b);
5856                    }
5857                    player_moved_any = true;
5858                    if car_is_dynamic {
5859                        any_dynamic_moved = true;
5860                    } else {
5861                        any_static_moved = true;
5862                    }
5863                }
5864            }
5865            let traffic_count: usize = self.traffic_vehicle_count();
5866            for slot_idx in 0..traffic_count {
5867                let mut npc: NpcVehicle3D = {
5868                    let Self {
5869                        traffic_vehicles, ..
5870                    } = self;
5871                    traffic_vehicles[slot_idx]
5872                };
5873                let npc_idx: usize = npc.get_object_index();
5874                let Some((cur_tr, mesh_id, is_dynamic)) =
5875                    self.get_objects().get(npc_idx).map(|obj: &SceneObject3D| {
5876                        (obj.get_transform(), obj.get_mesh_id(), obj.get_is_dynamic())
5877                    })
5878                else {
5879                    continue;
5880                };
5881                let local_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
5882                let mut tr: Transform3D = Transform3D::new(
5883                    Vec3::new(
5884                        cur_tr.get_position().get_x(),
5885                        0.0,
5886                        cur_tr.get_position().get_z(),
5887                    ),
5888                    cur_tr.get_yaw_rad(),
5889                    cur_tr.get_scale(),
5890                );
5891                let obb_npc: OrientedBox3D = tr.to_oriented_box(local_bounds);
5892                let margin: f32 = obb_npc
5893                    .get_half_extents()
5894                    .get_x()
5895                    .max(obb_npc.get_half_extents().get_z());
5896                let pos: Vec3 = tr.get_position();
5897                let yaw: f32 = tr.get_yaw_rad();
5898                let fwd: Vec3 = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
5899                let right: Vec3 = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
5900                let mut vel: Vec3 = npc.get_vel();
5901                let mut yaw_rate: f32 = npc.get_yaw_rate();
5902                let mut recovery: f32 = npc.get_recovery_timer();
5903                if recovery > 0.0 {
5904                    recovery = (recovery - sub_dt).max(0.0);
5905                    let mut v_fwd: f32 = vel.dot(fwd);
5906                    let mut v_lat: f32 = vel.dot(right);
5907                    v_fwd *= (-1.15 * sub_dt).exp();
5908                    v_lat *= (-2.85 * sub_dt).exp();
5909                    vel = fwd.scale(v_fwd).add(right.scale(v_lat));
5910                    yaw_rate *= (-2.3 * sub_dt).exp();
5911                    if recovery <= 0.0 && yaw_rate.abs() < 0.8 {
5912                        let (route_id, wp_idx, wp_pos): (u8, usize, Vec3) =
5913                            NpcVehicle3D::nearest_open_waypoint(pos);
5914                        npc.set_route_id(route_id);
5915                        npc.set_waypoint_idx(wp_idx);
5916                        npc.set_nav_target(wp_pos);
5917                    }
5918                } else {
5919                    let mut v_fwd: f32 = vel.dot(fwd);
5920                    let mut v_lat: f32 = vel.dot(right);
5921                    let target_pt: Vec3 = if npc.get_free_roam_mode() {
5922                        let cur_tgt: Vec3 = npc.get_nav_target();
5923                        let to_t: Vec3 = Vec3::new(
5924                            cur_tgt.get_x() - pos.get_x(),
5925                            0.0,
5926                            cur_tgt.get_z() - pos.get_z(),
5927                        );
5928                        if to_t.length_sq() < 49.0 {
5929                            let wps: &[(f32, f32)] =
5930                                NpcVehicle3D::route_waypoints(npc.get_route_id());
5931                            let next_wp: usize = (npc.get_waypoint_idx() + 1) % wps.len();
5932                            let next_pt: Vec3 = Vec3::new(wps[next_wp].0, 0.0, wps[next_wp].1);
5933                            npc.set_waypoint_idx(next_wp);
5934                            npc.set_nav_target(next_pt);
5935                            next_pt
5936                        } else {
5937                            cur_tgt
5938                        }
5939                    } else {
5940                        let cur_s: f32 = npc.get_loop_arc_s();
5941                        let lane_u: f32 = npc.get_loop_lane_u();
5942                        let dir: f32 = npc.get_loop_dir();
5943                        let (_, base_yaw_at_s): (Vec3, f32) = Self::loop_pose_at(cur_s, lane_u);
5944                        let tan_yaw: f32 = if dir >= 0.0 {
5945                            base_yaw_at_s
5946                        } else {
5947                            base_yaw_at_s + PI
5948                        };
5949                        let tan_dir: Vec3 = Vec3::new(-tan_yaw.sin(), 0.0, -tan_yaw.cos());
5950                        let prog: f32 = vel.dot(tan_dir).max(0.0) * sub_dt;
5951                        let next_s: f32 = (cur_s + dir * prog).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
5952                        npc.set_loop_arc_s(next_s);
5953                        let look_s: f32 = (next_s + dir * 11.0).rem_euclid(CITY_LOOP_TOTAL_LENGTH);
5954                        let (look_pt, _): (Vec3, f32) = Self::loop_pose_at(look_s, lane_u);
5955                        npc.set_nav_target(look_pt);
5956                        look_pt
5957                    };
5958                    let to_target: Vec3 = Vec3::new(
5959                        target_pt.get_x() - pos.get_x(),
5960                        0.0,
5961                        target_pt.get_z() - pos.get_z(),
5962                    );
5963                    let desired_yaw: f32 = if to_target.length_sq() > 1.0e-4 {
5964                        (-to_target.get_x()).atan2(-to_target.get_z())
5965                    } else {
5966                        yaw
5967                    };
5968                    let mut yaw_err: f32 = Self::wrap_angle_rad(desired_yaw - yaw);
5969                    let mut obstacle_slow: f32 = 1.0;
5970                    if npc.get_free_roam_mode() {
5971                        let probe_dist: f32 = (v_fwd.abs() * 0.55 + 5.5).clamp(5.0, 11.0);
5972                        let probe_tr: Transform3D =
5973                            Transform3D::new(pos.add(fwd.scale(probe_dist)), yaw, tr.get_scale());
5974                        if self
5975                            .mesh_oriented_box_static_collision(
5976                                probe_tr.to_oriented_box(local_bounds),
5977                                Some(npc_idx),
5978                            )
5979                            .is_some()
5980                        {
5981                            let left_yaw: f32 = yaw + 0.55;
5982                            let right_yaw: f32 = yaw - 0.55;
5983                            let left_fwd: Vec3 = Vec3::new(-left_yaw.sin(), 0.0, -left_yaw.cos());
5984                            let right_fwd: Vec3 =
5985                                Vec3::new(-right_yaw.sin(), 0.0, -right_yaw.cos());
5986                            let left_clear: bool = self
5987                                .mesh_oriented_box_static_collision(
5988                                    Transform3D::new(
5989                                        pos.add(left_fwd.scale(probe_dist)),
5990                                        left_yaw,
5991                                        tr.get_scale(),
5992                                    )
5993                                    .to_oriented_box(local_bounds),
5994                                    Some(npc_idx),
5995                                )
5996                                .is_none();
5997                            let right_clear: bool = self
5998                                .mesh_oriented_box_static_collision(
5999                                    Transform3D::new(
6000                                        pos.add(right_fwd.scale(probe_dist)),
6001                                        right_yaw,
6002                                        tr.get_scale(),
6003                                    )
6004                                    .to_oriented_box(local_bounds),
6005                                    Some(npc_idx),
6006                                )
6007                                .is_none();
6008                            if left_clear && !right_clear {
6009                                yaw_err = 0.85;
6010                                obstacle_slow = 0.65;
6011                            } else if right_clear && !left_clear {
6012                                yaw_err = -0.85;
6013                                obstacle_slow = 0.65;
6014                            } else if left_clear {
6015                                yaw_err = if yaw_err >= 0.0 { 0.85 } else { -0.85 };
6016                                obstacle_slow = 0.7;
6017                            } else {
6018                                yaw_err = 1.1;
6019                                obstacle_slow = 0.25;
6020                            }
6021                        }
6022                    }
6023                    let mut target_speed: f32 = npc.get_cruise_speed() * obstacle_slow;
6024                    if let Some(gap_m) =
6025                        self.npc_forward_blocking_gap(npc_idx, pos, fwd, right, v_fwd)
6026                    {
6027                        if gap_m < 9.5 {
6028                            target_speed = 0.0;
6029                        } else if gap_m < 14.5 {
6030                            target_speed *= ((gap_m - 9.5) / 5.0).clamp(0.0, 1.0);
6031                        }
6032                    }
6033                    let speed_diff: f32 = target_speed - v_fwd;
6034                    let accel_rate: f32 = if speed_diff < 0.0 { 36.0 } else { 18.0 };
6035                    v_fwd += speed_diff.clamp(-accel_rate * sub_dt, accel_rate * sub_dt);
6036                    if target_speed <= 0.05 && v_fwd.abs() < 0.15 {
6037                        v_fwd = 0.0;
6038                    }
6039                    v_lat *= (-8.5 * sub_dt).exp();
6040                    let target_omega: f32 = (yaw_err * 3.8).clamp(-2.6, 2.6);
6041                    let omega_blend: f32 = 1.0 - (-12.0 * sub_dt).exp();
6042                    yaw_rate += (target_omega - yaw_rate) * omega_blend;
6043                    if v_fwd.abs() < 0.1 {
6044                        yaw_rate *= (-8.0 * sub_dt).exp();
6045                    }
6046                    vel = fwd.scale(v_fwd).add(right.scale(v_lat));
6047                }
6048                let (npc_moved, npc_wall_imp, npc_wall_cp, npc_wall_n): (bool, f32, Vec3, Vec3) =
6049                    self.step_rigid_vehicle_static_ccd(
6050                        &mut tr,
6051                        &mut vel,
6052                        &mut yaw_rate,
6053                        (
6054                            1.0 / npc.get_mass().max(100.0),
6055                            1.0 / VEHICLE_NPC_INERTIA_YAW,
6056                        ),
6057                        (npc_idx, local_bounds),
6058                        VehicleCcdStepCtx3D {
6059                            sub_dt,
6060                            ground_limits,
6061                            ground_margin: margin,
6062                        },
6063                    );
6064                if npc_wall_imp > 3.5 {
6065                    let spark_int: f32 = ((npc_wall_imp - 2.5) / 22.0).clamp(0.15, 0.9);
6066                    self.emit_collision_sparks(npc_wall_cp, npc_wall_n, spark_int);
6067                    if npc.get_free_roam_mode() && recovery <= 0.0 {
6068                        let wps: &[(f32, f32)] = NpcVehicle3D::route_waypoints(npc.get_route_id());
6069                        let next_wp: usize = (npc.get_waypoint_idx() + 1) % wps.len();
6070                        npc.set_waypoint_idx(next_wp);
6071                        npc.set_nav_target(Vec3::new(wps[next_wp].0, 0.0, wps[next_wp].1));
6072                    }
6073                }
6074                npc.set_vel(vel);
6075                npc.set_yaw_rate(yaw_rate);
6076                npc.set_recovery_timer(recovery);
6077                {
6078                    let Self {
6079                        traffic_vehicles, ..
6080                    } = self;
6081                    traffic_vehicles[slot_idx] = npc;
6082                }
6083                if npc_moved {
6084                    let world_b: AxisAlignedBox3D = tr.transform_bounds(local_bounds);
6085                    if let Some(obj) = self.get_mut_objects().get_mut(npc_idx) {
6086                        obj.set_transform(tr);
6087                        obj.set_world_bounds(world_b);
6088                    }
6089                    if is_dynamic {
6090                        any_dynamic_moved = true;
6091                    } else {
6092                        any_static_moved = true;
6093                    }
6094                }
6095            }
6096            let (dyn_moved, dyn_imp, _dyn_cp, _dyn_n): (bool, f32, Vec3, Vec3) =
6097                self.resolve_dynamic_vehicle_collisions(ground_limits);
6098            if dyn_moved {
6099                any_dynamic_moved = true;
6100                player_moved_any = true;
6101            }
6102            if dyn_imp > 2.5 {
6103                let imp_norm: f32 = ((dyn_imp - 2.0) / 24.0).clamp(0.0, 1.0);
6104                let Self { player_physics, .. } = self;
6105                let next_shake: f32 = player_physics.get_camera_shake().max(imp_norm * 0.70);
6106                player_physics.set_camera_shake(next_shake);
6107            }
6108        }
6109        if let Some(car_idx) = car_opt
6110            && let Some((car_tr, mesh_id)) = self
6111                .get_objects()
6112                .get(car_idx)
6113                .map(|car: &SceneObject3D| (car.get_transform(), car.get_mesh_id()))
6114        {
6115            let car_bounds: AxisAlignedBox3D = self.local_bounds_for_mesh(mesh_id);
6116            let mut safe_tr: Transform3D = car_tr;
6117            let car_obb: OrientedBox3D = safe_tr.to_oriented_box(car_bounds);
6118            let car_margin: f32 = car_obb
6119                .get_half_extents()
6120                .get_x()
6121                .max(car_obb.get_half_extents().get_z());
6122            if self.depenetrate_vehicle_horizontally(
6123                &mut safe_tr,
6124                car_bounds,
6125                car_idx,
6126                ground_limits,
6127                car_margin,
6128            ) {
6129                let wb: AxisAlignedBox3D = safe_tr.transform_bounds(car_bounds);
6130                if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
6131                    car_mut.set_transform(safe_tr);
6132                    car_mut.set_world_bounds(wb);
6133                }
6134                player_moved_any = true;
6135                any_dynamic_moved = true;
6136            }
6137            let final_car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
6138            let car_pos: Vec3 = final_car_tr.get_position();
6139            let yaw: f32 = final_car_tr.get_yaw_rad();
6140            let car_fwd: Vec3 = Vec3::new(-yaw.sin(), 0.0, -yaw.cos());
6141            let car_right: Vec3 = Vec3::new(yaw.cos(), 0.0, -yaw.sin());
6142            let phys: PlayerVehiclePhysics3D = {
6143                let Self { player_physics, .. } = self;
6144                *player_physics
6145            };
6146            if player_moved_any || phys.get_boost_active() || phys.get_drift_active() {
6147                let beam_dir: Vec3 = Vec3::new(car_fwd.get_x(), -0.14, car_fwd.get_z()).normalize();
6148                if self.get_spot_lights().len() >= 2 {
6149                    let front_center: Vec3 = car_pos
6150                        .add(car_fwd.scale(2.2))
6151                        .add(Vec3::new(0.0, 0.95, 0.0));
6152                    let left_pos: Vec3 = front_center.sub(car_right.scale(0.85));
6153                    let right_pos: Vec3 = front_center.add(car_right.scale(0.85));
6154                    let spots: &mut Vec<SpotLight3D> = self.get_mut_spot_lights();
6155                    spots[0].set_position(left_pos);
6156                    spots[0].set_direction(beam_dir);
6157                    spots[1].set_position(right_pos);
6158                    spots[1].set_direction(beam_dir);
6159                }
6160                if let Some(tail_light) = self.get_mut_point_lights().first_mut()
6161                    && tail_light.get_color().get_x() > 0.90
6162                    && tail_light.get_color().get_y() < 0.15
6163                {
6164                    let rear_pos: Vec3 = car_pos
6165                        .sub(car_fwd.scale(2.9))
6166                        .add(Vec3::new(0.0, 0.95, 0.0));
6167                    tail_light.set_position(rear_pos);
6168                    if phys.get_boost_active() {
6169                        tail_light.set_color(Vec3::new(1.0, 0.14, 0.06));
6170                        tail_light.set_intensity(4.5);
6171                        tail_light.set_radius(10.5);
6172                    } else if phys.get_drift_active() || throttle < -0.15 {
6173                        tail_light.set_color(Vec3::new(1.0, 0.06, 0.18));
6174                        tail_light.set_intensity(3.85);
6175                        tail_light.set_radius(9.6);
6176                    } else {
6177                        tail_light.set_color(Vec3::new(1.0, 0.09, 0.27));
6178                        tail_light.set_intensity(1.85);
6179                        tail_light.set_radius(8.5);
6180                    }
6181                }
6182                if phys.get_boost_active() && (sim_tick & 1) == 0 {
6183                    self.emit_boost_flame(car_pos, car_fwd, car_right, phys.get_vel());
6184                }
6185                if phys.get_drift_active()
6186                    && phys.get_drift_slip_angle().abs() > 0.12
6187                    && (sim_tick & 1) == 0
6188                {
6189                    self.emit_drift_smoke(
6190                        car_pos,
6191                        car_fwd,
6192                        car_right,
6193                        phys.get_drift_slip_angle().abs(),
6194                    );
6195                } else if throttle.abs() > 0.25
6196                    && !phys.get_boost_active()
6197                    && (sim_tick & 3) == 0
6198                    && self.get_niagara().get_active_count() < 24
6199                {
6200                    let exhaust_pos: Vec3 = car_pos
6201                        .sub(car_fwd.scale(2.3))
6202                        .add(Vec3::new(0.0, 0.42, 0.0));
6203                    let mut spark_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6204                    spark_cfg.set_origin(exhaust_pos);
6205                    spark_cfg.set_base_velocity(car_fwd.scale(-4.5).add(Vec3::new(0.0, 1.1, 0.0)));
6206                    spark_cfg.set_start_size_m(0.11);
6207                    spark_cfg.set_end_size_m(0.03);
6208                    self.get_mut_niagara().emit_burst(1, &spark_cfg);
6209                }
6210            }
6211            let cam_mode: u8 = self.get_camera_mode();
6212            let fov_boost: f32 = phys.get_camera_fov_boost();
6213            let chase_pullback: f32 = fov_boost * 0.14;
6214            let reverse_speed_mps: f32 = -phys.get_vel().dot(car_fwd);
6215            let reverse_blend: f32 = ((reverse_speed_mps - 0.5) / 8.0).clamp(0.0, 1.0);
6216            let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
6217                1 => {
6218                    let eye: Vec3 = Vec3::new(
6219                        car_pos.get_x() - yaw.sin() * 1.4,
6220                        2.15,
6221                        car_pos.get_z() - yaw.cos() * 1.4,
6222                    );
6223                    let tgt: Vec3 = Vec3::new(
6224                        car_pos.get_x() - yaw.sin() * 18.0,
6225                        1.8,
6226                        car_pos.get_z() - yaw.cos() * 18.0,
6227                    );
6228                    (eye, tgt)
6229                }
6230                2 => {
6231                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
6232                    self.set_camera_orbit_rad(orbit);
6233                    let eye: Vec3 = Vec3::new(
6234                        car_pos.get_x() + orbit.sin() * 10.5,
6235                        5.2,
6236                        car_pos.get_z() + orbit.cos() * 10.5,
6237                    );
6238                    (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
6239                }
6240                3 => {
6241                    let eye: Vec3 = Vec3::new(
6242                        car_pos.get_x() + yaw.sin() * 18.0,
6243                        18.5,
6244                        car_pos.get_z() + yaw.cos() * 18.0,
6245                    );
6246                    (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
6247                }
6248                4 => {
6249                    let cur_cam: Camera3D = self.get_camera();
6250                    let fwd_c: Vec3 = cur_cam.forward();
6251                    let right_c: Vec3 = cur_cam.right();
6252                    let moved: Vec3 = cur_cam
6253                        .get_position()
6254                        .add(fwd_c.scale(throttle * 18.0 * dt))
6255                        .add(right_c.scale(steer * 14.0 * dt));
6256                    let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
6257                    (eye, eye.add(fwd_c.scale(16.0)))
6258                }
6259                5 => {
6260                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
6261                    self.set_camera_orbit_rad(orbit);
6262                    let eye: Vec3 = Vec3::new(
6263                        car_pos.get_x() + orbit.sin() * 7.8,
6264                        3.6 + (orbit * 1.5).sin() * 1.4,
6265                        car_pos.get_z() + orbit.cos() * 13.5,
6266                    );
6267                    (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
6268                }
6269                _ => {
6270                    let chase_dist: f32 = 9.8 + chase_pullback + reverse_blend * 2.4;
6271                    let eye: Vec3 = Vec3::new(
6272                        car_pos.get_x() + yaw.sin() * chase_dist,
6273                        4.25 + chase_pullback * 0.12 + reverse_blend * 0.55,
6274                        car_pos.get_z() + yaw.cos() * chase_dist,
6275                    );
6276                    let tgt: Vec3 = Vec3::new(
6277                        car_pos.get_x() - yaw.sin() * 16.0,
6278                        2.40 - reverse_blend * 0.65,
6279                        car_pos.get_z() - yaw.cos() * 16.0,
6280                    );
6281                    (eye, tgt)
6282                }
6283            };
6284            let shake_amp: f32 = phys.get_camera_shake();
6285            if shake_amp > 0.005 {
6286                let phase: f32 = self.get_world_time_secs() * 54.0;
6287                let sx: f32 = phase.sin() * shake_amp * 0.34;
6288                let sy: f32 = (phase * 1.37).cos() * shake_amp * 0.22;
6289                desired_eye = desired_eye
6290                    .add(car_right.scale(sx))
6291                    .add(Vec3::new(0.0, sy, 0.0));
6292            }
6293            let boom_anchor: Vec3 =
6294                Vec3::new(car_pos.get_x(), car_pos.get_y() + 1.8, car_pos.get_z());
6295            let boom_vec: Vec3 = desired_eye.sub(boom_anchor);
6296            let boom_len: f32 = boom_vec.length();
6297            if boom_len > 0.25 {
6298                let boom_dir: Vec3 = boom_vec.scale(1.0 / boom_len);
6299                if let Some(hit) =
6300                    self.raycast_solid_meshes(boom_anchor, boom_dir, boom_len, Some(car_idx))
6301                {
6302                    let safe_dist: f32 = (hit.get_distance() - 0.55).max(0.8);
6303                    desired_eye = boom_anchor.add(boom_dir.scale(safe_dist));
6304                }
6305            }
6306            let cam_probe: OrientedBox3D = OrientedBox3D::from_bounds(AxisAlignedBox3D::new(
6307                desired_eye.sub(Vec3::splat(0.45)),
6308                desired_eye.add(Vec3::splat(0.45)),
6309            ));
6310            if let Some(hit) = self.mesh_oriented_box_collision(cam_probe, Some(car_idx)) {
6311                desired_eye = desired_eye.add(hit.get_normal().scale(hit.get_penetration() + 0.1));
6312            }
6313            let prev_cam: Camera3D = self.get_camera();
6314            let mut cam: Camera3D = prev_cam;
6315            let follow_rate: f32 = 7.0 + reverse_blend * 5.0;
6316            let smooth: f32 = (dt * follow_rate).clamp(0.05, 1.0);
6317            cam.set_position(cam.get_position().lerp(desired_eye, smooth));
6318            let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
6319            cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
6320            cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
6321            cam.set_fov_deg(CAMERA_BASE_FOV_DEG + fov_boost);
6322            self.set_camera(cam);
6323            if cam != prev_cam {
6324                self.bump_world_revision();
6325            }
6326        }
6327        let Self {
6328            objects,
6329            mesh_library,
6330            ..
6331        } = self;
6332        for obj in objects.iter_mut() {
6333            let spin: f32 = obj.get_spin_speed();
6334            if spin.abs() > 0.001 {
6335                let mut object_transform: Transform3D = obj.get_transform();
6336                object_transform.set_yaw_rad(object_transform.get_yaw_rad() + spin * dt);
6337                obj.set_transform(object_transform);
6338                let local_bounds: AxisAlignedBox3D = mesh_library
6339                    .get(obj.get_mesh_id())
6340                    .and_then(|color_item: &MeshLodChain| color_item.get_levels().first())
6341                    .map(Mesh3D::get_bounds)
6342                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
6343                obj.set_world_bounds(object_transform.transform_bounds(local_bounds));
6344                if obj.get_is_dynamic() {
6345                    any_dynamic_moved = true;
6346                } else {
6347                    any_static_moved = true;
6348                }
6349            }
6350        }
6351        if self.get_atmosphere_preset() == 1
6352            && (sim_tick & 1) == 0
6353            && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES
6354        {
6355            let cam_pos: Vec3 = self.get_camera().get_position();
6356            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
6357            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 5.0, -14.0)));
6358            rain_cfg.set_base_velocity(Vec3::new(-0.5, -15.5, 0.3));
6359            rain_cfg.set_velocity_spread(3.6);
6360            rain_cfg.set_start_color(Color::rgba(150, 218, 255, 210));
6361            rain_cfg.set_end_color(Color::rgba(68, 152, 240, 60));
6362            rain_cfg.set_start_size_m(0.07);
6363            rain_cfg.set_end_size_m(0.03);
6364            rain_cfg.set_min_lifetime(0.6);
6365            rain_cfg.set_max_lifetime(0.95);
6366            rain_cfg.set_emissive_boost(1.4);
6367            self.get_mut_niagara().emit_burst(2, &rain_cfg);
6368        }
6369        if self.get_niagara().get_active_count() > 0 {
6370            let _: usize = self.get_mut_niagara().update(dt, 0.0);
6371        }
6372        if !self.get_animation_mixer().get_layers().is_empty() {
6373            let anim_updates: usize = self.tick_animations(dt);
6374            if anim_updates > 0 {
6375                any_dynamic_moved = true;
6376            }
6377        }
6378        if any_static_moved {
6379            self.set_bvh_dirty(true);
6380        }
6381        if any_dynamic_moved {
6382            self.set_dynamic_bvh_dirty(true);
6383        }
6384        if any_static_moved || any_dynamic_moved {
6385            self.bump_world_revision();
6386        }
6387    }
6388
6389    /// Returns the optional precomputed IBL environment attached to this world.
6390    ///
6391    /// # Returns
6392    ///
6393    /// - `Option<&EnvironmentIbl3D>` - Borrowed IBL environment if configured.
6394    #[must_use]
6395    pub fn environment_ibl(&self) -> Option<&EnvironmentIbl3D> {
6396        let Self {
6397            environment_ibl, ..
6398        } = self;
6399        environment_ibl.as_ref()
6400    }
6401
6402    /// Replaces the world's active IBL environment and increments the world revision.
6403    ///
6404    /// # Arguments
6405    ///
6406    /// - `&Self` - Mutable world.
6407    /// - `Option<EnvironmentIbl3D>` - New IBL environment or `None` to clear.
6408    pub fn set_environment_ibl(&mut self, ibl: Option<EnvironmentIbl3D>) {
6409        let Self {
6410            environment_ibl, ..
6411        } = self;
6412        *environment_ibl = ibl;
6413        self.bump_world_revision();
6414    }
6415
6416    /// Returns the currently active multi-camera index inside `scene_cameras`, if selected.
6417    ///
6418    /// # Returns
6419    ///
6420    /// - `Option<usize>` - Active camera index in `scene_cameras`, or `None` when using `camera`.
6421    #[must_use]
6422    pub fn active_scene_camera_index(&self) -> Option<usize> {
6423        let Self {
6424            active_scene_camera,
6425            ..
6426        } = self;
6427        *active_scene_camera
6428    }
6429
6430    /// Selects an active camera from `scene_cameras` (or `None` to revert to the default `camera`).
6431    ///
6432    /// # Arguments
6433    ///
6434    /// - `&Self` - Mutable world.
6435    /// - `Option<usize>` - Target camera index inside `scene_cameras`.
6436    ///
6437    /// # Returns
6438    ///
6439    /// - `bool` - `true` when the requested camera selection succeeded.
6440    pub fn set_active_scene_camera(&mut self, camera_index: Option<usize>) -> bool {
6441        let cam_count: usize = self.get_scene_cameras().len();
6442        if let Some(target_idx) = camera_index
6443            && target_idx >= cam_count
6444        {
6445            return false;
6446        }
6447        let Self {
6448            active_scene_camera,
6449            ..
6450        } = self;
6451        *active_scene_camera = camera_index;
6452        if let Some(target_idx) = camera_index
6453            && let Some(scene_cam) = self.get_scene_cameras().get(target_idx).cloned()
6454        {
6455            self.set_camera(scene_cam.to_camera3d());
6456        }
6457        self.bump_world_revision();
6458        true
6459    }
6460
6461    /// Returns the active camera's view-projection matrix (respecting Perspective or Orthographic `SceneCamera3D` when selected).
6462    ///
6463    /// # Arguments
6464    ///
6465    /// - `&Self` - World reference.
6466    /// - `f32` - Viewport width-to-height aspect ratio.
6467    ///
6468    /// # Returns
6469    ///
6470    /// - `Mat4` - Active view-projection matrix.
6471    #[must_use]
6472    pub fn active_view_projection(&self, viewport_aspect: f32) -> Mat4 {
6473        if let Some(cam_idx) = self.active_scene_camera_index()
6474            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
6475        {
6476            return scene_cam.view_projection(viewport_aspect);
6477        }
6478        self.get_camera().view_projection(viewport_aspect)
6479    }
6480
6481    /// Returns the live deformed (morphed and/or skinned) `Mesh3D` for `obj_idx` if active.
6482    ///
6483    /// # Arguments
6484    ///
6485    /// - `&Self` - World reference.
6486    /// - `usize` - Target object index in `objects`.
6487    ///
6488    /// # Returns
6489    ///
6490    /// - `Option<&Mesh3D>` - Borrowed deformed mesh when shape keys or armature skinning are active on `obj_idx`.
6491    #[must_use]
6492    pub fn deformed_mesh_for_object(&self, obj_idx: usize) -> Option<&Mesh3D> {
6493        let Self {
6494            deformed_meshes, ..
6495        } = self;
6496        deformed_meshes.get(obj_idx).and_then(Option::as_ref)
6497    }
6498
6499    /// Returns whether `obj_idx` is effectively visible after evaluating hierarchical node visibility and 64-bit Blender Collections masks.
6500    ///
6501    /// # Arguments
6502    ///
6503    /// - `&Self` - World reference.
6504    /// - `usize` - Target object index in `objects`.
6505    ///
6506    /// # Returns
6507    ///
6508    /// - `bool` - `true` when the object should be rendered.
6509    #[must_use]
6510    pub fn is_object_visible(&self, obj_idx: usize) -> bool {
6511        let Some(obj) = self.get_objects().get(obj_idx) else {
6512            return false;
6513        };
6514        if let Some(node_id) = obj.try_get_node_id() {
6515            return self.get_scene_graph().is_node_effectively_visible(node_id);
6516        }
6517        true
6518    }
6519
6520    /// Updates the deformation algorithm (`LinearBlend` or `DualQuaternion`) for skin `skin_idx` and refreshes deformed meshes immediately.
6521    ///
6522    /// # Arguments
6523    ///
6524    /// - `&Self` - Mutable world.
6525    /// - `usize` - Skin index inside `skins`.
6526    /// - `SkinningMode` - Desired skinning mode.
6527    ///
6528    /// # Returns
6529    ///
6530    /// - `bool` - `true` when `skin_idx` existed.
6531    pub fn set_skinning_mode(&mut self, skin_idx: usize, mode: SkinningMode) -> bool {
6532        let Some(skin) = self.get_mut_skins().get_mut(skin_idx) else {
6533            return false;
6534        };
6535        skin.set_skinning_mode(mode);
6536        let _: usize = self.update_deformed_meshes();
6537        self.bump_world_revision();
6538        true
6539    }
6540
6541    /// Toggles viewport visibility for Blender Collection `collection_name` in `scene_graph`.
6542    ///
6543    /// # Arguments
6544    ///
6545    /// - `&Self` - Mutable world.
6546    /// - `&str` - Collection name.
6547    /// - `bool` - Desired viewport visibility state.
6548    ///
6549    /// # Returns
6550    ///
6551    /// - `bool` - `true` when a matching collection was updated.
6552    pub fn set_collection_visible(&mut self, collection_name: &str, visible: bool) -> bool {
6553        let updated: bool = self
6554            .get_mut_scene_graph()
6555            .get_mut_collections()
6556            .set_collection_visible(collection_name, visible);
6557        if updated {
6558            self.bump_world_revision();
6559        }
6560        updated
6561    }
6562
6563    /// Loads an `ImportedScene3D` (from glTF 2.0 / binary GLB / `.euv3d`) directly into `World3D`, wiring hierarchy, collections, Principled BSDF materials, mipmapped textures, skins, animations, cameras, and lights.
6564    ///
6565    /// # Arguments
6566    ///
6567    /// - `&Self` - Mutable 3D world.
6568    /// - `&ImportedScene3D` - Parsed Blender/glTF 2.0 scene bundle.
6569    ///
6570    /// # Returns
6571    ///
6572    /// - `Vec<usize>` - Indices of all spawned `SceneObject3D` entries inside `World3D::objects`.
6573    pub fn load_imported_scene(&mut self, scene: &ImportedScene3D) -> Vec<usize> {
6574        let texture_base: u32 = self.get_textures().len() as u32;
6575        self.get_mut_textures()
6576            .extend(scene.get_textures().iter().cloned());
6577        let material_base: u32 = self.get_principled_materials().len() as u32;
6578        for raw_mat in scene.get_materials().iter() {
6579            let mut rebased: PrincipledMaterial3D = raw_mat.clone();
6580            Self::rebase_material_textures(&mut rebased, texture_base);
6581            self.get_mut_principled_materials().push(rebased);
6582        }
6583        let mesh_base: usize = self.get_mesh_library().len();
6584        for raw_mesh in scene.get_meshes().iter() {
6585            let mut mesh_copy: Mesh3D = raw_mesh.clone();
6586            if let Some(local_mat_id) = mesh_copy.try_get_material_index() {
6587                mesh_copy.set_material_index(Some(local_mat_id.saturating_add(material_base)));
6588            }
6589            let lod_chain: MeshLodChain = if mesh_copy.get_indices().len() > 24 {
6590                build_qem_lod_chain(&mesh_copy, 3)
6591            } else {
6592                MeshLodChain::from_mesh(mesh_copy)
6593            };
6594            let _: usize = self.register_mesh(lod_chain);
6595        }
6596        let node_base: u32 = self.get_scene_graph().get_nodes().len() as u32;
6597        let skin_base: u32 = self.get_skins().len() as u32;
6598        let mut collection_bit_remap: Vec<u64> = Vec::new();
6599        for coll_entry in scene
6600            .get_scene_graph()
6601            .get_collections()
6602            .get_entries()
6603            .iter()
6604        {
6605            let mask_val: u64 = self
6606                .get_mut_scene_graph()
6607                .get_mut_collections()
6608                .register_collection(coll_entry.get_name());
6609            if !coll_entry.get_visible_viewport() {
6610                let _: bool = self
6611                    .get_mut_scene_graph()
6612                    .get_mut_collections()
6613                    .set_collection_visible(coll_entry.get_name(), false);
6614            }
6615            collection_bit_remap.push(mask_val);
6616        }
6617        let src_graph: &SceneGraph3D = scene.get_scene_graph();
6618        let src_nodes: &[SceneNode3D] = src_graph.get_nodes().as_slice();
6619        for (src_idx, src_node) in src_nodes.iter().enumerate() {
6620            let rebased_parent: Option<u32> = src_node
6621                .try_get_parent()
6622                .map(|parent_idx: u32| parent_idx.saturating_add(node_base));
6623            let node_label: &str = if src_node.get_name().is_empty() {
6624                BLENDER_IMPORTED_NODE_FALLBACK
6625            } else {
6626                src_node.get_name().as_str()
6627            };
6628            let mut dst_node: SceneNode3D = SceneNode3D::from_name(node_label, rebased_parent);
6629            dst_node.set_local_translation(src_node.get_local_translation());
6630            dst_node.set_local_rotation(src_node.get_local_rotation());
6631            dst_node.set_local_scale(src_node.get_local_scale());
6632            dst_node.set_visible(src_node.get_visible());
6633            dst_node.set_extras(src_node.get_extras().clone());
6634            let mut mapped_mask: u64 = 0;
6635            let raw_mask: u64 = src_node.get_collection_mask();
6636            for (bit_pos, &dst_bit) in collection_bit_remap.iter().enumerate() {
6637                if (raw_mask & (1_u64 << (bit_pos as u32))) != 0 {
6638                    mapped_mask |= dst_bit;
6639                }
6640            }
6641            dst_node.set_collection_mask(if mapped_mask == 0 { 1 } else { mapped_mask });
6642            if let Some(src_mesh_id) = src_node.try_get_mesh_id() {
6643                dst_node.set_mesh_id(Some((mesh_base as u32).saturating_add(src_mesh_id)));
6644            }
6645            if let Some(src_skin_id) = src_node.try_get_skin_id() {
6646                dst_node.set_skin_id(Some(skin_base.saturating_add(src_skin_id)));
6647            }
6648            dst_node.set_camera_id(src_node.try_get_camera_id());
6649            dst_node.set_light_id(src_node.try_get_light_id());
6650            let dst_node_id: u32 = self.get_mut_scene_graph().add_node(dst_node);
6651            let src_weights: &[f32] = src_graph.morph_weights_for_node(src_idx as u32);
6652            if !src_weights.is_empty() {
6653                self.get_mut_scene_graph()
6654                    .attach_morph_weights(dst_node_id, src_weights);
6655            }
6656            let Self {
6657                node_object_map, ..
6658            } = self;
6659            node_object_map.push(None);
6660        }
6661        let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
6662        for src_skin in scene.get_skins().iter() {
6663            let mut runtime_skin: Skin3D = Skin3D::from_imported(src_skin);
6664            for joint_node in runtime_skin.get_mut_joints().iter_mut() {
6665                *joint_node = joint_node.saturating_add(node_base);
6666            }
6667            if let Some(root_idx) = runtime_skin.try_get_skeleton_root() {
6668                runtime_skin.set_skeleton_root(Some(root_idx.saturating_add(node_base)));
6669            }
6670            self.get_mut_skins().push(runtime_skin);
6671        }
6672        let mut first_clip_added: Option<usize> = None;
6673        for src_clip in scene.get_animations().iter() {
6674            let mut rebased_clip: ImportedAnimationClip3D = src_clip.clone();
6675            for chan in rebased_clip.get_mut_channels().iter_mut() {
6676                chan.set_target_node(chan.get_target_node().saturating_add(node_base));
6677            }
6678            let clip_idx: usize = self.get_mut_animation_mixer().add_clip(rebased_clip);
6679            if first_clip_added.is_none() {
6680                first_clip_added = Some(clip_idx);
6681            }
6682        }
6683        let graph_snapshot: SceneGraph3D = self.get_scene_graph().clone();
6684        self.get_mut_animation_mixer()
6685            .capture_rest_pose(&graph_snapshot);
6686        if let Some(clip_idx) = first_clip_added
6687            && self.get_animation_mixer().get_layers().is_empty()
6688        {
6689            let _: usize = self
6690                .get_mut_animation_mixer()
6691                .push_layer(NlaLayer3D::new(clip_idx));
6692        }
6693        let mut spawned_objects: Vec<usize> = Vec::new();
6694        let total_nodes: usize = self.get_scene_graph().get_nodes().len();
6695        for node_idx in (node_base as usize)..total_nodes {
6696            let node_copy: SceneNode3D = self.get_scene_graph().get_nodes()[node_idx].clone();
6697            let world_mat: Mat4 = node_copy.get_world_matrix();
6698            let world_tr: Transform3D = Transform3D::from_matrix(world_mat);
6699            if let Some(global_mesh_id) = node_copy.try_get_mesh_id() {
6700                let mesh_usize: usize = global_mesh_id as usize;
6701                let principled_id: Option<u32> = self
6702                    .get_mesh_library()
6703                    .get(mesh_usize)
6704                    .and_then(|chain: &MeshLodChain| chain.get_levels().first())
6705                    .and_then(|mesh_ref: &Mesh3D| mesh_ref.try_get_material_index());
6706                let legacy_mat: PbrMaterial = principled_id
6707                    .and_then(|mat_idx: u32| self.get_principled_materials().get(mat_idx as usize))
6708                    .map_or_else(
6709                        || {
6710                            self.get_mesh_library()
6711                                .get(mesh_usize)
6712                                .and_then(|chain: &MeshLodChain| chain.get_levels().first())
6713                                .map_or_else(PbrMaterial::default, Mesh3D::get_material)
6714                        },
6715                        PrincipledMaterial3D::to_legacy_pbr,
6716                    );
6717                let cast_shadows: bool = node_copy.get_extras().get_cast_shadows();
6718                let obj_idx: usize = self.spawn_object(
6719                    node_copy.get_name(),
6720                    mesh_usize,
6721                    world_tr,
6722                    legacy_mat,
6723                    cast_shadows,
6724                );
6725                let skin_opt: Option<u32> = node_copy.try_get_skin_id();
6726                let is_deformable: bool =
6727                    skin_opt.is_some() || node_copy.get_morph_weight_count() > 0;
6728                if let Some(obj_mut) = self.get_mut_objects().get_mut(obj_idx) {
6729                    obj_mut.set_node_id(Some(node_idx as u32));
6730                    obj_mut.set_principled_material_id(principled_id);
6731                    obj_mut.set_skin_id(skin_opt);
6732                }
6733                if is_deformable {
6734                    let _: bool = self.set_object_dynamic(obj_idx, true);
6735                }
6736                let Self {
6737                    node_object_map, ..
6738                } = self;
6739                if let Some(slot) = node_object_map.get_mut(node_idx) {
6740                    *slot = Some(obj_idx);
6741                }
6742                spawned_objects.push(obj_idx);
6743            }
6744            if let Some(src_cam_id) = node_copy.try_get_camera_id()
6745                && let Some(imp_cam) = scene.get_cameras().get(src_cam_id as usize)
6746            {
6747                self.get_mut_scene_cameras()
6748                    .push(SceneCamera3D::from_imported(
6749                        imp_cam,
6750                        Some(node_idx as u32),
6751                        world_tr.get_position(),
6752                        world_tr.get_rotation(),
6753                    ));
6754            }
6755            if let Some(src_light_id) = node_copy.try_get_light_id()
6756                && let Some(imp_light) = scene.get_lights().get(src_light_id as usize)
6757            {
6758                let emit_dir: Vec3 = world_tr
6759                    .get_rotation()
6760                    .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
6761                    .normalize();
6762                let light_color: Vec3 = imp_light.get_color();
6763                let light_intensity: f32 = imp_light.get_intensity();
6764                match imp_light.get_kind() {
6765                    GltfLightKind::Directional => {
6766                        let mut sun_val: DirectionalLight3D = self.get_sun();
6767                        sun_val.set_direction(emit_dir.scale(-1.0).normalize());
6768                        sun_val.set_color(light_color.scale(light_intensity.max(0.05)));
6769                        self.set_sun(sun_val);
6770                    }
6771                    GltfLightKind::Point { range } => {
6772                        let resolved_range: f32 = range.unwrap_or(24.0).max(0.5);
6773                        self.get_mut_point_lights().push(PointLight3D::from_linear(
6774                            world_tr.get_position(),
6775                            light_color,
6776                            light_intensity,
6777                            resolved_range,
6778                        ));
6779                    }
6780                    GltfLightKind::Spot {
6781                        range,
6782                        inner_cone_angle,
6783                        outer_cone_angle,
6784                    } => {
6785                        let resolved_range: f32 = range.unwrap_or(32.0).max(0.5);
6786                        self.get_mut_spot_lights().push(SpotLight3D::from_linear(
6787                            world_tr.get_position(),
6788                            emit_dir,
6789                            light_color,
6790                            light_intensity,
6791                            resolved_range,
6792                            (inner_cone_angle, outer_cone_angle),
6793                        ));
6794                    }
6795                    GltfLightKind::Area { width, height } => {
6796                        self.get_mut_area_lights().push(AreaLight3D::new_rect(
6797                            world_tr.get_position(),
6798                            emit_dir,
6799                            light_color,
6800                            light_intensity,
6801                            (width, height),
6802                            28.0,
6803                        ));
6804                    }
6805                }
6806            }
6807        }
6808        let _: usize = self.update_deformed_meshes();
6809        if self.environment_ibl().is_none() {
6810            let sun_ref: DirectionalLight3D = self.get_sun();
6811            let baked_ibl: EnvironmentIbl3D = EnvironmentIbl3D::from_procedural_sky(
6812                &sun_ref,
6813                WORLD_DEFAULT_IBL_OCT_SIZE,
6814                WORLD_DEFAULT_IBL_LUT_SIZE,
6815            );
6816            self.set_environment_ibl(Some(baked_ibl));
6817        }
6818        self.set_use_agx_tonemap(true);
6819        self.set_imported_model_count(self.get_imported_model_count().saturating_add(1));
6820        self.set_bvh_dirty(true);
6821        self.set_dynamic_bvh_dirty(true);
6822        self.set_dynamic_topology_dirty(true);
6823        self.bump_world_revision();
6824        spawned_objects
6825    }
6826
6827    /// Parses binary `.glb` or `.gltf` JSON bytes and loads the resulting Blender scene directly into `World3D`.
6828    ///
6829    /// # Arguments
6830    ///
6831    /// - `&Self` - Mutable 3D world.
6832    /// - `&[u8]` - Raw `.glb` or `.gltf` bytes.
6833    ///
6834    /// # Returns
6835    ///
6836    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured glTF import error.
6837    pub fn load_glb_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
6838        let imported: ImportedScene3D = parse_gltf_or_glb_bytes(bytes, None)?;
6839        Ok(self.load_imported_scene(&imported))
6840    }
6841
6842    /// Parses pure-Rust Blender 3.x/4.x/5.x `.blend` bytes directly and loads the resulting scene into this `World3D`.
6843    ///
6844    /// # Arguments
6845    ///
6846    /// - `&[u8]` - Raw `.blend` binary buffer (uncompressed, gzip, or Zstd).
6847    ///
6848    /// # Returns
6849    ///
6850    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured `.blend` import error.
6851    pub fn load_blend_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
6852        let imported: ImportedScene3D = parse_blend_bytes(bytes)?;
6853        Ok(self.load_imported_scene(&imported))
6854    }
6855
6856    /// Decodes a baked `.euv3d` (v1 or v2) binary package and loads its scene hierarchy, meshes, and materials into this `World3D`.
6857    ///
6858    /// # Arguments
6859    ///
6860    /// - `&[u8]` - Raw `.euv3d` binary buffer.
6861    ///
6862    /// # Returns
6863    ///
6864    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured `.euv3d` decode error.
6865    pub fn load_euv3d_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
6866        let bundle: BakedAssetBundle3D = Euv3dPackage::decode_any_bytes(bytes)?;
6867        Ok(self.load_imported_scene(bundle.get_scene()))
6868    }
6869
6870    /// Tests a single local-space ray against `mesh` using meshlet AABB pruning and exact Möller–Trumbore triangle intersection.
6871    ///
6872    /// # Arguments
6873    ///
6874    /// - `&Mesh3D` - Candidate triangle mesh in local object space.
6875    /// - `Vec3` - Ray origin in mesh local space.
6876    /// - `Vec3` - Ray direction in mesh local space (unnormalized so parametric `t` matches world distance).
6877    /// - `Vec3` - Reciprocal local ray direction for AABB slab pruning.
6878    /// - `f32` - Minimum valid hit distance `t_min`.
6879    /// - `f32` - Current closest hit distance ceiling `best_t`.
6880    ///
6881    /// # Returns
6882    ///
6883    /// - `Option<(f32, Vec3)>` - Nearest `(hit_t, local_unit_normal)` strictly closer than `best_t`, or `None`.
6884    #[must_use]
6885    fn intersect_mesh_triangles_local(
6886        mesh: &Mesh3D,
6887        local_origin: Vec3,
6888        local_dir: Vec3,
6889        local_inv_dir: Vec3,
6890        t_min: f32,
6891        best_t: f32,
6892    ) -> Option<(f32, Vec3)> {
6893        let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
6894        let tris: &[[u32; 3]] = mesh.get_indices().as_slice();
6895        if verts.is_empty() || tris.is_empty() {
6896            return None;
6897        }
6898        let mut closest_t: f32 = best_t;
6899        let mut closest_normal: Vec3 = Vec3::zero();
6900        let mut hit_any: bool = false;
6901        let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
6902        if !meshlets.is_empty() {
6903            for meshlet in meshlets.iter() {
6904                let mbox: AxisAlignedBox3D = meshlet.get_bounds();
6905                let box_t: f32 =
6906                    mbox.intersect_ray_near(local_origin, local_inv_dir, t_min, closest_t);
6907                if box_t >= closest_t {
6908                    continue;
6909                }
6910                let start: usize = meshlet.get_first_tri() as usize;
6911                let end: usize = start
6912                    .saturating_add(meshlet.get_tri_count() as usize)
6913                    .min(tris.len());
6914                for tri in &tris[start..end] {
6915                    let (i0, i1, i2): (usize, usize, usize) =
6916                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
6917                    if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
6918                        continue;
6919                    }
6920                    let v0: Vec3 = verts[i0].get_position();
6921                    let e1: Vec3 = verts[i1].get_position().sub(v0);
6922                    let e2: Vec3 = verts[i2].get_position().sub(v0);
6923                    let h: Vec3 = local_dir.cross(e2);
6924                    let a: f32 = e1.dot(h);
6925                    if a.abs() < 1e-7 {
6926                        continue;
6927                    }
6928                    let inv_a: f32 = 1.0 / a;
6929                    let s: Vec3 = local_origin.sub(v0);
6930                    let u: f32 = inv_a * s.dot(h);
6931                    if !(0.0..=1.0).contains(&u) {
6932                        continue;
6933                    }
6934                    let q: Vec3 = s.cross(e1);
6935                    let v: f32 = inv_a * local_dir.dot(q);
6936                    if v < 0.0 || (u + v) > 1.0 {
6937                        continue;
6938                    }
6939                    let t: f32 = inv_a * e2.dot(q);
6940                    if t >= t_min && t < closest_t {
6941                        closest_t = t;
6942                        closest_normal = e1.cross(e2).normalize();
6943                        hit_any = true;
6944                    }
6945                }
6946            }
6947        } else {
6948            for tri in tris.iter() {
6949                let (i0, i1, i2): (usize, usize, usize) =
6950                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
6951                if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
6952                    continue;
6953                }
6954                let v0: Vec3 = verts[i0].get_position();
6955                let e1: Vec3 = verts[i1].get_position().sub(v0);
6956                let e2: Vec3 = verts[i2].get_position().sub(v0);
6957                let h: Vec3 = local_dir.cross(e2);
6958                let a: f32 = e1.dot(h);
6959                if a.abs() < 1e-7 {
6960                    continue;
6961                }
6962                let inv_a: f32 = 1.0 / a;
6963                let s: Vec3 = local_origin.sub(v0);
6964                let u: f32 = inv_a * s.dot(h);
6965                if !(0.0..=1.0).contains(&u) {
6966                    continue;
6967                }
6968                let q: Vec3 = s.cross(e1);
6969                let v: f32 = inv_a * local_dir.dot(q);
6970                if v < 0.0 || (u + v) > 1.0 {
6971                    continue;
6972                }
6973                let t: f32 = inv_a * e2.dot(q);
6974                if t >= t_min && t < closest_t {
6975                    closest_t = t;
6976                    closest_normal = e1.cross(e2).normalize();
6977                    hit_any = true;
6978                }
6979            }
6980        }
6981        if hit_any {
6982            Some((closest_t, closest_normal))
6983        } else {
6984            None
6985        }
6986    }
6987
6988    /// Casts a picking ray through normalized screen coordinates `(screen_u, screen_v)` in `[0.0, 1.0]` using AABB/meshlet broadphase and exact Möller–Trumbore triangle intersection.
6989    ///
6990    /// # Arguments
6991    ///
6992    /// - `f32` - Normalized horizontal screen coordinate in `[0.0, 1.0]` (left to right).
6993    /// - `f32` - Normalized vertical screen coordinate in `[0.0, 1.0]` (top to bottom).
6994    /// - `f32` - Viewport aspect ratio `width / height`.
6995    ///
6996    /// # Returns
6997    ///
6998    /// - `Option<ScenePickHit3D>` - Nearest visible object triangle hit or `None` when no object is intersected.
6999    #[must_use]
7000    pub fn pick_object_ray(
7001        &self,
7002        screen_u: f32,
7003        screen_v: f32,
7004        aspect: f32,
7005    ) -> Option<ScenePickHit3D> {
7006        let safe_aspect: f32 = if aspect.is_finite() && aspect > 0.05 {
7007            aspect
7008        } else {
7009            1.0
7010        };
7011        let ndc_x: f32 = screen_u.clamp(0.0, 1.0) * 2.0 - 1.0;
7012        let ndc_y: f32 = 1.0 - screen_v.clamp(0.0, 1.0) * 2.0;
7013        let (origin, ray_dir, t_min, mut best_t): (Vec3, Vec3, f32, f32) = if let Some(cam_idx) =
7014            self.active_scene_camera_index()
7015            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
7016        {
7017            let fwd: Vec3 = scene_cam.forward();
7018            let right: Vec3 = scene_cam.right();
7019            let up: Vec3 = scene_cam.up();
7020            match scene_cam.get_projection() {
7021                GltfCameraProjection::Orthographic {
7022                    xmag,
7023                    ymag,
7024                    znear,
7025                    zfar,
7026                } => {
7027                    let o: Vec3 = scene_cam
7028                        .get_position()
7029                        .add(right.scale(ndc_x * xmag))
7030                        .add(up.scale(ndc_y * ymag));
7031                    (o, fwd, znear.max(0.01), zfar.max(znear + 1.0))
7032                }
7033                GltfCameraProjection::Perspective {
7034                    yfov_rad,
7035                    aspect_ratio,
7036                    znear,
7037                    zfar,
7038                } => {
7039                    let cam_aspect: f32 = aspect_ratio.unwrap_or(safe_aspect).max(0.05);
7040                    let half_tan_y: f32 = (yfov_rad.clamp(0.15, 2.6) * 0.5).tan();
7041                    let dir: Vec3 = fwd
7042                        .add(right.scale(ndc_x * half_tan_y * cam_aspect))
7043                        .add(up.scale(ndc_y * half_tan_y))
7044                        .normalize();
7045                    (
7046                        scene_cam.get_position(),
7047                        dir,
7048                        znear.max(0.01),
7049                        zfar.unwrap_or(480.0).max(znear + 1.0),
7050                    )
7051                }
7052            }
7053        } else {
7054            let cam: Camera3D = self.get_camera();
7055            let half_tan_y: f32 = (cam.get_fov_deg().clamp(12.0, 120.0).to_radians() * 0.5).tan();
7056            let half_tan_x: f32 = half_tan_y * safe_aspect;
7057            let forward: Vec3 = cam.forward();
7058            let right: Vec3 = cam.right();
7059            let up: Vec3 = right.cross(forward).normalize();
7060            let dir: Vec3 = forward
7061                .add(right.scale(ndc_x * half_tan_x))
7062                .add(up.scale(ndc_y * half_tan_y))
7063                .normalize();
7064            let near_v: f32 = cam.get_near().max(0.01);
7065            (
7066                cam.get_position(),
7067                dir,
7068                near_v,
7069                cam.get_far().max(near_v + 1.0),
7070            )
7071        };
7072        let inv_dir: Vec3 = Vec3::new(
7073            if ray_dir.get_x().abs() > 1e-6 {
7074                1.0 / ray_dir.get_x()
7075            } else {
7076                f32::INFINITY
7077            },
7078            if ray_dir.get_y().abs() > 1e-6 {
7079                1.0 / ray_dir.get_y()
7080            } else {
7081                f32::INFINITY
7082            },
7083            if ray_dir.get_z().abs() > 1e-6 {
7084                1.0 / ray_dir.get_z()
7085            } else {
7086                f32::INFINITY
7087            },
7088        );
7089        let Self {
7090            objects,
7091            mesh_library,
7092            deformed_meshes,
7093            ..
7094        } = self;
7095        let mut best_hit: Option<ScenePickHit3D> = None;
7096        for (obj_idx, obj) in objects.iter().enumerate() {
7097            if !self.is_object_visible(obj_idx) {
7098                continue;
7099            }
7100            let bounds: AxisAlignedBox3D = obj.get_world_bounds();
7101            let aabb_t: f32 = bounds.intersect_ray_near(origin, inv_dir, t_min, best_t);
7102            if aabb_t >= best_t {
7103                continue;
7104            }
7105            let mesh_ref: Option<&Mesh3D> = deformed_meshes
7106                .get(obj_idx)
7107                .and_then(|slot: &Option<Mesh3D>| slot.as_ref())
7108                .or_else(|| {
7109                    mesh_library
7110                        .get(obj.get_mesh_id())
7111                        .and_then(|chain: &MeshLodChain| chain.get_levels().first())
7112                });
7113            let Some(mesh) = mesh_ref else {
7114                best_t = aabb_t;
7115                let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
7116                best_hit = Some(ScenePickHit3D::new(
7117                    obj_idx,
7118                    obj.get_mesh_id(),
7119                    aabb_t,
7120                    world_pos,
7121                    ray_dir.scale(-1.0),
7122                ));
7123                continue;
7124            };
7125            if mesh.get_indices().is_empty() {
7126                best_t = aabb_t;
7127                let world_pos: Vec3 = origin.add(ray_dir.scale(aabb_t));
7128                best_hit = Some(ScenePickHit3D::new(
7129                    obj_idx,
7130                    obj.get_mesh_id(),
7131                    aabb_t,
7132                    world_pos,
7133                    ray_dir.scale(-1.0),
7134                ));
7135                continue;
7136            }
7137            let xform: Transform3D = obj.get_transform();
7138            let inv_elems: [f32; 16] = xform.to_inv_mat4().get_elements();
7139            let local_origin: Vec3 = Vec3::new(
7140                inv_elems[0] * origin.get_x()
7141                    + inv_elems[4] * origin.get_y()
7142                    + inv_elems[8] * origin.get_z()
7143                    + inv_elems[12],
7144                inv_elems[1] * origin.get_x()
7145                    + inv_elems[5] * origin.get_y()
7146                    + inv_elems[9] * origin.get_z()
7147                    + inv_elems[13],
7148                inv_elems[2] * origin.get_x()
7149                    + inv_elems[6] * origin.get_y()
7150                    + inv_elems[10] * origin.get_z()
7151                    + inv_elems[14],
7152            );
7153            let local_dir: Vec3 = Vec3::new(
7154                inv_elems[0] * ray_dir.get_x()
7155                    + inv_elems[4] * ray_dir.get_y()
7156                    + inv_elems[8] * ray_dir.get_z(),
7157                inv_elems[1] * ray_dir.get_x()
7158                    + inv_elems[5] * ray_dir.get_y()
7159                    + inv_elems[9] * ray_dir.get_z(),
7160                inv_elems[2] * ray_dir.get_x()
7161                    + inv_elems[6] * ray_dir.get_y()
7162                    + inv_elems[10] * ray_dir.get_z(),
7163            );
7164            let local_inv_dir: Vec3 = Vec3::new(
7165                if local_dir.get_x().abs() > 1e-6 {
7166                    1.0 / local_dir.get_x()
7167                } else {
7168                    f32::INFINITY
7169                },
7170                if local_dir.get_y().abs() > 1e-6 {
7171                    1.0 / local_dir.get_y()
7172                } else {
7173                    f32::INFINITY
7174                },
7175                if local_dir.get_z().abs() > 1e-6 {
7176                    1.0 / local_dir.get_z()
7177                } else {
7178                    f32::INFINITY
7179                },
7180            );
7181            if let Some((hit_t, local_n)) = Self::intersect_mesh_triangles_local(
7182                mesh,
7183                local_origin,
7184                local_dir,
7185                local_inv_dir,
7186                t_min,
7187                best_t,
7188            ) {
7189                best_t = hit_t;
7190                let nmat: [Vec3; 3] = xform.normal_mat3();
7191                let mut world_n: Vec3 = nmat[0]
7192                    .scale(local_n.get_x())
7193                    .add(nmat[1].scale(local_n.get_y()))
7194                    .add(nmat[2].scale(local_n.get_z()))
7195                    .normalize();
7196                if world_n.dot(ray_dir) > 0.0 {
7197                    world_n = world_n.scale(-1.0);
7198                }
7199                let world_pos: Vec3 = origin.add(ray_dir.scale(hit_t));
7200                best_hit = Some(ScenePickHit3D::new(
7201                    obj_idx,
7202                    obj.get_mesh_id(),
7203                    hit_t,
7204                    world_pos,
7205                    world_n,
7206                ));
7207            }
7208        }
7209        best_hit
7210    }
7211
7212    /// Advances active glTF/NLA animations by `dt_secs`, propagates dirty scene-graph transforms, synchronizes object/camera transforms, and evaluates Shape Keys + Armature Skinning with zero steady-state heap allocations.
7213    ///
7214    /// # Arguments
7215    ///
7216    /// - `&Self` - Mutable 3D world.
7217    /// - `f32` - Frame delta time in seconds.
7218    ///
7219    /// # Returns
7220    ///
7221    /// - `usize` - Count of updated scene nodes, morph channels, and deformed meshes.
7222    pub fn tick_animations(&mut self, dt_secs: f32) -> usize {
7223        let anim_updates: usize = {
7224            let Self {
7225                scene_graph,
7226                animation_mixer,
7227                ..
7228            } = self;
7229            animation_mixer.advance_and_apply(dt_secs, scene_graph)
7230        };
7231        let propagated: usize = self.get_mut_scene_graph().propagate_world_matrices();
7232        let synced: usize = self.sync_objects_from_scene_graph();
7233        let deformed: usize = self.update_deformed_meshes();
7234        let total: usize = anim_updates + propagated + synced + deformed;
7235        if total > 0 {
7236            self.set_dynamic_bvh_dirty(true);
7237            self.bump_world_revision();
7238        }
7239        total
7240    }
7241
7242    /// Evaluates Shape Keys (pre-skinning) and Armature Skinning (LBS or DQS) for all deformable objects into reusable `deformed_meshes` buffers with zero steady-state allocations.
7243    ///
7244    /// # Returns
7245    ///
7246    /// - `usize` - Number of objects whose deformed mesh was updated.
7247    pub fn update_deformed_meshes(&mut self) -> usize {
7248        let obj_count: usize = self.get_objects().len();
7249        let Self {
7250            mesh_library,
7251            objects,
7252            scene_graph,
7253            skins,
7254            skin_scratch,
7255            deformed_meshes,
7256            ..
7257        } = self;
7258        if deformed_meshes.len() < obj_count {
7259            deformed_meshes.resize(obj_count, None);
7260        }
7261        let mut updated_count: usize = 0;
7262        for obj_idx in 0..obj_count {
7263            let obj_ref: &SceneObject3D = &objects[obj_idx];
7264            let Some(node_id) = obj_ref.try_get_node_id() else {
7265                continue;
7266            };
7267            let morph_weights: &[f32] = scene_graph.morph_weights_for_node(node_id);
7268            let skin_opt: Option<u32> = obj_ref.try_get_skin_id();
7269            if skin_opt.is_none() && morph_weights.is_empty() {
7270                continue;
7271            }
7272            let Some(base_mesh) = mesh_library
7273                .get(obj_ref.get_mesh_id())
7274                .and_then(|chain: &MeshLodChain| chain.get_levels().first())
7275            else {
7276                continue;
7277            };
7278            let mesh_world: Mat4 = scene_graph.get_nodes().get(node_id as usize).map_or_else(
7279                || obj_ref.get_transform().to_mat4(),
7280                SceneNode3D::get_world_matrix,
7281            );
7282            let did_deform: bool = if let Some(skin_id) = skin_opt
7283                && let Some(skin_ref) = skins.get(skin_id as usize)
7284            {
7285                skin_ref.deform_mesh_into(
7286                    base_mesh,
7287                    morph_weights,
7288                    mesh_world,
7289                    scene_graph,
7290                    skin_scratch,
7291                )
7292            } else {
7293                let morphed: bool = apply_morph_targets_into(
7294                    base_mesh.get_vertices().as_slice(),
7295                    base_mesh.get_morph_targets().as_slice(),
7296                    morph_weights,
7297                    skin_scratch.get_mut_skinned_vertices(),
7298                );
7299                morphed
7300            };
7301            if did_deform {
7302                let deformed_verts: &[Vertex3D] = skin_scratch.get_skinned_vertices().as_slice();
7303                let mut local_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
7304                for vert_item in deformed_verts.iter() {
7305                    local_bounds.expand_point(vert_item.get_position());
7306                }
7307                let target_slot: &mut Option<Mesh3D> = &mut deformed_meshes[obj_idx];
7308                if let Some(existing_mesh) = target_slot.as_mut() {
7309                    let dst_verts: &mut Vec<Vertex3D> = existing_mesh.get_mut_vertices();
7310                    dst_verts.clear();
7311                    dst_verts.extend_from_slice(deformed_verts);
7312                    existing_mesh.set_bounds(local_bounds);
7313                } else {
7314                    let mut cloned_mesh: Mesh3D = base_mesh.clone();
7315                    let dst_verts: &mut Vec<Vertex3D> = cloned_mesh.get_mut_vertices();
7316                    dst_verts.clear();
7317                    dst_verts.extend_from_slice(deformed_verts);
7318                    cloned_mesh.set_bounds(local_bounds);
7319                    *target_slot = Some(cloned_mesh);
7320                }
7321                if let Some(deformed_ref) = target_slot.as_ref() {
7322                    let world_tr: Transform3D = objects[obj_idx].get_transform();
7323                    objects[obj_idx]
7324                        .set_world_bounds(world_tr.transform_bounds(deformed_ref.get_bounds()));
7325                }
7326                updated_count += 1;
7327            }
7328        }
7329        updated_count
7330    }
7331
7332    /// Applies an incremental Blender Live-Link delta in place without resetting camera state or rebuilding unrelated geometry.
7333    ///
7334    /// # Arguments
7335    ///
7336    /// - `&Self` - Mutable 3D world.
7337    /// - `&BlenderLiveDelta3D` - Structured Live-Link delta command.
7338    ///
7339    /// # Returns
7340    ///
7341    /// - `bool` - `true` when at least one scene entity was mutated.
7342    pub fn apply_live_delta(&mut self, delta: &BlenderLiveDelta3D) -> bool {
7343        match delta {
7344            BlenderLiveDelta3D::NodeTransform {
7345                node_name,
7346                translation,
7347                rotation,
7348                scale,
7349                blender_z_up,
7350            } => {
7351                let found_id: Option<u32> = self
7352                    .get_scene_graph()
7353                    .get_nodes()
7354                    .iter()
7355                    .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
7356                    .map(|idx: usize| idx as u32);
7357                let Some(node_id) = found_id else {
7358                    return false;
7359                };
7360                let raw_t: Vec3 = Vec3::from_array(*translation);
7361                let raw_r: Quat = Quat::from_array(*rotation).normalize();
7362                let raw_s: Vec3 = Vec3::from_array(*scale);
7363                let (dst_t, dst_r, dst_s): (Vec3, Quat, Vec3) = if *blender_z_up {
7364                    (
7365                        raw_t.blender_z_up_to_y_up(),
7366                        raw_r.blender_z_up_to_y_up(),
7367                        Vec3::new(raw_s.get_x(), raw_s.get_z(), raw_s.get_y()),
7368                    )
7369                } else {
7370                    (raw_t, raw_r, raw_s)
7371                };
7372                self.get_mut_scene_graph()
7373                    .set_local_trs(node_id, dst_t, dst_r, dst_s);
7374                let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
7375                let _: usize = self.sync_objects_from_scene_graph();
7376                let _: usize = self.update_deformed_meshes();
7377                self.set_dynamic_bvh_dirty(true);
7378                self.bump_world_revision();
7379                true
7380            }
7381            BlenderLiveDelta3D::MaterialParams {
7382                material_name,
7383                base_color_factor,
7384                metallic_factor,
7385                roughness_factor,
7386                clearcoat_factor,
7387                clearcoat_roughness_factor,
7388                sheen_color_factor,
7389                sheen_roughness_factor,
7390                emissive_factor,
7391                emissive_strength,
7392                transmission_factor,
7393                ior,
7394            } => {
7395                let found_idx: Option<usize> = self
7396                    .get_principled_materials()
7397                    .iter()
7398                    .position(|mat_ref: &PrincipledMaterial3D| mat_ref.get_name() == material_name);
7399                let Some(mat_idx) = found_idx else {
7400                    return false;
7401                };
7402                let updated_legacy: PbrMaterial = {
7403                    let mat_mut: &mut PrincipledMaterial3D =
7404                        &mut self.get_mut_principled_materials()[mat_idx];
7405                    if let Some(val) = *base_color_factor {
7406                        mat_mut.set_base_color_factor(val);
7407                    }
7408                    if let Some(val) = *metallic_factor {
7409                        mat_mut.set_metallic_factor(val.clamp(0.0, 1.0));
7410                    }
7411                    if let Some(val) = *roughness_factor {
7412                        mat_mut.set_roughness_factor(val.clamp(0.04, 1.0));
7413                    }
7414                    if let Some(val) = *clearcoat_factor {
7415                        mat_mut.set_clearcoat_factor(val.clamp(0.0, 1.0));
7416                    }
7417                    if let Some(val) = *clearcoat_roughness_factor {
7418                        mat_mut.set_clearcoat_roughness_factor(val.clamp(0.0, 1.0));
7419                    }
7420                    if let Some(val) = *sheen_color_factor {
7421                        mat_mut.set_sheen_color_factor(val);
7422                    }
7423                    if let Some(val) = *sheen_roughness_factor {
7424                        mat_mut.set_sheen_roughness_factor(val.clamp(0.0, 1.0));
7425                    }
7426                    if let Some(val) = *emissive_factor {
7427                        mat_mut.set_emissive_factor(val);
7428                    }
7429                    if let Some(val) = *emissive_strength {
7430                        mat_mut.set_emissive_strength(val.max(0.0));
7431                    }
7432                    if let Some(val) = *transmission_factor {
7433                        mat_mut.set_transmission_factor(val.clamp(0.0, 1.0));
7434                    }
7435                    if let Some(val) = *ior {
7436                        mat_mut.set_ior(val.clamp(1.0, 3.0));
7437                    }
7438                    mat_mut.to_legacy_pbr()
7439                };
7440                let mat_u32: u32 = mat_idx as u32;
7441                for obj_mut in self.get_mut_objects().iter_mut() {
7442                    if obj_mut.try_get_principled_material_id() == Some(mat_u32) {
7443                        obj_mut.set_material(updated_legacy);
7444                    }
7445                }
7446                self.bump_world_revision();
7447                true
7448            }
7449            BlenderLiveDelta3D::MorphWeights { node_name, weights } => {
7450                let found_id: Option<u32> = self
7451                    .get_scene_graph()
7452                    .get_nodes()
7453                    .iter()
7454                    .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
7455                    .map(|idx: usize| idx as u32);
7456                let Some(node_id) = found_id else {
7457                    return false;
7458                };
7459                self.get_mut_scene_graph()
7460                    .update_morph_weights(node_id, weights.as_slice());
7461                let _: usize = self.update_deformed_meshes();
7462                self.set_dynamic_bvh_dirty(true);
7463                self.bump_world_revision();
7464                true
7465            }
7466            BlenderLiveDelta3D::LightUpdate {
7467                light_index,
7468                color,
7469                intensity,
7470                position,
7471                direction,
7472            } => {
7473                let mut changed: bool = false;
7474                if let Some(point_mut) = self.get_mut_point_lights().get_mut(*light_index) {
7475                    if let Some(col_arr) = *color {
7476                        point_mut.set_color(Vec3::from_array(col_arr));
7477                    }
7478                    if let Some(int_val) = *intensity {
7479                        point_mut.set_intensity(int_val.max(0.0));
7480                    }
7481                    if let Some(pos_arr) = *position {
7482                        point_mut.set_position(Vec3::from_array(pos_arr));
7483                    }
7484                    changed = true;
7485                } else if let Some(area_mut) = self.get_mut_area_lights().get_mut(*light_index) {
7486                    if let Some(col_arr) = *color {
7487                        area_mut.set_color(Vec3::from_array(col_arr));
7488                    }
7489                    if let Some(int_val) = *intensity {
7490                        area_mut.set_intensity(int_val.max(0.0));
7491                    }
7492                    if let Some(pos_arr) = *position {
7493                        area_mut.set_position(Vec3::from_array(pos_arr));
7494                    }
7495                    if let Some(dir_arr) = *direction {
7496                        area_mut.set_direction(Vec3::from_array(dir_arr).normalize());
7497                    }
7498                    changed = true;
7499                }
7500                if changed {
7501                    self.bump_world_revision();
7502                }
7503                changed
7504            }
7505            BlenderLiveDelta3D::CameraUpdate {
7506                position,
7507                yaw,
7508                pitch,
7509                fov_deg,
7510            } => {
7511                let mut cam: Camera3D = self.get_camera();
7512                cam.set_position(Vec3::from_array(*position));
7513                cam.set_yaw(*yaw);
7514                cam.set_pitch(pitch.clamp(-1.4, 1.4));
7515                cam.set_fov_deg(fov_deg.clamp(12.0, 120.0));
7516                self.set_camera(cam);
7517                self.bump_world_revision();
7518                true
7519            }
7520            BlenderLiveDelta3D::CollectionVisibility {
7521                collection_name,
7522                visible,
7523            } => self.set_collection_visible(collection_name, *visible),
7524            BlenderLiveDelta3D::EnvironmentUpdate {
7525                rotation_y_rad,
7526                intensity,
7527            } => {
7528                let Self {
7529                    environment_ibl, ..
7530                } = self;
7531                if let Some(ibl_mut) = environment_ibl.as_mut() {
7532                    ibl_mut.set_rotation_y_rad(*rotation_y_rad);
7533                    ibl_mut.set_intensity(intensity.max(0.0));
7534                    self.bump_world_revision();
7535                    true
7536                } else {
7537                    false
7538                }
7539            }
7540        }
7541    }
7542
7543    /// Parses a JSON Live-Link delta payload and applies it in place to this world.
7544    ///
7545    /// # Arguments
7546    ///
7547    /// - `&Self` - Mutable 3D world.
7548    /// - `&str` - JSON Live-Link delta string.
7549    ///
7550    /// # Returns
7551    ///
7552    /// - `Result<bool, String>` - `Ok(applied)` on valid payload, or parse error string.
7553    pub fn apply_live_delta_json(&mut self, json_payload: &str) -> Result<bool, String> {
7554        let root: Value =
7555            from_str::<Value>(json_payload).map_err(|_| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
7556        let kind_str: &str = root
7557            .get(LIVE_KEY_KIND)
7558            .and_then(Value::as_str)
7559            .ok_or_else(|| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
7560        let delta: BlenderLiveDelta3D = match kind_str {
7561            LIVE_DELTA_KIND_TRANSFORM => BlenderLiveDelta3D::NodeTransform {
7562                node_name: root
7563                    .get(LIVE_KEY_NODE_NAME)
7564                    .and_then(Value::as_str)
7565                    .unwrap_or_default()
7566                    .to_string(),
7567                translation: Self::json_f32_array3(root.get(LIVE_KEY_TRANSLATION))
7568                    .unwrap_or([0.0, 0.0, 0.0]),
7569                rotation: Self::json_f32_array4(root.get(LIVE_KEY_ROTATION))
7570                    .unwrap_or([0.0, 0.0, 0.0, 1.0]),
7571                scale: Self::json_f32_array3(root.get(LIVE_KEY_SCALE)).unwrap_or([1.0, 1.0, 1.0]),
7572                blender_z_up: root
7573                    .get(LIVE_KEY_BLENDER_Z_UP)
7574                    .and_then(Value::as_bool)
7575                    .unwrap_or(false),
7576            },
7577            LIVE_DELTA_KIND_MATERIAL => BlenderLiveDelta3D::MaterialParams {
7578                material_name: root
7579                    .get(LIVE_KEY_MATERIAL_NAME)
7580                    .and_then(Value::as_str)
7581                    .unwrap_or_default()
7582                    .to_string(),
7583                base_color_factor: Self::json_f32_array4(root.get(LIVE_KEY_BASE_COLOR)),
7584                metallic_factor: root
7585                    .get(LIVE_KEY_METALLIC)
7586                    .and_then(Value::as_f64)
7587                    .map(|val: f64| val as f32),
7588                roughness_factor: root
7589                    .get(LIVE_KEY_ROUGHNESS)
7590                    .and_then(Value::as_f64)
7591                    .map(|val: f64| val as f32),
7592                clearcoat_factor: root
7593                    .get(LIVE_KEY_CLEARCOAT)
7594                    .and_then(Value::as_f64)
7595                    .map(|val: f64| val as f32),
7596                clearcoat_roughness_factor: root
7597                    .get(LIVE_KEY_CLEARCOAT_ROUGHNESS)
7598                    .and_then(Value::as_f64)
7599                    .map(|val: f64| val as f32),
7600                sheen_color_factor: Self::json_f32_array3(root.get(LIVE_KEY_SHEEN_COLOR)),
7601                sheen_roughness_factor: root
7602                    .get(LIVE_KEY_SHEEN_ROUGHNESS)
7603                    .and_then(Value::as_f64)
7604                    .map(|val: f64| val as f32),
7605                emissive_factor: Self::json_f32_array3(root.get(LIVE_KEY_EMISSIVE)),
7606                emissive_strength: root
7607                    .get(LIVE_KEY_EMISSIVE_STRENGTH)
7608                    .and_then(Value::as_f64)
7609                    .map(|val: f64| val as f32),
7610                transmission_factor: root
7611                    .get(LIVE_KEY_TRANSMISSION)
7612                    .and_then(Value::as_f64)
7613                    .map(|val: f64| val as f32),
7614                ior: root
7615                    .get("ior")
7616                    .and_then(Value::as_f64)
7617                    .map(|val: f64| val as f32),
7618            },
7619            LIVE_DELTA_KIND_MORPH => {
7620                let parsed_weights: Vec<f32> = root
7621                    .get(LIVE_KEY_WEIGHTS)
7622                    .and_then(Value::as_array)
7623                    .map(|items: &Vec<Value>| {
7624                        items
7625                            .iter()
7626                            .filter_map(|elem: &Value| elem.as_f64().map(|val: f64| val as f32))
7627                            .collect()
7628                    })
7629                    .unwrap_or_default();
7630                BlenderLiveDelta3D::MorphWeights {
7631                    node_name: root
7632                        .get(LIVE_KEY_NODE_NAME)
7633                        .and_then(Value::as_str)
7634                        .unwrap_or_default()
7635                        .to_string(),
7636                    weights: parsed_weights,
7637                }
7638            }
7639            LIVE_DELTA_KIND_LIGHT => BlenderLiveDelta3D::LightUpdate {
7640                light_index: root
7641                    .get(LIVE_KEY_LIGHT_INDEX)
7642                    .and_then(Value::as_u64)
7643                    .unwrap_or(0) as usize,
7644                color: Self::json_f32_array3(root.get(LIVE_KEY_COLOR)),
7645                intensity: root
7646                    .get(LIVE_KEY_INTENSITY)
7647                    .and_then(Value::as_f64)
7648                    .map(|val: f64| val as f32),
7649                position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION)),
7650                direction: Self::json_f32_array3(root.get(LIVE_KEY_DIRECTION)),
7651            },
7652            LIVE_DELTA_KIND_CAMERA => BlenderLiveDelta3D::CameraUpdate {
7653                position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION))
7654                    .unwrap_or([0.0, 2.0, 6.0]),
7655                yaw: root
7656                    .get("yaw")
7657                    .and_then(Value::as_f64)
7658                    .map_or(0.0, |val: f64| val as f32),
7659                pitch: root
7660                    .get(LIVE_KEY_PITCH)
7661                    .and_then(Value::as_f64)
7662                    .map_or(0.0, |val: f64| val as f32),
7663                fov_deg: root
7664                    .get(LIVE_KEY_FOV_DEG)
7665                    .and_then(Value::as_f64)
7666                    .map_or(60.0, |val: f64| val as f32),
7667            },
7668            LIVE_DELTA_KIND_COLLECTION => BlenderLiveDelta3D::CollectionVisibility {
7669                collection_name: root
7670                    .get(LIVE_KEY_COLLECTION_NAME)
7671                    .and_then(Value::as_str)
7672                    .unwrap_or_default()
7673                    .to_string(),
7674                visible: root
7675                    .get(LIVE_KEY_VISIBLE)
7676                    .and_then(Value::as_bool)
7677                    .unwrap_or(true),
7678            },
7679            LIVE_DELTA_KIND_ENVIRONMENT => BlenderLiveDelta3D::EnvironmentUpdate {
7680                rotation_y_rad: root
7681                    .get(LIVE_KEY_ROTATION_Y_RAD)
7682                    .and_then(Value::as_f64)
7683                    .map_or(0.0, |val: f64| val as f32),
7684                intensity: root
7685                    .get(LIVE_KEY_INTENSITY)
7686                    .and_then(Value::as_f64)
7687                    .map_or(1.0, |val: f64| val as f32),
7688            },
7689            _ => return Err(ERR_LIVE_DELTA_UNKNOWN_KIND.to_string()),
7690        };
7691        Ok(self.apply_live_delta(&delta))
7692    }
7693
7694    /// Synchronizes linked `SceneObject3D` and `SceneCamera3D` transforms from `scene_graph` propagated world matrices.
7695    ///
7696    /// # Returns
7697    ///
7698    /// - `usize` - Number of linked objects or cameras whose transforms were synchronized.
7699    fn sync_objects_from_scene_graph(&mut self) -> usize {
7700        let Self {
7701            mesh_library,
7702            objects,
7703            scene_graph,
7704            scene_cameras,
7705            node_object_map,
7706            deformed_meshes,
7707            ..
7708        } = self;
7709        let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
7710        let mut synced_count: usize = 0;
7711        for (node_idx, obj_slot) in node_object_map.iter().enumerate() {
7712            let Some(obj_idx) = *obj_slot else {
7713                continue;
7714            };
7715            if node_idx >= nodes.len() || obj_idx >= objects.len() {
7716                continue;
7717            }
7718            let world_tr: Transform3D =
7719                Transform3D::from_matrix(nodes[node_idx].get_world_matrix());
7720            if objects[obj_idx].get_transform() != world_tr {
7721                objects[obj_idx].set_transform(world_tr);
7722                let local_bounds: AxisAlignedBox3D = deformed_meshes
7723                    .get(obj_idx)
7724                    .and_then(Option::as_ref)
7725                    .map(Mesh3D::get_bounds)
7726                    .or_else(|| {
7727                        mesh_library
7728                            .get(objects[obj_idx].get_mesh_id())
7729                            .and_then(|chain: &MeshLodChain| chain.get_levels().first())
7730                            .map(Mesh3D::get_bounds)
7731                    })
7732                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
7733                objects[obj_idx].set_world_bounds(world_tr.transform_bounds(local_bounds));
7734                synced_count += 1;
7735            }
7736        }
7737        for cam_mut in scene_cameras.iter_mut() {
7738            if let Some(node_id) = cam_mut.try_get_node_id()
7739                && let Some(node_ref) = nodes.get(node_id as usize)
7740            {
7741                let (pos_val, rot_val, _scale_val): (Vec3, Quat, Vec3) =
7742                    node_ref.get_world_matrix().decompose_trs();
7743                cam_mut.set_position(pos_val);
7744                cam_mut.set_rotation(rot_val);
7745                synced_count += 1;
7746            }
7747        }
7748        synced_count
7749    }
7750
7751    /// Offsets all texture indices inside `material` by `texture_base` when merging an imported scene.
7752    ///
7753    /// # Arguments
7754    ///
7755    /// - `&mut PrincipledMaterial3D` - Mutable material whose texture slots are rebased.
7756    /// - `u32` - Texture pool offset.
7757    fn rebase_material_textures(material: &mut PrincipledMaterial3D, texture_base: u32) {
7758        if texture_base == 0 {
7759            return;
7760        }
7761        let shift_slot: fn(Option<TextureSlot3D>, u32) -> Option<TextureSlot3D> =
7762            |slot_opt: Option<TextureSlot3D>, base_val: u32| -> Option<TextureSlot3D> {
7763                slot_opt.map(|mut slot: TextureSlot3D| {
7764                    slot.set_texture_index(slot.get_texture_index().saturating_add(base_val));
7765                    slot
7766                })
7767            };
7768        material.set_base_color_texture(shift_slot(
7769            material.try_get_base_color_texture(),
7770            texture_base,
7771        ));
7772        material.set_metallic_roughness_texture(shift_slot(
7773            material.try_get_metallic_roughness_texture(),
7774            texture_base,
7775        ));
7776        material.set_normal_texture(shift_slot(material.try_get_normal_texture(), texture_base));
7777        material.set_occlusion_texture(shift_slot(
7778            material.try_get_occlusion_texture(),
7779            texture_base,
7780        ));
7781        material.set_emissive_texture(shift_slot(
7782            material.try_get_emissive_texture(),
7783            texture_base,
7784        ));
7785        material.set_specular_texture(shift_slot(
7786            material.try_get_specular_texture(),
7787            texture_base,
7788        ));
7789        material.set_specular_color_texture(shift_slot(
7790            material.try_get_specular_color_texture(),
7791            texture_base,
7792        ));
7793        material.set_clearcoat_texture(shift_slot(
7794            material.try_get_clearcoat_texture(),
7795            texture_base,
7796        ));
7797        material.set_clearcoat_roughness_texture(shift_slot(
7798            material.try_get_clearcoat_roughness_texture(),
7799            texture_base,
7800        ));
7801        material.set_clearcoat_normal_texture(shift_slot(
7802            material.try_get_clearcoat_normal_texture(),
7803            texture_base,
7804        ));
7805        material.set_transmission_texture(shift_slot(
7806            material.try_get_transmission_texture(),
7807            texture_base,
7808        ));
7809        material.set_sheen_color_texture(shift_slot(
7810            material.try_get_sheen_color_texture(),
7811            texture_base,
7812        ));
7813        material.set_sheen_roughness_texture(shift_slot(
7814            material.try_get_sheen_roughness_texture(),
7815            texture_base,
7816        ));
7817    }
7818
7819    /// Extracts a 3-element `f32` array from an optional JSON array value.
7820    ///
7821    /// # Arguments
7822    ///
7823    /// - `Option<&Value>` - Optional JSON node.
7824    ///
7825    /// # Returns
7826    ///
7827    /// - `Option<[f32; 3]>` - Decoded array when three numeric entries exist.
7828    #[must_use]
7829    fn json_f32_array3(val: Option<&Value>) -> Option<[f32; 3]> {
7830        let arr: &Vec<Value> = val?.as_array()?;
7831        if arr.len() < 3 {
7832            return None;
7833        }
7834        Some([
7835            arr[0].as_f64()? as f32,
7836            arr[1].as_f64()? as f32,
7837            arr[2].as_f64()? as f32,
7838        ])
7839    }
7840
7841    /// Extracts a 4-element `f32` array from an optional JSON array value.
7842    ///
7843    /// # Arguments
7844    ///
7845    /// - `Option<&Value>` - Optional JSON node.
7846    ///
7847    /// # Returns
7848    ///
7849    /// - `Option<[f32; 4]>` - Decoded array when four numeric entries exist.
7850    #[must_use]
7851    fn json_f32_array4(val: Option<&Value>) -> Option<[f32; 4]> {
7852        let arr: &Vec<Value> = val?.as_array()?;
7853        if arr.len() < 4 {
7854            return None;
7855        }
7856        Some([
7857            arr[0].as_f64()? as f32,
7858            arr[1].as_f64()? as f32,
7859            arr[2].as_f64()? as f32,
7860            arr[3].as_f64()? as f32,
7861        ])
7862    }
7863
7864    /// Allocates a globally unique non-zero revision tag for `GpuWorld3dMeshBuffer` VRAM caching across distinct `World3D` instances.
7865    ///
7866    /// # Returns
7867    ///
7868    /// - `u64` - Monotonically increasing non-zero mesh revision tag.
7869    #[must_use]
7870    pub fn allocate_gpu_mesh_revision() -> u64 {
7871        NEXT_GPU_WORLD3D_MESH_REVISION
7872            .fetch_add(1, Ordering::Relaxed)
7873            .max(1)
7874    }
7875
7876    /// Appends a smooth-shaded unit octahedron particle primitive (`8` triangles, `24` vertices) to `vertices`, returning its `(vertex_start, vertex_count)` range.
7877    ///
7878    /// # Arguments
7879    ///
7880    /// - `&mut Vec<GpuWorld3dVertex>` - Destination static GPU vertex buffer.
7881    ///
7882    /// # Returns
7883    ///
7884    /// - `(u32, u32)` - Starting vertex index and vertex count (`24`) for hardware-instanced Niagara particles.
7885    fn append_unit_particle_octahedron(vertices: &mut Vec<GpuWorld3dVertex>) -> (u32, u32) {
7886        let start_idx: u32 = vertices.len() as u32;
7887        let top: [f32; 3] = [0.0, 1.0, 0.0];
7888        let bot: [f32; 3] = [0.0, -1.0, 0.0];
7889        let pos_x: [f32; 3] = [1.0, 0.0, 0.0];
7890        let neg_x: [f32; 3] = [-1.0, 0.0, 0.0];
7891        let pos_z: [f32; 3] = [0.0, 0.0, 1.0];
7892        let neg_z: [f32; 3] = [0.0, 0.0, -1.0];
7893        let faces: [[[f32; 3]; 3]; 8] = [
7894            [top, pos_z, pos_x],
7895            [top, pos_x, neg_z],
7896            [top, neg_z, neg_x],
7897            [top, neg_x, pos_z],
7898            [bot, pos_x, pos_z],
7899            [bot, neg_z, pos_x],
7900            [bot, neg_x, neg_z],
7901            [bot, pos_z, neg_x],
7902        ];
7903        vertices.reserve(24);
7904        for tri in faces.iter() {
7905            for corner in tri.iter() {
7906                vertices.push(GpuWorld3dVertex::new(
7907                    [corner[0], corner[1], corner[2], 1.0],
7908                    [corner[0], corner[1], corner[2], 0.0],
7909                    [1.0, 1.0, 1.0, 0.0],
7910                ));
7911            }
7912        }
7913        let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
7914        (start_idx, vert_count)
7915    }
7916
7917    /// Flattens every registered `LOD0` prototype mesh in `mesh_library` plus one shared unit Niagara particle primitive into one resident GPU vertex buffer and per-mesh `(vertex_start, vertex_count)` table.
7918    ///
7919    /// # Arguments
7920    ///
7921    /// - `&Self` - World reference.
7922    /// - `u64` - Monotonic revision tag attached to the built buffer for VRAM upload caching.
7923    ///
7924    /// # Returns
7925    ///
7926    /// - `(Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>)` - Shared static GPU vertex buffer and per-mesh range table (with the Niagara particle primitive appended at index `mesh_library.len()`).
7927    #[must_use]
7928    pub fn build_gpu_mesh_buffer(
7929        &self,
7930        revision: u64,
7931    ) -> (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
7932        let mut vertices: Vec<GpuWorld3dVertex> = Vec::new();
7933        let mut ranges: Vec<(u32, u32)> = Vec::with_capacity(self.get_mesh_library().len() + 1);
7934        for chain in self.get_mesh_library() {
7935            let start_idx: u32 = vertices.len() as u32;
7936            if let Some(mesh) = chain.get_levels().first() {
7937                let mesh_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
7938                let tri_mats: &[u16] = mesh.get_tri_materials().as_slice();
7939                let sub_mats: &[PbrMaterial] = mesh.get_sub_materials().as_slice();
7940                vertices.reserve(mesh.get_indices().len() * 3);
7941                for (tri_idx, &[i0, i1, i2]) in mesh.get_indices().iter().enumerate() {
7942                    let (Some(v0), Some(v1), Some(v2)) = (
7943                        mesh_verts.get(i0 as usize),
7944                        mesh_verts.get(i1 as usize),
7945                        mesh_verts.get(i2 as usize),
7946                    ) else {
7947                        continue;
7948                    };
7949                    let mat_slot: usize = tri_mats.get(tri_idx).copied().unwrap_or(0) as usize;
7950                    let color_submat: [f32; 4] = if mat_slot > 0
7951                        && let Some(sub_mat) = sub_mats.get(mat_slot - 1)
7952                    {
7953                        let base_c: Vec3 = sub_mat.get_base_color();
7954                        let em_c: Vec3 = sub_mat.get_emissive();
7955                        if em_c.length_sq() > 0.01 {
7956                            [
7957                                base_c.get_x() + em_c.get_x() * 1.4,
7958                                base_c.get_y() + em_c.get_y() * 1.4,
7959                                base_c.get_z() + em_c.get_z() * 1.4,
7960                                2.0,
7961                            ]
7962                        } else {
7963                            [base_c.get_x(), base_c.get_y(), base_c.get_z(), 1.0]
7964                        }
7965                    } else {
7966                        [1.0, 1.0, 1.0, 0.0]
7967                    };
7968                    for vert in [v0, v1, v2] {
7969                        let pos: Vec3 = vert.get_position();
7970                        let nrm: Vec3 = vert.get_normal();
7971                        vertices.push(GpuWorld3dVertex::new(
7972                            [pos.get_x(), pos.get_y(), pos.get_z(), 1.0],
7973                            [nrm.get_x(), nrm.get_y(), nrm.get_z(), 0.0],
7974                            color_submat,
7975                        ));
7976                    }
7977                }
7978            }
7979            let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
7980            ranges.push((start_idx, vert_count));
7981        }
7982        let particle_range: (u32, u32) = Self::append_unit_particle_octahedron(&mut vertices);
7983        ranges.push(particle_range);
7984        (
7985            Arc::new(GpuWorld3dMeshBuffer { revision, vertices }),
7986            ranges,
7987        )
7988    }
7989
7990    /// Populates `out` with a frustum-culled hardware GPU 3D scene pass using `scratch`, performing O(1) indexed dynamic pose lookups and zero `Vec<Vec<_>>` heap allocations.
7991    ///
7992    /// # Arguments
7993    ///
7994    /// - `&Self` - World reference.
7995    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
7996    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
7997    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
7998    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
7999    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
8000    /// - `(&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass)` - Persistent flat scratch arena and destination scene pass reused across frames.
8001    fn populate_gpu_scene_pass_with_scratch(
8002        &self,
8003        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
8004        alpha: f32,
8005        viewport: (u32, u32),
8006        quality: &RenderQualityConfig,
8007        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
8008        buffers: (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass),
8009    ) {
8010        let (scratch, out): (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass) = buffers;
8011        let (target_width, target_height): (u32, u32) = viewport;
8012        let (mesh_buffer, mesh_ranges): (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]) = mesh_cache;
8013        let blend_alpha: f32 = alpha.clamp(0.0, 1.0);
8014        let prev_snap: &World3DSnapshot = snapshots.get_prev_state();
8015        let curr_snap: &World3DSnapshot = snapshots.get_curr_state();
8016        let mut interp_cam: Camera3D = if curr_snap.get_camera_cut() {
8017            curr_snap.get_camera()
8018        } else {
8019            prev_snap
8020                .get_camera()
8021                .lerp(curr_snap.get_camera(), blend_alpha)
8022        };
8023        let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
8024        if aspect > 3.5 {
8025            let pull_back: f32 = ((aspect - 3.5) * 0.42).min(1.6);
8026            let shifted_pos: Vec3 = interp_cam
8027                .get_position()
8028                .sub(interp_cam.forward().scale(pull_back));
8029            interp_cam.set_position(shifted_pos);
8030        }
8031        let view_proj_mat: Mat4 = if let Some(cam_idx) = self.active_scene_camera_index()
8032            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
8033        {
8034            scene_cam.view_projection(aspect)
8035        } else {
8036            interp_cam.view_projection(aspect)
8037        };
8038        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
8039        let cam_pos: Vec3 = interp_cam.get_position();
8040        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
8041        let frustum_on: bool = quality.get_frustum_culling();
8042        let obj_len: usize = self.get_objects().len();
8043        if scratch.dynamic_pose_epochs.len() < obj_len {
8044            scratch.dynamic_pose_epochs.resize(obj_len, 0);
8045            scratch
8046                .dynamic_pose_transforms
8047                .resize(obj_len, Transform3D::default());
8048        }
8049        let next_epoch: u32 = scratch.current_epoch.wrapping_add(1);
8050        let active_epoch: u32 = if next_epoch == 0 {
8051            scratch.dynamic_pose_epochs.fill(0);
8052            1
8053        } else {
8054            next_epoch
8055        };
8056        scratch.current_epoch = active_epoch;
8057        let prev_objs: &[ObjectPose3D] = prev_snap.get_objects().as_slice();
8058        let next_objs: &[ObjectPose3D] = curr_snap.get_objects().as_slice();
8059        for (slot_idx, curr) in next_objs.iter().copied().enumerate() {
8060            let obj_idx: usize = curr.get_object_index();
8061            if obj_idx >= obj_len {
8062                continue;
8063            }
8064            let mut blended_tr: Transform3D = curr.get_transform();
8065            if curr.get_visible()
8066                && let Some(prev) = prev_objs.get(slot_idx).copied()
8067            {
8068                let continuous: bool = prev.get_visible()
8069                    && prev.get_object_index() == obj_idx
8070                    && prev.get_teleport_epoch() == curr.get_teleport_epoch();
8071                if continuous {
8072                    blended_tr = prev
8073                        .get_transform()
8074                        .lerp_shortest_angle(curr.get_transform(), blend_alpha);
8075                }
8076            }
8077            scratch.dynamic_pose_epochs[obj_idx] = active_epoch;
8078            scratch.dynamic_pose_transforms[obj_idx] = blended_tr;
8079        }
8080        let mesh_len: usize = mesh_ranges.len();
8081        if scratch.mesh_counts.len() < mesh_len {
8082            scratch.mesh_counts.resize(mesh_len, 0);
8083            scratch.mesh_cursors.resize(mesh_len, 0);
8084        }
8085        scratch.mesh_counts[..mesh_len].fill(0);
8086        scratch.visible_scratch.clear();
8087        let principled_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
8088        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
8089        for (obj_idx, obj) in self.get_objects().iter().enumerate() {
8090            if !self.is_object_visible(obj_idx) {
8091                continue;
8092            }
8093            let mesh_id: usize = obj.get_mesh_id();
8094            let Some(&(_, vert_count)) = mesh_ranges.get(mesh_id) else {
8095                continue;
8096            };
8097            if vert_count == 0 {
8098                continue;
8099            }
8100            let mut tr: Transform3D = obj.get_transform();
8101            let mut world_bounds: AxisAlignedBox3D = obj.get_world_bounds();
8102            if scratch.dynamic_pose_epochs[obj_idx] == active_epoch {
8103                tr = scratch.dynamic_pose_transforms[obj_idx];
8104                if let Some(chain) = mesh_lib.get(mesh_id)
8105                    && let Some(mesh0) = chain.get_levels().first()
8106                {
8107                    world_bounds = tr.transform_bounds(mesh0.get_bounds());
8108                }
8109            }
8110            let dist_sq: f32 = world_bounds.center().sub(cam_pos).length_sq();
8111            let radius: f32 = world_bounds.get_max().sub(world_bounds.get_min()).length() * 0.5;
8112            if dist_sq > draw_dist_sq + radius * radius * 4.0 {
8113                continue;
8114            }
8115            if frustum_on && !frustum.intersects_bounds(&world_bounds) {
8116                continue;
8117            }
8118            let mat: PbrMaterial = obj.get_material();
8119            let (albedo, metallic, roughness, emissive): (Vec3, f32, f32, Vec3) = if let Some(pm_id) =
8120                obj.try_get_principled_material_id()
8121                && let Some(pm) = principled_mats.get(pm_id as usize)
8122            {
8123                let bc: [f32; 4] = pm.get_base_color_factor();
8124                let em: [f32; 3] = pm.get_emissive_factor();
8125                let em_str: f32 = pm.get_emissive_strength();
8126                (
8127                    Vec3::new(bc[0], bc[1], bc[2]),
8128                    pm.get_metallic_factor(),
8129                    pm.get_roughness_factor(),
8130                    Vec3::new(em[0] * em_str, em[1] * em_str, em[2] * em_str),
8131                )
8132            } else {
8133                (
8134                    mat.get_base_color(),
8135                    mat.get_metallic(),
8136                    mat.get_roughness(),
8137                    mat.get_emissive(),
8138                )
8139            };
8140            let mut model_elems: [f32; 16] = tr.to_mat4().get_elements();
8141            model_elems[15] = match mat.get_surface_detail() {
8142                SurfaceDetailMode::None => 0.0,
8143                SurfaceDetailMode::RoadSurface => 1.0,
8144                SurfaceDetailMode::ArchitecturalFacade => 2.0,
8145                SurfaceDetailMode::OceanWater => 3.0,
8146            };
8147            scratch.mesh_counts[mesh_id] = scratch.mesh_counts[mesh_id].saturating_add(1);
8148            scratch.visible_scratch.push((
8149                mesh_id as u32,
8150                GpuWorld3dInstance::new(
8151                    model_elems,
8152                    [
8153                        albedo.get_x(),
8154                        albedo.get_y(),
8155                        albedo.get_z(),
8156                        metallic.clamp(0.0, 1.0),
8157                    ],
8158                    [
8159                        emissive.get_x(),
8160                        emissive.get_y(),
8161                        emissive.get_z(),
8162                        roughness.clamp(0.05, 1.0),
8163                    ],
8164                ),
8165            ));
8166        }
8167        let total_instances: usize = scratch.visible_scratch.len();
8168        out.draw_batches.clear();
8169        let mut cursor: u32 = 0;
8170        for (mesh_id, &(vertex_start, vertex_count)) in mesh_ranges.iter().enumerate() {
8171            let count: u32 = scratch.mesh_counts[mesh_id];
8172            scratch.mesh_cursors[mesh_id] = cursor;
8173            if count == 0 {
8174                continue;
8175            }
8176            out.draw_batches.push(GpuWorld3dMeshRange::new(
8177                vertex_start,
8178                vertex_count,
8179                cursor,
8180                count,
8181            ));
8182            cursor = cursor.saturating_add(count);
8183        }
8184        out.instances
8185            .resize(total_instances, GpuWorld3dInstance::default());
8186        for &(mesh_id_u32, inst) in scratch.visible_scratch.iter() {
8187            let mesh_id: usize = mesh_id_u32 as usize;
8188            let dst_idx: usize = scratch.mesh_cursors[mesh_id] as usize;
8189            scratch.mesh_cursors[mesh_id] = scratch.mesh_cursors[mesh_id].saturating_add(1);
8190            out.instances[dst_idx] = inst;
8191        }
8192        let particle_mesh_idx: usize = mesh_lib.len();
8193        if self.get_niagara().get_active_count() > 0
8194            && let Some(&(particle_vert_start, particle_vert_count)) =
8195                mesh_ranges.get(particle_mesh_idx)
8196            && particle_vert_count > 0
8197        {
8198            let particle_inst_start: u32 = out.instances.len() as u32;
8199            let active_frustum: Option<&Frustum3D> = if frustum_on { Some(&frustum) } else { None };
8200            let particle_inst_count: u32 = self.get_niagara().append_gpu_world3d_instances(
8201                cam_pos,
8202                draw_dist_sq,
8203                active_frustum,
8204                &mut out.instances,
8205            );
8206            if particle_inst_count > 0 {
8207                out.draw_batches.push(GpuWorld3dMeshRange::new(
8208                    particle_vert_start,
8209                    particle_vert_count,
8210                    particle_inst_start,
8211                    particle_inst_count,
8212                ));
8213            }
8214        }
8215        let sun: DirectionalLight3D = self.get_sun();
8216        let sun_dir: Vec3 = sun.get_direction().normalize();
8217        let sun_col: Vec3 = sun.get_color();
8218        let sky_hor: Vec3 = sun.get_sky_horizon();
8219        let sky_zen: Vec3 = sun.get_sky_zenith();
8220        let fog_density: f32 = if quality.get_volumetric_fog() {
8221            0.0028
8222        } else {
8223            0.0008
8224        };
8225        out.target_width = target_width;
8226        out.target_height = target_height;
8227        out.view_proj = view_proj_mat.get_elements();
8228        out.camera_pos = [cam_pos.get_x(), cam_pos.get_y(), cam_pos.get_z(), 1.15];
8229        out.sun_dir_fog = [
8230            sun_dir.get_x(),
8231            sun_dir.get_y(),
8232            sun_dir.get_z(),
8233            fog_density,
8234        ];
8235        out.sun_color_ambient = [sun_col.get_x(), sun_col.get_y(), sun_col.get_z(), 0.34];
8236        let anim_time: f32 =
8237            (sun.get_time_of_day() + self.get_world_time_secs()).rem_euclid(3600.0);
8238        out.sky_horizon_tod = [sky_hor.get_x(), sky_hor.get_y(), sky_hor.get_z(), anim_time];
8239        out.sky_zenith_aspect = [sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), aspect];
8240        out.mesh_buffer = Arc::clone(mesh_buffer);
8241    }
8242
8243    /// Populates a recycled `GpuWorld3dScenePass` in-place using `World3D`'s persistent flat scratch arena with zero per-frame heap allocations.
8244    ///
8245    /// # Arguments
8246    ///
8247    /// - `&Self` - Mutable world reference.
8248    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
8249    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
8250    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
8251    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
8252    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
8253    /// - `&mut GpuWorld3dScenePass` - Recycled scene pass destination populated in-place.
8254    pub fn build_gpu_scene_pass_into(
8255        &mut self,
8256        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
8257        alpha: f32,
8258        viewport: (u32, u32),
8259        quality: &RenderQualityConfig,
8260        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
8261        out: &mut GpuWorld3dScenePass,
8262    ) {
8263        let mut scratch: World3dGpuPassScratch = {
8264            let Self {
8265                gpu_pass_scratch, ..
8266            } = self;
8267            take(gpu_pass_scratch)
8268        };
8269        self.populate_gpu_scene_pass_with_scratch(
8270            snapshots,
8271            alpha,
8272            viewport,
8273            quality,
8274            mesh_cache,
8275            (&mut scratch, out),
8276        );
8277        let Self {
8278            gpu_pass_scratch, ..
8279        } = self;
8280        *gpu_pass_scratch = scratch;
8281    }
8282
8283    /// Rebuilds the cached quantized 24-byte `GpuPbrMeshBuffer` and per-LOD index ranges only when `mesh_library` geometry changes.
8284    ///
8285    /// # Arguments
8286    ///
8287    /// - `&[MeshLodChain]` - Active scene mesh library.
8288    /// - `&mut World3dPbrPassScratch` - Persistent PBR scratch cache storing the quantized `Arc<GpuPbrMeshBuffer>`.
8289    fn sync_pbr_quantized_mesh_cache(
8290        mesh_library: &[MeshLodChain],
8291        scratch: &mut World3dPbrPassScratch,
8292    ) {
8293        let mut total_verts: usize = 0;
8294        let mut total_indices: usize = 0;
8295        let mut any_skinned: bool = false;
8296        let mut any_morphed: bool = false;
8297        for chain in mesh_library.iter() {
8298            for mesh in chain.get_levels().iter().take(4) {
8299                total_verts = total_verts.saturating_add(mesh.get_vertices().len());
8300                total_indices =
8301                    total_indices.saturating_add(mesh.get_indices().len().saturating_mul(3));
8302                if !mesh.get_skin_influences().is_empty() {
8303                    any_skinned = true;
8304                }
8305                if !mesh.get_morph_targets().is_empty() {
8306                    any_morphed = true;
8307                }
8308            }
8309        }
8310        let signature: (usize, usize, usize) = (mesh_library.len(), total_verts, total_indices);
8311        if scratch.cached_signature == signature && scratch.cached_mesh_buffer.get_revision() > 0 {
8312            return;
8313        }
8314        let next_rev: u64 = NEXT_GPU_PBR_MESH_REVISION
8315            .fetch_add(1, Ordering::Relaxed)
8316            .max(1);
8317        let mut vertices: Vec<QuantizedVertex3D> = Vec::with_capacity(total_verts);
8318        let mut indices: Vec<u32> = Vec::with_capacity(total_indices);
8319        let mut skin_vertices: Vec<QuantizedSkinVertex3D> = if any_skinned {
8320            Vec::with_capacity(total_verts)
8321        } else {
8322            Vec::new()
8323        };
8324        let mut uv1_f16: Vec<[u16; 2]> = Vec::with_capacity(total_verts);
8325        let mut mesh_bounds_min: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
8326        let mut mesh_bounds_extent: Vec<[f32; 4]> = Vec::with_capacity(mesh_library.len());
8327        let mut morph_deltas: Vec<[f32; 4]> = if any_morphed && total_verts > 0 {
8328            vec![[0.0; 4]; total_verts.saturating_mul(4)]
8329        } else {
8330            Vec::new()
8331        };
8332        scratch.cached_lod_ranges.clear();
8333        scratch.cached_lod_ranges.reserve(mesh_library.len());
8334        let mut vert_tags: Vec<u8> = Vec::new();
8335        for chain in mesh_library.iter() {
8336            let levels: &[Mesh3D] = chain.get_levels().as_slice();
8337            let mut lod_ranges: [CachedPbrLodRange; 4] = [CachedPbrLodRange::default(); 4];
8338            let mut base_min: [f32; 4] = [0.0; 4];
8339            let mut base_ext: [f32; 4] = [1.0, 1.0, 1.0, 0.0];
8340            for (lod_idx, mesh) in levels.iter().take(4).enumerate() {
8341                let m_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
8342                let m_tris: &[[u32; 3]] = mesh.get_indices().as_slice();
8343                let mb: AxisAlignedBox3D = mesh.get_bounds();
8344                let bmin: Vec3 = mb.get_min();
8345                let bext_raw: Vec3 = mb.get_max().sub(bmin);
8346                let bext: Vec3 = Vec3::new(
8347                    bext_raw.get_x().max(1e-4),
8348                    bext_raw.get_y().max(1e-4),
8349                    bext_raw.get_z().max(1e-4),
8350                );
8351                let min_arr: [f32; 4] = [bmin.get_x(), bmin.get_y(), bmin.get_z(), 0.0];
8352                let ext_arr: [f32; 4] = [bext.get_x(), bext.get_y(), bext.get_z(), 0.0];
8353                if lod_idx == 0 {
8354                    base_min = min_arr;
8355                    base_ext = ext_arr;
8356                }
8357                vert_tags.clear();
8358                vert_tags.resize(m_verts.len(), 0);
8359                for (cluster_idx, meshlet) in mesh.get_meshlets().iter().enumerate() {
8360                    let tag: u8 = ((cluster_idx % 255) + 1) as u8;
8361                    let t_start: usize = meshlet.get_first_tri() as usize;
8362                    let t_end: usize = t_start
8363                        .saturating_add(meshlet.get_tri_count() as usize)
8364                        .min(m_tris.len());
8365                    for tri in &m_tris[t_start..t_end] {
8366                        for &vi in tri.iter() {
8367                            if let Some(slot) = vert_tags.get_mut(vi as usize) {
8368                                *slot = tag;
8369                            }
8370                        }
8371                    }
8372                }
8373                let base_vertex: u32 = vertices.len() as u32;
8374                let index_start: u32 = indices.len() as u32;
8375                let skins: &[MeshSkinInfluence3D] = mesh.get_skin_influences().as_slice();
8376                for (vi, vert) in m_verts.iter().enumerate() {
8377                    let tag: u8 = vert_tags.get(vi).copied().unwrap_or(0);
8378                    vertices.push(quantize_vertex_3d(vert, bmin, bext, tag));
8379                    let uv1: [f32; 2] = vert.get_uv1();
8380                    uv1_f16.push([encode_f32_to_f16(uv1[0]), encode_f32_to_f16(uv1[1])]);
8381                    if any_skinned {
8382                        let qskin: QuantizedSkinVertex3D = skins
8383                            .get(vi)
8384                            .map_or_else(QuantizedSkinVertex3D::default, quantize_skin_vertex_3d);
8385                        skin_vertices.push(qskin);
8386                    }
8387                }
8388                let has_morphs: bool = !mesh.get_morph_targets().is_empty();
8389                if any_morphed && has_morphs && total_verts > 0 {
8390                    for (t_idx, target) in mesh.get_morph_targets().iter().take(4).enumerate() {
8391                        let dpos: &[[f32; 3]] = target.get_delta_positions().as_slice();
8392                        let target_base: usize = t_idx
8393                            .saturating_mul(total_verts)
8394                            .saturating_add(base_vertex as usize);
8395                        for (vi, delta) in dpos.iter().take(m_verts.len()).enumerate() {
8396                            if let Some(dst) = morph_deltas.get_mut(target_base + vi) {
8397                                *dst = [delta[0], delta[1], delta[2], 0.0];
8398                            }
8399                        }
8400                    }
8401                }
8402                for tri in m_tris.iter() {
8403                    indices.push(base_vertex.saturating_add(tri[0]));
8404                    indices.push(base_vertex.saturating_add(tri[1]));
8405                    indices.push(base_vertex.saturating_add(tri[2]));
8406                }
8407                let index_count: u32 = (indices.len() as u32).saturating_sub(index_start);
8408                lod_ranges[lod_idx] = CachedPbrLodRange {
8409                    index_start,
8410                    index_count,
8411                    bounds_min: min_arr,
8412                    bounds_extent: ext_arr,
8413                    has_morphs,
8414                };
8415            }
8416            let avail: usize = levels.len().min(4);
8417            if avail > 0 && avail < 4 {
8418                let fallback_lod: CachedPbrLodRange = lod_ranges[avail - 1];
8419                for fill_slot in lod_ranges.iter_mut().skip(avail) {
8420                    *fill_slot = fallback_lod;
8421                }
8422            }
8423            mesh_bounds_min.push(base_min);
8424            mesh_bounds_extent.push(base_ext);
8425            scratch.cached_lod_ranges.push(lod_ranges);
8426        }
8427        scratch.cached_signature = signature;
8428        scratch.cached_mesh_buffer = Arc::new(GpuPbrMeshBuffer {
8429            revision: next_rev,
8430            vertices,
8431            indices,
8432            skin_vertices,
8433            morph_deltas,
8434            uv1_f16,
8435            mesh_bounds_min,
8436            mesh_bounds_extent,
8437        });
8438    }
8439
8440    /// Converts a legacy `PbrMaterial` into a std140 `GpuMaterialData3D` and deduplicates against `materials[fallback_base..]` to maximize instancing coalescing.
8441    ///
8442    /// # Arguments
8443    ///
8444    /// - `PbrMaterial` - Legacy per-object PBR material.
8445    /// - `usize` - Starting index of deduplicated fallback materials inside `materials`.
8446    /// - `&mut Vec<GpuMaterialData3D>` - Destination frame material table.
8447    ///
8448    /// # Returns
8449    ///
8450    /// - `u32` - Resolved material table slot index.
8451    fn resolve_fallback_gpu_material(
8452        mat: PbrMaterial,
8453        fallback_base: usize,
8454        materials: &mut Vec<GpuMaterialData3D>,
8455    ) -> u32 {
8456        let albedo: Vec3 = mat.get_base_color();
8457        let emissive: Vec3 = mat.get_emissive();
8458        let candidate: GpuMaterialData3D = GpuMaterialData3D {
8459            base_color_factor: [albedo.get_x(), albedo.get_y(), albedo.get_z(), 1.0],
8460            emissive_alpha_cutoff: [emissive.get_x(), emissive.get_y(), emissive.get_z(), 0.5],
8461            pbr_ior_specular: [
8462                mat.get_metallic().clamp(0.0, 1.0),
8463                mat.get_roughness().clamp(0.04, 1.0),
8464                PRINCIPLED_DEFAULT_IOR,
8465                1.0,
8466            ],
8467            specular_color_clearcoat: [1.0, 1.0, 1.0, 0.0],
8468            clearcoat_normal_occ_trans: [0.1, 1.0, 1.0, 0.0],
8469            volume_attenuation: [1.0, 1.0, 1.0, 0.0],
8470            sheen_color_roughness: [0.0, 0.0, 0.0, 0.5],
8471            tex_indices_a: [GPU_MATERIAL_NO_TEXTURE; 4],
8472            tex_indices_b: [GPU_MATERIAL_NO_TEXTURE; 4],
8473            flags_volume: [
8474                0,
8475                f32::INFINITY.to_bits(),
8476                GPU_MATERIAL_NO_TEXTURE,
8477                GPU_MATERIAL_NO_TEXTURE,
8478            ],
8479        };
8480        if let Some(rel_idx) = materials[fallback_base..]
8481            .iter()
8482            .position(|existing: &GpuMaterialData3D| *existing == candidate)
8483        {
8484            return (fallback_base + rel_idx) as u32;
8485        }
8486        let slot: u32 = materials.len() as u32;
8487        materials.push(candidate);
8488        slot
8489    }
8490
8491    /// Populates a recycled `GpuPbrScenePass` using borrowed `pbr_pass_scratch` and `skin_scratch` arenas with zero steady-state heap allocations.
8492    ///
8493    /// # Arguments
8494    ///
8495    /// - `&Self` - World reference.
8496    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
8497    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, LOD bias, and fog.
8498    /// - `&mut GpuUploadBelt` - Frame-budgeted GPU staging belt enforcing `<= 4 MiB` and `<= 1.5 ms` ceilings.
8499    /// - `&mut World3dPbrPassScratch` - Persistent PBR geometry cache and batcher scratch arena.
8500    /// - `&mut SkinPaletteScratch3D` - Reusable bone matrix evaluation workspace.
8501    /// - `&mut GpuPbrScenePass` - Destination hardware PBR scene pass overwritten in-place.
8502    fn populate_gpu_pbr_scene_pass_with_scratch(
8503        &self,
8504        viewport: (u32, u32),
8505        quality: &RenderQualityConfig,
8506        belt: &mut GpuUploadBelt,
8507        scratch: &mut World3dPbrPassScratch,
8508        skin_scratch: &mut SkinPaletteScratch3D,
8509        out: &mut GpuPbrScenePass,
8510    ) {
8511        belt.begin_frame();
8512        let prev_vp: [f32; 16] = out.get_view_proj();
8513        out.clear_frame_payloads();
8514        let (target_width, target_height): (u32, u32) = viewport;
8515        let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
8516        let (view_proj_mat, cam_pos, cam_fov_deg, cam_far): (Mat4, Vec3, f32, f32) =
8517            if let Some(cam_idx) = self.active_scene_camera_index()
8518                && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
8519            {
8520                let proj_cam: Camera3D = scene_cam.to_camera3d();
8521                (
8522                    scene_cam.view_projection(aspect),
8523                    scene_cam.get_position(),
8524                    proj_cam.get_fov_deg(),
8525                    proj_cam.get_far(),
8526                )
8527            } else {
8528                let cam: Camera3D = self.get_camera();
8529                (
8530                    cam.view_projection(aspect),
8531                    cam.get_position(),
8532                    cam.get_fov_deg(),
8533                    cam.get_far(),
8534                )
8535            };
8536        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
8537        Self::sync_pbr_quantized_mesh_cache(mesh_lib, scratch);
8538        let src_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
8539        let dst_mats: &mut Vec<GpuMaterialData3D> = out.get_mut_materials();
8540        if dst_mats.capacity() < src_mats.len() {
8541            dst_mats.reserve(src_mats.len() - dst_mats.len());
8542        }
8543        for mat_ref in src_mats.iter() {
8544            dst_mats.push(mat_ref.to_gpu_data());
8545        }
8546        let fallback_mat_base: usize = dst_mats.len();
8547        let dst_lights: &mut Vec<GpuPackedLocalLight> = out.get_mut_local_lights();
8548        for pl in self.get_point_lights().iter() {
8549            if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
8550                break;
8551            }
8552            let p: Vec3 = pl.get_position();
8553            let c: Vec3 = pl.get_color();
8554            dst_lights.push(GpuPackedLocalLight::new(
8555                [p.get_x(), p.get_y(), p.get_z(), pl.get_radius().max(0.1)],
8556                [c.get_x(), c.get_y(), c.get_z(), pl.get_intensity().max(0.0)],
8557                [0.0, -1.0, 0.0, 0.0],
8558                [-1.0, -1.0, 0.0, 0.0],
8559            ));
8560        }
8561        for sl in self.get_spot_lights().iter() {
8562            if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
8563                break;
8564            }
8565            let p: Vec3 = sl.get_position();
8566            let c: Vec3 = sl.get_color();
8567            let d: Vec3 = sl.get_direction().normalize();
8568            dst_lights.push(GpuPackedLocalLight::new(
8569                [p.get_x(), p.get_y(), p.get_z(), sl.get_range().max(0.1)],
8570                [c.get_x(), c.get_y(), c.get_z(), sl.get_intensity().max(0.0)],
8571                [d.get_x(), d.get_y(), d.get_z(), 1.0],
8572                [sl.get_inner_cos(), sl.get_outer_cos(), 0.0, 0.0],
8573            ));
8574        }
8575        for al in self.get_area_lights().iter() {
8576            if dst_lights.len() >= PBR_MAX_LOCAL_LIGHTS {
8577                break;
8578            }
8579            let p: Vec3 = al.get_position();
8580            let c: Vec3 = al.get_color();
8581            let d: Vec3 = al.get_direction().normalize();
8582            dst_lights.push(GpuPackedLocalLight::new(
8583                [p.get_x(), p.get_y(), p.get_z(), al.get_range().max(0.1)],
8584                [c.get_x(), c.get_y(), c.get_z(), al.get_intensity().max(0.0)],
8585                [d.get_x(), d.get_y(), d.get_z(), 2.0],
8586                [0.0, -1.0, al.get_width(), al.get_height()],
8587            ));
8588        }
8589        let sun: DirectionalLight3D = self.get_sun();
8590        let sun_dir: Vec3 = sun.get_direction().normalize();
8591        let sun_col: Vec3 = sun.get_color();
8592        let sky_hor: Vec3 = sun.get_sky_horizon();
8593        let sky_zen: Vec3 = sun.get_sky_zenith();
8594        let ibl_sh: [[f32; 4]; 9] = if let Some(env) = self.environment_ibl() {
8595            let raw: [[f32; 3]; 9] = env.get_sh_irradiance();
8596            let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
8597            for (dst, src) in packed.iter_mut().zip(raw.iter()) {
8598                *dst = [src[0], src[1], src[2], 0.0];
8599            }
8600            packed
8601        } else {
8602            let mut packed: [[f32; 4]; 9] = [[0.0; 4]; 9];
8603            let avg_r: f32 = (sky_hor.get_x() + sky_zen.get_x()) * 0.5;
8604            let avg_g: f32 = (sky_hor.get_y() + sky_zen.get_y()) * 0.5;
8605            let avg_b: f32 = (sky_hor.get_z() + sky_zen.get_z()) * 0.5;
8606            packed[0] = [avg_r * 1.35, avg_g * 1.35, avg_b * 1.35, 0.0];
8607            packed[1] = [
8608                (sky_zen.get_x() - sky_hor.get_x()) * 0.35,
8609                (sky_zen.get_y() - sky_hor.get_y()) * 0.35,
8610                (sky_zen.get_z() - sky_hor.get_z()) * 0.35,
8611                0.0,
8612            ];
8613            packed
8614        };
8615        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
8616        let frustum_planes: [[f32; 4]; 6] = frustum.get_planes();
8617        let half_h: f32 = (cam_fov_deg.clamp(12.0, 120.0).to_radians() * 0.5)
8618            .tan()
8619            .max(0.05);
8620        let focal_px: f32 = (target_height.max(1) as f32) * 0.5 / half_h;
8621        let draw_dist: f32 = quality.get_draw_distance().max(1.0);
8622        let draw_dist_sq: f32 = draw_dist * draw_dist;
8623        let frustum_on: bool = quality.get_frustum_culling();
8624        let chunk_on: bool = quality.get_chunk_streaming();
8625        let lod_bias: f32 = quality.get_lod_bias();
8626        let inv_far: f32 = 1.0 / cam_far.max(draw_dist).max(1.0);
8627        let objects: &[SceneObject3D] = self.get_objects().as_slice();
8628        let scene_graph: &SceneGraph3D = self.get_scene_graph();
8629        let skins: &[Skin3D] = self.get_skins().as_slice();
8630        let total_objs: usize = objects.len();
8631        scratch.batcher.get_mut_entries().clear();
8632        if scratch.batcher.get_entries().capacity() < total_objs {
8633            let need: usize = total_objs - scratch.batcher.get_entries().len();
8634            scratch.batcher.get_mut_entries().reserve(need);
8635        }
8636        let mut meshlets_tested: u32 = 0;
8637        let mut meshlets_culled: u32 = 0;
8638        let mut lod_counts: [u32; 4] = [0; 4];
8639        let mut base_idx: usize = 0;
8640        while base_idx < total_objs {
8641            let chunk: usize = (total_objs - base_idx).min(4);
8642            let mut min_x: [f32; 4] = [0.0; 4];
8643            let mut min_y: [f32; 4] = [0.0; 4];
8644            let mut min_z: [f32; 4] = [0.0; 4];
8645            let mut max_x: [f32; 4] = [0.0; 4];
8646            let mut max_y: [f32; 4] = [0.0; 4];
8647            let mut max_z: [f32; 4] = [0.0; 4];
8648            let mut vis_flags: u8 = 0;
8649            for lane in 0..chunk {
8650                let obj_idx: usize = base_idx + lane;
8651                if !self.is_object_visible(obj_idx) {
8652                    continue;
8653                }
8654                let wb: AxisAlignedBox3D = objects[obj_idx].get_world_bounds();
8655                let dist_sq: f32 = wb.center().sub(cam_pos).length_sq();
8656                if chunk_on && dist_sq > draw_dist_sq {
8657                    continue;
8658                }
8659                let bmin: Vec3 = wb.get_min();
8660                let bmax: Vec3 = wb.get_max();
8661                min_x[lane] = bmin.get_x();
8662                min_y[lane] = bmin.get_y();
8663                min_z[lane] = bmin.get_z();
8664                max_x[lane] = bmax.get_x();
8665                max_y[lane] = bmax.get_y();
8666                max_z[lane] = bmax.get_z();
8667                vis_flags |= 1u8 << lane;
8668            }
8669            let frustum_mask: u8 = if frustum_on && vis_flags != 0 {
8670                let aabb4: SimdAabbBatch4 =
8671                    SimdAabbBatch4::new(min_x, min_y, min_z, max_x, max_y, max_z);
8672                cull_aabb_batch4_simd(&frustum_planes, &aabb4)
8673            } else {
8674                0x0F
8675            };
8676            let active_mask: u8 = vis_flags & frustum_mask;
8677            for lane in 0..chunk {
8678                let obj_idx: usize = base_idx + lane;
8679                let obj: &SceneObject3D = &objects[obj_idx];
8680                let mesh_id: usize = obj.get_mesh_id();
8681                let Some(chain) = mesh_lib.get(mesh_id) else {
8682                    continue;
8683                };
8684                if ((active_mask >> lane) & 1) == 0 {
8685                    if self.is_object_visible(obj_idx)
8686                        && let Some(base_mesh) = chain.get_levels().first()
8687                    {
8688                        let mcount: u32 = base_mesh.get_meshlets().len().max(1) as u32;
8689                        meshlets_tested = meshlets_tested.saturating_add(mcount);
8690                        meshlets_culled = meshlets_culled.saturating_add(mcount);
8691                    }
8692                    continue;
8693                }
8694                let wb: AxisAlignedBox3D = obj.get_world_bounds();
8695                let dist: f32 = wb.center().sub(cam_pos).length();
8696                let (selected_mesh, raw_lod): (&Mesh3D, usize) =
8697                    chain.select_screen_error(dist, wb.radius(), focal_px, lod_bias);
8698                let lod_idx: usize = raw_lod.min(3);
8699                let Some(lod_arr) = scratch.cached_lod_ranges.get(mesh_id) else {
8700                    continue;
8701                };
8702                let lod_range: CachedPbrLodRange = lod_arr[lod_idx];
8703                if lod_range.index_count == 0 {
8704                    continue;
8705                }
8706                let model_mat: Mat4 = obj.get_transform().to_mat4();
8707                let (m_tested, m_culled): (u32, u32) = if !selected_mesh.get_meshlets().is_empty() {
8708                    cull_meshlets_simd(
8709                        selected_mesh.get_meshlets().as_slice(),
8710                        &model_mat,
8711                        &frustum,
8712                        cam_pos,
8713                        selected_mesh.get_is_closed(),
8714                    )
8715                } else {
8716                    (1, 0)
8717                };
8718                meshlets_tested = meshlets_tested.saturating_add(m_tested);
8719                meshlets_culled = meshlets_culled.saturating_add(m_culled);
8720                if selected_mesh.get_is_closed() && m_tested > 0 && m_culled >= m_tested {
8721                    continue;
8722                }
8723                lod_counts[lod_idx] = lod_counts[lod_idx].saturating_add(1);
8724                let mat_slot: u32 = if let Some(pid) = obj.try_get_principled_material_id()
8725                    && (pid as usize) < fallback_mat_base
8726                {
8727                    pid
8728                } else {
8729                    Self::resolve_fallback_gpu_material(
8730                        obj.get_material(),
8731                        fallback_mat_base,
8732                        out.get_mut_materials(),
8733                    )
8734                };
8735                let mat_flags: u32 = out
8736                    .get_materials()
8737                    .get(mat_slot as usize)
8738                    .map_or(0, |m: &GpuMaterialData3D| m.get_flags_volume()[0]);
8739                let is_alpha_blend: bool = (mat_flags & GPU_MATERIAL_FLAG_ALPHA_BLEND) != 0;
8740                let mut inst_flags: u32 = 0;
8741                let mut bone_off: u32 = 0;
8742                let mut pso_variant: u8 = PBR_PSO_VARIANT_OPAQUE;
8743                if let Some(skin_id) = obj.try_get_skin_id()
8744                    && let Some(skin_ref) = skins.get(skin_id as usize)
8745                {
8746                    bone_off = out.get_bone_matrices().len() as u32;
8747                    skin_ref.compute_skin_matrices_into(model_mat, scene_graph, skin_scratch);
8748                    let palette: &[Mat4] = skin_scratch.get_skin_matrices().as_slice();
8749                    let dst_bones: &mut Vec<[f32; 16]> = out.get_mut_bone_matrices();
8750                    if dst_bones.capacity() < dst_bones.len() + palette.len() {
8751                        dst_bones.reserve(palette.len());
8752                    }
8753                    for bm in palette.iter() {
8754                        dst_bones.push(bm.get_elements());
8755                    }
8756                    inst_flags |= PBR_INST_FLAG_SKINNED;
8757                    if skin_ref.get_skinning_mode() == SkinningMode::DualQuaternion {
8758                        inst_flags |= PBR_INST_FLAG_DQS;
8759                    }
8760                    pso_variant = PBR_PSO_VARIANT_SKINNED;
8761                }
8762                let mut morph_off: u32 = 0;
8763                if lod_range.has_morphs
8764                    && let Some(node_id) = obj.try_get_node_id()
8765                {
8766                    let mweights: &[f32] = scene_graph.morph_weights_for_node(node_id);
8767                    if !mweights.is_empty() {
8768                        morph_off = out.get_morph_weights().len() as u32;
8769                        let dst_mw: &mut Vec<f32> = out.get_mut_morph_weights();
8770                        for k in 0..4 {
8771                            dst_mw.push(mweights.get(k).copied().unwrap_or(0.0));
8772                        }
8773                        inst_flags |= PBR_INST_FLAG_MORPHED;
8774                    }
8775                }
8776                let alpha_pass: u8 = if is_alpha_blend {
8777                    pso_variant = PBR_PSO_VARIANT_ALPHA_BLEND;
8778                    inst_flags |= PBR_INST_FLAG_ALPHA_BLEND;
8779                    1
8780                } else {
8781                    0
8782                };
8783                let depth_q16: u16 = ((dist * inv_far).clamp(0.0, 1.0) * 65_535.0).round() as u16;
8784                let sort_key: u64 = pack_pbr_sort_key(
8785                    alpha_pass,
8786                    pso_variant,
8787                    mat_slot,
8788                    mesh_id as u32,
8789                    lod_idx as u8,
8790                    depth_q16,
8791                );
8792                let mut q_origin: [f32; 4] = lod_range.bounds_min;
8793                q_origin[3] = f32::from_bits(obj_idx as u32);
8794                let mut q_extent: [f32; 4] = lod_range.bounds_extent;
8795                q_extent[3] = lod_idx as f32;
8796                let instance: GpuPbrInstance3D = GpuPbrInstance3D::new(
8797                    model_mat.get_elements(),
8798                    q_origin,
8799                    q_extent,
8800                    [mat_slot, bone_off, morph_off, inst_flags],
8801                );
8802                scratch.batcher.get_mut_entries().push(PbrSortEntry3D {
8803                    sort_key,
8804                    index_start: lod_range.index_start,
8805                    index_count: lod_range.index_count,
8806                    base_vertex: 0,
8807                    material_index: mat_slot,
8808                    pso_variant,
8809                    lod_level: lod_idx as u8,
8810                    instance,
8811                });
8812            }
8813            base_idx += 4;
8814        }
8815        let draw_call_count: u32 = {
8816            let GpuPbrScenePass {
8817                instances,
8818                draw_batches,
8819                ..
8820            } = out;
8821            coalesce_pbr_batches_into(&mut scratch.batcher, instances, draw_batches)
8822        };
8823        let textures: &[Texture2D3D] = self.get_textures().as_slice();
8824        if scratch.uploaded_texture_min_mip.len() < textures.len() {
8825            scratch
8826                .uploaded_texture_min_mip
8827                .resize(textures.len(), u8::MAX);
8828        }
8829        for (slot_idx, tex) in textures.iter().enumerate() {
8830            let mips: &[TextureMipLevel3D] = tex.get_mips().as_slice();
8831            if mips.is_empty() {
8832                continue;
8833            }
8834            let current_min: u8 = scratch.uploaded_texture_min_mip[slot_idx];
8835            if current_min == 0 {
8836                continue;
8837            }
8838            let total_mips: u8 = mips.len().min(16) as u8;
8839            let (target_mip, priority): (u8, StreamPriority) = if current_min == u8::MAX {
8840                (total_mips.saturating_sub(1), StreamPriority::Critical)
8841            } else {
8842                let next_mip: u8 = current_min.saturating_sub(1);
8843                let prio: StreamPriority = if next_mip > 0 {
8844                    StreamPriority::VisibleHigh
8845                } else {
8846                    StreamPriority::PrefetchMedium
8847                };
8848                (next_mip, prio)
8849            };
8850            if let Some(mip_data) = mips.get(target_mip as usize) {
8851                let upload: GpuTextureMipUpload = GpuTextureMipUpload {
8852                    texture_slot: slot_idx as u32,
8853                    mip_level: target_mip,
8854                    total_mip_levels: total_mips,
8855                    is_srgb: tex.get_color_space() == TextureColorSpace::Srgb,
8856                    min_lod_clamp: target_mip,
8857                    width: mip_data.get_width(),
8858                    height: mip_data.get_height(),
8859                    rgba8: mip_data.get_pixels().clone(),
8860                };
8861                let _: GpuUploadTicket = belt.enqueue_mip_upload(priority, upload);
8862            }
8863        }
8864        let _: usize = belt.drain_mip_uploads_into(out.get_mut_texture_uploads());
8865        for uploaded in out.get_texture_uploads().iter() {
8866            let slot_idx: usize = uploaded.get_texture_slot() as usize;
8867            if let Some(watermark) = scratch.uploaded_texture_min_mip.get_mut(slot_idx) {
8868                *watermark = (*watermark).min(uploaded.get_mip_level());
8869            }
8870        }
8871        let fog_density: f32 = if quality.get_volumetric_fog() {
8872            0.0028
8873        } else {
8874            0.0008
8875        };
8876        let agx_flag: f32 = if self.get_use_agx_tonemap() { 1.0 } else { 0.0 };
8877        out.set_target_width(target_width);
8878        out.set_target_height(target_height);
8879        out.set_prev_view_proj(prev_vp);
8880        out.set_view_proj(view_proj_mat.get_elements());
8881        out.set_camera_pos_exposure([cam_pos.get_x(), cam_pos.get_y(), cam_pos.get_z(), 1.15]);
8882        out.set_sun_dir_fog([
8883            sun_dir.get_x(),
8884            sun_dir.get_y(),
8885            sun_dir.get_z(),
8886            fog_density,
8887        ]);
8888        out.set_sun_color_ambient([sun_col.get_x(), sun_col.get_y(), sun_col.get_z(), 0.34]);
8889        out.set_sky_horizon_tod([
8890            sky_hor.get_x(),
8891            sky_hor.get_y(),
8892            sky_hor.get_z(),
8893            sun.get_time_of_day(),
8894        ]);
8895        out.set_sky_zenith_agx([sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), agx_flag]);
8896        out.set_ibl_sh(ibl_sh);
8897        out.set_mesh_buffer(Arc::clone(&scratch.cached_mesh_buffer));
8898        let stats: GpuPbrCullStats = GpuPbrCullStats::new(
8899            meshlets_tested,
8900            meshlets_culled,
8901            lod_counts,
8902            draw_call_count,
8903            belt.get_frame_bytes_used(),
8904            belt.get_frame_time_us_used(),
8905        );
8906        out.set_stats(stats);
8907    }
8908
8909    /// Populates a recycled `GpuPbrScenePass` in-place with quantized 24-byte PBR geometry, SIMD frustum and meshlet normal-cone culling, 64-bit instanced sorting, LBS/DQS skinning, morph weights, local lights, SH9 IBL, and budget-capped incremental mip uploads with zero steady-state heap allocations.
8910    ///
8911    /// # Arguments
8912    ///
8913    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
8914    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, LOD bias, and fog.
8915    /// - `&mut GpuUploadBelt` - Frame-budgeted GPU staging belt enforcing `<= 4 MiB` and `<= 1.5 ms` ceilings.
8916    /// - `&mut GpuPbrScenePass` - Recycled PBR scene pass destination populated in-place.
8917    pub fn build_gpu_pbr_scene_pass_into(
8918        &mut self,
8919        viewport: (u32, u32),
8920        quality: &RenderQualityConfig,
8921        belt: &mut GpuUploadBelt,
8922        out: &mut GpuPbrScenePass,
8923    ) {
8924        let (mut pbr_work, mut skin_work): (World3dPbrPassScratch, SkinPaletteScratch3D) = {
8925            let Self {
8926                pbr_pass_scratch,
8927                skin_scratch,
8928                ..
8929            } = self;
8930            (take(pbr_pass_scratch), take(skin_scratch))
8931        };
8932        self.populate_gpu_pbr_scene_pass_with_scratch(
8933            viewport,
8934            quality,
8935            belt,
8936            &mut pbr_work,
8937            &mut skin_work,
8938            out,
8939        );
8940        let Self {
8941            pbr_pass_scratch,
8942            skin_scratch,
8943            ..
8944        } = self;
8945        *pbr_pass_scratch = pbr_work;
8946        *skin_scratch = skin_work;
8947    }
8948
8949    /// Builds a hardware GPU 3D scene pass by frustum-culling visible objects and grouping instanced transforms by `mesh_id` with zero `Vec<Vec<_>>` allocations and O(1) dynamic pose lookup.
8950    ///
8951    /// # Arguments
8952    ///
8953    /// - `&Self` - World reference.
8954    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
8955    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
8956    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
8957    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
8958    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
8959    ///
8960    /// # Returns
8961    ///
8962    /// - `GpuWorld3dScenePass` - Hardware instanced 3D scene pass descriptor ready for Metal, GLES3, D3D11, or WebGL2.
8963    #[must_use]
8964    pub fn build_gpu_scene_pass(
8965        &self,
8966        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
8967        alpha: f32,
8968        viewport: (u32, u32),
8969        quality: &RenderQualityConfig,
8970        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
8971    ) -> GpuWorld3dScenePass {
8972        let mut out: GpuWorld3dScenePass = GpuWorld3dScenePass::default();
8973        let used_tls: bool = WORLD3D_GPU_PASS_SCRATCH
8974            .try_with(|cell: &RefCell<World3dGpuPassScratch>| -> bool {
8975                if let Ok(mut scratch) = cell.try_borrow_mut() {
8976                    self.populate_gpu_scene_pass_with_scratch(
8977                        snapshots,
8978                        alpha,
8979                        viewport,
8980                        quality,
8981                        mesh_cache,
8982                        (&mut scratch, &mut out),
8983                    );
8984                    true
8985                } else {
8986                    false
8987                }
8988            })
8989            .unwrap_or(false);
8990        if !used_tls {
8991            let mut local_scratch: World3dGpuPassScratch = World3dGpuPassScratch::default();
8992            self.populate_gpu_scene_pass_with_scratch(
8993                snapshots,
8994                alpha,
8995                viewport,
8996                quality,
8997                mesh_cache,
8998                (&mut local_scratch, &mut out),
8999            );
9000        }
9001        out
9002    }
9003}
9004
9005/// Perspective and Orthographic projection matrix builders for `SceneCamera3D`.
9006impl SceneCamera3D {
9007    /// Builds a `SceneCamera3D` from an imported glTF/Blender `ImportedCamera3D` and node world pose.
9008    ///
9009    /// # Arguments
9010    ///
9011    /// - `&ImportedCamera3D` - Imported camera parameters.
9012    /// - `Option<u32>` - Optional owning scene-graph node index.
9013    /// - `Vec3` - World-space camera eye position.
9014    /// - `Quat` - World-space camera orientation quaternion.
9015    ///
9016    /// # Returns
9017    ///
9018    /// - `Self` - Constructed multi-camera entry.
9019    #[must_use]
9020    pub fn from_imported(
9021        imported: &ImportedCamera3D,
9022        node_id: Option<u32>,
9023        position: Vec3,
9024        rotation: Quat,
9025    ) -> Self {
9026        Self {
9027            name: imported.get_name().clone(),
9028            node_id,
9029            position,
9030            rotation: rotation.normalize(),
9031            projection: imported.get_projection(),
9032        }
9033    }
9034
9035    /// Returns the unit world-space forward direction along glTF local `-Z`.
9036    ///
9037    /// # Returns
9038    ///
9039    /// - `Vec3` - Unit forward vector.
9040    #[must_use]
9041    pub fn forward(&self) -> Vec3 {
9042        self.get_rotation()
9043            .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
9044            .normalize()
9045    }
9046
9047    /// Returns the unit world-space right direction along glTF local `+X`.
9048    ///
9049    /// # Returns
9050    ///
9051    /// - `Vec3` - Unit right vector.
9052    #[must_use]
9053    pub fn right(&self) -> Vec3 {
9054        self.get_rotation()
9055            .rotate_vec3(Vec3::new(1.0, 0.0, 0.0))
9056            .normalize()
9057    }
9058
9059    /// Returns the unit world-space up direction along glTF local `+Y`.
9060    ///
9061    /// # Returns
9062    ///
9063    /// - `Vec3` - Unit up vector.
9064    #[must_use]
9065    pub fn up(&self) -> Vec3 {
9066        self.get_rotation()
9067            .rotate_vec3(Vec3::new(0.0, 1.0, 0.0))
9068            .normalize()
9069    }
9070
9071    /// Returns `true` when this camera uses orthographic projection.
9072    ///
9073    /// # Returns
9074    ///
9075    /// - `bool` - Whether projection is orthographic.
9076    #[must_use]
9077    pub fn is_orthographic(&self) -> bool {
9078        matches!(
9079            self.get_projection(),
9080            GltfCameraProjection::Orthographic { .. }
9081        )
9082    }
9083
9084    /// Computes the combined `projection * view` matrix supporting both Perspective and Orthographic projections.
9085    ///
9086    /// # Arguments
9087    ///
9088    /// - `&Self` - Scene camera reference.
9089    /// - `f32` - Active viewport aspect ratio `width / height`.
9090    ///
9091    /// # Returns
9092    ///
9093    /// - `Mat4` - Combined view-projection matrix.
9094    #[must_use]
9095    pub fn view_projection(&self, viewport_aspect: f32) -> Mat4 {
9096        let pos: Vec3 = self.get_position();
9097        let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), self.up());
9098        let proj: Mat4 = match self.get_projection() {
9099            GltfCameraProjection::Perspective {
9100                yfov_rad,
9101                aspect_ratio,
9102                znear,
9103                zfar,
9104            } => Mat4::perspective(
9105                yfov_rad.clamp(0.15, 2.6),
9106                aspect_ratio.unwrap_or(viewport_aspect).max(0.1),
9107                znear.max(0.02),
9108                zfar.unwrap_or(480.0).max(znear + 1.0),
9109            ),
9110            GltfCameraProjection::Orthographic {
9111                xmag,
9112                ymag,
9113                znear,
9114                zfar,
9115            } => Mat4::orthographic_mag(xmag, ymag, znear.max(0.01), zfar.max(znear + 1.0)),
9116        };
9117        proj.mul(view)
9118    }
9119
9120    /// Projects this scene camera to a compatible `Camera3D` for primary viewport synchronization.
9121    ///
9122    /// # Returns
9123    ///
9124    /// - `Camera3D` - Equivalent perspective viewport camera descriptor.
9125    #[must_use]
9126    pub fn to_camera3d(&self) -> Camera3D {
9127        let fwd: Vec3 = self.forward();
9128        let yaw_val: f32 = fwd.get_z().atan2(fwd.get_x());
9129        let pitch_val: f32 = fwd.get_y().clamp(-0.98, 0.98).asin();
9130        let (fov_deg, near_val, far_val): (f32, f32, f32) = match self.get_projection() {
9131            GltfCameraProjection::Perspective {
9132                yfov_rad,
9133                znear,
9134                zfar,
9135                ..
9136            } => (
9137                yfov_rad.to_degrees().clamp(12.0, 120.0),
9138                znear.max(0.05),
9139                zfar.unwrap_or(480.0).max(10.0),
9140            ),
9141            GltfCameraProjection::Orthographic { znear, zfar, .. } => {
9142                (45.0, znear.max(0.05), zfar.max(10.0))
9143            }
9144        };
9145        let mut cam: Camera3D = Camera3D::default();
9146        cam.set_position(self.get_position());
9147        cam.set_yaw(yaw_val);
9148        cam.set_pitch(pitch_val);
9149        cam.set_fov_deg(fov_deg);
9150        cam.set_near(near_val);
9151        cam.set_far(far_val);
9152        cam
9153    }
9154}