Skip to main content

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

1use super::*;
2
3/// Default session configuration targeting interactive path tracing with AgX tone mapping and SVGF denoising.
4impl Default for RaytraceConfig {
5    /// Creates a default `RaytraceConfig` at `320x180` using `PathTrace`, `Agx`, and `SvgfDenoiser`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default ray-tracing configuration.
10    fn default() -> Self {
11        Self::new(RT_DEFAULT_VIEWPORT_WIDTH, RT_DEFAULT_VIEWPORT_HEIGHT)
12    }
13}
14
15/// Constructors and fluent configuration helpers for `RaytraceConfig`.
16impl RaytraceConfig {
17    /// Creates a `RaytraceConfig` sized for `width x height` pixels with sensible path-tracing defaults.
18    ///
19    /// # Arguments
20    ///
21    /// - `u32` - Viewport width in pixels.
22    /// - `u32` - Viewport height in pixels.
23    ///
24    /// # Returns
25    ///
26    /// - `Self` - Configured `RaytraceConfig`.
27    #[must_use]
28    pub fn new(width: u32, height: u32) -> Self {
29        Self {
30            width: width.max(1),
31            height: height.max(1),
32            integrator: RtIntegratorMode::PathTrace,
33            tonemap: RtTonemapMode::Agx,
34            exposure: RT_DEFAULT_EXPOSURE,
35            tile_size: RT_DEFAULT_TILE_SIZE,
36            enable_denoiser: true,
37            whitted: WhittedIntegrator::default(),
38            path_trace: PathTraceIntegrator::default(),
39            rtao: RtaoIntegrator::default(),
40            hybrid_preview: HybridPreviewIntegrator::default(),
41            svgf: SvgfConfig::default(),
42            seed: RT_DEFAULT_SEED,
43        }
44    }
45
46    /// Selects the active ray-tracing integrator mode.
47    ///
48    /// # Arguments
49    ///
50    /// - `Self` - Base configuration.
51    /// - `RtIntegratorMode` - Integrator mode to activate.
52    ///
53    /// # Returns
54    ///
55    /// - `Self` - Updated configuration.
56    #[must_use]
57    pub fn with_integrator(mut self, integrator: RtIntegratorMode) -> Self {
58        self.set_integrator(integrator);
59        self
60    }
61
62    /// Selects the display tone-mapping operator.
63    ///
64    /// # Arguments
65    ///
66    /// - `Self` - Base configuration.
67    /// - `RtTonemapMode` - Tone-mapping curve.
68    ///
69    /// # Returns
70    ///
71    /// - `Self` - Updated configuration.
72    #[must_use]
73    pub fn with_tonemap(mut self, tonemap: RtTonemapMode) -> Self {
74        self.set_tonemap(tonemap);
75        self
76    }
77
78    /// Sets the linear HDR exposure multiplier.
79    ///
80    /// # Arguments
81    ///
82    /// - `Self` - Base configuration.
83    /// - `f32` - Positive exposure multiplier.
84    ///
85    /// # Returns
86    ///
87    /// - `Self` - Updated configuration.
88    #[must_use]
89    pub fn with_exposure(mut self, exposure: f32) -> Self {
90        self.set_exposure(exposure.max(0.01));
91        self
92    }
93
94    /// Sets the square tile edge size in pixels for progressive stepping.
95    ///
96    /// # Arguments
97    ///
98    /// - `Self` - Base configuration.
99    /// - `u32` - Tile width/height in pixels (`>= 1`).
100    ///
101    /// # Returns
102    ///
103    /// - `Self` - Updated configuration.
104    #[must_use]
105    pub fn with_tile_size(mut self, tile_size: u32) -> Self {
106        self.set_tile_size(tile_size.max(1));
107        self
108    }
109
110    /// Enables or disables the multi-pass À-Trous SVGF spatial denoiser.
111    ///
112    /// # Arguments
113    ///
114    /// - `Self` - Base configuration.
115    /// - `bool` - Whether SVGF denoising runs after accumulation.
116    ///
117    /// # Returns
118    ///
119    /// - `Self` - Updated configuration.
120    #[must_use]
121    pub fn with_denoiser(mut self, enabled: bool) -> Self {
122        self.set_enable_denoiser(enabled);
123        self
124    }
125
126    /// Overrides the SVGF denoiser configuration.
127    ///
128    /// # Arguments
129    ///
130    /// - `Self` - Base configuration.
131    /// - `SvgfConfig` - Denoiser edge-stopping parameters.
132    ///
133    /// # Returns
134    ///
135    /// - `Self` - Updated configuration.
136    #[must_use]
137    pub fn with_svgf(mut self, svgf: SvgfConfig) -> Self {
138        self.set_svgf(svgf);
139        self
140    }
141
142    /// Overrides the deterministic base RNG seed.
143    ///
144    /// # Arguments
145    ///
146    /// - `Self` - Base configuration.
147    /// - `u32` - Seed integer.
148    ///
149    /// # Returns
150    ///
151    /// - `Self` - Updated configuration.
152    #[must_use]
153    pub fn with_seed(mut self, seed: u32) -> Self {
154        self.set_seed(seed);
155        self
156    }
157}
158
159/// Zero-steady-state-allocation progressive rendering, resizing, and framebuffer access for `RaytraceSession`.
160impl RaytraceSession {
161    /// Creates a new `RaytraceSession`, pre-allocating all HDR accumulation, G-buffer, denoiser, and RGBA8 buffers once.
162    ///
163    /// # Arguments
164    ///
165    /// - `RaytraceConfig` - Session resolution, integrator, denoiser, and tone-mapping parameters.
166    ///
167    /// # Returns
168    ///
169    /// - `Self` - Ready-to-render zero-steady-state-allocation session.
170    #[must_use]
171    pub fn new(config: RaytraceConfig) -> Self {
172        let width: u32 = config.get_width().max(1);
173        let height: u32 = config.get_height().max(1);
174        let total_pixels: usize = (width as usize).saturating_mul(height as usize);
175        let mut stats: RaytraceStats = RaytraceStats::default();
176        stats.set_total_pixels(total_pixels as u32);
177        Self {
178            config,
179            accumulator: TemporalAccumulator::new(width, height),
180            gbuffer: RtGBuffer::new(width, height),
181            denoiser: SvgfDenoiser::new(width, height, config.get_svgf()),
182            variance_scratch: vec![0.0; total_pixels],
183            denoised_hdr: vec![Vec3::zero(); total_pixels],
184            rgba8_output: vec![0; total_pixels.saturating_mul(4)],
185            stats,
186            tile_cursor: 0,
187            pass_index: 0,
188        }
189    }
190
191    /// Resizes all persistent session buffers and resets progressive accumulation.
192    ///
193    /// # Arguments
194    ///
195    /// - `&Self` - Mutable session reference.
196    /// - `u32` - New viewport width in pixels.
197    /// - `u32` - New viewport height in pixels.
198    pub fn resize(&mut self, width: u32, height: u32) {
199        let w: u32 = width.max(1);
200        let h: u32 = height.max(1);
201        let total_pixels: usize = (w as usize).saturating_mul(h as usize);
202        let Self {
203            config,
204            accumulator,
205            gbuffer,
206            denoiser,
207            variance_scratch,
208            denoised_hdr,
209            rgba8_output,
210            stats,
211            tile_cursor,
212            pass_index,
213        } = self;
214        config.set_width(w);
215        config.set_height(h);
216        accumulator.resize(w, h);
217        gbuffer.resize(w, h);
218        denoiser.resize(w, h);
219        variance_scratch.resize(total_pixels, 0.0);
220        denoised_hdr.resize(total_pixels, Vec3::zero());
221        rgba8_output.resize(total_pixels.saturating_mul(4), 0);
222        *stats = RaytraceStats::default();
223        stats.set_total_pixels(total_pixels as u32);
224        *tile_cursor = 0;
225        *pass_index = 0;
226    }
227
228    /// Resets progressive accumulation, G-buffers, tile progress, and ray telemetry in place with zero heap allocation.
229    ///
230    /// # Arguments
231    ///
232    /// - `&Self` - Mutable session reference.
233    pub fn reset(&mut self) {
234        let total_pixels: u32 = self
235            .get_config()
236            .get_width()
237            .saturating_mul(self.get_config().get_height());
238        let Self {
239            accumulator,
240            gbuffer,
241            variance_scratch,
242            denoised_hdr,
243            rgba8_output,
244            stats,
245            tile_cursor,
246            pass_index,
247            ..
248        } = self;
249        accumulator.reset_accumulation();
250        gbuffer.clear();
251        variance_scratch.fill(0.0);
252        denoised_hdr.fill(Vec3::zero());
253        rgba8_output.fill(0);
254        *stats = RaytraceStats::default();
255        stats.set_total_pixels(total_pixels);
256        *tile_cursor = 0;
257        *pass_index = 0;
258    }
259
260    /// Switches the active integrator mode and resets temporal accumulation in place.
261    ///
262    /// # Arguments
263    ///
264    /// - `&Self` - Mutable session reference.
265    /// - `RtIntegratorMode` - New integrator mode.
266    pub fn set_integrator(&mut self, mode: RtIntegratorMode) {
267        if self.get_config().get_integrator() != mode {
268            let mut cfg: RaytraceConfig = self.get_config();
269            cfg.set_integrator(mode);
270            self.set_config(cfg);
271            self.reset();
272        }
273    }
274
275    /// Executes one non-blocking tiled progressive rendering step up to `budget_rays` with zero steady-state heap allocations.
276    ///
277    /// # Arguments
278    ///
279    /// - `&Self` - Mutable session owning persistent HDR, G-buffer, denoiser, and RGBA8 buffers.
280    /// - `&RaytraceScene` - Scene to ray-trace.
281    /// - `u64` - Ray budget limiting work per UI frame (`>= 1`; stops early at pass completion).
282    ///
283    /// # Returns
284    ///
285    /// - `RaytraceStats` - Updated telemetry including samples per pixel, ray breakdowns, and MRays/sec.
286    pub fn render_progressive_step(
287        &mut self,
288        scene: &RaytraceScene,
289        budget_rays: u64,
290    ) -> RaytraceStats {
291        let step_start: RtTimer = rt_now();
292        let cam_fp: u64 = scene.get_camera().motion_fingerprint();
293        let scene_rev: u64 = scene.get_revision();
294        let cfg: RaytraceConfig = self.get_config();
295        let width: u32 = cfg.get_width().max(1);
296        let height: u32 = cfg.get_height().max(1);
297        let total_pixels: u32 = width.saturating_mul(height);
298        let tile_size: u32 = cfg.get_tile_size().max(1);
299        let tiles_x: u32 = width.div_ceil(tile_size);
300        let tiles_y: u32 = height.div_ceil(tile_size);
301        let total_tiles: u32 = tiles_x.saturating_mul(tiles_y).max(1);
302        let Self {
303            accumulator,
304            gbuffer,
305            denoiser,
306            variance_scratch,
307            denoised_hdr,
308            rgba8_output,
309            stats,
310            tile_cursor,
311            pass_index,
312            ..
313        } = self;
314        if accumulator.sync_motion(cam_fp, scene_rev) {
315            gbuffer.clear();
316            variance_scratch.fill(0.0);
317            *tile_cursor = 0;
318            *pass_index = 0;
319            *stats = RaytraceStats::default();
320            stats.set_total_pixels(total_pixels);
321        }
322        denoiser.set_config(cfg.get_svgf());
323        let ray_budget: u64 = budget_rays.max(1);
324        let mut step_counter: RtRayCounter = RtRayCounter::default();
325        let mut pixels_this_step: u32 = 0;
326        let camera: RtCamera = scene.get_camera();
327        let base_seed: u32 = cfg.get_seed();
328        let resolution: [u32; 2] = [width, height];
329        let mut tiles_processed: u32 = 0;
330        while step_counter.total_rays() < ray_budget && tiles_processed < total_tiles {
331            let tile_idx: u32 = *tile_cursor;
332            let tx: u32 = tile_idx % tiles_x;
333            let ty: u32 = tile_idx / tiles_x;
334            let x_start: u32 = tx.saturating_mul(tile_size);
335            let y_start: u32 = ty.saturating_mul(tile_size);
336            let x_end: u32 = x_start.saturating_add(tile_size).min(width);
337            let y_end: u32 = y_start.saturating_add(tile_size).min(height);
338            let current_pass: u32 = *pass_index;
339            let jitter: [f32; 2] = r2_subpixel_jitter(current_pass);
340            for py in y_start..y_end {
341                let row_offset: usize = (py as usize) * (width as usize);
342                for px in x_start..x_end {
343                    let pixel_idx: usize = row_offset + (px as usize);
344                    let mut rng: RtRng =
345                        RtRng::from_pixel_sample(pixel_idx as u32, current_pass, base_seed);
346                    let lens_xi: [f32; 2] = rng.next_f32_pair();
347                    let ray: Ray3D = camera.generate_ray([px, py], resolution, jitter, lens_xi);
348                    let sample_out: RtSampleOutput =
349                        dispatch_integrator_ray(&cfg, scene, &ray, &mut rng, &mut step_counter);
350                    accumulator.accumulate_pixel(pixel_idx, sample_out.get_radiance());
351                    if current_pass == 0 || gbuffer.get_hit_mask()[pixel_idx] == 0 {
352                        gbuffer.set_pixel(
353                            pixel_idx,
354                            sample_out.get_albedo(),
355                            sample_out.get_normal(),
356                            sample_out.get_depth(),
357                            sample_out.get_hit(),
358                        );
359                    }
360                    pixels_this_step = pixels_this_step.saturating_add(1);
361                }
362            }
363            tiles_processed += 1;
364            *tile_cursor += 1;
365            if *tile_cursor >= total_tiles {
366                *tile_cursor = 0;
367                *pass_index = pass_index.saturating_add(1);
368                break;
369            }
370        }
371        let denoise_start: RtTimer = rt_now();
372        if cfg.get_enable_denoiser() {
373            accumulator.write_variance_into(gbuffer, variance_scratch.as_mut_slice());
374            denoiser.denoise(
375                accumulator.get_radiance().as_slice(),
376                variance_scratch.as_slice(),
377                gbuffer,
378                denoised_hdr.as_mut_slice(),
379            );
380        } else {
381            denoised_hdr.copy_from_slice(accumulator.get_radiance().as_slice());
382        }
383        let denoise_ms: f32 = rt_elapsed_ms(denoise_start);
384        tonemap_hdr_to_rgba8(
385            denoised_hdr.as_slice(),
386            cfg.get_tonemap(),
387            cfg.get_exposure(),
388            rgba8_output.as_mut_slice(),
389        );
390        let step_ms: f32 = rt_elapsed_ms(step_start);
391        let step_rays: u64 = step_counter.total_rays();
392        let mrays_per_sec: f32 = if step_ms > 1e-4 {
393            ((step_rays as f32) / (step_ms * 1000.0)).max(0.0)
394        } else {
395            0.0
396        };
397        let next_primary: u64 = stats
398            .get_primary_rays()
399            .saturating_add(step_counter.get_primary_rays());
400        let next_shadow: u64 = stats
401            .get_shadow_rays()
402            .saturating_add(step_counter.get_shadow_rays());
403        let next_bounce: u64 = stats
404            .get_bounce_rays()
405            .saturating_add(step_counter.get_bounce_rays());
406        let next_total: u64 = next_primary
407            .saturating_add(next_shadow)
408            .saturating_add(next_bounce);
409        stats.set_samples_per_pixel(accumulator.average_samples_per_pixel());
410        stats.set_completed_passes(*pass_index);
411        stats.set_primary_rays(next_primary);
412        stats.set_shadow_rays(next_shadow);
413        stats.set_bounce_rays(next_bounce);
414        stats.set_total_rays(next_total);
415        stats.set_last_step_rays(step_rays);
416        stats.set_last_step_ms(step_ms);
417        stats.set_mrays_per_sec(mrays_per_sec);
418        stats.set_denoise_ms(denoise_ms);
419        stats.set_pixels_traced_in_pass(if *tile_cursor == 0 {
420            total_pixels
421        } else {
422            stats
423                .get_pixels_traced_in_pass()
424                .saturating_add(pixels_this_step)
425                .min(total_pixels)
426        });
427        stats.set_total_pixels(total_pixels);
428        *stats
429    }
430
431    /// Renders one complete full-frame pass across all viewport pixels with zero steady-state allocations.
432    ///
433    /// # Arguments
434    ///
435    /// - `&Self` - Mutable session reference.
436    /// - `&RaytraceScene` - Scene to trace.
437    ///
438    /// # Returns
439    ///
440    /// - `RaytraceStats` - Telemetry after completing the pass.
441    pub fn render_full_pass(&mut self, scene: &RaytraceScene) -> RaytraceStats {
442        let start_pass: u32 = self.get_pass_index();
443        let mut latest: RaytraceStats = self.render_progressive_step(scene, u64::MAX);
444        if latest.get_completed_passes() == start_pass && self.get_tile_cursor() != 0 {
445            latest = self.render_progressive_step(scene, u64::MAX);
446        }
447        latest
448    }
449
450    /// Renders `samples` complete progressive passes sequentially and returns final telemetry.
451    ///
452    /// # Arguments
453    ///
454    /// - `&Self` - Mutable session reference.
455    /// - `&RaytraceScene` - Scene to trace.
456    /// - `u32` - Number of full samples per pixel to accumulate.
457    ///
458    /// # Returns
459    ///
460    /// - `RaytraceStats` - Final telemetry snapshot.
461    pub fn render_samples(&mut self, scene: &RaytraceScene, samples: u32) -> RaytraceStats {
462        let mut latest: RaytraceStats = self.get_stats();
463        for _ in 0..samples.max(1) {
464            latest = self.render_full_pass(scene);
465        }
466        latest
467    }
468
469    /// Returns a read-only view of the tone-mapped sRGB RGBA8 output framebuffer (`width * height * 4`).
470    ///
471    /// # Arguments
472    ///
473    /// - `&Self` - Session reference.
474    ///
475    /// # Returns
476    ///
477    /// - `&[u8]` - Contiguous RGBA8 byte slice ready for UI blitting or `ImageBuffer`.
478    #[must_use]
479    pub fn rgba8_slice(&self) -> &[u8] {
480        self.get_rgba8_output().as_slice()
481    }
482
483    /// Returns a read-only view of the linear denoised (or raw accumulated) HDR RGB buffer.
484    ///
485    /// # Arguments
486    ///
487    /// - `&Self` - Session reference.
488    ///
489    /// # Returns
490    ///
491    /// - `&[Vec3]` - Contiguous linear HDR RGB pixel slice.
492    #[must_use]
493    pub fn hdr_slice(&self) -> &[Vec3] {
494        self.get_denoised_hdr().as_slice()
495    }
496}