wgpu_types/
lib.rs

1//! This library describes the API surface of WebGPU that is agnostic of the backend.
2//! This API is used for targeting both Web and Native.
3
4#![cfg_attr(docsrs, feature(doc_cfg))]
5#![allow(
6    // We don't use syntax sugar where it's not necessary.
7    clippy::match_like_matches_macro,
8)]
9#![warn(
10    clippy::ptr_as_ptr,
11    missing_docs,
12    unsafe_op_in_unsafe_fn,
13    unused_qualifications
14)]
15#![no_std]
16
17#[cfg(feature = "std")]
18extern crate std;
19
20extern crate alloc;
21
22use core::{fmt, hash::Hash, time::Duration};
23
24#[cfg(any(feature = "serde", test))]
25use serde::{Deserialize, Serialize};
26
27mod adapter;
28pub mod assertions;
29mod backend;
30mod binding;
31mod buffer;
32mod cast_utils;
33mod counters;
34mod device;
35mod env;
36pub mod error;
37mod features;
38pub mod instance;
39mod limits;
40pub mod math;
41mod origin_extent;
42mod ray_tracing;
43mod render;
44#[doc(hidden)] // without this we get spurious missing_docs warnings
45mod send_sync;
46mod shader;
47mod surface;
48mod texture;
49mod tokens;
50mod transfers;
51mod vertex;
52
53pub use adapter::*;
54pub use backend::*;
55pub use binding::*;
56pub use buffer::*;
57pub use counters::*;
58pub use device::*;
59pub use features::*;
60pub use instance::*;
61pub use limits::*;
62pub use origin_extent::*;
63pub use ray_tracing::*;
64pub use render::*;
65#[doc(hidden)]
66pub use send_sync::*;
67pub use shader::*;
68pub use surface::*;
69pub use texture::*;
70pub use tokens::*;
71pub use transfers::*;
72pub use vertex::*;
73
74/// Create a Markdown link definition referring to the `wgpu` crate.
75///
76/// This macro should be used inside a `#[doc = ...]` attribute.
77/// The two arguments should be string literals or macros that expand to string literals.
78/// If the module in which the item using this macro is located is not the crate root,
79/// use the `../` syntax.
80///
81/// We cannot simply use rustdoc links to `wgpu` because it is one of our dependents.
82/// This link adapts to work in locally generated documentation (`cargo doc`) by default,
83/// and work with `docs.rs` URL structure when building for `docs.rs`.
84///
85/// Note: This macro cannot be used outside this crate, because `cfg(docsrs)` will not apply.
86#[cfg(not(docsrs))]
87macro_rules! link_to_wgpu_docs {
88    ([$reference:expr]: $url_path:expr) => {
89        concat!("[", $reference, "]: ../wgpu/", $url_path)
90    };
91
92    (../ [$reference:expr]: $url_path:expr) => {
93        concat!("[", $reference, "]: ../../wgpu/", $url_path)
94    };
95}
96#[cfg(docsrs)]
97macro_rules! link_to_wgpu_docs {
98    ($(../)? [$reference:expr]: $url_path:expr) => {
99        concat!(
100            "[",
101            $reference,
102            // URL path will have a base URL of https://docs.rs/
103            "]: /wgpu/",
104            // The version of wgpu-types is not necessarily the same as the version of wgpu
105            // if a patch release of either has been published, so we cannot use the full version
106            // number. docs.rs will interpret this single number as a Cargo-style version
107            // requirement and redirect to the latest compatible version.
108            //
109            // This technique would break if `wgpu` and `wgpu-types` ever switch to having distinct
110            // major version numbering. An alternative would be to hardcode the corresponding `wgpu`
111            // version, but that would give us another thing to forget to update.
112            env!("CARGO_PKG_VERSION_MAJOR"),
113            "/wgpu/",
114            $url_path
115        )
116    };
117}
118
119/// Create a Markdown link definition referring to an item in the `wgpu` crate.
120///
121/// This macro should be used inside a `#[doc = ...]` attribute.
122/// See [`link_to_wgpu_docs`] for more details.
123macro_rules! link_to_wgpu_item {
124    ($kind:ident $name:ident) => {
125        $crate::link_to_wgpu_docs!(
126            [concat!("`", stringify!($name), "`")]: concat!("$kind.", stringify!($name), ".html")
127        )
128    };
129}
130
131pub(crate) use {link_to_wgpu_docs, link_to_wgpu_item};
132
133/// Integral type used for [`Buffer`] offsets and sizes.
134///
135#[doc = link_to_wgpu_item!(struct Buffer)]
136pub type BufferAddress = u64;
137
138/// Integral type used for [`BufferSlice`] sizes.
139///
140/// Note that while this type is non-zero, a [`Buffer`] *per se* can have a size of zero,
141/// but no slice or mapping can be created from it.
142///
143#[doc = link_to_wgpu_item!(struct Buffer)]
144#[doc = link_to_wgpu_item!(struct BufferSlice)]
145pub type BufferSize = core::num::NonZeroU64;
146
147/// Integral type used for binding locations in shaders.
148///
149/// Used in [`VertexAttribute`]s and errors.
150///
151#[doc = link_to_wgpu_item!(struct VertexAttribute)]
152pub type ShaderLocation = u32;
153
154/// Integral type used for
155/// [dynamic bind group offsets](../wgpu/struct.RenderPass.html#method.set_bind_group).
156pub type DynamicOffset = u32;
157
158/// Buffer-texture copies must have [`bytes_per_row`] aligned to this number.
159///
160/// This doesn't apply to [`Queue::write_texture`][Qwt], only to [`copy_buffer_to_texture()`]
161/// and [`copy_texture_to_buffer()`].
162///
163/// [`bytes_per_row`]: TexelCopyBufferLayout::bytes_per_row
164#[doc = link_to_wgpu_docs!(["`copy_buffer_to_texture()`"]: "struct.Queue.html#method.copy_buffer_to_texture")]
165#[doc = link_to_wgpu_docs!(["`copy_texture_to_buffer()`"]: "struct.Queue.html#method.copy_texture_to_buffer")]
166#[doc = link_to_wgpu_docs!(["Qwt"]: "struct.Queue.html#method.write_texture")]
167pub const COPY_BYTES_PER_ROW_ALIGNMENT: u32 = 256;
168
169/// An [offset into the query resolve buffer] has to be aligned to this.
170///
171#[doc = link_to_wgpu_docs!(["offset into the query resolve buffer"]: "struct.CommandEncoder.html#method.resolve_query_set")]
172pub const QUERY_RESOLVE_BUFFER_ALIGNMENT: BufferAddress = 256;
173
174/// Buffer to buffer copy as well as buffer clear offsets and sizes must be aligned to this number.
175pub const COPY_BUFFER_ALIGNMENT: BufferAddress = 4;
176
177/// Minimum alignment of buffer mappings.
178///
179/// The range passed to [`map_async()`] or [`get_mapped_range()`] must be at least this aligned.
180///
181#[doc = link_to_wgpu_docs!(["`map_async()`"]: "struct.Buffer.html#method.map_async")]
182#[doc = link_to_wgpu_docs!(["`get_mapped_range()`"]: "struct.Buffer.html#method.get_mapped_range")]
183pub const MAP_ALIGNMENT: BufferAddress = 8;
184
185/// [Vertex buffer offsets] and [strides] have to be a multiple of this number.
186///
187#[doc = link_to_wgpu_docs!(["Vertex buffer offsets"]: "util/trait.RenderEncoder.html#tymethod.set_vertex_buffer")]
188#[doc = link_to_wgpu_docs!(["strides"]: "struct.VertexBufferLayout.html#structfield.array_stride")]
189pub const VERTEX_ALIGNMENT: BufferAddress = 4;
190
191/// [Vertex buffer strides] have to be a multiple of this number.
192///
193#[doc = link_to_wgpu_docs!(["Vertex buffer strides"]: "struct.VertexBufferLayout.html#structfield.array_stride")]
194#[deprecated(note = "Use `VERTEX_ALIGNMENT` instead", since = "27.0.0")]
195pub const VERTEX_STRIDE_ALIGNMENT: BufferAddress = 4;
196
197/// Ranges of [writes to immediate data] must be at least this aligned.
198///
199#[doc = link_to_wgpu_docs!(["writes to immediate data"]: "struct.RenderPass.html#method.set_immediates")]
200pub const IMMEDIATE_DATA_ALIGNMENT: u32 = 4;
201
202/// Storage buffer binding sizes must be multiples of this value.
203#[doc(hidden)]
204pub const STORAGE_BINDING_SIZE_ALIGNMENT: u32 = 4;
205
206/// Maximum queries in a [`QuerySetDescriptor`].
207pub const QUERY_SET_MAX_QUERIES: u32 = 4096;
208
209/// Size in bytes of a single piece of [query] data.
210///
211#[doc = link_to_wgpu_docs!(["query"]: "struct.QuerySet.html")]
212pub const QUERY_SIZE: u32 = 8;
213
214/// The minimum allowed value for [`AdapterInfo::subgroup_min_size`].
215///
216/// See <https://gpuweb.github.io/gpuweb/#gpuadapterinfo>
217/// where you can always use these values on all devices
218pub const MINIMUM_SUBGROUP_MIN_SIZE: u32 = 4;
219/// The maximum allowed value for [`AdapterInfo::subgroup_max_size`].
220///
221/// See <https://gpuweb.github.io/gpuweb/#gpuadapterinfo>
222/// where you can always use these values on all devices.
223pub const MAXIMUM_SUBGROUP_MAX_SIZE: u32 = 128;
224
225/// Passed to `Device::poll` to control how and if it should block.
226#[derive(Clone, Debug)]
227pub enum PollType<T> {
228    /// On wgpu-core based backends, block until the given submission has
229    /// completed execution, and any callbacks have been invoked.
230    ///
231    /// On WebGPU, this has no effect. Callbacks are invoked from the
232    /// window event loop.
233    Wait {
234        /// Submission index to wait for.
235        ///
236        /// If not specified, will wait for the most recent submission at the time of the poll.
237        /// By the time the method returns, more submissions may have taken place.
238        submission_index: Option<T>,
239
240        /// Max time to wait for the submission to complete.
241        ///
242        /// If not specified, will wait indefinitely (or until an error is detected).
243        /// If waiting for the GPU device takes this long or longer, the poll will return [`PollError::Timeout`].
244        timeout: Option<Duration>,
245    },
246
247    /// Check the device for a single time without blocking.
248    Poll,
249}
250
251impl<T> PollType<T> {
252    /// Wait indefinitely until for the most recent submission to complete.
253    ///
254    /// This is a convenience function that creates a [`Self::Wait`] variant with
255    /// no timeout and no submission index.
256    #[must_use]
257    pub const fn wait_indefinitely() -> Self {
258        Self::Wait {
259            submission_index: None,
260            timeout: None,
261        }
262    }
263
264    /// This `PollType` represents a wait of some kind.
265    #[must_use]
266    pub fn is_wait(&self) -> bool {
267        match *self {
268            Self::Wait { .. } => true,
269            Self::Poll => false,
270        }
271    }
272
273    /// Map on the wait index type.
274    #[must_use]
275    pub fn map_index<U, F>(self, func: F) -> PollType<U>
276    where
277        F: FnOnce(T) -> U,
278    {
279        match self {
280            Self::Wait {
281                submission_index,
282                timeout,
283            } => PollType::Wait {
284                submission_index: submission_index.map(func),
285                timeout,
286            },
287            Self::Poll => PollType::Poll,
288        }
289    }
290}
291
292/// Error states after a device poll.
293#[derive(Debug)]
294pub enum PollError {
295    /// The requested Wait timed out before the submission was completed.
296    Timeout,
297    /// The requested Wait was given a wrong submission index.
298    WrongSubmissionIndex(u64, u64),
299}
300
301// This impl could be derived by `thiserror`, but by not doing so, we can reduce the number of
302// dependencies this early in the dependency graph, which may improve build parallelism.
303impl fmt::Display for PollError {
304    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305        match self {
306            PollError::Timeout => {
307                f.write_str("The requested Wait timed out before the submission was completed.")
308            }
309            PollError::WrongSubmissionIndex(requested, successful) => write!(
310                f,
311                "Tried to wait using a submission index ({requested}) \
312                that has not been returned by a successful submission \
313                (last successful submission: {successful}"
314            ),
315        }
316    }
317}
318
319impl core::error::Error for PollError {}
320
321/// Status of device poll operation.
322#[derive(Debug, PartialEq, Eq)]
323pub enum PollStatus {
324    /// There are no active submissions in flight as of the beginning of the poll call.
325    /// Other submissions may have been queued on other threads during the call.
326    ///
327    /// This implies that the given Wait was satisfied before the timeout.
328    QueueEmpty,
329
330    /// The requested Wait was satisfied before the timeout.
331    WaitSucceeded,
332
333    /// This was a poll.
334    Poll,
335}
336
337impl PollStatus {
338    /// Returns true if the result is [`Self::QueueEmpty`].
339    #[must_use]
340    pub fn is_queue_empty(&self) -> bool {
341        matches!(self, Self::QueueEmpty)
342    }
343
344    /// Returns true if the result is either [`Self::WaitSucceeded`] or [`Self::QueueEmpty`].
345    #[must_use]
346    pub fn wait_finished(&self) -> bool {
347        matches!(self, Self::WaitSucceeded | Self::QueueEmpty)
348    }
349}
350
351/// Describes a [`CommandEncoder`](../wgpu/struct.CommandEncoder.html).
352///
353/// Corresponds to [WebGPU `GPUCommandEncoderDescriptor`](
354/// https://gpuweb.github.io/gpuweb/#dictdef-gpucommandencoderdescriptor).
355#[repr(C)]
356#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
357#[derive(Clone, Debug, PartialEq, Eq, Hash)]
358pub struct CommandEncoderDescriptor<L> {
359    /// Debug label for the command encoder. This will show up in graphics debuggers for easy identification.
360    pub label: L,
361}
362
363impl<L> CommandEncoderDescriptor<L> {
364    /// Takes a closure and maps the label of the command encoder descriptor into another.
365    #[must_use]
366    pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> CommandEncoderDescriptor<K> {
367        CommandEncoderDescriptor {
368            label: fun(&self.label),
369        }
370    }
371}
372
373impl<T> Default for CommandEncoderDescriptor<Option<T>> {
374    fn default() -> Self {
375        Self { label: None }
376    }
377}
378
379/// RGBA double precision color.
380///
381/// This is not to be used as a generic color type, only for specific wgpu interfaces.
382#[repr(C)]
383#[derive(Clone, Copy, Debug, Default, PartialEq)]
384#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
385#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
386pub struct Color {
387    /// Red component of the color
388    pub r: f64,
389    /// Green component of the color
390    pub g: f64,
391    /// Blue component of the color
392    pub b: f64,
393    /// Alpha component of the color
394    pub a: f64,
395}
396
397#[allow(missing_docs)]
398impl Color {
399    pub const TRANSPARENT: Self = Self {
400        r: 0.0,
401        g: 0.0,
402        b: 0.0,
403        a: 0.0,
404    };
405    pub const BLACK: Self = Self {
406        r: 0.0,
407        g: 0.0,
408        b: 0.0,
409        a: 1.0,
410    };
411    pub const WHITE: Self = Self {
412        r: 1.0,
413        g: 1.0,
414        b: 1.0,
415        a: 1.0,
416    };
417    pub const RED: Self = Self {
418        r: 1.0,
419        g: 0.0,
420        b: 0.0,
421        a: 1.0,
422    };
423    pub const GREEN: Self = Self {
424        r: 0.0,
425        g: 1.0,
426        b: 0.0,
427        a: 1.0,
428    };
429    pub const BLUE: Self = Self {
430        r: 0.0,
431        g: 0.0,
432        b: 1.0,
433        a: 1.0,
434    };
435}
436
437/// Describes a [`CommandBuffer`](../wgpu/struct.CommandBuffer.html).
438///
439/// Corresponds to [WebGPU `GPUCommandBufferDescriptor`](
440/// https://gpuweb.github.io/gpuweb/#dictdef-gpucommandbufferdescriptor).
441#[repr(C)]
442#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
443#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
444pub struct CommandBufferDescriptor<L> {
445    /// Debug label of this command buffer.
446    pub label: L,
447}
448
449impl<L> CommandBufferDescriptor<L> {
450    /// Takes a closure and maps the label of the command buffer descriptor into another.
451    #[must_use]
452    pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> CommandBufferDescriptor<K> {
453        CommandBufferDescriptor {
454            label: fun(&self.label),
455        }
456    }
457}
458
459/// Describes how to create a `QuerySet`.
460///
461/// Corresponds to [WebGPU `GPUQuerySetDescriptor`](
462/// https://gpuweb.github.io/gpuweb/#dictdef-gpuquerysetdescriptor).
463#[derive(Clone, Debug)]
464#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
465pub struct QuerySetDescriptor<L> {
466    /// Debug label for the query set.
467    pub label: L,
468    /// Kind of query that this query set should contain.
469    pub ty: QueryType,
470    /// Total count of queries the set contains. Must not be zero.
471    /// Must not be greater than [`QUERY_SET_MAX_QUERIES`].
472    pub count: u32,
473}
474
475impl<L> QuerySetDescriptor<L> {
476    /// Takes a closure and maps the label of the query set descriptor into another.
477    #[must_use]
478    pub fn map_label<'a, K>(&'a self, fun: impl FnOnce(&'a L) -> K) -> QuerySetDescriptor<K> {
479        QuerySetDescriptor {
480            label: fun(&self.label),
481            ty: self.ty,
482            count: self.count,
483        }
484    }
485}
486
487/// Type of query contained in a [`QuerySet`].
488///
489/// Corresponds to [WebGPU `GPUQueryType`](
490/// https://gpuweb.github.io/gpuweb/#enumdef-gpuquerytype).
491///
492#[doc = link_to_wgpu_item!(struct QuerySet)]
493#[derive(Copy, Clone, Debug)]
494#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
495pub enum QueryType {
496    /// Query returns a single 64-bit number, serving as an occlusion boolean.
497    Occlusion,
498    /// Query returns up to 5 64-bit numbers based on the given flags.
499    ///
500    /// See [`PipelineStatisticsTypes`]'s documentation for more information
501    /// on how they get resolved.
502    ///
503    /// [`Features::PIPELINE_STATISTICS_QUERY`] must be enabled to use this query type.
504    PipelineStatistics(PipelineStatisticsTypes),
505    /// Query returns a 64-bit number indicating the GPU-timestamp
506    /// where all previous commands have finished executing.
507    ///
508    /// Must be multiplied by [`Queue::get_timestamp_period`][Qgtp] to get
509    /// the value in nanoseconds. Absolute values have no meaning,
510    /// but timestamps can be subtracted to get the time it takes
511    /// for a string of operations to complete.
512    ///
513    /// [`Features::TIMESTAMP_QUERY`] must be enabled to use this query type.
514    ///
515    #[doc = link_to_wgpu_docs!(["Qgtp"]: "struct.Queue.html#method.get_timestamp_period")]
516    Timestamp,
517}
518
519bitflags::bitflags! {
520    /// Flags for which pipeline data should be recorded in a query.
521    ///
522    /// Used in [`QueryType`].
523    ///
524    /// The amount of values written when resolved depends
525    /// on the amount of flags set. For example, if 3 flags are set, 3
526    /// 64-bit values will be written per query.
527    ///
528    /// The order they are written is the order they are declared
529    /// in these bitflags. For example, if you enabled `CLIPPER_PRIMITIVES_OUT`
530    /// and `COMPUTE_SHADER_INVOCATIONS`, it would write 16 bytes,
531    /// the first 8 bytes being the primitive out value, the last 8
532    /// bytes being the compute shader invocation count.
533    #[repr(transparent)]
534    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
535    #[cfg_attr(feature = "serde", serde(transparent))]
536    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
537    pub struct PipelineStatisticsTypes : u8 {
538        /// Amount of times the vertex shader is ran. Accounts for
539        /// the vertex cache when doing indexed rendering.
540        const VERTEX_SHADER_INVOCATIONS = 1 << 0;
541        /// Amount of times the clipper is invoked. This
542        /// is also the amount of triangles output by the vertex shader.
543        const CLIPPER_INVOCATIONS = 1 << 1;
544        /// Amount of primitives that are not culled by the clipper.
545        /// This is the amount of triangles that are actually on screen
546        /// and will be rasterized and rendered.
547        const CLIPPER_PRIMITIVES_OUT = 1 << 2;
548        /// Amount of times the fragment shader is ran. Accounts for
549        /// fragment shaders running in 2x2 blocks in order to get
550        /// derivatives.
551        const FRAGMENT_SHADER_INVOCATIONS = 1 << 3;
552        /// Amount of times a compute shader is invoked. This will
553        /// be equivalent to the dispatch count times the workgroup size.
554        const COMPUTE_SHADER_INVOCATIONS = 1 << 4;
555    }
556}
557
558/// Corresponds to a [`GPUDeviceLostReason`].
559///
560/// [`GPUDeviceLostReason`]: https://www.w3.org/TR/webgpu/#enumdef-gpudevicelostreason
561#[repr(u8)]
562#[derive(Debug, Copy, Clone, Eq, PartialEq)]
563#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
564pub enum DeviceLostReason {
565    /// The device was lost for an unspecific reason, including driver errors.
566    Unknown = 0,
567    /// The device's `destroy` method was called.
568    Destroyed = 1,
569}