euv-core 0.48.2

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
use super::*;

#[link(name = "objc")]
unsafe extern "C" {
    /// Body of the `objc_getClass` free function.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - A `*const c_char` parameter.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn objc_getClass(name: *const c_char) -> *mut c_void;
    /// Body of the `sel_registerName` free function.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - A `*const c_char` parameter.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn sel_registerName(name: *const c_char) -> *mut c_void;
    /// Body of the `objc_msgSend` free function.
    fn objc_msgSend();
}

#[link(name = "UIKit", kind = "framework")]
unsafe extern "C" {}

#[link(name = "QuartzCore", kind = "framework")]
unsafe extern "C" {}

#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
    /// Copies pixel bytes into an immutable CoreFoundation `CFDataRef` safe for async CoreAnimation retention.
    ///
    /// # Arguments
    ///
    /// - `*const c_void` - Optional allocator (`null` for default).
    /// - `*const u8` - Source RGBA8 pixel bytes.
    /// - `isize` - Byte count.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Retained `CFDataRef`.
    fn CFDataCreate(allocator: *const c_void, bytes: *const u8, length: isize) -> *mut c_void;
    /// Releases a retained CoreFoundation object.
    ///
    /// # Arguments
    ///
    /// - `*const c_void` - CoreFoundation object pointer.
    fn CFRelease(cf: *const c_void);
}

#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
    /// Body of the `CGColorSpaceCreateDeviceRGB` free function.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn CGColorSpaceCreateDeviceRGB() -> *mut c_void;
    /// Body of the `CGColorSpaceRelease` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    fn CGColorSpaceRelease(space: *mut c_void);
    /// Creates a `CGDataProviderRef` retaining an immutable `CFDataRef` without dangling pointers.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Retained `CFDataRef` backing the image pixels.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Retained `CGDataProviderRef`.
    fn CGDataProviderCreateWithCFData(data: *mut c_void) -> *mut c_void;
    /// Body of the `CGDataProviderRelease` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    fn CGDataProviderRelease(provider: *mut c_void);
    /// Body of the `CGImageCreate` free function.
    ///
    /// # Arguments
    ///
    /// - `usize` - A non-negative integer (`usize`).
    /// - `usize` - A non-negative integer (`usize`).
    /// - `usize` - A non-negative integer (`usize`).
    /// - `usize` - A non-negative integer (`usize`).
    /// - `usize` - A non-negative integer (`usize`).
    /// - `*mut c_void` - A `*mut c_void` parameter.
    /// - `u32` - A 32-bit unsigned integer (`u32`).
    /// - `*mut c_void` - A `*mut c_void` parameter.
    /// - `*const f64` - A `*const f64` parameter.
    /// - `bool` - A boolean (`bool`).
    /// - `i32` - A 32-bit signed integer (`i32`).
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - A `*mut c_void` value.
    fn CGImageCreate(
        width: usize,
        height: usize,
        bits_per_component: usize,
        bits_per_pixel: usize,
        bytes_per_row: usize,
        space: *mut c_void,
        bitmap_info: u32,
        provider: *mut c_void,
        decode: *const f64,
        should_interpolate: bool,
        intent: i32,
    ) -> *mut c_void;
    /// Body of the `CGImageRelease` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    fn CGImageRelease(image: *mut c_void);
}

/// Sends a 0-arg Objective-C message returning a pointer on iOS / iPadOS.
///
/// # Arguments
///
/// - `*mut c_void` - Objective-C receiver.
/// - `*mut c_void` - Selector pointer.
///
/// # Returns
///
/// - `*mut c_void` - Returned object pointer.
pub(crate) fn uikit_send_ptr0(receiver: *mut c_void, sel: *mut c_void) -> *mut c_void {
    if receiver.is_null() {
        return null_mut();
    }
    // SAFETY: Matches 64-bit ARM64/x86_64 Apple Objective-C ABI for 0-arg pointer return.
    unsafe {
        let func: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
            transmute(objc_msgSend as *const ());
        func(receiver, sel)
    }
}

