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 engine3d_pipeline_handle: 0,
43 ocean_pipeline_handle: 0,
44 dummy_r8_tex: 0,
45 dummy_rgba8_tex: 0,
46 };
47 }
48 #[cfg(any(target_os = "macos", target_os = "ios"))]
49 {
50 probe_apple_metal_full(backend)
51 }
52 #[cfg(target_os = "windows")]
53 {
54 let (adapter, device_handle, queue_handle, library_handle): (
55 GpuAdapterInfo,
56 usize,
57 usize,
58 usize,
59 ) = probe_windows_d3d12(backend);
60 NativeGpuProbeOutput {
61 adapter,
62 device_handle,
63 queue_handle,
64 library_handle,
65 pipeline_handle: 0,
66 blur_pipeline_handle: 0,
67 engine3d_pipeline_handle: 0,
68 ocean_pipeline_handle: 0,
69 dummy_r8_tex: 0,
70 dummy_rgba8_tex: 0,
71 }
72 }
73 #[cfg(any(target_os = "linux", target_os = "android"))]
74 {
75 let (adapter, device_handle, queue_handle, library_handle): (
76 GpuAdapterInfo,
77 usize,
78 usize,
79 usize,
80 ) = probe_vulkan_runtime(backend);
81 NativeGpuProbeOutput {
82 adapter,
83 device_handle,
84 queue_handle,
85 library_handle,
86 pipeline_handle: 0,
87 blur_pipeline_handle: 0,
88 engine3d_pipeline_handle: 0,
89 ocean_pipeline_handle: 0,
90 dummy_r8_tex: 0,
91 dummy_rgba8_tex: 0,
92 }
93 }
94 #[cfg(target_arch = "wasm32")]
95 {
96 NativeGpuProbeOutput {
97 adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
98 device_handle: 0,
99 queue_handle: 0,
100 library_handle: 0,
101 pipeline_handle: 0,
102 blur_pipeline_handle: 0,
103 engine3d_pipeline_handle: 0,
104 ocean_pipeline_handle: 0,
105 dummy_r8_tex: 0,
106 dummy_rgba8_tex: 0,
107 }
108 }
109 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
110 #[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
111 {
112 NativeGpuProbeOutput {
113 adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
114 device_handle: 0,
115 queue_handle: 0,
116 library_handle: 0,
117 pipeline_handle: 0,
118 blur_pipeline_handle: 0,
119 engine3d_pipeline_handle: 0,
120 ocean_pipeline_handle: 0,
121 dummy_r8_tex: 0,
122 dummy_rgba8_tex: 0,
123 }
124 }
125}
126
127pub fn submit_native_gpu_batches(
139 device_handle: usize,
140 queue_handle: usize,
141 batches: &[GpuBatch],
142) -> usize {
143 #[cfg(any(target_os = "macos", target_os = "ios"))]
144 {
145 metal_submit_batches(device_handle, queue_handle, batches)
146 }
147 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
148 {
149 let _: (usize, usize) = (device_handle, queue_handle);
150 batches
151 .iter()
152 .map(|blue_val: &GpuBatch| {
153 blue_val
154 .get_primitives()
155 .len()
156 .max(blue_val.get_instances().len())
157 })
158 .sum()
159 }
160}
161
162pub(crate) fn submit_native_gpu_ring_frame(
176 driver: &mut NativeGpuDriver,
177 width: u32,
178 height: u32,
179 clear_color: Color,
180 batches: &[GpuBatch],
181) -> usize {
182 #[cfg(any(target_os = "macos", target_os = "ios"))]
183 {
184 metal_submit_ring_frame(driver, width, height, clear_color, batches)
185 }
186 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
187 {
188 let _: (&mut NativeGpuDriver, u32, u32, Color) = (driver, width, height, clear_color);
189 batches
190 .iter()
191 .map(|blue_val: &GpuBatch| {
192 blue_val
193 .get_primitives()
194 .len()
195 .max(blue_val.get_instances().len())
196 })
197 .sum()
198 }
199}
200
201pub(crate) fn configure_native_metal_layer(device_handle: usize, layer_handle: usize) {
208 #[cfg(any(target_os = "macos", target_os = "ios"))]
209 {
210 metal_configure_layer(device_handle, layer_handle);
211 }
212 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
213 {
214 let _: (usize, usize) = (device_handle, layer_handle);
215 }
216}
217
218pub(crate) fn upload_native_texture_dirty_rect(
234 device_handle: usize,
235 texture_handle: &mut usize,
236 format: GpuAtlasPixelFormat,
237 tex_dims: (u32, u32),
238 dirty_rect: (u32, u32, u32, u32),
239 bytes: &[u8],
240 bytes_per_row: usize,
241) -> bool {
242 #[cfg(any(target_os = "macos", target_os = "ios"))]
243 {
244 metal_upload_texture_dirty_rect(
245 device_handle,
246 texture_handle,
247 format,
248 tex_dims,
249 dirty_rect,
250 bytes,
251 bytes_per_row,
252 )
253 }
254 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
255 {
256 let _: usize = device_handle;
257 let _: &mut usize = texture_handle;
258 let _: GpuAtlasPixelFormat = format;
259 let _: (u32, u32) = tex_dims;
260 let _: (u32, u32, u32, u32) = dirty_rect;
261 let _: &[u8] = bytes;
262 let _: usize = bytes_per_row;
263 false
264 }
265}
266
267pub(crate) fn retain_native_gpu_object(handle: usize) -> usize {
277 #[cfg(any(target_os = "macos", target_os = "ios"))]
278 {
279 mtl_retain_handle(handle)
280 }
281 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
282 {
283 handle
284 }
285}
286
287pub(crate) fn release_native_gpu_object(handle: usize) {
293 #[cfg(any(target_os = "macos", target_os = "ios"))]
294 {
295 if handle != 0 {
296 let sel: &MetalSelectors = cached_metal_selectors();
297 mtl_send_void0(handle as *mut c_void, sel.release as *mut c_void);
298 }
299 }
300 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
301 {
302 let _: usize = handle;
303 }
304}
305
306pub fn release_native_gpu_handles(
314 device_handle: usize,
315 queue_handle: usize,
316 library_handle: usize,
317) {
318 #[cfg(any(target_os = "macos", target_os = "ios"))]
319 {
320 metal_release_handles(device_handle, queue_handle, library_handle);
321 }
322 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
323 {
324 let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
325 }
326}
327
328#[must_use]
334pub fn native_gpu_last_presented_ns() -> u64 {
335 #[cfg(any(target_os = "macos", target_os = "ios"))]
336 {
337 METAL_LAST_PRESENTED_NS.load(Ordering::Relaxed)
338 }
339 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
340 {
341 0
342 }
343}
344
345#[must_use]
351pub fn native_gpu_last_exec_ns() -> u64 {
352 #[cfg(any(target_os = "macos", target_os = "ios"))]
353 {
354 METAL_LAST_GPU_EXEC_NS.load(Ordering::Relaxed)
355 }
356 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
357 {
358 0
359 }
360}
361
362#[cfg(any(target_os = "macos", target_os = "ios"))]
363#[link(name = "Metal", kind = "framework")]
364unsafe extern "C" {
365 fn MTLCreateSystemDefaultDevice() -> *mut c_void;
371}
372
373#[cfg(any(target_os = "macos", target_os = "ios"))]
374#[link(name = "objc")]
375unsafe extern "C" {
376 fn objc_getClass(name: *const c_char) -> *mut c_void;
386 fn sel_registerName(name: *const c_char) -> *mut c_void;
396 fn objc_autoreleasePoolPush() -> *mut c_void;
402 fn objc_autoreleasePoolPop(pool: *mut c_void);
408 fn objc_msgSend();
410}
411
412#[cfg(any(target_os = "macos", target_os = "ios"))]
413unsafe extern "C" {
414 static _NSConcreteGlobalBlock: c_void;
416}
417
418#[cfg(any(target_os = "macos", target_os = "ios"))]
428fn mtl_sel_cstr(name: &'static str) -> *mut c_void {
429 unsafe { sel_registerName(name.as_ptr().cast::<c_char>()) }
430}
431
432#[cfg(any(target_os = "macos", target_os = "ios"))]
442fn mtl_cls_cstr(name: &'static str) -> *mut c_void {
443 unsafe { objc_getClass(name.as_ptr().cast::<c_char>()) }
444}
445
446#[cfg(any(target_os = "macos", target_os = "ios"))]
456fn mtl_ns_string(text: &str) -> *mut c_void {
457 let Ok(c_text) = CString::new(text) else {
458 return null_mut();
459 };
460 unsafe {
461 let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_STRING);
462 if cls.is_null() {
463 return null_mut();
464 }
465 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
466 transmute(objc_msgSend as *const c_void);
467 send(cls, mtl_sel_cstr(MTL_SEL_STRING_UTF8), c_text.as_ptr())
468 }
469}
470
471#[cfg(any(target_os = "macos", target_os = "ios"))]
482fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
483 if obj.is_null() || sel.is_null() {
484 return null_mut();
485 }
486 unsafe {
487 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
488 transmute(objc_msgSend as *const c_void);
489 send(obj, sel)
490 }
491}
492
493#[cfg(any(target_os = "macos", target_os = "ios"))]
505fn mtl_send_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) -> *mut c_void {
506 if obj.is_null() || sel.is_null() {
507 return null_mut();
508 }
509 unsafe {
510 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
511 transmute(objc_msgSend as *const c_void);
512 send(obj, sel, arg0)
513 }
514}
515
516#[cfg(any(target_os = "macos", target_os = "ios"))]
523fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
524 if obj.is_null() || sel.is_null() {
525 return;
526 }
527 unsafe {
528 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
529 transmute(objc_msgSend as *const c_void);
530 send(obj, sel);
531 }
532}
533
534#[cfg(any(target_os = "macos", target_os = "ios"))]
542fn mtl_send_void_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) {
543 if obj.is_null() || sel.is_null() {
544 return;
545 }
546 unsafe {
547 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
548 transmute(objc_msgSend as *const c_void);
549 send(obj, sel, arg0);
550 }
551}
552
553#[cfg(any(target_os = "macos", target_os = "ios"))]
561fn mtl_send_void_usize(obj: *mut c_void, sel: *mut c_void, val: usize) {
562 if obj.is_null() || sel.is_null() {
563 return;
564 }
565 unsafe {
566 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) =
567 transmute(objc_msgSend as *const c_void);
568 send(obj, sel, val);
569 }
570}
571
572#[cfg(any(target_os = "macos", target_os = "ios"))]
580fn mtl_send_void_bool(obj: *mut c_void, sel: *mut c_void, val: bool) {
581 if obj.is_null() || sel.is_null() {
582 return;
583 }
584 unsafe {
585 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
586 transmute(objc_msgSend as *const c_void);
587 send(obj, sel, if val { 1 } else { 0 });
588 }
589}
590
591#[cfg(any(target_os = "macos", target_os = "ios"))]
602fn mtl_send_usize0(obj: *mut c_void, sel: *mut c_void) -> usize {
603 if obj.is_null() || sel.is_null() {
604 return 0;
605 }
606 unsafe {
607 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
608 transmute(objc_msgSend as *const c_void);
609 send(obj, sel)
610 }
611}
612
613#[cfg(any(target_os = "macos", target_os = "ios"))]
624fn mtl_send_f64_0(obj: *mut c_void, sel: *mut c_void) -> f64 {
625 if obj.is_null() || sel.is_null() {
626 return 0.0;
627 }
628 unsafe {
629 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> f64 =
630 transmute(objc_msgSend as *const c_void);
631 send(obj, sel)
632 }
633}
634
635#[cfg(any(target_os = "macos", target_os = "ios"))]
646fn mtl_responds_to_sel(obj: *mut c_void, sel: *mut c_void) -> bool {
647 if obj.is_null() || sel.is_null() {
648 return false;
649 }
650 let responds_sel: *mut c_void = cached_metal_selectors().responds_to_sel as *mut c_void;
651 unsafe {
652 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i8 =
653 transmute(objc_msgSend as *const c_void);
654 send(obj, responds_sel, sel) != 0
655 }
656}
657
658#[cfg(any(target_os = "macos", target_os = "ios"))]
668fn mtl_retain_handle(handle: usize) -> usize {
669 if handle == 0 {
670 return 0;
671 }
672 let sel_retain: *mut c_void = cached_metal_selectors().retain as *mut c_void;
673 mtl_send_ptr0(handle as *mut c_void, sel_retain) as usize
674}
675
676#[cfg(any(target_os = "macos", target_os = "ios"))]
683unsafe extern "C" fn metal_presented_handler_invoke(_block: *mut c_void, drawable: *mut c_void) {
684 if drawable.is_null() {
685 return;
686 }
687 let sel: &MetalSelectors = cached_metal_selectors();
688 let presented_secs: f64 = mtl_send_f64_0(drawable, sel.presented_time as *mut c_void);
689 if presented_secs.is_finite() && presented_secs > 0.0 {
690 let ns: u64 = (presented_secs * 1_000_000_000.0).round() as u64;
691 METAL_LAST_PRESENTED_NS.store(ns, Ordering::Relaxed);
692 }
693}
694
695#[cfg(any(target_os = "macos", target_os = "ios"))]
702unsafe extern "C" fn metal_completed_handler_invoke(_block: *mut c_void, cmd_buf: *mut c_void) {
703 if cmd_buf.is_null() {
704 return;
705 }
706 let sel: &MetalSelectors = cached_metal_selectors();
707 let start_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_start_time as *mut c_void);
708 let end_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_end_time as *mut c_void);
709 if start_s.is_finite() && end_s.is_finite() && end_s >= start_s {
710 let exec_ns: u64 = ((end_s - start_s) * 1_000_000_000.0).round() as u64;
711 METAL_LAST_GPU_EXEC_NS.store(exec_ns, Ordering::Relaxed);
712 }
713}
714
715#[cfg(any(target_os = "macos", target_os = "ios"))]
721fn metal_presented_block_ptr() -> *mut c_void {
722 let addr: usize = *METAL_PRESENTED_BLOCK_ADDR.get_or_init(|| {
723 let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
724 isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
725 flags: OBJC_BLOCK_IS_GLOBAL,
726 reserved: 0,
727 invoke: metal_presented_handler_invoke,
728 descriptor: &METAL_BLOCK_DESCRIPTOR,
729 });
730 Box::into_raw(block) as usize
731 });
732 addr as *mut c_void
733}
734
735#[cfg(any(target_os = "macos", target_os = "ios"))]
741fn metal_completed_block_ptr() -> *mut c_void {
742 let addr: usize = *METAL_COMPLETED_BLOCK_ADDR.get_or_init(|| {
743 let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
744 isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
745 flags: OBJC_BLOCK_IS_GLOBAL,
746 reserved: 0,
747 invoke: metal_completed_handler_invoke,
748 descriptor: &METAL_BLOCK_DESCRIPTOR,
749 });
750 Box::into_raw(block) as usize
751 });
752 addr as *mut c_void
753}
754
755#[cfg(any(target_os = "macos", target_os = "ios"))]
765fn metal_pipeline_cache_hash(device_name: &str) -> u64 {
766 let mut hash: u64 = FNV1A_OFFSET_BASIS;
767 for chunk in [
768 device_name.as_bytes(),
769 MSL_UI_SHADER.as_bytes(),
770 MSL_BACKDROP_BLUR_SHADER.as_bytes(),
771 MSL_ENGINE3D_PBR_SHADER.as_bytes(),
772 MSL_FLUID_OCEAN_SHADER.as_bytes(),
773 ]
774 .iter()
775 {
776 for &byte in chunk.iter() {
777 hash ^= byte as u64;
778 hash = hash.wrapping_mul(FNV1A_PRIME);
779 }
780 }
781 hash
782}
783
784#[cfg(any(target_os = "macos", target_os = "ios"))]
797fn metal_create_texture(
798 device: *mut c_void,
799 format: GpuAtlasPixelFormat,
800 width: u32,
801 height: u32,
802) -> usize {
803 if device.is_null() {
804 return 0;
805 }
806 let px_fmt: usize = match format {
807 GpuAtlasPixelFormat::R8Unorm => MTL_PIXEL_FORMAT_R8_UNORM,
808 GpuAtlasPixelFormat::Rgba8Unorm => MTL_PIXEL_FORMAT_RGBA8_UNORM,
809 };
810 let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
811 if cls_desc.is_null() {
812 return 0;
813 }
814 unsafe {
815 let send_desc: unsafe extern "C" fn(
816 *mut c_void,
817 *mut c_void,
818 usize,
819 usize,
820 usize,
821 i8,
822 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
823 let desc: *mut c_void = send_desc(
824 cls_desc,
825 mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
826 px_fmt,
827 width.max(1) as usize,
828 height.max(1) as usize,
829 0,
830 );
831 if desc.is_null() {
832 return 0;
833 }
834 mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
835 let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
836 tex as usize
837 }
838}
839
840#[cfg(any(target_os = "macos", target_os = "ios"))]
855fn metal_build_render_pipeline(
856 device: *mut c_void,
857 library: *mut c_void,
858 vs_name: &str,
859 fs_name: &str,
860 archive: *mut c_void,
861 enable_blend: bool,
862) -> (usize, bool) {
863 if device.is_null() || library.is_null() {
864 return (0, false);
865 }
866 let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
867 let vs_fn: *mut c_void = mtl_send_ptr1(
868 library,
869 mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
870 mtl_ns_string(vs_name),
871 );
872 let fs_fn: *mut c_void = mtl_send_ptr1(
873 library,
874 mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
875 mtl_ns_string(fs_name),
876 );
877 let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
878 if !functions_ok {
879 if !vs_fn.is_null() {
880 mtl_send_void0(vs_fn, sel_rel);
881 }
882 if !fs_fn.is_null() {
883 mtl_send_void0(fs_fn, sel_rel);
884 }
885 return (0, false);
886 }
887 let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
888 let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
889 let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
890 if desc.is_null() {
891 mtl_send_void0(vs_fn, sel_rel);
892 mtl_send_void0(fs_fn, sel_rel);
893 return (0, functions_ok);
894 }
895 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
896 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
897 let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
898 let att0: *mut c_void = unsafe {
899 let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
900 transmute(objc_msgSend as *const c_void);
901 send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
902 };
903 if !att0.is_null() {
904 mtl_send_void_usize(
905 att0,
906 mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
907 MTL_PIXEL_FORMAT_BGRA8_UNORM,
908 );
909 if enable_blend {
910 mtl_send_void_bool(att0, mtl_sel_cstr(MTL_SEL_SET_BLENDING_ENABLED), true);
911 mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_RGB_BLEND_OP), 0);
912 mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_ALPHA_BLEND_OP), 0);
913 mtl_send_void_usize(
914 att0,
915 mtl_sel_cstr(MTL_SEL_SET_SRC_RGB_BLEND),
916 MTL_BLEND_FACTOR_SRC_ALPHA,
917 );
918 mtl_send_void_usize(
919 att0,
920 mtl_sel_cstr(MTL_SEL_SET_DST_RGB_BLEND),
921 MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
922 );
923 mtl_send_void_usize(
924 att0,
925 mtl_sel_cstr(MTL_SEL_SET_SRC_ALPHA_BLEND),
926 MTL_BLEND_FACTOR_ONE,
927 );
928 mtl_send_void_usize(
929 att0,
930 mtl_sel_cstr(MTL_SEL_SET_DST_ALPHA_BLEND),
931 MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
932 );
933 }
934 }
935 if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
936 let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
937 let arr: *mut c_void =
938 mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
939 if !arr.is_null() {
940 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
941 }
942 }
943 let mut err_ptr: *mut c_void = null_mut();
944 let pipeline: *mut c_void = unsafe {
945 let send_pso: unsafe extern "C" fn(
946 *mut c_void,
947 *mut c_void,
948 *mut c_void,
949 *mut *mut c_void,
950 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
951 send_pso(
952 device,
953 mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
954 desc,
955 &mut err_ptr,
956 )
957 };
958 if !archive.is_null() && !pipeline.is_null() {
959 let mut add_err: *mut c_void = null_mut();
960 unsafe {
961 let send_add: unsafe extern "C" fn(
962 *mut c_void,
963 *mut c_void,
964 *mut c_void,
965 *mut *mut c_void,
966 ) -> i8 = transmute(objc_msgSend as *const c_void);
967 let _: i8 = send_add(
968 archive,
969 mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
970 desc,
971 &mut add_err,
972 );
973 }
974 }
975 mtl_send_void0(desc, sel_rel);
976 mtl_send_void0(vs_fn, sel_rel);
977 mtl_send_void0(fs_fn, sel_rel);
978 (pipeline as usize, functions_ok)
979}
980
981#[cfg(any(target_os = "macos", target_os = "ios"))]
993fn metal_build_render_pipeline_3d(
994 device: *mut c_void,
995 library: *mut c_void,
996 archive: *mut c_void,
997) -> (usize, bool) {
998 if device.is_null() || library.is_null() {
999 return (0, false);
1000 }
1001 let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
1002 let vs_fn: *mut c_void = mtl_send_ptr1(
1003 library,
1004 mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1005 mtl_ns_string(MTL_FN_3D_VERTEX),
1006 );
1007 let fs_fn: *mut c_void = mtl_send_ptr1(
1008 library,
1009 mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
1010 mtl_ns_string(MTL_FN_3D_FRAGMENT),
1011 );
1012 let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
1013 if !functions_ok {
1014 if !vs_fn.is_null() {
1015 mtl_send_void0(vs_fn, sel_rel);
1016 }
1017 if !fs_fn.is_null() {
1018 mtl_send_void0(fs_fn, sel_rel);
1019 }
1020 return (0, false);
1021 }
1022 let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
1023 let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1024 let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1025 if desc.is_null() {
1026 mtl_send_void0(vs_fn, sel_rel);
1027 mtl_send_void0(fs_fn, sel_rel);
1028 return (0, functions_ok);
1029 }
1030 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
1031 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
1032 let vdesc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_VERTEX_DESC);
1033 let vdesc_alloc: *mut c_void = mtl_send_ptr0(vdesc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1034 let vdesc: *mut c_void = mtl_send_ptr0(vdesc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1035 if !vdesc.is_null() {
1036 let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1037 unsafe { transmute(objc_msgSend as *const c_void) };
1038 let sel_idx: *mut c_void = mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX);
1039 let attrs: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_ATTRIBUTES));
1040 let attr0: *mut c_void = unsafe { send_idx(attrs, sel_idx, 0) };
1041 let attr1: *mut c_void = unsafe { send_idx(attrs, sel_idx, 1) };
1042 if !attr0.is_null() {
1043 mtl_send_void_usize(
1044 attr0,
1045 mtl_sel_cstr(MTL_SEL_SET_FORMAT),
1046 MTL_VERTEX_FORMAT_FLOAT3,
1047 );
1048 mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 0);
1049 mtl_send_void_usize(attr0, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
1050 }
1051 if !attr1.is_null() {
1052 mtl_send_void_usize(
1053 attr1,
1054 mtl_sel_cstr(MTL_SEL_SET_FORMAT),
1055 MTL_VERTEX_FORMAT_FLOAT3,
1056 );
1057 mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_OFFSET), 12);
1058 mtl_send_void_usize(attr1, mtl_sel_cstr(MTL_SEL_SET_BUFFER_INDEX), 2);
1059 }
1060 let layouts: *mut c_void = mtl_send_ptr0(vdesc, mtl_sel_cstr(MTL_SEL_LAYOUTS));
1061 let layout2: *mut c_void = unsafe { send_idx(layouts, sel_idx, 2) };
1062 if !layout2.is_null() {
1063 mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STRIDE), 24);
1064 mtl_send_void_usize(
1065 layout2,
1066 mtl_sel_cstr(MTL_SEL_SET_STEP_FUNCTION),
1067 MTL_VERTEX_STEP_PER_VERTEX,
1068 );
1069 mtl_send_void_usize(layout2, mtl_sel_cstr(MTL_SEL_SET_STEP_RATE), 1);
1070 }
1071 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_DESC), vdesc);
1072 mtl_send_void0(vdesc, sel_rel);
1073 }
1074 let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
1075 let att0: *mut c_void = unsafe {
1076 let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1077 transmute(objc_msgSend as *const c_void);
1078 send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
1079 };
1080 if !att0.is_null() {
1081 mtl_send_void_usize(
1082 att0,
1083 mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1084 MTL_PIXEL_FORMAT_BGRA8_UNORM,
1085 );
1086 }
1087 if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
1088 let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
1089 let arr: *mut c_void =
1090 mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
1091 if !arr.is_null() {
1092 mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
1093 }
1094 }
1095 let mut err_ptr: *mut c_void = null_mut();
1096 let pipeline: *mut c_void = unsafe {
1097 let send_pso: unsafe extern "C" fn(
1098 *mut c_void,
1099 *mut c_void,
1100 *mut c_void,
1101 *mut *mut c_void,
1102 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1103 send_pso(
1104 device,
1105 mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
1106 desc,
1107 &mut err_ptr,
1108 )
1109 };
1110 if !archive.is_null() && !pipeline.is_null() {
1111 let mut add_err: *mut c_void = null_mut();
1112 unsafe {
1113 let send_add: unsafe extern "C" fn(
1114 *mut c_void,
1115 *mut c_void,
1116 *mut c_void,
1117 *mut *mut c_void,
1118 ) -> i8 = transmute(objc_msgSend as *const c_void);
1119 let _: i8 = send_add(
1120 archive,
1121 mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
1122 desc,
1123 &mut add_err,
1124 );
1125 }
1126 }
1127 mtl_send_void0(desc, sel_rel);
1128 mtl_send_void0(vs_fn, sel_rel);
1129 mtl_send_void0(fs_fn, sel_rel);
1130 (pipeline as usize, functions_ok)
1131}
1132
1133#[must_use]
1144pub fn metal_binary_archive_allowed(device_name: &str, is_simulator: bool) -> bool {
1145 if is_simulator {
1146 return false;
1147 }
1148 let lower: String = device_name.to_ascii_lowercase();
1149 !lower.contains(MTL_SIMULATOR_TOKEN) && !lower.contains(MTL_VIRTUAL_TOKEN)
1150}
1151
1152#[cfg(any(target_os = "macos", target_os = "ios"))]
1163fn metal_open_binary_archive(
1164 device: *mut c_void,
1165 device_name: &str,
1166) -> (*mut c_void, *mut c_void, bool) {
1167 if !metal_binary_archive_allowed(device_name, cfg!(target_abi = "sim"))
1168 || !mtl_responds_to_sel(device, mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE))
1169 {
1170 return (null_mut(), null_mut(), false);
1171 }
1172 let arch_desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_BINARY_ARCHIVE_DESC);
1173 if arch_desc_cls.is_null() {
1174 return (null_mut(), null_mut(), false);
1175 }
1176 let cache_hash: u64 = metal_pipeline_cache_hash(device_name);
1177 let archive_path: String = env::temp_dir()
1178 .join(format!(
1179 "{MTL_ARCHIVE_FILE_PREFIX}{cache_hash:016x}{MTL_ARCHIVE_FILE_SUFFIX}"
1180 ))
1181 .to_string_lossy()
1182 .into_owned();
1183 let existed: bool = fs::metadata(&archive_path).is_ok();
1184 let ns_path: *mut c_void = mtl_ns_string(&archive_path);
1185 let url_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_URL);
1186 let ns_url: *mut c_void =
1187 mtl_send_ptr1(url_cls, mtl_sel_cstr(MTL_SEL_FILE_URL_WITH_PATH), ns_path);
1188 let arch_desc_alloc: *mut c_void = mtl_send_ptr0(arch_desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
1189 let arch_desc: *mut c_void = mtl_send_ptr0(arch_desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
1190 if arch_desc.is_null() {
1191 return (null_mut(), ns_url, existed);
1192 }
1193 if existed && !ns_url.is_null() {
1194 mtl_send_void_ptr1(arch_desc, mtl_sel_cstr(MTL_SEL_SET_URL), ns_url);
1195 }
1196 let mut err_ptr: *mut c_void = null_mut();
1197 let archive: *mut c_void = unsafe {
1198 let send_new: unsafe extern "C" fn(
1199 *mut c_void,
1200 *mut c_void,
1201 *mut c_void,
1202 *mut *mut c_void,
1203 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1204 send_new(
1205 device,
1206 mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE),
1207 arch_desc,
1208 &mut err_ptr,
1209 )
1210 };
1211 mtl_send_void0(arch_desc, mtl_sel_cstr(MTL_SEL_RELEASE));
1212 (archive, ns_url, existed)
1213}
1214
1215#[cfg(any(target_os = "macos", target_os = "ios"))]
1225fn init_apple_metal_shared_cache(backend: GraphicsBackend) -> &'static MetalSharedPipelineCache {
1226 METAL_SHARED_PIPELINE.get_or_init(|| {
1227 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1228 let total_start: Instant = Instant::now();
1229 let result: MetalSharedPipelineCache = unsafe {
1230 let device: *mut c_void = MTLCreateSystemDefaultDevice();
1231 if device.is_null() {
1232 MetalSharedPipelineCache {
1233 adapter: GpuAdapterInfo::new(
1234 backend,
1235 GPU_DEVICE_FALLBACK.to_string(),
1236 false,
1237 false,
1238 ),
1239 device: 0,
1240 queue: 0,
1241 library: 0,
1242 pipeline: 0,
1243 blur_pipeline: 0,
1244 engine3d_pipeline: 0,
1245 ocean_pipeline: 0,
1246 binary_archive_enabled: false,
1247 binary_archive_hit: false,
1248 ui_compile_us: 0,
1249 blur_compile_us: 0,
1250 engine3d_compile_us: 0,
1251 ocean_compile_us: 0,
1252 total_compile_us: 0,
1253 dummy_r8_tex: 0,
1254 dummy_rgba8_tex: 0,
1255 }
1256 } else {
1257 let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NAME));
1258 let utf8_ptr: *const c_char =
1259 mtl_send_ptr0(ns_name, mtl_sel_cstr(MTL_SEL_UTF8_STRING)).cast::<c_char>();
1260 let device_name: String = if utf8_ptr.is_null() {
1261 GPU_DEVICE_APPLE_METAL.to_string()
1262 } else {
1263 CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
1264 };
1265 let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NEW_CMD_QUEUE));
1266 let (archive, archive_url, archive_existed): (*mut c_void, *mut c_void, bool) =
1267 metal_open_binary_archive(device, &device_name);
1268 let archive_enabled: bool = !archive.is_null();
1269 let send_lib: unsafe extern "C" fn(
1270 *mut c_void,
1271 *mut c_void,
1272 *mut c_void,
1273 *mut c_void,
1274 *mut *mut c_void,
1275 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1276 let ui_start: Instant = Instant::now();
1277 let mut err_ptr: *mut c_void = null_mut();
1278 let library: *mut c_void = send_lib(
1279 device,
1280 mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1281 mtl_ns_string(MSL_UI_SHADER),
1282 null_mut(),
1283 &mut err_ptr,
1284 );
1285 let (pipeline, ui_fns_ok): (usize, bool) = metal_build_render_pipeline(
1286 device,
1287 library,
1288 MTL_FN_VERTEX,
1289 MTL_FN_FRAGMENT,
1290 archive,
1291 true,
1292 );
1293 let ui_compile_us: u64 = ui_start.elapsed().as_micros() as u64;
1294 let blur_start: Instant = Instant::now();
1295 let mut blur_err: *mut c_void = null_mut();
1296 let blur_lib: *mut c_void = send_lib(
1297 device,
1298 mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1299 mtl_ns_string(MSL_BACKDROP_BLUR_SHADER),
1300 null_mut(),
1301 &mut blur_err,
1302 );
1303 let (blur_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1304 device,
1305 blur_lib,
1306 MTL_FN_BLUR_VERTEX,
1307 MTL_FN_BLUR_DOWN,
1308 archive,
1309 false,
1310 );
1311 let (blur_up_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1312 device,
1313 blur_lib,
1314 MTL_FN_BLUR_VERTEX,
1315 MTL_FN_BLUR_UP,
1316 archive,
1317 false,
1318 );
1319 if blur_up_pipeline != 0 {
1320 mtl_send_void0(
1321 blur_up_pipeline as *mut c_void,
1322 mtl_sel_cstr(MTL_SEL_RELEASE),
1323 );
1324 }
1325 if !blur_lib.is_null() {
1326 mtl_send_void0(blur_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1327 }
1328 let blur_compile_us: u64 = blur_start.elapsed().as_micros() as u64;
1329 let pbr_start: Instant = Instant::now();
1330 let mut pbr_err: *mut c_void = null_mut();
1331 let pbr_lib: *mut c_void = send_lib(
1332 device,
1333 mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1334 mtl_ns_string(MSL_ENGINE3D_PBR_SHADER),
1335 null_mut(),
1336 &mut pbr_err,
1337 );
1338 let (engine3d_pipeline, _): (usize, bool) =
1339 metal_build_render_pipeline_3d(device, pbr_lib, archive);
1340 if !pbr_lib.is_null() {
1341 mtl_send_void0(pbr_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1342 }
1343 let engine3d_compile_us: u64 = pbr_start.elapsed().as_micros() as u64;
1344 let ocean_start: Instant = Instant::now();
1345 let mut ocean_err: *mut c_void = null_mut();
1346 let ocean_lib: *mut c_void = send_lib(
1347 device,
1348 mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
1349 mtl_ns_string(MSL_FLUID_OCEAN_SHADER),
1350 null_mut(),
1351 &mut ocean_err,
1352 );
1353 let (ocean_pipeline, _): (usize, bool) = metal_build_render_pipeline(
1354 device,
1355 ocean_lib,
1356 MTL_FN_OCEAN_VERTEX,
1357 MTL_FN_OCEAN_FRAGMENT,
1358 archive,
1359 false,
1360 );
1361 if !ocean_lib.is_null() {
1362 mtl_send_void0(ocean_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
1363 }
1364 let ocean_compile_us: u64 = ocean_start.elapsed().as_micros() as u64;
1365 if !archive.is_null() {
1366 if !archive_existed
1367 && !archive_url.is_null()
1368 && pipeline != 0
1369 && metal_binary_archive_allowed(&device_name, cfg!(target_abi = "sim"))
1370 && mtl_responds_to_sel(archive, mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL))
1371 {
1372 let mut ser_err: *mut c_void = null_mut();
1373 let send_ser: unsafe extern "C" fn(
1374 *mut c_void,
1375 *mut c_void,
1376 *mut c_void,
1377 *mut *mut c_void,
1378 ) -> i8 = transmute(objc_msgSend as *const c_void);
1379 let _: i8 = send_ser(
1380 archive,
1381 mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL),
1382 archive_url,
1383 &mut ser_err,
1384 );
1385 }
1386 mtl_send_void0(archive, mtl_sel_cstr(MTL_SEL_RELEASE));
1387 }
1388 let dummy_r8_tex: usize =
1389 metal_create_texture(device, GpuAtlasPixelFormat::R8Unorm, 1, 1);
1390 let dummy_rgba8_tex: usize =
1391 metal_create_texture(device, GpuAtlasPixelFormat::Rgba8Unorm, 1, 1);
1392 let shader_compiled: bool = ui_fns_ok && pipeline != 0;
1393 let total_compile_us: u64 = total_start.elapsed().as_micros() as u64;
1394 MetalSharedPipelineCache {
1395 adapter: GpuAdapterInfo::new(
1396 GraphicsBackend::Metal,
1397 device_name,
1398 !queue.is_null(),
1399 shader_compiled,
1400 ),
1401 device: device as usize,
1402 queue: queue as usize,
1403 library: library as usize,
1404 pipeline,
1405 blur_pipeline,
1406 engine3d_pipeline,
1407 ocean_pipeline,
1408 binary_archive_enabled: archive_enabled,
1409 binary_archive_hit: archive_enabled && archive_existed,
1410 ui_compile_us,
1411 blur_compile_us,
1412 engine3d_compile_us,
1413 ocean_compile_us,
1414 total_compile_us,
1415 dummy_r8_tex,
1416 dummy_rgba8_tex,
1417 }
1418 }
1419 };
1420 unsafe { objc_autoreleasePoolPop(pool) };
1421 result
1422 })
1423}
1424
1425#[cfg(any(target_os = "macos", target_os = "ios"))]
1435fn probe_apple_metal_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
1436 let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
1437 NativeGpuProbeOutput {
1438 adapter: cached.adapter.clone(),
1439 device_handle: mtl_retain_handle(cached.device),
1440 queue_handle: mtl_retain_handle(cached.queue),
1441 library_handle: mtl_retain_handle(cached.library),
1442 pipeline_handle: mtl_retain_handle(cached.pipeline),
1443 blur_pipeline_handle: mtl_retain_handle(cached.blur_pipeline),
1444 engine3d_pipeline_handle: mtl_retain_handle(cached.engine3d_pipeline),
1445 ocean_pipeline_handle: mtl_retain_handle(cached.ocean_pipeline),
1446 dummy_r8_tex: mtl_retain_handle(cached.dummy_r8_tex),
1447 dummy_rgba8_tex: mtl_retain_handle(cached.dummy_rgba8_tex),
1448 }
1449}
1450
1451#[cfg(any(target_os = "macos", target_os = "ios"))]
1457fn cached_metal_selectors() -> &'static MetalSelectors {
1458 METAL_SELECTORS.get_or_init(|| MetalSelectors {
1459 retain: mtl_sel_cstr(MTL_SEL_RETAIN) as usize,
1460 new_buffer_with_bytes: mtl_sel_cstr(MTL_SEL_NEW_BUFFER) as usize,
1461 new_buffer_with_length: mtl_sel_cstr(MTL_SEL_NEW_BUFFER_LENGTH) as usize,
1462 contents: mtl_sel_cstr(MTL_SEL_CONTENTS) as usize,
1463 command_buffer: mtl_sel_cstr(MTL_SEL_CMD_BUFFER) as usize,
1464 render_encoder: mtl_sel_cstr(MTL_SEL_RENDER_ENCODER) as usize,
1465 set_pipeline_state: mtl_sel_cstr(MTL_SEL_SET_PIPELINE_STATE) as usize,
1466 set_vertex_buffer: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BUFFER) as usize,
1467 set_vertex_bytes: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BYTES) as usize,
1468 set_fragment_texture: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_TEXTURE) as usize,
1469 set_scissor_rect: mtl_sel_cstr(MTL_SEL_SET_SCISSOR_RECT) as usize,
1470 draw_primitives_instanced: mtl_sel_cstr(MTL_SEL_DRAW_PRIMITIVES_INSTANCED) as usize,
1471 end_encoding: mtl_sel_cstr(MTL_SEL_END_ENCODING) as usize,
1472 present_drawable: mtl_sel_cstr(MTL_SEL_PRESENT_DRAWABLE) as usize,
1473 add_presented_handler: mtl_sel_cstr(MTL_SEL_ADD_PRESENTED_HANDLER) as usize,
1474 add_completed_handler: mtl_sel_cstr(MTL_SEL_ADD_COMPLETED_HANDLER) as usize,
1475 presented_time: mtl_sel_cstr(MTL_SEL_PRESENTED_TIME) as usize,
1476 responds_to_sel: mtl_sel_cstr(MTL_SEL_RESPONDS_TO_SEL) as usize,
1477 status: mtl_sel_cstr(MTL_SEL_STATUS) as usize,
1478 wait_until_completed: mtl_sel_cstr(MTL_SEL_WAIT_UNTIL_COMPLETED) as usize,
1479 gpu_start_time: mtl_sel_cstr(MTL_SEL_GPU_START_TIME) as usize,
1480 gpu_end_time: mtl_sel_cstr(MTL_SEL_GPU_END_TIME) as usize,
1481 next_drawable: mtl_sel_cstr(MTL_SEL_NEXT_DRAWABLE) as usize,
1482 drawable_size: mtl_sel_cstr(MTL_SEL_DRAWABLE_SIZE) as usize,
1483 set_drawable_size: mtl_sel_cstr(MTL_SEL_SET_DRAWABLE_SIZE) as usize,
1484 texture: mtl_sel_cstr(MTL_SEL_TEXTURE) as usize,
1485 width: mtl_sel_cstr(MTL_SEL_WIDTH) as usize,
1486 height: mtl_sel_cstr(MTL_SEL_HEIGHT) as usize,
1487 render_pass_desc: mtl_sel_cstr(MTL_SEL_RENDER_PASS_DESC) as usize,
1488 color_attachments: mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS) as usize,
1489 object_at_index: mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX) as usize,
1490 set_texture: mtl_sel_cstr(MTL_SEL_SET_TEXTURE) as usize,
1491 set_load_action: mtl_sel_cstr(MTL_SEL_SET_LOAD_ACTION) as usize,
1492 set_store_action: mtl_sel_cstr(MTL_SEL_SET_STORE_ACTION) as usize,
1493 set_clear_color: mtl_sel_cstr(MTL_SEL_SET_CLEAR_COLOR) as usize,
1494 replace_region: mtl_sel_cstr(MTL_SEL_REPLACE_REGION) as usize,
1495 commit: mtl_sel_cstr(MTL_SEL_COMMIT) as usize,
1496 release: mtl_sel_cstr(MTL_SEL_RELEASE) as usize,
1497 })
1498}
1499
1500#[cfg(any(target_os = "macos", target_os = "ios"))]
1507fn metal_configure_layer(device_handle: usize, layer_handle: usize) {
1508 if device_handle == 0 || layer_handle == 0 {
1509 return;
1510 }
1511 let layer: *mut c_void = layer_handle as *mut c_void;
1512 mtl_send_void_ptr1(
1513 layer,
1514 mtl_sel_cstr(MTL_SEL_SET_DEVICE),
1515 device_handle as *mut c_void,
1516 );
1517 mtl_send_void_usize(
1518 layer,
1519 mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
1520 MTL_PIXEL_FORMAT_BGRA8_UNORM,
1521 );
1522 mtl_send_void_bool(layer, mtl_sel_cstr(MTL_SEL_SET_FRAMEBUFFER_ONLY), true);
1523 let sel_max: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_MAX_DRAWABLE_COUNT);
1524 if mtl_responds_to_sel(layer, sel_max) {
1525 mtl_send_void_usize(layer, sel_max, GPU_DRIVER_RING_SLOTS);
1526 }
1527 let sel_sync: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_DISPLAY_SYNC);
1528 if mtl_responds_to_sel(layer, sel_sync) {
1529 mtl_send_void_bool(layer, sel_sync, true);
1530 }
1531}
1532
1533#[cfg(any(target_os = "macos", target_os = "ios"))]
1549fn metal_upload_texture_dirty_rect(
1550 device_handle: usize,
1551 texture_handle: &mut usize,
1552 format: GpuAtlasPixelFormat,
1553 tex_dims: (u32, u32),
1554 dirty_rect: (u32, u32, u32, u32),
1555 bytes: &[u8],
1556 bytes_per_row: usize,
1557) -> bool {
1558 if device_handle == 0 || dirty_rect.2 == 0 || dirty_rect.3 == 0 || bytes.is_empty() {
1559 return false;
1560 }
1561 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1562 let (tex_w, tex_h): (u32, u32) = (tex_dims.0.max(1), tex_dims.1.max(1));
1563 let sel: &MetalSelectors = cached_metal_selectors();
1564 let cur_w: usize = if *texture_handle != 0 {
1565 mtl_send_usize0(*texture_handle as *mut c_void, sel.width as *mut c_void)
1566 } else {
1567 0
1568 };
1569 let cur_h: usize = if *texture_handle != 0 {
1570 mtl_send_usize0(*texture_handle as *mut c_void, sel.height as *mut c_void)
1571 } else {
1572 0
1573 };
1574 if *texture_handle == 0 || cur_w != tex_w as usize || cur_h != tex_h as usize {
1575 if *texture_handle != 0 {
1576 mtl_send_void0(*texture_handle as *mut c_void, sel.release as *mut c_void);
1577 }
1578 *texture_handle = metal_create_texture(device_handle as *mut c_void, format, tex_w, tex_h);
1579 }
1580 if *texture_handle == 0 {
1581 unsafe { objc_autoreleasePoolPop(pool) };
1582 return false;
1583 }
1584 let region: MtlRegion = MtlRegion {
1585 origin: MtlOrigin {
1586 x: dirty_rect.0 as usize,
1587 y: dirty_rect.1 as usize,
1588 z: 0,
1589 },
1590 size: MtlSize {
1591 width: dirty_rect.2 as usize,
1592 height: dirty_rect.3 as usize,
1593 depth: 1,
1594 },
1595 };
1596 unsafe {
1597 let send_replace: unsafe extern "C" fn(
1598 *mut c_void,
1599 *mut c_void,
1600 MtlRegion,
1601 usize,
1602 *const c_void,
1603 usize,
1604 ) = transmute(objc_msgSend as *const c_void);
1605 send_replace(
1606 *texture_handle as *mut c_void,
1607 sel.replace_region as *mut c_void,
1608 region,
1609 0,
1610 bytes.as_ptr().cast::<c_void>(),
1611 bytes_per_row,
1612 );
1613 objc_autoreleasePoolPop(pool);
1614 }
1615 true
1616}
1617
1618#[cfg(any(target_os = "macos", target_os = "ios"))]
1632fn metal_submit_ring_frame(
1633 driver: &mut NativeGpuDriver,
1634 width: u32,
1635 height: u32,
1636 clear_color: Color,
1637 batches: &[GpuBatch],
1638) -> usize {
1639 let total_instances: usize = batches
1640 .iter()
1641 .map(|blue_val: &GpuBatch| {
1642 blue_val
1643 .get_primitives()
1644 .len()
1645 .max(blue_val.get_instances().len())
1646 })
1647 .sum();
1648 let device_handle: usize = driver.get_device_handle();
1649 let queue_handle: usize = driver.get_queue_handle();
1650 if device_handle == 0 || queue_handle == 0 {
1651 return total_instances;
1652 }
1653 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
1654 let sel: &MetalSelectors = cached_metal_selectors();
1655 let sel_rel: *mut c_void = sel.release as *mut c_void;
1656 let slot_idx: usize = driver.get_ring_cursor() % GPU_DRIVER_RING_SLOTS;
1657 let device: *mut c_void = device_handle as *mut c_void;
1658 let queue: *mut c_void = queue_handle as *mut c_void;
1659 let pipeline: *mut c_void = driver.get_pipeline_handle() as *mut c_void;
1660 let layer_ptr: *mut c_void = driver.get_surface_layer_handle() as *mut c_void;
1661 let tex_r8: *mut c_void = driver.get_glyph_r8_texture_handle() as *mut c_void;
1662 let tex_rgba8: *mut c_void = driver.get_glyph_rgba8_texture_handle() as *mut c_void;
1663 let tex_img: *mut c_void = driver.get_image_texture_handle() as *mut c_void;
1664 let raw_ext: usize = driver.get_external_texture_handle();
1665 let tex_ext: *mut c_void = if raw_ext != 0 {
1666 raw_ext as *mut c_void
1667 } else {
1668 tex_rgba8
1669 };
1670 let total_bytes: usize = total_instances.saturating_mul(size_of::<GpuPrimitiveInstance>());
1671 let NativeGpuDriver {
1672 ring_slots,
1673 ring_cursor,
1674 staging_buffer_handle,
1675 staging_contents_ptr,
1676 staging_buffer_capacity,
1677 staging_reallocations,
1678 scratch_primitives,
1679 ..
1680 } = driver;
1681 let slot: &mut NativeGpuRingSlot = &mut ring_slots[slot_idx];
1682 let prev_cmd: usize = slot.get_in_flight_cmd_buffer();
1683 if prev_cmd != 0 {
1684 let status: usize = mtl_send_usize0(prev_cmd as *mut c_void, sel.status as *mut c_void);
1685 if status < MTL_CMD_BUFFER_STATUS_COMPLETED {
1686 mtl_send_void0(
1687 prev_cmd as *mut c_void,
1688 sel.wait_until_completed as *mut c_void,
1689 );
1690 }
1691 mtl_send_void0(prev_cmd as *mut c_void, sel_rel);
1692 slot.set_in_flight_cmd_buffer(0);
1693 }
1694 if total_bytes > 0
1695 && (slot.get_buffer_handle() == 0
1696 || slot.get_contents_ptr() == 0
1697 || total_bytes > slot.get_capacity_bytes())
1698 {
1699 if slot.get_buffer_handle() != 0 {
1700 mtl_send_void0(slot.get_buffer_handle() as *mut c_void, sel_rel);
1701 slot.set_buffer_handle(0);
1702 slot.set_contents_ptr(0);
1703 slot.set_capacity_bytes(0);
1704 }
1705 let alloc_bytes: usize = total_bytes.max(4096).next_power_of_two();
1706 unsafe {
1707 let send_new_len: unsafe extern "C" fn(
1708 *mut c_void,
1709 *mut c_void,
1710 usize,
1711 usize,
1712 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1713 let new_buf: *mut c_void = send_new_len(
1714 device,
1715 sel.new_buffer_with_length as *mut c_void,
1716 alloc_bytes,
1717 0,
1718 );
1719 if !new_buf.is_null() {
1720 let ptr: *mut c_void = mtl_send_ptr0(new_buf, sel.contents as *mut c_void);
1721 if !ptr.is_null() {
1722 slot.set_buffer_handle(new_buf as usize);
1723 slot.set_contents_ptr(ptr as usize);
1724 slot.set_capacity_bytes(alloc_bytes);
1725 *staging_reallocations = staging_reallocations.wrapping_add(1);
1726 } else {
1727 mtl_send_void0(new_buf, sel_rel);
1728 }
1729 }
1730 }
1731 }
1732 let buf_handle: usize = slot.get_buffer_handle();
1733 let contents_ptr: usize = slot.get_contents_ptr();
1734 let capacity_bytes: usize = slot.get_capacity_bytes();
1735 *staging_buffer_handle = buf_handle;
1736 *staging_contents_ptr = contents_ptr;
1737 *staging_buffer_capacity = capacity_bytes;
1738 if contents_ptr != 0 && total_bytes > 0 && total_bytes <= capacity_bytes {
1739 unsafe {
1740 let mut dst: *mut u8 = (contents_ptr as *mut c_void).cast::<u8>();
1741 for batch in batches.iter() {
1742 let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
1743 if !prims.is_empty() {
1744 let byte_len: usize = size_of_val(prims);
1745 dst.copy_from_nonoverlapping(prims.as_ptr().cast::<u8>(), byte_len);
1746 dst = dst.add(byte_len);
1747 } else if !batch.get_instances().is_empty() {
1748 scratch_primitives.clear();
1749 for quad in batch.get_instances().iter() {
1750 scratch_primitives.push(GpuPrimitiveInstance::from_quad_instance(
1751 quad,
1752 batch.get_texture_slot(),
1753 batch.get_layer_id(),
1754 ));
1755 }
1756 let byte_len: usize = size_of_val(scratch_primitives.as_slice());
1757 dst.copy_from_nonoverlapping(
1758 scratch_primitives.as_ptr().cast::<u8>(),
1759 byte_len,
1760 );
1761 dst = dst.add(byte_len);
1762 }
1763 }
1764 }
1765 }
1766 let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
1767 if !cmd_buf.is_null() {
1768 let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
1769 if mtl_responds_to_sel(cmd_buf, sel_completed) {
1770 mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
1771 }
1772 if !layer_ptr.is_null() && !pipeline.is_null() {
1773 if width > 0
1774 && height > 0
1775 && mtl_responds_to_sel(layer_ptr, sel.set_drawable_size as *mut c_void)
1776 {
1777 let target_w: f64 = f64::from(width);
1778 let target_h: f64 = f64::from(height);
1779 let needs_resize: bool =
1780 if mtl_responds_to_sel(layer_ptr, sel.drawable_size as *mut c_void) {
1781 let cur: MtlCgSize = unsafe {
1783 let get_size: unsafe extern "C" fn(
1784 *mut c_void,
1785 *mut c_void,
1786 )
1787 -> MtlCgSize = transmute(objc_msgSend as *const c_void);
1788 get_size(layer_ptr, sel.drawable_size as *mut c_void)
1789 };
1790 (cur.width - target_w).abs() > 0.5 || (cur.height - target_h).abs() > 0.5
1791 } else {
1792 true
1793 };
1794 if needs_resize {
1795 unsafe {
1797 let set_size: unsafe extern "C" fn(*mut c_void, *mut c_void, MtlCgSize) =
1798 transmute(objc_msgSend as *const c_void);
1799 set_size(
1800 layer_ptr,
1801 sel.set_drawable_size as *mut c_void,
1802 MtlCgSize {
1803 width: target_w,
1804 height: target_h,
1805 },
1806 );
1807 }
1808 }
1809 }
1810 let drawable: *mut c_void = mtl_send_ptr0(layer_ptr, sel.next_drawable as *mut c_void);
1811 if !drawable.is_null() {
1812 let drawable_tex: *mut c_void = mtl_send_ptr0(drawable, sel.texture as *mut c_void);
1813 let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
1814 let pass_desc: *mut c_void =
1815 mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
1816 if !drawable_tex.is_null() && !pass_desc.is_null() {
1817 let draw_w: usize = mtl_send_usize0(drawable_tex, sel.width as *mut c_void)
1818 .max(width.max(1) as usize);
1819 let draw_h: usize = mtl_send_usize0(drawable_tex, sel.height as *mut c_void)
1820 .max(height.max(1) as usize);
1821 let color_atts: *mut c_void =
1822 mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
1823 let att0: *mut c_void = unsafe {
1824 let send_idx: unsafe extern "C" fn(
1825 *mut c_void,
1826 *mut c_void,
1827 usize,
1828 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
1829 send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
1830 };
1831 if !att0.is_null() {
1832 mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, drawable_tex);
1833 mtl_send_void_usize(
1834 att0,
1835 sel.set_load_action as *mut c_void,
1836 MTL_LOAD_ACTION_CLEAR,
1837 );
1838 mtl_send_void_usize(
1839 att0,
1840 sel.set_store_action as *mut c_void,
1841 MTL_STORE_ACTION_STORE,
1842 );
1843 let clear_rgba: [f32; 4] = clear_color.to_f32_array();
1844 let mtl_clear: MtlClearColor = MtlClearColor {
1845 red: clear_rgba[0] as f64,
1846 green: clear_rgba[1] as f64,
1847 blue: clear_rgba[2] as f64,
1848 alpha: clear_rgba[3] as f64,
1849 };
1850 unsafe {
1851 let send_clear: unsafe extern "C" fn(
1852 *mut c_void,
1853 *mut c_void,
1854 MtlClearColor,
1855 ) = transmute(objc_msgSend as *const c_void);
1856 send_clear(att0, sel.set_clear_color as *mut c_void, mtl_clear);
1857 }
1858 }
1859 let encoder: *mut c_void =
1860 mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
1861 if !encoder.is_null() {
1862 mtl_send_void_ptr1(
1863 encoder,
1864 sel.set_pipeline_state as *mut c_void,
1865 pipeline,
1866 );
1867 unsafe {
1868 let send_vbuf: unsafe extern "C" fn(
1869 *mut c_void,
1870 *mut c_void,
1871 *mut c_void,
1872 usize,
1873 usize,
1874 ) = transmute(objc_msgSend as *const c_void);
1875 let send_vbytes: unsafe extern "C" fn(
1876 *mut c_void,
1877 *mut c_void,
1878 *const c_void,
1879 usize,
1880 usize,
1881 ) = transmute(objc_msgSend as *const c_void);
1882 let send_ftex: unsafe extern "C" fn(
1883 *mut c_void,
1884 *mut c_void,
1885 *mut c_void,
1886 usize,
1887 ) = transmute(objc_msgSend as *const c_void);
1888 let send_scissor: unsafe extern "C" fn(
1889 *mut c_void,
1890 *mut c_void,
1891 MtlScissorRect,
1892 ) = transmute(objc_msgSend as *const c_void);
1893 let send_draw: unsafe extern "C" fn(
1894 *mut c_void,
1895 *mut c_void,
1896 usize,
1897 usize,
1898 usize,
1899 usize,
1900 usize,
1901 ) = transmute(objc_msgSend as *const c_void);
1902 if buf_handle != 0 {
1903 send_vbuf(
1904 encoder,
1905 sel.set_vertex_buffer as *mut c_void,
1906 buf_handle as *mut c_void,
1907 0,
1908 0,
1909 );
1910 }
1911 if !tex_r8.is_null() {
1912 send_ftex(
1913 encoder,
1914 sel.set_fragment_texture as *mut c_void,
1915 tex_r8,
1916 0,
1917 );
1918 }
1919 if !tex_rgba8.is_null() {
1920 send_ftex(
1921 encoder,
1922 sel.set_fragment_texture as *mut c_void,
1923 tex_rgba8,
1924 1,
1925 );
1926 }
1927 if !tex_img.is_null() {
1928 send_ftex(
1929 encoder,
1930 sel.set_fragment_texture as *mut c_void,
1931 tex_img,
1932 2,
1933 );
1934 }
1935 if !tex_ext.is_null() {
1936 send_ftex(
1937 encoder,
1938 sel.set_fragment_texture as *mut c_void,
1939 tex_ext,
1940 3,
1941 );
1942 }
1943 let mut base_instance: usize = 0;
1944 for batch in batches.iter() {
1945 let count: usize = batch
1946 .get_primitives()
1947 .len()
1948 .max(batch.get_instances().len());
1949 if count == 0 || buf_handle == 0 {
1950 continue;
1951 }
1952 let uniform: GpuLayerUniform = GpuLayerUniform::new(
1953 draw_w as f32,
1954 draw_h as f32,
1955 batch.get_scroll_offset(),
1956 );
1957 send_vbytes(
1958 encoder,
1959 sel.set_vertex_bytes as *mut c_void,
1960 (&uniform as *const GpuLayerUniform).cast::<c_void>(),
1961 size_of::<GpuLayerUniform>(),
1962 1,
1963 );
1964 let rect_bounds: Rect = batch.get_scissor();
1965 let sx: usize = (rect_bounds.get_x().max(0.0).floor() as usize)
1966 .min(draw_w.saturating_sub(1));
1967 let sy: usize = (rect_bounds.get_y().max(0.0).floor() as usize)
1968 .min(draw_h.saturating_sub(1));
1969 let stroke_width: usize = (rect_bounds.get_width().max(1.0).ceil()
1970 as usize)
1971 .min(draw_w.saturating_sub(sx))
1972 .max(1);
1973 let sh: usize = (rect_bounds.get_height().max(1.0).ceil() as usize)
1974 .min(draw_h.saturating_sub(sy))
1975 .max(1);
1976 send_scissor(
1977 encoder,
1978 sel.set_scissor_rect as *mut c_void,
1979 MtlScissorRect {
1980 x: sx,
1981 y: sy,
1982 width: stroke_width,
1983 height: sh,
1984 },
1985 );
1986 send_draw(
1987 encoder,
1988 sel.draw_primitives_instanced as *mut c_void,
1989 MTL_PRIMITIVE_TYPE_TRIANGLE,
1990 0,
1991 6,
1992 count,
1993 base_instance,
1994 );
1995 base_instance = base_instance.saturating_add(count);
1996 }
1997 }
1998 mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
1999 }
2000 let sel_pres: *mut c_void = sel.add_presented_handler as *mut c_void;
2001 if mtl_responds_to_sel(drawable, sel_pres) {
2002 mtl_send_void_ptr1(drawable, sel_pres, metal_presented_block_ptr());
2003 }
2004 mtl_send_void_ptr1(cmd_buf, sel.present_drawable as *mut c_void, drawable);
2005 }
2006 }
2007 }
2008 let retained_cmd: usize = mtl_retain_handle(cmd_buf as usize);
2009 slot.set_in_flight_cmd_buffer(retained_cmd);
2010 mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
2011 }
2012 *ring_cursor = (slot_idx + 1) % GPU_DRIVER_RING_SLOTS;
2013 unsafe { objc_autoreleasePoolPop(pool) };
2014 total_instances
2015}
2016
2017#[cfg(any(target_os = "macos", target_os = "ios"))]
2029fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
2030 let total_instances: usize = batches
2031 .iter()
2032 .map(|blue_val: &GpuBatch| {
2033 blue_val
2034 .get_primitives()
2035 .len()
2036 .max(blue_val.get_instances().len())
2037 })
2038 .sum();
2039 if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
2040 return total_instances;
2041 }
2042 let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
2043 let device: *mut c_void = device_handle as *mut c_void;
2044 let queue: *mut c_void = queue_handle as *mut c_void;
2045 let sel: &MetalSelectors = cached_metal_selectors();
2046 let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
2047 let sel_rel: *mut c_void = sel.release as *mut c_void;
2048 unsafe {
2049 let send_buf: unsafe extern "C" fn(
2050 *mut c_void,
2051 *mut c_void,
2052 *const c_void,
2053 usize,
2054 usize,
2055 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
2056 for batch in batches.iter() {
2057 let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
2058 if !prims.is_empty() {
2059 let byte_len: usize = size_of_val(prims);
2060 let mtl_buf: *mut c_void = send_buf(
2061 device,
2062 sel_buf,
2063 prims.as_ptr().cast::<c_void>(),
2064 byte_len,
2065 0,
2066 );
2067 if !mtl_buf.is_null() {
2068 mtl_send_void0(mtl_buf, sel_rel);
2069 }
2070 } else {
2071 let instances: &[GpuQuadInstance] = batch.get_instances();
2072 if instances.is_empty() {
2073 continue;
2074 }
2075 let byte_len: usize = size_of_val(instances);
2076 let mtl_buf: *mut c_void = send_buf(
2077 device,
2078 sel_buf,
2079 instances.as_ptr().cast::<c_void>(),
2080 byte_len,
2081 0,
2082 );
2083 if !mtl_buf.is_null() {
2084 mtl_send_void0(mtl_buf, sel_rel);
2085 }
2086 }
2087 }
2088 let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
2089 if !cmd_buf.is_null() {
2090 mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
2091 }
2092 objc_autoreleasePoolPop(pool);
2093 }
2094 total_instances
2095}
2096
2097#[cfg(any(target_os = "macos", target_os = "ios"))]
2105fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
2106 let sel_rel: *mut c_void = cached_metal_selectors().release as *mut c_void;
2107 if library_handle != 0 {
2108 mtl_send_void0(library_handle as *mut c_void, sel_rel);
2109 }
2110 if queue_handle != 0 {
2111 mtl_send_void0(queue_handle as *mut c_void, sel_rel);
2112 }
2113 if device_handle != 0 {
2114 mtl_send_void0(device_handle as *mut c_void, sel_rel);
2115 }
2116}
2117
2118#[cfg(target_os = "windows")]
2119#[link(name = "kernel32")]
2120unsafe extern "system" {
2121 fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
2131 fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
2142}
2143
2144#[cfg(target_os = "windows")]
2154fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
2155 let cached: &WindowsD3d12ProbeCache = WINDOWS_D3D12_CACHE.get_or_init(|| unsafe {
2156 let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
2157 let has_d3d12: bool = if !d3d12_mod.is_null() {
2158 !GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr()).is_null()
2159 } else {
2160 false
2161 };
2162 let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
2163 let has_compiler: bool = if !compiler_mod.is_null() {
2164 !GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr()).is_null()
2165 } else {
2166 false
2167 };
2168 WindowsD3d12ProbeCache {
2169 has_d3d12,
2170 has_compiler,
2171 }
2172 });
2173 let label: &str = if cached.has_d3d12 {
2174 GPU_DEVICE_D3D12
2175 } else {
2176 GPU_DEVICE_FALLBACK
2177 };
2178 (
2179 GpuAdapterInfo::new(
2180 backend,
2181 label.to_string(),
2182 cached.has_d3d12,
2183 cached.has_compiler,
2184 ),
2185 0,
2186 0,
2187 0,
2188 )
2189}
2190
2191#[cfg(any(target_os = "linux", target_os = "android"))]
2192unsafe extern "C" {
2193 fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
2204 fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
2215}
2216
2217#[cfg(any(target_os = "linux", target_os = "android"))]
2227fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
2228 let cached: &VulkanProbeCache = VULKAN_PROBE_CACHE.get_or_init(|| {
2229 let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
2230 return VulkanProbeCache {
2231 available: false,
2232 lib_handle: 0,
2233 };
2234 };
2235 let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
2236 return VulkanProbeCache {
2237 available: false,
2238 lib_handle: 0,
2239 };
2240 };
2241 let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
2242 return VulkanProbeCache {
2243 available: false,
2244 lib_handle: 0,
2245 };
2246 };
2247 unsafe {
2248 let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
2249 if handle.is_null() {
2250 VulkanProbeCache {
2251 available: false,
2252 lib_handle: 0,
2253 }
2254 } else {
2255 let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
2256 let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
2257 VulkanProbeCache {
2258 available: !p1.is_null() && !p2.is_null(),
2259 lib_handle: handle as usize,
2260 }
2261 }
2262 }
2263 });
2264 let name: &str = if cached.available {
2265 GPU_DEVICE_VULKAN
2266 } else {
2267 GPU_DEVICE_FALLBACK
2268 };
2269 (
2270 GpuAdapterInfo::new(
2271 backend,
2272 name.to_string(),
2273 cached.available,
2274 cached.available,
2275 ),
2276 cached.lib_handle,
2277 0,
2278 0,
2279 )
2280}
2281
2282#[cfg(target_arch = "wasm32")]
2292pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
2293 let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
2294 gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
2295 gl.compile_shader(&vs);
2296 let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
2297 gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
2298 gl.compile_shader(&fs);
2299 let program: WebGlProgram = gl.create_program()?;
2300 gl.attach_shader(&program, &vs);
2301 gl.attach_shader(&program, &fs);
2302 gl.link_program(&program);
2303 Some(program)
2304}
2305
2306#[must_use]
2312pub const fn gles3_ui_instance_attribs() -> [Gles3InstanceAttribSpec; 5] {
2313 let stride: i32 = GPU_PRIMITIVE_INSTANCE_BYTES as i32;
2314 [
2315 Gles3InstanceAttribSpec {
2316 location: 1,
2317 components: 4,
2318 is_integer: false,
2319 byte_offset: 0,
2320 stride,
2321 },
2322 Gles3InstanceAttribSpec {
2323 location: 2,
2324 components: 4,
2325 is_integer: false,
2326 byte_offset: 16,
2327 stride,
2328 },
2329 Gles3InstanceAttribSpec {
2330 location: 3,
2331 components: 2,
2332 is_integer: true,
2333 byte_offset: 32,
2334 stride,
2335 },
2336 Gles3InstanceAttribSpec {
2337 location: 4,
2338 components: 4,
2339 is_integer: true,
2340 byte_offset: 40,
2341 stride,
2342 },
2343 Gles3InstanceAttribSpec {
2344 location: 5,
2345 components: 2,
2346 is_integer: true,
2347 byte_offset: 56,
2348 stride,
2349 },
2350 ]
2351}
2352
2353#[must_use]
2367pub fn gles3_scissor_from_top_down(
2368 surface_h: u32,
2369 sx: u32,
2370 sy: u32,
2371 stroke_width: u32,
2372 sh: u32,
2373) -> [i32; 4] {
2374 let y1: u32 = sy.saturating_add(sh).min(surface_h);
2375 let y_bottom: u32 = surface_h.saturating_sub(y1);
2376 [sx as i32, y_bottom as i32, stroke_width as i32, sh as i32]
2377}
2378
2379#[must_use]
2392pub fn select_adaptive_upload_plan(
2393 fb_w: u32,
2394 fb_h: u32,
2395 dirty_rects: &[PixelDirtyRect],
2396 force_full: bool,
2397) -> AdaptiveUploadPlan {
2398 if fb_w == 0 || fb_h == 0 {
2399 return AdaptiveUploadPlan {
2400 strategy: MobileUploadStrategy::None,
2401 rects: Vec::new(),
2402 total_upload_bytes: 0,
2403 merged_bbox_bytes: 0,
2404 full_frame_bytes: 0,
2405 estimated_cost_score: 0.0,
2406 };
2407 }
2408 let full_rect: PixelDirtyRect = PixelDirtyRect::new(0, 0, fb_w, fb_h);
2409 let full_bytes: usize = full_rect.byte_size_rgba8();
2410 if force_full {
2411 return AdaptiveUploadPlan {
2412 strategy: MobileUploadStrategy::FullFrame,
2413 rects: vec![full_rect],
2414 total_upload_bytes: full_bytes,
2415 merged_bbox_bytes: full_bytes,
2416 full_frame_bytes: full_bytes,
2417 estimated_cost_score: (full_bytes + MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES) as f32,
2418 };
2419 }
2420 let mut coalesced: Vec<PixelDirtyRect> = Vec::with_capacity(dirty_rects.len().min(16));
2421 for rect in dirty_rects.iter() {
2422 let Some(mut clamped) = rect.clamp_to(fb_w, fb_h) else {
2423 continue;
2424 };
2425 let mut merged_any: bool = true;
2426 while merged_any {
2427 merged_any = false;
2428 let mut idx: usize = 0;
2429 while idx < coalesced.len() {
2430 if coalesced[idx].intersects_or_adjacent(clamped, MOBILE_UPLOAD_COALESCE_PAD_PX) {
2431 let existing: PixelDirtyRect = coalesced.swap_remove(idx);
2432 clamped = clamped.union_with(existing);
2433 merged_any = true;
2434 } else {
2435 idx += 1;
2436 }
2437 }
2438 }
2439 coalesced.push(clamped);
2440 }
2441 if coalesced.is_empty() {
2442 return AdaptiveUploadPlan {
2443 strategy: MobileUploadStrategy::None,
2444 rects: Vec::new(),
2445 total_upload_bytes: 0,
2446 merged_bbox_bytes: 0,
2447 full_frame_bytes: full_bytes,
2448 estimated_cost_score: 0.0,
2449 };
2450 }
2451 let mut merged_bbox: PixelDirtyRect = coalesced[0];
2452 let mut multi_bytes: usize = 0;
2453 for red_val in coalesced.iter() {
2454 merged_bbox = merged_bbox.union_with(*red_val);
2455 multi_bytes = multi_bytes.saturating_add(red_val.byte_size_rgba8());
2456 }
2457 let merged_bytes: usize = merged_bbox.byte_size_rgba8();
2458 let multi_cost: usize = multi_bytes.saturating_add(
2459 coalesced
2460 .len()
2461 .saturating_mul(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES),
2462 );
2463 let merged_cost: usize = merged_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
2464 let full_threshold_bytes: usize =
2465 ((full_bytes as f32) * MOBILE_UPLOAD_FULL_FRAME_COVERAGE_THRESHOLD).round() as usize;
2466 let full_cost: usize = full_bytes.saturating_add(MOBILE_UPLOAD_PER_RECT_OVERHEAD_BYTES);
2467 let multi_eligible: bool = coalesced.len() >= 2
2468 && coalesced.len() <= MOBILE_MAX_MULTI_UPLOAD_RECTS
2469 && multi_bytes <= full_threshold_bytes
2470 && multi_cost < merged_cost
2471 && multi_cost < full_cost;
2472 if multi_eligible {
2473 return AdaptiveUploadPlan {
2474 strategy: MobileUploadStrategy::MultiRect,
2475 rects: coalesced,
2476 total_upload_bytes: multi_bytes,
2477 merged_bbox_bytes: merged_bytes,
2478 full_frame_bytes: full_bytes,
2479 estimated_cost_score: multi_cost as f32,
2480 };
2481 }
2482 if merged_bytes <= full_threshold_bytes && merged_cost < full_cost {
2483 return AdaptiveUploadPlan {
2484 strategy: MobileUploadStrategy::MergedBbox,
2485 rects: vec![merged_bbox],
2486 total_upload_bytes: merged_bytes,
2487 merged_bbox_bytes: merged_bytes,
2488 full_frame_bytes: full_bytes,
2489 estimated_cost_score: merged_cost as f32,
2490 };
2491 }
2492 AdaptiveUploadPlan {
2493 strategy: MobileUploadStrategy::FullFrame,
2494 rects: vec![full_rect],
2495 total_upload_bytes: full_bytes,
2496 merged_bbox_bytes: merged_bytes,
2497 full_frame_bytes: full_bytes,
2498 estimated_cost_score: full_cost as f32,
2499 }
2500}
2501
2502#[must_use]
2514pub fn damage_region_to_pixel_dirty_rects(
2515 damage: DamageRegion,
2516 fb_w: u32,
2517 fb_h: u32,
2518) -> Vec<PixelDirtyRect> {
2519 if fb_w == 0 || fb_h == 0 {
2520 return Vec::new();
2521 }
2522 if damage.get_full_damage() {
2523 return vec![PixelDirtyRect::new(0, 0, fb_w, fb_h)];
2524 }
2525 let Some(red_val) = damage.resolve(fb_w, fb_h) else {
2526 return Vec::new();
2527 };
2528 let rx0: u32 = (red_val.get_x().floor().max(0.0) as u32).min(fb_w);
2529 let ry0: u32 = (red_val.get_y().floor().max(0.0) as u32).min(fb_h);
2530 let rx1: u32 = (red_val.right().ceil().max(0.0) as u32).clamp(rx0, fb_w);
2531 let ry1: u32 = (red_val.bottom().ceil().max(0.0) as u32).clamp(ry0, fb_h);
2532 if rx1 > rx0 && ry1 > ry0 {
2533 vec![PixelDirtyRect::new(rx0, ry0, rx1 - rx0, ry1 - ry0)]
2534 } else {
2535 Vec::new()
2536 }
2537}
2538
2539#[must_use]
2553pub fn build_direct_gpu_frame_batch_from_batches(
2554 viewport_width: u32,
2555 viewport_height: u32,
2556 clear_color: Color,
2557 batches: &[GpuBatch],
2558 blur_passes: &[GpuBackdropBlurPass],
2559) -> DirectGpuFrameBatch {
2560 let total_prims: usize = batches
2561 .iter()
2562 .map(|blue_val: &GpuBatch| {
2563 blue_val
2564 .get_primitives()
2565 .len()
2566 .max(blue_val.get_instances().len())
2567 })
2568 .sum();
2569 let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(total_prims);
2570 let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(batches.len());
2571 let vw: u32 = viewport_width.max(1);
2572 let vh: u32 = viewport_height.max(1);
2573 for batch in batches.iter() {
2574 let base_instance: u32 = primitives.len() as u32;
2575 if !batch.get_primitives().is_empty() {
2576 primitives.extend_from_slice(batch.get_primitives());
2577 } else {
2578 for quad in batch.get_instances().iter() {
2579 primitives.push(GpuPrimitiveInstance::from_quad_instance(
2580 quad,
2581 batch.get_texture_slot(),
2582 batch.get_layer_id(),
2583 ));
2584 }
2585 }
2586 let instance_count: u32 = (primitives.len() as u32).saturating_sub(base_instance);
2587 if instance_count == 0 {
2588 continue;
2589 }
2590 let rect_bounds: Rect = batch.get_scissor();
2591 let sx: u32 = (rect_bounds.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
2592 let sy: u32 = (rect_bounds.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
2593 let stroke_width: u32 = (rect_bounds.get_width().max(1.0).ceil() as u32)
2594 .min(vw.saturating_sub(sx))
2595 .max(1);
2596 let sh: u32 = (rect_bounds.get_height().max(1.0).ceil() as u32)
2597 .min(vh.saturating_sub(sy))
2598 .max(1);
2599 let scroll: [f32; 2] = batch.get_scroll_offset();
2600 draw_ranges.push(DirectGpuBatchRange {
2601 base_instance,
2602 instance_count,
2603 scissor_x: sx,
2604 scissor_y: sy,
2605 scissor_w: stroke_width,
2606 scissor_h: sh,
2607 scroll_x: scroll[0],
2608 scroll_y: scroll[1],
2609 texture_slot: batch.get_texture_slot(),
2610 layer_id: batch.get_layer_id(),
2611 pad: [0, 0],
2612 });
2613 }
2614 let instance_upload_bytes: usize = primitives
2615 .len()
2616 .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
2617 DirectGpuFrameBatch {
2618 viewport_width: vw,
2619 viewport_height: vh,
2620 clear_rgba: clear_color.to_f32_array(),
2621 primitives,
2622 draw_ranges,
2623 backdrop_blurs: blur_passes.to_vec(),
2624 glyph_r8_atlas: None,
2625 image_rgba8_atlas: None,
2626 instance_upload_bytes,
2627 cpu_mirror_active: false,
2628 upload_strategy: MobileUploadStrategy::DirectGpu,
2629 }
2630}
2631
2632fn push_direct_gpu_primitive(
2643 primitives: &mut Vec<GpuPrimitiveInstance>,
2644 draw_ranges: &mut Vec<DirectGpuBatchRange>,
2645 prim: GpuPrimitiveInstance,
2646 clip: Rect,
2647 vw: u32,
2648 vh: u32,
2649) {
2650 if clip.get_width() <= 0.0 || clip.get_height() <= 0.0 {
2651 return;
2652 }
2653 let sx: u32 = (clip.get_x().max(0.0).floor() as u32).min(vw.saturating_sub(1));
2654 let sy: u32 = (clip.get_y().max(0.0).floor() as u32).min(vh.saturating_sub(1));
2655 let stroke_width: u32 = (clip.get_width().max(1.0).ceil() as u32)
2656 .min(vw.saturating_sub(sx))
2657 .max(1);
2658 let sh: u32 = (clip.get_height().max(1.0).ceil() as u32)
2659 .min(vh.saturating_sub(sy))
2660 .max(1);
2661 let layer_id: u8 = prim.layer_id();
2662 let base: u32 = primitives.len() as u32;
2663 primitives.push(prim);
2664 if let Some(last) = draw_ranges.last_mut()
2665 && last.get_scissor_x() == sx
2666 && last.get_scissor_y() == sy
2667 && last.get_scissor_w() == stroke_width
2668 && last.get_scissor_h() == sh
2669 && last.get_layer_id() == layer_id
2670 && last.get_instance_count() < MAX_QUADS_PER_BATCH as u32
2671 {
2672 last.set_instance_count(last.get_instance_count().saturating_add(1));
2673 return;
2674 }
2675 draw_ranges.push(DirectGpuBatchRange {
2676 base_instance: base,
2677 instance_count: 1,
2678 scissor_x: sx,
2679 scissor_y: sy,
2680 scissor_w: stroke_width,
2681 scissor_h: sh,
2682 scroll_x: 0.0,
2683 scroll_y: 0.0,
2684 texture_slot: 0,
2685 layer_id,
2686 pad: [0, 0],
2687 });
2688}
2689
2690fn encode_atlas_uv_rect(
2705 atlas_w: u32,
2706 atlas_h: u32,
2707 pos_x: u32,
2708 pos_y: u32,
2709 width_val: u32,
2710 height_val: u32,
2711) -> [u16; 4] {
2712 let inv_w: f32 = 1.0 / (atlas_w.max(1) as f32);
2713 let inv_h: f32 = 1.0 / (atlas_h.max(1) as f32);
2714 let u0: u16 = (((pos_x as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
2715 let v0: u16 = (((pos_y as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
2716 let u1: u16 = ((((pos_x + width_val) as f32) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16;
2717 let v1: u16 =
2718 ((((pos_y + height_val) as f32) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16;
2719 [u0, v0, u1, v1]
2720}
2721
2722fn pack_frame_image_atlas(
2733 images: &[DirectGpuImageSlice<'_>],
2734 revision: u64,
2735) -> (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) {
2736 if images.is_empty() {
2737 return (None, Vec::new());
2738 }
2739 let mut max_w: u32 = 1;
2740 let mut sum_w: u32 = 1;
2741 for entry in images.iter() {
2742 let cw: u32 = entry.crop.get_width();
2743 max_w = max_w.max(cw.saturating_add(2));
2744 sum_w = sum_w.saturating_add(cw.saturating_add(1));
2745 }
2746 let atlas_w: u32 = sum_w
2747 .clamp(64, 2048)
2748 .max(max_w)
2749 .next_power_of_two()
2750 .min(4096);
2751 let mut placements: Vec<(u32, u32, u32, u32)> = Vec::with_capacity(images.len());
2752 let mut cx: u32 = 1;
2753 let mut cy: u32 = 1;
2754 let mut shelf_h: u32 = 0;
2755 for entry in images.iter() {
2756 let clamped_w: u32 = entry.crop.get_width().min(atlas_w.saturating_sub(2)).max(1);
2757 let clamped_h: u32 = entry.crop.get_height().max(1);
2758 if cx + clamped_w + 1 > atlas_w {
2759 cx = 1;
2760 cy = cy.saturating_add(shelf_h).saturating_add(1);
2761 shelf_h = 0;
2762 }
2763 placements.push((cx, cy, clamped_w, clamped_h));
2764 cx = cx.saturating_add(clamped_w).saturating_add(1);
2765 shelf_h = shelf_h.max(clamped_h);
2766 }
2767 let atlas_h: u32 = cy.saturating_add(shelf_h).saturating_add(1).max(64);
2768 let mut pixels: Vec<u8> = vec![0; (atlas_w as usize) * (atlas_h as usize) * 4];
2769 let mut uvs: Vec<[u16; 4]> = Vec::with_capacity(images.len());
2770 for (idx, entry) in images.iter().enumerate() {
2771 let (dx, dy, copy_w, copy_h): (u32, u32, u32, u32) = placements[idx];
2772 let sx: u32 = entry.crop.get_x();
2773 let sy: u32 = entry.crop.get_y();
2774 let valid_w: u32 = copy_w.min(entry.src_w.saturating_sub(sx));
2775 let valid_h: u32 = copy_h.min(entry.src_h.saturating_sub(sy));
2776 for row in 0..valid_h {
2777 let src_off: usize =
2778 (((sy + row) as usize) * (entry.src_w as usize) + (sx as usize)) * 4;
2779 let dst_off: usize = (((dy + row) as usize) * (atlas_w as usize) + (dx as usize)) * 4;
2780 let row_bytes: usize = (valid_w as usize) * 4;
2781 if src_off + row_bytes <= entry.pixels.len() && dst_off + row_bytes <= pixels.len() {
2782 pixels[dst_off..dst_off + row_bytes]
2783 .copy_from_slice(&entry.pixels[src_off..src_off + row_bytes]);
2784 }
2785 }
2786 uvs.push(encode_atlas_uv_rect(
2787 atlas_w, atlas_h, dx, dy, valid_w, valid_h,
2788 ));
2789 }
2790 (
2791 Some(DirectGpuAtlasUpload {
2792 width: atlas_w,
2793 height: atlas_h,
2794 revision,
2795 pixels,
2796 }),
2797 uvs,
2798 )
2799}
2800
2801#[must_use]
2814pub fn compile_display_list_direct_gpu_batch(
2815 display_list: &DisplayList,
2816 mut glyph_atlas: Option<&mut GlyphAtlas>,
2817 font_provider: Option<&NativeSystemFont>,
2818 last_glyph_revision: u64,
2819) -> DirectGpuFrameBatch {
2820 let scale: f32 = display_list.get_scale_factor().max(0.5);
2821 let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
2822 let phys_h: u32 = ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
2823 let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
2824 let mut clip_stack: Vec<(Rect, Rect, u16)> = Vec::with_capacity(16);
2825 clip_stack.push((full_clip, full_clip, 0));
2826 let mut primitives: Vec<GpuPrimitiveInstance> =
2827 Vec::with_capacity(display_list.get_commands().len().saturating_mul(2));
2828 let mut draw_ranges: Vec<DirectGpuBatchRange> = Vec::with_capacity(16);
2829 let mut backdrop_blurs: Vec<GpuBackdropBlurPass> = Vec::new();
2830 let mut glyph_fixups: Vec<(usize, GlyphKey)> = Vec::new();
2831 let mut image_entries: Vec<DirectGpuImageSlice<'_>> = Vec::new();
2832 let mut image_fixups: Vec<(usize, usize)> = Vec::new();
2833 let mut clear_rgba: [f32; 4] = COLOR_WHITE.to_f32_array();
2834 let mut active_layer_id: u8 = 0;
2835 for cmd in display_list.get_commands().iter() {
2836 let (active_clip, safe_inner_clip, active_rounded_bits): (Rect, Rect, u16) = clip_stack
2837 .last()
2838 .copied()
2839 .unwrap_or((full_clip, full_clip, 0));
2840 let clip_arr: [f32; 4] = [
2841 active_clip.get_x(),
2842 active_clip.get_y(),
2843 active_clip.right(),
2844 active_clip.bottom(),
2845 ];
2846 let cmd_prim_start: usize = primitives.len();
2847 match cmd {
2848 DrawCommand::Clear(char_item) => {
2849 clear_rgba = char_item.to_f32_array();
2850 }
2851 DrawCommand::PushClip(rect) => {
2852 let phys: Rect = snap_physical_rect(*rect, scale);
2853 let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
2854 let next_safe: Rect = safe_inner_clip.intersect(phys).unwrap_or_default();
2855 let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
2856 active_clip,
2857 active_rounded_bits,
2858 next_scissor,
2859 phys,
2860 None,
2861 );
2862 clip_stack.push((next_scissor, next_safe, next_bits));
2863 }
2864 DrawCommand::PushRoundedClip { rect, radius } => {
2865 let phys: Rect = snap_physical_rect(*rect, scale);
2866 let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
2867 let phys_radius: CornerRadius = CornerRadius::new(
2868 radius.get_top_left() * scale,
2869 radius.get_top_right() * scale,
2870 radius.get_bottom_right() * scale,
2871 radius.get_bottom_left() * scale,
2872 );
2873 let max_r: f32 = phys_radius.max_radius().ceil();
2874 let inset_w: f32 = (phys.get_width() - max_r * 2.0).max(0.0);
2875 let inset_h: f32 = (phys.get_height() - max_r * 2.0).max(0.0);
2876 let rounded_safe: Rect =
2877 Rect::new(phys.get_x() + max_r, phys.get_y() + max_r, inset_w, inset_h);
2878 let next_safe: Rect = safe_inner_clip.intersect(rounded_safe).unwrap_or_default();
2879 let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
2880 active_clip,
2881 active_rounded_bits,
2882 next_scissor,
2883 phys,
2884 Some(phys_radius),
2885 );
2886 clip_stack.push((next_scissor, next_safe, next_bits));
2887 }
2888 DrawCommand::PopClip => {
2889 if clip_stack.len() > 1 {
2890 let _: Option<(Rect, Rect, u16)> = clip_stack.pop();
2891 }
2892 }
2893 DrawCommand::FillRoundedRect {
2894 rect,
2895 color,
2896 radius,
2897 border,
2898 } => {
2899 let snapped: Rect = snap_physical_rect(*rect, scale);
2900 let quad: [f32; 4] = [
2901 snapped.get_x(),
2902 snapped.get_y(),
2903 snapped.get_width(),
2904 snapped.get_height(),
2905 ];
2906 if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
2907 continue;
2908 }
2909 let border_width: f32 = if border.get_width() > 0.0 {
2910 (border.get_width() * scale).max(1.0)
2911 } else {
2912 0.0
2913 };
2914 let query_val: GpuQuadInstance = GpuQuadInstance {
2915 rect: quad,
2916 clip: clip_arr,
2917 color: color.to_f32_array(),
2918 secondary_color: border.get_color().to_f32_array(),
2919 radii: [
2920 radius.get_top_left() * scale,
2921 radius.get_top_right() * scale,
2922 radius.get_bottom_right() * scale,
2923 radius.get_bottom_left() * scale,
2924 ],
2925 stroke_or_blur: border_width,
2926 angle_rad: 0.0,
2927 kind: GpuPrimitiveKind::RoundedRect as u32,
2928 reserved: 0,
2929 };
2930 push_direct_gpu_primitive(
2931 &mut primitives,
2932 &mut draw_ranges,
2933 GpuPrimitiveInstance::from_quad_instance(&query_val, 0, active_layer_id),
2934 active_clip,
2935 phys_w,
2936 phys_h,
2937 );
2938 }
2939 DrawCommand::LinearGradientRect {
2940 rect,
2941 gradient,
2942 radius,
2943 } => {
2944 let snapped: Rect = snap_physical_rect(*rect, scale);
2945 let quad: [f32; 4] = [
2946 snapped.get_x(),
2947 snapped.get_y(),
2948 snapped.get_width(),
2949 snapped.get_height(),
2950 ];
2951 if quad[2] <= 0.0 || quad[3] <= 0.0 || active_clip.get_width() <= 0.0 {
2952 continue;
2953 }
2954 let quat_val: GpuQuadInstance = GpuQuadInstance {
2955 rect: quad,
2956 clip: clip_arr,
2957 color: gradient.get_start_color().to_f32_array(),
2958 secondary_color: gradient.get_end_color().to_f32_array(),
2959 radii: [
2960 radius.get_top_left() * scale,
2961 radius.get_top_right() * scale,
2962 radius.get_bottom_right() * scale,
2963 radius.get_bottom_left() * scale,
2964 ],
2965 stroke_or_blur: 0.0,
2966 angle_rad: gradient.get_angle_deg().to_radians(),
2967 kind: GpuPrimitiveKind::Gradient as u32,
2968 reserved: 0,
2969 };
2970 push_direct_gpu_primitive(
2971 &mut primitives,
2972 &mut draw_ranges,
2973 GpuPrimitiveInstance::from_quad_instance(&quat_val, 0, active_layer_id),
2974 active_clip,
2975 phys_w,
2976 phys_h,
2977 );
2978 }
2979 DrawCommand::BoxShadow {
2980 rect,
2981 radius,
2982 shadow,
2983 } => {
2984 let spread: f32 = shadow.get_spread_radius() * scale;
2985 let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
2986 let sigma: f32 = (blur * 0.5).max(0.75);
2987 let pad: f32 = (sigma * 3.0).ceil();
2988 let base_rect: Rect = snap_physical_rect(*rect, scale);
2989 let cx: f32 = base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
2990 let cy: f32 = base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
2991 let cw: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
2992 let ch: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
2993 let corner_vec: GpuQuadInstance = GpuQuadInstance {
2994 rect: [cx - pad, cy - pad, cw + pad * 2.0, ch + pad * 2.0],
2995 clip: clip_arr,
2996 color: shadow.get_color().to_f32_array(),
2997 secondary_color: [0.0; 4],
2998 radii: [
2999 (radius.get_top_left() * scale + spread).max(0.0),
3000 (radius.get_top_right() * scale + spread).max(0.0),
3001 (radius.get_bottom_right() * scale + spread).max(0.0),
3002 (radius.get_bottom_left() * scale + spread).max(0.0),
3003 ],
3004 stroke_or_blur: sigma,
3005 angle_rad: pad,
3006 kind: GpuPrimitiveKind::Shadow as u32,
3007 reserved: 0,
3008 };
3009 push_direct_gpu_primitive(
3010 &mut primitives,
3011 &mut draw_ranges,
3012 GpuPrimitiveInstance::from_quad_instance(&corner_vec, 0, active_layer_id),
3013 active_clip,
3014 phys_w,
3015 phys_h,
3016 );
3017 }
3018 DrawCommand::BackdropBlur {
3019 rect,
3020 radius,
3021 blur_radius,
3022 } => {
3023 let snapped: Rect = snap_physical_rect(*rect, scale);
3024 let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, 96.0);
3025 let radii_px: [f32; 4] = [
3026 radius.get_top_left() * scale,
3027 radius.get_top_right() * scale,
3028 radius.get_bottom_right() * scale,
3029 radius.get_bottom_left() * scale,
3030 ];
3031 let halo: Rect = Rect::new(
3032 (snapped.get_x() - phys_blur).max(0.0),
3033 (snapped.get_y() - phys_blur).max(0.0),
3034 (snapped.get_width() + phys_blur * 2.0).min(phys_w as f32),
3035 (snapped.get_height() + phys_blur * 2.0).min(phys_h as f32),
3036 );
3037 backdrop_blurs.push(GpuBackdropBlurPass {
3038 bounds: snapped,
3039 input_bounds: halo,
3040 clip_rect: active_clip,
3041 radii: radii_px,
3042 blur_radius: phys_blur,
3043 layer_id: active_layer_id,
3044 });
3045 active_layer_id = active_layer_id.saturating_add(1);
3046 }
3047 DrawCommand::TextRun { rect, text, style } => {
3048 if text.is_empty()
3049 || active_clip.get_width() <= 0.0
3050 || active_clip.get_height() <= 0.0
3051 {
3052 continue;
3053 }
3054 if let Some(atlas) = glyph_atlas.as_deref_mut() {
3055 let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
3056 let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
3057 text,
3058 *style,
3059 Some(rect.get_width().max(1.0)),
3060 );
3061 let line_h: f32 = meas.get_line_height_px() * scale;
3062 let letter_sp: f32 = style.get_letter_spacing() * scale;
3063 let rect_w_px: f32 = rect.get_width() * scale;
3064 let color_rgba: u32 = GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
3065 let kind_flags: u32 = GpuPrimitiveInstance::pack_kind_flags(
3066 PrimKind::GlyphAlpha8,
3067 0,
3068 0,
3069 active_layer_id,
3070 );
3071 let mut line_glyphs: Vec<(Option<GlyphKey>, u32, u32, f32)> = Vec::new();
3072 for (line_idx, line) in meas.get_lines().iter().enumerate() {
3073 line_glyphs.clear();
3074 let mut line_w_px: f32 = 0.0;
3075 for ch in line.get_text().chars() {
3076 if ch == ' ' || ch == '\t' {
3077 let sp_adv: f32 = measure_char_advance(ch, *style) * scale;
3078 line_glyphs.push((None, 0, 0, sp_adv));
3079 line_w_px += sp_adv;
3080 continue;
3081 }
3082 let key: GlyphKey = GlyphKey::from_text_style(ch, phys_font_px, *style);
3083 let (gw, gh, adv): (u32, u32, f32) = {
3084 let green_val: &RasterizedGlyph = match font_provider {
3085 Some(fp) => atlas.get_or_rasterize_with(key, fp),
3086 None => atlas.get_or_rasterize(key),
3087 };
3088 (
3089 green_val.get_width(),
3090 green_val.get_height(),
3091 (green_val.get_advance() as f32).max(1.0) + letter_sp,
3092 )
3093 };
3094 line_glyphs.push((Some(key), gw, gh, adv));
3095 line_w_px += adv;
3096 }
3097 let fit_scale: f32 = if rect_w_px > 1.0 && line_w_px > rect_w_px + 1.0 {
3098 (rect_w_px / line_w_px).clamp(0.72, 1.0)
3099 } else {
3100 1.0
3101 };
3102 let fitted_line_w: f32 = line_w_px * fit_scale;
3103 let align_offset: f32 = match style.get_align() {
3104 TextAlign::Center => ((rect_w_px - fitted_line_w) * 0.5).max(0.0),
3105 TextAlign::Right => (rect_w_px - fitted_line_w).max(0.0),
3106 TextAlign::Left => 0.0,
3107 };
3108 let base_y: f32 = rect.get_y() * scale + (line_idx as f32) * line_h;
3109 let mut pen_x: f32 = rect.get_x() * scale + align_offset;
3110 for &(key_opt, gw, gh, adv) in line_glyphs.iter() {
3111 if let Some(key) = key_opt
3112 && gw > 0
3113 && gh > 0
3114 {
3115 let y_off: f32 = ((line_h - (gh as f32)) * 0.5).round();
3116 let prim_idx: usize = primitives.len();
3117 let prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
3118 rect: [
3119 pen_x.round(),
3120 (base_y + y_off).round(),
3121 gw as f32,
3122 gh as f32,
3123 ],
3124 clip_rect: clip_arr,
3125 color_rgba,
3126 aux_color_rgba: 0,
3127 uv_rect: [0, 0, 0, 0],
3128 radii_border: [0; 4],
3129 kind_flags,
3130 extra_param: 0,
3131 };
3132 push_direct_gpu_primitive(
3133 &mut primitives,
3134 &mut draw_ranges,
3135 prim,
3136 active_clip,
3137 phys_w,
3138 phys_h,
3139 );
3140 glyph_fixups.push((prim_idx, key));
3141 }
3142 pen_x += adv * fit_scale;
3143 }
3144 }
3145 } else {
3146 let queue_entry: GpuQuadInstance = GpuQuadInstance {
3147 rect: [
3148 rect.get_x() * scale,
3149 rect.get_y() * scale,
3150 rect.get_width() * scale,
3151 rect.get_height() * scale,
3152 ],
3153 clip: clip_arr,
3154 color: style.get_color().to_f32_array(),
3155 secondary_color: [0.0; 4],
3156 radii: [0.0; 4],
3157 stroke_or_blur: style.get_font_size() * scale,
3158 angle_rad: 0.0,
3159 kind: GpuPrimitiveKind::Glyph as u32,
3160 reserved: text.chars().count() as u32,
3161 };
3162 push_direct_gpu_primitive(
3163 &mut primitives,
3164 &mut draw_ranges,
3165 GpuPrimitiveInstance::from_quad_instance(&queue_entry, 0, active_layer_id),
3166 active_clip,
3167 phys_w,
3168 phys_h,
3169 );
3170 }
3171 }
3172 DrawCommand::TextCaret {
3173 text_rect,
3174 content_rect,
3175 text,
3176 style,
3177 caret_height,
3178 color,
3179 multiline,
3180 } => {
3181 if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
3182 continue;
3183 }
3184 let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
3185 text,
3186 *style,
3187 if *multiline {
3188 Some(content_rect.get_width().max(1.0))
3189 } else {
3190 None
3191 },
3192 );
3193 let last_w_phys: f32 = if let Some(atlas) = glyph_atlas.as_deref_mut() {
3194 let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
3195 let letter_sp: f32 = style.get_letter_spacing() * scale;
3196 if let Some(line) = meas.get_lines().last() {
3197 let mut acc: f32 = 0.0;
3198 for ch in line.get_text().chars() {
3199 if ch == ' ' || ch == '\t' {
3200 acc += measure_char_advance(ch, *style) * scale + letter_sp;
3201 } else {
3202 let key: GlyphKey =
3203 GlyphKey::from_text_style(ch, phys_font_px, *style);
3204 let geometry_val: &RasterizedGlyph = match font_provider {
3205 Some(fp) => atlas.get_or_rasterize_with(key, fp),
3206 None => atlas.get_or_rasterize(key),
3207 };
3208 acc += (geometry_val.get_advance() as f32).max(1.0) + letter_sp;
3209 }
3210 }
3211 acc
3212 } else {
3213 0.0
3214 }
3215 } else {
3216 meas.get_lines()
3217 .last()
3218 .map(TextLine::get_width)
3219 .unwrap_or(0.0)
3220 * scale
3221 };
3222 let line_idx: usize = meas.get_lines().len().saturating_sub(1);
3223 let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
3224 let caret_x_phys: f32 =
3225 (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys).clamp(
3226 content_rect.get_x() * scale,
3227 ((content_rect.right() - 2.0) * scale).max(content_rect.get_x() * scale),
3228 );
3229 let caret_y: f32 = if *multiline {
3230 (content_rect.get_y()
3231 + (line_idx as f32) * meas.get_line_height_px()
3232 + ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
3233 .clamp(
3234 content_rect.get_y(),
3235 (content_rect.bottom() - caret_height).max(content_rect.get_y()),
3236 )
3237 } else {
3238 content_rect.get_y()
3239 + ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
3240 };
3241 let query_val_primary: GpuQuadInstance = GpuQuadInstance {
3242 rect: [
3243 caret_x_phys.round(),
3244 (caret_y * scale).round(),
3245 (1.5 * scale).max(1.0),
3246 (caret_height * scale).max(2.0),
3247 ],
3248 clip: clip_arr,
3249 color: color.to_f32_array(),
3250 secondary_color: [0.0; 4],
3251 radii: [0.5 * scale; 4],
3252 stroke_or_blur: 0.0,
3253 angle_rad: 0.0,
3254 kind: GpuPrimitiveKind::RoundedRect as u32,
3255 reserved: 0,
3256 };
3257 push_direct_gpu_primitive(
3258 &mut primitives,
3259 &mut draw_ranges,
3260 GpuPrimitiveInstance::from_quad_instance(
3261 &query_val_primary,
3262 0,
3263 active_layer_id,
3264 ),
3265 active_clip,
3266 phys_w,
3267 phys_h,
3268 );
3269 }
3270 DrawCommand::Image {
3271 rect,
3272 buffer,
3273 radius,
3274 } => {
3275 let snapped: Rect = snap_physical_rect(*rect, scale);
3276 let img_w: u32 = buffer.get_width();
3277 let img_h: u32 = buffer.get_height();
3278 if img_w == 0
3279 || img_h == 0
3280 || snapped.get_width() <= 0.0
3281 || snapped.get_height() <= 0.0
3282 {
3283 continue;
3284 }
3285 let img_idx: usize = image_entries.len();
3286 image_entries.push(DirectGpuImageSlice {
3287 src_w: img_w,
3288 src_h: img_h,
3289 pixels: buffer.get_pixels(),
3290 crop: PixelDirtyRect::new(0, 0, img_w, img_h),
3291 });
3292 let query_val_secondary: GpuQuadInstance = GpuQuadInstance {
3293 rect: [
3294 snapped.get_x(),
3295 snapped.get_y(),
3296 snapped.get_width(),
3297 snapped.get_height(),
3298 ],
3299 clip: clip_arr,
3300 color: [1.0, 1.0, 1.0, 1.0],
3301 secondary_color: [0.0; 4],
3302 radii: [
3303 radius.get_top_left() * scale,
3304 radius.get_top_right() * scale,
3305 radius.get_bottom_right() * scale,
3306 radius.get_bottom_left() * scale,
3307 ],
3308 stroke_or_blur: 0.0,
3309 angle_rad: 0.0,
3310 kind: GpuPrimitiveKind::TexturedQuad as u32,
3311 reserved: 0,
3312 };
3313 let prim_idx: usize = primitives.len();
3314 push_direct_gpu_primitive(
3315 &mut primitives,
3316 &mut draw_ranges,
3317 GpuPrimitiveInstance::from_quad_instance(
3318 &query_val_secondary,
3319 0,
3320 active_layer_id,
3321 ),
3322 active_clip,
3323 phys_w,
3324 phys_h,
3325 );
3326 image_fixups.push((prim_idx, img_idx));
3327 }
3328 DrawCommand::SharedImage {
3329 rect,
3330 width,
3331 height,
3332 pixels,
3333 radius,
3334 } => {
3335 let snapped: Rect = snap_physical_rect(*rect, scale);
3336 if *width == 0
3337 || *height == 0
3338 || snapped.get_width() <= 0.0
3339 || snapped.get_height() <= 0.0
3340 {
3341 continue;
3342 }
3343 let img_idx: usize = image_entries.len();
3344 image_entries.push(DirectGpuImageSlice {
3345 src_w: *width,
3346 src_h: *height,
3347 pixels: pixels.as_slice(),
3348 crop: PixelDirtyRect::new(0, 0, *width, *height),
3349 });
3350 let query_val_next: GpuQuadInstance = GpuQuadInstance {
3351 rect: [
3352 snapped.get_x(),
3353 snapped.get_y(),
3354 snapped.get_width(),
3355 snapped.get_height(),
3356 ],
3357 clip: clip_arr,
3358 color: [1.0, 1.0, 1.0, 1.0],
3359 secondary_color: [0.0; 4],
3360 radii: [
3361 radius.get_top_left() * scale,
3362 radius.get_top_right() * scale,
3363 radius.get_bottom_right() * scale,
3364 radius.get_bottom_left() * scale,
3365 ],
3366 stroke_or_blur: 0.0,
3367 angle_rad: 0.0,
3368 kind: GpuPrimitiveKind::TexturedQuad as u32,
3369 reserved: 0,
3370 };
3371 let prim_idx: usize = primitives.len();
3372 push_direct_gpu_primitive(
3373 &mut primitives,
3374 &mut draw_ranges,
3375 GpuPrimitiveInstance::from_quad_instance(&query_val_next, 0, active_layer_id),
3376 active_clip,
3377 phys_w,
3378 phys_h,
3379 );
3380 image_fixups.push((prim_idx, img_idx));
3381 }
3382 DrawCommand::SpriteRegion {
3383 rect,
3384 buffer,
3385 src_rect,
3386 tint,
3387 } => {
3388 let snapped: Rect = snap_physical_rect(*rect, scale);
3389 let img_w: u32 = buffer.get_width();
3390 let img_h: u32 = buffer.get_height();
3391 let sx: u32 = (src_rect.get_x().max(0.0).floor() as u32).min(img_w);
3392 let sy: u32 = (src_rect.get_y().max(0.0).floor() as u32).min(img_h);
3393 let stroke_width: u32 =
3394 (src_rect.get_width().max(1.0).ceil() as u32).min(img_w.saturating_sub(sx));
3395 let sh: u32 =
3396 (src_rect.get_height().max(1.0).ceil() as u32).min(img_h.saturating_sub(sy));
3397 if stroke_width == 0
3398 || sh == 0
3399 || snapped.get_width() <= 0.0
3400 || snapped.get_height() <= 0.0
3401 {
3402 continue;
3403 }
3404 let img_idx: usize = image_entries.len();
3405 image_entries.push(DirectGpuImageSlice {
3406 src_w: img_w,
3407 src_h: img_h,
3408 pixels: buffer.get_pixels(),
3409 crop: PixelDirtyRect::new(sx, sy, stroke_width, sh),
3410 });
3411 let query_val_alt: GpuQuadInstance = GpuQuadInstance {
3412 rect: [
3413 snapped.get_x(),
3414 snapped.get_y(),
3415 snapped.get_width(),
3416 snapped.get_height(),
3417 ],
3418 clip: clip_arr,
3419 color: tint.to_f32_array(),
3420 secondary_color: [0.0; 4],
3421 radii: [0.0; 4],
3422 stroke_or_blur: 0.0,
3423 angle_rad: 0.0,
3424 kind: GpuPrimitiveKind::TexturedQuad as u32,
3425 reserved: 1,
3426 };
3427 let prim_idx: usize = primitives.len();
3428 push_direct_gpu_primitive(
3429 &mut primitives,
3430 &mut draw_ranges,
3431 GpuPrimitiveInstance::from_quad_instance(&query_val_alt, 0, active_layer_id),
3432 active_clip,
3433 phys_w,
3434 phys_h,
3435 );
3436 image_fixups.push((prim_idx, img_idx));
3437 }
3438 DrawCommand::Circle {
3439 center,
3440 radius,
3441 color,
3442 } => {
3443 let red_val: f32 = radius * scale;
3444 let pad: f32 = 1.5;
3445 let extent: f32 = red_val + pad;
3446 let query_val_inner: GpuQuadInstance = GpuQuadInstance {
3447 rect: [
3448 center.get_x() * scale - extent,
3449 center.get_y() * scale - extent,
3450 extent * 2.0,
3451 extent * 2.0,
3452 ],
3453 clip: clip_arr,
3454 color: color.to_f32_array(),
3455 secondary_color: [0.0; 4],
3456 radii: [red_val; 4],
3457 stroke_or_blur: red_val,
3458 angle_rad: 0.0,
3459 kind: GpuPrimitiveKind::Circle as u32,
3460 reserved: 0,
3461 };
3462 push_direct_gpu_primitive(
3463 &mut primitives,
3464 &mut draw_ranges,
3465 GpuPrimitiveInstance::from_quad_instance(&query_val_inner, 0, active_layer_id),
3466 active_clip,
3467 phys_w,
3468 phys_h,
3469 );
3470 }
3471 DrawCommand::Line {
3472 from,
3473 to,
3474 color,
3475 width,
3476 } => {
3477 let fx0: f32 = from.get_x() * scale;
3478 let fy0: f32 = from.get_y() * scale;
3479 let fx1: f32 = to.get_x() * scale;
3480 let fy1: f32 = to.get_y() * scale;
3481 let dx: f32 = fx1 - fx0;
3482 let dy: f32 = fy1 - fy0;
3483 let stroke_px: f32 = (width * scale).max(1.0);
3484 let pad: f32 = stroke_px * 0.5 + 1.5;
3485 let min_x: f32 = fx0.min(fx1) - pad;
3486 let min_y: f32 = fy0.min(fy1) - pad;
3487 let max_x: f32 = fx0.max(fx1) + pad;
3488 let max_y: f32 = fy0.max(fy1) + pad;
3489 let query_val_local: GpuQuadInstance = GpuQuadInstance {
3490 rect: [
3491 min_x,
3492 min_y,
3493 (max_x - min_x).max(2.0),
3494 (max_y - min_y).max(2.0),
3495 ],
3496 clip: clip_arr,
3497 color: color.to_f32_array(),
3498 secondary_color: [0.0; 4],
3499 radii: [fx0, fy0, fx1, fy1],
3500 stroke_or_blur: stroke_px,
3501 angle_rad: dy.atan2(dx),
3502 kind: GpuPrimitiveKind::Line as u32,
3503 reserved: 0,
3504 };
3505 push_direct_gpu_primitive(
3506 &mut primitives,
3507 &mut draw_ranges,
3508 GpuPrimitiveInstance::from_quad_instance(&query_val_local, 0, active_layer_id),
3509 active_clip,
3510 phys_w,
3511 phys_h,
3512 );
3513 }
3514 DrawCommand::Triangle { p0, p1, p2, color } => {
3515 let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.5;
3516 let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.5;
3517 let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.5;
3518 let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.5;
3519 let query_val_cur: GpuQuadInstance = GpuQuadInstance {
3520 rect: [
3521 min_x,
3522 min_y,
3523 (max_x - min_x).max(2.0),
3524 (max_y - min_y).max(2.0),
3525 ],
3526 clip: clip_arr,
3527 color: color.to_f32_array(),
3528 secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
3529 radii: [
3530 p1.get_x() * scale,
3531 p1.get_y() * scale,
3532 p2.get_x() * scale,
3533 p2.get_y() * scale,
3534 ],
3535 stroke_or_blur: 0.0,
3536 angle_rad: 0.0,
3537 kind: GpuPrimitiveKind::Triangle as u32,
3538 reserved: 3,
3539 };
3540 push_direct_gpu_primitive(
3541 &mut primitives,
3542 &mut draw_ranges,
3543 GpuPrimitiveInstance::from_quad_instance(&query_val_cur, 0, active_layer_id),
3544 active_clip,
3545 phys_w,
3546 phys_h,
3547 );
3548 }
3549 }
3550 if active_rounded_bits != 0 && primitives.len() > cmd_prim_start {
3551 for prim_item in primitives[cmd_prim_start..].iter_mut() {
3552 let quad_rect: [f32; 4] = prim_item.get_rect();
3553 let safe_non_empty: bool =
3554 safe_inner_clip.get_width() > 0.0 && safe_inner_clip.get_height() > 0.0;
3555 let inside_safe: bool = safe_non_empty
3556 && quad_rect[0] >= safe_inner_clip.get_x()
3557 && quad_rect[1] >= safe_inner_clip.get_y()
3558 && (quad_rect[0] + quad_rect[2]) <= safe_inner_clip.right()
3559 && (quad_rect[1] + quad_rect[3]) <= safe_inner_clip.bottom();
3560 if !inside_safe {
3561 *prim_item = prim_item.with_rounded_clip_bits(active_rounded_bits);
3562 }
3563 }
3564 }
3565 }
3566 let mut glyph_r8_atlas: Option<DirectGpuAtlasUpload> = None;
3567 if let Some(atlas) = glyph_atlas.as_deref()
3568 && (!glyph_fixups.is_empty() || atlas.get_revision() != last_glyph_revision)
3569 && !atlas.is_empty()
3570 {
3571 let packed: PackedGlyphAtlas = atlas.pack_rgba_atlas();
3572 let aw: u32 = packed.get_width();
3573 let ah: u32 = packed.get_height();
3574 for &(prim_idx, key) in glyph_fixups.iter() {
3575 if let Some(&(gx, gy, gw, gh)) = packed.get_regions().get(&key) {
3576 primitives[prim_idx].set_uv_rect(encode_atlas_uv_rect(aw, ah, gx, gy, gw, gh));
3577 }
3578 }
3579 if packed.get_revision() != last_glyph_revision {
3580 let rgba: &[u8] = packed.get_pixels().as_slice();
3581 let mut r8: Vec<u8> = Vec::with_capacity((aw as usize).saturating_mul(ah as usize));
3582 for px in rgba.as_chunks::<4>().0 {
3583 r8.push(px[3]);
3584 }
3585 glyph_r8_atlas = Some(DirectGpuAtlasUpload {
3586 width: aw,
3587 height: ah,
3588 revision: packed.get_revision(),
3589 pixels: r8,
3590 });
3591 }
3592 }
3593 let (image_rgba8_atlas, img_uvs): (Option<DirectGpuAtlasUpload>, Vec<[u16; 4]>) =
3594 pack_frame_image_atlas(&image_entries, display_list.fast_hash());
3595 for &(prim_idx, img_idx) in image_fixups.iter() {
3596 if let Some(&uv) = img_uvs.get(img_idx) {
3597 primitives[prim_idx].set_uv_rect(uv);
3598 }
3599 }
3600 let glyph_bytes: usize = glyph_r8_atlas
3601 .as_ref()
3602 .map(|alpha_val: &DirectGpuAtlasUpload| alpha_val.get_pixels().len())
3603 .unwrap_or(0);
3604 let image_bytes: usize = image_rgba8_atlas
3605 .as_ref()
3606 .map(|first_val: &DirectGpuAtlasUpload| first_val.get_pixels().len())
3607 .unwrap_or(0);
3608 let instance_upload_bytes: usize = primitives
3609 .len()
3610 .saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES)
3611 .saturating_add(glyph_bytes)
3612 .saturating_add(image_bytes);
3613 DirectGpuFrameBatch {
3614 viewport_width: phys_w,
3615 viewport_height: phys_h,
3616 clear_rgba,
3617 primitives,
3618 draw_ranges,
3619 backdrop_blurs,
3620 glyph_r8_atlas,
3621 image_rgba8_atlas,
3622 instance_upload_bytes,
3623 cpu_mirror_active: false,
3624 upload_strategy: MobileUploadStrategy::DirectGpu,
3625 }
3626}
3627
3628#[must_use]
3634pub const fn default_native_gpu_backend() -> GraphicsBackend {
3635 #[cfg(any(target_os = "macos", target_os = "ios"))]
3636 {
3637 GraphicsBackend::Metal
3638 }
3639 #[cfg(target_os = "windows")]
3640 {
3641 GraphicsBackend::Direct3D12
3642 }
3643 #[cfg(any(target_os = "linux", target_os = "android"))]
3644 {
3645 GraphicsBackend::Vulkan
3646 }
3647 #[cfg(target_arch = "wasm32")]
3648 {
3649 GraphicsBackend::WebGl2
3650 }
3651 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
3652 #[cfg(not(any(target_os = "linux", target_os = "android", target_arch = "wasm32")))]
3653 {
3654 GraphicsBackend::Headless
3655 }
3656}
3657
3658#[must_use]
3670pub fn shader_program_cache_hash(device_name: &str, primary_src: &str, secondary_src: &str) -> u64 {
3671 let mut hash: u64 = FNV1A_OFFSET_BASIS;
3672 for chunk in [
3673 device_name.as_bytes(),
3674 primary_src.as_bytes(),
3675 secondary_src.as_bytes(),
3676 ]
3677 .iter()
3678 {
3679 for &byte in chunk.iter() {
3680 hash ^= byte as u64;
3681 hash = hash.wrapping_mul(FNV1A_PRIME);
3682 }
3683 }
3684 hash
3685}
3686
3687fn run_shader_precompile_uncached(backend: GraphicsBackend) -> ShaderPrecompileReport {
3697 #[cfg(not(target_arch = "wasm32"))]
3698 let total_start: Instant = Instant::now();
3699 let _: Vec<u8> = build_aces_srgb_lut();
3700 let lang_label: &str = ShaderProgramId::language_for_backend(backend);
3701 #[cfg(any(target_os = "macos", target_os = "ios"))]
3702 if backend == GraphicsBackend::Metal {
3703 let cached: &MetalSharedPipelineCache = init_apple_metal_shared_cache(backend);
3704 let device_name: String = cached.adapter.get_device_name().clone();
3705 let hardware_gpu: bool = cached.adapter.get_hardware_verified();
3706 let archive_enabled: bool = cached.binary_archive_enabled;
3707 let archive_hit: bool = cached.binary_archive_hit;
3708 let handles_and_us: [(ShaderProgramId, usize, u64); 4] = [
3709 (
3710 ShaderProgramId::UiUber,
3711 cached.pipeline,
3712 cached.ui_compile_us,
3713 ),
3714 (
3715 ShaderProgramId::BackdropBlur,
3716 cached.blur_pipeline,
3717 cached.blur_compile_us,
3718 ),
3719 (
3720 ShaderProgramId::Engine3dPbr,
3721 cached.engine3d_pipeline,
3722 cached.engine3d_compile_us,
3723 ),
3724 (
3725 ShaderProgramId::FluidOceanOptical,
3726 cached.ocean_pipeline,
3727 cached.ocean_compile_us,
3728 ),
3729 ];
3730 let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(handles_and_us.len());
3731 let mut ready_count: usize = 0;
3732 let mut hw_compiled: usize = 0;
3733 for (program, pso_handle, compile_us) in handles_and_us {
3734 let (src_a, src_b): (&str, &str) = program.source_pair(backend);
3735 let src_bytes: usize = src_a.len().saturating_add(src_b.len());
3736 let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
3737 let state: ShaderCompileState = if pso_handle != 0 {
3738 hw_compiled += 1;
3739 ready_count += 1;
3740 if archive_hit {
3741 ShaderCompileState::LoadedFromBinaryArchive
3742 } else {
3743 ShaderCompileState::CompiledHardware
3744 }
3745 } else if !src_a.is_empty() {
3746 ready_count += 1;
3747 ShaderCompileState::ValidatedFallback
3748 } else {
3749 ShaderCompileState::Failed
3750 };
3751 entries.push(ShaderProgramCacheEntry {
3752 program,
3753 name: program.label().to_string(),
3754 language: lang_label.to_string(),
3755 state,
3756 source_hash: src_hash,
3757 source_bytes: src_bytes,
3758 compile_time_us: compile_us,
3759 pipeline_ready: state.is_ready(),
3760 });
3761 }
3762 let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
3763 let cold_us: u64 = cached.total_compile_us.max(elapsed_us);
3764 return ShaderPrecompileReport {
3765 backend,
3766 device_name,
3767 hardware_gpu,
3768 binary_archive_enabled: archive_enabled,
3769 binary_archive_hit: archive_hit,
3770 cache_hit: false,
3771 total_programs: entries.len(),
3772 ready_programs: ready_count,
3773 hardware_compiled_programs: hw_compiled,
3774 cold_compile_us: cold_us,
3775 last_call_us: elapsed_us,
3776 entries,
3777 };
3778 }
3779 let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
3780 let device_name: String = probed.adapter.get_device_name().clone();
3781 let hardware_gpu: bool = probed.adapter.get_hardware_verified();
3782 let hw_shader_ok: bool = probed.adapter.get_shader_compiled();
3783 release_native_gpu_object(probed.dummy_r8_tex);
3784 release_native_gpu_object(probed.dummy_rgba8_tex);
3785 release_native_gpu_object(probed.ocean_pipeline_handle);
3786 release_native_gpu_object(probed.engine3d_pipeline_handle);
3787 release_native_gpu_object(probed.blur_pipeline_handle);
3788 release_native_gpu_object(probed.pipeline_handle);
3789 release_native_gpu_handles(
3790 probed.device_handle,
3791 probed.queue_handle,
3792 probed.library_handle,
3793 );
3794 let programs: [ShaderProgramId; 4] = ShaderProgramId::all();
3795 let mut entries: Vec<ShaderProgramCacheEntry> = Vec::with_capacity(programs.len());
3796 let mut ready_count: usize = 0;
3797 let mut hw_compiled: usize = 0;
3798 for program in programs {
3799 #[cfg(not(target_arch = "wasm32"))]
3800 let item_start: Instant = Instant::now();
3801 let (src_a, src_b): (&str, &str) = program.source_pair(backend);
3802 let src_bytes: usize = src_a.len().saturating_add(src_b.len());
3803 let src_hash: u64 = shader_program_cache_hash(&device_name, src_a, src_b);
3804 let is_valid: bool = !src_a.is_empty();
3805 let state: ShaderCompileState = if hardware_gpu && hw_shader_ok && is_valid {
3806 hw_compiled += 1;
3807 ready_count += 1;
3808 ShaderCompileState::CompiledHardware
3809 } else if is_valid {
3810 ready_count += 1;
3811 ShaderCompileState::ValidatedFallback
3812 } else {
3813 ShaderCompileState::Failed
3814 };
3815 #[cfg(not(target_arch = "wasm32"))]
3816 let item_us: u64 = item_start.elapsed().as_micros() as u64;
3817 #[cfg(target_arch = "wasm32")]
3818 let item_us: u64 = 0;
3819 entries.push(ShaderProgramCacheEntry {
3820 program,
3821 name: program.label().to_string(),
3822 language: lang_label.to_string(),
3823 state,
3824 source_hash: src_hash,
3825 source_bytes: src_bytes,
3826 compile_time_us: item_us,
3827 pipeline_ready: state.is_ready(),
3828 });
3829 }
3830 #[cfg(not(target_arch = "wasm32"))]
3831 let elapsed_us: u64 = total_start.elapsed().as_micros() as u64;
3832 #[cfg(target_arch = "wasm32")]
3833 let elapsed_us: u64 = 0;
3834 ShaderPrecompileReport {
3835 backend,
3836 device_name,
3837 hardware_gpu,
3838 binary_archive_enabled: false,
3839 binary_archive_hit: false,
3840 cache_hit: false,
3841 total_programs: entries.len(),
3842 ready_programs: ready_count,
3843 hardware_compiled_programs: hw_compiled,
3844 cold_compile_us: elapsed_us,
3845 last_call_us: elapsed_us,
3846 entries,
3847 }
3848}
3849
3850#[must_use]
3860pub fn precompile_shaders(backend: GraphicsBackend) -> ShaderPrecompileReport {
3861 #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
3862 {
3863 let call_start: Instant = Instant::now();
3864 let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
3865 SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
3866 if let Ok(guard) = cache_mutex.lock()
3867 && let Some(existing) = guard.get(&backend)
3868 {
3869 let mut hit_report: ShaderPrecompileReport = existing.clone();
3870 hit_report.set_cache_hit(true);
3871 hit_report.set_last_call_us(call_start.elapsed().as_micros() as u64);
3872 return hit_report;
3873 }
3874 let fresh: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
3875 if let Ok(mut guard) = cache_mutex.lock() {
3876 let _: Option<ShaderPrecompileReport> = guard.insert(backend, fresh.clone());
3877 }
3878 fresh
3879 }
3880 #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
3881 {
3882 run_shader_precompile_uncached(backend)
3883 }
3884}
3885
3886pub fn precompile_shaders_async(backend: GraphicsBackend) {
3892 #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
3893 {
3894 let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
3895 SHADER_PRECOMPILE_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
3896 if let Ok(guard) = cache_mutex.lock()
3897 && guard.contains_key(&backend)
3898 {
3899 return;
3900 }
3901 if SHADER_PRECOMPILE_IN_FLIGHT
3902 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
3903 .is_err()
3904 {
3905 return;
3906 }
3907 let spawn_result: io::Result<JoinHandle<()>> = Builder::new()
3908 .name("euv-shader-precompile".to_string())
3909 .spawn(move || {
3910 let _: ShaderPrecompileReport = precompile_shaders(backend);
3911 SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
3912 });
3913 if spawn_result.is_err() {
3914 SHADER_PRECOMPILE_IN_FLIGHT.store(false, Ordering::Release);
3915 let _: ShaderPrecompileReport = precompile_shaders(backend);
3916 }
3917 }
3918 #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
3919 {
3920 let _: ShaderPrecompileReport = run_shader_precompile_uncached(backend);
3921 }
3922}
3923
3924#[must_use]
3930pub fn shader_precompile_status() -> Option<ShaderPrecompileReport> {
3931 #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
3932 {
3933 let cache_mutex: &Mutex<HashMap<GraphicsBackend, ShaderPrecompileReport>> =
3934 SHADER_PRECOMPILE_CACHE.get()?;
3935 let guard: MutexGuard<'_, HashMap<GraphicsBackend, ShaderPrecompileReport>> =
3936 cache_mutex.lock().ok()?;
3937 let native_backend: GraphicsBackend = default_native_gpu_backend();
3938 if let Some(native_report) = guard.get(&native_backend) {
3939 return Some(native_report.clone());
3940 }
3941 guard.values().next().cloned()
3942 }
3943 #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
3944 {
3945 None
3946 }
3947}
3948
3949#[must_use]
3955pub fn is_shader_precompile_in_flight() -> bool {
3956 #[cfg(any(all(unix, not(target_os = "watchos")), windows))]
3957 {
3958 SHADER_PRECOMPILE_IN_FLIGHT.load(Ordering::Acquire)
3959 }
3960 #[cfg(not(any(all(unix, not(target_os = "watchos")), windows)))]
3961 {
3962 false
3963 }
3964}