wgpu_core/
global.rs

1use alloc::{borrow::ToOwned as _, sync::Arc};
2use core::fmt;
3
4use crate::{
5    hal_api::HalApi,
6    hub::{Hub, HubReport},
7    instance::{Instance, Surface},
8    registry::{Registry, RegistryReport},
9    resource_log,
10};
11
12#[derive(Debug, PartialEq, Eq)]
13pub struct GlobalReport {
14    pub surfaces: RegistryReport,
15    pub hub: HubReport,
16}
17
18impl GlobalReport {
19    pub fn surfaces(&self) -> &RegistryReport {
20        &self.surfaces
21    }
22    pub fn hub_report(&self) -> &HubReport {
23        &self.hub
24    }
25}
26
27pub struct Global {
28    pub(crate) surfaces: Registry<Arc<Surface>>,
29    pub(crate) hub: Hub,
30    // the instance must be dropped last
31    pub instance: Instance,
32}
33
34impl Global {
35    pub fn new(name: &str, instance_desc: &wgt::InstanceDescriptor) -> Self {
36        profiling::scope!("Global::new");
37        Self {
38            instance: Instance::new(name, instance_desc),
39            surfaces: Registry::new(),
40            hub: Hub::new(),
41        }
42    }
43
44    /// # Safety
45    ///
46    /// Refer to the creation of wgpu-hal Instance for every backend.
47    pub unsafe fn from_hal_instance<A: HalApi>(name: &str, hal_instance: A::Instance) -> Self {
48        profiling::scope!("Global::new");
49
50        Self {
51            instance: Instance::from_hal_instance::<A>(name.to_owned(), hal_instance),
52            surfaces: Registry::new(),
53            hub: Hub::new(),
54        }
55    }
56
57    /// # Safety
58    ///
59    /// - The raw instance handle returned must not be manually destroyed.
60    pub unsafe fn instance_as_hal<A: HalApi>(&self) -> Option<&A::Instance> {
61        unsafe { self.instance.as_hal::<A>() }
62    }
63
64    /// # Safety
65    ///
66    /// - The raw handles obtained from the Instance must not be manually destroyed
67    pub unsafe fn from_instance(instance: Instance) -> Self {
68        profiling::scope!("Global::new");
69        Self {
70            instance,
71            surfaces: Registry::new(),
72            hub: Hub::new(),
73        }
74    }
75
76    pub fn generate_report(&self) -> GlobalReport {
77        GlobalReport {
78            surfaces: self.surfaces.generate_report(),
79            hub: self.hub.generate_report(),
80        }
81    }
82}
83
84impl fmt::Debug for Global {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.debug_struct("Global").finish()
87    }
88}
89
90impl Drop for Global {
91    fn drop(&mut self) {
92        profiling::scope!("Global::drop");
93        resource_log!("Global::drop");
94    }
95}
96
97#[cfg(send_sync)]
98fn _test_send_sync(global: &Global) {
99    fn test_internal<T: Send + Sync>(_: T) {}
100    test_internal(global)
101}