Skip to main content

euv_core/game/engine3d/raytrace/denoiser/
impl.rs

1use super::*;
2
3#[cfg(not(target_arch = "wasm32"))]
4// SAFETY: `EngineWorkerPool::parallel_for_chunks` assigns disjoint row ranges `y0..y1` to each worker.
5unsafe impl Sync for VarianceRowMutView {}
6
7#[cfg(not(target_arch = "wasm32"))]
8impl VarianceRowMutView {
9    /// Returns the base mutable variance pointer while capturing the `Sync` wrapper by reference.
10    ///
11    /// # Returns
12    ///
13    /// - `*mut f32` - Base pointer to the pre-allocated variance buffer.
14    #[must_use]
15    pub(crate) fn ptr(&self) -> *mut f32 {
16        let Self { var_ptr } = *self;
17        var_ptr
18    }
19}
20
21#[cfg(not(target_arch = "wasm32"))]
22// SAFETY: `EngineWorkerPool::parallel_for_chunks` assigns disjoint row ranges `y0..y1` to each worker.
23unsafe impl Sync for SvgfRowMutView {}
24
25#[cfg(not(target_arch = "wasm32"))]
26impl SvgfRowMutView {
27    /// Returns the base mutable `(color, variance)` pointers while capturing the `Sync` wrapper by reference.
28    ///
29    /// # Returns
30    ///
31    /// - `(*mut Vec3, *mut f32)` - Base pointers to destination color and variance buffers.
32    #[must_use]
33    pub(crate) fn ptrs(&self) -> (*mut Vec3, *mut f32) {
34        let Self { color_ptr, var_ptr } = *self;
35        (color_ptr, var_ptr)
36    }
37}
38
39/// Persistent G-buffer allocation, clearing, and per-pixel update helpers for `RtGBuffer`.
40impl RtGBuffer {
41    /// Allocates a new `RtGBuffer` sized for `width x height` pixels.
42    ///
43    /// # Arguments
44    ///
45    /// - `u32` - Viewport width in pixels.
46    /// - `u32` - Viewport height in pixels.
47    ///
48    /// # Returns
49    ///
50    /// - `Self` - Pre-allocated G-buffer.
51    #[must_use]
52    pub fn new(width: u32, height: u32) -> Self {
53        let len: usize = (width as usize).saturating_mul(height as usize);
54        Self {
55            width,
56            height,
57            albedo: vec![Vec3::zero(); len],
58            normal: vec![Vec3::zero(); len],
59            depth: vec![RT_SKY_DEPTH; len],
60            hit_mask: vec![0; len],
61        }
62    }
63
64    /// Resizes the G-buffer in place and clears all channels to default miss values.
65    ///
66    /// # Arguments
67    ///
68    /// - `&Self` - Mutable G-buffer reference.
69    /// - `u32` - New viewport width in pixels.
70    /// - `u32` - New viewport height in pixels.
71    pub fn resize(&mut self, width: u32, height: u32) {
72        let len: usize = (width as usize).saturating_mul(height as usize);
73        self.set_width(width);
74        self.set_height(height);
75        self.get_mut_albedo().resize(len, Vec3::zero());
76        self.get_mut_normal().resize(len, Vec3::zero());
77        self.get_mut_depth().resize(len, RT_SKY_DEPTH);
78        self.get_mut_hit_mask().resize(len, 0);
79        self.clear();
80    }
81
82    /// Resets all G-buffer channels in place with zero heap allocation.
83    ///
84    /// # Arguments
85    ///
86    /// - `&Self` - Mutable G-buffer reference.
87    pub fn clear(&mut self) {
88        self.get_mut_albedo().fill(Vec3::zero());
89        self.get_mut_normal().fill(Vec3::zero());
90        self.get_mut_depth().fill(RT_SKY_DEPTH);
91        self.get_mut_hit_mask().fill(0);
92    }
93
94    /// Writes primary G-buffer attributes for a single pixel index.
95    ///
96    /// # Arguments
97    ///
98    /// - `&Self` - Mutable G-buffer reference.
99    /// - `usize` - Linear pixel index (`py * width + px`).
100    /// - `Vec3` - Primary surface albedo.
101    /// - `Vec3` - Primary world-space shading normal.
102    /// - `f32` - Primary linear hit distance.
103    /// - `bool` - Whether the primary ray hit geometry.
104    pub fn set_pixel(
105        &mut self,
106        pixel_index: usize,
107        albedo: Vec3,
108        normal: Vec3,
109        depth: f32,
110        hit: bool,
111    ) {
112        if pixel_index >= self.get_depth().len() {
113            return;
114        }
115        self.get_mut_albedo()[pixel_index] = albedo;
116        self.get_mut_normal()[pixel_index] = normal;
117        self.get_mut_depth()[pixel_index] = depth;
118        self.get_mut_hit_mask()[pixel_index] = if hit { 1 } else { 0 };
119    }
120}
121
122/// Progressive temporal accumulation, variance tracking, and motion reset for `TemporalAccumulator`.
123impl TemporalAccumulator {
124    /// Creates a pre-allocated `TemporalAccumulator` for `width x height` pixels.
125    ///
126    /// # Arguments
127    ///
128    /// - `u32` - Viewport width in pixels.
129    /// - `u32` - Viewport height in pixels.
130    ///
131    /// # Returns
132    ///
133    /// - `Self` - Pre-allocated temporal accumulator.
134    #[must_use]
135    pub fn new(width: u32, height: u32) -> Self {
136        let len: usize = (width as usize).saturating_mul(height as usize);
137        Self {
138            width,
139            height,
140            radiance: vec![Vec3::zero(); len],
141            moment_1: vec![0.0; len],
142            moment_2: vec![0.0; len],
143            sample_counts: vec![0; len],
144            camera_fingerprint: 0,
145            scene_revision: 0,
146            max_history_samples: 0,
147            reset_count: 0,
148        }
149    }
150
151    /// Resizes all accumulation buffers and resets accumulated samples to zero.
152    ///
153    /// # Arguments
154    ///
155    /// - `&Self` - Mutable accumulator reference.
156    /// - `u32` - New viewport width in pixels.
157    /// - `u32` - New viewport height in pixels.
158    pub fn resize(&mut self, width: u32, height: u32) {
159        let len: usize = (width as usize).saturating_mul(height as usize);
160        self.set_width(width);
161        self.set_height(height);
162        self.get_mut_radiance().resize(len, Vec3::zero());
163        self.get_mut_moment_1().resize(len, 0.0);
164        self.get_mut_moment_2().resize(len, 0.0);
165        self.get_mut_sample_counts().resize(len, 0);
166        self.reset_accumulation();
167    }
168
169    /// Clears all accumulated radiance, luminance moments, and sample counts in place with zero heap allocation.
170    ///
171    /// # Arguments
172    ///
173    /// - `&Self` - Mutable accumulator reference.
174    pub fn reset_accumulation(&mut self) {
175        self.get_mut_radiance().fill(Vec3::zero());
176        self.get_mut_moment_1().fill(0.0);
177        self.get_mut_moment_2().fill(0.0);
178        self.get_mut_sample_counts().fill(0);
179        let next_resets: u64 = self.get_reset_count().saturating_add(1);
180        self.set_reset_count(next_resets);
181    }
182
183    /// Synchronizes camera and scene fingerprints, automatically resetting accumulation whenever either changes.
184    ///
185    /// # Arguments
186    ///
187    /// - `&Self` - Mutable accumulator reference.
188    /// - `u64` - Current `RtCamera::motion_fingerprint()`.
189    /// - `u64` - Current `RaytraceScene::get_revision()`.
190    ///
191    /// # Returns
192    ///
193    /// - `bool` - `true` when motion or scene mutation triggered an accumulation reset.
194    pub fn sync_motion(&mut self, camera_fingerprint: u64, scene_revision: u64) -> bool {
195        if self.get_camera_fingerprint() == camera_fingerprint
196            && self.get_scene_revision() == scene_revision
197        {
198            return false;
199        }
200        self.set_camera_fingerprint(camera_fingerprint);
201        self.set_scene_revision(scene_revision);
202        self.reset_accumulation();
203        true
204    }
205
206    /// Incorporates a new HDR radiance sample at `pixel_index`, updating running mean radiance and luminance moments (`M1`, `M2`).
207    ///
208    /// # Arguments
209    ///
210    /// - `&Self` - Mutable accumulator reference.
211    /// - `usize` - Linear pixel index.
212    /// - `Vec3` - Sanitized linear HDR RGB sample radiance.
213    pub fn accumulate_pixel(&mut self, pixel_index: usize, sample_radiance: Vec3) {
214        if pixel_index >= self.get_sample_counts().len() {
215            return;
216        }
217        let max_hist: u32 = self.get_max_history_samples();
218        let prev_n: u32 = self.get_sample_counts()[pixel_index];
219        let next_n: u32 = if max_hist > 0 {
220            prev_n.saturating_add(1).min(max_hist)
221        } else {
222            prev_n.saturating_add(1)
223        };
224        let alpha: f32 = 1.0 / (next_n.max(1) as f32);
225        let luma: f32 = rgb_luminance(sample_radiance);
226        let Self {
227            radiance,
228            moment_1,
229            moment_2,
230            sample_counts,
231            ..
232        } = self;
233        if prev_n == 0 {
234            radiance[pixel_index] = sample_radiance;
235            moment_1[pixel_index] = luma;
236            moment_2[pixel_index] = luma * luma;
237        } else {
238            radiance[pixel_index] = radiance[pixel_index].lerp(sample_radiance, alpha);
239            moment_1[pixel_index] += alpha * (luma - moment_1[pixel_index]);
240            moment_2[pixel_index] += alpha * (luma * luma - moment_2[pixel_index]);
241        }
242        sample_counts[pixel_index] = next_n;
243    }
244
245    /// Returns the tracked temporal luminance variance `max(0, M2 - M1^2)` for `pixel_index`.
246    ///
247    /// # Arguments
248    ///
249    /// - `&Self` - Accumulator reference.
250    /// - `usize` - Linear pixel index.
251    ///
252    /// # Returns
253    ///
254    /// - `f32` - Non-negative temporal variance estimate.
255    #[must_use]
256    pub fn pixel_variance(&self, pixel_index: usize) -> f32 {
257        if pixel_index >= self.get_moment_1().len() {
258            return 0.0;
259        }
260        let m1: f32 = self.get_moment_1()[pixel_index];
261        let m2: f32 = self.get_moment_2()[pixel_index];
262        (m2 - m1 * m1).max(0.0)
263    }
264
265    /// Writes per-pixel temporal (or 3x3 spatial fallback at `spp <= 1`) luminance variance into `out_variance` with zero heap allocation.
266    ///
267    /// # Arguments
268    ///
269    /// - `&Self` - Accumulator reference.
270    /// - `&RtGBuffer` - Primary G-buffer used for edge-aware 1-spp spatial variance fallback.
271    /// - `&mut [f32]` - Pre-allocated output variance slice (`len == width * height`).
272    pub fn write_variance_into(&self, gbuffer: &RtGBuffer, out_variance: &mut [f32]) {
273        let w: usize = self.get_width() as usize;
274        let h: usize = self.get_height() as usize;
275        let len: usize = w.saturating_mul(h);
276        if out_variance.len() < len || len == 0 {
277            return;
278        }
279        #[cfg(not(target_arch = "wasm32"))]
280        if h >= 16 && len >= 4096 {
281            let view: VarianceRowMutView = VarianceRowMutView {
282                var_ptr: out_variance.as_mut_ptr(),
283            };
284            global_engine_worker_pool().parallel_for_chunks(
285                h,
286                8,
287                |y0: usize, y1: usize, _: usize| {
288                    let offset: usize = y0 * w;
289                    let slice_len: usize = (y1 - y0) * w;
290                    // SAFETY: Workers receive strictly disjoint row spans `[y0..y1)` within `len`.
291                    let row_out: &mut [f32] =
292                        unsafe { from_raw_parts_mut(view.ptr().add(offset), slice_len) };
293                    eval_variance_row_band(self, gbuffer, y0, y1, row_out);
294                },
295            );
296            return;
297        }
298        eval_variance_row_band(self, gbuffer, 0, h, &mut out_variance[..len]);
299    }
300
301    /// Computes the average temporal variance across all accumulated pixels.
302    ///
303    /// # Arguments
304    ///
305    /// - `&Self` - Accumulator reference.
306    ///
307    /// # Returns
308    ///
309    /// - `f32` - Mean pixel luminance variance.
310    #[must_use]
311    pub fn average_variance(&self) -> f32 {
312        let len: usize = self.get_moment_1().len();
313        if len == 0 {
314            return 0.0;
315        }
316        let mut sum: f32 = 0.0;
317        for idx in 0..len {
318            sum += self.pixel_variance(idx);
319        }
320        sum / (len as f32)
321    }
322
323    /// Computes the average accumulated sample count per pixel across the viewport.
324    ///
325    /// # Arguments
326    ///
327    /// - `&Self` - Accumulator reference.
328    ///
329    /// # Returns
330    ///
331    /// - `f32` - Mean samples per pixel (`spp`).
332    #[must_use]
333    pub fn average_samples_per_pixel(&self) -> f32 {
334        let counts: &[u32] = self.get_sample_counts().as_slice();
335        if counts.is_empty() {
336            return 0.0;
337        }
338        let mut sum: u64 = 0;
339        for &c in counts {
340            sum = sum.saturating_add(c as u64);
341        }
342        (sum as f32) / (counts.len() as f32)
343    }
344}
345
346/// Default SVGF edge-stopping configuration constructor for `SvgfConfig`.
347impl Default for SvgfConfig {
348    /// Creates a balanced 4-iteration À-Trous SVGF configuration preserving crisp normals and depth edges.
349    ///
350    /// # Returns
351    ///
352    /// - `Self` - Default `SvgfConfig`.
353    fn default() -> Self {
354        Self {
355            iterations: SVGF_DEFAULT_ITERATIONS,
356            phi_normal: SVGF_DEFAULT_PHI_NORMAL,
357            phi_depth: SVGF_DEFAULT_PHI_DEPTH,
358            phi_luma: SVGF_DEFAULT_PHI_LUMA,
359            variance_floor: 1.0e-4,
360            demodulate_albedo: false,
361        }
362    }
363}
364
365/// Zero-allocation multi-pass À-Trous wavelet spatial denoising for `SvgfDenoiser`.
366impl SvgfDenoiser {
367    /// Creates a pre-allocated `SvgfDenoiser` for `width x height` pixels with the specified `config`.
368    ///
369    /// # Arguments
370    ///
371    /// - `u32` - Viewport width in pixels.
372    /// - `u32` - Viewport height in pixels.
373    /// - `SvgfConfig` - Edge-stopping and iteration parameters.
374    ///
375    /// # Returns
376    ///
377    /// - `Self` - Pre-allocated denoiser ready for zero-alloc `denoise()` calls.
378    #[must_use]
379    pub fn new(width: u32, height: u32, config: SvgfConfig) -> Self {
380        let len: usize = (width as usize).saturating_mul(height as usize);
381        Self {
382            config,
383            width,
384            height,
385            ping_color: vec![Vec3::zero(); len],
386            pong_color: vec![Vec3::zero(); len],
387            ping_variance: vec![0.0; len],
388            pong_variance: vec![0.0; len],
389        }
390    }
391
392    /// Resizes internal ping-pong scratch buffers to match `width x height`.
393    ///
394    /// # Arguments
395    ///
396    /// - `&Self` - Mutable denoiser reference.
397    /// - `u32` - New viewport width.
398    /// - `u32` - New viewport height.
399    pub fn resize(&mut self, width: u32, height: u32) {
400        let len: usize = (width as usize).saturating_mul(height as usize);
401        let Self {
402            width: w_ref,
403            height: h_ref,
404            ping_color,
405            pong_color,
406            ping_variance,
407            pong_variance,
408            ..
409        } = self;
410        *w_ref = width;
411        *h_ref = height;
412        ping_color.resize(len, Vec3::zero());
413        pong_color.resize(len, Vec3::zero());
414        ping_variance.resize(len, 0.0);
415        pong_variance.resize(len, 0.0);
416    }
417
418    /// Executes multi-pass edge-stopping À-Trous wavelet spatial filtering with zero steady-state heap allocations.
419    ///
420    /// # Arguments
421    ///
422    /// - `&Self` - Mutable denoiser owning pre-allocated ping-pong buffers.
423    /// - `&[Vec3]` - Input noisy or temporally accumulated HDR radiance buffer.
424    /// - `&[f32]` - Per-pixel luminance variance buffer guiding `phi_luma`.
425    /// - `&RtGBuffer` - Primary G-buffer supplying world normals, linear depth, albedo, and hit mask.
426    /// - `&mut [Vec3]` - Destination denoised HDR radiance slice (`len == width * height`).
427    pub fn denoise(
428        &mut self,
429        input_radiance: &[Vec3],
430        input_variance: &[f32],
431        gbuffer: &RtGBuffer,
432        output: &mut [Vec3],
433    ) {
434        let w: usize = self.get_width() as usize;
435        let h: usize = self.get_height() as usize;
436        let len: usize = w.saturating_mul(h);
437        if len == 0
438            || input_radiance.len() < len
439            || input_variance.len() < len
440            || output.len() < len
441            || gbuffer.get_normal().len() < len
442            || gbuffer.get_depth().len() < len
443            || gbuffer.get_hit_mask().len() < len
444        {
445            return;
446        }
447        let cfg: SvgfConfig = self.get_config();
448        let iterations: u32 = cfg.get_iterations().clamp(1, SVGF_MAX_ITERATIONS);
449        let demod: bool = cfg.get_demodulate_albedo();
450        let albedos: &[Vec3] = gbuffer.get_albedo().as_slice();
451        let hit_mask: &[u8] = gbuffer.get_hit_mask().as_slice();
452        let Self {
453            ping_color,
454            pong_color,
455            ping_variance,
456            pong_variance,
457            ..
458        } = self;
459        for idx in 0..len {
460            let raw: Vec3 = input_radiance[idx];
461            if demod && hit_mask[idx] != 0 {
462                let alb: Vec3 = albedos[idx];
463                ping_color[idx] = Vec3::new(
464                    raw.get_x() / alb.get_x().max(SVGF_ALBEDO_DEMOD_FLOOR),
465                    raw.get_y() / alb.get_y().max(SVGF_ALBEDO_DEMOD_FLOOR),
466                    raw.get_z() / alb.get_z().max(SVGF_ALBEDO_DEMOD_FLOOR),
467                );
468            } else {
469                ping_color[idx] = raw;
470            }
471            ping_variance[idx] = input_variance[idx].max(0.0);
472        }
473        for pass in 0..iterations {
474            let step: isize = 1_isize << pass;
475            let src_color: &[Vec3] = ping_color.as_slice();
476            let src_var: &[f32] = ping_variance.as_slice();
477            #[cfg(not(target_arch = "wasm32"))]
478            if h >= 16 && len >= 4096 {
479                let row_view: SvgfRowMutView = SvgfRowMutView {
480                    color_ptr: pong_color.as_mut_ptr(),
481                    var_ptr: pong_variance.as_mut_ptr(),
482                };
483                global_engine_worker_pool().parallel_for_chunks(
484                    h,
485                    8,
486                    |y0: usize, y1: usize, _: usize| {
487                        let offset: usize = y0 * w;
488                        let slice_len: usize = (y1 - y0) * w;
489                        let (c_ptr, v_ptr): (*mut Vec3, *mut f32) = row_view.ptrs();
490                        // SAFETY: Workers receive strictly disjoint row spans `[y0..y1)` within `len`.
491                        let (dst_c, dst_v): (&mut [Vec3], &mut [f32]) = unsafe {
492                            (
493                                from_raw_parts_mut(c_ptr.add(offset), slice_len),
494                                from_raw_parts_mut(v_ptr.add(offset), slice_len),
495                            )
496                        };
497                        eval_atrous_row_band(
498                            cfg,
499                            gbuffer,
500                            (src_color, src_var),
501                            step,
502                            (y0, y1),
503                            (dst_c, dst_v),
504                        );
505                    },
506                );
507            } else {
508                eval_atrous_row_band(
509                    cfg,
510                    gbuffer,
511                    (src_color, src_var),
512                    step,
513                    (0, h),
514                    (&mut pong_color[..len], &mut pong_variance[..len]),
515                );
516            }
517            #[cfg(target_arch = "wasm32")]
518            {
519                eval_atrous_row_band(
520                    cfg,
521                    gbuffer,
522                    (src_color, src_var),
523                    step,
524                    (0, h),
525                    (&mut pong_color[..len], &mut pong_variance[..len]),
526                );
527            }
528            swap(ping_color, pong_color);
529            swap(ping_variance, pong_variance);
530        }
531        for idx in 0..len {
532            let filtered: Vec3 = ping_color[idx];
533            if demod && hit_mask[idx] != 0 {
534                let alb: Vec3 = albedos[idx];
535                output[idx] = Vec3::new(
536                    (filtered.get_x() * alb.get_x().max(SVGF_ALBEDO_DEMOD_FLOOR)).max(0.0),
537                    (filtered.get_y() * alb.get_y().max(SVGF_ALBEDO_DEMOD_FLOOR)).max(0.0),
538                    (filtered.get_z() * alb.get_z().max(SVGF_ALBEDO_DEMOD_FLOOR)).max(0.0),
539                );
540            } else {
541                output[idx] = Vec3::new(
542                    filtered.get_x().max(0.0),
543                    filtered.get_y().max(0.0),
544                    filtered.get_z().max(0.0),
545                );
546            }
547        }
548    }
549}