From c150de0ba765d0473a9cd3f4d0665f98a9acee33 Mon Sep 17 00:00:00 2001 From: Kevin Reid Date: Wed, 22 Jul 2026 09:27:18 -0700 Subject: [PATCH] Add inherent `pub const fn default()` to various types. The default functions are generated using a `macro_rules_attribute` emulated derive macro, just fancy enough to work. It does not support structs with generics, so `*Descriptor`s are left alone for now. When Rust const traits stabilize, we can replace this with real const traits. --- CHANGELOG.md | 1 + Cargo.lock | 1 + wgpu-types/Cargo.toml | 1 + wgpu-types/src/adapter.rs | 12 +- wgpu-types/src/backend.rs | 42 +++---- wgpu-types/src/device.rs | 12 +- wgpu-types/src/instance.rs | 6 +- wgpu-types/src/lib.rs | 2 + wgpu-types/src/macros.rs | 199 ++++++++++++++++++++++++++++++++ wgpu-types/src/render.rs | 62 ++++++---- wgpu-types/src/surface.rs | 26 +++-- wgpu-types/src/texture.rs | 32 ++--- wgpu-types/src/tokens.rs | 6 +- wgpu-types/src/vertex.rs | 8 +- wgpu/src/api/common_pipeline.rs | 20 +++- 15 files changed, 338 insertions(+), 92 deletions(-) create mode 100644 wgpu-types/src/macros.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bbdeb3e4..1b259e0a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,7 @@ Bottom level categories: - Support the `wasm64-unknown-unknown` target for the web backend. Building for wasm64 requires a nightly toolchain with `-Z build-std=std,panic_abort`. By @nickbabcock in [#9836](https://github.com/gfx-rs/wgpu/pull/9836). - `wgpu-core` now exposes a `validate_device_descriptor` function that validates a device descriptor as `request_device` would. This may be useful in conjunction with `create_device_from_hal`. By @andyleiserson in [#9967](https://github.com/gfx-rs/wgpu/pull/9967). +- Many types now offer `pub const fn default()` in addition to implementing the `Default` trait, allowing constants to make use of default values. By @kpreid in [#9929](https://github.com/gfx-rs/wgpu/pull/9929). #### Hal diff --git a/Cargo.lock b/Cargo.lock index d426e7db7..f1305016f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4980,6 +4980,7 @@ dependencies = [ "hashbrown 0.17.1", "js-sys", "log", + "macro_rules_attribute", "naga-types", "raw-window-handle", "serde", diff --git a/wgpu-types/Cargo.toml b/wgpu-types/Cargo.toml index 7a4d65f10..928c07d8a 100644 --- a/wgpu-types/Cargo.toml +++ b/wgpu-types/Cargo.toml @@ -61,6 +61,7 @@ bitflags.workspace = true bytemuck = { workspace = true, features = ["derive"] } exhaust = { workspace = true, optional = true } log.workspace = true +macro_rules_attribute.workspace = true raw-window-handle.workspace = true serde = { workspace = true, default-features = false, features = [ "alloc", diff --git a/wgpu-types/src/adapter.rs b/wgpu-types/src/adapter.rs index a146a4bec..397fd54df 100644 --- a/wgpu-types/src/adapter.rs +++ b/wgpu-types/src/adapter.rs @@ -1,7 +1,9 @@ use alloc::{borrow::Cow, string::String}; use core::{fmt, mem}; -use crate::{link_to_wgc_docs, link_to_wgpu_docs, Backend, Backends}; +use macro_rules_attribute::derive; + +use crate::{link_to_wgc_docs, link_to_wgpu_docs, Backend, Backends, ConstDefault}; #[cfg(any(feature = "serde", test))] use serde::{Deserialize, Serialize}; @@ -15,11 +17,11 @@ use crate::{Features, TextureUsages}; /// https://gpuweb.github.io/gpuweb/#feature-level-string). /// /// `wgpu` does not support compatibility-level adapters per se. -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, ConstDefault!)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum FeatureLevel { - #[default] + #[custom(default)] /// The `core` capability set Core, /// The `compatibility` capability set @@ -72,11 +74,11 @@ impl Default for RequestAdapterOptions { /// Corresponds to [WebGPU `GPUPowerPreference`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gpupowerpreference). #[repr(C)] -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, ConstDefault!)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum PowerPreference { - #[default] + #[custom(default)] /// Power usage is not considered when choosing an adapter. None = 0, /// Adapter that uses the least possible power. This is often an integrated GPU. diff --git a/wgpu-types/src/backend.rs b/wgpu-types/src/backend.rs index 427dad0a7..6c8449cff 100644 --- a/wgpu-types/src/backend.rs +++ b/wgpu-types/src/backend.rs @@ -3,10 +3,12 @@ use alloc::string::{String, ToString}; use core::{hash::Hash, str::FromStr}; +use macro_rules_attribute::derive; + #[cfg(any(feature = "serde", test))] use serde::{Deserialize, Serialize}; -use crate::link_to_wgpu_docs; +use crate::{link_to_wgpu_docs, ConstDefault}; #[cfg(doc)] use crate::InstanceDescriptor; @@ -222,7 +224,7 @@ impl Backends { /// Options that are passed to a given backend. /// /// Part of [`InstanceDescriptor`]. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, ConstDefault!)] pub struct BackendOptions { /// Options for the OpenGL/OpenGLES backend, [`Backend::Gl`]. pub gl: GlBackendOptions, @@ -261,7 +263,7 @@ impl BackendOptions { /// Configuration for the OpenGL/OpenGLES backend. /// /// Part of [`BackendOptions`]. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, ConstDefault!)] pub struct GlBackendOptions { /// Which OpenGL ES 3 minor version to request, if using OpenGL ES. pub gles_minor_version: Gles3MinorVersion, @@ -318,7 +320,7 @@ impl GlBackendOptions { /// /// Debug functions include `glPushDebugGroup`, `glPopDebugGroup`, `glObjectLabel`, etc. /// These are useful for debugging but can cause crashes on some buggy drivers. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, ConstDefault!)] pub enum GlDebugFns { /// Automatically decide whether to enable debug functions. /// @@ -327,7 +329,7 @@ pub enum GlDebugFns { /// (e.g., Mali GPUs which can crash in `glPushDebugGroup`). /// /// This is the default behavior. - #[default] + #[custom(default)] Auto, /// Force enable debug functions if supported by the driver. /// @@ -377,7 +379,7 @@ impl GlDebugFns { /// Used to force wgpu to expose certain features on passthrough shaders even when /// those features aren't present on runtime-compiled shaders -#[derive(Default, Clone, Debug)] +#[derive(Clone, Debug, ConstDefault!)] pub struct ForceShaderModelToken { inner: Option, } @@ -400,12 +402,12 @@ impl ForceShaderModelToken { /// Behavior when the Agility SDK fails to load. /// /// See [`Dx12AgilitySDK`] for details on the Agility SDK. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq, Eq)] pub enum Dx12AgilitySDKLoadFailure { /// Log a warning and fall back to the system-installed D3D12 runtime. /// /// This is the default behavior and is appropriate for most applications. - #[default] + #[custom(default)] Fallback, /// Fail instance creation entirely if the Agility SDK cannot be loaded. /// @@ -548,7 +550,7 @@ impl Dx12AgilitySDK { /// Configuration for the DX12 backend. /// /// Part of [`BackendOptions`]. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, ConstDefault!)] pub struct Dx12BackendOptions { /// Which DX12 shader compiler to use. pub shader_compiler: Dx12Compiler, @@ -617,7 +619,7 @@ impl Dx12BackendOptions { /// Configuration for the noop backend. /// /// Part of [`BackendOptions`]. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, ConstDefault!)] pub struct NoopBackendOptions { /// Whether to allow the noop backend to be used. /// @@ -685,13 +687,13 @@ impl NoopBackendOptions { } } -#[derive(Clone, Debug, Default, Copy, PartialEq, Eq)] +#[derive(Clone, Debug, ConstDefault!, Copy, PartialEq, Eq)] /// Selects which kind of swapchain to use on DX12. pub enum Dx12SwapchainKind { /// Use a DXGI swapchain made directly from the window's HWND. /// /// This does not support transparency but has better support from developer tooling from RenderDoc. - #[default] + #[custom(default)] DxgiFromHwnd, /// Use a DXGI swapchain made from a DirectComposition visual made automatically from the window's HWND. /// @@ -790,7 +792,7 @@ impl DxcShaderModel { } /// Selects which DX12 shader compiler to use. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, ConstDefault!)] pub enum Dx12Compiler { /// The Fxc compiler (default) is old, slow and unmaintained. /// @@ -814,7 +816,7 @@ pub enum Dx12Compiler { /// Not available on `windows-aarch64-pc-*` targets. StaticDxc, /// Use statically-linked DXC if available. Otherwise check for dynamically linked DXC on the PATH. Finally, fallback to FXC. - #[default] + #[custom(default)] Auto, } @@ -875,13 +877,13 @@ impl FromStr for Dx12Compiler { } /// Whether and how to use a waitable handle obtained from `GetFrameLatencyWaitableObject`. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, ConstDefault!)] pub enum Dx12UseFrameLatencyWaitableObject { /// Do not obtain a waitable handle and do not wait for it. The swapchain will /// be created without the `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT` flag. None, /// Obtain a waitable handle and wait for it before acquiring the next swapchain image. - #[default] + #[custom(default)] Wait, /// Create the swapchain with the `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT` flag and /// obtain a waitable handle, but do not wait for it before acquiring the next swapchain image. @@ -925,10 +927,10 @@ impl Dx12UseFrameLatencyWaitableObject { /// Selects which OpenGL ES 3 minor version to request. /// /// When using ANGLE as an OpenGL ES/EGL implementation, explicitly requesting `Version1` can provide a non-conformant ES 3.1 on APIs like D3D11. -#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)] +#[derive(Clone, Copy, Debug, ConstDefault!, Eq, PartialEq, Hash)] pub enum Gles3MinorVersion { /// No explicit minor version is requested, the driver automatically picks the highest available. - #[default] + #[custom(default)] Automatic, /// Request an ES 3.0 context. @@ -975,10 +977,10 @@ impl Gles3MinorVersion { } /// Dictate the behavior of fences in OpenGL. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, ConstDefault!)] pub enum GlFenceBehavior { /// Fences in OpenGL behave normally. If you don't know what to pick, this is what you want. - #[default] + #[custom(default)] Normal, /// Fences in OpenGL are short-circuited to always return `true` immediately. /// diff --git a/wgpu-types/src/device.rs b/wgpu-types/src/device.rs index a18fdce67..600c8658a 100644 --- a/wgpu-types/src/device.rs +++ b/wgpu-types/src/device.rs @@ -1,5 +1,9 @@ use core::ops::Range; +use macro_rules_attribute::derive; + +use crate::ConstDefault; + #[cfg(any(feature = "serde", test))] use serde::{Deserialize, Serialize}; @@ -52,11 +56,11 @@ impl DeviceDescriptor { /// Hints to the device about the memory allocation strategy. /// /// Some backends may ignore these hints. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, ConstDefault!)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum MemoryHints { /// Favor performance over memory usage (the default value). - #[default] + #[custom(default)] Performance, /// Favor memory usage over performance. MemoryUsage, @@ -83,13 +87,13 @@ pub enum MemoryHints { } /// Controls API call tracing and specifies where the trace is written. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, ConstDefault!)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] // This enum must be non-exhaustive so that enabling the "trace" feature is not a semver break. #[non_exhaustive] pub enum Trace { /// Tracing disabled. - #[default] + #[custom(default)] Off, /// Write trace to disk. diff --git a/wgpu-types/src/instance.rs b/wgpu-types/src/instance.rs index 25deb8158..d73465987 100644 --- a/wgpu-types/src/instance.rs +++ b/wgpu-types/src/instance.rs @@ -1,6 +1,8 @@ //! Types for dealing with Instances. -use crate::{link_to_wgpu_docs, Backends}; +use macro_rules_attribute::derive; + +use crate::{link_to_wgpu_docs, Backends, ConstDefault}; #[cfg(doc)] use crate::{Backend, DownlevelFlags}; @@ -335,7 +337,7 @@ impl InstanceFlags { /// Memory budget thresholds used by backends to try to avoid high memory pressure situations. /// /// Currently only the D3D12 and (optionally) Vulkan backends support these options. -#[derive(Default, Clone, Debug, Copy)] +#[derive(ConstDefault!, Clone, Debug, Copy)] pub struct MemoryBudgetThresholds { /// Threshold at which texture, buffer, query set and acceleration structure creation will start to return OOM errors. /// This is a percent of the memory budget reported by native APIs. diff --git a/wgpu-types/src/lib.rs b/wgpu-types/src/lib.rs index 5b4b097be..1c47f9dd5 100644 --- a/wgpu-types/src/lib.rs +++ b/wgpu-types/src/lib.rs @@ -39,6 +39,7 @@ pub mod error; mod features; pub mod instance; mod limits; +mod macros; pub mod math; mod origin_extent; mod ray_tracing; @@ -77,6 +78,7 @@ pub use transfers::*; pub use vertex::*; pub use write_only::*; +pub(crate) use macros::ConstDefault; pub(crate) use naga_types::{link_to_wgc_docs, link_to_wgpu_docs, link_to_wgpu_item}; /// Integral type used for [`Buffer`] offsets and sizes. diff --git a/wgpu-types/src/macros.rs b/wgpu-types/src/macros.rs new file mode 100644 index 000000000..09c00880b --- /dev/null +++ b/wgpu-types/src/macros.rs @@ -0,0 +1,199 @@ +/// Macro for use with [`macro_rules_attribute::derive`] to derive a `const fn default()` +/// in addition to `impl Default`. +/// +/// Generics are not supported. +/// +/// When using this macro on an enum, the default variant must be marked with `#[custom(default)]`, +/// rather than `#[default]` as the built-in derive macro does. This is a limitation of +/// [`macro_rules_attribute::derive`]. +macro_rules! ConstDefault { + // Simplify by dropping attributes and visibility from an `enum`. + ( + $(#[$attr:meta])+ + $vis:vis enum $enum_name:ident { + $($body:tt)* + } + ) => { + $crate::macros::ConstDefault!(enum $enum_name { $($body)* }); + }; + + // Simplify by dropping attributes and visibility from a `struct`. + ( + $(#[$attr:meta])+ + $vis:vis struct $struct_name:ident $($rest:tt)* + ) => { + $crate::macros::ConstDefault!(struct $struct_name $($rest)*); + }; + + // Base case: match an `enum` with `#[default]` on the first variant. + ( + enum $enum_name:ident { + #[custom(default)] + $(#[$other_variant_attr:meta])* + $variant_name:ident $(= $discriminant:expr)?, + $( $rest_of_body:tt )* + } + ) => { + impl $enum_name { + /// This function is identical to [`Default::default()`] except that it is a `const fn`. + pub const fn default() -> Self { + Self::$variant_name + } + } + + impl $crate::macros::ConstDefaultHelper for $enum_name { + const DEFAULT: Self = Self::$variant_name; + } + + impl ::core::default::Default for $enum_name { + fn default() -> Self { + Self::$variant_name + } + } + }; + + // Recursive case: remove an irrelevant attribute from the first variant. + ( + enum $enum_name:ident { + #[$attr_that_is_not_default:meta] + $( $rest_of_body:tt )* + } + ) => { + $crate::macros::ConstDefault!(enum $enum_name { $( $rest_of_body )* }); + }; + + + // Recursive cases: remove the first variant of an enum (which may or may not have fields), + // because we have checked it is not the default. + ( + enum $enum_name:ident { + $variant_name:ident $(= $discriminant:expr)?, + $( $rest_of_body:tt )* + } + ) => { + $crate::macros::ConstDefault!(enum $enum_name { $( $rest_of_body )* }); + }; + ( + enum $enum_name:ident { + $variant_name:ident ( $( $field_tokens:tt )* ), + $( $rest_of_body:tt )* + } + ) => { + $crate::macros::ConstDefault!(enum $enum_name { $( $rest_of_body )* }); + }; + ( + enum $enum_name:ident { + $variant_name:ident { $( $field_tokens:tt )* }, + $( $rest_of_body:tt )* + } + ) => { + $crate::macros::ConstDefault!(enum $enum_name { $( $rest_of_body )* }); + }; + + // Struct (without generics) + ( + $(#[$struct_attr:meta])* + $vis:vis struct $struct_name:ident { + $( + $(#[$field_attr:meta])* + $field_vis:vis $field_name:ident : $field_type:ty, + )* + } + ) => { + impl $struct_name { + /// This function is identical to [`Default::default()`] except that it is a `const fn`. + pub const fn default() -> Self { + ::DEFAULT + } + } + + impl $crate::macros::ConstDefaultHelper for $struct_name { + const DEFAULT: Self = Self { + $( + $field_name: <$field_type as $crate::macros::ConstDefaultHelper>::DEFAULT, + )* + }; + } + + impl ::core::default::Default for $struct_name { + fn default() -> Self { + ::DEFAULT + } + } + }; + + + // Tuple struct + ( + $(#[$struct_attr:meta])* + $vis:vis struct $struct_name:ident( + $( + $(#[$field_attr:meta])* + $field_vis:vis $field_type:ty + ),* $(,)? + ); + ) => { + impl $struct_name { + /// This function is identical to [`Default::default()`] except that it is a `const fn`. + pub const fn default() -> Self { + ::DEFAULT + } + } + + impl $crate::macros::ConstDefaultHelper for $struct_name { + const DEFAULT: Self = Self( + $( + <$field_type as $crate::macros::ConstDefaultHelper>::DEFAULT, + )* + ); + } + + impl ::core::default::Default for $struct_name { + fn default() -> Self { + ::DEFAULT + } + } + }; +} +pub(crate) use ConstDefault; + +/// Default value of a type, as a `const` item. +/// +/// This trait is not public and is used solely to help [`ConstDefault`] provide *inherent* +/// `const fn default()`s. +/// +/// Specifically, it is implemented both for `wgpu-types` types and `std` types, +/// so that the macro [`ConstDefault`] can call it without needing to understand the type. +pub(crate) trait ConstDefaultHelper { + const DEFAULT: Self; +} + +impl ConstDefaultHelper for bool { + const DEFAULT: Self = false; +} +impl ConstDefaultHelper for f32 { + const DEFAULT: Self = 0.; +} +impl ConstDefaultHelper for f64 { + const DEFAULT: Self = 0.; +} +impl ConstDefaultHelper for i32 { + const DEFAULT: Self = 0; +} +impl ConstDefaultHelper for i64 { + const DEFAULT: Self = 0; +} +impl ConstDefaultHelper for u32 { + const DEFAULT: Self = 0; +} +impl ConstDefaultHelper for u64 { + const DEFAULT: Self = 0; +} + +impl ConstDefaultHelper for Option { + const DEFAULT: Self = None; +} + +impl ConstDefaultHelper for [T; N] { + const DEFAULT: Self = [::DEFAULT; N]; +} diff --git a/wgpu-types/src/render.rs b/wgpu-types/src/render.rs index 901c10d75..6eb44850d 100644 --- a/wgpu-types/src/render.rs +++ b/wgpu-types/src/render.rs @@ -1,11 +1,12 @@ //! Types for configuring render passes and render pipelines (except for vertex attributes). use bytemuck::{Pod, Zeroable}; +use macro_rules_attribute::derive; #[cfg(any(feature = "serde", test))] use serde::{Deserialize, Serialize}; -use crate::{link_to_wgpu_docs, LoadOpDontCare}; +use crate::{link_to_wgpu_docs, ConstDefault, LoadOpDontCare}; #[cfg(doc)] use crate::{Features, TextureFormat}; @@ -97,12 +98,12 @@ impl BlendFactor { /// For further details on how the blend operations are applied, see /// the analogous functionality in OpenGL: . #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum BlendOperation { /// Src + Dst - #[default] + #[custom(default)] Add = 0, /// Src - Dst Subtract = 1, @@ -293,7 +294,7 @@ impl Default for ColorWrites { /// Corresponds to [WebGPU `GPUPrimitiveTopology`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gpuprimitivetopology). #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum PrimitiveTopology { @@ -310,7 +311,7 @@ pub enum PrimitiveTopology { /// Vertex data is a list of triangles. Each set of 3 vertices composes a new triangle. /// /// Vertices `0 1 2 3 4 5` create two triangles `0 1 2` and `3 4 5` - #[default] + #[custom(default)] TriangleList = 3, /// Vertex data is a triangle strip. Each set of three adjacent vertices form a triangle. /// @@ -343,14 +344,14 @@ impl PrimitiveTopology { /// Corresponds to [WebGPU `GPUFrontFace`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gpufrontface). #[repr(C)] -#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, ConstDefault!, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum FrontFace { /// Triangles with vertices in counter clockwise order are considered the front face. /// /// This is the default with right handed coordinate spaces. - #[default] + #[custom(default)] Ccw = 0, /// Triangles with vertices in clockwise order are considered the front face. /// @@ -376,12 +377,12 @@ pub enum Face { /// Type of drawing mode for polygons #[repr(C)] -#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, ConstDefault!, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum PolygonMode { /// Polygons are filled - #[default] + #[custom(default)] Fill = 0, /// Polygons are drawn as line segments Line = 1, @@ -394,7 +395,7 @@ pub enum PolygonMode { /// Corresponds to [WebGPU `GPUPrimitiveState`]( /// https://gpuweb.github.io/gpuweb/#dictdef-gpuprimitivestate). #[repr(C)] -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] pub struct PrimitiveState { @@ -457,8 +458,9 @@ pub struct MultisampleState { pub alpha_to_coverage_enabled: bool, } -impl Default for MultisampleState { - fn default() -> Self { +impl MultisampleState { + /// This function is identical to [`Default::default()`] except that it is a `const fn`. + pub const fn default() -> Self { MultisampleState { count: 1, mask: !0, @@ -467,19 +469,25 @@ impl Default for MultisampleState { } } +impl Default for MultisampleState { + fn default() -> Self { + Self::default() // call inherent function + } +} + /// Format of indices used with pipeline. /// /// Corresponds to [WebGPU `GPUIndexFormat`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gpuindexformat). #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum IndexFormat { /// Indices are 16 bit unsigned integers. Uint16 = 0, /// Indices are 32 bit unsigned integers. - #[default] + #[custom(default)] Uint32 = 1, } @@ -498,12 +506,12 @@ impl IndexFormat { /// Corresponds to [WebGPU `GPUStencilOperation`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gpustenciloperation). #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum StencilOperation { /// Keep stencil value unchanged. - #[default] + #[custom(default)] Keep = 0, /// Set stencil value to zero. Zero = 1, @@ -572,7 +580,11 @@ impl StencilFaceState { } } +impl crate::macros::ConstDefaultHelper for StencilFaceState { + const DEFAULT: Self = Self::IGNORE; +} impl Default for StencilFaceState { + /// Returns [`StencilFaceState::IGNORE`] as the default. fn default() -> Self { Self::IGNORE } @@ -583,7 +595,7 @@ impl Default for StencilFaceState { /// Corresponds to [WebGPU `GPUCompareFunction`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gpucomparefunction). #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum CompareFunction { @@ -606,7 +618,7 @@ pub enum CompareFunction { /// Function passes if new value is greater than or equal to existing value GreaterEqual = 7, /// Function always passes - #[default] + #[custom(default)] Always = 8, } @@ -628,7 +640,7 @@ impl CompareFunction { /// Corresponds to a portion of [WebGPU `GPUDepthStencilState`]( /// https://gpuweb.github.io/gpuweb/#dictdef-gpudepthstencilstate). #[repr(C)] -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, ConstDefault!, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct StencilState { /// Front face mode. @@ -678,7 +690,7 @@ impl StencilState { /// Corresponds to a portion of [WebGPU `GPUDepthStencilState`]( /// https://gpuweb.github.io/gpuweb/#dictdef-gpudepthstencilstate). #[repr(C)] -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Copy, Debug, ConstDefault!)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct DepthBiasState { /// Constant depth biasing factor, in basic units of the depth format. @@ -780,12 +792,12 @@ impl Default for LoadOp { /// /// Corresponds to [WebGPU `GPUStoreOp`](https://gpuweb.github.io/gpuweb/#enumdef-gpustoreop). #[repr(C)] -#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Default)] +#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, ConstDefault!)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum StoreOp { /// Stores the resulting value of the render pass for this attachment. - #[default] + #[custom(default)] Store = 0, /// Discards the resulting value of the render pass for this attachment. /// @@ -959,7 +971,7 @@ impl Default for RenderBundleDescriptor> { /// Argument buffer layout for `draw_indirect` commands. #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Pod, Zeroable)] +#[derive(Copy, Clone, Debug, ConstDefault!, Pod, Zeroable)] pub struct DrawIndirectArgs { /// The number of vertices to draw. pub vertex_count: u32, @@ -983,7 +995,7 @@ impl DrawIndirectArgs { /// Argument buffer layout for `draw_indexed_indirect` commands. #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Pod, Zeroable)] +#[derive(Copy, Clone, Debug, ConstDefault!, Pod, Zeroable)] pub struct DrawIndexedIndirectArgs { /// The number of indices to draw. pub index_count: u32, @@ -1009,7 +1021,7 @@ impl DrawIndexedIndirectArgs { /// Argument buffer layout for `dispatch_workgroups_indirect` commands. #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Pod, Zeroable)] +#[derive(Copy, Clone, Debug, ConstDefault!, Pod, Zeroable)] pub struct DispatchIndirectArgs { /// The number of work groups in X dimension. pub x: u32, diff --git a/wgpu-types/src/surface.rs b/wgpu-types/src/surface.rs index 17f39ca81..591a03527 100644 --- a/wgpu-types/src/surface.rs +++ b/wgpu-types/src/surface.rs @@ -6,7 +6,9 @@ use alloc::{vec, vec::Vec}; -use crate::{link_to_wgpu_docs, link_to_wgpu_item, TextureFormat, TextureUsages}; +use macro_rules_attribute::derive; + +use crate::{link_to_wgpu_docs, link_to_wgpu_item, ConstDefault, TextureFormat, TextureUsages}; #[cfg(any(feature = "serde", test))] use serde::{Deserialize, Serialize}; @@ -23,7 +25,7 @@ use serde::{Deserialize, Serialize}; #[doc = link_to_wgpu_docs!(["presented"]: "struct.SurfaceTexture.html#method.present")] #[doc = link_to_wgpu_docs!(["`SurfaceTexture::present()`"]: "struct.SurfaceTexture.html#method.present")] #[repr(C)] -#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, ConstDefault!, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum PresentMode { /// Chooses the first supported mode out of: @@ -60,7 +62,7 @@ pub enum PresentMode { /// If you don't know what mode to choose, choose this mode. /// #[doc = link_to_wgpu_docs!(["`Surface::get_current_texture()`"]: "struct.Surface.html#method.get_current_texture")] - #[default] + #[custom(default)] Fifo = 2, /// Presentation frames are kept in a First-In-First-Out queue approximately 3 frames @@ -107,13 +109,13 @@ pub enum PresentMode { /// Specifies how the alpha channel of the textures should be handled during /// compositing. #[repr(C)] -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, ConstDefault!, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))] pub enum CompositeAlphaMode { /// Chooses either `Opaque` or `Inherit` automatically, depending on the /// `alpha_mode` that the current surface can support. - #[default] + #[custom(default)] Auto = 0, /// The alpha channel, if it exists, of the textures is ignored in the /// compositing process. Instead, the textures is treated as if it has a @@ -237,7 +239,7 @@ pub enum CompositeAlphaMode { /// [`toneMapping`]: https://www.w3.org/TR/webgpu/#gpucanvastonemappingmode #[doc = link_to_wgpu_docs!(["color space and HDR primer"]: "index.html#surface-color-spaces-and-hdr-output")] #[repr(C)] -#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug, ConstDefault!, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum SurfaceColorSpace { /// Let the backend choose a color space, reproducing wgpu's historical @@ -264,7 +266,7 @@ pub enum SurfaceColorSpace { /// [`TextureFormat::Rgba16Float`]; request /// [`ExtendedSrgb`](Self::ExtendedSrgb) explicitly for HDR canvas output /// ([`ExtendedSrgbLinear`](Self::ExtendedSrgbLinear) is native-only). - #[default] + #[custom(default)] Auto = 0, /// The sRGB color space: BT.709 primaries, D65 white point, sRGB transfer @@ -582,7 +584,7 @@ impl Default for SurfaceCapabilities { /// optimistic and report the panel's claim, not what survives the compositor. /// #[doc = link_to_wgpu_item!(struct Surface)] -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, ConstDefault!, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct DisplayHdrInfo { /// Absolute-nit luminance levels. `Some` only on platforms that report @@ -618,7 +620,7 @@ pub struct DisplayHdrInfo { /// `Some(0.0)`; absence is `None`. These are achromatic (luminance = CIE Y), not a /// per-color ceiling: a display can't reach [`max_nits`](Self::max_nits) at a /// saturated chromaticity. Pair them with [`DisplayChromaticity`] for gamut mapping. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct DisplayLuminance { /// Peak luminance of a small patch, nits. DXGI `MaxLuminance`. @@ -644,7 +646,7 @@ pub struct DisplayLuminance { /// so this is separate from [`DisplayLuminance`] and can't be converted to nits. /// /// Populated only on macOS; `None` on iOS, tvOS, and visionOS. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct DisplayHeadroom { /// Headroom available *right now* (`maximumExtendedDynamicRangeColorComponentValue` @@ -663,7 +665,7 @@ pub struct DisplayHeadroom { /// CIE 1931 xy chromaticity of a display's primaries and white point. Each /// coordinate is `[x, y]`; a coordinate the platform omits is `None`. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct DisplayChromaticity { /// xy of the red primary. @@ -680,7 +682,7 @@ pub struct DisplayChromaticity { /// /// This is the only luminance-adjacent data the web exposes, and a useful /// cross-check on other platforms. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct DisplayCoarseRange { /// CSS `@media (dynamic-range: high)`: the display *can* present HDR-range diff --git a/wgpu-types/src/texture.rs b/wgpu-types/src/texture.rs index 302a92fd0..b22c39db0 100644 --- a/wgpu-types/src/texture.rs +++ b/wgpu-types/src/texture.rs @@ -1,6 +1,8 @@ use core::ops::Range; -use crate::{link_to_wgpu_docs, link_to_wgpu_item, Extent3d, Origin3d}; +use macro_rules_attribute::derive; + +use crate::{link_to_wgpu_docs, link_to_wgpu_item, ConstDefault, Extent3d, Origin3d}; #[cfg(any(feature = "serde", test))] use serde::{Deserialize, Serialize}; @@ -36,7 +38,7 @@ pub enum TextureDimension { } /// Order in which texture data is laid out in memory. -#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, ConstDefault!, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum TextureDataOrder { /// The texture is laid out densely in memory as: @@ -48,7 +50,7 @@ pub enum TextureDataOrder { /// ```` /// /// This is the layout used by dds files. - #[default] + #[custom(default)] LayerMajor, /// The texture is laid out densely in memory as: /// @@ -67,7 +69,7 @@ pub enum TextureDataOrder { /// Corresponds to [WebGPU `GPUTextureViewDimension`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gputextureviewdimension). #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum TextureViewDimension { /// A one dimensional texture. `texture_1d` in WGSL and `texture1D` in GLSL. @@ -75,7 +77,7 @@ pub enum TextureViewDimension { D1, /// A two dimensional texture. `texture_2d` in WGSL and `texture2D` in GLSL. #[cfg_attr(feature = "serde", serde(rename = "2d"))] - #[default] + #[custom(default)] D2, /// A two dimensional array texture. `texture_2d_array` in WGSL and `texture2DArray` in GLSL. #[cfg_attr(feature = "serde", serde(rename = "2d-array"))] @@ -113,12 +115,12 @@ impl TextureViewDimension { /// #[doc = link_to_wgpu_item!(struct Texture)] #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum TextureAspect { /// Depth, Stencil, and Color. - #[default] + #[custom(default)] All, /// Stencil. StencilOnly, @@ -727,7 +729,7 @@ impl SamplerDescriptor { /// Corresponds to [WebGPU `GPUAddressMode`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gpuaddressmode). #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum AddressMode { @@ -735,7 +737,7 @@ pub enum AddressMode { /// /// -0.25 -> 0.0 /// 1.25 -> 1.0 - #[default] + #[custom(default)] ClampToEdge = 0, /// Repeat the texture in a tiling fashion /// @@ -760,14 +762,14 @@ pub enum AddressMode { /// Corresponds to [WebGPU `GPUFilterMode`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gpufiltermode). #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum FilterMode { /// Nearest neighbor sampling. /// /// This creates a pixelated effect. - #[default] + #[custom(default)] Nearest = 0, /// Linear Interpolation /// @@ -780,14 +782,14 @@ pub enum FilterMode { /// Corresponds to [WebGPU `GPUMipmapFilterMode`]( /// https://gpuweb.github.io/gpuweb/#enumdef-gpumipmapfiltermode). #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum MipmapFilterMode { /// Nearest neighbor sampling. /// /// Return the value of the texel nearest to the texture coordinates. - #[default] + #[custom(default)] Nearest = 0, /// Linear Interpolation /// @@ -829,7 +831,7 @@ pub enum SamplerBorderColor { /// Corresponds to [WebGPU `GPUTexelCopyBufferLayout`]( /// https://gpuweb.github.io/gpuweb/#dictdef-gpuimagedatalayout). #[repr(C)] -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Copy, Debug, ConstDefault!)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct TexelCopyBufferLayout { /// Offset into the buffer that is the start of the texture. Must be a multiple of texture block size. @@ -923,7 +925,7 @@ impl TexelCopyTextureInfo { /// Subresource range within an image #[repr(C)] -#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +#[derive(Clone, Copy, Debug, ConstDefault!, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))] pub struct ImageSubresourceRange { diff --git a/wgpu-types/src/tokens.rs b/wgpu-types/src/tokens.rs index 89ade7a6f..31204c306 100644 --- a/wgpu-types/src/tokens.rs +++ b/wgpu-types/src/tokens.rs @@ -1,7 +1,9 @@ -use crate::link_to_wgpu_item; +use macro_rules_attribute::derive; + +use crate::{link_to_wgpu_item, ConstDefault}; /// Token of the user agreeing to access experimental features. -#[derive(Debug, Default, Copy, Clone)] +#[derive(Debug, ConstDefault!, Copy, Clone)] pub struct ExperimentalFeatures { enabled: bool, } diff --git a/wgpu-types/src/vertex.rs b/wgpu-types/src/vertex.rs index 7c3617018..67c2859b7 100644 --- a/wgpu-types/src/vertex.rs +++ b/wgpu-types/src/vertex.rs @@ -1,10 +1,12 @@ //! Types for defining vertex attributes and their buffers. +use macro_rules_attribute::derive; + use nt::VertexFormat; #[cfg(any(feature = "serde", test))] use serde::{Deserialize, Serialize}; -use crate::{link_to_wgpu_docs, link_to_wgpu_item}; +use crate::{link_to_wgpu_docs, link_to_wgpu_item, ConstDefault}; #[cfg(doc)] use crate::Features; @@ -67,12 +69,12 @@ use crate::Features; /// [`Vertex`]: VertexStepMode::Vertex /// [`Instance`]: VertexStepMode::Instance #[repr(C)] -#[derive(Copy, Clone, Debug, Default, Hash, Eq, PartialEq)] +#[derive(Copy, Clone, Debug, ConstDefault!, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))] pub enum VertexStepMode { /// Vertex data is advanced every vertex. - #[default] + #[custom(default)] Vertex = 0, /// Vertex data is advanced every instance. Instance = 1, diff --git a/wgpu/src/api/common_pipeline.rs b/wgpu/src/api/common_pipeline.rs index 79ac7121e..13ffe58c5 100644 --- a/wgpu/src/api/common_pipeline.rs +++ b/wgpu/src/api/common_pipeline.rs @@ -14,20 +14,32 @@ pub struct PipelineCompilationOptions<'a> { /// If the given constant is specified more than once, the last value specified is used. /// /// The value may represent any of WGSL's concrete scalar types. + /// + /// The default value is `&[]`. pub constants: &'a [(&'a str, f64)], + /// Whether workgroup scoped memory will be initialized with zero values for this stage. /// /// This is required by the WebGPU spec, but may have overhead which can be avoided /// for cross-platform applications + /// + /// The default value is `true`. pub zero_initialize_workgroup_memory: bool, } +impl PipelineCompilationOptions<'_> { + /// This function is identical to [`Default::default()`] except that it is a `const fn`. + pub const fn default() -> Self { + Self { + constants: &[], + zero_initialize_workgroup_memory: true, + } + } +} + impl Default for PipelineCompilationOptions<'_> { fn default() -> Self { - Self { - constants: Default::default(), - zero_initialize_workgroup_memory: true, - } + Self::default() // call inherent function } }