mln-rs-runtime 0.0.22

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

use mln_gfx::{SyncKind, SyncKinds};
use mln_style::error::Error;

#[cfg(has_native_webgpu)]
use super::adapter_index;
use crate::render::gfx_error;
use crate::render::local::{BackendRef, Borrowed, FramesInit, Gfx, LocalBackend, Target, gfx, overlay_of};
#[cfg(has_wasm_webgpu)]
use crate::render::target::CanvasFormat;
#[cfg(has_native_webgpu)]
use crate::render::target::{Adapter, BackendType};
use crate::render::target::{
    BorrowedRing, DepthStencilFormat, Device, FrameDepth, FrameTexture, FrameTextureKind, NativeTexture, RingKind,
    Surface, SurfaceKind, SurfaceOverlay,
};

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

#[cfg(has_native_webgpu)]
impl Surface {
    /// A surface that the host made with the instance of the WebGPU
    /// [`Device`] that the session renders on.
    pub fn wgpu(surface: wgpu::Surface<'static>) -> Surface {
        Surface::of(SurfaceKind::Wgpu(surface))
    }
}

impl Device {
    /// The host's WebGPU device and queue, which `instance` made. The
    /// session configures its surfaces with `format`, which each surface
    /// must support.
    #[cfg(has_native_webgpu)]
    #[must_use]
    pub fn webgpu(
        instance: wgpu::Instance,
        device: wgpu::Device,
        queue: wgpu::Queue,
        format: wgpu::TextureFormat,
    ) -> Device {
        Device::WebGpu(mln_webgpu::Device::from_wgpu(Some(instance), device, queue, Some(format)))
    }

    /// In the browser, the library's device on the browser's WebGPU, which
    /// arrives asynchronously. A surface session on a canvas without a
    /// device asks for one itself, and attaches once it has it.
    ///
    /// Fails as [`mln_webgpu::Device::request`] does.
    #[cfg(has_wasm_webgpu)]
    pub async fn request_web_gpu() -> Result<Device, Error> {
        mln_webgpu::Device::request().await.map(Device::WebGpu).map_err(gfx_error)
    }
}

pub(in super::super) fn ring_depth_stencil_format(
    textures: &mln_webgpu::BorrowedTextures,
) -> Option<DepthStencilFormat> {
    let texture = textures.depth_textures.first()?;
    mln_webgpu::depth_stencil_format(texture.format())
}

pub(in super::super) fn ring_same_texture(
    textures: &mln_webgpu::BorrowedTextures,
    slot: usize,
    others: &mln_webgpu::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_webgpu::BorrowedTextures, slot: usize) -> Option<FrameTexture> {
    textures.textures.get(slot).map(|_| FrameTexture {
        size: textures.size,
        kind: FrameTextureKind::WebGpu,
        native: None,
        depth: (!textures.depth_textures.is_empty())
            .then_some(FrameDepth { texture: NativeTexture::WebGpu, export: None }),
    })
}

#[cfg(has_native_webgpu)]
pub(in super::super) fn create_device(adapter: Option<Adapter>) -> Result<Device, Error> {
    mln_webgpu::Device::new(adapter_index(BackendType::WebGPU, adapter)?).map(Device::WebGpu).map_err(gfx_error)
}

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

/// A wgpu surface of `kind`, made with the instance of `backend`'s device
/// where the host didn't make it.
fn surface(backend: &mln_webgpu::RendererBackend, kind: SurfaceKind) -> Result<wgpu::Surface<'static>, Error> {
    let instance = || {
        backend
            .device()
            .instance()
            .ok_or_else(|| Error::invalid_argument("the session's device has no instance to make a surface with"))
    };
    let made = match kind {
        #[cfg(has_native_webgpu)]
        SurfaceKind::Wgpu(surface) => return Ok(surface),
        SurfaceKind::Window(window) => instance()?.create_surface(window),
        #[cfg(target_family = "wasm")]
        SurfaceKind::WebCanvas { canvas, .. } => {
            use wasm_bindgen::JsCast as _;
            let target = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
                Ok(canvas) => wgpu::SurfaceTarget::OffscreenCanvas(canvas),
                Err(canvas) => wgpu::SurfaceTarget::Canvas(canvas.unchecked_into()),
            };
            instance()?.create_surface(target)
        }
        #[cfg(has_metal)]
        SurfaceKind::MetalLayer(_) => return Err(Error::unsupported("a Metal layer presents on a Metal device")),
        #[cfg(has_vulkan)]
        SurfaceKind::Vulkan(_) => return Err(Error::unsupported("a Vulkan surface presents on a Vulkan device")),
        #[cfg(has_native_gl)]
        SurfaceKind::Gl(_) => return Err(Error::unsupported("an EGL surface presents on an OpenGL device")),
        #[cfg(has_d3d12)]
        SurfaceKind::D3d12Composition { .. } => {
            return Err(Error::unsupported("a composition swap chain presents on a D3D12 device"));
        }
    };
    made.map_err(|error| Error::failed(format!("can't make a surface on the window: {error}")))
}

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

    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
        match ring {
            RingKind::WebGpu(textures) => Some(textures),
            _ => None,
        }
    }

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

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

    fn surface(
        &mut self,
        target_surface: Surface,
        overlay: Option<SurfaceOverlay>,
        size: mln_gfx::Size,
    ) -> Result<Target<Self>, Error> {
        let kind = target_surface.kind;
        #[cfg(target_family = "wasm")]
        let format = match &kind {
            SurfaceKind::WebCanvas { format: Some(format), .. } => Some(match format {
                CanvasFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
                CanvasFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
                CanvasFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
            }),
            _ => None,
        };
        #[cfg(not(target_family = "wasm"))]
        let format = None;
        let overlay = overlay_of(overlay, |overlay| {
            if let SurfaceOverlay::WebGpu(overlay) = overlay { Ok(overlay) } else { Err(overlay) }
        })?;
        let target = surface(self, kind)?;
        let options = mln_webgpu::SurfaceOptions {
            cap_frame_rate: target_surface.cap_frame_rate,
            format,
            ..mln_webgpu::SurfaceOptions::default()
        };
        let mut target = mln_webgpu::SurfaceTarget::new(self, target, size, options).map_err(gfx_error)?;
        target.set_overlay(overlay);
        Ok(Box::new(target))
    }
}

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