Skip to main content

euv_core/game/engine3d/rhi/
impl.rs

1use super::*;
2
3/// Default identity-camera `GpuFramePacket3D`.
4impl Default for GpuFramePacket3D {
5    /// Creates an empty `GpuFramePacket3D` initialized with identity camera and CSM matrices.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Empty GPU 3D frame packet.
10    fn default() -> Self {
11        Self {
12            view_projection: Mat4::identity(),
13            prev_view_projection: Mat4::identity(),
14            camera_position: Vec3::zero(),
15            sun: DirectionalLight3D::default(),
16            instances: Vec::new(),
17            batches: Vec::new(),
18            materials: Vec::new(),
19            csm_matrices: [Mat4::identity(); VSM_CASCADE_COUNT],
20            csm_split_depths: [12.0, 36.0, 84.0, 160.0],
21            ibl_sh: [[0.0; 3]; 9],
22            bone_matrices: Vec::new(),
23            use_agx_tonemap: false,
24            active_pass_count: 0,
25            total_triangles: 0,
26        }
27    }
28}
29
30/// Cross-platform GPU 3D shader source lookup for `GpuShaderLanguage3D`.
31impl GpuShaderLanguage3D {
32    /// Resolves the canonical 3D shader language matching a runtime `GraphicsBackend`.
33    ///
34    /// # Arguments
35    ///
36    /// - `GraphicsBackend` - Active hardware graphics API backend.
37    ///
38    /// # Returns
39    ///
40    /// - `Self` - Matching 3D GPU shader language.
41    #[must_use]
42    pub fn from_graphics_backend(backend: GraphicsBackend) -> Self {
43        match backend {
44            GraphicsBackend::Metal => Self::Msl,
45            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => Self::GlslEs3,
46            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => Self::Hlsl,
47            GraphicsBackend::WebGpu
48            | GraphicsBackend::Vulkan
49            | GraphicsBackend::SoftwareCpu
50            | GraphicsBackend::Canvas2d
51            | GraphicsBackend::Headless => Self::Wgsl,
52        }
53    }
54
55    /// Returns the primary unified or vertex 3D Principled BSDF PBR shader source for this shader language.
56    ///
57    /// # Returns
58    ///
59    /// - `&'static str` - Validated GPU 3D PBR shader source string.
60    #[must_use]
61    pub const fn primary_pbr_shader_source(self) -> &'static str {
62        match self {
63            Self::Wgsl => WGSL_ENGINE3D_PBR_SHADER,
64            Self::Msl => MSL_ENGINE3D_PBR_SHADER,
65            Self::GlslEs3 => GLSL_ES3_ENGINE3D_VERTEX_SHADER,
66            Self::Hlsl => HLSL_ENGINE3D_PBR_SHADER,
67        }
68    }
69
70    /// Returns the paired fragment shader source when the backend splits vertex/fragment compilation (GLSL ES 3.0), or the unified shader otherwise.
71    ///
72    /// # Returns
73    ///
74    /// - `&'static str` - Validated GPU 3D PBR fragment shader source string.
75    #[must_use]
76    pub const fn fragment_pbr_shader_source(self) -> &'static str {
77        match self {
78            Self::GlslEs3 => GLSL_ES3_ENGINE3D_FRAGMENT_SHADER,
79            Self::Wgsl => WGSL_ENGINE3D_PBR_SHADER,
80            Self::Msl => MSL_ENGINE3D_PBR_SHADER,
81            Self::Hlsl => HLSL_ENGINE3D_PBR_SHADER,
82        }
83    }
84
85    /// Returns the GPU compute shader source implementing pre-skinning Shape Key morphing, 8-bone LBS/DQS skinning, and frustum+Hi-Z+meshlet normal-cone culling.
86    ///
87    /// # Returns
88    ///
89    /// - `&'static str` - Validated GPU compute shader source string.
90    #[must_use]
91    pub const fn compute_morph_skin_cull_shader_source(self) -> &'static str {
92        match self {
93            Self::Wgsl => WGSL_ENGINE3D_COMPUTE_SHADER,
94            Self::Msl => MSL_ENGINE3D_COMPUTE_SHADER,
95            Self::GlslEs3 => GLSL_ES3_ENGINE3D_COMPUTE_SHADER,
96            Self::Hlsl => HLSL_ENGINE3D_COMPUTE_SHADER,
97        }
98    }
99}
100
101/// Declarative UE5 Render Dependency Graph building, dead-pass culling, topological sorting, transient memory aliasing, and active pass execution for `RenderGraph3D`.
102impl RenderGraph3D {
103    /// Resets all declared resources and passes while retaining vector capacities for zero-allocation per-frame graph rebuilds.
104    pub fn reset(&mut self) {
105        self.get_mut_resources().clear();
106        self.get_mut_passes().clear();
107    }
108
109    /// Declares a transient render-target or buffer resource inside this render graph and returns its `resource_id`.
110    ///
111    /// # Arguments
112    ///
113    /// - `&str` - Human-readable resource label.
114    /// - `usize` - Memory footprint in bytes.
115    /// - `bool` - Whether this resource is an external swapchain/output anchor.
116    ///
117    /// # Returns
118    ///
119    /// - `usize` - Assigned resource identifier.
120    pub fn declare_resource(
121        &mut self,
122        name: &str,
123        size_bytes: usize,
124        is_external_output: bool,
125    ) -> usize {
126        let id: usize = self.get_resources().len();
127        self.get_mut_resources().push(RenderGraphResource3D {
128            resource_id: id,
129            name: name.to_string(),
130            size_bytes,
131            is_external_output,
132        });
133        id
134    }
135
136    /// Declares a render pass with explicit `reads` and `writes` resource dependencies and returns its `pass_id`.
137    ///
138    /// # Arguments
139    ///
140    /// - `RenderPassKind3D` - Pass category.
141    /// - `&str` - Diagnostic pass name.
142    /// - `&[usize]` - Resource IDs read by this pass.
143    /// - `&[usize]` - Resource IDs written by this pass.
144    ///
145    /// # Returns
146    ///
147    /// - `usize` - Assigned pass identifier.
148    pub fn add_pass(
149        &mut self,
150        kind: RenderPassKind3D,
151        name: &str,
152        reads: &[usize],
153        writes: &[usize],
154    ) -> usize {
155        let id: usize = self.get_passes().len();
156        self.get_mut_passes().push(RenderGraphPass3D {
157            pass_id: id,
158            kind,
159            name: name.to_string(),
160            reads: reads.to_vec(),
161            writes: writes.to_vec(),
162            last_duration_us: 0,
163        });
164        id
165    }
166
167    /// Compiles this render graph by performing backward liveness dead-pass culling from external outputs, topological pass ordering, and greedy transient memory aliasing.
168    ///
169    /// # Returns
170    ///
171    /// - `RenderGraphSchedule3D` - Compiled pass execution schedule and aliased VRAM footprint.
172    #[must_use]
173    pub fn compile(&self) -> RenderGraphSchedule3D {
174        let res_count: usize = self.get_resources().len();
175        let pass_count: usize = self.get_passes().len();
176        if pass_count == 0 {
177            return RenderGraphSchedule3D::default();
178        }
179        let resources: &[RenderGraphResource3D] = self.get_resources().as_slice();
180        let passes: &[RenderGraphPass3D] = self.get_passes().as_slice();
181        let mut live_res: Vec<bool> = vec![false; res_count];
182        let mut live_pass: Vec<bool> = vec![false; pass_count];
183        for resource in resources.iter() {
184            if resource.get_is_external_output() {
185                live_res[resource.get_resource_id()] = true;
186            }
187        }
188        let mut changed: bool = true;
189        while changed {
190            changed = false;
191            for pass in passes.iter().rev() {
192                let pid: usize = pass.get_pass_id();
193                if live_pass[pid] {
194                    continue;
195                }
196                let produces_live: bool = pass
197                    .get_writes()
198                    .iter()
199                    .any(|&rid: &usize| rid < res_count && live_res[rid]);
200                if produces_live {
201                    live_pass[pid] = true;
202                    changed = true;
203                    for &rid in pass.get_reads().iter() {
204                        if rid < res_count && !live_res[rid] {
205                            live_res[rid] = true;
206                        }
207                    }
208                }
209            }
210        }
211        let mut ordered_passes: Vec<usize> = Vec::with_capacity(pass_count);
212        for (pid, &is_live) in live_pass.iter().enumerate() {
213            if is_live {
214                ordered_passes.push(pid);
215            }
216        }
217        let culled_pass_count: usize = pass_count.saturating_sub(ordered_passes.len());
218        let mut first_use: Vec<usize> = vec![usize::MAX; res_count];
219        let mut last_use: Vec<usize> = vec![0; res_count];
220        for (exec_idx, &pid) in ordered_passes.iter().enumerate() {
221            let pass: &RenderGraphPass3D = &passes[pid];
222            for &rid in pass.get_writes().iter().chain(pass.get_reads().iter()) {
223                if rid < res_count {
224                    first_use[rid] = first_use[rid].min(exec_idx);
225                    last_use[rid] = last_use[rid].max(exec_idx);
226                }
227            }
228        }
229        let mut unaliased_bytes: usize = 0;
230        let mut pool_slots: Vec<usize> = vec![usize::MAX; res_count];
231        let mut slot_end_step: Vec<usize> = Vec::new();
232        let mut slot_bytes: Vec<usize> = Vec::new();
233        let mut transient_ids: Vec<usize> = Vec::new();
234        for (rid, resource) in resources.iter().enumerate() {
235            if first_use[rid] == usize::MAX || resource.get_is_external_output() {
236                continue;
237            }
238            unaliased_bytes = unaliased_bytes.saturating_add(resource.get_size_bytes());
239            transient_ids.push(rid);
240        }
241        transient_ids.sort_unstable_by(|left_id: &usize, right_id: &usize| {
242            first_use[*left_id]
243                .cmp(&first_use[*right_id])
244                .then_with(|| {
245                    resources[*right_id]
246                        .get_size_bytes()
247                        .cmp(&resources[*left_id].get_size_bytes())
248                })
249        });
250        for rid in transient_ids.into_iter() {
251            let start_step: usize = first_use[rid];
252            let end_step: usize = last_use[rid];
253            let req_bytes: usize = resources[rid].get_size_bytes();
254            let mut best_slot: Option<usize> = None;
255            let mut best_diff: usize = usize::MAX;
256            for (slot_idx, &prev_end) in slot_end_step.iter().enumerate() {
257                if prev_end < start_step {
258                    let diff: usize = slot_bytes[slot_idx].abs_diff(req_bytes);
259                    if diff < best_diff {
260                        best_diff = diff;
261                        best_slot = Some(slot_idx);
262                    }
263                }
264            }
265            if let Some(reused) = best_slot {
266                slot_end_step[reused] = end_step;
267                if req_bytes > slot_bytes[reused] {
268                    slot_bytes[reused] = req_bytes;
269                }
270                pool_slots[rid] = reused;
271            } else {
272                let new_slot: usize = slot_bytes.len();
273                slot_end_step.push(end_step);
274                slot_bytes.push(req_bytes);
275                pool_slots[rid] = new_slot;
276            }
277        }
278        let mut aliased_peak_bytes: usize = 0;
279        for &bytes in slot_bytes.iter() {
280            aliased_peak_bytes = aliased_peak_bytes.saturating_add(bytes);
281        }
282        RenderGraphSchedule3D {
283            ordered_passes,
284            culled_pass_count,
285            unaliased_bytes,
286            aliased_peak_bytes,
287            resource_pool_slots: pool_slots,
288        }
289    }
290
291    /// Executes every surviving pass in `schedule` in topological order by invoking `run_pass` with `(kind, name)`, recording zero-allocation pass execution.
292    ///
293    /// # Arguments
294    ///
295    /// - `&Self` - Mutable render graph.
296    /// - `&RenderGraphSchedule3D` - Compiled pass schedule from `compile`.
297    /// - `F` - Callback executing each pass and returning its duration in microseconds.
298    ///
299    /// # Returns
300    ///
301    /// - `usize` - Total number of active passes executed.
302    pub fn execute<F>(&mut self, schedule: &RenderGraphSchedule3D, mut run_pass: F) -> usize
303    where
304        F: FnMut(RenderPassKind3D, &str) -> u64,
305    {
306        let mut executed: usize = 0;
307        let passes: &mut Vec<RenderGraphPass3D> = self.get_mut_passes();
308        for &pass_id in schedule.get_ordered_passes().iter() {
309            if let Some(pass_mut) = passes.get_mut(pass_id) {
310                let kind: RenderPassKind3D = pass_mut.get_kind();
311                let duration_us: u64 = run_pass(kind, pass_mut.get_name().as_str());
312                pass_mut.set_last_duration_us(duration_us);
313                executed += 1;
314            }
315        }
316        executed
317    }
318
319    /// Builds the canonical UE5/Blender 3D frame graph (ComputeMorphSkin -> 4-Cascade CSM -> Hi-Z -> Nanite -> G-Buffer Principled PBR -> Clustered Lights -> Lumen GI -> Transmission -> Niagara -> TSR -> Bloom -> Present) for a viewport size and quality config.
320    ///
321    /// # Arguments
322    ///
323    /// - `u32` - Output viewport width in pixels.
324    /// - `u32` - Output viewport height in pixels.
325    /// - `&RenderQualityConfig` - Active graphics quality settings toggling RT, TSR, and bloom passes.
326    ///
327    /// # Returns
328    ///
329    /// - `Self` - Populated UE5 render dependency graph ready for compilation.
330    #[must_use]
331    pub fn build_ue5_frame_graph(
332        viewport_width: u32,
333        viewport_height: u32,
334        quality: &RenderQualityConfig,
335    ) -> Self {
336        let mut graph: Self = Self::default();
337        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 4.0);
338        let rw: usize = ((viewport_width as f32 * scale).round() as usize).max(1);
339        let rh: usize = ((viewport_height as f32 * scale).round() as usize).max(1);
340        let pixels: usize = rw.saturating_mul(rh);
341        let out_pixels: usize =
342            (viewport_width.max(1) as usize).saturating_mul(viewport_height.max(1) as usize);
343        let res_deformed: usize = graph.declare_resource(RDG_RES_DEFORMED, 65_536 * 64, false);
344        let res_vsm: usize =
345            graph.declare_resource(RDG_RES_VSM, 256 * 256 * VSM_CASCADE_COUNT * 4, false);
346        let res_hiz: usize = graph.declare_resource(RDG_RES_HIZ, (pixels / 64).max(64) * 8, false);
347        let res_gbuf: usize = graph.declare_resource(RDG_RES_GBUFFER, pixels * 8, false);
348        let res_clusters: usize = graph.declare_resource(RDG_RES_CLUSTERS, 2304 * 32, false);
349        let res_lumen: usize =
350            graph.declare_resource(RDG_RES_LUMEN, (pixels / 16).max(64) * 64, false);
351        let res_hdr: usize = graph.declare_resource(RDG_RES_HDR, pixels * 8, false);
352        let res_tsr: usize = graph.declare_resource(RDG_RES_TSR, out_pixels * 4, false);
353        let res_bloom: usize =
354            graph.declare_resource(RDG_RES_BLOOM, (pixels / 16).max(16) * 16, false);
355        let res_swapchain: usize = graph.declare_resource(RDG_RES_SWAPCHAIN, out_pixels * 4, true);
356        let _: usize = graph.add_pass(
357            RenderPassKind3D::ComputeMorphSkin,
358            RDG_PASS_MORPH_SKIN,
359            &[],
360            &[res_deformed],
361        );
362        let _: usize = graph.add_pass(
363            RenderPassKind3D::VirtualShadowMap,
364            RDG_PASS_VSM,
365            &[res_deformed],
366            &[res_vsm],
367        );
368        let _: usize = graph.add_pass(
369            RenderPassKind3D::HiZPrePass,
370            RDG_PASS_HIZ,
371            &[res_deformed],
372            &[res_hiz],
373        );
374        let _: usize = graph.add_pass(
375            RenderPassKind3D::NaniteVisibility,
376            RDG_PASS_NANITE,
377            &[res_deformed, res_hiz],
378            &[res_gbuf],
379        );
380        let _: usize = graph.add_pass(
381            RenderPassKind3D::ClusteredLighting,
382            RDG_PASS_CLUSTERS,
383            &[],
384            &[res_clusters],
385        );
386        let mut pbr_reads: Vec<usize> = vec![res_gbuf, res_clusters, res_vsm];
387        if quality.get_ray_tracing() != RayTracingMode::Off {
388            let _: usize = graph.add_pass(
389                RenderPassKind3D::LumenGlobalIllumination,
390                RDG_PASS_LUMEN,
391                &[res_gbuf, res_vsm],
392                &[res_lumen],
393            );
394            pbr_reads.push(res_lumen);
395        }
396        let _: usize = graph.add_pass(
397            RenderPassKind3D::DeferredGBufferPbr,
398            RDG_PASS_DEFERRED,
399            pbr_reads.as_slice(),
400            &[res_hdr],
401        );
402        let _: usize = graph.add_pass(
403            RenderPassKind3D::TransmissionAlphaBlend,
404            RDG_PASS_TRANSMISSION,
405            &[res_gbuf, res_hdr],
406            &[res_hdr],
407        );
408        let _: usize = graph.add_pass(
409            RenderPassKind3D::NiagaraParticles,
410            RDG_PASS_NIAGARA,
411            &[res_gbuf],
412            &[res_hdr],
413        );
414        let use_bloom: bool = matches!(
415            quality.get_preset(),
416            QualityPreset::High | QualityPreset::Ultra | QualityPreset::Cinematic
417        );
418        if use_bloom {
419            let _: usize = graph.add_pass(
420                RenderPassKind3D::PostProcessBloom,
421                RDG_PASS_BLOOM,
422                &[res_hdr],
423                &[res_bloom],
424            );
425        }
426        let _: usize = graph.add_pass(
427            RenderPassKind3D::TsrUpscale,
428            RDG_PASS_TSR,
429            &[res_hdr, res_gbuf],
430            &[res_tsr],
431        );
432        if use_bloom {
433            let _: usize = graph.add_pass(
434                RenderPassKind3D::HudCompositePresent,
435                RDG_PASS_PRESENT,
436                &[res_tsr, res_bloom],
437                &[res_swapchain],
438            );
439        } else {
440            let _: usize = graph.add_pass(
441                RenderPassKind3D::HudCompositePresent,
442                RDG_PASS_PRESENT,
443                &[res_tsr],
444                &[res_swapchain],
445            );
446        }
447        graph
448    }
449}
450
451/// GPU instanced draw packet construction with zero steady-state heap allocations for `GpuFramePacket3D`.
452impl GpuFramePacket3D {
453    /// Populates this `GpuFramePacket3D` in place from `world` (culling, LOD selection, Principled materials, 4-cascade CSM, IBL SH9, and bone palettes) reusing all buffer capacities for zero steady-state allocations.
454    ///
455    /// # Arguments
456    ///
457    /// - `&Self` - Mutable reusable frame packet overwritten in place.
458    /// - `&World3D` - Active 3D scene graph.
459    /// - `u32` - Target viewport width in pixels.
460    /// - `u32` - Target viewport height in pixels.
461    /// - `&RenderQualityConfig` - Active quality, draw distance, and LOD settings.
462    /// - `Mat4` - Previous frame view-projection matrix for GPU TSR velocity vectors.
463    /// - `&mut GpuFramePacketScratch3D` - Reusable scratch arena for zero-alloc sorting and bone palettes.
464    pub fn build_from_world_into(
465        &mut self,
466        world: &World3D,
467        viewport_width: u32,
468        viewport_height: u32,
469        quality: &RenderQualityConfig,
470        prev_view_projection: Mat4,
471        scratch: &mut GpuFramePacketScratch3D,
472    ) {
473        let cam: Camera3D = world.get_camera();
474        let aspect: f32 = (viewport_width.max(1) as f32) / (viewport_height.max(1) as f32);
475        let view_proj: Mat4 = world.active_view_projection(aspect);
476        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj);
477        let cam_pos: Vec3 = cam.get_position();
478        let half_h: f32 = (cam.get_fov_deg().to_radians() * 0.5).tan().max(0.05);
479        let focal_px: f32 = (viewport_height.max(1) as f32) * 0.5 / half_h;
480        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
481        let frustum_on: bool = quality.get_frustum_culling();
482        let chunk_on: bool = quality.get_chunk_streaming();
483        let lod_bias: f32 = quality.get_lod_bias();
484        let objects: &[SceneObject3D] = world.get_objects().as_slice();
485        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
486        let GpuFramePacketScratch3D {
487            keyed_instances,
488            skin_scratch,
489        } = scratch;
490        keyed_instances.clear();
491        if keyed_instances.capacity() < objects.len() {
492            keyed_instances.reserve(objects.len() - keyed_instances.len());
493        }
494        let Self {
495            instances,
496            batches,
497            materials,
498            bone_matrices,
499            ..
500        } = self;
501        materials.clear();
502        let src_mats: &[PrincipledMaterial3D] = world.get_principled_materials().as_slice();
503        if materials.capacity() < src_mats.len() {
504            materials.reserve(src_mats.len() - materials.len());
505        }
506        for mat_ref in src_mats.iter() {
507            materials.push(mat_ref.to_gpu_data());
508        }
509        bone_matrices.clear();
510        let scene_graph: &SceneGraph3D = world.get_scene_graph();
511        let skins: &[Skin3D] = world.get_skins().as_slice();
512        for (obj_idx, obj) in objects.iter().enumerate() {
513            if !world.is_object_visible(obj_idx) {
514                continue;
515            }
516            let wb: AxisAlignedBox3D = obj.get_world_bounds();
517            let dist_sq: f32 = wb.center().sub(cam_pos).length_sq();
518            if chunk_on && dist_sq > draw_dist_sq {
519                continue;
520            }
521            if frustum_on && !frustum.intersects_bounds(&wb) {
522                continue;
523            }
524            let Some(chain) = mesh_lib.get(obj.get_mesh_id()) else {
525                continue;
526            };
527            let (mesh, lod_idx): (&Mesh3D, usize) =
528                chain.select_screen_error(dist_sq.sqrt(), wb.radius(), focal_px, lod_bias);
529            let mat: PbrMaterial = obj.get_material();
530            let albedo: Vec3 = mat.get_base_color();
531            let emissive: Vec3 = mat.get_emissive();
532            let model_mat: Mat4 = obj.get_transform().to_mat4();
533            let model_elems: [f32; 16] = model_mat.get_elements();
534            let mut skin_palette_offset: u32 = u32::MAX;
535            let mut inst_flags: u32 = 0;
536            if let Some(skin_idx) = obj.try_get_skin_id()
537                && let Some(skin_ref) = skins.get(skin_idx as usize)
538            {
539                skin_palette_offset = bone_matrices.len() as u32;
540                skin_ref.compute_skin_matrices_into(model_mat, scene_graph, skin_scratch);
541                let palette_slice: &[Mat4] = skin_scratch.get_skin_matrices().as_slice();
542                if bone_matrices.capacity() < bone_matrices.len() + palette_slice.len() {
543                    bone_matrices.reserve(palette_slice.len());
544                }
545                bone_matrices.extend_from_slice(palette_slice);
546                inst_flags |= 1;
547            }
548            let mat_slot: u32 = obj.try_get_principled_material_id().unwrap_or(u32::MAX);
549            if mat_slot != u32::MAX {
550                inst_flags |= 2;
551            }
552            let morph_off: u32 = obj
553                .try_get_node_id()
554                .and_then(|nid: u32| scene_graph.get_nodes().get(nid as usize))
555                .map_or(0, SceneNode3D::get_morph_weight_offset);
556            keyed_instances.push((
557                obj.get_mesh_id(),
558                lod_idx,
559                mesh.get_indices().len() as u32,
560                GpuInstanceData3D {
561                    model_matrix: model_elems,
562                    albedo_metallic: [
563                        albedo.get_x(),
564                        albedo.get_y(),
565                        albedo.get_z(),
566                        mat.get_metallic(),
567                    ],
568                    emissive_roughness: [
569                        emissive.get_x(),
570                        emissive.get_y(),
571                        emissive.get_z(),
572                        mat.get_roughness(),
573                    ],
574                    material_skin_morph_flags: [
575                        mat_slot,
576                        skin_palette_offset,
577                        morph_off,
578                        inst_flags,
579                    ],
580                },
581            ));
582        }
583        keyed_instances.sort_unstable_by(
584            |left: &(usize, usize, u32, GpuInstanceData3D),
585             right: &(usize, usize, u32, GpuInstanceData3D)| {
586                left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))
587            },
588        );
589        instances.clear();
590        batches.clear();
591        if instances.capacity() < keyed_instances.len() {
592            instances.reserve(keyed_instances.len() - instances.len());
593        }
594        let mut total_triangles: usize = 0;
595        let mut cursor: usize = 0;
596        while cursor < keyed_instances.len() {
597            let (mesh_id, lod_idx, tri_per_inst, _): (usize, usize, u32, GpuInstanceData3D) =
598                keyed_instances[cursor];
599            let first_inst: u32 = instances.len() as u32;
600            let mut count: u32 = 0;
601            while cursor < keyed_instances.len()
602                && keyed_instances[cursor].0 == mesh_id
603                && keyed_instances[cursor].1 == lod_idx
604            {
605                instances.push(keyed_instances[cursor].3);
606                count += 1;
607                cursor += 1;
608            }
609            total_triangles =
610                total_triangles.saturating_add((tri_per_inst as usize) * (count as usize));
611            batches.push(GpuMeshDrawBatch3D::new(
612                mesh_id,
613                lod_idx,
614                first_inst,
615                count,
616                tri_per_inst,
617            ));
618        }
619        let csm_splits: [f32; VSM_CASCADE_COUNT] = VirtualShadowMap::compute_practical_splits(
620            cam.get_near().max(0.15),
621            cam.get_far().min(VSM_CSM_MAX_DISTANCE_M),
622            VSM_CSM_LAMBDA,
623        );
624        let ibl_sh: [[f32; 3]; 9] = world
625            .environment_ibl()
626            .map_or([[0.0; 3]; 9], EnvironmentIbl3D::get_sh_irradiance);
627        let graph: RenderGraph3D =
628            RenderGraph3D::build_ue5_frame_graph(viewport_width, viewport_height, quality);
629        let schedule: RenderGraphSchedule3D = graph.compile();
630        self.set_view_projection(view_proj);
631        self.set_prev_view_projection(prev_view_projection);
632        self.set_camera_position(cam_pos);
633        self.set_sun(world.get_sun());
634        self.set_csm_split_depths(csm_splits);
635        self.set_ibl_sh(ibl_sh);
636        self.set_use_agx_tonemap(world.get_use_agx_tonemap());
637        self.set_active_pass_count(schedule.get_ordered_passes().len());
638        self.set_total_triangles(total_triangles);
639    }
640
641    /// Synchronizes the 4-cascade CSM light view-projection matrices from an updated `VirtualShadowMap`.
642    ///
643    /// # Arguments
644    ///
645    /// - `&Self` - Mutable frame packet.
646    /// - `&VirtualShadowMap` - Updated 4-cascade directional shadow map.
647    pub fn apply_csm_matrices(&mut self, vsm: &VirtualShadowMap) {
648        let mut mats: [Mat4; VSM_CASCADE_COUNT] = [Mat4::identity(); VSM_CASCADE_COUNT];
649        for (cascade_idx, mat_slot) in mats.iter_mut().enumerate().take(VSM_CASCADE_COUNT) {
650            *mat_slot = vsm.cascade_light_view_proj(cascade_idx);
651        }
652        self.set_csm_matrices(mats);
653        self.set_csm_split_depths(vsm.get_cascade_split_depths());
654    }
655
656    /// Builds a frustum-culled, LOD-selected, mesh-sorted instanced `GpuFramePacket3D` directly from `world` ready for Metal/WebGPU/WebGL2/D3D12 submission.
657    ///
658    /// # Arguments
659    ///
660    /// - `&World3D` - Active 3D scene graph.
661    /// - `u32` - Target viewport width in pixels.
662    /// - `u32` - Target viewport height in pixels.
663    /// - `&RenderQualityConfig` - Active quality, draw distance, and LOD settings.
664    /// - `Mat4` - Previous frame view-projection matrix for GPU TSR velocity vectors.
665    ///
666    /// # Returns
667    ///
668    /// - `Self` - Deduplicated hardware instanced draw packet.
669    #[must_use]
670    pub fn build_from_world(
671        world: &World3D,
672        viewport_width: u32,
673        viewport_height: u32,
674        quality: &RenderQualityConfig,
675        prev_view_projection: Mat4,
676    ) -> Self {
677        let mut packet: Self = Self::default();
678        let mut scratch: GpuFramePacketScratch3D = GpuFramePacketScratch3D::default();
679        packet.build_from_world_into(
680            world,
681            viewport_width,
682            viewport_height,
683            quality,
684            prev_view_projection,
685            &mut scratch,
686        );
687        packet
688    }
689}