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