Skip to main content

mln_webgpu/
device.rs

1//! The GPU and queue that WebGPU renderers share.
2//!
3//! Natively, the library's device is on the backends that `WGPU_BACKEND`
4//! names (wgpu's variable, such as "vulkan"), or else Vulkan on Linux, where
5//! tests run on lavapipe (`VK_DRIVER_FILES`), and wgpu's defaults elsewhere.
6//! Every device `Device::new` makes comes from one instance per set of
7//! backends, kept for the life of the process: the Vulkan loader crashes when
8//! one thread names an object (`vkSetDebugUtilsObjectNameEXT`, which wgpu
9//! calls for each labeled object) while another thread destroys an instance.
10
11use std::sync::{Arc, OnceLock};
12
13use mln_util::error::Error;
14use mln_util::logging::{Event, Log};
15#[cfg(not(target_family = "wasm"))]
16use parking_lot::Mutex;
17
18/// A WebGPU device that renderers on any thread share: the library's, or the
19/// host's. Clones share it.
20#[derive(Clone, Debug)]
21pub struct Device {
22    /// What window surfaces are made with: the instance that made the
23    /// device. The host's device may come without it.
24    instance: Option<wgpu::Instance>,
25    /// What surfaces are checked against. The host's device has none.
26    adapter: Option<wgpu::Adapter>,
27    device: wgpu::Device,
28    queue: wgpu::Queue,
29    /// The format the host configures its surfaces with.
30    surface_format: Option<wgpu::TextureFormat>,
31    /// Why the library's device was lost, once it is.
32    lost: Arc<OnceLock<String>>,
33}
34
35/// Records in `lost` why `device` is lost, once it is.
36fn watch_for_loss(device: &wgpu::Device) -> Arc<OnceLock<String>> {
37    let lost = Arc::new(OnceLock::new());
38    let record = Arc::clone(&lost);
39    device.set_device_lost_callback(move |reason, message| {
40        let _ = record.set(format!("the WebGPU device was lost ({reason:?}): {message}"));
41    });
42    lost
43}
44
45#[cfg(not(target_family = "wasm"))]
46fn instance_backends() -> wgpu::Backends {
47    if let Some(backends) = wgpu::Backends::from_env() {
48        return backends;
49    }
50    if cfg!(target_os = "linux") { wgpu::Backends::VULKAN } else { wgpu::Backends::all() }
51}
52
53/// The instance for `backends`: one per set of backends, created on first
54/// use and never destroyed (see the module docs).
55#[cfg(not(target_family = "wasm"))]
56fn shared_instance(backends: wgpu::Backends) -> wgpu::Instance {
57    static INSTANCES: Mutex<Vec<(wgpu::Backends, wgpu::Instance)>> = Mutex::new(Vec::new());
58    let mut instances = INSTANCES.lock();
59    if let Some((_, instance)) = instances.iter().find(|(made_for, _)| *made_for == backends) {
60        return instance.clone();
61    }
62    let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
63        backends,
64        ..wgpu::InstanceDescriptor::new_without_display_handle()
65    });
66    instances.push((backends, instance.clone()));
67    instance
68}
69
70/// What the library's device is made with: the WebGPU default limits,
71/// lowered to what `adapter` supports (the Metal of the iOS, tvOS and
72/// visionOS simulators allows fewer inter-stage shader variables than they
73/// ask), and 32-bit float depth with stencil where `adapter` has it. A
74/// benchmark that measures the render passes also asks for pipeline
75/// statistics and timestamp queries (`bench::features`).
76fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
77    #[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only a benchmark asks for more"))]
78    let mut features = wgpu::Features::DEPTH32FLOAT_STENCIL8;
79    #[cfg(feature = "bench")]
80    {
81        features |= crate::bench::features();
82    }
83    wgpu::DeviceDescriptor {
84        label: Some("MapLibre WebGPU Device"),
85        required_features: adapter.features() & features,
86        required_limits: wgpu::Limits::default().or_worse_values_from(&adapter.limits()),
87        ..Default::default()
88    }
89}
90
91/// The name of `backend` in a device's log record.
92#[cfg(not(target_family = "wasm"))]
93pub(crate) fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
94    match backend {
95        wgpu::Backend::Noop => "Null",
96        wgpu::Backend::BrowserWebGpu => "WebGPU",
97        wgpu::Backend::Dx12 => "D3D12",
98        wgpu::Backend::Metal => "Metal",
99        wgpu::Backend::Vulkan => "Vulkan",
100        wgpu::Backend::Gl => "OpenGL",
101    }
102}
103
104impl Device {
105    /// The library's device, on the adapter at `adapter_index` in
106    /// [`wgpu::Instance::enumerate_adapters`] order, or on the
107    /// high-performance adapter when `None`. It logs the adapter it is on,
108    /// and its uncaptured errors.
109    ///
110    /// Fails with [`ErrorKind::NotFound`](mln_util::ErrorKind) when there is
111    /// no adapter at `adapter_index`, with
112    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) when there is no
113    /// adapter at all, and with [`ErrorKind::Native`](mln_util::ErrorKind)
114    /// when the adapter can't create the device.
115    #[cfg(not(target_family = "wasm"))]
116    pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
117        let backends = instance_backends();
118        let instance = shared_instance(backends);
119        let adapter = match adapter_index {
120            Some(index) => {
121                let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
122                let count = adapters.len();
123                if index >= count {
124                    return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
125                }
126                adapters.swap_remove(index)
127            }
128            None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
129                power_preference: wgpu::PowerPreference::HighPerformance,
130                ..Default::default()
131            }))
132            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
133        };
134
135        let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter)))
136            .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
137        let info = adapter.get_info();
138        Log::info(
139            Event::Render,
140            format!("graphics device uses WebGPU adapter {} on {}", info.name, backend_type_to_string(info.backend)),
141        );
142        Ok(Device::library(instance, adapter, device, queue))
143    }
144
145    /// The library's device in the browser, on the browser's WebGPU and its
146    /// high-performance adapter, which arrive asynchronously. Its uncaptured
147    /// errors are logged.
148    ///
149    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
150    /// browser has no WebGPU adapter, and with
151    /// [`ErrorKind::Native`](mln_util::ErrorKind) when the adapter can't
152    /// create the device.
153    #[cfg(target_family = "wasm")]
154    pub async fn request() -> Result<Device, Error> {
155        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
156            backends: wgpu::Backends::BROWSER_WEBGPU,
157            ..wgpu::InstanceDescriptor::new_without_display_handle()
158        });
159        let adapter = instance
160            .request_adapter(&wgpu::RequestAdapterOptions {
161                power_preference: wgpu::PowerPreference::HighPerformance,
162                ..Default::default()
163            })
164            .await
165            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?;
166        let (device, queue) = adapter
167            .request_device(&device_descriptor(&adapter))
168            .await
169            .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
170        Ok(Device::library(instance, adapter, device, queue))
171    }
172
173    /// The library's device, which logs its uncaptured errors: wgpu's
174    /// default handler panics.
175    fn library(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Device {
176        device.on_uncaptured_error(Arc::new(|error: wgpu::Error| {
177            Log::error(Event::Render, format!("WebGPU validation error: {error}"));
178        }));
179        let lost = watch_for_loss(&device);
180        Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
181    }
182
183    /// The host's device and queue. Window surfaces need the `instance` that
184    /// made the device. A surface on it is configured with the format that
185    /// its options name, or else with `surface_format`, which it must
186    /// support. The host keeps the device's uncaptured-error and device-lost
187    /// handlers.
188    #[must_use]
189    pub fn from_wgpu(
190        instance: Option<wgpu::Instance>,
191        device: wgpu::Device,
192        queue: wgpu::Queue,
193        surface_format: Option<wgpu::TextureFormat>,
194    ) -> Device {
195        Device { instance, adapter: None, device, queue, surface_format, lost: Arc::default() }
196    }
197
198    #[must_use]
199    pub fn device(&self) -> &wgpu::Device {
200        &self.device
201    }
202
203    #[must_use]
204    pub fn queue(&self) -> &wgpu::Queue {
205        &self.queue
206    }
207
208    #[must_use]
209    pub fn instance(&self) -> Option<&wgpu::Instance> {
210        self.instance.as_ref()
211    }
212
213    pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
214        self.adapter.as_ref()
215    }
216
217    pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
218        self.surface_format
219    }
220
221    /// Why the device was lost, once the library's device is: a browser
222    /// loses it when the GPU process resets or can't present. The host's
223    /// device keeps its own device-lost callback, and reports nothing here.
224    #[must_use]
225    pub fn lost(&self) -> Option<&str> {
226        self.lost.get().map(String::as_str)
227    }
228
229    /// The adapter the device is on (name, backend, driver).
230    #[must_use]
231    pub fn adapter_info(&self) -> wgpu::AdapterInfo {
232        self.device.adapter_info()
233    }
234}