Skip to main content

mln_engine/layer/
layout.rs

1//! How a layer type lays out a tile's features on a worker: its [`Layout`],
2//! which selects the features with a [`LayoutCx`] and builds the bucket
3//! with a [`BuildCx`].
4//!
5//! A `TileLayer` borrows its `TileData`, and the worker keeps layouts with
6//! pending dependencies across messages, so layouts keep the indexes of the
7//! features they select, and the contexts borrow the layer again from the
8//! engine's [`SourceLayer`] when they run.
9
10use std::sync::Arc;
11
12use mln_style::PropertyEvaluationParameters;
13use mln_style::collections::{VecMap, VecSet};
14use mln_style::crs::WorldMapping;
15use mln_style::error::Error;
16use mln_style::expression::{EvaluationContext, GlobalStateMap, UnavailableImages, Value};
17use mln_style::feature::{GeometryCollection, GeometryTileFeature};
18use mln_style::filter::Filter;
19use mln_style::layer::{PaintSet, StyleLayerType};
20use mln_style::subdivision_granularity::SubdivisionGranularitySetting;
21use mln_style::tile_id::CanonicalTileID;
22
23use crate::image::image_store::{ImageDependencies, ImageType};
24use crate::layer::bucket::Bucket;
25use crate::layer::bucket_parameters::BucketParameters;
26use crate::layer::filter_groups::FilterGroups;
27use crate::layer::layer_type::EvaluatedLayer;
28use crate::layer::paint_property_binder::{LayerBinders, PaintBinders, PatternLayerMap};
29use crate::layer::tile_layout::Resolved;
30use crate::map::MapMode;
31use crate::query::feature_index::FeatureIndexBuilder;
32use crate::text::atlas::ImagePositions;
33use crate::text::glyph::{FontFaces, GlyphDependencies};
34use crate::tile::{OverscaledTileID, TileData, TileLayer};
35
36/// How a group of layers of the type `T` that share their layout becomes a
37/// tile's bucket, on a tile worker: [`new`](Self::new) selects the tile's
38/// features, and once the glyphs and images it asked for are resolved,
39/// [`build`](Self::build) makes the bucket.
40pub trait Layout<T: StyleLayerType>: Send + Sized + 'static {
41    /// The bucket the layout makes.
42    type Bucket: Bucket;
43
44    /// Whether the layout of `group` may ask for glyphs or images. The
45    /// engine makes such a layout before it resolves them, and builds it
46    /// once they are, after every other.
47    fn needs_resources(_group: &[Arc<EvaluatedLayer<T>>]) -> bool {
48        false
49    }
50
51    /// Selects the features of the tile that the bucket draws.
52    fn new(cx: &mut LayoutCx<'_, T>) -> Result<Self, Error>;
53
54    /// Makes the bucket of the selected features; `None` for one with
55    /// nothing to draw. A feature that fails to decode fails the bucket,
56    /// which the engine reports as the tile's error.
57    fn build(self, cx: &mut BuildCx<'_, T>) -> Result<Option<Self::Bucket>, Error>;
58}
59
60/// The layer a layout reads: its tile data and its name.
61#[derive(Clone)]
62pub struct SourceLayer {
63    pub(crate) data: TileData,
64    pub(crate) name: String,
65}
66
67impl SourceLayer {
68    pub(crate) fn new(data: TileData, name: impl Into<String>) -> Self {
69        SourceLayer { data, name: name.into() }
70    }
71
72    /// The layer. The worker only creates layouts for layers the data has,
73    /// so neither error is expected.
74    pub(crate) fn layer(&self) -> Result<TileLayer<'_>, Error> {
75        self.data
76            .layer(&self.name)?
77            .ok_or_else(|| Error::failed(format!("SourceLayer: the tile data has no layer {:?}", self.name)))
78    }
79}
80
81/// What a tile's layouts read apart from their group, and where they record
82/// the glyphs and images they need.
83pub struct LayoutParameters<'a> {
84    pub(crate) bucket_parameters: &'a BucketParameters,
85    /// The style's font faces, and its fallback faces after them.
86    pub(crate) font_faces: Option<&'a Arc<FontFaces>>,
87    /// Whether the style has a `glyphs` URL.
88    pub(crate) glyph_pbfs: bool,
89    pub(crate) glyph_dependencies: &'a mut GlyphDependencies,
90    pub(crate) image_dependencies: &'a mut ImageDependencies,
91    pub(crate) available_images: &'a VecSet<String>,
92    /// Where `image` expressions record the images not in `available_images`.
93    pub(crate) unavailable_images: &'a UnavailableImages,
94    /// The tile's feature groups, shared by the layouts' filters.
95    pub(crate) filter_groups: &'a mut FilterGroups,
96}
97
98/// What a layout reads of its tile while it selects features.
99pub struct LayoutCx<'a, T: StyleLayerType> {
100    pub(crate) layers: &'a [Arc<EvaluatedLayer<T>>],
101    pub(crate) source_layer: &'a SourceLayer,
102    pub(crate) parameters: LayoutParameters<'a>,
103}
104
105impl<'a, T: StyleLayerType> LayoutCx<'a, T> {
106    /// The layers of the group, its leader first, whose style the layout's
107    /// layout properties and filter are.
108    #[must_use]
109    pub fn layers(&self) -> &'a [Arc<EvaluatedLayer<T>>] {
110        self.layers
111    }
112
113    /// The tile.
114    #[must_use]
115    pub fn tile(&self) -> OverscaledTileID {
116        self.parameters.bucket_parameters.tile_id
117    }
118
119    /// The tile's zoom.
120    #[must_use]
121    pub fn zoom(&self) -> f64 {
122        f64::from(self.tile().overscaled_z)
123    }
124
125    /// How the map renders.
126    #[must_use]
127    pub fn mode(&self) -> MapMode {
128        self.parameters.bucket_parameters.mode
129    }
130
131    /// The device pixels per logical pixel that the map draws at.
132    #[must_use]
133    pub fn pixel_ratio(&self) -> f32 {
134        self.parameters.bucket_parameters.pixel_ratio
135    }
136
137    /// The style's global state, which `global-state` expressions read.
138    #[must_use]
139    pub fn global_state(&self) -> Option<&'a Arc<GlobalStateMap>> {
140        self.parameters.bucket_parameters.global_state.as_ref()
141    }
142
143    /// The mapping of the map's world square, which the tile divides and
144    /// `within` and `distance` take its features to lng/lat through.
145    #[must_use]
146    pub fn world(&self) -> &'a WorldMapping {
147        &self.parameters.bucket_parameters.world
148    }
149
150    /// What the layout properties evaluate with: the tile's zoom and the
151    /// style's global state.
152    #[must_use]
153    pub fn parameters(&self) -> PropertyEvaluationParameters {
154        let mut parameters = PropertyEvaluationParameters::new(self.zoom());
155        parameters.global_state = self.global_state().cloned();
156        parameters
157    }
158
159    /// The style's font faces, which draw text in the scripts of their
160    /// ranges, and its fallback faces after them.
161    #[must_use]
162    pub fn font_faces(&self) -> Option<&'a Arc<FontFaces>> {
163        self.parameters.font_faces
164    }
165
166    /// Whether the style has glyphs of its own, a `glyphs` URL.
167    #[must_use]
168    pub fn has_glyphs(&self) -> bool {
169        self.parameters.glyph_pbfs
170    }
171
172    /// The images that exist, which `image` expressions branch on.
173    #[must_use]
174    pub fn available_images(&self) -> &'a VecSet<String> {
175        self.parameters.available_images
176    }
177
178    /// Where `image` expressions record the images they find unavailable.
179    #[must_use]
180    pub fn unavailable_images(&self) -> &'a UnavailableImages {
181        self.parameters.unavailable_images
182    }
183
184    /// The tile's source layer.
185    pub fn source_layer(&self) -> Result<TileLayer<'a>, Error> {
186        self.source_layer.layer()
187    }
188
189    /// The name of the tile's source layer that the layers lay out.
190    #[must_use]
191    pub fn source_layer_name(&self) -> &'a str {
192        &self.source_layer.name
193    }
194
195    /// What the leader's filter evaluates with apart from the feature: the
196    /// tile's zoom, id and world and the style's global state.
197    #[must_use]
198    pub fn filter_context(&self) -> EvaluationContext<'a> {
199        let parameters = self.parameters.bucket_parameters;
200        EvaluationContext::new(self.zoom())
201            .with_canonical_tile_id(Some(&parameters.tile_id.canonical))
202            .with_world(Some(&parameters.world))
203            .with_global_state(parameters.global_state.as_deref())
204    }
205
206    /// The features of `layer`, the tile's source layer, that the leader's
207    /// filter selects, evaluated with `context` ([`filter_context`](Self::filter_context)).
208    pub fn select(&mut self, layer: &TileLayer<'_>, context: EvaluationContext<'a>) -> Selection<'a> {
209        let leader = &self.layers[0].style;
210        let filter = &leader.filter;
211        let passes = |feature: &dyn GeometryTileFeature| {
212            filter.evaluate(&EvaluationContext { feature: Some(feature), ..context })
213        };
214        let selected = self.parameters.filter_groups.select(&leader.source_layer, layer, filter, &context, passes);
215        Selection { selected, filter, context }
216    }
217
218    /// Asks for the style's image `id`, as `kind`, unless it is asked for.
219    pub fn need_image(&mut self, id: &str, kind: ImageType) {
220        if !self.parameters.image_dependencies.contains_key(id) {
221            self.parameters.image_dependencies.insert(id.to_owned(), kind);
222        }
223    }
224
225    /// The glyphs and shapings the layout asks for.
226    pub fn glyphs(&mut self) -> &mut GlyphDependencies {
227        self.parameters.glyph_dependencies
228    }
229}
230
231/// The features of a tile's source layer that a filter selects
232/// ([`LayoutCx::select`]).
233pub struct Selection<'a> {
234    /// Whether the filter selects each feature, where feature groups
235    /// answered it; `None` where it evaluates each feature.
236    selected: Option<Vec<bool>>,
237    filter: &'a Filter,
238    context: EvaluationContext<'a>,
239}
240
241impl Selection<'_> {
242    /// The indexes of the selected features of `layer`, in feature order,
243    /// decoding only those that the filter evaluates.
244    pub fn indexes(&self, layer: &TileLayer<'_>) -> Result<Vec<usize>, Error> {
245        let mut indexes = Vec::new();
246        for i in 0..layer.len() {
247            let selects = match &self.selected {
248                Some(selected) => selected[i],
249                None => self.filter.evaluate(&EvaluationContext { feature: Some(&layer.feature(i)?), ..self.context }),
250            };
251            if selects {
252                indexes.push(i);
253            }
254        }
255        Ok(indexes)
256    }
257
258    /// Whether the filter may select the feature at `index`: false for one
259    /// that its feature group's evaluation rejected, which needn't decode.
260    #[inline]
261    #[must_use]
262    pub fn may_select(&self, index: usize) -> bool {
263        self.selected.as_ref().is_none_or(|selected| selected[index])
264    }
265
266    /// Whether the filter selects `feature`, a feature that it
267    /// [`may_select`](Self::may_select).
268    #[inline]
269    #[must_use]
270    pub fn selects(&self, feature: &dyn GeometryTileFeature) -> bool {
271        self.selected.is_some() || self.filter.evaluate(&EvaluationContext { feature: Some(feature), ..self.context })
272    }
273}
274
275/// What a layout reads and writes while it builds its bucket.
276pub struct BuildCx<'a, T: StyleLayerType> {
277    pub(crate) layers: &'a [Arc<EvaluatedLayer<T>>],
278    pub(crate) parameters: &'a BucketParameters,
279    pub(crate) first_load: bool,
280    pub(crate) source_layer: &'a SourceLayer,
281    pub(crate) resolved: Option<&'a Resolved>,
282    pub(crate) feature_index: &'a mut FeatureIndexBuilder,
283}
284
285impl<'a, T: StyleLayerType> BuildCx<'a, T> {
286    /// The group's layers by id, the first of each id kept.
287    #[must_use]
288    pub fn layers_by_id(&self) -> VecMap<String, Arc<EvaluatedLayer<T>>> {
289        layers_by_id(self.layers)
290    }
291
292    /// The tile.
293    #[must_use]
294    pub fn tile(&self) -> OverscaledTileID {
295        self.parameters.tile_id
296    }
297
298    /// The tile's id, without its overscaling.
299    #[must_use]
300    pub fn canonical(&self) -> &'a CanonicalTileID {
301        &self.parameters.tile_id.canonical
302    }
303
304    /// The mapping of the map's world square, which the tile divides and
305    /// `within` and `distance` take its features to lng/lat through.
306    #[must_use]
307    pub fn world(&self) -> &'a WorldMapping {
308        &self.parameters.world
309    }
310
311    /// The tile's zoom.
312    #[must_use]
313    pub(crate) fn zoom(&self) -> f32 {
314        f32::from(self.parameters.tile_id.overscaled_z)
315    }
316
317    /// How the map renders.
318    #[must_use]
319    pub fn mode(&self) -> MapMode {
320        self.parameters.mode
321    }
322
323    /// Whether the tile had no layout before this one.
324    #[must_use]
325    pub fn first_load(&self) -> bool {
326        self.first_load
327    }
328
329    /// How finely geometry splits to follow the globe's curve.
330    #[must_use]
331    pub fn subdivision_granularity(&self) -> SubdivisionGranularitySetting {
332        self.parameters.subdivision_granularity
333    }
334
335    /// What the glyphs and images the layout asked for resolved to; `None`
336    /// for a layout that asked for none.
337    #[must_use]
338    pub fn resolved(&self) -> Option<&'a Resolved> {
339        self.resolved
340    }
341
342    /// Where the resolved patterns are, or none.
343    #[must_use]
344    pub fn pattern_positions(&self) -> &'a ImagePositions {
345        static NONE: std::sync::LazyLock<ImagePositions> = std::sync::LazyLock::new(ImagePositions::default);
346        self.resolved.map_or(&NONE, |resolved| &resolved.patterns)
347    }
348
349    /// The tile's source layer.
350    pub fn source_layer(&self) -> Result<TileLayer<'a>, Error> {
351        self.source_layer.layer()
352    }
353
354    /// Binders of type `P` for each layer of the group, of its evaluated
355    /// paint values at the tile's zoom.
356    #[must_use]
357    pub fn binders<P>(&self) -> LayerBinders<P>
358    where
359        P: PaintBinders<Paint = <T::PaintProperties as PaintSet>::Evaluated>,
360    {
361        LayerBinders::new(self.layers, self.zoom())
362    }
363
364    /// Writes the values of `feature`, the feature at `index`, into
365    /// `binders` for the vertices up to `vertices`, those added since the
366    /// last call. `section` is the formatted section of the feature's text
367    /// that the vertices draw, which a property's `["get", ..]` of the
368    /// section reads; `patterns` the feature's patterns by layer, which the
369    /// values take where the resolved patterns put them. A layer whose
370    /// vertices draw neither passes `None` for both.
371    pub fn populate<P: PaintBinders>(
372        &self,
373        binders: &mut LayerBinders<P>,
374        index: usize,
375        feature: &dyn GeometryTileFeature,
376        vertices: usize,
377        section: Option<&Value>,
378        patterns: Option<&PatternLayerMap>,
379    ) {
380        static NO_SECTION: Value = Value::Null;
381        let no_patterns = ImagePositions::default();
382        let positions = if patterns.is_some() { self.pattern_positions() } else { &no_patterns };
383        let section = section.unwrap_or(&NO_SECTION);
384        binders.populate(feature, vertices, index, positions, patterns, self.canonical(), self.world(), section);
385    }
386
387    /// Adds `geometry`, the geometry of the feature at `index`, to the
388    /// tile's feature index, which queries search. A layer type that places
389    /// its features leaves them out: queries find what placement shows.
390    pub fn index(&mut self, index: usize, geometry: &GeometryCollection) {
391        let leader = &self.layers[0].style;
392        self.feature_index.insert(geometry, index, &leader.source_layer, &leader.id);
393    }
394}
395
396/// The group's layers by id, the first of each id kept.
397pub fn layers_by_id<T: StyleLayerType>(group: &[Arc<EvaluatedLayer<T>>]) -> VecMap<String, Arc<EvaluatedLayer<T>>> {
398    let mut layers = VecMap::new();
399    for layer in group {
400        layers.entry(layer.style.id.clone()).or_insert_with(|| Arc::clone(layer));
401    }
402    layers
403}