Skip to main content

mln_webgpu/
gpu.rs

1//! The [`Gpu`] interface on wgpu.
2
3use std::any::Any;
4use std::ops::Range;
5use std::sync::{Arc, OnceLock};
6
7use mln_gfx::gpu::validation::{
8    self, BindingsTags, BufferInfo, GeometryTags, LayoutTags, Lookup, PipelineTags, ShaderBinding, TextureInfo,
9    no_pass, open_pass,
10};
11use mln_gfx::gpu::{
12    BindGroupEntry, BindingsDesc, BindingsId, BufferDesc, BufferId, BufferUsage, Caps, ClipDepthRange, Draw,
13    DynamicState, GeometryDesc, GeometryId, Gpu, GpuError, LoadOp, PassDesc, PassState, PipelineDesc, PipelineId,
14    ReadbackId, ResourceId, SamplerId, Scissor, ShaderId, ShaderKey, SlotMap, TextureDesc, TextureFormat, TextureId,
15    TextureRegion, TextureUsage,
16};
17use mln_gfx::texture2d::SamplerState;
18use mln_gfx::types::{TextureFilterType, TextureWrapType};
19use mln_gfx::{Rgba, Size};
20
21use crate::index_table::IndexTable;
22use crate::mipmaps::Mipmapper;
23use crate::shaders::declaration;
24use crate::shaders::shader_program::{self, BindingType, ShaderProgram, validated};
25use crate::writes::Writes;
26use crate::{CustomLayerEncoder, CustomLayerPass, Device};
27
28/// The size of the buffers that small buffers share: uniform and storage
29/// buffers in one kind of page, vertex and index buffers in another.
30const PAGE: u64 = 16 << 10;
31
32/// How a vertex buffer binds: to a draw's vertex buffer slots, and as a
33/// storage buffer that a shader reads by vertex index
34/// (`Caps::binds_vertex_buffers`).
35const VERTEX_USAGES: wgpu::BufferUsages = wgpu::BufferUsages::VERTEX.union(wgpu::BufferUsages::STORAGE);
36
37/// The most storage buffers that a program's vertex stage reads, which a
38/// device's `max_storage_buffers_per_shader_stage` has to allow for its
39/// bindings to bind vertex buffers (`Caps::binds_vertex_buffers`). A device
40/// that allows fewer, such as one made with
41/// `wgpu::Limits::downlevel_defaults()`, draws instances instead.
42pub(crate) const VERTEX_STAGE_STORAGE_BUFFERS: u32 = 5;
43
44/// The alignment of a small uniform or storage buffer in its page: WebGPU's
45/// largest allowed `minUniformBufferOffsetAlignment`, so an offset any
46/// device binds.
47const UNIFORM_ALIGNMENT: u64 = 256;
48
49/// A buffer, or the part of a shared page that a small buffer takes.
50struct Buffer {
51    buffer: wgpu::Buffer,
52    usage: BufferUsage,
53    /// Where the buffer starts in `buffer`.
54    offset: u64,
55    /// The bytes of `buffer` from `offset` that the buffer takes, which
56    /// its writes and bindings stay in.
57    size: u64,
58    /// Of a buffer in a page, the end of the bytes written so far: those
59    /// after it still hold the zeros it was made with. `None` for a buffer
60    /// of its own.
61    written: Option<u64>,
62}
63
64struct Texture {
65    texture: wgpu::Texture,
66    /// The view of every level, which shaders sample.
67    view: wgpu::TextureView,
68    /// Of a texture with mips, a view of each level, which passes draw into
69    /// level 0 of.
70    levels: Vec<wgpu::TextureView>,
71    /// Of a texture whose mips a compute pass writes, what the write of each
72    /// level binds, made when its mips are first written.
73    mip_groups: Vec<wgpu::BindGroup>,
74}
75
76impl Texture {
77    /// The view of level 0, which passes draw into.
78    fn attachment(&self) -> &wgpu::TextureView {
79        self.levels.first().unwrap_or(&self.view)
80    }
81}
82
83/// A compiled program, and what it reads from its bindings.
84struct Shader {
85    program: ShaderProgram,
86    reads: Vec<ShaderBinding>,
87}
88
89struct Pipeline {
90    pipeline: wgpu::RenderPipeline,
91    tags: PipelineTags,
92}
93
94/// A shader's bind groups, by the pipeline layout's slot, and the slot of
95/// its group of `globalIndex`.
96struct Bindings {
97    groups: Vec<BindGroup>,
98    index_slot: Option<u32>,
99    tags: BindingsTags,
100}
101
102/// A bind group, the slot it binds at, and the entries it binds, which
103/// tell it apart from another bindings' group of the same shader.
104struct BindGroup {
105    slot: u32,
106    group: wgpu::BindGroup,
107    entries: Vec<BindGroupEntry>,
108}
109
110/// The vertex buffers and the index buffer of a draw, each with the range
111/// of its wgpu buffer that it binds: from its offset to the end of its
112/// buffer, which in a page is short of the page's end.
113struct Geometry {
114    vertex_buffers: Vec<(wgpu::Buffer, Range<u64>)>,
115    index_buffer: (wgpu::Buffer, Range<u64>),
116    /// The ids and offsets of the vertex buffers and of the index buffer,
117    /// which a draw compares with what the pass has bound.
118    vertex_ids: Vec<(BufferId, u64)>,
119    index_id: (BufferId, u64),
120    tags: GeometryTags,
121}
122
123/// A texture's texels, copied into a buffer that the CPU maps.
124struct Readback {
125    buffer: wgpu::Buffer,
126    /// The bytes in each row of `buffer`, which WebGPU pads, and of the
127    /// texels.
128    padded_bytes_per_row: usize,
129    bytes_per_row: usize,
130    rows: usize,
131    #[cfg_attr(target_family = "wasm", expect(dead_code, reason = "a browser can't wait for a submission"))]
132    submission: wgpu::SubmissionIndex,
133    /// How the map ended, once it has.
134    mapped: Arc<OnceLock<Result<(), wgpu::BufferAsyncError>>>,
135}
136
137/// The pass draws record into, and what the draws so far set on it.
138struct OpenPass {
139    pass: wgpu::RenderPass<'static>,
140    /// Whether a pipeline statistics query counts the pass's work.
141    #[cfg(feature = "bench")]
142    counted: bool,
143    state: PassState,
144    /// The wgpu formats of its attachments, which a custom layer's pass
145    /// tells.
146    color_format: Option<wgpu::TextureFormat>,
147    depth_stencil_format: Option<wgpu::TextureFormat>,
148    /// The vertex buffers bound, by slot, and the index buffer, as
149    /// [`Geometry::vertex_ids`]: geometries of other indices or attributes often
150    /// share vertex buffers.
151    vertex_buffers: Vec<(BufferId, u64)>,
152    index_buffer: Option<(BufferId, u64)>,
153    /// The bindings whose group each slot holds, by slot: consecutive
154    /// draws' bindings often bind a group of the same resources.
155    groups: Vec<Option<BindingsId>>,
156}
157
158impl OpenPass {
159    /// Forgets what the draws set, as after a custom layer drew.
160    fn forget_state(&mut self) {
161        self.state.forget();
162        self.vertex_buffers.clear();
163        self.index_buffer = None;
164        self.groups.clear();
165    }
166}
167
168/// A [`Gpu`] on a WebGPU [`Device`].
169///
170/// A shader's groups are WebGPU bind groups, made with the bindings.
171/// `globalIndex` is a dynamic offset into a table of indices. Draws record
172/// into a pass of the frame's command encoder at once, setting only what
173/// changed since the draw before.
174///
175/// Small buffers share larger ones, so that buffers made together sit
176/// together, their writes join one copy, and a frame that remakes many
177/// small buffers makes few wgpu buffers. Writes are gathered and copied into
178/// place ahead of the next flush's commands.
179///
180/// On a browser's WebGPU, a `create_*` call returns before the browser
181/// validates it, so a rejected descriptor reaches the device's
182/// uncaptured-error callback instead of the call's result.
183pub struct WebGpu {
184    device: Device,
185    caps: Caps,
186    index_table: IndexTable,
187    buffers: SlotMap<BufferId, Buffer>,
188    /// The page that small uniform and storage buffers are taken from, and
189    /// how many of its bytes are taken.
190    uniform_page: Option<(wgpu::Buffer, u64)>,
191    /// The page that small vertex and index buffers are taken from, and how
192    /// many of its bytes are taken.
193    geometry_page: Option<(wgpu::Buffer, u64)>,
194    /// The alignment of the offset a storage buffer binds at, which a small
195    /// vertex buffer starts at in its page.
196    storage_alignment: u64,
197    writes: Writes,
198    textures: SlotMap<TextureId, Texture>,
199    samplers: SlotMap<SamplerId, wgpu::Sampler>,
200    shaders: SlotMap<ShaderId, Shader>,
201    layout_tags: LayoutTags,
202    pipelines: SlotMap<PipelineId, Pipeline>,
203    bindings: SlotMap<BindingsId, Bindings>,
204    geometries: SlotMap<GeometryId, Geometry>,
205    dependents: validation::Dependents,
206    readbacks: SlotMap<ReadbackId, Readback>,
207    /// What draws mips, made for the first texture whose mips are made.
208    mipmapper: Option<Mipmapper>,
209    /// The buffer of the last readback taken, which the next readback of
210    /// its size copies into, as a frame read back each time is.
211    spare_readback: Option<wgpu::Buffer>,
212    /// The commands recorded since the last flush.
213    encoder: Option<wgpu::CommandEncoder>,
214    pass: Option<OpenPass>,
215    /// The pipeline statistics and timestamp queries of each pass, where
216    /// the device has them.
217    #[cfg(feature = "bench")]
218    queries: Option<crate::bench::Queries>,
219}
220
221impl WebGpu {
222    /// How many textures the `WebGpu` has, imports included.
223    #[cfg(test)]
224    pub(crate) fn texture_count(&self) -> usize {
225        self.textures.len()
226    }
227
228    #[must_use]
229    pub fn new(device: &Device) -> WebGpu {
230        let limits = device.device().limits();
231        let caps = Caps {
232            buffer_offset_alignment: limits
233                .min_uniform_buffer_offset_alignment
234                .max(limits.min_storage_buffer_offset_alignment),
235            max_texture_size: limits.max_texture_dimension_2d,
236            half_float_render_targets: true,
237            clip_depth: ClipDepthRange::ZeroToOne,
238            render_target_depth: Some(TextureFormat::Depth32Float),
239            clear_stencil_with_pass: false,
240            cpu_rasterizer: device.adapter_info().device_type == wgpu::DeviceType::Cpu,
241            max_line_width: 1.0,
242            binds_vertex_buffers: limits.max_storage_buffers_per_shader_stage >= VERTEX_STAGE_STORAGE_BUFFERS,
243        };
244        WebGpu {
245            index_table: IndexTable::new(device.device()),
246            device: device.clone(),
247            caps,
248            buffers: SlotMap::with_key(),
249            uniform_page: None,
250            geometry_page: None,
251            storage_alignment: u64::from(limits.min_storage_buffer_offset_alignment).max(wgpu::COPY_BUFFER_ALIGNMENT),
252            writes: Writes::default(),
253            textures: SlotMap::with_key(),
254            samplers: SlotMap::with_key(),
255            shaders: SlotMap::with_key(),
256            layout_tags: LayoutTags::default(),
257            pipelines: SlotMap::with_key(),
258            bindings: SlotMap::with_key(),
259            geometries: SlotMap::with_key(),
260            dependents: validation::Dependents::default(),
261            readbacks: SlotMap::with_key(),
262            mipmapper: None,
263            spare_readback: None,
264            #[cfg(feature = "bench")]
265            queries: crate::bench::Queries::new(device.device())
266                .map(|queries| queries.timed(device.device(), device.queue())),
267            encoder: None,
268            pass: None,
269        }
270    }
271
272    /// The device the backend renders on.
273    pub(crate) fn device(&self) -> &Device {
274        &self.device
275    }
276
277    /// Takes a texture made elsewhere, such as a surface's frame, as a
278    /// texture of this backend. Destroying it drops this backend's
279    /// reference.
280    pub fn import_texture(&mut self, texture: &wgpu::Texture) -> TextureId {
281        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
282        self.textures.insert(Texture { texture: texture.clone(), view, levels: Vec::new(), mip_groups: Vec::new() })
283    }
284
285    /// The wgpu texture of `texture`.
286    #[cfg(test)]
287    pub(crate) fn native_texture(&self, texture: TextureId) -> Option<&wgpu::Texture> {
288        self.textures.get(texture).map(|texture| &texture.texture)
289    }
290
291    /// The wgpu buffer that `readback` copies into.
292    #[cfg(test)]
293    pub(crate) fn readback_buffer(&self, readback: ReadbackId) -> Option<&wgpu::Buffer> {
294        self.readbacks.get(readback).map(|readback| &readback.buffer)
295    }
296
297    /// Submits the commands since the last flush after the copies of the
298    /// writes made so far, with `then` recorded after them.
299    fn submit(&mut self, then: impl FnOnce(&mut wgpu::CommandEncoder)) -> Result<wgpu::SubmissionIndex, GpuError> {
300        let mut encoder = self.encoder.take().unwrap_or_else(|| {
301            self.device.device().create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
302        });
303        then(&mut encoder);
304        #[cfg(feature = "bench")]
305        let measured = self.queries.as_mut().and_then(|queries| queries.resolve(self.device.device(), &mut encoder));
306        // wgpu reports what it rejects in the passes when they finish. The
307        // writes stay for the next flush.
308        let command_buffer = self.validated("flush", |_| encoder.finish())?;
309        let writes = self.writes.encode(self.device.device(), self.device.queue());
310        let submission = self.device.queue().submit(writes.into_iter().chain([command_buffer]));
311        self.writes.submitted();
312        #[cfg(feature = "bench")]
313        if let Some(measured) = measured {
314            crate::bench::Queries::read_back(measured);
315        }
316        Ok(submission)
317    }
318
319    fn info(&self) -> (impl Fn(BufferId) -> Option<BufferInfo> + '_, impl Fn(TextureId) -> Option<TextureInfo> + '_) {
320        let buffer =
321            |id| self.buffers.get(id).map(|buffer: &Buffer| BufferInfo { usage: buffer.usage, size: buffer.size });
322        let texture = |id| self.textures.get(id).map(|texture: &Texture| texture_info(&texture.texture));
323        (buffer, texture)
324    }
325
326    /// Begins a pass of `desc`, which the checks passed, on the frame's
327    /// encoder. Returns it, and the formats of its color and depth-stencil
328    /// attachments.
329    fn begin_render_pass(
330        &mut self,
331        desc: &PassDesc<'_>,
332    ) -> Result<(wgpu::RenderPass<'static>, Option<wgpu::TextureFormat>, Option<wgpu::TextureFormat>), GpuError> {
333        let texture = |id| self.textures.get(id).ok_or(GpuError::UnknownId("texture"));
334        let color = desc
335            .color
336            .map(|attachment| Ok::<_, GpuError>((texture(attachment.texture)?, attachment.load)))
337            .transpose()?;
338        let depth_stencil = desc
339            .depth_stencil
340            .map(|attachment| Ok::<_, GpuError>((texture(attachment.texture)?, attachment)))
341            .transpose()?;
342        let color_format = color.map(|(texture, _)| texture.texture.format());
343        let depth_stencil_format = depth_stencil.map(|(texture, _)| texture.texture.format());
344        let color_attachment = color.map(|(texture, load)| wgpu::RenderPassColorAttachment {
345            view: texture.attachment(),
346            depth_slice: None,
347            resolve_target: None,
348            ops: wgpu::Operations {
349                load: match load {
350                    LoadOp::Load => wgpu::LoadOp::Load,
351                    LoadOp::Clear(color) => wgpu::LoadOp::Clear(wgpu_color(color)),
352                },
353                store: wgpu::StoreOp::Store,
354            },
355        });
356        let depth_stencil_attachment =
357            depth_stencil.map(|(texture, attachment)| wgpu::RenderPassDepthStencilAttachment {
358                view: texture.attachment(),
359                depth_ops: Some(wgpu::Operations {
360                    load: match attachment.depth {
361                        LoadOp::Load => wgpu::LoadOp::Load,
362                        LoadOp::Clear(depth) => wgpu::LoadOp::Clear(depth),
363                    },
364                    store: wgpu::StoreOp::Store,
365                }),
366                stencil_ops: texture.texture.format().has_stencil_aspect().then_some(wgpu::Operations {
367                    load: match attachment.stencil {
368                        LoadOp::Load => wgpu::LoadOp::Load,
369                        LoadOp::Clear(stencil) => wgpu::LoadOp::Clear(stencil),
370                    },
371                    store: wgpu::StoreOp::Store,
372                }),
373            });
374        let device = self.device.device();
375        let encoder = self.encoder.get_or_insert_with(|| {
376            device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
377        });
378        #[cfg(feature = "bench")]
379        let timestamp_writes = self.queries.as_ref().and_then(crate::bench::Queries::timestamp_writes);
380        #[cfg(not(feature = "bench"))]
381        let timestamp_writes = None;
382        let pass = encoder
383            .begin_render_pass(&wgpu::RenderPassDescriptor {
384                label: Some(desc.label),
385                color_attachments: &[color_attachment],
386                depth_stencil_attachment,
387                timestamp_writes,
388                occlusion_query_set: None,
389                multiview_mask: None,
390            })
391            .forget_lifetime();
392        Ok((pass, color_format, depth_stencil_format))
393    }
394
395    /// Blocks until the GPU has finished `submission`, or everything
396    /// submitted with `None`.
397    #[cfg(not(target_family = "wasm"))]
398    fn wait_for(&self, submission: Option<&wgpu::SubmissionIndex>) -> Result<(), GpuError> {
399        /// How long the wait goes on asking after waits that reported a
400        /// timeout.
401        const WAIT_AGAIN_LIMIT: std::time::Duration = std::time::Duration::from_secs(1);
402        let device = self.device.device();
403        let wait = || device.poll(wgpu::PollType::Wait { submission_index: submission.cloned(), timeout: None });
404        // A wait without a timeout can still report one: PowerVR's Vulkan
405        // driver on Android ends the wait shortly before the fence value
406        // that wgpu reads afterwards shows the submission finished. Waiting
407        // again returns at once then, so this asks until the value caught up.
408        let start = web_time::Instant::now();
409        let mut waited = wait();
410        while matches!(waited, Err(wgpu::PollError::Timeout)) && start.elapsed() < WAIT_AGAIN_LIMIT {
411            waited = wait();
412        }
413        waited.map(drop).map_err(|error| GpuError::Invalid(format!("waiting for the GPU: {error}")))
414    }
415
416    /// `size` bytes of a page that small uniform and storage buffers share,
417    /// zero filled: the page and their offset in it.
418    fn allocate_uniform(&mut self, size: u64) -> Result<(wgpu::Buffer, u64), GpuError> {
419        let mut page = self.uniform_page.take();
420        let allocated =
421            allocate_in_page(&mut page, size.next_multiple_of(UNIFORM_ALIGNMENT), UNIFORM_ALIGNMENT, || {
422                self.create_uniform_buffer("uniform page", PAGE)
423            });
424        self.uniform_page = page;
425        allocated
426    }
427
428    /// `size` bytes of a page that small vertex and index buffers share,
429    /// zero filled: the page and their offset in it, a multiple of
430    /// `alignment`.
431    fn allocate_geometry(&mut self, size: u64, alignment: u64) -> Result<(wgpu::Buffer, u64), GpuError> {
432        let mut page = self.geometry_page.take();
433        let allocated = allocate_in_page(&mut page, size, alignment, || {
434            self.validated("geometry page", |device| {
435                device.create_buffer(&wgpu::BufferDescriptor {
436                    label: Some("geometry page"),
437                    size: PAGE,
438                    usage: VERTEX_USAGES | wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
439                    mapped_at_creation: false,
440                })
441            })
442        });
443        self.geometry_page = page;
444        allocated
445    }
446
447    /// A buffer that binds as a uniform or a storage buffer.
448    fn create_uniform_buffer(&self, label: &str, size: u64) -> Result<wgpu::Buffer, GpuError> {
449        self.validated(label, |device| {
450            device.create_buffer(&wgpu::BufferDescriptor {
451                label: Some(label),
452                size,
453                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
454                mapped_at_creation: false,
455            })
456        })
457    }
458
459    /// Runs `create` in a validation error scope, as the error of the call
460    /// that `what` names.
461    fn validated<T>(&self, what: &str, create: impl FnOnce(&wgpu::Device) -> T) -> Result<T, GpuError> {
462        let device = self.device.device();
463        validated(device, || create(device)).map_err(|error| GpuError::Invalid(format!("{what}: {error}")))
464    }
465}
466
467/// `size` bytes of `page`, or of a new page that `create` makes when it has
468/// too few left: the page and the offset in it, a multiple of `alignment`.
469fn allocate_in_page(
470    page: &mut Option<(wgpu::Buffer, u64)>,
471    size: u64,
472    alignment: u64,
473    create: impl FnOnce() -> Result<wgpu::Buffer, GpuError>,
474) -> Result<(wgpu::Buffer, u64), GpuError> {
475    let (buffer, taken) = match page {
476        Some((buffer, taken)) if taken.next_multiple_of(alignment) + size <= PAGE => (buffer, taken),
477        _ => {
478            let (buffer, taken) = page.insert((create()?, 0));
479            (buffer, taken)
480        }
481    };
482    let offset = taken.next_multiple_of(alignment);
483    *taken = offset + size;
484    Ok((buffer.clone(), offset))
485}
486
487/// What the checks read of `texture`.
488fn texture_info(texture: &wgpu::Texture) -> TextureInfo {
489    let usage = texture.usage();
490    TextureInfo {
491        format: from_wgpu_format(texture.format()),
492        size: Size { width: texture.width(), height: texture.height() },
493        usage: TextureUsage {
494            sampled: usage.contains(wgpu::TextureUsages::TEXTURE_BINDING),
495            render_target: usage.contains(wgpu::TextureUsages::RENDER_ATTACHMENT),
496            copy_src: usage.contains(wgpu::TextureUsages::COPY_SRC),
497        },
498    }
499}
500
501fn wgpu_color(color: Rgba) -> wgpu::Color {
502    wgpu::Color { r: f64::from(color.r), g: f64::from(color.g), b: f64::from(color.b), a: f64::from(color.a) }
503}
504
505fn texture_format(format: TextureFormat) -> wgpu::TextureFormat {
506    match format {
507        // WGSL reads an alpha texture's one channel as red.
508        TextureFormat::R8Unorm | TextureFormat::A8Unorm => wgpu::TextureFormat::R8Unorm,
509        TextureFormat::R16Float => wgpu::TextureFormat::R16Float,
510        TextureFormat::R32Float => wgpu::TextureFormat::R32Float,
511        TextureFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
512        TextureFormat::Rgba8UnormSrgb => wgpu::TextureFormat::Rgba8UnormSrgb,
513        TextureFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
514        TextureFormat::Bgra8UnormSrgb => wgpu::TextureFormat::Bgra8UnormSrgb,
515        TextureFormat::Rgb10a2Unorm => wgpu::TextureFormat::Rgb10a2Unorm,
516        TextureFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
517        TextureFormat::Rgba32Float => wgpu::TextureFormat::Rgba32Float,
518        TextureFormat::Depth32Float => wgpu::TextureFormat::Depth32Float,
519        TextureFormat::Depth24PlusStencil8 => wgpu::TextureFormat::Depth24PlusStencil8,
520        TextureFormat::Depth32FloatStencil8 => wgpu::TextureFormat::Depth32FloatStencil8,
521    }
522}
523
524/// What `shader` reads from its bindings, by the shaders' ids.
525fn shader_bindings(shader: &ShaderProgram) -> Vec<ShaderBinding> {
526    let mut bindings = Vec::new();
527    for &group in shader.bind_group_order() {
528        if Some(group) == shader.index_group() {
529            continue;
530        }
531        for info in shader.binding_infos(group) {
532            let binding = match info.kind {
533                BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer => {
534                    ShaderBinding::Buffer { id: info.binding, min_size: info.min_size }
535                }
536                BindingType::Sampler
537                | BindingType::NonFilteringSampler
538                | BindingType::Texture
539                | BindingType::UnfilterableTexture => {
540                    ShaderBinding::Texture { slot: declaration::texture_slot(info.binding) as u32 }
541                }
542            };
543            ShaderBinding::merge(&mut bindings, binding);
544        }
545    }
546    bindings
547}
548
549/// The format of `format`, `None` for a format the interface has no name
550/// for.
551pub(crate) fn from_wgpu_format(format: wgpu::TextureFormat) -> Option<TextureFormat> {
552    Some(match format {
553        wgpu::TextureFormat::R8Unorm => TextureFormat::R8Unorm,
554        wgpu::TextureFormat::R16Float => TextureFormat::R16Float,
555        wgpu::TextureFormat::R32Float => TextureFormat::R32Float,
556        wgpu::TextureFormat::Rgba8Unorm => TextureFormat::Rgba8Unorm,
557        wgpu::TextureFormat::Rgba8UnormSrgb => TextureFormat::Rgba8UnormSrgb,
558        wgpu::TextureFormat::Bgra8Unorm => TextureFormat::Bgra8Unorm,
559        wgpu::TextureFormat::Bgra8UnormSrgb => TextureFormat::Bgra8UnormSrgb,
560        wgpu::TextureFormat::Rgb10a2Unorm => TextureFormat::Rgb10a2Unorm,
561        wgpu::TextureFormat::Rgba16Float => TextureFormat::Rgba16Float,
562        wgpu::TextureFormat::Rgba32Float => TextureFormat::Rgba32Float,
563        wgpu::TextureFormat::Depth32Float => TextureFormat::Depth32Float,
564        wgpu::TextureFormat::Depth24PlusStencil8 => TextureFormat::Depth24PlusStencil8,
565        wgpu::TextureFormat::Depth32FloatStencil8 => TextureFormat::Depth32FloatStencil8,
566        _ => return None,
567    })
568}
569
570impl Gpu for WebGpu {
571    fn caps(&self) -> &Caps {
572        &self.caps
573    }
574
575    fn create_buffer(&mut self, desc: &BufferDesc<'_>) -> Result<BufferId, GpuError> {
576        let size = desc.size.next_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT);
577        let usage = match desc.usage {
578            BufferUsage::Vertex | BufferUsage::Index if size <= PAGE / 4 => {
579                // A vertex buffer starts where a storage buffer may bind.
580                let alignment = match desc.usage {
581                    BufferUsage::Vertex => self.storage_alignment,
582                    _ => wgpu::COPY_BUFFER_ALIGNMENT,
583                };
584                let (buffer, offset) = self.allocate_geometry(size, alignment)?;
585                let written = Some(0);
586                return Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset, size, written }));
587            }
588            BufferUsage::Vertex => VERTEX_USAGES,
589            BufferUsage::Index => wgpu::BufferUsages::INDEX,
590            BufferUsage::Uniform | BufferUsage::Storage => {
591                let (buffer, offset, written) = if size <= PAGE / 4 {
592                    let (page, offset) = self.allocate_uniform(size)?;
593                    (page, offset, Some(0))
594                } else {
595                    (self.create_uniform_buffer(desc.label, size)?, 0, None)
596                };
597                return Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset, size, written }));
598            }
599        };
600        let buffer = self.validated(desc.label, |device| {
601            device.create_buffer(&wgpu::BufferDescriptor {
602                label: Some(desc.label),
603                size,
604                usage: usage | wgpu::BufferUsages::COPY_DST,
605                mapped_at_creation: false,
606            })
607        })?;
608        Ok(self.buffers.insert(Buffer { buffer, usage: desc.usage, offset: 0, size, written: None }))
609    }
610
611    fn write_buffer(&mut self, buffer: BufferId, offset: u64, data: &[u8]) -> Result<(), GpuError> {
612        let entry = self.buffers.get_mut(buffer).ok_or(GpuError::UnknownId("buffer"))?;
613        validation::check_write(offset, data.len(), entry.size)?;
614        let end = offset + data.len() as u64;
615        // Where the rest of a buffer in a page still holds its zeros, they
616        // can be written with the data, so that the copy joins the next
617        // buffer's.
618        let padded = match &mut entry.written {
619            Some(written) if end >= *written => {
620                *written = end;
621                entry.size - offset
622            }
623            _ => data.len() as u64,
624        };
625        let (device, queue) = (self.device.device(), self.device.queue());
626        self.writes.write_padded(device, queue, &entry.buffer, entry.offset + offset, data, padded);
627        Ok(())
628    }
629
630    /// Writes from the JS array with `GPUQueue.writeBuffer`
631    /// (`Writes::write_from_host`).
632    #[cfg(target_family = "wasm")]
633    fn write_buffer_from_host(
634        &mut self,
635        buffer: BufferId,
636        offset: u64,
637        data: &js_sys::Uint8Array,
638    ) -> Result<(), GpuError> {
639        let entry = self.buffers.get_mut(buffer).ok_or(GpuError::UnknownId("buffer"))?;
640        let len = data.length() as usize;
641        validation::check_write(offset, len.next_multiple_of(4), entry.size)?;
642        let len = len as u64;
643        // A later write past these bytes pads only past them.
644        if let Some(written) = &mut entry.written {
645            *written = (*written).max(offset + len);
646        }
647        let (device, queue) = (self.device.device(), self.device.queue());
648        let at = entry.offset + offset;
649        let aligned = len & !(wgpu::COPY_BUFFER_ALIGNMENT - 1);
650        self.writes.write_from_host(device, queue, &entry.buffer, at, data, aligned);
651        if aligned < len {
652            // writeBuffer takes whole 4-byte words.
653            let mut tail = [0u8; wgpu::COPY_BUFFER_ALIGNMENT as usize];
654            data.subarray(aligned as u32, len as u32).copy_to(&mut tail[..(len - aligned) as usize]);
655            self.writes.write_padded(device, queue, &entry.buffer, at + aligned, &tail, wgpu::COPY_BUFFER_ALIGNMENT);
656        }
657        Ok(())
658    }
659
660    fn create_texture(&mut self, desc: &TextureDesc<'_>) -> Result<TextureId, GpuError> {
661        let mip_level_count = validation::check_mips(desc)?;
662        let mut usage = wgpu::TextureUsages::empty();
663        if desc.usage.sampled {
664            usage |= wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST;
665        }
666        if desc.usage.render_target {
667            usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
668        }
669        if desc.usage.copy_src {
670            usage |= wgpu::TextureUsages::COPY_SRC;
671        }
672        let format = texture_format(desc.format);
673        // A compute pass writes the mips of a texture that shaders can write,
674        // on a device that runs it, and a render pass for each level those of
675        // another (`generate_mipmaps`).
676        if desc.mipmapped {
677            usage |= if format == wgpu::TextureFormat::Rgba8Unorm
678                && crate::mipmaps::computes(&self.device.device().limits())
679            {
680                wgpu::TextureUsages::STORAGE_BINDING
681            } else {
682                wgpu::TextureUsages::RENDER_ATTACHMENT
683            };
684        }
685        let required = format.required_features();
686        if !self.device.device().features().contains(required) {
687            return Err(GpuError::Unsupported(format!("{:?} textures need {required:?}", desc.format)));
688        }
689        let texture = self.validated(desc.label, |device| {
690            device.create_texture(&wgpu::TextureDescriptor {
691                label: Some(desc.label),
692                size: wgpu::Extent3d { width: desc.size.width, height: desc.size.height, depth_or_array_layers: 1 },
693                mip_level_count,
694                sample_count: 1,
695                dimension: wgpu::TextureDimension::D2,
696                format,
697                usage,
698                view_formats: &[],
699            })
700        })?;
701        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
702        let levels = if desc.mipmapped {
703            let level = |base_mip_level| wgpu::TextureViewDescriptor {
704                base_mip_level,
705                mip_level_count: Some(1),
706                ..Default::default()
707            };
708            (0..mip_level_count).map(|base| texture.create_view(&level(base))).collect()
709        } else {
710            Vec::new()
711        };
712        Ok(self.textures.insert(Texture { texture, view, levels, mip_groups: Vec::new() }))
713    }
714
715    fn write_texture(&mut self, texture: TextureId, region: TextureRegion, data: &[u8]) -> Result<(), GpuError> {
716        let texture = &self.textures.get(texture).ok_or(GpuError::UnknownId("texture"))?.texture;
717        if !texture.usage().contains(wgpu::TextureUsages::COPY_DST) {
718            return Err(GpuError::Invalid("a write to a texture that isn't sampled".to_owned()));
719        }
720        let format = from_wgpu_format(texture.format())
721            .ok_or_else(|| GpuError::Invalid(format!("{:?} textures take no writes", texture.format())))?;
722        let size = Size::new(texture.width(), texture.height());
723        let bytes_per_row = region.write_bytes_per_row(size, format, data)?;
724        self.device.queue().write_texture(
725            wgpu::TexelCopyTextureInfo {
726                texture,
727                mip_level: 0,
728                origin: wgpu::Origin3d { x: region.x, y: region.y, z: 0 },
729                aspect: wgpu::TextureAspect::All,
730            },
731            data,
732            wgpu::TexelCopyBufferLayout {
733                offset: 0,
734                bytes_per_row: Some(bytes_per_row as u32),
735                rows_per_image: Some(region.size.height),
736            },
737            wgpu::Extent3d { width: region.size.width, height: region.size.height, depth_or_array_layers: 1 },
738        );
739        self.writes.note_queue_write();
740        Ok(())
741    }
742
743    /// Draws each level from the one before, in a pass of its own.
744    fn generate_mipmaps(&mut self, texture: TextureId) -> Result<(), GpuError> {
745        if self.pass.is_some() {
746            return Err(open_pass("generating mips"));
747        }
748        let texture = self.textures.get_mut(texture).ok_or(GpuError::UnknownId("texture"))?;
749        if texture.levels.is_empty() {
750            return Err(GpuError::Invalid("generating the mips of a texture without them".to_owned()));
751        }
752        let device = self.device.device();
753        let encoder = self.encoder.get_or_insert_with(|| {
754            device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") })
755        });
756        let mipmapper = self.mipmapper.get_or_insert_with(|| Mipmapper::new(device));
757        if texture.texture.usage().contains(wgpu::TextureUsages::STORAGE_BINDING) {
758            let size = texture.texture.size();
759            mipmapper.generate_in_compute(
760                device,
761                encoder,
762                size,
763                &texture.levels,
764                &mut texture.mip_groups,
765                #[cfg(feature = "bench")]
766                self.queries.as_mut(),
767            );
768            return Ok(());
769        }
770        mipmapper.generate(
771            device,
772            encoder,
773            texture.texture.format(),
774            &texture.levels,
775            #[cfg(feature = "bench")]
776            self.queries.as_mut(),
777        );
778        Ok(())
779    }
780
781    fn create_sampler(&mut self, state: SamplerState) -> Result<SamplerId, GpuError> {
782        let filter = match state.filter {
783            TextureFilterType::Linear => wgpu::FilterMode::Linear,
784            TextureFilterType::Nearest => wgpu::FilterMode::Nearest,
785        };
786        let address_mode = |wrap| match wrap {
787            TextureWrapType::Repeat => wgpu::AddressMode::Repeat,
788            TextureWrapType::Clamp => wgpu::AddressMode::ClampToEdge,
789        };
790        let sampler = self.validated("sampler", |device| {
791            device.create_sampler(&wgpu::SamplerDescriptor {
792                label: None,
793                address_mode_u: address_mode(state.wrap_u),
794                address_mode_v: address_mode(state.wrap_v),
795                address_mode_w: wgpu::AddressMode::ClampToEdge,
796                mag_filter: filter,
797                min_filter: filter,
798                mipmap_filter: if state.mipmapped {
799                    wgpu::MipmapFilterMode::Linear
800                } else {
801                    wgpu::MipmapFilterMode::Nearest
802                },
803                // Without mips, level 0 only.
804                lod_max_clamp: if state.mipmapped { 32.0 } else { 0.0 },
805                anisotropy_clamp: u16::from(state.anisotropy()),
806                ..Default::default()
807            })
808        })?;
809        Ok(self.samplers.insert(sampler))
810    }
811
812    fn create_shader(&mut self, key: &ShaderKey) -> Result<ShaderId, GpuError> {
813        let declared = key.program();
814        let source =
815            declared.sources.wgsl.ok_or_else(|| GpuError::Unsupported(format!("{} has no WGSL", declared.name)))?;
816        let program = shader_program::compile(self.device.device(), self.index_table.layout(), key, source)?;
817        let reads = shader_bindings(&program);
818        Ok(self.shaders.insert(Shader { program, reads }))
819    }
820
821    fn create_pipeline(&mut self, desc: &PipelineDesc<'_>) -> Result<PipelineId, GpuError> {
822        let shader = self.shaders.require(desc.shader)?;
823        let pipeline = shader.program.render_pipeline(
824            desc.vertex_buffers,
825            &desc.state,
826            desc.targets.color.map(texture_format),
827            desc.targets.depth_stencil.map(texture_format),
828        )?;
829        let layout = self.layout_tags.tag(desc.shader, desc.vertex_buffers);
830        let tags = PipelineTags { shader: desc.shader, layout, targets: desc.targets };
831        Ok(self.dependents.insert_pipeline(&mut self.pipelines, desc.shader, Pipeline { pipeline, tags }))
832    }
833
834    fn create_bindings(&mut self, desc: &BindingsDesc<'_>) -> Result<BindingsId, GpuError> {
835        let shader = self.shaders.require(desc.shader)?;
836        let elements = {
837            let (buffer, texture) = self.info();
838            let sampler = |id| self.samplers.contains_key(id);
839            let lookup = Lookup { buffer: &buffer, texture: &texture, sampler: &sampler };
840            validation::check_bindings(
841                desc,
842                &shader.reads,
843                self.caps.buffer_offset_alignment,
844                self.caps.binds_vertex_buffers,
845                &lookup,
846            )?
847        };
848        let program = &shader.program;
849        let mut groups = Vec::new();
850        let mut index_slot = None;
851        for &group in program.bind_group_order() {
852            if Some(group) == program.index_group() {
853                index_slot = Some(group);
854                continue;
855            }
856            let layout = program.bind_group_layout(group).ok_or(GpuError::UnknownId("bind group layout"))?;
857            let mut entries = Vec::new();
858            let mut bound = Vec::new();
859            for info in program.binding_infos(group) {
860                let missing = || {
861                    GpuError::Invalid(format!(
862                        "{} reads binding {} of group {}, which no entry binds",
863                        program.name(),
864                        info.binding,
865                        info.group
866                    ))
867                };
868                let resource = match info.kind {
869                    BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer => {
870                        let (buffer, offset, size) = desc.buffer(info.binding).ok_or_else(missing)?;
871                        bound.push(BindGroupEntry::Buffer { id: info.binding, buffer, offset, size });
872                        let buffer = self.buffers.require(buffer)?;
873                        wgpu::BindingResource::Buffer(wgpu::BufferBinding {
874                            buffer: &buffer.buffer,
875                            offset: buffer.offset + offset,
876                            size: wgpu::BufferSize::new(size),
877                        })
878                    }
879                    BindingType::Sampler
880                    | BindingType::NonFilteringSampler
881                    | BindingType::Texture
882                    | BindingType::UnfilterableTexture => {
883                        let sampler = matches!(info.kind, BindingType::Sampler | BindingType::NonFilteringSampler);
884                        let texture_slot = declaration::texture_slot(info.binding) as u32;
885                        let (texture, texture_sampler) = desc.texture(texture_slot).ok_or_else(missing)?;
886                        bound.push(BindGroupEntry::Texture { slot: texture_slot, texture, sampler: texture_sampler });
887                        if sampler {
888                            wgpu::BindingResource::Sampler(self.samplers.require(texture_sampler)?)
889                        } else {
890                            wgpu::BindingResource::TextureView(&self.textures.require(texture)?.view)
891                        }
892                    }
893                };
894                entries.push(wgpu::BindGroupEntry { binding: info.binding, resource });
895            }
896            let bind_group = self.validated(desc.label, |device| {
897                device.create_bind_group(&wgpu::BindGroupDescriptor {
898                    label: Some(desc.label),
899                    layout,
900                    entries: &entries,
901                })
902            })?;
903            groups.push(BindGroup { slot: group, group: bind_group, entries: bound });
904        }
905        let tags = BindingsTags { shader: desc.shader, elements };
906        Ok(self.dependents.insert_bindings(&mut self.bindings, desc, Bindings { groups, index_slot, tags }))
907    }
908
909    fn create_geometry(&mut self, desc: &GeometryDesc<'_>) -> Result<GeometryId, GpuError> {
910        self.shaders.check(desc.shader)?;
911        let ranges = {
912            let (buffer, _) = self.info();
913            validation::check_geometry(desc, &buffer)?
914        };
915        let native = |id: BufferId, offset: u64| {
916            let buffer = self.buffers.require(id)?;
917            Ok::<_, GpuError>((buffer.buffer.clone(), buffer.offset + offset..buffer.offset + buffer.size))
918        };
919        let vertex_buffers =
920            desc.vertex_buffers.iter().map(|&(id, offset)| native(id, offset)).collect::<Result<Vec<_>, _>>()?;
921        let index_buffer = native(desc.index_buffer, 0)?;
922        let tags = GeometryTags { layout: self.layout_tags.tag(desc.shader, desc.layouts), ranges };
923        Ok(self.dependents.insert_geometry(
924            &mut self.geometries,
925            desc,
926            Geometry {
927                vertex_buffers,
928                index_buffer,
929                vertex_ids: desc.vertex_buffers.to_vec(),
930                index_id: (desc.index_buffer, 0),
931                tags,
932            },
933        ))
934    }
935
936    /// Drops this backend's references: wgpu keeps a resource while
937    /// bindings, geometry or recorded commands hold it.
938    fn destroy(&mut self, resource: ResourceId) -> Result<(), GpuError> {
939        self.dependents.destroy(resource)?;
940        match resource {
941            ResourceId::Buffer(id) => drop(self.buffers.remove(id)),
942            ResourceId::Texture(id) => drop(self.textures.remove(id)),
943            ResourceId::Sampler(id) => drop(self.samplers.remove(id)),
944            ResourceId::Shader(id) => drop(self.shaders.remove(id)),
945            ResourceId::Pipeline(id) => drop(self.pipelines.remove(id)),
946            ResourceId::Bindings(id) => drop(self.bindings.remove(id)),
947            ResourceId::Geometry(id) => drop(self.geometries.remove(id)),
948            ResourceId::Readback(id) => drop(self.readbacks.remove(id)),
949        }
950        Ok(())
951    }
952
953    fn begin_pass(&mut self, desc: &PassDesc<'_>) -> Result<(), GpuError> {
954        if self.pass.is_some() {
955            return Err(open_pass("a pass"));
956        }
957        let target = {
958            let (_, texture) = self.info();
959            validation::check_pass(desc, &texture)?
960        };
961        #[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only the benchmarks' builds count the pass"))]
962        let (mut pass, color_format, depth_stencil_format) = self.begin_render_pass(desc)?;
963        #[cfg(feature = "bench")]
964        let counted = self.queries.as_mut().is_some_and(|queries| queries.begin(&mut pass));
965        self.pass = Some(OpenPass {
966            #[cfg(feature = "bench")]
967            counted,
968            pass,
969            state: PassState::with_dynamic(
970                target,
971                DynamicState {
972                    depth_range: (0.0, 1.0),
973                    scissor: Scissor::whole(target.size),
974                    stencil_reference: 0,
975                    blend_constant: Rgba::new(0.0, 0.0, 0.0, 0.0),
976                    line_width: 1.0,
977                },
978            ),
979            color_format,
980            depth_stencil_format,
981            vertex_buffers: Vec::new(),
982            index_buffer: None,
983            groups: Vec::new(),
984        });
985        Ok(())
986    }
987
988    fn draw(&mut self, draw: &Draw) -> Result<(), GpuError> {
989        let open = self.pass.as_mut().ok_or_else(|| no_pass("a draw"))?;
990        let pipeline = self.pipelines.require(draw.pipeline)?;
991        let bindings = self.bindings.require(draw.bindings)?;
992        let geometry = self.geometries.require(draw.geometry)?;
993        validation::check_draw(draw, open.state.target.targets, &pipeline.tags, &bindings.tags, &geometry.tags)?;
994        let pass = &mut open.pass;
995        if open.state.set_pipeline(draw.pipeline) {
996            pass.set_pipeline(&pipeline.pipeline);
997        }
998        let bindings_changed = open.state.set_bindings(draw.bindings);
999        if bindings_changed {
1000            for group in &bindings.groups {
1001                let slot = group.slot as usize;
1002                if open.groups.len() <= slot {
1003                    open.groups.resize(slot + 1, None);
1004                }
1005                let held = open.groups[slot].replace(draw.bindings).and_then(|id| self.bindings.get(id));
1006                // A group of the same shader and entries binds the same
1007                // resources with the same layout, so the slot keeps it.
1008                let holds = held.is_some_and(|held| {
1009                    held.tags.shader == bindings.tags.shader
1010                        && held.groups.iter().any(|held| held.slot == group.slot && held.entries == group.entries)
1011                });
1012                if !holds {
1013                    pass.set_bind_group(group.slot, &group.group, &[]);
1014                }
1015            }
1016        }
1017        if let Some(slot) = bindings.index_slot
1018            && (bindings_changed || open.state.global_index != Some(draw.global_index))
1019        {
1020            self.index_table.reserve(self.device.device(), self.device.queue(), draw.global_index);
1021            let (group, offset) = self
1022                .index_table
1023                .get(draw.global_index)
1024                .ok_or_else(|| GpuError::Invalid(format!("global index {}", draw.global_index)))?;
1025            pass.set_bind_group(slot, group, &[offset]);
1026            open.state.global_index = Some(draw.global_index);
1027            if let Some(held) = open.groups.get_mut(slot as usize) {
1028                *held = None;
1029            }
1030        }
1031        if open.state.set_geometry(draw.geometry) {
1032            for (slot, ((buffer, range), id)) in geometry.vertex_buffers.iter().zip(&geometry.vertex_ids).enumerate() {
1033                if open.vertex_buffers.get(slot) != Some(id) {
1034                    pass.set_vertex_buffer(slot as u32, buffer.slice(range.clone()));
1035                    match open.vertex_buffers.get_mut(slot) {
1036                        Some(bound) => *bound = *id,
1037                        None => open.vertex_buffers.push(*id),
1038                    }
1039                }
1040            }
1041            if open.index_buffer != Some(geometry.index_id) {
1042                let (buffer, range) = &geometry.index_buffer;
1043                pass.set_index_buffer(buffer.slice(range.clone()), wgpu::IndexFormat::Uint16);
1044                open.index_buffer = Some(geometry.index_id);
1045            }
1046        }
1047        let changes = open.state.update_dynamic(draw.dynamic);
1048        if let Some((min, max)) = changes.depth_range {
1049            let size = open.state.target.size;
1050            pass.set_viewport(0.0, 0.0, size.width as f32, size.height as f32, min, max);
1051        }
1052        if let Some(Scissor { x, y, width, height }) = changes.scissor {
1053            pass.set_scissor_rect(x, y, width, height);
1054        }
1055        if let Some(reference) = changes.stencil_reference {
1056            pass.set_stencil_reference(reference);
1057        }
1058        if let Some(color) = changes.blend_constant {
1059            pass.set_blend_constant(wgpu_color(color));
1060        }
1061        // WebGPU draws lines 1 pixel wide.
1062        let indices = draw.first_index..draw.first_index + draw.index_count;
1063        let instances = draw.first_instance..draw.first_instance + draw.instance_count;
1064        pass.draw_indexed(indices, draw.base_vertex, instances);
1065        Ok(())
1066    }
1067
1068    /// Lends the open pass, or the frame's command encoder. A pass that a
1069    /// custom layer draws into has a color attachment.
1070    fn lend(&mut self, f: &mut dyn FnMut(&mut dyn Any)) -> Result<(), GpuError> {
1071        let (device, queue) = (self.device.device().clone(), self.device.queue().clone());
1072        if let Some(mut open) = self.pass.take() {
1073            let Some(color_format) = open.color_format else {
1074                self.pass = Some(open);
1075                return Err(GpuError::Unsupported("a custom layer's pass without a color attachment".to_owned()));
1076            };
1077            let depth_stencil_format = open.depth_stencil_format;
1078            let mut lent =
1079                CustomLayerPass { device, queue, pass: open.pass, color_format, depth_stencil_format, sample_count: 1 };
1080            f(&mut lent);
1081            open.pass = lent.pass;
1082            open.forget_state();
1083            self.pass = Some(open);
1084            return Ok(());
1085        }
1086        let encoder = self
1087            .encoder
1088            .take()
1089            .unwrap_or_else(|| device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("frame") }));
1090        let mut lent = CustomLayerEncoder { device, queue, encoder };
1091        f(&mut lent);
1092        self.encoder = Some(lent.encoder);
1093        Ok(())
1094    }
1095
1096    fn end_pass(&mut self) -> Result<(), GpuError> {
1097        #[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only the benchmarks' builds count the pass"))]
1098        let mut open = self.pass.take().ok_or_else(|| no_pass("the end of a pass"))?;
1099        #[cfg(feature = "bench")]
1100        if open.counted {
1101            crate::bench::Queries::end(&mut open.pass);
1102        }
1103        drop(open);
1104        Ok(())
1105    }
1106
1107    fn flush(&mut self, wait: bool) -> Result<(), GpuError> {
1108        if self.pass.is_some() {
1109            return Err(open_pass("a flush"));
1110        }
1111        if !wait && self.encoder.is_none() && self.writes.is_empty() {
1112            return Ok(());
1113        }
1114        let submission = self.submit(|_| {})?;
1115        #[cfg(not(target_family = "wasm"))]
1116        if wait {
1117            return self.wait_for(Some(&submission));
1118        }
1119        let _ = (wait, submission);
1120        Ok(())
1121    }
1122
1123    /// Copies into a buffer that is mapped once the copy is done: the last
1124    /// readback's where it's as big, else a new one.
1125    fn read_texture(&mut self, texture: TextureId, region: TextureRegion) -> Result<ReadbackId, GpuError> {
1126        if self.pass.is_some() {
1127            return Err(open_pass("a readback"));
1128        }
1129        let texture = self.textures.get(texture).map(|texture| texture.texture.clone());
1130        let readback = validation::check_readback(texture.as_ref().map(texture_info), region)?;
1131        let texture = texture.ok_or(GpuError::UnknownId("texture"))?;
1132        let padded_bytes_per_row = readback.bytes_per_row.next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize);
1133        let (width, rows) = (region.size.width, region.size.height);
1134        let size = (padded_bytes_per_row * rows as usize) as u64;
1135        let buffer = match self.spare_readback.take() {
1136            Some(buffer) if buffer.size() == size => buffer,
1137            _ => self.validated("readback", |device| {
1138                device.create_buffer(&wgpu::BufferDescriptor {
1139                    label: Some("readback"),
1140                    size,
1141                    usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
1142                    mapped_at_creation: false,
1143                })
1144            })?,
1145        };
1146        let submission = self.submit(|encoder| {
1147            encoder.copy_texture_to_buffer(
1148                wgpu::TexelCopyTextureInfo {
1149                    texture: &texture,
1150                    mip_level: 0,
1151                    origin: wgpu::Origin3d { x: region.x, y: region.y, z: 0 },
1152                    aspect: wgpu::TextureAspect::All,
1153                },
1154                wgpu::TexelCopyBufferInfo {
1155                    buffer: &buffer,
1156                    layout: wgpu::TexelCopyBufferLayout {
1157                        offset: 0,
1158                        bytes_per_row: Some(padded_bytes_per_row as u32),
1159                        rows_per_image: Some(rows),
1160                    },
1161                },
1162                wgpu::Extent3d { width, height: rows, depth_or_array_layers: 1 },
1163            );
1164        })?;
1165        let mapped = Arc::new(OnceLock::new());
1166        let map_ended = Arc::clone(&mapped);
1167        buffer.map_async(wgpu::MapMode::Read, .., move |result| {
1168            let _ = map_ended.set(result);
1169        });
1170        Ok(self.readbacks.insert(Readback {
1171            buffer,
1172            padded_bytes_per_row,
1173            bytes_per_row: readback.bytes_per_row,
1174            rows: rows as usize,
1175            submission,
1176            mapped,
1177        }))
1178    }
1179
1180    /// Polls the device for the map, or on a browser leaves it to the
1181    /// browser's event loop, which can't wait.
1182    fn take_readback(&mut self, readback: ReadbackId, wait: bool) -> Result<Option<Vec<u8>>, GpuError> {
1183        let entry = self.readbacks.get(readback).ok_or(GpuError::UnknownId("readback"))?;
1184        let mapped = Arc::clone(&entry.mapped);
1185        if mapped.get().is_none() {
1186            #[cfg(not(target_family = "wasm"))]
1187            if wait {
1188                if let Err(error) = self.wait_for(Some(&entry.submission)) {
1189                    self.readbacks.remove(readback);
1190                    return Err(error);
1191                }
1192            } else {
1193                let _ = self.device.device().poll(wgpu::PollType::Poll);
1194            }
1195            #[cfg(target_family = "wasm")]
1196            let _ = wait;
1197        }
1198        let Some(mapped) = mapped.get() else {
1199            return Ok(None);
1200        };
1201        let Readback { buffer, padded_bytes_per_row, bytes_per_row, rows, .. } =
1202            self.readbacks.remove(readback).ok_or(GpuError::UnknownId("readback"))?;
1203        if let Err(error) = mapped {
1204            return Err(GpuError::Invalid(format!("mapping a readback: {error}")));
1205        }
1206        let texels = {
1207            let range = buffer
1208                .get_mapped_range(..)
1209                .map_err(|error| GpuError::Invalid(format!("a readback's range: {error}")))?;
1210            if padded_bytes_per_row == bytes_per_row {
1211                range[..bytes_per_row * rows].to_vec()
1212            } else {
1213                let mut texels = Vec::with_capacity(bytes_per_row * rows);
1214                for row in range.chunks(padded_bytes_per_row).take(rows) {
1215                    texels.extend_from_slice(&row[..bytes_per_row]);
1216                }
1217                texels
1218            }
1219        };
1220        buffer.unmap();
1221        self.spare_readback = Some(buffer);
1222        Ok(Some(texels))
1223    }
1224}