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 instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
66 backends,
67 ..wgpu::InstanceDescriptor::new_without_display_handle_from_env()
68 });
69 instances.push((backends, instance.clone()));
70 instance
71}
72
73fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> {
82 #[cfg_attr(not(feature = "bench"), expect(unused_mut, reason = "only a benchmark asks for more"))]
83 let mut features = wgpu::Features::DEPTH32FLOAT_STENCIL8;
84 #[cfg(feature = "bench")]
85 {
86 features |= crate::bench::features();
87 }
88 let limits = adapter.limits();
89 wgpu::DeviceDescriptor {
90 label: Some("MapLibre WebGPU Device"),
91 required_features: adapter.features() & features,
92 required_limits: wgpu::Limits {
93 max_texture_dimension_2d: limits.max_texture_dimension_2d,
94 ..wgpu::Limits::default().or_worse_values_from(&limits)
95 },
96 ..Default::default()
97 }
98}
99
100#[cfg(not(target_family = "wasm"))]
102pub(crate) fn backend_type_to_string(backend: wgpu::Backend) -> &'static str {
103 match backend {
104 wgpu::Backend::Noop => "Null",
105 wgpu::Backend::BrowserWebGpu => "WebGPU",
106 wgpu::Backend::Dx12 => "D3D12",
107 wgpu::Backend::Metal => "Metal",
108 wgpu::Backend::Vulkan => "Vulkan",
109 wgpu::Backend::Gl => "OpenGL",
110 }
111}
112
113impl Device {
114 #[cfg(not(target_family = "wasm"))]
125 pub fn new(adapter_index: Option<usize>) -> Result<Device, Error> {
126 let backends = instance_backends();
127 let instance = shared_instance(backends);
128 let adapter = match adapter_index {
129 Some(index) => {
130 let mut adapters = pollster::block_on(instance.enumerate_adapters(backends));
131 let count = adapters.len();
132 if index >= count {
133 return Err(Error::not_found(format!("adapter_index {index} is past the {count} adapters")));
134 }
135 adapters.swap_remove(index)
136 }
137 None => pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
138 power_preference: wgpu::PowerPreference::HighPerformance,
139 ..Default::default()
140 }))
141 .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?,
142 };
143
144 let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter)))
145 .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
146 let info = adapter.get_info();
147 log::info!(
148 target: log_target::RENDER,
149 "graphics device uses WebGPU adapter {} on {}",
150 info.name,
151 backend_type_to_string(info.backend)
152 );
153 Ok(Device::library(instance, adapter, device, queue))
154 }
155
156 #[cfg(target_family = "wasm")]
165 pub async fn request() -> Result<Device, Error> {
166 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
167 backends: wgpu::Backends::BROWSER_WEBGPU,
168 ..wgpu::InstanceDescriptor::new_without_display_handle()
169 });
170 let adapter = instance
171 .request_adapter(&wgpu::RequestAdapterOptions {
172 power_preference: wgpu::PowerPreference::HighPerformance,
173 ..Default::default()
174 })
175 .await
176 .map_err(|e| Error::unsupported(format!("No adapter found: {e}")))?;
177 let (device, queue) = adapter
178 .request_device(&device_descriptor(&adapter))
179 .await
180 .map_err(|e| Error::native(format!("Failed to create device: {e}")))?;
181 Ok(Device::library(instance, adapter, device, queue))
182 }
183
184 fn library(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Device {
187 device.on_uncaptured_error(Arc::new(|error: wgpu::Error| {
188 log::error!(target: log_target::RENDER, "WebGPU validation error: {error}");
189 }));
190 let lost = watch_for_loss(&device);
191 Device { instance: Some(instance), adapter: Some(adapter), device, queue, surface_format: None, lost }
192 }
193
194 #[must_use]
200 pub fn from_wgpu(
201 instance: Option<wgpu::Instance>,
202 device: wgpu::Device,
203 queue: wgpu::Queue,
204 surface_format: Option<wgpu::TextureFormat>,
205 ) -> Device {
206 Device { instance, adapter: None, device, queue, surface_format, lost: Arc::default() }
207 }
208
209 #[must_use]
210 pub fn device(&self) -> &wgpu::Device {
211 &self.device
212 }
213
214 #[must_use]
215 pub fn queue(&self) -> &wgpu::Queue {
216 &self.queue
217 }
218
219 #[must_use]
220 pub fn instance(&self) -> Option<&wgpu::Instance> {
221 self.instance.as_ref()
222 }
223
224 pub(crate) fn adapter(&self) -> Option<&wgpu::Adapter> {
225 self.adapter.as_ref()
226 }
227
228 pub(crate) fn surface_format(&self) -> Option<wgpu::TextureFormat> {
229 self.surface_format
230 }
231
232 #[must_use]
236 pub fn lost(&self) -> Option<&str> {
237 self.lost.get().map(String::as_str)
238 }
239
240 #[must_use]
242 pub fn adapter_info(&self) -> wgpu::AdapterInfo {
243 self.device.adapter_info()
244 }
245}