use std::cell::{Cell, RefCell};
use std::rc::Rc;
use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
use mln_gfx::gpu::{Gpu as _, ResourceId, TargetFormats};
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::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 {
backend: Rc<RendererBackend>,
textures: RefCell<BorrowedTextures>,
selected: Cell<usize>,
producer: SyncKind,
depth_stencil_format: wgpu::TextureFormat,
depth_stencil: Cell<Option<wgpu::Texture>>,
imports: Cell<Option<(usize, FrameImage)>>,
}
impl BorrowedTarget {
pub fn new(backend: Rc<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 depth_stencil_format =
if backend.device().device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
wgpu::TextureFormat::Depth32FloatStencil8
} else {
wgpu::TextureFormat::Depth24PlusStencil8
};
Ok(BorrowedTarget {
backend,
textures: RefCell::new(textures),
selected: Cell::new(0),
producer,
depth_stencil_format,
depth_stencil: Cell::new(None),
imports: Cell::new(None),
})
}
pub fn select(&self, slot: usize) {
self.selected.set(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(&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(&self, _slot: usize) {}
pub fn replace(&self, textures: BorrowedTextures) -> Result<(), Error> {
let current = self.textures.borrow();
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"));
}
drop(current);
textures.check()?;
if let Some((_, image)) = self.imports.take() {
self.destroy_imports(image);
}
*self.textures.borrow_mut() = textures;
Ok(())
}
fn depth_stencil(&self, textures: &BorrowedTextures) -> wgpu::Texture {
if let Some(depth) = textures.depth_textures.get(self.selected.get()) {
return depth.clone();
}
let size = textures.size;
let texture = match self.depth_stencil.take() {
Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture,
_ => self.backend.device().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: self.depth_stencil_format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
}),
};
self.depth_stencil.set(Some(texture.clone()));
texture
}
fn destroy_imports(&self, image: FrameImage) {
let mut gpu = self.backend.gpu();
for import in [Some(image.color), image.depth_stencil].into_iter().flatten() {
gpu.destroy(ResourceId::Texture(import));
}
}
}
impl Drop for BorrowedTarget {
fn drop(&mut self) {
if let Some((_, image)) = self.imports.take() {
self.destroy_imports(image);
}
}
}
impl FrameTarget for BorrowedTarget {
fn begin_frame(&self) -> Option<FrameImage> {
let slot = self.selected.get();
match self.imports.take() {
Some((imported, image)) if imported == slot => {
self.imports.set(Some((imported, image)));
return Some(image);
}
Some((_, image)) => self.destroy_imports(image),
None => {}
}
let textures = self.textures.borrow();
let texture = textures.textures.get(slot)?;
let depth_stencil = self.depth_stencil(&textures);
let mut gpu = self.backend.gpu();
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.set(Some((slot, image)));
Some(image)
}
fn end_frame(&self) -> Handoff {
let Some((_, image)) = self.imports.take() else {
return Handoff::Dropped;
};
self.destroy_imports(image);
let sync = if self.producer == SyncKind::QueueOrder {
GpuSync::of(SyncKind::QueueOrder)
} else {
if let Err(error) = self.backend.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.get(), sync }
}
}