Skip to main content

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

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