euv-core 0.53.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
use super::*;

/// Default `NativeGpuDriver` targets headless recording fallback.
impl Default for NativeGpuDriver {
    /// Creates a headless `NativeGpuDriver`.
    ///
    /// # Returns
    ///
    /// - `Self` - Headless GPU driver.
    fn default() -> Self {
        Self::probe(GraphicsBackend::Headless)
    }
}

/// Construction, surface attachment, texture dirty-rect upload, and pipeline query helpers for `NativeGpuDriver`.
impl NativeGpuDriver {
    /// Probes the active OS GPU hardware, loads or compiles cached native pipelines, and returns a live `NativeGpuDriver`.
    ///
    /// # Arguments
    ///
    /// - `GraphicsBackend` - Requested graphics backend.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized native GPU driver with automatic headless fallback.
    #[must_use]
    pub fn probe(backend: GraphicsBackend) -> Self {
        let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
        let mut fallback: RecordingGpuDriver = RecordingGpuDriver::default();
        fallback.set_backend_kind(backend);
        Self {
            adapter: probed.adapter,
            device_handle: probed.device_handle,
            queue_handle: probed.queue_handle,
            library_handle: probed.library_handle,
            pipeline_handle: probed.pipeline_handle,
            blur_pipeline_handle: probed.blur_pipeline_handle,
            blur_up_pipeline_handle: probed.blur_up_pipeline_handle,
            engine3d_pipeline_handle: probed.engine3d_pipeline_handle,
            ocean_pipeline_handle: probed.ocean_pipeline_handle,
            scene_ocean_pipeline_handle: probed.scene_ocean_pipeline_handle,
            scene_boat_pipeline_handle: probed.scene_boat_pipeline_handle,
            scene_3d_sky_pipeline_handle: probed.scene_3d_sky_pipeline_handle,
            scene_3d_mesh_pipeline_handle: probed.scene_3d_mesh_pipeline_handle,
            scene_depth_stencil_handle: probed.scene_depth_stencil_handle,
            scene_color_texture_handle: 0,
            scene_depth_texture_handle: 0,
            scene_wake_texture_handle: 0,
            scene_wake_texture_handles: [0; GPU_DRIVER_RING_SLOTS],
            scene_texture_dims: (0, 0),
            scene_3d_vertex_buffer_handle: 0,
            scene_3d_vertex_revision: 0,
            scene_3d_vertex_capacity: 0,
            scene_3d_instance_buffer_handle: 0,
            scene_3d_instance_capacity: 0,
            scene_3d_instance_buffer_handles: [0; GPU_DRIVER_RING_SLOTS],
            scene_3d_instance_capacities: [0; GPU_DRIVER_RING_SLOTS],
            scene_boat_buffer_handle: 0,
            scene_boat_capacity: 0,
            scene_boat_buffer_handles: [0; GPU_DRIVER_RING_SLOTS],
            scene_boat_capacities: [0; GPU_DRIVER_RING_SLOTS],
            pending_gpu_scene_pass: None,
            surface_layer_handle: 0,
            glyph_r8_texture_handle: probed.dummy_r8_tex,
            glyph_rgba8_texture_handle: probed.dummy_rgba8_tex,
            image_texture_handle: retain_native_gpu_object(probed.dummy_rgba8_tex),
            external_texture_handle: 0,
            blur_scene_texture_handle: 0,
            blur_half_texture_handle: 0,
            blur_full_texture_handle: 0,
            blur_texture_dims: (0, 0),
            ring_slots: [NativeGpuRingSlot::default(); GPU_DRIVER_RING_SLOTS],
            ring_cursor: 0,
            staging_buffer_handle: 0,
            staging_contents_ptr: 0,
            staging_buffer_capacity: 0,
            submitted_frames: 0,
            uploaded_instances: 0,
            uploaded_bytes: 0,
            last_upload_bytes: 0,
            last_submitted_batches: 0,
            staging_reallocations: 0,
            last_presented_time_ns: 0,
            last_gpu_exec_ns: 0,
            #[cfg(any(target_os = "macos", target_os = "ios"))]
            scratch_primitives: Vec::new(),
            fallback,
        }
    }

    /// Re-initializes the GPU driver for `backend`, releasing any previously retained OS handles.
    ///
    /// # Arguments
    ///
    /// - `GraphicsBackend` - Target graphics backend.
    pub fn switch_backend(&mut self, backend: GraphicsBackend) {
        if self.get_adapter().get_backend() == backend {
            return;
        }
        *self = Self::probe(backend);
    }

    /// Attaches a native `CAMetalLayer*` (or equivalent surface layer) for zero-readback hardware presentation.
    ///
    /// # Arguments
    ///
    /// - `usize` - Native `CAMetalLayer*` pointer (`0` detaches).
    pub fn attach_metal_layer(&mut self, layer_handle: usize) {
        let dev: usize = self.get_device_handle();
        let Self {
            surface_layer_handle,
            ..
        } = self;
        *surface_layer_handle = layer_handle;
        if dev != 0 && layer_handle != 0 {
            configure_native_metal_layer(dev, layer_handle);
        }
    }

