mln-rs-webgpu 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! A ring of the host's textures, on the device that renders into them, that
//! frames are drawn into and given back to the host. Both sides submit to the
//! device's one queue, which orders the host's reads after the frame and the
//! next frame after the host's reads.

use std::convert::Infallible;

use mln_gfx::gpu::{GpuError, TargetFormats, TextureFormat, TextureId};
use mln_gfx::ring::{self, RingBackend, RingTextures};
use mln_gfx::{ConsumerSync, DepthStencilFormat, DepthStencilFormats, Error, Size, SyncKind, SyncKinds};

use crate::gpu::{WebGpu, from_wgpu_format};
use crate::renderer_backend::RendererBackend;

/// A ring of the host's 2D textures, of `size` pixels and one format, with
/// one layer, one mip level, one sample and `RENDER_ATTACHMENT` usage.
#[derive(Clone, Debug, PartialEq)]
pub struct BorrowedTextures {
    pub textures: Vec<wgpu::Texture>,
    pub size: Size,
    /// The host's textures that frames draw their depth and stencil into
    /// and store, one for each of `textures`, of their size and kind and one
    /// depth and stencil format, or none for depth of the target's own.
    pub depth_textures: Vec<wgpu::Texture>,
}

impl BorrowedTextures {
    /// The kinds of sync with which the host can wait for a frame (the
    /// producer's) and the target for the host's reads (the consumer's):
    /// both share the device's queue. In a browser, which can't block on
    /// the GPU, a frame is handed over in queue order only.
    #[must_use]
    pub fn sync_kinds() -> (SyncKinds, SyncKinds) {
        let consumer = SyncKinds::of(&[SyncKind::CpuComplete, SyncKind::QueueOrder]);
        let producer = if cfg!(target_family = "wasm") { SyncKinds::of(&[SyncKind::QueueOrder]) } else { consumer };
        (producer, consumer)
    }

    /// The formats of the depth textures that frames draw into on `device`.
    #[must_use]
    pub fn depth_stencil_formats(device: &wgpu::Device) -> DepthStencilFormats {
        let formats = DepthStencilFormats::of(&[DepthStencilFormat::Depth24Stencil8]);
        if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
            formats.with(DepthStencilFormat::Depth32FloatStencil8)
        } else {
            formats
        }
    }

    /// Checks the textures against their ring.
    ///
    /// Fails with [`ErrorKind::InvalidArgument`](mln_gfx::ErrorKind) for a
    /// texture of another size than the ring's, of another format than the
    /// first, or that a frame can't render into, for depth textures that
    /// aren't one for each texture, and with
    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for depth textures of
    /// no depth and stencil format.
    pub fn check(&self) -> Result<(), Error> {
        let Some(first) = self.textures.first() else {
            return Err(Error::invalid_argument("a ring needs at least one texture"));
        };
        if let Some(depth) = self.depth_textures.first() {
            if self.depth_textures.len() != self.textures.len() {
                return Err(Error::invalid_argument("a ring's depth textures must be one for each of its textures"));
            }
            if depth_stencil_format(depth.format()).is_none() {
                return Err(Error::unsupported("a ring's depth textures must have a depth and stencil format"));
            }
        }
        for texture in self.textures.iter().chain(&self.depth_textures) {
            let size = texture.size();
            if (size.width, size.height) != (self.size.width, self.size.height) {
                return Err(Error::invalid_argument("each texture's size must match the ring's physical size"));
            }
            let kin =
                if texture.format().is_depth_stencil_format() { self.depth_textures.first() } else { Some(first) };
            if Some(texture.format()) != kin.map(wgpu::Texture::format) {
                return Err(Error::invalid_argument("the ring's textures must share a format"));
            }
            if !texture.usage().contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
                || texture.dimension() != wgpu::TextureDimension::D2
                || texture.mip_level_count() != 1
                || texture.sample_count() != 1
                || size.depth_or_array_layers != 1
            {
                return Err(Error::invalid_argument(
                    "each texture must be 2D with one layer, mip level and sample, and render-attachment usage",
                ));
            }
        }
        Ok(())
    }

    fn format(&self) -> Option<wgpu::TextureFormat> {
        self.textures.first().map(wgpu::Texture::format)
    }

    fn depth_format(&self) -> Option<wgpu::TextureFormat> {
        self.depth_textures.first().map(wgpu::Texture::format)
    }
}

