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