Skip to main content

euv_core/render/gpu/
fn.rs

1use super::*;
2
3/// Probes the host OS for a physical GPU adapter, compiles native UI shaders, and returns handles.
4///
5/// # Arguments
6///
7/// - `GraphicsBackend` - Requested graphics backend.
8///
9/// # Returns
10///
11/// - `(GpuAdapterInfo, usize, usize, usize)` - Adapter info plus `(device, queue, library)` raw handles.
12#[must_use]
13pub fn probe_native_gpu(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
14    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
54/// Uploads instanced quad buffers and submits a command buffer to the active physical GPU.
55///
56/// # Arguments
57///
58/// - `usize` - Raw OS device handle.
59/// - `usize` - Raw OS command queue handle.
60/// - `&[GpuBatch]` - Compiled instanced draw batches.
61///
62/// # Returns
63///
64/// - `usize` - Total GPU instances uploaded and submitted.
65pub 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
84/// Uploads instanced quad buffers via a reusable grow-only staging buffer and submits a command buffer to the active GPU.
85///
86/// # Arguments
87///
88/// - `usize` - Raw OS device handle.
89/// - `usize` - Raw OS command queue handle.
90/// - `&mut (usize, usize, usize)` - Reusable staging state `(buffer_handle, contents_ptr, byte_capacity)`.
91/// - `&[GpuBatch]` - Compiled instanced draw batches.
92///
93/// # Returns
94///
95/// - `usize` - Total GPU instances uploaded and submitted.
96pub(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
116/// Releases any retained persistent GPU staging buffer before tearing down device handles.
117///
118/// # Arguments
119///
120/// - `usize` - Retained staging buffer handle (`0` when unallocated).
121pub(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
138/// Releases native GPU handles on driver teardown.
139///
140/// # Arguments
141///
142/// - `usize` - Raw device handle.
143/// - `usize` - Raw command queue handle.
144/// - `usize` - Raw shader library handle.
145pub 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    /// Creates the default Apple Metal GPU device handle.
164    ///
165    /// # Returns
166    ///
167    /// - `*mut c_void` - A `*mut c_void` value.
168    fn MTLCreateSystemDefaultDevice() -> *mut c_void;
169}
170
171#[cfg(any(target_os = "macos", target_os = "ios"))]
172#[link(name = "objc")]
173unsafe extern "C" {
174    /// Looks up an Objective-C class pointer by C name.
175    ///
176    /// # Arguments
177    ///
178    /// - `*const c_char` - A `*const c_char` parameter.
179    ///
180    /// # Returns
181    ///
182    /// - `*mut c_void` - A `*mut c_void` value.
183    fn objc_getClass(name: *const c_char) -> *mut c_void;
184    /// Registers an Objective-C selector by C name.
185    ///
186    /// # Arguments
187    ///
188    /// - `*const c_char` - A `*const c_char` parameter.
189    ///
190    /// # Returns
191    ///
192    /// - `*mut c_void` - A `*mut c_void` value.
193    fn sel_registerName(name: *const c_char) -> *mut c_void;
194    /// Objective-C dynamic message dispatch entry point.
195    fn objc_msgSend();
196}
197
198/// Registers an Objective-C selector for Apple Metal FFI calls.
199///
200/// # Arguments
201///
202/// - `&str` - Selector name.
203///
204/// # Returns
205///
206/// - `*mut c_void` - Registered Objective-C selector pointer.
207#[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/// Allocates an autoreleased `NSString` from a UTF-8 Rust slice.
216///
217/// # Arguments
218///
219/// - `&str` - Source UTF-8 string.
220///
221/// # Returns
222///
223/// - `*mut c_void` - Objective-C `NSString` pointer.
224#[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/// Sends a zero-argument Objective-C message returning a pointer.
244///
245/// # Arguments
246///
247/// - `*mut c_void` - Target Objective-C object.
248/// - `*mut c_void` - Selector pointer.
249///
250/// # Returns
251///
252/// - `*mut c_void` - Returned Objective-C object pointer.
253#[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/// Sends a zero-argument Objective-C message returning void.
266///
267/// # Arguments
268///
269/// - `*mut c_void` - Target Objective-C object.
270/// - `*mut c_void` - Selector pointer.
271#[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/// Initializes a real Apple Metal GPU device, command queue, and runtime-compiled MSL library.
284///
285/// # Arguments
286///
287/// - `GraphicsBackend` - Requested backend tag.
288///
289/// # Returns
290///
291/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Metal device info and retained ObjC handles.
292#[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/// Returns the process-wide `OnceLock`-cached Objective-C selector pointers for Metal submission and teardown.
369///
370/// # Returns
371///
372/// - `&'static MetalSelectors` - Cached Metal selector addresses.
373#[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/// Uploads `GpuQuadInstance` buffers into a reusable grow-only shared `MTLBuffer` and commits a command buffer using cached selectors.
386///
387/// # Arguments
388///
389/// - `usize` - Retained `id<MTLDevice>` pointer.
390/// - `usize` - Retained `id<MTLCommandQueue>` pointer.
391/// - `&mut (usize, usize, usize)` - Persistent staging tuple `(buffer_handle, contents_ptr, byte_capacity)`.
392/// - `&[GpuBatch]` - Ordered GPU batches to upload.
393///
394/// # Returns
395///
396/// - `usize` - Total instances uploaded into Metal GPU memory.
397#[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/// Uploads `GpuQuadInstance` buffers to Metal GPU memory and commits a command buffer.
496///
497/// # Arguments
498///
499/// - `usize` - Retained `id<MTLDevice>` pointer.
500/// - `usize` - Retained `id<MTLCommandQueue>` pointer.
501/// - `&[GpuBatch]` - Ordered GPU batches to upload.
502///
503/// # Returns
504///
505/// - `usize` - Total instances uploaded into Metal buffers.
506#[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/// Releases retained Apple Metal Objective-C objects cleanly on drop.
554///
555/// # Arguments
556///
557/// - `usize` - `id<MTLDevice>` pointer.
558/// - `usize` - `id<MTLCommandQueue>` pointer.
559/// - `usize` - `id<MTLLibrary>` pointer.
560#[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    /// Dynamically loads a Windows DLL by ANSI path.
578    ///
579    /// # Arguments
580    ///
581    /// - `*const u8` - A `*const u8` parameter.
582    ///
583    /// # Returns
584    ///
585    /// - `*mut c_void` - A `*mut c_void` value.
586    fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
587    /// Looks up an exported procedure address from a loaded Windows DLL.
588    ///
589    /// # Arguments
590    ///
591    /// - `*mut c_void` - A `*mut c_void` parameter.
592    /// - `*const u8` - A `*const u8` parameter.
593    ///
594    /// # Returns
595    ///
596    /// - `*mut c_void` - A `*mut c_void` value.
597    fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
598    /// Unloads a dynamically loaded Windows DLL module.
599    ///
600    /// # Arguments
601    ///
602    /// - `*mut c_void` - A `*mut c_void` parameter.
603    ///
604    /// # Returns
605    ///
606    /// - `i32` - A 32-bit signed integer.
607    fn FreeLibrary(h_lib_module: *mut c_void) -> i32;
608}
609
610/// Probes Windows Direct3D 12 and `d3dcompiler_47.dll` at runtime with zero link-time dependency.
611///
612/// # Arguments
613///
614/// - `GraphicsBackend` - Requested graphics backend.
615///
616/// # Returns
617///
618/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Direct3D 12 availability metadata.
619#[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    /// Dynamically opens a shared library object by name.
655    ///
656    /// # Arguments
657    ///
658    /// - `*const c_char` - A `*const c_char` parameter.
659    /// - `i32` - A 32-bit signed integer (`i32`).
660    ///
661    /// # Returns
662    ///
663    /// - `*mut c_void` - A `*mut c_void` value.
664    fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
665    /// Resolves a symbol address from an open shared library handle.
666    ///
667    /// # Arguments
668    ///
669    /// - `*mut c_void` - A `*mut c_void` parameter.
670    /// - `*const c_char` - A `*const c_char` parameter.
671    ///
672    /// # Returns
673    ///
674    /// - `*mut c_void` - A `*mut c_void` value.
675    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
676    /// Closes an open shared library handle.
677    ///
678    /// # Arguments
679    ///
680    /// - `*mut c_void` - A `*mut c_void` parameter.
681    ///
682    /// # Returns
683    ///
684    /// - `i32` - A 32-bit signed integer.
685    fn dlclose(handle: *mut c_void) -> i32;
686}
687
688/// Probes Linux or Android Vulkan loader (`libvulkan.so.1` / `libvulkan.so`) at runtime via `dlopen`.
689///
690/// # Arguments
691///
692/// - `GraphicsBackend` - Requested graphics backend.
693///
694/// # Returns
695///
696/// - `(GpuAdapterInfo, usize, usize, usize)` - Probed Vulkan runtime status.
697#[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/// Compiles and links the WebGL 2 analytical SDF shader program on `wasm32`.
748///
749/// # Arguments
750///
751/// - `&WebGl2RenderingContext` - Active WebGL 2 canvas context.
752///
753/// # Returns
754///
755/// - `Option<WebGlProgram>` - Linked shader program when compilation succeeds.
756#[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}