    /// Configures `CAMetalLayer.displaySyncEnabled` on macOS to switch between tear-free native VRR sync (`true`) and uncapped non-blocking hardware presentation (`false`).
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` for hardware display sync; `false` for uncapped non-blocking presentation.
    pub fn set_display_sync_enabled(&mut self, enabled: bool) {
        let layer_handle: usize = self.get_surface_layer_handle();
        if layer_handle != 0 {
            configure_native_metal_display_sync(layer_handle, enabled);
        }
    }

    /// Binds an external shared-device GPU texture handle (3D game render target or hardware video surface).
    ///
    /// # Arguments
    ///
    /// - `usize` - Native external texture handle (`0` restores fallback dummy texture).
    pub fn set_external_texture(&mut self, texture_handle: usize) {
        let Self {
            external_texture_handle,
            ..
        } = self;
        *external_texture_handle = texture_handle;
    }

    /// Stages an optional hardware GPU Ocean or 3D PBR offscreen scene pass for execution in the next frame's command buffer.
    ///
    /// # Arguments
    ///
    /// - `Option<DirectGpuScenePass>` - Hardware scene pass rendered before UI compositing, or `None`.
    pub fn set_pending_gpu_scene_pass(&mut self, pass: Option<DirectGpuScenePass>) {
        let Self {
            pending_gpu_scene_pass,
            ..
        } = self;
        *pending_gpu_scene_pass = pass;
    }

    /// Uploads a dirty R8 or RGBA8 sub-rectangle to the resident glyph atlas or image texture on GPU.
    ///
    /// # Arguments
    ///
    /// - `GpuAtlasPixelFormat` - Target texture pixel format (`R8Unorm` or `Rgba8Unorm`).
    /// - `u8` - Texture slot (`0` = R8 glyph atlas, `1` = RGBA8 color glyph atlas, `2` = UI image texture).
    /// - `(u32, u32)` - Full backing texture dimensions `(width, height)`.
    /// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
    /// - `&[u8]` - Source pixel bytes.
    /// - `usize` - Row stride in bytes.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly to hardware GPU memory.
    pub fn upload_texture_dirty_rect(
        &mut self,
        format: GpuAtlasPixelFormat,
        texture_slot: u8,
        tex_dims: (u32, u32),
        dirty_rect: (u32, u32, u32, u32),
        bytes: &[u8],
        bytes_per_row: usize,
    ) -> bool {
        let dev: usize = self.get_device_handle();
        let Self {
            glyph_r8_texture_handle,
            glyph_rgba8_texture_handle,
            image_texture_handle,
            ..
        } = self;
        let target: &mut usize = match texture_slot {
            0 => glyph_r8_texture_handle,
            1 => glyph_rgba8_texture_handle,
            _ => image_texture_handle,
        };
        upload_native_texture_dirty_rect(
            dev,
            target,
            format,
            tex_dims,
            dirty_rect,
            bytes,
            bytes_per_row,
        )
    }

    /// Returns `true` when the driver has both Dual-Kawase `blur_down` and `blur_up` hardware pipelines compiled.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `BackdropBlur` can execute natively on GPU without CPU fallback.
    #[must_use]
    pub fn supports_backdrop_blur_pass(&self) -> bool {
        self.get_blur_pipeline_handle() != 0 && self.get_blur_up_pipeline_handle() != 0
    }

    /// Executes Pass 3 Dual-Kawase `blur_down` + `blur_up` ping-pong passes on hardware GPU for `blur_passes`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Physical surface width in pixels.
    /// - `u32` - Physical surface height in pixels.
    /// - `&[GpuBackdropBlurPass]` - Active Dual-Kawase backdrop blur regions.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of Dual-Kawase blur regions executed on hardware GPU (`0` when unsupported).
    pub fn execute_dual_kawase_blur_passes(
        &mut self,
        width: u32,
        height: u32,
        blur_passes: &[GpuBackdropBlurPass],
    ) -> usize {
        execute_native_dual_kawase_blur_passes(self, width, height, blur_passes)
    }

    /// Returns the count of resident hardware GPU render pipeline state objects (`UI`, `Blur`, `3D PBR`, `Fluid Ocean`) currently cached on this driver.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of non-zero resident hardware pipeline handles (`0..=4`).
    #[must_use]
    pub fn precompiled_pipeline_count(&self) -> usize {
        usize::from(self.get_pipeline_handle() != 0)
            + usize::from(
                self.get_blur_pipeline_handle() != 0 && self.get_blur_up_pipeline_handle() != 0,
            )
            + usize::from(self.get_engine3d_pipeline_handle() != 0)
            + usize::from(self.get_ocean_pipeline_handle() != 0)
    }
}

/// `GpuDriver` implementation uploading packed 64-byte `GpuPrimitiveInstance` streams to the active physical OS GPU.
impl GpuDriver for NativeGpuDriver {
    /// Returns the resolved `GraphicsBackend`.
    ///
    /// # Returns
    ///
    /// - `GraphicsBackend` - Active backend tag.
    fn backend(&self) -> GraphicsBackend {
        self.get_adapter().get_backend()
    }

    /// Returns the native shader source compiled by this GPU backend.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Native shader program source.
    fn shader_source(&self) -> &'static str {
        self.get_fallback().shader_source()
    }

    /// Uploads instanced 64-byte primitive batches through the 3-slot fenced ring and records draw telemetry.
    ///
    /// # Arguments
    ///
    /// - `u32` - Surface width.
    /// - `u32` - Surface height.
    /// - `Color` - Surface clear color.
    /// - `&[GpuBatch]` - Ordered draw batches.
    ///
    /// # Returns
    ///
    /// - `Result<usize, PlatformError>` - Number of submitted GPU draw calls.
    fn submit_batches(
        &mut self,
        width: u32,
        height: u32,
        clear_color: Color,
        batches: &[GpuBatch],
    ) -> Result<usize, PlatformError> {
        let uploaded: usize =
            submit_native_gpu_ring_frame(self, width, height, clear_color, batches);
        let frame_bytes: usize = uploaded.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
        let Self {
            submitted_frames,
            uploaded_instances,
            uploaded_bytes,
            last_upload_bytes,
            last_submitted_batches,
            last_presented_time_ns,
            last_gpu_exec_ns,
            fallback,
            ..
        } = self;
        *submitted_frames = submitted_frames.wrapping_add(1);
        *uploaded_instances = uploaded_instances.wrapping_add(uploaded as u64);
        *uploaded_bytes = uploaded_bytes.wrapping_add(frame_bytes as u64);
        *last_upload_bytes = frame_bytes;
        *last_submitted_batches = batches.len();
        *last_presented_time_ns = native_gpu_last_presented_ns();
        *last_gpu_exec_ns = native_gpu_last_exec_ns();
        fallback.submit_batches(width, height, clear_color, batches)
    }
}

/// Automatic native GPU handle cleanup when `NativeGpuDriver` is dropped.
impl Drop for NativeGpuDriver {
    /// Releases retained OS GPU ring buffers, in-flight command buffers, textures, pipelines, and device handles.
    fn drop(&mut self) {
        let Self {
            device_handle,
            queue_handle,
            library_handle,
            pipeline_handle,
            blur_pipeline_handle,
            blur_up_pipeline_handle,
            engine3d_pipeline_handle,
            ocean_pipeline_handle,
            scene_ocean_pipeline_handle,
            scene_boat_pipeline_handle,
            scene_3d_sky_pipeline_handle,
            scene_3d_mesh_pipeline_handle,
            scene_depth_stencil_handle,
            scene_color_texture_handle,
            scene_depth_texture_handle,
            scene_wake_texture_handle,
            scene_wake_texture_handles,
            scene_3d_vertex_buffer_handle,
            scene_3d_instance_buffer_handle,
            scene_3d_instance_buffer_handles,
            scene_3d_instance_capacities,
            scene_boat_buffer_handle,
            scene_boat_buffer_handles,
            scene_boat_capacities,
            glyph_r8_texture_handle,
            glyph_rgba8_texture_handle,
            image_texture_handle,
            blur_scene_texture_handle,
            blur_half_texture_handle,
            blur_full_texture_handle,
            ring_slots,
            staging_buffer_handle,
            staging_contents_ptr,
            staging_buffer_capacity,
            ..
        } = self;
        for slot in ring_slots.iter_mut() {
            let cmd: usize = slot.get_in_flight_cmd_buffer();
            if cmd != 0 {
                release_native_gpu_object(cmd);
                slot.set_in_flight_cmd_buffer(0);
            }
            let buf: usize = slot.get_buffer_handle();
            if buf != 0 {
                release_native_gpu_object(buf);
                slot.set_buffer_handle(0);
                slot.set_contents_ptr(0);
                slot.set_capacity_bytes(0);
            }
        }
        *staging_buffer_handle = 0;
        *staging_contents_ptr = 0;
        *staging_buffer_capacity = 0;
        for slot_idx in 0..GPU_DRIVER_RING_SLOTS {
            release_native_gpu_object(scene_3d_instance_buffer_handles[slot_idx]);
            scene_3d_instance_buffer_handles[slot_idx] = 0;
            scene_3d_instance_capacities[slot_idx] = 0;
            release_native_gpu_object(scene_boat_buffer_handles[slot_idx]);
            scene_boat_buffer_handles[slot_idx] = 0;
            scene_boat_capacities[slot_idx] = 0;
            release_native_gpu_object(scene_wake_texture_handles[slot_idx]);
            scene_wake_texture_handles[slot_idx] = 0;
        }
        *scene_3d_instance_buffer_handle = 0;
        *scene_boat_buffer_handle = 0;
        *scene_wake_texture_handle = 0;
        release_native_gpu_object(*blur_scene_texture_handle);
        release_native_gpu_object(*blur_half_texture_handle);
        release_native_gpu_object(*blur_full_texture_handle);
        release_native_gpu_object(*scene_color_texture_handle);
        release_native_gpu_object(*scene_depth_texture_handle);
        release_native_gpu_object(*scene_3d_vertex_buffer_handle);
        release_native_gpu_object(*scene_depth_stencil_handle);
        release_native_gpu_object(*scene_3d_mesh_pipeline_handle);
        release_native_gpu_object(*scene_3d_sky_pipeline_handle);
        release_native_gpu_object(*scene_boat_pipeline_handle);
        release_native_gpu_object(*scene_ocean_pipeline_handle);
        release_native_gpu_object(*glyph_r8_texture_handle);
        release_native_gpu_object(*glyph_rgba8_texture_handle);
        release_native_gpu_object(*image_texture_handle);
        release_native_gpu_object(*ocean_pipeline_handle);
        release_native_gpu_object(*engine3d_pipeline_handle);
        release_native_gpu_object(*blur_up_pipeline_handle);
        release_native_gpu_object(*blur_pipeline_handle);
        release_native_gpu_object(*pipeline_handle);
        release_native_gpu_handles(*device_handle, *queue_handle, *library_handle);
    }
}

/// Geometry and byte-size helpers for `PixelDirtyRect`.
impl PixelDirtyRect {
    /// Returns the exclusive right pixel edge (`x + width`).
    ///
    /// # Returns
    ///
    /// - `u32` - Exclusive right coordinate in pixels.
    #[must_use]
    pub fn right(&self) -> u32 {
        self.get_x().saturating_add(self.get_width())
    }

    /// Returns the exclusive bottom pixel edge (`y + height`).
    ///
    /// # Returns
    ///
    /// - `u32` - Exclusive bottom coordinate in pixels.
    #[must_use]
    pub fn bottom(&self) -> u32 {
        self.get_y().saturating_add(self.get_height())
    }

    /// Returns `true` when either width or height is zero.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the rectangle covers zero pixels.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.get_width() == 0 || self.get_height() == 0
    }

    /// Returns the covered pixel count (`width * height`).
    ///
    /// # Returns
    ///
    /// - `usize` - Total covered pixels.
    #[must_use]
    pub fn area_pixels(&self) -> usize {
        (self.get_width() as usize).saturating_mul(self.get_height() as usize)
    }

    /// Returns the RGBA8 byte payload size (`width * height * 4`).
    ///
    /// # Returns
    ///
    /// - `usize` - Payload size in bytes.
    #[must_use]
    pub fn byte_size_rgba8(&self) -> usize {
        self.area_pixels().saturating_mul(4)
    }

    /// Clamps this rectangle strictly inside `(fb_w, fb_h)` surface bounds.
    ///
    /// # Arguments
    ///
    /// - `u32` - Surface width in pixels.
    /// - `u32` - Surface height in pixels.
    ///
    /// # Returns
    ///
    /// - `Option<Self>` - Clamped non-empty rectangle, or `None` when outside bounds.
    #[must_use]
    pub fn clamp_to(&self, fb_w: u32, fb_h: u32) -> Option<Self> {
        let x0: u32 = self.get_x().min(fb_w);
        let y0: u32 = self.get_y().min(fb_h);
        let x1: u32 = self.right().min(fb_w);
        let y1: u32 = self.bottom().min(fb_h);
        let width_val: u32 = x1.saturating_sub(x0);
        let height_val: u32 = y1.saturating_sub(y0);
        if width_val == 0 || height_val == 0 {
            None
        } else {
            Some(Self::new(x0, y0, width_val, height_val))
        }
    }

    /// Returns the smallest enclosing bounding rectangle containing both `self` and `other`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Other pixel rectangle.
    ///
    /// # Returns
    ///
    /// - `Self` - Enclosing union rectangle.
    #[must_use]
    pub fn union_with(&self, other: Self) -> Self {
        if self.is_empty() {
            return other;
        }
        if other.is_empty() {
            return *self;
        }
        let x0: u32 = self.get_x().min(other.get_x());
        let y0: u32 = self.get_y().min(other.get_y());
        let x1: u32 = self.right().max(other.right());
        let y1: u32 = self.bottom().max(other.bottom());
        Self::new(x0, y0, x1.saturating_sub(x0), y1.saturating_sub(y0))
    }

    /// Returns `true` when `self` and `other` overlap or lie within `pad_px` pixels of each other.
    ///
    /// # Arguments
    ///
    /// - `Self` - Other pixel rectangle.
    /// - `u32` - Adjacency tolerance in pixels.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the two rectangles overlap or are adjacent within `pad_px`.
    #[must_use]
    pub fn intersects_or_adjacent(&self, other: Self, pad_px: u32) -> bool {
        if self.is_empty() || other.is_empty() {
            return false;
        }
        let ax0: u32 = self.get_x().saturating_sub(pad_px);
        let ay0: u32 = self.get_y().saturating_sub(pad_px);
        let ax1: u32 = self.right().saturating_add(pad_px);
        let ay1: u32 = self.bottom().saturating_add(pad_px);
        ax0 <= other.right()
            && ax1 >= other.get_x()
            && ay0 <= other.bottom()
            && ay1 >= other.get_y()
    }
}

/// Zero-copy borrowed atlas accessors for `DirectGpuFrameBatch`.
impl DirectGpuFrameBatch {
    /// Returns a borrowed reference to the optional R8 monochrome glyph atlas upload without cloning.
    ///
    /// # Returns
    ///
    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed R8 glyph atlas upload when present.
    #[must_use]
    pub fn glyph_r8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
        let Self { glyph_r8_atlas, .. } = self;
        glyph_r8_atlas.as_ref()
    }

    /// Returns a borrowed reference to the optional RGBA8 image atlas upload without cloning.
    ///
    /// # Returns
    ///
    /// - `Option<&DirectGpuAtlasUpload>` - Borrowed RGBA8 image atlas upload when present.
    #[must_use]
    pub fn image_rgba8_atlas_ref(&self) -> Option<&DirectGpuAtlasUpload> {
        let Self {
            image_rgba8_atlas, ..
        } = self;
        image_rgba8_atlas.as_ref()
    }
}

/// Telemetry recording and simulator-honesty methods for `MobilePresentTelemetry`.
impl MobilePresentTelemetry {
    /// Creates an initialized telemetry snapshot configured for `active_path`, `display_mode_hz`, and simulator status.
    ///
    /// # Arguments
    ///
    /// - `MobilePresentPath` - Active presentation channel.
    /// - `f32` - Display refresh rate in Hertz.
    /// - `bool` - `true` when executing inside a simulator where compositor timestamps are unobservable.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured mobile presentation telemetry state.
    #[must_use]
    pub fn for_host(
        active_path: MobilePresentPath,
        display_mode_hz: f32,
        is_simulator: bool,
    ) -> Self {
        let cpu_mirror_active: bool = active_path != MobilePresentPath::GpuDirect;
        let upload_strategy: MobileUploadStrategy = match active_path {
            MobilePresentPath::GpuDirect => MobileUploadStrategy::DirectGpu,
            MobilePresentPath::GpuUpload | MobilePresentPath::Software => {
                MobileUploadStrategy::FullFrame
            }
        };
        let (timing_source, unobservable_reason): (
            MobilePresentTimingSource,
            Option<&'static str>,
        ) = if is_simulator {
            (
                MobilePresentTimingSource::SubmissionProxy,
                Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR),
            )
        } else {
            (MobilePresentTimingSource::Unobservable, None)
        };
        Self {
            active_path,
            upload_strategy,
            cpu_mirror_active,
            timing_source,
            unobservable_reason,
            is_simulator,
            display_mode_hz: display_mode_hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ),
            frame_callback_count: 0,
            last_callback_timestamp_ns: 0,
            last_callback_interval_ms: None,
            last_target_timestamp_ns: None,
            last_presented_timestamp_ns: None,
            actual_presented_frames: 0,
            upload_bytes_last_frame: 0,
            upload_bytes_total: 0,
            primitive_count_last_frame: 0,
            draw_calls_last_frame: 0,
            submit_failures: 0,
            present_failures: 0,
            context_loss_count: 0,
            blank_frames_prevented: 0,
            last_valid_frame_retained: false,
        }
    }

    /// Records a VSync callback (`Choreographer.doFrame` or `CADisplayLink`) timestamp and optional target timestamp.
    ///
    /// # Arguments
    ///
    /// - `u64` - Monotonic VSync callback timestamp in nanoseconds.
    /// - `Option<u64>` - Optional target presentation deadline timestamp in nanoseconds.
    pub fn record_vsync_callback(&mut self, callback_ts_ns: u64, target_ts_ns: Option<u64>) {
        let prev_ts: u64 = self.get_last_callback_timestamp_ns();
        self.set_frame_callback_count(self.get_frame_callback_count().saturating_add(1));
        if callback_ts_ns > 0 {
            if prev_ts > 0 && callback_ts_ns > prev_ts {
                let delta_ms: f64 = ((callback_ts_ns - prev_ts) as f64) / 1_000_000.0;
                self.set_last_callback_interval_ms(Some(delta_ms));
            }
            self.set_last_callback_timestamp_ns(callback_ts_ns);
        }
        if let Some(target_ns) = target_ts_ns
            && target_ns > 0
        {
            self.set_last_target_timestamp_ns(Some(target_ns));
        }
    }

    /// Records a successful frame presentation with exact path, upload strategy, byte count, and draw telemetry.
    ///
    /// # Arguments
    ///
    /// - `MobilePresentPath` - Active presentation channel executed for this frame.
    /// - `MobileUploadStrategy` - Upload strategy executed for this frame.
    /// - `u64` - Payload bytes uploaded to GPU or native surface memory.
    /// - `u32` - Number of 64-byte `GpuPrimitiveInstance` records emitted (`0` on upload/software).
    /// - `u32` - Number of GPU draw calls emitted.
    /// - `Option<u64>` - Optional hardware compositor presentation timestamp in nanoseconds (`None` when unobservable).
    pub fn record_presented_frame(
        &mut self,
        path: MobilePresentPath,
        strategy: MobileUploadStrategy,
        upload_bytes: u64,
        primitive_count: u32,
        draw_calls: u32,
        compositor_presented_ns: Option<u64>,
    ) {
        self.set_active_path(path);
        self.set_upload_strategy(strategy);
        self.set_cpu_mirror_active(path != MobilePresentPath::GpuDirect);
        self.set_upload_bytes_last_frame(upload_bytes);
        self.set_upload_bytes_total(self.get_upload_bytes_total().saturating_add(upload_bytes));
        self.set_primitive_count_last_frame(primitive_count);
        self.set_draw_calls_last_frame(draw_calls);
        self.set_actual_presented_frames(self.get_actual_presented_frames().saturating_add(1));
        self.set_last_valid_frame_retained(true);
        self.record_compositor_present_timestamp(compositor_presented_ns);
    }

    /// Records an observed compositor presentation timestamp while honestly marking simulator or missing timestamps unobservable.
    ///
    /// # Arguments
    ///
    /// - `Option<u64>` - Compositor presentation timestamp in nanoseconds (`None` or `Some(0)` when unobservable).
    pub fn record_compositor_present_timestamp(&mut self, presented_ns: Option<u64>) {
        let is_sim: bool = self.get_is_simulator();
        match presented_ns {
            Some(timestamp_val) if timestamp_val > 0 && !is_sim => {
                self.set_last_presented_timestamp_ns(Some(timestamp_val));
                self.set_timing_source(MobilePresentTimingSource::CompositorMeasured);
                self.set_unobservable_reason(None);
            }
            _ if is_sim => {
                self.set_last_presented_timestamp_ns(None);
                self.set_timing_source(MobilePresentTimingSource::SubmissionProxy);
                self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_SIMULATOR));
            }
            _ => {
                self.set_last_presented_timestamp_ns(None);
                self.set_timing_source(MobilePresentTimingSource::Unobservable);
                self.set_unobservable_reason(Some(MOBILE_TIMING_UNOBSERVABLE_REASON_UNSUPPORTED));
            }
        }
    }

    /// Records a frame submission or presentation fault without fabricating a presented frame.
    ///
    /// # Arguments
    ///
    /// - `MobileSurfaceFault` - Fault category observed during submit or present.
    /// - `bool` - `true` when the last valid frame was retained to prevent submitting a blank frame.
    pub fn record_fault(&mut self, fault: MobileSurfaceFault, blank_prevented: bool) {
        match fault {
            MobileSurfaceFault::ContextLost => {
                self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
                self.set_present_failures(self.get_present_failures().saturating_add(1));
            }
            MobileSurfaceFault::SurfaceLost | MobileSurfaceFault::SubmitFailed => {
                self.set_submit_failures(self.get_submit_failures().saturating_add(1));
            }
            MobileSurfaceFault::ShaderCompileFailed => {
                self.set_submit_failures(self.get_submit_failures().saturating_add(1));
            }
        }
        if blank_prevented {
            self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
        }
    }
}

/// Immediate zero-blank-frame failover logic for `MobileFailoverController`.
impl Default for MobileFailoverController {
    /// Creates a failover controller preferring `GpuDirect` with both `GpuUpload` and `Software` fallbacks enabled.
    ///
    /// # Returns
    ///
    /// - `Self` - Default GPU-first failover controller.
    fn default() -> Self {
        Self::for_preferred(MobilePresentPath::GpuDirect, true, true)
    }
}

/// Fault-handling and path-selection methods for `MobileFailoverController`.
impl MobileFailoverController {
    /// Creates a failover controller honoring `preferred_path` and detected hardware capabilities.
    ///
    /// # Arguments
    ///
    /// - `MobilePresentPath` - Preferred initial presentation path.
    /// - `bool` - `true` when direct GPU uber-shader rendering is available.
    /// - `bool` - `true` when GPU texture upload rendering is available.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured failover controller with an immediately runnable active path.
    #[must_use]
    pub fn for_preferred(
        preferred_path: MobilePresentPath,
        direct_gpu_available: bool,
        gpu_upload_available: bool,
    ) -> Self {
        let active_path: MobilePresentPath = match preferred_path {
            MobilePresentPath::GpuDirect if direct_gpu_available => MobilePresentPath::GpuDirect,
            MobilePresentPath::GpuDirect | MobilePresentPath::GpuUpload if gpu_upload_available => {
                MobilePresentPath::GpuUpload
            }
            _ => MobilePresentPath::Software,
        };
        Self {
            active_path,
            preferred_path,
            has_valid_presented_frame: false,
            window_valid: true,
            direct_gpu_available,
            gpu_upload_available,
            context_loss_count: 0,
            blank_frames_prevented: 0,
            fallback_transitions: 0,
        }
    }

    /// Returns `true` when the active presentation path requires a CPU framebuffer mirror (`false` on `GpuDirect`).
    ///
    /// # Returns
    ///
    /// - `bool` - `false` for `GpuDirect`; `true` for `GpuUpload` and `Software`.
    #[must_use]
    pub fn cpu_mirror_active(&self) -> bool {
        self.get_active_path() != MobilePresentPath::GpuDirect
    }

    /// Marks the active window surface valid or detached (`false` clears retained-frame status on new surface).
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` when a live native window / Metal layer is attached.
    pub fn set_surface_valid(&mut self, valid: bool) {
        self.set_window_valid(valid);
        if !valid {
            self.set_has_valid_presented_frame(false);
        }
    }

