1use super::*;
2
3#[must_use]
13pub fn probe_native_gpu(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
14 if backend == GraphicsBackend::Headless || backend == GraphicsBackend::SoftwareCpu {
15 return (
16 GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
17 0,
18 0,
19 0,
20 );
21 }
22 #[cfg(any(target_os = "macos", target_os = "ios"))]
23 {
24 probe_apple_metal(backend)
25 }
26 #[cfg(target_os = "windows")]
27 {
28 probe_windows_d3d12(backend)
29 }
30 #[cfg(any(target_os = "linux", target_os = "android"))]
31 {
32 probe_vulkan_runtime(backend)
33 }
34 #[cfg(target_arch = "wasm32")]
35 {
36 (
37 GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
38 0,
39 0,
40 0,
41 )
42 }
43 #[cfg(not(any(target_arch = "wasm32", unix, windows)))]
44 {
45 (
46 GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
47 0,
48 0,
49 0,
50 )
51 }
52}
53
54pub fn submit_native_gpu_batches(
66 device_handle: usize,
67 queue_handle: usize,
68 batches: &[GpuBatch],
69) -> usize {
70 #[cfg(any(target_os = "macos", target_os = "ios"))]
71 {
72 metal_submit_batches(device_handle, queue_handle, batches)
73 }
74 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
75 {
76 let _: (usize, usize) = (device_handle, queue_handle);
77 batches
78 .iter()
79 .map(|b: &GpuBatch| b.get_instances().len())
80 .sum()
81 }
82}
83
84pub(crate) fn submit_native_gpu_batches_staged(
97 device_handle: usize,
98 queue_handle: usize,
99 staging: &mut (usize, usize, usize),
100 batches: &[GpuBatch],
101) -> usize {
102 #[cfg(any(target_os = "macos", target_os = "ios"))]
103 {
104 metal_submit_batches_staged(device_handle, queue_handle, staging, batches)
105 }
106 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
107 {
108 let _: (usize, usize, &mut (usize, usize, usize)) = (device_handle, queue_handle, staging);
109 batches
110 .iter()
111 .map(|b: &GpuBatch| b.get_instances().len())
112 .sum()
113 }
114}
115
116pub(crate) fn release_native_gpu_staging(staging_buffer_handle: usize) {
122 #[cfg(any(target_os = "macos", target_os = "ios"))]
123 {
124 if staging_buffer_handle != 0 {
125 let sel: &MetalSelectors = cached_metal_selectors();
126 mtl_send_void0(
127 staging_buffer_handle as *mut c_void,
128 sel.release as *mut c_void,
129 );
130 }
131 }
132 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
133 {
134 let _: usize = staging_buffer_handle;
135 }
136}
137
138pub fn release_native_gpu_handles(
146 device_handle: usize,
147 queue_handle: usize,
148 library_handle: usize,
149) {
150 #[cfg(any(target_os = "macos", target_os = "ios"))]
151 {
152 metal_release_handles(device_handle, queue_handle, library_handle);
153 }
154 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
155 {
156 let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
157 }
158}
159
160#[cfg(any(target_os = "macos", target_os = "ios"))]
161#[link(name = "Metal", kind = "framework")]
162unsafe extern "C" {
163 fn MTLCreateSystemDefaultDevice() -> *mut c_void;
169}
170
171#[cfg(any(target_os = "macos", target_os = "ios"))]
172#[link(name = "objc")]
173unsafe extern "C" {
174 fn objc_getClass(name: *const c_char) -> *mut c_void;
184 fn sel_registerName(name: *const c_char) -> *mut c_void;
194 fn objc_msgSend();
196}
197
198#[cfg(any(target_os = "macos", target_os = "ios"))]
208fn mtl_sel(name: &str) -> *mut c_void {
209 let Ok(c_name) = CString::new(name) else {
210 return null_mut();
211 };
212 unsafe { sel_registerName(c_name.as_ptr()) }
213}
214
215#[cfg(any(target_os = "macos", target_os = "ios"))]
225fn mtl_ns_string(text: &str) -> *mut c_void {
226 let Ok(cls_name) = CString::new(MTL_CLS_NS_STRING) else {
227 return null_mut();
228 };
229 let Ok(c_text) = CString::new(text) else {
230 return null_mut();
231 };
232 unsafe {
233 let cls: *mut c_void = objc_getClass(cls_name.as_ptr());
234 if cls.is_null() {
235 return null_mut();
236 }
237 let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
238 transmute(objc_msgSend as *const c_void);
239 send(cls, mtl_sel(MTL_SEL_STRING_UTF8), c_text.as_ptr())
240 }
241}
242
243#[cfg(any(target_os = "macos", target_os = "ios"))]
254fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
255 if obj.is_null() || sel.is_null() {
256 return null_mut();
257 }
258 unsafe {
259 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
260 transmute(objc_msgSend as *const c_void);
261 send(obj, sel)
262 }
263}
264
265#[cfg(any(target_os = "macos", target_os = "ios"))]
272fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
273 if obj.is_null() || sel.is_null() {
274 return;
275 }
276 unsafe {
277 let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
278 transmute(objc_msgSend as *const c_void);
279 send(obj, sel);
280 }
281}
282
283#[cfg(any(target_os = "macos", target_os = "ios"))]
293fn probe_apple_metal(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
294 unsafe {
295 let device: *mut c_void = MTLCreateSystemDefaultDevice();
296 if device.is_null() {
297 return (
298 GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
299 0,
300 0,
301 0,
302 );
303 }
304 let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel(MTL_SEL_NAME));
305 let utf8_ptr: *const c_char =
306 mtl_send_ptr0(ns_name, mtl_sel(MTL_SEL_UTF8_STRING)).cast::<c_char>();
307 let device_name: String = if utf8_ptr.is_null() {
308 GPU_DEVICE_APPLE_METAL.to_string()
309 } else {
310 CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
311 };
312 let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel(MTL_SEL_NEW_CMD_QUEUE));
313 let ns_src: *mut c_void = mtl_ns_string(MSL_UI_SHADER);
314 let mut err_ptr: *mut c_void = null_mut();
315 let send_lib: unsafe extern "C" fn(
316 *mut c_void,
317 *mut c_void,
318 *mut c_void,
319 *mut c_void,
320 *mut *mut c_void,
321 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
322 let library: *mut c_void = send_lib(
323 device,
324 mtl_sel(MTL_SEL_NEW_LIBRARY),
325 ns_src,
326 null_mut(),
327 &mut err_ptr,
328 );
329 let mut shader_compiled: bool = false;
330 if !library.is_null() {
331 let send_fn: unsafe extern "C" fn(
332 *mut c_void,
333 *mut c_void,
334 *mut c_void,
335 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
336 let vs_fn: *mut c_void = send_fn(
337 library,
338 mtl_sel(MTL_SEL_NEW_FUNCTION),
339 mtl_ns_string(MTL_FN_VERTEX),
340 );
341 let fs_fn: *mut c_void = send_fn(
342 library,
343 mtl_sel(MTL_SEL_NEW_FUNCTION),
344 mtl_ns_string(MTL_FN_FRAGMENT),
345 );
346 shader_compiled = !vs_fn.is_null() && !fs_fn.is_null();
347 if !vs_fn.is_null() {
348 mtl_send_void0(vs_fn, mtl_sel(MTL_SEL_RELEASE));
349 }
350 if !fs_fn.is_null() {
351 mtl_send_void0(fs_fn, mtl_sel(MTL_SEL_RELEASE));
352 }
353 }
354 (
355 GpuAdapterInfo::new(
356 GraphicsBackend::Metal,
357 device_name,
358 !queue.is_null(),
359 shader_compiled,
360 ),
361 device as usize,
362 queue as usize,
363 library as usize,
364 )
365 }
366}
367
368#[cfg(any(target_os = "macos", target_os = "ios"))]
374fn cached_metal_selectors() -> &'static MetalSelectors {
375 METAL_SELECTORS.get_or_init(|| MetalSelectors {
376 new_buffer_with_bytes: mtl_sel(MTL_SEL_NEW_BUFFER) as usize,
377 new_buffer_with_length: mtl_sel(MTL_SEL_NEW_BUFFER_LENGTH) as usize,
378 contents: mtl_sel(MTL_SEL_CONTENTS) as usize,
379 command_buffer: mtl_sel(MTL_SEL_CMD_BUFFER) as usize,
380 commit: mtl_sel(MTL_SEL_COMMIT) as usize,
381 release: mtl_sel(MTL_SEL_RELEASE) as usize,
382 })
383}
384
385#[cfg(any(target_os = "macos", target_os = "ios"))]
398fn metal_submit_batches_staged(
399 device_handle: usize,
400 queue_handle: usize,
401 staging: &mut (usize, usize, usize),
402 batches: &[GpuBatch],
403) -> usize {
404 let total_instances: usize = batches
405 .iter()
406 .map(|b: &GpuBatch| b.get_instances().len())
407 .sum();
408 if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
409 return total_instances;
410 }
411 let total_bytes: usize = total_instances.saturating_mul(size_of::<GpuQuadInstance>());
412 let device: *mut c_void = device_handle as *mut c_void;
413 let queue: *mut c_void = queue_handle as *mut c_void;
414 let sel: &MetalSelectors = cached_metal_selectors();
415 let sel_rel: *mut c_void = sel.release as *mut c_void;
416 let (buf_handle, contents_ptr, capacity): &mut (usize, usize, usize) = staging;
417 unsafe {
418 if *buf_handle == 0 || *contents_ptr == 0 || total_bytes > *capacity {
419 if *buf_handle != 0 {
420 mtl_send_void0(*buf_handle as *mut c_void, sel_rel);
421 *buf_handle = 0;
422 *contents_ptr = 0;
423 *capacity = 0;
424 }
425 let alloc_bytes: usize = total_bytes.max(4096).next_power_of_two();
426 let send_new_len: unsafe extern "C" fn(
427 *mut c_void,
428 *mut c_void,
429 usize,
430 usize,
431 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
432 let new_buf: *mut c_void = send_new_len(
433 device,
434 sel.new_buffer_with_length as *mut c_void,
435 alloc_bytes,
436 0,
437 );
438 if !new_buf.is_null() {
439 let ptr: *mut c_void = mtl_send_ptr0(new_buf, sel.contents as *mut c_void);
440 if !ptr.is_null() {
441 *buf_handle = new_buf as usize;
442 *contents_ptr = ptr as usize;
443 *capacity = alloc_bytes;
444 } else {
445 mtl_send_void0(new_buf, sel_rel);
446 }
447 }
448 }
449 if *contents_ptr != 0 && total_bytes <= *capacity {
450 let mut dst: *mut u8 = (*contents_ptr as *mut c_void).cast::<u8>();
451 for batch in batches.iter() {
452 let instances: &[GpuQuadInstance] = batch.get_instances();
453 if instances.is_empty() {
454 continue;
455 }
456 let byte_len: usize = size_of_val(instances);
457 dst.copy_from_nonoverlapping(instances.as_ptr().cast::<u8>(), byte_len);
458 dst = dst.add(byte_len);
459 }
460 } else {
461 let send_buf: unsafe extern "C" fn(
462 *mut c_void,
463 *mut c_void,
464 *const c_void,
465 usize,
466 usize,
467 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
468 let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
469 for batch in batches.iter() {
470 let instances: &[GpuQuadInstance] = batch.get_instances();
471 if instances.is_empty() {
472 continue;
473 }
474 let byte_len: usize = size_of_val(instances);
475 let mtl_buf: *mut c_void = send_buf(
476 device,
477 sel_buf,
478 instances.as_ptr().cast::<c_void>(),
479 byte_len,
480 0,
481 );
482 if !mtl_buf.is_null() {
483 mtl_send_void0(mtl_buf, sel_rel);
484 }
485 }
486 }
487 let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
488 if !cmd_buf.is_null() {
489 mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
490 }
491 }
492 total_instances
493}
494
495#[cfg(any(target_os = "macos", target_os = "ios"))]
507fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
508 let total_instances: usize = batches
509 .iter()
510 .map(|b: &GpuBatch| b.get_instances().len())
511 .sum();
512 if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
513 return total_instances;
514 }
515 let device: *mut c_void = device_handle as *mut c_void;
516 let queue: *mut c_void = queue_handle as *mut c_void;
517 let sel: &MetalSelectors = cached_metal_selectors();
518 let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
519 let sel_rel: *mut c_void = sel.release as *mut c_void;
520 unsafe {
521 let send_buf: unsafe extern "C" fn(
522 *mut c_void,
523 *mut c_void,
524 *const c_void,
525 usize,
526 usize,
527 ) -> *mut c_void = transmute(objc_msgSend as *const c_void);
528 for batch in batches.iter() {
529 let instances: &[GpuQuadInstance] = batch.get_instances();
530 if instances.is_empty() {
531 continue;
532 }
533 let byte_len: usize = size_of_val(instances);
534 let mtl_buf: *mut c_void = send_buf(
535 device,
536 sel_buf,
537 instances.as_ptr().cast::<c_void>(),
538 byte_len,
539 0,
540 );
541 if !mtl_buf.is_null() {
542 mtl_send_void0(mtl_buf, sel_rel);
543 }
544 }
545 let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
546 if !cmd_buf.is_null() {
547 mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
548 }
549 }
550 total_instances
551}
552
553#[cfg(any(target_os = "macos", target_os = "ios"))]
561fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
562 let sel_rel: *mut c_void = cached_metal_selectors().release as *mut c_void;
563 if library_handle != 0 {
564 mtl_send_void0(library_handle as *mut c_void, sel_rel);
565 }
566 if queue_handle != 0 {
567 mtl_send_void0(queue_handle as *mut c_void, sel_rel);
568 }
569 if device_handle != 0 {
570 mtl_send_void0(device_handle as *mut c_void, sel_rel);
571 }
572}
573
574#[cfg(target_os = "windows")]
575#[link(name = "kernel32")]
576unsafe extern "system" {
577 fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
587 fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
598 fn FreeLibrary(h_lib_module: *mut c_void) -> i32;
608}
609
610#[cfg(target_os = "windows")]
620fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
621 unsafe {
622 let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
623 let has_d3d12: bool = if !d3d12_mod.is_null() {
624 let fn_ptr: *mut c_void = GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr());
625 let _: i32 = FreeLibrary(d3d12_mod);
626 !fn_ptr.is_null()
627 } else {
628 false
629 };
630 let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
631 let has_compiler: bool = if !compiler_mod.is_null() {
632 let fn_ptr: *mut c_void = GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr());
633 let _: i32 = FreeLibrary(compiler_mod);
634 !fn_ptr.is_null()
635 } else {
636 false
637 };
638 let label: &str = if has_d3d12 {
639 GPU_DEVICE_D3D12
640 } else {
641 GPU_DEVICE_FALLBACK
642 };
643 (
644 GpuAdapterInfo::new(backend, label.to_string(), has_d3d12, has_compiler),
645 0,
646 0,
647 0,
648 )
649 }
650}
651
652#[cfg(any(target_os = "linux", target_os = "android"))]
653unsafe extern "C" {
654 fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
665 fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
676 fn dlclose(handle: *mut c_void) -> i32;
686}
687
688#[cfg(any(target_os = "linux", target_os = "android"))]
698fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
699 let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
700 return (
701 GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
702 0,
703 0,
704 0,
705 );
706 };
707 let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
708 return (
709 GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
710 0,
711 0,
712 0,
713 );
714 };
715 let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
716 return (
717 GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
718 0,
719 0,
720 0,
721 );
722 };
723 let available: bool = unsafe {
724 let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
725 if handle.is_null() {
726 false
727 } else {
728 let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
729 let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
730 let _: i32 = dlclose(handle);
731 !p1.is_null() && !p2.is_null()
732 }
733 };
734 let name: &str = if available {
735 GPU_DEVICE_VULKAN
736 } else {
737 GPU_DEVICE_FALLBACK
738 };
739 (
740 GpuAdapterInfo::new(backend, name.to_string(), available, available),
741 0,
742 0,
743 0,
744 )
745}
746
747#[cfg(target_arch = "wasm32")]
757pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
758 let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
759 gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
760 gl.compile_shader(&vs);
761 let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
762 gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
763 gl.compile_shader(&fs);
764 let program: WebGlProgram = gl.create_program()?;
765 gl.attach_shader(&program, &vs);
766 gl.attach_shader(&program, &fs);
767 gl.link_program(&program);
768 Some(program)
769}