mln-rs-runtime 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! Direct3D 12 backend glue for targets, rings, surfaces, and devices.

use mln_gfx::{ExportKind, ExportedRing, RendererBackend as _, SyncKind, SyncKinds};
use mln_style::error::Error;

use crate::render::gfx_error;
use crate::render::local::{
    BackendRef, Borrowed, Exported, FramesInit, Gfx, LocalBackend, Target, gfx, no_surface, overlay_of,
};
use crate::render::target::{
    Adapter, BorrowedRing, DepthStencilFormat, Device, FrameDepth, FrameTexture, FrameTextureKind, NativeTexture,
    RingKind, Surface, SurfaceKind, SurfaceOverlay,
};

impl BorrowedRing {
    /// A ring of the host's D3D12 textures, of the D3D12 device that renders
    /// into them.
    #[must_use]
    pub fn d3d12(textures: mln_d3d12::BorrowedTextures) -> BorrowedRing {
        BorrowedRing { kind: RingKind::D3d12(textures) }
    }
}

impl Surface {
    /// A composition swap chain that a session on D3D12 makes and presents
    /// to, which `composition` shows: a `DirectComposition` visual shows it
    /// once the host commits its device after the attach, and a XAML
    /// `SwapChainPanel` at once. The composition must outlive the session's
    /// use of it, as a window must. The swap chain has the target's size in
    /// pixels, with premultiplied alpha; the host scales its visual for the
    /// display's scale factor.
    ///
    /// A `SwapChainPanel` takes its swap chain only on its UI thread: make
    /// the surface there, and attach it with
    /// [`Driver::CallerThread`](crate::Driver::CallerThread),
    /// serviced on that thread. A session that makes its swap chain on
    /// another thread fails with
    /// [`ErrorKind::Unsupported`](mln_style::error::ErrorKind).
    #[must_use]
    pub fn d3d12_composition(composition: mln_d3d12::Composition) -> Surface {
        Surface::of(SurfaceKind::D3d12Composition { composition, thread: std::thread::current().id() })
    }
}

pub(in super::super) fn native_texture(
    resource: u64,
    format: u32,
    state: u32,
    device: &mln_d3d12::Device,
) -> FrameTextureKind {
    use mln_d3d12::windows::core::Interface as _;
    FrameTextureKind::D3d12 { resource, device: device.device().as_raw() as usize as u64, format, state }
}

pub(in super::super) fn ring_depth_stencil_format(
    textures: &mln_d3d12::BorrowedTextures,
) -> Option<DepthStencilFormat> {
    textures.depth_format().and_then(mln_d3d12::depth_stencil_format)
}

pub(in super::super) fn ring_same_texture(
    textures: &mln_d3d12::BorrowedTextures,
    slot: usize,
    others: &mln_d3d12::BorrowedTextures,
    other_slot: usize,
) -> bool {
    textures.textures.get(slot).is_some_and(|texture| others.textures.get(other_slot) == Some(texture))
}

pub(in super::super) fn ring_texture(
    textures: &mln_d3d12::BorrowedTextures,
    slot: usize,
    device: &mln_d3d12::Device,
) -> Option<FrameTexture> {
    use mln_d3d12::windows::core::Interface as _;
    let depth = textures.depth_textures.get(slot).zip(textures.depth_format()).map(|(depth, format)| FrameDepth {
        texture: NativeTexture::D3d12 {
            resource: depth.as_raw() as usize as u64,
            format: format.0 as u32,
            state: textures.depth_state.0 as u32,
        },
        export: None,
    });
    textures.textures.get(slot).map(|texture| FrameTexture {
        size: textures.size,
        kind: FrameTextureKind::D3d12 {
            resource: texture.as_raw() as usize as u64,
            device: device.device().as_raw() as usize as u64,
            format: textures.format().0 as u32,
            state: textures.state.0 as u32,
        },
        native: None,
        depth,
    })
}

pub(in super::super) fn create_device(adapter: Option<Adapter>) -> Result<Device, Error> {
    match adapter {
        None => mln_d3d12::Device::new(None),
        Some(Adapter::Index(index)) => mln_d3d12::Device::new(Some(index)),
        Some(Adapter::Luid(luid)) => mln_d3d12::Device::with_luid(luid),
        Some(Adapter::Uuid(_)) => Err(mln_gfx::Error::unsupported("D3D12 names no GPU by UUID")),
    }
    .map(Device::D3d12)
    .map_err(gfx_error)
}

pub(in super::super) fn borrowed_sync_kinds(
    device: &mln_d3d12::Device,
    textures: &mln_d3d12::BorrowedTextures,
) -> Result<(SyncKinds, SyncKinds), Error> {
    textures.check(device).map_err(gfx_error)?;
    Ok(mln_d3d12::BorrowedTextures::sync_kinds())
}

pub(in super::super) fn export_plan(
    device: &mln_d3d12::Device,
    ring: &ExportedRing,
) -> Result<(ExportKind, SyncKinds, SyncKinds), Error> {
    let kind = mln_d3d12::exported_target::plan(device, ring).map_err(gfx_error)?;
    let (producer, consumer) = mln_d3d12::exported_target::sync_kinds();
    Ok((kind, producer, consumer))
}

impl LocalBackend for mln_d3d12::RendererBackend {
    type RingTextures = mln_d3d12::BorrowedTextures;

    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
        if let RingKind::D3d12(textures) = ring { Some(textures) } else { None }
    }

    fn by_type(&self) -> BackendRef<'_> {
        BackendRef::D3d12(self)
    }

    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
        Ok(Box::new(mln_d3d12::BorrowedTarget::new(self, textures, producer).map_err(gfx_error)?))
    }

    fn exported(
        &mut self,
        _device: &Device,
        ring: &ExportedRing,
        kind: ExportKind,
        size: mln_gfx::Size,
        producer: SyncKind,
    ) -> Result<Box<dyn Exported<Self>>, Error> {
        Ok(Box::new(mln_d3d12::ExportedTarget::new(self, ring, kind, size, producer).map_err(gfx_error)?))
    }

    fn surface(
        &mut self,
        surface: Surface,
        overlay: Option<SurfaceOverlay>,
        size: mln_gfx::Size,
    ) -> Result<Target<Self>, Error> {
        let overlay = || {
            overlay_of(overlay, |overlay| match overlay {
                SurfaceOverlay::D3d12(overlay) => Ok(overlay),
                other => Err(other),
            })
        };
        let (mut target, overlay) = match surface.kind {
            SurfaceKind::Window(window) => {
                let overlay = overlay()?;
                (mln_d3d12::SurfaceTarget::new(self, window, size).map_err(gfx_error)?, overlay)
            }
            SurfaceKind::D3d12Composition { composition, thread } => {
                if composition.is_swap_chain_panel() && thread != std::thread::current().id() {
                    return Err(Error::unsupported(
                        "a SwapChainPanel takes its swap chain on its UI thread, which made the surface: attach it \
                         with Driver::CallerThread, serviced there",
                    ));
                }
                let overlay = overlay()?;
                (mln_d3d12::SurfaceTarget::for_composition(self, composition, size).map_err(gfx_error)?, overlay)
            }
            _ => return Err(no_surface()),
        };
        target.set_overlay(self.gpu(), overlay);
        Ok(Box::new(target))
    }
}

pub(in super::super) fn new_gfx(device: &mln_d3d12::Device, init: FramesInit<'_>) -> Result<Box<dyn Gfx>, Error> {
    gfx(mln_d3d12::RendererBackend::new(device).map_err(gfx_error)?, init)
}