Skip to main content

euv_core/render/pipeline/
impl.rs

1use super::*;
2
3/// Shared font, glyph atlas, and text shaping constructors for `FontAtlasService`.
4impl FontAtlasService {
5    /// Creates a shared font and glyph service bound to `font_provider` with zero eager glyph allocation.
6    ///
7    /// # Arguments
8    ///
9    /// - `NativeSystemFont` - Native OS or deterministic font provider.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Initialized shared font service.
14    #[must_use]
15    pub fn with_font_provider(font_provider: NativeSystemFont) -> Self {
16        Self {
17            font_provider,
18            glyph_atlas: GlyphAtlas::default(),
19            text_shaping_cache: TextShapingCache::default(),
20        }
21    }
22}
23
24/// Fluent builder helpers for `FrameRenderParams`.
25impl FrameRenderParams {
26    /// Creates frame render parameters for `viewport` with `1.0` scale, white clear color, and full damage.
27    ///
28    /// # Arguments
29    ///
30    /// - `Size` - Logical viewport size.
31    ///
32    /// # Returns
33    ///
34    /// - `Self` - Ready render parameters.
35    #[must_use]
36    pub fn new(viewport: Size) -> Self {
37        Self {
38            viewport,
39            scale_factor: 1.0,
40            clear_color: COLOR_WHITE,
41            layout_stats: LayoutStats::default(),
42            damage: DamageRegion::full(),
43        }
44    }
45
46    /// Sets the active DPI scale factor.
47    ///
48    /// # Arguments
49    ///
50    /// - `Self` - Base parameters.
51    /// - `f32` - Scale factor.
52    ///
53    /// # Returns
54    ///
55    /// - `Self` - Updated parameters.
56    #[must_use]
57    pub fn with_scale(mut self, scale_factor: f32) -> Self {
58        self.set_scale_factor(scale_factor.max(0.5));
59        self
60    }
61
62    /// Sets the surface clear color.
63    ///
64    /// # Arguments
65    ///
66    /// - `Self` - Base parameters.
67    /// - `Color` - Clear color.
68    ///
69    /// # Returns
70    ///
71    /// - `Self` - Updated parameters.
72    #[must_use]
73    pub fn with_clear(mut self, clear_color: Color) -> Self {
74        self.set_clear_color(clear_color);
75        self
76    }
77
78    /// Attaches layout telemetry from the current frame.
79    ///
80    /// # Arguments
81    ///
82    /// - `Self` - Base parameters.
83    /// - `LayoutStats` - Layout pass statistics.
84    ///
85    /// # Returns
86    ///
87    /// - `Self` - Updated parameters.
88    #[must_use]
89    pub fn with_layout_stats(mut self, layout_stats: LayoutStats) -> Self {
90        self.set_layout_stats(layout_stats);
91        self
92    }
93
94    /// Sets the active dirty damage region.
95    ///
96    /// # Arguments
97    ///
98    /// - `Self` - Base parameters.
99    /// - `DamageRegion` - Damage region.
100    ///
101    /// # Returns
102    ///
103    /// - `Self` - Updated parameters.
104    #[must_use]
105    pub fn with_damage(mut self, damage: DamageRegion) -> Self {
106        self.set_damage(damage);
107        self
108    }
109}
110
111/// Single-backend pipeline construction, live mode switching, and frame rendering for `Renderer`.
112impl Renderer {
113    /// Creates a `Renderer` instantiating strictly ONE active backend for `platform` and `config`.
114    ///
115    /// # Arguments
116    ///
117    /// - `PlatformKind` - Active execution platform.
118    /// - `PlatformCapabilities` - Hardware capabilities reported by the platform backend.
119    /// - `u32` - Initial physical width.
120    /// - `u32` - Initial physical height.
121    /// - `RenderConfig` - Requested rendering configuration.
122    ///
123    /// # Returns
124    ///
125    /// - `Self` - Initialized single-backend renderer facade with zero eager fallback allocation.
126    #[must_use]
127    pub fn new(
128        platform: PlatformKind,
129        capabilities: PlatformCapabilities,
130        width: u32,
131        height: u32,
132        config: RenderConfig,
133    ) -> Self {
134        Self::with_display_hz(
135            platform,
136            capabilities,
137            width,
138            height,
139            config,
140            platform.default_refresh_rate_hz(),
141        )
142    }
143
144    /// Creates a `Renderer` bound to live `display_refresh_hz` and instantiating strictly ONE active backend.
145    ///
146    /// # Arguments
147    ///
148    /// - `PlatformKind` - Active execution platform.
149    /// - `PlatformCapabilities` - Hardware capabilities reported by the platform backend.
150    /// - `u32` - Initial physical width.
151    /// - `u32` - Initial physical height.
152    /// - `RenderConfig` - Requested rendering configuration.
153    /// - `f32` - Live native display refresh rate in Hertz.
154    ///
155    /// # Returns
156    ///
157    /// - `Self` - Initialized single-backend renderer facade.
158    #[must_use]
159    pub fn with_display_hz(
160        platform: PlatformKind,
161        capabilities: PlatformCapabilities,
162        width: u32,
163        height: u32,
164        config: RenderConfig,
165        display_refresh_hz: f32,
166    ) -> Self {
167        let (active_mode, active_backend): (RenderMode, GraphicsBackend) =
168            Self::resolve_mode_and_backend(platform, capabilities, config);
169        let readback_mirror: bool = !config.get_direct_gpu_present();
170        let compute_pixel_hash: bool =
171            platform == PlatformKind::Headless || active_backend == GraphicsBackend::Headless;
172        let font_provider: NativeSystemFont = if platform == PlatformKind::Headless {
173            NativeSystemFont::deterministic()
174        } else {
175            NativeSystemFont::system()
176        };
177        let font_service: FontAtlasService =
178            FontAtlasService::with_font_provider(font_provider.clone());
179        let mut display_list: DisplayList = DisplayList::default();
180        display_list.reserve_steady_state();
181        let active_backend_impl: ActiveRenderBackend = match active_mode {
182            RenderMode::Software => ActiveRenderBackend::Software(Box::new(
183                SoftwareRenderer::with_font_provider(width, height, config, font_provider),
184            )),
185            RenderMode::Hybrid => {
186                ActiveRenderBackend::Hybrid(Box::new(HybridRenderer::with_backend_and_font(
187                    active_backend,
188                    width,
189                    height,
190                    config,
191                    font_provider,
192                )))
193            }
194            RenderMode::Hardware | RenderMode::Auto => {
195                let (hw_w, hw_h): (u32, u32) = if readback_mirror {
196                    (width, height)
197                } else {
198                    (0, 0)
199                };
200                ActiveRenderBackend::Hardware(Box::new(HardwareRenderer::with_backend_and_font(
201                    active_backend,
202                    hw_w,
203                    hw_h,
204                    config,
205                    readback_mirror,
206                    font_provider,
207                )))
208            }
209        };
210        let semantics: RenderSemanticsContract =
211            RenderSemanticsContract::from_render_config(config, 1.0);
212        Self {
213            config,
214            active_mode,
215            active_backend,
216            active_backend_impl,
217            fallback_software: None,
218            font_service,
219            surface_width: width,
220            surface_height: height,
221            paint_pass: PaintPass,
222            paint_fragment_cache: PaintFragmentCache::default(),
223            display_list,
224            frame_index: 0,
225            compute_pixel_hash,
226            telemetry_enabled: false,
227            last_hashed_mode: None,
228            last_hashed_dims: (0, 0),
229            last_stats: FrameStats::default(),
230            fallback_policy: FallbackPolicyEngine::with_display_hz(display_refresh_hz, semantics),
231            composite_fast_path_frames: 0,
232            cpu_fallback_frames: 0,
233        }
234    }
235
236    /// Returns an immutable reference to the single active rendering backend enum.
237    ///
238    /// # Arguments
239    ///
240    /// - `&Self` - Renderer reference.
241    ///
242    /// # Returns
243    ///
244    /// - `&ActiveRenderBackend` - Active backend variant.
245    #[must_use]
246    pub fn active_backend_ref(&self) -> &ActiveRenderBackend {
247        let Self {
248            active_backend_impl,
249            ..
250        } = self;
251        active_backend_impl
252    }
253
254    /// Returns a reference to the active or lazily-instantiated `SoftwareRenderer`, if one exists.
255    ///
256    /// # Arguments
257    ///
258    /// - `&Self` - Renderer reference.
259    ///
260    /// # Returns
261    ///
262    /// - `Option<&SoftwareRenderer>` - Software renderer reference when active or lazily allocated.
263    #[must_use]
264    pub fn software(&self) -> Option<&SoftwareRenderer> {
265        let Self {
266            active_backend_impl,
267            fallback_software,
268            ..
269        } = self;
270        match active_backend_impl {
271            ActiveRenderBackend::Software(sw) => Some(sw.as_ref()),
272            ActiveRenderBackend::Hybrid(hy) => Some(hy.get_software()),
273            ActiveRenderBackend::Hardware(_) => fallback_software.as_deref(),
274        }
275    }
276
277    /// Returns a reference to the active `HardwareRenderer` when hardware mode is active.
278    ///
279    /// # Arguments
280    ///
281    /// - `&Self` - Renderer reference.
282    ///
283    /// # Returns
284    ///
285    /// - `Option<&HardwareRenderer>` - Active hardware renderer, or `None` when inactive.
286    #[must_use]
287    pub fn hardware(&self) -> Option<&HardwareRenderer> {
288        let Self {
289            active_backend_impl,
290            ..
291        } = self;
292        match active_backend_impl {
293            ActiveRenderBackend::Hardware(hw) => Some(hw.as_ref()),
294            ActiveRenderBackend::Software(_) | ActiveRenderBackend::Hybrid(_) => None,
295        }
296    }
297
298    /// Returns a reference to the active `HybridRenderer` when hybrid mode is active.
299    ///
300    /// # Arguments
301    ///
302    /// - `&Self` - Renderer reference.
303    ///
304    /// # Returns
305    ///
306    /// - `Option<&HybridRenderer>` - Active hybrid renderer, or `None` when inactive.
307    #[must_use]
308    pub fn hybrid(&self) -> Option<&HybridRenderer> {
309        let Self {
310            active_backend_impl,
311            ..
312        } = self;
313        match active_backend_impl {
314            ActiveRenderBackend::Hybrid(hy) => Some(hy.as_ref()),
315            ActiveRenderBackend::Software(_) | ActiveRenderBackend::Hardware(_) => None,
316        }
317    }
318
319    /// Returns `true` when the lazy CPU fallback `SoftwareRenderer` has been instantiated.
320    ///
321    /// # Arguments
322    ///
323    /// - `&Self` - Renderer reference.
324    ///
325    /// # Returns
326    ///
327    /// - `bool` - Whether `fallback_software` is currently allocated.
328    #[must_use]
329    pub fn has_fallback_software(&self) -> bool {
330        let Self {
331            fallback_software, ..
332        } = self;
333        fallback_software.is_some()
334    }
335
336    /// Returns total CPU RGBA8 framebuffer bytes currently allocated across active and fallback renderers (`0` in GPU direct-draw mode).
337    ///
338    /// # Arguments
339    ///
340    /// - `&Self` - Renderer reference.
341    ///
342    /// # Returns
343    ///
344    /// - `usize` - Total allocated CPU framebuffer pixel bytes.
345    #[must_use]
346    pub fn allocated_cpu_framebuffer_bytes(&self) -> usize {
347        let Self {
348            active_backend_impl,
349            fallback_software,
350            ..
351        } = self;
352        let active_bytes: usize = match active_backend_impl {
353            ActiveRenderBackend::Software(sw) => sw.allocated_framebuffer_bytes(),
354            ActiveRenderBackend::Hybrid(hy) => hy.get_software().allocated_framebuffer_bytes(),
355            ActiveRenderBackend::Hardware(hw) => hw.get_readback().allocated_framebuffer_bytes(),
356        };
357        let fallback_bytes: usize = fallback_software
358            .as_deref()
359            .map_or(0, SoftwareRenderer::allocated_framebuffer_bytes);
360        active_bytes.saturating_add(fallback_bytes)
361    }
362
363    /// Lazily allocates `fallback_software` if unset and returns a mutable reference to it, reusing `font_service`.
364    ///
365    /// # Arguments
366    ///
367    /// - `&'a mut Option<Box<SoftwareRenderer>>` - Fallback slot to populate lazily.
368    /// - `&mut FontAtlasService` - Shared font and glyph atlas service.
369    /// - `(RenderConfig, u32, u32, bool)` - Tuple `(config, width, height, telemetry_enabled)`.
370    ///
371    /// # Returns
372    ///
373    /// - `&'a mut SoftwareRenderer` - Mutable reference to the lazy CPU reference renderer.
374    fn ensure_fallback_software<'a>(
375        fallback_slot: &'a mut Option<Box<SoftwareRenderer>>,
376        font_service: &mut FontAtlasService,
377        opts: (RenderConfig, u32, u32, bool),
378    ) -> &'a mut SoftwareRenderer {
379        let (config, width, height, telemetry_enabled): (RenderConfig, u32, u32, bool) = opts;
380        let sw_box: &mut Box<SoftwareRenderer> = fallback_slot.get_or_insert_with(|| {
381            let mut sw_cfg: RenderConfig = config;
382            sw_cfg.set_mode(RenderMode::Software);
383            sw_cfg.set_direct_gpu_present(false);
384            let mut sw: SoftwareRenderer = SoftwareRenderer::with_font_provider(
385                width,
386                height,
387                sw_cfg,
388                font_service.get_font_provider().clone(),
389            );
390            swap(sw.get_mut_glyph_atlas(), font_service.get_mut_glyph_atlas());
391            sw.set_telemetry_enabled(telemetry_enabled);
392            Box::new(sw)
393        });
394        sw_box.as_mut()
395    }
396
397    /// Returns a mutable reference to the active software renderer, lazily instantiating `fallback_software` only when in hardware mode.
398    ///
399    /// # Arguments
400    ///
401    /// - `&Self` - Mutable renderer.
402    ///
403    /// # Returns
404    ///
405    /// - `&mut SoftwareRenderer` - Mutable software renderer reference.
406    pub fn get_mut_software(&mut self) -> &mut SoftwareRenderer {
407        let Self {
408            active_backend_impl,
409            fallback_software,
410            font_service,
411            config,
412            surface_width,
413            surface_height,
414            telemetry_enabled,
415            ..
416        } = self;
417        match active_backend_impl {
418            ActiveRenderBackend::Software(sw) => sw.as_mut(),
419            ActiveRenderBackend::Hybrid(hy) => hy.get_mut_software(),
420            ActiveRenderBackend::Hardware(_) => Self::ensure_fallback_software(
421                fallback_software,
422                font_service,
423                (*config, *surface_width, *surface_height, *telemetry_enabled),
424            ),
425        }
426    }
427
428    /// Updates whether timing instrumentation (`Instant::now`) is active inside software band scheduling.
429    ///
430    /// # Arguments
431    ///
432    /// - `&Self` - Mutable renderer.
433    /// - `bool` - `true` to enable per-dispatch microsecond timing instrumentation.
434    pub fn set_timing_telemetry_enabled(&mut self, enabled: bool) {
435        self.set_telemetry_enabled(enabled);
436        let Self {
437            active_backend_impl,
438            fallback_software,
439            ..
440        } = self;
441        match active_backend_impl {
442            ActiveRenderBackend::Software(sw) => {
443                sw.set_telemetry_enabled(enabled);
444            }
445            ActiveRenderBackend::Hybrid(hy) => {
446                hy.get_mut_software().set_telemetry_enabled(enabled);
447            }
448            ActiveRenderBackend::Hardware(hw) => {
449                hw.get_mut_readback().set_telemetry_enabled(enabled);
450            }
451        }
452        if let Some(sw) = fallback_software.as_deref_mut() {
453            sw.set_telemetry_enabled(enabled);
454        }
455    }
456
457    /// Updates adaptive worker-pool spin behavior for active animation/scroll vs idle periods.
458    ///
459    /// # Arguments
460    ///
461    /// - `&Self` - Mutable renderer.
462    /// - `bool` - `true` during active animation or scrolling; `false` when idle to drop worker spin to `0`.
463    pub fn set_high_frequency_active(&mut self, active: bool) {
464        let Self {
465            active_backend_impl,
466            fallback_software,
467            ..
468        } = self;
469        match active_backend_impl {
470            ActiveRenderBackend::Software(sw) => sw.set_high_frequency_active(active),
471            ActiveRenderBackend::Hybrid(hy) => {
472                hy.get_mut_software().set_high_frequency_active(active);
473            }
474            ActiveRenderBackend::Hardware(hw) => {
475                hw.get_mut_readback().set_high_frequency_active(active);
476            }
477        }
478        if let Some(sw) = fallback_software.as_deref_mut() {
479            sw.set_high_frequency_active(active);
480        }
481    }
482
483    /// Enables or disables direct GPU rendering without steady-state CPU RGBA readback mirroring.
484    ///
485    /// # Arguments
486    ///
487    /// - `&Self` - Mutable renderer.
488    /// - `bool` - `true` for GPU direct-draw (zero CPU RGBA mirror); `false` to enable software readback mirror.
489    pub fn set_direct_gpu_present(&mut self, enabled: bool) {
490        let mut cfg: RenderConfig = self.get_config();
491        cfg.set_direct_gpu_present(enabled);
492        self.set_config(cfg);
493        let Self {
494            active_backend_impl,
495            last_hashed_mode,
496            ..
497        } = self;
498        if let ActiveRenderBackend::Hardware(hw) = active_backend_impl {
499            hw.set_enable_readback(!enabled);
500            if enabled {
501                hw.get_mut_readback().release_framebuffer();
502            }
503        }
504        *last_hashed_mode = None;
505    }
506
507    /// Synchronizes the fallback policy engine with the active native display refresh rate in Hertz.
508    ///
509    /// # Arguments
510    ///
511    /// - `&Self` - Mutable renderer.
512    /// - `f32` - Active display refresh rate in Hertz.
513    pub fn set_display_refresh_rate_hz(&mut self, display_refresh_hz: f32) {
514        self.get_mut_fallback_policy()
515            .update_display_refresh_hz(display_refresh_hz);
516    }
517
518    /// Captures the active visual semantics contract verifying zero quality degradation across fallback transitions.
519    ///
520    /// # Arguments
521    ///
522    /// - `&Self` - Renderer reference.
523    /// - `f32` - Active display scale factor.
524    ///
525    /// # Returns
526    ///
527    /// - `RenderSemanticsContract` - Immutable visual fidelity snapshot.
528    #[must_use]
529    pub fn semantics_contract(&self, scale_factor: f32) -> RenderSemanticsContract {
530        RenderSemanticsContract::from_render_config(self.get_config(), scale_factor)
531    }
532
533    /// Captures an on-demand CPU reference framebuffer for pixel-parity verification even while direct GPU draw is enabled.
534    ///
535    /// # Arguments
536    ///
537    /// - `&Self` - Mutable renderer.
538    /// - `DamageRegion` - Damage region to rasterize into the reference framebuffer.
539    ///
540    /// # Returns
541    ///
542    /// - `&Framebuffer` - Rendered full-fidelity CPU reference RGBA8 framebuffer.
543    pub fn capture_reference_framebuffer(&mut self, damage: DamageRegion) -> &Framebuffer {
544        let Self {
545            active_backend_impl,
546            fallback_software,
547            font_service,
548            config,
549            surface_width,
550            surface_height,
551            telemetry_enabled,
552            display_list,
553            ..
554        } = self;
555        match active_backend_impl {
556            ActiveRenderBackend::Software(sw) => {
557                let (_, _): (usize, usize) = sw.render(display_list, damage);
558                sw.get_framebuffer()
559            }
560            ActiveRenderBackend::Hybrid(hy) => hy.get_software().get_framebuffer(),
561            ActiveRenderBackend::Hardware(hw) => {
562                if hw.get_enable_readback() {
563                    hw.capture_reference_readback(display_list, damage)
564                } else {
565                    let sw: &mut SoftwareRenderer = Self::ensure_fallback_software(
566                        fallback_software,
567                        font_service,
568                        (*config, *surface_width, *surface_height, *telemetry_enabled),
569                    );
570                    let (_, _): (usize, usize) = sw.render(display_list, damage);
571                    sw.get_framebuffer()
572                }
573            }
574        }
575    }
576
577    /// Evaluates `trigger` through `FallbackPolicyEngine` and applies strictly non-degrading cache trimming or CPU reference switching.
578    ///
579    /// # Arguments
580    ///
581    /// - `&Self` - Mutable renderer.
582    /// - `FallbackTrigger` - Runtime pressure, frame overrun, or GPU fault trigger.
583    /// - `u64` - Monotonic clock timestamp in milliseconds.
584    ///
585    /// # Returns
586    ///
587    /// - `FallbackAction` - Strictly non-degrading action applied.
588    pub fn apply_fallback_trigger(
589        &mut self,
590        trigger: FallbackTrigger,
591        now_ms: u64,
592    ) -> FallbackAction {
593        let action: FallbackAction = self
594            .get_mut_fallback_policy()
595            .evaluate_trigger(trigger, now_ms);
596        match action {
597            FallbackAction::TrimPrefetchAndColdCache { retain_ratio } => {
598                let Self {
599                    active_backend_impl,
600                    fallback_software,
601                    font_service,
602                    paint_fragment_cache,
603                    ..
604                } = self;
605                let budget: usize =
606                    ((GLYPH_ATLAS_DEFAULT_BUDGET_BYTES as f32) * retain_ratio.clamp(0.1, 1.0))
607                        .round()
608                        .max(GLYPH_ATLAS_MIN_BUDGET_BYTES as f32) as usize;
609                font_service.get_mut_glyph_atlas().set_memory_budget(budget);
610                match active_backend_impl {
611                    ActiveRenderBackend::Software(sw) => {
612                        sw.get_mut_glyph_atlas().set_memory_budget(budget);
613                    }
614                    ActiveRenderBackend::Hybrid(hy) => {
615                        hy.get_mut_software()
616                            .get_mut_glyph_atlas()
617                            .set_memory_budget(budget);
618                    }
619                    ActiveRenderBackend::Hardware(hw) => {
620                        let _: usize = hw.trim_gpu_caches(retain_ratio);
621                        hw.get_mut_readback()
622                            .get_mut_glyph_atlas()
623                            .set_memory_budget(budget);
624                    }
625                }
626                if let Some(sw) = fallback_software.as_deref_mut() {
627                    sw.get_mut_glyph_atlas().set_memory_budget(budget);
628                }
629                if retain_ratio <= FALLBACK_CRITICAL_RETAIN_RATIO + 0.01 {
630                    paint_fragment_cache.clear();
631                }
632            }
633            FallbackAction::SwitchToCpuReference { .. } => {
634                let mut next_cfg: RenderConfig = self.get_config();
635                next_cfg.set_mode(RenderMode::Software);
636                next_cfg.set_direct_gpu_present(false);
637                self.set_config(next_cfg);
638                self.set_active_mode(RenderMode::Software);
639                self.set_active_backend(GraphicsBackend::SoftwareCpu);
640                let Self {
641                    active_backend_impl,
642                    fallback_software,
643                    font_service,
644                    surface_width,
645                    surface_height,
646                    telemetry_enabled,
647                    last_hashed_mode,
648                    ..
649                } = self;
650                if !matches!(active_backend_impl, ActiveRenderBackend::Software(_)) {
651                    let next_sw: Box<SoftwareRenderer> = match fallback_software.take() {
652                        Some(existing) => existing,
653                        None => {
654                            let mut sw: SoftwareRenderer = SoftwareRenderer::with_font_provider(
655                                *surface_width,
656                                *surface_height,
657                                next_cfg,
658                                font_service.get_font_provider().clone(),
659                            );
660                            swap(sw.get_mut_glyph_atlas(), font_service.get_mut_glyph_atlas());
661                            sw.set_telemetry_enabled(*telemetry_enabled);
662                            Box::new(sw)
663                        }
664                    };
665                    *active_backend_impl = ActiveRenderBackend::Software(next_sw);
666                }
667                *last_hashed_mode = None;
668            }
669            FallbackAction::None
670            | FallbackAction::AdjustPresentCadence { .. }
671            | FallbackAction::RouteLayerToCpuReference => {}
672        }
673        action
674    }
675
676    /// Resolves `(RenderMode, GraphicsBackend)` deterministically from platform capabilities and user preference.
677    ///
678    /// # Arguments
679    ///
680    /// - `PlatformKind` - Target platform.
681    /// - `PlatformCapabilities` - Hardware support flags.
682    /// - `RenderConfig` - User configuration.
683    ///
684    /// # Returns
685    ///
686    /// - `(RenderMode, GraphicsBackend)` - Concrete resolved mode and backend.
687    #[must_use]
688    pub fn resolve_mode_and_backend(
689        platform: PlatformKind,
690        capabilities: PlatformCapabilities,
691        config: RenderConfig,
692    ) -> (RenderMode, GraphicsBackend) {
693        let default_gpu: GraphicsBackend = platform.default_graphics_backend();
694        let mode: RenderMode = match config.get_mode() {
695            RenderMode::Auto => {
696                if capabilities.get_hardware_gpu() {
697                    RenderMode::Hardware
698                } else {
699                    RenderMode::Software
700                }
701            }
702            explicit => explicit,
703        };
704        let backend: GraphicsBackend = match mode {
705            RenderMode::Software => match platform {
706                PlatformKind::Web | PlatformKind::MiniApp | PlatformKind::QuickApp => {
707                    GraphicsBackend::Canvas2d
708                }
709                _ => GraphicsBackend::SoftwareCpu,
710            },
711            RenderMode::Hardware | RenderMode::Hybrid => {
712                config.preferred_backend_value().unwrap_or(default_gpu)
713            }
714            RenderMode::Auto => default_gpu,
715        };
716        (mode, backend)
717    }
718
719    /// Dynamically switches the active rendering mode at runtime, instantiating only the target backend and transferring the shared glyph atlas.
720    ///
721    /// # Arguments
722    ///
723    /// - `&Self` - Mutable renderer.
724    /// - `PlatformKind` - Active platform kind.
725    /// - `PlatformCapabilities` - Platform hardware capabilities.
726    /// - `RenderMode` - Target render mode.
727    pub fn switch_mode(
728        &mut self,
729        platform: PlatformKind,
730        capabilities: PlatformCapabilities,
731        mode: RenderMode,
732    ) {
733        let mut next_cfg: RenderConfig = self.get_config();
734        next_cfg.set_mode(mode);
735        let (resolved_mode, resolved_backend): (RenderMode, GraphicsBackend) =
736            Self::resolve_mode_and_backend(platform, capabilities, next_cfg);
737        self.set_config(next_cfg);
738        self.set_active_mode(resolved_mode);
739        self.set_active_backend(resolved_backend);
740        let Self {
741            active_backend_impl,
742            fallback_software,
743            font_service,
744            surface_width,
745            surface_height,
746            telemetry_enabled,
747            last_hashed_mode,
748            ..
749        } = self;
750        *last_hashed_mode = None;
751        let same_variant: bool = matches!(
752            (&*active_backend_impl, resolved_mode),
753            (ActiveRenderBackend::Software(_), RenderMode::Software)
754                | (
755                    ActiveRenderBackend::Hardware(_),
756                    RenderMode::Hardware | RenderMode::Auto
757                )
758                | (ActiveRenderBackend::Hybrid(_), RenderMode::Hybrid)
759        );
760        if same_variant {
761            match active_backend_impl {
762                ActiveRenderBackend::Hardware(hw) => {
763                    hw.get_mut_driver().switch_backend(resolved_backend);
764                }
765                ActiveRenderBackend::Hybrid(hy) => {
766                    hy.get_mut_compositor().set_backend_kind(resolved_backend);
767                }
768                ActiveRenderBackend::Software(_) => {}
769            }
770            return;
771        }
772        let mut carried_atlas: GlyphAtlas = take(font_service.get_mut_glyph_atlas());
773        match active_backend_impl {
774            ActiveRenderBackend::Software(sw) => {
775                if !sw.get_glyph_atlas().is_empty() {
776                    carried_atlas = take(sw.get_mut_glyph_atlas());
777                }
778            }
779            ActiveRenderBackend::Hybrid(hy) => {
780                if !hy.get_software().get_glyph_atlas().is_empty() {
781                    carried_atlas = take(hy.get_mut_software().get_mut_glyph_atlas());
782                }
783            }
784            ActiveRenderBackend::Hardware(hw) => {
785                if !hw.get_readback().get_glyph_atlas().is_empty() {
786                    carried_atlas = take(hw.get_mut_readback().get_mut_glyph_atlas());
787                }
788            }
789        }
790        let font_provider: NativeSystemFont = font_service.get_font_provider().clone();
791        let next_backend: ActiveRenderBackend = match resolved_mode {
792            RenderMode::Software => {
793                let mut sw: Box<SoftwareRenderer> = match fallback_software.take() {
794                    Some(existing) => existing,
795                    None => {
796                        let mut sw_cfg: RenderConfig = next_cfg;
797                        sw_cfg.set_direct_gpu_present(false);
798                        Box::new(SoftwareRenderer::with_font_provider(
799                            *surface_width,
800                            *surface_height,
801                            sw_cfg,
802                            font_provider,
803                        ))
804                    }
805                };
806                if !carried_atlas.is_empty() {
807                    sw.set_glyph_atlas(carried_atlas);
808                }
809                sw.set_telemetry_enabled(*telemetry_enabled);
810                ActiveRenderBackend::Software(sw)
811            }
812            RenderMode::Hybrid => {
813                let mut hy_cfg: RenderConfig = next_cfg;
814                hy_cfg.set_direct_gpu_present(false);
815                let mut hy: HybridRenderer = HybridRenderer::with_backend_and_font(
816                    resolved_backend,
817                    *surface_width,
818                    *surface_height,
819                    hy_cfg,
820                    font_provider,
821                );
822                if !carried_atlas.is_empty() {
823                    hy.get_mut_software().set_glyph_atlas(carried_atlas);
824                }
825                hy.get_mut_software()
826                    .set_telemetry_enabled(*telemetry_enabled);
827                ActiveRenderBackend::Hybrid(Box::new(hy))
828            }
829            RenderMode::Hardware | RenderMode::Auto => {
830                let readback_mirror: bool = !next_cfg.get_direct_gpu_present();
831                let (hw_w, hw_h): (u32, u32) = if readback_mirror {
832                    (*surface_width, *surface_height)
833                } else {
834                    (0, 0)
835                };
836                let mut hw: HardwareRenderer = HardwareRenderer::with_backend_and_font(
837                    resolved_backend,
838                    hw_w,
839                    hw_h,
840                    next_cfg,
841                    readback_mirror,
842                    font_provider,
843                );
844                if !carried_atlas.is_empty() {
845                    hw.get_mut_readback().set_glyph_atlas(carried_atlas);
846                }
847                hw.get_mut_readback()
848                    .set_telemetry_enabled(*telemetry_enabled);
849                ActiveRenderBackend::Hardware(Box::new(hw))
850            }
851        };
852        *active_backend_impl = next_backend;
853    }
854
855    /// Compiles `tree` into a `DisplayList`, executes the active render backend, and returns `FrameStats`.
856    ///
857    /// # Arguments
858    ///
859    /// - `&Self` - Mutable renderer.
860    /// - `&SceneTree` - Laid-out scene tree.
861    /// - `Size` - Logical viewport dimensions.
862    /// - `f32` - Active DPI scale factor.
863    /// - `Color` - Surface clear color.
864    /// - `LayoutStats` - Telemetry from the layout pass.
865    /// - `DamageRegion` - Damaged screen region.
866    ///
867    /// # Returns
868    ///
869    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
870    pub fn render_frame(
871        &mut self,
872        tree: &SceneTree,
873        viewport: Size,
874        scale_factor: f32,
875        clear_color: Color,
876        layout_stats: LayoutStats,
877        damage: DamageRegion,
878    ) -> Result<FrameStats, PlatformError> {
879        let params: FrameRenderParams = FrameRenderParams::new(viewport)
880            .with_scale(scale_factor)
881            .with_clear(clear_color)
882            .with_layout_stats(layout_stats)
883            .with_damage(damage);
884        self.render_frame_composite_aware(tree, &params, false)
885    }
886
887    /// Compiles `tree` into a `DisplayList`, honoring composite-only fast paths and non-degrading CPU reference fallback on unsupported GPU effects.
888    ///
889    /// # Arguments
890    ///
891    /// - `&Self` - Mutable renderer.
892    /// - `&SceneTree` - Laid-out scene tree.
893    /// - `&FrameRenderParams` - Viewport, DPI, clear color, layout stats, and damage bundle.
894    /// - `bool` - Whether only composite/scroll properties changed with zero layout or paint mutations.
895    ///
896    /// # Returns
897    ///
898    /// - `Result<FrameStats, PlatformError>` - Frame performance, direct-draw, fallback, and pixel-hash telemetry.
899    pub fn render_frame_composite_aware(
900        &mut self,
901        tree: &SceneTree,
902        params: &FrameRenderParams,
903        composite_only: bool,
904    ) -> Result<FrameStats, PlatformError> {
905        let viewport: Size = params.get_viewport();
906        let scale: f32 = params.get_scale_factor().max(0.5);
907        let clear_color: Color = params.get_clear_color();
908        let layout_stats: LayoutStats = params.get_layout_stats();
909        let damage: DamageRegion = params.get_damage();
910        let phys_w: u32 = ((viewport.get_width() * scale).round() as u32).max(1);
911        let phys_h: u32 = ((viewport.get_height() * scale).round() as u32).max(1);
912        let phys_dims: (u32, u32) = (phys_w, phys_h);
913        let Self {
914            config,
915            active_mode,
916            active_backend,
917            active_backend_impl,
918            fallback_software,
919            font_service,
920            surface_width,
921            surface_height,
922            paint_pass,
923            paint_fragment_cache,
924            display_list,
925            frame_index,
926            compute_pixel_hash,
927            telemetry_enabled,
928            last_hashed_mode,
929            last_hashed_dims,
930            last_stats,
931            fallback_policy,
932            composite_fast_path_frames,
933            cpu_fallback_frames,
934        } = self;
935        *surface_width = phys_w;
936        *surface_height = phys_h;
937        let mode: RenderMode = *active_mode;
938        let backend: GraphicsBackend = *active_backend;
939        let do_pixel_hash: bool = *compute_pixel_hash;
940        let hash_reusable: bool = *last_hashed_mode == Some(mode) && *last_hashed_dims == phys_dims;
941        if !damage.get_full_damage() && damage.bounds_rect().is_none() && hash_reusable {
942            *frame_index = frame_index.wrapping_add(1);
943            let stats: FrameStats = FrameStats {
944                frame_index: *frame_index,
945                active_mode: mode,
946                active_backend: backend,
947                layout_nodes: layout_stats.get_nodes_computed(),
948                layout_skipped: layout_stats.get_subtrees_skipped(),
949                draw_commands: 0,
950                draw_batches: 0,
951                pixels_shaded: 0,
952                frame_hash: last_stats.get_frame_hash(),
953                composite_only: false,
954                gpu_direct_draw: false,
955                cpu_rgba_upload_bytes: 0,
956                submit_outcome: FrameSubmitOutcome::SkippedNoDamage,
957                wait_in_flight: false,
958            };
959            *last_stats = stats;
960            return Ok(stats);
961        }
962        let _: &PaintPass = paint_pass;
963        let layout_changed: bool = layout_stats.get_nodes_computed() > 0;
964        let took_composite_fast_path: bool = composite_only && !layout_changed;
965        if took_composite_fast_path {
966            *composite_fast_path_frames = composite_fast_path_frames.saturating_add(1);
967        }
968        PaintPass::build_retained(
969            tree,
970            viewport,
971            scale,
972            clear_color,
973            layout_changed,
974            display_list,
975            paint_fragment_cache,
976        );
977        if *frame_index == 0 && tree.has_scroll_nodes() {
978            display_list.prewarm_scroll_string_pool(24);
979        }
980        let cmd_count: usize = display_list.len();
981        let mut gpu_direct_draw: bool = false;
982        let cpu_rgba_upload_bytes: usize;
983        let mut effective_mode: RenderMode = mode;
984        let mut effective_backend: GraphicsBackend = backend;
985        let (batches, pixels, hash): (usize, usize, u64) = match active_backend_impl {
986            ActiveRenderBackend::Software(sw) => {
987                let (b, p): (usize, usize) = sw.render(display_list, damage);
988                cpu_rgba_upload_bytes = (phys_w as usize)
989                    .saturating_mul(phys_h as usize)
990                    .saturating_mul(4);
991                let h: u64 = if p == 0 && hash_reusable {
992                    last_stats.get_frame_hash()
993                } else if do_pixel_hash {
994                    sw.incremental_framebuffer_hash()
995                } else {
996                    display_list.fast_hash()
997                };
998                (b, p, h)
999            }
1000            ActiveRenderBackend::Hybrid(hy) => {
1001                let (b, p): (usize, usize) = hy.render(display_list, damage)?;
1002                cpu_rgba_upload_bytes = (phys_w as usize)
1003                    .saturating_mul(phys_h as usize)
1004                    .saturating_mul(4);
1005                let h: u64 = if p == 0 && hash_reusable {
1006                    last_stats.get_frame_hash()
1007                } else if do_pixel_hash {
1008                    hy.get_mut_software().incremental_framebuffer_hash()
1009                } else {
1010                    display_list.fast_hash()
1011                };
1012                (b, p, h)
1013            }
1014            ActiveRenderBackend::Hardware(hw) => match hw.render(display_list, damage) {
1015                Ok((b, p)) => {
1016                    if hw.get_has_unsupported_effect() {
1017                        let _: FallbackAction = fallback_policy.evaluate_trigger(
1018                            FallbackTrigger::MissingGpuEffectPath { isolatable: false },
1019                            0,
1020                        );
1021                        *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
1022                        let sw: &mut SoftwareRenderer = Self::ensure_fallback_software(
1023                            fallback_software,
1024                            font_service,
1025                            (*config, phys_w, phys_h, *telemetry_enabled),
1026                        );
1027                        let (sb, sp): (usize, usize) = sw.render(display_list, damage);
1028                        effective_mode = RenderMode::Software;
1029                        effective_backend = GraphicsBackend::SoftwareCpu;
1030                        cpu_rgba_upload_bytes = (phys_w as usize)
1031                            .saturating_mul(phys_h as usize)
1032                            .saturating_mul(4);
1033                        let h: u64 = if do_pixel_hash {
1034                            sw.incremental_framebuffer_hash()
1035                        } else {
1036                            display_list.fast_hash()
1037                        };
1038                        (sb, sp, h)
1039                    } else {
1040                        gpu_direct_draw = !hw.get_enable_readback();
1041                        cpu_rgba_upload_bytes = hw.get_last_cpu_rgba_upload_bytes();
1042                        let h: u64 = if p == 0 && hash_reusable {
1043                            last_stats.get_frame_hash()
1044                        } else if hw.get_enable_readback() {
1045                            if do_pixel_hash {
1046                                hw.get_mut_readback().incremental_framebuffer_hash()
1047                            } else {
1048                                display_list.fast_hash()
1049                            }
1050                        } else {
1051                            hw.batch_hash()
1052                        };
1053                        (b, p, h)
1054                    }
1055                }
1056                Err(_) => {
1057                    let _: FallbackAction =
1058                        fallback_policy.evaluate_trigger(FallbackTrigger::DeviceLost, 0);
1059                    *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
1060                    let sw: &mut SoftwareRenderer = Self::ensure_fallback_software(
1061                        fallback_software,
1062                        font_service,
1063                        (*config, phys_w, phys_h, *telemetry_enabled),
1064                    );
1065                    let (sb, sp): (usize, usize) = sw.render(display_list, damage);
1066                    effective_mode = RenderMode::Software;
1067                    effective_backend = GraphicsBackend::SoftwareCpu;
1068                    cpu_rgba_upload_bytes = (phys_w as usize)
1069                        .saturating_mul(phys_h as usize)
1070                        .saturating_mul(4);
1071                    let h: u64 = if do_pixel_hash {
1072                        sw.incremental_framebuffer_hash()
1073                    } else {
1074                        display_list.fast_hash()
1075                    };
1076                    (sb, sp, h)
1077                }
1078            },
1079        };
1080        *last_hashed_mode = Some(effective_mode);
1081        *last_hashed_dims = phys_dims;
1082        *frame_index = frame_index.wrapping_add(1);
1083        let stats: FrameStats = FrameStats {
1084            frame_index: *frame_index,
1085            active_mode: effective_mode,
1086            active_backend: effective_backend,
1087            layout_nodes: layout_stats.get_nodes_computed(),
1088            layout_skipped: layout_stats.get_subtrees_skipped(),
1089            draw_commands: cmd_count,
1090            draw_batches: batches,
1091            pixels_shaded: pixels,
1092            frame_hash: hash,
1093            composite_only: took_composite_fast_path,
1094            gpu_direct_draw,
1095            cpu_rgba_upload_bytes,
1096            submit_outcome: FrameSubmitOutcome::Submitted,
1097            wait_in_flight: false,
1098        };
1099        *last_stats = stats;
1100        Ok(stats)
1101    }
1102
1103    /// Renders `tree` using a compact `FrameRenderParams` descriptor and returns `FrameStats`.
1104    ///
1105    /// # Arguments
1106    ///
1107    /// - `&Self` - Mutable renderer.
1108    /// - `&SceneTree` - Laid-out scene tree.
1109    /// - `&FrameRenderParams` - Viewport, DPI, clear color, layout stats, and damage bundle.
1110    ///
1111    /// # Returns
1112    ///
1113    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
1114    #[inline(always)]
1115    pub fn render_with(
1116        &mut self,
1117        tree: &SceneTree,
1118        params: &FrameRenderParams,
1119    ) -> Result<FrameStats, PlatformError> {
1120        self.render_frame(
1121            tree,
1122            params.get_viewport(),
1123            params.get_scale_factor(),
1124            params.get_clear_color(),
1125            params.get_layout_stats(),
1126            params.get_damage(),
1127        )
1128    }
1129
1130    /// Advances the frame counter for an undamaged idle frame without rasterizing or hashing pixels and drops worker spin to `0`.
1131    ///
1132    /// # Arguments
1133    ///
1134    /// - `&Self` - Mutable renderer.
1135    ///
1136    /// # Returns
1137    ///
1138    /// - `FrameStats` - Lightweight telemetry preserving the last rendered `frame_hash` with zero shaded pixels.
1139    pub fn record_skipped_frame(&mut self) -> FrameStats {
1140        self.set_high_frequency_active(false);
1141        let next_idx: u64 = self.get_frame_index().wrapping_add(1);
1142        self.set_frame_index(next_idx);
1143        let mut stats: FrameStats = self.get_last_stats();
1144        stats.set_frame_index(next_idx);
1145        stats.set_layout_nodes(0);
1146        stats.set_draw_batches(0);
1147        stats.set_pixels_shaded(0);
1148        stats.set_composite_only(false);
1149        stats.set_gpu_direct_draw(false);
1150        stats.set_cpu_rgba_upload_bytes(0);
1151        stats.record_present_outcome(PresentOutcome::SkippedNoDamage);
1152        self.set_last_stats(stats);
1153        stats
1154    }
1155
1156    /// Returns cumulative cross-frame `PaintFragmentCache` telemetry `(whole_list_hits, fragment_hits, fragment_misses, fragment_evictions)`.
1157    ///
1158    /// # Arguments
1159    ///
1160    /// - `&Self` - Renderer reference.
1161    ///
1162    /// # Returns
1163    ///
1164    /// - `(u64, u64, u64, u64)` - Tuple of whole-list hits, fragment hits, misses, and evictions.
1165    #[must_use]
1166    pub fn paint_fragment_cache_stats(&self) -> (u64, u64, u64, u64) {
1167        self.get_paint_fragment_cache().stats()
1168    }
1169
1170    /// Returns a reference to the latest CPU-accessible `Framebuffer` for software/hybrid/readback presentation (`None` when GPU direct-draw is active with 0 CPU FB bytes).
1171    ///
1172    /// # Arguments
1173    ///
1174    /// - `&Self` - Renderer reference.
1175    ///
1176    /// # Returns
1177    ///
1178    /// - `Option<&Framebuffer>` - Active RGBA8 framebuffer if resident in host memory.
1179    #[must_use]
1180    pub fn framebuffer(&self) -> Option<&Framebuffer> {
1181        let Self {
1182            active_backend_impl,
1183            fallback_software,
1184            last_stats,
1185            ..
1186        } = self;
1187        match active_backend_impl {
1188            ActiveRenderBackend::Software(sw) => sw.framebuffer_opt(),
1189            ActiveRenderBackend::Hybrid(hy) => hy.get_software().framebuffer_opt(),
1190            ActiveRenderBackend::Hardware(hw) => {
1191                if last_stats.get_active_mode() == RenderMode::Software {
1192                    fallback_software
1193                        .as_deref()
1194                        .and_then(SoftwareRenderer::framebuffer_opt)
1195                } else if hw.get_enable_readback() {
1196                    hw.get_readback().framebuffer_opt()
1197                } else {
1198                    None
1199                }
1200            }
1201        }
1202    }
1203}