mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! How a layer type lays out a tile's features on a worker: its [`Layout`],
//! which selects the features with a [`LayoutCx`] and builds the bucket
//! with a [`BuildCx`].
//!
//! A `TileLayer` borrows its `TileData`, and the worker keeps layouts with
//! pending dependencies across messages, so layouts keep the indexes of the
//! features they select, and the contexts lend them the layer from the
//! layers that the pass decodes once, when they run.

use std::sync::Arc;

use mln_style::PropertyEvaluationParameters;
use mln_style::collections::{VecMap, VecSet};
use mln_style::crs::WorldMapping;
use mln_style::error::Error;
use mln_style::expression::{EvaluationContext, GlobalStateMap, UnavailableImages, Value};
use mln_style::feature::{GeometryCollection, GeometryTileFeature};
use mln_style::filter::Filter;
use mln_style::layer::{PaintSet, StyleLayerType};
use mln_style::subdivision_granularity::SubdivisionGranularitySetting;
use mln_style::tile_id::CanonicalTileID;

use crate::image::image_store::{ImageDependencies, ImageType};
use crate::layer::bucket::Bucket;
use crate::layer::bucket_parameters::BucketParameters;
use crate::layer::filter_groups::FilterGroups;
use crate::layer::layer_type::EvaluatedLayer;
use crate::layer::paint_property_binder::{LayerBinders, PaintBinders, PatternLayerMap};
use crate::layer::tile_layout::Resolved;
use crate::map::MapMode;
use crate::query::feature_index::FeatureIndexBuilder;
use crate::text::atlas::ImagePositions;
use crate::text::glyph::{FontFaces, GlyphDependencies};
use crate::tile::{LayerSource, OverscaledTileID, TileLayer};

/// How a group of layers of the type `T` that share their layout becomes a
/// tile's bucket, on a tile worker: [`new`](Self::new) selects the tile's
/// features, and once the glyphs and images it asked for are resolved,
/// [`build`](Self::build) makes the bucket.
pub trait Layout<T: StyleLayerType>: Send + Sized + 'static {
    /// The bucket the layout makes.
    type Bucket: Bucket;

    /// Whether the layout of `group` may ask for glyphs or images. The
    /// engine makes such a layout before it resolves them, and builds it
    /// once they are, after every other.
    fn needs_resources(_group: &[Arc<EvaluatedLayer<T>>]) -> bool {
        false
    }

    /// Selects the features of the tile that the bucket draws.
    fn new(cx: &mut LayoutCx<'_, T>) -> Result<Self, Error>;

    /// Makes the bucket of the selected features; `None` for one with
    /// nothing to draw. A feature that fails to decode fails the bucket,
    /// which the engine reports as the tile's error.
    fn build(self, cx: &mut BuildCx<'_, T>) -> Result<Option<Self::Bucket>, Error>;
}

/// The layer `name` of `layers`. The worker only creates layouts for layers
/// the data has, so neither error is expected.
pub(crate) fn source_layer<'a>(layers: &'a dyn LayerSource, name: &str) -> Result<TileLayer<'a>, Error> {
    layers.layer(name)?.ok_or_else(|| Error::failed(format!("the tile data has no layer {name:?}")))
}

/// What a tile's layouts read apart from their group, and where they record
/// the glyphs and images they need.
pub struct LayoutParameters<'a> {
    pub(crate) bucket_parameters: &'a BucketParameters,
    /// The tile's layers, which the group's leader names its own of.
    pub(crate) tile_layers: &'a dyn LayerSource,
    /// The style's font faces, and its fallback faces after them.
    pub(crate) font_faces: Option<&'a Arc<FontFaces>>,
    /// Whether the style has a `glyphs` URL.
    pub(crate) glyph_pbfs: bool,
    pub(crate) glyph_dependencies: &'a mut GlyphDependencies,
    pub(crate) image_dependencies: &'a mut ImageDependencies,
    pub(crate) available_images: &'a VecSet<String>,
    /// Where `image` expressions record the images not in `available_images`.
    pub(crate) unavailable_images: &'a UnavailableImages,
    /// The tile's feature groups, shared by the layouts' filters.
    pub(crate) filter_groups: &'a mut FilterGroups,
}