/// Sends a 0-arg Objective-C message returning `isize` (`NSInteger`).
///
/// # Arguments
///
/// - `*mut c_void` - Objective-C receiver.
/// - `*mut c_void` - Selector pointer.
///
/// # Returns
///
/// - `isize` - Returned `NSInteger`.
pub(crate) fn uikit_send_isize0(receiver: *mut c_void, sel: *mut c_void) -> isize {
    if receiver.is_null() {
        return 0;
    }
    // SAFETY: Matches 64-bit Apple Objective-C ABI for `NSInteger`.
    unsafe {
        let func: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
            transmute(objc_msgSend as *const ());
        func(receiver, sel)
    }
}

/// Sends a 0-arg Objective-C message returning `f64` (`CGFloat`).
///
/// # Arguments
///
/// - `*mut c_void` - Objective-C receiver.
/// - `*mut c_void` - Selector pointer.
///
/// # Returns
///
/// - `f64` - Returned `CGFloat`.
pub(crate) fn uikit_send_f64_0(receiver: *mut c_void, sel: *mut c_void) -> f64 {
    if receiver.is_null() {
        return 2.0;
    }
    // SAFETY: Matches 64-bit Apple Objective-C ABI for `CGFloat`.
    unsafe {
        let func: unsafe extern "C" fn(*mut c_void, *mut c_void) -> f64 =
            transmute(objc_msgSend as *const ());
        func(receiver, sel)
    }
}

/// Queries `UIDevice.currentDevice.userInterfaceIdiom` to distinguish iOS Phone vs iPadOS Tablet.
///
/// # Returns
///
/// - `PlatformKind` - `PlatformKind::IpadOs` on iPad hardware, `PlatformKind::Ios` on iPhone.
#[must_use]
pub fn ios_detect_platform_kind() -> PlatformKind {
    // SAFETY: Static null-terminated Objective-C class and selector names.
    let (device_cls, sel_current, sel_idiom): (*mut c_void, *mut c_void, *mut c_void) = unsafe {
        (
            objc_getClass(UIKIT_CLS_UI_DEVICE.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_CURRENT_DEVICE.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_USER_INTERFACE_IDIOM.as_ptr().cast::<c_char>()),
        )
    };
    let device: *mut c_void = uikit_send_ptr0(device_cls, sel_current);
    let idiom: isize = uikit_send_isize0(device, sel_idiom);
    if idiom == UI_USER_INTERFACE_IDIOM_PAD {
        PlatformKind::IpadOs
    } else {
        PlatformKind::Ios
    }
}

/// Queries the native Retina scale factor via `UIScreen.mainScreen.nativeScale`.
///
/// # Returns
///
/// - `f32` - Device scale factor (`2.0` or `3.0`).
#[must_use]
pub fn ios_screen_scale() -> f32 {
    // SAFETY: Static null-terminated Objective-C class and selector names.
    let (screen_cls, sel_main, sel_scale): (*mut c_void, *mut c_void, *mut c_void) = unsafe {
        (
            objc_getClass(UIKIT_CLS_UI_SCREEN.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_MAIN_SCREEN.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_NATIVE_SCALE.as_ptr().cast::<c_char>()),
        )
    };
    let screen: *mut c_void = uikit_send_ptr0(screen_cls, sel_main);
    let scale: f64 = uikit_send_f64_0(screen, sel_scale);
    if scale > 0.0 { scale as f32 } else { 2.0 }
}

/// Queries the active iOS / iPadOS dark mode appearance via `UIScreen.mainScreen.traitCollection.userInterfaceStyle`.
///
/// # Returns
///
/// - `ThemeMode` - Active UIKit interface style.
#[must_use]
pub fn ios_system_theme() -> ThemeMode {
    // SAFETY: Static null-terminated Objective-C class and selector names.
    let (screen_cls, sel_main, sel_traits, sel_style): (
        *mut c_void,
        *mut c_void,
        *mut c_void,
        *mut c_void,
    ) = unsafe {
        (
            objc_getClass(UIKIT_CLS_UI_SCREEN.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_MAIN_SCREEN.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_TRAIT_COLLECTION.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_USER_INTERFACE_STYLE.as_ptr().cast::<c_char>()),
        )
    };
    let screen: *mut c_void = uikit_send_ptr0(screen_cls, sel_main);
    let traits: *mut c_void = uikit_send_ptr0(screen, sel_traits);
    let style: isize = uikit_send_isize0(traits, sel_style);
    if style == UI_USER_INTERFACE_STYLE_DARK {
        ThemeMode::Dark
    } else {
        ThemeMode::Light
    }
}

