Skip to main content

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    /// Returns the HDR and luminance characteristics of the display backing this
60    /// surface, or [`DisplayHdrInfo::default`] (all fields `None`) when nothing is
61    /// known - which means unknown, not an SDR display. Never panics, including on
62    /// wasm. See [`DisplayHdrInfo`] for the fields and how to use them.
63    ///
64    /// # Threading
65    ///
66    /// Each call re-queries the OS; nothing is cached. On the Metal backend the
67    /// display's HDR state lives on main-thread-only AppKit objects (`NSScreen` /
68    /// `NSWindow`), so call this from the main thread. Off the main thread it logs
69    /// once and returns [`DisplayHdrInfo::default`]; a later main-thread call still
70    /// returns real data. No other backend has this requirement.
71    pub fn display_hdr_info(&self, adapter: &Adapter) -> DisplayHdrInfo {
72        self.inner.display_hdr_info(&adapter.inner)
73    }
74
75    /// Return a default `SurfaceConfiguration` from width and height to use for the [`Surface`] with this adapter.
76    ///
77    /// The returned configuration requests the surface's preferred format and
78    /// [`SurfaceColorSpace::Auto`], reproducing wgpu's historical SDR / standard
79    /// behavior. Set the `color_space` field to opt into wide-gamut or HDR
80    /// output; see [`SurfaceColorSpace`] for what each color space means.
81    ///
82    /// Returns None if the surface isn't supported by this adapter
83    pub fn get_default_config(
84        &self,
85        adapter: &Adapter,
86        width: u32,
87        height: u32,
88    ) -> Option<SurfaceConfiguration> {
89        let caps = self.get_capabilities(adapter);
90        Some(SurfaceConfiguration {
91            usage: wgt::TextureUsages::RENDER_ATTACHMENT,
92            format: *caps.formats.first()?,
93            color_space: wgt::SurfaceColorSpace::Auto,
94            width,
95            height,
96            desired_maximum_frame_latency: 2,
97            present_mode: *caps.present_modes.first()?,
98            alpha_mode: wgt::CompositeAlphaMode::Auto,
99            view_formats: vec![],
100        })
101    }
102
103    /// Initializes [`Surface`] for presentation.
104    ///
105    /// If the surface is already configured, this will wait for the GPU to come idle
106    /// before recreating the swapchain to prevent race conditions.
107    ///
108    /// # Validation Errors
109    /// - Submissions that happen _during_ the configure may cause the
110    ///   internal wait-for-idle to fail, raising a validation error.
111    ///
112    /// # Panics
113    ///
114    /// - Texture format requested is unsupported on the surface.
115    /// - The requested color space is unsupported for the requested format
116    ///   (see [`SurfaceCapabilities::format_capabilities`]).
117    /// - `config.width` or `config.height` is zero.
118    pub fn configure(&self, device: &Device, config: &SurfaceConfiguration) {
119        self.inner.configure(&device.inner, config);
120
121        let mut conf = self.config.lock();
122        *conf = Some(config.clone());
123    }
124
125    /// Returns the current configuration of [`Surface`], if configured.
126    ///
127    /// This is similar to [WebGPU `GPUcCanvasContext::getConfiguration`](https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-getconfiguration).
128    ///
129    /// Note that this returns the configuration as passed to
130    /// [`Surface::configure`]: automatic values such as
131    /// [`SurfaceColorSpace::Auto`] are returned as-is, not as the concrete
132    /// values they resolved to.
133    pub fn get_configuration(&self) -> Option<SurfaceConfiguration> {
134        self.config.lock().clone()
135    }
136
137    /// Returns the next texture to be presented by the surface for drawing.
138    ///
139    /// After rendering to the returned [`SurfaceTexture`], submit work via [`Queue::submit`]
140    /// and then call [`Queue::present`] to display it.
141    ///
142    /// If a [`SurfaceTexture`] referencing this surface is alive when [`Surface::configure()`]
143    /// is called, the configure call will panic.
144    ///
145    /// See the documentation of [`CurrentSurfaceTexture`] for how each possible result
146    /// should be handled.
147    pub fn get_current_texture(&self) -> CurrentSurfaceTexture {
148        let desc = {
149            let guard = self.config.lock();
150            guard.as_ref().map(|config| TextureDescriptor {
151                label: None,
152                size: Extent3d {
153                    width: config.width,
154                    height: config.height,
155                    depth_or_array_layers: 1,
156                },
157                format: config.format,
158                usage: config.usage,
159                mip_level_count: 1,
160                sample_count: 1,
161                dimension: TextureDimension::D2,
162                view_formats: &[],
163            })
164        };
165        let (texture, status, detail) = self.inner.get_current_texture(desc);
166
167        let suboptimal = match status {
168            SurfaceStatus::Good => false,
169            SurfaceStatus::Suboptimal => true,
170            SurfaceStatus::Timeout => return CurrentSurfaceTexture::Timeout,
171            SurfaceStatus::Occluded => return CurrentSurfaceTexture::Occluded,
172            SurfaceStatus::Outdated => return CurrentSurfaceTexture::Outdated,
173            SurfaceStatus::Lost => return CurrentSurfaceTexture::Lost,
174            SurfaceStatus::Validation => return CurrentSurfaceTexture::Validation,
175        };
176
177        match texture {
178            Some(texture) => {
179                let surface_texture = SurfaceTexture {
180                    texture: Texture { inner: texture },
181                    presented: false,
182                    detail,
183                };
184                if suboptimal {
185                    CurrentSurfaceTexture::Suboptimal(surface_texture)
186                } else {
187                    CurrentSurfaceTexture::Success(surface_texture)
188                }
189            }
190            None => CurrentSurfaceTexture::Lost,
191        }
192    }
193
194    /// Get the [`wgpu_hal`] surface from this `Surface`.
195    ///
196    /// Find the Api struct corresponding to the active backend in [`wgpu_hal::api`],
197    /// and pass that struct to the to the `A` type parameter.
198    ///
199    /// Returns a guard that dereferences to the type of the hal backend
200    /// which implements [`A::Surface`].
201    ///
202    /// # Types
203    ///
204    /// The returned type depends on the backend:
205    ///
206    #[doc = crate::macros::hal_type_vulkan!("Surface")]
207    #[doc = crate::macros::hal_type_metal!("Surface")]
208    #[doc = crate::macros::hal_type_dx12!("Surface")]
209    #[doc = crate::macros::hal_type_gles!("Surface")]
210    ///
211    /// # Errors
212    ///
213    /// This method will return None if:
214    /// - The surface is not from the backend specified by `A`.
215    /// - The surface is from the `webgpu` or `custom` backend.
216    ///
217    /// # Safety
218    ///
219    /// - The returned resource must not be destroyed unless the guard
220    ///   is the last reference to it and it is not in use by the GPU.
221    ///   The guard and handle may be dropped at any time however.
222    /// - All the safety requirements of wgpu-hal must be upheld.
223    ///
224    /// [`A::Surface`]: hal::Api::Surface
225    #[cfg(wgpu_core)]
226    pub unsafe fn as_hal<A: hal::Api>(
227        &self,
228    ) -> Option<impl Deref<Target = A::Surface> + WasmNotSendSync> {
229        let core_surface = self.inner.as_core_opt()?;
230
231        unsafe { core_surface.as_hal::<A>() }
232    }
233
234    #[cfg(custom)]
235    /// Returns custom implementation of Surface (if custom backend and is internally T)
236    pub fn as_custom<T: custom::SurfaceInterface>(&self) -> Option<&T> {
237        self.inner.as_custom()
238    }
239}
240
241// This custom implementation is required because [`Surface::_surface`] doesn't
242// require [`Debug`](fmt::Debug), which we should not require from the user.
243impl fmt::Debug for Surface<'_> {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        f.debug_struct("Surface")
246            .field(
247                "_handle_source",
248                &if self._handle_source.is_some() {
249                    "Some"
250                } else {
251                    "None"
252                },
253            )
254            .field("inner", &self.inner)
255            .field("config", &self.config)
256            .finish()
257    }
258}
259
260#[cfg(send_sync)]
261static_assertions::assert_impl_all!(Surface<'_>: Send, Sync);
262
263crate::cmp::impl_eq_ord_hash_proxy!(Surface<'_> => .inner);
264
265/// [`Send`]/[`Sync`] blanket trait for [`HasWindowHandle`] used in [`SurfaceTarget`].
266pub trait WindowHandle: HasWindowHandle + WasmNotSendSync {}
267
268impl<T: HasWindowHandle + WasmNotSendSync> WindowHandle for T {}
269
270/// Super trait for a pair of display and window handles as used in [`SurfaceTarget`].
271pub trait DisplayAndWindowHandle: WindowHandle + HasDisplayHandle {}
272
273impl<T> DisplayAndWindowHandle for T where T: WindowHandle + HasDisplayHandle {}
274
275/// The window/canvas/surface/swap-chain/etc. a surface is attached to, for use with safe surface creation.
276///
277/// This is either a window or an actual web canvas depending on the platform and
278/// enabled features.
279/// Refer to the individual variants for more information.
280///
281/// See also [`SurfaceTargetUnsafe`] for unsafe variants.
282#[non_exhaustive]
283pub enum SurfaceTarget<'window> {
284    /// Window and display handle producer.
285    ///
286    /// If the specified display and window handle are not supported by any of the backends, then the surface
287    /// will not be supported by any adapters.
288    ///
289    /// # Errors
290    ///
291    /// - On WebGL2: surface creation returns an error if the browser does not support WebGL2,
292    ///   or declines to provide GPU access (such as due to a resource shortage).
293    ///
294    /// # Panics
295    ///
296    /// - On macOS/Metal: will panic if not called on the main thread.
297    /// - On web: will panic if the [`HasWindowHandle`] does not properly refer to a
298    ///   canvas element.
299    /// - On all platforms: If [`crate::InstanceDescriptor::display`] was not [`None`]
300    ///   but its value is not identical to that returned by [`HasDisplayHandle::display_handle()`].
301    DisplayAndWindow(Box<dyn DisplayAndWindowHandle + 'window>),
302
303    /// Window handle producer.
304    ///
305    /// [`HasWindowHandle`]-only version of [`SurfaceTarget::DisplayAndWindow`].
306    ///
307    /// This requires that the display handle was already passed through
308    /// [`crate::InstanceDescriptor::display`].
309    Window(Box<dyn WindowHandle + 'window>),
310
311    /// Surface from a `web_sys::HtmlCanvasElement`.
312    ///
313    /// The `canvas` argument must be a valid `<canvas>` element to
314    /// create a surface upon.
315    ///
316    /// # Errors
317    ///
318    /// - On WebGL2: surface creation will return an error if the browser does not support WebGL2,
319    ///   or declines to provide GPU access (such as due to a resource shortage).
320    #[cfg(web)]
321    Canvas(web_sys::HtmlCanvasElement),
322
323    /// Surface from a `web_sys::OffscreenCanvas`.
324    ///
325    /// The `canvas` argument must be a valid `OffscreenCanvas` object
326    /// to create a surface upon.
327    ///
328    /// # Errors
329    ///
330    /// - On WebGL2: surface creation will return an error if the browser does not support WebGL2,
331    ///   or declines to provide GPU access (such as due to a resource shortage).
332    #[cfg(web)]
333    OffscreenCanvas(web_sys::OffscreenCanvas),
334}
335
336impl fmt::Debug for SurfaceTarget<'_> {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        match self {
339            Self::DisplayAndWindow(_) => f.debug_tuple("DisplayAndWindow").finish_non_exhaustive(),
340            Self::Window(_) => f.debug_tuple("Window").finish_non_exhaustive(),
341            #[cfg(web)]
342            Self::Canvas(canvas) => f.debug_tuple("Canvas").field(canvas).finish(),
343            #[cfg(web)]
344            Self::OffscreenCanvas(canvas) => {
345                f.debug_tuple("OffscreenCanvas").field(canvas).finish()
346            }
347        }
348    }
349}
350
351impl<'a> SurfaceTarget<'a> {
352    /// Constructor for [`Self::Window`] without consuming a display handle
353    pub fn from_window_without_display(window: impl WindowHandle + 'a) -> Self {
354        Self::Window(Box::new(window))
355    }
356}
357
358impl<'a, T> From<T> for SurfaceTarget<'a>
359where
360    T: DisplayAndWindowHandle + 'a,
361{
362    fn from(window: T) -> Self {
363        Self::DisplayAndWindow(Box::new(window))
364    }
365}
366
367/// The window/canvas/surface/swap-chain/etc. a surface is attached to, for use with unsafe surface creation.
368///
369/// This is either a window or an actual web canvas depending on the platform and
370/// enabled features.
371/// Refer to the individual variants for more information.
372///
373/// See also [`SurfaceTarget`] for safe variants.
374#[non_exhaustive]
375#[derive(Debug)]
376pub enum SurfaceTargetUnsafe {
377    /// Raw window & display handle.
378    ///
379    /// If the specified display and window handle are not supported by any of the backends, then the surface
380    /// will not be supported by any adapters.
381    ///
382    /// If the `raw_display_handle` is not [`None`] here and was not [`None`] in
383    /// [`crate::InstanceDescriptor::display`], their values _must_ be identical.
384    ///
385    /// # Safety
386    ///
387    /// - `raw_window_handle` & `raw_display_handle` must be valid objects to create a surface upon.
388    /// - `raw_window_handle` & `raw_display_handle` must remain valid until after the returned
389    ///   [`Surface`] is  dropped.
390    RawHandle {
391        /// Raw display handle, underlying display must outlive the surface created from this.
392        raw_display_handle: Option<raw_window_handle::RawDisplayHandle>,
393
394        /// Raw window handle, underlying window must outlive the surface created from this.
395        raw_window_handle: raw_window_handle::RawWindowHandle,
396    },
397
398    /// Surface from a DRM device.
399    ///
400    /// If the specified DRM configuration is not supported by any of the backends, then the surface
401    /// will not be supported by any adapters.
402    ///
403    /// # Safety
404    ///
405    /// - All parameters must point to valid DRM values and remain valid for as long as the resulting [`Surface`] exists.
406    /// - The file descriptor (`fd`), plane, connector, and mode configuration must be valid and compatible.
407    #[cfg(drm)]
408    Drm {
409        /// The file descriptor of the DRM device.
410        fd: i32,
411        /// The plane index on which to create the surface.
412        plane: u32,
413        /// The ID of the connector associated with the selected mode.
414        connector_id: u32,
415        /// The display width of the selected mode.
416        width: u32,
417        /// The display height of the selected mode.
418        height: u32,
419        /// The display refresh rate of the selected mode multiplied by 1000 (e.g., 60Hz → 60000).
420        refresh_rate: u32,
421    },
422
423    /// Surface from `CoreAnimationLayer`.
424    ///
425    /// # Safety
426    ///
427    /// - layer must be a valid object to create a surface upon.
428    #[cfg(metal)]
429    CoreAnimationLayer(*mut core::ffi::c_void),
430
431    /// Surface from `IDCompositionVisual`.
432    ///
433    /// # Safety
434    ///
435    /// - 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.
436    #[cfg(dx12)]
437    CompositionVisual(*mut core::ffi::c_void),
438
439    /// Surface from DX12 `DirectComposition` handle.
440    ///
441    /// <https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_3/nf-dxgi1_3-idxgifactorymedia-createswapchainforcompositionsurfacehandle>
442    ///
443    /// # Safety
444    ///
445    /// - 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
446    ///   the resulting [`Surface`] is destroyed.
447    #[cfg(dx12)]
448    SurfaceHandle(*mut core::ffi::c_void),
449
450    /// Surface from DX12 `SwapChainPanel`.
451    ///
452    /// # Safety
453    ///
454    /// - 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.
455    #[cfg(dx12)]
456    SwapChainPanel(*mut core::ffi::c_void),
457}
458
459impl SurfaceTargetUnsafe {
460    /// Creates a [`SurfaceTargetUnsafe::RawHandle`] from a display and window.
461    ///
462    /// The `display` is optional and may be omitted if it was also passed to
463    /// [`crate::InstanceDescriptor::display`].  If passed to both it must (currently) be identical.
464    ///
465    /// # Safety
466    ///
467    /// - `display` must outlive the resulting surface target
468    ///   (and subsequently the surface created for this target).
469    /// - `window` must outlive the resulting surface target
470    ///   (and subsequently the surface created for this target).
471    pub unsafe fn from_display_and_window(
472        display: &impl HasDisplayHandle,
473        window: &impl HasWindowHandle,
474    ) -> Result<Self, raw_window_handle::HandleError> {
475        Ok(Self::RawHandle {
476            raw_display_handle: Some(display.display_handle()?.as_raw()),
477            raw_window_handle: window.window_handle()?.as_raw(),
478        })
479    }
480
481    /// Creates a [`SurfaceTargetUnsafe::RawHandle`] from a window.
482    ///
483    /// # Safety
484    ///
485    /// - `window` must outlive the resulting surface target
486    ///   (and subsequently the surface created for this target).
487    pub unsafe fn from_window(
488        window: &impl HasWindowHandle,
489    ) -> Result<Self, raw_window_handle::HandleError> {
490        Ok(Self::RawHandle {
491            raw_display_handle: None,
492            raw_window_handle: window.window_handle()?.as_raw(),
493        })
494    }
495}
496
497/// [`Instance::create_surface()`] or a related function failed.
498#[derive(Clone, Debug)]
499#[non_exhaustive]
500pub struct CreateSurfaceError {
501    pub(crate) inner: CreateSurfaceErrorKind,
502}
503#[derive(Clone, Debug)]
504pub(crate) enum CreateSurfaceErrorKind {
505    /// Error from [`wgpu_hal`].
506    #[cfg(wgpu_core)]
507    Hal(wgc::instance::CreateSurfaceError),
508
509    /// Error from WebGPU surface creation.
510    #[cfg_attr(not(webgpu), expect(dead_code))]
511    Web(String),
512
513    /// Error when trying to get a [`RawDisplayHandle`][rdh] or a
514    /// [`RawWindowHandle`][rwh] from a [`SurfaceTarget`].
515    ///
516    /// [rdh]: raw_window_handle::RawDisplayHandle
517    /// [rwh]: raw_window_handle::RawWindowHandle
518    RawHandle(raw_window_handle::HandleError),
519}
520static_assertions::assert_impl_all!(CreateSurfaceError: Send, Sync);
521
522impl fmt::Display for CreateSurfaceError {
523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524        match &self.inner {
525            #[cfg(wgpu_core)]
526            CreateSurfaceErrorKind::Hal(e) => e.fmt(f),
527            CreateSurfaceErrorKind::Web(e) => e.fmt(f),
528            CreateSurfaceErrorKind::RawHandle(e) => e.fmt(f),
529        }
530    }
531}
532
533impl error::Error for CreateSurfaceError {
534    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
535        match &self.inner {
536            #[cfg(wgpu_core)]
537            CreateSurfaceErrorKind::Hal(e) => e.source(),
538            CreateSurfaceErrorKind::Web(_) => None,
539            #[cfg(feature = "std")]
540            CreateSurfaceErrorKind::RawHandle(e) => e.source(),
541            #[cfg(not(feature = "std"))]
542            CreateSurfaceErrorKind::RawHandle(_) => None,
543        }
544    }
545}
546
547#[cfg(wgpu_core)]
548impl From<wgc::instance::CreateSurfaceError> for CreateSurfaceError {
549    fn from(e: wgc::instance::CreateSurfaceError) -> Self {
550        Self {
551            inner: CreateSurfaceErrorKind::Hal(e),
552        }
553    }
554}