/// What a layout reads of its tile while it selects features.
pub struct LayoutCx<'a, T: StyleLayerType> {
    pub(crate) layers: &'a [Arc<EvaluatedLayer<T>>],
    pub(crate) parameters: LayoutParameters<'a>,
}

impl<'a, T: StyleLayerType> LayoutCx<'a, T> {
    /// The layers of the group, its leader first, whose style the layout's
    /// layout properties and filter are.
    #[must_use]
    pub fn layers(&self) -> &'a [Arc<EvaluatedLayer<T>>] {
        self.layers
    }

    /// The tile.
    #[must_use]
    pub fn tile(&self) -> OverscaledTileID {
        self.parameters.bucket_parameters.tile_id
    }

    /// The tile's zoom.
    #[must_use]
    pub fn zoom(&self) -> f64 {
        f64::from(self.tile().overscaled_z)
    }

    /// How the map renders.
    #[must_use]
    pub fn mode(&self) -> MapMode {
        self.parameters.bucket_parameters.mode
    }

    /// The device pixels per logical pixel that the map draws at.
    #[must_use]
    pub fn pixel_ratio(&self) -> f32 {
        self.parameters.bucket_parameters.pixel_ratio
    }

    /// The style's global state, which `global-state` expressions read.
    #[must_use]
    pub fn global_state(&self) -> Option<&'a Arc<GlobalStateMap>> {
        self.parameters.bucket_parameters.global_state.as_ref()
    }

    /// The mapping of the map's world square, which the tile divides and
    /// `within` and `distance` take its features to lng/lat through.
    #[must_use]
    pub fn world(&self) -> &'a WorldMapping {
        &self.parameters.bucket_parameters.world
    }

    /// What the layout properties evaluate with: the tile's zoom and the
    /// style's global state.
    #[must_use]
    pub fn parameters(&self) -> PropertyEvaluationParameters {
        let mut parameters = PropertyEvaluationParameters::new(self.zoom());
        parameters.global_state = self.global_state().cloned();
        parameters.canonical = Some(self.tile().canonical);
        parameters
    }

    /// The style's font faces, which draw text in the scripts of their
    /// ranges, and its fallback faces after them.
    #[must_use]
    pub fn font_faces(&self) -> Option<&'a Arc<FontFaces>> {
        self.parameters.font_faces
    }

    /// Whether the style has glyphs of its own, a `glyphs` URL.
    #[must_use]
    pub fn has_glyphs(&self) -> bool {
        self.parameters.glyph_pbfs
    }

    /// The images that exist, which `image` expressions branch on.
    #[must_use]
    pub fn available_images(&self) -> &'a VecSet<String> {
        self.parameters.available_images
    }

    /// Where `image` expressions record the images they find unavailable.
    #[must_use]
    pub fn unavailable_images(&self) -> &'a UnavailableImages {
        self.parameters.unavailable_images
    }

    /// The tile's source layer.
    pub fn source_layer(&self) -> Result<TileLayer<'a>, Error> {
        source_layer(self.parameters.tile_layers, self.source_layer_name())
    }

    /// The name of the tile's source layer that the layers lay out.
    #[must_use]
    pub fn source_layer_name(&self) -> &'a str {
        &self.layers[0].style.source_layer
    }

    /// What the leader's filter evaluates with apart from the feature: the
    /// tile's zoom, id and world and the style's global state.
    #[must_use]
    pub fn filter_context(&self) -> EvaluationContext<'a> {
        let parameters = self.parameters.bucket_parameters;
        EvaluationContext::new(self.zoom())
            .with_canonical_tile_id(Some(&parameters.tile_id.canonical))
            .with_world(Some(&parameters.world))
            .with_global_state(parameters.global_state.as_deref())
    }

    /// The features of `layer`, the tile's source layer, that the leader's
    /// filter selects, evaluated with `context` ([`filter_context`](Self::filter_context)).
    pub fn select(&mut self, layer: &TileLayer<'_>, context: EvaluationContext<'a>) -> Selection<'a> {
        let leader = &self.layers[0].style;
        let filter = &leader.filter;
        let passes = |feature: &dyn GeometryTileFeature| {
            filter.evaluate(&EvaluationContext { feature: Some(feature), ..context })
        };
        let selected = self.parameters.filter_groups.select(&leader.source_layer, layer, filter, &context, passes);
        Selection { selected, filter, context }
    }

    /// Asks for the style's image `id`, as `kind`, unless it is asked for.
    pub fn need_image(&mut self, id: &str, kind: ImageType) {
        if !self.parameters.image_dependencies.contains_key(id) {
            self.parameters.image_dependencies.insert(id.to_owned(), kind);
        }
    }

    /// The glyphs and shapings the layout asks for.
    pub fn glyphs(&mut self) -> &mut GlyphDependencies {
        self.parameters.glyph_dependencies
    }
}

