Skip to main content

wgpu_types/
backend.rs

1//! [`Backend`], [`Backends`], and backend-specific options.
2
3use alloc::string::{String, ToString};
4use core::{hash::Hash, str::FromStr};
5
6use macro_rules_attribute::derive;
7
8#[cfg(any(feature = "serde", test))]
9use serde::{Deserialize, Serialize};
10
11use crate::{link_to_wgpu_docs, ConstDefault};
12
13#[cfg(doc)]
14use crate::InstanceDescriptor;
15
16/// Backends supported by wgpu.
17///
18/// See also [`Backends`].
19#[repr(u8)]
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub enum Backend {
23    /// Dummy backend, which may be used for testing.
24    ///
25    /// It performs no rendering or computation, but allows creation of stub GPU resource types,
26    /// so that code which manages GPU resources can be tested without an available GPU.
27    /// Specifically, the following operations are implemented:
28    ///
29    /// * Enumerating adapters will always return one noop adapter, which can be used to create
30    ///   devices.
31    /// * Buffers may be created, written, mapped, and copied to other buffers.
32    /// * Command encoders may be created, but only buffer operations are useful.
33    ///
34    /// Other resources can be created but are nonfunctional; notably,
35    ///
36    /// * Render passes and compute passes are not executed.
37    /// * Textures may be created, but do not store any texels.
38    /// * There are no compatible surfaces.
39    ///
40    /// An adapter using the noop backend can only be obtained if [`NoopBackendOptions`]
41    /// enables it, in addition to the ordinary requirement of [`Backends::NOOP`] being set.
42    /// This ensures that applications not desiring a non-functional backend will not receive it.
43    Noop = 0,
44
45    /// Vulkan API (Windows, Linux, Android, MacOS via `vulkan-portability`/MoltenVK)
46    Vulkan = 1,
47
48    /// Metal API (Apple platforms)
49    Metal = 2,
50
51    /// Direct3D-12 (Windows)
52    Dx12 = 3,
53
54    /// OpenGL 3.3+, OpenGL ES 3.0+, WebGL2.
55    ///
56    /// - On Windows, this is normally OpenGL. If you build with
57    ///   `cfg(windows_angle)` to use ANGLE instead, then this is OpenGL ES.
58    ///
59    /// - On Linux, we create a full OpenGL context if possible (Mesa offers
60    ///   it), but if that fails we fall back to OpenGL ES.
61    ///
62    /// - On Android and macOS with ANGLE, we get OpenGL ES.
63    ///
64    /// - When running in a web browser, we get WebGL2.
65    Gl = 4,
66
67    /// WebGPU in the browser
68    BrowserWebGpu = 5,
69}
70
71impl Backend {
72    /// Array of all [`Backend`] values, corresponding to [`Backends::all()`].
73    pub const ALL: [Backend; Backends::all().bits().count_ones() as usize] = [
74        Self::Noop,
75        Self::Vulkan,
76        Self::Metal,
77        Self::Dx12,
78        Self::Gl,
79        Self::BrowserWebGpu,
80    ];
81
82    /// Returns the string name of the backend.
83    #[must_use]
84    pub const fn to_str(self) -> &'static str {
85        match self {
86            Backend::Noop => "noop",
87            Backend::Vulkan => "vulkan",
88            Backend::Metal => "metal",
89            Backend::Dx12 => "dx12",
90            Backend::Gl => "gl",
91            Backend::BrowserWebGpu => "webgpu",
92        }
93    }
94}
95
96impl core::fmt::Display for Backend {
97    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
98        f.write_str(self.to_str())
99    }
100}
101
102bitflags::bitflags! {
103    /// Represents the backends that wgpu will use.
104    #[repr(transparent)]
105    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
106    #[cfg_attr(feature = "serde", serde(transparent))]
107    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
108    pub struct Backends: u32 {
109        /// [`Backend::Noop`].
110        const NOOP = 1 << Backend::Noop as u32;
111
112        /// [`Backend::Vulkan`].
113        /// Supported on Windows, Linux/Android, and macOS/iOS via Vulkan Portability (with the Vulkan feature enabled)
114        const VULKAN = 1 << Backend::Vulkan as u32;
115
116        /// [`Backend::Gl`].
117        /// Supported on Linux/Android, the web through webassembly via WebGL, and
118        /// Windows through native OpenGL by default or ANGLE with `cfg(windows_angle)`.
119        const GL = 1 << Backend::Gl as u32;
120
121        /// [`Backend::Metal`].
122        /// Supported on macOS and iOS.
123        const METAL = 1 << Backend::Metal as u32;
124
125        /// [`Backend::Dx12`].
126        /// Supported on Windows 10 and later
127        const DX12 = 1 << Backend::Dx12 as u32;
128
129        /// [`Backend::BrowserWebGpu`].
130        /// Supported when targeting the web through WebAssembly with the `webgpu` feature enabled.
131        ///
132        /// The WebGPU backend is special in several ways:
133        /// It is not not implemented by `wgpu_core` and instead by the higher level `wgpu` crate.
134        /// Whether WebGPU is targeted is decided upon the creation of the `wgpu::Instance`,
135        /// *not* upon adapter creation. See `wgpu::Instance::new`.
136        const BROWSER_WEBGPU = 1 << Backend::BrowserWebGpu as u32;
137
138        /// All the apis that wgpu offers first tier of support for.
139        ///
140        /// * [`Backends::VULKAN`]
141        /// * [`Backends::METAL`]
142        /// * [`Backends::DX12`]
143        /// * [`Backends::BROWSER_WEBGPU`]
144        const PRIMARY = Self::VULKAN.bits()
145            | Self::METAL.bits()
146            | Self::DX12.bits()
147            | Self::BROWSER_WEBGPU.bits();
148
149        /// All the apis that wgpu offers second tier of support for. These may
150        /// be unsupported/still experimental.
151        ///
152        /// * [`Backends::GL`]
153        const SECONDARY = Self::GL.bits();
154    }
155}
156
157impl Default for Backends {
158    fn default() -> Self {
159        Self::all()
160    }
161}
162
163impl From<Backend> for Backends {
164    fn from(backend: Backend) -> Self {
165        Self::from_bits(1 << backend as u32).unwrap()
166    }
167}
168
169impl Backends {
170    /// Gets a set of backends from the environment variable `WGPU_BACKEND`.
171    ///
172    /// See [`Self::from_comma_list()`] for the format of the string.
173    pub fn from_env() -> Option<Self> {
174        let env = crate::env::var("WGPU_BACKEND")?;
175        Some(Self::from_comma_list(&env))
176    }
177
178    /// Takes the given options, modifies them based on the `WGPU_BACKEND` environment variable, and returns the result.
179    pub fn with_env(&self) -> Self {
180        if let Some(env) = Self::from_env() {
181            env
182        } else {
183            *self
184        }
185    }
186
187    /// Generates a set of backends from a comma separated list of case-insensitive backend names.
188    ///
189    /// Whitespace is stripped, so both 'gl, dx12' and 'gl,dx12' are valid.
190    ///
191    /// Always returns WEBGPU on wasm over webgpu.
192    ///
193    /// Names:
194    /// - vulkan = "vulkan" or "vk"
195    /// - dx12   = "dx12" or "d3d12"
196    /// - metal  = "metal" or "mtl"
197    /// - gles   = "opengl" or "gles" or "gl"
198    /// - webgpu = "webgpu"
199    pub fn from_comma_list(string: &str) -> Self {
200        let mut backends = Self::empty();
201        for backend in string.to_lowercase().split(',') {
202            backends |= match backend.trim() {
203                "vulkan" | "vk" => Self::VULKAN,
204                "dx12" | "d3d12" => Self::DX12,
205                "metal" | "mtl" => Self::METAL,
206                "opengl" | "gles" | "gl" => Self::GL,
207                "webgpu" => Self::BROWSER_WEBGPU,
208                "noop" => Self::NOOP,
209                b => {
210                    log::warn!("unknown backend string '{b}'");
211                    continue;
212                }
213            }
214        }
215
216        if backends.is_empty() {
217            log::warn!("no valid backend strings found!");
218        }
219
220        backends
221    }
222}
223
224/// Options that are passed to a given backend.
225///
226/// Part of [`InstanceDescriptor`].
227#[derive(Clone, Debug, Eq, PartialEq, ConstDefault!)]
228pub struct BackendOptions {
229    /// Options for the OpenGL/OpenGLES backend, [`Backend::Gl`].
230    pub gl: GlBackendOptions,
231    /// Options for the DX12 backend, [`Backend::Dx12`].
232    pub dx12: Dx12BackendOptions,
233    /// Options for the Vulkan backend, [`Backend::Vulkan`].
234    pub vulkan: VulkanBackendOptions,
235    /// Options for the noop backend, [`Backend::Noop`].
236    pub noop: NoopBackendOptions,
237}
238
239impl BackendOptions {
240    /// Choose backend options by calling `from_env` on every field.
241    ///
242    /// See those methods for more information.
243    #[must_use]
244    pub fn from_env_or_default() -> Self {
245        Self {
246            gl: GlBackendOptions::from_env_or_default(),
247            dx12: Dx12BackendOptions::from_env_or_default(),
248            vulkan: VulkanBackendOptions::from_env_or_default(),
249            noop: NoopBackendOptions::from_env_or_default(),
250        }
251    }
252
253    /// Takes the given options, modifies them based on the environment variables, and returns the result.
254    ///
255    /// This is equivalent to calling `with_env` on every field.
256    #[must_use]
257    pub fn with_env(self) -> Self {
258        Self {
259            gl: self.gl.with_env(),
260            dx12: self.dx12.with_env(),
261            vulkan: self.vulkan.with_env(),
262            noop: self.noop.with_env(),
263        }
264    }
265}
266
267/// Configuration for the OpenGL/OpenGLES backend.
268///
269/// Part of [`BackendOptions`].
270#[derive(Clone, Debug, Eq, PartialEq, ConstDefault!)]
271pub struct GlBackendOptions {
272    /// Which OpenGL ES 3 minor version to request, if using OpenGL ES.
273    pub gles_minor_version: Gles3MinorVersion,
274    /// Behavior of OpenGL fences. Affects how `on_completed_work_done` and `device.poll` behave.
275    pub fence_behavior: GlFenceBehavior,
276    /// Controls whether debug functions (`glPushDebugGroup`, `glPopDebugGroup`,
277    /// `glObjectLabel`, etc.) are enabled when supported by the driver.
278    ///
279    /// By default ([`GlDebugFns::Auto`]), debug functions are automatically
280    /// disabled on devices with known bugs (e.g., Mali GPUs can crash in
281    /// `glPushDebugGroup`). Use [`GlDebugFns::ForceEnabled`] to override this
282    /// behavior, or [`GlDebugFns::Disabled`] to disable debug functions entirely.
283    ///
284    /// See also [`InstanceFlags::DISCARD_HAL_LABELS`], which prevents debug
285    /// markers and labels from being sent to *any* backend, but without the
286    /// driver-specific bug workarounds provided here.
287    ///
288    /// [`InstanceFlags::DISCARD_HAL_LABELS`]: crate::InstanceFlags::DISCARD_HAL_LABELS
289    pub debug_fns: GlDebugFns,
290}
291
292impl GlBackendOptions {
293    /// Choose OpenGL backend options by calling `from_env` on every field.
294    ///
295    /// See those methods for more information.
296    #[must_use]
297    pub fn from_env_or_default() -> Self {
298        let gles_minor_version = Gles3MinorVersion::from_env().unwrap_or_default();
299        let debug_fns = GlDebugFns::from_env().unwrap_or_default();
300        Self {
301            gles_minor_version,
302            fence_behavior: GlFenceBehavior::Normal,
303            debug_fns,
304        }
305    }
306
307    /// Takes the given options, modifies them based on the environment variables, and returns the result.
308    ///
309    /// This is equivalent to calling `with_env` on every field.
310    #[must_use]
311    pub fn with_env(self) -> Self {
312        let gles_minor_version = self.gles_minor_version.with_env();
313        let fence_behavior = self.fence_behavior.with_env();
314        let debug_fns = self.debug_fns.with_env();
315        Self {
316            gles_minor_version,
317            fence_behavior,
318            debug_fns,
319        }
320    }
321}
322
323/// Controls whether OpenGL debug functions are enabled.
324///
325/// Debug functions include `glPushDebugGroup`, `glPopDebugGroup`, `glObjectLabel`, etc.
326/// These are useful for debugging but can cause crashes on some buggy drivers.
327#[derive(Clone, Copy, Debug, PartialEq, Eq, ConstDefault!)]
328pub enum GlDebugFns {
329    /// Automatically decide whether to enable debug functions.
330    ///
331    /// Debug functions will be enabled if supported by the driver, unless
332    /// running on a device known to have buggy debug function implementations
333    /// (e.g., Mali GPUs which can crash in `glPushDebugGroup`).
334    ///
335    /// This is the default behavior.
336    #[custom(default)]
337    Auto,
338    /// Force enable debug functions if supported by the driver.
339    ///
340    /// This ignores any device-specific workarounds and enables debug functions
341    /// on all devices that support them, including those with known bugs.
342    ForceEnabled,
343    /// Disable debug functions entirely.
344    ///
345    /// Debug functions will not be used even if supported by the driver.
346    Disabled,
347}
348
349impl GlDebugFns {
350    /// Choose debug functions setting from the environment variable `WGPU_GL_DEBUG_FNS`.
351    ///
352    /// Possible values (case insensitive):
353    /// - `auto` - automatically decide based on device
354    /// - `forceenabled`, `force_enabled`, or `enabled` - force enable
355    /// - `disabled` - disable entirely
356    ///
357    /// Use with `unwrap_or_default()` to get the default value if the environment variable is not set.
358    #[must_use]
359    pub fn from_env() -> Option<Self> {
360        let value = crate::env::var("WGPU_GL_DEBUG_FNS")
361            .as_deref()?
362            .to_lowercase();
363        match value.as_str() {
364            "auto" => Some(Self::Auto),
365            "forceenabled" | "force_enabled" | "enabled" => Some(Self::ForceEnabled),
366            "disabled" => Some(Self::Disabled),
367            _ => None,
368        }
369    }
370
371    /// Takes the given setting, modifies it based on the `WGPU_GL_DEBUG_FNS` environment variable, and returns the result.
372    ///
373    /// See `from_env` for more information.
374    #[must_use]
375    pub fn with_env(self) -> Self {
376        if let Some(debug_fns) = Self::from_env() {
377            debug_fns
378        } else {
379            self
380        }
381    }
382}
383
384/// Used to force wgpu to expose certain features on passthrough shaders even when
385/// those features aren't present on runtime-compiled shaders
386#[derive(Clone, Debug, Eq, PartialEq, ConstDefault!)]
387pub struct ForceShaderModelToken {
388    inner: Option<DxcShaderModel>,
389}
390impl ForceShaderModelToken {
391    /// Creates an unsafe token, opting you in to seeing features that you may not necessarily use
392    /// on standard runtime-compiled shaders.
393    /// # Safety
394    /// Do not make use in runtime-compiled shaders of any features that may not be supported by the FXC or DXC
395    /// version you use.
396    pub const unsafe fn with_shader_model(sm: DxcShaderModel) -> Self {
397        Self { inner: Some(sm) }
398    }
399
400    /// Returns the shader model version, if any, in this token.
401    pub const fn get(&self) -> Option<DxcShaderModel> {
402        self.inner
403    }
404}
405
406/// Behavior when the Agility SDK fails to load.
407///
408/// See [`Dx12AgilitySDK`] for details on the Agility SDK.
409#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq, Eq)]
410pub enum Dx12AgilitySDKLoadFailure {
411    /// Log a warning and fall back to the system-installed D3D12 runtime.
412    ///
413    /// This is the default behavior and is appropriate for most applications.
414    #[custom(default)]
415    Fallback,
416    /// Fail instance creation entirely if the Agility SDK cannot be loaded.
417    ///
418    /// Use this in environments where you are shipping the Agility SDK alongside your application
419    /// and want to ensure that it is being loaded correctly.
420    Error,
421}
422
423impl Dx12AgilitySDKLoadFailure {
424    /// Read the load failure behavior from the environment variable
425    /// `WGPU_DX12_AGILITY_SDK_REQUIRE`.
426    ///
427    /// When set to `1`, returns [`Error`](Self::Error).
428    /// When set to `0`, returns [`Fallback`](Self::Fallback).
429    #[must_use]
430    pub fn from_env() -> Option<Self> {
431        let value = crate::env::var("WGPU_DX12_AGILITY_SDK_REQUIRE")?;
432        match value.as_str() {
433            "1" => Some(Self::Error),
434            "0" => Some(Self::Fallback),
435            _ => None,
436        }
437    }
438
439    /// Takes the given setting, modifies it based on the
440    /// `WGPU_DX12_AGILITY_SDK_REQUIRE` environment variable, and returns the result.
441    ///
442    /// See [`from_env`](Self::from_env) for more information.
443    #[must_use]
444    pub fn with_env(self) -> Self {
445        if let Some(v) = Self::from_env() {
446            v
447        } else {
448            self
449        }
450    }
451}
452
453/// Configuration for loading a specific [DirectX 12 Agility SDK] runtime.
454///
455/// The Agility SDK allows applications to ship a newer version of the D3D12 runtime
456/// (`D3D12Core.dll`) alongside the application, enabling access to the latest D3D12
457/// features without waiting for the OS to update its built-in runtime. This is the
458/// standard way for games and applications to adopt new D3D12 functionality on older
459/// Windows versions.
460///
461/// Downloads and release notes are available at the [DirectX 12 Agility SDK] page.
462///
463/// wgpu loads the Agility SDK via the [Independent Devices API], which allows
464/// specifying the SDK path and version at runtime without requiring exported constants
465/// or developer mode. The [`sdk_version`](Self::sdk_version) must match the version of
466/// the `D3D12Core.dll` in the provided path exactly, or loading will fail, irrespective of
467/// the OS's built-in runtime version.
468///
469/// If the shipped SDK is older than the system runtime, the system runtime will be used.
470/// This allows applications to ship a minimum SDK version while still benefiting from SDK updates on the user's system.
471///
472/// If the Agility SDK fails to load (version mismatch, missing DLL, unsupported OS,
473/// etc.), the behavior is controlled by [`on_load_failure`](Self::on_load_failure).
474/// By default, wgpu logs a warning and falls back to the system-installed D3D12 runtime.
475/// Set it to [`Error`](Dx12AgilitySDKLoadFailure::Error) to fail instance creation instead
476/// (useful in CI/testing).
477///
478/// ## OS requirements
479///
480/// The Independent Devices API requires a Windows update from August/September 2023
481/// or newer:
482///
483/// - [Windows 11 21H2+ (KB5029332)][win11-21h2]
484/// - [Windows 10 22H2+ (KB5029331)][win10-22h2]
485/// - [Windows Server 2022+ (KB5030216)][server-2022]
486///
487/// On older OS builds the Agility SDK will not load and wgpu will log a warning and
488/// fall back to the system runtime (or error, per [`on_load_failure`](Self::on_load_failure)).
489///
490/// [DirectX 12 Agility SDK]: https://devblogs.microsoft.com/directx/directx12agility/
491/// [Independent Devices API]: https://devblogs.microsoft.com/directx/d3d12-independent-devices/
492/// [win11-21h2]: https://support.microsoft.com/en-us/topic/august-22-2023-kb5029332-os-build-22000-2360-preview-8f8aec64-77b4-4225-9a0f-f0153204ae28
493/// [win10-22h2]: https://support.microsoft.com/en-gb/topic/august-22-2023-kb5029331-os-build-19045-3393-preview-9f6c1dbd-0ee6-469b-af24-f9d0bf35ca18
494/// [server-2022]: https://support.microsoft.com/en-au/topic/september-12-2023-kb5030216-os-build-20348-1970-34d4aff3-fd05-4270-b288-4ab6379c7f81
495#[derive(Clone, Debug, Eq, PartialEq)]
496pub struct Dx12AgilitySDK {
497    /// The Agility SDK version number (e.g., 614 for SDK version 1.614.0).
498    ///
499    /// This must match the version of the `D3D12Core.dll` at [`sdk_path`](Self::sdk_path)
500    /// exactly, or the runtime will fail to load.
501    pub sdk_version: u32,
502    /// Path to the directory containing the Agility SDK's `D3D12Core.dll`.
503    pub sdk_path: String,
504    /// What to do if the Agility SDK fails to load.
505    ///
506    /// Defaults to [`Fallback`](Dx12AgilitySDKLoadFailure::Fallback).
507    ///
508    /// Can also be set via the `WGPU_DX12_AGILITY_SDK_REQUIRE` environment variable
509    /// (`1` for [`Error`](Dx12AgilitySDKLoadFailure::Error),
510    /// `0` for [`Fallback`](Dx12AgilitySDKLoadFailure::Fallback)).
511    pub on_load_failure: Dx12AgilitySDKLoadFailure,
512}
513
514impl Dx12AgilitySDK {
515    /// Read Agility SDK configuration from environment variables.
516    ///
517    /// Reads `WGPU_DX12_AGILITY_SDK_PATH`, `WGPU_DX12_AGILITY_SDK_VERSION`,
518    /// and `WGPU_DX12_AGILITY_SDK_REQUIRE`.
519    /// Both path and version must be set for this to return `Some`.
520    #[must_use]
521    pub fn from_env() -> Option<Self> {
522        let sdk_path = crate::env::var("WGPU_DX12_AGILITY_SDK_PATH")?;
523        let sdk_version_str = crate::env::var("WGPU_DX12_AGILITY_SDK_VERSION")?;
524        let sdk_version = sdk_version_str.parse::<u32>().ok()?;
525        let on_load_failure = Dx12AgilitySDKLoadFailure::from_env().unwrap_or_default();
526        Some(Self {
527            sdk_version,
528            sdk_path,
529            on_load_failure,
530        })
531    }
532
533    /// Takes the given configuration, overrides fields with environment variables if present,
534    /// and returns the result.
535    ///
536    /// Reads `WGPU_DX12_AGILITY_SDK_PATH`, `WGPU_DX12_AGILITY_SDK_VERSION`,
537    /// and `WGPU_DX12_AGILITY_SDK_REQUIRE`.
538    /// Each variable overrides the corresponding field independently.
539    #[must_use]
540    pub fn with_env(mut self) -> Self {
541        if let Some(sdk_path) = crate::env::var("WGPU_DX12_AGILITY_SDK_PATH") {
542            self.sdk_path = sdk_path;
543        }
544        if let Some(sdk_version_str) = crate::env::var("WGPU_DX12_AGILITY_SDK_VERSION") {
545            if let Ok(sdk_version) = sdk_version_str.parse::<u32>() {
546                self.sdk_version = sdk_version;
547            }
548        }
549        self.on_load_failure = self.on_load_failure.with_env();
550        self
551    }
552}
553
554/// Configuration for the DX12 backend.
555///
556/// Part of [`BackendOptions`].
557#[derive(Clone, Debug, Eq, PartialEq, ConstDefault!)]
558pub struct Dx12BackendOptions {
559    /// Which DX12 shader compiler to use.
560    pub shader_compiler: Dx12Compiler,
561    /// Presentation system to use.
562    pub presentation_system: Dx12SwapchainKind,
563    /// Whether to wait for the latency waitable object before acquiring the next swapchain image.
564    pub latency_waitable_object: Dx12UseFrameLatencyWaitableObject,
565    /// For use with passthrough shaders. Expose features as if this shader model is present, even if you do not
566    /// intend to ship DXC with your app.
567    ///
568    /// This does not override the device's shader model version, only the external shader compiler's version.
569    pub force_shader_model: ForceShaderModelToken,
570    /// Optional Agility SDK configuration for using the Independent Devices API.
571    ///
572    /// When set, wgpu will attempt to load the specified D3D12 runtime via the
573    /// Independent Devices API. If the API is unavailable or the configuration is
574    /// invalid, it falls back to the system-installed D3D12 runtime.
575    ///
576    /// Can also be set via `WGPU_DX12_AGILITY_SDK_PATH` and `WGPU_DX12_AGILITY_SDK_VERSION`
577    /// environment variables.
578    pub agility_sdk: Option<Dx12AgilitySDK>,
579}
580
581impl Dx12BackendOptions {
582    /// Choose DX12 backend options by calling `from_env` on every field.
583    ///
584    /// See those methods for more information.
585    #[must_use]
586    pub fn from_env_or_default() -> Self {
587        let compiler = Dx12Compiler::from_env().unwrap_or_default();
588        let presentation_system = Dx12SwapchainKind::from_env().unwrap_or_default();
589        let latency_waitable_object =
590            Dx12UseFrameLatencyWaitableObject::from_env().unwrap_or_default();
591        let agility_sdk = Dx12AgilitySDK::from_env();
592        Self {
593            shader_compiler: compiler,
594            presentation_system,
595            latency_waitable_object,
596            force_shader_model: ForceShaderModelToken::default(),
597            agility_sdk,
598        }
599    }
600
601    /// Takes the given options, modifies them based on the environment variables, and returns the result.
602    ///
603    /// This is equivalent to calling `with_env` on every field.
604    #[must_use]
605    pub fn with_env(self) -> Self {
606        let shader_compiler = self.shader_compiler.with_env();
607        let presentation_system = self.presentation_system.with_env();
608        let latency_waitable_object = self.latency_waitable_object.with_env();
609        let agility_sdk = self
610            .agility_sdk
611            .map(|s| s.with_env())
612            .or_else(Dx12AgilitySDK::from_env);
613        Self {
614            shader_compiler,
615            presentation_system,
616            latency_waitable_object,
617            force_shader_model: ForceShaderModelToken::default(),
618            agility_sdk,
619        }
620    }
621}
622
623/// Configuration for the noop backend.
624///
625/// Part of [`BackendOptions`].
626#[derive(Clone, Debug, Eq, PartialEq, ConstDefault!)]
627pub struct NoopBackendOptions {
628    /// Whether to allow the noop backend to be used.
629    ///
630    /// The noop backend stubs out all operations except for buffer creation and mapping, so
631    /// it must not be used when not expected. Therefore, it will not be used unless explicitly
632    /// enabled.
633    pub enable: bool,
634
635    /// Specify the reported limits values. If `None`, reports maximally permissive limits.
636    pub limits: Option<crate::Limits>,
637
638    /// Specify the reported feature support. If `None`, reports support for all features.
639    pub features: Option<crate::Features>,
640
641    /// Specify the reported device type. If `None`, uses [`crate::DeviceType::Other`].
642    pub device_type: Option<crate::DeviceType>,
643
644    /// Specify the reported minimum subgroup size.
645    pub subgroup_min_size: Option<u32>,
646
647    /// Specify the reported maximum subgroup size.
648    pub subgroup_max_size: Option<u32>,
649}
650
651impl NoopBackendOptions {
652    /// Enable the noop backend.
653    pub fn enabled() -> Self {
654        Self {
655            enable: true,
656            ..Default::default()
657        }
658    }
659
660    /// Choose whether the noop backend is enabled from the environment.
661    ///
662    /// It will be enabled if the environment variable `WGPU_NOOP_BACKEND` has the value `1`
663    /// and not otherwise. Future versions may assign other meanings to other values.
664    #[must_use]
665    pub fn from_env_or_default() -> Self {
666        Self {
667            enable: Self::enable_from_env().unwrap_or(false),
668            ..Default::default()
669        }
670    }
671
672    /// Takes the given options, modifies them based on the environment variables, and returns the
673    /// result.
674    ///
675    /// See [`from_env_or_default()`](Self::from_env_or_default) for the interpretation.
676    #[must_use]
677    pub fn with_env(self) -> Self {
678        Self {
679            enable: Self::enable_from_env().unwrap_or(self.enable),
680            ..self
681        }
682    }
683
684    fn enable_from_env() -> Option<bool> {
685        let value = crate::env::var("WGPU_NOOP_BACKEND")?;
686        match value.as_str() {
687            "1" => Some(true),
688            "0" => Some(false),
689            _ => None,
690        }
691    }
692}
693
694#[derive(Clone, Debug, ConstDefault!, Copy, PartialEq, Eq)]
695/// Selects which kind of swapchain to use on DX12.
696pub enum Dx12SwapchainKind {
697    /// Use a DXGI swapchain made directly from the window's HWND.
698    ///
699    /// This does not support transparency but has better support from developer tooling from RenderDoc.
700    #[custom(default)]
701    DxgiFromHwnd,
702    /// Use a DXGI swapchain made from a DirectComposition visual made automatically from the window's HWND.
703    ///
704    /// This creates a single [`IDCompositionVisual`] over the entire window that is used by the `Surface`.
705    /// If a user wants to manage the composition tree themselves, they should create their own device and
706    /// composition, and pass the relevant visual down via [`SurfaceTargetUnsafe::CompositionVisual`][CV].
707    ///
708    /// This supports transparent windows, but does not have support from RenderDoc.
709    ///
710    /// [`IDCompositionVisual`]: https://learn.microsoft.com/en-us/windows/win32/api/dcomp/nn-dcomp-idcompositionvisual
711    #[doc = link_to_wgpu_docs!(["CV"]: "struct.SurfaceTargetUnsafe.html#variant.CompositionVisual")]
712    DxgiFromVisual,
713}
714
715impl Dx12SwapchainKind {
716    /// Choose which presentation system to use from the environment variable `WGPU_DX12_PRESENTATION_SYSTEM`.
717    ///
718    /// Valid values, case insensitive:
719    /// - `DxgiFromVisual` or `Visual`
720    /// - `DxgiFromHwnd` or `Hwnd` for [`Self::DxgiFromHwnd`]
721    #[must_use]
722    pub fn from_env() -> Option<Self> {
723        let value = crate::env::var("WGPU_DX12_PRESENTATION_SYSTEM")
724            .as_deref()?
725            .to_lowercase();
726        match value.as_str() {
727            "dxgifromvisual" | "visual" => Some(Self::DxgiFromVisual),
728            "dxgifromhwnd" | "hwnd" => Some(Self::DxgiFromHwnd),
729            _ => None,
730        }
731    }
732
733    /// Takes the given presentation system, modifies it based on the `WGPU_DX12_PRESENTATION_SYSTEM` environment variable, and returns the result.
734    ///
735    /// See [`from_env`](Self::from_env) for more information.
736    #[must_use]
737    pub fn with_env(self) -> Self {
738        if let Some(presentation_system) = Self::from_env() {
739            presentation_system
740        } else {
741            self
742        }
743    }
744}
745
746/// Configuration for the Vulkan backend.
747///
748/// Part of [`BackendOptions`].
749#[derive(Clone, Debug, Eq, PartialEq, ConstDefault!)]
750pub struct VulkanBackendOptions {
751    /// Which kind of swapchain to use.
752    pub swapchain_kind: VulkanSwapchainKind,
753    /// D3D12 Agility SDK to load for the interop device backing a DXGI [`swapchain_kind`].
754    ///
755    /// A `Dxgi*` swapchain kind presents through an interop D3D12 device; this is the same
756    /// [`Dx12AgilitySDK`] configuration the DX12 backend uses, applied to that device. Ignored for
757    /// [`VulkanSwapchainKind::Native`].
758    ///
759    /// [`swapchain_kind`]: Self::swapchain_kind
760    pub agility_sdk: Option<Dx12AgilitySDK>,
761}
762
763impl VulkanBackendOptions {
764    /// Choose Vulkan backend options by calling `from_env` on every field.
765    ///
766    /// See those methods for more information.
767    #[must_use]
768    pub fn from_env_or_default() -> Self {
769        let swapchain_kind = VulkanSwapchainKind::from_env().unwrap_or_default();
770        let agility_sdk = Dx12AgilitySDK::from_env();
771        Self {
772            swapchain_kind,
773            agility_sdk,
774        }
775    }
776
777    /// Takes the given options, modifies them based on the environment variables, and returns the result.
778    ///
779    /// This is equivalent to calling `with_env` on every field.
780    #[must_use]
781    pub fn with_env(self) -> Self {
782        let swapchain_kind = self.swapchain_kind.with_env();
783        let agility_sdk = self
784            .agility_sdk
785            .map(|sdk| sdk.with_env())
786            .or_else(Dx12AgilitySDK::from_env);
787        Self {
788            swapchain_kind,
789            agility_sdk,
790        }
791    }
792}
793
794/// Selects which kind of swapchain to use on Vulkan.
795///
796/// The DXGI kinds fall back to [`Self::Native`] for the whole instance, with a warning, if the
797/// platform is not Windows, or if the DXGI factory, `d3d12.dll`, or the D3D12 device factory is
798/// not available.
799///
800/// With a DXGI kind, presentation is not available on an adapter that has no LUID, no timeline
801/// semaphores, no `VK_KHR_external_memory_win32` or `VK_KHR_external_semaphore_win32`, or
802/// cannot import D3D12 fences. A surface only reports the formats that the adapter can import
803/// as D3D12 resources, and is not supported if there are none. Surface configuration fails if
804/// no DXGI adapter has the LUID of the Vulkan device, or if the D3D12 device on it does not
805/// support Shader Model 6.0. A missing LUID or missing Shader Model 6.0 support indicates old
806/// hardware or an old driver.
807#[derive(Clone, Copy, Debug, ConstDefault!, PartialEq, Eq)]
808pub enum VulkanSwapchainKind {
809    /// Use a native vulkan swapchain via `VK_KHR_swapchain`.
810    #[custom(default)]
811    Native,
812    /// Use a DXGI swapchain presenting directly to a HWND.
813    ///
814    /// This mode may give better frame pacing, lower latency, and more predictable performance than
815    /// the native swapchain on Windows.
816    ///
817    /// When using RenderDoc, this mode will cause RenderDoc to only capture the work on the D3D12 interop device,
818    /// not the work on the Vulkan device. However [`Device::start_graphics_debugger_capture`] will still function
819    /// correctly and result in a vulkan capture.
820    ///
821    /// Nsight and RGP profiling continue to work.
822    ///
823    /// To have a transparent window with DXGI, use [`Self::DxgiFromVisual`] instead.
824    ///
825    #[doc = link_to_wgpu_docs!(["`Device::start_graphics_debugger_capture`"]: "struct.Device.html#method.start_graphics_debugger_capture")]
826    DxgiFromHwnd,
827    /// Use a DXGI swapchain presenting to a DirectComposition visual created from the HWND.
828    ///
829    /// This mode may give better frame pacing, lower latency, and more predictable performance than
830    /// the native swapchain on Windows.
831    ///
832    /// Nsight and RGP profiling continue to work.
833    ///
834    /// This mode supports transparent windows, but does not have support from RenderDoc and may have memory overhead
835    /// compared to [`Self::DxgiFromHwnd`].
836    DxgiFromVisual,
837}
838
839impl VulkanSwapchainKind {
840    /// Choose which swapchain kind to use from the environment variable `WGPU_VULKAN_SWAPCHAIN_KIND`.
841    ///
842    /// Valid values, case insensitive:
843    /// - `native`
844    /// - `dxgi-hwnd`
845    /// - `dxgi-visual`
846    #[must_use]
847    pub fn from_env() -> Option<Self> {
848        let value = crate::env::var("WGPU_VULKAN_SWAPCHAIN_KIND")
849            .as_deref()?
850            .to_lowercase();
851        match value.as_str() {
852            "native" => Some(Self::Native),
853            "dxgi-hwnd" => Some(Self::DxgiFromHwnd),
854            "dxgi-visual" => Some(Self::DxgiFromVisual),
855            _ => None,
856        }
857    }
858
859    /// Takes the given swapchain kind, modifies it based on the `WGPU_VULKAN_SWAPCHAIN_KIND` environment variable, and returns the result.
860    ///
861    /// See [`from_env`](Self::from_env) for more information.
862    #[must_use]
863    pub fn with_env(self) -> Self {
864        if let Some(swapchain_kind) = Self::from_env() {
865            swapchain_kind
866        } else {
867            self
868        }
869    }
870}
871
872/// DXC shader model.
873#[derive(Clone, Copy, Eq, PartialEq, Debug)]
874#[expect(missing_docs, reason = "variants are self-explanatory version numbers")]
875pub enum DxcShaderModel {
876    V6_0,
877    V6_1,
878    V6_2,
879    V6_3,
880    V6_4,
881    V6_5,
882    V6_6,
883    V6_7,
884    V6_8,
885    V6_9,
886}
887
888impl DxcShaderModel {
889    /// Get the shader model supported by a certain DXC version.
890    pub fn from_dxc_version(major: u32, minor: u32) -> Self {
891        // DXC version roughly has corresponded to shader model so far, where DXC 1.x supports SM 6.x.
892        // See discussion in https://discord.com/channels/590611987420020747/996417435374714920/1471234702206701650.
893        // Presumably DXC 2.0 and up will still support shader model 6.9.
894        if major > 1 {
895            Self::V6_9
896        } else {
897            Self::from_parts(6, minor)
898        }
899    }
900
901    /// Parse a DxcShaderModel from its version components.
902    pub fn from_parts(major: u32, minor: u32) -> Self {
903        if major > 6 || minor > 8 {
904            Self::V6_9
905        } else {
906            match minor {
907                0 => DxcShaderModel::V6_0,
908                1 => DxcShaderModel::V6_1,
909                2 => DxcShaderModel::V6_2,
910                3 => DxcShaderModel::V6_3,
911                4 => DxcShaderModel::V6_4,
912                5 => DxcShaderModel::V6_5,
913                6 => DxcShaderModel::V6_6,
914                7 => DxcShaderModel::V6_7,
915                8 => DxcShaderModel::V6_8,
916                9 => DxcShaderModel::V6_9,
917                // > 6.9
918                _ => DxcShaderModel::V6_9,
919            }
920        }
921    }
922}
923
924/// Selects which DX12 shader compiler to use.
925#[derive(Clone, Debug, Eq, PartialEq, ConstDefault!)]
926pub enum Dx12Compiler {
927    /// The Fxc compiler (default) is old, slow and unmaintained.
928    ///
929    /// However, it doesn't require any additional .dlls to be shipped with the application.
930    Fxc,
931    /// The Dxc compiler is new, fast and maintained.
932    ///
933    /// However, it requires `dxcompiler.dll` to be shipped with the application.
934    /// These files can be downloaded from <https://github.com/microsoft/DirectXShaderCompiler/releases>.
935    ///
936    /// Minimum supported version: [v1.8.2502](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.8.2502)
937    ///
938    /// It also requires WDDM 2.1 (Windows 10 version 1607).
939    DynamicDxc {
940        /// Path to `dxcompiler.dll`.
941        dxc_path: String,
942    },
943    /// The statically-linked variant of Dxc.
944    ///
945    /// The `static-dxc` feature is required for this setting to be used successfully on DX12.
946    /// Not available on `windows-aarch64-pc-*` targets.
947    StaticDxc,
948    /// Use statically-linked DXC if available. Otherwise check for dynamically linked DXC on the PATH. Finally, fallback to FXC.
949    #[custom(default)]
950    Auto,
951}
952
953impl Dx12Compiler {
954    /// Helper function to construct a `DynamicDxc` variant with default paths.
955    ///
956    /// The dll must support at least shader model 6.8.
957    pub fn default_dynamic_dxc() -> Self {
958        Self::DynamicDxc {
959            dxc_path: String::from("dxcompiler.dll"),
960        }
961    }
962
963    /// Choose which DX12 shader compiler to use from the environment variable `WGPU_DX12_COMPILER`.
964    ///
965    /// Valid values, case insensitive:
966    /// - `Fxc`
967    /// - `Dxc` or `DynamicDxc`
968    /// - `StaticDxc`
969    #[must_use]
970    pub fn from_env() -> Option<Self> {
971        let env = crate::env::var("WGPU_DX12_COMPILER")?;
972        env.parse().map_err(|expected_msg| {
973            log::warn!(
974                "Unknown value `{env:?}` for `WGPU_DX12_COMPILER` environment variable. {expected_msg}"
975            )
976        })
977        .ok()
978    }
979
980    /// Takes the given compiler, modifies it based on the `WGPU_DX12_COMPILER` environment variable, and returns the result.
981    ///
982    /// See `from_env` for more information.
983    #[must_use]
984    pub fn with_env(self) -> Self {
985        if let Some(compiler) = Self::from_env() {
986            compiler
987        } else {
988            self
989        }
990    }
991}
992
993impl FromStr for Dx12Compiler {
994    type Err = &'static str;
995
996    fn from_str(value: &str) -> Result<Self, Self::Err> {
997        Ok(match value.to_lowercase().as_str() {
998            "dxc" | "dynamicdxc" => Self::default_dynamic_dxc(),
999            "staticdxc" => Self::StaticDxc,
1000            "fxc" => Self::Fxc,
1001            "auto" => Self::Auto,
1002            path => Self::DynamicDxc {
1003                dxc_path: path.to_string(),
1004            },
1005        })
1006    }
1007}
1008
1009/// Whether and how to use a waitable handle obtained from `GetFrameLatencyWaitableObject`.
1010///
1011/// Only the DX12 backend uses this option. The DXGI swapchain of the Vulkan backend always waits
1012/// for the waitable handle.
1013#[derive(Clone, Debug, Eq, PartialEq, ConstDefault!)]
1014pub enum Dx12UseFrameLatencyWaitableObject {
1015    /// Do not obtain a waitable handle and do not wait for it. The swapchain will
1016    /// be created without the `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT` flag.
1017    None,
1018    /// Obtain a waitable handle and wait for it before acquiring the next swapchain image.
1019    #[custom(default)]
1020    Wait,
1021    /// Create the swapchain with the `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT` flag and
1022    /// obtain a waitable handle, but do not wait for it before acquiring the next swapchain image.
1023    /// This is useful if the application wants to wait for the waitable object itself.
1024    DontWait,
1025}
1026
1027impl Dx12UseFrameLatencyWaitableObject {
1028    /// Choose whether to use a frame latency waitable object from the environment variable `WGPU_DX12_USE_FRAME_LATENCY_WAITABLE_OBJECT`.
1029    ///
1030    /// Valid values, case insensitive:
1031    /// - `None`
1032    /// - `Wait`
1033    /// - `DontWait`
1034    #[must_use]
1035    pub fn from_env() -> Option<Self> {
1036        let value = crate::env::var("WGPU_DX12_USE_FRAME_LATENCY_WAITABLE_OBJECT")
1037            .as_deref()?
1038            .to_lowercase();
1039        match value.as_str() {
1040            "none" => Some(Self::None),
1041            "wait" => Some(Self::Wait),
1042            "dontwait" => Some(Self::DontWait),
1043            _ => None,
1044        }
1045    }
1046
1047    /// Takes the given setting, modifies it based on the `WGPU_DX12_USE_FRAME_LATENCY_WAITABLE_OBJECT` environment variable, and returns the result.
1048    ///
1049    /// See `from_env` for more information.
1050    #[must_use]
1051    pub fn with_env(self) -> Self {
1052        if let Some(compiler) = Self::from_env() {
1053            compiler
1054        } else {
1055            self
1056        }
1057    }
1058}
1059
1060/// Selects which OpenGL ES 3 minor version to request.
1061///
1062/// When using ANGLE as an OpenGL ES/EGL implementation, explicitly requesting `Version1` can provide a non-conformant ES 3.1 on APIs like D3D11.
1063#[derive(Clone, Copy, Debug, ConstDefault!, Eq, PartialEq, Hash)]
1064pub enum Gles3MinorVersion {
1065    /// No explicit minor version is requested, the driver automatically picks the highest available.
1066    #[custom(default)]
1067    Automatic,
1068
1069    /// Request an ES 3.0 context.
1070    Version0,
1071
1072    /// Request an ES 3.1 context.
1073    Version1,
1074
1075    /// Request an ES 3.2 context.
1076    Version2,
1077}
1078
1079impl Gles3MinorVersion {
1080    /// Choose which minor OpenGL ES version to use from the environment variable `WGPU_GLES_MINOR_VERSION`.
1081    ///
1082    /// Possible values are `0`, `1`, `2` or `automatic`. Case insensitive.
1083    ///
1084    /// Use with `unwrap_or_default()` to get the default value if the environment variable is not set.
1085    #[must_use]
1086    pub fn from_env() -> Option<Self> {
1087        let value = crate::env::var("WGPU_GLES_MINOR_VERSION")
1088            .as_deref()?
1089            .to_lowercase();
1090        match value.as_str() {
1091            "automatic" => Some(Self::Automatic),
1092            "0" => Some(Self::Version0),
1093            "1" => Some(Self::Version1),
1094            "2" => Some(Self::Version2),
1095            _ => None,
1096        }
1097    }
1098
1099    /// Takes the given compiler, modifies it based on the `WGPU_GLES_MINOR_VERSION` environment variable, and returns the result.
1100    ///
1101    /// See `from_env` for more information.
1102    #[must_use]
1103    pub fn with_env(self) -> Self {
1104        if let Some(compiler) = Self::from_env() {
1105            compiler
1106        } else {
1107            self
1108        }
1109    }
1110}
1111
1112/// Dictate the behavior of fences in OpenGL.
1113#[derive(Clone, Copy, Debug, PartialEq, Eq, ConstDefault!)]
1114pub enum GlFenceBehavior {
1115    /// Fences in OpenGL behave normally. If you don't know what to pick, this is what you want.
1116    #[custom(default)]
1117    Normal,
1118    /// Fences in OpenGL are short-circuited to always return `true` immediately.
1119    ///
1120    /// This solves a very specific issue that arose due to a bug in wgpu-core that made
1121    /// many WebGL programs work when they "shouldn't" have. If you have code that is trying
1122    /// to call `device.poll(wgpu::PollType::Wait)` on WebGL, you need to enable this option
1123    /// for the "Wait" to behave how you would expect.
1124    ///
1125    /// Previously all `poll(Wait)` acted like the OpenGL fences were signalled even if they weren't.
1126    /// See <https://github.com/gfx-rs/wgpu/issues/4589> for more information.
1127    ///
1128    /// When this is set `Queue::on_completed_work_done` will always return the next time the device
1129    /// is maintained, not when the work is actually done on the GPU.
1130    AutoFinish,
1131}
1132
1133impl GlFenceBehavior {
1134    /// Returns true if the fence behavior is `AutoFinish`.
1135    pub fn is_auto_finish(&self) -> bool {
1136        matches!(self, Self::AutoFinish)
1137    }
1138
1139    /// Returns true if the fence behavior is `Normal`.
1140    pub fn is_normal(&self) -> bool {
1141        matches!(self, Self::Normal)
1142    }
1143
1144    /// Choose which minor OpenGL ES version to use from the environment variable `WGPU_GL_FENCE_BEHAVIOR`.
1145    ///
1146    /// Possible values are `Normal` or `AutoFinish`. Case insensitive.
1147    ///
1148    /// Use with `unwrap_or_default()` to get the default value if the environment variable is not set.
1149    #[must_use]
1150    pub fn from_env() -> Option<Self> {
1151        let value = crate::env::var("WGPU_GL_FENCE_BEHAVIOR")
1152            .as_deref()?
1153            .to_lowercase();
1154        match value.as_str() {
1155            "normal" => Some(Self::Normal),
1156            "autofinish" => Some(Self::AutoFinish),
1157            _ => None,
1158        }
1159    }
1160
1161    /// Takes the given compiler, modifies it based on the `WGPU_GL_FENCE_BEHAVIOR` environment variable, and returns the result.
1162    ///
1163    /// See `from_env` for more information.
1164    #[must_use]
1165    pub fn with_env(self) -> Self {
1166        if let Some(fence) = Self::from_env() {
1167            fence
1168        } else {
1169            self
1170        }
1171    }
1172}