euv-core 0.50.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use super::*;

/// Default identity-camera `GpuFramePacket3D`.
impl Default for GpuFramePacket3D {
    /// Creates an empty `GpuFramePacket3D` initialized with identity camera matrices.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty GPU 3D frame packet.
    fn default() -> Self {
        Self {
            view_projection: Mat4::identity(),
            prev_view_projection: Mat4::identity(),
            camera_position: Vec3::zero(),
            sun: DirectionalLight3D::default(),
            instances: Vec::new(),
            batches: Vec::new(),
            total_triangles: 0,
        }
    }
}

/// Cross-platform GPU 3D shader source lookup for `GpuShaderLanguage3D`.
impl GpuShaderLanguage3D {
    /// Resolves the canonical 3D shader language matching a runtime `GraphicsBackend`.
    ///
    /// # Arguments
    ///
    /// - `GraphicsBackend` - Active hardware graphics API backend.
    ///
    /// # Returns
    ///
    /// - `Self` - Matching 3D GPU shader language.
    #[must_use]
    pub fn from_graphics_backend(backend: GraphicsBackend) -> Self {
        match backend {
            GraphicsBackend::Metal => Self::Msl,
            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => Self::GlslEs3,
            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => Self::Hlsl,
            GraphicsBackend::WebGpu
            | GraphicsBackend::Vulkan
            | GraphicsBackend::SoftwareCpu
            | GraphicsBackend::Canvas2d
            | GraphicsBackend::Headless => Self::Wgsl,
        }
    }

    /// Returns the primary unified or vertex 3D PBR shader source for this shader language.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Validated GPU 3D PBR shader source string.
    #[must_use]
    pub const fn primary_pbr_shader_source(self) -> &'static str {
        match self {
            Self::Wgsl => WGSL_ENGINE3D_PBR_SHADER,
            Self::Msl => MSL_ENGINE3D_PBR_SHADER,
            Self::GlslEs3 => GLSL_ES3_ENGINE3D_VERTEX_SHADER,
            Self::Hlsl => HLSL_ENGINE3D_PBR_SHADER,
        }
    }

    /// Returns the paired fragment shader source when the backend splits vertex/fragment compilation (GLSL ES 3.0), or the unified shader otherwise.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Validated GPU 3D PBR fragment shader source string.
    #[must_use]
    pub const fn fragment_pbr_shader_source(self) -> &'static str {
        match self {
            Self::GlslEs3 => GLSL_ES3_ENGINE3D_FRAGMENT_SHADER,
            Self::Wgsl => WGSL_ENGINE3D_PBR_SHADER,
            Self::Msl => MSL_ENGINE3D_PBR_SHADER,
            Self::Hlsl => HLSL_ENGINE3D_PBR_SHADER,
        }
    }
}

/// Declarative UE5 Render Dependency Graph building, dead-pass culling, topological sorting, and transient memory aliasing for `RenderGraph3D`.
impl RenderGraph3D {
    /// Resets all declared resources and passes while retaining vector capacities for zero-allocation per-frame graph rebuilds.
    pub fn reset(&mut self) {
        self.get_mut_resources().clear();
        self.get_mut_passes().clear();
    }

    /// Declares a transient render-target or buffer resource inside this render graph and returns its `resource_id`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Human-readable resource label.
    /// - `usize` - Memory footprint in bytes.
    /// - `bool` - Whether this resource is an external swapchain/output anchor.
    ///
    /// # Returns
    ///
    /// - `usize` - Assigned resource identifier.
    pub fn declare_resource(
        &mut self,
        name: &str,
        size_bytes: usize,
        is_external_output: bool,
    ) -> usize {
        let id: usize = self.get_resources().len();
        self.get_mut_resources().push(RenderGraphResource3D {
            resource_id: id,
            name: name.to_string(),
            size_bytes,
            is_external_output,
        });
        id
    }

