mln-rs-webgpu 0.0.8

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
// Ports the window-surface part of platform/glfw/glfw_webgpu_backend.hpp and
// platform/glfw/glfw_webgpu_backend_impl.ipp (the Linux, wgpu-native branch):
// a `webgpu::RendererBackend` that is its own default `gfx::Renderable` and
// presents to a `wgpu::Surface`. The GLFW specifics (window, raw handles,
// framebuffer size queries) stay in //platform/glfw, which creates the
// surface and reports framebuffer resizes through `set_framebuffer_size`.
//
// Differences from C++, all structural (see DEVIATIONS.md [glfw]):
// - The C++ backend reads `glfwGetFramebufferSize` where it needs the size;
//   here the window reports it (`set_framebuffer_size`, also what C++'s
//   `onFramebufferResize` calls), so `reconfigureSurface` and the depth
//   texture use the size last reported.
// - C++ reconfigures a resized surface in `swap()`, after rendering one
//   frame into the old-size swapchain texture with the new-size viewport
//   (Dawn logs a validation error for it). The port also reconfigures
//   before acquiring the next texture when a reconfigure is pending.
// - Single-threaded (the renderer runs on the main thread): the spin lock,
//   `frameInProgress` (never set in C++) and `isShuttingDown` atomics are
//   plain cells, and `waitForFrame` always succeeds immediately as in C++.
// - wgpu's default uncaptured-error handler panics; like the C++ Dawn
//   branch (`logUncapturedError`), errors are logged instead.
// - Port-only: `request_readback` copies the next presented frame into a
//   `PremultipliedImage` (the surface is configured with COPY_SRC when the
//   surface supports it), so a frame can be checked without screenshots.

use std::any::Any;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::{Duration, Instant};

use mln_gfx::context::Context as GfxContext;
use mln_gfx::renderable::{Renderable, RenderableBase};
use mln_gfx::renderer_backend::{self, ContextMode, RendererBackendBase};
use mln_gfx::shader_registry::ShaderRegistry;
use mln_gfx::shaders::program_parameters::ProgramParameters;
use mln_util::image::PremultipliedImage;
use mln_util::logging::{Event, Log};
use mln_util::size::Size;

use crate::renderable_resource::{RenderableResource, RenderableResourceBox};
use crate::renderer_backend::RendererBackend;

/// `maxConsecutiveErrors`
const MAX_CONSECUTIVE_ERRORS: i32 = 3;

/// `backendTypeToString`
fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
    match backend {
        wgpu::Backend::Noop => "Null",
        wgpu::Backend::BrowserWebGpu => "WebGPU",
        wgpu::Backend::Dx12 => "D3D12",
        wgpu::Backend::Metal => "Metal",
        wgpu::Backend::Vulkan => "Vulkan",
        wgpu::Backend::Gl => "OpenGL",
    }
}

/// The instance backends, as the headless backend picks them: `WGPU_BACKEND`
/// if set, else Vulkan on Linux (C++ wgpu-native: the default instance).
fn instance_backends() -> wgpu::Backends {
    if let Some(backends) = wgpu::Backends::from_env() {
        return backends;
    }
    if cfg!(target_os = "linux") { wgpu::Backends::VULKAN } else { wgpu::Backends::all() }
}

/// The current swapchain texture and its view (`currentTexture`,
/// `currentTextureView`).
struct CurrentTexture {
    texture: wgpu::SurfaceTexture,
    view: wgpu::TextureView,
}

/// The members of `GLFWWebGPUBackend` that the renderable resource reaches
/// through its `backend` reference in C++.
pub struct SurfaceState {
    surface: wgpu::Surface<'static>,
    device: wgpu::Device,
    queue: wgpu::Queue,
    swap_chain_format: wgpu::TextureFormat,
    surface_usage: wgpu::TextureUsages,
    depth_stencil_format: Cell<Option<wgpu::TextureFormat>>,

    current: RefCell<Option<CurrentTexture>>,
    depth_stencil: RefCell<Option<(wgpu::Texture, wgpu::TextureView)>>,

