Skip to main content

mln_engine/tile/
mvt.rs

1// Tiles are read with fast-mvt's lazy reader: a layer is decoded when it is
2// asked for (once per `MvtLayers`) and a feature when it is read, and tags
3// and geometry are read from the tile's bytes.
4//
5// Errors: a tile whose layers can't be found, or a layer that fast-mvt can't
6// decode, fails `MvtTile::layer`; a feature it can't decode (including
7// malformed packed tags or geometry varints) or whose tags are malformed fails
8// `MvtLayer::feature`, so reading a value afterwards can't fail; a malformed
9// geometry command stream fails `MvtFeature::geometry`.
10
11use std::cell::OnceCell;
12#[cfg(test)]
13use std::collections::BTreeSet;
14use std::ops::{Deref, Range};
15use std::sync::{Arc, OnceLock};
16
17use fast_mvt::{MvtLazyFeature, MvtLazyLayer, MvtLazyReader, MvtValueRef};
18use mln_style::constants::EXTENT;
19use mln_style::feature::{GeometryCollection, Identifier, PropertyMap, Value, ValueRef};
20use mln_style::geometry::{FeatureType, Point};
21use mln_style::hash::HashMap;
22use mln_style::sources::tileset::PromoteId;
23
24use crate::tile::TileError;
25use crate::tile::geometry_tile_data::fixup_polygons;
26use crate::tile::tile_data::FeatureGroups;
27
28/// The MVT geometry types, as fast-mvt reads a feature's type.
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30#[repr(i32)]
31enum MvtGeometryType {
32    Point = 1,
33    LineString = 2,
34    Polygon = 3,
35}
36
37impl MvtGeometryType {
38    fn from_i32(value: i32) -> Option<Self> {
39        match value {
40            1 => Some(MvtGeometryType::Point),
41            2 => Some(MvtGeometryType::LineString),
42            3 => Some(MvtGeometryType::Polygon),
43            _ => None,
44        }
45    }
46}
47
48/// A layer of the tile: its name and its message, as ranges of the tile's
49/// bytes.
50struct LayerEntry {
51    name: Range<usize>,
52    data: Range<usize>,
53}
54
55struct MvtData {
56    bytes: Arc<Vec<u8>>,
57    promote_id: Option<Arc<PromoteId>>,
58    /// The tile's layers in tile order, found on the first lookup.
59    layers: OnceLock<Vec<LayerEntry>>,
60}
61
62/// Mapbox Vector Tile data. Cloning shares the bytes and the layers found in
63/// them.
64#[derive(Clone)]
65pub struct MvtTile(Arc<MvtData>);
66
67impl MvtTile {
68    #[must_use]
69    pub fn new(bytes: Arc<Vec<u8>>) -> Self {
70        Self::with_promote_id(bytes, None)
71    }
72
73    /// Tile data whose features take their ids from the properties that
74    /// `promote_id` names.
75    #[must_use]
76    pub fn with_promote_id(bytes: Arc<Vec<u8>>, promote_id: Option<Arc<PromoteId>>) -> Self {
77        MvtTile(Arc::new(MvtData { bytes, promote_id, layers: OnceLock::new() }))
78    }
79
80    /// The source's `promoteId` that the features take their ids from.
81    #[must_use]
82    pub(crate) fn promote_id(&self) -> Option<&Arc<PromoteId>> {
83        self.0.promote_id.as_ref()
84    }
85
86    /// The tile's bytes.
87    #[must_use]
88    pub fn bytes(&self) -> &Arc<Vec<u8>> {
89        &self.0.bytes
90    }
91
92    /// The tile's layers. Only a successful search is kept: a tile that
93    /// fails is searched again next time.
94    fn layers(&self) -> Result<&[LayerEntry], TileError> {
95        if let Some(layers) = self.0.layers.get() {
96            return Ok(layers);
97        }
98        let bytes = &self.0.bytes;
99        let range = |slice: &[u8]| {
100            let start = slice.as_ptr() as usize - bytes.as_ptr() as usize;
101            start..start + slice.len()
102        };
103        let layers = MvtLazyReader::new(bytes)?
104            .layers()
105            .map(|layer| LayerEntry { name: range(layer.name().as_bytes()), data: range(layer.data()) })
106            .collect();
107        Ok(self.0.layers.get_or_init(|| layers))
108    }
109
110    /// The first layer named `name`: its place among
111    /// [`layers`](Self::layers) and its message.
112    fn find(&self, name: &str) -> Result<Option<(usize, &[u8])>, TileError> {
113        let bytes = &self.0.bytes;
114        let mut layers = self.layers()?.iter().enumerate();
115        let found = layers.find(|(_, entry)| bytes.get(entry.name.clone()) == Some(name.as_bytes()));
116        Ok(found.and_then(|(index, entry)| Some((index, bytes.get(entry.data.clone())?))))
117    }
118
119    /// The first layer named `name`, decoded; `None` if there is none.
120    pub(crate) fn layer(&self, name: &str) -> Result<Option<MvtLayer<'_>>, TileError> {
121        let Some((_, data)) = self.find(name)? else { return Ok(None) };
122        Ok(Some(MvtLayer { layer: Decoded::Owned(MvtLazyLayer::decode(data)?) }))
123    }
124
125    /// Whether the tile has a layer named `name`, found without decoding it.
126    pub(crate) fn has_layer(&self, name: &str) -> Result<bool, TileError> {
127        Ok(self.find(name)?.is_some())
128    }
129
130    /// The names of the tile's layers, each once, in byte order.
131    #[cfg(test)]
132    pub(crate) fn layer_names(&self) -> Result<Vec<String>, TileError> {
133        let bytes = &self.0.bytes;
134        let names: BTreeSet<&[u8]> = self.layers()?.iter().filter_map(|entry| bytes.get(entry.name.clone())).collect();
135        Ok(names.into_iter().map(|name| String::from_utf8_lossy(name).into_owned()).collect())
136    }
137}
138
139/// The layers of an [`MvtTile`], each decoded on its first lookup and kept
140/// for the next.
141pub(crate) struct MvtLayers<'a> {
142    tile: &'a MvtTile,
143    /// By place among the tile's layers.
144    decoded: Box<[OnceCell<MvtLazyLayer<'a>>]>,
145}
146
147impl<'a> MvtLayers<'a> {
148    pub(crate) fn new(tile: &'a MvtTile) -> Self {
149        // A tile whose layers can't be found keeps none: `layer` fails.
150        let count = tile.layers().map_or(0, <[LayerEntry]>::len);
151        MvtLayers { tile, decoded: (0..count).map(|_| OnceCell::new()).collect() }
152    }
153
154    /// [`MvtTile::layer`], decoded once.
155    pub(crate) fn layer(&self, name: &str) -> Result<Option<MvtLayer<'_>>, TileError> {
156        let Some((index, data)) = self.tile.find(name)? else { return Ok(None) };
157        // `find` succeeded, so the tile's layers, which sized `decoded`, were found.
158        let cell = &self.decoded[index];
159        let layer = if let Some(layer) = cell.get() {
160            layer
161        } else {
162            let layer = MvtLazyLayer::decode(data)?;
163            cell.get_or_init(|| layer)
164        };
165        Ok(Some(MvtLayer { layer: Decoded::Kept(layer) }))
166    }
167}
168
169/// A layer of an [`MvtTile`], decoded.
170pub struct MvtLayer<'a> {
171    layer: Decoded<'a>,
172}
173
174/// A decoded layer, its own or one that [`MvtLayers`] keeps.
175enum Decoded<'a> {
176    Owned(MvtLazyLayer<'a>),
177    Kept(&'a MvtLazyLayer<'a>),
178}
179
180impl<'a> Deref for Decoded<'a> {
181    type Target = MvtLazyLayer<'a>;
182
183    fn deref(&self) -> &MvtLazyLayer<'a> {
184        match self {
185            Decoded::Owned(layer) => layer,
186            Decoded::Kept(layer) => layer,
187        }
188    }
189}
190
191impl MvtLayer<'_> {
192    pub(crate) fn name(&self) -> &str {
193        self.layer.name()
194    }
195
196    pub(crate) fn extent(&self) -> u32 {
197        self.layer.extent()
198    }
199
200    pub(crate) fn len(&self) -> usize {
201        self.layer.feature_count()
202    }
203
204    /// The feature at `i`, with its tags checked. Fails with
205    /// [`TileError::OutOfRange`] past the end, and with fast-mvt's error for
206    /// a feature it can't decode or a malformed tag.
207    pub(crate) fn feature(&self, i: usize) -> Result<MvtFeature<'_>, TileError> {
208        let feature = match self.layer.feature(i) {
209            Some(feature) => feature?,
210            None => return Err(TileError::out_of_range(i, self.layer.feature_count())),
211        };
212        for property in feature.properties() {
213            property?;
214        }
215        Ok(MvtFeature { layer: &self.layer, feature })
216    }
217
218    /// Groups by geometry type and by the value-table index of each key's
219    /// first tag, as `value` reads it: equal indices are equal values.
220    /// Equal values at distinct indices only split a group. `None` for a
221    /// malformed feature, leaving its error to `feature`.
222    pub(crate) fn group_features(&self, keys: &[String]) -> Option<FeatureGroups> {
223        /// A key the feature has no tag for.
224        const ABSENT: u32 = u32::MAX;
225        let count = self.layer.feature_count();
226        // Grouping costs about as much as evaluating each feature once.
227        let limit = count / 4 + 8;
228        let value_count = self.layer.values().len();
229        let slots: Vec<Option<usize>> =
230            (self.layer.keys().iter()).map(|key| keys.iter().position(|k| k == key)).collect();
231        let mut index: HashMap<Box<[u32]>, u32> = HashMap::default();
232        let mut codes = vec![ABSENT; keys.len() + 1];
233        let mut groups = FeatureGroups { of_feature: Vec::with_capacity(count), first: Vec::new() };
234        for (i, feature) in self.layer.features().enumerate() {
235            let feature = feature.ok()?;
236            codes.fill(ABSENT);
237            codes[keys.len()] = feature.geom_type_value().unwrap_or(0) as u32;
238            let mut tags = feature.tags();
239            while let Some(key) = tags.next() {
240                let value = tags.next()?;
241                let slot = *slots.get(key as usize)?;
242                if value as usize >= value_count {
243                    return None;
244                }
245                if let Some(slot) = slot
246                    && codes[slot] == ABSENT
247                {
248                    codes[slot] = value;
249                }
250            }
251            let group = if let Some(&group) = index.get(codes.as_slice()) {
252                group
253            } else {
254                if groups.first.len() == limit {
255                    return None;
256                }
257                let group = groups.first.len() as u32;
258                index.insert(codes.as_slice().into(), group);
259                groups.first.push(i);
260                group
261            };
262            groups.of_feature.push(group);
263        }
264        Some(groups)
265    }
266}
267
268/// A feature of an [`MvtLayer`], whose tags are known to be well formed.
269pub struct MvtFeature<'a> {
270    layer: &'a MvtLazyLayer<'a>,
271    feature: MvtLazyFeature<'a, 'a>,
272}
273
274impl MvtFeature<'_> {
275    /// The tags; [`MvtLayer::feature`] checked them.
276    fn tags(&self) -> impl Iterator<Item = (&str, MvtValueRef<'_>)> {
277        self.feature.properties().map_while(Result::ok)
278    }
279
280    pub(crate) fn feature_type(&self) -> FeatureType {
281        match self.feature.geom_type_value().and_then(MvtGeometryType::from_i32) {
282            Some(MvtGeometryType::Point) => FeatureType::Point,
283            Some(MvtGeometryType::LineString) => FeatureType::LineString,
284            Some(MvtGeometryType::Polygon) => FeatureType::Polygon,
285            None => FeatureType::Unknown,
286        }
287    }
288
289    pub(crate) fn id(&self) -> Identifier {
290        self.feature.id().map_or(Identifier::Null, Identifier::Uint)
291    }
292
293    /// The value of the first tag whose key is `key`; `None` for none or a
294    /// null value.
295    pub(crate) fn value_ref(&self, key: &str) -> Option<ValueRef<'_>> {
296        let (_, value) = self.tags().find(|&(tag_key, _)| tag_key == key)?;
297        match to_value_ref(value) {
298            ValueRef::Null => None,
299            value => Some(value),
300        }
301    }
302
303    /// Every property. A repeated key keeps its first value. The tags are
304    /// sorted by key before they are copied, so that the map is built by
305    /// appending and a repeated key is copied once.
306    pub(crate) fn properties(&self) -> PropertyMap {
307        // A feature seldom has a key twice: room for one tag per key.
308        let mut tags = Vec::with_capacity(self.layer.keys().len());
309        tags.extend(self.tags());
310        // Stable, so the first of a repeated key stays first and is kept.
311        tags.sort_by_key(|&(key, _)| key);
312        tags.dedup_by(|(a, _), (b, _)| a == b);
313        tags.into_iter().map(|(key, value)| (key.to_owned(), Value::from(to_value_ref(value)))).collect()
314    }
315
316    /// The geometry, scaled to [`EXTENT`]. Version 1 polygons go
317    /// through [`fixup_polygons`].
318    pub(crate) fn geometry(&self) -> Result<GeometryCollection, TileError> {
319        let scale = EXTENT as f32 / self.layer.extent() as f32;
320        let lines = GeometryCollection::from(
321            decode_geometry(self.feature.geometry_commands(), scale).map_err(TileError::Geometry)?,
322        );
323        Ok(
324            if self.layer.version() < 2
325                && self.feature.geom_type_value().and_then(MvtGeometryType::from_i32) == Some(MvtGeometryType::Polygon)
326            {
327                fixup_polygons(&lines)
328            } else {
329                lines
330            },
331        )
332    }
333}
334
335fn to_value_ref(value: MvtValueRef<'_>) -> ValueRef<'_> {
336    match value {
337        MvtValueRef::String(value) => ValueRef::String(value),
338        MvtValueRef::Float(value) => ValueRef::Double(f64::from(value)),
339        MvtValueRef::Double(value) => ValueRef::Double(value),
340        MvtValueRef::Int(value) | MvtValueRef::SInt(value) => ValueRef::Int(value),
341        MvtValueRef::UInt(value) => ValueRef::Uint(value),
342        MvtValueRef::Bool(value) => ValueRef::Bool(value),
343        MvtValueRef::Null => ValueRef::Null,
344    }
345}
346
347/// Decodes a feature's geometry commands into rings, scaling each
348/// coordinate by `scale` and rounding it. A `MoveTo` starts a new ring
349/// (each point of a multipoint is a ring of its own), a `ClosePath` repeats
350/// the ring's first point, and no commands give one empty ring. Fails for
351/// an unknown command, a command short of its parameters, or a coordinate
352/// outside the `i16` range.
353fn decode_geometry(mut commands: impl Iterator<Item = u32>, scale: f32) -> Result<Vec<Vec<Point<i16>>>, String> {
354    #[derive(Clone, Copy, PartialEq, Eq)]
355    #[repr(u32)]
356    enum MvtCommand {
357        MoveTo = 1,
358        LineTo = 2,
359        ClosePath = 7,
360    }
361
362    impl MvtCommand {
363        fn from_u32(value: u32) -> Option<Self> {
364            match value {
365                1 => Some(MvtCommand::MoveTo),
366                2 => Some(MvtCommand::LineTo),
367                7 => Some(MvtCommand::ClosePath),
368                _ => None,
369            }
370        }
371    }
372
373    /// The most points a command reserves room for: its count comes from
374    /// the tile, unchecked, and a malformed tile mustn't reserve much more
375    /// than it holds.
376    const MAX_RESERVE: usize = 1024 * 1024 / 16;
377
378    let (min, max) = (f32::from(i16::MIN), f32::from(i16::MAX));
379    let mut rings = Vec::new();
380    let mut ring: Vec<Point<i16>> = Vec::new();
381    let (mut x, mut y) = (0i64, 0i64);
382    while let Some(command) = commands.next() {
383        let count = (command >> 3) as usize;
384        match MvtCommand::from_u32(command & 0x7) {
385            Some(id @ (MvtCommand::MoveTo | MvtCommand::LineTo)) => {
386                if id == MvtCommand::LineTo {
387                    // Room for the ClosePath of a polygon ring.
388                    ring.reserve(count.min(MAX_RESERVE) + 1);
389                }
390                for _ in 0..count {
391                    let (Some(dx), Some(dy)) = (commands.next(), commands.next()) else {
392                        return Err("geometry command parameters past the end".to_owned());
393                    };
394                    if id == MvtCommand::MoveTo && !ring.is_empty() {
395                        rings.push(std::mem::take(&mut ring));
396                    }
397                    x = x.wrapping_add(i64::from(zigzag(dx)));
398                    y = y.wrapping_add(i64::from(zigzag(dy)));
399                    let px = (x as f32 * scale).round();
400                    let py = (y as f32 * scale).round();
401                    if px > max || px < min || py > max || py < min {
402                        return Err("geometry coordinates outside the i16 range".to_owned());
403                    }
404                    // A NaN scale passes the range check and becomes 0.
405                    ring.push(Point::new(px as i16, py as i16));
406                }
407            }
408            Some(MvtCommand::ClosePath) => {
409                if let Some(&first) = ring.first() {
410                    ring.push(first);
411                }
412            }
413            None => return Err("unknown command".to_owned()),
414        }
415    }
416    rings.push(ring);
417    Ok(rings)
418}
419
420fn zigzag(value: u32) -> i32 {
421    (value >> 1) as i32 ^ -((value & 1) as i32)
422}
423
424#[cfg(test)]
425mod tests {
426    use std::sync::Arc;
427
428    use fast_mvt::MvtLazyLayer;
429    use mln_style::geometry::Point;
430
431    use super::{MvtLayer, MvtLayers, MvtTile, decode_geometry};
432    use crate::tile::vector_tile_test::MVT;
433
434    #[test]
435    fn layers_decode_each_layer_once() {
436        fn decoded<'a>(layer: &'a MvtLayer<'a>) -> *const MvtLazyLayer<'a> {
437            &raw const *layer.layer
438        }
439        let tile = MvtTile::new(Arc::new(MVT.clone()));
440        let layers = MvtLayers::new(&tile);
441        let [admin, again, water] = ["admin", "admin", "water"].map(|name| layers.layer(name).unwrap().unwrap());
442        assert!(std::ptr::eq(decoded(&admin), decoded(&again)));
443        assert!(!std::ptr::eq(decoded(&admin), decoded(&water)));
444        assert!(layers.layer("missing").unwrap().is_none());
445    }
446
447    fn rings(commands: &[u32], scale: f32) -> Vec<Vec<(i16, i16)>> {
448        let rings = decode_geometry(commands.iter().copied(), scale).unwrap();
449        rings.iter().map(|ring| ring.iter().map(|p: &Point<i16>| (p.x, p.y)).collect()).collect()
450    }
451
452    #[test]
453    fn decodes_rings() {
454        // No commands: one empty ring.
455        assert_eq!(rings(&[], 1.0), vec![vec![]]);
456        // MoveTo(2): each point is a ring.
457        assert_eq!(rings(&[17, 2, 4, 2, 2], 1.0), vec![vec![(1, 2)], vec![(2, 3)]]);
458        // MoveTo, LineTo(2), MoveTo, LineTo(1): two lines.
459        assert_eq!(
460            rings(&[9, 0, 0, 18, 2, 0, 0, 2, 9, 2, 2, 10, 1, 1], 1.0),
461            vec![vec![(0, 0), (1, 0), (1, 1)], vec![(2, 2), (1, 1)]]
462        );
463        // ClosePath repeats the first point; the scale rounds.
464        assert_eq!(rings(&[9, 2, 2, 18, 2, 0, 0, 2, 15], 2.5), vec![vec![(3, 3), (5, 3), (5, 5), (3, 3)]]);
465    }
466
467    #[test]
468    fn rejects_malformed_commands() {
469        let error = |commands: &[u32], scale| decode_geometry(commands.iter().copied(), scale).unwrap_err();
470        assert_eq!(error(&[3], 1.0), "unknown command");
471        assert_eq!(error(&[17, 2, 4, 2], 1.0), "geometry command parameters past the end");
472        assert_eq!(error(&[9, 2, 0], 40000.0), "geometry coordinates outside the i16 range");
473    }
474}