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