    frame_presented: Cell<bool>,
    surface_configured: Cell<bool>,
    surface_needs_reconfigure: Cell<bool>,
    last_configured_size: Cell<Size>,
    consecutive_errors: Cell<i32>,
    enable_vsync: bool,
    /// symbols (user report: the window froze while hidden): the vsync'ed
    /// present mode. FIFO blocks in acquire/present on Wayland while the
    /// window is not visible (no frame callbacks), which stalls the whole
    /// event loop; MAILBOX is vsync'ed without blocking, so it is used when
    /// the surface supports it (DEVIATIONS.md).
    vsync_present_mode: wgpu::PresentMode,
    /// What `glfwGetFramebufferSize` returns in C++.
    framebuffer_size: Cell<Size>,
    /// `static auto lastSwapTime` in `swap()`.
    last_swap_time: Cell<Instant>,

    readback_requested: Cell<bool>,
    readback: RefCell<Option<PremultipliedImage>>,
}

impl SurfaceState {
    fn configuration(&self, size: Size) -> wgpu::SurfaceConfiguration {
        wgpu::SurfaceConfiguration {
            usage: self.surface_usage,
            format: self.swap_chain_format,
            width: size.width,
            height: size.height,
            // Use Immediate mode (no vsync) in benchmark mode, Fifo (vsync) otherwise
            present_mode: if self.enable_vsync { self.vsync_present_mode } else { wgpu::PresentMode::Immediate },
            desired_maximum_frame_latency: 2,
            alpha_mode: wgpu::CompositeAlphaMode::Auto,
            view_formats: vec![self.swap_chain_format],
            color_space: wgpu::SurfaceColorSpace::Auto,
        }
    }

    /// `processEvents()`: `wgpuDevicePoll(device, false)`.
    fn process_events(&self) {
        let _ = self.device.poll(wgpu::PollType::Poll);
    }

    /// `swap()`: presents the current frame.
    fn swap(&self) {
        let now = Instant::now();
        let time_since_last_swap = now.duration_since(self.last_swap_time.get());

        // If it's been too long since last swap, tick the device to keep it alive
        if time_since_last_swap > Duration::from_millis(1000) {
            self.process_events();
            // Only reconfigure if really needed (> 10 seconds)
            if time_since_last_swap > Duration::from_millis(10000) && self.surface_configured.get() {
                self.surface_needs_reconfigure.set(true);
            }
        }
        self.last_swap_time.set(now);

        // Note: Command buffer is already submitted in CommandEncoder::present()
        // before swap() is called, so we don't need to submit it again here.

        // Present the current frame
        if self.surface_configured.get() {
            // Check if surface needs reconfiguration
            if self.surface_needs_reconfigure.get() {
                self.reconfigure_surface();
            }

            // Only present if we have a valid texture view and haven't presented yet
            let current = if self.frame_presented.get() { None } else { self.current.borrow_mut().take() };
            {
                if let Some(current) = current {
                    if self.readback_requested.get() {
                        self.readback_requested.set(false);
                        *self.readback.borrow_mut() = self.read_texture(&current.texture.texture);
                    }
                    drop(current.view);
                    self.queue.present(current.texture);
                    self.frame_presented.set(true);
                }
            }

            // Reset error counter on successful present
            self.consecutive_errors.set(0);
        }

        // signalFrameComplete(): `frameInProgress` is never set (see the
        // file comment). C++ calls glfwPollEvents here; the GLFW wrapper does.
    }

    /// `getCurrentTextureView()`
    fn get_current_texture_view(&self) -> Option<wgpu::TextureView> {
        if !self.surface_configured.get() {
            return None;
        }

        // Check error threshold
        if self.consecutive_errors.get() >= MAX_CONSECUTIVE_ERRORS {
            // Too many errors, need to reconfigure
            self.surface_needs_reconfigure.set(true);
            self.reconfigure_surface();
            self.consecutive_errors.set(0);
        }

        if let Some(current) = self.current.borrow().as_ref()
            && !self.frame_presented.get()
        {
            return Some(current.view.clone());
        }

        // Always release textures before acquiring new ones to avoid "already acquired" error
        self.current.borrow_mut().take();
        self.frame_presented.set(false);

        // Port: apply a pending resize before acquiring (see the file comment).
        if self.surface_needs_reconfigure.get() {
            self.reconfigure_surface();
        }

        let surface_texture = match self.surface.get_current_texture() {
            wgpu::CurrentSurfaceTexture::Success(texture) | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
            wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
                self.surface_needs_reconfigure.set(true);
                self.consecutive_errors.set(self.consecutive_errors.get() + 1);
                return None;
            }
            wgpu::CurrentSurfaceTexture::Timeout
            | wgpu::CurrentSurfaceTexture::Occluded
            | wgpu::CurrentSurfaceTexture::Validation => {
                self.consecutive_errors.set(self.consecutive_errors.get() + 1);
                return None;
            }
        };

