Skip to main content

mln_webgpu/
device.rs

1// The GPU and queue that WebGPU renderers share.
2//
3// C++ wgpu-native creates the instance with default options (all backends)
4// and takes the HighPerformance adapter. The library's device restricts the
5// instance to `WGPU_BACKEND` if set (wgpu's env var, e.g. "vulkan"), else
6// Vulkan on Linux, so tests run on lavapipe (VK_DRIVER_FILES) like the C++
7// CI; other platforms use wgpu's defaults.
8//
9// Deviation: C++ creates an instance for each device. Here every device
10// `Device::new` makes comes from one instance per set of backends, kept for
11// the life of the process: the Vulkan loader crashes when one thread names an
12// object (`vkSetDebugUtilsObjectNameEXT`, which wgpu calls for each labeled
13// object) while another thread destroys an instance, which renderers on many
14// threads did whenever one of them finished.
15
16#[cfg(not(target_family = "wasm"))]
17use std::sync::Mutex;
18
19#[cfg(not(target_family = "wasm"))]
20use mln_util::error::Error;
21#[cfg(not(target_family = "wasm"))]
22use mln_util::logging::{Event, Log};
23#[cfg(not(target_family = "wasm"))]
24use mln_util::sync::MutexExt;
25
26/// A WebGPU device that renderers on any thread share: the library's, or the
27/// host's. Clones share it.
28#[derive(Clone, Debug)]
29pub struct Device {
30    /// What window surfaces are made with: the instance that made the
31    /// device. The host's device may come without it.
32    instance: Option<wgpu::Instance>,
33    /// What surfaces are checked against. The host's device has none.
34    adapter: Option<wgpu::Adapter>,
35    device: wgpu::Device,
36    queue: wgpu::Queue,
37    /// The format the host configures its surfaces with.
38    surface_format: Option<wgpu::TextureFormat>,
39}
40
41#[cfg(not(target_family = "wasm"))]
42fn instance_backends() -> wgpu::Backends {
43    if let Some(backends) = wgpu::Backends::from_env() {
44        return backends;
45    }
46    if cfg!(target_os = "linux") { wgpu::Backends::VULKAN } else { wgpu::Backends::all() }
47}
48
49/// The instance for the backends `WGPU_BACKEND` names (Vulkan on Linux by
50/// default): one per set of backends, created on first use and never
51/// destroyed (see the deviation above).
52#[cfg(not(target_family = "wasm"))]
53fn shared_instance(backends: wgpu::Backends) -> wgpu::Instance {
54    static INSTANCES: Mutex<Vec<(wgpu::Backends, wgpu::Instance)>> = Mutex::new(Vec::new());
55    let mut instances = INSTANCES.lock_unpoisoned();
56    if let Some((_, instance)) = instances.iter().find(|(made_for, _)| *made_for == backends) {
57        return instance.clone();
58    }
59    let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
60        backends,
61        ..wgpu::InstanceDescriptor::new_without_display_handle()
62    });
63    instances.push((backends, instance.clone()));
64    instance
65}
66
67impl Device {
68    /// The library's device, on the adapter at `adapter_index` in
69    /// [`wgpu::Instance::enumerate_adapters`] order, or on the
70    /// high-performance adapter when `None`. Its uncaptured errors are
71    /// logged.
72    ///
73    /// Fails with [`ErrorKind::NotFound`](mln_util::ErrorKind) when there is
74    /// no adapter at `adapter_index`, with
75    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) when there is no
76    /// adapter at all, and with [`ErrorKind::Native`](mln_util::ErrorKind)
77    /// when the adapter can't create the device.
78    #[cfg(not(target_family = "wasm"))]
79    pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
80        let backends = instance_backends();
81        let instance = shared_instance(backends);
82        let adapter = match adapter_index {
83            Some(index) => {
84                let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
85                let count = adapters.len();
86                if index >= count {
87                    return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
88                }
89                adapters.swap_remove(index)
90            }
91            None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
92                power_preference: wgpu::PowerPreference::HighPerformance,
93                ..Default::default()
94            }))
95            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
96        };
97
98        // The WebGPU default limits lowered to what the adapter supports:
99        // the Metal of the iOS, tvOS and visionOS simulators allows fewer
100        // inter-stage shader variables than they ask. A surface's depth and
101        // stencil take 32-bit float depth where the adapter has it.
102        let required_limits = wgpu::Limits::default().or_worse_values_from(&adapter.limits());
103        let required_features = adapter.features() & wgpu::Features::DEPTH32FLOAT_STENCIL8;
104        let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
105            label: Some("MapLibre WebGPU Device"),
106            required_features,
107            required_limits,
108            ..Default::default()
109        }))
110        .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
111
112        // C++ sets no uncaptured-error callback, and Dawn logs the error and
113        // invalidates the object. wgpu's default handler panics; log instead
114        // (Dawn's logUncapturedError).
115        device.on_uncaptured_error(std::sync::Arc::new(|error: wgpu::Error| {
116            Log::error(Event::Render, format!("WebGPU validation error: {error}"));
117        }));
118        Ok(Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None })
119    }
120
121    /// The host's device and queue. Window surfaces need the `instance` that
122    /// made the device. A surface is configured with `surface_format`, which
123    /// it must support, or else with a format it supports that is the first
124    /// of BGRA8 and RGBA8 for the device's adapter. The host keeps the
125    /// device's uncaptured-error handler.
126    #[must_use]
127    pub fn from_wgpu(
128        instance: Option<wgpu::Instance>,
129        device: wgpu::Device,
130        queue: wgpu::Queue,
131        surface_format: Option<wgpu::TextureFormat>,
132    ) -> Device {
133        Device { instance, adapter: None, device, queue, surface_format }
134    }
135
136    #[must_use]
137    pub fn device(&self) -> &wgpu::Device {
138        &self.device
139    }
140
141    #[must_use]
142    pub fn queue(&self) -> &wgpu::Queue {
143        &self.queue
144    }
145
146    #[must_use]
147    pub fn instance(&self) -> Option<&wgpu::Instance> {
148        self.instance.as_ref()
149    }
150
151    pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
152        self.adapter.as_ref()
153    }
154
155    pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
156        self.surface_format
157    }
158
159    /// The adapter the device is on (name, backend, driver).
160    #[must_use]
161    pub fn adapter_info(&self) -> wgpu::AdapterInfo {
162        self.device.adapter_info()
163    }
164}