use std::any::Any;
use std::ops::Range;
use std::sync::{Arc, OnceLock};
use mln_gfx::gpu::validation::{
self, BindingsTags, BufferInfo, GeometryTags, LayoutTags, Lookup, PipelineTags, ShaderBinding, TextureInfo,
no_pass, open_pass,
};
use mln_gfx::gpu::{
BindGroupEntry, BindingsDesc, BindingsId, BufferDesc, BufferId, BufferUsage, Caps, ClipDepthRange, Draw,
DynamicState, GeometryDesc, GeometryId, Gpu, GpuError, LoadOp, PassDesc, PassState, PipelineDesc, PipelineId,
ReadbackId, ResourceId, SamplerId, Scissor, ShaderId, ShaderKey, SlotMap, TextureDesc, TextureFormat, TextureId,
TextureRegion, TextureUsage,
};
use mln_gfx::texture2d::SamplerState;
use mln_gfx::types::{TextureFilterType, TextureWrapType};
use mln_gfx::{Rgba, Size};
use crate::index_table::IndexTable;
use crate::mipmaps::Mipmapper;
use crate::shaders::declaration;
use crate::shaders::shader_program::{self, BindingType, ShaderProgram, validated};
use crate::writes::Writes;
use crate::{CustomLayerEncoder, CustomLayerPass, Device};
const PAGE: u64 = 16 << 10;
const VERTEX_USAGES: wgpu::BufferUsages = wgpu::BufferUsages::VERTEX.union(wgpu::BufferUsages::STORAGE);
pub(crate) const VERTEX_STAGE_STORAGE_BUFFERS: u32 = 5;
const UNIFORM_ALIGNMENT: u64 = 256;
struct Buffer {
buffer: wgpu::Buffer,
usage: BufferUsage,
offset: u64,
size: u64,
written: Option<u64>,
}
struct Texture {
texture: wgpu::Texture,
view: wgpu::TextureView,
levels: Vec<wgpu::TextureView>,
mip_groups: Vec<wgpu::BindGroup>,
}
impl Texture {
fn attachment(&self) -> &wgpu::TextureView {
self.levels.first().unwrap_or(&self.view)
}
}
struct Shader {
program: ShaderProgram,
reads: Vec<ShaderBinding>,
}
struct Pipeline {
pipeline: wgpu::RenderPipeline,
tags: PipelineTags,
}
struct Bindings {
groups: Vec<BindGroup>,
index_slot: Option<u32>,
tags: BindingsTags,
}
struct BindGroup {
slot: u32,
group: wgpu::BindGroup,
entries: Vec<BindGroupEntry>,
}
struct Geometry {
vertex_buffers: Vec<(wgpu::Buffer, Range<u64>)>,
index_buffer: (wgpu::Buffer, Range<u64>),
vertex_ids: Vec<(BufferId, u64)>,
index_id: (BufferId, u64),
tags: GeometryTags,
}
struct Readback {
buffer: wgpu::Buffer,
padded_bytes_per_row: usize,
bytes_per_row: usize,
rows: usize,
#[cfg_attr(target_family = "wasm", expect(dead_code, reason = "a browser can't wait for a submission"))]
submission: wgpu::SubmissionIndex,
mapped: Arc<OnceLock<Result<(), wgpu::BufferAsyncError>>>,
}
struct OpenPass {
pass: wgpu::RenderPass<'static>,
#[cfg(feature = "bench")]
counted: bool,
state: PassState,
color_format: Option<wgpu::TextureFormat>,
depth_stencil_format: Option<wgpu::TextureFormat>,
vertex_buffers: Vec<(BufferId, u64)>,
index_buffer: Option<(BufferId, u64)>,
groups: Vec<Option<BindingsId>>,
}
impl OpenPass {
fn forget_state(&mut self) {
self.state.forget();
self.vertex_buffers.clear();
self.index_buffer = None;
self.groups.clear();
}
}
pub struct WebGpu {
device: Device,
caps: Caps,
index_table: IndexTable,
buffers: SlotMap<BufferId, Buffer>,
uniform_page: Option<(wgpu::Buffer, u64)>,
geometry_page: Option<(wgpu::Buffer, u64)>,
storage_alignment: u64,
writes: Writes,
textures: SlotMap<TextureId, Texture>,
samplers: SlotMap<SamplerId, wgpu::Sampler>,
shaders: SlotMap<ShaderId, Shader>,
layout_tags: LayoutTags,
pipelines: SlotMap<PipelineId, Pipeline>,
bindings: SlotMap<BindingsId, Bindings>,
geometries: SlotMap<GeometryId, Geometry>,
dependents: validation::Dependents,
readbacks: SlotMap<ReadbackId, Readback>,
mipmapper: Option<Mipmapper>,
spare_readback: Option<wgpu::Buffer>,
encoder: Option<wgpu::CommandEncoder>,
pass: Option<OpenPass>,
#[cfg(feature = "bench")]
queries: Option<crate::bench::Queries>,
}
impl WebGpu {
#[cfg(test)]
pub(crate) fn texture_count(&self) -> usize {
self.textures.len()
}
#[must_use]
pub fn new(device: &Device) -> WebGpu {
let limits = device.device().limits();
let caps = Caps {
buffer_offset_alignment: limits
.min_uniform_buffer_offset_alignment
.max(limits.min_storage_buffer_offset_alignment),
max_texture_size: limits.max_texture_dimension_2d,
half_float_render_targets: true,
clip_depth: ClipDepthRange::ZeroToOne,
render_target_depth: Some(TextureFormat::Depth32Float),
clear_stencil_with_pass: false,
cpu_rasterizer: device.adapter_info().device_type == wgpu::DeviceType::Cpu,
max_line_width: 1.0,
binds_vertex_buffers: limits.max_storage_buffers_per_shader_stage >= VERTEX_STAGE_STORAGE_BUFFERS,
};
WebGpu {
index_table: IndexTable::new(device.device()),
device: device.clone(),
caps,
buffers: SlotMap::with_key(),
uniform_page: None,
geometry_page: None,
storage_alignment: u64::from(limits.min_storage_buffer_offset_alignment).max(wgpu::COPY_BUFFER_ALIGNMENT),
writes: Writes::default(),
textures: SlotMap::with_key(),
samplers: SlotMap::with_key(),
shaders: SlotMap::with_key(),
layout_tags: LayoutTags::default(),
pipelines: SlotMap::with_key(),
bindings: SlotMap::with_key(),
geometries: SlotMap::with_key(),
dependents: validation::Dependents::default(),
readbacks: SlotMap::with_key(),
mipmapper: None,
spare_readback: None,
#[cfg(feature = "bench")]
queries: crate::bench::Queries::new(device.device())
.map(|queries| queries.timed(device.device(), device.queue())),
encoder: None,
pass: None,
}
}
pub(crate) fn device(&self) -> &Device {
&self.device
}
pub fn import_texture(&mut self, texture: &wgpu::Texture) -> TextureId {
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
self.textures.insert(Texture { texture: texture.clone(), view, levels: Vec::new(), mip_groups: Vec::new() })
}
#[cfg(test)]
pub(crate) fn native_texture(&self, texture: TextureId) -> Option<&wgpu::Texture> {
self.textures.get(texture).map(|texture| &texture.texture)
}
#[cfg(test)]
pub(crate) fn readback_buffer(&self, readback: ReadbackId) -> Option<&wgpu::Buffer> {
self.readbacks.get(readback).map(|readback| &readback.buffer)
}
fn submit(&mut self, then: impl FnOnce(&mut wgpu::CommandEncoder)) -> Result<wgpu::SubmissionIndex, GpuError> {
let mut encoder = self.encoder.take().unwrap_or_else(|| {
self.device.device().create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
});
then(&mut encoder);
#[cfg(feature = "bench")]
let measured = self.queries.as_mut().and_then(|queries| queries.resolve(self.device.device(), &mut encoder));
let command_buffer = self.validated("flush", |_| encoder.finish())?;
let writes = self.writes.encode(self.device.device(), self.device.queue());
let submission = self.device.queue().submit(writes.into_iter().chain([command_buffer]));
self.writes.submitted();
#[cfg(feature = "bench")]
if let Some(measured) = measured {
crate::bench::Queries::read_back(measured);
}
Ok(submission)
}
fn info(&self) -> (impl Fn(BufferId) -> Option<BufferInfo> + '_, impl Fn(TextureId) -> Option<TextureInfo> + '_) {
let buffer =
|id| self.buffers.get(id).map(|buffer: &Buffer| BufferInfo { usage: buffer.usage, size: buffer.size });
let texture = |id| self.textures.get(id).map(|texture: &Texture| texture_info(&texture.texture));
(buffer, texture)
}
fn begin_render_pass(
&mut self,
desc: &PassDesc<'_>,
) -> Result<(wgpu::RenderPass<'static>, Option<wgpu::TextureFormat>, Option<wgpu::TextureFormat>), GpuError> {
let texture = |id| self.textures.get(id).ok_or(GpuError::UnknownId("texture"));
let color = desc
.color
.map(|attachment| Ok::<_, GpuError>((texture(attachment.texture)?, attachment.load)))
.transpose()?;
let depth_stencil = desc
.depth_stencil
.map(|attachment| Ok::<_, GpuError>((texture(attachment.texture)?, attachment)))
.transpose()?;
let color_format = color.map(|(texture, _)| texture.texture.format());
let depth_stencil_format = depth_stencil.map(|(texture, _)| texture.texture.format());
let color_attachment = color.map(|(texture, load)| wgpu::RenderPassColorAttachment {
view: texture.attachment(),
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: match load {
LoadOp::Load => wgpu::LoadOp::Load,
LoadOp::Clear(color) => wgpu::LoadOp::Clear(wgpu_color(color)),
},
store: wgpu::StoreOp::Store,
},
});
let depth_stencil_attachment =
depth_stencil.map(|(texture, attachment)| wgpu::RenderPassDepthStencilAttachment {
view: texture.attachment(),
depth_ops: Some(wgpu::Operations {
load: match attachment.depth {
LoadOp::Load => wgpu::LoadOp::Load,
LoadOp::Clear(depth) => wgpu::LoadOp::Clear(depth),
},
store: wgpu::StoreOp::Store,
}),
stencil_ops: texture.texture.format().has_stencil_aspect().then_some(wgpu::Operations {
load: match attachment.stencil {
LoadOp::Load => wgpu::LoadOp::Load,
LoadOp::Clear(stencil) => wgpu::LoadOp::Clear(stencil),
},
store: wgpu::StoreOp::Store,
}),
});
let device = self.device.device();
let encoder = self.encoder.get_or_insert_with(|| {
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
});
#[cfg(feature = "bench")]
let timestamp_writes = self.queries.as_ref().and_then(crate::bench::Queries::timestamp_writes);
#[cfg(not(feature = "bench"))]
let timestamp_writes = None;
let pass = encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some(desc.label),
color_attachments: &[color_attachment],
depth_stencil_attachment,
timestamp_writes,
occlusion_query_set: None,
multiview_mask: None,
})
.forget_lifetime();
Ok((pass, color_format, depth_stencil_format))
}
#[cfg(not(target_family = "wasm"))]
fn wait_for(&self, submission: Option<&wgpu::SubmissionIndex>) -> Result<(), GpuError> {
const WAIT_AGAIN_LIMIT: std::time::Duration = std::time::Duration::from_secs(1);
let device = self.device.device();
let wait = || device.poll(wgpu::PollType::Wait { submission_index: submission.cloned(), timeout: None });
let start = web_time::Instant::now();
let mut waited = wait();
while matches!(waited, Err(wgpu::PollError::Timeout)) && start.elapsed() < WAIT_AGAIN_LIMIT {
waited = wait();
}
waited.map(drop).map_err(|error| GpuError::Invalid(format!("waiting for the GPU: {error}")))
}
fn allocate_uniform(&mut self, size: u64) -> Result<(wgpu::Buffer, u64), GpuError> {
let mut page = self.uniform_page.take();
let allocated =
allocate_in_page(&mut page, size.next_multiple_of(UNIFORM_ALIGNMENT), UNIFORM_ALIGNMENT, || {
self.create_uniform_buffer("uniform page", PAGE)
});
self.uniform_page = page;
allocated
}
fn allocate_geometry(&mut self, size: u64, alignment: u64) -> Result<(wgpu::Buffer, u64), GpuError> {
let mut page = self.geometry_page.take();
let allocated = allocate_in_page(&mut page, size, alignment, || {
self.validated("geometry page", |device| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("geometry page"),
size: PAGE,
usage: VERTEX_USAGES | wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
})
});
self.geometry_page = page;
allocated
}
fn create_uniform_buffer(&self, label: &str, size: u64) -> Result<wgpu::Buffer, GpuError> {
self.validated(label, |device| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
})
}
fn validated<T>(&self, what: &str, create: impl FnOnce(&wgpu::Device) -> T) -> Result<T, GpuError> {
let device = self.device.device();
validated(device, || create(device)).map_err(|error| GpuError::Invalid(format!("{what}: {error}")))
}
}
fn allocate_in_page(
page: &mut Option<(wgpu::Buffer, u64)>,
size: u64,
alignment: u64,
create: impl FnOnce() -> Result<wgpu::Buffer, GpuError>,
) -> Result<(wgpu::Buffer, u64), GpuError> {
let (buffer, taken) = match page {
Some((buffer, taken)) if taken.next_multiple_of(alignment) + size <= PAGE => (buffer, taken),
_ => {
let (buffer, taken) = page.insert((create()?, 0));
(buffer, taken)
}
};
let offset = taken.next_multiple_of(alignment);
*taken = offset + size;
Ok((buffer.clone(), offset))
}
fn texture_info(texture: &wgpu::Texture) -> TextureInfo {
let usage = texture.usage();
TextureInfo {
format: from_wgpu_format(texture.format()),
size: Size { width: texture.width(), height: texture.height() },
usage: TextureUsage {
sampled: usage.contains(wgpu::TextureUsages::TEXTURE_BINDING),
render_target: usage.contains(wgpu::TextureUsages::RENDER_ATTACHMENT),
copy_src: usage.contains(wgpu::TextureUsages::COPY_SRC),
},
}
}
fn wgpu_color(color: Rgba) -> wgpu::Color {
wgpu::Color { r: f64::from(color.r), g: f64::from(color.g), b: f64::from(color.b), a: f64::from(color.a) }
}
fn texture_format(format: TextureFormat) -> wgpu::TextureFormat {
match format {
TextureFormat::R8Unorm | TextureFormat::A8Unorm => wgpu::TextureFormat::R8Unorm,
TextureFormat::R16Float => wgpu::TextureFormat::R16Float,
TextureFormat::R32Float => wgpu::TextureFormat::R32Float,
TextureFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
TextureFormat::Rgba8UnormSrgb => wgpu::TextureFormat::Rgba8UnormSrgb,
TextureFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
TextureFormat::Bgra8UnormSrgb => wgpu::TextureFormat::Bgra8UnormSrgb,
TextureFormat::Rgb10a2Unorm => wgpu::TextureFormat::Rgb10a2Unorm,
TextureFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
TextureFormat::Rgba32Float => wgpu::TextureFormat::Rgba32Float,
TextureFormat::Depth32Float => wgpu::TextureFormat::Depth32Float,
TextureFormat::Depth24PlusStencil8 => wgpu::TextureFormat::Depth24PlusStencil8,
TextureFormat::Depth32FloatStencil8 => wgpu::TextureFormat::Depth32FloatStencil8,
}
}
fn shader_bindings(shader: &ShaderProgram) -> Vec<ShaderBinding> {
let mut bindings = Vec::new();
for &group in shader.bind_group_order() {
if Some(group) == shader.index_group() {
continue;
}
for info in shader.binding_infos(group) {
let binding = match info.kind {
BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer => {
ShaderBinding::Buffer { id: info.binding, min_size: info.min_size }
}
BindingType::Sampler
| BindingType::NonFilteringSampler
| BindingType::Texture
| BindingType::UnfilterableTexture => {
ShaderBinding::Texture { slot: declaration::texture_slot(info.binding) as u32 }
}
};
ShaderBinding::merge(&mut bindings, binding);
}
}
bindings
}
pub(crate) fn from_wgpu_format(format: wgpu::TextureFormat) -> Option<TextureFormat> {
Some(match format {
wgpu::TextureFormat::R8Unorm => TextureFormat::R8Unorm,
wgpu::TextureFormat::R16Float => TextureFormat::R16Float,
wgpu::TextureFormat::R32Float => TextureFormat::R32Float,
wgpu::TextureFormat::Rgba8Unorm => TextureFormat::Rgba8Unorm,
wgpu::TextureFormat::Rgba8UnormSrgb => TextureFormat::Rgba8UnormSrgb,
wgpu::TextureFormat::Bgra8Unorm => TextureFormat::Bgra8Unorm,
wgpu::TextureFormat::Bgra8UnormSrgb => TextureFormat::Bgra8UnormSrgb,
wgpu::TextureFormat::Rgb10a2Unorm => TextureFormat::Rgb10a2Unorm,
wgpu::TextureFormat::Rgba16Float => TextureFormat::Rgba16Float,
wgpu::TextureFormat::Rgba32Float => TextureFormat::Rgba32Float,
wgpu::TextureFormat::Depth32Float => TextureFormat::Depth32Float,
wgpu::TextureFormat::Depth24PlusStencil8 => TextureFormat::Depth24PlusStencil8,
wgpu::TextureFormat::Depth32FloatStencil8 => TextureFormat::Depth32FloatStencil8,
_ => return None,
})
}
impl Gpu for WebGpu {
fn caps(&self) -> &Caps {
&self.caps
}
fn create_buffer(&mut self, desc: &BufferDesc<'_>) -> Result<BufferId, GpuError> {
let size = desc.size.next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT);
let usage = match desc.usage {
BufferUsage::Vertex | BufferUsage::Index if size <= PAGE / 4 => {
let alignment = match desc.usage {
BufferUsage::Vertex => self.storage_alignment,
_ => wgpu::COPY_BUFFER_ALIGNMENT,
};
let (buffer, offset) = self.allocate_geometry(size, alignment)?;
let written = Some(0);
return Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset, size, written }));
}
BufferUsage::Vertex => VERTEX_USAGES,
BufferUsage::Index => wgpu::BufferUsages::INDEX,
BufferUsage::Uniform | BufferUsage::Storage => {
let (buffer, offset, written) = if size <= PAGE / 4 {
let (page, offset) = self.allocate_uniform(size)?;
(page, offset, Some(0))
} else {
(self.create_uniform_buffer(desc.label, size)?, 0, None)
};
return Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset, size, written }));
}
};
let buffer = self.validated(desc.label, |device| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(desc.label),
size,
usage: usage | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
})?;
Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset: 0, size, written: None }))
}
fn write_buffer(&mut self, buffer: BufferId, offset: u64, data: &[u8]) -> Result<(), GpuError> {
let entry = self.buffers.get_mut(buffer).ok_or(GpuError::UnknownId("buffer"))?;
validation::check_write(offset, data.len(), entry.size)?;
let end = offset + data.len() as u64;
let padded = match &mut entry.written {
Some(written) if end >= *written => {
*written = end;
entry.size - offset
}
_ => data.len() as u64,
};
let (device, queue) = (self.device.device(), self.device.queue());
self.writes.write_padded(device, queue, &entry.buffer, entry.offset + offset, data, padded);
Ok(())
}
#[cfg(target_family = "wasm")]
fn write_buffer_from_host(
&mut self,
buffer: BufferId,
offset: u64,
data: &js_sys::Uint8Array,
) -> Result<(), GpuError> {
let entry = self.buffers.get_mut(buffer).ok_or(GpuError::UnknownId("buffer"))?;
let len = data.length() as usize;
validation::check_write(offset, len.next_multiple_of(4), entry.size)?;
let len = len as u64;
if let Some(written) = &mut entry.written {
*written = (*written).max(offset + len);
}
let (device, queue) = (self.device.device(), self.device.queue());
let at = entry.offset + offset;
let aligned = len & !(wgpu::COPY_BUFFER_ALIGNMENT - 1);
self.writes.write_from_host(device, queue, &entry.buffer, at, data, aligned);
if aligned < len {
let mut tail = [0u8; wgpu::COPY_BUFFER_ALIGNMENT as usize];
data.subarray(aligned as u32, len as u32).copy_to(&mut tail[..(len - aligned) as usize]);
self.writes.write_padded(device, queue, &entry.buffer, at + aligned, &tail, wgpu::COPY_BUFFER_ALIGNMENT);
}
Ok(())
}
fn create_texture(&mut self, desc: &TextureDesc<'_>) -> Result<TextureId, GpuError> {
let mip_level_count = validation::check_mips(desc)?;
let mut usage = wgpu::TextureUsages::empty();
if desc.usage.sampled {
usage |= wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST;
}
if desc.usage.render_target {
usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
}
if desc.usage.copy_src {
usage |= wgpu::TextureUsages::COPY_SRC;
}
let format = texture_format(desc.format);
if desc.mipmapped {
usage |= if format == wgpu::TextureFormat::Rgba8Unorm
&& crate::mipmaps::computes(&self.device.device().limits())
{
wgpu::TextureUsages::STORAGE_BINDING
} else {
wgpu::TextureUsages::RENDER_ATTACHMENT
};
}
let required = format.required_features();
if !self.device.device().features().contains(required) {
return Err(GpuError::Unsupported(format!("{:?} textures need {required:?}", desc.format)));
}
let texture = self.validated(desc.label, |device| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(desc.label),
size: wgpu::Extent3d { width: desc.size.width, height: desc.size.height, depth_or_array_layers: 1 },
mip_level_count,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
})?;
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let levels = if desc.mipmapped {
let level = |base_mip_level| wgpu::TextureViewDescriptor {
base_mip_level,
mip_level_count: Some(1),
..Default::default()
};
(0..mip_level_count).map(|base| texture.create_view(&level(base))).collect()
} else {
Vec::new()
};
Ok(self.textures.insert(Texture { texture, view, levels, mip_groups: Vec::new() }))
}
fn write_texture(&mut self, texture: TextureId, region: TextureRegion, data: &[u8]) -> Result<(), GpuError> {
let texture = &self.textures.get(texture).ok_or(GpuError::UnknownId("texture"))?.texture;
if !texture.usage().contains(wgpu::TextureUsages::COPY_DST) {
return Err(GpuError::Invalid("a write to a texture that isn't sampled".to_owned()));
}
let format = from_wgpu_format(texture.format())
.ok_or_else(|| GpuError::Invalid(format!("{:?} textures take no writes", texture.format())))?;
let size = Size::new(texture.width(), texture.height());
let bytes_per_row = region.write_bytes_per_row(size, format, data)?;
self.device.queue().write_texture(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d { x: region.x, y: region.y, z: 0 },
aspect: wgpu::TextureAspect::All,
},
data,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(bytes_per_row as u32),
rows_per_image: Some(region.size.height),
},
wgpu::Extent3d { width: region.size.width, height: region.size.height, depth_or_array_layers: 1 },
);
self.writes.note_queue_write();
Ok(())
}
fn generate_mipmaps(&mut self, texture: TextureId) -> Result<(), GpuError> {
if self.pass.is_some() {
return Err(open_pass("generating mips"));
}
let texture = self.textures.get_mut(texture).ok_or(GpuError::UnknownId("texture"))?;
if texture.levels.is_empty() {
return Err(GpuError::Invalid("generating the mips of a texture without them".to_owned()));
}
let device = self.device.device();
let encoder = self.encoder.get_or_insert_with(|| {
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
});
let mipmapper = self.mipmapper.get_or_insert_with(|| Mipmapper::new(device));
if texture.texture.usage().contains(wgpu::TextureUsages::STORAGE_BINDING) {
let size = texture.texture.size();
mipmapper.generate_in_compute(
device,
encoder,
size,
&texture.levels,
&mut texture.mip_groups,
#[cfg(feature = "bench")]
self.queries.as_mut(),
);
return Ok(());
}
mipmapper.generate(
device,
encoder,
texture.texture.format(),
&texture.levels,
#[cfg(feature = "bench")]
self.queries.as_mut(),
);
Ok(())
}
fn create_sampler(&mut self, state: SamplerState) -> Result<SamplerId, GpuError> {
let filter = match state.filter {
TextureFilterType::Linear => wgpu::FilterMode::Linear,
TextureFilterType::Nearest => wgpu::FilterMode::Nearest,
};
let address_mode = |wrap| match wrap {
TextureWrapType::Repeat => wgpu::AddressMode::Repeat,
TextureWrapType::Clamp => wgpu::AddressMode::ClampToEdge,
};
let sampler = self.validated("sampler", |device| {
device.create_sampler(&wgpu::SamplerDescriptor {
label: None,
address_mode_u: address_mode(state.wrap_u),
address_mode_v: address_mode(state.wrap_v),
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: filter,
min_filter: filter,
mipmap_filter: if state.mipmapped {
wgpu::MipmapFilterMode::Linear
} else {
wgpu::MipmapFilterMode::Nearest
},
lod_max_clamp: if state.mipmapped { 32.0 } else { 0.0 },
anisotropy_clamp: u16::from(state.anisotropy()),
..Default::default()
})
})?;
Ok(self.samplers.insert(sampler))
}
fn create_shader(&mut self, key: &ShaderKey) -> Result<ShaderId, GpuError> {
let declared = key.program();
let source =
declared.sources.wgsl.ok_or_else(|| GpuError::Unsupported(format!("{} has no WGSL", declared.name)))?;
let program = shader_program::compile(self.device.device(), self.index_table.layout(), key, source)?;
let reads = shader_bindings(&program);
Ok(self.shaders.insert(Shader { program, reads }))
}
fn create_pipeline(&mut self, desc: &PipelineDesc<'_>) -> Result<PipelineId, GpuError> {
let shader = self.shaders.require(desc.shader)?;
let pipeline = shader.program.render_pipeline(
desc.vertex_buffers,
&desc.state,
desc.targets.color.map(texture_format),
desc.targets.depth_stencil.map(texture_format),
)?;
let layout = self.layout_tags.tag(desc.shader, desc.vertex_buffers);
let tags = PipelineTags { shader: desc.shader, layout, targets: desc.targets };
Ok(self.dependents.insert_pipeline(&mut self.pipelines, desc.shader, Pipeline { pipeline, tags }))
}
fn create_bindings(&mut self, desc: &BindingsDesc<'_>) -> Result<BindingsId, GpuError> {
let shader = self.shaders.require(desc.shader)?;
let elements = {
let (buffer, texture) = self.info();
let sampler = |id| self.samplers.contains_key(id);
let lookup = Lookup { buffer: &buffer, texture: &texture, sampler: &sampler };
validation::check_bindings(
desc,
&shader.reads,
self.caps.buffer_offset_alignment,
self.caps.binds_vertex_buffers,
&lookup,
)?
};
let program = &shader.program;
let mut groups = Vec::new();
let mut index_slot = None;
for &group in program.bind_group_order() {
if Some(group) == program.index_group() {
index_slot = Some(group);
continue;
}
let layout = program.bind_group_layout(group).ok_or(GpuError::UnknownId("bind group layout"))?;
let mut entries = Vec::new();
let mut bound = Vec::new();
for info in program.binding_infos(group) {
let missing = || {
GpuError::Invalid(format!(
"{} reads binding {} of group {}, which no entry binds",
program.name(),
info.binding,
info.group
))
};
let resource = match info.kind {
BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer => {
let (buffer, offset, size) = desc.buffer(info.binding).ok_or_else(missing)?;
bound.push(BindGroupEntry::Buffer { id: info.binding, buffer, offset, size });
let buffer = self.buffers.require(buffer)?;
wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &buffer.buffer,
offset: buffer.offset + offset,
size: wgpu::BufferSize::new(size),
})
}
BindingType::Sampler
| BindingType::NonFilteringSampler
| BindingType::Texture
| BindingType::UnfilterableTexture => {
let sampler = matches!(info.kind, BindingType::Sampler | BindingType::NonFilteringSampler);
let texture_slot = declaration::texture_slot(info.binding) as u32;
let (texture, texture_sampler) = desc.texture(texture_slot).ok_or_else(missing)?;
bound.push(BindGroupEntry::Texture { slot: texture_slot, texture, sampler: texture_sampler });
if sampler {
wgpu::BindingResource::Sampler(self.samplers.require(texture_sampler)?)
} else {
wgpu::BindingResource::TextureView(&self.textures.require(texture)?.view)
}
}
};
entries.push(wgpu::BindGroupEntry { binding: info.binding, resource });
}
let bind_group = self.validated(desc.label, |device| {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some(desc.label),
layout,
entries: &entries,
})
})?;
groups.push(BindGroup { slot: group, group: bind_group, entries: bound });
}
let tags = BindingsTags { shader: desc.shader, elements };
Ok(self.dependents.insert_bindings(&mut self.bindings, desc, Bindings { groups, index_slot, tags }))
}
fn create_geometry(&mut self, desc: &GeometryDesc<'_>) -> Result<GeometryId, GpuError> {
self.shaders.check(desc.shader)?;
let ranges = {
let (buffer, _) = self.info();
validation::check_geometry(desc, &buffer)?
};
let native = |id: BufferId, offset: u64| {
let buffer = self.buffers.require(id)?;
Ok::<_, GpuError>((buffer.buffer.clone(), buffer.offset + offset..buffer.offset + buffer.size))
};
let vertex_buffers =
desc.vertex_buffers.iter().map(|&(id, offset)| native(id, offset)).collect::<Result<Vec<_>, _>>()?;
let index_buffer = native(desc.index_buffer, 0)?;
let tags = GeometryTags { layout: self.layout_tags.tag(desc.shader, desc.layouts), ranges };
Ok(self.dependents.insert_geometry(
&mut self.geometries,
desc,
Geometry {
vertex_buffers,
index_buffer,
vertex_ids: desc.vertex_buffers.to_vec(),
index_id: (desc.index_buffer, 0),
tags,
},
))
}
fn destroy(&mut self, resource: ResourceId) -> Result<(), GpuError> {
self.dependents.destroy(resource)?;
match resource {
ResourceId::Buffer(id) => drop(self.buffers.remove(id)),
ResourceId::Texture(id) => drop(self.textures.remove(id)),
ResourceId::Sampler(id) => drop(self.samplers.remove(id)),
ResourceId::Shader(id) => drop(self.shaders.remove(id)),
ResourceId::Pipeline(id) => drop(self.pipelines.remove(id)),
ResourceId::Bindings(id) => drop(self.bindings.remove(id)),
ResourceId::Geometry(id) => drop(self.geometries.remove(id)),
ResourceId::Readback(id) => drop(self.readbacks.remove(id)),
}
Ok(())
}
fn begin_pass(&mut self, desc: &PassDesc<'_>) -> Result<(), GpuError> {
if self.pass.is_some() {
return Err(open_pass("a pass"));
}
let target = {
let (_, texture) = self.info();
validation::check_pass(desc, &texture)?
};
#[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only the benchmarks' builds count the pass"))]
let (mut pass, color_format, depth_stencil_format) = self.begin_render_pass(desc)?;
#[cfg(feature = "bench")]
let counted = self.queries.as_mut().is_some_and(|queries| queries.begin(&mut pass));
self.pass = Some(OpenPass {
#[cfg(feature = "bench")]
counted,
pass,
state: PassState::with_dynamic(
target,
DynamicState {
depth_range: (0.0, 1.0),
scissor: Scissor::whole(target.size),
stencil_reference: 0,
blend_constant: Rgba::new(0.0, 0.0, 0.0, 0.0),
line_width: 1.0,
},
),
color_format,
depth_stencil_format,
vertex_buffers: Vec::new(),
index_buffer: None,
groups: Vec::new(),
});
Ok(())
}
fn draw(&mut self, draw: &Draw) -> Result<(), GpuError> {
let open = self.pass.as_mut().ok_or_else(|| no_pass("a draw"))?;
let pipeline = self.pipelines.require(draw.pipeline)?;
let bindings = self.bindings.require(draw.bindings)?;
let geometry = self.geometries.require(draw.geometry)?;
validation::check_draw(draw, open.state.target.targets, &pipeline.tags, &bindings.tags, &geometry.tags)?;
let pass = &mut open.pass;
if open.state.set_pipeline(draw.pipeline) {
pass.set_pipeline(&pipeline.pipeline);
}
let bindings_changed = open.state.set_bindings(draw.bindings);
if bindings_changed {
for group in &bindings.groups {
let slot = group.slot as usize;
if open.groups.len() <= slot {
open.groups.resize(slot + 1, None);
}
let held = open.groups[slot].replace(draw.bindings).and_then(|id| self.bindings.get(id));
let holds = held.is_some_and(|held| {
held.tags.shader == bindings.tags.shader
&& held.groups.iter().any(|held| held.slot == group.slot && held.entries == group.entries)
});
if !holds {
pass.set_bind_group(group.slot, &group.group, &[]);
}
}
}
if let Some(slot) = bindings.index_slot
&& (bindings_changed || open.state.global_index != Some(draw.global_index))
{
self.index_table.reserve(self.device.device(), self.device.queue(), draw.global_index);
let (group, offset) = self
.index_table
.get(draw.global_index)
.ok_or_else(|| GpuError::Invalid(format!("global index {}", draw.global_index)))?;
pass.set_bind_group(slot, group, &[offset]);
open.state.global_index = Some(draw.global_index);
if let Some(held) = open.groups.get_mut(slot as usize) {
*held = None;
}
}
if open.state.set_geometry(draw.geometry) {
for (slot, ((buffer, range), id)) in geometry.vertex_buffers.iter().zip(&geometry.vertex_ids).enumerate() {
if open.vertex_buffers.get(slot) != Some(id) {
pass.set_vertex_buffer(slot as u32, buffer.slice(range.clone()));
match open.vertex_buffers.get_mut(slot) {
Some(bound) => *bound = *id,
None => open.vertex_buffers.push(*id),
}
}
}
if open.index_buffer != Some(geometry.index_id) {
let (buffer, range) = &geometry.index_buffer;
pass.set_index_buffer(buffer.slice(range.clone()), wgpu::IndexFormat::Uint16);
open.index_buffer = Some(geometry.index_id);
}
}
let changes = open.state.update_dynamic(draw.dynamic);
if let Some((min, max)) = changes.depth_range {
let size = open.state.target.size;
pass.set_viewport(0.0, 0.0, size.width as f32, size.height as f32, min, max);
}
if let Some(Scissor { x, y, width, height }) = changes.scissor {
pass.set_scissor_rect(x, y, width, height);
}
if let Some(reference) = changes.stencil_reference {
pass.set_stencil_reference(reference);
}
if let Some(color) = changes.blend_constant {
pass.set_blend_constant(wgpu_color(color));
}
let indices = draw.first_index..draw.first_index + draw.index_count;
let instances = draw.first_instance..draw.first_instance + draw.instance_count;
pass.draw_indexed(indices, draw.base_vertex, instances);
Ok(())
}
fn lend(&mut self, f: &mut dyn FnMut(&mut dyn Any)) -> Result<(), GpuError> {
let (device, queue) = (self.device.device().clone(), self.device.queue().clone());
if let Some(mut open) = self.pass.take() {
let Some(color_format) = open.color_format else {
self.pass = Some(open);
return Err(GpuError::Unsupported("a custom layer's pass without a color attachment".to_owned()));
};
let depth_stencil_format = open.depth_stencil_format;
let mut lent =
CustomLayerPass { device, queue, pass: open.pass, color_format, depth_stencil_format, sample_count: 1 };
f(&mut lent);
open.pass = lent.pass;
open.forget_state();
self.pass = Some(open);
return Ok(());
}
let encoder = self
.encoder
.take()
.unwrap_or_else(|| device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") }));
let mut lent = CustomLayerEncoder { device, queue, encoder };
f(&mut lent);
self.encoder = Some(lent.encoder);
Ok(())
}
fn end_pass(&mut self) -> Result<(), GpuError> {
#[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only the benchmarks' builds count the pass"))]
let mut open = self.pass.take().ok_or_else(|| no_pass("the end of a pass"))?;
#[cfg(feature = "bench")]
if open.counted {
crate::bench::Queries::end(&mut open.pass);
}
drop(open);
Ok(())
}
fn flush(&mut self, wait: bool) -> Result<(), GpuError> {
if self.pass.is_some() {
return Err(open_pass("a flush"));
}
if !wait && self.encoder.is_none() && self.writes.is_empty() {
return Ok(());
}
let submission = self.submit(|_| {})?;
#[cfg(not(target_family = "wasm"))]
if wait {
return self.wait_for(Some(&submission));
}
let _ = (wait, submission);
Ok(())
}
fn read_texture(&mut self, texture: TextureId, region: TextureRegion) -> Result<ReadbackId, GpuError> {
if self.pass.is_some() {
return Err(open_pass("a readback"));
}
let texture = self.textures.get(texture).map(|texture| texture.texture.clone());
let readback = validation::check_readback(texture.as_ref().map(texture_info), region)?;
let texture = texture.ok_or(GpuError::UnknownId("texture"))?;
let padded_bytes_per_row = readback.bytes_per_row.next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize);
let (width, rows) = (region.size.width, region.size.height);
let size = (padded_bytes_per_row * rows as usize) as u64;
let buffer = match self.spare_readback.take() {
Some(buffer) if buffer.size() == size => buffer,
_ => self.validated("readback", |device| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("readback"),
size,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
})
})?,
};
let submission = self.submit(|encoder| {
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d { x: region.x, y: region.y, z: 0 },
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded_bytes_per_row as u32),
rows_per_image: Some(rows),
},
},
wgpu::Extent3d { width, height: rows, depth_or_array_layers: 1 },
);
})?;
let mapped = Arc::new(OnceLock::new());
let map_ended = Arc::clone(&mapped);
buffer.map_async(wgpu::MapMode::Read, .., move |result| {
let _ = map_ended.set(result);
});
Ok(self.readbacks.insert(Readback {
buffer,
padded_bytes_per_row,
bytes_per_row: readback.bytes_per_row,
rows: rows as usize,
submission,
mapped,
}))
}
fn take_readback(&mut self, readback: ReadbackId, wait: bool) -> Result<Option<Vec<u8>>, GpuError> {
let entry = self.readbacks.get(readback).ok_or(GpuError::UnknownId("readback"))?;
let mapped = Arc::clone(&entry.mapped);
if mapped.get().is_none() {
#[cfg(not(target_family = "wasm"))]
if wait {
if let Err(error) = self.wait_for(Some(&entry.submission)) {
self.readbacks.remove(readback);
return Err(error);
}
} else {
let _ = self.device.device().poll(wgpu::PollType::Poll);
}
#[cfg(target_family = "wasm")]
let _ = wait;
}
let Some(mapped) = mapped.get() else {
return Ok(None);
};
let Readback { buffer, padded_bytes_per_row, bytes_per_row, rows, .. } =
self.readbacks.remove(readback).ok_or(GpuError::UnknownId("readback"))?;
if let Err(error) = mapped {
return Err(GpuError::Invalid(format!("mapping a readback: {error}")));
}
let texels = {
let range = buffer
.get_mapped_range(..)
.map_err(|error| GpuError::Invalid(format!("a readback's range: {error}")))?;
if padded_bytes_per_row == bytes_per_row {
range[..bytes_per_row * rows].to_vec()
} else {
let mut texels = Vec::with_capacity(bytes_per_row * rows);
for row in range.chunks(padded_bytes_per_row).take(rows) {
texels.extend_from_slice(&row[..bytes_per_row]);
}
texels
}
};
buffer.unmap();
self.spare_readback = Some(buffer);
Ok(Some(texels))
}
}