/// Queries the native display maximum refresh rate via `UIScreen.mainScreen.maximumFramesPerSecond`.
///
/// # Returns
///
/// - `f32` - Active display refresh rate in Hertz (`120.0` on ProMotion iPhones/iPads, `60.0` fallback).
#[must_use]
pub fn ios_display_refresh_rate_hz() -> f32 {
    // SAFETY: Static null-terminated Objective-C class and selector names.
    let (screen_cls, sel_main, sel_max_fps): (*mut c_void, *mut c_void, *mut c_void) = unsafe {
        (
            objc_getClass(UIKIT_CLS_UI_SCREEN.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_MAIN_SCREEN.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_MAX_FPS.as_ptr().cast::<c_char>()),
        )
    };
    let screen: *mut c_void = uikit_send_ptr0(screen_cls, sel_main);
    let hz: isize = uikit_send_isize0(screen, sel_max_fps);
    if hz >= 24 {
        (hz as f32).clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ)
    } else {
        FALLBACK_REFRESH_RATE_HZ
    }
}

/// Allocates a `UIWindow`, `UIView`, and triple-buffered `CAMetalLayer` via direct UIKit / QuartzCore FFI.
///
/// # Returns
///
/// - `(usize, usize, usize)` - Tuple `(ui_window, ui_view, metal_layer)`.
pub(crate) fn ios_create_native_handles() -> (usize, usize, usize) {
    // SAFETY: Static null-terminated Objective-C names.
    let (win_cls, view_cls, layer_cls, sel_alloc, sel_init, sel_layer, sel_max_drawables): (
        *mut c_void,
        *mut c_void,
        *mut c_void,
        *mut c_void,
        *mut c_void,
        *mut c_void,
        *mut c_void,
    ) = unsafe {
        (
            objc_getClass(UIKIT_CLS_UI_WINDOW.as_ptr().cast::<c_char>()),
            objc_getClass(UIKIT_CLS_UI_VIEW.as_ptr().cast::<c_char>()),
            objc_getClass(UIKIT_CLS_CA_METAL_LAYER.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_ALLOC.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_INIT.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_LAYER.as_ptr().cast::<c_char>()),
            sel_registerName(UIKIT_SEL_SET_MAX_DRAWABLE_COUNT.as_ptr().cast::<c_char>()),
        )
    };
    let ui_window: *mut c_void = uikit_send_ptr0(uikit_send_ptr0(win_cls, sel_alloc), sel_init);
    let ui_view: *mut c_void = uikit_send_ptr0(uikit_send_ptr0(view_cls, sel_alloc), sel_init);
    let metal_layer: *mut c_void = uikit_send_ptr0(layer_cls, sel_layer);
    if !metal_layer.is_null() {
        let scale: f64 = ios_screen_scale() as f64;
        // SAFETY: Configures `CAMetalLayer` with native Retina `contentsScale`, `framebufferOnly = YES`, and triple-buffered drawable count.
        unsafe {
            let sel_scale: *mut c_void =
                sel_registerName(UIKIT_SEL_SET_CONTENTS_SCALE.as_ptr().cast::<c_char>());
            let set_f64: unsafe extern "C" fn(*mut c_void, *mut c_void, f64) =
                transmute(objc_msgSend as *const ());
            set_f64(metal_layer, sel_scale, scale);
            let sel_fb_only: *mut c_void =
                sel_registerName(UIKIT_SEL_SET_FRAMEBUFFER_ONLY.as_ptr().cast::<c_char>());
            let set_bool: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
                transmute(objc_msgSend as *const ());
            set_bool(metal_layer, sel_fb_only, 1);
            let set_usize: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) =
                transmute(objc_msgSend as *const ());
            set_usize(
                metal_layer,
                sel_max_drawables,
                IOS_METAL_TRIPLE_BUFFER_COUNT,
            );
        }
    }
    (ui_window as usize, ui_view as usize, metal_layer as usize)
}

/// Allocates a CoreGraphics device RGB color space pointer suitable for caching across frames.
///
/// # Returns
///
/// - `usize` - Raw `CGColorSpaceRef` pointer as `usize`.
pub(crate) fn ios_create_device_rgb_space() -> usize {
    // SAFETY: `CGColorSpaceCreateDeviceRGB` returns a retained `CGColorSpaceRef` valid for reuse.
    unsafe { CGColorSpaceCreateDeviceRGB() as usize }
}

