Skip to main content

mln_engine/tile/
mlt.rs

1// MapLibre Tiles are decoded by the mlt-core crate. A tile's layers decode on
2// the first read, all at once, into columns the layer owns: mlt-core's
3// decoded layer borrows the tile's bytes, so it can't be kept beside them.
4// The geometry columns are mlt-core's own; the property columns are copied
5// out with one value or absence per feature. A feature is an index into the
6// columns, and reads its geometry from them when asked.
7//
8// A tile mlt-core can't decode, and one that uses FastPFOR where it isn't
9// enabled, is logged and reads as a tile without layers.
10
11use std::ops::Range;
12use std::sync::{Arc, OnceLock};
13
14use mln_style::constants::EXTENT;
15use mln_style::feature::{GeometryCollection, GeometryCoordinate, GeometryCoordinates, Identifier, PropertyMap, Value};
16use mln_style::geometry::FeatureType;
17use mln_style::hash::HashMap;
18use mln_style::sources::tileset::PromoteId;
19use mlt_core::wire::{Analyze as _, LogicalEncoding, PhysicalEncoding};
20use mlt_core::{GeometryType, GeometryValues, ParsedLayer01, ParsedProperty};
21
22use crate::log_target;
23use crate::tile::TileError;
24use crate::tile::tile_data::FeatureGroups;
25
26struct MltData {
27    bytes: Arc<Vec<u8>>,
28    fast_pfor_enabled: bool,
29    promote_id: Option<Arc<PromoteId>>,
30    /// The decoded layers, in tile order.
31    layers: OnceLock<Vec<Layer>>,
32}
33
34/// MapLibre Tile data. Cloning shares the bytes and the decoded layers.
35#[derive(Clone)]
36pub struct MltTile(Arc<MltData>);
37
38impl MltTile {
39    /// Tile data that decodes `bytes`; with `fast_pfor_enabled` false, a tile
40    /// that uses FastPFOR integer encoding has no layers.
41    #[must_use]
42    pub fn new(bytes: Arc<Vec<u8>>, fast_pfor_enabled: bool) -> Self {
43        Self::with_promote_id(bytes, fast_pfor_enabled, None)
44    }
45
46    /// Tile data whose features take their ids from the properties that
47    /// `promote_id` names.
48    #[must_use]
49    pub fn with_promote_id(bytes: Arc<Vec<u8>>, fast_pfor_enabled: bool, promote_id: Option<Arc<PromoteId>>) -> Self {
50        MltTile(Arc::new(MltData { bytes, fast_pfor_enabled, promote_id, layers: OnceLock::new() }))
51    }
52
53    /// The source's `promoteId` that the features take their ids from.
54    #[must_use]
55    pub(crate) fn promote_id(&self) -> Option<&Arc<PromoteId>> {
56        self.0.promote_id.as_ref()
57    }
58
59    /// The tile's bytes.
60    #[must_use]
61    pub fn bytes(&self) -> &Arc<Vec<u8>> {
62        &self.0.bytes
63    }
64
65    #[must_use]
66    pub(crate) fn fast_pfor_enabled(&self) -> bool {
67        self.0.fast_pfor_enabled
68    }
69
70    fn layers(&self) -> &[Layer] {
71        self.0.layers.get_or_init(|| {
72            decode(&self.0.bytes, self.0.fast_pfor_enabled).unwrap_or_else(|e| {
73                tracing::warn!(target: log_target::PARSE_TILE, error = %e, "MLT parse failed");
74                Vec::new()
75            })
76        })
77    }
78
79    /// The first layer named `name`.
80    pub(crate) fn layer(&self, name: &str) -> Option<MltLayer<'_>> {
81        self.layers().iter().find(|layer| layer.name == name).map(MltLayer)
82    }
83
84    /// The names of the tile's layers, in tile order, duplicates included.
85    #[cfg(test)]
86    pub(crate) fn layer_names(&self) -> Vec<String> {
87        self.layers().iter().map(|layer| layer.name.clone()).collect()
88    }
89}
90
91/// Decodes the tile's layers; a layer of a version mlt-core reads but this
92/// doesn't is skipped.
93fn decode(data: &[u8], fast_pfor_enabled: bool) -> Result<Vec<Layer>, String> {
94    let error = |e: mlt_core::MltError| e.to_string();
95    let mut parser = mlt_core::Parser::default();
96    let mut decoder = mlt_core::Decoder::default();
97    let mut layers = Vec::new();
98    for layer in parser.parse_layers(data).map_err(error)? {
99        let mlt_core::Layer::Tag01(layer) = layer else {
100            continue;
101        };
102        if !fast_pfor_enabled && uses_fast_pfor(&layer) {
103            return Err("FastPFOR decoding is not enabled".to_owned());
104        }
105        layers.push(Layer::new(&layer.decode_all(&mut decoder).map_err(error)?)?);
106    }
107    Ok(layers)
108}
109
110/// Whether an integer or vertex stream of the layer uses FastPFOR.
111fn uses_fast_pfor(layer: &mlt_core::Layer01<'_>) -> bool {
112    let mut found = false;
113    layer.for_each_stream(&mut |meta| {
114        found |= matches!(meta.encoding.physical, PhysicalEncoding::FastPFor(_))
115            && matches!(meta.encoding.logical, LogicalEncoding::Int(_) | LogicalEncoding::Vertex(_));
116    });
117    found
118}
119
120/// A property column: each feature's value, `None` for an absent one.
121enum Values {
122    Bool(Vec<Option<bool>>),
123    Int(Vec<Option<i64>>),
124    Uint(Vec<Option<u64>>),
125    Double(Vec<Option<f64>>),
126    /// The strings back to back, and each feature's byte range in them.
127    Str {
128        data: String,
129        spans: Vec<Option<(u32, u32)>>,
130    },
131}
132
133impl Values {
134    fn strings<'a>(len: usize, get: impl Fn(usize) -> Option<&'a str>) -> Values {
135        let mut data = String::new();
136        let spans = (0..len)
137            .map(|i| {
138                get(i).map(|s| {
139                    let start = data.len() as u32;
140                    data.push_str(s);
141                    (start, data.len() as u32)
142                })
143            })
144            .collect();
145        Values::Str { data, spans }
146    }
147
148    /// The value of feature `i`; `None` for an absent value, also past the
149    /// end of the column.
150    fn get(&self, i: usize) -> Option<Value> {
151        match self {
152            Values::Bool(v) => v.get(i).copied().flatten().map(Value::Bool),
153            Values::Int(v) => v.get(i).copied().flatten().map(Value::Int),
154            Values::Uint(v) => v.get(i).copied().flatten().map(Value::Uint),
155            Values::Double(v) => v.get(i).copied().flatten().map(Value::Double),
156            Values::Str { data, spans } => spans
157                .get(i)
158                .copied()
159                .flatten()
160                .map(|(start, end)| Value::String(data[start as usize..end as usize].to_owned())),
161        }
162    }
163}
164
165struct Column {
166    values: Values,
167    /// Each string's code, numbered by first use, made by the first
168    /// [`Column::codes`]; `None` if the strings are too varied to be worth
169    /// coding.
170    string_codes: OnceLock<Option<Box<[u32]>>>,
171}
172
173/// Equal codes for equal values ([`Column::codes`]).
174struct ValueCodes<'a> {
175    values: &'a Values,
176    strings: &'a [u32],
177}
178
179impl ValueCodes<'_> {
180    /// The code of feature `i`'s value, `None` for an absent value.
181    fn get(&self, i: usize) -> Option<u64> {
182        match self.values {
183            Values::Bool(v) => v.get(i).copied().flatten().map(u64::from),
184            Values::Int(v) => v.get(i).copied().flatten().map(|x| x as u64),
185            Values::Uint(v) => v.get(i).copied().flatten(),
186            Values::Double(v) => v.get(i).copied().flatten().map(f64::to_bits),
187            Values::Str { .. } => self.strings.get(i).copied().filter(|&code| code != u32::MAX).map(u64::from),
188        }
189    }
190}
191
192impl Column {
193    fn new(values: Values) -> Self {
194        Column { values, string_codes: OnceLock::new() }
195    }
196
197    /// A code for each value, equal codes for equal values (equal values may
198    /// differ in code). Numbers and booleans are their bits; strings are
199    /// numbered, on the first call. `None` for a string column with more
200    /// distinct strings than about a quarter of its values.
201    fn codes(&self) -> Option<ValueCodes<'_>> {
202        let strings = match &self.values {
203            Values::Str { data, spans } => self
204                .string_codes
205                .get_or_init(|| {
206                    // Past about a quarter as many strings as values, the codes
207                    // would group little and cost about as much as reading
208                    // every value.
209                    let limit = spans.len() / 4 + 8;
210                    let mut index: HashMap<&str, u32> = HashMap::default();
211                    let mut codes = Vec::with_capacity(spans.len());
212                    for span in spans {
213                        codes.push(match *span {
214                            Some((start, end)) => {
215                                let next = index.len() as u32;
216                                let code = *index.entry(&data[start as usize..end as usize]).or_insert(next);
217                                if index.len() > limit {
218                                    return None;
219                                }
220                                code
221                            }
222                            None => u32::MAX,
223                        });
224                    }
225                    Some(codes.into_boxed_slice())
226                })
227                .as_deref()?,
228            _ => &[],
229        };
230        Some(ValueCodes { values: &self.values, strings })
231    }
232}
233
234/// The triangles of a layer's tessellated polygons.
235struct Triangles {
236    /// Three indices per triangle, each into its feature's decoded vertices
237    /// (see [`GeometryCollection::triangles`]).
238    indices: Arc<[u32]>,
239    /// Each feature's range of `indices`; `None` for a feature without
240    /// triangles.
241    of_feature: Vec<Option<Range<usize>>>,
242}
243
244/// The lines or rings of a feature, as the vertices they take.
245enum Parts {
246    /// A point, or the points of a multi-point, as one line.
247    Points(Vec<usize>),
248    Lines(Vec<Range<usize>>),
249    /// Polygon rings, which decoding closes.
250    Rings(Vec<Range<usize>>),
251}
252
253struct Layer {
254    name: String,
255    extent: u32,
256    geometry: GeometryValues,
257    ids: Option<Vec<Option<u64>>>,
258    /// The property columns in wire order; of two with the same name, the
259    /// first.
260    columns: Vec<(String, Column)>,
261    column_index: HashMap<String, usize>,
262    triangles: Option<Triangles>,
263}
264
265impl Layer {
266    fn new(parsed: &ParsedLayer01<'_>) -> Result<Layer, String> {
267        let mut layer = Layer {
268            name: parsed.name().to_owned(),
269            extent: parsed.extent().get(),
270            geometry: parsed.geometry_values().clone(),
271            ids: parsed.id().map(|id| id.iter_optional().collect()),
272            columns: Vec::new(),
273            column_index: HashMap::default(),
274            triangles: None,
275        };
276        let mut names = parsed.iterate_prop_names().map(|name| name.to_string());
277        let mut next_name = || names.next().ok_or_else(|| "property column count mismatch".to_owned());
278        for column in parsed.properties() {
279            let values = match column {
280                ParsedProperty::Bool(s) => Values::Bool(s.iter_optional().collect()),
281                ParsedProperty::I8(s) => Values::Int(s.iter_optional().map(|v| v.map(i64::from)).collect()),
282                ParsedProperty::U8(s) => Values::Uint(s.iter_optional().map(|v| v.map(u64::from)).collect()),
283                ParsedProperty::I32(s) => Values::Int(s.iter_optional().map(|v| v.map(i64::from)).collect()),
284                ParsedProperty::U32(s) => Values::Uint(s.iter_optional().map(|v| v.map(u64::from)).collect()),
285                ParsedProperty::I64(s) => Values::Int(s.iter_optional().collect()),
286                ParsedProperty::U64(s) => Values::Uint(s.iter_optional().collect()),
287                ParsedProperty::F32(s) => Values::Double(s.iter_optional().map(|v| v.map(f64::from)).collect()),
288                ParsedProperty::F64(s) => Values::Double(s.iter_optional().collect()),
289                ParsedProperty::Str(s) => Values::strings(s.feature_count(), |i| s.get(i as u32)),
290                ParsedProperty::SharedDict(dict) => {
291                    // One column per child, named prefix + suffix.
292                    for item in dict.items() {
293                        let values = Values::strings(item.feature_count(), |i| item.get(dict, i));
294                        layer.insert_column(next_name()?, values);
295                    }
296                    continue;
297                }
298                _ => return Err(format!("unsupported property column type {:?}", column.kind())),
299            };
300            layer.insert_column(next_name()?, values);
301        }
302        layer.triangles = layer.triangles();
303        Ok(layer)
304    }
305
306    fn insert_column(&mut self, name: String, values: Values) {
307        if !self.column_index.contains_key(&name) {
308            self.column_index.insert(name.clone(), self.columns.len());
309            self.columns.push((name, Column::new(values)));
310        }
311    }
312
313    fn column(&self, key: &str) -> Option<&Column> {
314        self.column_index.get(key).map(|&i| &self.columns[i].1)
315    }
316
317    fn len(&self) -> usize {
318        self.geometry.feature_count()
319    }
320
321    fn feature_type(&self, index: usize) -> FeatureType {
322        match self.geometry.vector_types()[index] {
323            GeometryType::Point | GeometryType::MultiPoint => FeatureType::Point,
324            GeometryType::LineString | GeometryType::MultiLineString => FeatureType::LineString,
325            GeometryType::Polygon | GeometryType::MultiPolygon => FeatureType::Polygon,
326        }
327    }
328
329    /// The lines or rings of feature `index`.
330    fn parts(&self, index: usize) -> Result<Parts, TileError> {
331        let values = &self.geometry;
332        let geometry_type = values.vector_types()[index];
333        let geoms = values.geometry_offsets();
334        let parts = values.part_offsets();
335        let rings = values.ring_offsets();
336        let malformed = |what: &str| TileError::Geometry(format!("MLT {what} out of range"));
337        let offset =
338            |level: &[u32], i: usize, what: &str| level.get(i).map(|&v| v as usize).ok_or_else(|| malformed(what));
339        let span = |level: &[u32], i: usize, what: &str| {
340            Ok::<_, TileError>(offset(level, i, what)?..offset(level, i + 1, what)?)
341        };
342        let no_topology = || TileError::Geometry(format!("MLT {geometry_type} geometry without topology"));
343        // The geometry, else this feature's first part.
344        let first = |i: usize| geoms.map_or(Ok(i), |g| offset(g, i, "geometry offset"));
345        // A line: a range of rings, else of parts.
346        let line = |part: usize, p: &[u32]| match rings {
347            Some(r) => span(r, offset(p, part, "part offset")?, "ring offset"),
348            None => span(p, part, "part offset"),
349        };
350
351        if parts.is_none() && values.index_buffer().is_some() {
352            // Tessellated without topology: only points can be read.
353            return match geometry_type {
354                GeometryType::Point => Ok(Parts::Points(vec![index])),
355                _ => Err(no_topology()),
356            };
357        }
358        Ok(match geometry_type {
359            GeometryType::Point => {
360                let mut i = first(index)?;
361                if let Some(p) = parts {
362                    i = offset(p, i, "part offset")?;
363                }
364                if let Some(r) = rings {
365                    i = offset(r, i, "ring offset")?;
366                }
367                Parts::Points(vec![i])
368            }
369            GeometryType::MultiPoint => {
370                let g = geoms.ok_or_else(no_topology)?;
371                let mut points = Vec::new();
372                for i in span(g, index, "geometry offset")? {
373                    points.push(match (parts, rings) {
374                        (Some(p), Some(r)) => offset(r, offset(p, i, "part offset")?, "ring offset")?,
375                        (Some(p), None) => offset(p, i, "part offset")?,
376                        (None, _) => i,
377                    });
378                }
379                Parts::Points(points)
380            }
381            GeometryType::LineString => Parts::Lines(vec![line(first(index)?, parts.ok_or_else(no_topology)?)?]),
382            GeometryType::MultiLineString => {
383                let lines = span(geoms.ok_or_else(no_topology)?, index, "geometry offset")?;
384                let mut result = Vec::with_capacity(lines.len());
385                for i in lines {
386                    result.push(line(i, parts.ok_or_else(no_topology)?)?);
387                }
388                Parts::Lines(result)
389            }
390            GeometryType::Polygon => {
391                let (p, r) = (parts.ok_or_else(no_topology)?, rings.ok_or_else(no_topology)?);
392                let mut result = Vec::new();
393                for i in span(p, first(index)?, "part offset")? {
394                    result.push(span(r, i, "ring offset")?);
395                }
396                Parts::Rings(result)
397            }
398            GeometryType::MultiPolygon => {
399                let polygons = span(geoms.ok_or_else(no_topology)?, index, "geometry offset")?;
400                let mut result = Vec::new();
401                for polygon in polygons {
402                    let (p, r) = (parts.ok_or_else(no_topology)?, rings.ok_or_else(no_topology)?);
403                    for i in span(p, polygon, "part offset")? {
404                        result.push(span(r, i, "ring offset")?);
405                    }
406                }
407                Parts::Rings(result)
408            }
409        })
410    }
411
412    /// The geometry of feature `index`, scaled to [`EXTENT`]. Decoding
413    /// closes polygon rings, which the tile stores without their closing
414    /// vertex.
415    fn geometry(&self, index: usize) -> Result<GeometryCollection, TileError> {
416        let vertices = self.geometry.vertices().unwrap_or(&[]);
417        let scale = f64::from(EXTENT) / f64::from(self.extent);
418        let vertex = |i: usize| -> Result<GeometryCoordinate, TileError> {
419            let v = vertices
420                .get(2 * i..2 * i + 2)
421                .ok_or_else(|| TileError::Geometry("MLT vertex out of range".to_owned()))?;
422            let convert = |c: i32| (f64::from(c) * scale).round() as i16;
423            Ok(GeometryCoordinate::new(convert(v[0]), convert(v[1])))
424        };
425        let line = |range: Range<usize>, close: bool| -> Result<GeometryCoordinates, TileError> {
426            let mut coords = Vec::with_capacity(range.len() + usize::from(close));
427            for i in range.clone() {
428                coords.push(vertex(i)?);
429            }
430            if close && let Some(&first) = coords.first() {
431                coords.push(first);
432            }
433            Ok(coords)
434        };
435        let mut geometry = match self.parts(index)? {
436            Parts::Points(points) => {
437                GeometryCollection::from(vec![points.into_iter().map(vertex).collect::<Result<Vec<_>, _>>()?])
438            }
439            Parts::Lines(lines) => {
440                GeometryCollection::from(lines.into_iter().map(|l| line(l, false)).collect::<Result<Vec<_>, _>>()?)
441            }
442            Parts::Rings(rings) => {
443                GeometryCollection::from(rings.into_iter().map(|r| line(r, true)).collect::<Result<Vec<_>, _>>()?)
444            }
445        };
446        if let Some(triangles) = &self.triangles
447            && let Some(Some(range)) = triangles.of_feature.get(index)
448        {
449            geometry.set_triangles(Arc::clone(&triangles.indices), range.clone());
450        }
451        Ok(geometry)
452    }
453
454    /// The triangles of the tessellated polygons: each polygon and
455    /// multi-polygon takes the next count of triangles from the index
456    /// buffer. A feature whose triangles name a vertex it doesn't have, or
457    /// that the counts run out before, has none.
458    fn triangles(&self) -> Option<Triangles> {
459        let values = &self.geometry;
460        let (indices, counts) = (values.index_buffer()?, values.triangle_offsets()?);
461        let mut rebased = Vec::with_capacity(indices.len());
462        let mut of_feature = vec![None; self.len()];
463        let (mut ring_lens, mut ring_shifts) = (Vec::new(), Vec::new());
464        let mut runs = counts.windows(2);
465        for (index, &t) in values.vector_types().iter().enumerate() {
466            if !matches!(t, GeometryType::Polygon | GeometryType::MultiPolygon) {
467                continue;
468            }
469            let Some(run) = runs.next() else { break };
470            let Some(corners) = indices.get(run[0] as usize * 3..run[1] as usize * 3) else { break };
471            if corners.is_empty() {
472                continue;
473            }
474            let (Ok(Parts::Rings(rings)), Ok(vertices)) = (self.parts(index), values.vertex_range(index)) else {
475                continue;
476            };
477            ring_lens.clear();
478            ring_lens.extend(rings.iter().map(|r| (r.len() as u32, (r.len() + usize::from(!r.is_empty())) as u32)));
479            let first = rebased.len();
480            if rebase_triangles(corners, vertices.start as u32, &ring_lens, &mut ring_shifts, &mut rebased) {
481                of_feature[index] = Some(first..rebased.len());
482            }
483        }
484        Some(Triangles { indices: Arc::from(rebased), of_feature })
485    }
486
487    /// Groups by geometry type and by each key's value code
488    /// ([`Column::codes`]): equal codes are equal values, and equal values
489    /// with distinct codes only split a group. A key without a column is
490    /// absent from every feature.
491    fn group_features(&self, keys: &[String]) -> Option<FeatureGroups> {
492        let count = self.len();
493        // Grouping costs about as much as evaluating each feature once.
494        let limit = count / 4 + 8;
495        let columns: Vec<ValueCodes<'_>> =
496            keys.iter().filter_map(|key| self.column(key)).map(Column::codes).collect::<Option<_>>()?;
497        let mut index: HashMap<Box<[Option<u64>]>, u32> = HashMap::default();
498        let mut codes = vec![None; columns.len() + 1];
499        let mut groups = FeatureGroups { of_feature: Vec::with_capacity(count), first: Vec::new() };
500        for i in 0..count {
501            codes[columns.len()] = Some(self.feature_type(i) as u64);
502            for (code, column) in codes.iter_mut().zip(&columns) {
503                *code = column.get(i);
504            }
505            let group = if let Some(&group) = index.get(codes.as_slice()) {
506                group
507            } else {
508                if groups.first.len() == limit {
509                    return None;
510                }
511                let group = groups.first.len() as u32;
512                index.insert(codes.as_slice().into(), group);
513                groups.first.push(i);
514                group
515            };
516            groups.of_feature.push(group);
517        }
518        Some(groups)
519    }
520}
521
522/// A layer of an [`MltTile`].
523#[derive(Clone, Copy)]
524pub struct MltLayer<'a>(&'a Layer);
525
526impl<'a> MltLayer<'a> {
527    pub(crate) fn name(self) -> &'a str {
528        &self.0.name
529    }
530
531    pub(crate) fn extent(self) -> u32 {
532        self.0.extent
533    }
534
535    pub(crate) fn len(self) -> usize {
536        self.0.len()
537    }
538
539    /// The feature at `index`; fails with [`TileError::OutOfRange`] past the
540    /// end.
541    pub(crate) fn feature(self, index: usize) -> Result<MltFeature<'a>, TileError> {
542        if index < self.len() {
543            Ok(MltFeature { layer: self.0, index })
544        } else {
545            Err(TileError::out_of_range(index, self.len()))
546        }
547    }
548
549    pub(crate) fn group_features(self, keys: &[String]) -> Option<FeatureGroups> {
550        self.0.group_features(keys)
551    }
552}
553
554/// A feature of an [`MltLayer`].
555#[derive(Clone, Copy)]
556pub struct MltFeature<'a> {
557    layer: &'a Layer,
558    index: usize,
559}
560
561impl MltFeature<'_> {
562    pub(crate) fn feature_type(&self) -> FeatureType {
563        self.layer.feature_type(self.index)
564    }
565
566    pub(crate) fn id(&self) -> Identifier {
567        let id = self.layer.ids.as_ref().and_then(|ids| ids.get(self.index).copied().flatten());
568        id.map_or(Identifier::Null, Identifier::Uint)
569    }
570
571    pub(crate) fn value(&self, key: &str) -> Option<Value> {
572        self.layer.column(key)?.values.get(self.index)
573    }
574
575    /// Every property; an absent value is a null.
576    pub(crate) fn properties(&self) -> PropertyMap {
577        (self.layer.columns.iter())
578            .map(|(key, column)| (key.clone(), column.values.get(self.index).unwrap_or(Value::Null)))
579            .collect()
580    }
581
582    pub(crate) fn geometry(&self) -> Result<GeometryCollection, TileError> {
583        self.layer.geometry(self.index)
584    }
585}
586
587/// Appends `corners`, the triangles of a feature as indices of the layer's
588/// vertices, to `out` as indices of the feature's decoded vertices; returns
589/// `false`, appending nothing, when a corner is not one of the feature's
590/// vertices.
591///
592/// `first_vertex` is the feature's first vertex in the layer, and `rings`
593/// the stored and decoded vertex counts of its rings. A ring decodes one
594/// vertex longer than it is stored when decoding closes it, which moves the
595/// vertices of the rings after it up by one. `ring_shifts` is scratch space.
596fn rebase_triangles(
597    corners: &[u32],
598    first_vertex: u32,
599    rings: &[(u32, u32)],
600    ring_shifts: &mut Vec<(u32, u32)>,
601    out: &mut Vec<u32>,
602) -> bool {
603    // The first stored vertex of each ring, and how far decoding moves it.
604    ring_shifts.clear();
605    let (mut stored, mut decoded) = (0u32, 0u32);
606    for &(stored_len, decoded_len) in rings {
607        ring_shifts.push((stored, decoded - stored));
608        stored += stored_len;
609        decoded += decoded_len;
610    }
611    // Only a closing vertex before the last ring moves any corner.
612    let moved = ring_shifts.last().is_some_and(|&(_, shift)| shift > 0);
613    let first = out.len();
614    for &corner in corners {
615        let i = corner.wrapping_sub(first_vertex);
616        if i >= stored {
617            out.truncate(first);
618            return false;
619        }
620        let shift = if moved { ring_shifts[ring_shifts.partition_point(|&(start, _)| start <= i) - 1].1 } else { 0 };
621        out.push(i + shift);
622    }
623    true
624}
625
626#[cfg(test)]
627mod tests {
628    use std::path::Path;
629
630    use geometry::Point;
631    use mln_style::feature::Value;
632    use mlt_core::encoder::{EncoderConfig, Network, Profile};
633    use mlt_core::geo_types::Coord;
634    use mlt_core::{LayerWriter, PropKind};
635
636    use super::*;
637
638    /// A layer "l" with a multi-point, a polygon and a line, an 8-bit
639    /// integer column, and a string column the line lacks.
640    fn tile() -> Vec<u8> {
641        let mut layer = LayerWriter::new("l", 2 * EXTENT as u32).unwrap();
642        let small = layer.add_property("small", PropKind::I8).unwrap();
643        let name = layer.add_property("name", PropKind::Str).unwrap();
644        let points = [Coord { x: 2, y: 4 }, Coord { x: 6, y: 8 }];
645        let ring = [Coord { x: 0, y: 0 }, Coord { x: 100, y: 0 }, Coord { x: 100, y: 100 }];
646        for (i, geometry_type) in
647            [GeometryType::MultiPoint, GeometryType::Polygon, GeometryType::LineString].into_iter().enumerate()
648        {
649            let mut feature = layer.feature(geometry_type);
650            match geometry_type {
651                GeometryType::MultiPoint => feature.points(points),
652                GeometryType::Polygon => feature.exterior_ring(ring),
653                _ => feature.line(points),
654            }
655            .unwrap();
656            feature.id(Some(i as u64 + 10));
657            feature.property(small, -(i as i8)).unwrap();
658            if geometry_type != GeometryType::LineString {
659                feature.property(name, "n").unwrap();
660            }
661            feature.finish().unwrap();
662        }
663        layer.encode(EncoderConfig::from_profile(Profile::Web(Network::Offline))).unwrap()
664    }
665
666    #[test]
667    fn features_read_their_columns() {
668        let tile = MltTile::new(Arc::new(tile()), false);
669        let layer = tile.layer("l").unwrap();
670        assert_eq!((layer.name(), layer.len()), ("l", 3));
671        let [multi_point, polygon, line] = [0, 1, 2].map(|i| layer.feature(i).unwrap());
672        assert!(layer.feature(3).is_err());
673
674        // A multi-point is a point feature, its points one line; an extent
675        // of twice `util::EXTENT` halves the coordinates.
676        assert_eq!(multi_point.feature_type(), FeatureType::Point);
677        assert_eq!(*multi_point.geometry().unwrap(), [vec![Point::new(1, 2), Point::new(3, 4)]]);
678        assert_eq!(multi_point.id(), Identifier::Uint(10));
679        // Decoding closes a polygon's rings.
680        assert_eq!(polygon.feature_type(), FeatureType::Polygon);
681        assert_eq!(
682            *polygon.geometry().unwrap(),
683            [vec![Point::new(0, 0), Point::new(50, 0), Point::new(50, 50), Point::new(0, 0)]]
684        );
685        assert_eq!(line.feature_type(), FeatureType::LineString);
686
687        // 8-bit integers read as integers; an absent value is none, and a
688        // null among the properties.
689        assert_eq!(polygon.value("small"), Some(Value::Int(-1)));
690        assert_eq!(polygon.value("name"), Some(Value::String("n".to_owned())));
691        assert_eq!(line.value("name"), None);
692        assert_eq!(line.properties().get("name"), Some(&Value::Null));
693        assert_eq!(line.value("nothing"), None);
694    }
695
696    /// Clones share one decoding, which threads may race to make.
697    #[test]
698    fn clones_share_the_decoded_layers() {
699        let path = Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap())
700            .join("testdata/test/fixtures/map/issue12432/0-0-0.mlt");
701        let tile = MltTile::new(Arc::new(std::fs::read(path).unwrap()), false);
702        let layers: Vec<usize> = std::thread::scope(|scope| {
703            let threads: Vec<_> = (0..4)
704                .map(|_| {
705                    let tile = tile.clone();
706                    scope.spawn(move || std::ptr::from_ref(tile.layer("admin").unwrap().0) as usize)
707                })
708                .collect();
709            threads.into_iter().map(|thread| thread.join().unwrap()).collect()
710        });
711        let here = std::ptr::from_ref(tile.layer("admin").unwrap().0) as usize;
712        assert!(layers.iter().all(|&layer| layer == here));
713    }
714
715    fn rebase(corners: &[u32], first_vertex: u32, rings: &[(u32, u32)]) -> Option<Vec<u32>> {
716        let mut out = vec![7];
717        let ok = rebase_triangles(corners, first_vertex, rings, &mut Vec::new(), &mut out);
718        assert_eq!(out[0], 7, "kept what was there");
719        ok.then(|| out[1..].to_vec())
720    }
721
722    #[test]
723    fn rebases_corners_past_closing_vertices() {
724        // A ring of 4 stored vertices closed by decoding, an empty ring, a
725        // ring stored closed, and a ring closed by decoding.
726        let rings = [(4, 5), (0, 0), (3, 3), (3, 4)];
727        assert_eq!(rebase(&[10, 13, 14, 16, 17, 19], 10, &rings), Some(vec![0, 3, 5, 7, 8, 10]));
728        // One ring: its closing vertex moves nothing.
729        assert_eq!(rebase(&[2, 3, 5], 2, &[(4, 5)]), Some(vec![0, 1, 3]));
730    }
731
732    #[test]
733    fn rejects_corners_outside_the_feature() {
734        let rings = [(4, 5), (3, 4)];
735        // Past the feature's last vertex.
736        assert_eq!(rebase(&[0, 1, 7], 0, &rings), None);
737        // Before its first.
738        assert_eq!(rebase(&[5, 6, 4], 5, &rings), None);
739        assert_eq!(rebase(&[0, 1, 2], 0, &[]), None);
740    }
741}