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 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            total_triangles: 0,
19        }
20    }
21}
22
23/// Cross-platform GPU 3D shader source lookup for `GpuShaderLanguage3D`.
24impl GpuShaderLanguage3D {
25    /// Resolves the canonical 3D shader language matching a runtime `GraphicsBackend`.
26    ///
27    /// # Arguments
28    ///
29    /// - `GraphicsBackend` - Active hardware graphics API backend.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Matching 3D GPU shader language.
34    #[must_use]
35    pub fn from_graphics_backend(backend: GraphicsBackend) -> Self {
36        match backend {
37            GraphicsBackend::Metal => Self::Msl,
38            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => Self::GlslEs3,
39            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => Self::Hlsl,
40            GraphicsBackend::WebGpu
41            | GraphicsBackend::Vulkan
42            | GraphicsBackend::SoftwareCpu
43            | GraphicsBackend::Canvas2d
44            | GraphicsBackend::Headless => Self::Wgsl,
45        }
46    }
47
48    /// Returns the primary unified or vertex 3D PBR shader source for this shader language.
49    ///
50    /// # Returns
51    ///
52    /// - `&'static str` - Validated GPU 3D PBR shader source string.
53    #[must_use]
54    pub const fn primary_pbr_shader_source(self) -> &'static str {
55        match self {
56            Self::Wgsl => WGSL_ENGINE3D_PBR_SHADER,
57            Self::Msl => MSL_ENGINE3D_PBR_SHADER,
58            Self::GlslEs3 => GLSL_ES3_ENGINE3D_VERTEX_SHADER,
59            Self::Hlsl => HLSL_ENGINE3D_PBR_SHADER,
60        }
61    }
62
63    /// Returns the paired fragment shader source when the backend splits vertex/fragment compilation (GLSL ES 3.0), or the unified shader otherwise.
64    ///
65    /// # Returns
66    ///
67    /// - `&'static str` - Validated GPU 3D PBR fragment shader source string.
68    #[must_use]
69    pub const fn fragment_pbr_shader_source(self) -> &'static str {
70        match self {
71            Self::GlslEs3 => GLSL_ES3_ENGINE3D_FRAGMENT_SHADER,
72            Self::Wgsl => WGSL_ENGINE3D_PBR_SHADER,
73            Self::Msl => MSL_ENGINE3D_PBR_SHADER,
74            Self::Hlsl => HLSL_ENGINE3D_PBR_SHADER,
75        }
76    }
77}
78
79/// Declarative UE5 Render Dependency Graph building, dead-pass culling, topological sorting, and transient memory aliasing for `RenderGraph3D`.
80impl RenderGraph3D {
81    /// Resets all declared resources and passes while retaining vector capacities for zero-allocation per-frame graph rebuilds.
82    pub fn reset(&mut self) {
83        self.get_mut_resources().clear();
84        self.get_mut_passes().clear();
85    }
86
87    /// Declares a transient render-target or buffer resource inside this render graph and returns its `resource_id`.
88    ///
89    /// # Arguments
90    ///
91    /// - `&str` - Human-readable resource label.
92    /// - `usize` - Memory footprint in bytes.
93    /// - `bool` - Whether this resource is an external swapchain/output anchor.
94    ///
95    /// # Returns
96    ///
97    /// - `usize` - Assigned resource identifier.
98    pub fn declare_resource(
99        &mut self,
100        name: &str,
101        size_bytes: usize,
102        is_external_output: bool,
103    ) -> usize {
104        let id: usize = self.get_resources().len();
105        self.get_mut_resources().push(RenderGraphResource3D {
106            resource_id: id,
107            name: name.to_string(),
108            size_bytes,
109            is_external_output,
110        });
111        id
112    }
113
114    /// Declares a render pass with explicit `reads` and `writes` resource dependencies and returns its `pass_id`.
115    ///
116    /// # Arguments
117    ///
118    /// - `RenderPassKind3D` - Pass category.
119    /// - `&str` - Diagnostic pass name.
120    /// - `&[usize]` - Resource IDs read by this pass.
121    /// - `&[usize]` - Resource IDs written by this pass.
122    ///
123    /// # Returns
124    ///
125    /// - `usize` - Assigned pass identifier.
126    pub fn add_pass(
127        &mut self,
128        kind: RenderPassKind3D,
129        name: &str,
130        reads: &[usize],
131        writes: &[usize],
132    ) -> usize {
133        let id: usize = self.get_passes().len();
134        self.get_mut_passes().push(RenderGraphPass3D {
135            pass_id: id,
136            kind,
137            name: name.to_string(),
138            reads: reads.to_vec(),
139            writes: writes.to_vec(),
140            last_duration_us: 0,
141        });
142        id
143    }
144
145    /// Compiles this render graph by performing backward liveness dead-pass culling from external outputs, topological pass ordering, and greedy transient memory aliasing.
146    ///
147    /// # Returns
148    ///
149    /// - `RenderGraphSchedule3D` - Compiled pass execution schedule and aliased VRAM footprint.
150    #[must_use]
151    pub fn compile(&self) -> RenderGraphSchedule3D {
152        let res_count: usize = self.get_resources().len();
153        let pass_count: usize = self.get_passes().len();
154        if pass_count == 0 {
155            return RenderGraphSchedule3D::default();
156        }
157        let resources: &[RenderGraphResource3D] = self.get_resources().as_slice();
158        let passes: &[RenderGraphPass3D] = self.get_passes().as_slice();
159        let mut live_res: Vec<bool> = vec![false; res_count];
160        let mut live_pass: Vec<bool> = vec![false; pass_count];
161        for resource in resources.iter() {
162            if resource.get_is_external_output() {
163                live_res[resource.get_resource_id()] = true;
164            }
165        }
166        let mut changed: bool = true;
167        while changed {
168            changed = false;
169            for pass in passes.iter().rev() {
170                let pid: usize = pass.get_pass_id();
171                if live_pass[pid] {
172                    continue;
173                }
174                let produces_live: bool = pass
175                    .get_writes()
176                    .iter()
177                    .any(|&rid: &usize| rid < res_count && live_res[rid]);
178                if produces_live {
179                    live_pass[pid] = true;
180                    changed = true;
181                    for &rid in pass.get_reads().iter() {
182                        if rid < res_count && !live_res[rid] {
183                            live_res[rid] = true;
184                        }
185                    }
186                }
187            }
188        }
189        let mut ordered_passes: Vec<usize> = Vec::with_capacity(pass_count);
190        for (pid, &is_live) in live_pass.iter().enumerate() {
191            if is_live {
192                ordered_passes.push(pid);
193            }
194        }
195        let culled_pass_count: usize = pass_count.saturating_sub(ordered_passes.len());
196        let mut first_use: Vec<usize> = vec![usize::MAX; res_count];
197        let mut last_use: Vec<usize> = vec![0; res_count];
198        for (exec_idx, &pid) in ordered_passes.iter().enumerate() {
199            let pass: &RenderGraphPass3D = &passes[pid];
200            for &rid in pass.get_writes().iter().chain(pass.get_reads().iter()) {
201                if rid < res_count {
202                    first_use[rid] = first_use[rid].min(exec_idx);
203                    last_use[rid] = last_use[rid].max(exec_idx);
204                }
205            }
206        }
207        let mut unaliased_bytes: usize = 0;
208        let mut pool_slots: Vec<usize> = vec![usize::MAX; res_count];
209        let mut slot_end_step: Vec<usize> = Vec::new();
210        let mut slot_bytes: Vec<usize> = Vec::new();
211        let mut transient_ids: Vec<usize> = Vec::new();
212        for (rid, resource) in resources.iter().enumerate() {
213            if first_use[rid] == usize::MAX || resource.get_is_external_output() {
214                continue;
215            }
216            unaliased_bytes = unaliased_bytes.saturating_add(resource.get_size_bytes());
217            transient_ids.push(rid);
218        }
219        transient_ids.sort_unstable_by(|left_id: &usize, right_id: &usize| {
220            first_use[*left_id]
221                .cmp(&first_use[*right_id])
222                .then_with(|| {
223                    resources[*right_id]
224                        .get_size_bytes()
225                        .cmp(&resources[*left_id].get_size_bytes())
226                })
227        });
228        for rid in transient_ids.into_iter() {
229            let start_step: usize = first_use[rid];
230            let end_step: usize = last_use[rid];
231            let req_bytes: usize = resources[rid].get_size_bytes();
232            let mut best_slot: Option<usize> = None;
233            let mut best_diff: usize = usize::MAX;
234            for (slot_idx, &prev_end) in slot_end_step.iter().enumerate() {
235                if prev_end < start_step {
236                    let diff: usize = slot_bytes[slot_idx].abs_diff(req_bytes);
237                    if diff < best_diff {
238                        best_diff = diff;
239                        best_slot = Some(slot_idx);
240                    }
241                }
242            }
243            if let Some(reused) = best_slot {
244                slot_end_step[reused] = end_step;
245                if req_bytes > slot_bytes[reused] {
246                    slot_bytes[reused] = req_bytes;
247                }
248                pool_slots[rid] = reused;
249            } else {
250                let new_slot: usize = slot_bytes.len();
251                slot_end_step.push(end_step);
252                slot_bytes.push(req_bytes);
253                pool_slots[rid] = new_slot;
254            }
255        }
256        let mut aliased_peak_bytes: usize = 0;
257        for &bytes in slot_bytes.iter() {
258            aliased_peak_bytes = aliased_peak_bytes.saturating_add(bytes);
259        }
260        RenderGraphSchedule3D {
261            ordered_passes,
262            culled_pass_count,
263            unaliased_bytes,
264            aliased_peak_bytes,
265            resource_pool_slots: pool_slots,
266        }
267    }
268
269    /// Builds the canonical UE5-aligned 3D frame graph (VSM -> Hi-Z -> Nanite -> G-Buffer PBR -> Clustered Lights -> Lumen GI -> Niagara -> TSR -> Bloom -> Present) for a viewport size and quality config.
270    ///
271    /// # Arguments
272    ///
273    /// - `u32` - Output viewport width in pixels.
274    /// - `u32` - Output viewport height in pixels.
275    /// - `&RenderQualityConfig` - Active graphics quality settings toggling RT, TSR, and bloom passes.
276    ///
277    /// # Returns
278    ///
279    /// - `Self` - Populated UE5 render dependency graph ready for compilation.
280    #[must_use]
281    pub fn build_ue5_frame_graph(
282        viewport_width: u32,
283        viewport_height: u32,
284        quality: &RenderQualityConfig,
285    ) -> Self {
286        let mut graph: Self = Self::default();
287        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 2.0);
288        let rw: usize = ((viewport_width as f32 * scale).round() as usize).max(160);
289        let rh: usize = ((viewport_height as f32 * scale).round() as usize).max(144);
290        let pixels: usize = rw * rh;
291        let out_pixels: usize =
292            (viewport_width.max(1) as usize) * (viewport_height.max(1) as usize);
293        let res_vsm: usize = graph.declare_resource(RDG_RES_VSM, 256 * 256 * 4 * 2, false);
294        let res_hiz: usize = graph.declare_resource(RDG_RES_HIZ, (pixels / 64).max(64) * 8, false);
295        let res_gbuf: usize = graph.declare_resource(RDG_RES_GBUFFER, pixels * 8, false);
296        let res_clusters: usize = graph.declare_resource(RDG_RES_CLUSTERS, 2304 * 32, false);
297        let res_lumen: usize =
298            graph.declare_resource(RDG_RES_LUMEN, (pixels / 16).max(64) * 64, false);
299        let res_hdr: usize = graph.declare_resource(RDG_RES_HDR, pixels * 8, false);
300        let res_tsr: usize = graph.declare_resource(RDG_RES_TSR, out_pixels * 4, false);
301        let res_bloom: usize =
302            graph.declare_resource(RDG_RES_BLOOM, (pixels / 16).max(16) * 16, false);
303        let res_swapchain: usize = graph.declare_resource(RDG_RES_SWAPCHAIN, out_pixels * 4, true);
304        let _: usize = graph.add_pass(
305            RenderPassKind3D::VirtualShadowMap,
306            RDG_PASS_VSM,
307            &[],
308            &[res_vsm],
309        );
310        let _: usize = graph.add_pass(RenderPassKind3D::HiZPrePass, RDG_PASS_HIZ, &[], &[res_hiz]);
311        let _: usize = graph.add_pass(
312            RenderPassKind3D::NaniteVisibility,
313            RDG_PASS_NANITE,
314            &[res_hiz],
315            &[res_gbuf],
316        );
317        let _: usize = graph.add_pass(
318            RenderPassKind3D::ClusteredLighting,
319            RDG_PASS_CLUSTERS,
320            &[],
321            &[res_clusters],
322        );
323        let mut pbr_reads: Vec<usize> = vec![res_gbuf, res_clusters, res_vsm];
324        if quality.get_ray_tracing() != RayTracingMode::Off {
325            let _: usize = graph.add_pass(
326                RenderPassKind3D::LumenGlobalIllumination,
327                RDG_PASS_LUMEN,
328                &[res_gbuf, res_vsm],
329                &[res_lumen],
330            );
331            pbr_reads.push(res_lumen);
332        }
333        let _: usize = graph.add_pass(
334            RenderPassKind3D::DeferredGBufferPbr,
335            RDG_PASS_DEFERRED,
336            pbr_reads.as_slice(),
337            &[res_hdr],
338        );
339        let _: usize = graph.add_pass(
340            RenderPassKind3D::NiagaraParticles,
341            RDG_PASS_NIAGARA,
342            &[res_gbuf],
343            &[res_hdr],
344        );
345        let use_bloom: bool = matches!(
346            quality.get_preset(),
347            QualityPreset::High | QualityPreset::Ultra | QualityPreset::Cinematic
348        );
349        if use_bloom {
350            let _: usize = graph.add_pass(
351                RenderPassKind3D::PostProcessBloom,
352                RDG_PASS_BLOOM,
353                &[res_hdr],
354                &[res_bloom],
355            );
356        }
357        let _: usize = graph.add_pass(
358            RenderPassKind3D::TsrUpscale,
359            RDG_PASS_TSR,
360            &[res_hdr, res_gbuf],
361            &[res_tsr],
362        );
363        if use_bloom {
364            let _: usize = graph.add_pass(
365                RenderPassKind3D::HudCompositePresent,
366                RDG_PASS_PRESENT,
367                &[res_tsr, res_bloom],
368                &[res_swapchain],
369            );
370        } else {
371            let _: usize = graph.add_pass(
372                RenderPassKind3D::HudCompositePresent,
373                RDG_PASS_PRESENT,
374                &[res_tsr],
375                &[res_swapchain],
376            );
377        }
378        graph
379    }
380}
381
382/// GPU instanced draw packet construction for `GpuFramePacket3D`.
383impl GpuFramePacket3D {
384    /// Builds a frustum-culled, LOD-selected, mesh-sorted instanced `GpuFramePacket3D` directly from `world` ready for Metal/WebGPU/WebGL2/D3D12 submission.
385    ///
386    /// # Arguments
387    ///
388    /// - `&World3D` - Active 3D scene graph.
389    /// - `u32` - Target viewport width in pixels.
390    /// - `u32` - Target viewport height in pixels.
391    /// - `&RenderQualityConfig` - Active quality, draw distance, and LOD settings.
392    /// - `Mat4` - Previous frame view-projection matrix for GPU TSR velocity vectors.
393    ///
394    /// # Returns
395    ///
396    /// - `Self` - Deduplicated hardware instanced draw packet.
397    #[must_use]
398    pub fn build_from_world(
399        world: &World3D,
400        viewport_width: u32,
401        viewport_height: u32,
402        quality: &RenderQualityConfig,
403        prev_view_projection: Mat4,
404    ) -> Self {
405        let cam: Camera3D = world.get_camera();
406        let aspect: f32 = (viewport_width.max(1) as f32) / (viewport_height.max(1) as f32);
407        let view_proj: Mat4 = cam.view_projection(aspect);
408        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj);
409        let cam_pos: Vec3 = cam.get_position();
410        let half_h: f32 = (cam.get_fov_deg().to_radians() * 0.5).tan().max(0.05);
411        let focal_px: f32 = (viewport_height.max(1) as f32) * 0.5 / half_h;
412        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
413        let frustum_on: bool = quality.get_frustum_culling();
414        let chunk_on: bool = quality.get_chunk_streaming();
415        let lod_bias: f32 = quality.get_lod_bias();
416        let objects: &[SceneObject3D] = world.get_objects().as_slice();
417        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
418        let mut keyed: Vec<(usize, usize, u32, GpuInstanceData3D)> =
419            Vec::with_capacity(objects.len());
420        for obj in objects.iter() {
421            let wb: AxisAlignedBox3D = obj.get_world_bounds();
422            let dist_sq: f32 = wb.center().sub(cam_pos).length_sq();
423            if chunk_on && dist_sq > draw_dist_sq {
424                continue;
425            }
426            if frustum_on && !frustum.intersects_bounds(&wb) {
427                continue;
428            }
429            let Some(chain) = mesh_lib.get(obj.get_mesh_id()) else {
430                continue;
431            };
432            let (mesh, lod_idx): (&Mesh3D, usize) =
433                chain.select_screen_error(dist_sq.sqrt(), wb.radius(), focal_px, lod_bias);
434            let mat: PbrMaterial = obj.get_material();
435            let albedo: Vec3 = mat.get_base_color();
436            let emissive: Vec3 = mat.get_emissive();
437            let model_elems: [f32; 16] = obj.get_transform().to_mat4().get_elements();
438            keyed.push((
439                obj.get_mesh_id(),
440                lod_idx,
441                mesh.get_indices().len() as u32,
442                GpuInstanceData3D {
443                    model_matrix: model_elems,
444                    albedo_metallic: [
445                        albedo.get_x(),
446                        albedo.get_y(),
447                        albedo.get_z(),
448                        mat.get_metallic(),
449                    ],
450                    emissive_roughness: [
451                        emissive.get_x(),
452                        emissive.get_y(),
453                        emissive.get_z(),
454                        mat.get_roughness(),
455                    ],
456                },
457            ));
458        }
459        keyed.sort_unstable_by(
460            |left: &(usize, usize, u32, GpuInstanceData3D),
461             right: &(usize, usize, u32, GpuInstanceData3D)| {
462                left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))
463            },
464        );
465        let mut instances: Vec<GpuInstanceData3D> = Vec::with_capacity(keyed.len());
466        let mut batches: Vec<GpuMeshDrawBatch3D> = Vec::new();
467        let mut total_triangles: usize = 0;
468        let mut cursor: usize = 0;
469        while cursor < keyed.len() {
470            let (mesh_id, lod_idx, tri_per_inst, _): (usize, usize, u32, GpuInstanceData3D) =
471                keyed[cursor];
472            let first_inst: u32 = instances.len() as u32;
473            let mut count: u32 = 0;
474            while cursor < keyed.len() && keyed[cursor].0 == mesh_id && keyed[cursor].1 == lod_idx {
475                instances.push(keyed[cursor].3);
476                count += 1;
477                cursor += 1;
478            }
479            total_triangles =
480                total_triangles.saturating_add((tri_per_inst as usize) * (count as usize));
481            batches.push(GpuMeshDrawBatch3D::new(
482                mesh_id,
483                lod_idx,
484                first_inst,
485                count,
486                tri_per_inst,
487            ));
488        }
489        Self {
490            view_projection: view_proj,
491            prev_view_projection,
492            camera_position: cam_pos,
493            sun: world.get_sun(),
494            instances,
495            batches,
496            total_triangles,
497        }
498    }
499}