Skip to main content

mln_webgpu/
uniform_buffer.rs

1// Ports include/mln/webgpu/uniform_buffer.hpp and src/mln/webgpu/uniform_buffer.cpp
2//
3// `webgpu::UniformBufferArray` only overrides `bind` (a no-op: bind groups
4// are built per drawable in `Drawable::draw`) and `copy`, so the port uses
5// `gfx::UniformBufferArray` directly.
6
7use std::any::Any;
8use std::cell::Cell;
9use std::rc::{Rc, Weak};
10
11use mln_gfx::uniform_buffer;
12
13use crate::context::Context;
14use crate::renderer_backend::BackendImpl;
15
16/// WebGPU's largest allowed `minUniformBufferOffsetAlignment`, so a valid
17/// uniform binding offset on any device.
18pub(crate) const UNIFORM_BUFFER_ALIGNMENT: usize = 256;
19
20const fn aligned_uniform_size(size: usize) -> usize {
21    if size == 0 {
22        return 0;
23    }
24    size.div_ceil(UNIFORM_BUFFER_ALIGNMENT) * UNIFORM_BUFFER_ALIGNMENT
25}
26
27pub struct UniformBuffer {
28    /// The size of the data, which `get_size` reports. The GPU buffer is
29    /// padded to 256 bytes. C++ reports the padded size, so
30    /// `UniformBufferArray::createOrUpdate`, which compares it to the data
31    /// size, creates a new GPU buffer on every update of a UBO whose size
32    /// isn't a multiple of 256 bytes. Reporting the data size updates it in
33    /// place. Bind groups still bind the whole padded buffer, because some
34    /// UBOs hold less data than their shader struct.
35    size: usize,
36    /// C++ keeps `Context&`; only device and queue are used. Holding the
37    /// backend state rather than `Rc<Context>` avoids an Rc cycle through the
38    /// context's global uniform buffer array.
39    backend: Rc<BackendImpl>,
40    /// The context whose stats count this buffer. Weak for the same reason;
41    /// a buffer the context drops has no stats left to update.
42    context: Weak<Context>,
43    /// The GPU buffer, which other uniform buffers may share, and where in it
44    /// this one's padded bytes start.
45    buffer: Option<wgpu::Buffer>,
46    offset: u64,
47    /// The end of the bytes that may not be zeros: an update ending there or
48    /// later can write the padding's zeros with it.
49    written: Cell<usize>,
50}
51
52impl UniformBuffer {
53    /// `UniformBuffer(context, data, size)`; `data == None` is the C++ null
54    /// pointer.
55    pub fn new(context: &Context, data: Option<&[u8]>, size: usize) -> Self {
56        Self::with_backend(context.get_backend().clone(), context.weak(), data, size)
57    }
58
59    fn with_backend(backend: Rc<BackendImpl>, context: Weak<Context>, data: Option<&[u8]>, size: usize) -> Self {
60        let aligned_size = aligned_uniform_size(size);
61        let mut buffer = None;
62        let mut offset = 0;
63        let mut written = 0;
64        if let Some(device) = backend.get_device()
65            && aligned_size > 0
66        {
67            // C++ creates the buffer mapped and copies the data (zero padded);
68            // a queue write of the data has the same effect for the next
69            // submission.
70            let (b, at) = backend.allocate_uniform_buffer(&device, aligned_size as u64);
71            if let Some(data) = data {
72                backend.write_buffer_padded(&b, at, &data[..size], aligned_size as u64);
73                written = size;
74            }
75            if let Some(context) = context.upgrade() {
76                context.count_buffer_created(aligned_size as u64);
77                let mut stats = context.rendering_stats_mut();
78                stats.num_uniform_buffers += 1;
79                stats.mem_uniform_buffers += aligned_size as i32;
80            }
81            buffer = Some(b);
82            offset = at;
83        }
84        UniformBuffer { size, backend, context, buffer, offset, written: Cell::new(written) }
85    }
86
87    pub fn get_buffer(&self) -> Option<&wgpu::Buffer> {
88        self.buffer.as_ref()
89    }
90
91    /// Where this uniform buffer starts in [`get_buffer`](Self::get_buffer).
92    pub fn get_offset(&self) -> u64 {
93        self.offset
94    }
95
96    /// The size of this uniform buffer in its GPU buffer: the data's, padded
97    /// to 256 bytes.
98    pub fn get_aligned_size(&self) -> u64 {
99        aligned_uniform_size(self.size) as u64
100    }
101}
102
103impl Drop for UniformBuffer {
104    fn drop(&mut self) {
105        if self.buffer.is_some()
106            && let Some(context) = self.context.upgrade()
107        {
108            let size = self.get_aligned_size();
109            context.count_buffer_released(size);
110            let mut stats = context.rendering_stats_mut();
111            stats.num_uniform_buffers -= 1;
112            stats.mem_uniform_buffers -= size as i32;
113        }
114    }
115}
116
117impl uniform_buffer::UniformBuffer for UniformBuffer {
118    fn update(&self, data: &[u8]) {
119        debug_assert!(data.len() <= aligned_uniform_size(self.size), "update larger than the uniform buffer");
120        if !data.is_empty()
121            && let Some(buffer) = &self.buffer
122        {
123            let written = self.written.get();
124            if data.len() >= written {
125                self.backend.write_buffer_padded(buffer, self.offset, data, self.get_aligned_size());
126            } else {
127                self.backend.write_buffer(buffer, self.offset, data);
128            }
129            self.written.set(written.max(data.len()));
130            if let Some(context) = self.context.upgrade() {
131                context.count_buffer_update(data.len());
132                let mut stats = context.rendering_stats_mut();
133                stats.num_uniform_updates += 1;
134                stats.uniform_update_bytes = stats.uniform_update_bytes.wrapping_add(data.len());
135            }
136        }
137    }
138
139    fn get_size(&self) -> usize {
140        self.size
141    }
142
143    fn as_any(&self) -> &dyn Any {
144        self
145    }
146}