Skip to main content

euv_core/game/engine3d/world/
struct.rs

1use super::*;
2
3/// Gimbal-lock-free 3D world-space transform backed by a unit Hamilton quaternion (`position`, `rotation`, `scale`).
4#[derive(Clone, Copy, Data, Debug, PartialEq)]
5pub struct Transform3D {
6    /// World-space translation `(x, y, z)`.
7    #[get(type(copy))]
8    pub(crate) position: Vec3,
9    /// Unit Hamilton quaternion orientation `(x, y, z, w)`.
10    #[get(type(copy))]
11    pub(crate) rotation: Quat,
12    /// Scale multiplier along `(x, y, z)`.
13    #[get(type(copy))]
14    pub(crate) scale: Vec3,
15}
16
17/// Multi-camera scene registry entry supporting both Perspective and Orthographic Blender/glTF cameras.
18#[derive(Clone, Data, Debug, PartialEq)]
19pub struct SceneCamera3D {
20    /// Human-readable camera label.
21    pub(crate) name: String,
22    /// Optional owning node index inside `World3D::scene_graph`.
23    #[get(type(copy))]
24    pub(crate) node_id: Option<u32>,
25    /// World-space camera eye position.
26    #[get(type(copy))]
27    pub(crate) position: Vec3,
28    /// World-space camera orientation quaternion (glTF camera looks along local `-Z`, up `+Y`).
29    #[get(type(copy))]
30    pub(crate) rotation: Quat,
31    /// Perspective or orthographic projection parameters.
32    #[get(type(copy))]
33    pub(crate) projection: GltfCameraProjection,
34}
35
36/// Fluent descriptor for spawning a `SceneObject3D` into `World3D`.
37#[derive(Clone, Data, Debug, PartialEq)]
38pub struct SpawnObjectDesc {
39    /// Human-readable object label.
40    pub(crate) name: String,
41    /// Registered mesh identifier from `World3D::register_mesh`.
42    #[get(type(copy))]
43    pub(crate) mesh_id: usize,
44    /// World-space TRS transform.
45    #[get(type(copy))]
46    pub(crate) transform: Transform3D,
47    /// Surface PBR material.
48    #[get(type(copy))]
49    pub(crate) material: PbrMaterial,
50    /// Whether this object casts ray-traced shadows and appears in BVH reflections.
51    #[get(type(copy))]
52    pub(crate) ray_trace_caster: bool,
53    /// Whether this object participates in solid vehicle and camera collision detection.
54    #[get(type(copy))]
55    pub(crate) solid_collider: bool,
56    /// Continuous spin speed in radians/sec.
57    #[get(type(copy))]
58    pub(crate) spin_speed: f32,
59    /// Whether this object moves dynamically and belongs in the incrementally refitted dynamic BVH.
60    #[get(type(copy))]
61    pub(crate) is_dynamic: bool,
62}
63
64/// Fluent descriptor for importing a 3D `.obj` or `.gltf` model into `World3D`.
65#[derive(Clone, Data, Debug, PartialEq)]
66pub struct ImportModelDesc {
67    /// Source model interchange format.
68    #[get(type(copy))]
69    pub(crate) format: ModelFormat,
70    /// Raw `.obj` or `.gltf` text content.
71    pub(crate) source: String,
72    /// World-space placement transform.
73    #[get(type(copy))]
74    pub(crate) transform: Transform3D,
75    /// Fallback PBR material when source omits material definitions.
76    #[get(type(copy))]
77    pub(crate) fallback_material: PbrMaterial,
78    /// Optional continuous Y-spin speed in radians/sec.
79    #[get(type(copy))]
80    pub(crate) spin_speed: f32,
81}
82
83/// Instanced 3D scene object placed inside an open-world chunk.
84#[derive(Clone, Data, Debug, PartialEq)]
85pub struct SceneObject3D {
86    /// Human-readable object label.
87    pub(crate) name: String,
88    /// Index into `World3D::mesh_library` enabling GPU instancing batching.
89    #[get(type(copy))]
90    pub(crate) mesh_id: usize,
91    /// World-space TRS transform.
92    #[get(type(copy))]
93    pub(crate) transform: Transform3D,
94    /// Material override (or default mesh material).
95    #[get(type(copy))]
96    pub(crate) material: PbrMaterial,
97    /// Cached world-space axis-aligned bounding box for O(1) frustum culling and chunk streaming.
98    #[get(type(copy))]
99    pub(crate) world_bounds: AxisAlignedBox3D,
100    /// Spatial open-world chunk coordinate `(chunk_x, chunk_z)`.
101    #[get(type(copy))]
102    pub(crate) chunk_coord: (i32, i32),
103    /// Whether this object casts ray-traced shadows and appears in BVH reflections.
104    #[get(type(copy))]
105    pub(crate) ray_trace_caster: bool,
106    /// Whether this object participates in solid vehicle and camera collision detection.
107    #[get(type(copy))]
108    pub(crate) solid_collider: bool,
109    /// Continuous spin speed in radians/sec for animated hero models or props.
110    #[get(type(copy))]
111    pub(crate) spin_speed: f32,
112    /// Whether this object belongs to the dynamic incrementally-refitted BVH rather than the static world BVH.
113    #[get(type(copy))]
114    pub(crate) is_dynamic: bool,
115    /// Discontinuity counter incremented on teleports so snapshot interpolation snaps cleanly.
116    #[get(type(copy))]
117    pub(crate) teleport_epoch: u32,
118    /// Optional owning hierarchical node index inside `World3D::scene_graph`.
119    #[get(type(copy))]
120    pub(crate) node_id: Option<u32>,
121    /// Optional index into `World3D::principled_materials` for full Principled BSDF shading.
122    #[get(type(copy))]
123    pub(crate) principled_material_id: Option<u32>,
124    /// Optional index into `World3D::skins` for armature LBS/DQS vertex deformation.
125    #[get(type(copy))]
126    pub(crate) skin_id: Option<u32>,
127}
128
129/// Primary sun/moon directional light and atmospheric sky parameters.
130#[derive(Clone, Copy, Data, Debug, PartialEq)]
131pub struct DirectionalLight3D {
132    /// Normalized direction pointing toward the sun.
133    #[get(type(copy))]
134    pub(crate) direction: Vec3,
135    /// Linear HDR sun radiance color.
136    #[get(type(copy))]
137    pub(crate) color: Vec3,
138    /// Ambient sky zenith color.
139    #[get(type(copy))]
140    pub(crate) sky_zenith: Vec3,
141    /// Ambient sky horizon and volumetric fog color.
142    #[get(type(copy))]
143    pub(crate) sky_horizon: Vec3,
144    /// Time of day in `[0.0, 24.0]` hours.
145    #[get(type(copy))]
146    pub(crate) time_of_day: f32,
147}
148
149/// Oriented bounding box in 3D space used for tight rotated collider narrow-phase tests.
150#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
151pub struct OrientedBox3D {
152    /// Box center position in target coordinate space.
153    #[get(type(copy))]
154    pub(crate) center: Vec3,
155    /// Orthonormal local X, Y, and Z basis axes.
156    #[get(type(copy))]
157    pub(crate) axes: [Vec3; 3],
158    /// Positive half-extents along each local axis.
159    #[get(type(copy))]
160    pub(crate) half_extents: Vec3,
161}
162
163/// Real-mesh narrow-phase collision contact reported against a solid `SceneObject3D` triangle.
164#[derive(Clone, Copy, Data, Debug, New, PartialEq)]
165pub struct MeshCollisionHit3D {
166    /// Colliding obstacle index inside `World3D::objects`.
167    #[get(type(copy))]
168    pub(crate) object_index: usize,
169    /// Unit world-space separation normal pointing toward the moving collider.
170    #[get(type(copy))]
171    pub(crate) normal: Vec3,
172    /// Positive penetration depth along `normal` in meters.
173    #[get(type(copy))]
174    pub(crate) penetration: f32,
175    /// World-space contact point on the colliding triangle surface.
176    #[get(type(copy))]
177    pub(crate) contact_point: Vec3,
178}
179
180/// Interactive raycast scene picking result returned by `World3D::pick_object_ray`.
181#[derive(Clone, Copy, Data, Debug, Default, New, PartialEq)]
182pub struct ScenePickHit3D {
183    /// Picked object index inside `World3D::objects`.
184    #[get(type(copy))]
185    pub(crate) object_index: usize,
186    /// Registered mesh identifier of the picked object.
187    #[get(type(copy))]
188    pub(crate) mesh_id: usize,
189    /// Ray distance from the camera origin to the intersection point in meters.
190    #[get(type(copy))]
191    pub(crate) distance: f32,
192    /// World-space intersection point on the picked object.
193    #[get(type(copy))]
194    pub(crate) world_position: Vec3,
195    /// Outward world-space surface normal at the intersection point.
196    #[get(type(copy))]
197    pub(crate) world_normal: Vec3,
198}
199
200/// Object-space raytracing instance descriptor enabling exact interpolated dynamic shadows and reflections with zero BVH rebuilds per VSync.
201#[derive(Clone, Copy, Debug)]
202pub(crate) struct DynamicRayInstance {
203    /// Owning scene object index in `World3D::objects`.
204    pub(crate) obj_idx: usize,
205    /// Registered mesh index referencing `World3D::mesh_local_bvhs`.
206    pub(crate) mesh_id: usize,
207    /// World-space axis-aligned bounding box for O(1) miss rejection before transforming rays into object space.
208    pub(crate) world_bounds: AxisAlignedBox3D,
209    /// Exact analytical inverse model matrix (`S^-1 * R^T * T^-1`) mapping world rays to local space.
210    pub(crate) inv_model: Mat4,
211    /// Inverse-transpose 3x3 normal basis mapping local hit normals back to world space.
212    pub(crate) normal_basis: [Vec3; 3],
213    /// Surface PBR material override for this instance.
214    pub(crate) material: PbrMaterial,
215}
216
217/// Complete open-world 3D scene graph with mesh instancing library, chunk streaming, and BVH acceleration.
218#[derive(Clone, Data, Debug)]
219pub struct World3D {
220    /// Shared copy-on-write LOD mesh asset library referenced by `SceneObject3D::mesh_id` (`O(1)` `Arc::clone` on world clone).
221    #[get(skip)]
222    #[get_mut(skip)]
223    #[set(skip)]
224    pub(crate) mesh_library: Arc<Vec<MeshLodChain>>,
225    /// All world objects partitioned into open-world chunks.
226    pub(crate) objects: Vec<SceneObject3D>,
227    /// Active 3D perspective camera.
228    #[get(type(copy))]
229    pub(crate) camera: Camera3D,
230    /// Active directional sun/sky lighting.
231    #[get(type(copy))]
232    pub(crate) sun: DirectionalLight3D,
233    /// Shared copy-on-write flat BVH built over static world-space ray-trace casters (`O(1)` `Arc::clone` on world clone, flat zero-indirection `&Bvh3D` during raytracing).
234    #[get(skip)]
235    #[get_mut(skip)]
236    #[set(skip)]
237    pub(crate) bvh: Arc<Bvh3D>,
238    /// Shared copy-on-write flat BVH over moving/dynamic ray-trace casters (`O(1)` `Arc::clone` on world clone, unique zero-alloc in-place refit via `Arc::make_mut`).
239    #[get(skip)]
240    #[get_mut(skip)]
241    #[set(skip)]
242    pub(crate) dynamic_bvh: Arc<Bvh3D>,
243    /// Lazily constructed shared local-space BVH4/BVH8 cache indexed by `mesh_id` for zero-rebuild object-space dynamic raytracing.
244    #[get(skip)]
245    #[get_mut(skip)]
246    #[set(skip)]
247    pub(crate) mesh_local_bvhs: Arc<Vec<Option<Bvh3D>>>,
248    /// Active object-space dynamic raytracing instances updated via inverse interpolated `Mat4` without BVH rebuilds.
249    #[get(skip)]
250    #[get_mut(skip)]
251    #[set(skip)]
252    pub(crate) dynamic_instances: Vec<DynamicRayInstance>,
253    /// Dirty flag triggering static BVH rebuild when static casters are added or modified.
254    #[get(type(copy))]
255    pub(crate) bvh_dirty: bool,
256    /// Dirty flag triggering dynamic BVH incremental refit or rebuild when moving casters update.
257    #[get(type(copy))]
258    pub(crate) dynamic_bvh_dirty: bool,
259    /// Topology change flag forcing a fresh dynamic BVH SAH build rather than an in-place refit.
260    #[get(type(copy))]
261    pub(crate) dynamic_topology_dirty: bool,
262    /// Total static BVH full rebuilds executed.
263    #[get(type(copy))]
264    pub(crate) static_bvh_rebuilds: u64,
265    /// Total zero-allocation incremental dynamic BVH refits executed.
266    #[get(type(copy))]
267    pub(crate) dynamic_bvh_refits: u64,
268    /// Total full dynamic BVH rebuilds executed (topology changes or SAH quality resets).
269    #[get(type(copy))]
270    pub(crate) dynamic_bvh_rebuilds: u64,
271    /// Monotonic revision incremented only when 3D world transforms, camera, or lighting change (isolated from HUD dirtiness).
272    #[get(type(copy))]
273    pub(crate) world_revision: u64,
274    /// Monotonic simulation step counter incremented once per `step_simulation` call for parity-invariant particle emission.
275    #[get(type(copy))]
276    pub(crate) sim_tick: u64,
277    /// Reusable scratch buffer holding transformed dynamic caster triangles during incremental BVH refits.
278    #[get(skip)]
279    #[get_mut(skip)]
280    #[set(skip)]
281    pub(crate) dynamic_tris_scratch: Vec<BvhTriangle>,
282    /// Open-world chunk size in meters (`64.0m` per city block).
283    #[get(type(copy))]
284    pub(crate) chunk_size: f32,
285    /// Index of the drivable player vehicle object if spawned.
286    #[get(skip)]
287    pub(crate) player_vehicle_index: Option<usize>,
288    /// Active hero supercar bodywork archetype (`AventadorV12` or `ShelbyCobra`).
289    #[get(type(copy))]
290    #[set(skip)]
291    #[get_mut(skip)]
292    pub(crate) hero_vehicle_style: HeroVehicleStyle,
293    /// Pre-registered `(mesh_id, signature_material)` handles indexed by `HeroVehicleStyle` for zero-allocation live car switching.
294    #[get(skip)]
295    #[get_mut(skip)]
296    #[set(skip)]
297    pub(crate) hero_vehicle_meshes: [Option<(usize, PbrMaterial)>; 2],
298    /// Pre-registered rotating wheel `(mesh_id, rim_material)` handles indexed by `HeroVehicleStyle` for zero-allocation live car switching.
299    #[get(skip)]
300    #[get_mut(skip)]
301    #[set(skip)]
302    pub(crate) hero_wheel_meshes: [Option<(usize, PbrMaterial)>; 2],
303    /// Pre-allocated dynamic wheel `SceneObject3D` indices `[FL, FR, RL, RR]` mounted on the player vehicle.
304    #[get(skip)]
305    #[get_mut(skip)]
306    #[set(skip)]
307    pub(crate) player_wheel_objects: [Option<usize>; 4],
308    /// Total imported external 3D models (`.obj` / `.gltf`).
309    #[get(type(copy))]
310    pub(crate) imported_model_count: usize,
311    /// Active 3D camera mode index (`0=Chase..=10=CityAerialDroneOrbit`).
312    #[get(type(copy))]
313    pub(crate) camera_mode: u8,
314    /// Last active car-mounted camera mode restored when cycling `K` back from city views.
315    #[get(skip)]
316    #[get_mut(skip)]
317    #[set(skip)]
318    pub(crate) last_car_camera_mode: CameraMode3D,
319    /// Continuous orbit angle in radians used for `Orbit`, `CinematicDolly`, and `CityAerialDroneOrbit` modes.
320    #[get(type(copy))]
321    pub(crate) camera_orbit_rad: f32,
322    /// Dynamic world-space omnidirectional point lights binned by `LightClusterGrid3D`.
323    pub(crate) point_lights: Vec<PointLight3D>,
324    /// Dynamic world-space spotlights (vehicle headlights, streetlamps) binned by `LightClusterGrid3D`.
325    pub(crate) spot_lights: Vec<SpotLight3D>,
326    /// Zero-allocation 3D Niagara particle system for sparks, exhaust trails, and atmospheric effects.
327    pub(crate) niagara: NiagaraSystem3D,
328    /// Active atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`).
329    #[get(type(copy))]
330    pub(crate) atmosphere_preset: u8,
331    /// Active independent time-of-day preset cycled via the `T` shortcut.
332    #[get(skip)]
333    #[get_mut(skip)]
334    #[set(skip)]
335    pub(crate) time_of_day_preset: TimeOfDayPreset3D,
336    /// Active independent atmospheric weather preset cycled via the `Y` shortcut.
337    #[get(skip)]
338    #[get_mut(skip)]
339    #[set(skip)]
340    pub(crate) weather_preset: WeatherPreset3D,
341    /// Whether current weather produces wet reflective specular sheen on city asphalt.
342    #[get(skip)]
343    #[get_mut(skip)]
344    #[set(skip)]
345    pub(crate) wet_asphalt: bool,
346    /// Active volumetric fog density multiplier applied to GPU and software atmospheric depth fog.
347    #[get(skip)]
348    #[get_mut(skip)]
349    #[set(skip)]
350    pub(crate) weather_fog_density: f32,
351    /// Active ambient hemisphere lighting factor tuned jointly by time of day and weather.
352    #[get(skip)]
353    #[get_mut(skip)]
354    #[set(skip)]
355    pub(crate) weather_ambient_strength: f32,
356    /// Active exposure scale tuned jointly by time of day and weather.
357    #[get(skip)]
358    #[get_mut(skip)]
359    #[set(skip)]
360    pub(crate) weather_exposure: f32,
361    /// Pre-allocated object indices of the layered 3D volumetric exhaust flame cones (`4 pipes x 3 layers`).
362    #[get(skip)]
363    #[get_mut(skip)]
364    #[set(skip)]
365    pub(crate) exhaust_flame_objects: [Option<usize>; EXHAUST_TOTAL_FLAME_OBJECTS],
366    /// Per-object visibility mask for volumetric exhaust flame cones (`true` while actively emitting flame).
367    #[get(skip)]
368    #[get_mut(skip)]
369    #[set(skip)]
370    pub(crate) exhaust_flame_visible: [bool; EXHAUST_TOTAL_FLAME_OBJECTS],
371    /// Dedicated dynamic point light index illuminating the rear diffuser and asphalt during boost and backfire.
372    #[get(skip)]
373    #[get_mut(skip)]
374    #[set(skip)]
375    pub(crate) exhaust_light_index: Option<usize>,
376    /// Scene object index of the primary city road ground mesh for live wet/dry asphalt material tuning.
377    #[get(skip)]
378    #[get_mut(skip)]
379    #[set(skip)]
380    pub(crate) road_ground_object_index: Option<usize>,
381    /// Dynamic rigid-body autonomous NPC vehicles supporting boulevard cruising, off-road plaza free-roaming, and momentum-transfer impacts.
382    #[get(skip)]
383    #[get_mut(skip)]
384    #[set(skip)]
385    pub(crate) traffic_vehicles: Vec<NpcVehicle3D>,
386    /// Persistent player chassis dynamics state (velocity, slip angle, drift, nitro boost, suspension pitch/roll, camera feedback).
387    #[get(skip)]
388    #[get_mut(skip)]
389    #[set(skip)]
390    pub(crate) player_physics: PlayerVehiclePhysics3D,
391    /// Monotonic simulation clock in seconds driving continuous animated ocean waves, caustics, and shoreline foam.
392    #[get(type(copy))]
393    pub(crate) world_time_secs: f32,
394    /// Hierarchical Blender/glTF scene graph with topological propagation and 64-bit Collections visibility.
395    pub(crate) scene_graph: SceneGraph3D,
396    /// Full 1:1 Blender Principled BSDF materials referenced by `SceneObject3D::principled_material_id`.
397    pub(crate) principled_materials: Vec<PrincipledMaterial3D>,
398    /// Mipmapped 2D texture pool referenced by `PrincipledMaterial3D` slots.
399    pub(crate) textures: Vec<Texture2D3D>,
400    /// Active armature skins evaluated against `scene_graph` joint world matrices.
401    pub(crate) skins: Vec<Skin3D>,
402    /// Multi-layer glTF/NLA animation mixer ticking directly into `scene_graph`.
403    pub(crate) animation_mixer: AnimationMixer3D,
404    /// Optional precomputed SH9 + octahedral specular + BRDF LUT IBL environment.
405    #[get(skip)]
406    #[get_mut(skip)]
407    #[set(skip)]
408    pub(crate) environment_ibl: Option<EnvironmentIbl3D>,
409    /// Physically based rectangular and disk Blender area lights.
410    pub(crate) area_lights: Vec<AreaLight3D>,
411    /// Imported and user-registered multi-camera list supporting Perspective and Orthographic projections.
412    pub(crate) scene_cameras: Vec<SceneCamera3D>,
413    /// Optional active camera index inside `scene_cameras` (`None` uses primary `camera`).
414    #[get(skip)]
415    #[get_mut(skip)]
416    #[set(skip)]
417    pub(crate) active_scene_camera: Option<usize>,
418    /// Mapping from `scene_graph` node index to spawned `World3D::objects` index for O(1) transform synchronization.
419    #[get(skip)]
420    #[get_mut(skip)]
421    #[set(skip)]
422    pub(crate) node_object_map: Vec<Option<usize>>,
423    /// Reusable pre-allocated skinning and shape-key scratch arena for zero steady-state heap allocations.
424    #[get(skip)]
425    #[get_mut(skip)]
426    #[set(skip)]
427    pub(crate) skin_scratch: SkinPaletteScratch3D,
428    /// Per-object deformed mesh cache aligned with `objects` holding live morphed and skinned vertices.
429    #[get(skip)]
430    #[get_mut(skip)]
431    #[set(skip)]
432    pub(crate) deformed_meshes: Vec<Option<Mesh3D>>,
433    /// Selects Blender AgX filmic view transform (`true`) or ACES Filmic (`false`) during CPU/GPU tonemapping.
434    #[get(type(copy))]
435    pub(crate) use_agx_tonemap: bool,
436    /// Persistent flat scratch buffers eliminating per-frame `Vec<Vec<_>>` allocations and O(N*M) pose scans during GPU pass building.
437    #[get(skip)]
438    #[get_mut(skip)]
439    #[set(skip)]
440    pub(crate) gpu_pass_scratch: World3dGpuPassScratch,
441    /// Persistent quantized geometry cache, batcher scratch, and progressive mip upload watermark reused by `build_gpu_pbr_scene_pass_into`.
442    #[get(skip)]
443    #[get_mut(skip)]
444    #[set(skip)]
445    pub(crate) pbr_pass_scratch: World3dPbrPassScratch,
446    /// Persistent living city ecosystem state driving live traffic lights, drifting cumulus clouds, `BoidsFlockSolver` flocking birds, river shimmer, and wind sway.
447    pub(crate) city_ecosystem: CityEcosystemState3D,
448}
449
450/// Persistent flat scratch buffers reused by `World3D::build_gpu_scene_pass_into` for zero-allocation O(N) instanced batch building.
451#[derive(Clone, Debug, Default)]
452pub(crate) struct World3dGpuPassScratch {
453    /// Generation-stamped dense lookup epochs indexed directly by `object_index` for O(1) dynamic pose lookup and O(1) clear.
454    pub(crate) dynamic_pose_epochs: Vec<u32>,
455    /// Interpolated dynamic transforms aligned 1:1 with `dynamic_pose_epochs`.
456    pub(crate) dynamic_pose_transforms: Vec<Transform3D>,
457    /// Monotonic epoch counter incremented per pass (`0` triggers full reset on wrap).
458    pub(crate) current_epoch: u32,
459    /// Per-mesh visible instance counts indexed by `mesh_id`.
460    pub(crate) mesh_counts: Vec<u32>,
461    /// Per-mesh scatter write cursors indexed by `mesh_id`.
462    pub(crate) mesh_cursors: Vec<u32>,
463    /// Flat single-allocation gather buffer holding visible `(mesh_id, instance)` pairs before O(N) counting-sort scatter.
464    pub(crate) visible_scratch: Vec<(u32, GpuWorld3dInstance)>,
465}
466
467/// Per-LOD quantized index range and quantization bounds cached inside `World3dPbrPassScratch`.
468#[derive(Clone, Copy, Debug, Default)]
469pub(crate) struct CachedPbrLodRange {
470    /// Starting index inside `GpuPbrMeshBuffer::indices`.
471    pub(crate) index_start: u32,
472    /// Number of triangle indices in this LOD level.
473    pub(crate) index_count: u32,
474    /// Local quantization AABB minimum `[min_x, min_y, min_z, 0.0]`.
475    pub(crate) bounds_min: [f32; 4],
476    /// Local quantization AABB extent `[ext_x, ext_y, ext_z, 0.0]`.
477    pub(crate) bounds_extent: [f32; 4],
478    /// Whether this LOD level contains morph target deltas.
479    pub(crate) has_morphs: bool,
480}
481
482/// Persistent quantized mesh cache and reusable sorting scratch enabling zero-allocation `World3D::build_gpu_pbr_scene_pass_into`.
483#[derive(Clone, Debug, Default)]
484pub(crate) struct World3dPbrPassScratch {
485    /// Cached `Arc`-shared 24-byte quantized geometry buffer rebuilt only when `mesh_library` changes.
486    pub(crate) cached_mesh_buffer: Arc<GpuPbrMeshBuffer>,
487    /// Structural fingerprint `(mesh_count, total_vertices, total_indices)` detecting mesh library mutations.
488    pub(crate) cached_signature: (usize, usize, usize),
489    /// Cached `LOD0..LOD3` index ranges and quantization bounds indexed by `mesh_id`.
490    pub(crate) cached_lod_ranges: Vec<[CachedPbrLodRange; 4]>,
491    /// Reusable 64-bit sort and hardware instancing coalescer arena.
492    pub(crate) batcher: GpuPbrBatcherScratch3D,
493    /// Lowest uploaded mipmap level (`0 = FullRes`, `u8::MAX = Unloaded`) per `World3D::textures` slot.
494    pub(crate) uploaded_texture_min_mip: Vec<u8>,
495}
496
497/// Persistent zero-allocation player vehicle chassis dynamics state for `World3D`.
498#[derive(Clone, Copy, Data, Debug, PartialEq)]
499pub(crate) struct PlayerVehiclePhysics3D {
500    /// World-space horizontal chassis velocity vector `(vx, 0.0, vz)` in meters per second.
501    #[get(type(copy))]
502    pub(crate) vel: Vec3,
503    /// Active yaw angular velocity around the vertical Y axis in radians per second.
504    #[get(type(copy))]
505    pub(crate) yaw_rate: f32,
506    /// Smoothly damped visual chassis lateral body roll angle in radians.
507    #[get(type(copy))]
508    pub(crate) body_roll_rad: f32,
509    /// Smoothly damped visual chassis longitudinal pitch angle in radians (squat/dive).
510    #[get(type(copy))]
511    pub(crate) body_pitch_rad: f32,
512    /// Whether Shift nitro boost is currently delivering extra thrust.
513    #[get(type(copy))]
514    pub(crate) boost_active: bool,
515    /// Normalized turbo overdrive reserve gauge in `[0.0, 1.0]` staying smoothly high during continuous boost.
516    #[get(type(copy))]
517    pub(crate) boost_charge: f32,
518    /// Smooth progressive turbocharger spool-up factor in `[0.0, 1.0]` driving continuous thrust and exhaust afterburner stretch.
519    #[get(type(copy))]
520    pub(crate) boost_spool: f32,
521    /// Normalized engine RPM estimate in `[0.0, 1.0]` across the 6-speed gearbox.
522    #[get(type(copy))]
523    pub(crate) engine_rpm_norm: f32,
524    /// Active sequential gearbox gear index (`1..=6`) for realistic upshift exhaust crackle detection.
525    #[get(type(copy))]
526    pub(crate) active_gear: u8,
527    /// Previous tick throttle command used to detect crisp off-throttle lift-off backfires.
528    #[get(type(copy))]
529    pub(crate) prev_throttle: f32,
530    /// Remaining duration in seconds of active off-throttle or upshift exhaust backfire flame pops.
531    #[get(type(copy))]
532    pub(crate) backfire_timer: f32,
533    /// Whether Space handbrake powerslide drift is currently active.
534    #[get(type(copy))]
535    pub(crate) drift_active: bool,
536    /// Signed lateral chassis slip angle `atan2(v_lateral, |v_forward|)` in radians.
537    #[get(type(copy))]
538    pub(crate) drift_slip_angle: f32,
539    /// Accumulated continuous drift duration in seconds for exit-drift boost kick qualification.
540    #[get(type(copy))]
541    pub(crate) drift_duration: f32,
542    /// Peak absolute slip angle reached during the active drift window in radians.
543    #[get(type(copy))]
544    pub(crate) drift_peak_slip: f32,
545    /// Smoothly damped dynamic chase-camera vertical FOV boost in degrees.
546    #[get(type(copy))]
547    pub(crate) camera_fov_boost: f32,
548    /// Smoothly decaying impact camera shake amplitude in `[0.0, 1.0]`.
549    #[get(type(copy))]
550    pub(crate) camera_shake: f32,
551    /// Cumulative wheel rolling angle in radians around the local X axle (negative forward, positive reverse).
552    #[get(type(copy))]
553    pub(crate) wheel_spin_rad: f32,
554    /// Smoothly damped front-wheel physical steering yaw offset in `[-0.48, +0.48]` radians.
555    #[get(type(copy))]
556    pub(crate) front_steer_rad: f32,
557}
558
559/// Full dynamic rigid-body state for an autonomous NPC vehicle capable of boulevard cruising, off-road plaza free-roaming, and momentum-transfer impacts.
560#[derive(Clone, Copy, Data, Debug, PartialEq)]
561pub(crate) struct NpcVehicle3D {
562    /// Owning scene object index inside `World3D::objects`.
563    #[get(type(copy))]
564    pub(crate) object_index: usize,
565    /// World-space horizontal rigid-body velocity `(vx, 0.0, vz)` in meters per second.
566    #[get(type(copy))]
567    pub(crate) vel: Vec3,
568    /// Active angular spin rate around the vertical Y axis in radians per second.
569    #[get(type(copy))]
570    pub(crate) yaw_rate: f32,
571    /// Simulated vehicle mass in kilograms for 2-body collision impulse resolution.
572    #[get(type(copy))]
573    pub(crate) mass: f32,
574    /// Target cruising speed in meters per second when autonomous steering is active.
575    #[get(type(copy))]
576    pub(crate) cruise_speed: f32,
577    /// Remaining collision knockback recovery time in seconds during which the vehicle slides/spins freely under tire friction.
578    #[get(type(copy))]
579    pub(crate) recovery_timer: f32,
580    /// Whether this NPC freely roams open off-road plazas and city grounds rather than following the boulevard loop.
581    #[get(type(copy))]
582    pub(crate) free_roam_mode: bool,
583    /// Current progress along the 962m boulevard centerline in meters for loop-cruising NPCs.
584    #[get(type(copy))]
585    pub(crate) loop_arc_s: f32,
586    /// Target lateral offset on the boulevard in meters for undisturbed loop-cruising NPCs.
587    #[get(type(copy))]
588    pub(crate) loop_lane_u: f32,
589    /// Travel direction along the boulevard loop (`+1.0` clockwise, `-1.0` counter-clockwise).
590    #[get(type(copy))]
591    pub(crate) loop_dir: f32,
592    /// Active world-space navigation waypoint `(x, 0.0, z)` for free-roaming NPCs.
593    #[get(type(copy))]
594    pub(crate) nav_target: Vec3,
595    /// Current waypoint index inside the assigned open-city route.
596    #[get(type(copy))]
597    pub(crate) waypoint_idx: usize,
598    /// Open-city off-road route identifier (`0=InnerPlaza, 1=OuterWestPlaza, 2=CrossCourtyard`).
599    #[get(type(copy))]
600    pub(crate) route_id: u8,
601    /// Accumulated stalled time in seconds while intending to move below `NPC_STUCK_SPEED_MPS`.
602    #[get(type(copy))]
603    pub(crate) stuck_timer: f32,
604    /// Remaining duration in seconds of the active 3-point Ackermann reverse-and-turn unstick maneuver.
605    #[get(type(copy))]
606    pub(crate) unstick_timer: f32,
607    /// Signed Ackermann reverse steering direction (`-1.0` or `+1.0`) steering away from the blocking wall normal.
608    #[get(type(copy))]
609    pub(crate) unstick_steer: f32,
610    /// Verified obstacle-free escape heading in radians locked after scanning 8 candidate headings.
611    #[get(type(copy))]
612    pub(crate) escape_heading: f32,
613    /// Remaining duration in seconds to hold `escape_heading` before resuming normal navigation.
614    #[get(type(copy))]
615    pub(crate) escape_timer: f32,
616    /// Smoothly damped lateral avoidance offset in meters for reciprocal oncoming passing and overtaking.
617    #[get(type(copy))]
618    pub(crate) lane_avoid_offset: f32,
619    /// Last horizontal wall contact normal X component used to bias reverse unstick away from obstacles.
620    #[get(type(copy))]
621    pub(crate) last_wall_normal_x: f32,
622    /// Last horizontal wall contact normal Z component used to bias reverse unstick away from obstacles.
623    #[get(type(copy))]
624    pub(crate) last_wall_normal_z: f32,
625    /// Cumulative wheel rolling angle in radians around the local X axle (negative forward, positive reverse).
626    #[get(type(copy))]
627    pub(crate) wheel_spin_rad: f32,
628    /// Smoothly damped front-wheel physical steering yaw offset in `[-0.48, +0.48]` radians.
629    #[get(type(copy))]
630    pub(crate) front_steer_rad: f32,
631    /// Pre-allocated dynamic wheel `SceneObject3D` indices `[FL, FR, RL, RR]` mounted on this NPC vehicle.
632    #[get(type(copy))]
633    pub(crate) wheel_object_indices: [Option<usize>; 4],
634    /// Sculpted vehicle archetype controlling wheel hub layout and rolling tire radius.
635    #[get(type(copy))]
636    pub(crate) vehicle_kind: SculptedVehicleKind,
637}
638
639/// Per-substep CCD stepping context carrying substep duration, optional playable ground bounds, and vehicle half-extent margin.
640#[derive(Clone, Copy, Debug)]
641pub(crate) struct VehicleCcdStepCtx3D {
642    /// Substep duration in seconds.
643    pub(crate) sub_dt: f32,
644    /// Optional playable horizontal `(min_x, max_x, min_z, max_z)` ground bounds.
645    pub(crate) ground_limits: Option<(f32, f32, f32, f32)>,
646    /// Vehicle horizontal boundary margin in meters.
647    pub(crate) ground_margin: f32,
648}
649
650/// Process-wide cached Vice Boulevard city template bundling pre-built meshes, BVHs, and static GPU vertex buffers for near-zero `/game3d` entry latency.
651#[derive(Clone, Debug)]
652pub(crate) struct OpenWorldCityTemplate3D {
653    /// Fully assembled open-world `World3D` with static and dynamic BVHs already constructed.
654    pub(crate) world: World3D,
655    /// Pre-baked static GPU vertex buffer shared across scene instances in O(1) via `Arc::clone`.
656    pub(crate) gpu_mesh_buffer: Arc<GpuWorld3dMeshBuffer>,
657    /// Per-mesh `(vertex_start, vertex_count)` table paired with `gpu_mesh_buffer`.
658    pub(crate) gpu_mesh_ranges: Vec<(u32, u32)>,
659}