use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
use mln_gfx::gpu::{Gpu as _, ResourceId, TargetFormats, destroy_unused};
use mln_gfx::{ConsumerSync, DepthStencilFormat, DepthStencilFormats, GpuSync, SyncKind, SyncKinds};
use mln_util::error::Error;
use mln_util::logging::{Event, Log};
use mln_util::size::Size;
use crate::gpu::{WebGpu, from_wgpu_format};
use crate::renderer_backend::RendererBackend;
#[derive(Clone, Debug, PartialEq)]
pub struct BorrowedTextures {
pub textures: Vec<wgpu::Texture>,
pub size: Size,
pub depth_textures: Vec<wgpu::Texture>,
}
impl BorrowedTextures {
#[must_use]
pub fn sync_kinds() -> (SyncKinds, SyncKinds) {
let kinds = SyncKinds::of(&[SyncKind::CpuComplete, SyncKind::QueueOrder]);
(kinds, kinds)
}
#[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
}
}
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)
}
}
#[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,
}
}
pub struct BorrowedTarget {
device: wgpu::Device,
textures: Option<BorrowedTextures>,
selected: usize,
producer: SyncKind,
depth_stencil_format: wgpu::TextureFormat,
depth_stencil: Option<wgpu::Texture>,
imports: Option<(usize, FrameImage)>,
}
impl BorrowedTarget {
pub fn new(backend: &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:?}")));
}
let device = backend.device().device().clone();
let depth_stencil_format = if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
wgpu::TextureFormat::Depth32FloatStencil8
} else {
wgpu::TextureFormat::Depth24PlusStencil8
};
Ok(BorrowedTarget {
device,
textures: Some(textures),
selected: 0,
producer,
depth_stencil_format,
depth_stencil: None,
imports: None,
})
}
pub fn select(&mut self, slot: usize) {
self.selected = slot;
}
#[expect(
clippy::needless_pass_by_value,
reason = "the release takes the host's sync, as every backend's does, and drops it"
)]
pub fn release(&mut self, _slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
match consumer.sync.kind {
SyncKind::CpuComplete | SyncKind::QueueOrder => Ok(()),
kind => Err(Error::unsupported(format!("the WebGPU target waits for no {kind:?}"))),
}
}
pub fn discard(&mut self, _slot: usize) {}
pub fn replace(&mut self, gpu: &mut WebGpu, textures: BorrowedTextures) -> Result<GpuSync, Error> {
let Some(current) = &self.textures else {
return Err(Error::invalid_state("the ring let go of its textures"));
};
if textures.textures.len() != current.textures.len() {
return Err(Error::invalid_argument("a ring keeps its depth"));
}
if (textures.format(), textures.depth_format()) != (current.format(), current.depth_format()) {
return Err(Error::unsupported("a ring keeps its formats, and its depth textures or their lack"));
}
textures.check()?;
let sync = self.end_work(gpu)?;
self.textures = Some(textures);
Ok(sync)
}
pub fn release_textures(&mut self, gpu: &mut WebGpu) -> Result<GpuSync, Error> {
if self.textures.is_none() {
return Err(Error::invalid_state("the ring let go of its textures"));
}
let sync = self.end_work(gpu)?;
self.textures = None;
self.depth_stencil = None;
Ok(sync)
}
fn end_work(&mut self, gpu: &mut WebGpu) -> Result<GpuSync, Error> {
if let Some((_, image)) = self.imports.take() {
destroy_imports(gpu, image);
}
let wait = self.producer == SyncKind::CpuComplete;
gpu.flush(wait).map_err(|error| Error::native(format!("Submitting a ring's frames failed: {error}")))?;
Ok(GpuSync::of(self.producer))
}
}
fn own_depth_stencil(
device: &wgpu::Device,
format: wgpu::TextureFormat,
own: &mut Option<wgpu::Texture>,
size: Size,
) -> wgpu::Texture {
match own {
Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture.clone(),
_ => own
.insert(device.create_texture(&wgpu::TextureDescriptor {
label: Some("borrowed ring depth and stencil"),
size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
}))
.clone(),
}
}
fn destroy_imports(gpu: &mut WebGpu, image: FrameImage) {
let imports = [Some(image.color), image.depth_stencil].into_iter().flatten();
destroy_unused(gpu, imports.map(ResourceId::Texture));
}
impl FrameTarget for BorrowedTarget {
type Gpu = WebGpu;
fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
let slot = self.selected;
match self.imports {
Some((imported, image)) if imported == slot => return Some(image),
Some((_, image)) => {
self.imports = None;
destroy_imports(gpu, image);
}
None => {}
}
let textures = self.textures.as_ref()?;
let texture = textures.textures.get(slot)?.clone();
let depth_stencil = match textures.depth_textures.get(slot) {
Some(depth) => depth.clone(),
None => own_depth_stencil(&self.device, self.depth_stencil_format, &mut self.depth_stencil, textures.size),
};
let image = FrameImage {
size: textures.size,
color: gpu.import_texture(&texture),
depth_stencil: Some(gpu.import_texture(&depth_stencil)),
targets: TargetFormats {
color: from_wgpu_format(texture.format()),
depth_stencil: from_wgpu_format(depth_stencil.format()),
},
};
self.imports = Some((slot, image));
Some(image)
}
fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
let Some((_, image)) = self.imports.take() else {
return Handoff::Dropped;
};
destroy_imports(gpu, image);
let sync = if self.producer == SyncKind::QueueOrder {
GpuSync::of(SyncKind::QueueOrder)
} else {
if let Err(error) = gpu.flush(true) {
Log::error(Event::Render, format!("WebGPU: waiting for a borrowed texture's frame failed: {error}"));
return Handoff::Dropped;
}
GpuSync::of(SyncKind::CpuComplete)
};
Handoff::GivenBack { slot: self.selected, sync }
}
fn tear_down(&mut self, gpu: &mut WebGpu) {
if let Some((_, image)) = self.imports.take() {
destroy_imports(gpu, image);
}
}
}