Skip to main content

mln_webgpu/
surface_target.rs

1//! Frames presented to a `wgpu::Surface`. The window stays with the host,
2//! which makes the surface and reports framebuffer resizes through
3//! [`SurfaceTarget::resize`].
4
5use mln_gfx::frame::{FrameImage, FrameTarget, Handoff};
6use mln_gfx::gpu::{Gpu as _, ReadbackId, ResourceId, TargetFormats, TextureId, TextureRegion, destroy_unused};
7use mln_gfx::{Error, FramePixels, Size};
8
9use crate::device::Device;
10use crate::gpu::{WebGpu, from_wgpu_format};
11use crate::log_target;
12use crate::renderer_backend::RendererBackend;
13
14/// How a surface's frames composite with what is behind them. A browser's
15/// canvas shows the page where the map draws nothing, as a WebGL2 canvas
16/// does: the renderer's colors are premultiplied. Elsewhere the surface
17/// picks.
18const ALPHA_MODE: wgpu::CompositeAlphaMode =
19    if cfg!(target_family = "wasm") { wgpu::CompositeAlphaMode::PreMultiplied } else { wgpu::CompositeAlphaMode::Auto };
20
21/// What an overlay draws into ([`SurfaceTarget::set_overlay`]): the frame's
22/// surface texture, after the map and before it is presented.
23pub struct OverlayTarget<'a> {
24    pub device: &'a wgpu::Device,
25    pub queue: &'a wgpu::Queue,
26    pub view: &'a wgpu::TextureView,
27    pub format: wgpu::TextureFormat,
28    /// In physical pixels.
29    pub size: Size,
30}
31
32/// Draws over a frame ([`SurfaceTarget::set_overlay`]), submitting its own
33/// commands to the queue.
34pub type Overlay = Box<dyn FnMut(&OverlayTarget<'_>)>;
35
36/// How a [`SurfaceTarget`] presents.
37#[derive(Clone, Copy, Debug)]
38pub struct SurfaceOptions {
39    /// Present in step with the display. Off, frames are presented at once,
40    /// tearing.
41    pub cap_frame_rate: bool,
42    /// The usages the surface supports, where the host knows them better
43    /// than the device's adapter does, as for a browser's canvas, or where
44    /// the device has no adapter. Frames can be read back when they have
45    /// `COPY_SRC`.
46    pub usages: Option<wgpu::TextureUsages>,
47    /// The format to configure the surface with, in place of the device's
48    /// surface format.
49    pub format: Option<wgpu::TextureFormat>,
50}
51
52impl Default for SurfaceOptions {
53    fn default() -> Self {
54        SurfaceOptions { cap_frame_rate: true, usages: None, format: None }
55    }
56}
57
58/// Frames presented to a `wgpu::Surface`.
59///
60/// The surface is configured when a frame begins at a size it isn't
61/// configured at, so a target that replaces another on the same window
62/// configures it only after the other one has let go of it. A minimized
63/// window's frames keep the size the surface was last configured at.
64pub struct SurfaceTarget {
65    state: Box<State>,
66}
67
68struct State {
69    /// The surface texture of the frame begun, until it is presented.
70    current: Option<wgpu::SurfaceTexture>,
71    /// The depth and stencil texture, of the last frame's size.
72    depth_stencil: Option<wgpu::Texture>,
73    overlay: Option<Overlay>,
74    surface: wgpu::Surface<'static>,
75
76    format: wgpu::TextureFormat,
77    usage: wgpu::TextureUsages,
78    present_mode: wgpu::PresentMode,
79    depth_stencil_format: wgpu::TextureFormat,
80    /// The size of the frames, as the host last reported it.
81    size: Size,
82    /// The size the surface is configured at; `None` before the first frame
83    /// and once the surface has to be configured again.
84    configured: Option<Size>,
85
86    /// The textures of the frame begun, imported into the backend's
87    /// `WebGpu`: the surface texture until the frame ends, and the depth
88    /// and stencil texture until it is replaced.
89    color_import: Option<TextureId>,
90    depth_import: Option<TextureId>,
91
92    readback_requested: bool,
93    /// The readback of the frame that `request_readback` asked for, and its
94    /// size, until it has the texels.
95    pending_readback: Option<(ReadbackId, Size)>,
96    readback: Option<FramePixels>,
97    device: Device,
98}
99
100impl SurfaceTarget {
101    /// A target on `backend` that presents to `surface`, made with the
102    /// instance of the backend's device, at `framebuffer_size` physical
103    /// pixels. The surface is configured with the options' format, or the
104    /// device's surface format, or else an 8-bit RGBA or BGRA format that
105    /// the surface supports: in the browser the one the canvas prefers, and
106    /// elsewhere the first of BGRA8 and RGBA8.
107    ///
108    /// Fails with [`ErrorKind::Unsupported`](mln_gfx::ErrorKind) when the
109    /// device's adapter can't present to the surface or the surface supports
110    /// none of those formats, and with
111    /// [`ErrorKind::InvalidArgument`](mln_gfx::ErrorKind) when the device
112    /// has neither an adapter to ask nor a surface format.
113    pub fn new(
114        backend: &RendererBackend,
115        surface: wgpu::Surface<'static>,
116        framebuffer_size: Size,
117        options: SurfaceOptions,
118    ) -> Result<SurfaceTarget, Error> {
119        let device = backend.device();
120        let (format, mut usage, vsync_present_mode) = if let Some(adapter) = device.adapter() {
121            let capabilities = surface.get_capabilities(adapter);
122            if capabilities.formats.is_empty() {
123                return Err(Error::unsupported("The WebGPU adapter can't present to the surface"));
124            }
125            let format = match options.format.or(device.surface_format()) {
126                Some(format) if capabilities.formats.contains(&format) => format,
127                Some(format) => {
128                    return Err(Error::unsupported(format!("The surface does not take the {format:?} format")));
129                }
130                None => {
131                    const RENDERED: [wgpu::TextureFormat; 4] = [
132                        wgpu::TextureFormat::Bgra8Unorm,
133                        wgpu::TextureFormat::Bgra8UnormSrgb,
134                        wgpu::TextureFormat::Rgba8Unorm,
135                        wgpu::TextureFormat::Rgba8UnormSrgb,
136                    ];
137                    // A browser lists the canvas format it prefers first
138                    // (`getPreferredCanvasFormat()`), which it presents
139                    // without a copy.
140                    let format = if cfg!(target_family = "wasm") {
141                        capabilities.formats.iter().copied().find(|f| RENDERED.contains(f))
142                    } else {
143                        RENDERED.into_iter().find(|f| capabilities.formats.contains(f))
144                    };
145                    format
146                        .ok_or_else(|| Error::unsupported("The surface takes none of the formats the map renders in"))?
147                }
148            };
149            let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (capabilities.usages & wgpu::TextureUsages::COPY_SRC);
150            // FIFO blocks in acquire and present on Wayland while the window
151            // is hidden, which stalls the host's event loop. Mailbox is in
152            // step with the display without blocking.
153            let present_mode = if capabilities.present_modes.contains(&wgpu::PresentMode::Mailbox) {
154                wgpu::PresentMode::Mailbox
155            } else {
156                wgpu::PresentMode::Fifo
157            };
158            (format, usage, present_mode)
159        } else {
160            let format = options.format.or(device.surface_format()).ok_or_else(|| {
161                Error::invalid_argument("A surface on a device without an adapter needs the device's surface format")
162            })?;
163            (format, wgpu::TextureUsages::RENDER_ATTACHMENT, wgpu::PresentMode::Fifo)
164        };
165        if let Some(usages) = options.usages {
166            usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (usages & wgpu::TextureUsages::COPY_SRC);
167        }
168        let depth_stencil_format = if device.device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
169            wgpu::TextureFormat::Depth32FloatStencil8
170        } else {
171            wgpu::TextureFormat::Depth24PlusStencil8
172        };
173
174        Ok(SurfaceTarget {
175            state: Box::new(State {
176                current: None,
177                depth_stencil: None,
178                overlay: None,
179                surface,
180                format,
181                usage,
182                present_mode: if options.cap_frame_rate { vsync_present_mode } else { wgpu::PresentMode::Immediate },
183                depth_stencil_format,
184                size: framebuffer_size,
185                configured: None,
186                color_import: None,
187                depth_import: None,
188                readback_requested: false,
189                pending_readback: None,
190                readback: None,
191                device: device.clone(),
192            }),
193        })
194    }
195
196    /// The format the surface is configured with.
197    #[must_use]
198    pub fn format(&self) -> wgpu::TextureFormat {
199        self.state.format
200    }
201
202    /// The size of the frames, in physical pixels.
203    #[must_use]
204    pub fn size(&self) -> Size {
205        self.state.size
206    }
207
208    /// Copies the next presented frame, for [`take_readback`](Self::take_readback).
209    pub fn request_readback(&mut self) {
210        self.state.readback_requested = true;
211    }
212
213    /// The frame copied after [`request_readback`](Self::request_readback),
214    /// once it is presented and mapped: natively at once, and in the browser
215    /// on a later turn of the event loop.
216    #[must_use]
217    pub fn take_readback(&mut self, gpu: &mut WebGpu) -> Option<FramePixels> {
218        self.state.finish_readback(gpu, false);
219        self.state.readback.take()
220    }
221
222    /// Draws `overlay` over each frame from now on, after the map and before
223    /// the frame is presented and read back, or stops with `None`.
224    pub fn set_overlay(&mut self, overlay: Option<Overlay>) {
225        self.state.overlay = overlay;
226    }
227}
228
229impl State {
230    /// The size of the frame's surface texture, which is acquired, first
231    /// configuring the surface, if the frame has none yet. `None` when the
232    /// surface gives none, and the frame is skipped.
233    fn acquire(&mut self) -> Option<Size> {
234        let size_of = |texture: &wgpu::SurfaceTexture| Size::new(texture.texture.width(), texture.texture.height());
235        if let Some(current) = &self.current {
236            return Some(size_of(current));
237        }
238        let size = self.size;
239        // wgpu rejects a configuration without area, which a minimized
240        // window reports.
241        if self.configured != Some(size) && size.width != 0 && size.height != 0 {
242            self.surface.configure(
243                self.device.device(),
244                &wgpu::SurfaceConfiguration {
245                    usage: self.usage,
246                    format: self.format,
247                    width: size.width,
248                    height: size.height,
249                    present_mode: self.present_mode,
250                    desired_maximum_frame_latency: 2,
251                    alpha_mode: ALPHA_MODE,
252                    view_formats: vec![self.format],
253                    color_space: wgpu::SurfaceColorSpace::Auto,
254                },
255            );
256            self.configured = Some(size);
257        }
258        self.configured?;
259        let texture = match self.surface.get_current_texture() {
260            wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
261            wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
262                self.configured = None;
263                return None;
264            }
265            wgpu::CurrentSurfaceTexture::Timeout
266            | wgpu::CurrentSurfaceTexture::Occluded
267            | wgpu::CurrentSurfaceTexture::Validation => return None,
268        };
269        Some(size_of(self.current.insert(texture)))
270    }
271
272    /// The depth and stencil texture of `size`, imported into `gpu`.
273    fn depth_stencil_import(&mut self, gpu: &mut WebGpu, size: Size) -> TextureId {
274        let texture = match self.depth_stencil.take() {
275            Some(texture) if (texture.width(), texture.height()) == (size.width, size.height) => texture,
276            _ => {
277                if let Some(import) = self.depth_import.take() {
278                    destroy_unused(gpu, [ResourceId::Texture(import)]);
279                }
280                self.device.device().create_texture(&wgpu::TextureDescriptor {
281                    label: Some("surface depth and stencil"),
282                    size: wgpu::Extent3d { width: size.width, height: size.height, depth_or_array_layers: 1 },
283                    mip_level_count: 1,
284                    sample_count: 1,
285                    dimension: wgpu::TextureDimension::D2,
286                    format: self.depth_stencil_format,
287                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
288                    view_formats: &[],
289                })
290            }
291        };
292        let import = *self.depth_import.get_or_insert_with(|| gpu.import_texture(&texture));
293        self.depth_stencil = Some(texture);
294        import
295    }
296
297    /// Starts reading `texture`, the surface's, back.
298    fn read_back(&mut self, gpu: &mut WebGpu, texture: &wgpu::Texture) {
299        if !self.usage.contains(wgpu::TextureUsages::COPY_SRC) {
300            tracing::warn!(target: log_target::RENDER, "WebGPU: the surface does not support readback (no COPY_SRC)");
301            return;
302        }
303        let size = Size::new(texture.width(), texture.height());
304        let imported = gpu.import_texture(texture);
305        let readback = gpu.read_texture(imported, TextureRegion::whole(size));
306        destroy_unused(gpu, [ResourceId::Texture(imported)]);
307        match readback {
308            Ok(readback) => {
309                if let Some((stale, _)) = self.pending_readback.replace((readback, size)) {
310                    destroy_unused(gpu, [ResourceId::Readback(stale)]);
311                }
312            }
313            Err(error) => {
314                tracing::error!(target: log_target::RENDER, error = %error, "WebGPU: reading the frame back failed");
315            }
316        }
317    }
318
319    /// Turns the pending readback into an RGBA image once it has the
320    /// texels, waiting for them with `wait` where the platform can.
321    fn finish_readback(&mut self, gpu: &mut WebGpu, wait: bool) {
322        let Some((readback, size)) = self.pending_readback.take() else {
323            return;
324        };
325        let mut texels = match gpu.take_readback(readback, wait) {
326            Ok(Some(texels)) => texels,
327            Ok(None) => {
328                self.pending_readback = Some((readback, size));
329                return;
330            }
331            Err(error) => {
332                return tracing::error!(target: log_target::RENDER, error = %error, "WebGPU: reading the frame back failed");
333            }
334        };
335        if matches!(self.format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb) {
336            for texel in texels.as_chunks_mut::<4>().0 {
337                texel.swap(0, 2);
338            }
339        }
340        self.readback = Some(FramePixels { size, data: texels });
341    }
342}
343
344impl FrameTarget for SurfaceTarget {
345    type Gpu = WebGpu;
346
347    /// Draws the next frame at `size` physical pixels.
348    fn resize(&mut self, _gpu: &mut WebGpu, size: Size) {
349        self.state.size = size;
350    }
351
352    /// Acquires the surface's next texture, unless the frame has one. A
353    /// frame without one is skipped.
354    fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
355        self.state.begin_frame(gpu)
356    }
357
358    /// Draws the overlay over the frame, reads it back if that was asked
359    /// for, and presents it.
360    fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
361        self.state.end_frame(gpu)
362    }
363
364    fn tear_down(&mut self, gpu: &mut WebGpu) {
365        let state = &mut *self.state;
366        if let Some((readback, _)) = state.pending_readback.take() {
367            destroy_unused(gpu, [ResourceId::Readback(readback)]);
368        }
369        let imports = [state.color_import.take(), state.depth_import.take()].into_iter().flatten();
370        destroy_unused(gpu, imports.map(ResourceId::Texture));
371    }
372}
373
374impl State {
375    fn begin_frame(&mut self, gpu: &mut WebGpu) -> Option<FrameImage> {
376        let size = self.acquire()?;
377        let depth_stencil = self.depth_stencil_import(gpu, size);
378        let current = self.current.as_ref()?;
379        let color = *self.color_import.get_or_insert_with(|| gpu.import_texture(&current.texture));
380        let targets = TargetFormats {
381            color: from_wgpu_format(self.format),
382            depth_stencil: from_wgpu_format(self.depth_stencil_format),
383        };
384        Some(FrameImage { size, color, depth_stencil: Some(depth_stencil), targets })
385    }
386
387    fn end_frame(&mut self, gpu: &mut WebGpu) -> Handoff {
388        if let Some(color) = self.color_import.take() {
389            destroy_unused(gpu, [ResourceId::Texture(color)]);
390        }
391        let Some(current) = self.current.take() else {
392            return Handoff::Dropped;
393        };
394        if let Some(overlay) = self.overlay.as_mut() {
395            let view = current.texture.create_view(&wgpu::TextureViewDescriptor::default());
396            overlay(&OverlayTarget {
397                device: self.device.device(),
398                queue: self.device.queue(),
399                view: &view,
400                format: self.format,
401                size: Size::new(current.texture.width(), current.texture.height()),
402            });
403        }
404        if std::mem::take(&mut self.readback_requested) {
405            self.read_back(gpu, &current.texture);
406            // Natively this waits for the copy; in the browser the event
407            // loop maps it later.
408            self.finish_readback(gpu, true);
409        }
410        self.device.queue().present(current);
411        Handoff::Presented
412    }
413}
414
415impl Drop for State {
416    fn drop(&mut self) {
417        // The surface texture goes before the surface.
418        drop(self.current.take());
419        drop(self.depth_stencil.take());
420        drop(self.overlay.take());
421        // Runs the callbacks still outstanding.
422        let _ = self.device.device().poll(wgpu::PollType::Poll);
423    }
424}