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