/// Presents an RGBA8 `Framebuffer` directly onto a UIKit `CALayer` / `CAMetalLayer` via safe `CFData` + cached `CGColorSpace`.
///
/// # Arguments
///
/// - `usize` - Raw `CALayer*` pointer.
/// - `usize` - Cached `CGColorSpaceRef` pointer (`0` allocates a transient fallback).
/// - `&Framebuffer` - Rendered RGBA8 pixel buffer.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
pub(crate) fn ios_present_cg_image(
    layer_ptr: usize,
    cached_space: usize,
    framebuffer: &Framebuffer,
) -> Result<(), PlatformError> {
    if layer_ptr == 0 {
        return Ok(());
    }
    let width: usize = framebuffer.get_width() as usize;
    let height: usize = framebuffer.get_height() as usize;
    let bytes: &[u8] = framebuffer.get_pixels().as_slice();
    // SAFETY: `CFDataCreate` copies `bytes` into Apple-owned immutable storage retained safely by CoreAnimation.
    unsafe {
        let owned_space: bool = cached_space == 0;
        let color_space: *mut c_void = if owned_space {
            CGColorSpaceCreateDeviceRGB()
        } else {
            cached_space as *mut c_void
        };
        let cf_data: *mut c_void = CFDataCreate(null(), bytes.as_ptr(), bytes.len() as isize);
        let provider: *mut c_void = if cf_data.is_null() {
            null_mut()
        } else {
            CGDataProviderCreateWithCFData(cf_data)
        };
        let cg_image: *mut c_void = if provider.is_null() {
            null_mut()
        } else {
            CGImageCreate(
                width,
                height,
                8,
                32,
                width * 4,
                color_space,
                IOS_CG_BITMAP_INFO_RGBA8,
                provider,
                null(),
                false,
                0,
            )
        };
        if !cg_image.is_null() {
            let sel: *mut c_void =
                sel_registerName(UIKIT_SEL_SET_CONTENTS.as_ptr().cast::<c_char>());
            let func: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
                transmute(objc_msgSend as *const ());
            let _: *mut c_void = func(layer_ptr as *mut c_void, sel, cg_image);
            CGImageRelease(cg_image);
        }
        if !provider.is_null() {
            CGDataProviderRelease(provider);
        }
        if !cf_data.is_null() {
            CFRelease(cf_data.cast_const());
        }
        if owned_space && !color_space.is_null() {
            CGColorSpaceRelease(color_space);
        }
    }
    Ok(())
}

/// Configures a UIKit `CADisplayLink*` for uncapped ProMotion high-refresh rendering (`60..maxHz`, preferred `maxHz`).
///
/// # Arguments
///
/// - `usize` - Raw `CADisplayLink*` pointer (`0` when detached).
/// - `f32` - Target maximum display refresh rate in Hertz (`60.0`..`MAX_REFRESH_RATE_HZ`).
pub(crate) fn uikit_configure_display_link_refresh(display_link: usize, max_hz: f32) {
    if display_link == 0 {
        return;
    }
    let pacing: FramePacingConfig = compute_frame_pacing(max_hz);
    let preferred_hz: f32 = pacing.get_preferred_hz();
    let range: CaFrameRateRange = CaFrameRateRange {
        minimum: FALLBACK_REFRESH_RATE_HZ.min(preferred_hz),
        maximum: pacing
            .get_max_hz()
            .max(preferred_hz)
            .max(MAX_REFRESH_RATE_HZ),
        preferred: preferred_hz,
    };
    // SAFETY: Checks `respondsToSelector:` before sending iOS 15+ `CAFrameRateRange` or fallback `NSInteger` FPS.
    unsafe {
        let link: *mut c_void = display_link as *mut c_void;
        let sel_responds: *mut c_void =
            sel_registerName(UIKIT_SEL_RESPONDS_TO_SELECTOR.as_ptr().cast::<c_char>());
        let sel_range: *mut c_void = sel_registerName(
            UIKIT_SEL_SET_PREFERRED_FRAME_RATE_RANGE
                .as_ptr()
                .cast::<c_char>(),
        );
        let responds_fn: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i8 =
            transmute(objc_msgSend as *const ());
        if responds_fn(link, sel_responds, sel_range) != 0 {
            let set_range: unsafe extern "C" fn(*mut c_void, *mut c_void, CaFrameRateRange) =
                transmute(objc_msgSend as *const ());
            set_range(link, sel_range, range);
        } else {
            let sel_fps: *mut c_void =
                sel_registerName(UIKIT_SEL_SET_PREFERRED_FPS.as_ptr().cast::<c_char>());
            let set_fps: unsafe extern "C" fn(*mut c_void, *mut c_void, isize) =
                transmute(objc_msgSend as *const ());
            set_fps(link, sel_fps, pacing.get_preferred_hz().round() as isize);
        }
    }
}

