Skip to main content

mln_engine/tile/
cut.rs

1//! Tiles deeper than their tileset's last zoom, cut from its tiles there.
2//!
3//! The tiles cut from one tile share its data as an [`Ancestor`], which
4//! decodes each layer they read once, and keeps where each feature lies, so
5//! that a cut tile clips only the features that reach it ([`CutData`]), as in
6//! GL JS.
7
8use std::borrow::Cow;
9use std::sync::Arc;
10
11use geometry::Point;
12use mln_style::constants::EXTENT;
13use mln_style::feature::{
14    GeometryCollection, GeometryCoordinates, GeometryTileFeature, Identifier, PropertyMap, Value,
15};
16use mln_style::geometry::FeatureType;
17use mln_style::hash::HashMap;
18use mln_style::tile_id::CanonicalTileID;
19use mln_wire::{Reader, Wire, Writer, shared};
20use parking_lot::Mutex;
21
22use crate::tile::TileError;
23use crate::tile::tile_data::{TileData, TileLayer};
24
25/// How far a cut tile's geometry reaches past its edges, in its units, for
26/// a source layer of `extent` units across: 128 of these, and no less than 16
27/// pixels of a 512-pixel tile, as in GL JS, so that the ends that clipping
28/// makes of lines stay off screen.
29fn buffer(extent: u32) -> i64 {
30    let extent = i64::from(extent.max(1));
31    let units = ((extent + 16) / 32).max(128);
32    units * i64::from(EXTENT) / extent
33}
34
35/// Where a tile lies in the tile of a shallower zoom it's cut from.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct Cut {
38    /// How many zooms deeper the tile is.
39    pub(crate) dz: u8,
40    /// The tile's column and row among the `2^dz` by `2^dz` tiles that the
41    /// source tile holds.
42    pub(crate) x: u32,
43    pub(crate) y: u32,
44}
45
46impl Cut {
47    /// Where `tile` lies in its ancestor at zoom `z`; `None` unless `tile`
48    /// is deeper.
49    #[must_use]
50    pub fn of(tile: &CanonicalTileID, z: u8) -> Option<Cut> {
51        let dz = tile.z.checked_sub(z).filter(|&dz| dz > 0)?;
52        let mask = (1u64 << dz) - 1;
53        Some(Cut { dz, x: (u64::from(tile.x) & mask) as u32, y: (u64::from(tile.y) & mask) as u32 })
54    }
55
56    /// The part of the source tile, in its units and widened to whole ones,
57    /// that the cut tile and `buffer` around it cover.
58    fn reach(&self, buffer: i64) -> Bounds {
59        let size = 1i64 << self.dz;
60        let edge = |at: u32, end: i64| (i64::from(at) + end) * i64::from(EXTENT);
61        let (x0, y0) = ((edge(self.x, 0) - buffer).div_euclid(size), (edge(self.y, 0) - buffer).div_euclid(size));
62        let ceil = |at: i64| (at + size - 1).div_euclid(size);
63        let (x1, y1) = (ceil(edge(self.x, 1) + buffer), ceil(edge(self.y, 1) + buffer));
64        Bounds { min: [x0, y0], max: [x1, y1] }
65    }
66
67    /// `geometry` of the source tile, as a feature of `kind` of a layer of
68    /// `extent` units across, in the cut tile's units, clipped to the cut
69    /// tile and its buffer as GL JS clips it: each point of a multipoint, each piece of a line that leaves and
70    /// comes back, and each ring are geometries of their own, and a ring
71    /// that leaves runs along the edge it left by. Empty if nothing is
72    /// left.
73    #[must_use]
74    pub(crate) fn geometry(&self, kind: FeatureType, geometry: &GeometryCollection, extent: u32) -> GeometryCollection {
75        let scale = (1u64 << self.dz) as f64;
76        let offset = [f64::from(self.x) * f64::from(EXTENT), f64::from(self.y) * f64::from(EXTENT)];
77        let rings: Vec<Vec<P>> = geometry
78            .iter()
79            .map(|ring| {
80                ring.iter().map(|p| [f64::from(p.x) * scale - offset[0], f64::from(p.y) * scale - offset[1]]).collect()
81            })
82            .collect();
83        let buffer = buffer(extent);
84        let (start, end) = (-buffer as f64, (i64::from(EXTENT) + buffer) as f64);
85        let clipped = clip_on_axis(clip_on_axis(rings, kind, start, end, 0), kind, start, end, 1);
86        // Every coordinate is within the buffer, so an `i16`.
87        let round = |p: P| Point::new(p[0].round() as i16, p[1].round() as i16);
88        GeometryCollection::from(
89            clipped
90                .into_iter()
91                .map(|ring| ring.into_iter().map(round).collect::<GeometryCoordinates>())
92                .collect::<Vec<_>>(),
93        )
94    }
95}
96
97/// A point, its `x` then `y`, for code that works on either axis.
98type P = [f64; 2];
99
100/// Clips `rings` to `start..=end` on `axis` (0 for `x`).
101fn clip_on_axis(rings: Vec<Vec<P>>, kind: FeatureType, start: f64, end: f64, axis: usize) -> Vec<Vec<P>> {
102    match kind {
103        FeatureType::Point => {
104            rings.into_iter().flatten().filter(|p| (start..=end).contains(&p[axis])).map(|p| vec![p]).collect()
105        }
106        FeatureType::LineString => rings.iter().flat_map(|line| clip_line(line, start, end, axis, false)).collect(),
107        FeatureType::Polygon => rings.iter().flat_map(|ring| clip_line(ring, start, end, axis, true)).collect(),
108        FeatureType::Unknown => Vec::new(),
109    }
110}
111
112/// The parts of `line` within `start..=end` on `axis`; for a `polygon`'s
113/// ring, the one ring that runs along the bounds where it left them.
114fn clip_line(line: &[P], start: f64, end: f64, axis: usize, polygon: bool) -> Vec<Vec<P>> {
115    let Some(&last) = line.last() else { return Vec::new() };
116    let mut slice: Vec<P> = Vec::new();
117    let mut parts = Vec::new();
118    for pair in line.windows(2) {
119        let (p1, p2) = (pair[0], pair[1]);
120        let (a, b) = (p1[axis], p2[axis]);
121        let mut exited = false;
122        if a < start {
123            if b >= start {
124                slice.push(intersection(p1, p2, start, axis));
125            }
126        } else if a > end {
127            if b <= end {
128                slice.push(intersection(p1, p2, end, axis));
129            }
130        } else {
131            slice.push(p1);
132        }
133        if b < start && a >= start {
134            slice.push(intersection(p1, p2, start, axis));
135            exited = true;
136        }
137        if b > end && a <= end {
138            slice.push(intersection(p1, p2, end, axis));
139            exited = true;
140        }
141        if !polygon && exited {
142            parts.push(std::mem::take(&mut slice));
143        }
144    }
145    if (start..=end).contains(&last[axis]) {
146        slice.push(last);
147    }
148    if polygon
149        && let (Some(&first), Some(&closing)) = (slice.first(), slice.last())
150        && first != closing
151    {
152        slice.push(first);
153    }
154    if !slice.is_empty() {
155        parts.push(slice);
156    }
157    parts
158}
159
160/// The point of `p1`–`p2` whose `axis` coordinate is `at`.
161fn intersection(p1: P, p2: P, at: f64, axis: usize) -> P {
162    let other = 1 - axis;
163    let t = (at - p1[axis]) / (p2[axis] - p1[axis]);
164    let mut p = [0.0; 2];
165    p[axis] = at;
166    p[other] = p1[other] + (p2[other] - p1[other]) * t;
167    p
168}
169
170/// A box in a tile's units, its edges included.
171#[derive(Clone, Copy, Debug, PartialEq, Eq)]
172struct Bounds {
173    min: [i64; 2],
174    max: [i64; 2],
175}
176
177impl Bounds {
178    /// The bounds of `geometry`'s points; `None` if it has none.
179    fn of(geometry: &GeometryCollection) -> Option<Bounds> {
180        let mut points = geometry.iter().flatten();
181        let first = points.next()?;
182        let mut bounds = Bounds { min: [first.x.into(), first.y.into()], max: [first.x.into(), first.y.into()] };
183        for p in points {
184            for (axis, at) in [i64::from(p.x), i64::from(p.y)].into_iter().enumerate() {
185                bounds.min[axis] = bounds.min[axis].min(at);
186                bounds.max[axis] = bounds.max[axis].max(at);
187            }
188        }
189        Some(bounds)
190    }
191
192    fn overlaps(&self, other: &Bounds) -> bool {
193        (0..2).all(|axis| self.min[axis] <= other.max[axis] && other.min[axis] <= self.max[axis])
194    }
195}
196
197/// A tile's data at its tileset's last zoom, which the deeper tiles cut from
198/// it share, and each of its layers that they have read, decoded once for
199/// all of them and kept while any of them is.
200pub struct Ancestor {
201    data: TileData,
202    /// By layer name; `None` for a layer the data lacks.
203    layers: Mutex<HashMap<String, Option<Arc<AncestorLayer>>>>,
204}
205
206/// An ancestor's layer, decoded once for all the tiles cut from it.
207struct AncestorLayer {
208    name: String,
209    /// The units across the tile of the layer as encoded.
210    extent: u32,
211    features: Vec<AncestorFeature>,
212}
213
214/// A feature of an [`AncestorLayer`], and where it lies.
215struct AncestorFeature {
216    kind: FeatureType,
217    id: Identifier,
218    properties: Arc<PropertyMap>,
219    geometry: GeometryCollection,
220    /// `None` for a feature without points.
221    bounds: Option<Bounds>,
222}
223
224impl Ancestor {
225    #[must_use]
226    pub fn new(data: TileData) -> Self {
227        Ancestor { data, layers: Mutex::default() }
228    }
229
230    #[must_use]
231    pub fn data(&self) -> &TileData {
232        &self.data
233    }
234
235    /// Layer `name`, decoded; `None` if the data has none.
236    fn layer(&self, name: &str) -> Result<Option<Arc<AncestorLayer>>, TileError> {
237        if let Some(layer) = self.layers.lock().get(name) {
238            return Ok(layer.clone());
239        }
240        // Decoded unlocked: a cut tile reading another layer needn't wait.
241        let layer = match self.data.layer(name)? {
242            Some(layer) => Some(Arc::new(AncestorLayer::decode(&layer)?)),
243            None => None,
244        };
245        Ok(self.layers.lock().entry(name.to_owned()).or_insert(layer).clone())
246    }
247}
248
249impl AncestorLayer {
250    fn decode(layer: &TileLayer<'_>) -> Result<AncestorLayer, TileError> {
251        let features = (0..layer.len())
252            .map(|index| {
253                let feature = layer.feature(index)?;
254                let geometry = feature.geometry()?;
255                Ok(AncestorFeature {
256                    kind: feature.get_type(),
257                    id: feature.get_id(),
258                    properties: Arc::new(feature.get_properties().into_owned()),
259                    bounds: Bounds::of(&geometry),
260                    geometry,
261                })
262            })
263            .collect::<Result<_, TileError>>()?;
264        Ok(AncestorLayer { name: layer.name().to_owned(), extent: layer.extent(), features })
265    }
266}
267
268/// The `shared::Kind` of ancestors, which cross to a worker once for all the
269/// tiles cut from them.
270pub(crate) struct SharedAncestor;
271
272impl shared::Kind for SharedAncestor {
273    type Value = Ancestor;
274
275    fn write(ancestor: &Ancestor, w: &mut Writer) {
276        ancestor.data.write(w);
277    }
278
279    fn read(r: &mut Reader<'_>) -> Option<Arc<Ancestor>> {
280        TileData::read(r).map(|data| Arc::new(Ancestor::new(data)))
281    }
282}
283
284/// A tile's data cut from its ancestor's, and each layer's cut once read.
285pub struct CutData {
286    ancestor: Arc<Ancestor>,
287    cut: Cut,
288    /// By layer name; `None` for a layer the ancestor lacks.
289    layers: Mutex<HashMap<String, Option<Arc<CutLayer>>>>,
290}
291
292/// The features of an ancestor's layer that reach a cut tile. They keep what
293/// they are read for, so that reading them needn't decode the ancestor's
294/// layer again.
295pub struct CutLayer {
296    name: String,
297    features: Vec<CutFeature>,
298}
299
300impl CutLayer {
301    pub(crate) fn name(&self) -> &str {
302        &self.name
303    }
304
305    pub(crate) fn features(&self) -> &[CutFeature] {
306        &self.features
307    }
308}
309
310/// A feature of a [`CutLayer`], with its geometry in the cut tile.
311pub struct CutFeature {
312    kind: FeatureType,
313    id: Identifier,
314    /// Shared with the ancestor's feature.
315    properties: Arc<PropertyMap>,
316    geometry: GeometryCollection,
317}
318
319impl CutFeature {
320    pub(crate) fn geometry(&self) -> &GeometryCollection {
321        &self.geometry
322    }
323}
324
325impl GeometryTileFeature for CutFeature {
326    fn get_type(&self) -> FeatureType {
327        self.kind
328    }
329
330    fn get_value(&self, key: &str) -> Option<Value> {
331        self.properties.get(key).filter(|value| !matches!(value, Value::Null)).cloned()
332    }
333
334    fn get_properties(&self) -> Cow<'_, PropertyMap> {
335        Cow::Borrowed(&*self.properties)
336    }
337
338    fn get_id(&self) -> Identifier {
339        self.id.clone()
340    }
341
342    fn get_geometries(&self) -> Result<Cow<'_, GeometryCollection>, mln_style::error::Error> {
343        Ok(Cow::Borrowed(&self.geometry))
344    }
345}
346
347impl CutData {
348    #[must_use]
349    pub fn new(ancestor: Arc<Ancestor>, cut: Cut) -> Self {
350        CutData { ancestor, cut, layers: Mutex::default() }
351    }
352
353    #[must_use]
354    pub(crate) fn ancestor(&self) -> &Arc<Ancestor> {
355        &self.ancestor
356    }
357
358    #[must_use]
359    pub(crate) fn cut(&self) -> Cut {
360        self.cut
361    }
362
363    pub(crate) fn layer(&self, name: &str) -> Result<Option<Arc<CutLayer>>, TileError> {
364        if let Some(layer) = self.layers.lock().get(name) {
365            return Ok(layer.clone());
366        }
367        let layer = self.ancestor.layer(name)?.map(|layer| Arc::new(self.cut_layer(&layer)));
368        Ok(self.layers.lock().entry(name.to_owned()).or_insert(layer).clone())
369    }
370
371    /// The features of the ancestor's `layer` that reach the cut tile.
372    fn cut_layer(&self, layer: &AncestorLayer) -> CutLayer {
373        let reach = self.cut.reach(buffer(layer.extent));
374        let features = layer
375            .features
376            .iter()
377            .filter(|feature| feature.bounds.is_some_and(|bounds| bounds.overlaps(&reach)))
378            .filter_map(|feature| {
379                let geometry = self.cut.geometry(feature.kind, &feature.geometry, layer.extent);
380                (!geometry.is_empty()).then(|| CutFeature {
381                    kind: feature.kind,
382                    id: feature.id.clone(),
383                    properties: Arc::clone(&feature.properties),
384                    geometry,
385                })
386            })
387            .collect();
388        CutLayer { name: layer.name.clone(), features }
389    }
390
391    pub(crate) fn has_layer(&self, name: &str) -> Result<bool, TileError> {
392        self.ancestor.data.has_layer(name)
393    }
394
395    pub(crate) fn write(&self, w: &mut Writer) {
396        shared::write::<SharedAncestor>(&self.ancestor, w);
397        w.push(self.cut.dz);
398        self.cut.x.write(w);
399        self.cut.y.write(w);
400    }
401
402    pub(crate) fn read(r: &mut Reader<'_>) -> Option<Self> {
403        let ancestor = shared::read::<SharedAncestor>(r)?;
404        let cut = Cut { dz: r.byte()?, x: u32::read(r)?, y: u32::read(r)? };
405        Some(CutData::new(ancestor, cut))
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    fn clip(kind: FeatureType, rings: &[&[(i32, i32)]]) -> Vec<Vec<(i32, i32)>> {
414        let rings =
415            rings.iter().map(|ring| ring.iter().map(|&(x, y)| [f64::from(x), f64::from(y)]).collect()).collect();
416        let clipped = clip_on_axis(clip_on_axis(rings, kind, 0.0, 10.0, 0), kind, 0.0, 10.0, 1);
417        clipped.into_iter().map(|ring| ring.into_iter().map(|p| (p[0] as i32, p[1] as i32)).collect()).collect()
418    }
419
420    #[test]
421    fn a_tile_finds_its_place_in_an_ancestor() {
422        assert_eq!(Cut::of(&CanonicalTileID::new(16, 4 * 10 + 3, 4 * 20 + 1), 14), Some(Cut { dz: 2, x: 3, y: 1 }));
423        assert_eq!(Cut::of(&CanonicalTileID::new(14, 10, 20), 14), None);
424    }
425
426    #[test]
427    fn the_buffer_is_128_units_of_the_layer_or_a_32nd_of_the_tile() {
428        let extent = i64::from(EXTENT);
429        assert_eq!(buffer(4096), extent / 32);
430        assert_eq!(buffer(8192), extent / 32);
431        assert_eq!(buffer(1024), extent / 8);
432    }
433
434    #[test]
435    fn a_cut_reaches_its_buffer_in_the_ancestor() {
436        let quarter = i64::from(EXTENT) / 4;
437        let reach = Cut { dz: 2, x: 1, y: 0 }.reach(256);
438        assert_eq!(reach, Bounds { min: [quarter - 64, -64], max: [2 * quarter + 64, quarter + 64] });
439    }
440
441    #[test]
442    fn a_line_through_the_tile_keeps_its_middle() {
443        assert_eq!(clip(FeatureType::LineString, &[&[(-5, 5), (15, 5)]]), vec![vec![(0, 5), (10, 5)]]);
444    }
445
446    #[test]
447    fn a_line_leaving_and_coming_back_splits() {
448        let parts = clip(FeatureType::LineString, &[&[(2, 2), (2, 20), (8, 20), (8, 2)]]);
449        assert_eq!(parts, vec![vec![(2, 2), (2, 10)], vec![(8, 10), (8, 2)]]);
450    }
451
452    #[test]
453    fn a_ring_around_the_tile_becomes_its_bounds() {
454        let ring = clip(FeatureType::Polygon, &[&[(-5, -5), (15, -5), (15, 15), (-5, 15), (-5, -5)]]);
455        assert_eq!(ring, vec![vec![(10, 0), (10, 10), (0, 10), (0, 0), (10, 0)]]);
456    }
457
458    #[test]
459    fn each_point_inside_is_a_geometry_of_its_own() {
460        let points = clip(FeatureType::Point, &[&[(1, 1), (20, 1), (9, 9)]]);
461        assert_eq!(points, vec![vec![(1, 1)], vec![(9, 9)]]);
462    }
463
464    #[test]
465    fn a_cut_scales_and_moves_its_part_of_the_ancestor() {
466        let half = (EXTENT / 2) as i16;
467        let cut = Cut { dz: 1, x: 1, y: 1 };
468        let line =
469            GeometryCollection::from(vec![vec![Point::new(half + 10, half + 20), Point::new(half + 30, half + 20)]]);
470        let geometry = cut.geometry(FeatureType::LineString, &line, 4096);
471        assert_eq!(geometry[0], vec![Point::new(20, 40), Point::new(60, 40)]);
472        let elsewhere = GeometryCollection::from(vec![vec![Point::new(10, 10), Point::new(30, 10)]]);
473        assert!(cut.geometry(FeatureType::LineString, &elsewhere, 4096).is_empty());
474    }
475
476    #[test]
477    fn the_tiles_cut_from_an_ancestor_share_its_decoded_layer() {
478        let (half, quarter) = ((EXTENT / 2) as i16, (EXTENT / 4) as i16);
479        let road = mln_style::feature::Feature {
480            geometry: Some(geo_types::Geometry::LineString(geo_types::LineString::from(vec![
481                (half - 100, quarter),
482                (half + 100, quarter),
483            ]))),
484            properties: Arc::new(PropertyMap::new()),
485            id: Identifier::Uint(1),
486        };
487        let ancestor = Arc::new(Ancestor::new(TileData::Features(Arc::new(vec![road]))));
488        let decoded = ancestor.layer("roads").unwrap().unwrap();
489        let [west, east] = [0, 1].map(|x| CutData::new(Arc::clone(&ancestor), Cut { dz: 1, x, y: 0 }));
490        let [west, east] = [west, east].map(|cut| cut.layer("roads").unwrap().unwrap());
491
492        assert!(Arc::ptr_eq(&decoded, &ancestor.layer("roads").unwrap().unwrap()), "decoded once");
493        assert!(Arc::ptr_eq(&west.features()[0].properties, &east.features()[0].properties));
494        assert_eq!(
495            west.features()[0].geometry()[0],
496            vec![Point::new(EXTENT as i16 - 200, half), Point::new(EXTENT as i16 + 200, half)]
497        );
498    }
499}