1use std::sync::{Arc, OnceLock};
17
18use mln_gfx::Error;
19#[cfg(not(target_family = "wasm"))]
20use parking_lot::Mutex;
21
22use crate::log_target;
23
24#[derive(Clone, Debug)]
27pub struct Device {
28 instance: Option<wgpu::Instance>,
31 adapter: Option<wgpu::Adapter>,
33 device: wgpu::Device,
34 queue: wgpu::Queue,
35 surface_format: Option<wgpu::TextureFormat>,
37 lost: Arc<OnceLock<String>>,
39}
40
41fn watch_for_loss(device: &wgpu::Device) -> Arc<OnceLock<String>> {
43 let lost = Arc::new(OnceLock::new());
44 let record = Arc::clone(&lost);
45 device.set_device_lost_callback(move |reason, message| {
46 let _ = record.set(format!("the WebGPU device was lost ({reason:?}): {message}"));
47 });
48 lost
49}
50
51#[cfg(not(target_family = "wasm"))]
52fn instance_backends() -> wgpu::Backends {
53 if let Some(backends) = wgpu::Backends::from_env() {
54 return backends;
55 }
56 if cfg!(target_os = "linux") { wgpu::Backends::VULKAN } else { wgpu::Backends::all() }
57}
58
59#[cfg(not(target_family = "wasm"))]
62fn shared_instance(backends: wgpu::Backends) -> wgpu::Instance {
63 static INSTANCES: Mutex<Vec<(wgpu::Backends, wgpu::Instance)>> = Mutex::new(Vec::new());
64 let mut instances = INSTANCES.lock();
65 if let Some((_, instance)) = instances.iter().find(|(made_for, _)| *made_for == backends) {
66 return instance.clone();
67 }
68 let mut descriptor =
69 wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle_from_env() };
70 let skipped = wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL | wgpu::InstanceFlags::VALIDATION;
78 descriptor.flags = descriptor.flags.difference(skipped).with_env();
79 let instance = wgpu::Instance::new(descriptor);
80 instances.push((backends, instance.clone()));
81 instance
82}
83
84fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
93 #[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only a benchmark asks for more"))]
94 let mut features = wgpu::Features::DEPTH32FLOAT_STENCIL8;
95 #[cfg(feature = "bench")]
96 {
97 features |= crate::bench::features();
98 }
99 let limits = adapter.limits();
100 wgpu::DeviceDescriptor {
101 label: Some("MapLibre WebGPU Device"),
102 required_features: adapter.features() & features,
103 required_limits: wgpu::Limits {
104 max_texture_dimension_2d: limits.max_texture_dimension_2d,
105 ..wgpu::Limits::default().or_worse_values_from(&limits)
106 },
107 ..Default::default()
108 }
109}
110
111#[cfg(not(target_family = "wasm"))]
113pub(crate) fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
114 match backend {
115 wgpu::Backend::Noop => "Null",
116 wgpu::Backend::BrowserWebGpu => "WebGPU",
117 wgpu::Backend::Dx12 => "D3D12",
118 wgpu::Backend::Metal => "Metal",
119 wgpu::Backend::Vulkan => "Vulkan",
120 wgpu::Backend::Gl => "OpenGL",
121 }
122}
123
124impl Device {
125 #[cfg(not(target_family = "wasm"))]
136 pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
137 let backends = instance_backends();
138 let instance = shared_instance(backends);
139 let adapter = match adapter_index {
140 Some(index) => {
141 let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
142 let count = adapters.len();
143 if index >= count {
144 return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
145 }
146 adapters.swap_remove(index)
147 }
148 None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
149 power_preference: wgpu::PowerPreference::HighPerformance,
150 ..Default::default()
151 }))
152 .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
153 };
154
155 let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter)))
156 .map_err(|e| Error::failed(format!("Failed to create device: {e}")))?;
157 let info = adapter.get_info();
158 tracing::info!(
159 target: log_target::RENDER,
160 adapter = %info.name,
161 backend = backend_type_to_string(info.backend),
162 "Graphics device uses a WebGPU adapter"
163 );
164 Ok(Device::library(instance, adapter, device, queue))
165 }
166
167 #[cfg(target_family = "wasm")]
176 pub async fn request() -> Result<Device, Error> {
177 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
178 backends: wgpu::Backends::BROWSER_WEBGPU,
179 ..wgpu::InstanceDescriptor::new_without_display_handle()
180 });
181 let adapter = instance
182 .request_adapter(&wgpu::RequestAdapterOptions {
183 power_preference: wgpu::PowerPreference::HighPerformance,
184 ..Default::default()
185 })
186 .await
187 .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?;
188 let (device, queue) = adapter
189 .request_device(&device_descriptor(&adapter))
190 .await
191 .map_err(|e| Error::failed(format!("Failed to create device: {e}")))?;
192 Ok(Device::library(instance, adapter, device, queue))
193 }
194
195 fn library(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Device {
198 device.on_uncaptured_error(Arc::new(|error: wgpu::Error| {
199 tracing::error!(target: log_target::RENDER, error = %error, "WebGPU validation error");
200 }));
201 let lost = watch_for_loss(&device);
202 Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
203 }
204
205 #[must_use]
211 pub fn from_wgpu(
212 instance: Option<wgpu::Instance>,
213 device: wgpu::Device,
214 queue: wgpu::Queue,
215 surface_format: Option<wgpu::TextureFormat>,
216 ) -> Device {
217 Device { instance, adapter: None, device, queue, surface_format, lost: Arc::default() }
218 }
219
220 #[must_use]
221 pub fn device(&self) -> &wgpu::Device {
222 &self.device
223 }
224
225 #[must_use]
226 pub fn queue(&self) -> &wgpu::Queue {
227 &self.queue
228 }
229
230 #[must_use]
231 pub fn instance(&self) -> Option<&wgpu::Instance> {
232 self.instance.as_ref()
233 }
234
235 pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
236 self.adapter.as_ref()
237 }
238
239 pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
240 self.surface_format
241 }
242
243 #[must_use]
247 pub fn lost(&self) -> Option<&str> {
248 self.lost.get().map(String::as_str)
249 }
250
251 #[must_use]
253 pub fn adapter_info(&self) -> wgpu::AdapterInfo {
254 self.device.adapter_info()
255 }
256}