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 /// World-space surface X coordinate for temporal probe reprojection validation.
194 pub(crate) world_x: Vec<f32>,
195 /// World-space surface Y coordinate for temporal probe reprojection validation.
196 pub(crate) world_y: Vec<f32>,
197 /// World-space surface Z coordinate for temporal probe reprojection validation.
198 pub(crate) world_z: Vec<f32>,
199 /// Non-zero when this probe sits on valid scene geometry.
200 pub(crate) valid: Vec<u8>,
201}
202
203/// Fixed-capacity L1-stack single-row SoA probe buffer (`gw <= PROBE_ROW_STACK_CAP`) enabling zero-allocation streaming bilateral denoising inside `shade_deferred_band`.
204#[derive(Clone, Debug)]
205pub(crate) struct RtProbeRowStack {
206 /// Sun visibility factor across one probe row.
207 pub(crate) shadow: [f32; PROBE_ROW_STACK_CAP],
208 /// Reflection linear red radiance across one probe row.
209 pub(crate) refl_r: [f32; PROBE_ROW_STACK_CAP],
210 /// Reflection linear green radiance across one probe row.
211 pub(crate) refl_g: [f32; PROBE_ROW_STACK_CAP],
212 /// Reflection linear blue radiance across one probe row.
213 pub(crate) refl_b: [f32; PROBE_ROW_STACK_CAP],
214 /// Colored Lumen GI red radiance across one probe row.
215 pub(crate) gi_r: [f32; PROBE_ROW_STACK_CAP],
216 /// Colored Lumen GI green radiance across one probe row.
217 pub(crate) gi_g: [f32; PROBE_ROW_STACK_CAP],
218 /// Colored Lumen GI blue radiance across one probe row.
219 pub(crate) gi_b: [f32; PROBE_ROW_STACK_CAP],
220 /// Ambient occlusion factor across one probe row.
221 pub(crate) ao: [f32; PROBE_ROW_STACK_CAP],
222 /// Linear probe depth across one probe row.
223 pub(crate) depth: [f32; PROBE_ROW_STACK_CAP],
224 /// Surface normal X across one probe row.
225 pub(crate) nx: [f32; PROBE_ROW_STACK_CAP],
226 /// Surface normal Y across one probe row.
227 pub(crate) ny: [f32; PROBE_ROW_STACK_CAP],
228 /// Surface normal Z across one probe row.
229 pub(crate) nz: [f32; PROBE_ROW_STACK_CAP],
230 /// Validity flags (`0` sky, `1` geometry) across one probe row.
231 pub(crate) valid: [u8; PROBE_ROW_STACK_CAP],
232}
233
234/// 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.
235#[derive(Clone, Debug)]
236pub(crate) struct RtProbeRowScratch {
237 /// Monotonic frame generation tag invalidating cached rows across frames.
238 pub(crate) frame_gen: u64,
239 /// Probe row index cached in `buf_a` (`usize::MAX` if invalid).
240 pub(crate) cached_gy_a: usize,
241 /// Probe row index cached in `buf_b` (`usize::MAX` if invalid).
242 pub(crate) cached_gy_b: usize,
243 /// First L1-hot denoised probe row buffer.
244 pub(crate) buf_a: RtProbeRowStack,
245 /// Second L1-hot denoised probe row buffer.
246 pub(crate) buf_b: RtProbeRowStack,
247}
248
249/// Zero-copy borrowed view over one contiguous row of SoA RT probes (stack-denoised or wide pre-denoised).
250#[derive(Clone, Copy)]
251pub(crate) struct RtProbeRowView<'a> {
252 /// Sun visibility slice for this row.
253 pub(crate) shadow: &'a [f32],
254 /// Reflection red slice.
255 pub(crate) refl_r: &'a [f32],
256 /// Reflection green slice.
257 pub(crate) refl_g: &'a [f32],
258 /// Reflection blue slice.
259 pub(crate) refl_b: &'a [f32],
260 /// Lumen GI red slice.
261 pub(crate) gi_r: &'a [f32],
262 /// Lumen GI green slice.
263 pub(crate) gi_g: &'a [f32],
264 /// Lumen GI blue slice.
265 pub(crate) gi_b: &'a [f32],
266 /// Ambient occlusion slice.
267 pub(crate) ao: &'a [f32],
268 /// Linear depth slice.
269 pub(crate) depth: &'a [f32],
270 /// Normal X slice.
271 pub(crate) nx: &'a [f32],
272 /// Normal Y slice.
273 pub(crate) ny: &'a [f32],
274 /// Normal Z slice.
275 pub(crate) nz: &'a [f32],
276 /// Validity flags slice.
277 pub(crate) valid: &'a [u8],
278}
279
280/// 16-byte-aligned 2x2 bilinear probe cell packed into 4-lane SIMD arrays and cached across consecutive horizontal pixels sharing `(gx0, gx1, tid)`.
281#[repr(C, align(16))]
282#[derive(Clone, Copy)]
283pub(crate) struct CachedProbeCell {
284 /// Four corner linear depths `[p00, p10, p01, p11]`.
285 pub(crate) depth: [f32; 4],
286 /// Four corner sun visibility factors.
287 pub(crate) shadow: [f32; 4],
288 /// Four corner reflection linear red samples.
289 pub(crate) refl_r: [f32; 4],
290 /// Four corner reflection linear green samples.
291 pub(crate) refl_g: [f32; 4],
292 /// Four corner reflection linear blue samples.
293 pub(crate) refl_b: [f32; 4],
294 /// Four corner GI linear red samples.
295 pub(crate) gi_r: [f32; 4],
296 /// Four corner GI linear green samples.
297 pub(crate) gi_g: [f32; 4],
298 /// Four corner GI linear blue samples.
299 pub(crate) gi_b: [f32; 4],
300 /// Four corner ambient occlusion samples.
301 pub(crate) ao: [f32; 4],
302 /// Four corner bilateral depth tolerance scale (`0.58` high-agreement, `0.20` low-agreement).
303 pub(crate) tol_scale: [f32; 4],
304 /// Four corner bilateral depth tolerance bias (`2.4` high-agreement, `0.75` low-agreement).
305 pub(crate) tol_bias: [f32; 4],
306 /// Four corner SIMD validity bitmasks (`0xFFFF_FFFF` when corner passes normal test, else `0`).
307 pub(crate) valid_u32: [u32; 4],
308 /// Compact 4-bit corner validity mask (`0` triggers immediate edge fallback).
309 pub(crate) vmask: u8,
310}
311
312/// 16-byte-aligned 32-pixel L1-hot Structure-of-Arrays run scratch decoupling probe bilateral upsampling from zero-spill specialized PBR shading kernels.
313#[repr(C, align(16))]
314#[derive(Clone, Copy)]
315pub(crate) struct RunScratch32 {
316 /// Linear camera depth for up to 32 contiguous pixels of one triangle.
317 pub(crate) depths: [f32; 32],
318 /// Interpolated sun shadow factor for up to 32 pixels.
319 pub(crate) shadow: [f32; 32],
320 /// Interpolated reflection linear red for up to 32 pixels.
321 pub(crate) refl_r: [f32; 32],
322 /// Interpolated reflection linear green for up to 32 pixels.
323 pub(crate) refl_g: [f32; 32],
324 /// Interpolated reflection linear blue for up to 32 pixels.
325 pub(crate) refl_b: [f32; 32],
326 /// Interpolated Lumen GI linear red for up to 32 pixels.
327 pub(crate) gi_r: [f32; 32],
328 /// Interpolated Lumen GI linear green for up to 32 pixels.
329 pub(crate) gi_g: [f32; 32],
330 /// Interpolated Lumen GI linear blue for up to 32 pixels.
331 pub(crate) gi_b: [f32; 32],
332 /// Interpolated ambient occlusion for up to 32 pixels.
333 pub(crate) ao: [f32; 32],
334}
335
336/// Writable 4-pixel scanline slice targets and optional quarter-res HDR bloom slot for `shade_span_4x_specialized`.
337pub(crate) struct SpanShadeOut<'a> {
338 /// 16-byte RGBA8 destination span.
339 pub(crate) rgba: &'a mut [u8],
340 /// 4-byte Rec.601 luma destination span.
341 pub(crate) luma: &'a mut [u8],
342 /// Optional `(lane_index, bloom_cell)` HDR excess radiance slot.
343 pub(crate) bloom: Option<(usize, &'a mut [f32; 4])>,
344}
345
346/// Writable full-scanline color, luma, and quarter-res bloom buffers passed to 32-pixel run shaders.
347pub(crate) struct RunRowOut<'a> {
348 /// Full scanline RGBA8 output slice.
349 pub(crate) color: &'a mut [u8],
350 /// Full scanline Rec.601 luma output slice.
351 pub(crate) luma: &'a mut [u8],
352 /// Whether bloom extraction is active on this scanline (`(py & 3) == 0`).
353 pub(crate) write_bloom: bool,
354 /// Starting index of this scanline's bloom row inside `bloom_band`.
355 pub(crate) bloom_off: usize,
356 /// Writable quarter-resolution HDR bloom band slice.
357 pub(crate) bloom_band: &'a mut [[f32; 4]],
358}
359
360/// Shared read-only probe rows and horizontal bilinear stepping context for `upsample_run_probes_32` and `shade_tri_run_4x`.
361#[derive(Clone, Copy)]
362pub(crate) struct ProbeBandCtx<'a> {
363 /// Top denoised probe row view `gy0`.
364 pub(crate) r0: &'a RtProbeRowView<'a>,
365 /// Bottom denoised probe row view `gy1`.
366 pub(crate) r1: &'a RtProbeRowView<'a>,
367 /// Vertical bilinear weight for `r0`.
368 pub(crate) wy0: f32,
369 /// Vertical bilinear weight for `r1`.
370 pub(crate) wy1: f32,
371 /// Maximum valid coarse probe column index `gw - 1`.
372 pub(crate) gw_max: usize,
373 /// Doubled integer probe stride `rt_step * 2`.
374 pub(crate) step2_i32: i32,
375 /// Precomputed fractional horizontal lookup table indexed by `sub_x`.
376 pub(crate) fx_lut: &'a [f32; 16],
377}
378
379/// Raw writable base addresses for lock-free disjoint-tile writes into `RtProbeGridSoa`.
380#[derive(Clone, Copy, Debug)]
381pub(crate) struct RtProbeGridMutPtrs {
382 /// Base pointer for `shadow`.
383 pub(crate) shadow: usize,
384 /// Base pointer for `refl_r`.
385 pub(crate) refl_r: usize,
386 /// Base pointer for `refl_g`.
387 pub(crate) refl_g: usize,
388 /// Base pointer for `refl_b`.
389 pub(crate) refl_b: usize,
390 /// Base pointer for `gi_r`.
391 pub(crate) gi_r: usize,
392 /// Base pointer for `gi_g`.
393 pub(crate) gi_g: usize,
394 /// Base pointer for `gi_b`.
395 pub(crate) gi_b: usize,
396 /// Base pointer for `ao`.
397 pub(crate) ao: usize,
398 /// Base pointer for `depth`.
399 pub(crate) depth: usize,
400 /// Base pointer for `nx`.
401 pub(crate) nx: usize,
402 /// Base pointer for `ny`.
403 pub(crate) ny: usize,
404 /// Base pointer for `nz`.
405 pub(crate) nz: usize,
406 /// Base pointer for `world_x`.
407 pub(crate) world_x: usize,
408 /// Base pointer for `world_y`.
409 pub(crate) world_y: usize,
410 /// Base pointer for `world_z`.
411 pub(crate) world_z: usize,
412 /// Base pointer for `valid`.
413 pub(crate) valid: usize,
414}
415
416/// Shared read-only inputs for fused Barrier 1 tiled rasterization and L1-hot coherent 2x2 probe packet tracing.
417pub(crate) struct TileRasterProbeInputs<'a> {
418 /// Screen-space triangle setup records.
419 pub(crate) raster_tris: &'a [RasterTri2D],
420 /// Flat CSR prefix offsets per tile (`len == total_tiles + 1`).
421 pub(crate) tile_offsets: &'a [u32],
422 /// Binned triangle indices into `raster_tris`.
423 pub(crate) tile_tri_indices: &'a [u32],
424 /// Precomputed GGX triangle shading records.
425 pub(crate) shaded_tris: &'a [GShadeTri],
426 /// Static world BVH4/BVH8 acceleration structure.
427 pub(crate) static_bvh: &'a Bvh3D,
428 /// Active object-space dynamic raytracing instances.
429 pub(crate) dyn_instances: &'a [DynamicRayInstance],
430 /// Local-space BVH4/BVH8 cache indexed by `mesh_id`.
431 pub(crate) local_bvhs: &'a [Option<Bvh3D>],
432 /// Previous frame coarse RT probe grid for world-space-validated temporal checkerboard reuse.
433 pub(crate) prev_probes: Option<&'a RtProbeGridSoa>,
434 /// Alternating checkerboard parity (`0` or `1`) selecting which 2x2 probe blocks refresh vs reuse.
435 pub(crate) probe_checker_parity: usize,
436 /// Tile edge dimension in pixels (`<= 64`, multiple of `rt_step` when RT active).
437 pub(crate) tile_px: usize,
438 /// Number of tiles horizontally.
439 pub(crate) tiles_x: usize,
440}
441
442/// Shared read-only inputs for fused Barrier 2 streaming bilateral denoise and vectorized deferred PBR shading.
443pub(crate) struct ShadeBandInputs<'a> {
444 /// Reverse-Z `1/w` depth buffer.
445 pub(crate) depth_buf: &'a [f32],
446 /// Deferred G-Buffer triangle IDs.
447 pub(crate) g_tri_idx: &'a [u32],
448 /// Precomputed GGX triangle shading records.
449 pub(crate) shaded_tris: &'a [GShadeTri],
450 /// Raw coarse RT probe SoA grid written by Barrier 1.
451 pub(crate) raw_probes: &'a RtProbeGridSoa,
452 /// Optional pre-denoised full probe grid used only when `gw > 256` (e.g. 4K viewports).
453 pub(crate) wide_denoised_probes: &'a RtProbeGridSoa,
454 /// Whether bilateral 3x3 probe denoising is active during row streaming (`gw <= 256`).
455 pub(crate) denoise_probes: bool,
456 /// Static world BVH4/BVH8 acceleration structure.
457 pub(crate) static_bvh: &'a Bvh3D,
458 /// Active object-space dynamic raytracing instances.
459 pub(crate) dyn_instances: &'a [DynamicRayInstance],
460 /// Local-space BVH4/BVH8 cache indexed by `mesh_id`.
461 pub(crate) local_bvhs: &'a [Option<Bvh3D>],
462 /// Atomic bitset marking quarter-resolution bloom rows that received non-zero HDR radiance (`576` bits -> `bh <= 576`).
463 pub(crate) bloom_row_bits: &'a [AtomicU64; 9],
464}
465
466/// Shared read-only inputs for Barrier 3 vectorized FXAA/MLAA/TAA and bilinear HDR bloom compositing.
467pub(crate) struct PostProcessInputs<'a> {
468 /// Tone-mapped RGBA8 intermediate framebuffer.
469 pub(crate) color_src: &'a [u8],
470 /// Rec.601 luma buffer populated during deferred shading.
471 pub(crate) luma: &'a [u8],
472 /// Deferred G-Buffer triangle IDs for geometry-aware AA edge detection.
473 pub(crate) g_tri_idx: &'a [u32],
474 /// Blurred quarter-resolution HDR bloom buffer (`[r, g, b, 0]`).
475 pub(crate) bloom: &'a [[f32; 4]],
476 /// Active bloom tile mask (`1` where bloom contributes `>= 1` RGB LSB).
477 pub(crate) bloom_tile_active: &'a [u8],
478 /// Previous frame RGBA8 TAA temporal history buffer.
479 pub(crate) taa_history: &'a [u8],
480}
481
482/// Immutable per-frame camera, lighting, volumetric, and ray-tracing configuration shared across worker threads.
483#[derive(Clone, Copy, Debug)]
484pub(crate) struct DeferredFrameCtx {
485 /// Framebuffer width in pixels.
486 pub(crate) w: usize,
487 /// Framebuffer height in pixels.
488 pub(crate) h: usize,
489 /// Coarse RT grid width in probes.
490 pub(crate) gw: usize,
491 /// Coarse RT grid height in probes.
492 pub(crate) gh: usize,
493 /// Quarter-res HDR bloom width.
494 pub(crate) bw: usize,
495 /// Pixel stride per coarse RT probe.
496 pub(crate) rt_step: usize,
497 /// Reciprocal framebuffer width.
498 pub(crate) inv_w_f: f32,
499 /// Reciprocal framebuffer height.
500 pub(crate) inv_h_f: f32,
501 /// Camera world position.
502 pub(crate) cam_pos: Vec3,
503 /// Camera unit forward basis.
504 pub(crate) cam_fwd: Vec3,
505 /// Camera right basis scaled by `half_w`.
506 pub(crate) cam_right_scaled: Vec3,
507 /// Camera up basis scaled by `half_h`.
508 pub(crate) cam_up_scaled: Vec3,
509 /// Active directional sun & sky parameters.
510 pub(crate) sun: DirectionalLight3D,
511 /// Precomputed safe reciprocal sun direction for fast shadow BVH traversal.
512 pub(crate) inv_sun_dir: Vec3,
513 /// Precomputed 2x2 soft-shadow jittered `(dir, inv_dir)` ray table hoisted once per frame.
514 pub(crate) soft_shadow_rays: [(Vec3, Vec3); 4],
515 /// Active ray-tracing quality tier.
516 pub(crate) rt_mode: RayTracingMode,
517 /// Maximum reflection/GI bounce depth (`0..=3`).
518 pub(crate) reflection_bounces: u8,
519 /// Whether volumetric height/distance fog and crepuscular sun-shafts are enabled.
520 pub(crate) fog_on: bool,
521 /// Precomputed inverse fog attenuation distance.
522 pub(crate) inv_fog_dist: f32,
523 /// Exposure scale derived from physically based camera EV100.
524 pub(crate) exposure_scale: f32,
525 /// Whether quarter-res emissive/specular bloom extraction is active.
526 pub(crate) bloom_on: bool,
527 /// Monotonic frame generation tag for per-thread probe denoise scratch cache invalidation.
528 pub(crate) probe_frame_gen: u64,
529}
530
531/// Zero-allocation UE5-class Deferred GGX PBR + Persistent Multi-Core SIMD BVH4/BVH8 + Lumen GI + Bloom + Morphological AA/TAA 3D renderer.
532#[derive(Clone, Data, Debug, Default)]
533pub struct Renderer3D {
534 /// Pre-allocated RGBA8 tone-mapped intermediate pixel buffer.
535 pub(crate) color_buffer: Vec<u8>,
536 /// Pre-allocated RGBA8 temporal history buffer for variance-clamped TAA.
537 pub(crate) aa_buffer: Vec<u8>,
538 /// Pre-allocated floating-point linear `1/w` reverse-Z depth buffer (`0.0` = sky).
539 pub(crate) depth_buffer: Vec<f32>,
540 /// Deferred G-Buffer triangle index per pixel (`u32::MAX` = sky).
541 #[get(skip)]
542 #[get_mut(skip)]
543 #[set(skip)]
544 pub(crate) g_tri_idx: Vec<u32>,
545 /// Single-byte per-pixel Rec.601 luma buffer populated during deferred shading for fast morphological AA.
546 #[get(skip)]
547 #[get_mut(skip)]
548 #[set(skip)]
549 pub(crate) luma_buffer: Vec<u8>,
550 /// Per-frame precomputed GGX triangle shading records.
551 #[get(skip)]
552 #[get_mut(skip)]
553 #[set(skip)]
554 pub(crate) shaded_tris: Vec<GShadeTri>,
555 /// Persistent reusable RGBA8 final output buffer eliminating per-frame allocations in `render_world_rgba`.
556 #[get(skip)]
557 #[get_mut(skip)]
558 #[set(skip)]
559 pub(crate) rgba_scratch: Vec<u8>,
560 /// Structure-of-Arrays coarse coherent ray-tracing probe grid.
561 #[get(skip)]
562 #[get_mut(skip)]
563 #[set(skip)]
564 pub(crate) rt_probes: RtProbeGridSoa,
565 /// Previous frame coarse RT probe grid swapped in O(1) for temporal checkerboard probe reuse.
566 #[get(skip)]
567 #[get_mut(skip)]
568 #[set(skip)]
569 pub(crate) prev_rt_probes: RtProbeGridSoa,
570 /// Whether `prev_rt_probes` holds valid history matching `(prev_probe_gw, prev_probe_gh, prev_probe_rt_mode)`.
571 #[get(skip)]
572 #[get_mut(skip)]
573 #[set(skip)]
574 pub(crate) has_probe_history: bool,
575 /// Coarse probe width stored in `prev_rt_probes`.
576 #[get(skip)]
577 #[get_mut(skip)]
578 #[set(skip)]
579 pub(crate) prev_probe_gw: usize,
580 /// Coarse probe height stored in `prev_rt_probes`.
581 #[get(skip)]
582 #[get_mut(skip)]
583 #[set(skip)]
584 pub(crate) prev_probe_gh: usize,
585 /// Ray-tracing mode stored in `prev_rt_probes`.
586 #[get(skip)]
587 #[get_mut(skip)]
588 #[set(skip)]
589 pub(crate) prev_probe_rt_mode: RayTracingMode,
590 /// Previous frame directional sun vector for invalidating temporal probes on lighting changes.
591 #[get(skip)]
592 #[get_mut(skip)]
593 #[set(skip)]
594 pub(crate) prev_sun_dir: Vec3,
595 /// Fallback full-grid denoised SoA probe buffer used only when `gw > 256` (4K+).
596 #[get(skip)]
597 #[get_mut(skip)]
598 #[set(skip)]
599 pub(crate) rt_probes_wide_denoised: RtProbeGridSoa,
600 /// Quarter-res 16-byte-aligned HDR bloom extraction and vertical blur buffer.
601 #[get(skip)]
602 #[get_mut(skip)]
603 #[set(skip)]
604 pub(crate) bloom_a: Vec<[f32; 4]>,
605 /// Quarter-res 16-byte-aligned HDR bloom horizontal blur scratch buffer.
606 #[get(skip)]
607 #[get_mut(skip)]
608 #[set(skip)]
609 pub(crate) bloom_b: Vec<[f32; 4]>,
610 /// Quarter-res active-bloom tile mask (`1` when any bilinear corner contributes `>= 1` RGB LSB) skipping dark tiles in post-processing.
611 #[get(skip)]
612 #[get_mut(skip)]
613 #[set(skip)]
614 pub(crate) bloom_tile_active: Vec<u8>,
615 /// Reusable front-to-back object sorting scratch buffer.
616 #[get(skip)]
617 #[get_mut(skip)]
618 #[set(skip)]
619 pub(crate) visible_scratch: Vec<(f32, usize)>,
620 /// Reusable meshlet triangle-range scratch buffer eliminating per-object heap allocations.
621 #[get(skip)]
622 #[get_mut(skip)]
623 #[set(skip)]
624 pub(crate) cluster_ranges_scratch: Vec<(usize, usize)>,
625 /// Reusable per-object transformed vertex cache `(clip_pos, world_pos)` avoiding redundant vertex transforms.
626 #[get(skip)]
627 #[get_mut(skip)]
628 #[set(skip)]
629 pub(crate) projected_verts_scratch: Vec<([f32; 4], Vec3)>,
630 /// Reusable unique mesh-id set for instancing telemetry.
631 #[get(skip)]
632 #[get_mut(skip)]
633 #[set(skip)]
634 pub(crate) unique_meshes_scratch: HashSet<usize>,
635 /// Reusable saved dynamic-object transforms for zero-allocation interpolated rendering.
636 #[get(skip)]
637 #[get_mut(skip)]
638 #[set(skip)]
639 pub(crate) saved_objs_scratch: Vec<(usize, Transform3D, Aabb3D)>,
640 /// Reusable screen-space triangle setup list for parallel tiled rasterization.
641 #[get(skip)]
642 #[get_mut(skip)]
643 #[set(skip)]
644 pub(crate) raster_tris_scratch: Vec<RasterTri2D>,
645 /// Reusable per-tile triangle count array for flat CSR binning.
646 #[get(skip)]
647 #[get_mut(skip)]
648 #[set(skip)]
649 pub(crate) tile_counts_scratch: Vec<u32>,
650 /// Reusable flat CSR prefix-sum offset array (`total_tiles + 1`).
651 #[get(skip)]
652 #[get_mut(skip)]
653 #[set(skip)]
654 pub(crate) tile_offsets_scratch: Vec<u32>,
655 /// Reusable per-tile insertion cursor array for flat CSR binning.
656 #[get(skip)]
657 #[get_mut(skip)]
658 #[set(skip)]
659 pub(crate) tile_cursors_scratch: Vec<u32>,
660 /// Reusable flat array of binned triangle indices across all screen tiles.
661 #[get(skip)]
662 #[get_mut(skip)]
663 #[set(skip)]
664 pub(crate) tile_tri_indices_scratch: Vec<u32>,
665 /// Optional shared-device GPU composite target for zero-readback single-pass UI+3D compositing.
666 #[get(skip)]
667 #[get_mut(skip)]
668 #[set(skip)]
669 pub(crate) gpu_target: GpuCompositeTarget,
670 /// Whether `aa_buffer` holds a valid previous frame compatible with temporal anti-aliasing.
671 #[get(skip)]
672 #[get_mut(skip)]
673 #[set(skip)]
674 pub(crate) has_taa_history: bool,
675 /// Previous frame view-projection fingerprint used to detect camera cuts for TAA.
676 #[get(skip)]
677 #[get_mut(skip)]
678 #[set(skip)]
679 pub(crate) prev_vp_m0: f32,
680 /// Monotonic frame counter driving Halton(2, 3) temporal subpixel jitter.
681 #[get(skip)]
682 #[get_mut(skip)]
683 #[set(skip)]
684 pub(crate) frame_index: u32,
685 /// Last rendered `World3D::world_revision` enabling HUD-only dirty frames to reuse the cached 3D frame.
686 #[get(type(copy))]
687 pub(crate) last_world_revision: u64,
688 /// Quality and viewport configuration fingerprint paired with `last_world_revision`.
689 #[get(skip)]
690 #[get_mut(skip)]
691 #[set(skip)]
692 pub(crate) last_quality_fingerprint: u64,
693 /// Number of consecutive static-world TAA accumulation frames completed since the last world change.
694 #[get(type(copy))]
695 pub(crate) taa_accumulated_frames: u32,
696 /// Total HUD-only dirty frames satisfied from the cached 3D framebuffer without re-rasterizing.
697 #[get(type(copy))]
698 pub(crate) cached_world_reuses: u64,
699 /// Last rendered internal width.
700 #[get(type(copy))]
701 pub(crate) width: u32,
702 /// Last rendered internal height.
703 #[get(type(copy))]
704 pub(crate) height: u32,
705 /// Telemetry from the most recent frame.
706 #[get(type(copy))]
707 pub(crate) last_stats: RenderStats3D,
708}