Skip to main content

mln_webgpu/
surface_target.rs

1// Ports the window-surface part of platform/glfw/glfw_webgpu_backend.hpp and
2// platform/glfw/glfw_webgpu_backend_impl.ipp (the Linux, wgpu-native branch):
3// frames presented to a `wgpu::Surface`. The window stays with the host,
4// which makes the surface, or hands its window over for the target to make
5// one, and reports framebuffer resizes through `resize`.
6//
7// Differences from C++, all structural:
8// - The C++ backend reads `glfwGetFramebufferSize` where it needs the size;
9//   here the host reports it (`resize`, also what C++'s
10//   `onFramebufferResize` calls), so `reconfigureSurface` and the depth
11//   texture use the size last reported.
12// - C++ reconfigures a resized surface in `swap()`, after rendering one
13//   frame into the old-size swapchain texture with the new-size viewport
14//   (Dawn logs a validation error for it). The port also reconfigures
15//   before acquiring the next texture when a reconfigure is pending.
16// - The surface is configured with the first frame, so a target that
17//   replaces another on the same window configures it after the other one
18//   let go of it.
19// - Single-threaded (the renderer runs on one thread): the spin lock,
20//   `frameInProgress` (never set in C++) and `isShuttingDown` atomics are
21//   plain cells, and `waitForFrame` always succeeds immediately as in C++.
22// - Port-only: `request_readback` copies the next presented frame into a
23//   `PremultipliedImage` (the surface is configured with COPY_SRC when the
24//   surface supports it), so a frame can be checked without screenshots.
25//   The copy is mapped asynchronously: natively `swap` waits for it, and in
26//   the browser, where nothing can wait for the GPU, `take_readback` returns
27//   it once the event loop has mapped it.
28// - Port-only: `set_overlay` draws over each frame before it is presented,
29//   such as an app's controls over the map.
30
31use std::any::Any;
32use std::cell::{Cell, RefCell};
33use std::rc::Rc;
34use std::time::Duration;
35
36use mln_gfx::command_encoder::CommandEncoder as GfxCommandEncoder;
37use mln_gfx::frame::{self, FrameTarget, Handoff};
38use mln_util::error::Error;
39use mln_util::image::PremultipliedImage;
40use mln_util::logging::{Event, Log};
41use mln_util::size::Size;
42use mln_util::time::Instant;
43
44use crate::command_encoder::CommandEncoder;
45use crate::draw_target::{DrawTarget, TargetResource};
46use crate::renderer_backend::RendererBackend;
47
48/// `maxConsecutiveErrors`
49const MAX_CONSECUTIVE_ERRORS: i32 = 3;
50
51/// `backendTypeToString`
52fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
53    match backend {
54        wgpu::Backend::Noop => "Null",
55        wgpu::Backend::BrowserWebGpu => "WebGPU",
56        wgpu::Backend::Dx12 => "D3D12",
57        wgpu::Backend::Metal => "Metal",
58        wgpu::Backend::Vulkan => "Vulkan",
59        wgpu::Backend::Gl => "OpenGL",
60    }
61}
62
63/// The usages and vsync'ed present mode to configure a surface with: `COPY_SRC`
64/// for readback where the surface has it, and MAILBOX where it has it (see
65/// `SurfaceState::vsync_present_mode`).
66fn surface_options(capabilities: &wgpu::SurfaceCapabilities) -> (wgpu::TextureUsages, wgpu::PresentMode) {
67    let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (capabilities.usages & wgpu::TextureUsages::COPY_SRC);
68    let present_mode = if capabilities.present_modes.contains(&wgpu::PresentMode::Mailbox) {
69        wgpu::PresentMode::Mailbox
70    } else {
71        wgpu::PresentMode::Fifo
72    };
73    (usage, present_mode)
74}
75/// Port-only: what an overlay draws into (`SurfaceTarget::set_overlay`):
76/// the frame's swapchain texture, after the map and before it is presented.
77pub struct OverlayTarget<'a> {
78    pub device: &'a wgpu::Device,
79    pub queue: &'a wgpu::Queue,
80    pub view: &'a wgpu::TextureView,
81    pub format: wgpu::TextureFormat,
82    /// In physical pixels.
83    pub size: Size,
84}
85
86/// Port-only: draws over a frame (`SurfaceTarget::set_overlay`). It submits
87/// its own commands to the queue.
88pub type Overlay = Box<dyn FnMut(&OverlayTarget<'_>)>;
89
90/// The current swapchain texture and its view (`currentTexture`,
91/// `currentTextureView`).
92struct CurrentTexture {
93    texture: wgpu::SurfaceTexture,
94    view: wgpu::TextureView,
95}
96
97/// The members of `GLFWWebGPUBackend` that the draw target reaches through
98/// its `backend` reference in C++.
99struct SurfaceState {
100    surface: RefCell<Option<wgpu::Surface<'static>>>,
101    device: wgpu::Device,
102    queue: wgpu::Queue,
103    swap_chain_format: wgpu::TextureFormat,
104    surface_usage: Cell<wgpu::TextureUsages>,
105    depth_stencil_format: wgpu::TextureFormat,
106
107    current: RefCell<Option<CurrentTexture>>,
108    depth_stencil: RefCell<Option<(wgpu::Texture, wgpu::TextureView)>>,
109
110    frame_presented: Cell<bool>,
111    surface_configured: Cell<bool>,
112    surface_needs_reconfigure: Cell<bool>,
113    last_configured_size: Cell<Size>,
114    consecutive_errors: Cell<i32>,
115    enable_vsync: bool,
116    /// symbols (user report: the window froze while hidden): the vsync'ed
117    /// present mode. FIFO blocks in acquire/present on Wayland while the
118    /// window is not visible (no frame callbacks), which stalls the whole
119    /// event loop; MAILBOX is vsync'ed without blocking, so it is used when
120    /// the surface supports it.
121    vsync_present_mode: Cell<wgpu::PresentMode>,
122    /// What `glfwGetFramebufferSize` returns in C++.
123    framebuffer_size: Cell<Size>,
124    /// `static auto lastSwapTime` in `swap()`.
125    last_swap_time: Cell<Instant>,
126
127    readback_requested: Cell<bool>,
128    /// The copy of the frame `request_readback` asked for, until mapped.
129    pending_readback: RefCell<Option<PendingReadback>>,
130    readback: RefCell<Option<PremultipliedImage>>,
131    overlay: RefCell<Option<Overlay>>,
132}
133
134/// Port-only: a frame copied into a buffer, waiting to be mapped.
135struct PendingReadback {
136    buffer: wgpu::Buffer,
137    bytes_per_row: u32,
138    size: Size,
139    mapped: std::sync::mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
140}
141
142impl SurfaceState {
143    fn configuration(&self, size: Size) -> wgpu::SurfaceConfiguration {
144        wgpu::SurfaceConfiguration {
145            usage: self.surface_usage.get(),
146            format: self.swap_chain_format,
147            width: size.width,
148            height: size.height,
149            // Use Immediate mode (no vsync) in benchmark mode, Fifo (vsync) otherwise
150            present_mode: if self.enable_vsync { self.vsync_present_mode.get() } else { wgpu::PresentMode::Immediate },
151            desired_maximum_frame_latency: 2,
152            alpha_mode: wgpu::CompositeAlphaMode::Auto,
153            view_formats: vec![self.swap_chain_format],
154            color_space: wgpu::SurfaceColorSpace::Auto,
155        }
156    }
157
158    /// `processEvents()`: `wgpuDevicePoll(device, false)`.
159    fn process_events(&self) {
160        let _ = self.device.poll(wgpu::PollType::Poll);
161    }
162
163    /// `swap()`: presents the current frame.
164    /// Presents the current frame. Returns whether there was one.
165    fn swap(&self) -> bool {
166        let mut presented = false;
167        let now = Instant::now();
168        let time_since_last_swap = now.duration_since(self.last_swap_time.get());
169
170        // If it's been too long since last swap, tick the device to keep it alive
171        if time_since_last_swap > Duration::from_millis(1000) {
172            self.process_events();
173            // Only reconfigure if really needed (> 10 seconds)
174            if time_since_last_swap > Duration::from_millis(10000) && self.surface_configured.get() {
175                self.surface_needs_reconfigure.set(true);
176            }
177        }
178        self.last_swap_time.set(now);
179
180        // Note: Command buffer is already submitted in CommandEncoder::present()
181        // before swap() is called, so we don't need to submit it again here.
182
183        // Present the current frame
184        if self.surface_configured.get() {
185            // Check if surface needs reconfiguration
186            if self.surface_needs_reconfigure.get() {
187                self.reconfigure_surface();
188            }
189
190            // Only present if we have a valid texture view and haven't presented yet
191            let current = if self.frame_presented.get() { None } else { self.current.borrow_mut().take() };
192            {
193                if let Some(current) = current {
194                    if let Some(overlay) = self.overlay.borrow_mut().as_mut() {
195                        overlay(&OverlayTarget {
196                            device: &self.device,
197                            queue: &self.queue,
198                            view: &current.view,
199                            format: self.swap_chain_format,
200                            size: self.last_configured_size.get(),
201                        });
202                    }
203                    if self.readback_requested.get() {
204                        self.readback_requested.set(false);
205                        *self.pending_readback.borrow_mut() = self.copy_texture(&current.texture.texture);
206                        // Natively this waits for the copy; in the browser it
207                        // returns at once and the event loop maps it later.
208                        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
209                        self.finish_readback();
210                    }
211                    drop(current.view);
212                    self.queue.present(current.texture);
213                    self.frame_presented.set(true);
214                    presented = true;
215                }
216            }
217
218            // Reset error counter on successful present
219            self.consecutive_errors.set(0);
220        }
221
222        // signalFrameComplete(): `frameInProgress` is never set (see the
223        // file comment). C++ calls glfwPollEvents here; the host does.
224        presented
225    }
226
227    /// `getCurrentTextureView()`
228    fn get_current_texture_view(&self) -> Option<wgpu::TextureView> {
229        // Port: a surface that had no size to configure with yet (or was
230        // just set) is configured once it has one.
231        if !self.surface_configured.get() && self.surface_needs_reconfigure.get() {
232            self.reconfigure_surface();
233        }
234        if !self.surface_configured.get() {
235            return None;
236        }
237
238        // Check error threshold
239        if self.consecutive_errors.get() >= MAX_CONSECUTIVE_ERRORS {
240            // Too many errors, need to reconfigure
241            self.surface_needs_reconfigure.set(true);
242            self.reconfigure_surface();
243            self.consecutive_errors.set(0);
244        }
245
246        if let Some(current) = self.current.borrow().as_ref()
247            && !self.frame_presented.get()
248        {
249            return Some(current.view.clone());
250        }
251
252        // Always release textures before acquiring new ones to avoid "already acquired" error
253        self.current.borrow_mut().take();
254        self.frame_presented.set(false);
255
256        // Port: apply a pending resize before acquiring (see the file comment).
257        if self.surface_needs_reconfigure.get() {
258            self.reconfigure_surface();
259        }
260
261        let acquired = self.surface.borrow().as_ref()?.get_current_texture();
262        let surface_texture = match acquired {
263            wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
264            wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
265                self.surface_needs_reconfigure.set(true);
266                self.consecutive_errors.set(self.consecutive_errors.get() + 1);
267                return None;
268            }
269            wgpu::CurrentSurfaceTexture::Timeout
270            | wgpu::CurrentSurfaceTexture::Occluded
271            | wgpu::CurrentSurfaceTexture::Validation => {
272                self.consecutive_errors.set(self.consecutive_errors.get() + 1);
273                return None;
274            }
275        };
276
277        // Create texture view with explicit descriptor
278        let view = surface_texture.texture.create_view(&wgpu::TextureViewDescriptor {
279            label: Some("SwapChain TextureView"),
280            format: Some(self.swap_chain_format),
281            dimension: Some(wgpu::TextureViewDimension::D2),
282            usage: None,
283            aspect: wgpu::TextureAspect::All,
284            base_mip_level: 0,
285            mip_level_count: Some(1),
286            base_array_layer: 0,
287            array_layer_count: Some(1),
288        });
289
290        // Store the texture to keep it alive
291        *self.current.borrow_mut() = Some(CurrentTexture { texture: surface_texture, view: view.clone() });
292
293        // Success - reset error counter
294        self.consecutive_errors.set(0);
295        Some(view)
296    }
297
298    /// `getDepthStencilView()`
299    fn get_depth_stencil_view(&self) -> Option<wgpu::TextureView> {
300        if self.depth_stencil.borrow().is_none() {
301            let size = self.framebuffer_size.get();
302            self.create_depth_stencil_texture(size.width, size.height);
303        }
304        self.depth_stencil.borrow().as_ref().map(|(_, view)| view.clone())
305    }
306
307    /// `reconfigureSurface()`
308    fn reconfigure_surface(&self) {
309        // Wait for any in-progress frame: never in progress (file comment).
310
311        // Clear all texture state
312        self.current.borrow_mut().take();
313
314        let surface = self.surface.borrow();
315        let Some(surface) = surface.as_ref() else {
316            return;
317        };
318
319        // Get current size
320        let size = self.framebuffer_size.get();
321
322        // Skip if size hasn't changed and we're already configured
323        if self.surface_configured.get() && self.last_configured_size.get() == size {
324            self.surface_needs_reconfigure.set(false);
325            return;
326        }
327
328        // wgpu (unlike wgpu-native) rejects a zero-sized configuration, which
329        // a minimized window reports; keep the old one until it has a size.
330        if size.width == 0 || size.height == 0 {
331            return;
332        }
333
334        surface.configure(&self.device, &self.configuration(size));
335
336        self.create_depth_stencil_texture(size.width, size.height);
337
338        // Update state
339        self.surface_configured.set(true);
340        self.surface_needs_reconfigure.set(false);
341        self.last_configured_size.set(size);
342        self.consecutive_errors.set(0);
343    }
344
345    /// `createDepthStencilTexture(width, height)`
346    fn create_depth_stencil_texture(&self, width: u32, height: u32) {
347        self.depth_stencil.borrow_mut().take();
348
349        let format = self.depth_stencil_format;
350        if width == 0 || height == 0 {
351            return;
352        }
353
354        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
355            label: Some("DepthStencilTexture"),
356            size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
357            mip_level_count: 1,
358            sample_count: 1,
359            dimension: wgpu::TextureDimension::D2,
360            format,
361            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
362            view_formats: &[],
363        });
364        let view = texture.create_view(&wgpu::TextureViewDescriptor {
365            label: Some("DepthStencilTextureView"),
366            format: Some(format),
367            dimension: Some(wgpu::TextureViewDimension::D2),
368            usage: None,
369            aspect: wgpu::TextureAspect::All,
370            base_mip_level: 0,
371            mip_level_count: Some(1),
372            base_array_layer: 0,
373            array_layer_count: Some(1),
374        });
375        *self.depth_stencil.borrow_mut() = Some((texture, view));
376    }
377
378    /// Port-only: copies the swapchain texture into a buffer and starts
379    /// mapping it (`finish_readback` makes the image).
380    fn copy_texture(&self, texture: &wgpu::Texture) -> Option<PendingReadback> {
381        if !self.surface_usage.get().contains(wgpu::TextureUsages::COPY_SRC) {
382            Log::warning(Event::Render, "WebGPU: the surface does not support readback (no COPY_SRC)");
383            return None;
384        }
385        let (width, height) = (texture.width(), texture.height());
386        let bytes_per_row =
387            (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
388        let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
389            label: Some("Surface readback"),
390            size: u64::from(bytes_per_row) * u64::from(height),
391            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
392            mapped_at_creation: false,
393        });
394        let mut encoder =
395            self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Surface readback") });
396        encoder.copy_texture_to_buffer(
397            texture.as_image_copy(),
398            wgpu::TexelCopyBufferInfo {
399                buffer: &buffer,
400                layout: wgpu::TexelCopyBufferLayout {
401                    offset: 0,
402                    bytes_per_row: Some(bytes_per_row),
403                    rows_per_image: Some(height),
404                },
405            },
406            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
407        );
408        self.queue.submit([encoder.finish()]);
409        let (tx, mapped) = std::sync::mpsc::channel();
410        buffer.map_async(wgpu::MapMode::Read, .., move |result| {
411            let _ = tx.send(result);
412        });
413        Some(PendingReadback { buffer, bytes_per_row, size: Size::new(width, height), mapped })
414    }
415
416    /// Port-only: turns the pending copy into an RGBA image once it is
417    /// mapped (drops it if mapping failed).
418    fn finish_readback(&self) {
419        let mut pending = self.pending_readback.borrow_mut();
420        let Some(readback) = pending.take() else {
421            return;
422        };
423        match readback.mapped.try_recv() {
424            Err(std::sync::mpsc::TryRecvError::Empty) => {
425                *pending = Some(readback);
426                return;
427            }
428            Ok(Ok(())) => {}
429            Ok(Err(_)) | Err(std::sync::mpsc::TryRecvError::Disconnected) => return,
430        }
431        let PendingReadback { buffer, bytes_per_row, size, .. } = readback;
432        let (width, height) = (size.width, size.height);
433        let bgra =
434            matches!(self.swap_chain_format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb);
435        let mut image = PremultipliedImage::new(size);
436        {
437            let Ok(mapped) = buffer.get_mapped_range(..) else {
438                return;
439            };
440            for y in 0..height as usize {
441                let src = &mapped[y * bytes_per_row as usize..][..width as usize * 4];
442                let dst = &mut image.data[y * width as usize * 4..][..width as usize * 4];
443                dst.copy_from_slice(src);
444                if bgra {
445                    for px in dst.as_chunks_mut::<4>().0 {
446                        px.swap(0, 2);
447                    }
448                }
449            }
450        }
451        buffer.unmap();
452        *self.readback.borrow_mut() = Some(image);
453    }
454}
455
456/// `WebGPURenderableResource`: the swapchain's texture as a draw target.
457struct SurfaceResource {
458    state: Rc<SurfaceState>,
459}
460
461impl TargetResource for SurfaceResource {
462    fn get_color_texture_view(&self) -> Option<wgpu::TextureView> {
463        self.state.get_current_texture_view()
464    }
465
466    fn get_color_texture_format(&self) -> Option<wgpu::TextureFormat> {
467        Some(self.state.swap_chain_format)
468    }
469
470    fn get_depth_stencil_texture_view(&self) -> Option<wgpu::TextureView> {
471        self.state.get_depth_stencil_view()
472    }
473
474    fn get_depth_stencil_texture_format(&self) -> Option<wgpu::TextureFormat> {
475        Some(self.state.depth_stencil_format)
476    }
477
478    fn as_any(&self) -> &dyn Any {
479        self
480    }
481}
482
483/// How a [`SurfaceTarget`] presents.
484#[derive(Clone, Copy, Debug)]
485pub struct SurfaceOptions {
486    /// Present in step with the display. Off, frames are presented at once,
487    /// tearing.
488    pub cap_frame_rate: bool,
489    /// The usages the surface supports, where the host knows them better
490    /// than the device's adapter does, as for a browser's canvas, or where
491    /// the device has no adapter. Frames can be read back when they have
492    /// `COPY_SRC`.
493    pub usages: Option<wgpu::TextureUsages>,
494}
495
496impl Default for SurfaceOptions {
497    fn default() -> Self {
498        SurfaceOptions { cap_frame_rate: true, usages: None }
499    }
500}
501
502/// `GLFWWebGPUBackend`'s surface without the window: frames presented to a
503/// `wgpu::Surface`.
504pub struct SurfaceTarget {
505    backend: Rc<RendererBackend>,
506    state: Rc<SurfaceState>,
507    image: Rc<DrawTarget>,
508}
509
510impl SurfaceTarget {
511    /// A target on `backend` that presents to `surface`, made with the
512    /// instance of the backend's device, at `framebuffer_size` physical
513    /// pixels. The surface is configured with the device's surface format,
514    /// or with the first of BGRA8 and RGBA8 that the surface supports.
515    ///
516    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
517    /// device's adapter can't present to the surface or the surface supports
518    /// none of those formats, and with
519    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) when the device
520    /// has neither an adapter to ask nor a surface format.
521    pub fn new(
522        backend: Rc<RendererBackend>,
523        surface: wgpu::Surface<'static>,
524        framebuffer_size: Size,
525        options: SurfaceOptions,
526    ) -> Result<SurfaceTarget, Error> {
527        let device = backend.device();
528        let (swap_chain_format, mut surface_usage, present_mode) = if let Some(adapter) = device.adapter() {
529            let capabilities = surface.get_capabilities(adapter);
530            if capabilities.formats.is_empty() {
531                return Err(Error::unsupported("The WebGPU adapter can't present to the surface"));
532            }
533            let format = match device.surface_format() {
534                Some(format) if capabilities.formats.contains(&format) => format,
535                Some(format) => {
536                    return Err(Error::unsupported(format!("The surface does not take the {format:?} format")));
537                }
538                None => [
539                    wgpu::TextureFormat::Bgra8Unorm,
540                    wgpu::TextureFormat::Bgra8UnormSrgb,
541                    wgpu::TextureFormat::Rgba8Unorm,
542                    wgpu::TextureFormat::Rgba8UnormSrgb,
543                ]
544                .into_iter()
545                .find(|f| capabilities.formats.contains(f))
546                .ok_or_else(|| Error::unsupported("The surface takes none of the formats the map renders in"))?,
547            };
548            let (usage, present_mode) = surface_options(&capabilities);
549            (format, usage, present_mode)
550        } else {
551            let format = device.surface_format().ok_or_else(|| {
552                Error::invalid_argument("A surface on a device without an adapter needs the device's surface format")
553            })?;
554            (format, wgpu::TextureUsages::RENDER_ATTACHMENT, wgpu::PresentMode::Fifo)
555        };
556        if let Some(usages) = options.usages {
557            surface_usage = wgpu::TextureUsages::RENDER_ATTACHMENT | (usages & wgpu::TextureUsages::COPY_SRC);
558        }
559        let depth_stencil_format = if device.device().features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
560            wgpu::TextureFormat::Depth32FloatStencil8
561        } else {
562            wgpu::TextureFormat::Depth24PlusStencil8
563        };
564
565        let info = device.adapter_info();
566        Log::info(
567            Event::Render,
568            format!(
569                "WebGPU: Selected adapter backend = {}, name = {}",
570                backend_type_to_string(info.backend),
571                if info.name.is_empty() { "<unknown>" } else { &info.name }
572            ),
573        );
574
575        let state = Rc::new(SurfaceState {
576            surface: RefCell::new(Some(surface)),
577            device: device.device().clone(),
578            queue: device.queue().clone(),
579            swap_chain_format,
580            surface_usage: Cell::new(surface_usage),
581            depth_stencil_format,
582            current: RefCell::new(None),
583            depth_stencil: RefCell::new(None),
584            frame_presented: Cell::new(true),
585            surface_configured: Cell::new(false),
586            // Configured with the first frame (see the file comment).
587            surface_needs_reconfigure: Cell::new(true),
588            last_configured_size: Cell::new(Size::default()),
589            consecutive_errors: Cell::new(0),
590            enable_vsync: options.cap_frame_rate,
591            vsync_present_mode: Cell::new(present_mode),
592            framebuffer_size: Cell::new(framebuffer_size),
593            last_swap_time: Cell::new(Instant::now()),
594            readback_requested: Cell::new(false),
595            pending_readback: RefCell::new(None),
596            readback: RefCell::new(None),
597            overlay: RefCell::new(None),
598        });
599        let image = Rc::new(DrawTarget::new(framebuffer_size, SurfaceResource { state: state.clone() }));
600        Ok(SurfaceTarget { backend, state, image })
601    }
602
603    /// The backend the target draws on.
604    #[must_use]
605    pub fn backend(&self) -> &Rc<RendererBackend> {
606        &self.backend
607    }
608
609    /// The format the surface is configured with.
610    #[must_use]
611    pub fn format(&self) -> wgpu::TextureFormat {
612        self.state.swap_chain_format
613    }
614
615    /// The size of the frames, in physical pixels.
616    #[must_use]
617    pub fn size(&self) -> Size {
618        self.state.framebuffer_size.get()
619    }
620
621    /// `setFramebufferSize(Size)`: draws the next frame at `size` physical
622    /// pixels.
623    pub fn resize(&self, size: Size) {
624        if self.state.framebuffer_size.replace(size) != size {
625            self.image.set_size(size);
626            self.state.surface_needs_reconfigure.set(true);
627        }
628    }
629
630    /// `processEvents()`
631    pub fn process_events(&self) {
632        self.state.process_events();
633    }
634
635    /// Port-only: copy the next presented frame (see `take_readback`).
636    pub fn request_readback(&self) {
637        self.state.readback_requested.set(true);
638    }
639
640    /// Port-only: the frame copied after `request_readback`, once presented
641    /// and mapped (natively at once; in the browser on a later turn of the
642    /// event loop).
643    #[must_use]
644    pub fn take_readback(&self) -> Option<PremultipliedImage> {
645        self.state.finish_readback();
646        self.state.readback.borrow_mut().take()
647    }
648
649    /// Port-only: draws `overlay` over each frame from now on, after the map
650    /// and before the frame is presented (and read back), or stops with
651    /// `None`.
652    pub fn set_overlay(&self, overlay: Option<Overlay>) {
653        *self.state.overlay.borrow_mut() = overlay;
654    }
655}
656
657impl FrameTarget for SurfaceTarget {
658    /// Acquires the surface's next texture, unless the frame has one. A
659    /// frame without one is skipped: a render pass without a color
660    /// attachment trips the drawables' debug assertions.
661    fn begin_frame(&self) -> Option<Rc<dyn frame::DrawTarget>> {
662        self.state.get_current_texture_view()?;
663        Some(self.image.clone())
664    }
665
666    fn end_frame(&self, encoder: &dyn GfxCommandEncoder) -> Handoff {
667        if let Some(encoder) = encoder.as_any().downcast_ref::<CommandEncoder>() {
668            encoder.submit_frame(Some(self.image.resource()));
669        }
670        if self.state.swap() { Handoff::Presented } else { Handoff::Dropped }
671    }
672}
673
674impl Drop for SurfaceTarget {
675    fn drop(&mut self) {
676        // ~GLFWWebGPUBackend: release the textures and pump outstanding
677        // callbacks; the swapchain texture goes before the surface.
678        self.state.current.borrow_mut().take();
679        self.state.depth_stencil.borrow_mut().take();
680        self.state.overlay.borrow_mut().take();
681        self.state.process_events();
682        self.state.surface.borrow_mut().take();
683    }
684}