    /// Records that a valid non-blank frame has been presented onto the current surface.
    pub fn mark_frame_presented(&mut self) {
        self.set_has_valid_presented_frame(true);
    }

    /// Handles a graphics context or submission fault immediately without waiting for perf comparisons while preventing blank frames.
    ///
    /// # Arguments
    ///
    /// - `MobileSurfaceFault` - Observed context, shader, surface, or submission fault.
    ///
    /// # Returns
    ///
    /// - `MobileFailoverAction` - Deterministic immediate failover instruction.
    pub fn handle_fault(&mut self, fault: MobileSurfaceFault) -> MobileFailoverAction {
        if !self.get_window_valid() {
            return MobileFailoverAction::WaitForNewSurface;
        }
        let retained: bool = self.get_has_valid_presented_frame();
        if retained {
            self.set_blank_frames_prevented(self.get_blank_frames_prevented().saturating_add(1));
        }
        match fault {
            MobileSurfaceFault::ContextLost => {
                self.set_context_loss_count(self.get_context_loss_count().saturating_add(1));
                self.set_direct_gpu_available(false);
                self.set_gpu_upload_available(false);
                let prev: MobilePresentPath = self.get_active_path();
                self.set_active_path(MobilePresentPath::Software);
                if prev != MobilePresentPath::Software {
                    self.set_fallback_transitions(
                        self.get_fallback_transitions().saturating_add(1),
                    );
                }
                MobileFailoverAction::KeepLastFrameAndSwitch(MobilePresentPath::Software)
            }
            MobileSurfaceFault::ShaderCompileFailed => {
                self.set_direct_gpu_available(false);
                let next: MobilePresentPath = if self.get_gpu_upload_available() {
                    MobilePresentPath::GpuUpload
                } else {
                    MobilePresentPath::Software
                };
                if self.get_active_path() != next {
                    self.set_active_path(next);
                    self.set_fallback_transitions(
                        self.get_fallback_transitions().saturating_add(1),
                    );
                }
                MobileFailoverAction::KeepLastFrameAndSwitch(next)
            }
            MobileSurfaceFault::SubmitFailed => {
                let next: MobilePresentPath = match self.get_active_path() {
                    MobilePresentPath::GpuDirect => {
                        if self.get_gpu_upload_available() {
                            MobilePresentPath::GpuUpload
                        } else {
                            MobilePresentPath::Software
                        }
                    }
                    MobilePresentPath::GpuUpload => MobilePresentPath::Software,
                    MobilePresentPath::Software => {
                        return MobileFailoverAction::KeepLastFrameAndRetry;
                    }
                };
                self.set_active_path(next);
                self.set_fallback_transitions(self.get_fallback_transitions().saturating_add(1));
                MobileFailoverAction::KeepLastFrameAndSwitch(next)
            }
            MobileSurfaceFault::SurfaceLost => MobileFailoverAction::KeepLastFrameAndRetry,
        }
    }
}