/// Pauses or resumes a UIKit `CADisplayLink*` via `-[CADisplayLink setPaused:]`.
///
/// # Arguments
///
/// - `usize` - Raw `CADisplayLink*` pointer (`0` when no display link is attached).
/// - `bool` - `true` to pause display-link ticks in background; `false` to resume.
pub(crate) fn uikit_set_display_link_paused(display_link: usize, paused: bool) {
    if display_link == 0 {
        return;
    }
    // SAFETY: `objc_msgSend` matches `void (id, SEL, BOOL)` ABI on 64-bit Apple platforms.
    unsafe {
        let sel: *mut c_void = sel_registerName(UIKIT_SEL_SET_PAUSED.as_ptr().cast::<c_char>());
        let func: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
            transmute(objc_msgSend as *const ());
        func(display_link as *mut c_void, sel, if paused { 1 } else { 0 });
    }
}

/// Returns `true` when compiled for an iOS / iPadOS Simulator target where hardware `MTLDrawable.presentedTime` is unobservable.
///
/// # Returns
///
/// - `bool` - `true` on `aarch64-apple-ios-sim` / `x86_64-apple-ios` simulator targets.
#[must_use]
pub const fn ios_is_simulator_target() -> bool {
    cfg!(target_abi = "sim")
}

/// Converts a positive finite Apple `CFTimeInterval` timestamp in seconds into nanoseconds (`None` when `<= 0.0` or non-finite).
///
/// # Arguments
///
/// - `f64` - `CFTimeInterval` value in seconds from `CADisplayLink` or `MTLDrawable.presentedTime`.
///
/// # Returns
///
/// - `Option<u64>` - Nanosecond timestamp, or `None` when unobservable/unset.
#[must_use]
pub fn ios_cf_time_secs_to_ns(secs: f64) -> Option<u64> {
    if secs.is_finite() && secs > 0.0 {
        Some((secs * 1_000_000_000.0).round() as u64)
    } else {
        None
    }
}

/// Converts a flat `DirectGpuFrameBatch` into ordered `GpuBatch` records ready for `NativeGpuDriver::submit_batches` onto `CAMetalLayer`.
///
/// # Arguments
///
/// - `&DirectGpuFrameBatch` - Compiled zero-CPU-mirror direct GPU frame batch.
///
/// # Returns
///
/// - `Vec<GpuBatch>` - Scissor-ordered GPU batches carrying packed 64-byte `GpuPrimitiveInstance` records.
#[must_use]
pub fn ios_direct_gpu_batches_from_frame(batch: &DirectGpuFrameBatch) -> Vec<GpuBatch> {
    let mut out: Vec<GpuBatch> = Vec::with_capacity(batch.get_draw_ranges().len());
    let all_prims: &[GpuPrimitiveInstance] = batch.get_primitives().as_slice();
    for range in batch.get_draw_ranges().iter() {
        let start: usize = range.get_base_instance() as usize;
        let end: usize = start
            .saturating_add(range.get_instance_count() as usize)
            .min(all_prims.len());
        if start >= end {
            continue;
        }
        let mut gb: GpuBatch = GpuBatch::default();
        gb.set_scissor(Rect::new(
            range.get_scissor_x() as f32,
            range.get_scissor_y() as f32,
            range.get_scissor_w() as f32,
            range.get_scissor_h() as f32,
        ));
        gb.set_scroll_offset([range.get_scroll_x(), range.get_scroll_y()]);
        gb.set_texture_slot(range.get_texture_slot());
        gb.set_layer_id(range.get_layer_id());
        gb.get_mut_primitives()
            .extend_from_slice(&all_prims[start..end]);
        out.push(gb);
    }
    out
}