Skip to main content

mln_webgpu/
surface_backend.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// a `webgpu::RendererBackend` that is its own default `gfx::Renderable` and
4// presents to a `wgpu::Surface`. The GLFW specifics (window, raw handles,
5// framebuffer size queries) stay in //platform/glfw, which creates the
6// surface and reports framebuffer resizes through `set_framebuffer_size`.
7//
8// Differences from C++, all structural (see DEVIATIONS.md [glfw]):
9// - The C++ backend reads `glfwGetFramebufferSize` where it needs the size;
10//   here the window reports it (`set_framebuffer_size`, also what C++'s
11//   `onFramebufferResize` calls), so `reconfigureSurface` and the depth
12//   texture use the size last reported.
13// - C++ reconfigures a resized surface in `swap()`, after rendering one
14//   frame into the old-size swapchain texture with the new-size viewport
15//   (Dawn logs a validation error for it). The port also reconfigures
16//   before acquiring the next texture when a reconfigure is pending.
17// - Single-threaded (the renderer runs on the main thread): the spin lock,
18//   `frameInProgress` (never set in C++) and `isShuttingDown` atomics are
19//   plain cells, and `waitForFrame` always succeeds immediately as in C++.
20// - wgpu's default uncaptured-error handler panics; like the C++ Dawn
21//   branch (`logUncapturedError`), errors are logged instead.
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
26use std::any::Any;
27use std::cell::{Cell, RefCell};
28use std::rc::Rc;
29use std::time::{Duration, Instant};
30
31use mln_gfx::context::Context as GfxContext;
32use mln_gfx::renderable::{Renderable, RenderableBase};
33use mln_gfx::renderer_backend::{self, ContextMode, RendererBackendBase};
34use mln_gfx::shader_registry::ShaderRegistry;
35use mln_gfx::shaders::program_parameters::ProgramParameters;
36use mln_util::image::PremultipliedImage;
37use mln_util::logging::{Event, Log};
38use mln_util::size::Size;
39
40use crate::renderable_resource::{RenderableResource, RenderableResourceBox};
41use crate::renderer_backend::RendererBackend;
42
43/// `maxConsecutiveErrors`
44const MAX_CONSECUTIVE_ERRORS: i32 = 3;
45
46/// `backendTypeToString`
47fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
48    match backend {
49        wgpu::Backend::Noop => "Null",
50        wgpu::Backend::BrowserWebGpu => "WebGPU",
51        wgpu::Backend::Dx12 => "D3D12",
52        wgpu::Backend::Metal => "Metal",
53        wgpu::Backend::Vulkan => "Vulkan",
54        wgpu::Backend::Gl => "OpenGL",
55    }
56}
57
58/// The instance backends, as the headless backend picks them: `WGPU_BACKEND`
59/// if set, else Vulkan on Linux (C++ wgpu-native: the default instance).
60fn instance_backends() -> wgpu::Backends {
61    if let Some(backends) = wgpu::Backends::from_env() {
62        return backends;
63    }
64    if cfg!(target_os = "linux") { wgpu::Backends::VULKAN } else { wgpu::Backends::all() }
65}
66
67/// The current swapchain texture and its view (`currentTexture`,
68/// `currentTextureView`).
69struct CurrentTexture {
70    texture: wgpu::SurfaceTexture,
71    view: wgpu::TextureView,
72}
73
74/// The members of `GLFWWebGPUBackend` that the renderable resource reaches
75/// through its `backend` reference in C++.
76pub struct SurfaceState {
77    surface: wgpu::Surface<'static>,
78    device: wgpu::Device,
79    queue: wgpu::Queue,
80    swap_chain_format: wgpu::TextureFormat,
81    surface_usage: wgpu::TextureUsages,
82    depth_stencil_format: Cell<Option<wgpu::TextureFormat>>,
83
84    current: RefCell<Option<CurrentTexture>>,
85    depth_stencil: RefCell<Option<(wgpu::Texture, wgpu::TextureView)>>,
86
87    frame_presented: Cell<bool>,
88    surface_configured: Cell<bool>,
89    surface_needs_reconfigure: Cell<bool>,
90    last_configured_size: Cell<Size>,
91    consecutive_errors: Cell<i32>,
92    enable_vsync: bool,
93    /// symbols (user report: the window froze while hidden): the vsync'ed
94    /// present mode. FIFO blocks in acquire/present on Wayland while the
95    /// window is not visible (no frame callbacks), which stalls the whole
96    /// event loop; MAILBOX is vsync'ed without blocking, so it is used when
97    /// the surface supports it (DEVIATIONS.md).
98    vsync_present_mode: wgpu::PresentMode,
99    /// What `glfwGetFramebufferSize` returns in C++.
100    framebuffer_size: Cell<Size>,
101    /// `static auto lastSwapTime` in `swap()`.
102    last_swap_time: Cell<Instant>,
103
104    readback_requested: Cell<bool>,
105    readback: RefCell<Option<PremultipliedImage>>,
106}
107
108impl SurfaceState {
109    fn configuration(&self, size: Size) -> wgpu::SurfaceConfiguration {
110        wgpu::SurfaceConfiguration {
111            usage: self.surface_usage,
112            format: self.swap_chain_format,
113            width: size.width,
114            height: size.height,
115            // Use Immediate mode (no vsync) in benchmark mode, Fifo (vsync) otherwise
116            present_mode: if self.enable_vsync { self.vsync_present_mode } else { wgpu::PresentMode::Immediate },
117            desired_maximum_frame_latency: 2,
118            alpha_mode: wgpu::CompositeAlphaMode::Auto,
119            view_formats: vec![self.swap_chain_format],
120            color_space: wgpu::SurfaceColorSpace::Auto,
121        }
122    }
123
124    /// `processEvents()`: `wgpuDevicePoll(device, false)`.
125    fn process_events(&self) {
126        let _ = self.device.poll(wgpu::PollType::Poll);
127    }
128
129    /// `swap()`: presents the current frame.
130    fn swap(&self) {
131        let now = Instant::now();
132        let time_since_last_swap = now.duration_since(self.last_swap_time.get());
133
134        // If it's been too long since last swap, tick the device to keep it alive
135        if time_since_last_swap > Duration::from_millis(1000) {
136            self.process_events();
137            // Only reconfigure if really needed (> 10 seconds)
138            if time_since_last_swap > Duration::from_millis(10000) && self.surface_configured.get() {
139                self.surface_needs_reconfigure.set(true);
140            }
141        }
142        self.last_swap_time.set(now);
143
144        // Note: Command buffer is already submitted in CommandEncoder::present()
145        // before swap() is called, so we don't need to submit it again here.
146
147        // Present the current frame
148        if self.surface_configured.get() {
149            // Check if surface needs reconfiguration
150            if self.surface_needs_reconfigure.get() {
151                self.reconfigure_surface();
152            }
153
154            // Only present if we have a valid texture view and haven't presented yet
155            let current = if self.frame_presented.get() { None } else { self.current.borrow_mut().take() };
156            {
157                if let Some(current) = current {
158                    if self.readback_requested.get() {
159                        self.readback_requested.set(false);
160                        *self.readback.borrow_mut() = self.read_texture(&current.texture.texture);
161                    }
162                    drop(current.view);
163                    self.queue.present(current.texture);
164                    self.frame_presented.set(true);
165                }
166            }
167
168            // Reset error counter on successful present
169            self.consecutive_errors.set(0);
170        }
171
172        // signalFrameComplete(): `frameInProgress` is never set (see the
173        // file comment). C++ calls glfwPollEvents here; the GLFW wrapper does.
174    }
175
176    /// `getCurrentTextureView()`
177    fn get_current_texture_view(&self) -> Option<wgpu::TextureView> {
178        if !self.surface_configured.get() {
179            return None;
180        }
181
182        // Check error threshold
183        if self.consecutive_errors.get() >= MAX_CONSECUTIVE_ERRORS {
184            // Too many errors, need to reconfigure
185            self.surface_needs_reconfigure.set(true);
186            self.reconfigure_surface();
187            self.consecutive_errors.set(0);
188        }
189
190        if let Some(current) = self.current.borrow().as_ref()
191            && !self.frame_presented.get()
192        {
193            return Some(current.view.clone());
194        }
195
196        // Always release textures before acquiring new ones to avoid "already acquired" error
197        self.current.borrow_mut().take();
198        self.frame_presented.set(false);
199
200        // Port: apply a pending resize before acquiring (see the file comment).
201        if self.surface_needs_reconfigure.get() {
202            self.reconfigure_surface();
203        }
204
205        let surface_texture = match self.surface.get_current_texture() {
206            wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
207            wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
208                self.surface_needs_reconfigure.set(true);
209                self.consecutive_errors.set(self.consecutive_errors.get() + 1);
210                return None;
211            }
212            wgpu::CurrentSurfaceTexture::Timeout
213            | wgpu::CurrentSurfaceTexture::Occluded
214            | wgpu::CurrentSurfaceTexture::Validation => {
215                self.consecutive_errors.set(self.consecutive_errors.get() + 1);
216                return None;
217            }
218        };
219
220        // Create texture view with explicit descriptor
221        let view = surface_texture.texture.create_view(&wgpu::TextureViewDescriptor {
222            label: Some("SwapChain TextureView"),
223            format: Some(self.swap_chain_format),
224            dimension: Some(wgpu::TextureViewDimension::D2),
225            usage: None,
226            aspect: wgpu::TextureAspect::All,
227            base_mip_level: 0,
228            mip_level_count: Some(1),
229            base_array_layer: 0,
230            array_layer_count: Some(1),
231        });
232
233        // Store the texture to keep it alive
234        *self.current.borrow_mut() = Some(CurrentTexture { texture: surface_texture, view: view.clone() });
235
236        // Success - reset error counter
237        self.consecutive_errors.set(0);
238        Some(view)
239    }
240
241    /// `getDepthStencilView()`
242    fn get_depth_stencil_view(&self) -> Option<wgpu::TextureView> {
243        if self.depth_stencil.borrow().is_none() {
244            let size = self.framebuffer_size.get();
245            self.create_depth_stencil_texture(size.width, size.height);
246        }
247        self.depth_stencil.borrow().as_ref().map(|(_, view)| view.clone())
248    }
249
250    /// `reconfigureSurface()`
251    fn reconfigure_surface(&self) {
252        // Wait for any in-progress frame: never in progress (file comment).
253
254        // Clear all texture state
255        self.current.borrow_mut().take();
256
257        // Get current size
258        let size = self.framebuffer_size.get();
259
260        // Skip if size hasn't changed and we're already configured
261        if self.surface_configured.get() && self.last_configured_size.get() == size {
262            self.surface_needs_reconfigure.set(false);
263            return;
264        }
265
266        // wgpu (unlike wgpu-native) rejects a zero-sized configuration, which
267        // a minimized window reports; keep the old one until it has a size.
268        if size.width == 0 || size.height == 0 {
269            return;
270        }
271
272        self.surface.configure(&self.device, &self.configuration(size));
273
274        self.create_depth_stencil_texture(size.width, size.height);
275
276        // Update state
277        self.surface_configured.set(true);
278        self.surface_needs_reconfigure.set(false);
279        self.last_configured_size.set(size);
280        self.consecutive_errors.set(0);
281    }
282
283    /// `createDepthStencilTexture(width, height)`
284    fn create_depth_stencil_texture(&self, width: u32, height: u32) {
285        self.depth_stencil.borrow_mut().take();
286
287        let Some(format) = self.depth_stencil_format.get() else {
288            return;
289        };
290        if width == 0 || height == 0 {
291            return;
292        }
293
294        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
295            label: Some("DepthStencilTexture"),
296            size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
297            mip_level_count: 1,
298            sample_count: 1,
299            dimension: wgpu::TextureDimension::D2,
300            format,
301            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
302            view_formats: &[],
303        });
304        let view = texture.create_view(&wgpu::TextureViewDescriptor {
305            label: Some("DepthStencilTextureView"),
306            format: Some(format),
307            dimension: Some(wgpu::TextureViewDimension::D2),
308            usage: None,
309            aspect: wgpu::TextureAspect::All,
310            base_mip_level: 0,
311            mip_level_count: Some(1),
312            base_array_layer: 0,
313            array_layer_count: Some(1),
314        });
315        *self.depth_stencil.borrow_mut() = Some((texture, view));
316    }
317
318    /// Port-only: copies the swapchain texture into an RGBA image.
319    fn read_texture(&self, texture: &wgpu::Texture) -> Option<PremultipliedImage> {
320        if !self.surface_usage.contains(wgpu::TextureUsages::COPY_SRC) {
321            Log::warning(Event::Render, "WebGPU: the surface does not support readback (no COPY_SRC)");
322            return None;
323        }
324        let (width, height) = (texture.width(), texture.height());
325        let bytes_per_row =
326            (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
327        let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
328            label: Some("Surface readback"),
329            size: u64::from(bytes_per_row) * u64::from(height),
330            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
331            mapped_at_creation: false,
332        });
333        let mut encoder =
334            self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Surface readback") });
335        encoder.copy_texture_to_buffer(
336            texture.as_image_copy(),
337            wgpu::TexelCopyBufferInfo {
338                buffer: &buffer,
339                layout: wgpu::TexelCopyBufferLayout {
340                    offset: 0,
341                    bytes_per_row: Some(bytes_per_row),
342                    rows_per_image: Some(height),
343                },
344            },
345            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
346        );
347        self.queue.submit([encoder.finish()]);
348        let (tx, rx) = std::sync::mpsc::channel();
349        buffer.map_async(wgpu::MapMode::Read, .., move |result| {
350            let _ = tx.send(result);
351        });
352        if self.device.poll(wgpu::PollType::wait_indefinitely()).is_err() {
353            return None;
354        }
355        if !matches!(rx.try_recv(), Ok(Ok(()))) {
356            return None;
357        }
358        let bgra =
359            matches!(self.swap_chain_format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb);
360        let mut image = PremultipliedImage::new(Size::new(width, height));
361        {
362            let mapped = buffer.get_mapped_range(..).ok()?;
363            for y in 0..height as usize {
364                let src = &mapped[y * bytes_per_row as usize..][..width as usize * 4];
365                let dst = &mut image.data[y * width as usize * 4..][..width as usize * 4];
366                dst.copy_from_slice(src);
367                if bgra {
368                    for px in dst.chunks_exact_mut(4) {
369                        px.swap(0, 2);
370                    }
371                }
372            }
373        }
374        buffer.unmap();
375        Some(image)
376    }
377}
378
379/// `WebGPURenderableResource`: the swapchain as a renderable resource.
380struct SurfaceRenderableResource {
381    state: Rc<SurfaceState>,
382}
383
384impl RenderableResource for SurfaceRenderableResource {
385    fn bind(&self) {
386        // Nothing to do here for WebGPU as command encoder is managed by
387        // CommandEncoder class
388    }
389
390    fn swap(&self) {
391        // The command buffer submission happens in CommandEncoder::present()
392        // Here we just present the surface
393        self.state.swap();
394    }
395
396    fn get_color_texture_view(&self) -> Option<wgpu::TextureView> {
397        self.state.get_current_texture_view()
398    }
399
400    fn get_depth_stencil_texture_view(&self) -> Option<wgpu::TextureView> {
401        self.state.get_depth_stencil_view()
402    }
403
404    fn as_any(&self) -> &dyn Any {
405        self
406    }
407}
408
409/// What `SurfaceBackend::finish` builds on.
410struct Parts {
411    instance: wgpu::Instance,
412    adapter: Option<wgpu::Adapter>,
413    device: wgpu::Device,
414    queue: wgpu::Queue,
415    surface: wgpu::Surface<'static>,
416}
417
418/// The surface configuration `SurfaceBackend::finish` uses.
419struct SurfaceChoice {
420    swap_chain_format: wgpu::TextureFormat,
421    surface_usage: wgpu::TextureUsages,
422    present_mode: wgpu::PresentMode,
423    depth_stencil_format: wgpu::TextureFormat,
424}
425
426/// `GLFWWebGPUBackend` without the window: a `webgpu::RendererBackend` and
427/// `gfx::Renderable` presenting to a surface.
428pub struct SurfaceBackend {
429    renderer_backend: RendererBackend,
430    renderable: RenderableBase,
431    state: Rc<SurfaceState>,
432    adapter_info: wgpu::AdapterInfo,
433}
434
435impl SurfaceBackend {
436    /// The constructor of `GLFWWebGPUBackend(window, capFrameRate)` from the
437    /// instance on: adapter, device, surface (made by `create_surface` from
438    /// the window's handles), format selection and configuration.
439    pub fn new(
440        create_surface: impl FnOnce(&wgpu::Instance) -> Result<wgpu::Surface<'static>, String>,
441        framebuffer_size: Size,
442        cap_frame_rate: bool,
443    ) -> Result<SurfaceBackend, String> {
444        let renderer_backend = RendererBackend::new(ContextMode::Unique);
445
446        // Create the instance
447        let instance = crate::headless_backend::create_instance(instance_backends());
448
449        // Request adapter
450        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
451            power_preference: wgpu::PowerPreference::HighPerformance,
452            ..Default::default()
453        }))
454        .map_err(|e| format!("No WebGPU adapter found: {e}"))?;
455
456        // Log adapter info
457        let adapter_info = adapter.get_info();
458        Log::info(
459            Event::Render,
460            format!(
461                "WebGPU: Selected adapter backend = {}, name = {}",
462                backend_type_to_string(adapter_info.backend),
463                if adapter_info.name.is_empty() { "<unknown>" } else { &adapter_info.name }
464            ),
465        );
466
467        let has_depth32_stencil = adapter.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8);
468        let (required_features, depth_stencil_format) = if has_depth32_stencil {
469            (wgpu::Features::DEPTH32FLOAT_STENCIL8, wgpu::TextureFormat::Depth32FloatStencil8)
470        } else {
471            (wgpu::Features::empty(), wgpu::TextureFormat::Depth24PlusStencil8)
472        };
473
474        // The WebGPU default limits, lowered to what the adapter supports, as
475        // the headless backend requests them.
476        let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
477            label: Some("MapLibre WebGPU Device"),
478            required_features,
479            required_limits: wgpu::Limits::default().or_worse_values_from(&adapter.limits()),
480            ..Default::default()
481        }))
482        .map_err(|e| format!("Failed to create WebGPU device: {e}"))?;
483
484        // Dawn's logUncapturedError instead of wgpu's panicking default.
485        device.on_uncaptured_error(std::sync::Arc::new(|error: wgpu::Error| {
486            Log::error(Event::Render, format!("WebGPU validation error: {error}"));
487        }));
488
489        renderer_backend.set_depth_stencil_format(Some(depth_stencil_format));
490
491        // Process device events to ensure it's ready
492        let _ = device.poll(wgpu::PollType::Poll);
493
494        // Create surface for WebGPU
495        let surface = create_surface(&instance)?;
496
497        let capabilities = surface.get_capabilities(&adapter);
498        let preferred_formats = [
499            wgpu::TextureFormat::Bgra8Unorm,
500            wgpu::TextureFormat::Bgra8UnormSrgb,
501            wgpu::TextureFormat::Rgba8Unorm,
502            wgpu::TextureFormat::Rgba8UnormSrgb,
503        ];
504        let swap_chain_format = preferred_formats
505            .into_iter()
506            .find(|f| capabilities.formats.contains(f))
507            .or_else(|| capabilities.formats.first().copied())
508            .unwrap_or(wgpu::TextureFormat::Bgra8Unorm);
509        let mut surface_usage = wgpu::TextureUsages::RENDER_ATTACHMENT;
510        if capabilities.usages.contains(wgpu::TextureUsages::COPY_SRC) {
511            surface_usage |= wgpu::TextureUsages::COPY_SRC;
512        }
513
514        let present_mode = if capabilities.present_modes.contains(&wgpu::PresentMode::Mailbox) {
515            wgpu::PresentMode::Mailbox
516        } else {
517            wgpu::PresentMode::Fifo
518        };
519        Ok(Self::finish(
520            renderer_backend,
521            Parts { instance, adapter: Some(adapter), device, queue, surface },
522            SurfaceChoice { swap_chain_format, surface_usage, present_mode, depth_stencil_format },
523            framebuffer_size,
524            cap_frame_rate,
525            adapter_info,
526        ))
527    }
528
529    /// Port-only: a backend on a device and surface that the host created,
530    /// as maplibre-native-ffi's `mln_map_attach_web_gpu_surface` passes them,
531    /// or a browser's WebGPU through a custom wgpu backend. There is no
532    /// adapter: the surface is configured with `format`, for rendering only,
533    /// and presents in FIFO order, which every surface supports.
534    pub fn from_host(
535        instance: wgpu::Instance,
536        device: wgpu::Device,
537        queue: wgpu::Queue,
538        surface: wgpu::Surface<'static>,
539        format: wgpu::TextureFormat,
540        framebuffer_size: Size,
541    ) -> SurfaceBackend {
542        let renderer_backend = RendererBackend::new(ContextMode::Unique);
543        let adapter_info = device.adapter_info();
544        let depth_stencil_format = if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
545            wgpu::TextureFormat::Depth32FloatStencil8
546        } else {
547            wgpu::TextureFormat::Depth24PlusStencil8
548        };
549        device.on_uncaptured_error(std::sync::Arc::new(|error: wgpu::Error| {
550            Log::error(Event::Render, format!("WebGPU validation error: {error}"));
551        }));
552        renderer_backend.set_depth_stencil_format(Some(depth_stencil_format));
553        Self::finish(
554            renderer_backend,
555            Parts { instance, adapter: None, device, queue, surface },
556            SurfaceChoice {
557                swap_chain_format: format,
558                surface_usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
559                present_mode: wgpu::PresentMode::Fifo,
560                depth_stencil_format,
561            },
562            framebuffer_size,
563            true,
564            adapter_info,
565        )
566    }
567
568    /// The rest of the construction, once the device, surface and formats
569    /// are there.
570    fn finish(
571        renderer_backend: RendererBackend,
572        parts: Parts,
573        choice: SurfaceChoice,
574        framebuffer_size: Size,
575        cap_frame_rate: bool,
576        adapter_info: wgpu::AdapterInfo,
577    ) -> SurfaceBackend {
578        let Parts { instance, adapter, device, queue, surface } = parts;
579        let SurfaceChoice { swap_chain_format, surface_usage, present_mode, depth_stencil_format } = choice;
580        renderer_backend.set_color_format(Some(swap_chain_format));
581
582        let backend_impl = renderer_backend.backend_impl().clone();
583        let state = Rc::new(SurfaceState {
584            surface,
585            device: device.clone(),
586            queue: queue.clone(),
587            swap_chain_format,
588            surface_usage,
589            depth_stencil_format: Cell::new(Some(depth_stencil_format)),
590            current: RefCell::new(None),
591            depth_stencil: RefCell::new(None),
592            frame_presented: Cell::new(true),
593            surface_configured: Cell::new(false),
594            surface_needs_reconfigure: Cell::new(false),
595            last_configured_size: Cell::new(Size::default()),
596            consecutive_errors: Cell::new(0),
597            enable_vsync: cap_frame_rate,
598            vsync_present_mode: present_mode,
599            framebuffer_size: Cell::new(framebuffer_size),
600            last_swap_time: Cell::new(Instant::now()),
601            readback_requested: Cell::new(false),
602            readback: RefCell::new(None),
603        });
604
605        // Configure surface
606        if framebuffer_size.width > 0 && framebuffer_size.height > 0 {
607            state.surface.configure(&device, &state.configuration(framebuffer_size));
608            state.surface_configured.set(true);
609            state.last_configured_size.set(framebuffer_size);
610        } else {
611            state.surface_needs_reconfigure.set(true);
612        }
613
614        // Store WebGPU instance, device and queue in the base class
615        backend_impl.set_instance(Some(instance));
616        backend_impl.set_adapter(adapter);
617        backend_impl.set_device(Some(device));
618        backend_impl.set_queue(Some(queue));
619
620        let resource = RenderableResourceBox::new_rc(SurfaceRenderableResource { state: state.clone() });
621        SurfaceBackend {
622            renderer_backend,
623            renderable: RenderableBase::new(framebuffer_size, Some(resource)),
624            state,
625            adapter_info,
626        }
627    }
628
629    pub fn webgpu_backend(&self) -> &RendererBackend {
630        &self.renderer_backend
631    }
632
633    /// The adapter in use (name, backend, driver).
634    pub fn get_adapter_info(&self) -> &wgpu::AdapterInfo {
635        &self.adapter_info
636    }
637
638    /// The swapchain format picked from the surface capabilities.
639    pub fn get_swap_chain_format(&self) -> wgpu::TextureFormat {
640        self.state.swap_chain_format
641    }
642
643    /// `getFramebufferSize()`
644    pub fn get_framebuffer_size(&self) -> Size {
645        self.get_size()
646    }
647
648    /// `setFramebufferSize(Size)`
649    pub fn set_framebuffer_size(&self, new_size: Size) {
650        self.state.framebuffer_size.set(new_size);
651        // Update swap chain size if needed
652        if self.get_size() != new_size {
653            self.set_renderable_size(new_size);
654            self.state.surface_needs_reconfigure.set(true);
655        }
656    }
657
658    /// `swap()`
659    pub fn swap(&self) {
660        self.state.swap();
661    }
662
663    /// `processEvents()`
664    pub fn process_events(&self) {
665        self.state.process_events();
666    }
667
668    /// Port-only: acquires the next swapchain texture ahead of a frame;
669    /// false when the surface has none right now (timeout, occluded,
670    /// outdated). The caller skips the frame: a render pass without a color
671    /// attachment trips the drawables' debug assertions.
672    pub fn acquire_next_texture(&self) -> bool {
673        self.state.get_current_texture_view().is_some()
674    }
675
676    /// Port-only: copy the next presented frame (see `take_readback`).
677    pub fn request_readback(&self) {
678        self.state.readback_requested.set(true);
679    }
680
681    /// Port-only: the frame copied after `request_readback`, once presented.
682    pub fn take_readback(&self) -> Option<PremultipliedImage> {
683        self.state.readback.borrow_mut().take()
684    }
685
686    /// The device, for tests and tools.
687    pub fn get_device(&self) -> wgpu::Device {
688        self.state.device.clone()
689    }
690}
691
692impl Drop for SurfaceBackend {
693    fn drop(&mut self) {
694        // ~GLFWWebGPUBackend: context.reset(), release the textures, pump
695        // outstanding callbacks; the surface goes before the device.
696        self.renderer_backend.reset_context();
697        self.state.current.borrow_mut().take();
698        self.state.depth_stencil.borrow_mut().take();
699        self.state.process_events();
700        self.set_resource(None);
701    }
702}
703
704impl Renderable for SurfaceBackend {
705    fn renderable_base(&self) -> &RenderableBase {
706        &self.renderable
707    }
708}
709
710impl renderer_backend::RendererBackend for SurfaceBackend {
711    fn renderer_backend_base(&self) -> &RendererBackendBase {
712        &self.renderer_backend.base
713    }
714
715    fn as_any(&self) -> &dyn Any {
716        self
717    }
718
719    fn get_default_renderable(&self) -> &dyn Renderable {
720        // We directly inherit from gfx::Renderable
721        self
722    }
723
724    fn init_shaders(&self, registry: &ShaderRegistry, parameters: &ProgramParameters) {
725        self.renderer_backend.init_shaders(registry, parameters);
726    }
727
728    fn create_context(&self) -> Rc<dyn GfxContext> {
729        self.renderer_backend.create_context()
730    }
731
732    fn activate(&self) {
733        // WebGPU doesn't need explicit context activation like OpenGL
734    }
735
736    fn deactivate(&self) {
737        // WebGPU doesn't need explicit context deactivation like OpenGL
738    }
739}