Skip to main content

wgpu_core/
present.rs

1/*! Presentation.
2
3## Lifecycle
4
5Whenever a submission detects the use of any surface texture, it adds it to the device
6tracker for the duration of the submission (temporarily, while recording).
7It's added with `UNINITIALIZED` state and transitioned into `empty()` state.
8When this texture is presented, we remove it from the device tracker as well as
9extract it from the hub.
10!*/
11
12use alloc::{boxed::Box, sync::Arc, vec::Vec};
13use core::mem::ManuallyDrop;
14
15#[cfg(feature = "trace")]
16use crate::device::trace::{Action, IntoTrace};
17use crate::{
18    conv,
19    device::{queue::Queue, Device, DeviceError, MissingDownlevelFlags, WaitIdleError},
20    hal_label,
21    instance::Surface,
22    resource::{self, Labeled},
23};
24
25use thiserror::Error;
26use wgt::{
27    error::{ErrorType, WebGpuError},
28    SurfaceStatus as Status,
29};
30
31const FRAME_TIMEOUT_MS: u32 = 1000;
32
33#[derive(Debug)]
34pub(crate) struct Presentation {
35    pub(crate) device: Arc<Device>,
36    pub(crate) config: wgt::SurfaceConfiguration<Vec<wgt::TextureFormat>>,
37    pub(crate) acquired_texture: Option<Arc<resource::Texture>>,
38}
39
40#[derive(Clone, Debug, Error)]
41#[non_exhaustive]
42pub enum SurfaceError {
43    #[error("Surface is invalid")]
44    Invalid,
45    #[error("Surface is not configured for presentation")]
46    NotConfigured,
47    #[error(transparent)]
48    Device(#[from] DeviceError),
49    #[error("Surface image is already acquired")]
50    AlreadyAcquired,
51    #[error("No surface image is currently acquired to present")]
52    NothingToPresent,
53    #[error("Texture has been destroyed")]
54    TextureDestroyed,
55}
56
57impl WebGpuError for SurfaceError {
58    fn webgpu_error_type(&self) -> ErrorType {
59        match self {
60            Self::Device(e) => e.webgpu_error_type(),
61            Self::Invalid
62            | Self::NotConfigured
63            | Self::AlreadyAcquired
64            | Self::NothingToPresent
65            | Self::TextureDestroyed => ErrorType::Validation,
66        }
67    }
68}
69
70#[derive(Clone, Debug, Error)]
71#[non_exhaustive]
72pub enum ConfigureSurfaceError {
73    #[error(transparent)]
74    Device(#[from] DeviceError),
75    #[error("Invalid surface")]
76    InvalidSurface,
77    #[error("The view format {0:?} is not compatible with texture format {1:?}, only changing srgb-ness is allowed.")]
78    InvalidViewFormat(wgt::TextureFormat, wgt::TextureFormat),
79    #[error(transparent)]
80    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
81    #[error("The `SurfaceOutput` returned by `get_current_texture` must be dropped before re-configuring via `configure` or  retrieving a new texture via `get_current_texture`.")]
82    PreviousOutputExists,
83    #[error("Failed to wait for GPU to come idle before reconfiguring the Surface")]
84    GpuWaitTimeout,
85    #[error("Both `Surface` width and height must be non-zero. Wait to recreate the `Surface` until the window has non-zero area.")]
86    ZeroArea,
87    #[error("`Surface` width and height must be within the maximum supported texture size. Requested was ({width}, {height}), maximum extent for either dimension is {max_texture_dimension_2d}.")]
88    TooLarge {
89        width: u32,
90        height: u32,
91        max_texture_dimension_2d: u32,
92    },
93    #[error("Surface does not support the adapter's queue family")]
94    UnsupportedQueueFamily,
95    #[error("Requested format {requested:?} is not in list of supported formats: {available:?}")]
96    UnsupportedFormat {
97        requested: wgt::TextureFormat,
98        available: Vec<wgt::TextureFormat>,
99    },
100    #[error("Requested color space {requested:?} is not in the list of color spaces supported for format {format:?}: {available:?}")]
101    UnsupportedColorSpace {
102        requested: wgt::SurfaceColorSpace,
103        format: wgt::TextureFormat,
104        available: wgt::SurfaceColorSpaces,
105    },
106    #[error("Requested present mode {requested:?} is not in the list of supported present modes: {available:?}")]
107    UnsupportedPresentMode {
108        requested: wgt::PresentMode,
109        available: Vec<wgt::PresentMode>,
110    },
111    #[error("Requested alpha mode {requested:?} is not in the list of supported alpha modes: {available:?}")]
112    UnsupportedAlphaMode {
113        requested: wgt::CompositeAlphaMode,
114        available: Vec<wgt::CompositeAlphaMode>,
115    },
116    #[error("Requested usage {requested:?} is not in the list of supported usages: {available:?}")]
117    UnsupportedUsage {
118        requested: wgt::TextureUses,
119        available: wgt::TextureUses,
120    },
121}
122
123impl From<WaitIdleError> for ConfigureSurfaceError {
124    fn from(e: WaitIdleError) -> Self {
125        match e {
126            WaitIdleError::Device(d) => ConfigureSurfaceError::Device(d),
127            WaitIdleError::WrongSubmissionIndex(..) => unreachable!(),
128            WaitIdleError::Timeout => ConfigureSurfaceError::GpuWaitTimeout,
129        }
130    }
131}
132
133impl WebGpuError for ConfigureSurfaceError {
134    fn webgpu_error_type(&self) -> ErrorType {
135        match self {
136            Self::Device(e) => e.webgpu_error_type(),
137            Self::MissingDownlevelFlags(e) => e.webgpu_error_type(),
138            Self::InvalidSurface
139            | Self::InvalidViewFormat(..)
140            | Self::PreviousOutputExists
141            | Self::GpuWaitTimeout
142            | Self::ZeroArea
143            | Self::TooLarge { .. }
144            | Self::UnsupportedQueueFamily
145            | Self::UnsupportedFormat { .. }
146            | Self::UnsupportedColorSpace { .. }
147            | Self::UnsupportedPresentMode { .. }
148            | Self::UnsupportedAlphaMode { .. }
149            | Self::UnsupportedUsage { .. } => ErrorType::Validation,
150        }
151    }
152}
153
154#[repr(C)]
155#[derive(Debug)]
156pub struct SurfaceOutput<T = Arc<resource::Texture>> {
157    pub status: Status,
158    pub texture: Option<T>,
159}
160
161impl Surface {
162    pub fn get_current_texture(self: &Arc<Self>) -> Result<SurfaceOutput, SurfaceError> {
163        let output = self.get_current_texture_inner();
164        #[cfg(feature = "trace")]
165        if let Some(present) = self.presentation.lock().as_ref() {
166            if let Some(ref mut trace) = *present.device.trace.lock() {
167                if let Some(texture) = present.acquired_texture.as_ref() {
168                    trace.add(Action::GetSurfaceTexture {
169                        id: texture.to_trace(),
170                        parent: self.to_trace(),
171                    });
172                }
173            }
174        }
175        output
176    }
177
178    pub(crate) fn get_current_texture_inner(&self) -> Result<SurfaceOutput, SurfaceError> {
179        profiling::scope!("Surface::get_current_texture");
180
181        let (device, config) = if let Some(ref present) = *self.presentation.lock() {
182            present.device.check_is_valid()?;
183            (present.device.clone(), present.config.clone())
184        } else {
185            return Err(SurfaceError::NotConfigured);
186        };
187
188        let suf = self.raw(device.backend()).unwrap();
189        let (texture, status) = match unsafe {
190            suf.acquire_texture(
191                Some(core::time::Duration::from_millis(FRAME_TIMEOUT_MS as u64)),
192                device.fence.as_ref(),
193            )
194        } {
195            Ok(ast) => {
196                let texture_desc = wgt::TextureDescriptor {
197                    label: hal_label(
198                        Some(alloc::borrow::Cow::Borrowed("<Surface Texture>")),
199                        device.instance_flags,
200                    ),
201                    size: wgt::Extent3d {
202                        width: config.width,
203                        height: config.height,
204                        depth_or_array_layers: 1,
205                    },
206                    sample_count: 1,
207                    mip_level_count: 1,
208                    format: config.format,
209                    dimension: wgt::TextureDimension::D2,
210                    texture_binding_view_dimension: None,
211                    usage: config.usage,
212                    view_formats: config.view_formats,
213                };
214                let format_features = wgt::TextureFormatFeatures {
215                    allowed_usages: wgt::TextureUsages::RENDER_ATTACHMENT,
216                    flags: wgt::TextureFormatFeatureFlags::MULTISAMPLE_X4
217                        | wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
218                };
219                let hal_usage = conv::map_texture_usage(
220                    config.usage,
221                    config.format.into(),
222                    format_features.flags,
223                );
224                let clear_view_desc = hal::TextureViewDescriptor {
225                    label: hal_label(
226                        Some("(wgpu internal) clear surface texture view"),
227                        device.instance_flags,
228                    ),
229                    format: config.format,
230                    dimension: wgt::TextureViewDimension::D2,
231                    usage: wgt::TextureUses::COLOR_TARGET,
232                    range: wgt::ImageSubresourceRange::default(),
233                    swizzle: wgt::TextureComponentSwizzle::default(),
234                };
235                let clear_view = unsafe {
236                    device
237                        .raw()
238                        .create_texture_view(ast.texture.as_ref().borrow(), &clear_view_desc)
239                }
240                .map_err(|e| device.handle_hal_error(e))?;
241
242                let mut presentation = self.presentation.lock();
243                let present = presentation.as_mut().unwrap();
244                let texture = resource::Texture::new(
245                    &device,
246                    resource::TextureInner::Surface { raw: ast.texture },
247                    hal_usage,
248                    &texture_desc,
249                    format_features,
250                    resource::TextureClearMode::Surface {
251                        clear_view: ManuallyDrop::new(clear_view),
252                    },
253                    true,
254                    None,
255                );
256
257                let texture = Arc::new(texture);
258
259                device
260                    .trackers
261                    .lock()
262                    .textures
263                    .insert_single(&texture, wgt::TextureUses::UNINITIALIZED);
264
265                if present.acquired_texture.is_some() {
266                    return Err(SurfaceError::AlreadyAcquired);
267                }
268                present.acquired_texture = Some(texture.clone());
269
270                let status = if ast.suboptimal {
271                    Status::Suboptimal
272                } else {
273                    Status::Good
274                };
275                (Some(texture), status)
276            }
277            Err(err) => (
278                None,
279                match err {
280                    hal::SurfaceError::Timeout => Status::Timeout,
281                    hal::SurfaceError::Occluded => Status::Occluded,
282                    hal::SurfaceError::Lost => Status::Lost,
283                    hal::SurfaceError::Device(err) => {
284                        return Err(device.handle_hal_error(err).into());
285                    }
286                    hal::SurfaceError::Outdated => Status::Outdated,
287                    hal::SurfaceError::Other(msg) => {
288                        log::error!("acquire error: {msg}");
289                        Status::Lost
290                    }
291                },
292            ),
293        };
294
295        Ok(SurfaceOutput { status, texture })
296    }
297
298    pub fn present(self: &Arc<Self>) -> Result<Status, SurfaceError> {
299        self.present_with_damage(&[])
300    }
301
302    pub fn present_with_damage(
303        self: &Arc<Self>,
304        damage_rects: &[wgt::Rect<u32>],
305    ) -> Result<Status, SurfaceError> {
306        #[cfg(feature = "trace")]
307        if let Some(present) = self.presentation.lock().as_ref() {
308            if let Some(ref mut trace) = *present.device.trace.lock() {
309                trace.add(Action::Present(self.to_trace()));
310            }
311        }
312        self.present_inner(damage_rects)
313    }
314
315    pub(crate) fn present_inner(
316        &self,
317        damage_rects: &[wgt::Rect<u32>],
318    ) -> Result<Status, SurfaceError> {
319        profiling::scope!("Surface::present");
320
321        let presentation = self.presentation.lock();
322        let present = match presentation.as_ref() {
323            Some(present) => present,
324            None => return Err(SurfaceError::NotConfigured),
325        };
326
327        present.device.check_is_valid()?;
328        let queue = present
329            .device
330            .get_queue()
331            .ok_or(SurfaceError::Device(DeviceError::Lost))?;
332        drop(presentation);
333
334        queue.present_with_damage(self, damage_rects)
335    }
336}
337
338impl Queue {
339    pub fn present(&self, surface: &Surface) -> Result<Status, SurfaceError> {
340        self.present_with_damage(surface, &[])
341    }
342
343    pub fn present_with_damage(
344        &self,
345        surface: &Surface,
346        damage_rects: &[wgt::Rect<u32>],
347    ) -> Result<Status, SurfaceError> {
348        profiling::scope!("Queue::present");
349
350        let (texture, damage_rects) = {
351            let mut presentation = surface.presentation.lock();
352            let present = match presentation.as_mut() {
353                Some(present) => present,
354                None => return Err(SurfaceError::NotConfigured),
355            };
356
357            let device = &self.device;
358
359            // Check the surface is configured for this device.
360            if !Arc::ptr_eq(&present.device, device) {
361                return Err(SurfaceError::Device(DeviceError::DeviceMismatch(Box::new(
362                    crate::device::DeviceMismatch {
363                        res: self.error_ident(),
364                        res_device: device.error_ident(),
365                        target: None,
366                        target_device: present.device.error_ident(),
367                    },
368                ))));
369            }
370
371            let texture = present
372                .acquired_texture
373                .take()
374                .ok_or(SurfaceError::NothingToPresent)?;
375
376            // hal requires damage rects to be non-empty and within the surface.
377            let surface_rect = wgt::Rect {
378                x: 0,
379                y: 0,
380                w: present.config.width,
381                h: present.config.height,
382            };
383            let damage_rects = damage_rects
384                .iter()
385                .filter_map(|rect| rect.intersect(&surface_rect))
386                .collect::<Vec<_>>();
387
388            (texture, damage_rects)
389        };
390
391        // If the texture was never rendered to, clear it and transition to
392        // PRESENT state before presenting.
393        // Fixes <https://github.com/gfx-rs/wgpu/issues/6748>
394        self.prepare_surface_texture_for_present(&texture)?;
395
396        let device = &self.device;
397
398        let mut exclusive_snatch_guard = device.snatchable_lock.write();
399        let inner = texture
400            .state()
401            .ok()
402            .and_then(|state| state.inner.snatch(&mut exclusive_snatch_guard));
403        drop(exclusive_snatch_guard);
404
405        let result = match inner {
406            None => return Err(SurfaceError::TextureDestroyed),
407            Some(resource::TextureInner::Surface { raw }) => {
408                let raw_surface = surface.raw(device.backend()).unwrap();
409                let raw_queue = self.raw();
410                // [`wgpu_hal::Queue::present`] requires the queue to be synchronized with submit calls and
411                // other present calls. Locking command indices prevents submits which must increment the
412                // submission index, and by `write`ing prevents other present calls.
413                let _command_indices = device.command_indices.write();
414                unsafe { raw_queue.present(raw_surface, raw, &damage_rects) }
415            }
416            _ => unreachable!(),
417        };
418
419        match result {
420            Ok(()) => Ok(Status::Good),
421            Err(err) => match err {
422                hal::SurfaceError::Timeout => Ok(Status::Timeout),
423                hal::SurfaceError::Occluded => Ok(Status::Occluded),
424                hal::SurfaceError::Lost => Ok(Status::Lost),
425                hal::SurfaceError::Device(err) => {
426                    Err(SurfaceError::from(device.handle_hal_error(err)))
427                }
428                hal::SurfaceError::Outdated => Ok(Status::Outdated),
429                hal::SurfaceError::Other(msg) => {
430                    log::error!("present error: {msg}");
431                    Err(SurfaceError::Invalid)
432                }
433            },
434        }
435    }
436}
437
438impl Surface {
439    pub fn discard(self: &Arc<Self>) -> Result<(), SurfaceError> {
440        #[cfg(feature = "trace")]
441        if let Some(present) = self.presentation.lock().as_ref() {
442            if let Some(ref mut trace) = *present.device.trace.lock() {
443                trace.add(Action::DiscardSurfaceTexture(self.to_trace()));
444            }
445        }
446        self.discard_inner()
447    }
448
449    pub(crate) fn discard_inner(&self) -> Result<(), SurfaceError> {
450        profiling::scope!("Surface::discard");
451
452        let mut presentation = self.presentation.lock();
453        let present = match presentation.as_mut() {
454            Some(present) => present,
455            None => return Err(SurfaceError::NotConfigured),
456        };
457
458        let device = &present.device;
459
460        device.check_is_valid()?;
461
462        let texture = present
463            .acquired_texture
464            .take()
465            .ok_or(SurfaceError::NothingToPresent)?;
466
467        let mut exclusive_snatch_guard = device.snatchable_lock.write();
468        let inner = texture
469            .state()
470            .ok()
471            .and_then(|state| state.inner.snatch(&mut exclusive_snatch_guard));
472        drop(exclusive_snatch_guard);
473
474        match inner {
475            None => return Err(SurfaceError::TextureDestroyed),
476            Some(resource::TextureInner::Surface { raw }) => {
477                let raw_surface = self.raw(device.backend()).unwrap();
478                unsafe { raw_surface.discard_texture(raw) };
479            }
480            _ => unreachable!(),
481        }
482
483        Ok(())
484    }
485
486    pub fn release(self: &Arc<Self>) -> Result<(), SurfaceError> {
487        #[cfg(feature = "trace")]
488        if let Some(present) = self.presentation.lock().as_ref() {
489            if let Some(ref mut trace) = *present.device.trace.lock() {
490                trace.add(Action::ReleaseSurfaceTexture(self.to_trace()));
491            }
492        }
493        self.release_inner()
494    }
495
496    /// Like `discard`, drops the inner texture reference, but skips the
497    /// HAL `discard_texture` call. Safe to call during unwinding
498    pub(crate) fn release_inner(&self) -> Result<(), SurfaceError> {
499        profiling::scope!("Surface::release");
500
501        let mut presentation = self.presentation.lock();
502        let Some(present) = presentation.as_mut() else {
503            return Err(SurfaceError::NotConfigured);
504        };
505
506        // `texture` is dropped here, decrementing the refcount of
507        // Arc<SwapchainAcquireSemaphore>. If this was the last Arc, the Texture
508        // is freed, which drops NativeSurfaceTextureMetadata and
509        // its Arc<SwapchainAcquireSemaphore>.
510        _ = present
511            .acquired_texture
512            .take()
513            .ok_or(SurfaceError::NothingToPresent)?;
514
515        Ok(())
516    }
517}