wgpu/api/
surface.rs

1use alloc::{boxed::Box, string::String, vec, vec::Vec};
2#[cfg(wgpu_core)]
3use core::ops::Deref;
4use core::{error, fmt};
5
6use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
7
8use crate::util::Mutex;
9use crate::*;
10
11/// Describes a [`Surface`].
12///
13/// For use with [`Surface::configure`].
14///
15/// Corresponds to [WebGPU `GPUCanvasConfiguration`](
16/// https://gpuweb.github.io/gpuweb/#canvas-configuration).
17pub type SurfaceConfiguration = wgt::SurfaceConfiguration<Vec<TextureFormat>>;
18static_assertions::assert_impl_all!(SurfaceConfiguration: Send, Sync);
19
20/// Handle to a presentable surface.
21///
22/// A `Surface` represents a platform-specific surface (e.g. a window) onto which rendered images may
23/// be presented. A `Surface` may be created with the function [`Instance::create_surface`].
24///
25/// This type is unique to the Rust API of `wgpu`. In the WebGPU specification,
26/// [`GPUCanvasContext`](https://gpuweb.github.io/gpuweb/#canvas-context)
27/// serves a similar role.
28pub struct Surface<'window> {
29    /// Additional surface data returned by [`InstanceInterface::create_surface`][cs].
30    ///
31    /// [cs]: crate::dispatch::InstanceInterface::create_surface
32    pub(crate) inner: dispatch::DispatchSurface,
33
34    // Stores the latest `SurfaceConfiguration` that was set using `Surface::configure`.
35    // It is required to set the attributes of the `SurfaceTexture` in the
36    // `Surface::get_current_texture` method.
37    // Because the `Surface::configure` method operates on an immutable reference this type has to
38    // be wrapped in a mutex and since the configuration is only supplied after the surface has
39    // been created is is additionally wrapped in an option.
40    pub(crate) config: Mutex<Option<SurfaceConfiguration>>,
41
42    /// Optionally, keep the source of the handle used for the surface alive.
43    ///
44    /// This is useful for platforms where the surface is created from a window and the surface
45    /// would become invalid when the window is dropped.
46    ///
47    /// SAFETY: This field must be dropped *after* all other fields to ensure proper cleanup.
48    pub(crate) _handle_source: Option<Box<dyn WindowHandle + 'window>>,
49}
50
51impl Surface<'_> {
52    /// Returns the capabilities of the surface when used with the given adapter.
53    ///
54    /// Returns specified values (see [`SurfaceCapabilities`]) if surface is incompatible with the adapter.
55    pub fn get_capabilities(&self, adapter: &Adapter) -> SurfaceCapabilities {
56        self.inner.get_capabilities(&adapter.inner)
57    }
58
59    /// Return a default `SurfaceConfiguration` from width and height to use for the [`Surface`] with this adapter.
60    ///
61    /// Returns None if the surface isn't supported by this adapter
62    pub fn get_default_config(
63        &self,
64        adapter: &Adapter,
65        width: u32,
66        height: u32,
67    ) -> Option<SurfaceConfiguration> {
68        let caps = self.get_capabilities(adapter);
69        Some(SurfaceConfiguration {
70            usage: wgt::TextureUsages::RENDER_ATTACHMENT,
71            format: *caps.formats.first()?,
72            width,
73            height,
74            desired_maximum_frame_latency: 2,
75            present_mode: *caps.present_modes.first()?,
76            alpha_mode: wgt::CompositeAlphaMode::Auto,
77            view_formats: vec![],
78        })
79    }
80
81    /// Initializes [`Surface`] for presentation.
82    ///
83    /// If the surface is already configured, this will wait for the GPU to come idle
84    /// before recreating the swapchain to prevent race conditions.
85    ///
86    /// # Validation Errors
87    /// - Submissions that happen _during_ the configure may cause the
88    ///   internal wait-for-idle to fail, raising a validation error.
89    ///
90    /// # Panics
91    ///
92    /// - An old [`SurfaceTexture`] is still alive referencing an old surface.
93    /// - Texture format requested is unsupported on the surface.
94    /// - `config.width` or `config.height` is zero.
95    pub fn configure(&self, device: &Device, config: &SurfaceConfiguration) {
96        self.inner.configure(&device.inner, config);
97
98        let mut conf = self.config.lock();
99        *conf = Some(config.clone());
100    }
101
102    /// Returns the current configuration of [`Surface`], if configured.
103    ///
104    /// This is similar to [WebGPU `GPUcCanvasContext::getConfiguration`](https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-getconfiguration).
105    pub fn get_configuration(&self) -> Option<SurfaceConfiguration> {
106        self.config.lock().clone()
107    }
108
109    /// Returns the next texture to be presented by the surface for drawing.
110    ///
111    /// In order to present the [`SurfaceTexture`] returned by this method,
112    /// first a [`Queue::submit`] needs to be done with some work rendering to this texture.
113    /// Then [`SurfaceTexture::present`] needs to be called.
114    ///
115    /// If a [`SurfaceTexture`] referencing this surface is alive when [`Surface::configure()`]
116    /// is called, the configure call will panic.
117    ///
118    /// See the documentation of [`CurrentSurfaceTexture`] for how each possible result
119    /// should be handled.
120    pub fn get_current_texture(&self) -> CurrentSurfaceTexture {
121        let (texture, status, detail) = self.inner.get_current_texture();
122
123        let suboptimal = match status {
124            SurfaceStatus::Good => false,
125            SurfaceStatus::Suboptimal => true,
126            SurfaceStatus::Timeout => return CurrentSurfaceTexture::Timeout,
127            SurfaceStatus::Occluded => return CurrentSurfaceTexture::Occluded,
128            SurfaceStatus::Outdated => return CurrentSurfaceTexture::Outdated,
129            SurfaceStatus::Lost => return CurrentSurfaceTexture::Lost,
130            SurfaceStatus::Validation => return CurrentSurfaceTexture::Validation,
131        };
132
133        let guard = self.config.lock();
134        let config = guard
135            .as_ref()
136            .expect("This surface has not been configured yet.");
137
138        let descriptor = TextureDescriptor {
139            label: None,
140            size: Extent3d {
141                width: config.width,
142                height: config.height,
143                depth_or_array_layers: 1,
144            },
145            format: config.format,
146            usage: config.usage,
147            mip_level_count: 1,
148            sample_count: 1,
149            dimension: TextureDimension::D2,
150            view_formats: &[],
151        };
152
153        match texture {
154            Some(texture) => {
155                let surface_texture = SurfaceTexture {
156                    texture: Texture {
157                        inner: texture,
158                        descriptor,
159                    },
160                    presented: false,
161                    detail,
162                };
163                if suboptimal {
164                    CurrentSurfaceTexture::Suboptimal(surface_texture)
165                } else {
166                    CurrentSurfaceTexture::Success(surface_texture)
167                }
168            }
169            None => CurrentSurfaceTexture::Lost,
170        }
171    }
172
173    /// Get the [`wgpu_hal`] surface from this `Surface`.
174    ///
175    /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
176    /// and pass that struct to the to the `A` type parameter.
177    ///
178    /// Returns a guard that dereferences to the type of the hal backend
179    /// which implements [`A::Surface`].
180    ///
181    /// # Types
182    ///
183    /// The returned type depends on the backend:
184    ///
185    #[doc = crate::macros::hal_type_vulkan!("Surface")]
186    #[doc = crate::macros::hal_type_metal!("Surface")]
187    #[doc = crate::macros::hal_type_dx12!("Surface")]
188    #[doc = crate::macros::hal_type_gles!("Surface")]
189    ///
190    /// # Errors
191    ///
192    /// This method will return None if:
193    /// - The surface is not from the backend specified by `A`.
194    /// - The surface is from the `webgpu` or `custom` backend.
195    ///
196    /// # Safety
197    ///
198    /// - The returned resource must not be destroyed unless the guard
199    ///   is the last reference to it and it is not in use by the GPU.
200    ///   The guard and handle may be dropped at any time however.
201    /// - All the safety requirements of wgpu-hal must be upheld.
202    ///
203    /// [`A::Surface`]: hal::Api::Surface
204    #[cfg(wgpu_core)]
205    pub unsafe fn as_hal<A: hal::Api>(
206        &self,
207    ) -> Option<impl Deref<Target = A::Surface> + WasmNotSendSync> {
208        let core_surface = self.inner.as_core_opt()?;
209
210        unsafe { core_surface.context.surface_as_hal::<A>(core_surface) }
211    }
212
213    #[cfg(custom)]
214    /// Returns custom implementation of Surface (if custom backend and is internally T)
215    pub fn as_custom<T: custom::SurfaceInterface>(&self) -> Option<&T> {
216        self.inner.as_custom()
217    }
218}
219
220// This custom implementation is required because [`Surface::_surface`] doesn't
221// require [`Debug`](fmt::Debug), which we should not require from the user.
222impl fmt::Debug for Surface<'_> {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        f.debug_struct("Surface")
225            .field(
226                "_handle_source",
227                &if self._handle_source.is_some() {
228                    "Some"
229                } else {
230                    "None"
231                },
232            )
233            .field("inner", &self.inner)
234            .field("config", &self.config)
235            .finish()
236    }
237}
238
239#[cfg(send_sync)]
240static_assertions::assert_impl_all!(Surface<'_>: Send, Sync);
241
242crate::cmp::impl_eq_ord_hash_proxy!(Surface<'_> => .inner);
243
244/// [`Send`]/[`Sync`] blanket trait for [`HasWindowHandle`] used in [`SurfaceTarget`].
245pub trait WindowHandle: HasWindowHandle + WasmNotSendSync {}
246
247impl<T: HasWindowHandle + WasmNotSendSync> WindowHandle for T {}
248
249/// Super trait for a pair of display and window handles as used in [`SurfaceTarget`].
250pub trait DisplayAndWindowHandle: WindowHandle + HasDisplayHandle {}
251
252impl<T> DisplayAndWindowHandle for T where T: WindowHandle + HasDisplayHandle {}
253
254/// The window/canvas/surface/swap-chain/etc. a surface is attached to, for use with safe surface creation.
255///
256/// This is either a window or an actual web canvas depending on the platform and
257/// enabled features.
258/// Refer to the individual variants for more information.
259///
260/// See also [`SurfaceTargetUnsafe`] for unsafe variants.
261#[non_exhaustive]
262pub enum SurfaceTarget<'window> {
263    /// Window and display handle producer.
264    ///
265    /// If the specified display and window handle are not supported by any of the backends, then the surface
266    /// will not be supported by any adapters.
267    ///
268    /// # Errors
269    ///
270    /// - On WebGL2: surface creation returns an error if the browser does not support WebGL2,
271    ///   or declines to provide GPU access (such as due to a resource shortage).
272    ///
273    /// # Panics
274    ///
275    /// - On macOS/Metal: will panic if not called on the main thread.
276    /// - On web: will panic if the [`HasWindowHandle`] does not properly refer to a
277    ///   canvas element.
278    /// - On all platforms: If [`crate::InstanceDescriptor::display`] was not [`None`]
279    ///   but its value is not identical to that returned by [`HasDisplayHandle::display_handle()`].
280    DisplayAndWindow(Box<dyn DisplayAndWindowHandle + 'window>),
281
282    /// Window handle producer.
283    ///
284    /// [`HasWindowHandle`]-only version of [`SurfaceTarget::DisplayAndWindow`].
285    ///
286    /// This requires that the display handle was already passed through
287    /// [`crate::InstanceDescriptor::display`].
288    Window(Box<dyn WindowHandle + 'window>),
289
290    /// Surface from a `web_sys::HtmlCanvasElement`.
291    ///
292    /// The `canvas` argument must be a valid `<canvas>` element to
293    /// create a surface upon.
294    ///
295    /// # Errors
296    ///
297    /// - On WebGL2: surface creation will return an error if the browser does not support WebGL2,
298    ///   or declines to provide GPU access (such as due to a resource shortage).
299    #[cfg(web)]
300    Canvas(web_sys::HtmlCanvasElement),
301
302    /// Surface from a `web_sys::OffscreenCanvas`.
303    ///
304    /// The `canvas` argument must be a valid `OffscreenCanvas` object
305    /// to create a surface upon.
306    ///
307    /// # Errors
308    ///
309    /// - On WebGL2: surface creation will return an error if the browser does not support WebGL2,
310    ///   or declines to provide GPU access (such as due to a resource shortage).
311    #[cfg(web)]
312    OffscreenCanvas(web_sys::OffscreenCanvas),
313}
314
315impl<'a> SurfaceTarget<'a> {
316    /// Constructor for [`Self::Window`] without consuming a display handle
317    pub fn from_window_without_display(window: impl WindowHandle + 'a) -> Self {
318        Self::Window(Box::new(window))
319    }
320}
321
322impl<'a, T> From<T> for SurfaceTarget<'a>
323where
324    T: DisplayAndWindowHandle + 'a,
325{
326    fn from(window: T) -> Self {
327        Self::DisplayAndWindow(Box::new(window))
328    }
329}
330
331/// The window/canvas/surface/swap-chain/etc. a surface is attached to, for use with unsafe surface creation.
332///
333/// This is either a window or an actual web canvas depending on the platform and
334/// enabled features.
335/// Refer to the individual variants for more information.
336///
337/// See also [`SurfaceTarget`] for safe variants.
338#[non_exhaustive]
339pub enum SurfaceTargetUnsafe {
340    /// Raw window & display handle.
341    ///
342    /// If the specified display and window handle are not supported by any of the backends, then the surface
343    /// will not be supported by any adapters.
344    ///
345    /// If the `raw_display_handle` is not [`None`] here and was not [`None`] in
346    /// [`crate::InstanceDescriptor::display`], their values _must_ be identical.
347    ///
348    /// # Safety
349    ///
350    /// - `raw_window_handle` & `raw_display_handle` must be valid objects to create a surface upon.
351    /// - `raw_window_handle` & `raw_display_handle` must remain valid until after the returned
352    ///   [`Surface`] is  dropped.
353    RawHandle {
354        /// Raw display handle, underlying display must outlive the surface created from this.
355        raw_display_handle: Option<raw_window_handle::RawDisplayHandle>,
356
357        /// Raw window handle, underlying window must outlive the surface created from this.
358        raw_window_handle: raw_window_handle::RawWindowHandle,
359    },
360
361    /// Surface from a DRM device.
362    ///
363    /// If the specified DRM configuration is not supported by any of the backends, then the surface
364    /// will not be supported by any adapters.
365    ///
366    /// # Safety
367    ///
368    /// - All parameters must point to valid DRM values and remain valid for as long as the resulting [`Surface`] exists.
369    /// - The file descriptor (`fd`), plane, connector, and mode configuration must be valid and compatible.
370    #[cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))]
371    Drm {
372        /// The file descriptor of the DRM device.
373        fd: i32,
374        /// The plane index on which to create the surface.
375        plane: u32,
376        /// The ID of the connector associated with the selected mode.
377        connector_id: u32,
378        /// The display width of the selected mode.
379        width: u32,
380        /// The display height of the selected mode.
381        height: u32,
382        /// The display refresh rate of the selected mode multiplied by 1000 (e.g., 60Hz → 60000).
383        refresh_rate: u32,
384    },
385
386    /// Surface from `CoreAnimationLayer`.
387    ///
388    /// # Safety
389    ///
390    /// - layer must be a valid object to create a surface upon.
391    #[cfg(metal)]
392    CoreAnimationLayer(*mut core::ffi::c_void),
393
394    /// Surface from `IDCompositionVisual`.
395    ///
396    /// # Safety
397    ///
398    /// - visual must be a valid `IDCompositionVisual` to create a surface upon.  Its refcount will be incremented internally and kept live as long as the resulting [`Surface`] is live.
399    #[cfg(dx12)]
400    CompositionVisual(*mut core::ffi::c_void),
401
402    /// Surface from DX12 `DirectComposition` handle.
403    ///
404    /// <https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_3/nf-dxgi1_3-idxgifactorymedia-createswapchainforcompositionsurfacehandle>
405    ///
406    /// # Safety
407    ///
408    /// - surface_handle must be a valid `DirectComposition` handle to create a surface upon.   Its lifetime **will not** be internally managed: this handle **should not** be freed before
409    ///   the resulting [`Surface`] is destroyed.
410    #[cfg(dx12)]
411    SurfaceHandle(*mut core::ffi::c_void),
412
413    /// Surface from DX12 `SwapChainPanel`.
414    ///
415    /// # Safety
416    ///
417    /// - visual must be a valid SwapChainPanel to create a surface upon.  Its refcount will be incremented internally and kept live as long as the resulting [`Surface`] is live.
418    #[cfg(dx12)]
419    SwapChainPanel(*mut core::ffi::c_void),
420}
421
422impl SurfaceTargetUnsafe {
423    /// Creates a [`SurfaceTargetUnsafe::RawHandle`] from a display and window.
424    ///
425    /// The `display` is optional and may be omitted if it was also passed to
426    /// [`crate::InstanceDescriptor::display`].  If passed to both it must (currently) be identical.
427    ///
428    /// # Safety
429    ///
430    /// - `display` must outlive the resulting surface target
431    ///   (and subsequently the surface created for this target).
432    /// - `window` must outlive the resulting surface target
433    ///   (and subsequently the surface created for this target).
434    pub unsafe fn from_display_and_window(
435        display: &impl HasDisplayHandle,
436        window: &impl HasWindowHandle,
437    ) -> Result<Self, raw_window_handle::HandleError> {
438        Ok(Self::RawHandle {
439            raw_display_handle: Some(display.display_handle()?.as_raw()),
440            raw_window_handle: window.window_handle()?.as_raw(),
441        })
442    }
443
444    /// Creates a [`SurfaceTargetUnsafe::RawHandle`] from a window.
445    ///
446    /// # Safety
447    ///
448    /// - `window` must outlive the resulting surface target
449    ///   (and subsequently the surface created for this target).
450    pub unsafe fn from_window(
451        window: &impl HasWindowHandle,
452    ) -> Result<Self, raw_window_handle::HandleError> {
453        Ok(Self::RawHandle {
454            raw_display_handle: None,
455            raw_window_handle: window.window_handle()?.as_raw(),
456        })
457    }
458}
459
460/// [`Instance::create_surface()`] or a related function failed.
461#[derive(Clone, Debug)]
462#[non_exhaustive]
463pub struct CreateSurfaceError {
464    pub(crate) inner: CreateSurfaceErrorKind,
465}
466#[derive(Clone, Debug)]
467pub(crate) enum CreateSurfaceErrorKind {
468    /// Error from [`wgpu_hal`].
469    #[cfg(wgpu_core)]
470    Hal(wgc::instance::CreateSurfaceError),
471
472    /// Error from WebGPU surface creation.
473    #[cfg_attr(not(webgpu), expect(dead_code))]
474    Web(String),
475
476    /// Error when trying to get a [`RawDisplayHandle`][rdh] or a
477    /// [`RawWindowHandle`][rwh] from a [`SurfaceTarget`].
478    ///
479    /// [rdh]: raw_window_handle::RawDisplayHandle
480    /// [rwh]: raw_window_handle::RawWindowHandle
481    RawHandle(raw_window_handle::HandleError),
482}
483static_assertions::assert_impl_all!(CreateSurfaceError: Send, Sync);
484
485impl fmt::Display for CreateSurfaceError {
486    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487        match &self.inner {
488            #[cfg(wgpu_core)]
489            CreateSurfaceErrorKind::Hal(e) => e.fmt(f),
490            CreateSurfaceErrorKind::Web(e) => e.fmt(f),
491            CreateSurfaceErrorKind::RawHandle(e) => e.fmt(f),
492        }
493    }
494}
495
496impl error::Error for CreateSurfaceError {
497    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
498        match &self.inner {
499            #[cfg(wgpu_core)]
500            CreateSurfaceErrorKind::Hal(e) => e.source(),
501            CreateSurfaceErrorKind::Web(_) => None,
502            #[cfg(feature = "std")]
503            CreateSurfaceErrorKind::RawHandle(e) => e.source(),
504            #[cfg(not(feature = "std"))]
505            CreateSurfaceErrorKind::RawHandle(_) => None,
506        }
507    }
508}
509
510#[cfg(wgpu_core)]
511impl From<wgc::instance::CreateSurfaceError> for CreateSurfaceError {
512    fn from(e: wgc::instance::CreateSurfaceError) -> Self {
513        Self {
514            inner: CreateSurfaceErrorKind::Hal(e),
515        }
516    }
517}