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            physical_width: 0,
44            physical_height: 0,
45        }
46    }
47
48    /// Sets the active DPI scale factor clamped to `[0.25, 16.0]`.
49    ///
50    /// # Arguments
51    ///
52    /// - `Self` - Base parameters.
53    /// - `f32` - Scale factor.
54    ///
55    /// # Returns
56    ///
57    /// - `Self` - Updated parameters.
58    #[must_use]
59    pub fn with_scale(mut self, scale_factor: f32) -> Self {
60        self.set_scale_factor(scale_factor.clamp(0.25, 16.0));
61        self
62    }
63
64    /// Attaches exact authoritative physical backing dimensions `(physical_width, physical_height)` preventing fractional-DPI round-trip drift.
65    ///
66    /// # Arguments
67    ///
68    /// - `Self` - Base parameters.
69    /// - `u32` - Authoritative physical width in pixels.
70    /// - `u32` - Authoritative physical height in pixels.
71    ///
72    /// # Returns
73    ///
74    /// - `Self` - Updated parameters.
75    #[must_use]
76    pub fn with_physical_size(mut self, physical_width: u32, physical_height: u32) -> Self {
77        self.set_physical_width(physical_width);
78        self.set_physical_height(physical_height);
79        self
80    }
81
82    /// Sets the surface clear color.
83    ///
84    /// # Arguments
85    ///
86    /// - `Self` - Base parameters.
87    /// - `Color` - Clear color.
88    ///
89    /// # Returns
90    ///
91    /// - `Self` - Updated parameters.
92    #[must_use]
93    pub fn with_clear(mut self, clear_color: Color) -> Self {
94        self.set_clear_color(clear_color);
95        self
96    }
97
98    /// Attaches layout telemetry from the current frame.
99    ///
100    /// # Arguments
101    ///
102    /// - `Self` - Base parameters.
103    /// - `LayoutStats` - Layout pass statistics.
104    ///
105    /// # Returns
106    ///
107    /// - `Self` - Updated parameters.
108    #[must_use]
109    pub fn with_layout_stats(mut self, layout_stats: LayoutStats) -> Self {
110        self.set_layout_stats(layout_stats);
111        self
112    }
113
114    /// Sets the active dirty damage region.
115    ///
116    /// # Arguments
117    ///
118    /// - `Self` - Base parameters.
119    /// - `DamageRegion` - Damage region.
120    ///
121    /// # Returns
122    ///
123    /// - `Self` - Updated parameters.
124    #[must_use]
125    pub fn with_damage(mut self, damage: DamageRegion) -> Self {
126        self.set_damage(damage);
127        self
128    }
129}
130
131/// Single-backend pipeline construction, live mode switching, and frame rendering for `Renderer`.
132impl Renderer {
133    /// Creates a `Renderer` instantiating strictly ONE active backend for `platform` and `config`.
134    ///
135    /// # Arguments
136    ///
137    /// - `PlatformKind` - Active execution platform.
138    /// - `PlatformCapabilities` - Hardware capabilities reported by the platform backend.
139    /// - `u32` - Initial physical width.
140    /// - `u32` - Initial physical height.
141    /// - `RenderConfig` - Requested rendering configuration.
142    ///
143    /// # Returns
144    ///
145    /// - `Self` - Initialized single-backend renderer facade with zero eager fallback allocation.
146    #[must_use]
147    pub fn new(
148        platform: PlatformKind,
149        capabilities: PlatformCapabilities,
150        width: u32,
151        height: u32,
152        config: RenderConfig,
153    ) -> Self {
154        Self::with_display_hz(
155            platform,
156            capabilities,
157            width,
158            height,
159            config,
160            platform.default_refresh_rate_hz(),
161        )
162    }
163
164    /// Creates a `Renderer` bound to live `display_refresh_hz` and instantiating strictly ONE active backend.
165    ///
166    /// # Arguments
167    ///
168    /// - `PlatformKind` - Active execution platform.
169    /// - `PlatformCapabilities` - Hardware capabilities reported by the platform backend.
170    /// - `u32` - Initial physical width.
171    /// - `u32` - Initial physical height.
172    /// - `RenderConfig` - Requested rendering configuration.
173    /// - `f32` - Live native display refresh rate in Hertz.
174    ///
175    /// # Returns
176    ///
177    /// - `Self` - Initialized single-backend renderer facade.
178    #[must_use]
179    pub fn with_display_hz(
180        platform: PlatformKind,
181        capabilities: PlatformCapabilities,
182        width: u32,
183        height: u32,
184        config: RenderConfig,
185        display_refresh_hz: f32,
186    ) -> Self {
187        let (active_mode, active_backend): (RenderMode, GraphicsBackend) =
188            Self::resolve_mode_and_backend(platform, capabilities, config);
189        let readback_mirror: bool = !config.get_direct_gpu_present();
190        let compute_pixel_hash: bool =
191            platform == PlatformKind::Headless || active_backend == GraphicsBackend::Headless;
192        let font_provider: NativeSystemFont = if platform == PlatformKind::Headless {
193            NativeSystemFont::deterministic()
194        } else {
195            NativeSystemFont::system()
196        };
197        let font_service: FontAtlasService =
198            FontAtlasService::with_font_provider(font_provider.clone());
199        let mut display_list: DisplayList = DisplayList::default();
200        display_list.reserve_steady_state();
201        let active_backend_impl: ActiveRenderBackend = match active_mode {
202            RenderMode::Software => ActiveRenderBackend::Software(Box::new(
203                SoftwareRenderer::with_font_provider(width, height, config, font_provider),
204            )),
205            RenderMode::Hybrid => {
206                ActiveRenderBackend::Hybrid(Box::new(HybridRenderer::with_backend_and_font(
207                    active_backend,
208                    width,
209                    height,
210                    config,
211                    font_provider,
212                )))
213            }
214            RenderMode::Hardware | RenderMode::Auto => {
215                let (hw_w, hw_h): (u32, u32) = if readback_mirror {
216                    (width, height)
217                } else {
218                    (0, 0)
219                };
220                ActiveRenderBackend::Hardware(Box::new(HardwareRenderer::with_backend_and_font(
221                    active_backend,
222                    hw_w,
223                    hw_h,
224                    config,
225                    readback_mirror,
226                    font_provider,
227                )))
228            }
229        };
230        let semantics: RenderSemanticsContract =
231            RenderSemanticsContract::from_render_config(config, 1.0);
232        let host_profile: HostCapabilityProfile =
233            HostCapabilityProfile::from_platform(platform, capabilities);
234        let mut router_cfg: AdaptiveRouterConfig = AdaptiveRouterConfig::default();
235        router_cfg.set_switch_mode(config.get_adaptive_switch_mode());
236        let mut adaptive_router: AdaptiveRenderRouter =
237            AdaptiveRenderRouter::new(router_cfg, host_profile, display_refresh_hz as f64);
238        let active_candidate: RenderBackendCandidate = match active_mode {
239            RenderMode::Software => {
240                if platform == PlatformKind::Terminal {
241                    RenderBackendCandidate::Terminal
242                } else {
243                    RenderBackendCandidate::Software
244                }
245            }
246            RenderMode::Hybrid => RenderBackendCandidate::Hybrid,
247            RenderMode::Hardware | RenderMode::Auto => {
248                if config.get_direct_gpu_present() {
249                    RenderBackendCandidate::GpuDirect
250                } else {
251                    RenderBackendCandidate::GpuUpload
252                }
253            }
254        };
255        adaptive_router.set_active_candidate(active_candidate);
256        adaptive_router.set_recommended_candidate(active_candidate);
257        let initial_metrics: AdaptiveFrameMetrics = AdaptiveFrameMetrics::with_context(
258            ObservableMetric::Measured(display_refresh_hz as f64),
259            PresentTimingSource::Unobservable,
260            adaptive_router.snapshot(),
261        );
262        Self {
263            config,
264            active_mode,
265            active_backend,
266            active_platform: platform,
267            active_backend_impl,
268            fallback_software: None,
269            font_service,
270            surface_width: width,
271            surface_height: height,
272            paint_pass: PaintPass,
273            paint_fragment_cache: PaintFragmentCache::default(),
274            display_list,
275            frame_index: 0,
276            compute_pixel_hash,
277            telemetry_enabled: false,
278            last_hashed_mode: None,
279            last_hashed_dims: (0, 0),
280            last_stats: FrameStats::default(),
281            fallback_policy: FallbackPolicyEngine::with_display_hz(display_refresh_hz, semantics),
282            composite_fast_path_frames: 0,
283            cpu_fallback_frames: 0,
284            adaptive_router,
285            last_adaptive_metrics: initial_metrics,
286            execution_router: AdaptiveExecutionRouter::default(),
287            render_graph: RenderGraph::default(),
288            last_scale_bits: 0,
289            direct_submission_scratch: Box::new(GpuFrameSubmission::default()),
290            direct_batch_tail_pool: Vec::new(),
291        }
292    }
293
294    /// Returns an immutable reference to the single active rendering backend enum.
295    ///
296    /// # Arguments
297    ///
298    /// - `&Self` - Renderer reference.
299    ///
300    /// # Returns
301    ///
302    /// - `&ActiveRenderBackend` - Active backend variant.
303    #[must_use]
304    pub fn active_backend_ref(&self) -> &ActiveRenderBackend {
305        let Self {
306            active_backend_impl,
307            ..
308        } = self;
309        active_backend_impl
310    }
311
312    /// Returns a reference to the active or lazily-instantiated `SoftwareRenderer`, if one exists.
313    ///
314    /// # Arguments
315    ///
316    /// - `&Self` - Renderer reference.
317    ///
318    /// # Returns
319    ///
320    /// - `Option<&SoftwareRenderer>` - Software renderer reference when active or lazily allocated.
321    #[must_use]
322    pub fn software(&self) -> Option<&SoftwareRenderer> {
323        let Self {
324            active_backend_impl,
325            fallback_software,
326            ..
327        } = self;
328        match active_backend_impl {
329            ActiveRenderBackend::Software(stroke_width) => Some(stroke_width.as_ref()),
330            ActiveRenderBackend::Hybrid(hy) => Some(hy.get_software()),
331            ActiveRenderBackend::Hardware(_) => fallback_software.as_deref(),
332        }
333    }
334
335    /// Returns a reference to the active `HardwareRenderer` when hardware mode is active.
336    ///
337    /// # Arguments
338    ///
339    /// - `&Self` - Renderer reference.
340    ///
341    /// # Returns
342    ///
343    /// - `Option<&HardwareRenderer>` - Active hardware renderer, or `None` when inactive.
344    #[must_use]
345    pub fn hardware(&self) -> Option<&HardwareRenderer> {
346        let Self {
347            active_backend_impl,
348            ..
349        } = self;
350        match active_backend_impl {
351            ActiveRenderBackend::Hardware(hw) => Some(hw.as_ref()),
352            ActiveRenderBackend::Software(_) | ActiveRenderBackend::Hybrid(_) => None,
353        }
354    }
355
356    /// Returns a reference to the active `HybridRenderer` when hybrid mode is active.
357    ///
358    /// # Arguments
359    ///
360    /// - `&Self` - Renderer reference.
361    ///
362    /// # Returns
363    ///
364    /// - `Option<&HybridRenderer>` - Active hybrid renderer, or `None` when inactive.
365    #[must_use]
366    pub fn hybrid(&self) -> Option<&HybridRenderer> {
367        let Self {
368            active_backend_impl,
369            ..
370        } = self;
371        match active_backend_impl {
372            ActiveRenderBackend::Hybrid(hy) => Some(hy.as_ref()),
373            ActiveRenderBackend::Software(_) | ActiveRenderBackend::Hardware(_) => None,
374        }
375    }
376
377    /// Returns `true` when the lazy CPU fallback `SoftwareRenderer` has been instantiated.
378    ///
379    /// # Arguments
380    ///
381    /// - `&Self` - Renderer reference.
382    ///
383    /// # Returns
384    ///
385    /// - `bool` - Whether `fallback_software` is currently allocated.
386    #[must_use]
387    pub fn has_fallback_software(&self) -> bool {
388        let Self {
389            fallback_software, ..
390        } = self;
391        fallback_software.is_some()
392    }
393
394    /// Returns total CPU RGBA8 framebuffer bytes currently allocated across active and fallback renderers (`0` in GPU direct-draw mode).
395    ///
396    /// # Arguments
397    ///
398    /// - `&Self` - Renderer reference.
399    ///
400    /// # Returns
401    ///
402    /// - `usize` - Total allocated CPU framebuffer pixel bytes.
403    #[must_use]
404    pub fn allocated_cpu_framebuffer_bytes(&self) -> usize {
405        let Self {
406            active_backend_impl,
407            fallback_software,
408            ..
409        } = self;
410        let active_bytes: usize = match active_backend_impl {
411            ActiveRenderBackend::Software(stroke_width) => {
412                stroke_width.allocated_framebuffer_bytes()
413            }
414            ActiveRenderBackend::Hybrid(hy) => hy.get_software().allocated_framebuffer_bytes(),
415            ActiveRenderBackend::Hardware(hw) => hw.get_readback().allocated_framebuffer_bytes(),
416        };
417        let fallback_bytes: usize = fallback_software
418            .as_deref()
419            .map_or(0, SoftwareRenderer::allocated_framebuffer_bytes);
420        active_bytes.saturating_add(fallback_bytes)
421    }
422
423    /// Lazily allocates `fallback_software` if unset and returns a mutable reference to it, reusing `font_service`.
424    ///
425    /// # Arguments
426    ///
427    /// - `&'a mut Option<Box<SoftwareRenderer>>` - Fallback slot to populate lazily.
428    /// - `&mut FontAtlasService` - Shared font and glyph atlas service.
429    /// - `(RenderConfig, u32, u32, bool)` - Tuple `(config, width, height, telemetry_enabled)`.
430    ///
431    /// # Returns
432    ///
433    /// - `&'a mut SoftwareRenderer` - Mutable reference to the lazy CPU reference renderer.
434    fn ensure_fallback_software<'a>(
435        fallback_slot: &'a mut Option<Box<SoftwareRenderer>>,
436        font_service: &mut FontAtlasService,
437        opts: (RenderConfig, u32, u32, bool),
438    ) -> &'a mut SoftwareRenderer {
439        let (config, width, height, telemetry_enabled): (RenderConfig, u32, u32, bool) = opts;
440        let sw_box: &mut Box<SoftwareRenderer> = fallback_slot.get_or_insert_with(|| {
441            let mut sw_cfg: RenderConfig = config;
442            sw_cfg.set_mode(RenderMode::Software);
443            sw_cfg.set_direct_gpu_present(false);
444            let mut stroke_width: SoftwareRenderer = SoftwareRenderer::with_font_provider(
445                width,
446                height,
447                sw_cfg,
448                font_service.get_font_provider().clone(),
449            );
450            swap(
451                stroke_width.get_mut_glyph_atlas(),
452                font_service.get_mut_glyph_atlas(),
453            );
454            stroke_width.set_telemetry_enabled(telemetry_enabled);
455            Box::new(stroke_width)
456        });
457        sw_box.as_mut()
458    }
459
460    /// Returns a mutable reference to the active software renderer, lazily instantiating `fallback_software` only when in hardware mode.
461    ///
462    /// # Arguments
463    ///
464    /// - `&Self` - Mutable renderer.
465    ///
466    /// # Returns
467    ///
468    /// - `&mut SoftwareRenderer` - Mutable software renderer reference.
469    pub fn get_mut_software(&mut self) -> &mut SoftwareRenderer {
470        let Self {
471            active_backend_impl,
472            fallback_software,
473            font_service,
474            config,
475            surface_width,
476            surface_height,
477            telemetry_enabled,
478            ..
479        } = self;
480        match active_backend_impl {
481            ActiveRenderBackend::Software(stroke_width) => stroke_width.as_mut(),
482            ActiveRenderBackend::Hybrid(hy) => hy.get_mut_software(),
483            ActiveRenderBackend::Hardware(_) => Self::ensure_fallback_software(
484                fallback_software,
485                font_service,
486                (*config, *surface_width, *surface_height, *telemetry_enabled),
487            ),
488        }
489    }
490
491    /// Updates whether timing instrumentation (`Instant::now`) is active inside software band scheduling.
492    ///
493    /// # Arguments
494    ///
495    /// - `&Self` - Mutable renderer.
496    /// - `bool` - `true` to enable per-dispatch microsecond timing instrumentation.
497    pub fn set_timing_telemetry_enabled(&mut self, enabled: bool) {
498        self.set_telemetry_enabled(enabled);
499        let Self {
500            active_backend_impl,
501            fallback_software,
502            ..
503        } = self;
504        match active_backend_impl {
505            ActiveRenderBackend::Software(stroke_width) => {
506                stroke_width.set_telemetry_enabled(enabled);
507            }
508            ActiveRenderBackend::Hybrid(hy) => {
509                hy.get_mut_software().set_telemetry_enabled(enabled);
510            }
511            ActiveRenderBackend::Hardware(hw) => {
512                hw.get_mut_readback().set_telemetry_enabled(enabled);
513            }
514        }
515        if let Some(source_width) = fallback_software.as_deref_mut() {
516            source_width.set_telemetry_enabled(enabled);
517        }
518    }
519
520    /// Updates adaptive worker-pool spin behavior for active animation/scroll vs idle periods.
521    ///
522    /// # Arguments
523    ///
524    /// - `&Self` - Mutable renderer.
525    /// - `bool` - `true` during active animation or scrolling; `false` when idle to drop worker spin to `0`.
526    pub fn set_high_frequency_active(&mut self, active: bool) {
527        let Self {
528            active_backend_impl,
529            fallback_software,
530            ..
531        } = self;
532        match active_backend_impl {
533            ActiveRenderBackend::Software(stroke_width) => {
534                stroke_width.set_high_frequency_active(active)
535            }
536            ActiveRenderBackend::Hybrid(hy) => {
537                hy.get_mut_software().set_high_frequency_active(active);
538            }
539            ActiveRenderBackend::Hardware(hw) => {
540                hw.get_mut_readback().set_high_frequency_active(active);
541            }
542        }
543        if let Some(source_width) = fallback_software.as_deref_mut() {
544            source_width.set_high_frequency_active(active);
545        }
546    }
547
548    /// Enables or disables direct GPU rendering without steady-state CPU RGBA readback mirroring.
549    ///
550    /// # Arguments
551    ///
552    /// - `&Self` - Mutable renderer.
553    /// - `bool` - `true` for GPU direct-draw (zero CPU RGBA mirror); `false` to enable software readback mirror.
554    pub fn set_direct_gpu_present(&mut self, enabled: bool) {
555        let mut config_spec: RenderConfig = self.get_config();
556        config_spec.set_direct_gpu_present(enabled);
557        self.set_config(config_spec);
558        let Self {
559            active_backend_impl,
560            last_hashed_mode,
561            ..
562        } = self;
563        if let ActiveRenderBackend::Hardware(hw) = active_backend_impl {
564            hw.set_enable_readback(!enabled);
565            hw.set_per_glyph_atlas(enabled);
566            if enabled {
567                hw.get_mut_readback().release_framebuffer();
568                hw.get_mut_gpu_glyph_atlas()
569                    .set_submission_needs_full_upload(true);
570            }
571        }
572        *last_hashed_mode = None;
573    }
574
575    /// Synchronizes the fallback policy engine with the active native display refresh rate in Hertz.
576    ///
577    /// # Arguments
578    ///
579    /// - `&Self` - Mutable renderer.
580    /// - `f32` - Active display refresh rate in Hertz.
581    pub fn set_display_refresh_rate_hz(&mut self, display_refresh_hz: f32) {
582        self.get_mut_fallback_policy()
583            .update_display_refresh_hz(display_refresh_hz);
584        if display_refresh_hz.is_finite() && display_refresh_hz > 0.0 {
585            self.get_mut_adaptive_router()
586                .set_display_mode_hz(display_refresh_hz as f64);
587        }
588    }
589
590    /// Returns a compact serializable telemetry snapshot of the active `AdaptiveRenderRouter`.
591    ///
592    /// # Arguments
593    ///
594    /// - `&Self` - Renderer reference.
595    ///
596    /// # Returns
597    ///
598    /// - `AdaptiveRouterSnapshot` - Current adaptive router and handoff snapshot.
599    #[must_use]
600    pub fn adaptive_router_snapshot(&self) -> AdaptiveRouterSnapshot {
601        self.get_adaptive_router().snapshot()
602    }
603
604    /// Returns the active rollout switch mode (`RecommendOnly` vs `AutoSwitch`) on `AdaptiveRenderRouter`.
605    ///
606    /// # Arguments
607    ///
608    /// - `&Self` - Renderer reference.
609    ///
610    /// # Returns
611    ///
612    /// - `AdaptiveSwitchMode` - Active rollout switch policy.
613    #[must_use]
614    pub fn adaptive_switch_mode(&self) -> AdaptiveSwitchMode {
615        self.get_adaptive_router().get_config().get_switch_mode()
616    }
617
618    /// Updates the rollout switch mode (`RecommendOnly` vs `AutoSwitch`) on both `RenderConfig` and the live `AdaptiveRenderRouter`.
619    ///
620    /// # Arguments
621    ///
622    /// - `&Self` - Mutable renderer reference.
623    /// - `AdaptiveSwitchMode` - Requested rollout switch policy.
624    pub fn set_adaptive_switch_mode(&mut self, mode: AdaptiveSwitchMode) {
625        let mut config_spec: RenderConfig = self.get_config();
626        config_spec.set_adaptive_switch_mode(mode);
627        self.set_config(config_spec);
628        let mut router_cfg: AdaptiveRouterConfig = self.get_adaptive_router().get_config();
629        router_cfg.set_switch_mode(mode);
630        self.get_mut_adaptive_router().set_config(router_cfg);
631        let snap: AdaptiveRouterSnapshot = self.get_adaptive_router().snapshot();
632        self.get_mut_last_adaptive_metrics()
633            .set_adaptive_router(snap);
634    }
635
636    /// Returns the most recent truthful `AdaptiveFrameMetrics` snapshot synchronized with the live router state.
637    ///
638    /// # Arguments
639    ///
640    /// - `&Self` - Renderer reference.
641    ///
642    /// # Returns
643    ///
644    /// - `AdaptiveFrameMetrics` - Truthful per-frame adaptive observability snapshot.
645    #[must_use]
646    pub fn adaptive_frame_metrics(&self) -> AdaptiveFrameMetrics {
647        let mut metrics: AdaptiveFrameMetrics = self.get_last_adaptive_metrics();
648        metrics.set_adaptive_router(self.get_adaptive_router().snapshot());
649        metrics
650    }
651
652    /// Applies an adaptive candidate selection to the active pipeline, aligning `direct_gpu_present` strictly with GPU-first selection.
653    ///
654    /// # Arguments
655    ///
656    /// - `&Self` - Mutable renderer reference.
657    /// - `PlatformKind` - Active platform kind.
658    /// - `PlatformCapabilities` - Host hardware capabilities.
659    /// - `RenderBackendCandidate` - Candidate backend to activate.
660    pub fn apply_adaptive_candidate(
661        &mut self,
662        platform: PlatformKind,
663        capabilities: PlatformCapabilities,
664        candidate: RenderBackendCandidate,
665    ) {
666        let direct_gpu: bool = self.get_config().resolve_direct_gpu_present(candidate);
667        let mut config_spec: RenderConfig = self.get_config();
668        config_spec.set_direct_gpu_present(direct_gpu);
669        self.set_config(config_spec);
670        self.switch_mode(platform, capabilities, candidate.to_render_mode());
671        self.set_direct_gpu_present(direct_gpu);
672        self.get_mut_adaptive_router()
673            .set_active_candidate(candidate);
674        self.get_mut_adaptive_router()
675            .set_recommended_candidate(candidate);
676    }
677
678    /// Captures the active visual semantics contract verifying zero quality degradation across fallback transitions.
679    ///
680    /// # Arguments
681    ///
682    /// - `&Self` - Renderer reference.
683    /// - `f32` - Active display scale factor.
684    ///
685    /// # Returns
686    ///
687    /// - `RenderSemanticsContract` - Immutable visual fidelity snapshot.
688    #[must_use]
689    pub fn semantics_contract(&self, scale_factor: f32) -> RenderSemanticsContract {
690        RenderSemanticsContract::from_render_config(self.get_config(), scale_factor)
691    }
692
693    /// Captures an on-demand CPU reference framebuffer for pixel-parity verification even while direct GPU draw is enabled.
694    ///
695    /// # Arguments
696    ///
697    /// - `&Self` - Mutable renderer.
698    /// - `DamageRegion` - Damage region to rasterize into the reference framebuffer.
699    ///
700    /// # Returns
701    ///
702    /// - `&Framebuffer` - Rendered full-fidelity CPU reference RGBA8 framebuffer.
703    pub fn capture_reference_framebuffer(&mut self, damage: DamageRegion) -> &Framebuffer {
704        let Self {
705            active_backend_impl,
706            fallback_software,
707            font_service,
708            config,
709            surface_width,
710            surface_height,
711            telemetry_enabled,
712            display_list,
713            ..
714        } = self;
715        match active_backend_impl {
716            ActiveRenderBackend::Software(stroke_width) => {
717                let (_, _): (usize, usize) = stroke_width.render(display_list, damage);
718                stroke_width.get_framebuffer()
719            }
720            ActiveRenderBackend::Hybrid(hy) => hy.get_software().get_framebuffer(),
721            ActiveRenderBackend::Hardware(hw) => {
722                if hw.get_enable_readback() {
723                    hw.capture_reference_readback(display_list, damage)
724                } else {
725                    let source_width: &mut SoftwareRenderer = Self::ensure_fallback_software(
726                        fallback_software,
727                        font_service,
728                        (*config, *surface_width, *surface_height, *telemetry_enabled),
729                    );
730                    let (_, _): (usize, usize) = source_width.render(display_list, damage);
731                    source_width.get_framebuffer()
732                }
733            }
734        }
735    }
736
737    /// Evaluates `trigger` through `FallbackPolicyEngine` and applies strictly non-degrading cache trimming or CPU reference switching.
738    ///
739    /// # Arguments
740    ///
741    /// - `&Self` - Mutable renderer.
742    /// - `FallbackTrigger` - Runtime pressure, frame overrun, or GPU fault trigger.
743    /// - `u64` - Monotonic clock timestamp in milliseconds.
744    ///
745    /// # Returns
746    ///
747    /// - `FallbackAction` - Strictly non-degrading action applied.
748    pub fn apply_fallback_trigger(
749        &mut self,
750        trigger: FallbackTrigger,
751        now_ms: u64,
752    ) -> FallbackAction {
753        let action: FallbackAction = self
754            .get_mut_fallback_policy()
755            .evaluate_trigger(trigger, now_ms);
756        match action {
757            FallbackAction::TrimPrefetchAndColdCache { retain_ratio } => {
758                let Self {
759                    active_backend_impl,
760                    fallback_software,
761                    font_service,
762                    paint_fragment_cache,
763                    ..
764                } = self;
765                let budget: usize =
766                    ((GLYPH_ATLAS_DEFAULT_BUDGET_BYTES as f32) * retain_ratio.clamp(0.1, 1.0))
767                        .round()
768                        .max(GLYPH_ATLAS_MIN_BUDGET_BYTES as f32) as usize;
769                font_service.get_mut_glyph_atlas().set_memory_budget(budget);
770                match active_backend_impl {
771                    ActiveRenderBackend::Software(stroke_width) => {
772                        stroke_width.get_mut_glyph_atlas().set_memory_budget(budget);
773                    }
774                    ActiveRenderBackend::Hybrid(hy) => {
775                        hy.get_mut_software()
776                            .get_mut_glyph_atlas()
777                            .set_memory_budget(budget);
778                    }
779                    ActiveRenderBackend::Hardware(hw) => {
780                        let _: usize = hw.trim_gpu_caches(retain_ratio);
781                        hw.get_mut_readback()
782                            .get_mut_glyph_atlas()
783                            .set_memory_budget(budget);
784                    }
785                }
786                if let Some(source_width) = fallback_software.as_deref_mut() {
787                    source_width.get_mut_glyph_atlas().set_memory_budget(budget);
788                }
789                if retain_ratio <= FALLBACK_CRITICAL_RETAIN_RATIO + 0.01 {
790                    paint_fragment_cache.clear();
791                }
792            }
793            FallbackAction::SwitchToCpuReference { .. } => {
794                let mut next_cfg: RenderConfig = self.get_config();
795                next_cfg.set_mode(RenderMode::Software);
796                next_cfg.set_direct_gpu_present(false);
797                self.set_config(next_cfg);
798                self.set_active_mode(RenderMode::Software);
799                self.set_active_backend(GraphicsBackend::SoftwareCpu);
800                let Self {
801                    active_backend_impl,
802                    fallback_software,
803                    font_service,
804                    surface_width,
805                    surface_height,
806                    telemetry_enabled,
807                    last_hashed_mode,
808                    ..
809                } = self;
810                if !matches!(active_backend_impl, ActiveRenderBackend::Software(_)) {
811                    let next_sw: Box<SoftwareRenderer> = match fallback_software.take() {
812                        Some(existing) => existing,
813                        None => {
814                            let mut span_width: SoftwareRenderer =
815                                SoftwareRenderer::with_font_provider(
816                                    *surface_width,
817                                    *surface_height,
818                                    next_cfg,
819                                    font_service.get_font_provider().clone(),
820                                );
821                            swap(
822                                span_width.get_mut_glyph_atlas(),
823                                font_service.get_mut_glyph_atlas(),
824                            );
825                            span_width.set_telemetry_enabled(*telemetry_enabled);
826                            Box::new(span_width)
827                        }
828                    };
829                    *active_backend_impl = ActiveRenderBackend::Software(next_sw);
830                }
831                *last_hashed_mode = None;
832            }
833            FallbackAction::None
834            | FallbackAction::AdjustPresentCadence { .. }
835            | FallbackAction::RouteLayerToCpuReference => {}
836        }
837        action
838    }
839
840    /// Resolves `(RenderMode, GraphicsBackend)` deterministically from platform capabilities and user preference.
841    ///
842    /// # Arguments
843    ///
844    /// - `PlatformKind` - Target platform.
845    /// - `PlatformCapabilities` - Hardware support flags.
846    /// - `RenderConfig` - User configuration.
847    ///
848    /// # Returns
849    ///
850    /// - `(RenderMode, GraphicsBackend)` - Concrete resolved mode and backend.
851    #[must_use]
852    pub fn resolve_mode_and_backend(
853        platform: PlatformKind,
854        capabilities: PlatformCapabilities,
855        config: RenderConfig,
856    ) -> (RenderMode, GraphicsBackend) {
857        let default_gpu: GraphicsBackend = platform.default_graphics_backend();
858        let mode: RenderMode = match config.get_mode() {
859            RenderMode::Auto => {
860                if capabilities.get_hardware_gpu() {
861                    RenderMode::Hardware
862                } else {
863                    RenderMode::Software
864                }
865            }
866            explicit => explicit,
867        };
868        let backend: GraphicsBackend = match mode {
869            RenderMode::Software => match platform {
870                PlatformKind::Web | PlatformKind::MiniApp | PlatformKind::QuickApp => {
871                    GraphicsBackend::Canvas2d
872                }
873                _ => GraphicsBackend::SoftwareCpu,
874            },
875            RenderMode::Hardware | RenderMode::Hybrid => {
876                config.preferred_backend_value().unwrap_or(default_gpu)
877            }
878            RenderMode::Auto => default_gpu,
879        };
880        (mode, backend)
881    }
882
883    /// Dynamically switches the active rendering mode at runtime, instantiating only the target backend and transferring the shared glyph atlas.
884    ///
885    /// # Arguments
886    ///
887    /// - `&Self` - Mutable renderer.
888    /// - `PlatformKind` - Active platform kind.
889    /// - `PlatformCapabilities` - Platform hardware capabilities.
890    /// - `RenderMode` - Target render mode.
891    pub fn switch_mode(
892        &mut self,
893        platform: PlatformKind,
894        capabilities: PlatformCapabilities,
895        mode: RenderMode,
896    ) {
897        let mut next_cfg: RenderConfig = self.get_config();
898        next_cfg.set_mode(mode);
899        let (resolved_mode, resolved_backend): (RenderMode, GraphicsBackend) =
900            Self::resolve_mode_and_backend(platform, capabilities, next_cfg);
901        self.set_config(next_cfg);
902        self.set_active_mode(resolved_mode);
903        self.set_active_backend(resolved_backend);
904        let Self {
905            active_backend_impl,
906            fallback_software,
907            font_service,
908            surface_width,
909            surface_height,
910            telemetry_enabled,
911            last_hashed_mode,
912            ..
913        } = self;
914        *last_hashed_mode = None;
915        let same_variant: bool = matches!(
916            (&*active_backend_impl, resolved_mode),
917            (ActiveRenderBackend::Software(_), RenderMode::Software)
918                | (
919                    ActiveRenderBackend::Hardware(_),
920                    RenderMode::Hardware | RenderMode::Auto
921                )
922                | (ActiveRenderBackend::Hybrid(_), RenderMode::Hybrid)
923        );
924        if same_variant {
925            match active_backend_impl {
926                ActiveRenderBackend::Hardware(hw) => {
927                    hw.get_mut_driver().switch_backend(resolved_backend);
928                }
929                ActiveRenderBackend::Hybrid(hy) => {
930                    hy.get_mut_driver().switch_backend(resolved_backend);
931                }
932                ActiveRenderBackend::Software(_) => {}
933            }
934            return;
935        }
936        let mut carried_atlas: GlyphAtlas = take(font_service.get_mut_glyph_atlas());
937        match active_backend_impl {
938            ActiveRenderBackend::Software(stroke_width) => {
939                if !stroke_width.get_glyph_atlas().is_empty() {
940                    carried_atlas = take(stroke_width.get_mut_glyph_atlas());
941                }
942            }
943            ActiveRenderBackend::Hybrid(hy) => {
944                if !hy.get_software().get_glyph_atlas().is_empty() {
945                    carried_atlas = take(hy.get_mut_software().get_mut_glyph_atlas());
946                }
947            }
948            ActiveRenderBackend::Hardware(hw) => {
949                if !hw.get_readback().get_glyph_atlas().is_empty() {
950                    carried_atlas = take(hw.get_mut_readback().get_mut_glyph_atlas());
951                }
952            }
953        }
954        let font_provider: NativeSystemFont = font_service.get_font_provider().clone();
955        let next_backend: ActiveRenderBackend = match resolved_mode {
956            RenderMode::Software => {
957                let mut source_width: Box<SoftwareRenderer> = match fallback_software.take() {
958                    Some(existing) => existing,
959                    None => {
960                        let mut sw_cfg: RenderConfig = next_cfg;
961                        sw_cfg.set_direct_gpu_present(false);
962                        Box::new(SoftwareRenderer::with_font_provider(
963                            *surface_width,
964                            *surface_height,
965                            sw_cfg,
966                            font_provider,
967                        ))
968                    }
969                };
970                if !carried_atlas.is_empty() {
971                    source_width.set_glyph_atlas(carried_atlas);
972                }
973                source_width.set_telemetry_enabled(*telemetry_enabled);
974                ActiveRenderBackend::Software(source_width)
975            }
976            RenderMode::Hybrid => {
977                let mut hy_cfg: RenderConfig = next_cfg;
978                hy_cfg.set_direct_gpu_present(false);
979                let mut hy: HybridRenderer = HybridRenderer::with_backend_and_font(
980                    resolved_backend,
981                    *surface_width,
982                    *surface_height,
983                    hy_cfg,
984                    font_provider,
985                );
986                if !carried_atlas.is_empty() {
987                    hy.get_mut_software().set_glyph_atlas(carried_atlas);
988                }
989                hy.get_mut_software()
990                    .set_telemetry_enabled(*telemetry_enabled);
991                ActiveRenderBackend::Hybrid(Box::new(hy))
992            }
993            RenderMode::Hardware | RenderMode::Auto => {
994                let readback_mirror: bool = !next_cfg.get_direct_gpu_present();
995                let (hw_w, hw_h): (u32, u32) = if readback_mirror {
996                    (*surface_width, *surface_height)
997                } else {
998                    (0, 0)
999                };
1000                let mut hw: HardwareRenderer = HardwareRenderer::with_backend_and_font(
1001                    resolved_backend,
1002                    hw_w,
1003                    hw_h,
1004                    next_cfg,
1005                    readback_mirror,
1006                    font_provider,
1007                );
1008                if !carried_atlas.is_empty() {
1009                    hw.get_mut_readback().set_glyph_atlas(carried_atlas);
1010                }
1011                hw.get_mut_readback()
1012                    .set_telemetry_enabled(*telemetry_enabled);
1013                ActiveRenderBackend::Hardware(Box::new(hw))
1014            }
1015        };
1016        *active_backend_impl = next_backend;
1017    }
1018
1019    /// Compiles `tree` into a `DisplayList`, executes the active render backend, and returns `FrameStats`.
1020    ///
1021    /// # Arguments
1022    ///
1023    /// - `&Self` - Mutable renderer.
1024    /// - `&SceneTree` - Laid-out scene tree.
1025    /// - `Size` - Logical viewport dimensions.
1026    /// - `f32` - Active DPI scale factor.
1027    /// - `Color` - Surface clear color.
1028    /// - `LayoutStats` - Telemetry from the layout pass.
1029    /// - `DamageRegion` - Damaged screen region.
1030    ///
1031    /// # Returns
1032    ///
1033    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
1034    pub fn render_frame(
1035        &mut self,
1036        tree: &SceneTree,
1037        viewport: Size,
1038        scale_factor: f32,
1039        clear_color: Color,
1040        layout_stats: LayoutStats,
1041        damage: DamageRegion,
1042    ) -> Result<FrameStats, PlatformError> {
1043        let params: FrameRenderParams = FrameRenderParams::new(viewport)
1044            .with_scale(scale_factor)
1045            .with_clear(clear_color)
1046            .with_layout_stats(layout_stats)
1047            .with_damage(damage);
1048        self.render_frame_composite_aware(tree, &params, false)
1049    }
1050
1051    /// Compiles `tree` into a `DisplayList`, honoring composite-only fast paths and non-degrading CPU reference fallback on unsupported GPU effects.
1052    ///
1053    /// # Arguments
1054    ///
1055    /// - `&Self` - Mutable renderer.
1056    /// - `&SceneTree` - Laid-out scene tree.
1057    /// - `&FrameRenderParams` - Viewport, DPI, clear color, layout stats, and damage bundle.
1058    /// - `bool` - Whether only composite/scroll properties changed with zero layout or paint mutations.
1059    ///
1060    /// # Returns
1061    ///
1062    /// - `Result<FrameStats, PlatformError>` - Frame performance, direct-draw, fallback, and pixel-hash telemetry.
1063    pub fn render_frame_composite_aware(
1064        &mut self,
1065        tree: &SceneTree,
1066        params: &FrameRenderParams,
1067        composite_only: bool,
1068    ) -> Result<FrameStats, PlatformError> {
1069        let viewport: Size = params.get_viewport();
1070        let scale: f32 = params.get_scale_factor().clamp(0.25, 16.0);
1071        let clear_color: Color = params.get_clear_color();
1072        let layout_stats: LayoutStats = params.get_layout_stats();
1073        let damage: DamageRegion = params.get_damage();
1074        let phys_w: u32 = if params.get_physical_width() > 0 {
1075            params.get_physical_width()
1076        } else {
1077            ((viewport.get_width() * scale).round() as u32).max(1)
1078        };
1079        let phys_h: u32 = if params.get_physical_height() > 0 {
1080            params.get_physical_height()
1081        } else {
1082            ((viewport.get_height() * scale).round() as u32).max(1)
1083        };
1084        let phys_dims: (u32, u32) = (phys_w, phys_h);
1085        let scale_bits: u32 = scale.to_bits();
1086        let Self {
1087            config,
1088            active_mode,
1089            active_backend,
1090            active_platform,
1091            active_backend_impl,
1092            fallback_software,
1093            font_service,
1094            surface_width,
1095            surface_height,
1096            paint_pass,
1097            paint_fragment_cache,
1098            display_list,
1099            frame_index,
1100            compute_pixel_hash,
1101            telemetry_enabled,
1102            last_hashed_mode,
1103            last_hashed_dims,
1104            last_stats,
1105            fallback_policy,
1106            composite_fast_path_frames,
1107            cpu_fallback_frames,
1108            adaptive_router,
1109            last_adaptive_metrics,
1110            execution_router,
1111            render_graph: _,
1112            last_scale_bits,
1113            direct_submission_scratch: _,
1114            direct_batch_tail_pool: _,
1115        } = self;
1116        *surface_width = phys_w;
1117        *surface_height = phys_h;
1118        if *last_scale_bits != scale_bits {
1119            let aa_mode: AntialiasingMode = config.get_antialiasing();
1120            let _: bool = font_service
1121                .get_mut_glyph_atlas()
1122                .invalidate_for_render_params(scale, aa_mode, 0);
1123            match active_backend_impl {
1124                ActiveRenderBackend::Software(sw) => {
1125                    let _: bool = sw
1126                        .get_mut_glyph_atlas()
1127                        .invalidate_for_render_params(scale, aa_mode, 0);
1128                }
1129                ActiveRenderBackend::Hybrid(hy) => {
1130                    let _: bool = hy
1131                        .get_mut_software()
1132                        .get_mut_glyph_atlas()
1133                        .invalidate_for_render_params(scale, aa_mode, 0);
1134                }
1135                ActiveRenderBackend::Hardware(hw) => {
1136                    let _: bool = hw
1137                        .get_mut_readback()
1138                        .get_mut_glyph_atlas()
1139                        .invalidate_for_render_params(scale, aa_mode, 0);
1140                }
1141            }
1142            if let Some(fb_sw) = fallback_software.as_mut() {
1143                let _: bool = fb_sw
1144                    .get_mut_glyph_atlas()
1145                    .invalidate_for_render_params(scale, aa_mode, 0);
1146            }
1147            *last_scale_bits = scale_bits;
1148        }
1149        let mode: RenderMode = *active_mode;
1150        let backend: GraphicsBackend = *active_backend;
1151        let do_pixel_hash: bool = *compute_pixel_hash;
1152        let hash_reusable: bool = *last_hashed_mode == Some(mode) && *last_hashed_dims == phys_dims;
1153        if !damage.get_full_damage() && damage.bounds_rect().is_none() && hash_reusable {
1154            *frame_index = frame_index.wrapping_add(1);
1155            let stats: FrameStats = FrameStats {
1156                frame_index: *frame_index,
1157                active_mode: mode,
1158                active_backend: backend,
1159                layout_nodes: layout_stats.get_nodes_computed(),
1160                layout_skipped: layout_stats.get_subtrees_skipped(),
1161                draw_commands: 0,
1162                draw_batches: 0,
1163                pixels_shaded: 0,
1164                frame_hash: last_stats.get_frame_hash(),
1165                composite_only: false,
1166                gpu_direct_draw: false,
1167                cpu_rgba_upload_bytes: 0,
1168                submit_outcome: FrameSubmitOutcome::SkippedNoDamage,
1169                wait_in_flight: false,
1170            };
1171            *last_stats = stats;
1172            let hz: f64 = adaptive_router.get_display_mode_hz();
1173            let mut skipped_metrics: AdaptiveFrameMetrics = AdaptiveFrameMetrics::with_context(
1174                ObservableMetric::Measured(hz),
1175                PresentTimingSource::Unobservable,
1176                adaptive_router.snapshot(),
1177            );
1178            skipped_metrics.set_present_outcome(SurfacePresentOutcome::SkippedUnchanged);
1179            skipped_metrics.set_upload_strategy(UploadStrategy::None);
1180            skipped_metrics.set_texture_upload_bytes(0);
1181            skipped_metrics.set_cpu_mirror_active(false);
1182            *last_adaptive_metrics = skipped_metrics;
1183            return Ok(stats);
1184        }
1185        let _: &PaintPass = paint_pass;
1186        let layout_changed: bool = layout_stats.get_nodes_computed() > 0;
1187        let took_composite_fast_path: bool = composite_only && !layout_changed;
1188        if took_composite_fast_path {
1189            *composite_fast_path_frames = composite_fast_path_frames.saturating_add(1);
1190        }
1191        let direct_scene_ok: bool = matches!(
1192            active_backend_impl,
1193            ActiveRenderBackend::Hardware(hw) if !hw.get_enable_readback()
1194        ) && active_platform.supports_direct_gpu_scene_pass(backend);
1195        display_list.set_direct_gpu_scene_enabled(direct_scene_ok);
1196        {
1197            let DisplayList { gpu_scene_pass, .. } = display_list;
1198            recycle_gpu_scene_pass(gpu_scene_pass.take());
1199        }
1200        PaintPass::build_retained(
1201            tree,
1202            viewport,
1203            scale,
1204            clear_color,
1205            layout_changed,
1206            display_list,
1207            paint_fragment_cache,
1208        );
1209        if *frame_index == 0 && tree.has_scroll_nodes() {
1210            display_list.prewarm_scroll_string_pool(24);
1211        }
1212        let cmd_count: usize = display_list.len();
1213        let mut gpu_direct_draw: bool = false;
1214        let cpu_mirror_active: bool;
1215        let upload_strategy: UploadStrategy;
1216        let cpu_rgba_upload_bytes: usize;
1217        let mut effective_mode: RenderMode = mode;
1218        let mut effective_backend: GraphicsBackend = backend;
1219        let (batches, pixels, hash): (usize, usize, u64) = match active_backend_impl {
1220            ActiveRenderBackend::Software(stroke_width) => {
1221                let (blue_val, point_val): (usize, usize) =
1222                    stroke_width.render(display_list, damage);
1223                cpu_mirror_active = true;
1224                upload_strategy = UploadStrategy::FullFrame;
1225                cpu_rgba_upload_bytes = (phys_w as usize)
1226                    .saturating_mul(phys_h as usize)
1227                    .saturating_mul(4);
1228                let height_val: u64 = if point_val == 0 && hash_reusable {
1229                    last_stats.get_frame_hash()
1230                } else if do_pixel_hash {
1231                    stroke_width.incremental_framebuffer_hash()
1232                } else {
1233                    display_list.fast_hash()
1234                };
1235                (blue_val, point_val, height_val)
1236            }
1237            ActiveRenderBackend::Hybrid(hy) => {
1238                let (byte_val, palette_val): (usize, usize) =
1239                    hy.render_with_physical_size(display_list, damage, Some(phys_dims))?;
1240                cpu_rgba_upload_bytes = hy.get_last_cpu_upload_bytes();
1241                let sparse_active: bool = hy.get_last_cpu_tile_count() > 0;
1242                cpu_mirror_active = sparse_active;
1243                upload_strategy = if sparse_active {
1244                    UploadStrategy::MultiRect
1245                } else {
1246                    UploadStrategy::DirectGpu
1247                };
1248                let span_height: u64 = if palette_val == 0 && hash_reusable {
1249                    last_stats.get_frame_hash()
1250                } else if do_pixel_hash && sparse_active {
1251                    hy.get_mut_software().incremental_framebuffer_hash()
1252                } else {
1253                    display_list.fast_hash()
1254                };
1255                (byte_val, palette_val, span_height)
1256            }
1257            ActiveRenderBackend::Hardware(hw) => {
1258                match hw.render_with_physical_size(display_list, damage, Some(phys_dims)) {
1259                    Ok((bounds_val, pixel_slice)) => {
1260                        if hw.get_has_unsupported_effect() {
1261                            let _: FallbackAction = fallback_policy.evaluate_trigger(
1262                                FallbackTrigger::MissingGpuEffectPath { isolatable: false },
1263                                0,
1264                            );
1265                            *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
1266                            let source_width: &mut SoftwareRenderer =
1267                                Self::ensure_fallback_software(
1268                                    fallback_software,
1269                                    font_service,
1270                                    (*config, phys_w, phys_h, *telemetry_enabled),
1271                                );
1272                            let (sb, sp): (usize, usize) =
1273                                source_width.render(display_list, damage);
1274                            effective_mode = RenderMode::Software;
1275                            effective_backend = GraphicsBackend::SoftwareCpu;
1276                            cpu_mirror_active = true;
1277                            upload_strategy = UploadStrategy::FullFrame;
1278                            cpu_rgba_upload_bytes = (phys_w as usize)
1279                                .saturating_mul(phys_h as usize)
1280                                .saturating_mul(4);
1281                            let half_extent: u64 = if do_pixel_hash {
1282                                source_width.incremental_framebuffer_hash()
1283                            } else {
1284                                display_list.fast_hash()
1285                            };
1286                            (sb, sp, half_extent)
1287                        } else {
1288                            gpu_direct_draw = !hw.get_enable_readback();
1289                            cpu_mirror_active = hw.get_enable_readback();
1290                            upload_strategy = if gpu_direct_draw {
1291                                UploadStrategy::DirectGpu
1292                            } else {
1293                                UploadStrategy::FullFrame
1294                            };
1295                            cpu_rgba_upload_bytes = hw.get_last_cpu_rgba_upload_bytes();
1296                            let height_val_primary: u64 = if pixel_slice == 0 && hash_reusable {
1297                                last_stats.get_frame_hash()
1298                            } else if hw.get_enable_readback() {
1299                                if do_pixel_hash {
1300                                    hw.get_mut_readback().incremental_framebuffer_hash()
1301                                } else {
1302                                    display_list.fast_hash()
1303                                }
1304                            } else {
1305                                hw.batch_hash()
1306                            };
1307                            (bounds_val, pixel_slice, height_val_primary)
1308                        }
1309                    }
1310                    Err(_) => {
1311                        let _: FallbackAction =
1312                            fallback_policy.evaluate_trigger(FallbackTrigger::DeviceLost, 0);
1313                        let _: AdaptiveDecision =
1314                            adaptive_router.handle_fault(FaultEventKind::DeviceLost, true, 0);
1315                        *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
1316                        let span_width: &mut SoftwareRenderer = Self::ensure_fallback_software(
1317                            fallback_software,
1318                            font_service,
1319                            (*config, phys_w, phys_h, *telemetry_enabled),
1320                        );
1321                        let (sb, sp): (usize, usize) = span_width.render(display_list, damage);
1322                        effective_mode = RenderMode::Software;
1323                        effective_backend = GraphicsBackend::SoftwareCpu;
1324                        cpu_mirror_active = true;
1325                        upload_strategy = UploadStrategy::FullFrame;
1326                        cpu_rgba_upload_bytes = (phys_w as usize)
1327                            .saturating_mul(phys_h as usize)
1328                            .saturating_mul(4);
1329                        let height_val_secondary: u64 = if do_pixel_hash {
1330                            span_width.incremental_framebuffer_hash()
1331                        } else {
1332                            display_list.fast_hash()
1333                        };
1334                        (sb, sp, height_val_secondary)
1335                    }
1336                }
1337            }
1338        };
1339        *last_hashed_mode = Some(effective_mode);
1340        *last_hashed_dims = phys_dims;
1341        *frame_index = frame_index.wrapping_add(1);
1342        let stats: FrameStats = FrameStats {
1343            frame_index: *frame_index,
1344            active_mode: effective_mode,
1345            active_backend: effective_backend,
1346            layout_nodes: layout_stats.get_nodes_computed(),
1347            layout_skipped: layout_stats.get_subtrees_skipped(),
1348            draw_commands: cmd_count,
1349            draw_batches: batches,
1350            pixels_shaded: pixels,
1351            frame_hash: hash,
1352            composite_only: took_composite_fast_path,
1353            gpu_direct_draw,
1354            cpu_rgba_upload_bytes,
1355            submit_outcome: FrameSubmitOutcome::Submitted,
1356            wait_in_flight: false,
1357        };
1358        *last_stats = stats;
1359        let hz: f64 = adaptive_router.get_display_mode_hz();
1360        let mut frame_metrics: AdaptiveFrameMetrics = AdaptiveFrameMetrics::with_context(
1361            ObservableMetric::Measured(hz),
1362            PresentTimingSource::SubmissionProxy,
1363            adaptive_router.snapshot(),
1364        );
1365        frame_metrics.set_frame_callback_count(*frame_index);
1366        frame_metrics.set_present_outcome(SurfacePresentOutcome::Submitted);
1367        frame_metrics.set_cpu_mirror_active(cpu_mirror_active);
1368        frame_metrics.set_texture_upload_bytes(cpu_rgba_upload_bytes as u64);
1369        frame_metrics.set_upload_strategy(upload_strategy);
1370        *last_adaptive_metrics = frame_metrics;
1371        let exec_workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures {
1372            dirty_nodes: layout_stats.get_nodes_computed(),
1373            visible_nodes: cmd_count,
1374            tree_depth: 4,
1375            gpu_eligible_nodes: if gpu_direct_draw { cmd_count } else { 0 },
1376            cpu_chrome_nodes: if gpu_direct_draw { 0 } else { cmd_count },
1377            dirty_upload_bytes: cmd_count.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES),
1378            wrapping_text_ratio: 0.0,
1379            worker_threads: 1,
1380            gpu_compute_available: gpu_direct_draw,
1381            thermal_throttled: false,
1382        };
1383        let _: ExecutionRouterDecision = execution_router.evaluate(exec_workload, *frame_index);
1384        execution_router.observe_frame(
1385            0.0,
1386            last_gpu_compute_ns(),
1387            last_gpu_render_ns(),
1388            exec_workload,
1389            false,
1390            *frame_index,
1391        );
1392        Ok(stats)
1393    }
1394
1395    /// Executes `callback` with a borrowed `GpuFrameSubmission` built via O(1) pointer swaps, eliminating per-frame `GpuBatch`, `DirectGpuScenePass`, and multi-MB atlas `Vec<u8>` clones while restoring all buffers intact immediately after presentation.
1396    ///
1397    /// # Arguments
1398    ///
1399    /// - `&Self` - Mutable renderer reference.
1400    /// - `Color` - Surface clear color for the active frame.
1401    /// - `F` - Synchronous presentation closure borrowing `&GpuFrameSubmission`.
1402    ///
1403    /// # Returns
1404    ///
1405    /// - `Option<R>` - Presentation callback result when hardware or hybrid batches are ready.
1406    pub fn with_direct_gpu_submission<R, F>(&mut self, clear_color: Color, callback: F) -> Option<R>
1407    where
1408        F: FnOnce(&GpuFrameSubmission) -> R,
1409    {
1410        let width: u32 = self.get_surface_width().max(1);
1411        let height: u32 = self.get_surface_height().max(1);
1412        let scale_factor: f32 = self.get_display_list().get_scale_factor().clamp(0.25, 16.0);
1413        let Self {
1414            active_backend_impl,
1415            display_list,
1416            direct_submission_scratch,
1417            direct_batch_tail_pool,
1418            ..
1419        } = self;
1420        let DisplayList { gpu_scene_pass, .. } = display_list;
1421        match active_backend_impl {
1422            ActiveRenderBackend::Hardware(hw) => {
1423                let active_len: usize = hw.get_active_batches().min(hw.get_batches().len());
1424                direct_batch_tail_pool.clear();
1425                direct_batch_tail_pool.extend(hw.get_mut_batches().drain(active_len..));
1426                swap(&mut direct_submission_scratch.batches, hw.get_mut_batches());
1427                swap(
1428                    &mut direct_submission_scratch.blur_passes,
1429                    hw.get_mut_blur_passes(),
1430                );
1431                direct_submission_scratch.width = width;
1432                direct_submission_scratch.height = height;
1433                direct_submission_scratch.scale_factor = scale_factor;
1434                direct_submission_scratch.clear_color = clear_color;
1435                direct_submission_scratch.external_texture_handle =
1436                    hw.get_driver().get_external_texture_handle();
1437                direct_submission_scratch.gpu_scene_pass = gpu_scene_pass.take();
1438                let mut dirty_rects: Vec<PixelDirtyRect> =
1439                    hw.get_mut_gpu_glyph_atlas().take_submission_dirty_rects();
1440                dirty_rects
1441                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
1442                if !dirty_rects.is_empty() {
1443                    let atlas: &mut IncrementalGpuGlyphAtlas = hw.get_mut_gpu_glyph_atlas();
1444                    let atlas_w: u32 = atlas.get_width();
1445                    let atlas_h: u32 = atlas.get_height();
1446                    let atlas_rev: u64 = atlas.get_synced_revision();
1447                    let moved_pixels: Vec<u8> = take(atlas.get_mut_pixels());
1448                    direct_submission_scratch.set_glyph_atlas_payload(
1449                        Some(DirectGpuAtlasUpload {
1450                            width: atlas_w,
1451                            height: atlas_h,
1452                            revision: atlas_rev,
1453                            pixels: moved_pixels,
1454                        }),
1455                        dirty_rects,
1456                    );
1457                } else {
1458                    direct_submission_scratch.set_glyph_atlas_payload(None, Vec::new());
1459                }
1460                let mut img_dirty_rects: Vec<PixelDirtyRect> =
1461                    hw.get_mut_gpu_image_atlas().take_submission_dirty_rects();
1462                img_dirty_rects
1463                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
1464                if !img_dirty_rects.is_empty() {
1465                    let img_atlas: &mut IncrementalGpuImageAtlas = hw.get_mut_gpu_image_atlas();
1466                    let img_w: u32 = img_atlas.get_width();
1467                    let img_h: u32 = img_atlas.get_height();
1468                    let img_rev: u64 = img_atlas.get_revision();
1469                    let moved_pixels: Vec<u8> = take(img_atlas.get_mut_pixels());
1470                    direct_submission_scratch.set_image_atlas_payload(
1471                        Some(DirectGpuAtlasUpload {
1472                            width: img_w,
1473                            height: img_h,
1474                            revision: img_rev,
1475                            pixels: moved_pixels,
1476                        }),
1477                        img_dirty_rects,
1478                    );
1479                } else {
1480                    direct_submission_scratch.set_image_atlas_payload(None, Vec::new());
1481                }
1482                let outcome: R = callback(direct_submission_scratch);
1483                if let Some(upload) = direct_submission_scratch.glyph_atlas_r8.take() {
1484                    hw.get_mut_gpu_glyph_atlas().set_pixels(upload.pixels);
1485                }
1486                direct_submission_scratch.glyph_dirty_rects.clear();
1487                if let Some(upload) = direct_submission_scratch.image_atlas_rgba8.take() {
1488                    hw.get_mut_gpu_image_atlas().set_pixels(upload.pixels);
1489                }
1490                direct_submission_scratch.image_dirty_rects.clear();
1491                *gpu_scene_pass = direct_submission_scratch.gpu_scene_pass.take();
1492                swap(
1493                    &mut direct_submission_scratch.blur_passes,
1494                    hw.get_mut_blur_passes(),
1495                );
1496                swap(&mut direct_submission_scratch.batches, hw.get_mut_batches());
1497                hw.get_mut_batches().append(direct_batch_tail_pool);
1498                Some(outcome)
1499            }
1500            ActiveRenderBackend::Hybrid(hy) => {
1501                swap(
1502                    &mut direct_submission_scratch.batches,
1503                    hy.get_mut_last_batches(),
1504                );
1505                direct_submission_scratch.blur_passes.clear();
1506                direct_submission_scratch.width = width;
1507                direct_submission_scratch.height = height;
1508                direct_submission_scratch.scale_factor = scale_factor;
1509                direct_submission_scratch.clear_color = clear_color;
1510                direct_submission_scratch.external_texture_handle =
1511                    hy.get_driver().get_external_texture_handle();
1512                direct_submission_scratch.gpu_scene_pass = gpu_scene_pass.take();
1513                let mut dirty_rects: Vec<PixelDirtyRect> =
1514                    hy.get_mut_gpu_glyph_atlas().take_submission_dirty_rects();
1515                dirty_rects
1516                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
1517                if !dirty_rects.is_empty() {
1518                    let atlas: &mut IncrementalGpuGlyphAtlas = hy.get_mut_gpu_glyph_atlas();
1519                    let atlas_w: u32 = atlas.get_width();
1520                    let atlas_h: u32 = atlas.get_height();
1521                    let atlas_rev: u64 = atlas.get_synced_revision();
1522                    let moved_pixels: Vec<u8> = take(atlas.get_mut_pixels());
1523                    direct_submission_scratch.set_glyph_atlas_payload(
1524                        Some(DirectGpuAtlasUpload {
1525                            width: atlas_w,
1526                            height: atlas_h,
1527                            revision: atlas_rev,
1528                            pixels: moved_pixels,
1529                        }),
1530                        dirty_rects,
1531                    );
1532                } else {
1533                    direct_submission_scratch.set_glyph_atlas_payload(None, Vec::new());
1534                }
1535                direct_submission_scratch.set_image_atlas_payload(None, Vec::new());
1536                let outcome: R = callback(direct_submission_scratch);
1537                if let Some(upload) = direct_submission_scratch.glyph_atlas_r8.take() {
1538                    hy.get_mut_gpu_glyph_atlas().set_pixels(upload.pixels);
1539                }
1540                direct_submission_scratch.glyph_dirty_rects.clear();
1541                *gpu_scene_pass = direct_submission_scratch.gpu_scene_pass.take();
1542                swap(
1543                    &mut direct_submission_scratch.batches,
1544                    hy.get_mut_last_batches(),
1545                );
1546                Some(outcome)
1547            }
1548            ActiveRenderBackend::Software(_) => None,
1549        }
1550    }
1551
1552    /// Builds a direct-GPU `GpuFrameSubmission` payload from the active `HardwareRenderer` or `HybridRenderer` for `PlatformBackend::present_gpu_frame`.
1553    ///
1554    /// # Arguments
1555    ///
1556    /// - `&Self` - Mutable renderer reference.
1557    /// - `Color` - Surface clear color for the active frame.
1558    ///
1559    /// # Returns
1560    ///
1561    /// - `Option<GpuFrameSubmission>` - Direct-GPU frame submission when hardware or hybrid batches are ready.
1562    #[must_use]
1563    pub fn build_direct_gpu_submission(
1564        &mut self,
1565        clear_color: Color,
1566    ) -> Option<GpuFrameSubmission> {
1567        let width: u32 = self.get_surface_width().max(1);
1568        let height: u32 = self.get_surface_height().max(1);
1569        let scale_factor: f32 = self.get_display_list().get_scale_factor().clamp(0.25, 16.0);
1570        let gpu_scene_pass: Option<DirectGpuScenePass> =
1571            self.get_display_list().gpu_scene_pass_clone();
1572        let Self {
1573            active_backend_impl,
1574            ..
1575        } = self;
1576        match active_backend_impl {
1577            ActiveRenderBackend::Hardware(hw) => {
1578                let batches: Vec<GpuBatch> = hw.active_batches_slice().to_vec();
1579                let blur_passes: Vec<GpuBackdropBlurPass> = hw.get_blur_passes().clone();
1580                let external_tex: usize = hw.get_driver().get_external_texture_handle();
1581                let mut submission: GpuFrameSubmission = GpuFrameSubmission {
1582                    width,
1583                    height,
1584                    scale_factor,
1585                    clear_color,
1586                    batches,
1587                    blur_passes,
1588                    external_texture_handle: external_tex,
1589                    gpu_scene_pass,
1590                    glyph_atlas_r8: None,
1591                    glyph_dirty_rects: Vec::new(),
1592                    image_atlas_rgba8: None,
1593                    image_dirty_rects: Vec::new(),
1594                };
1595                let mut dirty_rects: Vec<PixelDirtyRect> =
1596                    hw.get_mut_gpu_glyph_atlas().take_submission_dirty_rects();
1597                dirty_rects
1598                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
1599                if !dirty_rects.is_empty() {
1600                    let atlas: &IncrementalGpuGlyphAtlas = hw.get_gpu_glyph_atlas();
1601                    submission.set_glyph_atlas_payload(
1602                        Some(DirectGpuAtlasUpload {
1603                            width: atlas.get_width(),
1604                            height: atlas.get_height(),
1605                            revision: atlas.get_synced_revision(),
1606                            pixels: atlas.get_pixels().clone(),
1607                        }),
1608                        dirty_rects,
1609                    );
1610                }
1611                let mut img_dirty_rects: Vec<PixelDirtyRect> =
1612                    hw.get_mut_gpu_image_atlas().take_submission_dirty_rects();
1613                img_dirty_rects
1614                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
1615                if !img_dirty_rects.is_empty() {
1616                    let img_atlas: &IncrementalGpuImageAtlas = hw.get_gpu_image_atlas();
1617                    submission.set_image_atlas_payload(
1618                        Some(DirectGpuAtlasUpload {
1619                            width: img_atlas.get_width(),
1620                            height: img_atlas.get_height(),
1621                            revision: img_atlas.get_revision(),
1622                            pixels: img_atlas.get_pixels().clone(),
1623                        }),
1624                        img_dirty_rects,
1625                    );
1626                }
1627                Some(submission)
1628            }
1629            ActiveRenderBackend::Hybrid(hy) => {
1630                let batches: Vec<GpuBatch> = hy.get_last_batches().clone();
1631                let external_tex: usize = hy.get_driver().get_external_texture_handle();
1632                let mut submission: GpuFrameSubmission = GpuFrameSubmission {
1633                    width,
1634                    height,
1635                    scale_factor,
1636                    clear_color,
1637                    batches,
1638                    blur_passes: Vec::new(),
1639                    external_texture_handle: external_tex,
1640                    gpu_scene_pass,
1641                    glyph_atlas_r8: None,
1642                    glyph_dirty_rects: Vec::new(),
1643                    image_atlas_rgba8: None,
1644                    image_dirty_rects: Vec::new(),
1645                };
1646                let mut dirty_rects: Vec<PixelDirtyRect> =
1647                    hy.get_mut_gpu_glyph_atlas().take_submission_dirty_rects();
1648                dirty_rects
1649                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
1650                if !dirty_rects.is_empty() {
1651                    let atlas: &IncrementalGpuGlyphAtlas = hy.get_gpu_glyph_atlas();
1652                    submission.set_glyph_atlas_payload(
1653                        Some(DirectGpuAtlasUpload {
1654                            width: atlas.get_width(),
1655                            height: atlas.get_height(),
1656                            revision: atlas.get_synced_revision(),
1657                            pixels: atlas.get_pixels().clone(),
1658                        }),
1659                        dirty_rects,
1660                    );
1661                }
1662                Some(submission)
1663            }
1664            ActiveRenderBackend::Software(_) => None,
1665        }
1666    }
1667
1668    /// Handles a GPU presentation `DeviceLost` or `SurfaceError` by invoking `FallbackPolicyEngine`, `AdaptiveExecutionRouter` fault failover, and rendering a non-degrading CPU software fallback framebuffer.
1669    ///
1670    /// # Arguments
1671    ///
1672    /// - `&Self` - Mutable renderer reference.
1673    /// - `DamageRegion` - Frame damage region for software fallback recovery.
1674    ///
1675    /// # Returns
1676    ///
1677    /// - `bool` - `true` when the CPU software fallback framebuffer is ready for immediate presentation.
1678    pub fn recover_gpu_present_fault(&mut self, damage: DamageRegion) -> bool {
1679        let phys_w: u32 = self.get_surface_width().max(1);
1680        let phys_h: u32 = self.get_surface_height().max(1);
1681        let Self {
1682            config,
1683            fallback_software,
1684            font_service,
1685            display_list,
1686            telemetry_enabled,
1687            fallback_policy,
1688            cpu_fallback_frames,
1689            adaptive_router,
1690            execution_router,
1691            frame_index,
1692            last_stats,
1693            ..
1694        } = self;
1695        let _: FallbackAction = fallback_policy.evaluate_trigger(FallbackTrigger::DeviceLost, 0);
1696        let _: AdaptiveDecision = adaptive_router.handle_fault(FaultEventKind::DeviceLost, true, 0);
1697        let _: ExecutionLane = execution_router.trigger_gpu_fault_failover(1, *frame_index);
1698        *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
1699        let sw: &mut SoftwareRenderer = Self::ensure_fallback_software(
1700            fallback_software,
1701            font_service,
1702            (*config, phys_w, phys_h, *telemetry_enabled),
1703        );
1704        let _: (usize, usize) = sw.render(display_list, damage);
1705        last_stats.set_active_mode(RenderMode::Software);
1706        last_stats.set_gpu_direct_draw(false);
1707        true
1708    }
1709
1710    /// Renders `tree` using a compact `FrameRenderParams` descriptor and returns `FrameStats`.
1711    ///
1712    /// # Arguments
1713    ///
1714    /// - `&Self` - Mutable renderer.
1715    /// - `&SceneTree` - Laid-out scene tree.
1716    /// - `&FrameRenderParams` - Viewport, DPI, clear color, layout stats, and damage bundle.
1717    ///
1718    /// # Returns
1719    ///
1720    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
1721    #[inline(always)]
1722    pub fn render_with(
1723        &mut self,
1724        tree: &SceneTree,
1725        params: &FrameRenderParams,
1726    ) -> Result<FrameStats, PlatformError> {
1727        self.render_frame(
1728            tree,
1729            params.get_viewport(),
1730            params.get_scale_factor(),
1731            params.get_clear_color(),
1732            params.get_layout_stats(),
1733            params.get_damage(),
1734        )
1735    }
1736
1737    /// Advances the frame counter for an undamaged idle frame without rasterizing or hashing pixels and drops worker spin to `0`.
1738    ///
1739    /// # Arguments
1740    ///
1741    /// - `&Self` - Mutable renderer.
1742    ///
1743    /// # Returns
1744    ///
1745    /// - `FrameStats` - Lightweight telemetry preserving the last rendered `frame_hash` with zero shaded pixels.
1746    pub fn record_skipped_frame(&mut self) -> FrameStats {
1747        self.set_high_frequency_active(false);
1748        let next_idx: u64 = self.get_frame_index().wrapping_add(1);
1749        self.set_frame_index(next_idx);
1750        let mut stats: FrameStats = self.get_last_stats();
1751        stats.set_frame_index(next_idx);
1752        stats.set_layout_nodes(0);
1753        stats.set_draw_commands(0);
1754        stats.set_draw_batches(0);
1755        stats.set_pixels_shaded(0);
1756        stats.set_composite_only(false);
1757        stats.set_gpu_direct_draw(false);
1758        stats.set_cpu_rgba_upload_bytes(0);
1759        stats.record_present_outcome(PresentOutcome::SkippedNoDamage);
1760        self.set_last_stats(stats);
1761        stats
1762    }
1763
1764    /// Returns cumulative cross-frame `PaintFragmentCache` telemetry `(whole_list_hits, fragment_hits, fragment_misses, fragment_evictions)`.
1765    ///
1766    /// # Arguments
1767    ///
1768    /// - `&Self` - Renderer reference.
1769    ///
1770    /// # Returns
1771    ///
1772    /// - `(u64, u64, u64, u64)` - Tuple of whole-list hits, fragment hits, misses, and evictions.
1773    #[must_use]
1774    pub fn paint_fragment_cache_stats(&self) -> (u64, u64, u64, u64) {
1775        self.get_paint_fragment_cache().stats()
1776    }
1777
1778    /// 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).
1779    ///
1780    /// # Arguments
1781    ///
1782    /// - `&Self` - Renderer reference.
1783    ///
1784    /// # Returns
1785    ///
1786    /// - `Option<&Framebuffer>` - Active RGBA8 framebuffer if resident in host memory.
1787    #[must_use]
1788    pub fn framebuffer(&self) -> Option<&Framebuffer> {
1789        let Self {
1790            active_backend_impl,
1791            fallback_software,
1792            last_stats,
1793            ..
1794        } = self;
1795        match active_backend_impl {
1796            ActiveRenderBackend::Software(stroke_width) => stroke_width.framebuffer_opt(),
1797            ActiveRenderBackend::Hybrid(hy) => hy.get_software().framebuffer_opt(),
1798            ActiveRenderBackend::Hardware(hw) => {
1799                if last_stats.get_active_mode() == RenderMode::Software {
1800                    fallback_software
1801                        .as_deref()
1802                        .and_then(SoftwareRenderer::framebuffer_opt)
1803                } else if hw.get_enable_readback() {
1804                    hw.get_readback().framebuffer_opt()
1805                } else {
1806                    None
1807                }
1808            }
1809        }
1810    }
1811}