impl RingTextures for BorrowedTextures {
    type Image = wgpu::Texture;

    fn images(&self) -> &[wgpu::Texture] {
        &self.textures
    }

    fn same_image(a: &wgpu::Texture, b: &wgpu::Texture) -> bool {
        a == b
    }

    fn size(&self) -> Size {
        self.size
    }

    fn has_depth(&self) -> bool {
        !self.depth_textures.is_empty()
    }
}

/// The depth and stencil format that `format` is, if it is one.
#[must_use]
pub fn depth_stencil_format(format: wgpu::TextureFormat) -> Option<DepthStencilFormat> {
    match format {
        wgpu::TextureFormat::Depth24PlusStencil8 => Some(DepthStencilFormat::Depth24Stencil8),
        wgpu::TextureFormat::Depth32FloatStencil8 => Some(DepthStencilFormat::Depth32FloatStencil8),
        _ => None,
    }
}

/// Frames drawn into the host's textures, each given back to the host.
pub type BorrowedTarget = ring::BorrowedTarget<WebGpuRing>;

/// A [`BorrowedTarget`]'s part on WebGPU: both sides share the device's
/// queue, so frames need no separate sync objects.
pub struct WebGpuRing;

impl RingBackend for WebGpuRing {
    type Gpu = WebGpu;
    type Renderer = RendererBackend;
    type Textures = BorrowedTextures;
    type Wait = Infallible;
    type Handed = Infallible;

    /// Fails as [`BorrowedTextures::check`] does, and with
    /// [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for a producer kind
    /// the target can't hand over.
    fn new(_backend: &mut RendererBackend, textures: &BorrowedTextures, producer: SyncKind) -> Result<Self, Error> {
        textures.check()?;
        if !BorrowedTextures::sync_kinds().0.contains(producer) {
            return Err(Error::unsupported(format!("a WebGPU target hands frames over with no {producer:?}")));
        }
        Ok(WebGpuRing)
    }

    /// Fails with [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for another
    /// format or depth format, or depth textures where the ring had none, and
    /// as [`BorrowedTextures::check`] does.
    fn check_replacement(&self, current: &BorrowedTextures, next: &BorrowedTextures) -> Result<(), Error> {
        if (next.format(), next.depth_format()) != (current.format(), current.depth_format()) {
            return Err(Error::unsupported("a ring keeps its formats, and its depth textures or their lack"));
        }
        next.check()
    }

    /// Fails with [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) for a color
    /// format that `WebGpu` has no texture of.
    fn targets(gpu: &WebGpu, textures: &BorrowedTextures) -> Result<TargetFormats, Error> {
        let format = textures.format();
        let color = format
            .and_then(from_wgpu_format)
            .ok_or_else(|| Error::unsupported(format!("the WebGPU target draws into no {format:?}")))?;
        let depth_stencil = match textures.depth_format() {
            Some(depth) => from_wgpu_format(depth),
            None => Some(if gpu.device().device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
                TextureFormat::Depth32FloatStencil8
            } else {
                TextureFormat::Depth24PlusStencil8
            }),
        };
        Ok(TargetFormats { color: Some(color), depth_stencil })
    }

    fn import(gpu: &mut WebGpu, textures: &BorrowedTextures, slot: usize, depth: bool) -> Result<TextureId, GpuError> {
        let list = if depth { &textures.depth_textures } else { &textures.textures };
        let texture = list.get(slot).ok_or_else(|| GpuError::Invalid(format!("the ring has no slot {slot}")))?;
        Ok(gpu.import_texture(texture))
    }

    fn wait_for(&mut self, _gpu: &mut WebGpu, consumer: ConsumerSync) -> Result<Option<Infallible>, Error> {
        match consumer.sync.kind {
            SyncKind::CpuComplete | SyncKind::QueueOrder => Ok(None),
            kind => Err(Error::unsupported(format!("the WebGPU target waits for no {kind:?}"))),
        }
    }
}