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