Skip to main content

euv_core/render/gpu/
fn.rs

1use super::*;
2
3/// Probes the host OS for a physical GPU adapter, compiles or loads cached native UI pipelines, and returns handles.
4///
5/// # Arguments
6///
7/// - `GraphicsBackend` - Requested graphics backend.
8///
9/// # Returns
10///
11/// - `(GpuAdapterInfo, usize, usize, usize)` - Adapter info plus `(device, queue, library)` raw handles.
12#[must_use]
13pub fn probe_native_gpu(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
14    let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
15    (
16        probed.adapter,
17        probed.device_handle,
18        probed.queue_handle,
19        probed.library_handle,
20    )
21}
22
23/// Probes the host OS for a physical GPU adapter, cached uber-shader & blur pipelines, and fallback textures.
24///
25/// # Arguments
26///
27/// - `GraphicsBackend` - Requested graphics backend.
28///
29/// # Returns
30///
31/// - `NativeGpuProbeOutput` - Adapter info plus retained device, queue, library, pipeline, and dummy texture handles.
32#[must_use]
33pub(crate) fn probe_native_gpu_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
34    if backend == GraphicsBackend::Headless || backend == GraphicsBackend::SoftwareCpu {
35        return NativeGpuProbeOutput {
36            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
37            device_handle: 0,
38            queue_handle: 0,
39            library_handle: 0,
40            pipeline_handle: 0,
41            blur_pipeline_handle: 0,
42            blur_up_pipeline_handle: 0,
43            engine3d_pipeline_handle: 0,
44            ocean_pipeline_handle: 0,
45            scene_ocean_pipeline_handle: 0,
46            scene_boat_pipeline_handle: 0,
47            scene_3d_sky_pipeline_handle: 0,
48            scene_3d_mesh_pipeline_handle: 0,
49            scene_depth_stencil_handle: 0,
50            dummy_r8_tex: 0,
51            dummy_rgba8_tex: 0,
52            scene_pbr_pipelines: [0; 5],
53        };
54    }
55    #[cfg(any(target_os = "macos", target_os = "ios"))]
56    {
57        if backend == GraphicsBackend::Metal {
58            probe_apple_metal_full(backend)
59        } else {
60            NativeGpuProbeOutput {
61                adapter: GpuAdapterInfo::new(
62                    backend,
63                    GPU_DEVICE_FALLBACK.to_string(),
64                    false,
65                    false,
66                ),
67                device_handle: 0,
68                queue_handle: 0,
69                library_handle: 0,
70                pipeline_handle: 0,
71                blur_pipeline_handle: 0,
72                blur_up_pipeline_handle: 0,
73                engine3d_pipeline_handle: 0,
74                ocean_pipeline_handle: 0,
75                scene_ocean_pipeline_handle: 0,
76                scene_boat_pipeline_handle: 0,
77                scene_3d_sky_pipeline_handle: 0,
78                scene_3d_mesh_pipeline_handle: 0,
79                scene_depth_stencil_handle: 0,
80                dummy_r8_tex: 0,
81                dummy_rgba8_tex: 0,
82                scene_pbr_pipelines: [0; 5],
83            }
84        }
85    }
86    #[cfg(target_os = "windows")]
87    {
88        let (adapter, device_handle, queue_handle, library_handle): (
89            GpuAdapterInfo,
90            usize,
91            usize,
92            usize,
93        ) = probe_windows_d3d12(backend);
94        NativeGpuProbeOutput {
95            adapter,
96            device_handle,
97            queue_handle,
98            library_handle,
99            pipeline_handle: 0,
100            blur_pipeline_handle: 0,
101            blur_up_pipeline_handle: 0,
102            engine3d_pipeline_handle: 0,
103            ocean_pipeline_handle: 0,
104            scene_ocean_pipeline_handle: 0,
105            scene_boat_pipeline_handle: 0,
106            scene_3d_sky_pipeline_handle: 0,
107            scene_3d_mesh_pipeline_handle: 0,
108            scene_depth_stencil_handle: 0,
109            dummy_r8_tex: 0,
110            dummy_rgba8_tex: 0,
111            scene_pbr_pipelines: [0; 5],
112        }
113    }
114    #[cfg(any(target_os = "linux", target_os = "android"))]
115    {
116        let (adapter, device_handle, queue_handle, library_handle): (
117            GpuAdapterInfo,
118            usize,
119            usize,
120            usize,
121        ) = probe_vulkan_runtime(backend);
122        NativeGpuProbeOutput {
123            adapter,
124            device_handle,
125            queue_handle,
126            library_handle,
127            pipeline_handle: 0,
128            blur_pipeline_handle: 0,
129            blur_up_pipeline_handle: 0,
130            engine3d_pipeline_handle: 0,
131            ocean_pipeline_handle: 0,
132            scene_ocean_pipeline_handle: 0,
133            scene_boat_pipeline_handle: 0,
134            scene_3d_sky_pipeline_handle: 0,
135            scene_3d_mesh_pipeline_handle: 0,
136            scene_depth_stencil_handle: 0,
137            dummy_r8_tex: 0,
138            dummy_rgba8_tex: 0,
139            scene_pbr_pipelines: [0; 5],
140        }
141    }
142    #[cfg(target_arch = "wasm32")]
143    {
144        NativeGpuProbeOutput {
145            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
146            device_handle: 0,
147            queue_handle: 0,
148            library_handle: 0,
149            pipeline_handle: 0,
150            blur_pipeline_handle: 0,
151            blur_up_pipeline_handle: 0,
152            engine3d_pipeline_handle: 0,
153            ocean_pipeline_handle: 0,
154            scene_ocean_pipeline_handle: 0,
155            scene_boat_pipeline_handle: 0,
156            scene_3d_sky_pipeline_handle: 0,
157            scene_3d_mesh_pipeline_handle: 0,
158            scene_depth_stencil_handle: 0,
159            dummy_r8_tex: 0,
160            dummy_rgba8_tex: 0,
161            scene_pbr_pipelines: [0; 5],
162        }
163    }
164    #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
165    #[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
166    {
167        NativeGpuProbeOutput {
168            adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
169            device_handle: 0,
170            queue_handle: 0,
171            library_handle: 0,
172            pipeline_handle: 0,
173            blur_pipeline_handle: 0,
174            blur_up_pipeline_handle: 0,
175            engine3d_pipeline_handle: 0,
176            ocean_pipeline_handle: 0,
177            scene_ocean_pipeline_handle: 0,
178            scene_boat_pipeline_handle: 0,
179            scene_3d_sky_pipeline_handle: 0,
180            scene_3d_mesh_pipeline_handle: 0,
181            scene_depth_stencil_handle: 0,
182            dummy_r8_tex: 0,
183            dummy_rgba8_tex: 0,
184            scene_pbr_pipelines: [0; 5],
185        }
186    }
187}
188
189/// Uploads instanced quad buffers and submits a command buffer to the active physical GPU.
190///
191/// # Arguments
192///
193/// - `usize` - Raw OS device handle.
194/// - `usize` - Raw OS command queue handle.
195/// - `&[GpuBatch]` - Compiled instanced draw batches.
196///
197/// # Returns
198///
199/// - `usize` - Total GPU instances uploaded and submitted.
200pub fn submit_native_gpu_batches(
201    device_handle: usize,
202    queue_handle: usize,
203    batches: &[GpuBatch],
204) -> usize {
205    #[cfg(any(target_os = "macos", target_os = "ios"))]
206    {
207        metal_submit_batches(device_handle, queue_handle, batches)
208    }
209    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
210    {
211        let _: (usize, usize) = (device_handle, queue_handle);
212        batches
213            .iter()
214            .map(|blue_val: &GpuBatch| {
215                blue_val
216                    .get_primitives()
217                    .len()
218                    .max(blue_val.get_instances().len())
219            })
220            .sum()
221    }
222}
223
224/// Uploads packed 64-byte `GpuPrimitiveInstance` streams into a fenced 3-slot ring, encodes real instanced draw calls when a `CAMetalLayer` is bound, and commits.
225///
226/// # Arguments
227///
228/// - `&mut NativeGpuDriver` - Mutable GPU driver holding ring slots, pipelines, textures, and surface handle.
229/// - `u32` - Physical surface width in pixels.
230/// - `u32` - Physical surface height in pixels.
231/// - `Color` - Surface clear color.
232/// - `&[GpuBatch]` - Ordered instanced draw batches.
233///
234/// # Returns
235///
236/// - `usize` - Total 64-byte `GpuPrimitiveInstance` records uploaded and submitted.
237pub(crate) fn submit_native_gpu_ring_frame(
238    driver: &mut NativeGpuDriver,
239    width: u32,
240    height: u32,
241    clear_color: Color,
242    batches: &[GpuBatch],
243) -> usize {
244    #[cfg(any(target_os = "macos", target_os = "ios"))]
245    {
246        metal_submit_ring_frame(driver, width, height, clear_color, batches)
247    }
248    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
249    {
250        let _: (&mut NativeGpuDriver, u32, u32, Color) = (driver, width, height, clear_color);
251        batches
252            .iter()
253            .map(|blue_val: &GpuBatch| {
254                blue_val
255                    .get_primitives()
256                    .len()
257                    .max(blue_val.get_instances().len())
258            })
259            .sum()
260    }
261}
262
263/// Executes Pass 3 Dual-Kawase `blur_down` + `blur_up` ping-pong passes on the active hardware GPU.
264///
265/// # Arguments
266///
267/// - `&mut NativeGpuDriver` - Mutable hardware GPU driver owning both blur pipelines and ping-pong textures.
268/// - `u32` - Physical surface width in pixels.
269/// - `u32` - Physical surface height in pixels.
270/// - `&[GpuBackdropBlurPass]` - Active Dual-Kawase backdrop blur regions.
271///
272/// # Returns
273///
274/// - `usize` - Number of blur regions executed on hardware GPU (`0` when unsupported).
275pub(crate) fn execute_native_dual_kawase_blur_passes(
276    driver: &mut NativeGpuDriver,
277    width: u32,
278    height: u32,
279    blur_passes: &[GpuBackdropBlurPass],
280) -> usize {
281    if blur_passes.is_empty() || !driver.supports_backdrop_blur_pass() {
282        return 0;
283    }
284    #[cfg(any(target_os = "macos", target_os = "ios"))]
285    {
286        metal_execute_dual_kawase_blur_passes(driver, width, height, blur_passes)
287    }
288    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
289    {
290        let _: (&mut NativeGpuDriver, u32, u32) = (driver, width, height);
291        0
292    }
293}
294
295/// Configures a native `CAMetalLayer` for triple-buffered direct-draw presentation (`framebufferOnly = YES`, `maximumDrawableCount = 3`).
296///
297/// # Arguments
298///
299/// - `usize` - Raw OS device handle (`id<MTLDevice>`).
300/// - `usize` - Raw `CAMetalLayer*` pointer.
301pub(crate) fn configure_native_metal_layer(device_handle: usize, layer_handle: usize) {
302    #[cfg(any(target_os = "macos", target_os = "ios"))]
303    {
304        metal_configure_layer(device_handle, layer_handle);
305    }
306    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
307    {
308        let _: (usize, usize) = (device_handle, layer_handle);
309    }
310}
311
312/// Configures `CAMetalLayer.displaySyncEnabled` on Apple platforms (`false` unlocks uncapped non-blocking hardware presentation on macOS).
313///
314/// # Arguments
315///
316/// - `usize` - Raw `CAMetalLayer*` pointer.
317/// - `bool` - `true` to enable hardware VRR display sync; `false` for uncapped non-blocking presentation.
318pub(crate) fn configure_native_metal_display_sync(layer_handle: usize, enabled: bool) {
319    #[cfg(any(target_os = "macos", target_os = "ios"))]
320    {
321        metal_set_layer_display_sync(layer_handle, enabled);
322    }
323    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
324    {
325        let _: (usize, bool) = (layer_handle, enabled);
326    }
327}
328
329/// Uploads a dirty sub-rectangle of R8 or RGBA8 texels into a resident native GPU texture without full-texture reallocation.
330///
331/// # Arguments
332///
333/// - `usize` - Raw OS GPU device handle.
334/// - `&mut usize` - Resident native texture handle (`0` triggers lazy creation).
335/// - `GpuAtlasPixelFormat` - Target texture format (`R8Unorm` or `Rgba8Unorm`).
336/// - `(u32, u32)` - Full backing texture dimensions `(tex_w, tex_h)`.
337/// - `(u32, u32, u32, u32)` - Dirty rectangle `(x, y, width, height)`.
338/// - `&[u8]` - Tightly or stride-packed source texel bytes.
339/// - `usize` - Row stride in bytes of `bytes`.
340///
341/// # Returns
342///
343/// - `bool` - `true` when the dirty sub-rectangle was uploaded cleanly.
344pub(crate) fn upload_native_texture_dirty_rect(
345    device_handle: usize,
346    texture_handle: &mut usize,
347    format: GpuAtlasPixelFormat,
348    tex_dims: (u32, u32),
349    dirty_rect: (u32, u32, u32, u32),
350    bytes: &[u8],
351    bytes_per_row: usize,
352) -> bool {
353    #[cfg(any(target_os = "macos", target_os = "ios"))]
354    {
355        metal_upload_texture_dirty_rect(
356            device_handle,
357            texture_handle,
358            format,
359            tex_dims,
360            dirty_rect,
361            bytes,
362            bytes_per_row,
363        )
364    }
365    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
366    {
367        let _: usize = device_handle;
368        let _: &mut usize = texture_handle;
369        let _: GpuAtlasPixelFormat = format;
370        let _: (u32, u32) = tex_dims;
371        let _: (u32, u32, u32, u32) = dirty_rect;
372        let _: &[u8] = bytes;
373        let _: usize = bytes_per_row;
374        false
375    }
376}
377
378/// Retains a single native GPU object handle cleanly so each owning slot holds an independent reference.
379///
380/// # Arguments
381///
382/// - `usize` - Raw OS GPU object handle (`0` returns `0`).
383///
384/// # Returns
385///
386/// - `usize` - Independently retained GPU object handle.
387pub(crate) fn retain_native_gpu_object(handle: usize) -> usize {
388    #[cfg(any(target_os = "macos", target_os = "ios"))]
389    {
390        mtl_retain_handle(handle)
391    }
392    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
393    {
394        handle
395    }
396}
397
398/// Releases a single retained native GPU object handle cleanly on teardown.
399///
400/// # Arguments
401///
402/// - `usize` - Retained OS GPU handle (`0` is a no-op).
403pub(crate) fn release_native_gpu_object(handle: usize) {
404    #[cfg(any(target_os = "macos", target_os = "ios"))]
405    {
406        if handle != 0 {
407            let sel: &MetalSelectors = cached_metal_selectors();
408            mtl_send_void0(handle as *mut c_void, sel.release as *mut c_void);
409        }
410    }
411    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
412    {
413        let _: usize = handle;
414    }
415}
416
417/// Releases native GPU handles on driver teardown.
418///
419/// # Arguments
420///
421/// - `usize` - Raw device handle.
422/// - `usize` - Raw command queue handle.
423/// - `usize` - Raw shader library handle.
424pub fn release_native_gpu_handles(
425    device_handle: usize,
426    queue_handle: usize,
427    library_handle: usize,
428) {
429    #[cfg(any(target_os = "macos", target_os = "ios"))]
430    {
431        metal_release_handles(device_handle, queue_handle, library_handle);
432    }
433    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
434    {
435        let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
436    }
437}
438
439/// Returns the latest hardware presentation timestamp in nanoseconds recorded by the GPU driver.
440///
441/// # Returns
442///
443/// - `u64` - Presentation timestamp in nanoseconds (`0` before first hardware present).
444#[must_use]
445pub fn native_gpu_last_presented_ns() -> u64 {
446    #[cfg(any(target_os = "macos", target_os = "ios"))]
447    {
448        METAL_LAST_PRESENTED_NS.load(Ordering::Relaxed)
449    }
450    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
451    {
452        0
453    }
454}
455
456/// Returns the latest hardware GPU command execution duration in nanoseconds.
457///
458/// # Returns
459///
460/// - `u64` - GPU execution duration in nanoseconds (`0` before first completed GPU command buffer).
461#[must_use]
462pub fn native_gpu_last_exec_ns() -> u64 {
463    #[cfg(any(target_os = "macos", target_os = "ios"))]
464    {
465        METAL_LAST_GPU_EXEC_NS.load(Ordering::Relaxed)
466    }
467    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
468    {
469        0
470    }
471}
472
473#[cfg(any(target_os = "macos", target_os = "ios"))]
474#[link(name = "Metal", kind = "framework")]
475unsafe extern "C" {
476    /// Creates the default Apple Metal GPU device handle.
477    ///
478    /// # Returns
479    ///
480    /// - `*mut c_void` - Retained `id<MTLDevice>` pointer or null.
481    fn MTLCreateSystemDefaultDevice() -> *mut c_void;
482}
483
484#[cfg(any(target_os = "macos", target_os = "ios"))]
485#[link(name = "objc")]
486unsafe extern "C" {
487    /// Looks up an Objective-C class pointer by null-terminated C name.
488    ///
489    /// # Arguments
490    ///
491    /// - `*const c_char` - Null-terminated class name.
492    ///
493    /// # Returns
494    ///
495    /// - `*mut c_void` - Objective-C class pointer or null.
496    fn objc_getClass(name: *const c_char) -> *mut c_void;
497    /// Registers an Objective-C selector by null-terminated C name.
498    ///
499    /// # Arguments
500    ///
501    /// - `*const c_char` - Null-terminated selector name.
502    ///
503    /// # Returns
504    ///
505    /// - `*mut c_void` - Registered selector pointer.
506    fn sel_registerName(name: *const c_char) -> *mut c_void;
507    /// Pushes a scoped Objective-C autorelease pool frame.
508    ///
509    /// # Returns
510    ///
511    /// - `*mut c_void` - Autorelease pool token to pop via `objc_autoreleasePoolPop`.
512    pub(crate) fn objc_autoreleasePoolPush() -> *mut c_void;
513    /// Pops and drains a scoped Objective-C autorelease pool frame.
514    ///
515    /// # Arguments
516    ///
517    /// - `*mut c_void` - Pool token returned by `objc_autoreleasePoolPush`.
518    pub(crate) fn objc_autoreleasePoolPop(pool: *mut c_void);
519    /// Objective-C dynamic message dispatch entry point.
520    pub(crate) fn objc_msgSend();
521}
522
523#[cfg(any(target_os = "macos", target_os = "ios"))]
524unsafe extern "C" {
525    /// Standard Apple `libSystem` class symbol identifying static global Objective-C blocks.
526    pub(crate) static _NSConcreteGlobalBlock: c_void;
527}
528
529/// Registers an Objective-C selector from a static null-terminated string literal.
530///
531/// # Arguments
532///
533/// - `&'static str` - Null-terminated selector name.
534///
535/// # Returns
536///
537/// - `*mut c_void` - Registered Objective-C selector pointer.
538#[cfg(any(target_os = "macos", target_os = "ios"))]
539pub(crate) fn mtl_sel_cstr(name: &'static str) -> *mut c_void {
540    unsafe { sel_registerName(name.as_ptr().cast::<c_char>()) }
541}
542
543/// Looks up an Objective-C class from a static null-terminated string literal.
544///
545/// # Arguments
546///
547/// - `&'static str` - Null-terminated class name.
548///
549/// # Returns
550///
551/// - `*mut c_void` - Objective-C class pointer or null.
552#[cfg(any(target_os = "macos", target_os = "ios"))]
553pub(crate) fn mtl_cls_cstr(name: &'static str) -> *mut c_void {
554    unsafe { objc_getClass(name.as_ptr().cast::<c_char>()) }
555}
556
557/// Allocates an autoreleased `NSString` from a UTF-8 Rust slice.
558///
559/// # Arguments
560///
561/// - `&str` - Source UTF-8 string.
562///
563/// # Returns
564///
565/// - `*mut c_void` - Objective-C `NSString` pointer.
566#[cfg(any(target_os = "macos", target_os = "ios"))]
567pub(crate) fn mtl_ns_string(text: &str) -> *mut c_void {
568    let Ok(c_text) = CString::new(text) else {
569        return null_mut();
570    };
571    unsafe {
572        let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_STRING);
573        if cls.is_null() {
574            return null_mut();
575        }
576        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
577            transmute(objc_msgSend as *const c_void);
578        send(cls, mtl_sel_cstr(MTL_SEL_STRING_UTF8), c_text.as_ptr())
579    }
580}
581
582/// Sends a zero-argument Objective-C message returning a pointer.
583///
584/// # Arguments
585///
586/// - `*mut c_void` - Target Objective-C object.
587/// - `*mut c_void` - Selector pointer.
588///
589/// # Returns
590///
591/// - `*mut c_void` - Returned Objective-C object pointer.
592#[cfg(any(target_os = "macos", target_os = "ios"))]
593pub(crate) fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
594    if obj.is_null() || sel.is_null() {
595        return null_mut();
596    }
597    unsafe {
598        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
599            transmute(objc_msgSend as *const c_void);
600        send(obj, sel)
601    }
602}
603
604/// Sends a one-pointer-argument Objective-C message returning a pointer.
605///
606/// # Arguments
607///
608/// - `*mut c_void` - Target Objective-C object.
609/// - `*mut c_void` - Selector pointer.
610/// - `*mut c_void` - Pointer argument.
611///
612/// # Returns
613///
614/// - `*mut c_void` - Returned Objective-C object pointer.
615#[cfg(any(target_os = "macos", target_os = "ios"))]
616pub(crate) fn mtl_send_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) -> *mut c_void {
617    if obj.is_null() || sel.is_null() {
618        return null_mut();
619    }
620    unsafe {
621        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
622            transmute(objc_msgSend as *const c_void);
623        send(obj, sel, arg0)
624    }
625}
626
627/// Sends a zero-argument Objective-C message returning void.
628///
629/// # Arguments
630///
631/// - `*mut c_void` - Target Objective-C object.
632/// - `*mut c_void` - Selector pointer.
633#[cfg(any(target_os = "macos", target_os = "ios"))]
634pub(crate) fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
635    if obj.is_null() || sel.is_null() {
636        return;
637    }
638    unsafe {
639        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
640            transmute(objc_msgSend as *const c_void);
641        send(obj, sel);
642    }
643}
644
645/// Sends a one-pointer-argument Objective-C message returning void.
646///
647/// # Arguments
648///
649/// - `*mut c_void` - Target Objective-C object.
650/// - `*mut c_void` - Selector pointer.
651/// - `*mut c_void` - Pointer argument.
652#[cfg(any(target_os = "macos", target_os = "ios"))]
653pub(crate) fn mtl_send_void_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) {
654    if obj.is_null() || sel.is_null() {
655        return;
656    }
657    unsafe {
658        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
659            transmute(objc_msgSend as *const c_void);
660        send(obj, sel, arg0);
661    }
662}
663
664/// Sends a one-`usize`-argument Objective-C message returning void.
665///
666/// # Arguments
667///
668/// - `*mut c_void` - Target Objective-C object.
669/// - `*mut c_void` - Selector pointer.
670/// - `usize` - Unsigned integer argument (`NSUInteger`).
671#[cfg(any(target_os = "macos", target_os = "ios"))]
672pub(crate) fn mtl_send_void_usize(obj: *mut c_void, sel: *mut c_void, val: usize) {
673    if obj.is_null() || sel.is_null() {
674        return;
675    }
676    unsafe {
677        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) =
678            transmute(objc_msgSend as *const c_void);
679        send(obj, sel, val);
680    }
681}
682
683/// Sends a one-boolean Objective-C message returning void.
684///
685/// # Arguments
686///
687/// - `*mut c_void` - Target Objective-C object.
688/// - `*mut c_void` - Selector pointer.
689/// - `bool` - Boolean flag converted to Objective-C `BOOL`.
690#[cfg(any(target_os = "macos", target_os = "ios"))]
691pub(crate) fn mtl_send_void_bool(obj: *mut c_void, sel: *mut c_void, val: bool) {
692    if obj.is_null() || sel.is_null() {
693        return;
694    }
695    unsafe {
696        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
697            transmute(objc_msgSend as *const c_void);
698        send(obj, sel, if val { 1 } else { 0 });
699    }
700}
701
702/// Sends a zero-argument Objective-C message returning `usize` (`NSUInteger`).
703///
704/// # Arguments
705///
706/// - `*mut c_void` - Target Objective-C object.
707/// - `*mut c_void` - Selector pointer.
708///
709/// # Returns
710///
711/// - `usize` - Returned `NSUInteger`.
712#[cfg(any(target_os = "macos", target_os = "ios"))]
713pub(crate) fn mtl_send_usize0(obj: *mut c_void, sel: *mut c_void) -> usize {
714    if obj.is_null() || sel.is_null() {
715        return 0;
716    }
717    unsafe {
718        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
719            transmute(objc_msgSend as *const c_void);
720        send(obj, sel)
721    }
722}
723
724/// Sends a zero-argument Objective-C message returning `f64` (`CFTimeInterval`).
725///
726/// # Arguments
727///
728/// - `*mut c_void` - Target Objective-C object.
729/// - `*mut c_void` - Selector pointer.
730///
731/// # Returns
732///
733/// - `f64` - Returned floating-point timestamp or duration in seconds.
734#[cfg(any(target_os = "macos", target_os = "ios"))]
735pub(crate) fn mtl_send_f64_0(obj: *mut c_void, sel: *mut c_void) -> f64 {
736    if obj.is_null() || sel.is_null() {
737        return 0.0;
738    }
739    unsafe {
740        let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> f64 =
741            transmute(objc_msgSend as *const c_void);
742        send(obj, sel)
743    }
744}
745
746/// Checks whether an Objective-C object responds to `sel`.
747///
748/// # Arguments
749///
750/// - `*mut c_void` - Target Objective-C object.
751/// - `*mut c_void` - Selector to query.
752///
753/// # Returns
754///
755/// - `bool` - `true` when the object implements `sel`.
756#[cfg(any(target_os = "macos", target_os = "ios"))]
757pub(crate) fn mtl_responds_to_sel(obj: *mut c_void, sel: *mut c_void) -> bool {
758    if obj.is_null() || sel.is_null() {
759        return false;
760    }
761    let responds_sel: *mut c_void = cached_metal_selectors().responds_to_sel as *mut c_void;
762    unsafe {
763        let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i8 =
764            transmute(objc_msgSend as *const c_void);
765        send(obj, responds_sel, sel) != 0
766    }
767}
768
769/// Retains a non-zero Objective-C handle and returns it as `usize`.
770///
771/// # Arguments
772///
773/// - `usize` - Raw Objective-C object handle (`0` returns `0`).
774///
775/// # Returns
776///
777/// - `usize` - Retained handle.
778#[cfg(any(target_os = "macos", target_os = "ios"))]
779pub(crate) fn mtl_retain_handle(handle: usize) -> usize {
780    if handle == 0 {
781        return 0;
782    }
783    let sel_retain: *mut c_void = cached_metal_selectors().retain as *mut c_void;
784    mtl_send_ptr0(handle as *mut c_void, sel_retain) as usize
785}
786
787/// Objective-C global block callback invoked by `-[MTLDrawable addPresentedHandler:]` upon display scan-out.
788///
789/// # Arguments
790///
791/// - `*mut c_void` - Global block pointer (unused).
792/// - `*mut c_void` - Presented `id<MTLDrawable>` pointer.
793#[cfg(all(any(target_os = "macos", target_os = "ios"), not(target_abi = "sim")))]
794unsafe extern "C" fn metal_presented_handler_invoke(_block: *mut c_void, drawable: *mut c_void) {
795    if drawable.is_null() {
796        return;
797    }
798    let sel: &MetalSelectors = cached_metal_selectors();
799    let presented_secs: f64 = mtl_send_f64_0(drawable, sel.presented_time as *mut c_void);
800    if presented_secs.is_finite() && presented_secs > 0.0 {
801        let ns: u64 = (presented_secs * 1_000_000_000.0).round() as u64;
802        METAL_LAST_PRESENTED_NS.store(ns, Ordering::Relaxed);
803    }
804}
805
806/// Objective-C global block callback invoked by `-[MTLCommandBuffer addCompletedHandler:]` on GPU completion.
807///
808/// # Arguments
809///
810/// - `*mut c_void` - Global block pointer (unused).
811/// - `*mut c_void` - Completed `id<MTLCommandBuffer>` pointer.
812#[cfg(any(target_os = "macos", target_os = "ios"))]
813unsafe extern "C" fn metal_completed_handler_invoke(_block: *mut c_void, cmd_buf: *mut c_void) {
814    if cmd_buf.is_null() {
815        return;
816    }
817    let sel: &MetalSelectors = cached_metal_selectors();
818    let start_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_start_time as *mut c_void);
819    let end_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_end_time as *mut c_void);
820    if start_s.is_finite() && end_s.is_finite() && end_s >= start_s {
821        let exec_ns: u64 = ((end_s - start_s) * 1_000_000_000.0).round() as u64;
822        METAL_LAST_GPU_EXEC_NS.store(exec_ns, Ordering::Relaxed);
823        LAST_GPU_RENDER_NS.store(exec_ns, Ordering::Relaxed);
824    }
825    let _: u64 = COMPLETED_GPU_FENCE.fetch_add(1, Ordering::Release);
826}
827
828/// Returns the process-lifetime pinned global Objective-C block pointer for `addPresentedHandler:`.
829///
830/// # Returns
831///
832/// - `*mut c_void` - Pointer to static `ObjcGlobalBlock`.
833#[cfg(all(any(target_os = "macos", target_os = "ios"), not(target_abi = "sim")))]
834fn metal_presented_block_ptr() -> *mut c_void {
835    let addr: usize = *METAL_PRESENTED_BLOCK_ADDR.get_or_init(|| {
836        let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
837            isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
838            flags: OBJC_BLOCK_IS_GLOBAL,
839            reserved: 0,
840            invoke: metal_presented_handler_invoke,
841            descriptor: &METAL_BLOCK_DESCRIPTOR,
842        });
843        Box::into_raw(block) as usize
844    });
845    addr as *mut c_void
846}
847
848/// Returns the process-lifetime pinned global Objective-C block pointer for `addCompletedHandler:`.
849///
850/// # Returns
851///
852/// - `*mut c_void` - Pointer to static `ObjcGlobalBlock`.
853#[cfg(any(target_os = "macos", target_os = "ios"))]
854fn metal_completed_block_ptr() -> *mut c_void {
855    let addr: usize = *METAL_COMPLETED_BLOCK_ADDR.get_or_init(|| {
856        let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
857            isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
858            flags: OBJC_BLOCK_IS_GLOBAL,
859            reserved: 0,
860            invoke: metal_completed_handler_invoke,
861            descriptor: &METAL_BLOCK_DESCRIPTOR,
862        });
863        Box::into_raw(block) as usize
864    });
865    addr as *mut c_void
866}
867
868/// Computes a deterministic 64-bit FNV-1a cache key over shader sources and GPU device name for `MTLBinaryArchive`.
869///
870/// # Arguments
871///
872/// - `&str` - Probed GPU device name.
873///
874/// # Returns
875///
876/// - `u64` - Deterministic cache key hash.
877#[cfg(any(target_os = "macos", target_os = "ios"))]
878fn metal_pipeline_cache_hash(device_name: &str) -> u64 {
879    let mut hash: u64 = FNV1A_OFFSET_BASIS;
880    for chunk in [
881        device_name.as_bytes(),
882        MSL_UI_SHADER.as_bytes(),
883        MSL_BACKDROP_BLUR_SHADER.as_bytes(),
884        MSL_ENGINE3D_PBR_SHADER.as_bytes(),
885        MSL_FLUID_OCEAN_SHADER.as_bytes(),
886        MSL_GPU_SCENE_SHADER.as_bytes(),
887        MSL_PBR_SCENE_SHADER.as_bytes(),
888    ]
889    .iter()
890    {
891        for &byte in chunk.iter() {
892            hash ^= byte as u64;
893            hash = hash.wrapping_mul(FNV1A_PRIME);
894        }
895    }
896    hash
897}
898
899/// Creates a Metal `MTLTexture` (`R8Unorm` or `RGBA8Unorm`) with explicit dimensions for atlases or fallback slots.
900///
901/// # Arguments
902///
903/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
904/// - `GpuAtlasPixelFormat` - Pixel format to allocate.
905/// - `u32` - Texture width in pixels.
906/// - `u32` - Texture height in pixels.
907///
908/// # Returns
909///
910/// - `usize` - Retained `id<MTLTexture>` pointer or `0` on failure.
911#[cfg(any(target_os = "macos", target_os = "ios"))]
912fn metal_create_texture(
913    device: *mut c_void,
914    format: GpuAtlasPixelFormat,
915    width: u32,
916    height: u32,
917) -> usize {
918    if device.is_null() {
919        return 0;
920    }
921    let px_fmt: usize = match format {
922        GpuAtlasPixelFormat::R8Unorm => MTL_PIXEL_FORMAT_R8_UNORM,
923        GpuAtlasPixelFormat::Rgba8Unorm => MTL_PIXEL_FORMAT_RGBA8_UNORM,
924    };
925    let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
926    if cls_desc.is_null() {
927        return 0;
928    }
929    unsafe {
930        let send_desc: unsafe extern "C" fn(
931            *mut c_void,
932            *mut c_void,
933            usize,
934            usize,
935            usize,
936            i8,
937        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
938        let desc: *mut c_void = send_desc(
939            cls_desc,
940            mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
941            px_fmt,
942            width.max(1) as usize,
943            height.max(1) as usize,
944            0,
945        );
946        if desc.is_null() {
947            return 0;
948        }
949        mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
950        let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
951        tex as usize
952    }
953}
954
955/// Builds a real `MTLRenderPipelineState` with optional `MTLBinaryArchive` disk caching and straight-alpha blending.
956///
957/// # Arguments
958///
959/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
960/// - `*mut c_void` - Compiled `id<MTLLibrary>` handle.
961/// - `&str` - Vertex shader entry function name.
962/// - `&str` - Fragment shader entry function name.
963/// - `*mut c_void` - Optional `id<MTLBinaryArchive>` handle (null if unsupported).
964/// - `bool` - Whether alpha blending should be enabled on color attachment 0.
965///
966/// # Returns
967///
968/// - `(usize, bool)` - Tuple `(pipeline_state_handle, functions_found)`.
969#[cfg(any(target_os = "macos", target_os = "ios"))]
970fn metal_build_render_pipeline(
971    device: *mut c_void,
972    library: *mut c_void,
973    vs_name: &str,
974    fs_name: &str,
975    archive: *mut c_void,
976    enable_blend: bool,
977) -> (usize, bool) {
978    metal_build_render_pipeline_with_depth(
979        device,
980        library,
981        vs_name,
982        fs_name,
983        archive,
984        enable_blend,
985        0,
986    )
987}
988
989/// Builds a Metal `MTLRenderPipelineState` with optional alpha blending and optional depth attachment format (`0` = no depth attachment).
990///
991/// # Arguments
992///
993/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
994/// - `*mut c_void` - Compiled `id<MTLLibrary>` handle.
995/// - `&str` - Vertex shader entry function name.
996/// - `&str` - Fragment shader entry function name.
997/// - `*mut c_void` - Optional `id<MTLBinaryArchive>` handle.
998/// - `bool` - Whether alpha blending should be enabled on color attachment `0`.
999/// - `usize` - Metal depth attachment pixel format (`0` for none, `MTL_PIXEL_FORMAT_DEPTH32_FLOAT` for 3D Z-buffer).
1000///
1001/// # Returns
1002///
1003/// - `(usize, bool)` - Tuple `(pipeline_state_handle, functions_found)`.
1004#[cfg(any(target_os = "macos", target_os = "ios"))]
1005fn metal_build_render_pipeline_with_depth(
1006    device: *mut c_void,
1007    library: *mut c_void,
1008    vs_name: &str,
1009    fs_name: &str,
1010    archive: *mut c_void,
1011    enable_blend: bool,
1012    depth_pixel_format: usize,
1013) -> (usize, bool) {
1014    if device.is_null() || library.is_null() {
1015        return (0, false);
1016    }
1017    let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
1018    let vs_fn: *mut c_void = mtl_send_ptr1(
1019        library,
1020        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1021        mtl_ns_string(vs_name),
1022    );
1023    let fs_fn: *mut c_void = mtl_send_ptr1(
1024        library,
1025        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1026        mtl_ns_string(fs_name),
1027    );
1028    let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
1029    if !functions_ok {
1030        if !vs_fn.is_null() {
1031            mtl_send_void0(vs_fn, sel_rel);
1032        }
1033        if !fs_fn.is_null() {
1034            mtl_send_void0(fs_fn, sel_rel);
1035        }
1036        return (0, false);
1037    }
1038    let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
1039    let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1040    let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1041    if desc.is_null() {
1042        mtl_send_void0(vs_fn, sel_rel);
1043        mtl_send_void0(fs_fn, sel_rel);
1044        return (0, functions_ok);
1045    }
1046    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
1047    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
1048    let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
1049    let att0: *mut c_void = unsafe {
1050        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1051            transmute(objc_msgSend as *const c_void);
1052        send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
1053    };
1054    if !att0.is_null() {
1055        mtl_send_void_usize(
1056            att0,
1057            mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1058            MTL_PIXEL_FORMAT_BGRA8_UNORM,
1059        );
1060        if enable_blend {
1061            mtl_send_void_bool(att0, mtl_sel_cstr(MTL_SEL_SET_BLENDING_ENABLED), true);
1062            mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_RGB_BLEND_OP), 0);
1063            mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_ALPHA_BLEND_OP), 0);
1064            mtl_send_void_usize(
1065                att0,
1066                mtl_sel_cstr(MTL_SEL_SET_SRC_RGB_BLEND),
1067                MTL_BLEND_FACTOR_SRC_ALPHA,
1068            );
1069            mtl_send_void_usize(
1070                att0,
1071                mtl_sel_cstr(MTL_SEL_SET_DST_RGB_BLEND),
1072                MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
1073            );
1074            mtl_send_void_usize(
1075                att0,
1076                mtl_sel_cstr(MTL_SEL_SET_SRC_ALPHA_BLEND),
1077                MTL_BLEND_FACTOR_ONE,
1078            );
1079            mtl_send_void_usize(
1080                att0,
1081                mtl_sel_cstr(MTL_SEL_SET_DST_ALPHA_BLEND),
1082                MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
1083            );
1084        }
1085    }
1086    if depth_pixel_format != 0 {
1087        mtl_send_void_usize(
1088            desc,
1089            mtl_sel_cstr(MTL_SEL_SET_DEPTH_ATTACHMENT_PIXEL_FORMAT),
1090            depth_pixel_format,
1091        );
1092    }
1093    if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
1094        let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
1095        let arr: *mut c_void =
1096            mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
1097        if !arr.is_null() {
1098            mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
1099        }
1100    }
1101    let mut err_ptr: *mut c_void = null_mut();
1102    let pipeline: *mut c_void = unsafe {
1103        let send_pso: unsafe extern "C" fn(
1104            *mut c_void,
1105            *mut c_void,
1106            *mut c_void,
1107            *mut *mut c_void,
1108        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1109        send_pso(
1110            device,
1111            mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
1112            desc,
1113            &mut err_ptr,
1114        )
1115    };
1116    if !archive.is_null() && !pipeline.is_null() {
1117        let mut add_err: *mut c_void = null_mut();
1118        unsafe {
1119            let send_add: unsafe extern "C" fn(
1120                *mut c_void,
1121                *mut c_void,
1122                *mut c_void,
1123                *mut *mut c_void,
1124            ) -> i8 = transmute(objc_msgSend as *const c_void);
1125            let _: i8 = send_add(
1126                archive,
1127                mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
1128                desc,
1129                &mut add_err,
1130            );
1131        }
1132    }
1133    mtl_send_void0(desc, sel_rel);
1134    mtl_send_void0(vs_fn, sel_rel);
1135    mtl_send_void0(fs_fn, sel_rel);
1136    (pipeline as usize, functions_ok)
1137}
1138
1139/// Builds a real `MTLRenderPipelineState` with `MTLVertexDescriptor` (`float3 position`, `float3 normal`, stride 24 at buffer 2) for `MSL_ENGINE3D_PBR_SHADER`.
1140///
1141/// # Arguments
1142///
1143/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1144/// - `*mut c_void` - Compiled 3D PBR `id<MTLLibrary>` handle.
1145/// - `*mut c_void` - Optional `id<MTLBinaryArchive>` handle (null if unsupported).
1146///
1147/// # Returns
1148///
1149/// - `(usize, bool)` - Tuple `(pipeline_state_handle, functions_found)`.
1150#[cfg(any(target_os = "macos", target_os = "ios"))]
1151fn metal_build_render_pipeline_3d(
1152    device: *mut c_void,
1153    library: *mut c_void,
1154    archive: *mut c_void,
1155) -> (usize, bool) {
1156    if device.is_null() || library.is_null() {
1157        return (0, false);
1158    }
1159    let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
1160    let vs_fn: *mut c_void = mtl_send_ptr1(
1161        library,
1162        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1163        mtl_ns_string(MTL_FN_3D_VERTEX),
1164    );
1165    let fs_fn: *mut c_void = mtl_send_ptr1(
1166        library,
1167        mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1168        mtl_ns_string(MTL_FN_3D_FRAGMENT),
1169    );
1170    let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
1171    if !functions_ok {
1172        if !vs_fn.is_null() {
1173            mtl_send_void0(vs_fn, sel_rel);
1174        }
1175        if !fs_fn.is_null() {
1176            mtl_send_void0(fs_fn, sel_rel);
1177        }
1178        return (0, false);
1179    }
1180    let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
1181    let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1182    let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1183    if desc.is_null() {
1184        mtl_send_void0(vs_fn, sel_rel);
1185        mtl_send_void0(fs_fn, sel_rel);
1186        return (0, functions_ok);
1187    }
1188    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
1189    mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
1190    let vdesc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_VERTEX_DESC);
1191    let vdesc_alloc: *mut c_void = mtl_send_ptr0(vdesc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1192    let vdesc: *mut c_void = mtl_send_ptr0(vdesc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1193    if !vdesc.is_null() {
1194        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1195            unsafe { transmute(objc_msgSend as *const c_void) };
1196        let sel_idx: *mut c_void = mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX);
1197        let attrs: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_ATTRIBUTES));
1198        let attr0: *mut c_void = unsafe { send_idx(attrs, sel_idx, 0) };
1199        let attr1: *mut c_void = unsafe { send_idx(attrs, sel_idx, 1) };
1200        if !attr0.is_null() {
1201            mtl_send_void_usize(
1202                attr0,
1203                mtl_sel_cstr(MTL_SEL_SET_FORMAT),
1204                MTL_VERTEX_FORMAT_FLOAT3,
1205            );
1206            mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 0);
1207            mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
1208        }
1209        if !attr1.is_null() {
1210            mtl_send_void_usize(
1211                attr1,
1212                mtl_sel_cstr(MTL_SEL_SET_FORMAT),
1213                MTL_VERTEX_FORMAT_FLOAT3,
1214            );
1215            mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 12);
1216            mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
1217        }
1218        let layouts: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_LAYOUTS));
1219        let layout2: *mut c_void = unsafe { send_idx(layouts, sel_idx, 2) };
1220        if !layout2.is_null() {
1221            mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STRIDE), 24);
1222            mtl_send_void_usize(
1223                layout2,
1224                mtl_sel_cstr(MTL_SEL_SET_STEP_FUNCTION),
1225                MTL_VERTEX_STEP_PER_VERTEX,
1226            );
1227            mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STEP_RATE), 1);
1228        }
1229        mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_DESC), vdesc);
1230        mtl_send_void0(vdesc, sel_rel);
1231    }
1232    let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
1233    let att0: *mut c_void = unsafe {
1234        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1235            transmute(objc_msgSend as *const c_void);
1236        send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
1237    };
1238    if !att0.is_null() {
1239        mtl_send_void_usize(
1240            att0,
1241            mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1242            MTL_PIXEL_FORMAT_BGRA8_UNORM,
1243        );
1244    }
1245    if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
1246        let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
1247        let arr: *mut c_void =
1248            mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
1249        if !arr.is_null() {
1250            mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
1251        }
1252    }
1253    let mut err_ptr: *mut c_void = null_mut();
1254    let pipeline: *mut c_void = unsafe {
1255        let send_pso: unsafe extern "C" fn(
1256            *mut c_void,
1257            *mut c_void,
1258            *mut c_void,
1259            *mut *mut c_void,
1260        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1261        send_pso(
1262            device,
1263            mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
1264            desc,
1265            &mut err_ptr,
1266        )
1267    };
1268    if !archive.is_null() && !pipeline.is_null() {
1269        let mut add_err: *mut c_void = null_mut();
1270        unsafe {
1271            let send_add: unsafe extern "C" fn(
1272                *mut c_void,
1273                *mut c_void,
1274                *mut c_void,
1275                *mut *mut c_void,
1276            ) -> i8 = transmute(objc_msgSend as *const c_void);
1277            let _: i8 = send_add(
1278                archive,
1279                mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
1280                desc,
1281                &mut add_err,
1282            );
1283        }
1284    }
1285    mtl_send_void0(desc, sel_rel);
1286    mtl_send_void0(vs_fn, sel_rel);
1287    mtl_send_void0(fs_fn, sel_rel);
1288    (pipeline as usize, functions_ok)
1289}
1290
1291/// Creates a Metal `MTLDepthStencilState` configured with `MTLCompareFunctionLess` and `depthWriteEnabled = YES`.
1292///
1293/// # Arguments
1294///
1295/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1296///
1297/// # Returns
1298///
1299/// - `usize` - Retained `id<MTLDepthStencilState>` pointer, or `0` on failure.
1300#[cfg(any(target_os = "macos", target_os = "ios"))]
1301fn metal_create_depth_stencil_state(device: *mut c_void) -> usize {
1302    if device.is_null() {
1303        return 0;
1304    }
1305    let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_DEPTH_STENCIL_DESC);
1306    if cls.is_null() {
1307        return 0;
1308    }
1309    let alloc: *mut c_void = mtl_send_ptr0(cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1310    let desc: *mut c_void = mtl_send_ptr0(alloc, mtl_sel_cstr(MTL_SEL_INIT));
1311    if desc.is_null() {
1312        return 0;
1313    }
1314    mtl_send_void_usize(
1315        desc,
1316        mtl_sel_cstr(MTL_SEL_SET_DEPTH_COMPARE_FN),
1317        MTL_COMPARE_FUNC_LESS,
1318    );
1319    mtl_send_void_bool(desc, mtl_sel_cstr(MTL_SEL_SET_DEPTH_WRITE_ENABLED), true);
1320    let state: *mut c_void =
1321        mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_DEPTH_STENCIL_STATE), desc);
1322    mtl_send_void0(desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1323    state as usize
1324}
1325
1326/// Builds a `MTLDepthStencilState` (`Less`, depth writes disabled) for back-to-front alpha-blended PBR geometry.
1327///
1328/// # Arguments
1329///
1330/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1331///
1332/// # Returns
1333///
1334/// - `usize` - Retained `id<MTLDepthStencilState>` pointer, or `0` on failure.
1335#[cfg(any(target_os = "macos", target_os = "ios"))]
1336fn metal_create_read_only_depth_stencil_state(device: *mut c_void) -> usize {
1337    if device.is_null() {
1338        return 0;
1339    }
1340    let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_DEPTH_STENCIL_DESC);
1341    if cls.is_null() {
1342        return 0;
1343    }
1344    let alloc: *mut c_void = mtl_send_ptr0(cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1345    let desc: *mut c_void = mtl_send_ptr0(alloc, mtl_sel_cstr(MTL_SEL_INIT));
1346    if desc.is_null() {
1347        return 0;
1348    }
1349    mtl_send_void_usize(
1350        desc,
1351        mtl_sel_cstr(MTL_SEL_SET_DEPTH_COMPARE_FN),
1352        MTL_COMPARE_FUNC_LESS,
1353    );
1354    mtl_send_void_bool(desc, mtl_sel_cstr(MTL_SEL_SET_DEPTH_WRITE_ENABLED), false);
1355    let state: *mut c_void =
1356        mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_DEPTH_STENCIL_STATE), desc);
1357    mtl_send_void0(desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1358    state as usize
1359}
1360
1361/// Allocates a mipmapped `RGBA8Unorm` shader-read `MTLTexture` sized `(base_width, base_height)` for progressive mipmap streaming.
1362///
1363/// # Arguments
1364///
1365/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1366/// - `u32` - Base `LOD0` width in texels.
1367/// - `u32` - Base `LOD0` height in texels.
1368///
1369/// # Returns
1370///
1371/// - `(usize, u8)` - Tuple `(retained_mtl_texture_handle, allocated_mip_level_count)`.
1372#[cfg(any(target_os = "macos", target_os = "ios"))]
1373fn metal_create_mipmapped_rgba8_texture(
1374    device: *mut c_void,
1375    base_width: u32,
1376    base_height: u32,
1377) -> (usize, u8) {
1378    if device.is_null() {
1379        return (0, 0);
1380    }
1381    let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
1382    if cls_desc.is_null() {
1383        return (0, 0);
1384    }
1385    let w: u32 = base_width.clamp(1, 8192);
1386    let h: u32 = base_height.clamp(1, 8192);
1387    let max_dim: u32 = w.max(h);
1388    let mip_count: u8 = (32u32.saturating_sub(max_dim.leading_zeros())).min(14) as u8;
1389    unsafe {
1390        let send_desc: unsafe extern "C" fn(
1391            *mut c_void,
1392            *mut c_void,
1393            usize,
1394            usize,
1395            usize,
1396            i8,
1397        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1398        let desc: *mut c_void = send_desc(
1399            cls_desc,
1400            mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
1401            MTL_PIXEL_FORMAT_RGBA8_UNORM,
1402            w as usize,
1403            h as usize,
1404            1,
1405        );
1406        if desc.is_null() {
1407            return (0, 0);
1408        }
1409        mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
1410        let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
1411        (tex as usize, mip_count.max(1))
1412    }
1413}
1414
1415/// Applies incremental `GpuTextureMipUpload` records onto resident mipmapped Metal textures via `replaceRegion` and updates zero-copy `minLodClamp` texture views.
1416///
1417/// # Arguments
1418///
1419/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1420/// - `&mut MetalPbrSceneResources` - Resident PBR texture pool receiving mip uploads.
1421/// - `&[GpuTextureMipUpload]` - Frame-budgeted incremental mipmap upload records.
1422#[cfg(any(target_os = "macos", target_os = "ios"))]
1423fn metal_apply_pbr_mip_uploads(
1424    device: *mut c_void,
1425    pbr_res: &mut MetalPbrSceneResources,
1426    uploads: &[GpuTextureMipUpload],
1427) {
1428    if device.is_null() || uploads.is_empty() {
1429        return;
1430    }
1431    let sel: &MetalSelectors = cached_metal_selectors();
1432    for up in uploads.iter() {
1433        let mip: u8 = up.get_mip_level();
1434        let shift: u32 = u32::from(mip.min(13));
1435        let base_w: u32 = up
1436            .get_width()
1437            .max(1)
1438            .checked_shl(shift)
1439            .unwrap_or(8192)
1440            .clamp(1, 8192);
1441        let base_h: u32 = up
1442            .get_height()
1443            .max(1)
1444            .checked_shl(shift)
1445            .unwrap_or(8192)
1446            .clamp(1, 8192);
1447        let slot: u32 = up.get_texture_slot();
1448        let needs_alloc: bool = match pbr_res.textures.get(&slot) {
1449            Some(existing) => {
1450                existing.tex_handle == 0
1451                    || existing.base_width != base_w
1452                    || existing.base_height != base_h
1453            }
1454            None => true,
1455        };
1456        if needs_alloc {
1457            if let Some(old) = pbr_res.textures.remove(&slot) {
1458                release_native_gpu_object(old.view_handle);
1459                release_native_gpu_object(old.tex_handle);
1460            }
1461            let (tex_h, total_mips): (usize, u8) =
1462                metal_create_mipmapped_rgba8_texture(device, base_w, base_h);
1463            if tex_h == 0 {
1464                continue;
1465            }
1466            let _: Option<MetalResidentMipTexture> = pbr_res.textures.insert(
1467                slot,
1468                MetalResidentMipTexture {
1469                    tex_handle: tex_h,
1470                    view_handle: 0,
1471                    base_width: base_w,
1472                    base_height: base_h,
1473                    total_mips,
1474                    min_lod_clamp: total_mips.saturating_sub(1),
1475                },
1476            );
1477        }
1478        let Some(entry) = pbr_res.textures.get_mut(&slot) else {
1479            continue;
1480        };
1481        if mip >= entry.total_mips {
1482            continue;
1483        }
1484        let mip_w: u32 = (entry.base_width >> shift).max(1);
1485        let mip_h: u32 = (entry.base_height >> shift).max(1);
1486        let expected_bytes: usize = (mip_w as usize)
1487            .saturating_mul(mip_h as usize)
1488            .saturating_mul(4);
1489        let rgba8: &[u8] = up.get_rgba8().as_slice();
1490        if rgba8.len() < expected_bytes {
1491            continue;
1492        }
1493        let region: MtlRegion = MtlRegion {
1494            origin: MtlOrigin { x: 0, y: 0, z: 0 },
1495            size: MtlSize {
1496                width: mip_w as usize,
1497                height: mip_h as usize,
1498                depth: 1,
1499            },
1500        };
1501        unsafe {
1502            let send_rep: unsafe extern "C" fn(
1503                *mut c_void,
1504                *mut c_void,
1505                MtlRegion,
1506                usize,
1507                *const c_void,
1508                usize,
1509            ) = transmute(objc_msgSend as *const c_void);
1510            send_rep(
1511                entry.tex_handle as *mut c_void,
1512                sel.replace_region as *mut c_void,
1513                region,
1514                mip as usize,
1515                rgba8.as_ptr().cast::<c_void>(),
1516                (mip_w as usize).saturating_mul(4),
1517            );
1518        }
1519        let next_clamp: u8 = up
1520            .get_min_lod_clamp()
1521            .min(mip)
1522            .min(entry.total_mips.saturating_sub(1));
1523        if entry.min_lod_clamp != next_clamp || (next_clamp > 0 && entry.view_handle == 0) {
1524            release_native_gpu_object(entry.view_handle);
1525            entry.view_handle = 0;
1526            entry.min_lod_clamp = next_clamp;
1527            if next_clamp > 0 {
1528                let len_levels: usize =
1529                    usize::from(entry.total_mips.saturating_sub(next_clamp)).max(1);
1530                let level_range: MtlNsRange = MtlNsRange {
1531                    location: next_clamp as usize,
1532                    length: len_levels,
1533                };
1534                let slice_range: MtlNsRange = MtlNsRange {
1535                    location: 0,
1536                    length: 1,
1537                };
1538                let view_ptr: *mut c_void = unsafe {
1539                    let send_view: unsafe extern "C" fn(
1540                        *mut c_void,
1541                        *mut c_void,
1542                        usize,
1543                        usize,
1544                        MtlNsRange,
1545                        MtlNsRange,
1546                    ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1547                    send_view(
1548                        entry.tex_handle as *mut c_void,
1549                        sel.new_texture_view as *mut c_void,
1550                        MTL_PIXEL_FORMAT_RGBA8_UNORM,
1551                        MTL_TEXTURE_TYPE_2D,
1552                        level_range,
1553                        slice_range,
1554                    )
1555                };
1556                entry.view_handle = view_ptr as usize;
1557            }
1558        }
1559    }
1560}
1561
1562/// Allocates a private `Depth32Float` render-target `MTLTexture` sized `(width, height)`.
1563///
1564/// # Arguments
1565///
1566/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1567/// - `u32` - Width in physical pixels.
1568/// - `u32` - Height in physical pixels.
1569///
1570/// # Returns
1571///
1572/// - `usize` - Retained `id<MTLTexture>` pointer, or `0` on failure.
1573#[cfg(any(target_os = "macos", target_os = "ios"))]
1574fn metal_create_depth_texture(device: *mut c_void, width: u32, height: u32) -> usize {
1575    if device.is_null() {
1576        return 0;
1577    }
1578    let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
1579    if cls_desc.is_null() {
1580        return 0;
1581    }
1582    unsafe {
1583        let send_desc: unsafe extern "C" fn(
1584            *mut c_void,
1585            *mut c_void,
1586            usize,
1587            usize,
1588            usize,
1589            bool,
1590        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1591        let desc: *mut c_void = send_desc(
1592            cls_desc,
1593            mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
1594            MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1595            width.max(1) as usize,
1596            height.max(1) as usize,
1597            false,
1598        );
1599        if desc.is_null() {
1600            return 0;
1601        }
1602        mtl_send_void_usize(
1603            desc,
1604            mtl_sel_cstr(MTL_SEL_SET_USAGE),
1605            MTL_TEX_USAGE_RENDER_TARGET_GPU,
1606        );
1607        mtl_send_void_usize(
1608            desc,
1609            mtl_sel_cstr(MTL_SEL_SET_STORAGE_MODE_GPU),
1610            MTL_STORAGE_MODE_PRIVATE_GPU,
1611        );
1612        mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc) as usize
1613    }
1614}
1615
1616/// Ensures a grow-only shared-memory Metal buffer can store `bytes.len()` bytes and copies `bytes` into it.
1617///
1618/// # Arguments
1619///
1620/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1621/// - `&mut usize` - Resident `id<MTLBuffer>` handle.
1622/// - `&mut usize` - Resident buffer byte capacity.
1623/// - `&[u8]` - Source byte payload to upload.
1624///
1625/// # Returns
1626///
1627/// - `*mut c_void` - Valid `id<MTLBuffer>` pointer, or null on allocation failure.
1628#[cfg(any(target_os = "macos", target_os = "ios"))]
1629fn metal_ensure_and_upload_shared_buffer(
1630    device: *mut c_void,
1631    buf_handle: &mut usize,
1632    buf_capacity: &mut usize,
1633    bytes: &[u8],
1634) -> *mut c_void {
1635    if device.is_null() || bytes.is_empty() {
1636        return *buf_handle as *mut c_void;
1637    }
1638    let sel: &MetalSelectors = cached_metal_selectors();
1639    if *buf_handle == 0 || *buf_capacity < bytes.len() {
1640        if *buf_handle != 0 {
1641            mtl_send_void0(*buf_handle as *mut c_void, sel.release as *mut c_void);
1642            *buf_handle = 0;
1643            *buf_capacity = 0;
1644        }
1645        let alloc_bytes: usize = bytes.len().max(1024).next_power_of_two();
1646        unsafe {
1647            let send_new_len: unsafe extern "C" fn(
1648                *mut c_void,
1649                *mut c_void,
1650                usize,
1651                usize,
1652            ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1653            let new_buf: *mut c_void = send_new_len(
1654                device,
1655                sel.new_buffer_with_length as *mut c_void,
1656                alloc_bytes,
1657                0,
1658            );
1659            if !new_buf.is_null() {
1660                *buf_handle = new_buf as usize;
1661                *buf_capacity = alloc_bytes;
1662            }
1663        }
1664    }
1665    if *buf_handle == 0 {
1666        return null_mut();
1667    }
1668    let ptr: *mut c_void = mtl_send_ptr0(*buf_handle as *mut c_void, sel.contents as *mut c_void);
1669    if !ptr.is_null() {
1670        unsafe {
1671            ptr.cast::<u8>()
1672                .copy_from_nonoverlapping(bytes.as_ptr(), bytes.len());
1673        }
1674    }
1675    *buf_handle as *mut c_void
1676}
1677
1678/// Returns whether disk-backed `MTLBinaryArchive` caching is safe for the active Metal device.
1679///
1680/// # Arguments
1681///
1682/// - `&str` - Probed Metal GPU device name.
1683/// - `bool` - `true` when compiled for an Apple Simulator target (`target_abi = "sim"`).
1684///
1685/// # Returns
1686///
1687/// - `bool` - `true` on real physical Apple GPUs; `false` on simulator or virtualized drivers where `serializeToURL:error:` aborts inside `MTLSimDriver`.
1688#[must_use]
1689pub fn metal_binary_archive_allowed(device_name: &str, is_simulator: bool) -> bool {
1690    if is_simulator {
1691        return false;
1692    }
1693    let lower: String = device_name.to_ascii_lowercase();
1694    !lower.contains(MTL_SIMULATOR_TOKEN) && !lower.contains(MTL_VIRTUAL_TOKEN)
1695}
1696
1697/// Opens or initializes a disk-backed `MTLBinaryArchive` keyed by shader source hash and GPU device name.
1698///
1699/// # Arguments
1700///
1701/// - `*mut c_void` - Retained `id<MTLDevice>` handle.
1702/// - `&str` - Detected physical GPU device name.
1703///
1704/// # Returns
1705///
1706/// - `(*mut c_void, *mut c_void, bool)` - Tuple `(archive_handle, ns_url_handle, existed_on_disk)`.
1707#[cfg(any(target_os = "macos", target_os = "ios"))]
1708fn metal_open_binary_archive(
1709    device: *mut c_void,
1710    device_name: &str,
1711) -> (*mut c_void, *mut c_void, bool) {
1712    if !metal_binary_archive_allowed(device_name, cfg!(target_abi = "sim"))
1713        || !mtl_responds_to_sel(device, mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE))
1714    {
1715        return (null_mut(), null_mut(), false);
1716    }
1717    let arch_desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_BINARY_ARCHIVE_DESC);
1718    if arch_desc_cls.is_null() {
1719        return (null_mut(), null_mut(), false);
1720    }
1721    let cache_hash: u64 = metal_pipeline_cache_hash(device_name);
1722    let archive_path: String = env::temp_dir()
1723        .join(format!(
1724            "{MTL_ARCHIVE_FILE_PREFIX}{cache_hash:016x}{MTL_ARCHIVE_FILE_SUFFIX}"
1725        ))
1726        .to_string_lossy()
1727        .into_owned();
1728    let existed: bool = fs::metadata(&archive_path).is_ok();
1729    let ns_path: *mut c_void = mtl_ns_string(&archive_path);
1730    let url_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_URL);
1731    let ns_url: *mut c_void =
1732        mtl_send_ptr1(url_cls, mtl_sel_cstr(MTL_SEL_FILE_URL_WITH_PATH), ns_path);
1733    let arch_desc_alloc: *mut c_void = mtl_send_ptr0(arch_desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1734    let arch_desc: *mut c_void = mtl_send_ptr0(arch_desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1735    if arch_desc.is_null() {
1736        return (null_mut(), ns_url, existed);
1737    }
1738    if existed && !ns_url.is_null() {
1739        mtl_send_void_ptr1(arch_desc, mtl_sel_cstr(MTL_SEL_SET_URL), ns_url);
1740    }
1741    let mut err_ptr: *mut c_void = null_mut();
1742    let archive: *mut c_void = unsafe {
1743        let send_new: unsafe extern "C" fn(
1744            *mut c_void,
1745            *mut c_void,
1746            *mut c_void,
1747            *mut *mut c_void,
1748        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1749        send_new(
1750            device,
1751            mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE),
1752            arch_desc,
1753            &mut err_ptr,
1754        )
1755    };
1756    mtl_send_void0(arch_desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1757    (archive, ns_url, existed)
1758}
1759
1760/// Initializes or returns the process-wide cached Apple Metal device, command queue, binary-archived shader pipelines (`UI`, `Blur`, `3D PBR`, `Fluid Ocean`), and fallback textures.
1761///
1762/// # Arguments
1763///
1764/// - `GraphicsBackend` - Requested graphics backend.
1765///
1766/// # Returns
1767///
1768/// - `&'static MetalSharedPipelineCache` - Reference to the process-wide shared Metal PSO cache.
1769#[cfg(any(target_os = "macos", target_os = "ios"))]
1770pub(crate) fn init_apple_metal_shared_cache(
1771    backend: GraphicsBackend,
1772) -> &'static MetalSharedPipelineCache {
1773    METAL_SHARED_PIPELINE.get_or_init(|| {
1774        let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1775        let total_start: Instant = Instant::now();
1776        let result: MetalSharedPipelineCache = unsafe {
1777            let device: *mut c_void = MTLCreateSystemDefaultDevice();
1778            if device.is_null() {
1779                MetalSharedPipelineCache {
1780                    adapter: GpuAdapterInfo::new(
1781                        backend,
1782                        GPU_DEVICE_FALLBACK.to_string(),
1783                        false,
1784                        false,
1785                    ),
1786                    device: 0,
1787                    queue: 0,
1788                    library: 0,
1789                    pipeline: 0,
1790                    blur_pipeline: 0,
1791                    blur_up_pipeline: 0,
1792                    engine3d_pipeline: 0,
1793                    ocean_pipeline: 0,
1794                    scene_ocean_pipeline: 0,
1795                    scene_boat_pipeline: 0,
1796                    scene_3d_sky_pipeline: 0,
1797                    scene_3d_mesh_pipeline: 0,
1798                    scene_depth_stencil: 0,
1799                    scene_pbr_pipelines: [0; 5],
1800                    binary_archive_enabled: false,
1801                    binary_archive_hit: false,
1802                    ui_compile_us: 0,
1803                    blur_compile_us: 0,
1804                    engine3d_compile_us: 0,
1805                    ocean_compile_us: 0,
1806                    total_compile_us: 0,
1807                    dummy_r8_tex: 0,
1808                    dummy_rgba8_tex: 0,
1809                }
1810            } else {
1811                let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NAME));
1812                let utf8_ptr: *const c_char =
1813                    mtl_send_ptr0(ns_name, mtl_sel_cstr(MTL_SEL_UTF8_STRING)).cast::<c_char>();
1814                let device_name: String = if utf8_ptr.is_null() {
1815                    GPU_DEVICE_APPLE_METAL.to_string()
1816                } else {
1817                    CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
1818                };
1819                let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NEW_CMD_QUEUE));
1820                let (archive, archive_url, archive_existed): (*mut c_void, *mut c_void, bool) =
1821                    metal_open_binary_archive(device, &device_name);
1822                let archive_enabled: bool = !archive.is_null();
1823                let send_lib: unsafe extern "C" fn(
1824                    *mut c_void,
1825                    *mut c_void,
1826                    *mut c_void,
1827                    *mut c_void,
1828                    *mut *mut c_void,
1829                ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1830                let ui_start: Instant = Instant::now();
1831                let mut err_ptr: *mut c_void = null_mut();
1832                let library: *mut c_void = send_lib(
1833                    device,
1834                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1835                    mtl_ns_string(MSL_UI_SHADER),
1836                    null_mut(),
1837                    &mut err_ptr,
1838                );
1839                let (pipeline, ui_fns_ok): (usize, bool) = metal_build_render_pipeline(
1840                    device,
1841                    library,
1842                    MTL_FN_VERTEX,
1843                    MTL_FN_FRAGMENT,
1844                    archive,
1845                    true,
1846                );
1847                let ui_compile_us: u64 = ui_start.elapsed().as_micros() as u64;
1848                let blur_start: Instant = Instant::now();
1849                let mut blur_err: *mut c_void = null_mut();
1850                let blur_lib: *mut c_void = send_lib(
1851                    device,
1852                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1853                    mtl_ns_string(MSL_BACKDROP_BLUR_SHADER),
1854                    null_mut(),
1855                    &mut blur_err,
1856                );
1857                let (blur_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1858                    device,
1859                    blur_lib,
1860                    MTL_FN_BLUR_VERTEX,
1861                    MTL_FN_BLUR_DOWN,
1862                    archive,
1863                    false,
1864                );
1865                let (blur_up_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1866                    device,
1867                    blur_lib,
1868                    MTL_FN_BLUR_VERTEX,
1869                    MTL_FN_BLUR_UP,
1870                    archive,
1871                    false,
1872                );
1873                if !blur_lib.is_null() {
1874                    mtl_send_void0(blur_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1875                }
1876                let blur_compile_us: u64 = blur_start.elapsed().as_micros() as u64;
1877                let pbr_start: Instant = Instant::now();
1878                let mut pbr_err: *mut c_void = null_mut();
1879                let pbr_lib: *mut c_void = send_lib(
1880                    device,
1881                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1882                    mtl_ns_string(MSL_ENGINE3D_PBR_SHADER),
1883                    null_mut(),
1884                    &mut pbr_err,
1885                );
1886                let (engine3d_pipeline, _): (usize, bool) =
1887                    metal_build_render_pipeline_3d(device, pbr_lib, archive);
1888                if !pbr_lib.is_null() {
1889                    mtl_send_void0(pbr_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1890                }
1891                let engine3d_compile_us: u64 = pbr_start.elapsed().as_micros() as u64;
1892                let ocean_start: Instant = Instant::now();
1893                let mut ocean_err: *mut c_void = null_mut();
1894                let ocean_lib: *mut c_void = send_lib(
1895                    device,
1896                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1897                    mtl_ns_string(MSL_FLUID_OCEAN_SHADER),
1898                    null_mut(),
1899                    &mut ocean_err,
1900                );
1901                let (ocean_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1902                    device,
1903                    ocean_lib,
1904                    MTL_FN_OCEAN_VERTEX,
1905                    MTL_FN_OCEAN_FRAGMENT,
1906                    archive,
1907                    false,
1908                );
1909                if !ocean_lib.is_null() {
1910                    mtl_send_void0(ocean_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1911                }
1912                let ocean_compile_us: u64 = ocean_start.elapsed().as_micros() as u64;
1913                let mut scene_err: *mut c_void = null_mut();
1914                let scene_lib: *mut c_void = send_lib(
1915                    device,
1916                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1917                    mtl_ns_string(MSL_GPU_SCENE_SHADER),
1918                    null_mut(),
1919                    &mut scene_err,
1920                );
1921                let (scene_ocean_pipeline, _): (usize, bool) =
1922                    metal_build_render_pipeline_with_depth(
1923                        device,
1924                        scene_lib,
1925                        MTL_FN_SCENE_OCEAN_VERT,
1926                        MTL_FN_SCENE_OCEAN_FRAG,
1927                        archive,
1928                        false,
1929                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1930                    );
1931                let (scene_boat_pipeline, _): (usize, bool) =
1932                    metal_build_render_pipeline_with_depth(
1933                        device,
1934                        scene_lib,
1935                        MTL_FN_SCENE_BOAT_VERT,
1936                        MTL_FN_SCENE_BOAT_FRAG,
1937                        archive,
1938                        false,
1939                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1940                    );
1941                let (scene_3d_sky_pipeline, _): (usize, bool) =
1942                    metal_build_render_pipeline_with_depth(
1943                        device,
1944                        scene_lib,
1945                        MTL_FN_SCENE_3D_SKY_VERT,
1946                        MTL_FN_SCENE_3D_SKY_FRAG,
1947                        archive,
1948                        false,
1949                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1950                    );
1951                let (scene_3d_mesh_pipeline, _): (usize, bool) =
1952                    metal_build_render_pipeline_with_depth(
1953                        device,
1954                        scene_lib,
1955                        MTL_FN_SCENE_3D_MESH_VERT,
1956                        MTL_FN_SCENE_3D_MESH_FRAG,
1957                        archive,
1958                        false,
1959                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1960                    );
1961                if !scene_lib.is_null() {
1962                    mtl_send_void0(scene_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1963                }
1964                let mut pbr_scene_err: *mut c_void = null_mut();
1965                let pbr_scene_lib: *mut c_void = send_lib(
1966                    device,
1967                    mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1968                    mtl_ns_string(MSL_PBR_SCENE_SHADER),
1969                    null_mut(),
1970                    &mut pbr_scene_err,
1971                );
1972                let (scene_pbr_sky_pso, _): (usize, bool) = metal_build_render_pipeline_with_depth(
1973                    device,
1974                    pbr_scene_lib,
1975                    MTL_FN_SCENE_PBR_SKY_VERT,
1976                    MTL_FN_SCENE_PBR_SKY_FRAG,
1977                    archive,
1978                    false,
1979                    MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1980                );
1981                let (scene_pbr_opaque_pso, _): (usize, bool) =
1982                    metal_build_render_pipeline_with_depth(
1983                        device,
1984                        pbr_scene_lib,
1985                        MTL_FN_SCENE_PBR_VERT,
1986                        MTL_FN_SCENE_PBR_FRAG,
1987                        archive,
1988                        false,
1989                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1990                    );
1991                let (scene_pbr_skinned_pso, _): (usize, bool) =
1992                    metal_build_render_pipeline_with_depth(
1993                        device,
1994                        pbr_scene_lib,
1995                        MTL_FN_SCENE_PBR_SKINNED_VERT,
1996                        MTL_FN_SCENE_PBR_FRAG,
1997                        archive,
1998                        false,
1999                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
2000                    );
2001                let (scene_pbr_alpha_pso, _): (usize, bool) =
2002                    metal_build_render_pipeline_with_depth(
2003                        device,
2004                        pbr_scene_lib,
2005                        MTL_FN_SCENE_PBR_VERT,
2006                        MTL_FN_SCENE_PBR_FRAG,
2007                        archive,
2008                        true,
2009                        MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
2010                    );
2011                if !pbr_scene_lib.is_null() {
2012                    mtl_send_void0(pbr_scene_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
2013                }
2014                let scene_depth_stencil: usize = metal_create_depth_stencil_state(device);
2015                let scene_depth_ro_stencil: usize =
2016                    metal_create_read_only_depth_stencil_state(device);
2017                let scene_pbr_pipelines: [usize; 5] = [
2018                    scene_pbr_sky_pso,
2019                    scene_pbr_opaque_pso,
2020                    scene_pbr_skinned_pso,
2021                    scene_pbr_alpha_pso,
2022                    scene_depth_ro_stencil,
2023                ];
2024                if !archive.is_null() {
2025                    if !archive_existed
2026                        && !archive_url.is_null()
2027                        && pipeline != 0
2028                        && metal_binary_archive_allowed(&device_name, cfg!(target_abi = "sim"))
2029                        && mtl_responds_to_sel(archive, mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL))
2030                    {
2031                        let mut ser_err: *mut c_void = null_mut();
2032                        let send_ser: unsafe extern "C" fn(
2033                            *mut c_void,
2034                            *mut c_void,
2035                            *mut c_void,
2036                            *mut *mut c_void,
2037                        ) -> i8 = transmute(objc_msgSend as *const c_void);
2038                        let _: i8 = send_ser(
2039                            archive,
2040                            mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL),
2041                            archive_url,
2042                            &mut ser_err,
2043                        );
2044                    }
2045                    mtl_send_void0(archive, mtl_sel_cstr(MTL_SEL_RELEASE));
2046                }
2047                let dummy_r8_tex: usize =
2048                    metal_create_texture(device, GpuAtlasPixelFormat::R8Unorm, 1, 1);
2049                let dummy_rgba8_tex: usize =
2050                    metal_create_texture(device, GpuAtlasPixelFormat::Rgba8Unorm, 1, 1);
2051                let shader_compiled: bool = ui_fns_ok && pipeline != 0;
2052                let total_compile_us: u64 = total_start.elapsed().as_micros() as u64;
2053                MetalSharedPipelineCache {
2054                    adapter: GpuAdapterInfo::new(
2055                        GraphicsBackend::Metal,
2056                        device_name,
2057                        !queue.is_null(),
2058                        shader_compiled,
2059                    ),
2060                    device: device as usize,
2061                    queue: queue as usize,
2062                    library: library as usize,
2063                    pipeline,
2064                    blur_pipeline,
2065                    blur_up_pipeline,
2066                    engine3d_pipeline,
2067                    ocean_pipeline,
2068                    scene_ocean_pipeline,
2069                    scene_boat_pipeline,
2070                    scene_3d_sky_pipeline,
2071                    scene_3d_mesh_pipeline,
2072                    scene_depth_stencil,
2073                    scene_pbr_pipelines,
2074                    binary_archive_enabled: archive_enabled,
2075                    binary_archive_hit: archive_enabled && archive_existed,
2076                    ui_compile_us,
2077                    blur_compile_us,
2078                    engine3d_compile_us,
2079                    ocean_compile_us,
2080                    total_compile_us,
2081                    dummy_r8_tex,
2082                    dummy_rgba8_tex,
2083                }
2084            }
2085        };
2086        unsafe { objc_autoreleasePoolPop(pool) };
2087        result
2088    })
2089}
2090
2091/// Retains and returns handles from the process-wide Apple Metal shared pipeline cache for a new `NativeGpuDriver`.
2092///
2093/// # Arguments
2094///
2095/// - `GraphicsBackend` - Requested graphics backend.
2096///
2097/// # Returns
2098///
2099/// - `NativeGpuProbeOutput` - Retained device, queue, library, pipelines, and dummy texture handles.
2100#[cfg(any(target_os = "macos", target_os = "ios"))]
2101fn probe_apple_metal_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
2102    let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
2103    NativeGpuProbeOutput {
2104        adapter: cached.adapter.clone(),
2105        device_handle: mtl_retain_handle(cached.device),
2106        queue_handle: mtl_retain_handle(cached.queue),
2107        library_handle: mtl_retain_handle(cached.library),
2108        pipeline_handle: mtl_retain_handle(cached.pipeline),
2109        blur_pipeline_handle: mtl_retain_handle(cached.blur_pipeline),
2110        blur_up_pipeline_handle: mtl_retain_handle(cached.blur_up_pipeline),
2111        engine3d_pipeline_handle: mtl_retain_handle(cached.engine3d_pipeline),
2112        ocean_pipeline_handle: mtl_retain_handle(cached.ocean_pipeline),
2113        scene_ocean_pipeline_handle: mtl_retain_handle(cached.scene_ocean_pipeline),
2114        scene_boat_pipeline_handle: mtl_retain_handle(cached.scene_boat_pipeline),
2115        scene_3d_sky_pipeline_handle: mtl_retain_handle(cached.scene_3d_sky_pipeline),
2116        scene_3d_mesh_pipeline_handle: mtl_retain_handle(cached.scene_3d_mesh_pipeline),
2117        scene_depth_stencil_handle: mtl_retain_handle(cached.scene_depth_stencil),
2118        dummy_r8_tex: mtl_retain_handle(cached.dummy_r8_tex),
2119        dummy_rgba8_tex: mtl_retain_handle(cached.dummy_rgba8_tex),
2120        scene_pbr_pipelines: [
2121            mtl_retain_handle(cached.scene_pbr_pipelines[0]),
2122            mtl_retain_handle(cached.scene_pbr_pipelines[1]),
2123            mtl_retain_handle(cached.scene_pbr_pipelines[2]),
2124            mtl_retain_handle(cached.scene_pbr_pipelines[3]),
2125            mtl_retain_handle(cached.scene_pbr_pipelines[4]),
2126        ],
2127    }
2128}
2129
2130/// Returns the process-wide `OnceLock`-cached Objective-C selector pointers for Metal hot-path submission and encoding.
2131///
2132/// # Returns
2133///
2134/// - `&'static MetalSelectors` - Cached Metal selector addresses.
2135#[cfg(any(target_os = "macos", target_os = "ios"))]
2136pub(crate) fn cached_metal_selectors() -> &'static MetalSelectors {
2137    METAL_SELECTORS.get_or_init(|| MetalSelectors {
2138        retain: mtl_sel_cstr(MTL_SEL_RETAIN) as usize,
2139        new_buffer_with_bytes: mtl_sel_cstr(MTL_SEL_NEW_BUFFER) as usize,
2140        new_buffer_with_length: mtl_sel_cstr(MTL_SEL_NEW_BUFFER_LENGTH) as usize,
2141        contents: mtl_sel_cstr(MTL_SEL_CONTENTS) as usize,
2142        command_buffer: mtl_sel_cstr(MTL_SEL_CMD_BUFFER) as usize,
2143        render_encoder: mtl_sel_cstr(MTL_SEL_RENDER_ENCODER) as usize,
2144        set_pipeline_state: mtl_sel_cstr(MTL_SEL_SET_PIPELINE_STATE) as usize,
2145        set_vertex_buffer: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BUFFER) as usize,
2146        set_vertex_bytes: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BYTES) as usize,
2147        set_fragment_texture: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_TEXTURE) as usize,
2148        set_fragment_bytes: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_BYTES) as usize,
2149        set_scissor_rect: mtl_sel_cstr(MTL_SEL_SET_SCISSOR_RECT) as usize,
2150        set_viewport: mtl_sel_cstr(MTL_SEL_SET_VIEWPORT) as usize,
2151        draw_primitives_instanced: mtl_sel_cstr(MTL_SEL_DRAW_PRIMITIVES_INSTANCED) as usize,
2152        end_encoding: mtl_sel_cstr(MTL_SEL_END_ENCODING) as usize,
2153        present_drawable: mtl_sel_cstr(MTL_SEL_PRESENT_DRAWABLE) as usize,
2154        #[cfg(not(target_abi = "sim"))]
2155        add_presented_handler: mtl_sel_cstr(MTL_SEL_ADD_PRESENTED_HANDLER) as usize,
2156        add_completed_handler: mtl_sel_cstr(MTL_SEL_ADD_COMPLETED_HANDLER) as usize,
2157        #[cfg(not(target_abi = "sim"))]
2158        presented_time: mtl_sel_cstr(MTL_SEL_PRESENTED_TIME) as usize,
2159        responds_to_sel: mtl_sel_cstr(MTL_SEL_RESPONDS_TO_SEL) as usize,
2160        status: mtl_sel_cstr(MTL_SEL_STATUS) as usize,
2161        wait_until_completed: mtl_sel_cstr(MTL_SEL_WAIT_UNTIL_COMPLETED) as usize,
2162        gpu_start_time: mtl_sel_cstr(MTL_SEL_GPU_START_TIME) as usize,
2163        gpu_end_time: mtl_sel_cstr(MTL_SEL_GPU_END_TIME) as usize,
2164        next_drawable: mtl_sel_cstr(MTL_SEL_NEXT_DRAWABLE) as usize,
2165        drawable_size: mtl_sel_cstr(MTL_SEL_DRAWABLE_SIZE) as usize,
2166        set_drawable_size: mtl_sel_cstr(MTL_SEL_SET_DRAWABLE_SIZE) as usize,
2167        texture: mtl_sel_cstr(MTL_SEL_TEXTURE) as usize,
2168        width: mtl_sel_cstr(MTL_SEL_WIDTH) as usize,
2169        height: mtl_sel_cstr(MTL_SEL_HEIGHT) as usize,
2170        render_pass_desc: mtl_sel_cstr(MTL_SEL_RENDER_PASS_DESC) as usize,
2171        color_attachments: mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS) as usize,
2172        object_at_index: mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX) as usize,
2173        set_texture: mtl_sel_cstr(MTL_SEL_SET_TEXTURE) as usize,
2174        set_load_action: mtl_sel_cstr(MTL_SEL_SET_LOAD_ACTION) as usize,
2175        set_store_action: mtl_sel_cstr(MTL_SEL_SET_STORE_ACTION) as usize,
2176        set_clear_color: mtl_sel_cstr(MTL_SEL_SET_CLEAR_COLOR) as usize,
2177        depth_attachment: mtl_sel_cstr(MTL_SEL_DEPTH_ATTACHMENT) as usize,
2178        set_clear_depth: mtl_sel_cstr(MTL_SEL_SET_CLEAR_DEPTH) as usize,
2179        set_depth_stencil_state: mtl_sel_cstr(MTL_SEL_SET_DEPTH_STENCIL_STATE) as usize,
2180        replace_region: mtl_sel_cstr(MTL_SEL_REPLACE_REGION) as usize,
2181        set_fragment_buffer: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_BUFFER) as usize,
2182        draw_indexed_instanced: mtl_sel_cstr(MTL_SEL_DRAW_INDEXED_INSTANCED) as usize,
2183        new_texture_view: mtl_sel_cstr(MTL_SEL_NEW_TEXTURE_VIEW) as usize,
2184        commit: mtl_sel_cstr(MTL_SEL_COMMIT) as usize,
2185        release: mtl_sel_cstr(MTL_SEL_RELEASE) as usize,
2186    })
2187}
2188
2189/// Resolves whether macOS `CAMetalLayer.displaySyncEnabled` should be active by default (`false` when uncapped throughput env flags are set).
2190///
2191/// # Returns
2192///
2193/// - `bool` - `true` for tear-free native VRR sync; `false` when uncapped non-blocking presentation is requested.
2194#[cfg(any(target_os = "macos", target_os = "ios"))]
2195#[must_use]
2196pub(crate) fn metal_preferred_display_sync_enabled() -> bool {
2197    let uncapped_env: bool = env::var(ENV_UNCAPPED_PRESENT)
2198        .map(|val: String| {
2199            let trimmed: &str = val.trim();
2200            trimmed == MTL_ENV_VALUE_ON || trimmed.eq_ignore_ascii_case(MTL_ENV_VALUE_TRUE)
2201        })
2202        .unwrap_or(false);
2203    if uncapped_env {
2204        return false;
2205    }
2206    let sync_disabled: bool = env::var(ENV_METAL_DISPLAY_SYNC)
2207        .map(|val: String| {
2208            let trimmed: &str = val.trim();
2209            trimmed == MTL_ENV_VALUE_OFF || trimmed.eq_ignore_ascii_case(MTL_ENV_VALUE_FALSE)
2210        })
2211        .unwrap_or(false);
2212    !sync_disabled
2213}
2214
2215/// Applies `CAMetalLayer.displaySyncEnabled` when supported by the host Apple OS layer (macOS).
2216///
2217/// # Arguments
2218///
2219/// - `usize` - Target `CAMetalLayer*` pointer.
2220/// - `bool` - `true` for hardware display sync; `false` for uncapped non-blocking throughput.
2221#[cfg(any(target_os = "macos", target_os = "ios"))]
2222fn metal_set_layer_display_sync(layer_handle: usize, enabled: bool) {
2223    if layer_handle == 0 {
2224        return;
2225    }
2226    let layer: *mut c_void = layer_handle as *mut c_void;
2227    let sel_sync: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_DISPLAY_SYNC);
2228    if mtl_responds_to_sel(layer, sel_sync) {
2229        mtl_send_void_bool(layer, sel_sync, enabled);
2230    }
2231}
2232
2233/// Configures a `CAMetalLayer*` for direct triple-buffered GPU draw (`BGRA8Unorm`, `framebufferOnly = YES`, `maximumDrawableCount = 3`).
2234///
2235/// # Arguments
2236///
2237/// - `usize` - Retained `id<MTLDevice>` handle.
2238/// - `usize` - Target `CAMetalLayer*` pointer.
2239#[cfg(any(target_os = "macos", target_os = "ios"))]
2240fn metal_configure_layer(device_handle: usize, layer_handle: usize) {
2241    if device_handle == 0 || layer_handle == 0 {
2242        return;
2243    }
2244    let layer: *mut c_void = layer_handle as *mut c_void;
2245    mtl_send_void_ptr1(
2246        layer,
2247        mtl_sel_cstr(MTL_SEL_SET_DEVICE),
2248        device_handle as *mut c_void,
2249    );
2250    mtl_send_void_usize(
2251        layer,
2252        mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
2253        MTL_PIXEL_FORMAT_BGRA8_UNORM,
2254    );
2255    mtl_send_void_bool(layer, mtl_sel_cstr(MTL_SEL_SET_FRAMEBUFFER_ONLY), true);
2256    let sel_max: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_MAX_DRAWABLE_COUNT);
2257    if mtl_responds_to_sel(layer, sel_max) {
2258        mtl_send_void_usize(layer, sel_max, GPU_DRIVER_RING_SLOTS);
2259    }
2260    metal_set_layer_display_sync(layer_handle, metal_preferred_display_sync_enabled());
2261}
2262
2263/// Uploads a dirty R8 or RGBA8 sub-rectangle into a Metal `MTLTexture` via `replaceRegion:mipmapLevel:withBytes:bytesPerRow:`.
2264///
2265/// # Arguments
2266///
2267/// - `usize` - Retained `id<MTLDevice>` handle.
2268/// - `&mut usize` - Resident `id<MTLTexture>` handle (`0` lazily allocates a new texture).
2269/// - `GpuAtlasPixelFormat` - Target Metal pixel format.
2270/// - `(u32, u32)` - Backing texture dimensions `(width, height)`.
2271/// - `(u32, u32, u32, u32)` - Dirty sub-region `(x, y, width, height)`.
2272/// - `&[u8]` - Source pixel slice.
2273/// - `usize` - Row stride in bytes.
2274///
2275/// # Returns
2276///
2277/// - `bool` - `true` when the dirty sub-rectangle uploaded cleanly.
2278#[cfg(any(target_os = "macos", target_os = "ios"))]
2279fn metal_upload_texture_dirty_rect(
2280    device_handle: usize,
2281    texture_handle: &mut usize,
2282    format: GpuAtlasPixelFormat,
2283    tex_dims: (u32, u32),
2284    dirty_rect: (u32, u32, u32, u32),
2285    bytes: &[u8],
2286    bytes_per_row: usize,
2287) -> bool {
2288    if device_handle == 0 || dirty_rect.2 == 0 || dirty_rect.3 == 0 || bytes.is_empty() {
2289        return false;
2290    }
2291    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
2292    let (tex_w, tex_h): (u32, u32) = (tex_dims.0.max(1), tex_dims.1.max(1));
2293    let sel: &MetalSelectors = cached_metal_selectors();
2294    let cur_w: usize = if *texture_handle != 0 {
2295        mtl_send_usize0(*texture_handle as *mut c_void, sel.width as *mut c_void)
2296    } else {
2297        0
2298    };
2299    let cur_h: usize = if *texture_handle != 0 {
2300        mtl_send_usize0(*texture_handle as *mut c_void, sel.height as *mut c_void)
2301    } else {
2302        0
2303    };
2304    if *texture_handle == 0 || cur_w != tex_w as usize || cur_h != tex_h as usize {
2305        if *texture_handle != 0 {
2306            mtl_send_void0(*texture_handle as *mut c_void, sel.release as *mut c_void);
2307        }
2308        *texture_handle = metal_create_texture(device_handle as *mut c_void, format, tex_w, tex_h);
2309    }
2310    if *texture_handle == 0 {
2311        unsafe { objc_autoreleasePoolPop(pool) };
2312        return false;
2313    }
2314    let region: MtlRegion = MtlRegion {
2315        origin: MtlOrigin {
2316            x: dirty_rect.0 as usize,
2317            y: dirty_rect.1 as usize,
2318            z: 0,
2319        },
2320        size: MtlSize {
2321            width: dirty_rect.2 as usize,
2322            height: dirty_rect.3 as usize,
2323            depth: 1,
2324        },
2325    };
2326    unsafe {
2327        let send_replace: unsafe extern "C" fn(
2328            *mut c_void,
2329            *mut c_void,
2330            MtlRegion,
2331            usize,
2332            *const c_void,
2333            usize,
2334        ) = transmute(objc_msgSend as *const c_void);
2335        send_replace(
2336            *texture_handle as *mut c_void,
2337            sel.replace_region as *mut c_void,
2338            region,
2339            0,
2340            bytes.as_ptr().cast::<c_void>(),
2341            bytes_per_row,
2342        );
2343        objc_autoreleasePoolPop(pool);
2344    }
2345    true
2346}
2347
2348/// Uploads packed 64-byte `GpuPrimitiveInstance` buffers into a 3-slot fenced Metal ring, encodes real instanced `MTLRenderCommandEncoder` draws when a `CAMetalLayer` is bound, and commits with presentation timing handlers.
2349///
2350/// # Arguments
2351///
2352/// - `&mut NativeGpuDriver` - Mutable GPU driver holding ring slots, pipelines, textures, and layer handle.
2353/// - `u32` - Physical surface width in pixels.
2354/// - `u32` - Physical surface height in pixels.
2355/// - `Color` - Surface clear color.
2356/// - `&[GpuBatch]` - Ordered GPU batches to encode and submit.
2357///
2358/// # Returns
2359///
2360/// - `usize` - Total 64-byte `GpuPrimitiveInstance` records uploaded and submitted.
2361#[cfg(any(target_os = "macos", target_os = "ios"))]
2362fn metal_submit_ring_frame(
2363    driver: &mut NativeGpuDriver,
2364    width: u32,
2365    height: u32,
2366    clear_color: Color,
2367    batches: &[GpuBatch],
2368) -> usize {
2369    let total_instances: usize = batches
2370        .iter()
2371        .map(|blue_val: &GpuBatch| {
2372            blue_val
2373                .get_primitives()
2374                .len()
2375                .max(blue_val.get_instances().len())
2376        })
2377        .sum();
2378    let device_handle: usize = driver.get_device_handle();
2379    let queue_handle: usize = driver.get_queue_handle();
2380    let layer_handle: usize = driver.get_surface_layer_handle();
2381    if device_handle == 0 || queue_handle == 0 || layer_handle == 0 {
2382        return total_instances;
2383    }
2384    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
2385    let sel: &MetalSelectors = cached_metal_selectors();
2386    let sel_rel: *mut c_void = sel.release as *mut c_void;
2387    let slot_idx: usize = driver.get_ring_cursor() % GPU_DRIVER_RING_SLOTS;
2388    let device: *mut c_void = device_handle as *mut c_void;
2389    let queue: *mut c_void = queue_handle as *mut c_void;
2390    let pipeline: *mut c_void = driver.get_pipeline_handle() as *mut c_void;
2391    let blur_down_pso: *mut c_void = driver.get_blur_pipeline_handle() as *mut c_void;
2392    let blur_up_pso: *mut c_void = driver.get_blur_up_pipeline_handle() as *mut c_void;
2393    let scene_pipelines: [*mut c_void; 5] = [
2394        driver.get_scene_ocean_pipeline_handle() as *mut c_void,
2395        driver.get_scene_boat_pipeline_handle() as *mut c_void,
2396        driver.get_scene_3d_sky_pipeline_handle() as *mut c_void,
2397        driver.get_scene_3d_mesh_pipeline_handle() as *mut c_void,
2398        driver.get_scene_depth_stencil_handle() as *mut c_void,
2399    ];
2400    let layer_ptr: *mut c_void = layer_handle as *mut c_void;
2401    let tex_r8: *mut c_void = driver.get_glyph_r8_texture_handle() as *mut c_void;
2402    let tex_rgba8: *mut c_void = driver.get_glyph_rgba8_texture_handle() as *mut c_void;
2403    let tex_img: *mut c_void = driver.get_image_texture_handle() as *mut c_void;
2404    let raw_ext: usize = driver.get_external_texture_handle();
2405    let mut tex_ext: *mut c_void = if raw_ext != 0 {
2406        raw_ext as *mut c_void
2407    } else {
2408        tex_rgba8
2409    };
2410    let has_blur_batches: bool = !blur_down_pso.is_null()
2411        && !blur_up_pso.is_null()
2412        && batches.iter().any(|batch_item: &GpuBatch| {
2413            batch_item
2414                .get_primitives()
2415                .iter()
2416                .any(|prim_item: &GpuPrimitiveInstance| {
2417                    prim_item.prim_kind() == PrimKind::BackdropBlur
2418                })
2419        });
2420    let total_bytes: usize = total_instances.saturating_mul(size_of::<GpuPrimitiveInstance>());
2421    let NativeGpuDriver {
2422        ring_slots,
2423        ring_cursor,
2424        staging_buffer_handle,
2425        staging_contents_ptr,
2426        staging_buffer_capacity,
2427        staging_reallocations,
2428        scratch_primitives,
2429        blur_scene_texture_handle,
2430        blur_half_texture_handle,
2431        blur_full_texture_handle,
2432        blur_texture_dims,
2433        scene_color_texture_handle,
2434        scene_depth_texture_handle,
2435        scene_wake_texture_handle,
2436        scene_wake_texture_handles,
2437        scene_texture_dims,
2438        scene_3d_vertex_buffer_handle,
2439        scene_3d_vertex_revision,
2440        scene_3d_vertex_capacity,
2441        scene_3d_instance_buffer_handle,
2442        scene_3d_instance_capacity,
2443        scene_3d_instance_buffer_handles,
2444        scene_3d_instance_capacities,
2445        scene_boat_buffer_handle,
2446        scene_boat_capacity,
2447        scene_boat_buffer_handles,
2448        scene_boat_capacities,
2449        pending_gpu_scene_pass,
2450        pbr_scene_resources,
2451        ..
2452    } = driver;
2453    let frame_scene_pass: Option<DirectGpuScenePass> = pending_gpu_scene_pass.take();
2454    let slot: &mut NativeGpuRingSlot = &mut ring_slots[slot_idx];
2455    let prev_cmd: usize = slot.get_in_flight_cmd_buffer();
2456    if prev_cmd != 0 {
2457        let status: usize = mtl_send_usize0(prev_cmd as *mut c_void, sel.status as *mut c_void);
2458        if status < MTL_CMD_BUFFER_STATUS_COMPLETED {
2459            mtl_send_void0(
2460                prev_cmd as *mut c_void,
2461                sel.wait_until_completed as *mut c_void,
2462            );
2463        }
2464        mtl_send_void0(prev_cmd as *mut c_void, sel_rel);
2465        slot.set_in_flight_cmd_buffer(0);
2466    }
2467    if total_bytes > 0
2468        && (slot.get_buffer_handle() == 0
2469            || slot.get_contents_ptr() == 0
2470            || total_bytes > slot.get_capacity_bytes())
2471    {
2472        if slot.get_buffer_handle() != 0 {
2473            mtl_send_void0(slot.get_buffer_handle() as *mut c_void, sel_rel);
2474            slot.set_buffer_handle(0);
2475            slot.set_contents_ptr(0);
2476            slot.set_capacity_bytes(0);
2477        }
2478        let alloc_bytes: usize = total_bytes.max(4096).next_power_of_two();
2479        unsafe {
2480            let send_new_len: unsafe extern "C" fn(
2481                *mut c_void,
2482                *mut c_void,
2483                usize,
2484                usize,
2485            ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
2486            let new_buf: *mut c_void = send_new_len(
2487                device,
2488                sel.new_buffer_with_length as *mut c_void,
2489                alloc_bytes,
2490                0,
2491            );
2492            if !new_buf.is_null() {
2493                let ptr: *mut c_void = mtl_send_ptr0(new_buf, sel.contents as *mut c_void);
2494                if !ptr.is_null() {
2495                    slot.set_buffer_handle(new_buf as usize);
2496                    slot.set_contents_ptr(ptr as usize);
2497                    slot.set_capacity_bytes(alloc_bytes);
2498                    *staging_reallocations = staging_reallocations.wrapping_add(1);
2499                } else {
2500                    mtl_send_void0(new_buf, sel_rel);
2501                }
2502            }
2503        }
2504    }
2505    let buf_handle: usize = slot.get_buffer_handle();
2506    let contents_ptr: usize = slot.get_contents_ptr();
2507    let capacity_bytes: usize = slot.get_capacity_bytes();
2508    *staging_buffer_handle = buf_handle;
2509    *staging_contents_ptr = contents_ptr;
2510    *staging_buffer_capacity = capacity_bytes;
2511    if contents_ptr != 0 && total_bytes > 0 && total_bytes <= capacity_bytes {
2512        unsafe {
2513            let mut dst: *mut u8 = (contents_ptr as *mut c_void).cast::<u8>();
2514            for batch in batches.iter() {
2515                let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
2516                if !prims.is_empty() {
2517                    let byte_len: usize = size_of_val(prims);
2518                    dst.copy_from_nonoverlapping(prims.as_ptr().cast::<u8>(), byte_len);
2519                    dst = dst.add(byte_len);
2520                } else if !batch.get_instances().is_empty() {
2521                    scratch_primitives.clear();
2522                    for quad in batch.get_instances().iter() {
2523                        scratch_primitives.push(GpuPrimitiveInstance::from_quad_instance(
2524                            quad,
2525                            batch.get_texture_slot(),
2526                            batch.get_layer_id(),
2527                        ));
2528                    }
2529                    let byte_len: usize = size_of_val(scratch_primitives.as_slice());
2530                    dst.copy_from_nonoverlapping(
2531                        scratch_primitives.as_ptr().cast::<u8>(),
2532                        byte_len,
2533                    );
2534                    dst = dst.add(byte_len);
2535                }
2536            }
2537        }
2538    }
2539    let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
2540    if !cmd_buf.is_null() {
2541        let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
2542        if mtl_responds_to_sel(cmd_buf, sel_completed) {
2543            mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
2544        }
2545        if !layer_ptr.is_null() && !pipeline.is_null() {
2546            if width > 0
2547                && height > 0
2548                && mtl_responds_to_sel(layer_ptr, sel.set_drawable_size as *mut c_void)
2549            {
2550                let target_w: f64 = f64::from(width);
2551                let target_h: f64 = f64::from(height);
2552                let needs_resize: bool =
2553                    if mtl_responds_to_sel(layer_ptr, sel.drawable_size as *mut c_void) {
2554                        // SAFETY: `-[CAMetalLayer drawableSize]` returns a 16-byte `CGSize` in FP registers on 64-bit Apple targets.
2555                        let cur: MtlCgSize = unsafe {
2556                            let get_size: unsafe extern "C" fn(
2557                                *mut c_void,
2558                                *mut c_void,
2559                            )
2560                                -> MtlCgSize = transmute(objc_msgSend as *const c_void);
2561                            get_size(layer_ptr, sel.drawable_size as *mut c_void)
2562                        };
2563                        (cur.width - target_w).abs() > 0.5 || (cur.height - target_h).abs() > 0.5
2564                    } else {
2565                        true
2566                    };
2567                if needs_resize {
2568                    // SAFETY: `-[CAMetalLayer setDrawableSize:]` takes a single `CGSize` (`{ f64, f64 }`) value.
2569                    unsafe {
2570                        let set_size: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlCgSize) =
2571                            transmute(objc_msgSend as *const c_void);
2572                        set_size(
2573                            layer_ptr,
2574                            sel.set_drawable_size as *mut c_void,
2575                            MtlCgSize {
2576                                width: target_w,
2577                                height: target_h,
2578                            },
2579                        );
2580                    }
2581                }
2582            }
2583            let drawable: *mut c_void = mtl_send_ptr0(layer_ptr, sel.next_drawable as *mut c_void);
2584            if !drawable.is_null() {
2585                let drawable_tex: *mut c_void = mtl_send_ptr0(drawable, sel.texture as *mut c_void);
2586                let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
2587                if !drawable_tex.is_null() && !pass_cls.is_null() {
2588                    let tex_w: usize = mtl_send_usize0(drawable_tex, sel.width as *mut c_void);
2589                    let tex_h: usize = mtl_send_usize0(drawable_tex, sel.height as *mut c_void);
2590                    let draw_w: usize = if tex_w > 0 {
2591                        tex_w
2592                    } else {
2593                        width.max(1) as usize
2594                    };
2595                    let draw_h: usize = if tex_h > 0 {
2596                        tex_h
2597                    } else {
2598                        height.max(1) as usize
2599                    };
2600                    let clear_rgba: [f32; 4] = clear_color.to_f32_array();
2601                    let mtl_clear: MtlClearColor = MtlClearColor {
2602                        red: clear_rgba[0] as f64,
2603                        green: clear_rgba[1] as f64,
2604                        blue: clear_rgba[2] as f64,
2605                        alpha: clear_rgba[3] as f64,
2606                    };
2607                    let mut use_blur_offscreen: bool = false;
2608                    let mut scene_tex_ptr: *mut c_void = null_mut();
2609                    let mut half_tex_ptr: *mut c_void = null_mut();
2610                    let mut full_tex_ptr: *mut c_void = null_mut();
2611                    let half_w_u32: u32 = ((draw_w as u32) / 2).max(1);
2612                    let half_h_u32: u32 = ((draw_h as u32) / 2).max(1);
2613                    if has_blur_batches {
2614                        let target_dims: (u32, u32) = (draw_w as u32, draw_h as u32);
2615                        if *blur_scene_texture_handle == 0
2616                            || *blur_half_texture_handle == 0
2617                            || *blur_full_texture_handle == 0
2618                            || *blur_texture_dims != target_dims
2619                        {
2620                            release_native_gpu_object(*blur_scene_texture_handle);
2621                            release_native_gpu_object(*blur_half_texture_handle);
2622                            release_native_gpu_object(*blur_full_texture_handle);
2623                            let unified_mem: bool = cfg!(target_arch = "aarch64");
2624                            *blur_scene_texture_handle = metal_create_offscreen_render_texture(
2625                                device_handle,
2626                                target_dims.0,
2627                                target_dims.1,
2628                                unified_mem,
2629                            );
2630                            *blur_half_texture_handle = metal_create_offscreen_render_texture(
2631                                device_handle,
2632                                half_w_u32,
2633                                half_h_u32,
2634                                unified_mem,
2635                            );
2636                            *blur_full_texture_handle = metal_create_offscreen_render_texture(
2637                                device_handle,
2638                                target_dims.0,
2639                                target_dims.1,
2640                                unified_mem,
2641                            );
2642                            *blur_texture_dims = target_dims;
2643                        }
2644                        scene_tex_ptr = *blur_scene_texture_handle as *mut c_void;
2645                        half_tex_ptr = *blur_half_texture_handle as *mut c_void;
2646                        full_tex_ptr = *blur_full_texture_handle as *mut c_void;
2647                        use_blur_offscreen = !scene_tex_ptr.is_null()
2648                            && !half_tex_ptr.is_null()
2649                            && !full_tex_ptr.is_null();
2650                    }
2651                    let primary_target: *mut c_void = if use_blur_offscreen {
2652                        scene_tex_ptr
2653                    } else {
2654                        drawable_tex
2655                    };
2656                    if let Some(scene_pass) = frame_scene_pass.as_ref() {
2657                        let mut scene_buf_handles: [usize; 6] = [
2658                            *scene_3d_vertex_buffer_handle,
2659                            *scene_3d_vertex_capacity,
2660                            scene_3d_instance_buffer_handles[slot_idx],
2661                            scene_3d_instance_capacities[slot_idx],
2662                            scene_boat_buffer_handles[slot_idx],
2663                            scene_boat_capacities[slot_idx],
2664                        ];
2665                        let maybe_scene_tex: Option<*mut c_void> = metal_encode_gpu_scene_pass(
2666                            [cmd_buf, pass_cls, device],
2667                            scene_pipelines,
2668                            (
2669                                scene_color_texture_handle,
2670                                scene_depth_texture_handle,
2671                                &mut scene_wake_texture_handles[slot_idx],
2672                                scene_texture_dims,
2673                            ),
2674                            (&mut scene_buf_handles, scene_3d_vertex_revision),
2675                            (pbr_scene_resources, slot_idx, tex_rgba8),
2676                            scene_pass,
2677                        );
2678                        *scene_wake_texture_handle = scene_wake_texture_handles[slot_idx];
2679                        *scene_3d_vertex_buffer_handle = scene_buf_handles[0];
2680                        *scene_3d_vertex_capacity = scene_buf_handles[1];
2681                        scene_3d_instance_buffer_handles[slot_idx] = scene_buf_handles[2];
2682                        scene_3d_instance_capacities[slot_idx] = scene_buf_handles[3];
2683                        scene_boat_buffer_handles[slot_idx] = scene_buf_handles[4];
2684                        scene_boat_capacities[slot_idx] = scene_buf_handles[5];
2685                        *scene_3d_instance_buffer_handle = scene_buf_handles[2];
2686                        *scene_3d_instance_capacity = scene_buf_handles[3];
2687                        *scene_boat_buffer_handle = scene_buf_handles[4];
2688                        *scene_boat_capacity = scene_buf_handles[5];
2689                        if let Some(rendered_scene_tex) = maybe_scene_tex {
2690                            tex_ext = rendered_scene_tex;
2691                        }
2692                    }
2693                    let mut active_encoder: *mut c_void = metal_begin_ui_render_encoder(
2694                        cmd_buf,
2695                        pass_cls,
2696                        primary_target,
2697                        (MTL_LOAD_ACTION_CLEAR, mtl_clear),
2698                        (draw_w, draw_h),
2699                        (pipeline, buf_handle as *mut c_void),
2700                        [tex_r8, tex_rgba8, tex_img, tex_ext],
2701                    );
2702                    let mut base_instance: usize = 0;
2703                    for batch in batches.iter() {
2704                        let count: usize = batch
2705                            .get_primitives()
2706                            .len()
2707                            .max(batch.get_instances().len());
2708                        if count == 0 || buf_handle == 0 {
2709                            continue;
2710                        }
2711                        let is_blur_batch: bool = use_blur_offscreen
2712                            && batch.get_primitives().iter().any(
2713                                |prim_item: &GpuPrimitiveInstance| {
2714                                    prim_item.prim_kind() == PrimKind::BackdropBlur
2715                                },
2716                            );
2717                        if is_blur_batch {
2718                            if !active_encoder.is_null() {
2719                                mtl_send_void0(active_encoder, sel.end_encoding as *mut c_void);
2720                            }
2721                            let blur_prim_opt: Option<&GpuPrimitiveInstance> = batch
2722                                .get_primitives()
2723                                .iter()
2724                                .find(|prim_item: &&GpuPrimitiveInstance| {
2725                                    prim_item.prim_kind() == PrimKind::BackdropBlur
2726                                });
2727                            let blur_offset: f32 = blur_prim_opt
2728                                .map_or(2.5, |prim_item: &GpuPrimitiveInstance| {
2729                                    prim_item.backdrop_blur_offset()
2730                                });
2731                            let clip_uv: [f32; 4] = blur_prim_opt.map_or(
2732                                [0.0; 4],
2733                                |prim_item: &GpuPrimitiveInstance| {
2734                                    prim_item.backdrop_blur_clip_uv(
2735                                        (draw_w as f32, draw_h as f32),
2736                                        [0.0, 0.0],
2737                                        false,
2738                                    )
2739                                },
2740                            );
2741                            let down_uniform: GpuBlurUniforms = GpuBlurUniforms::new(
2742                                [1.0 / (draw_w.max(1) as f32), 1.0 / (draw_h.max(1) as f32)],
2743                                blur_offset,
2744                                GPU_BLUR_PASS_MODE_DOWN,
2745                                clip_uv,
2746                            );
2747                            let up_uniform: GpuBlurUniforms = GpuBlurUniforms::new(
2748                                [1.0 / (half_w_u32 as f32), 1.0 / (half_h_u32 as f32)],
2749                                blur_offset,
2750                                GPU_BLUR_PASS_MODE_UP,
2751                                clip_uv,
2752                            );
2753                            let _: bool = metal_encode_fullscreen_blur_pass(
2754                                cmd_buf,
2755                                pass_cls,
2756                                half_tex_ptr,
2757                                blur_down_pso,
2758                                scene_tex_ptr,
2759                                &down_uniform,
2760                            );
2761                            let _: bool = metal_encode_fullscreen_blur_pass(
2762                                cmd_buf,
2763                                pass_cls,
2764                                full_tex_ptr,
2765                                blur_up_pso,
2766                                half_tex_ptr,
2767                                &up_uniform,
2768                            );
2769                            active_encoder = metal_begin_ui_render_encoder(
2770                                cmd_buf,
2771                                pass_cls,
2772                                scene_tex_ptr,
2773                                (MTL_LOAD_ACTION_LOAD, mtl_clear),
2774                                (draw_w, draw_h),
2775                                (pipeline, buf_handle as *mut c_void),
2776                                [tex_r8, tex_rgba8, tex_img, full_tex_ptr],
2777                            );
2778                        }
2779                        if !active_encoder.is_null() {
2780                            metal_encode_ui_batch_draw(
2781                                active_encoder,
2782                                (draw_w, draw_h),
2783                                batch,
2784                                count,
2785                                base_instance,
2786                            );
2787                            if is_blur_batch && !tex_ext.is_null() {
2788                                unsafe {
2789                                    let send_ftex: unsafe extern "C" fn(
2790                                        *mut c_void,
2791                                        *mut c_void,
2792                                        *mut c_void,
2793                                        usize,
2794                                    ) = transmute(objc_msgSend as *const c_void);
2795                                    send_ftex(
2796                                        active_encoder,
2797                                        sel.set_fragment_texture as *mut c_void,
2798                                        tex_ext,
2799                                        3,
2800                                    );
2801                                }
2802                            }
2803                        }
2804                        base_instance = base_instance.saturating_add(count);
2805                    }
2806                    if !active_encoder.is_null() {
2807                        mtl_send_void0(active_encoder, sel.end_encoding as *mut c_void);
2808                    }
2809                    if use_blur_offscreen {
2810                        let copy_uniform: GpuBlurUniforms = GpuBlurUniforms::new(
2811                            [1.0 / (draw_w.max(1) as f32), 1.0 / (draw_h.max(1) as f32)],
2812                            0.5,
2813                            GPU_BLUR_PASS_MODE_COPY,
2814                            [0.0; 4],
2815                        );
2816                        let _: bool = metal_encode_fullscreen_blur_pass(
2817                            cmd_buf,
2818                            pass_cls,
2819                            drawable_tex,
2820                            blur_up_pso,
2821                            scene_tex_ptr,
2822                            &copy_uniform,
2823                        );
2824                    }
2825                    #[cfg(not(target_abi = "sim"))]
2826                    {
2827                        let sel_pres: *mut c_void = sel.add_presented_handler as *mut c_void;
2828                        if mtl_responds_to_sel(drawable, sel_pres) {
2829                            mtl_send_void_ptr1(drawable, sel_pres, metal_presented_block_ptr());
2830                        }
2831                    }
2832                    mtl_send_void_ptr1(cmd_buf, sel.present_drawable as *mut c_void, drawable);
2833                }
2834            }
2835        }
2836        let retained_cmd: usize = mtl_retain_handle(cmd_buf as usize);
2837        slot.set_in_flight_cmd_buffer(retained_cmd);
2838        let _: u64 = SUBMITTED_GPU_FENCE.fetch_add(1, Ordering::AcqRel);
2839        mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
2840    }
2841    *ring_cursor = (slot_idx + 1) % GPU_DRIVER_RING_SLOTS;
2842    unsafe { objc_autoreleasePoolPop(pool) };
2843    total_instances
2844}
2845
2846/// Executes Dual-Kawase `blur_down` and `blur_up` ping-pong passes on Apple Metal into persistent offscreen textures.
2847///
2848/// # Arguments
2849///
2850/// - `&mut NativeGpuDriver` - Mutable Apple Metal GPU driver retaining both `blur_pipeline` and `blur_up_pipeline`.
2851/// - `u32` - Physical surface width in pixels.
2852/// - `u32` - Physical surface height in pixels.
2853/// - `&[GpuBackdropBlurPass]` - Active Dual-Kawase blur regions.
2854///
2855/// # Returns
2856///
2857/// - `usize` - Number of Dual-Kawase blur regions executed on hardware Metal (`0` when unsupported).
2858#[cfg(any(target_os = "macos", target_os = "ios"))]
2859fn metal_execute_dual_kawase_blur_passes(
2860    driver: &mut NativeGpuDriver,
2861    width: u32,
2862    height: u32,
2863    blur_passes: &[GpuBackdropBlurPass],
2864) -> usize {
2865    let device_handle: usize = driver.get_device_handle();
2866    let queue_handle: usize = driver.get_queue_handle();
2867    let blur_down_pso: usize = driver.get_blur_pipeline_handle();
2868    let blur_up_pso: usize = driver.get_blur_up_pipeline_handle();
2869    if device_handle == 0
2870        || queue_handle == 0
2871        || blur_down_pso == 0
2872        || blur_up_pso == 0
2873        || blur_passes.is_empty()
2874    {
2875        return 0;
2876    }
2877    let full_w: u32 = width.max(2);
2878    let full_h: u32 = height.max(2);
2879    let half_w: u32 = (full_w / 2).max(1);
2880    let half_h: u32 = (full_h / 2).max(1);
2881    let src_tex_handle: usize = if driver.get_external_texture_handle() != 0 {
2882        driver.get_external_texture_handle()
2883    } else if driver.get_image_texture_handle() != 0 {
2884        driver.get_image_texture_handle()
2885    } else {
2886        driver.get_glyph_rgba8_texture_handle()
2887    };
2888    if src_tex_handle == 0 {
2889        return 0;
2890    }
2891    let NativeGpuDriver {
2892        blur_half_texture_handle,
2893        blur_full_texture_handle,
2894        blur_texture_dims,
2895        ..
2896    } = driver;
2897    if *blur_half_texture_handle == 0
2898        || *blur_full_texture_handle == 0
2899        || *blur_texture_dims != (full_w, full_h)
2900    {
2901        release_native_gpu_object(*blur_half_texture_handle);
2902        release_native_gpu_object(*blur_full_texture_handle);
2903        let unified_mem: bool = cfg!(target_arch = "aarch64");
2904        *blur_half_texture_handle =
2905            metal_create_offscreen_render_texture(device_handle, half_w, half_h, unified_mem);
2906        *blur_full_texture_handle =
2907            metal_create_offscreen_render_texture(device_handle, full_w, full_h, unified_mem);
2908        *blur_texture_dims = (full_w, full_h);
2909    }
2910    let half_tex: *mut c_void = *blur_half_texture_handle as *mut c_void;
2911    let full_tex: *mut c_void = *blur_full_texture_handle as *mut c_void;
2912    if half_tex.is_null() || full_tex.is_null() {
2913        return 0;
2914    }
2915    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
2916    let sel: &MetalSelectors = cached_metal_selectors();
2917    let queue: *mut c_void = queue_handle as *mut c_void;
2918    let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
2919    if cmd_buf.is_null() {
2920        unsafe { objc_autoreleasePoolPop(pool) };
2921        return 0;
2922    }
2923    let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
2924    if mtl_responds_to_sel(cmd_buf, sel_completed) {
2925        mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
2926    }
2927    let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
2928    let mut executed: usize = 0;
2929    let max_regions: usize = blur_passes.len().min(RENDER_GRAPH_MAX_BLUR_PASSES);
2930    for pass in blur_passes.iter().take(max_regions) {
2931        let blur_offset: f32 = (pass.get_blur_radius() * 0.25).clamp(0.5, 8.0);
2932        let clip: Rect = pass.get_clip_rect();
2933        let fw: f32 = full_w as f32;
2934        let fh: f32 = full_h as f32;
2935        let u0: f32 = (clip.get_x() / fw).clamp(0.0, 1.0);
2936        let v0: f32 = (clip.get_y() / fh).clamp(0.0, 1.0);
2937        let u1: f32 = (clip.right() / fw).clamp(u0, 1.0);
2938        let v1: f32 = (clip.bottom() / fh).clamp(v0, 1.0);
2939        let clip_uv: [f32; 4] = if u1 > u0 && v1 > v0 {
2940            [u0, v0, u1, v1]
2941        } else {
2942            [0.0; 4]
2943        };
2944        let down_uniform: GpuBlurUniforms = GpuBlurUniforms::new(
2945            [1.0 / fw, 1.0 / fh],
2946            blur_offset,
2947            GPU_BLUR_PASS_MODE_DOWN,
2948            clip_uv,
2949        );
2950        let up_uniform: GpuBlurUniforms = GpuBlurUniforms::new(
2951            [1.0 / (half_w as f32), 1.0 / (half_h as f32)],
2952            blur_offset,
2953            GPU_BLUR_PASS_MODE_UP,
2954            clip_uv,
2955        );
2956        let down_ok: bool = metal_encode_fullscreen_blur_pass(
2957            cmd_buf,
2958            pass_cls,
2959            half_tex,
2960            blur_down_pso as *mut c_void,
2961            src_tex_handle as *mut c_void,
2962            &down_uniform,
2963        );
2964        let up_ok: bool = if down_ok {
2965            metal_encode_fullscreen_blur_pass(
2966                cmd_buf,
2967                pass_cls,
2968                full_tex,
2969                blur_up_pso as *mut c_void,
2970                half_tex,
2971                &up_uniform,
2972            )
2973        } else {
2974            false
2975        };
2976        if down_ok && up_ok {
2977            executed = executed.saturating_add(1);
2978        }
2979    }
2980    let _: u64 = SUBMITTED_GPU_FENCE.fetch_add(1, Ordering::AcqRel);
2981    mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
2982    unsafe { objc_autoreleasePoolPop(pool) };
2983    executed
2984}
2985
2986/// Encodes one fullscreen triangle Dual-Kawase blur render pass (`blur_down` or `blur_up`) into `dst_tex`.
2987///
2988/// # Arguments
2989///
2990/// - `*mut c_void` - Active `id<MTLCommandBuffer>`.
2991/// - `*mut c_void` - `MTLRenderPassDescriptor` class pointer.
2992/// - `*mut c_void` - Destination `id<MTLTexture>` render target.
2993/// - `*mut c_void` - Compiled Dual-Kawase `id<MTLRenderPipelineState>`.
2994/// - `*mut c_void` - Source `id<MTLTexture>` sampled at fragment texture index `0`.
2995/// - `&GpuBlurUniforms` - 32-byte `BlurUniforms` payload bound at fragment buffer index `0`.
2996///
2997/// # Returns
2998///
2999/// - `bool` - `true` when the render pass encoded cleanly.
3000#[cfg(any(target_os = "macos", target_os = "ios"))]
3001fn metal_encode_fullscreen_blur_pass(
3002    cmd_buf: *mut c_void,
3003    pass_cls: *mut c_void,
3004    dst_tex: *mut c_void,
3005    pso: *mut c_void,
3006    src_tex: *mut c_void,
3007    uniform: &GpuBlurUniforms,
3008) -> bool {
3009    let sel: &MetalSelectors = cached_metal_selectors();
3010    let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
3011    if pass_desc.is_null() {
3012        return false;
3013    }
3014    let color_atts: *mut c_void = mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
3015    let att0: *mut c_void = unsafe {
3016        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
3017            transmute(objc_msgSend as *const c_void);
3018        send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
3019    };
3020    if att0.is_null() {
3021        return false;
3022    }
3023    mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, dst_tex);
3024    mtl_send_void_usize(
3025        att0,
3026        sel.set_load_action as *mut c_void,
3027        MTL_LOAD_ACTION_CLEAR,
3028    );
3029    unsafe {
3030        let send_clear: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlClearColor) =
3031            transmute(objc_msgSend as *const c_void);
3032        send_clear(
3033            att0,
3034            sel.set_clear_color as *mut c_void,
3035            MtlClearColor {
3036                red: 0.0,
3037                green: 0.0,
3038                blue: 0.0,
3039                alpha: 1.0,
3040            },
3041        );
3042    }
3043    mtl_send_void_usize(
3044        att0,
3045        sel.set_store_action as *mut c_void,
3046        MTL_STORE_ACTION_STORE,
3047    );
3048    let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
3049    if encoder.is_null() {
3050        return false;
3051    }
3052    mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, pso);
3053    unsafe {
3054        let send_fbytes: unsafe extern "C" fn(
3055            *mut c_void,
3056            *mut c_void,
3057            *const c_void,
3058            usize,
3059            usize,
3060        ) = transmute(objc_msgSend as *const c_void);
3061        let send_ftex: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, usize) =
3062            transmute(objc_msgSend as *const c_void);
3063        let send_draw: unsafe extern "C" fn(
3064            *mut c_void,
3065            *mut c_void,
3066            usize,
3067            usize,
3068            usize,
3069            usize,
3070            usize,
3071        ) = transmute(objc_msgSend as *const c_void);
3072        send_fbytes(
3073            encoder,
3074            sel.set_fragment_bytes as *mut c_void,
3075            (uniform as *const GpuBlurUniforms).cast::<c_void>(),
3076            size_of::<GpuBlurUniforms>(),
3077            0,
3078        );
3079        send_ftex(encoder, sel.set_fragment_texture as *mut c_void, src_tex, 0);
3080        send_draw(
3081            encoder,
3082            sel.draw_primitives_instanced as *mut c_void,
3083            MTL_PRIMITIVE_TYPE_TRIANGLE,
3084            0,
3085            3,
3086            1,
3087            0,
3088        );
3089    }
3090    mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
3091    true
3092}
3093
3094/// Encodes an inline offscreen hardware GPU `DirectGpuScenePass` (`OceanFluid`, `World3d`, or `PbrScene`) before UI compositing.
3095///
3096/// # Arguments
3097///
3098/// - `[*mut c_void; 3]` - Active Metal handles `[cmd_buf, pass_cls, device]`.
3099/// - `[*mut c_void; 5]` - Pipeline handles `[ocean_pso, boat_pso, sky_pso, mesh_pso, depth_stencil]`.
3100/// - `(&mut usize, &mut usize, &mut usize, &mut (u32, u32))` - Offscreen color, depth, wake textures, and dimensions.
3101/// - `(&mut [usize; 6], &mut u64)` - Legacy `World3d`/boat vertex and instance buffers plus mesh revision.
3102/// - `(&mut MetalPbrSceneResources, usize, *mut c_void)` - Resident `PbrScene` pipelines/buffers/mip pool, ring slot index, and fallback 1x1 RGBA8 texture.
3103/// - `&DirectGpuScenePass` - Hardware scene pass payload to encode.
3104///
3105/// # Returns
3106///
3107/// - `Option<*mut c_void>` - Offscreen rendered color `MTLTexture` bound into UI compositor slot `3`, or `None` on setup failure.
3108#[cfg(any(target_os = "macos", target_os = "ios"))]
3109fn metal_encode_gpu_scene_pass(
3110    mtl_handles: [*mut c_void; 3],
3111    pipelines: [*mut c_void; 5],
3112    textures: (&mut usize, &mut usize, &mut usize, &mut (u32, u32)),
3113    buffers: (&mut [usize; 6], &mut u64),
3114    pbr_ctx: (&mut MetalPbrSceneResources, usize, *mut c_void),
3115    scene_pass: &DirectGpuScenePass,
3116) -> Option<*mut c_void> {
3117    let [cmd_buf, pass_cls, device]: [*mut c_void; 3] = mtl_handles;
3118    let (color_tex_h, depth_tex_h, wake_tex_h, tex_dims): (
3119        &mut usize,
3120        &mut usize,
3121        &mut usize,
3122        &mut (u32, u32),
3123    ) = textures;
3124    let (buf_arr, v3d_rev): (&mut [usize; 6], &mut u64) = buffers;
3125    let [v3d_buf_h, v3d_cap, i3d_buf_h, i3d_cap, boat_buf_h, boat_cap]: &mut [usize; 6] = buf_arr;
3126    let sel: &MetalSelectors = cached_metal_selectors();
3127    let (req_w, req_h, needs_depth): (u32, u32, bool) = match scene_pass {
3128        DirectGpuScenePass::OceanFluid(ocean) => (
3129            ocean.get_target_width().clamp(64, 16384),
3130            ocean.get_target_height().clamp(64, 16384),
3131            true,
3132        ),
3133        DirectGpuScenePass::World3d(world) => (
3134            world.get_target_width().clamp(64, 16384),
3135            world.get_target_height().clamp(64, 16384),
3136            true,
3137        ),
3138        DirectGpuScenePass::PbrScene(pbr) => (
3139            pbr.get_target_width().clamp(64, 16384),
3140            pbr.get_target_height().clamp(64, 16384),
3141            true,
3142        ),
3143    };
3144    if *color_tex_h == 0 || *tex_dims != (req_w, req_h) || (needs_depth && *depth_tex_h == 0) {
3145        release_native_gpu_object(*color_tex_h);
3146        release_native_gpu_object(*depth_tex_h);
3147        let unified_mem: bool = cfg!(target_arch = "aarch64");
3148        *color_tex_h =
3149            metal_create_offscreen_render_texture(device as usize, req_w, req_h, unified_mem);
3150        *depth_tex_h = if needs_depth {
3151            metal_create_depth_texture(device, req_w, req_h)
3152        } else {
3153            0
3154        };
3155        *tex_dims = (req_w, req_h);
3156    }
3157    let color_tex: *mut c_void = *color_tex_h as *mut c_void;
3158    if color_tex.is_null() {
3159        return None;
3160    }
3161    let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
3162    if pass_desc.is_null() {
3163        return None;
3164    }
3165    let color_atts: *mut c_void = mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
3166    let att0: *mut c_void = unsafe {
3167        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
3168            transmute(objc_msgSend as *const c_void);
3169        send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
3170    };
3171    if att0.is_null() {
3172        return None;
3173    }
3174    mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, color_tex);
3175    mtl_send_void_usize(
3176        att0,
3177        sel.set_load_action as *mut c_void,
3178        MTL_LOAD_ACTION_CLEAR,
3179    );
3180    unsafe {
3181        let send_clear: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlClearColor) =
3182            transmute(objc_msgSend as *const c_void);
3183        send_clear(
3184            att0,
3185            sel.set_clear_color as *mut c_void,
3186            MtlClearColor {
3187                red: 0.0,
3188                green: 0.0,
3189                blue: 0.0,
3190                alpha: 1.0,
3191            },
3192        );
3193    }
3194    mtl_send_void_usize(
3195        att0,
3196        sel.set_store_action as *mut c_void,
3197        MTL_STORE_ACTION_STORE,
3198    );
3199    if needs_depth {
3200        let depth_tex: *mut c_void = *depth_tex_h as *mut c_void;
3201        if depth_tex.is_null() {
3202            return None;
3203        }
3204        let depth_att: *mut c_void = mtl_send_ptr0(pass_desc, sel.depth_attachment as *mut c_void);
3205        if depth_att.is_null() {
3206            return None;
3207        }
3208        mtl_send_void_ptr1(depth_att, sel.set_texture as *mut c_void, depth_tex);
3209        mtl_send_void_usize(
3210            depth_att,
3211            sel.set_load_action as *mut c_void,
3212            MTL_LOAD_ACTION_CLEAR,
3213        );
3214        mtl_send_void_usize(
3215            depth_att,
3216            sel.set_store_action as *mut c_void,
3217            MTL_STORE_ACTION_DONT_CARE,
3218        );
3219        unsafe {
3220            let send_clear_d: unsafe extern "C" fn(*mut c_void, *mut c_void, f64) =
3221                transmute(objc_msgSend as *const c_void);
3222            send_clear_d(depth_att, sel.set_clear_depth as *mut c_void, 1.0);
3223        }
3224    }
3225    let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
3226    if encoder.is_null() {
3227        return None;
3228    }
3229    let viewport: MtlViewport = MtlViewport {
3230        origin_x: 0.0,
3231        origin_y: 0.0,
3232        width: f64::from(req_w),
3233        height: f64::from(req_h),
3234        znear: 0.0,
3235        zfar: 1.0,
3236    };
3237    unsafe {
3238        let send_vp: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlViewport) =
3239            transmute(objc_msgSend as *const c_void);
3240        send_vp(encoder, sel.set_viewport as *mut c_void, viewport);
3241    }
3242    match scene_pass {
3243        DirectGpuScenePass::OceanFluid(ocean) => {
3244            let ocean_pso: *mut c_void = pipelines[0];
3245            let boat_pso: *mut c_void = pipelines[1];
3246            if !ocean_pso.is_null() {
3247                let wake_w: u32 = ocean.get_wake_width().max(1);
3248                let wake_h: u32 = ocean.get_wake_height().max(1);
3249                if (*wake_tex_h == 0 || ocean.get_has_active_wake())
3250                    && ocean.get_wake_rgba8().len() >= (wake_w as usize) * (wake_h as usize) * 4
3251                {
3252                    let _: bool = metal_upload_texture_dirty_rect(
3253                        device as usize,
3254                        wake_tex_h,
3255                        GpuAtlasPixelFormat::Rgba8Unorm,
3256                        (wake_w, wake_h),
3257                        (0, 0, wake_w, wake_h),
3258                        ocean.get_wake_rgba8().as_slice(),
3259                        (wake_w as usize) * 4,
3260                    );
3261                }
3262                let sun: [f32; 3] = ocean.get_sun_dir();
3263                let boat_uv: [f32; 2] = ocean.get_boat_uv();
3264                let wf: f32 = req_w as f32;
3265                let hf: f32 = req_h as f32;
3266                let ocean_uniform: [f32; 16] = [
3267                    ocean.get_sim_time(),
3268                    ocean.get_agitation(),
3269                    ocean.get_horizon_v(),
3270                    ocean.get_aspect(),
3271                    ocean.get_roll_cos(),
3272                    ocean.get_roll_sin(),
3273                    boat_uv[0],
3274                    boat_uv[1],
3275                    sun[0],
3276                    sun[1],
3277                    sun[2],
3278                    if ocean.get_has_active_wake() && *wake_tex_h != 0 {
3279                        1.0
3280                    } else {
3281                        0.0
3282                    },
3283                    wf,
3284                    hf,
3285                    1.0 / wf.max(1.0),
3286                    1.0 / hf.max(1.0),
3287                ];
3288                mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, ocean_pso);
3289                unsafe {
3290                    let send_fbytes: unsafe extern "C" fn(
3291                        *mut c_void,
3292                        *mut c_void,
3293                        *const c_void,
3294                        usize,
3295                        usize,
3296                    ) = transmute(objc_msgSend as *const c_void);
3297                    let send_ftex: unsafe extern "C" fn(
3298                        *mut c_void,
3299                        *mut c_void,
3300                        *mut c_void,
3301                        usize,
3302                    ) = transmute(objc_msgSend as *const c_void);
3303                    let send_draw: unsafe extern "C" fn(
3304                        *mut c_void,
3305                        *mut c_void,
3306                        usize,
3307                        usize,
3308                        usize,
3309                        usize,
3310                        usize,
3311                    ) = transmute(objc_msgSend as *const c_void);
3312                    send_fbytes(
3313                        encoder,
3314                        sel.set_fragment_bytes as *mut c_void,
3315                        ocean_uniform.as_ptr().cast::<c_void>(),
3316                        size_of::<[f32; 16]>(),
3317                        0,
3318                    );
3319                    if *wake_tex_h != 0 {
3320                        send_ftex(
3321                            encoder,
3322                            sel.set_fragment_texture as *mut c_void,
3323                            *wake_tex_h as *mut c_void,
3324                            0,
3325                        );
3326                    }
3327                    send_draw(
3328                        encoder,
3329                        sel.draw_primitives_instanced as *mut c_void,
3330                        MTL_PRIMITIVE_TYPE_TRIANGLE,
3331                        0,
3332                        3,
3333                        1,
3334                        0,
3335                    );
3336                }
3337            }
3338            let boat_verts: &[GpuOceanBoatVertex] = ocean.get_boat_vertices().as_slice();
3339            let depth_state: *mut c_void = pipelines[4];
3340            if !boat_pso.is_null() && !boat_verts.is_empty() {
3341                let boat_bytes: &[u8] = unsafe {
3342                    from_raw_parts(boat_verts.as_ptr().cast::<u8>(), size_of_val(boat_verts))
3343                };
3344                let boat_buf: *mut c_void =
3345                    metal_ensure_and_upload_shared_buffer(device, boat_buf_h, boat_cap, boat_bytes);
3346                if !boat_buf.is_null() {
3347                    mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, boat_pso);
3348                    if !depth_state.is_null() {
3349                        mtl_send_void_ptr1(
3350                            encoder,
3351                            sel.set_depth_stencil_state as *mut c_void,
3352                            depth_state,
3353                        );
3354                    }
3355                    unsafe {
3356                        let send_vbuf: unsafe extern "C" fn(
3357                            *mut c_void,
3358                            *mut c_void,
3359                            *mut c_void,
3360                            usize,
3361                            usize,
3362                        ) = transmute(objc_msgSend as *const c_void);
3363                        let send_draw: unsafe extern "C" fn(
3364                            *mut c_void,
3365                            *mut c_void,
3366                            usize,
3367                            usize,
3368                            usize,
3369                            usize,
3370                            usize,
3371                        ) = transmute(objc_msgSend as *const c_void);
3372                        send_vbuf(
3373                            encoder,
3374                            sel.set_vertex_buffer as *mut c_void,
3375                            boat_buf,
3376                            0,
3377                            0,
3378                        );
3379                        send_draw(
3380                            encoder,
3381                            sel.draw_primitives_instanced as *mut c_void,
3382                            MTL_PRIMITIVE_TYPE_TRIANGLE,
3383                            0,
3384                            boat_verts.len(),
3385                            1,
3386                            0,
3387                        );
3388                    }
3389                }
3390            }
3391        }
3392        DirectGpuScenePass::World3d(world) => {
3393            let sky_pso: *mut c_void = pipelines[2];
3394            let mesh_pso: *mut c_void = pipelines[3];
3395            let depth_state: *mut c_void = pipelines[4];
3396            let mut uniform: [f32; 36] = [0.0; 36];
3397            uniform[0..16].copy_from_slice(&world.get_view_proj());
3398            uniform[16..20].copy_from_slice(&world.get_camera_pos());
3399            uniform[20..24].copy_from_slice(&world.get_sun_dir_fog());
3400            uniform[24..28].copy_from_slice(&world.get_sun_color_ambient());
3401            uniform[28..32].copy_from_slice(&world.get_sky_horizon_tod());
3402            uniform[32..36].copy_from_slice(&world.get_sky_zenith_aspect());
3403            if !sky_pso.is_null() {
3404                mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, sky_pso);
3405                unsafe {
3406                    let send_fbytes: unsafe extern "C" fn(
3407                        *mut c_void,
3408                        *mut c_void,
3409                        *const c_void,
3410                        usize,
3411                        usize,
3412                    ) = transmute(objc_msgSend as *const c_void);
3413                    let send_draw: unsafe extern "C" fn(
3414                        *mut c_void,
3415                        *mut c_void,
3416                        usize,
3417                        usize,
3418                        usize,
3419                        usize,
3420                        usize,
3421                    ) = transmute(objc_msgSend as *const c_void);
3422                    send_fbytes(
3423                        encoder,
3424                        sel.set_fragment_bytes as *mut c_void,
3425                        uniform.as_ptr().cast::<c_void>(),
3426                        size_of::<[f32; 36]>(),
3427                        0,
3428                    );
3429                    send_draw(
3430                        encoder,
3431                        sel.draw_primitives_instanced as *mut c_void,
3432                        MTL_PRIMITIVE_TYPE_TRIANGLE,
3433                        0,
3434                        3,
3435                        1,
3436                        0,
3437                    );
3438                }
3439            }
3440            let mesh_verts: &[GpuWorld3dVertex] = world.get_mesh_buffer().get_vertices().as_slice();
3441            let mesh_insts: &[GpuWorld3dInstance] = world.get_instances().as_slice();
3442            if !mesh_pso.is_null() && !mesh_verts.is_empty() && !mesh_insts.is_empty() {
3443                let mesh_rev: u64 = world.get_mesh_buffer().get_revision();
3444                let vbuf: *mut c_void = if *v3d_buf_h == 0 || *v3d_rev != mesh_rev {
3445                    let vert_bytes: &[u8] = unsafe {
3446                        from_raw_parts(mesh_verts.as_ptr().cast::<u8>(), size_of_val(mesh_verts))
3447                    };
3448                    let uploaded: *mut c_void = metal_ensure_and_upload_shared_buffer(
3449                        device, v3d_buf_h, v3d_cap, vert_bytes,
3450                    );
3451                    if !uploaded.is_null() {
3452                        *v3d_rev = mesh_rev;
3453                    }
3454                    uploaded
3455                } else {
3456                    *v3d_buf_h as *mut c_void
3457                };
3458                let inst_bytes: &[u8] = unsafe {
3459                    from_raw_parts(mesh_insts.as_ptr().cast::<u8>(), size_of_val(mesh_insts))
3460                };
3461                let ibuf: *mut c_void =
3462                    metal_ensure_and_upload_shared_buffer(device, i3d_buf_h, i3d_cap, inst_bytes);
3463                if !vbuf.is_null() && !ibuf.is_null() {
3464                    mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, mesh_pso);
3465                    if !depth_state.is_null() {
3466                        mtl_send_void_ptr1(
3467                            encoder,
3468                            sel.set_depth_stencil_state as *mut c_void,
3469                            depth_state,
3470                        );
3471                    }
3472                    unsafe {
3473                        let send_vbytes: unsafe extern "C" fn(
3474                            *mut c_void,
3475                            *mut c_void,
3476                            *const c_void,
3477                            usize,
3478                            usize,
3479                        ) = transmute(objc_msgSend as *const c_void);
3480                        let send_fbytes: unsafe extern "C" fn(
3481                            *mut c_void,
3482                            *mut c_void,
3483                            *const c_void,
3484                            usize,
3485                            usize,
3486                        ) = transmute(objc_msgSend as *const c_void);
3487                        let send_vbuf: unsafe extern "C" fn(
3488                            *mut c_void,
3489                            *mut c_void,
3490                            *mut c_void,
3491                            usize,
3492                            usize,
3493                        ) = transmute(objc_msgSend as *const c_void);
3494                        let send_draw: unsafe extern "C" fn(
3495                            *mut c_void,
3496                            *mut c_void,
3497                            usize,
3498                            usize,
3499                            usize,
3500                            usize,
3501                            usize,
3502                        ) = transmute(objc_msgSend as *const c_void);
3503                        send_vbytes(
3504                            encoder,
3505                            sel.set_vertex_bytes as *mut c_void,
3506                            uniform.as_ptr().cast::<c_void>(),
3507                            size_of::<[f32; 36]>(),
3508                            0,
3509                        );
3510                        send_fbytes(
3511                            encoder,
3512                            sel.set_fragment_bytes as *mut c_void,
3513                            uniform.as_ptr().cast::<c_void>(),
3514                            size_of::<[f32; 36]>(),
3515                            0,
3516                        );
3517                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, vbuf, 0, 1);
3518                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, ibuf, 0, 2);
3519                        for batch in world.get_draw_batches().iter() {
3520                            if batch.get_vertex_count() == 0 || batch.get_instance_count() == 0 {
3521                                continue;
3522                            }
3523                            send_draw(
3524                                encoder,
3525                                sel.draw_primitives_instanced as *mut c_void,
3526                                MTL_PRIMITIVE_TYPE_TRIANGLE,
3527                                batch.get_vertex_start() as usize,
3528                                batch.get_vertex_count() as usize,
3529                                batch.get_instance_count() as usize,
3530                                batch.get_instance_start() as usize,
3531                            );
3532                        }
3533                    }
3534                }
3535            }
3536        }
3537        DirectGpuScenePass::PbrScene(pbr) => {
3538            let (pbr_res, ring_slot, fallback_tex): (
3539                &mut MetalPbrSceneResources,
3540                usize,
3541                *mut c_void,
3542            ) = pbr_ctx;
3543            let ring_idx: usize = ring_slot % GPU_DRIVER_RING_SLOTS;
3544            metal_apply_pbr_mip_uploads(device, pbr_res, pbr.get_texture_uploads().as_slice());
3545            let sky_pso: *mut c_void = pbr_res.pipelines[0] as *mut c_void;
3546            let opaque_pso: *mut c_void = pbr_res.pipelines[1] as *mut c_void;
3547            let skinned_pso: *mut c_void = pbr_res.pipelines[2] as *mut c_void;
3548            let alpha_pso: *mut c_void = pbr_res.pipelines[3] as *mut c_void;
3549            let depth_write_state: *mut c_void = pipelines[4];
3550            let depth_ro_state: *mut c_void = pbr_res.pipelines[4] as *mut c_void;
3551            let base_uniform: PbrSceneUniformBlock =
3552                build_pbr_scene_uniform_block(pbr, 0, 0, [0, 0, 0, 0]);
3553            if !sky_pso.is_null() {
3554                mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, sky_pso);
3555                if !depth_ro_state.is_null() {
3556                    mtl_send_void_ptr1(
3557                        encoder,
3558                        sel.set_depth_stencil_state as *mut c_void,
3559                        depth_ro_state,
3560                    );
3561                }
3562                unsafe {
3563                    let send_fbytes: unsafe extern "C" fn(
3564                        *mut c_void,
3565                        *mut c_void,
3566                        *const c_void,
3567                        usize,
3568                        usize,
3569                    ) = transmute(objc_msgSend as *const c_void);
3570                    let send_draw: unsafe extern "C" fn(
3571                        *mut c_void,
3572                        *mut c_void,
3573                        usize,
3574                        usize,
3575                        usize,
3576                        usize,
3577                        usize,
3578                    ) = transmute(objc_msgSend as *const c_void);
3579                    send_fbytes(
3580                        encoder,
3581                        sel.set_fragment_bytes as *mut c_void,
3582                        (&base_uniform as *const PbrSceneUniformBlock).cast::<c_void>(),
3583                        size_of::<PbrSceneUniformBlock>(),
3584                        0,
3585                    );
3586                    send_draw(
3587                        encoder,
3588                        sel.draw_primitives_instanced as *mut c_void,
3589                        MTL_PRIMITIVE_TYPE_TRIANGLE,
3590                        0,
3591                        3,
3592                        1,
3593                        0,
3594                    );
3595                }
3596            }
3597            let mesh_buf: &GpuPbrMeshBuffer = pbr.get_mesh_buffer();
3598            let q_verts: &[QuantizedVertex3D] = mesh_buf.get_vertices().as_slice();
3599            let q_indices: &[u32] = mesh_buf.get_indices().as_slice();
3600            let insts: &[GpuPbrInstance3D] = pbr.get_instances().as_slice();
3601            let batches: &[GpuPbrDrawBatch] = pbr.get_draw_batches().as_slice();
3602            if !opaque_pso.is_null()
3603                && !q_verts.is_empty()
3604                && !q_indices.is_empty()
3605                && !insts.is_empty()
3606                && !batches.is_empty()
3607            {
3608                let rev: u64 = mesh_buf.get_revision();
3609                if pbr_res.vert_buf == 0 || pbr_res.idx_buf == 0 || pbr_res.mesh_rev != rev {
3610                    let vbytes: &[u8] = unsafe {
3611                        from_raw_parts(q_verts.as_ptr().cast::<u8>(), size_of_val(q_verts))
3612                    };
3613                    let ibytes: &[u8] = unsafe {
3614                        from_raw_parts(q_indices.as_ptr().cast::<u8>(), size_of_val(q_indices))
3615                    };
3616                    let vb_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3617                        device,
3618                        &mut pbr_res.vert_buf,
3619                        &mut pbr_res.vert_cap,
3620                        vbytes,
3621                    );
3622                    let ib_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3623                        device,
3624                        &mut pbr_res.idx_buf,
3625                        &mut pbr_res.idx_cap,
3626                        ibytes,
3627                    );
3628                    let skin_slice: &[QuantizedSkinVertex3D] =
3629                        mesh_buf.get_skin_vertices().as_slice();
3630                    if !skin_slice.is_empty() {
3631                        let sbytes: &[u8] = unsafe {
3632                            from_raw_parts(
3633                                skin_slice.as_ptr().cast::<u8>(),
3634                                size_of_val(skin_slice),
3635                            )
3636                        };
3637                        let _: *mut c_void = metal_ensure_and_upload_shared_buffer(
3638                            device,
3639                            &mut pbr_res.skin_buf,
3640                            &mut pbr_res.skin_cap,
3641                            sbytes,
3642                        );
3643                    }
3644                    let morph_slice: &[[f32; 4]] = mesh_buf.get_morph_deltas().as_slice();
3645                    if !morph_slice.is_empty() {
3646                        let mbytes: &[u8] = unsafe {
3647                            from_raw_parts(
3648                                morph_slice.as_ptr().cast::<u8>(),
3649                                size_of_val(morph_slice),
3650                            )
3651                        };
3652                        let _: *mut c_void = metal_ensure_and_upload_shared_buffer(
3653                            device,
3654                            &mut pbr_res.morph_delta_buf,
3655                            &mut pbr_res.morph_delta_cap,
3656                            mbytes,
3657                        );
3658                    }
3659                    if !vb_ptr.is_null() && !ib_ptr.is_null() {
3660                        pbr_res.mesh_rev = rev;
3661                    }
3662                }
3663                let inst_bytes: &[u8] =
3664                    unsafe { from_raw_parts(insts.as_ptr().cast::<u8>(), size_of_val(insts)) };
3665                let inst_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3666                    device,
3667                    &mut pbr_res.inst_bufs[ring_idx],
3668                    &mut pbr_res.inst_caps[ring_idx],
3669                    inst_bytes,
3670                );
3671                let default_mat: [GpuMaterialData3D; 1] = [GpuMaterialData3D::default()];
3672                let mats_slice: &[GpuMaterialData3D] = if pbr.get_materials().is_empty() {
3673                    &default_mat
3674                } else {
3675                    pbr.get_materials().as_slice()
3676                };
3677                let mat_bytes: &[u8] = unsafe {
3678                    from_raw_parts(mats_slice.as_ptr().cast::<u8>(), size_of_val(mats_slice))
3679                };
3680                let mat_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3681                    device,
3682                    &mut pbr_res.mat_bufs[ring_idx],
3683                    &mut pbr_res.mat_caps[ring_idx],
3684                    mat_bytes,
3685                );
3686                let default_bone: [[f32; 16]; 1] = [Mat4::identity().get_elements()];
3687                let bones_slice: &[[f32; 16]] = if pbr.get_bone_matrices().is_empty() {
3688                    &default_bone
3689                } else {
3690                    pbr.get_bone_matrices().as_slice()
3691                };
3692                let bone_bytes: &[u8] = unsafe {
3693                    from_raw_parts(bones_slice.as_ptr().cast::<u8>(), size_of_val(bones_slice))
3694                };
3695                let bone_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3696                    device,
3697                    &mut pbr_res.bone_bufs[ring_idx],
3698                    &mut pbr_res.bone_caps[ring_idx],
3699                    bone_bytes,
3700                );
3701                let default_mw: [f32; 4] = [0.0; 4];
3702                let mw_slice: &[f32] = if pbr.get_morph_weights().is_empty() {
3703                    &default_mw
3704                } else {
3705                    pbr.get_morph_weights().as_slice()
3706                };
3707                let mw_bytes: &[u8] = unsafe {
3708                    from_raw_parts(mw_slice.as_ptr().cast::<u8>(), size_of_val(mw_slice))
3709                };
3710                let mw_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3711                    device,
3712                    &mut pbr_res.morph_w_bufs[ring_idx],
3713                    &mut pbr_res.morph_w_caps[ring_idx],
3714                    mw_bytes,
3715                );
3716                let default_light: [GpuPackedLocalLight; 1] = [GpuPackedLocalLight::default()];
3717                let lights_slice: &[GpuPackedLocalLight] = if pbr.get_local_lights().is_empty() {
3718                    &default_light
3719                } else {
3720                    pbr.get_local_lights().as_slice()
3721                };
3722                let light_bytes: &[u8] = unsafe {
3723                    from_raw_parts(
3724                        lights_slice.as_ptr().cast::<u8>(),
3725                        size_of_val(lights_slice),
3726                    )
3727                };
3728                let light_ptr: *mut c_void = metal_ensure_and_upload_shared_buffer(
3729                    device,
3730                    &mut pbr_res.light_bufs[ring_idx],
3731                    &mut pbr_res.light_caps[ring_idx],
3732                    light_bytes,
3733                );
3734                let vbuf: *mut c_void = pbr_res.vert_buf as *mut c_void;
3735                let ibuf: *mut c_void = pbr_res.idx_buf as *mut c_void;
3736                let sbuf: *mut c_void = if pbr_res.skin_buf != 0 {
3737                    pbr_res.skin_buf as *mut c_void
3738                } else {
3739                    inst_ptr
3740                };
3741                let mdbuf: *mut c_void = if pbr_res.morph_delta_buf != 0 {
3742                    pbr_res.morph_delta_buf as *mut c_void
3743                } else {
3744                    bone_ptr
3745                };
3746                if !vbuf.is_null()
3747                    && !ibuf.is_null()
3748                    && !inst_ptr.is_null()
3749                    && !mat_ptr.is_null()
3750                    && !bone_ptr.is_null()
3751                    && !mw_ptr.is_null()
3752                    && !light_ptr.is_null()
3753                {
3754                    let morph_stride: u32 = if !mesh_buf.get_morph_deltas().is_empty() {
3755                        q_verts.len() as u32
3756                    } else {
3757                        0
3758                    };
3759                    let mut bound_pso: *mut c_void = null_mut();
3760                    let mut bound_depth: *mut c_void = null_mut();
3761                    unsafe {
3762                        let send_vbytes: unsafe extern "C" fn(
3763                            *mut c_void,
3764                            *mut c_void,
3765                            *const c_void,
3766                            usize,
3767                            usize,
3768                        ) = transmute(objc_msgSend as *const c_void);
3769                        let send_fbytes: unsafe extern "C" fn(
3770                            *mut c_void,
3771                            *mut c_void,
3772                            *const c_void,
3773                            usize,
3774                            usize,
3775                        ) = transmute(objc_msgSend as *const c_void);
3776                        let send_vbuf: unsafe extern "C" fn(
3777                            *mut c_void,
3778                            *mut c_void,
3779                            *mut c_void,
3780                            usize,
3781                            usize,
3782                        ) = transmute(objc_msgSend as *const c_void);
3783                        let send_fbuf: unsafe extern "C" fn(
3784                            *mut c_void,
3785                            *mut c_void,
3786                            *mut c_void,
3787                            usize,
3788                            usize,
3789                        ) = transmute(objc_msgSend as *const c_void);
3790                        let send_ftex: unsafe extern "C" fn(
3791                            *mut c_void,
3792                            *mut c_void,
3793                            *mut c_void,
3794                            usize,
3795                        ) = transmute(objc_msgSend as *const c_void);
3796                        let send_draw_idx: unsafe extern "C" fn(
3797                            *mut c_void,
3798                            *mut c_void,
3799                            usize,
3800                            usize,
3801                            usize,
3802                            *mut c_void,
3803                            usize,
3804                            usize,
3805                            isize,
3806                            usize,
3807                        ) = transmute(objc_msgSend as *const c_void);
3808                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, vbuf, 0, 1);
3809                        send_vbuf(
3810                            encoder,
3811                            sel.set_vertex_buffer as *mut c_void,
3812                            inst_ptr,
3813                            0,
3814                            2,
3815                        );
3816                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, sbuf, 0, 3);
3817                        send_vbuf(
3818                            encoder,
3819                            sel.set_vertex_buffer as *mut c_void,
3820                            bone_ptr,
3821                            0,
3822                            4,
3823                        );
3824                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, mdbuf, 0, 5);
3825                        send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, mw_ptr, 0, 6);
3826                        send_fbuf(
3827                            encoder,
3828                            sel.set_fragment_buffer as *mut c_void,
3829                            mat_ptr,
3830                            0,
3831                            1,
3832                        );
3833                        send_fbuf(
3834                            encoder,
3835                            sel.set_fragment_buffer as *mut c_void,
3836                            light_ptr,
3837                            0,
3838                            2,
3839                        );
3840                        for batch in batches.iter() {
3841                            if batch.get_index_count() == 0 || batch.get_instance_count() == 0 {
3842                                continue;
3843                            }
3844                            let target_pso: *mut c_void = match batch.get_pso_variant() {
3845                                PBR_PSO_VARIANT_SKINNED if !skinned_pso.is_null() => skinned_pso,
3846                                PBR_PSO_VARIANT_ALPHA_BLEND if !alpha_pso.is_null() => alpha_pso,
3847                                _ => opaque_pso,
3848                            };
3849                            if target_pso != bound_pso {
3850                                mtl_send_void_ptr1(
3851                                    encoder,
3852                                    sel.set_pipeline_state as *mut c_void,
3853                                    target_pso,
3854                                );
3855                                bound_pso = target_pso;
3856                            }
3857                            let target_depth: *mut c_void = if batch.get_pso_variant()
3858                                == PBR_PSO_VARIANT_ALPHA_BLEND
3859                                && !depth_ro_state.is_null()
3860                            {
3861                                depth_ro_state
3862                            } else {
3863                                depth_write_state
3864                            };
3865                            if !target_depth.is_null() && target_depth != bound_depth {
3866                                mtl_send_void_ptr1(
3867                                    encoder,
3868                                    sel.set_depth_stencil_state as *mut c_void,
3869                                    target_depth,
3870                                );
3871                                bound_depth = target_depth;
3872                            }
3873                            let mat_idx: u32 = batch
3874                                .get_material_index()
3875                                .min(mats_slice.len().saturating_sub(1) as u32);
3876                            let mat_ref: &GpuMaterialData3D = &mats_slice[mat_idx as usize];
3877                            let tex_slots: [u32; 5] = [
3878                                mat_ref.get_tex_indices_a()[0],
3879                                mat_ref.get_tex_indices_a()[1],
3880                                mat_ref.get_tex_indices_a()[2],
3881                                mat_ref.get_tex_indices_a()[3],
3882                                mat_ref.get_tex_indices_b()[0],
3883                            ];
3884                            let mut tex_mask: u32 = 0;
3885                            let mut mip_tier: u32 = 3;
3886                            for (unit, &slot_id) in tex_slots.iter().enumerate() {
3887                                let bound_tex: *mut c_void = if slot_id != GPU_MATERIAL_NO_TEXTURE
3888                                    && let Some(res_tex) = pbr_res.textures.get(&slot_id)
3889                                    && res_tex.tex_handle != 0
3890                                {
3891                                    tex_mask |= 1u32 << unit;
3892                                    if unit == 0 {
3893                                        mip_tier = if res_tex.min_lod_clamp == 0 {
3894                                            0
3895                                        } else if res_tex.min_lod_clamp <= 2 {
3896                                            1
3897                                        } else {
3898                                            2
3899                                        };
3900                                    }
3901                                    if res_tex.view_handle != 0 {
3902                                        res_tex.view_handle as *mut c_void
3903                                    } else {
3904                                        res_tex.tex_handle as *mut c_void
3905                                    }
3906                                } else {
3907                                    fallback_tex
3908                                };
3909                                send_ftex(
3910                                    encoder,
3911                                    sel.set_fragment_texture as *mut c_void,
3912                                    bound_tex,
3913                                    unit,
3914                                );
3915                            }
3916                            let lod_mip_mask: u32 = u32::from(batch.get_lod_level() & 3)
3917                                | ((mip_tier & 255) << 8)
3918                                | ((tex_mask & 31) << 16);
3919                            let uniform: PbrSceneUniformBlock = build_pbr_scene_uniform_block(
3920                                pbr,
3921                                lod_mip_mask,
3922                                mat_idx,
3923                                [
3924                                    batch.get_base_vertex(),
3925                                    batch.get_instance_start(),
3926                                    morph_stride,
3927                                    batch.get_index_start(),
3928                                ],
3929                            );
3930                            send_vbytes(
3931                                encoder,
3932                                sel.set_vertex_bytes as *mut c_void,
3933                                (&uniform as *const PbrSceneUniformBlock).cast::<c_void>(),
3934                                size_of::<PbrSceneUniformBlock>(),
3935                                0,
3936                            );
3937                            send_fbytes(
3938                                encoder,
3939                                sel.set_fragment_bytes as *mut c_void,
3940                                (&uniform as *const PbrSceneUniformBlock).cast::<c_void>(),
3941                                size_of::<PbrSceneUniformBlock>(),
3942                                0,
3943                            );
3944                            let idx_byte_offset: usize =
3945                                (batch.get_index_start() as usize).saturating_mul(size_of::<u32>());
3946                            send_draw_idx(
3947                                encoder,
3948                                sel.draw_indexed_instanced as *mut c_void,
3949                                MTL_PRIMITIVE_TYPE_TRIANGLE,
3950                                batch.get_index_count() as usize,
3951                                MTL_INDEX_TYPE_UINT32,
3952                                ibuf,
3953                                idx_byte_offset,
3954                                batch.get_instance_count() as usize,
3955                                batch.get_base_vertex() as isize,
3956                                batch.get_instance_start() as usize,
3957                            );
3958                        }
3959                    }
3960                }
3961            }
3962        }
3963    }
3964    mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
3965    Some(color_tex)
3966}
3967
3968/// Begins a Metal UI uber-shader `MTLRenderCommandEncoder` targeting `target_tex` with viewport, vertex buffer, and 4 texture slots bound.
3969///
3970/// # Arguments
3971///
3972/// - `*mut c_void` - Active `id<MTLCommandBuffer>`.
3973/// - `*mut c_void` - `MTLRenderPassDescriptor` class pointer.
3974/// - `*mut c_void` - Destination color attachment `id<MTLTexture>`.
3975/// - `(usize, MtlClearColor)` - Tuple of `(load_action, clear_color)`.
3976/// - `(usize, usize)` - Viewport dimensions `(draw_w, draw_h)`.
3977/// - `(*mut c_void, *mut c_void)` - Tuple of `(pipeline_state, vertex_instance_buffer)`.
3978/// - `[*mut c_void; 4]` - Fragment texture bindings `[glyph_r8, glyph_rgba8, image_atlas, external_or_blur]`.
3979///
3980/// # Returns
3981///
3982/// - `*mut c_void` - Active `id<MTLRenderCommandEncoder>` pointer, or null on failure.
3983#[cfg(any(target_os = "macos", target_os = "ios"))]
3984fn metal_begin_ui_render_encoder(
3985    cmd_buf: *mut c_void,
3986    pass_cls: *mut c_void,
3987    target_tex: *mut c_void,
3988    load_spec: (usize, MtlClearColor),
3989    draw_dims: (usize, usize),
3990    pipe_buf: (*mut c_void, *mut c_void),
3991    textures: [*mut c_void; 4],
3992) -> *mut c_void {
3993    let sel: &MetalSelectors = cached_metal_selectors();
3994    let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
3995    if pass_desc.is_null() {
3996        return null_mut();
3997    }
3998    let color_atts: *mut c_void = mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
3999    let att0: *mut c_void = unsafe {
4000        let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
4001            transmute(objc_msgSend as *const c_void);
4002        send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
4003    };
4004    if att0.is_null() {
4005        return null_mut();
4006    }
4007    mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, target_tex);
4008    mtl_send_void_usize(att0, sel.set_load_action as *mut c_void, load_spec.0);
4009    mtl_send_void_usize(
4010        att0,
4011        sel.set_store_action as *mut c_void,
4012        MTL_STORE_ACTION_STORE,
4013    );
4014    if load_spec.0 == MTL_LOAD_ACTION_CLEAR {
4015        unsafe {
4016            let send_clear: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlClearColor) =
4017                transmute(objc_msgSend as *const c_void);
4018            send_clear(att0, sel.set_clear_color as *mut c_void, load_spec.1);
4019        }
4020    }
4021    let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
4022    if encoder.is_null() {
4023        return null_mut();
4024    }
4025    mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, pipe_buf.0);
4026    unsafe {
4027        let send_viewport: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlViewport) =
4028            transmute(objc_msgSend as *const c_void);
4029        send_viewport(
4030            encoder,
4031            sel.set_viewport as *mut c_void,
4032            MtlViewport {
4033                origin_x: 0.0,
4034                origin_y: 0.0,
4035                width: draw_dims.0 as f64,
4036                height: draw_dims.1 as f64,
4037                znear: 0.0,
4038                zfar: 1.0,
4039            },
4040        );
4041        if !pipe_buf.1.is_null() {
4042            let send_vbuf: unsafe extern "C" fn(
4043                *mut c_void,
4044                *mut c_void,
4045                *mut c_void,
4046                usize,
4047                usize,
4048            ) = transmute(objc_msgSend as *const c_void);
4049            send_vbuf(
4050                encoder,
4051                sel.set_vertex_buffer as *mut c_void,
4052                pipe_buf.1,
4053                0,
4054                0,
4055            );
4056        }
4057        let send_ftex: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, usize) =
4058            transmute(objc_msgSend as *const c_void);
4059        for (slot_idx, tex_ptr) in textures.iter().enumerate() {
4060            if !tex_ptr.is_null() {
4061                send_ftex(
4062                    encoder,
4063                    sel.set_fragment_texture as *mut c_void,
4064                    *tex_ptr,
4065                    slot_idx,
4066                );
4067            }
4068        }
4069    }
4070    encoder
4071}
4072
4073/// Encodes one instanced `GpuBatch` draw call onto an active Metal UI `MTLRenderCommandEncoder`.
4074///
4075/// # Arguments
4076///
4077/// - `*mut c_void` - Active `id<MTLRenderCommandEncoder>`.
4078/// - `(usize, usize)` - Active render target dimensions `(draw_w, draw_h)`.
4079/// - `&GpuBatch` - Source GPU draw batch.
4080/// - `usize` - Instance count inside the bound vertex buffer.
4081/// - `usize` - Starting base instance index inside the bound vertex buffer.
4082#[cfg(any(target_os = "macos", target_os = "ios"))]
4083fn metal_encode_ui_batch_draw(
4084    encoder: *mut c_void,
4085    draw_dims: (usize, usize),
4086    batch: &GpuBatch,
4087    count: usize,
4088    base_instance: usize,
4089) {
4090    let sel: &MetalSelectors = cached_metal_selectors();
4091    let (draw_w, draw_h): (usize, usize) = draw_dims;
4092    let uniform: GpuLayerUniform =
4093        GpuLayerUniform::new(draw_w as f32, draw_h as f32, batch.get_scroll_offset());
4094    let rect_bounds: Rect = batch.get_scissor();
4095    if rect_bounds.get_width() <= 0.0 || rect_bounds.get_height() <= 0.0 {
4096        return;
4097    }
4098    let sx0: usize = rect_bounds.get_x().max(0.0).floor() as usize;
4099    let sy0: usize = rect_bounds.get_y().max(0.0).floor() as usize;
4100    let sx1: usize = (rect_bounds.right().max(0.0).ceil() as usize).min(draw_w);
4101    let sy1: usize = (rect_bounds.bottom().max(0.0).ceil() as usize).min(draw_h);
4102    if sx0 >= sx1 || sy0 >= sy1 {
4103        return;
4104    }
4105    let sx: usize = sx0;
4106    let sy: usize = sy0;
4107    let sw: usize = sx1 - sx0;
4108    let sh: usize = sy1 - sy0;
4109    unsafe {
4110        let send_vbytes: unsafe extern "C" fn(
4111            *mut c_void,
4112            *mut c_void,
4113            *const c_void,
4114            usize,
4115            usize,
4116        ) = transmute(objc_msgSend as *const c_void);
4117        let send_scissor: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlScissorRect) =
4118            transmute(objc_msgSend as *const c_void);
4119        let send_draw: unsafe extern "C" fn(
4120            *mut c_void,
4121            *mut c_void,
4122            usize,
4123            usize,
4124            usize,
4125            usize,
4126            usize,
4127        ) = transmute(objc_msgSend as *const c_void);
4128        send_vbytes(
4129            encoder,
4130            sel.set_vertex_bytes as *mut c_void,
4131            (&uniform as *const GpuLayerUniform).cast::<c_void>(),
4132            size_of::<GpuLayerUniform>(),
4133            1,
4134        );
4135        send_scissor(
4136            encoder,
4137            sel.set_scissor_rect as *mut c_void,
4138            MtlScissorRect {
4139                x: sx,
4140                y: sy,
4141                width: sw,
4142                height: sh,
4143            },
4144        );
4145        send_draw(
4146            encoder,
4147            sel.draw_primitives_instanced as *mut c_void,
4148            MTL_PRIMITIVE_TYPE_TRIANGLE,
4149            0,
4150            6,
4151            count,
4152            base_instance,
4153        );
4154    }
4155}
4156
4157/// Uploads `GpuPrimitiveInstance` buffers to Metal GPU memory and commits a command buffer.
4158///
4159/// # Arguments
4160///
4161/// - `usize` - Retained `id<MTLDevice>` pointer.
4162/// - `usize` - Retained `id<MTLCommandQueue>` pointer.
4163/// - `&[GpuBatch]` - Ordered GPU batches to upload.
4164///
4165/// # Returns
4166///
4167/// - `usize` - Total instances uploaded into Metal buffers.
4168#[cfg(any(target_os = "macos", target_os = "ios"))]
4169fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
4170    let total_instances: usize = batches
4171        .iter()
4172        .map(|blue_val: &GpuBatch| {
4173            blue_val
4174                .get_primitives()
4175                .len()
4176                .max(blue_val.get_instances().len())
4177        })
4178        .sum();
4179    if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
4180        return total_instances;
4181    }
4182    let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
4183    let device: *mut c_void = device_handle as *mut c_void;
4184    let queue: *mut c_void = queue_handle as *mut c_void;
4185    let sel: &MetalSelectors = cached_metal_selectors();
4186    let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
4187    let sel_rel: *mut c_void = sel.release as *mut c_void;
4188    unsafe {
4189        let send_buf: unsafe extern "C" fn(
4190            *mut c_void,
4191            *mut c_void,
4192            *const c_void,
4193            usize,
4194            usize,
4195        ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
4196        for batch in batches.iter() {
4197            let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
4198            if !prims.is_empty() {
4199                let byte_len: usize = size_of_val(prims);
4200                let mtl_buf: *mut c_void = send_buf(
4201                    device,
4202                    sel_buf,
4203                    prims.as_ptr().cast::<c_void>(),
4204                    byte_len,
4205                    0,
4206                );
4207                if !mtl_buf.is_null() {
4208                    mtl_send_void0(mtl_buf, sel_rel);
4209                }
4210            } else {
4211                let instances: &[GpuQuadInstance] = batch.get_instances();
4212                if instances.is_empty() {
4213                    continue;
4214                }
4215                let byte_len: usize = size_of_val(instances);
4216                let mtl_buf: *mut c_void = send_buf(
4217                    device,
4218                    sel_buf,
4219                    instances.as_ptr().cast::<c_void>(),
4220                    byte_len,
4221                    0,
4222                );
4223                if !mtl_buf.is_null() {
4224                    mtl_send_void0(mtl_buf, sel_rel);
4225                }
4226            }
4227        }
4228        let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
4229        if !cmd_buf.is_null() {
4230            mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
4231        }
4232        objc_autoreleasePoolPop(pool);
4233    }
4234    total_instances
4235}
4236
4237/// Releases retained Apple Metal Objective-C objects cleanly on drop.
4238///
4239/// # Arguments
4240///
4241/// - `usize` - `id<MTLDevice>` pointer.
4242/// - `usize` - `id<MTLCommandQueue>` pointer.
4243/// - `usize` - `id<MTLLibrary>` pointer.
4244#[cfg(any(target_os = "macos", target_os = "ios"))]
4245fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
4246    let sel_rel: *mut c_void = cached_metal_selectors().release as *mut c_void;
4247    if library_handle != 0 {
4248        mtl_send_void0(library_handle as *mut c_void, sel_rel);
4249    }
4250    if queue_handle != 0 {
4251        mtl_send_void0(queue_handle as *mut c_void, sel_rel);
4252    }
4253    if device_handle != 0 {
4254        mtl_send_void0(device_handle as *mut c_void, sel_rel);
4255    }
4256}
4257
4258#[cfg(target_os = "windows")]
4259#[link(name = "kernel32")]
4260unsafe extern "system" {
4261    /// Dynamically loads a Windows DLL by ANSI path.
4262    ///
4263    /// # Arguments
4264    ///
4265    /// - `*const u8` - Null-terminated ANSI DLL path.
4266    ///
4267    /// # Returns
4268    ///
4269    /// - `*mut c_void` - Loaded `HMODULE` handle or null.
4270    fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
4271    /// Looks up an exported procedure address from a loaded Windows DLL.
4272    ///
4273    /// # Arguments
4274    ///
4275    /// - `*mut c_void` - Loaded `HMODULE` handle.
4276    /// - `*const u8` - Null-terminated ASCII export name.
4277    ///
4278    /// # Returns
4279    ///
4280    /// - `*mut c_void` - Exported function address or null.
4281    fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
4282}
4283
4284/// Probes Windows Direct3D 12 and `d3dcompiler_47.dll` once per process (caching handles in `OnceLock`).
4285///
4286/// # Arguments
4287///
4288/// - `GraphicsBackend` - Requested graphics backend.
4289///
4290/// # Returns
4291///
4292/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Direct3D 12 availability metadata.
4293#[cfg(target_os = "windows")]
4294fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
4295    let cached: &WindowsD3d12ProbeCache = WINDOWS_D3D12_CACHE.get_or_init(|| unsafe {
4296        let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
4297        let has_d3d12: bool = if !d3d12_mod.is_null() {
4298            !GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr()).is_null()
4299        } else {
4300            false
4301        };
4302        let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
4303        let has_compiler: bool = if !compiler_mod.is_null() {
4304            !GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr()).is_null()
4305        } else {
4306            false
4307        };
4308        WindowsD3d12ProbeCache {
4309            has_d3d12,
4310            has_compiler,
4311        }
4312    });
4313    let has_runtime: bool = cached.has_d3d12 && cached.has_compiler;
4314    let label: &str = if cached.has_d3d12 {
4315        GPU_DEVICE_D3D12
4316    } else {
4317        GPU_DEVICE_FALLBACK
4318    };
4319    (
4320        GpuAdapterInfo::new(backend, label.to_string(), has_runtime, false),
4321        0,
4322        0,
4323        0,
4324    )
4325}
4326
4327#[cfg(any(target_os = "linux", target_os = "android"))]
4328unsafe extern "C" {
4329    /// Dynamically opens a shared library object by name.
4330    ///
4331    /// # Arguments
4332    ///
4333    /// - `*const c_char` - Null-terminated library name.
4334    /// - `i32` - POSIX `RTLD_*` resolution flags.
4335    ///
4336    /// # Returns
4337    ///
4338    /// - `*mut c_void` - Shared library handle or null.
4339    fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
4340    /// Resolves a symbol address from an open shared library handle.
4341    ///
4342    /// # Arguments
4343    ///
4344    /// - `*mut c_void` - Open shared library handle.
4345    /// - `*const c_char` - Null-terminated symbol name.
4346    ///
4347    /// # Returns
4348    ///
4349    /// - `*mut c_void` - Resolved symbol pointer or null.
4350    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
4351}
4352
4353/// Probes Linux or Android Vulkan loader once per process and retains the library handle in `OnceLock`.
4354///
4355/// # Arguments
4356///
4357/// - `GraphicsBackend` - Requested graphics backend.
4358///
4359/// # Returns
4360///
4361/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Vulkan runtime status.
4362#[cfg(any(target_os = "linux", target_os = "android"))]
4363fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
4364    let cached: &VulkanProbeCache = VULKAN_PROBE_CACHE.get_or_init(|| {
4365        let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
4366            return VulkanProbeCache {
4367                available: false,
4368                lib_handle: 0,
4369            };
4370        };
4371        let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
4372            return VulkanProbeCache {
4373                available: false,
4374                lib_handle: 0,
4375            };
4376        };
4377        let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
4378            return VulkanProbeCache {
4379                available: false,
4380                lib_handle: 0,
4381            };
4382        };
4383        unsafe {
4384            let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
4385            if handle.is_null() {
4386                VulkanProbeCache {
4387                    available: false,
4388                    lib_handle: 0,
4389                }
4390            } else {
4391                let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
4392                let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
4393                VulkanProbeCache {
4394                    available: !p1.is_null() && !p2.is_null(),
4395                    lib_handle: handle as usize,
4396                }
4397            }
4398        }
4399    });
4400    let name: &str = if cached.available {
4401        GPU_DEVICE_VULKAN
4402    } else {
4403        GPU_DEVICE_FALLBACK
4404    };
4405    (
4406        GpuAdapterInfo::new(backend, name.to_string(), cached.available, false),
4407        cached.lib_handle,
4408        0,
4409        0,
4410    )
4411}
4412
4413/// Compiles and links the WebGL 2 64-byte instanced uber-shader program on `wasm32`.
4414///
4415/// # Arguments
4416///
4417/// - `&WebGl2RenderingContext` - Active WebGL 2 canvas context.
4418///
4419/// # Returns
4420///
4421/// - `Option<WebGlProgram>` - Linked shader program when compilation succeeds.
4422#[cfg(target_arch = "wasm32")]
4423pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
4424    let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
4425    gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
4426    gl.compile_shader(&vs);
4427    let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
4428    gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
4429    gl.compile_shader(&fs);
4430    let program: WebGlProgram = gl.create_program()?;
4431    gl.attach_shader(&program, &vs);
4432    gl.attach_shader(&program, &fs);
4433    gl.link_program(&program);
4434    Some(program)
4435}
4436
4437/// Returns the canonical 5-attribute GLES 3.0 instanced vertex layout matching `GLSL_ES3_UI_VERTEX_SHADER` and 64-byte `GpuPrimitiveInstance`.
4438///
4439/// # Returns
4440///
4441/// - `[Gles3InstanceAttribSpec; 5]` - Ordered instanced vertex attribute bindings (`locations 1..=5`, stride `64`).
4442#[must_use]
4443pub const fn gles3_ui_instance_attribs() -> [Gles3InstanceAttribSpec; 5] {
4444    let stride: i32 = GPU_PRIMITIVE_INSTANCE_BYTES as i32;
4445    [
4446        Gles3InstanceAttribSpec {
4447            location: 1,
4448            components: 4,
4449            is_integer: false,
4450            byte_offset: 0,
4451            stride,
4452        },
4453        Gles3InstanceAttribSpec {
4454            location: 2,
4455            components: 4,
4456            is_integer: false,
4457            byte_offset: 16,
4458            stride,
4459        },
4460        Gles3InstanceAttribSpec {
4461            location: 3,
4462            components: 2,
4463            is_integer: true,
4464            byte_offset: 32,
4465            stride,
4466        },
4467        Gles3InstanceAttribSpec {
4468            location: 4,
4469            components: 4,
4470            is_integer: true,
4471            byte_offset: 40,
4472            stride,
4473        },
4474        Gles3InstanceAttribSpec {
4475            location: 5,
4476            components: 2,
4477            is_integer: true,
4478            byte_offset: 56,
4479            stride,
4480        },
4481    ]
4482}
4483
4484/// Converts a top-left physical scissor rectangle into an OpenGL ES bottom-left scissor tuple `(x, y, width, height)`.
4485///
4486/// # Arguments
4487///
4488/// - `u32` - Surface height in physical pixels.
4489/// - `u32` - Top-left scissor X coordinate.
4490/// - `u32` - Top-left scissor Y coordinate.
4491/// - `u32` - Scissor width in physical pixels.
4492/// - `u32` - Scissor height in physical pixels.
4493///
4494/// # Returns
4495///
4496/// - `[i32; 4]` - OpenGL ES `[x, y_bottom_up, width, height]` scissor rectangle.
4497#[must_use]
4498pub fn gles3_scissor_from_top_down(
4499    surface_h: u32,
4500    sx: u32,
4501    sy: u32,
4502    stroke_width: u32,
4503    sh: u32,
4504) -> [i32; 4] {
4505    let y1: u32 = sy.saturating_add(sh).min(surface_h);
4506    let y_bottom: u32 = surface_h.saturating_sub(y1);
4507    [sx as i32, y_bottom as i32, stroke_width as i32, sh as i32]
4508}
4509
4510/// Selects the lowest-cost texture upload strategy (`MultiRect`, `MergedBbox`, `FullFrame`, or `None`) from dirty rectangles and surface dimensions.
4511///
4512/// # Arguments
4513///
4514/// - `u32` - Framebuffer width in pixels.
4515/// - `u32` - Framebuffer height in pixels.
4516/// - `&[PixelDirtyRect]` - Candidate damaged sub-rectangles in physical pixels.
4517/// - `bool` - When `true`, forces a `FullFrame` upload (e.g. surface resize or first frame).
4518///
4519/// # Returns
4520///
4521/// - `AdaptiveUploadPlan` - Selected strategy, coalesced rectangle list, and byte/cost metrics.
4522#[must_use]
4523pub fn select_adaptive_upload_plan(
4524    fb_w: u32,
4525    fb_h: u32,
4526    dirty_rects: &[PixelDirtyRect],
4527    force_full: bool,
4528) -> AdaptiveUploadPlan {
4529    if fb_w == 0 || fb_h == 0 {
4530        return AdaptiveUploadPlan {
4531            strategy: MobileUploadStrategy::None,
4532            rects: Vec::new(),
4533            total_upload_bytes: 0,
4534            merged_bbox_bytes: 0,
4535            full_frame_bytes: 0,
4536            estimated_cost_score: 0.0,
4537        };
4538    }
4539    let full_rect: PixelDirtyRect = PixelDirtyRect::new(0, 0, fb_w, fb_h);
4540    let full_bytes: usize = full_rect.byte_size_rgba8();
4541    if force_full {
4542        return AdaptiveUploadPlan {
4543            strategy: MobileUploadStrategy::FullFrame,
4544            rects: vec![full_rect],
4545            total_upload_bytes: full_bytes,
4546            merged_bbox_bytes: full_bytes,
4547            full_frame_bytes: full_bytes,
4548            estimated_cost_score: (full_bytes + MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES) as f32,
4549        };
4550    }
4551    let mut coalesced: Vec<PixelDirtyRect> = Vec::with_capacity(dirty_rects.len().min(16));
4552    for rect in dirty_rects.iter() {
4553        let Some(mut clamped) = rect.clamp_to(fb_w, fb_h) else {
4554            continue;
4555        };
4556        let mut merged_any: bool = true;
4557        while merged_any {
4558            merged_any = false;
4559            let mut idx: usize = 0;
4560            while idx < coalesced.len() {
4561                if coalesced[idx].intersects_or_adjacent(clamped, MOBILE_UPLOAD_COALESCE_PAD_PX) {
4562                    let existing: PixelDirtyRect = coalesced.swap_remove(idx);
4563                    clamped = clamped.union_with(existing);
4564                    merged_any = true;
4565                } else {
4566                    idx += 1;
4567                }
4568            }
4569        }
4570        coalesced.push(clamped);
4571    }
4572    if coalesced.is_empty() {
4573        return AdaptiveUploadPlan {
4574            strategy: MobileUploadStrategy::None,
4575            rects: Vec::new(),
4576            total_upload_bytes: 0,
4577            merged_bbox_bytes: 0,
4578            full_frame_bytes: full_bytes,
4579            estimated_cost_score: 0.0,
4580        };
4581    }
4582    let mut merged_bbox: PixelDirtyRect = coalesced[0];
4583    let mut multi_bytes: usize = 0;
4584    for red_val in coalesced.iter() {
4585        merged_bbox = merged_bbox.union_with(*red_val);
4586        multi_bytes = multi_bytes.saturating_add(red_val.byte_size_rgba8());
4587    }
4588    let merged_bytes: usize = merged_bbox.byte_size_rgba8();
4589    let multi_cost: usize = multi_bytes.saturating_add(
4590        coalesced
4591            .len()
4592            .saturating_mul(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES),
4593    );
4594    let merged_cost: usize = merged_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
4595    let full_threshold_bytes: usize =
4596        ((full_bytes as f32) * MOBILE_UPLOAD_FULL_FRAME_COVERAGE_THRESHOLD).round() as usize;
4597    let full_cost: usize = full_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
4598    let multi_eligible: bool = coalesced.len() >= 2
4599        && coalesced.len() <= MOBILE_MAX_MULTI_UPLOAD_RECTS
4600        && multi_bytes <= full_threshold_bytes
4601        && multi_cost < merged_cost
4602        && multi_cost < full_cost;
4603    if multi_eligible {
4604        return AdaptiveUploadPlan {
4605            strategy: MobileUploadStrategy::MultiRect,
4606            rects: coalesced,
4607            total_upload_bytes: multi_bytes,
4608            merged_bbox_bytes: merged_bytes,
4609            full_frame_bytes: full_bytes,
4610            estimated_cost_score: multi_cost as f32,
4611        };
4612    }
4613    if merged_bytes <= full_threshold_bytes && merged_cost < full_cost {
4614        return AdaptiveUploadPlan {
4615            strategy: MobileUploadStrategy::MergedBbox,
4616            rects: vec![merged_bbox],
4617            total_upload_bytes: merged_bytes,
4618            merged_bbox_bytes: merged_bytes,
4619            full_frame_bytes: full_bytes,
4620            estimated_cost_score: merged_cost as f32,
4621        };
4622    }
4623    AdaptiveUploadPlan {
4624        strategy: MobileUploadStrategy::FullFrame,
4625        rects: vec![full_rect],
4626        total_upload_bytes: full_bytes,
4627        merged_bbox_bytes: merged_bytes,
4628        full_frame_bytes: full_bytes,
4629        estimated_cost_score: full_cost as f32,
4630    }
4631}
4632
4633/// Converts a `DamageRegion` into physical `PixelDirtyRect` entries clamped to `(fb_w, fb_h)`.
4634///
4635/// # Arguments
4636///
4637/// - `DamageRegion` - Frame damage region from layout/paint.
4638/// - `u32` - Surface width in physical pixels.
4639/// - `u32` - Surface height in physical pixels.
4640///
4641/// # Returns
4642///
4643/// - `Vec<PixelDirtyRect>` - Clamped physical dirty rectangles (`empty` when no damage).
4644#[must_use]
4645pub fn damage_region_to_pixel_dirty_rects(
4646    damage: DamageRegion,
4647    fb_w: u32,
4648    fb_h: u32,
4649) -> Vec<PixelDirtyRect> {
4650    if fb_w == 0 || fb_h == 0 {
4651        return Vec::new();
4652    }
4653    if damage.get_full_damage() {
4654        return vec![PixelDirtyRect::new(0, 0, fb_w, fb_h)];
4655    }
4656    let Some(red_val) = damage.resolve(fb_w, fb_h) else {
4657        return Vec::new();
4658    };
4659    let rx0: u32 = (red_val.get_x().floor().max(0.0) as u32).min(fb_w);
4660    let ry0: u32 = (red_val.get_y().floor().max(0.0) as u32).min(fb_h);
4661    let rx1: u32 = (red_val.right().ceil().max(0.0) as u32).clamp(rx0, fb_w);
4662    let ry1: u32 = (red_val.bottom().ceil().max(0.0) as u32).clamp(ry0, fb_h);
4663    if rx1 > rx0 && ry1 > ry0 {
4664        vec![PixelDirtyRect::new(rx0, ry0, rx1 - rx0, ry1 - ry0)]
4665    } else {
4666        Vec::new()
4667    }
4668}
4669
4670/// Flattens pre-compiled `HardwareRenderer` `GpuBatch` and `GpuBackdropBlurPass` slices into a single direct-GPU frame payload.
4671///
4672/// # Arguments
4673///
4674/// - `u32` - Physical surface width in pixels.
4675/// - `u32` - Physical surface height in pixels.
4676/// - `Color` - Surface clear color.
4677/// - `&[GpuBatch]` - Ordered GPU batches from `HardwareRenderer::active_batches_slice()`.
4678/// - `&[GpuBackdropBlurPass]` - Ordered Dual-Kawase backdrop blur passes.
4679///
4680/// # Returns
4681///
4682/// - `DirectGpuFrameBatch` - Flat 64-byte primitive stream and scissor draw ranges with `cpu_mirror_active = false`.
4683#[must_use]
4684pub fn build_direct_gpu_frame_batch_from_batches(
4685    viewport_width: u32,
4686    viewport_height: u32,
4687    clear_color: Color,
4688    batches: &[GpuBatch],
4689    blur_passes: &[GpuBackdropBlurPass],
4690) -> DirectGpuFrameBatch {
4691    let total_prims: usize = batches
4692        .iter()
4693        .map(|blue_val: &GpuBatch| {
4694            blue_val
4695                .get_primitives()
4696                .len()
4697                .max(blue_val.get_instances().len())
4698        })
4699        .sum();
4700    let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(total_prims);
4701    let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(batches.len());
4702    let vw: u32 = viewport_width.max(1);
4703    let vh: u32 = viewport_height.max(1);
4704    for batch in batches.iter() {
4705        let base_instance: u32 = primitives.len() as u32;
4706        if !batch.get_primitives().is_empty() {
4707            primitives.extend_from_slice(batch.get_primitives());
4708        } else {
4709            for quad in batch.get_instances().iter() {
4710                primitives.push(GpuPrimitiveInstance::from_quad_instance(
4711                    quad,
4712                    batch.get_texture_slot(),
4713                    batch.get_layer_id(),
4714                ));
4715            }
4716        }
4717        let instance_count: u32 = (primitives.len() as u32).saturating_sub(base_instance);
4718        if instance_count == 0 {
4719            continue;
4720        }
4721        let rect_bounds: Rect = batch.get_scissor();
4722        let sx: u32 = (rect_bounds.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
4723        let sy: u32 = (rect_bounds.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
4724        let stroke_width: u32 = (rect_bounds.get_width().max(1.0).ceil() as u32)
4725            .min(vw.saturating_sub(sx))
4726            .max(1);
4727        let sh: u32 = (rect_bounds.get_height().max(1.0).ceil() as u32)
4728            .min(vh.saturating_sub(sy))
4729            .max(1);
4730        let scroll: [f32; 2] = batch.get_scroll_offset();
4731        draw_ranges.push(DirectGpuBatchRange {
4732            base_instance,
4733            instance_count,
4734            scissor_x: sx,
4735            scissor_y: sy,
4736            scissor_w: stroke_width,
4737            scissor_h: sh,
4738            scroll_x: scroll[0],
4739            scroll_y: scroll[1],
4740            texture_slot: batch.get_texture_slot(),
4741            layer_id: batch.get_layer_id(),
4742            pad: [0, 0],
4743        });
4744    }
4745    let instance_upload_bytes: usize = primitives
4746        .len()
4747        .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
4748    DirectGpuFrameBatch {
4749        viewport_width: vw,
4750        viewport_height: vh,
4751        clear_rgba: clear_color.to_f32_array(),
4752        primitives,
4753        draw_ranges,
4754        backdrop_blurs: blur_passes.to_vec(),
4755        glyph_r8_atlas: None,
4756        image_rgba8_atlas: None,
4757        instance_upload_bytes,
4758        cpu_mirror_active: false,
4759        upload_strategy: MobileUploadStrategy::DirectGpu,
4760    }
4761}
4762
4763/// Appends one `GpuPrimitiveInstance` into `primitives` and extends or opens a scissor-matched `DirectGpuBatchRange`.
4764///
4765/// # Arguments
4766///
4767/// - `&mut Vec<GpuPrimitiveInstance>` - Flat primitive stream.
4768/// - `&mut Vec<DirectGpuBatchRange>` - Ordered draw ranges.
4769/// - `GpuPrimitiveInstance` - Primitive to emit.
4770/// - `Rect` - Active physical scissor clip rectangle.
4771/// - `u32` - Surface width in physical pixels.
4772/// - `u32` - Surface height in physical pixels.
4773fn push_direct_gpu_primitive(
4774    primitives: &mut Vec<GpuPrimitiveInstance>,
4775    draw_ranges: &mut Vec<DirectGpuBatchRange>,
4776    prim: GpuPrimitiveInstance,
4777    clip: Rect,
4778    vw: u32,
4779    vh: u32,
4780) {
4781    if clip.get_width() <= 0.0 || clip.get_height() <= 0.0 {
4782        return;
4783    }
4784    let sx: u32 = (clip.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
4785    let sy: u32 = (clip.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
4786    let stroke_width: u32 = (clip.get_width().max(1.0).ceil() as u32)
4787        .min(vw.saturating_sub(sx))
4788        .max(1);
4789    let sh: u32 = (clip.get_height().max(1.0).ceil() as u32)
4790        .min(vh.saturating_sub(sy))
4791        .max(1);
4792    let layer_id: u8 = prim.layer_id();
4793    let is_blur: bool = prim.prim_kind() == PrimKind::BackdropBlur;
4794    let base: u32 = primitives.len() as u32;
4795    let prev_is_blur: bool = draw_ranges
4796        .last()
4797        .is_some_and(|last: &DirectGpuBatchRange| {
4798            primitives
4799                .get(last.get_base_instance() as usize)
4800                .is_some_and(|head: &GpuPrimitiveInstance| {
4801                    head.prim_kind() == PrimKind::BackdropBlur
4802                })
4803        });
4804    primitives.push(prim);
4805    if !is_blur
4806        && !prev_is_blur
4807        && let Some(last) = draw_ranges.last_mut()
4808        && last.get_scissor_x() == sx
4809        && last.get_scissor_y() == sy
4810        && last.get_scissor_w() == stroke_width
4811        && last.get_scissor_h() == sh
4812        && last.get_layer_id() == layer_id
4813        && last.get_instance_count() < MAX_QUADS_PER_BATCH as u32
4814    {
4815        last.set_instance_count(last.get_instance_count().saturating_add(1));
4816        return;
4817    }
4818    draw_ranges.push(DirectGpuBatchRange {
4819        base_instance: base,
4820        instance_count: 1,
4821        scissor_x: sx,
4822        scissor_y: sy,
4823        scissor_w: stroke_width,
4824        scissor_h: sh,
4825        scroll_x: 0.0,
4826        scroll_y: 0.0,
4827        texture_slot: 0,
4828        layer_id,
4829        pad: [0, 0],
4830    });
4831}
4832
4833/// Encodes normalized `[u0, v0, u1, v1]` texel bounds inside an `(atlas_w, atlas_h)` sheet into `[u16; 4]`.
4834///
4835/// # Arguments
4836///
4837/// - `u32` - Atlas width in texels.
4838/// - `u32` - Atlas height in texels.
4839/// - `u32` - Sub-rectangle X coordinate in texels.
4840/// - `u32` - Sub-rectangle Y coordinate in texels.
4841/// - `u32` - Sub-rectangle width in texels.
4842/// - `u32` - Sub-rectangle height in texels.
4843///
4844/// # Returns
4845///
4846/// - `[u16; 4]` - Normalized UV coordinates in `[0..=65535]`.
4847fn encode_atlas_uv_rect(
4848    atlas_w: u32,
4849    atlas_h: u32,
4850    pos_x: u32,
4851    pos_y: u32,
4852    width_val: u32,
4853    height_val: u32,
4854) -> [u16; 4] {
4855    let inv_w: f32 = 1.0 / (atlas_w.max(1) as f32);
4856    let inv_h: f32 = 1.0 / (atlas_h.max(1) as f32);
4857    let u0: u16 = (((pos_x as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
4858    let v0: u16 = (((pos_y as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
4859    let u1: u16 = ((((pos_x + width_val) as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
4860    let v1: u16 =
4861        ((((pos_y + height_val) as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
4862    [u0, v0, u1, v1]
4863}
4864
4865/// Packs frame RGBA8 image/sprite slices into a single shelf-packed RGBA8 texture atlas and resolves UV rectangles.
4866///
4867/// # Arguments
4868///
4869/// - `&[DirectGpuImageSlice<'_>]` - Borrowed RGBA8 image and sprite crop descriptors.
4870/// - `u64` - Revision tag stamped onto the output atlas.
4871///
4872/// # Returns
4873///
4874/// - `(Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>)` - Packed RGBA8 image sheet and per-entry normalized UVs.
4875fn pack_frame_image_atlas(
4876    images: &[DirectGpuImageSlice<'_>],
4877    revision: u64,
4878) -> (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) {
4879    if images.is_empty() {
4880        return (None, Vec::new());
4881    }
4882    let mut max_w: u32 = 1;
4883    let mut sum_w: u32 = 1;
4884    for entry in images.iter() {
4885        let cw: u32 = entry.crop.get_width();
4886        max_w = max_w.max(cw.saturating_add(2));
4887        sum_w = sum_w.saturating_add(cw.saturating_add(1));
4888    }
4889    let atlas_w: u32 = sum_w
4890        .clamp(64, 2048)
4891        .max(max_w)
4892        .next_power_of_two()
4893        .min(16384);
4894    let mut placements: Vec<(u32, u32, u32, u32)> = Vec::with_capacity(images.len());
4895    let mut cx: u32 = 1;
4896    let mut cy: u32 = 1;
4897    let mut shelf_h: u32 = 0;
4898    for entry in images.iter() {
4899        let clamped_w: u32 = entry.crop.get_width().min(atlas_w.saturating_sub(2)).max(1);
4900        let clamped_h: u32 = entry.crop.get_height().max(1);
4901        if cx + clamped_w + 1 > atlas_w {
4902            cx = 1;
4903            cy = cy.saturating_add(shelf_h).saturating_add(1);
4904            shelf_h = 0;
4905        }
4906        placements.push((cx, cy, clamped_w, clamped_h));
4907        cx = cx.saturating_add(clamped_w).saturating_add(1);
4908        shelf_h = shelf_h.max(clamped_h);
4909    }
4910    let atlas_h: u32 = cy.saturating_add(shelf_h).saturating_add(1).max(64);
4911    let mut pixels: Vec<u8> = vec![0; (atlas_w as usize) * (atlas_h as usize) * 4];
4912    let mut uvs: Vec<[u16; 4]> = Vec::with_capacity(images.len());
4913    for (idx, entry) in images.iter().enumerate() {
4914        let (dx, dy, copy_w, copy_h): (u32, u32, u32, u32) = placements[idx];
4915        let sx: u32 = entry.crop.get_x();
4916        let sy: u32 = entry.crop.get_y();
4917        let valid_w: u32 = copy_w.min(entry.src_w.saturating_sub(sx));
4918        let valid_h: u32 = copy_h.min(entry.src_h.saturating_sub(sy));
4919        for row in 0..valid_h {
4920            let src_off: usize =
4921                (((sy + row) as usize) * (entry.src_w as usize) + (sx as usize)) * 4;
4922            let dst_off: usize = (((dy + row) as usize) * (atlas_w as usize) + (dx as usize)) * 4;
4923            let row_bytes: usize = (valid_w as usize) * 4;
4924            if src_off + row_bytes <= entry.pixels.len() && dst_off + row_bytes <= pixels.len() {
4925                pixels[dst_off..dst_off + row_bytes]
4926                    .copy_from_slice(&entry.pixels[src_off..src_off + row_bytes]);
4927            }
4928        }
4929        uvs.push(encode_atlas_uv_rect(
4930            atlas_w, atlas_h, dx, dy, valid_w, valid_h,
4931        ));
4932    }
4933    (
4934        Some(DirectGpuAtlasUpload {
4935            width: atlas_w,
4936            height: atlas_h,
4937            revision,
4938            pixels,
4939        }),
4940        uvs,
4941    )
4942}
4943
4944/// Compiles a complete `DisplayList` directly into a zero-CPU-mirror `DirectGpuFrameBatch` with R8 glyph atlas and RGBA8 image sheet uploads for Android GLES 3.0 and iOS Metal.
4945///
4946/// # Arguments
4947///
4948/// - `&DisplayList` - Scene draw command stream for the current frame.
4949/// - `Option<&mut GlyphAtlas>` - Shared glyph atlas used to rasterize and pack `PrimKind::GlyphAlpha8` quads.
4950/// - `Option<&NativeSystemFont>` - Optional native OS font provider for glyph rasterization.
4951/// - `u64` - Previously uploaded glyph atlas revision (`0` forces initial upload).
4952///
4953/// # Returns
4954///
4955/// - `DirectGpuFrameBatch` - Self-contained direct-GPU primitive, range, blur, and atlas payload (`cpu_mirror_active = false`).
4956#[must_use]
4957pub fn compile_display_list_direct_gpu_batch(
4958    display_list: &DisplayList,
4959    mut glyph_atlas: Option<&mut GlyphAtlas>,
4960    font_provider: Option<&NativeSystemFont>,
4961    last_glyph_revision: u64,
4962) -> DirectGpuFrameBatch {
4963    let scale: f32 = display_list.get_scale_factor().max(0.5);
4964    let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
4965    let phys_h: u32 = ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
4966    let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
4967    let mut clip_stack: Vec<(Rect, Rect, u16)> = Vec::with_capacity(16);
4968    clip_stack.push((full_clip, full_clip, 0));
4969    let mut primitives: Vec<GpuPrimitiveInstance> =
4970        Vec::with_capacity(display_list.get_commands().len().saturating_mul(2));
4971    let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(16);
4972    let mut backdrop_blurs: Vec<GpuBackdropBlurPass> = Vec::new();
4973    let mut glyph_fixups: Vec<(usize, GlyphKey)> = Vec::new();
4974    let mut image_entries: Vec<DirectGpuImageSlice<'_>> = Vec::new();
4975    let mut image_fixups: Vec<(usize, usize)> = Vec::new();
4976    let mut clear_rgba: [f32; 4] = COLOR_WHITE.to_f32_array();
4977    let mut active_layer_id: u8 = 0;
4978    for cmd in display_list.get_commands().iter() {
4979        let (active_clip, safe_inner_clip, active_rounded_bits): (Rect, Rect, u16) = clip_stack
4980            .last()
4981            .copied()
4982            .unwrap_or((full_clip, full_clip, 0));
4983        let clip_arr: [f32; 4] = [
4984            active_clip.get_x(),
4985            active_clip.get_y(),
4986            active_clip.right(),
4987            active_clip.bottom(),
4988        ];
4989        let cmd_prim_start: usize = primitives.len();
4990        match cmd {
4991            DrawCommand::Clear(char_item) => {
4992                clear_rgba = char_item.to_f32_array();
4993            }
4994            DrawCommand::PushClip(rect) => {
4995                let phys: Rect = snap_physical_rect(*rect, scale);
4996                let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
4997                let next_safe: Rect = safe_inner_clip.intersect(phys).unwrap_or_default();
4998                let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
4999                    active_clip,
5000                    active_rounded_bits,
5001                    next_scissor,
5002                    phys,
5003                    None,
5004                );
5005                clip_stack.push((next_scissor, next_safe, next_bits));
5006            }
5007            DrawCommand::PushRoundedClip { rect, radius } => {
5008                let phys: Rect = snap_physical_rect(*rect, scale);
5009                let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
5010                let phys_radius: CornerRadius = CornerRadius::new(
5011                    radius.get_top_left() * scale,
5012                    radius.get_top_right() * scale,
5013                    radius.get_bottom_right() * scale,
5014                    radius.get_bottom_left() * scale,
5015                );
5016                let max_r: f32 = phys_radius.max_radius().ceil();
5017                let inset_w: f32 = (phys.get_width() - max_r * 2.0).max(0.0);
5018                let inset_h: f32 = (phys.get_height() - max_r * 2.0).max(0.0);
5019                let rounded_safe: Rect =
5020                    Rect::new(phys.get_x() + max_r, phys.get_y() + max_r, inset_w, inset_h);
5021                let next_safe: Rect = safe_inner_clip.intersect(rounded_safe).unwrap_or_default();
5022                let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
5023                    active_clip,
5024                    active_rounded_bits,
5025                    next_scissor,
5026                    phys,
5027                    Some(phys_radius),
5028                );
5029                clip_stack.push((next_scissor, next_safe, next_bits));
5030            }
5031            DrawCommand::PopClip => {
5032                if clip_stack.len() > 1 {
5033                    let _: Option<(Rect, Rect, u16)> = clip_stack.pop();
5034                }
5035            }
5036            DrawCommand::FillRoundedRect {
5037                rect,
5038                color,
5039                radius,
5040                border,
5041            } => {
5042                let snapped: Rect = snap_physical_rect(*rect, scale);
5043                let quad: [f32; 4] = [
5044                    snapped.get_x(),
5045                    snapped.get_y(),
5046                    snapped.get_width(),
5047                    snapped.get_height(),
5048                ];
5049                if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
5050                    continue;
5051                }
5052                let border_width: f32 = if border.get_width() > 0.0 {
5053                    (border.get_width() * scale).round().max(1.0)
5054                } else {
5055                    0.0
5056                };
5057                let query_val: GpuQuadInstance = GpuQuadInstance {
5058                    rect: quad,
5059                    clip: clip_arr,
5060                    color: color.to_f32_array(),
5061                    secondary_color: border.get_color().to_f32_array(),
5062                    radii: [
5063                        radius.get_top_left() * scale,
5064                        radius.get_top_right() * scale,
5065                        radius.get_bottom_right() * scale,
5066                        radius.get_bottom_left() * scale,
5067                    ],
5068                    stroke_or_blur: border_width,
5069                    angle_rad: 0.0,
5070                    kind: GpuPrimitiveKind::RoundedRect as u32,
5071                    reserved: 0,
5072                };
5073                push_direct_gpu_primitive(
5074                    &mut primitives,
5075                    &mut draw_ranges,
5076                    GpuPrimitiveInstance::from_quad_instance(&query_val, 0, active_layer_id),
5077                    active_clip,
5078                    phys_w,
5079                    phys_h,
5080                );
5081            }
5082            DrawCommand::LinearGradientRect {
5083                rect,
5084                gradient,
5085                radius,
5086            } => {
5087                let snapped: Rect = snap_physical_rect(*rect, scale);
5088                let quad: [f32; 4] = [
5089                    snapped.get_x(),
5090                    snapped.get_y(),
5091                    snapped.get_width(),
5092                    snapped.get_height(),
5093                ];
5094                if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
5095                    continue;
5096                }
5097                let quat_val: GpuQuadInstance = GpuQuadInstance {
5098                    rect: quad,
5099                    clip: clip_arr,
5100                    color: gradient.get_start_color().to_f32_array(),
5101                    secondary_color: gradient.get_end_color().to_f32_array(),
5102                    radii: [
5103                        radius.get_top_left() * scale,
5104                        radius.get_top_right() * scale,
5105                        radius.get_bottom_right() * scale,
5106                        radius.get_bottom_left() * scale,
5107                    ],
5108                    stroke_or_blur: 0.0,
5109                    angle_rad: gradient.get_angle_deg().to_radians(),
5110                    kind: GpuPrimitiveKind::Gradient as u32,
5111                    reserved: 0,
5112                };
5113                push_direct_gpu_primitive(
5114                    &mut primitives,
5115                    &mut draw_ranges,
5116                    GpuPrimitiveInstance::from_quad_instance(&quat_val, 0, active_layer_id),
5117                    active_clip,
5118                    phys_w,
5119                    phys_h,
5120                );
5121            }
5122            DrawCommand::BoxShadow {
5123                rect,
5124                radius,
5125                shadow,
5126            } => {
5127                let spread: f32 = shadow.get_spread_radius() * scale;
5128                let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
5129                let sigma: f32 = (blur * 0.5).max(0.75);
5130                let pad: f32 = (sigma * 3.0).ceil();
5131                let base_rect: Rect = snap_physical_rect(*rect, scale);
5132                let cx: f32 = base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
5133                let cy: f32 = base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
5134                let cw: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
5135                let ch: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
5136                let corner_vec: GpuQuadInstance = GpuQuadInstance {
5137                    rect: [cx - pad, cy - pad, cw + pad * 2.0, ch + pad * 2.0],
5138                    clip: clip_arr,
5139                    color: shadow.get_color().to_f32_array(),
5140                    secondary_color: [0.0; 4],
5141                    radii: [
5142                        (radius.get_top_left() * scale + spread).max(0.0),
5143                        (radius.get_top_right() * scale + spread).max(0.0),
5144                        (radius.get_bottom_right() * scale + spread).max(0.0),
5145                        (radius.get_bottom_left() * scale + spread).max(0.0),
5146                    ],
5147                    stroke_or_blur: sigma,
5148                    angle_rad: pad,
5149                    kind: GpuPrimitiveKind::Shadow as u32,
5150                    reserved: 0,
5151                };
5152                push_direct_gpu_primitive(
5153                    &mut primitives,
5154                    &mut draw_ranges,
5155                    GpuPrimitiveInstance::from_quad_instance(&corner_vec, 0, active_layer_id),
5156                    active_clip,
5157                    phys_w,
5158                    phys_h,
5159                );
5160            }
5161            DrawCommand::BackdropBlur {
5162                rect,
5163                radius,
5164                blur_radius,
5165            } => {
5166                let snapped: Rect = snap_physical_rect(*rect, scale);
5167                let Some(vis_blur) = snapped.intersect(active_clip) else {
5168                    continue;
5169                };
5170                if vis_blur.get_width() <= 0.0 || vis_blur.get_height() <= 0.0 {
5171                    continue;
5172                }
5173                let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 96.0);
5174                let radii_px: [f32; 4] = [
5175                    radius.get_top_left() * scale,
5176                    radius.get_top_right() * scale,
5177                    radius.get_bottom_right() * scale,
5178                    radius.get_bottom_left() * scale,
5179                ];
5180                let halo_x0: f32 = (vis_blur.get_x() - phys_blur)
5181                    .max(active_clip.get_x())
5182                    .max(0.0);
5183                let halo_y0: f32 = (vis_blur.get_y() - phys_blur)
5184                    .max(active_clip.get_y())
5185                    .max(0.0);
5186                let halo_x1: f32 = (vis_blur.right() + phys_blur)
5187                    .min(active_clip.right())
5188                    .min(phys_w as f32);
5189                let halo_y1: f32 = (vis_blur.bottom() + phys_blur)
5190                    .min(active_clip.bottom())
5191                    .min(phys_h as f32);
5192                let halo: Rect = Rect::new(
5193                    halo_x0,
5194                    halo_y0,
5195                    (halo_x1 - halo_x0).max(0.0),
5196                    (halo_y1 - halo_y0).max(0.0),
5197                );
5198                let pass_layer_id: u8 = active_layer_id;
5199                backdrop_blurs.push(GpuBackdropBlurPass {
5200                    bounds: snapped,
5201                    input_bounds: halo,
5202                    clip_rect: active_clip,
5203                    radii: radii_px,
5204                    blur_radius: phys_blur,
5205                    layer_id: pass_layer_id,
5206                });
5207                let quad: [f32; 4] = [
5208                    snapped.get_x(),
5209                    snapped.get_y(),
5210                    snapped.get_width(),
5211                    snapped.get_height(),
5212                ];
5213                let inv_vp_w: f32 = 1.0 / (phys_w.max(1) as f32);
5214                let inv_vp_h: f32 = 1.0 / (phys_h.max(1) as f32);
5215                let blur_uv: [u16; 4] = [
5216                    (snapped.get_x() * inv_vp_w * 65535.0)
5217                        .round()
5218                        .clamp(0.0, 65535.0) as u16,
5219                    (snapped.get_y() * inv_vp_h * 65535.0)
5220                        .round()
5221                        .clamp(0.0, 65535.0) as u16,
5222                    (snapped.right() * inv_vp_w * 65535.0)
5223                        .round()
5224                        .clamp(0.0, 65535.0) as u16,
5225                    (snapped.bottom() * inv_vp_h * 65535.0)
5226                        .round()
5227                        .clamp(0.0, 65535.0) as u16,
5228                ];
5229                let radius_cap: f32 = GpuPrimitiveInstance::corner_radius_cap(quad, 0, 0.0);
5230                let blur_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
5231                    rect: quad,
5232                    clip_rect: clip_arr,
5233                    color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
5234                    aux_color_rgba: 0,
5235                    uv_rect: blur_uv,
5236                    radii_border: [
5237                        GpuPrimitiveInstance::pack_u16_q4(radii_px[0].min(radius_cap)),
5238                        GpuPrimitiveInstance::pack_u16_q4(radii_px[1].min(radius_cap)),
5239                        GpuPrimitiveInstance::pack_u16_q4(radii_px[2].min(radius_cap)),
5240                        GpuPrimitiveInstance::pack_u16_q4(radii_px[3].min(radius_cap)),
5241                    ],
5242                    kind_flags: GpuPrimitiveInstance::pack_kind_flags(
5243                        PrimKind::BackdropBlur,
5244                        0,
5245                        0,
5246                        pass_layer_id,
5247                    ),
5248                    extra_param: GpuPrimitiveInstance::pack_f16x2(phys_blur, 0.0),
5249                }
5250                .with_rounded_clip_bits(active_rounded_bits);
5251                push_direct_gpu_primitive(
5252                    &mut primitives,
5253                    &mut draw_ranges,
5254                    blur_prim,
5255                    active_clip,
5256                    phys_w,
5257                    phys_h,
5258                );
5259                active_layer_id = active_layer_id.saturating_add(1);
5260            }
5261            DrawCommand::TextRun { rect, text, style } => {
5262                if text.is_empty()
5263                    || active_clip.get_width() <= 0.0
5264                    || active_clip.get_height() <= 0.0
5265                {
5266                    continue;
5267                }
5268                if let Some(atlas) = glyph_atlas.as_deref_mut() {
5269                    let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
5270                    let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
5271                        text,
5272                        *style,
5273                        Some(rect.get_width().max(1.0)),
5274                    );
5275                    let line_h: f32 = meas.get_line_height_px() * scale;
5276                    let letter_sp: f32 = style.get_letter_spacing() * scale;
5277                    let rect_w_px: f32 = rect.get_width() * scale;
5278                    let color_rgba: u32 = GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
5279                    let kind_flags: u32 = GpuPrimitiveInstance::pack_kind_flags(
5280                        PrimKind::GlyphAlpha8,
5281                        0,
5282                        0,
5283                        active_layer_id,
5284                    );
5285                    let mut line_glyphs: Vec<(Option<GlyphKey>, u32, u32, f32)> = Vec::new();
5286                    for (line_idx, line) in meas.get_lines().iter().enumerate() {
5287                        line_glyphs.clear();
5288                        let mut line_w_px: f32 = 0.0;
5289                        for ch in line.get_text().chars() {
5290                            if ch == ' ' || ch == '\t' {
5291                                let sp_adv: f32 = measure_char_advance(ch, *style) * scale;
5292                                line_glyphs.push((None, 0, 0, sp_adv));
5293                                line_w_px += sp_adv;
5294                                continue;
5295                            }
5296                            let key: GlyphKey = GlyphKey::from_text_style(ch, phys_font_px, *style);
5297                            let (gw, gh, adv): (u32, u32, f32) = {
5298                                let green_val: &RasterizedGlyph = match font_provider {
5299                                    Some(fp) => atlas.get_or_rasterize_with(key, fp),
5300                                    None => atlas.get_or_rasterize(key),
5301                                };
5302                                (
5303                                    green_val.get_width(),
5304                                    green_val.get_height(),
5305                                    (green_val.get_advance() as f32).max(1.0) + letter_sp,
5306                                )
5307                            };
5308                            line_glyphs.push((Some(key), gw, gh, adv));
5309                            line_w_px += adv;
5310                        }
5311                        let fit_scale: f32 = if rect_w_px > 1.0 && line_w_px > rect_w_px + 1.0 {
5312                            (rect_w_px / line_w_px).clamp(0.72, 1.0)
5313                        } else {
5314                            1.0
5315                        };
5316                        let fitted_line_w: f32 = line_w_px * fit_scale;
5317                        let align_offset: f32 = match style.get_align() {
5318                            TextAlign::Center => ((rect_w_px - fitted_line_w) * 0.5).max(0.0),
5319                            TextAlign::Right => (rect_w_px - fitted_line_w).max(0.0),
5320                            TextAlign::Left => 0.0,
5321                        };
5322                        let base_y: f32 = rect.get_y() * scale + (line_idx as f32) * line_h;
5323                        let mut pen_x: f32 = rect.get_x() * scale + align_offset;
5324                        for &(key_opt, gw, gh, adv) in line_glyphs.iter() {
5325                            if let Some(key) = key_opt
5326                                && gw > 0
5327                                && gh > 0
5328                            {
5329                                let y_off: f32 = ((line_h - (gh as f32)) * 0.5).round();
5330                                let prim_idx: usize = primitives.len();
5331                                let prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
5332                                    rect: [
5333                                        pen_x.round(),
5334                                        (base_y + y_off).round(),
5335                                        gw as f32,
5336                                        gh as f32,
5337                                    ],
5338                                    clip_rect: clip_arr,
5339                                    color_rgba,
5340                                    aux_color_rgba: 0,
5341                                    uv_rect: [0, 0, 0, 0],
5342                                    radii_border: [0; 4],
5343                                    kind_flags,
5344                                    extra_param: 0,
5345                                };
5346                                push_direct_gpu_primitive(
5347                                    &mut primitives,
5348                                    &mut draw_ranges,
5349                                    prim,
5350                                    active_clip,
5351                                    phys_w,
5352                                    phys_h,
5353                                );
5354                                glyph_fixups.push((prim_idx, key));
5355                            }
5356                            pen_x += adv * fit_scale;
5357                        }
5358                    }
5359                } else {
5360                    let queue_entry: GpuQuadInstance = GpuQuadInstance {
5361                        rect: [
5362                            rect.get_x() * scale,
5363                            rect.get_y() * scale,
5364                            rect.get_width() * scale,
5365                            rect.get_height() * scale,
5366                        ],
5367                        clip: clip_arr,
5368                        color: style.get_color().to_f32_array(),
5369                        secondary_color: [0.0; 4],
5370                        radii: [0.0; 4],
5371                        stroke_or_blur: style.get_font_size() * scale,
5372                        angle_rad: 0.0,
5373                        kind: GpuPrimitiveKind::Glyph as u32,
5374                        reserved: text.chars().count() as u32,
5375                    };
5376                    push_direct_gpu_primitive(
5377                        &mut primitives,
5378                        &mut draw_ranges,
5379                        GpuPrimitiveInstance::from_quad_instance(&queue_entry, 0, active_layer_id),
5380                        active_clip,
5381                        phys_w,
5382                        phys_h,
5383                    );
5384                }
5385            }
5386            DrawCommand::TextCaret {
5387                text_rect,
5388                content_rect,
5389                text,
5390                style,
5391                caret_height,
5392                color,
5393                multiline,
5394            } => {
5395                if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
5396                    continue;
5397                }
5398                let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
5399                    text,
5400                    *style,
5401                    if *multiline {
5402                        Some(content_rect.get_width().max(1.0))
5403                    } else {
5404                        None
5405                    },
5406                );
5407                let last_w_phys: f32 = if let Some(atlas) = glyph_atlas.as_deref_mut() {
5408                    let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
5409                    let letter_sp: f32 = style.get_letter_spacing() * scale;
5410                    if let Some(line) = meas.get_lines().last() {
5411                        let mut acc: f32 = 0.0;
5412                        for ch in line.get_text().chars() {
5413                            if ch == ' ' || ch == '\t' {
5414                                acc += measure_char_advance(ch, *style) * scale + letter_sp;
5415                            } else {
5416                                let key: GlyphKey =
5417                                    GlyphKey::from_text_style(ch, phys_font_px, *style);
5418                                let geometry_val: &RasterizedGlyph = match font_provider {
5419                                    Some(fp) => atlas.get_or_rasterize_with(key, fp),
5420                                    None => atlas.get_or_rasterize(key),
5421                                };
5422                                acc += (geometry_val.get_advance() as f32).max(1.0) + letter_sp;
5423                            }
5424                        }
5425                        acc
5426                    } else {
5427                        0.0
5428                    }
5429                } else {
5430                    meas.get_lines()
5431                        .last()
5432                        .map(TextLine::get_width)
5433                        .unwrap_or(0.0)
5434                        * scale
5435                };
5436                let line_idx: usize = meas.get_lines().len().saturating_sub(1);
5437                let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
5438                let caret_x_phys: f32 =
5439                    (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys).clamp(
5440                        content_rect.get_x() * scale,
5441                        ((content_rect.right() - 2.0) * scale).max(content_rect.get_x() * scale),
5442                    );
5443                let caret_y: f32 = if *multiline {
5444                    (content_rect.get_y()
5445                        + (line_idx as f32) * meas.get_line_height_px()
5446                        + ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
5447                    .clamp(
5448                        content_rect.get_y(),
5449                        (content_rect.bottom() - caret_height).max(content_rect.get_y()),
5450                    )
5451                } else {
5452                    content_rect.get_y()
5453                        + ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
5454                };
5455                let query_val_primary: GpuQuadInstance = GpuQuadInstance {
5456                    rect: [
5457                        caret_x_phys.round(),
5458                        (caret_y * scale).round(),
5459                        (1.5 * scale).max(1.0),
5460                        (caret_height * scale).max(2.0),
5461                    ],
5462                    clip: clip_arr,
5463                    color: color.to_f32_array(),
5464                    secondary_color: [0.0; 4],
5465                    radii: [0.5 * scale; 4],
5466                    stroke_or_blur: 0.0,
5467                    angle_rad: 0.0,
5468                    kind: GpuPrimitiveKind::RoundedRect as u32,
5469                    reserved: 0,
5470                };
5471                push_direct_gpu_primitive(
5472                    &mut primitives,
5473                    &mut draw_ranges,
5474                    GpuPrimitiveInstance::from_quad_instance(
5475                        &query_val_primary,
5476                        0,
5477                        active_layer_id,
5478                    ),
5479                    active_clip,
5480                    phys_w,
5481                    phys_h,
5482                );
5483            }
5484            DrawCommand::Image {
5485                rect,
5486                buffer,
5487                radius,
5488            } => {
5489                let snapped: Rect = snap_physical_rect(*rect, scale);
5490                let img_w: u32 = buffer.get_width();
5491                let img_h: u32 = buffer.get_height();
5492                if img_w == 0
5493                    || img_h == 0
5494                    || snapped.get_width() <= 0.0
5495                    || snapped.get_height() <= 0.0
5496                {
5497                    continue;
5498                }
5499                let img_idx: usize = image_entries.len();
5500                image_entries.push(DirectGpuImageSlice {
5501                    src_w: img_w,
5502                    src_h: img_h,
5503                    pixels: buffer.get_pixels(),
5504                    crop: PixelDirtyRect::new(0, 0, img_w, img_h),
5505                });
5506                let query_val_secondary: GpuQuadInstance = GpuQuadInstance {
5507                    rect: [
5508                        snapped.get_x(),
5509                        snapped.get_y(),
5510                        snapped.get_width(),
5511                        snapped.get_height(),
5512                    ],
5513                    clip: clip_arr,
5514                    color: [1.0, 1.0, 1.0, 1.0],
5515                    secondary_color: [0.0; 4],
5516                    radii: [
5517                        radius.get_top_left() * scale,
5518                        radius.get_top_right() * scale,
5519                        radius.get_bottom_right() * scale,
5520                        radius.get_bottom_left() * scale,
5521                    ],
5522                    stroke_or_blur: 0.0,
5523                    angle_rad: 0.0,
5524                    kind: GpuPrimitiveKind::TexturedQuad as u32,
5525                    reserved: 0,
5526                };
5527                let prim_idx: usize = primitives.len();
5528                push_direct_gpu_primitive(
5529                    &mut primitives,
5530                    &mut draw_ranges,
5531                    GpuPrimitiveInstance::from_quad_instance(
5532                        &query_val_secondary,
5533                        0,
5534                        active_layer_id,
5535                    ),
5536                    active_clip,
5537                    phys_w,
5538                    phys_h,
5539                );
5540                image_fixups.push((prim_idx, img_idx));
5541            }
5542            DrawCommand::SharedImage {
5543                rect,
5544                width,
5545                height,
5546                pixels,
5547                radius,
5548            } => {
5549                let snapped: Rect = snap_physical_rect(*rect, scale);
5550                if *width == 0
5551                    || *height == 0
5552                    || snapped.get_width() <= 0.0
5553                    || snapped.get_height() <= 0.0
5554                {
5555                    continue;
5556                }
5557                let img_idx: usize = image_entries.len();
5558                image_entries.push(DirectGpuImageSlice {
5559                    src_w: *width,
5560                    src_h: *height,
5561                    pixels: pixels.as_slice(),
5562                    crop: PixelDirtyRect::new(0, 0, *width, *height),
5563                });
5564                let query_val_next: GpuQuadInstance = GpuQuadInstance {
5565                    rect: [
5566                        snapped.get_x(),
5567                        snapped.get_y(),
5568                        snapped.get_width(),
5569                        snapped.get_height(),
5570                    ],
5571                    clip: clip_arr,
5572                    color: [1.0, 1.0, 1.0, 1.0],
5573                    secondary_color: [0.0; 4],
5574                    radii: [
5575                        radius.get_top_left() * scale,
5576                        radius.get_top_right() * scale,
5577                        radius.get_bottom_right() * scale,
5578                        radius.get_bottom_left() * scale,
5579                    ],
5580                    stroke_or_blur: 0.0,
5581                    angle_rad: 0.0,
5582                    kind: GpuPrimitiveKind::TexturedQuad as u32,
5583                    reserved: 0,
5584                };
5585                let prim_idx: usize = primitives.len();
5586                push_direct_gpu_primitive(
5587                    &mut primitives,
5588                    &mut draw_ranges,
5589                    GpuPrimitiveInstance::from_quad_instance(&query_val_next, 0, active_layer_id),
5590                    active_clip,
5591                    phys_w,
5592                    phys_h,
5593                );
5594                image_fixups.push((prim_idx, img_idx));
5595            }
5596            DrawCommand::SpriteRegion {
5597                rect,
5598                buffer,
5599                src_rect,
5600                tint,
5601            } => {
5602                let snapped: Rect = snap_physical_rect(*rect, scale);
5603                let img_w: u32 = buffer.get_width();
5604                let img_h: u32 = buffer.get_height();
5605                let sx: u32 = (src_rect.get_x().max(0.0).floor() as u32).min(img_w);
5606                let sy: u32 = (src_rect.get_y().max(0.0).floor() as u32).min(img_h);
5607                let stroke_width: u32 =
5608                    (src_rect.get_width().max(1.0).ceil() as u32).min(img_w.saturating_sub(sx));
5609                let sh: u32 =
5610                    (src_rect.get_height().max(1.0).ceil() as u32).min(img_h.saturating_sub(sy));
5611                if stroke_width == 0
5612                    || sh == 0
5613                    || snapped.get_width() <= 0.0
5614                    || snapped.get_height() <= 0.0
5615                {
5616                    continue;
5617                }
5618                let img_idx: usize = image_entries.len();
5619                image_entries.push(DirectGpuImageSlice {
5620                    src_w: img_w,
5621                    src_h: img_h,
5622                    pixels: buffer.get_pixels(),
5623                    crop: PixelDirtyRect::new(sx, sy, stroke_width, sh),
5624                });
5625                let query_val_alt: GpuQuadInstance = GpuQuadInstance {
5626                    rect: [
5627                        snapped.get_x(),
5628                        snapped.get_y(),
5629                        snapped.get_width(),
5630                        snapped.get_height(),
5631                    ],
5632                    clip: clip_arr,
5633                    color: tint.to_f32_array(),
5634                    secondary_color: [0.0; 4],
5635                    radii: [0.0; 4],
5636                    stroke_or_blur: 0.0,
5637                    angle_rad: 0.0,
5638                    kind: GpuPrimitiveKind::TexturedQuad as u32,
5639                    reserved: 1,
5640                };
5641                let prim_idx: usize = primitives.len();
5642                push_direct_gpu_primitive(
5643                    &mut primitives,
5644                    &mut draw_ranges,
5645                    GpuPrimitiveInstance::from_quad_instance(&query_val_alt, 0, active_layer_id),
5646                    active_clip,
5647                    phys_w,
5648                    phys_h,
5649                );
5650                image_fixups.push((prim_idx, img_idx));
5651            }
5652            DrawCommand::ExternalSurface { rect, radius } => {
5653                let snapped: Rect = snap_physical_rect(*rect, scale);
5654                if snapped.get_width() <= 0.0 || snapped.get_height() <= 0.0 {
5655                    continue;
5656                }
5657                let ext_quad: GpuQuadInstance = GpuQuadInstance {
5658                    rect: [
5659                        snapped.get_x(),
5660                        snapped.get_y(),
5661                        snapped.get_width(),
5662                        snapped.get_height(),
5663                    ],
5664                    clip: clip_arr,
5665                    color: [1.0, 1.0, 1.0, 1.0],
5666                    secondary_color: [0.0; 4],
5667                    radii: [
5668                        radius.get_top_left() * scale,
5669                        radius.get_top_right() * scale,
5670                        radius.get_bottom_right() * scale,
5671                        radius.get_bottom_left() * scale,
5672                    ],
5673                    stroke_or_blur: 0.0,
5674                    angle_rad: 0.0,
5675                    kind: GpuPrimitiveKind::ExternalSurface as u32,
5676                    reserved: 0,
5677                };
5678                push_direct_gpu_primitive(
5679                    &mut primitives,
5680                    &mut draw_ranges,
5681                    GpuPrimitiveInstance::from_quad_instance(&ext_quad, 3, active_layer_id),
5682                    active_clip,
5683                    phys_w,
5684                    phys_h,
5685                );
5686            }
5687            DrawCommand::Circle {
5688                center,
5689                radius,
5690                color,
5691            } => {
5692                let red_val: f32 = radius * scale;
5693                let pad: f32 = 1.5;
5694                let extent: f32 = red_val + pad;
5695                let query_val_inner: GpuQuadInstance = GpuQuadInstance {
5696                    rect: [
5697                        center.get_x() * scale - extent,
5698                        center.get_y() * scale - extent,
5699                        extent * 2.0,
5700                        extent * 2.0,
5701                    ],
5702                    clip: clip_arr,
5703                    color: color.to_f32_array(),
5704                    secondary_color: [0.0; 4],
5705                    radii: [red_val; 4],
5706                    stroke_or_blur: red_val,
5707                    angle_rad: 0.0,
5708                    kind: GpuPrimitiveKind::Circle as u32,
5709                    reserved: 0,
5710                };
5711                push_direct_gpu_primitive(
5712                    &mut primitives,
5713                    &mut draw_ranges,
5714                    GpuPrimitiveInstance::from_quad_instance(&query_val_inner, 0, active_layer_id),
5715                    active_clip,
5716                    phys_w,
5717                    phys_h,
5718                );
5719            }
5720            DrawCommand::Line {
5721                from,
5722                to,
5723                color,
5724                width,
5725            } => {
5726                let fx0: f32 = from.get_x() * scale;
5727                let fy0: f32 = from.get_y() * scale;
5728                let fx1: f32 = to.get_x() * scale;
5729                let fy1: f32 = to.get_y() * scale;
5730                let dx: f32 = fx1 - fx0;
5731                let dy: f32 = fy1 - fy0;
5732                let stroke_px: f32 = (width * scale).max(1.0);
5733                let pad: f32 = stroke_px * 0.5 + 1.5;
5734                let min_x: f32 = fx0.min(fx1) - pad;
5735                let min_y: f32 = fy0.min(fy1) - pad;
5736                let max_x: f32 = fx0.max(fx1) + pad;
5737                let max_y: f32 = fy0.max(fy1) + pad;
5738                let query_val_local: GpuQuadInstance = GpuQuadInstance {
5739                    rect: [
5740                        min_x,
5741                        min_y,
5742                        (max_x - min_x).max(2.0),
5743                        (max_y - min_y).max(2.0),
5744                    ],
5745                    clip: clip_arr,
5746                    color: color.to_f32_array(),
5747                    secondary_color: [0.0; 4],
5748                    radii: [fx0, fy0, fx1, fy1],
5749                    stroke_or_blur: stroke_px,
5750                    angle_rad: dy.atan2(dx),
5751                    kind: GpuPrimitiveKind::Line as u32,
5752                    reserved: 0,
5753                };
5754                push_direct_gpu_primitive(
5755                    &mut primitives,
5756                    &mut draw_ranges,
5757                    GpuPrimitiveInstance::from_quad_instance(&query_val_local, 0, active_layer_id),
5758                    active_clip,
5759                    phys_w,
5760                    phys_h,
5761                );
5762            }
5763            DrawCommand::Triangle { p0, p1, p2, color } => {
5764                let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.5;
5765                let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.5;
5766                let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.5;
5767                let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.5;
5768                let query_val_cur: GpuQuadInstance = GpuQuadInstance {
5769                    rect: [
5770                        min_x,
5771                        min_y,
5772                        (max_x - min_x).max(2.0),
5773                        (max_y - min_y).max(2.0),
5774                    ],
5775                    clip: clip_arr,
5776                    color: color.to_f32_array(),
5777                    secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
5778                    radii: [
5779                        p1.get_x() * scale,
5780                        p1.get_y() * scale,
5781                        p2.get_x() * scale,
5782                        p2.get_y() * scale,
5783                    ],
5784                    stroke_or_blur: 0.0,
5785                    angle_rad: 0.0,
5786                    kind: GpuPrimitiveKind::Triangle as u32,
5787                    reserved: 3,
5788                };
5789                push_direct_gpu_primitive(
5790                    &mut primitives,
5791                    &mut draw_ranges,
5792                    GpuPrimitiveInstance::from_quad_instance(&query_val_cur, 0, active_layer_id),
5793                    active_clip,
5794                    phys_w,
5795                    phys_h,
5796                );
5797            }
5798        }
5799        if active_rounded_bits != 0 && primitives.len() > cmd_prim_start {
5800            for prim_item in primitives[cmd_prim_start..].iter_mut() {
5801                let quad_rect: [f32; 4] = prim_item.get_rect();
5802                let safe_non_empty: bool =
5803                    safe_inner_clip.get_width() > 0.0 && safe_inner_clip.get_height() > 0.0;
5804                let inside_safe: bool = safe_non_empty
5805                    && quad_rect[0] >= safe_inner_clip.get_x()
5806                    && quad_rect[1] >= safe_inner_clip.get_y()
5807                    && (quad_rect[0] + quad_rect[2]) <= safe_inner_clip.right()
5808                    && (quad_rect[1] + quad_rect[3]) <= safe_inner_clip.bottom();
5809                if !inside_safe {
5810                    *prim_item = prim_item.with_rounded_clip_bits(active_rounded_bits);
5811                }
5812            }
5813        }
5814    }
5815    let mut glyph_r8_atlas: Option<DirectGpuAtlasUpload> = None;
5816    if let Some(atlas) = glyph_atlas.as_deref()
5817        && (!glyph_fixups.is_empty() || atlas.get_revision() != last_glyph_revision)
5818        && !atlas.is_empty()
5819    {
5820        let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
5821        let aw: u32 = packed.get_width();
5822        let ah: u32 = packed.get_height();
5823        for &(prim_idx, key) in glyph_fixups.iter() {
5824            if let Some(&(gx, gy, gw, gh)) = packed.get_regions().get(&key) {
5825                primitives[prim_idx].set_uv_rect(encode_atlas_uv_rect(aw, ah, gx, gy, gw, gh));
5826            }
5827        }
5828        if packed.get_revision() != last_glyph_revision {
5829            let rgba: &[u8] = packed.get_pixels().as_slice();
5830            let mut r8: Vec<u8> = Vec::with_capacity((aw as usize).saturating_mul(ah as usize));
5831            for px in rgba.as_chunks::<4>().0 {
5832                r8.push(px[3]);
5833            }
5834            glyph_r8_atlas = Some(DirectGpuAtlasUpload {
5835                width: aw,
5836                height: ah,
5837                revision: packed.get_revision(),
5838                pixels: r8,
5839            });
5840        }
5841    }
5842    let (image_rgba8_atlas, img_uvs): (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) =
5843        pack_frame_image_atlas(&image_entries, display_list.fast_hash());
5844    for &(prim_idx, img_idx) in image_fixups.iter() {
5845        if let Some(&uv) = img_uvs.get(img_idx) {
5846            primitives[prim_idx].set_uv_rect(uv);
5847        }
5848    }
5849    let glyph_bytes: usize = glyph_r8_atlas
5850        .as_ref()
5851        .map(|alpha_val: &DirectGpuAtlasUpload| alpha_val.get_pixels().len())
5852        .unwrap_or(0);
5853    let image_bytes: usize = image_rgba8_atlas
5854        .as_ref()
5855        .map(|first_val: &DirectGpuAtlasUpload| first_val.get_pixels().len())
5856        .unwrap_or(0);
5857    let instance_upload_bytes: usize = primitives
5858        .len()
5859        .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES)
5860        .saturating_add(glyph_bytes)
5861        .saturating_add(image_bytes);
5862    DirectGpuFrameBatch {
5863        viewport_width: phys_w,
5864        viewport_height: phys_h,
5865        clear_rgba,
5866        primitives,
5867        draw_ranges,
5868        backdrop_blurs,
5869        glyph_r8_atlas,
5870        image_rgba8_atlas,
5871        instance_upload_bytes,
5872        cpu_mirror_active: false,
5873        upload_strategy: MobileUploadStrategy::DirectGpu,
5874    }
5875}
5876
5877/// Returns the preferred native hardware `GraphicsBackend` for the active compilation target.
5878///
5879/// # Returns
5880///
5881/// - `GraphicsBackend` - Host-native GPU graphics backend (`Metal`, `Direct3D12`, `Vulkan`, `WebGl2`, or `Headless`).
5882#[must_use]
5883pub const fn default_native_gpu_backend() -> GraphicsBackend {
5884    #[cfg(any(target_os = "macos", target_os = "ios"))]
5885    {
5886        GraphicsBackend::Metal
5887    }
5888    #[cfg(target_os = "windows")]
5889    {
5890        GraphicsBackend::Direct3D12
5891    }
5892    #[cfg(any(target_os = "linux", target_os = "android"))]
5893    {
5894        GraphicsBackend::Vulkan
5895    }
5896    #[cfg(target_arch = "wasm32")]
5897    {
5898        GraphicsBackend::WebGl2
5899    }
5900    #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
5901    #[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
5902    {
5903        GraphicsBackend::Headless
5904    }
5905}
5906
5907/// Computes a deterministic 64-bit FNV-1a cache digest over a shader program's source pair and target GPU device label.
5908///
5909/// # Arguments
5910///
5911/// - `&str` - Probed GPU adapter or fallback device label.
5912/// - `&str` - Primary shader source string.
5913/// - `&str` - Optional secondary fragment shader source string.
5914///
5915/// # Returns
5916///
5917/// - `u64` - Deterministic 64-bit FNV-1a content key.
5918#[must_use]
5919pub fn shader_program_cache_hash(device_name: &str, primary_src: &str, secondary_src: &str) -> u64 {
5920    let mut hash: u64 = FNV1A_OFFSET_BASIS;
5921    for chunk in [
5922        device_name.as_bytes(),
5923        primary_src.as_bytes(),
5924        secondary_src.as_bytes(),
5925    ]
5926    .iter()
5927    {
5928        for &byte in chunk.iter() {
5929            hash ^= byte as u64;
5930            hash = hash.wrapping_mul(FNV1A_PRIME);
5931        }
5932    }
5933    hash
5934}
5935
5936/// Executes cold shader pipeline precompilation and optical LUT warm-up for `backend` without consulting the outer report cache.
5937///
5938/// # Arguments
5939///
5940/// - `GraphicsBackend` - Graphics API backend to precompile shaders for.
5941///
5942/// # Returns
5943///
5944/// - `ShaderPrecompileReport` - Measured compilation telemetry across all built-in shader programs.
5945fn run_shader_precompile_uncached(backend: GraphicsBackend) -> ShaderPrecompileReport {
5946    #[cfg(not(target_arch = "wasm32"))]
5947    let total_start: Instant = Instant::now();
5948    let _: Vec<u8> = build_aces_srgb_lut();
5949    let lang_label: &str = ShaderProgramId::language_for_backend(backend);
5950    #[cfg(any(target_os = "macos", target_os = "ios"))]
5951    if backend == GraphicsBackend::Metal {
5952        let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
5953        let device_name: String = cached.adapter.get_device_name().clone();
5954        let hardware_gpu: bool = cached.adapter.get_hardware_verified();
5955        let archive_enabled: bool = cached.binary_archive_enabled;
5956        let archive_hit: bool = cached.binary_archive_hit;
5957        let handles_and_us: [(ShaderProgramId, usize, u64); 4] = [
5958            (
5959                ShaderProgramId::UiUber,
5960                cached.pipeline,
5961                cached.ui_compile_us,
5962            ),
5963            (
5964                ShaderProgramId::BackdropBlur,
5965                if cached.blur_pipeline != 0 && cached.blur_up_pipeline != 0 {
5966                    cached.blur_pipeline
5967                } else {
5968                    0
5969                },
5970                cached.blur_compile_us,
5971            ),
5972            (
5973                ShaderProgramId::Engine3dPbr,
5974                cached.engine3d_pipeline,
5975                cached.engine3d_compile_us,
5976            ),
5977            (
5978                ShaderProgramId::FluidOceanOptical,
5979                cached.ocean_pipeline,
5980                cached.ocean_compile_us,
5981            ),
5982        ];
5983        let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(handles_and_us.len());
5984        let mut ready_count: usize = 0;
5985        let mut hw_compiled: usize = 0;
5986        for (program, pso_handle, compile_us) in handles_and_us {
5987            let (src_a, src_b): (&str, &str) = program.source_pair(backend);
5988            let src_bytes: usize = src_a.len().saturating_add(src_b.len());
5989            let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
5990            let state: ShaderCompileState = if pso_handle != 0 {
5991                hw_compiled += 1;
5992                ready_count += 1;
5993                if archive_hit {
5994                    ShaderCompileState::LoadedFromBinaryArchive
5995                } else {
5996                    ShaderCompileState::CompiledHardware
5997                }
5998            } else if !src_a.is_empty() {
5999                ready_count += 1;
6000                ShaderCompileState::ValidatedFallback
6001            } else {
6002                ShaderCompileState::Failed
6003            };
6004            entries.push(ShaderProgramCacheEntry {
6005                program,
6006                name: program.label().to_string(),
6007                language: lang_label.to_string(),
6008                state,
6009                source_hash: src_hash,
6010                source_bytes: src_bytes,
6011                compile_time_us: compile_us,
6012                pipeline_ready: state.is_ready(),
6013            });
6014        }
6015        let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
6016        let cold_us: u64 = cached.total_compile_us.max(elapsed_us);
6017        return ShaderPrecompileReport {
6018            backend,
6019            device_name,
6020            hardware_gpu,
6021            binary_archive_enabled: archive_enabled,
6022            binary_archive_hit: archive_hit,
6023            cache_hit: false,
6024            total_programs: entries.len(),
6025            ready_programs: ready_count,
6026            hardware_compiled_programs: hw_compiled,
6027            cold_compile_us: cold_us,
6028            last_call_us: elapsed_us,
6029            entries,
6030        };
6031    }
6032    let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
6033    let device_name: String = probed.adapter.get_device_name().clone();
6034    let hardware_gpu: bool = probed.adapter.get_hardware_verified();
6035    let hw_shader_ok: bool = probed.adapter.get_shader_compiled();
6036    let has_compiled_pso: bool = probed.device_handle != 0 && probed.pipeline_handle != 0;
6037    for handle in probed.scene_pbr_pipelines.iter() {
6038        release_native_gpu_object(*handle);
6039    }
6040    release_native_gpu_object(probed.dummy_r8_tex);
6041    release_native_gpu_object(probed.dummy_rgba8_tex);
6042    release_native_gpu_object(probed.ocean_pipeline_handle);
6043    release_native_gpu_object(probed.engine3d_pipeline_handle);
6044    release_native_gpu_object(probed.blur_up_pipeline_handle);
6045    release_native_gpu_object(probed.blur_pipeline_handle);
6046    release_native_gpu_object(probed.pipeline_handle);
6047    release_native_gpu_handles(
6048        probed.device_handle,
6049        probed.queue_handle,
6050        probed.library_handle,
6051    );
6052    let programs: [ShaderProgramId; 4] = ShaderProgramId::all();
6053    let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(programs.len());
6054    let mut ready_count: usize = 0;
6055    let mut hw_compiled: usize = 0;
6056    for program in programs {
6057        #[cfg(not(target_arch = "wasm32"))]
6058        let item_start: Instant = Instant::now();
6059        let (src_a, src_b): (&str, &str) = program.source_pair(backend);
6060        let src_bytes: usize = src_a.len().saturating_add(src_b.len());
6061        let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
6062        let is_valid: bool = !src_a.is_empty();
6063        let state: ShaderCompileState =
6064            if has_compiled_pso && hardware_gpu && hw_shader_ok && is_valid {
6065                hw_compiled += 1;
6066                ready_count += 1;
6067                ShaderCompileState::CompiledHardware
6068            } else if is_valid {
6069                ready_count += 1;
6070                ShaderCompileState::ValidatedFallback
6071            } else {
6072                ShaderCompileState::Failed
6073            };
6074        #[cfg(not(target_arch = "wasm32"))]
6075        let item_us: u64 = item_start.elapsed().as_micros() as u64;
6076        #[cfg(target_arch = "wasm32")]
6077        let item_us: u64 = 0;
6078        entries.push(ShaderProgramCacheEntry {
6079            program,
6080            name: program.label().to_string(),
6081            language: lang_label.to_string(),
6082            state,
6083            source_hash: src_hash,
6084            source_bytes: src_bytes,
6085            compile_time_us: item_us,
6086            pipeline_ready: state.is_ready(),
6087        });
6088    }
6089    #[cfg(not(target_arch = "wasm32"))]
6090    let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
6091    #[cfg(target_arch = "wasm32")]
6092    let elapsed_us: u64 = 0;
6093    ShaderPrecompileReport {
6094        backend,
6095        device_name,
6096        hardware_gpu,
6097        binary_archive_enabled: false,
6098        binary_archive_hit: false,
6099        cache_hit: false,
6100        total_programs: entries.len(),
6101        ready_programs: ready_count,
6102        hardware_compiled_programs: hw_compiled,
6103        cold_compile_us: elapsed_us,
6104        last_call_us: elapsed_us,
6105        entries,
6106    }
6107}
6108
6109/// Precompiles all built-in GPU shader programs (`UiUber`, `BackdropBlur`, `Engine3dPbr`, `FluidOceanOptical`) and warms optical LUTs for `backend`, returning cached results in `< 5 us` on subsequent calls.
6110///
6111/// # Arguments
6112///
6113/// - `GraphicsBackend` - Target graphics backend (`default_native_gpu_backend()` for active OS hardware).
6114///
6115/// # Returns
6116///
6117/// - `ShaderPrecompileReport` - Detailed precompilation status, cache-hit flag, and cold vs warm timing telemetry.
6118#[must_use]
6119pub fn precompile_shaders(backend: GraphicsBackend) -> ShaderPrecompileReport {
6120    #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
6121    {
6122        let call_start: Instant = Instant::now();
6123        let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
6124            SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
6125        if let Ok(guard) = cache_mutex.lock()
6126            && let Some(existing) = guard.get(&backend)
6127        {
6128            let mut hit_report: ShaderPrecompileReport = existing.clone();
6129            hit_report.set_cache_hit(true);
6130            hit_report.set_last_call_us(call_start.elapsed().as_micros() as u64);
6131            return hit_report;
6132        }
6133        let fresh: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
6134        if let Ok(mut guard) = cache_mutex.lock() {
6135            let _: Option<ShaderPrecompileReport> = guard.insert(backend, fresh.clone());
6136        }
6137        fresh
6138    }
6139    #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
6140    {
6141        run_shader_precompile_uncached(backend)
6142    }
6143}
6144
6145/// Launches non-blocking background-thread GPU shader precompilation for `backend` to eliminate 40-180ms cold-start main-thread frame hitches.
6146///
6147/// # Arguments
6148///
6149/// - `GraphicsBackend` - Target graphics backend to warm on a background worker thread.
6150pub fn precompile_shaders_async(backend: GraphicsBackend) {
6151    #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
6152    {
6153        let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
6154            SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
6155        if let Ok(guard) = cache_mutex.lock()
6156            && guard.contains_key(&backend)
6157        {
6158            return;
6159        }
6160        if SHADER_PRECOMPILE_IN_FLIGHT
6161            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
6162            .is_err()
6163        {
6164            return;
6165        }
6166        let spawn_result: io::Result<JoinHandle<()>> = Builder::new()
6167            .name("euv-shader-precompile".to_string())
6168            .spawn(move || {
6169                let _: ShaderPrecompileReport = precompile_shaders(backend);
6170                SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
6171            });
6172        if spawn_result.is_err() {
6173            SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
6174            let _: ShaderPrecompileReport = precompile_shaders(backend);
6175        }
6176    }
6177    #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
6178    {
6179        let _: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
6180    }
6181}
6182
6183/// Returns the latest cached `ShaderPrecompileReport` without triggering compilation if precompilation has not completed yet.
6184///
6185/// # Returns
6186///
6187/// - `Option<ShaderPrecompileReport>` - Cached precompile report prioritizing the active native GPU backend, or `None`.
6188#[must_use]
6189pub fn shader_precompile_status() -> Option<ShaderPrecompileReport> {
6190    #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
6191    {
6192        let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
6193            SHADER_PRECOMPILE_CACHE.get()?;
6194        let guard: MutexGuard<'_, HashMap<GraphicsBackend, ShaderPrecompileReport>> =
6195            cache_mutex.lock().ok()?;
6196        let native_backend: GraphicsBackend = default_native_gpu_backend();
6197        if let Some(native_report) = guard.get(&native_backend) {
6198            return Some(native_report.clone());
6199        }
6200        guard.values().next().cloned()
6201    }
6202    #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
6203    {
6204        None
6205    }
6206}
6207
6208/// Returns `true` while an asynchronous background shader precompilation worker thread is actively compiling PSOs.
6209///
6210/// # Returns
6211///
6212/// - `bool` - `true` when background precompilation is currently in flight.
6213#[must_use]
6214pub fn is_shader_precompile_in_flight() -> bool {
6215    #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
6216    {
6217        SHADER_PRECOMPILE_IN_FLIGHT.load(Ordering::Acquire)
6218    }
6219    #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
6220    {
6221        false
6222    }
6223}