/// Canonical shader program listing, metadata, and per-backend source lookup for `ShaderProgramId`.
impl ShaderProgramId {
    /// Returns all built-in GPU shader programs ordered for ahead-of-time precompilation.
    ///
    /// # Returns
    ///
    /// - `[Self; 4]` - Complete ordered list of built-in shader programs.
    #[must_use]
    pub const fn all() -> [Self; 4] {
        [
            Self::UiUber,
            Self::BackdropBlur,
            Self::Engine3dPbr,
            Self::FluidOceanOptical,
        ]
    }

    /// Returns the human-readable diagnostic title for this shader program.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Descriptive shader pipeline name.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::UiUber => "UI Uber-Shader (64B SDF)",
            Self::BackdropBlur => "Dual-Kawase BackdropBlur",
            Self::Engine3dPbr => "3D Engine PBR (GGX + ACES)",
            Self::FluidOceanOptical => "Fluid Ocean Optical (Gerstner + GGX)",
        }
    }

    /// Resolves the shading language name paired with `backend`.
    ///
    /// # Arguments
    ///
    /// - `GraphicsBackend` - Active graphics API backend.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Target shading language label (`MSL`, `WGSL`, `GLSL ES 3.0`, or `HLSL SM 6.0`).
    #[must_use]
    pub const fn language_for_backend(backend: GraphicsBackend) -> &'static str {
        match backend {
            GraphicsBackend::Metal => "MSL",
            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => "GLSL ES 3.0",
            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => "HLSL SM 6.0",
            GraphicsBackend::WebGpu
            | GraphicsBackend::Vulkan
            | GraphicsBackend::SoftwareCpu
            | GraphicsBackend::Canvas2d
            | GraphicsBackend::Headless => "WGSL",
        }
    }

    /// Returns the primary and optional secondary shader source slices for this program on `backend`.
    ///
    /// # Arguments
    ///
    /// - `GraphicsBackend` - Active graphics API backend.
    ///
    /// # Returns
    ///
    /// - `(&'static str, &'static str)` - Primary shader source and optional paired fragment shader source (empty when unified).
    #[must_use]
    pub const fn source_pair(self, backend: GraphicsBackend) -> (&'static str, &'static str) {
        match (self, backend) {
            (Self::UiUber, GraphicsBackend::Metal) => (MSL_UI_SHADER, ""),
            (Self::UiUber, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => {
                (GLSL_ES3_UI_VERTEX_SHADER, GLSL_ES3_UI_FRAGMENT_SHADER)
            }
            (Self::UiUber, GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11) => {
                (HLSL_UI_SHADER, "")
            }
            (Self::UiUber, _) => (WGSL_UI_SHADER, ""),
            (Self::BackdropBlur, GraphicsBackend::Metal) => (MSL_BACKDROP_BLUR_SHADER, ""),
            (Self::BackdropBlur, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => (
                GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER,
                GLSL_ES3_BACKDROP_BLUR_FRAGMENT_SHADER,
            ),
            (Self::BackdropBlur, GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11) => {
                (HLSL_BACKDROP_BLUR_SHADER, "")
            }
            (Self::BackdropBlur, _) => (WGSL_BACKDROP_BLUR_SHADER, ""),
            (Self::Engine3dPbr, GraphicsBackend::Metal) => (MSL_ENGINE3D_PBR_SHADER, ""),
            (Self::Engine3dPbr, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => (
                GLSL_ES3_ENGINE3D_VERTEX_SHADER,
                GLSL_ES3_ENGINE3D_FRAGMENT_SHADER,
            ),
            (Self::Engine3dPbr, GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11) => {
                (HLSL_ENGINE3D_PBR_SHADER, "")
            }
            (Self::Engine3dPbr, _) => (WGSL_ENGINE3D_PBR_SHADER, ""),
            (Self::FluidOceanOptical, GraphicsBackend::Metal) => (MSL_FLUID_OCEAN_SHADER, ""),
            (Self::FluidOceanOptical, GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs) => (
                GLSL_ES3_BACKDROP_BLUR_VERTEX_SHADER,
                GLSL_ES3_FLUID_OCEAN_FRAGMENT_SHADER,
            ),
            (
                Self::FluidOceanOptical,
                GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11,
            ) => (HLSL_FLUID_OCEAN_SHADER, ""),
            (Self::FluidOceanOptical, _) => (WGSL_FLUID_OCEAN_SHADER, ""),
        }
    }
}

/// Diagnostic label and readiness query helpers for `ShaderCompileState`.
impl ShaderCompileState {
    /// Returns a concise human-readable label for UI telemetry displays.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Status label string.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Pending => "Pending",
            Self::Compiling => "Compiling",
            Self::CompiledHardware => "GPU PSO Ready",
            Self::LoadedFromBinaryArchive => "Binary Archive Hit",
            Self::ValidatedFallback => SHADER_STATE_LABEL_VALIDATED_FALLBACK,
            Self::Failed => "Fallback",
        }
    }

    /// Returns `true` when this state represents a ready precompiled or validated shader entry.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` for hardware compiled, archive hit, or validated fallback states.
    #[must_use]
    pub const fn is_ready(self) -> bool {
        matches!(
            self,
            Self::CompiledHardware | Self::LoadedFromBinaryArchive | Self::ValidatedFallback
        )
    }
}

