Skip to main content

euv_core/game/engine3d/renderer/
struct.rs

1use super::*;
2
3/// Per-worker atomic wakeup epoch and condition variable slot eliminating shared-mutex contention and cache-line false sharing in `Engine3dWorkerPool`.
4#[cfg(not(target_arch = "wasm32"))]
5#[repr(align(128))]
6#[derive(Debug, Default)]
7pub(crate) struct Engine3dWorkerSlot {
8    /// Monotonically incremented epoch signaling this worker to run the active job.
9    pub(crate) epoch: AtomicUsize,
10    /// Non-zero while this worker is parked on `wake` and requires condvar notification.
11    pub(crate) parked: AtomicUsize,
12    /// Private sleep mutex paired with `wake`.
13    pub(crate) lock: Mutex<()>,
14    /// Condition variable waking this worker when parked between frames.
15    pub(crate) wake: Condvar,
16}
17
18/// Shared lock-free dispatch state coordinating caller and persistent 3D background workers.
19#[cfg(not(target_arch = "wasm32"))]
20#[repr(align(128))]
21#[derive(Debug)]
22pub(crate) struct Engine3dPoolShared {
23    /// Raw pointer address of the caller-pinned `Engine3dJob` (`0` when idle).
24    pub(crate) active_job: AtomicUsize,
25    /// Number of background workers woken for the active dispatch.
26    pub(crate) active_workers: AtomicUsize,
27    /// Non-zero while the calling thread is parked waiting for workers to complete.
28    pub(crate) caller_parked: AlignedAtomicUsize,
29    /// Caller sleep mutex paired with `wake_caller`.
30    pub(crate) caller_lock: Mutex<()>,
31    /// Condition variable waking the calling thread once all active workers finish.
32    pub(crate) wake_caller: Condvar,
33    /// Per-worker wakeup slots (`len == worker_count`).
34    pub(crate) slots: Vec<Engine3dWorkerSlot>,
35}
36
37/// Active work-stealing range job executed synchronously across caller and persistent 3D worker threads with 128-byte isolated atomics.
38#[cfg(not(target_arch = "wasm32"))]
39#[repr(align(128))]
40#[derive(Debug)]
41pub(crate) struct Engine3dJob {
42    /// Type-erased chunk execution trampoline.
43    pub(crate) trampoline: fn(usize, usize, usize),
44    /// Caller-pinned closure reference encoded as `usize`.
45    pub(crate) ctx_ptr: usize,
46    /// Total logical items across all chunks.
47    pub(crate) total_items: usize,
48    /// Number of items per dynamic work-stealing chunk.
49    pub(crate) chunk_size: usize,
50    /// Total chunks to claim (`total_items.div_ceil(chunk_size)`).
51    pub(crate) total_chunks: usize,
52    /// Cache-line-isolated atomic cursor of the next unclaimed chunk index.
53    pub(crate) next_chunk: AlignedAtomicUsize,
54    /// Cache-line-isolated atomic count of background workers finished observing this epoch.
55    pub(crate) workers_done: AlignedAtomicUsize,
56}
57
58/// Persistent warm thread pool eliminating per-frame OS thread spawns in `Renderer3D`.
59#[cfg(not(target_arch = "wasm32"))]
60#[derive(Debug)]
61pub(crate) struct Engine3dWorkerPool {
62    /// Number of background worker threads (excluding the calling thread).
63    pub(crate) worker_count: usize,
64    /// Non-blocking re-entrancy guard serializing top-level dispatches cleanly.
65    pub(crate) dispatch_lock: Mutex<()>,
66    /// Shared lock-free atomic dispatch state and per-worker wakeup slots.
67    pub(crate) shared: Arc<Engine3dPoolShared>,
68}
69
70/// Per-frame telemetry emitted by `Renderer3D` for live FPS/RT/LOD/Nanite/culling diagnostics.
71#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
72pub struct RenderStats3D {
73    /// Internal rasterized framebuffer width in pixels.
74    #[get(type(copy))]
75    pub(crate) render_width: u32,
76    /// Internal rasterized framebuffer height in pixels.
77    #[get(type(copy))]
78    pub(crate) render_height: u32,
79    /// Active objects rendered inside frustum & chunk stream radius.
80    #[get(type(copy))]
81    pub(crate) visible_objects: usize,
82    /// Objects rejected by 6-plane frustum culling or chunk draw distance.
83    #[get(type(copy))]
84    pub(crate) culled_objects: usize,
85    /// Deduplicated GPU instancing draw batches.
86    #[get(type(copy))]
87    pub(crate) instanced_batches: usize,
88    /// Triangles rasterized after backface culling.
89    #[get(type(copy))]
90    pub(crate) triangles_drawn: usize,
91    /// BVH shadow/reflection/GI rays traced during this frame.
92    #[get(type(copy))]
93    pub(crate) rays_traced: usize,
94    /// Total BVH nodes active in the acceleration structure.
95    #[get(type(copy))]
96    pub(crate) bvh_nodes: usize,
97    /// Objects rendered at simplified distant LOD (`LOD1+`).
98    #[get(type(copy))]
99    pub(crate) lod_simplified_objects: usize,
100    /// Nanite-style meshlet clusters drawn this frame.
101    #[get(type(copy))]
102    pub(crate) meshlets_drawn: usize,
103    /// Nanite-style meshlet clusters culled by frustum or backface normal cones.
104    #[get(type(copy))]
105    pub(crate) meshlets_culled: usize,
106}
107
108/// Precomputed screen-space triangle rasterization setup record for parallel tiled G-Buffer rasterization.
109#[derive(Clone, Copy, Debug)]
110pub(crate) struct RasterTri2D {
111    /// Inclusive clamped top scanline index.
112    pub(crate) min_y: i32,
113    /// Inclusive clamped bottom scanline index.
114    pub(crate) max_y: i32,
115    /// Inclusive clamped left pixel coordinate.
116    pub(crate) min_x: i32,
117    /// Horizontal bounding-box span width (`max_x - min_x`).
118    pub(crate) span_max: i32,
119    /// Index into `shaded_tris`.
120    pub(crate) tri_id: u32,
121    /// Edge slopes `(dw0_dx, dw1_dx, dw2_dx)`.
122    pub(crate) slopes: [f32; 3],
123    /// Precomputed negative reciprocal edge slopes for span clipping.
124    pub(crate) neg_inv_slopes: [f32; 3],
125    /// Vertical barycentric step `(dw0_dy, dw1_dy, dw2_dy)`.
126    pub(crate) dw_dy: [f32; 3],
127    /// Barycentric coordinates evaluated at `(min_x + 0.5, min_y + 0.5)`.
128    pub(crate) w_start: [f32; 3],
129    /// Reverse-Z `1/w` evaluated at `(min_x + 0.5, min_y + 0.5)`.
130    pub(crate) inv_w_start: f32,
131    /// Horizontal `1/w` derivative per pixel.
132    pub(crate) d_inv_w_dx: f32,
133    /// Vertical `1/w` derivative per scanline.
134    pub(crate) d_inv_w_dy: f32,
135}
136
137/// Precomputed per-triangle Cook-Torrance GGX PBR shading record referenced by deferred G-Buffer indices.
138#[derive(Clone, Copy, Debug)]
139pub(crate) struct GShadeTri {
140    /// Camera-facing unit shading normal.
141    pub(crate) shade_n: Vec3,
142    /// Material linear base albedo.
143    pub(crate) mat_base: Vec3,
144    /// Material linear emissive radiance.
145    pub(crate) mat_emissive: Vec3,
146    /// Precomputed hemisphere sky ambient tint.
147    pub(crate) ambient_sky: Vec3,
148    /// Precomputed Schlick base specular reflectance `F0 = lerp(0.04, albedo, metallic)`.
149    pub(crate) f0: Vec3,
150    /// Clamped directional sun Lambertian term `max(N·L, 0)`.
151    pub(crate) n_dot_l: f32,
152    /// GGX roughness squared (`alpha^2 = roughness^4`).
153    pub(crate) alpha2: f32,
154    /// Energy-conserving diffuse scale `(1.0 - metallic)`.
155    pub(crate) diffuse_scale: f32,
156    /// Surface base reflectivity weight `[0.0, 1.0]`.
157    pub(crate) mat_refl: f32,
158    /// Surface metallic scalar `[0.0, 1.0]`.
159    pub(crate) metallic: f32,
160    /// Whether this surface traces specular reflections.
161    pub(crate) do_refl: bool,
162    /// Procedural surface detail mode attached to the triangle's material.
163    pub(crate) surface_detail: SurfaceDetailMode,
164}
165
166/// Structure-of-Arrays coarse deferred ray-tracing probe grid enabling contiguous SIMD bilateral denoise and upsampling.
167#[derive(Clone, Debug, Default)]
168pub(crate) struct RtProbeGridSoa {
169    /// Sun visibility factor per probe (`1.0` lit, `0.22` shadowed).
170    pub(crate) shadow: Vec<f32>,
171    /// Traced reflection linear red radiance.
172    pub(crate) refl_r: Vec<f32>,
173    /// Traced reflection linear green radiance.
174    pub(crate) refl_g: Vec<f32>,
175    /// Traced reflection linear blue radiance.
176    pub(crate) refl_b: Vec<f32>,
177    /// Colored indirect Lumen GI bounce red radiance.
178    pub(crate) gi_r: Vec<f32>,
179    /// Colored indirect Lumen GI bounce green radiance.
180    pub(crate) gi_g: Vec<f32>,
181    /// Colored indirect Lumen GI bounce blue radiance.
182    pub(crate) gi_b: Vec<f32>,
183    /// Ambient occlusion factor in `[0.42, 1.0]`.
184    pub(crate) ao: Vec<f32>,
185    /// Camera-space linear depth at probe center.
186    pub(crate) depth: Vec<f32>,
187    /// Surface normal X for bilateral edge stopping.
188    pub(crate) nx: Vec<f32>,
189    /// Surface normal Y for bilateral edge stopping.
190    pub(crate) ny: Vec<f32>,
191    /// Surface normal Z for bilateral edge stopping.
192    pub(crate) nz: Vec<f32>,
193    /// Non-zero when this probe sits on valid scene geometry.
194    pub(crate) valid: Vec<u8>,
195}
196
197/// Fixed-capacity L1-stack single-row SoA probe buffer (`gw <= PROBE_ROW_STACK_CAP`) enabling zero-allocation streaming bilateral denoising inside `shade_deferred_band`.
198#[derive(Clone, Debug)]
199pub(crate) struct RtProbeRowStack {
200    /// Sun visibility factor across one probe row.
201    pub(crate) shadow: [f32; PROBE_ROW_STACK_CAP],
202    /// Reflection linear red radiance across one probe row.
203    pub(crate) refl_r: [f32; PROBE_ROW_STACK_CAP],
204    /// Reflection linear green radiance across one probe row.
205    pub(crate) refl_g: [f32; PROBE_ROW_STACK_CAP],
206    /// Reflection linear blue radiance across one probe row.
207    pub(crate) refl_b: [f32; PROBE_ROW_STACK_CAP],
208    /// Colored Lumen GI red radiance across one probe row.
209    pub(crate) gi_r: [f32; PROBE_ROW_STACK_CAP],
210    /// Colored Lumen GI green radiance across one probe row.
211    pub(crate) gi_g: [f32; PROBE_ROW_STACK_CAP],
212    /// Colored Lumen GI blue radiance across one probe row.
213    pub(crate) gi_b: [f32; PROBE_ROW_STACK_CAP],
214    /// Ambient occlusion factor across one probe row.
215    pub(crate) ao: [f32; PROBE_ROW_STACK_CAP],
216    /// Linear probe depth across one probe row.
217    pub(crate) depth: [f32; PROBE_ROW_STACK_CAP],
218    /// Surface normal X across one probe row.
219    pub(crate) nx: [f32; PROBE_ROW_STACK_CAP],
220    /// Surface normal Y across one probe row.
221    pub(crate) ny: [f32; PROBE_ROW_STACK_CAP],
222    /// Surface normal Z across one probe row.
223    pub(crate) nz: [f32; PROBE_ROW_STACK_CAP],
224    /// Validity flags (`0` sky, `1` geometry) across one probe row.
225    pub(crate) valid: [u8; PROBE_ROW_STACK_CAP],
226}
227
228/// Per-thread persistent L1-hot 2-row probe denoise scratch avoiding 25 KB per-band stack zero-initialization and reusing denoised boundary rows across contiguous chunks.
229#[derive(Clone, Debug)]
230pub(crate) struct RtProbeRowScratch {
231    /// Monotonic frame generation tag invalidating cached rows across frames.
232    pub(crate) frame_gen: u64,
233    /// Probe row index cached in `buf_a` (`usize::MAX` if invalid).
234    pub(crate) cached_gy_a: usize,
235    /// Probe row index cached in `buf_b` (`usize::MAX` if invalid).
236    pub(crate) cached_gy_b: usize,
237    /// First L1-hot denoised probe row buffer.
238    pub(crate) buf_a: RtProbeRowStack,
239    /// Second L1-hot denoised probe row buffer.
240    pub(crate) buf_b: RtProbeRowStack,
241}
242
243/// Zero-copy borrowed view over one contiguous row of SoA RT probes (stack-denoised or wide pre-denoised).
244#[derive(Clone, Copy)]
245pub(crate) struct RtProbeRowView<'a> {
246    /// Sun visibility slice for this row.
247    pub(crate) shadow: &'a [f32],
248    /// Reflection red slice.
249    pub(crate) refl_r: &'a [f32],
250    /// Reflection green slice.
251    pub(crate) refl_g: &'a [f32],
252    /// Reflection blue slice.
253    pub(crate) refl_b: &'a [f32],
254    /// Lumen GI red slice.
255    pub(crate) gi_r: &'a [f32],
256    /// Lumen GI green slice.
257    pub(crate) gi_g: &'a [f32],
258    /// Lumen GI blue slice.
259    pub(crate) gi_b: &'a [f32],
260    /// Ambient occlusion slice.
261    pub(crate) ao: &'a [f32],
262    /// Linear depth slice.
263    pub(crate) depth: &'a [f32],
264    /// Normal X slice.
265    pub(crate) nx: &'a [f32],
266    /// Normal Y slice.
267    pub(crate) ny: &'a [f32],
268    /// Normal Z slice.
269    pub(crate) nz: &'a [f32],
270    /// Validity flags slice.
271    pub(crate) valid: &'a [u8],
272}
273
274/// 16-byte-aligned 2x2 bilinear probe cell packed into 4-lane SIMD arrays and cached across consecutive horizontal pixels sharing `(gx0, gx1, tid)`.
275#[repr(C, align(16))]
276#[derive(Clone, Copy)]
277pub(crate) struct CachedProbeCell {
278    /// Four corner linear depths `[p00, p10, p01, p11]`.
279    pub(crate) depth: [f32; 4],
280    /// Four corner sun visibility factors.
281    pub(crate) shadow: [f32; 4],
282    /// Four corner reflection linear red samples.
283    pub(crate) refl_r: [f32; 4],
284    /// Four corner reflection linear green samples.
285    pub(crate) refl_g: [f32; 4],
286    /// Four corner reflection linear blue samples.
287    pub(crate) refl_b: [f32; 4],
288    /// Four corner GI linear red samples.
289    pub(crate) gi_r: [f32; 4],
290    /// Four corner GI linear green samples.
291    pub(crate) gi_g: [f32; 4],
292    /// Four corner GI linear blue samples.
293    pub(crate) gi_b: [f32; 4],
294    /// Four corner ambient occlusion samples.
295    pub(crate) ao: [f32; 4],
296    /// Four corner bilateral depth tolerance scale (`0.58` high-agreement, `0.20` low-agreement).
297    pub(crate) tol_scale: [f32; 4],
298    /// Four corner bilateral depth tolerance bias (`2.4` high-agreement, `0.75` low-agreement).
299    pub(crate) tol_bias: [f32; 4],
300    /// Four corner SIMD validity bitmasks (`0xFFFF_FFFF` when corner passes normal test, else `0`).
301    pub(crate) valid_u32: [u32; 4],
302    /// Compact 4-bit corner validity mask (`0` triggers immediate edge fallback).
303    pub(crate) vmask: u8,
304}
305
306/// 16-byte-aligned 32-pixel L1-hot Structure-of-Arrays run scratch decoupling probe bilateral upsampling from zero-spill specialized PBR shading kernels.
307#[repr(C, align(16))]
308#[derive(Clone, Copy)]
309pub(crate) struct RunScratch32 {
310    /// Linear camera depth for up to 32 contiguous pixels of one triangle.
311    pub(crate) depths: [f32; 32],
312    /// Interpolated sun shadow factor for up to 32 pixels.
313    pub(crate) shadow: [f32; 32],
314    /// Interpolated reflection linear red for up to 32 pixels.
315    pub(crate) refl_r: [f32; 32],
316    /// Interpolated reflection linear green for up to 32 pixels.
317    pub(crate) refl_g: [f32; 32],
318    /// Interpolated reflection linear blue for up to 32 pixels.
319    pub(crate) refl_b: [f32; 32],
320    /// Interpolated Lumen GI linear red for up to 32 pixels.
321    pub(crate) gi_r: [f32; 32],
322    /// Interpolated Lumen GI linear green for up to 32 pixels.
323    pub(crate) gi_g: [f32; 32],
324    /// Interpolated Lumen GI linear blue for up to 32 pixels.
325    pub(crate) gi_b: [f32; 32],
326    /// Interpolated ambient occlusion for up to 32 pixels.
327    pub(crate) ao: [f32; 32],
328}
329
330/// Writable 4-pixel scanline slice targets and optional quarter-res HDR bloom slot for `shade_span_4x_specialized`.
331pub(crate) struct SpanShadeOut<'a> {
332    /// 16-byte RGBA8 destination span.
333    pub(crate) rgba: &'a mut [u8],
334    /// 4-byte Rec.601 luma destination span.
335    pub(crate) luma: &'a mut [u8],
336    /// Optional `(lane_index, bloom_cell)` HDR excess radiance slot.
337    pub(crate) bloom: Option<(usize, &'a mut [f32; 4])>,
338}
339
340/// Writable full-scanline color, luma, and quarter-res bloom buffers passed to 32-pixel run shaders.
341pub(crate) struct RunRowOut<'a> {
342    /// Full scanline RGBA8 output slice.
343    pub(crate) color: &'a mut [u8],
344    /// Full scanline Rec.601 luma output slice.
345    pub(crate) luma: &'a mut [u8],
346    /// Whether bloom extraction is active on this scanline (`(py & 3) == 0`).
347    pub(crate) write_bloom: bool,
348    /// Starting index of this scanline's bloom row inside `bloom_band`.
349    pub(crate) bloom_off: usize,
350    /// Writable quarter-resolution HDR bloom band slice.
351    pub(crate) bloom_band: &'a mut [[f32; 4]],
352}
353
354/// Shared read-only probe rows and horizontal bilinear stepping context for `upsample_run_probes_32` and `shade_tri_run_4x`.
355#[derive(Clone, Copy)]
356pub(crate) struct ProbeBandCtx<'a> {
357    /// Top denoised probe row view `gy0`.
358    pub(crate) r0: &'a RtProbeRowView<'a>,
359    /// Bottom denoised probe row view `gy1`.
360    pub(crate) r1: &'a RtProbeRowView<'a>,
361    /// Vertical bilinear weight for `r0`.
362    pub(crate) wy0: f32,
363    /// Vertical bilinear weight for `r1`.
364    pub(crate) wy1: f32,
365    /// Maximum valid coarse probe column index `gw - 1`.
366    pub(crate) gw_max: usize,
367    /// Doubled integer probe stride `rt_step * 2`.
368    pub(crate) step2_i32: i32,
369    /// Precomputed fractional horizontal lookup table indexed by `sub_x`.
370    pub(crate) fx_lut: &'a [f32; 16],
371}
372
373/// Raw writable base addresses for lock-free disjoint-tile writes into `RtProbeGridSoa`.
374#[derive(Clone, Copy, Debug)]
375pub(crate) struct RtProbeGridMutPtrs {
376    /// Base pointer for `shadow`.
377    pub(crate) shadow: usize,
378    /// Base pointer for `refl_r`.
379    pub(crate) refl_r: usize,
380    /// Base pointer for `refl_g`.
381    pub(crate) refl_g: usize,
382    /// Base pointer for `refl_b`.
383    pub(crate) refl_b: usize,
384    /// Base pointer for `gi_r`.
385    pub(crate) gi_r: usize,
386    /// Base pointer for `gi_g`.
387    pub(crate) gi_g: usize,
388    /// Base pointer for `gi_b`.
389    pub(crate) gi_b: usize,
390    /// Base pointer for `ao`.
391    pub(crate) ao: usize,
392    /// Base pointer for `depth`.
393    pub(crate) depth: usize,
394    /// Base pointer for `nx`.
395    pub(crate) nx: usize,
396    /// Base pointer for `ny`.
397    pub(crate) ny: usize,
398    /// Base pointer for `nz`.
399    pub(crate) nz: usize,
400    /// Base pointer for `valid`.
401    pub(crate) valid: usize,
402}
403
404/// Shared read-only inputs for fused Barrier 1 tiled rasterization and L1-hot coherent 2x2 probe packet tracing.
405pub(crate) struct TileRasterProbeInputs<'a> {
406    /// Screen-space triangle setup records.
407    pub(crate) raster_tris: &'a [RasterTri2D],
408    /// Flat CSR prefix offsets per tile (`len == total_tiles + 1`).
409    pub(crate) tile_offsets: &'a [u32],
410    /// Binned triangle indices into `raster_tris`.
411    pub(crate) tile_tri_indices: &'a [u32],
412    /// Precomputed GGX triangle shading records.
413    pub(crate) shaded_tris: &'a [GShadeTri],
414    /// Static world BVH4/BVH8 acceleration structure.
415    pub(crate) static_bvh: &'a Bvh3D,
416    /// Active object-space dynamic raytracing instances.
417    pub(crate) dyn_instances: &'a [DynamicRayInstance],
418    /// Local-space BVH4/BVH8 cache indexed by `mesh_id`.
419    pub(crate) local_bvhs: &'a [Option<Bvh3D>],
420    /// Tile edge dimension in pixels (`<= 64`, multiple of `rt_step` when RT active).
421    pub(crate) tile_px: usize,
422    /// Number of tiles horizontally.
423    pub(crate) tiles_x: usize,
424}
425
426/// Shared read-only inputs for fused Barrier 2 streaming bilateral denoise and vectorized deferred PBR shading.
427pub(crate) struct ShadeBandInputs<'a> {
428    /// Reverse-Z `1/w` depth buffer.
429    pub(crate) depth_buf: &'a [f32],
430    /// Deferred G-Buffer triangle IDs.
431    pub(crate) g_tri_idx: &'a [u32],
432    /// Precomputed GGX triangle shading records.
433    pub(crate) shaded_tris: &'a [GShadeTri],
434    /// Raw coarse RT probe SoA grid written by Barrier 1.
435    pub(crate) raw_probes: &'a RtProbeGridSoa,
436    /// Optional pre-denoised full probe grid used only when `gw > 256` (e.g. 4K viewports).
437    pub(crate) wide_denoised_probes: &'a RtProbeGridSoa,
438    /// Whether bilateral 3x3 probe denoising is active during row streaming (`gw <= 256`).
439    pub(crate) denoise_probes: bool,
440    /// Static world BVH4/BVH8 acceleration structure.
441    pub(crate) static_bvh: &'a Bvh3D,
442    /// Active object-space dynamic raytracing instances.
443    pub(crate) dyn_instances: &'a [DynamicRayInstance],
444    /// Local-space BVH4/BVH8 cache indexed by `mesh_id`.
445    pub(crate) local_bvhs: &'a [Option<Bvh3D>],
446    /// Atomic bitset marking quarter-resolution bloom rows that received non-zero HDR radiance (`576` bits -> `bh <= 576`).
447    pub(crate) bloom_row_bits: &'a [AtomicU64; 9],
448}
449
450/// Shared read-only inputs for Barrier 3 vectorized FXAA/MLAA/TAA and bilinear HDR bloom compositing.
451pub(crate) struct PostProcessInputs<'a> {
452    /// Tone-mapped RGBA8 intermediate framebuffer.
453    pub(crate) color_src: &'a [u8],
454    /// Rec.601 luma buffer populated during deferred shading.
455    pub(crate) luma: &'a [u8],
456    /// Deferred G-Buffer triangle IDs for geometry-aware AA edge detection.
457    pub(crate) g_tri_idx: &'a [u32],
458    /// Blurred quarter-resolution HDR bloom buffer (`[r, g, b, 0]`).
459    pub(crate) bloom: &'a [[f32; 4]],
460    /// Active bloom tile mask (`1` where bloom contributes `>= 1` RGB LSB).
461    pub(crate) bloom_tile_active: &'a [u8],
462    /// Previous frame RGBA8 TAA temporal history buffer.
463    pub(crate) taa_history: &'a [u8],
464}
465
466/// Immutable per-frame camera, lighting, volumetric, and ray-tracing configuration shared across worker threads.
467#[derive(Clone, Copy, Debug)]
468pub(crate) struct DeferredFrameCtx {
469    /// Framebuffer width in pixels.
470    pub(crate) w: usize,
471    /// Framebuffer height in pixels.
472    pub(crate) h: usize,
473    /// Coarse RT grid width in probes.
474    pub(crate) gw: usize,
475    /// Coarse RT grid height in probes.
476    pub(crate) gh: usize,
477    /// Quarter-res HDR bloom width.
478    pub(crate) bw: usize,
479    /// Pixel stride per coarse RT probe.
480    pub(crate) rt_step: usize,
481    /// Reciprocal framebuffer width.
482    pub(crate) inv_w_f: f32,
483    /// Reciprocal framebuffer height.
484    pub(crate) inv_h_f: f32,
485    /// Camera world position.
486    pub(crate) cam_pos: Vec3,
487    /// Camera unit forward basis.
488    pub(crate) cam_fwd: Vec3,
489    /// Camera right basis scaled by `half_w`.
490    pub(crate) cam_right_scaled: Vec3,
491    /// Camera up basis scaled by `half_h`.
492    pub(crate) cam_up_scaled: Vec3,
493    /// Active directional sun & sky parameters.
494    pub(crate) sun: DirectionalLight3D,
495    /// Precomputed safe reciprocal sun direction for fast shadow BVH traversal.
496    pub(crate) inv_sun_dir: Vec3,
497    /// Precomputed 2x2 soft-shadow jittered `(dir, inv_dir)` ray table hoisted once per frame.
498    pub(crate) soft_shadow_rays: [(Vec3, Vec3); 4],
499    /// Active ray-tracing quality tier.
500    pub(crate) rt_mode: RayTracingMode,
501    /// Maximum reflection/GI bounce depth (`0..=3`).
502    pub(crate) reflection_bounces: u8,
503    /// Whether volumetric height/distance fog and crepuscular sun-shafts are enabled.
504    pub(crate) fog_on: bool,
505    /// Precomputed inverse fog attenuation distance.
506    pub(crate) inv_fog_dist: f32,
507    /// Exposure scale derived from physically based camera EV100.
508    pub(crate) exposure_scale: f32,
509    /// Whether quarter-res emissive/specular bloom extraction is active.
510    pub(crate) bloom_on: bool,
511    /// Monotonic frame generation tag for per-thread probe denoise scratch cache invalidation.
512    pub(crate) probe_frame_gen: u64,
513}
514
515/// Zero-allocation UE5-class Deferred GGX PBR + Persistent Multi-Core SIMD BVH4/BVH8 + Lumen GI + Bloom + Morphological AA/TAA 3D renderer.
516#[derive(Clone, Data, Debug, Default)]
517pub struct Renderer3D {
518    /// Pre-allocated RGBA8 tone-mapped intermediate pixel buffer.
519    pub(crate) color_buffer: Vec<u8>,
520    /// Pre-allocated RGBA8 temporal history buffer for variance-clamped TAA.
521    pub(crate) aa_buffer: Vec<u8>,
522    /// Pre-allocated floating-point linear `1/w` reverse-Z depth buffer (`0.0` = sky).
523    pub(crate) depth_buffer: Vec<f32>,
524    /// Deferred G-Buffer triangle index per pixel (`u32::MAX` = sky).
525    #[get(skip)]
526    #[get_mut(skip)]
527    #[set(skip)]
528    pub(crate) g_tri_idx: Vec<u32>,
529    /// Single-byte per-pixel Rec.601 luma buffer populated during deferred shading for fast morphological AA.
530    #[get(skip)]
531    #[get_mut(skip)]
532    #[set(skip)]
533    pub(crate) luma_buffer: Vec<u8>,
534    /// Per-frame precomputed GGX triangle shading records.
535    #[get(skip)]
536    #[get_mut(skip)]
537    #[set(skip)]
538    pub(crate) shaded_tris: Vec<GShadeTri>,
539    /// Persistent reusable RGBA8 final output buffer eliminating per-frame allocations in `render_world_rgba`.
540    #[get(skip)]
541    #[get_mut(skip)]
542    #[set(skip)]
543    pub(crate) rgba_scratch: Vec<u8>,
544    /// Structure-of-Arrays coarse coherent ray-tracing probe grid.
545    #[get(skip)]
546    #[get_mut(skip)]
547    #[set(skip)]
548    pub(crate) rt_probes: RtProbeGridSoa,
549    /// Fallback full-grid denoised SoA probe buffer used only when `gw > 256` (4K+).
550    #[get(skip)]
551    #[get_mut(skip)]
552    #[set(skip)]
553    pub(crate) rt_probes_wide_denoised: RtProbeGridSoa,
554    /// Quarter-res 16-byte-aligned HDR bloom extraction and vertical blur buffer.
555    #[get(skip)]
556    #[get_mut(skip)]
557    #[set(skip)]
558    pub(crate) bloom_a: Vec<[f32; 4]>,
559    /// Quarter-res 16-byte-aligned HDR bloom horizontal blur scratch buffer.
560    #[get(skip)]
561    #[get_mut(skip)]
562    #[set(skip)]
563    pub(crate) bloom_b: Vec<[f32; 4]>,
564    /// Quarter-res active-bloom tile mask (`1` when any bilinear corner contributes `>= 1` RGB LSB) skipping dark tiles in post-processing.
565    #[get(skip)]
566    #[get_mut(skip)]
567    #[set(skip)]
568    pub(crate) bloom_tile_active: Vec<u8>,
569    /// Reusable front-to-back object sorting scratch buffer.
570    #[get(skip)]
571    #[get_mut(skip)]
572    #[set(skip)]
573    pub(crate) visible_scratch: Vec<(f32, usize)>,
574    /// Reusable meshlet triangle-range scratch buffer eliminating per-object heap allocations.
575    #[get(skip)]
576    #[get_mut(skip)]
577    #[set(skip)]
578    pub(crate) cluster_ranges_scratch: Vec<(usize, usize)>,
579    /// Reusable per-object transformed vertex cache `(clip_pos, world_pos)` avoiding redundant vertex transforms.
580    #[get(skip)]
581    #[get_mut(skip)]
582    #[set(skip)]
583    pub(crate) projected_verts_scratch: Vec<([f32; 4], Vec3)>,
584    /// Reusable unique mesh-id set for instancing telemetry.
585    #[get(skip)]
586    #[get_mut(skip)]
587    #[set(skip)]
588    pub(crate) unique_meshes_scratch: HashSet<usize>,
589    /// Reusable saved dynamic-object transforms for zero-allocation interpolated rendering.
590    #[get(skip)]
591    #[get_mut(skip)]
592    #[set(skip)]
593    pub(crate) saved_objs_scratch: Vec<(usize, Transform3D, Aabb3D)>,
594    /// Reusable screen-space triangle setup list for parallel tiled rasterization.
595    #[get(skip)]
596    #[get_mut(skip)]
597    #[set(skip)]
598    pub(crate) raster_tris_scratch: Vec<RasterTri2D>,
599    /// Reusable per-tile triangle count array for flat CSR binning.
600    #[get(skip)]
601    #[get_mut(skip)]
602    #[set(skip)]
603    pub(crate) tile_counts_scratch: Vec<u32>,
604    /// Reusable flat CSR prefix-sum offset array (`total_tiles + 1`).
605    #[get(skip)]
606    #[get_mut(skip)]
607    #[set(skip)]
608    pub(crate) tile_offsets_scratch: Vec<u32>,
609    /// Reusable per-tile insertion cursor array for flat CSR binning.
610    #[get(skip)]
611    #[get_mut(skip)]
612    #[set(skip)]
613    pub(crate) tile_cursors_scratch: Vec<u32>,
614    /// Reusable flat array of binned triangle indices across all screen tiles.
615    #[get(skip)]
616    #[get_mut(skip)]
617    #[set(skip)]
618    pub(crate) tile_tri_indices_scratch: Vec<u32>,
619    /// Optional shared-device GPU composite target for zero-readback single-pass UI+3D compositing.
620    #[get(skip)]
621    #[get_mut(skip)]
622    #[set(skip)]
623    pub(crate) gpu_target: GpuCompositeTarget,
624    /// Whether `aa_buffer` holds a valid previous frame compatible with temporal anti-aliasing.
625    #[get(skip)]
626    #[get_mut(skip)]
627    #[set(skip)]
628    pub(crate) has_taa_history: bool,
629    /// Previous frame view-projection fingerprint used to detect camera cuts for TAA.
630    #[get(skip)]
631    #[get_mut(skip)]
632    #[set(skip)]
633    pub(crate) prev_vp_m0: f32,
634    /// Monotonic frame counter driving Halton(2, 3) temporal subpixel jitter.
635    #[get(skip)]
636    #[get_mut(skip)]
637    #[set(skip)]
638    pub(crate) frame_index: u32,
639    /// Last rendered `World3D::world_revision` enabling HUD-only dirty frames to reuse the cached 3D frame.
640    #[get(type(copy))]
641    pub(crate) last_world_revision: u64,
642    /// Quality and viewport configuration fingerprint paired with `last_world_revision`.
643    #[get(skip)]
644    #[get_mut(skip)]
645    #[set(skip)]
646    pub(crate) last_quality_fingerprint: u64,
647    /// Number of consecutive static-world TAA accumulation frames completed since the last world change.
648    #[get(type(copy))]
649    pub(crate) taa_accumulated_frames: u32,
650    /// Total HUD-only dirty frames satisfied from the cached 3D framebuffer without re-rasterizing.
651    #[get(type(copy))]
652    pub(crate) cached_world_reuses: u64,
653    /// Last rendered internal width.
654    #[get(type(copy))]
655    pub(crate) width: u32,
656    /// Last rendered internal height.
657    #[get(type(copy))]
658    pub(crate) height: u32,
659    /// Telemetry from the most recent frame.
660    #[get(type(copy))]
661    pub(crate) last_stats: RenderStats3D,
662}