Skip to main content

spatialrust_gpu/
upload_cache.rs

1//! Reusable wgpu storage-buffer pool for host→device uploads.
2
3use std::sync::Mutex;
4
5use bytemuck::Pod;
6use spatialrust_core::SpatialResult;
7
8use crate::resource_cache::{GpuResourcePoolStats, ResourceCache, DEFAULT_GPU_POOL_BUDGET_BYTES};
9use crate::runtime::WgpuRuntime;
10
11/// Reusable GPU storage buffers keyed by byte length.
12///
13/// Buffers are recycled through [`WgpuRuntime::recycle_storage`] or
14/// [`GpuBufferPool::recycle`]. Prefer the runtime helpers for typical use;
15/// access the pool directly when implementing custom kernels. Use each pool with
16/// one runtime/device only. Recycle only after submitting every encoder using
17/// the buffer and relinquishing all other handles to it. New acquisitions are
18/// uninitialized: kernels must overwrite or explicitly clear what they read.
19///
20/// Retention defaults to 64 MiB with at most eight buffers per size. This budget
21/// does not limit live allocations. Full pools drop incoming buffers; reducing
22/// the budget below current retention clears the cache.
23#[derive(Debug)]
24pub struct GpuBufferPool {
25    free: Mutex<ResourceCache<u64, wgpu::Buffer>>,
26}
27
28impl Default for GpuBufferPool {
29    fn default() -> Self {
30        Self::with_budget(DEFAULT_GPU_POOL_BUDGET_BYTES)
31    }
32}
33
34impl GpuBufferPool {
35    /// Creates a pool with a retained-byte budget; zero disables retention.
36    #[must_use]
37    pub fn with_budget(budget_bytes: u64) -> Self {
38        Self { free: Mutex::new(ResourceCache::new(budget_bytes)) }
39    }
40
41    /// Changes the retention budget, clearing cached buffers if needed.
42    pub fn set_budget(&self, budget_bytes: u64) {
43        if let Ok(mut free) = self.free.lock() {
44            free.set_budget(budget_bytes);
45        }
46    }
47
48    /// Returns retained bytes/resources and lifetime allocation/reuse counters.
49    #[must_use]
50    pub fn stats(&self) -> GpuResourcePoolStats {
51        self.free.lock().map(|free| free.stats()).unwrap_or_default()
52    }
53
54    /// Acquires an uninitialized reusable storage buffer of the requested size.
55    pub fn acquire_storage(
56        &self,
57        runtime: &WgpuRuntime,
58        label: &'static str,
59        byte_len: u64,
60    ) -> wgpu::Buffer {
61        self.take_storage(runtime, label, byte_len)
62    }
63
64    /// Uploads a POD slice into a pooled storage buffer.
65    pub fn upload_pod_storage<T: Pod>(
66        &self,
67        runtime: &WgpuRuntime,
68        label: &'static str,
69        data: &[T],
70    ) -> SpatialResult<wgpu::Buffer> {
71        let byte_len = std::mem::size_of_val(data) as u64;
72        let buffer = self.take_storage(runtime, label, byte_len);
73        runtime.queue().write_buffer(&buffer, 0, bytemuck::cast_slice(data));
74        Ok(buffer)
75    }
76
77    /// Uploads `f32` values into a pooled storage buffer.
78    pub fn upload_f32_storage(
79        &self,
80        runtime: &WgpuRuntime,
81        label: &'static str,
82        data: &[f32],
83    ) -> SpatialResult<wgpu::Buffer> {
84        self.upload_pod_storage(runtime, label, data)
85    }
86
87    /// Uploads `u32` values into a pooled storage buffer.
88    pub fn upload_u32_storage(
89        &self,
90        runtime: &WgpuRuntime,
91        label: &'static str,
92        data: &[u32],
93    ) -> SpatialResult<wgpu::Buffer> {
94        self.upload_pod_storage(runtime, label, data)
95    }
96
97    /// Returns a storage buffer after all users have submitted their work.
98    ///
99    /// Buffers with a mismatched size or incompatible usage are discarded.
100    /// The caller must relinquish every other handle and use this pool only
101    /// with the runtime/device that created the buffer.
102    pub fn recycle(&self, byte_len: u64, buffer: wgpu::Buffer) {
103        if let Ok(mut free) = self.free.lock() {
104            if buffer.size() != byte_len || !buffer.usage().contains(storage_usage()) {
105                free.record_discard();
106                return;
107            }
108            free.put(byte_len, byte_len, buffer);
109        }
110    }
111
112    /// Drops cached handles while preserving lifetime counters and the budget.
113    /// Actual device memory release follows wgpu's outstanding-work lifetimes.
114    pub fn clear(&self) {
115        if let Ok(mut free) = self.free.lock() {
116            free.clear();
117        }
118    }
119
120    /// Returns the number of buffers currently held in the pool.
121    #[must_use]
122    pub fn cached_buffer_count(&self) -> usize {
123        self.stats().cached_resources
124    }
125
126    fn take_storage(
127        &self,
128        runtime: &WgpuRuntime,
129        label: &'static str,
130        byte_len: u64,
131    ) -> wgpu::Buffer {
132        if let Ok(mut free) = self.free.lock() {
133            if byte_len != 0 {
134                if let Some(buffer) = free.take(&byte_len) {
135                    return buffer;
136                }
137            }
138            free.record_allocation();
139        }
140        runtime.device().create_buffer(&wgpu::BufferDescriptor {
141            label: Some(label),
142            size: if byte_len == 0 { 4 } else { byte_len },
143            usage: storage_usage(),
144            mapped_at_creation: false,
145        })
146    }
147}
148
149fn storage_usage() -> wgpu::BufferUsages {
150    wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC
151}
152
153#[cfg(all(feature = "gpu-wgpu", test))]
154mod tests {
155    use super::GpuBufferPool;
156    use crate::runtime::WgpuRuntime;
157
158    #[test]
159    fn buffer_pool_reuses_equal_sized_buffers() {
160        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
161        let pool = GpuBufferPool::default();
162        let data = [1.0_f32, 2.0, 3.0];
163
164        let first =
165            pool.upload_f32_storage(&runtime, "upload-pool-test", &data).expect("first upload");
166        assert_eq!(pool.cached_buffer_count(), 0);
167        pool.recycle(first.size(), first);
168        assert_eq!(pool.cached_buffer_count(), 1);
169
170        let second =
171            pool.upload_f32_storage(&runtime, "upload-pool-test", &data).expect("second upload");
172        assert_eq!(second.size(), (data.len() * std::mem::size_of::<f32>()) as u64);
173        assert_eq!(pool.cached_buffer_count(), 0);
174    }
175
176    #[test]
177    fn runtime_buffer_pool_matches_direct_upload() {
178        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
179        let data = [4.0_f32, 5.0];
180        let buffer = runtime.upload_f32_storage("runtime-pool-test", &data).expect("upload");
181        runtime.recycle_storage(buffer.size(), buffer);
182        assert_eq!(runtime.buffer_pool().cached_buffer_count(), 1);
183        runtime.buffer_pool().clear();
184        assert_eq!(runtime.buffer_pool().cached_buffer_count(), 0);
185    }
186
187    #[test]
188    fn pool_budget_rejects_incompatible_buffers_and_preserves_live_buffers() {
189        let runtime = WgpuRuntime::new_headless().unwrap();
190        let pool = GpuBufferPool::with_budget(8);
191        let live = pool.acquire_storage(&runtime, "live", 8);
192        let extra = pool.acquire_storage(&runtime, "extra", 8);
193        pool.recycle(extra.size(), extra);
194        assert_eq!(pool.stats().cached_bytes, 8);
195        let mismatched = pool.acquire_storage(&runtime, "mismatched", 4);
196        pool.recycle(8, mismatched);
197        let incompatible = runtime.device().create_buffer(&wgpu::BufferDescriptor {
198            label: None,
199            size: 4,
200            usage: wgpu::BufferUsages::STORAGE,
201            mapped_at_creation: false,
202        });
203        pool.recycle(4, incompatible);
204        assert_eq!(pool.stats().discarded_count, 2);
205        pool.set_budget(0);
206        assert_eq!(pool.stats().cached_bytes, 0);
207        runtime.queue().write_buffer(&live, 0, bytemuck::cast_slice(&[1_u32, 2]));
208        runtime.wait_idle();
209        pool.recycle(live.size(), live);
210        assert_eq!(pool.stats().cached_resources, 0);
211        assert_eq!(pool.stats().allocation_count, 3);
212        assert_eq!(pool.stats().discarded_count, 4);
213    }
214}