Skip to main content

mln_engine/draw/
vertices.rs

1//! The vertices that draws bind from the context's store: a bucket's, which
2//! a tile's draws share, and those a layer makes for its draws. Draws hold
3//! them as [`VertexBuffer`]s. Dynamic vertices keep their bytes' storage
4//! across uploads for the updates that replace them. Only the store makes
5//! a handle, of the entries it adds, so its count is its entry's.
6
7use std::rc::Rc;
8
9use mln_gfx::gpu::{BufferId, BufferUsage, Gpu, GpuError};
10#[cfg(target_family = "wasm")]
11use mln_wire::host_bytes::HostBytes;
12
13use crate::draw::buffer::Buffer;
14use crate::draw::owned::Held;
15use crate::draw::release::ReleaseQueue;
16use crate::draw::resources::Device;
17use crate::draw::store::{Shared, Store, VerticesKey};
18
19/// Where the vertices' bytes are: in the vector of the alignment of their
20/// type, which a vector of vertices moves into without a copy, or of
21/// dynamic vertices in bytes.
22enum VertexData {
23    Bytes(Vec<u8>),
24    Halves(Vec<u16>),
25    Words(Vec<u32>),
26    Doubles(Vec<u64>),
27    /// Dynamic vertices' bytes, which the next upload writes.
28    Dynamic(Vec<u8>),
29    /// Dynamic vertices' bytes that the last upload wrote, whose storage the
30    /// next update fills.
31    Written(Vec<u8>),
32    /// The bytes in the JS array they arrived in, which the upload writes
33    /// from there.
34    #[cfg(target_family = "wasm")]
35    Host(HostBytes),
36    /// Freed once in a buffer.
37    Freed,
38}
39
40/// Vertices of the context's store: their bytes until an upload writes them
41/// to a buffer, which frees them, and that buffer. Dynamic vertices take
42/// updates, each new bytes of as many vertices, which the next upload
43/// writes over the buffer's; their uploads keep their bytes' storage for
44/// the next update to fill.
45pub(crate) struct Vertices {
46    /// The bytes the next upload writes; once it wrote them, `Freed`, or
47    /// `Written` for dynamic vertices.
48    data: VertexData,
49    count: usize,
50    vertex_size: usize,
51    buffer: Option<Buffer>,
52}
53
54impl VertexData {
55    /// The data of `vertices`, moved.
56    fn of<V: bytemuck::Pod>(vertices: Vec<V>) -> VertexData {
57        use bytemuck::allocation::try_cast_vec;
58        let moved = match align_of::<V>() {
59            1 => try_cast_vec(vertices).map(VertexData::Bytes),
60            2 => try_cast_vec(vertices).map(VertexData::Halves),
61            4 => try_cast_vec(vertices).map(VertexData::Words),
62            8 => try_cast_vec(vertices).map(VertexData::Doubles),
63            _ => Err((bytemuck::PodCastError::AlignmentMismatch, vertices)),
64        };
65        moved.unwrap_or_else(|(_, vertices)| VertexData::Bytes(bytemuck::cast_slice(&vertices).to_vec()))
66    }
67
68    /// The bytes, while they are in wasm memory, to change.
69    fn bytes_mut(&mut self) -> Option<&mut [u8]> {
70        match self {
71            VertexData::Bytes(bytes) => Some(bytes),
72            VertexData::Halves(data) => Some(bytemuck::cast_slice_mut(data)),
73            VertexData::Words(data) => Some(bytemuck::cast_slice_mut(data)),
74            VertexData::Doubles(data) => Some(bytemuck::cast_slice_mut(data)),
75            VertexData::Dynamic(bytes) => Some(bytes),
76            #[cfg(target_family = "wasm")]
77            VertexData::Host(_) => None,
78            VertexData::Written(_) | VertexData::Freed => None,
79        }
80    }
81
82    /// The bytes, while they are in wasm memory.
83    fn bytes(&self) -> Option<&[u8]> {
84        match self {
85            VertexData::Bytes(bytes) => Some(bytes),
86            VertexData::Halves(data) => Some(bytemuck::cast_slice(data)),
87            VertexData::Words(data) => Some(bytemuck::cast_slice(data)),
88            VertexData::Doubles(data) => Some(bytemuck::cast_slice(data)),
89            VertexData::Dynamic(bytes) => Some(bytes),
90            #[cfg(target_family = "wasm")]
91            VertexData::Host(_) => None,
92            VertexData::Written(_) | VertexData::Freed => None,
93        }
94    }
95}
96
97impl Vertices {
98    /// `vertices`, moved.
99    fn new<V: bytemuck::Pod>(vertices: Vec<V>) -> Vertices {
100        let count = vertices.len();
101        let data = VertexData::of(vertices);
102        Vertices { data, count, vertex_size: size_of::<V>(), buffer: None }
103    }
104
105    /// Dynamic vertices of a copy of `vertices`.
106    fn dynamic<V: bytemuck::Pod>(vertices: &[V]) -> Vertices {
107        let data = VertexData::Dynamic(bytemuck::cast_slice(vertices).to_vec());
108        Vertices { data, count: vertices.len(), vertex_size: size_of::<V>(), buffer: None }
109    }
110
111    /// The vertices of `vertex_size` bytes each in a JS array.
112    #[cfg(target_family = "wasm")]
113    fn from_host(bytes: HostBytes, vertex_size: usize) -> Vertices {
114        debug_assert!(bytes.len().is_multiple_of(vertex_size.max(1)));
115        let count = bytes.len() / vertex_size.max(1);
116        Vertices { data: VertexData::Host(bytes), count, vertex_size, buffer: None }
117    }
118
119    /// The number of vertices, which stays once the upload freed them.
120    #[must_use]
121    pub(crate) fn count(&self) -> usize {
122        self.count
123    }
124
125    /// The bytes a vertex takes.
126    #[must_use]
127    pub(crate) fn vertex_size(&self) -> usize {
128        self.vertex_size
129    }
130
131    /// The bytes the vertices take.
132    fn size(&self) -> usize {
133        self.count() * self.vertex_size()
134    }
135
136    /// Whether the next upload writes the vertices: they are new, or
137    /// updated since the last upload, which wrote their bytes. A draw bound
138    /// before then binds them again, and its other attributes with them.
139    #[must_use]
140    pub(crate) fn needs_upload(&self) -> bool {
141        !matches!(self.data, VertexData::Written(_) | VertexData::Freed)
142    }
143
144    /// The bytes of the vertices while they are in wasm memory.
145    #[must_use]
146    pub(crate) fn bytes(&self) -> &[u8] {
147        self.data.bytes().unwrap_or_default()
148    }
149
150    /// Replaces the bytes of dynamic vertices with `bytes`, of as many
151    /// vertices, which the next upload writes. Returns false, leaving the
152    /// vertices be, for another number of bytes.
153    fn update(&mut self, bytes: &[u8]) -> bool {
154        if bytes.len() != self.size() {
155            return false;
156        }
157        if let VertexData::Written(storage) = &mut self.data {
158            self.data = VertexData::Dynamic(std::mem::take(storage));
159        }
160        match self.data.bytes_mut() {
161            Some(data) => data.copy_from_slice(bytes),
162            None => self.data = VertexData::Bytes(bytes.to_vec()),
163        }
164        true
165    }
166
167    /// Frees the bytes, which the upload wrote, or keeps those of dynamic
168    /// vertices for the next update.
169    fn written(&mut self) {
170        self.data = match std::mem::replace(&mut self.data, VertexData::Freed) {
171            VertexData::Dynamic(bytes) | VertexData::Written(bytes) => VertexData::Written(bytes),
172            _ => VertexData::Freed,
173        };
174    }
175
176    /// The buffer of the vertices of `gpu` through `device`: made of them
177    /// by the first upload, and written over by the upload after an update,
178    /// each of which frees their bytes, or keeps dynamic vertices' for the
179    /// next update; `None` where there are none.
180    fn upload(&mut self, gpu: &mut dyn Gpu, device: &mut Device) -> Result<Option<BufferId>, GpuError> {
181        if let Some(buffer) = &self.buffer {
182            let id = buffer.id();
183            if let Some(bytes) = self.data.bytes() {
184                device.write(gpu, buffer, bytes)?;
185                self.written();
186            }
187            return Ok(Some(id));
188        }
189        let size = self.size();
190        if size == 0 {
191            self.written();
192            return Ok(None);
193        }
194        let buffer = match &self.data {
195            #[cfg(target_family = "wasm")]
196            VertexData::Host(bytes) => device.buffer_from_host(gpu, BufferUsage::Vertex, bytes)?,
197            data => {
198                let Some(bytes) = data.bytes() else {
199                    debug_assert!(false, "vertices without data or a buffer");
200                    return Err(GpuError::Invalid("vertices without data or a buffer".to_owned()));
201                };
202                device.buffer(gpu, BufferUsage::Vertex, &bytes[..size])?
203            }
204        };
205        let id = buffer.id();
206        self.buffer = Some(buffer);
207        self.written();
208        Ok(Some(id))
209    }
210}
211
212/// The context's store of the vertices that draws bind, which their
213/// handles keep while they last.
214#[derive(Default)]
215pub(crate) struct VertexStore(Store<VerticesKey, Vertices>);
216
217impl VertexStore {
218    /// Keeps `vertices` while a clone of the returned handle lasts, whose
219    /// key goes to `queue` once the last clone drops.
220    pub(crate) fn add<V: bytemuck::Pod>(&mut self, vertices: Vec<V>, queue: &Rc<ReleaseQueue>) -> VertexBuffer {
221        self.insert(Vertices::new(vertices), queue)
222    }
223
224    /// Keeps a copy of `vertices` as dynamic vertices, which the holder of
225    /// the returned handle updates ([`update`](Self::update)), as
226    /// [`add`](Self::add) does.
227    pub(crate) fn add_dynamic<V: bytemuck::Pod>(&mut self, vertices: &[V], queue: &Rc<ReleaseQueue>) -> VertexBuffer {
228        self.insert(Vertices::dynamic(vertices), queue)
229    }
230
231    /// Keeps the vertices of the type `V` in the JS array `bytes`, as
232    /// [`add`](Self::add) does.
233    #[cfg(target_family = "wasm")]
234    pub(crate) fn add_host<V: bytemuck::Pod>(&mut self, bytes: HostBytes, queue: &Rc<ReleaseQueue>) -> VertexBuffer {
235        self.insert(Vertices::from_host(bytes, size_of::<V>()), queue)
236    }
237
238    fn insert(&mut self, vertices: Vertices, queue: &Rc<ReleaseQueue>) -> VertexBuffer {
239        let count = vertices.count();
240        VertexBuffer { handle: self.0.add(vertices, queue), count }
241    }
242
243    /// The vertices of `shared`.
244    pub(crate) fn get(&self, shared: &VertexBuffer) -> Option<&Vertices> {
245        self.0.get(&shared.handle)
246    }
247
248    /// Whether the store has the vertices `key`.
249    #[cfg(test)]
250    pub(crate) fn contains(&self, key: VerticesKey) -> bool {
251        self.0.contains(key)
252    }
253
254    /// Replaces the vertices of `buffer` with a copy of `data`, as many,
255    /// as [`Vertices::update`] does.
256    pub(crate) fn update<V: bytemuck::Pod>(&mut self, buffer: &VertexBuffer, data: &[V]) -> bool {
257        let Some(entry) = self.0.get_mut(&buffer.handle) else {
258            return false;
259        };
260        debug_assert_eq!(entry.vertex_size(), size_of::<V>());
261        entry.update(bytemuck::cast_slice(data))
262    }
263
264    /// The buffer of the vertices of `shared`, as [`Vertices::upload`]
265    /// makes it.
266    pub(crate) fn upload(
267        &mut self,
268        gpu: &mut dyn Gpu,
269        device: &mut Device,
270        shared: &VertexBuffer,
271    ) -> Result<Option<BufferId>, GpuError> {
272        self.0.get_mut(&shared.handle).ok_or(GpuError::UnknownId("vertices"))?.upload(gpu, device)
273    }
274
275    /// Takes out the vertices `key`, whose last handle dropped.
276    pub(crate) fn remove(&mut self, key: VerticesKey) -> Option<Vertices> {
277        self.0.remove(key)
278    }
279
280    /// Drops every entry.
281    pub(crate) fn clear(&mut self) {
282        self.0.clear();
283    }
284}
285
286/// A buffer of vertices that meshes read ([`VertexBinding`]), with their
287/// count. It stays while a clone does; clones are the same buffer, and
288/// handles are equal where they are.
289///
290/// [`VertexBinding`]: crate::draw::VertexBinding
291#[derive(Clone, Debug, PartialEq, Eq)]
292pub struct VertexBuffer {
293    handle: Shared<VerticesKey>,
294    count: usize,
295}
296
297impl VertexBuffer {
298    /// What geometry made of the vertices holds.
299    pub(crate) fn held(&self) -> Held {
300        Held::Vertices(self.handle.clone())
301    }
302
303    /// The entry's key in the store.
304    #[cfg(test)]
305    #[must_use]
306    pub(crate) fn key(&self) -> VerticesKey {
307        self.handle.key()
308    }
309
310    /// The number of vertices.
311    #[must_use]
312    pub fn count(&self) -> usize {
313        self.count
314    }
315}