Skip to main content

euv_core/render/pipeline/
impl.rs

1use super::*;
2
3/// Fluent builder helpers for `FrameRenderParams`.
4impl FrameRenderParams {
5    /// Creates frame render parameters for `viewport` with `1.0` scale, white clear color, and full damage.
6    ///
7    /// # Arguments
8    ///
9    /// - `Size` - Logical viewport size.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Ready render parameters.
14    #[must_use]
15    pub fn new(viewport: Size) -> Self {
16        Self {
17            viewport,
18            scale_factor: 1.0,
19            clear_color: COLOR_WHITE,
20            layout_stats: LayoutStats::default(),
21            damage: DamageRegion::full(),
22        }
23    }
24
25    /// Sets the active DPI scale factor.
26    ///
27    /// # Arguments
28    ///
29    /// - `Self` - Base parameters.
30    /// - `f32` - Scale factor.
31    ///
32    /// # Returns
33    ///
34    /// - `Self` - Updated parameters.
35    #[must_use]
36    pub fn with_scale(mut self, scale_factor: f32) -> Self {
37        self.set_scale_factor(scale_factor.max(0.5));
38        self
39    }
40
41    /// Sets the surface clear color.
42    ///
43    /// # Arguments
44    ///
45    /// - `Self` - Base parameters.
46    /// - `Color` - Clear color.
47    ///
48    /// # Returns
49    ///
50    /// - `Self` - Updated parameters.
51    #[must_use]
52    pub fn with_clear(mut self, clear_color: Color) -> Self {
53        self.set_clear_color(clear_color);
54        self
55    }
56
57    /// Attaches layout telemetry from the current frame.
58    ///
59    /// # Arguments
60    ///
61    /// - `Self` - Base parameters.
62    /// - `LayoutStats` - Layout pass statistics.
63    ///
64    /// # Returns
65    ///
66    /// - `Self` - Updated parameters.
67    #[must_use]
68    pub fn with_layout_stats(mut self, layout_stats: LayoutStats) -> Self {
69        self.set_layout_stats(layout_stats);
70        self
71    }
72
73    /// Sets the active dirty damage region.
74    ///
75    /// # Arguments
76    ///
77    /// - `Self` - Base parameters.
78    /// - `DamageRegion` - Damage region.
79    ///
80    /// # Returns
81    ///
82    /// - `Self` - Updated parameters.
83    #[must_use]
84    pub fn with_damage(mut self, damage: DamageRegion) -> Self {
85        self.set_damage(damage);
86        self
87    }
88}
89
90/// Multi-mode pipeline construction, live mode switching, and frame rendering for `Renderer`.
91impl Renderer {
92    /// Creates a `Renderer` resolving the optimal backend for `platform` and `config`.
93    ///
94    /// # Arguments
95    ///
96    /// - `PlatformKind` - Active execution platform.
97    /// - `PlatformCapabilities` - Hardware capabilities reported by the platform backend.
98    /// - `u32` - Initial physical width.
99    /// - `u32` - Initial physical height.
100    /// - `RenderConfig` - Requested rendering configuration.
101    ///
102    /// # Returns
103    ///
104    /// - `Self` - Initialized multi-mode renderer facade.
105    #[must_use]
106    pub fn new(
107        platform: PlatformKind,
108        capabilities: PlatformCapabilities,
109        width: u32,
110        height: u32,
111        config: RenderConfig,
112    ) -> Self {
113        let (active_mode, active_backend): (RenderMode, GraphicsBackend) =
114            Self::resolve_mode_and_backend(platform, capabilities, config);
115        let readback_mirror: bool = true;
116        let compute_pixel_hash: bool =
117            platform == PlatformKind::Headless || active_backend == GraphicsBackend::Headless;
118        let font_provider: NativeSystemFont = if platform == PlatformKind::Headless {
119            NativeSystemFont::deterministic()
120        } else {
121            NativeSystemFont::system()
122        };
123        let mut display_list: DisplayList = DisplayList::default();
124        display_list.get_mut_commands().reserve(128);
125        let (sw_w, sw_h): (u32, u32) = if active_mode == RenderMode::Software {
126            (width, height)
127        } else {
128            (1, 1)
129        };
130        let (hw_w, hw_h, hw_backend): (u32, u32, GraphicsBackend) =
131            if matches!(active_mode, RenderMode::Hardware | RenderMode::Auto) {
132                (width, height, active_backend)
133            } else {
134                (1, 1, GraphicsBackend::Headless)
135            };
136        let (hy_w, hy_h): (u32, u32) = if active_mode == RenderMode::Hybrid {
137            (width, height)
138        } else {
139            (1, 1)
140        };
141        Self {
142            config,
143            active_mode,
144            active_backend,
145            software: SoftwareRenderer::with_font_provider(
146                sw_w,
147                sw_h,
148                config,
149                font_provider.clone(),
150            ),
151            hardware: HardwareRenderer::with_backend_and_font(
152                hw_backend,
153                hw_w,
154                hw_h,
155                config,
156                readback_mirror,
157                font_provider.clone(),
158            ),
159            hybrid: HybridRenderer::with_backend_and_font(
160                active_backend,
161                hy_w,
162                hy_h,
163                config,
164                font_provider,
165            ),
166            paint_pass: PaintPass,
167            paint_fragment_cache: PaintFragmentCache::default(),
168            display_list,
169            frame_index: 0,
170            compute_pixel_hash,
171            last_hashed_mode: None,
172            last_hashed_dims: (0, 0),
173            last_stats: FrameStats::default(),
174        }
175    }
176
177    /// Resolves `(RenderMode, GraphicsBackend)` deterministically from platform capabilities and user preference.
178    ///
179    /// # Arguments
180    ///
181    /// - `PlatformKind` - Target platform.
182    /// - `PlatformCapabilities` - Hardware support flags.
183    /// - `RenderConfig` - User configuration.
184    ///
185    /// # Returns
186    ///
187    /// - `(RenderMode, GraphicsBackend)` - Concrete resolved mode and backend.
188    #[must_use]
189    pub fn resolve_mode_and_backend(
190        platform: PlatformKind,
191        capabilities: PlatformCapabilities,
192        config: RenderConfig,
193    ) -> (RenderMode, GraphicsBackend) {
194        let default_gpu: GraphicsBackend = match platform {
195            PlatformKind::MacOs | PlatformKind::Ios | PlatformKind::IpadOs => {
196                GraphicsBackend::Metal
197            }
198            PlatformKind::Windows => GraphicsBackend::Direct3D12,
199            PlatformKind::Linux | PlatformKind::Android => GraphicsBackend::Vulkan,
200            PlatformKind::Web => GraphicsBackend::WebGpu,
201            PlatformKind::Headless => GraphicsBackend::Headless,
202        };
203        let mode: RenderMode = match config.get_mode() {
204            RenderMode::Auto => {
205                if capabilities.get_hardware_gpu() {
206                    RenderMode::Hardware
207                } else {
208                    RenderMode::Software
209                }
210            }
211            explicit => explicit,
212        };
213        let backend: GraphicsBackend = match mode {
214            RenderMode::Software => match platform {
215                PlatformKind::Web => GraphicsBackend::Canvas2d,
216                _ => GraphicsBackend::SoftwareCpu,
217            },
218            RenderMode::Hardware | RenderMode::Hybrid => {
219                config.preferred_backend_value().unwrap_or(default_gpu)
220            }
221            RenderMode::Auto => default_gpu,
222        };
223        (mode, backend)
224    }
225
226    /// Dynamically switches the active rendering mode at runtime without rebuilding the scene tree.
227    ///
228    /// # Arguments
229    ///
230    /// - `&Self` - Mutable renderer.
231    /// - `PlatformKind` - Active platform kind.
232    /// - `PlatformCapabilities` - Platform hardware capabilities.
233    /// - `RenderMode` - Target render mode.
234    pub fn switch_mode(
235        &mut self,
236        platform: PlatformKind,
237        capabilities: PlatformCapabilities,
238        mode: RenderMode,
239    ) {
240        let mut next_cfg: RenderConfig = self.get_config();
241        next_cfg.set_mode(mode);
242        let (resolved_mode, resolved_backend): (RenderMode, GraphicsBackend) =
243            Self::resolve_mode_and_backend(platform, capabilities, next_cfg);
244        self.set_config(next_cfg);
245        self.set_active_mode(resolved_mode);
246        self.set_active_backend(resolved_backend);
247        let Self {
248            hardware,
249            hybrid,
250            last_hashed_mode,
251            ..
252        } = self;
253        *last_hashed_mode = None;
254        hardware.get_mut_driver().switch_backend(resolved_backend);
255        hybrid
256            .get_mut_compositor()
257            .set_backend_kind(resolved_backend);
258    }
259
260    /// Compiles `tree` into a `DisplayList`, executes the active render backend, and returns `FrameStats`.
261    ///
262    /// # Arguments
263    ///
264    /// - `&Self` - Mutable renderer.
265    /// - `&SceneTree` - Laid-out scene tree.
266    /// - `Size` - Logical viewport dimensions.
267    /// - `f32` - Active DPI scale factor.
268    /// - `Color` - Surface clear color.
269    /// - `LayoutStats` - Telemetry from the layout pass.
270    /// - `DamageRegion` - Damaged screen region.
271    ///
272    /// # Returns
273    ///
274    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
275    pub fn render_frame(
276        &mut self,
277        tree: &SceneTree,
278        viewport: Size,
279        scale_factor: f32,
280        clear_color: Color,
281        layout_stats: LayoutStats,
282        damage: DamageRegion,
283    ) -> Result<FrameStats, PlatformError> {
284        let scale: f32 = scale_factor.max(0.5);
285        let phys_w: u32 = ((viewport.get_width() * scale).round() as u32).max(1);
286        let phys_h: u32 = ((viewport.get_height() * scale).round() as u32).max(1);
287        let phys_dims: (u32, u32) = (phys_w, phys_h);
288        let Self {
289            active_mode,
290            active_backend,
291            software,
292            hardware,
293            hybrid,
294            paint_pass,
295            paint_fragment_cache,
296            display_list,
297            frame_index,
298            compute_pixel_hash,
299            last_hashed_mode,
300            last_hashed_dims,
301            last_stats,
302            ..
303        } = self;
304        let mode: RenderMode = *active_mode;
305        let backend: GraphicsBackend = *active_backend;
306        let do_pixel_hash: bool = *compute_pixel_hash;
307        let hash_reusable: bool = *last_hashed_mode == Some(mode) && *last_hashed_dims == phys_dims;
308        if !damage.get_full_damage() && damage.bounds_rect().is_none() && hash_reusable {
309            *frame_index = frame_index.wrapping_add(1);
310            let stats: FrameStats = FrameStats {
311                frame_index: *frame_index,
312                active_mode: mode,
313                active_backend: backend,
314                layout_nodes: layout_stats.get_nodes_computed(),
315                layout_skipped: layout_stats.get_subtrees_skipped(),
316                draw_commands: 0,
317                draw_batches: 0,
318                pixels_shaded: 0,
319                frame_hash: last_stats.get_frame_hash(),
320            };
321            *last_stats = stats;
322            return Ok(stats);
323        }
324        let _: &PaintPass = paint_pass;
325        let layout_changed: bool = layout_stats.get_nodes_computed() > 0;
326        PaintPass::build_retained(
327            tree,
328            viewport,
329            scale,
330            clear_color,
331            layout_changed,
332            display_list,
333            paint_fragment_cache,
334        );
335        let cmd_count: usize = display_list.len();
336        let (batches, pixels, hash): (usize, usize, u64) = match mode {
337            RenderMode::Software => {
338                let (b, p): (usize, usize) = software.render(display_list, damage);
339                let h: u64 = if p == 0 && hash_reusable {
340                    last_stats.get_frame_hash()
341                } else if do_pixel_hash {
342                    software.get_framebuffer().fnv1a_hash()
343                } else {
344                    display_list.fast_hash()
345                };
346                (b, p, h)
347            }
348            RenderMode::Hybrid => {
349                let (b, p): (usize, usize) = hybrid.render(display_list, damage)?;
350                let h: u64 = if p == 0 && hash_reusable {
351                    last_stats.get_frame_hash()
352                } else if do_pixel_hash {
353                    hybrid.get_software().get_framebuffer().fnv1a_hash()
354                } else {
355                    display_list.fast_hash()
356                };
357                (b, p, h)
358            }
359            RenderMode::Hardware | RenderMode::Auto => {
360                let (b, p): (usize, usize) = hardware.render(display_list, damage)?;
361                let h: u64 = if p == 0 && hash_reusable {
362                    last_stats.get_frame_hash()
363                } else if hardware.get_enable_readback() {
364                    if do_pixel_hash {
365                        hardware.get_readback().get_framebuffer().fnv1a_hash()
366                    } else {
367                        display_list.fast_hash()
368                    }
369                } else {
370                    hardware.batch_hash()
371                };
372                (b, p, h)
373            }
374        };
375        *last_hashed_mode = Some(mode);
376        *last_hashed_dims = phys_dims;
377        *frame_index = frame_index.wrapping_add(1);
378        let stats: FrameStats = FrameStats {
379            frame_index: *frame_index,
380            active_mode: mode,
381            active_backend: backend,
382            layout_nodes: layout_stats.get_nodes_computed(),
383            layout_skipped: layout_stats.get_subtrees_skipped(),
384            draw_commands: cmd_count,
385            draw_batches: batches,
386            pixels_shaded: pixels,
387            frame_hash: hash,
388        };
389        *last_stats = stats;
390        Ok(stats)
391    }
392
393    /// Renders `tree` using a compact `FrameRenderParams` descriptor and returns `FrameStats`.
394    ///
395    /// # Arguments
396    ///
397    /// - `&Self` - Mutable renderer.
398    /// - `&SceneTree` - Laid-out scene tree.
399    /// - `&FrameRenderParams` - Viewport, DPI, clear color, layout stats, and damage bundle.
400    ///
401    /// # Returns
402    ///
403    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
404    #[inline(always)]
405    pub fn render_with(
406        &mut self,
407        tree: &SceneTree,
408        params: &FrameRenderParams,
409    ) -> Result<FrameStats, PlatformError> {
410        self.render_frame(
411            tree,
412            params.get_viewport(),
413            params.get_scale_factor(),
414            params.get_clear_color(),
415            params.get_layout_stats(),
416            params.get_damage(),
417        )
418    }
419
420    /// Advances the frame counter for an undamaged idle frame without rasterizing or hashing pixels.
421    ///
422    /// # Arguments
423    ///
424    /// - `&Self` - Mutable renderer.
425    ///
426    /// # Returns
427    ///
428    /// - `FrameStats` - Lightweight telemetry preserving the last rendered `frame_hash` with zero shaded pixels.
429    pub fn record_skipped_frame(&mut self) -> FrameStats {
430        let next_idx: u64 = self.get_frame_index().wrapping_add(1);
431        self.set_frame_index(next_idx);
432        let mut stats: FrameStats = self.get_last_stats();
433        stats.set_frame_index(next_idx);
434        stats.set_layout_nodes(0);
435        stats.set_draw_batches(0);
436        stats.set_pixels_shaded(0);
437        self.set_last_stats(stats);
438        stats
439    }
440
441    /// Returns cumulative cross-frame `PaintFragmentCache` telemetry `(whole_list_hits, fragment_hits, fragment_misses, fragment_evictions)`.
442    ///
443    /// # Arguments
444    ///
445    /// - `&Self` - Renderer reference.
446    ///
447    /// # Returns
448    ///
449    /// - `(u64, u64, u64, u64)` - Tuple of whole-list hits, fragment hits, misses, and evictions.
450    #[must_use]
451    pub fn paint_fragment_cache_stats(&self) -> (u64, u64, u64, u64) {
452        self.get_paint_fragment_cache().stats()
453    }
454
455    /// Returns a reference to the latest CPU-accessible `Framebuffer` for software/hybrid/readback presentation.
456    ///
457    /// # Arguments
458    ///
459    /// - `&Self` - Renderer reference.
460    ///
461    /// # Returns
462    ///
463    /// - `Option<&Framebuffer>` - Active RGBA8 framebuffer if available in host memory.
464    #[must_use]
465    pub fn framebuffer(&self) -> Option<&Framebuffer> {
466        match self.get_active_mode() {
467            RenderMode::Software => Some(self.get_software().get_framebuffer()),
468            RenderMode::Hybrid => Some(self.get_hybrid().get_software().get_framebuffer()),
469            RenderMode::Hardware | RenderMode::Auto => {
470                if self.get_hardware().get_enable_readback() {
471                    Some(self.get_hardware().get_readback().get_framebuffer())
472                } else {
473                    None
474                }
475            }
476        }
477    }
478}