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