use std::ffi::c_void;
use super::enums::*;
use super::objc::{
alloc_init, class, error_message, msg0, msg1, msg2, msg3, nsstring, nsstring_to_string, sel,
AutoreleasePool, Bool, Id, Owned, NIL, YES,
};
#[link(name = "Metal", kind = "framework")]
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),
}
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}"),
}
}
}
impl std::error::Error for MetalError {}
#[derive(Clone)]
pub struct MetalDevice {
device: Owned,
queue: Owned,
library: Owned,
}
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 = Owned::retain(device).ok_or(MetalError::NoDevice)?;
Self::build(device, super::SHADER_SOURCE)
}
unsafe fn build(device: Owned, source: &str) -> Result<Self, MetalError> {
let queue = Owned::from_retained(msg0(device.id(), sel!("newCommandQueue")))
.ok_or(MetalError::NoCommandQueue)?;
let library = compile_library(device.id(), source)?;
Ok(Self {
device,
queue,
library,
})
}
#[inline]
pub fn device_id(&self) -> Id {
self.device.id()
}
#[inline]
pub fn queue_id(&self) -> Id {
self.queue.id()
}
#[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 unsafe fn command_buffer(&self) -> Id {
msg0(self.queue.id(), sel!("commandBuffer"))
}
pub unsafe fn set_label(obj: Id, label: &str) {
let _pool = AutoreleasePool::new();
let _: () = 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()
}
}
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 = msg3(
device,
sel!("newLibraryWithSource:options:error:"),
src,
NIL, &mut err as *mut Id,
);
match Owned::from_retained(lib) {
Some(lib) => Ok(lib),
None => Err(MetalError::ShaderCompilation(error_message(err))),
}
}
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"));
}
}