    /// Declares a render pass with explicit `reads` and `writes` resource dependencies and returns its `pass_id`.
    ///
    /// # Arguments
    ///
    /// - `RenderPassKind3D` - Pass category.
    /// - `&str` - Diagnostic pass name.
    /// - `&[usize]` - Resource IDs read by this pass.
    /// - `&[usize]` - Resource IDs written by this pass.
    ///
    /// # Returns
    ///
    /// - `usize` - Assigned pass identifier.
    pub fn add_pass(
        &mut self,
        kind: RenderPassKind3D,
        name: &str,
        reads: &[usize],
        writes: &[usize],
    ) -> usize {
        let id: usize = self.get_passes().len();
        self.get_mut_passes().push(RenderGraphPass3D {
            pass_id: id,
            kind,
            name: name.to_string(),
            reads: reads.to_vec(),
            writes: writes.to_vec(),
            last_duration_us: 0,
        });
        id
    }

    /// Compiles this render graph by performing backward liveness dead-pass culling from external outputs, topological pass ordering, and greedy transient memory aliasing.
    ///
    /// # Returns
    ///
    /// - `RenderGraphSchedule3D` - Compiled pass execution schedule and aliased VRAM footprint.
    #[must_use]
    pub fn compile(&self) -> RenderGraphSchedule3D {
        let res_count: usize = self.get_resources().len();
        let pass_count: usize = self.get_passes().len();
        if pass_count == 0 {
            return RenderGraphSchedule3D::default();
        }
        let resources: &[RenderGraphResource3D] = self.get_resources().as_slice();
        let passes: &[RenderGraphPass3D] = self.get_passes().as_slice();
        let mut live_res: Vec<bool> = vec![false; res_count];
        let mut live_pass: Vec<bool> = vec![false; pass_count];
        for resource in resources.iter() {
            if resource.get_is_external_output() {
                live_res[resource.get_resource_id()] = true;
            }
        }
        let mut changed: bool = true;
        while changed {
            changed = false;
            for pass in passes.iter().rev() {
                let pid: usize = pass.get_pass_id();
                if live_pass[pid] {
                    continue;
                }
                let produces_live: bool = pass
                    .get_writes()
                    .iter()
                    .any(|&rid: &usize| rid < res_count && live_res[rid]);
                if produces_live {
                    live_pass[pid] = true;
                    changed = true;
                    for &rid in pass.get_reads().iter() {
                        if rid < res_count && !live_res[rid] {
                            live_res[rid] = true;
                        }
                    }
                }
            }
        }
        let mut ordered_passes: Vec<usize> = Vec::with_capacity(pass_count);
        for (pid, &is_live) in live_pass.iter().enumerate() {
            if is_live {
                ordered_passes.push(pid);
            }
        }
        let culled_pass_count: usize = pass_count.saturating_sub(ordered_passes.len());
        let mut first_use: Vec<usize> = vec![usize::MAX; res_count];
        let mut last_use: Vec<usize> = vec![0; res_count];
        for (exec_idx, &pid) in ordered_passes.iter().enumerate() {
            let pass: &RenderGraphPass3D = &passes[pid];
            for &rid in pass.get_writes().iter().chain(pass.get_reads().iter()) {
                if rid < res_count {
                    first_use[rid] = first_use[rid].min(exec_idx);
                    last_use[rid] = last_use[rid].max(exec_idx);
                }
            }
        }
        let mut unaliased_bytes: usize = 0;
        let mut pool_slots: Vec<usize> = vec![usize::MAX; res_count];
        let mut slot_end_step: Vec<usize> = Vec::new();
        let mut slot_bytes: Vec<usize> = Vec::new();
        let mut transient_ids: Vec<usize> = Vec::new();
        for (rid, resource) in resources.iter().enumerate() {
            if first_use[rid] == usize::MAX || resource.get_is_external_output() {
                continue;
            }
            unaliased_bytes = unaliased_bytes.saturating_add(resource.get_size_bytes());
            transient_ids.push(rid);
        }
        transient_ids.sort_unstable_by(|left_id: &usize, right_id: &usize| {
            first_use[*left_id]
                .cmp(&first_use[*right_id])
                .then_with(|| {
                    resources[*right_id]
                        .get_size_bytes()
                        .cmp(&resources[*left_id].get_size_bytes())
                })
        });
        for rid in transient_ids.into_iter() {
            let start_step: usize = first_use[rid];
            let end_step: usize = last_use[rid];
            let req_bytes: usize = resources[rid].get_size_bytes();
            let mut best_slot: Option<usize> = None;
            let mut best_diff: usize = usize::MAX;
            for (slot_idx, &prev_end) in slot_end_step.iter().enumerate() {
                if prev_end < start_step {
                    let diff: usize = slot_bytes[slot_idx].abs_diff(req_bytes);
                    if diff < best_diff {
                        best_diff = diff;
                        best_slot = Some(slot_idx);
                    }
                }
            }
            if let Some(reused) = best_slot {
                slot_end_step[reused] = end_step;
                if req_bytes > slot_bytes[reused] {
                    slot_bytes[reused] = req_bytes;
                }
                pool_slots[rid] = reused;
            } else {
                let new_slot: usize = slot_bytes.len();
                slot_end_step.push(end_step);
                slot_bytes.push(req_bytes);
                pool_slots[rid] = new_slot;
            }
        }
        let mut aliased_peak_bytes: usize = 0;
        for &bytes in slot_bytes.iter() {
            aliased_peak_bytes = aliased_peak_bytes.saturating_add(bytes);
        }
        RenderGraphSchedule3D {
            ordered_passes,
            culled_pass_count,
            unaliased_bytes,
            aliased_peak_bytes,
            resource_pool_slots: pool_slots,
        }
    }

