Skip to main content

wgpu/api/
device.rs

1use alloc::{boxed::Box, string::String, sync::Arc, vec};
2#[cfg(wgpu_core)]
3use core::ops::Deref;
4use core::{error, fmt, future::Future, marker::PhantomData};
5
6use crate::api::blas::{Blas, BlasGeometrySizeDescriptors, CreateBlasDescriptor};
7use crate::api::tlas::{CreateTlasDescriptor, Tlas};
8use crate::util::Mutex;
9use crate::*;
10
11/// Open connection to a graphics and/or compute device.
12///
13/// Responsible for the creation of most rendering and compute resources.
14/// These are then used in commands, which are submitted to a [`Queue`].
15///
16/// A device may be requested from an adapter with [`Adapter::request_device`].
17///
18/// Corresponds to [WebGPU `GPUDevice`](https://gpuweb.github.io/gpuweb/#gpu-device).
19#[derive(Debug, Clone)]
20pub struct Device {
21    pub(crate) inner: dispatch::DispatchDevice,
22}
23#[cfg(send_sync)]
24static_assertions::assert_impl_all!(Device: Send, Sync);
25
26crate::cmp::impl_eq_ord_hash_proxy!(Device => .inner);
27
28/// Describes a [`Device`].
29///
30/// For use with [`Adapter::request_device`].
31///
32/// Corresponds to [WebGPU `GPUDeviceDescriptor`](
33/// https://gpuweb.github.io/gpuweb/#dictdef-gpudevicedescriptor).
34pub type DeviceDescriptor<'a> = wgt::DeviceDescriptor<Label<'a>>;
35static_assertions::assert_impl_all!(DeviceDescriptor<'_>: Send, Sync);
36
37impl Device {
38    #[cfg(custom)]
39    /// Returns custom implementation of Device (if custom backend and is internally T)
40    pub fn as_custom<T: custom::DeviceInterface>(&self) -> Option<&T> {
41        self.inner.as_custom()
42    }
43
44    #[cfg(custom)]
45    /// Creates Device from custom implementation
46    pub fn from_custom<T: custom::DeviceInterface>(device: T) -> Self {
47        Self {
48            inner: dispatch::DispatchDevice::custom(device),
49        }
50    }
51
52    /// Constructs a stub device for testing using [`Backend::Noop`].
53    ///
54    /// This is a convenience function which avoids the configuration, `async`, and fallibility
55    /// aspects of constructing a device through `Instance`.
56    #[cfg(feature = "noop")]
57    pub fn noop(desc: &DeviceDescriptor<'_>) -> (Device, Queue) {
58        use core::future::Future as _;
59        use core::pin::pin;
60        use core::task;
61        let ctx = &mut task::Context::from_waker(task::Waker::noop());
62
63        let instance = Instance::new(InstanceDescriptor {
64            backends: Backends::NOOP,
65            backend_options: BackendOptions {
66                noop: NoopBackendOptions::enabled(),
67                ..Default::default()
68            },
69            ..InstanceDescriptor::new_without_display_handle()
70        });
71
72        // Both of these futures are trivial and should complete instantaneously,
73        // so we do not need an executor and can just poll them once.
74        let task::Poll::Ready(Ok(adapter)) =
75            pin!(instance.request_adapter(&RequestAdapterOptions::default())).poll(ctx)
76        else {
77            unreachable!()
78        };
79        let task::Poll::Ready(Ok(device_and_queue)) = pin!(adapter.request_device(desc)).poll(ctx)
80        else {
81            unreachable!()
82        };
83        device_and_queue
84    }
85
86    /// Check for resource cleanups and mapping callbacks. Will block if [`PollType::Wait`] is passed.
87    ///
88    /// Return `true` if the queue is empty, or `false` if there are more queue
89    /// submissions still in flight. (Note that, unless access to the [`Queue`] is
90    /// coordinated somehow, this information could be out of date by the time
91    /// the caller receives it. `Queue`s can be shared between threads, so
92    /// other threads could submit new work at any time.)
93    ///
94    /// When running on WebGPU, this is a no-op. `Device`s are automatically polled.
95    pub fn poll(&self, poll_type: PollType) -> Result<crate::PollStatus, crate::PollError> {
96        self.inner.poll(poll_type.map_index(|s| s.index))
97    }
98
99    /// The [features][Features] which can be used on this device.
100    ///
101    /// This will be equal to the [`required_features`][DeviceDescriptor::required_features]
102    /// specified when creating the device.
103    /// No additional features can be used, even if the underlying adapter can support them.
104    #[must_use]
105    pub fn features(&self) -> Features {
106        self.inner.features()
107    }
108
109    /// The limits which can be used on this device.
110    ///
111    /// This will be equal to the [`required_limits`][DeviceDescriptor::required_limits]
112    /// specified when creating the device.
113    /// No better limits can be used, even if the underlying adapter can support them.
114    #[must_use]
115    pub fn limits(&self) -> Limits {
116        self.inner.limits()
117    }
118
119    /// Get info about the adapter that this device was created from.
120    pub fn adapter_info(&self) -> AdapterInfo {
121        self.inner.adapter_info()
122    }
123
124    /// Creates a shader module.
125    ///
126    /// <div class="warning">
127    // NOTE: Keep this in sync with `naga::front::wgsl::parse_str`!
128    // NOTE: Keep this in sync with `wgpu_core::Global::device_create_shader_module`!
129    ///
130    /// This function may consume a lot of stack space. Compiler-enforced limits for parsing
131    /// recursion exist; if shader compilation runs into them, it will return an error gracefully.
132    /// However, on some build profiles and platforms, the default stack size for a thread may be
133    /// exceeded before this limit is reached during parsing. Callers should ensure that there is
134    /// enough stack space for this, particularly if calls to this method are exposed to user
135    /// input.
136    ///
137    /// </div>
138    #[must_use]
139    pub fn create_shader_module(&self, desc: ShaderModuleDescriptor<'_>) -> ShaderModule {
140        let module = self
141            .inner
142            .create_shader_module(desc, wgt::ShaderRuntimeChecks::checked());
143        ShaderModule { inner: module }
144    }
145
146    /// Deprecated: Use [`create_shader_module_trusted`][csmt] instead.
147    ///
148    /// # Safety
149    ///
150    /// See [`create_shader_module_trusted`][csmt].
151    ///
152    /// [csmt]: Self::create_shader_module_trusted
153    #[deprecated(
154        since = "24.0.0",
155        note = "Use `Device::create_shader_module_trusted(desc, wgpu::ShaderRuntimeChecks::unchecked())` instead."
156    )]
157    #[must_use]
158    pub unsafe fn create_shader_module_unchecked(
159        &self,
160        desc: ShaderModuleDescriptor<'_>,
161    ) -> ShaderModule {
162        unsafe { self.create_shader_module_trusted(desc, crate::ShaderRuntimeChecks::unchecked()) }
163    }
164
165    /// Creates a shader module with flags to dictate runtime checks.
166    ///
167    /// When running on WebGPU, this will merely call [`create_shader_module`][csm].
168    ///
169    /// # Safety
170    ///
171    /// In contrast with [`create_shader_module`][csm] this function
172    /// creates a shader module with user-customizable runtime checks which allows shaders to
173    /// perform operations which can lead to undefined behavior like indexing out of bounds,
174    /// thus it's the caller responsibility to pass a shader which doesn't perform any of this
175    /// operations.
176    ///
177    /// See the documentation for [`ShaderRuntimeChecks`] for more information about specific checks.
178    ///
179    /// [csm]: Self::create_shader_module
180    #[must_use]
181    pub unsafe fn create_shader_module_trusted(
182        &self,
183        desc: ShaderModuleDescriptor<'_>,
184        runtime_checks: crate::ShaderRuntimeChecks,
185    ) -> ShaderModule {
186        let module = self.inner.create_shader_module(desc, runtime_checks);
187        ShaderModule { inner: module }
188    }
189
190    /// Creates a shader module which will bypass wgpu's shader tooling and validation and be used directly by the backend.
191    ///
192    /// # Safety
193    ///
194    /// This function passes data to the backend as-is and can potentially result in a
195    /// driver crash or bogus behaviour. No attempt is made to ensure that data is valid.
196    #[must_use]
197    pub unsafe fn create_shader_module_passthrough(
198        &self,
199        desc: ShaderModuleDescriptorPassthrough<'_>,
200    ) -> ShaderModule {
201        let module = unsafe { self.inner.create_shader_module_passthrough(&desc) };
202        ShaderModule { inner: module }
203    }
204
205    /// Reads the link of every program this GL `Device` built that no
206    /// submission has drawn with yet, and returns whether there was one;
207    /// nothing on another backend. A link is read at the first submission
208    /// that draws with its program, and the read waits for the GPU to reach
209    /// the link: call this between frames, once the GPU has done the work
210    /// submitted after the last pipeline was created, and that first frame
211    /// reads none.
212    #[cfg(wgpu_core)]
213    pub fn read_program_links(&self) -> bool {
214        self.inner
215            .as_core_opt()
216            .is_some_and(crate::backend::wgpu_core::CoreDevice::read_program_links)
217    }
218
219    /// Creates a shader module from GLSL ES templates, one per entry point,
220    /// on a WebGL device; `None` on a device of another backend.
221    ///
222    /// A pipeline's constants are defined as the templates' macros, and the
223    /// browser compiles the GLSL: no naga runs. The browser checks the GLSL,
224    /// so unlike [`Device::create_shader_module_passthrough`] this is safe.
225    #[cfg(webgl)]
226    #[must_use]
227    pub fn create_shader_module_glsl_templates(
228        &self,
229        label: Label<'_>,
230        templates: &'static [hal::GlslTemplate],
231    ) -> Option<ShaderModule> {
232        let device = self.inner.as_core_opt()?;
233        Some(ShaderModule {
234            inner: device.create_shader_module_glsl_templates(label, templates),
235        })
236    }
237
238    /// Creates an empty [`CommandEncoder`].
239    #[must_use]
240    pub fn create_command_encoder(&self, desc: &CommandEncoderDescriptor<'_>) -> CommandEncoder {
241        let encoder = self.inner.create_command_encoder(desc);
242        // Each encoder starts with its own deferred-action store that travels
243        // with the CommandBuffer produced by finish().
244        CommandEncoder {
245            inner: encoder,
246            actions: Default::default(),
247        }
248    }
249
250    /// Creates an empty [`RenderBundleEncoder`].
251    #[must_use]
252    pub fn create_render_bundle_encoder<'a>(
253        &self,
254        desc: &RenderBundleEncoderDescriptor<'_>,
255    ) -> RenderBundleEncoder<'a> {
256        let encoder = self.inner.create_render_bundle_encoder(desc);
257        RenderBundleEncoder {
258            inner: encoder,
259            _p: PhantomData,
260        }
261    }
262
263    /// Creates a new [`BindGroup`].
264    #[must_use]
265    pub fn create_bind_group(&self, desc: &BindGroupDescriptor<'_>) -> BindGroup {
266        let group = self.inner.create_bind_group(desc);
267        BindGroup { inner: group }
268    }
269
270    /// Creates a [`BindGroupLayout`].
271    #[must_use]
272    pub fn create_bind_group_layout(
273        &self,
274        desc: &BindGroupLayoutDescriptor<'_>,
275    ) -> BindGroupLayout {
276        let layout = self.inner.create_bind_group_layout(desc);
277        BindGroupLayout { inner: layout }
278    }
279
280    /// Creates a [`PipelineLayout`].
281    #[must_use]
282    pub fn create_pipeline_layout(&self, desc: &PipelineLayoutDescriptor<'_>) -> PipelineLayout {
283        let layout = self.inner.create_pipeline_layout(desc);
284        PipelineLayout { inner: layout }
285    }
286
287    /// Creates a [`RenderPipeline`].
288    #[must_use]
289    pub fn create_render_pipeline(&self, desc: &RenderPipelineDescriptor<'_>) -> RenderPipeline {
290        let pipeline = self.inner.create_render_pipeline(desc);
291        RenderPipeline { inner: pipeline }
292    }
293
294    /// Creates a mesh shader based [`RenderPipeline`].
295    #[must_use]
296    pub fn create_mesh_pipeline(&self, desc: &MeshPipelineDescriptor<'_>) -> RenderPipeline {
297        let pipeline = self.inner.create_mesh_pipeline(desc);
298        RenderPipeline { inner: pipeline }
299    }
300
301    /// Creates a [`ComputePipeline`].
302    #[must_use]
303    pub fn create_compute_pipeline(&self, desc: &ComputePipelineDescriptor<'_>) -> ComputePipeline {
304        let pipeline = self.inner.create_compute_pipeline(desc);
305        ComputePipeline { inner: pipeline }
306    }
307
308    /// Creates a [`Buffer`].
309    #[must_use]
310    pub fn create_buffer(&self, desc: &BufferDescriptor<'_>) -> Buffer {
311        let map_context = MapContext::new(desc.mapped_at_creation.then_some(0..desc.size));
312
313        let buffer = self.inner.create_buffer(desc);
314
315        Buffer {
316            inner: buffer,
317            map_context: Arc::new(Mutex::new(map_context)),
318            size: desc.size,
319            usage: desc.usage,
320        }
321    }
322
323    /// Creates a new [`Texture`].
324    ///
325    /// `desc` specifies the general format of the texture.
326    #[must_use]
327    pub fn create_texture(&self, desc: &TextureDescriptor<'_>) -> Texture {
328        let texture = self.inner.create_texture(desc);
329
330        Texture {
331            inner: texture,
332            descriptor: TextureDescriptor {
333                label: None,
334                view_formats: &[],
335                ..desc.clone()
336            },
337        }
338    }
339
340    /// Creates a [`Texture`] from a wgpu-hal Texture.
341    ///
342    /// # Types
343    ///
344    /// The type of `A::Texture` depends on the backend:
345    ///
346    #[doc = crate::macros::hal_type_vulkan!("Texture")]
347    #[doc = crate::macros::hal_type_metal!("Texture")]
348    #[doc = crate::macros::hal_type_dx12!("Texture")]
349    #[doc = crate::macros::hal_type_gles!("Texture")]
350    ///
351    /// On [`Backend::BrowserWebGpu`], use `Device::create_texture_from_webgpu_handle()` instead.
352    ///
353    /// # `initial_state`
354    ///
355    /// If the resource has already been initialized, `initial_state` should be
356    /// set to the [`wgt::TextureUses`] state of the wrapped resource.  It will
357    /// be used as the source state (`oldLayout` / `StateBefore`) of the first
358    /// barrier emitted on the texture.
359    ///
360    /// If the resource has not been initialized (or if the existing contents
361    /// may be discarded), `initial_state` may be set to
362    /// `TextureUses::UNINITIALIZED`.
363    ///
364    /// # Safety
365    ///
366    /// - `hal_texture` must be created from this device internal handle
367    /// - `hal_texture` must be created respecting `desc`
368    /// - `hal_texture` must be initialized
369    /// - `initial_state`, if it is not `TextureUses::UNINITIALIZED`, must
370    ///   match the actual driver-side layout/state of the wrapped resource at
371    ///   the moment of wrap.
372    #[cfg(wgpu_core)]
373    #[must_use]
374    pub unsafe fn create_texture_from_hal<A: hal::Api>(
375        &self,
376        hal_texture: A::Texture,
377        desc: &TextureDescriptor<'_>,
378        initial_state: wgt::TextureUses,
379    ) -> Texture {
380        let texture = unsafe {
381            let core_device = self.inner.as_core();
382            core_device.context.create_texture_from_hal::<A>(
383                hal_texture,
384                core_device,
385                desc,
386                initial_state,
387            )
388        };
389        Texture {
390            inner: texture.into(),
391            descriptor: TextureDescriptor {
392                label: None,
393                view_formats: &[],
394                ..desc.clone()
395            },
396        }
397    }
398
399    /// Wraps a foreign [`webgpu::GpuTexture`] (e.g. a canvas `getCurrentTexture()` result)
400    /// as a [`Texture`] without any copy.
401    ///
402    /// The wrapped texture is *external*: dropping the returned `Texture` (or
403    /// calling [`Texture::destroy`] on it) does **not** call `GpuTexture.destroy()`
404    /// on the underlying handle - its lifetime is the caller's responsibility.
405    ///
406    /// If `drop_callback` is `Some`, it fires when wgpu releases its last
407    /// reference to the wrapped handle. wgpu never calls `GpuTexture.destroy()`
408    /// itself on a wrapped texture; to hand the handle's lifetime to wgpu,
409    /// supply a callback that calls `GpuTexture.destroy()`. The callback can
410    /// also be used to free a pool slot or notify dependent code that wgpu is
411    /// done with the handle. Pass `None` if the caller manages the handle's
412    /// lifetime entirely on their own.
413    ///
414    /// This is the WebGPU counterpart of [`Self::create_texture_from_hal`].
415    /// A `Some` `drop_callback` plays the same role as `wgpu_hal::DropCallback`
416    /// does on the Vulkan backend. The `None` case differs: here the texture is
417    /// always external and wgpu never destroys it, whereas on Vulkan a `None`
418    /// callback means wgpu takes ownership of the image and destroys it.
419    ///
420    /// The caller must guarantee:
421    ///
422    /// 1. `texture` was produced by the same underlying `GpuDevice` that this `Device` wraps.
423    /// 2. `desc.format`, `desc.size`, `desc.usage`, `desc.dimension`,
424    ///    `desc.mip_level_count`, and `desc.sample_count` match the actual
425    ///    `GPUTexture`'s reflected values. wgpu stores these verbatim and
426    ///    returns them from [`Texture::size`], [`Texture::format`], etc.
427    ///    without re-checking the handle; a mismatch yields silently incorrect
428    ///    metadata and, downstream, `GPUValidationError`s rather than memory
429    ///    unsafety (the browser bounds every access).
430    /// 3. The underlying `GpuTexture` must remain alive for as long as wgpu
431    ///    may use it (e.g. until any submitted command buffer that references
432    ///    it has finished executing). If `drop_callback` is `Some`, it is
433    ///    sufficient to keep the handle alive until the callback fires.
434    #[cfg(webgpu)]
435    #[must_use]
436    pub fn create_texture_from_webgpu_handle(
437        &self,
438        texture: webgpu::GpuTexture,
439        desc: &TextureDescriptor<'_>,
440        drop_callback: Option<webgpu::DropCallback>,
441    ) -> Texture {
442        let inner = self
443            .inner
444            .as_webgpu()
445            .wrap_external_texture(texture, drop_callback);
446        Texture {
447            inner,
448            descriptor: TextureDescriptor {
449                label: None,
450                view_formats: &[],
451                ..desc.clone()
452            },
453        }
454    }
455
456    /// Compiles every render pipeline this `Device` creates from now on in
457    /// the background, when it is on the WebGPU backend, and returns whether
458    /// it does. The browser compiles each through `createRenderPipelineAsync`,
459    /// beside the others; until it has, the draws that use the pipeline are
460    /// left out, and from then on they draw. Created one after another
461    /// instead, new pipelines hold the browser's GPU process, and every
462    /// frame of the page, until each compiled.
463    #[cfg(webgpu)]
464    pub fn compile_pipelines_in_background(&self) -> bool {
465        self.inner
466            .as_webgpu_opt()
467            .map(crate::backend::webgpu::WebDevice::compile_pipelines_in_background)
468            .is_some()
469    }
470
471    /// Whether a pipeline compiling in the background
472    /// ([`Self::compile_pipelines_in_background`]) has neither compiled nor
473    /// failed yet; `false` on every other backend. The browser compiles
474    /// several beside each other, on threads the page's frames need too.
475    pub fn compiles_in_background(&self) -> bool {
476        #[cfg(webgpu)]
477        if let Some(device) = self.inner.as_webgpu_opt() {
478            return device.compiles_in_background();
479        }
480        false
481    }
482
483    /// Takes the pipelines compiling in the background whose draws a pass
484    /// left out since the last call, with a future that resolves once each
485    /// compiled or failed; `None` when no pass left one out. A frame that
486    /// left their draws out draws again then. A pipeline created ahead of
487    /// its first draw, which compiles before any pass needs it, is never
488    /// taken.
489    #[cfg(webgpu)]
490    pub fn take_background_pipelines(
491        &self,
492    ) -> Option<impl core::future::Future<Output = ()> + 'static> {
493        self.inner
494            .as_webgpu_opt()
495            .and_then(crate::backend::webgpu::WebDevice::take_background_pipelines)
496    }
497
498    /// Asks the browser for the render pipelines that compile in the
499    /// background ([`Self::compile_pipelines_in_background`]). Returns a
500    /// future that resolves once the page holds every one of them compiled
501    /// before the browser's GPU process answered; `None` when none
502    /// compiles. Chrome hands the page a compiled pipeline only after the
503    /// page sent its GPU process a call. A frame drawn right after a long
504    /// task finds pipelines compiled long before still compiling, unless
505    /// the page awaited this future first.
506    #[cfg(webgpu)]
507    pub fn deliver_background_pipelines(
508        &self,
509    ) -> Option<impl core::future::Future<Output = ()> + 'static> {
510        self.inner
511            .as_webgpu_opt()
512            .and_then(crate::backend::webgpu::WebDevice::deliver_background_pipelines)
513    }
514
515    /// Returns the underlying [`webgpu::GpuDevice`] handle if this `Device`
516    /// is on the WebGPU backend, otherwise `None`.
517    #[cfg(webgpu)]
518    pub fn as_webgpu(&self) -> Option<&webgpu::GpuDevice> {
519        self.inner.as_webgpu_opt().map(|wd| &wd.inner)
520    }
521
522    /// Creates a new [`ExternalTexture`].
523    #[must_use]
524    pub fn create_external_texture(
525        &self,
526        desc: &ExternalTextureDescriptor<'_>,
527        planes: &[&TextureView],
528    ) -> ExternalTexture {
529        let external_texture = self.inner.create_external_texture(desc, planes);
530
531        ExternalTexture {
532            inner: external_texture,
533        }
534    }
535
536    /// Creates a [`Buffer`] from a wgpu-hal Buffer.
537    ///
538    /// # Types
539    ///
540    /// The type of `A::Buffer` depends on the backend:
541    ///
542    #[doc = crate::macros::hal_type_vulkan!("Buffer")]
543    #[doc = crate::macros::hal_type_metal!("Buffer")]
544    #[doc = crate::macros::hal_type_dx12!("Buffer")]
545    #[doc = crate::macros::hal_type_gles!("Buffer")]
546    ///
547    /// # Safety
548    ///
549    /// - `hal_buffer` must be created from this device internal handle
550    /// - `hal_buffer` must be created respecting `desc`
551    /// - `hal_buffer` must be initialized
552    /// - `hal_buffer` must not have zero size
553    #[cfg(wgpu_core)]
554    #[must_use]
555    pub unsafe fn create_buffer_from_hal<A: hal::Api>(
556        &self,
557        hal_buffer: A::Buffer,
558        desc: &BufferDescriptor<'_>,
559    ) -> Buffer {
560        let map_context = MapContext::new(desc.mapped_at_creation.then_some(0..desc.size));
561
562        let buffer = unsafe {
563            let core_device = self.inner.as_core();
564            core_device
565                .context
566                .create_buffer_from_hal::<A>(hal_buffer, core_device, desc)
567        };
568
569        Buffer {
570            inner: buffer.into(),
571            map_context: Arc::new(Mutex::new(map_context)),
572            size: desc.size,
573            usage: desc.usage,
574        }
575    }
576
577    /// Creates a new [`Sampler`].
578    ///
579    /// `desc` specifies the behavior of the sampler.
580    #[must_use]
581    pub fn create_sampler(&self, desc: &SamplerDescriptor<'_>) -> Sampler {
582        let sampler = self.inner.create_sampler(desc);
583        Sampler { inner: sampler }
584    }
585
586    /// Creates a new [`QuerySet`].
587    #[must_use]
588    pub fn create_query_set(&self, desc: &QuerySetDescriptor<'_>) -> QuerySet {
589        let query_set = self.inner.create_query_set(desc);
590        QuerySet {
591            inner: query_set,
592            ty: desc.ty,
593            count: desc.count,
594        }
595    }
596
597    /// Set a callback which will be called for all errors that are not handled in error scopes.
598    pub fn on_uncaptured_error(&self, handler: Arc<dyn UncapturedErrorHandler>) {
599        self.inner.on_uncaptured_error(handler)
600    }
601
602    /// Push an error scope on this device's thread-local error scope
603    /// stack. All operations on this device, or on resources created
604    /// from this device, will have their errors captured by this scope
605    /// until the scope is popped.
606    ///
607    /// Scopes must be popped in reverse order to their creation. If
608    /// a guard is dropped without being `pop()`ped, the scope will be
609    /// popped, and the captured errors will be dropped.
610    ///
611    /// Multiple error scopes may be active at one time, forming a stack.
612    /// Each error will be reported to the inner-most scope that matches
613    /// its filter.
614    ///
615    /// With the `std` feature enabled, this stack is **thread-local**.
616    /// Without, this is **global** to all threads.
617    ///
618    /// ```rust
619    /// # async move {
620    /// # let device: wgpu::Device = unreachable!();
621    /// let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
622    ///
623    /// // ...
624    /// // do work that may produce validation errors
625    /// // ...
626    ///
627    /// // pop the error scope and get a future for the result
628    /// let error_future = error_scope.pop();
629    ///
630    /// // await the future to get the error, if any
631    /// let error = error_future.await;
632    /// # };
633    /// ```
634    pub fn push_error_scope(&self, filter: ErrorFilter) -> ErrorScopeGuard {
635        let index = self.inner.push_error_scope(filter);
636        ErrorScopeGuard {
637            device: self.inner.clone(),
638            index,
639            popped: false,
640            _phantom: PhantomData,
641        }
642    }
643
644    /// Starts a capture in the attached graphics debugger.
645    ///
646    /// This behaves differently depending on which graphics debugger is attached:
647    ///
648    /// - Renderdoc: Calls [`StartFrameCapture(device, NULL)`][rd].
649    /// - Xcode: Creates a capture with [`MTLCaptureManager`][xcode].
650    /// - None: No action is taken.
651    ///
652    /// # Safety
653    ///
654    /// - There should not be any other captures currently active.
655    /// - All other safety rules are defined by the graphics debugger, see the
656    ///   documentation for the specific debugger.
657    /// - In general, graphics debuggers can easily cause crashes, so this isn't
658    ///   ever guaranteed to be sound.
659    ///
660    /// # Tips
661    ///
662    /// - Debuggers need to capture both the recording of the commands and the
663    ///   submission of the commands to the GPU. Try to wrap all of your
664    ///   gpu work in a capture.
665    /// - If you encounter issues, try waiting for the GPU to finish all work
666    ///   before stopping the capture.
667    ///
668    /// [rd]: https://renderdoc.org/docs/in_application_api.html#_CPPv417StartFrameCapture23RENDERDOC_DevicePointer22RENDERDOC_WindowHandle
669    /// [xcode]: https://developer.apple.com/documentation/metal/mtlcapturemanager
670    #[doc(alias = "start_renderdoc_capture")]
671    #[doc(alias = "start_xcode_capture")]
672    pub unsafe fn start_graphics_debugger_capture(&self) {
673        unsafe { self.inner.start_graphics_debugger_capture() }
674    }
675
676    /// Stops the current capture in the attached graphics debugger.
677    ///
678    /// This behaves differently depending on which graphics debugger is attached:
679    ///
680    /// - Renderdoc: Calls [`EndFrameCapture(device, NULL)`][rd].
681    /// - Xcode: Stops the capture with [`MTLCaptureManager`][xcode].
682    /// - None: No action is taken.
683    ///
684    /// # Safety
685    ///
686    /// - There should be a capture currently active.
687    /// - All other safety rules are defined by the graphics debugger, see the
688    ///   documentation for the specific debugger.
689    /// - In general, graphics debuggers can easily cause crashes, so this isn't
690    ///   ever guaranteed to be sound.
691    ///
692    /// # Tips
693    ///
694    /// - If you encounter issues, try to submit all work to the GPU, and waiting
695    ///   for that work to finish before stopping the capture.
696    ///
697    /// [rd]: https://renderdoc.org/docs/in_application_api.html#_CPPv415EndFrameCapture23RENDERDOC_DevicePointer22RENDERDOC_WindowHandle
698    /// [xcode]: https://developer.apple.com/documentation/metal/mtlcapturemanager
699    #[doc(alias = "stop_renderdoc_capture")]
700    #[doc(alias = "stop_xcode_capture")]
701    pub unsafe fn stop_graphics_debugger_capture(&self) {
702        unsafe { self.inner.stop_graphics_debugger_capture() }
703    }
704
705    /// Query internal counters from the native backend for debugging purposes.
706    ///
707    /// Some backends may not set all counters, or may not set any counter at all.
708    /// The `counters` cargo feature must be enabled for any counter to be set.
709    ///
710    /// If a counter is not set, its contains its default value (zero).
711    #[must_use]
712    pub fn get_internal_counters(&self) -> wgt::InternalCounters {
713        self.inner.get_internal_counters()
714    }
715
716    /// Generate an GPU memory allocation report if the underlying backend supports it.
717    ///
718    /// Backends that do not support producing these reports return `None`. A backend may
719    /// Support it and still return `None` if it is not using performing sub-allocation,
720    /// for example as a workaround for driver issues.
721    #[must_use]
722    pub fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
723        self.inner.generate_allocator_report()
724    }
725
726    /// Get the [`wgpu_hal`] device from this `Device`.
727    ///
728    /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
729    /// and pass that struct to the to the `A` type parameter.
730    ///
731    /// Returns a guard that dereferences to the type of the hal backend
732    /// which implements [`A::Device`].
733    ///
734    /// # Types
735    ///
736    /// The returned type depends on the backend:
737    ///
738    #[doc = crate::macros::hal_type_vulkan!("Device")]
739    #[doc = crate::macros::hal_type_metal!("Device")]
740    #[doc = crate::macros::hal_type_dx12!("Device")]
741    #[doc = crate::macros::hal_type_gles!("Device")]
742    ///
743    /// # Errors
744    ///
745    /// This method will return None if:
746    /// - The device is not from the backend specified by `A`.
747    /// - The device is from the `webgpu` or `custom` backend.
748    ///
749    /// On the `webgpu` backend, use `as_webgpu` instead.
750    ///
751    /// # Safety
752    ///
753    /// - The returned resource must not be destroyed unless the guard
754    ///   is the last reference to it and it is not in use by the GPU.
755    ///   The guard and handle may be dropped at any time however.
756    /// - All the safety requirements of wgpu-hal must be upheld.
757    ///
758    /// [`A::Device`]: hal::Api::Device
759    #[cfg(wgpu_core)]
760    pub unsafe fn as_hal<A: hal::Api>(
761        &self,
762    ) -> Option<impl Deref<Target = A::Device> + WasmNotSendSync> {
763        let device = self.inner.as_core_opt()?;
764        unsafe { device.context.device_as_hal::<A>(device) }
765    }
766
767    /// Destroy this device.
768    pub fn destroy(&self) {
769        self.inner.destroy()
770    }
771
772    /// Set a DeviceLostCallback on this device.
773    pub fn set_device_lost_callback(
774        &self,
775        callback: impl Fn(DeviceLostReason, String) + Send + 'static,
776    ) {
777        self.inner.set_device_lost_callback(Box::new(callback))
778    }
779
780    /// Create a [`PipelineCache`] with initial data
781    ///
782    /// This can be passed to [`Device::create_compute_pipeline`]
783    /// and [`Device::create_render_pipeline`] to either accelerate these
784    /// or add the cache results from those.
785    ///
786    /// # Safety
787    ///
788    /// If the `data` field of `desc` is set, it must have previously been returned from a call
789    /// to [`PipelineCache::get_data`][^saving]. This `data` will only be used if it came
790    /// from an adapter with the same [`util::pipeline_cache_key`].
791    /// This *is* compatible across wgpu versions, as any data format change will
792    /// be accounted for.
793    ///
794    /// It is *not* supported to bring caches from previous direct uses of backend APIs
795    /// into this method.
796    ///
797    /// # Errors
798    ///
799    /// Returns an error value if:
800    ///  * the [`PIPELINE_CACHE`](wgt::Features::PIPELINE_CACHE) feature is not enabled
801    ///  * this device is invalid; or
802    ///  * the device is out of memory
803    ///
804    /// This method also returns an error value if:
805    ///  * The `fallback` field on `desc` is false; and
806    ///  * the `data` provided would not be used[^data_not_used]
807    ///
808    /// If an error value is used in subsequent calls, default caching will be used.
809    ///
810    /// [^saving]: We do recognise that saving this data to disk means this condition
811    /// is impossible to fully prove. Consider the risks for your own application in this case.
812    ///
813    /// [^data_not_used]: This data may be not used if: the data was produced by a prior
814    /// version of wgpu; or was created for an incompatible adapter, or there was a GPU driver
815    /// update. In some cases, the data might not be used and a real value is returned,
816    /// this is left to the discretion of GPU drivers.
817    #[must_use]
818    pub unsafe fn create_pipeline_cache(
819        &self,
820        desc: &PipelineCacheDescriptor<'_>,
821    ) -> PipelineCache {
822        let cache = unsafe { self.inner.create_pipeline_cache(desc) };
823        PipelineCache { inner: cache }
824    }
825}
826
827/// [`Features::EXPERIMENTAL_RAY_QUERY`] must be enabled on the device in order to call these functions.
828impl Device {
829    /// Create a bottom level acceleration structure, used inside a top level acceleration structure for ray tracing.
830    /// - `desc`: The descriptor of the acceleration structure.
831    /// - `sizes`: Size descriptor limiting what can be built into the acceleration structure.
832    ///
833    /// # Validation
834    /// If any of the following is not satisfied a validation error is generated
835    ///
836    /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_QUERY`] enabled.
837    /// if `sizes` is [`BlasGeometrySizeDescriptors::Triangles`] then the following must be satisfied
838    /// - For every geometry descriptor (for the purposes this is called `geo_desc`) of `sizes.descriptors` the following must be satisfied:
839    ///     - `geo_desc.vertex_format` must be within allowed formats (allowed formats for a given feature set
840    ///       may be queried with [`Features::allowed_vertex_formats_for_blas`]).
841    ///     - Both or neither of `geo_desc.index_format` and `geo_desc.index_count` must be provided.
842    ///
843    /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY
844    /// [`Features::allowed_vertex_formats_for_blas`]: wgt::Features::allowed_vertex_formats_for_blas
845    #[must_use]
846    pub fn create_blas(
847        &self,
848        desc: &CreateBlasDescriptor<'_>,
849        sizes: BlasGeometrySizeDescriptors,
850    ) -> Blas {
851        let (handle, blas) = self.inner.create_blas(desc, sizes);
852
853        Blas {
854            inner: blas,
855            handle,
856        }
857    }
858
859    /// Create a top level acceleration structure, used for ray tracing.
860    /// - `desc`: The descriptor of the acceleration structure.
861    ///
862    /// # Validation
863    /// If any of the following is not satisfied a validation error is generated
864    ///
865    /// The device ***must*** have [`Features::EXPERIMENTAL_RAY_QUERY`] enabled.
866    ///
867    /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY
868    #[must_use]
869    pub fn create_tlas(&self, desc: &CreateTlasDescriptor<'_>) -> Tlas {
870        let tlas = self.inner.create_tlas(desc);
871
872        Tlas {
873            inner: tlas,
874            instances: vec![None; desc.max_instances as usize],
875            lowest_unmodified: 0,
876        }
877    }
878}
879
880/// Requesting a device from an [`Adapter`] failed.
881#[derive(Clone, Debug)]
882pub struct RequestDeviceError {
883    pub(crate) inner: RequestDeviceErrorKind,
884}
885
886impl RequestDeviceError {
887    /// Construct an error from a custom backend message. This is mainly useful for custom backends.
888    #[cfg(custom)]
889    pub fn from_message(message: String) -> Self {
890        RequestDeviceError {
891            inner: RequestDeviceErrorKind::Custom(message),
892        }
893    }
894}
895
896#[derive(Clone, Debug)]
897pub(crate) enum RequestDeviceErrorKind {
898    /// Error from [`wgpu_core`].
899    // must match dependency cfg
900    #[cfg(wgpu_core)]
901    Core(wgc::instance::RequestDeviceError),
902
903    /// Error from web API that was called by `wgpu` to request a device.
904    ///
905    /// (This is currently never used by the webgl backend, but it could be.)
906    #[cfg(webgpu)]
907    WebGpu(String),
908
909    /// Error from a custom backend.
910    #[cfg(custom)]
911    Custom(String),
912}
913
914static_assertions::assert_impl_all!(RequestDeviceError: Send, Sync);
915
916impl fmt::Display for RequestDeviceError {
917    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
918        match &self.inner {
919            #[cfg(wgpu_core)]
920            RequestDeviceErrorKind::Core(error) => error.fmt(_f),
921            #[cfg(webgpu)]
922            RequestDeviceErrorKind::WebGpu(error) => {
923                write!(_f, "{error}")
924            }
925            #[cfg(custom)]
926            RequestDeviceErrorKind::Custom(msg) => write!(_f, "{msg}"),
927            #[cfg(not(any(webgpu, wgpu_core)))]
928            _ => unimplemented!("unknown `RequestDeviceErrorKind`"),
929        }
930    }
931}
932
933impl error::Error for RequestDeviceError {
934    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
935        match &self.inner {
936            #[cfg(wgpu_core)]
937            RequestDeviceErrorKind::Core(error) => error.source(),
938            #[cfg(webgpu)]
939            RequestDeviceErrorKind::WebGpu(_) => None,
940            #[cfg(custom)]
941            RequestDeviceErrorKind::Custom(_) => None,
942            #[cfg(not(any(webgpu, wgpu_core)))]
943            _ => unimplemented!("unknown `RequestDeviceErrorKind`"),
944        }
945    }
946}
947
948#[cfg(wgpu_core)]
949impl From<wgc::instance::RequestDeviceError> for RequestDeviceError {
950    fn from(error: wgc::instance::RequestDeviceError) -> Self {
951        Self {
952            inner: RequestDeviceErrorKind::Core(error),
953        }
954    }
955}
956
957/// The callback of [`Device::on_uncaptured_error()`].
958///
959/// It must be a function with this signature.
960pub trait UncapturedErrorHandler: Fn(Error) + Send + Sync + 'static {}
961impl<T> UncapturedErrorHandler for T where T: Fn(Error) + Send + Sync + 'static {}
962
963/// Kinds of [`Error`]s a [`Device::push_error_scope()`] may be configured to catch.
964#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd)]
965pub enum ErrorFilter {
966    /// Catch only out-of-memory errors.
967    OutOfMemory,
968    /// Catch only validation errors.
969    Validation,
970    /// Catch only internal errors.
971    Internal,
972}
973static_assertions::assert_impl_all!(ErrorFilter: Send, Sync);
974
975/// Lower level source of the error.
976///
977/// `Send + Sync` varies depending on configuration.
978#[cfg(send_sync)]
979#[cfg_attr(docsrs, doc(cfg(all())))]
980pub type ErrorSource = Box<dyn error::Error + Send + Sync + 'static>;
981/// Lower level source of the error.
982///
983/// `Send + Sync` varies depending on configuration.
984#[cfg(not(send_sync))]
985#[cfg_attr(docsrs, doc(cfg(all())))]
986pub type ErrorSource = Box<dyn error::Error + 'static>;
987
988/// Errors resulting from usage of GPU APIs.
989///
990/// By default, errors translate into panics. Depending on the backend and circumstances,
991/// errors may occur synchronously or asynchronously. When errors need to be handled, use
992/// [`Device::push_error_scope()`] or [`Device::on_uncaptured_error()`].
993#[derive(Debug)]
994pub enum Error {
995    /// Out of memory.
996    OutOfMemory {
997        /// Lower level source of the error.
998        source: ErrorSource,
999    },
1000    /// Validation error, signifying a bug in code or data provided to `wgpu`.
1001    Validation {
1002        /// Lower level source of the error.
1003        source: ErrorSource,
1004        /// Description of the validation error.
1005        description: String,
1006    },
1007    /// Internal error. Used for signalling any failures not explicitly expected by WebGPU.
1008    ///
1009    /// These could be due to internal implementation or system limits being reached.
1010    Internal {
1011        /// Lower level source of the error.
1012        source: ErrorSource,
1013        /// Description of the internal GPU error.
1014        description: String,
1015    },
1016}
1017#[cfg(send_sync)]
1018static_assertions::assert_impl_all!(Error: Send, Sync);
1019
1020impl error::Error for Error {
1021    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
1022        match self {
1023            Error::OutOfMemory { source } => Some(source.as_ref()),
1024            Error::Validation { source, .. } => Some(source.as_ref()),
1025            Error::Internal { source, .. } => Some(source.as_ref()),
1026        }
1027    }
1028}
1029
1030impl fmt::Display for Error {
1031    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1032        match self {
1033            Error::OutOfMemory { .. } => f.write_str("Out of Memory"),
1034            Error::Validation { description, .. } => f.write_str(description),
1035            Error::Internal { description, .. } => f.write_str(description),
1036        }
1037    }
1038}
1039
1040/// Guard for an error scope pushed with [`Device::push_error_scope()`].
1041///
1042/// Call [`pop()`] to pop the scope and get a future for the result. If
1043/// the guard is dropped without being popped explicitly, the scope will still be popped,
1044/// and the captured errors will be dropped.
1045///
1046/// This guard is neither `Send` nor `Sync`, as error scopes are handled
1047/// on a per-thread basis when the `std` feature is enabled.
1048///
1049/// [`pop()`]: ErrorScopeGuard::pop
1050#[must_use = "Error scopes must be explicitly popped to retrieve errors they catch"]
1051pub struct ErrorScopeGuard {
1052    device: dispatch::DispatchDevice,
1053    index: u32,
1054    popped: bool,
1055    // Ensure the guard is !Send and !Sync
1056    _phantom: PhantomData<*mut ()>,
1057}
1058
1059static_assertions::assert_not_impl_any!(ErrorScopeGuard: Send, Sync);
1060
1061impl ErrorScopeGuard {
1062    /// Pops the error scope.
1063    ///
1064    /// Returns a future which resolves to the error captured by this scope, if any.
1065    /// The pop takes effect immediately; the future does not need to be awaited before doing work that is outside of this error scope.
1066    pub fn pop(mut self) -> impl Future<Output = Option<Error>> + WasmNotSend {
1067        self.popped = true;
1068        self.device.pop_error_scope(self.index)
1069    }
1070}
1071
1072impl Drop for ErrorScopeGuard {
1073    fn drop(&mut self) {
1074        if !self.popped {
1075            drop(self.device.pop_error_scope(self.index));
1076        }
1077    }
1078}
1079
1080impl fmt::Debug for ErrorScopeGuard {
1081    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1082        let ErrorScopeGuard {
1083            device,
1084            index,
1085            popped,
1086            _phantom: _,
1087        } = self;
1088        f.debug_struct("ErrorScopeGuard")
1089            .field("device", device)
1090            .field("index", index)
1091            .field("popped", popped)
1092            .finish()
1093    }
1094}