Debian Codegraph @

third_party/rust/wgpu-types/src/lib.rs

raw
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, doc_auto_cfg))]
5 #![allow(
6 // We don't use syntax sugar where it's not necessary.
7 clippy::match_like_matches_macro,
8 )]
9 #![warn(clippy::ptr_as_ptr, missing_docs, unsafe_op_in_unsafe_fn)]
10 #![no_std]
11
12 #[cfg(feature = "std")]
13 extern crate std;
14
15 extern crate alloc;
16
17 use alloc::borrow::Cow;
18 use alloc::{string::String, vec, vec::Vec};
19 use core::{
20 fmt,
21 hash::{Hash, Hasher},
22 mem,
23 num::NonZeroU32,
24 ops::Range,
25 };
26
27 use bytemuck::{Pod, Zeroable};
28
29 #[cfg(any(feature = "serde", test))]
30 use {
31 alloc::format,
32 serde::{Deserialize, Serialize},
33 };
34
35 pub mod assertions;
36 mod cast_utils;
37 mod counters;
38 mod env;
39 mod features;
40 pub mod instance;
41 pub mod math;
42 mod transfers;
43
44 pub use counters::*;
45 pub use features::*;
46 pub use instance::*;
47 pub use transfers::*;
48
49 /// Integral type used for [`Buffer`] offsets and sizes.
50 ///
51 /// [`Buffer`]: ../wgpu/struct.Buffer.html
52 pub type BufferAddress = u64;
53
54 /// Integral type used for [`BufferSlice`] sizes.
55 ///
56 /// Note that while this type is non-zero, a [`Buffer`] *per se* can have a size of zero,
57 /// but no slice or mapping can be created from it.
58 ///
59 /// [`Buffer`]: ../wgpu/struct.Buffer.html
60 /// [`BufferSlice`]: ../wgpu/struct.BufferSlice.html
61 pub type BufferSize = core::num::NonZeroU64;
62
63 /// Integral type used for binding locations in shaders.
64 ///
65 /// Used in [`VertexAttribute`]s and errors.
66 ///
67 /// [`VertexAttribute`]: ../wgpu/struct.VertexAttribute.html
68 pub type ShaderLocation = u32;
69
70 /// Integral type used for
71 /// [dynamic bind group offsets](../wgpu/struct.RenderPass.html#method.set_bind_group).
72 pub type DynamicOffset = u32;
73
74 /// Buffer-to-texture copies must have [`bytes_per_row`] aligned to this number.
75 ///
76 /// This doesn't apply to [`Queue::write_texture`][Qwt], only to [`copy_buffer_to_texture()`].
77 ///
78 /// [`bytes_per_row`]: TexelCopyBufferLayout::bytes_per_row
79 /// [`copy_buffer_to_texture()`]: ../wgpu/struct.Queue.html#method.copy_buffer_to_texture
80 /// [Qwt]: ../wgpu/struct.Queue.html#method.write_texture
81 pub const COPY_BYTES_PER_ROW_ALIGNMENT: u32 = 256;
82
83 /// An [offset into the query resolve buffer] has to be aligned to this.
84 ///
85 /// [offset into the query resolve buffer]: ../wgpu/struct.CommandEncoder.html#method.resolve_query_set
86 pub const QUERY_RESOLVE_BUFFER_ALIGNMENT: BufferAddress = 256;
87
88 /// Buffer to buffer copy as well as buffer clear offsets and sizes must be aligned to this number.
89 pub const COPY_BUFFER_ALIGNMENT: BufferAddress = 4;
90
91 /// Minimum alignment of buffer mappings.
92 ///
93 /// The range passed to [`map_async()`] or [`get_mapped_range()`] must be at least this aligned.
94 ///
95 /// [`map_async()`]: ../wgpu/struct.Buffer.html#method.map_async
96 /// [`get_mapped_range()`]: ../wgpu/struct.Buffer.html#method.get_mapped_range
97 pub const MAP_ALIGNMENT: BufferAddress = 8;
98
99 /// [Vertex buffer strides] have to be a multiple of this number.
100 ///
101 /// [Vertex buffer strides]: ../wgpu/struct.VertexBufferLayout.html#structfield.array_stride
102 pub const VERTEX_STRIDE_ALIGNMENT: BufferAddress = 4;
103 /// Ranges of [writes to push constant storage] must be at least this aligned.
104 ///
105 /// [writes to push constant storage]: ../wgpu/struct.RenderPass.html#method.set_push_constants
106 pub const PUSH_CONSTANT_ALIGNMENT: u32 = 4;
107
108 /// Maximum queries in a [`QuerySetDescriptor`].
109 pub const QUERY_SET_MAX_QUERIES: u32 = 4096;
110
111 /// Size in bytes of a single piece of [query] data.
112 ///
113 /// [query]: ../wgpu/struct.QuerySet.html
114 pub const QUERY_SIZE: u32 = 8;
115
116 /// Backends supported by wgpu.
117 ///
118 /// See also [`Backends`].
119 #[repr(u8)]
120 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
121 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
122 pub enum Backend {
123 /// Dummy backend, which may be used for testing.
124 ///
125 /// It performs no rendering or computation, but allows creation of stub GPU resource types,
126 /// so that code which manages GPU resources can be tested without an available GPU.
127 /// Specifically, the following operations are implemented:
128 ///
129 /// * Enumerating adapters will always return one noop adapter, which can be used to create
130 /// devices.
131 /// * Buffers may be created, written, mapped, and copied to other buffers.
132 /// * Command encoders may be created, but only buffer operations are useful.
133 ///
134 /// Other resources can be created but are nonfunctional; notably,
135 ///
136 /// * Render passes and compute passes are not executed.
137 /// * Textures may be created, but do not store any texels.
138 /// * There are no compatible surfaces.
139 ///
140 /// An adapter using the noop backend can only be obtained if [`NoopBackendOptions`]
141 /// enables it, in addition to the ordinary requirement of [`Backends::NOOP`] being set.
142 /// This ensures that applications not desiring a non-functional backend will not receive it.
143 Noop = 0,
144 /// Vulkan API (Windows, Linux, Android, MacOS via `vulkan-portability`/MoltenVK)
145 Vulkan = 1,
146 /// Metal API (Apple platforms)
147 Metal = 2,
148 /// Direct3D-12 (Windows)
149 Dx12 = 3,
150 /// OpenGL 3.3+ (Windows), OpenGL ES 3.0+ (Linux, Android, MacOS via Angle), and WebGL2
151 Gl = 4,
152 /// WebGPU in the browser
153 BrowserWebGpu = 5,
154 }
155
156 impl Backend {
157 /// Array of all [`Backend`] values, corresponding to [`Backends::all()`].
158 pub const ALL: [Backend; Backends::all().bits().count_ones() as usize] = [
159 Self::Noop,
160 Self::Vulkan,
161 Self::Metal,
162 Self::Dx12,
163 Self::Gl,
164 Self::BrowserWebGpu,
165 ];
166
167 /// Returns the string name of the backend.
168 #[must_use]
169 pub const fn to_str(self) -> &'static str {
170 match self {
171 Backend::Noop => "noop",
172 Backend::Vulkan => "vulkan",
173 Backend::Metal => "metal",
174 Backend::Dx12 => "dx12",
175 Backend::Gl => "gl",
176 Backend::BrowserWebGpu => "webgpu",
177 }
178 }
179 }
180
181 impl core::fmt::Display for Backend {
182 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
183 f.write_str(self.to_str())
184 }
185 }
186
187 /// Power Preference when choosing a physical adapter.
188 ///
189 /// Corresponds to [WebGPU `GPUPowerPreference`](
190 /// https://gpuweb.github.io/gpuweb/#enumdef-gpupowerpreference).
191 #[repr(C)]
192 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
193 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
194 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
195 pub enum PowerPreference {
196 #[default]
197 /// Power usage is not considered when choosing an adapter.
198 None = 0,
199 /// Adapter that uses the least possible power. This is often an integrated GPU.
200 LowPower = 1,
201 /// Adapter that has the highest performance. This is often a discrete GPU.
202 HighPerformance = 2,
203 }
204
205 impl PowerPreference {
206 /// Get a power preference from the environment variable `WGPU_POWER_PREF`.
207 pub fn from_env() -> Option<Self> {
208 let env = crate::env::var("WGPU_POWER_PREF")?;
209 match env.to_lowercase().as_str() {
210 "low" => Some(Self::LowPower),
211 "high" => Some(Self::HighPerformance),
212 "none" => Some(Self::None),
213 _ => None,
214 }
215 }
216 }
217
218 bitflags::bitflags! {
219 /// Represents the backends that wgpu will use.
220 #[repr(transparent)]
221 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
222 #[cfg_attr(feature = "serde", serde(transparent))]
223 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
224 pub struct Backends: u32 {
225 /// [`Backend::Noop`].
226 const NOOP = 1 << Backend::Noop as u32;
227
228 /// [`Backend::Vulkan`].
229 /// Supported on Windows, Linux/Android, and macOS/iOS via Vulkan Portability (with the Vulkan feature enabled)
230 const VULKAN = 1 << Backend::Vulkan as u32;
231
232 /// [`Backend::Gl`].
233 /// Supported on Linux/Android, the web through webassembly via WebGL, and Windows and
234 /// macOS/iOS via ANGLE
235 const GL = 1 << Backend::Gl as u32;
236
237 /// [`Backend::Metal`].
238 /// Supported on macOS and iOS.
239 const METAL = 1 << Backend::Metal as u32;
240
241 /// [`Backend::Dx12`].
242 /// Supported on Windows 10 and later
243 const DX12 = 1 << Backend::Dx12 as u32;
244
245 /// [`Backend::BrowserWebGpu`].
246 /// Supported when targeting the web through WebAssembly with the `webgpu` feature enabled.
247 ///
248 /// The WebGPU backend is special in several ways:
249 /// It is not not implemented by `wgpu_core` and instead by the higher level `wgpu` crate.
250 /// Whether WebGPU is targeted is decided upon the creation of the `wgpu::Instance`,
251 /// *not* upon adapter creation. See `wgpu::Instance::new`.
252 const BROWSER_WEBGPU = 1 << Backend::BrowserWebGpu as u32;
253
254 /// All the apis that wgpu offers first tier of support for.
255 ///
256 /// * [`Backends::VULKAN`]
257 /// * [`Backends::METAL`]
258 /// * [`Backends::DX12`]
259 /// * [`Backends::BROWSER_WEBGPU`]
260 const PRIMARY = Self::VULKAN.bits()
261 | Self::METAL.bits()
262 | Self::DX12.bits()
263 | Self::BROWSER_WEBGPU.bits();
264
265 /// All the apis that wgpu offers second tier of support for. These may
266 /// be unsupported/still experimental.
267 ///
268 /// * [`Backends::GL`]
269 const SECONDARY = Self::GL.bits();
270 }
271 }
272
273 impl Default for Backends {
274 fn default() -> Self {
275 Self::all()
276 }
277 }
278
279 impl From<Backend> for Backends {
280 fn from(backend: Backend) -> Self {
281 Self::from_bits(1 << backend as u32).unwrap()
282 }
283 }
284
285 impl Backends {
286 /// Gets a set of backends from the environment variable `WGPU_BACKEND`.
287 ///
288 /// See [`Self::from_comma_list()`] for the format of the string.
289 pub fn from_env() -> Option<Self> {
290 let env = crate::env::var("WGPU_BACKEND")?;
291 Some(Self::from_comma_list(&env))
292 }
293
294 /// Takes the given options, modifies them based on the `WGPU_BACKEND` environment variable, and returns the result.
295 pub fn with_env(&self) -> Self {
296 if let Some(env) = Self::from_env() {
297 env
298 } else {
299 *self
300 }
301 }
302
303 /// Generates a set of backends from a comma separated list of case-insensitive backend names.
304 ///
305 /// Whitespace is stripped, so both 'gl, dx12' and 'gl,dx12' are valid.
306 ///
307 /// Always returns WEBGPU on wasm over webgpu.
308 ///
309 /// Names:
310 /// - vulkan = "vulkan" or "vk"
311 /// - dx12 = "dx12" or "d3d12"
312 /// - metal = "metal" or "mtl"
313 /// - gles = "opengl" or "gles" or "gl"
314 /// - webgpu = "webgpu"
315 pub fn from_comma_list(string: &str) -> Self {
316 let mut backends = Self::empty();
317 for backend in string.to_lowercase().split(',') {
318 backends |= match backend.trim() {
319 "vulkan" | "vk" => Self::VULKAN,
320 "dx12" | "d3d12" => Self::DX12,
321 "metal" | "mtl" => Self::METAL,
322 "opengl" | "gles" | "gl" => Self::GL,
323 "webgpu" => Self::BROWSER_WEBGPU,
324 "noop" => Self::NOOP,
325 b => {
326 log::warn!("unknown backend string '{}'", b);
327 continue;
328 }
329 }
330 }
331
332 if backends.is_empty() {
333 log::warn!("no valid backend strings found!");
334 }
335
336 backends
337 }
338 }
339
340 /// Options for requesting adapter.
341 ///
342 /// Corresponds to [WebGPU `GPURequestAdapterOptions`](
343 /// https://gpuweb.github.io/gpuweb/#dictdef-gpurequestadapteroptions).
344 #[repr(C)]
345 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
346 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
347 pub struct RequestAdapterOptions<S> {
348 /// Power preference for the adapter.
349 pub power_preference: PowerPreference,
350 /// Indicates that only a fallback adapter can be returned. This is generally a "software"
351 /// implementation on the system.
352 pub force_fallback_adapter: bool,
353 /// Surface that is required to be presentable with the requested adapter. This does not
354 /// create the surface, only guarantees that the adapter can present to said surface.
355 /// For WebGL, this is strictly required, as an adapter can not be created without a surface.
356 pub compatible_surface: Option<S>,
357 }
358
359 impl<S> Default for RequestAdapterOptions<S> {
360 fn default() -> Self {
361 Self {
362 power_preference: PowerPreference::default(),
363 force_fallback_adapter: false,
364 compatible_surface: None,
365 }
366 }
367 }
368
369 /// Error when [`Instance::request_adapter()`] fails.
370 ///
371 /// This type is not part of the WebGPU standard, where `requestAdapter()` would simply return null.
372 ///
373 /// [`Instance::request_adapter()`]: ../wgpu/struct.Instance.html#method.request_adapter
374 #[derive(Clone, Debug, PartialEq)]
375 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
376 #[non_exhaustive]
377 pub enum RequestAdapterError {
378 /// No adapter available via the instance’s backends matched the request’s adapter criteria.
379 NotFound {
380 // These fields must be set by wgpu-core and wgpu, but are not intended to be stable API,
381 // only data for the production of the error message.
382 #[doc(hidden)]
383 active_backends: Backends,
384 #[doc(hidden)]
385 requested_backends: Backends,
386 #[doc(hidden)]
387 supported_backends: Backends,
388 #[doc(hidden)]
389 no_fallback_backends: Backends,
390 #[doc(hidden)]
391 no_adapter_backends: Backends,
392 #[doc(hidden)]
393 incompatible_surface_backends: Backends,
394 },
395
396 /// Attempted to obtain adapter specified by environment variable, but the environment variable
397 /// was not set.
398 EnvNotSet,
399 }
400
401 impl core::error::Error for RequestAdapterError {}
402 impl fmt::Display for RequestAdapterError {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 match self {
405 RequestAdapterError::NotFound {
406 active_backends,
407 requested_backends,
408 supported_backends,
409 no_fallback_backends,
410 no_adapter_backends,
411 incompatible_surface_backends,
412 } => {
413 write!(f, "No suitable graphics adapter found; ")?;
414 let mut first = true;
415 for backend in Backend::ALL {
416 let bit = Backends::from(backend);
417 let comma = if mem::take(&mut first) { "" } else { ", " };
418 let explanation = if !requested_backends.contains(bit) {
419 // We prefer reporting this, because it makes the error most stable with
420 // respect to what is directly controllable by the caller, as opposed to
421 // compilation options or the run-time environment.
422 "not requested"
423 } else if !supported_backends.contains(bit) {
424 "support not compiled in"
425 } else if no_adapter_backends.contains(bit) {
426 "found no adapters"
427 } else if incompatible_surface_backends.contains(bit) {
428 "not compatible with provided surface"
429 } else if no_fallback_backends.contains(bit) {
430 "had no fallback adapters"
431 } else if !active_backends.contains(bit) {
432 // Backend requested but not active in this instance
433 if backend == Backend::Noop {
434 "not explicitly enabled"
435 } else {
436 "drivers/libraries could not be loaded"
437 }
438 } else {
439 // This path should be unreachable, but don't crash.
440 "[unknown reason]"
441 };
442 write!(f, "{comma}{backend} {explanation}")?;
443 }
444 }
445 RequestAdapterError::EnvNotSet => f.write_str("WGPU_ADAPTER_NAME not set")?,
446 }
447 Ok(())
448 }
449 }
450
451 /// Represents the sets of limits an adapter/device supports.
452 ///
453 /// We provide three different defaults.
454 /// - [`Limits::downlevel_defaults()`]. This is a set of limits that is guaranteed to work on almost
455 /// all backends, including "downlevel" backends such as OpenGL and D3D11, other than WebGL. For
456 /// most applications we recommend using these limits, assuming they are high enough for your
457 /// application, and you do not intent to support WebGL.
458 /// - [`Limits::downlevel_webgl2_defaults()`] This is a set of limits that is lower even than the
459 /// [`downlevel_defaults()`], configured to be low enough to support running in the browser using
460 /// WebGL2.
461 /// - [`Limits::default()`]. This is the set of limits that is guaranteed to work on all modern
462 /// backends and is guaranteed to be supported by WebGPU. Applications needing more modern
463 /// features can use this as a reasonable set of limits if they are targeting only desktop and
464 /// modern mobile devices.
465 ///
466 /// We recommend starting with the most restrictive limits you can and manually increasing the
467 /// limits you need boosted. This will let you stay running on all hardware that supports the limits
468 /// you need.
469 ///
470 /// Limits "better" than the default must be supported by the adapter and requested when requesting
471 /// a device. If limits "better" than the adapter supports are requested, requesting a device will
472 /// panic. Once a device is requested, you may only use resources up to the limits requested _even_
473 /// if the adapter supports "better" limits.
474 ///
475 /// Requesting limits that are "better" than you need may cause performance to decrease because the
476 /// implementation needs to support more than is needed. You should ideally only request exactly
477 /// what you need.
478 ///
479 /// Corresponds to [WebGPU `GPUSupportedLimits`](
480 /// https://gpuweb.github.io/gpuweb/#gpusupportedlimits).
481 ///
482 /// [`downlevel_defaults()`]: Limits::downlevel_defaults
483 #[repr(C)]
484 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
485 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
486 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase", default))]
487 pub struct Limits {
488 /// Maximum allowed value for the `size.width` of a texture created with `TextureDimension::D1`.
489 /// Defaults to 8192. Higher is "better".
490 #[cfg_attr(feature = "serde", serde(rename = "maxTextureDimension1D"))]
491 pub max_texture_dimension_1d: u32,
492 /// Maximum allowed value for the `size.width` and `size.height` of a texture created with `TextureDimension::D2`.
493 /// Defaults to 8192. Higher is "better".
494 #[cfg_attr(feature = "serde", serde(rename = "maxTextureDimension2D"))]
495 pub max_texture_dimension_2d: u32,
496 /// Maximum allowed value for the `size.width`, `size.height`, and `size.depth_or_array_layers`
497 /// of a texture created with `TextureDimension::D3`.
498 /// Defaults to 2048. Higher is "better".
499 #[cfg_attr(feature = "serde", serde(rename = "maxTextureDimension3D"))]
500 pub max_texture_dimension_3d: u32,
501 /// Maximum allowed value for the `size.depth_or_array_layers` of a texture created with `TextureDimension::D2`.
502 /// Defaults to 256. Higher is "better".
503 pub max_texture_array_layers: u32,
504 /// Amount of bind groups that can be attached to a pipeline at the same time. Defaults to 4. Higher is "better".
505 pub max_bind_groups: u32,
506 /// Maximum binding index allowed in `create_bind_group_layout`. Defaults to 1000. Higher is "better".
507 pub max_bindings_per_bind_group: u32,
508 /// Amount of uniform buffer bindings that can be dynamic in a single pipeline. Defaults to 8. Higher is "better".
509 pub max_dynamic_uniform_buffers_per_pipeline_layout: u32,
510 /// Amount of storage buffer bindings that can be dynamic in a single pipeline. Defaults to 4. Higher is "better".
511 pub max_dynamic_storage_buffers_per_pipeline_layout: u32,
512 /// Amount of sampled textures visible in a single shader stage. Defaults to 16. Higher is "better".
513 pub max_sampled_textures_per_shader_stage: u32,
514 /// Amount of samplers visible in a single shader stage. Defaults to 16. Higher is "better".
515 pub max_samplers_per_shader_stage: u32,
516 /// Amount of storage buffers visible in a single shader stage. Defaults to 8. Higher is "better".
517 pub max_storage_buffers_per_shader_stage: u32,
518 /// Amount of storage textures visible in a single shader stage. Defaults to 4. Higher is "better".
519 pub max_storage_textures_per_shader_stage: u32,
520 /// Amount of uniform buffers visible in a single shader stage. Defaults to 12. Higher is "better".
521 pub max_uniform_buffers_per_shader_stage: u32,
522 /// Amount of individual resources within binding arrays that can be accessed in a single shader stage. Applies
523 /// to all types of bindings except samplers.
524 ///
525 /// This "defaults" to 0. However if binding arrays are supported, all devices can support 500,000. Higher is "better".
526 pub max_binding_array_elements_per_shader_stage: u32,
527 /// Amount of individual samplers within binding arrays that can be accessed in a single shader stage.
528 ///
529 /// This "defaults" to 0. However if binding arrays are supported, all devices can support 1,000. Higher is "better".
530 pub max_binding_array_sampler_elements_per_shader_stage: u32,
531 /// Maximum size in bytes of a binding to a uniform buffer. Defaults to 64 KiB. Higher is "better".
532 pub max_uniform_buffer_binding_size: u32,
533 /// Maximum size in bytes of a binding to a storage buffer. Defaults to 128 MiB. Higher is "better".
534 pub max_storage_buffer_binding_size: u32,
535 /// Maximum length of `VertexState::buffers` when creating a `RenderPipeline`.
536 /// Defaults to 8. Higher is "better".
537 pub max_vertex_buffers: u32,
538 /// A limit above which buffer allocations are guaranteed to fail.
539 /// Defaults to 256 MiB. Higher is "better".
540 ///
541 /// Buffer allocations below the maximum buffer size may not succeed depending on available memory,
542 /// fragmentation and other factors.
543 pub max_buffer_size: u64,
544 /// Maximum length of `VertexBufferLayout::attributes`, summed over all `VertexState::buffers`,
545 /// when creating a `RenderPipeline`.
546 /// Defaults to 16. Higher is "better".
547 pub max_vertex_attributes: u32,
548 /// Maximum value for `VertexBufferLayout::array_stride` when creating a `RenderPipeline`.
549 /// Defaults to 2048. Higher is "better".
550 pub max_vertex_buffer_array_stride: u32,
551 /// Required `BufferBindingType::Uniform` alignment for `BufferBinding::offset`
552 /// when creating a `BindGroup`, or for `set_bind_group` `dynamicOffsets`.
553 /// Defaults to 256. Lower is "better".
554 pub min_uniform_buffer_offset_alignment: u32,
555 /// Required `BufferBindingType::Storage` alignment for `BufferBinding::offset`
556 /// when creating a `BindGroup`, or for `set_bind_group` `dynamicOffsets`.
557 /// Defaults to 256. Lower is "better".
558 pub min_storage_buffer_offset_alignment: u32,
559 /// Maximum allowed number of components (scalars) of input or output locations for
560 /// inter-stage communication (vertex outputs to fragment inputs). Defaults to 60.
561 /// Higher is "better".
562 pub max_inter_stage_shader_components: u32,
563 /// The maximum allowed number of color attachments.
564 pub max_color_attachments: u32,
565 /// The maximum number of bytes necessary to hold one sample (pixel or subpixel) of render
566 /// pipeline output data, across all color attachments as described by [`TextureFormat::target_pixel_byte_cost`]
567 /// and [`TextureFormat::target_component_alignment`]. Defaults to 32. Higher is "better".
568 ///
569 /// ⚠️ `Rgba8Unorm`/`Rgba8Snorm`/`Bgra8Unorm`/`Bgra8Snorm` are deceptively 8 bytes per sample. ⚠️
570 pub max_color_attachment_bytes_per_sample: u32,
571 /// Maximum number of bytes used for workgroup memory in a compute entry point. Defaults to
572 /// 16384. Higher is "better".
573 pub max_compute_workgroup_storage_size: u32,
574 /// Maximum value of the product of the `workgroup_size` dimensions for a compute entry-point.
575 /// Defaults to 256. Higher is "better".
576 pub max_compute_invocations_per_workgroup: u32,
577 /// The maximum value of the `workgroup_size` X dimension for a compute stage `ShaderModule` entry-point.
578 /// Defaults to 256. Higher is "better".
579 pub max_compute_workgroup_size_x: u32,
580 /// The maximum value of the `workgroup_size` Y dimension for a compute stage `ShaderModule` entry-point.
581 /// Defaults to 256. Higher is "better".
582 pub max_compute_workgroup_size_y: u32,
583 /// The maximum value of the `workgroup_size` Z dimension for a compute stage `ShaderModule` entry-point.
584 /// Defaults to 64. Higher is "better".
585 pub max_compute_workgroup_size_z: u32,
586 /// The maximum value for each dimension of a `ComputePass::dispatch(x, y, z)` operation.
587 /// Defaults to 65535. Higher is "better".
588 pub max_compute_workgroups_per_dimension: u32,
589
590 /// Minimal number of invocations in a subgroup. Higher is "better".
591 pub min_subgroup_size: u32,
592 /// Maximal number of invocations in a subgroup. Lower is "better".
593 pub max_subgroup_size: u32,
594 /// Amount of storage available for push constants in bytes. Defaults to 0. Higher is "better".
595 /// Requesting more than 0 during device creation requires [`Features::PUSH_CONSTANTS`] to be enabled.
596 ///
597 /// Expect the size to be:
598 /// - Vulkan: 128-256 bytes
599 /// - DX12: 256 bytes
600 /// - Metal: 4096 bytes
601 /// - OpenGL doesn't natively support push constants, and are emulated with uniforms,
602 /// so this number is less useful but likely 256.
603 pub max_push_constant_size: u32,
604 /// Maximum number of live non-sampler bindings.
605 ///
606 /// This limit only affects the d3d12 backend. Using a large number will allow the device
607 /// to create many bind groups at the cost of a large up-front allocation at device creation.
608 pub max_non_sampler_bindings: u32,
609 }
610
611 impl Default for Limits {
612 fn default() -> Self {
613 Self::defaults()
614 }
615 }
616
617 impl Limits {
618 /// These default limits are guaranteed to to work on all modern
619 /// backends and guaranteed to be supported by WebGPU
620 ///
621 /// Those limits are as follows:
622 /// ```rust
623 /// # use wgpu_types::Limits;
624 /// assert_eq!(Limits::defaults(), Limits {
625 /// max_texture_dimension_1d: 8192,
626 /// max_texture_dimension_2d: 8192,
627 /// max_texture_dimension_3d: 2048,
628 /// max_texture_array_layers: 256,
629 /// max_bind_groups: 4,
630 /// max_bindings_per_bind_group: 1000,
631 /// max_dynamic_uniform_buffers_per_pipeline_layout: 8,
632 /// max_dynamic_storage_buffers_per_pipeline_layout: 4,
633 /// max_sampled_textures_per_shader_stage: 16,
634 /// max_samplers_per_shader_stage: 16,
635 /// max_storage_buffers_per_shader_stage: 8,
636 /// max_storage_textures_per_shader_stage: 4,
637 /// max_uniform_buffers_per_shader_stage: 12,
638 /// max_binding_array_elements_per_shader_stage: 0,
639 /// max_binding_array_sampler_elements_per_shader_stage: 0,
640 /// max_uniform_buffer_binding_size: 64 << 10, // (64 KiB)
641 /// max_storage_buffer_binding_size: 128 << 20, // (128 MiB)
642 /// max_vertex_buffers: 8,
643 /// max_buffer_size: 256 << 20, // (256 MiB)
644 /// max_vertex_attributes: 16,
645 /// max_vertex_buffer_array_stride: 2048,
646 /// min_uniform_buffer_offset_alignment: 256,
647 /// min_storage_buffer_offset_alignment: 256,
648 /// max_inter_stage_shader_components: 60,
649 /// max_color_attachments: 8,
650 /// max_color_attachment_bytes_per_sample: 32,
651 /// max_compute_workgroup_storage_size: 16384,
652 /// max_compute_invocations_per_workgroup: 256,
653 /// max_compute_workgroup_size_x: 256,
654 /// max_compute_workgroup_size_y: 256,
655 /// max_compute_workgroup_size_z: 64,
656 /// max_compute_workgroups_per_dimension: 65535,
657 /// min_subgroup_size: 0,
658 /// max_subgroup_size: 0,
659 /// max_push_constant_size: 0,
660 /// max_non_sampler_bindings: 1_000_000,
661 /// });
662 /// ```
663 ///
664 /// Rust doesn't allow const in trait implementations, so we break this out
665 /// to allow reusing these defaults in const contexts
666 #[must_use]
667 pub const fn defaults() -> Self {
668 Self {
669 max_texture_dimension_1d: 8192,
670 max_texture_dimension_2d: 8192,
671 max_texture_dimension_3d: 2048,
672 max_texture_array_layers: 256,
673 max_bind_groups: 4,
674 max_bindings_per_bind_group: 1000,
675 max_dynamic_uniform_buffers_per_pipeline_layout: 8,
676 max_dynamic_storage_buffers_per_pipeline_layout: 4,
677 max_sampled_textures_per_shader_stage: 16,
678 max_samplers_per_shader_stage: 16,
679 max_storage_buffers_per_shader_stage: 8,
680 max_storage_textures_per_shader_stage: 4,
681 max_uniform_buffers_per_shader_stage: 12,
682 max_binding_array_elements_per_shader_stage: 0,
683 max_binding_array_sampler_elements_per_shader_stage: 0,
684 max_uniform_buffer_binding_size: 64 << 10, // (64 KiB)
685 max_storage_buffer_binding_size: 128 << 20, // (128 MiB)
686 max_vertex_buffers: 8,
687 max_buffer_size: 256 << 20, // (256 MiB)
688 max_vertex_attributes: 16,
689 max_vertex_buffer_array_stride: 2048,
690 min_uniform_buffer_offset_alignment: 256,
691 min_storage_buffer_offset_alignment: 256,
692 max_inter_stage_shader_components: 60,
693 max_color_attachments: 8,
694 max_color_attachment_bytes_per_sample: 32,
695 max_compute_workgroup_storage_size: 16384,
696 max_compute_invocations_per_workgroup: 256,
697 max_compute_workgroup_size_x: 256,
698 max_compute_workgroup_size_y: 256,
699 max_compute_workgroup_size_z: 64,
700 max_compute_workgroups_per_dimension: 65535,
701 min_subgroup_size: 0,
702 max_subgroup_size: 0,
703 max_push_constant_size: 0,
704 max_non_sampler_bindings: 1_000_000,
705 }
706 }
707
708 /// These default limits are guaranteed to be compatible with GLES-3.1, and D3D11
709 ///
710 /// Those limits are as follows (different from default are marked with *):
711 /// ```rust
712 /// # use wgpu_types::Limits;
713 /// assert_eq!(Limits::downlevel_defaults(), Limits {
714 /// max_texture_dimension_1d: 2048, // *
715 /// max_texture_dimension_2d: 2048, // *
716 /// max_texture_dimension_3d: 256, // *
717 /// max_texture_array_layers: 256,
718 /// max_bind_groups: 4,
719 /// max_bindings_per_bind_group: 1000,
720 /// max_dynamic_uniform_buffers_per_pipeline_layout: 8,
721 /// max_dynamic_storage_buffers_per_pipeline_layout: 4,
722 /// max_sampled_textures_per_shader_stage: 16,
723 /// max_samplers_per_shader_stage: 16,
724 /// max_storage_buffers_per_shader_stage: 4, // *
725 /// max_storage_textures_per_shader_stage: 4,
726 /// max_uniform_buffers_per_shader_stage: 12,
727 /// max_binding_array_elements_per_shader_stage: 0,
728 /// max_binding_array_sampler_elements_per_shader_stage: 0,
729 /// max_uniform_buffer_binding_size: 16 << 10, // * (16 KiB)
730 /// max_storage_buffer_binding_size: 128 << 20, // (128 MiB)
731 /// max_vertex_buffers: 8,
732 /// max_vertex_attributes: 16,
733 /// max_vertex_buffer_array_stride: 2048,
734 /// min_subgroup_size: 0,
735 /// max_subgroup_size: 0,
736 /// max_push_constant_size: 0,
737 /// min_uniform_buffer_offset_alignment: 256,
738 /// min_storage_buffer_offset_alignment: 256,
739 /// max_inter_stage_shader_components: 60,
740 /// max_color_attachments: 4,
741 /// max_color_attachment_bytes_per_sample: 32,
742 /// max_compute_workgroup_storage_size: 16352, // *
743 /// max_compute_invocations_per_workgroup: 256,
744 /// max_compute_workgroup_size_x: 256,
745 /// max_compute_workgroup_size_y: 256,
746 /// max_compute_workgroup_size_z: 64,
747 /// max_compute_workgroups_per_dimension: 65535,
748 /// max_buffer_size: 256 << 20, // (256 MiB)
749 /// max_non_sampler_bindings: 1_000_000,
750 /// });
751 /// ```
752 #[must_use]
753 pub const fn downlevel_defaults() -> Self {
754 Self {
755 max_texture_dimension_1d: 2048,
756 max_texture_dimension_2d: 2048,
757 max_texture_dimension_3d: 256,
758 max_storage_buffers_per_shader_stage: 4,
759 max_uniform_buffer_binding_size: 16 << 10, // (16 KiB)
760 max_color_attachments: 4,
761 // see: https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=7
762 max_compute_workgroup_storage_size: 16352,
763 ..Self::defaults()
764 }
765 }
766
767 /// These default limits are guaranteed to be compatible with GLES-3.0, and D3D11, and WebGL2
768 ///
769 /// Those limits are as follows (different from `downlevel_defaults` are marked with +,
770 /// *'s from `downlevel_defaults` shown as well.):
771 /// ```rust
772 /// # use wgpu_types::Limits;
773 /// assert_eq!(Limits::downlevel_webgl2_defaults(), Limits {
774 /// max_texture_dimension_1d: 2048, // *
775 /// max_texture_dimension_2d: 2048, // *
776 /// max_texture_dimension_3d: 256, // *
777 /// max_texture_array_layers: 256,
778 /// max_bind_groups: 4,
779 /// max_bindings_per_bind_group: 1000,
780 /// max_dynamic_uniform_buffers_per_pipeline_layout: 8,
781 /// max_dynamic_storage_buffers_per_pipeline_layout: 0, // +
782 /// max_sampled_textures_per_shader_stage: 16,
783 /// max_samplers_per_shader_stage: 16,
784 /// max_storage_buffers_per_shader_stage: 0, // * +
785 /// max_storage_textures_per_shader_stage: 0, // +
786 /// max_uniform_buffers_per_shader_stage: 11, // +
787 /// max_binding_array_elements_per_shader_stage: 0,
788 /// max_binding_array_sampler_elements_per_shader_stage: 0,
789 /// max_uniform_buffer_binding_size: 16 << 10, // * (16 KiB)
790 /// max_storage_buffer_binding_size: 0, // * +
791 /// max_vertex_buffers: 8,
792 /// max_vertex_attributes: 16,
793 /// max_vertex_buffer_array_stride: 255, // +
794 /// min_subgroup_size: 0,
795 /// max_subgroup_size: 0,
796 /// max_push_constant_size: 0,
797 /// min_uniform_buffer_offset_alignment: 256,
798 /// min_storage_buffer_offset_alignment: 256,
799 /// max_inter_stage_shader_components: 31,
800 /// max_color_attachments: 4,
801 /// max_color_attachment_bytes_per_sample: 32,
802 /// max_compute_workgroup_storage_size: 0, // +
803 /// max_compute_invocations_per_workgroup: 0, // +
804 /// max_compute_workgroup_size_x: 0, // +
805 /// max_compute_workgroup_size_y: 0, // +
806 /// max_compute_workgroup_size_z: 0, // +
807 /// max_compute_workgroups_per_dimension: 0, // +
808 /// max_buffer_size: 256 << 20, // (256 MiB),
809 /// max_non_sampler_bindings: 1_000_000,
810 /// });
811 /// ```
812 #[must_use]
813 pub const fn downlevel_webgl2_defaults() -> Self {
814 Self {
815 max_uniform_buffers_per_shader_stage: 11,
816 max_storage_buffers_per_shader_stage: 0,
817 max_storage_textures_per_shader_stage: 0,
818 max_dynamic_storage_buffers_per_pipeline_layout: 0,
819 max_storage_buffer_binding_size: 0,
820 max_vertex_buffer_array_stride: 255,
821 max_compute_workgroup_storage_size: 0,
822 max_compute_invocations_per_workgroup: 0,
823 max_compute_workgroup_size_x: 0,
824 max_compute_workgroup_size_y: 0,
825 max_compute_workgroup_size_z: 0,
826 max_compute_workgroups_per_dimension: 0,
827 min_subgroup_size: 0,
828 max_subgroup_size: 0,
829
830 // Value supported by Intel Celeron B830 on Windows (OpenGL 3.1)
831 max_inter_stage_shader_components: 31,
832
833 // Most of the values should be the same as the downlevel defaults
834 ..Self::downlevel_defaults()
835 }
836 }
837
838 /// Modify the current limits to use the resolution limits of the other.
839 ///
840 /// This is useful because the swapchain might need to be larger than any other image in the application.
841 ///
842 /// If your application only needs 512x512, you might be running on a 4k display and need extremely high resolution limits.
843 #[must_use]
844 pub const fn using_resolution(self, other: Self) -> Self {
845 Self {
846 max_texture_dimension_1d: other.max_texture_dimension_1d,
847 max_texture_dimension_2d: other.max_texture_dimension_2d,
848 max_texture_dimension_3d: other.max_texture_dimension_3d,
849 ..self
850 }
851 }
852
853 /// Modify the current limits to use the buffer alignment limits of the adapter.
854 ///
855 /// This is useful for when you'd like to dynamically use the "best" supported buffer alignments.
856 #[must_use]
857 pub const fn using_alignment(self, other: Self) -> Self {
858 Self {
859 min_uniform_buffer_offset_alignment: other.min_uniform_buffer_offset_alignment,
860 min_storage_buffer_offset_alignment: other.min_storage_buffer_offset_alignment,
861 ..self
862 }
863 }
864
865 /// Compares every limits within self is within the limits given in `allowed`.
866 ///
867 /// If you need detailed information on failures, look at [`Limits::check_limits_with_fail_fn`].
868 #[must_use]
869 pub fn check_limits(&self, allowed: &Self) -> bool {
870 let mut within = true;
871 self.check_limits_with_fail_fn(allowed, true, |_, _, _| within = false);
872 within
873 }
874
875 /// Compares every limits within self is within the limits given in `allowed`.
876 /// For an easy to use binary choice, use [`Limits::check_limits`].
877 ///
878 /// If a value is not within the allowed limit, this function calls the `fail_fn`
879 /// with the:
880 /// - limit name
881 /// - self's limit
882 /// - allowed's limit.
883 ///
884 /// If fatal is true, a single failure bails out the comparison after a single failure.
885 pub fn check_limits_with_fail_fn(
886 &self,
887 allowed: &Self,
888 fatal: bool,
889 mut fail_fn: impl FnMut(&'static str, u64, u64),
890 ) {
891 use core::cmp::Ordering;
892
893 macro_rules! compare {
894 ($name:ident, $ordering:ident) => {
895 match self.$name.cmp(&allowed.$name) {
896 Ordering::$ordering | Ordering::Equal => (),
897 _ => {
898 fail_fn(stringify!($name), self.$name as u64, allowed.$name as u64);
899 if fatal {
900 return;
901 }
902 }
903 }
904 };
905 }
906
907 compare!(max_texture_dimension_1d, Less);
908 compare!(max_texture_dimension_2d, Less);
909 compare!(max_texture_dimension_3d, Less);
910 compare!(max_texture_array_layers, Less);
911 compare!(max_bind_groups, Less);
912 compare!(max_bindings_per_bind_group, Less);
913 compare!(max_dynamic_uniform_buffers_per_pipeline_layout, Less);
914 compare!(max_dynamic_storage_buffers_per_pipeline_layout, Less);
915 compare!(max_sampled_textures_per_shader_stage, Less);
916 compare!(max_samplers_per_shader_stage, Less);
917 compare!(max_storage_buffers_per_shader_stage, Less);
918 compare!(max_storage_textures_per_shader_stage, Less);
919 compare!(max_uniform_buffers_per_shader_stage, Less);
920 compare!(max_binding_array_elements_per_shader_stage, Less);
921 compare!(max_uniform_buffer_binding_size, Less);
922 compare!(max_storage_buffer_binding_size, Less);
923 compare!(max_vertex_buffers, Less);
924 compare!(max_buffer_size, Less);
925 compare!(max_vertex_attributes, Less);
926 compare!(max_vertex_buffer_array_stride, Less);
927 compare!(min_uniform_buffer_offset_alignment, Greater);
928 compare!(min_storage_buffer_offset_alignment, Greater);
929 compare!(max_inter_stage_shader_components, Less);
930 compare!(max_color_attachments, Less);
931 compare!(max_color_attachment_bytes_per_sample, Less);
932 compare!(max_compute_workgroup_storage_size, Less);
933 compare!(max_compute_invocations_per_workgroup, Less);
934 compare!(max_compute_workgroup_size_x, Less);
935 compare!(max_compute_workgroup_size_y, Less);
936 compare!(max_compute_workgroup_size_z, Less);
937 compare!(max_compute_workgroups_per_dimension, Less);
938 if self.min_subgroup_size > 0 && self.max_subgroup_size > 0 {
939 compare!(min_subgroup_size, Greater);
940 compare!(max_subgroup_size, Less);
941 }
942 compare!(max_push_constant_size, Less);
943 compare!(max_non_sampler_bindings, Less);
944 }
945 }
946
947 /// Represents the sets of additional limits on an adapter,
948 /// which take place when running on downlevel backends.
949 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
950 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
951 pub struct DownlevelLimits {}
952
953 #[allow(clippy::derivable_impls)]
954 impl Default for DownlevelLimits {
955 fn default() -> Self {
956 DownlevelLimits {}
957 }
958 }
959
960 /// Lists various ways the underlying platform does not conform to the WebGPU standard.
961 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
962 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
963 pub struct DownlevelCapabilities {
964 /// Combined boolean flags.
965 pub flags: DownlevelFlags,
966 /// Additional limits
967 pub limits: DownlevelLimits,
968 /// Which collections of features shaders support. Defined in terms of D3D's shader models.
969 pub shader_model: ShaderModel,
970 }
971
972 impl Default for DownlevelCapabilities {
973 fn default() -> Self {
974 Self {
975 flags: DownlevelFlags::all(),
976 limits: DownlevelLimits::default(),
977 shader_model: ShaderModel::Sm5,
978 }
979 }
980 }
981
982 impl DownlevelCapabilities {
983 /// Returns true if the underlying platform offers complete support of the baseline WebGPU standard.
984 ///
985 /// If this returns false, some parts of the API will result in validation errors where they would not normally.
986 /// These parts can be determined by the values in this structure.
987 #[must_use]
988 pub fn is_webgpu_compliant(&self) -> bool {
989 self.flags.contains(DownlevelFlags::compliant())
990 && self.limits == DownlevelLimits::default()
991 && self.shader_model >= ShaderModel::Sm5
992 }
993 }
994
995 bitflags::bitflags! {
996 /// Binary flags listing features that may or may not be present on downlevel adapters.
997 ///
998 /// A downlevel adapter is a GPU adapter that WGPU supports, but with potentially limited
999 /// features, due to the lack of hardware feature support.
1000 ///
1001 /// Flags that are **not** present for a downlevel adapter or device usually indicates
1002 /// non-compliance with the WebGPU specification, but not always.
1003 ///
1004 /// You can check whether a set of flags is compliant through the
1005 /// [`DownlevelCapabilities::is_webgpu_compliant()`] function.
1006 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1007 #[cfg_attr(feature = "serde", serde(transparent))]
1008 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1009 pub struct DownlevelFlags: u32 {
1010 /// The device supports compiling and using compute shaders.
1011 ///
1012 /// WebGL2, and GLES3.0 devices do not support compute.
1013 const COMPUTE_SHADERS = 1 << 0;
1014 /// Supports binding storage buffers and textures to fragment shaders.
1015 const FRAGMENT_WRITABLE_STORAGE = 1 << 1;
1016 /// Supports indirect drawing and dispatching.
1017 ///
1018 /// [`Self::COMPUTE_SHADERS`] must be present for this flag.
1019 ///
1020 /// WebGL2, GLES 3.0, and Metal on Apple1/Apple2 GPUs do not support indirect.
1021 const INDIRECT_EXECUTION = 1 << 2;
1022 /// Supports non-zero `base_vertex` parameter to direct indexed draw calls.
1023 ///
1024 /// Indirect calls, if supported, always support non-zero `base_vertex`.
1025 ///
1026 /// Supported by:
1027 /// - Vulkan
1028 /// - DX12
1029 /// - Metal on Apple3+ or Mac1+
1030 /// - OpenGL 3.2+
1031 /// - OpenGL ES 3.2
1032 const BASE_VERTEX = 1 << 3;
1033 /// Supports reading from a depth/stencil texture while using it as a read-only
1034 /// depth/stencil attachment.
1035 ///
1036 /// The WebGL2 and GLES backends do not support RODS.
1037 const READ_ONLY_DEPTH_STENCIL = 1 << 4;
1038 /// Supports textures with mipmaps which have a non power of two size.
1039 const NON_POWER_OF_TWO_MIPMAPPED_TEXTURES = 1 << 5;
1040 /// Supports textures that are cube arrays.
1041 const CUBE_ARRAY_TEXTURES = 1 << 6;
1042 /// Supports comparison samplers.
1043 const COMPARISON_SAMPLERS = 1 << 7;
1044 /// Supports different blend operations per color attachment.
1045 const INDEPENDENT_BLEND = 1 << 8;
1046 /// Supports storage buffers in vertex shaders.
1047 const VERTEX_STORAGE = 1 << 9;
1048
1049 /// Supports samplers with anisotropic filtering. Note this isn't actually required by
1050 /// WebGPU, the implementation is allowed to completely ignore aniso clamp. This flag is
1051 /// here for native backends so they can communicate to the user of aniso is enabled.
1052 ///
1053 /// All backends and all devices support anisotropic filtering.
1054 const ANISOTROPIC_FILTERING = 1 << 10;
1055
1056 /// Supports storage buffers in fragment shaders.
1057 const FRAGMENT_STORAGE = 1 << 11;
1058
1059 /// Supports sample-rate shading.
1060 const MULTISAMPLED_SHADING = 1 << 12;
1061
1062 /// Supports copies between depth textures and buffers.
1063 ///
1064 /// GLES/WebGL don't support this.
1065 const DEPTH_TEXTURE_AND_BUFFER_COPIES = 1 << 13;
1066
1067 /// Supports all the texture usages described in WebGPU. If this isn't supported, you
1068 /// should call `get_texture_format_features` to get how you can use textures of a given format
1069 const WEBGPU_TEXTURE_FORMAT_SUPPORT = 1 << 14;
1070
1071 /// Supports buffer bindings with sizes that aren't a multiple of 16.
1072 ///
1073 /// WebGL doesn't support this.
1074 const BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED = 1 << 15;
1075
1076 /// Supports buffers to combine [`BufferUsages::INDEX`] with usages other than [`BufferUsages::COPY_DST`] and [`BufferUsages::COPY_SRC`].
1077 /// Furthermore, in absence of this feature it is not allowed to copy index buffers from/to buffers with a set of usage flags containing
1078 /// [`BufferUsages::VERTEX`]/[`BufferUsages::UNIFORM`]/[`BufferUsages::STORAGE`] or [`BufferUsages::INDIRECT`].
1079 ///
1080 /// WebGL doesn't support this.
1081 const UNRESTRICTED_INDEX_BUFFER = 1 << 16;
1082
1083 /// Supports full 32-bit range indices (2^32-1 as opposed to 2^24-1 without this flag)
1084 ///
1085 /// Corresponds to Vulkan's `VkPhysicalDeviceFeatures.fullDrawIndexUint32`
1086 const FULL_DRAW_INDEX_UINT32 = 1 << 17;
1087
1088 /// Supports depth bias clamping
1089 ///
1090 /// Corresponds to Vulkan's `VkPhysicalDeviceFeatures.depthBiasClamp`
1091 const DEPTH_BIAS_CLAMP = 1 << 18;
1092
1093 /// Supports specifying which view format values are allowed when create_view() is called on a texture.
1094 ///
1095 /// The WebGL and GLES backends doesn't support this.
1096 const VIEW_FORMATS = 1 << 19;
1097
1098 /// With this feature not present, there are the following restrictions on `Queue::copy_external_image_to_texture`:
1099 /// - The source must not be [`web_sys::OffscreenCanvas`]
1100 /// - [`CopyExternalImageSourceInfo::origin`] must be zero.
1101 /// - [`CopyExternalImageDestInfo::color_space`] must be srgb.
1102 /// - If the source is an [`web_sys::ImageBitmap`]:
1103 /// - [`CopyExternalImageSourceInfo::flip_y`] must be false.
1104 /// - [`CopyExternalImageDestInfo::premultiplied_alpha`] must be false.
1105 ///
1106 /// WebGL doesn't support this. WebGPU does.
1107 const UNRESTRICTED_EXTERNAL_TEXTURE_COPIES = 1 << 20;
1108
1109 /// Supports specifying which view formats are allowed when calling create_view on the texture returned by
1110 /// `Surface::get_current_texture`.
1111 ///
1112 /// The GLES/WebGL and Vulkan on Android doesn't support this.
1113 const SURFACE_VIEW_FORMATS = 1 << 21;
1114
1115 /// If this is true, calls to `CommandEncoder::resolve_query_set` will be performed on the queue timeline.
1116 ///
1117 /// If this is false, calls to `CommandEncoder::resolve_query_set` will be performed on the device (i.e. cpu) timeline
1118 /// and will block that timeline until the query has data. You may work around this limitation by waiting until the submit
1119 /// whose queries you are resolving is fully finished (through use of `queue.on_submitted_work_done`) and only
1120 /// then submitting the resolve_query_set command. The queries will be guaranteed finished, so will not block.
1121 ///
1122 /// Supported by:
1123 /// - Vulkan,
1124 /// - DX12
1125 /// - Metal
1126 /// - OpenGL 4.4+
1127 ///
1128 /// Not Supported by:
1129 /// - GL ES / WebGL
1130 const NONBLOCKING_QUERY_RESOLVE = 1 << 22;
1131 }
1132 }
1133
1134 impl DownlevelFlags {
1135 /// All flags that indicate if the backend is WebGPU compliant
1136 #[must_use]
1137 pub const fn compliant() -> Self {
1138 // We use manual bit twiddling to make this a const fn as `Sub` and `.remove` aren't const
1139
1140 // WebGPU doesn't actually require aniso
1141 Self::from_bits_truncate(Self::all().bits() & !Self::ANISOTROPIC_FILTERING.bits())
1142 }
1143 }
1144
1145 /// Collections of shader features a device supports if they support less than WebGPU normally allows.
1146 // TODO: Fill out the differences between shader models more completely
1147 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1148 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1149 pub enum ShaderModel {
1150 /// Extremely limited shaders, including a total instruction limit.
1151 Sm2,
1152 /// Missing minor features and storage images.
1153 Sm4,
1154 /// WebGPU supports shader module 5.
1155 Sm5,
1156 }
1157
1158 /// Supported physical device types.
1159 #[repr(u8)]
1160 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
1161 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1162 pub enum DeviceType {
1163 /// Other or Unknown.
1164 Other,
1165 /// Integrated GPU with shared CPU/GPU memory.
1166 IntegratedGpu,
1167 /// Discrete GPU with separate CPU/GPU memory.
1168 DiscreteGpu,
1169 /// Virtual / Hosted.
1170 VirtualGpu,
1171 /// Cpu / Software Rendering.
1172 Cpu,
1173 }
1174
1175 //TODO: convert `vendor` and `device` to `u32`
1176
1177 /// Information about an adapter.
1178 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
1179 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1180 pub struct AdapterInfo {
1181 /// Adapter name
1182 pub name: String,
1183 /// [`Backend`]-specific vendor ID of the adapter
1184 ///
1185 /// This generally is a 16-bit PCI vendor ID in the least significant bytes of this field.
1186 /// However, more significant bytes may be non-zero if the backend uses a different
1187 /// representation.
1188 ///
1189 /// * For [`Backend::Vulkan`], the [`VkPhysicalDeviceProperties::vendorID`] is used, which is
1190 /// a superset of PCI IDs.
1191 ///
1192 /// [`VkPhysicalDeviceProperties::vendorID`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceProperties.html
1193 pub vendor: u32,
1194 /// [`Backend`]-specific device ID of the adapter
1195 ///
1196 ///
1197 /// This generally is a 16-bit PCI device ID in the least significant bytes of this field.
1198 /// However, more significant bytes may be non-zero if the backend uses a different
1199 /// representation.
1200 ///
1201 /// * For [`Backend::Vulkan`], the [`VkPhysicalDeviceProperties::deviceID`] is used, which is
1202 /// a superset of PCI IDs.
1203 ///
1204 /// [`VkPhysicalDeviceProperties::deviceID`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceProperties.html
1205 pub device: u32,
1206 /// Type of device
1207 pub device_type: DeviceType,
1208 /// Driver name
1209 pub driver: String,
1210 /// Driver info
1211 pub driver_info: String,
1212 /// Backend used for device
1213 pub backend: Backend,
1214 }
1215
1216 /// Hints to the device about the memory allocation strategy.
1217 ///
1218 /// Some backends may ignore these hints.
1219 #[derive(Clone, Debug, Default)]
1220 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1221 pub enum MemoryHints {
1222 /// Favor performance over memory usage (the default value).
1223 #[default]
1224 Performance,
1225 /// Favor memory usage over performance.
1226 MemoryUsage,
1227 /// Applications that have control over the content that is rendered
1228 /// (typically games) may find an optimal compromise between memory
1229 /// usage and performance by specifying the allocation configuration.
1230 Manual {
1231 /// Defines the range of allowed memory block sizes for sub-allocated
1232 /// resources.
1233 ///
1234 /// The backend may attempt to group multiple resources into fewer
1235 /// device memory blocks (sub-allocation) for performance reasons.
1236 /// The start of the provided range specifies the initial memory
1237 /// block size for sub-allocated resources. After running out of
1238 /// space in existing memory blocks, the backend may chose to
1239 /// progressively increase the block size of subsequent allocations
1240 /// up to a limit specified by the end of the range.
1241 ///
1242 /// This does not limit resource sizes. If a resource does not fit
1243 /// in the specified range, it will typically be placed in a dedicated
1244 /// memory block.
1245 suballocated_device_memory_block_size: Range<u64>,
1246 },
1247 }
1248
1249 /// Describes a [`Device`](../wgpu/struct.Device.html).
1250 ///
1251 /// Corresponds to [WebGPU `GPUDeviceDescriptor`](
1252 /// https://gpuweb.github.io/gpuweb/#gpudevicedescriptor).
1253 #[derive(Clone, Debug, Default)]
1254 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1255 pub struct DeviceDescriptor<L> {
1256 /// Debug label for the device.
1257 pub label: L,
1258 /// Specifies the features that are required by the device request.
1259 /// The request will fail if the adapter cannot provide these features.
1260 ///
1261 /// Exactly the specified set of features, and no more or less,
1262 /// will be allowed in validation of API calls on the resulting device.
1263 pub required_features: Features,
1264 /// Specifies the limits that are required by the device request.
1265 /// The request will fail if the adapter cannot provide these limits.
1266 ///
1267 /// Exactly the specified limits, and no better or worse,
1268 /// will be allowed in validation of API calls on the resulting device.
1269 pub required_limits: Limits,
1270 /// Hints for memory allocation strategies.
1271 pub memory_hints: MemoryHints,
1272 /// Whether API tracing for debugging is enabled,
1273 /// and where the trace is written if so.
1274 pub trace: Trace,
1275 }
1276
1277 impl<L> DeviceDescriptor<L> {
1278 /// Takes a closure and maps the label of the device descriptor into another.
1279 #[must_use]
1280 pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> DeviceDescriptor<K> {
1281 DeviceDescriptor {
1282 label: fun(&self.label),
1283 required_features: self.required_features,
1284 required_limits: self.required_limits.clone(),
1285 memory_hints: self.memory_hints.clone(),
1286 trace: self.trace.clone(),
1287 }
1288 }
1289 }
1290
1291 /// Controls API call tracing and specifies where the trace is written.
1292 ///
1293 /// **Note:** Tracing is currently unavailable.
1294 /// See [issue 5974](https://github.com/gfx-rs/wgpu/issues/5974) for updates.
1295 #[derive(Clone, Debug, Default)]
1296 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1297 // This enum must be non-exhaustive so that enabling the "trace" feature is not a semver break.
1298 #[non_exhaustive]
1299 pub enum Trace {
1300 /// Tracing disabled.
1301 #[default]
1302 Off,
1303
1304 /// Tracing enabled.
1305 #[cfg(feature = "trace")]
1306 // This must be owned rather than `&'a Path`, because if it were that, then the lifetime
1307 // parameter would be unused when the "trace" feature is disabled, which is prohibited.
1308 Directory(std::path::PathBuf),
1309 }
1310
1311 bitflags::bitflags! {
1312 /// Describes the shader stages that a binding will be visible from.
1313 ///
1314 /// These can be combined so something that is visible from both vertex and fragment shaders can be defined as:
1315 ///
1316 /// `ShaderStages::VERTEX | ShaderStages::FRAGMENT`
1317 ///
1318 /// Corresponds to [WebGPU `GPUShaderStageFlags`](
1319 /// https://gpuweb.github.io/gpuweb/#typedefdef-gpushaderstageflags).
1320 #[repr(transparent)]
1321 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1322 #[cfg_attr(feature = "serde", serde(transparent))]
1323 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1324 pub struct ShaderStages: u32 {
1325 /// Binding is not visible from any shader stage.
1326 const NONE = 0;
1327 /// Binding is visible from the vertex shader of a render pipeline.
1328 const VERTEX = 1 << 0;
1329 /// Binding is visible from the fragment shader of a render pipeline.
1330 const FRAGMENT = 1 << 1;
1331 /// Binding is visible from the compute shader of a compute pipeline.
1332 const COMPUTE = 1 << 2;
1333 /// Binding is visible from the vertex and fragment shaders of a render pipeline.
1334 const VERTEX_FRAGMENT = Self::VERTEX.bits() | Self::FRAGMENT.bits();
1335 /// Binding is visible from the task shader of a mesh pipeline
1336 const TASK = 1 << 3;
1337 /// Binding is visible from the mesh shader of a mesh pipeline
1338 const MESH = 1 << 4;
1339 }
1340 }
1341
1342 /// Order in which texture data is laid out in memory.
1343 #[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
1344 pub enum TextureDataOrder {
1345 /// The texture is laid out densely in memory as:
1346 ///
1347 /// ```text
1348 /// Layer0Mip0 Layer0Mip1 Layer0Mip2
1349 /// Layer1Mip0 Layer1Mip1 Layer1Mip2
1350 /// Layer2Mip0 Layer2Mip1 Layer2Mip2
1351 /// ````
1352 ///
1353 /// This is the layout used by dds files.
1354 #[default]
1355 LayerMajor,
1356 /// The texture is laid out densely in memory as:
1357 ///
1358 /// ```text
1359 /// Layer0Mip0 Layer1Mip0 Layer2Mip0
1360 /// Layer0Mip1 Layer1Mip1 Layer2Mip1
1361 /// Layer0Mip2 Layer1Mip2 Layer2Mip2
1362 /// ```
1363 ///
1364 /// This is the layout used by ktx and ktx2 files.
1365 MipMajor,
1366 }
1367
1368 /// Dimensions of a particular texture view.
1369 ///
1370 /// Corresponds to [WebGPU `GPUTextureViewDimension`](
1371 /// https://gpuweb.github.io/gpuweb/#enumdef-gputextureviewdimension).
1372 #[repr(C)]
1373 #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
1374 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1375 pub enum TextureViewDimension {
1376 /// A one dimensional texture. `texture_1d` in WGSL and `texture1D` in GLSL.
1377 #[cfg_attr(feature = "serde", serde(rename = "1d"))]
1378 D1,
1379 /// A two dimensional texture. `texture_2d` in WGSL and `texture2D` in GLSL.
1380 #[cfg_attr(feature = "serde", serde(rename = "2d"))]
1381 #[default]
1382 D2,
1383 /// A two dimensional array texture. `texture_2d_array` in WGSL and `texture2DArray` in GLSL.
1384 #[cfg_attr(feature = "serde", serde(rename = "2d-array"))]
1385 D2Array,
1386 /// A cubemap texture. `texture_cube` in WGSL and `textureCube` in GLSL.
1387 #[cfg_attr(feature = "serde", serde(rename = "cube"))]
1388 Cube,
1389 /// A cubemap array texture. `texture_cube_array` in WGSL and `textureCubeArray` in GLSL.
1390 #[cfg_attr(feature = "serde", serde(rename = "cube-array"))]
1391 CubeArray,
1392 /// A three dimensional texture. `texture_3d` in WGSL and `texture3D` in GLSL.
1393 #[cfg_attr(feature = "serde", serde(rename = "3d"))]
1394 D3,
1395 }
1396
1397 impl TextureViewDimension {
1398 /// Get the texture dimension required of this texture view dimension.
1399 #[must_use]
1400 pub fn compatible_texture_dimension(self) -> TextureDimension {
1401 match self {
1402 Self::D1 => TextureDimension::D1,
1403 Self::D2 | Self::D2Array | Self::Cube | Self::CubeArray => TextureDimension::D2,
1404 Self::D3 => TextureDimension::D3,
1405 }
1406 }
1407 }
1408
1409 /// Alpha blend factor.
1410 ///
1411 /// Corresponds to [WebGPU `GPUBlendFactor`](
1412 /// https://gpuweb.github.io/gpuweb/#enumdef-gpublendfactor). Values using `Src1`
1413 /// require [`Features::DUAL_SOURCE_BLENDING`] and can only be used with the first
1414 /// render target.
1415 ///
1416 /// For further details on how the blend factors are applied, see the analogous
1417 /// functionality in OpenGL: <https://www.khronos.org/opengl/wiki/Blending#Blending_Parameters>.
1418 #[repr(C)]
1419 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
1420 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1421 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
1422 pub enum BlendFactor {
1423 /// 0.0
1424 Zero = 0,
1425 /// 1.0
1426 One = 1,
1427 /// S.component
1428 Src = 2,
1429 /// 1.0 - S.component
1430 OneMinusSrc = 3,
1431 /// S.alpha
1432 SrcAlpha = 4,
1433 /// 1.0 - S.alpha
1434 OneMinusSrcAlpha = 5,
1435 /// D.component
1436 Dst = 6,
1437 /// 1.0 - D.component
1438 OneMinusDst = 7,
1439 /// D.alpha
1440 DstAlpha = 8,
1441 /// 1.0 - D.alpha
1442 OneMinusDstAlpha = 9,
1443 /// min(S.alpha, 1.0 - D.alpha)
1444 SrcAlphaSaturated = 10,
1445 /// Constant
1446 Constant = 11,
1447 /// 1.0 - Constant
1448 OneMinusConstant = 12,
1449 /// S1.component
1450 Src1 = 13,
1451 /// 1.0 - S1.component
1452 OneMinusSrc1 = 14,
1453 /// S1.alpha
1454 Src1Alpha = 15,
1455 /// 1.0 - S1.alpha
1456 OneMinusSrc1Alpha = 16,
1457 }
1458
1459 impl BlendFactor {
1460 /// Returns `true` if the blend factor references the second blend source.
1461 ///
1462 /// Note that the usage of those blend factors require [`Features::DUAL_SOURCE_BLENDING`].
1463 #[must_use]
1464 pub fn ref_second_blend_source(&self) -> bool {
1465 match self {
1466 BlendFactor::Src1
1467 | BlendFactor::OneMinusSrc1
1468 | BlendFactor::Src1Alpha
1469 | BlendFactor::OneMinusSrc1Alpha => true,
1470 _ => false,
1471 }
1472 }
1473 }
1474
1475 /// Alpha blend operation.
1476 ///
1477 /// Corresponds to [WebGPU `GPUBlendOperation`](
1478 /// https://gpuweb.github.io/gpuweb/#enumdef-gpublendoperation).
1479 ///
1480 /// For further details on how the blend operations are applied, see
1481 /// the analogous functionality in OpenGL: <https://www.khronos.org/opengl/wiki/Blending#Blend_Equations>.
1482 #[repr(C)]
1483 #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
1484 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1485 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
1486 pub enum BlendOperation {
1487 /// Src + Dst
1488 #[default]
1489 Add = 0,
1490 /// Src - Dst
1491 Subtract = 1,
1492 /// Dst - Src
1493 ReverseSubtract = 2,
1494 /// min(Src, Dst)
1495 Min = 3,
1496 /// max(Src, Dst)
1497 Max = 4,
1498 }
1499
1500 /// Describes a blend component of a [`BlendState`].
1501 ///
1502 /// Corresponds to [WebGPU `GPUBlendComponent`](
1503 /// https://gpuweb.github.io/gpuweb/#dictdef-gpublendcomponent).
1504 #[repr(C)]
1505 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1506 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1507 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1508 pub struct BlendComponent {
1509 /// Multiplier for the source, which is produced by the fragment shader.
1510 pub src_factor: BlendFactor,
1511 /// Multiplier for the destination, which is stored in the target.
1512 pub dst_factor: BlendFactor,
1513 /// The binary operation applied to the source and destination,
1514 /// multiplied by their respective factors.
1515 pub operation: BlendOperation,
1516 }
1517
1518 impl BlendComponent {
1519 /// Default blending state that replaces destination with the source.
1520 pub const REPLACE: Self = Self {
1521 src_factor: BlendFactor::One,
1522 dst_factor: BlendFactor::Zero,
1523 operation: BlendOperation::Add,
1524 };
1525
1526 /// Blend state of `(1 * src) + ((1 - src_alpha) * dst)`.
1527 pub const OVER: Self = Self {
1528 src_factor: BlendFactor::One,
1529 dst_factor: BlendFactor::OneMinusSrcAlpha,
1530 operation: BlendOperation::Add,
1531 };
1532
1533 /// Returns true if the state relies on the constant color, which is
1534 /// set independently on a render command encoder.
1535 #[must_use]
1536 pub fn uses_constant(&self) -> bool {
1537 match (self.src_factor, self.dst_factor) {
1538 (BlendFactor::Constant, _)
1539 | (BlendFactor::OneMinusConstant, _)
1540 | (_, BlendFactor::Constant)
1541 | (_, BlendFactor::OneMinusConstant) => true,
1542 (_, _) => false,
1543 }
1544 }
1545 }
1546
1547 impl Default for BlendComponent {
1548 fn default() -> Self {
1549 Self::REPLACE
1550 }
1551 }
1552
1553 /// Describe the blend state of a render pipeline,
1554 /// within [`ColorTargetState`].
1555 ///
1556 /// Corresponds to [WebGPU `GPUBlendState`](
1557 /// https://gpuweb.github.io/gpuweb/#dictdef-gpublendstate).
1558 #[repr(C)]
1559 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1560 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1561 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1562 pub struct BlendState {
1563 /// Color equation.
1564 pub color: BlendComponent,
1565 /// Alpha equation.
1566 pub alpha: BlendComponent,
1567 }
1568
1569 impl BlendState {
1570 /// Blend mode that does no color blending, just overwrites the output with the contents of the shader.
1571 pub const REPLACE: Self = Self {
1572 color: BlendComponent::REPLACE,
1573 alpha: BlendComponent::REPLACE,
1574 };
1575
1576 /// Blend mode that does standard alpha blending with non-premultiplied alpha.
1577 pub const ALPHA_BLENDING: Self = Self {
1578 color: BlendComponent {
1579 src_factor: BlendFactor::SrcAlpha,
1580 dst_factor: BlendFactor::OneMinusSrcAlpha,
1581 operation: BlendOperation::Add,
1582 },
1583 alpha: BlendComponent::OVER,
1584 };
1585
1586 /// Blend mode that does standard alpha blending with premultiplied alpha.
1587 pub const PREMULTIPLIED_ALPHA_BLENDING: Self = Self {
1588 color: BlendComponent::OVER,
1589 alpha: BlendComponent::OVER,
1590 };
1591 }
1592
1593 /// Describes the color state of a render pipeline.
1594 ///
1595 /// Corresponds to [WebGPU `GPUColorTargetState`](
1596 /// https://gpuweb.github.io/gpuweb/#dictdef-gpucolortargetstate).
1597 #[repr(C)]
1598 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
1599 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1600 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1601 pub struct ColorTargetState {
1602 /// The [`TextureFormat`] of the image that this pipeline will render to. Must match the format
1603 /// of the corresponding color attachment in [`CommandEncoder::begin_render_pass`][CEbrp]
1604 ///
1605 /// [CEbrp]: ../wgpu/struct.CommandEncoder.html#method.begin_render_pass
1606 pub format: TextureFormat,
1607 /// The blending that is used for this pipeline.
1608 #[cfg_attr(feature = "serde", serde(default))]
1609 pub blend: Option<BlendState>,
1610 /// Mask which enables/disables writes to different color/alpha channel.
1611 #[cfg_attr(feature = "serde", serde(default))]
1612 pub write_mask: ColorWrites,
1613 }
1614
1615 impl From<TextureFormat> for ColorTargetState {
1616 fn from(format: TextureFormat) -> Self {
1617 Self {
1618 format,
1619 blend: None,
1620 write_mask: ColorWrites::ALL,
1621 }
1622 }
1623 }
1624
1625 /// Primitive type the input mesh is composed of.
1626 ///
1627 /// Corresponds to [WebGPU `GPUPrimitiveTopology`](
1628 /// https://gpuweb.github.io/gpuweb/#enumdef-gpuprimitivetopology).
1629 #[repr(C)]
1630 #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
1631 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1632 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
1633 pub enum PrimitiveTopology {
1634 /// Vertex data is a list of points. Each vertex is a new point.
1635 PointList = 0,
1636 /// Vertex data is a list of lines. Each pair of vertices composes a new line.
1637 ///
1638 /// Vertices `0 1 2 3` create two lines `0 1` and `2 3`
1639 LineList = 1,
1640 /// Vertex data is a strip of lines. Each set of two adjacent vertices form a line.
1641 ///
1642 /// Vertices `0 1 2 3` create three lines `0 1`, `1 2`, and `2 3`.
1643 LineStrip = 2,
1644 /// Vertex data is a list of triangles. Each set of 3 vertices composes a new triangle.
1645 ///
1646 /// Vertices `0 1 2 3 4 5` create two triangles `0 1 2` and `3 4 5`
1647 #[default]
1648 TriangleList = 3,
1649 /// Vertex data is a triangle strip. Each set of three adjacent vertices form a triangle.
1650 ///
1651 /// Vertices `0 1 2 3 4 5` create four triangles `0 1 2`, `2 1 3`, `2 3 4`, and `4 3 5`
1652 TriangleStrip = 4,
1653 }
1654
1655 impl PrimitiveTopology {
1656 /// Returns true for strip topologies.
1657 #[must_use]
1658 pub fn is_strip(&self) -> bool {
1659 match *self {
1660 Self::PointList | Self::LineList | Self::TriangleList => false,
1661 Self::LineStrip | Self::TriangleStrip => true,
1662 }
1663 }
1664 }
1665
1666 /// Vertex winding order which classifies the "front" face of a triangle.
1667 ///
1668 /// Corresponds to [WebGPU `GPUFrontFace`](
1669 /// https://gpuweb.github.io/gpuweb/#enumdef-gpufrontface).
1670 #[repr(C)]
1671 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
1672 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1673 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
1674 pub enum FrontFace {
1675 /// Triangles with vertices in counter clockwise order are considered the front face.
1676 ///
1677 /// This is the default with right handed coordinate spaces.
1678 #[default]
1679 Ccw = 0,
1680 /// Triangles with vertices in clockwise order are considered the front face.
1681 ///
1682 /// This is the default with left handed coordinate spaces.
1683 Cw = 1,
1684 }
1685
1686 /// Face of a vertex.
1687 ///
1688 /// Corresponds to [WebGPU `GPUCullMode`](
1689 /// https://gpuweb.github.io/gpuweb/#enumdef-gpucullmode),
1690 /// except that the `"none"` value is represented using `Option<Face>` instead.
1691 #[repr(C)]
1692 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1693 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1694 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
1695 pub enum Face {
1696 /// Front face
1697 Front = 0,
1698 /// Back face
1699 Back = 1,
1700 }
1701
1702 /// Type of drawing mode for polygons
1703 #[repr(C)]
1704 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
1705 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1706 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
1707 pub enum PolygonMode {
1708 /// Polygons are filled
1709 #[default]
1710 Fill = 0,
1711 /// Polygons are drawn as line segments
1712 Line = 1,
1713 /// Polygons are drawn as points
1714 Point = 2,
1715 }
1716
1717 /// Describes the state of primitive assembly and rasterization in a render pipeline.
1718 ///
1719 /// Corresponds to [WebGPU `GPUPrimitiveState`](
1720 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuprimitivestate).
1721 #[repr(C)]
1722 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1723 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1724 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1725 pub struct PrimitiveState {
1726 /// The primitive topology used to interpret vertices.
1727 pub topology: PrimitiveTopology,
1728 /// When drawing strip topologies with indices, this is the required format for the index buffer.
1729 /// This has no effect on non-indexed or non-strip draws.
1730 ///
1731 /// Specifying this value enables primitive restart, allowing individual strips to be separated
1732 /// with the index value `0xFFFF` when using `Uint16`, or `0xFFFFFFFF` when using `Uint32`.
1733 #[cfg_attr(feature = "serde", serde(default))]
1734 pub strip_index_format: Option<IndexFormat>,
1735 /// The face to consider the front for the purpose of culling and stencil operations.
1736 #[cfg_attr(feature = "serde", serde(default))]
1737 pub front_face: FrontFace,
1738 /// The face culling mode.
1739 #[cfg_attr(feature = "serde", serde(default))]
1740 pub cull_mode: Option<Face>,
1741 /// If set to true, the polygon depth is not clipped to 0-1 before rasterization.
1742 ///
1743 /// Enabling this requires [`Features::DEPTH_CLIP_CONTROL`] to be enabled.
1744 #[cfg_attr(feature = "serde", serde(default))]
1745 pub unclipped_depth: bool,
1746 /// Controls the way each polygon is rasterized. Can be either `Fill` (default), `Line` or `Point`
1747 ///
1748 /// Setting this to `Line` requires [`Features::POLYGON_MODE_LINE`] to be enabled.
1749 ///
1750 /// Setting this to `Point` requires [`Features::POLYGON_MODE_POINT`] to be enabled.
1751 #[cfg_attr(feature = "serde", serde(default))]
1752 pub polygon_mode: PolygonMode,
1753 /// If set to true, the primitives are rendered with conservative overestimation. I.e. any rastered pixel touched by it is filled.
1754 /// Only valid for `[PolygonMode::Fill`]!
1755 ///
1756 /// Enabling this requires [`Features::CONSERVATIVE_RASTERIZATION`] to be enabled.
1757 pub conservative: bool,
1758 }
1759
1760 /// Describes the multi-sampling state of a render pipeline.
1761 ///
1762 /// Corresponds to [WebGPU `GPUMultisampleState`](
1763 /// https://gpuweb.github.io/gpuweb/#dictdef-gpumultisamplestate).
1764 #[repr(C)]
1765 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1766 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1767 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1768 pub struct MultisampleState {
1769 /// The number of samples calculated per pixel (for MSAA). For non-multisampled textures,
1770 /// this should be `1`
1771 pub count: u32,
1772 /// Bitmask that restricts the samples of a pixel modified by this pipeline. All samples
1773 /// can be enabled using the value `!0`
1774 pub mask: u64,
1775 /// When enabled, produces another sample mask per pixel based on the alpha output value, that
1776 /// is ANDed with the sample mask and the primitive coverage to restrict the set of samples
1777 /// affected by a primitive.
1778 ///
1779 /// The implicit mask produced for alpha of zero is guaranteed to be zero, and for alpha of one
1780 /// is guaranteed to be all 1-s.
1781 pub alpha_to_coverage_enabled: bool,
1782 }
1783
1784 impl Default for MultisampleState {
1785 fn default() -> Self {
1786 MultisampleState {
1787 count: 1,
1788 mask: !0,
1789 alpha_to_coverage_enabled: false,
1790 }
1791 }
1792 }
1793
1794 bitflags::bitflags! {
1795 /// Feature flags for a texture format.
1796 #[repr(transparent)]
1797 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1798 #[cfg_attr(feature = "serde", serde(transparent))]
1799 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1800 pub struct TextureFormatFeatureFlags: u32 {
1801 /// If not present, the texture can't be sampled with a filtering sampler.
1802 /// This may overwrite TextureSampleType::Float.filterable
1803 const FILTERABLE = 1 << 0;
1804 /// Allows [`TextureDescriptor::sample_count`] to be `2`.
1805 const MULTISAMPLE_X2 = 1 << 1;
1806 /// Allows [`TextureDescriptor::sample_count`] to be `4`.
1807 const MULTISAMPLE_X4 = 1 << 2 ;
1808 /// Allows [`TextureDescriptor::sample_count`] to be `8`.
1809 const MULTISAMPLE_X8 = 1 << 3 ;
1810 /// Allows [`TextureDescriptor::sample_count`] to be `16`.
1811 const MULTISAMPLE_X16 = 1 << 4;
1812 /// Allows a texture of this format to back a view passed as `resolve_target`
1813 /// to a render pass for an automatic driver-implemented resolve.
1814 const MULTISAMPLE_RESOLVE = 1 << 5;
1815 /// When used as a STORAGE texture, then a texture with this format can be bound with
1816 /// [`StorageTextureAccess::ReadOnly`].
1817 const STORAGE_READ_ONLY = 1 << 6;
1818 /// When used as a STORAGE texture, then a texture with this format can be bound with
1819 /// [`StorageTextureAccess::WriteOnly`].
1820 const STORAGE_WRITE_ONLY = 1 << 7;
1821 /// When used as a STORAGE texture, then a texture with this format can be bound with
1822 /// [`StorageTextureAccess::ReadWrite`].
1823 const STORAGE_READ_WRITE = 1 << 8;
1824 /// When used as a STORAGE texture, then a texture with this format can be bound with
1825 /// [`StorageTextureAccess::Atomic`].
1826 const STORAGE_ATOMIC = 1 << 9;
1827 /// If not present, the texture can't be blended into the render target.
1828 const BLENDABLE = 1 << 10;
1829 }
1830 }
1831
1832 impl TextureFormatFeatureFlags {
1833 /// Sample count supported by a given texture format.
1834 ///
1835 /// returns `true` if `count` is a supported sample count.
1836 #[must_use]
1837 pub fn sample_count_supported(&self, count: u32) -> bool {
1838 use TextureFormatFeatureFlags as tfsc;
1839
1840 match count {
1841 1 => true,
1842 2 => self.contains(tfsc::MULTISAMPLE_X2),
1843 4 => self.contains(tfsc::MULTISAMPLE_X4),
1844 8 => self.contains(tfsc::MULTISAMPLE_X8),
1845 16 => self.contains(tfsc::MULTISAMPLE_X16),
1846 _ => false,
1847 }
1848 }
1849
1850 /// A `Vec` of supported sample counts.
1851 #[must_use]
1852 pub fn supported_sample_counts(&self) -> Vec<u32> {
1853 let all_possible_sample_counts: [u32; 5] = [1, 2, 4, 8, 16];
1854 all_possible_sample_counts
1855 .into_iter()
1856 .filter(|&sc| self.sample_count_supported(sc))
1857 .collect()
1858 }
1859 }
1860
1861 /// Features supported by a given texture format
1862 ///
1863 /// Features are defined by WebGPU specification unless [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] is enabled.
1864 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
1865 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1866 pub struct TextureFormatFeatures {
1867 /// Valid bits for `TextureDescriptor::Usage` provided for format creation.
1868 pub allowed_usages: TextureUsages,
1869 /// Additional property flags for the format.
1870 pub flags: TextureFormatFeatureFlags,
1871 }
1872
1873 /// ASTC block dimensions
1874 #[repr(C)]
1875 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
1876 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1877 pub enum AstcBlock {
1878 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px).
1879 B4x4,
1880 /// 5x4 block compressed texture. 16 bytes per block (6.4 bit/px).
1881 B5x4,
1882 /// 5x5 block compressed texture. 16 bytes per block (5.12 bit/px).
1883 B5x5,
1884 /// 6x5 block compressed texture. 16 bytes per block (4.27 bit/px).
1885 B6x5,
1886 /// 6x6 block compressed texture. 16 bytes per block (3.56 bit/px).
1887 B6x6,
1888 /// 8x5 block compressed texture. 16 bytes per block (3.2 bit/px).
1889 B8x5,
1890 /// 8x6 block compressed texture. 16 bytes per block (2.67 bit/px).
1891 B8x6,
1892 /// 8x8 block compressed texture. 16 bytes per block (2 bit/px).
1893 B8x8,
1894 /// 10x5 block compressed texture. 16 bytes per block (2.56 bit/px).
1895 B10x5,
1896 /// 10x6 block compressed texture. 16 bytes per block (2.13 bit/px).
1897 B10x6,
1898 /// 10x8 block compressed texture. 16 bytes per block (1.6 bit/px).
1899 B10x8,
1900 /// 10x10 block compressed texture. 16 bytes per block (1.28 bit/px).
1901 B10x10,
1902 /// 12x10 block compressed texture. 16 bytes per block (1.07 bit/px).
1903 B12x10,
1904 /// 12x12 block compressed texture. 16 bytes per block (0.89 bit/px).
1905 B12x12,
1906 }
1907
1908 /// ASTC RGBA channel
1909 #[repr(C)]
1910 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
1911 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1912 pub enum AstcChannel {
1913 /// 8 bit integer RGBA, [0, 255] converted to/from linear-color float [0, 1] in shader.
1914 ///
1915 /// [`Features::TEXTURE_COMPRESSION_ASTC`] must be enabled to use this channel.
1916 Unorm,
1917 /// 8 bit integer RGBA, Srgb-color [0, 255] converted to/from linear-color float [0, 1] in shader.
1918 ///
1919 /// [`Features::TEXTURE_COMPRESSION_ASTC`] must be enabled to use this channel.
1920 UnormSrgb,
1921 /// floating-point RGBA, linear-color float can be outside of the [0, 1] range.
1922 ///
1923 /// [`Features::TEXTURE_COMPRESSION_ASTC_HDR`] must be enabled to use this channel.
1924 Hdr,
1925 }
1926
1927 /// Format in which a texture’s texels are stored in GPU memory.
1928 ///
1929 /// Certain formats additionally specify a conversion.
1930 /// When these formats are used in a shader, the conversion automatically takes place when loading
1931 /// from or storing to the texture.
1932 ///
1933 /// * `Unorm` formats linearly scale the integer range of the storage format to a floating-point
1934 /// range of 0 to 1, inclusive.
1935 /// * `Snorm` formats linearly scale the integer range of the storage format to a floating-point
1936 /// range of &minus;1 to 1, inclusive, except that the most negative value
1937 /// (&minus;128 for 8-bit, &minus;32768 for 16-bit) is excluded; on conversion,
1938 /// it is treated as identical to the second most negative
1939 /// (&minus;127 for 8-bit, &minus;32767 for 16-bit),
1940 /// so that the positive and negative ranges are symmetric.
1941 /// * `UnormSrgb` formats apply the [sRGB transfer function] so that the storage is sRGB encoded
1942 /// while the shader works with linear intensity values.
1943 /// * `Uint`, `Sint`, and `Float` formats perform no conversion.
1944 ///
1945 /// Corresponds to [WebGPU `GPUTextureFormat`](
1946 /// https://gpuweb.github.io/gpuweb/#enumdef-gputextureformat).
1947 ///
1948 /// [sRGB transfer function]: https://en.wikipedia.org/wiki/SRGB#Transfer_function_(%22gamma%22)
1949 #[repr(C)]
1950 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
1951 pub enum TextureFormat {
1952 // Normal 8 bit formats
1953 /// Red channel only. 8 bit integer per channel. [0, 255] converted to/from float [0, 1] in shader.
1954 R8Unorm,
1955 /// Red channel only. 8 bit integer per channel. [&minus;127, 127] converted to/from float [&minus;1, 1] in shader.
1956 R8Snorm,
1957 /// Red channel only. 8 bit integer per channel. Unsigned in shader.
1958 R8Uint,
1959 /// Red channel only. 8 bit integer per channel. Signed in shader.
1960 R8Sint,
1961
1962 // Normal 16 bit formats
1963 /// Red channel only. 16 bit integer per channel. Unsigned in shader.
1964 R16Uint,
1965 /// Red channel only. 16 bit integer per channel. Signed in shader.
1966 R16Sint,
1967 /// Red channel only. 16 bit integer per channel. [0, 65535] converted to/from float [0, 1] in shader.
1968 ///
1969 /// [`Features::TEXTURE_FORMAT_16BIT_NORM`] must be enabled to use this texture format.
1970 R16Unorm,
1971 /// Red channel only. 16 bit integer per channel. [&minus;32767, 32767] converted to/from float [&minus;1, 1] in shader.
1972 ///
1973 /// [`Features::TEXTURE_FORMAT_16BIT_NORM`] must be enabled to use this texture format.
1974 R16Snorm,
1975 /// Red channel only. 16 bit float per channel. Float in shader.
1976 R16Float,
1977 /// Red and green channels. 8 bit integer per channel. [0, 255] converted to/from float [0, 1] in shader.
1978 Rg8Unorm,
1979 /// Red and green channels. 8 bit integer per channel. [&minus;127, 127] converted to/from float [&minus;1, 1] in shader.
1980 Rg8Snorm,
1981 /// Red and green channels. 8 bit integer per channel. Unsigned in shader.
1982 Rg8Uint,
1983 /// Red and green channels. 8 bit integer per channel. Signed in shader.
1984 Rg8Sint,
1985
1986 // Normal 32 bit formats
1987 /// Red channel only. 32 bit integer per channel. Unsigned in shader.
1988 R32Uint,
1989 /// Red channel only. 32 bit integer per channel. Signed in shader.
1990 R32Sint,
1991 /// Red channel only. 32 bit float per channel. Float in shader.
1992 R32Float,
1993 /// Red and green channels. 16 bit integer per channel. Unsigned in shader.
1994 Rg16Uint,
1995 /// Red and green channels. 16 bit integer per channel. Signed in shader.
1996 Rg16Sint,
1997 /// Red and green channels. 16 bit integer per channel. [0, 65535] converted to/from float [0, 1] in shader.
1998 ///
1999 /// [`Features::TEXTURE_FORMAT_16BIT_NORM`] must be enabled to use this texture format.
2000 Rg16Unorm,
2001 /// Red and green channels. 16 bit integer per channel. [&minus;32767, 32767] converted to/from float [&minus;1, 1] in shader.
2002 ///
2003 /// [`Features::TEXTURE_FORMAT_16BIT_NORM`] must be enabled to use this texture format.
2004 Rg16Snorm,
2005 /// Red and green channels. 16 bit float per channel. Float in shader.
2006 Rg16Float,
2007 /// Red, green, blue, and alpha channels. 8 bit integer per channel. [0, 255] converted to/from float [0, 1] in shader.
2008 Rgba8Unorm,
2009 /// Red, green, blue, and alpha channels. 8 bit integer per channel. Srgb-color [0, 255] converted to/from linear-color float [0, 1] in shader.
2010 Rgba8UnormSrgb,
2011 /// Red, green, blue, and alpha channels. 8 bit integer per channel. [&minus;127, 127] converted to/from float [&minus;1, 1] in shader.
2012 Rgba8Snorm,
2013 /// Red, green, blue, and alpha channels. 8 bit integer per channel. Unsigned in shader.
2014 Rgba8Uint,
2015 /// Red, green, blue, and alpha channels. 8 bit integer per channel. Signed in shader.
2016 Rgba8Sint,
2017 /// Blue, green, red, and alpha channels. 8 bit integer per channel. [0, 255] converted to/from float [0, 1] in shader.
2018 Bgra8Unorm,
2019 /// Blue, green, red, and alpha channels. 8 bit integer per channel. Srgb-color [0, 255] converted to/from linear-color float [0, 1] in shader.
2020 Bgra8UnormSrgb,
2021
2022 // Packed 32 bit formats
2023 /// Packed unsigned float with 9 bits mantisa for each RGB component, then a common 5 bits exponent
2024 Rgb9e5Ufloat,
2025 /// Red, green, blue, and alpha channels. 10 bit integer for RGB channels, 2 bit integer for alpha channel. Unsigned in shader.
2026 Rgb10a2Uint,
2027 /// Red, green, blue, and alpha channels. 10 bit integer for RGB channels, 2 bit integer for alpha channel. [0, 1023] ([0, 3] for alpha) converted to/from float [0, 1] in shader.
2028 Rgb10a2Unorm,
2029 /// Red, green, and blue channels. 11 bit float with no sign bit for RG channels. 10 bit float with no sign bit for blue channel. Float in shader.
2030 Rg11b10Ufloat,
2031
2032 // Normal 64 bit formats
2033 /// Red channel only. 64 bit integer per channel. Unsigned in shader.
2034 ///
2035 /// [`Features::TEXTURE_INT64_ATOMIC`] must be enabled to use this texture format.
2036 R64Uint,
2037 /// Red and green channels. 32 bit integer per channel. Unsigned in shader.
2038 Rg32Uint,
2039 /// Red and green channels. 32 bit integer per channel. Signed in shader.
2040 Rg32Sint,
2041 /// Red and green channels. 32 bit float per channel. Float in shader.
2042 Rg32Float,
2043 /// Red, green, blue, and alpha channels. 16 bit integer per channel. Unsigned in shader.
2044 Rgba16Uint,
2045 /// Red, green, blue, and alpha channels. 16 bit integer per channel. Signed in shader.
2046 Rgba16Sint,
2047 /// Red, green, blue, and alpha channels. 16 bit integer per channel. [0, 65535] converted to/from float [0, 1] in shader.
2048 ///
2049 /// [`Features::TEXTURE_FORMAT_16BIT_NORM`] must be enabled to use this texture format.
2050 Rgba16Unorm,
2051 /// Red, green, blue, and alpha. 16 bit integer per channel. [&minus;32767, 32767] converted to/from float [&minus;1, 1] in shader.
2052 ///
2053 /// [`Features::TEXTURE_FORMAT_16BIT_NORM`] must be enabled to use this texture format.
2054 Rgba16Snorm,
2055 /// Red, green, blue, and alpha channels. 16 bit float per channel. Float in shader.
2056 Rgba16Float,
2057
2058 // Normal 128 bit formats
2059 /// Red, green, blue, and alpha channels. 32 bit integer per channel. Unsigned in shader.
2060 Rgba32Uint,
2061 /// Red, green, blue, and alpha channels. 32 bit integer per channel. Signed in shader.
2062 Rgba32Sint,
2063 /// Red, green, blue, and alpha channels. 32 bit float per channel. Float in shader.
2064 Rgba32Float,
2065
2066 // Depth and stencil formats
2067 /// Stencil format with 8 bit integer stencil.
2068 Stencil8,
2069 /// Special depth format with 16 bit integer depth.
2070 Depth16Unorm,
2071 /// Special depth format with at least 24 bit integer depth.
2072 Depth24Plus,
2073 /// Special depth/stencil format with at least 24 bit integer depth and 8 bits integer stencil.
2074 Depth24PlusStencil8,
2075 /// Special depth format with 32 bit floating point depth.
2076 Depth32Float,
2077 /// Special depth/stencil format with 32 bit floating point depth and 8 bits integer stencil.
2078 ///
2079 /// [`Features::DEPTH32FLOAT_STENCIL8`] must be enabled to use this texture format.
2080 Depth32FloatStencil8,
2081
2082 /// YUV 4:2:0 chroma subsampled format.
2083 ///
2084 /// Contains two planes:
2085 /// - 0: Single 8 bit channel luminance.
2086 /// - 1: Dual 8 bit channel chrominance at half width and half height.
2087 ///
2088 /// Valid view formats for luminance are [`TextureFormat::R8Unorm`].
2089 ///
2090 /// Valid view formats for chrominance are [`TextureFormat::Rg8Unorm`].
2091 ///
2092 /// Width and height must be even.
2093 ///
2094 /// [`Features::TEXTURE_FORMAT_NV12`] must be enabled to use this texture format.
2095 NV12,
2096
2097 // Compressed textures usable with `TEXTURE_COMPRESSION_BC` feature. `TEXTURE_COMPRESSION_SLICED_3D` is required to use with 3D textures.
2098 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). 4 color + alpha pallet. 5 bit R + 6 bit G + 5 bit B + 1 bit alpha.
2099 /// [0, 63] ([0, 1] for alpha) converted to/from float [0, 1] in shader.
2100 ///
2101 /// Also known as DXT1.
2102 ///
2103 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2104 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2105 Bc1RgbaUnorm,
2106 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). 4 color + alpha pallet. 5 bit R + 6 bit G + 5 bit B + 1 bit alpha.
2107 /// Srgb-color [0, 63] ([0, 1] for alpha) converted to/from linear-color float [0, 1] in shader.
2108 ///
2109 /// Also known as DXT1.
2110 ///
2111 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2112 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2113 Bc1RgbaUnormSrgb,
2114 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). 4 color pallet. 5 bit R + 6 bit G + 5 bit B + 4 bit alpha.
2115 /// [0, 63] ([0, 15] for alpha) converted to/from float [0, 1] in shader.
2116 ///
2117 /// Also known as DXT3.
2118 ///
2119 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2120 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2121 Bc2RgbaUnorm,
2122 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). 4 color pallet. 5 bit R + 6 bit G + 5 bit B + 4 bit alpha.
2123 /// Srgb-color [0, 63] ([0, 255] for alpha) converted to/from linear-color float [0, 1] in shader.
2124 ///
2125 /// Also known as DXT3.
2126 ///
2127 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2128 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2129 Bc2RgbaUnormSrgb,
2130 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). 4 color pallet + 8 alpha pallet. 5 bit R + 6 bit G + 5 bit B + 8 bit alpha.
2131 /// [0, 63] ([0, 255] for alpha) converted to/from float [0, 1] in shader.
2132 ///
2133 /// Also known as DXT5.
2134 ///
2135 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2136 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2137 Bc3RgbaUnorm,
2138 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). 4 color pallet + 8 alpha pallet. 5 bit R + 6 bit G + 5 bit B + 8 bit alpha.
2139 /// Srgb-color [0, 63] ([0, 255] for alpha) converted to/from linear-color float [0, 1] in shader.
2140 ///
2141 /// Also known as DXT5.
2142 ///
2143 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2144 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2145 Bc3RgbaUnormSrgb,
2146 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). 8 color pallet. 8 bit R.
2147 /// [0, 255] converted to/from float [0, 1] in shader.
2148 ///
2149 /// Also known as RGTC1.
2150 ///
2151 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2152 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2153 Bc4RUnorm,
2154 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). 8 color pallet. 8 bit R.
2155 /// [&minus;127, 127] converted to/from float [&minus;1, 1] in shader.
2156 ///
2157 /// Also known as RGTC1.
2158 ///
2159 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2160 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2161 Bc4RSnorm,
2162 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). 8 color red pallet + 8 color green pallet. 8 bit RG.
2163 /// [0, 255] converted to/from float [0, 1] in shader.
2164 ///
2165 /// Also known as RGTC2.
2166 ///
2167 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2168 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2169 Bc5RgUnorm,
2170 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). 8 color red pallet + 8 color green pallet. 8 bit RG.
2171 /// [&minus;127, 127] converted to/from float [&minus;1, 1] in shader.
2172 ///
2173 /// Also known as RGTC2.
2174 ///
2175 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2176 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2177 Bc5RgSnorm,
2178 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Variable sized pallet. 16 bit unsigned float RGB. Float in shader.
2179 ///
2180 /// Also known as BPTC (float).
2181 ///
2182 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2183 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2184 Bc6hRgbUfloat,
2185 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Variable sized pallet. 16 bit signed float RGB. Float in shader.
2186 ///
2187 /// Also known as BPTC (float).
2188 ///
2189 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2190 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2191 Bc6hRgbFloat,
2192 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Variable sized pallet. 8 bit integer RGBA.
2193 /// [0, 255] converted to/from float [0, 1] in shader.
2194 ///
2195 /// Also known as BPTC (unorm).
2196 ///
2197 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2198 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2199 Bc7RgbaUnorm,
2200 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Variable sized pallet. 8 bit integer RGBA.
2201 /// Srgb-color [0, 255] converted to/from linear-color float [0, 1] in shader.
2202 ///
2203 /// Also known as BPTC (unorm).
2204 ///
2205 /// [`Features::TEXTURE_COMPRESSION_BC`] must be enabled to use this texture format.
2206 /// [`Features::TEXTURE_COMPRESSION_BC_SLICED_3D`] must be enabled to use this texture format with 3D dimension.
2207 Bc7RgbaUnormSrgb,
2208 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). Complex pallet. 8 bit integer RGB.
2209 /// [0, 255] converted to/from float [0, 1] in shader.
2210 ///
2211 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2212 Etc2Rgb8Unorm,
2213 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). Complex pallet. 8 bit integer RGB.
2214 /// Srgb-color [0, 255] converted to/from linear-color float [0, 1] in shader.
2215 ///
2216 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2217 Etc2Rgb8UnormSrgb,
2218 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). Complex pallet. 8 bit integer RGB + 1 bit alpha.
2219 /// [0, 255] ([0, 1] for alpha) converted to/from float [0, 1] in shader.
2220 ///
2221 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2222 Etc2Rgb8A1Unorm,
2223 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). Complex pallet. 8 bit integer RGB + 1 bit alpha.
2224 /// Srgb-color [0, 255] ([0, 1] for alpha) converted to/from linear-color float [0, 1] in shader.
2225 ///
2226 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2227 Etc2Rgb8A1UnormSrgb,
2228 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Complex pallet. 8 bit integer RGB + 8 bit alpha.
2229 /// [0, 255] converted to/from float [0, 1] in shader.
2230 ///
2231 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2232 Etc2Rgba8Unorm,
2233 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Complex pallet. 8 bit integer RGB + 8 bit alpha.
2234 /// Srgb-color [0, 255] converted to/from linear-color float [0, 1] in shader.
2235 ///
2236 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2237 Etc2Rgba8UnormSrgb,
2238 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). Complex pallet. 11 bit integer R.
2239 /// [0, 255] converted to/from float [0, 1] in shader.
2240 ///
2241 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2242 EacR11Unorm,
2243 /// 4x4 block compressed texture. 8 bytes per block (4 bit/px). Complex pallet. 11 bit integer R.
2244 /// [&minus;127, 127] converted to/from float [&minus;1, 1] in shader.
2245 ///
2246 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2247 EacR11Snorm,
2248 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Complex pallet. 11 bit integer R + 11 bit integer G.
2249 /// [0, 255] converted to/from float [0, 1] in shader.
2250 ///
2251 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2252 EacRg11Unorm,
2253 /// 4x4 block compressed texture. 16 bytes per block (8 bit/px). Complex pallet. 11 bit integer R + 11 bit integer G.
2254 /// [&minus;127, 127] converted to/from float [&minus;1, 1] in shader.
2255 ///
2256 /// [`Features::TEXTURE_COMPRESSION_ETC2`] must be enabled to use this texture format.
2257 EacRg11Snorm,
2258 /// block compressed texture. 16 bytes per block.
2259 ///
2260 /// Features [`TEXTURE_COMPRESSION_ASTC`] or [`TEXTURE_COMPRESSION_ASTC_HDR`]
2261 /// must be enabled to use this texture format.
2262 ///
2263 /// [`TEXTURE_COMPRESSION_ASTC`]: Features::TEXTURE_COMPRESSION_ASTC
2264 /// [`TEXTURE_COMPRESSION_ASTC_HDR`]: Features::TEXTURE_COMPRESSION_ASTC_HDR
2265 Astc {
2266 /// compressed block dimensions
2267 block: AstcBlock,
2268 /// ASTC RGBA channel
2269 channel: AstcChannel,
2270 },
2271 }
2272
2273 #[cfg(any(feature = "serde", test))]
2274 impl<'de> Deserialize<'de> for TextureFormat {
2275 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2276 where
2277 D: serde::Deserializer<'de>,
2278 {
2279 use serde::de::{self, Error, Unexpected};
2280
2281 struct TextureFormatVisitor;
2282
2283 impl de::Visitor<'_> for TextureFormatVisitor {
2284 type Value = TextureFormat;
2285
2286 fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
2287 formatter.write_str("a valid texture format")
2288 }
2289
2290 fn visit_str<E: Error>(self, s: &str) -> Result<Self::Value, E> {
2291 let format = match s {
2292 "r8unorm" => TextureFormat::R8Unorm,
2293 "r8snorm" => TextureFormat::R8Snorm,
2294 "r8uint" => TextureFormat::R8Uint,
2295 "r8sint" => TextureFormat::R8Sint,
2296 "r16uint" => TextureFormat::R16Uint,
2297 "r16sint" => TextureFormat::R16Sint,
2298 "r16unorm" => TextureFormat::R16Unorm,
2299 "r16snorm" => TextureFormat::R16Snorm,
2300 "r16float" => TextureFormat::R16Float,
2301 "rg8unorm" => TextureFormat::Rg8Unorm,
2302 "rg8snorm" => TextureFormat::Rg8Snorm,
2303 "rg8uint" => TextureFormat::Rg8Uint,
2304 "rg8sint" => TextureFormat::Rg8Sint,
2305 "r32uint" => TextureFormat::R32Uint,
2306 "r32sint" => TextureFormat::R32Sint,
2307 "r32float" => TextureFormat::R32Float,
2308 "rg16uint" => TextureFormat::Rg16Uint,
2309 "rg16sint" => TextureFormat::Rg16Sint,
2310 "rg16unorm" => TextureFormat::Rg16Unorm,
2311 "rg16snorm" => TextureFormat::Rg16Snorm,
2312 "rg16float" => TextureFormat::Rg16Float,
2313 "rgba8unorm" => TextureFormat::Rgba8Unorm,
2314 "rgba8unorm-srgb" => TextureFormat::Rgba8UnormSrgb,
2315 "rgba8snorm" => TextureFormat::Rgba8Snorm,
2316 "rgba8uint" => TextureFormat::Rgba8Uint,
2317 "rgba8sint" => TextureFormat::Rgba8Sint,
2318 "bgra8unorm" => TextureFormat::Bgra8Unorm,
2319 "bgra8unorm-srgb" => TextureFormat::Bgra8UnormSrgb,
2320 "rgb10a2uint" => TextureFormat::Rgb10a2Uint,
2321 "rgb10a2unorm" => TextureFormat::Rgb10a2Unorm,
2322 "rg11b10ufloat" => TextureFormat::Rg11b10Ufloat,
2323 "r64uint" => TextureFormat::R64Uint,
2324 "rg32uint" => TextureFormat::Rg32Uint,
2325 "rg32sint" => TextureFormat::Rg32Sint,
2326 "rg32float" => TextureFormat::Rg32Float,
2327 "rgba16uint" => TextureFormat::Rgba16Uint,
2328 "rgba16sint" => TextureFormat::Rgba16Sint,
2329 "rgba16unorm" => TextureFormat::Rgba16Unorm,
2330 "rgba16snorm" => TextureFormat::Rgba16Snorm,
2331 "rgba16float" => TextureFormat::Rgba16Float,
2332 "rgba32uint" => TextureFormat::Rgba32Uint,
2333 "rgba32sint" => TextureFormat::Rgba32Sint,
2334 "rgba32float" => TextureFormat::Rgba32Float,
2335 "stencil8" => TextureFormat::Stencil8,
2336 "depth32float" => TextureFormat::Depth32Float,
2337 "depth32float-stencil8" => TextureFormat::Depth32FloatStencil8,
2338 "depth16unorm" => TextureFormat::Depth16Unorm,
2339 "depth24plus" => TextureFormat::Depth24Plus,
2340 "depth24plus-stencil8" => TextureFormat::Depth24PlusStencil8,
2341 "nv12" => TextureFormat::NV12,
2342 "rgb9e5ufloat" => TextureFormat::Rgb9e5Ufloat,
2343 "bc1-rgba-unorm" => TextureFormat::Bc1RgbaUnorm,
2344 "bc1-rgba-unorm-srgb" => TextureFormat::Bc1RgbaUnormSrgb,
2345 "bc2-rgba-unorm" => TextureFormat::Bc2RgbaUnorm,
2346 "bc2-rgba-unorm-srgb" => TextureFormat::Bc2RgbaUnormSrgb,
2347 "bc3-rgba-unorm" => TextureFormat::Bc3RgbaUnorm,
2348 "bc3-rgba-unorm-srgb" => TextureFormat::Bc3RgbaUnormSrgb,
2349 "bc4-r-unorm" => TextureFormat::Bc4RUnorm,
2350 "bc4-r-snorm" => TextureFormat::Bc4RSnorm,
2351 "bc5-rg-unorm" => TextureFormat::Bc5RgUnorm,
2352 "bc5-rg-snorm" => TextureFormat::Bc5RgSnorm,
2353 "bc6h-rgb-ufloat" => TextureFormat::Bc6hRgbUfloat,
2354 "bc6h-rgb-float" => TextureFormat::Bc6hRgbFloat,
2355 "bc7-rgba-unorm" => TextureFormat::Bc7RgbaUnorm,
2356 "bc7-rgba-unorm-srgb" => TextureFormat::Bc7RgbaUnormSrgb,
2357 "etc2-rgb8unorm" => TextureFormat::Etc2Rgb8Unorm,
2358 "etc2-rgb8unorm-srgb" => TextureFormat::Etc2Rgb8UnormSrgb,
2359 "etc2-rgb8a1unorm" => TextureFormat::Etc2Rgb8A1Unorm,
2360 "etc2-rgb8a1unorm-srgb" => TextureFormat::Etc2Rgb8A1UnormSrgb,
2361 "etc2-rgba8unorm" => TextureFormat::Etc2Rgba8Unorm,
2362 "etc2-rgba8unorm-srgb" => TextureFormat::Etc2Rgba8UnormSrgb,
2363 "eac-r11unorm" => TextureFormat::EacR11Unorm,
2364 "eac-r11snorm" => TextureFormat::EacR11Snorm,
2365 "eac-rg11unorm" => TextureFormat::EacRg11Unorm,
2366 "eac-rg11snorm" => TextureFormat::EacRg11Snorm,
2367 other => {
2368 if let Some(parts) = other.strip_prefix("astc-") {
2369 let (block, channel) = parts
2370 .split_once('-')
2371 .ok_or_else(|| E::invalid_value(Unexpected::Str(s), &self))?;
2372
2373 let block = match block {
2374 "4x4" => AstcBlock::B4x4,
2375 "5x4" => AstcBlock::B5x4,
2376 "5x5" => AstcBlock::B5x5,
2377 "6x5" => AstcBlock::B6x5,
2378 "6x6" => AstcBlock::B6x6,
2379 "8x5" => AstcBlock::B8x5,
2380 "8x6" => AstcBlock::B8x6,
2381 "8x8" => AstcBlock::B8x8,
2382 "10x5" => AstcBlock::B10x5,
2383 "10x6" => AstcBlock::B10x6,
2384 "10x8" => AstcBlock::B10x8,
2385 "10x10" => AstcBlock::B10x10,
2386 "12x10" => AstcBlock::B12x10,
2387 "12x12" => AstcBlock::B12x12,
2388 _ => return Err(E::invalid_value(Unexpected::Str(s), &self)),
2389 };
2390
2391 let channel = match channel {
2392 "unorm" => AstcChannel::Unorm,
2393 "unorm-srgb" => AstcChannel::UnormSrgb,
2394 "hdr" => AstcChannel::Hdr,
2395 _ => return Err(E::invalid_value(Unexpected::Str(s), &self)),
2396 };
2397
2398 TextureFormat::Astc { block, channel }
2399 } else {
2400 return Err(E::invalid_value(Unexpected::Str(s), &self));
2401 }
2402 }
2403 };
2404
2405 Ok(format)
2406 }
2407 }
2408
2409 deserializer.deserialize_str(TextureFormatVisitor)
2410 }
2411 }
2412
2413 #[cfg(any(feature = "serde", test))]
2414 impl Serialize for TextureFormat {
2415 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2416 where
2417 S: serde::Serializer,
2418 {
2419 let s: String;
2420 let name = match *self {
2421 TextureFormat::R8Unorm => "r8unorm",
2422 TextureFormat::R8Snorm => "r8snorm",
2423 TextureFormat::R8Uint => "r8uint",
2424 TextureFormat::R8Sint => "r8sint",
2425 TextureFormat::R16Uint => "r16uint",
2426 TextureFormat::R16Sint => "r16sint",
2427 TextureFormat::R16Unorm => "r16unorm",
2428 TextureFormat::R16Snorm => "r16snorm",
2429 TextureFormat::R16Float => "r16float",
2430 TextureFormat::Rg8Unorm => "rg8unorm",
2431 TextureFormat::Rg8Snorm => "rg8snorm",
2432 TextureFormat::Rg8Uint => "rg8uint",
2433 TextureFormat::Rg8Sint => "rg8sint",
2434 TextureFormat::R32Uint => "r32uint",
2435 TextureFormat::R32Sint => "r32sint",
2436 TextureFormat::R32Float => "r32float",
2437 TextureFormat::Rg16Uint => "rg16uint",
2438 TextureFormat::Rg16Sint => "rg16sint",
2439 TextureFormat::Rg16Unorm => "rg16unorm",
2440 TextureFormat::Rg16Snorm => "rg16snorm",
2441 TextureFormat::Rg16Float => "rg16float",
2442 TextureFormat::Rgba8Unorm => "rgba8unorm",
2443 TextureFormat::Rgba8UnormSrgb => "rgba8unorm-srgb",
2444 TextureFormat::Rgba8Snorm => "rgba8snorm",
2445 TextureFormat::Rgba8Uint => "rgba8uint",
2446 TextureFormat::Rgba8Sint => "rgba8sint",
2447 TextureFormat::Bgra8Unorm => "bgra8unorm",
2448 TextureFormat::Bgra8UnormSrgb => "bgra8unorm-srgb",
2449 TextureFormat::Rgb10a2Uint => "rgb10a2uint",
2450 TextureFormat::Rgb10a2Unorm => "rgb10a2unorm",
2451 TextureFormat::Rg11b10Ufloat => "rg11b10ufloat",
2452 TextureFormat::R64Uint => "r64uint",
2453 TextureFormat::Rg32Uint => "rg32uint",
2454 TextureFormat::Rg32Sint => "rg32sint",
2455 TextureFormat::Rg32Float => "rg32float",
2456 TextureFormat::Rgba16Uint => "rgba16uint",
2457 TextureFormat::Rgba16Sint => "rgba16sint",
2458 TextureFormat::Rgba16Unorm => "rgba16unorm",
2459 TextureFormat::Rgba16Snorm => "rgba16snorm",
2460 TextureFormat::Rgba16Float => "rgba16float",
2461 TextureFormat::Rgba32Uint => "rgba32uint",
2462 TextureFormat::Rgba32Sint => "rgba32sint",
2463 TextureFormat::Rgba32Float => "rgba32float",
2464 TextureFormat::Stencil8 => "stencil8",
2465 TextureFormat::Depth32Float => "depth32float",
2466 TextureFormat::Depth16Unorm => "depth16unorm",
2467 TextureFormat::Depth32FloatStencil8 => "depth32float-stencil8",
2468 TextureFormat::Depth24Plus => "depth24plus",
2469 TextureFormat::Depth24PlusStencil8 => "depth24plus-stencil8",
2470 TextureFormat::NV12 => "nv12",
2471 TextureFormat::Rgb9e5Ufloat => "rgb9e5ufloat",
2472 TextureFormat::Bc1RgbaUnorm => "bc1-rgba-unorm",
2473 TextureFormat::Bc1RgbaUnormSrgb => "bc1-rgba-unorm-srgb",
2474 TextureFormat::Bc2RgbaUnorm => "bc2-rgba-unorm",
2475 TextureFormat::Bc2RgbaUnormSrgb => "bc2-rgba-unorm-srgb",
2476 TextureFormat::Bc3RgbaUnorm => "bc3-rgba-unorm",
2477 TextureFormat::Bc3RgbaUnormSrgb => "bc3-rgba-unorm-srgb",
2478 TextureFormat::Bc4RUnorm => "bc4-r-unorm",
2479 TextureFormat::Bc4RSnorm => "bc4-r-snorm",
2480 TextureFormat::Bc5RgUnorm => "bc5-rg-unorm",
2481 TextureFormat::Bc5RgSnorm => "bc5-rg-snorm",
2482 TextureFormat::Bc6hRgbUfloat => "bc6h-rgb-ufloat",
2483 TextureFormat::Bc6hRgbFloat => "bc6h-rgb-float",
2484 TextureFormat::Bc7RgbaUnorm => "bc7-rgba-unorm",
2485 TextureFormat::Bc7RgbaUnormSrgb => "bc7-rgba-unorm-srgb",
2486 TextureFormat::Etc2Rgb8Unorm => "etc2-rgb8unorm",
2487 TextureFormat::Etc2Rgb8UnormSrgb => "etc2-rgb8unorm-srgb",
2488 TextureFormat::Etc2Rgb8A1Unorm => "etc2-rgb8a1unorm",
2489 TextureFormat::Etc2Rgb8A1UnormSrgb => "etc2-rgb8a1unorm-srgb",
2490 TextureFormat::Etc2Rgba8Unorm => "etc2-rgba8unorm",
2491 TextureFormat::Etc2Rgba8UnormSrgb => "etc2-rgba8unorm-srgb",
2492 TextureFormat::EacR11Unorm => "eac-r11unorm",
2493 TextureFormat::EacR11Snorm => "eac-r11snorm",
2494 TextureFormat::EacRg11Unorm => "eac-rg11unorm",
2495 TextureFormat::EacRg11Snorm => "eac-rg11snorm",
2496 TextureFormat::Astc { block, channel } => {
2497 let block = match block {
2498 AstcBlock::B4x4 => "4x4",
2499 AstcBlock::B5x4 => "5x4",
2500 AstcBlock::B5x5 => "5x5",
2501 AstcBlock::B6x5 => "6x5",
2502 AstcBlock::B6x6 => "6x6",
2503 AstcBlock::B8x5 => "8x5",
2504 AstcBlock::B8x6 => "8x6",
2505 AstcBlock::B8x8 => "8x8",
2506 AstcBlock::B10x5 => "10x5",
2507 AstcBlock::B10x6 => "10x6",
2508 AstcBlock::B10x8 => "10x8",
2509 AstcBlock::B10x10 => "10x10",
2510 AstcBlock::B12x10 => "12x10",
2511 AstcBlock::B12x12 => "12x12",
2512 };
2513
2514 let channel = match channel {
2515 AstcChannel::Unorm => "unorm",
2516 AstcChannel::UnormSrgb => "unorm-srgb",
2517 AstcChannel::Hdr => "hdr",
2518 };
2519
2520 s = format!("astc-{block}-{channel}");
2521 &s
2522 }
2523 };
2524 serializer.serialize_str(name)
2525 }
2526 }
2527
2528 impl TextureAspect {
2529 /// Returns the texture aspect for a given plane.
2530 #[must_use]
2531 pub fn from_plane(plane: u32) -> Option<Self> {
2532 Some(match plane {
2533 0 => Self::Plane0,
2534 1 => Self::Plane1,
2535 2 => Self::Plane2,
2536 _ => return None,
2537 })
2538 }
2539 }
2540
2541 impl TextureFormat {
2542 /// Returns the aspect-specific format of the original format
2543 ///
2544 /// see <https://gpuweb.github.io/gpuweb/#abstract-opdef-resolving-gputextureaspect>
2545 #[must_use]
2546 pub fn aspect_specific_format(&self, aspect: TextureAspect) -> Option<Self> {
2547 match (*self, aspect) {
2548 (Self::Stencil8, TextureAspect::StencilOnly) => Some(*self),
2549 (
2550 Self::Depth16Unorm | Self::Depth24Plus | Self::Depth32Float,
2551 TextureAspect::DepthOnly,
2552 ) => Some(*self),
2553 (
2554 Self::Depth24PlusStencil8 | Self::Depth32FloatStencil8,
2555 TextureAspect::StencilOnly,
2556 ) => Some(Self::Stencil8),
2557 (Self::Depth24PlusStencil8, TextureAspect::DepthOnly) => Some(Self::Depth24Plus),
2558 (Self::Depth32FloatStencil8, TextureAspect::DepthOnly) => Some(Self::Depth32Float),
2559 (Self::NV12, TextureAspect::Plane0) => Some(Self::R8Unorm),
2560 (Self::NV12, TextureAspect::Plane1) => Some(Self::Rg8Unorm),
2561 // views to multi-planar formats must specify the plane
2562 (format, TextureAspect::All) if !format.is_multi_planar_format() => Some(format),
2563 _ => None,
2564 }
2565 }
2566
2567 /// Returns `true` if `self` is a depth or stencil component of the given
2568 /// combined depth-stencil format
2569 #[must_use]
2570 pub fn is_depth_stencil_component(&self, combined_format: Self) -> bool {
2571 match (combined_format, *self) {
2572 (Self::Depth24PlusStencil8, Self::Depth24Plus | Self::Stencil8)
2573 | (Self::Depth32FloatStencil8, Self::Depth32Float | Self::Stencil8) => true,
2574 _ => false,
2575 }
2576 }
2577
2578 /// Returns `true` if the format is a depth and/or stencil format
2579 ///
2580 /// see <https://gpuweb.github.io/gpuweb/#depth-formats>
2581 #[must_use]
2582 pub fn is_depth_stencil_format(&self) -> bool {
2583 match *self {
2584 Self::Stencil8
2585 | Self::Depth16Unorm
2586 | Self::Depth24Plus
2587 | Self::Depth24PlusStencil8
2588 | Self::Depth32Float
2589 | Self::Depth32FloatStencil8 => true,
2590 _ => false,
2591 }
2592 }
2593
2594 /// Returns `true` if the format is a combined depth-stencil format
2595 ///
2596 /// see <https://gpuweb.github.io/gpuweb/#combined-depth-stencil-format>
2597 #[must_use]
2598 pub fn is_combined_depth_stencil_format(&self) -> bool {
2599 match *self {
2600 Self::Depth24PlusStencil8 | Self::Depth32FloatStencil8 => true,
2601 _ => false,
2602 }
2603 }
2604
2605 /// Returns `true` if the format is a multi-planar format
2606 #[must_use]
2607 pub fn is_multi_planar_format(&self) -> bool {
2608 self.planes().is_some()
2609 }
2610
2611 /// Returns the number of planes a multi-planar format has.
2612 #[must_use]
2613 pub fn planes(&self) -> Option<u32> {
2614 match *self {
2615 Self::NV12 => Some(2),
2616 _ => None,
2617 }
2618 }
2619
2620 /// Returns `true` if the format has a color aspect
2621 #[must_use]
2622 pub fn has_color_aspect(&self) -> bool {
2623 !self.is_depth_stencil_format()
2624 }
2625
2626 /// Returns `true` if the format has a depth aspect
2627 #[must_use]
2628 pub fn has_depth_aspect(&self) -> bool {
2629 match *self {
2630 Self::Depth16Unorm
2631 | Self::Depth24Plus
2632 | Self::Depth24PlusStencil8
2633 | Self::Depth32Float
2634 | Self::Depth32FloatStencil8 => true,
2635 _ => false,
2636 }
2637 }
2638
2639 /// Returns `true` if the format has a stencil aspect
2640 #[must_use]
2641 pub fn has_stencil_aspect(&self) -> bool {
2642 match *self {
2643 Self::Stencil8 | Self::Depth24PlusStencil8 | Self::Depth32FloatStencil8 => true,
2644 _ => false,
2645 }
2646 }
2647
2648 /// Returns the size multiple requirement for a texture using this format.
2649 #[must_use]
2650 pub fn size_multiple_requirement(&self) -> (u32, u32) {
2651 match *self {
2652 Self::NV12 => (2, 2),
2653 _ => self.block_dimensions(),
2654 }
2655 }
2656
2657 /// Returns the dimension of a [block](https://gpuweb.github.io/gpuweb/#texel-block) of texels.
2658 ///
2659 /// Uncompressed formats have a block dimension of `(1, 1)`.
2660 #[must_use]
2661 pub fn block_dimensions(&self) -> (u32, u32) {
2662 match *self {
2663 Self::R8Unorm
2664 | Self::R8Snorm
2665 | Self::R8Uint
2666 | Self::R8Sint
2667 | Self::R16Uint
2668 | Self::R16Sint
2669 | Self::R16Unorm
2670 | Self::R16Snorm
2671 | Self::R16Float
2672 | Self::Rg8Unorm
2673 | Self::Rg8Snorm
2674 | Self::Rg8Uint
2675 | Self::Rg8Sint
2676 | Self::R32Uint
2677 | Self::R32Sint
2678 | Self::R32Float
2679 | Self::Rg16Uint
2680 | Self::Rg16Sint
2681 | Self::Rg16Unorm
2682 | Self::Rg16Snorm
2683 | Self::Rg16Float
2684 | Self::Rgba8Unorm
2685 | Self::Rgba8UnormSrgb
2686 | Self::Rgba8Snorm
2687 | Self::Rgba8Uint
2688 | Self::Rgba8Sint
2689 | Self::Bgra8Unorm
2690 | Self::Bgra8UnormSrgb
2691 | Self::Rgb9e5Ufloat
2692 | Self::Rgb10a2Uint
2693 | Self::Rgb10a2Unorm
2694 | Self::Rg11b10Ufloat
2695 | Self::R64Uint
2696 | Self::Rg32Uint
2697 | Self::Rg32Sint
2698 | Self::Rg32Float
2699 | Self::Rgba16Uint
2700 | Self::Rgba16Sint
2701 | Self::Rgba16Unorm
2702 | Self::Rgba16Snorm
2703 | Self::Rgba16Float
2704 | Self::Rgba32Uint
2705 | Self::Rgba32Sint
2706 | Self::Rgba32Float
2707 | Self::Stencil8
2708 | Self::Depth16Unorm
2709 | Self::Depth24Plus
2710 | Self::Depth24PlusStencil8
2711 | Self::Depth32Float
2712 | Self::Depth32FloatStencil8
2713 | Self::NV12 => (1, 1),
2714
2715 Self::Bc1RgbaUnorm
2716 | Self::Bc1RgbaUnormSrgb
2717 | Self::Bc2RgbaUnorm
2718 | Self::Bc2RgbaUnormSrgb
2719 | Self::Bc3RgbaUnorm
2720 | Self::Bc3RgbaUnormSrgb
2721 | Self::Bc4RUnorm
2722 | Self::Bc4RSnorm
2723 | Self::Bc5RgUnorm
2724 | Self::Bc5RgSnorm
2725 | Self::Bc6hRgbUfloat
2726 | Self::Bc6hRgbFloat
2727 | Self::Bc7RgbaUnorm
2728 | Self::Bc7RgbaUnormSrgb => (4, 4),
2729
2730 Self::Etc2Rgb8Unorm
2731 | Self::Etc2Rgb8UnormSrgb
2732 | Self::Etc2Rgb8A1Unorm
2733 | Self::Etc2Rgb8A1UnormSrgb
2734 | Self::Etc2Rgba8Unorm
2735 | Self::Etc2Rgba8UnormSrgb
2736 | Self::EacR11Unorm
2737 | Self::EacR11Snorm
2738 | Self::EacRg11Unorm
2739 | Self::EacRg11Snorm => (4, 4),
2740
2741 Self::Astc { block, .. } => match block {
2742 AstcBlock::B4x4 => (4, 4),
2743 AstcBlock::B5x4 => (5, 4),
2744 AstcBlock::B5x5 => (5, 5),
2745 AstcBlock::B6x5 => (6, 5),
2746 AstcBlock::B6x6 => (6, 6),
2747 AstcBlock::B8x5 => (8, 5),
2748 AstcBlock::B8x6 => (8, 6),
2749 AstcBlock::B8x8 => (8, 8),
2750 AstcBlock::B10x5 => (10, 5),
2751 AstcBlock::B10x6 => (10, 6),
2752 AstcBlock::B10x8 => (10, 8),
2753 AstcBlock::B10x10 => (10, 10),
2754 AstcBlock::B12x10 => (12, 10),
2755 AstcBlock::B12x12 => (12, 12),
2756 },
2757 }
2758 }
2759
2760 /// Returns `true` for compressed formats.
2761 #[must_use]
2762 pub fn is_compressed(&self) -> bool {
2763 self.block_dimensions() != (1, 1)
2764 }
2765
2766 /// Returns `true` for BCn compressed formats.
2767 #[must_use]
2768 pub fn is_bcn(&self) -> bool {
2769 self.required_features() == Features::TEXTURE_COMPRESSION_BC
2770 }
2771
2772 /// Returns `true` for ASTC compressed formats.
2773 #[must_use]
2774 pub fn is_astc(&self) -> bool {
2775 self.required_features() == Features::TEXTURE_COMPRESSION_ASTC
2776 || self.required_features() == Features::TEXTURE_COMPRESSION_ASTC_HDR
2777 }
2778
2779 /// Returns the required features (if any) in order to use the texture.
2780 #[must_use]
2781 pub fn required_features(&self) -> Features {
2782 match *self {
2783 Self::R8Unorm
2784 | Self::R8Snorm
2785 | Self::R8Uint
2786 | Self::R8Sint
2787 | Self::R16Uint
2788 | Self::R16Sint
2789 | Self::R16Float
2790 | Self::Rg8Unorm
2791 | Self::Rg8Snorm
2792 | Self::Rg8Uint
2793 | Self::Rg8Sint
2794 | Self::R32Uint
2795 | Self::R32Sint
2796 | Self::R32Float
2797 | Self::Rg16Uint
2798 | Self::Rg16Sint
2799 | Self::Rg16Float
2800 | Self::Rgba8Unorm
2801 | Self::Rgba8UnormSrgb
2802 | Self::Rgba8Snorm
2803 | Self::Rgba8Uint
2804 | Self::Rgba8Sint
2805 | Self::Bgra8Unorm
2806 | Self::Bgra8UnormSrgb
2807 | Self::Rgb9e5Ufloat
2808 | Self::Rgb10a2Uint
2809 | Self::Rgb10a2Unorm
2810 | Self::Rg11b10Ufloat
2811 | Self::Rg32Uint
2812 | Self::Rg32Sint
2813 | Self::Rg32Float
2814 | Self::Rgba16Uint
2815 | Self::Rgba16Sint
2816 | Self::Rgba16Float
2817 | Self::Rgba32Uint
2818 | Self::Rgba32Sint
2819 | Self::Rgba32Float
2820 | Self::Stencil8
2821 | Self::Depth16Unorm
2822 | Self::Depth24Plus
2823 | Self::Depth24PlusStencil8
2824 | Self::Depth32Float => Features::empty(),
2825
2826 Self::R64Uint => Features::TEXTURE_INT64_ATOMIC,
2827
2828 Self::Depth32FloatStencil8 => Features::DEPTH32FLOAT_STENCIL8,
2829
2830 Self::NV12 => Features::TEXTURE_FORMAT_NV12,
2831
2832 Self::R16Unorm
2833 | Self::R16Snorm
2834 | Self::Rg16Unorm
2835 | Self::Rg16Snorm
2836 | Self::Rgba16Unorm
2837 | Self::Rgba16Snorm => Features::TEXTURE_FORMAT_16BIT_NORM,
2838
2839 Self::Bc1RgbaUnorm
2840 | Self::Bc1RgbaUnormSrgb
2841 | Self::Bc2RgbaUnorm
2842 | Self::Bc2RgbaUnormSrgb
2843 | Self::Bc3RgbaUnorm
2844 | Self::Bc3RgbaUnormSrgb
2845 | Self::Bc4RUnorm
2846 | Self::Bc4RSnorm
2847 | Self::Bc5RgUnorm
2848 | Self::Bc5RgSnorm
2849 | Self::Bc6hRgbUfloat
2850 | Self::Bc6hRgbFloat
2851 | Self::Bc7RgbaUnorm
2852 | Self::Bc7RgbaUnormSrgb => Features::TEXTURE_COMPRESSION_BC,
2853
2854 Self::Etc2Rgb8Unorm
2855 | Self::Etc2Rgb8UnormSrgb
2856 | Self::Etc2Rgb8A1Unorm
2857 | Self::Etc2Rgb8A1UnormSrgb
2858 | Self::Etc2Rgba8Unorm
2859 | Self::Etc2Rgba8UnormSrgb
2860 | Self::EacR11Unorm
2861 | Self::EacR11Snorm
2862 | Self::EacRg11Unorm
2863 | Self::EacRg11Snorm => Features::TEXTURE_COMPRESSION_ETC2,
2864
2865 Self::Astc { channel, .. } => match channel {
2866 AstcChannel::Hdr => Features::TEXTURE_COMPRESSION_ASTC_HDR,
2867 AstcChannel::Unorm | AstcChannel::UnormSrgb => Features::TEXTURE_COMPRESSION_ASTC,
2868 },
2869 }
2870 }
2871
2872 /// Returns the format features guaranteed by the WebGPU spec.
2873 ///
2874 /// Additional features are available if `Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES` is enabled.
2875 #[must_use]
2876 pub fn guaranteed_format_features(&self, device_features: Features) -> TextureFormatFeatures {
2877 // Multisampling
2878 let none = TextureFormatFeatureFlags::empty();
2879 let msaa = TextureFormatFeatureFlags::MULTISAMPLE_X4;
2880 let msaa_resolve = msaa | TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE;
2881
2882 let s_ro_wo = TextureFormatFeatureFlags::STORAGE_READ_ONLY
2883 | TextureFormatFeatureFlags::STORAGE_WRITE_ONLY;
2884 let s_all = s_ro_wo | TextureFormatFeatureFlags::STORAGE_READ_WRITE;
2885
2886 // Flags
2887 let basic =
2888 TextureUsages::COPY_SRC | TextureUsages::COPY_DST | TextureUsages::TEXTURE_BINDING;
2889 let attachment = basic | TextureUsages::RENDER_ATTACHMENT;
2890 let storage = basic | TextureUsages::STORAGE_BINDING;
2891 let binding = TextureUsages::TEXTURE_BINDING;
2892 let all_flags = attachment | storage | binding;
2893 let atomic_64 = if device_features.contains(Features::TEXTURE_ATOMIC) {
2894 storage | binding | TextureUsages::STORAGE_ATOMIC
2895 } else {
2896 storage | binding
2897 };
2898 let atomic = attachment | atomic_64;
2899 let rg11b10f = if device_features.contains(Features::RG11B10UFLOAT_RENDERABLE) {
2900 attachment
2901 } else {
2902 basic
2903 };
2904 let (bgra8unorm_f, bgra8unorm) = if device_features.contains(Features::BGRA8UNORM_STORAGE) {
2905 (
2906 msaa_resolve | TextureFormatFeatureFlags::STORAGE_WRITE_ONLY,
2907 attachment | TextureUsages::STORAGE_BINDING,
2908 )
2909 } else {
2910 (msaa_resolve, attachment)
2911 };
2912
2913 #[rustfmt::skip] // lets make a nice table
2914 let (
2915 mut flags,
2916 allowed_usages,
2917 ) = match *self {
2918 Self::R8Unorm => (msaa_resolve, attachment),
2919 Self::R8Snorm => ( none, basic),
2920 Self::R8Uint => ( msaa, attachment),
2921 Self::R8Sint => ( msaa, attachment),
2922 Self::R16Uint => ( msaa, attachment),
2923 Self::R16Sint => ( msaa, attachment),
2924 Self::R16Float => (msaa_resolve, attachment),
2925 Self::Rg8Unorm => (msaa_resolve, attachment),
2926 Self::Rg8Snorm => ( none, basic),
2927 Self::Rg8Uint => ( msaa, attachment),
2928 Self::Rg8Sint => ( msaa, attachment),
2929 Self::R32Uint => ( s_all, atomic),
2930 Self::R32Sint => ( s_all, atomic),
2931 Self::R32Float => (msaa | s_all, all_flags),
2932 Self::Rg16Uint => ( msaa, attachment),
2933 Self::Rg16Sint => ( msaa, attachment),
2934 Self::Rg16Float => (msaa_resolve, attachment),
2935 Self::Rgba8Unorm => (msaa_resolve | s_ro_wo, all_flags),
2936 Self::Rgba8UnormSrgb => (msaa_resolve, attachment),
2937 Self::Rgba8Snorm => ( s_ro_wo, storage),
2938 Self::Rgba8Uint => ( msaa | s_ro_wo, all_flags),
2939 Self::Rgba8Sint => ( msaa | s_ro_wo, all_flags),
2940 Self::Bgra8Unorm => (bgra8unorm_f, bgra8unorm),
2941 Self::Bgra8UnormSrgb => (msaa_resolve, attachment),
2942 Self::Rgb10a2Uint => ( msaa, attachment),
2943 Self::Rgb10a2Unorm => (msaa_resolve, attachment),
2944 Self::Rg11b10Ufloat => ( msaa, rg11b10f),
2945 Self::R64Uint => ( s_ro_wo, atomic_64),
2946 Self::Rg32Uint => ( s_ro_wo, all_flags),
2947 Self::Rg32Sint => ( s_ro_wo, all_flags),
2948 Self::Rg32Float => ( s_ro_wo, all_flags),
2949 Self::Rgba16Uint => ( msaa | s_ro_wo, all_flags),
2950 Self::Rgba16Sint => ( msaa | s_ro_wo, all_flags),
2951 Self::Rgba16Float => (msaa_resolve | s_ro_wo, all_flags),
2952 Self::Rgba32Uint => ( s_ro_wo, all_flags),
2953 Self::Rgba32Sint => ( s_ro_wo, all_flags),
2954 Self::Rgba32Float => ( s_ro_wo, all_flags),
2955
2956 Self::Stencil8 => ( msaa, attachment),
2957 Self::Depth16Unorm => ( msaa, attachment),
2958 Self::Depth24Plus => ( msaa, attachment),
2959 Self::Depth24PlusStencil8 => ( msaa, attachment),
2960 Self::Depth32Float => ( msaa, attachment),
2961 Self::Depth32FloatStencil8 => ( msaa, attachment),
2962
2963 // We only support sampling nv12 textures until we implement transfer plane data.
2964 Self::NV12 => ( none, binding),
2965
2966 Self::R16Unorm => ( msaa | s_ro_wo, storage),
2967 Self::R16Snorm => ( msaa | s_ro_wo, storage),
2968 Self::Rg16Unorm => ( msaa | s_ro_wo, storage),
2969 Self::Rg16Snorm => ( msaa | s_ro_wo, storage),
2970 Self::Rgba16Unorm => ( msaa | s_ro_wo, storage),
2971 Self::Rgba16Snorm => ( msaa | s_ro_wo, storage),
2972
2973 Self::Rgb9e5Ufloat => ( none, basic),
2974
2975 Self::Bc1RgbaUnorm => ( none, basic),
2976 Self::Bc1RgbaUnormSrgb => ( none, basic),
2977 Self::Bc2RgbaUnorm => ( none, basic),
2978 Self::Bc2RgbaUnormSrgb => ( none, basic),
2979 Self::Bc3RgbaUnorm => ( none, basic),
2980 Self::Bc3RgbaUnormSrgb => ( none, basic),
2981 Self::Bc4RUnorm => ( none, basic),
2982 Self::Bc4RSnorm => ( none, basic),
2983 Self::Bc5RgUnorm => ( none, basic),
2984 Self::Bc5RgSnorm => ( none, basic),
2985 Self::Bc6hRgbUfloat => ( none, basic),
2986 Self::Bc6hRgbFloat => ( none, basic),
2987 Self::Bc7RgbaUnorm => ( none, basic),
2988 Self::Bc7RgbaUnormSrgb => ( none, basic),
2989
2990 Self::Etc2Rgb8Unorm => ( none, basic),
2991 Self::Etc2Rgb8UnormSrgb => ( none, basic),
2992 Self::Etc2Rgb8A1Unorm => ( none, basic),
2993 Self::Etc2Rgb8A1UnormSrgb => ( none, basic),
2994 Self::Etc2Rgba8Unorm => ( none, basic),
2995 Self::Etc2Rgba8UnormSrgb => ( none, basic),
2996 Self::EacR11Unorm => ( none, basic),
2997 Self::EacR11Snorm => ( none, basic),
2998 Self::EacRg11Unorm => ( none, basic),
2999 Self::EacRg11Snorm => ( none, basic),
3000
3001 Self::Astc { .. } => ( none, basic),
3002 };
3003
3004 // Get whether the format is filterable, taking features into account
3005 let sample_type1 = self.sample_type(None, Some(device_features));
3006 let is_filterable = sample_type1 == Some(TextureSampleType::Float { filterable: true });
3007
3008 // Features that enable filtering don't affect blendability
3009 let sample_type2 = self.sample_type(None, None);
3010 let is_blendable = sample_type2 == Some(TextureSampleType::Float { filterable: true });
3011
3012 flags.set(TextureFormatFeatureFlags::FILTERABLE, is_filterable);
3013 flags.set(TextureFormatFeatureFlags::BLENDABLE, is_blendable);
3014 flags.set(
3015 TextureFormatFeatureFlags::STORAGE_ATOMIC,
3016 allowed_usages.contains(TextureUsages::STORAGE_ATOMIC),
3017 );
3018
3019 TextureFormatFeatures {
3020 allowed_usages,
3021 flags,
3022 }
3023 }
3024
3025 /// Returns the sample type compatible with this format and aspect.
3026 ///
3027 /// Returns `None` only if this is a combined depth-stencil format or a multi-planar format
3028 /// and `TextureAspect::All` or no `aspect` was provided.
3029 #[must_use]
3030 pub fn sample_type(
3031 &self,
3032 aspect: Option<TextureAspect>,
3033 device_features: Option<Features>,
3034 ) -> Option<TextureSampleType> {
3035 let float = TextureSampleType::Float { filterable: true };
3036 let unfilterable_float = TextureSampleType::Float { filterable: false };
3037 let float32_sample_type = TextureSampleType::Float {
3038 filterable: device_features
3039 .unwrap_or(Features::empty())
3040 .contains(Features::FLOAT32_FILTERABLE),
3041 };
3042 let depth = TextureSampleType::Depth;
3043 let uint = TextureSampleType::Uint;
3044 let sint = TextureSampleType::Sint;
3045
3046 match *self {
3047 Self::R8Unorm
3048 | Self::R8Snorm
3049 | Self::Rg8Unorm
3050 | Self::Rg8Snorm
3051 | Self::Rgba8Unorm
3052 | Self::Rgba8UnormSrgb
3053 | Self::Rgba8Snorm
3054 | Self::Bgra8Unorm
3055 | Self::Bgra8UnormSrgb
3056 | Self::R16Float
3057 | Self::Rg16Float
3058 | Self::Rgba16Float
3059 | Self::Rgb10a2Unorm
3060 | Self::Rg11b10Ufloat => Some(float),
3061
3062 Self::R32Float | Self::Rg32Float | Self::Rgba32Float => Some(float32_sample_type),
3063
3064 Self::R8Uint
3065 | Self::Rg8Uint
3066 | Self::Rgba8Uint
3067 | Self::R16Uint
3068 | Self::Rg16Uint
3069 | Self::Rgba16Uint
3070 | Self::R32Uint
3071 | Self::R64Uint
3072 | Self::Rg32Uint
3073 | Self::Rgba32Uint
3074 | Self::Rgb10a2Uint => Some(uint),
3075
3076 Self::R8Sint
3077 | Self::Rg8Sint
3078 | Self::Rgba8Sint
3079 | Self::R16Sint
3080 | Self::Rg16Sint
3081 | Self::Rgba16Sint
3082 | Self::R32Sint
3083 | Self::Rg32Sint
3084 | Self::Rgba32Sint => Some(sint),
3085
3086 Self::Stencil8 => Some(uint),
3087 Self::Depth16Unorm | Self::Depth24Plus | Self::Depth32Float => Some(depth),
3088 Self::Depth24PlusStencil8 | Self::Depth32FloatStencil8 => match aspect {
3089 Some(TextureAspect::DepthOnly) => Some(depth),
3090 Some(TextureAspect::StencilOnly) => Some(uint),
3091 _ => None,
3092 },
3093
3094 Self::NV12 => match aspect {
3095 Some(TextureAspect::Plane0) | Some(TextureAspect::Plane1) => {
3096 Some(unfilterable_float)
3097 }
3098 _ => None,
3099 },
3100
3101 Self::R16Unorm
3102 | Self::R16Snorm
3103 | Self::Rg16Unorm
3104 | Self::Rg16Snorm
3105 | Self::Rgba16Unorm
3106 | Self::Rgba16Snorm => Some(float),
3107
3108 Self::Rgb9e5Ufloat => Some(float),
3109
3110 Self::Bc1RgbaUnorm
3111 | Self::Bc1RgbaUnormSrgb
3112 | Self::Bc2RgbaUnorm
3113 | Self::Bc2RgbaUnormSrgb
3114 | Self::Bc3RgbaUnorm
3115 | Self::Bc3RgbaUnormSrgb
3116 | Self::Bc4RUnorm
3117 | Self::Bc4RSnorm
3118 | Self::Bc5RgUnorm
3119 | Self::Bc5RgSnorm
3120 | Self::Bc6hRgbUfloat
3121 | Self::Bc6hRgbFloat
3122 | Self::Bc7RgbaUnorm
3123 | Self::Bc7RgbaUnormSrgb => Some(float),
3124
3125 Self::Etc2Rgb8Unorm
3126 | Self::Etc2Rgb8UnormSrgb
3127 | Self::Etc2Rgb8A1Unorm
3128 | Self::Etc2Rgb8A1UnormSrgb
3129 | Self::Etc2Rgba8Unorm
3130 | Self::Etc2Rgba8UnormSrgb
3131 | Self::EacR11Unorm
3132 | Self::EacR11Snorm
3133 | Self::EacRg11Unorm
3134 | Self::EacRg11Snorm => Some(float),
3135
3136 Self::Astc { .. } => Some(float),
3137 }
3138 }
3139
3140 /// The number of bytes one [texel block](https://gpuweb.github.io/gpuweb/#texel-block) occupies during an image copy, if applicable.
3141 ///
3142 /// Known as the [texel block copy footprint](https://gpuweb.github.io/gpuweb/#texel-block-copy-footprint).
3143 ///
3144 /// Note that for uncompressed formats this is the same as the size of a single texel,
3145 /// since uncompressed formats have a block size of 1x1.
3146 ///
3147 /// Returns `None` if any of the following are true:
3148 /// - the format is a combined depth-stencil and no `aspect` was provided
3149 /// - the format is a multi-planar format and no `aspect` was provided
3150 /// - the format is `Depth24Plus`
3151 /// - the format is `Depth24PlusStencil8` and `aspect` is depth.
3152 #[deprecated(since = "0.19.0", note = "Use `block_copy_size` instead.")]
3153 #[must_use]
3154 pub fn block_size(&self, aspect: Option<TextureAspect>) -> Option<u32> {
3155 self.block_copy_size(aspect)
3156 }
3157
3158 /// The number of bytes one [texel block](https://gpuweb.github.io/gpuweb/#texel-block) occupies during an image copy, if applicable.
3159 ///
3160 /// Known as the [texel block copy footprint](https://gpuweb.github.io/gpuweb/#texel-block-copy-footprint).
3161 ///
3162 /// Note that for uncompressed formats this is the same as the size of a single texel,
3163 /// since uncompressed formats have a block size of 1x1.
3164 ///
3165 /// Returns `None` if any of the following are true:
3166 /// - the format is a combined depth-stencil and no `aspect` was provided
3167 /// - the format is a multi-planar format and no `aspect` was provided
3168 /// - the format is `Depth24Plus`
3169 /// - the format is `Depth24PlusStencil8` and `aspect` is depth.
3170 #[must_use]
3171 pub fn block_copy_size(&self, aspect: Option<TextureAspect>) -> Option<u32> {
3172 match *self {
3173 Self::R8Unorm | Self::R8Snorm | Self::R8Uint | Self::R8Sint => Some(1),
3174
3175 Self::Rg8Unorm | Self::Rg8Snorm | Self::Rg8Uint | Self::Rg8Sint => Some(2),
3176 Self::R16Unorm | Self::R16Snorm | Self::R16Uint | Self::R16Sint | Self::R16Float => {
3177 Some(2)
3178 }
3179
3180 Self::Rgba8Unorm
3181 | Self::Rgba8UnormSrgb
3182 | Self::Rgba8Snorm
3183 | Self::Rgba8Uint
3184 | Self::Rgba8Sint
3185 | Self::Bgra8Unorm
3186 | Self::Bgra8UnormSrgb => Some(4),
3187 Self::Rg16Unorm
3188 | Self::Rg16Snorm
3189 | Self::Rg16Uint
3190 | Self::Rg16Sint
3191 | Self::Rg16Float => Some(4),
3192 Self::R32Uint | Self::R32Sint | Self::R32Float => Some(4),
3193 Self::Rgb9e5Ufloat | Self::Rgb10a2Uint | Self::Rgb10a2Unorm | Self::Rg11b10Ufloat => {
3194 Some(4)
3195 }
3196
3197 Self::Rgba16Unorm
3198 | Self::Rgba16Snorm
3199 | Self::Rgba16Uint
3200 | Self::Rgba16Sint
3201 | Self::Rgba16Float => Some(8),
3202 Self::R64Uint | Self::Rg32Uint | Self::Rg32Sint | Self::Rg32Float => Some(8),
3203
3204 Self::Rgba32Uint | Self::Rgba32Sint | Self::Rgba32Float => Some(16),
3205
3206 Self::Stencil8 => Some(1),
3207 Self::Depth16Unorm => Some(2),
3208 Self::Depth32Float => Some(4),
3209 Self::Depth24Plus => None,
3210 Self::Depth24PlusStencil8 => match aspect {
3211 Some(TextureAspect::DepthOnly) => None,
3212 Some(TextureAspect::StencilOnly) => Some(1),
3213 _ => None,
3214 },
3215 Self::Depth32FloatStencil8 => match aspect {
3216 Some(TextureAspect::DepthOnly) => Some(4),
3217 Some(TextureAspect::StencilOnly) => Some(1),
3218 _ => None,
3219 },
3220
3221 Self::NV12 => match aspect {
3222 Some(TextureAspect::Plane0) => Some(1),
3223 Some(TextureAspect::Plane1) => Some(2),
3224 _ => None,
3225 },
3226
3227 Self::Bc1RgbaUnorm | Self::Bc1RgbaUnormSrgb | Self::Bc4RUnorm | Self::Bc4RSnorm => {
3228 Some(8)
3229 }
3230 Self::Bc2RgbaUnorm
3231 | Self::Bc2RgbaUnormSrgb
3232 | Self::Bc3RgbaUnorm
3233 | Self::Bc3RgbaUnormSrgb
3234 | Self::Bc5RgUnorm
3235 | Self::Bc5RgSnorm
3236 | Self::Bc6hRgbUfloat
3237 | Self::Bc6hRgbFloat
3238 | Self::Bc7RgbaUnorm
3239 | Self::Bc7RgbaUnormSrgb => Some(16),
3240
3241 Self::Etc2Rgb8Unorm
3242 | Self::Etc2Rgb8UnormSrgb
3243 | Self::Etc2Rgb8A1Unorm
3244 | Self::Etc2Rgb8A1UnormSrgb
3245 | Self::EacR11Unorm
3246 | Self::EacR11Snorm => Some(8),
3247 Self::Etc2Rgba8Unorm
3248 | Self::Etc2Rgba8UnormSrgb
3249 | Self::EacRg11Unorm
3250 | Self::EacRg11Snorm => Some(16),
3251
3252 Self::Astc { .. } => Some(16),
3253 }
3254 }
3255
3256 /// The largest number that can be returned by [`Self::target_pixel_byte_cost`].
3257 pub const MAX_TARGET_PIXEL_BYTE_COST: u32 = 16;
3258
3259 /// The number of bytes occupied per pixel in a color attachment
3260 /// <https://gpuweb.github.io/gpuweb/#render-target-pixel-byte-cost>
3261 #[must_use]
3262 pub fn target_pixel_byte_cost(&self) -> Option<u32> {
3263 match *self {
3264 Self::R8Unorm | Self::R8Snorm | Self::R8Uint | Self::R8Sint => Some(1),
3265 Self::Rg8Unorm
3266 | Self::Rg8Snorm
3267 | Self::Rg8Uint
3268 | Self::Rg8Sint
3269 | Self::R16Uint
3270 | Self::R16Sint
3271 | Self::R16Unorm
3272 | Self::R16Snorm
3273 | Self::R16Float => Some(2),
3274 Self::Rgba8Uint
3275 | Self::Rgba8Sint
3276 | Self::Rg16Uint
3277 | Self::Rg16Sint
3278 | Self::Rg16Unorm
3279 | Self::Rg16Snorm
3280 | Self::Rg16Float
3281 | Self::R32Uint
3282 | Self::R32Sint
3283 | Self::R32Float => Some(4),
3284 // Despite being 4 bytes per pixel, these are 8 bytes per pixel in the table
3285 Self::Rgba8Unorm
3286 | Self::Rgba8UnormSrgb
3287 | Self::Rgba8Snorm
3288 | Self::Bgra8Unorm
3289 | Self::Bgra8UnormSrgb
3290 // ---
3291 | Self::Rgba16Uint
3292 | Self::Rgba16Sint
3293 | Self::Rgba16Unorm
3294 | Self::Rgba16Snorm
3295 | Self::Rgba16Float
3296 | Self::R64Uint
3297 | Self::Rg32Uint
3298 | Self::Rg32Sint
3299 | Self::Rg32Float
3300 | Self::Rgb10a2Uint
3301 | Self::Rgb10a2Unorm
3302 | Self::Rg11b10Ufloat => Some(8),
3303 Self::Rgba32Uint | Self::Rgba32Sint | Self::Rgba32Float => Some(16),
3304 // ⚠️ If you add formats with larger sizes, make sure you change `MAX_TARGET_PIXEL_BYTE_COST`` ⚠️
3305 Self::Stencil8
3306 | Self::Depth16Unorm
3307 | Self::Depth24Plus
3308 | Self::Depth24PlusStencil8
3309 | Self::Depth32Float
3310 | Self::Depth32FloatStencil8
3311 | Self::NV12
3312 | Self::Rgb9e5Ufloat
3313 | Self::Bc1RgbaUnorm
3314 | Self::Bc1RgbaUnormSrgb
3315 | Self::Bc2RgbaUnorm
3316 | Self::Bc2RgbaUnormSrgb
3317 | Self::Bc3RgbaUnorm
3318 | Self::Bc3RgbaUnormSrgb
3319 | Self::Bc4RUnorm
3320 | Self::Bc4RSnorm
3321 | Self::Bc5RgUnorm
3322 | Self::Bc5RgSnorm
3323 | Self::Bc6hRgbUfloat
3324 | Self::Bc6hRgbFloat
3325 | Self::Bc7RgbaUnorm
3326 | Self::Bc7RgbaUnormSrgb
3327 | Self::Etc2Rgb8Unorm
3328 | Self::Etc2Rgb8UnormSrgb
3329 | Self::Etc2Rgb8A1Unorm
3330 | Self::Etc2Rgb8A1UnormSrgb
3331 | Self::Etc2Rgba8Unorm
3332 | Self::Etc2Rgba8UnormSrgb
3333 | Self::EacR11Unorm
3334 | Self::EacR11Snorm
3335 | Self::EacRg11Unorm
3336 | Self::EacRg11Snorm
3337 | Self::Astc { .. } => None,
3338 }
3339 }
3340
3341 /// See <https://gpuweb.github.io/gpuweb/#render-target-component-alignment>
3342 #[must_use]
3343 pub fn target_component_alignment(&self) -> Option<u32> {
3344 match *self {
3345 Self::R8Unorm
3346 | Self::R8Snorm
3347 | Self::R8Uint
3348 | Self::R8Sint
3349 | Self::Rg8Unorm
3350 | Self::Rg8Snorm
3351 | Self::Rg8Uint
3352 | Self::Rg8Sint
3353 | Self::Rgba8Unorm
3354 | Self::Rgba8UnormSrgb
3355 | Self::Rgba8Snorm
3356 | Self::Rgba8Uint
3357 | Self::Rgba8Sint
3358 | Self::Bgra8Unorm
3359 | Self::Bgra8UnormSrgb => Some(1),
3360 Self::R16Uint
3361 | Self::R16Sint
3362 | Self::R16Unorm
3363 | Self::R16Snorm
3364 | Self::R16Float
3365 | Self::Rg16Uint
3366 | Self::Rg16Sint
3367 | Self::Rg16Unorm
3368 | Self::Rg16Snorm
3369 | Self::Rg16Float
3370 | Self::Rgba16Uint
3371 | Self::Rgba16Sint
3372 | Self::Rgba16Unorm
3373 | Self::Rgba16Snorm
3374 | Self::Rgba16Float => Some(2),
3375 Self::R32Uint
3376 | Self::R32Sint
3377 | Self::R32Float
3378 | Self::R64Uint
3379 | Self::Rg32Uint
3380 | Self::Rg32Sint
3381 | Self::Rg32Float
3382 | Self::Rgba32Uint
3383 | Self::Rgba32Sint
3384 | Self::Rgba32Float
3385 | Self::Rgb10a2Uint
3386 | Self::Rgb10a2Unorm
3387 | Self::Rg11b10Ufloat => Some(4),
3388 Self::Stencil8
3389 | Self::Depth16Unorm
3390 | Self::Depth24Plus
3391 | Self::Depth24PlusStencil8
3392 | Self::Depth32Float
3393 | Self::Depth32FloatStencil8
3394 | Self::NV12
3395 | Self::Rgb9e5Ufloat
3396 | Self::Bc1RgbaUnorm
3397 | Self::Bc1RgbaUnormSrgb
3398 | Self::Bc2RgbaUnorm
3399 | Self::Bc2RgbaUnormSrgb
3400 | Self::Bc3RgbaUnorm
3401 | Self::Bc3RgbaUnormSrgb
3402 | Self::Bc4RUnorm
3403 | Self::Bc4RSnorm
3404 | Self::Bc5RgUnorm
3405 | Self::Bc5RgSnorm
3406 | Self::Bc6hRgbUfloat
3407 | Self::Bc6hRgbFloat
3408 | Self::Bc7RgbaUnorm
3409 | Self::Bc7RgbaUnormSrgb
3410 | Self::Etc2Rgb8Unorm
3411 | Self::Etc2Rgb8UnormSrgb
3412 | Self::Etc2Rgb8A1Unorm
3413 | Self::Etc2Rgb8A1UnormSrgb
3414 | Self::Etc2Rgba8Unorm
3415 | Self::Etc2Rgba8UnormSrgb
3416 | Self::EacR11Unorm
3417 | Self::EacR11Snorm
3418 | Self::EacRg11Unorm
3419 | Self::EacRg11Snorm
3420 | Self::Astc { .. } => None,
3421 }
3422 }
3423
3424 /// Returns the number of components this format has.
3425 #[must_use]
3426 pub fn components(&self) -> u8 {
3427 self.components_with_aspect(TextureAspect::All)
3428 }
3429
3430 /// Returns the number of components this format has taking into account the `aspect`.
3431 ///
3432 /// The `aspect` is only relevant for combined depth-stencil formats and multi-planar formats.
3433 #[must_use]
3434 pub fn components_with_aspect(&self, aspect: TextureAspect) -> u8 {
3435 match *self {
3436 Self::R8Unorm
3437 | Self::R8Snorm
3438 | Self::R8Uint
3439 | Self::R8Sint
3440 | Self::R16Unorm
3441 | Self::R16Snorm
3442 | Self::R16Uint
3443 | Self::R16Sint
3444 | Self::R16Float
3445 | Self::R32Uint
3446 | Self::R32Sint
3447 | Self::R32Float
3448 | Self::R64Uint => 1,
3449
3450 Self::Rg8Unorm
3451 | Self::Rg8Snorm
3452 | Self::Rg8Uint
3453 | Self::Rg8Sint
3454 | Self::Rg16Unorm
3455 | Self::Rg16Snorm
3456 | Self::Rg16Uint
3457 | Self::Rg16Sint
3458 | Self::Rg16Float
3459 | Self::Rg32Uint
3460 | Self::Rg32Sint
3461 | Self::Rg32Float => 2,
3462
3463 Self::Rgba8Unorm
3464 | Self::Rgba8UnormSrgb
3465 | Self::Rgba8Snorm
3466 | Self::Rgba8Uint
3467 | Self::Rgba8Sint
3468 | Self::Bgra8Unorm
3469 | Self::Bgra8UnormSrgb
3470 | Self::Rgba16Unorm
3471 | Self::Rgba16Snorm
3472 | Self::Rgba16Uint
3473 | Self::Rgba16Sint
3474 | Self::Rgba16Float
3475 | Self::Rgba32Uint
3476 | Self::Rgba32Sint
3477 | Self::Rgba32Float => 4,
3478
3479 Self::Rgb9e5Ufloat | Self::Rg11b10Ufloat => 3,
3480 Self::Rgb10a2Uint | Self::Rgb10a2Unorm => 4,
3481
3482 Self::Stencil8 | Self::Depth16Unorm | Self::Depth24Plus | Self::Depth32Float => 1,
3483
3484 Self::Depth24PlusStencil8 | Self::Depth32FloatStencil8 => match aspect {
3485 TextureAspect::DepthOnly | TextureAspect::StencilOnly => 1,
3486 _ => 2,
3487 },
3488
3489 Self::NV12 => match aspect {
3490 TextureAspect::Plane0 => 1,
3491 TextureAspect::Plane1 => 2,
3492 _ => 3,
3493 },
3494
3495 Self::Bc4RUnorm | Self::Bc4RSnorm => 1,
3496 Self::Bc5RgUnorm | Self::Bc5RgSnorm => 2,
3497 Self::Bc6hRgbUfloat | Self::Bc6hRgbFloat => 3,
3498 Self::Bc1RgbaUnorm
3499 | Self::Bc1RgbaUnormSrgb
3500 | Self::Bc2RgbaUnorm
3501 | Self::Bc2RgbaUnormSrgb
3502 | Self::Bc3RgbaUnorm
3503 | Self::Bc3RgbaUnormSrgb
3504 | Self::Bc7RgbaUnorm
3505 | Self::Bc7RgbaUnormSrgb => 4,
3506
3507 Self::EacR11Unorm | Self::EacR11Snorm => 1,
3508 Self::EacRg11Unorm | Self::EacRg11Snorm => 2,
3509 Self::Etc2Rgb8Unorm | Self::Etc2Rgb8UnormSrgb => 3,
3510 Self::Etc2Rgb8A1Unorm
3511 | Self::Etc2Rgb8A1UnormSrgb
3512 | Self::Etc2Rgba8Unorm
3513 | Self::Etc2Rgba8UnormSrgb => 4,
3514
3515 Self::Astc { .. } => 4,
3516 }
3517 }
3518
3519 /// Strips the `Srgb` suffix from the given texture format.
3520 #[must_use]
3521 pub fn remove_srgb_suffix(&self) -> TextureFormat {
3522 match *self {
3523 Self::Rgba8UnormSrgb => Self::Rgba8Unorm,
3524 Self::Bgra8UnormSrgb => Self::Bgra8Unorm,
3525 Self::Bc1RgbaUnormSrgb => Self::Bc1RgbaUnorm,
3526 Self::Bc2RgbaUnormSrgb => Self::Bc2RgbaUnorm,
3527 Self::Bc3RgbaUnormSrgb => Self::Bc3RgbaUnorm,
3528 Self::Bc7RgbaUnormSrgb => Self::Bc7RgbaUnorm,
3529 Self::Etc2Rgb8UnormSrgb => Self::Etc2Rgb8Unorm,
3530 Self::Etc2Rgb8A1UnormSrgb => Self::Etc2Rgb8A1Unorm,
3531 Self::Etc2Rgba8UnormSrgb => Self::Etc2Rgba8Unorm,
3532 Self::Astc {
3533 block,
3534 channel: AstcChannel::UnormSrgb,
3535 } => Self::Astc {
3536 block,
3537 channel: AstcChannel::Unorm,
3538 },
3539 _ => *self,
3540 }
3541 }
3542
3543 /// Adds an `Srgb` suffix to the given texture format, if the format supports it.
3544 #[must_use]
3545 pub fn add_srgb_suffix(&self) -> TextureFormat {
3546 match *self {
3547 Self::Rgba8Unorm => Self::Rgba8UnormSrgb,
3548 Self::Bgra8Unorm => Self::Bgra8UnormSrgb,
3549 Self::Bc1RgbaUnorm => Self::Bc1RgbaUnormSrgb,
3550 Self::Bc2RgbaUnorm => Self::Bc2RgbaUnormSrgb,
3551 Self::Bc3RgbaUnorm => Self::Bc3RgbaUnormSrgb,
3552 Self::Bc7RgbaUnorm => Self::Bc7RgbaUnormSrgb,
3553 Self::Etc2Rgb8Unorm => Self::Etc2Rgb8UnormSrgb,
3554 Self::Etc2Rgb8A1Unorm => Self::Etc2Rgb8A1UnormSrgb,
3555 Self::Etc2Rgba8Unorm => Self::Etc2Rgba8UnormSrgb,
3556 Self::Astc {
3557 block,
3558 channel: AstcChannel::Unorm,
3559 } => Self::Astc {
3560 block,
3561 channel: AstcChannel::UnormSrgb,
3562 },
3563 _ => *self,
3564 }
3565 }
3566
3567 /// Returns `true` for srgb formats.
3568 #[must_use]
3569 pub fn is_srgb(&self) -> bool {
3570 *self != self.remove_srgb_suffix()
3571 }
3572
3573 /// Returns the theoretical memory footprint of a texture with the given format and dimensions.
3574 ///
3575 /// Actual memory usage may greatly exceed this value due to alignment and padding.
3576 #[must_use]
3577 pub fn theoretical_memory_footprint(&self, size: Extent3d) -> u64 {
3578 let (block_width, block_height) = self.block_dimensions();
3579
3580 let block_size = self.block_copy_size(None);
3581
3582 let approximate_block_size = match block_size {
3583 Some(size) => size,
3584 None => match self {
3585 // One f16 per pixel
3586 Self::Depth16Unorm => 2,
3587 // One u24 per pixel, padded to 4 bytes
3588 Self::Depth24Plus => 4,
3589 // One u24 per pixel, plus one u8 per pixel
3590 Self::Depth24PlusStencil8 => 4,
3591 // One f32 per pixel
3592 Self::Depth32Float => 4,
3593 // One f32 per pixel, plus one u8 per pixel, with 3 bytes intermediary padding
3594 Self::Depth32FloatStencil8 => 8,
3595 // One u8 per pixel
3596 Self::Stencil8 => 1,
3597 // Two chroma bytes per block, one luma byte per block
3598 Self::NV12 => 3,
3599 f => {
3600 log::warn!("Memory footprint for format {:?} is not implemented", f);
3601 0
3602 }
3603 },
3604 };
3605
3606 let width_blocks = size.width.div_ceil(block_width) as u64;
3607 let height_blocks = size.height.div_ceil(block_height) as u64;
3608
3609 let total_blocks = width_blocks * height_blocks * size.depth_or_array_layers as u64;
3610
3611 total_blocks * approximate_block_size as u64
3612 }
3613 }
3614
3615 #[test]
3616 fn texture_format_serialize() {
3617 use alloc::string::ToString;
3618
3619 assert_eq!(
3620 serde_json::to_string(&TextureFormat::R8Unorm).unwrap(),
3621 "\"r8unorm\"".to_string()
3622 );
3623 assert_eq!(
3624 serde_json::to_string(&TextureFormat::R8Snorm).unwrap(),
3625 "\"r8snorm\"".to_string()
3626 );
3627 assert_eq!(
3628 serde_json::to_string(&TextureFormat::R8Uint).unwrap(),
3629 "\"r8uint\"".to_string()
3630 );
3631 assert_eq!(
3632 serde_json::to_string(&TextureFormat::R8Sint).unwrap(),
3633 "\"r8sint\"".to_string()
3634 );
3635 assert_eq!(
3636 serde_json::to_string(&TextureFormat::R16Uint).unwrap(),
3637 "\"r16uint\"".to_string()
3638 );
3639 assert_eq!(
3640 serde_json::to_string(&TextureFormat::R16Sint).unwrap(),
3641 "\"r16sint\"".to_string()
3642 );
3643 assert_eq!(
3644 serde_json::to_string(&TextureFormat::R16Unorm).unwrap(),
3645 "\"r16unorm\"".to_string()
3646 );
3647 assert_eq!(
3648 serde_json::to_string(&TextureFormat::R16Snorm).unwrap(),
3649 "\"r16snorm\"".to_string()
3650 );
3651 assert_eq!(
3652 serde_json::to_string(&TextureFormat::R16Float).unwrap(),
3653 "\"r16float\"".to_string()
3654 );
3655 assert_eq!(
3656 serde_json::to_string(&TextureFormat::Rg8Unorm).unwrap(),
3657 "\"rg8unorm\"".to_string()
3658 );
3659 assert_eq!(
3660 serde_json::to_string(&TextureFormat::Rg8Snorm).unwrap(),
3661 "\"rg8snorm\"".to_string()
3662 );
3663 assert_eq!(
3664 serde_json::to_string(&TextureFormat::Rg8Uint).unwrap(),
3665 "\"rg8uint\"".to_string()
3666 );
3667 assert_eq!(
3668 serde_json::to_string(&TextureFormat::Rg8Sint).unwrap(),
3669 "\"rg8sint\"".to_string()
3670 );
3671 assert_eq!(
3672 serde_json::to_string(&TextureFormat::R32Uint).unwrap(),
3673 "\"r32uint\"".to_string()
3674 );
3675 assert_eq!(
3676 serde_json::to_string(&TextureFormat::R32Sint).unwrap(),
3677 "\"r32sint\"".to_string()
3678 );
3679 assert_eq!(
3680 serde_json::to_string(&TextureFormat::R32Float).unwrap(),
3681 "\"r32float\"".to_string()
3682 );
3683 assert_eq!(
3684 serde_json::to_string(&TextureFormat::Rg16Uint).unwrap(),
3685 "\"rg16uint\"".to_string()
3686 );
3687 assert_eq!(
3688 serde_json::to_string(&TextureFormat::Rg16Sint).unwrap(),
3689 "\"rg16sint\"".to_string()
3690 );
3691 assert_eq!(
3692 serde_json::to_string(&TextureFormat::Rg16Unorm).unwrap(),
3693 "\"rg16unorm\"".to_string()
3694 );
3695 assert_eq!(
3696 serde_json::to_string(&TextureFormat::Rg16Snorm).unwrap(),
3697 "\"rg16snorm\"".to_string()
3698 );
3699 assert_eq!(
3700 serde_json::to_string(&TextureFormat::Rg16Float).unwrap(),
3701 "\"rg16float\"".to_string()
3702 );
3703 assert_eq!(
3704 serde_json::to_string(&TextureFormat::Rgba8Unorm).unwrap(),
3705 "\"rgba8unorm\"".to_string()
3706 );
3707 assert_eq!(
3708 serde_json::to_string(&TextureFormat::Rgba8UnormSrgb).unwrap(),
3709 "\"rgba8unorm-srgb\"".to_string()
3710 );
3711 assert_eq!(
3712 serde_json::to_string(&TextureFormat::Rgba8Snorm).unwrap(),
3713 "\"rgba8snorm\"".to_string()
3714 );
3715 assert_eq!(
3716 serde_json::to_string(&TextureFormat::Rgba8Uint).unwrap(),
3717 "\"rgba8uint\"".to_string()
3718 );
3719 assert_eq!(
3720 serde_json::to_string(&TextureFormat::Rgba8Sint).unwrap(),
3721 "\"rgba8sint\"".to_string()
3722 );
3723 assert_eq!(
3724 serde_json::to_string(&TextureFormat::Bgra8Unorm).unwrap(),
3725 "\"bgra8unorm\"".to_string()
3726 );
3727 assert_eq!(
3728 serde_json::to_string(&TextureFormat::Bgra8UnormSrgb).unwrap(),
3729 "\"bgra8unorm-srgb\"".to_string()
3730 );
3731 assert_eq!(
3732 serde_json::to_string(&TextureFormat::Rgb10a2Uint).unwrap(),
3733 "\"rgb10a2uint\"".to_string()
3734 );
3735 assert_eq!(
3736 serde_json::to_string(&TextureFormat::Rgb10a2Unorm).unwrap(),
3737 "\"rgb10a2unorm\"".to_string()
3738 );
3739 assert_eq!(
3740 serde_json::to_string(&TextureFormat::Rg11b10Ufloat).unwrap(),
3741 "\"rg11b10ufloat\"".to_string()
3742 );
3743 assert_eq!(
3744 serde_json::to_string(&TextureFormat::R64Uint).unwrap(),
3745 "\"r64uint\"".to_string()
3746 );
3747 assert_eq!(
3748 serde_json::to_string(&TextureFormat::Rg32Uint).unwrap(),
3749 "\"rg32uint\"".to_string()
3750 );
3751 assert_eq!(
3752 serde_json::to_string(&TextureFormat::Rg32Sint).unwrap(),
3753 "\"rg32sint\"".to_string()
3754 );
3755 assert_eq!(
3756 serde_json::to_string(&TextureFormat::Rg32Float).unwrap(),
3757 "\"rg32float\"".to_string()
3758 );
3759 assert_eq!(
3760 serde_json::to_string(&TextureFormat::Rgba16Uint).unwrap(),
3761 "\"rgba16uint\"".to_string()
3762 );
3763 assert_eq!(
3764 serde_json::to_string(&TextureFormat::Rgba16Sint).unwrap(),
3765 "\"rgba16sint\"".to_string()
3766 );
3767 assert_eq!(
3768 serde_json::to_string(&TextureFormat::Rgba16Unorm).unwrap(),
3769 "\"rgba16unorm\"".to_string()
3770 );
3771 assert_eq!(
3772 serde_json::to_string(&TextureFormat::Rgba16Snorm).unwrap(),
3773 "\"rgba16snorm\"".to_string()
3774 );
3775 assert_eq!(
3776 serde_json::to_string(&TextureFormat::Rgba16Float).unwrap(),
3777 "\"rgba16float\"".to_string()
3778 );
3779 assert_eq!(
3780 serde_json::to_string(&TextureFormat::Rgba32Uint).unwrap(),
3781 "\"rgba32uint\"".to_string()
3782 );
3783 assert_eq!(
3784 serde_json::to_string(&TextureFormat::Rgba32Sint).unwrap(),
3785 "\"rgba32sint\"".to_string()
3786 );
3787 assert_eq!(
3788 serde_json::to_string(&TextureFormat::Rgba32Float).unwrap(),
3789 "\"rgba32float\"".to_string()
3790 );
3791 assert_eq!(
3792 serde_json::to_string(&TextureFormat::Stencil8).unwrap(),
3793 "\"stencil8\"".to_string()
3794 );
3795 assert_eq!(
3796 serde_json::to_string(&TextureFormat::Depth32Float).unwrap(),
3797 "\"depth32float\"".to_string()
3798 );
3799 assert_eq!(
3800 serde_json::to_string(&TextureFormat::Depth16Unorm).unwrap(),
3801 "\"depth16unorm\"".to_string()
3802 );
3803 assert_eq!(
3804 serde_json::to_string(&TextureFormat::Depth32FloatStencil8).unwrap(),
3805 "\"depth32float-stencil8\"".to_string()
3806 );
3807 assert_eq!(
3808 serde_json::to_string(&TextureFormat::Depth24Plus).unwrap(),
3809 "\"depth24plus\"".to_string()
3810 );
3811 assert_eq!(
3812 serde_json::to_string(&TextureFormat::Depth24PlusStencil8).unwrap(),
3813 "\"depth24plus-stencil8\"".to_string()
3814 );
3815 assert_eq!(
3816 serde_json::to_string(&TextureFormat::Rgb9e5Ufloat).unwrap(),
3817 "\"rgb9e5ufloat\"".to_string()
3818 );
3819 assert_eq!(
3820 serde_json::to_string(&TextureFormat::Bc1RgbaUnorm).unwrap(),
3821 "\"bc1-rgba-unorm\"".to_string()
3822 );
3823 assert_eq!(
3824 serde_json::to_string(&TextureFormat::Bc1RgbaUnormSrgb).unwrap(),
3825 "\"bc1-rgba-unorm-srgb\"".to_string()
3826 );
3827 assert_eq!(
3828 serde_json::to_string(&TextureFormat::Bc2RgbaUnorm).unwrap(),
3829 "\"bc2-rgba-unorm\"".to_string()
3830 );
3831 assert_eq!(
3832 serde_json::to_string(&TextureFormat::Bc2RgbaUnormSrgb).unwrap(),
3833 "\"bc2-rgba-unorm-srgb\"".to_string()
3834 );
3835 assert_eq!(
3836 serde_json::to_string(&TextureFormat::Bc3RgbaUnorm).unwrap(),
3837 "\"bc3-rgba-unorm\"".to_string()
3838 );
3839 assert_eq!(
3840 serde_json::to_string(&TextureFormat::Bc3RgbaUnormSrgb).unwrap(),
3841 "\"bc3-rgba-unorm-srgb\"".to_string()
3842 );
3843 assert_eq!(
3844 serde_json::to_string(&TextureFormat::Bc4RUnorm).unwrap(),
3845 "\"bc4-r-unorm\"".to_string()
3846 );
3847 assert_eq!(
3848 serde_json::to_string(&TextureFormat::Bc4RSnorm).unwrap(),
3849 "\"bc4-r-snorm\"".to_string()
3850 );
3851 assert_eq!(
3852 serde_json::to_string(&TextureFormat::Bc5RgUnorm).unwrap(),
3853 "\"bc5-rg-unorm\"".to_string()
3854 );
3855 assert_eq!(
3856 serde_json::to_string(&TextureFormat::Bc5RgSnorm).unwrap(),
3857 "\"bc5-rg-snorm\"".to_string()
3858 );
3859 assert_eq!(
3860 serde_json::to_string(&TextureFormat::Bc6hRgbUfloat).unwrap(),
3861 "\"bc6h-rgb-ufloat\"".to_string()
3862 );
3863 assert_eq!(
3864 serde_json::to_string(&TextureFormat::Bc6hRgbFloat).unwrap(),
3865 "\"bc6h-rgb-float\"".to_string()
3866 );
3867 assert_eq!(
3868 serde_json::to_string(&TextureFormat::Bc7RgbaUnorm).unwrap(),
3869 "\"bc7-rgba-unorm\"".to_string()
3870 );
3871 assert_eq!(
3872 serde_json::to_string(&TextureFormat::Bc7RgbaUnormSrgb).unwrap(),
3873 "\"bc7-rgba-unorm-srgb\"".to_string()
3874 );
3875 assert_eq!(
3876 serde_json::to_string(&TextureFormat::Etc2Rgb8Unorm).unwrap(),
3877 "\"etc2-rgb8unorm\"".to_string()
3878 );
3879 assert_eq!(
3880 serde_json::to_string(&TextureFormat::Etc2Rgb8UnormSrgb).unwrap(),
3881 "\"etc2-rgb8unorm-srgb\"".to_string()
3882 );
3883 assert_eq!(
3884 serde_json::to_string(&TextureFormat::Etc2Rgb8A1Unorm).unwrap(),
3885 "\"etc2-rgb8a1unorm\"".to_string()
3886 );
3887 assert_eq!(
3888 serde_json::to_string(&TextureFormat::Etc2Rgb8A1UnormSrgb).unwrap(),
3889 "\"etc2-rgb8a1unorm-srgb\"".to_string()
3890 );
3891 assert_eq!(
3892 serde_json::to_string(&TextureFormat::Etc2Rgba8Unorm).unwrap(),
3893 "\"etc2-rgba8unorm\"".to_string()
3894 );
3895 assert_eq!(
3896 serde_json::to_string(&TextureFormat::Etc2Rgba8UnormSrgb).unwrap(),
3897 "\"etc2-rgba8unorm-srgb\"".to_string()
3898 );
3899 assert_eq!(
3900 serde_json::to_string(&TextureFormat::EacR11Unorm).unwrap(),
3901 "\"eac-r11unorm\"".to_string()
3902 );
3903 assert_eq!(
3904 serde_json::to_string(&TextureFormat::EacR11Snorm).unwrap(),
3905 "\"eac-r11snorm\"".to_string()
3906 );
3907 assert_eq!(
3908 serde_json::to_string(&TextureFormat::EacRg11Unorm).unwrap(),
3909 "\"eac-rg11unorm\"".to_string()
3910 );
3911 assert_eq!(
3912 serde_json::to_string(&TextureFormat::EacRg11Snorm).unwrap(),
3913 "\"eac-rg11snorm\"".to_string()
3914 );
3915 }
3916
3917 #[test]
3918 fn texture_format_deserialize() {
3919 assert_eq!(
3920 serde_json::from_str::<TextureFormat>("\"r8unorm\"").unwrap(),
3921 TextureFormat::R8Unorm
3922 );
3923 assert_eq!(
3924 serde_json::from_str::<TextureFormat>("\"r8snorm\"").unwrap(),
3925 TextureFormat::R8Snorm
3926 );
3927 assert_eq!(
3928 serde_json::from_str::<TextureFormat>("\"r8uint\"").unwrap(),
3929 TextureFormat::R8Uint
3930 );
3931 assert_eq!(
3932 serde_json::from_str::<TextureFormat>("\"r8sint\"").unwrap(),
3933 TextureFormat::R8Sint
3934 );
3935 assert_eq!(
3936 serde_json::from_str::<TextureFormat>("\"r16uint\"").unwrap(),
3937 TextureFormat::R16Uint
3938 );
3939 assert_eq!(
3940 serde_json::from_str::<TextureFormat>("\"r16sint\"").unwrap(),
3941 TextureFormat::R16Sint
3942 );
3943 assert_eq!(
3944 serde_json::from_str::<TextureFormat>("\"r16unorm\"").unwrap(),
3945 TextureFormat::R16Unorm
3946 );
3947 assert_eq!(
3948 serde_json::from_str::<TextureFormat>("\"r16snorm\"").unwrap(),
3949 TextureFormat::R16Snorm
3950 );
3951 assert_eq!(
3952 serde_json::from_str::<TextureFormat>("\"r16float\"").unwrap(),
3953 TextureFormat::R16Float
3954 );
3955 assert_eq!(
3956 serde_json::from_str::<TextureFormat>("\"rg8unorm\"").unwrap(),
3957 TextureFormat::Rg8Unorm
3958 );
3959 assert_eq!(
3960 serde_json::from_str::<TextureFormat>("\"rg8snorm\"").unwrap(),
3961 TextureFormat::Rg8Snorm
3962 );
3963 assert_eq!(
3964 serde_json::from_str::<TextureFormat>("\"rg8uint\"").unwrap(),
3965 TextureFormat::Rg8Uint
3966 );
3967 assert_eq!(
3968 serde_json::from_str::<TextureFormat>("\"rg8sint\"").unwrap(),
3969 TextureFormat::Rg8Sint
3970 );
3971 assert_eq!(
3972 serde_json::from_str::<TextureFormat>("\"r32uint\"").unwrap(),
3973 TextureFormat::R32Uint
3974 );
3975 assert_eq!(
3976 serde_json::from_str::<TextureFormat>("\"r32sint\"").unwrap(),
3977 TextureFormat::R32Sint
3978 );
3979 assert_eq!(
3980 serde_json::from_str::<TextureFormat>("\"r32float\"").unwrap(),
3981 TextureFormat::R32Float
3982 );
3983 assert_eq!(
3984 serde_json::from_str::<TextureFormat>("\"rg16uint\"").unwrap(),
3985 TextureFormat::Rg16Uint
3986 );
3987 assert_eq!(
3988 serde_json::from_str::<TextureFormat>("\"rg16sint\"").unwrap(),
3989 TextureFormat::Rg16Sint
3990 );
3991 assert_eq!(
3992 serde_json::from_str::<TextureFormat>("\"rg16unorm\"").unwrap(),
3993 TextureFormat::Rg16Unorm
3994 );
3995 assert_eq!(
3996 serde_json::from_str::<TextureFormat>("\"rg16snorm\"").unwrap(),
3997 TextureFormat::Rg16Snorm
3998 );
3999 assert_eq!(
4000 serde_json::from_str::<TextureFormat>("\"rg16float\"").unwrap(),
4001 TextureFormat::Rg16Float
4002 );
4003 assert_eq!(
4004 serde_json::from_str::<TextureFormat>("\"rgba8unorm\"").unwrap(),
4005 TextureFormat::Rgba8Unorm
4006 );
4007 assert_eq!(
4008 serde_json::from_str::<TextureFormat>("\"rgba8unorm-srgb\"").unwrap(),
4009 TextureFormat::Rgba8UnormSrgb
4010 );
4011 assert_eq!(
4012 serde_json::from_str::<TextureFormat>("\"rgba8snorm\"").unwrap(),
4013 TextureFormat::Rgba8Snorm
4014 );
4015 assert_eq!(
4016 serde_json::from_str::<TextureFormat>("\"rgba8uint\"").unwrap(),
4017 TextureFormat::Rgba8Uint
4018 );
4019 assert_eq!(
4020 serde_json::from_str::<TextureFormat>("\"rgba8sint\"").unwrap(),
4021 TextureFormat::Rgba8Sint
4022 );
4023 assert_eq!(
4024 serde_json::from_str::<TextureFormat>("\"bgra8unorm\"").unwrap(),
4025 TextureFormat::Bgra8Unorm
4026 );
4027 assert_eq!(
4028 serde_json::from_str::<TextureFormat>("\"bgra8unorm-srgb\"").unwrap(),
4029 TextureFormat::Bgra8UnormSrgb
4030 );
4031 assert_eq!(
4032 serde_json::from_str::<TextureFormat>("\"rgb10a2uint\"").unwrap(),
4033 TextureFormat::Rgb10a2Uint
4034 );
4035 assert_eq!(
4036 serde_json::from_str::<TextureFormat>("\"rgb10a2unorm\"").unwrap(),
4037 TextureFormat::Rgb10a2Unorm
4038 );
4039 assert_eq!(
4040 serde_json::from_str::<TextureFormat>("\"rg11b10ufloat\"").unwrap(),
4041 TextureFormat::Rg11b10Ufloat
4042 );
4043 assert_eq!(
4044 serde_json::from_str::<TextureFormat>("\"r64uint\"").unwrap(),
4045 TextureFormat::R64Uint
4046 );
4047 assert_eq!(
4048 serde_json::from_str::<TextureFormat>("\"rg32uint\"").unwrap(),
4049 TextureFormat::Rg32Uint
4050 );
4051 assert_eq!(
4052 serde_json::from_str::<TextureFormat>("\"rg32sint\"").unwrap(),
4053 TextureFormat::Rg32Sint
4054 );
4055 assert_eq!(
4056 serde_json::from_str::<TextureFormat>("\"rg32float\"").unwrap(),
4057 TextureFormat::Rg32Float
4058 );
4059 assert_eq!(
4060 serde_json::from_str::<TextureFormat>("\"rgba16uint\"").unwrap(),
4061 TextureFormat::Rgba16Uint
4062 );
4063 assert_eq!(
4064 serde_json::from_str::<TextureFormat>("\"rgba16sint\"").unwrap(),
4065 TextureFormat::Rgba16Sint
4066 );
4067 assert_eq!(
4068 serde_json::from_str::<TextureFormat>("\"rgba16unorm\"").unwrap(),
4069 TextureFormat::Rgba16Unorm
4070 );
4071 assert_eq!(
4072 serde_json::from_str::<TextureFormat>("\"rgba16snorm\"").unwrap(),
4073 TextureFormat::Rgba16Snorm
4074 );
4075 assert_eq!(
4076 serde_json::from_str::<TextureFormat>("\"rgba16float\"").unwrap(),
4077 TextureFormat::Rgba16Float
4078 );
4079 assert_eq!(
4080 serde_json::from_str::<TextureFormat>("\"rgba32uint\"").unwrap(),
4081 TextureFormat::Rgba32Uint
4082 );
4083 assert_eq!(
4084 serde_json::from_str::<TextureFormat>("\"rgba32sint\"").unwrap(),
4085 TextureFormat::Rgba32Sint
4086 );
4087 assert_eq!(
4088 serde_json::from_str::<TextureFormat>("\"rgba32float\"").unwrap(),
4089 TextureFormat::Rgba32Float
4090 );
4091 assert_eq!(
4092 serde_json::from_str::<TextureFormat>("\"stencil8\"").unwrap(),
4093 TextureFormat::Stencil8
4094 );
4095 assert_eq!(
4096 serde_json::from_str::<TextureFormat>("\"depth32float\"").unwrap(),
4097 TextureFormat::Depth32Float
4098 );
4099 assert_eq!(
4100 serde_json::from_str::<TextureFormat>("\"depth16unorm\"").unwrap(),
4101 TextureFormat::Depth16Unorm
4102 );
4103 assert_eq!(
4104 serde_json::from_str::<TextureFormat>("\"depth32float-stencil8\"").unwrap(),
4105 TextureFormat::Depth32FloatStencil8
4106 );
4107 assert_eq!(
4108 serde_json::from_str::<TextureFormat>("\"depth24plus\"").unwrap(),
4109 TextureFormat::Depth24Plus
4110 );
4111 assert_eq!(
4112 serde_json::from_str::<TextureFormat>("\"depth24plus-stencil8\"").unwrap(),
4113 TextureFormat::Depth24PlusStencil8
4114 );
4115 assert_eq!(
4116 serde_json::from_str::<TextureFormat>("\"rgb9e5ufloat\"").unwrap(),
4117 TextureFormat::Rgb9e5Ufloat
4118 );
4119 assert_eq!(
4120 serde_json::from_str::<TextureFormat>("\"bc1-rgba-unorm\"").unwrap(),
4121 TextureFormat::Bc1RgbaUnorm
4122 );
4123 assert_eq!(
4124 serde_json::from_str::<TextureFormat>("\"bc1-rgba-unorm-srgb\"").unwrap(),
4125 TextureFormat::Bc1RgbaUnormSrgb
4126 );
4127 assert_eq!(
4128 serde_json::from_str::<TextureFormat>("\"bc2-rgba-unorm\"").unwrap(),
4129 TextureFormat::Bc2RgbaUnorm
4130 );
4131 assert_eq!(
4132 serde_json::from_str::<TextureFormat>("\"bc2-rgba-unorm-srgb\"").unwrap(),
4133 TextureFormat::Bc2RgbaUnormSrgb
4134 );
4135 assert_eq!(
4136 serde_json::from_str::<TextureFormat>("\"bc3-rgba-unorm\"").unwrap(),
4137 TextureFormat::Bc3RgbaUnorm
4138 );
4139 assert_eq!(
4140 serde_json::from_str::<TextureFormat>("\"bc3-rgba-unorm-srgb\"").unwrap(),
4141 TextureFormat::Bc3RgbaUnormSrgb
4142 );
4143 assert_eq!(
4144 serde_json::from_str::<TextureFormat>("\"bc4-r-unorm\"").unwrap(),
4145 TextureFormat::Bc4RUnorm
4146 );
4147 assert_eq!(
4148 serde_json::from_str::<TextureFormat>("\"bc4-r-snorm\"").unwrap(),
4149 TextureFormat::Bc4RSnorm
4150 );
4151 assert_eq!(
4152 serde_json::from_str::<TextureFormat>("\"bc5-rg-unorm\"").unwrap(),
4153 TextureFormat::Bc5RgUnorm
4154 );
4155 assert_eq!(
4156 serde_json::from_str::<TextureFormat>("\"bc5-rg-snorm\"").unwrap(),
4157 TextureFormat::Bc5RgSnorm
4158 );
4159 assert_eq!(
4160 serde_json::from_str::<TextureFormat>("\"bc6h-rgb-ufloat\"").unwrap(),
4161 TextureFormat::Bc6hRgbUfloat
4162 );
4163 assert_eq!(
4164 serde_json::from_str::<TextureFormat>("\"bc6h-rgb-float\"").unwrap(),
4165 TextureFormat::Bc6hRgbFloat
4166 );
4167 assert_eq!(
4168 serde_json::from_str::<TextureFormat>("\"bc7-rgba-unorm\"").unwrap(),
4169 TextureFormat::Bc7RgbaUnorm
4170 );
4171 assert_eq!(
4172 serde_json::from_str::<TextureFormat>("\"bc7-rgba-unorm-srgb\"").unwrap(),
4173 TextureFormat::Bc7RgbaUnormSrgb
4174 );
4175 assert_eq!(
4176 serde_json::from_str::<TextureFormat>("\"etc2-rgb8unorm\"").unwrap(),
4177 TextureFormat::Etc2Rgb8Unorm
4178 );
4179 assert_eq!(
4180 serde_json::from_str::<TextureFormat>("\"etc2-rgb8unorm-srgb\"").unwrap(),
4181 TextureFormat::Etc2Rgb8UnormSrgb
4182 );
4183 assert_eq!(
4184 serde_json::from_str::<TextureFormat>("\"etc2-rgb8a1unorm\"").unwrap(),
4185 TextureFormat::Etc2Rgb8A1Unorm
4186 );
4187 assert_eq!(
4188 serde_json::from_str::<TextureFormat>("\"etc2-rgb8a1unorm-srgb\"").unwrap(),
4189 TextureFormat::Etc2Rgb8A1UnormSrgb
4190 );
4191 assert_eq!(
4192 serde_json::from_str::<TextureFormat>("\"etc2-rgba8unorm\"").unwrap(),
4193 TextureFormat::Etc2Rgba8Unorm
4194 );
4195 assert_eq!(
4196 serde_json::from_str::<TextureFormat>("\"etc2-rgba8unorm-srgb\"").unwrap(),
4197 TextureFormat::Etc2Rgba8UnormSrgb
4198 );
4199 assert_eq!(
4200 serde_json::from_str::<TextureFormat>("\"eac-r11unorm\"").unwrap(),
4201 TextureFormat::EacR11Unorm
4202 );
4203 assert_eq!(
4204 serde_json::from_str::<TextureFormat>("\"eac-r11snorm\"").unwrap(),
4205 TextureFormat::EacR11Snorm
4206 );
4207 assert_eq!(
4208 serde_json::from_str::<TextureFormat>("\"eac-rg11unorm\"").unwrap(),
4209 TextureFormat::EacRg11Unorm
4210 );
4211 assert_eq!(
4212 serde_json::from_str::<TextureFormat>("\"eac-rg11snorm\"").unwrap(),
4213 TextureFormat::EacRg11Snorm
4214 );
4215 }
4216
4217 /// Color write mask. Disabled color channels will not be written to.
4218 ///
4219 /// Corresponds to [WebGPU `GPUColorWriteFlags`](
4220 /// https://gpuweb.github.io/gpuweb/#typedefdef-gpucolorwriteflags).
4221 #[repr(transparent)]
4222 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4223 #[cfg_attr(feature = "serde", serde(transparent))]
4224 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
4225 pub struct ColorWrites(u32);
4226
4227 bitflags::bitflags! {
4228 impl ColorWrites: u32 {
4229 /// Enable red channel writes
4230 const RED = 1 << 0;
4231 /// Enable green channel writes
4232 const GREEN = 1 << 1;
4233 /// Enable blue channel writes
4234 const BLUE = 1 << 2;
4235 /// Enable alpha channel writes
4236 const ALPHA = 1 << 3;
4237 /// Enable red, green, and blue channel writes
4238 const COLOR = Self::RED.bits() | Self::GREEN.bits() | Self::BLUE.bits();
4239 /// Enable writes to all channels.
4240 const ALL = Self::RED.bits() | Self::GREEN.bits() | Self::BLUE.bits() | Self::ALPHA.bits();
4241 }
4242 }
4243
4244 impl Default for ColorWrites {
4245 fn default() -> Self {
4246 Self::ALL
4247 }
4248 }
4249
4250 /// Passed to `Device::poll` to control how and if it should block.
4251 #[derive(Clone, Debug)]
4252 pub enum PollType<T> {
4253 /// On wgpu-core based backends, block until the given submission has
4254 /// completed execution, and any callbacks have been invoked.
4255 ///
4256 /// On WebGPU, this has no effect. Callbacks are invoked from the
4257 /// window event loop.
4258 WaitForSubmissionIndex(T),
4259 /// Same as `WaitForSubmissionIndex` but waits for the most recent submission.
4260 Wait,
4261 /// Check the device for a single time without blocking.
4262 Poll,
4263 }
4264
4265 impl<T> PollType<T> {
4266 /// Construct a [`Self::Wait`] variant
4267 #[must_use]
4268 pub fn wait() -> Self {
4269 // This function seems a little silly, but it is useful to allow
4270 // <https://github.com/gfx-rs/wgpu/pull/5012> to be split up, as
4271 // it has meaning in that PR.
4272 Self::Wait
4273 }
4274
4275 /// Construct a [`Self::WaitForSubmissionIndex`] variant
4276 #[must_use]
4277 pub fn wait_for(submission_index: T) -> Self {
4278 // This function seems a little silly, but it is useful to allow
4279 // <https://github.com/gfx-rs/wgpu/pull/5012> to be split up, as
4280 // it has meaning in that PR.
4281 Self::WaitForSubmissionIndex(submission_index)
4282 }
4283
4284 /// This `PollType` represents a wait of some kind.
4285 #[must_use]
4286 pub fn is_wait(&self) -> bool {
4287 match *self {
4288 Self::WaitForSubmissionIndex(..) | Self::Wait => true,
4289 Self::Poll => false,
4290 }
4291 }
4292
4293 /// Map on the wait index type.
4294 #[must_use]
4295 pub fn map_index<U, F>(self, func: F) -> PollType<U>
4296 where
4297 F: FnOnce(T) -> U,
4298 {
4299 match self {
4300 Self::WaitForSubmissionIndex(i) => PollType::WaitForSubmissionIndex(func(i)),
4301 Self::Wait => PollType::Wait,
4302 Self::Poll => PollType::Poll,
4303 }
4304 }
4305 }
4306
4307 /// Error states after a device poll
4308 #[derive(Debug)]
4309 #[cfg_attr(feature = "std", derive(thiserror::Error))]
4310 pub enum PollError {
4311 /// The requested Wait timed out before the submission was completed.
4312 #[cfg_attr(
4313 feature = "std",
4314 error("The requested Wait timed out before the submission was completed.")
4315 )]
4316 Timeout,
4317 }
4318
4319 /// Status of device poll operation.
4320 #[derive(Debug, PartialEq, Eq)]
4321 pub enum PollStatus {
4322 /// There are no active submissions in flight as of the beginning of the poll call.
4323 /// Other submissions may have been queued on other threads during the call.
4324 ///
4325 /// This implies that the given Wait was satisfied before the timeout.
4326 QueueEmpty,
4327
4328 /// The requested Wait was satisfied before the timeout.
4329 WaitSucceeded,
4330
4331 /// This was a poll.
4332 Poll,
4333 }
4334
4335 impl PollStatus {
4336 /// Returns true if the result is [`Self::QueueEmpty`].
4337 #[must_use]
4338 pub fn is_queue_empty(&self) -> bool {
4339 matches!(self, Self::QueueEmpty)
4340 }
4341
4342 /// Returns true if the result is either [`Self::WaitSucceeded`] or [`Self::QueueEmpty`].
4343 #[must_use]
4344 pub fn wait_finished(&self) -> bool {
4345 matches!(self, Self::WaitSucceeded | Self::QueueEmpty)
4346 }
4347 }
4348
4349 /// State of the stencil operation (fixed-pipeline stage).
4350 ///
4351 /// For use in [`DepthStencilState`].
4352 ///
4353 /// Corresponds to a portion of [WebGPU `GPUDepthStencilState`](
4354 /// https://gpuweb.github.io/gpuweb/#dictdef-gpudepthstencilstate).
4355 #[repr(C)]
4356 #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
4357 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4358 pub struct StencilState {
4359 /// Front face mode.
4360 pub front: StencilFaceState,
4361 /// Back face mode.
4362 pub back: StencilFaceState,
4363 /// Stencil values are AND'd with this mask when reading and writing from the stencil buffer. Only low 8 bits are used.
4364 pub read_mask: u32,
4365 /// Stencil values are AND'd with this mask when writing to the stencil buffer. Only low 8 bits are used.
4366 pub write_mask: u32,
4367 }
4368
4369 impl StencilState {
4370 /// Returns true if the stencil test is enabled.
4371 #[must_use]
4372 pub fn is_enabled(&self) -> bool {
4373 (self.front != StencilFaceState::IGNORE || self.back != StencilFaceState::IGNORE)
4374 && (self.read_mask != 0 || self.write_mask != 0)
4375 }
4376 /// Returns true if the state doesn't mutate the target values.
4377 #[must_use]
4378 pub fn is_read_only(&self, cull_mode: Option<Face>) -> bool {
4379 // The rules are defined in step 7 of the "Device timeline initialization steps"
4380 // subsection of the "Render Pipeline Creation" section of WebGPU
4381 // (link to the section: https://gpuweb.github.io/gpuweb/#render-pipeline-creation)
4382
4383 if self.write_mask == 0 {
4384 return true;
4385 }
4386
4387 let front_ro = cull_mode == Some(Face::Front) || self.front.is_read_only();
4388 let back_ro = cull_mode == Some(Face::Back) || self.back.is_read_only();
4389
4390 front_ro && back_ro
4391 }
4392 /// Returns true if the stencil state uses the reference value for testing.
4393 #[must_use]
4394 pub fn needs_ref_value(&self) -> bool {
4395 self.front.needs_ref_value() || self.back.needs_ref_value()
4396 }
4397 }
4398
4399 /// Describes the biasing setting for the depth target.
4400 ///
4401 /// For use in [`DepthStencilState`].
4402 ///
4403 /// Corresponds to a portion of [WebGPU `GPUDepthStencilState`](
4404 /// https://gpuweb.github.io/gpuweb/#dictdef-gpudepthstencilstate).
4405 #[repr(C)]
4406 #[derive(Clone, Copy, Debug, Default)]
4407 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4408 pub struct DepthBiasState {
4409 /// Constant depth biasing factor, in basic units of the depth format.
4410 pub constant: i32,
4411 /// Slope depth biasing factor.
4412 pub slope_scale: f32,
4413 /// Depth bias clamp value (absolute).
4414 pub clamp: f32,
4415 }
4416
4417 impl DepthBiasState {
4418 /// Returns true if the depth biasing is enabled.
4419 #[must_use]
4420 pub fn is_enabled(&self) -> bool {
4421 self.constant != 0 || self.slope_scale != 0.0
4422 }
4423 }
4424
4425 impl Hash for DepthBiasState {
4426 fn hash<H: Hasher>(&self, state: &mut H) {
4427 self.constant.hash(state);
4428 self.slope_scale.to_bits().hash(state);
4429 self.clamp.to_bits().hash(state);
4430 }
4431 }
4432
4433 impl PartialEq for DepthBiasState {
4434 fn eq(&self, other: &Self) -> bool {
4435 (self.constant == other.constant)
4436 && (self.slope_scale.to_bits() == other.slope_scale.to_bits())
4437 && (self.clamp.to_bits() == other.clamp.to_bits())
4438 }
4439 }
4440
4441 impl Eq for DepthBiasState {}
4442
4443 /// Operation to perform to the output attachment at the start of a render pass.
4444 ///
4445 /// Corresponds to [WebGPU `GPULoadOp`](https://gpuweb.github.io/gpuweb/#enumdef-gpuloadop),
4446 /// plus the corresponding clearValue.
4447 #[repr(u8)]
4448 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
4449 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
4450 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
4451 pub enum LoadOp<V> {
4452 /// Loads the specified value for this attachment into the render pass.
4453 ///
4454 /// On some GPU hardware (primarily mobile), "clear" is significantly cheaper
4455 /// because it avoids loading data from main memory into tile-local memory.
4456 ///
4457 /// On other GPU hardware, there isn’t a significant difference.
4458 ///
4459 /// As a result, it is recommended to use "clear" rather than "load" in cases
4460 /// where the initial value doesn’t matter
4461 /// (e.g. the render target will be cleared using a skybox).
4462 Clear(V) = 0,
4463 /// Loads the existing value for this attachment into the render pass.
4464 Load = 1,
4465 }
4466
4467 impl<V> LoadOp<V> {
4468 /// Returns true if variants are same (ignoring clear value)
4469 pub fn eq_variant<T>(&self, other: LoadOp<T>) -> bool {
4470 matches!(
4471 (self, other),
4472 (LoadOp::Clear(_), LoadOp::Clear(_)) | (LoadOp::Load, LoadOp::Load)
4473 )
4474 }
4475 }
4476
4477 impl<V: Default> Default for LoadOp<V> {
4478 fn default() -> Self {
4479 Self::Clear(Default::default())
4480 }
4481 }
4482
4483 /// Operation to perform to the output attachment at the end of a render pass.
4484 ///
4485 /// Corresponds to [WebGPU `GPUStoreOp`](https://gpuweb.github.io/gpuweb/#enumdef-gpustoreop).
4486 #[repr(C)]
4487 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Default)]
4488 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
4489 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
4490 pub enum StoreOp {
4491 /// Stores the resulting value of the render pass for this attachment.
4492 #[default]
4493 Store = 0,
4494 /// Discards the resulting value of the render pass for this attachment.
4495 ///
4496 /// The attachment will be treated as uninitialized afterwards.
4497 /// (If only either Depth or Stencil texture-aspects is set to `Discard`,
4498 /// the respective other texture-aspect will be preserved.)
4499 ///
4500 /// This can be significantly faster on tile-based render hardware.
4501 ///
4502 /// Prefer this if the attachment is not read by subsequent passes.
4503 Discard = 1,
4504 }
4505
4506 /// Pair of load and store operations for an attachment aspect.
4507 ///
4508 /// This type is unique to the Rust API of `wgpu`. In the WebGPU specification,
4509 /// separate `loadOp` and `storeOp` fields are used instead.
4510 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
4511 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
4512 pub struct Operations<V> {
4513 /// How data should be read through this attachment.
4514 pub load: LoadOp<V>,
4515 /// Whether data will be written to through this attachment.
4516 ///
4517 /// Note that resolve textures (if specified) are always written to,
4518 /// regardless of this setting.
4519 pub store: StoreOp,
4520 }
4521
4522 impl<V: Default> Default for Operations<V> {
4523 #[inline]
4524 fn default() -> Self {
4525 Self {
4526 load: LoadOp::<V>::default(),
4527 store: StoreOp::default(),
4528 }
4529 }
4530 }
4531
4532 /// Describes the depth/stencil state in a render pipeline.
4533 ///
4534 /// Corresponds to [WebGPU `GPUDepthStencilState`](
4535 /// https://gpuweb.github.io/gpuweb/#dictdef-gpudepthstencilstate).
4536 #[repr(C)]
4537 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
4538 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4539 pub struct DepthStencilState {
4540 /// Format of the depth/stencil buffer, must be special depth format. Must match the format
4541 /// of the depth/stencil attachment in [`CommandEncoder::begin_render_pass`][CEbrp].
4542 ///
4543 /// [CEbrp]: ../wgpu/struct.CommandEncoder.html#method.begin_render_pass
4544 pub format: TextureFormat,
4545 /// If disabled, depth will not be written to.
4546 pub depth_write_enabled: bool,
4547 /// Comparison function used to compare depth values in the depth test.
4548 pub depth_compare: CompareFunction,
4549 /// Stencil state.
4550 #[cfg_attr(feature = "serde", serde(default))]
4551 pub stencil: StencilState,
4552 /// Depth bias state.
4553 #[cfg_attr(feature = "serde", serde(default))]
4554 pub bias: DepthBiasState,
4555 }
4556
4557 impl DepthStencilState {
4558 /// Returns true if the depth testing is enabled.
4559 #[must_use]
4560 pub fn is_depth_enabled(&self) -> bool {
4561 self.depth_compare != CompareFunction::Always || self.depth_write_enabled
4562 }
4563
4564 /// Returns true if the state doesn't mutate the depth buffer.
4565 #[must_use]
4566 pub fn is_depth_read_only(&self) -> bool {
4567 !self.depth_write_enabled
4568 }
4569
4570 /// Returns true if the state doesn't mutate the stencil.
4571 #[must_use]
4572 pub fn is_stencil_read_only(&self, cull_mode: Option<Face>) -> bool {
4573 self.stencil.is_read_only(cull_mode)
4574 }
4575
4576 /// Returns true if the state doesn't mutate either depth or stencil of the target.
4577 #[must_use]
4578 pub fn is_read_only(&self, cull_mode: Option<Face>) -> bool {
4579 self.is_depth_read_only() && self.is_stencil_read_only(cull_mode)
4580 }
4581 }
4582
4583 /// Format of indices used with pipeline.
4584 ///
4585 /// Corresponds to [WebGPU `GPUIndexFormat`](
4586 /// https://gpuweb.github.io/gpuweb/#enumdef-gpuindexformat).
4587 #[repr(C)]
4588 #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
4589 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4590 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
4591 pub enum IndexFormat {
4592 /// Indices are 16 bit unsigned integers.
4593 Uint16 = 0,
4594 /// Indices are 32 bit unsigned integers.
4595 #[default]
4596 Uint32 = 1,
4597 }
4598
4599 impl IndexFormat {
4600 /// Returns the size in bytes of the index format
4601 pub fn byte_size(&self) -> usize {
4602 match self {
4603 IndexFormat::Uint16 => 2,
4604 IndexFormat::Uint32 => 4,
4605 }
4606 }
4607 }
4608
4609 /// Operation to perform on the stencil value.
4610 ///
4611 /// Corresponds to [WebGPU `GPUStencilOperation`](
4612 /// https://gpuweb.github.io/gpuweb/#enumdef-gpustenciloperation).
4613 #[repr(C)]
4614 #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
4615 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4616 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
4617 pub enum StencilOperation {
4618 /// Keep stencil value unchanged.
4619 #[default]
4620 Keep = 0,
4621 /// Set stencil value to zero.
4622 Zero = 1,
4623 /// Replace stencil value with value provided in most recent call to
4624 /// [`RenderPass::set_stencil_reference`][RPssr].
4625 ///
4626 /// [RPssr]: ../wgpu/struct.RenderPass.html#method.set_stencil_reference
4627 Replace = 2,
4628 /// Bitwise inverts stencil value.
4629 Invert = 3,
4630 /// Increments stencil value by one, clamping on overflow.
4631 IncrementClamp = 4,
4632 /// Decrements stencil value by one, clamping on underflow.
4633 DecrementClamp = 5,
4634 /// Increments stencil value by one, wrapping on overflow.
4635 IncrementWrap = 6,
4636 /// Decrements stencil value by one, wrapping on underflow.
4637 DecrementWrap = 7,
4638 }
4639
4640 /// Describes stencil state in a render pipeline.
4641 ///
4642 /// If you are not using stencil state, set this to [`StencilFaceState::IGNORE`].
4643 ///
4644 /// Corresponds to [WebGPU `GPUStencilFaceState`](
4645 /// https://gpuweb.github.io/gpuweb/#dictdef-gpustencilfacestate).
4646 #[repr(C)]
4647 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4648 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4649 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
4650 pub struct StencilFaceState {
4651 /// Comparison function that determines if the fail_op or pass_op is used on the stencil buffer.
4652 pub compare: CompareFunction,
4653 /// Operation that is performed when stencil test fails.
4654 pub fail_op: StencilOperation,
4655 /// Operation that is performed when depth test fails but stencil test succeeds.
4656 pub depth_fail_op: StencilOperation,
4657 /// Operation that is performed when stencil test success.
4658 pub pass_op: StencilOperation,
4659 }
4660
4661 impl StencilFaceState {
4662 /// Ignore the stencil state for the face.
4663 pub const IGNORE: Self = StencilFaceState {
4664 compare: CompareFunction::Always,
4665 fail_op: StencilOperation::Keep,
4666 depth_fail_op: StencilOperation::Keep,
4667 pass_op: StencilOperation::Keep,
4668 };
4669
4670 /// Returns true if the face state uses the reference value for testing or operation.
4671 #[must_use]
4672 pub fn needs_ref_value(&self) -> bool {
4673 self.compare.needs_ref_value()
4674 || self.fail_op == StencilOperation::Replace
4675 || self.depth_fail_op == StencilOperation::Replace
4676 || self.pass_op == StencilOperation::Replace
4677 }
4678
4679 /// Returns true if the face state doesn't mutate the target values.
4680 #[must_use]
4681 pub fn is_read_only(&self) -> bool {
4682 self.pass_op == StencilOperation::Keep
4683 && self.depth_fail_op == StencilOperation::Keep
4684 && self.fail_op == StencilOperation::Keep
4685 }
4686 }
4687
4688 impl Default for StencilFaceState {
4689 fn default() -> Self {
4690 Self::IGNORE
4691 }
4692 }
4693
4694 /// Comparison function used for depth and stencil operations.
4695 ///
4696 /// Corresponds to [WebGPU `GPUCompareFunction`](
4697 /// https://gpuweb.github.io/gpuweb/#enumdef-gpucomparefunction).
4698 #[repr(C)]
4699 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
4700 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4701 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
4702 pub enum CompareFunction {
4703 /// Function never passes
4704 Never = 1,
4705 /// Function passes if new value less than existing value
4706 Less = 2,
4707 /// Function passes if new value is equal to existing value. When using
4708 /// this compare function, make sure to mark your Vertex Shader's `@builtin(position)`
4709 /// output as `@invariant` to prevent artifacting.
4710 Equal = 3,
4711 /// Function passes if new value is less than or equal to existing value
4712 LessEqual = 4,
4713 /// Function passes if new value is greater than existing value
4714 Greater = 5,
4715 /// Function passes if new value is not equal to existing value. When using
4716 /// this compare function, make sure to mark your Vertex Shader's `@builtin(position)`
4717 /// output as `@invariant` to prevent artifacting.
4718 NotEqual = 6,
4719 /// Function passes if new value is greater than or equal to existing value
4720 GreaterEqual = 7,
4721 /// Function always passes
4722 Always = 8,
4723 }
4724
4725 impl CompareFunction {
4726 /// Returns true if the comparison depends on the reference value.
4727 #[must_use]
4728 pub fn needs_ref_value(self) -> bool {
4729 match self {
4730 Self::Never | Self::Always => false,
4731 _ => true,
4732 }
4733 }
4734 }
4735
4736 /// Whether a vertex buffer is indexed by vertex or by instance.
4737 ///
4738 /// Consider a call to [`RenderPass::draw`] like this:
4739 ///
4740 /// ```ignore
4741 /// render_pass.draw(vertices, instances)
4742 /// ```
4743 ///
4744 /// where `vertices` is a `Range<u32>` of vertex indices, and
4745 /// `instances` is a `Range<u32>` of instance indices.
4746 ///
4747 /// For this call, `wgpu` invokes the vertex shader entry point once
4748 /// for every possible `(v, i)` pair, where `v` is drawn from
4749 /// `vertices` and `i` is drawn from `instances`. These invocations
4750 /// may happen in any order, and will usually run in parallel.
4751 ///
4752 /// Each vertex buffer has a step mode, established by the
4753 /// [`step_mode`] field of its [`VertexBufferLayout`], given when the
4754 /// pipeline was created. Buffers whose step mode is [`Vertex`] use
4755 /// `v` as the index into their contents, whereas buffers whose step
4756 /// mode is [`Instance`] use `i`. The indicated buffer element then
4757 /// contributes zero or more attribute values for the `(v, i)` vertex
4758 /// shader invocation to use, based on the [`VertexBufferLayout`]'s
4759 /// [`attributes`] list.
4760 ///
4761 /// You can visualize the results from all these vertex shader
4762 /// invocations as a matrix with a row for each `i` from `instances`,
4763 /// and with a column for each `v` from `vertices`. In one sense, `v`
4764 /// and `i` are symmetrical: both are used to index vertex buffers and
4765 /// provide attribute values. But the key difference between `v` and
4766 /// `i` is that line and triangle primitives are built from the values
4767 /// of each row, along which `i` is constant and `v` varies, not the
4768 /// columns.
4769 ///
4770 /// An indexed draw call works similarly:
4771 ///
4772 /// ```ignore
4773 /// render_pass.draw_indexed(indices, base_vertex, instances)
4774 /// ```
4775 ///
4776 /// The only difference is that `v` values are drawn from the contents
4777 /// of the index buffer&mdash;specifically, the subrange of the index
4778 /// buffer given by `indices`&mdash;instead of simply being sequential
4779 /// integers, as they are in a `draw` call.
4780 ///
4781 /// A non-instanced call, where `instances` is `0..1`, is simply a
4782 /// matrix with only one row.
4783 ///
4784 /// Corresponds to [WebGPU `GPUVertexStepMode`](
4785 /// https://gpuweb.github.io/gpuweb/#enumdef-gpuvertexstepmode).
4786 ///
4787 /// [`RenderPass::draw`]: ../wgpu/struct.RenderPass.html#method.draw
4788 /// [`VertexBufferLayout`]: ../wgpu/struct.VertexBufferLayout.html
4789 /// [`step_mode`]: ../wgpu/struct.VertexBufferLayout.html#structfield.step_mode
4790 /// [`attributes`]: ../wgpu/struct.VertexBufferLayout.html#structfield.attributes
4791 /// [`Vertex`]: VertexStepMode::Vertex
4792 /// [`Instance`]: VertexStepMode::Instance
4793 #[repr(C)]
4794 #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
4795 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4796 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
4797 pub enum VertexStepMode {
4798 /// Vertex data is advanced every vertex.
4799 #[default]
4800 Vertex = 0,
4801 /// Vertex data is advanced every instance.
4802 Instance = 1,
4803 }
4804
4805 /// Vertex inputs (attributes) to shaders.
4806 ///
4807 /// These are used to specify the individual attributes within a [`VertexBufferLayout`].
4808 /// See its documentation for an example.
4809 ///
4810 /// The [`vertex_attr_array!`] macro can help create these with appropriate offsets.
4811 ///
4812 /// Corresponds to [WebGPU `GPUVertexAttribute`](
4813 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuvertexattribute).
4814 ///
4815 /// [`vertex_attr_array!`]: ../wgpu/macro.vertex_attr_array.html
4816 /// [`VertexBufferLayout`]: ../wgpu/struct.VertexBufferLayout.html
4817 #[repr(C)]
4818 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4819 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4820 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
4821 pub struct VertexAttribute {
4822 /// Format of the input
4823 pub format: VertexFormat,
4824 /// Byte offset of the start of the input
4825 pub offset: BufferAddress,
4826 /// Location for this input. Must match the location in the shader.
4827 pub shader_location: ShaderLocation,
4828 }
4829
4830 /// Vertex Format for a [`VertexAttribute`] (input).
4831 ///
4832 /// Corresponds to [WebGPU `GPUVertexFormat`](
4833 /// https://gpuweb.github.io/gpuweb/#enumdef-gpuvertexformat).
4834 #[repr(C)]
4835 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
4836 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4837 #[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
4838 pub enum VertexFormat {
4839 /// One unsigned byte (u8). `u32` in shaders.
4840 Uint8 = 0,
4841 /// Two unsigned bytes (u8). `vec2<u32>` in shaders.
4842 Uint8x2 = 1,
4843 /// Four unsigned bytes (u8). `vec4<u32>` in shaders.
4844 Uint8x4 = 2,
4845 /// One signed byte (i8). `i32` in shaders.
4846 Sint8 = 3,
4847 /// Two signed bytes (i8). `vec2<i32>` in shaders.
4848 Sint8x2 = 4,
4849 /// Four signed bytes (i8). `vec4<i32>` in shaders.
4850 Sint8x4 = 5,
4851 /// One unsigned byte (u8). [0, 255] converted to float [0, 1] `f32` in shaders.
4852 Unorm8 = 6,
4853 /// Two unsigned bytes (u8). [0, 255] converted to float [0, 1] `vec2<f32>` in shaders.
4854 Unorm8x2 = 7,
4855 /// Four unsigned bytes (u8). [0, 255] converted to float [0, 1] `vec4<f32>` in shaders.
4856 Unorm8x4 = 8,
4857 /// One signed byte (i8). [&minus;127, 127] converted to float [&minus;1, 1] `f32` in shaders.
4858 Snorm8 = 9,
4859 /// Two signed bytes (i8). [&minus;127, 127] converted to float [&minus;1, 1] `vec2<f32>` in shaders.
4860 Snorm8x2 = 10,
4861 /// Four signed bytes (i8). [&minus;127, 127] converted to float [&minus;1, 1] `vec4<f32>` in shaders.
4862 Snorm8x4 = 11,
4863 /// One unsigned short (u16). `u32` in shaders.
4864 Uint16 = 12,
4865 /// Two unsigned shorts (u16). `vec2<u32>` in shaders.
4866 Uint16x2 = 13,
4867 /// Four unsigned shorts (u16). `vec4<u32>` in shaders.
4868 Uint16x4 = 14,
4869 /// One signed short (u16). `i32` in shaders.
4870 Sint16 = 15,
4871 /// Two signed shorts (i16). `vec2<i32>` in shaders.
4872 Sint16x2 = 16,
4873 /// Four signed shorts (i16). `vec4<i32>` in shaders.
4874 Sint16x4 = 17,
4875 /// One unsigned short (u16). [0, 65535] converted to float [0, 1] `f32` in shaders.
4876 Unorm16 = 18,
4877 /// Two unsigned shorts (u16). [0, 65535] converted to float [0, 1] `vec2<f32>` in shaders.
4878 Unorm16x2 = 19,
4879 /// Four unsigned shorts (u16). [0, 65535] converted to float [0, 1] `vec4<f32>` in shaders.
4880 Unorm16x4 = 20,
4881 /// One signed short (i16). [&minus;32767, 32767] converted to float [&minus;1, 1] `f32` in shaders.
4882 Snorm16 = 21,
4883 /// Two signed shorts (i16). [&minus;32767, 32767] converted to float [&minus;1, 1] `vec2<f32>` in shaders.
4884 Snorm16x2 = 22,
4885 /// Four signed shorts (i16). [&minus;32767, 32767] converted to float [&minus;1, 1] `vec4<f32>` in shaders.
4886 Snorm16x4 = 23,
4887 /// One half-precision float (no Rust equiv). `f32` in shaders.
4888 Float16 = 24,
4889 /// Two half-precision floats (no Rust equiv). `vec2<f32>` in shaders.
4890 Float16x2 = 25,
4891 /// Four half-precision floats (no Rust equiv). `vec4<f32>` in shaders.
4892 Float16x4 = 26,
4893 /// One single-precision float (f32). `f32` in shaders.
4894 Float32 = 27,
4895 /// Two single-precision floats (f32). `vec2<f32>` in shaders.
4896 Float32x2 = 28,
4897 /// Three single-precision floats (f32). `vec3<f32>` in shaders.
4898 Float32x3 = 29,
4899 /// Four single-precision floats (f32). `vec4<f32>` in shaders.
4900 Float32x4 = 30,
4901 /// One unsigned int (u32). `u32` in shaders.
4902 Uint32 = 31,
4903 /// Two unsigned ints (u32). `vec2<u32>` in shaders.
4904 Uint32x2 = 32,
4905 /// Three unsigned ints (u32). `vec3<u32>` in shaders.
4906 Uint32x3 = 33,
4907 /// Four unsigned ints (u32). `vec4<u32>` in shaders.
4908 Uint32x4 = 34,
4909 /// One signed int (i32). `i32` in shaders.
4910 Sint32 = 35,
4911 /// Two signed ints (i32). `vec2<i32>` in shaders.
4912 Sint32x2 = 36,
4913 /// Three signed ints (i32). `vec3<i32>` in shaders.
4914 Sint32x3 = 37,
4915 /// Four signed ints (i32). `vec4<i32>` in shaders.
4916 Sint32x4 = 38,
4917 /// One double-precision float (f64). `f32` in shaders. Requires [`Features::VERTEX_ATTRIBUTE_64BIT`].
4918 Float64 = 39,
4919 /// Two double-precision floats (f64). `vec2<f32>` in shaders. Requires [`Features::VERTEX_ATTRIBUTE_64BIT`].
4920 Float64x2 = 40,
4921 /// Three double-precision floats (f64). `vec3<f32>` in shaders. Requires [`Features::VERTEX_ATTRIBUTE_64BIT`].
4922 Float64x3 = 41,
4923 /// Four double-precision floats (f64). `vec4<f32>` in shaders. Requires [`Features::VERTEX_ATTRIBUTE_64BIT`].
4924 Float64x4 = 42,
4925 /// Three unsigned 10-bit integers and one 2-bit integer, packed into a 32-bit integer (u32). [0, 1024] converted to float [0, 1] `vec4<f32>` in shaders.
4926 #[cfg_attr(feature = "serde", serde(rename = "unorm10-10-10-2"))]
4927 Unorm10_10_10_2 = 43,
4928 /// Four unsigned 8-bit integers, packed into a 32-bit integer (u32). [0, 255] converted to float [0, 1] `vec4<f32>` in shaders.
4929 #[cfg_attr(feature = "serde", serde(rename = "unorm8x4-bgra"))]
4930 Unorm8x4Bgra = 44,
4931 }
4932
4933 impl VertexFormat {
4934 /// Returns the byte size of the format.
4935 #[must_use]
4936 pub const fn size(&self) -> u64 {
4937 match self {
4938 Self::Uint8 | Self::Sint8 | Self::Unorm8 | Self::Snorm8 => 1,
4939 Self::Uint8x2
4940 | Self::Sint8x2
4941 | Self::Unorm8x2
4942 | Self::Snorm8x2
4943 | Self::Uint16
4944 | Self::Sint16
4945 | Self::Unorm16
4946 | Self::Snorm16
4947 | Self::Float16 => 2,
4948 Self::Uint8x4
4949 | Self::Sint8x4
4950 | Self::Unorm8x4
4951 | Self::Snorm8x4
4952 | Self::Uint16x2
4953 | Self::Sint16x2
4954 | Self::Unorm16x2
4955 | Self::Snorm16x2
4956 | Self::Float16x2
4957 | Self::Float32
4958 | Self::Uint32
4959 | Self::Sint32
4960 | Self::Unorm10_10_10_2
4961 | Self::Unorm8x4Bgra => 4,
4962 Self::Uint16x4
4963 | Self::Sint16x4
4964 | Self::Unorm16x4
4965 | Self::Snorm16x4
4966 | Self::Float16x4
4967 | Self::Float32x2
4968 | Self::Uint32x2
4969 | Self::Sint32x2
4970 | Self::Float64 => 8,
4971 Self::Float32x3 | Self::Uint32x3 | Self::Sint32x3 => 12,
4972 Self::Float32x4 | Self::Uint32x4 | Self::Sint32x4 | Self::Float64x2 => 16,
4973 Self::Float64x3 => 24,
4974 Self::Float64x4 => 32,
4975 }
4976 }
4977 }
4978
4979 bitflags::bitflags! {
4980 /// Different ways that you can use a buffer.
4981 ///
4982 /// The usages determine what kind of memory the buffer is allocated from and what
4983 /// actions the buffer can partake in.
4984 ///
4985 /// Corresponds to [WebGPU `GPUBufferUsageFlags`](
4986 /// https://gpuweb.github.io/gpuweb/#typedefdef-gpubufferusageflags).
4987 #[repr(transparent)]
4988 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4989 #[cfg_attr(feature = "serde", serde(transparent))]
4990 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
4991 pub struct BufferUsages: u32 {
4992 /// Allow a buffer to be mapped for reading using [`Buffer::map_async`] + [`Buffer::get_mapped_range`].
4993 /// This does not include creating a buffer with [`BufferDescriptor::mapped_at_creation`] set.
4994 ///
4995 /// If [`Features::MAPPABLE_PRIMARY_BUFFERS`] isn't enabled, the only other usage a buffer
4996 /// may have is COPY_DST.
4997 const MAP_READ = 1 << 0;
4998 /// Allow a buffer to be mapped for writing using [`Buffer::map_async`] + [`Buffer::get_mapped_range_mut`].
4999 /// This does not include creating a buffer with `mapped_at_creation` set.
5000 ///
5001 /// If [`Features::MAPPABLE_PRIMARY_BUFFERS`] feature isn't enabled, the only other usage a buffer
5002 /// may have is COPY_SRC.
5003 const MAP_WRITE = 1 << 1;
5004 /// Allow a buffer to be the source buffer for a [`CommandEncoder::copy_buffer_to_buffer`] or [`CommandEncoder::copy_buffer_to_texture`]
5005 /// operation.
5006 const COPY_SRC = 1 << 2;
5007 /// Allow a buffer to be the destination buffer for a [`CommandEncoder::copy_buffer_to_buffer`], [`CommandEncoder::copy_texture_to_buffer`],
5008 /// [`CommandEncoder::clear_buffer`] or [`Queue::write_buffer`] operation.
5009 const COPY_DST = 1 << 3;
5010 /// Allow a buffer to be the index buffer in a draw operation.
5011 const INDEX = 1 << 4;
5012 /// Allow a buffer to be the vertex buffer in a draw operation.
5013 const VERTEX = 1 << 5;
5014 /// Allow a buffer to be a [`BufferBindingType::Uniform`] inside a bind group.
5015 const UNIFORM = 1 << 6;
5016 /// Allow a buffer to be a [`BufferBindingType::Storage`] inside a bind group.
5017 const STORAGE = 1 << 7;
5018 /// Allow a buffer to be the indirect buffer in an indirect draw call.
5019 const INDIRECT = 1 << 8;
5020 /// Allow a buffer to be the destination buffer for a [`CommandEncoder::resolve_query_set`] operation.
5021 const QUERY_RESOLVE = 1 << 9;
5022 /// Allows a buffer to be used as input for a bottom level acceleration structure build
5023 const BLAS_INPUT = 1 << 10;
5024 /// Allows a buffer to be used as input for a top level acceleration structure build
5025 const TLAS_INPUT = 1 << 11;
5026 }
5027 }
5028
5029 bitflags::bitflags! {
5030 /// Similar to `BufferUsages`, but used only for `CommandEncoder::transition_resources`.
5031 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
5032 pub struct BufferUses: u16 {
5033 /// The argument to a read-only mapping.
5034 const MAP_READ = 1 << 0;
5035 /// The argument to a write-only mapping.
5036 const MAP_WRITE = 1 << 1;
5037 /// The source of a hardware copy.
5038 /// cbindgen:ignore
5039 const COPY_SRC = 1 << 2;
5040 /// The destination of a hardware copy.
5041 /// cbindgen:ignore
5042 const COPY_DST = 1 << 3;
5043 /// The index buffer used for drawing.
5044 const INDEX = 1 << 4;
5045 /// A vertex buffer used for drawing.
5046 const VERTEX = 1 << 5;
5047 /// A uniform buffer bound in a bind group.
5048 const UNIFORM = 1 << 6;
5049 /// A read-only storage buffer used in a bind group.
5050 /// cbindgen:ignore
5051 const STORAGE_READ_ONLY = 1 << 7;
5052 /// A read-write buffer used in a bind group.
5053 /// cbindgen:ignore
5054 const STORAGE_READ_WRITE = 1 << 8;
5055 /// The indirect or count buffer in a indirect draw or dispatch.
5056 const INDIRECT = 1 << 9;
5057 /// A buffer used to store query results.
5058 const QUERY_RESOLVE = 1 << 10;
5059 /// Buffer used for acceleration structure building.
5060 const ACCELERATION_STRUCTURE_SCRATCH = 1 << 11;
5061 /// Buffer used for bottom level acceleration structure building.
5062 const BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT = 1 << 12;
5063 /// Buffer used for top level acceleration structure building.
5064 const TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT = 1 << 13;
5065 /// A buffer used to store the compacted size of an acceleration structure
5066 const ACCELERATION_STRUCTURE_QUERY = 1 << 14;
5067 /// The combination of states that a buffer may be in _at the same time_.
5068 const INCLUSIVE = Self::MAP_READ.bits() | Self::COPY_SRC.bits() |
5069 Self::INDEX.bits() | Self::VERTEX.bits() | Self::UNIFORM.bits() |
5070 Self::STORAGE_READ_ONLY.bits() | Self::INDIRECT.bits() | Self::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT.bits() | Self::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT.bits();
5071 /// The combination of states that a buffer must exclusively be in.
5072 const EXCLUSIVE = Self::MAP_WRITE.bits() | Self::COPY_DST.bits() | Self::STORAGE_READ_WRITE.bits() | Self::ACCELERATION_STRUCTURE_SCRATCH.bits();
5073 /// The combination of all usages that the are guaranteed to be be ordered by the hardware.
5074 /// If a usage is ordered, then if the buffer state doesn't change between draw calls, there
5075 /// are no barriers needed for synchronization.
5076 const ORDERED = Self::INCLUSIVE.bits() | Self::MAP_WRITE.bits();
5077 }
5078 }
5079
5080 /// A buffer transition for use with `CommandEncoder::transition_resources`.
5081 #[derive(Debug)]
5082 pub struct BufferTransition<T> {
5083 /// The buffer to transition.
5084 pub buffer: T,
5085 /// The new state to transition to.
5086 pub state: BufferUses,
5087 }
5088
5089 /// Describes a [`Buffer`](../wgpu/struct.Buffer.html).
5090 ///
5091 /// Corresponds to [WebGPU `GPUBufferDescriptor`](
5092 /// https://gpuweb.github.io/gpuweb/#dictdef-gpubufferdescriptor).
5093 #[repr(C)]
5094 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
5095 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5096 pub struct BufferDescriptor<L> {
5097 /// Debug label of a buffer. This will show up in graphics debuggers for easy identification.
5098 pub label: L,
5099 /// Size of a buffer, in bytes.
5100 pub size: BufferAddress,
5101 /// Usages of a buffer. If the buffer is used in any way that isn't specified here, the operation
5102 /// will panic.
5103 pub usage: BufferUsages,
5104 /// Allows a buffer to be mapped immediately after they are made. It does not have to be [`BufferUsages::MAP_READ`] or
5105 /// [`BufferUsages::MAP_WRITE`], all buffers are allowed to be mapped at creation.
5106 ///
5107 /// If this is `true`, [`size`](#structfield.size) must be a multiple of
5108 /// [`COPY_BUFFER_ALIGNMENT`].
5109 pub mapped_at_creation: bool,
5110 }
5111
5112 impl<L> BufferDescriptor<L> {
5113 /// Takes a closure and maps the label of the buffer descriptor into another.
5114 #[must_use]
5115 pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> BufferDescriptor<K> {
5116 BufferDescriptor {
5117 label: fun(&self.label),
5118 size: self.size,
5119 usage: self.usage,
5120 mapped_at_creation: self.mapped_at_creation,
5121 }
5122 }
5123 }
5124
5125 /// Describes a [`CommandEncoder`](../wgpu/struct.CommandEncoder.html).
5126 ///
5127 /// Corresponds to [WebGPU `GPUCommandEncoderDescriptor`](
5128 /// https://gpuweb.github.io/gpuweb/#dictdef-gpucommandencoderdescriptor).
5129 #[repr(C)]
5130 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5131 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
5132 pub struct CommandEncoderDescriptor<L> {
5133 /// Debug label for the command encoder. This will show up in graphics debuggers for easy identification.
5134 pub label: L,
5135 }
5136
5137 impl<L> CommandEncoderDescriptor<L> {
5138 /// Takes a closure and maps the label of the command encoder descriptor into another.
5139 #[must_use]
5140 pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> CommandEncoderDescriptor<K> {
5141 CommandEncoderDescriptor {
5142 label: fun(&self.label),
5143 }
5144 }
5145 }
5146
5147 impl<T> Default for CommandEncoderDescriptor<Option<T>> {
5148 fn default() -> Self {
5149 Self { label: None }
5150 }
5151 }
5152
5153 /// Timing and queueing with which frames are actually displayed to the user.
5154 ///
5155 /// Use this as part of a [`SurfaceConfiguration`] to control the behavior of
5156 /// [`SurfaceTexture::present()`].
5157 ///
5158 /// Some modes are only supported by some backends.
5159 /// You can use one of the `Auto*` modes, [`Fifo`](Self::Fifo),
5160 /// or choose one of the supported modes from [`SurfaceCapabilities::present_modes`].
5161 ///
5162 /// [presented]: ../wgpu/struct.SurfaceTexture.html#method.present
5163 /// [`SurfaceTexture::present()`]: ../wgpu/struct.SurfaceTexture.html#method.present
5164 #[repr(C)]
5165 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
5166 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5167 pub enum PresentMode {
5168 /// Chooses the first supported mode out of:
5169 ///
5170 /// 1. [`FifoRelaxed`](Self::FifoRelaxed)
5171 /// 2. [`Fifo`](Self::Fifo)
5172 ///
5173 /// Because of the fallback behavior, this is supported everywhere.
5174 AutoVsync = 0,
5175
5176 /// Chooses the first supported mode out of:
5177 ///
5178 /// 1. [`Immediate`](Self::Immediate)
5179 /// 2. [`Mailbox`](Self::Mailbox)
5180 /// 3. [`Fifo`](Self::Fifo)
5181 ///
5182 /// Because of the fallback behavior, this is supported everywhere.
5183 AutoNoVsync = 1,
5184
5185 /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
5186 /// long. Every vertical blanking period, the presentation engine will pop a frame
5187 /// off the queue to display. If there is no frame to display, it will present the same
5188 /// frame again until the next vblank.
5189 ///
5190 /// When a present command is executed on the GPU, the presented image is added on the queue.
5191 ///
5192 /// Calls to [`Surface::get_current_texture()`] will block until there is a spot in the queue.
5193 ///
5194 /// * **Tearing:** No tearing will be observed.
5195 /// * **Supported on**: All platforms.
5196 /// * **Also known as**: "Vsync On"
5197 ///
5198 /// This is the [default](Self::default) value for `PresentMode`.
5199 /// If you don't know what mode to choose, choose this mode.
5200 ///
5201 /// [`Surface::get_current_texture()`]: ../wgpu/struct.Surface.html#method.get_current_texture
5202 #[default]
5203 Fifo = 2,
5204
5205 /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames
5206 /// long. Every vertical blanking period, the presentation engine will pop a frame
5207 /// off the queue to display. If there is no frame to display, it will present the
5208 /// same frame until there is a frame in the queue. The moment there is a frame in the
5209 /// queue, it will immediately pop the frame off the queue.
5210 ///
5211 /// When a present command is executed on the GPU, the presented image is added on the queue.
5212 ///
5213 /// Calls to [`Surface::get_current_texture()`] will block until there is a spot in the queue.
5214 ///
5215 /// * **Tearing**:
5216 /// Tearing will be observed if frames last more than one vblank as the front buffer.
5217 /// * **Supported on**: AMD on Vulkan.
5218 /// * **Also known as**: "Adaptive Vsync"
5219 ///
5220 /// [`Surface::get_current_texture()`]: ../wgpu/struct.Surface.html#method.get_current_texture
5221 FifoRelaxed = 3,
5222
5223 /// Presentation frames are not queued at all. The moment a present command
5224 /// is executed on the GPU, the presented image is swapped onto the front buffer
5225 /// immediately.
5226 ///
5227 /// * **Tearing**: Tearing can be observed.
5228 /// * **Supported on**: Most platforms except older DX12 and Wayland.
5229 /// * **Also known as**: "Vsync Off"
5230 Immediate = 4,
5231
5232 /// Presentation frames are kept in a single-frame queue. Every vertical blanking period,
5233 /// the presentation engine will pop a frame from the queue. If there is no frame to display,
5234 /// it will present the same frame again until the next vblank.
5235 ///
5236 /// When a present command is executed on the GPU, the frame will be put into the queue.
5237 /// If there was already a frame in the queue, the new frame will _replace_ the old frame
5238 /// on the queue.
5239 ///
5240 /// * **Tearing**: No tearing will be observed.
5241 /// * **Supported on**: DX12 on Windows 10, NVidia on Vulkan and Wayland on Vulkan.
5242 /// * **Also known as**: "Fast Vsync"
5243 Mailbox = 5,
5244 }
5245
5246 /// Specifies how the alpha channel of the textures should be handled during
5247 /// compositing.
5248 #[repr(C)]
5249 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5250 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5251 #[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
5252 pub enum CompositeAlphaMode {
5253 /// Chooses either `Opaque` or `Inherit` automatically,depending on the
5254 /// `alpha_mode` that the current surface can support.
5255 Auto = 0,
5256 /// The alpha channel, if it exists, of the textures is ignored in the
5257 /// compositing process. Instead, the textures is treated as if it has a
5258 /// constant alpha of 1.0.
5259 Opaque = 1,
5260 /// The alpha channel, if it exists, of the textures is respected in the
5261 /// compositing process. The non-alpha channels of the textures are
5262 /// expected to already be multiplied by the alpha channel by the
5263 /// application.
5264 PreMultiplied = 2,
5265 /// The alpha channel, if it exists, of the textures is respected in the
5266 /// compositing process. The non-alpha channels of the textures are not
5267 /// expected to already be multiplied by the alpha channel by the
5268 /// application; instead, the compositor will multiply the non-alpha
5269 /// channels of the texture by the alpha channel during compositing.
5270 PostMultiplied = 3,
5271 /// The alpha channel, if it exists, of the textures is unknown for processing
5272 /// during compositing. Instead, the application is responsible for setting
5273 /// the composite alpha blending mode using native WSI command. If not set,
5274 /// then a platform-specific default will be used.
5275 Inherit = 4,
5276 }
5277
5278 impl Default for CompositeAlphaMode {
5279 fn default() -> Self {
5280 Self::Auto
5281 }
5282 }
5283
5284 bitflags::bitflags! {
5285 /// Different ways that you can use a texture.
5286 ///
5287 /// The usages determine what kind of memory the texture is allocated from and what
5288 /// actions the texture can partake in.
5289 ///
5290 /// Corresponds to [WebGPU `GPUTextureUsageFlags`](
5291 /// https://gpuweb.github.io/gpuweb/#typedefdef-gputextureusageflags).
5292 #[repr(transparent)]
5293 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5294 #[cfg_attr(feature = "serde", serde(transparent))]
5295 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
5296 pub struct TextureUsages: u32 {
5297 //
5298 // ---- Start numbering at 1 << 0 ----
5299 //
5300 // WebGPU features:
5301 //
5302 /// Allows a texture to be the source in a [`CommandEncoder::copy_texture_to_buffer`] or
5303 /// [`CommandEncoder::copy_texture_to_texture`] operation.
5304 const COPY_SRC = 1 << 0;
5305 /// Allows a texture to be the destination in a [`CommandEncoder::copy_buffer_to_texture`],
5306 /// [`CommandEncoder::copy_texture_to_texture`], or [`Queue::write_texture`] operation.
5307 const COPY_DST = 1 << 1;
5308 /// Allows a texture to be a [`BindingType::Texture`] in a bind group.
5309 const TEXTURE_BINDING = 1 << 2;
5310 /// Allows a texture to be a [`BindingType::StorageTexture`] in a bind group.
5311 const STORAGE_BINDING = 1 << 3;
5312 /// Allows a texture to be an output attachment of a render pass.
5313 const RENDER_ATTACHMENT = 1 << 4;
5314
5315 //
5316 // ---- Restart Numbering for Native Features ---
5317 //
5318 // Native Features:
5319 //
5320 /// Allows a texture to be used with image atomics. Requires [`Features::TEXTURE_ATOMIC`].
5321 const STORAGE_ATOMIC = 1 << 16;
5322 }
5323 }
5324
5325 bitflags::bitflags! {
5326 /// Similar to `TextureUsages`, but used only for `CommandEncoder::transition_resources`.
5327 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
5328 pub struct TextureUses: u16 {
5329 /// The texture is in unknown state.
5330 const UNINITIALIZED = 1 << 0;
5331 /// Ready to present image to the surface.
5332 const PRESENT = 1 << 1;
5333 /// The source of a hardware copy.
5334 /// cbindgen:ignore
5335 const COPY_SRC = 1 << 2;
5336 /// The destination of a hardware copy.
5337 /// cbindgen:ignore
5338 const COPY_DST = 1 << 3;
5339 /// Read-only sampled or fetched resource.
5340 const RESOURCE = 1 << 4;
5341 /// The color target of a renderpass.
5342 const COLOR_TARGET = 1 << 5;
5343 /// Read-only depth stencil usage.
5344 const DEPTH_STENCIL_READ = 1 << 6;
5345 /// Read-write depth stencil usage
5346 const DEPTH_STENCIL_WRITE = 1 << 7;
5347 /// Read-only storage texture usage. Corresponds to a UAV in d3d, so is exclusive, despite being read only.
5348 /// cbindgen:ignore
5349 const STORAGE_READ_ONLY = 1 << 8;
5350 /// Write-only storage texture usage.
5351 /// cbindgen:ignore
5352 const STORAGE_WRITE_ONLY = 1 << 9;
5353 /// Read-write storage texture usage.
5354 /// cbindgen:ignore
5355 const STORAGE_READ_WRITE = 1 << 10;
5356 /// Image atomic enabled storage.
5357 /// cbindgen:ignore
5358 const STORAGE_ATOMIC = 1 << 11;
5359 /// The combination of states that a texture may be in _at the same time_.
5360 /// cbindgen:ignore
5361 const INCLUSIVE = Self::COPY_SRC.bits() | Self::RESOURCE.bits() | Self::DEPTH_STENCIL_READ.bits();
5362 /// The combination of states that a texture must exclusively be in.
5363 /// cbindgen:ignore
5364 const EXCLUSIVE = Self::COPY_DST.bits() | Self::COLOR_TARGET.bits() | Self::DEPTH_STENCIL_WRITE.bits() | Self::STORAGE_READ_ONLY.bits() | Self::STORAGE_WRITE_ONLY.bits() | Self::STORAGE_READ_WRITE.bits() | Self::STORAGE_ATOMIC.bits() | Self::PRESENT.bits();
5365 /// The combination of all usages that the are guaranteed to be be ordered by the hardware.
5366 /// If a usage is ordered, then if the texture state doesn't change between draw calls, there
5367 /// are no barriers needed for synchronization.
5368 /// cbindgen:ignore
5369 const ORDERED = Self::INCLUSIVE.bits() | Self::COLOR_TARGET.bits() | Self::DEPTH_STENCIL_WRITE.bits() | Self::STORAGE_READ_ONLY.bits();
5370
5371 /// Flag used by the wgpu-core texture tracker to say a texture is in different states for every sub-resource
5372 const COMPLEX = 1 << 12;
5373 /// Flag used by the wgpu-core texture tracker to say that the tracker does not know the state of the sub-resource.
5374 /// This is different from UNINITIALIZED as that says the tracker does know, but the texture has not been initialized.
5375 const UNKNOWN = 1 << 13;
5376 }
5377 }
5378
5379 /// A texture transition for use with `CommandEncoder::transition_resources`.
5380 #[derive(Debug)]
5381 pub struct TextureTransition<T> {
5382 /// The texture to transition.
5383 pub texture: T,
5384 /// An optional selector to transition only part of the texture.
5385 ///
5386 /// If None, the entire texture will be transitioned.
5387 pub selector: Option<TextureSelector>,
5388 /// The new state to transition to.
5389 pub state: TextureUses,
5390 }
5391
5392 /// Specifies a particular set of subresources in a texture.
5393 #[derive(Clone, Debug, PartialEq, Eq)]
5394 pub struct TextureSelector {
5395 /// Range of mips to use.
5396 pub mips: Range<u32>,
5397 /// Range of layers to use.
5398 pub layers: Range<u32>,
5399 }
5400
5401 /// Defines the capabilities of a given surface and adapter.
5402 #[derive(Debug)]
5403 pub struct SurfaceCapabilities {
5404 /// List of supported formats to use with the given adapter. The first format in the vector is preferred.
5405 ///
5406 /// Returns an empty vector if the surface is incompatible with the adapter.
5407 pub formats: Vec<TextureFormat>,
5408 /// List of supported presentation modes to use with the given adapter.
5409 ///
5410 /// Returns an empty vector if the surface is incompatible with the adapter.
5411 pub present_modes: Vec<PresentMode>,
5412 /// List of supported alpha modes to use with the given adapter.
5413 ///
5414 /// Will return at least one element, [`CompositeAlphaMode::Opaque`] or [`CompositeAlphaMode::Inherit`].
5415 pub alpha_modes: Vec<CompositeAlphaMode>,
5416 /// Bitflag of supported texture usages for the surface to use with the given adapter.
5417 ///
5418 /// The usage [`TextureUsages::RENDER_ATTACHMENT`] is guaranteed.
5419 pub usages: TextureUsages,
5420 }
5421
5422 impl Default for SurfaceCapabilities {
5423 fn default() -> Self {
5424 Self {
5425 formats: Vec::new(),
5426 present_modes: Vec::new(),
5427 alpha_modes: vec![CompositeAlphaMode::Opaque],
5428 usages: TextureUsages::RENDER_ATTACHMENT,
5429 }
5430 }
5431 }
5432
5433 /// Configures a [`Surface`] for presentation.
5434 ///
5435 /// [`Surface`]: ../wgpu/struct.Surface.html
5436 #[repr(C)]
5437 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
5438 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5439 pub struct SurfaceConfiguration<V> {
5440 /// The usage of the swap chain. The only usage guaranteed to be supported is [`TextureUsages::RENDER_ATTACHMENT`].
5441 pub usage: TextureUsages,
5442 /// The texture format of the swap chain. The only formats that are guaranteed are
5443 /// [`TextureFormat::Bgra8Unorm`] and [`TextureFormat::Bgra8UnormSrgb`].
5444 pub format: TextureFormat,
5445 /// Width of the swap chain. Must be the same size as the surface, and nonzero.
5446 ///
5447 /// If this is not the same size as the underlying surface (e.g. if it is
5448 /// set once, and the window is later resized), the behaviour is defined
5449 /// but platform-specific, and may change in the future (currently macOS
5450 /// scales the surface, other platforms may do something else).
5451 pub width: u32,
5452 /// Height of the swap chain. Must be the same size as the surface, and nonzero.
5453 ///
5454 /// If this is not the same size as the underlying surface (e.g. if it is
5455 /// set once, and the window is later resized), the behaviour is defined
5456 /// but platform-specific, and may change in the future (currently macOS
5457 /// scales the surface, other platforms may do something else).
5458 pub height: u32,
5459 /// Presentation mode of the swap chain. Fifo is the only mode guaranteed to be supported.
5460 /// `FifoRelaxed`, `Immediate`, and `Mailbox` will crash if unsupported, while `AutoVsync` and
5461 /// `AutoNoVsync` will gracefully do a designed sets of fallbacks if their primary modes are
5462 /// unsupported.
5463 pub present_mode: PresentMode,
5464 /// Desired maximum number of frames that the presentation engine should queue in advance.
5465 ///
5466 /// This is a hint to the backend implementation and will always be clamped to the supported range.
5467 /// As a consequence, either the maximum frame latency is set directly on the swap chain,
5468 /// or waits on present are scheduled to avoid exceeding the maximum frame latency if supported,
5469 /// or the swap chain size is set to (max-latency + 1).
5470 ///
5471 /// Defaults to 2 when created via `Surface::get_default_config`.
5472 ///
5473 /// Typical values range from 3 to 1, but higher values are possible:
5474 /// * Choose 2 or higher for potentially smoother frame display, as it allows to be at least one frame
5475 /// to be queued up. This typically avoids starving the GPU's work queue.
5476 /// Higher values are useful for achieving a constant flow of frames to the display under varying load.
5477 /// * Choose 1 for low latency from frame recording to frame display.
5478 /// ⚠️ If the backend does not support waiting on present, this will cause the CPU to wait for the GPU
5479 /// to finish all work related to the previous frame when calling `Surface::get_current_texture`,
5480 /// causing CPU-GPU serialization (i.e. when `Surface::get_current_texture` returns, the GPU might be idle).
5481 /// It is currently not possible to query this. See <https://github.com/gfx-rs/wgpu/issues/2869>.
5482 /// * A value of 0 is generally not supported and always clamped to a higher value.
5483 pub desired_maximum_frame_latency: u32,
5484 /// Specifies how the alpha channel of the textures should be handled during compositing.
5485 pub alpha_mode: CompositeAlphaMode,
5486 /// Specifies what view formats will be allowed when calling `Texture::create_view` on the texture returned by `Surface::get_current_texture`.
5487 ///
5488 /// View formats of the same format as the texture are always allowed.
5489 ///
5490 /// Note: currently, only the srgb-ness is allowed to change. (ex: `Rgba8Unorm` texture + `Rgba8UnormSrgb` view)
5491 pub view_formats: V,
5492 }
5493
5494 impl<V: Clone> SurfaceConfiguration<V> {
5495 /// Map `view_formats` of the texture descriptor into another.
5496 pub fn map_view_formats<M>(&self, fun: impl FnOnce(V) -> M) -> SurfaceConfiguration<M> {
5497 SurfaceConfiguration {
5498 usage: self.usage,
5499 format: self.format,
5500 width: self.width,
5501 height: self.height,
5502 present_mode: self.present_mode,
5503 desired_maximum_frame_latency: self.desired_maximum_frame_latency,
5504 alpha_mode: self.alpha_mode,
5505 view_formats: fun(self.view_formats.clone()),
5506 }
5507 }
5508 }
5509
5510 /// Status of the received surface image.
5511 #[repr(C)]
5512 #[derive(Debug)]
5513 pub enum SurfaceStatus {
5514 /// No issues.
5515 Good,
5516 /// The swap chain is operational, but it does no longer perfectly
5517 /// match the surface. A re-configuration is needed.
5518 Suboptimal,
5519 /// Unable to get the next frame, timed out.
5520 Timeout,
5521 /// The surface under the swap chain has changed.
5522 Outdated,
5523 /// The surface under the swap chain is lost.
5524 Lost,
5525 /// The surface status is not known since `Surface::get_current_texture` previously failed.
5526 Unknown,
5527 }
5528
5529 /// Nanosecond timestamp used by the presentation engine.
5530 ///
5531 /// The specific clock depends on the window system integration (WSI) API used.
5532 ///
5533 /// <table>
5534 /// <tr>
5535 /// <td>WSI</td>
5536 /// <td>Clock</td>
5537 /// </tr>
5538 /// <tr>
5539 /// <td>IDXGISwapchain</td>
5540 /// <td><a href="https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter">QueryPerformanceCounter</a></td>
5541 /// </tr>
5542 /// <tr>
5543 /// <td>IPresentationManager</td>
5544 /// <td><a href="https://docs.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryinterrupttimeprecise">QueryInterruptTimePrecise</a></td>
5545 /// </tr>
5546 /// <tr>
5547 /// <td>CAMetalLayer</td>
5548 /// <td><a href="https://developer.apple.com/documentation/kernel/1462446-mach_absolute_time">mach_absolute_time</a></td>
5549 /// </tr>
5550 /// <tr>
5551 /// <td>VK_GOOGLE_display_timing</td>
5552 /// <td><a href="https://linux.die.net/man/3/clock_gettime">clock_gettime(CLOCK_MONOTONIC)</a></td>
5553 /// </tr>
5554 /// </table>
5555 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
5556 pub struct PresentationTimestamp(
5557 /// Timestamp in nanoseconds.
5558 pub u128,
5559 );
5560
5561 impl PresentationTimestamp {
5562 /// A timestamp that is invalid due to the platform not having a timestamp system.
5563 pub const INVALID_TIMESTAMP: Self = Self(u128::MAX);
5564
5565 /// Returns true if this timestamp is the invalid timestamp.
5566 #[must_use]
5567 pub fn is_invalid(self) -> bool {
5568 self == Self::INVALID_TIMESTAMP
5569 }
5570 }
5571
5572 /// RGBA double precision color.
5573 ///
5574 /// This is not to be used as a generic color type, only for specific wgpu interfaces.
5575 #[repr(C)]
5576 #[derive(Clone, Copy, Debug, Default, PartialEq)]
5577 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
5578 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
5579 pub struct Color {
5580 /// Red component of the color
5581 pub r: f64,
5582 /// Green component of the color
5583 pub g: f64,
5584 /// Blue component of the color
5585 pub b: f64,
5586 /// Alpha component of the color
5587 pub a: f64,
5588 }
5589
5590 #[allow(missing_docs)]
5591 impl Color {
5592 pub const TRANSPARENT: Self = Self {
5593 r: 0.0,
5594 g: 0.0,
5595 b: 0.0,
5596 a: 0.0,
5597 };
5598 pub const BLACK: Self = Self {
5599 r: 0.0,
5600 g: 0.0,
5601 b: 0.0,
5602 a: 1.0,
5603 };
5604 pub const WHITE: Self = Self {
5605 r: 1.0,
5606 g: 1.0,
5607 b: 1.0,
5608 a: 1.0,
5609 };
5610 pub const RED: Self = Self {
5611 r: 1.0,
5612 g: 0.0,
5613 b: 0.0,
5614 a: 1.0,
5615 };
5616 pub const GREEN: Self = Self {
5617 r: 0.0,
5618 g: 1.0,
5619 b: 0.0,
5620 a: 1.0,
5621 };
5622 pub const BLUE: Self = Self {
5623 r: 0.0,
5624 g: 0.0,
5625 b: 1.0,
5626 a: 1.0,
5627 };
5628 }
5629
5630 /// Dimensionality of a texture.
5631 ///
5632 /// Corresponds to [WebGPU `GPUTextureDimension`](
5633 /// https://gpuweb.github.io/gpuweb/#enumdef-gputexturedimension).
5634 #[repr(C)]
5635 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
5636 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5637 pub enum TextureDimension {
5638 /// 1D texture
5639 #[cfg_attr(feature = "serde", serde(rename = "1d"))]
5640 D1,
5641 /// 2D texture
5642 #[cfg_attr(feature = "serde", serde(rename = "2d"))]
5643 D2,
5644 /// 3D texture
5645 #[cfg_attr(feature = "serde", serde(rename = "3d"))]
5646 D3,
5647 }
5648
5649 /// Origin of a copy from a 2D image.
5650 ///
5651 /// Corresponds to [WebGPU `GPUOrigin2D`](
5652 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuorigin2ddict).
5653 #[repr(C)]
5654 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
5655 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5656 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
5657 pub struct Origin2d {
5658 #[allow(missing_docs)]
5659 pub x: u32,
5660 #[allow(missing_docs)]
5661 pub y: u32,
5662 }
5663
5664 impl Origin2d {
5665 /// Zero origin.
5666 pub const ZERO: Self = Self { x: 0, y: 0 };
5667
5668 /// Adds the third dimension to this origin
5669 #[must_use]
5670 pub fn to_3d(self, z: u32) -> Origin3d {
5671 Origin3d {
5672 x: self.x,
5673 y: self.y,
5674 z,
5675 }
5676 }
5677 }
5678
5679 impl core::fmt::Debug for Origin2d {
5680 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
5681 (self.x, self.y).fmt(f)
5682 }
5683 }
5684
5685 /// Origin of a copy to/from a texture.
5686 ///
5687 /// Corresponds to [WebGPU `GPUOrigin3D`](
5688 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuorigin3ddict).
5689 #[repr(C)]
5690 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
5691 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5692 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
5693 pub struct Origin3d {
5694 /// X position of the origin
5695 pub x: u32,
5696 /// Y position of the origin
5697 pub y: u32,
5698 /// Z position of the origin
5699 pub z: u32,
5700 }
5701
5702 impl Origin3d {
5703 /// Zero origin.
5704 pub const ZERO: Self = Self { x: 0, y: 0, z: 0 };
5705
5706 /// Removes the third dimension from this origin
5707 #[must_use]
5708 pub fn to_2d(self) -> Origin2d {
5709 Origin2d {
5710 x: self.x,
5711 y: self.y,
5712 }
5713 }
5714 }
5715
5716 impl Default for Origin3d {
5717 fn default() -> Self {
5718 Self::ZERO
5719 }
5720 }
5721
5722 impl core::fmt::Debug for Origin3d {
5723 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
5724 (self.x, self.y, self.z).fmt(f)
5725 }
5726 }
5727
5728 /// Extent of a texture related operation.
5729 ///
5730 /// Corresponds to [WebGPU `GPUExtent3D`](
5731 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuextent3ddict).
5732 #[repr(C)]
5733 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
5734 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5735 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
5736 pub struct Extent3d {
5737 /// Width of the extent
5738 pub width: u32,
5739 /// Height of the extent
5740 pub height: u32,
5741 /// The depth of the extent or the number of array layers
5742 #[cfg_attr(feature = "serde", serde(default = "default_depth"))]
5743 pub depth_or_array_layers: u32,
5744 }
5745
5746 impl core::fmt::Debug for Extent3d {
5747 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
5748 (self.width, self.height, self.depth_or_array_layers).fmt(f)
5749 }
5750 }
5751
5752 #[cfg(feature = "serde")]
5753 fn default_depth() -> u32 {
5754 1
5755 }
5756
5757 impl Default for Extent3d {
5758 fn default() -> Self {
5759 Self {
5760 width: 1,
5761 height: 1,
5762 depth_or_array_layers: 1,
5763 }
5764 }
5765 }
5766
5767 impl Extent3d {
5768 /// Calculates the [physical size] backing a texture of the given
5769 /// format and extent. This includes padding to the block width
5770 /// and height of the format.
5771 ///
5772 /// This is the texture extent that you must upload at when uploading to _mipmaps_ of compressed textures.
5773 ///
5774 /// [physical size]: https://gpuweb.github.io/gpuweb/#physical-miplevel-specific-texture-extent
5775 #[must_use]
5776 pub fn physical_size(&self, format: TextureFormat) -> Self {
5777 let (block_width, block_height) = format.block_dimensions();
5778
5779 let width = self.width.div_ceil(block_width) * block_width;
5780 let height = self.height.div_ceil(block_height) * block_height;
5781
5782 Self {
5783 width,
5784 height,
5785 depth_or_array_layers: self.depth_or_array_layers,
5786 }
5787 }
5788
5789 /// Calculates the maximum possible count of mipmaps.
5790 ///
5791 /// Treats the depth as part of the mipmaps. If calculating
5792 /// for a 2DArray texture, which does not mipmap depth, set depth to 1.
5793 #[must_use]
5794 pub fn max_mips(&self, dim: TextureDimension) -> u32 {
5795 match dim {
5796 TextureDimension::D1 => 1,
5797 TextureDimension::D2 => {
5798 let max_dim = self.width.max(self.height);
5799 32 - max_dim.leading_zeros()
5800 }
5801 TextureDimension::D3 => {
5802 let max_dim = self.width.max(self.height.max(self.depth_or_array_layers));
5803 32 - max_dim.leading_zeros()
5804 }
5805 }
5806 }
5807
5808 /// Calculates the extent at a given mip level.
5809 /// Does *not* account for memory size being a multiple of block size.
5810 ///
5811 /// <https://gpuweb.github.io/gpuweb/#logical-miplevel-specific-texture-extent>
5812 #[must_use]
5813 pub fn mip_level_size(&self, level: u32, dim: TextureDimension) -> Self {
5814 Self {
5815 width: u32::max(1, self.width >> level),
5816 height: match dim {
5817 TextureDimension::D1 => 1,
5818 _ => u32::max(1, self.height >> level),
5819 },
5820 depth_or_array_layers: match dim {
5821 TextureDimension::D1 => 1,
5822 TextureDimension::D2 => self.depth_or_array_layers,
5823 TextureDimension::D3 => u32::max(1, self.depth_or_array_layers >> level),
5824 },
5825 }
5826 }
5827 }
5828
5829 #[test]
5830 fn test_physical_size() {
5831 let format = TextureFormat::Bc1RgbaUnormSrgb; // 4x4 blocks
5832 assert_eq!(
5833 Extent3d {
5834 width: 7,
5835 height: 7,
5836 depth_or_array_layers: 1
5837 }
5838 .physical_size(format),
5839 Extent3d {
5840 width: 8,
5841 height: 8,
5842 depth_or_array_layers: 1
5843 }
5844 );
5845 // Doesn't change, already aligned
5846 assert_eq!(
5847 Extent3d {
5848 width: 8,
5849 height: 8,
5850 depth_or_array_layers: 1
5851 }
5852 .physical_size(format),
5853 Extent3d {
5854 width: 8,
5855 height: 8,
5856 depth_or_array_layers: 1
5857 }
5858 );
5859 let format = TextureFormat::Astc {
5860 block: AstcBlock::B8x5,
5861 channel: AstcChannel::Unorm,
5862 }; // 8x5 blocks
5863 assert_eq!(
5864 Extent3d {
5865 width: 7,
5866 height: 7,
5867 depth_or_array_layers: 1
5868 }
5869 .physical_size(format),
5870 Extent3d {
5871 width: 8,
5872 height: 10,
5873 depth_or_array_layers: 1
5874 }
5875 );
5876 }
5877
5878 #[test]
5879 fn test_max_mips() {
5880 // 1D
5881 assert_eq!(
5882 Extent3d {
5883 width: 240,
5884 height: 1,
5885 depth_or_array_layers: 1
5886 }
5887 .max_mips(TextureDimension::D1),
5888 1
5889 );
5890 // 2D
5891 assert_eq!(
5892 Extent3d {
5893 width: 1,
5894 height: 1,
5895 depth_or_array_layers: 1
5896 }
5897 .max_mips(TextureDimension::D2),
5898 1
5899 );
5900 assert_eq!(
5901 Extent3d {
5902 width: 60,
5903 height: 60,
5904 depth_or_array_layers: 1
5905 }
5906 .max_mips(TextureDimension::D2),
5907 6
5908 );
5909 assert_eq!(
5910 Extent3d {
5911 width: 240,
5912 height: 1,
5913 depth_or_array_layers: 1000
5914 }
5915 .max_mips(TextureDimension::D2),
5916 8
5917 );
5918 // 3D
5919 assert_eq!(
5920 Extent3d {
5921 width: 16,
5922 height: 30,
5923 depth_or_array_layers: 60
5924 }
5925 .max_mips(TextureDimension::D3),
5926 6
5927 );
5928 }
5929
5930 /// Describes a [`TextureView`].
5931 ///
5932 /// For use with [`Texture::create_view()`].
5933 ///
5934 /// Corresponds to [WebGPU `GPUTextureViewDescriptor`](
5935 /// https://gpuweb.github.io/gpuweb/#dictdef-gputextureviewdescriptor).
5936 ///
5937 /// [`TextureView`]: ../wgpu/struct.TextureView.html
5938 /// [`Texture::create_view()`]: ../wgpu/struct.Texture.html#method.create_view
5939 #[derive(Clone, Debug, Default, Eq, PartialEq)]
5940 pub struct TextureViewDescriptor<L> {
5941 /// Debug label of the texture view. This will show up in graphics debuggers for easy identification.
5942 pub label: L,
5943 /// Format of the texture view. Either must be the same as the texture format or in the list
5944 /// of `view_formats` in the texture's descriptor.
5945 pub format: Option<TextureFormat>,
5946 /// The dimension of the texture view. For 1D textures, this must be `D1`. For 2D textures it must be one of
5947 /// `D2`, `D2Array`, `Cube`, and `CubeArray`. For 3D textures it must be `D3`
5948 pub dimension: Option<TextureViewDimension>,
5949 /// The allowed usage(s) for the texture view. Must be a subset of the usage flags of the texture.
5950 /// If not provided, defaults to the full set of usage flags of the texture.
5951 pub usage: Option<TextureUsages>,
5952 /// Aspect of the texture. Color textures must be [`TextureAspect::All`].
5953 pub aspect: TextureAspect,
5954 /// Base mip level.
5955 pub base_mip_level: u32,
5956 /// Mip level count.
5957 /// If `Some(count)`, `base_mip_level + count` must be less or equal to underlying texture mip count.
5958 /// If `None`, considered to include the rest of the mipmap levels, but at least 1 in total.
5959 pub mip_level_count: Option<u32>,
5960 /// Base array layer.
5961 pub base_array_layer: u32,
5962 /// Layer count.
5963 /// If `Some(count)`, `base_array_layer + count` must be less or equal to the underlying array count.
5964 /// If `None`, considered to include the rest of the array layers, but at least 1 in total.
5965 pub array_layer_count: Option<u32>,
5966 }
5967
5968 /// Describes a [`Texture`](../wgpu/struct.Texture.html).
5969 ///
5970 /// Corresponds to [WebGPU `GPUTextureDescriptor`](
5971 /// https://gpuweb.github.io/gpuweb/#dictdef-gputexturedescriptor).
5972 #[repr(C)]
5973 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
5974 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5975 pub struct TextureDescriptor<L, V> {
5976 /// Debug label of the texture. This will show up in graphics debuggers for easy identification.
5977 pub label: L,
5978 /// Size of the texture. All components must be greater than zero. For a
5979 /// regular 1D/2D texture, the unused sizes will be 1. For 2DArray textures,
5980 /// Z is the number of 2D textures in that array.
5981 pub size: Extent3d,
5982 /// Mip count of texture. For a texture with no extra mips, this must be 1.
5983 pub mip_level_count: u32,
5984 /// Sample count of texture. If this is not 1, texture must have [`BindingType::Texture::multisampled`] set to true.
5985 pub sample_count: u32,
5986 /// Dimensions of the texture.
5987 pub dimension: TextureDimension,
5988 /// Format of the texture.
5989 pub format: TextureFormat,
5990 /// Allowed usages of the texture. If used in other ways, the operation will panic.
5991 pub usage: TextureUsages,
5992 /// Specifies what view formats will be allowed when calling `Texture::create_view` on this texture.
5993 ///
5994 /// View formats of the same format as the texture are always allowed.
5995 ///
5996 /// Note: currently, only the srgb-ness is allowed to change. (ex: `Rgba8Unorm` texture + `Rgba8UnormSrgb` view)
5997 pub view_formats: V,
5998 }
5999
6000 impl<L, V> TextureDescriptor<L, V> {
6001 /// Takes a closure and maps the label of the texture descriptor into another.
6002 #[must_use]
6003 pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> TextureDescriptor<K, V>
6004 where
6005 V: Clone,
6006 {
6007 TextureDescriptor {
6008 label: fun(&self.label),
6009 size: self.size,
6010 mip_level_count: self.mip_level_count,
6011 sample_count: self.sample_count,
6012 dimension: self.dimension,
6013 format: self.format,
6014 usage: self.usage,
6015 view_formats: self.view_formats.clone(),
6016 }
6017 }
6018
6019 /// Maps the label and view formats of the texture descriptor into another.
6020 #[must_use]
6021 pub fn map_label_and_view_formats<K, M>(
6022 &self,
6023 l_fun: impl FnOnce(&L) -> K,
6024 v_fun: impl FnOnce(V) -> M,
6025 ) -> TextureDescriptor<K, M>
6026 where
6027 V: Clone,
6028 {
6029 TextureDescriptor {
6030 label: l_fun(&self.label),
6031 size: self.size,
6032 mip_level_count: self.mip_level_count,
6033 sample_count: self.sample_count,
6034 dimension: self.dimension,
6035 format: self.format,
6036 usage: self.usage,
6037 view_formats: v_fun(self.view_formats.clone()),
6038 }
6039 }
6040
6041 /// Calculates the extent at a given mip level.
6042 ///
6043 /// If the given mip level is larger than possible, returns None.
6044 ///
6045 /// Treats the depth as part of the mipmaps. If calculating
6046 /// for a 2DArray texture, which does not mipmap depth, set depth to 1.
6047 ///
6048 /// ```rust
6049 /// # use wgpu_types as wgpu;
6050 /// # type TextureDescriptor<'a> = wgpu::TextureDescriptor<(), &'a [wgpu::TextureFormat]>;
6051 /// let desc = TextureDescriptor {
6052 /// label: (),
6053 /// size: wgpu::Extent3d { width: 100, height: 60, depth_or_array_layers: 1 },
6054 /// mip_level_count: 7,
6055 /// sample_count: 1,
6056 /// dimension: wgpu::TextureDimension::D3,
6057 /// format: wgpu::TextureFormat::Rgba8Sint,
6058 /// usage: wgpu::TextureUsages::empty(),
6059 /// view_formats: &[],
6060 /// };
6061 ///
6062 /// assert_eq!(desc.mip_level_size(0), Some(wgpu::Extent3d { width: 100, height: 60, depth_or_array_layers: 1 }));
6063 /// assert_eq!(desc.mip_level_size(1), Some(wgpu::Extent3d { width: 50, height: 30, depth_or_array_layers: 1 }));
6064 /// assert_eq!(desc.mip_level_size(2), Some(wgpu::Extent3d { width: 25, height: 15, depth_or_array_layers: 1 }));
6065 /// assert_eq!(desc.mip_level_size(3), Some(wgpu::Extent3d { width: 12, height: 7, depth_or_array_layers: 1 }));
6066 /// assert_eq!(desc.mip_level_size(4), Some(wgpu::Extent3d { width: 6, height: 3, depth_or_array_layers: 1 }));
6067 /// assert_eq!(desc.mip_level_size(5), Some(wgpu::Extent3d { width: 3, height: 1, depth_or_array_layers: 1 }));
6068 /// assert_eq!(desc.mip_level_size(6), Some(wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }));
6069 /// assert_eq!(desc.mip_level_size(7), None);
6070 /// ```
6071 #[must_use]
6072 pub fn mip_level_size(&self, level: u32) -> Option<Extent3d> {
6073 if level >= self.mip_level_count {
6074 return None;
6075 }
6076
6077 Some(self.size.mip_level_size(level, self.dimension))
6078 }
6079
6080 /// Computes the render extent of this texture.
6081 ///
6082 /// <https://gpuweb.github.io/gpuweb/#abstract-opdef-compute-render-extent>
6083 #[must_use]
6084 pub fn compute_render_extent(&self, mip_level: u32) -> Extent3d {
6085 Extent3d {
6086 width: u32::max(1, self.size.width >> mip_level),
6087 height: u32::max(1, self.size.height >> mip_level),
6088 depth_or_array_layers: 1,
6089 }
6090 }
6091
6092 /// Returns the number of array layers.
6093 ///
6094 /// <https://gpuweb.github.io/gpuweb/#abstract-opdef-array-layer-count>
6095 #[must_use]
6096 pub fn array_layer_count(&self) -> u32 {
6097 match self.dimension {
6098 TextureDimension::D1 | TextureDimension::D3 => 1,
6099 TextureDimension::D2 => self.size.depth_or_array_layers,
6100 }
6101 }
6102 }
6103
6104 /// Describes a `Sampler`.
6105 ///
6106 /// For use with `Device::create_sampler`.
6107 ///
6108 /// Corresponds to [WebGPU `GPUSamplerDescriptor`](
6109 /// https://gpuweb.github.io/gpuweb/#dictdef-gpusamplerdescriptor).
6110 #[derive(Clone, Debug, PartialEq)]
6111 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6112 pub struct SamplerDescriptor<L> {
6113 /// Debug label of the sampler. This will show up in graphics debuggers for easy identification.
6114 pub label: L,
6115 /// How to deal with out of bounds accesses in the u (i.e. x) direction
6116 pub address_mode_u: AddressMode,
6117 /// How to deal with out of bounds accesses in the v (i.e. y) direction
6118 pub address_mode_v: AddressMode,
6119 /// How to deal with out of bounds accesses in the w (i.e. z) direction
6120 pub address_mode_w: AddressMode,
6121 /// How to filter the texture when it needs to be magnified (made larger)
6122 pub mag_filter: FilterMode,
6123 /// How to filter the texture when it needs to be minified (made smaller)
6124 pub min_filter: FilterMode,
6125 /// How to filter between mip map levels
6126 pub mipmap_filter: FilterMode,
6127 /// Minimum level of detail (i.e. mip level) to use
6128 pub lod_min_clamp: f32,
6129 /// Maximum level of detail (i.e. mip level) to use
6130 pub lod_max_clamp: f32,
6131 /// If this is enabled, this is a comparison sampler using the given comparison function.
6132 pub compare: Option<CompareFunction>,
6133 /// Must be at least 1. If this is not 1, all filter modes must be linear.
6134 pub anisotropy_clamp: u16,
6135 /// Border color to use when `address_mode` is [`AddressMode::ClampToBorder`]
6136 pub border_color: Option<SamplerBorderColor>,
6137 }
6138
6139 impl<L: Default> Default for SamplerDescriptor<L> {
6140 fn default() -> Self {
6141 Self {
6142 label: Default::default(),
6143 address_mode_u: Default::default(),
6144 address_mode_v: Default::default(),
6145 address_mode_w: Default::default(),
6146 mag_filter: Default::default(),
6147 min_filter: Default::default(),
6148 mipmap_filter: Default::default(),
6149 lod_min_clamp: 0.0,
6150 lod_max_clamp: 32.0,
6151 compare: None,
6152 anisotropy_clamp: 1,
6153 border_color: None,
6154 }
6155 }
6156 }
6157
6158 /// Selects a subset of the data a [`Texture`] holds.
6159 ///
6160 /// Used in [texture views](TextureViewDescriptor) and
6161 /// [texture copy operations](TexelCopyTextureInfo).
6162 ///
6163 /// Corresponds to [WebGPU `GPUTextureAspect`](
6164 /// https://gpuweb.github.io/gpuweb/#enumdef-gputextureaspect).
6165 ///
6166 /// [`Texture`]: ../wgpu/struct.Texture.html
6167 #[repr(C)]
6168 #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
6169 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6170 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
6171 pub enum TextureAspect {
6172 /// Depth, Stencil, and Color.
6173 #[default]
6174 All,
6175 /// Stencil.
6176 StencilOnly,
6177 /// Depth.
6178 DepthOnly,
6179 /// Plane 0.
6180 Plane0,
6181 /// Plane 1.
6182 Plane1,
6183 /// Plane 2.
6184 Plane2,
6185 }
6186
6187 /// How edges should be handled in texture addressing.
6188 ///
6189 /// Corresponds to [WebGPU `GPUAddressMode`](
6190 /// https://gpuweb.github.io/gpuweb/#enumdef-gpuaddressmode).
6191 #[repr(C)]
6192 #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
6193 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6194 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
6195 pub enum AddressMode {
6196 /// Clamp the value to the edge of the texture
6197 ///
6198 /// -0.25 -> 0.0
6199 /// 1.25 -> 1.0
6200 #[default]
6201 ClampToEdge = 0,
6202 /// Repeat the texture in a tiling fashion
6203 ///
6204 /// -0.25 -> 0.75
6205 /// 1.25 -> 0.25
6206 Repeat = 1,
6207 /// Repeat the texture, mirroring it every repeat
6208 ///
6209 /// -0.25 -> 0.25
6210 /// 1.25 -> 0.75
6211 MirrorRepeat = 2,
6212 /// Clamp the value to the border of the texture
6213 /// Requires feature [`Features::ADDRESS_MODE_CLAMP_TO_BORDER`]
6214 ///
6215 /// -0.25 -> border
6216 /// 1.25 -> border
6217 ClampToBorder = 3,
6218 }
6219
6220 /// Texel mixing mode when sampling between texels.
6221 ///
6222 /// Corresponds to [WebGPU `GPUFilterMode`](
6223 /// https://gpuweb.github.io/gpuweb/#enumdef-gpufiltermode).
6224 #[repr(C)]
6225 #[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)]
6226 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6227 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
6228 pub enum FilterMode {
6229 /// Nearest neighbor sampling.
6230 ///
6231 /// This creates a pixelated effect when used as a mag filter
6232 #[default]
6233 Nearest = 0,
6234 /// Linear Interpolation
6235 ///
6236 /// This makes textures smooth but blurry when used as a mag filter.
6237 Linear = 1,
6238 }
6239
6240 /// A range of push constant memory to pass to a shader stage.
6241 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
6242 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6243 pub struct PushConstantRange {
6244 /// Stage push constant range is visible from. Each stage can only be served by at most one range.
6245 /// One range can serve multiple stages however.
6246 pub stages: ShaderStages,
6247 /// Range in push constant memory to use for the stage. Must be less than [`Limits::max_push_constant_size`].
6248 /// Start and end must be aligned to the 4s.
6249 pub range: Range<u32>,
6250 }
6251
6252 /// Describes a [`CommandBuffer`](../wgpu/struct.CommandBuffer.html).
6253 ///
6254 /// Corresponds to [WebGPU `GPUCommandBufferDescriptor`](
6255 /// https://gpuweb.github.io/gpuweb/#dictdef-gpucommandbufferdescriptor).
6256 #[repr(C)]
6257 #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
6258 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6259 pub struct CommandBufferDescriptor<L> {
6260 /// Debug label of this command buffer.
6261 pub label: L,
6262 }
6263
6264 impl<L> CommandBufferDescriptor<L> {
6265 /// Takes a closure and maps the label of the command buffer descriptor into another.
6266 #[must_use]
6267 pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> CommandBufferDescriptor<K> {
6268 CommandBufferDescriptor {
6269 label: fun(&self.label),
6270 }
6271 }
6272 }
6273
6274 /// Describes the depth/stencil attachment for render bundles.
6275 ///
6276 /// Corresponds to a portion of [WebGPU `GPURenderBundleEncoderDescriptor`](
6277 /// https://gpuweb.github.io/gpuweb/#dictdef-gpurenderbundleencoderdescriptor).
6278 #[repr(C)]
6279 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6280 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6281 pub struct RenderBundleDepthStencil {
6282 /// Format of the attachment.
6283 pub format: TextureFormat,
6284 /// If the depth aspect of the depth stencil attachment is going to be written to.
6285 ///
6286 /// This must match the [`RenderPassDepthStencilAttachment::depth_ops`] of the renderpass this render bundle is executed in.
6287 /// If `depth_ops` is `Some(..)` this must be false. If it is `None` this must be true.
6288 ///
6289 /// [`RenderPassDepthStencilAttachment::depth_ops`]: ../wgpu/struct.RenderPassDepthStencilAttachment.html#structfield.depth_ops
6290 pub depth_read_only: bool,
6291
6292 /// If the stencil aspect of the depth stencil attachment is going to be written to.
6293 ///
6294 /// This must match the [`RenderPassDepthStencilAttachment::stencil_ops`] of the renderpass this render bundle is executed in.
6295 /// If `depth_ops` is `Some(..)` this must be false. If it is `None` this must be true.
6296 ///
6297 /// [`RenderPassDepthStencilAttachment::stencil_ops`]: ../wgpu/struct.RenderPassDepthStencilAttachment.html#structfield.stencil_ops
6298 pub stencil_read_only: bool,
6299 }
6300
6301 /// Describes a [`RenderBundle`](../wgpu/struct.RenderBundle.html).
6302 ///
6303 /// Corresponds to [WebGPU `GPURenderBundleDescriptor`](
6304 /// https://gpuweb.github.io/gpuweb/#dictdef-gpurenderbundledescriptor).
6305 #[repr(C)]
6306 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
6307 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6308 pub struct RenderBundleDescriptor<L> {
6309 /// Debug label of the render bundle encoder. This will show up in graphics debuggers for easy identification.
6310 pub label: L,
6311 }
6312
6313 impl<L> RenderBundleDescriptor<L> {
6314 /// Takes a closure and maps the label of the render bundle descriptor into another.
6315 #[must_use]
6316 pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> RenderBundleDescriptor<K> {
6317 RenderBundleDescriptor {
6318 label: fun(&self.label),
6319 }
6320 }
6321 }
6322
6323 impl<T> Default for RenderBundleDescriptor<Option<T>> {
6324 fn default() -> Self {
6325 Self { label: None }
6326 }
6327 }
6328
6329 /// Layout of a texture in a buffer's memory.
6330 ///
6331 /// The bytes per row and rows per image can be hard to figure out so here are some examples:
6332 ///
6333 /// | Resolution | Format | Bytes per block | Pixels per block | Bytes per row | Rows per image |
6334 /// |------------|--------|-----------------|------------------|----------------------------------------|------------------------------|
6335 /// | 256x256 | RGBA8 | 4 | 1 * 1 * 1 | 256 * 4 = Some(1024) | None |
6336 /// | 32x16x8 | RGBA8 | 4 | 1 * 1 * 1 | 32 * 4 = 128 padded to 256 = Some(256) | None |
6337 /// | 256x256 | BC3 | 16 | 4 * 4 * 1 | 16 * (256 / 4) = 1024 = Some(1024) | None |
6338 /// | 64x64x8 | BC3 | 16 | 4 * 4 * 1 | 16 * (64 / 4) = 256 = Some(256) | 64 / 4 = 16 = Some(16) |
6339 ///
6340 /// Corresponds to [WebGPU `GPUTexelCopyBufferLayout`](
6341 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagedatalayout).
6342 #[repr(C)]
6343 #[derive(Clone, Copy, Debug, Default)]
6344 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6345 pub struct TexelCopyBufferLayout {
6346 /// Offset into the buffer that is the start of the texture. Must be a multiple of texture block size.
6347 /// For non-compressed textures, this is 1.
6348 pub offset: BufferAddress,
6349 /// Bytes per "row" in an image.
6350 ///
6351 /// A row is one row of pixels or of compressed blocks in the x direction.
6352 ///
6353 /// This value is required if there are multiple rows (i.e. height or depth is more than one pixel or pixel block for compressed textures)
6354 ///
6355 /// Must be a multiple of 256 for [`CommandEncoder::copy_buffer_to_texture`][CEcbtt]
6356 /// and [`CommandEncoder::copy_texture_to_buffer`][CEcttb]. You must manually pad the
6357 /// image such that this is a multiple of 256. It will not affect the image data.
6358 ///
6359 /// [`Queue::write_texture`][Qwt] does not have this requirement.
6360 ///
6361 /// Must be a multiple of the texture block size. For non-compressed textures, this is 1.
6362 ///
6363 /// [CEcbtt]: ../wgpu/struct.CommandEncoder.html#method.copy_buffer_to_texture
6364 /// [CEcttb]: ../wgpu/struct.CommandEncoder.html#method.copy_texture_to_buffer
6365 /// [Qwt]: ../wgpu/struct.Queue.html#method.write_texture
6366 pub bytes_per_row: Option<u32>,
6367 /// "Rows" that make up a single "image".
6368 ///
6369 /// A row is one row of pixels or of compressed blocks in the x direction.
6370 ///
6371 /// An image is one layer in the z direction of a 3D image or 2DArray texture.
6372 ///
6373 /// The amount of rows per image may be larger than the actual amount of rows of data.
6374 ///
6375 /// Required if there are multiple images (i.e. the depth is more than one).
6376 pub rows_per_image: Option<u32>,
6377 }
6378
6379 /// Old name for a [`TexelCopyBufferLayout`].
6380 #[deprecated(
6381 since = "24.0.0",
6382 note = "This has been renamed to `TexelCopyBufferLayout`, and will be removed in 25.0.0."
6383 )]
6384 pub type ImageDataLayout = TexelCopyBufferLayout;
6385
6386 /// Specific type of a buffer binding.
6387 ///
6388 /// Corresponds to [WebGPU `GPUBufferBindingType`](
6389 /// https://gpuweb.github.io/gpuweb/#enumdef-gpubufferbindingtype).
6390 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
6391 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6392 pub enum BufferBindingType {
6393 /// A buffer for uniform values.
6394 ///
6395 /// Example WGSL syntax:
6396 /// ```rust,ignore
6397 /// struct Globals {
6398 /// a_uniform: vec2<f32>,
6399 /// another_uniform: vec2<f32>,
6400 /// }
6401 /// @group(0) @binding(0)
6402 /// var<uniform> globals: Globals;
6403 /// ```
6404 ///
6405 /// Example GLSL syntax:
6406 /// ```cpp,ignore
6407 /// layout(std140, binding = 0)
6408 /// uniform Globals {
6409 /// vec2 aUniform;
6410 /// vec2 anotherUniform;
6411 /// };
6412 /// ```
6413 #[default]
6414 Uniform,
6415 /// A storage buffer.
6416 ///
6417 /// Example WGSL syntax:
6418 /// ```rust,ignore
6419 /// @group(0) @binding(0)
6420 /// var<storage, read_write> my_element: array<vec4<f32>>;
6421 /// ```
6422 ///
6423 /// Example GLSL syntax:
6424 /// ```cpp,ignore
6425 /// layout (set=0, binding=0) buffer myStorageBuffer {
6426 /// vec4 myElement[];
6427 /// };
6428 /// ```
6429 Storage {
6430 /// If `true`, the buffer can only be read in the shader,
6431 /// and it:
6432 /// - may or may not be annotated with `read` (WGSL).
6433 /// - must be annotated with `readonly` (GLSL).
6434 ///
6435 /// Example WGSL syntax:
6436 /// ```rust,ignore
6437 /// @group(0) @binding(0)
6438 /// var<storage, read> my_element: array<vec4<f32>>;
6439 /// ```
6440 ///
6441 /// Example GLSL syntax:
6442 /// ```cpp,ignore
6443 /// layout (set=0, binding=0) readonly buffer myStorageBuffer {
6444 /// vec4 myElement[];
6445 /// };
6446 /// ```
6447 read_only: bool,
6448 },
6449 }
6450
6451 /// Specific type of a sample in a texture binding.
6452 ///
6453 /// Corresponds to [WebGPU `GPUTextureSampleType`](
6454 /// https://gpuweb.github.io/gpuweb/#enumdef-gputexturesampletype).
6455 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
6456 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6457 pub enum TextureSampleType {
6458 /// Sampling returns floats.
6459 ///
6460 /// Example WGSL syntax:
6461 /// ```rust,ignore
6462 /// @group(0) @binding(0)
6463 /// var t: texture_2d<f32>;
6464 /// ```
6465 ///
6466 /// Example GLSL syntax:
6467 /// ```cpp,ignore
6468 /// layout(binding = 0)
6469 /// uniform texture2D t;
6470 /// ```
6471 Float {
6472 /// If this is `false`, the texture can't be sampled with
6473 /// a filtering sampler.
6474 ///
6475 /// Even if this is `true`, it's possible to sample with
6476 /// a **non-filtering** sampler.
6477 filterable: bool,
6478 },
6479 /// Sampling does the depth reference comparison.
6480 ///
6481 /// This is also compatible with a non-filtering sampler.
6482 ///
6483 /// Example WGSL syntax:
6484 /// ```rust,ignore
6485 /// @group(0) @binding(0)
6486 /// var t: texture_depth_2d;
6487 /// ```
6488 ///
6489 /// Example GLSL syntax:
6490 /// ```cpp,ignore
6491 /// layout(binding = 0)
6492 /// uniform texture2DShadow t;
6493 /// ```
6494 Depth,
6495 /// Sampling returns signed integers.
6496 ///
6497 /// Example WGSL syntax:
6498 /// ```rust,ignore
6499 /// @group(0) @binding(0)
6500 /// var t: texture_2d<i32>;
6501 /// ```
6502 ///
6503 /// Example GLSL syntax:
6504 /// ```cpp,ignore
6505 /// layout(binding = 0)
6506 /// uniform itexture2D t;
6507 /// ```
6508 Sint,
6509 /// Sampling returns unsigned integers.
6510 ///
6511 /// Example WGSL syntax:
6512 /// ```rust,ignore
6513 /// @group(0) @binding(0)
6514 /// var t: texture_2d<u32>;
6515 /// ```
6516 ///
6517 /// Example GLSL syntax:
6518 /// ```cpp,ignore
6519 /// layout(binding = 0)
6520 /// uniform utexture2D t;
6521 /// ```
6522 Uint,
6523 }
6524
6525 impl Default for TextureSampleType {
6526 fn default() -> Self {
6527 Self::Float { filterable: true }
6528 }
6529 }
6530
6531 /// Specific type of a sample in a texture binding.
6532 ///
6533 /// For use in [`BindingType::StorageTexture`].
6534 ///
6535 /// Corresponds to [WebGPU `GPUStorageTextureAccess`](
6536 /// https://gpuweb.github.io/gpuweb/#enumdef-gpustoragetextureaccess).
6537 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
6538 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6539 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
6540 pub enum StorageTextureAccess {
6541 /// The texture can only be written in the shader and it:
6542 /// - may or may not be annotated with `write` (WGSL).
6543 /// - must be annotated with `writeonly` (GLSL).
6544 ///
6545 /// Example WGSL syntax:
6546 /// ```rust,ignore
6547 /// @group(0) @binding(0)
6548 /// var my_storage_image: texture_storage_2d<r32float, write>;
6549 /// ```
6550 ///
6551 /// Example GLSL syntax:
6552 /// ```cpp,ignore
6553 /// layout(set=0, binding=0, r32f) writeonly uniform image2D myStorageImage;
6554 /// ```
6555 WriteOnly,
6556 /// The texture can only be read in the shader and it must be annotated with `read` (WGSL) or
6557 /// `readonly` (GLSL).
6558 ///
6559 /// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] must be enabled to use this access
6560 /// mode. This is a native-only extension.
6561 ///
6562 /// Example WGSL syntax:
6563 /// ```rust,ignore
6564 /// @group(0) @binding(0)
6565 /// var my_storage_image: texture_storage_2d<r32float, read>;
6566 /// ```
6567 ///
6568 /// Example GLSL syntax:
6569 /// ```cpp,ignore
6570 /// layout(set=0, binding=0, r32f) readonly uniform image2D myStorageImage;
6571 /// ```
6572 ReadOnly,
6573 /// The texture can be both read and written in the shader and must be annotated with
6574 /// `read_write` in WGSL.
6575 ///
6576 /// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] must be enabled to use this access
6577 /// mode. This is a nonstandard, native-only extension.
6578 ///
6579 /// Example WGSL syntax:
6580 /// ```rust,ignore
6581 /// @group(0) @binding(0)
6582 /// var my_storage_image: texture_storage_2d<r32float, read_write>;
6583 /// ```
6584 ///
6585 /// Example GLSL syntax:
6586 /// ```cpp,ignore
6587 /// layout(set=0, binding=0, r32f) uniform image2D myStorageImage;
6588 /// ```
6589 ReadWrite,
6590 /// The texture can be both read and written in the shader via atomics and must be annotated
6591 /// with `read_write` in WGSL.
6592 ///
6593 /// [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] must be enabled to use this access
6594 /// mode. This is a nonstandard, native-only extension.
6595 ///
6596 /// Example WGSL syntax:
6597 /// ```rust,ignore
6598 /// @group(0) @binding(0)
6599 /// var my_storage_image: texture_storage_2d<r32uint, atomic>;
6600 /// ```
6601 Atomic,
6602 }
6603
6604 /// Specific type of a sampler binding.
6605 ///
6606 /// For use in [`BindingType::Sampler`].
6607 ///
6608 /// Corresponds to [WebGPU `GPUSamplerBindingType`](
6609 /// https://gpuweb.github.io/gpuweb/#enumdef-gpusamplerbindingtype).
6610 #[repr(C)]
6611 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
6612 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6613 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
6614 pub enum SamplerBindingType {
6615 /// The sampling result is produced based on more than a single color sample from a texture,
6616 /// e.g. when bilinear interpolation is enabled.
6617 Filtering,
6618 /// The sampling result is produced based on a single color sample from a texture.
6619 NonFiltering,
6620 /// Use as a comparison sampler instead of a normal sampler.
6621 /// For more info take a look at the analogous functionality in OpenGL: <https://www.khronos.org/opengl/wiki/Sampler_Object#Comparison_mode>.
6622 Comparison,
6623 }
6624
6625 /// Type of a binding in a [bind group layout][`BindGroupLayoutEntry`].
6626 ///
6627 /// For each binding in a layout, a [`BindGroup`] must provide a [`BindingResource`] of the
6628 /// corresponding type.
6629 ///
6630 /// Corresponds to WebGPU's mutually exclusive fields within [`GPUBindGroupLayoutEntry`](
6631 /// https://gpuweb.github.io/gpuweb/#dictdef-gpubindgrouplayoutentry).
6632 ///
6633 /// [`BindingResource`]: ../wgpu/enum.BindingResource.html
6634 /// [`BindGroup`]: ../wgpu/struct.BindGroup.html
6635 #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
6636 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6637 pub enum BindingType {
6638 /// A buffer binding.
6639 ///
6640 /// Corresponds to [WebGPU `GPUBufferBindingLayout`](
6641 /// https://gpuweb.github.io/gpuweb/#dictdef-gpubufferbindinglayout).
6642 Buffer {
6643 /// Sub-type of the buffer binding.
6644 ty: BufferBindingType,
6645
6646 /// Indicates that the binding has a dynamic offset.
6647 ///
6648 /// One offset must be passed to [`RenderPass::set_bind_group`][RPsbg]
6649 /// for each dynamic binding in increasing order of binding number.
6650 ///
6651 /// [RPsbg]: ../wgpu/struct.RenderPass.html#method.set_bind_group
6652 #[cfg_attr(feature = "serde", serde(default))]
6653 has_dynamic_offset: bool,
6654
6655 /// The minimum size for a [`BufferBinding`] matching this entry, in bytes.
6656 ///
6657 /// If this is `Some(size)`:
6658 ///
6659 /// - When calling [`create_bind_group`], the resource at this bind point
6660 /// must be a [`BindingResource::Buffer`] whose effective size is at
6661 /// least `size`.
6662 ///
6663 /// - When calling [`create_render_pipeline`] or [`create_compute_pipeline`],
6664 /// `size` must be at least the [minimum buffer binding size] for the
6665 /// shader module global at this bind point: large enough to hold the
6666 /// global's value, along with one element of a trailing runtime-sized
6667 /// array, if present.
6668 ///
6669 /// If this is `None`:
6670 ///
6671 /// - Each draw or dispatch command checks that the buffer range at this
6672 /// bind point satisfies the [minimum buffer binding size].
6673 ///
6674 /// [`BufferBinding`]: ../wgpu/struct.BufferBinding.html
6675 /// [`create_bind_group`]: ../wgpu/struct.Device.html#method.create_bind_group
6676 /// [`BindingResource::Buffer`]: ../wgpu/enum.BindingResource.html#variant.Buffer
6677 /// [minimum buffer binding size]: https://www.w3.org/TR/webgpu/#minimum-buffer-binding-size
6678 /// [`create_render_pipeline`]: ../wgpu/struct.Device.html#method.create_render_pipeline
6679 /// [`create_compute_pipeline`]: ../wgpu/struct.Device.html#method.create_compute_pipeline
6680 #[cfg_attr(feature = "serde", serde(default))]
6681 min_binding_size: Option<BufferSize>,
6682 },
6683 /// A sampler that can be used to sample a texture.
6684 ///
6685 /// Example WGSL syntax:
6686 /// ```rust,ignore
6687 /// @group(0) @binding(0)
6688 /// var s: sampler;
6689 /// ```
6690 ///
6691 /// Example GLSL syntax:
6692 /// ```cpp,ignore
6693 /// layout(binding = 0)
6694 /// uniform sampler s;
6695 /// ```
6696 ///
6697 /// Corresponds to [WebGPU `GPUSamplerBindingLayout`](
6698 /// https://gpuweb.github.io/gpuweb/#dictdef-gpusamplerbindinglayout).
6699 Sampler(SamplerBindingType),
6700 /// A texture binding.
6701 ///
6702 /// Example WGSL syntax:
6703 /// ```rust,ignore
6704 /// @group(0) @binding(0)
6705 /// var t: texture_2d<f32>;
6706 /// ```
6707 ///
6708 /// Example GLSL syntax:
6709 /// ```cpp,ignore
6710 /// layout(binding = 0)
6711 /// uniform texture2D t;
6712 /// ```
6713 ///
6714 /// Corresponds to [WebGPU `GPUTextureBindingLayout`](
6715 /// https://gpuweb.github.io/gpuweb/#dictdef-gputexturebindinglayout).
6716 Texture {
6717 /// Sample type of the texture binding.
6718 sample_type: TextureSampleType,
6719 /// Dimension of the texture view that is going to be sampled.
6720 view_dimension: TextureViewDimension,
6721 /// True if the texture has a sample count greater than 1. If this is true,
6722 /// the texture must be declared as `texture_multisampled_2d` or
6723 /// `texture_depth_multisampled_2d` in the shader, and read using `textureLoad`.
6724 multisampled: bool,
6725 },
6726 /// A storage texture.
6727 ///
6728 /// Example WGSL syntax:
6729 /// ```rust,ignore
6730 /// @group(0) @binding(0)
6731 /// var my_storage_image: texture_storage_2d<r32float, write>;
6732 /// ```
6733 ///
6734 /// Example GLSL syntax:
6735 /// ```cpp,ignore
6736 /// layout(set=0, binding=0, r32f) writeonly uniform image2D myStorageImage;
6737 /// ```
6738 /// Note that the texture format must be specified in the shader, along with the
6739 /// access mode. For WGSL, the format must be one of the enumerants in the list
6740 /// of [storage texel formats](https://gpuweb.github.io/gpuweb/wgsl/#storage-texel-formats).
6741 ///
6742 /// Corresponds to [WebGPU `GPUStorageTextureBindingLayout`](
6743 /// https://gpuweb.github.io/gpuweb/#dictdef-gpustoragetexturebindinglayout).
6744 StorageTexture {
6745 /// Allowed access to this texture.
6746 access: StorageTextureAccess,
6747 /// Format of the texture.
6748 format: TextureFormat,
6749 /// Dimension of the texture view that is going to be sampled.
6750 view_dimension: TextureViewDimension,
6751 },
6752
6753 /// A ray-tracing acceleration structure binding.
6754 ///
6755 /// Example WGSL syntax:
6756 /// ```rust,ignore
6757 /// @group(0) @binding(0)
6758 /// var as: acceleration_structure;
6759 /// ```
6760 ///
6761 /// or with vertex return enabled
6762 /// ```rust,ignore
6763 /// @group(0) @binding(0)
6764 /// var as: acceleration_structure<vertex_return>;
6765 /// ```
6766 ///
6767 /// Example GLSL syntax:
6768 /// ```cpp,ignore
6769 /// layout(binding = 0)
6770 /// uniform accelerationStructureEXT as;
6771 /// ```
6772 AccelerationStructure {
6773 /// Whether this acceleration structure can be used to
6774 /// create a ray query that has flag vertex return in the shader
6775 ///
6776 /// If enabled requires [`Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN`]
6777 vertex_return: bool,
6778 },
6779 }
6780
6781 impl BindingType {
6782 /// Returns true for buffer bindings with dynamic offset enabled.
6783 #[must_use]
6784 pub fn has_dynamic_offset(&self) -> bool {
6785 match *self {
6786 Self::Buffer {
6787 has_dynamic_offset, ..
6788 } => has_dynamic_offset,
6789 _ => false,
6790 }
6791 }
6792 }
6793
6794 /// Describes a single binding inside a bind group.
6795 ///
6796 /// Corresponds to [WebGPU `GPUBindGroupLayoutEntry`](
6797 /// https://gpuweb.github.io/gpuweb/#dictdef-gpubindgrouplayoutentry).
6798 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6799 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6800 pub struct BindGroupLayoutEntry {
6801 /// Binding index. Must match shader index and be unique inside a `BindGroupLayout`. A binding
6802 /// of index 1, would be described as `@group(0) @binding(1)` in shaders.
6803 pub binding: u32,
6804 /// Which shader stages can see this binding.
6805 pub visibility: ShaderStages,
6806 /// The type of the binding
6807 pub ty: BindingType,
6808 /// If the binding is an array of multiple resources. Corresponds to `binding_array<T>` in the shader.
6809 ///
6810 /// When this is `Some` the following validation applies:
6811 /// - Size must be of value 1 or greater.
6812 /// - When `ty == BindingType::Texture`, [`Features::TEXTURE_BINDING_ARRAY`] must be supported.
6813 /// - When `ty == BindingType::Sampler`, [`Features::TEXTURE_BINDING_ARRAY`] must be supported.
6814 /// - When `ty == BindingType::Buffer`, [`Features::BUFFER_BINDING_ARRAY`] must be supported.
6815 /// - When `ty == BindingType::Buffer` and `ty.ty == BufferBindingType::Storage`, [`Features::STORAGE_RESOURCE_BINDING_ARRAY`] must be supported.
6816 /// - When `ty == BindingType::StorageTexture`, [`Features::STORAGE_RESOURCE_BINDING_ARRAY`] must be supported.
6817 /// - When any binding in the group is an array, no `BindingType::Buffer` in the group may have `has_dynamic_offset == true`
6818 /// - When any binding in the group is an array, no `BindingType::Buffer` in the group may have `ty.ty == BufferBindingType::Uniform`.
6819 ///
6820 #[cfg_attr(feature = "serde", serde(default))]
6821 pub count: Option<NonZeroU32>,
6822 }
6823
6824 /// View of a buffer which can be used to copy to/from a texture.
6825 ///
6826 /// Corresponds to [WebGPU `GPUTexelCopyBufferInfo`](
6827 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagecopybuffer).
6828 #[repr(C)]
6829 #[derive(Copy, Clone, Debug)]
6830 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6831 pub struct TexelCopyBufferInfo<B> {
6832 /// The buffer to be copied to/from.
6833 pub buffer: B,
6834 /// The layout of the texture data in this buffer.
6835 pub layout: TexelCopyBufferLayout,
6836 }
6837
6838 /// Old name for a [`TexelCopyBufferInfo`].
6839 #[deprecated(
6840 since = "24.0.0",
6841 note = "This has been renamed to `TexelCopyBufferInfo`, and will be removed in 25.0.0."
6842 )]
6843 pub type ImageCopyBuffer<B> = TexelCopyBufferInfo<B>;
6844
6845 /// View of a texture which can be used to copy to/from a buffer/texture.
6846 ///
6847 /// Corresponds to [WebGPU `GPUTexelCopyTextureInfo`](
6848 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagecopytexture).
6849 #[repr(C)]
6850 #[derive(Copy, Clone, Debug)]
6851 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6852 pub struct TexelCopyTextureInfo<T> {
6853 /// The texture to be copied to/from.
6854 pub texture: T,
6855 /// The target mip level of the texture.
6856 pub mip_level: u32,
6857 /// The base texel of the texture in the selected `mip_level`. Together
6858 /// with the `copy_size` argument to copy functions, defines the
6859 /// sub-region of the texture to copy.
6860 #[cfg_attr(feature = "serde", serde(default))]
6861 pub origin: Origin3d,
6862 /// The copy aspect.
6863 #[cfg_attr(feature = "serde", serde(default))]
6864 pub aspect: TextureAspect,
6865 }
6866
6867 impl<T> TexelCopyTextureInfo<T> {
6868 /// Adds color space and premultiplied alpha information to make this
6869 /// descriptor tagged.
6870 pub fn to_tagged(
6871 self,
6872 color_space: PredefinedColorSpace,
6873 premultiplied_alpha: bool,
6874 ) -> CopyExternalImageDestInfo<T> {
6875 CopyExternalImageDestInfo {
6876 texture: self.texture,
6877 mip_level: self.mip_level,
6878 origin: self.origin,
6879 aspect: self.aspect,
6880 color_space,
6881 premultiplied_alpha,
6882 }
6883 }
6884 }
6885
6886 /// Old name for a [`TexelCopyTextureInfo`].
6887 #[deprecated(
6888 since = "24.0.0",
6889 note = "This has been renamed to `TexelCopyTextureInfo`, and will be removed in 25.0.0."
6890 )]
6891 pub type ImageCopyTexture<T> = TexelCopyTextureInfo<T>;
6892
6893 /// View of an external texture that can be used to copy to a texture.
6894 ///
6895 /// Corresponds to [WebGPU `GPUCopyExternalImageSourceInfo`](
6896 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagecopyexternalimage).
6897 #[cfg(target_arch = "wasm32")]
6898 #[derive(Clone, Debug)]
6899 pub struct CopyExternalImageSourceInfo {
6900 /// The texture to be copied from. The copy source data is captured at the moment
6901 /// the copy is issued.
6902 pub source: ExternalImageSource,
6903 /// The base texel used for copying from the external image. Together
6904 /// with the `copy_size` argument to copy functions, defines the
6905 /// sub-region of the image to copy.
6906 ///
6907 /// Relative to the top left of the image.
6908 ///
6909 /// Must be [`Origin2d::ZERO`] if [`DownlevelFlags::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES`] is not supported.
6910 pub origin: Origin2d,
6911 /// If the Y coordinate of the image should be flipped. Even if this is
6912 /// true, `origin` is still relative to the top left.
6913 pub flip_y: bool,
6914 }
6915
6916 /// Old name for a [`CopyExternalImageSourceInfo`].
6917 #[deprecated(
6918 since = "24.0.0",
6919 note = "This has been renamed to `CopyExternalImageSourceInfo`, and will be removed in 25.0.0."
6920 )]
6921 #[cfg(target_arch = "wasm32")]
6922 pub type ImageCopyExternalImage = CopyExternalImageSourceInfo;
6923
6924 /// Source of an external texture copy.
6925 ///
6926 /// Corresponds to the [implicit union type on WebGPU `GPUCopyExternalImageSourceInfo.source`](
6927 /// https://gpuweb.github.io/gpuweb/#dom-gpuimagecopyexternalimage-source).
6928 #[cfg(target_arch = "wasm32")]
6929 #[derive(Clone, Debug)]
6930 pub enum ExternalImageSource {
6931 /// Copy from a previously-decoded image bitmap.
6932 ImageBitmap(web_sys::ImageBitmap),
6933 /// Copy from an image element.
6934 HTMLImageElement(web_sys::HtmlImageElement),
6935 /// Copy from a current frame of a video element.
6936 HTMLVideoElement(web_sys::HtmlVideoElement),
6937 /// Copy from an image.
6938 ImageData(web_sys::ImageData),
6939 /// Copy from a on-screen canvas.
6940 HTMLCanvasElement(web_sys::HtmlCanvasElement),
6941 /// Copy from a off-screen canvas.
6942 ///
6943 /// Requires [`DownlevelFlags::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES`]
6944 OffscreenCanvas(web_sys::OffscreenCanvas),
6945 /// Copy from a video frame.
6946 #[cfg(web_sys_unstable_apis)]
6947 VideoFrame(web_sys::VideoFrame),
6948 }
6949
6950 #[cfg(target_arch = "wasm32")]
6951 impl ExternalImageSource {
6952 /// Gets the pixel, not css, width of the source.
6953 pub fn width(&self) -> u32 {
6954 match self {
6955 ExternalImageSource::ImageBitmap(b) => b.width(),
6956 ExternalImageSource::HTMLImageElement(i) => i.width(),
6957 ExternalImageSource::HTMLVideoElement(v) => v.video_width(),
6958 ExternalImageSource::ImageData(i) => i.width(),
6959 ExternalImageSource::HTMLCanvasElement(c) => c.width(),
6960 ExternalImageSource::OffscreenCanvas(c) => c.width(),
6961 #[cfg(web_sys_unstable_apis)]
6962 ExternalImageSource::VideoFrame(v) => v.display_width(),
6963 }
6964 }
6965
6966 /// Gets the pixel, not css, height of the source.
6967 pub fn height(&self) -> u32 {
6968 match self {
6969 ExternalImageSource::ImageBitmap(b) => b.height(),
6970 ExternalImageSource::HTMLImageElement(i) => i.height(),
6971 ExternalImageSource::HTMLVideoElement(v) => v.video_height(),
6972 ExternalImageSource::ImageData(i) => i.height(),
6973 ExternalImageSource::HTMLCanvasElement(c) => c.height(),
6974 ExternalImageSource::OffscreenCanvas(c) => c.height(),
6975 #[cfg(web_sys_unstable_apis)]
6976 ExternalImageSource::VideoFrame(v) => v.display_height(),
6977 }
6978 }
6979 }
6980
6981 #[cfg(target_arch = "wasm32")]
6982 impl core::ops::Deref for ExternalImageSource {
6983 type Target = js_sys::Object;
6984
6985 fn deref(&self) -> &Self::Target {
6986 match self {
6987 Self::ImageBitmap(b) => b,
6988 Self::HTMLImageElement(i) => i,
6989 Self::HTMLVideoElement(v) => v,
6990 Self::ImageData(i) => i,
6991 Self::HTMLCanvasElement(c) => c,
6992 Self::OffscreenCanvas(c) => c,
6993 #[cfg(web_sys_unstable_apis)]
6994 Self::VideoFrame(v) => v,
6995 }
6996 }
6997 }
6998
6999 #[cfg(all(
7000 target_arch = "wasm32",
7001 feature = "fragile-send-sync-non-atomic-wasm",
7002 not(target_feature = "atomics")
7003 ))]
7004 unsafe impl Send for ExternalImageSource {}
7005 #[cfg(all(
7006 target_arch = "wasm32",
7007 feature = "fragile-send-sync-non-atomic-wasm",
7008 not(target_feature = "atomics")
7009 ))]
7010 unsafe impl Sync for ExternalImageSource {}
7011
7012 /// Color spaces supported on the web.
7013 ///
7014 /// Corresponds to [HTML Canvas `PredefinedColorSpace`](
7015 /// https://html.spec.whatwg.org/multipage/canvas.html#predefinedcolorspace).
7016 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
7017 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7018 #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
7019 pub enum PredefinedColorSpace {
7020 /// sRGB color space
7021 Srgb,
7022 /// Display-P3 color space
7023 DisplayP3,
7024 }
7025
7026 /// View of a texture which can be used to copy to a texture, including
7027 /// color space and alpha premultiplication information.
7028 ///
7029 /// Corresponds to [WebGPU `GPUCopyExternalImageDestInfo`](
7030 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagecopytexturetagged).
7031 #[derive(Copy, Clone, Debug)]
7032 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7033 pub struct CopyExternalImageDestInfo<T> {
7034 /// The texture to be copied to/from.
7035 pub texture: T,
7036 /// The target mip level of the texture.
7037 pub mip_level: u32,
7038 /// The base texel of the texture in the selected `mip_level`.
7039 pub origin: Origin3d,
7040 /// The copy aspect.
7041 pub aspect: TextureAspect,
7042 /// The color space of this texture.
7043 pub color_space: PredefinedColorSpace,
7044 /// The premultiplication of this texture
7045 pub premultiplied_alpha: bool,
7046 }
7047
7048 impl<T> CopyExternalImageDestInfo<T> {
7049 /// Removes the colorspace information from the type.
7050 pub fn to_untagged(self) -> TexelCopyTextureInfo<T> {
7051 TexelCopyTextureInfo {
7052 texture: self.texture,
7053 mip_level: self.mip_level,
7054 origin: self.origin,
7055 aspect: self.aspect,
7056 }
7057 }
7058 }
7059
7060 /// Old name for a [`CopyExternalImageDestInfo`].
7061 #[deprecated(
7062 since = "24.0.0",
7063 note = "This has been renamed to `CopyExternalImageDestInfo`, and will be removed in 25.0.0."
7064 )]
7065 pub type ImageCopyTextureTagged<T> = CopyExternalImageDestInfo<T>;
7066
7067 /// Subresource range within an image
7068 #[repr(C)]
7069 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
7070 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7071 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
7072 pub struct ImageSubresourceRange {
7073 /// Aspect of the texture. Color textures must be [`TextureAspect::All`][TAA].
7074 ///
7075 /// [TAA]: ../wgpu/enum.TextureAspect.html#variant.All
7076 pub aspect: TextureAspect,
7077 /// Base mip level.
7078 pub base_mip_level: u32,
7079 /// Mip level count.
7080 /// If `Some(count)`, `base_mip_level + count` must be less or equal to underlying texture mip count.
7081 /// If `None`, considered to include the rest of the mipmap levels, but at least 1 in total.
7082 pub mip_level_count: Option<u32>,
7083 /// Base array layer.
7084 pub base_array_layer: u32,
7085 /// Layer count.
7086 /// If `Some(count)`, `base_array_layer + count` must be less or equal to the underlying array count.
7087 /// If `None`, considered to include the rest of the array layers, but at least 1 in total.
7088 pub array_layer_count: Option<u32>,
7089 }
7090
7091 impl ImageSubresourceRange {
7092 /// Returns if the given range represents a full resource, with a texture of the given
7093 /// layer count and mip count.
7094 ///
7095 /// ```rust
7096 /// # use wgpu_types as wgpu;
7097 ///
7098 /// let range_none = wgpu::ImageSubresourceRange {
7099 /// aspect: wgpu::TextureAspect::All,
7100 /// base_mip_level: 0,
7101 /// mip_level_count: None,
7102 /// base_array_layer: 0,
7103 /// array_layer_count: None,
7104 /// };
7105 /// assert_eq!(range_none.is_full_resource(wgpu::TextureFormat::Stencil8, 5, 10), true);
7106 ///
7107 /// let range_some = wgpu::ImageSubresourceRange {
7108 /// aspect: wgpu::TextureAspect::All,
7109 /// base_mip_level: 0,
7110 /// mip_level_count: Some(5),
7111 /// base_array_layer: 0,
7112 /// array_layer_count: Some(10),
7113 /// };
7114 /// assert_eq!(range_some.is_full_resource(wgpu::TextureFormat::Stencil8, 5, 10), true);
7115 ///
7116 /// let range_mixed = wgpu::ImageSubresourceRange {
7117 /// aspect: wgpu::TextureAspect::StencilOnly,
7118 /// base_mip_level: 0,
7119 /// // Only partial resource
7120 /// mip_level_count: Some(3),
7121 /// base_array_layer: 0,
7122 /// array_layer_count: None,
7123 /// };
7124 /// assert_eq!(range_mixed.is_full_resource(wgpu::TextureFormat::Stencil8, 5, 10), false);
7125 /// ```
7126 #[must_use]
7127 pub fn is_full_resource(
7128 &self,
7129 format: TextureFormat,
7130 mip_levels: u32,
7131 array_layers: u32,
7132 ) -> bool {
7133 // Mip level count and array layer count need to deal with both the None and Some(count) case.
7134 let mip_level_count = self.mip_level_count.unwrap_or(mip_levels);
7135 let array_layer_count = self.array_layer_count.unwrap_or(array_layers);
7136
7137 let aspect_eq = Some(format) == format.aspect_specific_format(self.aspect);
7138
7139 let base_mip_level_eq = self.base_mip_level == 0;
7140 let mip_level_count_eq = mip_level_count == mip_levels;
7141
7142 let base_array_layer_eq = self.base_array_layer == 0;
7143 let array_layer_count_eq = array_layer_count == array_layers;
7144
7145 aspect_eq
7146 && base_mip_level_eq
7147 && mip_level_count_eq
7148 && base_array_layer_eq
7149 && array_layer_count_eq
7150 }
7151
7152 /// Returns the mip level range of a subresource range describes for a specific texture.
7153 #[must_use]
7154 pub fn mip_range(&self, mip_level_count: u32) -> Range<u32> {
7155 self.base_mip_level..match self.mip_level_count {
7156 Some(mip_level_count) => self.base_mip_level + mip_level_count,
7157 None => mip_level_count,
7158 }
7159 }
7160
7161 /// Returns the layer range of a subresource range describes for a specific texture.
7162 #[must_use]
7163 pub fn layer_range(&self, array_layer_count: u32) -> Range<u32> {
7164 self.base_array_layer..match self.array_layer_count {
7165 Some(array_layer_count) => self.base_array_layer + array_layer_count,
7166 None => array_layer_count,
7167 }
7168 }
7169 }
7170
7171 /// Color variation to use when sampler addressing mode is [`AddressMode::ClampToBorder`]
7172 #[repr(C)]
7173 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
7174 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7175 pub enum SamplerBorderColor {
7176 /// [0, 0, 0, 0]
7177 TransparentBlack,
7178 /// [0, 0, 0, 1]
7179 OpaqueBlack,
7180 /// [1, 1, 1, 1]
7181 OpaqueWhite,
7182
7183 /// On the Metal backend, this is equivalent to `TransparentBlack` for
7184 /// textures that have an alpha component, and equivalent to `OpaqueBlack`
7185 /// for textures that do not have an alpha component. On other backends,
7186 /// this is equivalent to `TransparentBlack`. Requires
7187 /// [`Features::ADDRESS_MODE_CLAMP_TO_ZERO`]. Not supported on the web.
7188 Zero,
7189 }
7190
7191 /// Describes how to create a `QuerySet`.
7192 ///
7193 /// Corresponds to [WebGPU `GPUQuerySetDescriptor`](
7194 /// https://gpuweb.github.io/gpuweb/#dictdef-gpuquerysetdescriptor).
7195 #[derive(Clone, Debug)]
7196 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7197 pub struct QuerySetDescriptor<L> {
7198 /// Debug label for the query set.
7199 pub label: L,
7200 /// Kind of query that this query set should contain.
7201 pub ty: QueryType,
7202 /// Total count of queries the set contains. Must not be zero.
7203 /// Must not be greater than [`QUERY_SET_MAX_QUERIES`].
7204 pub count: u32,
7205 }
7206
7207 impl<L> QuerySetDescriptor<L> {
7208 /// Takes a closure and maps the label of the query set descriptor into another.
7209 #[must_use]
7210 pub fn map_label<'a, K>(&'a self, fun: impl FnOnce(&'a L) -> K) -> QuerySetDescriptor<K> {
7211 QuerySetDescriptor {
7212 label: fun(&self.label),
7213 ty: self.ty,
7214 count: self.count,
7215 }
7216 }
7217 }
7218
7219 /// Type of query contained in a [`QuerySet`].
7220 ///
7221 /// Corresponds to [WebGPU `GPUQueryType`](
7222 /// https://gpuweb.github.io/gpuweb/#enumdef-gpuquerytype).
7223 ///
7224 /// [`QuerySet`]: ../wgpu/struct.QuerySet.html
7225 #[derive(Copy, Clone, Debug)]
7226 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7227 pub enum QueryType {
7228 /// Query returns a single 64-bit number, serving as an occlusion boolean.
7229 Occlusion,
7230 /// Query returns up to 5 64-bit numbers based on the given flags.
7231 ///
7232 /// See [`PipelineStatisticsTypes`]'s documentation for more information
7233 /// on how they get resolved.
7234 ///
7235 /// [`Features::PIPELINE_STATISTICS_QUERY`] must be enabled to use this query type.
7236 PipelineStatistics(PipelineStatisticsTypes),
7237 /// Query returns a 64-bit number indicating the GPU-timestamp
7238 /// where all previous commands have finished executing.
7239 ///
7240 /// Must be multiplied by [`Queue::get_timestamp_period`][Qgtp] to get
7241 /// the value in nanoseconds. Absolute values have no meaning,
7242 /// but timestamps can be subtracted to get the time it takes
7243 /// for a string of operations to complete.
7244 ///
7245 /// [`Features::TIMESTAMP_QUERY`] must be enabled to use this query type.
7246 ///
7247 /// [Qgtp]: ../wgpu/struct.Queue.html#method.get_timestamp_period
7248 Timestamp,
7249 }
7250
7251 bitflags::bitflags! {
7252 /// Flags for which pipeline data should be recorded in a query.
7253 ///
7254 /// Used in [`QueryType`].
7255 ///
7256 /// The amount of values written when resolved depends
7257 /// on the amount of flags set. For example, if 3 flags are set, 3
7258 /// 64-bit values will be written per query.
7259 ///
7260 /// The order they are written is the order they are declared
7261 /// in these bitflags. For example, if you enabled `CLIPPER_PRIMITIVES_OUT`
7262 /// and `COMPUTE_SHADER_INVOCATIONS`, it would write 16 bytes,
7263 /// the first 8 bytes being the primitive out value, the last 8
7264 /// bytes being the compute shader invocation count.
7265 #[repr(transparent)]
7266 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7267 #[cfg_attr(feature = "serde", serde(transparent))]
7268 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
7269 pub struct PipelineStatisticsTypes : u8 {
7270 /// Amount of times the vertex shader is ran. Accounts for
7271 /// the vertex cache when doing indexed rendering.
7272 const VERTEX_SHADER_INVOCATIONS = 1 << 0;
7273 /// Amount of times the clipper is invoked. This
7274 /// is also the amount of triangles output by the vertex shader.
7275 const CLIPPER_INVOCATIONS = 1 << 1;
7276 /// Amount of primitives that are not culled by the clipper.
7277 /// This is the amount of triangles that are actually on screen
7278 /// and will be rasterized and rendered.
7279 const CLIPPER_PRIMITIVES_OUT = 1 << 2;
7280 /// Amount of times the fragment shader is ran. Accounts for
7281 /// fragment shaders running in 2x2 blocks in order to get
7282 /// derivatives.
7283 const FRAGMENT_SHADER_INVOCATIONS = 1 << 3;
7284 /// Amount of times a compute shader is invoked. This will
7285 /// be equivalent to the dispatch count times the workgroup size.
7286 const COMPUTE_SHADER_INVOCATIONS = 1 << 4;
7287 }
7288 }
7289
7290 /// Argument buffer layout for `draw_indirect` commands.
7291 #[repr(C)]
7292 #[derive(Copy, Clone, Debug, Default, Pod, Zeroable)]
7293 pub struct DrawIndirectArgs {
7294 /// The number of vertices to draw.
7295 pub vertex_count: u32,
7296 /// The number of instances to draw.
7297 pub instance_count: u32,
7298 /// The Index of the first vertex to draw.
7299 pub first_vertex: u32,
7300 /// The instance ID of the first instance to draw.
7301 ///
7302 /// Has to be 0, unless [`Features::INDIRECT_FIRST_INSTANCE`](crate::Features::INDIRECT_FIRST_INSTANCE) is enabled.
7303 pub first_instance: u32,
7304 }
7305
7306 impl DrawIndirectArgs {
7307 /// Returns the bytes representation of the struct, ready to be written in a buffer.
7308 #[must_use]
7309 pub fn as_bytes(&self) -> &[u8] {
7310 bytemuck::bytes_of(self)
7311 }
7312 }
7313
7314 /// Argument buffer layout for `draw_indexed_indirect` commands.
7315 #[repr(C)]
7316 #[derive(Copy, Clone, Debug, Default, Pod, Zeroable)]
7317 pub struct DrawIndexedIndirectArgs {
7318 /// The number of indices to draw.
7319 pub index_count: u32,
7320 /// The number of instances to draw.
7321 pub instance_count: u32,
7322 /// The first index within the index buffer.
7323 pub first_index: u32,
7324 /// The value added to the vertex index before indexing into the vertex buffer.
7325 pub base_vertex: i32,
7326 /// The instance ID of the first instance to draw.
7327 ///
7328 /// Has to be 0, unless [`Features::INDIRECT_FIRST_INSTANCE`](crate::Features::INDIRECT_FIRST_INSTANCE) is enabled.
7329 pub first_instance: u32,
7330 }
7331
7332 impl DrawIndexedIndirectArgs {
7333 /// Returns the bytes representation of the struct, ready to be written in a buffer.
7334 #[must_use]
7335 pub fn as_bytes(&self) -> &[u8] {
7336 bytemuck::bytes_of(self)
7337 }
7338 }
7339
7340 /// Argument buffer layout for `dispatch_indirect` commands.
7341 #[repr(C)]
7342 #[derive(Copy, Clone, Debug, Default, Pod, Zeroable)]
7343 pub struct DispatchIndirectArgs {
7344 /// The number of work groups in X dimension.
7345 pub x: u32,
7346 /// The number of work groups in Y dimension.
7347 pub y: u32,
7348 /// The number of work groups in Z dimension.
7349 pub z: u32,
7350 }
7351
7352 impl DispatchIndirectArgs {
7353 /// Returns the bytes representation of the struct, ready to be written into a buffer.
7354 #[must_use]
7355 pub fn as_bytes(&self) -> &[u8] {
7356 bytemuck::bytes_of(self)
7357 }
7358 }
7359
7360 /// Describes how shader bound checks should be performed.
7361 #[derive(Copy, Clone, Debug)]
7362 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7363 pub struct ShaderRuntimeChecks {
7364 /// Enforce bounds checks in shaders, even if the underlying driver doesn't
7365 /// support doing so natively.
7366 ///
7367 /// When this is `true`, `wgpu` promises that shaders can only read or
7368 /// write the accessible region of a bindgroup's buffer bindings. If
7369 /// the underlying graphics platform cannot implement these bounds checks
7370 /// itself, `wgpu` will inject bounds checks before presenting the
7371 /// shader to the platform.
7372 ///
7373 /// When this is `false`, `wgpu` only enforces such bounds checks if the
7374 /// underlying platform provides a way to do so itself. `wgpu` does not
7375 /// itself add any bounds checks to generated shader code.
7376 ///
7377 /// Note that `wgpu` users may try to initialize only those portions of
7378 /// buffers that they anticipate might be read from. Passing `false` here
7379 /// may allow shaders to see wider regions of the buffers than expected,
7380 /// making such deferred initialization visible to the application.
7381 pub bounds_checks: bool,
7382 ///
7383 /// If false, the caller MUST ensure that all passed shaders do not contain any infinite loops.
7384 ///
7385 /// If it does, backend compilers MAY treat such a loop as unreachable code and draw
7386 /// conclusions about other safety-critical code paths. This option SHOULD NOT be disabled
7387 /// when running untrusted code.
7388 pub force_loop_bounding: bool,
7389 }
7390
7391 impl ShaderRuntimeChecks {
7392 /// Creates a new configuration where the shader is fully checked.
7393 #[must_use]
7394 pub fn checked() -> Self {
7395 unsafe { Self::all(true) }
7396 }
7397
7398 /// Creates a new configuration where none of the checks are performed.
7399 ///
7400 /// # Safety
7401 ///
7402 /// See the documentation for the `set_*` methods for the safety requirements
7403 /// of each sub-configuration.
7404 #[must_use]
7405 pub fn unchecked() -> Self {
7406 unsafe { Self::all(false) }
7407 }
7408
7409 /// Creates a new configuration where all checks are enabled or disabled. To safely
7410 /// create a configuration with all checks enabled, use [`ShaderRuntimeChecks::checked`].
7411 ///
7412 /// # Safety
7413 ///
7414 /// See the documentation for the `set_*` methods for the safety requirements
7415 /// of each sub-configuration.
7416 #[must_use]
7417 pub unsafe fn all(all_checks: bool) -> Self {
7418 Self {
7419 bounds_checks: all_checks,
7420 force_loop_bounding: all_checks,
7421 }
7422 }
7423 }
7424
7425 impl Default for ShaderRuntimeChecks {
7426 fn default() -> Self {
7427 Self::checked()
7428 }
7429 }
7430
7431 #[derive(Clone, Debug, PartialEq, Eq)]
7432 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7433 /// Descriptor for all size defining attributes of a single triangle geometry inside a bottom level acceleration structure.
7434 pub struct BlasTriangleGeometrySizeDescriptor {
7435 /// Format of a vertex position, must be [`VertexFormat::Float32x3`]
7436 /// with just [`Features::EXPERIMENTAL_RAY_TRACING_ACCELERATION_STRUCTURE`]
7437 /// but later features may add more formats.
7438 pub vertex_format: VertexFormat,
7439 /// Number of vertices.
7440 pub vertex_count: u32,
7441 /// Format of an index. Only needed if an index buffer is used.
7442 /// If `index_format` is provided `index_count` is required.
7443 pub index_format: Option<IndexFormat>,
7444 /// Number of indices. Only needed if an index buffer is used.
7445 /// If `index_count` is provided `index_format` is required.
7446 pub index_count: Option<u32>,
7447 /// Flags for the geometry.
7448 pub flags: AccelerationStructureGeometryFlags,
7449 }
7450
7451 #[derive(Clone, Debug)]
7452 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7453 /// Descriptor for all size defining attributes of all geometries inside a bottom level acceleration structure.
7454 pub enum BlasGeometrySizeDescriptors {
7455 /// Triangle geometry version.
7456 Triangles {
7457 /// Descriptor for each triangle geometry.
7458 descriptors: Vec<BlasTriangleGeometrySizeDescriptor>,
7459 },
7460 }
7461
7462 #[repr(u8)]
7463 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
7464 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7465 /// Update mode for acceleration structure builds.
7466 pub enum AccelerationStructureUpdateMode {
7467 /// Always perform a full build.
7468 Build,
7469 /// If possible, perform an incremental update.
7470 ///
7471 /// Not advised for major topology changes.
7472 /// (Useful for e.g. skinning)
7473 PreferUpdate,
7474 }
7475
7476 #[repr(C)]
7477 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
7478 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7479 /// Descriptor for creating a bottom level acceleration structure.
7480 pub struct CreateBlasDescriptor<L> {
7481 /// Label for the bottom level acceleration structure.
7482 pub label: L,
7483 /// Flags for the bottom level acceleration structure.
7484 pub flags: AccelerationStructureFlags,
7485 /// Update mode for the bottom level acceleration structure.
7486 pub update_mode: AccelerationStructureUpdateMode,
7487 }
7488
7489 impl<L> CreateBlasDescriptor<L> {
7490 /// Takes a closure and maps the label of the blas descriptor into another.
7491 pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> CreateBlasDescriptor<K> {
7492 CreateBlasDescriptor {
7493 label: fun(&self.label),
7494 flags: self.flags,
7495 update_mode: self.update_mode,
7496 }
7497 }
7498 }
7499
7500 #[repr(C)]
7501 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
7502 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7503 /// Descriptor for creating a top level acceleration structure.
7504 pub struct CreateTlasDescriptor<L> {
7505 /// Label for the top level acceleration structure.
7506 pub label: L,
7507 /// Number of instances that can be stored in the acceleration structure.
7508 pub max_instances: u32,
7509 /// Flags for the bottom level acceleration structure.
7510 pub flags: AccelerationStructureFlags,
7511 /// Update mode for the bottom level acceleration structure.
7512 pub update_mode: AccelerationStructureUpdateMode,
7513 }
7514
7515 impl<L> CreateTlasDescriptor<L> {
7516 /// Takes a closure and maps the label of the blas descriptor into another.
7517 pub fn map_label<K>(&self, fun: impl FnOnce(&L) -> K) -> CreateTlasDescriptor<K> {
7518 CreateTlasDescriptor {
7519 label: fun(&self.label),
7520 flags: self.flags,
7521 update_mode: self.update_mode,
7522 max_instances: self.max_instances,
7523 }
7524 }
7525 }
7526
7527 bitflags::bitflags!(
7528 /// Flags for acceleration structures
7529 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7530 #[cfg_attr(feature = "serde", serde(transparent))]
7531 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7532 pub struct AccelerationStructureFlags: u8 {
7533 /// Allow for incremental updates (no change in size), currently this is unimplemented
7534 /// and will build as normal (this is fine, update vs build should be unnoticeable)
7535 const ALLOW_UPDATE = 1 << 0;
7536 /// Allow the acceleration structure to be compacted in a copy operation, the function
7537 /// to compact is not currently implemented.
7538 const ALLOW_COMPACTION = 1 << 1;
7539 /// Optimize for fast ray tracing performance, recommended if the geometry is unlikely
7540 /// to change (e.g. in a game: non-interactive scene geometry)
7541 const PREFER_FAST_TRACE = 1 << 2;
7542 /// Optimize for fast build time, recommended if geometry is likely to change frequently
7543 /// (e.g. in a game: player model).
7544 const PREFER_FAST_BUILD = 1 << 3;
7545 /// Optimize for low memory footprint (both while building and in the output BLAS).
7546 const LOW_MEMORY = 1 << 4;
7547 /// Use `BlasTriangleGeometry::transform_buffer` when building a BLAS (only allowed in
7548 /// BLAS creation)
7549 const USE_TRANSFORM = 1 << 5;
7550 /// Allow retrieval of the vertices of the triangle hit by a ray.
7551 const ALLOW_RAY_HIT_VERTEX_RETURN = 1 << 6;
7552 }
7553 );
7554
7555 bitflags::bitflags!(
7556 /// Flags for acceleration structure geometries
7557 #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7558 #[cfg_attr(feature = "serde", serde(transparent))]
7559 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7560 pub struct AccelerationStructureGeometryFlags: u8 {
7561 /// Is OPAQUE (is there no alpha test) recommended as currently in naga there is no
7562 /// candidate intersections yet so currently BLASes without this flag will not have hits.
7563 /// Not enabling this makes the BLAS unable to be interacted with in WGSL.
7564 const OPAQUE = 1 << 0;
7565 /// NO_DUPLICATE_ANY_HIT_INVOCATION, not useful unless using hal with wgpu, ray-tracing
7566 /// pipelines are not supported in wgpu so any-hit shaders do not exist. For when any-hit
7567 /// shaders are implemented (or experienced users who combine this with an underlying library:
7568 /// for any primitive (triangle or AABB) multiple any-hit shaders sometimes may be invoked
7569 /// (especially in AABBs like a sphere), if this flag in present only one hit on a primitive may
7570 /// invoke an any-hit shader.
7571 const NO_DUPLICATE_ANY_HIT_INVOCATION = 1 << 1;
7572 }
7573 );
7574
7575 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7576 /// What a copy between acceleration structures should do
7577 pub enum AccelerationStructureCopy {
7578 /// Directly duplicate an acceleration structure to another
7579 Clone,
7580 /// Duplicate and compact an acceleration structure
7581 Compact,
7582 }
7583
7584 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7585 /// What type the data of an acceleration structure is
7586 pub enum AccelerationStructureType {
7587 /// The types of the acceleration structure are triangles
7588 Triangles,
7589 /// The types of the acceleration structure are axis aligned bounding boxes
7590 AABBs,
7591 /// The types of the acceleration structure are instances
7592 Instances,
7593 }
7594
7595 /// Alignment requirement for transform buffers used in acceleration structure builds
7596 pub const TRANSFORM_BUFFER_ALIGNMENT: BufferAddress = 16;
7597
7598 /// Alignment requirement for instance buffers used in acceleration structure builds (`build_acceleration_structures_unsafe_tlas`)
7599 pub const INSTANCE_BUFFER_ALIGNMENT: BufferAddress = 16;
7600
7601 pub use send_sync::*;
7602
7603 #[doc(hidden)]
7604 mod send_sync {
7605 pub trait WasmNotSendSync: WasmNotSend + WasmNotSync {}
7606 impl<T: WasmNotSend + WasmNotSync> WasmNotSendSync for T {}
7607 #[cfg(any(
7608 not(target_arch = "wasm32"),
7609 all(
7610 feature = "fragile-send-sync-non-atomic-wasm",
7611 not(target_feature = "atomics")
7612 )
7613 ))]
7614 pub trait WasmNotSend: Send {}
7615 #[cfg(any(
7616 not(target_arch = "wasm32"),
7617 all(
7618 feature = "fragile-send-sync-non-atomic-wasm",
7619 not(target_feature = "atomics")
7620 )
7621 ))]
7622 impl<T: Send> WasmNotSend for T {}
7623 #[cfg(not(any(
7624 not(target_arch = "wasm32"),
7625 all(
7626 feature = "fragile-send-sync-non-atomic-wasm",
7627 not(target_feature = "atomics")
7628 )
7629 )))]
7630 pub trait WasmNotSend {}
7631 #[cfg(not(any(
7632 not(target_arch = "wasm32"),
7633 all(
7634 feature = "fragile-send-sync-non-atomic-wasm",
7635 not(target_feature = "atomics")
7636 )
7637 )))]
7638 impl<T> WasmNotSend for T {}
7639
7640 #[cfg(any(
7641 not(target_arch = "wasm32"),
7642 all(
7643 feature = "fragile-send-sync-non-atomic-wasm",
7644 not(target_feature = "atomics")
7645 )
7646 ))]
7647 pub trait WasmNotSync: Sync {}
7648 #[cfg(any(
7649 not(target_arch = "wasm32"),
7650 all(
7651 feature = "fragile-send-sync-non-atomic-wasm",
7652 not(target_feature = "atomics")
7653 )
7654 ))]
7655 impl<T: Sync> WasmNotSync for T {}
7656 #[cfg(not(any(
7657 not(target_arch = "wasm32"),
7658 all(
7659 feature = "fragile-send-sync-non-atomic-wasm",
7660 not(target_feature = "atomics")
7661 )
7662 )))]
7663 pub trait WasmNotSync {}
7664 #[cfg(not(any(
7665 not(target_arch = "wasm32"),
7666 all(
7667 feature = "fragile-send-sync-non-atomic-wasm",
7668 not(target_feature = "atomics")
7669 )
7670 )))]
7671 impl<T> WasmNotSync for T {}
7672 }
7673
7674 /// Reason for "lose the device".
7675 ///
7676 /// Corresponds to [WebGPU `GPUDeviceLostReason`](https://gpuweb.github.io/gpuweb/#enumdef-gpudevicelostreason).
7677 #[repr(u8)]
7678 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
7679 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7680 pub enum DeviceLostReason {
7681 /// Triggered by driver
7682 Unknown = 0,
7683 /// After `Device::destroy`
7684 Destroyed = 1,
7685 }
7686
7687 /// Descriptor for creating a shader module.
7688 ///
7689 /// This type is unique to the Rust API of `wgpu`. In the WebGPU specification,
7690 /// only WGSL source code strings are accepted.
7691 #[derive(Debug, Clone)]
7692 pub enum CreateShaderModuleDescriptorPassthrough<'a, L> {
7693 /// Passthrough for SPIR-V binaries.
7694 SpirV(ShaderModuleDescriptorSpirV<'a, L>),
7695 /// Passthrough for MSL source code.
7696 Msl(ShaderModuleDescriptorMsl<'a, L>),
7697 }
7698
7699 impl<'a, L> CreateShaderModuleDescriptorPassthrough<'a, L> {
7700 /// Takes a closure and maps the label of the shader module descriptor into another.
7701 pub fn map_label<K>(
7702 &self,
7703 fun: impl FnOnce(&L) -> K,
7704 ) -> CreateShaderModuleDescriptorPassthrough<'_, K> {
7705 match self {
7706 CreateShaderModuleDescriptorPassthrough::SpirV(inner) => {
7707 CreateShaderModuleDescriptorPassthrough::<'_, K>::SpirV(
7708 ShaderModuleDescriptorSpirV {
7709 label: fun(&inner.label),
7710 source: inner.source.clone(),
7711 },
7712 )
7713 }
7714 CreateShaderModuleDescriptorPassthrough::Msl(inner) => {
7715 CreateShaderModuleDescriptorPassthrough::<'_, K>::Msl(ShaderModuleDescriptorMsl {
7716 entry_point: inner.entry_point.clone(),
7717 label: fun(&inner.label),
7718 num_workgroups: inner.num_workgroups,
7719 source: inner.source.clone(),
7720 })
7721 }
7722 }
7723 }
7724
7725 /// Returns the label of shader module passthrough descriptor.
7726 pub fn label(&'a self) -> &'a L {
7727 match self {
7728 CreateShaderModuleDescriptorPassthrough::SpirV(inner) => &inner.label,
7729 CreateShaderModuleDescriptorPassthrough::Msl(inner) => &inner.label,
7730 }
7731 }
7732
7733 #[cfg(feature = "trace")]
7734 /// Returns the source data for tracing purpose.
7735 pub fn trace_data(&self) -> &[u8] {
7736 match self {
7737 CreateShaderModuleDescriptorPassthrough::SpirV(inner) => {
7738 bytemuck::cast_slice(&inner.source)
7739 }
7740 CreateShaderModuleDescriptorPassthrough::Msl(inner) => inner.source.as_bytes(),
7741 }
7742 }
7743
7744 #[cfg(feature = "trace")]
7745 /// Returns the binary file extension for tracing purpose.
7746 pub fn trace_binary_ext(&self) -> &'static str {
7747 match self {
7748 CreateShaderModuleDescriptorPassthrough::SpirV(..) => "spv",
7749 CreateShaderModuleDescriptorPassthrough::Msl(..) => "msl",
7750 }
7751 }
7752 }
7753
7754 /// Descriptor for a shader module given by Metal MSL source.
7755 ///
7756 /// This type is unique to the Rust API of `wgpu`. In the WebGPU specification,
7757 /// only WGSL source code strings are accepted.
7758 #[derive(Debug, Clone)]
7759 pub struct ShaderModuleDescriptorMsl<'a, L> {
7760 /// Entrypoint.
7761 pub entry_point: String,
7762 /// Debug label of the shader module. This will show up in graphics debuggers for easy identification.
7763 pub label: L,
7764 /// Number of workgroups in each dimension x, y and z.
7765 pub num_workgroups: (u32, u32, u32),
7766 /// Shader MSL source.
7767 pub source: Cow<'a, str>,
7768 }
7769
7770 /// Descriptor for a shader module given by SPIR-V binary.
7771 ///
7772 /// This type is unique to the Rust API of `wgpu`. In the WebGPU specification,
7773 /// only WGSL source code strings are accepted.
7774 #[derive(Debug, Clone)]
7775 pub struct ShaderModuleDescriptorSpirV<'a, L> {
7776 /// Debug label of the shader module. This will show up in graphics debuggers for easy identification.
7777 pub label: L,
7778 /// Binary SPIR-V data, in 4-byte words.
7779 pub source: Cow<'a, [u32]>,
7780 }