        // Create texture view with explicit descriptor
        let view = surface_texture.texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("SwapChain TextureView"),
            format: Some(self.swap_chain_format),
            dimension: Some(wgpu::TextureViewDimension::D2),
            usage: None,
            aspect: wgpu::TextureAspect::All,
            base_mip_level: 0,
            mip_level_count: Some(1),
            base_array_layer: 0,
            array_layer_count: Some(1),
        });

        // Store the texture to keep it alive
        *self.current.borrow_mut() = Some(CurrentTexture { texture: surface_texture, view: view.clone() });

        // Success - reset error counter
        self.consecutive_errors.set(0);
        Some(view)
    }

    /// `getDepthStencilView()`
    fn get_depth_stencil_view(&self) -> Option<wgpu::TextureView> {
        if self.depth_stencil.borrow().is_none() {
            let size = self.framebuffer_size.get();
            self.create_depth_stencil_texture(size.width, size.height);
        }
        self.depth_stencil.borrow().as_ref().map(|(_, view)| view.clone())
    }

    /// `reconfigureSurface()`
    fn reconfigure_surface(&self) {
        // Wait for any in-progress frame: never in progress (file comment).

        // Clear all texture state
        self.current.borrow_mut().take();

        // Get current size
        let size = self.framebuffer_size.get();

        // Skip if size hasn't changed and we're already configured
        if self.surface_configured.get() && self.last_configured_size.get() == size {
            self.surface_needs_reconfigure.set(false);
            return;
        }

        // wgpu (unlike wgpu-native) rejects a zero-sized configuration, which
        // a minimized window reports; keep the old one until it has a size.
        if size.width == 0 || size.height == 0 {
            return;
        }

        self.surface.configure(&self.device, &self.configuration(size));

        self.create_depth_stencil_texture(size.width, size.height);

        // Update state
        self.surface_configured.set(true);
        self.surface_needs_reconfigure.set(false);
        self.last_configured_size.set(size);
        self.consecutive_errors.set(0);
    }

    /// `createDepthStencilTexture(width, height)`
    fn create_depth_stencil_texture(&self, width: u32, height: u32) {
        self.depth_stencil.borrow_mut().take();

        let Some(format) = self.depth_stencil_format.get() else {
            return;
        };
        if width == 0 || height == 0 {
            return;
        }

        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
            label: Some("DepthStencilTexture"),
            size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("DepthStencilTextureView"),
            format: Some(format),
            dimension: Some(wgpu::TextureViewDimension::D2),
            usage: None,
            aspect: wgpu::TextureAspect::All,
            base_mip_level: 0,
            mip_level_count: Some(1),
            base_array_layer: 0,
            array_layer_count: Some(1),
        });
        *self.depth_stencil.borrow_mut() = Some((texture, view));
    }

    /// Port-only: copies the swapchain texture into an RGBA image.
    fn read_texture(&self, texture: &wgpu::Texture) -> Option<PremultipliedImage> {
        if !self.surface_usage.contains(wgpu::TextureUsages::COPY_SRC) {
            Log::warning(Event::Render, "WebGPU: the surface does not support readback (no COPY_SRC)");
            return None;
        }
        let (width, height) = (texture.width(), texture.height());
        let bytes_per_row =
            (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
        let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Surface readback"),
            size: u64::from(bytes_per_row) * u64::from(height),
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });
        let mut encoder =
            self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Surface readback") });
        encoder.copy_texture_to_buffer(
            texture.as_image_copy(),
            wgpu::TexelCopyBufferInfo {
                buffer: &buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(bytes_per_row),
                    rows_per_image: Some(height),
                },
            },
            wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
        );
        self.queue.submit([encoder.finish()]);
        let (tx, rx) = std::sync::mpsc::channel();
        buffer.map_async(wgpu::MapMode::Read, .., move |result| {
            let _ = tx.send(result);
        });
        if self.device.poll(wgpu::PollType::wait_indefinitely()).is_err() {
            return None;
        }
        if !matches!(rx.try_recv(), Ok(Ok(()))) {
            return None;
        }
        let bgra =
            matches!(self.swap_chain_format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb);
        let mut image = PremultipliedImage::new(Size::new(width, height));
        {
            let mapped = buffer.get_mapped_range(..).ok()?;
            for y in 0..height as usize {
                let src = &mapped[y * bytes_per_row as usize..][..width as usize * 4];
                let dst = &mut image.data[y * width as usize * 4..][..width as usize * 4];
                dst.copy_from_slice(src);
                if bgra {
                    for px in dst.chunks_exact_mut(4) {
                        px.swap(0, 2);
                    }
                }
            }
        }
        buffer.unmap();
        Some(image)
    }
}

