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        let host_profile: HostCapabilityProfile =
213            HostCapabilityProfile::from_platform(platform, capabilities);
214        let mut router_cfg: AdaptiveRouterConfig = AdaptiveRouterConfig::default();
215        router_cfg.set_switch_mode(config.get_adaptive_switch_mode());
216        let mut adaptive_router: AdaptiveRenderRouter =
217            AdaptiveRenderRouter::new(router_cfg, host_profile, display_refresh_hz as f64);
218        let active_candidate: RenderBackendCandidate = match active_mode {
219            RenderMode::Software => {
220                if platform == PlatformKind::Terminal {
221                    RenderBackendCandidate::Terminal
222                } else {
223                    RenderBackendCandidate::Software
224                }
225            }
226            RenderMode::Hybrid => RenderBackendCandidate::Hybrid,
227            RenderMode::Hardware | RenderMode::Auto => {
228                if config.get_direct_gpu_present() {
229                    RenderBackendCandidate::GpuDirect
230                } else {
231                    RenderBackendCandidate::GpuUpload
232                }
233            }
234        };
235        adaptive_router.set_active_candidate(active_candidate);
236        adaptive_router.set_recommended_candidate(active_candidate);
237        let initial_metrics: AdaptiveFrameMetrics = AdaptiveFrameMetrics::with_context(
238            ObservableMetric::Measured(display_refresh_hz as f64),
239            PresentTimingSource::Unobservable,
240            adaptive_router.snapshot(),
241        );
242        Self {
243            config,
244            active_mode,
245            active_backend,
246            active_backend_impl,
247            fallback_software: None,
248            font_service,
249            surface_width: width,
250            surface_height: height,
251            paint_pass: PaintPass,
252            paint_fragment_cache: PaintFragmentCache::default(),
253            display_list,
254            frame_index: 0,
255            compute_pixel_hash,
256            telemetry_enabled: false,
257            last_hashed_mode: None,
258            last_hashed_dims: (0, 0),
259            last_stats: FrameStats::default(),
260            fallback_policy: FallbackPolicyEngine::with_display_hz(display_refresh_hz, semantics),
261            composite_fast_path_frames: 0,
262            cpu_fallback_frames: 0,
263            adaptive_router,
264            last_adaptive_metrics: initial_metrics,
265        }
266    }
267
268    /// Returns an immutable reference to the single active rendering backend enum.
269    ///
270    /// # Arguments
271    ///
272    /// - `&Self` - Renderer reference.
273    ///
274    /// # Returns
275    ///
276    /// - `&ActiveRenderBackend` - Active backend variant.
277    #[must_use]
278    pub fn active_backend_ref(&self) -> &ActiveRenderBackend {
279        let Self {
280            active_backend_impl,
281            ..
282        } = self;
283        active_backend_impl
284    }
285
286    /// Returns a reference to the active or lazily-instantiated `SoftwareRenderer`, if one exists.
287    ///
288    /// # Arguments
289    ///
290    /// - `&Self` - Renderer reference.
291    ///
292    /// # Returns
293    ///
294    /// - `Option<&SoftwareRenderer>` - Software renderer reference when active or lazily allocated.
295    #[must_use]
296    pub fn software(&self) -> Option<&SoftwareRenderer> {
297        let Self {
298            active_backend_impl,
299            fallback_software,
300            ..
301        } = self;
302        match active_backend_impl {
303            ActiveRenderBackend::Software(stroke_width) => Some(stroke_width.as_ref()),
304            ActiveRenderBackend::Hybrid(hy) => Some(hy.get_software()),
305            ActiveRenderBackend::Hardware(_) => fallback_software.as_deref(),
306        }
307    }
308
309    /// Returns a reference to the active `HardwareRenderer` when hardware mode is active.
310    ///
311    /// # Arguments
312    ///
313    /// - `&Self` - Renderer reference.
314    ///
315    /// # Returns
316    ///
317    /// - `Option<&HardwareRenderer>` - Active hardware renderer, or `None` when inactive.
318    #[must_use]
319    pub fn hardware(&self) -> Option<&HardwareRenderer> {
320        let Self {
321            active_backend_impl,
322            ..
323        } = self;
324        match active_backend_impl {
325            ActiveRenderBackend::Hardware(hw) => Some(hw.as_ref()),
326            ActiveRenderBackend::Software(_) | ActiveRenderBackend::Hybrid(_) => None,
327        }
328    }
329
330    /// Returns a reference to the active `HybridRenderer` when hybrid mode is active.
331    ///
332    /// # Arguments
333    ///
334    /// - `&Self` - Renderer reference.
335    ///
336    /// # Returns
337    ///
338    /// - `Option<&HybridRenderer>` - Active hybrid renderer, or `None` when inactive.
339    #[must_use]
340    pub fn hybrid(&self) -> Option<&HybridRenderer> {
341        let Self {
342            active_backend_impl,
343            ..
344        } = self;
345        match active_backend_impl {
346            ActiveRenderBackend::Hybrid(hy) => Some(hy.as_ref()),
347            ActiveRenderBackend::Software(_) | ActiveRenderBackend::Hardware(_) => None,
348        }
349    }
350
351    /// Returns `true` when the lazy CPU fallback `SoftwareRenderer` has been instantiated.
352    ///
353    /// # Arguments
354    ///
355    /// - `&Self` - Renderer reference.
356    ///
357    /// # Returns
358    ///
359    /// - `bool` - Whether `fallback_software` is currently allocated.
360    #[must_use]
361    pub fn has_fallback_software(&self) -> bool {
362        let Self {
363            fallback_software, ..
364        } = self;
365        fallback_software.is_some()
366    }
367
368    /// Returns total CPU RGBA8 framebuffer bytes currently allocated across active and fallback renderers (`0` in GPU direct-draw mode).
369    ///
370    /// # Arguments
371    ///
372    /// - `&Self` - Renderer reference.
373    ///
374    /// # Returns
375    ///
376    /// - `usize` - Total allocated CPU framebuffer pixel bytes.
377    #[must_use]
378    pub fn allocated_cpu_framebuffer_bytes(&self) -> usize {
379        let Self {
380            active_backend_impl,
381            fallback_software,
382            ..
383        } = self;
384        let active_bytes: usize = match active_backend_impl {
385            ActiveRenderBackend::Software(stroke_width) => {
386                stroke_width.allocated_framebuffer_bytes()
387            }
388            ActiveRenderBackend::Hybrid(hy) => hy.get_software().allocated_framebuffer_bytes(),
389            ActiveRenderBackend::Hardware(hw) => hw.get_readback().allocated_framebuffer_bytes(),
390        };
391        let fallback_bytes: usize = fallback_software
392            .as_deref()
393            .map_or(0, SoftwareRenderer::allocated_framebuffer_bytes);
394        active_bytes.saturating_add(fallback_bytes)
395    }
396
397    /// Lazily allocates `fallback_software` if unset and returns a mutable reference to it, reusing `font_service`.
398    ///
399    /// # Arguments
400    ///
401    /// - `&'a mut Option<Box<SoftwareRenderer>>` - Fallback slot to populate lazily.
402    /// - `&mut FontAtlasService` - Shared font and glyph atlas service.
403    /// - `(RenderConfig, u32, u32, bool)` - Tuple `(config, width, height, telemetry_enabled)`.
404    ///
405    /// # Returns
406    ///
407    /// - `&'a mut SoftwareRenderer` - Mutable reference to the lazy CPU reference renderer.
408    fn ensure_fallback_software<'a>(
409        fallback_slot: &'a mut Option<Box<SoftwareRenderer>>,
410        font_service: &mut FontAtlasService,
411        opts: (RenderConfig, u32, u32, bool),
412    ) -> &'a mut SoftwareRenderer {
413        let (config, width, height, telemetry_enabled): (RenderConfig, u32, u32, bool) = opts;
414        let sw_box: &mut Box<SoftwareRenderer> = fallback_slot.get_or_insert_with(|| {
415            let mut sw_cfg: RenderConfig = config;
416            sw_cfg.set_mode(RenderMode::Software);
417            sw_cfg.set_direct_gpu_present(false);
418            let mut stroke_width: SoftwareRenderer = SoftwareRenderer::with_font_provider(
419                width,
420                height,
421                sw_cfg,
422                font_service.get_font_provider().clone(),
423            );
424            swap(
425                stroke_width.get_mut_glyph_atlas(),
426                font_service.get_mut_glyph_atlas(),
427            );
428            stroke_width.set_telemetry_enabled(telemetry_enabled);
429            Box::new(stroke_width)
430        });
431        sw_box.as_mut()
432    }
433
434    /// Returns a mutable reference to the active software renderer, lazily instantiating `fallback_software` only when in hardware mode.
435    ///
436    /// # Arguments
437    ///
438    /// - `&Self` - Mutable renderer.
439    ///
440    /// # Returns
441    ///
442    /// - `&mut SoftwareRenderer` - Mutable software renderer reference.
443    pub fn get_mut_software(&mut self) -> &mut SoftwareRenderer {
444        let Self {
445            active_backend_impl,
446            fallback_software,
447            font_service,
448            config,
449            surface_width,
450            surface_height,
451            telemetry_enabled,
452            ..
453        } = self;
454        match active_backend_impl {
455            ActiveRenderBackend::Software(stroke_width) => stroke_width.as_mut(),
456            ActiveRenderBackend::Hybrid(hy) => hy.get_mut_software(),
457            ActiveRenderBackend::Hardware(_) => Self::ensure_fallback_software(
458                fallback_software,
459                font_service,
460                (*config, *surface_width, *surface_height, *telemetry_enabled),
461            ),
462        }
463    }
464
465    /// Updates whether timing instrumentation (`Instant::now`) is active inside software band scheduling.
466    ///
467    /// # Arguments
468    ///
469    /// - `&Self` - Mutable renderer.
470    /// - `bool` - `true` to enable per-dispatch microsecond timing instrumentation.
471    pub fn set_timing_telemetry_enabled(&mut self, enabled: bool) {
472        self.set_telemetry_enabled(enabled);
473        let Self {
474            active_backend_impl,
475            fallback_software,
476            ..
477        } = self;
478        match active_backend_impl {
479            ActiveRenderBackend::Software(stroke_width) => {
480                stroke_width.set_telemetry_enabled(enabled);
481            }
482            ActiveRenderBackend::Hybrid(hy) => {
483                hy.get_mut_software().set_telemetry_enabled(enabled);
484            }
485            ActiveRenderBackend::Hardware(hw) => {
486                hw.get_mut_readback().set_telemetry_enabled(enabled);
487            }
488        }
489        if let Some(source_width) = fallback_software.as_deref_mut() {
490            source_width.set_telemetry_enabled(enabled);
491        }
492    }
493
494    /// Updates adaptive worker-pool spin behavior for active animation/scroll vs idle periods.
495    ///
496    /// # Arguments
497    ///
498    /// - `&Self` - Mutable renderer.
499    /// - `bool` - `true` during active animation or scrolling; `false` when idle to drop worker spin to `0`.
500    pub fn set_high_frequency_active(&mut self, active: bool) {
501        let Self {
502            active_backend_impl,
503            fallback_software,
504            ..
505        } = self;
506        match active_backend_impl {
507            ActiveRenderBackend::Software(stroke_width) => {
508                stroke_width.set_high_frequency_active(active)
509            }
510            ActiveRenderBackend::Hybrid(hy) => {
511                hy.get_mut_software().set_high_frequency_active(active);
512            }
513            ActiveRenderBackend::Hardware(hw) => {
514                hw.get_mut_readback().set_high_frequency_active(active);
515            }
516        }
517        if let Some(source_width) = fallback_software.as_deref_mut() {
518            source_width.set_high_frequency_active(active);
519        }
520    }
521
522    /// Enables or disables direct GPU rendering without steady-state CPU RGBA readback mirroring.
523    ///
524    /// # Arguments
525    ///
526    /// - `&Self` - Mutable renderer.
527    /// - `bool` - `true` for GPU direct-draw (zero CPU RGBA mirror); `false` to enable software readback mirror.
528    pub fn set_direct_gpu_present(&mut self, enabled: bool) {
529        let mut config_spec: RenderConfig = self.get_config();
530        config_spec.set_direct_gpu_present(enabled);
531        self.set_config(config_spec);
532        let Self {
533            active_backend_impl,
534            last_hashed_mode,
535            ..
536        } = self;
537        if let ActiveRenderBackend::Hardware(hw) = active_backend_impl {
538            hw.set_enable_readback(!enabled);
539            if enabled {
540                hw.get_mut_readback().release_framebuffer();
541            }
542        }
543        *last_hashed_mode = None;
544    }
545
546    /// Synchronizes the fallback policy engine with the active native display refresh rate in Hertz.
547    ///
548    /// # Arguments
549    ///
550    /// - `&Self` - Mutable renderer.
551    /// - `f32` - Active display refresh rate in Hertz.
552    pub fn set_display_refresh_rate_hz(&mut self, display_refresh_hz: f32) {
553        self.get_mut_fallback_policy()
554            .update_display_refresh_hz(display_refresh_hz);
555        if display_refresh_hz.is_finite() && display_refresh_hz > 0.0 {
556            self.get_mut_adaptive_router()
557                .set_display_mode_hz(display_refresh_hz as f64);
558        }
559    }
560
561    /// Returns a compact serializable telemetry snapshot of the active `AdaptiveRenderRouter`.
562    ///
563    /// # Arguments
564    ///
565    /// - `&Self` - Renderer reference.
566    ///
567    /// # Returns
568    ///
569    /// - `AdaptiveRouterSnapshot` - Current adaptive router and handoff snapshot.
570    #[must_use]
571    pub fn adaptive_router_snapshot(&self) -> AdaptiveRouterSnapshot {
572        self.get_adaptive_router().snapshot()
573    }
574
575    /// Returns the active rollout switch mode (`RecommendOnly` vs `AutoSwitch`) on `AdaptiveRenderRouter`.
576    ///
577    /// # Arguments
578    ///
579    /// - `&Self` - Renderer reference.
580    ///
581    /// # Returns
582    ///
583    /// - `AdaptiveSwitchMode` - Active rollout switch policy.
584    #[must_use]
585    pub fn adaptive_switch_mode(&self) -> AdaptiveSwitchMode {
586        self.get_adaptive_router().get_config().get_switch_mode()
587    }
588
589    /// Updates the rollout switch mode (`RecommendOnly` vs `AutoSwitch`) on both `RenderConfig` and the live `AdaptiveRenderRouter`.
590    ///
591    /// # Arguments
592    ///
593    /// - `&Self` - Mutable renderer reference.
594    /// - `AdaptiveSwitchMode` - Requested rollout switch policy.
595    pub fn set_adaptive_switch_mode(&mut self, mode: AdaptiveSwitchMode) {
596        let mut config_spec: RenderConfig = self.get_config();
597        config_spec.set_adaptive_switch_mode(mode);
598        self.set_config(config_spec);
599        let mut router_cfg: AdaptiveRouterConfig = self.get_adaptive_router().get_config();
600        router_cfg.set_switch_mode(mode);
601        self.get_mut_adaptive_router().set_config(router_cfg);
602        let snap: AdaptiveRouterSnapshot = self.get_adaptive_router().snapshot();
603        self.get_mut_last_adaptive_metrics()
604            .set_adaptive_router(snap);
605    }
606
607    /// Returns the most recent truthful `AdaptiveFrameMetrics` snapshot synchronized with the live router state.
608    ///
609    /// # Arguments
610    ///
611    /// - `&Self` - Renderer reference.
612    ///
613    /// # Returns
614    ///
615    /// - `AdaptiveFrameMetrics` - Truthful per-frame adaptive observability snapshot.
616    #[must_use]
617    pub fn adaptive_frame_metrics(&self) -> AdaptiveFrameMetrics {
618        let mut metrics: AdaptiveFrameMetrics = self.get_last_adaptive_metrics();
619        metrics.set_adaptive_router(self.get_adaptive_router().snapshot());
620        metrics
621    }
622
623    /// Applies an adaptive candidate selection to the active pipeline, aligning `direct_gpu_present` strictly with GPU-first selection.
624    ///
625    /// # Arguments
626    ///
627    /// - `&Self` - Mutable renderer reference.
628    /// - `PlatformKind` - Active platform kind.
629    /// - `PlatformCapabilities` - Host hardware capabilities.
630    /// - `RenderBackendCandidate` - Candidate backend to activate.
631    pub fn apply_adaptive_candidate(
632        &mut self,
633        platform: PlatformKind,
634        capabilities: PlatformCapabilities,
635        candidate: RenderBackendCandidate,
636    ) {
637        let direct_gpu: bool = self.get_config().resolve_direct_gpu_present(candidate);
638        let mut config_spec: RenderConfig = self.get_config();
639        config_spec.set_direct_gpu_present(direct_gpu);
640        self.set_config(config_spec);
641        self.switch_mode(platform, capabilities, candidate.to_render_mode());
642        self.set_direct_gpu_present(direct_gpu);
643        self.get_mut_adaptive_router()
644            .set_active_candidate(candidate);
645        self.get_mut_adaptive_router()
646            .set_recommended_candidate(candidate);
647    }
648
649    /// Captures the active visual semantics contract verifying zero quality degradation across fallback transitions.
650    ///
651    /// # Arguments
652    ///
653    /// - `&Self` - Renderer reference.
654    /// - `f32` - Active display scale factor.
655    ///
656    /// # Returns
657    ///
658    /// - `RenderSemanticsContract` - Immutable visual fidelity snapshot.
659    #[must_use]
660    pub fn semantics_contract(&self, scale_factor: f32) -> RenderSemanticsContract {
661        RenderSemanticsContract::from_render_config(self.get_config(), scale_factor)
662    }
663
664    /// Captures an on-demand CPU reference framebuffer for pixel-parity verification even while direct GPU draw is enabled.
665    ///
666    /// # Arguments
667    ///
668    /// - `&Self` - Mutable renderer.
669    /// - `DamageRegion` - Damage region to rasterize into the reference framebuffer.
670    ///
671    /// # Returns
672    ///
673    /// - `&Framebuffer` - Rendered full-fidelity CPU reference RGBA8 framebuffer.
674    pub fn capture_reference_framebuffer(&mut self, damage: DamageRegion) -> &Framebuffer {
675        let Self {
676            active_backend_impl,
677            fallback_software,
678            font_service,
679            config,
680            surface_width,
681            surface_height,
682            telemetry_enabled,
683            display_list,
684            ..
685        } = self;
686        match active_backend_impl {
687            ActiveRenderBackend::Software(stroke_width) => {
688                let (_, _): (usize, usize) = stroke_width.render(display_list, damage);
689                stroke_width.get_framebuffer()
690            }
691            ActiveRenderBackend::Hybrid(hy) => hy.get_software().get_framebuffer(),
692            ActiveRenderBackend::Hardware(hw) => {
693                if hw.get_enable_readback() {
694                    hw.capture_reference_readback(display_list, damage)
695                } else {
696                    let source_width: &mut SoftwareRenderer = Self::ensure_fallback_software(
697                        fallback_software,
698                        font_service,
699                        (*config, *surface_width, *surface_height, *telemetry_enabled),
700                    );
701                    let (_, _): (usize, usize) = source_width.render(display_list, damage);
702                    source_width.get_framebuffer()
703                }
704            }
705        }
706    }
707
708    /// Evaluates `trigger` through `FallbackPolicyEngine` and applies strictly non-degrading cache trimming or CPU reference switching.
709    ///
710    /// # Arguments
711    ///
712    /// - `&Self` - Mutable renderer.
713    /// - `FallbackTrigger` - Runtime pressure, frame overrun, or GPU fault trigger.
714    /// - `u64` - Monotonic clock timestamp in milliseconds.
715    ///
716    /// # Returns
717    ///
718    /// - `FallbackAction` - Strictly non-degrading action applied.
719    pub fn apply_fallback_trigger(
720        &mut self,
721        trigger: FallbackTrigger,
722        now_ms: u64,
723    ) -> FallbackAction {
724        let action: FallbackAction = self
725            .get_mut_fallback_policy()
726            .evaluate_trigger(trigger, now_ms);
727        match action {
728            FallbackAction::TrimPrefetchAndColdCache { retain_ratio } => {
729                let Self {
730                    active_backend_impl,
731                    fallback_software,
732                    font_service,
733                    paint_fragment_cache,
734                    ..
735                } = self;
736                let budget: usize =
737                    ((GLYPH_ATLAS_DEFAULT_BUDGET_BYTES as f32) * retain_ratio.clamp(0.1, 1.0))
738                        .round()
739                        .max(GLYPH_ATLAS_MIN_BUDGET_BYTES as f32) as usize;
740                font_service.get_mut_glyph_atlas().set_memory_budget(budget);
741                match active_backend_impl {
742                    ActiveRenderBackend::Software(stroke_width) => {
743                        stroke_width.get_mut_glyph_atlas().set_memory_budget(budget);
744                    }
745                    ActiveRenderBackend::Hybrid(hy) => {
746                        hy.get_mut_software()
747                            .get_mut_glyph_atlas()
748                            .set_memory_budget(budget);
749                    }
750                    ActiveRenderBackend::Hardware(hw) => {
751                        let _: usize = hw.trim_gpu_caches(retain_ratio);
752                        hw.get_mut_readback()
753                            .get_mut_glyph_atlas()
754                            .set_memory_budget(budget);
755                    }
756                }
757                if let Some(source_width) = fallback_software.as_deref_mut() {
758                    source_width.get_mut_glyph_atlas().set_memory_budget(budget);
759                }
760                if retain_ratio <= FALLBACK_CRITICAL_RETAIN_RATIO + 0.01 {
761                    paint_fragment_cache.clear();
762                }
763            }
764            FallbackAction::SwitchToCpuReference { .. } => {
765                let mut next_cfg: RenderConfig = self.get_config();
766                next_cfg.set_mode(RenderMode::Software);
767                next_cfg.set_direct_gpu_present(false);
768                self.set_config(next_cfg);
769                self.set_active_mode(RenderMode::Software);
770                self.set_active_backend(GraphicsBackend::SoftwareCpu);
771                let Self {
772                    active_backend_impl,
773                    fallback_software,
774                    font_service,
775                    surface_width,
776                    surface_height,
777                    telemetry_enabled,
778                    last_hashed_mode,
779                    ..
780                } = self;
781                if !matches!(active_backend_impl, ActiveRenderBackend::Software(_)) {
782                    let next_sw: Box<SoftwareRenderer> = match fallback_software.take() {
783                        Some(existing) => existing,
784                        None => {
785                            let mut span_width: SoftwareRenderer =
786                                SoftwareRenderer::with_font_provider(
787                                    *surface_width,
788                                    *surface_height,
789                                    next_cfg,
790                                    font_service.get_font_provider().clone(),
791                                );
792                            swap(
793                                span_width.get_mut_glyph_atlas(),
794                                font_service.get_mut_glyph_atlas(),
795                            );
796                            span_width.set_telemetry_enabled(*telemetry_enabled);
797                            Box::new(span_width)
798                        }
799                    };
800                    *active_backend_impl = ActiveRenderBackend::Software(next_sw);
801                }
802                *last_hashed_mode = None;
803            }
804            FallbackAction::None
805            | FallbackAction::AdjustPresentCadence { .. }
806            | FallbackAction::RouteLayerToCpuReference => {}
807        }
808        action
809    }
810
811    /// Resolves `(RenderMode, GraphicsBackend)` deterministically from platform capabilities and user preference.
812    ///
813    /// # Arguments
814    ///
815    /// - `PlatformKind` - Target platform.
816    /// - `PlatformCapabilities` - Hardware support flags.
817    /// - `RenderConfig` - User configuration.
818    ///
819    /// # Returns
820    ///
821    /// - `(RenderMode, GraphicsBackend)` - Concrete resolved mode and backend.
822    #[must_use]
823    pub fn resolve_mode_and_backend(
824        platform: PlatformKind,
825        capabilities: PlatformCapabilities,
826        config: RenderConfig,
827    ) -> (RenderMode, GraphicsBackend) {
828        let default_gpu: GraphicsBackend = platform.default_graphics_backend();
829        let mode: RenderMode = match config.get_mode() {
830            RenderMode::Auto => {
831                if capabilities.get_hardware_gpu() {
832                    RenderMode::Hardware
833                } else {
834                    RenderMode::Software
835                }
836            }
837            explicit => explicit,
838        };
839        let backend: GraphicsBackend = match mode {
840            RenderMode::Software => match platform {
841                PlatformKind::Web | PlatformKind::MiniApp | PlatformKind::QuickApp => {
842                    GraphicsBackend::Canvas2d
843                }
844                _ => GraphicsBackend::SoftwareCpu,
845            },
846            RenderMode::Hardware | RenderMode::Hybrid => {
847                config.preferred_backend_value().unwrap_or(default_gpu)
848            }
849            RenderMode::Auto => default_gpu,
850        };
851        (mode, backend)
852    }
853
854    /// Dynamically switches the active rendering mode at runtime, instantiating only the target backend and transferring the shared glyph atlas.
855    ///
856    /// # Arguments
857    ///
858    /// - `&Self` - Mutable renderer.
859    /// - `PlatformKind` - Active platform kind.
860    /// - `PlatformCapabilities` - Platform hardware capabilities.
861    /// - `RenderMode` - Target render mode.
862    pub fn switch_mode(
863        &mut self,
864        platform: PlatformKind,
865        capabilities: PlatformCapabilities,
866        mode: RenderMode,
867    ) {
868        let mut next_cfg: RenderConfig = self.get_config();
869        next_cfg.set_mode(mode);
870        let (resolved_mode, resolved_backend): (RenderMode, GraphicsBackend) =
871            Self::resolve_mode_and_backend(platform, capabilities, next_cfg);
872        self.set_config(next_cfg);
873        self.set_active_mode(resolved_mode);
874        self.set_active_backend(resolved_backend);
875        let Self {
876            active_backend_impl,
877            fallback_software,
878            font_service,
879            surface_width,
880            surface_height,
881            telemetry_enabled,
882            last_hashed_mode,
883            ..
884        } = self;
885        *last_hashed_mode = None;
886        let same_variant: bool = matches!(
887            (&*active_backend_impl, resolved_mode),
888            (ActiveRenderBackend::Software(_), RenderMode::Software)
889                | (
890                    ActiveRenderBackend::Hardware(_),
891                    RenderMode::Hardware | RenderMode::Auto
892                )
893                | (ActiveRenderBackend::Hybrid(_), RenderMode::Hybrid)
894        );
895        if same_variant {
896            match active_backend_impl {
897                ActiveRenderBackend::Hardware(hw) => {
898                    hw.get_mut_driver().switch_backend(resolved_backend);
899                }
900                ActiveRenderBackend::Hybrid(hy) => {
901                    hy.get_mut_compositor().set_backend_kind(resolved_backend);
902                }
903                ActiveRenderBackend::Software(_) => {}
904            }
905            return;
906        }
907        let mut carried_atlas: GlyphAtlas = take(font_service.get_mut_glyph_atlas());
908        match active_backend_impl {
909            ActiveRenderBackend::Software(stroke_width) => {
910                if !stroke_width.get_glyph_atlas().is_empty() {
911                    carried_atlas = take(stroke_width.get_mut_glyph_atlas());
912                }
913            }
914            ActiveRenderBackend::Hybrid(hy) => {
915                if !hy.get_software().get_glyph_atlas().is_empty() {
916                    carried_atlas = take(hy.get_mut_software().get_mut_glyph_atlas());
917                }
918            }
919            ActiveRenderBackend::Hardware(hw) => {
920                if !hw.get_readback().get_glyph_atlas().is_empty() {
921                    carried_atlas = take(hw.get_mut_readback().get_mut_glyph_atlas());
922                }
923            }
924        }
925        let font_provider: NativeSystemFont = font_service.get_font_provider().clone();
926        let next_backend: ActiveRenderBackend = match resolved_mode {
927            RenderMode::Software => {
928                let mut source_width: Box<SoftwareRenderer> = match fallback_software.take() {
929                    Some(existing) => existing,
930                    None => {
931                        let mut sw_cfg: RenderConfig = next_cfg;
932                        sw_cfg.set_direct_gpu_present(false);
933                        Box::new(SoftwareRenderer::with_font_provider(
934                            *surface_width,
935                            *surface_height,
936                            sw_cfg,
937                            font_provider,
938                        ))
939                    }
940                };
941                if !carried_atlas.is_empty() {
942                    source_width.set_glyph_atlas(carried_atlas);
943                }
944                source_width.set_telemetry_enabled(*telemetry_enabled);
945                ActiveRenderBackend::Software(source_width)
946            }
947            RenderMode::Hybrid => {
948                let mut hy_cfg: RenderConfig = next_cfg;
949                hy_cfg.set_direct_gpu_present(false);
950                let mut hy: HybridRenderer = HybridRenderer::with_backend_and_font(
951                    resolved_backend,
952                    *surface_width,
953                    *surface_height,
954                    hy_cfg,
955                    font_provider,
956                );
957                if !carried_atlas.is_empty() {
958                    hy.get_mut_software().set_glyph_atlas(carried_atlas);
959                }
960                hy.get_mut_software()
961                    .set_telemetry_enabled(*telemetry_enabled);
962                ActiveRenderBackend::Hybrid(Box::new(hy))
963            }
964            RenderMode::Hardware | RenderMode::Auto => {
965                let readback_mirror: bool = !next_cfg.get_direct_gpu_present();
966                let (hw_w, hw_h): (u32, u32) = if readback_mirror {
967                    (*surface_width, *surface_height)
968                } else {
969                    (0, 0)
970                };
971                let mut hw: HardwareRenderer = HardwareRenderer::with_backend_and_font(
972                    resolved_backend,
973                    hw_w,
974                    hw_h,
975                    next_cfg,
976                    readback_mirror,
977                    font_provider,
978                );
979                if !carried_atlas.is_empty() {
980                    hw.get_mut_readback().set_glyph_atlas(carried_atlas);
981                }
982                hw.get_mut_readback()
983                    .set_telemetry_enabled(*telemetry_enabled);
984                ActiveRenderBackend::Hardware(Box::new(hw))
985            }
986        };
987        *active_backend_impl = next_backend;
988    }
989
990    /// Compiles `tree` into a `DisplayList`, executes the active render backend, and returns `FrameStats`.
991    ///
992    /// # Arguments
993    ///
994    /// - `&Self` - Mutable renderer.
995    /// - `&SceneTree` - Laid-out scene tree.
996    /// - `Size` - Logical viewport dimensions.
997    /// - `f32` - Active DPI scale factor.
998    /// - `Color` - Surface clear color.
999    /// - `LayoutStats` - Telemetry from the layout pass.
1000    /// - `DamageRegion` - Damaged screen region.
1001    ///
1002    /// # Returns
1003    ///
1004    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
1005    pub fn render_frame(
1006        &mut self,
1007        tree: &SceneTree,
1008        viewport: Size,
1009        scale_factor: f32,
1010        clear_color: Color,
1011        layout_stats: LayoutStats,
1012        damage: DamageRegion,
1013    ) -> Result<FrameStats, PlatformError> {
1014        let params: FrameRenderParams = FrameRenderParams::new(viewport)
1015            .with_scale(scale_factor)
1016            .with_clear(clear_color)
1017            .with_layout_stats(layout_stats)
1018            .with_damage(damage);
1019        self.render_frame_composite_aware(tree, &params, false)
1020    }
1021
1022    /// Compiles `tree` into a `DisplayList`, honoring composite-only fast paths and non-degrading CPU reference fallback on unsupported GPU effects.
1023    ///
1024    /// # Arguments
1025    ///
1026    /// - `&Self` - Mutable renderer.
1027    /// - `&SceneTree` - Laid-out scene tree.
1028    /// - `&FrameRenderParams` - Viewport, DPI, clear color, layout stats, and damage bundle.
1029    /// - `bool` - Whether only composite/scroll properties changed with zero layout or paint mutations.
1030    ///
1031    /// # Returns
1032    ///
1033    /// - `Result<FrameStats, PlatformError>` - Frame performance, direct-draw, fallback, and pixel-hash telemetry.
1034    pub fn render_frame_composite_aware(
1035        &mut self,
1036        tree: &SceneTree,
1037        params: &FrameRenderParams,
1038        composite_only: bool,
1039    ) -> Result<FrameStats, PlatformError> {
1040        let viewport: Size = params.get_viewport();
1041        let scale: f32 = params.get_scale_factor().max(0.5);
1042        let clear_color: Color = params.get_clear_color();
1043        let layout_stats: LayoutStats = params.get_layout_stats();
1044        let damage: DamageRegion = params.get_damage();
1045        let phys_w: u32 = ((viewport.get_width() * scale).round() as u32).max(1);
1046        let phys_h: u32 = ((viewport.get_height() * scale).round() as u32).max(1);
1047        let phys_dims: (u32, u32) = (phys_w, phys_h);
1048        let Self {
1049            config,
1050            active_mode,
1051            active_backend,
1052            active_backend_impl,
1053            fallback_software,
1054            font_service,
1055            surface_width,
1056            surface_height,
1057            paint_pass,
1058            paint_fragment_cache,
1059            display_list,
1060            frame_index,
1061            compute_pixel_hash,
1062            telemetry_enabled,
1063            last_hashed_mode,
1064            last_hashed_dims,
1065            last_stats,
1066            fallback_policy,
1067            composite_fast_path_frames,
1068            cpu_fallback_frames,
1069            adaptive_router,
1070            last_adaptive_metrics,
1071        } = self;
1072        *surface_width = phys_w;
1073        *surface_height = phys_h;
1074        let mode: RenderMode = *active_mode;
1075        let backend: GraphicsBackend = *active_backend;
1076        let do_pixel_hash: bool = *compute_pixel_hash;
1077        let hash_reusable: bool = *last_hashed_mode == Some(mode) && *last_hashed_dims == phys_dims;
1078        if !damage.get_full_damage() && damage.bounds_rect().is_none() && hash_reusable {
1079            *frame_index = frame_index.wrapping_add(1);
1080            let stats: FrameStats = FrameStats {
1081                frame_index: *frame_index,
1082                active_mode: mode,
1083                active_backend: backend,
1084                layout_nodes: layout_stats.get_nodes_computed(),
1085                layout_skipped: layout_stats.get_subtrees_skipped(),
1086                draw_commands: 0,
1087                draw_batches: 0,
1088                pixels_shaded: 0,
1089                frame_hash: last_stats.get_frame_hash(),
1090                composite_only: false,
1091                gpu_direct_draw: false,
1092                cpu_rgba_upload_bytes: 0,
1093                submit_outcome: FrameSubmitOutcome::SkippedNoDamage,
1094                wait_in_flight: false,
1095            };
1096            *last_stats = stats;
1097            let hz: f64 = adaptive_router.get_display_mode_hz();
1098            let mut skipped_metrics: AdaptiveFrameMetrics = AdaptiveFrameMetrics::with_context(
1099                ObservableMetric::Measured(hz),
1100                PresentTimingSource::Unobservable,
1101                adaptive_router.snapshot(),
1102            );
1103            skipped_metrics.set_present_outcome(SurfacePresentOutcome::SkippedUnchanged);
1104            skipped_metrics.set_upload_strategy(UploadStrategy::None);
1105            skipped_metrics.set_texture_upload_bytes(0);
1106            skipped_metrics.set_cpu_mirror_active(false);
1107            *last_adaptive_metrics = skipped_metrics;
1108            return Ok(stats);
1109        }
1110        let _: &PaintPass = paint_pass;
1111        let layout_changed: bool = layout_stats.get_nodes_computed() > 0;
1112        let took_composite_fast_path: bool = composite_only && !layout_changed;
1113        if took_composite_fast_path {
1114            *composite_fast_path_frames = composite_fast_path_frames.saturating_add(1);
1115        }
1116        PaintPass::build_retained(
1117            tree,
1118            viewport,
1119            scale,
1120            clear_color,
1121            layout_changed,
1122            display_list,
1123            paint_fragment_cache,
1124        );
1125        if *frame_index == 0 && tree.has_scroll_nodes() {
1126            display_list.prewarm_scroll_string_pool(24);
1127        }
1128        let cmd_count: usize = display_list.len();
1129        let mut gpu_direct_draw: bool = false;
1130        let cpu_mirror_active: bool;
1131        let upload_strategy: UploadStrategy;
1132        let cpu_rgba_upload_bytes: usize;
1133        let mut effective_mode: RenderMode = mode;
1134        let mut effective_backend: GraphicsBackend = backend;
1135        let (batches, pixels, hash): (usize, usize, u64) = match active_backend_impl {
1136            ActiveRenderBackend::Software(stroke_width) => {
1137                let (blue_val, point_val): (usize, usize) =
1138                    stroke_width.render(display_list, damage);
1139                cpu_mirror_active = true;
1140                upload_strategy = UploadStrategy::FullFrame;
1141                cpu_rgba_upload_bytes = (phys_w as usize)
1142                    .saturating_mul(phys_h as usize)
1143                    .saturating_mul(4);
1144                let height_val: u64 = if point_val == 0 && hash_reusable {
1145                    last_stats.get_frame_hash()
1146                } else if do_pixel_hash {
1147                    stroke_width.incremental_framebuffer_hash()
1148                } else {
1149                    display_list.fast_hash()
1150                };
1151                (blue_val, point_val, height_val)
1152            }
1153            ActiveRenderBackend::Hybrid(hy) => {
1154                let (byte_val, palette_val): (usize, usize) = hy.render(display_list, damage)?;
1155                cpu_rgba_upload_bytes = hy.get_last_cpu_upload_bytes();
1156                let sparse_active: bool = hy.get_last_cpu_tile_count() > 0;
1157                cpu_mirror_active = sparse_active;
1158                upload_strategy = if sparse_active {
1159                    UploadStrategy::MultiRect
1160                } else {
1161                    UploadStrategy::DirectGpu
1162                };
1163                let span_height: u64 = if palette_val == 0 && hash_reusable {
1164                    last_stats.get_frame_hash()
1165                } else if do_pixel_hash && sparse_active {
1166                    hy.get_mut_software().incremental_framebuffer_hash()
1167                } else {
1168                    display_list.fast_hash()
1169                };
1170                (byte_val, palette_val, span_height)
1171            }
1172            ActiveRenderBackend::Hardware(hw) => match hw.render(display_list, damage) {
1173                Ok((bounds_val, pixel_slice)) => {
1174                    if hw.get_has_unsupported_effect() {
1175                        let _: FallbackAction = fallback_policy.evaluate_trigger(
1176                            FallbackTrigger::MissingGpuEffectPath { isolatable: false },
1177                            0,
1178                        );
1179                        *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
1180                        let source_width: &mut SoftwareRenderer = Self::ensure_fallback_software(
1181                            fallback_software,
1182                            font_service,
1183                            (*config, phys_w, phys_h, *telemetry_enabled),
1184                        );
1185                        let (sb, sp): (usize, usize) = source_width.render(display_list, damage);
1186                        effective_mode = RenderMode::Software;
1187                        effective_backend = GraphicsBackend::SoftwareCpu;
1188                        cpu_mirror_active = true;
1189                        upload_strategy = UploadStrategy::FullFrame;
1190                        cpu_rgba_upload_bytes = (phys_w as usize)
1191                            .saturating_mul(phys_h as usize)
1192                            .saturating_mul(4);
1193                        let half_extent: u64 = if do_pixel_hash {
1194                            source_width.incremental_framebuffer_hash()
1195                        } else {
1196                            display_list.fast_hash()
1197                        };
1198                        (sb, sp, half_extent)
1199                    } else {
1200                        gpu_direct_draw = !hw.get_enable_readback();
1201                        cpu_mirror_active = hw.get_enable_readback();
1202                        upload_strategy = if gpu_direct_draw {
1203                            UploadStrategy::DirectGpu
1204                        } else {
1205                            UploadStrategy::FullFrame
1206                        };
1207                        cpu_rgba_upload_bytes = hw.get_last_cpu_rgba_upload_bytes();
1208                        let height_val_primary: u64 = if pixel_slice == 0 && hash_reusable {
1209                            last_stats.get_frame_hash()
1210                        } else if hw.get_enable_readback() {
1211                            if do_pixel_hash {
1212                                hw.get_mut_readback().incremental_framebuffer_hash()
1213                            } else {
1214                                display_list.fast_hash()
1215                            }
1216                        } else {
1217                            hw.batch_hash()
1218                        };
1219                        (bounds_val, pixel_slice, height_val_primary)
1220                    }
1221                }
1222                Err(_) => {
1223                    let _: FallbackAction =
1224                        fallback_policy.evaluate_trigger(FallbackTrigger::DeviceLost, 0);
1225                    let _: AdaptiveDecision =
1226                        adaptive_router.handle_fault(FaultEventKind::DeviceLost, true, 0);
1227                    *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
1228                    let span_width: &mut SoftwareRenderer = Self::ensure_fallback_software(
1229                        fallback_software,
1230                        font_service,
1231                        (*config, phys_w, phys_h, *telemetry_enabled),
1232                    );
1233                    let (sb, sp): (usize, usize) = span_width.render(display_list, damage);
1234                    effective_mode = RenderMode::Software;
1235                    effective_backend = GraphicsBackend::SoftwareCpu;
1236                    cpu_mirror_active = true;
1237                    upload_strategy = UploadStrategy::FullFrame;
1238                    cpu_rgba_upload_bytes = (phys_w as usize)
1239                        .saturating_mul(phys_h as usize)
1240                        .saturating_mul(4);
1241                    let height_val_secondary: u64 = if do_pixel_hash {
1242                        span_width.incremental_framebuffer_hash()
1243                    } else {
1244                        display_list.fast_hash()
1245                    };
1246                    (sb, sp, height_val_secondary)
1247                }
1248            },
1249        };
1250        *last_hashed_mode = Some(effective_mode);
1251        *last_hashed_dims = phys_dims;
1252        *frame_index = frame_index.wrapping_add(1);
1253        let stats: FrameStats = FrameStats {
1254            frame_index: *frame_index,
1255            active_mode: effective_mode,
1256            active_backend: effective_backend,
1257            layout_nodes: layout_stats.get_nodes_computed(),
1258            layout_skipped: layout_stats.get_subtrees_skipped(),
1259            draw_commands: cmd_count,
1260            draw_batches: batches,
1261            pixels_shaded: pixels,
1262            frame_hash: hash,
1263            composite_only: took_composite_fast_path,
1264            gpu_direct_draw,
1265            cpu_rgba_upload_bytes,
1266            submit_outcome: FrameSubmitOutcome::Submitted,
1267            wait_in_flight: false,
1268        };
1269        *last_stats = stats;
1270        let hz: f64 = adaptive_router.get_display_mode_hz();
1271        let mut frame_metrics: AdaptiveFrameMetrics = AdaptiveFrameMetrics::with_context(
1272            ObservableMetric::Measured(hz),
1273            PresentTimingSource::SubmissionProxy,
1274            adaptive_router.snapshot(),
1275        );
1276        frame_metrics.set_frame_callback_count(*frame_index);
1277        frame_metrics.set_present_outcome(SurfacePresentOutcome::Submitted);
1278        frame_metrics.set_cpu_mirror_active(cpu_mirror_active);
1279        frame_metrics.set_texture_upload_bytes(cpu_rgba_upload_bytes as u64);
1280        frame_metrics.set_upload_strategy(upload_strategy);
1281        *last_adaptive_metrics = frame_metrics;
1282        Ok(stats)
1283    }
1284
1285    /// Renders `tree` using a compact `FrameRenderParams` descriptor and returns `FrameStats`.
1286    ///
1287    /// # Arguments
1288    ///
1289    /// - `&Self` - Mutable renderer.
1290    /// - `&SceneTree` - Laid-out scene tree.
1291    /// - `&FrameRenderParams` - Viewport, DPI, clear color, layout stats, and damage bundle.
1292    ///
1293    /// # Returns
1294    ///
1295    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
1296    #[inline(always)]
1297    pub fn render_with(
1298        &mut self,
1299        tree: &SceneTree,
1300        params: &FrameRenderParams,
1301    ) -> Result<FrameStats, PlatformError> {
1302        self.render_frame(
1303            tree,
1304            params.get_viewport(),
1305            params.get_scale_factor(),
1306            params.get_clear_color(),
1307            params.get_layout_stats(),
1308            params.get_damage(),
1309        )
1310    }
1311
1312    /// Advances the frame counter for an undamaged idle frame without rasterizing or hashing pixels and drops worker spin to `0`.
1313    ///
1314    /// # Arguments
1315    ///
1316    /// - `&Self` - Mutable renderer.
1317    ///
1318    /// # Returns
1319    ///
1320    /// - `FrameStats` - Lightweight telemetry preserving the last rendered `frame_hash` with zero shaded pixels.
1321    pub fn record_skipped_frame(&mut self) -> FrameStats {
1322        self.set_high_frequency_active(false);
1323        let next_idx: u64 = self.get_frame_index().wrapping_add(1);
1324        self.set_frame_index(next_idx);
1325        let mut stats: FrameStats = self.get_last_stats();
1326        stats.set_frame_index(next_idx);
1327        stats.set_layout_nodes(0);
1328        stats.set_draw_batches(0);
1329        stats.set_pixels_shaded(0);
1330        stats.set_composite_only(false);
1331        stats.set_gpu_direct_draw(false);
1332        stats.set_cpu_rgba_upload_bytes(0);
1333        stats.record_present_outcome(PresentOutcome::SkippedNoDamage);
1334        self.set_last_stats(stats);
1335        stats
1336    }
1337
1338    /// Returns cumulative cross-frame `PaintFragmentCache` telemetry `(whole_list_hits, fragment_hits, fragment_misses, fragment_evictions)`.
1339    ///
1340    /// # Arguments
1341    ///
1342    /// - `&Self` - Renderer reference.
1343    ///
1344    /// # Returns
1345    ///
1346    /// - `(u64, u64, u64, u64)` - Tuple of whole-list hits, fragment hits, misses, and evictions.
1347    #[must_use]
1348    pub fn paint_fragment_cache_stats(&self) -> (u64, u64, u64, u64) {
1349        self.get_paint_fragment_cache().stats()
1350    }
1351
1352    /// 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).
1353    ///
1354    /// # Arguments
1355    ///
1356    /// - `&Self` - Renderer reference.
1357    ///
1358    /// # Returns
1359    ///
1360    /// - `Option<&Framebuffer>` - Active RGBA8 framebuffer if resident in host memory.
1361    #[must_use]
1362    pub fn framebuffer(&self) -> Option<&Framebuffer> {
1363        let Self {
1364            active_backend_impl,
1365            fallback_software,
1366            last_stats,
1367            ..
1368        } = self;
1369        match active_backend_impl {
1370            ActiveRenderBackend::Software(stroke_width) => stroke_width.framebuffer_opt(),
1371            ActiveRenderBackend::Hybrid(hy) => hy.get_software().framebuffer_opt(),
1372            ActiveRenderBackend::Hardware(hw) => {
1373                if last_stats.get_active_mode() == RenderMode::Software {
1374                    fallback_software
1375                        .as_deref()
1376                        .and_then(SoftwareRenderer::framebuffer_opt)
1377                } else if hw.get_enable_readback() {
1378                    hw.get_readback().framebuffer_opt()
1379                } else {
1380                    None
1381                }
1382            }
1383        }
1384    }
1385}