1use std::sync::{Arc, OnceLock};
14
15use mln_gfx::Error;
16#[cfg(not(target_family = "wasm"))]
17use parking_lot::Mutex;
18
19use crate::log_target;
20
21#[derive(Clone, Debug)]
24pub struct Device {
25 instance: Option<wgpu::Instance>,
28 adapter: Option<wgpu::Adapter>,
30 device: wgpu::Device,
31 queue: wgpu::Queue,
32 surface_format: Option<wgpu::TextureFormat>,
34 lost: Arc<OnceLock<String>>,
36}
37
38fn watch_for_loss(device: &wgpu::Device) -> Arc<OnceLock<String>> {
40 let lost = Arc::new(OnceLock::new());
41 let record = Arc::clone(&lost);
42 device.set_device_lost_callback(move |reason, message| {
43 let _ = record.set(format!("the WebGPU device was lost ({reason:?}): {message}"));
44 });
45 lost
46}
47
48#[cfg(not(target_family = "wasm"))]
49fn instance_backends() -> wgpu::Backends {
50 if let Some(backends) = wgpu::Backends::from_env() {
51 return backends;
52 }
53 if cfg!(target_os = "linux") { wgpu::Backends::VULKAN } else { wgpu::Backends::all() }
54}
55
56#[cfg(not(target_family = "wasm"))]
59fn shared_instance(backends: wgpu::Backends) -> wgpu::Instance {
60 static INSTANCES: Mutex<Vec<(wgpu::Backends, wgpu::Instance)>> = Mutex::new(Vec::new());
61 let mut instances = INSTANCES.lock();
62 if let Some((_, instance)) = instances.iter().find(|(made_for, _)| *made_for == backends) {
63 return instance.clone();
64 }
65 let mut descriptor =
66 wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle_from_env() };
67 descriptor.flags = descriptor.flags.difference(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
72 let instance = wgpu::Instance::new(descriptor);
73 instances.push((backends, instance.clone()));
74 instance
75}
76
77fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
86 #[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only a benchmark asks for more"))]
87 let mut features = wgpu::Features::DEPTH32FLOAT_STENCIL8;
88 #[cfg(feature = "bench")]
89 {
90 features |= crate::bench::features();
91 }
92 let limits = adapter.limits();
93 wgpu::DeviceDescriptor {
94 label: Some("MapLibre WebGPU Device"),
95 required_features: adapter.features() & features,
96 required_limits: wgpu::Limits {
97 max_texture_dimension_2d: limits.max_texture_dimension_2d,
98 ..wgpu::Limits::default().or_worse_values_from(&limits)
99 },
100 ..Default::default()
101 }
102}
103
104#[cfg(not(target_family = "wasm"))]
106pub(crate) fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
107 match backend {
108 wgpu::Backend::Noop => "Null",
109 wgpu::Backend::BrowserWebGpu => "WebGPU",
110 wgpu::Backend::Dx12 => "D3D12",
111 wgpu::Backend::Metal => "Metal",
112 wgpu::Backend::Vulkan => "Vulkan",
113 wgpu::Backend::Gl => "OpenGL",
114 }
115}
116
117impl Device {
118 #[cfg(not(target_family = "wasm"))]
129 pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
130 let backends = instance_backends();
131 let instance = shared_instance(backends);
132 let adapter = match adapter_index {
133 Some(index) => {
134 let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
135 let count = adapters.len();
136 if index >= count {
137 return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
138 }
139 adapters.swap_remove(index)
140 }
141 None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
142 power_preference: wgpu::PowerPreference::HighPerformance,
143 ..Default::default()
144 }))
145 .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
146 };
147
148 let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter)))
149 .map_err(|e| Error::failed(format!("Failed to create device: {e}")))?;
150 let info = adapter.get_info();
151 tracing::info!(
152 target: log_target::RENDER,
153 adapter = %info.name,
154 backend = backend_type_to_string(info.backend),
155 "Graphics device uses a WebGPU adapter"
156 );
157 Ok(Device::library(instance, adapter, device, queue))
158 }
159
160 #[cfg(target_family = "wasm")]
169 pub async fn request() -> Result<Device, Error> {
170 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
171 backends: wgpu::Backends::BROWSER_WEBGPU,
172 ..wgpu::InstanceDescriptor::new_without_display_handle()
173 });
174 let adapter = instance
175 .request_adapter(&wgpu::RequestAdapterOptions {
176 power_preference: wgpu::PowerPreference::HighPerformance,
177 ..Default::default()
178 })
179 .await
180 .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?;
181 let (device, queue) = adapter
182 .request_device(&device_descriptor(&adapter))
183 .await
184 .map_err(|e| Error::failed(format!("Failed to create device: {e}")))?;
185 Ok(Device::library(instance, adapter, device, queue))
186 }
187
188 fn library(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Device {
191 device.on_uncaptured_error(Arc::new(|error: wgpu::Error| {
192 tracing::error!(target: log_target::RENDER, error = %error, "WebGPU validation error");
193 }));
194 let lost = watch_for_loss(&device);
195 Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
196 }
197
198 #[must_use]
204 pub fn from_wgpu(
205 instance: Option<wgpu::Instance>,
206 device: wgpu::Device,
207 queue: wgpu::Queue,
208 surface_format: Option<wgpu::TextureFormat>,
209 ) -> Device {
210 Device { instance, adapter: None, device, queue, surface_format, lost: Arc::default() }
211 }
212
213 #[must_use]
214 pub fn device(&self) -> &wgpu::Device {
215 &self.device
216 }
217
218 #[must_use]
219 pub fn queue(&self) -> &wgpu::Queue {
220 &self.queue
221 }
222
223 #[must_use]
224 pub fn instance(&self) -> Option<&wgpu::Instance> {
225 self.instance.as_ref()
226 }
227
228 pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
229 self.adapter.as_ref()
230 }
231
232 pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
233 self.surface_format
234 }
235
236 #[must_use]
240 pub fn lost(&self) -> Option<&str> {
241 self.lost.get().map(String::as_str)
242 }
243
244 #[must_use]
246 pub fn adapter_info(&self) -> wgpu::AdapterInfo {
247 self.device.adapter_info()
248 }
249}