lactea-host 0.3.2

Host-side helpers for embedding lactea: directory texture provider, image decoding, headless GPU setup, non-blocking frame read-back, rendering on the host's own Vulkan or Metal device, WAV reading.
Documentation
//! Metal interop: run lactea on the host's own `MTLDevice` and render into host `MTLTexture`s.
//!
//! The Apple counterpart of [`crate::vulkan`]: wgpu cannot render into a texture of a device it does
//! not run on, so the engine runs on the host's device and command queue. Only raw Objective-C
//! object pointers cross this API, so the host may use any Metal binding (objc2, metal-rs, Swift
//! through the C API) or a wgpu of another major version (its `as_hal::<Metal>()` gives the
//! objects). lactea retains what it keeps and never owns more than those references.
//!
//! 1. [`open_device`] wraps the host's `id<MTLDevice>` and an `id<MTLCommandQueue>` of it as a
//!    `wgpu::Device` + `wgpu::Queue` for `lactea::Engine`.
//! 2. Every frame, [`wrap_texture`] turns the host's `id<MTLTexture>` into a `wgpu::Texture` to
//!    render into.
//!
//! Synchronisation: lactea commits its command buffers to the host's queue, so work the host
//! encodes on the same queue afterwards sees the finished frame (Metal orders command buffers of one
//! queue and tracks hazards of tracked resources). From another queue, wait for the frame first
//! (e.g. `Device::poll` with `wait_indefinitely`).
//!
//! Present on Apple targets.

use std::ffi::c_void;

use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_metal::{MTLCommandQueue, MTLDevice, MTLTexture, MTLTextureType};
use wgpu::hal::api::Metal;
use wgpu::hal::metal as hal;

/// `MTLPixelFormatRGBA8Unorm`.
pub const MTL_PIXEL_FORMAT_RGBA8_UNORM: u64 = 70;
/// `MTLPixelFormatBGRA8Unorm`.
pub const MTL_PIXEL_FORMAT_BGRA8_UNORM: u64 = 80;

/// The texture formats lactea renders into, by `MTLPixelFormat`; `None` for any other.
pub fn format_from_mtl(pixel_format: u64) -> Option<wgpu::TextureFormat> {
    match pixel_format {
        MTL_PIXEL_FORMAT_RGBA8_UNORM => Some(wgpu::TextureFormat::Rgba8Unorm),
        MTL_PIXEL_FORMAT_BGRA8_UNORM => Some(wgpu::TextureFormat::Bgra8Unorm),
        _ => None,
    }
}

/// The host's Metal objects, as `id` pointers.
#[derive(Clone, Copy, Debug)]
pub struct MetalHost {
    /// `id<MTLDevice>`.
    pub device: *mut c_void,
    /// `id<MTLCommandQueue>` of that device, which lactea commits to.
    pub command_queue: *mut c_void,
}

/// Retain the object behind `ptr`, `None` for nil.
///
/// # Safety
/// `ptr` is nil or a live Objective-C object conforming to `P`.
unsafe fn retain<P: ?Sized>(ptr: *mut c_void) -> Option<Retained<ProtocolObject<P>>> {
    unsafe { Retained::retain(ptr.cast::<ProtocolObject<P>>()) }
}

/// Wrap the host's device and queue as the device and queue to build a `lactea::Engine` on. Uses
/// wgpu's default limits and no optional features.
///
/// # Safety
/// `host.device` is an `id<MTLDevice>` and `host.command_queue` an `id<MTLCommandQueue>` created
/// from it (or nil, which is an error).
pub unsafe fn open_device(host: &MetalHost) -> Result<(wgpu::Device, wgpu::Queue), String> {
    let device = unsafe { retain::<dyn MTLDevice>(host.device) }.ok_or("device is nil")?;
    let queue = unsafe { retain::<dyn MTLCommandQueue>(host.command_queue) }
        .ok_or("command_queue is nil")?;
    let registry_id = device.registryID();
    if queue.device().registryID() != registry_id {
        return Err("command_queue belongs to another MTLDevice".into());
    }
    // wgpu-core opens devices through an adapter: take the one wgpu itself sees for this device.
    let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
        backends: wgpu::Backends::METAL,
        ..wgpu::InstanceDescriptor::new_without_display_handle()
    });
    let adapter = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::METAL))
        .into_iter()
        .find(|a| {
            unsafe { a.as_hal::<Metal>() }
                .is_some_and(|h| h.raw_device().registryID() == registry_id)
        })
        .ok_or("wgpu does not list this MTLDevice")?;
    let open = wgpu::hal::OpenDevice {
        device: unsafe {
            hal::Device::device_from_raw(device, wgpu::Features::empty(), &wgpu::Limits::default())
        },
        // The period only scales timestamp queries, which lactea does not use.
        queue: unsafe { hal::Queue::queue_from_raw(queue, 1.0) },
    };
    unsafe { adapter.create_device_from_hal::<Metal>(open, &wgpu::DeviceDescriptor::default()) }
        .map_err(|e| format!("create_device_from_hal: {e}"))
}

/// The host's `id<MTLTexture>` as a render attachment of `device`: a 2D texture of `width` x
/// `height`, one mip level, `format` one [`format_from_mtl`] accepts and the texture's own, usage
/// including `MTLTextureUsageRenderTarget`. Wrap it again for every frame and drop the result after
/// submitting; the contents are overwritten.
///
/// # Safety
/// `device` comes from [`open_device`]; `texture` is an `id<MTLTexture>` of that `MTLDevice`
/// matching the description above.
pub unsafe fn wrap_texture(
    device: &wgpu::Device,
    texture: *mut c_void,
    width: u32,
    height: u32,
    format: wgpu::TextureFormat,
) -> Result<wgpu::Texture, String> {
    let raw = unsafe { retain::<dyn MTLTexture>(texture) }.ok_or("texture is nil")?;
    let (w, h) = (raw.width(), raw.height());
    if (w, h) != (width as usize, height as usize) {
        return Err(format!(
            "the texture is {w}x{h}, the engine renders {width}x{height}"
        ));
    }
    if raw.textureType() != MTLTextureType::Type2D {
        return Err("the texture must be MTLTextureType2D".into());
    }
    let size = wgpu::Extent3d {
        width,
        height,
        depth_or_array_layers: 1,
    };
    let hal_texture = unsafe {
        hal::Device::texture_from_raw(
            raw,
            format,
            MTLTextureType::Type2D,
            1,
            1,
            wgpu::hal::CopyExtent {
                width,
                height,
                depth: 1,
            },
            None,
        )
    };
    Ok(unsafe {
        device.create_texture_from_hal::<Metal>(
            hal_texture,
            &wgpu::TextureDescriptor {
                label: Some("lactea host texture"),
                size,
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                view_formats: &[],
                texture_binding_view_dimension: None,
            },
            wgpu::TextureUses::UNINITIALIZED,
            true,
        )
    })
}