/// The features of a tile's source layer that a filter selects
/// ([`LayoutCx::select`]).
pub struct Selection<'a> {
    /// Whether the filter selects each feature, where feature groups
    /// answered it; `None` where it evaluates each feature.
    selected: Option<Vec<bool>>,
    filter: &'a Filter,
    context: EvaluationContext<'a>,
}

impl Selection<'_> {
    /// The indexes of the selected features of `layer`, in feature order,
    /// decoding only those that the filter evaluates.
    pub fn indexes(&self, layer: &TileLayer<'_>) -> Result<Vec<usize>, Error> {
        let mut indexes = Vec::new();
        for i in 0..layer.len() {
            let selects = match &self.selected {
                Some(selected) => selected[i],
                None => self.filter.evaluate(&EvaluationContext { feature: Some(&layer.feature(i)?), ..self.context }),
            };
            if selects {
                indexes.push(i);
            }
        }
        Ok(indexes)
    }

    /// Whether the filter may select the feature at `index`: false for one
    /// that its feature group's evaluation rejected, which needn't decode.
    #[inline]
    #[must_use]
    pub fn may_select(&self, index: usize) -> bool {
        self.selected.as_ref().is_none_or(|selected| selected[index])
    }

    /// Whether the filter selects `feature`, a feature that it
    /// [`may_select`](Self::may_select).
    #[inline]
    #[must_use]
    pub fn selects(&self, feature: &dyn GeometryTileFeature) -> bool {
        self.selected.is_some() || self.evaluates(feature)
    }

    /// Whether the filter selects `feature`, evaluated on it: for a feature
    /// that isn't one of the selection's layer.
    #[must_use]
    pub fn evaluates(&self, feature: &dyn GeometryTileFeature) -> bool {
        self.filter.evaluate(&EvaluationContext { feature: Some(feature), ..self.context })
    }
}

/// What a layout reads and writes while it builds its bucket.
pub struct BuildCx<'a, T: StyleLayerType> {
    pub(crate) layers: &'a [Arc<EvaluatedLayer<T>>],
    pub(crate) parameters: &'a BucketParameters,
    pub(crate) first_load: bool,
    /// The tile's layers, which the group's leader names its own of.
    pub(crate) tile_layers: &'a dyn LayerSource,
    pub(crate) resolved: Option<&'a Resolved>,
    pub(crate) feature_index: &'a mut FeatureIndexBuilder,
}

