wgpu_core/
instance.rs

1use alloc::{borrow::ToOwned as _, boxed::Box, string::String, sync::Arc, vec, vec::Vec};
2
3use hashbrown::HashMap;
4use thiserror::Error;
5
6use crate::{
7    api_log, api_log_debug,
8    device::{queue::Queue, resource::Device, DeviceDescriptor, DeviceError},
9    global::Global,
10    id::{markers, AdapterId, DeviceId, QueueId, SurfaceId},
11    limits::{self, check_limits, FailedLimit},
12    lock::{rank, Mutex},
13    present::Presentation,
14    resource::ResourceType,
15    resource_log,
16    timestamp_normalization::TimestampNormalizerInitError,
17    DOWNLEVEL_WARNING_MESSAGE,
18};
19
20use wgt::{Backend, Backends, PowerPreference};
21
22pub type RequestAdapterOptions = wgt::RequestAdapterOptions<SurfaceId>;
23
24#[test]
25fn downlevel_default_limits_less_than_default_limits() {
26    let res = check_limits(&wgt::Limits::downlevel_defaults(), &wgt::Limits::default());
27    assert!(
28        res.is_empty(),
29        "Downlevel limits are greater than default limits",
30    )
31}
32
33#[derive(Default)]
34pub struct Instance {
35    _name: String,
36
37    /// List of instances per `wgpu-hal` backend.
38    ///
39    /// The ordering in this list implies prioritization and needs to be preserved.
40    instance_per_backend: Vec<(Backend, Box<dyn hal::DynInstance>)>,
41
42    /// The backends that were requested by the user.
43    requested_backends: Backends,
44
45    /// The backends that we could have attempted to obtain from `wgpu-hal` —
46    /// those for which support is compiled in, currently.
47    ///
48    /// The union of this and `requested_backends` is the set of backends that would be used,
49    /// independent of whether accessing the drivers/hardware for them succeeds.
50    /// To obtain the set of backends actually in use by this instance, check
51    /// `instance_per_backend` instead.
52    supported_backends: Backends,
53
54    pub flags: wgt::InstanceFlags,
55
56    /// Non-lifetimed [`raw_window_handle::DisplayHandle`], for keepalive and validation purposes in
57    /// [`Self::create_surface()`].
58    ///
59    /// When used with `winit`, callers are expected to pass its `OwnedDisplayHandle` (created from
60    /// the `EventLoop`) here.
61    display: Option<Box<dyn wgt::WgpuHasDisplayHandle>>,
62}
63
64impl Instance {
65    pub fn new(
66        name: &str,
67        mut instance_desc: wgt::InstanceDescriptor,
68        telemetry: Option<hal::Telemetry>,
69    ) -> Self {
70        let mut this = Self {
71            _name: name.to_owned(),
72            instance_per_backend: Vec::new(),
73            requested_backends: instance_desc.backends,
74            supported_backends: Backends::empty(),
75            flags: instance_desc.flags,
76            // HACK: We must take ownership of the field here, without being able to pass it into
77            // try_add_hal(). Remove it from the mutable descriptor instead, while try_add_hal()
78            // borrows the handle from `this.display` instead.
79            display: instance_desc.display.take(),
80        };
81
82        #[cfg(all(vulkan, not(target_os = "netbsd")))]
83        this.try_add_hal(hal::api::Vulkan, &instance_desc, telemetry);
84        #[cfg(metal)]
85        this.try_add_hal(hal::api::Metal, &instance_desc, telemetry);
86        #[cfg(dx12)]
87        this.try_add_hal(hal::api::Dx12, &instance_desc, telemetry);
88        #[cfg(gles)]
89        this.try_add_hal(hal::api::Gles, &instance_desc, telemetry);
90        #[cfg(feature = "noop")]
91        this.try_add_hal(hal::api::Noop, &instance_desc, telemetry);
92
93        this
94    }
95
96    /// Helper for `Instance::new()`; attempts to add a single `wgpu-hal` backend to this instance.
97    fn try_add_hal<A: hal::Api>(
98        &mut self,
99        _: A,
100        instance_desc: &wgt::InstanceDescriptor,
101        telemetry: Option<hal::Telemetry>,
102    ) {
103        // Whether or not the backend was requested, and whether or not it succeeds,
104        // note that we *could* try it.
105        self.supported_backends |= A::VARIANT.into();
106
107        if !instance_desc.backends.contains(A::VARIANT.into()) {
108            log::trace!("Instance::new: backend {:?} not requested", A::VARIANT);
109            return;
110        }
111
112        // If this was Some, it was moved into self
113        assert!(instance_desc.display.is_none());
114
115        let hal_desc = hal::InstanceDescriptor {
116            name: "wgpu",
117            flags: self.flags,
118            memory_budget_thresholds: instance_desc.memory_budget_thresholds,
119            backend_options: instance_desc.backend_options.clone(),
120            telemetry,
121            // Pass a borrow, the core instance here keeps the owned handle alive already
122            // WARNING: Using self here, not instance_desc!
123            display: self.display.as_ref().map(|hdh| {
124                hdh.display_handle()
125                    .expect("Implementation did not provide a DisplayHandle")
126            }),
127        };
128
129        use hal::Instance as _;
130        // SAFETY: ???
131        match unsafe { A::Instance::init(&hal_desc) } {
132            Ok(instance) => {
133                log::debug!("Instance::new: created {:?} backend", A::VARIANT);
134                self.instance_per_backend
135                    .push((A::VARIANT, Box::new(instance)));
136            }
137            Err(err) => {
138                log::debug!(
139                    "Instance::new: failed to create {:?} backend: {:?}",
140                    A::VARIANT,
141                    err
142                );
143            }
144        }
145    }
146
147    pub(crate) fn from_hal_instance<A: hal::Api>(
148        name: String,
149        hal_instance: <A as hal::Api>::Instance,
150    ) -> Self {
151        Self {
152            _name: name,
153            instance_per_backend: vec![(A::VARIANT, Box::new(hal_instance))],
154            requested_backends: A::VARIANT.into(),
155            supported_backends: A::VARIANT.into(),
156            flags: wgt::InstanceFlags::default(),
157            display: None, // TODO: Extract display from HAL instance if available?
158        }
159    }
160
161    pub fn raw(&self, backend: Backend) -> Option<&dyn hal::DynInstance> {
162        self.instance_per_backend
163            .iter()
164            .find_map(|(instance_backend, instance)| {
165                (*instance_backend == backend).then(|| instance.as_ref())
166            })
167    }
168
169    /// # Safety
170    ///
171    /// - The raw instance handle returned must not be manually destroyed.
172    pub unsafe fn as_hal<A: hal::Api>(&self) -> Option<&A::Instance> {
173        self.raw(A::VARIANT).map(|instance| {
174            instance
175                .as_any()
176                .downcast_ref()
177                // This should be impossible. It would mean that backend instance and enum type are mismatching.
178                .expect("Stored instance is not of the correct type")
179        })
180    }
181
182    /// Creates a new surface targeting the given display/window handles.
183    ///
184    /// Internally attempts to create hal surfaces for all enabled backends.
185    ///
186    /// Fails only if creation for surfaces for all enabled backends fails in which case
187    /// the error for each enabled backend is listed.
188    /// Vice versa, if creation for any backend succeeds, success is returned.
189    /// Surface creation errors are logged to the debug log in any case.
190    ///
191    /// # Safety
192    ///
193    /// - `display_handle` must be a valid object to create a surface upon,
194    ///   falls back to the instance display handle otherwise.
195    /// - `window_handle` must remain valid as long as the returned
196    ///   [`SurfaceId`] is being used.
197    pub unsafe fn create_surface(
198        &self,
199        display_handle: Option<raw_window_handle::RawDisplayHandle>,
200        window_handle: raw_window_handle::RawWindowHandle,
201    ) -> Result<Surface, CreateSurfaceError> {
202        profiling::scope!("Instance::create_surface");
203
204        let instance_display_handle = self.display.as_ref().map(|d| {
205            d.display_handle()
206                .expect("Implementation did not provide a DisplayHandle")
207                .as_raw()
208        });
209        let display_handle = match (instance_display_handle, display_handle) {
210            (Some(a), Some(b)) => {
211                if a != b {
212                    return Err(CreateSurfaceError::MismatchingDisplayHandle);
213                }
214                a
215            }
216            (Some(hnd), None) => hnd,
217            (None, Some(hnd)) => hnd,
218            (None, None) => return Err(CreateSurfaceError::MissingDisplayHandle),
219        };
220
221        let mut errors = HashMap::default();
222        let mut surface_per_backend = HashMap::default();
223
224        for (backend, instance) in &self.instance_per_backend {
225            match unsafe {
226                instance
227                    .as_ref()
228                    .create_surface(display_handle, window_handle)
229            } {
230                Ok(raw) => {
231                    surface_per_backend.insert(*backend, raw);
232                }
233                Err(err) => {
234                    log::debug!(
235                        "Instance::create_surface: failed to create surface for {backend:?}: {err:?}"
236                    );
237                    errors.insert(*backend, err);
238                }
239            }
240        }
241
242        if surface_per_backend.is_empty() {
243            Err(CreateSurfaceError::FailedToCreateSurfaceForAnyBackend(
244                errors,
245            ))
246        } else {
247            let surface = Surface {
248                presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
249                surface_per_backend,
250            };
251
252            Ok(surface)
253        }
254    }
255
256    /// Creates a new surface from the given drm configuration.
257    ///
258    /// # Safety
259    ///
260    /// - All parameters must point to valid DRM values.
261    ///
262    /// # Platform Support
263    ///
264    /// This function requires the `"drm"` feature. It is only available on
265    /// non-apple Unix-like platforms (Linux, FreeBSD) and currently only works
266    /// with the Vulkan backend.
267    #[cfg(drm)]
268    #[cfg_attr(not(vulkan), expect(unused_variables, unused_mut))]
269    pub unsafe fn create_surface_from_drm(
270        &self,
271        fd: i32,
272        plane: u32,
273        connector_id: u32,
274        width: u32,
275        height: u32,
276        refresh_rate: u32,
277    ) -> Result<Surface, CreateSurfaceError> {
278        profiling::scope!("Instance::create_surface_from_drm");
279
280        let mut errors = HashMap::default();
281        let mut surface_per_backend: HashMap<Backend, Box<dyn hal::DynSurface>> =
282            HashMap::default();
283
284        #[cfg(vulkan)]
285        {
286            let instance = unsafe { self.as_hal::<hal::api::Vulkan>() }
287                .ok_or(CreateSurfaceError::BackendNotEnabled(Backend::Vulkan))?;
288
289            // Safety must be upheld by the caller
290            match unsafe {
291                instance.create_surface_from_drm(
292                    fd,
293                    plane,
294                    connector_id,
295                    width,
296                    height,
297                    refresh_rate,
298                )
299            } {
300                Ok(surface) => {
301                    surface_per_backend.insert(Backend::Vulkan, Box::new(surface));
302                }
303                Err(err) => {
304                    errors.insert(Backend::Vulkan, err);
305                }
306            }
307        }
308
309        if surface_per_backend.is_empty() {
310            Err(CreateSurfaceError::FailedToCreateSurfaceForAnyBackend(
311                errors,
312            ))
313        } else {
314            let surface = Surface {
315                presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
316                surface_per_backend,
317            };
318
319            Ok(surface)
320        }
321    }
322
323    /// # Safety
324    ///
325    /// `layer` must be a valid pointer.
326    #[cfg(metal)]
327    pub unsafe fn create_surface_metal(
328        &self,
329        layer: *mut core::ffi::c_void,
330    ) -> Result<Surface, CreateSurfaceError> {
331        profiling::scope!("Instance::create_surface_metal");
332
333        let instance = unsafe { self.as_hal::<hal::api::Metal>() }
334            .ok_or(CreateSurfaceError::BackendNotEnabled(Backend::Metal))?;
335
336        let layer = layer.cast();
337        // SAFETY: We do this cast and deref. (rather than using `metal` to get the
338        // object we want) to avoid direct coupling on the `metal` crate.
339        //
340        // To wit, this pointer…
341        //
342        // - …is properly aligned.
343        // - …is dereferenceable to a `MetalLayerRef` as an invariant of the `metal`
344        //   field.
345        // - …points to an _initialized_ `MetalLayerRef`.
346        // - …is only ever aliased via an immutable reference that lives within this
347        //   lexical scope.
348        let layer = unsafe { &*layer };
349        let raw_surface: Box<dyn hal::DynSurface> =
350            Box::new(instance.create_surface_from_layer(layer));
351
352        let surface = Surface {
353            presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
354            surface_per_backend: core::iter::once((Backend::Metal, raw_surface)).collect(),
355        };
356
357        Ok(surface)
358    }
359
360    #[cfg(dx12)]
361    fn create_surface_dx12(
362        &self,
363        create_surface_func: impl FnOnce(&hal::dx12::Instance) -> hal::dx12::Surface,
364    ) -> Result<Surface, CreateSurfaceError> {
365        let instance = unsafe { self.as_hal::<hal::api::Dx12>() }
366            .ok_or(CreateSurfaceError::BackendNotEnabled(Backend::Dx12))?;
367        let surface: Box<dyn hal::DynSurface> = Box::new(create_surface_func(instance));
368
369        let surface = Surface {
370            presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
371            surface_per_backend: core::iter::once((Backend::Dx12, surface)).collect(),
372        };
373
374        Ok(surface)
375    }
376
377    #[cfg(dx12)]
378    /// # Safety
379    ///
380    /// The visual must be valid and able to be used to make a swapchain with.
381    pub unsafe fn create_surface_from_visual(
382        &self,
383        visual: *mut core::ffi::c_void,
384    ) -> Result<Surface, CreateSurfaceError> {
385        profiling::scope!("Instance::instance_create_surface_from_visual");
386        self.create_surface_dx12(|inst| unsafe { inst.create_surface_from_visual(visual) })
387    }
388
389    #[cfg(dx12)]
390    /// # Safety
391    ///
392    /// The surface_handle must be valid and able to be used to make a swapchain with.
393    pub unsafe fn create_surface_from_surface_handle(
394        &self,
395        surface_handle: *mut core::ffi::c_void,
396    ) -> Result<Surface, CreateSurfaceError> {
397        profiling::scope!("Instance::instance_create_surface_from_surface_handle");
398        self.create_surface_dx12(|inst| unsafe {
399            inst.create_surface_from_surface_handle(surface_handle)
400        })
401    }
402
403    #[cfg(dx12)]
404    /// # Safety
405    ///
406    /// The swap_chain_panel must be valid and able to be used to make a swapchain with.
407    pub unsafe fn create_surface_from_swap_chain_panel(
408        &self,
409        swap_chain_panel: *mut core::ffi::c_void,
410    ) -> Result<Surface, CreateSurfaceError> {
411        profiling::scope!("Instance::instance_create_surface_from_swap_chain_panel");
412        self.create_surface_dx12(|inst| unsafe {
413            inst.create_surface_from_swap_chain_panel(swap_chain_panel)
414        })
415    }
416
417    pub fn enumerate_adapters(
418        &self,
419        backends: Backends,
420        apply_limit_buckets: bool,
421    ) -> Vec<Adapter> {
422        profiling::scope!("Instance::enumerate_adapters");
423        api_log!("Instance::enumerate_adapters");
424
425        let mut adapters = Vec::new();
426        for (_backend, instance) in self
427            .instance_per_backend
428            .iter()
429            .filter(|(backend, _)| backends.contains(Backends::from(*backend)))
430        {
431            // NOTE: We might be using `profiling` without any features. The empty backend of this
432            // macro emits no code, so unused code linting changes depending on the backend.
433            profiling::scope!("enumerating", &*alloc::format!("{_backend:?}"));
434
435            let hal_adapters = unsafe { instance.enumerate_adapters(None) };
436
437            adapters.extend(
438                hal_adapters
439                    .into_iter()
440                    .filter_map(|raw| {
441                        if apply_limit_buckets {
442                            limits::apply_limit_buckets(raw)
443                        } else {
444                            Some(raw)
445                        }
446                    })
447                    .map(|raw| {
448                        let adapter = Adapter::new(raw);
449                        api_log_debug!("Adapter {:?}", adapter.raw.info);
450                        adapter
451                    }),
452            );
453        }
454        adapters
455    }
456
457    pub fn request_adapter(
458        &self,
459        desc: &wgt::RequestAdapterOptions<&Surface>,
460        backends: Backends,
461    ) -> Result<Adapter, wgt::RequestAdapterError> {
462        profiling::scope!("Instance::request_adapter");
463        api_log!("Instance::request_adapter");
464
465        let mut adapters = Vec::new();
466        let mut incompatible_surface_backends = Backends::empty();
467        let mut no_fallback_backends = Backends::empty();
468        let mut no_adapter_backends = Backends::empty();
469
470        for &(backend, ref instance) in self
471            .instance_per_backend
472            .iter()
473            .filter(|&&(backend, _)| backends.contains(Backends::from(backend)))
474        {
475            let compatible_hal_surface = desc
476                .compatible_surface
477                .and_then(|surface| surface.raw(backend));
478
479            let mut backend_adapters =
480                unsafe { instance.enumerate_adapters(compatible_hal_surface) };
481            if backend_adapters.is_empty() {
482                log::debug!("enabled backend `{backend:?}` has no adapters");
483                no_adapter_backends |= Backends::from(backend);
484                // by continuing, we avoid setting the further error bits below
485                continue;
486            }
487
488            if desc.force_fallback_adapter {
489                log::debug!("Filtering `{backend:?}` for `force_fallback_adapter`");
490                backend_adapters.retain(|exposed| {
491                    let keep = exposed.info.device_type == wgt::DeviceType::Cpu;
492                    if !keep {
493                        log::debug!("* Eliminating adapter `{}`", exposed.info.name);
494                    }
495                    keep
496                });
497                if backend_adapters.is_empty() {
498                    log::debug!("* Backend `{backend:?}` has no fallback adapters");
499                    no_fallback_backends |= Backends::from(backend);
500                    continue;
501                }
502            }
503
504            if let Some(surface) = desc.compatible_surface {
505                backend_adapters.retain(|exposed| {
506                    let capabilities = surface.get_capabilities_with_raw(exposed);
507                    if let Err(err) = capabilities {
508                        log::debug!(
509                            "Adapter {:?} not compatible with surface: {}",
510                            exposed.info,
511                            err
512                        );
513                        incompatible_surface_backends |= Backends::from(backend);
514                        false
515                    } else {
516                        true
517                    }
518                });
519                if backend_adapters.is_empty() {
520                    incompatible_surface_backends |= Backends::from(backend);
521                    continue;
522                }
523            }
524
525            if desc.apply_limit_buckets {
526                adapters.extend(
527                    backend_adapters
528                        .into_iter()
529                        .filter_map(limits::apply_limit_buckets),
530                );
531            } else {
532                adapters.append(&mut backend_adapters);
533            }
534        }
535
536        match desc.power_preference {
537            PowerPreference::LowPower => {
538                sort(&mut adapters, true);
539            }
540            PowerPreference::HighPerformance => {
541                sort(&mut adapters, false);
542            }
543            PowerPreference::None => {}
544        };
545
546        fn sort(adapters: &mut [hal::DynExposedAdapter], prefer_integrated_gpu: bool) {
547            adapters
548                .sort_by_key(|adapter| get_order(adapter.info.device_type, prefer_integrated_gpu));
549        }
550
551        fn get_order(device_type: wgt::DeviceType, prefer_integrated_gpu: bool) -> u8 {
552            // Since devices of type "Other" might really be "Unknown" and come
553            // from APIs like OpenGL that don't specify device type, Prefer more
554            // Specific types over Other.
555            //
556            // This means that backends which do provide accurate device types
557            // will be preferred if their device type indicates an actual
558            // hardware GPU (integrated or discrete).
559            match device_type {
560                wgt::DeviceType::DiscreteGpu if prefer_integrated_gpu => 2,
561                wgt::DeviceType::IntegratedGpu if prefer_integrated_gpu => 1,
562                wgt::DeviceType::DiscreteGpu => 1,
563                wgt::DeviceType::IntegratedGpu => 2,
564                wgt::DeviceType::Other => 3,
565                wgt::DeviceType::VirtualGpu => 4,
566                wgt::DeviceType::Cpu => 5,
567            }
568        }
569
570        // `request_adapter` can be a bit of a black box.
571        // Shine some light on its decision in debug log.
572        if adapters.is_empty() {
573            log::debug!("Request adapter didn't find compatible adapters.");
574        } else {
575            log::debug!(
576                "Found {} compatible adapters. Sorted by preference:",
577                adapters.len()
578            );
579            for adapter in &adapters {
580                log::debug!("* {:?}", adapter.info);
581            }
582        }
583
584        if let Some(adapter) = adapters.into_iter().next() {
585            api_log_debug!("Request adapter result {:?}", adapter.info);
586            let adapter = Adapter::new(adapter);
587            Ok(adapter)
588        } else {
589            Err(wgt::RequestAdapterError::NotFound {
590                supported_backends: self.supported_backends,
591                requested_backends: self.requested_backends,
592                active_backends: self.active_backends(),
593                no_fallback_backends,
594                no_adapter_backends,
595                incompatible_surface_backends,
596            })
597        }
598    }
599
600    fn active_backends(&self) -> Backends {
601        self.instance_per_backend
602            .iter()
603            .map(|&(backend, _)| Backends::from(backend))
604            .collect()
605    }
606}
607
608pub struct Surface {
609    pub(crate) presentation: Mutex<Option<Presentation>>,
610    pub surface_per_backend: HashMap<Backend, Box<dyn hal::DynSurface>>,
611}
612
613impl ResourceType for Surface {
614    const TYPE: &'static str = "Surface";
615}
616impl crate::storage::StorageItem for Surface {
617    type Marker = markers::Surface;
618}
619
620impl Surface {
621    pub fn get_capabilities(
622        &self,
623        adapter: &Adapter,
624    ) -> Result<hal::SurfaceCapabilities, GetSurfaceSupportError> {
625        self.get_capabilities_with_raw(&adapter.raw)
626    }
627
628    pub fn get_capabilities_with_raw(
629        &self,
630        adapter: &hal::DynExposedAdapter,
631    ) -> Result<hal::SurfaceCapabilities, GetSurfaceSupportError> {
632        let backend = adapter.backend();
633        let suf = self
634            .raw(backend)
635            .ok_or(GetSurfaceSupportError::NotSupportedByBackend(backend))?;
636        profiling::scope!("surface_capabilities");
637        let caps = unsafe { adapter.adapter.surface_capabilities(suf) }
638            .ok_or(GetSurfaceSupportError::FailedToRetrieveSurfaceCapabilitiesForAdapter)?;
639        Ok(caps)
640    }
641
642    pub fn raw(&self, backend: Backend) -> Option<&dyn hal::DynSurface> {
643        self.surface_per_backend
644            .get(&backend)
645            .map(|surface| surface.as_ref())
646    }
647}
648
649impl Drop for Surface {
650    fn drop(&mut self) {
651        if let Some(present) = self.presentation.lock().take() {
652            for (&backend, surface) in &self.surface_per_backend {
653                if backend == present.device.backend() {
654                    unsafe { surface.unconfigure(present.device.raw()) };
655                }
656            }
657        }
658    }
659}
660
661pub struct Adapter {
662    pub(crate) raw: hal::DynExposedAdapter,
663}
664
665impl Adapter {
666    pub fn new(raw: hal::DynExposedAdapter) -> Self {
667        Self { raw }
668    }
669
670    /// Returns the backend this adapter is using.
671    pub fn backend(&self) -> Backend {
672        self.raw.backend()
673    }
674
675    pub fn is_surface_supported(&self, surface: &Surface) -> bool {
676        // If get_capabilities returns Err, then the API does not advertise support for the surface.
677        //
678        // This could occur if the user is running their app on Wayland but Vulkan does not support
679        // VK_KHR_wayland_surface.
680        surface.get_capabilities(self).is_ok()
681    }
682
683    pub fn get_info(&self) -> wgt::AdapterInfo {
684        self.raw.info.clone()
685    }
686
687    pub fn features(&self) -> wgt::Features {
688        self.raw.features
689    }
690
691    pub fn limits(&self) -> wgt::Limits {
692        self.raw.capabilities.limits.clone()
693    }
694
695    pub fn downlevel_capabilities(&self) -> wgt::DownlevelCapabilities {
696        self.raw.capabilities.downlevel.clone()
697    }
698
699    pub fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
700        unsafe { self.raw.adapter.get_presentation_timestamp() }
701    }
702
703    pub fn cooperative_matrix_properties(&self) -> Vec<wgt::CooperativeMatrixProperties> {
704        self.raw.capabilities.cooperative_matrix_properties.clone()
705    }
706
707    pub fn get_texture_format_features(
708        &self,
709        format: wgt::TextureFormat,
710    ) -> wgt::TextureFormatFeatures {
711        use hal::TextureFormatCapabilities as Tfc;
712
713        let caps = unsafe { self.raw.adapter.texture_format_capabilities(format) };
714        let mut allowed_usages = wgt::TextureUsages::empty();
715
716        allowed_usages.set(wgt::TextureUsages::COPY_SRC, caps.contains(Tfc::COPY_SRC));
717        allowed_usages.set(wgt::TextureUsages::COPY_DST, caps.contains(Tfc::COPY_DST));
718        allowed_usages.set(
719            wgt::TextureUsages::TEXTURE_BINDING,
720            caps.contains(Tfc::SAMPLED),
721        );
722        allowed_usages.set(
723            wgt::TextureUsages::STORAGE_BINDING,
724            caps.intersects(
725                Tfc::STORAGE_WRITE_ONLY
726                    | Tfc::STORAGE_READ_ONLY
727                    | Tfc::STORAGE_READ_WRITE
728                    | Tfc::STORAGE_ATOMIC,
729            ),
730        );
731        allowed_usages.set(
732            wgt::TextureUsages::RENDER_ATTACHMENT | wgt::TextureUsages::TRANSIENT,
733            caps.intersects(Tfc::COLOR_ATTACHMENT | Tfc::DEPTH_STENCIL_ATTACHMENT),
734        );
735        allowed_usages.set(
736            wgt::TextureUsages::STORAGE_ATOMIC,
737            caps.contains(Tfc::STORAGE_ATOMIC),
738        );
739
740        let mut flags = wgt::TextureFormatFeatureFlags::empty();
741        flags.set(
742            wgt::TextureFormatFeatureFlags::STORAGE_READ_ONLY,
743            caps.contains(Tfc::STORAGE_READ_ONLY),
744        );
745        flags.set(
746            wgt::TextureFormatFeatureFlags::STORAGE_WRITE_ONLY,
747            caps.contains(Tfc::STORAGE_WRITE_ONLY),
748        );
749        flags.set(
750            wgt::TextureFormatFeatureFlags::STORAGE_READ_WRITE,
751            caps.contains(Tfc::STORAGE_READ_WRITE),
752        );
753
754        flags.set(
755            wgt::TextureFormatFeatureFlags::STORAGE_ATOMIC,
756            caps.contains(Tfc::STORAGE_ATOMIC),
757        );
758
759        flags.set(
760            wgt::TextureFormatFeatureFlags::FILTERABLE,
761            caps.contains(Tfc::SAMPLED_LINEAR),
762        );
763
764        flags.set(
765            wgt::TextureFormatFeatureFlags::BLENDABLE,
766            caps.contains(Tfc::COLOR_ATTACHMENT_BLEND),
767        );
768
769        flags.set(
770            wgt::TextureFormatFeatureFlags::MULTISAMPLE_X2,
771            caps.contains(Tfc::MULTISAMPLE_X2),
772        );
773        flags.set(
774            wgt::TextureFormatFeatureFlags::MULTISAMPLE_X4,
775            caps.contains(Tfc::MULTISAMPLE_X4),
776        );
777        flags.set(
778            wgt::TextureFormatFeatureFlags::MULTISAMPLE_X8,
779            caps.contains(Tfc::MULTISAMPLE_X8),
780        );
781        flags.set(
782            wgt::TextureFormatFeatureFlags::MULTISAMPLE_X16,
783            caps.contains(Tfc::MULTISAMPLE_X16),
784        );
785
786        flags.set(
787            wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
788            caps.contains(Tfc::MULTISAMPLE_RESOLVE),
789        );
790
791        wgt::TextureFormatFeatures {
792            allowed_usages,
793            flags,
794        }
795    }
796
797    fn create_device_and_queue_from_hal(
798        self: &Arc<Self>,
799        hal_device: hal::DynOpenDevice,
800        desc: &DeviceDescriptor,
801        instance_flags: wgt::InstanceFlags,
802    ) -> Result<(Arc<Device>, Arc<Queue>), RequestDeviceError> {
803        api_log!("Adapter::create_device");
804
805        let device = Device::new(hal_device.device, self, desc, instance_flags)?;
806        let device = Arc::new(device);
807
808        let queue = Queue::new(device.clone(), hal_device.queue, instance_flags)?;
809        let queue = Arc::new(queue);
810
811        device.set_queue(&queue);
812        device.late_init_resources_with_queue()?;
813
814        Ok((device, queue))
815    }
816
817    pub fn create_device_and_queue(
818        self: &Arc<Self>,
819        desc: &DeviceDescriptor,
820        instance_flags: wgt::InstanceFlags,
821    ) -> Result<(Arc<Device>, Arc<Queue>), RequestDeviceError> {
822        // Verify all features were exposed by the adapter
823        if !self.raw.features.contains(desc.required_features) {
824            return Err(RequestDeviceError::UnsupportedFeature(
825                desc.required_features - self.raw.features,
826            ));
827        }
828
829        // Check if experimental features are permitted to be enabled.
830        if desc
831            .required_features
832            .intersects(wgt::Features::all_experimental_mask())
833            && !desc.experimental_features.is_enabled()
834        {
835            return Err(RequestDeviceError::ExperimentalFeaturesNotEnabled(
836                desc.required_features
837                    .intersection(wgt::Features::all_experimental_mask()),
838            ));
839        }
840
841        let caps = &self.raw.capabilities;
842        if Backends::PRIMARY.contains(Backends::from(self.backend()))
843            && !caps.downlevel.is_webgpu_compliant()
844        {
845            let missing_flags = wgt::DownlevelFlags::compliant() - caps.downlevel.flags;
846            log::warn!("Missing downlevel flags: {missing_flags:?}\n{DOWNLEVEL_WARNING_MESSAGE}");
847            log::warn!("{:#?}", caps.downlevel);
848        }
849
850        // Verify feature preconditions
851        if desc
852            .required_features
853            .contains(wgt::Features::MAPPABLE_PRIMARY_BUFFERS)
854            && self.raw.info.device_type == wgt::DeviceType::DiscreteGpu
855        {
856            log::warn!(
857                "Feature MAPPABLE_PRIMARY_BUFFERS enabled on a discrete gpu. \
858                        This is a massive performance footgun and likely not what you wanted"
859            );
860        }
861
862        if let Some(failed) = check_limits(&desc.required_limits, &caps.limits).pop() {
863            return Err(RequestDeviceError::LimitsExceeded(failed));
864        }
865
866        let open = unsafe {
867            self.raw.adapter.open(
868                desc.required_features,
869                &desc.required_limits,
870                &desc.memory_hints,
871            )
872        }
873        .map_err(DeviceError::from_hal)?;
874
875        self.create_device_and_queue_from_hal(open, desc, instance_flags)
876    }
877}
878
879crate::impl_resource_type!(Adapter);
880crate::impl_storage_item!(Adapter);
881
882#[derive(Clone, Debug, Error)]
883#[non_exhaustive]
884pub enum GetSurfaceSupportError {
885    #[error("Surface is not supported for the specified backend {0}")]
886    NotSupportedByBackend(Backend),
887    #[error("Failed to retrieve surface capabilities for the specified adapter.")]
888    FailedToRetrieveSurfaceCapabilitiesForAdapter,
889}
890
891#[derive(Clone, Debug, Error)]
892/// Error when requesting a device from the adapter
893#[non_exhaustive]
894pub enum RequestDeviceError {
895    #[error(transparent)]
896    Device(#[from] DeviceError),
897    #[error(transparent)]
898    LimitsExceeded(#[from] FailedLimit),
899    #[error("Failed to initialize Timestamp Normalizer")]
900    TimestampNormalizerInitFailed(#[from] TimestampNormalizerInitError),
901    #[error("Unsupported features were requested: {0}")]
902    UnsupportedFeature(wgt::Features),
903    #[error(
904        "Some experimental features, {0}, were requested, but experimental features are not enabled"
905    )]
906    ExperimentalFeaturesNotEnabled(wgt::Features),
907}
908
909#[derive(Clone, Debug, Error)]
910#[non_exhaustive]
911pub enum CreateSurfaceError {
912    #[error("The backend {0} was not enabled on the instance.")]
913    BackendNotEnabled(Backend),
914    #[error("Failed to create surface for any enabled backend: {0:?}")]
915    FailedToCreateSurfaceForAnyBackend(HashMap<Backend, hal::InstanceError>),
916    #[error("The display handle used to create this Instance does not match the one used to create a surface on it")]
917    MismatchingDisplayHandle,
918    #[error(
919        "No `DisplayHandle` is available to create this surface with.  When creating a surface with `create_surface()` \
920        you must specify a display handle in `InstanceDescriptor::display`.  \
921        Rarely, if you need to create surfaces from different `DisplayHandle`s (ex. different Wayland or X11 connections), \
922        you must use `create_surface_unsafe()`."
923    )]
924    MissingDisplayHandle,
925}
926
927impl Global {
928    /// Creates a new surface targeting the given display/window handles.
929    ///
930    /// Internally attempts to create hal surfaces for all enabled backends.
931    ///
932    /// Fails only if creation for surfaces for all enabled backends fails in which case
933    /// the error for each enabled backend is listed.
934    /// Vice versa, if creation for any backend succeeds, success is returned.
935    /// Surface creation errors are logged to the debug log in any case.
936    ///
937    /// id_in:
938    /// - If `Some`, the id to assign to the surface. A new one will be generated otherwise.
939    ///
940    /// # Safety
941    ///
942    /// - `display_handle` must be a valid object to create a surface upon,
943    ///   falls back to the instance display handle otherwise.
944    /// - `window_handle` must remain valid as long as the returned
945    ///   [`SurfaceId`] is being used.
946    pub unsafe fn instance_create_surface(
947        &self,
948        display_handle: Option<raw_window_handle::RawDisplayHandle>,
949        window_handle: raw_window_handle::RawWindowHandle,
950        id_in: Option<SurfaceId>,
951    ) -> Result<SurfaceId, CreateSurfaceError> {
952        let surface = unsafe { self.instance.create_surface(display_handle, window_handle) }?;
953        let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
954        Ok(id)
955    }
956
957    /// Creates a new surface from the given drm configuration.
958    ///
959    /// # Safety
960    ///
961    /// - All parameters must point to valid DRM values.
962    ///
963    /// # Platform Support
964    ///
965    /// This function requires the `"drm"` feature, and is only available on
966    /// non-apple Unix-like platforms (Linux, FreeBSD) and currently only works
967    /// with the Vulkan backend.
968    #[cfg(drm)]
969    pub unsafe fn instance_create_surface_from_drm(
970        &self,
971        fd: i32,
972        plane: u32,
973        connector_id: u32,
974        width: u32,
975        height: u32,
976        refresh_rate: u32,
977        id_in: Option<SurfaceId>,
978    ) -> Result<SurfaceId, CreateSurfaceError> {
979        let surface = unsafe {
980            self.instance.create_surface_from_drm(
981                fd,
982                plane,
983                connector_id,
984                width,
985                height,
986                refresh_rate,
987            )
988        }?;
989        let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
990
991        Ok(id)
992    }
993
994    /// # Safety
995    ///
996    /// `layer` must be a valid pointer.
997    #[cfg(metal)]
998    pub unsafe fn instance_create_surface_metal(
999        &self,
1000        layer: *mut core::ffi::c_void,
1001        id_in: Option<SurfaceId>,
1002    ) -> Result<SurfaceId, CreateSurfaceError> {
1003        let surface = unsafe { self.instance.create_surface_metal(layer) }?;
1004        let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
1005        Ok(id)
1006    }
1007
1008    #[cfg(dx12)]
1009    /// # Safety
1010    ///
1011    /// The visual must be valid and able to be used to make a swapchain with.
1012    pub unsafe fn instance_create_surface_from_visual(
1013        &self,
1014        visual: *mut core::ffi::c_void,
1015        id_in: Option<SurfaceId>,
1016    ) -> Result<SurfaceId, CreateSurfaceError> {
1017        let surface = unsafe { self.instance.create_surface_from_visual(visual) }?;
1018        let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
1019        Ok(id)
1020    }
1021
1022    #[cfg(dx12)]
1023    /// # Safety
1024    ///
1025    /// The surface_handle must be valid and able to be used to make a swapchain with.
1026    pub unsafe fn instance_create_surface_from_surface_handle(
1027        &self,
1028        surface_handle: *mut core::ffi::c_void,
1029        id_in: Option<SurfaceId>,
1030    ) -> Result<SurfaceId, CreateSurfaceError> {
1031        let surface = unsafe {
1032            self.instance
1033                .create_surface_from_surface_handle(surface_handle)
1034        }?;
1035        let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
1036        Ok(id)
1037    }
1038
1039    #[cfg(dx12)]
1040    /// # Safety
1041    ///
1042    /// The swap_chain_panel must be valid and able to be used to make a swapchain with.
1043    pub unsafe fn instance_create_surface_from_swap_chain_panel(
1044        &self,
1045        swap_chain_panel: *mut core::ffi::c_void,
1046        id_in: Option<SurfaceId>,
1047    ) -> Result<SurfaceId, CreateSurfaceError> {
1048        let surface = unsafe {
1049            self.instance
1050                .create_surface_from_swap_chain_panel(swap_chain_panel)
1051        }?;
1052        let id = self.surfaces.prepare(id_in).assign(Arc::new(surface));
1053        Ok(id)
1054    }
1055
1056    pub fn surface_drop(&self, id: SurfaceId) {
1057        profiling::scope!("Surface::drop");
1058
1059        api_log!("Surface::drop {id:?}");
1060
1061        self.surfaces.remove(id);
1062    }
1063
1064    pub fn enumerate_adapters(
1065        &self,
1066        backends: Backends,
1067        apply_limit_buckets: bool,
1068    ) -> Vec<AdapterId> {
1069        let adapters = self
1070            .instance
1071            .enumerate_adapters(backends, apply_limit_buckets);
1072        adapters
1073            .into_iter()
1074            .map(|adapter| self.hub.adapters.prepare(None).assign(Arc::new(adapter)))
1075            .collect()
1076    }
1077
1078    pub fn request_adapter(
1079        &self,
1080        desc: &RequestAdapterOptions,
1081        backends: Backends,
1082        id_in: Option<AdapterId>,
1083    ) -> Result<AdapterId, wgt::RequestAdapterError> {
1084        let compatible_surface = desc.compatible_surface.map(|id| self.surfaces.get(id));
1085        let desc = wgt::RequestAdapterOptions {
1086            power_preference: desc.power_preference,
1087            force_fallback_adapter: desc.force_fallback_adapter,
1088            compatible_surface: compatible_surface.as_deref(),
1089            apply_limit_buckets: desc.apply_limit_buckets,
1090        };
1091        let adapter = self.instance.request_adapter(&desc, backends)?;
1092        let id = self.hub.adapters.prepare(id_in).assign(Arc::new(adapter));
1093        Ok(id)
1094    }
1095
1096    /// Create an adapter from a HAL adapter.
1097    ///
1098    /// The HAL adapter may be obtained e.g. by calling `enumerate_adapters` on
1099    /// the HAL directly.
1100    ///
1101    /// If [limit bucketing][lt] is desired, [`crate::limits::apply_limit_buckets`]
1102    /// should be called with the HAL adapter before calling this function.
1103    ///
1104    /// # Safety
1105    ///
1106    /// `hal_adapter` must be created from this global internal instance handle.
1107    ///
1108    /// [lt]: crate::limits#Limit-bucketing
1109    pub unsafe fn create_adapter_from_hal(
1110        &self,
1111        hal_adapter: hal::DynExposedAdapter,
1112        input: Option<AdapterId>,
1113    ) -> AdapterId {
1114        profiling::scope!("Instance::create_adapter_from_hal");
1115
1116        let fid = self.hub.adapters.prepare(input);
1117        let id = fid.assign(Arc::new(Adapter::new(hal_adapter)));
1118
1119        resource_log!("Created Adapter {:?}", id);
1120        id
1121    }
1122
1123    pub fn adapter_get_info(&self, adapter_id: AdapterId) -> wgt::AdapterInfo {
1124        let adapter = self.hub.adapters.get(adapter_id);
1125        adapter.get_info()
1126    }
1127
1128    pub fn adapter_get_texture_format_features(
1129        &self,
1130        adapter_id: AdapterId,
1131        format: wgt::TextureFormat,
1132    ) -> wgt::TextureFormatFeatures {
1133        let adapter = self.hub.adapters.get(adapter_id);
1134        adapter.get_texture_format_features(format)
1135    }
1136
1137    pub fn adapter_features(&self, adapter_id: AdapterId) -> wgt::Features {
1138        let adapter = self.hub.adapters.get(adapter_id);
1139        adapter.features()
1140    }
1141
1142    pub fn adapter_limits(&self, adapter_id: AdapterId) -> wgt::Limits {
1143        let adapter = self.hub.adapters.get(adapter_id);
1144        adapter.limits()
1145    }
1146
1147    pub fn adapter_downlevel_capabilities(
1148        &self,
1149        adapter_id: AdapterId,
1150    ) -> wgt::DownlevelCapabilities {
1151        let adapter = self.hub.adapters.get(adapter_id);
1152        adapter.downlevel_capabilities()
1153    }
1154
1155    pub fn adapter_get_presentation_timestamp(
1156        &self,
1157        adapter_id: AdapterId,
1158    ) -> wgt::PresentationTimestamp {
1159        let adapter = self.hub.adapters.get(adapter_id);
1160        adapter.get_presentation_timestamp()
1161    }
1162
1163    pub fn adapter_cooperative_matrix_properties(
1164        &self,
1165        adapter_id: AdapterId,
1166    ) -> Vec<wgt::CooperativeMatrixProperties> {
1167        let adapter = self.hub.adapters.get(adapter_id);
1168        adapter.cooperative_matrix_properties()
1169    }
1170
1171    pub fn adapter_drop(&self, adapter_id: AdapterId) {
1172        profiling::scope!("Adapter::drop");
1173        api_log!("Adapter::drop {adapter_id:?}");
1174
1175        self.hub.adapters.remove(adapter_id);
1176    }
1177}
1178
1179impl Global {
1180    pub fn adapter_request_device(
1181        &self,
1182        adapter_id: AdapterId,
1183        desc: &DeviceDescriptor,
1184        device_id_in: Option<DeviceId>,
1185        queue_id_in: Option<QueueId>,
1186    ) -> Result<(DeviceId, QueueId), RequestDeviceError> {
1187        profiling::scope!("Adapter::request_device");
1188        api_log!("Adapter::request_device");
1189
1190        let device_fid = self.hub.devices.prepare(device_id_in);
1191        let queue_fid = self.hub.queues.prepare(queue_id_in);
1192
1193        let adapter = self.hub.adapters.get(adapter_id);
1194        let (device, queue) = adapter.create_device_and_queue(desc, self.instance.flags)?;
1195
1196        let device_id = device_fid.assign(device);
1197        resource_log!("Created Device {:?}", device_id);
1198
1199        let queue_id = queue_fid.assign(queue);
1200        resource_log!("Created Queue {:?}", queue_id);
1201
1202        Ok((device_id, queue_id))
1203    }
1204
1205    /// # Safety
1206    ///
1207    /// - `hal_device` must be created from `adapter_id` or its internal handle.
1208    /// - `desc` must be a subset of `hal_device` features and limits.
1209    pub unsafe fn create_device_from_hal(
1210        &self,
1211        adapter_id: AdapterId,
1212        hal_device: hal::DynOpenDevice,
1213        desc: &DeviceDescriptor,
1214        device_id_in: Option<DeviceId>,
1215        queue_id_in: Option<QueueId>,
1216    ) -> Result<(DeviceId, QueueId), RequestDeviceError> {
1217        profiling::scope!("Global::create_device_from_hal");
1218
1219        let devices_fid = self.hub.devices.prepare(device_id_in);
1220        let queues_fid = self.hub.queues.prepare(queue_id_in);
1221
1222        let adapter = self.hub.adapters.get(adapter_id);
1223        let (device, queue) =
1224            adapter.create_device_and_queue_from_hal(hal_device, desc, self.instance.flags)?;
1225
1226        let device_id = devices_fid.assign(device);
1227        resource_log!("Created Device {:?}", device_id);
1228
1229        let queue_id = queues_fid.assign(queue);
1230        resource_log!("Created Queue {:?}", queue_id);
1231
1232        Ok((device_id, queue_id))
1233    }
1234}