Skip to main content

alpha2_render/
uniform.rs

1use std::collections::HashMap;
2use std::num::NonZeroU64;
3use std::sync::Mutex;
4
5use crate::retire::{Retired, Retirement};
6use crate::{RenderError, Shared};
7
8/// Bytes per effect parameter in `EffectParams`; every type pads to one 16-byte slot.
9pub(crate) const PARAM_SLOT_BYTES: usize = 16;
10
11/// Bytes of an effect's parameter uniform: one slot per parameter, minimum one since a uniform
12/// cannot be empty. Shared by the graph reservation and the pass write.
13pub(crate) const fn param_uniform_bytes(count: usize) -> usize {
14    let slots = if count == 0 { 1 } else { count };
15    slots.saturating_mul(PARAM_SLOT_BYTES)
16}
17
18/// 32-bit words of the runtime uniform: two `vec4f` of values, then a `vec4u` with the ticks.
19pub(crate) const RUNTIME_UNIFORM_WORDS: usize = 12;
20
21/// Floats in composite.wesl's `BatchParams`: three `vec4f` of controls, then four per layer.
22pub(crate) const BATCH_UNIFORM_FLOATS: usize = 12 + 16 * crate::composite::COMPOSITE_BATCH_LAYERS;
23
24pub(crate) const fn float_uniform_bytes(values: usize) -> u64 {
25    (values * size_of::<f32>()) as u64
26}
27
28// Bounds on what an unusual frame can leave idle; normal frames stay within one capacity's peak.
29const MAX_IDLE_UNIFORM_BUFFERS: usize = 64;
30const MAX_IDLE_UNIFORM_BYTES: u64 = 4 * 1024 * 1024;
31
32/// Allocation and retention counters for submission-scoped uniform arenas.
33#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
34pub struct UniformBufferPoolStats {
35    /// Physical buffers created since renderer construction.
36    pub created: u64,
37    /// Graph executions served by an idle buffer.
38    pub reused: u64,
39    /// Buffers dropped instead of retained, including failed graph encodes.
40    pub discarded: u64,
41    /// Arenas currently being encoded or awaiting submission.
42    pub active: usize,
43    /// Bytes currently owned by active arenas.
44    pub active_bytes: u64,
45    /// Maximum active bytes observed since renderer construction.
46    pub high_water_bytes: u64,
47    /// Unmapped buffers currently available for reuse.
48    pub available: usize,
49    /// Bytes retained by idle reusable buffers.
50    pub available_bytes: u64,
51}
52
53#[derive(Debug)]
54pub(crate) struct UniformBufferPool {
55    alignment: u64,
56    state: Mutex<UniformBufferPoolState>,
57    retirement: Shared<Retirement>,
58}
59
60#[derive(Debug, Default)]
61struct UniformBufferPoolState {
62    /// Oldest release first: capacity, buffer, bytes, creation generation.
63    available: Vec<(u64, wgpu::Buffer, Vec<u8>, u64)>,
64    /// Generation whose untrusted idle buffers were last dropped.
65    checked_generation: u64,
66    active_by_capacity: HashMap<u64, usize>,
67    peak_active_by_capacity: HashMap<u64, usize>,
68    created: u64,
69    reused: u64,
70    discarded: u64,
71    active: usize,
72    active_bytes: u64,
73    high_water_bytes: u64,
74    available_bytes: u64,
75}
76
77#[derive(Debug)]
78pub(crate) struct UniformArenaLease {
79    pool: Shared<UniformBufferPool>,
80    buffer: Option<wgpu::Buffer>,
81    capacity: u64,
82    alignment: u64,
83    cursor: u64,
84    bytes: Vec<u8>,
85    generation: u64,
86}
87
88#[derive(Copy, Clone, Debug)]
89pub(crate) struct UniformSlice {
90    offset: u64,
91    size: NonZeroU64,
92}
93
94impl UniformSlice {
95    /// Offset in the arena, a multiple of the device's uniform offset alignment.
96    pub(crate) const fn offset(self) -> u64 {
97        self.offset
98    }
99
100    pub(crate) fn dynamic_offset(self) -> u32 {
101        u32::try_from(self.offset).expect("a uniform arena is smaller than 4 GiB")
102    }
103
104    pub(crate) const fn size(self) -> NonZeroU64 {
105        self.size
106    }
107}
108
109impl UniformBufferPool {
110    pub(crate) fn new(alignment: u64, retirement: Shared<Retirement>) -> Self {
111        Self {
112            alignment: alignment.max(1),
113            state: Mutex::default(),
114            retirement,
115        }
116    }
117
118    /// Leases an arena of at least `capacity` bytes, rounded up to a power of two so similar graphs
119    /// share arenas.
120    pub(crate) fn acquire(
121        self: &Shared<Self>,
122        device: &wgpu::Device,
123        capacity: u64,
124    ) -> UniformArenaLease {
125        let alignment = self.alignment;
126        let capacity = align_up(capacity.max(1), alignment)
127            .checked_next_power_of_two()
128            .unwrap_or(u64::MAX);
129        let reused = {
130            let mut state = self
131                .state
132                .lock()
133                .unwrap_or_else(std::sync::PoisonError::into_inner);
134            let untrusted = self.drop_untrusted(&mut state);
135            let index = state
136                .available
137                .iter()
138                .position(|(available_capacity, _, _, _)| *available_capacity == capacity);
139            let reused = index.map(|index| {
140                state.reused = state.reused.saturating_add(1);
141                state.available_bytes = state.available_bytes.saturating_sub(capacity);
142                let (_, buffer, bytes, generation) = state.available.remove(index);
143                (buffer, bytes, generation)
144            });
145            drop(state);
146            self.retirement.retire(untrusted);
147            reused
148        };
149        let (buffer, bytes, generation) = reused.unwrap_or_else(|| {
150            let mut state = self
151                .state
152                .lock()
153                .unwrap_or_else(std::sync::PoisonError::into_inner);
154            state.created = state.created.saturating_add(1);
155            drop(state);
156            let generation = self.retirement.generation();
157            let buffer = device.create_buffer(&wgpu::BufferDescriptor {
158                label: Some("alpha2 uniform arena"),
159                size: capacity,
160                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
161                mapped_at_creation: false,
162            });
163            self.retirement.bind_groups.adopt_buffer(&buffer);
164            (
165                buffer,
166                vec![0; usize::try_from(capacity).expect("uniform arena fits host indexing")],
167                generation,
168            )
169        });
170        {
171            let mut state = self
172                .state
173                .lock()
174                .unwrap_or_else(std::sync::PoisonError::into_inner);
175            state.active = state.active.saturating_add(1);
176            state.active_bytes = state.active_bytes.saturating_add(capacity);
177            state.high_water_bytes = state.high_water_bytes.max(state.active_bytes);
178            let active = state.active_by_capacity.entry(capacity).or_default();
179            *active = active.saturating_add(1);
180            let active = *active;
181            let peak = state.peak_active_by_capacity.entry(capacity).or_default();
182            *peak = (*peak).max(active);
183        }
184        UniformArenaLease {
185            pool: Shared::clone(self),
186            buffer: Some(buffer),
187            capacity,
188            alignment,
189            cursor: 0,
190            bytes,
191            generation,
192        }
193    }
194
195    /// Removes idle arenas created before the last reported GPU error, once per report.
196    fn drop_untrusted(&self, state: &mut UniformBufferPoolState) -> Vec<(Retired, u64)> {
197        let generation = self.retirement.generation();
198        if state.checked_generation == generation {
199            return Vec::new();
200        }
201        state.checked_generation = generation;
202        let (kept, untrusted): (Vec<_>, Vec<_>) = std::mem::take(&mut state.available)
203            .into_iter()
204            .partition(|(_, _, _, created)| *created == generation);
205        state.available = kept;
206        state.available_bytes = state
207            .available
208            .iter()
209            .map(|(capacity, _, _, _)| *capacity)
210            .sum();
211        state.discarded = state
212            .discarded
213            .saturating_add(u64::try_from(untrusted.len()).unwrap_or(u64::MAX));
214        untrusted
215            .into_iter()
216            .map(|(capacity, buffer, _, _)| {
217                prune_capacity(state, capacity);
218                (Retired::Buffer(buffer), capacity)
219            })
220            .collect()
221    }
222
223    /// Destroys every idle uniform buffer.
224    pub(crate) fn clear(&self) {
225        let mut state = self
226            .state
227            .lock()
228            .unwrap_or_else(std::sync::PoisonError::into_inner);
229        let discarded = u64::try_from(state.available.len()).unwrap_or(u64::MAX);
230        let idle = std::mem::take(&mut state.available);
231        state.discarded = state.discarded.saturating_add(discarded);
232        state.available_bytes = 0;
233        drop(state);
234        self.retirement.retire(
235            idle.into_iter()
236                .map(|(capacity, buffer, _, _)| (Retired::Buffer(buffer), capacity)),
237        );
238    }
239
240    pub(crate) fn stats(&self) -> UniformBufferPoolStats {
241        let state = self
242            .state
243            .lock()
244            .unwrap_or_else(std::sync::PoisonError::into_inner);
245        UniformBufferPoolStats {
246            created: state.created,
247            reused: state.reused,
248            discarded: state.discarded,
249            active: state.active,
250            active_bytes: state.active_bytes,
251            high_water_bytes: state.high_water_bytes,
252            available: state.available.len(),
253            available_bytes: state.available_bytes,
254        }
255    }
256
257    /// Keeps a finished arena while its capacity has fewer idle arenas than its peak in use, within
258    /// the idle bounds (oldest evicted first); otherwise destroys it.
259    fn release(&self, capacity: u64, buffer: wgpu::Buffer, bytes: Vec<u8>, generation: u64) {
260        if !self.retirement.trusts(generation) {
261            self.discard(capacity, buffer);
262            return;
263        }
264        let mut retired = Vec::new();
265        self.keep_or_retire(capacity, buffer, bytes, generation, &mut retired);
266        self.retirement.retire(retired);
267    }
268
269    fn keep_or_retire(
270        &self,
271        capacity: u64,
272        buffer: wgpu::Buffer,
273        bytes: Vec<u8>,
274        generation: u64,
275        retired: &mut Vec<(Retired, u64)>,
276    ) {
277        let mut state = self
278            .state
279            .lock()
280            .unwrap_or_else(std::sync::PoisonError::into_inner);
281        finish_active(&mut state, capacity);
282        let retention_target = state
283            .peak_active_by_capacity
284            .get(&capacity)
285            .copied()
286            .unwrap_or(1);
287        let idle_at_capacity = state
288            .available
289            .iter()
290            .filter(|(available, _, _, _)| *available == capacity)
291            .count();
292        if idle_at_capacity >= retention_target || capacity > MAX_IDLE_UNIFORM_BYTES {
293            state.discarded = state.discarded.saturating_add(1);
294            retired.push((Retired::Buffer(buffer), capacity));
295            return;
296        }
297        while state.available.len() >= MAX_IDLE_UNIFORM_BUFFERS
298            || state.available_bytes.saturating_add(capacity) > MAX_IDLE_UNIFORM_BYTES
299        {
300            let (discarded, discarded_buffer, _bytes, _) = state.available.remove(0);
301            state.available_bytes = state.available_bytes.saturating_sub(discarded);
302            state.discarded = state.discarded.saturating_add(1);
303            prune_capacity(&mut state, discarded);
304            retired.push((Retired::Buffer(discarded_buffer), discarded));
305        }
306        state.available.push((capacity, buffer, bytes, generation));
307        state.available_bytes = state.available_bytes.saturating_add(capacity);
308    }
309
310    /// Takes back an arena whose encode failed or was abandoned.
311    fn discard(&self, capacity: u64, buffer: wgpu::Buffer) {
312        let mut state = self
313            .state
314            .lock()
315            .unwrap_or_else(std::sync::PoisonError::into_inner);
316        finish_active(&mut state, capacity);
317        state.discarded = state.discarded.saturating_add(1);
318        prune_capacity(&mut state, capacity);
319        drop(state);
320        self.retirement
321            .retire([(Retired::Buffer(buffer), capacity)]);
322    }
323}
324
325impl UniformArenaLease {
326    pub(crate) fn write(&mut self, contents: &[u8]) -> Result<UniformSlice, RenderError> {
327        self.write_with(contents.len(), |bytes| {
328            bytes.copy_from_slice(contents);
329            Ok(())
330        })
331    }
332
333    pub(crate) fn write_with(
334        &mut self,
335        size: usize,
336        fill: impl FnOnce(&mut [u8]) -> Result<(), RenderError>,
337    ) -> Result<UniformSlice, RenderError> {
338        let offset = align_up(self.cursor, self.alignment);
339        let end = u64::try_from(size)
340            .ok()
341            .and_then(|size| offset.checked_add(size))
342            .filter(|end| *end <= self.capacity)
343            .ok_or(RenderError::UniformArenaOverrun)?;
344        let size = NonZeroU64::new(end - offset).expect("uniform binding is non-empty");
345        let start = usize::try_from(offset).expect("uniform offset fits host indexing");
346        let end = usize::try_from(end).expect("uniform end fits host indexing");
347        let bytes = &mut self.bytes[start..end];
348        bytes.fill(0);
349        fill(bytes)?;
350        self.cursor = u64::try_from(end).expect("uniform cursor fits u64");
351        Ok(UniformSlice { offset, size })
352    }
353
354    /// The arena's first `size` bytes as a dynamic-offset binding; pass a slice's
355    /// [`UniformSlice::dynamic_offset`] when drawing.
356    pub(crate) fn dynamic_binding(&self, size: NonZeroU64) -> wgpu::BindingResource<'_> {
357        wgpu::BindingResource::Buffer(wgpu::BufferBinding {
358            buffer: self.buffer.as_ref().expect("live uniform arena"),
359            offset: 0,
360            size: Some(size),
361        })
362    }
363
364    #[cfg(test)]
365    pub(crate) fn buffer(&self) -> &wgpu::Buffer {
366        self.buffer.as_ref().expect("live uniform arena")
367    }
368
369    pub(crate) fn flush(&self, queue: &wgpu::Queue) {
370        if self.cursor > 0 {
371            let used = usize::try_from(self.cursor).expect("uniform cursor fits host indexing");
372            queue.write_buffer(
373                self.buffer.as_ref().expect("live uniform arena"),
374                0,
375                &self.bytes[..used],
376            );
377        }
378    }
379
380    pub(crate) fn recycle(mut self) {
381        let buffer = self.buffer.take().expect("live uniform arena");
382        let bytes = std::mem::take(&mut self.bytes);
383        self.pool
384            .release(self.capacity, buffer, bytes, self.generation);
385    }
386}
387
388impl Drop for UniformArenaLease {
389    fn drop(&mut self) {
390        if let Some(buffer) = self.buffer.take() {
391            self.pool.discard(self.capacity, buffer);
392        }
393    }
394}
395
396fn finish_active(state: &mut UniformBufferPoolState, capacity: u64) {
397    state.active = state.active.saturating_sub(1);
398    state.active_bytes = state.active_bytes.saturating_sub(capacity);
399    if let Some(active) = state.active_by_capacity.get_mut(&capacity) {
400        *active = active.saturating_sub(1);
401        if *active == 0 {
402            state.active_by_capacity.remove(&capacity);
403        }
404    }
405}
406
407/// Forgets a capacity's peak once nothing of it is active or idle.
408fn prune_capacity(state: &mut UniformBufferPoolState, capacity: u64) {
409    if !state.active_by_capacity.contains_key(&capacity)
410        && !state
411            .available
412            .iter()
413            .any(|(available, _, _, _)| *available == capacity)
414    {
415        state.peak_active_by_capacity.remove(&capacity);
416    }
417}
418
419pub(crate) const fn aligned_uniform_end(cursor: u64, size: u64, alignment: u64) -> u64 {
420    align_up(cursor, alignment).saturating_add(size)
421}
422
423const fn align_up(value: u64, alignment: u64) -> u64 {
424    value
425        .saturating_add(alignment.saturating_sub(1))
426        .div_euclid(alignment)
427        .saturating_mul(alignment)
428}