wgpu_core/
hub.rs

1/*! Allocating resource ids, and tracking the resources they refer to.
2
3The `wgpu_core` API uses identifiers of type [`Id<R>`] to refer to
4resources of type `R`. For example, [`id::DeviceId`] is an alias for
5`Id<markers::Device>`, and [`id::BufferId`] is an alias for
6`Id<markers::Buffer>`. `Id` implements `Copy`, `Hash`, `Eq`, `Ord`, and
7of course `Debug`.
8
9[`id::DeviceId`]: crate::id::DeviceId
10[`id::BufferId`]: crate::id::BufferId
11
12Each `Id` contains not only an index for the resource it denotes but
13also a Backend indicating which `wgpu` backend it belongs to.
14
15`Id`s also incorporate a generation number, for additional validation.
16
17The resources to which identifiers refer are freed explicitly.
18Attempting to use an identifier for a resource that has been freed
19elicits an error result.
20
21## Assigning ids to resources
22
23The users of `wgpu_core` generally want resource ids to be assigned
24in one of two ways:
25
26- Users like `wgpu` want `wgpu_core` to assign ids to resources itself.
27  For example, `wgpu` expects to call `Global::device_create_buffer`
28  and have the return value indicate the newly created buffer's id.
29
30- Users like `player` and Firefox want to allocate ids themselves, and
31  pass `Global::device_create_buffer` and friends the id to assign the
32  new resource.
33
34To accommodate either pattern, `wgpu_core` methods that create
35resources all expect an `id_in` argument that the caller can use to
36specify the id, and they all return the id used. For example, the
37declaration of `Global::device_create_buffer` looks like this:
38
39```ignore
40impl Global {
41    /* ... */
42    pub fn device_create_buffer<A: HalApi>(
43        &self,
44        device_id: id::DeviceId,
45        desc: &resource::BufferDescriptor,
46        id_in: Input<G>,
47    ) -> (id::BufferId, Option<resource::CreateBufferError>) {
48        /* ... */
49    }
50    /* ... */
51}
52```
53
54Users that want to assign resource ids themselves pass in the id they
55want as the `id_in` argument, whereas users that want `wgpu_core`
56itself to choose ids always pass `()`. In either case, the id
57ultimately assigned is returned as the first element of the tuple.
58
59Producing true identifiers from `id_in` values is the job of an
60[`crate::identity::IdentityManager`] or ids will be received from outside through `Option<Id>` arguments.
61
62## Id allocation and streaming
63
64Perhaps surprisingly, allowing users to assign resource ids themselves
65enables major performance improvements in some applications.
66
67The `wgpu_core` API is designed for use by Firefox's [WebGPU]
68implementation. For security, web content and GPU use must be kept
69segregated in separate processes, with all interaction between them
70mediated by an inter-process communication protocol. As web content uses
71the WebGPU API, the content process sends messages to the GPU process,
72which interacts with the platform's GPU APIs on content's behalf,
73occasionally sending results back.
74
75In a classic Rust API, a resource allocation function takes parameters
76describing the resource to create, and if creation succeeds, it returns
77the resource id in a `Result::Ok` value. However, this design is a poor
78fit for the split-process design described above: content must wait for
79the reply to its buffer-creation message (say) before it can know which
80id it can use in the next message that uses that buffer. On a common
81usage pattern, the classic Rust design imposes the latency of a full
82cross-process round trip.
83
84We can avoid incurring these round-trip latencies simply by letting the
85content process assign resource ids itself. With this approach, content
86can choose an id for the new buffer, send a message to create the
87buffer, and then immediately send the next message operating on that
88buffer, since it already knows its id. Allowing content and GPU process
89activity to be pipelined greatly improves throughput.
90
91To help propagate errors correctly in this style of usage, when resource
92creation fails, the id supplied for that resource is marked to indicate
93as much, allowing subsequent operations using that id to be properly
94flagged as errors as well.
95
96[`process`]: crate::identity::IdentityManager::process
97[`Id<R>`]: crate::id::Id
98[wrapped in a mutex]: trait.IdentityHandler.html#impl-IdentityHandler%3CI%3E-for-Mutex%3CIdentityManager%3E
99[WebGPU]: https://www.w3.org/TR/webgpu/
100
101*/
102
103use crate::{
104    binding_model::{BindGroup, BindGroupLayout, PipelineLayout},
105    command::{CommandBuffer, RenderBundle},
106    device::{queue::Queue, Device},
107    instance::Adapter,
108    pipeline::{ComputePipeline, PipelineCache, RenderPipeline, ShaderModule},
109    registry::{Registry, RegistryReport},
110    resource::{Buffer, Fallible, QuerySet, Sampler, StagingBuffer, Texture, TextureView},
111};
112use std::{fmt::Debug, sync::Arc};
113
114#[derive(Debug, PartialEq, Eq)]
115pub struct HubReport {
116    pub adapters: RegistryReport,
117    pub devices: RegistryReport,
118    pub queues: RegistryReport,
119    pub pipeline_layouts: RegistryReport,
120    pub shader_modules: RegistryReport,
121    pub bind_group_layouts: RegistryReport,
122    pub bind_groups: RegistryReport,
123    pub command_buffers: RegistryReport,
124    pub render_bundles: RegistryReport,
125    pub render_pipelines: RegistryReport,
126    pub compute_pipelines: RegistryReport,
127    pub pipeline_caches: RegistryReport,
128    pub query_sets: RegistryReport,
129    pub buffers: RegistryReport,
130    pub textures: RegistryReport,
131    pub texture_views: RegistryReport,
132    pub samplers: RegistryReport,
133}
134
135impl HubReport {
136    pub fn is_empty(&self) -> bool {
137        self.adapters.is_empty()
138    }
139}
140
141#[allow(rustdoc::private_intra_doc_links)]
142/// All the resources tracked by a [`crate::global::Global`].
143///
144/// ## Locking
145///
146/// Each field in `Hub` is a [`Registry`] holding all the values of a
147/// particular type of resource, all protected by a single RwLock.
148/// So for example, to access any [`Buffer`], you must acquire a read
149/// lock on the `Hub`s entire buffers registry. The lock guard
150/// gives you access to the `Registry`'s [`Storage`], which you can
151/// then index with the buffer's id. (Yes, this design causes
152/// contention; see [#2272].)
153///
154/// But most `wgpu` operations require access to several different
155/// kinds of resource, so you often need to hold locks on several
156/// different fields of your [`Hub`] simultaneously.
157///
158/// Inside the `Registry` there are `Arc<T>` where `T` is a Resource
159/// Lock of `Registry` happens only when accessing to get the specific resource
160///
161/// [`Storage`]: crate::storage::Storage
162pub struct Hub {
163    pub(crate) adapters: Registry<Arc<Adapter>>,
164    pub(crate) devices: Registry<Arc<Device>>,
165    pub(crate) queues: Registry<Arc<Queue>>,
166    pub(crate) pipeline_layouts: Registry<Fallible<PipelineLayout>>,
167    pub(crate) shader_modules: Registry<Fallible<ShaderModule>>,
168    pub(crate) bind_group_layouts: Registry<Fallible<BindGroupLayout>>,
169    pub(crate) bind_groups: Registry<Fallible<BindGroup>>,
170    pub(crate) command_buffers: Registry<Arc<CommandBuffer>>,
171    pub(crate) render_bundles: Registry<Fallible<RenderBundle>>,
172    pub(crate) render_pipelines: Registry<Fallible<RenderPipeline>>,
173    pub(crate) compute_pipelines: Registry<Fallible<ComputePipeline>>,
174    pub(crate) pipeline_caches: Registry<Fallible<PipelineCache>>,
175    pub(crate) query_sets: Registry<Fallible<QuerySet>>,
176    pub(crate) buffers: Registry<Fallible<Buffer>>,
177    pub(crate) staging_buffers: Registry<StagingBuffer>,
178    pub(crate) textures: Registry<Fallible<Texture>>,
179    pub(crate) texture_views: Registry<Fallible<TextureView>>,
180    pub(crate) samplers: Registry<Fallible<Sampler>>,
181}
182
183impl Hub {
184    pub(crate) fn new() -> Self {
185        Self {
186            adapters: Registry::new(),
187            devices: Registry::new(),
188            queues: Registry::new(),
189            pipeline_layouts: Registry::new(),
190            shader_modules: Registry::new(),
191            bind_group_layouts: Registry::new(),
192            bind_groups: Registry::new(),
193            command_buffers: Registry::new(),
194            render_bundles: Registry::new(),
195            render_pipelines: Registry::new(),
196            compute_pipelines: Registry::new(),
197            pipeline_caches: Registry::new(),
198            query_sets: Registry::new(),
199            buffers: Registry::new(),
200            staging_buffers: Registry::new(),
201            textures: Registry::new(),
202            texture_views: Registry::new(),
203            samplers: Registry::new(),
204        }
205    }
206
207    pub fn generate_report(&self) -> HubReport {
208        HubReport {
209            adapters: self.adapters.generate_report(),
210            devices: self.devices.generate_report(),
211            queues: self.queues.generate_report(),
212            pipeline_layouts: self.pipeline_layouts.generate_report(),
213            shader_modules: self.shader_modules.generate_report(),
214            bind_group_layouts: self.bind_group_layouts.generate_report(),
215            bind_groups: self.bind_groups.generate_report(),
216            command_buffers: self.command_buffers.generate_report(),
217            render_bundles: self.render_bundles.generate_report(),
218            render_pipelines: self.render_pipelines.generate_report(),
219            compute_pipelines: self.compute_pipelines.generate_report(),
220            pipeline_caches: self.pipeline_caches.generate_report(),
221            query_sets: self.query_sets.generate_report(),
222            buffers: self.buffers.generate_report(),
223            textures: self.textures.generate_report(),
224            texture_views: self.texture_views.generate_report(),
225            samplers: self.samplers.generate_report(),
226        }
227    }
228}