1use super::*;
2
3#[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#[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 };
53 }
54 #[cfg(any(target_os = "macos", target_os = "ios"))]
55 {
56 if backend == GraphicsBackend::Metal {
57 probe_apple_metal_full(backend)
58 } else {
59 NativeGpuProbeOutput {
60 adapter: GpuAdapterInfo::new(
61 backend,
62 GPU_DEVICE_FALLBACK.to_string(),
63 false,
64 false,
65 ),
66 device_handle: 0,
67 queue_handle: 0,
68 library_handle: 0,
69 pipeline_handle: 0,
70 blur_pipeline_handle: 0,
71 blur_up_pipeline_handle: 0,
72 engine3d_pipeline_handle: 0,
73 ocean_pipeline_handle: 0,
74 scene_ocean_pipeline_handle: 0,
75 scene_boat_pipeline_handle: 0,
76 scene_3d_sky_pipeline_handle: 0,
77 scene_3d_mesh_pipeline_handle: 0,
78 scene_depth_stencil_handle: 0,
79 dummy_r8_tex: 0,
80 dummy_rgba8_tex: 0,
81 }
82 }
83 }
84 #[cfg(target_os = "windows")]
85 {
86 let (adapter, device_handle, queue_handle, library_handle): (
87 GpuAdapterInfo,
88 usize,
89 usize,
90 usize,
91 ) = probe_windows_d3d12(backend);
92 NativeGpuProbeOutput {
93 adapter,
94 device_handle,
95 queue_handle,
96 library_handle,
97 pipeline_handle: 0,
98 blur_pipeline_handle: 0,
99 blur_up_pipeline_handle: 0,
100 engine3d_pipeline_handle: 0,
101 ocean_pipeline_handle: 0,
102 scene_ocean_pipeline_handle: 0,
103 scene_boat_pipeline_handle: 0,
104 scene_3d_sky_pipeline_handle: 0,
105 scene_3d_mesh_pipeline_handle: 0,
106 scene_depth_stencil_handle: 0,
107 dummy_r8_tex: 0,
108 dummy_rgba8_tex: 0,
109 }
110 }
111 #[cfg(any(target_os = "linux", target_os = "android"))]
112 {
113 let (adapter, device_handle, queue_handle, library_handle): (
114 GpuAdapterInfo,
115 usize,
116 usize,
117 usize,
118 ) = probe_vulkan_runtime(backend);
119 NativeGpuProbeOutput {
120 adapter,
121 device_handle,
122 queue_handle,
123 library_handle,
124 pipeline_handle: 0,
125 blur_pipeline_handle: 0,
126 blur_up_pipeline_handle: 0,
127 engine3d_pipeline_handle: 0,
128 ocean_pipeline_handle: 0,
129 scene_ocean_pipeline_handle: 0,
130 scene_boat_pipeline_handle: 0,
131 scene_3d_sky_pipeline_handle: 0,
132 scene_3d_mesh_pipeline_handle: 0,
133 scene_depth_stencil_handle: 0,
134 dummy_r8_tex: 0,
135 dummy_rgba8_tex: 0,
136 }
137 }
138 #[cfg(target_arch = "wasm32")]
139 {
140 NativeGpuProbeOutput {
141 adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
142 device_handle: 0,
143 queue_handle: 0,
144 library_handle: 0,
145 pipeline_handle: 0,
146 blur_pipeline_handle: 0,
147 blur_up_pipeline_handle: 0,
148 engine3d_pipeline_handle: 0,
149 ocean_pipeline_handle: 0,
150 scene_ocean_pipeline_handle: 0,
151 scene_boat_pipeline_handle: 0,
152 scene_3d_sky_pipeline_handle: 0,
153 scene_3d_mesh_pipeline_handle: 0,
154 scene_depth_stencil_handle: 0,
155 dummy_r8_tex: 0,
156 dummy_rgba8_tex: 0,
157 }
158 }
159 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
160 #[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
161 {
162 NativeGpuProbeOutput {
163 adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
164 device_handle: 0,
165 queue_handle: 0,
166 library_handle: 0,
167 pipeline_handle: 0,
168 blur_pipeline_handle: 0,
169 blur_up_pipeline_handle: 0,
170 engine3d_pipeline_handle: 0,
171 ocean_pipeline_handle: 0,
172 scene_ocean_pipeline_handle: 0,
173 scene_boat_pipeline_handle: 0,
174 scene_3d_sky_pipeline_handle: 0,
175 scene_3d_mesh_pipeline_handle: 0,
176 scene_depth_stencil_handle: 0,
177 dummy_r8_tex: 0,
178 dummy_rgba8_tex: 0,
179 }
180 }
181}
182
183pub fn submit_native_gpu_batches(
195 device_handle: usize,
196 queue_handle: usize,
197 batches: &[GpuBatch],
198) -> usize {
199 #[cfg(any(target_os = "macos", target_os = "ios"))]
200 {
201 metal_submit_batches(device_handle, queue_handle, batches)
202 }
203 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
204 {
205 let _: (usize, usize) = (device_handle, queue_handle);
206 batches
207 .iter()
208 .map(|blue_val: &GpuBatch| {
209 blue_val
210 .get_primitives()
211 .len()
212 .max(blue_val.get_instances().len())
213 })
214 .sum()
215 }
216}
217
218pub(crate) fn submit_native_gpu_ring_frame(
232 driver: &mut NativeGpuDriver,
233 width: u32,
234 height: u32,
235 clear_color: Color,
236 batches: &[GpuBatch],
237) -> usize {
238 #[cfg(any(target_os = "macos", target_os = "ios"))]
239 {
240 metal_submit_ring_frame(driver, width, height, clear_color, batches)
241 }
242 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
243 {
244 let _: (&mut NativeGpuDriver, u32, u32, Color) = (driver, width, height, clear_color);
245 batches
246 .iter()
247 .map(|blue_val: &GpuBatch| {
248 blue_val
249 .get_primitives()
250 .len()
251 .max(blue_val.get_instances().len())
252 })
253 .sum()
254 }
255}
256
257pub(crate) fn execute_native_dual_kawase_blur_passes(
270 driver: &mut NativeGpuDriver,
271 width: u32,
272 height: u32,
273 blur_passes: &[GpuBackdropBlurPass],
274) -> usize {
275 if blur_passes.is_empty() || !driver.supports_backdrop_blur_pass() {
276 return 0;
277 }
278 #[cfg(any(target_os = "macos", target_os = "ios"))]
279 {
280 metal_execute_dual_kawase_blur_passes(driver, width, height, blur_passes)
281 }
282 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
283 {
284 let _: (&mut NativeGpuDriver, u32, u32) = (driver, width, height);
285 0
286 }
287}
288
289pub(crate) fn configure_native_metal_layer(device_handle: usize, layer_handle: usize) {
296 #[cfg(any(target_os = "macos", target_os = "ios"))]
297 {
298 metal_configure_layer(device_handle, layer_handle);
299 }
300 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
301 {
302 let _: (usize, usize) = (device_handle, layer_handle);
303 }
304}
305
306pub(crate) fn configure_native_metal_display_sync(layer_handle: usize, enabled: bool) {
313 #[cfg(any(target_os = "macos", target_os = "ios"))]
314 {
315 metal_set_layer_display_sync(layer_handle, enabled);
316 }
317 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
318 {
319 let _: (usize, bool) = (layer_handle, enabled);
320 }
321}
322
323pub(crate) fn upload_native_texture_dirty_rect(
339 device_handle: usize,
340 texture_handle: &mut usize,
341 format: GpuAtlasPixelFormat,
342 tex_dims: (u32, u32),
343 dirty_rect: (u32, u32, u32, u32),
344 bytes: &[u8],
345 bytes_per_row: usize,
346) -> bool {
347 #[cfg(any(target_os = "macos", target_os = "ios"))]
348 {
349 metal_upload_texture_dirty_rect(
350 device_handle,
351 texture_handle,
352 format,
353 tex_dims,
354 dirty_rect,
355 bytes,
356 bytes_per_row,
357 )
358 }
359 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
360 {
361 let _: usize = device_handle;
362 let _: &mut usize = texture_handle;
363 let _: GpuAtlasPixelFormat = format;
364 let _: (u32, u32) = tex_dims;
365 let _: (u32, u32, u32, u32) = dirty_rect;
366 let _: &[u8] = bytes;
367 let _: usize = bytes_per_row;
368 false
369 }
370}
371
372pub(crate) fn retain_native_gpu_object(handle: usize) -> usize {
382 #[cfg(any(target_os = "macos", target_os = "ios"))]
383 {
384 mtl_retain_handle(handle)
385 }
386 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
387 {
388 handle
389 }
390}
391
392pub(crate) fn release_native_gpu_object(handle: usize) {
398 #[cfg(any(target_os = "macos", target_os = "ios"))]
399 {
400 if handle != 0 {
401 let sel: &MetalSelectors = cached_metal_selectors();
402 mtl_send_void0(handle as *mut c_void, sel.release as *mut c_void);
403 }
404 }
405 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
406 {
407 let _: usize = handle;
408 }
409}
410
411pub fn release_native_gpu_handles(
419 device_handle: usize,
420 queue_handle: usize,
421 library_handle: usize,
422) {
423 #[cfg(any(target_os = "macos", target_os = "ios"))]
424 {
425 metal_release_handles(device_handle, queue_handle, library_handle);
426 }
427 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
428 {
429 let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
430 }
431}
432
433#[must_use]
439pub fn native_gpu_last_presented_ns() -> u64 {
440 #[cfg(any(target_os = "macos", target_os = "ios"))]
441 {
442 METAL_LAST_PRESENTED_NS.load(Ordering::Relaxed)
443 }
444 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
445 {
446 0
447 }
448}
449
450#[must_use]
456pub fn native_gpu_last_exec_ns() -> u64 {
457 #[cfg(any(target_os = "macos", target_os = "ios"))]
458 {
459 METAL_LAST_GPU_EXEC_NS.load(Ordering::Relaxed)
460 }
461 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
462 {
463 0
464 }
465}
466
467#[cfg(any(target_os = "macos", target_os = "ios"))]
468#[link(name = "Metal", kind = "framework")]
469unsafe extern "C" {
470 fn MTLCreateSystemDefaultDevice() -> *mut c_void;
476}
477
478#[cfg(any(target_os = "macos", target_os = "ios"))]
479#[link(name = "objc")]
480unsafe extern "C" {
481 fn objc_getClass(name: *const c_char) -> *mut c_void;
491 fn sel_registerName(name: *const c_char) -> *mut c_void;
501 pub(crate) fn objc_autoreleasePoolPush() -> *mut c_void;
507 pub(crate) fn objc_autoreleasePoolPop(pool: *mut c_void);
513 pub(crate) fn objc_msgSend();
515}
516
517#[cfg(any(target_os = "macos", target_os = "ios"))]
518unsafe extern "C" {
519 pub(crate) static _NSConcreteGlobalBlock: c_void;
521}
522
523#[cfg(any(target_os = "macos", target_os = "ios"))]
533pub(crate) fn mtl_sel_cstr(name: &'static str) -> *mut c_void {
534 unsafe { sel_registerName(name.as_ptr().cast::<c_char>()) }
535}
536
537#[cfg(any(target_os = "macos", target_os = "ios"))]
547pub(crate) fn mtl_cls_cstr(name: &'static str) -> *mut c_void {
548 unsafe { objc_getClass(name.as_ptr().cast::<c_char>()) }
549}
550
551#[cfg(any(target_os = "macos", target_os = "ios"))]
561pub(crate) fn mtl_ns_string(text: &str) -> *mut c_void {
562 let Ok(c_text) = CString::new(text) else {
563 return null_mut();
564 };
565 unsafe {
566 let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_STRING);
567 if cls.is_null() {
568 return null_mut();
569 }
570 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
571 transmute(objc_msgSend as *const c_void);
572 send(cls, mtl_sel_cstr(MTL_SEL_STRING_UTF8), c_text.as_ptr())
573 }
574}
575
576#[cfg(any(target_os = "macos", target_os = "ios"))]
587pub(crate) fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
588 if obj.is_null() || sel.is_null() {
589 return null_mut();
590 }
591 unsafe {
592 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
593 transmute(objc_msgSend as *const c_void);
594 send(obj, sel)
595 }
596}
597
598#[cfg(any(target_os = "macos", target_os = "ios"))]
610pub(crate) fn mtl_send_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) -> *mut c_void {
611 if obj.is_null() || sel.is_null() {
612 return null_mut();
613 }
614 unsafe {
615 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
616 transmute(objc_msgSend as *const c_void);
617 send(obj, sel, arg0)
618 }
619}
620
621#[cfg(any(target_os = "macos", target_os = "ios"))]
628pub(crate) fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
629 if obj.is_null() || sel.is_null() {
630 return;
631 }
632 unsafe {
633 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
634 transmute(objc_msgSend as *const c_void);
635 send(obj, sel);
636 }
637}
638
639#[cfg(any(target_os = "macos", target_os = "ios"))]
647pub(crate) fn mtl_send_void_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) {
648 if obj.is_null() || sel.is_null() {
649 return;
650 }
651 unsafe {
652 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
653 transmute(objc_msgSend as *const c_void);
654 send(obj, sel, arg0);
655 }
656}
657
658#[cfg(any(target_os = "macos", target_os = "ios"))]
666pub(crate) fn mtl_send_void_usize(obj: *mut c_void, sel: *mut c_void, val: usize) {
667 if obj.is_null() || sel.is_null() {
668 return;
669 }
670 unsafe {
671 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) =
672 transmute(objc_msgSend as *const c_void);
673 send(obj, sel, val);
674 }
675}
676
677#[cfg(any(target_os = "macos", target_os = "ios"))]
685pub(crate) fn mtl_send_void_bool(obj: *mut c_void, sel: *mut c_void, val: bool) {
686 if obj.is_null() || sel.is_null() {
687 return;
688 }
689 unsafe {
690 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
691 transmute(objc_msgSend as *const c_void);
692 send(obj, sel, if val { 1 } else { 0 });
693 }
694}
695
696#[cfg(any(target_os = "macos", target_os = "ios"))]
707pub(crate) fn mtl_send_usize0(obj: *mut c_void, sel: *mut c_void) -> usize {
708 if obj.is_null() || sel.is_null() {
709 return 0;
710 }
711 unsafe {
712 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
713 transmute(objc_msgSend as *const c_void);
714 send(obj, sel)
715 }
716}
717
718#[cfg(any(target_os = "macos", target_os = "ios"))]
729pub(crate) fn mtl_send_f64_0(obj: *mut c_void, sel: *mut c_void) -> f64 {
730 if obj.is_null() || sel.is_null() {
731 return 0.0;
732 }
733 unsafe {
734 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> f64 =
735 transmute(objc_msgSend as *const c_void);
736 send(obj, sel)
737 }
738}
739
740#[cfg(any(target_os = "macos", target_os = "ios"))]
751pub(crate) fn mtl_responds_to_sel(obj: *mut c_void, sel: *mut c_void) -> bool {
752 if obj.is_null() || sel.is_null() {
753 return false;
754 }
755 let responds_sel: *mut c_void = cached_metal_selectors().responds_to_sel as *mut c_void;
756 unsafe {
757 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i8 =
758 transmute(objc_msgSend as *const c_void);
759 send(obj, responds_sel, sel) != 0
760 }
761}
762
763#[cfg(any(target_os = "macos", target_os = "ios"))]
773pub(crate) fn mtl_retain_handle(handle: usize) -> usize {
774 if handle == 0 {
775 return 0;
776 }
777 let sel_retain: *mut c_void = cached_metal_selectors().retain as *mut c_void;
778 mtl_send_ptr0(handle as *mut c_void, sel_retain) as usize
779}
780
781#[cfg(all(any(target_os = "macos", target_os = "ios"), not(target_abi = "sim")))]
788unsafe extern "C" fn metal_presented_handler_invoke(_block: *mut c_void, drawable: *mut c_void) {
789 if drawable.is_null() {
790 return;
791 }
792 let sel: &MetalSelectors = cached_metal_selectors();
793 let presented_secs: f64 = mtl_send_f64_0(drawable, sel.presented_time as *mut c_void);
794 if presented_secs.is_finite() && presented_secs > 0.0 {
795 let ns: u64 = (presented_secs * 1_000_000_000.0).round() as u64;
796 METAL_LAST_PRESENTED_NS.store(ns, Ordering::Relaxed);
797 }
798}
799
800#[cfg(any(target_os = "macos", target_os = "ios"))]
807unsafe extern "C" fn metal_completed_handler_invoke(_block: *mut c_void, cmd_buf: *mut c_void) {
808 if cmd_buf.is_null() {
809 return;
810 }
811 let sel: &MetalSelectors = cached_metal_selectors();
812 let start_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_start_time as *mut c_void);
813 let end_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_end_time as *mut c_void);
814 if start_s.is_finite() && end_s.is_finite() && end_s >= start_s {
815 let exec_ns: u64 = ((end_s - start_s) * 1_000_000_000.0).round() as u64;
816 METAL_LAST_GPU_EXEC_NS.store(exec_ns, Ordering::Relaxed);
817 LAST_GPU_RENDER_NS.store(exec_ns, Ordering::Relaxed);
818 }
819 let _: u64 = COMPLETED_GPU_FENCE.fetch_add(1, Ordering::Release);
820}
821
822#[cfg(all(any(target_os = "macos", target_os = "ios"), not(target_abi = "sim")))]
828fn metal_presented_block_ptr() -> *mut c_void {
829 let addr: usize = *METAL_PRESENTED_BLOCK_ADDR.get_or_init(|| {
830 let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
831 isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
832 flags: OBJC_BLOCK_IS_GLOBAL,
833 reserved: 0,
834 invoke: metal_presented_handler_invoke,
835 descriptor: &METAL_BLOCK_DESCRIPTOR,
836 });
837 Box::into_raw(block) as usize
838 });
839 addr as *mut c_void
840}
841
842#[cfg(any(target_os = "macos", target_os = "ios"))]
848fn metal_completed_block_ptr() -> *mut c_void {
849 let addr: usize = *METAL_COMPLETED_BLOCK_ADDR.get_or_init(|| {
850 let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
851 isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
852 flags: OBJC_BLOCK_IS_GLOBAL,
853 reserved: 0,
854 invoke: metal_completed_handler_invoke,
855 descriptor: &METAL_BLOCK_DESCRIPTOR,
856 });
857 Box::into_raw(block) as usize
858 });
859 addr as *mut c_void
860}
861
862#[cfg(any(target_os = "macos", target_os = "ios"))]
872fn metal_pipeline_cache_hash(device_name: &str) -> u64 {
873 let mut hash: u64 = FNV1A_OFFSET_BASIS;
874 for chunk in [
875 device_name.as_bytes(),
876 MSL_UI_SHADER.as_bytes(),
877 MSL_BACKDROP_BLUR_SHADER.as_bytes(),
878 MSL_ENGINE3D_PBR_SHADER.as_bytes(),
879 MSL_FLUID_OCEAN_SHADER.as_bytes(),
880 MSL_GPU_SCENE_SHADER.as_bytes(),
881 ]
882 .iter()
883 {
884 for &byte in chunk.iter() {
885 hash ^= byte as u64;
886 hash = hash.wrapping_mul(FNV1A_PRIME);
887 }
888 }
889 hash
890}
891
892#[cfg(any(target_os = "macos", target_os = "ios"))]
905fn metal_create_texture(
906 device: *mut c_void,
907 format: GpuAtlasPixelFormat,
908 width: u32,
909 height: u32,
910) -> usize {
911 if device.is_null() {
912 return 0;
913 }
914 let px_fmt: usize = match format {
915 GpuAtlasPixelFormat::R8Unorm => MTL_PIXEL_FORMAT_R8_UNORM,
916 GpuAtlasPixelFormat::Rgba8Unorm => MTL_PIXEL_FORMAT_RGBA8_UNORM,
917 };
918 let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
919 if cls_desc.is_null() {
920 return 0;
921 }
922 unsafe {
923 let send_desc: unsafe extern "C" fn(
924 *mut c_void,
925 *mut c_void,
926 usize,
927 usize,
928 usize,
929 i8,
930 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
931 let desc: *mut c_void = send_desc(
932 cls_desc,
933 mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
934 px_fmt,
935 width.max(1) as usize,
936 height.max(1) as usize,
937 0,
938 );
939 if desc.is_null() {
940 return 0;
941 }
942 mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
943 let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
944 tex as usize
945 }
946}
947
948#[cfg(any(target_os = "macos", target_os = "ios"))]
963fn metal_build_render_pipeline(
964 device: *mut c_void,
965 library: *mut c_void,
966 vs_name: &str,
967 fs_name: &str,
968 archive: *mut c_void,
969 enable_blend: bool,
970) -> (usize, bool) {
971 metal_build_render_pipeline_with_depth(
972 device,
973 library,
974 vs_name,
975 fs_name,
976 archive,
977 enable_blend,
978 0,
979 )
980}
981
982#[cfg(any(target_os = "macos", target_os = "ios"))]
998fn metal_build_render_pipeline_with_depth(
999 device: *mut c_void,
1000 library: *mut c_void,
1001 vs_name: &str,
1002 fs_name: &str,
1003 archive: *mut c_void,
1004 enable_blend: bool,
1005 depth_pixel_format: usize,
1006) -> (usize, bool) {
1007 if device.is_null() || library.is_null() {
1008 return (0, false);
1009 }
1010 let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
1011 let vs_fn: *mut c_void = mtl_send_ptr1(
1012 library,
1013 mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1014 mtl_ns_string(vs_name),
1015 );
1016 let fs_fn: *mut c_void = mtl_send_ptr1(
1017 library,
1018 mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1019 mtl_ns_string(fs_name),
1020 );
1021 let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
1022 if !functions_ok {
1023 if !vs_fn.is_null() {
1024 mtl_send_void0(vs_fn, sel_rel);
1025 }
1026 if !fs_fn.is_null() {
1027 mtl_send_void0(fs_fn, sel_rel);
1028 }
1029 return (0, false);
1030 }
1031 let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
1032 let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1033 let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1034 if desc.is_null() {
1035 mtl_send_void0(vs_fn, sel_rel);
1036 mtl_send_void0(fs_fn, sel_rel);
1037 return (0, functions_ok);
1038 }
1039 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
1040 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
1041 let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
1042 let att0: *mut c_void = unsafe {
1043 let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1044 transmute(objc_msgSend as *const c_void);
1045 send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
1046 };
1047 if !att0.is_null() {
1048 mtl_send_void_usize(
1049 att0,
1050 mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1051 MTL_PIXEL_FORMAT_BGRA8_UNORM,
1052 );
1053 if enable_blend {
1054 mtl_send_void_bool(att0, mtl_sel_cstr(MTL_SEL_SET_BLENDING_ENABLED), true);
1055 mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_RGB_BLEND_OP), 0);
1056 mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_ALPHA_BLEND_OP), 0);
1057 mtl_send_void_usize(
1058 att0,
1059 mtl_sel_cstr(MTL_SEL_SET_SRC_RGB_BLEND),
1060 MTL_BLEND_FACTOR_SRC_ALPHA,
1061 );
1062 mtl_send_void_usize(
1063 att0,
1064 mtl_sel_cstr(MTL_SEL_SET_DST_RGB_BLEND),
1065 MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
1066 );
1067 mtl_send_void_usize(
1068 att0,
1069 mtl_sel_cstr(MTL_SEL_SET_SRC_ALPHA_BLEND),
1070 MTL_BLEND_FACTOR_ONE,
1071 );
1072 mtl_send_void_usize(
1073 att0,
1074 mtl_sel_cstr(MTL_SEL_SET_DST_ALPHA_BLEND),
1075 MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
1076 );
1077 }
1078 }
1079 if depth_pixel_format != 0 {
1080 mtl_send_void_usize(
1081 desc,
1082 mtl_sel_cstr(MTL_SEL_SET_DEPTH_ATTACHMENT_PIXEL_FORMAT),
1083 depth_pixel_format,
1084 );
1085 }
1086 if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
1087 let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
1088 let arr: *mut c_void =
1089 mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
1090 if !arr.is_null() {
1091 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
1092 }
1093 }
1094 let mut err_ptr: *mut c_void = null_mut();
1095 let pipeline: *mut c_void = unsafe {
1096 let send_pso: unsafe extern "C" fn(
1097 *mut c_void,
1098 *mut c_void,
1099 *mut c_void,
1100 *mut *mut c_void,
1101 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1102 send_pso(
1103 device,
1104 mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
1105 desc,
1106 &mut err_ptr,
1107 )
1108 };
1109 if !archive.is_null() && !pipeline.is_null() {
1110 let mut add_err: *mut c_void = null_mut();
1111 unsafe {
1112 let send_add: unsafe extern "C" fn(
1113 *mut c_void,
1114 *mut c_void,
1115 *mut c_void,
1116 *mut *mut c_void,
1117 ) -> i8 = transmute(objc_msgSend as *const c_void);
1118 let _: i8 = send_add(
1119 archive,
1120 mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
1121 desc,
1122 &mut add_err,
1123 );
1124 }
1125 }
1126 mtl_send_void0(desc, sel_rel);
1127 mtl_send_void0(vs_fn, sel_rel);
1128 mtl_send_void0(fs_fn, sel_rel);
1129 (pipeline as usize, functions_ok)
1130}
1131
1132#[cfg(any(target_os = "macos", target_os = "ios"))]
1144fn metal_build_render_pipeline_3d(
1145 device: *mut c_void,
1146 library: *mut c_void,
1147 archive: *mut c_void,
1148) -> (usize, bool) {
1149 if device.is_null() || library.is_null() {
1150 return (0, false);
1151 }
1152 let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
1153 let vs_fn: *mut c_void = mtl_send_ptr1(
1154 library,
1155 mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1156 mtl_ns_string(MTL_FN_3D_VERTEX),
1157 );
1158 let fs_fn: *mut c_void = mtl_send_ptr1(
1159 library,
1160 mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1161 mtl_ns_string(MTL_FN_3D_FRAGMENT),
1162 );
1163 let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
1164 if !functions_ok {
1165 if !vs_fn.is_null() {
1166 mtl_send_void0(vs_fn, sel_rel);
1167 }
1168 if !fs_fn.is_null() {
1169 mtl_send_void0(fs_fn, sel_rel);
1170 }
1171 return (0, false);
1172 }
1173 let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
1174 let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1175 let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1176 if desc.is_null() {
1177 mtl_send_void0(vs_fn, sel_rel);
1178 mtl_send_void0(fs_fn, sel_rel);
1179 return (0, functions_ok);
1180 }
1181 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
1182 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
1183 let vdesc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_VERTEX_DESC);
1184 let vdesc_alloc: *mut c_void = mtl_send_ptr0(vdesc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1185 let vdesc: *mut c_void = mtl_send_ptr0(vdesc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1186 if !vdesc.is_null() {
1187 let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1188 unsafe { transmute(objc_msgSend as *const c_void) };
1189 let sel_idx: *mut c_void = mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX);
1190 let attrs: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_ATTRIBUTES));
1191 let attr0: *mut c_void = unsafe { send_idx(attrs, sel_idx, 0) };
1192 let attr1: *mut c_void = unsafe { send_idx(attrs, sel_idx, 1) };
1193 if !attr0.is_null() {
1194 mtl_send_void_usize(
1195 attr0,
1196 mtl_sel_cstr(MTL_SEL_SET_FORMAT),
1197 MTL_VERTEX_FORMAT_FLOAT3,
1198 );
1199 mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 0);
1200 mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
1201 }
1202 if !attr1.is_null() {
1203 mtl_send_void_usize(
1204 attr1,
1205 mtl_sel_cstr(MTL_SEL_SET_FORMAT),
1206 MTL_VERTEX_FORMAT_FLOAT3,
1207 );
1208 mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 12);
1209 mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
1210 }
1211 let layouts: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_LAYOUTS));
1212 let layout2: *mut c_void = unsafe { send_idx(layouts, sel_idx, 2) };
1213 if !layout2.is_null() {
1214 mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STRIDE), 24);
1215 mtl_send_void_usize(
1216 layout2,
1217 mtl_sel_cstr(MTL_SEL_SET_STEP_FUNCTION),
1218 MTL_VERTEX_STEP_PER_VERTEX,
1219 );
1220 mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STEP_RATE), 1);
1221 }
1222 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_DESC), vdesc);
1223 mtl_send_void0(vdesc, sel_rel);
1224 }
1225 let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
1226 let att0: *mut c_void = unsafe {
1227 let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1228 transmute(objc_msgSend as *const c_void);
1229 send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
1230 };
1231 if !att0.is_null() {
1232 mtl_send_void_usize(
1233 att0,
1234 mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1235 MTL_PIXEL_FORMAT_BGRA8_UNORM,
1236 );
1237 }
1238 if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
1239 let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
1240 let arr: *mut c_void =
1241 mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
1242 if !arr.is_null() {
1243 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
1244 }
1245 }
1246 let mut err_ptr: *mut c_void = null_mut();
1247 let pipeline: *mut c_void = unsafe {
1248 let send_pso: unsafe extern "C" fn(
1249 *mut c_void,
1250 *mut c_void,
1251 *mut c_void,
1252 *mut *mut c_void,
1253 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1254 send_pso(
1255 device,
1256 mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
1257 desc,
1258 &mut err_ptr,
1259 )
1260 };
1261 if !archive.is_null() && !pipeline.is_null() {
1262 let mut add_err: *mut c_void = null_mut();
1263 unsafe {
1264 let send_add: unsafe extern "C" fn(
1265 *mut c_void,
1266 *mut c_void,
1267 *mut c_void,
1268 *mut *mut c_void,
1269 ) -> i8 = transmute(objc_msgSend as *const c_void);
1270 let _: i8 = send_add(
1271 archive,
1272 mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
1273 desc,
1274 &mut add_err,
1275 );
1276 }
1277 }
1278 mtl_send_void0(desc, sel_rel);
1279 mtl_send_void0(vs_fn, sel_rel);
1280 mtl_send_void0(fs_fn, sel_rel);
1281 (pipeline as usize, functions_ok)
1282}
1283
1284#[cfg(any(target_os = "macos", target_os = "ios"))]
1294fn metal_create_depth_stencil_state(device: *mut c_void) -> usize {
1295 if device.is_null() {
1296 return 0;
1297 }
1298 let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_DEPTH_STENCIL_DESC);
1299 if cls.is_null() {
1300 return 0;
1301 }
1302 let alloc: *mut c_void = mtl_send_ptr0(cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1303 let desc: *mut c_void = mtl_send_ptr0(alloc, mtl_sel_cstr(MTL_SEL_INIT));
1304 if desc.is_null() {
1305 return 0;
1306 }
1307 mtl_send_void_usize(
1308 desc,
1309 mtl_sel_cstr(MTL_SEL_SET_DEPTH_COMPARE_FN),
1310 MTL_COMPARE_FUNC_LESS,
1311 );
1312 mtl_send_void_bool(desc, mtl_sel_cstr(MTL_SEL_SET_DEPTH_WRITE_ENABLED), true);
1313 let state: *mut c_void =
1314 mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_DEPTH_STENCIL_STATE), desc);
1315 mtl_send_void0(desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1316 state as usize
1317}
1318
1319#[cfg(any(target_os = "macos", target_os = "ios"))]
1331fn metal_create_depth_texture(device: *mut c_void, width: u32, height: u32) -> usize {
1332 if device.is_null() {
1333 return 0;
1334 }
1335 let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
1336 if cls_desc.is_null() {
1337 return 0;
1338 }
1339 unsafe {
1340 let send_desc: unsafe extern "C" fn(
1341 *mut c_void,
1342 *mut c_void,
1343 usize,
1344 usize,
1345 usize,
1346 bool,
1347 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1348 let desc: *mut c_void = send_desc(
1349 cls_desc,
1350 mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
1351 MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1352 width.max(1) as usize,
1353 height.max(1) as usize,
1354 false,
1355 );
1356 if desc.is_null() {
1357 return 0;
1358 }
1359 mtl_send_void_usize(
1360 desc,
1361 mtl_sel_cstr(MTL_SEL_SET_USAGE),
1362 MTL_TEX_USAGE_RENDER_TARGET_GPU,
1363 );
1364 mtl_send_void_usize(
1365 desc,
1366 mtl_sel_cstr(MTL_SEL_SET_STORAGE_MODE_GPU),
1367 MTL_STORAGE_MODE_PRIVATE_GPU,
1368 );
1369 mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc) as usize
1370 }
1371}
1372
1373#[cfg(any(target_os = "macos", target_os = "ios"))]
1386fn metal_ensure_and_upload_shared_buffer(
1387 device: *mut c_void,
1388 buf_handle: &mut usize,
1389 buf_capacity: &mut usize,
1390 bytes: &[u8],
1391) -> *mut c_void {
1392 if device.is_null() || bytes.is_empty() {
1393 return *buf_handle as *mut c_void;
1394 }
1395 let sel: &MetalSelectors = cached_metal_selectors();
1396 if *buf_handle == 0 || *buf_capacity < bytes.len() {
1397 if *buf_handle != 0 {
1398 mtl_send_void0(*buf_handle as *mut c_void, sel.release as *mut c_void);
1399 *buf_handle = 0;
1400 *buf_capacity = 0;
1401 }
1402 let alloc_bytes: usize = bytes.len().max(1024).next_power_of_two();
1403 unsafe {
1404 let send_new_len: unsafe extern "C" fn(
1405 *mut c_void,
1406 *mut c_void,
1407 usize,
1408 usize,
1409 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1410 let new_buf: *mut c_void = send_new_len(
1411 device,
1412 sel.new_buffer_with_length as *mut c_void,
1413 alloc_bytes,
1414 0,
1415 );
1416 if !new_buf.is_null() {
1417 *buf_handle = new_buf as usize;
1418 *buf_capacity = alloc_bytes;
1419 }
1420 }
1421 }
1422 if *buf_handle == 0 {
1423 return null_mut();
1424 }
1425 let ptr: *mut c_void = mtl_send_ptr0(*buf_handle as *mut c_void, sel.contents as *mut c_void);
1426 if !ptr.is_null() {
1427 unsafe {
1428 ptr.cast::<u8>()
1429 .copy_from_nonoverlapping(bytes.as_ptr(), bytes.len());
1430 }
1431 }
1432 *buf_handle as *mut c_void
1433}
1434
1435#[must_use]
1446pub fn metal_binary_archive_allowed(device_name: &str, is_simulator: bool) -> bool {
1447 if is_simulator {
1448 return false;
1449 }
1450 let lower: String = device_name.to_ascii_lowercase();
1451 !lower.contains(MTL_SIMULATOR_TOKEN) && !lower.contains(MTL_VIRTUAL_TOKEN)
1452}
1453
1454#[cfg(any(target_os = "macos", target_os = "ios"))]
1465fn metal_open_binary_archive(
1466 device: *mut c_void,
1467 device_name: &str,
1468) -> (*mut c_void, *mut c_void, bool) {
1469 if !metal_binary_archive_allowed(device_name, cfg!(target_abi = "sim"))
1470 || !mtl_responds_to_sel(device, mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE))
1471 {
1472 return (null_mut(), null_mut(), false);
1473 }
1474 let arch_desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_BINARY_ARCHIVE_DESC);
1475 if arch_desc_cls.is_null() {
1476 return (null_mut(), null_mut(), false);
1477 }
1478 let cache_hash: u64 = metal_pipeline_cache_hash(device_name);
1479 let archive_path: String = env::temp_dir()
1480 .join(format!(
1481 "{MTL_ARCHIVE_FILE_PREFIX}{cache_hash:016x}{MTL_ARCHIVE_FILE_SUFFIX}"
1482 ))
1483 .to_string_lossy()
1484 .into_owned();
1485 let existed: bool = fs::metadata(&archive_path).is_ok();
1486 let ns_path: *mut c_void = mtl_ns_string(&archive_path);
1487 let url_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_URL);
1488 let ns_url: *mut c_void =
1489 mtl_send_ptr1(url_cls, mtl_sel_cstr(MTL_SEL_FILE_URL_WITH_PATH), ns_path);
1490 let arch_desc_alloc: *mut c_void = mtl_send_ptr0(arch_desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1491 let arch_desc: *mut c_void = mtl_send_ptr0(arch_desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1492 if arch_desc.is_null() {
1493 return (null_mut(), ns_url, existed);
1494 }
1495 if existed && !ns_url.is_null() {
1496 mtl_send_void_ptr1(arch_desc, mtl_sel_cstr(MTL_SEL_SET_URL), ns_url);
1497 }
1498 let mut err_ptr: *mut c_void = null_mut();
1499 let archive: *mut c_void = unsafe {
1500 let send_new: unsafe extern "C" fn(
1501 *mut c_void,
1502 *mut c_void,
1503 *mut c_void,
1504 *mut *mut c_void,
1505 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1506 send_new(
1507 device,
1508 mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE),
1509 arch_desc,
1510 &mut err_ptr,
1511 )
1512 };
1513 mtl_send_void0(arch_desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1514 (archive, ns_url, existed)
1515}
1516
1517#[cfg(any(target_os = "macos", target_os = "ios"))]
1527pub(crate) fn init_apple_metal_shared_cache(
1528 backend: GraphicsBackend,
1529) -> &'static MetalSharedPipelineCache {
1530 METAL_SHARED_PIPELINE.get_or_init(|| {
1531 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1532 let total_start: Instant = Instant::now();
1533 let result: MetalSharedPipelineCache = unsafe {
1534 let device: *mut c_void = MTLCreateSystemDefaultDevice();
1535 if device.is_null() {
1536 MetalSharedPipelineCache {
1537 adapter: GpuAdapterInfo::new(
1538 backend,
1539 GPU_DEVICE_FALLBACK.to_string(),
1540 false,
1541 false,
1542 ),
1543 device: 0,
1544 queue: 0,
1545 library: 0,
1546 pipeline: 0,
1547 blur_pipeline: 0,
1548 blur_up_pipeline: 0,
1549 engine3d_pipeline: 0,
1550 ocean_pipeline: 0,
1551 scene_ocean_pipeline: 0,
1552 scene_boat_pipeline: 0,
1553 scene_3d_sky_pipeline: 0,
1554 scene_3d_mesh_pipeline: 0,
1555 scene_depth_stencil: 0,
1556 binary_archive_enabled: false,
1557 binary_archive_hit: false,
1558 ui_compile_us: 0,
1559 blur_compile_us: 0,
1560 engine3d_compile_us: 0,
1561 ocean_compile_us: 0,
1562 total_compile_us: 0,
1563 dummy_r8_tex: 0,
1564 dummy_rgba8_tex: 0,
1565 }
1566 } else {
1567 let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NAME));
1568 let utf8_ptr: *const c_char =
1569 mtl_send_ptr0(ns_name, mtl_sel_cstr(MTL_SEL_UTF8_STRING)).cast::<c_char>();
1570 let device_name: String = if utf8_ptr.is_null() {
1571 GPU_DEVICE_APPLE_METAL.to_string()
1572 } else {
1573 CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
1574 };
1575 let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NEW_CMD_QUEUE));
1576 let (archive, archive_url, archive_existed): (*mut c_void, *mut c_void, bool) =
1577 metal_open_binary_archive(device, &device_name);
1578 let archive_enabled: bool = !archive.is_null();
1579 let send_lib: unsafe extern "C" fn(
1580 *mut c_void,
1581 *mut c_void,
1582 *mut c_void,
1583 *mut c_void,
1584 *mut *mut c_void,
1585 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1586 let ui_start: Instant = Instant::now();
1587 let mut err_ptr: *mut c_void = null_mut();
1588 let library: *mut c_void = send_lib(
1589 device,
1590 mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1591 mtl_ns_string(MSL_UI_SHADER),
1592 null_mut(),
1593 &mut err_ptr,
1594 );
1595 let (pipeline, ui_fns_ok): (usize, bool) = metal_build_render_pipeline(
1596 device,
1597 library,
1598 MTL_FN_VERTEX,
1599 MTL_FN_FRAGMENT,
1600 archive,
1601 true,
1602 );
1603 let ui_compile_us: u64 = ui_start.elapsed().as_micros() as u64;
1604 let blur_start: Instant = Instant::now();
1605 let mut blur_err: *mut c_void = null_mut();
1606 let blur_lib: *mut c_void = send_lib(
1607 device,
1608 mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1609 mtl_ns_string(MSL_BACKDROP_BLUR_SHADER),
1610 null_mut(),
1611 &mut blur_err,
1612 );
1613 let (blur_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1614 device,
1615 blur_lib,
1616 MTL_FN_BLUR_VERTEX,
1617 MTL_FN_BLUR_DOWN,
1618 archive,
1619 false,
1620 );
1621 let (blur_up_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1622 device,
1623 blur_lib,
1624 MTL_FN_BLUR_VERTEX,
1625 MTL_FN_BLUR_UP,
1626 archive,
1627 false,
1628 );
1629 if !blur_lib.is_null() {
1630 mtl_send_void0(blur_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1631 }
1632 let blur_compile_us: u64 = blur_start.elapsed().as_micros() as u64;
1633 let pbr_start: Instant = Instant::now();
1634 let mut pbr_err: *mut c_void = null_mut();
1635 let pbr_lib: *mut c_void = send_lib(
1636 device,
1637 mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1638 mtl_ns_string(MSL_ENGINE3D_PBR_SHADER),
1639 null_mut(),
1640 &mut pbr_err,
1641 );
1642 let (engine3d_pipeline, _): (usize, bool) =
1643 metal_build_render_pipeline_3d(device, pbr_lib, archive);
1644 if !pbr_lib.is_null() {
1645 mtl_send_void0(pbr_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1646 }
1647 let engine3d_compile_us: u64 = pbr_start.elapsed().as_micros() as u64;
1648 let ocean_start: Instant = Instant::now();
1649 let mut ocean_err: *mut c_void = null_mut();
1650 let ocean_lib: *mut c_void = send_lib(
1651 device,
1652 mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1653 mtl_ns_string(MSL_FLUID_OCEAN_SHADER),
1654 null_mut(),
1655 &mut ocean_err,
1656 );
1657 let (ocean_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1658 device,
1659 ocean_lib,
1660 MTL_FN_OCEAN_VERTEX,
1661 MTL_FN_OCEAN_FRAGMENT,
1662 archive,
1663 false,
1664 );
1665 if !ocean_lib.is_null() {
1666 mtl_send_void0(ocean_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1667 }
1668 let ocean_compile_us: u64 = ocean_start.elapsed().as_micros() as u64;
1669 let mut scene_err: *mut c_void = null_mut();
1670 let scene_lib: *mut c_void = send_lib(
1671 device,
1672 mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1673 mtl_ns_string(MSL_GPU_SCENE_SHADER),
1674 null_mut(),
1675 &mut scene_err,
1676 );
1677 let (scene_ocean_pipeline, _): (usize, bool) =
1678 metal_build_render_pipeline_with_depth(
1679 device,
1680 scene_lib,
1681 MTL_FN_SCENE_OCEAN_VERT,
1682 MTL_FN_SCENE_OCEAN_FRAG,
1683 archive,
1684 false,
1685 0,
1686 );
1687 let (scene_boat_pipeline, _): (usize, bool) =
1688 metal_build_render_pipeline_with_depth(
1689 device,
1690 scene_lib,
1691 MTL_FN_SCENE_BOAT_VERT,
1692 MTL_FN_SCENE_BOAT_FRAG,
1693 archive,
1694 true,
1695 0,
1696 );
1697 let (scene_3d_sky_pipeline, _): (usize, bool) =
1698 metal_build_render_pipeline_with_depth(
1699 device,
1700 scene_lib,
1701 MTL_FN_SCENE_3D_SKY_VERT,
1702 MTL_FN_SCENE_3D_SKY_FRAG,
1703 archive,
1704 false,
1705 MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1706 );
1707 let (scene_3d_mesh_pipeline, _): (usize, bool) =
1708 metal_build_render_pipeline_with_depth(
1709 device,
1710 scene_lib,
1711 MTL_FN_SCENE_3D_MESH_VERT,
1712 MTL_FN_SCENE_3D_MESH_FRAG,
1713 archive,
1714 false,
1715 MTL_PIXEL_FORMAT_DEPTH32_FLOAT,
1716 );
1717 if !scene_lib.is_null() {
1718 mtl_send_void0(scene_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1719 }
1720 let scene_depth_stencil: usize = metal_create_depth_stencil_state(device);
1721 if !archive.is_null() {
1722 if !archive_existed
1723 && !archive_url.is_null()
1724 && pipeline != 0
1725 && metal_binary_archive_allowed(&device_name, cfg!(target_abi = "sim"))
1726 && mtl_responds_to_sel(archive, mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL))
1727 {
1728 let mut ser_err: *mut c_void = null_mut();
1729 let send_ser: unsafe extern "C" fn(
1730 *mut c_void,
1731 *mut c_void,
1732 *mut c_void,
1733 *mut *mut c_void,
1734 ) -> i8 = transmute(objc_msgSend as *const c_void);
1735 let _: i8 = send_ser(
1736 archive,
1737 mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL),
1738 archive_url,
1739 &mut ser_err,
1740 );
1741 }
1742 mtl_send_void0(archive, mtl_sel_cstr(MTL_SEL_RELEASE));
1743 }
1744 let dummy_r8_tex: usize =
1745 metal_create_texture(device, GpuAtlasPixelFormat::R8Unorm, 1, 1);
1746 let dummy_rgba8_tex: usize =
1747 metal_create_texture(device, GpuAtlasPixelFormat::Rgba8Unorm, 1, 1);
1748 let shader_compiled: bool = ui_fns_ok && pipeline != 0;
1749 let total_compile_us: u64 = total_start.elapsed().as_micros() as u64;
1750 MetalSharedPipelineCache {
1751 adapter: GpuAdapterInfo::new(
1752 GraphicsBackend::Metal,
1753 device_name,
1754 !queue.is_null(),
1755 shader_compiled,
1756 ),
1757 device: device as usize,
1758 queue: queue as usize,
1759 library: library as usize,
1760 pipeline,
1761 blur_pipeline,
1762 blur_up_pipeline,
1763 engine3d_pipeline,
1764 ocean_pipeline,
1765 scene_ocean_pipeline,
1766 scene_boat_pipeline,
1767 scene_3d_sky_pipeline,
1768 scene_3d_mesh_pipeline,
1769 scene_depth_stencil,
1770 binary_archive_enabled: archive_enabled,
1771 binary_archive_hit: archive_enabled && archive_existed,
1772 ui_compile_us,
1773 blur_compile_us,
1774 engine3d_compile_us,
1775 ocean_compile_us,
1776 total_compile_us,
1777 dummy_r8_tex,
1778 dummy_rgba8_tex,
1779 }
1780 }
1781 };
1782 unsafe { objc_autoreleasePoolPop(pool) };
1783 result
1784 })
1785}
1786
1787#[cfg(any(target_os = "macos", target_os = "ios"))]
1797fn probe_apple_metal_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
1798 let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
1799 NativeGpuProbeOutput {
1800 adapter: cached.adapter.clone(),
1801 device_handle: mtl_retain_handle(cached.device),
1802 queue_handle: mtl_retain_handle(cached.queue),
1803 library_handle: mtl_retain_handle(cached.library),
1804 pipeline_handle: mtl_retain_handle(cached.pipeline),
1805 blur_pipeline_handle: mtl_retain_handle(cached.blur_pipeline),
1806 blur_up_pipeline_handle: mtl_retain_handle(cached.blur_up_pipeline),
1807 engine3d_pipeline_handle: mtl_retain_handle(cached.engine3d_pipeline),
1808 ocean_pipeline_handle: mtl_retain_handle(cached.ocean_pipeline),
1809 scene_ocean_pipeline_handle: mtl_retain_handle(cached.scene_ocean_pipeline),
1810 scene_boat_pipeline_handle: mtl_retain_handle(cached.scene_boat_pipeline),
1811 scene_3d_sky_pipeline_handle: mtl_retain_handle(cached.scene_3d_sky_pipeline),
1812 scene_3d_mesh_pipeline_handle: mtl_retain_handle(cached.scene_3d_mesh_pipeline),
1813 scene_depth_stencil_handle: mtl_retain_handle(cached.scene_depth_stencil),
1814 dummy_r8_tex: mtl_retain_handle(cached.dummy_r8_tex),
1815 dummy_rgba8_tex: mtl_retain_handle(cached.dummy_rgba8_tex),
1816 }
1817}
1818
1819#[cfg(any(target_os = "macos", target_os = "ios"))]
1825pub(crate) fn cached_metal_selectors() -> &'static MetalSelectors {
1826 METAL_SELECTORS.get_or_init(|| MetalSelectors {
1827 retain: mtl_sel_cstr(MTL_SEL_RETAIN) as usize,
1828 new_buffer_with_bytes: mtl_sel_cstr(MTL_SEL_NEW_BUFFER) as usize,
1829 new_buffer_with_length: mtl_sel_cstr(MTL_SEL_NEW_BUFFER_LENGTH) as usize,
1830 contents: mtl_sel_cstr(MTL_SEL_CONTENTS) as usize,
1831 command_buffer: mtl_sel_cstr(MTL_SEL_CMD_BUFFER) as usize,
1832 render_encoder: mtl_sel_cstr(MTL_SEL_RENDER_ENCODER) as usize,
1833 set_pipeline_state: mtl_sel_cstr(MTL_SEL_SET_PIPELINE_STATE) as usize,
1834 set_vertex_buffer: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BUFFER) as usize,
1835 set_vertex_bytes: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BYTES) as usize,
1836 set_fragment_texture: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_TEXTURE) as usize,
1837 set_fragment_bytes: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_BYTES) as usize,
1838 set_scissor_rect: mtl_sel_cstr(MTL_SEL_SET_SCISSOR_RECT) as usize,
1839 set_viewport: mtl_sel_cstr(MTL_SEL_SET_VIEWPORT) as usize,
1840 draw_primitives_instanced: mtl_sel_cstr(MTL_SEL_DRAW_PRIMITIVES_INSTANCED) as usize,
1841 end_encoding: mtl_sel_cstr(MTL_SEL_END_ENCODING) as usize,
1842 present_drawable: mtl_sel_cstr(MTL_SEL_PRESENT_DRAWABLE) as usize,
1843 #[cfg(not(target_abi = "sim"))]
1844 add_presented_handler: mtl_sel_cstr(MTL_SEL_ADD_PRESENTED_HANDLER) as usize,
1845 add_completed_handler: mtl_sel_cstr(MTL_SEL_ADD_COMPLETED_HANDLER) as usize,
1846 #[cfg(not(target_abi = "sim"))]
1847 presented_time: mtl_sel_cstr(MTL_SEL_PRESENTED_TIME) as usize,
1848 responds_to_sel: mtl_sel_cstr(MTL_SEL_RESPONDS_TO_SEL) as usize,
1849 status: mtl_sel_cstr(MTL_SEL_STATUS) as usize,
1850 wait_until_completed: mtl_sel_cstr(MTL_SEL_WAIT_UNTIL_COMPLETED) as usize,
1851 gpu_start_time: mtl_sel_cstr(MTL_SEL_GPU_START_TIME) as usize,
1852 gpu_end_time: mtl_sel_cstr(MTL_SEL_GPU_END_TIME) as usize,
1853 next_drawable: mtl_sel_cstr(MTL_SEL_NEXT_DRAWABLE) as usize,
1854 drawable_size: mtl_sel_cstr(MTL_SEL_DRAWABLE_SIZE) as usize,
1855 set_drawable_size: mtl_sel_cstr(MTL_SEL_SET_DRAWABLE_SIZE) as usize,
1856 texture: mtl_sel_cstr(MTL_SEL_TEXTURE) as usize,
1857 width: mtl_sel_cstr(MTL_SEL_WIDTH) as usize,
1858 height: mtl_sel_cstr(MTL_SEL_HEIGHT) as usize,
1859 render_pass_desc: mtl_sel_cstr(MTL_SEL_RENDER_PASS_DESC) as usize,
1860 color_attachments: mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS) as usize,
1861 object_at_index: mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX) as usize,
1862 set_texture: mtl_sel_cstr(MTL_SEL_SET_TEXTURE) as usize,
1863 set_load_action: mtl_sel_cstr(MTL_SEL_SET_LOAD_ACTION) as usize,
1864 set_store_action: mtl_sel_cstr(MTL_SEL_SET_STORE_ACTION) as usize,
1865 set_clear_color: mtl_sel_cstr(MTL_SEL_SET_CLEAR_COLOR) as usize,
1866 depth_attachment: mtl_sel_cstr(MTL_SEL_DEPTH_ATTACHMENT) as usize,
1867 set_clear_depth: mtl_sel_cstr(MTL_SEL_SET_CLEAR_DEPTH) as usize,
1868 set_depth_stencil_state: mtl_sel_cstr(MTL_SEL_SET_DEPTH_STENCIL_STATE) as usize,
1869 replace_region: mtl_sel_cstr(MTL_SEL_REPLACE_REGION) as usize,
1870 commit: mtl_sel_cstr(MTL_SEL_COMMIT) as usize,
1871 release: mtl_sel_cstr(MTL_SEL_RELEASE) as usize,
1872 })
1873}
1874
1875#[cfg(any(target_os = "macos", target_os = "ios"))]
1881#[must_use]
1882pub(crate) fn metal_preferred_display_sync_enabled() -> bool {
1883 let uncapped_env: bool = env::var(ENV_UNCAPPED_PRESENT)
1884 .map(|val: String| {
1885 let trimmed: &str = val.trim();
1886 trimmed == MTL_ENV_VALUE_ON || trimmed.eq_ignore_ascii_case(MTL_ENV_VALUE_TRUE)
1887 })
1888 .unwrap_or(false);
1889 if uncapped_env {
1890 return false;
1891 }
1892 let sync_disabled: bool = env::var(ENV_METAL_DISPLAY_SYNC)
1893 .map(|val: String| {
1894 let trimmed: &str = val.trim();
1895 trimmed == MTL_ENV_VALUE_OFF || trimmed.eq_ignore_ascii_case(MTL_ENV_VALUE_FALSE)
1896 })
1897 .unwrap_or(false);
1898 !sync_disabled
1899}
1900
1901#[cfg(any(target_os = "macos", target_os = "ios"))]
1908fn metal_set_layer_display_sync(layer_handle: usize, enabled: bool) {
1909 if layer_handle == 0 {
1910 return;
1911 }
1912 let layer: *mut c_void = layer_handle as *mut c_void;
1913 let sel_sync: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_DISPLAY_SYNC);
1914 if mtl_responds_to_sel(layer, sel_sync) {
1915 mtl_send_void_bool(layer, sel_sync, enabled);
1916 }
1917}
1918
1919#[cfg(any(target_os = "macos", target_os = "ios"))]
1926fn metal_configure_layer(device_handle: usize, layer_handle: usize) {
1927 if device_handle == 0 || layer_handle == 0 {
1928 return;
1929 }
1930 let layer: *mut c_void = layer_handle as *mut c_void;
1931 mtl_send_void_ptr1(
1932 layer,
1933 mtl_sel_cstr(MTL_SEL_SET_DEVICE),
1934 device_handle as *mut c_void,
1935 );
1936 mtl_send_void_usize(
1937 layer,
1938 mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1939 MTL_PIXEL_FORMAT_BGRA8_UNORM,
1940 );
1941 mtl_send_void_bool(layer, mtl_sel_cstr(MTL_SEL_SET_FRAMEBUFFER_ONLY), true);
1942 let sel_max: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_MAX_DRAWABLE_COUNT);
1943 if mtl_responds_to_sel(layer, sel_max) {
1944 mtl_send_void_usize(layer, sel_max, GPU_DRIVER_RING_SLOTS);
1945 }
1946 metal_set_layer_display_sync(layer_handle, metal_preferred_display_sync_enabled());
1947}
1948
1949#[cfg(any(target_os = "macos", target_os = "ios"))]
1965fn metal_upload_texture_dirty_rect(
1966 device_handle: usize,
1967 texture_handle: &mut usize,
1968 format: GpuAtlasPixelFormat,
1969 tex_dims: (u32, u32),
1970 dirty_rect: (u32, u32, u32, u32),
1971 bytes: &[u8],
1972 bytes_per_row: usize,
1973) -> bool {
1974 if device_handle == 0 || dirty_rect.2 == 0 || dirty_rect.3 == 0 || bytes.is_empty() {
1975 return false;
1976 }
1977 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1978 let (tex_w, tex_h): (u32, u32) = (tex_dims.0.max(1), tex_dims.1.max(1));
1979 let sel: &MetalSelectors = cached_metal_selectors();
1980 let cur_w: usize = if *texture_handle != 0 {
1981 mtl_send_usize0(*texture_handle as *mut c_void, sel.width as *mut c_void)
1982 } else {
1983 0
1984 };
1985 let cur_h: usize = if *texture_handle != 0 {
1986 mtl_send_usize0(*texture_handle as *mut c_void, sel.height as *mut c_void)
1987 } else {
1988 0
1989 };
1990 if *texture_handle == 0 || cur_w != tex_w as usize || cur_h != tex_h as usize {
1991 if *texture_handle != 0 {
1992 mtl_send_void0(*texture_handle as *mut c_void, sel.release as *mut c_void);
1993 }
1994 *texture_handle = metal_create_texture(device_handle as *mut c_void, format, tex_w, tex_h);
1995 }
1996 if *texture_handle == 0 {
1997 unsafe { objc_autoreleasePoolPop(pool) };
1998 return false;
1999 }
2000 let region: MtlRegion = MtlRegion {
2001 origin: MtlOrigin {
2002 x: dirty_rect.0 as usize,
2003 y: dirty_rect.1 as usize,
2004 z: 0,
2005 },
2006 size: MtlSize {
2007 width: dirty_rect.2 as usize,
2008 height: dirty_rect.3 as usize,
2009 depth: 1,
2010 },
2011 };
2012 unsafe {
2013 let send_replace: unsafe extern "C" fn(
2014 *mut c_void,
2015 *mut c_void,
2016 MtlRegion,
2017 usize,
2018 *const c_void,
2019 usize,
2020 ) = transmute(objc_msgSend as *const c_void);
2021 send_replace(
2022 *texture_handle as *mut c_void,
2023 sel.replace_region as *mut c_void,
2024 region,
2025 0,
2026 bytes.as_ptr().cast::<c_void>(),
2027 bytes_per_row,
2028 );
2029 objc_autoreleasePoolPop(pool);
2030 }
2031 true
2032}
2033
2034#[cfg(any(target_os = "macos", target_os = "ios"))]
2048fn metal_submit_ring_frame(
2049 driver: &mut NativeGpuDriver,
2050 width: u32,
2051 height: u32,
2052 clear_color: Color,
2053 batches: &[GpuBatch],
2054) -> usize {
2055 let total_instances: usize = batches
2056 .iter()
2057 .map(|blue_val: &GpuBatch| {
2058 blue_val
2059 .get_primitives()
2060 .len()
2061 .max(blue_val.get_instances().len())
2062 })
2063 .sum();
2064 let device_handle: usize = driver.get_device_handle();
2065 let queue_handle: usize = driver.get_queue_handle();
2066 let layer_handle: usize = driver.get_surface_layer_handle();
2067 if device_handle == 0 || queue_handle == 0 || layer_handle == 0 {
2068 return total_instances;
2069 }
2070 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
2071 let sel: &MetalSelectors = cached_metal_selectors();
2072 let sel_rel: *mut c_void = sel.release as *mut c_void;
2073 let slot_idx: usize = driver.get_ring_cursor() % GPU_DRIVER_RING_SLOTS;
2074 let device: *mut c_void = device_handle as *mut c_void;
2075 let queue: *mut c_void = queue_handle as *mut c_void;
2076 let pipeline: *mut c_void = driver.get_pipeline_handle() as *mut c_void;
2077 let blur_down_pso: *mut c_void = driver.get_blur_pipeline_handle() as *mut c_void;
2078 let blur_up_pso: *mut c_void = driver.get_blur_up_pipeline_handle() as *mut c_void;
2079 let scene_pipelines: [*mut c_void; 5] = [
2080 driver.get_scene_ocean_pipeline_handle() as *mut c_void,
2081 driver.get_scene_boat_pipeline_handle() as *mut c_void,
2082 driver.get_scene_3d_sky_pipeline_handle() as *mut c_void,
2083 driver.get_scene_3d_mesh_pipeline_handle() as *mut c_void,
2084 driver.get_scene_depth_stencil_handle() as *mut c_void,
2085 ];
2086 let layer_ptr: *mut c_void = layer_handle as *mut c_void;
2087 let tex_r8: *mut c_void = driver.get_glyph_r8_texture_handle() as *mut c_void;
2088 let tex_rgba8: *mut c_void = driver.get_glyph_rgba8_texture_handle() as *mut c_void;
2089 let tex_img: *mut c_void = driver.get_image_texture_handle() as *mut c_void;
2090 let raw_ext: usize = driver.get_external_texture_handle();
2091 let mut tex_ext: *mut c_void = if raw_ext != 0 {
2092 raw_ext as *mut c_void
2093 } else {
2094 tex_rgba8
2095 };
2096 let has_blur_batches: bool = !blur_down_pso.is_null()
2097 && !blur_up_pso.is_null()
2098 && batches.iter().any(|batch_item: &GpuBatch| {
2099 batch_item
2100 .get_primitives()
2101 .iter()
2102 .any(|prim_item: &GpuPrimitiveInstance| {
2103 prim_item.prim_kind() == PrimKind::BackdropBlur
2104 })
2105 });
2106 let total_bytes: usize = total_instances.saturating_mul(size_of::<GpuPrimitiveInstance>());
2107 let NativeGpuDriver {
2108 ring_slots,
2109 ring_cursor,
2110 staging_buffer_handle,
2111 staging_contents_ptr,
2112 staging_buffer_capacity,
2113 staging_reallocations,
2114 scratch_primitives,
2115 blur_scene_texture_handle,
2116 blur_half_texture_handle,
2117 blur_full_texture_handle,
2118 blur_texture_dims,
2119 scene_color_texture_handle,
2120 scene_depth_texture_handle,
2121 scene_wake_texture_handle,
2122 scene_wake_texture_handles,
2123 scene_texture_dims,
2124 scene_3d_vertex_buffer_handle,
2125 scene_3d_vertex_revision,
2126 scene_3d_vertex_capacity,
2127 scene_3d_instance_buffer_handle,
2128 scene_3d_instance_capacity,
2129 scene_3d_instance_buffer_handles,
2130 scene_3d_instance_capacities,
2131 scene_boat_buffer_handle,
2132 scene_boat_capacity,
2133 scene_boat_buffer_handles,
2134 scene_boat_capacities,
2135 pending_gpu_scene_pass,
2136 ..
2137 } = driver;
2138 let frame_scene_pass: Option<DirectGpuScenePass> = pending_gpu_scene_pass.take();
2139 let slot: &mut NativeGpuRingSlot = &mut ring_slots[slot_idx];
2140 let prev_cmd: usize = slot.get_in_flight_cmd_buffer();
2141 if prev_cmd != 0 {
2142 let status: usize = mtl_send_usize0(prev_cmd as *mut c_void, sel.status as *mut c_void);
2143 if status < MTL_CMD_BUFFER_STATUS_COMPLETED {
2144 mtl_send_void0(
2145 prev_cmd as *mut c_void,
2146 sel.wait_until_completed as *mut c_void,
2147 );
2148 }
2149 mtl_send_void0(prev_cmd as *mut c_void, sel_rel);
2150 slot.set_in_flight_cmd_buffer(0);
2151 }
2152 if total_bytes > 0
2153 && (slot.get_buffer_handle() == 0
2154 || slot.get_contents_ptr() == 0
2155 || total_bytes > slot.get_capacity_bytes())
2156 {
2157 if slot.get_buffer_handle() != 0 {
2158 mtl_send_void0(slot.get_buffer_handle() as *mut c_void, sel_rel);
2159 slot.set_buffer_handle(0);
2160 slot.set_contents_ptr(0);
2161 slot.set_capacity_bytes(0);
2162 }
2163 let alloc_bytes: usize = total_bytes.max(4096).next_power_of_two();
2164 unsafe {
2165 let send_new_len: unsafe extern "C" fn(
2166 *mut c_void,
2167 *mut c_void,
2168 usize,
2169 usize,
2170 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
2171 let new_buf: *mut c_void = send_new_len(
2172 device,
2173 sel.new_buffer_with_length as *mut c_void,
2174 alloc_bytes,
2175 0,
2176 );
2177 if !new_buf.is_null() {
2178 let ptr: *mut c_void = mtl_send_ptr0(new_buf, sel.contents as *mut c_void);
2179 if !ptr.is_null() {
2180 slot.set_buffer_handle(new_buf as usize);
2181 slot.set_contents_ptr(ptr as usize);
2182 slot.set_capacity_bytes(alloc_bytes);
2183 *staging_reallocations = staging_reallocations.wrapping_add(1);
2184 } else {
2185 mtl_send_void0(new_buf, sel_rel);
2186 }
2187 }
2188 }
2189 }
2190 let buf_handle: usize = slot.get_buffer_handle();
2191 let contents_ptr: usize = slot.get_contents_ptr();
2192 let capacity_bytes: usize = slot.get_capacity_bytes();
2193 *staging_buffer_handle = buf_handle;
2194 *staging_contents_ptr = contents_ptr;
2195 *staging_buffer_capacity = capacity_bytes;
2196 if contents_ptr != 0 && total_bytes > 0 && total_bytes <= capacity_bytes {
2197 unsafe {
2198 let mut dst: *mut u8 = (contents_ptr as *mut c_void).cast::<u8>();
2199 for batch in batches.iter() {
2200 let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
2201 if !prims.is_empty() {
2202 let byte_len: usize = size_of_val(prims);
2203 dst.copy_from_nonoverlapping(prims.as_ptr().cast::<u8>(), byte_len);
2204 dst = dst.add(byte_len);
2205 } else if !batch.get_instances().is_empty() {
2206 scratch_primitives.clear();
2207 for quad in batch.get_instances().iter() {
2208 scratch_primitives.push(GpuPrimitiveInstance::from_quad_instance(
2209 quad,
2210 batch.get_texture_slot(),
2211 batch.get_layer_id(),
2212 ));
2213 }
2214 let byte_len: usize = size_of_val(scratch_primitives.as_slice());
2215 dst.copy_from_nonoverlapping(
2216 scratch_primitives.as_ptr().cast::<u8>(),
2217 byte_len,
2218 );
2219 dst = dst.add(byte_len);
2220 }
2221 }
2222 }
2223 }
2224 let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
2225 if !cmd_buf.is_null() {
2226 let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
2227 if mtl_responds_to_sel(cmd_buf, sel_completed) {
2228 mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
2229 }
2230 if !layer_ptr.is_null() && !pipeline.is_null() {
2231 if width > 0
2232 && height > 0
2233 && mtl_responds_to_sel(layer_ptr, sel.set_drawable_size as *mut c_void)
2234 {
2235 let target_w: f64 = f64::from(width);
2236 let target_h: f64 = f64::from(height);
2237 let needs_resize: bool =
2238 if mtl_responds_to_sel(layer_ptr, sel.drawable_size as *mut c_void) {
2239 let cur: MtlCgSize = unsafe {
2241 let get_size: unsafe extern "C" fn(
2242 *mut c_void,
2243 *mut c_void,
2244 )
2245 -> MtlCgSize = transmute(objc_msgSend as *const c_void);
2246 get_size(layer_ptr, sel.drawable_size as *mut c_void)
2247 };
2248 (cur.width - target_w).abs() > 0.5 || (cur.height - target_h).abs() > 0.5
2249 } else {
2250 true
2251 };
2252 if needs_resize {
2253 unsafe {
2255 let set_size: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlCgSize) =
2256 transmute(objc_msgSend as *const c_void);
2257 set_size(
2258 layer_ptr,
2259 sel.set_drawable_size as *mut c_void,
2260 MtlCgSize {
2261 width: target_w,
2262 height: target_h,
2263 },
2264 );
2265 }
2266 }
2267 }
2268 let drawable: *mut c_void = mtl_send_ptr0(layer_ptr, sel.next_drawable as *mut c_void);
2269 if !drawable.is_null() {
2270 let drawable_tex: *mut c_void = mtl_send_ptr0(drawable, sel.texture as *mut c_void);
2271 let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
2272 if !drawable_tex.is_null() && !pass_cls.is_null() {
2273 let tex_w: usize = mtl_send_usize0(drawable_tex, sel.width as *mut c_void);
2274 let tex_h: usize = mtl_send_usize0(drawable_tex, sel.height as *mut c_void);
2275 let draw_w: usize = if tex_w > 0 {
2276 tex_w
2277 } else {
2278 width.max(1) as usize
2279 };
2280 let draw_h: usize = if tex_h > 0 {
2281 tex_h
2282 } else {
2283 height.max(1) as usize
2284 };
2285 let clear_rgba: [f32; 4] = clear_color.to_f32_array();
2286 let mtl_clear: MtlClearColor = MtlClearColor {
2287 red: clear_rgba[0] as f64,
2288 green: clear_rgba[1] as f64,
2289 blue: clear_rgba[2] as f64,
2290 alpha: clear_rgba[3] as f64,
2291 };
2292 let mut use_blur_offscreen: bool = false;
2293 let mut scene_tex_ptr: *mut c_void = null_mut();
2294 let mut half_tex_ptr: *mut c_void = null_mut();
2295 let mut full_tex_ptr: *mut c_void = null_mut();
2296 let half_w_u32: u32 = ((draw_w as u32) / 2).max(1);
2297 let half_h_u32: u32 = ((draw_h as u32) / 2).max(1);
2298 if has_blur_batches {
2299 let target_dims: (u32, u32) = (draw_w as u32, draw_h as u32);
2300 if *blur_scene_texture_handle == 0
2301 || *blur_half_texture_handle == 0
2302 || *blur_full_texture_handle == 0
2303 || *blur_texture_dims != target_dims
2304 {
2305 release_native_gpu_object(*blur_scene_texture_handle);
2306 release_native_gpu_object(*blur_half_texture_handle);
2307 release_native_gpu_object(*blur_full_texture_handle);
2308 let unified_mem: bool = cfg!(target_arch = "aarch64");
2309 *blur_scene_texture_handle = metal_create_offscreen_render_texture(
2310 device_handle,
2311 target_dims.0,
2312 target_dims.1,
2313 unified_mem,
2314 );
2315 *blur_half_texture_handle = metal_create_offscreen_render_texture(
2316 device_handle,
2317 half_w_u32,
2318 half_h_u32,
2319 unified_mem,
2320 );
2321 *blur_full_texture_handle = metal_create_offscreen_render_texture(
2322 device_handle,
2323 target_dims.0,
2324 target_dims.1,
2325 unified_mem,
2326 );
2327 *blur_texture_dims = target_dims;
2328 }
2329 scene_tex_ptr = *blur_scene_texture_handle as *mut c_void;
2330 half_tex_ptr = *blur_half_texture_handle as *mut c_void;
2331 full_tex_ptr = *blur_full_texture_handle as *mut c_void;
2332 use_blur_offscreen = !scene_tex_ptr.is_null()
2333 && !half_tex_ptr.is_null()
2334 && !full_tex_ptr.is_null();
2335 }
2336 let primary_target: *mut c_void = if use_blur_offscreen {
2337 scene_tex_ptr
2338 } else {
2339 drawable_tex
2340 };
2341 if let Some(scene_pass) = frame_scene_pass.as_ref() {
2342 let mut scene_buf_handles: [usize; 6] = [
2343 *scene_3d_vertex_buffer_handle,
2344 *scene_3d_vertex_capacity,
2345 scene_3d_instance_buffer_handles[slot_idx],
2346 scene_3d_instance_capacities[slot_idx],
2347 scene_boat_buffer_handles[slot_idx],
2348 scene_boat_capacities[slot_idx],
2349 ];
2350 let maybe_scene_tex: Option<*mut c_void> = metal_encode_gpu_scene_pass(
2351 cmd_buf,
2352 pass_cls,
2353 device,
2354 scene_pipelines,
2355 (
2356 scene_color_texture_handle,
2357 scene_depth_texture_handle,
2358 &mut scene_wake_texture_handles[slot_idx],
2359 scene_texture_dims,
2360 ),
2361 (&mut scene_buf_handles, scene_3d_vertex_revision),
2362 scene_pass,
2363 );
2364 *scene_wake_texture_handle = scene_wake_texture_handles[slot_idx];
2365 *scene_3d_vertex_buffer_handle = scene_buf_handles[0];
2366 *scene_3d_vertex_capacity = scene_buf_handles[1];
2367 scene_3d_instance_buffer_handles[slot_idx] = scene_buf_handles[2];
2368 scene_3d_instance_capacities[slot_idx] = scene_buf_handles[3];
2369 scene_boat_buffer_handles[slot_idx] = scene_buf_handles[4];
2370 scene_boat_capacities[slot_idx] = scene_buf_handles[5];
2371 *scene_3d_instance_buffer_handle = scene_buf_handles[2];
2372 *scene_3d_instance_capacity = scene_buf_handles[3];
2373 *scene_boat_buffer_handle = scene_buf_handles[4];
2374 *scene_boat_capacity = scene_buf_handles[5];
2375 if let Some(rendered_scene_tex) = maybe_scene_tex {
2376 tex_ext = rendered_scene_tex;
2377 }
2378 }
2379 let mut active_encoder: *mut c_void = metal_begin_ui_render_encoder(
2380 cmd_buf,
2381 pass_cls,
2382 primary_target,
2383 (MTL_LOAD_ACTION_CLEAR, mtl_clear),
2384 (draw_w, draw_h),
2385 (pipeline, buf_handle as *mut c_void),
2386 [tex_r8, tex_rgba8, tex_img, tex_ext],
2387 );
2388 let mut base_instance: usize = 0;
2389 for batch in batches.iter() {
2390 let count: usize = batch
2391 .get_primitives()
2392 .len()
2393 .max(batch.get_instances().len());
2394 if count == 0 || buf_handle == 0 {
2395 continue;
2396 }
2397 let is_blur_batch: bool = use_blur_offscreen
2398 && batch.get_primitives().iter().any(
2399 |prim_item: &GpuPrimitiveInstance| {
2400 prim_item.prim_kind() == PrimKind::BackdropBlur
2401 },
2402 );
2403 if is_blur_batch {
2404 if !active_encoder.is_null() {
2405 mtl_send_void0(active_encoder, sel.end_encoding as *mut c_void);
2406 }
2407 let blur_offset: f32 = 2.5;
2408 let down_uniform: [f32; 4] = [
2409 1.0 / (draw_w.max(1) as f32),
2410 1.0 / (draw_h.max(1) as f32),
2411 blur_offset,
2412 0.0,
2413 ];
2414 let up_uniform: [f32; 4] = [
2415 1.0 / (half_w_u32 as f32),
2416 1.0 / (half_h_u32 as f32),
2417 blur_offset,
2418 1.0,
2419 ];
2420 let _: bool = metal_encode_fullscreen_blur_pass(
2421 cmd_buf,
2422 pass_cls,
2423 half_tex_ptr,
2424 blur_down_pso,
2425 scene_tex_ptr,
2426 &down_uniform,
2427 );
2428 let _: bool = metal_encode_fullscreen_blur_pass(
2429 cmd_buf,
2430 pass_cls,
2431 full_tex_ptr,
2432 blur_up_pso,
2433 half_tex_ptr,
2434 &up_uniform,
2435 );
2436 active_encoder = metal_begin_ui_render_encoder(
2437 cmd_buf,
2438 pass_cls,
2439 scene_tex_ptr,
2440 (MTL_LOAD_ACTION_LOAD, mtl_clear),
2441 (draw_w, draw_h),
2442 (pipeline, buf_handle as *mut c_void),
2443 [tex_r8, tex_rgba8, tex_img, full_tex_ptr],
2444 );
2445 }
2446 if !active_encoder.is_null() {
2447 metal_encode_ui_batch_draw(
2448 active_encoder,
2449 (draw_w, draw_h),
2450 batch,
2451 count,
2452 base_instance,
2453 );
2454 if is_blur_batch && !tex_ext.is_null() {
2455 unsafe {
2456 let send_ftex: unsafe extern "C" fn(
2457 *mut c_void,
2458 *mut c_void,
2459 *mut c_void,
2460 usize,
2461 ) = transmute(objc_msgSend as *const c_void);
2462 send_ftex(
2463 active_encoder,
2464 sel.set_fragment_texture as *mut c_void,
2465 tex_ext,
2466 3,
2467 );
2468 }
2469 }
2470 }
2471 base_instance = base_instance.saturating_add(count);
2472 }
2473 if !active_encoder.is_null() {
2474 mtl_send_void0(active_encoder, sel.end_encoding as *mut c_void);
2475 }
2476 if use_blur_offscreen {
2477 let copy_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
2478 rect: [0.0, 0.0, draw_w as f32, draw_h as f32],
2479 clip_rect: [0.0, 0.0, draw_w as f32, draw_h as f32],
2480 color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
2481 aux_color_rgba: 0,
2482 uv_rect: [0, 0, u16::MAX, u16::MAX],
2483 radii_border: [0; 4],
2484 kind_flags: GpuPrimitiveInstance::pack_kind_flags(
2485 PrimKind::ExternalGpuSurface,
2486 0,
2487 0,
2488 0,
2489 ),
2490 extra_param: 0,
2491 };
2492 let copy_enc: *mut c_void = metal_begin_ui_render_encoder(
2493 cmd_buf,
2494 pass_cls,
2495 drawable_tex,
2496 (MTL_LOAD_ACTION_CLEAR, mtl_clear),
2497 (draw_w, draw_h),
2498 (pipeline, null_mut()),
2499 [tex_r8, tex_rgba8, tex_img, scene_tex_ptr],
2500 );
2501 if !copy_enc.is_null() {
2502 let uniform: GpuLayerUniform =
2503 GpuLayerUniform::new(draw_w as f32, draw_h as f32, [0.0, 0.0]);
2504 unsafe {
2505 let send_vbytes: unsafe extern "C" fn(
2506 *mut c_void,
2507 *mut c_void,
2508 *const c_void,
2509 usize,
2510 usize,
2511 ) = transmute(objc_msgSend as *const c_void);
2512 let send_scissor: unsafe extern "C" fn(
2513 *mut c_void,
2514 *mut c_void,
2515 MtlScissorRect,
2516 ) = transmute(objc_msgSend as *const c_void);
2517 let send_draw: unsafe extern "C" fn(
2518 *mut c_void,
2519 *mut c_void,
2520 usize,
2521 usize,
2522 usize,
2523 usize,
2524 usize,
2525 ) = transmute(objc_msgSend as *const c_void);
2526 send_vbytes(
2527 copy_enc,
2528 sel.set_vertex_bytes as *mut c_void,
2529 (©_prim as *const GpuPrimitiveInstance).cast::<c_void>(),
2530 size_of::<GpuPrimitiveInstance>(),
2531 0,
2532 );
2533 send_vbytes(
2534 copy_enc,
2535 sel.set_vertex_bytes as *mut c_void,
2536 (&uniform as *const GpuLayerUniform).cast::<c_void>(),
2537 size_of::<GpuLayerUniform>(),
2538 1,
2539 );
2540 send_scissor(
2541 copy_enc,
2542 sel.set_scissor_rect as *mut c_void,
2543 MtlScissorRect {
2544 x: 0,
2545 y: 0,
2546 width: draw_w,
2547 height: draw_h,
2548 },
2549 );
2550 send_draw(
2551 copy_enc,
2552 sel.draw_primitives_instanced as *mut c_void,
2553 MTL_PRIMITIVE_TYPE_TRIANGLE,
2554 0,
2555 6,
2556 1,
2557 0,
2558 );
2559 }
2560 mtl_send_void0(copy_enc, sel.end_encoding as *mut c_void);
2561 }
2562 }
2563 #[cfg(not(target_abi = "sim"))]
2564 {
2565 let sel_pres: *mut c_void = sel.add_presented_handler as *mut c_void;
2566 if mtl_responds_to_sel(drawable, sel_pres) {
2567 mtl_send_void_ptr1(drawable, sel_pres, metal_presented_block_ptr());
2568 }
2569 }
2570 mtl_send_void_ptr1(cmd_buf, sel.present_drawable as *mut c_void, drawable);
2571 }
2572 }
2573 }
2574 let retained_cmd: usize = mtl_retain_handle(cmd_buf as usize);
2575 slot.set_in_flight_cmd_buffer(retained_cmd);
2576 let _: u64 = SUBMITTED_GPU_FENCE.fetch_add(1, Ordering::AcqRel);
2577 mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
2578 }
2579 *ring_cursor = (slot_idx + 1) % GPU_DRIVER_RING_SLOTS;
2580 unsafe { objc_autoreleasePoolPop(pool) };
2581 total_instances
2582}
2583
2584#[cfg(any(target_os = "macos", target_os = "ios"))]
2597fn metal_execute_dual_kawase_blur_passes(
2598 driver: &mut NativeGpuDriver,
2599 width: u32,
2600 height: u32,
2601 blur_passes: &[GpuBackdropBlurPass],
2602) -> usize {
2603 let device_handle: usize = driver.get_device_handle();
2604 let queue_handle: usize = driver.get_queue_handle();
2605 let blur_down_pso: usize = driver.get_blur_pipeline_handle();
2606 let blur_up_pso: usize = driver.get_blur_up_pipeline_handle();
2607 if device_handle == 0
2608 || queue_handle == 0
2609 || blur_down_pso == 0
2610 || blur_up_pso == 0
2611 || blur_passes.is_empty()
2612 {
2613 return 0;
2614 }
2615 let full_w: u32 = width.max(2);
2616 let full_h: u32 = height.max(2);
2617 let half_w: u32 = (full_w / 2).max(1);
2618 let half_h: u32 = (full_h / 2).max(1);
2619 let src_tex_handle: usize = if driver.get_external_texture_handle() != 0 {
2620 driver.get_external_texture_handle()
2621 } else if driver.get_image_texture_handle() != 0 {
2622 driver.get_image_texture_handle()
2623 } else {
2624 driver.get_glyph_rgba8_texture_handle()
2625 };
2626 if src_tex_handle == 0 {
2627 return 0;
2628 }
2629 let NativeGpuDriver {
2630 blur_half_texture_handle,
2631 blur_full_texture_handle,
2632 blur_texture_dims,
2633 ..
2634 } = driver;
2635 if *blur_half_texture_handle == 0
2636 || *blur_full_texture_handle == 0
2637 || *blur_texture_dims != (full_w, full_h)
2638 {
2639 release_native_gpu_object(*blur_half_texture_handle);
2640 release_native_gpu_object(*blur_full_texture_handle);
2641 let unified_mem: bool = cfg!(target_arch = "aarch64");
2642 *blur_half_texture_handle =
2643 metal_create_offscreen_render_texture(device_handle, half_w, half_h, unified_mem);
2644 *blur_full_texture_handle =
2645 metal_create_offscreen_render_texture(device_handle, full_w, full_h, unified_mem);
2646 *blur_texture_dims = (full_w, full_h);
2647 }
2648 let half_tex: *mut c_void = *blur_half_texture_handle as *mut c_void;
2649 let full_tex: *mut c_void = *blur_full_texture_handle as *mut c_void;
2650 if half_tex.is_null() || full_tex.is_null() {
2651 return 0;
2652 }
2653 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
2654 let sel: &MetalSelectors = cached_metal_selectors();
2655 let queue: *mut c_void = queue_handle as *mut c_void;
2656 let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
2657 if cmd_buf.is_null() {
2658 unsafe { objc_autoreleasePoolPop(pool) };
2659 return 0;
2660 }
2661 let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
2662 if mtl_responds_to_sel(cmd_buf, sel_completed) {
2663 mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
2664 }
2665 let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
2666 let mut executed: usize = 0;
2667 let max_regions: usize = blur_passes.len().min(RENDER_GRAPH_MAX_BLUR_PASSES);
2668 for pass in blur_passes.iter().take(max_regions) {
2669 let blur_offset: f32 = (pass.get_blur_radius() * 0.25).clamp(0.5, 8.0);
2670 let down_uniform: [f32; 4] = [
2671 1.0 / (full_w as f32),
2672 1.0 / (full_h as f32),
2673 blur_offset,
2674 0.0,
2675 ];
2676 let up_uniform: [f32; 4] = [
2677 1.0 / (half_w as f32),
2678 1.0 / (half_h as f32),
2679 blur_offset,
2680 1.0,
2681 ];
2682 let down_ok: bool = metal_encode_fullscreen_blur_pass(
2683 cmd_buf,
2684 pass_cls,
2685 half_tex,
2686 blur_down_pso as *mut c_void,
2687 src_tex_handle as *mut c_void,
2688 &down_uniform,
2689 );
2690 let up_ok: bool = if down_ok {
2691 metal_encode_fullscreen_blur_pass(
2692 cmd_buf,
2693 pass_cls,
2694 full_tex,
2695 blur_up_pso as *mut c_void,
2696 half_tex,
2697 &up_uniform,
2698 )
2699 } else {
2700 false
2701 };
2702 if down_ok && up_ok {
2703 executed = executed.saturating_add(1);
2704 }
2705 }
2706 let _: u64 = SUBMITTED_GPU_FENCE.fetch_add(1, Ordering::AcqRel);
2707 mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
2708 unsafe { objc_autoreleasePoolPop(pool) };
2709 executed
2710}
2711
2712#[cfg(any(target_os = "macos", target_os = "ios"))]
2727fn metal_encode_fullscreen_blur_pass(
2728 cmd_buf: *mut c_void,
2729 pass_cls: *mut c_void,
2730 dst_tex: *mut c_void,
2731 pso: *mut c_void,
2732 src_tex: *mut c_void,
2733 uniform: &[f32; 4],
2734) -> bool {
2735 let sel: &MetalSelectors = cached_metal_selectors();
2736 let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
2737 if pass_desc.is_null() {
2738 return false;
2739 }
2740 let color_atts: *mut c_void = mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
2741 let att0: *mut c_void = unsafe {
2742 let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
2743 transmute(objc_msgSend as *const c_void);
2744 send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
2745 };
2746 if att0.is_null() {
2747 return false;
2748 }
2749 mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, dst_tex);
2750 mtl_send_void_usize(
2751 att0,
2752 sel.set_load_action as *mut c_void,
2753 MTL_LOAD_ACTION_CLEAR,
2754 );
2755 unsafe {
2756 let send_clear: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlClearColor) =
2757 transmute(objc_msgSend as *const c_void);
2758 send_clear(
2759 att0,
2760 sel.set_clear_color as *mut c_void,
2761 MtlClearColor {
2762 red: 0.0,
2763 green: 0.0,
2764 blue: 0.0,
2765 alpha: 1.0,
2766 },
2767 );
2768 }
2769 mtl_send_void_usize(
2770 att0,
2771 sel.set_store_action as *mut c_void,
2772 MTL_STORE_ACTION_STORE,
2773 );
2774 let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
2775 if encoder.is_null() {
2776 return false;
2777 }
2778 mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, pso);
2779 unsafe {
2780 let send_fbytes: unsafe extern "C" fn(
2781 *mut c_void,
2782 *mut c_void,
2783 *const c_void,
2784 usize,
2785 usize,
2786 ) = transmute(objc_msgSend as *const c_void);
2787 let send_ftex: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, usize) =
2788 transmute(objc_msgSend as *const c_void);
2789 let send_draw: unsafe extern "C" fn(
2790 *mut c_void,
2791 *mut c_void,
2792 usize,
2793 usize,
2794 usize,
2795 usize,
2796 usize,
2797 ) = transmute(objc_msgSend as *const c_void);
2798 send_fbytes(
2799 encoder,
2800 sel.set_fragment_bytes as *mut c_void,
2801 uniform.as_ptr().cast::<c_void>(),
2802 size_of::<[f32; 4]>(),
2803 0,
2804 );
2805 send_ftex(encoder, sel.set_fragment_texture as *mut c_void, src_tex, 0);
2806 send_draw(
2807 encoder,
2808 sel.draw_primitives_instanced as *mut c_void,
2809 MTL_PRIMITIVE_TYPE_TRIANGLE,
2810 0,
2811 3,
2812 1,
2813 0,
2814 );
2815 }
2816 mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
2817 true
2818}
2819
2820#[cfg(any(target_os = "macos", target_os = "ios"))]
2836fn metal_encode_gpu_scene_pass(
2837 cmd_buf: *mut c_void,
2838 pass_cls: *mut c_void,
2839 device: *mut c_void,
2840 pipelines: [*mut c_void; 5],
2841 textures: (&mut usize, &mut usize, &mut usize, &mut (u32, u32)),
2842 buffers: (&mut [usize; 6], &mut u64),
2843 scene_pass: &DirectGpuScenePass,
2844) -> Option<*mut c_void> {
2845 let (color_tex_h, depth_tex_h, wake_tex_h, tex_dims): (
2846 &mut usize,
2847 &mut usize,
2848 &mut usize,
2849 &mut (u32, u32),
2850 ) = textures;
2851 let (buf_arr, v3d_rev): (&mut [usize; 6], &mut u64) = buffers;
2852 let [v3d_buf_h, v3d_cap, i3d_buf_h, i3d_cap, boat_buf_h, boat_cap]: &mut [usize; 6] = buf_arr;
2853 let sel: &MetalSelectors = cached_metal_selectors();
2854 let (req_w, req_h, needs_depth): (u32, u32, bool) = match scene_pass {
2855 DirectGpuScenePass::OceanFluid(ocean) => (
2856 ocean.get_target_width().clamp(64, 16384),
2857 ocean.get_target_height().clamp(64, 16384),
2858 false,
2859 ),
2860 DirectGpuScenePass::World3d(world) => (
2861 world.get_target_width().clamp(64, 16384),
2862 world.get_target_height().clamp(64, 16384),
2863 true,
2864 ),
2865 };
2866 if *color_tex_h == 0 || *tex_dims != (req_w, req_h) || (needs_depth && *depth_tex_h == 0) {
2867 release_native_gpu_object(*color_tex_h);
2868 release_native_gpu_object(*depth_tex_h);
2869 let unified_mem: bool = cfg!(target_arch = "aarch64");
2870 *color_tex_h =
2871 metal_create_offscreen_render_texture(device as usize, req_w, req_h, unified_mem);
2872 *depth_tex_h = if needs_depth {
2873 metal_create_depth_texture(device, req_w, req_h)
2874 } else {
2875 0
2876 };
2877 *tex_dims = (req_w, req_h);
2878 }
2879 let color_tex: *mut c_void = *color_tex_h as *mut c_void;
2880 if color_tex.is_null() {
2881 return None;
2882 }
2883 let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
2884 if pass_desc.is_null() {
2885 return None;
2886 }
2887 let color_atts: *mut c_void = mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
2888 let att0: *mut c_void = unsafe {
2889 let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
2890 transmute(objc_msgSend as *const c_void);
2891 send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
2892 };
2893 if att0.is_null() {
2894 return None;
2895 }
2896 mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, color_tex);
2897 mtl_send_void_usize(
2898 att0,
2899 sel.set_load_action as *mut c_void,
2900 MTL_LOAD_ACTION_CLEAR,
2901 );
2902 unsafe {
2903 let send_clear: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlClearColor) =
2904 transmute(objc_msgSend as *const c_void);
2905 send_clear(
2906 att0,
2907 sel.set_clear_color as *mut c_void,
2908 MtlClearColor {
2909 red: 0.0,
2910 green: 0.0,
2911 blue: 0.0,
2912 alpha: 1.0,
2913 },
2914 );
2915 }
2916 mtl_send_void_usize(
2917 att0,
2918 sel.set_store_action as *mut c_void,
2919 MTL_STORE_ACTION_STORE,
2920 );
2921 if needs_depth {
2922 let depth_tex: *mut c_void = *depth_tex_h as *mut c_void;
2923 if depth_tex.is_null() {
2924 return None;
2925 }
2926 let depth_att: *mut c_void = mtl_send_ptr0(pass_desc, sel.depth_attachment as *mut c_void);
2927 if depth_att.is_null() {
2928 return None;
2929 }
2930 mtl_send_void_ptr1(depth_att, sel.set_texture as *mut c_void, depth_tex);
2931 mtl_send_void_usize(
2932 depth_att,
2933 sel.set_load_action as *mut c_void,
2934 MTL_LOAD_ACTION_CLEAR,
2935 );
2936 mtl_send_void_usize(
2937 depth_att,
2938 sel.set_store_action as *mut c_void,
2939 MTL_STORE_ACTION_DONT_CARE,
2940 );
2941 unsafe {
2942 let send_clear_d: unsafe extern "C" fn(*mut c_void, *mut c_void, f64) =
2943 transmute(objc_msgSend as *const c_void);
2944 send_clear_d(depth_att, sel.set_clear_depth as *mut c_void, 1.0);
2945 }
2946 }
2947 let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
2948 if encoder.is_null() {
2949 return None;
2950 }
2951 let viewport: MtlViewport = MtlViewport {
2952 origin_x: 0.0,
2953 origin_y: 0.0,
2954 width: f64::from(req_w),
2955 height: f64::from(req_h),
2956 znear: 0.0,
2957 zfar: 1.0,
2958 };
2959 unsafe {
2960 let send_vp: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlViewport) =
2961 transmute(objc_msgSend as *const c_void);
2962 send_vp(encoder, sel.set_viewport as *mut c_void, viewport);
2963 }
2964 match scene_pass {
2965 DirectGpuScenePass::OceanFluid(ocean) => {
2966 let ocean_pso: *mut c_void = pipelines[0];
2967 let boat_pso: *mut c_void = pipelines[1];
2968 if !ocean_pso.is_null() {
2969 let wake_w: u32 = ocean.get_wake_width().max(1);
2970 let wake_h: u32 = ocean.get_wake_height().max(1);
2971 if (*wake_tex_h == 0 || ocean.get_has_active_wake())
2972 && ocean.get_wake_rgba8().len() >= (wake_w as usize) * (wake_h as usize) * 4
2973 {
2974 let _: bool = metal_upload_texture_dirty_rect(
2975 device as usize,
2976 wake_tex_h,
2977 GpuAtlasPixelFormat::Rgba8Unorm,
2978 (wake_w, wake_h),
2979 (0, 0, wake_w, wake_h),
2980 ocean.get_wake_rgba8().as_slice(),
2981 (wake_w as usize) * 4,
2982 );
2983 }
2984 let sun: [f32; 3] = ocean.get_sun_dir();
2985 let boat_uv: [f32; 2] = ocean.get_boat_uv();
2986 let wf: f32 = req_w as f32;
2987 let hf: f32 = req_h as f32;
2988 let ocean_uniform: [f32; 16] = [
2989 ocean.get_sim_time(),
2990 ocean.get_agitation(),
2991 ocean.get_horizon_v(),
2992 ocean.get_aspect(),
2993 ocean.get_roll_cos(),
2994 ocean.get_roll_sin(),
2995 boat_uv[0],
2996 boat_uv[1],
2997 sun[0],
2998 sun[1],
2999 sun[2],
3000 if ocean.get_has_active_wake() && *wake_tex_h != 0 {
3001 1.0
3002 } else {
3003 0.0
3004 },
3005 wf,
3006 hf,
3007 1.0 / wf.max(1.0),
3008 1.0 / hf.max(1.0),
3009 ];
3010 mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, ocean_pso);
3011 unsafe {
3012 let send_fbytes: unsafe extern "C" fn(
3013 *mut c_void,
3014 *mut c_void,
3015 *const c_void,
3016 usize,
3017 usize,
3018 ) = transmute(objc_msgSend as *const c_void);
3019 let send_ftex: unsafe extern "C" fn(
3020 *mut c_void,
3021 *mut c_void,
3022 *mut c_void,
3023 usize,
3024 ) = transmute(objc_msgSend as *const c_void);
3025 let send_draw: unsafe extern "C" fn(
3026 *mut c_void,
3027 *mut c_void,
3028 usize,
3029 usize,
3030 usize,
3031 usize,
3032 usize,
3033 ) = transmute(objc_msgSend as *const c_void);
3034 send_fbytes(
3035 encoder,
3036 sel.set_fragment_bytes as *mut c_void,
3037 ocean_uniform.as_ptr().cast::<c_void>(),
3038 size_of::<[f32; 16]>(),
3039 0,
3040 );
3041 if *wake_tex_h != 0 {
3042 send_ftex(
3043 encoder,
3044 sel.set_fragment_texture as *mut c_void,
3045 *wake_tex_h as *mut c_void,
3046 0,
3047 );
3048 }
3049 send_draw(
3050 encoder,
3051 sel.draw_primitives_instanced as *mut c_void,
3052 MTL_PRIMITIVE_TYPE_TRIANGLE,
3053 0,
3054 3,
3055 1,
3056 0,
3057 );
3058 }
3059 }
3060 let boat_verts: &[GpuOceanBoatVertex] = ocean.get_boat_vertices().as_slice();
3061 if !boat_pso.is_null() && !boat_verts.is_empty() {
3062 let boat_bytes: &[u8] = unsafe {
3063 from_raw_parts(boat_verts.as_ptr().cast::<u8>(), size_of_val(boat_verts))
3064 };
3065 let boat_buf: *mut c_void =
3066 metal_ensure_and_upload_shared_buffer(device, boat_buf_h, boat_cap, boat_bytes);
3067 if !boat_buf.is_null() {
3068 mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, boat_pso);
3069 unsafe {
3070 let send_vbuf: unsafe extern "C" fn(
3071 *mut c_void,
3072 *mut c_void,
3073 *mut c_void,
3074 usize,
3075 usize,
3076 ) = transmute(objc_msgSend as *const c_void);
3077 let send_draw: unsafe extern "C" fn(
3078 *mut c_void,
3079 *mut c_void,
3080 usize,
3081 usize,
3082 usize,
3083 usize,
3084 usize,
3085 ) = transmute(objc_msgSend as *const c_void);
3086 send_vbuf(
3087 encoder,
3088 sel.set_vertex_buffer as *mut c_void,
3089 boat_buf,
3090 0,
3091 0,
3092 );
3093 send_draw(
3094 encoder,
3095 sel.draw_primitives_instanced as *mut c_void,
3096 MTL_PRIMITIVE_TYPE_TRIANGLE,
3097 0,
3098 boat_verts.len(),
3099 1,
3100 0,
3101 );
3102 }
3103 }
3104 }
3105 }
3106 DirectGpuScenePass::World3d(world) => {
3107 let sky_pso: *mut c_void = pipelines[2];
3108 let mesh_pso: *mut c_void = pipelines[3];
3109 let depth_state: *mut c_void = pipelines[4];
3110 let mut uniform: [f32; 36] = [0.0; 36];
3111 uniform[0..16].copy_from_slice(&world.get_view_proj());
3112 uniform[16..20].copy_from_slice(&world.get_camera_pos());
3113 uniform[20..24].copy_from_slice(&world.get_sun_dir_fog());
3114 uniform[24..28].copy_from_slice(&world.get_sun_color_ambient());
3115 uniform[28..32].copy_from_slice(&world.get_sky_horizon_tod());
3116 uniform[32..36].copy_from_slice(&world.get_sky_zenith_aspect());
3117 if !sky_pso.is_null() {
3118 mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, sky_pso);
3119 unsafe {
3120 let send_fbytes: unsafe extern "C" fn(
3121 *mut c_void,
3122 *mut c_void,
3123 *const c_void,
3124 usize,
3125 usize,
3126 ) = transmute(objc_msgSend as *const c_void);
3127 let send_draw: unsafe extern "C" fn(
3128 *mut c_void,
3129 *mut c_void,
3130 usize,
3131 usize,
3132 usize,
3133 usize,
3134 usize,
3135 ) = transmute(objc_msgSend as *const c_void);
3136 send_fbytes(
3137 encoder,
3138 sel.set_fragment_bytes as *mut c_void,
3139 uniform.as_ptr().cast::<c_void>(),
3140 size_of::<[f32; 36]>(),
3141 0,
3142 );
3143 send_draw(
3144 encoder,
3145 sel.draw_primitives_instanced as *mut c_void,
3146 MTL_PRIMITIVE_TYPE_TRIANGLE,
3147 0,
3148 3,
3149 1,
3150 0,
3151 );
3152 }
3153 }
3154 let mesh_verts: &[GpuWorld3dVertex] = world.get_mesh_buffer().get_vertices().as_slice();
3155 let mesh_insts: &[GpuWorld3dInstance] = world.get_instances().as_slice();
3156 if !mesh_pso.is_null() && !mesh_verts.is_empty() && !mesh_insts.is_empty() {
3157 let mesh_rev: u64 = world.get_mesh_buffer().get_revision();
3158 let vbuf: *mut c_void = if *v3d_buf_h == 0 || *v3d_rev != mesh_rev {
3159 let vert_bytes: &[u8] = unsafe {
3160 from_raw_parts(mesh_verts.as_ptr().cast::<u8>(), size_of_val(mesh_verts))
3161 };
3162 let uploaded: *mut c_void = metal_ensure_and_upload_shared_buffer(
3163 device, v3d_buf_h, v3d_cap, vert_bytes,
3164 );
3165 if !uploaded.is_null() {
3166 *v3d_rev = mesh_rev;
3167 }
3168 uploaded
3169 } else {
3170 *v3d_buf_h as *mut c_void
3171 };
3172 let inst_bytes: &[u8] = unsafe {
3173 from_raw_parts(mesh_insts.as_ptr().cast::<u8>(), size_of_val(mesh_insts))
3174 };
3175 let ibuf: *mut c_void =
3176 metal_ensure_and_upload_shared_buffer(device, i3d_buf_h, i3d_cap, inst_bytes);
3177 if !vbuf.is_null() && !ibuf.is_null() {
3178 mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, mesh_pso);
3179 if !depth_state.is_null() {
3180 mtl_send_void_ptr1(
3181 encoder,
3182 sel.set_depth_stencil_state as *mut c_void,
3183 depth_state,
3184 );
3185 }
3186 unsafe {
3187 let send_vbytes: unsafe extern "C" fn(
3188 *mut c_void,
3189 *mut c_void,
3190 *const c_void,
3191 usize,
3192 usize,
3193 ) = transmute(objc_msgSend as *const c_void);
3194 let send_fbytes: unsafe extern "C" fn(
3195 *mut c_void,
3196 *mut c_void,
3197 *const c_void,
3198 usize,
3199 usize,
3200 ) = transmute(objc_msgSend as *const c_void);
3201 let send_vbuf: unsafe extern "C" fn(
3202 *mut c_void,
3203 *mut c_void,
3204 *mut c_void,
3205 usize,
3206 usize,
3207 ) = transmute(objc_msgSend as *const c_void);
3208 let send_draw: unsafe extern "C" fn(
3209 *mut c_void,
3210 *mut c_void,
3211 usize,
3212 usize,
3213 usize,
3214 usize,
3215 usize,
3216 ) = transmute(objc_msgSend as *const c_void);
3217 send_vbytes(
3218 encoder,
3219 sel.set_vertex_bytes as *mut c_void,
3220 uniform.as_ptr().cast::<c_void>(),
3221 size_of::<[f32; 36]>(),
3222 0,
3223 );
3224 send_fbytes(
3225 encoder,
3226 sel.set_fragment_bytes as *mut c_void,
3227 uniform.as_ptr().cast::<c_void>(),
3228 size_of::<[f32; 36]>(),
3229 0,
3230 );
3231 send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, vbuf, 0, 1);
3232 send_vbuf(encoder, sel.set_vertex_buffer as *mut c_void, ibuf, 0, 2);
3233 for batch in world.get_draw_batches().iter() {
3234 if batch.get_vertex_count() == 0 || batch.get_instance_count() == 0 {
3235 continue;
3236 }
3237 send_draw(
3238 encoder,
3239 sel.draw_primitives_instanced as *mut c_void,
3240 MTL_PRIMITIVE_TYPE_TRIANGLE,
3241 batch.get_vertex_start() as usize,
3242 batch.get_vertex_count() as usize,
3243 batch.get_instance_count() as usize,
3244 batch.get_instance_start() as usize,
3245 );
3246 }
3247 }
3248 }
3249 }
3250 }
3251 }
3252 mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
3253 Some(color_tex)
3254}
3255
3256#[cfg(any(target_os = "macos", target_os = "ios"))]
3272fn metal_begin_ui_render_encoder(
3273 cmd_buf: *mut c_void,
3274 pass_cls: *mut c_void,
3275 target_tex: *mut c_void,
3276 load_spec: (usize, MtlClearColor),
3277 draw_dims: (usize, usize),
3278 pipe_buf: (*mut c_void, *mut c_void),
3279 textures: [*mut c_void; 4],
3280) -> *mut c_void {
3281 let sel: &MetalSelectors = cached_metal_selectors();
3282 let pass_desc: *mut c_void = mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
3283 if pass_desc.is_null() {
3284 return null_mut();
3285 }
3286 let color_atts: *mut c_void = mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
3287 let att0: *mut c_void = unsafe {
3288 let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
3289 transmute(objc_msgSend as *const c_void);
3290 send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
3291 };
3292 if att0.is_null() {
3293 return null_mut();
3294 }
3295 mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, target_tex);
3296 mtl_send_void_usize(att0, sel.set_load_action as *mut c_void, load_spec.0);
3297 mtl_send_void_usize(
3298 att0,
3299 sel.set_store_action as *mut c_void,
3300 MTL_STORE_ACTION_STORE,
3301 );
3302 if load_spec.0 == MTL_LOAD_ACTION_CLEAR {
3303 unsafe {
3304 let send_clear: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlClearColor) =
3305 transmute(objc_msgSend as *const c_void);
3306 send_clear(att0, sel.set_clear_color as *mut c_void, load_spec.1);
3307 }
3308 }
3309 let encoder: *mut c_void = mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
3310 if encoder.is_null() {
3311 return null_mut();
3312 }
3313 mtl_send_void_ptr1(encoder, sel.set_pipeline_state as *mut c_void, pipe_buf.0);
3314 unsafe {
3315 let send_viewport: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlViewport) =
3316 transmute(objc_msgSend as *const c_void);
3317 send_viewport(
3318 encoder,
3319 sel.set_viewport as *mut c_void,
3320 MtlViewport {
3321 origin_x: 0.0,
3322 origin_y: 0.0,
3323 width: draw_dims.0 as f64,
3324 height: draw_dims.1 as f64,
3325 znear: 0.0,
3326 zfar: 1.0,
3327 },
3328 );
3329 if !pipe_buf.1.is_null() {
3330 let send_vbuf: unsafe extern "C" fn(
3331 *mut c_void,
3332 *mut c_void,
3333 *mut c_void,
3334 usize,
3335 usize,
3336 ) = transmute(objc_msgSend as *const c_void);
3337 send_vbuf(
3338 encoder,
3339 sel.set_vertex_buffer as *mut c_void,
3340 pipe_buf.1,
3341 0,
3342 0,
3343 );
3344 }
3345 let send_ftex: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void, usize) =
3346 transmute(objc_msgSend as *const c_void);
3347 for (slot_idx, tex_ptr) in textures.iter().enumerate() {
3348 if !tex_ptr.is_null() {
3349 send_ftex(
3350 encoder,
3351 sel.set_fragment_texture as *mut c_void,
3352 *tex_ptr,
3353 slot_idx,
3354 );
3355 }
3356 }
3357 }
3358 encoder
3359}
3360
3361#[cfg(any(target_os = "macos", target_os = "ios"))]
3371fn metal_encode_ui_batch_draw(
3372 encoder: *mut c_void,
3373 draw_dims: (usize, usize),
3374 batch: &GpuBatch,
3375 count: usize,
3376 base_instance: usize,
3377) {
3378 let sel: &MetalSelectors = cached_metal_selectors();
3379 let (draw_w, draw_h): (usize, usize) = draw_dims;
3380 let uniform: GpuLayerUniform =
3381 GpuLayerUniform::new(draw_w as f32, draw_h as f32, batch.get_scroll_offset());
3382 let rect_bounds: Rect = batch.get_scissor();
3383 let sx: usize = (rect_bounds.get_x().max(0.0).floor() as usize).min(draw_w.saturating_sub(1));
3384 let sy: usize = (rect_bounds.get_y().max(0.0).floor() as usize).min(draw_h.saturating_sub(1));
3385 let sw: usize = (rect_bounds.get_width().max(1.0).ceil() as usize)
3386 .min(draw_w.saturating_sub(sx))
3387 .max(1);
3388 let sh: usize = (rect_bounds.get_height().max(1.0).ceil() as usize)
3389 .min(draw_h.saturating_sub(sy))
3390 .max(1);
3391 unsafe {
3392 let send_vbytes: unsafe extern "C" fn(
3393 *mut c_void,
3394 *mut c_void,
3395 *const c_void,
3396 usize,
3397 usize,
3398 ) = transmute(objc_msgSend as *const c_void);
3399 let send_scissor: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlScissorRect) =
3400 transmute(objc_msgSend as *const c_void);
3401 let send_draw: unsafe extern "C" fn(
3402 *mut c_void,
3403 *mut c_void,
3404 usize,
3405 usize,
3406 usize,
3407 usize,
3408 usize,
3409 ) = transmute(objc_msgSend as *const c_void);
3410 send_vbytes(
3411 encoder,
3412 sel.set_vertex_bytes as *mut c_void,
3413 (&uniform as *const GpuLayerUniform).cast::<c_void>(),
3414 size_of::<GpuLayerUniform>(),
3415 1,
3416 );
3417 send_scissor(
3418 encoder,
3419 sel.set_scissor_rect as *mut c_void,
3420 MtlScissorRect {
3421 x: sx,
3422 y: sy,
3423 width: sw,
3424 height: sh,
3425 },
3426 );
3427 send_draw(
3428 encoder,
3429 sel.draw_primitives_instanced as *mut c_void,
3430 MTL_PRIMITIVE_TYPE_TRIANGLE,
3431 0,
3432 6,
3433 count,
3434 base_instance,
3435 );
3436 }
3437}
3438
3439#[cfg(any(target_os = "macos", target_os = "ios"))]
3451fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
3452 let total_instances: usize = batches
3453 .iter()
3454 .map(|blue_val: &GpuBatch| {
3455 blue_val
3456 .get_primitives()
3457 .len()
3458 .max(blue_val.get_instances().len())
3459 })
3460 .sum();
3461 if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
3462 return total_instances;
3463 }
3464 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
3465 let device: *mut c_void = device_handle as *mut c_void;
3466 let queue: *mut c_void = queue_handle as *mut c_void;
3467 let sel: &MetalSelectors = cached_metal_selectors();
3468 let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
3469 let sel_rel: *mut c_void = sel.release as *mut c_void;
3470 unsafe {
3471 let send_buf: unsafe extern "C" fn(
3472 *mut c_void,
3473 *mut c_void,
3474 *const c_void,
3475 usize,
3476 usize,
3477 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
3478 for batch in batches.iter() {
3479 let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
3480 if !prims.is_empty() {
3481 let byte_len: usize = size_of_val(prims);
3482 let mtl_buf: *mut c_void = send_buf(
3483 device,
3484 sel_buf,
3485 prims.as_ptr().cast::<c_void>(),
3486 byte_len,
3487 0,
3488 );
3489 if !mtl_buf.is_null() {
3490 mtl_send_void0(mtl_buf, sel_rel);
3491 }
3492 } else {
3493 let instances: &[GpuQuadInstance] = batch.get_instances();
3494 if instances.is_empty() {
3495 continue;
3496 }
3497 let byte_len: usize = size_of_val(instances);
3498 let mtl_buf: *mut c_void = send_buf(
3499 device,
3500 sel_buf,
3501 instances.as_ptr().cast::<c_void>(),
3502 byte_len,
3503 0,
3504 );
3505 if !mtl_buf.is_null() {
3506 mtl_send_void0(mtl_buf, sel_rel);
3507 }
3508 }
3509 }
3510 let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
3511 if !cmd_buf.is_null() {
3512 mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
3513 }
3514 objc_autoreleasePoolPop(pool);
3515 }
3516 total_instances
3517}
3518
3519#[cfg(any(target_os = "macos", target_os = "ios"))]
3527fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
3528 let sel_rel: *mut c_void = cached_metal_selectors().release as *mut c_void;
3529 if library_handle != 0 {
3530 mtl_send_void0(library_handle as *mut c_void, sel_rel);
3531 }
3532 if queue_handle != 0 {
3533 mtl_send_void0(queue_handle as *mut c_void, sel_rel);
3534 }
3535 if device_handle != 0 {
3536 mtl_send_void0(device_handle as *mut c_void, sel_rel);
3537 }
3538}
3539
3540#[cfg(target_os = "windows")]
3541#[link(name = "kernel32")]
3542unsafe extern "system" {
3543 fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
3553 fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
3564}
3565
3566#[cfg(target_os = "windows")]
3576fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
3577 let cached: &WindowsD3d12ProbeCache = WINDOWS_D3D12_CACHE.get_or_init(|| unsafe {
3578 let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
3579 let has_d3d12: bool = if !d3d12_mod.is_null() {
3580 !GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr()).is_null()
3581 } else {
3582 false
3583 };
3584 let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
3585 let has_compiler: bool = if !compiler_mod.is_null() {
3586 !GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr()).is_null()
3587 } else {
3588 false
3589 };
3590 WindowsD3d12ProbeCache {
3591 has_d3d12,
3592 has_compiler,
3593 }
3594 });
3595 let has_runtime: bool = cached.has_d3d12 && cached.has_compiler;
3596 let label: &str = if cached.has_d3d12 {
3597 GPU_DEVICE_D3D12
3598 } else {
3599 GPU_DEVICE_FALLBACK
3600 };
3601 (
3602 GpuAdapterInfo::new(backend, label.to_string(), has_runtime, false),
3603 0,
3604 0,
3605 0,
3606 )
3607}
3608
3609#[cfg(any(target_os = "linux", target_os = "android"))]
3610unsafe extern "C" {
3611 fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
3622 fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
3633}
3634
3635#[cfg(any(target_os = "linux", target_os = "android"))]
3645fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
3646 let cached: &VulkanProbeCache = VULKAN_PROBE_CACHE.get_or_init(|| {
3647 let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
3648 return VulkanProbeCache {
3649 available: false,
3650 lib_handle: 0,
3651 };
3652 };
3653 let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
3654 return VulkanProbeCache {
3655 available: false,
3656 lib_handle: 0,
3657 };
3658 };
3659 let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
3660 return VulkanProbeCache {
3661 available: false,
3662 lib_handle: 0,
3663 };
3664 };
3665 unsafe {
3666 let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
3667 if handle.is_null() {
3668 VulkanProbeCache {
3669 available: false,
3670 lib_handle: 0,
3671 }
3672 } else {
3673 let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
3674 let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
3675 VulkanProbeCache {
3676 available: !p1.is_null() && !p2.is_null(),
3677 lib_handle: handle as usize,
3678 }
3679 }
3680 }
3681 });
3682 let name: &str = if cached.available {
3683 GPU_DEVICE_VULKAN
3684 } else {
3685 GPU_DEVICE_FALLBACK
3686 };
3687 (
3688 GpuAdapterInfo::new(backend, name.to_string(), cached.available, false),
3689 cached.lib_handle,
3690 0,
3691 0,
3692 )
3693}
3694
3695#[cfg(target_arch = "wasm32")]
3705pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
3706 let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
3707 gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
3708 gl.compile_shader(&vs);
3709 let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
3710 gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
3711 gl.compile_shader(&fs);
3712 let program: WebGlProgram = gl.create_program()?;
3713 gl.attach_shader(&program, &vs);
3714 gl.attach_shader(&program, &fs);
3715 gl.link_program(&program);
3716 Some(program)
3717}
3718
3719#[must_use]
3725pub const fn gles3_ui_instance_attribs() -> [Gles3InstanceAttribSpec; 5] {
3726 let stride: i32 = GPU_PRIMITIVE_INSTANCE_BYTES as i32;
3727 [
3728 Gles3InstanceAttribSpec {
3729 location: 1,
3730 components: 4,
3731 is_integer: false,
3732 byte_offset: 0,
3733 stride,
3734 },
3735 Gles3InstanceAttribSpec {
3736 location: 2,
3737 components: 4,
3738 is_integer: false,
3739 byte_offset: 16,
3740 stride,
3741 },
3742 Gles3InstanceAttribSpec {
3743 location: 3,
3744 components: 2,
3745 is_integer: true,
3746 byte_offset: 32,
3747 stride,
3748 },
3749 Gles3InstanceAttribSpec {
3750 location: 4,
3751 components: 4,
3752 is_integer: true,
3753 byte_offset: 40,
3754 stride,
3755 },
3756 Gles3InstanceAttribSpec {
3757 location: 5,
3758 components: 2,
3759 is_integer: true,
3760 byte_offset: 56,
3761 stride,
3762 },
3763 ]
3764}
3765
3766#[must_use]
3780pub fn gles3_scissor_from_top_down(
3781 surface_h: u32,
3782 sx: u32,
3783 sy: u32,
3784 stroke_width: u32,
3785 sh: u32,
3786) -> [i32; 4] {
3787 let y1: u32 = sy.saturating_add(sh).min(surface_h);
3788 let y_bottom: u32 = surface_h.saturating_sub(y1);
3789 [sx as i32, y_bottom as i32, stroke_width as i32, sh as i32]
3790}
3791
3792#[must_use]
3805pub fn select_adaptive_upload_plan(
3806 fb_w: u32,
3807 fb_h: u32,
3808 dirty_rects: &[PixelDirtyRect],
3809 force_full: bool,
3810) -> AdaptiveUploadPlan {
3811 if fb_w == 0 || fb_h == 0 {
3812 return AdaptiveUploadPlan {
3813 strategy: MobileUploadStrategy::None,
3814 rects: Vec::new(),
3815 total_upload_bytes: 0,
3816 merged_bbox_bytes: 0,
3817 full_frame_bytes: 0,
3818 estimated_cost_score: 0.0,
3819 };
3820 }
3821 let full_rect: PixelDirtyRect = PixelDirtyRect::new(0, 0, fb_w, fb_h);
3822 let full_bytes: usize = full_rect.byte_size_rgba8();
3823 if force_full {
3824 return AdaptiveUploadPlan {
3825 strategy: MobileUploadStrategy::FullFrame,
3826 rects: vec![full_rect],
3827 total_upload_bytes: full_bytes,
3828 merged_bbox_bytes: full_bytes,
3829 full_frame_bytes: full_bytes,
3830 estimated_cost_score: (full_bytes + MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES) as f32,
3831 };
3832 }
3833 let mut coalesced: Vec<PixelDirtyRect> = Vec::with_capacity(dirty_rects.len().min(16));
3834 for rect in dirty_rects.iter() {
3835 let Some(mut clamped) = rect.clamp_to(fb_w, fb_h) else {
3836 continue;
3837 };
3838 let mut merged_any: bool = true;
3839 while merged_any {
3840 merged_any = false;
3841 let mut idx: usize = 0;
3842 while idx < coalesced.len() {
3843 if coalesced[idx].intersects_or_adjacent(clamped, MOBILE_UPLOAD_COALESCE_PAD_PX) {
3844 let existing: PixelDirtyRect = coalesced.swap_remove(idx);
3845 clamped = clamped.union_with(existing);
3846 merged_any = true;
3847 } else {
3848 idx += 1;
3849 }
3850 }
3851 }
3852 coalesced.push(clamped);
3853 }
3854 if coalesced.is_empty() {
3855 return AdaptiveUploadPlan {
3856 strategy: MobileUploadStrategy::None,
3857 rects: Vec::new(),
3858 total_upload_bytes: 0,
3859 merged_bbox_bytes: 0,
3860 full_frame_bytes: full_bytes,
3861 estimated_cost_score: 0.0,
3862 };
3863 }
3864 let mut merged_bbox: PixelDirtyRect = coalesced[0];
3865 let mut multi_bytes: usize = 0;
3866 for red_val in coalesced.iter() {
3867 merged_bbox = merged_bbox.union_with(*red_val);
3868 multi_bytes = multi_bytes.saturating_add(red_val.byte_size_rgba8());
3869 }
3870 let merged_bytes: usize = merged_bbox.byte_size_rgba8();
3871 let multi_cost: usize = multi_bytes.saturating_add(
3872 coalesced
3873 .len()
3874 .saturating_mul(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES),
3875 );
3876 let merged_cost: usize = merged_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
3877 let full_threshold_bytes: usize =
3878 ((full_bytes as f32) * MOBILE_UPLOAD_FULL_FRAME_COVERAGE_THRESHOLD).round() as usize;
3879 let full_cost: usize = full_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
3880 let multi_eligible: bool = coalesced.len() >= 2
3881 && coalesced.len() <= MOBILE_MAX_MULTI_UPLOAD_RECTS
3882 && multi_bytes <= full_threshold_bytes
3883 && multi_cost < merged_cost
3884 && multi_cost < full_cost;
3885 if multi_eligible {
3886 return AdaptiveUploadPlan {
3887 strategy: MobileUploadStrategy::MultiRect,
3888 rects: coalesced,
3889 total_upload_bytes: multi_bytes,
3890 merged_bbox_bytes: merged_bytes,
3891 full_frame_bytes: full_bytes,
3892 estimated_cost_score: multi_cost as f32,
3893 };
3894 }
3895 if merged_bytes <= full_threshold_bytes && merged_cost < full_cost {
3896 return AdaptiveUploadPlan {
3897 strategy: MobileUploadStrategy::MergedBbox,
3898 rects: vec![merged_bbox],
3899 total_upload_bytes: merged_bytes,
3900 merged_bbox_bytes: merged_bytes,
3901 full_frame_bytes: full_bytes,
3902 estimated_cost_score: merged_cost as f32,
3903 };
3904 }
3905 AdaptiveUploadPlan {
3906 strategy: MobileUploadStrategy::FullFrame,
3907 rects: vec![full_rect],
3908 total_upload_bytes: full_bytes,
3909 merged_bbox_bytes: merged_bytes,
3910 full_frame_bytes: full_bytes,
3911 estimated_cost_score: full_cost as f32,
3912 }
3913}
3914
3915#[must_use]
3927pub fn damage_region_to_pixel_dirty_rects(
3928 damage: DamageRegion,
3929 fb_w: u32,
3930 fb_h: u32,
3931) -> Vec<PixelDirtyRect> {
3932 if fb_w == 0 || fb_h == 0 {
3933 return Vec::new();
3934 }
3935 if damage.get_full_damage() {
3936 return vec![PixelDirtyRect::new(0, 0, fb_w, fb_h)];
3937 }
3938 let Some(red_val) = damage.resolve(fb_w, fb_h) else {
3939 return Vec::new();
3940 };
3941 let rx0: u32 = (red_val.get_x().floor().max(0.0) as u32).min(fb_w);
3942 let ry0: u32 = (red_val.get_y().floor().max(0.0) as u32).min(fb_h);
3943 let rx1: u32 = (red_val.right().ceil().max(0.0) as u32).clamp(rx0, fb_w);
3944 let ry1: u32 = (red_val.bottom().ceil().max(0.0) as u32).clamp(ry0, fb_h);
3945 if rx1 > rx0 && ry1 > ry0 {
3946 vec![PixelDirtyRect::new(rx0, ry0, rx1 - rx0, ry1 - ry0)]
3947 } else {
3948 Vec::new()
3949 }
3950}
3951
3952#[must_use]
3966pub fn build_direct_gpu_frame_batch_from_batches(
3967 viewport_width: u32,
3968 viewport_height: u32,
3969 clear_color: Color,
3970 batches: &[GpuBatch],
3971 blur_passes: &[GpuBackdropBlurPass],
3972) -> DirectGpuFrameBatch {
3973 let total_prims: usize = batches
3974 .iter()
3975 .map(|blue_val: &GpuBatch| {
3976 blue_val
3977 .get_primitives()
3978 .len()
3979 .max(blue_val.get_instances().len())
3980 })
3981 .sum();
3982 let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(total_prims);
3983 let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(batches.len());
3984 let vw: u32 = viewport_width.max(1);
3985 let vh: u32 = viewport_height.max(1);
3986 for batch in batches.iter() {
3987 let base_instance: u32 = primitives.len() as u32;
3988 if !batch.get_primitives().is_empty() {
3989 primitives.extend_from_slice(batch.get_primitives());
3990 } else {
3991 for quad in batch.get_instances().iter() {
3992 primitives.push(GpuPrimitiveInstance::from_quad_instance(
3993 quad,
3994 batch.get_texture_slot(),
3995 batch.get_layer_id(),
3996 ));
3997 }
3998 }
3999 let instance_count: u32 = (primitives.len() as u32).saturating_sub(base_instance);
4000 if instance_count == 0 {
4001 continue;
4002 }
4003 let rect_bounds: Rect = batch.get_scissor();
4004 let sx: u32 = (rect_bounds.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
4005 let sy: u32 = (rect_bounds.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
4006 let stroke_width: u32 = (rect_bounds.get_width().max(1.0).ceil() as u32)
4007 .min(vw.saturating_sub(sx))
4008 .max(1);
4009 let sh: u32 = (rect_bounds.get_height().max(1.0).ceil() as u32)
4010 .min(vh.saturating_sub(sy))
4011 .max(1);
4012 let scroll: [f32; 2] = batch.get_scroll_offset();
4013 draw_ranges.push(DirectGpuBatchRange {
4014 base_instance,
4015 instance_count,
4016 scissor_x: sx,
4017 scissor_y: sy,
4018 scissor_w: stroke_width,
4019 scissor_h: sh,
4020 scroll_x: scroll[0],
4021 scroll_y: scroll[1],
4022 texture_slot: batch.get_texture_slot(),
4023 layer_id: batch.get_layer_id(),
4024 pad: [0, 0],
4025 });
4026 }
4027 let instance_upload_bytes: usize = primitives
4028 .len()
4029 .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
4030 DirectGpuFrameBatch {
4031 viewport_width: vw,
4032 viewport_height: vh,
4033 clear_rgba: clear_color.to_f32_array(),
4034 primitives,
4035 draw_ranges,
4036 backdrop_blurs: blur_passes.to_vec(),
4037 glyph_r8_atlas: None,
4038 image_rgba8_atlas: None,
4039 instance_upload_bytes,
4040 cpu_mirror_active: false,
4041 upload_strategy: MobileUploadStrategy::DirectGpu,
4042 }
4043}
4044
4045fn push_direct_gpu_primitive(
4056 primitives: &mut Vec<GpuPrimitiveInstance>,
4057 draw_ranges: &mut Vec<DirectGpuBatchRange>,
4058 prim: GpuPrimitiveInstance,
4059 clip: Rect,
4060 vw: u32,
4061 vh: u32,
4062) {
4063 if clip.get_width() <= 0.0 || clip.get_height() <= 0.0 {
4064 return;
4065 }
4066 let sx: u32 = (clip.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
4067 let sy: u32 = (clip.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
4068 let stroke_width: u32 = (clip.get_width().max(1.0).ceil() as u32)
4069 .min(vw.saturating_sub(sx))
4070 .max(1);
4071 let sh: u32 = (clip.get_height().max(1.0).ceil() as u32)
4072 .min(vh.saturating_sub(sy))
4073 .max(1);
4074 let layer_id: u8 = prim.layer_id();
4075 let base: u32 = primitives.len() as u32;
4076 primitives.push(prim);
4077 if let Some(last) = draw_ranges.last_mut()
4078 && last.get_scissor_x() == sx
4079 && last.get_scissor_y() == sy
4080 && last.get_scissor_w() == stroke_width
4081 && last.get_scissor_h() == sh
4082 && last.get_layer_id() == layer_id
4083 && last.get_instance_count() < MAX_QUADS_PER_BATCH as u32
4084 {
4085 last.set_instance_count(last.get_instance_count().saturating_add(1));
4086 return;
4087 }
4088 draw_ranges.push(DirectGpuBatchRange {
4089 base_instance: base,
4090 instance_count: 1,
4091 scissor_x: sx,
4092 scissor_y: sy,
4093 scissor_w: stroke_width,
4094 scissor_h: sh,
4095 scroll_x: 0.0,
4096 scroll_y: 0.0,
4097 texture_slot: 0,
4098 layer_id,
4099 pad: [0, 0],
4100 });
4101}
4102
4103fn encode_atlas_uv_rect(
4118 atlas_w: u32,
4119 atlas_h: u32,
4120 pos_x: u32,
4121 pos_y: u32,
4122 width_val: u32,
4123 height_val: u32,
4124) -> [u16; 4] {
4125 let inv_w: f32 = 1.0 / (atlas_w.max(1) as f32);
4126 let inv_h: f32 = 1.0 / (atlas_h.max(1) as f32);
4127 let u0: u16 = (((pos_x as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
4128 let v0: u16 = (((pos_y as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
4129 let u1: u16 = ((((pos_x + width_val) as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
4130 let v1: u16 =
4131 ((((pos_y + height_val) as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
4132 [u0, v0, u1, v1]
4133}
4134
4135fn pack_frame_image_atlas(
4146 images: &[DirectGpuImageSlice<'_>],
4147 revision: u64,
4148) -> (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) {
4149 if images.is_empty() {
4150 return (None, Vec::new());
4151 }
4152 let mut max_w: u32 = 1;
4153 let mut sum_w: u32 = 1;
4154 for entry in images.iter() {
4155 let cw: u32 = entry.crop.get_width();
4156 max_w = max_w.max(cw.saturating_add(2));
4157 sum_w = sum_w.saturating_add(cw.saturating_add(1));
4158 }
4159 let atlas_w: u32 = sum_w
4160 .clamp(64, 2048)
4161 .max(max_w)
4162 .next_power_of_two()
4163 .min(16384);
4164 let mut placements: Vec<(u32, u32, u32, u32)> = Vec::with_capacity(images.len());
4165 let mut cx: u32 = 1;
4166 let mut cy: u32 = 1;
4167 let mut shelf_h: u32 = 0;
4168 for entry in images.iter() {
4169 let clamped_w: u32 = entry.crop.get_width().min(atlas_w.saturating_sub(2)).max(1);
4170 let clamped_h: u32 = entry.crop.get_height().max(1);
4171 if cx + clamped_w + 1 > atlas_w {
4172 cx = 1;
4173 cy = cy.saturating_add(shelf_h).saturating_add(1);
4174 shelf_h = 0;
4175 }
4176 placements.push((cx, cy, clamped_w, clamped_h));
4177 cx = cx.saturating_add(clamped_w).saturating_add(1);
4178 shelf_h = shelf_h.max(clamped_h);
4179 }
4180 let atlas_h: u32 = cy.saturating_add(shelf_h).saturating_add(1).max(64);
4181 let mut pixels: Vec<u8> = vec![0; (atlas_w as usize) * (atlas_h as usize) * 4];
4182 let mut uvs: Vec<[u16; 4]> = Vec::with_capacity(images.len());
4183 for (idx, entry) in images.iter().enumerate() {
4184 let (dx, dy, copy_w, copy_h): (u32, u32, u32, u32) = placements[idx];
4185 let sx: u32 = entry.crop.get_x();
4186 let sy: u32 = entry.crop.get_y();
4187 let valid_w: u32 = copy_w.min(entry.src_w.saturating_sub(sx));
4188 let valid_h: u32 = copy_h.min(entry.src_h.saturating_sub(sy));
4189 for row in 0..valid_h {
4190 let src_off: usize =
4191 (((sy + row) as usize) * (entry.src_w as usize) + (sx as usize)) * 4;
4192 let dst_off: usize = (((dy + row) as usize) * (atlas_w as usize) + (dx as usize)) * 4;
4193 let row_bytes: usize = (valid_w as usize) * 4;
4194 if src_off + row_bytes <= entry.pixels.len() && dst_off + row_bytes <= pixels.len() {
4195 pixels[dst_off..dst_off + row_bytes]
4196 .copy_from_slice(&entry.pixels[src_off..src_off + row_bytes]);
4197 }
4198 }
4199 uvs.push(encode_atlas_uv_rect(
4200 atlas_w, atlas_h, dx, dy, valid_w, valid_h,
4201 ));
4202 }
4203 (
4204 Some(DirectGpuAtlasUpload {
4205 width: atlas_w,
4206 height: atlas_h,
4207 revision,
4208 pixels,
4209 }),
4210 uvs,
4211 )
4212}
4213
4214#[must_use]
4227pub fn compile_display_list_direct_gpu_batch(
4228 display_list: &DisplayList,
4229 mut glyph_atlas: Option<&mut GlyphAtlas>,
4230 font_provider: Option<&NativeSystemFont>,
4231 last_glyph_revision: u64,
4232) -> DirectGpuFrameBatch {
4233 let scale: f32 = display_list.get_scale_factor().max(0.5);
4234 let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
4235 let phys_h: u32 = ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
4236 let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
4237 let mut clip_stack: Vec<(Rect, Rect, u16)> = Vec::with_capacity(16);
4238 clip_stack.push((full_clip, full_clip, 0));
4239 let mut primitives: Vec<GpuPrimitiveInstance> =
4240 Vec::with_capacity(display_list.get_commands().len().saturating_mul(2));
4241 let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(16);
4242 let mut backdrop_blurs: Vec<GpuBackdropBlurPass> = Vec::new();
4243 let mut glyph_fixups: Vec<(usize, GlyphKey)> = Vec::new();
4244 let mut image_entries: Vec<DirectGpuImageSlice<'_>> = Vec::new();
4245 let mut image_fixups: Vec<(usize, usize)> = Vec::new();
4246 let mut clear_rgba: [f32; 4] = COLOR_WHITE.to_f32_array();
4247 let mut active_layer_id: u8 = 0;
4248 for cmd in display_list.get_commands().iter() {
4249 let (active_clip, safe_inner_clip, active_rounded_bits): (Rect, Rect, u16) = clip_stack
4250 .last()
4251 .copied()
4252 .unwrap_or((full_clip, full_clip, 0));
4253 let clip_arr: [f32; 4] = [
4254 active_clip.get_x(),
4255 active_clip.get_y(),
4256 active_clip.right(),
4257 active_clip.bottom(),
4258 ];
4259 let cmd_prim_start: usize = primitives.len();
4260 match cmd {
4261 DrawCommand::Clear(char_item) => {
4262 clear_rgba = char_item.to_f32_array();
4263 }
4264 DrawCommand::PushClip(rect) => {
4265 let phys: Rect = snap_physical_rect(*rect, scale);
4266 let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
4267 let next_safe: Rect = safe_inner_clip.intersect(phys).unwrap_or_default();
4268 let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
4269 active_clip,
4270 active_rounded_bits,
4271 next_scissor,
4272 phys,
4273 None,
4274 );
4275 clip_stack.push((next_scissor, next_safe, next_bits));
4276 }
4277 DrawCommand::PushRoundedClip { rect, radius } => {
4278 let phys: Rect = snap_physical_rect(*rect, scale);
4279 let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
4280 let phys_radius: CornerRadius = CornerRadius::new(
4281 radius.get_top_left() * scale,
4282 radius.get_top_right() * scale,
4283 radius.get_bottom_right() * scale,
4284 radius.get_bottom_left() * scale,
4285 );
4286 let max_r: f32 = phys_radius.max_radius().ceil();
4287 let inset_w: f32 = (phys.get_width() - max_r * 2.0).max(0.0);
4288 let inset_h: f32 = (phys.get_height() - max_r * 2.0).max(0.0);
4289 let rounded_safe: Rect =
4290 Rect::new(phys.get_x() + max_r, phys.get_y() + max_r, inset_w, inset_h);
4291 let next_safe: Rect = safe_inner_clip.intersect(rounded_safe).unwrap_or_default();
4292 let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
4293 active_clip,
4294 active_rounded_bits,
4295 next_scissor,
4296 phys,
4297 Some(phys_radius),
4298 );
4299 clip_stack.push((next_scissor, next_safe, next_bits));
4300 }
4301 DrawCommand::PopClip => {
4302 if clip_stack.len() > 1 {
4303 let _: Option<(Rect, Rect, u16)> = clip_stack.pop();
4304 }
4305 }
4306 DrawCommand::FillRoundedRect {
4307 rect,
4308 color,
4309 radius,
4310 border,
4311 } => {
4312 let snapped: Rect = snap_physical_rect(*rect, scale);
4313 let quad: [f32; 4] = [
4314 snapped.get_x(),
4315 snapped.get_y(),
4316 snapped.get_width(),
4317 snapped.get_height(),
4318 ];
4319 if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
4320 continue;
4321 }
4322 let border_width: f32 = if border.get_width() > 0.0 {
4323 (border.get_width() * scale).round().max(1.0)
4324 } else {
4325 0.0
4326 };
4327 let query_val: GpuQuadInstance = GpuQuadInstance {
4328 rect: quad,
4329 clip: clip_arr,
4330 color: color.to_f32_array(),
4331 secondary_color: border.get_color().to_f32_array(),
4332 radii: [
4333 radius.get_top_left() * scale,
4334 radius.get_top_right() * scale,
4335 radius.get_bottom_right() * scale,
4336 radius.get_bottom_left() * scale,
4337 ],
4338 stroke_or_blur: border_width,
4339 angle_rad: 0.0,
4340 kind: GpuPrimitiveKind::RoundedRect as u32,
4341 reserved: 0,
4342 };
4343 push_direct_gpu_primitive(
4344 &mut primitives,
4345 &mut draw_ranges,
4346 GpuPrimitiveInstance::from_quad_instance(&query_val, 0, active_layer_id),
4347 active_clip,
4348 phys_w,
4349 phys_h,
4350 );
4351 }
4352 DrawCommand::LinearGradientRect {
4353 rect,
4354 gradient,
4355 radius,
4356 } => {
4357 let snapped: Rect = snap_physical_rect(*rect, scale);
4358 let quad: [f32; 4] = [
4359 snapped.get_x(),
4360 snapped.get_y(),
4361 snapped.get_width(),
4362 snapped.get_height(),
4363 ];
4364 if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
4365 continue;
4366 }
4367 let quat_val: GpuQuadInstance = GpuQuadInstance {
4368 rect: quad,
4369 clip: clip_arr,
4370 color: gradient.get_start_color().to_f32_array(),
4371 secondary_color: gradient.get_end_color().to_f32_array(),
4372 radii: [
4373 radius.get_top_left() * scale,
4374 radius.get_top_right() * scale,
4375 radius.get_bottom_right() * scale,
4376 radius.get_bottom_left() * scale,
4377 ],
4378 stroke_or_blur: 0.0,
4379 angle_rad: gradient.get_angle_deg().to_radians(),
4380 kind: GpuPrimitiveKind::Gradient as u32,
4381 reserved: 0,
4382 };
4383 push_direct_gpu_primitive(
4384 &mut primitives,
4385 &mut draw_ranges,
4386 GpuPrimitiveInstance::from_quad_instance(&quat_val, 0, active_layer_id),
4387 active_clip,
4388 phys_w,
4389 phys_h,
4390 );
4391 }
4392 DrawCommand::BoxShadow {
4393 rect,
4394 radius,
4395 shadow,
4396 } => {
4397 let spread: f32 = shadow.get_spread_radius() * scale;
4398 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
4399 let sigma: f32 = (blur * 0.5).max(0.75);
4400 let pad: f32 = (sigma * 3.0).ceil();
4401 let base_rect: Rect = snap_physical_rect(*rect, scale);
4402 let cx: f32 = base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
4403 let cy: f32 = base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
4404 let cw: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
4405 let ch: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
4406 let corner_vec: GpuQuadInstance = GpuQuadInstance {
4407 rect: [cx - pad, cy - pad, cw + pad * 2.0, ch + pad * 2.0],
4408 clip: clip_arr,
4409 color: shadow.get_color().to_f32_array(),
4410 secondary_color: [0.0; 4],
4411 radii: [
4412 (radius.get_top_left() * scale + spread).max(0.0),
4413 (radius.get_top_right() * scale + spread).max(0.0),
4414 (radius.get_bottom_right() * scale + spread).max(0.0),
4415 (radius.get_bottom_left() * scale + spread).max(0.0),
4416 ],
4417 stroke_or_blur: sigma,
4418 angle_rad: pad,
4419 kind: GpuPrimitiveKind::Shadow as u32,
4420 reserved: 0,
4421 };
4422 push_direct_gpu_primitive(
4423 &mut primitives,
4424 &mut draw_ranges,
4425 GpuPrimitiveInstance::from_quad_instance(&corner_vec, 0, active_layer_id),
4426 active_clip,
4427 phys_w,
4428 phys_h,
4429 );
4430 }
4431 DrawCommand::BackdropBlur {
4432 rect,
4433 radius,
4434 blur_radius,
4435 } => {
4436 let snapped: Rect = snap_physical_rect(*rect, scale);
4437 let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 96.0);
4438 let radii_px: [f32; 4] = [
4439 radius.get_top_left() * scale,
4440 radius.get_top_right() * scale,
4441 radius.get_bottom_right() * scale,
4442 radius.get_bottom_left() * scale,
4443 ];
4444 let halo: Rect = Rect::new(
4445 (snapped.get_x() - phys_blur).max(0.0),
4446 (snapped.get_y() - phys_blur).max(0.0),
4447 (snapped.get_width() + phys_blur * 2.0).min(phys_w as f32),
4448 (snapped.get_height() + phys_blur * 2.0).min(phys_h as f32),
4449 );
4450 backdrop_blurs.push(GpuBackdropBlurPass {
4451 bounds: snapped,
4452 input_bounds: halo,
4453 clip_rect: active_clip,
4454 radii: radii_px,
4455 blur_radius: phys_blur,
4456 layer_id: active_layer_id,
4457 });
4458 active_layer_id = active_layer_id.saturating_add(1);
4459 }
4460 DrawCommand::TextRun { rect, text, style } => {
4461 if text.is_empty()
4462 || active_clip.get_width() <= 0.0
4463 || active_clip.get_height() <= 0.0
4464 {
4465 continue;
4466 }
4467 if let Some(atlas) = glyph_atlas.as_deref_mut() {
4468 let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
4469 let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
4470 text,
4471 *style,
4472 Some(rect.get_width().max(1.0)),
4473 );
4474 let line_h: f32 = meas.get_line_height_px() * scale;
4475 let letter_sp: f32 = style.get_letter_spacing() * scale;
4476 let rect_w_px: f32 = rect.get_width() * scale;
4477 let color_rgba: u32 = GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
4478 let kind_flags: u32 = GpuPrimitiveInstance::pack_kind_flags(
4479 PrimKind::GlyphAlpha8,
4480 0,
4481 0,
4482 active_layer_id,
4483 );
4484 let mut line_glyphs: Vec<(Option<GlyphKey>, u32, u32, f32)> = Vec::new();
4485 for (line_idx, line) in meas.get_lines().iter().enumerate() {
4486 line_glyphs.clear();
4487 let mut line_w_px: f32 = 0.0;
4488 for ch in line.get_text().chars() {
4489 if ch == ' ' || ch == '\t' {
4490 let sp_adv: f32 = measure_char_advance(ch, *style) * scale;
4491 line_glyphs.push((None, 0, 0, sp_adv));
4492 line_w_px += sp_adv;
4493 continue;
4494 }
4495 let key: GlyphKey = GlyphKey::from_text_style(ch, phys_font_px, *style);
4496 let (gw, gh, adv): (u32, u32, f32) = {
4497 let green_val: &RasterizedGlyph = match font_provider {
4498 Some(fp) => atlas.get_or_rasterize_with(key, fp),
4499 None => atlas.get_or_rasterize(key),
4500 };
4501 (
4502 green_val.get_width(),
4503 green_val.get_height(),
4504 (green_val.get_advance() as f32).max(1.0) + letter_sp,
4505 )
4506 };
4507 line_glyphs.push((Some(key), gw, gh, adv));
4508 line_w_px += adv;
4509 }
4510 let fit_scale: f32 = if rect_w_px > 1.0 && line_w_px > rect_w_px + 1.0 {
4511 (rect_w_px / line_w_px).clamp(0.72, 1.0)
4512 } else {
4513 1.0
4514 };
4515 let fitted_line_w: f32 = line_w_px * fit_scale;
4516 let align_offset: f32 = match style.get_align() {
4517 TextAlign::Center => ((rect_w_px - fitted_line_w) * 0.5).max(0.0),
4518 TextAlign::Right => (rect_w_px - fitted_line_w).max(0.0),
4519 TextAlign::Left => 0.0,
4520 };
4521 let base_y: f32 = rect.get_y() * scale + (line_idx as f32) * line_h;
4522 let mut pen_x: f32 = rect.get_x() * scale + align_offset;
4523 for &(key_opt, gw, gh, adv) in line_glyphs.iter() {
4524 if let Some(key) = key_opt
4525 && gw > 0
4526 && gh > 0
4527 {
4528 let y_off: f32 = ((line_h - (gh as f32)) * 0.5).round();
4529 let prim_idx: usize = primitives.len();
4530 let prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
4531 rect: [
4532 pen_x.round(),
4533 (base_y + y_off).round(),
4534 gw as f32,
4535 gh as f32,
4536 ],
4537 clip_rect: clip_arr,
4538 color_rgba,
4539 aux_color_rgba: 0,
4540 uv_rect: [0, 0, 0, 0],
4541 radii_border: [0; 4],
4542 kind_flags,
4543 extra_param: 0,
4544 };
4545 push_direct_gpu_primitive(
4546 &mut primitives,
4547 &mut draw_ranges,
4548 prim,
4549 active_clip,
4550 phys_w,
4551 phys_h,
4552 );
4553 glyph_fixups.push((prim_idx, key));
4554 }
4555 pen_x += adv * fit_scale;
4556 }
4557 }
4558 } else {
4559 let queue_entry: GpuQuadInstance = GpuQuadInstance {
4560 rect: [
4561 rect.get_x() * scale,
4562 rect.get_y() * scale,
4563 rect.get_width() * scale,
4564 rect.get_height() * scale,
4565 ],
4566 clip: clip_arr,
4567 color: style.get_color().to_f32_array(),
4568 secondary_color: [0.0; 4],
4569 radii: [0.0; 4],
4570 stroke_or_blur: style.get_font_size() * scale,
4571 angle_rad: 0.0,
4572 kind: GpuPrimitiveKind::Glyph as u32,
4573 reserved: text.chars().count() as u32,
4574 };
4575 push_direct_gpu_primitive(
4576 &mut primitives,
4577 &mut draw_ranges,
4578 GpuPrimitiveInstance::from_quad_instance(&queue_entry, 0, active_layer_id),
4579 active_clip,
4580 phys_w,
4581 phys_h,
4582 );
4583 }
4584 }
4585 DrawCommand::TextCaret {
4586 text_rect,
4587 content_rect,
4588 text,
4589 style,
4590 caret_height,
4591 color,
4592 multiline,
4593 } => {
4594 if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
4595 continue;
4596 }
4597 let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
4598 text,
4599 *style,
4600 if *multiline {
4601 Some(content_rect.get_width().max(1.0))
4602 } else {
4603 None
4604 },
4605 );
4606 let last_w_phys: f32 = if let Some(atlas) = glyph_atlas.as_deref_mut() {
4607 let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
4608 let letter_sp: f32 = style.get_letter_spacing() * scale;
4609 if let Some(line) = meas.get_lines().last() {
4610 let mut acc: f32 = 0.0;
4611 for ch in line.get_text().chars() {
4612 if ch == ' ' || ch == '\t' {
4613 acc += measure_char_advance(ch, *style) * scale + letter_sp;
4614 } else {
4615 let key: GlyphKey =
4616 GlyphKey::from_text_style(ch, phys_font_px, *style);
4617 let geometry_val: &RasterizedGlyph = match font_provider {
4618 Some(fp) => atlas.get_or_rasterize_with(key, fp),
4619 None => atlas.get_or_rasterize(key),
4620 };
4621 acc += (geometry_val.get_advance() as f32).max(1.0) + letter_sp;
4622 }
4623 }
4624 acc
4625 } else {
4626 0.0
4627 }
4628 } else {
4629 meas.get_lines()
4630 .last()
4631 .map(TextLine::get_width)
4632 .unwrap_or(0.0)
4633 * scale
4634 };
4635 let line_idx: usize = meas.get_lines().len().saturating_sub(1);
4636 let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
4637 let caret_x_phys: f32 =
4638 (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys).clamp(
4639 content_rect.get_x() * scale,
4640 ((content_rect.right() - 2.0) * scale).max(content_rect.get_x() * scale),
4641 );
4642 let caret_y: f32 = if *multiline {
4643 (content_rect.get_y()
4644 + (line_idx as f32) * meas.get_line_height_px()
4645 + ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
4646 .clamp(
4647 content_rect.get_y(),
4648 (content_rect.bottom() - caret_height).max(content_rect.get_y()),
4649 )
4650 } else {
4651 content_rect.get_y()
4652 + ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
4653 };
4654 let query_val_primary: GpuQuadInstance = GpuQuadInstance {
4655 rect: [
4656 caret_x_phys.round(),
4657 (caret_y * scale).round(),
4658 (1.5 * scale).max(1.0),
4659 (caret_height * scale).max(2.0),
4660 ],
4661 clip: clip_arr,
4662 color: color.to_f32_array(),
4663 secondary_color: [0.0; 4],
4664 radii: [0.5 * scale; 4],
4665 stroke_or_blur: 0.0,
4666 angle_rad: 0.0,
4667 kind: GpuPrimitiveKind::RoundedRect as u32,
4668 reserved: 0,
4669 };
4670 push_direct_gpu_primitive(
4671 &mut primitives,
4672 &mut draw_ranges,
4673 GpuPrimitiveInstance::from_quad_instance(
4674 &query_val_primary,
4675 0,
4676 active_layer_id,
4677 ),
4678 active_clip,
4679 phys_w,
4680 phys_h,
4681 );
4682 }
4683 DrawCommand::Image {
4684 rect,
4685 buffer,
4686 radius,
4687 } => {
4688 let snapped: Rect = snap_physical_rect(*rect, scale);
4689 let img_w: u32 = buffer.get_width();
4690 let img_h: u32 = buffer.get_height();
4691 if img_w == 0
4692 || img_h == 0
4693 || snapped.get_width() <= 0.0
4694 || snapped.get_height() <= 0.0
4695 {
4696 continue;
4697 }
4698 let img_idx: usize = image_entries.len();
4699 image_entries.push(DirectGpuImageSlice {
4700 src_w: img_w,
4701 src_h: img_h,
4702 pixels: buffer.get_pixels(),
4703 crop: PixelDirtyRect::new(0, 0, img_w, img_h),
4704 });
4705 let query_val_secondary: GpuQuadInstance = GpuQuadInstance {
4706 rect: [
4707 snapped.get_x(),
4708 snapped.get_y(),
4709 snapped.get_width(),
4710 snapped.get_height(),
4711 ],
4712 clip: clip_arr,
4713 color: [1.0, 1.0, 1.0, 1.0],
4714 secondary_color: [0.0; 4],
4715 radii: [
4716 radius.get_top_left() * scale,
4717 radius.get_top_right() * scale,
4718 radius.get_bottom_right() * scale,
4719 radius.get_bottom_left() * scale,
4720 ],
4721 stroke_or_blur: 0.0,
4722 angle_rad: 0.0,
4723 kind: GpuPrimitiveKind::TexturedQuad as u32,
4724 reserved: 0,
4725 };
4726 let prim_idx: usize = primitives.len();
4727 push_direct_gpu_primitive(
4728 &mut primitives,
4729 &mut draw_ranges,
4730 GpuPrimitiveInstance::from_quad_instance(
4731 &query_val_secondary,
4732 0,
4733 active_layer_id,
4734 ),
4735 active_clip,
4736 phys_w,
4737 phys_h,
4738 );
4739 image_fixups.push((prim_idx, img_idx));
4740 }
4741 DrawCommand::SharedImage {
4742 rect,
4743 width,
4744 height,
4745 pixels,
4746 radius,
4747 } => {
4748 let snapped: Rect = snap_physical_rect(*rect, scale);
4749 if *width == 0
4750 || *height == 0
4751 || snapped.get_width() <= 0.0
4752 || snapped.get_height() <= 0.0
4753 {
4754 continue;
4755 }
4756 let img_idx: usize = image_entries.len();
4757 image_entries.push(DirectGpuImageSlice {
4758 src_w: *width,
4759 src_h: *height,
4760 pixels: pixels.as_slice(),
4761 crop: PixelDirtyRect::new(0, 0, *width, *height),
4762 });
4763 let query_val_next: GpuQuadInstance = GpuQuadInstance {
4764 rect: [
4765 snapped.get_x(),
4766 snapped.get_y(),
4767 snapped.get_width(),
4768 snapped.get_height(),
4769 ],
4770 clip: clip_arr,
4771 color: [1.0, 1.0, 1.0, 1.0],
4772 secondary_color: [0.0; 4],
4773 radii: [
4774 radius.get_top_left() * scale,
4775 radius.get_top_right() * scale,
4776 radius.get_bottom_right() * scale,
4777 radius.get_bottom_left() * scale,
4778 ],
4779 stroke_or_blur: 0.0,
4780 angle_rad: 0.0,
4781 kind: GpuPrimitiveKind::TexturedQuad as u32,
4782 reserved: 0,
4783 };
4784 let prim_idx: usize = primitives.len();
4785 push_direct_gpu_primitive(
4786 &mut primitives,
4787 &mut draw_ranges,
4788 GpuPrimitiveInstance::from_quad_instance(&query_val_next, 0, active_layer_id),
4789 active_clip,
4790 phys_w,
4791 phys_h,
4792 );
4793 image_fixups.push((prim_idx, img_idx));
4794 }
4795 DrawCommand::SpriteRegion {
4796 rect,
4797 buffer,
4798 src_rect,
4799 tint,
4800 } => {
4801 let snapped: Rect = snap_physical_rect(*rect, scale);
4802 let img_w: u32 = buffer.get_width();
4803 let img_h: u32 = buffer.get_height();
4804 let sx: u32 = (src_rect.get_x().max(0.0).floor() as u32).min(img_w);
4805 let sy: u32 = (src_rect.get_y().max(0.0).floor() as u32).min(img_h);
4806 let stroke_width: u32 =
4807 (src_rect.get_width().max(1.0).ceil() as u32).min(img_w.saturating_sub(sx));
4808 let sh: u32 =
4809 (src_rect.get_height().max(1.0).ceil() as u32).min(img_h.saturating_sub(sy));
4810 if stroke_width == 0
4811 || sh == 0
4812 || snapped.get_width() <= 0.0
4813 || snapped.get_height() <= 0.0
4814 {
4815 continue;
4816 }
4817 let img_idx: usize = image_entries.len();
4818 image_entries.push(DirectGpuImageSlice {
4819 src_w: img_w,
4820 src_h: img_h,
4821 pixels: buffer.get_pixels(),
4822 crop: PixelDirtyRect::new(sx, sy, stroke_width, sh),
4823 });
4824 let query_val_alt: GpuQuadInstance = GpuQuadInstance {
4825 rect: [
4826 snapped.get_x(),
4827 snapped.get_y(),
4828 snapped.get_width(),
4829 snapped.get_height(),
4830 ],
4831 clip: clip_arr,
4832 color: tint.to_f32_array(),
4833 secondary_color: [0.0; 4],
4834 radii: [0.0; 4],
4835 stroke_or_blur: 0.0,
4836 angle_rad: 0.0,
4837 kind: GpuPrimitiveKind::TexturedQuad as u32,
4838 reserved: 1,
4839 };
4840 let prim_idx: usize = primitives.len();
4841 push_direct_gpu_primitive(
4842 &mut primitives,
4843 &mut draw_ranges,
4844 GpuPrimitiveInstance::from_quad_instance(&query_val_alt, 0, active_layer_id),
4845 active_clip,
4846 phys_w,
4847 phys_h,
4848 );
4849 image_fixups.push((prim_idx, img_idx));
4850 }
4851 DrawCommand::ExternalSurface { rect, radius } => {
4852 let snapped: Rect = snap_physical_rect(*rect, scale);
4853 if snapped.get_width() <= 0.0 || snapped.get_height() <= 0.0 {
4854 continue;
4855 }
4856 let ext_quad: GpuQuadInstance = GpuQuadInstance {
4857 rect: [
4858 snapped.get_x(),
4859 snapped.get_y(),
4860 snapped.get_width(),
4861 snapped.get_height(),
4862 ],
4863 clip: clip_arr,
4864 color: [1.0, 1.0, 1.0, 1.0],
4865 secondary_color: [0.0; 4],
4866 radii: [
4867 radius.get_top_left() * scale,
4868 radius.get_top_right() * scale,
4869 radius.get_bottom_right() * scale,
4870 radius.get_bottom_left() * scale,
4871 ],
4872 stroke_or_blur: 0.0,
4873 angle_rad: 0.0,
4874 kind: GpuPrimitiveKind::ExternalSurface as u32,
4875 reserved: 0,
4876 };
4877 push_direct_gpu_primitive(
4878 &mut primitives,
4879 &mut draw_ranges,
4880 GpuPrimitiveInstance::from_quad_instance(&ext_quad, 3, active_layer_id),
4881 active_clip,
4882 phys_w,
4883 phys_h,
4884 );
4885 }
4886 DrawCommand::Circle {
4887 center,
4888 radius,
4889 color,
4890 } => {
4891 let red_val: f32 = radius * scale;
4892 let pad: f32 = 1.5;
4893 let extent: f32 = red_val + pad;
4894 let query_val_inner: GpuQuadInstance = GpuQuadInstance {
4895 rect: [
4896 center.get_x() * scale - extent,
4897 center.get_y() * scale - extent,
4898 extent * 2.0,
4899 extent * 2.0,
4900 ],
4901 clip: clip_arr,
4902 color: color.to_f32_array(),
4903 secondary_color: [0.0; 4],
4904 radii: [red_val; 4],
4905 stroke_or_blur: red_val,
4906 angle_rad: 0.0,
4907 kind: GpuPrimitiveKind::Circle as u32,
4908 reserved: 0,
4909 };
4910 push_direct_gpu_primitive(
4911 &mut primitives,
4912 &mut draw_ranges,
4913 GpuPrimitiveInstance::from_quad_instance(&query_val_inner, 0, active_layer_id),
4914 active_clip,
4915 phys_w,
4916 phys_h,
4917 );
4918 }
4919 DrawCommand::Line {
4920 from,
4921 to,
4922 color,
4923 width,
4924 } => {
4925 let fx0: f32 = from.get_x() * scale;
4926 let fy0: f32 = from.get_y() * scale;
4927 let fx1: f32 = to.get_x() * scale;
4928 let fy1: f32 = to.get_y() * scale;
4929 let dx: f32 = fx1 - fx0;
4930 let dy: f32 = fy1 - fy0;
4931 let stroke_px: f32 = (width * scale).max(1.0);
4932 let pad: f32 = stroke_px * 0.5 + 1.5;
4933 let min_x: f32 = fx0.min(fx1) - pad;
4934 let min_y: f32 = fy0.min(fy1) - pad;
4935 let max_x: f32 = fx0.max(fx1) + pad;
4936 let max_y: f32 = fy0.max(fy1) + pad;
4937 let query_val_local: GpuQuadInstance = GpuQuadInstance {
4938 rect: [
4939 min_x,
4940 min_y,
4941 (max_x - min_x).max(2.0),
4942 (max_y - min_y).max(2.0),
4943 ],
4944 clip: clip_arr,
4945 color: color.to_f32_array(),
4946 secondary_color: [0.0; 4],
4947 radii: [fx0, fy0, fx1, fy1],
4948 stroke_or_blur: stroke_px,
4949 angle_rad: dy.atan2(dx),
4950 kind: GpuPrimitiveKind::Line as u32,
4951 reserved: 0,
4952 };
4953 push_direct_gpu_primitive(
4954 &mut primitives,
4955 &mut draw_ranges,
4956 GpuPrimitiveInstance::from_quad_instance(&query_val_local, 0, active_layer_id),
4957 active_clip,
4958 phys_w,
4959 phys_h,
4960 );
4961 }
4962 DrawCommand::Triangle { p0, p1, p2, color } => {
4963 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.5;
4964 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.5;
4965 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.5;
4966 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.5;
4967 let query_val_cur: GpuQuadInstance = GpuQuadInstance {
4968 rect: [
4969 min_x,
4970 min_y,
4971 (max_x - min_x).max(2.0),
4972 (max_y - min_y).max(2.0),
4973 ],
4974 clip: clip_arr,
4975 color: color.to_f32_array(),
4976 secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
4977 radii: [
4978 p1.get_x() * scale,
4979 p1.get_y() * scale,
4980 p2.get_x() * scale,
4981 p2.get_y() * scale,
4982 ],
4983 stroke_or_blur: 0.0,
4984 angle_rad: 0.0,
4985 kind: GpuPrimitiveKind::Triangle as u32,
4986 reserved: 3,
4987 };
4988 push_direct_gpu_primitive(
4989 &mut primitives,
4990 &mut draw_ranges,
4991 GpuPrimitiveInstance::from_quad_instance(&query_val_cur, 0, active_layer_id),
4992 active_clip,
4993 phys_w,
4994 phys_h,
4995 );
4996 }
4997 }
4998 if active_rounded_bits != 0 && primitives.len() > cmd_prim_start {
4999 for prim_item in primitives[cmd_prim_start..].iter_mut() {
5000 let quad_rect: [f32; 4] = prim_item.get_rect();
5001 let safe_non_empty: bool =
5002 safe_inner_clip.get_width() > 0.0 && safe_inner_clip.get_height() > 0.0;
5003 let inside_safe: bool = safe_non_empty
5004 && quad_rect[0] >= safe_inner_clip.get_x()
5005 && quad_rect[1] >= safe_inner_clip.get_y()
5006 && (quad_rect[0] + quad_rect[2]) <= safe_inner_clip.right()
5007 && (quad_rect[1] + quad_rect[3]) <= safe_inner_clip.bottom();
5008 if !inside_safe {
5009 *prim_item = prim_item.with_rounded_clip_bits(active_rounded_bits);
5010 }
5011 }
5012 }
5013 }
5014 let mut glyph_r8_atlas: Option<DirectGpuAtlasUpload> = None;
5015 if let Some(atlas) = glyph_atlas.as_deref()
5016 && (!glyph_fixups.is_empty() || atlas.get_revision() != last_glyph_revision)
5017 && !atlas.is_empty()
5018 {
5019 let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
5020 let aw: u32 = packed.get_width();
5021 let ah: u32 = packed.get_height();
5022 for &(prim_idx, key) in glyph_fixups.iter() {
5023 if let Some(&(gx, gy, gw, gh)) = packed.get_regions().get(&key) {
5024 primitives[prim_idx].set_uv_rect(encode_atlas_uv_rect(aw, ah, gx, gy, gw, gh));
5025 }
5026 }
5027 if packed.get_revision() != last_glyph_revision {
5028 let rgba: &[u8] = packed.get_pixels().as_slice();
5029 let mut r8: Vec<u8> = Vec::with_capacity((aw as usize).saturating_mul(ah as usize));
5030 for px in rgba.as_chunks::<4>().0 {
5031 r8.push(px[3]);
5032 }
5033 glyph_r8_atlas = Some(DirectGpuAtlasUpload {
5034 width: aw,
5035 height: ah,
5036 revision: packed.get_revision(),
5037 pixels: r8,
5038 });
5039 }
5040 }
5041 let (image_rgba8_atlas, img_uvs): (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) =
5042 pack_frame_image_atlas(&image_entries, display_list.fast_hash());
5043 for &(prim_idx, img_idx) in image_fixups.iter() {
5044 if let Some(&uv) = img_uvs.get(img_idx) {
5045 primitives[prim_idx].set_uv_rect(uv);
5046 }
5047 }
5048 let glyph_bytes: usize = glyph_r8_atlas
5049 .as_ref()
5050 .map(|alpha_val: &DirectGpuAtlasUpload| alpha_val.get_pixels().len())
5051 .unwrap_or(0);
5052 let image_bytes: usize = image_rgba8_atlas
5053 .as_ref()
5054 .map(|first_val: &DirectGpuAtlasUpload| first_val.get_pixels().len())
5055 .unwrap_or(0);
5056 let instance_upload_bytes: usize = primitives
5057 .len()
5058 .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES)
5059 .saturating_add(glyph_bytes)
5060 .saturating_add(image_bytes);
5061 DirectGpuFrameBatch {
5062 viewport_width: phys_w,
5063 viewport_height: phys_h,
5064 clear_rgba,
5065 primitives,
5066 draw_ranges,
5067 backdrop_blurs,
5068 glyph_r8_atlas,
5069 image_rgba8_atlas,
5070 instance_upload_bytes,
5071 cpu_mirror_active: false,
5072 upload_strategy: MobileUploadStrategy::DirectGpu,
5073 }
5074}
5075
5076#[must_use]
5082pub const fn default_native_gpu_backend() -> GraphicsBackend {
5083 #[cfg(any(target_os = "macos", target_os = "ios"))]
5084 {
5085 GraphicsBackend::Metal
5086 }
5087 #[cfg(target_os = "windows")]
5088 {
5089 GraphicsBackend::Direct3D12
5090 }
5091 #[cfg(any(target_os = "linux", target_os = "android"))]
5092 {
5093 GraphicsBackend::Vulkan
5094 }
5095 #[cfg(target_arch = "wasm32")]
5096 {
5097 GraphicsBackend::WebGl2
5098 }
5099 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
5100 #[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
5101 {
5102 GraphicsBackend::Headless
5103 }
5104}
5105
5106#[must_use]
5118pub fn shader_program_cache_hash(device_name: &str, primary_src: &str, secondary_src: &str) -> u64 {
5119 let mut hash: u64 = FNV1A_OFFSET_BASIS;
5120 for chunk in [
5121 device_name.as_bytes(),
5122 primary_src.as_bytes(),
5123 secondary_src.as_bytes(),
5124 ]
5125 .iter()
5126 {
5127 for &byte in chunk.iter() {
5128 hash ^= byte as u64;
5129 hash = hash.wrapping_mul(FNV1A_PRIME);
5130 }
5131 }
5132 hash
5133}
5134
5135fn run_shader_precompile_uncached(backend: GraphicsBackend) -> ShaderPrecompileReport {
5145 #[cfg(not(target_arch = "wasm32"))]
5146 let total_start: Instant = Instant::now();
5147 let _: Vec<u8> = build_aces_srgb_lut();
5148 let lang_label: &str = ShaderProgramId::language_for_backend(backend);
5149 #[cfg(any(target_os = "macos", target_os = "ios"))]
5150 if backend == GraphicsBackend::Metal {
5151 let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
5152 let device_name: String = cached.adapter.get_device_name().clone();
5153 let hardware_gpu: bool = cached.adapter.get_hardware_verified();
5154 let archive_enabled: bool = cached.binary_archive_enabled;
5155 let archive_hit: bool = cached.binary_archive_hit;
5156 let handles_and_us: [(ShaderProgramId, usize, u64); 4] = [
5157 (
5158 ShaderProgramId::UiUber,
5159 cached.pipeline,
5160 cached.ui_compile_us,
5161 ),
5162 (
5163 ShaderProgramId::BackdropBlur,
5164 if cached.blur_pipeline != 0 && cached.blur_up_pipeline != 0 {
5165 cached.blur_pipeline
5166 } else {
5167 0
5168 },
5169 cached.blur_compile_us,
5170 ),
5171 (
5172 ShaderProgramId::Engine3dPbr,
5173 cached.engine3d_pipeline,
5174 cached.engine3d_compile_us,
5175 ),
5176 (
5177 ShaderProgramId::FluidOceanOptical,
5178 cached.ocean_pipeline,
5179 cached.ocean_compile_us,
5180 ),
5181 ];
5182 let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(handles_and_us.len());
5183 let mut ready_count: usize = 0;
5184 let mut hw_compiled: usize = 0;
5185 for (program, pso_handle, compile_us) in handles_and_us {
5186 let (src_a, src_b): (&str, &str) = program.source_pair(backend);
5187 let src_bytes: usize = src_a.len().saturating_add(src_b.len());
5188 let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
5189 let state: ShaderCompileState = if pso_handle != 0 {
5190 hw_compiled += 1;
5191 ready_count += 1;
5192 if archive_hit {
5193 ShaderCompileState::LoadedFromBinaryArchive
5194 } else {
5195 ShaderCompileState::CompiledHardware
5196 }
5197 } else if !src_a.is_empty() {
5198 ready_count += 1;
5199 ShaderCompileState::ValidatedFallback
5200 } else {
5201 ShaderCompileState::Failed
5202 };
5203 entries.push(ShaderProgramCacheEntry {
5204 program,
5205 name: program.label().to_string(),
5206 language: lang_label.to_string(),
5207 state,
5208 source_hash: src_hash,
5209 source_bytes: src_bytes,
5210 compile_time_us: compile_us,
5211 pipeline_ready: state.is_ready(),
5212 });
5213 }
5214 let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
5215 let cold_us: u64 = cached.total_compile_us.max(elapsed_us);
5216 return ShaderPrecompileReport {
5217 backend,
5218 device_name,
5219 hardware_gpu,
5220 binary_archive_enabled: archive_enabled,
5221 binary_archive_hit: archive_hit,
5222 cache_hit: false,
5223 total_programs: entries.len(),
5224 ready_programs: ready_count,
5225 hardware_compiled_programs: hw_compiled,
5226 cold_compile_us: cold_us,
5227 last_call_us: elapsed_us,
5228 entries,
5229 };
5230 }
5231 let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
5232 let device_name: String = probed.adapter.get_device_name().clone();
5233 let hardware_gpu: bool = probed.adapter.get_hardware_verified();
5234 let hw_shader_ok: bool = probed.adapter.get_shader_compiled();
5235 let has_compiled_pso: bool = probed.device_handle != 0 && probed.pipeline_handle != 0;
5236 release_native_gpu_object(probed.dummy_r8_tex);
5237 release_native_gpu_object(probed.dummy_rgba8_tex);
5238 release_native_gpu_object(probed.ocean_pipeline_handle);
5239 release_native_gpu_object(probed.engine3d_pipeline_handle);
5240 release_native_gpu_object(probed.blur_up_pipeline_handle);
5241 release_native_gpu_object(probed.blur_pipeline_handle);
5242 release_native_gpu_object(probed.pipeline_handle);
5243 release_native_gpu_handles(
5244 probed.device_handle,
5245 probed.queue_handle,
5246 probed.library_handle,
5247 );
5248 let programs: [ShaderProgramId; 4] = ShaderProgramId::all();
5249 let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(programs.len());
5250 let mut ready_count: usize = 0;
5251 let mut hw_compiled: usize = 0;
5252 for program in programs {
5253 #[cfg(not(target_arch = "wasm32"))]
5254 let item_start: Instant = Instant::now();
5255 let (src_a, src_b): (&str, &str) = program.source_pair(backend);
5256 let src_bytes: usize = src_a.len().saturating_add(src_b.len());
5257 let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
5258 let is_valid: bool = !src_a.is_empty();
5259 let state: ShaderCompileState =
5260 if has_compiled_pso && hardware_gpu && hw_shader_ok && is_valid {
5261 hw_compiled += 1;
5262 ready_count += 1;
5263 ShaderCompileState::CompiledHardware
5264 } else if is_valid {
5265 ready_count += 1;
5266 ShaderCompileState::ValidatedFallback
5267 } else {
5268 ShaderCompileState::Failed
5269 };
5270 #[cfg(not(target_arch = "wasm32"))]
5271 let item_us: u64 = item_start.elapsed().as_micros() as u64;
5272 #[cfg(target_arch = "wasm32")]
5273 let item_us: u64 = 0;
5274 entries.push(ShaderProgramCacheEntry {
5275 program,
5276 name: program.label().to_string(),
5277 language: lang_label.to_string(),
5278 state,
5279 source_hash: src_hash,
5280 source_bytes: src_bytes,
5281 compile_time_us: item_us,
5282 pipeline_ready: state.is_ready(),
5283 });
5284 }
5285 #[cfg(not(target_arch = "wasm32"))]
5286 let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
5287 #[cfg(target_arch = "wasm32")]
5288 let elapsed_us: u64 = 0;
5289 ShaderPrecompileReport {
5290 backend,
5291 device_name,
5292 hardware_gpu,
5293 binary_archive_enabled: false,
5294 binary_archive_hit: false,
5295 cache_hit: false,
5296 total_programs: entries.len(),
5297 ready_programs: ready_count,
5298 hardware_compiled_programs: hw_compiled,
5299 cold_compile_us: elapsed_us,
5300 last_call_us: elapsed_us,
5301 entries,
5302 }
5303}
5304
5305#[must_use]
5315pub fn precompile_shaders(backend: GraphicsBackend) -> ShaderPrecompileReport {
5316 #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
5317 {
5318 let call_start: Instant = Instant::now();
5319 let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
5320 SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
5321 if let Ok(guard) = cache_mutex.lock()
5322 && let Some(existing) = guard.get(&backend)
5323 {
5324 let mut hit_report: ShaderPrecompileReport = existing.clone();
5325 hit_report.set_cache_hit(true);
5326 hit_report.set_last_call_us(call_start.elapsed().as_micros() as u64);
5327 return hit_report;
5328 }
5329 let fresh: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
5330 if let Ok(mut guard) = cache_mutex.lock() {
5331 let _: Option<ShaderPrecompileReport> = guard.insert(backend, fresh.clone());
5332 }
5333 fresh
5334 }
5335 #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
5336 {
5337 run_shader_precompile_uncached(backend)
5338 }
5339}
5340
5341pub fn precompile_shaders_async(backend: GraphicsBackend) {
5347 #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
5348 {
5349 let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
5350 SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
5351 if let Ok(guard) = cache_mutex.lock()
5352 && guard.contains_key(&backend)
5353 {
5354 return;
5355 }
5356 if SHADER_PRECOMPILE_IN_FLIGHT
5357 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
5358 .is_err()
5359 {
5360 return;
5361 }
5362 let spawn_result: io::Result<JoinHandle<()>> = Builder::new()
5363 .name("euv-shader-precompile".to_string())
5364 .spawn(move || {
5365 let _: ShaderPrecompileReport = precompile_shaders(backend);
5366 SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
5367 });
5368 if spawn_result.is_err() {
5369 SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
5370 let _: ShaderPrecompileReport = precompile_shaders(backend);
5371 }
5372 }
5373 #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
5374 {
5375 let _: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
5376 }
5377}
5378
5379#[must_use]
5385pub fn shader_precompile_status() -> Option<ShaderPrecompileReport> {
5386 #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
5387 {
5388 let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
5389 SHADER_PRECOMPILE_CACHE.get()?;
5390 let guard: MutexGuard<'_, HashMap<GraphicsBackend, ShaderPrecompileReport>> =
5391 cache_mutex.lock().ok()?;
5392 let native_backend: GraphicsBackend = default_native_gpu_backend();
5393 if let Some(native_report) = guard.get(&native_backend) {
5394 return Some(native_report.clone());
5395 }
5396 guard.values().next().cloned()
5397 }
5398 #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
5399 {
5400 None
5401 }
5402}
5403
5404#[must_use]
5410pub fn is_shader_precompile_in_flight() -> bool {
5411 #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
5412 {
5413 SHADER_PRECOMPILE_IN_FLIGHT.load(Ordering::Acquire)
5414 }
5415 #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
5416 {
5417 false
5418 }
5419}