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.
74fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
75    wgpu::DeviceDescriptor {
76        label: Some("MapLibre WebGPU Device"),
77        required_features: adapter.features() & wgpu::Features::DEPTH32FLOAT_STENCIL8,
78        required_limits: wgpu::Limits::default().or_worse_values_from(&adapter.limits()),
79        ..Default::default()
80    }
81}
82
83/// The name of `backend` in a device's log record.
84#[cfg(not(target_family = "wasm"))]
85pub(crate) fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
86    match backend {
87        wgpu::Backend::Noop => "Null",
88        wgpu::Backend::BrowserWebGpu => "WebGPU",
89        wgpu::Backend::Dx12 => "D3D12",
90        wgpu::Backend::Metal => "Metal",
91        wgpu::Backend::Vulkan => "Vulkan",
92        wgpu::Backend::Gl => "OpenGL",
93    }
94}
95
96impl Device {
97    /// The library's device, on the adapter at `adapter_index` in
98    /// [`wgpu::Instance::enumerate_adapters`] order, or on the
99    /// high-performance adapter when `None`. It logs the adapter it is on,
100    /// and its uncaptured errors.
101    ///
102    /// Fails with [`ErrorKind::NotFound`](mln_util::ErrorKind) when there is
103    /// no adapter at `adapter_index`, with
104    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) when there is no
105    /// adapter at all, and with [`ErrorKind::Native`](mln_util::ErrorKind)
106    /// when the adapter can't create the device.
107    #[cfg(not(target_family = "wasm"))]
108    pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
109        let backends = instance_backends();
110        let instance = shared_instance(backends);
111        let adapter = match adapter_index {
112            Some(index) => {
113                let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
114                let count = adapters.len();
115                if index >= count {
116                    return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
117                }
118                adapters.swap_remove(index)
119            }
120            None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
121                power_preference: wgpu::PowerPreference::HighPerformance,
122                ..Default::default()
123            }))
124            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
125        };
126
127        let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter)))
128            .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
129        let info = adapter.get_info();
130        Log::info(
131            Event::Render,
132            format!("graphics device uses WebGPU adapter {} on {}", info.name, backend_type_to_string(info.backend)),
133        );
134        Ok(Device::library(instance, adapter, device, queue))
135    }
136
137    /// The library's device in the browser, on the browser's WebGPU and its
138    /// high-performance adapter, which arrive asynchronously. Its uncaptured
139    /// errors are logged.
140    ///
141    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
142    /// browser has no WebGPU adapter, and with
143    /// [`ErrorKind::Native`](mln_util::ErrorKind) when the adapter can't
144    /// create the device.
145    #[cfg(target_family = "wasm")]
146    pub async fn request() -> Result<Device, Error> {
147        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
148            backends: wgpu::Backends::BROWSER_WEBGPU,
149            ..wgpu::InstanceDescriptor::new_without_display_handle()
150        });
151        let adapter = instance
152            .request_adapter(&wgpu::RequestAdapterOptions {
153                power_preference: wgpu::PowerPreference::HighPerformance,
154                ..Default::default()
155            })
156            .await
157            .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?;
158        let (device, queue) = adapter
159            .request_device(&device_descriptor(&adapter))
160            .await
161            .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
162        Ok(Device::library(instance, adapter, device, queue))
163    }
164
165    /// The library's device, which logs its uncaptured errors: wgpu's
166    /// default handler panics.
167    fn library(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Device {
168        device.on_uncaptured_error(Arc::new(|error: wgpu::Error| {
169            Log::error(Event::Render, format!("WebGPU validation error: {error}"));
170        }));
171        let lost = watch_for_loss(&device);
172        Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
173    }
174
175    /// The host's device and queue. Window surfaces need the `instance` that
176    /// made the device. A surface on it is configured with the format that
177    /// its options name, or else with `surface_format`, which it must
178    /// support. The host keeps the device's uncaptured-error and device-lost
179    /// handlers.
180    #[must_use]
181    pub fn from_wgpu(
182        instance: Option<wgpu::Instance>,
183        device: wgpu::Device,
184        queue: wgpu::Queue,
185        surface_format: Option<wgpu::TextureFormat>,
186    ) -> Device {
187        Device { instance, adapter: None, device, queue, surface_format, lost: Arc::default() }
188    }
189
190    #[must_use]
191    pub fn device(&self) -> &wgpu::Device {
192        &self.device
193    }
194
195    #[must_use]
196    pub fn queue(&self) -> &wgpu::Queue {
197        &self.queue
198    }
199
200    #[must_use]
201    pub fn instance(&self) -> Option<&wgpu::Instance> {
202        self.instance.as_ref()
203    }
204
205    pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
206        self.adapter.as_ref()
207    }
208
209    pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
210        self.surface_format
211    }
212
213    /// Why the device was lost, once the library's device is: a browser
214    /// loses it when the GPU process resets or can't present. The host's
215    /// device keeps its own device-lost callback, and reports nothing here.
216    #[must_use]
217    pub fn lost(&self) -> Option<&str> {
218        self.lost.get().map(String::as_str)
219    }
220
221    /// The adapter the device is on (name, backend, driver).
222    #[must_use]
223    pub fn adapter_info(&self) -> wgpu::AdapterInfo {
224        self.device.adapter_info()
225    }
226}