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        self.mapped_range.slice()
88    }
89}
90
91/// A recommended key for storing [`PipelineCache`]s for the adapter
92/// associated with the given [`AdapterInfo`](wgt::AdapterInfo)
93/// This key will define a class of adapters for which the same cache
94/// might be valid.
95///
96/// If this returns `None`, the adapter doesn't support [`PipelineCache`].
97/// This may be because the API doesn't support application managed caches
98/// (such as browser WebGPU), or that `wgpu` hasn't implemented it for
99/// that API yet.
100///
101/// This key could be used as a filename, as seen in the example below.
102///
103/// # Examples
104///
105/// ```no_run
106/// # use std::path::PathBuf;
107/// use wgpu::PipelineCacheDescriptor;
108/// # let adapter_info = todo!();
109/// # let device: wgpu::Device = todo!();
110/// let cache_dir: PathBuf = unimplemented!("Some reasonable platform-specific cache directory for your app.");
111/// let filename = wgpu::util::pipeline_cache_key(&adapter_info);
112/// let (pipeline_cache, cache_file) = if let Some(filename) = filename {
113///     let cache_path = cache_dir.join(&filename);
114///     // If we failed to read the cache, for whatever reason, treat the data as lost.
115///     // In a real app, we'd probably avoid caching entirely unless the error was "file not found".
116///     let cache_data = std::fs::read(&cache_path).ok();
117///     let pipeline_cache = unsafe {
118///         device.create_pipeline_cache(&PipelineCacheDescriptor {
119///             data: cache_data.as_deref(),
120///             label: None,
121///             fallback: true
122///         })
123///     };
124///     (Some(pipeline_cache), Some(cache_path))
125/// } else {
126///     (None, None)
127/// };
128///
129/// // Run pipeline initialisation, making sure to set the `cache`
130/// // fields of your `*PipelineDescriptor` to `pipeline_cache`
131///
132/// // And then save the resulting cache (probably off the main thread).
133/// if let (Some(pipeline_cache), Some(cache_file)) = (pipeline_cache, cache_file) {
134///     let data = pipeline_cache.get_data();
135///     if let Some(data) = data {
136///         let temp_file = cache_file.with_extension("temp");
137///         std::fs::write(&temp_file, &data)?;
138///         std::fs::rename(&temp_file, &cache_file)?;
139///     }
140/// }
141/// # Ok::<_, std::io::Error>(())
142/// ```
143///
144/// [`PipelineCache`]: super::PipelineCache
145pub fn pipeline_cache_key(adapter_info: &wgt::AdapterInfo) -> Option<String> {
146    match adapter_info.backend {
147        wgt::Backend::Vulkan => Some(format!(
148            // The vendor/device should uniquely define a driver
149            // We/the driver will also later validate that the vendor/device and driver
150            // version match, which may lead to clearing an outdated
151            // cache for the same device.
152            "wgpu_pipeline_cache_vulkan_{}_{}",
153            adapter_info.vendor, adapter_info.device
154        )),
155        _ => None,
156    }
157}
158
159/// Adds extra conversion functions to `TextureFormat`.
160pub trait TextureFormatExt {
161    /// Finds the [`TextureFormat`](wgt::TextureFormat) corresponding to the given
162    /// [`StorageFormat`](wgc::naga::StorageFormat).
163    ///
164    /// # Examples
165    /// ```
166    /// use wgpu::util::TextureFormatExt;
167    /// assert_eq!(wgpu::TextureFormat::from_storage_format(wgpu::naga::StorageFormat::Bgra8Unorm), wgpu::TextureFormat::Bgra8Unorm);
168    /// ```
169    #[cfg(wgpu_core)]
170    fn from_storage_format(storage_format: crate::naga::StorageFormat) -> Self;
171
172    /// Finds the [`StorageFormat`](wgc::naga::StorageFormat) corresponding to the given [`TextureFormat`](wgt::TextureFormat).
173    /// Returns `None` if there is no matching storage format,
174    /// which typically indicates this format is not supported
175    /// for storage textures.
176    ///
177    /// # Examples
178    /// ```
179    /// use wgpu::util::TextureFormatExt;
180    /// assert_eq!(wgpu::TextureFormat::Bgra8Unorm.to_storage_format(), Some(wgpu::naga::StorageFormat::Bgra8Unorm));
181    /// ```
182    #[cfg(wgpu_core)]
183    fn to_storage_format(&self) -> Option<crate::naga::StorageFormat>;
184}
185
186impl TextureFormatExt for wgt::TextureFormat {
187    #[cfg(wgpu_core)]
188    fn from_storage_format(storage_format: crate::naga::StorageFormat) -> Self {
189        wgc::map_storage_format_from_naga(storage_format)
190    }
191
192    #[cfg(wgpu_core)]
193    fn to_storage_format(&self) -> Option<crate::naga::StorageFormat> {
194        wgc::map_storage_format_to_naga(*self)
195    }
196}