use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
use mln_gfx::gpu::{Gpu as _, ReadbackId, ResourceId, TargetFormats, TextureId, TextureRegion, destroy_unused};
use mln_gfx::{Error, FramePixels, Size};
use crate::device::Device;
use crate::gpu::{WebGpu, from_wgpu_format};
use crate::log_target;
use crate::renderer_backend::RendererBackend;
const ALPHA_MODE: wgpu::CompositeAlphaMode =
if cfg!(target_family = "wasm") { wgpu::CompositeAlphaMode::PreMultiplied } else { wgpu::CompositeAlphaMode::Auto };
pub struct OverlayTarget<'a> {
pub device: &'a wgpu::Device,
pub queue: &'a wgpu::Queue,
pub view: &'a wgpu::TextureView,
pub format: wgpu::TextureFormat,
pub size: Size,
}
pub type Overlay = Box<dyn FnMut(&OverlayTarget<'_>)>;
#[derive(Clone, Copy, Debug)]
pub struct SurfaceOptions {
pub cap_frame_rate: bool,
pub usages: Option<wgpu::TextureUsages>,
pub format: Option<wgpu::TextureFormat>,
}
impl Default for SurfaceOptions {
fn default() -> Self {
SurfaceOptions { cap_frame_rate: true, usages: None, format: None }
}
}
pub struct SurfaceTarget {
state: Box<State>,
}
struct State {
current: Option<wgpu::SurfaceTexture>,
depth_stencil: Option<wgpu::Texture>,
overlay: Option<Overlay>,
surface: wgpu::Surface<'static>,
format: wgpu::TextureFormat,
usage: wgpu::TextureUsages,
present_mode: wgpu::PresentMode,
depth_stencil_format: wgpu::TextureFormat,
size: Size,
configured: Option<Size>,
color_import: Option<TextureId>,
depth_import: Option<TextureId>,
readback_requested: bool,
pending_readback: Option<(ReadbackId, Size)>,
readback: Option<FramePixels>,
device: Device,
}
impl SurfaceTarget {
pub fn new(
backend: &RendererBackend,
surface: wgpu::Surface<'static>,
framebuffer_size: Size,
options: SurfaceOptions,
) -> Result<SurfaceTarget, Error> {
let device = backend.device();
let (format, mut usage, vsync_present_mode) = if let Some(adapter) = device.adapter() {
let capabilities = surface.get_capabilities(adapter);
if capabilities.formats.is_empty() {
return Err(Error::unsupported("The WebGPU adapter can't present to the surface"));
}
let format = match options.format.or(device.surface_format()) {
Some(format) if capabilities.formats.contains(&format) => format,
Some(format) => {
return Err(Error::unsupported(format!("The surface does not take the {format:?} format")));
}
None => {
const RENDERED: [wgpu::TextureFormat; 4] = [
wgpu::TextureFormat::Bgra8Unorm,
wgpu::TextureFormat::Bgra8UnormSrgb,
wgpu::TextureFormat::Rgba8Unorm,
wgpu::TextureFormat::Rgba8UnormSrgb,
];
let format = if cfg!(target_family = "wasm") {
capabilities.formats.iter().copied().find(|f| RENDERED.contains(f))
} else {
RENDERED.into_iter().find(|f| capabilities.formats.contains(f))
};
format
.ok_or_else(|| Error::unsupported("The surface takes none of the formats the map renders in"))?
}
};
let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (capabilities.usages & wgpu::TextureUsages::COPY_SRC);
let present_mode = if capabilities.present_modes.contains(&wgpu::PresentMode::Mailbox) {
wgpu::PresentMode::Mailbox
} else {
wgpu::PresentMode::Fifo
};
(format, usage, present_mode)
} else {
let format = options.format.or(device.surface_format()).ok_or_else(|| {
Error::invalid_argument("A surface on a device without an adapter needs the device's surface format")
})?;
(format, wgpu::TextureUsages::RENDER_ATTACHMENT, wgpu::PresentMode::Fifo)
};
if let Some(usages) = options.usages {
usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (usages & wgpu::TextureUsages::COPY_SRC);
}
let depth_stencil_format = if device.device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
wgpu::TextureFormat::Depth32FloatStencil8
} else {
wgpu::TextureFormat::Depth24PlusStencil8
};
Ok(SurfaceTarget {
state: Box::new(State {
current: None,
depth_stencil: None,
overlay: None,
surface,
format,
usage,
present_mode: if options.cap_frame_rate { vsync_present_mode } else { wgpu::PresentMode::Immediate },
depth_stencil_format,
size: framebuffer_size,
configured: None,
color_import: None,
depth_import: None,
readback_requested: false,
pending_readback: None,
readback: None,
device: device.clone(),
}),
})
}
#[must_use]
pub fn format(&self) -> wgpu::TextureFormat {
self.state.format
}
#[must_use]
pub fn size(&self) -> Size {
self.state.size
}
pub fn request_readback(&mut self) {
self.state.readback_requested = true;
}
#[must_use]
pub fn take_readback(&mut self, gpu: &mut WebGpu) -> Option<FramePixels> {
self.state.finish_readback(gpu, false);
self.state.readback.take()
}
pub fn set_overlay(&mut self, overlay: Option<Overlay>) {
self.state.overlay = overlay;
}
}
impl State {
fn acquire(&mut self) -> Option<Size> {
let size_of = |texture: &wgpu::SurfaceTexture| Size::new(texture.texture.width(), texture.texture.height());
if let Some(current) = &self.current {
return Some(size_of(current));
}
let size = self.size;
if self.configured != Some(size) && size.width != 0 && size.height != 0 {
self.surface.configure(
self.device.device(),
&wgpu::SurfaceConfiguration {
usage: self.usage,
format: self.format,
width: size.width,
height: size.height,
present_mode: self.present_mode,
desired_maximum_frame_latency: 2,
alpha_mode: ALPHA_MODE,
view_formats: vec![self.format],
color_space: wgpu::SurfaceColorSpace::Auto,
},
);
self.configured = Some(size);
}
self.configured?;
let texture = match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
self.configured = None;
return None;
}
wgpu::CurrentSurfaceTexture::Timeout
| wgpu::CurrentSurfaceTexture::Occluded
| wgpu::CurrentSurfaceTexture::Validation => return None,
};
Some(size_of(self.current.insert(texture)))
}
fn depth_stencil_import(&mut self, gpu: &mut WebGpu, size: Size) -> TextureId {
let texture = match self.depth_stencil.take() {
Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture,
_ => {
if let Some(import) = self.depth_import.take() {
destroy_unused(gpu, [ResourceId::Texture(import)]);
}
self.device.device().create_texture(&wgpu::TextureDescriptor {
label: Some("surface 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: &[],
})
}
};
let import = *self.depth_import.get_or_insert_with(|| gpu.import_texture(&texture));
self.depth_stencil = Some(texture);
import
}
fn read_back(&mut self, gpu: &mut WebGpu, texture: &wgpu::Texture) {
if !self.usage.contains(wgpu::TextureUsages::COPY_SRC) {
tracing::warn!(target: log_target::RENDER, "WebGPU: the surface does not support readback (no COPY_SRC)");
return;
}
let size = Size::new(texture.width(), texture.height());
let imported = gpu.import_texture(texture);
let readback = gpu.read_texture(imported, TextureRegion::whole(size));
destroy_unused(gpu, [ResourceId::Texture(imported)]);
match readback {
Ok(readback) => {
if let Some((stale, _)) = self.pending_readback.replace((readback, size)) {
destroy_unused(gpu, [ResourceId::Readback(stale)]);
}
}
Err(error) => {
tracing::error!(target: log_target::RENDER, error = %error, "WebGPU: reading the frame back failed");
}
}
}
fn finish_readback(&mut self, gpu: &mut WebGpu, wait: bool) {
let Some((readback, size)) = self.pending_readback.take() else {
return;
};
let mut texels = match gpu.take_readback(readback, wait) {
Ok(Some(texels)) => texels,
Ok(None) => {
self.pending_readback = Some((readback, size));
return;
}
Err(error) => {
return tracing::error!(target: log_target::RENDER, error = %error, "WebGPU: reading the frame back failed");
}
};
if matches!(self.format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb) {
for texel in texels.as_chunks_mut::<4>().0 {
texel.swap(0, 2);
}
}
self.readback = Some(FramePixels { size, data: texels });
}
}
impl FrameTarget for SurfaceTarget {
type Gpu = WebGpu;
fn resize(&mut self, _gpu: &mut WebGpu, size: Size) {
self.state.size = size;
}
fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
self.state.begin_frame(gpu)
}
fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
self.state.end_frame(gpu)
}
fn tear_down(&mut self, gpu: &mut WebGpu) {
let state = &mut *self.state;
if let Some((readback, _)) = state.pending_readback.take() {
destroy_unused(gpu, [ResourceId::Readback(readback)]);
}
let imports = [state.color_import.take(), state.depth_import.take()].into_iter().flatten();
destroy_unused(gpu, imports.map(ResourceId::Texture));
}
}
impl State {
fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
let size = self.acquire()?;
let depth_stencil = self.depth_stencil_import(gpu, size);
let current = self.current.as_ref()?;
let color = *self.color_import.get_or_insert_with(|| gpu.import_texture(¤t.texture));
let targets = TargetFormats {
color: from_wgpu_format(self.format),
depth_stencil: from_wgpu_format(self.depth_stencil_format),
};
Some(FrameImage { size, color, depth_stencil: Some(depth_stencil), targets })
}
fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
if let Some(color) = self.color_import.take() {
destroy_unused(gpu, [ResourceId::Texture(color)]);
}
let Some(current) = self.current.take() else {
return Handoff::Dropped;
};
if let Some(overlay) = self.overlay.as_mut() {
let view = current.texture.create_view(&wgpu::TextureViewDescriptor::default());
overlay(&OverlayTarget {
device: self.device.device(),
queue: self.device.queue(),
view: &view,
format: self.format,
size: Size::new(current.texture.width(), current.texture.height()),
});
}
if std::mem::take(&mut self.readback_requested) {
self.read_back(gpu, ¤t.texture);
self.finish_readback(gpu, true);
}
self.device.queue().present(current);
Handoff::Presented
}
}
impl Drop for State {
fn drop(&mut self) {
drop(self.current.take());
drop(self.depth_stencil.take());
drop(self.overlay.take());
let _ = self.device.device().poll(wgpu::PollType::Poll);
}
}