Skip to main content

mln_gfx/
gpu.rs

1//! The interface a GPU backend implements: resources the backend owns and
2//! the caller names by id, objects prepared from them, and draws.
3//!
4//! A [`Gpu`] keeps each kind of resource in a slot map keyed by its id, so a
5//! resource holds no pointer back to the backend, and the caller decides
6//! when one goes. What a draw reads is prepared ahead of it, and checked
7//! then: a [`ShaderId`]'s pipelines ([`Gpu::create_pipeline`]), the buffers
8//! and textures it binds ([`Gpu::create_bindings`]) and its vertex and
9//! index buffers ([`Gpu::create_geometry`]). A [`Draw`] names one of each,
10//! between [`Gpu::begin_pass`] and [`Gpu::end_pass`], and the backend
11//! records it at once.
12//!
13//! Bindings use the shaders' own numbering: a buffer binds at the id the
14//! program declares it at, or the engine's
15//! ([`shaders::bindings`](crate::shaders::bindings)), and a texture and a
16//! vertex attribute at the slot and location the program declares them at
17//! ([`Program`]). Each
18//! backend maps them to its own slots, groups, descriptor sets or shader
19//! locations.
20
21mod ids;
22pub mod validation;
23
24use std::any::Any;
25use std::sync::Arc;
26
27pub use self::ids::{
28    BindingsId, BufferId, GeometryId, Id, IdData, PipelineId, ReadbackId, ResourceId, SamplerId, ShaderId, SlotMap,
29    TextureId,
30};
31use crate::color_mode::{BlendFunction, Mask, Rgba};
32use crate::cull_face_mode::CullFaceMode;
33use crate::depth_mode::DepthMode;
34use crate::gfx_types::{AttributeDataType, DrawModeType};
35use crate::log_target;
36use crate::shaders::program::Program;
37use crate::size::Size;
38use crate::stencil_mode::{StencilMode, Test};
39use crate::texture2d::SamplerState;
40use crate::types::{DepthFunctionType, DepthMaskType, StencilOpType};
41
42/// Why a [`Gpu`] call failed.
43#[derive(Debug, thiserror::Error)]
44pub enum GpuError {
45    /// The call named a resource this backend doesn't have: one another
46    /// backend made, or one already destroyed.
47    #[error("no such {0}")]
48    UnknownId(&'static str),
49    /// A destroy of a resource that live pipelines, bindings or geometry
50    /// were made of, which debug builds refuse.
51    #[error("the {0} is in use by pipelines, bindings or geometry")]
52    InUse(&'static str),
53    /// The backend can't make what the descriptor asks for, such as a
54    /// texture format the device lacks.
55    #[error("unsupported: {0}")]
56    Unsupported(String),
57    /// The backend rejected the call: a shader that doesn't compile, a
58    /// descriptor its API refuses, bindings missing a buffer their shader
59    /// reads, or a draw past its geometry.
60    #[error("{0}")]
61    Invalid(String),
62}
63
64/// What a backend's device allows, and how the renderer draws on it.
65#[derive(Clone, Copy, Debug, PartialEq)]
66pub struct Caps {
67    /// The alignment of the offset a uniform or storage buffer binds at.
68    pub buffer_offset_alignment: u32,
69    /// The widest and tallest texture.
70    pub max_texture_size: u32,
71    /// Whether passes draw into textures of `Rgba16Float`.
72    pub half_float_render_targets: bool,
73    pub clip_depth: ClipDepthRange,
74    /// The format of the depth attachment of the passes that draw into a
75    /// render target's texture, `None` for passes without one.
76    pub render_target_depth: Option<TextureFormat>,
77    /// Whether the renderer clears the stencil inside a pass by ending it
78    /// and beginning one that clears it, rather than drawing zero over it.
79    pub clear_stencil_with_pass: bool,
80    /// Whether the device rasterizes on the CPU, as Mesa's llvmpipe and
81    /// lavapipe do. Their vertex pipeline runs once per instance, so an
82    /// instanced draw costs about as much as a draw of each instance.
83    pub cpu_rasterizer: bool,
84    /// The widest line in pixels that a pipeline of line primitives draws
85    /// ([`DynamicState::line_width`]): 1 on a device without wide lines.
86    pub max_line_width: f32,
87    /// Whether bindings bind [`Vertex`](BufferUsage::Vertex) buffers too,
88    /// which shaders read as storage buffers. The renderer draws the walls
89    /// of fill extrusions there as quads whose vertex shader reads the
90    /// bucket's vertices by vertex index, rather than as instances.
91    pub binds_vertex_buffers: bool,
92}
93
94/// How a graphics API's clip space holds depth.
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
96pub enum ClipDepthRange {
97    /// Clip z from 0 to w: Metal, Vulkan, D3D12 and WebGPU.
98    ZeroToOne,
99    /// Clip z from -w to w: OpenGL.
100    NegativeOneToOne,
101}
102
103/// How a buffer is bound.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
105pub enum BufferUsage {
106    Vertex,
107    /// 16-bit indices.
108    Index,
109    Uniform,
110    Storage,
111}
112
113#[derive(Clone, Copy, Debug)]
114pub struct BufferDesc<'a> {
115    pub label: &'a str,
116    pub usage: BufferUsage,
117    /// The size in bytes, which the backend may round up.
118    pub size: u64,
119}
120
121/// The texel formats of textures and render targets.
122#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123pub enum TextureFormat {
124    R8Unorm,
125    /// One 8-bit channel that shaders read as alpha, with red, green and
126    /// blue 0. WebGPU, which has no such format, stores it as `R8Unorm`,
127    /// which its shaders read as red.
128    A8Unorm,
129    R16Float,
130    R32Float,
131    Rgba8Unorm,
132    Rgba8UnormSrgb,
133    Bgra8Unorm,
134    Bgra8UnormSrgb,
135    Rgb10a2Unorm,
136    Rgba16Float,
137    Rgba32Float,
138    Depth32Float,
139    Depth24PlusStencil8,
140    Depth32FloatStencil8,
141}
142
143impl TextureFormat {
144    /// Every format.
145    pub const ALL: [TextureFormat; 13] = [
146        TextureFormat::R8Unorm,
147        TextureFormat::R16Float,
148        TextureFormat::R32Float,
149        TextureFormat::Rgba8Unorm,
150        TextureFormat::Rgba8UnormSrgb,
151        TextureFormat::Bgra8Unorm,
152        TextureFormat::Bgra8UnormSrgb,
153        TextureFormat::Rgb10a2Unorm,
154        TextureFormat::Rgba16Float,
155        TextureFormat::Rgba32Float,
156        TextureFormat::Depth32Float,
157        TextureFormat::Depth24PlusStencil8,
158        TextureFormat::Depth32FloatStencil8,
159    ];
160
161    /// The bytes a texel of a color format takes in
162    /// [`write_texture`](Gpu::write_texture)'s data; `None` for a depth
163    /// format.
164    #[must_use]
165    pub fn bytes_per_texel(self) -> Option<u32> {
166        match self {
167            TextureFormat::R8Unorm | TextureFormat::A8Unorm => Some(1),
168            TextureFormat::R16Float => Some(2),
169            TextureFormat::R32Float
170            | TextureFormat::Rgba8Unorm
171            | TextureFormat::Rgba8UnormSrgb
172            | TextureFormat::Bgra8Unorm
173            | TextureFormat::Bgra8UnormSrgb
174            | TextureFormat::Rgb10a2Unorm => Some(4),
175            TextureFormat::Rgba16Float => Some(8),
176            TextureFormat::Rgba32Float => Some(16),
177            TextureFormat::Depth32Float | TextureFormat::Depth24PlusStencil8 | TextureFormat::Depth32FloatStencil8 => {
178                None
179            }
180        }
181    }
182
183    #[must_use]
184    pub fn has_stencil(self) -> bool {
185        matches!(self, TextureFormat::Depth24PlusStencil8 | TextureFormat::Depth32FloatStencil8)
186    }
187
188    /// Whether a texture of the format can be
189    /// [`mipmapped`](TextureDesc::mipmapped): a color format that every
190    /// backend filters and draws into, as making its mips takes. (A backend
191    /// may still lack a format, as GL lacks the BGRA ones.)
192    #[must_use]
193    pub fn mipmappable(self) -> bool {
194        self.bytes_per_texel().is_some()
195            && !matches!(self, TextureFormat::A8Unorm | TextureFormat::R32Float | TextureFormat::Rgba32Float)
196    }
197}
198
199/// What a texture is used for.
200#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
201pub struct TextureUsage {
202    /// Shaders sample it, and [`write_texture`](Gpu::write_texture) fills
203    /// it.
204    pub sampled: bool,
205    /// Passes draw into it.
206    pub render_target: bool,
207    /// Its texels are copied out after a pass, for a readback.
208    pub copy_src: bool,
209}
210
211#[derive(Clone, Copy, Debug)]
212pub struct TextureDesc<'a> {
213    pub label: &'a str,
214    pub size: Size,
215    pub format: TextureFormat,
216    pub usage: TextureUsage,
217    /// Whether the texture has a full chain of mip levels, each half the
218    /// size of the one before, rounded down, to 1×1, which
219    /// [`generate_mipmaps`](Gpu::generate_mipmaps) fills from level 0.
220    /// Passes, writes and readbacks reach level 0 only.
221    /// [`validation::check_mips`] says what such a texture is.
222    pub mipmapped: bool,
223}
224
225impl TextureDesc<'_> {
226    /// The number of mip levels of the texture: 1 without mips.
227    #[must_use]
228    pub fn mip_level_count(&self) -> u32 {
229        if self.mipmapped { self.size.width.max(self.size.height).max(1).bit_width() } else { 1 }
230    }
231}
232
233/// The texels at `x`, `y` of `size` that a write replaces.
234#[derive(Clone, Copy, Debug, PartialEq, Eq)]
235pub struct TextureRegion {
236    pub x: u32,
237    pub y: u32,
238    pub size: Size,
239}
240
241impl TextureRegion {
242    /// The whole of a texture of `size`.
243    #[must_use]
244    pub fn whole(size: Size) -> TextureRegion {
245        TextureRegion { x: 0, y: 0, size }
246    }
247
248    /// The bytes in each row of this region of a texture of `size` and
249    /// `format`, as [`write_texture`](Gpu::write_texture) takes them and
250    /// [`take_readback`](Gpu::take_readback) returns them. Fails for a depth
251    /// format, or a region past the texture's edges.
252    pub fn bytes_per_row(&self, size: Size, format: TextureFormat) -> Result<usize, GpuError> {
253        let bytes_per_texel = format
254            .bytes_per_texel()
255            .ok_or_else(|| GpuError::Invalid(format!("{format:?} textures have no texels to copy")))?;
256        let past = |start: u32, length: u32, limit: u32| u64::from(start) + u64::from(length) > u64::from(limit);
257        if past(self.x, self.size.width, size.width) || past(self.y, self.size.height, size.height) {
258            return Err(GpuError::Invalid(format!("{self:?} of a texture of {size:?}")));
259        }
260        Ok(self.size.width as usize * bytes_per_texel as usize)
261    }
262
263    /// The bytes in each row of `data` that
264    /// [`write_texture`](Gpu::write_texture) writes to this region of a
265    /// texture of `size` and `format`. Fails as
266    /// [`bytes_per_row`](Self::bytes_per_row) does, and for `data` of
267    /// another length.
268    pub fn write_bytes_per_row(&self, size: Size, format: TextureFormat, data: &[u8]) -> Result<usize, GpuError> {
269        let bytes_per_row = self.bytes_per_row(size, format)?;
270        let expected = bytes_per_row * self.size.height as usize;
271        if data.len() != expected {
272            return Err(GpuError::Invalid(format!("a write of {} bytes to a region of {expected}", data.len())));
273        }
274        Ok(bytes_per_row)
275    }
276}
277
278/// Whether a vertex buffer advances per vertex or per instance.
279#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
280pub enum VertexStep {
281    Vertex,
282    Instance,
283}
284
285/// An attribute of a vertex buffer: the program's attribute at `location`
286/// ([`Program::location`]) reads `format` from `offset` bytes into each
287/// element. It is one of the program's per-vertex attributes in a
288/// [`VertexStep::Vertex`] buffer, and of its per-instance ones in a
289/// [`VertexStep::Instance`] buffer.
290#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
291pub struct VertexAttribute {
292    pub location: u32,
293    pub format: AttributeDataType,
294    pub offset: u32,
295}
296
297/// The layout of the vertex buffer in one slot.
298#[derive(Clone, Debug, PartialEq, Eq, Hash)]
299pub struct VertexBufferLayout {
300    /// The bytes between elements.
301    pub stride: u32,
302    pub step: VertexStep,
303    pub attributes: Vec<VertexAttribute>,
304}
305
306/// A program and the defines it is compiled with, from the source the
307/// backend has registered for the program. Clones share the defines.
308#[derive(Clone, Debug, PartialEq, Eq, Hash)]
309pub struct ShaderKey {
310    program: &'static Program,
311    defines: Arc<[String]>,
312}
313
314impl ShaderKey {
315    /// `program` with `defines`, in any order and with repeats: names such
316    /// as `PROJECTION_GLOBE` or `HAS_UNIFORM_u_color`, or `NAME=value` for
317    /// a define with a value, such as `DEVICE_PIXEL_RATIO=2.0`.
318    #[must_use]
319    pub fn new(program: &'static Program, defines: impl IntoIterator<Item = String>) -> ShaderKey {
320        let mut defines: Vec<String> = defines.into_iter().collect();
321        defines.sort_unstable();
322        defines.dedup();
323        ShaderKey { program, defines: defines.into() }
324    }
325
326    #[must_use]
327    pub fn program(&self) -> &'static Program {
328        self.program
329    }
330
331    /// The defines, sorted.
332    #[must_use]
333    pub fn defines(&self) -> &[String] {
334        &self.defines
335    }
336
337    /// Each define's name and value, `""` for one without a value.
338    pub fn define_values(&self) -> impl Iterator<Item = (&str, &str)> {
339        self.defines.iter().map(|define| define.split_once('=').unwrap_or((define, "")))
340    }
341}
342
343/// The depth test and write of a pipeline. Its depth range is each draw's
344/// ([`DynamicState::depth_range`]).
345#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
346pub struct DepthState {
347    pub compare: DepthFunctionType,
348    pub write: bool,
349}
350
351impl From<&DepthMode> for DepthState {
352    fn from(mode: &DepthMode) -> DepthState {
353        DepthState { compare: mode.func, write: mode.mask == DepthMaskType::ReadWrite }
354    }
355}
356
357/// The stencil test and operations of a pipeline, on both faces. The
358/// reference value is each draw's ([`DynamicState::stencil_reference`]).
359#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
360pub struct StencilState {
361    /// The comparison, and the mask it reads through.
362    pub test: Test,
363    pub write_mask: u32,
364    pub fail: StencilOpType,
365    pub depth_fail: StencilOpType,
366    pub pass: StencilOpType,
367}
368
369impl StencilState {
370    /// Whether the state leaves the stencil buffer alone: it always passes
371    /// and writes nothing.
372    #[must_use]
373    pub fn is_disabled(&self) -> bool {
374        self.test == Test::Always
375            && self.write_mask == 0
376            && self.fail == StencilOpType::Keep
377            && self.depth_fail == StencilOpType::Keep
378            && self.pass == StencilOpType::Keep
379    }
380}
381
382impl From<&StencilMode> for StencilState {
383    fn from(mode: &StencilMode) -> StencilState {
384        StencilState {
385            test: mode.test,
386            write_mask: mode.mask,
387            fail: mode.fail,
388            depth_fail: mode.depth_fail,
389            pass: mode.pass,
390        }
391    }
392}
393
394/// The fixed-function state of a pipeline.
395#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
396pub struct FixedState {
397    pub primitive: DrawModeType,
398    pub cull: CullFaceMode,
399    /// The blend of both color and alpha. Its constant is each draw's
400    /// ([`DynamicState::blend_constant`]).
401    pub blend: BlendFunction,
402    pub color_mask: Mask,
403    pub depth: DepthState,
404    pub stencil: StencilState,
405}
406
407/// The formats of the attachments a pipeline draws into.
408#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
409pub struct TargetFormats {
410    /// `None` for a pass without a color attachment, which only tests and
411    /// writes depth and stencil.
412    pub color: Option<TextureFormat>,
413    pub depth_stencil: Option<TextureFormat>,
414}
415
416/// What [`Gpu::create_pipeline`] makes a pipeline of.
417#[derive(Clone, Copy, Debug)]
418pub struct PipelineDesc<'a> {
419    pub shader: ShaderId,
420    /// The layout of each vertex buffer slot, from slot 0.
421    pub vertex_buffers: &'a [VertexBufferLayout],
422    pub state: FixedState,
423    pub targets: TargetFormats,
424}
425
426/// A [`PipelineDesc`] that owns its layouts. Equal keys make
427/// interchangeable pipelines, so a caller keeps one pipeline per key.
428#[derive(Clone, Debug, PartialEq, Eq, Hash)]
429pub struct PipelineKey {
430    pub shader: ShaderId,
431    pub vertex_buffers: Vec<VertexBufferLayout>,
432    pub state: FixedState,
433    pub targets: TargetFormats,
434}
435
436impl PipelineKey {
437    #[must_use]
438    pub fn desc(&self) -> PipelineDesc<'_> {
439        PipelineDesc {
440            shader: self.shader,
441            vertex_buffers: &self.vertex_buffers,
442            state: self.state,
443            targets: self.targets,
444        }
445    }
446}
447
448/// What bindings bind at one of the shaders' ids.
449#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
450pub enum BindGroupEntry {
451    /// `size` bytes of `buffer` from `offset`, at uniform or storage buffer
452    /// id `id`. A shader reads a [`Vertex`](BufferUsage::Vertex) buffer as
453    /// a storage buffer ([`Caps::binds_vertex_buffers`]).
454    Buffer { id: u32, buffer: BufferId, offset: u64, size: u64 },
455    /// `texture`, sampled with `sampler`, at the program's texture slot
456    /// `slot` ([`Program::texture_slot`]).
457    Texture { slot: u32, texture: TextureId, sampler: SamplerId },
458}
459
460/// What [`Gpu::create_bindings`] makes bindings of.
461#[derive(Clone, Copy, Debug)]
462pub struct BindingsDesc<'a> {
463    pub label: &'a str,
464    /// The shader whose draws bind them.
465    pub shader: ShaderId,
466    /// Everything the shader reads, each id once, and possibly more, which
467    /// the bindings leave out: the frame's, the layer's and the draw's
468    /// buffers and textures together.
469    pub entries: &'a [BindGroupEntry],
470}
471
472/// What [`Gpu::create_geometry`] makes geometry of.
473#[derive(Clone, Copy, Debug)]
474pub struct GeometryDesc<'a> {
475    /// The shader whose draws read it.
476    pub shader: ShaderId,
477    /// The layout of each vertex buffer, as the pipelines that draw it have
478    /// them.
479    pub layouts: &'a [VertexBufferLayout],
480    /// The buffer of each layout, and the offset its elements start at.
481    pub vertex_buffers: &'a [(BufferId, u64)],
482    /// The 16-bit indices, from the buffer's start.
483    pub index_buffer: BufferId,
484}
485
486/// What a pass does with an attachment's contents before it draws.
487#[derive(Clone, Copy, Debug, PartialEq)]
488pub enum LoadOp<T> {
489    /// Keeps them.
490    Load,
491    /// Clears them to the value.
492    Clear(T),
493}
494
495#[derive(Clone, Copy, Debug, PartialEq)]
496pub struct ColorAttachment {
497    pub texture: TextureId,
498    pub load: LoadOp<Rgba>,
499}
500
501#[derive(Clone, Copy, Debug, PartialEq)]
502pub struct DepthStencilAttachment {
503    pub texture: TextureId,
504    pub depth: LoadOp<f32>,
505    /// Ignored for a format without stencil.
506    pub stencil: LoadOp<u32>,
507}
508
509/// A render pass: the attachments its draws draw into, of one size, which
510/// are stored when it ends.
511#[derive(Clone, Copy, Debug, PartialEq)]
512pub struct PassDesc<'a> {
513    pub label: &'a str,
514    pub color: Option<ColorAttachment>,
515    pub depth_stencil: Option<DepthStencilAttachment>,
516}
517
518/// The area of the attachments that draws may write to, in pixels from the
519/// top left.
520#[derive(Clone, Copy, Debug, PartialEq, Eq)]
521pub struct Scissor {
522    pub x: u32,
523    pub y: u32,
524    pub width: u32,
525    pub height: u32,
526}
527
528/// The state of a draw that its pipeline leaves to it. Draws map clip space
529/// to the pass's whole attachments.
530#[derive(Clone, Copy, Debug, PartialEq)]
531pub struct DynamicState {
532    /// The depths that clip z maps to, from near to far.
533    pub depth_range: (f32, f32),
534    pub scissor: Scissor,
535    pub stencil_reference: u32,
536    /// The constant the pipeline's `Constant*` blend factors read.
537    pub blend_constant: Rgba,
538    /// The width in pixels of the lines that a pipeline of line primitives
539    /// draws, up to [`Caps::max_line_width`].
540    pub line_width: f32,
541}
542
543/// A draw of `index_count` of the geometry's indices from `first_index`,
544/// offset by `base_vertex`, for each of `instance_count` instances from
545/// `first_instance`. A vertex's index, as a shader reads it, includes
546/// `base_vertex`.
547#[derive(Clone, Copy, Debug, PartialEq)]
548pub struct Draw {
549    pub pipeline: PipelineId,
550    pub bindings: BindingsId,
551    pub geometry: GeometryId,
552    pub first_index: u32,
553    pub index_count: u32,
554    pub base_vertex: i32,
555    pub first_instance: u32,
556    pub instance_count: u32,
557    /// The value shaders read as `globalIndex`: the index of the draw's
558    /// elements in the storage buffers its bindings bind.
559    pub global_index: u32,
560    pub dynamic: DynamicState,
561}
562
563/// A GPU backend. It owns what its `create_*` calls make, until
564/// [`destroy`](Gpu::destroy).
565///
566/// An id names a resource of the backend that made it, which keeps it in a
567/// [`SlotMap`]. Another backend's id names nothing there: a call that names
568/// one fails with [`GpuError::UnknownId`], and destroying it does nothing.
569///
570/// The caller destroys what was made of a resource before the resource:
571/// pipelines before their shader, and bindings and geometry before the
572/// buffers, textures, samplers and shader they were made of. In debug
573/// builds, destroying a resource that live pipelines, bindings or geometry
574/// were made of fails with [`GpuError::InUse`] and keeps it, as every
575/// backend checks with [`validation::Dependents`]; release builds don't
576/// check, and a draw with what was made of a destroyed resource is then
577/// the caller's error.
578///
579/// A destroyed resource's id is invalid from the call on: a later call that
580/// names it fails with [`GpuError::UnknownId`], and destroying it again
581/// does nothing. The backend keeps the native object alive while the work
582/// recorded before the call, flushed or not, still reads it.
583///
584/// A draw reads what the buffers and textures it binds hold when the work
585/// is flushed, or what they held when it was recorded, for each write since
586/// it was recorded; work flushed later reads what the writes wrote.
587pub trait Gpu {
588    fn caps(&self) -> &Caps;
589
590    /// Makes a buffer of `desc`, whose contents are undefined until written.
591    fn create_buffer(&mut self, desc: &BufferDesc<'_>) -> Result<BufferId, GpuError>;
592    /// Writes `data` at `offset` bytes into `buffer`. `offset` and the
593    /// length of `data` are multiples of 4.
594    fn write_buffer(&mut self, buffer: BufferId, offset: u64, data: &[u8]) -> Result<(), GpuError>;
595    /// Writes the bytes of `data`, which are in a JS array, at `offset`
596    /// bytes into `buffer`. `offset` is a multiple of 4. A length that isn't
597    /// writes zeros to the rest of the last word. A backend that can write
598    /// from the array overrides this, which copies the bytes into wasm
599    /// memory first.
600    #[cfg(target_family = "wasm")]
601    fn write_buffer_from_host(
602        &mut self,
603        buffer: BufferId,
604        offset: u64,
605        data: &js_sys::Uint8Array,
606    ) -> Result<(), GpuError> {
607        let mut bytes = data.to_vec();
608        bytes.resize(bytes.len().next_multiple_of(4), 0);
609        self.write_buffer(buffer, offset, &bytes)
610    }
611
612    /// Makes a texture of `desc`. Fails as [`validation::check_mips`] does,
613    /// and for a size or format the backend doesn't make.
614    fn create_texture(&mut self, desc: &TextureDesc<'_>) -> Result<TextureId, GpuError>;
615    /// Writes `data`, the region's texels in rows from the top with no
616    /// padding, to `region` of `texture`, which is
617    /// [`sampled`](TextureUsage::sampled).
618    fn write_texture(&mut self, texture: TextureId, region: TextureRegion, data: &[u8]) -> Result<(), GpuError>;
619
620    /// Fills mip levels 1 and on of `texture`, which is
621    /// [`mipmapped`](TextureDesc::mipmapped), each with the average of the
622    /// texels of the level before, from what level 0 holds once the work
623    /// recorded so far is done. Fails while a pass is open, and for a
624    /// texture without mips.
625    fn generate_mipmaps(&mut self, texture: TextureId) -> Result<(), GpuError>;
626
627    fn create_sampler(&mut self, state: &SamplerState) -> Result<SamplerId, GpuError>;
628
629    /// Compiles the program of `key`. Fails with [`GpuError::Unsupported`]
630    /// for a program the backend has no source for.
631    fn create_shader(&mut self, key: &ShaderKey) -> Result<ShaderId, GpuError>;
632    /// Makes a pipeline of `desc`'s shader and state. Fails with
633    /// [`GpuError::Unsupported`] for a primitive the backend doesn't draw.
634    fn create_pipeline(&mut self, desc: &PipelineDesc<'_>) -> Result<PipelineId, GpuError>;
635    /// Makes the bindings of `desc`'s entries that its shader reads. Fails
636    /// as [`validation::check_bindings`] does: for an entry of a buffer of
637    /// another usage than [`Uniform`](BufferUsage::Uniform) or
638    /// [`Storage`](BufferUsage::Storage), or
639    /// [`Vertex`](BufferUsage::Vertex) where
640    /// [`Caps::binds_vertex_buffers`] says, a range outside its buffer or at
641    /// an offset the backend doesn't align, a texture that isn't
642    /// [`sampled`](TextureUsage::sampled), two entries of one id, or a
643    /// buffer or texture the shader reads and no entry binds.
644    fn create_bindings(&mut self, desc: &BindingsDesc<'_>) -> Result<BindingsId, GpuError>;
645    /// Makes geometry of `desc`'s buffers. Fails as
646    /// [`validation::check_geometry`] does: for a buffer of another usage
647    /// than [`Vertex`](BufferUsage::Vertex) or the index buffer's
648    /// [`Index`](BufferUsage::Index), an offset past a buffer's end, or a
649    /// buffer for each layout but not one.
650    fn create_geometry(&mut self, desc: &GeometryDesc<'_>) -> Result<GeometryId, GpuError>;
651
652    /// Destroys `resource`, or drops a readback without reading it. Fails,
653    /// destroying nothing, as [`validation::Dependents::destroy`] does.
654    fn destroy(&mut self, resource: ResourceId) -> Result<(), GpuError>;
655
656    /// Begins a pass over `desc`'s attachments, which are render targets of
657    /// one size, a color one and a depth one, at least one of them. Fails
658    /// while a pass is open.
659    fn begin_pass(&mut self, desc: &PassDesc<'_>) -> Result<(), GpuError>;
660    /// Whether a pass can draw into `depth_stencil`, a depth attachment,
661    /// together with any color attachment of its size. Not where it is an
662    /// attachment of a framebuffer made elsewhere, such as a window
663    /// surface's, which a pass draws into only with that framebuffer's
664    /// color.
665    fn attaches_with_any_color(&self, _depth_stencil: TextureId) -> bool {
666        true
667    }
668    /// Draws `draw` into the open pass. Fails, drawing nothing, outside a
669    /// pass, for a pipeline of other target formats than the pass's
670    /// attachments, for bindings or geometry made for another shader or
671    /// vertex layouts than the pipeline's, for indices or instances past
672    /// the geometry's buffers, and for a global index past the elements of
673    /// the storage buffers the bindings bind. The contents of the indices
674    /// are the caller's to keep inside the vertex buffers.
675    fn draw(&mut self, draw: &Draw) -> Result<(), GpuError>;
676    /// Lends the backend's own commands to `f`: inside the open pass, its
677    /// `CustomLayerPass`, which records into the pass after its draws so
678    /// far; outside a pass, its `CustomLayerEncoder`, which records after
679    /// the work so far. The docs of each say what `f` may record.
680    fn lend(&mut self, f: &mut dyn FnMut(&mut dyn Any)) -> Result<(), GpuError>;
681    /// Ends the open pass, storing its attachments.
682    fn end_pass(&mut self) -> Result<(), GpuError>;
683    /// Sends the work recorded so far to the GPU; with `wait`, then blocks
684    /// until the GPU has finished it, on a backend that can block. Fails
685    /// while a pass is open.
686    fn flush(&mut self, wait: bool) -> Result<(), GpuError>;
687
688    /// Starts copying `region` of `texture`, whose `y` counts rows from the
689    /// top as passes do, out of the GPU, once the work recorded so far is
690    /// done, which it flushes: later work and writes don't change what the
691    /// copy holds. [`take_readback`](Self::take_readback) reads it. Fails
692    /// while a pass is open, as [`validation::check_readback`] does, or
693    /// with [`GpuError::Unsupported`] for a format the backend reads no
694    /// texels of.
695    fn read_texture(&mut self, texture: TextureId, region: TextureRegion) -> Result<ReadbackId, GpuError>;
696    /// The texels that `readback` copied, in the texture's format and with
697    /// no padding, as [`write_texture`](Self::write_texture) takes them, in
698    /// rows from the top as passes count them. (A backend that stores what
699    /// passes draw bottom row first reads a written texture's rows back in
700    /// the other order.) `None` while the GPU hasn't finished the copy;
701    /// with `wait`, the call blocks until it has, except on a backend that
702    /// can't block, which returns `None` as without it. Once the call
703    /// returns texels or fails, `readback` is gone.
704    fn take_readback(&mut self, readback: ReadbackId, wait: bool) -> Result<Option<Vec<u8>>, GpuError>;
705}
706
707/// The texels of `region` of `texture` once the work recorded so far is
708/// done: [`read_texture`](Gpu::read_texture), then a
709/// [`take_readback`](Gpu::take_readback) that waits. Fails with
710/// [`GpuError::Unsupported`] on a backend that can't block.
711pub fn read_texels(
712    gpu: &mut (impl Gpu + ?Sized),
713    texture: TextureId,
714    region: TextureRegion,
715) -> Result<Vec<u8>, GpuError> {
716    let readback = gpu.read_texture(texture, region)?;
717    if let Some(texels) = gpu.take_readback(readback, true)? {
718        return Ok(texels);
719    }
720    gpu.destroy(ResourceId::Readback(readback))?;
721    Err(GpuError::Unsupported("waiting for a readback".to_owned()))
722}
723
724/// Destroys `resources`, of which no bindings or geometry were made, such as
725/// a frame target's textures and readbacks. Logs a failure, which only a
726/// caller that made bindings or geometry of one of them causes.
727pub fn destroy_unused(gpu: &mut (impl Gpu + ?Sized), resources: impl IntoIterator<Item = ResourceId>) {
728    for resource in resources {
729        if let Err(error) = gpu.destroy(resource) {
730            log::error!(target: log_target::RENDER, "Destroying {resource:?} failed: {error}");
731        }
732    }
733}
734
735#[cfg(test)]
736mod tests {
737    use super::*;
738    use crate::shaders::program::Projection;
739    use crate::shaders::source::Sources;
740
741    const fn program(name: &'static str) -> Program {
742        Program {
743            name,
744            buffers: &[],
745            paint_params: None,
746            projection: Projection::None,
747            attributes: &[],
748            instance_attributes: &[],
749            textures: &[],
750            properties: &[],
751            sources: Sources::NONE,
752        }
753    }
754
755    static A: Program = program("A");
756    static B: Program = program("B");
757
758    #[test]
759    fn shader_keys_ignore_define_order_and_repeats() {
760        let key = |defines: &[&str]| ShaderKey::new(&A, defines.iter().map(|&d| d.to_owned()));
761        assert_eq!(key(&["B", "A", "B"]), key(&["A", "B"]));
762        assert_eq!(key(&["B", "A"]).defines(), ["A", "B"]);
763        assert_ne!(key(&["A"]), ShaderKey::new(&B, ["A".to_owned()]));
764        assert_eq!(key(&["B=2.0", "A"]).define_values().collect::<Vec<_>>(), [("A", ""), ("B", "2.0")]);
765    }
766
767    #[test]
768    fn texture_writes_fit_their_region_and_texture() {
769        let size = Size { width: 4, height: 2 };
770        let region = TextureRegion { x: 1, y: 0, size: Size { width: 3, height: 2 } };
771        assert_eq!(region.write_bytes_per_row(size, TextureFormat::Rgba8Unorm, &[0; 24]).ok(), Some(12));
772        assert!(region.write_bytes_per_row(size, TextureFormat::Rgba8Unorm, &[0; 20]).is_err());
773        assert!(region.write_bytes_per_row(size, TextureFormat::Depth32Float, &[0; 24]).is_err());
774        let past = TextureRegion { x: 2, ..region };
775        assert!(past.write_bytes_per_row(size, TextureFormat::Rgba8Unorm, &[0; 24]).is_err());
776    }
777
778    #[test]
779    fn a_disabled_stencil_mode_leaves_the_stencil_alone() {
780        assert!(StencilState::from(&StencilMode::disabled()).is_disabled());
781        assert!(!StencilState::from(&StencilMode { mask: 0xFF, ..StencilMode::disabled() }).is_disabled());
782    }
783}