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