impl<'a, T: StyleLayerType> BuildCx<'a, T> {
    /// The layers of the group, its leader first.
    #[must_use]
    pub fn layers(&self) -> &'a [Arc<EvaluatedLayer<T>>] {
        self.layers
    }

    /// The group's layers by id, the first of each id kept.
    #[must_use]
    pub fn layers_by_id(&self) -> VecMap<String, Arc<EvaluatedLayer<T>>> {
        layers_by_id(self.layers)
    }

    /// The tile.
    #[must_use]
    pub fn tile(&self) -> OverscaledTileID {
        self.parameters.tile_id
    }

    /// The tile's id, without its overscaling.
    #[must_use]
    pub fn canonical(&self) -> &'a CanonicalTileID {
        &self.parameters.tile_id.canonical
    }

    /// The mapping of the map's world square, which the tile divides and
    /// `within` and `distance` take its features to lng/lat through.
    #[must_use]
    pub fn world(&self) -> &'a WorldMapping {
        &self.parameters.world
    }

    /// The tile's zoom.
    #[must_use]
    pub(crate) fn zoom(&self) -> f32 {
        f32::from(self.parameters.tile_id.overscaled_z)
    }

    /// The style's global state, which `global-state` expressions read.
    #[must_use]
    pub fn global_state(&self) -> Option<&'a Arc<GlobalStateMap>> {
        self.parameters.global_state.as_ref()
    }

    /// How the map renders.
    #[must_use]
    pub fn mode(&self) -> MapMode {
        self.parameters.mode
    }

    /// Whether the tile had no layout before this one.
    #[must_use]
    pub fn first_load(&self) -> bool {
        self.first_load
    }

    /// How finely geometry splits to follow the globe's curve.
    #[must_use]
    pub fn subdivision_granularity(&self) -> SubdivisionGranularitySetting {
        self.parameters.subdivision_granularity
    }

    /// What the glyphs and images the layout asked for resolved to; `None`
    /// for a layout that asked for none.
    #[must_use]
    pub fn resolved(&self) -> Option<&'a Resolved> {
        self.resolved
    }

    /// Where the resolved patterns are, or none.
    #[must_use]
    pub fn pattern_positions(&self) -> &'a ImagePositions {
        static NONE: std::sync::LazyLock<ImagePositions> = std::sync::LazyLock::new(ImagePositions::default);
        self.resolved.map_or(&NONE, |resolved| &resolved.patterns)
    }

    /// The tile's source layer.
    pub fn source_layer(&self) -> Result<TileLayer<'a>, Error> {
        source_layer(self.tile_layers, &self.layers[0].style.source_layer)
    }

    /// Binders of type `P` for each layer of the group, of its evaluated
    /// paint values at the tile's zoom.
    #[must_use]
    pub fn binders<P>(&self) -> LayerBinders<P>
    where
        P: PaintBinders<Paint = <T::PaintProperties as PaintSet>::Evaluated>,
    {
        LayerBinders::new(self.layers, self.zoom())
    }

    /// Writes the values of `feature`, the feature at `index`, into
    /// `binders` for the vertices up to `vertices`, those added since the
    /// last call. `section` is the formatted section of the feature's text
    /// that the vertices draw, which a property's `["get", ..]` of the
    /// section reads; `patterns` the feature's patterns by layer, which the
    /// values take where the resolved patterns put them. A layer whose
    /// vertices draw neither passes `None` for both.
    pub fn populate<P: PaintBinders>(
        &self,
        binders: &mut LayerBinders<P>,
        index: usize,
        feature: &dyn GeometryTileFeature,
        vertices: usize,
        section: Option<&Value>,
        patterns: Option<&PatternLayerMap>,
    ) {
        static NO_SECTION: Value = Value::Null;
        let no_patterns = ImagePositions::default();
        let positions = if patterns.is_some() { self.pattern_positions() } else { &no_patterns };
        let section = section.unwrap_or(&NO_SECTION);
        binders.populate(feature, vertices, index, positions, patterns, self.canonical(), self.world(), section);
    }

    /// Adds `geometry`, the geometry of the feature at `index`, to the
    /// tile's feature index, which queries search. A layer type that places
    /// its features leaves them out: queries find what placement shows.
    pub fn index(&mut self, index: usize, geometry: &GeometryCollection) {
        let leader = &self.layers[0].style;
        self.feature_index.insert(geometry, index, &leader.source_layer, &leader.id);
    }
}

/// The group's layers by id, the first of each id kept.
pub fn layers_by_id<T: StyleLayerType>(group: &[Arc<EvaluatedLayer<T>>]) -> VecMap<String, Arc<EvaluatedLayer<T>>> {
    let mut layers = VecMap::new();
    for layer in group {
        layers.entry(layer.style.id.clone()).or_insert_with(|| Arc::clone(layer));
    }
    layers
}