use super::*;
#[must_use]
pub fn probe_native_gpu(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
let probed: NativeGpuProbeOutput = probe_native_gpu_full(backend);
(
probed.adapter,
probed.device_handle,
probed.queue_handle,
probed.library_handle,
)
}
#[must_use]
pub(crate) fn probe_native_gpu_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
if backend == GraphicsBackend::Headless || backend == GraphicsBackend::SoftwareCpu {
return NativeGpuProbeOutput {
adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
device_handle: 0,
queue_handle: 0,
library_handle: 0,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
};
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
probe_apple_metal_full(backend)
}
#[cfg(target_os = "windows")]
{
let (adapter, device_handle, queue_handle, library_handle): (
GpuAdapterInfo,
usize,
usize,
usize,
) = probe_windows_d3d12(backend);
NativeGpuProbeOutput {
adapter,
device_handle,
queue_handle,
library_handle,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
{
let (adapter, device_handle, queue_handle, library_handle): (
GpuAdapterInfo,
usize,
usize,
usize,
) = probe_vulkan_runtime(backend);
NativeGpuProbeOutput {
adapter,
device_handle,
queue_handle,
library_handle,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
#[cfg(target_arch = "wasm32")]
{
NativeGpuProbeOutput {
adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_WEB.to_string(), true, false),
device_handle: 0,
queue_handle: 0,
library_handle: 0,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
#[cfg(not(any(target_arch = "wasm32", unix, windows)))]
{
NativeGpuProbeOutput {
adapter: GpuAdapterInfo::new(backend, GPU_DEVICE_FALLBACK.to_string(), false, false),
device_handle: 0,
queue_handle: 0,
library_handle: 0,
pipeline_handle: 0,
blur_pipeline_handle: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
}
}
pub fn submit_native_gpu_batches(
device_handle: usize,
queue_handle: usize,
batches: &[GpuBatch],
) -> usize {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_submit_batches(device_handle, queue_handle, batches)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: (usize, usize) = (device_handle, queue_handle);
batches
.iter()
.map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
.sum()
}
}
pub(crate) fn submit_native_gpu_ring_frame(
driver: &mut NativeGpuDriver,
width: u32,
height: u32,
clear_color: Color,
batches: &[GpuBatch],
) -> usize {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_submit_ring_frame(driver, width, height, clear_color, batches)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: (&mut NativeGpuDriver, u32, u32, Color) = (driver, width, height, clear_color);
batches
.iter()
.map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
.sum()
}
}
pub(crate) fn configure_native_metal_layer(device_handle: usize, layer_handle: usize) {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_configure_layer(device_handle, layer_handle);
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: (usize, usize) = (device_handle, layer_handle);
}
}
pub(crate) fn upload_native_texture_dirty_rect(
device_handle: usize,
texture_handle: &mut usize,
format: GpuAtlasPixelFormat,
tex_dims: (u32, u32),
dirty_rect: (u32, u32, u32, u32),
bytes: &[u8],
bytes_per_row: usize,
) -> bool {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_upload_texture_dirty_rect(
device_handle,
texture_handle,
format,
tex_dims,
dirty_rect,
bytes,
bytes_per_row,
)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: usize = device_handle;
let _: &mut usize = texture_handle;
let _: GpuAtlasPixelFormat = format;
let _: (u32, u32) = tex_dims;
let _: (u32, u32, u32, u32) = dirty_rect;
let _: &[u8] = bytes;
let _: usize = bytes_per_row;
false
}
}
pub(crate) fn retain_native_gpu_object(handle: usize) -> usize {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
mtl_retain_handle(handle)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
handle
}
}
pub(crate) fn release_native_gpu_object(handle: usize) {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
if handle != 0 {
let sel: &MetalSelectors = cached_metal_selectors();
mtl_send_void0(handle as *mut c_void, sel.release as *mut c_void);
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: usize = handle;
}
}
pub fn release_native_gpu_handles(
device_handle: usize,
queue_handle: usize,
library_handle: usize,
) {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
metal_release_handles(device_handle, queue_handle, library_handle);
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
let _: (usize, usize, usize) = (device_handle, queue_handle, library_handle);
}
}
#[must_use]
pub fn native_gpu_last_presented_ns() -> u64 {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
METAL_LAST_PRESENTED_NS.load(Ordering::Relaxed)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
0
}
}
#[must_use]
pub fn native_gpu_last_exec_ns() -> u64 {
#[cfg(any(target_os = "macos", target_os = "ios"))]
{
METAL_LAST_GPU_EXEC_NS.load(Ordering::Relaxed)
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
{
0
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "Metal", kind = "framework")]
unsafe extern "C" {
fn MTLCreateSystemDefaultDevice() -> *mut c_void;
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "objc")]
unsafe extern "C" {
fn objc_getClass(name: *const c_char) -> *mut c_void;
fn sel_registerName(name: *const c_char) -> *mut c_void;
fn objc_autoreleasePoolPush() -> *mut c_void;
fn objc_autoreleasePoolPop(pool: *mut c_void);
fn objc_msgSend();
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" {
static _NSConcreteGlobalBlock: c_void;
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_sel_cstr(name: &'static str) -> *mut c_void {
unsafe { sel_registerName(name.as_ptr().cast::<c_char>()) }
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_cls_cstr(name: &'static str) -> *mut c_void {
unsafe { objc_getClass(name.as_ptr().cast::<c_char>()) }
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_ns_string(text: &str) -> *mut c_void {
let Ok(c_text) = CString::new(text) else {
return null_mut();
};
unsafe {
let cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_STRING);
if cls.is_null() {
return null_mut();
}
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
transmute(objc_msgSend as *const c_void);
send(cls, mtl_sel_cstr(MTL_SEL_STRING_UTF8), c_text.as_ptr())
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_ptr0(obj: *mut c_void, sel: *mut c_void) -> *mut c_void {
if obj.is_null() || sel.is_null() {
return null_mut();
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
transmute(objc_msgSend as *const c_void);
send(obj, sel)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) -> *mut c_void {
if obj.is_null() || sel.is_null() {
return null_mut();
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> *mut c_void =
transmute(objc_msgSend as *const c_void);
send(obj, sel, arg0)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void0(obj: *mut c_void, sel: *mut c_void) {
if obj.is_null() || sel.is_null() {
return;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void) =
transmute(objc_msgSend as *const c_void);
send(obj, sel);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void_ptr1(obj: *mut c_void, sel: *mut c_void, arg0: *mut c_void) {
if obj.is_null() || sel.is_null() {
return;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
transmute(objc_msgSend as *const c_void);
send(obj, sel, arg0);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void_usize(obj: *mut c_void, sel: *mut c_void, val: usize) {
if obj.is_null() || sel.is_null() {
return;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) =
transmute(objc_msgSend as *const c_void);
send(obj, sel, val);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_void_bool(obj: *mut c_void, sel: *mut c_void, val: bool) {
if obj.is_null() || sel.is_null() {
return;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, i8) =
transmute(objc_msgSend as *const c_void);
send(obj, sel, if val { 1 } else { 0 });
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_usize0(obj: *mut c_void, sel: *mut c_void) -> usize {
if obj.is_null() || sel.is_null() {
return 0;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
transmute(objc_msgSend as *const c_void);
send(obj, sel)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_send_f64_0(obj: *mut c_void, sel: *mut c_void) -> f64 {
if obj.is_null() || sel.is_null() {
return 0.0;
}
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void) -> f64 =
transmute(objc_msgSend as *const c_void);
send(obj, sel)
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_responds_to_sel(obj: *mut c_void, sel: *mut c_void) -> bool {
if obj.is_null() || sel.is_null() {
return false;
}
let responds_sel: *mut c_void = cached_metal_selectors().responds_to_sel as *mut c_void;
unsafe {
let send: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) -> i8 =
transmute(objc_msgSend as *const c_void);
send(obj, responds_sel, sel) != 0
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mtl_retain_handle(handle: usize) -> usize {
if handle == 0 {
return 0;
}
let sel_retain: *mut c_void = cached_metal_selectors().retain as *mut c_void;
mtl_send_ptr0(handle as *mut c_void, sel_retain) as usize
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" fn metal_presented_handler_invoke(_block: *mut c_void, drawable: *mut c_void) {
if drawable.is_null() {
return;
}
let sel: &MetalSelectors = cached_metal_selectors();
let presented_secs: f64 = mtl_send_f64_0(drawable, sel.presented_time as *mut c_void);
if presented_secs.is_finite() && presented_secs > 0.0 {
let ns: u64 = (presented_secs * 1_000_000_000.0).round() as u64;
METAL_LAST_PRESENTED_NS.store(ns, Ordering::Relaxed);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
unsafe extern "C" fn metal_completed_handler_invoke(_block: *mut c_void, cmd_buf: *mut c_void) {
if cmd_buf.is_null() {
return;
}
let sel: &MetalSelectors = cached_metal_selectors();
let start_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_start_time as *mut c_void);
let end_s: f64 = mtl_send_f64_0(cmd_buf, sel.gpu_end_time as *mut c_void);
if start_s.is_finite() && end_s.is_finite() && end_s >= start_s {
let exec_ns: u64 = ((end_s - start_s) * 1_000_000_000.0).round() as u64;
METAL_LAST_GPU_EXEC_NS.store(exec_ns, Ordering::Relaxed);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_presented_block_ptr() -> *mut c_void {
let addr: usize = *METAL_PRESENTED_BLOCK_ADDR.get_or_init(|| {
let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
flags: OBJC_BLOCK_IS_GLOBAL,
reserved: 0,
invoke: metal_presented_handler_invoke,
descriptor: &METAL_BLOCK_DESCRIPTOR,
});
Box::into_raw(block) as usize
});
addr as *mut c_void
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_completed_block_ptr() -> *mut c_void {
let addr: usize = *METAL_COMPLETED_BLOCK_ADDR.get_or_init(|| {
let block: Box<ObjcGlobalBlock> = Box::new(ObjcGlobalBlock {
isa: unsafe { &_NSConcreteGlobalBlock as *const c_void },
flags: OBJC_BLOCK_IS_GLOBAL,
reserved: 0,
invoke: metal_completed_handler_invoke,
descriptor: &METAL_BLOCK_DESCRIPTOR,
});
Box::into_raw(block) as usize
});
addr as *mut c_void
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_pipeline_cache_hash(device_name: &str) -> u64 {
let mut hash: u64 = FNV1A_OFFSET_BASIS;
for chunk in [
device_name.as_bytes(),
MSL_UI_SHADER.as_bytes(),
MSL_BACKDROP_BLUR_SHADER.as_bytes(),
]
.iter()
{
for &byte in chunk.iter() {
hash ^= byte as u64;
hash = hash.wrapping_mul(FNV1A_PRIME);
}
}
hash
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_create_texture(
device: *mut c_void,
format: GpuAtlasPixelFormat,
width: u32,
height: u32,
) -> usize {
if device.is_null() {
return 0;
}
let px_fmt: usize = match format {
GpuAtlasPixelFormat::R8Unorm => MTL_PIXEL_FORMAT_R8_UNORM,
GpuAtlasPixelFormat::Rgba8Unorm => MTL_PIXEL_FORMAT_RGBA8_UNORM,
};
let cls_desc: *mut c_void = mtl_cls_cstr(MTL_CLS_TEX_DESC);
if cls_desc.is_null() {
return 0;
}
unsafe {
let send_desc: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
usize,
i8,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
let desc: *mut c_void = send_desc(
cls_desc,
mtl_sel_cstr(MTL_SEL_TEX_2D_DESC),
px_fmt,
width.max(1) as usize,
height.max(1) as usize,
0,
);
if desc.is_null() {
return 0;
}
mtl_send_void_usize(desc, mtl_sel_cstr(MTL_SEL_SET_USAGE), 1);
let tex: *mut c_void = mtl_send_ptr1(device, mtl_sel_cstr(MTL_SEL_NEW_TEXTURE), desc);
tex as usize
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_build_render_pipeline(
device: *mut c_void,
library: *mut c_void,
vs_name: &str,
fs_name: &str,
archive: *mut c_void,
enable_blend: bool,
) -> (usize, bool) {
if device.is_null() || library.is_null() {
return (0, false);
}
let sel_rel: *mut c_void = mtl_sel_cstr(MTL_SEL_RELEASE);
let vs_fn: *mut c_void = mtl_send_ptr1(
library,
mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
mtl_ns_string(vs_name),
);
let fs_fn: *mut c_void = mtl_send_ptr1(
library,
mtl_sel_cstr(MTL_SEL_NEW_FUNCTION),
mtl_ns_string(fs_name),
);
let functions_ok: bool = !vs_fn.is_null() && !fs_fn.is_null();
if !functions_ok {
if !vs_fn.is_null() {
mtl_send_void0(vs_fn, sel_rel);
}
if !fs_fn.is_null() {
mtl_send_void0(fs_fn, sel_rel);
}
return (0, false);
}
let desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PIPELINE_DESC);
let desc_alloc: *mut c_void = mtl_send_ptr0(desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
let desc: *mut c_void = mtl_send_ptr0(desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
if desc.is_null() {
mtl_send_void0(vs_fn, sel_rel);
mtl_send_void0(fs_fn, sel_rel);
return (0, functions_ok);
}
mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_VERTEX_FUNCTION), vs_fn);
mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_FUNCTION), fs_fn);
let color_atts: *mut c_void = mtl_send_ptr0(desc, mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS));
let att0: *mut c_void = unsafe {
let send_idx: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
transmute(objc_msgSend as *const c_void);
send_idx(color_atts, mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX), 0)
};
if !att0.is_null() {
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
MTL_PIXEL_FORMAT_BGRA8_UNORM,
);
if enable_blend {
mtl_send_void_bool(att0, mtl_sel_cstr(MTL_SEL_SET_BLENDING_ENABLED), true);
mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_RGB_BLEND_OP), 0);
mtl_send_void_usize(att0, mtl_sel_cstr(MTL_SEL_SET_ALPHA_BLEND_OP), 0);
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_SRC_RGB_BLEND),
MTL_BLEND_FACTOR_SRC_ALPHA,
);
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_DST_RGB_BLEND),
MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
);
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_SRC_ALPHA_BLEND),
MTL_BLEND_FACTOR_ONE,
);
mtl_send_void_usize(
att0,
mtl_sel_cstr(MTL_SEL_SET_DST_ALPHA_BLEND),
MTL_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
);
}
}
if !archive.is_null() && mtl_responds_to_sel(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES)) {
let arr_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_ARRAY);
let arr: *mut c_void =
mtl_send_ptr1(arr_cls, mtl_sel_cstr(MTL_SEL_ARRAY_WITH_OBJECT), archive);
if !arr.is_null() {
mtl_send_void_ptr1(desc, mtl_sel_cstr(MTL_SEL_SET_BINARY_ARCHIVES), arr);
}
}
let mut err_ptr: *mut c_void = null_mut();
let pipeline: *mut c_void = unsafe {
let send_pso: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
send_pso(
device,
mtl_sel_cstr(MTL_SEL_NEW_PIPELINE_STATE),
desc,
&mut err_ptr,
)
};
if !archive.is_null() && !pipeline.is_null() {
let mut add_err: *mut c_void = null_mut();
unsafe {
let send_add: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> i8 = transmute(objc_msgSend as *const c_void);
let _: i8 = send_add(
archive,
mtl_sel_cstr(MTL_SEL_ADD_PIPELINE_TO_ARCHIVE),
desc,
&mut add_err,
);
}
}
mtl_send_void0(desc, sel_rel);
mtl_send_void0(vs_fn, sel_rel);
mtl_send_void0(fs_fn, sel_rel);
(pipeline as usize, functions_ok)
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_open_binary_archive(
device: *mut c_void,
device_name: &str,
) -> (*mut c_void, *mut c_void, bool) {
let arch_desc_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_BINARY_ARCHIVE_DESC);
if arch_desc_cls.is_null() {
return (null_mut(), null_mut(), false);
}
let cache_hash: u64 = metal_pipeline_cache_hash(device_name);
let archive_path: String = env::temp_dir()
.join(format!(
"{MTL_ARCHIVE_FILE_PREFIX}{cache_hash:016x}{MTL_ARCHIVE_FILE_SUFFIX}"
))
.to_string_lossy()
.into_owned();
let existed: bool = fs::metadata(&archive_path).is_ok();
let ns_path: *mut c_void = mtl_ns_string(&archive_path);
let url_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_NS_URL);
let ns_url: *mut c_void =
mtl_send_ptr1(url_cls, mtl_sel_cstr(MTL_SEL_FILE_URL_WITH_PATH), ns_path);
let arch_desc_alloc: *mut c_void = mtl_send_ptr0(arch_desc_cls, mtl_sel_cstr(MTL_SEL_ALLOC));
let arch_desc: *mut c_void = mtl_send_ptr0(arch_desc_alloc, mtl_sel_cstr(MTL_SEL_INIT));
if arch_desc.is_null() {
return (null_mut(), ns_url, existed);
}
if existed && !ns_url.is_null() {
mtl_send_void_ptr1(arch_desc, mtl_sel_cstr(MTL_SEL_SET_URL), ns_url);
}
let mut err_ptr: *mut c_void = null_mut();
let archive: *mut c_void = unsafe {
let send_new: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
send_new(
device,
mtl_sel_cstr(MTL_SEL_NEW_BINARY_ARCHIVE),
arch_desc,
&mut err_ptr,
)
};
mtl_send_void0(arch_desc, mtl_sel_cstr(MTL_SEL_RELEASE));
(archive, ns_url, existed)
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn probe_apple_metal_full(backend: GraphicsBackend) -> NativeGpuProbeOutput {
let cached: &MetalSharedPipelineCache = METAL_SHARED_PIPELINE.get_or_init(|| {
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let result: MetalSharedPipelineCache = unsafe {
let device: *mut c_void = MTLCreateSystemDefaultDevice();
if device.is_null() {
MetalSharedPipelineCache {
adapter: GpuAdapterInfo::new(
backend,
GPU_DEVICE_FALLBACK.to_string(),
false,
false,
),
device: 0,
queue: 0,
library: 0,
pipeline: 0,
blur_pipeline: 0,
dummy_r8_tex: 0,
dummy_rgba8_tex: 0,
}
} else {
let ns_name: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NAME));
let utf8_ptr: *const c_char =
mtl_send_ptr0(ns_name, mtl_sel_cstr(MTL_SEL_UTF8_STRING)).cast::<c_char>();
let device_name: String = if utf8_ptr.is_null() {
GPU_DEVICE_APPLE_METAL.to_string()
} else {
CStr::from_ptr(utf8_ptr).to_string_lossy().into_owned()
};
let queue: *mut c_void = mtl_send_ptr0(device, mtl_sel_cstr(MTL_SEL_NEW_CMD_QUEUE));
let (archive, archive_url, archive_existed): (*mut c_void, *mut c_void, bool) =
metal_open_binary_archive(device, &device_name);
let send_lib: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
let mut err_ptr: *mut c_void = null_mut();
let library: *mut c_void = send_lib(
device,
mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
mtl_ns_string(MSL_UI_SHADER),
null_mut(),
&mut err_ptr,
);
let (pipeline, ui_fns_ok): (usize, bool) = metal_build_render_pipeline(
device,
library,
MTL_FN_VERTEX,
MTL_FN_FRAGMENT,
archive,
true,
);
let mut blur_err: *mut c_void = null_mut();
let blur_lib: *mut c_void = send_lib(
device,
mtl_sel_cstr(MTL_SEL_NEW_LIBRARY),
mtl_ns_string(MSL_BACKDROP_BLUR_SHADER),
null_mut(),
&mut blur_err,
);
let (blur_pipeline, _): (usize, bool) = metal_build_render_pipeline(
device,
blur_lib,
MTL_FN_BLUR_VERTEX,
MTL_FN_BLUR_DOWN,
archive,
false,
);
let (blur_up_pipeline, _): (usize, bool) = metal_build_render_pipeline(
device,
blur_lib,
MTL_FN_BLUR_VERTEX,
MTL_FN_BLUR_UP,
archive,
false,
);
if blur_up_pipeline != 0 {
mtl_send_void0(
blur_up_pipeline as *mut c_void,
mtl_sel_cstr(MTL_SEL_RELEASE),
);
}
if !blur_lib.is_null() {
mtl_send_void0(blur_lib, mtl_sel_cstr(MTL_SEL_RELEASE));
}
if !archive.is_null() {
if !archive_existed && !archive_url.is_null() && pipeline != 0 {
let mut ser_err: *mut c_void = null_mut();
let send_ser: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
*mut *mut c_void,
) -> i8 = transmute(objc_msgSend as *const c_void);
let _: i8 = send_ser(
archive,
mtl_sel_cstr(MTL_SEL_SERIALIZE_TO_URL),
archive_url,
&mut ser_err,
);
}
mtl_send_void0(archive, mtl_sel_cstr(MTL_SEL_RELEASE));
}
let dummy_r8_tex: usize =
metal_create_texture(device, GpuAtlasPixelFormat::R8Unorm, 1, 1);
let dummy_rgba8_tex: usize =
metal_create_texture(device, GpuAtlasPixelFormat::Rgba8Unorm, 1, 1);
let shader_compiled: bool = ui_fns_ok && pipeline != 0;
MetalSharedPipelineCache {
adapter: GpuAdapterInfo::new(
GraphicsBackend::Metal,
device_name,
!queue.is_null(),
shader_compiled,
),
device: device as usize,
queue: queue as usize,
library: library as usize,
pipeline,
blur_pipeline,
dummy_r8_tex,
dummy_rgba8_tex,
}
}
};
unsafe { objc_autoreleasePoolPop(pool) };
result
});
NativeGpuProbeOutput {
adapter: cached.adapter.clone(),
device_handle: mtl_retain_handle(cached.device),
queue_handle: mtl_retain_handle(cached.queue),
library_handle: mtl_retain_handle(cached.library),
pipeline_handle: mtl_retain_handle(cached.pipeline),
blur_pipeline_handle: mtl_retain_handle(cached.blur_pipeline),
dummy_r8_tex: mtl_retain_handle(cached.dummy_r8_tex),
dummy_rgba8_tex: mtl_retain_handle(cached.dummy_rgba8_tex),
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn cached_metal_selectors() -> &'static MetalSelectors {
METAL_SELECTORS.get_or_init(|| MetalSelectors {
retain: mtl_sel_cstr(MTL_SEL_RETAIN) as usize,
new_buffer_with_bytes: mtl_sel_cstr(MTL_SEL_NEW_BUFFER) as usize,
new_buffer_with_length: mtl_sel_cstr(MTL_SEL_NEW_BUFFER_LENGTH) as usize,
contents: mtl_sel_cstr(MTL_SEL_CONTENTS) as usize,
command_buffer: mtl_sel_cstr(MTL_SEL_CMD_BUFFER) as usize,
render_encoder: mtl_sel_cstr(MTL_SEL_RENDER_ENCODER) as usize,
set_pipeline_state: mtl_sel_cstr(MTL_SEL_SET_PIPELINE_STATE) as usize,
set_vertex_buffer: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BUFFER) as usize,
set_vertex_bytes: mtl_sel_cstr(MTL_SEL_SET_VERTEX_BYTES) as usize,
set_fragment_texture: mtl_sel_cstr(MTL_SEL_SET_FRAGMENT_TEXTURE) as usize,
set_scissor_rect: mtl_sel_cstr(MTL_SEL_SET_SCISSOR_RECT) as usize,
draw_primitives_instanced: mtl_sel_cstr(MTL_SEL_DRAW_PRIMITIVES_INSTANCED) as usize,
end_encoding: mtl_sel_cstr(MTL_SEL_END_ENCODING) as usize,
present_drawable: mtl_sel_cstr(MTL_SEL_PRESENT_DRAWABLE) as usize,
add_presented_handler: mtl_sel_cstr(MTL_SEL_ADD_PRESENTED_HANDLER) as usize,
add_completed_handler: mtl_sel_cstr(MTL_SEL_ADD_COMPLETED_HANDLER) as usize,
presented_time: mtl_sel_cstr(MTL_SEL_PRESENTED_TIME) as usize,
responds_to_sel: mtl_sel_cstr(MTL_SEL_RESPONDS_TO_SEL) as usize,
status: mtl_sel_cstr(MTL_SEL_STATUS) as usize,
wait_until_completed: mtl_sel_cstr(MTL_SEL_WAIT_UNTIL_COMPLETED) as usize,
gpu_start_time: mtl_sel_cstr(MTL_SEL_GPU_START_TIME) as usize,
gpu_end_time: mtl_sel_cstr(MTL_SEL_GPU_END_TIME) as usize,
next_drawable: mtl_sel_cstr(MTL_SEL_NEXT_DRAWABLE) as usize,
texture: mtl_sel_cstr(MTL_SEL_TEXTURE) as usize,
width: mtl_sel_cstr(MTL_SEL_WIDTH) as usize,
height: mtl_sel_cstr(MTL_SEL_HEIGHT) as usize,
render_pass_desc: mtl_sel_cstr(MTL_SEL_RENDER_PASS_DESC) as usize,
color_attachments: mtl_sel_cstr(MTL_SEL_COLOR_ATTACHMENTS) as usize,
object_at_index: mtl_sel_cstr(MTL_SEL_OBJECT_AT_INDEX) as usize,
set_texture: mtl_sel_cstr(MTL_SEL_SET_TEXTURE) as usize,
set_load_action: mtl_sel_cstr(MTL_SEL_SET_LOAD_ACTION) as usize,
set_store_action: mtl_sel_cstr(MTL_SEL_SET_STORE_ACTION) as usize,
set_clear_color: mtl_sel_cstr(MTL_SEL_SET_CLEAR_COLOR) as usize,
replace_region: mtl_sel_cstr(MTL_SEL_REPLACE_REGION) as usize,
commit: mtl_sel_cstr(MTL_SEL_COMMIT) as usize,
release: mtl_sel_cstr(MTL_SEL_RELEASE) as usize,
})
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_configure_layer(device_handle: usize, layer_handle: usize) {
if device_handle == 0 || layer_handle == 0 {
return;
}
let layer: *mut c_void = layer_handle as *mut c_void;
mtl_send_void_ptr1(
layer,
mtl_sel_cstr(MTL_SEL_SET_DEVICE),
device_handle as *mut c_void,
);
mtl_send_void_usize(
layer,
mtl_sel_cstr(MTL_SEL_SET_PIXEL_FORMAT),
MTL_PIXEL_FORMAT_BGRA8_UNORM,
);
mtl_send_void_bool(layer, mtl_sel_cstr(MTL_SEL_SET_FRAMEBUFFER_ONLY), true);
let sel_max: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_MAX_DRAWABLE_COUNT);
if mtl_responds_to_sel(layer, sel_max) {
mtl_send_void_usize(layer, sel_max, GPU_DRIVER_RING_SLOTS);
}
let sel_sync: *mut c_void = mtl_sel_cstr(MTL_SEL_SET_DISPLAY_SYNC);
if mtl_responds_to_sel(layer, sel_sync) {
mtl_send_void_bool(layer, sel_sync, true);
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_upload_texture_dirty_rect(
device_handle: usize,
texture_handle: &mut usize,
format: GpuAtlasPixelFormat,
tex_dims: (u32, u32),
dirty_rect: (u32, u32, u32, u32),
bytes: &[u8],
bytes_per_row: usize,
) -> bool {
if device_handle == 0 || dirty_rect.2 == 0 || dirty_rect.3 == 0 || bytes.is_empty() {
return false;
}
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let (tex_w, tex_h): (u32, u32) = (tex_dims.0.max(1), tex_dims.1.max(1));
let sel: &MetalSelectors = cached_metal_selectors();
let cur_w: usize = if *texture_handle != 0 {
mtl_send_usize0(*texture_handle as *mut c_void, sel.width as *mut c_void)
} else {
0
};
let cur_h: usize = if *texture_handle != 0 {
mtl_send_usize0(*texture_handle as *mut c_void, sel.height as *mut c_void)
} else {
0
};
if *texture_handle == 0 || cur_w != tex_w as usize || cur_h != tex_h as usize {
if *texture_handle != 0 {
mtl_send_void0(*texture_handle as *mut c_void, sel.release as *mut c_void);
}
*texture_handle = metal_create_texture(device_handle as *mut c_void, format, tex_w, tex_h);
}
if *texture_handle == 0 {
unsafe { objc_autoreleasePoolPop(pool) };
return false;
}
let region: MtlRegion = MtlRegion {
origin: MtlOrigin {
x: dirty_rect.0 as usize,
y: dirty_rect.1 as usize,
z: 0,
},
size: MtlSize {
width: dirty_rect.2 as usize,
height: dirty_rect.3 as usize,
depth: 1,
},
};
unsafe {
let send_replace: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
MtlRegion,
usize,
*const c_void,
usize,
) = transmute(objc_msgSend as *const c_void);
send_replace(
*texture_handle as *mut c_void,
sel.replace_region as *mut c_void,
region,
0,
bytes.as_ptr().cast::<c_void>(),
bytes_per_row,
);
objc_autoreleasePoolPop(pool);
}
true
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_submit_ring_frame(
driver: &mut NativeGpuDriver,
width: u32,
height: u32,
clear_color: Color,
batches: &[GpuBatch],
) -> usize {
let total_instances: usize = batches
.iter()
.map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
.sum();
let device_handle: usize = driver.get_device_handle();
let queue_handle: usize = driver.get_queue_handle();
if device_handle == 0 || queue_handle == 0 {
return total_instances;
}
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let sel: &MetalSelectors = cached_metal_selectors();
let sel_rel: *mut c_void = sel.release as *mut c_void;
let slot_idx: usize = driver.get_ring_cursor() % GPU_DRIVER_RING_SLOTS;
let device: *mut c_void = device_handle as *mut c_void;
let queue: *mut c_void = queue_handle as *mut c_void;
let pipeline: *mut c_void = driver.get_pipeline_handle() as *mut c_void;
let layer_ptr: *mut c_void = driver.get_surface_layer_handle() as *mut c_void;
let tex_r8: *mut c_void = driver.get_glyph_r8_texture_handle() as *mut c_void;
let tex_rgba8: *mut c_void = driver.get_glyph_rgba8_texture_handle() as *mut c_void;
let tex_img: *mut c_void = driver.get_image_texture_handle() as *mut c_void;
let raw_ext: usize = driver.get_external_texture_handle();
let tex_ext: *mut c_void = if raw_ext != 0 {
raw_ext as *mut c_void
} else {
tex_rgba8
};
let total_bytes: usize = total_instances.saturating_mul(size_of::<GpuPrimitiveInstance>());
let NativeGpuDriver {
ring_slots,
ring_cursor,
staging_buffer_handle,
staging_contents_ptr,
staging_buffer_capacity,
staging_reallocations,
scratch_primitives,
..
} = driver;
let slot: &mut NativeGpuRingSlot = &mut ring_slots[slot_idx];
let prev_cmd: usize = slot.get_in_flight_cmd_buffer();
if prev_cmd != 0 {
let status: usize = mtl_send_usize0(prev_cmd as *mut c_void, sel.status as *mut c_void);
if status < MTL_CMD_BUFFER_STATUS_COMPLETED {
mtl_send_void0(
prev_cmd as *mut c_void,
sel.wait_until_completed as *mut c_void,
);
}
mtl_send_void0(prev_cmd as *mut c_void, sel_rel);
slot.set_in_flight_cmd_buffer(0);
}
if total_bytes > 0
&& (slot.get_buffer_handle() == 0
|| slot.get_contents_ptr() == 0
|| total_bytes > slot.get_capacity_bytes())
{
if slot.get_buffer_handle() != 0 {
mtl_send_void0(slot.get_buffer_handle() as *mut c_void, sel_rel);
slot.set_buffer_handle(0);
slot.set_contents_ptr(0);
slot.set_capacity_bytes(0);
}
let alloc_bytes: usize = total_bytes.max(4096).next_power_of_two();
unsafe {
let send_new_len: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
let new_buf: *mut c_void = send_new_len(
device,
sel.new_buffer_with_length as *mut c_void,
alloc_bytes,
0,
);
if !new_buf.is_null() {
let ptr: *mut c_void = mtl_send_ptr0(new_buf, sel.contents as *mut c_void);
if !ptr.is_null() {
slot.set_buffer_handle(new_buf as usize);
slot.set_contents_ptr(ptr as usize);
slot.set_capacity_bytes(alloc_bytes);
*staging_reallocations = staging_reallocations.wrapping_add(1);
} else {
mtl_send_void0(new_buf, sel_rel);
}
}
}
}
let buf_handle: usize = slot.get_buffer_handle();
let contents_ptr: usize = slot.get_contents_ptr();
let capacity_bytes: usize = slot.get_capacity_bytes();
*staging_buffer_handle = buf_handle;
*staging_contents_ptr = contents_ptr;
*staging_buffer_capacity = capacity_bytes;
if contents_ptr != 0 && total_bytes > 0 && total_bytes <= capacity_bytes {
unsafe {
let mut dst: *mut u8 = (contents_ptr as *mut c_void).cast::<u8>();
for batch in batches.iter() {
let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
if !prims.is_empty() {
let byte_len: usize = size_of_val(prims);
dst.copy_from_nonoverlapping(prims.as_ptr().cast::<u8>(), byte_len);
dst = dst.add(byte_len);
} else if !batch.get_instances().is_empty() {
scratch_primitives.clear();
for quad in batch.get_instances().iter() {
scratch_primitives.push(GpuPrimitiveInstance::from_quad_instance(
quad,
batch.get_texture_slot(),
batch.get_layer_id(),
));
}
let byte_len: usize = size_of_val(scratch_primitives.as_slice());
dst.copy_from_nonoverlapping(
scratch_primitives.as_ptr().cast::<u8>(),
byte_len,
);
dst = dst.add(byte_len);
}
}
}
}
let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
if !cmd_buf.is_null() {
let sel_completed: *mut c_void = sel.add_completed_handler as *mut c_void;
if mtl_responds_to_sel(cmd_buf, sel_completed) {
mtl_send_void_ptr1(cmd_buf, sel_completed, metal_completed_block_ptr());
}
if !layer_ptr.is_null() && !pipeline.is_null() {
let drawable: *mut c_void = mtl_send_ptr0(layer_ptr, sel.next_drawable as *mut c_void);
if !drawable.is_null() {
let drawable_tex: *mut c_void = mtl_send_ptr0(drawable, sel.texture as *mut c_void);
let pass_cls: *mut c_void = mtl_cls_cstr(MTL_CLS_PASS_DESC);
let pass_desc: *mut c_void =
mtl_send_ptr0(pass_cls, sel.render_pass_desc as *mut c_void);
if !drawable_tex.is_null() && !pass_desc.is_null() {
let draw_w: usize = mtl_send_usize0(drawable_tex, sel.width as *mut c_void)
.max(width.max(1) as usize);
let draw_h: usize = mtl_send_usize0(drawable_tex, sel.height as *mut c_void)
.max(height.max(1) as usize);
let color_atts: *mut c_void =
mtl_send_ptr0(pass_desc, sel.color_attachments as *mut c_void);
let att0: *mut c_void = unsafe {
let send_idx: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
send_idx(color_atts, sel.object_at_index as *mut c_void, 0)
};
if !att0.is_null() {
mtl_send_void_ptr1(att0, sel.set_texture as *mut c_void, drawable_tex);
mtl_send_void_usize(
att0,
sel.set_load_action as *mut c_void,
MTL_LOAD_ACTION_CLEAR,
);
mtl_send_void_usize(
att0,
sel.set_store_action as *mut c_void,
MTL_STORE_ACTION_STORE,
);
let clear_rgba: [f32; 4] = clear_color.to_f32_array();
let mtl_clear: MtlClearColor = MtlClearColor {
red: clear_rgba[0] as f64,
green: clear_rgba[1] as f64,
blue: clear_rgba[2] as f64,
alpha: clear_rgba[3] as f64,
};
unsafe {
let send_clear: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
MtlClearColor,
) = transmute(objc_msgSend as *const c_void);
send_clear(att0, sel.set_clear_color as *mut c_void, mtl_clear);
}
}
let encoder: *mut c_void =
mtl_send_ptr1(cmd_buf, sel.render_encoder as *mut c_void, pass_desc);
if !encoder.is_null() {
mtl_send_void_ptr1(
encoder,
sel.set_pipeline_state as *mut c_void,
pipeline,
);
unsafe {
let send_vbuf: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
let send_vbytes: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*const c_void,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
let send_ftex: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*mut c_void,
usize,
) = transmute(objc_msgSend as *const c_void);
let send_scissor: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
MtlScissorRect,
) = transmute(objc_msgSend as *const c_void);
let send_draw: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
usize,
usize,
usize,
usize,
usize,
) = transmute(objc_msgSend as *const c_void);
if buf_handle != 0 {
send_vbuf(
encoder,
sel.set_vertex_buffer as *mut c_void,
buf_handle as *mut c_void,
0,
0,
);
}
if !tex_r8.is_null() {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
tex_r8,
0,
);
}
if !tex_rgba8.is_null() {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
tex_rgba8,
1,
);
}
if !tex_img.is_null() {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
tex_img,
2,
);
}
if !tex_ext.is_null() {
send_ftex(
encoder,
sel.set_fragment_texture as *mut c_void,
tex_ext,
3,
);
}
let mut base_instance: usize = 0;
for batch in batches.iter() {
let count: usize = batch
.get_primitives()
.len()
.max(batch.get_instances().len());
if count == 0 || buf_handle == 0 {
continue;
}
let uniform: GpuLayerUniform = GpuLayerUniform::new(
draw_w as f32,
draw_h as f32,
batch.get_scroll_offset(),
);
send_vbytes(
encoder,
sel.set_vertex_bytes as *mut c_void,
(&uniform as *const GpuLayerUniform).cast::<c_void>(),
size_of::<GpuLayerUniform>(),
1,
);
let sc: Rect = batch.get_scissor();
let sx: usize = (sc.get_x().max(0.0).floor() as usize)
.min(draw_w.saturating_sub(1));
let sy: usize = (sc.get_y().max(0.0).floor() as usize)
.min(draw_h.saturating_sub(1));
let sw: usize = (sc.get_width().max(1.0).ceil() as usize)
.min(draw_w.saturating_sub(sx))
.max(1);
let sh: usize = (sc.get_height().max(1.0).ceil() as usize)
.min(draw_h.saturating_sub(sy))
.max(1);
send_scissor(
encoder,
sel.set_scissor_rect as *mut c_void,
MtlScissorRect {
x: sx,
y: sy,
width: sw,
height: sh,
},
);
send_draw(
encoder,
sel.draw_primitives_instanced as *mut c_void,
MTL_PRIMITIVE_TYPE_TRIANGLE,
0,
6,
count,
base_instance,
);
base_instance = base_instance.saturating_add(count);
}
}
mtl_send_void0(encoder, sel.end_encoding as *mut c_void);
}
let sel_pres: *mut c_void = sel.add_presented_handler as *mut c_void;
if mtl_responds_to_sel(drawable, sel_pres) {
mtl_send_void_ptr1(drawable, sel_pres, metal_presented_block_ptr());
}
mtl_send_void_ptr1(cmd_buf, sel.present_drawable as *mut c_void, drawable);
}
}
}
let retained_cmd: usize = mtl_retain_handle(cmd_buf as usize);
slot.set_in_flight_cmd_buffer(retained_cmd);
mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
}
*ring_cursor = (slot_idx + 1) % GPU_DRIVER_RING_SLOTS;
unsafe { objc_autoreleasePoolPop(pool) };
total_instances
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_submit_batches(device_handle: usize, queue_handle: usize, batches: &[GpuBatch]) -> usize {
let total_instances: usize = batches
.iter()
.map(|b: &GpuBatch| b.get_primitives().len().max(b.get_instances().len()))
.sum();
if device_handle == 0 || queue_handle == 0 || total_instances == 0 {
return total_instances;
}
let pool: *mut c_void = unsafe { objc_autoreleasePoolPush() };
let device: *mut c_void = device_handle as *mut c_void;
let queue: *mut c_void = queue_handle as *mut c_void;
let sel: &MetalSelectors = cached_metal_selectors();
let sel_buf: *mut c_void = sel.new_buffer_with_bytes as *mut c_void;
let sel_rel: *mut c_void = sel.release as *mut c_void;
unsafe {
let send_buf: unsafe extern "C" fn(
*mut c_void,
*mut c_void,
*const c_void,
usize,
usize,
) -> *mut c_void = transmute(objc_msgSend as *const c_void);
for batch in batches.iter() {
let prims: &[GpuPrimitiveInstance] = batch.get_primitives();
if !prims.is_empty() {
let byte_len: usize = size_of_val(prims);
let mtl_buf: *mut c_void = send_buf(
device,
sel_buf,
prims.as_ptr().cast::<c_void>(),
byte_len,
0,
);
if !mtl_buf.is_null() {
mtl_send_void0(mtl_buf, sel_rel);
}
} else {
let instances: &[GpuQuadInstance] = batch.get_instances();
if instances.is_empty() {
continue;
}
let byte_len: usize = size_of_val(instances);
let mtl_buf: *mut c_void = send_buf(
device,
sel_buf,
instances.as_ptr().cast::<c_void>(),
byte_len,
0,
);
if !mtl_buf.is_null() {
mtl_send_void0(mtl_buf, sel_rel);
}
}
}
let cmd_buf: *mut c_void = mtl_send_ptr0(queue, sel.command_buffer as *mut c_void);
if !cmd_buf.is_null() {
mtl_send_void0(cmd_buf, sel.commit as *mut c_void);
}
objc_autoreleasePoolPop(pool);
}
total_instances
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_release_handles(device_handle: usize, queue_handle: usize, library_handle: usize) {
let sel_rel: *mut c_void = cached_metal_selectors().release as *mut c_void;
if library_handle != 0 {
mtl_send_void0(library_handle as *mut c_void, sel_rel);
}
if queue_handle != 0 {
mtl_send_void0(queue_handle as *mut c_void, sel_rel);
}
if device_handle != 0 {
mtl_send_void0(device_handle as *mut c_void, sel_rel);
}
}
#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut c_void;
fn GetProcAddress(h_module: *mut c_void, lp_proc_name: *const u8) -> *mut c_void;
}
#[cfg(target_os = "windows")]
fn probe_windows_d3d12(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
let cached: &WindowsD3d12ProbeCache = WINDOWS_D3D12_CACHE.get_or_init(|| unsafe {
let d3d12_mod: *mut c_void = LoadLibraryA(DLL_D3D12.as_ptr());
let has_d3d12: bool = if !d3d12_mod.is_null() {
!GetProcAddress(d3d12_mod, SYM_D3D12_CREATE_DEVICE.as_ptr()).is_null()
} else {
false
};
let compiler_mod: *mut c_void = LoadLibraryA(DLL_D3DCOMPILER.as_ptr());
let has_compiler: bool = if !compiler_mod.is_null() {
!GetProcAddress(compiler_mod, SYM_D3D_COMPILE.as_ptr()).is_null()
} else {
false
};
WindowsD3d12ProbeCache {
has_d3d12,
has_compiler,
}
});
let label: &str = if cached.has_d3d12 {
GPU_DEVICE_D3D12
} else {
GPU_DEVICE_FALLBACK
};
(
GpuAdapterInfo::new(
backend,
label.to_string(),
cached.has_d3d12,
cached.has_compiler,
),
0,
0,
0,
)
}
#[cfg(any(target_os = "linux", target_os = "android"))]
unsafe extern "C" {
fn dlopen(filename: *const c_char, flags: i32) -> *mut c_void;
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn probe_vulkan_runtime(backend: GraphicsBackend) -> (GpuAdapterInfo, usize, usize, usize) {
let cached: &VulkanProbeCache = VULKAN_PROBE_CACHE.get_or_init(|| {
let Ok(lib_name) = CString::new(LIB_VULKAN_SONAME) else {
return VulkanProbeCache {
available: false,
lib_handle: 0,
};
};
let Ok(sym_create) = CString::new(SYM_VK_CREATE_INSTANCE) else {
return VulkanProbeCache {
available: false,
lib_handle: 0,
};
};
let Ok(sym_enum) = CString::new(SYM_VK_ENUM_DEVICES) else {
return VulkanProbeCache {
available: false,
lib_handle: 0,
};
};
unsafe {
let handle: *mut c_void = dlopen(lib_name.as_ptr(), RTLD_LAZY_GPU);
if handle.is_null() {
VulkanProbeCache {
available: false,
lib_handle: 0,
}
} else {
let p1: *mut c_void = dlsym(handle, sym_create.as_ptr());
let p2: *mut c_void = dlsym(handle, sym_enum.as_ptr());
VulkanProbeCache {
available: !p1.is_null() && !p2.is_null(),
lib_handle: handle as usize,
}
}
}
});
let name: &str = if cached.available {
GPU_DEVICE_VULKAN
} else {
GPU_DEVICE_FALLBACK
};
(
GpuAdapterInfo::new(
backend,
name.to_string(),
cached.available,
cached.available,
),
cached.lib_handle,
0,
0,
)
}
#[cfg(target_arch = "wasm32")]
pub fn webgl2_compile_ui_program(gl: &WebGl2RenderingContext) -> Option<WebGlProgram> {
let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
gl.shader_source(&vs, GLSL_ES3_UI_VERTEX_SHADER);
gl.compile_shader(&vs);
let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
gl.shader_source(&fs, GLSL_ES3_UI_FRAGMENT_SHADER);
gl.compile_shader(&fs);
let program: WebGlProgram = gl.create_program()?;
gl.attach_shader(&program, &vs);
gl.attach_shader(&program, &fs);
gl.link_program(&program);
Some(program)
}