Skip to main content

euv_core/render/gpu/
impl.rs

1use super::*;
2
3/// Default `NativeGpuDriver` targets headless recording fallback.
4impl Default for NativeGpuDriver {
5    /// Creates a headless `NativeGpuDriver`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Headless GPU driver.
10    fn default() -> Self {
11        Self::probe(GraphicsBackend::Headless)
12    }
13}
14
15/// Construction, surface attachment, texture dirty-rect upload, and pipeline query helpers for `NativeGpuDriver`.
16impl NativeGpuDriver {
17    /// Probes the active OS GPU hardware, loads or compiles cached native pipelines, and returns a live `NativeGpuDriver`.
18    ///
19    /// # Arguments
20    ///
21    /// - `GraphicsBackend` - Requested graphics backend.
22    ///
23    /// # Returns
24    ///
25    /// - `Self` - Initialized native GPU driver with automatic headless fallback.
26    #[must_use]
27    pub fn probe(backend: GraphicsBackend) -> Self {
28        let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
29        let mut fallback: RecordingGpuDriver = RecordingGpuDriver::default();
30        fallback.set_backend_kind(backend);
31        Self {
32            adapter: probed.adapter,
33            device_handle: probed.device_handle,
34            queue_handle: probed.queue_handle,
35            library_handle: probed.library_handle,
36            pipeline_handle: probed.pipeline_handle,
37            blur_pipeline_handle: probed.blur_pipeline_handle,
38            surface_layer_handle: 0,
39            glyph_r8_texture_handle: probed.dummy_r8_tex,
40            glyph_rgba8_texture_handle: probed.dummy_rgba8_tex,
41            image_texture_handle: retain_native_gpu_object(probed.dummy_rgba8_tex),
42            external_texture_handle: 0,
43            ring_slots: [NativeGpuRingSlot::default(); GPU_DRIVER_RING_SLOTS],
44            ring_cursor: 0,
45            staging_buffer_handle: 0,
46            staging_contents_ptr: 0,
47            staging_buffer_capacity: 0,
48            submitted_frames: 0,
49            uploaded_instances: 0,
50            uploaded_bytes: 0,
51            last_upload_bytes: 0,
52            last_submitted_batches: 0,
53            staging_reallocations: 0,
54            last_presented_time_ns: 0,
55            last_gpu_exec_ns: 0,
56            #[cfg(any(target_os = "macos", target_os = "ios"))]
57            scratch_primitives: Vec::new(),
58            fallback,
59        }
60    }
61
62    /// Re-initializes the GPU driver for `backend`, releasing any previously retained OS handles.
63    ///
64    /// # Arguments
65    ///
66    /// - `GraphicsBackend` - Target graphics backend.
67    pub fn switch_backend(&mut self, backend: GraphicsBackend) {
68        if self.get_adapter().get_backend() == backend {
69            return;
70        }
71        *self = Self::probe(backend);
72    }
73
74    /// Attaches a native `CAMetalLayer*` (or equivalent surface layer) for zero-readback hardware presentation.
75    ///
76    /// # Arguments
77    ///
78    /// - `usize` - Native `CAMetalLayer*` pointer (`0` detaches).
79    pub fn attach_metal_layer(&mut self, layer_handle: usize) {
80        let dev: usize = self.get_device_handle();
81        let Self {
82            surface_layer_handle,
83            ..
84        } = self;
85        *surface_layer_handle = layer_handle;
86        if dev != 0 && layer_handle != 0 {
87            configure_native_metal_layer(dev, layer_handle);
88        }
89    }
90
91    /// Binds an external shared-device GPU texture handle (3D game render target or hardware video surface).
92    ///
93    /// # Arguments
94    ///
95    /// - `usize` - Native external texture handle (`0` restores fallback dummy texture).
96    pub fn set_external_texture(&mut self, texture_handle: usize) {
97        let Self {
98            external_texture_handle,
99            ..
100        } = self;
101        *external_texture_handle = texture_handle;
102    }
103
104    /// Uploads a dirty R8 or RGBA8 sub-rectangle to the resident glyph atlas or image texture on GPU.
105    ///
106    /// # Arguments
107    ///
108    /// - `GpuAtlasPixelFormat` - Target texture pixel format (`R8Unorm` or `Rgba8Unorm`).
109    /// - `u8` - Texture slot (`0` = R8 glyph atlas, `1` = RGBA8 color glyph atlas, `2` = UI image texture).
110    /// - `(u32, u32)` - Full backing texture dimensions `(width, height)`.
111    /// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
112    /// - `&[u8]` - Source pixel bytes.
113    /// - `usize` - Row stride in bytes.
114    ///
115    /// # Returns
116    ///
117    /// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly to hardware GPU memory.
118    pub fn upload_texture_dirty_rect(
119        &mut self,
120        format: GpuAtlasPixelFormat,
121        texture_slot: u8,
122        tex_dims: (u32, u32),
123        dirty_rect: (u32, u32, u32, u32),
124        bytes: &[u8],
125        bytes_per_row: usize,
126    ) -> bool {
127        let dev: usize = self.get_device_handle();
128        let Self {
129            glyph_r8_texture_handle,
130            glyph_rgba8_texture_handle,
131            image_texture_handle,
132            ..
133        } = self;
134        let target: &mut usize = match texture_slot {
135            0 => glyph_r8_texture_handle,
136            1 => glyph_rgba8_texture_handle,
137            _ => image_texture_handle,
138        };
139        upload_native_texture_dirty_rect(
140            dev,
141            target,
142            format,
143            tex_dims,
144            dirty_rect,
145            bytes,
146            bytes_per_row,
147        )
148    }
149
150    /// Returns `true` when the driver has both a live compiled GPU blur pipeline and an attached presentation surface.
151    ///
152    /// # Returns
153    ///
154    /// - `bool` - `true` when `BackdropBlur` can execute natively on GPU without CPU fallback.
155    #[must_use]
156    pub fn supports_backdrop_blur_pass(&self) -> bool {
157        self.get_blur_pipeline_handle() != 0 && self.get_surface_layer_handle() != 0
158    }
159}
160
161/// `GpuDriver` implementation uploading packed 64-byte `GpuPrimitiveInstance` streams to the active physical OS GPU.
162impl GpuDriver for NativeGpuDriver {
163    /// Returns the resolved `GraphicsBackend`.
164    ///
165    /// # Returns
166    ///
167    /// - `GraphicsBackend` - Active backend tag.
168    fn backend(&self) -> GraphicsBackend {
169        self.get_adapter().get_backend()
170    }
171
172    /// Returns the native shader source compiled by this GPU backend.
173    ///
174    /// # Returns
175    ///
176    /// - `&'static str` - Native shader program source.
177    fn shader_source(&self) -> &'static str {
178        self.get_fallback().shader_source()
179    }
180
181    /// Uploads instanced 64-byte primitive batches through the 3-slot fenced ring and records draw telemetry.
182    ///
183    /// # Arguments
184    ///
185    /// - `u32` - Surface width.
186    /// - `u32` - Surface height.
187    /// - `Color` - Surface clear color.
188    /// - `&[GpuBatch]` - Ordered draw batches.
189    ///
190    /// # Returns
191    ///
192    /// - `Result<usize, PlatformError>` - Number of submitted GPU draw calls.
193    fn submit_batches(
194        &mut self,
195        width: u32,
196        height: u32,
197        clear_color: Color,
198        batches: &[GpuBatch],
199    ) -> Result<usize, PlatformError> {
200        let uploaded: usize =
201            submit_native_gpu_ring_frame(self, width, height, clear_color, batches);
202        let frame_bytes: usize = uploaded.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
203        let Self {
204            submitted_frames,
205            uploaded_instances,
206            uploaded_bytes,
207            last_upload_bytes,
208            last_submitted_batches,
209            last_presented_time_ns,
210            last_gpu_exec_ns,
211            fallback,
212            ..
213        } = self;
214        *submitted_frames = submitted_frames.wrapping_add(1);
215        *uploaded_instances = uploaded_instances.wrapping_add(uploaded as u64);
216        *uploaded_bytes = uploaded_bytes.wrapping_add(frame_bytes as u64);
217        *last_upload_bytes = frame_bytes;
218        *last_submitted_batches = batches.len();
219        *last_presented_time_ns = native_gpu_last_presented_ns();
220        *last_gpu_exec_ns = native_gpu_last_exec_ns();
221        fallback.submit_batches(width, height, clear_color, batches)
222    }
223}
224
225/// Automatic native GPU handle cleanup when `NativeGpuDriver` is dropped.
226impl Drop for NativeGpuDriver {
227    /// Releases retained OS GPU ring buffers, in-flight command buffers, textures, pipelines, and device handles.
228    fn drop(&mut self) {
229        let Self {
230            device_handle,
231            queue_handle,
232            library_handle,
233            pipeline_handle,
234            blur_pipeline_handle,
235            glyph_r8_texture_handle,
236            glyph_rgba8_texture_handle,
237            image_texture_handle,
238            ring_slots,
239            staging_buffer_handle,
240            staging_contents_ptr,
241            staging_buffer_capacity,
242            ..
243        } = self;
244        for slot in ring_slots.iter_mut() {
245            let cmd: usize = slot.get_in_flight_cmd_buffer();
246            if cmd != 0 {
247                release_native_gpu_object(cmd);
248                slot.set_in_flight_cmd_buffer(0);
249            }
250            let buf: usize = slot.get_buffer_handle();
251            if buf != 0 {
252                release_native_gpu_object(buf);
253                slot.set_buffer_handle(0);
254                slot.set_contents_ptr(0);
255                slot.set_capacity_bytes(0);
256            }
257        }
258        *staging_buffer_handle = 0;
259        *staging_contents_ptr = 0;
260        *staging_buffer_capacity = 0;
261        release_native_gpu_object(*glyph_r8_texture_handle);
262        release_native_gpu_object(*glyph_rgba8_texture_handle);
263        release_native_gpu_object(*image_texture_handle);
264        release_native_gpu_object(*blur_pipeline_handle);
265        release_native_gpu_object(*pipeline_handle);
266        release_native_gpu_handles(*device_handle, *queue_handle, *library_handle);
267    }
268}
269
270/// Geometry and byte-size helpers for `PixelDirtyRect`.
271impl PixelDirtyRect {
272    /// Returns the exclusive right pixel edge (`x + width`).
273    ///
274    /// # Returns
275    ///
276    /// - `u32` - Exclusive right coordinate in pixels.
277    #[must_use]
278    pub fn right(&self) -> u32 {
279        self.get_x().saturating_add(self.get_width())
280    }
281
282    /// Returns the exclusive bottom pixel edge (`y + height`).
283    ///
284    /// # Returns
285    ///
286    /// - `u32` - Exclusive bottom coordinate in pixels.
287    #[must_use]
288    pub fn bottom(&self) -> u32 {
289        self.get_y().saturating_add(self.get_height())
290    }
291
292    /// Returns `true` when either width or height is zero.
293    ///
294    /// # Returns
295    ///
296    /// - `bool` - `true` when the rectangle covers zero pixels.
297    #[must_use]
298    pub fn is_empty(&self) -> bool {
299        self.get_width() == 0 || self.get_height() == 0
300    }
301
302    /// Returns the covered pixel count (`width * height`).
303    ///
304    /// # Returns
305    ///
306    /// - `usize` - Total covered pixels.
307    #[must_use]
308    pub fn area_pixels(&self) -> usize {
309        (self.get_width() as usize).saturating_mul(self.get_height() as usize)
310    }
311
312    /// Returns the RGBA8 byte payload size (`width * height * 4`).
313    ///
314    /// # Returns
315    ///
316    /// - `usize` - Payload size in bytes.
317    #[must_use]
318    pub fn byte_size_rgba8(&self) -> usize {
319        self.area_pixels().saturating_mul(4)
320    }
321
322    /// Clamps this rectangle strictly inside `(fb_w, fb_h)` surface bounds.
323    ///
324    /// # Arguments
325    ///
326    /// - `u32` - Surface width in pixels.
327    /// - `u32` - Surface height in pixels.
328    ///
329    /// # Returns
330    ///
331    /// - `Option<Self>` - Clamped non-empty rectangle, or `None` when outside bounds.
332    #[must_use]
333    pub fn clamp_to(&self, fb_w: u32, fb_h: u32) -> Option<Self> {
334        let x0: u32 = self.get_x().min(fb_w);
335        let y0: u32 = self.get_y().min(fb_h);
336        let x1: u32 = self.right().min(fb_w);
337        let y1: u32 = self.bottom().min(fb_h);
338        let w: u32 = x1.saturating_sub(x0);
339        let h: u32 = y1.saturating_sub(y0);
340        if w == 0 || h == 0 {
341            None
342        } else {
343            Some(Self::new(x0, y0, w, h))
344        }
345    }
346
347    /// Returns the smallest enclosing bounding rectangle containing both `self` and `other`.
348    ///
349    /// # Arguments
350    ///
351    /// - `Self` - Other pixel rectangle.
352    ///
353    /// # Returns
354    ///
355    /// - `Self` - Enclosing union rectangle.
356    #[must_use]
357    pub fn union_with(&self, other: Self) -> Self {
358        if self.is_empty() {
359            return other;
360        }
361        if other.is_empty() {
362            return *self;
363        }
364        let x0: u32 = self.get_x().min(other.get_x());
365        let y0: u32 = self.get_y().min(other.get_y());
366        let x1: u32 = self.right().max(other.right());
367        let y1: u32 = self.bottom().max(other.bottom());
368        Self::new(x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
369    }
370
371    /// Returns `true` when `self` and `other` overlap or lie within `pad_px` pixels of each other.
372    ///
373    /// # Arguments
374    ///
375    /// - `Self` - Other pixel rectangle.
376    /// - `u32` - Adjacency tolerance in pixels.
377    ///
378    /// # Returns
379    ///
380    /// - `bool` - `true` when the two rectangles overlap or are adjacent within `pad_px`.
381    #[must_use]
382    pub fn intersects_or_adjacent(&self, other: Self, pad_px: u32) -> bool {
383        if self.is_empty() || other.is_empty() {
384            return false;
385        }
386        let ax0: u32 = self.get_x().saturating_sub(pad_px);
387        let ay0: u32 = self.get_y().saturating_sub(pad_px);
388        let ax1: u32 = self.right().saturating_add(pad_px);
389        let ay1: u32 = self.bottom().saturating_add(pad_px);
390        ax0 <= other.right()
391            && ax1 >= other.get_x()
392            && ay0 <= other.bottom()
393            && ay1 >= other.get_y()
394    }
395}
396
397/// Zero-copy borrowed atlas accessors for `DirectGpuFrameBatch`.
398impl DirectGpuFrameBatch {
399    /// Returns a borrowed reference to the optional R8 monochrome glyph atlas upload without cloning.
400    ///
401    /// # Returns
402    ///
403    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed R8 glyph atlas upload when present.
404    #[must_use]
405    pub fn glyph_r8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
406        let Self { glyph_r8_atlas, .. } = self;
407        glyph_r8_atlas.as_ref()
408    }
409
410    /// Returns a borrowed reference to the optional RGBA8 image atlas upload without cloning.
411    ///
412    /// # Returns
413    ///
414    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed RGBA8 image atlas upload when present.
415    #[must_use]
416    pub fn image_rgba8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
417        let Self {
418            image_rgba8_atlas, ..
419        } = self;
420        image_rgba8_atlas.as_ref()
421    }
422}
423
424/// Telemetry recording and simulator-honesty methods for `MobilePresentTelemetry`.
425impl MobilePresentTelemetry {
426    /// Creates an initialized telemetry snapshot configured for `active_path`, `display_mode_hz`, and simulator status.
427    ///
428    /// # Arguments
429    ///
430    /// - `MobilePresentPath` - Active presentation channel.
431    /// - `f32` - Display refresh rate in Hertz.
432    /// - `bool` - `true` when executing inside a simulator where compositor timestamps are unobservable.
433    ///
434    /// # Returns
435    ///
436    /// - `Self` - Configured mobile presentation telemetry state.
437    #[must_use]
438    pub fn for_host(
439        active_path: MobilePresentPath,
440        display_mode_hz: f32,
441        is_simulator: bool,
442    ) -> Self {
443        let cpu_mirror_active: bool = active_path != MobilePresentPath::GpuDirect;
444        let upload_strategy: MobileUploadStrategy = match active_path {
445            MobilePresentPath::GpuDirect => MobileUploadStrategy::DirectGpu,
446            MobilePresentPath::GpuUpload | MobilePresentPath::Software => {
447                MobileUploadStrategy::FullFrame
448            }
449        };
450        let (timing_source, unobservable_reason): (
451            MobilePresentTimingSource,
452            Option<&'static str>,
453        ) = if is_simulator {
454            (
455                MobilePresentTimingSource::SubmissionProxy,
456                Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR),
457            )
458        } else {
459            (MobilePresentTimingSource::Unobservable, None)
460        };
461        Self {
462            active_path,
463            upload_strategy,
464            cpu_mirror_active,
465            timing_source,
466            unobservable_reason,
467            is_simulator,
468            display_mode_hz: display_mode_hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ),
469            frame_callback_count: 0,
470            last_callback_timestamp_ns: 0,
471            last_callback_interval_ms: None,
472            last_target_timestamp_ns: None,
473            last_presented_timestamp_ns: None,
474            actual_presented_frames: 0,
475            upload_bytes_last_frame: 0,
476            upload_bytes_total: 0,
477            primitive_count_last_frame: 0,
478            draw_calls_last_frame: 0,
479            submit_failures: 0,
480            present_failures: 0,
481            context_loss_count: 0,
482            blank_frames_prevented: 0,
483            last_valid_frame_retained: false,
484        }
485    }
486
487    /// Records a VSync callback (`Choreographer.doFrame` or `CADisplayLink`) timestamp and optional target timestamp.
488    ///
489    /// # Arguments
490    ///
491    /// - `u64` - Monotonic VSync callback timestamp in nanoseconds.
492    /// - `Option<u64>` - Optional target presentation deadline timestamp in nanoseconds.
493    pub fn record_vsync_callback(&mut self, callback_ts_ns: u64, target_ts_ns: Option<u64>) {
494        let prev_ts: u64 = self.get_last_callback_timestamp_ns();
495        self.set_frame_callback_count(self.get_frame_callback_count().saturating_add(1));
496        if callback_ts_ns > 0 {
497            if prev_ts > 0 && callback_ts_ns > prev_ts {
498                let delta_ms: f64 = ((callback_ts_ns - prev_ts) as f64) / 1_000_000.0;
499                self.set_last_callback_interval_ms(Some(delta_ms));
500            }
501            self.set_last_callback_timestamp_ns(callback_ts_ns);
502        }
503        if let Some(target_ns) = target_ts_ns
504            && target_ns > 0
505        {
506            self.set_last_target_timestamp_ns(Some(target_ns));
507        }
508    }
509
510    /// Records a successful frame presentation with exact path, upload strategy, byte count, and draw telemetry.
511    ///
512    /// # Arguments
513    ///
514    /// - `MobilePresentPath` - Active presentation channel executed for this frame.
515    /// - `MobileUploadStrategy` - Upload strategy executed for this frame.
516    /// - `u64` - Payload bytes uploaded to GPU or native surface memory.
517    /// - `u32` - Number of 64-byte `GpuPrimitiveInstance` records emitted (`0` on upload/software).
518    /// - `u32` - Number of GPU draw calls emitted.
519    /// - `Option<u64>` - Optional hardware compositor presentation timestamp in nanoseconds (`None` when unobservable).
520    pub fn record_presented_frame(
521        &mut self,
522        path: MobilePresentPath,
523        strategy: MobileUploadStrategy,
524        upload_bytes: u64,
525        primitive_count: u32,
526        draw_calls: u32,
527        compositor_presented_ns: Option<u64>,
528    ) {
529        self.set_active_path(path);
530        self.set_upload_strategy(strategy);
531        self.set_cpu_mirror_active(path != MobilePresentPath::GpuDirect);
532        self.set_upload_bytes_last_frame(upload_bytes);
533        self.set_upload_bytes_total(self.get_upload_bytes_total().saturating_add(upload_bytes));
534        self.set_primitive_count_last_frame(primitive_count);
535        self.set_draw_calls_last_frame(draw_calls);
536        self.set_actual_presented_frames(self.get_actual_presented_frames().saturating_add(1));
537        self.set_last_valid_frame_retained(true);
538        self.record_compositor_present_timestamp(compositor_presented_ns);
539    }
540
541    /// Records an observed compositor presentation timestamp while honestly marking simulator or missing timestamps unobservable.
542    ///
543    /// # Arguments
544    ///
545    /// - `Option<u64>` - Compositor presentation timestamp in nanoseconds (`None` or `Some(0)` when unobservable).
546    pub fn record_compositor_present_timestamp(&mut self, presented_ns: Option<u64>) {
547        let is_sim: bool = self.get_is_simulator();
548        match presented_ns {
549            Some(ts) if ts > 0 && !is_sim => {
550                self.set_last_presented_timestamp_ns(Some(ts));
551                self.set_timing_source(MobilePresentTimingSource::CompositorMeasured);
552                self.set_unobservable_reason(None);
553            }
554            _ if is_sim => {
555                self.set_last_presented_timestamp_ns(None);
556                self.set_timing_source(MobilePresentTimingSource::SubmissionProxy);
557                self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR));
558            }
559            _ => {
560                self.set_last_presented_timestamp_ns(None);
561                self.set_timing_source(MobilePresentTimingSource::Unobservable);
562                self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_UNSUPPORTED));
563            }
564        }
565    }
566
567    /// Records a frame submission or presentation fault without fabricating a presented frame.
568    ///
569    /// # Arguments
570    ///
571    /// - `MobileSurfaceFault` - Fault category observed during submit or present.
572    /// - `bool` - `true` when the last valid frame was retained to prevent submitting a blank frame.
573    pub fn record_fault(&mut self, fault: MobileSurfaceFault, blank_prevented: bool) {
574        match fault {
575            MobileSurfaceFault::ContextLost => {
576                self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
577                self.set_present_failures(self.get_present_failures().saturating_add(1));
578            }
579            MobileSurfaceFault::SurfaceLost | MobileSurfaceFault::SubmitFailed => {
580                self.set_submit_failures(self.get_submit_failures().saturating_add(1));
581            }
582            MobileSurfaceFault::ShaderCompileFailed => {
583                self.set_submit_failures(self.get_submit_failures().saturating_add(1));
584            }
585        }
586        if blank_prevented {
587            self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
588        }
589    }
590}
591
592/// Immediate zero-blank-frame failover logic for `MobileFailoverController`.
593impl Default for MobileFailoverController {
594    /// Creates a failover controller preferring `GpuDirect` with both `GpuUpload` and `Software` fallbacks enabled.
595    ///
596    /// # Returns
597    ///
598    /// - `Self` - Default GPU-first failover controller.
599    fn default() -> Self {
600        Self::for_preferred(MobilePresentPath::GpuDirect, true, true)
601    }
602}
603
604/// Fault-handling and path-selection methods for `MobileFailoverController`.
605impl MobileFailoverController {
606    /// Creates a failover controller honoring `preferred_path` and detected hardware capabilities.
607    ///
608    /// # Arguments
609    ///
610    /// - `MobilePresentPath` - Preferred initial presentation path.
611    /// - `bool` - `true` when direct GPU uber-shader rendering is available.
612    /// - `bool` - `true` when GPU texture upload rendering is available.
613    ///
614    /// # Returns
615    ///
616    /// - `Self` - Configured failover controller with an immediately runnable active path.
617    #[must_use]
618    pub fn for_preferred(
619        preferred_path: MobilePresentPath,
620        direct_gpu_available: bool,
621        gpu_upload_available: bool,
622    ) -> Self {
623        let active_path: MobilePresentPath = match preferred_path {
624            MobilePresentPath::GpuDirect if direct_gpu_available => MobilePresentPath::GpuDirect,
625            MobilePresentPath::GpuDirect | MobilePresentPath::GpuUpload if gpu_upload_available => {
626                MobilePresentPath::GpuUpload
627            }
628            _ => MobilePresentPath::Software,
629        };
630        Self {
631            active_path,
632            preferred_path,
633            has_valid_presented_frame: false,
634            window_valid: true,
635            direct_gpu_available,
636            gpu_upload_available,
637            context_loss_count: 0,
638            blank_frames_prevented: 0,
639            fallback_transitions: 0,
640        }
641    }
642
643    /// Returns `true` when the active presentation path requires a CPU framebuffer mirror (`false` on `GpuDirect`).
644    ///
645    /// # Returns
646    ///
647    /// - `bool` - `false` for `GpuDirect`; `true` for `GpuUpload` and `Software`.
648    #[must_use]
649    pub fn cpu_mirror_active(&self) -> bool {
650        self.get_active_path() != MobilePresentPath::GpuDirect
651    }
652
653    /// Marks the active window surface valid or detached (`false` clears retained-frame status on new surface).
654    ///
655    /// # Arguments
656    ///
657    /// - `bool` - `true` when a live native window / Metal layer is attached.
658    pub fn set_surface_valid(&mut self, valid: bool) {
659        self.set_window_valid(valid);
660        if !valid {
661            self.set_has_valid_presented_frame(false);
662        }
663    }
664
665    /// Records that a valid non-blank frame has been presented onto the current surface.
666    pub fn mark_frame_presented(&mut self) {
667        self.set_has_valid_presented_frame(true);
668    }
669
670    /// Handles a graphics context or submission fault immediately without waiting for perf comparisons while preventing blank frames.
671    ///
672    /// # Arguments
673    ///
674    /// - `MobileSurfaceFault` - Observed context, shader, surface, or submission fault.
675    ///
676    /// # Returns
677    ///
678    /// - `MobileFailoverAction` - Deterministic immediate failover instruction.
679    pub fn handle_fault(&mut self, fault: MobileSurfaceFault) -> MobileFailoverAction {
680        if !self.get_window_valid() {
681            return MobileFailoverAction::WaitForNewSurface;
682        }
683        let retained: bool = self.get_has_valid_presented_frame();
684        if retained {
685            self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
686        }
687        match fault {
688            MobileSurfaceFault::ContextLost => {
689                self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
690                self.set_direct_gpu_available(false);
691                self.set_gpu_upload_available(false);
692                let prev: MobilePresentPath = self.get_active_path();
693                self.set_active_path(MobilePresentPath::Software);
694                if prev != MobilePresentPath::Software {
695                    self.set_fallback_transitions(
696                        self.get_fallback_transitions().saturating_add(1),
697                    );
698                }
699                MobileFailoverAction::KeepLastFrameAndSwitch(MobilePresentPath::Software)
700            }
701            MobileSurfaceFault::ShaderCompileFailed => {
702                self.set_direct_gpu_available(false);
703                let next: MobilePresentPath = if self.get_gpu_upload_available() {
704                    MobilePresentPath::GpuUpload
705                } else {
706                    MobilePresentPath::Software
707                };
708                if self.get_active_path() != next {
709                    self.set_active_path(next);
710                    self.set_fallback_transitions(
711                        self.get_fallback_transitions().saturating_add(1),
712                    );
713                }
714                MobileFailoverAction::KeepLastFrameAndSwitch(next)
715            }
716            MobileSurfaceFault::SubmitFailed => {
717                let next: MobilePresentPath = match self.get_active_path() {
718                    MobilePresentPath::GpuDirect => {
719                        if self.get_gpu_upload_available() {
720                            MobilePresentPath::GpuUpload
721                        } else {
722                            MobilePresentPath::Software
723                        }
724                    }
725                    MobilePresentPath::GpuUpload => MobilePresentPath::Software,
726                    MobilePresentPath::Software => {
727                        return MobileFailoverAction::KeepLastFrameAndRetry;
728                    }
729                };
730                self.set_active_path(next);
731                self.set_fallback_transitions(self.get_fallback_transitions().saturating_add(1));
732                MobileFailoverAction::KeepLastFrameAndSwitch(next)
733            }
734            MobileSurfaceFault::SurfaceLost => MobileFailoverAction::KeepLastFrameAndRetry,
735        }
736    }
737}