Skip to main content

mln_engine/layer/
bucket.rs

1//! Buckets: what a tile's layout makes of a layer group's features for the
2//! layers' draws, their vertices, indices and paint values. Workers build
3//! buckets and send them to the render thread, which owns each one once, in
4//! its tile's contents, as a `Stored` bucket behind `dyn ErasedBucket`.
5//! A layer type's `Bucket` names its data to an `Upload`; the engine
6//! keeps the rest: the bucket's identity, whether it uploaded, and the
7//! feature-state rewrites of its paint values.
8
9use std::any::Any;
10
11use mln_gfx::gpu::Caps;
12use mln_wire::{Wire, Writer};
13
14use crate::draw::context::Context;
15use crate::draw::identity::SimpleIdentity;
16use crate::layer::bucket_geometry::{BucketGeometry, GeometryUpload, GeometryVec};
17use crate::layer::paint_property_binder::{LayerBinders, PaintBinders};
18use crate::tile::TileLayer;
19
20/// The state of each feature of a source layer, by the feature's id.
21pub type FeatureStates = mln_style::hash::HashMap<String, mln_style::feature::FeatureState>;
22/// The state of each feature of each source layer, by source layer and
23/// feature id.
24pub type LayerFeatureStates = mln_style::hash::HashMap<String, FeatureStates>;
25
26/// What a layout makes of a tile for a group of layers: the vertices,
27/// indices and paint values that their draws read.
28///
29/// The engine moves a bucket from the worker to the render thread, copies
30/// it for the tile's other world copies, and uploads it.
31pub trait Bucket: Clone + Send + Wire + 'static {
32    /// Names the bucket's `GeometryVec`s and `LayerBinders` to `up`: the
33    /// engine moves them into the context's stores once the bucket reaches
34    /// the render thread, and rewrites the binders' values where feature
35    /// state changes.
36    fn upload(&mut self, up: &mut Upload<'_>);
37
38    /// How far above the ground, in meters, the bucket's highest content
39    /// is raised, for a layer whose content's elevation is an expression.
40    fn max_elevation(&self) -> f32 {
41        0.0
42    }
43}
44
45/// What a bucket names its data to, in its [`upload`](Bucket::upload).
46pub struct Upload<'a> {
47    kind: Kind<'a>,
48}
49
50enum Kind<'a> {
51    /// Moves the data into the context's stores.
52    Geometry(GeometryUpload<'a>),
53    /// Rewrites the binders of the layer `layer_id` for `states`, the
54    /// states of `layer`'s features, and records whether any read them.
55    FeatureState { states: &'a FeatureStates, layer: &'a TileLayer<'a>, layer_id: &'a str, rewrote: bool },
56}
57
58impl<'a> Upload<'a> {
59    /// The upload of a bucket whose geometry `geometry` keeps, into
60    /// `context`'s stores, sharing what `copies` keep: what the engine
61    /// makes as a bucket reaches the render thread, for a type's tests of
62    /// its buckets.
63    pub fn geometry(
64        geometry: &'a mut BucketGeometry,
65        copies: &'a [&'a BucketGeometry],
66        context: &'a mut Context,
67    ) -> Self {
68        Upload { kind: Kind::Geometry(GeometryUpload::new(geometry, copies, context)) }
69    }
70}
71
72impl Upload<'_> {
73    /// What the context's device allows, where the upload moves data: a
74    /// bucket names only the vectors its draws read there. `None` where the
75    /// upload rewrites the binders' values that read feature state, and
76    /// moves nothing.
77    #[must_use]
78    pub fn caps(&self) -> Option<&Caps> {
79        match &self.kind {
80            Kind::Geometry(geometry) => Some(geometry.caps()),
81            Kind::FeatureState { .. } => None,
82        }
83    }
84
85    /// Names `vec`, vertices that the bucket's draws read
86    /// ([`bucket_vertices`](crate::layer::bucket_geometry::bucket_vertices)).
87    pub fn vec<V: bytemuck::Pod>(&mut self, vec: &mut GeometryVec<V>) {
88        if let Kind::Geometry(geometry) = &mut self.kind {
89            geometry.move_vertices(vec);
90        }
91    }
92
93    /// Names `indexes`, which the bucket's draws draw
94    /// ([`bucket_indexes`](crate::layer::bucket_geometry::bucket_indexes)).
95    pub fn indexes(&mut self, indexes: &mut GeometryVec<u16>) {
96        if let Kind::Geometry(geometry) = &mut self.kind {
97            geometry.move_indexes(indexes);
98        }
99    }
100
101    /// Keeps the vertices that `make` makes of the data of `vec`, for
102    /// [`derived_vertices`](crate::layer::bucket_geometry::derived_vertices).
103    /// Before `vec` is named.
104    pub fn derive<V: bytemuck::Pod, D: bytemuck::Pod>(
105        &mut self,
106        vec: &GeometryVec<V>,
107        make: impl FnOnce(&[V]) -> Vec<D>,
108    ) {
109        if let Kind::Geometry(geometry) = &mut self.kind {
110            geometry.derive_vertices(vec, make);
111        }
112    }
113
114    /// Names `binders`, whose values the bucket's draws read
115    /// ([`paint_vertices`](crate::layer::bucket_geometry::paint_vertices)).
116    /// Values that feature state rewrites stay with the bucket.
117    pub fn binders<P: PaintBinders>(&mut self, binders: &mut LayerBinders<P>) {
118        for (layer_id, binders) in binders.iter_mut() {
119            self.paint(layer_id, binders);
120        }
121    }
122
123    /// Names `binders`, the layer `layer_id`'s, as [`binders`](Self::binders)
124    /// names each layer's, for a bucket that keeps a layer's binders its own
125    /// way.
126    pub fn paint<P: PaintBinders>(&mut self, layer_id: &str, binders: &mut P) {
127        let depends_on_feature_state = binders.depends_on_feature_state();
128        match &mut self.kind {
129            Kind::Geometry(geometry) => geometry.move_paint(binders.vertices_mut(), depends_on_feature_state),
130            Kind::FeatureState { states, layer, layer_id: changed, rewrote } => {
131                if layer_id == *changed && depends_on_feature_state {
132                    binders.feature_state(states, layer);
133                    *rewrote = true;
134                }
135            }
136        }
137    }
138}
139
140/// A bucket with what the engine keeps of it: its identity, which tells
141/// apart what the tile's layers made of it, and whether its data is in its
142/// tile's stores as it is. A copy keeps the identity: its draws are the
143/// same. The worker codec writes the bucket alone, so a bucket read from a
144/// worker is new to the side that reads it.
145#[derive(Clone)]
146pub(crate) struct Stored<B> {
147    pub(crate) bucket: B,
148    id: SimpleIdentity,
149    uploaded: bool,
150}
151
152impl<B> Stored<B> {
153    pub(crate) fn new(bucket: B) -> Self {
154        Stored { bucket, id: SimpleIdentity::new(), uploaded: false }
155    }
156}
157
158/// What the engine does with a bucket, whatever its type.
159pub trait ErasedBucket: Any + Send {
160    /// The bucket's identity.
161    fn id(&self) -> SimpleIdentity;
162
163    /// Whether the bucket has data its tile's stores don't have yet.
164    fn needs_upload(&self) -> bool;
165
166    /// Moves the bucket's data into `geometry`'s stores in `context`,
167    /// sharing what `copies`, the geometry of the tile's other world
168    /// copies, keep of it.
169    fn upload(&mut self, geometry: &mut BucketGeometry, copies: &[&BucketGeometry], context: &mut Context);
170
171    /// Rewrites the values of the layer `layer_id` that read feature state
172    /// for `states`, the states of `layer`'s features. Returns whether the
173    /// bucket has any.
174    fn set_feature_state(&mut self, states: &FeatureStates, layer: &TileLayer<'_>, layer_id: &str) -> bool;
175
176    /// [`Bucket::max_elevation`].
177    fn max_elevation(&self) -> f32;
178
179    /// A copy, for the tile in another world copy.
180    fn clone_bucket(&self) -> Box<dyn ErasedBucket>;
181
182    /// Writes the bucket for its layer type's
183    /// `read_bucket`.
184    fn write_wire(&self, w: &mut Writer);
185}
186
187impl<B: Bucket> ErasedBucket for Stored<B> {
188    fn id(&self) -> SimpleIdentity {
189        self.id
190    }
191
192    fn needs_upload(&self) -> bool {
193        !self.uploaded
194    }
195
196    fn upload(&mut self, geometry: &mut BucketGeometry, copies: &[&BucketGeometry], context: &mut Context) {
197        let geometry = GeometryUpload::new(geometry, copies, context);
198        self.bucket.upload(&mut Upload { kind: Kind::Geometry(geometry) });
199        self.uploaded = true;
200    }
201
202    fn set_feature_state(&mut self, states: &FeatureStates, layer: &TileLayer<'_>, layer_id: &str) -> bool {
203        let mut upload = Upload { kind: Kind::FeatureState { states, layer, layer_id, rewrote: false } };
204        self.bucket.upload(&mut upload);
205        matches!(upload.kind, Kind::FeatureState { rewrote: true, .. })
206    }
207
208    fn max_elevation(&self) -> f32 {
209        self.bucket.max_elevation()
210    }
211
212    fn clone_bucket(&self) -> Box<dyn ErasedBucket> {
213        Box::new(self.clone())
214    }
215
216    fn write_wire(&self, w: &mut Writer) {
217        self.bucket.write(w);
218    }
219}
220
221impl dyn ErasedBucket {
222    /// The bucket as a `B`; `None` for one of another type.
223    pub(crate) fn downcast_ref<B: Bucket>(&self) -> Option<&B> {
224        let any: &dyn Any = self;
225        Some(&any.downcast_ref::<Stored<B>>()?.bucket)
226    }
227
228    /// [`downcast_ref`](Self::downcast_ref), to change.
229    pub(crate) fn downcast_mut<B: Bucket>(&mut self) -> Option<&mut B> {
230        let any: &mut dyn Any = self;
231        Some(&mut any.downcast_mut::<Stored<B>>()?.bucket)
232    }
233}