/// Summary and lookup helpers for `ShaderPrecompileReport`.
impl ShaderPrecompileReport {
    /// Returns `true` when all registered shader programs are ready for zero-hitch rendering.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `total_programs > 0 && ready_programs == total_programs`.
    #[must_use]
    pub fn is_all_ready(&self) -> bool {
        self.get_total_programs() > 0 && self.get_ready_programs() == self.get_total_programs()
    }

    /// Looks up the cache entry for a specific `ShaderProgramId`.
    ///
    /// # Arguments
    ///
    /// - `ShaderProgramId` - Target built-in shader program identifier.
    ///
    /// # Returns
    ///
    /// - `Option<&ShaderProgramCacheEntry>` - Matching shader cache entry if present.
    #[must_use]
    pub fn entry_for(&self, program: ShaderProgramId) -> Option<&ShaderProgramCacheEntry> {
        self.get_entries()
            .iter()
            .find(|entry: &&ShaderProgramCacheEntry| entry.get_program() == program)
    }

    /// Formats a single-line telemetry summary suitable for HUD badges and developer inspector cards.
    ///
    /// # Returns
    ///
    /// - `String` - Formatted shader precompile status line.
    #[must_use]
    pub fn summary_line(&self) -> String {
        let mode_label: &str = if self.get_binary_archive_hit() {
            "Disk Archive Hit"
        } else if self.get_cache_hit() {
            "Warm PSO Hit"
        } else if self.get_hardware_gpu() {
            "GPU Compiled"
        } else {
            SHADER_STATE_LABEL_VALIDATED_FALLBACK
        };
        let cold_ms: f64 = (self.get_cold_compile_us() as f64) / 1000.0;
        let call_ms: f64 = (self.get_last_call_us() as f64) / 1000.0;
        format!(
            "PSO {}/{} ({mode_label}) | {} | Cold {cold_ms:.2}ms -> Call {call_ms:.3}ms",
            self.get_ready_programs(),
            self.get_total_programs(),
            self.get_device_name(),
        )
    }
}