Skip to main content

mln_engine/layer/
bucket_geometry.rs

1// Where a bucket's vertices and indices live once the render thread draws
2// them.
3//
4// Buckets cross from the worker threads, so they hold plain vectors
5// (`GeometryVec`). A bucket's upload moves each vector into the context's
6// stores, which the draws of the bucket's tile share, so the bucket and the
7// draws don't each keep a copy; the tile keeps their handles, by the key of
8// the vector they were made of, in a `BucketGeometry`. The stores free the
9// data once it is in a GPU buffer, and the draws a layer builds again for
10// the same bucket reuse that buffer. Vertices that a layer makes of a
11// bucket's vector are kept there too, made before the vector moves.
12//
13// A copy of a vector keeps its key. The tiles of a tile's other world
14// copies hold copies of its buckets, and the upload of either takes what
15// the other already moved into the stores, freeing its own copy.
16//
17// In the browser, the arrays a bucket gets from a tile worker in another
18// wasm instance stay the JS arrays they arrived in (mln_wire::host_bytes)
19// and move to the store as they are, which uploads them from there.
20// Anything that reads or changes them first copies them into wasm memory.
21
22use std::borrow::Cow;
23
24#[cfg(target_family = "wasm")]
25use mln_wire::host_bytes::HostBytes;
26use mln_wire::payload::{Payload, pod};
27
28use crate::draw::context::Context;
29use crate::draw::identity::SimpleIdentity;
30use crate::draw::indexes::{DrawIndexes, Indexes, SharedIndexes};
31use crate::draw::vertices::SharedVertices;
32use crate::layer::paint_property_binder::InterleavedVertexBuffer;
33
34/// A bucket's vertices or indices. The worker fills it through `get_mut`;
35/// the render thread can move the data out (`BucketGeometry`), after which
36/// `len` still counts it.
37#[derive(Clone, Debug)]
38pub struct GeometryVec<T> {
39    data: Data<T>,
40    /// What `BucketGeometry` keeps the vector's stored geometry under. A
41    /// copy keeps it, so the stored geometry of either serves both.
42    key: SimpleIdentity,
43}
44
45/// Where a [`GeometryVec`]'s data is.
46#[derive(Clone, Debug)]
47enum Data<T> {
48    /// In memory.
49    Vec(Vec<T>),
50    /// In the JS array it arrived in.
51    #[cfg(target_family = "wasm")]
52    Host(HostBytes),
53    /// Moved out, `len` elements of it.
54    Moved { len: usize },
55}
56
57impl<T> Default for GeometryVec<T> {
58    fn default() -> Self {
59        GeometryVec::new(Vec::new())
60    }
61}
62
63impl<T> GeometryVec<T> {
64    #[must_use]
65    pub(crate) fn new(v: Vec<T>) -> Self {
66        GeometryVec::of(Data::Vec(v))
67    }
68
69    fn of(data: Data<T>) -> Self {
70        GeometryVec { data, key: SimpleIdentity::new() }
71    }
72
73    /// The data, to fill. Not after it is moved out.
74    pub fn get_mut(&mut self) -> &mut Vec<T>
75    where
76        T: bytemuck::Pod,
77    {
78        debug_assert!(!self.is_moved(), "geometry modified after it moved to the render thread");
79        self.data.vec_mut()
80    }
81
82    /// The element count, which stays when the data is moved out.
83    #[must_use]
84    pub fn len(&self) -> usize {
85        match &self.data {
86            Data::Vec(v) => v.len(),
87            #[cfg(target_family = "wasm")]
88            Data::Host(bytes) => bytes.len() / size_of::<T>(),
89            Data::Moved { len } => *len,
90        }
91    }
92
93    /// Whether the vector holds no element.
94    #[must_use]
95    pub fn is_empty(&self) -> bool {
96        self.len() == 0
97    }
98
99    /// True once the data has moved to the context's store.
100    #[must_use]
101    pub fn is_moved(&self) -> bool {
102        matches!(self.data, Data::Moved { .. })
103    }
104
105    /// The data, empty once it is moved out.
106    #[must_use]
107    pub fn data(&self) -> Cow<'_, [T]>
108    where
109        T: bytemuck::Pod,
110    {
111        self.data.data()
112    }
113
114    /// The data, moved out, leaving its count.
115    fn take(&mut self) -> Data<T> {
116        let len = self.len();
117        std::mem::replace(&mut self.data, Data::Moved { len })
118    }
119}
120
121impl<T: bytemuck::Pod> Data<T> {
122    /// The data, empty once it is moved out.
123    fn data(&self) -> Cow<'_, [T]> {
124        match self {
125            Data::Vec(v) => Cow::Borrowed(v),
126            #[cfg(target_family = "wasm")]
127            Data::Host(bytes) => Cow::Owned(bytes.to_pod_vec()),
128            Data::Moved { .. } => Cow::Borrowed(&[]),
129        }
130    }
131
132    /// The data's vector, which replaces the data where it isn't in memory:
133    /// a copy of the JS array's, or an empty one where it moved out.
134    fn vec_mut(&mut self) -> &mut Vec<T> {
135        match self {
136            Data::Vec(v) => v,
137            #[cfg(target_family = "wasm")]
138            host @ Data::Host(_) => {
139                *host = Data::Vec(host.data().into_owned());
140                host.vec_mut()
141            }
142            moved @ Data::Moved { .. } => {
143                *moved = Data::Vec(Vec::new());
144                moved.vec_mut()
145            }
146        }
147    }
148}
149
150impl<T: bytemuck::Pod> GeometryVec<T> {
151    /// Frees the data, which nothing will draw. `len` still counts it.
152    pub fn discard(&mut self) {
153        self.take();
154    }
155
156    /// The data, moved out into `context`'s store.
157    fn store_vertices(&mut self, context: &mut Context) -> SharedVertices {
158        match self.take() {
159            Data::Vec(v) => context.add_vertices(v),
160            #[cfg(target_family = "wasm")]
161            Data::Host(bytes) => context.add_host_vertices::<T>(bytes),
162            Data::Moved { .. } => context.add_vertices(Vec::<T>::new()),
163        }
164    }
165}
166
167impl GeometryVec<u16> {
168    /// Indexes of the data, moved out.
169    fn indexes(&mut self) -> Indexes {
170        match self.take() {
171            Data::Vec(v) => Indexes::new(v),
172            #[cfg(target_family = "wasm")]
173            Data::Host(bytes) => Indexes::from_host(bytes),
174            Data::Moved { .. } => Indexes::new(Vec::new()),
175        }
176    }
177}
178
179impl<T: bytemuck::Pod + PartialEq> PartialEq for GeometryVec<T> {
180    fn eq(&self, other: &Self) -> bool {
181        self.is_moved() == other.is_moved() && self.len() == other.len() && self.data() == other.data()
182    }
183}
184
185impl<T> From<Vec<T>> for GeometryVec<T> {
186    fn from(v: Vec<T>) -> Self {
187        GeometryVec::new(v)
188    }
189}
190
191/// As the plain values' bytes (`payload::pod`). Workers send buckets before
192/// the render thread moves anything out. A payload the host kept in JS
193/// stays there (`mln_wire::host_bytes`).
194impl<T: bytemuck::Pod> mln_wire::Wire for GeometryVec<T> {
195    fn write(&self, w: &mut mln_wire::Writer) {
196        debug_assert!(!self.is_moved());
197        pod::write(&self.data(), w);
198    }
199
200    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
201        Some(match pod::read_payload::<T>(r)? {
202            Payload::Bytes(bytes) => GeometryVec::new(bytemuck::pod_collect_to_vec(&bytes)),
203            #[cfg(target_family = "wasm")]
204            Payload::Host(bytes) => GeometryVec::of(Data::Host(bytes)),
205        })
206    }
207}
208
209/// The geometry of a tile's buckets in the context's stores, by the key of
210/// the bucket's vector it was made of. The tile keeps one per layout result,
211/// so it lives as long as the buckets it was made from.
212#[derive(Clone, Default)]
213pub struct BucketGeometry {
214    vertices: Kept<SharedVertices>,
215    indexes: Kept<SharedIndexes>,
216    /// The vertices a layer made of a bucket's vector.
217    derived: Kept<SharedVertices>,
218}
219
220impl BucketGeometry {
221    /// The vertices that `vec`, a bucket's, moved into.
222    fn vertices<V>(&self, vec: &GeometryVec<V>) -> Option<&SharedVertices> {
223        self.vertices.get(vec.key)
224    }
225
226    /// Frees the room that the entries' lists keep for more, where it is
227    /// over a quarter of what they keep, once a tile's buckets uploaded.
228    pub(crate) fn shrink(&mut self) {
229        self.vertices.shrink();
230        self.indexes.shrink();
231        self.derived.shrink();
232    }
233}
234
235/// Entries by the key of the vector they were made of, in key order: a
236/// tile's are few, and a list takes less memory than a map.
237#[derive(Clone)]
238struct Kept<T>(Vec<(SimpleIdentity, T)>);
239
240impl<T> Default for Kept<T> {
241    fn default() -> Self {
242        Kept(Vec::new())
243    }
244}
245
246impl<T> Kept<T> {
247    fn get(&self, key: SimpleIdentity) -> Option<&T> {
248        let at = self.0.binary_search_by_key(&key, |(key, _)| *key).ok()?;
249        self.0.get(at).map(|(_, value)| value)
250    }
251
252    fn insert(&mut self, key: SimpleIdentity, value: T) {
253        match self.0.binary_search_by_key(&key, |(key, _)| *key) {
254            Ok(at) => {
255                if let Some(entry) = self.0.get_mut(at) {
256                    entry.1 = value;
257                }
258            }
259            Err(at) => self.0.insert(at, (key, value)),
260        }
261    }
262
263    /// Whether the list has an entry under `key`, taking the first of
264    /// `others`' where it has none.
265    fn has_or_takes<'a>(&mut self, key: SimpleIdentity, mut others: impl Iterator<Item = &'a Kept<T>>) -> bool
266    where
267        T: Clone + 'a,
268    {
269        if self.get(key).is_some() {
270            return true;
271        }
272        let Some(shared) = others.find_map(|other| other.get(key)) else {
273            return false;
274        };
275        self.insert(key, shared.clone());
276        true
277    }
278
279    fn shrink(&mut self) {
280        if self.0.capacity() - self.0.len() > self.0.len() / 4 {
281            self.0.shrink_to_fit();
282        }
283    }
284}
285
286/// A bucket's upload: what moves the bucket's geometry into the context's
287/// stores, and keeps its handles in its tile's [`BucketGeometry`].
288pub(crate) struct GeometryUpload<'a> {
289    geometry: &'a mut BucketGeometry,
290    /// The geometry of the tile's other world copies, whose buckets the
291    /// tile's are copies of, or they of the tile's.
292    copies: &'a [&'a BucketGeometry],
293    context: &'a mut Context,
294}
295
296impl<'a> GeometryUpload<'a> {
297    /// The upload of buckets whose geometry `geometry` keeps, into
298    /// `context`'s stores, which takes what of it `copies`, the geometry of
299    /// the tile's other world copies, keep.
300    pub(crate) fn new(
301        geometry: &'a mut BucketGeometry,
302        copies: &'a [&'a BucketGeometry],
303        context: &'a mut Context,
304    ) -> Self {
305        GeometryUpload { geometry, copies, context }
306    }
307
308    /// What the context's device allows.
309    pub(crate) fn caps(&self) -> &mln_gfx::gpu::Caps {
310        self.context.caps()
311    }
312
313    /// Moves the data of `vec`, a bucket's, into the store, unless it moved
314    /// before. Where a copy of it moved, this frees it and shares the
315    /// copy's.
316    pub(crate) fn move_vertices<V: bytemuck::Pod>(&mut self, vec: &mut GeometryVec<V>) {
317        if vec.is_moved() {
318            return;
319        }
320        if self.geometry.vertices.has_or_takes(vec.key, self.copies.iter().map(|copy| &copy.vertices)) {
321            vec.discard();
322        } else {
323            let vertices = vec.store_vertices(self.context);
324            self.geometry.vertices.insert(vec.key, vertices);
325        }
326    }
327
328    /// Moves the data of `vec`, a bucket's, into the store's indexes,
329    /// unless it moved before, as [`move_vertices`](Self::move_vertices)
330    /// does.
331    pub(crate) fn move_indexes(&mut self, vec: &mut GeometryVec<u16>) {
332        if vec.is_moved() {
333            return;
334        }
335        if self.geometry.indexes.has_or_takes(vec.key, self.copies.iter().map(|copy| &copy.indexes)) {
336            vec.discard();
337        } else {
338            let indexes = self.context.add_indexes(vec.indexes());
339            self.geometry.indexes.insert(vec.key, indexes);
340        }
341    }
342
343    /// Moves the values of `buffer`, a layer's data-driven paint values,
344    /// into the store, unless they `depend_on_feature_state`: those stay in
345    /// the bucket, where feature state rewrites them.
346    pub(crate) fn move_paint(&mut self, buffer: &mut InterleavedVertexBuffer, depends_on_feature_state: bool) {
347        if !depends_on_feature_state {
348            self.move_vertices(&mut buffer.shared_vertex_vector);
349        }
350    }
351
352    /// Keeps the vertices that `make` makes of the data of `vec`, a
353    /// bucket's, for [`derived_vertices`], unless it or a copy has some.
354    /// Before the data moves.
355    pub(crate) fn derive_vertices<V: bytemuck::Pod, D: bytemuck::Pod>(
356        &mut self,
357        vec: &GeometryVec<V>,
358        make: impl FnOnce(&[V]) -> Vec<D>,
359    ) {
360        if !self.geometry.derived.has_or_takes(vec.key, self.copies.iter().map(|copy| &copy.derived)) {
361            debug_assert!(!vec.is_moved(), "vertices derived from data that moved to the store");
362            let derived = self.context.add_vertices(make(&vec.data()));
363            self.geometry.derived.insert(vec.key, derived);
364        }
365    }
366}
367
368/// The vertices that a bucket's upload made of `vec`, one of its vectors,
369/// with `GeometryUpload::derive_vertices`, which its tile's `geometry`
370/// keeps.
371#[must_use]
372pub fn derived_vertices<V>(geometry: &BucketGeometry, vec: &GeometryVec<V>) -> Option<SharedVertices> {
373    let derived = geometry.derived.get(vec.key);
374    debug_assert!(derived.is_some(), "vertices that the bucket's upload didn't derive");
375    derived.cloned()
376}
377
378/// Vertices of `context`'s store holding a copy of `vertices`, which the
379/// draws that bind them don't change: draws replace such vertices instead.
380pub fn copied_vertices<V: bytemuck::Pod>(context: &mut Context, vertices: &[V]) -> SharedVertices {
381    context.add_vertices(vertices.to_vec())
382}
383
384/// Indexes holding a copy of `indexes`, which a draw owns.
385#[must_use]
386pub fn copied_indexes(indexes: &[u16]) -> DrawIndexes {
387    DrawIndexes::new(indexes.to_vec())
388}
389
390/// The vertices that a bucket's upload moved `vec`, one of its vectors,
391/// into, which its tile's `geometry` keeps.
392#[must_use]
393pub fn bucket_vertices<V>(geometry: &BucketGeometry, vec: &GeometryVec<V>) -> Option<SharedVertices> {
394    let vertices = geometry.vertices(vec);
395    debug_assert!(vertices.is_some(), "vertices that the bucket's upload didn't move");
396    vertices.cloned()
397}
398
399/// The indexes that a bucket's upload moved `vec`, one of its vectors,
400/// into, which its tile's `geometry` keeps and its draws share.
401#[must_use]
402pub fn bucket_indexes(geometry: &BucketGeometry, vec: &GeometryVec<u16>) -> Option<SharedIndexes> {
403    let indexes = geometry.indexes.get(vec.key);
404    debug_assert!(indexes.is_some(), "indexes that the bucket's upload didn't move");
405    indexes.cloned()
406}
407
408/// The vertices of a layer's data-driven paint values: those that a
409/// bucket's upload moved, which its tile's `geometry` keeps, or a copy in
410/// `context`'s store of the values that feature state rewrites, which stay
411/// in the bucket, and which the draws copy again each time they change.
412pub fn paint_vertices(
413    context: &mut Context,
414    geometry: &BucketGeometry,
415    buffer: &InterleavedVertexBuffer,
416    depends_on_feature_state: bool,
417) -> Option<SharedVertices> {
418    if depends_on_feature_state {
419        Some(copied_vertices(context, &buffer.shared_vertex_vector.data()))
420    } else {
421        bucket_vertices(geometry, &buffer.shared_vertex_vector)
422    }
423}