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