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            engine3d_pipeline_handle: probed.engine3d_pipeline_handle,
39            ocean_pipeline_handle: probed.ocean_pipeline_handle,
40            surface_layer_handle: 0,
41            glyph_r8_texture_handle: probed.dummy_r8_tex,
42            glyph_rgba8_texture_handle: probed.dummy_rgba8_tex,
43            image_texture_handle: retain_native_gpu_object(probed.dummy_rgba8_tex),
44            external_texture_handle: 0,
45            ring_slots: [NativeGpuRingSlot::default(); GPU_DRIVER_RING_SLOTS],
46            ring_cursor: 0,
47            staging_buffer_handle: 0,
48            staging_contents_ptr: 0,
49            staging_buffer_capacity: 0,
50            submitted_frames: 0,
51            uploaded_instances: 0,
52            uploaded_bytes: 0,
53            last_upload_bytes: 0,
54            last_submitted_batches: 0,
55            staging_reallocations: 0,
56            last_presented_time_ns: 0,
57            last_gpu_exec_ns: 0,
58            #[cfg(any(target_os = "macos", target_os = "ios"))]
59            scratch_primitives: Vec::new(),
60            fallback,
61        }
62    }
63
64    /// Re-initializes the GPU driver for `backend`, releasing any previously retained OS handles.
65    ///
66    /// # Arguments
67    ///
68    /// - `GraphicsBackend` - Target graphics backend.
69    pub fn switch_backend(&mut self, backend: GraphicsBackend) {
70        if self.get_adapter().get_backend() == backend {
71            return;
72        }
73        *self = Self::probe(backend);
74    }
75
76    /// Attaches a native `CAMetalLayer*` (or equivalent surface layer) for zero-readback hardware presentation.
77    ///
78    /// # Arguments
79    ///
80    /// - `usize` - Native `CAMetalLayer*` pointer (`0` detaches).
81    pub fn attach_metal_layer(&mut self, layer_handle: usize) {
82        let dev: usize = self.get_device_handle();
83        let Self {
84            surface_layer_handle,
85            ..
86        } = self;
87        *surface_layer_handle = layer_handle;
88        if dev != 0 && layer_handle != 0 {
89            configure_native_metal_layer(dev, layer_handle);
90        }
91    }
92
93    /// Binds an external shared-device GPU texture handle (3D game render target or hardware video surface).
94    ///
95    /// # Arguments
96    ///
97    /// - `usize` - Native external texture handle (`0` restores fallback dummy texture).
98    pub fn set_external_texture(&mut self, texture_handle: usize) {
99        let Self {
100            external_texture_handle,
101            ..
102        } = self;
103        *external_texture_handle = texture_handle;
104    }
105
106    /// Uploads a dirty R8 or RGBA8 sub-rectangle to the resident glyph atlas or image texture on GPU.
107    ///
108    /// # Arguments
109    ///
110    /// - `GpuAtlasPixelFormat` - Target texture pixel format (`R8Unorm` or `Rgba8Unorm`).
111    /// - `u8` - Texture slot (`0` = R8 glyph atlas, `1` = RGBA8 color glyph atlas, `2` = UI image texture).
112    /// - `(u32, u32)` - Full backing texture dimensions `(width, height)`.
113    /// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
114    /// - `&[u8]` - Source pixel bytes.
115    /// - `usize` - Row stride in bytes.
116    ///
117    /// # Returns
118    ///
119    /// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly to hardware GPU memory.
120    pub fn upload_texture_dirty_rect(
121        &mut self,
122        format: GpuAtlasPixelFormat,
123        texture_slot: u8,
124        tex_dims: (u32, u32),
125        dirty_rect: (u32, u32, u32, u32),
126        bytes: &[u8],
127        bytes_per_row: usize,
128    ) -> bool {
129        let dev: usize = self.get_device_handle();
130        let Self {
131            glyph_r8_texture_handle,
132            glyph_rgba8_texture_handle,
133            image_texture_handle,
134            ..
135        } = self;
136        let target: &mut usize = match texture_slot {
137            0 => glyph_r8_texture_handle,
138            1 => glyph_rgba8_texture_handle,
139            _ => image_texture_handle,
140        };
141        upload_native_texture_dirty_rect(
142            dev,
143            target,
144            format,
145            tex_dims,
146            dirty_rect,
147            bytes,
148            bytes_per_row,
149        )
150    }
151
152    /// Returns `true` when the driver has both a live compiled GPU blur pipeline and an attached presentation surface.
153    ///
154    /// # Returns
155    ///
156    /// - `bool` - `true` when `BackdropBlur` can execute natively on GPU without CPU fallback.
157    #[must_use]
158    pub fn supports_backdrop_blur_pass(&self) -> bool {
159        self.get_blur_pipeline_handle() != 0 && self.get_surface_layer_handle() != 0
160    }
161
162    /// Returns the count of resident hardware GPU render pipeline state objects (`UI`, `Blur`, `3D PBR`, `Fluid Ocean`) currently cached on this driver.
163    ///
164    /// # Returns
165    ///
166    /// - `usize` - Number of non-zero resident hardware pipeline handles (`0..=4`).
167    #[must_use]
168    pub fn precompiled_pipeline_count(&self) -> usize {
169        usize::from(self.get_pipeline_handle() != 0)
170            + usize::from(self.get_blur_pipeline_handle() != 0)
171            + usize::from(self.get_engine3d_pipeline_handle() != 0)
172            + usize::from(self.get_ocean_pipeline_handle() != 0)
173    }
174}
175
176/// `GpuDriver` implementation uploading packed 64-byte `GpuPrimitiveInstance` streams to the active physical OS GPU.
177impl GpuDriver for NativeGpuDriver {
178    /// Returns the resolved `GraphicsBackend`.
179    ///
180    /// # Returns
181    ///
182    /// - `GraphicsBackend` - Active backend tag.
183    fn backend(&self) -> GraphicsBackend {
184        self.get_adapter().get_backend()
185    }
186
187    /// Returns the native shader source compiled by this GPU backend.
188    ///
189    /// # Returns
190    ///
191    /// - `&'static str` - Native shader program source.
192    fn shader_source(&self) -> &'static str {
193        self.get_fallback().shader_source()
194    }
195
196    /// Uploads instanced 64-byte primitive batches through the 3-slot fenced ring and records draw telemetry.
197    ///
198    /// # Arguments
199    ///
200    /// - `u32` - Surface width.
201    /// - `u32` - Surface height.
202    /// - `Color` - Surface clear color.
203    /// - `&[GpuBatch]` - Ordered draw batches.
204    ///
205    /// # Returns
206    ///
207    /// - `Result<usize, PlatformError>` - Number of submitted GPU draw calls.
208    fn submit_batches(
209        &mut self,
210        width: u32,
211        height: u32,
212        clear_color: Color,
213        batches: &[GpuBatch],
214    ) -> Result<usize, PlatformError> {
215        let uploaded: usize =
216            submit_native_gpu_ring_frame(self, width, height, clear_color, batches);
217        let frame_bytes: usize = uploaded.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
218        let Self {
219            submitted_frames,
220            uploaded_instances,
221            uploaded_bytes,
222            last_upload_bytes,
223            last_submitted_batches,
224            last_presented_time_ns,
225            last_gpu_exec_ns,
226            fallback,
227            ..
228        } = self;
229        *submitted_frames = submitted_frames.wrapping_add(1);
230        *uploaded_instances = uploaded_instances.wrapping_add(uploaded as u64);
231        *uploaded_bytes = uploaded_bytes.wrapping_add(frame_bytes as u64);
232        *last_upload_bytes = frame_bytes;
233        *last_submitted_batches = batches.len();
234        *last_presented_time_ns = native_gpu_last_presented_ns();
235        *last_gpu_exec_ns = native_gpu_last_exec_ns();
236        fallback.submit_batches(width, height, clear_color, batches)
237    }
238}
239
240/// Automatic native GPU handle cleanup when `NativeGpuDriver` is dropped.
241impl Drop for NativeGpuDriver {
242    /// Releases retained OS GPU ring buffers, in-flight command buffers, textures, pipelines, and device handles.
243    fn drop(&mut self) {
244        let Self {
245            device_handle,
246            queue_handle,
247            library_handle,
248            pipeline_handle,
249            blur_pipeline_handle,
250            engine3d_pipeline_handle,
251            ocean_pipeline_handle,
252            glyph_r8_texture_handle,
253            glyph_rgba8_texture_handle,
254            image_texture_handle,
255            ring_slots,
256            staging_buffer_handle,
257            staging_contents_ptr,
258            staging_buffer_capacity,
259            ..
260        } = self;
261        for slot in ring_slots.iter_mut() {
262            let cmd: usize = slot.get_in_flight_cmd_buffer();
263            if cmd != 0 {
264                release_native_gpu_object(cmd);
265                slot.set_in_flight_cmd_buffer(0);
266            }
267            let buf: usize = slot.get_buffer_handle();
268            if buf != 0 {
269                release_native_gpu_object(buf);
270                slot.set_buffer_handle(0);
271                slot.set_contents_ptr(0);
272                slot.set_capacity_bytes(0);
273            }
274        }
275        *staging_buffer_handle = 0;
276        *staging_contents_ptr = 0;
277        *staging_buffer_capacity = 0;
278        release_native_gpu_object(*glyph_r8_texture_handle);
279        release_native_gpu_object(*glyph_rgba8_texture_handle);
280        release_native_gpu_object(*image_texture_handle);
281        release_native_gpu_object(*ocean_pipeline_handle);
282        release_native_gpu_object(*engine3d_pipeline_handle);
283        release_native_gpu_object(*blur_pipeline_handle);
284        release_native_gpu_object(*pipeline_handle);
285        release_native_gpu_handles(*device_handle, *queue_handle, *library_handle);
286    }
287}
288
289/// Geometry and byte-size helpers for `PixelDirtyRect`.
290impl PixelDirtyRect {
291    /// Returns the exclusive right pixel edge (`x + width`).
292    ///
293    /// # Returns
294    ///
295    /// - `u32` - Exclusive right coordinate in pixels.
296    #[must_use]
297    pub fn right(&self) -> u32 {
298        self.get_x().saturating_add(self.get_width())
299    }
300
301    /// Returns the exclusive bottom pixel edge (`y + height`).
302    ///
303    /// # Returns
304    ///
305    /// - `u32` - Exclusive bottom coordinate in pixels.
306    #[must_use]
307    pub fn bottom(&self) -> u32 {
308        self.get_y().saturating_add(self.get_height())
309    }
310
311    /// Returns `true` when either width or height is zero.
312    ///
313    /// # Returns
314    ///
315    /// - `bool` - `true` when the rectangle covers zero pixels.
316    #[must_use]
317    pub fn is_empty(&self) -> bool {
318        self.get_width() == 0 || self.get_height() == 0
319    }
320
321    /// Returns the covered pixel count (`width * height`).
322    ///
323    /// # Returns
324    ///
325    /// - `usize` - Total covered pixels.
326    #[must_use]
327    pub fn area_pixels(&self) -> usize {
328        (self.get_width() as usize).saturating_mul(self.get_height() as usize)
329    }
330
331    /// Returns the RGBA8 byte payload size (`width * height * 4`).
332    ///
333    /// # Returns
334    ///
335    /// - `usize` - Payload size in bytes.
336    #[must_use]
337    pub fn byte_size_rgba8(&self) -> usize {
338        self.area_pixels().saturating_mul(4)
339    }
340
341    /// Clamps this rectangle strictly inside `(fb_w, fb_h)` surface bounds.
342    ///
343    /// # Arguments
344    ///
345    /// - `u32` - Surface width in pixels.
346    /// - `u32` - Surface height in pixels.
347    ///
348    /// # Returns
349    ///
350    /// - `Option<Self>` - Clamped non-empty rectangle, or `None` when outside bounds.
351    #[must_use]
352    pub fn clamp_to(&self, fb_w: u32, fb_h: u32) -> Option<Self> {
353        let x0: u32 = self.get_x().min(fb_w);
354        let y0: u32 = self.get_y().min(fb_h);
355        let x1: u32 = self.right().min(fb_w);
356        let y1: u32 = self.bottom().min(fb_h);
357        let width_val: u32 = x1.saturating_sub(x0);
358        let height_val: u32 = y1.saturating_sub(y0);
359        if width_val == 0 || height_val == 0 {
360            None
361        } else {
362            Some(Self::new(x0, y0, width_val, height_val))
363        }
364    }
365
366    /// Returns the smallest enclosing bounding rectangle containing both `self` and `other`.
367    ///
368    /// # Arguments
369    ///
370    /// - `Self` - Other pixel rectangle.
371    ///
372    /// # Returns
373    ///
374    /// - `Self` - Enclosing union rectangle.
375    #[must_use]
376    pub fn union_with(&self, other: Self) -> Self {
377        if self.is_empty() {
378            return other;
379        }
380        if other.is_empty() {
381            return *self;
382        }
383        let x0: u32 = self.get_x().min(other.get_x());
384        let y0: u32 = self.get_y().min(other.get_y());
385        let x1: u32 = self.right().max(other.right());
386        let y1: u32 = self.bottom().max(other.bottom());
387        Self::new(x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
388    }
389
390    /// Returns `true` when `self` and `other` overlap or lie within `pad_px` pixels of each other.
391    ///
392    /// # Arguments
393    ///
394    /// - `Self` - Other pixel rectangle.
395    /// - `u32` - Adjacency tolerance in pixels.
396    ///
397    /// # Returns
398    ///
399    /// - `bool` - `true` when the two rectangles overlap or are adjacent within `pad_px`.
400    #[must_use]
401    pub fn intersects_or_adjacent(&self, other: Self, pad_px: u32) -> bool {
402        if self.is_empty() || other.is_empty() {
403            return false;
404        }
405        let ax0: u32 = self.get_x().saturating_sub(pad_px);
406        let ay0: u32 = self.get_y().saturating_sub(pad_px);
407        let ax1: u32 = self.right().saturating_add(pad_px);
408        let ay1: u32 = self.bottom().saturating_add(pad_px);
409        ax0 <= other.right()
410            && ax1 >= other.get_x()
411            && ay0 <= other.bottom()
412            && ay1 >= other.get_y()
413    }
414}
415
416/// Zero-copy borrowed atlas accessors for `DirectGpuFrameBatch`.
417impl DirectGpuFrameBatch {
418    /// Returns a borrowed reference to the optional R8 monochrome glyph atlas upload without cloning.
419    ///
420    /// # Returns
421    ///
422    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed R8 glyph atlas upload when present.
423    #[must_use]
424    pub fn glyph_r8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
425        let Self { glyph_r8_atlas, .. } = self;
426        glyph_r8_atlas.as_ref()
427    }
428
429    /// Returns a borrowed reference to the optional RGBA8 image atlas upload without cloning.
430    ///
431    /// # Returns
432    ///
433    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed RGBA8 image atlas upload when present.
434    #[must_use]
435    pub fn image_rgba8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
436        let Self {
437            image_rgba8_atlas, ..
438        } = self;
439        image_rgba8_atlas.as_ref()
440    }
441}
442
443/// Telemetry recording and simulator-honesty methods for `MobilePresentTelemetry`.
444impl MobilePresentTelemetry {
445    /// Creates an initialized telemetry snapshot configured for `active_path`, `display_mode_hz`, and simulator status.
446    ///
447    /// # Arguments
448    ///
449    /// - `MobilePresentPath` - Active presentation channel.
450    /// - `f32` - Display refresh rate in Hertz.
451    /// - `bool` - `true` when executing inside a simulator where compositor timestamps are unobservable.
452    ///
453    /// # Returns
454    ///
455    /// - `Self` - Configured mobile presentation telemetry state.
456    #[must_use]
457    pub fn for_host(
458        active_path: MobilePresentPath,
459        display_mode_hz: f32,
460        is_simulator: bool,
461    ) -> Self {
462        let cpu_mirror_active: bool = active_path != MobilePresentPath::GpuDirect;
463        let upload_strategy: MobileUploadStrategy = match active_path {
464            MobilePresentPath::GpuDirect => MobileUploadStrategy::DirectGpu,
465            MobilePresentPath::GpuUpload | MobilePresentPath::Software => {
466                MobileUploadStrategy::FullFrame
467            }
468        };
469        let (timing_source, unobservable_reason): (
470            MobilePresentTimingSource,
471            Option<&'static str>,
472        ) = if is_simulator {
473            (
474                MobilePresentTimingSource::SubmissionProxy,
475                Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR),
476            )
477        } else {
478            (MobilePresentTimingSource::Unobservable, None)
479        };
480        Self {
481            active_path,
482            upload_strategy,
483            cpu_mirror_active,
484            timing_source,
485            unobservable_reason,
486            is_simulator,
487            display_mode_hz: display_mode_hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ),
488            frame_callback_count: 0,
489            last_callback_timestamp_ns: 0,
490            last_callback_interval_ms: None,
491            last_target_timestamp_ns: None,
492            last_presented_timestamp_ns: None,
493            actual_presented_frames: 0,
494            upload_bytes_last_frame: 0,
495            upload_bytes_total: 0,
496            primitive_count_last_frame: 0,
497            draw_calls_last_frame: 0,
498            submit_failures: 0,
499            present_failures: 0,
500            context_loss_count: 0,
501            blank_frames_prevented: 0,
502            last_valid_frame_retained: false,
503        }
504    }
505
506    /// Records a VSync callback (`Choreographer.doFrame` or `CADisplayLink`) timestamp and optional target timestamp.
507    ///
508    /// # Arguments
509    ///
510    /// - `u64` - Monotonic VSync callback timestamp in nanoseconds.
511    /// - `Option<u64>` - Optional target presentation deadline timestamp in nanoseconds.
512    pub fn record_vsync_callback(&mut self, callback_ts_ns: u64, target_ts_ns: Option<u64>) {
513        let prev_ts: u64 = self.get_last_callback_timestamp_ns();
514        self.set_frame_callback_count(self.get_frame_callback_count().saturating_add(1));
515        if callback_ts_ns > 0 {
516            if prev_ts > 0 && callback_ts_ns > prev_ts {
517                let delta_ms: f64 = ((callback_ts_ns - prev_ts) as f64) / 1_000_000.0;
518                self.set_last_callback_interval_ms(Some(delta_ms));
519            }
520            self.set_last_callback_timestamp_ns(callback_ts_ns);
521        }
522        if let Some(target_ns) = target_ts_ns
523            && target_ns > 0
524        {
525            self.set_last_target_timestamp_ns(Some(target_ns));
526        }
527    }
528
529    /// Records a successful frame presentation with exact path, upload strategy, byte count, and draw telemetry.
530    ///
531    /// # Arguments
532    ///
533    /// - `MobilePresentPath` - Active presentation channel executed for this frame.
534    /// - `MobileUploadStrategy` - Upload strategy executed for this frame.
535    /// - `u64` - Payload bytes uploaded to GPU or native surface memory.
536    /// - `u32` - Number of 64-byte `GpuPrimitiveInstance` records emitted (`0` on upload/software).
537    /// - `u32` - Number of GPU draw calls emitted.
538    /// - `Option<u64>` - Optional hardware compositor presentation timestamp in nanoseconds (`None` when unobservable).
539    pub fn record_presented_frame(
540        &mut self,
541        path: MobilePresentPath,
542        strategy: MobileUploadStrategy,
543        upload_bytes: u64,
544        primitive_count: u32,
545        draw_calls: u32,
546        compositor_presented_ns: Option<u64>,
547    ) {
548        self.set_active_path(path);
549        self.set_upload_strategy(strategy);
550        self.set_cpu_mirror_active(path != MobilePresentPath::GpuDirect);
551        self.set_upload_bytes_last_frame(upload_bytes);
552        self.set_upload_bytes_total(self.get_upload_bytes_total().saturating_add(upload_bytes));
553        self.set_primitive_count_last_frame(primitive_count);
554        self.set_draw_calls_last_frame(draw_calls);
555        self.set_actual_presented_frames(self.get_actual_presented_frames().saturating_add(1));
556        self.set_last_valid_frame_retained(true);
557        self.record_compositor_present_timestamp(compositor_presented_ns);
558    }
559
560    /// Records an observed compositor presentation timestamp while honestly marking simulator or missing timestamps unobservable.
561    ///
562    /// # Arguments
563    ///
564    /// - `Option<u64>` - Compositor presentation timestamp in nanoseconds (`None` or `Some(0)` when unobservable).
565    pub fn record_compositor_present_timestamp(&mut self, presented_ns: Option<u64>) {
566        let is_sim: bool = self.get_is_simulator();
567        match presented_ns {
568            Some(timestamp_val) if timestamp_val > 0 && !is_sim => {
569                self.set_last_presented_timestamp_ns(Some(timestamp_val));
570                self.set_timing_source(MobilePresentTimingSource::CompositorMeasured);
571                self.set_unobservable_reason(None);
572            }
573            _ if is_sim => {
574                self.set_last_presented_timestamp_ns(None);
575                self.set_timing_source(MobilePresentTimingSource::SubmissionProxy);
576                self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR));
577            }
578            _ => {
579                self.set_last_presented_timestamp_ns(None);
580                self.set_timing_source(MobilePresentTimingSource::Unobservable);
581                self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_UNSUPPORTED));
582            }
583        }
584    }
585
586    /// Records a frame submission or presentation fault without fabricating a presented frame.
587    ///
588    /// # Arguments
589    ///
590    /// - `MobileSurfaceFault` - Fault category observed during submit or present.
591    /// - `bool` - `true` when the last valid frame was retained to prevent submitting a blank frame.
592    pub fn record_fault(&mut self, fault: MobileSurfaceFault, blank_prevented: bool) {
593        match fault {
594            MobileSurfaceFault::ContextLost => {
595                self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
596                self.set_present_failures(self.get_present_failures().saturating_add(1));
597            }
598            MobileSurfaceFault::SurfaceLost | MobileSurfaceFault::SubmitFailed => {
599                self.set_submit_failures(self.get_submit_failures().saturating_add(1));
600            }
601            MobileSurfaceFault::ShaderCompileFailed => {
602                self.set_submit_failures(self.get_submit_failures().saturating_add(1));
603            }
604        }
605        if blank_prevented {
606            self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
607        }
608    }
609}
610
611/// Immediate zero-blank-frame failover logic for `MobileFailoverController`.
612impl Default for MobileFailoverController {
613    /// Creates a failover controller preferring `GpuDirect` with both `GpuUpload` and `Software` fallbacks enabled.
614    ///
615    /// # Returns
616    ///
617    /// - `Self` - Default GPU-first failover controller.
618    fn default() -> Self {
619        Self::for_preferred(MobilePresentPath::GpuDirect, true, true)
620    }
621}
622
623/// Fault-handling and path-selection methods for `MobileFailoverController`.
624impl MobileFailoverController {
625    /// Creates a failover controller honoring `preferred_path` and detected hardware capabilities.
626    ///
627    /// # Arguments
628    ///
629    /// - `MobilePresentPath` - Preferred initial presentation path.
630    /// - `bool` - `true` when direct GPU uber-shader rendering is available.
631    /// - `bool` - `true` when GPU texture upload rendering is available.
632    ///
633    /// # Returns
634    ///
635    /// - `Self` - Configured failover controller with an immediately runnable active path.
636    #[must_use]
637    pub fn for_preferred(
638        preferred_path: MobilePresentPath,
639        direct_gpu_available: bool,
640        gpu_upload_available: bool,
641    ) -> Self {
642        let active_path: MobilePresentPath = match preferred_path {
643            MobilePresentPath::GpuDirect if direct_gpu_available => MobilePresentPath::GpuDirect,
644            MobilePresentPath::GpuDirect | MobilePresentPath::GpuUpload if gpu_upload_available => {
645                MobilePresentPath::GpuUpload
646            }
647            _ => MobilePresentPath::Software,
648        };
649        Self {
650            active_path,
651            preferred_path,
652            has_valid_presented_frame: false,
653            window_valid: true,
654            direct_gpu_available,
655            gpu_upload_available,
656            context_loss_count: 0,
657            blank_frames_prevented: 0,
658            fallback_transitions: 0,
659        }
660    }
661
662    /// Returns `true` when the active presentation path requires a CPU framebuffer mirror (`false` on `GpuDirect`).
663    ///
664    /// # Returns
665    ///
666    /// - `bool` - `false` for `GpuDirect`; `true` for `GpuUpload` and `Software`.
667    #[must_use]
668    pub fn cpu_mirror_active(&self) -> bool {
669        self.get_active_path() != MobilePresentPath::GpuDirect
670    }
671
672    /// Marks the active window surface valid or detached (`false` clears retained-frame status on new surface).
673    ///
674    /// # Arguments
675    ///
676    /// - `bool` - `true` when a live native window / Metal layer is attached.
677    pub fn set_surface_valid(&mut self, valid: bool) {
678        self.set_window_valid(valid);
679        if !valid {
680            self.set_has_valid_presented_frame(false);
681        }
682    }
683
684    /// Records that a valid non-blank frame has been presented onto the current surface.
685    pub fn mark_frame_presented(&mut self) {
686        self.set_has_valid_presented_frame(true);
687    }
688
689    /// Handles a graphics context or submission fault immediately without waiting for perf comparisons while preventing blank frames.
690    ///
691    /// # Arguments
692    ///
693    /// - `MobileSurfaceFault` - Observed context, shader, surface, or submission fault.
694    ///
695    /// # Returns
696    ///
697    /// - `MobileFailoverAction` - Deterministic immediate failover instruction.
698    pub fn handle_fault(&mut self, fault: MobileSurfaceFault) -> MobileFailoverAction {
699        if !self.get_window_valid() {
700            return MobileFailoverAction::WaitForNewSurface;
701        }
702        let retained: bool = self.get_has_valid_presented_frame();
703        if retained {
704            self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
705        }
706        match fault {
707            MobileSurfaceFault::ContextLost => {
708                self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
709                self.set_direct_gpu_available(false);
710                self.set_gpu_upload_available(false);
711                let prev: MobilePresentPath = self.get_active_path();
712                self.set_active_path(MobilePresentPath::Software);
713                if prev != MobilePresentPath::Software {
714                    self.set_fallback_transitions(
715                        self.get_fallback_transitions().saturating_add(1),
716                    );
717                }
718                MobileFailoverAction::KeepLastFrameAndSwitch(MobilePresentPath::Software)
719            }
720            MobileSurfaceFault::ShaderCompileFailed => {
721                self.set_direct_gpu_available(false);
722                let next: MobilePresentPath = if self.get_gpu_upload_available() {
723                    MobilePresentPath::GpuUpload
724                } else {
725                    MobilePresentPath::Software
726                };
727                if self.get_active_path() != next {
728                    self.set_active_path(next);
729                    self.set_fallback_transitions(
730                        self.get_fallback_transitions().saturating_add(1),
731                    );
732                }
733                MobileFailoverAction::KeepLastFrameAndSwitch(next)
734            }
735            MobileSurfaceFault::SubmitFailed => {
736                let next: MobilePresentPath = match self.get_active_path() {
737                    MobilePresentPath::GpuDirect => {
738                        if self.get_gpu_upload_available() {
739                            MobilePresentPath::GpuUpload
740                        } else {
741                            MobilePresentPath::Software
742                        }
743                    }
744                    MobilePresentPath::GpuUpload => MobilePresentPath::Software,
745                    MobilePresentPath::Software => {
746                        return MobileFailoverAction::KeepLastFrameAndRetry;
747                    }
748                };
749                self.set_active_path(next);
750                self.set_fallback_transitions(self.get_fallback_transitions().saturating_add(1));
751                MobileFailoverAction::KeepLastFrameAndSwitch(next)
752            }
753            MobileSurfaceFault::SurfaceLost => MobileFailoverAction::KeepLastFrameAndRetry,
754        }
755    }
756}
757
758/// Canonical shader program listing, metadata, and per-backend source lookup for `ShaderProgramId`.
759impl ShaderProgramId {
760    /// Returns all built-in GPU shader programs ordered for ahead-of-time precompilation.
761    ///
762    /// # Returns
763    ///
764    /// - `[Self; 4]` - Complete ordered list of built-in shader programs.
765    #[must_use]
766    pub const fn all() -> [Self; 4] {
767        [
768            Self::UiUber,
769            Self::BackdropBlur,
770            Self::Engine3dPbr,
771            Self::FluidOceanOptical,
772        ]
773    }
774
775    /// Returns the human-readable diagnostic title for this shader program.
776    ///
777    /// # Returns
778    ///
779    /// - `&'static str` - Descriptive shader pipeline name.
780    #[must_use]
781    pub const fn label(self) -> &'static str {
782        match self {
783            Self::UiUber => "UI Uber-Shader (64B SDF)",
784            Self::BackdropBlur => "Dual-Kawase BackdropBlur",
785            Self::Engine3dPbr => "3D Engine PBR (GGX + ACES)",
786            Self::FluidOceanOptical => "Fluid Ocean Optical (Gerstner + GGX)",
787        }
788    }
789
790    /// Resolves the shading language name paired with `backend`.
791    ///
792    /// # Arguments
793    ///
794    /// - `GraphicsBackend` - Active graphics API backend.
795    ///
796    /// # Returns
797    ///
798    /// - `&'static str` - Target shading language label (`MSL`, `WGSL`, `GLSL ES 3.0`, or `HLSL SM 6.0`).
799    #[must_use]
800    pub const fn language_for_backend(backend: GraphicsBackend) -> &'static str {
801        match backend {
802            GraphicsBackend::Metal => "MSL",
803            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => "GLSL ES 3.0",
804            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => "HLSL SM 6.0",
805            GraphicsBackend::WebGpu
806            | GraphicsBackend::Vulkan
807            | GraphicsBackend::SoftwareCpu
808            | GraphicsBackend::Canvas2d
809            | GraphicsBackend::Headless => "WGSL",
810        }
811    }
812
813    /// Returns the primary and optional secondary shader source slices for this program on `backend`.
814    ///
815    /// # Arguments
816    ///
817    /// - `GraphicsBackend` - Active graphics API backend.
818    ///
819    /// # Returns
820    ///
821    /// - `(&'static str, &'static str)` - Primary shader source and optional paired fragment shader source (empty when unified).
822    #[must_use]
823    pub const fn source_pair(self, backend: GraphicsBackend) -> (&'static str, &'static str) {
824        match (self, backend) {
825            (Self::UiUber, GraphicsBackend::Metal) => (MSL_UI_SHADER, ""),
826            (Self::UiUber, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => {
827                (GLSL_ES3_UI_VERTEX_SHADER, GLSL_ES3_UI_FRAGMENT_SHADER)
828            }
829            (Self::UiUber, GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11) => {
830                (HLSL_UI_SHADER, "")
831            }
832            (Self::UiUber, _) => (WGSL_UI_SHADER, ""),
833            (Self::BackdropBlur, GraphicsBackend::Metal) => (MSL_BACKDROP_BLUR_SHADER, ""),
834            (Self::BackdropBlur, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => (
835                GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER,
836                GLSL_ES3_BACKDROP_BLUR_FRAGMENT_SHADER,
837            ),
838            (Self::BackdropBlur, GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11) => {
839                (HLSL_BACKDROP_BLUR_SHADER, "")
840            }
841            (Self::BackdropBlur, _) => (WGSL_BACKDROP_BLUR_SHADER, ""),
842            (Self::Engine3dPbr, GraphicsBackend::Metal) => (MSL_ENGINE3D_PBR_SHADER, ""),
843            (Self::Engine3dPbr, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => (
844                GLSL_ES3_ENGINE3D_VERTEX_SHADER,
845                GLSL_ES3_ENGINE3D_FRAGMENT_SHADER,
846            ),
847            (Self::Engine3dPbr, GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11) => {
848                (HLSL_ENGINE3D_PBR_SHADER, "")
849            }
850            (Self::Engine3dPbr, _) => (WGSL_ENGINE3D_PBR_SHADER, ""),
851            (Self::FluidOceanOptical, GraphicsBackend::Metal) => (MSL_FLUID_OCEAN_SHADER, ""),
852            (Self::FluidOceanOptical, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => (
853                GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER,
854                GLSL_ES3_FLUID_OCEAN_FRAGMENT_SHADER,
855            ),
856            (
857                Self::FluidOceanOptical,
858                GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11,
859            ) => (HLSL_FLUID_OCEAN_SHADER, ""),
860            (Self::FluidOceanOptical, _) => (WGSL_FLUID_OCEAN_SHADER, ""),
861        }
862    }
863}
864
865/// Diagnostic label and readiness query helpers for `ShaderCompileState`.
866impl ShaderCompileState {
867    /// Returns a concise human-readable label for UI telemetry displays.
868    ///
869    /// # Returns
870    ///
871    /// - `&'static str` - Status label string.
872    #[must_use]
873    pub const fn label(self) -> &'static str {
874        match self {
875            Self::Pending => "Pending",
876            Self::Compiling => "Compiling",
877            Self::CompiledHardware => "GPU PSO Ready",
878            Self::LoadedFromBinaryArchive => "Binary Archive Hit",
879            Self::ValidatedFallback => SHADER_STATE_LABEL_VALIDATED_FALLBACK,
880            Self::Failed => "Fallback",
881        }
882    }
883
884    /// Returns `true` when this state represents a ready precompiled or validated shader entry.
885    ///
886    /// # Returns
887    ///
888    /// - `bool` - `true` for hardware compiled, archive hit, or validated fallback states.
889    #[must_use]
890    pub const fn is_ready(self) -> bool {
891        matches!(
892            self,
893            Self::CompiledHardware | Self::LoadedFromBinaryArchive | Self::ValidatedFallback
894        )
895    }
896}
897
898/// Summary and lookup helpers for `ShaderPrecompileReport`.
899impl ShaderPrecompileReport {
900    /// Returns `true` when all registered shader programs are ready for zero-hitch rendering.
901    ///
902    /// # Returns
903    ///
904    /// - `bool` - `true` when `total_programs > 0 && ready_programs == total_programs`.
905    #[must_use]
906    pub fn is_all_ready(&self) -> bool {
907        self.get_total_programs() > 0 && self.get_ready_programs() == self.get_total_programs()
908    }
909
910    /// Looks up the cache entry for a specific `ShaderProgramId`.
911    ///
912    /// # Arguments
913    ///
914    /// - `ShaderProgramId` - Target built-in shader program identifier.
915    ///
916    /// # Returns
917    ///
918    /// - `Option<&ShaderProgramCacheEntry>` - Matching shader cache entry if present.
919    #[must_use]
920    pub fn entry_for(&self, program: ShaderProgramId) -> Option<&ShaderProgramCacheEntry> {
921        self.get_entries()
922            .iter()
923            .find(|entry: &&ShaderProgramCacheEntry| entry.get_program() == program)
924    }
925
926    /// Formats a single-line telemetry summary suitable for HUD badges and developer inspector cards.
927    ///
928    /// # Returns
929    ///
930    /// - `String` - Formatted shader precompile status line.
931    #[must_use]
932    pub fn summary_line(&self) -> String {
933        let mode_label: &str = if self.get_binary_archive_hit() {
934            "Disk Archive Hit"
935        } else if self.get_cache_hit() {
936            "Warm PSO Hit"
937        } else if self.get_hardware_gpu() {
938            "GPU Compiled"
939        } else {
940            SHADER_STATE_LABEL_VALIDATED_FALLBACK
941        };
942        let cold_ms: f64 = (self.get_cold_compile_us() as f64) / 1000.0;
943        let call_ms: f64 = (self.get_last_call_us() as f64) / 1000.0;
944        format!(
945            "PSO {}/{} ({mode_label}) | {} | Cold {cold_ms:.2}ms -> Call {call_ms:.3}ms",
946            self.get_ready_programs(),
947            self.get_total_programs(),
948            self.get_device_name(),
949        )
950    }
951}