/// `WebGPURenderableResource`: the swapchain as a renderable resource.
struct SurfaceRenderableResource {
    state: Rc<SurfaceState>,
}

impl RenderableResource for SurfaceRenderableResource {
    fn bind(&self) {
        // Nothing to do here for WebGPU as command encoder is managed by
        // CommandEncoder class
    }

    fn swap(&self) {
        // The command buffer submission happens in CommandEncoder::present()
        // Here we just present the surface
        self.state.swap();
    }

    fn get_color_texture_view(&self) -> Option<wgpu::TextureView> {
        self.state.get_current_texture_view()
    }

    fn get_depth_stencil_texture_view(&self) -> Option<wgpu::TextureView> {
        self.state.get_depth_stencil_view()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// What `SurfaceBackend::finish` builds on.
struct Parts {
    instance: wgpu::Instance,
    adapter: Option<wgpu::Adapter>,
    device: wgpu::Device,
    queue: wgpu::Queue,
    surface: wgpu::Surface<'static>,
}

/// The surface configuration `SurfaceBackend::finish` uses.
struct SurfaceChoice {
    swap_chain_format: wgpu::TextureFormat,
    surface_usage: wgpu::TextureUsages,
    present_mode: wgpu::PresentMode,
    depth_stencil_format: wgpu::TextureFormat,
}

/// `GLFWWebGPUBackend` without the window: a `webgpu::RendererBackend` and
/// `gfx::Renderable` presenting to a surface.
pub struct SurfaceBackend {
    renderer_backend: RendererBackend,
    renderable: RenderableBase,
    state: Rc<SurfaceState>,
    adapter_info: wgpu::AdapterInfo,
}

impl SurfaceBackend {
    /// The constructor of `GLFWWebGPUBackend(window, capFrameRate)` from the
    /// instance on: adapter, device, surface (made by `create_surface` from
    /// the window's handles), format selection and configuration.
    pub fn new(
        create_surface: impl FnOnce(&wgpu::Instance) -> Result<wgpu::Surface<'static>, String>,
        framebuffer_size: Size,
        cap_frame_rate: bool,
    ) -> Result<SurfaceBackend, String> {
        let renderer_backend = RendererBackend::new(ContextMode::Unique);

        // Create the instance
        let instance = crate::headless_backend::create_instance(instance_backends());

        // Request adapter
        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
            power_preference: wgpu::PowerPreference::HighPerformance,
            ..Default::default()
        }))
        .map_err(|e| format!("No WebGPU adapter found: {e}"))?;

        // Log adapter info
        let adapter_info = adapter.get_info();
        Log::info(
            Event::Render,
            format!(
                "WebGPU: Selected adapter backend = {}, name = {}",
                backend_type_to_string(adapter_info.backend),
                if adapter_info.name.is_empty() { "<unknown>" } else { &adapter_info.name }
            ),
        );

