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
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,
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,
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);
}
}
/// 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;
}
/// 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 a live compiled GPU blur pipeline and an attached presentation surface.
///
/// # 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_surface_layer_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,
glyph_r8_texture_handle,
glyph_rgba8_texture_handle,
image_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;
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(*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 w: u32 = x1.saturating_sub(x0);
let h: u32 = y1.saturating_sub(y0);
if w == 0 || h == 0 {
None
} else {
Some(Self::new(x0, y0, w, h))
}
}
/// 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(ts) if ts > 0 && !is_sim => {
self.set_last_presented_timestamp_ns(Some(ts));
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,
}
}
}