    /// 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.
    ///
    /// # Arguments
    ///
    /// - `u32` - Output viewport width in pixels.
    /// - `u32` - Output viewport height in pixels.
    /// - `&RenderQualityConfig` - Active graphics quality settings toggling RT, TSR, and bloom passes.
    ///
    /// # Returns
    ///
    /// - `Self` - Populated UE5 render dependency graph ready for compilation.
    #[must_use]
    pub fn build_ue5_frame_graph(
        viewport_width: u32,
        viewport_height: u32,
        quality: &RenderQualityConfig,
    ) -> Self {
        let mut graph: Self = Self::default();
        let scale: f32 = quality.get_resolution_scale().clamp(0.40, 2.0);
        let rw: usize = ((viewport_width as f32 * scale).round() as usize).max(160);
        let rh: usize = ((viewport_height as f32 * scale).round() as usize).max(144);
        let pixels: usize = rw * rh;
        let out_pixels: usize =
            (viewport_width.max(1) as usize) * (viewport_height.max(1) as usize);
        let res_vsm: usize = graph.declare_resource(RDG_RES_VSM, 256 * 256 * 4 * 2, false);
        let res_hiz: usize = graph.declare_resource(RDG_RES_HIZ, (pixels / 64).max(64) * 8, false);
        let res_gbuf: usize = graph.declare_resource(RDG_RES_GBUFFER, pixels * 8, false);
        let res_clusters: usize = graph.declare_resource(RDG_RES_CLUSTERS, 2304 * 32, false);
        let res_lumen: usize =
            graph.declare_resource(RDG_RES_LUMEN, (pixels / 16).max(64) * 64, false);
        let res_hdr: usize = graph.declare_resource(RDG_RES_HDR, pixels * 8, false);
        let res_tsr: usize = graph.declare_resource(RDG_RES_TSR, out_pixels * 4, false);
        let res_bloom: usize =
            graph.declare_resource(RDG_RES_BLOOM, (pixels / 16).max(16) * 16, false);
        let res_swapchain: usize = graph.declare_resource(RDG_RES_SWAPCHAIN, out_pixels * 4, true);
        let _: usize = graph.add_pass(
            RenderPassKind3D::VirtualShadowMap,
            RDG_PASS_VSM,
            &[],
            &[res_vsm],
        );
        let _: usize = graph.add_pass(RenderPassKind3D::HiZPrePass, RDG_PASS_HIZ, &[], &[res_hiz]);
        let _: usize = graph.add_pass(
            RenderPassKind3D::NaniteVisibility,
            RDG_PASS_NANITE,
            &[res_hiz],
            &[res_gbuf],
        );
        let _: usize = graph.add_pass(
            RenderPassKind3D::ClusteredLighting,
            RDG_PASS_CLUSTERS,
            &[],
            &[res_clusters],
        );
        let mut pbr_reads: Vec<usize> = vec![res_gbuf, res_clusters, res_vsm];
        if quality.get_ray_tracing() != RayTracingMode::Off {
            let _: usize = graph.add_pass(
                RenderPassKind3D::LumenGlobalIllumination,
                RDG_PASS_LUMEN,
                &[res_gbuf, res_vsm],
                &[res_lumen],
            );
            pbr_reads.push(res_lumen);
        }
        let _: usize = graph.add_pass(
            RenderPassKind3D::DeferredGBufferPbr,
            RDG_PASS_DEFERRED,
            pbr_reads.as_slice(),
            &[res_hdr],
        );
        let _: usize = graph.add_pass(
            RenderPassKind3D::NiagaraParticles,
            RDG_PASS_NIAGARA,
            &[res_gbuf],
            &[res_hdr],
        );
        let use_bloom: bool = matches!(
            quality.get_preset(),
            QualityPreset::High | QualityPreset::Ultra | QualityPreset::Cinematic
        );
        if use_bloom {
            let _: usize = graph.add_pass(
                RenderPassKind3D::PostProcessBloom,
                RDG_PASS_BLOOM,
                &[res_hdr],
                &[res_bloom],
            );
        }
        let _: usize = graph.add_pass(
            RenderPassKind3D::TsrUpscale,
            RDG_PASS_TSR,
            &[res_hdr, res_gbuf],
            &[res_tsr],
        );
        if use_bloom {
            let _: usize = graph.add_pass(
                RenderPassKind3D::HudCompositePresent,
                RDG_PASS_PRESENT,
                &[res_tsr, res_bloom],
                &[res_swapchain],
            );
        } else {
            let _: usize = graph.add_pass(
                RenderPassKind3D::HudCompositePresent,
                RDG_PASS_PRESENT,
                &[res_tsr],
                &[res_swapchain],
            );
        }
        graph
    }
}