        let has_depth32_stencil = adapter.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8);
        let (required_features, depth_stencil_format) = if has_depth32_stencil {
            (wgpu::Features::DEPTH32FLOAT_STENCIL8, wgpu::TextureFormat::Depth32FloatStencil8)
        } else {
            (wgpu::Features::empty(), wgpu::TextureFormat::Depth24PlusStencil8)
        };

        // The WebGPU default limits, lowered to what the adapter supports, as
        // the headless backend requests them.
        let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
            label: Some("MapLibre WebGPU Device"),
            required_features,
            required_limits: wgpu::Limits::default().or_worse_values_from(&adapter.limits()),
            ..Default::default()
        }))
        .map_err(|e| format!("Failed to create WebGPU device: {e}"))?;

        // Dawn's logUncapturedError instead of wgpu's panicking default.
        device.on_uncaptured_error(std::sync::Arc::new(|error: wgpu::Error| {
            Log::error(Event::Render, format!("WebGPU validation error: {error}"));
        }));

        renderer_backend.set_depth_stencil_format(Some(depth_stencil_format));

        // Process device events to ensure it's ready
        let _ = device.poll(wgpu::PollType::Poll);

        // Create surface for WebGPU
        let surface = create_surface(&instance)?;

        let capabilities = surface.get_capabilities(&adapter);
        let preferred_formats = [
            wgpu::TextureFormat::Bgra8Unorm,
            wgpu::TextureFormat::Bgra8UnormSrgb,
            wgpu::TextureFormat::Rgba8Unorm,
            wgpu::TextureFormat::Rgba8UnormSrgb,
        ];
        let swap_chain_format = preferred_formats
            .into_iter()
            .find(|f| capabilities.formats.contains(f))
            .or_else(|| capabilities.formats.first().copied())
            .unwrap_or(wgpu::TextureFormat::Bgra8Unorm);
        let mut surface_usage = wgpu::TextureUsages::RENDER_ATTACHMENT;
        if capabilities.usages.contains(wgpu::TextureUsages::COPY_SRC) {
            surface_usage |= wgpu::TextureUsages::COPY_SRC;
        }

        let present_mode = if capabilities.present_modes.contains(&wgpu::PresentMode::Mailbox) {
            wgpu::PresentMode::Mailbox
        } else {
            wgpu::PresentMode::Fifo
        };
        Ok(Self::finish(
            renderer_backend,
            Parts { instance, adapter: Some(adapter), device, queue, surface },
            SurfaceChoice { swap_chain_format, surface_usage, present_mode, depth_stencil_format },
            framebuffer_size,
            cap_frame_rate,
            adapter_info,
        ))
    }

    /// Port-only: a backend on a device and surface that the host created,
    /// as maplibre-native-ffi's `mln_map_attach_web_gpu_surface` passes them
    /// (wrapped by `mln_wgpu_webgpu_h::wrap_host_objects`). There is no
    /// adapter: the surface is configured with `format`, for rendering only,
    /// and presents in FIFO order, which every surface supports.
    pub fn from_host(
        instance: wgpu::Instance,
        device: wgpu::Device,
        queue: wgpu::Queue,
        surface: wgpu::Surface<'static>,
        format: wgpu::TextureFormat,
        framebuffer_size: Size,
    ) -> SurfaceBackend {
        let renderer_backend = RendererBackend::new(ContextMode::Unique);
        let adapter_info = device.adapter_info();
        let depth_stencil_format = if device.features().contains(wgpu::Features::DEPTH32FLOAT_STENCIL8) {
            wgpu::TextureFormat::Depth32FloatStencil8
        } else {
            wgpu::TextureFormat::Depth24PlusStencil8
        };
        device.on_uncaptured_error(std::sync::Arc::new(|error: wgpu::Error| {
            Log::error(Event::Render, format!("WebGPU validation error: {error}"));
        }));
        renderer_backend.set_depth_stencil_format(Some(depth_stencil_format));
        Self::finish(
            renderer_backend,
            Parts { instance, adapter: None, device, queue, surface },
            SurfaceChoice {
                swap_chain_format: format,
                surface_usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                present_mode: wgpu::PresentMode::Fifo,
                depth_stencil_format,
            },
            framebuffer_size,
            true,
            adapter_info,
        )
    }

    /// The rest of the construction, once the device, surface and formats
    /// are there.
    fn finish(
        renderer_backend: RendererBackend,
        parts: Parts,
        choice: SurfaceChoice,
        framebuffer_size: Size,
        cap_frame_rate: bool,
        adapter_info: wgpu::AdapterInfo,
    ) -> SurfaceBackend {
        let Parts { instance, adapter, device, queue, surface } = parts;
        let SurfaceChoice { swap_chain_format, surface_usage, present_mode, depth_stencil_format } = choice;
        renderer_backend.set_color_format(Some(swap_chain_format));

        let backend_impl = renderer_backend.backend_impl().clone();
        let state = Rc::new(SurfaceState {
            surface,
            device: device.clone(),
            queue: queue.clone(),
            swap_chain_format,
            surface_usage,
            depth_stencil_format: Cell::new(Some(depth_stencil_format)),
            current: RefCell::new(None),
            depth_stencil: RefCell::new(None),
            frame_presented: Cell::new(true),
            surface_configured: Cell::new(false),
            surface_needs_reconfigure: Cell::new(false),
            last_configured_size: Cell::new(Size::default()),
            consecutive_errors: Cell::new(0),
            enable_vsync: cap_frame_rate,
            vsync_present_mode: present_mode,
            framebuffer_size: Cell::new(framebuffer_size),
            last_swap_time: Cell::new(Instant::now()),
            readback_requested: Cell::new(false),
            readback: RefCell::new(None),
        });

        // Configure surface
        if framebuffer_size.width > 0 && framebuffer_size.height > 0 {
            state.surface.configure(&device, &state.configuration(framebuffer_size));
            state.surface_configured.set(true);
            state.last_configured_size.set(framebuffer_size);
        } else {
            state.surface_needs_reconfigure.set(true);
        }

        // Store WebGPU instance, device and queue in the base class
        backend_impl.set_instance(Some(instance));
        backend_impl.set_adapter(adapter);
        backend_impl.set_device(Some(device));
        backend_impl.set_queue(Some(queue));

        let resource = RenderableResourceBox::new_rc(SurfaceRenderableResource { state: state.clone() });
        SurfaceBackend {
            renderer_backend,
            renderable: RenderableBase::new(framebuffer_size, Some(resource)),
            state,
            adapter_info,
        }
    }

    pub fn webgpu_backend(&self) -> &RendererBackend {
        &self.renderer_backend
    }

    /// The adapter in use (name, backend, driver).
    pub fn get_adapter_info(&self) -> &wgpu::AdapterInfo {
        &self.adapter_info
    }

    /// The swapchain format picked from the surface capabilities.
    pub fn get_swap_chain_format(&self) -> wgpu::TextureFormat {
        self.state.swap_chain_format
    }

    /// `getFramebufferSize()`
    pub fn get_framebuffer_size(&self) -> Size {
        self.get_size()
    }

    /// `setFramebufferSize(Size)`
    pub fn set_framebuffer_size(&self, new_size: Size) {
        self.state.framebuffer_size.set(new_size);
        // Update swap chain size if needed
        if self.get_size() != new_size {
            self.set_renderable_size(new_size);
            self.state.surface_needs_reconfigure.set(true);
        }
    }

    /// `swap()`
    pub fn swap(&self) {
        self.state.swap();
    }

    /// `processEvents()`
    pub fn process_events(&self) {
        self.state.process_events();
    }

    /// Port-only: acquires the next swapchain texture ahead of a frame;
    /// false when the surface has none right now (timeout, occluded,
    /// outdated). The caller skips the frame: a render pass without a color
    /// attachment trips the drawables' debug assertions.
    pub fn acquire_next_texture(&self) -> bool {
        self.state.get_current_texture_view().is_some()
    }

    /// Port-only: copy the next presented frame (see `take_readback`).
    pub fn request_readback(&self) {
        self.state.readback_requested.set(true);
    }

    /// Port-only: the frame copied after `request_readback`, once presented.
    pub fn take_readback(&self) -> Option<PremultipliedImage> {
        self.state.readback.borrow_mut().take()
    }

    /// The device, for tests and tools.
    pub fn get_device(&self) -> wgpu::Device {
        self.state.device.clone()
    }
}

