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