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 LOD mesh asset library referenced by `SceneObject3D::mesh_id`.
221    pub(crate) mesh_library: Vec<MeshLodChain>,
222    /// All world objects partitioned into open-world chunks.
223    pub(crate) objects: Vec<SceneObject3D>,
224    /// Active 3D perspective camera.
225    #[get(type(copy))]
226    pub(crate) camera: Camera3D,
227    /// Active directional sun/sky lighting.
228    #[get(type(copy))]
229    pub(crate) sun: DirectionalLight3D,
230    /// Flat BVH built over static world-space ray-trace casters (rebuilt only on static geometry edits).
231    pub(crate) bvh: Bvh3D,
232    /// Separate flat BVH over moving/dynamic ray-trace casters supporting O(N) incremental bottom-up refits.
233    pub(crate) dynamic_bvh: Bvh3D,
234    /// Lazily constructed local-space BVH4/BVH8 cache indexed by `mesh_id` for zero-rebuild object-space dynamic raytracing.
235    #[get(skip)]
236    #[get_mut(skip)]
237    #[set(skip)]
238    pub(crate) mesh_local_bvhs: Vec<Option<Bvh3D>>,
239    /// Active object-space dynamic raytracing instances updated via inverse interpolated `Mat4` without BVH rebuilds.
240    #[get(skip)]
241    #[get_mut(skip)]
242    #[set(skip)]
243    pub(crate) dynamic_instances: Vec<DynamicRayInstance>,
244    /// Dirty flag triggering static BVH rebuild when static casters are added or modified.
245    #[get(type(copy))]
246    pub(crate) bvh_dirty: bool,
247    /// Dirty flag triggering dynamic BVH incremental refit or rebuild when moving casters update.
248    #[get(type(copy))]
249    pub(crate) dynamic_bvh_dirty: bool,
250    /// Topology change flag forcing a fresh dynamic BVH SAH build rather than an in-place refit.
251    #[get(type(copy))]
252    pub(crate) dynamic_topology_dirty: bool,
253    /// Total static BVH full rebuilds executed.
254    #[get(type(copy))]
255    pub(crate) static_bvh_rebuilds: u64,
256    /// Total zero-allocation incremental dynamic BVH refits executed.
257    #[get(type(copy))]
258    pub(crate) dynamic_bvh_refits: u64,
259    /// Total full dynamic BVH rebuilds executed (topology changes or SAH quality resets).
260    #[get(type(copy))]
261    pub(crate) dynamic_bvh_rebuilds: u64,
262    /// Monotonic revision incremented only when 3D world transforms, camera, or lighting change (isolated from HUD dirtiness).
263    #[get(type(copy))]
264    pub(crate) world_revision: u64,
265    /// Reusable scratch buffer holding transformed dynamic caster triangles during incremental BVH refits.
266    #[get(skip)]
267    #[get_mut(skip)]
268    #[set(skip)]
269    pub(crate) dynamic_tris_scratch: Vec<BvhTriangle>,
270    /// Open-world chunk size in meters (`64.0m` per city block).
271    #[get(type(copy))]
272    pub(crate) chunk_size: f32,
273    /// Index of the drivable player vehicle object if spawned.
274    #[get(skip)]
275    pub(crate) player_vehicle_index: Option<usize>,
276    /// Active hero supercar bodywork archetype (`AventadorV12` or `ShelbyCobra`).
277    #[get(type(copy))]
278    #[set(skip)]
279    #[get_mut(skip)]
280    pub(crate) hero_vehicle_style: HeroVehicleStyle,
281    /// Pre-registered `(mesh_id, signature_material)` handles indexed by `HeroVehicleStyle` for zero-allocation live car switching.
282    #[get(skip)]
283    #[get_mut(skip)]
284    #[set(skip)]
285    pub(crate) hero_vehicle_meshes: [Option<(usize, PbrMaterial)>; 2],
286    /// Total imported external 3D models (`.obj` / `.gltf`).
287    #[get(type(copy))]
288    pub(crate) imported_model_count: usize,
289    /// Active 3D camera mode index (`0=Chase`, `1=Hood`, `2=Orbit`, `3=Aerial`, `4=FreeFly`, `5=CinematicDolly`).
290    #[get(type(copy))]
291    pub(crate) camera_mode: u8,
292    /// Continuous orbit angle in radians used for `Orbit` and `CinematicDolly` modes.
293    #[get(type(copy))]
294    pub(crate) camera_orbit_rad: f32,
295    /// Dynamic world-space omnidirectional point lights binned by `LightClusterGrid3D`.
296    pub(crate) point_lights: Vec<PointLight3D>,
297    /// Dynamic world-space spotlights (vehicle headlights, streetlamps) binned by `LightClusterGrid3D`.
298    pub(crate) spot_lights: Vec<SpotLight3D>,
299    /// Zero-allocation 3D Niagara particle system for sparks, exhaust trails, and atmospheric effects.
300    pub(crate) niagara: NiagaraSystem3D,
301    /// Active atmospheric mood preset (`0=Sunset, 1=RainyNight, 2=Noon, 3=Midnight`).
302    #[get(type(copy))]
303    pub(crate) atmosphere_preset: u8,
304    /// Cruising AI traffic vehicles `(object_index, velocity_z_mps, z_min, z_max)` animated smoothly on outer boulevard lanes.
305    #[get(skip)]
306    #[get_mut(skip)]
307    #[set(skip)]
308    pub(crate) traffic_vehicles: Vec<(usize, f32, f32, f32)>,
309    /// Monotonic simulation clock in seconds driving continuous animated ocean waves, caustics, and shoreline foam.
310    #[get(type(copy))]
311    pub(crate) world_time_secs: f32,
312    /// Hierarchical Blender/glTF scene graph with topological propagation and 64-bit Collections visibility.
313    pub(crate) scene_graph: SceneGraph3D,
314    /// Full 1:1 Blender Principled BSDF materials referenced by `SceneObject3D::principled_material_id`.
315    pub(crate) principled_materials: Vec<PrincipledMaterial3D>,
316    /// Mipmapped 2D texture pool referenced by `PrincipledMaterial3D` slots.
317    pub(crate) textures: Vec<Texture2D3D>,
318    /// Active armature skins evaluated against `scene_graph` joint world matrices.
319    pub(crate) skins: Vec<Skin3D>,
320    /// Multi-layer glTF/NLA animation mixer ticking directly into `scene_graph`.
321    pub(crate) animation_mixer: AnimationMixer3D,
322    /// Optional precomputed SH9 + octahedral specular + BRDF LUT IBL environment.
323    #[get(skip)]
324    #[get_mut(skip)]
325    #[set(skip)]
326    pub(crate) environment_ibl: Option<EnvironmentIbl3D>,
327    /// Physically based rectangular and disk Blender area lights.
328    pub(crate) area_lights: Vec<AreaLight3D>,
329    /// Imported and user-registered multi-camera list supporting Perspective and Orthographic projections.
330    pub(crate) scene_cameras: Vec<SceneCamera3D>,
331    /// Optional active camera index inside `scene_cameras` (`None` uses primary `camera`).
332    #[get(skip)]
333    #[get_mut(skip)]
334    #[set(skip)]
335    pub(crate) active_scene_camera: Option<usize>,
336    /// Mapping from `scene_graph` node index to spawned `World3D::objects` index for O(1) transform synchronization.
337    #[get(skip)]
338    #[get_mut(skip)]
339    #[set(skip)]
340    pub(crate) node_object_map: Vec<Option<usize>>,
341    /// Reusable pre-allocated skinning and shape-key scratch arena for zero steady-state heap allocations.
342    #[get(skip)]
343    #[get_mut(skip)]
344    #[set(skip)]
345    pub(crate) skin_scratch: SkinPaletteScratch3D,
346    /// Per-object deformed mesh cache aligned with `objects` holding live morphed and skinned vertices.
347    #[get(skip)]
348    #[get_mut(skip)]
349    #[set(skip)]
350    pub(crate) deformed_meshes: Vec<Option<Mesh3D>>,
351    /// Selects Blender AgX filmic view transform (`true`) or ACES Filmic (`false`) during CPU/GPU tonemapping.
352    #[get(type(copy))]
353    pub(crate) use_agx_tonemap: bool,
354    /// Persistent flat scratch buffers eliminating per-frame `Vec<Vec<_>>` allocations and O(N*M) pose scans during GPU pass building.
355    #[get(skip)]
356    #[get_mut(skip)]
357    #[set(skip)]
358    pub(crate) gpu_pass_scratch: World3dGpuPassScratch,
359    /// Persistent quantized geometry cache, batcher scratch, and progressive mip upload watermark reused by `build_gpu_pbr_scene_pass_into`.
360    #[get(skip)]
361    #[get_mut(skip)]
362    #[set(skip)]
363    pub(crate) pbr_pass_scratch: World3dPbrPassScratch,
364}
365
366/// Persistent flat scratch buffers reused by `World3D::build_gpu_scene_pass_into` for zero-allocation O(N) instanced batch building.
367#[derive(Clone, Debug, Default)]
368pub(crate) struct World3dGpuPassScratch {
369    /// Generation-stamped dense lookup epochs indexed directly by `object_index` for O(1) dynamic pose lookup and O(1) clear.
370    pub(crate) dynamic_pose_epochs: Vec<u32>,
371    /// Interpolated dynamic transforms aligned 1:1 with `dynamic_pose_epochs`.
372    pub(crate) dynamic_pose_transforms: Vec<Transform3D>,
373    /// Monotonic epoch counter incremented per pass (`0` triggers full reset on wrap).
374    pub(crate) current_epoch: u32,
375    /// Per-mesh visible instance counts indexed by `mesh_id`.
376    pub(crate) mesh_counts: Vec<u32>,
377    /// Per-mesh scatter write cursors indexed by `mesh_id`.
378    pub(crate) mesh_cursors: Vec<u32>,
379    /// Flat single-allocation gather buffer holding visible `(mesh_id, instance)` pairs before O(N) counting-sort scatter.
380    pub(crate) visible_scratch: Vec<(u32, GpuWorld3dInstance)>,
381}
382
383/// Per-LOD quantized index range and quantization bounds cached inside `World3dPbrPassScratch`.
384#[derive(Clone, Copy, Debug, Default)]
385pub(crate) struct CachedPbrLodRange {
386    /// Starting index inside `GpuPbrMeshBuffer::indices`.
387    pub(crate) index_start: u32,
388    /// Number of triangle indices in this LOD level.
389    pub(crate) index_count: u32,
390    /// Local quantization AABB minimum `[min_x, min_y, min_z, 0.0]`.
391    pub(crate) bounds_min: [f32; 4],
392    /// Local quantization AABB extent `[ext_x, ext_y, ext_z, 0.0]`.
393    pub(crate) bounds_extent: [f32; 4],
394    /// Whether this LOD level contains morph target deltas.
395    pub(crate) has_morphs: bool,
396}
397
398/// Persistent quantized mesh cache and reusable sorting scratch enabling zero-allocation `World3D::build_gpu_pbr_scene_pass_into`.
399#[derive(Clone, Debug, Default)]
400pub(crate) struct World3dPbrPassScratch {
401    /// Cached `Arc`-shared 24-byte quantized geometry buffer rebuilt only when `mesh_library` changes.
402    pub(crate) cached_mesh_buffer: Arc<GpuPbrMeshBuffer>,
403    /// Structural fingerprint `(mesh_count, total_vertices, total_indices)` detecting mesh library mutations.
404    pub(crate) cached_signature: (usize, usize, usize),
405    /// Cached `LOD0..LOD3` index ranges and quantization bounds indexed by `mesh_id`.
406    pub(crate) cached_lod_ranges: Vec<[CachedPbrLodRange; 4]>,
407    /// Reusable 64-bit sort and hardware instancing coalescer arena.
408    pub(crate) batcher: GpuPbrBatcherScratch3D,
409    /// Lowest uploaded mipmap level (`0 = FullRes`, `u8::MAX = Unloaded`) per `World3D::textures` slot.
410    pub(crate) uploaded_texture_min_mip: Vec<u8>,
411}