impl Drop for SurfaceBackend {
    fn drop(&mut self) {
        // ~GLFWWebGPUBackend: context.reset(), release the textures, pump
        // outstanding callbacks; the surface goes before the device.
        self.renderer_backend.reset_context();
        self.state.current.borrow_mut().take();
        self.state.depth_stencil.borrow_mut().take();
        self.state.process_events();
        self.set_resource(None);
    }
}

impl Renderable for SurfaceBackend {
    fn renderable_base(&self) -> &RenderableBase {
        &self.renderable
    }
}

impl renderer_backend::RendererBackend for SurfaceBackend {
    fn renderer_backend_base(&self) -> &RendererBackendBase {
        &self.renderer_backend.base
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn get_default_renderable(&self) -> &dyn Renderable {
        // We directly inherit from gfx::Renderable
        self
    }

    fn init_shaders(&self, registry: &ShaderRegistry, parameters: &ProgramParameters) {
        self.renderer_backend.init_shaders(registry, parameters);
    }

    fn create_context(&self) -> Rc<dyn GfxContext> {
        self.renderer_backend.create_context()
    }

    fn activate(&self) {
        // WebGPU doesn't need explicit context activation like OpenGL
    }

    fn deactivate(&self) {
        // WebGPU doesn't need explicit context deactivation like OpenGL
    }
}