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
663/// Conversion helpers for `CameraMode3D`.
664impl CameraMode3D {
665    /// Converts a numeric mode index (`0..=5`) into a typed `CameraMode3D`.
666    ///
667    /// # Arguments
668    ///
669    /// - `u8` - Numeric camera mode index.
670    ///
671    /// # Returns
672    ///
673    /// - `Self` - Corresponding `CameraMode3D`.
674    #[must_use]
675    pub const fn from_u8(index: u8) -> Self {
676        match index {
677            1 => Self::Hood,
678            2 => Self::Orbit,
679            3 => Self::Aerial,
680            4 => Self::FreeFly,
681            5 => Self::CinematicDolly,
682            _ => Self::Chase,
683        }
684    }
685
686    /// Converts this `CameraMode3D` into its stable numeric index (`0..=5`).
687    ///
688    /// # Arguments
689    ///
690    /// - `Self` - Camera mode variant.
691    ///
692    /// # Returns
693    ///
694    /// - `u8` - Numeric mode index.
695    #[must_use]
696    pub const fn as_u8(self) -> u8 {
697        match self {
698            Self::Chase => 0,
699            Self::Hood => 1,
700            Self::Orbit => 2,
701            Self::Aerial => 3,
702            Self::FreeFly => 4,
703            Self::CinematicDolly => 5,
704        }
705    }
706}
707
708/// Fluent builder helpers for `SpawnObjectDesc`.
709impl SpawnObjectDesc {
710    /// Creates an object spawn descriptor with identity transform, default PBR material, and BVH ray tracing enabled.
711    ///
712    /// # Arguments
713    ///
714    /// - `&str` - Human-readable object label.
715    /// - `usize` - Registered mesh identifier.
716    ///
717    /// # Returns
718    ///
719    /// - `Self` - Ready spawn descriptor.
720    #[must_use]
721    pub fn new(name: &str, mesh_id: usize) -> Self {
722        Self {
723            name: name.to_string(),
724            mesh_id,
725            transform: Transform3D::default(),
726            material: PbrMaterial::default(),
727            ray_trace_caster: true,
728            solid_collider: true,
729            spin_speed: 0.0,
730            is_dynamic: false,
731        }
732    }
733
734    /// Sets the world-space transform for the spawned object.
735    ///
736    /// # Arguments
737    ///
738    /// - `Self` - Base descriptor.
739    /// - `Transform3D` - World-space transform.
740    ///
741    /// # Returns
742    ///
743    /// - `Self` - Updated descriptor.
744    #[must_use]
745    pub fn with_transform(mut self, transform: Transform3D) -> Self {
746        self.set_transform(transform);
747        self
748    }
749
750    /// Sets the PBR surface material override for the spawned object.
751    ///
752    /// # Arguments
753    ///
754    /// - `Self` - Base descriptor.
755    /// - `PbrMaterial` - PBR material.
756    ///
757    /// # Returns
758    ///
759    /// - `Self` - Updated descriptor.
760    #[must_use]
761    pub fn with_material(mut self, material: PbrMaterial) -> Self {
762        self.set_material(material);
763        self
764    }
765
766    /// Sets whether this object casts BVH shadows and appears in reflections.
767    ///
768    /// # Arguments
769    ///
770    /// - `Self` - Base descriptor.
771    /// - `bool` - Ray-trace caster toggle.
772    ///
773    /// # Returns
774    ///
775    /// - `Self` - Updated descriptor.
776    #[must_use]
777    pub fn with_ray_trace(mut self, ray_trace_caster: bool) -> Self {
778        self.set_ray_trace_caster(ray_trace_caster);
779        self
780    }
781
782    /// Sets whether this object participates in solid vehicle and camera collision detection.
783    ///
784    /// # Arguments
785    ///
786    /// - `Self` - Base descriptor.
787    /// - `bool` - Solid collider toggle.
788    ///
789    /// # Returns
790    ///
791    /// - `Self` - Updated descriptor.
792    #[must_use]
793    pub fn with_solid_collider(mut self, solid_collider: bool) -> Self {
794        self.set_solid_collider(solid_collider);
795        self
796    }
797
798    /// Sets continuous Y-axis spin speed in radians per second.
799    ///
800    /// # Arguments
801    ///
802    /// - `Self` - Base descriptor.
803    /// - `f32` - Spin speed in radians/sec.
804    ///
805    /// # Returns
806    ///
807    /// - `Self` - Updated descriptor.
808    #[must_use]
809    pub fn with_spin(mut self, spin_speed: f32) -> Self {
810        self.set_spin_speed(spin_speed);
811        if spin_speed.abs() > 0.001 {
812            self.set_is_dynamic(true);
813        }
814        self
815    }
816
817    /// Explicitly marks whether this object belongs in the incrementally refitted dynamic BVH.
818    ///
819    /// # Arguments
820    ///
821    /// - `Self` - Base descriptor.
822    /// - `bool` - Dynamic caster flag.
823    ///
824    /// # Returns
825    ///
826    /// - `Self` - Updated descriptor.
827    #[must_use]
828    pub fn with_dynamic(mut self, is_dynamic: bool) -> Self {
829        self.set_is_dynamic(is_dynamic);
830        self
831    }
832}
833
834/// Fluent builder helpers for `ImportModelDesc`.
835impl ImportModelDesc {
836    /// Creates an external model import descriptor with identity transform and default PBR fallback material.
837    ///
838    /// # Arguments
839    ///
840    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
841    /// - `&str` - Raw model source text.
842    ///
843    /// # Returns
844    ///
845    /// - `Self` - Ready import descriptor.
846    #[must_use]
847    pub fn new(format: ModelFormat, source: &str) -> Self {
848        Self {
849            format,
850            source: source.to_string(),
851            transform: Transform3D::default(),
852            fallback_material: PbrMaterial::default(),
853            spin_speed: 0.0,
854        }
855    }
856
857    /// Sets the placement transform for the imported model.
858    ///
859    /// # Arguments
860    ///
861    /// - `Self` - Base descriptor.
862    /// - `Transform3D` - Placement transform.
863    ///
864    /// # Returns
865    ///
866    /// - `Self` - Updated descriptor.
867    #[must_use]
868    pub fn with_transform(mut self, transform: Transform3D) -> Self {
869        self.set_transform(transform);
870        self
871    }
872
873    /// Sets the fallback PBR material when source omits material metadata.
874    ///
875    /// # Arguments
876    ///
877    /// - `Self` - Base descriptor.
878    /// - `PbrMaterial` - Fallback PBR material.
879    ///
880    /// # Returns
881    ///
882    /// - `Self` - Updated descriptor.
883    #[must_use]
884    pub fn with_material(mut self, fallback_material: PbrMaterial) -> Self {
885        self.set_fallback_material(fallback_material);
886        self
887    }
888
889    /// Sets continuous Y-axis turntable spin speed in radians per second.
890    ///
891    /// # Arguments
892    ///
893    /// - `Self` - Base descriptor.
894    /// - `f32` - Spin speed in radians/sec.
895    ///
896    /// # Returns
897    ///
898    /// - `Self` - Updated descriptor.
899    #[must_use]
900    pub fn with_spin(mut self, spin_speed: f32) -> Self {
901        self.set_spin_speed(spin_speed);
902        self
903    }
904}
905
906/// Dynamic Time-of-Day sun and atmospheric sky lighting for `DirectionalLight3D`.
907impl DirectionalLight3D {
908    /// Computes physically inspired sun direction, sun color, and sky colors for `hour` in `[0.0, 24.0]`.
909    ///
910    /// # Arguments
911    ///
912    /// - `f32` - Hour of day (`6.0` dawn, `12.0` noon, `17.5` golden sunset, `22.0` neon night).
913    ///
914    /// # Returns
915    ///
916    /// - `Self` - Updated atmospheric directional light.
917    #[must_use]
918    pub fn from_time_of_day(hour: f32) -> Self {
919        let height_val: f32 = hour.rem_euclid(24.0);
920        let elev_angle: f32 = ((height_val - 6.0) / 12.0 * PI).clamp(-0.35, 3.49);
921        let sun_y: f32 = elev_angle.sin();
922        let sun_x: f32 = elev_angle.cos();
923        let dir: Vec3 = Vec3::new(-sun_x * 0.62, sun_y.max(0.22), -0.78).normalize();
924        if (7.5..=16.5).contains(&height_val) {
925            Self {
926                direction: dir,
927                color: Vec3::new(2.35, 2.18, 1.96),
928                sky_zenith: Vec3::new(0.08, 0.24, 0.64),
929                sky_horizon: Vec3::new(0.46, 0.66, 0.88),
930                time_of_day: height_val,
931            }
932        } else if (5.5..7.5).contains(&height_val) || (16.5..19.5).contains(&height_val) {
933            Self {
934                direction: Vec3::new(-0.14, 0.165, -0.976).normalize(),
935                color: Vec3::new(2.85, 1.42, 0.66),
936                sky_zenith: Vec3::new(0.028, 0.038, 0.155),
937                sky_horizon: Vec3::new(0.62, 0.24, 0.22),
938                time_of_day: height_val,
939            }
940        } else {
941            Self {
942                direction: Vec3::new(-0.36, 0.56, -0.74).normalize(),
943                color: Vec3::new(0.52, 0.68, 1.22),
944                sky_zenith: Vec3::new(0.012, 0.022, 0.068),
945                sky_horizon: Vec3::new(0.068, 0.115, 0.235),
946                time_of_day: height_val,
947            }
948        }
949    }
950}
951
952/// Default golden-sunset directional light.
953impl Default for DirectionalLight3D {
954    /// Creates a golden-hour sunset sun configuration.
955    ///
956    /// # Returns
957    ///
958    /// - `Self` - Sunset `DirectionalLight3D`.
959    fn default() -> Self {
960        Self::from_time_of_day(17.2)
961    }
962}
963
964/// Default empty 3D open world.
965impl Default for World3D {
966    /// Creates an empty `World3D` with 64m chunk streaming enabled.
967    ///
968    /// # Returns
969    ///
970    /// - `Self` - Empty `World3D`.
971    fn default() -> Self {
972        Self {
973            mesh_library: Vec::new(),
974            objects: Vec::new(),
975            camera: Camera3D::default(),
976            sun: DirectionalLight3D::default(),
977            bvh: Bvh3D::default(),
978            dynamic_bvh: Bvh3D::default(),
979            mesh_local_bvhs: Vec::new(),
980            dynamic_instances: Vec::new(),
981            bvh_dirty: true,
982            dynamic_bvh_dirty: true,
983            dynamic_topology_dirty: true,
984            static_bvh_rebuilds: 0,
985            dynamic_bvh_refits: 0,
986            dynamic_bvh_rebuilds: 0,
987            world_revision: 1,
988            dynamic_tris_scratch: Vec::new(),
989            chunk_size: 64.0,
990            player_vehicle_index: None,
991            imported_model_count: 0,
992            camera_mode: 0,
993            camera_orbit_rad: 0.4,
994            point_lights: Vec::new(),
995            spot_lights: Vec::new(),
996            niagara: NiagaraSystem3D::default(),
997            atmosphere_preset: 0,
998            traffic_vehicles: Vec::new(),
999            world_time_secs: 0.0,
1000            scene_graph: SceneGraph3D::default(),
1001            principled_materials: Vec::new(),
1002            textures: Vec::new(),
1003            skins: Vec::new(),
1004            animation_mixer: AnimationMixer3D::default(),
1005            environment_ibl: None,
1006            area_lights: Vec::new(),
1007            scene_cameras: Vec::new(),
1008            active_scene_camera: None,
1009            node_object_map: Vec::new(),
1010            skin_scratch: SkinPaletteScratch3D::default(),
1011            deformed_meshes: Vec::new(),
1012            use_agx_tonemap: false,
1013            gpu_pass_scratch: World3dGpuPassScratch::default(),
1014        }
1015    }
1016}
1017
1018/// Open-world construction, model importing, BVH rebuild, and live vehicle/camera simulation for `World3D`.
1019impl World3D {
1020    /// Registers a `MeshLodChain` in the instancing library and returns its `mesh_id`.
1021    ///
1022    /// # Arguments
1023    ///
1024    /// - `&Self` - Mutable world.
1025    /// - `MeshLodChain` - Multi-level LOD mesh chain.
1026    ///
1027    /// # Returns
1028    ///
1029    /// - `usize` - Assigned `mesh_id`.
1030    pub fn register_mesh(&mut self, chain: MeshLodChain) -> usize {
1031        let id: usize = self.get_mesh_library().len();
1032        self.get_mut_mesh_library().push(chain);
1033        id
1034    }
1035
1036    /// Spawns an instanced `SceneObject3D` referencing `mesh_id` into its spatial world chunk.
1037    ///
1038    /// # Arguments
1039    ///
1040    /// - `&Self` - Mutable world.
1041    /// - `&str` - Object name.
1042    /// - `usize` - Registered `mesh_id`.
1043    /// - `Transform3D` - World transform.
1044    /// - `PbrMaterial` - Surface PBR material.
1045    /// - `bool` - Whether this object participates in BVH ray tracing.
1046    ///
1047    /// # Returns
1048    ///
1049    /// - `usize` - Index of the spawned `SceneObject3D`.
1050    pub fn spawn_object(
1051        &mut self,
1052        name: &str,
1053        mesh_id: usize,
1054        transform: Transform3D,
1055        material: PbrMaterial,
1056        ray_trace_caster: bool,
1057    ) -> usize {
1058        let local_bounds: AxisAlignedBox3D = self
1059            .get_mesh_library()
1060            .get(mesh_id)
1061            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1062            .map(Mesh3D::get_bounds)
1063            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1064        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1065        let cs: f32 = self.get_chunk_size().max(8.0);
1066        let pos: Vec3 = transform.get_position();
1067        let chunk_coord: (i32, i32) = (
1068            (pos.get_x() / cs).floor() as i32,
1069            (pos.get_z() / cs).floor() as i32,
1070        );
1071        let idx: usize = self.get_objects().len();
1072        self.get_mut_objects().push(SceneObject3D {
1073            name: name.to_string(),
1074            mesh_id,
1075            transform,
1076            material,
1077            world_bounds,
1078            chunk_coord,
1079            ray_trace_caster,
1080            solid_collider: ray_trace_caster,
1081            spin_speed: 0.0,
1082            is_dynamic: false,
1083            teleport_epoch: 0,
1084            node_id: None,
1085            principled_material_id: None,
1086            skin_id: None,
1087        });
1088        let Self {
1089            deformed_meshes, ..
1090        } = self;
1091        deformed_meshes.push(None);
1092        if ray_trace_caster {
1093            self.set_bvh_dirty(true);
1094        }
1095        self.bump_world_revision();
1096        idx
1097    }
1098
1099    /// Increments the 3D world revision counter so 3D render caches invalidate independently of UI HUD updates.
1100    ///
1101    /// # Arguments
1102    ///
1103    /// - `&Self` - Mutable world.
1104    pub fn bump_world_revision(&mut self) {
1105        let next: u64 = self.get_world_revision().wrapping_add(1);
1106        self.set_world_revision(next);
1107    }
1108
1109    /// Marks object `obj_idx` as static or dynamic, routing its triangles between the static BVH and incrementally refitted dynamic BVH.
1110    ///
1111    /// # Arguments
1112    ///
1113    /// - `&Self` - Mutable world.
1114    /// - `usize` - Target object index in `objects`.
1115    /// - `bool` - `true` for dynamic BVH routing, `false` for static BVH routing.
1116    ///
1117    /// # Returns
1118    ///
1119    /// - `bool` - `true` when `obj_idx` existed and was updated.
1120    pub fn set_object_dynamic(&mut self, obj_idx: usize, is_dynamic: bool) -> bool {
1121        let Some(obj) = self.get_mut_objects().get_mut(obj_idx) else {
1122            return false;
1123        };
1124        if obj.get_is_dynamic() != is_dynamic {
1125            obj.set_is_dynamic(is_dynamic);
1126            if obj.get_ray_trace_caster() {
1127                self.set_bvh_dirty(true);
1128                self.set_dynamic_bvh_dirty(true);
1129                self.set_dynamic_topology_dirty(true);
1130            }
1131            self.bump_world_revision();
1132        }
1133        true
1134    }
1135
1136    /// Teleports object `obj_idx` to `transform`, incrementing `teleport_epoch` so snapshot interpolation snaps instead of sweeping.
1137    ///
1138    /// # Arguments
1139    ///
1140    /// - `&Self` - Mutable world.
1141    /// - `usize` - Target object index in `objects`.
1142    /// - `Transform3D` - Destination world transform.
1143    ///
1144    /// # Returns
1145    ///
1146    /// - `bool` - `true` when `obj_idx` existed and was teleported.
1147    pub fn teleport_object(&mut self, obj_idx: usize, transform: Transform3D) -> bool {
1148        let Some((mesh_id, ray_caster, is_dynamic)) =
1149            self.get_objects().get(obj_idx).map(|obj: &SceneObject3D| {
1150                (
1151                    obj.get_mesh_id(),
1152                    obj.get_ray_trace_caster(),
1153                    obj.get_is_dynamic(),
1154                )
1155            })
1156        else {
1157            return false;
1158        };
1159        let local_bounds: AxisAlignedBox3D = self
1160            .get_mesh_library()
1161            .get(mesh_id)
1162            .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
1163            .map(Mesh3D::get_bounds)
1164            .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
1165        let world_bounds: AxisAlignedBox3D = transform.transform_bounds(local_bounds);
1166        if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1167            obj.set_transform(transform);
1168            obj.set_world_bounds(world_bounds);
1169            let next_epoch: u32 = obj.get_teleport_epoch().wrapping_add(1);
1170            obj.set_teleport_epoch(next_epoch);
1171        }
1172        if ray_caster {
1173            if is_dynamic {
1174                self.set_dynamic_bvh_dirty(true);
1175            } else {
1176                self.set_bvh_dirty(true);
1177            }
1178        }
1179        self.bump_world_revision();
1180        true
1181    }
1182
1183    /// Imports an external `.obj` or `.gltf` model directly into the live 3D world and returns import telemetry.
1184    ///
1185    /// # Arguments
1186    ///
1187    /// - `&Self` - Mutable world.
1188    /// - `ModelFormat` - Source model format.
1189    /// - `&str` - Raw `.obj` or `.gltf` text content.
1190    /// - `Transform3D` - Placement transform in the 3D scene.
1191    /// - `PbrMaterial` - Fallback PBR material.
1192    /// - `f32` - Optional continuous Y-spin speed in radians/sec.
1193    ///
1194    /// # Returns
1195    ///
1196    /// - `Result<ImportedModel3D, String>` - Imported model summary or parse error.
1197    pub fn import_model(
1198        &mut self,
1199        format: ModelFormat,
1200        source: &str,
1201        transform: Transform3D,
1202        fallback_material: PbrMaterial,
1203        spin_speed: f32,
1204    ) -> Result<ImportedModel3D, String> {
1205        let imported: ImportedModel3D = ModelImporter3D::import(format, source, fallback_material)?;
1206        let model_name: String = imported.get_name().clone();
1207        for (item_index, chain) in imported.get_meshes().iter().cloned().enumerate() {
1208            let mat: PbrMaterial = chain
1209                .get_levels()
1210                .first()
1211                .map(Mesh3D::get_material)
1212                .unwrap_or(fallback_material);
1213            let mid: usize = self.register_mesh(chain);
1214            let obj_idx: usize = self.spawn_object(
1215                &format!("{model_name}_{item_index}"),
1216                mid,
1217                transform,
1218                mat,
1219                true,
1220            );
1221            if let Some(obj) = self.get_mut_objects().get_mut(obj_idx) {
1222                obj.set_spin_speed(spin_speed);
1223            }
1224            if spin_speed.abs() > 0.001 {
1225                let _: bool = self.set_object_dynamic(obj_idx, true);
1226            }
1227        }
1228        let next_cnt: usize = self.get_imported_model_count().saturating_add(1);
1229        self.set_imported_model_count(next_cnt);
1230        Ok(imported)
1231    }
1232
1233    /// Spawns an object from a fluent `SpawnObjectDesc`.
1234    ///
1235    /// # Arguments
1236    ///
1237    /// - `&Self` - Mutable world.
1238    /// - `&SpawnObjectDesc` - Spawn descriptor.
1239    ///
1240    /// # Returns
1241    ///
1242    /// - `usize` - Spawned object index.
1243    pub fn spawn_with(&mut self, desc: &SpawnObjectDesc) -> usize {
1244        let idx: usize = self.spawn_object(
1245            desc.get_name(),
1246            desc.get_mesh_id(),
1247            desc.get_transform(),
1248            desc.get_material(),
1249            desc.get_ray_trace_caster(),
1250        );
1251        if let Some(obj) = self.get_mut_objects().get_mut(idx) {
1252            obj.set_solid_collider(desc.get_solid_collider());
1253            obj.set_spin_speed(desc.get_spin_speed());
1254        }
1255        if desc.get_is_dynamic() || desc.get_spin_speed().abs() > 0.001 {
1256            let _: bool = self.set_object_dynamic(idx, true);
1257        }
1258        idx
1259    }
1260
1261    /// Imports an external `.obj` or `.gltf` model using a fluent `ImportModelDesc`.
1262    ///
1263    /// # Arguments
1264    ///
1265    /// - `&Self` - Mutable world.
1266    /// - `&ImportModelDesc` - Import descriptor.
1267    ///
1268    /// # Returns
1269    ///
1270    /// - `Result<ImportedModel3D, String>` - Imported model telemetry or parse error.
1271    pub fn import_with(&mut self, desc: &ImportModelDesc) -> Result<ImportedModel3D, String> {
1272        self.import_model(
1273            desc.get_format(),
1274            desc.get_source(),
1275            desc.get_transform(),
1276            desc.get_fallback_material(),
1277            desc.get_spin_speed(),
1278        )
1279    }
1280
1281    /// Returns the typed `CameraMode3D` currently active in this world.
1282    ///
1283    /// # Arguments
1284    ///
1285    /// - `&Self` - World reference.
1286    ///
1287    /// # Returns
1288    ///
1289    /// - `CameraMode3D` - Active typed camera controller mode.
1290    #[must_use]
1291    pub fn active_camera_mode(&self) -> CameraMode3D {
1292        CameraMode3D::from_u8(self.get_camera_mode())
1293    }
1294
1295    /// Sets the active 3D camera controller using a typed `CameraMode3D`.
1296    ///
1297    /// # Arguments
1298    ///
1299    /// - `&Self` - Mutable world.
1300    /// - `CameraMode3D` - Desired camera controller mode.
1301    pub fn set_camera_mode_enum(&mut self, mode: CameraMode3D) {
1302        self.set_camera_mode(mode.as_u8());
1303    }
1304
1305    /// Collects world-space triangles for all ray-trace casters matching `dynamic_filter` into `out_tris`.
1306    ///
1307    /// # Arguments
1308    ///
1309    /// - `&[SceneObject3D]` - World object slice.
1310    /// - `&[MeshLodChain]` - Registered mesh library slice.
1311    /// - `bool` - `true` to gather dynamic casters, `false` to gather static casters.
1312    /// - `&mut Vec<BvhTriangle>` - Destination triangle buffer cleared and populated in place.
1313    fn collect_caster_triangles(
1314        objects: &[SceneObject3D],
1315        mesh_library: &[MeshLodChain],
1316        dynamic_filter: bool,
1317        out_tris: &mut Vec<BvhTriangle>,
1318    ) {
1319        out_tris.clear();
1320        for obj in objects.iter() {
1321            if !obj.get_ray_trace_caster() || obj.get_is_dynamic() != dynamic_filter {
1322                continue;
1323            }
1324            let Some(chain) = mesh_library.get(obj.get_mesh_id()) else {
1325                continue;
1326            };
1327            let Some(mesh) = chain.get_levels().first() else {
1328                continue;
1329            };
1330            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1331            let model_m: Mat4 = obj.get_transform().to_mat4();
1332            let mat: PbrMaterial = obj.get_material();
1333            for (tri_idx, tri) in mesh.get_indices().iter().enumerate() {
1334                let (i0, i1, i2): (usize, usize, usize) =
1335                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1336                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1337                    let p0: Vec3 = model_m.mul_point3(verts[i0].get_position());
1338                    let p1: Vec3 = model_m.mul_point3(verts[i1].get_position());
1339                    let p2: Vec3 = model_m.mul_point3(verts[i2].get_position());
1340                    let (tri_mat, mat_slot): (PbrMaterial, u16) =
1341                        mesh.resolve_triangle_material(tri_idx, mat);
1342                    out_tris.push(BvhTriangle::from_points_with_slot(
1343                        p0, p1, p2, tri_mat, mat_slot,
1344                    ));
1345                }
1346            }
1347        }
1348    }
1349
1350    /// Synchronizes the split static and dynamic BVH acceleration structures, refitting moving dynamic casters in O(N) without rebuilding static world geometry.
1351    ///
1352    /// # Arguments
1353    ///
1354    /// - `&Self` - Mutable world.
1355    pub fn ensure_bvh(&mut self) {
1356        if self.get_bvh_dirty() {
1357            let mut static_tris: Vec<BvhTriangle> = Vec::new();
1358            Self::collect_caster_triangles(
1359                self.get_objects().as_slice(),
1360                self.get_mesh_library().as_slice(),
1361                false,
1362                &mut static_tris,
1363            );
1364            self.set_bvh(Bvh3D::build(static_tris));
1365            self.set_bvh_dirty(false);
1366            let next_static: u64 = self.get_static_bvh_rebuilds().saturating_add(1);
1367            self.set_static_bvh_rebuilds(next_static);
1368        }
1369        if self.get_dynamic_bvh_dirty() {
1370            let topology_dirty: bool = self.get_dynamic_topology_dirty();
1371            let Self {
1372                objects,
1373                mesh_library,
1374                dynamic_bvh,
1375                dynamic_tris_scratch,
1376                dynamic_bvh_dirty,
1377                dynamic_topology_dirty,
1378                dynamic_bvh_refits,
1379                dynamic_bvh_rebuilds,
1380                ..
1381            } = self;
1382            Self::collect_caster_triangles(
1383                objects.as_slice(),
1384                mesh_library.as_slice(),
1385                true,
1386                dynamic_tris_scratch,
1387            );
1388            if dynamic_tris_scratch.is_empty() {
1389                dynamic_bvh.rebuild_in_place(&[]);
1390            } else if !topology_dirty
1391                && dynamic_bvh.refit_from_source(dynamic_tris_scratch.as_slice())
1392            {
1393                let check_degraded: bool = ((*dynamic_bvh_refits + 1) & 15) == 0;
1394                if check_degraded && dynamic_bvh.needs_rebuild_after_refit(3.5) {
1395                    dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1396                    *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1397                } else {
1398                    *dynamic_bvh_refits = dynamic_bvh_refits.saturating_add(1);
1399                }
1400            } else {
1401                dynamic_bvh.rebuild_in_place(dynamic_tris_scratch.as_slice());
1402                *dynamic_bvh_rebuilds = dynamic_bvh_rebuilds.saturating_add(1);
1403            }
1404            *dynamic_bvh_dirty = false;
1405            *dynamic_topology_dirty = false;
1406        }
1407        self.sync_dynamic_ray_instances();
1408    }
1409
1410    /// Lazily constructs local-space BVH4/BVH8 trees for dynamic meshes and updates `dynamic_instances` from current object transforms with zero BVH rebuilds.
1411    ///
1412    /// # Arguments
1413    ///
1414    /// - `&Self` - Mutable world reference.
1415    pub fn sync_dynamic_ray_instances(&mut self) {
1416        let Self {
1417            mesh_library,
1418            objects,
1419            mesh_local_bvhs,
1420            dynamic_instances,
1421            ..
1422        } = self;
1423        if mesh_local_bvhs.len() < mesh_library.len() {
1424            mesh_local_bvhs.resize_with(mesh_library.len(), || None);
1425        }
1426        dynamic_instances.clear();
1427        for (obj_idx, obj) in objects.iter().enumerate() {
1428            if !obj.get_ray_trace_caster() || !obj.get_is_dynamic() {
1429                continue;
1430            }
1431            let mesh_id: usize = obj.get_mesh_id();
1432            let Some(chain) = mesh_library.get(mesh_id) else {
1433                continue;
1434            };
1435            let Some(mesh) = chain.get_levels().first() else {
1436                continue;
1437            };
1438            if mesh_local_bvhs[mesh_id].is_none() {
1439                let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
1440                let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
1441                let mut local_tris: Vec<BvhTriangle> = Vec::with_capacity(indices.len());
1442                let neutral: PbrMaterial = PbrMaterial::default();
1443                for (tri_idx, tri) in indices.iter().enumerate() {
1444                    let (i0, i1, i2): (usize, usize, usize) =
1445                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
1446                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
1447                        let (tri_mat, mat_slot): (PbrMaterial, u16) =
1448                            mesh.resolve_triangle_material(tri_idx, neutral);
1449                        local_tris.push(BvhTriangle::from_points_with_slot(
1450                            verts[i0].get_position(),
1451                            verts[i1].get_position(),
1452                            verts[i2].get_position(),
1453                            tri_mat,
1454                            mat_slot,
1455                        ));
1456                    }
1457                }
1458                mesh_local_bvhs[mesh_id] = Some(Bvh3D::build(local_tris));
1459            }
1460            let transform_val: Transform3D = obj.get_transform();
1461            dynamic_instances.push(DynamicRayInstance {
1462                obj_idx,
1463                mesh_id,
1464                world_bounds: obj.get_world_bounds(),
1465                inv_model: transform_val.to_inv_mat4(),
1466                normal_basis: transform_val.normal_mat3(),
1467                material: obj.get_material(),
1468            });
1469        }
1470    }
1471
1472    /// Updates only the inverse-model transform, normal basis, and world axis-aligned bounding box of an existing dynamic instance without rebuilding any BVH.
1473    ///
1474    /// # Arguments
1475    ///
1476    /// - `&Self` - Mutable world reference.
1477    /// - `usize` - Scene object index.
1478    /// - `Transform3D` - Interpolated world transform.
1479    /// - `AxisAlignedBox3D` - Interpolated world axis-aligned bounding box.
1480    pub(crate) fn override_dynamic_instance_pose(
1481        &mut self,
1482        obj_idx: usize,
1483        transform: Transform3D,
1484        world_bounds: AxisAlignedBox3D,
1485    ) {
1486        let Self {
1487            dynamic_instances, ..
1488        } = self;
1489        for inst in dynamic_instances.iter_mut() {
1490            if inst.obj_idx == obj_idx {
1491                inst.world_bounds = world_bounds;
1492                inst.inv_model = transform.to_inv_mat4();
1493                inst.normal_basis = transform.normal_mat3();
1494                return;
1495            }
1496        }
1497    }
1498
1499    /// Traces a shadow ray against object-space dynamic instances via inverse interpolated `Mat4` with zero dynamic BVH rebuilds.
1500    ///
1501    /// # Arguments
1502    ///
1503    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1504    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1505    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1506    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1507    /// - `&mut u32` - Per-thread local occluder triangle hint.
1508    ///
1509    /// # Returns
1510    ///
1511    /// - `bool` - `true` if occluded by any dynamic object at its current or interpolated pose.
1512    #[inline(always)]
1513    #[must_use]
1514    pub(crate) fn trace_any_shadow_dynamic_instances(
1515        instances: &[DynamicRayInstance],
1516        local_bvhs: &[Option<Bvh3D>],
1517        ray: (Vec3, Vec3, Vec3),
1518        bounds: (f32, f32),
1519        dyn_cache: &mut u32,
1520    ) -> bool {
1521        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1522        let (t_min, t_max): (f32, f32) = bounds;
1523        for inst in instances.iter() {
1524            if !inst
1525                .world_bounds
1526                .intersect_ray_near(origin, inv_dir, t_min, t_max)
1527                .is_finite()
1528            {
1529                continue;
1530            }
1531            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1532                continue;
1533            };
1534            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1535            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1536            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1537            if local_bvh
1538                .trace_any_shadow_cached(local_orig, local_dir, local_inv, t_min, t_max, dyn_cache)
1539            {
1540                return true;
1541            }
1542        }
1543        false
1544    }
1545
1546    /// Traces a coherent 4-ray shadow packet against static BVH and object-space inverse-interpolated dynamic instances.
1547    ///
1548    /// # Arguments
1549    ///
1550    /// - `&Bvh3D` - Static world BVH4/BVH8.
1551    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1552    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1553    /// - `&RayPacket4` - Coherent 4-ray shadow packet.
1554    /// - `u8` - 4-bit mask of active rays to trace.
1555    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1556    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1557    ///
1558    /// # Returns
1559    ///
1560    /// - `u8` - 4-bit mask of occluded rays.
1561    #[inline(always)]
1562    #[must_use]
1563    pub(crate) fn trace_any_shadow_packet4_with_instances(
1564        static_bvh: &Bvh3D,
1565        instances: &[DynamicRayInstance],
1566        local_bvhs: &[Option<Bvh3D>],
1567        pkt: &RayPacket4,
1568        active_mask: u8,
1569        bounds: (f32, f32),
1570        caches: (&mut u32, &mut u32),
1571    ) -> u8 {
1572        let (t_min, t_max): (f32, f32) = bounds;
1573        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1574        let mut occluded: u8 =
1575            static_bvh.trace_any_shadow_packet4(pkt, active_mask, t_min, t_max, static_cache);
1576        let mut rem: u8 = active_mask & !occluded;
1577        if rem == 0 || instances.is_empty() {
1578            return occluded;
1579        }
1580        for inst in instances.iter() {
1581            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1582                continue;
1583            };
1584            let mut hit_box_mask: u8 = 0;
1585            let mut check: u8 = rem;
1586            while check != 0 {
1587                let red_val: usize = check.trailing_zeros() as usize;
1588                check &= check - 1;
1589                let orig_r: Vec3 = Vec3::new(pkt.ox[red_val], pkt.oy[red_val], pkt.oz[red_val]);
1590                let inv_r: Vec3 = Vec3::new(pkt.ix[red_val], pkt.iy[red_val], pkt.iz[red_val]);
1591                if inst
1592                    .world_bounds
1593                    .intersect_ray_near(orig_r, inv_r, t_min, t_max)
1594                    .is_finite()
1595                {
1596                    hit_box_mask |= 1_u8 << red_val;
1597                }
1598            }
1599            if hit_box_mask == 0 {
1600                continue;
1601            }
1602            let mut local_pkt: RayPacket4 = *pkt;
1603            let mut tr_mask: u8 = hit_box_mask;
1604            while tr_mask != 0 {
1605                let radius_val: usize = tr_mask.trailing_zeros() as usize;
1606                tr_mask &= tr_mask - 1;
1607                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1608                    pkt.ox[radius_val],
1609                    pkt.oy[radius_val],
1610                    pkt.oz[radius_val],
1611                ));
1612                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1613                    pkt.dx[radius_val],
1614                    pkt.dy[radius_val],
1615                    pkt.dz[radius_val],
1616                ));
1617                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1618                local_pkt.ox[radius_val] = lo.get_x();
1619                local_pkt.oy[radius_val] = lo.get_y();
1620                local_pkt.oz[radius_val] = lo.get_z();
1621                local_pkt.dx[radius_val] = ld.get_x();
1622                local_pkt.dy[radius_val] = ld.get_y();
1623                local_pkt.dz[radius_val] = ld.get_z();
1624                local_pkt.ix[radius_val] = li.get_x();
1625                local_pkt.iy[radius_val] = li.get_y();
1626                local_pkt.iz[radius_val] = li.get_z();
1627            }
1628            let dyn_occ: u8 = local_bvh.trace_any_shadow_packet4(
1629                &local_pkt,
1630                hit_box_mask,
1631                t_min,
1632                t_max,
1633                dyn_cache,
1634            );
1635            occluded |= dyn_occ;
1636            rem &= !dyn_occ;
1637            if rem == 0 {
1638                break;
1639            }
1640        }
1641        occluded
1642    }
1643
1644    /// Traces a shadow/occlusion ray across static BVH and object-space inverse-interpolated dynamic instances.
1645    ///
1646    /// # Arguments
1647    ///
1648    /// - `&Bvh3D` - Static world BVH.
1649    /// - `&[DynamicRayInstance]` - Active dynamic raytracing instances.
1650    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1651    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1652    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1653    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder hints.
1654    ///
1655    /// # Returns
1656    ///
1657    /// - `bool` - `true` when occluded by static or dynamic geometry.
1658    #[inline(always)]
1659    #[must_use]
1660    pub(crate) fn trace_any_shadow_with_instances(
1661        static_bvh: &Bvh3D,
1662        instances: &[DynamicRayInstance],
1663        local_bvhs: &[Option<Bvh3D>],
1664        ray: (Vec3, Vec3, Vec3),
1665        bounds: (f32, f32),
1666        caches: (&mut u32, &mut u32),
1667    ) -> bool {
1668        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1669        let (t_min, t_max): (f32, f32) = bounds;
1670        let (static_cache, dyn_cache): (&mut u32, &mut u32) = caches;
1671        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
1672            return true;
1673        }
1674        if !instances.is_empty() {
1675            return Self::trace_any_shadow_dynamic_instances(
1676                instances, local_bvhs, ray, bounds, dyn_cache,
1677            );
1678        }
1679        false
1680    }
1681
1682    /// Traces a reflection/GI ray across static BVH and object-space inverse-interpolated dynamic instances, returning `(distance, world_normal, material)`.
1683    ///
1684    /// # Arguments
1685    ///
1686    /// - `&Bvh3D` - Static world BVH.
1687    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1688    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1689    /// - `(Vec3, Vec3, Vec3)` - World-space `(origin, dir, inv_dir)` ray triple.
1690    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1691    ///
1692    /// # Returns
1693    ///
1694    /// - `Option<(f32, Vec3, PbrMaterial)>` - Closest hit distance, world-space unit normal, and PBR material.
1695    #[inline(always)]
1696    #[must_use]
1697    pub(crate) fn trace_closest_with_instances(
1698        static_bvh: &Bvh3D,
1699        instances: &[DynamicRayInstance],
1700        local_bvhs: &[Option<Bvh3D>],
1701        ray: (Vec3, Vec3, Vec3),
1702        bounds: (f32, f32),
1703    ) -> Option<(f32, Vec3, PbrMaterial)> {
1704        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
1705        let (t_min, t_max): (f32, f32) = bounds;
1706        let mut best_t: f32 = t_max;
1707        let mut best_hit: Option<(f32, Vec3, PbrMaterial)> = static_bvh
1708            .trace_closest_raw(origin, dir, inv_dir, t_min, t_max)
1709            .map(|(node_style, si): (f32, usize)| {
1710                let tri: &BvhTriangle = &static_bvh.get_triangles()[si];
1711                best_t = node_style;
1712                (node_style, tri.get_normal(), tri.get_material())
1713            });
1714        for inst in instances.iter() {
1715            if !inst
1716                .world_bounds
1717                .intersect_ray_near(origin, inv_dir, t_min, best_t)
1718                .is_finite()
1719            {
1720                continue;
1721            }
1722            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1723                continue;
1724            };
1725            let local_orig: Vec3 = inst.inv_model.mul_point3(origin);
1726            let local_dir: Vec3 = inst.inv_model.mul_vec3(dir);
1727            let local_inv: Vec3 = Ray3D::safe_inv_vec(local_dir);
1728            if let Some((dt, di)) =
1729                local_bvh.trace_closest_raw(local_orig, local_dir, local_inv, t_min, best_t)
1730            {
1731                best_t = dt;
1732                let hit_tri: &BvhTriangle = &local_bvh.get_triangles()[di];
1733                let local_n: Vec3 = hit_tri.get_normal();
1734                let world_n: Vec3 = Mat4::transform_normal_with_basis(local_n, inst.normal_basis);
1735                let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
1736                    inst.material
1737                } else {
1738                    hit_tri.get_material()
1739                };
1740                best_hit = Some((dt, world_n, hit_mat));
1741            }
1742        }
1743        best_hit
1744    }
1745
1746    /// Traces a coherent 4-ray closest-hit packet across static BVH and object-space inverse-interpolated dynamic instances.
1747    ///
1748    /// # Arguments
1749    ///
1750    /// - `&Bvh3D` - Static world BVH4/BVH8.
1751    /// - `&[DynamicRayInstance]` - Active object-space dynamic instances.
1752    /// - `&[Option<Bvh3D>]` - Local-space BVH cache indexed by `mesh_id`.
1753    /// - `&RayPacket4` - Coherent 4-ray reflection or GI packet.
1754    /// - `u8` - 4-bit mask of active rays.
1755    /// - `(f32, f32)` - Distance bounds `(t_min, t_max)`.
1756    ///
1757    /// # Returns
1758    ///
1759    /// - `[Option<(f32, Vec3, PbrMaterial)>; 4]` - Closest hit distance, world normal, and material per lane.
1760    #[inline(always)]
1761    #[must_use]
1762    pub(crate) fn trace_closest_packet4_with_instances(
1763        static_bvh: &Bvh3D,
1764        instances: &[DynamicRayInstance],
1765        local_bvhs: &[Option<Bvh3D>],
1766        pkt: &RayPacket4,
1767        active_mask: u8,
1768        bounds: (f32, f32),
1769    ) -> [Option<(f32, Vec3, PbrMaterial)>; 4] {
1770        let (t_min, t_max): (f32, f32) = bounds;
1771        let mut best_t: [f32; 4] = [t_max; 4];
1772        let mut best_static_idx: [usize; 4] = [usize::MAX; 4];
1773        static_bvh.trace_closest_packet4(
1774            pkt,
1775            active_mask,
1776            t_min,
1777            &mut best_t,
1778            &mut best_static_idx,
1779        );
1780        let static_tris: &[BvhTriangle] = static_bvh.get_triangles().as_slice();
1781        let mut out: [Option<(f32, Vec3, PbrMaterial)>; 4] = [None; 4];
1782        let mut matrix_elems: u8 = active_mask;
1783        while matrix_elems != 0 {
1784            let red_val: usize = matrix_elems.trailing_zeros() as usize;
1785            matrix_elems &= matrix_elems - 1;
1786            let sidx: usize = best_static_idx[red_val];
1787            if sidx != usize::MAX {
1788                let tri: &BvhTriangle = &static_tris[sidx];
1789                out[red_val] = Some((best_t[red_val], tri.get_normal(), tri.get_material()));
1790            }
1791        }
1792        for inst in instances.iter() {
1793            let Some(Some(local_bvh)) = local_bvhs.get(inst.mesh_id) else {
1794                continue;
1795            };
1796            let mut hit_box_mask: u8 = 0;
1797            let mut check: u8 = active_mask;
1798            while check != 0 {
1799                let radius_val: usize = check.trailing_zeros() as usize;
1800                check &= check - 1;
1801                if inst
1802                    .world_bounds
1803                    .intersect_ray_near(
1804                        Vec3::new(pkt.ox[radius_val], pkt.oy[radius_val], pkt.oz[radius_val]),
1805                        Vec3::new(pkt.ix[radius_val], pkt.iy[radius_val], pkt.iz[radius_val]),
1806                        t_min,
1807                        best_t[radius_val],
1808                    )
1809                    .is_finite()
1810                {
1811                    hit_box_mask |= 1_u8 << radius_val;
1812                }
1813            }
1814            if hit_box_mask == 0 {
1815                continue;
1816            }
1817            let mut local_pkt: RayPacket4 = *pkt;
1818            let mut tr_mask: u8 = hit_box_mask;
1819            while tr_mask != 0 {
1820                let rect_val: usize = tr_mask.trailing_zeros() as usize;
1821                tr_mask &= tr_mask - 1;
1822                let lo: Vec3 = inst.inv_model.mul_point3(Vec3::new(
1823                    pkt.ox[rect_val],
1824                    pkt.oy[rect_val],
1825                    pkt.oz[rect_val],
1826                ));
1827                let ld: Vec3 = inst.inv_model.mul_vec3(Vec3::new(
1828                    pkt.dx[rect_val],
1829                    pkt.dy[rect_val],
1830                    pkt.dz[rect_val],
1831                ));
1832                let li: Vec3 = Ray3D::safe_inv_vec(ld);
1833                local_pkt.ox[rect_val] = lo.get_x();
1834                local_pkt.oy[rect_val] = lo.get_y();
1835                local_pkt.oz[rect_val] = lo.get_z();
1836                local_pkt.dx[rect_val] = ld.get_x();
1837                local_pkt.dy[rect_val] = ld.get_y();
1838                local_pkt.dz[rect_val] = ld.get_z();
1839                local_pkt.ix[rect_val] = li.get_x();
1840                local_pkt.iy[rect_val] = li.get_y();
1841                local_pkt.iz[rect_val] = li.get_z();
1842            }
1843            let mut dyn_idx: [usize; 4] = [usize::MAX; 4];
1844            local_bvh.trace_closest_packet4(
1845                &local_pkt,
1846                hit_box_mask,
1847                t_min,
1848                &mut best_t,
1849                &mut dyn_idx,
1850            );
1851            let local_tris: &[BvhTriangle] = local_bvh.get_triangles().as_slice();
1852            let mut upd: u8 = hit_box_mask;
1853            while upd != 0 {
1854                let row_val: usize = upd.trailing_zeros() as usize;
1855                upd &= upd - 1;
1856                let di: usize = dyn_idx[row_val];
1857                if di != usize::MAX {
1858                    let hit_tri: &BvhTriangle = &local_tris[di];
1859                    let wn: Vec3 =
1860                        Mat4::transform_normal_with_basis(hit_tri.get_normal(), inst.normal_basis);
1861                    let hit_mat: PbrMaterial = if hit_tri.get_material_slot() == 0 {
1862                        inst.material
1863                    } else {
1864                        hit_tri.get_material()
1865                    };
1866                    out[row_val] = Some((best_t[row_val], wn, hit_mat));
1867                }
1868            }
1869        }
1870        out
1871    }
1872
1873    /// Traces a shadow ray using static BVH plus object-space inverse-interpolated dynamic instances.
1874    ///
1875    /// # Arguments
1876    ///
1877    /// - `&Self` - World reference.
1878    /// - `&Ray3D` - World-space shadow ray.
1879    /// - `f32` - Minimum hit distance.
1880    /// - `f32` - Maximum hit distance.
1881    ///
1882    /// # Returns
1883    ///
1884    /// - `bool` - `true` when occluded by static or dynamic geometry at its current/interpolated pose.
1885    #[must_use]
1886    pub fn trace_any_shadow_object_space(&self, ray: &Ray3D, t_min: f32, t_max: f32) -> bool {
1887        let Self {
1888            bvh,
1889            dynamic_instances,
1890            mesh_local_bvhs,
1891            ..
1892        } = self;
1893        let mut scale_factor: u32 = u32::MAX;
1894        let mut dc: u32 = u32::MAX;
1895        Self::trace_any_shadow_with_instances(
1896            bvh,
1897            dynamic_instances.as_slice(),
1898            mesh_local_bvhs.as_slice(),
1899            (
1900                ray.get_origin(),
1901                ray.get_direction(),
1902                ray.get_inv_direction(),
1903            ),
1904            (t_min, t_max),
1905            (&mut scale_factor, &mut dc),
1906        )
1907    }
1908
1909    /// Traces a coherent 4-ray closest-hit packet against both the static BVH4 and object-space inverse-interpolated dynamic instances.
1910    ///
1911    /// # Arguments
1912    ///
1913    /// - `&Self` - World reference.
1914    /// - `&RayPacket4` - Coherent 4-ray query packet.
1915    /// - `u8` - 4-bit mask of active rays (`0..=15`).
1916    /// - `f32` - Minimum hit distance.
1917    /// - `f32` - Maximum hit distance.
1918    ///
1919    /// # Returns
1920    ///
1921    /// - `[Option<RayHit3D>; 4]` - Closest hit surface with world normal and material per active lane.
1922    #[must_use]
1923    pub fn trace_closest_packet4(
1924        &self,
1925        pkt: &RayPacket4,
1926        active_mask: u8,
1927        t_min: f32,
1928        t_max: f32,
1929    ) -> [Option<RayHit3D>; 4] {
1930        let Self {
1931            bvh,
1932            dynamic_instances,
1933            mesh_local_bvhs,
1934            ..
1935        } = self;
1936        let raw: [Option<(f32, Vec3, PbrMaterial)>; 4] = Self::trace_closest_packet4_with_instances(
1937            bvh,
1938            dynamic_instances.as_slice(),
1939            mesh_local_bvhs.as_slice(),
1940            pkt,
1941            active_mask,
1942            (t_min, t_max),
1943        );
1944        let mut out: [Option<RayHit3D>; 4] = [None; 4];
1945        for lane in 0..4 {
1946            if let Some((blend_factor, normal, material)) = raw[lane] {
1947                let point: Vec3 = Vec3::new(
1948                    pkt.ox[lane] + pkt.dx[lane] * blend_factor,
1949                    pkt.oy[lane] + pkt.dy[lane] * blend_factor,
1950                    pkt.oz[lane] + pkt.dz[lane] * blend_factor,
1951                );
1952                out[lane] = Some(RayHit3D {
1953                    distance: blend_factor,
1954                    point,
1955                    normal,
1956                    material,
1957                });
1958            }
1959        }
1960        out
1961    }
1962
1963    /// Traces a closest-hit ray using static BVH plus object-space inverse-interpolated dynamic instances.
1964    ///
1965    /// # Arguments
1966    ///
1967    /// - `&Self` - World reference.
1968    /// - `&Ray3D` - World-space query ray.
1969    /// - `f32` - Minimum hit distance.
1970    /// - `f32` - Maximum hit distance.
1971    ///
1972    /// # Returns
1973    ///
1974    /// - `Option<RayHit3D>` - Closest hit surface with world-space normal and material.
1975    #[must_use]
1976    pub fn trace_closest_object_space(
1977        &self,
1978        ray: &Ray3D,
1979        t_min: f32,
1980        t_max: f32,
1981    ) -> Option<RayHit3D> {
1982        let Self {
1983            bvh,
1984            dynamic_instances,
1985            mesh_local_bvhs,
1986            ..
1987        } = self;
1988        let (blend_factor, normal, material): (f32, Vec3, PbrMaterial) =
1989            Self::trace_closest_with_instances(
1990                bvh,
1991                dynamic_instances.as_slice(),
1992                mesh_local_bvhs.as_slice(),
1993                (
1994                    ray.get_origin(),
1995                    ray.get_direction(),
1996                    ray.get_inv_direction(),
1997                ),
1998                (t_min, t_max),
1999            )?;
2000        Some(RayHit3D {
2001            distance: blend_factor,
2002            point: ray
2003                .get_origin()
2004                .add(ray.get_direction().scale(blend_factor)),
2005            normal,
2006            material,
2007        })
2008    }
2009
2010    /// Returns the combined node count across both static and dynamic BVH acceleration trees.
2011    ///
2012    /// # Arguments
2013    ///
2014    /// - `&Self` - World reference.
2015    ///
2016    /// # Returns
2017    ///
2018    /// - `usize` - Total active BVH nodes.
2019    #[must_use]
2020    pub fn total_bvh_nodes(&self) -> usize {
2021        self.get_bvh()
2022            .get_nodes()
2023            .len()
2024            .saturating_add(self.get_dynamic_bvh().get_nodes().len())
2025    }
2026
2027    /// Traces a shadow/occlusion ray across both static and dynamic BVHs using 1-triangle occluder caches.
2028    ///
2029    /// # Arguments
2030    ///
2031    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
2032    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
2033    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
2034    /// - `(&mut u32, &mut u32)` - `(static_cache, dynamic_cache)` occluder triangle hints.
2035    ///
2036    /// # Returns
2037    ///
2038    /// - `bool` - `true` if occluded by either static or dynamic geometry.
2039    #[must_use]
2040    pub fn trace_any_shadow_split(
2041        bvhs: (&Bvh3D, &Bvh3D),
2042        ray: (Vec3, Vec3, Vec3),
2043        bounds: (f32, f32),
2044        caches: (&mut u32, &mut u32),
2045    ) -> bool {
2046        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2047        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2048        let (t_min, t_max): (f32, f32) = bounds;
2049        let (static_cache, dynamic_cache): (&mut u32, &mut u32) = caches;
2050        if static_bvh.trace_any_shadow_cached(origin, dir, inv_dir, t_min, t_max, static_cache) {
2051            return true;
2052        }
2053        if !dynamic_bvh.is_empty() {
2054            return dynamic_bvh.trace_any_shadow_cached(
2055                origin,
2056                dir,
2057                inv_dir,
2058                t_min,
2059                t_max,
2060                dynamic_cache,
2061            );
2062        }
2063        false
2064    }
2065
2066    /// Traces a reflection/GI ray across both static and dynamic BVHs and returns `(distance, is_dynamic, tri_index)`.
2067    ///
2068    /// # Arguments
2069    ///
2070    /// - `(&Bvh3D, &Bvh3D)` - `(static_bvh, dynamic_bvh)` pair.
2071    /// - `(Vec3, Vec3, Vec3)` - `(origin, dir, inv_dir)` ray triple.
2072    /// - `(f32, f32)` - `(t_min, t_max)` distance bounds.
2073    ///
2074    /// # Returns
2075    ///
2076    /// - `Option<(f32, bool, usize)>` - Closest `(t, hit_in_dynamic_bvh, triangle_index)`.
2077    #[must_use]
2078    pub fn trace_closest_split(
2079        bvhs: (&Bvh3D, &Bvh3D),
2080        ray: (Vec3, Vec3, Vec3),
2081        bounds: (f32, f32),
2082    ) -> Option<(f32, bool, usize)> {
2083        let (static_bvh, dynamic_bvh): (&Bvh3D, &Bvh3D) = bvhs;
2084        let (origin, dir, inv_dir): (Vec3, Vec3, Vec3) = ray;
2085        let (t_min, t_max): (f32, f32) = bounds;
2086        let static_hit: Option<(f32, usize)> =
2087            static_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, t_max);
2088        let dyn_limit: f32 =
2089            static_hit.map_or(t_max, |(blend_factor, _): (f32, usize)| blend_factor);
2090        let dynamic_hit: Option<(f32, usize)> = if !dynamic_bvh.is_empty() {
2091            dynamic_bvh.trace_closest_raw(origin, dir, inv_dir, t_min, dyn_limit)
2092        } else {
2093            None
2094        };
2095        match (static_hit, dynamic_hit) {
2096            (_, Some((dt, di))) => Some((dt, true, di)),
2097            (Some((node_style, si)), None) => Some((node_style, false, si)),
2098            (None, None) => None,
2099        }
2100    }
2101
2102    /// Returns the optional player vehicle index.
2103    ///
2104    /// # Arguments
2105    ///
2106    /// - `&Self` - World reference.
2107    ///
2108    /// # Returns
2109    ///
2110    /// - `Option<usize>` - Vehicle index in `objects`.
2111    #[must_use]
2112    pub fn vehicle_index(&self) -> Option<usize> {
2113        let Self {
2114            player_vehicle_index,
2115            ..
2116        } = self;
2117        *player_vehicle_index
2118    }
2119
2120    /// Builds a GTA-inspired open-world neon downtown city with reflective wet asphalt, glass towers, and a drivable sports car.
2121    ///
2122    /// # Returns
2123    ///
2124    /// - `Self` - Populated open-world 3D city ready for real-time PBR + Ray Tracing.
2125    #[must_use]
2126    pub fn create_open_world_city() -> Self {
2127        let mut world: Self = Self::default();
2128        let island_w: f32 = CITY_ISLAND_HALF_X * 2.0;
2129        let island_d: f32 = CITY_ISLAND_Z_MAX - CITY_ISLAND_Z_MIN;
2130        let island_z_center: f32 = (CITY_ISLAND_Z_MIN + CITY_ISLAND_Z_MAX) * 0.5;
2131        let asphalt_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0E131C), 0.08, 0.24, 0.62)
2132            .with_surface_detail(SurfaceDetailMode::RoadSurface);
2133        let road_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::ground_plane(
2134            "wet_asphalt_boulevard",
2135            island_w,
2136            island_d,
2137            24,
2138            asphalt_mat,
2139        )));
2140        let _: usize = world.spawn_object(
2141            "city_ground",
2142            road_mesh,
2143            Transform3D::new(Vec3::new(0.0, 0.0, island_z_center), 0.0, Vec3::splat(1.0)),
2144            asphalt_mat,
2145            false,
2146        );
2147        let ocean_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x063846), 0.05, 0.06, 0.86)
2148            .with_surface_detail(SurfaceDetailMode::OceanWater);
2149        let ocean_mesh: usize =
2150            world.register_mesh(MeshLodChain::from_mesh(Mesh3D::coastal_ocean_ring(
2151                CITY_OCEAN_MESH_NAME,
2152                CITY_OCEAN_SPAN_M,
2153                CITY_ISLAND_HALF_X,
2154                island_d * 0.5,
2155                24,
2156                ocean_mat,
2157            )));
2158        let _: usize = world.spawn_object(
2159            CITY_OCEAN_MESH_NAME,
2160            ocean_mesh,
2161            Transform3D::new(
2162                Vec3::new(0.0, CITY_OCEAN_SURFACE_Y, island_z_center),
2163                0.0,
2164                Vec3::splat(1.0),
2165            ),
2166            ocean_mat,
2167            false,
2168        );
2169        let stud_mat: PbrMaterial = PbrMaterial::neon(Color::hex(0xFBBF24), 0.90);
2170        let stud_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2171            "lane_stripe",
2172            0.10,
2173            0.018,
2174            0.16,
2175            true,
2176            stud_mat,
2177        )));
2178        for iz in -7..=0 {
2179            let _: usize = world.spawn_object(
2180                &format!("stripe_{iz}"),
2181                stud_mesh,
2182                Transform3D::new(
2183                    Vec3::new(0.0, 0.008, (iz as f32) * 12.0),
2184                    0.0,
2185                    Vec3::splat(1.0),
2186                ),
2187                stud_mat,
2188                false,
2189            );
2190        }
2191        let tower_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2192            "city_skyscraper",
2193            1.0,
2194            1.0,
2195            1.0,
2196            true,
2197            PbrMaterial::default(),
2198        )));
2199        let neon_unit: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2200            "neon_sign",
2201            1.0,
2202            1.0,
2203            1.0,
2204            true,
2205            PbrMaterial::neon(Color::hex(0x38BDF8), 1.8),
2206        )));
2207        let tower_palettes: [PbrMaterial; 4] = [
2208            PbrMaterial::pbr(Color::hex(0x1E293B), 0.72, 0.16, 0.65)
2209                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2210            PbrMaterial::pbr(Color::hex(0x334155), 0.55, 0.24, 0.45)
2211                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2212            PbrMaterial::pbr(Color::hex(0x0F172A), 0.85, 0.10, 0.78)
2213                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2214            PbrMaterial::pbr(Color::hex(0x475569), 0.40, 0.35, 0.35)
2215                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2216        ];
2217        let neon_colors: [Color; 4] = [
2218            Color::hex(0x38BDF8),
2219            Color::hex(0xF43F5E),
2220            Color::hex(0xA855F7),
2221            Color::hex(0x34D399),
2222        ];
2223        let mut idx_counter: usize = 0;
2224        for side in [-1.0_f32, 1.0_f32] {
2225            for row in -4..=4 {
2226                let pos_z: f32 = (row as f32) * 20.0 - 12.0;
2227                let pos_x: f32 = side * (19.0 + ((idx_counter % 3) as f32) * 3.0);
2228                let height_val: f32 = 16.0 + ((idx_counter * 7) % 5) as f32 * 8.5;
2229                let width_val: f32 = 9.0 + ((idx_counter % 2) as f32) * 3.0;
2230                let mat: PbrMaterial = tower_palettes[idx_counter % tower_palettes.len()];
2231                let _: usize = world.spawn_object(
2232                    &format!("tower_{idx_counter}"),
2233                    tower_unit,
2234                    Transform3D::new(
2235                        Vec3::new(pos_x, 0.0, pos_z),
2236                        0.0,
2237                        Vec3::new(width_val, height_val, 11.0),
2238                    ),
2239                    mat,
2240                    true,
2241                );
2242                let neon_mat: PbrMaterial =
2243                    PbrMaterial::neon(neon_colors[idx_counter % neon_colors.len()], 1.9);
2244                let _: usize = world.spawn_object(
2245                    &format!("crown_{idx_counter}"),
2246                    neon_unit,
2247                    Transform3D::new(
2248                        Vec3::new(
2249                            pos_x - side * (width_val * 0.5 + 0.28),
2250                            height_val * 0.72,
2251                            pos_z,
2252                        ),
2253                        0.0,
2254                        Vec3::new(0.36, 1.4, 8.2),
2255                    ),
2256                    neon_mat,
2257                    true,
2258                );
2259                if idx_counter.is_multiple_of(2) {
2260                    let awning_mat: PbrMaterial =
2261                        PbrMaterial::pbr(Color::hex(0x111827), 0.72, 0.22, 0.45);
2262                    let _: usize = world.spawn_object(
2263                        &format!("awning_{idx_counter}"),
2264                        tower_unit,
2265                        Transform3D::new(
2266                            Vec3::new(pos_x - side * (width_val * 0.5 + 0.68), 3.45, pos_z),
2267                            0.0,
2268                            Vec3::new(1.35, 0.28, 9.6),
2269                        ),
2270                        awning_mat,
2271                        true,
2272                    );
2273                    let sign_mat: PbrMaterial =
2274                        PbrMaterial::neon(neon_colors[(idx_counter + 1) % neon_colors.len()], 2.4);
2275                    let _: usize = world.spawn_object(
2276                        &format!("blade_sign_{idx_counter}"),
2277                        neon_unit,
2278                        Transform3D::new(
2279                            Vec3::new(pos_x - side * (width_val * 0.5 + 0.72), 7.2, pos_z + 2.4),
2280                            0.0,
2281                            Vec3::new(0.24, 5.2, 1.35),
2282                        ),
2283                        sign_mat,
2284                        true,
2285                    );
2286                }
2287                if height_val >= 28.0 {
2288                    let spire_mat: PbrMaterial =
2289                        PbrMaterial::pbr(Color::hex(0x1E293B), 0.85, 0.14, 0.75);
2290                    let _: usize = world.spawn_object(
2291                        &format!("penthouse_{idx_counter}"),
2292                        tower_unit,
2293                        Transform3D::new(
2294                            Vec3::new(pos_x, height_val, pos_z),
2295                            0.0,
2296                            Vec3::new(width_val * 0.52, 4.2, 5.8),
2297                        ),
2298                        spire_mat,
2299                        true,
2300                    );
2301                    let _: usize = world.spawn_object(
2302                        &format!("spire_{idx_counter}"),
2303                        neon_unit,
2304                        Transform3D::new(
2305                            Vec3::new(pos_x, height_val + 4.2, pos_z),
2306                            0.0,
2307                            Vec3::new(0.45, 7.5, 0.45),
2308                        ),
2309                        neon_mat,
2310                        true,
2311                    );
2312                }
2313                idx_counter += 1;
2314            }
2315        }
2316        let palm_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::palm_tree(
2317            CITY_PALM_MESH_NAME,
2318        )));
2319        let palm_bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
2320        let palm_z_positions: [f32; 6] = [1.0, -15.0, -31.0, -47.0, -63.0, -79.0];
2321        for (palm_row, &palm_z) in palm_z_positions.iter().enumerate() {
2322            for side_idx in 0..2usize {
2323                let side_sign: f32 = if side_idx == 0 { -1.0 } else { 1.0 };
2324                let yaw_palm: f32 = (palm_row as f32) * 0.95
2325                    + (side_idx as f32) * 2.1
2326                    + if side_idx == 0 { 0.35 } else { -0.35 };
2327                let scale_palm: f32 = 0.94 + ((palm_row + side_idx) % 3) as f32 * 0.08;
2328                let _: usize = world.spawn_object(
2329                    &format!("palm_{palm_row}_{side_idx}"),
2330                    palm_mesh,
2331                    Transform3D::new(
2332                        Vec3::new(side_sign * 11.6, 0.0, palm_z + (side_idx as f32) * 2.5),
2333                        yaw_palm,
2334                        Vec3::splat(scale_palm),
2335                    ),
2336                    palm_bark_mat,
2337                    true,
2338                );
2339            }
2340        }
2341        let skyline_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0B1120), 0.65, 0.22, 0.48)
2342            .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade);
2343        let skyline_specs: [(f32, f32, f32, f32); 6] = [
2344            (-40.0, -96.0, 12.0, 52.0),
2345            (-40.0, -72.0, 12.0, 62.0),
2346            (40.0, -72.0, 12.0, 60.0),
2347            (40.0, -96.0, 12.0, 54.0),
2348            (-40.0, -46.0, 12.0, 48.0),
2349            (40.0, -46.0, 12.0, 50.0),
2350        ];
2351        for (sky_idx, &(sx, sz, sw, sh)) in skyline_specs.iter().enumerate() {
2352            let _: usize = world.spawn_object(
2353                &format!("{CITY_SKYLINE_MESH_NAME}_{sky_idx}"),
2354                tower_unit,
2355                Transform3D::new(Vec3::new(sx, 0.0, sz), 0.0, Vec3::new(sw, sh, 12.0)),
2356                skyline_mat,
2357                true,
2358            );
2359        }
2360        let seawall_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x334155), 0.14, 0.62, 0.18);
2361        let seawall_specs: [(f32, f32, f32, f32); 4] = [
2362            (0.0, CITY_ISLAND_Z_MIN + 0.75, island_w, 1.5),
2363            (0.0, CITY_ISLAND_Z_MAX - 0.75, island_w, 1.5),
2364            (-CITY_ISLAND_HALF_X + 0.75, island_z_center, 1.5, island_d),
2365            (CITY_ISLAND_HALF_X - 0.75, island_z_center, 1.5, island_d),
2366        ];
2367        for (wall_idx, &(wx, wz, ww, wd)) in seawall_specs.iter().enumerate() {
2368            let _: usize = world.spawn_object(
2369                &format!("{CITY_SEAWALL_MESH_NAME}_{wall_idx}"),
2370                tower_unit,
2371                Transform3D::new(Vec3::new(wx, -1.25, wz), 0.0, Vec3::new(ww, 1.51, wd)),
2372                seawall_mat,
2373                true,
2374            );
2375        }
2376        let arch_frame_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x0F172A), 0.82, 0.18, 0.60);
2377        for (arch_idx, &arch_z) in [-22.0_f32, -58.0_f32, -92.0_f32].iter().enumerate() {
2378            let arch_neon: PbrMaterial =
2379                PbrMaterial::neon(neon_colors[arch_idx % neon_colors.len()], 2.1);
2380            let _: usize = world.spawn_object(
2381                &format!("arch_beam_{arch_idx}"),
2382                tower_unit,
2383                Transform3D::new(
2384                    Vec3::new(0.0, 13.4, arch_z),
2385                    0.0,
2386                    Vec3::new(22.4, 0.58, 0.72),
2387                ),
2388                arch_frame_mat,
2389                true,
2390            );
2391            let _: usize = world.spawn_object(
2392                &format!("arch_glow_{arch_idx}"),
2393                neon_unit,
2394                Transform3D::new(
2395                    Vec3::new(0.0, 13.08, arch_z),
2396                    0.0,
2397                    Vec3::new(20.6, 0.24, 0.34),
2398                ),
2399                arch_neon,
2400                true,
2401            );
2402            for side in [-1.0_f32, 1.0_f32] {
2403                let _: usize = world.spawn_object(
2404                    &format!("arch_pillar_{arch_idx}_{}", if side < 0.0 { 0 } else { 1 }),
2405                    tower_unit,
2406                    Transform3D::new(
2407                        Vec3::new(side * 10.9, 0.0, arch_z),
2408                        0.0,
2409                        Vec3::new(0.58, 13.4, 0.68),
2410                    ),
2411                    arch_frame_mat,
2412                    true,
2413                );
2414            }
2415        }
2416        let car_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0xDC143C), 0.86, 0.11, 0.76);
2417        let car_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::sports_car(
2418            "hero_gt", car_mat,
2419        )));
2420        let car_idx: usize = world.spawn_object(
2421            "player_gt_car",
2422            car_mesh,
2423            Transform3D::new(Vec3::new(0.0, 0.0, 6.0), 0.0, Vec3::splat(1.1)),
2424            car_mat,
2425            true,
2426        );
2427        let _: bool = world.set_object_dynamic(car_idx, true);
2428        world.set_player_vehicle_index(Some(car_idx));
2429        let _: usize = world.add_point_light(PointLight3D::new(
2430            Vec3::new(0.0, 0.95, 9.2),
2431            Color::hex(0xFF1744),
2432            1.85,
2433            8.5,
2434        ));
2435        let traffic_specs: [(f32, f32, f32, f32, Color); 4] = [
2436            (-5.6, -16.0, PI, 11.5, Color::hex(0x38BDF8)),
2437            (-5.6, -56.0, PI, 10.0, Color::hex(0xA855F7)),
2438            (5.6, -24.0, 0.0, -13.0, Color::hex(0x34D399)),
2439            (5.6, -68.0, 0.0, -11.0, Color::hex(0xF59E0B)),
2440        ];
2441        for (t_idx, &(tx, tz, tyaw, tvel, tcol)) in traffic_specs.iter().enumerate() {
2442            let tmat: PbrMaterial = PbrMaterial::pbr(tcol, 0.86, 0.14, 0.74);
2443            let obj_id: usize = world.spawn_object(
2444                &format!("ai_traffic_{t_idx}"),
2445                car_mesh,
2446                Transform3D::new(Vec3::new(tx, 0.0, tz), tyaw, Vec3::splat(1.04)),
2447                tmat,
2448                true,
2449            );
2450            let _: bool = world.set_object_dynamic(obj_id, true);
2451            let Self {
2452                traffic_vehicles, ..
2453            } = &mut world;
2454            traffic_vehicles.push((obj_id, tvel, -94.0, 68.0));
2455        }
2456        let lamp_palette: [Color; 4] = [
2457            Color::hex(0x38BDF8),
2458            Color::hex(0xF43F5E),
2459            Color::hex(0xA855F7),
2460            Color::hex(0x34D399),
2461        ];
2462        for lamp_idx in 0..8usize {
2463            let side: f32 = if lamp_idx % 2 == 0 { -1.0 } else { 1.0 };
2464            let z_pos: f32 = -42.0 + ((lamp_idx / 2) as f32) * 24.0;
2465            let lamp_color: Color = lamp_palette[lamp_idx % lamp_palette.len()];
2466            let _: usize = world.spawn_object(
2467                &format!("lamp_pole_{lamp_idx}"),
2468                tower_unit,
2469                Transform3D::new(
2470                    Vec3::new(side * 10.35, 0.0, z_pos),
2471                    0.0,
2472                    Vec3::new(0.20, 6.2, 0.20),
2473                ),
2474                arch_frame_mat,
2475                true,
2476            );
2477            let _: usize = world.spawn_object(
2478                &format!("lamp_head_{lamp_idx}"),
2479                neon_unit,
2480                Transform3D::new(
2481                    Vec3::new(side * 9.85, 6.2, z_pos),
2482                    0.0,
2483                    Vec3::new(1.1, 0.18, 0.28),
2484                ),
2485                PbrMaterial::neon(lamp_color, 2.2),
2486                true,
2487            );
2488            let _: usize = world.add_point_light(PointLight3D::new(
2489                Vec3::new(side * 9.5, 6.2, z_pos),
2490                lamp_color,
2491                2.35,
2492                16.5,
2493            ));
2494        }
2495        let _: usize = world.add_spot_light(SpotLight3D::new(
2496            Vec3::new(-0.85, 0.95, 3.8),
2497            Vec3::new(0.0, -0.14, -1.0),
2498            Color::hex(0xFEF3C7),
2499            2.8,
2500            24.0,
2501            (14.0, 26.0),
2502        ));
2503        let _: usize = world.add_spot_light(SpotLight3D::new(
2504            Vec3::new(0.85, 0.95, 3.8),
2505            Vec3::new(0.0, -0.14, -1.0),
2506            Color::hex(0xFEF3C7),
2507            2.8,
2508            24.0,
2509            (14.0, 26.0),
2510        ));
2511        world.set_camera(Camera3D {
2512            position: Vec3::new(0.0, 4.25, 15.8),
2513            yaw: -FRAC_PI_2,
2514            pitch: -0.068,
2515            fov_deg: 60.0,
2516            near: 0.3,
2517            far: 480.0,
2518        });
2519        world.ensure_bvh();
2520        world
2521    }
2522
2523    /// Returns the number of autonomous cruising traffic vehicles registered in this world.
2524    ///
2525    /// # Returns
2526    ///
2527    /// - `usize` - Active cruising traffic vehicle count.
2528    #[must_use]
2529    pub fn traffic_vehicle_count(&self) -> usize {
2530        let Self {
2531            traffic_vehicles, ..
2532        } = self;
2533        traffic_vehicles.len()
2534    }
2535
2536    /// Applies an atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`), updating sun lighting and ambient Niagara rain streaks.
2537    ///
2538    /// # Arguments
2539    ///
2540    /// - `u8` - Atmosphere preset index (`0..=3`).
2541    ///
2542    /// # Returns
2543    ///
2544    /// - `f32` - Corresponding time-of-day hour in `[0.0, 24.0]`.
2545    pub fn apply_atmosphere_preset(&mut self, preset: u8) -> f32 {
2546        let clamped: u8 = preset.min(3);
2547        let hour: f32 = match clamped {
2548            1 => ATMOSPHERE_HOUR_RAINY_NIGHT,
2549            2 => ATMOSPHERE_HOUR_NOON,
2550            3 => ATMOSPHERE_HOUR_MIDNIGHT,
2551            _ => ATMOSPHERE_HOUR_SUNSET,
2552        };
2553        self.set_atmosphere_preset(clamped);
2554        let sun_light: DirectionalLight3D = match clamped {
2555            1 => DirectionalLight3D {
2556                direction: Vec3::new(-0.32, 0.48, -0.82).normalize(),
2557                color: Vec3::new(0.56, 0.78, 1.24),
2558                sky_zenith: Vec3::new(0.015, 0.038, 0.105),
2559                sky_horizon: Vec3::new(0.078, 0.155, 0.275),
2560                time_of_day: hour,
2561            },
2562            3 => DirectionalLight3D {
2563                direction: Vec3::new(-0.42, 0.62, -0.66).normalize(),
2564                color: Vec3::new(0.36, 0.34, 0.88),
2565                sky_zenith: Vec3::new(0.007, 0.005, 0.024),
2566                sky_horizon: Vec3::new(0.135, 0.036, 0.215),
2567                time_of_day: hour,
2568            },
2569            _ => DirectionalLight3D::from_time_of_day(hour),
2570        };
2571        self.set_sun(sun_light);
2572        if clamped == 1 && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES {
2573            let cam_pos: Vec3 = self.get_camera().get_position();
2574            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
2575            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 4.5, -14.0)));
2576            rain_cfg.set_base_velocity(Vec3::new(-0.4, -17.0, 0.3));
2577            rain_cfg.set_velocity_spread(2.4);
2578            rain_cfg.set_start_color(Color::rgba(175, 222, 255, 165));
2579            rain_cfg.set_end_color(Color::rgba(92, 162, 235, 42));
2580            rain_cfg.set_start_size_m(0.042);
2581            rain_cfg.set_end_size_m(0.016);
2582            rain_cfg.set_min_lifetime(0.55);
2583            rain_cfg.set_max_lifetime(0.95);
2584            rain_cfg.set_emissive_boost(0.85);
2585            self.get_mut_niagara().emit_burst(8, &rain_cfg);
2586        }
2587        self.bump_world_revision();
2588        hour
2589    }
2590
2591    /// Registers a dynamic `PointLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
2592    ///
2593    /// # Arguments
2594    ///
2595    /// - `PointLight3D` - World-space point light descriptor.
2596    ///
2597    /// # Returns
2598    ///
2599    /// - `usize` - Assigned point light index.
2600    pub fn add_point_light(&mut self, light: PointLight3D) -> usize {
2601        let light_idx: usize = self.get_point_lights().len();
2602        self.get_mut_point_lights().push(light);
2603        self.bump_world_revision();
2604        light_idx
2605    }
2606
2607    /// Registers a dynamic `SpotLight3D` into this world for UE5 Clustered Deferred Lighting and returns its index.
2608    ///
2609    /// # Arguments
2610    ///
2611    /// - `SpotLight3D` - World-space spotlight descriptor.
2612    ///
2613    /// # Returns
2614    ///
2615    /// - `usize` - Assigned spotlight index.
2616    pub fn add_spot_light(&mut self, light: SpotLight3D) -> usize {
2617        let light_idx: usize = self.get_spot_lights().len();
2618        self.get_mut_spot_lights().push(light);
2619        self.bump_world_revision();
2620        light_idx
2621    }
2622
2623    /// Clears all dynamic local point and spot lights from this world.
2624    pub fn clear_local_lights(&mut self) {
2625        self.get_mut_point_lights().clear();
2626        self.get_mut_spot_lights().clear();
2627        self.bump_world_revision();
2628    }
2629
2630    /// Emits `count` 3D particles into the world's `NiagaraSystem3D` with zero heap allocations.
2631    ///
2632    /// # Arguments
2633    ///
2634    /// - `&NiagaraEmitterConfig3D` - Emitter properties.
2635    /// - `usize` - Number of particles to emit.
2636    ///
2637    /// # Returns
2638    ///
2639    /// - `usize` - Active particle count after emission.
2640    pub fn emit_particles_3d(&mut self, config: &NiagaraEmitterConfig3D, count: usize) -> usize {
2641        self.get_mut_niagara().emit_burst(count, config);
2642        let active: usize = self.get_niagara().get_active_count();
2643        if count > 0 {
2644            self.bump_world_revision();
2645        }
2646        active
2647    }
2648
2649    /// 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.
2650    ///
2651    /// # Arguments
2652    ///
2653    /// - `i32` - City block half-radius (`1..=5`, producing `(2r+1)x(2r+1)` multi-tower blocks).
2654    ///
2655    /// # Returns
2656    ///
2657    /// - `Self` - Populated dense 3D open-world metropolis with built static/dynamic BVHs.
2658    #[must_use]
2659    pub fn create_dense_open_world_city(blocks_radius: i32) -> Self {
2660        let radius: i32 = blocks_radius.clamp(1, 5);
2661        let mut world: Self = Self::create_open_world_city();
2662        let tower_mesh: usize = world.register_mesh(MeshLodChain::from_mesh(Mesh3D::box_mesh(
2663            DENSE_TOWER_MESH_NAME,
2664            1.0,
2665            1.0,
2666            1.0,
2667            true,
2668            PbrMaterial::default(),
2669        )));
2670        let facades: [PbrMaterial; 4] = [
2671            PbrMaterial::pbr(Color::hex(0x1E293B), 0.72, 0.16, 0.65)
2672                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2673            PbrMaterial::pbr(Color::hex(0x334155), 0.55, 0.24, 0.45)
2674                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2675            PbrMaterial::pbr(Color::hex(0x0F172A), 0.85, 0.10, 0.78)
2676                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2677            PbrMaterial::pbr(Color::hex(0x475569), 0.40, 0.35, 0.35)
2678                .with_surface_detail(SurfaceDetailMode::ArchitecturalFacade),
2679        ];
2680        let neon_palette: [Color; 4] = [
2681            Color::hex(0x38BDF8),
2682            Color::hex(0xF43F5E),
2683            Color::hex(0xA855F7),
2684            Color::hex(0x34D399),
2685        ];
2686        let mut serial: usize = 0;
2687        for bx in -radius..=radius {
2688            for bz in -radius..=radius {
2689                if bx == 0 && (-3..=3).contains(&bz) {
2690                    continue;
2691                }
2692                let center_x: f32 = (bx as f32) * 26.0;
2693                let center_z: f32 = (bz as f32) * 24.0 - 16.0;
2694                for sub in 0..4usize {
2695                    let off_x: f32 = if (sub & 1) == 0 { -5.5 } else { 5.5 };
2696                    let off_z: f32 = if (sub & 2) == 0 { -5.5 } else { 5.5 };
2697                    let height_m: f32 = 14.0 + (((serial * 11 + sub * 7) % 6) as f32) * 7.5;
2698                    let width_m: f32 = 7.5 + ((serial % 3) as f32) * 1.4;
2699                    let mat: PbrMaterial = facades[serial % facades.len()];
2700                    let _: usize = world.spawn_object(
2701                        &format!("dense_bldg_{serial}"),
2702                        tower_mesh,
2703                        Transform3D::new(
2704                            Vec3::new(center_x + off_x, 0.0, center_z + off_z),
2705                            0.0,
2706                            Vec3::new(width_m, height_m, 8.5),
2707                        ),
2708                        mat,
2709                        true,
2710                    );
2711                    serial += 1;
2712                }
2713                if (bx + bz).abs() <= 2 && world.get_point_lights().len() < 32 {
2714                    let _: usize = world.add_point_light(PointLight3D::new(
2715                        Vec3::new(center_x, 7.0, center_z),
2716                        neon_palette[serial % neon_palette.len()],
2717                        4.5,
2718                        22.0,
2719                    ));
2720                }
2721            }
2722        }
2723        world.ensure_bvh();
2724        world
2725    }
2726
2727    /// Cycles the active 3D camera perspective (`Chase` -> `Hood` -> `Orbit` -> `Aerial`) safely without clipping.
2728    ///
2729    /// # Arguments
2730    ///
2731    /// - `&Self` - Mutable world.
2732    ///
2733    /// # Returns
2734    ///
2735    /// - `u8` - New active camera mode index.
2736    pub fn cycle_camera_mode(&mut self) -> u8 {
2737        let next: u8 = (self.get_camera_mode() + 1) % 4;
2738        self.set_camera_mode(next);
2739        next
2740    }
2741
2742    /// Computes horizontal playable world bounds from non-solid ground meshes when present, preventing hardcoded invisible walls.
2743    ///
2744    /// # Arguments
2745    ///
2746    /// - `&Self` - World reference.
2747    ///
2748    /// # Returns
2749    ///
2750    /// - `Option<(f32, f32, f32, f32)>` - `(min_x, max_x, min_z, max_z)` horizontal ground limits.
2751    #[must_use]
2752    pub fn ground_play_bounds(&self) -> Option<(f32, f32, f32, f32)> {
2753        let mut found: bool = false;
2754        let mut min_x: f32 = f32::INFINITY;
2755        let mut max_x: f32 = f32::NEG_INFINITY;
2756        let mut min_z: f32 = f32::INFINITY;
2757        let mut max_z: f32 = f32::NEG_INFINITY;
2758        for obj in self.get_objects().iter() {
2759            if obj.get_ray_trace_caster()
2760                || obj.get_material().get_surface_detail() == SurfaceDetailMode::OceanWater
2761            {
2762                continue;
2763            }
2764            let blue_val: AxisAlignedBox3D = obj.get_world_bounds();
2765            let span_x: f32 = blue_val.get_max().get_x() - blue_val.get_min().get_x();
2766            let span_z: f32 = blue_val.get_max().get_z() - blue_val.get_min().get_z();
2767            if span_x >= 16.0 && span_z >= 16.0 {
2768                min_x = min_x.min(blue_val.get_min().get_x());
2769                max_x = max_x.max(blue_val.get_max().get_x());
2770                min_z = min_z.min(blue_val.get_min().get_z());
2771                max_z = max_z.max(blue_val.get_max().get_z());
2772                found = true;
2773            }
2774        }
2775        if found {
2776            Some((min_x, max_x, min_z, max_z))
2777        } else {
2778            None
2779        }
2780    }
2781
2782    /// 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.
2783    ///
2784    /// # Arguments
2785    ///
2786    /// - `&Self` - World reference.
2787    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
2788    /// - `Option<usize>` - Optional scene object index to exclude (self).
2789    ///
2790    /// # Returns
2791    ///
2792    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh triangle or closed-volume collision contact, or `None` when clear.
2793    #[must_use]
2794    pub fn mesh_oriented_box_collision(
2795        &self,
2796        candidate: OrientedBox3D,
2797        ignore_idx: Option<usize>,
2798    ) -> Option<MeshCollisionHit3D> {
2799        let query_bounds: AxisAlignedBox3D = candidate.to_world_bounds();
2800        let mut deepest: Option<MeshCollisionHit3D> = None;
2801        let objects: &[SceneObject3D] = self.get_objects().as_slice();
2802        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
2803        for (idx, obj) in objects.iter().enumerate() {
2804            if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
2805            {
2806                continue;
2807            }
2808            let obj_bounds: AxisAlignedBox3D = obj.get_world_bounds();
2809            if !Self::boxes_overlap(query_bounds, obj_bounds) {
2810                continue;
2811            }
2812            let Some(mesh) = mesh_lib
2813                .get(obj.get_mesh_id())
2814                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
2815            else {
2816                continue;
2817            };
2818            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
2819            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
2820            let obj_tr: Transform3D = obj.get_transform();
2821            let model_mat: Mat4 = obj_tr.to_mat4();
2822            let meshlets: &[Meshlet3D] = mesh.get_meshlets().as_slice();
2823            let mut hit_this_obj: bool = false;
2824            if meshlets.is_empty() {
2825                for tri in indices.iter() {
2826                    let (i0, i1, i2): (usize, usize, usize) =
2827                        (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2828                    if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2829                        let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
2830                        let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
2831                        let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
2832                        if let Some((normal, pen, contact)) =
2833                            candidate.intersect_triangle_world(w0, w1, w2)
2834                        {
2835                            hit_this_obj = true;
2836                            let replace: bool = deepest
2837                                .map(|delta_val: MeshCollisionHit3D| {
2838                                    pen > delta_val.get_penetration()
2839                                })
2840                                .unwrap_or(true);
2841                            if replace {
2842                                deepest = Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
2843                            }
2844                        }
2845                    }
2846                }
2847            } else {
2848                for ml in meshlets.iter() {
2849                    let ml_bounds: AxisAlignedBox3D = model_mat.transform_bounds(ml.get_bounds());
2850                    if !Self::boxes_overlap(query_bounds, ml_bounds) {
2851                        continue;
2852                    }
2853                    let start: usize = ml.get_first_tri() as usize;
2854                    let end: usize = start
2855                        .saturating_add(ml.get_tri_count() as usize)
2856                        .min(indices.len());
2857                    for tri in indices[start..end].iter() {
2858                        let (i0, i1, i2): (usize, usize, usize) =
2859                            (tri[0] as usize, tri[1] as usize, tri[2] as usize);
2860                        if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
2861                            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
2862                            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
2863                            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
2864                            if let Some((normal, pen, contact)) =
2865                                candidate.intersect_triangle_world(w0, w1, w2)
2866                            {
2867                                hit_this_obj = true;
2868                                let replace: bool = deepest
2869                                    .map(|distance_val: MeshCollisionHit3D| {
2870                                        pen > distance_val.get_penetration()
2871                                    })
2872                                    .unwrap_or(true);
2873                                if replace {
2874                                    deepest =
2875                                        Some(MeshCollisionHit3D::new(idx, normal, pen, contact));
2876                                }
2877                            }
2878                        }
2879                    }
2880                }
2881            }
2882            if !hit_this_obj
2883                && mesh.get_is_closed()
2884                && Self::point_in_bounds(candidate.get_center(), obj_bounds)
2885                && let Some(inside_hit) =
2886                    Self::point_inside_closed_mesh_mtv(idx, candidate, verts, indices, model_mat)
2887            {
2888                let replace: bool = deepest
2889                    .map(|prev_hit: MeshCollisionHit3D| {
2890                        inside_hit.get_penetration() > prev_hit.get_penetration()
2891                    })
2892                    .unwrap_or(true);
2893                if replace {
2894                    deepest = Some(inside_hit);
2895                }
2896            }
2897        }
2898        deepest
2899    }
2900
2901    /// Tests whether a world-space point lies strictly inside an axis-aligned bounding box.
2902    ///
2903    /// # Arguments
2904    ///
2905    /// - `Vec3` - Query point in world space.
2906    /// - `AxisAlignedBox3D` - World-space axis-aligned bounding box.
2907    ///
2908    /// # Returns
2909    ///
2910    /// - `bool` - `true` when the point lies inside the bounding box on all three axes.
2911    #[inline]
2912    #[must_use]
2913    fn point_in_bounds(point: Vec3, bounds: AxisAlignedBox3D) -> bool {
2914        let bmin: Vec3 = bounds.get_min();
2915        let bmax: Vec3 = bounds.get_max();
2916        point.get_x() >= bmin.get_x()
2917            && point.get_x() <= bmax.get_x()
2918            && point.get_y() >= bmin.get_y()
2919            && point.get_y() <= bmax.get_y()
2920            && point.get_z() >= bmin.get_z()
2921            && point.get_z() <= bmax.get_z()
2922    }
2923
2924    /// Computes the exact closest point on a 3D triangle `(v0, v1, v2)` to query point `point`.
2925    ///
2926    /// # Arguments
2927    ///
2928    /// - `Vec3` - Query point in world space.
2929    /// - `Vec3` - Triangle vertex 0.
2930    /// - `Vec3` - Triangle vertex 1.
2931    /// - `Vec3` - Triangle vertex 2.
2932    ///
2933    /// # Returns
2934    ///
2935    /// - `Vec3` - Closest point lying on or inside the triangle.
2936    #[inline]
2937    #[must_use]
2938    fn closest_point_on_triangle(point: Vec3, v0: Vec3, v1: Vec3, v2: Vec3) -> Vec3 {
2939        let ab: Vec3 = v1.sub(v0);
2940        let ac: Vec3 = v2.sub(v0);
2941        let ap: Vec3 = point.sub(v0);
2942        let d1: f32 = ab.dot(ap);
2943        let d2: f32 = ac.dot(ap);
2944        if d1 <= 0.0 && d2 <= 0.0 {
2945            return v0;
2946        }
2947        let bp: Vec3 = point.sub(v1);
2948        let d3: f32 = ab.dot(bp);
2949        let d4: f32 = ac.dot(bp);
2950        if d3 >= 0.0 && d4 <= d3 {
2951            return v1;
2952        }
2953        let vc: f32 = d1 * d4 - d3 * d2;
2954        if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
2955            let weight_v: f32 = d1 / (d1 - d3).max(1.0e-7);
2956            return v0.add(ab.scale(weight_v));
2957        }
2958        let cp: Vec3 = point.sub(v2);
2959        let d5: f32 = ab.dot(cp);
2960        let d6: f32 = ac.dot(cp);
2961        if d6 >= 0.0 && d5 <= d6 {
2962            return v2;
2963        }
2964        let vb: f32 = d5 * d2 - d1 * d6;
2965        if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
2966            let weight_w: f32 = d2 / (d2 - d6).max(1.0e-7);
2967            return v0.add(ac.scale(weight_w));
2968        }
2969        let va: f32 = d3 * d6 - d5 * d4;
2970        if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
2971            let denom_bc: f32 = ((d4 - d3) + (d5 - d6)).max(1.0e-7);
2972            let weight_w: f32 = (d4 - d3) / denom_bc;
2973            return v1.add(v2.sub(v1).scale(weight_w));
2974        }
2975        let denom: f32 = (va + vb + vc).max(1.0e-7);
2976        let weight_v: f32 = vb / denom;
2977        let weight_w: f32 = vc / denom;
2978        v0.add(ab.scale(weight_v)).add(ac.scale(weight_w))
2979    }
2980
2981    /// 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.
2982    ///
2983    /// # Arguments
2984    ///
2985    /// - `usize` - Solid scene object index in `World3D::objects`.
2986    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
2987    /// - `&[Vertex3D]` - Local mesh vertex buffer.
2988    /// - `&[[u32; 3]]` - Local mesh triangle index buffer.
2989    /// - `Mat4` - World model transform matrix of the solid mesh.
2990    ///
2991    /// # Returns
2992    ///
2993    /// - `Option<MeshCollisionHit3D>` - Outward minimum-translation-vector hit when strictly inside the closed solid, or `None` when outside (e.g. open archway tunnels).
2994    #[must_use]
2995    fn point_inside_closed_mesh_mtv(
2996        obj_idx: usize,
2997        candidate: OrientedBox3D,
2998        verts: &[Vertex3D],
2999        indices: &[[u32; 3]],
3000        model_mat: Mat4,
3001    ) -> Option<MeshCollisionHit3D> {
3002        let center: Vec3 = candidate.get_center();
3003        let parity_dir: Vec3 = Vec3::new(1.0, 1.37e-4, 2.71e-4).normalize();
3004        let mut crossings: u32 = 0;
3005        let mut best_horiz_dist_sq: f32 = f32::INFINITY;
3006        let mut best_horiz_cp: Vec3 = center;
3007        let mut best_horiz_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
3008        let mut best_any_dist_sq: f32 = f32::INFINITY;
3009        let mut best_any_cp: Vec3 = center;
3010        let mut best_any_n: Vec3 = Vec3::new(1.0, 0.0, 0.0);
3011        for tri in indices.iter() {
3012            let (i0, i1, i2): (usize, usize, usize) =
3013                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3014            if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
3015                continue;
3016            }
3017            let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3018            let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3019            let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3020            if Self::ray_intersect_triangle(center, parity_dir, w0, w1, w2, 1.0e-5, f32::INFINITY)
3021                .is_some()
3022            {
3023                crossings = crossings.wrapping_add(1);
3024            }
3025            let cp: Vec3 = Self::closest_point_on_triangle(center, w0, w1, w2);
3026            let delta: Vec3 = cp.sub(center);
3027            let dist_sq: f32 = delta.length_sq();
3028            let raw_face_n: Vec3 = w1.sub(w0).cross(w2.sub(w0));
3029            let face_n: Vec3 = if raw_face_n.length_sq() > 1.0e-10 {
3030                raw_face_n.normalize()
3031            } else {
3032                Vec3::new(1.0, 0.0, 0.0)
3033            };
3034            if dist_sq < best_any_dist_sq {
3035                best_any_dist_sq = dist_sq;
3036                best_any_cp = cp;
3037                best_any_n = face_n;
3038            }
3039            let horiz_mag_sq: f32 =
3040                face_n.get_x() * face_n.get_x() + face_n.get_z() * face_n.get_z();
3041            if horiz_mag_sq > 0.25 && dist_sq < best_horiz_dist_sq {
3042                best_horiz_dist_sq = dist_sq;
3043                best_horiz_cp = cp;
3044                best_horiz_n = Vec3::new(face_n.get_x(), 0.0, face_n.get_z()).normalize();
3045            }
3046        }
3047        if (crossings & 1) == 0 {
3048            return None;
3049        }
3050        let (target_cp, fallback_n, target_dist_sq): (Vec3, Vec3, f32) =
3051            if best_horiz_dist_sq.is_finite() {
3052                (best_horiz_cp, best_horiz_n, best_horiz_dist_sq)
3053            } else if best_any_dist_sq.is_finite() {
3054                (best_any_cp, best_any_n, best_any_dist_sq)
3055            } else {
3056                return None;
3057            };
3058        let push_raw: Vec3 = target_cp.sub(center);
3059        let push_n: Vec3 = if push_raw.length_sq() > 1.0e-8 {
3060            push_raw.normalize()
3061        } else {
3062            fallback_n
3063        };
3064        let axes: [Vec3; 3] = candidate.get_axes();
3065        let half_extents: Vec3 = candidate.get_half_extents();
3066        let obb_proj: f32 = axes[0].dot(push_n).abs() * half_extents.get_x()
3067            + axes[1].dot(push_n).abs() * half_extents.get_y()
3068            + axes[2].dot(push_n).abs() * half_extents.get_z();
3069        let total_pen: f32 = target_dist_sq.sqrt() + obb_proj;
3070        Some(MeshCollisionHit3D::new(
3071            obj_idx, push_n, total_pen, target_cp,
3072        ))
3073    }
3074
3075    /// 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.
3076    ///
3077    /// # Arguments
3078    ///
3079    /// - `&Self` - World reference.
3080    /// - `OrientedBox3D` - Candidate oriented bounding box in world space.
3081    /// - `usize` - Colliding solid scene object index.
3082    ///
3083    /// # Returns
3084    ///
3085    /// - `Vec3` - Unit horizontal outward separation normal in the XZ plane, or `Vec3::zero()` if degenerate.
3086    #[must_use]
3087    fn horizontal_collision_normal(&self, candidate: OrientedBox3D, obj_idx: usize) -> Vec3 {
3088        let Some(obj) = self.get_objects().get(obj_idx) else {
3089            return Vec3::zero();
3090        };
3091        if let Some(mesh) = self
3092            .get_mesh_library()
3093            .get(obj.get_mesh_id())
3094            .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
3095        {
3096            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
3097            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
3098            let model_mat: Mat4 = obj.get_transform().to_mat4();
3099            let mut best_pen: f32 = f32::INFINITY;
3100            let mut best_hn: Vec3 = Vec3::zero();
3101            for tri in indices.iter() {
3102                let (i0, i1, i2): (usize, usize, usize) =
3103                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3104                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3105                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3106                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3107                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3108                    if let Some((normal, pen, _)) = candidate.intersect_triangle_world(w0, w1, w2) {
3109                        let hn: Vec3 = Vec3::new(normal.get_x(), 0.0, normal.get_z());
3110                        if hn.length_sq() > 0.25 && pen < best_pen {
3111                            best_pen = pen;
3112                            best_hn = hn.normalize();
3113                        }
3114                    }
3115                }
3116            }
3117            if best_hn.length_sq() > 1.0e-6 {
3118                return best_hn;
3119            }
3120        }
3121        let bounds: AxisAlignedBox3D = obj.get_world_bounds();
3122        let bcenter: Vec3 = bounds.get_min().add(bounds.get_max()).scale(0.5);
3123        let diff: Vec3 = candidate.get_center().sub(bcenter);
3124        let horiz: Vec3 = Vec3::new(diff.get_x(), 0.0, diff.get_z());
3125        if horiz.length_sq() > 1.0e-6 {
3126            horiz.normalize()
3127        } else {
3128            Vec3::new(1.0, 0.0, 0.0)
3129        }
3130    }
3131
3132    /// Clamps a horizontal world position to playable island ground limits when present.
3133    ///
3134    /// # Arguments
3135    ///
3136    /// - `Vec3` - Candidate world position.
3137    /// - `Option<(f32, f32, f32, f32)>` - Optional playable horizontal `(min_x, max_x, min_z, max_z)` bounds.
3138    /// - `f32` - Vehicle horizontal margin in meters.
3139    ///
3140    /// # Returns
3141    ///
3142    /// - `Vec3` - Ground-clamped world position.
3143    #[inline]
3144    #[must_use]
3145    fn clamp_horizontal_to_ground(
3146        mut pos: Vec3,
3147        ground_limits: Option<(f32, f32, f32, f32)>,
3148        ground_margin: f32,
3149    ) -> Vec3 {
3150        if let Some((gx0, gx1, gz0, gz1)) = ground_limits {
3151            let lo_x: f32 = (gx0 + ground_margin).min(gx1);
3152            let hi_x: f32 = (gx1 - ground_margin).max(lo_x);
3153            let lo_z: f32 = (gz0 + ground_margin).min(gz1);
3154            let hi_z: f32 = (gz1 - ground_margin).max(lo_z);
3155            pos.set_x(pos.get_x().clamp(lo_x, hi_x));
3156            pos.set_z(pos.get_z().clamp(lo_z, hi_z));
3157        }
3158        pos
3159    }
3160
3161    /// Iteratively pushes a penetrating vehicle horizontally out of solid obstacles along the minimum-translation-vector normal until collision-free.
3162    ///
3163    /// # Arguments
3164    ///
3165    /// - `&Self` - World reference.
3166    /// - `&mut Transform3D` - Candidate vehicle transform adjusted in place when penetrating.
3167    /// - `AxisAlignedBox3D` - Vehicle local mesh bounds.
3168    /// - `usize` - Vehicle object index to ignore during self-test.
3169    /// - `Option<(f32, f32, f32, f32)>` - Optional playable ground bounds.
3170    /// - `f32` - Horizontal ground margin in meters.
3171    ///
3172    /// # Returns
3173    ///
3174    /// - `bool` - `true` when the transform was moved to resolve penetration.
3175    fn depenetrate_vehicle_horizontally(
3176        &self,
3177        transform_val: &mut Transform3D,
3178        mesh_bounds: AxisAlignedBox3D,
3179        vehicle_idx: usize,
3180        ground_limits: Option<(f32, f32, f32, f32)>,
3181        ground_margin: f32,
3182    ) -> bool {
3183        let mut adjusted: bool = false;
3184        for _ in 0..COLLISION_MTV_MAX_ITERS {
3185            let Some(hit) = self.collides_with_obstacles(*transform_val, mesh_bounds, vehicle_idx)
3186            else {
3187                break;
3188            };
3189            let raw_hn: Vec3 = Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
3190            let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
3191                raw_hn.normalize()
3192            } else {
3193                self.horizontal_collision_normal(
3194                    transform_val.to_oriented_box(mesh_bounds),
3195                    hit.get_object_index(),
3196                )
3197            };
3198            if hn.length_sq() <= 1.0e-6 {
3199                break;
3200            }
3201            let push_dist: f32 = hit.get_penetration() + COLLISION_MTV_PUSH_EPS;
3202            let cur_pos: Vec3 = transform_val.get_position();
3203            let pushed_pos: Vec3 = Self::clamp_horizontal_to_ground(
3204                Vec3::new(
3205                    cur_pos.get_x() + hn.get_x() * push_dist,
3206                    cur_pos.get_y(),
3207                    cur_pos.get_z() + hn.get_z() * push_dist,
3208                ),
3209                ground_limits,
3210                ground_margin,
3211            );
3212            transform_val.set_position(pushed_pos);
3213            adjusted = true;
3214        }
3215        adjusted
3216    }
3217
3218    /// Casts a world-space ray against every solid (`ray_trace_caster == true`) model's real mesh triangles (excluding `ignore_idx`) up to `max_dist`.
3219    ///
3220    /// # Arguments
3221    ///
3222    /// - `&Self` - World reference.
3223    /// - `Vec3` - Ray origin in world space.
3224    /// - `Vec3` - Unit ray direction in world space.
3225    /// - `f32` - Maximum ray distance.
3226    /// - `Option<usize>` - Optional scene object index to exclude.
3227    ///
3228    /// # Returns
3229    ///
3230    /// - `Option<RayHit3D>` - Closest real-mesh triangle intersection within `(1e-4, max_dist]`.
3231    #[must_use]
3232    pub fn raycast_solid_meshes(
3233        &self,
3234        origin: Vec3,
3235        direction: Vec3,
3236        max_dist: f32,
3237        ignore_idx: Option<usize>,
3238    ) -> Option<RayHit3D> {
3239        let dir: Vec3 = direction.normalize();
3240        let inv_dir: Vec3 = Ray3D::safe_inv_vec(dir);
3241        let t_min: f32 = 1e-4;
3242        let mut best_t: f32 = max_dist;
3243        let mut best_hit: Option<RayHit3D> = None;
3244        let objects: &[SceneObject3D] = self.get_objects().as_slice();
3245        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
3246        let ignore_is_static_caster: bool = ignore_idx
3247            .and_then(|idx: usize| objects.get(idx))
3248            .is_some_and(|obj: &SceneObject3D| obj.get_ray_trace_caster() && !obj.get_is_dynamic());
3249        let use_static_bvh: bool =
3250            !self.get_bvh_dirty() && !self.get_bvh().is_empty() && !ignore_is_static_caster;
3251        if use_static_bvh
3252            && let Some((hit_dist, tri_idx)) = self
3253                .get_bvh()
3254                .trace_closest_raw(origin, dir, inv_dir, t_min, best_t)
3255        {
3256            let bvh_tris: &[BvhTriangle] = self.get_bvh().get_triangles().as_slice();
3257            if let Some(hit_tri) = bvh_tris.get(tri_idx) {
3258                let raw_normal: Vec3 = hit_tri.get_normal();
3259                let oriented_normal: Vec3 = if raw_normal.dot(dir) > 0.0 {
3260                    raw_normal.scale(-1.0)
3261                } else {
3262                    raw_normal
3263                };
3264                best_t = hit_dist;
3265                best_hit = Some(RayHit3D {
3266                    distance: hit_dist,
3267                    point: origin.add(dir.scale(hit_dist)),
3268                    normal: oriented_normal,
3269                    material: hit_tri.get_material(),
3270                });
3271            }
3272        }
3273        for (idx, obj) in objects.iter().enumerate() {
3274            if ignore_idx == Some(idx) || !(obj.get_solid_collider() || obj.get_ray_trace_caster())
3275            {
3276                continue;
3277            }
3278            if use_static_bvh && obj.get_ray_trace_caster() && !obj.get_is_dynamic() {
3279                continue;
3280            }
3281            if !obj
3282                .get_world_bounds()
3283                .intersect_ray_near(origin, inv_dir, t_min, best_t)
3284                .is_finite()
3285            {
3286                continue;
3287            }
3288            let Some(mesh) = mesh_lib
3289                .get(obj.get_mesh_id())
3290                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
3291            else {
3292                continue;
3293            };
3294            let verts: &[Vertex3D] = mesh.get_vertices().as_slice();
3295            let indices: &[[u32; 3]] = mesh.get_indices().as_slice();
3296            let model_mat: Mat4 = obj.get_transform().to_mat4();
3297            let mat: PbrMaterial = obj.get_material();
3298            for tri in indices.iter() {
3299                let (i0, i1, i2): (usize, usize, usize) =
3300                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
3301                if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
3302                    let w0: Vec3 = model_mat.mul_point3(verts[i0].get_position());
3303                    let w1: Vec3 = model_mat.mul_point3(verts[i1].get_position());
3304                    let w2: Vec3 = model_mat.mul_point3(verts[i2].get_position());
3305                    if let Some((blend_factor, normal)) =
3306                        Self::ray_intersect_triangle(origin, dir, w0, w1, w2, t_min, best_t)
3307                    {
3308                        best_t = blend_factor;
3309                        best_hit = Some(RayHit3D {
3310                            distance: blend_factor,
3311                            point: origin.add(dir.scale(blend_factor)),
3312                            normal,
3313                            material: mat,
3314                        });
3315                    }
3316                }
3317            }
3318        }
3319        best_hit
3320    }
3321
3322    /// Tests whether two world-space `AxisAlignedBox3D` boxes overlap strictly.
3323    ///
3324    /// # Arguments
3325    ///
3326    /// - `AxisAlignedBox3D` - First bounding box.
3327    /// - `AxisAlignedBox3D` - Second bounding box.
3328    ///
3329    /// # Returns
3330    ///
3331    /// - `bool` - `true` when both axis-aligned bounding boxes overlap on all three axes.
3332    #[inline]
3333    #[must_use]
3334    fn boxes_overlap(alpha_val: AxisAlignedBox3D, blue_val: AxisAlignedBox3D) -> bool {
3335        let ox: bool = alpha_val.get_min().get_x() < blue_val.get_max().get_x()
3336            && alpha_val.get_max().get_x() > blue_val.get_min().get_x();
3337        let oy: bool = alpha_val.get_min().get_y() < blue_val.get_max().get_y()
3338            && alpha_val.get_max().get_y() > blue_val.get_min().get_y();
3339        let oz: bool = alpha_val.get_min().get_z() < blue_val.get_max().get_z()
3340            && alpha_val.get_max().get_z() > blue_val.get_min().get_z();
3341        ox && oy && oz
3342    }
3343
3344    /// Double-sided Möller-Trumbore ray-triangle intersection returning `(t, outward_unit_normal)`.
3345    ///
3346    /// # Arguments
3347    ///
3348    /// - `Vec3` - Ray origin.
3349    /// - `Vec3` - Unit ray direction.
3350    /// - `Vec3` - Triangle vertex 0.
3351    /// - `Vec3` - Triangle vertex 1.
3352    /// - `Vec3` - Triangle vertex 2.
3353    /// - `f32` - Minimum ray parameter `t`.
3354    /// - `f32` - Maximum ray parameter `t`.
3355    ///
3356    /// # Returns
3357    ///
3358    /// - `Option<(f32, Vec3)>` - Hit distance and facing unit normal.
3359    #[inline]
3360    #[must_use]
3361    fn ray_intersect_triangle(
3362        origin: Vec3,
3363        dir: Vec3,
3364        v0: Vec3,
3365        v1: Vec3,
3366        v2: Vec3,
3367        t_min: f32,
3368        t_max: f32,
3369    ) -> Option<(f32, Vec3)> {
3370        let e1: Vec3 = v1.sub(v0);
3371        let e2: Vec3 = v2.sub(v0);
3372        let pvec: Vec3 = dir.cross(e2);
3373        let det: f32 = e1.dot(pvec);
3374        if det.abs() < 1e-7 {
3375            return None;
3376        }
3377        let inv_det: f32 = 1.0 / det;
3378        let tvec: Vec3 = origin.sub(v0);
3379        let tex_u: f32 = tvec.dot(pvec) * inv_det;
3380        if !(0.0..=1.0).contains(&tex_u) {
3381            return None;
3382        }
3383        let qvec: Vec3 = tvec.cross(e1);
3384        let item_val: f32 = dir.dot(qvec) * inv_det;
3385        if item_val < 0.0 || tex_u + item_val > 1.0 {
3386            return None;
3387        }
3388        let blend_factor: f32 = e2.dot(qvec) * inv_det;
3389        if blend_factor <= t_min || blend_factor > t_max {
3390            return None;
3391        }
3392        let raw_n: Vec3 = e1.cross(e2).normalize();
3393        let normal: Vec3 = if raw_n.dot(dir) > 0.0 {
3394            raw_n.scale(-1.0)
3395        } else {
3396            raw_n
3397        };
3398        Some((blend_factor, normal))
3399    }
3400
3401    /// Tests whether a candidate transformed mesh collides with any solid obstacle's real triangles excluding `ignore_idx`.
3402    ///
3403    /// # Arguments
3404    ///
3405    /// - `&Self` - World reference.
3406    /// - `Transform3D` - Candidate object transform.
3407    /// - `AxisAlignedBox3D` - Candidate local mesh bounds.
3408    /// - `usize` - Self object index to skip.
3409    ///
3410    /// # Returns
3411    ///
3412    /// - `Option<MeshCollisionHit3D>` - Deepest real-mesh collision hit, or `None` when clear.
3413    #[must_use]
3414    fn collides_with_obstacles(
3415        &self,
3416        candidate_tr: Transform3D,
3417        local_bounds: AxisAlignedBox3D,
3418        ignore_idx: usize,
3419    ) -> Option<MeshCollisionHit3D> {
3420        let oriented_box: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
3421        self.mesh_oriented_box_collision(oriented_box, Some(ignore_idx))
3422    }
3423
3424    /// Tests whether a candidate traffic-vehicle transform overlaps any static obstacle mesh or symmetrically intersects any other dynamic vehicle's oriented bounding box.
3425    ///
3426    /// # Arguments
3427    ///
3428    /// - `&Self` - World reference.
3429    /// - `Transform3D` - Candidate traffic vehicle transform.
3430    /// - `AxisAlignedBox3D` - Candidate traffic vehicle local mesh bounds.
3431    /// - `usize` - Traffic vehicle object index to exclude.
3432    ///
3433    /// # Returns
3434    ///
3435    /// - `bool` - `true` when the candidate pose collides with a static obstacle or another dynamic vehicle OBB.
3436    #[must_use]
3437    fn traffic_pose_blocked(
3438        &self,
3439        candidate_tr: Transform3D,
3440        local_bounds: AxisAlignedBox3D,
3441        traffic_idx: usize,
3442    ) -> bool {
3443        let cand_obb: OrientedBox3D = candidate_tr.to_oriented_box(local_bounds);
3444        if self
3445            .mesh_oriented_box_collision(cand_obb, Some(traffic_idx))
3446            .is_some()
3447        {
3448            return true;
3449        }
3450        let objects: &[SceneObject3D] = self.get_objects().as_slice();
3451        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
3452        let cand_bounds: AxisAlignedBox3D = cand_obb.to_world_bounds();
3453        for (other_idx, other_obj) in objects.iter().enumerate() {
3454            let is_solid_other: bool =
3455                other_obj.get_solid_collider() || other_obj.get_ray_trace_caster();
3456            if other_idx == traffic_idx || !other_obj.get_is_dynamic() || !is_solid_other {
3457                continue;
3458            }
3459            if !Self::boxes_overlap(cand_bounds, other_obj.get_world_bounds()) {
3460                continue;
3461            }
3462            let other_local: AxisAlignedBox3D = mesh_lib
3463                .get(other_obj.get_mesh_id())
3464                .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
3465                .map(Mesh3D::get_bounds)
3466                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
3467            let other_obb: OrientedBox3D = other_obj.get_transform().to_oriented_box(other_local);
3468            if cand_obb.intersects_oriented_box(&other_obb) {
3469                return true;
3470            }
3471        }
3472        false
3473    }
3474
3475    /// Advances drivable vehicle/camera controls with continuous real-mesh oriented bounding box-vs-triangle collision, wall sliding, raycast camera boom, and synchronized spinning bounds.
3476    ///
3477    /// # Arguments
3478    ///
3479    /// - `&Self` - Mutable world.
3480    /// - `f32` - Delta time in seconds.
3481    /// - `&InputState` - Real-time polled keyboard/pointer input.
3482    /// - `&ActionMap` - Action bindings for WASD/Arrows movement.
3483    pub fn step_simulation(&mut self, dt: f32, input: &InputState, actions: &ActionMap) {
3484        if dt > 0.0 {
3485            self.set_world_time_secs(self.get_world_time_secs() + dt);
3486        }
3487        let move_vec: Point = actions.movement_vector(input);
3488        let steer: f32 = move_vec.get_x();
3489        let throttle: f32 = -move_vec.get_y();
3490        let mut any_dynamic_moved: bool = false;
3491        let mut any_static_moved: bool = false;
3492        let ground_limits: Option<(f32, f32, f32, f32)> = self.ground_play_bounds();
3493        let car_opt: Option<usize> = self.vehicle_index();
3494        if let Some(car_idx) = car_opt
3495            && let Some((mut transform_val, mesh_id, car_is_dynamic)) =
3496                self.get_objects().get(car_idx).map(|car: &SceneObject3D| {
3497                    (car.get_transform(), car.get_mesh_id(), car.get_is_dynamic())
3498                })
3499        {
3500            let mut car_moved: bool = false;
3501            let mesh_bounds: AxisAlignedBox3D = self
3502                .get_mesh_library()
3503                .get(mesh_id)
3504                .and_then(|char_item: &MeshLodChain| char_item.get_levels().first())
3505                .map(Mesh3D::get_bounds)
3506                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-2.0), Vec3::splat(2.0)));
3507            let init_obb: OrientedBox3D = transform_val.to_oriented_box(mesh_bounds);
3508            let ground_margin: f32 = init_obb
3509                .get_half_extents()
3510                .get_x()
3511                .max(init_obb.get_half_extents().get_z());
3512            if self.depenetrate_vehicle_horizontally(
3513                &mut transform_val,
3514                mesh_bounds,
3515                car_idx,
3516                ground_limits,
3517                ground_margin,
3518            ) {
3519                car_moved = true;
3520            }
3521            if steer.abs() > 0.05 {
3522                let total_yaw: f32 = -steer * 1.85 * dt;
3523                let rot_steps: usize = ((total_yaw.abs() / COLLISION_ROT_MAX_STEP_RAD).ceil()
3524                    as usize)
3525                    .clamp(1, COLLISION_ROT_MAX_SUBSTEPS);
3526                let step_yaw: f32 = total_yaw / (rot_steps as f32);
3527                for _ in 0..rot_steps {
3528                    let mut rotated: Transform3D = transform_val;
3529                    rotated.set_yaw_rad(transform_val.get_yaw_rad() + step_yaw);
3530                    if let Some(rot_hit) =
3531                        self.collides_with_obstacles(rotated, mesh_bounds, car_idx)
3532                    {
3533                        if rot_hit.get_penetration() <= COLLISION_ROT_MAX_PUSH_M {
3534                            let mut pushed_rot: Transform3D = rotated;
3535                            let _: bool = self.depenetrate_vehicle_horizontally(
3536                                &mut pushed_rot,
3537                                mesh_bounds,
3538                                car_idx,
3539                                ground_limits,
3540                                ground_margin,
3541                            );
3542                            let shift_m: f32 = pushed_rot
3543                                .get_position()
3544                                .sub(rotated.get_position())
3545                                .length();
3546                            if shift_m <= COLLISION_ROT_MAX_PUSH_M
3547                                && self
3548                                    .collides_with_obstacles(pushed_rot, mesh_bounds, car_idx)
3549                                    .is_none()
3550                            {
3551                                transform_val = pushed_rot;
3552                                car_moved = true;
3553                                continue;
3554                            }
3555                        }
3556                        break;
3557                    }
3558                    transform_val = rotated;
3559                    car_moved = true;
3560                }
3561            }
3562            if throttle.abs() > 0.05 {
3563                let fwd_x: f32 = -transform_val.get_yaw_rad().sin();
3564                let fwd_z: f32 = -transform_val.get_yaw_rad().cos();
3565                let total_disp: Vec3 = Vec3::new(fwd_x, 0.0, fwd_z).scale(24.0 * throttle * dt);
3566                let oriented_box_now: OrientedBox3D = transform_val.to_oriented_box(mesh_bounds);
3567                let min_half: f32 = oriented_box_now
3568                    .get_half_extents()
3569                    .get_x()
3570                    .min(oriented_box_now.get_half_extents().get_z())
3571                    .max(0.25);
3572                let max_step_len: f32 = (min_half * 0.25).min(COLLISION_CCD_MAX_STEP_M);
3573                let substeps: usize = ((total_disp.length() / max_step_len).ceil() as usize)
3574                    .clamp(1, COLLISION_CCD_MAX_SUBSTEPS);
3575                let step_delta: Vec3 = total_disp.scale(1.0 / (substeps as f32));
3576                for _ in 0..substeps {
3577                    let cur: Vec3 = transform_val.get_position();
3578                    let next_pos: Vec3 = Self::clamp_horizontal_to_ground(
3579                        Vec3::new(
3580                            cur.get_x() + step_delta.get_x(),
3581                            cur.get_y(),
3582                            cur.get_z() + step_delta.get_z(),
3583                        ),
3584                        ground_limits,
3585                        ground_margin,
3586                    );
3587                    let mut cand: Transform3D = transform_val;
3588                    cand.set_position(next_pos);
3589                    if let Some(hit) = self.collides_with_obstacles(cand, mesh_bounds, car_idx) {
3590                        let raw_hn: Vec3 =
3591                            Vec3::new(hit.get_normal().get_x(), 0.0, hit.get_normal().get_z());
3592                        let hn: Vec3 = if raw_hn.length_sq() > 1.0e-4 {
3593                            raw_hn.normalize()
3594                        } else {
3595                            self.horizontal_collision_normal(
3596                                cand.to_oriented_box(mesh_bounds),
3597                                hit.get_object_index(),
3598                            )
3599                        };
3600                        if hn.length_sq() > 1.0e-6 {
3601                            let into: f32 = step_delta.dot(hn);
3602                            let slide_delta: Vec3 = if into < 0.0 {
3603                                step_delta.sub(hn.scale(into))
3604                            } else {
3605                                Vec3::zero()
3606                            };
3607                            if slide_delta.length_sq() > 1.0e-8 {
3608                                let slide_pos: Vec3 = Self::clamp_horizontal_to_ground(
3609                                    Vec3::new(
3610                                        cur.get_x() + slide_delta.get_x(),
3611                                        cur.get_y(),
3612                                        cur.get_z() + slide_delta.get_z(),
3613                                    ),
3614                                    ground_limits,
3615                                    ground_margin,
3616                                );
3617                                let mut slide_tr: Transform3D = transform_val;
3618                                slide_tr.set_position(slide_pos);
3619                                if self
3620                                    .collides_with_obstacles(slide_tr, mesh_bounds, car_idx)
3621                                    .is_none()
3622                                {
3623                                    transform_val = slide_tr;
3624                                    car_moved = true;
3625                                    continue;
3626                                }
3627                            }
3628                        }
3629                        break;
3630                    } else {
3631                        transform_val = cand;
3632                        car_moved = true;
3633                    }
3634                }
3635            }
3636            if car_moved {
3637                let world_b: AxisAlignedBox3D = transform_val.transform_bounds(mesh_bounds);
3638                if let Some(car_mut) = self.get_mut_objects().get_mut(car_idx) {
3639                    car_mut.set_transform(transform_val);
3640                    car_mut.set_world_bounds(world_b);
3641                }
3642                if car_is_dynamic {
3643                    any_dynamic_moved = true;
3644                } else {
3645                    any_static_moved = true;
3646                }
3647                let car_yaw: f32 = transform_val.get_yaw_rad();
3648                let car_origin: Vec3 = transform_val.get_position();
3649                let car_fwd: Vec3 = Vec3::new(-car_yaw.sin(), 0.0, -car_yaw.cos());
3650                let car_right: Vec3 = Vec3::new(car_yaw.cos(), 0.0, -car_yaw.sin());
3651                let beam_dir: Vec3 = Vec3::new(car_fwd.get_x(), -0.14, car_fwd.get_z()).normalize();
3652                if self.get_spot_lights().len() >= 2 {
3653                    let front_center: Vec3 = car_origin
3654                        .add(car_fwd.scale(2.2))
3655                        .add(Vec3::new(0.0, 0.95, 0.0));
3656                    let left_pos: Vec3 = front_center.sub(car_right.scale(0.85));
3657                    let right_pos: Vec3 = front_center.add(car_right.scale(0.85));
3658                    let spots: &mut Vec<SpotLight3D> = self.get_mut_spot_lights();
3659                    spots[0].set_position(left_pos);
3660                    spots[0].set_direction(beam_dir);
3661                    spots[1].set_position(right_pos);
3662                    spots[1].set_direction(beam_dir);
3663                }
3664                if let Some(tail_light) = self.get_mut_point_lights().first_mut()
3665                    && tail_light.get_color().get_x() > 0.90
3666                    && tail_light.get_color().get_y() < 0.15
3667                {
3668                    let rear_pos: Vec3 = car_origin
3669                        .sub(car_fwd.scale(2.9))
3670                        .add(Vec3::new(0.0, 0.95, 0.0));
3671                    tail_light.set_position(rear_pos);
3672                }
3673                if throttle.abs() > 0.25
3674                    && (self.get_world_revision() & 3) == 0
3675                    && self.get_niagara().get_active_count() < 24
3676                {
3677                    let exhaust_pos: Vec3 = car_origin
3678                        .sub(car_fwd.scale(2.3))
3679                        .add(Vec3::new(0.0, 0.42, 0.0));
3680                    let mut spark_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
3681                    spark_cfg.set_origin(exhaust_pos);
3682                    spark_cfg.set_base_velocity(car_fwd.scale(-4.5).add(Vec3::new(0.0, 1.1, 0.0)));
3683                    spark_cfg.set_start_size_m(0.11);
3684                    spark_cfg.set_end_size_m(0.03);
3685                    self.get_mut_niagara().emit_burst(1, &spark_cfg);
3686                }
3687            }
3688            let car_tr: Transform3D = self.get_objects()[car_idx].get_transform();
3689            let car_pos: Vec3 = car_tr.get_position();
3690            let yaw: f32 = car_tr.get_yaw_rad();
3691            let cam_mode: u8 = self.get_camera_mode();
3692            let (mut desired_eye, look_target): (Vec3, Vec3) = match cam_mode {
3693                1 => {
3694                    let eye: Vec3 = Vec3::new(
3695                        car_pos.get_x() - yaw.sin() * 1.4,
3696                        2.15,
3697                        car_pos.get_z() - yaw.cos() * 1.4,
3698                    );
3699                    let tgt: Vec3 = Vec3::new(
3700                        car_pos.get_x() - yaw.sin() * 18.0,
3701                        1.8,
3702                        car_pos.get_z() - yaw.cos() * 18.0,
3703                    );
3704                    (eye, tgt)
3705                }
3706                2 => {
3707                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.45;
3708                    self.set_camera_orbit_rad(orbit);
3709                    let eye: Vec3 = Vec3::new(
3710                        car_pos.get_x() + orbit.sin() * 10.5,
3711                        5.2,
3712                        car_pos.get_z() + orbit.cos() * 10.5,
3713                    );
3714                    (eye, Vec3::new(car_pos.get_x(), 1.6, car_pos.get_z()))
3715                }
3716                3 => {
3717                    let eye: Vec3 = Vec3::new(
3718                        car_pos.get_x() + yaw.sin() * 18.0,
3719                        18.5,
3720                        car_pos.get_z() + yaw.cos() * 18.0,
3721                    );
3722                    (eye, Vec3::new(car_pos.get_x(), 1.2, car_pos.get_z()))
3723                }
3724                4 => {
3725                    let cur_cam: Camera3D = self.get_camera();
3726                    let fwd: Vec3 = cur_cam.forward();
3727                    let right: Vec3 = cur_cam.right();
3728                    let moved: Vec3 = cur_cam
3729                        .get_position()
3730                        .add(fwd.scale(throttle * 18.0 * dt))
3731                        .add(right.scale(steer * 14.0 * dt));
3732                    let eye: Vec3 = Vec3::new(moved.get_x(), moved.get_y().max(1.5), moved.get_z());
3733                    (eye, eye.add(fwd.scale(16.0)))
3734                }
3735                5 => {
3736                    let orbit: f32 = self.get_camera_orbit_rad() + dt * 0.28;
3737                    self.set_camera_orbit_rad(orbit);
3738                    let eye: Vec3 = Vec3::new(
3739                        car_pos.get_x() + orbit.sin() * 7.8,
3740                        3.6 + (orbit * 1.5).sin() * 1.4,
3741                        car_pos.get_z() + orbit.cos() * 13.5,
3742                    );
3743                    (eye, Vec3::new(car_pos.get_x(), 1.8, car_pos.get_z() - 3.0))
3744                }
3745                _ => {
3746                    let eye: Vec3 = Vec3::new(
3747                        car_pos.get_x() + yaw.sin() * 9.8,
3748                        4.25,
3749                        car_pos.get_z() + yaw.cos() * 9.8,
3750                    );
3751                    let tgt: Vec3 = Vec3::new(
3752                        car_pos.get_x() - yaw.sin() * 16.0,
3753                        2.40,
3754                        car_pos.get_z() - yaw.cos() * 16.0,
3755                    );
3756                    (eye, tgt)
3757                }
3758            };
3759            let boom_anchor: Vec3 =
3760                Vec3::new(car_pos.get_x(), car_pos.get_y() + 1.8, car_pos.get_z());
3761            let boom_vec: Vec3 = desired_eye.sub(boom_anchor);
3762            let boom_len: f32 = boom_vec.length();
3763            if boom_len > 0.25 {
3764                let boom_dir: Vec3 = boom_vec.scale(1.0 / boom_len);
3765                if let Some(hit) =
3766                    self.raycast_solid_meshes(boom_anchor, boom_dir, boom_len, Some(car_idx))
3767                {
3768                    let safe_dist: f32 = (hit.get_distance() - 0.55).max(0.8);
3769                    desired_eye = boom_anchor.add(boom_dir.scale(safe_dist));
3770                }
3771            }
3772            let cam_probe: OrientedBox3D = OrientedBox3D::from_bounds(AxisAlignedBox3D::new(
3773                desired_eye.sub(Vec3::splat(0.45)),
3774                desired_eye.add(Vec3::splat(0.45)),
3775            ));
3776            if let Some(hit) = self.mesh_oriented_box_collision(cam_probe, Some(car_idx)) {
3777                desired_eye = desired_eye.add(hit.get_normal().scale(hit.get_penetration() + 0.1));
3778            }
3779            let prev_cam: Camera3D = self.get_camera();
3780            let mut cam: Camera3D = prev_cam;
3781            let smooth: f32 = (dt * 7.0).clamp(0.05, 1.0);
3782            cam.set_position(cam.get_position().lerp(desired_eye, smooth));
3783            let look_dir: Vec3 = look_target.sub(cam.get_position()).normalize();
3784            cam.set_yaw(look_dir.get_z().atan2(look_dir.get_x()));
3785            cam.set_pitch(look_dir.get_y().clamp(-0.92, 0.92).asin());
3786            self.set_camera(cam);
3787            if cam != prev_cam {
3788                self.bump_world_revision();
3789            }
3790        }
3791        let traffic_count: usize = self.traffic_vehicle_count();
3792        let bumper_clearance_m: f32 = 0.75;
3793        for slot_idx in 0..traffic_count {
3794            let (traffic_idx, vel_z, z_min, z_max): (usize, f32, f32, f32) = {
3795                let Self {
3796                    traffic_vehicles, ..
3797                } = self;
3798                traffic_vehicles[slot_idx]
3799            };
3800            let Some((mut tr, mesh_id, is_dynamic)) =
3801                self.get_objects()
3802                    .get(traffic_idx)
3803                    .map(|obj: &SceneObject3D| {
3804                        (obj.get_transform(), obj.get_mesh_id(), obj.get_is_dynamic())
3805                    })
3806            else {
3807                continue;
3808            };
3809            let local_bounds: AxisAlignedBox3D = self
3810                .get_mesh_library()
3811                .get(mesh_id)
3812                .and_then(|chain_item: &MeshLodChain| chain_item.get_levels().first())
3813                .map(Mesh3D::get_bounds)
3814                .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
3815            let traffic_obb: OrientedBox3D = tr.to_oriented_box(local_bounds);
3816            let traffic_margin: f32 = traffic_obb
3817                .get_half_extents()
3818                .get_x()
3819                .max(traffic_obb.get_half_extents().get_z());
3820            let mut moved_traffic: bool = self.depenetrate_vehicle_horizontally(
3821                &mut tr,
3822                local_bounds,
3823                traffic_idx,
3824                ground_limits,
3825                traffic_margin,
3826            );
3827            let total_dz: f32 = vel_z * dt;
3828            if total_dz.abs() <= 1e-6 && !moved_traffic {
3829                continue;
3830            }
3831            let dir_z: f32 = if vel_z >= 0.0 { 1.0 } else { -1.0 };
3832            let start_z: f32 = tr.get_position().get_z();
3833            let target_z: f32 = start_z + total_dz;
3834            let mut wrapped: bool = false;
3835            if total_dz.abs() > 1e-6 && (target_z < z_min || target_z > z_max) {
3836                let wrap_z: f32 = if target_z < z_min { z_max } else { z_min };
3837                let mut wrap_tr: Transform3D = tr;
3838                let mut wrap_pos: Vec3 = wrap_tr.get_position();
3839                wrap_pos.set_z(wrap_z);
3840                wrap_tr.set_position(wrap_pos);
3841                let mut probe_tr: Transform3D = wrap_tr;
3842                let mut probe_pos: Vec3 = wrap_pos;
3843                probe_pos.set_z(wrap_z + dir_z * bumper_clearance_m);
3844                probe_tr.set_position(probe_pos);
3845                if !self.traffic_pose_blocked(wrap_tr, local_bounds, traffic_idx)
3846                    && !self.traffic_pose_blocked(probe_tr, local_bounds, traffic_idx)
3847                {
3848                    tr = wrap_tr;
3849                    moved_traffic = true;
3850                    wrapped = true;
3851                }
3852            } else if total_dz.abs() > 1e-6 {
3853                let substeps: usize = ((total_dz.abs() / COLLISION_CCD_MAX_STEP_M).ceil() as usize)
3854                    .clamp(1, COLLISION_CCD_MAX_SUBSTEPS);
3855                let step_dz: f32 = total_dz / (substeps as f32);
3856                for _ in 0..substeps {
3857                    let cur_pos: Vec3 = tr.get_position();
3858                    let next_z: f32 = cur_pos.get_z() + step_dz;
3859                    let mut cand_tr: Transform3D = tr;
3860                    let mut cand_pos: Vec3 = cur_pos;
3861                    cand_pos.set_z(next_z);
3862                    cand_tr.set_position(cand_pos);
3863                    let mut probe_tr: Transform3D = cand_tr;
3864                    let mut probe_pos: Vec3 = cand_pos;
3865                    probe_pos.set_z(next_z + dir_z * bumper_clearance_m);
3866                    probe_tr.set_position(probe_pos);
3867                    let blocked: bool =
3868                        self.traffic_pose_blocked(cand_tr, local_bounds, traffic_idx)
3869                            || self.traffic_pose_blocked(probe_tr, local_bounds, traffic_idx);
3870                    if blocked {
3871                        break;
3872                    }
3873                    tr = cand_tr;
3874                    moved_traffic = true;
3875                }
3876            }
3877            if moved_traffic {
3878                let world_b: AxisAlignedBox3D = tr.transform_bounds(local_bounds);
3879                if let Some(obj) = self.get_mut_objects().get_mut(traffic_idx) {
3880                    obj.set_transform(tr);
3881                    if wrapped {
3882                        obj.set_teleport_epoch(obj.get_teleport_epoch().wrapping_add(1));
3883                    }
3884                    obj.set_world_bounds(world_b);
3885                }
3886                if is_dynamic {
3887                    any_dynamic_moved = true;
3888                } else {
3889                    any_static_moved = true;
3890                }
3891            }
3892        }
3893        let Self {
3894            objects,
3895            mesh_library,
3896            ..
3897        } = self;
3898        for obj in objects.iter_mut() {
3899            let spin: f32 = obj.get_spin_speed();
3900            if spin.abs() > 0.001 {
3901                let mut object_transform: Transform3D = obj.get_transform();
3902                object_transform.set_yaw_rad(object_transform.get_yaw_rad() + spin * dt);
3903                obj.set_transform(object_transform);
3904                let local_bounds: AxisAlignedBox3D = mesh_library
3905                    .get(obj.get_mesh_id())
3906                    .and_then(|color_item: &MeshLodChain| color_item.get_levels().first())
3907                    .map(Mesh3D::get_bounds)
3908                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
3909                obj.set_world_bounds(object_transform.transform_bounds(local_bounds));
3910                if obj.get_is_dynamic() {
3911                    any_dynamic_moved = true;
3912                } else {
3913                    any_static_moved = true;
3914                }
3915            }
3916        }
3917        if self.get_atmosphere_preset() == 1
3918            && (self.get_world_revision() & 1) == 0
3919            && self.get_niagara().get_active_count() < RAINY_NIGHT_MAX_PARTICLES
3920        {
3921            let cam_pos: Vec3 = self.get_camera().get_position();
3922            let mut rain_cfg: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
3923            rain_cfg.set_origin(cam_pos.add(Vec3::new(0.0, 5.0, -14.0)));
3924            rain_cfg.set_base_velocity(Vec3::new(-0.5, -15.5, 0.3));
3925            rain_cfg.set_velocity_spread(3.6);
3926            rain_cfg.set_start_color(Color::rgba(150, 218, 255, 210));
3927            rain_cfg.set_end_color(Color::rgba(68, 152, 240, 60));
3928            rain_cfg.set_start_size_m(0.07);
3929            rain_cfg.set_end_size_m(0.03);
3930            rain_cfg.set_min_lifetime(0.6);
3931            rain_cfg.set_max_lifetime(0.95);
3932            rain_cfg.set_emissive_boost(1.4);
3933            self.get_mut_niagara().emit_burst(2, &rain_cfg);
3934        }
3935        if self.get_niagara().get_active_count() > 0 {
3936            let _: usize = self.get_mut_niagara().update(dt, 0.0);
3937        }
3938        if !self.get_animation_mixer().get_layers().is_empty() {
3939            let anim_updates: usize = self.tick_animations(dt);
3940            if anim_updates > 0 {
3941                any_dynamic_moved = true;
3942            }
3943        }
3944        if any_static_moved {
3945            self.set_bvh_dirty(true);
3946        }
3947        if any_dynamic_moved {
3948            self.set_dynamic_bvh_dirty(true);
3949        }
3950        if any_static_moved || any_dynamic_moved {
3951            self.bump_world_revision();
3952        }
3953    }
3954
3955    /// Returns the optional precomputed IBL environment attached to this world.
3956    ///
3957    /// # Returns
3958    ///
3959    /// - `Option<&EnvironmentIbl3D>` - Borrowed IBL environment if configured.
3960    #[must_use]
3961    pub fn environment_ibl(&self) -> Option<&EnvironmentIbl3D> {
3962        let Self {
3963            environment_ibl, ..
3964        } = self;
3965        environment_ibl.as_ref()
3966    }
3967
3968    /// Replaces the world's active IBL environment and increments the world revision.
3969    ///
3970    /// # Arguments
3971    ///
3972    /// - `&Self` - Mutable world.
3973    /// - `Option<EnvironmentIbl3D>` - New IBL environment or `None` to clear.
3974    pub fn set_environment_ibl(&mut self, ibl: Option<EnvironmentIbl3D>) {
3975        let Self {
3976            environment_ibl, ..
3977        } = self;
3978        *environment_ibl = ibl;
3979        self.bump_world_revision();
3980    }
3981
3982    /// Returns the currently active multi-camera index inside `scene_cameras`, if selected.
3983    ///
3984    /// # Returns
3985    ///
3986    /// - `Option<usize>` - Active camera index in `scene_cameras`, or `None` when using `camera`.
3987    #[must_use]
3988    pub fn active_scene_camera_index(&self) -> Option<usize> {
3989        let Self {
3990            active_scene_camera,
3991            ..
3992        } = self;
3993        *active_scene_camera
3994    }
3995
3996    /// Selects an active camera from `scene_cameras` (or `None` to revert to the default `camera`).
3997    ///
3998    /// # Arguments
3999    ///
4000    /// - `&Self` - Mutable world.
4001    /// - `Option<usize>` - Target camera index inside `scene_cameras`.
4002    ///
4003    /// # Returns
4004    ///
4005    /// - `bool` - `true` when the requested camera selection succeeded.
4006    pub fn set_active_scene_camera(&mut self, camera_index: Option<usize>) -> bool {
4007        let cam_count: usize = self.get_scene_cameras().len();
4008        if let Some(target_idx) = camera_index
4009            && target_idx >= cam_count
4010        {
4011            return false;
4012        }
4013        let Self {
4014            active_scene_camera,
4015            ..
4016        } = self;
4017        *active_scene_camera = camera_index;
4018        if let Some(target_idx) = camera_index
4019            && let Some(scene_cam) = self.get_scene_cameras().get(target_idx).cloned()
4020        {
4021            self.set_camera(scene_cam.to_camera3d());
4022        }
4023        self.bump_world_revision();
4024        true
4025    }
4026
4027    /// Returns the active camera's view-projection matrix (respecting Perspective or Orthographic `SceneCamera3D` when selected).
4028    ///
4029    /// # Arguments
4030    ///
4031    /// - `&Self` - World reference.
4032    /// - `f32` - Viewport width-to-height aspect ratio.
4033    ///
4034    /// # Returns
4035    ///
4036    /// - `Mat4` - Active view-projection matrix.
4037    #[must_use]
4038    pub fn active_view_projection(&self, viewport_aspect: f32) -> Mat4 {
4039        if let Some(cam_idx) = self.active_scene_camera_index()
4040            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
4041        {
4042            return scene_cam.view_projection(viewport_aspect);
4043        }
4044        self.get_camera().view_projection(viewport_aspect)
4045    }
4046
4047    /// Returns the live deformed (morphed and/or skinned) `Mesh3D` for `obj_idx` if active.
4048    ///
4049    /// # Arguments
4050    ///
4051    /// - `&Self` - World reference.
4052    /// - `usize` - Target object index in `objects`.
4053    ///
4054    /// # Returns
4055    ///
4056    /// - `Option<&Mesh3D>` - Borrowed deformed mesh when shape keys or armature skinning are active on `obj_idx`.
4057    #[must_use]
4058    pub fn deformed_mesh_for_object(&self, obj_idx: usize) -> Option<&Mesh3D> {
4059        let Self {
4060            deformed_meshes, ..
4061        } = self;
4062        deformed_meshes.get(obj_idx).and_then(Option::as_ref)
4063    }
4064
4065    /// Returns whether `obj_idx` is effectively visible after evaluating hierarchical node visibility and 64-bit Blender Collections masks.
4066    ///
4067    /// # Arguments
4068    ///
4069    /// - `&Self` - World reference.
4070    /// - `usize` - Target object index in `objects`.
4071    ///
4072    /// # Returns
4073    ///
4074    /// - `bool` - `true` when the object should be rendered.
4075    #[must_use]
4076    pub fn is_object_visible(&self, obj_idx: usize) -> bool {
4077        let Some(obj) = self.get_objects().get(obj_idx) else {
4078            return false;
4079        };
4080        if let Some(node_id) = obj.try_get_node_id() {
4081            return self.get_scene_graph().is_node_effectively_visible(node_id);
4082        }
4083        true
4084    }
4085
4086    /// Updates the deformation algorithm (`LinearBlend` or `DualQuaternion`) for skin `skin_idx` and refreshes deformed meshes immediately.
4087    ///
4088    /// # Arguments
4089    ///
4090    /// - `&Self` - Mutable world.
4091    /// - `usize` - Skin index inside `skins`.
4092    /// - `SkinningMode` - Desired skinning mode.
4093    ///
4094    /// # Returns
4095    ///
4096    /// - `bool` - `true` when `skin_idx` existed.
4097    pub fn set_skinning_mode(&mut self, skin_idx: usize, mode: SkinningMode) -> bool {
4098        let Some(skin) = self.get_mut_skins().get_mut(skin_idx) else {
4099            return false;
4100        };
4101        skin.set_skinning_mode(mode);
4102        let _: usize = self.update_deformed_meshes();
4103        self.bump_world_revision();
4104        true
4105    }
4106
4107    /// Toggles viewport visibility for Blender Collection `collection_name` in `scene_graph`.
4108    ///
4109    /// # Arguments
4110    ///
4111    /// - `&Self` - Mutable world.
4112    /// - `&str` - Collection name.
4113    /// - `bool` - Desired viewport visibility state.
4114    ///
4115    /// # Returns
4116    ///
4117    /// - `bool` - `true` when a matching collection was updated.
4118    pub fn set_collection_visible(&mut self, collection_name: &str, visible: bool) -> bool {
4119        let updated: bool = self
4120            .get_mut_scene_graph()
4121            .get_mut_collections()
4122            .set_collection_visible(collection_name, visible);
4123        if updated {
4124            self.bump_world_revision();
4125        }
4126        updated
4127    }
4128
4129    /// 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.
4130    ///
4131    /// # Arguments
4132    ///
4133    /// - `&Self` - Mutable 3D world.
4134    /// - `&ImportedScene3D` - Parsed Blender/glTF 2.0 scene bundle.
4135    ///
4136    /// # Returns
4137    ///
4138    /// - `Vec<usize>` - Indices of all spawned `SceneObject3D` entries inside `World3D::objects`.
4139    pub fn load_imported_scene(&mut self, scene: &ImportedScene3D) -> Vec<usize> {
4140        let texture_base: u32 = self.get_textures().len() as u32;
4141        self.get_mut_textures()
4142            .extend(scene.get_textures().iter().cloned());
4143        let material_base: u32 = self.get_principled_materials().len() as u32;
4144        for raw_mat in scene.get_materials().iter() {
4145            let mut rebased: PrincipledMaterial3D = raw_mat.clone();
4146            Self::rebase_material_textures(&mut rebased, texture_base);
4147            self.get_mut_principled_materials().push(rebased);
4148        }
4149        let mesh_base: usize = self.get_mesh_library().len();
4150        for raw_mesh in scene.get_meshes().iter() {
4151            let mut mesh_copy: Mesh3D = raw_mesh.clone();
4152            if let Some(local_mat_id) = mesh_copy.try_get_material_index() {
4153                mesh_copy.set_material_index(Some(local_mat_id.saturating_add(material_base)));
4154            }
4155            let lod_chain: MeshLodChain = if mesh_copy.get_indices().len() > 24 {
4156                build_qem_lod_chain(&mesh_copy, 3)
4157            } else {
4158                MeshLodChain::from_mesh(mesh_copy)
4159            };
4160            let _: usize = self.register_mesh(lod_chain);
4161        }
4162        let node_base: u32 = self.get_scene_graph().get_nodes().len() as u32;
4163        let skin_base: u32 = self.get_skins().len() as u32;
4164        let mut collection_bit_remap: Vec<u64> = Vec::new();
4165        for coll_entry in scene
4166            .get_scene_graph()
4167            .get_collections()
4168            .get_entries()
4169            .iter()
4170        {
4171            let mask_val: u64 = self
4172                .get_mut_scene_graph()
4173                .get_mut_collections()
4174                .register_collection(coll_entry.get_name());
4175            if !coll_entry.get_visible_viewport() {
4176                let _: bool = self
4177                    .get_mut_scene_graph()
4178                    .get_mut_collections()
4179                    .set_collection_visible(coll_entry.get_name(), false);
4180            }
4181            collection_bit_remap.push(mask_val);
4182        }
4183        let src_graph: &SceneGraph3D = scene.get_scene_graph();
4184        let src_nodes: &[SceneNode3D] = src_graph.get_nodes().as_slice();
4185        for (src_idx, src_node) in src_nodes.iter().enumerate() {
4186            let rebased_parent: Option<u32> = src_node
4187                .try_get_parent()
4188                .map(|parent_idx: u32| parent_idx.saturating_add(node_base));
4189            let node_label: &str = if src_node.get_name().is_empty() {
4190                BLENDER_IMPORTED_NODE_FALLBACK
4191            } else {
4192                src_node.get_name().as_str()
4193            };
4194            let mut dst_node: SceneNode3D = SceneNode3D::from_name(node_label, rebased_parent);
4195            dst_node.set_local_translation(src_node.get_local_translation());
4196            dst_node.set_local_rotation(src_node.get_local_rotation());
4197            dst_node.set_local_scale(src_node.get_local_scale());
4198            dst_node.set_visible(src_node.get_visible());
4199            dst_node.set_extras(src_node.get_extras().clone());
4200            let mut mapped_mask: u64 = 0;
4201            let raw_mask: u64 = src_node.get_collection_mask();
4202            for (bit_pos, &dst_bit) in collection_bit_remap.iter().enumerate() {
4203                if (raw_mask & (1_u64 << (bit_pos as u32))) != 0 {
4204                    mapped_mask |= dst_bit;
4205                }
4206            }
4207            dst_node.set_collection_mask(if mapped_mask == 0 { 1 } else { mapped_mask });
4208            if let Some(src_mesh_id) = src_node.try_get_mesh_id() {
4209                dst_node.set_mesh_id(Some((mesh_base as u32).saturating_add(src_mesh_id)));
4210            }
4211            if let Some(src_skin_id) = src_node.try_get_skin_id() {
4212                dst_node.set_skin_id(Some(skin_base.saturating_add(src_skin_id)));
4213            }
4214            dst_node.set_camera_id(src_node.try_get_camera_id());
4215            dst_node.set_light_id(src_node.try_get_light_id());
4216            let dst_node_id: u32 = self.get_mut_scene_graph().add_node(dst_node);
4217            let src_weights: &[f32] = src_graph.morph_weights_for_node(src_idx as u32);
4218            if !src_weights.is_empty() {
4219                self.get_mut_scene_graph()
4220                    .attach_morph_weights(dst_node_id, src_weights);
4221            }
4222            let Self {
4223                node_object_map, ..
4224            } = self;
4225            node_object_map.push(None);
4226        }
4227        let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
4228        for src_skin in scene.get_skins().iter() {
4229            let mut runtime_skin: Skin3D = Skin3D::from_imported(src_skin);
4230            for joint_node in runtime_skin.get_mut_joints().iter_mut() {
4231                *joint_node = joint_node.saturating_add(node_base);
4232            }
4233            if let Some(root_idx) = runtime_skin.try_get_skeleton_root() {
4234                runtime_skin.set_skeleton_root(Some(root_idx.saturating_add(node_base)));
4235            }
4236            self.get_mut_skins().push(runtime_skin);
4237        }
4238        let mut first_clip_added: Option<usize> = None;
4239        for src_clip in scene.get_animations().iter() {
4240            let mut rebased_clip: ImportedAnimationClip3D = src_clip.clone();
4241            for chan in rebased_clip.get_mut_channels().iter_mut() {
4242                chan.set_target_node(chan.get_target_node().saturating_add(node_base));
4243            }
4244            let clip_idx: usize = self.get_mut_animation_mixer().add_clip(rebased_clip);
4245            if first_clip_added.is_none() {
4246                first_clip_added = Some(clip_idx);
4247            }
4248        }
4249        let graph_snapshot: SceneGraph3D = self.get_scene_graph().clone();
4250        self.get_mut_animation_mixer()
4251            .capture_rest_pose(&graph_snapshot);
4252        if let Some(clip_idx) = first_clip_added
4253            && self.get_animation_mixer().get_layers().is_empty()
4254        {
4255            let _: usize = self
4256                .get_mut_animation_mixer()
4257                .push_layer(NlaLayer3D::new(clip_idx));
4258        }
4259        let mut spawned_objects: Vec<usize> = Vec::new();
4260        let total_nodes: usize = self.get_scene_graph().get_nodes().len();
4261        for node_idx in (node_base as usize)..total_nodes {
4262            let node_copy: SceneNode3D = self.get_scene_graph().get_nodes()[node_idx].clone();
4263            let world_mat: Mat4 = node_copy.get_world_matrix();
4264            let world_tr: Transform3D = Transform3D::from_matrix(world_mat);
4265            if let Some(global_mesh_id) = node_copy.try_get_mesh_id() {
4266                let mesh_usize: usize = global_mesh_id as usize;
4267                let principled_id: Option<u32> = self
4268                    .get_mesh_library()
4269                    .get(mesh_usize)
4270                    .and_then(|chain: &MeshLodChain| chain.get_levels().first())
4271                    .and_then(|mesh_ref: &Mesh3D| mesh_ref.try_get_material_index());
4272                let legacy_mat: PbrMaterial = principled_id
4273                    .and_then(|mat_idx: u32| self.get_principled_materials().get(mat_idx as usize))
4274                    .map_or_else(
4275                        || {
4276                            self.get_mesh_library()
4277                                .get(mesh_usize)
4278                                .and_then(|chain: &MeshLodChain| chain.get_levels().first())
4279                                .map_or_else(PbrMaterial::default, Mesh3D::get_material)
4280                        },
4281                        PrincipledMaterial3D::to_legacy_pbr,
4282                    );
4283                let cast_shadows: bool = node_copy.get_extras().get_cast_shadows();
4284                let obj_idx: usize = self.spawn_object(
4285                    node_copy.get_name(),
4286                    mesh_usize,
4287                    world_tr,
4288                    legacy_mat,
4289                    cast_shadows,
4290                );
4291                let skin_opt: Option<u32> = node_copy.try_get_skin_id();
4292                let is_deformable: bool =
4293                    skin_opt.is_some() || node_copy.get_morph_weight_count() > 0;
4294                if let Some(obj_mut) = self.get_mut_objects().get_mut(obj_idx) {
4295                    obj_mut.set_node_id(Some(node_idx as u32));
4296                    obj_mut.set_principled_material_id(principled_id);
4297                    obj_mut.set_skin_id(skin_opt);
4298                }
4299                if is_deformable {
4300                    let _: bool = self.set_object_dynamic(obj_idx, true);
4301                }
4302                let Self {
4303                    node_object_map, ..
4304                } = self;
4305                if let Some(slot) = node_object_map.get_mut(node_idx) {
4306                    *slot = Some(obj_idx);
4307                }
4308                spawned_objects.push(obj_idx);
4309            }
4310            if let Some(src_cam_id) = node_copy.try_get_camera_id()
4311                && let Some(imp_cam) = scene.get_cameras().get(src_cam_id as usize)
4312            {
4313                self.get_mut_scene_cameras()
4314                    .push(SceneCamera3D::from_imported(
4315                        imp_cam,
4316                        Some(node_idx as u32),
4317                        world_tr.get_position(),
4318                        world_tr.get_rotation(),
4319                    ));
4320            }
4321            if let Some(src_light_id) = node_copy.try_get_light_id()
4322                && let Some(imp_light) = scene.get_lights().get(src_light_id as usize)
4323            {
4324                let emit_dir: Vec3 = world_tr
4325                    .get_rotation()
4326                    .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
4327                    .normalize();
4328                let light_color: Vec3 = imp_light.get_color();
4329                let light_intensity: f32 = imp_light.get_intensity();
4330                match imp_light.get_kind() {
4331                    GltfLightKind::Directional => {
4332                        let mut sun_val: DirectionalLight3D = self.get_sun();
4333                        sun_val.set_direction(emit_dir.scale(-1.0).normalize());
4334                        sun_val.set_color(light_color.scale(light_intensity.max(0.05)));
4335                        self.set_sun(sun_val);
4336                    }
4337                    GltfLightKind::Point { range } => {
4338                        let resolved_range: f32 = range.unwrap_or(24.0).max(0.5);
4339                        self.get_mut_point_lights().push(PointLight3D::from_linear(
4340                            world_tr.get_position(),
4341                            light_color,
4342                            light_intensity,
4343                            resolved_range,
4344                        ));
4345                    }
4346                    GltfLightKind::Spot {
4347                        range,
4348                        inner_cone_angle,
4349                        outer_cone_angle,
4350                    } => {
4351                        let resolved_range: f32 = range.unwrap_or(32.0).max(0.5);
4352                        self.get_mut_spot_lights().push(SpotLight3D::from_linear(
4353                            world_tr.get_position(),
4354                            emit_dir,
4355                            light_color,
4356                            light_intensity,
4357                            resolved_range,
4358                            (inner_cone_angle, outer_cone_angle),
4359                        ));
4360                    }
4361                    GltfLightKind::Area { width, height } => {
4362                        self.get_mut_area_lights().push(AreaLight3D::new_rect(
4363                            world_tr.get_position(),
4364                            emit_dir,
4365                            light_color,
4366                            light_intensity,
4367                            (width, height),
4368                            28.0,
4369                        ));
4370                    }
4371                }
4372            }
4373        }
4374        let _: usize = self.update_deformed_meshes();
4375        if self.environment_ibl().is_none() {
4376            let sun_ref: DirectionalLight3D = self.get_sun();
4377            let baked_ibl: EnvironmentIbl3D = EnvironmentIbl3D::from_procedural_sky(
4378                &sun_ref,
4379                WORLD_DEFAULT_IBL_OCT_SIZE,
4380                WORLD_DEFAULT_IBL_LUT_SIZE,
4381            );
4382            self.set_environment_ibl(Some(baked_ibl));
4383        }
4384        self.set_use_agx_tonemap(true);
4385        self.set_imported_model_count(self.get_imported_model_count().saturating_add(1));
4386        self.set_bvh_dirty(true);
4387        self.set_dynamic_bvh_dirty(true);
4388        self.set_dynamic_topology_dirty(true);
4389        self.bump_world_revision();
4390        spawned_objects
4391    }
4392
4393    /// Parses binary `.glb` or `.gltf` JSON bytes and loads the resulting Blender scene directly into `World3D`.
4394    ///
4395    /// # Arguments
4396    ///
4397    /// - `&Self` - Mutable 3D world.
4398    /// - `&[u8]` - Raw `.glb` or `.gltf` bytes.
4399    ///
4400    /// # Returns
4401    ///
4402    /// - `Result<Vec<usize>, String>` - Spawned object indices or structured glTF import error.
4403    pub fn load_glb_bytes(&mut self, bytes: &[u8]) -> Result<Vec<usize>, String> {
4404        let imported: ImportedScene3D = parse_gltf_or_glb_bytes(bytes, None)?;
4405        Ok(self.load_imported_scene(&imported))
4406    }
4407
4408    /// 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.
4409    ///
4410    /// # Arguments
4411    ///
4412    /// - `&Self` - Mutable 3D world.
4413    /// - `f32` - Frame delta time in seconds.
4414    ///
4415    /// # Returns
4416    ///
4417    /// - `usize` - Count of updated scene nodes, morph channels, and deformed meshes.
4418    pub fn tick_animations(&mut self, dt_secs: f32) -> usize {
4419        let anim_updates: usize = {
4420            let Self {
4421                scene_graph,
4422                animation_mixer,
4423                ..
4424            } = self;
4425            animation_mixer.advance_and_apply(dt_secs, scene_graph)
4426        };
4427        let propagated: usize = self.get_mut_scene_graph().propagate_world_matrices();
4428        let synced: usize = self.sync_objects_from_scene_graph();
4429        let deformed: usize = self.update_deformed_meshes();
4430        let total: usize = anim_updates + propagated + synced + deformed;
4431        if total > 0 {
4432            self.set_dynamic_bvh_dirty(true);
4433            self.bump_world_revision();
4434        }
4435        total
4436    }
4437
4438    /// 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.
4439    ///
4440    /// # Returns
4441    ///
4442    /// - `usize` - Number of objects whose deformed mesh was updated.
4443    pub fn update_deformed_meshes(&mut self) -> usize {
4444        let obj_count: usize = self.get_objects().len();
4445        let Self {
4446            mesh_library,
4447            objects,
4448            scene_graph,
4449            skins,
4450            skin_scratch,
4451            deformed_meshes,
4452            ..
4453        } = self;
4454        if deformed_meshes.len() < obj_count {
4455            deformed_meshes.resize(obj_count, None);
4456        }
4457        let mut updated_count: usize = 0;
4458        for obj_idx in 0..obj_count {
4459            let obj_ref: &SceneObject3D = &objects[obj_idx];
4460            let Some(node_id) = obj_ref.try_get_node_id() else {
4461                continue;
4462            };
4463            let morph_weights: &[f32] = scene_graph.morph_weights_for_node(node_id);
4464            let skin_opt: Option<u32> = obj_ref.try_get_skin_id();
4465            if skin_opt.is_none() && morph_weights.is_empty() {
4466                continue;
4467            }
4468            let Some(base_mesh) = mesh_library
4469                .get(obj_ref.get_mesh_id())
4470                .and_then(|chain: &MeshLodChain| chain.get_levels().first())
4471            else {
4472                continue;
4473            };
4474            let mesh_world: Mat4 = scene_graph.get_nodes().get(node_id as usize).map_or_else(
4475                || obj_ref.get_transform().to_mat4(),
4476                SceneNode3D::get_world_matrix,
4477            );
4478            let did_deform: bool = if let Some(skin_id) = skin_opt
4479                && let Some(skin_ref) = skins.get(skin_id as usize)
4480            {
4481                skin_ref.deform_mesh_into(
4482                    base_mesh,
4483                    morph_weights,
4484                    mesh_world,
4485                    scene_graph,
4486                    skin_scratch,
4487                )
4488            } else {
4489                let morphed: bool = apply_morph_targets_into(
4490                    base_mesh.get_vertices().as_slice(),
4491                    base_mesh.get_morph_targets().as_slice(),
4492                    morph_weights,
4493                    skin_scratch.get_mut_skinned_vertices(),
4494                );
4495                morphed
4496            };
4497            if did_deform {
4498                let deformed_verts: &[Vertex3D] = skin_scratch.get_skinned_vertices().as_slice();
4499                let mut local_bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
4500                for vert_item in deformed_verts.iter() {
4501                    local_bounds.expand_point(vert_item.get_position());
4502                }
4503                let target_slot: &mut Option<Mesh3D> = &mut deformed_meshes[obj_idx];
4504                if let Some(existing_mesh) = target_slot.as_mut() {
4505                    let dst_verts: &mut Vec<Vertex3D> = existing_mesh.get_mut_vertices();
4506                    dst_verts.clear();
4507                    dst_verts.extend_from_slice(deformed_verts);
4508                    existing_mesh.set_bounds(local_bounds);
4509                } else {
4510                    let mut cloned_mesh: Mesh3D = base_mesh.clone();
4511                    let dst_verts: &mut Vec<Vertex3D> = cloned_mesh.get_mut_vertices();
4512                    dst_verts.clear();
4513                    dst_verts.extend_from_slice(deformed_verts);
4514                    cloned_mesh.set_bounds(local_bounds);
4515                    *target_slot = Some(cloned_mesh);
4516                }
4517                if let Some(deformed_ref) = target_slot.as_ref() {
4518                    let world_tr: Transform3D = objects[obj_idx].get_transform();
4519                    objects[obj_idx]
4520                        .set_world_bounds(world_tr.transform_bounds(deformed_ref.get_bounds()));
4521                }
4522                updated_count += 1;
4523            }
4524        }
4525        updated_count
4526    }
4527
4528    /// Applies an incremental Blender Live-Link delta in place without resetting camera state or rebuilding unrelated geometry.
4529    ///
4530    /// # Arguments
4531    ///
4532    /// - `&Self` - Mutable 3D world.
4533    /// - `&BlenderLiveDelta3D` - Structured Live-Link delta command.
4534    ///
4535    /// # Returns
4536    ///
4537    /// - `bool` - `true` when at least one scene entity was mutated.
4538    pub fn apply_live_delta(&mut self, delta: &BlenderLiveDelta3D) -> bool {
4539        match delta {
4540            BlenderLiveDelta3D::NodeTransform {
4541                node_name,
4542                translation,
4543                rotation,
4544                scale,
4545                blender_z_up,
4546            } => {
4547                let found_id: Option<u32> = self
4548                    .get_scene_graph()
4549                    .get_nodes()
4550                    .iter()
4551                    .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
4552                    .map(|idx: usize| idx as u32);
4553                let Some(node_id) = found_id else {
4554                    return false;
4555                };
4556                let raw_t: Vec3 = Vec3::from_array(*translation);
4557                let raw_r: Quat = Quat::from_array(*rotation).normalize();
4558                let raw_s: Vec3 = Vec3::from_array(*scale);
4559                let (dst_t, dst_r, dst_s): (Vec3, Quat, Vec3) = if *blender_z_up {
4560                    (
4561                        raw_t.blender_z_up_to_y_up(),
4562                        raw_r.blender_z_up_to_y_up(),
4563                        Vec3::new(raw_s.get_x(), raw_s.get_z(), raw_s.get_y()),
4564                    )
4565                } else {
4566                    (raw_t, raw_r, raw_s)
4567                };
4568                self.get_mut_scene_graph()
4569                    .set_local_trs(node_id, dst_t, dst_r, dst_s);
4570                let _: usize = self.get_mut_scene_graph().propagate_world_matrices();
4571                let _: usize = self.sync_objects_from_scene_graph();
4572                let _: usize = self.update_deformed_meshes();
4573                self.set_dynamic_bvh_dirty(true);
4574                self.bump_world_revision();
4575                true
4576            }
4577            BlenderLiveDelta3D::MaterialParams {
4578                material_name,
4579                base_color_factor,
4580                metallic_factor,
4581                roughness_factor,
4582                clearcoat_factor,
4583                clearcoat_roughness_factor,
4584                sheen_color_factor,
4585                sheen_roughness_factor,
4586                emissive_factor,
4587                emissive_strength,
4588                transmission_factor,
4589                ior,
4590            } => {
4591                let found_idx: Option<usize> = self
4592                    .get_principled_materials()
4593                    .iter()
4594                    .position(|mat_ref: &PrincipledMaterial3D| mat_ref.get_name() == material_name);
4595                let Some(mat_idx) = found_idx else {
4596                    return false;
4597                };
4598                let updated_legacy: PbrMaterial = {
4599                    let mat_mut: &mut PrincipledMaterial3D =
4600                        &mut self.get_mut_principled_materials()[mat_idx];
4601                    if let Some(val) = *base_color_factor {
4602                        mat_mut.set_base_color_factor(val);
4603                    }
4604                    if let Some(val) = *metallic_factor {
4605                        mat_mut.set_metallic_factor(val.clamp(0.0, 1.0));
4606                    }
4607                    if let Some(val) = *roughness_factor {
4608                        mat_mut.set_roughness_factor(val.clamp(0.04, 1.0));
4609                    }
4610                    if let Some(val) = *clearcoat_factor {
4611                        mat_mut.set_clearcoat_factor(val.clamp(0.0, 1.0));
4612                    }
4613                    if let Some(val) = *clearcoat_roughness_factor {
4614                        mat_mut.set_clearcoat_roughness_factor(val.clamp(0.0, 1.0));
4615                    }
4616                    if let Some(val) = *sheen_color_factor {
4617                        mat_mut.set_sheen_color_factor(val);
4618                    }
4619                    if let Some(val) = *sheen_roughness_factor {
4620                        mat_mut.set_sheen_roughness_factor(val.clamp(0.0, 1.0));
4621                    }
4622                    if let Some(val) = *emissive_factor {
4623                        mat_mut.set_emissive_factor(val);
4624                    }
4625                    if let Some(val) = *emissive_strength {
4626                        mat_mut.set_emissive_strength(val.max(0.0));
4627                    }
4628                    if let Some(val) = *transmission_factor {
4629                        mat_mut.set_transmission_factor(val.clamp(0.0, 1.0));
4630                    }
4631                    if let Some(val) = *ior {
4632                        mat_mut.set_ior(val.clamp(1.0, 3.0));
4633                    }
4634                    mat_mut.to_legacy_pbr()
4635                };
4636                let mat_u32: u32 = mat_idx as u32;
4637                for obj_mut in self.get_mut_objects().iter_mut() {
4638                    if obj_mut.try_get_principled_material_id() == Some(mat_u32) {
4639                        obj_mut.set_material(updated_legacy);
4640                    }
4641                }
4642                self.bump_world_revision();
4643                true
4644            }
4645            BlenderLiveDelta3D::MorphWeights { node_name, weights } => {
4646                let found_id: Option<u32> = self
4647                    .get_scene_graph()
4648                    .get_nodes()
4649                    .iter()
4650                    .position(|node_ref: &SceneNode3D| node_ref.get_name() == node_name)
4651                    .map(|idx: usize| idx as u32);
4652                let Some(node_id) = found_id else {
4653                    return false;
4654                };
4655                self.get_mut_scene_graph()
4656                    .update_morph_weights(node_id, weights.as_slice());
4657                let _: usize = self.update_deformed_meshes();
4658                self.set_dynamic_bvh_dirty(true);
4659                self.bump_world_revision();
4660                true
4661            }
4662            BlenderLiveDelta3D::LightUpdate {
4663                light_index,
4664                color,
4665                intensity,
4666                position,
4667                direction,
4668            } => {
4669                let mut changed: bool = false;
4670                if let Some(point_mut) = self.get_mut_point_lights().get_mut(*light_index) {
4671                    if let Some(col_arr) = *color {
4672                        point_mut.set_color(Vec3::from_array(col_arr));
4673                    }
4674                    if let Some(int_val) = *intensity {
4675                        point_mut.set_intensity(int_val.max(0.0));
4676                    }
4677                    if let Some(pos_arr) = *position {
4678                        point_mut.set_position(Vec3::from_array(pos_arr));
4679                    }
4680                    changed = true;
4681                } else if let Some(area_mut) = self.get_mut_area_lights().get_mut(*light_index) {
4682                    if let Some(col_arr) = *color {
4683                        area_mut.set_color(Vec3::from_array(col_arr));
4684                    }
4685                    if let Some(int_val) = *intensity {
4686                        area_mut.set_intensity(int_val.max(0.0));
4687                    }
4688                    if let Some(pos_arr) = *position {
4689                        area_mut.set_position(Vec3::from_array(pos_arr));
4690                    }
4691                    if let Some(dir_arr) = *direction {
4692                        area_mut.set_direction(Vec3::from_array(dir_arr).normalize());
4693                    }
4694                    changed = true;
4695                }
4696                if changed {
4697                    self.bump_world_revision();
4698                }
4699                changed
4700            }
4701            BlenderLiveDelta3D::CameraUpdate {
4702                position,
4703                yaw,
4704                pitch,
4705                fov_deg,
4706            } => {
4707                let mut cam: Camera3D = self.get_camera();
4708                cam.set_position(Vec3::from_array(*position));
4709                cam.set_yaw(*yaw);
4710                cam.set_pitch(pitch.clamp(-1.4, 1.4));
4711                cam.set_fov_deg(fov_deg.clamp(12.0, 120.0));
4712                self.set_camera(cam);
4713                self.bump_world_revision();
4714                true
4715            }
4716            BlenderLiveDelta3D::CollectionVisibility {
4717                collection_name,
4718                visible,
4719            } => self.set_collection_visible(collection_name, *visible),
4720            BlenderLiveDelta3D::EnvironmentUpdate {
4721                rotation_y_rad,
4722                intensity,
4723            } => {
4724                let Self {
4725                    environment_ibl, ..
4726                } = self;
4727                if let Some(ibl_mut) = environment_ibl.as_mut() {
4728                    ibl_mut.set_rotation_y_rad(*rotation_y_rad);
4729                    ibl_mut.set_intensity(intensity.max(0.0));
4730                    self.bump_world_revision();
4731                    true
4732                } else {
4733                    false
4734                }
4735            }
4736        }
4737    }
4738
4739    /// Parses a JSON Live-Link delta payload and applies it in place to this world.
4740    ///
4741    /// # Arguments
4742    ///
4743    /// - `&Self` - Mutable 3D world.
4744    /// - `&str` - JSON Live-Link delta string.
4745    ///
4746    /// # Returns
4747    ///
4748    /// - `Result<bool, String>` - `Ok(applied)` on valid payload, or parse error string.
4749    pub fn apply_live_delta_json(&mut self, json_payload: &str) -> Result<bool, String> {
4750        let root: Value =
4751            from_str::<Value>(json_payload).map_err(|_| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
4752        let kind_str: &str = root
4753            .get(LIVE_KEY_KIND)
4754            .and_then(Value::as_str)
4755            .ok_or_else(|| ERR_LIVE_DELTA_UNKNOWN_KIND.to_string())?;
4756        let delta: BlenderLiveDelta3D = match kind_str {
4757            LIVE_DELTA_KIND_TRANSFORM => BlenderLiveDelta3D::NodeTransform {
4758                node_name: root
4759                    .get(LIVE_KEY_NODE_NAME)
4760                    .and_then(Value::as_str)
4761                    .unwrap_or_default()
4762                    .to_string(),
4763                translation: Self::json_f32_array3(root.get(LIVE_KEY_TRANSLATION))
4764                    .unwrap_or([0.0, 0.0, 0.0]),
4765                rotation: Self::json_f32_array4(root.get(LIVE_KEY_ROTATION))
4766                    .unwrap_or([0.0, 0.0, 0.0, 1.0]),
4767                scale: Self::json_f32_array3(root.get(LIVE_KEY_SCALE)).unwrap_or([1.0, 1.0, 1.0]),
4768                blender_z_up: root
4769                    .get(LIVE_KEY_BLENDER_Z_UP)
4770                    .and_then(Value::as_bool)
4771                    .unwrap_or(false),
4772            },
4773            LIVE_DELTA_KIND_MATERIAL => BlenderLiveDelta3D::MaterialParams {
4774                material_name: root
4775                    .get(LIVE_KEY_MATERIAL_NAME)
4776                    .and_then(Value::as_str)
4777                    .unwrap_or_default()
4778                    .to_string(),
4779                base_color_factor: Self::json_f32_array4(root.get(LIVE_KEY_BASE_COLOR)),
4780                metallic_factor: root
4781                    .get(LIVE_KEY_METALLIC)
4782                    .and_then(Value::as_f64)
4783                    .map(|val: f64| val as f32),
4784                roughness_factor: root
4785                    .get(LIVE_KEY_ROUGHNESS)
4786                    .and_then(Value::as_f64)
4787                    .map(|val: f64| val as f32),
4788                clearcoat_factor: root
4789                    .get(LIVE_KEY_CLEARCOAT)
4790                    .and_then(Value::as_f64)
4791                    .map(|val: f64| val as f32),
4792                clearcoat_roughness_factor: root
4793                    .get(LIVE_KEY_CLEARCOAT_ROUGHNESS)
4794                    .and_then(Value::as_f64)
4795                    .map(|val: f64| val as f32),
4796                sheen_color_factor: Self::json_f32_array3(root.get(LIVE_KEY_SHEEN_COLOR)),
4797                sheen_roughness_factor: root
4798                    .get(LIVE_KEY_SHEEN_ROUGHNESS)
4799                    .and_then(Value::as_f64)
4800                    .map(|val: f64| val as f32),
4801                emissive_factor: Self::json_f32_array3(root.get(LIVE_KEY_EMISSIVE)),
4802                emissive_strength: root
4803                    .get(LIVE_KEY_EMISSIVE_STRENGTH)
4804                    .and_then(Value::as_f64)
4805                    .map(|val: f64| val as f32),
4806                transmission_factor: root
4807                    .get(LIVE_KEY_TRANSMISSION)
4808                    .and_then(Value::as_f64)
4809                    .map(|val: f64| val as f32),
4810                ior: root
4811                    .get("ior")
4812                    .and_then(Value::as_f64)
4813                    .map(|val: f64| val as f32),
4814            },
4815            LIVE_DELTA_KIND_MORPH => {
4816                let parsed_weights: Vec<f32> = root
4817                    .get(LIVE_KEY_WEIGHTS)
4818                    .and_then(Value::as_array)
4819                    .map(|items: &Vec<Value>| {
4820                        items
4821                            .iter()
4822                            .filter_map(|elem: &Value| elem.as_f64().map(|val: f64| val as f32))
4823                            .collect()
4824                    })
4825                    .unwrap_or_default();
4826                BlenderLiveDelta3D::MorphWeights {
4827                    node_name: root
4828                        .get(LIVE_KEY_NODE_NAME)
4829                        .and_then(Value::as_str)
4830                        .unwrap_or_default()
4831                        .to_string(),
4832                    weights: parsed_weights,
4833                }
4834            }
4835            LIVE_DELTA_KIND_LIGHT => BlenderLiveDelta3D::LightUpdate {
4836                light_index: root
4837                    .get(LIVE_KEY_LIGHT_INDEX)
4838                    .and_then(Value::as_u64)
4839                    .unwrap_or(0) as usize,
4840                color: Self::json_f32_array3(root.get(LIVE_KEY_COLOR)),
4841                intensity: root
4842                    .get(LIVE_KEY_INTENSITY)
4843                    .and_then(Value::as_f64)
4844                    .map(|val: f64| val as f32),
4845                position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION)),
4846                direction: Self::json_f32_array3(root.get(LIVE_KEY_DIRECTION)),
4847            },
4848            LIVE_DELTA_KIND_CAMERA => BlenderLiveDelta3D::CameraUpdate {
4849                position: Self::json_f32_array3(root.get(LIVE_KEY_POSITION))
4850                    .unwrap_or([0.0, 2.0, 6.0]),
4851                yaw: root
4852                    .get("yaw")
4853                    .and_then(Value::as_f64)
4854                    .map_or(0.0, |val: f64| val as f32),
4855                pitch: root
4856                    .get(LIVE_KEY_PITCH)
4857                    .and_then(Value::as_f64)
4858                    .map_or(0.0, |val: f64| val as f32),
4859                fov_deg: root
4860                    .get(LIVE_KEY_FOV_DEG)
4861                    .and_then(Value::as_f64)
4862                    .map_or(60.0, |val: f64| val as f32),
4863            },
4864            LIVE_DELTA_KIND_COLLECTION => BlenderLiveDelta3D::CollectionVisibility {
4865                collection_name: root
4866                    .get(LIVE_KEY_COLLECTION_NAME)
4867                    .and_then(Value::as_str)
4868                    .unwrap_or_default()
4869                    .to_string(),
4870                visible: root
4871                    .get(LIVE_KEY_VISIBLE)
4872                    .and_then(Value::as_bool)
4873                    .unwrap_or(true),
4874            },
4875            LIVE_DELTA_KIND_ENVIRONMENT => BlenderLiveDelta3D::EnvironmentUpdate {
4876                rotation_y_rad: root
4877                    .get(LIVE_KEY_ROTATION_Y_RAD)
4878                    .and_then(Value::as_f64)
4879                    .map_or(0.0, |val: f64| val as f32),
4880                intensity: root
4881                    .get(LIVE_KEY_INTENSITY)
4882                    .and_then(Value::as_f64)
4883                    .map_or(1.0, |val: f64| val as f32),
4884            },
4885            _ => return Err(ERR_LIVE_DELTA_UNKNOWN_KIND.to_string()),
4886        };
4887        Ok(self.apply_live_delta(&delta))
4888    }
4889
4890    /// Synchronizes linked `SceneObject3D` and `SceneCamera3D` transforms from `scene_graph` propagated world matrices.
4891    ///
4892    /// # Returns
4893    ///
4894    /// - `usize` - Number of linked objects or cameras whose transforms were synchronized.
4895    fn sync_objects_from_scene_graph(&mut self) -> usize {
4896        let Self {
4897            mesh_library,
4898            objects,
4899            scene_graph,
4900            scene_cameras,
4901            node_object_map,
4902            deformed_meshes,
4903            ..
4904        } = self;
4905        let nodes: &[SceneNode3D] = scene_graph.get_nodes().as_slice();
4906        let mut synced_count: usize = 0;
4907        for (node_idx, obj_slot) in node_object_map.iter().enumerate() {
4908            let Some(obj_idx) = *obj_slot else {
4909                continue;
4910            };
4911            if node_idx >= nodes.len() || obj_idx >= objects.len() {
4912                continue;
4913            }
4914            let world_tr: Transform3D =
4915                Transform3D::from_matrix(nodes[node_idx].get_world_matrix());
4916            if objects[obj_idx].get_transform() != world_tr {
4917                objects[obj_idx].set_transform(world_tr);
4918                let local_bounds: AxisAlignedBox3D = deformed_meshes
4919                    .get(obj_idx)
4920                    .and_then(Option::as_ref)
4921                    .map(Mesh3D::get_bounds)
4922                    .or_else(|| {
4923                        mesh_library
4924                            .get(objects[obj_idx].get_mesh_id())
4925                            .and_then(|chain: &MeshLodChain| chain.get_levels().first())
4926                            .map(Mesh3D::get_bounds)
4927                    })
4928                    .unwrap_or_else(|| AxisAlignedBox3D::new(Vec3::splat(-1.0), Vec3::splat(1.0)));
4929                objects[obj_idx].set_world_bounds(world_tr.transform_bounds(local_bounds));
4930                synced_count += 1;
4931            }
4932        }
4933        for cam_mut in scene_cameras.iter_mut() {
4934            if let Some(node_id) = cam_mut.try_get_node_id()
4935                && let Some(node_ref) = nodes.get(node_id as usize)
4936            {
4937                let (pos_val, rot_val, _scale_val): (Vec3, Quat, Vec3) =
4938                    node_ref.get_world_matrix().decompose_trs();
4939                cam_mut.set_position(pos_val);
4940                cam_mut.set_rotation(rot_val);
4941                synced_count += 1;
4942            }
4943        }
4944        synced_count
4945    }
4946
4947    /// Offsets all texture indices inside `material` by `texture_base` when merging an imported scene.
4948    ///
4949    /// # Arguments
4950    ///
4951    /// - `&mut PrincipledMaterial3D` - Mutable material whose texture slots are rebased.
4952    /// - `u32` - Texture pool offset.
4953    fn rebase_material_textures(material: &mut PrincipledMaterial3D, texture_base: u32) {
4954        if texture_base == 0 {
4955            return;
4956        }
4957        let shift_slot: fn(Option<TextureSlot3D>, u32) -> Option<TextureSlot3D> =
4958            |slot_opt: Option<TextureSlot3D>, base_val: u32| -> Option<TextureSlot3D> {
4959                slot_opt.map(|mut slot: TextureSlot3D| {
4960                    slot.set_texture_index(slot.get_texture_index().saturating_add(base_val));
4961                    slot
4962                })
4963            };
4964        material.set_base_color_texture(shift_slot(
4965            material.try_get_base_color_texture(),
4966            texture_base,
4967        ));
4968        material.set_metallic_roughness_texture(shift_slot(
4969            material.try_get_metallic_roughness_texture(),
4970            texture_base,
4971        ));
4972        material.set_normal_texture(shift_slot(material.try_get_normal_texture(), texture_base));
4973        material.set_occlusion_texture(shift_slot(
4974            material.try_get_occlusion_texture(),
4975            texture_base,
4976        ));
4977        material.set_emissive_texture(shift_slot(
4978            material.try_get_emissive_texture(),
4979            texture_base,
4980        ));
4981        material.set_specular_texture(shift_slot(
4982            material.try_get_specular_texture(),
4983            texture_base,
4984        ));
4985        material.set_specular_color_texture(shift_slot(
4986            material.try_get_specular_color_texture(),
4987            texture_base,
4988        ));
4989        material.set_clearcoat_texture(shift_slot(
4990            material.try_get_clearcoat_texture(),
4991            texture_base,
4992        ));
4993        material.set_clearcoat_roughness_texture(shift_slot(
4994            material.try_get_clearcoat_roughness_texture(),
4995            texture_base,
4996        ));
4997        material.set_clearcoat_normal_texture(shift_slot(
4998            material.try_get_clearcoat_normal_texture(),
4999            texture_base,
5000        ));
5001        material.set_transmission_texture(shift_slot(
5002            material.try_get_transmission_texture(),
5003            texture_base,
5004        ));
5005        material.set_sheen_color_texture(shift_slot(
5006            material.try_get_sheen_color_texture(),
5007            texture_base,
5008        ));
5009        material.set_sheen_roughness_texture(shift_slot(
5010            material.try_get_sheen_roughness_texture(),
5011            texture_base,
5012        ));
5013    }
5014
5015    /// Extracts a 3-element `f32` array from an optional JSON array value.
5016    ///
5017    /// # Arguments
5018    ///
5019    /// - `Option<&Value>` - Optional JSON node.
5020    ///
5021    /// # Returns
5022    ///
5023    /// - `Option<[f32; 3]>` - Decoded array when three numeric entries exist.
5024    #[must_use]
5025    fn json_f32_array3(val: Option<&Value>) -> Option<[f32; 3]> {
5026        let arr: &Vec<Value> = val?.as_array()?;
5027        if arr.len() < 3 {
5028            return None;
5029        }
5030        Some([
5031            arr[0].as_f64()? as f32,
5032            arr[1].as_f64()? as f32,
5033            arr[2].as_f64()? as f32,
5034        ])
5035    }
5036
5037    /// Extracts a 4-element `f32` array from an optional JSON array value.
5038    ///
5039    /// # Arguments
5040    ///
5041    /// - `Option<&Value>` - Optional JSON node.
5042    ///
5043    /// # Returns
5044    ///
5045    /// - `Option<[f32; 4]>` - Decoded array when four numeric entries exist.
5046    #[must_use]
5047    fn json_f32_array4(val: Option<&Value>) -> Option<[f32; 4]> {
5048        let arr: &Vec<Value> = val?.as_array()?;
5049        if arr.len() < 4 {
5050            return None;
5051        }
5052        Some([
5053            arr[0].as_f64()? as f32,
5054            arr[1].as_f64()? as f32,
5055            arr[2].as_f64()? as f32,
5056            arr[3].as_f64()? as f32,
5057        ])
5058    }
5059
5060    /// Flattens every registered `LOD0` prototype mesh in `mesh_library` into one resident GPU vertex buffer and per-mesh `(vertex_start, vertex_count)` table.
5061    ///
5062    /// # Arguments
5063    ///
5064    /// - `&Self` - World reference.
5065    /// - `u64` - Monotonic revision tag attached to the built buffer for VRAM upload caching.
5066    ///
5067    /// # Returns
5068    ///
5069    /// - `(Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>)` - Shared static GPU vertex buffer and per-mesh range table.
5070    #[must_use]
5071    pub fn build_gpu_mesh_buffer(
5072        &self,
5073        revision: u64,
5074    ) -> (Arc<GpuWorld3dMeshBuffer>, Vec<(u32, u32)>) {
5075        let mut vertices: Vec<GpuWorld3dVertex> = Vec::new();
5076        let mut ranges: Vec<(u32, u32)> = Vec::with_capacity(self.get_mesh_library().len());
5077        for chain in self.get_mesh_library() {
5078            let start_idx: u32 = vertices.len() as u32;
5079            if let Some(mesh) = chain.get_levels().first() {
5080                let mesh_verts: &[Vertex3D] = mesh.get_vertices().as_slice();
5081                let tri_mats: &[u16] = mesh.get_tri_materials().as_slice();
5082                let sub_mats: &[PbrMaterial] = mesh.get_sub_materials().as_slice();
5083                vertices.reserve(mesh.get_indices().len() * 3);
5084                for (tri_idx, &[i0, i1, i2]) in mesh.get_indices().iter().enumerate() {
5085                    let (Some(v0), Some(v1), Some(v2)) = (
5086                        mesh_verts.get(i0 as usize),
5087                        mesh_verts.get(i1 as usize),
5088                        mesh_verts.get(i2 as usize),
5089                    ) else {
5090                        continue;
5091                    };
5092                    let mat_slot: usize = tri_mats.get(tri_idx).copied().unwrap_or(0) as usize;
5093                    let color_submat: [f32; 4] = if mat_slot > 0
5094                        && let Some(sub_mat) = sub_mats.get(mat_slot - 1)
5095                    {
5096                        let base_c: Vec3 = sub_mat.get_base_color();
5097                        let em_c: Vec3 = sub_mat.get_emissive();
5098                        if em_c.length_sq() > 0.01 {
5099                            [
5100                                base_c.get_x() + em_c.get_x() * 1.4,
5101                                base_c.get_y() + em_c.get_y() * 1.4,
5102                                base_c.get_z() + em_c.get_z() * 1.4,
5103                                2.0,
5104                            ]
5105                        } else {
5106                            [base_c.get_x(), base_c.get_y(), base_c.get_z(), 1.0]
5107                        }
5108                    } else {
5109                        [1.0, 1.0, 1.0, 0.0]
5110                    };
5111                    for vert in [v0, v1, v2] {
5112                        let pos: Vec3 = vert.get_position();
5113                        let nrm: Vec3 = vert.get_normal();
5114                        vertices.push(GpuWorld3dVertex::new(
5115                            [pos.get_x(), pos.get_y(), pos.get_z(), 1.0],
5116                            [nrm.get_x(), nrm.get_y(), nrm.get_z(), 0.0],
5117                            color_submat,
5118                        ));
5119                    }
5120                }
5121            }
5122            let vert_count: u32 = (vertices.len() as u32).saturating_sub(start_idx);
5123            ranges.push((start_idx, vert_count));
5124        }
5125        (
5126            Arc::new(GpuWorld3dMeshBuffer { revision, vertices }),
5127            ranges,
5128        )
5129    }
5130
5131    /// 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.
5132    ///
5133    /// # Arguments
5134    ///
5135    /// - `&Self` - World reference.
5136    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
5137    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
5138    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
5139    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
5140    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
5141    /// - `(&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass)` - Persistent flat scratch arena and destination scene pass reused across frames.
5142    fn populate_gpu_scene_pass_with_scratch(
5143        &self,
5144        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
5145        alpha: f32,
5146        viewport: (u32, u32),
5147        quality: &RenderQualityConfig,
5148        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
5149        buffers: (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass),
5150    ) {
5151        let (scratch, out): (&mut World3dGpuPassScratch, &mut GpuWorld3dScenePass) = buffers;
5152        let (target_width, target_height): (u32, u32) = viewport;
5153        let (mesh_buffer, mesh_ranges): (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]) = mesh_cache;
5154        let blend_alpha: f32 = alpha.clamp(0.0, 1.0);
5155        let prev_snap: &World3DSnapshot = snapshots.get_prev_state();
5156        let curr_snap: &World3DSnapshot = snapshots.get_curr_state();
5157        let mut interp_cam: Camera3D = if curr_snap.get_camera_cut() {
5158            curr_snap.get_camera()
5159        } else {
5160            prev_snap
5161                .get_camera()
5162                .lerp(curr_snap.get_camera(), blend_alpha)
5163        };
5164        let aspect: f32 = (target_width.max(1) as f32) / (target_height.max(1) as f32);
5165        if aspect > 3.5 {
5166            let pull_back: f32 = ((aspect - 3.5) * 0.42).min(1.6);
5167            let shifted_pos: Vec3 = interp_cam
5168                .get_position()
5169                .sub(interp_cam.forward().scale(pull_back));
5170            interp_cam.set_position(shifted_pos);
5171        }
5172        let view_proj_mat: Mat4 = if let Some(cam_idx) = self.active_scene_camera_index()
5173            && let Some(scene_cam) = self.get_scene_cameras().get(cam_idx)
5174        {
5175            scene_cam.view_projection(aspect)
5176        } else {
5177            interp_cam.view_projection(aspect)
5178        };
5179        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj_mat);
5180        let cam_pos: Vec3 = interp_cam.get_position();
5181        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
5182        let frustum_on: bool = quality.get_frustum_culling();
5183        let obj_len: usize = self.get_objects().len();
5184        if scratch.dynamic_pose_epochs.len() < obj_len {
5185            scratch.dynamic_pose_epochs.resize(obj_len, 0);
5186            scratch
5187                .dynamic_pose_transforms
5188                .resize(obj_len, Transform3D::default());
5189        }
5190        let next_epoch: u32 = scratch.current_epoch.wrapping_add(1);
5191        let active_epoch: u32 = if next_epoch == 0 {
5192            scratch.dynamic_pose_epochs.fill(0);
5193            1
5194        } else {
5195            next_epoch
5196        };
5197        scratch.current_epoch = active_epoch;
5198        let prev_objs: &[ObjectPose3D] = prev_snap.get_objects().as_slice();
5199        let next_objs: &[ObjectPose3D] = curr_snap.get_objects().as_slice();
5200        for (slot_idx, curr) in next_objs.iter().copied().enumerate() {
5201            let obj_idx: usize = curr.get_object_index();
5202            if obj_idx >= obj_len {
5203                continue;
5204            }
5205            let mut blended_tr: Transform3D = curr.get_transform();
5206            if curr.get_visible()
5207                && let Some(prev) = prev_objs.get(slot_idx).copied()
5208            {
5209                let continuous: bool = prev.get_visible()
5210                    && prev.get_object_index() == obj_idx
5211                    && prev.get_teleport_epoch() == curr.get_teleport_epoch();
5212                if continuous {
5213                    blended_tr = prev
5214                        .get_transform()
5215                        .lerp_shortest_angle(curr.get_transform(), blend_alpha);
5216                }
5217            }
5218            scratch.dynamic_pose_epochs[obj_idx] = active_epoch;
5219            scratch.dynamic_pose_transforms[obj_idx] = blended_tr;
5220        }
5221        let mesh_len: usize = mesh_ranges.len();
5222        if scratch.mesh_counts.len() < mesh_len {
5223            scratch.mesh_counts.resize(mesh_len, 0);
5224            scratch.mesh_cursors.resize(mesh_len, 0);
5225        }
5226        scratch.mesh_counts[..mesh_len].fill(0);
5227        scratch.visible_scratch.clear();
5228        let principled_mats: &[PrincipledMaterial3D] = self.get_principled_materials().as_slice();
5229        let mesh_lib: &[MeshLodChain] = self.get_mesh_library().as_slice();
5230        for (obj_idx, obj) in self.get_objects().iter().enumerate() {
5231            if !self.is_object_visible(obj_idx) {
5232                continue;
5233            }
5234            let mesh_id: usize = obj.get_mesh_id();
5235            let Some(&(_, vert_count)) = mesh_ranges.get(mesh_id) else {
5236                continue;
5237            };
5238            if vert_count == 0 {
5239                continue;
5240            }
5241            let mut tr: Transform3D = obj.get_transform();
5242            let mut world_bounds: AxisAlignedBox3D = obj.get_world_bounds();
5243            if scratch.dynamic_pose_epochs[obj_idx] == active_epoch {
5244                tr = scratch.dynamic_pose_transforms[obj_idx];
5245                if let Some(chain) = mesh_lib.get(mesh_id)
5246                    && let Some(mesh0) = chain.get_levels().first()
5247                {
5248                    world_bounds = tr.transform_bounds(mesh0.get_bounds());
5249                }
5250            }
5251            let dist_sq: f32 = world_bounds.center().sub(cam_pos).length_sq();
5252            let radius: f32 = world_bounds.get_max().sub(world_bounds.get_min()).length() * 0.5;
5253            if dist_sq > draw_dist_sq + radius * radius * 4.0 {
5254                continue;
5255            }
5256            if frustum_on && !frustum.intersects_bounds(&world_bounds) {
5257                continue;
5258            }
5259            let mat: PbrMaterial = obj.get_material();
5260            let (albedo, metallic, roughness, emissive): (Vec3, f32, f32, Vec3) = if let Some(pm_id) =
5261                obj.try_get_principled_material_id()
5262                && let Some(pm) = principled_mats.get(pm_id as usize)
5263            {
5264                let bc: [f32; 4] = pm.get_base_color_factor();
5265                let em: [f32; 3] = pm.get_emissive_factor();
5266                let em_str: f32 = pm.get_emissive_strength();
5267                (
5268                    Vec3::new(bc[0], bc[1], bc[2]),
5269                    pm.get_metallic_factor(),
5270                    pm.get_roughness_factor(),
5271                    Vec3::new(em[0] * em_str, em[1] * em_str, em[2] * em_str),
5272                )
5273            } else {
5274                (
5275                    mat.get_base_color(),
5276                    mat.get_metallic(),
5277                    mat.get_roughness(),
5278                    mat.get_emissive(),
5279                )
5280            };
5281            let mut model_elems: [f32; 16] = tr.to_mat4().get_elements();
5282            model_elems[15] = match mat.get_surface_detail() {
5283                SurfaceDetailMode::None => 0.0,
5284                SurfaceDetailMode::RoadSurface => 1.0,
5285                SurfaceDetailMode::ArchitecturalFacade => 2.0,
5286                SurfaceDetailMode::OceanWater => 3.0,
5287            };
5288            scratch.mesh_counts[mesh_id] = scratch.mesh_counts[mesh_id].saturating_add(1);
5289            scratch.visible_scratch.push((
5290                mesh_id as u32,
5291                GpuWorld3dInstance::new(
5292                    model_elems,
5293                    [
5294                        albedo.get_x(),
5295                        albedo.get_y(),
5296                        albedo.get_z(),
5297                        metallic.clamp(0.0, 1.0),
5298                    ],
5299                    [
5300                        emissive.get_x(),
5301                        emissive.get_y(),
5302                        emissive.get_z(),
5303                        roughness.clamp(0.05, 1.0),
5304                    ],
5305                ),
5306            ));
5307        }
5308        let total_instances: usize = scratch.visible_scratch.len();
5309        out.draw_batches.clear();
5310        let mut cursor: u32 = 0;
5311        for (mesh_id, &(vertex_start, vertex_count)) in mesh_ranges.iter().enumerate() {
5312            let count: u32 = scratch.mesh_counts[mesh_id];
5313            scratch.mesh_cursors[mesh_id] = cursor;
5314            if count == 0 {
5315                continue;
5316            }
5317            out.draw_batches.push(GpuWorld3dMeshRange::new(
5318                vertex_start,
5319                vertex_count,
5320                cursor,
5321                count,
5322            ));
5323            cursor = cursor.saturating_add(count);
5324        }
5325        out.instances
5326            .resize(total_instances, GpuWorld3dInstance::default());
5327        for &(mesh_id_u32, inst) in scratch.visible_scratch.iter() {
5328            let mesh_id: usize = mesh_id_u32 as usize;
5329            let dst_idx: usize = scratch.mesh_cursors[mesh_id] as usize;
5330            scratch.mesh_cursors[mesh_id] = scratch.mesh_cursors[mesh_id].saturating_add(1);
5331            out.instances[dst_idx] = inst;
5332        }
5333        let sun: DirectionalLight3D = self.get_sun();
5334        let sun_dir: Vec3 = sun.get_direction().normalize();
5335        let sun_col: Vec3 = sun.get_color();
5336        let sky_hor: Vec3 = sun.get_sky_horizon();
5337        let sky_zen: Vec3 = sun.get_sky_zenith();
5338        let fog_density: f32 = if quality.get_volumetric_fog() {
5339            0.0028
5340        } else {
5341            0.0008
5342        };
5343        out.target_width = target_width;
5344        out.target_height = target_height;
5345        out.view_proj = view_proj_mat.get_elements();
5346        out.camera_pos = [cam_pos.get_x(), cam_pos.get_y(), cam_pos.get_z(), 1.15];
5347        out.sun_dir_fog = [
5348            sun_dir.get_x(),
5349            sun_dir.get_y(),
5350            sun_dir.get_z(),
5351            fog_density,
5352        ];
5353        out.sun_color_ambient = [sun_col.get_x(), sun_col.get_y(), sun_col.get_z(), 0.34];
5354        out.sky_horizon_tod = [
5355            sky_hor.get_x(),
5356            sky_hor.get_y(),
5357            sky_hor.get_z(),
5358            sun.get_time_of_day(),
5359        ];
5360        out.sky_zenith_aspect = [sky_zen.get_x(), sky_zen.get_y(), sky_zen.get_z(), aspect];
5361        out.mesh_buffer = Arc::clone(mesh_buffer);
5362    }
5363
5364    /// Populates a recycled `GpuWorld3dScenePass` in-place using `World3D`'s persistent flat scratch arena with zero per-frame heap allocations.
5365    ///
5366    /// # Arguments
5367    ///
5368    /// - `&Self` - Mutable world reference.
5369    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
5370    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
5371    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
5372    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
5373    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
5374    /// - `&mut GpuWorld3dScenePass` - Recycled scene pass destination populated in-place.
5375    pub fn build_gpu_scene_pass_into(
5376        &mut self,
5377        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
5378        alpha: f32,
5379        viewport: (u32, u32),
5380        quality: &RenderQualityConfig,
5381        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
5382        out: &mut GpuWorld3dScenePass,
5383    ) {
5384        let mut scratch: World3dGpuPassScratch = {
5385            let Self {
5386                gpu_pass_scratch, ..
5387            } = self;
5388            take(gpu_pass_scratch)
5389        };
5390        self.populate_gpu_scene_pass_with_scratch(
5391            snapshots,
5392            alpha,
5393            viewport,
5394            quality,
5395            mesh_cache,
5396            (&mut scratch, out),
5397        );
5398        let Self {
5399            gpu_pass_scratch, ..
5400        } = self;
5401        *gpu_pass_scratch = scratch;
5402    }
5403
5404    /// 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.
5405    ///
5406    /// # Arguments
5407    ///
5408    /// - `&Self` - World reference.
5409    /// - `&DoubleBufferedSnapshot<World3DSnapshot>` - Double-buffered dynamic object and camera snapshots.
5410    /// - `f32` - Render interpolation alpha in `[0.0, 1.0]`.
5411    /// - `(u32, u32)` - Target physical framebuffer `(width, height)`.
5412    /// - `&RenderQualityConfig` - Active quality settings controlling draw distance, culling, and fog.
5413    /// - `(&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)])` - Cached static mesh buffer and per-mesh `(vertex_start, vertex_count)` ranges.
5414    ///
5415    /// # Returns
5416    ///
5417    /// - `GpuWorld3dScenePass` - Hardware instanced 3D scene pass descriptor ready for Metal, GLES3, D3D11, or WebGL2.
5418    #[must_use]
5419    pub fn build_gpu_scene_pass(
5420        &self,
5421        snapshots: &DoubleBufferedSnapshot<World3DSnapshot>,
5422        alpha: f32,
5423        viewport: (u32, u32),
5424        quality: &RenderQualityConfig,
5425        mesh_cache: (&Arc<GpuWorld3dMeshBuffer>, &[(u32, u32)]),
5426    ) -> GpuWorld3dScenePass {
5427        let mut out: GpuWorld3dScenePass = GpuWorld3dScenePass::default();
5428        let used_tls: bool = WORLD3D_GPU_PASS_SCRATCH
5429            .try_with(|cell: &RefCell<World3dGpuPassScratch>| -> bool {
5430                if let Ok(mut scratch) = cell.try_borrow_mut() {
5431                    self.populate_gpu_scene_pass_with_scratch(
5432                        snapshots,
5433                        alpha,
5434                        viewport,
5435                        quality,
5436                        mesh_cache,
5437                        (&mut scratch, &mut out),
5438                    );
5439                    true
5440                } else {
5441                    false
5442                }
5443            })
5444            .unwrap_or(false);
5445        if !used_tls {
5446            let mut local_scratch: World3dGpuPassScratch = World3dGpuPassScratch::default();
5447            self.populate_gpu_scene_pass_with_scratch(
5448                snapshots,
5449                alpha,
5450                viewport,
5451                quality,
5452                mesh_cache,
5453                (&mut local_scratch, &mut out),
5454            );
5455        }
5456        out
5457    }
5458}
5459
5460/// Perspective and Orthographic projection matrix builders for `SceneCamera3D`.
5461impl SceneCamera3D {
5462    /// Builds a `SceneCamera3D` from an imported glTF/Blender `ImportedCamera3D` and node world pose.
5463    ///
5464    /// # Arguments
5465    ///
5466    /// - `&ImportedCamera3D` - Imported camera parameters.
5467    /// - `Option<u32>` - Optional owning scene-graph node index.
5468    /// - `Vec3` - World-space camera eye position.
5469    /// - `Quat` - World-space camera orientation quaternion.
5470    ///
5471    /// # Returns
5472    ///
5473    /// - `Self` - Constructed multi-camera entry.
5474    #[must_use]
5475    pub fn from_imported(
5476        imported: &ImportedCamera3D,
5477        node_id: Option<u32>,
5478        position: Vec3,
5479        rotation: Quat,
5480    ) -> Self {
5481        Self {
5482            name: imported.get_name().clone(),
5483            node_id,
5484            position,
5485            rotation: rotation.normalize(),
5486            projection: imported.get_projection(),
5487        }
5488    }
5489
5490    /// Returns the unit world-space forward direction along glTF local `-Z`.
5491    ///
5492    /// # Returns
5493    ///
5494    /// - `Vec3` - Unit forward vector.
5495    #[must_use]
5496    pub fn forward(&self) -> Vec3 {
5497        self.get_rotation()
5498            .rotate_vec3(Vec3::new(0.0, 0.0, -1.0))
5499            .normalize()
5500    }
5501
5502    /// Returns the unit world-space right direction along glTF local `+X`.
5503    ///
5504    /// # Returns
5505    ///
5506    /// - `Vec3` - Unit right vector.
5507    #[must_use]
5508    pub fn right(&self) -> Vec3 {
5509        self.get_rotation()
5510            .rotate_vec3(Vec3::new(1.0, 0.0, 0.0))
5511            .normalize()
5512    }
5513
5514    /// Returns the unit world-space up direction along glTF local `+Y`.
5515    ///
5516    /// # Returns
5517    ///
5518    /// - `Vec3` - Unit up vector.
5519    #[must_use]
5520    pub fn up(&self) -> Vec3 {
5521        self.get_rotation()
5522            .rotate_vec3(Vec3::new(0.0, 1.0, 0.0))
5523            .normalize()
5524    }
5525
5526    /// Returns `true` when this camera uses orthographic projection.
5527    ///
5528    /// # Returns
5529    ///
5530    /// - `bool` - Whether projection is orthographic.
5531    #[must_use]
5532    pub fn is_orthographic(&self) -> bool {
5533        matches!(
5534            self.get_projection(),
5535            GltfCameraProjection::Orthographic { .. }
5536        )
5537    }
5538
5539    /// Computes the combined `projection * view` matrix supporting both Perspective and Orthographic projections.
5540    ///
5541    /// # Arguments
5542    ///
5543    /// - `&Self` - Scene camera reference.
5544    /// - `f32` - Active viewport aspect ratio `width / height`.
5545    ///
5546    /// # Returns
5547    ///
5548    /// - `Mat4` - Combined view-projection matrix.
5549    #[must_use]
5550    pub fn view_projection(&self, viewport_aspect: f32) -> Mat4 {
5551        let pos: Vec3 = self.get_position();
5552        let view: Mat4 = Mat4::look_at(pos, pos.add(self.forward()), self.up());
5553        let proj: Mat4 = match self.get_projection() {
5554            GltfCameraProjection::Perspective {
5555                yfov_rad,
5556                aspect_ratio,
5557                znear,
5558                zfar,
5559            } => Mat4::perspective(
5560                yfov_rad.clamp(0.15, 2.6),
5561                aspect_ratio.unwrap_or(viewport_aspect).max(0.1),
5562                znear.max(0.02),
5563                zfar.unwrap_or(480.0).max(znear + 1.0),
5564            ),
5565            GltfCameraProjection::Orthographic {
5566                xmag,
5567                ymag,
5568                znear,
5569                zfar,
5570            } => Mat4::orthographic_mag(xmag, ymag, znear.max(0.01), zfar.max(znear + 1.0)),
5571        };
5572        proj.mul(view)
5573    }
5574
5575    /// Projects this scene camera to a compatible `Camera3D` for primary viewport synchronization.
5576    ///
5577    /// # Returns
5578    ///
5579    /// - `Camera3D` - Equivalent perspective viewport camera descriptor.
5580    #[must_use]
5581    pub fn to_camera3d(&self) -> Camera3D {
5582        let fwd: Vec3 = self.forward();
5583        let yaw_val: f32 = fwd.get_z().atan2(fwd.get_x());
5584        let pitch_val: f32 = fwd.get_y().clamp(-0.98, 0.98).asin();
5585        let (fov_deg, near_val, far_val): (f32, f32, f32) = match self.get_projection() {
5586            GltfCameraProjection::Perspective {
5587                yfov_rad,
5588                znear,
5589                zfar,
5590                ..
5591            } => (
5592                yfov_rad.to_degrees().clamp(12.0, 120.0),
5593                znear.max(0.05),
5594                zfar.unwrap_or(480.0).max(10.0),
5595            ),
5596            GltfCameraProjection::Orthographic { znear, zfar, .. } => {
5597                (45.0, znear.max(0.05), zfar.max(10.0))
5598            }
5599        };
5600        let mut cam: Camera3D = Camera3D::default();
5601        cam.set_position(self.get_position());
5602        cam.set_yaw(yaw_val);
5603        cam.set_pitch(pitch_val);
5604        cam.set_fov_deg(fov_deg);
5605        cam.set_near(near_val);
5606        cam.set_far(far_val);
5607        cam
5608    }
5609}