Skip to main content

wde_wgpu/resources/
memory.rs

1//! Tracking of the GPU memory of the [`Buffer`](crate::buffer::Buffer)s and [`Texture`](crate::texture::Texture)s
2//! (see [`GpuMemory`]).
3//!
4//! Sizes are estimated from the descriptors of the resources: the alignment, padding and compression of the driver
5//! are not counted.
6
7use std::{
8    collections::HashMap,
9    sync::{LazyLock, Mutex, MutexGuard}
10};
11
12use wgpu::{BufferUsages, TextureFormat, TextureUsages};
13
14/// Category of a tracked GPU resource, deduced from its usages.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
16pub enum GpuMemoryCategory {
17    /// Textures only sampled or copied, such as the loaded images.
18    SampledTexture,
19    RenderTarget,
20    DepthStencil,
21    StorageTexture,
22    VertexBuffer,
23    IndexBuffer,
24    IndirectBuffer,
25    StorageBuffer,
26    UniformBuffer,
27    /// Buffers mapped by the CPU, for uploads and readbacks.
28    StagingBuffer,
29    OtherBuffer
30}
31impl GpuMemoryCategory {
32    pub const ALL: [Self; 11] = [
33        Self::SampledTexture,
34        Self::RenderTarget,
35        Self::DepthStencil,
36        Self::StorageTexture,
37        Self::VertexBuffer,
38        Self::IndexBuffer,
39        Self::IndirectBuffer,
40        Self::StorageBuffer,
41        Self::UniformBuffer,
42        Self::StagingBuffer,
43        Self::OtherBuffer
44    ];
45
46    pub fn of_texture(format: TextureFormat, usage: TextureUsages) -> Self {
47        if format.has_depth_aspect() || format.has_stencil_aspect() {
48            Self::DepthStencil
49        } else if usage.contains(TextureUsages::RENDER_ATTACHMENT) {
50            Self::RenderTarget
51        } else if usage.contains(TextureUsages::STORAGE_BINDING) {
52            Self::StorageTexture
53        } else {
54            Self::SampledTexture
55        }
56    }
57
58    pub fn of_buffer(usage: BufferUsages) -> Self {
59        if usage.intersects(BufferUsages::MAP_READ | BufferUsages::MAP_WRITE) {
60            Self::StagingBuffer
61        } else if usage.contains(BufferUsages::INDIRECT) {
62            Self::IndirectBuffer
63        } else if usage.contains(BufferUsages::VERTEX) {
64            Self::VertexBuffer
65        } else if usage.contains(BufferUsages::INDEX) {
66            Self::IndexBuffer
67        } else if usage.contains(BufferUsages::STORAGE) {
68            Self::StorageBuffer
69        } else if usage.contains(BufferUsages::UNIFORM) {
70            Self::UniformBuffer
71        } else {
72            Self::OtherBuffer
73        }
74    }
75
76    pub fn is_texture(self) -> bool {
77        matches!(
78            self,
79            Self::SampledTexture | Self::RenderTarget | Self::DepthStencil | Self::StorageTexture
80        )
81    }
82
83    pub fn label(self) -> &'static str {
84        match self {
85            Self::SampledTexture => "Sampled",
86            Self::RenderTarget => "Render targets",
87            Self::DepthStencil => "Depth / stencil",
88            Self::StorageTexture => "Storage",
89            Self::VertexBuffer => "Vertex",
90            Self::IndexBuffer => "Index",
91            Self::IndirectBuffer => "Indirect",
92            Self::StorageBuffer => "Storage",
93            Self::UniformBuffer => "Uniform",
94            Self::StagingBuffer => "Staging",
95            Self::OtherBuffer => "Other"
96        }
97    }
98}
99
100/// A live tracked GPU resource.
101#[derive(Clone, Debug)]
102pub struct GpuAllocationInfo {
103    pub label: String,
104    pub category: GpuMemoryCategory,
105    pub bytes: u64,
106    /// Size, format, layers, mips and samples of textures, empty for buffers.
107    pub description: String
108}
109
110#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
111pub struct GpuMemoryTotal {
112    pub count: usize,
113    pub bytes: u64
114}
115
116#[derive(Default)]
117struct Registry {
118    next_id: u64,
119    allocations: HashMap<u64, GpuAllocationInfo>,
120    totals: HashMap<GpuMemoryCategory, GpuMemoryTotal>
121}
122static REGISTRY: LazyLock<Mutex<Registry>> = LazyLock::new(Default::default);
123fn registry() -> MutexGuard<'static, Registry> {
124    REGISTRY.lock().unwrap_or_else(|e| e.into_inner())
125}
126
127/// A tracked GPU resource, untracked when dropped. Keep it next to the resource.
128#[derive(Debug)]
129pub struct GpuAllocation(u64);
130impl GpuAllocation {
131    pub fn track(info: GpuAllocationInfo) -> Self {
132        let mut registry = registry();
133        let id = registry.next_id;
134        registry.next_id += 1;
135        let total = registry.totals.entry(info.category).or_default();
136        total.count += 1;
137        total.bytes += info.bytes;
138        registry.allocations.insert(id, info);
139        Self(id)
140    }
141
142    pub fn buffer(label: &str, buffer: &wgpu::Buffer) -> Self {
143        Self::track(GpuAllocationInfo {
144            label: label.to_string(),
145            category: GpuMemoryCategory::of_buffer(buffer.usage()),
146            bytes: buffer.size(),
147            description: String::new()
148        })
149    }
150
151    pub fn texture(label: &str, texture: &wgpu::Texture) -> Self {
152        let size = texture.size();
153        let (format, layers, mips, samples) = (
154            texture.format(),
155            size.depth_or_array_layers,
156            texture.mip_level_count(),
157            texture.sample_count()
158        );
159        let mut description = format!("{}x{} {format:?}", size.width, size.height);
160        for (count, unit) in [(layers, " layers"), (mips, " mips"), (samples, "x MSAA")] {
161            if count > 1 {
162                description += &format!(", {count}{unit}");
163            }
164        }
165        Self::track(GpuAllocationInfo {
166            label: label.to_string(),
167            category: GpuMemoryCategory::of_texture(format, texture.usage()),
168            bytes: texture_bytes(format, (size.width, size.height), layers, mips, samples),
169            description
170        })
171    }
172}
173impl GpuAllocation {
174    /// Overrides the category deduced from the usages.
175    pub fn set_category(&self, category: GpuMemoryCategory) {
176        let mut registry = registry();
177        let Some(info) = registry.allocations.get_mut(&self.0) else {
178            return;
179        };
180        let (previous, bytes) = (std::mem::replace(&mut info.category, category), info.bytes);
181        if previous == category {
182            return;
183        }
184        if let Some(total) = registry.totals.get_mut(&previous) {
185            total.count -= 1;
186            total.bytes -= bytes;
187        }
188        let total = registry.totals.entry(category).or_default();
189        total.count += 1;
190        total.bytes += bytes;
191    }
192}
193impl Drop for GpuAllocation {
194    fn drop(&mut self) {
195        let mut registry = registry();
196        let Some(info) = registry.allocations.remove(&self.0) else {
197            return;
198        };
199        if let Some(total) = registry.totals.get_mut(&info.category) {
200            total.count -= 1;
201            total.bytes -= info.bytes;
202        }
203    }
204}
205
206/// GPU memory of the live [`Buffer`](crate::buffer::Buffer)s and [`Texture`](crate::texture::Texture)s, shared
207/// by the whole process. Resources created directly with `wgpu` are only counted if they hold a [`GpuAllocation`].
208pub struct GpuMemory;
209impl GpuMemory {
210    /// Totals of every category, in the order of [`GpuMemoryCategory::ALL`].
211    pub fn totals() -> Vec<(GpuMemoryCategory, GpuMemoryTotal)> {
212        let registry = registry();
213        GpuMemoryCategory::ALL
214            .iter()
215            .map(|c| (*c, registry.totals.get(c).copied().unwrap_or_default()))
216            .collect()
217    }
218
219    pub fn allocations() -> Vec<GpuAllocationInfo> {
220        registry().allocations.values().cloned().collect()
221    }
222}
223
224/// Estimated size in bytes of a 2D texture with all its mips, layers and samples.
225pub fn texture_bytes(
226    format: TextureFormat,
227    size: (u32, u32),
228    layers: u32,
229    mips: u32,
230    samples: u32
231) -> u64 {
232    let (block_width, block_height) = format.block_dimensions();
233    let block_bytes = match format {
234        TextureFormat::Depth24Plus | TextureFormat::Depth24PlusStencil8 => 4,
235        TextureFormat::Depth32FloatStencil8 => 8,
236        f => f.block_copy_size(None).unwrap_or(4)
237    } as u64;
238    let layer_bytes: u64 = (0..mips.max(1))
239        .map(|mip| {
240            let width = (size.0 >> mip).max(1).div_ceil(block_width) as u64;
241            let height = (size.1 >> mip).max(1).div_ceil(block_height) as u64;
242            width * height * block_bytes
243        })
244        .sum();
245    layer_bytes * layers.max(1) as u64 * samples.max(1) as u64
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn texture_sizes() {
254        assert_eq!(
255            texture_bytes(TextureFormat::Rgba8Unorm, (256, 256), 1, 1, 1),
256            262_144
257        );
258        // 256² + 128² + ... + 1² texels
259        assert_eq!(
260            texture_bytes(TextureFormat::R8Unorm, (256, 256), 1, 9, 1),
261            87_381
262        );
263        assert_eq!(
264            texture_bytes(TextureFormat::Bc7RgbaUnorm, (256, 256), 1, 1, 1),
265            65_536
266        );
267        assert_eq!(
268            texture_bytes(TextureFormat::Bc1RgbaUnorm, (2, 2), 1, 1, 1),
269            8
270        );
271        assert_eq!(
272            texture_bytes(TextureFormat::Depth32Float, (16, 16), 6, 1, 4),
273            24_576
274        );
275    }
276
277    #[test]
278    fn tracking() {
279        let total = || {
280            GpuMemory::totals()
281                .into_iter()
282                .find(|(c, _)| *c == GpuMemoryCategory::OtherBuffer)
283                .unwrap()
284                .1
285        };
286        let info = |bytes| GpuAllocationInfo {
287            label: "test".to_string(),
288            category: GpuMemoryCategory::OtherBuffer,
289            bytes,
290            description: String::new()
291        };
292        let before = total();
293        let a = GpuAllocation::track(info(100));
294        let b = GpuAllocation::track(info(20));
295        assert_eq!(total().bytes, before.bytes + 120);
296        drop(a);
297        assert_eq!(total().count, before.count + 1);
298        b.set_category(GpuMemoryCategory::StagingBuffer);
299        assert_eq!(total().count, before.count);
300        drop(b);
301        assert_eq!(total(), before);
302    }
303
304    #[test]
305    fn categories() {
306        use GpuMemoryCategory as C;
307        let texture = |format, usage| C::of_texture(format, usage);
308        assert_eq!(
309            texture(
310                TextureFormat::Depth32Float,
311                TextureUsages::RENDER_ATTACHMENT
312            ),
313            C::DepthStencil
314        );
315        assert_eq!(
316            texture(TextureFormat::Rgba16Float, TextureUsages::RENDER_ATTACHMENT),
317            C::RenderTarget
318        );
319        assert_eq!(
320            C::of_buffer(BufferUsages::STORAGE | BufferUsages::INDIRECT),
321            C::IndirectBuffer
322        );
323        assert_eq!(
324            C::of_buffer(BufferUsages::COPY_DST | BufferUsages::MAP_READ),
325            C::StagingBuffer
326        );
327    }
328}