Skip to main content

wgpu_hal/
lib.rs

1//! A cross-platform unsafe graphics abstraction.
2//!
3//! This crate defines a set of traits abstracting over modern graphics APIs,
4//! with implementations ("backends") for Vulkan, Metal, Direct3D, and GL.
5//!
6//! `wgpu-hal` is a spiritual successor to
7//! [gfx-hal](https://github.com/gfx-rs/gfx), but with reduced scope, and
8//! oriented towards WebGPU implementation goals. It has no overhead for
9//! validation or tracking, and the API translation overhead is kept to the bare
10//! minimum by the design of WebGPU. This API can be used for resource-demanding
11//! applications and engines.
12//!
13//! The `wgpu-hal` crate's main design choices:
14//!
15//! - Our traits are meant to be *portable*: proper use
16//!   should get equivalent results regardless of the backend.
17//!
18//! - Our traits' contracts are *unsafe*: implementations perform minimal
19//!   validation, if any, and incorrect use will often cause undefined behavior.
20//!   This allows us to minimize the overhead we impose over the underlying
21//!   graphics system. If you need safety, the [`wgpu-core`] crate provides a
22//!   safe API for driving `wgpu-hal`, implementing all necessary validation,
23//!   resource state tracking, and so on. (Note that `wgpu-core` is designed for
24//!   use via FFI; the [`wgpu`] crate provides more idiomatic Rust bindings for
25//!   `wgpu-core`.) Or, you can do your own validation.
26//!
27//! - In the same vein, returned errors *only cover cases the user can't
28//!   anticipate*, like running out of memory or losing the device. Any errors
29//!   that the user could reasonably anticipate are their responsibility to
30//!   avoid. For example, `wgpu-hal` returns no error for mapping a buffer that's
31//!   not mappable: as the buffer creator, the user should already know if they
32//!   can map it.
33//!
34//! - We use *static dispatch*. The traits are not
35//!   generally object-safe. You must select a specific backend type
36//!   like [`vulkan::Api`] or [`metal::Api`], and then use that
37//!   according to the main traits, or call backend-specific methods.
38//!
39//! - We use *idiomatic Rust parameter passing*,
40//!   taking objects by reference, returning them by value, and so on,
41//!   unlike `wgpu-core`, which refers to objects by ID.
42//!
43//! - We map buffer contents *persistently*. This means that the buffer can
44//!   remain mapped on the CPU while the GPU reads or writes to it. You must
45//!   explicitly indicate when data might need to be transferred between CPU and
46//!   GPU, if [`Device::map_buffer`] indicates that this is necessary.
47//!
48//! - You must record *explicit barriers* between different usages of a
49//!   resource. For example, if a buffer is written to by a compute
50//!   shader, and then used as and index buffer to a draw call, you
51//!   must use [`CommandEncoder::transition_buffers`] between those two
52//!   operations.
53//!
54//! - Pipeline layouts are *explicitly specified* when setting bind groups.
55//!   Incompatible layouts disturb groups bound at higher indices.
56//!
57//! - The API *accepts collections as iterators*, to avoid forcing the user to
58//!   store data in particular containers. The implementation doesn't guarantee
59//!   that any of the iterators are drained, unless stated otherwise by the
60//!   function documentation. For this reason, we recommend that iterators don't
61//!   do any mutating work.
62//!
63//! Unfortunately, `wgpu-hal`'s safety requirements are not fully documented.
64//! Ideally, all trait methods would have doc comments setting out the
65//! requirements users must meet to ensure correct and portable behavior. If you
66//! are aware of a specific requirement that a backend imposes that is not
67//! ensured by the traits' documented rules, please file an issue. Or, if you are
68//! a capable technical writer, please file a pull request!
69//!
70//! [`wgpu-core`]: https://crates.io/crates/wgpu-core
71//! [`wgpu`]: https://crates.io/crates/wgpu
72//! [`vulkan::Api`]: vulkan/struct.Api.html
73//! [`metal::Api`]: metal/struct.Api.html
74//!
75//! ## Primary backends
76//!
77//! The `wgpu-hal` crate has full-featured backends implemented on the following
78//! platform graphics APIs:
79//!
80//! - Vulkan, available on Linux, Android, and Windows, using the [`ash`] crate's
81//!   Vulkan bindings. It's also available on macOS, if you install [MoltenVK].
82//!
83//! - Metal on macOS, using the [`metal`] crate's bindings.
84//!
85//! - Direct3D 12 on Windows, using the [`windows`] crate's bindings.
86//!
87//! [`ash`]: https://crates.io/crates/ash
88//! [MoltenVK]: https://github.com/KhronosGroup/MoltenVK
89//! [`metal`]: https://crates.io/crates/metal
90//! [`windows`]: https://crates.io/crates/windows
91//!
92//! ## Secondary backends
93//!
94//! The `wgpu-hal` crate has a partial implementation based on the following
95//! platform graphics API:
96//!
97//! - The GL backend is available anywhere OpenGL, OpenGL ES, or WebGL are
98//!   available. See the [`gles`] module documentation for details.
99//!
100//! [`gles`]: gles/index.html
101//!
102//! You can see what capabilities an adapter is missing by checking the
103//! [`DownlevelCapabilities`][tdc] in [`ExposedAdapter::capabilities`], available
104//! from [`Instance::enumerate_adapters`].
105//!
106//! The API is generally designed to fit the primary backends better than the
107//! secondary backends, so the latter may impose more overhead.
108//!
109//! [tdc]: wgt::DownlevelCapabilities
110//!
111//! ## Traits
112//!
113//! The `wgpu-hal` crate defines a handful of traits that together
114//! represent a cross-platform abstraction for modern GPU APIs.
115//!
116//! - The [`Api`] trait represents a `wgpu-hal` backend. It has no methods of its
117//!   own, only a collection of associated types.
118//!
119//! - [`Api::Instance`] implements the [`Instance`] trait. [`Instance::init`]
120//!   creates an instance value, which you can use to enumerate the adapters
121//!   available on the system. For example, [`vulkan::Api::Instance::init`][Ii]
122//!   returns an instance that can enumerate the Vulkan physical devices on your
123//!   system.
124//!
125//! - [`Api::Adapter`] implements the [`Adapter`] trait, representing a
126//!   particular device from a particular backend. For example, a Vulkan instance
127//!   might have a Lavapipe software adapter and a GPU-based adapter.
128//!
129//! - [`Api::Device`] implements the [`Device`] trait, representing an active
130//!   link to a device. You get a device value by calling [`Adapter::open`], and
131//!   then use it to create buffers, textures, shader modules, and so on.
132//!
133//! - [`Api::Queue`] implements the [`Queue`] trait, which you use to submit
134//!   command buffers to a given device.
135//!
136//! - [`Api::CommandEncoder`] implements the [`CommandEncoder`] trait, which you
137//!   use to build buffers of commands to submit to a queue. This has all the
138//!   methods for drawing and running compute shaders, which is presumably what
139//!   you're here for.
140//!
141//! - [`Api::Surface`] implements the [`Surface`] trait, which represents a
142//!   swapchain for presenting images on the screen, via interaction with the
143//!   system's window manager.
144//!
145//! The [`Api`] trait has various other associated types like [`Api::Buffer`] and
146//! [`Api::Texture`] that represent resources the rest of the interface can
147//! operate on, but these generally do not have their own traits.
148//!
149//! [Ii]: Instance::init
150//!
151//! ## Validation is the calling code's responsibility, not `wgpu-hal`'s
152//!
153//! As much as possible, `wgpu-hal` traits place the burden of validation,
154//! resource tracking, and state tracking on the caller, not on the trait
155//! implementations themselves. Anything which can reasonably be handled in
156//! backend-independent code should be. A `wgpu_hal` backend's sole obligation is
157//! to provide portable behavior, and report conditions that the calling code
158//! can't reasonably anticipate, like device loss or running out of memory.
159//!
160//! The `wgpu` crate collection is intended for use in security-sensitive
161//! applications, like web browsers, where the API is available to untrusted
162//! code. This means that `wgpu-core`'s validation is not simply a service to
163//! developers, to be provided opportunistically when the performance costs are
164//! acceptable and the necessary data is ready at hand. Rather, `wgpu-core`'s
165//! validation must be exhaustive, to ensure that even malicious content cannot
166//! provoke and exploit undefined behavior in the platform's graphics API.
167//!
168//! Because graphics APIs' requirements are complex, the only practical way for
169//! `wgpu` to provide exhaustive validation is to comprehensively track the
170//! lifetime and state of all the resources in the system. Implementing this
171//! separately for each backend is infeasible; effort would be better spent
172//! making the cross-platform validation in `wgpu-core` legible and trustworthy.
173//! Fortunately, the requirements are largely similar across the various
174//! platforms, so cross-platform validation is practical.
175//!
176//! Some backends have specific requirements that aren't practical to foist off
177//! on the `wgpu-hal` user. For example, properly managing macOS Objective-C or
178//! Microsoft COM reference counts is best handled by using appropriate pointer
179//! types within the backend.
180//!
181//! A desire for "defense in depth" may suggest performing additional validation
182//! in `wgpu-hal` when the opportunity arises, but this must be done with
183//! caution. Even experienced contributors infer the expectations their changes
184//! must meet by considering not just requirements made explicit in types, tests,
185//! assertions, and comments, but also those implicit in the surrounding code.
186//! When one sees validation or state-tracking code in `wgpu-hal`, it is tempting
187//! to conclude, "Oh, `wgpu-hal` checks for this, so `wgpu-core` needn't worry
188//! about it - that would be redundant!" The responsibility for exhaustive
189//! validation always rests with `wgpu-core`, regardless of what may or may not
190//! be checked in `wgpu-hal`.
191//!
192//! To this end, any "defense in depth" validation that does appear in `wgpu-hal`
193//! for requirements that `wgpu-core` should have enforced should report failure
194//! via the `unreachable!` macro, because problems detected at this stage always
195//! indicate a bug in `wgpu-core`.
196//!
197//! ## Debugging
198//!
199//! Most of the information in the [Debugging wgpu Applications][debug-docs]
200//! documentation still applies to this API, with the exception of API
201//! tracing/replay functionality, which is only available in `wgpu-core`.
202//!
203//! [debug-docs]: https://docs.rs/wgpu/latest/wgpu/documentation/debugging/debugging_applications/index.html
204
205#![no_std]
206#![cfg_attr(docsrs, feature(doc_cfg))]
207#![allow(
208    // this happens on the GL backend, where it is both thread safe and non-thread safe in the same code.
209    clippy::arc_with_non_send_sync,
210    // We don't use syntax sugar where it's not necessary.
211    clippy::match_like_matches_macro,
212    // Redundant matching is more explicit.
213    clippy::redundant_pattern_matching,
214    // Explicit lifetimes are often easier to reason about.
215    clippy::needless_lifetimes,
216    // No need for defaults in the internal types.
217    clippy::new_without_default,
218    // Matches are good and extendable, no need to make an exception here.
219    clippy::single_match,
220    // Push commands are more regular than macros.
221    clippy::vec_init_then_push,
222    // TODO!
223    clippy::missing_safety_doc,
224    // It gets in the way a lot and does not prevent bugs in practice.
225    clippy::pattern_type_mismatch,
226    // We should investigate these.
227    clippy::large_enum_variant
228)]
229#![warn(
230    clippy::alloc_instead_of_core,
231    clippy::ptr_as_ptr,
232    clippy::std_instead_of_alloc,
233    clippy::std_instead_of_core,
234    trivial_casts,
235    trivial_numeric_casts,
236    unsafe_op_in_unsafe_fn,
237    unused_extern_crates,
238    unused_qualifications
239)]
240
241extern crate alloc;
242#[allow(unused_extern_crates)]
243extern crate naga_types as nt;
244extern crate wgpu_types as wgt;
245// Each of these backends needs `std` in some fashion; usually `std::thread` functions.
246#[cfg(any(dx12, gles_with_std, metal, vulkan, test))]
247#[macro_use]
248extern crate std;
249
250/// DirectX12 API internals.
251#[cfg(dx12)]
252pub mod dx12;
253/// GLES API internals.
254#[cfg(gles)]
255pub mod gles;
256/// Metal API internals.
257#[cfg(metal)]
258pub mod metal;
259/// A dummy API implementation.
260// TODO(https://github.com/gfx-rs/wgpu/issues/7120): this should have a cfg
261pub mod noop;
262/// Vulkan API internals.
263#[cfg(vulkan)]
264pub mod vulkan;
265
266pub mod auxil;
267pub mod api {
268    #[cfg(dx12)]
269    pub use super::dx12::Api as Dx12;
270    #[cfg(gles)]
271    pub use super::gles::Api as Gles;
272    #[cfg(metal)]
273    pub use super::metal::Api as Metal;
274    pub use super::noop::Api as Noop;
275    #[cfg(vulkan)]
276    pub use super::vulkan::Api as Vulkan;
277}
278
279mod dynamic;
280#[cfg(feature = "validation_canary")]
281mod validation_canary;
282
283#[cfg(feature = "validation_canary")]
284pub use validation_canary::{ValidationCanary, VALIDATION_CANARY};
285
286pub(crate) use dynamic::impl_dyn_resource;
287pub use dynamic::{
288    DynAccelerationStructure, DynAcquiredSurfaceTexture, DynAdapter, DynBindGroup,
289    DynBindGroupLayout, DynBuffer, DynCommandBuffer, DynCommandEncoder, DynComputePipeline,
290    DynDevice, DynExposedAdapter, DynFence, DynInstance, DynOpenDevice, DynPipelineCache,
291    DynPipelineLayout, DynQuerySet, DynQueue, DynRayTracingPipeline, DynRenderPipeline,
292    DynResource, DynSampler, DynShaderModule, DynSurface, DynSurfaceTexture, DynTexture,
293    DynTextureView,
294};
295
296#[allow(unused)]
297use alloc::boxed::Box;
298use alloc::{borrow::Cow, string::String, vec::Vec};
299use core::{
300    borrow::Borrow,
301    error::Error,
302    fmt,
303    num::NonZeroU32,
304    ops::{Range, RangeInclusive},
305    ptr::NonNull,
306};
307
308use bitflags::bitflags;
309use raw_window_handle::DisplayHandle;
310use thiserror::Error;
311use wgpu_sync::Arc;
312use wgt::WasmNotSendSync;
313
314// - Vertex + Fragment
315// - Compute
316// Task + Mesh + Fragment
317pub const MAX_CONCURRENT_SHADER_STAGES: usize = 3;
318pub const MAX_ANISOTROPY: u8 = 16;
319pub const MAX_BIND_GROUPS: usize = 8;
320pub const MAX_VERTEX_BUFFERS: usize = 16;
321pub const MAX_COLOR_ATTACHMENTS: usize = 8;
322pub const MAX_MIP_LEVELS: u32 = 16;
323/// Size of a single occlusion/timestamp query, when copied into a buffer, in bytes.
324/// cbindgen:ignore
325pub const QUERY_SIZE: wgt::BufferAddress = 8;
326// The struct itself is defined in core, but we need to know the size.
327// There is a const assert for correctness located with the struct definition.
328#[doc(hidden)]
329pub const EXTERNAL_TEXTURE_PARAMS_SIZE: wgt::BufferAddress = 208;
330/// Universally safe value for buffer size alignment.
331///
332/// This is determined by `D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT`.
333pub const UNIVERSAL_BUFFER_SIZE_ALIGNMENT: wgt::BufferAddress = 256;
334
335pub type Label<'a> = Option<&'a str>;
336pub type MemoryRange = Range<wgt::BufferAddress>;
337pub type FenceValue = u64;
338pub type AtomicFenceValue = wgpu_sync::atomic::AtomicU64;
339
340/// A callback to signal that wgpu is no longer using a resource.
341#[cfg(all(any(gles, vulkan, metal, dx12), not(webgl)))]
342pub type DropCallback = Box<dyn FnOnce() + Send + Sync + 'static>;
343
344/// A callback to signal that wgpu is no longer using a resource.
345///
346/// On WebGL the callback is not required to be `Send + Sync`, so it can
347/// capture JS handles — e.g. to `gl.deleteTexture` an imported
348/// `web_sys::WebGlTexture` once wgpu is done with it.
349#[cfg(webgl)]
350pub type DropCallback = Box<dyn FnOnce() + 'static>;
351
352#[cfg(any(gles, vulkan, metal, dx12))]
353pub struct DropGuard {
354    callback: Option<DropCallback>,
355}
356
357// SAFETY: On WebGL the callback may capture JS values, which are neither
358// `Send` nor `Sync`. Claiming both under the `send_sync` cfg follows the
359// `fragile-send-sync-non-atomic-wasm` contract: that feature promises the
360// program runs on a single thread (wasm without atomics).
361#[cfg(all(webgl, send_sync))]
362unsafe impl Send for DropGuard {}
363#[cfg(all(webgl, send_sync))]
364unsafe impl Sync for DropGuard {}
365
366#[cfg(any(gles, vulkan, metal, dx12))]
367impl DropGuard {
368    #[cfg(any(native, Emscripten))]
369    fn from_option(callback: Option<DropCallback>) -> Option<Self> {
370        callback.map(Self::new)
371    }
372
373    /// A guard that may carry no callback, for resources that are externally
374    /// owned regardless of whether the caller wants a notification: the
375    /// guard's presence is what marks the resource as never-deleted-by-wgpu.
376    #[cfg(webgl)]
377    fn external(callback: Option<DropCallback>) -> Self {
378        Self { callback }
379    }
380
381    #[cfg(any(native, Emscripten))]
382    fn new(callback: DropCallback) -> Self {
383        Self {
384            callback: Some(callback),
385        }
386    }
387}
388
389#[cfg(any(gles, vulkan, metal, dx12))]
390impl Drop for DropGuard {
391    fn drop(&mut self) {
392        if let Some(cb) = self.callback.take() {
393            (cb)();
394        }
395    }
396}
397
398#[cfg(any(gles, vulkan, metal, dx12))]
399impl fmt::Debug for DropGuard {
400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401        f.debug_struct("DropGuard").finish()
402    }
403}
404
405#[derive(Clone, Debug, PartialEq, Eq, Error)]
406pub enum DeviceError {
407    #[error("Out of memory")]
408    OutOfMemory,
409    #[error("Device is lost")]
410    Lost,
411    #[error("Unexpected error variant (driver implementation is at fault)")]
412    Unexpected,
413}
414
415#[cfg(any(dx12, vulkan))]
416impl From<gpu_allocator::AllocationError> for DeviceError {
417    fn from(result: gpu_allocator::AllocationError) -> Self {
418        match result {
419            gpu_allocator::AllocationError::OutOfMemory => Self::OutOfMemory,
420            gpu_allocator::AllocationError::FailedToMap(e) => {
421                log::error!("gpu-allocator: Failed to map: {e}");
422                Self::Lost
423            }
424            gpu_allocator::AllocationError::NoCompatibleMemoryTypeFound => {
425                log::error!("gpu-allocator: No Compatible Memory Type Found");
426                Self::Lost
427            }
428            gpu_allocator::AllocationError::InvalidAllocationCreateDesc => {
429                log::error!("gpu-allocator: Invalid Allocation Creation Description");
430                Self::Lost
431            }
432            gpu_allocator::AllocationError::InvalidAllocatorCreateDesc(e) => {
433                log::error!("gpu-allocator: Invalid Allocator Creation Description: {e}");
434                Self::Lost
435            }
436
437            gpu_allocator::AllocationError::Internal(e) => {
438                log::error!("gpu-allocator: Internal Error: {e}");
439                Self::Lost
440            }
441            gpu_allocator::AllocationError::BarrierLayoutNeedsDevice10
442            | gpu_allocator::AllocationError::CastableFormatsRequiresEnhancedBarriers
443            | gpu_allocator::AllocationError::CastableFormatsRequiresAtLeastDevice12 => {
444                unreachable!()
445            }
446        }
447    }
448}
449
450// A copy of gpu_allocator::AllocationSizes, allowing to read the configured value for
451// the dx12 backend, we should instead add getters to gpu_allocator::AllocationSizes
452// and remove this type.
453// https://github.com/Traverse-Research/gpu-allocator/issues/295
454#[cfg_attr(not(any(dx12, vulkan)), expect(dead_code))]
455#[derive(Clone, Copy)]
456pub(crate) struct AllocationSizes {
457    pub(crate) min_device_memblock_size: u64,
458    pub(crate) max_device_memblock_size: u64,
459    pub(crate) min_host_memblock_size: u64,
460    pub(crate) max_host_memblock_size: u64,
461}
462
463impl AllocationSizes {
464    #[allow(dead_code, reason = "may be unused on some platforms")]
465    pub(crate) fn from_memory_hints(memory_hints: &wgt::MemoryHints) -> Self {
466        // TODO: the allocator's configuration should take hardware capability into
467        // account.
468        const MB: u64 = 1024 * 1024;
469
470        match memory_hints {
471            wgt::MemoryHints::Performance => Self {
472                min_device_memblock_size: 128 * MB,
473                max_device_memblock_size: 256 * MB,
474                min_host_memblock_size: 64 * MB,
475                max_host_memblock_size: 128 * MB,
476            },
477            wgt::MemoryHints::MemoryUsage => Self {
478                min_device_memblock_size: 8 * MB,
479                max_device_memblock_size: 64 * MB,
480                min_host_memblock_size: 4 * MB,
481                max_host_memblock_size: 32 * MB,
482            },
483            wgt::MemoryHints::Manual {
484                suballocated_device_memory_block_size,
485            } => {
486                // TODO: https://github.com/gfx-rs/wgpu/issues/8625
487                // Would it be useful to expose the host size in memory hints
488                // instead of always using half of the device size?
489                let device_size = suballocated_device_memory_block_size;
490                let host_size = device_size.start / 2..device_size.end / 2;
491
492                // gpu_allocator clamps the sizes between 4MiB and 256MiB, but we clamp them ourselves since we use
493                // the sizes when detecting high memory pressure and there is no way to query the values otherwise.
494                Self {
495                    min_device_memblock_size: device_size.start.clamp(4 * MB, 256 * MB),
496                    max_device_memblock_size: device_size.end.clamp(4 * MB, 256 * MB),
497                    min_host_memblock_size: host_size.start.clamp(4 * MB, 256 * MB),
498                    max_host_memblock_size: host_size.end.clamp(4 * MB, 256 * MB),
499                }
500            }
501        }
502    }
503
504    /// Sizes for the transient pool. Minimum block sizes are reduced because
505    /// gpu-allocator never frees the last block of a memory type.
506    #[allow(dead_code, reason = "only the vulkan backend has a transient pool")]
507    pub(crate) fn transient(self) -> Self {
508        Self {
509            min_device_memblock_size: self.min_device_memblock_size / 4,
510            min_host_memblock_size: self.min_host_memblock_size / 4,
511            ..self
512        }
513    }
514}
515
516#[cfg(any(dx12, vulkan))]
517impl From<AllocationSizes> for gpu_allocator::AllocationSizes {
518    fn from(value: AllocationSizes) -> gpu_allocator::AllocationSizes {
519        gpu_allocator::AllocationSizes::new(
520            value.min_device_memblock_size,
521            value.min_host_memblock_size,
522        )
523        .with_max_device_memblock_size(value.max_device_memblock_size)
524        .with_max_host_memblock_size(value.max_host_memblock_size)
525    }
526}
527
528#[allow(dead_code, reason = "may be unused on some platforms")]
529#[cold]
530fn hal_usage_error<T: fmt::Display>(txt: T) -> ! {
531    panic!("wgpu-hal invariant was violated (usage error): {txt}")
532}
533
534#[allow(dead_code, reason = "may be unused on some platforms")]
535#[cold]
536fn hal_internal_error<T: fmt::Display>(txt: T) -> ! {
537    panic!("wgpu-hal ran into a preventable internal error: {txt}")
538}
539
540#[derive(Clone, Debug, Eq, PartialEq, Error)]
541pub enum ShaderError {
542    #[error("Compilation failed: {0:?}")]
543    Compilation(String),
544    #[error(transparent)]
545    Device(#[from] DeviceError),
546}
547
548#[derive(Clone, Debug, Eq, PartialEq, Error)]
549pub enum PipelineError {
550    #[error("Linkage failed for stage {0:?}: {1}")]
551    Linkage(wgt::ShaderStages, String),
552    #[error("Entry point for stage {0:?} is invalid")]
553    EntryPoint(naga::ShaderStage),
554    #[error(transparent)]
555    Device(#[from] DeviceError),
556    #[error("Pipeline constant error for stage {0:?}: {1}")]
557    PipelineConstants(wgt::ShaderStages, String),
558}
559
560#[derive(Clone, Debug, Eq, PartialEq, Error)]
561pub enum PipelineCacheError {
562    #[error(transparent)]
563    Device(#[from] DeviceError),
564}
565
566#[derive(Clone, Debug, Eq, PartialEq, Error)]
567pub enum SurfaceError {
568    #[error("Surface is lost")]
569    Lost,
570    #[error("Surface is outdated, needs to be re-created")]
571    Outdated,
572    #[error("Timed out waiting for a surface texture")]
573    Timeout,
574    #[error("The window is occluded (e.g. minimized or behind another window). Try again once the window is no longer occluded.")]
575    Occluded,
576    #[error(transparent)]
577    Device(#[from] DeviceError),
578    #[error("Other reason: {0}")]
579    Other(&'static str),
580}
581
582/// Error occurring while trying to create an instance, or create a surface from an instance;
583/// typically relating to the state of the underlying graphics API or hardware.
584#[derive(Clone, Debug, Error)]
585#[error("{message}")]
586pub struct InstanceError {
587    /// These errors are very platform specific, so do not attempt to encode them as an enum.
588    ///
589    /// This message should describe the problem in sufficient detail to be useful for a
590    /// user-to-developer “why won't this work on my machine” bug report, and otherwise follow
591    /// <https://rust-lang.github.io/api-guidelines/interoperability.html#error-types-are-meaningful-and-well-behaved-c-good-err>.
592    message: String,
593
594    /// Underlying error value, if any is available.
595    #[source]
596    source: Option<Arc<dyn Error + Send + Sync + 'static>>,
597}
598
599impl InstanceError {
600    #[allow(dead_code, reason = "may be unused on some platforms")]
601    pub(crate) fn new(message: String) -> Self {
602        Self {
603            message,
604            source: None,
605        }
606    }
607    #[allow(dead_code, reason = "may be unused on some platforms")]
608    pub(crate) fn with_source(message: String, source: impl Error + Send + Sync + 'static) -> Self {
609        cfg_if::cfg_if! {
610            if #[cfg(target_has_atomic = "ptr")] {
611                let source = Arc::new(source);
612            } else {
613                // TODO(https://github.com/rust-lang/rust/issues/18598): avoid indirection via Box once arbitrary types support unsized coercion
614                let source: Box<dyn Error + Send + Sync + 'static> = Box::new(source);
615                let source = Arc::from(source);
616            }
617        }
618        Self {
619            message,
620            source: Some(source),
621        }
622    }
623}
624
625/// All the types and methods that make up a implementation on top of a backend.
626///
627/// Only the types that have non-dyn trait bounds have methods on them. Most methods
628/// are either on [`CommandEncoder`] or [`Device`].
629///
630/// The api can either be used through generics (through use of this trait and associated
631/// types) or dynamically through using the `Dyn*` traits.
632pub trait Api: Clone + fmt::Debug + Sized + WasmNotSendSync + 'static {
633    const VARIANT: wgt::Backend;
634
635    type Instance: DynInstance + Instance<A = Self>;
636    type Surface: DynSurface + Surface<A = Self>;
637    type Adapter: DynAdapter + Adapter<A = Self>;
638    type Device: DynDevice + Device<A = Self>;
639
640    type Queue: DynQueue + Queue<A = Self>;
641    type CommandEncoder: DynCommandEncoder + CommandEncoder<A = Self>;
642
643    /// This API's command buffer type.
644    ///
645    /// The only thing you can do with `CommandBuffer`s is build them
646    /// with a [`CommandEncoder`] and then pass them to
647    /// [`Queue::submit`] for execution, or destroy them by passing
648    /// them to [`CommandEncoder::reset_all`].
649    ///
650    /// [`CommandEncoder`]: Api::CommandEncoder
651    type CommandBuffer: DynCommandBuffer;
652
653    type Buffer: DynBuffer;
654    type Texture: DynTexture;
655    type SurfaceTexture: DynSurfaceTexture + Borrow<Self::Texture>;
656    type TextureView: DynTextureView;
657    type Sampler: DynSampler;
658    type QuerySet: DynQuerySet;
659
660    /// A value you can block on to wait for something to finish.
661    ///
662    /// A `Fence` holds a monotonically increasing [`FenceValue`]. You can call
663    /// [`Device::wait`] to block until a fence reaches or passes a value you
664    /// choose. [`Queue::submit`] can take a `Fence` and a [`FenceValue`] to
665    /// store in it when the submitted work is complete.
666    ///
667    /// Attempting to set a fence to a value less than its current value has no
668    /// effect.
669    ///
670    /// Waiting on a fence returns as soon as the fence reaches *or passes* the
671    /// requested value. This implies that, in order to reliably determine when
672    /// an operation has completed, operations must finish in order of
673    /// increasing fence values: if a higher-valued operation were to finish
674    /// before a lower-valued operation, then waiting for the fence to reach the
675    /// lower value could return before the lower-valued operation has actually
676    /// finished.
677    ///
678    /// Fences are internally synchronised by the hal, and so should not need to be
679    /// contained in external synchronisation primitives.
680    type Fence: DynFence;
681
682    type BindGroupLayout: DynBindGroupLayout;
683    type BindGroup: DynBindGroup;
684    type PipelineLayout: DynPipelineLayout;
685    type ShaderModule: DynShaderModule;
686    type RenderPipeline: DynRenderPipeline;
687    type ComputePipeline: DynComputePipeline + ComputePipeline;
688    type RayTracingPipeline: DynRayTracingPipeline;
689    type PipelineCache: DynPipelineCache;
690
691    type AccelerationStructure: DynAccelerationStructure + 'static;
692}
693
694pub trait Instance: Sized + WasmNotSendSync {
695    type A: Api;
696
697    unsafe fn init(desc: &InstanceDescriptor<'_>) -> Result<Self, InstanceError>;
698    unsafe fn create_surface(
699        &self,
700        display_handle: raw_window_handle::RawDisplayHandle,
701        window_handle: raw_window_handle::RawWindowHandle,
702    ) -> Result<<Self::A as Api>::Surface, InstanceError>;
703    /// `surface_hint` is only used by the GLES backend targeting WebGL2
704    unsafe fn enumerate_adapters(
705        &self,
706        surface_hint: Option<&<Self::A as Api>::Surface>,
707    ) -> Vec<ExposedAdapter<Self::A>>;
708}
709
710pub trait Surface: WasmNotSendSync {
711    type A: Api;
712
713    /// Configure `self` to use `device`.
714    ///
715    /// # Safety
716    ///
717    /// - All GPU work using `self` must have been completed.
718    /// - All [`AcquiredSurfaceTexture`]s must have been destroyed.
719    /// - All [`Api::TextureView`]s derived from the [`AcquiredSurfaceTexture`]s must have been destroyed.
720    /// - The surface `self` must not currently be configured to use any other [`Device`].
721    /// - Must be externally synchronized with all other queue operations on
722    ///   `device`'s queue, including `configure` and `unconfigure` of other
723    ///   surfaces.
724    unsafe fn configure(
725        &self,
726        device: &<Self::A as Api>::Device,
727        config: &SurfaceConfiguration,
728    ) -> Result<(), SurfaceError>;
729
730    /// Unconfigure `self` on `device`.
731    ///
732    /// # Safety
733    ///
734    /// - All GPU work that uses `surface` must have been completed.
735    /// - All [`AcquiredSurfaceTexture`]s must have been destroyed.
736    /// - All [`Api::TextureView`]s derived from the [`AcquiredSurfaceTexture`]s must have been destroyed.
737    /// - The surface `self` must have been configured on `device`.
738    /// - Must be externally synchronized with all other queue operations on
739    ///   `device`'s queue, including `configure` and `unconfigure` of other
740    ///   surfaces.
741    unsafe fn unconfigure(&self, device: &<Self::A as Api>::Device);
742
743    /// Return the next texture to be presented by `self`, for the caller to draw on.
744    ///
745    /// On success, return an [`AcquiredSurfaceTexture`] representing the
746    /// texture into which the caller should draw the image to be displayed on
747    /// `self`.
748    ///
749    /// If `timeout` elapses before `self` has a texture ready to be acquired,
750    /// return `Err(SurfaceError::Timeout)`. If `timeout` is `None`, wait
751    /// indefinitely, with no timeout.
752    ///
753    /// # Using an [`AcquiredSurfaceTexture`]
754    ///
755    /// On success, this function returns an [`AcquiredSurfaceTexture`] whose
756    /// [`texture`] field is a [`SurfaceTexture`] from which the caller can
757    /// [`borrow`] a [`Texture`] to draw on. The [`AcquiredSurfaceTexture`] also
758    /// carries some metadata about that [`SurfaceTexture`].
759    ///
760    /// All calls to [`Queue::submit`] that draw on that [`Texture`] must also
761    /// include the [`SurfaceTexture`] in the `surface_textures` argument.
762    ///
763    /// When you are done drawing on the texture, you can display it on `self`
764    /// by passing the [`SurfaceTexture`] and `self` to [`Queue::present`].
765    ///
766    /// If you do not wish to display the texture, you must pass the
767    /// [`SurfaceTexture`] to [`self.discard_texture`], so that it can be reused
768    /// by future acquisitions.
769    ///
770    /// The fence is internally synchronised by the hal.
771    ///
772    /// # Portability
773    ///
774    /// Some backends can't support a timeout when acquiring a texture. On these
775    /// backends, `timeout` is ignored.
776    ///
777    /// On macOS, this returns `Err(SurfaceError::Timeout)` when the window is
778    /// not visible (minimized, fully occluded, or on another virtual desktop)
779    /// to avoid blocking in `CAMetalLayer.nextDrawable()`.
780    ///
781    /// # Safety
782    ///
783    /// - The surface `self` must currently be configured on some [`Device`].
784    ///
785    /// - The `fence` argument must be the same [`Fence`] passed to all calls to
786    ///   [`Queue::submit`] that used [`Texture`]s acquired from this surface.
787    ///
788    /// - You may only have one texture acquired from `self` at a time. When
789    ///   `acquire_texture` returns `Ok(ast)`, you must pass the returned
790    ///   [`SurfaceTexture`] `ast.texture` to either [`Queue::present`] or
791    ///   [`Surface::discard_texture`] before calling `acquire_texture` again.
792    ///
793    /// [`texture`]: AcquiredSurfaceTexture::texture
794    /// [`SurfaceTexture`]: Api::SurfaceTexture
795    /// [`borrow`]: alloc::borrow::Borrow::borrow
796    /// [`Texture`]: Api::Texture
797    /// [`Fence`]: Api::Fence
798    /// [`self.discard_texture`]: Surface::discard_texture
799    unsafe fn acquire_texture(
800        &self,
801        timeout: Option<core::time::Duration>,
802        fence: &<Self::A as Api>::Fence,
803    ) -> Result<AcquiredSurfaceTexture<Self::A>, SurfaceError>;
804
805    /// Relinquish an acquired texture without presenting it.
806    ///
807    /// After this call, the texture underlying [`SurfaceTexture`] may be
808    /// returned by subsequent calls to [`self.acquire_texture`].
809    ///
810    /// # Safety
811    ///
812    /// - The surface `self` must currently be configured on some [`Device`].
813    ///
814    /// - `texture` must be a [`SurfaceTexture`] returned by a call to
815    ///   [`self.acquire_texture`] that has not yet been passed to
816    ///   [`Queue::present`].
817    ///
818    /// [`SurfaceTexture`]: Api::SurfaceTexture
819    /// [`self.acquire_texture`]: Surface::acquire_texture
820    unsafe fn discard_texture(&self, texture: <Self::A as Api>::SurfaceTexture);
821}
822
823pub trait Adapter: WasmNotSendSync {
824    type A: Api;
825
826    unsafe fn open(
827        &self,
828        features: wgt::Features,
829        limits: &wgt::Limits,
830        memory_hints: &wgt::MemoryHints,
831    ) -> Result<OpenDevice<Self::A>, DeviceError>;
832
833    /// Return the set of supported capabilities for a texture format.
834    unsafe fn texture_format_capabilities(
835        &self,
836        format: wgt::TextureFormat,
837    ) -> TextureFormatCapabilities;
838
839    /// Returns the capabilities of working with a specified surface.
840    ///
841    /// `None` means presentation is not supported for it.
842    unsafe fn surface_capabilities(
843        &self,
844        surface: &<Self::A as Api>::Surface,
845    ) -> Option<SurfaceCapabilities>;
846
847    /// Returns the HDR / luminance characteristics of the display backing
848    /// `surface`, queried from the OS on each call.
849    ///
850    /// `None` means no information is available; wgpu-core maps it to
851    /// [`wgt::DisplayHdrInfo::default`]. Implementors must not panic; degrade any
852    /// OS-query failure to `None`. The default implementation returns `None`.
853    ///
854    /// Implemented by Metal (macOS only, and only from the main thread), DX12, and
855    /// Vulkan (Win32 `HWND` surfaces only); GLES and noop keep the default `None`.
856    unsafe fn surface_display_hdr_info(
857        &self,
858        surface: &<Self::A as Api>::Surface,
859    ) -> Option<wgt::DisplayHdrInfo> {
860        let _ = surface;
861        None
862    }
863
864    /// Creates a [`PresentationTimestamp`] using the adapter's WSI.
865    ///
866    /// [`PresentationTimestamp`]: wgt::PresentationTimestamp
867    unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp;
868
869    /// The combination of all usages that the are guaranteed to be be ordered by the hardware.
870    /// If a usage is ordered, then if the buffer state doesn't change between draw calls,
871    /// there are no barriers needed for synchronization.
872    fn get_ordered_buffer_usages(&self) -> wgt::BufferUses;
873
874    /// The combination of all usages that the are guaranteed to be be ordered by the hardware.
875    /// If a usage is ordered, then if the buffer state doesn't change between draw calls,
876    /// there are no barriers needed for synchronization.
877    fn get_ordered_texture_usages(&self) -> wgt::TextureUses;
878}
879
880/// A connection to a GPU and a pool of resources to use with it.
881///
882/// A `wgpu-hal` `Device` represents an open connection to a specific graphics
883/// processor, controlled via the backend [`Device::A`]. A `Device` is mostly
884/// used for creating resources. Each `Device` has an associated [`Queue`] used
885/// for command submission.
886///
887/// On Vulkan a `Device` corresponds to a logical device ([`VkDevice`]). Other
888/// backends don't have an exact analog: for example, [`ID3D12Device`]s and
889/// [`MTLDevice`]s are owned by the backends' [`wgpu_hal::Adapter`]
890/// implementations, and shared by all [`wgpu_hal::Device`]s created from that
891/// `Adapter`.
892///
893/// A `Device`'s life cycle is generally:
894///
895/// 1)  Obtain a `Device` and its associated [`Queue`] by calling
896///     [`Adapter::open`].
897///
898///     Alternatively, the backend-specific types that implement [`Adapter`] often
899///     have methods for creating a `wgpu-hal` `Device` from a platform-specific
900///     handle. For example, [`vulkan::Adapter::device_from_raw`] can create a
901///     [`vulkan::Device`] from an [`ash::Device`].
902///
903/// 1)  Create resources to use on the device by calling methods like
904///     [`Device::create_texture`] or [`Device::create_shader_module`].
905///
906/// 1)  Call [`Device::create_command_encoder`] to obtain a [`CommandEncoder`],
907///     which you can use to build [`CommandBuffer`]s holding commands to be
908///     executed on the GPU.
909///
910/// 1)  Call [`Queue::submit`] on the `Device`'s associated [`Queue`] to submit
911///     [`CommandBuffer`]s for execution on the GPU. If needed, call
912///     [`Device::wait`] to wait for them to finish execution.
913///
914/// 1)  Free resources with methods like [`Device::destroy_texture`] or
915///     [`Device::destroy_shader_module`].
916///
917/// 1)  Drop the device.
918///
919/// [`vkDevice`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkDevice
920/// [`ID3D12Device`]: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12device
921/// [`MTLDevice`]: https://developer.apple.com/documentation/metal/mtldevice
922/// [`wgpu_hal::Adapter`]: Adapter
923/// [`wgpu_hal::Device`]: Device
924/// [`vulkan::Adapter::device_from_raw`]: vulkan/struct.Adapter.html#method.device_from_raw
925/// [`vulkan::Device`]: vulkan/struct.Device.html
926/// [`ash::Device`]: https://docs.rs/ash/latest/ash/struct.Device.html
927/// [`CommandBuffer`]: Api::CommandBuffer
928///
929/// # Safety
930///
931/// As with other `wgpu-hal` APIs, [validation] is the caller's
932/// responsibility. Here are the general requirements for all `Device`
933/// methods:
934///
935/// - Any resource passed to a `Device` method must have been created by that
936///   `Device`. For example, a [`Texture`] passed to [`Device::destroy_texture`] must
937///   have been created with the `Device` passed as `self`.
938///
939/// - Resources may not be destroyed if they are used by any submitted command
940///   buffers that have not yet finished execution.
941///
942/// [validation]: index.html#validation-is-the-calling-codes-responsibility-not-wgpu-hals
943/// [`Texture`]: Api::Texture
944pub trait Device: WasmNotSendSync {
945    type A: Api;
946
947    /// Creates a new buffer.
948    ///
949    /// The initial usage is `wgt::BufferUses::empty()`.
950    ///
951    /// `wgpu_hal` may adjust the size in `desc` to a larger value if required
952    /// by the platform. On success, it returns a tuple of the buffer itself
953    /// and its actual allocated size. `wgpu-core` is responsible for
954    /// initializing any portion of the buffer that may be accessed, including
955    /// any padding added by `create_buffer`.
956    ///
957    /// Platform-dependent padding is currently required for uniform buffers on
958    /// dx12. Support for zero-size vertex and index bindings is also platform
959    /// dependent, but presently, `wgpu-core` adds padding to the end of all
960    /// buffers with vertex or index usage, and redirects all zero-size bindings
961    /// to that padding region, regardless of platform.
962    unsafe fn create_buffer(
963        &self,
964        desc: &BufferDescriptor,
965    ) -> Result<(<Self::A as Api>::Buffer, wgt::BufferAddress), DeviceError>;
966
967    /// Free `buffer` and any GPU resources it owns.
968    ///
969    /// Note that backends are allowed to allocate GPU memory for buffers from
970    /// allocation pools, and this call is permitted to simply return `buffer`'s
971    /// storage to that pool, without making it available to other applications.
972    ///
973    /// # Safety
974    ///
975    /// - The given `buffer` must not currently be mapped.
976    unsafe fn destroy_buffer(&self, buffer: <Self::A as Api>::Buffer);
977
978    /// A hook for when a wgpu-core buffer is created from a raw wgpu-hal buffer.
979    unsafe fn add_raw_buffer(&self, buffer: &<Self::A as Api>::Buffer);
980
981    /// Return a pointer to CPU memory mapping the contents of `buffer`.
982    ///
983    /// Buffer mappings are persistent: the buffer may remain mapped on the CPU
984    /// while the GPU reads or writes to it. (Note that `wgpu_core` does not use
985    /// this feature: when a `wgpu_core::Buffer` is unmapped, the underlying
986    /// `wgpu_hal` buffer is also unmapped.)
987    ///
988    /// If this function returns `Ok(mapping)`, then:
989    ///
990    /// - `mapping.ptr` is the CPU address of the start of the mapped memory.
991    ///
992    /// - If `mapping.is_coherent` is `true`, then CPU writes to the mapped
993    ///   memory are immediately visible on the GPU, and vice versa.
994    ///
995    /// # Safety
996    ///
997    /// - The given `buffer` must have been created with the [`MAP_READ`] or
998    ///   [`MAP_WRITE`] flags set in [`BufferDescriptor::usage`].
999    ///
1000    /// - The given `range` must fall within the size of `buffer`.
1001    ///
1002    /// - The caller must avoid data races between the CPU and the GPU. A data
1003    ///   race is any pair of accesses to a particular byte, one of which is a
1004    ///   write, that are not ordered with respect to each other by some sort of
1005    ///   synchronization operation.
1006    ///
1007    /// - If this function returns `Ok(mapping)` and `mapping.is_coherent` is
1008    ///   `false`, then:
1009    ///
1010    ///   - Every CPU write to a mapped byte followed by a GPU read of that byte
1011    ///     must have at least one call to [`Device::flush_mapped_ranges`]
1012    ///     covering that byte that occurs between those two accesses.
1013    ///
1014    ///   - Every GPU write to a mapped byte followed by a CPU read of that byte
1015    ///     must have at least one call to [`Device::invalidate_mapped_ranges`]
1016    ///     covering that byte that occurs between those two accesses.
1017    ///
1018    ///   Note that the data race rule above requires that all such access pairs
1019    ///   be ordered, so it is meaningful to talk about what must occur
1020    ///   "between" them.
1021    ///
1022    /// - Zero-sized mappings are not allowed.
1023    ///
1024    /// - The returned [`BufferMapping::ptr`] must not be used after a call to
1025    ///   [`Device::unmap_buffer`].
1026    ///
1027    /// [`MAP_READ`]: wgt::BufferUses::MAP_READ
1028    /// [`MAP_WRITE`]: wgt::BufferUses::MAP_WRITE
1029    unsafe fn map_buffer(
1030        &self,
1031        buffer: &<Self::A as Api>::Buffer,
1032        range: MemoryRange,
1033    ) -> Result<BufferMapping, DeviceError>;
1034
1035    /// Remove the mapping established by the last call to [`Device::map_buffer`].
1036    ///
1037    /// # Safety
1038    ///
1039    /// - The given `buffer` must be currently mapped.
1040    unsafe fn unmap_buffer(&self, buffer: &<Self::A as Api>::Buffer);
1041
1042    /// Indicate that CPU writes to mapped buffer memory should be made visible to the GPU.
1043    ///
1044    /// # Safety
1045    ///
1046    /// - The given `buffer` must be currently mapped.
1047    ///
1048    /// - All ranges produced by `ranges` must fall within `buffer`'s size.
1049    unsafe fn flush_mapped_ranges<I>(&self, buffer: &<Self::A as Api>::Buffer, ranges: I)
1050    where
1051        I: Iterator<Item = MemoryRange>;
1052
1053    /// Indicate that GPU writes to mapped buffer memory should be made visible to the CPU.
1054    ///
1055    /// # Safety
1056    ///
1057    /// - The given `buffer` must be currently mapped.
1058    ///
1059    /// - All ranges produced by `ranges` must fall within `buffer`'s size.
1060    unsafe fn invalidate_mapped_ranges<I>(&self, buffer: &<Self::A as Api>::Buffer, ranges: I)
1061    where
1062        I: Iterator<Item = MemoryRange>;
1063
1064    /// Creates a new texture.
1065    ///
1066    /// The initial usage for all subresources is `wgt::TextureUses::UNINITIALIZED`.
1067    unsafe fn create_texture(
1068        &self,
1069        desc: &TextureDescriptor,
1070    ) -> Result<<Self::A as Api>::Texture, DeviceError>;
1071    unsafe fn destroy_texture(&self, texture: <Self::A as Api>::Texture);
1072
1073    /// A hook for when a wgpu-core texture is created from a raw wgpu-hal texture.
1074    unsafe fn add_raw_texture(&self, texture: &<Self::A as Api>::Texture);
1075
1076    unsafe fn create_texture_view(
1077        &self,
1078        texture: &<Self::A as Api>::Texture,
1079        desc: &TextureViewDescriptor,
1080    ) -> Result<<Self::A as Api>::TextureView, DeviceError>;
1081    unsafe fn destroy_texture_view(&self, view: <Self::A as Api>::TextureView);
1082    unsafe fn create_sampler(
1083        &self,
1084        desc: &SamplerDescriptor,
1085    ) -> Result<<Self::A as Api>::Sampler, DeviceError>;
1086    unsafe fn destroy_sampler(&self, sampler: <Self::A as Api>::Sampler);
1087
1088    /// Create a fresh [`CommandEncoder`].
1089    ///
1090    /// The new `CommandEncoder` is in the "closed" state.
1091    unsafe fn create_command_encoder(
1092        &self,
1093        desc: &CommandEncoderDescriptor<<Self::A as Api>::Queue>,
1094    ) -> Result<<Self::A as Api>::CommandEncoder, DeviceError>;
1095
1096    /// Creates a bind group layout.
1097    unsafe fn create_bind_group_layout(
1098        &self,
1099        desc: &BindGroupLayoutDescriptor,
1100    ) -> Result<<Self::A as Api>::BindGroupLayout, DeviceError>;
1101    unsafe fn destroy_bind_group_layout(&self, bg_layout: <Self::A as Api>::BindGroupLayout);
1102    unsafe fn create_pipeline_layout(
1103        &self,
1104        desc: &PipelineLayoutDescriptor<<Self::A as Api>::BindGroupLayout>,
1105    ) -> Result<<Self::A as Api>::PipelineLayout, DeviceError>;
1106    unsafe fn destroy_pipeline_layout(&self, pipeline_layout: <Self::A as Api>::PipelineLayout);
1107
1108    #[allow(clippy::type_complexity)]
1109    unsafe fn create_bind_group(
1110        &self,
1111        desc: &BindGroupDescriptor<
1112            <Self::A as Api>::BindGroupLayout,
1113            <Self::A as Api>::Buffer,
1114            <Self::A as Api>::Sampler,
1115            <Self::A as Api>::TextureView,
1116            <Self::A as Api>::AccelerationStructure,
1117        >,
1118    ) -> Result<<Self::A as Api>::BindGroup, DeviceError>;
1119    unsafe fn destroy_bind_group(&self, group: <Self::A as Api>::BindGroup);
1120
1121    unsafe fn create_shader_module(
1122        &self,
1123        desc: &ShaderModuleDescriptor,
1124        shader: ShaderInput,
1125    ) -> Result<<Self::A as Api>::ShaderModule, ShaderError>;
1126    unsafe fn destroy_shader_module(&self, module: <Self::A as Api>::ShaderModule);
1127
1128    /// Create a render pipeline according to `desc`.
1129    ///
1130    /// The returned pipeline's lifetime is independent of that of
1131    /// `desc.layout`, `desc.cache`, and all the shader modules in any
1132    /// [`ProgrammableStage`] values in `desc`. The pipeline is safe to use even
1133    /// after those resources have been destroyed.
1134    #[allow(clippy::type_complexity)]
1135    unsafe fn create_render_pipeline(
1136        &self,
1137        desc: &RenderPipelineDescriptor<
1138            <Self::A as Api>::PipelineLayout,
1139            <Self::A as Api>::ShaderModule,
1140            <Self::A as Api>::PipelineCache,
1141        >,
1142    ) -> Result<<Self::A as Api>::RenderPipeline, PipelineError>;
1143    unsafe fn destroy_render_pipeline(&self, pipeline: <Self::A as Api>::RenderPipeline);
1144
1145    /// Create a compute pipeline according to `desc`.
1146    ///
1147    /// The returned pipeline's lifetime is independent of that of
1148    /// `desc.layout`, `desc.stage.module`, and `desc.cache`. The pipeline is
1149    /// safe to use even after those resources have been destroyed.
1150    #[allow(clippy::type_complexity)]
1151    unsafe fn create_compute_pipeline(
1152        &self,
1153        desc: &ComputePipelineDescriptor<
1154            <Self::A as Api>::PipelineLayout,
1155            <Self::A as Api>::ShaderModule,
1156            <Self::A as Api>::PipelineCache,
1157        >,
1158    ) -> Result<<Self::A as Api>::ComputePipeline, PipelineError>;
1159    unsafe fn destroy_compute_pipeline(&self, pipeline: <Self::A as Api>::ComputePipeline);
1160
1161    /// Create a ray tracing pipeline according to `desc`.
1162    ///
1163    /// The returned pipeline's lifetime is independent of that of
1164    /// `desc.layout`, `desc.cache`, and all the shader modules in any
1165    /// [`ProgrammableStage`] values in `desc`. The pipeline is safe to use even
1166    /// after those resources have been destroyed.
1167    #[allow(clippy::type_complexity)]
1168    unsafe fn create_ray_tracing_pipeline(
1169        &self,
1170        desc: &RayTracingPipelineDescriptor<
1171            <Self::A as Api>::PipelineLayout,
1172            <Self::A as Api>::ShaderModule,
1173            <Self::A as Api>::PipelineCache,
1174        >,
1175    ) -> Result<<Self::A as Api>::RayTracingPipeline, PipelineError>;
1176    unsafe fn destroy_ray_tracing_pipeline(&self, pipeline: <Self::A as Api>::RayTracingPipeline);
1177    /// Obtain the opaque data from each group, behaves as if group 0 is the ray generation, group 1
1178    /// is the miss shader, and group 2.. are the intersection groups.
1179    unsafe fn get_raytracing_pipeline_group_data(
1180        &self,
1181        pipeline: &<Self::A as Api>::RayTracingPipeline,
1182        groups: Range<u32>,
1183    ) -> Result<Vec<u8>, DeviceError>;
1184
1185    unsafe fn create_pipeline_cache(
1186        &self,
1187        desc: &PipelineCacheDescriptor<'_>,
1188    ) -> Result<<Self::A as Api>::PipelineCache, PipelineCacheError>;
1189    fn pipeline_cache_validation_key(&self) -> Option<[u8; 16]> {
1190        None
1191    }
1192    unsafe fn destroy_pipeline_cache(&self, cache: <Self::A as Api>::PipelineCache);
1193
1194    unsafe fn create_query_set(
1195        &self,
1196        desc: &wgt::QuerySetDescriptor<Label>,
1197    ) -> Result<<Self::A as Api>::QuerySet, DeviceError>;
1198    unsafe fn destroy_query_set(&self, set: <Self::A as Api>::QuerySet);
1199    unsafe fn create_fence(&self) -> Result<<Self::A as Api>::Fence, DeviceError>;
1200    unsafe fn destroy_fence(&self, fence: <Self::A as Api>::Fence);
1201    unsafe fn get_fence_value(
1202        &self,
1203        fence: &<Self::A as Api>::Fence,
1204    ) -> Result<FenceValue, DeviceError>;
1205
1206    /// Wait for `fence` to reach `value`.
1207    ///
1208    /// Operations like [`Queue::submit`] can accept a [`Fence`] and a
1209    /// [`FenceValue`] to store in it, so you can use this `wait` function
1210    /// to wait for a given queue submission to finish execution.
1211    ///
1212    /// The `value` argument must not exceed the highest value that an actual
1213    /// operation you have already presented to the device is going to store in
1214    /// `fence`. You cannot wait for values yet to be submitted. (This
1215    /// restriction accommodates implementations like the `vulkan` backend's
1216    /// [`FencePool`] that must allocate a distinct synchronization object for
1217    /// each fence value one is able to wait for.)
1218    ///
1219    /// Calling `wait` with a lower [`FenceValue`] than `fence`'s current value
1220    /// returns immediately.
1221    ///
1222    /// If `timeout` is not provided, the function will block indefinitely or until
1223    /// an error is encountered.
1224    ///
1225    /// Returns `Ok(true)` on success and `Ok(false)` on timeout.
1226    ///
1227    /// [`Fence`]: Api::Fence
1228    /// [`FencePool`]: vulkan/enum.Fence.html#variant.FencePool
1229    unsafe fn wait(
1230        &self,
1231        fence: &<Self::A as Api>::Fence,
1232        value: FenceValue,
1233        timeout: Option<core::time::Duration>,
1234    ) -> Result<bool, DeviceError>;
1235
1236    /// Start a graphics debugger capture.
1237    ///
1238    /// # Safety
1239    ///
1240    /// See [`wgpu::Device::start_graphics_debugger_capture`][api] for more details.
1241    ///
1242    /// [api]: ../wgpu/struct.Device.html#method.start_graphics_debugger_capture
1243    unsafe fn start_graphics_debugger_capture(&self) -> bool;
1244
1245    /// Stop a graphics debugger capture.
1246    ///
1247    /// # Safety
1248    ///
1249    /// See [`wgpu::Device::stop_graphics_debugger_capture`][api] for more details.
1250    ///
1251    /// [api]: ../wgpu/struct.Device.html#method.stop_graphics_debugger_capture
1252    unsafe fn stop_graphics_debugger_capture(&self);
1253
1254    #[allow(unused_variables)]
1255    unsafe fn pipeline_cache_get_data(
1256        &self,
1257        cache: &<Self::A as Api>::PipelineCache,
1258    ) -> Option<Vec<u8>> {
1259        None
1260    }
1261
1262    unsafe fn create_acceleration_structure(
1263        &self,
1264        desc: &AccelerationStructureDescriptor,
1265    ) -> Result<<Self::A as Api>::AccelerationStructure, DeviceError>;
1266    unsafe fn get_acceleration_structure_build_sizes(
1267        &self,
1268        desc: &GetAccelerationStructureBuildSizesDescriptor<<Self::A as Api>::Buffer>,
1269    ) -> AccelerationStructureBuildSizes;
1270    unsafe fn get_acceleration_structure_device_address(
1271        &self,
1272        acceleration_structure: &<Self::A as Api>::AccelerationStructure,
1273    ) -> wgt::BufferAddress;
1274    unsafe fn destroy_acceleration_structure(
1275        &self,
1276        acceleration_structure: <Self::A as Api>::AccelerationStructure,
1277    );
1278    /// Converts the `TlasInstance` into a implementation defined format, appending it to
1279    /// `to_extend`. The vector must be have a length exactly the old length plus
1280    /// `Alignments::raw_tlas_instance_size`
1281    fn tlas_instance_to_bytes(&self, instance: TlasInstance, to_extend: &mut Vec<u8>);
1282
1283    fn get_internal_counters(&self) -> wgt::HalCounters;
1284
1285    fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
1286        None
1287    }
1288
1289    fn check_if_oom(&self) -> Result<(), DeviceError>;
1290}
1291
1292pub trait Queue: WasmNotSendSync {
1293    type A: Api;
1294
1295    /// Submit `command_buffers` for execution on GPU.
1296    ///
1297    /// Update `fence` to `value` when the operation is complete. See
1298    /// [`Fence`] for details.
1299    ///
1300    /// All command buffers submitted to a `wgpu_hal` queue are executed in the
1301    /// order they're submitted, with each buffer able to observe the effects of
1302    /// previous buffers' execution. Specifically:
1303    ///
1304    /// - If two calls to `submit` on a single `Queue` occur in a particular
1305    ///   order (that is, they happen on the same thread, or on two threads that
1306    ///   have synchronized to establish an ordering), then the first
1307    ///   submission's commands all complete execution before any of the second
1308    ///   submission's commands begin. All results produced by one submission
1309    ///   are visible to the next.
1310    ///
1311    /// - Within a submission, command buffers execute in the order in which they
1312    ///   appear in `command_buffers`. All results produced by one buffer are
1313    ///   visible to the next.
1314    ///
1315    /// If two calls to `submit` on a single `Queue` from different threads are
1316    /// not synchronized to occur in a particular order, they must pass distinct
1317    /// [`Fence`]s. As explained in the [`Fence`] documentation, waiting for
1318    /// operations to complete is only trustworthy when operations finish in
1319    /// order of increasing fence value, but submissions from different threads
1320    /// cannot determine how to order the fence values if the submissions
1321    /// themselves are unordered. If each thread uses a separate [`Fence`], this
1322    /// problem does not arise.
1323    ///
1324    /// # Safety
1325    ///
1326    /// - Each [`CommandBuffer`][cb] in `command_buffers` must have been created
1327    ///   from a [`CommandEncoder`][ce] that was constructed from the
1328    ///   [`Device`][d] associated with this [`Queue`].
1329    ///
1330    /// - Each [`CommandBuffer`][cb] must remain alive until the submitted
1331    ///   commands have finished execution. Since command buffers must not
1332    ///   outlive their encoders, this implies that the encoders must remain
1333    ///   alive as well.
1334    ///
1335    /// - All resources used by a submitted [`CommandBuffer`][cb]
1336    ///   ([`Texture`][t]s, [`BindGroup`][bg]s, [`RenderPipeline`][rp]s, and so
1337    ///   on) must remain alive until the command buffer finishes execution.
1338    ///
1339    /// - Every [`SurfaceTexture`][st] that any command in `command_buffers`
1340    ///   writes to must appear in the `surface_textures` argument.
1341    ///
1342    /// - No [`SurfaceTexture`][st] may appear in the `surface_textures`
1343    ///   argument more than once.
1344    ///
1345    /// - Each [`SurfaceTexture`][st] in `surface_textures` must be configured
1346    ///   for use with the [`Device`][d] associated with this [`Queue`],
1347    ///   typically by calling [`Surface::configure`].
1348    ///
1349    /// - All calls to this function that include a given [`SurfaceTexture`][st]
1350    ///   in `surface_textures` must use the same [`Fence`].
1351    ///
1352    /// - The [`Fence`] passed as `signal_fence.0` must remain alive until
1353    ///   all submissions that will signal it have completed.
1354    ///
1355    /// [`Fence`]: Api::Fence
1356    /// [cb]: Api::CommandBuffer
1357    /// [ce]: Api::CommandEncoder
1358    /// [d]: Api::Device
1359    /// [t]: Api::Texture
1360    /// [bg]: Api::BindGroup
1361    /// [rp]: Api::RenderPipeline
1362    /// [st]: Api::SurfaceTexture
1363    unsafe fn submit(
1364        &self,
1365        command_buffers: &[&<Self::A as Api>::CommandBuffer],
1366        surface_textures: &[&<Self::A as Api>::SurfaceTexture],
1367        signal_fence: (&<Self::A as Api>::Fence, FenceValue),
1368    ) -> Result<(), DeviceError>;
1369    /// Present a surface texture to the screen.
1370    ///
1371    /// This consumes the surface texture, returning it to the swapchain.
1372    ///
1373    /// `damage_rects` are the regions that changed since the last present, as a
1374    /// hint for backends that support incremental presentation. An empty slice
1375    /// means the whole surface changed.
1376    ///
1377    /// # Safety
1378    ///
1379    /// - `texture` must have been acquired from `surface` via
1380    ///   [`Surface::acquire_texture`] and not yet presented or discarded.
1381    /// - `surface` must be configured for use with the [`Device`][d] associated
1382    ///   with this [`Queue`].
1383    /// - `texture` must be in the "present" state. Either:
1384    ///   - It was passed in [`submit`][s]'s `surface_textures` argument
1385    ///     (which transitions it to the present state), or
1386    ///   - The caller has otherwise transitioned it (e.g. via a clear +
1387    ///     barrier to `PRESENT` for textures that were never rendered to).
1388    /// - Any command buffers that write to `texture` must have been submitted
1389    ///   via [`submit`][s] before this call. The submissions do not need to
1390    ///   have completed on the GPU; platform-level synchronization handles the
1391    ///   ordering between rendering and display.
1392    /// - Must be externally synchronized with all other queue operations
1393    ///   ([`submit`][s], [`present`][Queue::present],
1394    ///   [`wait_for_idle`][Queue::wait_for_idle]) on the same queue, and with
1395    ///   [`Surface::configure`] and [`Surface::unconfigure`] on its device.
1396    /// - Every rect in `damage_rects` must be non-empty and lie within the
1397    ///   surface's configured extent.
1398    ///
1399    /// [d]: Api::Device
1400    /// [s]: Queue::submit
1401    unsafe fn present(
1402        &self,
1403        surface: &<Self::A as Api>::Surface,
1404        texture: <Self::A as Api>::SurfaceTexture,
1405        damage_rects: &[wgt::Rect<u32>],
1406    ) -> Result<(), SurfaceError>;
1407    /// Block until all previously submitted work on this queue has completed,
1408    /// including any pending presentations.
1409    ///
1410    /// # Safety
1411    ///
1412    /// - Must be externally synchronized with all other queue operations
1413    ///   ([`submit`][Queue::submit], [`present`][Queue::present],
1414    ///   [`wait_for_idle`][Queue::wait_for_idle]) on the same queue, and with
1415    ///   [`Surface::configure`] and [`Surface::unconfigure`] on its device.
1416    unsafe fn wait_for_idle(&self) -> Result<(), DeviceError>;
1417    unsafe fn get_timestamp_period(&self) -> f32;
1418}
1419
1420pub trait ComputePipeline {
1421    /// Returns the subgroup size this pipeline executes with, or `None` if the backend cannot determine it.
1422    fn get_subgroup_size(&self) -> Option<u32>;
1423}
1424
1425/// Encoder and allocation pool for `CommandBuffer`s.
1426///
1427/// A `CommandEncoder` not only constructs `CommandBuffer`s but also
1428/// acts as the allocation pool that owns the buffers' underlying
1429/// storage. Thus, `CommandBuffer`s must not outlive the
1430/// `CommandEncoder` that created them.
1431///
1432/// The life cycle of a `CommandBuffer` is as follows:
1433///
1434/// - Call [`Device::create_command_encoder`] to create a new
1435///   `CommandEncoder`, in the "closed" state.
1436///
1437/// - Call `begin_encoding` on a closed `CommandEncoder` to begin
1438///   recording commands. This puts the `CommandEncoder` in the
1439///   "recording" state.
1440///
1441/// - Call methods like `copy_buffer_to_buffer`, `begin_render_pass`,
1442///   etc. on a "recording" `CommandEncoder` to add commands to the
1443///   list. (If an error occurs, you must call `discard_encoding`; see
1444///   below.)
1445///
1446/// - Call `end_encoding` on a recording `CommandEncoder` to close the
1447///   encoder and construct a fresh `CommandBuffer` consisting of the
1448///   list of commands recorded up to that point.
1449///
1450/// - Call `discard_encoding` on a recording `CommandEncoder` to drop
1451///   the commands recorded thus far and close the encoder. This is
1452///   the only safe thing to do on a `CommandEncoder` if an error has
1453///   occurred while recording commands.
1454///
1455/// - Call `reset_all` on a closed `CommandEncoder`, passing all the
1456///   live `CommandBuffers` built from it. All the `CommandBuffer`s
1457///   are destroyed, and their resources are freed.
1458///
1459/// # Safety
1460///
1461/// - The `CommandEncoder` must be in the states described above to
1462///   make the given calls.
1463///
1464/// - A `CommandBuffer` that has been submitted for execution on the
1465///   GPU must live until its execution is complete.
1466///
1467/// - A `CommandBuffer` must not outlive the `CommandEncoder` that
1468///   built it.
1469///
1470/// It is the user's responsibility to meet this requirements. This
1471/// allows `CommandEncoder` implementations to keep their state
1472/// tracking to a minimum.
1473pub trait CommandEncoder: WasmNotSendSync + fmt::Debug {
1474    type A: Api;
1475
1476    /// Begin encoding a new command buffer.
1477    ///
1478    /// This puts this `CommandEncoder` in the "recording" state.
1479    ///
1480    /// # Safety
1481    ///
1482    /// This `CommandEncoder` must be in the "closed" state.
1483    unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError>;
1484
1485    /// Discard the command list under construction.
1486    ///
1487    /// If an error has occurred while recording commands, this
1488    /// is the only safe thing to do with the encoder.
1489    ///
1490    /// This puts this `CommandEncoder` in the "closed" state.
1491    ///
1492    /// # Safety
1493    ///
1494    /// This `CommandEncoder` must be in the "recording" state.
1495    ///
1496    /// Callers must not assume that implementations of this
1497    /// function are idempotent, and thus should not call it
1498    /// multiple times in a row.
1499    unsafe fn discard_encoding(&mut self);
1500
1501    /// Return a fresh [`CommandBuffer`] holding the recorded commands.
1502    ///
1503    /// The returned [`CommandBuffer`] holds all the commands recorded
1504    /// on this `CommandEncoder` since the last call to
1505    /// [`begin_encoding`].
1506    ///
1507    /// This puts this `CommandEncoder` in the "closed" state.
1508    ///
1509    /// # Safety
1510    ///
1511    /// This `CommandEncoder` must be in the "recording" state.
1512    ///
1513    /// The returned [`CommandBuffer`] must not outlive this
1514    /// `CommandEncoder`. Implementations are allowed to build
1515    /// `CommandBuffer`s that depend on storage owned by this
1516    /// `CommandEncoder`.
1517    ///
1518    /// [`CommandBuffer`]: Api::CommandBuffer
1519    /// [`begin_encoding`]: CommandEncoder::begin_encoding
1520    unsafe fn end_encoding(&mut self) -> Result<<Self::A as Api>::CommandBuffer, DeviceError>;
1521
1522    /// Reclaim all resources belonging to this `CommandEncoder`.
1523    ///
1524    /// # Safety
1525    ///
1526    /// This `CommandEncoder` must be in the "closed" state.
1527    ///
1528    /// The `command_buffers` iterator must produce all the live
1529    /// [`CommandBuffer`]s built using this `CommandEncoder` --- that
1530    /// is, every extant `CommandBuffer` returned from `end_encoding`.
1531    ///
1532    /// [`CommandBuffer`]: Api::CommandBuffer
1533    unsafe fn reset_all<I>(&mut self, command_buffers: I)
1534    where
1535        I: Iterator<Item = <Self::A as Api>::CommandBuffer>;
1536
1537    unsafe fn transition_buffers<'a, T>(&mut self, barriers: T)
1538    where
1539        T: Iterator<Item = BufferBarrier<'a, <Self::A as Api>::Buffer>>;
1540
1541    unsafe fn transition_textures<'a, T>(&mut self, barriers: T)
1542    where
1543        T: Iterator<Item = TextureBarrier<'a, <Self::A as Api>::Texture>>;
1544
1545    // copy operations
1546
1547    unsafe fn clear_buffer(&mut self, buffer: &<Self::A as Api>::Buffer, range: MemoryRange);
1548
1549    unsafe fn copy_buffer_to_buffer<T>(
1550        &mut self,
1551        src: &<Self::A as Api>::Buffer,
1552        dst: &<Self::A as Api>::Buffer,
1553        regions: T,
1554    ) where
1555        T: Iterator<Item = BufferCopy>;
1556
1557    /// Copy from an external image to an internal texture.
1558    /// Works with a single array layer.
1559    /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`.
1560    /// Note: the copy extent is in physical size (rounded to the block size)
1561    #[cfg(webgl)]
1562    unsafe fn copy_external_image_to_texture<T>(
1563        &mut self,
1564        src: &wgt::CopyExternalImageSourceInfo,
1565        dst: &<Self::A as Api>::Texture,
1566        dst_premultiplication: bool,
1567        regions: T,
1568    ) where
1569        T: Iterator<Item = TextureCopy>;
1570
1571    /// Copy from one texture to another.
1572    /// Works with a single array layer.
1573    /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`.
1574    /// Note: the copy extent is in physical size (rounded to the block size)
1575    unsafe fn copy_texture_to_texture<T>(
1576        &mut self,
1577        src: &<Self::A as Api>::Texture,
1578        src_usage: wgt::TextureUses,
1579        dst: &<Self::A as Api>::Texture,
1580        regions: T,
1581    ) where
1582        T: Iterator<Item = TextureCopy>;
1583
1584    /// Copy from buffer to texture.
1585    /// Works with a single array layer.
1586    /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`.
1587    /// Note: the copy extent is in physical size (rounded to the block size)
1588    unsafe fn copy_buffer_to_texture<T>(
1589        &mut self,
1590        src: &<Self::A as Api>::Buffer,
1591        dst: &<Self::A as Api>::Texture,
1592        regions: T,
1593    ) where
1594        T: Iterator<Item = BufferTextureCopy>;
1595
1596    /// Copy from texture to buffer.
1597    /// Works with a single array layer.
1598    /// Note: the copy extent is in physical size (rounded to the block size)
1599    unsafe fn copy_texture_to_buffer<T>(
1600        &mut self,
1601        src: &<Self::A as Api>::Texture,
1602        src_usage: wgt::TextureUses,
1603        dst: &<Self::A as Api>::Buffer,
1604        regions: T,
1605    ) where
1606        T: Iterator<Item = BufferTextureCopy>;
1607
1608    unsafe fn copy_acceleration_structure_to_acceleration_structure(
1609        &mut self,
1610        src: &<Self::A as Api>::AccelerationStructure,
1611        dst: &<Self::A as Api>::AccelerationStructure,
1612        copy: wgt::AccelerationStructureCopy,
1613    );
1614    // pass common
1615
1616    /// Sets the bind group at `index` to `group`.
1617    ///
1618    /// If this is not the first call to `set_bind_group` within the current
1619    /// render or compute pass:
1620    ///
1621    /// - If `layout` contains `n` bind group layouts, then any previously set
1622    ///   bind groups at indices `n` or higher are cleared.
1623    ///
1624    /// - If the first `m` bind group layouts of `layout` are equal to those of
1625    ///   the previously passed layout, but no more, then any previously set
1626    ///   bind groups at indices `m` or higher are cleared.
1627    ///
1628    /// It follows from the above that passing the same layout as before doesn't
1629    /// clear any bind groups.
1630    ///
1631    /// # Safety
1632    ///
1633    /// - This [`CommandEncoder`] must be within a render or compute pass.
1634    ///
1635    /// - `index` must be the valid index of some bind group layout in `layout`.
1636    ///   Call this the "relevant bind group layout".
1637    ///
1638    /// - The layout of `group` must be equal to the relevant bind group layout.
1639    ///
1640    /// - The length of `dynamic_offsets` must match the number of buffer
1641    ///   bindings [with dynamic offsets][hdo] in the relevant bind group
1642    ///   layout.
1643    ///
1644    /// - If those buffer bindings are ordered by increasing [`binding` number]
1645    ///   and paired with elements from `dynamic_offsets`, then each offset must
1646    ///   be a valid offset for the binding's corresponding buffer in `group`.
1647    ///
1648    /// [hdo]: wgt::BindingType::Buffer::has_dynamic_offset
1649    /// [`binding` number]: wgt::BindGroupLayoutEntry::binding
1650    unsafe fn set_bind_group(
1651        &mut self,
1652        layout: &<Self::A as Api>::PipelineLayout,
1653        index: u32,
1654        group: &<Self::A as Api>::BindGroup,
1655        dynamic_offsets: &[wgt::DynamicOffset],
1656    );
1657
1658    /// Sets a range in immediate data.
1659    ///
1660    /// IMPORTANT: while the data is passed as words, the offset is in bytes!
1661    ///
1662    /// # Safety
1663    ///
1664    /// - `offset_bytes` must be a multiple of 4.
1665    /// - `data` must not be empty.
1666    /// - The range of immediates written must be valid for the pipeline layout at draw time.
1667    unsafe fn set_immediates(
1668        &mut self,
1669        layout: &<Self::A as Api>::PipelineLayout,
1670        offset_bytes: u32,
1671        data: &[u32],
1672    );
1673
1674    unsafe fn insert_debug_marker(&mut self, label: &str);
1675    unsafe fn begin_debug_marker(&mut self, group_label: &str);
1676    unsafe fn end_debug_marker(&mut self);
1677
1678    // queries
1679
1680    /// # Safety:
1681    ///
1682    /// - If `set` is an occlusion query set, it must be the same one as used in the [`RenderPassDescriptor::occlusion_query_set`] parameter.
1683    unsafe fn begin_query(&mut self, set: &<Self::A as Api>::QuerySet, index: u32);
1684    /// # Safety:
1685    ///
1686    /// - If `set` is an occlusion query set, it must be the same one as used in the [`RenderPassDescriptor::occlusion_query_set`] parameter.
1687    unsafe fn end_query(&mut self, set: &<Self::A as Api>::QuerySet, index: u32);
1688    unsafe fn write_timestamp(&mut self, set: &<Self::A as Api>::QuerySet, index: u32);
1689    unsafe fn reset_queries(&mut self, set: &<Self::A as Api>::QuerySet, range: Range<u32>);
1690    unsafe fn copy_query_results(
1691        &mut self,
1692        set: &<Self::A as Api>::QuerySet,
1693        range: Range<u32>,
1694        buffer: &<Self::A as Api>::Buffer,
1695        offset: wgt::BufferAddress,
1696        stride: wgt::BufferSize,
1697    );
1698
1699    // render passes
1700
1701    /// Begin a new render pass, clearing all active bindings.
1702    ///
1703    /// This clears any bindings established by the following calls:
1704    ///
1705    /// - [`set_bind_group`](CommandEncoder::set_bind_group)
1706    /// - [`set_immediates`](CommandEncoder::set_immediates)
1707    /// - [`begin_query`](CommandEncoder::begin_query)
1708    /// - [`set_render_pipeline`](CommandEncoder::set_render_pipeline)
1709    /// - [`set_index_buffer`](CommandEncoder::set_index_buffer)
1710    /// - [`set_vertex_buffer`](CommandEncoder::set_vertex_buffer)
1711    ///
1712    /// # Safety
1713    ///
1714    /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed
1715    ///   by a call to [`end_render_pass`].
1716    ///
1717    /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed
1718    ///   by a call to [`end_compute_pass`].
1719    ///
1720    /// - All prior calls to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] must have been followed
1721    ///   by a call to [`end_ray_tracing_pass`].
1722    ///
1723    /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1724    /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1725    /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass
1726    /// [`end_render_pass`]: CommandEncoder::end_render_pass
1727    /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1728    /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass
1729    unsafe fn begin_render_pass(
1730        &mut self,
1731        desc: &RenderPassDescriptor<<Self::A as Api>::QuerySet, <Self::A as Api>::TextureView>,
1732    ) -> Result<(), DeviceError>;
1733
1734    /// End the current render pass.
1735    ///
1736    /// # Safety
1737    ///
1738    /// - There must have been a prior call to [`begin_render_pass`] on this [`CommandEncoder`]
1739    ///   that has not been followed by a call to [`end_render_pass`].
1740    ///
1741    /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1742    /// [`end_render_pass`]: CommandEncoder::end_render_pass
1743    unsafe fn end_render_pass(&mut self);
1744
1745    unsafe fn set_render_pipeline(&mut self, pipeline: &<Self::A as Api>::RenderPipeline);
1746
1747    /// Register an index buffer binding.
1748    ///
1749    /// The binding offset must be 4B-aligned and strictly less than the buffer
1750    /// size. On some backends, the binding size is ignored. This means that
1751    /// zero-size bindings must be simulated by binding a region of zeros
1752    /// spanning from the provided offset to the end of the buffer. See
1753    /// [`CommandEncoder::set_vertex_buffer`] for more detail.
1754    unsafe fn set_index_buffer<'a>(
1755        &mut self,
1756        binding: BufferBinding<'a, <Self::A as Api>::Buffer, wgt::BufferAddress>,
1757        format: wgt::IndexFormat,
1758    );
1759    /// Register a vertex buffer binding.
1760    ///
1761    /// The binding offset must be 4B-aligned and strictly less than the buffer
1762    /// size. On some backends, the binding size is ignored. This means that
1763    /// zero-size bindings must be simulated by binding a region of zeros
1764    /// spanning from the provided offset to the end of the buffer.
1765    ///
1766    /// These restrictions arise from Vulkan's `vkCmdBindVertexBuffers` and
1767    /// `vkCmdBindIndexBuffer`, which:
1768    ///
1769    ///  1. Do not support specifying the size of the binding.
1770    ///  2. Require that the binding offset is strictly less than the buffer size.
1771    ///
1772    /// A read at any offset from a zero-size binding is out-of-bounds, and
1773    /// should return zero. Because the binding size is not respected, this
1774    /// means there may not be non-zero data between the binding offset and
1775    /// the end of the buffer.
1776    ///
1777    /// Because the binding offset must be strictly less than the buffer size,
1778    /// supporting zero-size bindings requires zero padding at the end of the
1779    /// buffer.
1780    unsafe fn set_vertex_buffer<'a>(
1781        &mut self,
1782        index: u32,
1783        binding: BufferBinding<'a, <Self::A as Api>::Buffer, wgt::BufferAddress>,
1784    );
1785    unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>);
1786    unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>);
1787    unsafe fn set_stencil_reference(&mut self, value: u32);
1788    unsafe fn set_blend_constants(&mut self, color: &[f32; 4]);
1789
1790    unsafe fn draw(
1791        &mut self,
1792        first_vertex: u32,
1793        vertex_count: u32,
1794        first_instance: u32,
1795        instance_count: u32,
1796    );
1797    unsafe fn draw_indexed(
1798        &mut self,
1799        first_index: u32,
1800        index_count: u32,
1801        base_vertex: i32,
1802        first_instance: u32,
1803        instance_count: u32,
1804    );
1805    /// # Safety
1806    ///
1807    /// - If `draw_count > 1`, see the deferred-work obligation on
1808    ///   [`encode_deferred_multi_draws`](CommandEncoder::encode_deferred_multi_draws).
1809    unsafe fn draw_indirect(
1810        &mut self,
1811        buffer: &<Self::A as Api>::Buffer,
1812        offset: wgt::BufferAddress,
1813        draw_count: u32,
1814    );
1815    /// # Safety
1816    ///
1817    /// - If `draw_count > 1`, see the deferred-work obligation on
1818    ///   [`encode_deferred_multi_draws`](CommandEncoder::encode_deferred_multi_draws).
1819    unsafe fn draw_indexed_indirect(
1820        &mut self,
1821        buffer: &<Self::A as Api>::Buffer,
1822        offset: wgt::BufferAddress,
1823        draw_count: u32,
1824    );
1825    unsafe fn draw_indirect_count(
1826        &mut self,
1827        buffer: &<Self::A as Api>::Buffer,
1828        offset: wgt::BufferAddress,
1829        count_buffer: &<Self::A as Api>::Buffer,
1830        count_offset: wgt::BufferAddress,
1831        max_count: u32,
1832    );
1833    unsafe fn draw_indexed_indirect_count(
1834        &mut self,
1835        buffer: &<Self::A as Api>::Buffer,
1836        offset: wgt::BufferAddress,
1837        count_buffer: &<Self::A as Api>::Buffer,
1838        count_offset: wgt::BufferAddress,
1839        max_count: u32,
1840    );
1841    unsafe fn draw_mesh_tasks(
1842        &mut self,
1843        group_count_x: u32,
1844        group_count_y: u32,
1845        group_count_z: u32,
1846    );
1847    /// # Safety
1848    ///
1849    /// - If `draw_count > 1`, see the deferred-work obligation on
1850    ///   [`encode_deferred_multi_draws`](CommandEncoder::encode_deferred_multi_draws).
1851    unsafe fn draw_mesh_tasks_indirect(
1852        &mut self,
1853        buffer: &<Self::A as Api>::Buffer,
1854        offset: wgt::BufferAddress,
1855        draw_count: u32,
1856    );
1857    unsafe fn draw_mesh_tasks_indirect_count(
1858        &mut self,
1859        buffer: &<Self::A as Api>::Buffer,
1860        offset: wgt::BufferAddress,
1861        count_buffer: &<Self::A as Api>::Buffer,
1862        count_offset: wgt::BufferAddress,
1863        max_count: u32,
1864    );
1865
1866    /// Record any deferred setup work for indirect multi-draws of the most
1867    /// recently ended render pass into the current command buffer.
1868    ///
1869    /// Some backends lower [`draw_indirect`]-family calls with `draw_count > 1`
1870    /// to GPU-generated command lists (e.g. Metal indirect command buffers).
1871    /// The generation work must execute *before* the render pass that consumes
1872    /// it, but the pass contents are only known once the pass has been
1873    /// recorded, so such backends queue the generation work at draw-record time
1874    /// and encode it when this method is called.
1875    ///
1876    /// The default implementation does nothing; backends that don't defer any
1877    /// multi-draw work don't need to override it.
1878    ///
1879    /// # Safety
1880    ///
1881    /// - Must be called outside of a render, compute, or ray-tracing pass.
1882    /// - Between the [`end_render_pass`] for a pass that recorded indirect
1883    ///   multi-draws and the submission of that pass's command buffer, this
1884    ///   method must be called on this [`CommandEncoder`], while recording a
1885    ///   command buffer that the queue will execute *before* the pass's
1886    ///   command buffer. One call covers every pass ended since the previous
1887    ///   call.
1888    /// - The command buffer recorded here must not be reset until the pass's
1889    ///   command buffer has completed.
1890    /// - Any indirect (or count) buffer passed to a [`draw_indirect`]-family
1891    ///   call in that pass must not be written between that call and the
1892    ///   execution of the command buffer recorded here, other than by wgpu's
1893    ///   own indirect validation.
1894    ///
1895    /// [`draw_indirect`]: CommandEncoder::draw_indirect
1896    /// [`end_render_pass`]: CommandEncoder::end_render_pass
1897    unsafe fn encode_deferred_multi_draws(&mut self) {}
1898
1899    // compute passes
1900
1901    /// Begin a new compute pass, clearing all active bindings.
1902    ///
1903    /// This clears any bindings established by the following calls:
1904    ///
1905    /// - [`set_bind_group`](CommandEncoder::set_bind_group)
1906    /// - [`set_immediates`](CommandEncoder::set_immediates)
1907    /// - [`begin_query`](CommandEncoder::begin_query)
1908    /// - [`set_compute_pipeline`](CommandEncoder::set_compute_pipeline)
1909    ///
1910    /// # Safety
1911    ///
1912    /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed
1913    ///   by a call to [`end_render_pass`].
1914    ///
1915    /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed
1916    ///   by a call to [`end_compute_pass`].
1917    ///
1918    /// - All prior calls to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] must have been followed
1919    ///   by a call to [`end_ray_tracing_pass`].
1920    ///
1921    /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1922    /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1923    /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass
1924    /// [`end_render_pass`]: CommandEncoder::end_render_pass
1925    /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1926    /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass
1927    unsafe fn begin_compute_pass(
1928        &mut self,
1929        desc: &ComputePassDescriptor<<Self::A as Api>::QuerySet>,
1930    );
1931
1932    /// End the current compute pass.
1933    ///
1934    /// # Safety
1935    ///
1936    /// - There must have been a prior call to [`begin_compute_pass`] on this [`CommandEncoder`]
1937    ///   that has not been followed by a call to [`end_compute_pass`].
1938    ///
1939    /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1940    /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1941    unsafe fn end_compute_pass(&mut self);
1942
1943    unsafe fn set_compute_pipeline(&mut self, pipeline: &<Self::A as Api>::ComputePipeline);
1944
1945    unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]);
1946    unsafe fn dispatch_workgroups_indirect(
1947        &mut self,
1948        buffer: &<Self::A as Api>::Buffer,
1949        offset: wgt::BufferAddress,
1950    );
1951
1952    /// Begin a new ray tracing pass, clearing all active bindings.
1953    ///
1954    /// This clears any bindings established by the following calls:
1955    ///
1956    /// - [`set_bind_group`](CommandEncoder::set_bind_group)
1957    /// - [`set_immediates`](CommandEncoder::set_immediates)
1958    /// - [`begin_query`](CommandEncoder::begin_query)
1959    /// - [`set_ray_tracing_pipeline`](CommandEncoder::set_compute_pipeline)
1960    ///
1961    /// # Safety
1962    ///
1963    /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed
1964    ///   by a call to [`end_render_pass`].
1965    ///
1966    /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed
1967    ///   by a call to [`end_compute_pass`].
1968    ///
1969    /// - All prior calls to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] must have been followed
1970    ///   by a call to [`end_ray_tracing_pass`].
1971    ///
1972    /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1973    /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1974    /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass
1975    /// [`end_render_pass`]: CommandEncoder::end_render_pass
1976    /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1977    /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass
1978    unsafe fn begin_ray_tracing_pass(&mut self, desc: &RayTracingPassDescriptor);
1979
1980    /// End the current compute pass.
1981    ///
1982    /// # Safety
1983    ///
1984    /// - There must have been a prior call to [`begin_ray_tracing_pass`] on this [`CommandEncoder`]
1985    ///   that has not been followed by a call to [`end_ray_tracing_pass`].
1986    ///
1987    /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass
1988    /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass
1989    unsafe fn end_ray_tracing_pass(&mut self);
1990
1991    /// # Safety
1992    ///
1993    /// - Pipeline must not be destroyed
1994    unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &<Self::A as Api>::RayTracingPipeline);
1995
1996    unsafe fn trace_rays<'a>(
1997        &mut self,
1998        count: [u32; 3],
1999        ray_generation_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>,
2000        miss_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>,
2001        intersection_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>,
2002    );
2003
2004    /// Same as [`trace_rays`](CommandEncoder::trace_rays), but the ray counts are read
2005    /// from `buffer` at `offset` as three `u32`s.
2006    ///
2007    /// # Safety
2008    ///
2009    /// - The device must have been created with
2010    ///   [`wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES_INDIRECT`].
2011    /// - `buffer` must have been created with [`wgt::BufferUses::INDIRECT`] and must be in the
2012    ///   [`wgt::BufferUses::INDIRECT`] state.
2013    /// - If `buffer` was not created by [`Device::create_buffer`], it must meet the requirements
2014    ///   in the backend's documentation for buffer import.
2015    /// - `offset` must be a multiple of 4, and `offset + 12` must not exceed the buffer size.
2016    /// - The ray counts in the buffer must not exceed the per-dimension and total ray dispatch
2017    ///   limits of the device.
2018    unsafe fn trace_rays_indirect<'a>(
2019        &mut self,
2020        buffer: &<Self::A as Api>::Buffer,
2021        offset: wgt::BufferAddress,
2022        ray_generation_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>,
2023        miss_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>,
2024        intersection_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>,
2025    );
2026
2027    /// To get the required sizes for the buffer allocations use `get_acceleration_structure_build_sizes` per descriptor
2028    /// All buffers must be synchronized externally
2029    /// All buffer regions, which are written to may only be passed once per function call,
2030    /// with the exception of updates in the same descriptor.
2031    /// Consequences of this limitation:
2032    /// - scratch buffers need to be unique
2033    /// - a tlas can't be build in the same call with a blas it contains
2034    unsafe fn build_acceleration_structures<'a, T>(
2035        &mut self,
2036        descriptor_count: u32,
2037        descriptors: T,
2038    ) where
2039        Self::A: 'a,
2040        T: IntoIterator<
2041            Item = BuildAccelerationStructureDescriptor<
2042                'a,
2043                <Self::A as Api>::Buffer,
2044                <Self::A as Api>::AccelerationStructure,
2045            >,
2046        >;
2047    unsafe fn place_acceleration_structure_barrier(
2048        &mut self,
2049        barrier: AccelerationStructureBarrier,
2050    );
2051    // modeled off dx12, because this is able to be polyfilled in vulkan as opposed to the other way round
2052    unsafe fn read_acceleration_structure_compact_size(
2053        &mut self,
2054        acceleration_structure: &<Self::A as Api>::AccelerationStructure,
2055        buf: &<Self::A as Api>::Buffer,
2056    );
2057    unsafe fn set_acceleration_structure_dependencies(
2058        command_buffers: &[&<Self::A as Api>::CommandBuffer],
2059        dependencies: &[&<Self::A as Api>::AccelerationStructure],
2060    );
2061}
2062
2063bitflags!(
2064    /// Pipeline layout creation flags.
2065    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2066    pub struct PipelineLayoutFlags: u32 {
2067        /// D3D12: Add support for `first_vertex` and `first_instance` builtins
2068        /// via immediates for direct execution.
2069        const FIRST_VERTEX_INSTANCE = 1 << 0;
2070        /// D3D12: Add support for `num_workgroups` builtins via immediates
2071        /// for direct execution.
2072        const NUM_WORK_GROUPS = 1 << 1;
2073        /// D3D12: Add support for the builtins that the other flags enable for
2074        /// indirect execution.
2075        const INDIRECT_BUILTIN_UPDATE = 1 << 2;
2076    }
2077);
2078
2079bitflags!(
2080    /// Pipeline layout creation flags.
2081    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2082    pub struct BindGroupLayoutFlags: u32 {
2083        /// Allows for bind group binding arrays to be shorter than the array in the BGL.
2084        const PARTIALLY_BOUND = 1 << 0;
2085    }
2086);
2087
2088bitflags!(
2089    /// Texture format capability flags.
2090    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2091    pub struct TextureFormatCapabilities: u32 {
2092        /// Format can be sampled.
2093        const SAMPLED = 1 << 0;
2094        /// Format can be sampled with a linear sampler.
2095        const SAMPLED_LINEAR = 1 << 1;
2096        /// Format can be sampled with a min/max reduction sampler.
2097        const SAMPLED_MINMAX = 1 << 2;
2098
2099        /// Format can be used as storage with read-only access.
2100        const STORAGE_READ_ONLY = 1 << 3;
2101        /// Format can be used as storage with write-only access.
2102        const STORAGE_WRITE_ONLY = 1 << 4;
2103        /// Format can be used as storage with both read and write access.
2104        const STORAGE_READ_WRITE = 1 << 5;
2105        /// Format can be used as storage with atomics.
2106        const STORAGE_ATOMIC = 1 << 6;
2107
2108        /// Format can be used as color and input attachment.
2109        const COLOR_ATTACHMENT = 1 << 7;
2110        /// Format can be used as color (with blending) and input attachment.
2111        const COLOR_ATTACHMENT_BLEND = 1 << 8;
2112        /// Format can be used as depth-stencil and input attachment.
2113        const DEPTH_STENCIL_ATTACHMENT = 1 << 9;
2114
2115        /// Format can be multisampled by x2.
2116        const MULTISAMPLE_X2   = 1 << 10;
2117        /// Format can be multisampled by x4.
2118        const MULTISAMPLE_X4   = 1 << 11;
2119        /// Format can be multisampled by x8.
2120        const MULTISAMPLE_X8   = 1 << 12;
2121        /// Format can be multisampled by x16.
2122        const MULTISAMPLE_X16  = 1 << 13;
2123
2124        /// Format can be used for render pass resolve targets.
2125        const MULTISAMPLE_RESOLVE = 1 << 14;
2126
2127        /// Format can be copied from.
2128        const COPY_SRC = 1 << 15;
2129        /// Format can be copied to.
2130        const COPY_DST = 1 << 16;
2131    }
2132);
2133
2134#[cfg(any(metal, vulkan))]
2135impl TextureFormatCapabilities {
2136    /// Capabilities that may be offered by multi-planar texture formats. It is generally
2137    /// not possible to operate on a multi-planar texture as a whole. Presence of these
2138    /// capabilities on a multi-planar format signifies that plane views support the
2139    /// indicated usage.
2140    ///
2141    /// This constant omits `COPY_SRC` and `COPY_DST` because they are handled separately
2142    /// in the code that uses it.
2143    pub(crate) const VALID_FOR_MULTI_PLANAR: Self = Self::empty()
2144        .union(Self::SAMPLED)
2145        .union(Self::SAMPLED_LINEAR)
2146        .union(Self::COLOR_ATTACHMENT)
2147        .union(Self::COLOR_ATTACHMENT_BLEND);
2148}
2149
2150bitflags!(
2151    /// Texture format capability flags.
2152    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2153    pub struct FormatAspects: u8 {
2154        const COLOR = 1 << 0;
2155        const DEPTH = 1 << 1;
2156        const STENCIL = 1 << 2;
2157        const PLANE_0 = 1 << 3;
2158        const PLANE_1 = 1 << 4;
2159        const PLANE_2 = 1 << 5;
2160
2161        const DEPTH_STENCIL = Self::DEPTH.bits() | Self::STENCIL.bits();
2162    }
2163);
2164
2165impl FormatAspects {
2166    /// Computes a [`FormatAspects`] mask from a [`wgt::TextureFormat`] and [`wgt::TextureAspect`].
2167    ///
2168    /// When called from `wgpu-core`, additional validation of the return value is typically
2169    /// required:
2170    ///
2171    /// - This function returns an empty mask, if `aspect` does not identify any
2172    ///   valid aspect(s) of `format`.
2173    /// - This function returns a mask of all valid aspects, if `aspect` is
2174    ///   [`wgt::TextureAspect::All`], but some texture operations do not
2175    ///   support that.
2176    pub fn new(format: wgt::TextureFormat, aspect: wgt::TextureAspect) -> Self {
2177        let aspect_mask = match aspect {
2178            wgt::TextureAspect::All => Self::all(),
2179            wgt::TextureAspect::DepthOnly => Self::DEPTH,
2180            wgt::TextureAspect::StencilOnly => Self::STENCIL,
2181            wgt::TextureAspect::Plane0 => Self::PLANE_0,
2182            wgt::TextureAspect::Plane1 => Self::PLANE_1,
2183            wgt::TextureAspect::Plane2 => Self::PLANE_2,
2184        };
2185        Self::from(format) & aspect_mask
2186    }
2187
2188    /// Returns `true` if only one flag is set
2189    pub fn is_one(&self) -> bool {
2190        self.bits().is_power_of_two()
2191    }
2192
2193    pub fn map(&self) -> wgt::TextureAspect {
2194        match *self {
2195            Self::COLOR => wgt::TextureAspect::All,
2196            Self::DEPTH => wgt::TextureAspect::DepthOnly,
2197            Self::STENCIL => wgt::TextureAspect::StencilOnly,
2198            Self::PLANE_0 => wgt::TextureAspect::Plane0,
2199            Self::PLANE_1 => wgt::TextureAspect::Plane1,
2200            Self::PLANE_2 => wgt::TextureAspect::Plane2,
2201            _ => unreachable!(),
2202        }
2203    }
2204}
2205
2206impl From<wgt::TextureFormat> for FormatAspects {
2207    fn from(format: wgt::TextureFormat) -> Self {
2208        match format {
2209            wgt::TextureFormat::Stencil8 => Self::STENCIL,
2210            wgt::TextureFormat::Depth16Unorm
2211            | wgt::TextureFormat::Depth32Float
2212            | wgt::TextureFormat::Depth24Plus => Self::DEPTH,
2213            wgt::TextureFormat::Depth32FloatStencil8 | wgt::TextureFormat::Depth24PlusStencil8 => {
2214                Self::DEPTH_STENCIL
2215            }
2216            wgt::TextureFormat::NV12 | wgt::TextureFormat::P010 => Self::PLANE_0 | Self::PLANE_1,
2217            _ => Self::COLOR,
2218        }
2219    }
2220}
2221
2222bitflags!(
2223    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2224    pub struct MemoryFlags: u32 {
2225        /// The resource is short-lived and may be placed in a separate memory pool.
2226        const TRANSIENT = 1 << 0;
2227        const PREFER_COHERENT = 1 << 1;
2228    }
2229);
2230
2231bitflags!(
2232    /// Attachment load and store operations.
2233    ///
2234    /// There must be at least one flag from the LOAD group and one from the STORE group set.
2235    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2236    pub struct AttachmentOps: u8 {
2237        /// Load the existing contents of the attachment.
2238        const LOAD = 1 << 0;
2239        /// Clear the attachment to a specified value.
2240        const LOAD_CLEAR = 1 << 1;
2241        /// The contents of the attachment are undefined.
2242        const LOAD_DONT_CARE = 1 << 2;
2243        /// Store the contents of the attachment.
2244        const STORE = 1 << 3;
2245        /// The contents of the attachment are undefined after the pass.
2246        const STORE_DISCARD = 1 << 4;
2247    }
2248);
2249
2250#[derive(Debug)]
2251pub struct InstanceDescriptor<'a> {
2252    pub name: &'a str,
2253    pub flags: wgt::InstanceFlags,
2254    pub memory_budget_thresholds: wgt::MemoryBudgetThresholds,
2255    pub backend_options: wgt::BackendOptions,
2256    pub telemetry: Option<Telemetry>,
2257    /// This is a borrow because the surrounding `core::Instance` keeps the owned display handle
2258    /// alive already.
2259    pub display: Option<DisplayHandle<'a>>,
2260}
2261
2262#[derive(Clone, Debug)]
2263pub struct Alignments {
2264    /// The alignment of the start of the buffer used as a GPU copy source.
2265    pub buffer_copy_offset: wgt::BufferSize,
2266
2267    /// The alignment of the row pitch of the texture data stored in a buffer that is
2268    /// used in a GPU copy operation.
2269    pub buffer_copy_pitch: wgt::BufferSize,
2270
2271    /// The finest alignment of bound range checking for uniform buffers.
2272    ///
2273    /// When `wgpu_hal` restricts shader references to the [accessible
2274    /// region][ar] of a [`Uniform`] buffer, the size of the accessible region
2275    /// is the bind group binding's stated [size], rounded up to the next
2276    /// multiple of this value.
2277    ///
2278    /// We don't need an analogous field for storage buffer bindings, because
2279    /// all our backends promise to enforce the size at least to a four-byte
2280    /// alignment, and `wgpu_hal` requires bound range lengths to be a multiple
2281    /// of four anyway.
2282    ///
2283    /// [ar]: struct.BufferBinding.html#accessible-region
2284    /// [`Uniform`]: wgt::BufferBindingType::Uniform
2285    /// [size]: BufferBinding::size
2286    pub uniform_bounds_check_alignment: wgt::BufferSize,
2287
2288    /// The size of the raw TLAS instance
2289    pub raw_tlas_instance_size: u32,
2290
2291    /// What the scratch buffer for building an acceleration structure must be aligned to
2292    pub ray_tracing_scratch_buffer_alignment: u32,
2293
2294    /// How large a single piece of group data is. That is, how large the vector returned
2295    /// from `device.get_raytracing_pipeline_group_data(&pipeline, n..(n+1))` is.
2296    ///
2297    /// If ray tracing pipelines are implemented, this must be non zero.
2298    pub ray_tracing_pipeline_group_data_size: u32,
2299
2300    /// If ray tracing pipelines are implemented, this must be a power of two (and non zero).
2301    pub ray_tracing_pipeline_group_data_alignment: u32,
2302
2303    /// If ray tracing pipelines are implemented, this must be a power of two (and non zero).
2304    ///
2305    /// The offset within `PipelineGroupData` must be a multiple of this
2306    pub ray_tracing_pipeline_data_offset_alignment: u32,
2307}
2308
2309#[derive(Clone, Debug)]
2310pub struct Capabilities {
2311    pub limits: wgt::Limits,
2312    pub alignments: Alignments,
2313    pub downlevel: wgt::DownlevelCapabilities,
2314    /// Supported cooperative matrix configurations.
2315    ///
2316    /// Empty if cooperative matrices are not supported.
2317    pub cooperative_matrix_properties: Vec<wgt::CooperativeMatrixProperties>,
2318
2319    /// Whether the implementation reports that it is likely to reorder ray tracing invocations.
2320    ///
2321    /// [`None`] if [`Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER`] is not supported.
2322    ///
2323    /// [`None`]: wgt::RayTracingInvocationReorderMode::None
2324    /// [`Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER
2325    pub ray_tracing_invocation_reorder_mode: wgt::RayTracingInvocationReorderMode,
2326}
2327
2328/// An adapter with all the information needed to reason about its capabilities.
2329///
2330/// These are either made by [`Instance::enumerate_adapters`] or by backend specific
2331/// methods on the backend [`Instance`] or [`Adapter`].
2332#[derive(Debug)]
2333pub struct ExposedAdapter<A: Api> {
2334    pub adapter: A::Adapter,
2335    pub info: wgt::AdapterInfo,
2336    pub features: wgt::Features,
2337    pub capabilities: Capabilities,
2338}
2339
2340/// Describes information about what a `Surface`'s presentation capabilities are.
2341/// Fetch this with [Adapter::surface_capabilities].
2342#[derive(Debug, Clone)]
2343pub struct SurfaceCapabilities {
2344    /// List of supported texture formats together with the color spaces
2345    /// supported for each format.
2346    ///
2347    /// Must be at least one. At most one entry per format, each with a
2348    /// non-empty set of color spaces.
2349    pub formats: Vec<wgt::SurfaceFormatCapabilities>,
2350
2351    /// Range for the number of queued frames.
2352    ///
2353    /// This adjusts either the swapchain frame count to value + 1 - or sets SetMaximumFrameLatency to the value given,
2354    /// or uses a wait-for-present in the acquire method to limit rendering such that it acts like it's a value + 1 swapchain frame set.
2355    ///
2356    /// - `maximum_frame_latency.start` must be at least 1.
2357    /// - `maximum_frame_latency.end` must be larger or equal to `maximum_frame_latency.start`.
2358    pub maximum_frame_latency: RangeInclusive<u32>,
2359
2360    /// Current extent of the surface, if known.
2361    pub current_extent: Option<wgt::Extent3d>,
2362
2363    /// Supported texture usage flags.
2364    ///
2365    /// Must have at least `wgt::TextureUses::COLOR_TARGET`
2366    pub usage: wgt::TextureUses,
2367
2368    /// List of supported V-sync modes.
2369    ///
2370    /// Must be at least one.
2371    pub present_modes: Vec<wgt::PresentMode>,
2372
2373    /// List of supported alpha composition modes.
2374    ///
2375    /// Must be at least one.
2376    pub composite_alpha_modes: Vec<wgt::CompositeAlphaMode>,
2377}
2378
2379impl SurfaceCapabilities {
2380    /// Returns the supported texture formats, dropping the per-format color-space
2381    /// information carried in [`Self::formats`].
2382    pub fn texture_formats(&self) -> impl Iterator<Item = wgt::TextureFormat> + '_ {
2383        self.formats.iter().map(|fc| fc.format)
2384    }
2385}
2386
2387#[derive(Debug)]
2388pub struct AcquiredSurfaceTexture<A: Api> {
2389    pub texture: A::SurfaceTexture,
2390    /// The presentation configuration no longer matches
2391    /// the surface properties exactly, but can still be used to present
2392    /// to the surface successfully.
2393    pub suboptimal: bool,
2394}
2395
2396/// An open connection to a device and a queue.
2397///
2398/// This can be created from [`Adapter::open`] or backend
2399/// specific methods on the backend's [`Instance`] or [`Adapter`].
2400#[derive(Debug)]
2401pub struct OpenDevice<A: Api> {
2402    pub device: A::Device,
2403    pub queue: A::Queue,
2404}
2405
2406#[derive(Clone, Debug)]
2407pub struct BufferMapping {
2408    pub ptr: NonNull<u8>,
2409    pub is_coherent: bool,
2410}
2411
2412#[derive(Clone, Debug)]
2413pub struct BufferDescriptor<'a> {
2414    pub label: Label<'a>,
2415
2416    /// The requested size of the buffer.
2417    ///
2418    /// `wgpu-hal` may allocate more bytes than requested, if required by the
2419    /// platform. The actual allocation size is returned by `create_buffer`.
2420    /// Where platforms offer bounds checking, it will operate based on the
2421    /// allocated size, not the requested size, so other means may be necessary
2422    /// to prevent access beyond the original requested size. The content of
2423    /// newly-created buffers is undefined.
2424    pub size: wgt::BufferAddress,
2425    pub usage: wgt::BufferUses,
2426    pub memory_flags: MemoryFlags,
2427}
2428
2429#[derive(Clone, Debug)]
2430pub struct TextureDescriptor<'a> {
2431    pub label: Label<'a>,
2432    pub size: wgt::Extent3d,
2433    pub mip_level_count: u32,
2434    pub sample_count: u32,
2435    pub dimension: wgt::TextureDimension,
2436    pub format: wgt::TextureFormat,
2437    pub usage: wgt::TextureUses,
2438    pub memory_flags: MemoryFlags,
2439    /// The view dimension texture bindings will use.
2440    /// Must be `Some` on devices without
2441    /// [`ARBITRARY_BINDING_VIEW_DIMENSIONS`](wgt::DownlevelFlags::ARBITRARY_BINDING_VIEW_DIMENSIONS)
2442    /// (GLES), ignored otherwise.
2443    pub texture_binding_view_dimension: Option<wgt::TextureViewDimension>,
2444    /// Allows views of this texture to have a different format
2445    /// than the texture does.
2446    pub view_formats: Vec<wgt::TextureFormat>,
2447}
2448
2449impl TextureDescriptor<'_> {
2450    pub fn copy_extent(&self) -> CopyExtent {
2451        CopyExtent::map_extent_to_copy_size(&self.size, self.dimension)
2452    }
2453
2454    pub fn is_cube_compatible(&self) -> bool {
2455        self.dimension == wgt::TextureDimension::D2
2456            && self.size.depth_or_array_layers.is_multiple_of(6)
2457            && self.sample_count == 1
2458            && self.size.width == self.size.height
2459    }
2460
2461    pub fn array_layer_count(&self) -> u32 {
2462        match self.dimension {
2463            wgt::TextureDimension::D1 | wgt::TextureDimension::D3 => 1,
2464            wgt::TextureDimension::D2 => self.size.depth_or_array_layers,
2465        }
2466    }
2467}
2468
2469/// TextureView descriptor.
2470///
2471/// Valid usage:
2472///. - `format` has to be the same as `TextureDescriptor::format`
2473///. - `dimension` has to be compatible with `TextureDescriptor::dimension`
2474///. - `usage` has to be a subset of `TextureDescriptor::usage`
2475///. - `range` has to be a subset of parent texture
2476#[derive(Clone, Debug)]
2477pub struct TextureViewDescriptor<'a> {
2478    pub label: Label<'a>,
2479    pub format: wgt::TextureFormat,
2480    pub dimension: wgt::TextureViewDimension,
2481    pub usage: wgt::TextureUses,
2482    pub range: wgt::ImageSubresourceRange,
2483    pub swizzle: wgt::TextureComponentSwizzle,
2484}
2485
2486#[derive(Clone, Debug)]
2487pub struct SamplerDescriptor<'a> {
2488    pub label: Label<'a>,
2489    pub address_modes: [wgt::AddressMode; 3],
2490    pub mag_filter: wgt::FilterMode,
2491    pub min_filter: wgt::FilterMode,
2492    pub mipmap_filter: wgt::MipmapFilterMode,
2493    pub lod_clamp: Range<f32>,
2494    pub compare: Option<wgt::CompareFunction>,
2495    // Must in the range [1, 16].
2496    //
2497    // Anisotropic filtering must be supported if this is not 1.
2498    pub anisotropy_clamp: u16,
2499    pub border_color: Option<wgt::SamplerBorderColor>,
2500}
2501
2502/// BindGroupLayout descriptor.
2503///
2504/// Valid usage:
2505/// - `entries` are sorted by ascending `wgt::BindGroupLayoutEntry::binding`
2506#[derive(Clone, Debug)]
2507pub struct BindGroupLayoutDescriptor<'a> {
2508    pub label: Label<'a>,
2509    pub flags: BindGroupLayoutFlags,
2510    pub entries: &'a [wgt::BindGroupLayoutEntry],
2511}
2512
2513#[derive(Clone, Debug)]
2514pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> {
2515    pub label: Label<'a>,
2516    pub flags: PipelineLayoutFlags,
2517    pub bind_group_layouts: &'a [Option<&'a B>],
2518    pub immediate_size: u32,
2519}
2520
2521/// A region of a buffer made visible to shaders via a [`BindGroup`].
2522///
2523/// [`BindGroup`]: Api::BindGroup
2524///
2525/// ## Construction
2526///
2527/// The recommended way to construct a `BufferBinding` is using the `binding`
2528/// method on a wgpu-core `Buffer`, which will validate the binding size
2529/// against the buffer size. A `new_unchecked` constructor is also provided for
2530/// cases where direct construction is necessary.
2531///
2532/// ## Accessible region
2533///
2534/// `wgpu_hal` guarantees that shaders compiled with
2535/// [`ShaderModuleDescriptor::runtime_checks`] set to `true` cannot read or
2536/// write data via this binding outside the *accessible region* of a buffer:
2537///
2538/// - The accessible region starts at [`offset`].
2539///
2540/// - For [`Storage`] bindings, the size of the accessible region is [`size`],
2541///   which must be a multiple of 4.
2542///
2543/// - For [`Uniform`] bindings, the size of the accessible region is [`size`]
2544///   rounded up to the next multiple of
2545///   [`Alignments::uniform_bounds_check_alignment`].
2546///
2547/// Note that this guarantee is stricter than WGSL's requirements for
2548/// [out-of-bounds accesses][woob], as WGSL allows them to return values from
2549/// elsewhere in the buffer. But this guarantee is necessary anyway, to permit
2550/// `wgpu-core` to avoid clearing uninitialized regions of buffers that will
2551/// never be read by the application before they are overwritten. This
2552/// optimization consults bind group buffer binding regions to determine which
2553/// parts of which buffers shaders might observe. This optimization is only
2554/// sound if shader access is bounds-checked.
2555///
2556/// ## Zero-length bindings
2557///
2558/// Some platform APIs do not accept zero-length regions; for example, see
2559/// [VUID-VkDescriptorBufferInfo-offset-00340][340],
2560/// [VUID-VkDescriptorBufferInfo-range-00341][341], or the
2561/// documentation for GLES's [glBindBufferRange][bbr]. For
2562/// [VUID-VkCmdBindVertexBuffers-pOffsets-00626][626], no size is specified,
2563/// the binding extends from the offset to the end of the buffer, and the offset
2564/// must be strictly less than the buffer size.
2565///
2566/// WebGPU does not allow zero-length storage/uniform buffer bindings, but does
2567/// allow zero-length vertex/index buffer bindings. `wgpu-core` ensures that
2568/// buffers supporting vertex/index usage have 4B of naturally-aligned padding at
2569/// the end, to enable simulating a zero-length binding at the end of the buffer.
2570///
2571/// [`offset`]: BufferBinding::offset
2572/// [`size`]: BufferBinding::size
2573/// [`Storage`]: wgt::BufferBindingType::Storage
2574/// [`Uniform`]: wgt::BufferBindingType::Uniform
2575/// [340]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-offset-00340
2576/// [341]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-range-00341
2577/// [626]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdBindVertexBuffers-pOffsets-00626
2578/// [bbr]: https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glBindBufferRange.xhtml
2579/// [woob]: https://gpuweb.github.io/gpuweb/wgsl/#out-of-bounds-access-sec
2580#[derive(Debug)]
2581pub struct BufferBinding<'a, B: DynBuffer + ?Sized, S> {
2582    /// The buffer being bound.
2583    ///
2584    /// This is not fully `pub` to prevent direct construction of
2585    /// `BufferBinding`s, while still allowing public read access to the `offset`
2586    /// and `size` properties. Read access to the buffer is available via
2587    /// [`Self::buffer`].
2588    pub(crate) buffer: &'a B,
2589
2590    /// The offset at which the bound region starts.
2591    ///
2592    /// This must be less or equal to the size of the buffer.
2593    pub offset: wgt::BufferAddress,
2594
2595    /// The size of the region bound, in bytes.
2596    pub size: S,
2597}
2598
2599// We must implement this manually because `B` is not necessarily `Clone`.
2600impl<B: DynBuffer + ?Sized, S: Copy> Clone for BufferBinding<'_, B, S> {
2601    fn clone(&self) -> Self {
2602        BufferBinding {
2603            buffer: self.buffer,
2604            offset: self.offset,
2605            size: self.size,
2606        }
2607    }
2608}
2609
2610impl<'a, B: DynBuffer + ?Sized, S> BufferBinding<'a, B, S> {
2611    /// Construct a `BufferBinding` with the given contents.
2612    ///
2613    /// When possible, use the `binding` method on a wgpu-core `Buffer` instead
2614    /// of this method. `Buffer::binding` validates the size of the binding
2615    /// against the size of the buffer.
2616    ///
2617    /// It is more difficult to provide a validating constructor here, due to
2618    /// not having direct access to the size of a `DynBuffer`.
2619    ///
2620    /// SAFETY: The caller is responsible for ensuring that a binding of `size`
2621    /// bytes starting at `offset` is contained within the buffer. `size`
2622    /// may be zero only for vertex/index buffer bindings.
2623    pub fn new_unchecked(buffer: &'a B, offset: wgt::BufferAddress, size: S) -> Self {
2624        Self {
2625            buffer,
2626            offset,
2627            size,
2628        }
2629    }
2630
2631    /// The buffer being bound.
2632    pub fn buffer(&self) -> &'a B {
2633        self.buffer
2634    }
2635}
2636
2637#[derive(Debug)]
2638pub struct TextureBinding<'a, T: DynTextureView + ?Sized> {
2639    pub view: &'a T,
2640    pub usage: wgt::TextureUses,
2641}
2642
2643impl<'a, T: DynTextureView + ?Sized> Clone for TextureBinding<'a, T> {
2644    fn clone(&self) -> Self {
2645        TextureBinding {
2646            view: self.view,
2647            usage: self.usage,
2648        }
2649    }
2650}
2651
2652#[derive(Debug)]
2653pub struct ExternalTextureBinding<'a, B: DynBuffer + ?Sized, T: DynTextureView + ?Sized> {
2654    pub planes: [TextureBinding<'a, T>; 3],
2655    pub params: BufferBinding<'a, B, wgt::BufferSize>,
2656}
2657
2658impl<'a, B: DynBuffer + ?Sized, T: DynTextureView + ?Sized> Clone
2659    for ExternalTextureBinding<'a, B, T>
2660{
2661    fn clone(&self) -> Self {
2662        ExternalTextureBinding {
2663            planes: self.planes.clone(),
2664            params: self.params.clone(),
2665        }
2666    }
2667}
2668
2669/// cbindgen:ignore
2670#[derive(Clone, Debug)]
2671pub struct BindGroupEntry {
2672    pub binding: u32,
2673    pub resource_index: u32,
2674    pub count: u32,
2675}
2676
2677/// BindGroup descriptor.
2678///
2679/// Valid usage:
2680///. - `entries` has to be sorted by ascending `BindGroupEntry::binding`
2681///. - `entries` has to have the same set of `BindGroupEntry::binding` as `layout`
2682///. - each entry has to be compatible with the `layout`
2683///. - each entry's `BindGroupEntry::resource_index` is within range
2684///    of the corresponding resource array, selected by the relevant
2685///    `BindGroupLayoutEntry`.
2686#[derive(Clone, Debug)]
2687pub struct BindGroupDescriptor<
2688    'a,
2689    Bgl: DynBindGroupLayout + ?Sized,
2690    B: DynBuffer + ?Sized,
2691    S: DynSampler + ?Sized,
2692    T: DynTextureView + ?Sized,
2693    A: DynAccelerationStructure + ?Sized,
2694> {
2695    pub label: Label<'a>,
2696    pub layout: &'a Bgl,
2697    pub buffers: &'a [BufferBinding<'a, B, wgt::BufferSize>],
2698    pub samplers: &'a [&'a S],
2699    pub textures: &'a [TextureBinding<'a, T>],
2700    pub entries: &'a [BindGroupEntry],
2701    pub acceleration_structures: &'a [&'a A],
2702    pub external_textures: &'a [ExternalTextureBinding<'a, B, T>],
2703}
2704
2705#[derive(Clone, Debug)]
2706pub struct CommandEncoderDescriptor<'a, Q: DynQueue + ?Sized> {
2707    pub label: Label<'a>,
2708    pub queue: &'a Q,
2709}
2710
2711/// Naga shader module.
2712#[derive(Default)]
2713pub struct NagaShader {
2714    /// Shader module IR.
2715    pub module: Cow<'static, naga::Module>,
2716    /// Analysis information of the module.
2717    pub info: naga::valid::ModuleInfo,
2718    /// Source codes for debug
2719    pub debug_source: Option<DebugSource>,
2720}
2721
2722// Custom implementation avoids the need to generate Debug impl code
2723// for the whole Naga module and info.
2724impl fmt::Debug for NagaShader {
2725    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2726        write!(formatter, "Naga shader")
2727    }
2728}
2729
2730/// Shader input.
2731pub enum ShaderInput<'a> {
2732    Naga(NagaShader),
2733    MetalLib {
2734        file: &'a [u8],
2735        num_workgroups: hashbrown::HashMap<String, (u32, u32, u32)>,
2736    },
2737    Msl {
2738        shader: &'a str,
2739        num_workgroups: hashbrown::HashMap<String, (u32, u32, u32)>,
2740    },
2741    SpirV(&'a [u32]),
2742    Dxil {
2743        shader: &'a [u8],
2744    },
2745    Hlsl {
2746        shader: &'a str,
2747    },
2748    Glsl {
2749        shader: &'a str,
2750    },
2751}
2752
2753impl fmt::Debug for ShaderInput<'_> {
2754    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2755        match self {
2756            // Don't include the entire shader source, especially for binary formats, because it
2757            // would be spammy.
2758            Self::Naga { .. } => f.debug_tuple("Naga").finish_non_exhaustive(),
2759            Self::MetalLib { .. } => f.debug_tuple("MetalLib").finish_non_exhaustive(),
2760            Self::Msl { .. } => f.debug_tuple("Msl").finish_non_exhaustive(),
2761            Self::SpirV { .. } => f.debug_tuple("SpirV").finish_non_exhaustive(),
2762            Self::Dxil { .. } => f.debug_tuple("Dxil").finish_non_exhaustive(),
2763            Self::Hlsl { .. } => f.debug_tuple("Hlsl").finish_non_exhaustive(),
2764            Self::Glsl { .. } => f.debug_tuple("Glsl").finish_non_exhaustive(),
2765        }
2766    }
2767}
2768
2769#[derive(Debug)]
2770pub struct ShaderModuleDescriptor<'a> {
2771    pub label: Label<'a>,
2772
2773    /// # Safety
2774    ///
2775    /// See the documentation for each flag in [`ShaderRuntimeChecks`][src].
2776    ///
2777    /// [src]: wgt::ShaderRuntimeChecks
2778    pub runtime_checks: wgt::ShaderRuntimeChecks,
2779}
2780
2781#[derive(Debug, Clone)]
2782pub struct DebugSource {
2783    pub file_name: Cow<'static, str>,
2784    pub source_code: Cow<'static, str>,
2785}
2786
2787/// Describes a programmable pipeline stage.
2788#[derive(Debug)]
2789pub struct ProgrammableStage<'a, M: DynShaderModule + ?Sized> {
2790    /// The compiled shader module for this stage.
2791    pub module: &'a M,
2792    /// The name of the entry point in the compiled shader. There must be a function with this name
2793    ///  in the shader.
2794    pub entry_point: &'a str,
2795    /// Pipeline constants
2796    pub constants: &'a naga::back::PipelineConstants,
2797    /// Whether workgroup scoped memory will be initialized with zero values for this stage.
2798    ///
2799    /// This is required by the WebGPU spec, but may have overhead which can be avoided
2800    /// for cross-platform applications
2801    pub zero_initialize_workgroup_memory: bool,
2802}
2803
2804impl<M: DynShaderModule + ?Sized> Clone for ProgrammableStage<'_, M> {
2805    fn clone(&self) -> Self {
2806        Self {
2807            module: self.module,
2808            entry_point: self.entry_point,
2809            constants: self.constants,
2810            zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory,
2811        }
2812    }
2813}
2814
2815/// Describes a compute pipeline.
2816#[derive(Clone, Debug)]
2817pub struct ComputePipelineDescriptor<
2818    'a,
2819    Pl: DynPipelineLayout + ?Sized,
2820    M: DynShaderModule + ?Sized,
2821    Pc: DynPipelineCache + ?Sized,
2822> {
2823    pub label: Label<'a>,
2824    /// The layout of bind groups for this pipeline.
2825    pub layout: &'a Pl,
2826    /// The compiled compute stage and its entry point.
2827    pub stage: ProgrammableStage<'a, M>,
2828    /// The cache which will be used and filled when compiling this pipeline
2829    pub cache: Option<&'a Pc>,
2830}
2831
2832#[derive(Debug)]
2833pub struct PipelineCacheDescriptor<'a> {
2834    pub label: Label<'a>,
2835    pub data: Option<&'a [u8]>,
2836}
2837
2838/// Describes how the vertex buffer is interpreted.
2839#[derive(Clone, Debug)]
2840pub struct VertexBufferLayout<'a> {
2841    /// The stride, in bytes, between elements of this buffer.
2842    pub array_stride: wgt::BufferAddress,
2843    /// How often this vertex buffer is "stepped" forward.
2844    pub step_mode: wgt::VertexStepMode,
2845    /// The list of attributes which comprise a single vertex.
2846    pub attributes: &'a [wgt::VertexAttribute],
2847}
2848
2849#[derive(Clone, Debug)]
2850pub enum VertexProcessor<'a, M: DynShaderModule + ?Sized> {
2851    Standard {
2852        /// The format of any vertex buffers used with this pipeline.
2853        vertex_buffers: &'a [Option<VertexBufferLayout<'a>>],
2854        /// The vertex stage for this pipeline.
2855        vertex_stage: ProgrammableStage<'a, M>,
2856    },
2857    Mesh {
2858        task_stage: Option<ProgrammableStage<'a, M>>,
2859        mesh_stage: ProgrammableStage<'a, M>,
2860    },
2861}
2862
2863/// Describes a render (graphics) pipeline.
2864#[derive(Clone, Debug)]
2865pub struct RenderPipelineDescriptor<
2866    'a,
2867    Pl: DynPipelineLayout + ?Sized,
2868    M: DynShaderModule + ?Sized,
2869    Pc: DynPipelineCache + ?Sized,
2870> {
2871    pub label: Label<'a>,
2872    /// The layout of bind groups for this pipeline.
2873    pub layout: &'a Pl,
2874    /// The vertex processing state(vertex shader + buffers or task + mesh shaders)
2875    pub vertex_processor: VertexProcessor<'a, M>,
2876    /// The properties of the pipeline at the primitive assembly and rasterization level.
2877    pub primitive: wgt::PrimitiveState,
2878    /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
2879    pub depth_stencil: Option<wgt::DepthStencilState>,
2880    /// The multi-sampling properties of the pipeline.
2881    pub multisample: wgt::MultisampleState,
2882    /// The fragment stage for this pipeline.
2883    pub fragment_stage: Option<ProgrammableStage<'a, M>>,
2884    /// The effect of draw calls on the color aspect of the output target.
2885    pub color_targets: &'a [Option<wgt::ColorTargetState>],
2886    /// If the pipeline will be used with a multiview render pass, this indicates how many array
2887    /// layers the attachments will have.
2888    pub multiview_mask: Option<NonZeroU32>,
2889    /// The cache which will be used and filled when compiling this pipeline
2890    pub cache: Option<&'a Pc>,
2891}
2892
2893#[derive(Clone, Debug)]
2894pub struct RayObjectIntersectionState<'a, M: DynShaderModule + ?Sized> {
2895    pub closest_hit: ProgrammableStage<'a, M>,
2896    pub any_hit: Option<ProgrammableStage<'a, M>>,
2897}
2898
2899/// Describes a ray tracing pipeline.
2900#[derive(Clone, Debug)]
2901pub struct RayTracingPipelineDescriptor<
2902    'a,
2903    Pl: DynPipelineLayout + ?Sized,
2904    M: DynShaderModule + ?Sized,
2905    Pc: DynPipelineCache + ?Sized,
2906> {
2907    pub label: Label<'a>,
2908    /// The layout of bind groups for this pipeline.
2909    pub layout: &'a Pl,
2910    /// The ray generation stage.
2911    pub ray_generation: ProgrammableStage<'a, M>,
2912    /// The miss stage.
2913    pub miss: ProgrammableStage<'a, M>,
2914    /// All the object intersection stages.
2915    pub intersection: &'a [RayObjectIntersectionState<'a, M>],
2916    /// The maximum recursion depth allowed for the ray tracing (ray_generation shader counts as depth 0).
2917    pub max_recursion_depth: u32,
2918    /// The cache which will be used and filled when compiling this pipeline
2919    pub cache: Option<&'a Pc>,
2920}
2921
2922#[derive(Debug, Clone)]
2923pub struct SurfaceConfiguration {
2924    /// Maximum number of queued frames. Must be in
2925    /// `SurfaceCapabilities::maximum_frame_latency` range.
2926    pub maximum_frame_latency: u32,
2927    /// Vertical synchronization mode.
2928    pub present_mode: wgt::PresentMode,
2929    /// Alpha composition mode.
2930    pub composite_alpha_mode: wgt::CompositeAlphaMode,
2931    /// Format of the surface textures.
2932    pub format: wgt::TextureFormat,
2933    /// Color space in which the presentation engine interprets the surface
2934    /// textures. Never [`wgt::SurfaceColorSpace::Auto`]; `wgpu-core` resolves
2935    /// `Auto` to a concrete color space before configuring the surface, and
2936    /// the (format, color space) pair must be listed in
2937    /// `SurfaceCapabilities::formats`.
2938    pub color_space: wgt::SurfaceColorSpace,
2939    /// Requested texture extent. Must be in
2940    /// `SurfaceCapabilities::extents` range.
2941    pub extent: wgt::Extent3d,
2942    /// Allowed usage of surface textures,
2943    pub usage: wgt::TextureUses,
2944    /// Allows views of swapchain texture to have a different format
2945    /// than the texture does.
2946    pub view_formats: Vec<wgt::TextureFormat>,
2947}
2948
2949#[derive(Debug, Clone)]
2950pub struct Rect<T> {
2951    pub x: T,
2952    pub y: T,
2953    pub w: T,
2954    pub h: T,
2955}
2956
2957#[derive(Debug, Clone, PartialEq)]
2958pub struct StateTransition<T> {
2959    pub from: T,
2960    pub to: T,
2961}
2962
2963#[derive(Debug, Clone)]
2964pub struct BufferBarrier<'a, B: DynBuffer + ?Sized> {
2965    pub buffer: &'a B,
2966    pub usage: StateTransition<wgt::BufferUses>,
2967}
2968
2969/// One side of a [`QueueFamilyOwnershipTransfer`].
2970///
2971/// The named variants stand for the queue families that Vulkan reserves for
2972/// resources shared outside the current device; [`Explicit`] carries an
2973/// ordinary queue family index, such as the one returned by
2974/// `vulkan::Device::queue_family_index`.
2975///
2976/// [`Explicit`]: QueueFamily::Explicit
2977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2978pub enum QueueFamily {
2979    /// A specific queue family, identified by its index.
2980    Explicit(u32),
2981
2982    /// The queue family of an external, non-Vulkan API
2983    /// (`VK_QUEUE_FAMILY_EXTERNAL`).
2984    External,
2985
2986    /// The queue family of a foreign consumer of the memory, such as a
2987    /// different device or the kernel (`VK_QUEUE_FAMILY_FOREIGN_EXT`).
2988    ///
2989    /// Requires the `VK_EXT_queue_family_foreign` extension.
2990    Foreign,
2991}
2992
2993/// A queue family ownership transfer to perform as part of a [`TextureBarrier`].
2994///
2995/// This is only honored by the Vulkan backend; every other backend ignores it.
2996/// It exists so that textures imported from external memory (for example via
2997/// `VK_KHR_external_memory`) can have their backing image transferred between
2998/// wgpu's queue family and a queue family outside of wgpu's control when the
2999/// image is acquired for use and released afterwards.
3000///
3001/// `src` becomes `VkImageMemoryBarrier::srcQueueFamilyIndex` and `dst` becomes
3002/// `VkImageMemoryBarrier::dstQueueFamilyIndex`. To acquire an externally owned
3003/// image, set `src` to [`QueueFamily::External`] or [`QueueFamily::Foreign`]
3004/// and `dst` to [`QueueFamily::Explicit`] with wgpu's own family, obtained from
3005/// `vulkan::Device::queue_family_index`. To release it again, swap the two.
3006///
3007/// A queue family ownership transfer requires a matching barrier to be recorded
3008/// on *both* queues; wgpu-hal only records the barrier on its own queue, so the
3009/// owner of the other queue is responsible for recording the complementary one.
3010#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3011pub struct QueueFamilyOwnershipTransfer {
3012    /// The queue family that currently owns the image (`srcQueueFamilyIndex`).
3013    pub src: QueueFamily,
3014    /// The queue family that should own the image afterwards (`dstQueueFamilyIndex`).
3015    pub dst: QueueFamily,
3016}
3017
3018#[derive(Debug)]
3019pub struct TextureBarrier<'a, T: DynTexture + ?Sized> {
3020    pub texture: &'a T,
3021    pub range: wgt::ImageSubresourceRange,
3022    pub usage: StateTransition<wgt::TextureUses>,
3023    /// An optional Vulkan queue family ownership transfer to perform alongside
3024    /// the layout/access transition described by `usage`.
3025    ///
3026    /// This is honored only by the Vulkan backend; all other backends ignore
3027    /// it. Leave it as `None` for the common case where no ownership transfer
3028    /// is required. See [`QueueFamilyOwnershipTransfer`] for details.
3029    pub queue_family_ownership_transfer: Option<QueueFamilyOwnershipTransfer>,
3030}
3031
3032impl<'a, T: DynTexture + ?Sized> Clone for TextureBarrier<'a, T> {
3033    fn clone(&self) -> Self {
3034        Self {
3035            texture: self.texture,
3036            range: self.range,
3037            queue_family_ownership_transfer: self.queue_family_ownership_transfer,
3038            usage: self.usage.clone(),
3039        }
3040    }
3041}
3042
3043#[derive(Clone, Copy, Debug)]
3044pub struct BufferCopy {
3045    pub src_offset: wgt::BufferAddress,
3046    pub dst_offset: wgt::BufferAddress,
3047    pub size: wgt::BufferSize,
3048}
3049
3050#[derive(Clone, Debug)]
3051pub struct TextureCopyBase {
3052    pub mip_level: u32,
3053    pub array_layer: u32,
3054    /// Origin within a texture.
3055    /// Note: for 1D and 2D textures, Z must be 0.
3056    pub origin: wgt::Origin3d,
3057    pub aspect: FormatAspects,
3058}
3059
3060#[derive(Clone, Copy, Debug)]
3061pub struct CopyExtent {
3062    pub width: u32,
3063    pub height: u32,
3064    pub depth: u32,
3065}
3066
3067impl From<wgt::Extent3d> for CopyExtent {
3068    fn from(value: wgt::Extent3d) -> Self {
3069        let wgt::Extent3d {
3070            width,
3071            height,
3072            depth_or_array_layers,
3073        } = value;
3074        Self {
3075            width,
3076            height,
3077            depth: depth_or_array_layers,
3078        }
3079    }
3080}
3081
3082impl From<CopyExtent> for wgt::Extent3d {
3083    fn from(value: CopyExtent) -> Self {
3084        let CopyExtent {
3085            width,
3086            height,
3087            depth,
3088        } = value;
3089        Self {
3090            width,
3091            height,
3092            depth_or_array_layers: depth,
3093        }
3094    }
3095}
3096
3097#[derive(Clone, Debug)]
3098pub struct TextureCopy {
3099    pub src_base: TextureCopyBase,
3100    pub dst_base: TextureCopyBase,
3101    pub size: CopyExtent,
3102}
3103
3104#[derive(Clone, Debug)]
3105pub struct BufferTextureCopy {
3106    pub buffer_layout: wgt::TexelCopyBufferLayout,
3107    pub texture_base: TextureCopyBase,
3108    pub size: CopyExtent,
3109}
3110
3111#[derive(Clone, Debug)]
3112pub struct Attachment<'a, T: DynTextureView + ?Sized> {
3113    pub view: &'a T,
3114    /// Contains either a single mutating usage as a target,
3115    /// or a valid combination of read-only usages.
3116    pub usage: wgt::TextureUses,
3117}
3118
3119#[derive(Clone, Debug)]
3120pub struct ColorAttachment<'a, T: DynTextureView + ?Sized> {
3121    pub target: Attachment<'a, T>,
3122    pub depth_slice: Option<u32>,
3123    pub resolve_target: Option<Attachment<'a, T>>,
3124    pub ops: AttachmentOps,
3125    pub clear_value: wgt::Color,
3126}
3127
3128#[derive(Clone, Debug)]
3129pub struct DepthStencilAttachment<'a, T: DynTextureView + ?Sized> {
3130    pub target: Attachment<'a, T>,
3131    pub depth_ops: AttachmentOps,
3132    pub stencil_ops: AttachmentOps,
3133    pub depth_read_only: bool,
3134    pub stencil_read_only: bool,
3135    pub clear_value: (f32, u32),
3136}
3137
3138#[derive(Clone, Debug)]
3139pub struct PassTimestampWrites<'a, Q: DynQuerySet + ?Sized> {
3140    pub query_set: &'a Q,
3141    pub beginning_of_pass_write_index: Option<u32>,
3142    pub end_of_pass_write_index: Option<u32>,
3143}
3144
3145#[derive(Clone, Debug)]
3146pub struct RenderPassDescriptor<'a, Q: DynQuerySet + ?Sized, T: DynTextureView + ?Sized> {
3147    pub label: Label<'a>,
3148    pub extent: wgt::Extent3d,
3149    pub sample_count: u32,
3150    pub color_attachments: &'a [Option<ColorAttachment<'a, T>>],
3151    pub depth_stencil_attachment: Option<DepthStencilAttachment<'a, T>>,
3152    pub multiview_mask: Option<NonZeroU32>,
3153    pub timestamp_writes: Option<PassTimestampWrites<'a, Q>>,
3154    pub occlusion_query_set: Option<&'a Q>,
3155}
3156
3157#[derive(Clone, Debug)]
3158pub struct ComputePassDescriptor<'a, Q: DynQuerySet + ?Sized> {
3159    pub label: Label<'a>,
3160    pub timestamp_writes: Option<PassTimestampWrites<'a, Q>>,
3161}
3162
3163#[derive(Clone, Debug)]
3164pub struct RayTracingPassDescriptor<'a> {
3165    pub label: Label<'a>,
3166}
3167
3168#[cfg(test)]
3169mod tests {
3170    use super::*;
3171
3172    #[test]
3173    fn test_default_limits() {
3174        let limits = wgt::Limits::default();
3175        assert!(limits.max_bind_groups <= MAX_BIND_GROUPS as u32);
3176    }
3177}
3178
3179#[derive(Clone, Debug)]
3180pub struct AccelerationStructureDescriptor<'a> {
3181    pub label: Label<'a>,
3182    pub size: wgt::BufferAddress,
3183    pub format: AccelerationStructureFormat,
3184    /// Backends may allocate the structure as a short-lived resource, since it is
3185    /// usually replaced by its compacted copy.
3186    pub allow_compaction: bool,
3187}
3188
3189#[derive(Debug, Clone, Copy, Eq, PartialEq)]
3190pub enum AccelerationStructureFormat {
3191    TopLevel,
3192    BottomLevel,
3193}
3194
3195#[derive(Debug, Clone, Copy, Eq, PartialEq)]
3196pub enum AccelerationStructureBuildMode {
3197    Build,
3198    Update,
3199}
3200
3201/// Information of the required size for a corresponding entries struct (+ flags)
3202#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
3203pub struct AccelerationStructureBuildSizes {
3204    pub acceleration_structure_size: wgt::BufferAddress,
3205    pub update_scratch_size: wgt::BufferAddress,
3206    pub build_scratch_size: wgt::BufferAddress,
3207}
3208
3209/// Updates use source_acceleration_structure if present, else the update will be performed in place.
3210/// For updates, only the data is allowed to change (not the meta data or sizes).
3211#[derive(Clone, Debug)]
3212pub struct BuildAccelerationStructureDescriptor<
3213    'a,
3214    B: DynBuffer + ?Sized,
3215    A: DynAccelerationStructure + ?Sized,
3216> {
3217    pub entries: &'a AccelerationStructureEntries<'a, B>,
3218    pub mode: AccelerationStructureBuildMode,
3219    pub flags: AccelerationStructureBuildFlags,
3220    pub source_acceleration_structure: Option<&'a A>,
3221    pub destination_acceleration_structure: &'a A,
3222    pub scratch_buffer: &'a B,
3223    pub scratch_buffer_offset: wgt::BufferAddress,
3224}
3225
3226/// - All buffers, buffer addresses and offsets will be ignored.
3227/// - The build mode will be ignored.
3228/// - Reducing the amount of Instances, Triangle groups or AABB groups (or the number of Triangles/AABBs in corresponding groups),
3229///   may result in reduced size requirements.
3230/// - Any other change may result in a bigger or smaller size requirement.
3231#[derive(Clone, Debug)]
3232pub struct GetAccelerationStructureBuildSizesDescriptor<'a, B: DynBuffer + ?Sized> {
3233    pub entries: &'a AccelerationStructureEntries<'a, B>,
3234    pub flags: AccelerationStructureBuildFlags,
3235}
3236
3237/// Entries for a single descriptor
3238/// * `Instances` - Multiple instances for a top level acceleration structure
3239/// * `Triangles` - Multiple triangle meshes for a bottom level acceleration structure
3240/// * `AABBs` - List of list of axis aligned bounding boxes for a bottom level acceleration structure
3241#[derive(Debug)]
3242pub enum AccelerationStructureEntries<'a, B: DynBuffer + ?Sized> {
3243    Instances(AccelerationStructureInstances<'a, B>),
3244    Triangles(Vec<AccelerationStructureTriangles<'a, B>>),
3245    AABBs(Vec<AccelerationStructureAABBs<'a, B>>),
3246}
3247
3248/// * `first_vertex` - offset in the vertex buffer (as number of vertices)
3249/// * `indices` - optional index buffer with attributes
3250/// * `transform` - optional transform
3251#[derive(Clone, Debug)]
3252pub struct AccelerationStructureTriangles<'a, B: DynBuffer + ?Sized> {
3253    pub vertex_buffer: Option<&'a B>,
3254    pub vertex_format: wgt::VertexFormat,
3255    pub first_vertex: u32,
3256    pub vertex_count: u32,
3257    pub vertex_stride: wgt::BufferAddress,
3258    pub indices: Option<AccelerationStructureTriangleIndices<'a, B>>,
3259    pub transform: Option<AccelerationStructureTriangleTransform<'a, B>>,
3260    pub flags: AccelerationStructureGeometryFlags,
3261}
3262
3263/// * `offset` - offset in bytes
3264#[derive(Clone, Debug)]
3265pub struct AccelerationStructureAABBs<'a, B: DynBuffer + ?Sized> {
3266    pub buffer: Option<&'a B>,
3267    pub offset: u32,
3268    pub count: u32,
3269    pub stride: wgt::BufferAddress,
3270    pub flags: AccelerationStructureGeometryFlags,
3271}
3272
3273#[derive(Clone, Debug)]
3274pub struct AccelerationStructureCopy {
3275    pub copy_flags: wgt::AccelerationStructureCopy,
3276    pub type_flags: wgt::AccelerationStructureType,
3277}
3278
3279/// * `offset` - offset in bytes
3280#[derive(Clone, Debug)]
3281pub struct AccelerationStructureInstances<'a, B: DynBuffer + ?Sized> {
3282    pub buffer: Option<&'a B>,
3283    pub offset: u32,
3284    pub count: u32,
3285}
3286
3287/// * `offset` - offset in bytes
3288#[derive(Clone, Debug)]
3289pub struct AccelerationStructureTriangleIndices<'a, B: DynBuffer + ?Sized> {
3290    pub format: wgt::IndexFormat,
3291    pub buffer: Option<&'a B>,
3292    pub offset: u32,
3293    pub count: u32,
3294}
3295
3296/// * `offset` - offset in bytes
3297#[derive(Clone, Debug)]
3298pub struct AccelerationStructureTriangleTransform<'a, B: DynBuffer + ?Sized> {
3299    pub buffer: &'a B,
3300    pub offset: u32,
3301}
3302
3303pub use wgt::AccelerationStructureFlags as AccelerationStructureBuildFlags;
3304pub use wgt::AccelerationStructureGeometryFlags;
3305
3306bitflags::bitflags! {
3307    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3308    pub struct AccelerationStructureUses: u8 {
3309        // For blas used as input for tlas
3310        const BUILD_INPUT = 1 << 0;
3311        // Target for acceleration structure build
3312        const BUILD_OUTPUT = 1 << 1;
3313        // Tlas used in a shader
3314        const SHADER_INPUT = 1 << 2;
3315        // Blas used to query compacted size
3316        const QUERY_INPUT = 1 << 3;
3317        // BLAS used as a src for a copy operation
3318        const COPY_SRC = 1 << 4;
3319        // BLAS used as a dst for a copy operation
3320        const COPY_DST = 1 << 5;
3321    }
3322}
3323
3324#[derive(Debug, Clone)]
3325pub struct AccelerationStructureBarrier {
3326    pub usage: StateTransition<AccelerationStructureUses>,
3327}
3328
3329#[derive(Debug, Copy, Clone)]
3330pub struct TlasInstance {
3331    pub transform: [f32; 12],
3332    pub custom_data: u32,
3333    pub mask: u8,
3334    pub flags: wgt::AccelerationStructureInstanceFlags,
3335    pub blas_address: u64,
3336    /// The offset for the index into the intersection hit
3337    /// group calculation. Number is in hit groups.
3338    pub pipeline_intersection_data_offset: u32,
3339}
3340
3341#[cfg(dx12)]
3342#[derive(Debug)]
3343pub enum D3D12ExposeAdapterResult {
3344    CreateDeviceError(dx12::CreateDeviceError),
3345    UnknownFeatureLevel(i32),
3346    ResourceBindingTier2Requirement,
3347    ShaderModel6Requirement,
3348    Success(dx12::FeatureLevel, dx12::ShaderModel),
3349}
3350
3351/// Pluggable telemetry, mainly to be used by Firefox.
3352#[derive(Debug, Clone, Copy)]
3353pub struct Telemetry {
3354    #[cfg(dx12)]
3355    pub d3d12_expose_adapter: fn(
3356        desc: &windows::Win32::Graphics::Dxgi::DXGI_ADAPTER_DESC2,
3357        driver_version: Result<[u16; 4], windows_core::HRESULT>,
3358        result: D3D12ExposeAdapterResult,
3359    ),
3360}
3361
3362#[derive(Debug)]
3363pub struct PipelineGroupData<'a, B: DynBuffer + ?Sized> {
3364    pub buffer: &'a B,
3365    pub offset: wgt::BufferAddress,
3366    pub stride: u64,
3367    pub count: u64,
3368}