/// GPU instanced draw packet construction for `GpuFramePacket3D`.
impl GpuFramePacket3D {
    /// Builds a frustum-culled, LOD-selected, mesh-sorted instanced `GpuFramePacket3D` directly from `world` ready for Metal/WebGPU/WebGL2/D3D12 submission.
    ///
    /// # Arguments
    ///
    /// - `&World3D` - Active 3D scene graph.
    /// - `u32` - Target viewport width in pixels.
    /// - `u32` - Target viewport height in pixels.
    /// - `&RenderQualityConfig` - Active quality, draw distance, and LOD settings.
    /// - `Mat4` - Previous frame view-projection matrix for GPU TSR velocity vectors.
    ///
    /// # Returns
    ///
    /// - `Self` - Deduplicated hardware instanced draw packet.
    #[must_use]
    pub fn build_from_world(
        world: &World3D,
        viewport_width: u32,
        viewport_height: u32,
        quality: &RenderQualityConfig,
        prev_view_projection: Mat4,
    ) -> Self {
        let cam: Camera3D = world.get_camera();
        let aspect: f32 = (viewport_width.max(1) as f32) / (viewport_height.max(1) as f32);
        let view_proj: Mat4 = cam.view_projection(aspect);
        let frustum: Frustum3D = Frustum3D::from_view_proj(&view_proj);
        let cam_pos: Vec3 = cam.get_position();
        let half_h: f32 = (cam.get_fov_deg().to_radians() * 0.5).tan().max(0.05);
        let focal_px: f32 = (viewport_height.max(1) as f32) * 0.5 / half_h;
        let draw_dist_sq: f32 = quality.get_draw_distance() * quality.get_draw_distance();
        let frustum_on: bool = quality.get_frustum_culling();
        let chunk_on: bool = quality.get_chunk_streaming();
        let lod_bias: f32 = quality.get_lod_bias();
        let objects: &[SceneObject3D] = world.get_objects().as_slice();
        let mesh_lib: &[MeshLodChain] = world.get_mesh_library().as_slice();
        let mut keyed: Vec<(usize, usize, u32, GpuInstanceData3D)> =
            Vec::with_capacity(objects.len());
        for obj in objects.iter() {
            let wb: AxisAlignedBox3D = obj.get_world_bounds();
            let dist_sq: f32 = wb.center().sub(cam_pos).length_sq();
            if chunk_on && dist_sq > draw_dist_sq {
                continue;
            }
            if frustum_on && !frustum.intersects_bounds(&wb) {
                continue;
            }
            let Some(chain) = mesh_lib.get(obj.get_mesh_id()) else {
                continue;
            };
            let (mesh, lod_idx): (&Mesh3D, usize) =
                chain.select_screen_error(dist_sq.sqrt(), wb.radius(), focal_px, lod_bias);
            let mat: PbrMaterial = obj.get_material();
            let albedo: Vec3 = mat.get_base_color();
            let emissive: Vec3 = mat.get_emissive();
            let model_elems: [f32; 16] = obj.get_transform().to_mat4().get_elements();
            keyed.push((
                obj.get_mesh_id(),
                lod_idx,
                mesh.get_indices().len() as u32,
                GpuInstanceData3D {
                    model_matrix: model_elems,
                    albedo_metallic: [
                        albedo.get_x(),
                        albedo.get_y(),
                        albedo.get_z(),
                        mat.get_metallic(),
                    ],
                    emissive_roughness: [
                        emissive.get_x(),
                        emissive.get_y(),
                        emissive.get_z(),
                        mat.get_roughness(),
                    ],
                },
            ));
        }
        keyed.sort_unstable_by(
            |left: &(usize, usize, u32, GpuInstanceData3D),
             right: &(usize, usize, u32, GpuInstanceData3D)| {
                left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))
            },
        );
        let mut instances: Vec<GpuInstanceData3D> = Vec::with_capacity(keyed.len());
        let mut batches: Vec<GpuMeshDrawBatch3D> = Vec::new();
        let mut total_triangles: usize = 0;
        let mut cursor: usize = 0;
        while cursor < keyed.len() {
            let (mesh_id, lod_idx, tri_per_inst, _): (usize, usize, u32, GpuInstanceData3D) =
                keyed[cursor];
            let first_inst: u32 = instances.len() as u32;
            let mut count: u32 = 0;
            while cursor < keyed.len() && keyed[cursor].0 == mesh_id && keyed[cursor].1 == lod_idx {
                instances.push(keyed[cursor].3);
                count += 1;
                cursor += 1;
            }
            total_triangles =
                total_triangles.saturating_add((tri_per_inst as usize) * (count as usize));
            batches.push(GpuMeshDrawBatch3D::new(
                mesh_id,
                lod_idx,
                first_inst,
                count,
                tri_per_inst,
            ));
        }
        Self {
            view_projection: view_proj,
            prev_view_projection,
            camera_position: cam_pos,
            sun: world.get_sun(),
            instances,
            batches,
            total_triangles,
        }
    }
}