use std::ffi::c_void;
use super::enums::*;
use super::objc::{
error_message, msg0, msg1, msg2, msg3, nsstring, nsstring_to_string, sel, AutoreleasePool, Bool,
Id, Owned, NIL,
};
#[cfg(metal_backend)]
use super::objc::{alloc_init, class, YES};
#[link(name = "Metal", kind = "framework")]
unsafe extern "C" {
fn MTLCreateSystemDefaultDevice() -> Id;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetalError {
NoDevice,
NoCommandQueue,
ShaderCompilation(String),
MissingFunction(String),
PipelineCreation(String),
Allocation(String),
Unsupported(String),
CommandBuffer(String),
}
impl std::fmt::Display for MetalError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NoDevice => write!(f, "no Metal device available"),
Self::NoCommandQueue => write!(f, "could not create a Metal command queue"),
Self::ShaderCompilation(m) => write!(f, "Metal shader compilation failed: {m}"),
Self::MissingFunction(n) => write!(f, "shader function `{n}` not found in library"),
Self::PipelineCreation(m) => write!(f, "Metal pipeline creation failed: {m}"),
Self::Allocation(m) => write!(f, "Metal allocation failed: {m}"),
Self::Unsupported(m) => write!(f, "unsupported by the Metal backend: {m}"),
Self::CommandBuffer(m) => write!(f, "Metal command buffer failed: {m}"),
}
}
}
impl std::error::Error for MetalError {}
#[derive(Clone)]
pub struct MetalDevice {
device: Owned,
queue: Owned,
library: Owned,
source: std::sync::Arc<str>,
}
unsafe impl Send for MetalDevice {}
unsafe impl Sync for MetalDevice {}
impl MetalDevice {
pub fn new() -> Result<Self, MetalError> {
Self::with_shader_source(super::shader_source())
}
pub fn with_shader_source(source: &str) -> Result<Self, MetalError> {
let _pool = AutoreleasePool::new();
let device = unsafe { Owned::from_retained(MTLCreateSystemDefaultDevice()) }
.ok_or(MetalError::NoDevice)?;
unsafe { Self::build(device, source) }
}
pub unsafe fn adopt(device: Id) -> Result<Self, MetalError> {
let _pool = AutoreleasePool::new();
let device = unsafe { Owned::retain(device) }.ok_or(MetalError::NoDevice)?;
unsafe { Self::build(device, super::shader_source()) }
}
pub unsafe fn adopt_with_shader_source(device: Id, source: &str) -> Result<Self, MetalError> {
let _pool = AutoreleasePool::new();
let device = unsafe { Owned::retain(device) }.ok_or(MetalError::NoDevice)?;
unsafe { Self::build(device, source) }
}
unsafe fn build(device: Owned, source: &str) -> Result<Self, MetalError> {
let queue = unsafe { Owned::from_retained(msg0(device.id(), sel!("newCommandQueue"))) }
.ok_or(MetalError::NoCommandQueue)?;
let library = unsafe { compile_library(device.id(), source) }?;
Ok(Self {
device,
queue,
library,
source: source.into(),
})
}
#[inline]
pub fn device_id(&self) -> Id {
self.device.id()
}
#[inline]
pub fn queue_id(&self) -> Id {
self.queue.id()
}
pub fn shader_source(&self) -> &str {
&self.source
}
#[inline]
pub fn library_id(&self) -> Id {
self.library.id()
}
pub fn name(&self) -> String {
let _pool = AutoreleasePool::new();
unsafe { nsstring_to_string(msg0(self.device.id(), sel!("name"))) }
.unwrap_or_else(|| "unknown".into())
}
pub fn has_unified_memory(&self) -> bool {
let has: Bool = unsafe { msg0(self.device.id(), sel!("hasUnifiedMemory")) };
has != 0
}
pub fn supports_sample_count(&self, sample_count: u32) -> bool {
let ok: Bool = unsafe {
msg1(
self.device.id(),
sel!("supportsTextureSampleCount:"),
sample_count as NSUInteger,
)
};
ok != 0
}
pub fn function(&self, name: &str) -> Result<Owned, MetalError> {
let _pool = AutoreleasePool::new();
unsafe {
let ns = nsstring(name);
let f: Id = msg1(self.library.id(), sel!("newFunctionWithName:"), ns);
Owned::from_retained(f).ok_or_else(|| MetalError::MissingFunction(name.into()))
}
}
pub fn new_buffer(&self, bytes: &[u8]) -> Result<Owned, MetalError> {
let len = bytes.len().max(1) as NSUInteger;
unsafe {
let buf: Id = if bytes.is_empty() {
msg2(
self.device.id(),
sel!("newBufferWithLength:options:"),
len,
resource_options::STORAGE_MODE_SHARED,
)
} else {
msg3(
self.device.id(),
sel!("newBufferWithBytes:length:options:"),
bytes.as_ptr() as *const c_void,
len,
resource_options::STORAGE_MODE_SHARED,
)
};
Owned::from_retained(buf)
.ok_or_else(|| MetalError::Allocation(format!("buffer of {len} bytes")))
}
}
pub fn command_buffer(&self) -> Id {
unsafe { msg0(self.queue.id(), sel!("commandBuffer")) }
}
pub unsafe fn set_label(obj: Id, label: &str) {
let _pool = AutoreleasePool::new();
let _: () = unsafe { msg1(obj, sel!("setLabel:"), nsstring(label)) };
}
}
impl std::fmt::Debug for MetalDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MetalDevice")
.field("name", &self.name())
.field("unified_memory", &self.has_unified_memory())
.finish()
}
}
#[cfg(metal_backend)]
const COMMAND_BUFFER_STATUS_ERROR: NSUInteger = 5;
#[cfg(metal_backend)]
pub(crate) unsafe fn wait_until_completed(cmd: Id) -> Result<(), MetalError> {
let _pool = AutoreleasePool::new();
let _: () = unsafe { msg0(cmd, sel!("waitUntilCompleted")) };
let status: NSUInteger = unsafe { msg0(cmd, sel!("status")) };
if status == COMMAND_BUFFER_STATUS_ERROR {
return Err(MetalError::CommandBuffer(unsafe {
error_message(msg0(cmd, sel!("error")))
}));
}
Ok(())
}
pub(crate) unsafe fn compile_library(device: Id, source: &str) -> Result<Owned, MetalError> {
let src = nsstring(source);
if src.is_null() {
return Err(MetalError::ShaderCompilation(
"shader source contains an interior NUL byte".into(),
));
}
let mut err: Id = NIL;
let lib: Id = unsafe {
msg3(
device,
sel!("newLibraryWithSource:options:error:"),
src,
NIL, &mut err as *mut Id,
)
};
match unsafe { Owned::from_retained(lib) } {
Some(lib) => Ok(lib),
None => Err(MetalError::ShaderCompilation(unsafe { error_message(err) })),
}
}
#[cfg(metal_backend)]
pub fn depth_stencil_state(
device: &MetalDevice,
compare: NSUInteger,
write: bool,
) -> Result<Owned, MetalError> {
let _pool = AutoreleasePool::new();
unsafe {
let desc = alloc_init(class!("MTLDepthStencilDescriptor"));
let desc = Owned::from_retained(desc)
.ok_or_else(|| MetalError::Allocation("MTLDepthStencilDescriptor".into()))?;
let _: () = msg1(desc.id(), sel!("setDepthCompareFunction:"), compare);
let _: () = msg1(
desc.id(),
sel!("setDepthWriteEnabled:"),
if write { YES } else { 0 as Bool },
);
let state: Id = msg1(
device.device_id(),
sel!("newDepthStencilStateWithDescriptor:"),
desc.id(),
);
Owned::from_retained(state)
.ok_or_else(|| MetalError::Allocation("MTLDepthStencilState".into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_messages_name_the_stage() {
assert!(MetalError::NoDevice.to_string().contains("no Metal device"));
assert!(MetalError::ShaderCompilation("line 4: oops".into())
.to_string()
.contains("line 4: oops"));
assert!(MetalError::MissingFunction("vs_mesh".into())
.to_string()
.contains("vs_mesh"));
}
}