1use 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#[derive(Clone, Debug)]
21pub struct Device {
22 instance: Option<wgpu::Instance>,
25 adapter: Option<wgpu::Adapter>,
27 device: wgpu::Device,
28 queue: wgpu::Queue,
29 surface_format: Option<wgpu::TextureFormat>,
31 lost: Arc<OnceLock<String>>,
33}
34
35fn 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#[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
70fn 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#[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 #[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 #[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 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 #[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 #[must_use]
225 pub fn lost(&self) -> Option<&str> {
226 self.lost.get().map(String::as_str)
227 }
228
229 #[must_use]
231 pub fn adapter_info(&self) -> wgpu::AdapterInfo {
232 self.device.adapter_info()
233 }
234}