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;
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
1420/// Encoder and allocation pool for `CommandBuffer`s.
1421///
1422/// A `CommandEncoder` not only constructs `CommandBuffer`s but also
1423/// acts as the allocation pool that owns the buffers' underlying
1424/// storage. Thus, `CommandBuffer`s must not outlive the
1425/// `CommandEncoder` that created them.
1426///
1427/// The life cycle of a `CommandBuffer` is as follows:
1428///
1429/// - Call [`Device::create_command_encoder`] to create a new
1430/// `CommandEncoder`, in the "closed" state.
1431///
1432/// - Call `begin_encoding` on a closed `CommandEncoder` to begin
1433/// recording commands. This puts the `CommandEncoder` in the
1434/// "recording" state.
1435///
1436/// - Call methods like `copy_buffer_to_buffer`, `begin_render_pass`,
1437/// etc. on a "recording" `CommandEncoder` to add commands to the
1438/// list. (If an error occurs, you must call `discard_encoding`; see
1439/// below.)
1440///
1441/// - Call `end_encoding` on a recording `CommandEncoder` to close the
1442/// encoder and construct a fresh `CommandBuffer` consisting of the
1443/// list of commands recorded up to that point.
1444///
1445/// - Call `discard_encoding` on a recording `CommandEncoder` to drop
1446/// the commands recorded thus far and close the encoder. This is
1447/// the only safe thing to do on a `CommandEncoder` if an error has
1448/// occurred while recording commands.
1449///
1450/// - Call `reset_all` on a closed `CommandEncoder`, passing all the
1451/// live `CommandBuffers` built from it. All the `CommandBuffer`s
1452/// are destroyed, and their resources are freed.
1453///
1454/// # Safety
1455///
1456/// - The `CommandEncoder` must be in the states described above to
1457/// make the given calls.
1458///
1459/// - A `CommandBuffer` that has been submitted for execution on the
1460/// GPU must live until its execution is complete.
1461///
1462/// - A `CommandBuffer` must not outlive the `CommandEncoder` that
1463/// built it.
1464///
1465/// It is the user's responsibility to meet this requirements. This
1466/// allows `CommandEncoder` implementations to keep their state
1467/// tracking to a minimum.
1468pub trait CommandEncoder: WasmNotSendSync + fmt::Debug {
1469 type A: Api;
1470
1471 /// Begin encoding a new command buffer.
1472 ///
1473 /// This puts this `CommandEncoder` in the "recording" state.
1474 ///
1475 /// # Safety
1476 ///
1477 /// This `CommandEncoder` must be in the "closed" state.
1478 unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError>;
1479
1480 /// Discard the command list under construction.
1481 ///
1482 /// If an error has occurred while recording commands, this
1483 /// is the only safe thing to do with the encoder.
1484 ///
1485 /// This puts this `CommandEncoder` in the "closed" state.
1486 ///
1487 /// # Safety
1488 ///
1489 /// This `CommandEncoder` must be in the "recording" state.
1490 ///
1491 /// Callers must not assume that implementations of this
1492 /// function are idempotent, and thus should not call it
1493 /// multiple times in a row.
1494 unsafe fn discard_encoding(&mut self);
1495
1496 /// Return a fresh [`CommandBuffer`] holding the recorded commands.
1497 ///
1498 /// The returned [`CommandBuffer`] holds all the commands recorded
1499 /// on this `CommandEncoder` since the last call to
1500 /// [`begin_encoding`].
1501 ///
1502 /// This puts this `CommandEncoder` in the "closed" state.
1503 ///
1504 /// # Safety
1505 ///
1506 /// This `CommandEncoder` must be in the "recording" state.
1507 ///
1508 /// The returned [`CommandBuffer`] must not outlive this
1509 /// `CommandEncoder`. Implementations are allowed to build
1510 /// `CommandBuffer`s that depend on storage owned by this
1511 /// `CommandEncoder`.
1512 ///
1513 /// [`CommandBuffer`]: Api::CommandBuffer
1514 /// [`begin_encoding`]: CommandEncoder::begin_encoding
1515 unsafe fn end_encoding(&mut self) -> Result<<Self::A as Api>::CommandBuffer, DeviceError>;
1516
1517 /// Reclaim all resources belonging to this `CommandEncoder`.
1518 ///
1519 /// # Safety
1520 ///
1521 /// This `CommandEncoder` must be in the "closed" state.
1522 ///
1523 /// The `command_buffers` iterator must produce all the live
1524 /// [`CommandBuffer`]s built using this `CommandEncoder` --- that
1525 /// is, every extant `CommandBuffer` returned from `end_encoding`.
1526 ///
1527 /// [`CommandBuffer`]: Api::CommandBuffer
1528 unsafe fn reset_all<I>(&mut self, command_buffers: I)
1529 where
1530 I: Iterator<Item = <Self::A as Api>::CommandBuffer>;
1531
1532 unsafe fn transition_buffers<'a, T>(&mut self, barriers: T)
1533 where
1534 T: Iterator<Item = BufferBarrier<'a, <Self::A as Api>::Buffer>>;
1535
1536 unsafe fn transition_textures<'a, T>(&mut self, barriers: T)
1537 where
1538 T: Iterator<Item = TextureBarrier<'a, <Self::A as Api>::Texture>>;
1539
1540 // copy operations
1541
1542 unsafe fn clear_buffer(&mut self, buffer: &<Self::A as Api>::Buffer, range: MemoryRange);
1543
1544 unsafe fn copy_buffer_to_buffer<T>(
1545 &mut self,
1546 src: &<Self::A as Api>::Buffer,
1547 dst: &<Self::A as Api>::Buffer,
1548 regions: T,
1549 ) where
1550 T: Iterator<Item = BufferCopy>;
1551
1552 /// Copy from an external image to an internal texture.
1553 /// Works with a single array layer.
1554 /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`.
1555 /// Note: the copy extent is in physical size (rounded to the block size)
1556 #[cfg(webgl)]
1557 unsafe fn copy_external_image_to_texture<T>(
1558 &mut self,
1559 src: &wgt::CopyExternalImageSourceInfo,
1560 dst: &<Self::A as Api>::Texture,
1561 dst_premultiplication: bool,
1562 regions: T,
1563 ) where
1564 T: Iterator<Item = TextureCopy>;
1565
1566 /// Copy from one texture to another.
1567 /// Works with a single array layer.
1568 /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`.
1569 /// Note: the copy extent is in physical size (rounded to the block size)
1570 unsafe fn copy_texture_to_texture<T>(
1571 &mut self,
1572 src: &<Self::A as Api>::Texture,
1573 src_usage: wgt::TextureUses,
1574 dst: &<Self::A as Api>::Texture,
1575 regions: T,
1576 ) where
1577 T: Iterator<Item = TextureCopy>;
1578
1579 /// Copy from buffer to texture.
1580 /// Works with a single array layer.
1581 /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`.
1582 /// Note: the copy extent is in physical size (rounded to the block size)
1583 unsafe fn copy_buffer_to_texture<T>(
1584 &mut self,
1585 src: &<Self::A as Api>::Buffer,
1586 dst: &<Self::A as Api>::Texture,
1587 regions: T,
1588 ) where
1589 T: Iterator<Item = BufferTextureCopy>;
1590
1591 /// Copy from texture to buffer.
1592 /// Works with a single array layer.
1593 /// Note: the copy extent is in physical size (rounded to the block size)
1594 unsafe fn copy_texture_to_buffer<T>(
1595 &mut self,
1596 src: &<Self::A as Api>::Texture,
1597 src_usage: wgt::TextureUses,
1598 dst: &<Self::A as Api>::Buffer,
1599 regions: T,
1600 ) where
1601 T: Iterator<Item = BufferTextureCopy>;
1602
1603 unsafe fn copy_acceleration_structure_to_acceleration_structure(
1604 &mut self,
1605 src: &<Self::A as Api>::AccelerationStructure,
1606 dst: &<Self::A as Api>::AccelerationStructure,
1607 copy: wgt::AccelerationStructureCopy,
1608 );
1609 // pass common
1610
1611 /// Sets the bind group at `index` to `group`.
1612 ///
1613 /// If this is not the first call to `set_bind_group` within the current
1614 /// render or compute pass:
1615 ///
1616 /// - If `layout` contains `n` bind group layouts, then any previously set
1617 /// bind groups at indices `n` or higher are cleared.
1618 ///
1619 /// - If the first `m` bind group layouts of `layout` are equal to those of
1620 /// the previously passed layout, but no more, then any previously set
1621 /// bind groups at indices `m` or higher are cleared.
1622 ///
1623 /// It follows from the above that passing the same layout as before doesn't
1624 /// clear any bind groups.
1625 ///
1626 /// # Safety
1627 ///
1628 /// - This [`CommandEncoder`] must be within a render or compute pass.
1629 ///
1630 /// - `index` must be the valid index of some bind group layout in `layout`.
1631 /// Call this the "relevant bind group layout".
1632 ///
1633 /// - The layout of `group` must be equal to the relevant bind group layout.
1634 ///
1635 /// - The length of `dynamic_offsets` must match the number of buffer
1636 /// bindings [with dynamic offsets][hdo] in the relevant bind group
1637 /// layout.
1638 ///
1639 /// - If those buffer bindings are ordered by increasing [`binding` number]
1640 /// and paired with elements from `dynamic_offsets`, then each offset must
1641 /// be a valid offset for the binding's corresponding buffer in `group`.
1642 ///
1643 /// [hdo]: wgt::BindingType::Buffer::has_dynamic_offset
1644 /// [`binding` number]: wgt::BindGroupLayoutEntry::binding
1645 unsafe fn set_bind_group(
1646 &mut self,
1647 layout: &<Self::A as Api>::PipelineLayout,
1648 index: u32,
1649 group: &<Self::A as Api>::BindGroup,
1650 dynamic_offsets: &[wgt::DynamicOffset],
1651 );
1652
1653 /// Sets a range in immediate data.
1654 ///
1655 /// IMPORTANT: while the data is passed as words, the offset is in bytes!
1656 ///
1657 /// # Safety
1658 ///
1659 /// - `offset_bytes` must be a multiple of 4.
1660 /// - The range of immediates written must be valid for the pipeline layout at draw time.
1661 unsafe fn set_immediates(
1662 &mut self,
1663 layout: &<Self::A as Api>::PipelineLayout,
1664 offset_bytes: u32,
1665 data: &[u32],
1666 );
1667
1668 unsafe fn insert_debug_marker(&mut self, label: &str);
1669 unsafe fn begin_debug_marker(&mut self, group_label: &str);
1670 unsafe fn end_debug_marker(&mut self);
1671
1672 // queries
1673
1674 /// # Safety:
1675 ///
1676 /// - If `set` is an occlusion query set, it must be the same one as used in the [`RenderPassDescriptor::occlusion_query_set`] parameter.
1677 unsafe fn begin_query(&mut self, set: &<Self::A as Api>::QuerySet, index: u32);
1678 /// # Safety:
1679 ///
1680 /// - If `set` is an occlusion query set, it must be the same one as used in the [`RenderPassDescriptor::occlusion_query_set`] parameter.
1681 unsafe fn end_query(&mut self, set: &<Self::A as Api>::QuerySet, index: u32);
1682 unsafe fn write_timestamp(&mut self, set: &<Self::A as Api>::QuerySet, index: u32);
1683 unsafe fn reset_queries(&mut self, set: &<Self::A as Api>::QuerySet, range: Range<u32>);
1684 unsafe fn copy_query_results(
1685 &mut self,
1686 set: &<Self::A as Api>::QuerySet,
1687 range: Range<u32>,
1688 buffer: &<Self::A as Api>::Buffer,
1689 offset: wgt::BufferAddress,
1690 stride: wgt::BufferSize,
1691 );
1692
1693 // render passes
1694
1695 /// Begin a new render pass, clearing all active bindings.
1696 ///
1697 /// This clears any bindings established by the following calls:
1698 ///
1699 /// - [`set_bind_group`](CommandEncoder::set_bind_group)
1700 /// - [`set_immediates`](CommandEncoder::set_immediates)
1701 /// - [`begin_query`](CommandEncoder::begin_query)
1702 /// - [`set_render_pipeline`](CommandEncoder::set_render_pipeline)
1703 /// - [`set_index_buffer`](CommandEncoder::set_index_buffer)
1704 /// - [`set_vertex_buffer`](CommandEncoder::set_vertex_buffer)
1705 ///
1706 /// # Safety
1707 ///
1708 /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed
1709 /// by a call to [`end_render_pass`].
1710 ///
1711 /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed
1712 /// by a call to [`end_compute_pass`].
1713 ///
1714 /// - All prior calls to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] must have been followed
1715 /// by a call to [`end_ray_tracing_pass`].
1716 ///
1717 /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1718 /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1719 /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass
1720 /// [`end_render_pass`]: CommandEncoder::end_render_pass
1721 /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1722 /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass
1723 unsafe fn begin_render_pass(
1724 &mut self,
1725 desc: &RenderPassDescriptor<<Self::A as Api>::QuerySet, <Self::A as Api>::TextureView>,
1726 ) -> Result<(), DeviceError>;
1727
1728 /// End the current render pass.
1729 ///
1730 /// # Safety
1731 ///
1732 /// - There must have been a prior call to [`begin_render_pass`] on this [`CommandEncoder`]
1733 /// that has not been followed by a call to [`end_render_pass`].
1734 ///
1735 /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1736 /// [`end_render_pass`]: CommandEncoder::end_render_pass
1737 unsafe fn end_render_pass(&mut self);
1738
1739 unsafe fn set_render_pipeline(&mut self, pipeline: &<Self::A as Api>::RenderPipeline);
1740
1741 /// Register an index buffer binding.
1742 ///
1743 /// The binding offset must be 4B-aligned and strictly less than the buffer
1744 /// size. On some backends, the binding size is ignored. This means that
1745 /// zero-size bindings must be simulated by binding a region of zeros
1746 /// spanning from the provided offset to the end of the buffer. See
1747 /// [`CommandEncoder::set_vertex_buffer`] for more detail.
1748 unsafe fn set_index_buffer<'a>(
1749 &mut self,
1750 binding: BufferBinding<'a, <Self::A as Api>::Buffer, wgt::BufferAddress>,
1751 format: wgt::IndexFormat,
1752 );
1753 /// Register a vertex buffer binding.
1754 ///
1755 /// The binding offset must be 4B-aligned and strictly less than the buffer
1756 /// size. On some backends, the binding size is ignored. This means that
1757 /// zero-size bindings must be simulated by binding a region of zeros
1758 /// spanning from the provided offset to the end of the buffer.
1759 ///
1760 /// These restrictions arise from Vulkan's `vkCmdBindVertexBuffers` and
1761 /// `vkCmdBindIndexBuffer`, which:
1762 ///
1763 /// 1. Do not support specifying the size of the binding.
1764 /// 2. Require that the binding offset is strictly less than the buffer size.
1765 ///
1766 /// A read at any offset from a zero-size binding is out-of-bounds, and
1767 /// should return zero. Because the binding size is not respected, this
1768 /// means there may not be non-zero data between the binding offset and
1769 /// the end of the buffer.
1770 ///
1771 /// Because the binding offset must be strictly less than the buffer size,
1772 /// supporting zero-size bindings requires zero padding at the end of the
1773 /// buffer.
1774 unsafe fn set_vertex_buffer<'a>(
1775 &mut self,
1776 index: u32,
1777 binding: BufferBinding<'a, <Self::A as Api>::Buffer, wgt::BufferAddress>,
1778 );
1779 unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>);
1780 unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>);
1781 unsafe fn set_stencil_reference(&mut self, value: u32);
1782 unsafe fn set_blend_constants(&mut self, color: &[f32; 4]);
1783
1784 unsafe fn draw(
1785 &mut self,
1786 first_vertex: u32,
1787 vertex_count: u32,
1788 first_instance: u32,
1789 instance_count: u32,
1790 );
1791 unsafe fn draw_indexed(
1792 &mut self,
1793 first_index: u32,
1794 index_count: u32,
1795 base_vertex: i32,
1796 first_instance: u32,
1797 instance_count: u32,
1798 );
1799 /// # Safety
1800 ///
1801 /// - If `draw_count > 1`, see the deferred-work obligation on
1802 /// [`encode_deferred_multi_draws`](CommandEncoder::encode_deferred_multi_draws).
1803 unsafe fn draw_indirect(
1804 &mut self,
1805 buffer: &<Self::A as Api>::Buffer,
1806 offset: wgt::BufferAddress,
1807 draw_count: u32,
1808 );
1809 /// # Safety
1810 ///
1811 /// - If `draw_count > 1`, see the deferred-work obligation on
1812 /// [`encode_deferred_multi_draws`](CommandEncoder::encode_deferred_multi_draws).
1813 unsafe fn draw_indexed_indirect(
1814 &mut self,
1815 buffer: &<Self::A as Api>::Buffer,
1816 offset: wgt::BufferAddress,
1817 draw_count: u32,
1818 );
1819 unsafe fn draw_indirect_count(
1820 &mut self,
1821 buffer: &<Self::A as Api>::Buffer,
1822 offset: wgt::BufferAddress,
1823 count_buffer: &<Self::A as Api>::Buffer,
1824 count_offset: wgt::BufferAddress,
1825 max_count: u32,
1826 );
1827 unsafe fn draw_indexed_indirect_count(
1828 &mut self,
1829 buffer: &<Self::A as Api>::Buffer,
1830 offset: wgt::BufferAddress,
1831 count_buffer: &<Self::A as Api>::Buffer,
1832 count_offset: wgt::BufferAddress,
1833 max_count: u32,
1834 );
1835 unsafe fn draw_mesh_tasks(
1836 &mut self,
1837 group_count_x: u32,
1838 group_count_y: u32,
1839 group_count_z: u32,
1840 );
1841 /// # Safety
1842 ///
1843 /// - If `draw_count > 1`, see the deferred-work obligation on
1844 /// [`encode_deferred_multi_draws`](CommandEncoder::encode_deferred_multi_draws).
1845 unsafe fn draw_mesh_tasks_indirect(
1846 &mut self,
1847 buffer: &<Self::A as Api>::Buffer,
1848 offset: wgt::BufferAddress,
1849 draw_count: u32,
1850 );
1851 unsafe fn draw_mesh_tasks_indirect_count(
1852 &mut self,
1853 buffer: &<Self::A as Api>::Buffer,
1854 offset: wgt::BufferAddress,
1855 count_buffer: &<Self::A as Api>::Buffer,
1856 count_offset: wgt::BufferAddress,
1857 max_count: u32,
1858 );
1859
1860 /// Record any deferred setup work for indirect multi-draws of the most
1861 /// recently ended render pass into the current command buffer.
1862 ///
1863 /// Some backends lower [`draw_indirect`]-family calls with `draw_count > 1`
1864 /// to GPU-generated command lists (e.g. Metal indirect command buffers).
1865 /// The generation work must execute *before* the render pass that consumes
1866 /// it, but the pass contents are only known once the pass has been
1867 /// recorded, so such backends queue the generation work at draw-record time
1868 /// and encode it when this method is called.
1869 ///
1870 /// The default implementation does nothing; backends that don't defer any
1871 /// multi-draw work don't need to override it.
1872 ///
1873 /// # Safety
1874 ///
1875 /// - Must be called outside of a render, compute, or ray-tracing pass.
1876 /// - Between the [`end_render_pass`] for a pass that recorded indirect
1877 /// multi-draws and the submission of that pass's command buffer, this
1878 /// method must be called on this [`CommandEncoder`], while recording a
1879 /// command buffer that the queue will execute *before* the pass's
1880 /// command buffer. One call covers every pass ended since the previous
1881 /// call.
1882 /// - The command buffer recorded here must not be reset until the pass's
1883 /// command buffer has completed.
1884 /// - Any indirect (or count) buffer passed to a [`draw_indirect`]-family
1885 /// call in that pass must not be written between that call and the
1886 /// execution of the command buffer recorded here, other than by wgpu's
1887 /// own indirect validation.
1888 ///
1889 /// [`draw_indirect`]: CommandEncoder::draw_indirect
1890 /// [`end_render_pass`]: CommandEncoder::end_render_pass
1891 unsafe fn encode_deferred_multi_draws(&mut self) {}
1892
1893 // compute passes
1894
1895 /// Begin a new compute pass, clearing all active bindings.
1896 ///
1897 /// This clears any bindings established by the following calls:
1898 ///
1899 /// - [`set_bind_group`](CommandEncoder::set_bind_group)
1900 /// - [`set_immediates`](CommandEncoder::set_immediates)
1901 /// - [`begin_query`](CommandEncoder::begin_query)
1902 /// - [`set_compute_pipeline`](CommandEncoder::set_compute_pipeline)
1903 ///
1904 /// # Safety
1905 ///
1906 /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed
1907 /// by a call to [`end_render_pass`].
1908 ///
1909 /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed
1910 /// by a call to [`end_compute_pass`].
1911 ///
1912 /// - All prior calls to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] must have been followed
1913 /// by a call to [`end_ray_tracing_pass`].
1914 ///
1915 /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1916 /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1917 /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass
1918 /// [`end_render_pass`]: CommandEncoder::end_render_pass
1919 /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1920 /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass
1921 unsafe fn begin_compute_pass(
1922 &mut self,
1923 desc: &ComputePassDescriptor<<Self::A as Api>::QuerySet>,
1924 );
1925
1926 /// End the current compute pass.
1927 ///
1928 /// # Safety
1929 ///
1930 /// - There must have been a prior call to [`begin_compute_pass`] on this [`CommandEncoder`]
1931 /// that has not been followed by a call to [`end_compute_pass`].
1932 ///
1933 /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1934 /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1935 unsafe fn end_compute_pass(&mut self);
1936
1937 unsafe fn set_compute_pipeline(&mut self, pipeline: &<Self::A as Api>::ComputePipeline);
1938
1939 unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]);
1940 unsafe fn dispatch_workgroups_indirect(
1941 &mut self,
1942 buffer: &<Self::A as Api>::Buffer,
1943 offset: wgt::BufferAddress,
1944 );
1945
1946 /// Begin a new ray tracing pass, clearing all active bindings.
1947 ///
1948 /// This clears any bindings established by the following calls:
1949 ///
1950 /// - [`set_bind_group`](CommandEncoder::set_bind_group)
1951 /// - [`set_immediates`](CommandEncoder::set_immediates)
1952 /// - [`begin_query`](CommandEncoder::begin_query)
1953 /// - [`set_ray_tracing_pipeline`](CommandEncoder::set_compute_pipeline)
1954 ///
1955 /// # Safety
1956 ///
1957 /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed
1958 /// by a call to [`end_render_pass`].
1959 ///
1960 /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed
1961 /// by a call to [`end_compute_pass`].
1962 ///
1963 /// - All prior calls to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] must have been followed
1964 /// by a call to [`end_ray_tracing_pass`].
1965 ///
1966 /// [`begin_render_pass`]: CommandEncoder::begin_render_pass
1967 /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass
1968 /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass
1969 /// [`end_render_pass`]: CommandEncoder::end_render_pass
1970 /// [`end_compute_pass`]: CommandEncoder::end_compute_pass
1971 /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass
1972 unsafe fn begin_ray_tracing_pass(&mut self, desc: &RayTracingPassDescriptor);
1973
1974 /// End the current compute pass.
1975 ///
1976 /// # Safety
1977 ///
1978 /// - There must have been a prior call to [`begin_ray_tracing_pass`] on this [`CommandEncoder`]
1979 /// that has not been followed by a call to [`end_ray_tracing_pass`].
1980 ///
1981 /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass
1982 /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass
1983 unsafe fn end_ray_tracing_pass(&mut self);
1984
1985 /// # Safety
1986 ///
1987 /// - Pipeline must not be destroyed
1988 unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &<Self::A as Api>::RayTracingPipeline);
1989
1990 unsafe fn trace_rays<'a>(
1991 &mut self,
1992 count: [u32; 3],
1993 ray_generation_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>,
1994 miss_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>,
1995 intersection_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>,
1996 );
1997
1998 /// To get the required sizes for the buffer allocations use `get_acceleration_structure_build_sizes` per descriptor
1999 /// All buffers must be synchronized externally
2000 /// All buffer regions, which are written to may only be passed once per function call,
2001 /// with the exception of updates in the same descriptor.
2002 /// Consequences of this limitation:
2003 /// - scratch buffers need to be unique
2004 /// - a tlas can't be build in the same call with a blas it contains
2005 unsafe fn build_acceleration_structures<'a, T>(
2006 &mut self,
2007 descriptor_count: u32,
2008 descriptors: T,
2009 ) where
2010 Self::A: 'a,
2011 T: IntoIterator<
2012 Item = BuildAccelerationStructureDescriptor<
2013 'a,
2014 <Self::A as Api>::Buffer,
2015 <Self::A as Api>::AccelerationStructure,
2016 >,
2017 >;
2018 unsafe fn place_acceleration_structure_barrier(
2019 &mut self,
2020 barrier: AccelerationStructureBarrier,
2021 );
2022 // modeled off dx12, because this is able to be polyfilled in vulkan as opposed to the other way round
2023 unsafe fn read_acceleration_structure_compact_size(
2024 &mut self,
2025 acceleration_structure: &<Self::A as Api>::AccelerationStructure,
2026 buf: &<Self::A as Api>::Buffer,
2027 );
2028 unsafe fn set_acceleration_structure_dependencies(
2029 command_buffers: &[&<Self::A as Api>::CommandBuffer],
2030 dependencies: &[&<Self::A as Api>::AccelerationStructure],
2031 );
2032}
2033
2034bitflags!(
2035 /// Pipeline layout creation flags.
2036 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2037 pub struct PipelineLayoutFlags: u32 {
2038 /// D3D12: Add support for `first_vertex` and `first_instance` builtins
2039 /// via immediates for direct execution.
2040 const FIRST_VERTEX_INSTANCE = 1 << 0;
2041 /// D3D12: Add support for `num_workgroups` builtins via immediates
2042 /// for direct execution.
2043 const NUM_WORK_GROUPS = 1 << 1;
2044 /// D3D12: Add support for the builtins that the other flags enable for
2045 /// indirect execution.
2046 const INDIRECT_BUILTIN_UPDATE = 1 << 2;
2047 }
2048);
2049
2050bitflags!(
2051 /// Pipeline layout creation flags.
2052 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2053 pub struct BindGroupLayoutFlags: u32 {
2054 /// Allows for bind group binding arrays to be shorter than the array in the BGL.
2055 const PARTIALLY_BOUND = 1 << 0;
2056 }
2057);
2058
2059bitflags!(
2060 /// Texture format capability flags.
2061 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2062 pub struct TextureFormatCapabilities: u32 {
2063 /// Format can be sampled.
2064 const SAMPLED = 1 << 0;
2065 /// Format can be sampled with a linear sampler.
2066 const SAMPLED_LINEAR = 1 << 1;
2067 /// Format can be sampled with a min/max reduction sampler.
2068 const SAMPLED_MINMAX = 1 << 2;
2069
2070 /// Format can be used as storage with read-only access.
2071 const STORAGE_READ_ONLY = 1 << 3;
2072 /// Format can be used as storage with write-only access.
2073 const STORAGE_WRITE_ONLY = 1 << 4;
2074 /// Format can be used as storage with both read and write access.
2075 const STORAGE_READ_WRITE = 1 << 5;
2076 /// Format can be used as storage with atomics.
2077 const STORAGE_ATOMIC = 1 << 6;
2078
2079 /// Format can be used as color and input attachment.
2080 const COLOR_ATTACHMENT = 1 << 7;
2081 /// Format can be used as color (with blending) and input attachment.
2082 const COLOR_ATTACHMENT_BLEND = 1 << 8;
2083 /// Format can be used as depth-stencil and input attachment.
2084 const DEPTH_STENCIL_ATTACHMENT = 1 << 9;
2085
2086 /// Format can be multisampled by x2.
2087 const MULTISAMPLE_X2 = 1 << 10;
2088 /// Format can be multisampled by x4.
2089 const MULTISAMPLE_X4 = 1 << 11;
2090 /// Format can be multisampled by x8.
2091 const MULTISAMPLE_X8 = 1 << 12;
2092 /// Format can be multisampled by x16.
2093 const MULTISAMPLE_X16 = 1 << 13;
2094
2095 /// Format can be used for render pass resolve targets.
2096 const MULTISAMPLE_RESOLVE = 1 << 14;
2097
2098 /// Format can be copied from.
2099 const COPY_SRC = 1 << 15;
2100 /// Format can be copied to.
2101 const COPY_DST = 1 << 16;
2102 }
2103);
2104
2105#[cfg(any(metal, vulkan))]
2106impl TextureFormatCapabilities {
2107 /// Capabilities that may be offered by multi-planar texture formats. It is generally
2108 /// not possible to operate on a multi-planar texture as a whole. Presence of these
2109 /// capabilities on a multi-planar format signifies that plane views support the
2110 /// indicated usage.
2111 ///
2112 /// This constant omits `COPY_SRC` and `COPY_DST` because they are handled separately
2113 /// in the code that uses it.
2114 pub(crate) const VALID_FOR_MULTI_PLANAR: Self = Self::empty()
2115 .union(Self::SAMPLED)
2116 .union(Self::SAMPLED_LINEAR)
2117 .union(Self::COLOR_ATTACHMENT)
2118 .union(Self::COLOR_ATTACHMENT_BLEND);
2119}
2120
2121bitflags!(
2122 /// Texture format capability flags.
2123 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2124 pub struct FormatAspects: u8 {
2125 const COLOR = 1 << 0;
2126 const DEPTH = 1 << 1;
2127 const STENCIL = 1 << 2;
2128 const PLANE_0 = 1 << 3;
2129 const PLANE_1 = 1 << 4;
2130 const PLANE_2 = 1 << 5;
2131
2132 const DEPTH_STENCIL = Self::DEPTH.bits() | Self::STENCIL.bits();
2133 }
2134);
2135
2136impl FormatAspects {
2137 /// Computes a [`FormatAspects`] mask from a [`wgt::TextureFormat`] and [`wgt::TextureAspect`].
2138 ///
2139 /// When called from `wgpu-core`, additional validation of the return value is typically
2140 /// required:
2141 ///
2142 /// - This function returns an empty mask, if `aspect` does not identify any
2143 /// valid aspect(s) of `format`.
2144 /// - This function returns a mask of all valid aspects, if `aspect` is
2145 /// [`wgt::TextureAspect::All`], but some texture operations do not
2146 /// support that.
2147 pub fn new(format: wgt::TextureFormat, aspect: wgt::TextureAspect) -> Self {
2148 let aspect_mask = match aspect {
2149 wgt::TextureAspect::All => Self::all(),
2150 wgt::TextureAspect::DepthOnly => Self::DEPTH,
2151 wgt::TextureAspect::StencilOnly => Self::STENCIL,
2152 wgt::TextureAspect::Plane0 => Self::PLANE_0,
2153 wgt::TextureAspect::Plane1 => Self::PLANE_1,
2154 wgt::TextureAspect::Plane2 => Self::PLANE_2,
2155 };
2156 Self::from(format) & aspect_mask
2157 }
2158
2159 /// Returns `true` if only one flag is set
2160 pub fn is_one(&self) -> bool {
2161 self.bits().is_power_of_two()
2162 }
2163
2164 pub fn map(&self) -> wgt::TextureAspect {
2165 match *self {
2166 Self::COLOR => wgt::TextureAspect::All,
2167 Self::DEPTH => wgt::TextureAspect::DepthOnly,
2168 Self::STENCIL => wgt::TextureAspect::StencilOnly,
2169 Self::PLANE_0 => wgt::TextureAspect::Plane0,
2170 Self::PLANE_1 => wgt::TextureAspect::Plane1,
2171 Self::PLANE_2 => wgt::TextureAspect::Plane2,
2172 _ => unreachable!(),
2173 }
2174 }
2175}
2176
2177impl From<wgt::TextureFormat> for FormatAspects {
2178 fn from(format: wgt::TextureFormat) -> Self {
2179 match format {
2180 wgt::TextureFormat::Stencil8 => Self::STENCIL,
2181 wgt::TextureFormat::Depth16Unorm
2182 | wgt::TextureFormat::Depth32Float
2183 | wgt::TextureFormat::Depth24Plus => Self::DEPTH,
2184 wgt::TextureFormat::Depth32FloatStencil8 | wgt::TextureFormat::Depth24PlusStencil8 => {
2185 Self::DEPTH_STENCIL
2186 }
2187 wgt::TextureFormat::NV12 | wgt::TextureFormat::P010 => Self::PLANE_0 | Self::PLANE_1,
2188 _ => Self::COLOR,
2189 }
2190 }
2191}
2192
2193bitflags!(
2194 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2195 pub struct MemoryFlags: u32 {
2196 /// The resource is short-lived and may be placed in a separate memory pool.
2197 const TRANSIENT = 1 << 0;
2198 const PREFER_COHERENT = 1 << 1;
2199 }
2200);
2201
2202bitflags!(
2203 /// Attachment load and store operations.
2204 ///
2205 /// There must be at least one flag from the LOAD group and one from the STORE group set.
2206 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2207 pub struct AttachmentOps: u8 {
2208 /// Load the existing contents of the attachment.
2209 const LOAD = 1 << 0;
2210 /// Clear the attachment to a specified value.
2211 const LOAD_CLEAR = 1 << 1;
2212 /// The contents of the attachment are undefined.
2213 const LOAD_DONT_CARE = 1 << 2;
2214 /// Store the contents of the attachment.
2215 const STORE = 1 << 3;
2216 /// The contents of the attachment are undefined after the pass.
2217 const STORE_DISCARD = 1 << 4;
2218 }
2219);
2220
2221#[derive(Debug)]
2222pub struct InstanceDescriptor<'a> {
2223 pub name: &'a str,
2224 pub flags: wgt::InstanceFlags,
2225 pub memory_budget_thresholds: wgt::MemoryBudgetThresholds,
2226 pub backend_options: wgt::BackendOptions,
2227 pub telemetry: Option<Telemetry>,
2228 /// This is a borrow because the surrounding `core::Instance` keeps the owned display handle
2229 /// alive already.
2230 pub display: Option<DisplayHandle<'a>>,
2231}
2232
2233#[derive(Clone, Debug)]
2234pub struct Alignments {
2235 /// The alignment of the start of the buffer used as a GPU copy source.
2236 pub buffer_copy_offset: wgt::BufferSize,
2237
2238 /// The alignment of the row pitch of the texture data stored in a buffer that is
2239 /// used in a GPU copy operation.
2240 pub buffer_copy_pitch: wgt::BufferSize,
2241
2242 /// The finest alignment of bound range checking for uniform buffers.
2243 ///
2244 /// When `wgpu_hal` restricts shader references to the [accessible
2245 /// region][ar] of a [`Uniform`] buffer, the size of the accessible region
2246 /// is the bind group binding's stated [size], rounded up to the next
2247 /// multiple of this value.
2248 ///
2249 /// We don't need an analogous field for storage buffer bindings, because
2250 /// all our backends promise to enforce the size at least to a four-byte
2251 /// alignment, and `wgpu_hal` requires bound range lengths to be a multiple
2252 /// of four anyway.
2253 ///
2254 /// [ar]: struct.BufferBinding.html#accessible-region
2255 /// [`Uniform`]: wgt::BufferBindingType::Uniform
2256 /// [size]: BufferBinding::size
2257 pub uniform_bounds_check_alignment: wgt::BufferSize,
2258
2259 /// The size of the raw TLAS instance
2260 pub raw_tlas_instance_size: u32,
2261
2262 /// What the scratch buffer for building an acceleration structure must be aligned to
2263 pub ray_tracing_scratch_buffer_alignment: u32,
2264
2265 /// How large a single piece of group data is. That is, how large the vector returned
2266 /// from `device.get_raytracing_pipeline_group_data(&pipeline, n..(n+1))` is.
2267 ///
2268 /// If ray tracing pipelines are implemented, this must be non zero.
2269 pub ray_tracing_pipeline_group_data_size: u32,
2270
2271 /// If ray tracing pipelines are implemented, this must be a power of two (and non zero).
2272 pub ray_tracing_pipeline_group_data_alignment: u32,
2273
2274 /// If ray tracing pipelines are implemented, this must be a power of two (and non zero).
2275 ///
2276 /// The offset within `PipelineGroupData` must be a multiple of this
2277 pub ray_tracing_pipeline_data_offset_alignment: u32,
2278}
2279
2280#[derive(Clone, Debug)]
2281pub struct Capabilities {
2282 pub limits: wgt::Limits,
2283 pub alignments: Alignments,
2284 pub downlevel: wgt::DownlevelCapabilities,
2285 /// Supported cooperative matrix configurations.
2286 ///
2287 /// Empty if cooperative matrices are not supported.
2288 pub cooperative_matrix_properties: Vec<wgt::CooperativeMatrixProperties>,
2289
2290 /// Whether the implementation reports that it is likely to reorder ray tracing invocations.
2291 ///
2292 /// [`None`] if [`Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER`] is not supported.
2293 ///
2294 /// [`None`]: wgt::RayTracingInvocationReorderMode::None
2295 /// [`Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER`]: wgt::Features::EXPERIMENTAL_RAY_TRACING_INVOCATION_REORDER
2296 pub ray_tracing_invocation_reorder_mode: wgt::RayTracingInvocationReorderMode,
2297}
2298
2299/// An adapter with all the information needed to reason about its capabilities.
2300///
2301/// These are either made by [`Instance::enumerate_adapters`] or by backend specific
2302/// methods on the backend [`Instance`] or [`Adapter`].
2303#[derive(Debug)]
2304pub struct ExposedAdapter<A: Api> {
2305 pub adapter: A::Adapter,
2306 pub info: wgt::AdapterInfo,
2307 pub features: wgt::Features,
2308 pub capabilities: Capabilities,
2309}
2310
2311/// Describes information about what a `Surface`'s presentation capabilities are.
2312/// Fetch this with [Adapter::surface_capabilities].
2313#[derive(Debug, Clone)]
2314pub struct SurfaceCapabilities {
2315 /// List of supported texture formats together with the color spaces
2316 /// supported for each format.
2317 ///
2318 /// Must be at least one. At most one entry per format, each with a
2319 /// non-empty set of color spaces.
2320 pub formats: Vec<wgt::SurfaceFormatCapabilities>,
2321
2322 /// Range for the number of queued frames.
2323 ///
2324 /// This adjusts either the swapchain frame count to value + 1 - or sets SetMaximumFrameLatency to the value given,
2325 /// 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.
2326 ///
2327 /// - `maximum_frame_latency.start` must be at least 1.
2328 /// - `maximum_frame_latency.end` must be larger or equal to `maximum_frame_latency.start`.
2329 pub maximum_frame_latency: RangeInclusive<u32>,
2330
2331 /// Current extent of the surface, if known.
2332 pub current_extent: Option<wgt::Extent3d>,
2333
2334 /// Supported texture usage flags.
2335 ///
2336 /// Must have at least `wgt::TextureUses::COLOR_TARGET`
2337 pub usage: wgt::TextureUses,
2338
2339 /// List of supported V-sync modes.
2340 ///
2341 /// Must be at least one.
2342 pub present_modes: Vec<wgt::PresentMode>,
2343
2344 /// List of supported alpha composition modes.
2345 ///
2346 /// Must be at least one.
2347 pub composite_alpha_modes: Vec<wgt::CompositeAlphaMode>,
2348}
2349
2350impl SurfaceCapabilities {
2351 /// Returns the supported texture formats, dropping the per-format color-space
2352 /// information carried in [`Self::formats`].
2353 pub fn texture_formats(&self) -> impl Iterator<Item = wgt::TextureFormat> + '_ {
2354 self.formats.iter().map(|fc| fc.format)
2355 }
2356}
2357
2358#[derive(Debug)]
2359pub struct AcquiredSurfaceTexture<A: Api> {
2360 pub texture: A::SurfaceTexture,
2361 /// The presentation configuration no longer matches
2362 /// the surface properties exactly, but can still be used to present
2363 /// to the surface successfully.
2364 pub suboptimal: bool,
2365}
2366
2367/// An open connection to a device and a queue.
2368///
2369/// This can be created from [`Adapter::open`] or backend
2370/// specific methods on the backend's [`Instance`] or [`Adapter`].
2371#[derive(Debug)]
2372pub struct OpenDevice<A: Api> {
2373 pub device: A::Device,
2374 pub queue: A::Queue,
2375}
2376
2377#[derive(Clone, Debug)]
2378pub struct BufferMapping {
2379 pub ptr: NonNull<u8>,
2380 pub is_coherent: bool,
2381}
2382
2383#[derive(Clone, Debug)]
2384pub struct BufferDescriptor<'a> {
2385 pub label: Label<'a>,
2386
2387 /// The requested size of the buffer.
2388 ///
2389 /// `wgpu-hal` may allocate more bytes than requested, if required by the
2390 /// platform. The actual allocation size is returned by `create_buffer`.
2391 /// Where platforms offer bounds checking, it will operate based on the
2392 /// allocated size, not the requested size, so other means may be necessary
2393 /// to prevent access beyond the original requested size. The content of
2394 /// newly-created buffers is undefined.
2395 pub size: wgt::BufferAddress,
2396 pub usage: wgt::BufferUses,
2397 pub memory_flags: MemoryFlags,
2398}
2399
2400#[derive(Clone, Debug)]
2401pub struct TextureDescriptor<'a> {
2402 pub label: Label<'a>,
2403 pub size: wgt::Extent3d,
2404 pub mip_level_count: u32,
2405 pub sample_count: u32,
2406 pub dimension: wgt::TextureDimension,
2407 pub format: wgt::TextureFormat,
2408 pub usage: wgt::TextureUses,
2409 pub memory_flags: MemoryFlags,
2410 /// The view dimension texture bindings will use.
2411 /// Must be `Some` on devices without
2412 /// [`ARBITRARY_BINDING_VIEW_DIMENSIONS`](wgt::DownlevelFlags::ARBITRARY_BINDING_VIEW_DIMENSIONS)
2413 /// (GLES), ignored otherwise.
2414 pub texture_binding_view_dimension: Option<wgt::TextureViewDimension>,
2415 /// Allows views of this texture to have a different format
2416 /// than the texture does.
2417 pub view_formats: Vec<wgt::TextureFormat>,
2418}
2419
2420impl TextureDescriptor<'_> {
2421 pub fn copy_extent(&self) -> CopyExtent {
2422 CopyExtent::map_extent_to_copy_size(&self.size, self.dimension)
2423 }
2424
2425 pub fn is_cube_compatible(&self) -> bool {
2426 self.dimension == wgt::TextureDimension::D2
2427 && self.size.depth_or_array_layers.is_multiple_of(6)
2428 && self.sample_count == 1
2429 && self.size.width == self.size.height
2430 }
2431
2432 pub fn array_layer_count(&self) -> u32 {
2433 match self.dimension {
2434 wgt::TextureDimension::D1 | wgt::TextureDimension::D3 => 1,
2435 wgt::TextureDimension::D2 => self.size.depth_or_array_layers,
2436 }
2437 }
2438}
2439
2440/// TextureView descriptor.
2441///
2442/// Valid usage:
2443///. - `format` has to be the same as `TextureDescriptor::format`
2444///. - `dimension` has to be compatible with `TextureDescriptor::dimension`
2445///. - `usage` has to be a subset of `TextureDescriptor::usage`
2446///. - `range` has to be a subset of parent texture
2447#[derive(Clone, Debug)]
2448pub struct TextureViewDescriptor<'a> {
2449 pub label: Label<'a>,
2450 pub format: wgt::TextureFormat,
2451 pub dimension: wgt::TextureViewDimension,
2452 pub usage: wgt::TextureUses,
2453 pub range: wgt::ImageSubresourceRange,
2454 pub swizzle: wgt::TextureComponentSwizzle,
2455}
2456
2457#[derive(Clone, Debug)]
2458pub struct SamplerDescriptor<'a> {
2459 pub label: Label<'a>,
2460 pub address_modes: [wgt::AddressMode; 3],
2461 pub mag_filter: wgt::FilterMode,
2462 pub min_filter: wgt::FilterMode,
2463 pub mipmap_filter: wgt::MipmapFilterMode,
2464 pub lod_clamp: Range<f32>,
2465 pub compare: Option<wgt::CompareFunction>,
2466 // Must in the range [1, 16].
2467 //
2468 // Anisotropic filtering must be supported if this is not 1.
2469 pub anisotropy_clamp: u16,
2470 pub border_color: Option<wgt::SamplerBorderColor>,
2471}
2472
2473/// BindGroupLayout descriptor.
2474///
2475/// Valid usage:
2476/// - `entries` are sorted by ascending `wgt::BindGroupLayoutEntry::binding`
2477#[derive(Clone, Debug)]
2478pub struct BindGroupLayoutDescriptor<'a> {
2479 pub label: Label<'a>,
2480 pub flags: BindGroupLayoutFlags,
2481 pub entries: &'a [wgt::BindGroupLayoutEntry],
2482}
2483
2484#[derive(Clone, Debug)]
2485pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> {
2486 pub label: Label<'a>,
2487 pub flags: PipelineLayoutFlags,
2488 pub bind_group_layouts: &'a [Option<&'a B>],
2489 pub immediate_size: u32,
2490}
2491
2492/// A region of a buffer made visible to shaders via a [`BindGroup`].
2493///
2494/// [`BindGroup`]: Api::BindGroup
2495///
2496/// ## Construction
2497///
2498/// The recommended way to construct a `BufferBinding` is using the `binding`
2499/// method on a wgpu-core `Buffer`, which will validate the binding size
2500/// against the buffer size. A `new_unchecked` constructor is also provided for
2501/// cases where direct construction is necessary.
2502///
2503/// ## Accessible region
2504///
2505/// `wgpu_hal` guarantees that shaders compiled with
2506/// [`ShaderModuleDescriptor::runtime_checks`] set to `true` cannot read or
2507/// write data via this binding outside the *accessible region* of a buffer:
2508///
2509/// - The accessible region starts at [`offset`].
2510///
2511/// - For [`Storage`] bindings, the size of the accessible region is [`size`],
2512/// which must be a multiple of 4.
2513///
2514/// - For [`Uniform`] bindings, the size of the accessible region is [`size`]
2515/// rounded up to the next multiple of
2516/// [`Alignments::uniform_bounds_check_alignment`].
2517///
2518/// Note that this guarantee is stricter than WGSL's requirements for
2519/// [out-of-bounds accesses][woob], as WGSL allows them to return values from
2520/// elsewhere in the buffer. But this guarantee is necessary anyway, to permit
2521/// `wgpu-core` to avoid clearing uninitialized regions of buffers that will
2522/// never be read by the application before they are overwritten. This
2523/// optimization consults bind group buffer binding regions to determine which
2524/// parts of which buffers shaders might observe. This optimization is only
2525/// sound if shader access is bounds-checked.
2526///
2527/// ## Zero-length bindings
2528///
2529/// Some platform APIs do not accept zero-length regions; for example, see
2530/// [VUID-VkDescriptorBufferInfo-offset-00340][340],
2531/// [VUID-VkDescriptorBufferInfo-range-00341][341], or the
2532/// documentation for GLES's [glBindBufferRange][bbr]. For
2533/// [VUID-VkCmdBindVertexBuffers-pOffsets-00626][626], no size is specified,
2534/// the binding extends from the offset to the end of the buffer, and the offset
2535/// must be strictly less than the buffer size.
2536///
2537/// WebGPU does not allow zero-length storage/uniform buffer bindings, but does
2538/// allow zero-length vertex/index buffer bindings. `wgpu-core` ensures that
2539/// buffers supporting vertex/index usage have 4B of naturally-aligned padding at
2540/// the end, to enable simulating a zero-length binding at the end of the buffer.
2541///
2542/// [`offset`]: BufferBinding::offset
2543/// [`size`]: BufferBinding::size
2544/// [`Storage`]: wgt::BufferBindingType::Storage
2545/// [`Uniform`]: wgt::BufferBindingType::Uniform
2546/// [340]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-offset-00340
2547/// [341]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-range-00341
2548/// [626]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-vkCmdBindVertexBuffers-pOffsets-00626
2549/// [bbr]: https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glBindBufferRange.xhtml
2550/// [woob]: https://gpuweb.github.io/gpuweb/wgsl/#out-of-bounds-access-sec
2551#[derive(Debug)]
2552pub struct BufferBinding<'a, B: DynBuffer + ?Sized, S> {
2553 /// The buffer being bound.
2554 ///
2555 /// This is not fully `pub` to prevent direct construction of
2556 /// `BufferBinding`s, while still allowing public read access to the `offset`
2557 /// and `size` properties. Read access to the buffer is available via
2558 /// [`Self::buffer`].
2559 pub(crate) buffer: &'a B,
2560
2561 /// The offset at which the bound region starts.
2562 ///
2563 /// This must be less or equal to the size of the buffer.
2564 pub offset: wgt::BufferAddress,
2565
2566 /// The size of the region bound, in bytes.
2567 pub size: S,
2568}
2569
2570// We must implement this manually because `B` is not necessarily `Clone`.
2571impl<B: DynBuffer + ?Sized, S: Copy> Clone for BufferBinding<'_, B, S> {
2572 fn clone(&self) -> Self {
2573 BufferBinding {
2574 buffer: self.buffer,
2575 offset: self.offset,
2576 size: self.size,
2577 }
2578 }
2579}
2580
2581impl<'a, B: DynBuffer + ?Sized, S> BufferBinding<'a, B, S> {
2582 /// Construct a `BufferBinding` with the given contents.
2583 ///
2584 /// When possible, use the `binding` method on a wgpu-core `Buffer` instead
2585 /// of this method. `Buffer::binding` validates the size of the binding
2586 /// against the size of the buffer.
2587 ///
2588 /// It is more difficult to provide a validating constructor here, due to
2589 /// not having direct access to the size of a `DynBuffer`.
2590 ///
2591 /// SAFETY: The caller is responsible for ensuring that a binding of `size`
2592 /// bytes starting at `offset` is contained within the buffer. `size`
2593 /// may be zero only for vertex/index buffer bindings.
2594 pub fn new_unchecked(buffer: &'a B, offset: wgt::BufferAddress, size: S) -> Self {
2595 Self {
2596 buffer,
2597 offset,
2598 size,
2599 }
2600 }
2601
2602 /// The buffer being bound.
2603 pub fn buffer(&self) -> &'a B {
2604 self.buffer
2605 }
2606}
2607
2608#[derive(Debug)]
2609pub struct TextureBinding<'a, T: DynTextureView + ?Sized> {
2610 pub view: &'a T,
2611 pub usage: wgt::TextureUses,
2612}
2613
2614impl<'a, T: DynTextureView + ?Sized> Clone for TextureBinding<'a, T> {
2615 fn clone(&self) -> Self {
2616 TextureBinding {
2617 view: self.view,
2618 usage: self.usage,
2619 }
2620 }
2621}
2622
2623#[derive(Debug)]
2624pub struct ExternalTextureBinding<'a, B: DynBuffer + ?Sized, T: DynTextureView + ?Sized> {
2625 pub planes: [TextureBinding<'a, T>; 3],
2626 pub params: BufferBinding<'a, B, wgt::BufferSize>,
2627}
2628
2629impl<'a, B: DynBuffer + ?Sized, T: DynTextureView + ?Sized> Clone
2630 for ExternalTextureBinding<'a, B, T>
2631{
2632 fn clone(&self) -> Self {
2633 ExternalTextureBinding {
2634 planes: self.planes.clone(),
2635 params: self.params.clone(),
2636 }
2637 }
2638}
2639
2640/// cbindgen:ignore
2641#[derive(Clone, Debug)]
2642pub struct BindGroupEntry {
2643 pub binding: u32,
2644 pub resource_index: u32,
2645 pub count: u32,
2646}
2647
2648/// BindGroup descriptor.
2649///
2650/// Valid usage:
2651///. - `entries` has to be sorted by ascending `BindGroupEntry::binding`
2652///. - `entries` has to have the same set of `BindGroupEntry::binding` as `layout`
2653///. - each entry has to be compatible with the `layout`
2654///. - each entry's `BindGroupEntry::resource_index` is within range
2655/// of the corresponding resource array, selected by the relevant
2656/// `BindGroupLayoutEntry`.
2657#[derive(Clone, Debug)]
2658pub struct BindGroupDescriptor<
2659 'a,
2660 Bgl: DynBindGroupLayout + ?Sized,
2661 B: DynBuffer + ?Sized,
2662 S: DynSampler + ?Sized,
2663 T: DynTextureView + ?Sized,
2664 A: DynAccelerationStructure + ?Sized,
2665> {
2666 pub label: Label<'a>,
2667 pub layout: &'a Bgl,
2668 pub buffers: &'a [BufferBinding<'a, B, wgt::BufferSize>],
2669 pub samplers: &'a [&'a S],
2670 pub textures: &'a [TextureBinding<'a, T>],
2671 pub entries: &'a [BindGroupEntry],
2672 pub acceleration_structures: &'a [&'a A],
2673 pub external_textures: &'a [ExternalTextureBinding<'a, B, T>],
2674}
2675
2676#[derive(Clone, Debug)]
2677pub struct CommandEncoderDescriptor<'a, Q: DynQueue + ?Sized> {
2678 pub label: Label<'a>,
2679 pub queue: &'a Q,
2680}
2681
2682/// Naga shader module.
2683#[derive(Default)]
2684pub struct NagaShader {
2685 /// Shader module IR.
2686 pub module: Cow<'static, naga::Module>,
2687 /// Analysis information of the module.
2688 pub info: naga::valid::ModuleInfo,
2689 /// Source codes for debug
2690 pub debug_source: Option<DebugSource>,
2691}
2692
2693// Custom implementation avoids the need to generate Debug impl code
2694// for the whole Naga module and info.
2695impl fmt::Debug for NagaShader {
2696 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2697 write!(formatter, "Naga shader")
2698 }
2699}
2700
2701/// Shader input.
2702pub enum ShaderInput<'a> {
2703 Naga(NagaShader),
2704 MetalLib {
2705 file: &'a [u8],
2706 num_workgroups: hashbrown::HashMap<String, (u32, u32, u32)>,
2707 },
2708 Msl {
2709 shader: &'a str,
2710 num_workgroups: hashbrown::HashMap<String, (u32, u32, u32)>,
2711 },
2712 SpirV(&'a [u32]),
2713 Dxil {
2714 shader: &'a [u8],
2715 },
2716 Hlsl {
2717 shader: &'a str,
2718 },
2719 Glsl {
2720 shader: &'a str,
2721 },
2722}
2723
2724impl fmt::Debug for ShaderInput<'_> {
2725 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2726 match self {
2727 // Don't include the entire shader source, especially for binary formats, because it
2728 // would be spammy.
2729 Self::Naga { .. } => f.debug_tuple("Naga").finish_non_exhaustive(),
2730 Self::MetalLib { .. } => f.debug_tuple("MetalLib").finish_non_exhaustive(),
2731 Self::Msl { .. } => f.debug_tuple("Msl").finish_non_exhaustive(),
2732 Self::SpirV { .. } => f.debug_tuple("SpirV").finish_non_exhaustive(),
2733 Self::Dxil { .. } => f.debug_tuple("Dxil").finish_non_exhaustive(),
2734 Self::Hlsl { .. } => f.debug_tuple("Hlsl").finish_non_exhaustive(),
2735 Self::Glsl { .. } => f.debug_tuple("Glsl").finish_non_exhaustive(),
2736 }
2737 }
2738}
2739
2740#[derive(Debug)]
2741pub struct ShaderModuleDescriptor<'a> {
2742 pub label: Label<'a>,
2743
2744 /// # Safety
2745 ///
2746 /// See the documentation for each flag in [`ShaderRuntimeChecks`][src].
2747 ///
2748 /// [src]: wgt::ShaderRuntimeChecks
2749 pub runtime_checks: wgt::ShaderRuntimeChecks,
2750}
2751
2752#[derive(Debug, Clone)]
2753pub struct DebugSource {
2754 pub file_name: Cow<'static, str>,
2755 pub source_code: Cow<'static, str>,
2756}
2757
2758/// Describes a programmable pipeline stage.
2759#[derive(Debug)]
2760pub struct ProgrammableStage<'a, M: DynShaderModule + ?Sized> {
2761 /// The compiled shader module for this stage.
2762 pub module: &'a M,
2763 /// The name of the entry point in the compiled shader. There must be a function with this name
2764 /// in the shader.
2765 pub entry_point: &'a str,
2766 /// Pipeline constants
2767 pub constants: &'a naga::back::PipelineConstants,
2768 /// Whether workgroup scoped memory will be initialized with zero values for this stage.
2769 ///
2770 /// This is required by the WebGPU spec, but may have overhead which can be avoided
2771 /// for cross-platform applications
2772 pub zero_initialize_workgroup_memory: bool,
2773}
2774
2775impl<M: DynShaderModule + ?Sized> Clone for ProgrammableStage<'_, M> {
2776 fn clone(&self) -> Self {
2777 Self {
2778 module: self.module,
2779 entry_point: self.entry_point,
2780 constants: self.constants,
2781 zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory,
2782 }
2783 }
2784}
2785
2786/// Describes a compute pipeline.
2787#[derive(Clone, Debug)]
2788pub struct ComputePipelineDescriptor<
2789 'a,
2790 Pl: DynPipelineLayout + ?Sized,
2791 M: DynShaderModule + ?Sized,
2792 Pc: DynPipelineCache + ?Sized,
2793> {
2794 pub label: Label<'a>,
2795 /// The layout of bind groups for this pipeline.
2796 pub layout: &'a Pl,
2797 /// The compiled compute stage and its entry point.
2798 pub stage: ProgrammableStage<'a, M>,
2799 /// The cache which will be used and filled when compiling this pipeline
2800 pub cache: Option<&'a Pc>,
2801}
2802
2803#[derive(Debug)]
2804pub struct PipelineCacheDescriptor<'a> {
2805 pub label: Label<'a>,
2806 pub data: Option<&'a [u8]>,
2807}
2808
2809/// Describes how the vertex buffer is interpreted.
2810#[derive(Clone, Debug)]
2811pub struct VertexBufferLayout<'a> {
2812 /// The stride, in bytes, between elements of this buffer.
2813 pub array_stride: wgt::BufferAddress,
2814 /// How often this vertex buffer is "stepped" forward.
2815 pub step_mode: wgt::VertexStepMode,
2816 /// The list of attributes which comprise a single vertex.
2817 pub attributes: &'a [wgt::VertexAttribute],
2818}
2819
2820#[derive(Clone, Debug)]
2821pub enum VertexProcessor<'a, M: DynShaderModule + ?Sized> {
2822 Standard {
2823 /// The format of any vertex buffers used with this pipeline.
2824 vertex_buffers: &'a [Option<VertexBufferLayout<'a>>],
2825 /// The vertex stage for this pipeline.
2826 vertex_stage: ProgrammableStage<'a, M>,
2827 },
2828 Mesh {
2829 task_stage: Option<ProgrammableStage<'a, M>>,
2830 mesh_stage: ProgrammableStage<'a, M>,
2831 },
2832}
2833
2834/// Describes a render (graphics) pipeline.
2835#[derive(Clone, Debug)]
2836pub struct RenderPipelineDescriptor<
2837 'a,
2838 Pl: DynPipelineLayout + ?Sized,
2839 M: DynShaderModule + ?Sized,
2840 Pc: DynPipelineCache + ?Sized,
2841> {
2842 pub label: Label<'a>,
2843 /// The layout of bind groups for this pipeline.
2844 pub layout: &'a Pl,
2845 /// The vertex processing state(vertex shader + buffers or task + mesh shaders)
2846 pub vertex_processor: VertexProcessor<'a, M>,
2847 /// The properties of the pipeline at the primitive assembly and rasterization level.
2848 pub primitive: wgt::PrimitiveState,
2849 /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
2850 pub depth_stencil: Option<wgt::DepthStencilState>,
2851 /// The multi-sampling properties of the pipeline.
2852 pub multisample: wgt::MultisampleState,
2853 /// The fragment stage for this pipeline.
2854 pub fragment_stage: Option<ProgrammableStage<'a, M>>,
2855 /// The effect of draw calls on the color aspect of the output target.
2856 pub color_targets: &'a [Option<wgt::ColorTargetState>],
2857 /// If the pipeline will be used with a multiview render pass, this indicates how many array
2858 /// layers the attachments will have.
2859 pub multiview_mask: Option<NonZeroU32>,
2860 /// The cache which will be used and filled when compiling this pipeline
2861 pub cache: Option<&'a Pc>,
2862}
2863
2864#[derive(Clone, Debug)]
2865pub struct RayObjectIntersectionState<'a, M: DynShaderModule + ?Sized> {
2866 pub closest_hit: ProgrammableStage<'a, M>,
2867 pub any_hit: Option<ProgrammableStage<'a, M>>,
2868}
2869
2870/// Describes a ray tracing pipeline.
2871#[derive(Clone, Debug)]
2872pub struct RayTracingPipelineDescriptor<
2873 'a,
2874 Pl: DynPipelineLayout + ?Sized,
2875 M: DynShaderModule + ?Sized,
2876 Pc: DynPipelineCache + ?Sized,
2877> {
2878 pub label: Label<'a>,
2879 /// The layout of bind groups for this pipeline.
2880 pub layout: &'a Pl,
2881 /// The ray generation stage.
2882 pub ray_generation: ProgrammableStage<'a, M>,
2883 /// The miss stage.
2884 pub miss: ProgrammableStage<'a, M>,
2885 /// All the object intersection stages.
2886 pub intersection: &'a [RayObjectIntersectionState<'a, M>],
2887 /// The maximum recursion depth allowed for the ray tracing (ray_generation shader counts as depth 0).
2888 pub max_recursion_depth: u32,
2889 /// The cache which will be used and filled when compiling this pipeline
2890 pub cache: Option<&'a Pc>,
2891}
2892
2893#[derive(Debug, Clone)]
2894pub struct SurfaceConfiguration {
2895 /// Maximum number of queued frames. Must be in
2896 /// `SurfaceCapabilities::maximum_frame_latency` range.
2897 pub maximum_frame_latency: u32,
2898 /// Vertical synchronization mode.
2899 pub present_mode: wgt::PresentMode,
2900 /// Alpha composition mode.
2901 pub composite_alpha_mode: wgt::CompositeAlphaMode,
2902 /// Format of the surface textures.
2903 pub format: wgt::TextureFormat,
2904 /// Color space in which the presentation engine interprets the surface
2905 /// textures. Never [`wgt::SurfaceColorSpace::Auto`]; `wgpu-core` resolves
2906 /// `Auto` to a concrete color space before configuring the surface, and
2907 /// the (format, color space) pair must be listed in
2908 /// `SurfaceCapabilities::formats`.
2909 pub color_space: wgt::SurfaceColorSpace,
2910 /// Requested texture extent. Must be in
2911 /// `SurfaceCapabilities::extents` range.
2912 pub extent: wgt::Extent3d,
2913 /// Allowed usage of surface textures,
2914 pub usage: wgt::TextureUses,
2915 /// Allows views of swapchain texture to have a different format
2916 /// than the texture does.
2917 pub view_formats: Vec<wgt::TextureFormat>,
2918}
2919
2920#[derive(Debug, Clone)]
2921pub struct Rect<T> {
2922 pub x: T,
2923 pub y: T,
2924 pub w: T,
2925 pub h: T,
2926}
2927
2928#[derive(Debug, Clone, PartialEq)]
2929pub struct StateTransition<T> {
2930 pub from: T,
2931 pub to: T,
2932}
2933
2934#[derive(Debug, Clone)]
2935pub struct BufferBarrier<'a, B: DynBuffer + ?Sized> {
2936 pub buffer: &'a B,
2937 pub usage: StateTransition<wgt::BufferUses>,
2938}
2939
2940/// One side of a [`QueueFamilyOwnershipTransfer`].
2941///
2942/// The named variants stand for the queue families that Vulkan reserves for
2943/// resources shared outside the current device; [`Explicit`] carries an
2944/// ordinary queue family index, such as the one returned by
2945/// `vulkan::Device::queue_family_index`.
2946///
2947/// [`Explicit`]: QueueFamily::Explicit
2948#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2949pub enum QueueFamily {
2950 /// A specific queue family, identified by its index.
2951 Explicit(u32),
2952
2953 /// The queue family of an external, non-Vulkan API
2954 /// (`VK_QUEUE_FAMILY_EXTERNAL`).
2955 External,
2956
2957 /// The queue family of a foreign consumer of the memory, such as a
2958 /// different device or the kernel (`VK_QUEUE_FAMILY_FOREIGN_EXT`).
2959 ///
2960 /// Requires the `VK_EXT_queue_family_foreign` extension.
2961 Foreign,
2962}
2963
2964/// A queue family ownership transfer to perform as part of a [`TextureBarrier`].
2965///
2966/// This is only honored by the Vulkan backend; every other backend ignores it.
2967/// It exists so that textures imported from external memory (for example via
2968/// `VK_KHR_external_memory`) can have their backing image transferred between
2969/// wgpu's queue family and a queue family outside of wgpu's control when the
2970/// image is acquired for use and released afterwards.
2971///
2972/// `src` becomes `VkImageMemoryBarrier::srcQueueFamilyIndex` and `dst` becomes
2973/// `VkImageMemoryBarrier::dstQueueFamilyIndex`. To acquire an externally owned
2974/// image, set `src` to [`QueueFamily::External`] or [`QueueFamily::Foreign`]
2975/// and `dst` to [`QueueFamily::Explicit`] with wgpu's own family, obtained from
2976/// `vulkan::Device::queue_family_index`. To release it again, swap the two.
2977///
2978/// A queue family ownership transfer requires a matching barrier to be recorded
2979/// on *both* queues; wgpu-hal only records the barrier on its own queue, so the
2980/// owner of the other queue is responsible for recording the complementary one.
2981#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2982pub struct QueueFamilyOwnershipTransfer {
2983 /// The queue family that currently owns the image (`srcQueueFamilyIndex`).
2984 pub src: QueueFamily,
2985 /// The queue family that should own the image afterwards (`dstQueueFamilyIndex`).
2986 pub dst: QueueFamily,
2987}
2988
2989#[derive(Debug)]
2990pub struct TextureBarrier<'a, T: DynTexture + ?Sized> {
2991 pub texture: &'a T,
2992 pub range: wgt::ImageSubresourceRange,
2993 pub usage: StateTransition<wgt::TextureUses>,
2994 /// An optional Vulkan queue family ownership transfer to perform alongside
2995 /// the layout/access transition described by `usage`.
2996 ///
2997 /// This is honored only by the Vulkan backend; all other backends ignore
2998 /// it. Leave it as `None` for the common case where no ownership transfer
2999 /// is required. See [`QueueFamilyOwnershipTransfer`] for details.
3000 pub queue_family_ownership_transfer: Option<QueueFamilyOwnershipTransfer>,
3001}
3002
3003impl<'a, T: DynTexture + ?Sized> Clone for TextureBarrier<'a, T> {
3004 fn clone(&self) -> Self {
3005 Self {
3006 texture: self.texture,
3007 range: self.range,
3008 queue_family_ownership_transfer: self.queue_family_ownership_transfer,
3009 usage: self.usage.clone(),
3010 }
3011 }
3012}
3013
3014#[derive(Clone, Copy, Debug)]
3015pub struct BufferCopy {
3016 pub src_offset: wgt::BufferAddress,
3017 pub dst_offset: wgt::BufferAddress,
3018 pub size: wgt::BufferSize,
3019}
3020
3021#[derive(Clone, Debug)]
3022pub struct TextureCopyBase {
3023 pub mip_level: u32,
3024 pub array_layer: u32,
3025 /// Origin within a texture.
3026 /// Note: for 1D and 2D textures, Z must be 0.
3027 pub origin: wgt::Origin3d,
3028 pub aspect: FormatAspects,
3029}
3030
3031#[derive(Clone, Copy, Debug)]
3032pub struct CopyExtent {
3033 pub width: u32,
3034 pub height: u32,
3035 pub depth: u32,
3036}
3037
3038impl From<wgt::Extent3d> for CopyExtent {
3039 fn from(value: wgt::Extent3d) -> Self {
3040 let wgt::Extent3d {
3041 width,
3042 height,
3043 depth_or_array_layers,
3044 } = value;
3045 Self {
3046 width,
3047 height,
3048 depth: depth_or_array_layers,
3049 }
3050 }
3051}
3052
3053impl From<CopyExtent> for wgt::Extent3d {
3054 fn from(value: CopyExtent) -> Self {
3055 let CopyExtent {
3056 width,
3057 height,
3058 depth,
3059 } = value;
3060 Self {
3061 width,
3062 height,
3063 depth_or_array_layers: depth,
3064 }
3065 }
3066}
3067
3068#[derive(Clone, Debug)]
3069pub struct TextureCopy {
3070 pub src_base: TextureCopyBase,
3071 pub dst_base: TextureCopyBase,
3072 pub size: CopyExtent,
3073}
3074
3075#[derive(Clone, Debug)]
3076pub struct BufferTextureCopy {
3077 pub buffer_layout: wgt::TexelCopyBufferLayout,
3078 pub texture_base: TextureCopyBase,
3079 pub size: CopyExtent,
3080}
3081
3082#[derive(Clone, Debug)]
3083pub struct Attachment<'a, T: DynTextureView + ?Sized> {
3084 pub view: &'a T,
3085 /// Contains either a single mutating usage as a target,
3086 /// or a valid combination of read-only usages.
3087 pub usage: wgt::TextureUses,
3088}
3089
3090#[derive(Clone, Debug)]
3091pub struct ColorAttachment<'a, T: DynTextureView + ?Sized> {
3092 pub target: Attachment<'a, T>,
3093 pub depth_slice: Option<u32>,
3094 pub resolve_target: Option<Attachment<'a, T>>,
3095 pub ops: AttachmentOps,
3096 pub clear_value: wgt::Color,
3097}
3098
3099#[derive(Clone, Debug)]
3100pub struct DepthStencilAttachment<'a, T: DynTextureView + ?Sized> {
3101 pub target: Attachment<'a, T>,
3102 pub depth_ops: AttachmentOps,
3103 pub stencil_ops: AttachmentOps,
3104 pub depth_read_only: bool,
3105 pub stencil_read_only: bool,
3106 pub clear_value: (f32, u32),
3107}
3108
3109#[derive(Clone, Debug)]
3110pub struct PassTimestampWrites<'a, Q: DynQuerySet + ?Sized> {
3111 pub query_set: &'a Q,
3112 pub beginning_of_pass_write_index: Option<u32>,
3113 pub end_of_pass_write_index: Option<u32>,
3114}
3115
3116#[derive(Clone, Debug)]
3117pub struct RenderPassDescriptor<'a, Q: DynQuerySet + ?Sized, T: DynTextureView + ?Sized> {
3118 pub label: Label<'a>,
3119 pub extent: wgt::Extent3d,
3120 pub sample_count: u32,
3121 pub color_attachments: &'a [Option<ColorAttachment<'a, T>>],
3122 pub depth_stencil_attachment: Option<DepthStencilAttachment<'a, T>>,
3123 pub multiview_mask: Option<NonZeroU32>,
3124 pub timestamp_writes: Option<PassTimestampWrites<'a, Q>>,
3125 pub occlusion_query_set: Option<&'a Q>,
3126}
3127
3128#[derive(Clone, Debug)]
3129pub struct ComputePassDescriptor<'a, Q: DynQuerySet + ?Sized> {
3130 pub label: Label<'a>,
3131 pub timestamp_writes: Option<PassTimestampWrites<'a, Q>>,
3132}
3133
3134#[derive(Clone, Debug)]
3135pub struct RayTracingPassDescriptor<'a> {
3136 pub label: Label<'a>,
3137}
3138
3139#[cfg(test)]
3140mod tests {
3141 use super::*;
3142
3143 #[test]
3144 fn test_default_limits() {
3145 let limits = wgt::Limits::default();
3146 assert!(limits.max_bind_groups <= MAX_BIND_GROUPS as u32);
3147 }
3148}
3149
3150#[derive(Clone, Debug)]
3151pub struct AccelerationStructureDescriptor<'a> {
3152 pub label: Label<'a>,
3153 pub size: wgt::BufferAddress,
3154 pub format: AccelerationStructureFormat,
3155 /// Backends may allocate the structure as a short-lived resource, since it is
3156 /// usually replaced by its compacted copy.
3157 pub allow_compaction: bool,
3158}
3159
3160#[derive(Debug, Clone, Copy, Eq, PartialEq)]
3161pub enum AccelerationStructureFormat {
3162 TopLevel,
3163 BottomLevel,
3164}
3165
3166#[derive(Debug, Clone, Copy, Eq, PartialEq)]
3167pub enum AccelerationStructureBuildMode {
3168 Build,
3169 Update,
3170}
3171
3172/// Information of the required size for a corresponding entries struct (+ flags)
3173#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
3174pub struct AccelerationStructureBuildSizes {
3175 pub acceleration_structure_size: wgt::BufferAddress,
3176 pub update_scratch_size: wgt::BufferAddress,
3177 pub build_scratch_size: wgt::BufferAddress,
3178}
3179
3180/// Updates use source_acceleration_structure if present, else the update will be performed in place.
3181/// For updates, only the data is allowed to change (not the meta data or sizes).
3182#[derive(Clone, Debug)]
3183pub struct BuildAccelerationStructureDescriptor<
3184 'a,
3185 B: DynBuffer + ?Sized,
3186 A: DynAccelerationStructure + ?Sized,
3187> {
3188 pub entries: &'a AccelerationStructureEntries<'a, B>,
3189 pub mode: AccelerationStructureBuildMode,
3190 pub flags: AccelerationStructureBuildFlags,
3191 pub source_acceleration_structure: Option<&'a A>,
3192 pub destination_acceleration_structure: &'a A,
3193 pub scratch_buffer: &'a B,
3194 pub scratch_buffer_offset: wgt::BufferAddress,
3195}
3196
3197/// - All buffers, buffer addresses and offsets will be ignored.
3198/// - The build mode will be ignored.
3199/// - Reducing the amount of Instances, Triangle groups or AABB groups (or the number of Triangles/AABBs in corresponding groups),
3200/// may result in reduced size requirements.
3201/// - Any other change may result in a bigger or smaller size requirement.
3202#[derive(Clone, Debug)]
3203pub struct GetAccelerationStructureBuildSizesDescriptor<'a, B: DynBuffer + ?Sized> {
3204 pub entries: &'a AccelerationStructureEntries<'a, B>,
3205 pub flags: AccelerationStructureBuildFlags,
3206}
3207
3208/// Entries for a single descriptor
3209/// * `Instances` - Multiple instances for a top level acceleration structure
3210/// * `Triangles` - Multiple triangle meshes for a bottom level acceleration structure
3211/// * `AABBs` - List of list of axis aligned bounding boxes for a bottom level acceleration structure
3212#[derive(Debug)]
3213pub enum AccelerationStructureEntries<'a, B: DynBuffer + ?Sized> {
3214 Instances(AccelerationStructureInstances<'a, B>),
3215 Triangles(Vec<AccelerationStructureTriangles<'a, B>>),
3216 AABBs(Vec<AccelerationStructureAABBs<'a, B>>),
3217}
3218
3219/// * `first_vertex` - offset in the vertex buffer (as number of vertices)
3220/// * `indices` - optional index buffer with attributes
3221/// * `transform` - optional transform
3222#[derive(Clone, Debug)]
3223pub struct AccelerationStructureTriangles<'a, B: DynBuffer + ?Sized> {
3224 pub vertex_buffer: Option<&'a B>,
3225 pub vertex_format: wgt::VertexFormat,
3226 pub first_vertex: u32,
3227 pub vertex_count: u32,
3228 pub vertex_stride: wgt::BufferAddress,
3229 pub indices: Option<AccelerationStructureTriangleIndices<'a, B>>,
3230 pub transform: Option<AccelerationStructureTriangleTransform<'a, B>>,
3231 pub flags: AccelerationStructureGeometryFlags,
3232}
3233
3234/// * `offset` - offset in bytes
3235#[derive(Clone, Debug)]
3236pub struct AccelerationStructureAABBs<'a, B: DynBuffer + ?Sized> {
3237 pub buffer: Option<&'a B>,
3238 pub offset: u32,
3239 pub count: u32,
3240 pub stride: wgt::BufferAddress,
3241 pub flags: AccelerationStructureGeometryFlags,
3242}
3243
3244#[derive(Clone, Debug)]
3245pub struct AccelerationStructureCopy {
3246 pub copy_flags: wgt::AccelerationStructureCopy,
3247 pub type_flags: wgt::AccelerationStructureType,
3248}
3249
3250/// * `offset` - offset in bytes
3251#[derive(Clone, Debug)]
3252pub struct AccelerationStructureInstances<'a, B: DynBuffer + ?Sized> {
3253 pub buffer: Option<&'a B>,
3254 pub offset: u32,
3255 pub count: u32,
3256}
3257
3258/// * `offset` - offset in bytes
3259#[derive(Clone, Debug)]
3260pub struct AccelerationStructureTriangleIndices<'a, B: DynBuffer + ?Sized> {
3261 pub format: wgt::IndexFormat,
3262 pub buffer: Option<&'a B>,
3263 pub offset: u32,
3264 pub count: u32,
3265}
3266
3267/// * `offset` - offset in bytes
3268#[derive(Clone, Debug)]
3269pub struct AccelerationStructureTriangleTransform<'a, B: DynBuffer + ?Sized> {
3270 pub buffer: &'a B,
3271 pub offset: u32,
3272}
3273
3274pub use wgt::AccelerationStructureFlags as AccelerationStructureBuildFlags;
3275pub use wgt::AccelerationStructureGeometryFlags;
3276
3277bitflags::bitflags! {
3278 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3279 pub struct AccelerationStructureUses: u8 {
3280 // For blas used as input for tlas
3281 const BUILD_INPUT = 1 << 0;
3282 // Target for acceleration structure build
3283 const BUILD_OUTPUT = 1 << 1;
3284 // Tlas used in a shader
3285 const SHADER_INPUT = 1 << 2;
3286 // Blas used to query compacted size
3287 const QUERY_INPUT = 1 << 3;
3288 // BLAS used as a src for a copy operation
3289 const COPY_SRC = 1 << 4;
3290 // BLAS used as a dst for a copy operation
3291 const COPY_DST = 1 << 5;
3292 }
3293}
3294
3295#[derive(Debug, Clone)]
3296pub struct AccelerationStructureBarrier {
3297 pub usage: StateTransition<AccelerationStructureUses>,
3298}
3299
3300#[derive(Debug, Copy, Clone)]
3301pub struct TlasInstance {
3302 pub transform: [f32; 12],
3303 pub custom_data: u32,
3304 pub mask: u8,
3305 pub blas_address: u64,
3306 /// The offset for the index into the intersection hit
3307 /// group calculation. Number is in hit groups.
3308 pub pipeline_intersection_data_offset: u32,
3309}
3310
3311#[cfg(dx12)]
3312#[derive(Debug)]
3313pub enum D3D12ExposeAdapterResult {
3314 CreateDeviceError(dx12::CreateDeviceError),
3315 UnknownFeatureLevel(i32),
3316 ResourceBindingTier2Requirement,
3317 ShaderModel6Requirement,
3318 Success(dx12::FeatureLevel, dx12::ShaderModel),
3319}
3320
3321/// Pluggable telemetry, mainly to be used by Firefox.
3322#[derive(Debug, Clone, Copy)]
3323pub struct Telemetry {
3324 #[cfg(dx12)]
3325 pub d3d12_expose_adapter: fn(
3326 desc: &windows::Win32::Graphics::Dxgi::DXGI_ADAPTER_DESC2,
3327 driver_version: Result<[u16; 4], windows_core::HRESULT>,
3328 result: D3D12ExposeAdapterResult,
3329 ),
3330}
3331
3332#[derive(Debug)]
3333pub struct PipelineGroupData<'a, B: DynBuffer + ?Sized> {
3334 pub buffer: &'a B,
3335 pub offset: wgt::BufferAddress,
3336 pub stride: u64,
3337 pub count: u64,
3338}