wgpu/api/
adapter.rs

1use alloc::vec::Vec;
2use core::future::Future;
3#[cfg(wgpu_core)]
4use core::ops::Deref;
5
6use crate::*;
7
8/// Handle to a physical graphics and/or compute device.
9///
10/// Adapters can be created using [`Instance::request_adapter`]
11/// or other [`Instance`] methods.
12///
13/// Adapters can be used to open a connection to the corresponding [`Device`]
14/// on the host system by using [`Adapter::request_device`].
15///
16/// Does not have to be kept alive.
17///
18/// Corresponds to [WebGPU `GPUAdapter`](https://gpuweb.github.io/gpuweb/#gpu-adapter).
19#[derive(Debug, Clone)]
20pub struct Adapter {
21    pub(crate) inner: dispatch::DispatchAdapter,
22}
23#[cfg(send_sync)]
24static_assertions::assert_impl_all!(Adapter: Send, Sync);
25
26crate::cmp::impl_eq_ord_hash_proxy!(Adapter => .inner);
27
28pub use wgt::RequestAdapterOptions as RequestAdapterOptionsBase;
29/// Additional information required when requesting an adapter.
30///
31/// For use with [`Instance::request_adapter`].
32///
33/// Corresponds to [WebGPU `GPURequestAdapterOptions`](
34/// https://gpuweb.github.io/gpuweb/#dictdef-gpurequestadapteroptions).
35pub type RequestAdapterOptions<'a, 'b> = RequestAdapterOptionsBase<&'a Surface<'b>>;
36#[cfg(send_sync)]
37static_assertions::assert_impl_all!(RequestAdapterOptions<'_, '_>: Send, Sync);
38
39impl Adapter {
40    /// Requests a connection to a physical device, creating a logical device.
41    ///
42    /// Returns the [`Device`] together with a [`Queue`] that executes command buffers.
43    ///
44    /// [Per the WebGPU specification], an [`Adapter`] may only be used once to create a device.
45    /// If another device is wanted, call [`Instance::request_adapter()`] again to get a fresh
46    /// [`Adapter`].
47    /// However, `wgpu` does not currently enforce this restriction.
48    ///
49    /// # Panics
50    ///
51    /// - `request_device()` was already called on this `Adapter`.
52    /// - Features specified by `desc` are not supported by this adapter.
53    /// - Unsafe features were requested but not enabled when requesting the adapter.
54    /// - Limits requested exceed the values provided by the adapter.
55    /// - Adapter does not support all features wgpu requires to safely operate.
56    ///
57    /// [Per the WebGPU specification]: https://www.w3.org/TR/webgpu/#dom-gpuadapter-requestdevice
58    pub fn request_device(
59        &self,
60        desc: &DeviceDescriptor<'_>,
61    ) -> impl Future<Output = Result<(Device, Queue), RequestDeviceError>> + WasmNotSend {
62        let device = self.inner.request_device(desc);
63        async move {
64            device
65                .await
66                .map(|(device, queue)| (Device { inner: device }, Queue { inner: queue }))
67        }
68    }
69
70    /// Create a wgpu [`Device`] and [`Queue`] from a wgpu-hal [`hal::OpenDevice`].
71    ///
72    /// # Safety
73    ///
74    /// - `hal_device` must be created from this adapter internal handle.
75    /// - `desc.features` must be a subset of `hal_device`'s supported features.
76    #[cfg(wgpu_core)]
77    pub unsafe fn create_device_from_hal<A: hal::Api>(
78        &self,
79        hal_device: hal::OpenDevice<A>,
80        desc: &DeviceDescriptor<'_>,
81    ) -> Result<(Device, Queue), RequestDeviceError> {
82        let core_adapter = self.inner.as_core();
83        let (device, queue) = unsafe { core_adapter.create_device_from_hal(hal_device, desc) }?;
84
85        Ok((
86            Device {
87                inner: device.into(),
88            },
89            Queue {
90                inner: queue.into(),
91            },
92        ))
93    }
94
95    /// Get the [`wgpu_hal`] adapter from this `Adapter`.
96    ///
97    /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
98    /// and pass that struct to the to the `A` type parameter.
99    ///
100    /// Returns a guard that dereferences to the type of the hal backend
101    /// which implements [`A::Adapter`].
102    ///
103    /// # Types
104    ///
105    /// The returned type depends on the backend:
106    ///
107    #[doc = crate::macros::hal_type_vulkan!("Adapter")]
108    #[doc = crate::macros::hal_type_metal!("Adapter")]
109    #[doc = crate::macros::hal_type_dx12!("Adapter")]
110    #[doc = crate::macros::hal_type_gles!("Adapter")]
111    ///
112    /// # Errors
113    ///
114    /// This method will return None if:
115    /// - The adapter is not from the backend specified by `A`.
116    /// - The adapter is from the `webgpu` or `custom` backend.
117    ///
118    /// # Safety
119    ///
120    /// - The returned resource must not be destroyed unless the guard
121    ///   is the last reference to it and it is not in use by the GPU.
122    ///   The guard and handle may be dropped at any time however.
123    /// - All the safety requirements of wgpu-hal must be upheld.
124    ///
125    /// [`A::Adapter`]: hal::Api::Adapter
126    #[cfg(wgpu_core)]
127    pub unsafe fn as_hal<A: hal::Api>(
128        &self,
129    ) -> Option<impl Deref<Target = A::Adapter> + WasmNotSendSync> {
130        let adapter = self.inner.as_core_opt()?;
131
132        unsafe { adapter.as_hal::<A>() }
133    }
134
135    #[cfg(custom)]
136    /// Returns custom implementation of adapter (if custom backend and is internally T)
137    pub fn as_custom<T: custom::AdapterInterface>(&self) -> Option<&T> {
138        self.inner.as_custom()
139    }
140
141    #[cfg(custom)]
142    /// Creates Adapter from custom implementation
143    pub fn from_custom<T: custom::AdapterInterface>(adapter: T) -> Self {
144        Self {
145            inner: dispatch::DispatchAdapter::custom(adapter),
146        }
147    }
148
149    /// Returns whether this adapter may present to the passed surface.
150    pub fn is_surface_supported(&self, surface: &Surface<'_>) -> bool {
151        self.inner.is_surface_supported(&surface.inner)
152    }
153
154    /// The features which can be used to create devices on this adapter.
155    pub fn features(&self) -> Features {
156        self.inner.features()
157    }
158
159    /// The best limits which can be used to create devices on this adapter.
160    pub fn limits(&self) -> Limits {
161        self.inner.limits()
162    }
163
164    /// Get info about the adapter itself.
165    pub fn get_info(&self) -> AdapterInfo {
166        self.inner.get_info()
167    }
168
169    /// Get info about the adapter itself.
170    pub fn get_downlevel_capabilities(&self) -> DownlevelCapabilities {
171        self.inner.downlevel_capabilities()
172    }
173
174    /// Returns the features supported for a given texture format by this adapter.
175    ///
176    /// Note that the WebGPU spec further restricts the available usages/features.
177    /// To disable these restrictions on a device, request the [`Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES`] feature.
178    pub fn get_texture_format_features(&self, format: TextureFormat) -> TextureFormatFeatures {
179        self.inner.get_texture_format_features(format)
180    }
181
182    /// Generates a timestamp using the clock used by the presentation engine.
183    ///
184    /// When comparing completely opaque timestamp systems, we need a way of generating timestamps that signal
185    /// the exact same time. You can do this by calling your own timestamp function immediately after a call to
186    /// this function. This should result in timestamps that are 0.5 to 5 microseconds apart. There are locks
187    /// that must be taken during the call, so don't call your function before.
188    ///
189    /// ```no_run
190    /// # let adapter: wgpu::Adapter = panic!();
191    /// # let some_code = || wgpu::PresentationTimestamp::INVALID_TIMESTAMP;
192    /// use std::time::{Duration, Instant};
193    /// let presentation = adapter.get_presentation_timestamp();
194    /// let instant = Instant::now();
195    ///
196    /// // We can now turn a new presentation timestamp into an Instant.
197    /// let some_pres_timestamp = some_code();
198    /// let duration = Duration::from_nanos((some_pres_timestamp.0 - presentation.0) as u64);
199    /// let new_instant: Instant = instant + duration;
200    /// ```
201    //
202    /// [Instant]: std::time::Instant
203    pub fn get_presentation_timestamp(&self) -> PresentationTimestamp {
204        self.inner.get_presentation_timestamp()
205    }
206
207    /// Returns the supported cooperative matrix configurations for this adapter.
208    ///
209    /// Cooperative matrices enable hardware-accelerated matrix multiply-accumulate
210    /// operations where threads in a subgroup collectively process matrix tiles.
211    ///
212    /// Returns an empty vector if cooperative matrices are not supported.
213    ///
214    /// Requires [`Features::EXPERIMENTAL_COOPERATIVE_MATRIX`] to be meaningful.
215    pub fn cooperative_matrix_properties(&self) -> Vec<CooperativeMatrixProperties> {
216        self.inner.cooperative_matrix_properties()
217    }
218}