wgpu/util/
mod.rs

1//! Utility structures and functions that are built on top of the main `wgpu` API.
2//!
3//! Nothing in this module is a part of the WebGPU API specification;
4//! they are unique to the `wgpu` library.
5
6// TODO: For [`belt::StagingBelt`] to be available in `no_std` its usage of [`std::sync::mpsc`]
7// must be replaced with an appropriate alternative.
8#[cfg(std)]
9mod belt;
10mod device;
11mod encoder;
12mod init;
13mod mutex;
14mod panicking;
15mod spirv;
16mod texture_blitter;
17
18use alloc::{format, string::String};
19
20#[cfg(std)]
21pub use belt::StagingBelt;
22pub use device::{BufferInitDescriptor, DeviceExt};
23pub use encoder::RenderEncoder;
24pub use init::*;
25pub use spirv::*;
26#[cfg(feature = "wgsl")]
27pub use texture_blitter::{TextureBlitter, TextureBlitterBuilder};
28pub use wgt::{
29    math::*, DispatchIndirectArgs, DrawIndexedIndirectArgs, DrawIndirectArgs, TextureDataOrder,
30};
31
32pub(crate) use mutex::Mutex;
33pub(crate) use panicking::is_panicking;
34
35use crate::dispatch;
36
37/// CPU accessible buffer used to download data back from the GPU.
38pub struct DownloadBuffer {
39    _gpu_buffer: super::Buffer,
40    mapped_range: dispatch::DispatchBufferMappedRange,
41}
42
43impl DownloadBuffer {
44    /// Asynchronously read the contents of a buffer.
45    pub fn read_buffer(
46        device: &super::Device,
47        queue: &super::Queue,
48        buffer: &super::BufferSlice<'_>,
49        callback: impl FnOnce(Result<Self, super::BufferAsyncError>) + Send + 'static,
50    ) {
51        let size = buffer.size.into();
52
53        let download = device.create_buffer(&super::BufferDescriptor {
54            size,
55            usage: super::BufferUsages::COPY_DST | super::BufferUsages::MAP_READ,
56            mapped_at_creation: false,
57            label: None,
58        });
59
60        let mut encoder =
61            device.create_command_encoder(&super::CommandEncoderDescriptor { label: None });
62        encoder.copy_buffer_to_buffer(buffer.buffer, buffer.offset, &download, 0, size);
63        let command_buffer: super::CommandBuffer = encoder.finish();
64        queue.submit(Some(command_buffer));
65
66        download
67            .clone()
68            .slice(..)
69            .map_async(super::MapMode::Read, move |result| {
70                if let Err(e) = result {
71                    callback(Err(e));
72                    return;
73                }
74
75                let mapped_range = download.inner.get_mapped_range(0..size);
76                callback(Ok(Self {
77                    _gpu_buffer: download,
78                    mapped_range,
79                }));
80            });
81    }
82}
83
84impl core::ops::Deref for DownloadBuffer {
85    type Target = [u8];
86    fn deref(&self) -> &[u8] {
87        // SAFETY: `self.mapped_range` is always a read mapping
88        unsafe { self.mapped_range.read_slice() }
89    }
90}
91
92/// A recommended key for storing [`PipelineCache`]s for the adapter
93/// associated with the given [`AdapterInfo`](wgt::AdapterInfo)
94/// This key will define a class of adapters for which the same cache
95/// might be valid.
96///
97/// If this returns `None`, the adapter doesn't support [`PipelineCache`].
98/// This may be because the API doesn't support application managed caches
99/// (such as browser WebGPU), or that `wgpu` hasn't implemented it for
100/// that API yet.
101///
102/// This key could be used as a filename, as seen in the example below.
103///
104/// # Examples
105///
106/// ```no_run
107/// # use std::path::PathBuf;
108/// use wgpu::PipelineCacheDescriptor;
109/// # let adapter_info = todo!();
110/// # let device: wgpu::Device = todo!();
111/// let cache_dir: PathBuf = unimplemented!("Some reasonable platform-specific cache directory for your app.");
112/// let filename = wgpu::util::pipeline_cache_key(&adapter_info);
113/// let (pipeline_cache, cache_file) = if let Some(filename) = filename {
114///     let cache_path = cache_dir.join(&filename);
115///     // If we failed to read the cache, for whatever reason, treat the data as lost.
116///     // In a real app, we'd probably avoid caching entirely unless the error was "file not found".
117///     let cache_data = std::fs::read(&cache_path).ok();
118///     let pipeline_cache = unsafe {
119///         device.create_pipeline_cache(&PipelineCacheDescriptor {
120///             data: cache_data.as_deref(),
121///             label: None,
122///             fallback: true
123///         })
124///     };
125///     (Some(pipeline_cache), Some(cache_path))
126/// } else {
127///     (None, None)
128/// };
129///
130/// // Run pipeline initialisation, making sure to set the `cache`
131/// // fields of your `*PipelineDescriptor` to `pipeline_cache`
132///
133/// // And then save the resulting cache (probably off the main thread).
134/// if let (Some(pipeline_cache), Some(cache_file)) = (pipeline_cache, cache_file) {
135///     let data = pipeline_cache.get_data();
136///     if let Some(data) = data {
137///         let temp_file = cache_file.with_extension("temp");
138///         std::fs::write(&temp_file, &data)?;
139///         std::fs::rename(&temp_file, &cache_file)?;
140///     }
141/// }
142/// # Ok::<_, std::io::Error>(())
143/// ```
144///
145/// [`PipelineCache`]: super::PipelineCache
146pub fn pipeline_cache_key(adapter_info: &wgt::AdapterInfo) -> Option<String> {
147    match adapter_info.backend {
148        wgt::Backend::Vulkan => Some(format!(
149            // The vendor/device should uniquely define a driver
150            // We/the driver will also later validate that the vendor/device and driver
151            // version match, which may lead to clearing an outdated
152            // cache for the same device.
153            "wgpu_pipeline_cache_vulkan_{}_{}",
154            adapter_info.vendor, adapter_info.device
155        )),
156        _ => None,
157    }
158}
159
160/// Adds extra conversion functions to `TextureFormat`.
161pub trait TextureFormatExt {
162    /// Finds the [`TextureFormat`](wgt::TextureFormat) corresponding to the given
163    /// [`StorageFormat`](wgc::naga::StorageFormat).
164    ///
165    /// # Examples
166    /// ```
167    /// use wgpu::util::TextureFormatExt;
168    /// assert_eq!(wgpu::TextureFormat::from_storage_format(wgpu::naga::StorageFormat::Bgra8Unorm), wgpu::TextureFormat::Bgra8Unorm);
169    /// ```
170    #[cfg(wgpu_core)]
171    fn from_storage_format(storage_format: crate::naga::StorageFormat) -> Self;
172
173    /// Finds the [`StorageFormat`](wgc::naga::StorageFormat) corresponding to the given [`TextureFormat`](wgt::TextureFormat).
174    /// Returns `None` if there is no matching storage format,
175    /// which typically indicates this format is not supported
176    /// for storage textures.
177    ///
178    /// # Examples
179    /// ```
180    /// use wgpu::util::TextureFormatExt;
181    /// assert_eq!(wgpu::TextureFormat::Bgra8Unorm.to_storage_format(), Some(wgpu::naga::StorageFormat::Bgra8Unorm));
182    /// ```
183    #[cfg(wgpu_core)]
184    fn to_storage_format(&self) -> Option<crate::naga::StorageFormat>;
185}
186
187impl TextureFormatExt for wgt::TextureFormat {
188    #[cfg(wgpu_core)]
189    fn from_storage_format(storage_format: crate::naga::StorageFormat) -> Self {
190        wgc::map_storage_format_from_naga(storage_format)
191    }
192
193    #[cfg(wgpu_core)]
194    fn to_storage_format(&self) -> Option<crate::naga::StorageFormat> {
195        wgc::map_storage_format_to_naga(*self)
196    }
197}