1use std::borrow::Cow;
8use std::sync::Arc;
9
10use mln_style::constants::EXTENT;
11use mln_style::feature::{
12 GeometryCollection, GeometryCoordinates, GeometryTileFeature, Identifier, PropertyMap, Value, ValueRef,
13};
14use mln_style::geometry::{FeatureType, Point};
15use mln_style::hash::HashMap;
16use mln_style::tile_id::CanonicalTileID;
17use mln_wire::{Reader, Wire, Writer, shared};
18use parking_lot::Mutex;
19
20use crate::tile::TileError;
21use crate::tile::tile_data::{TileData, TileLayer};
22
23fn buffer(extent: u32) -> i64 {
28 let extent = i64::from(extent.max(1));
29 let units = ((extent + 16) / 32).max(128);
30 units * i64::from(EXTENT) / extent
31}
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub struct Cut {
36 pub(crate) dz: u8,
38 pub(crate) x: u32,
41 pub(crate) y: u32,
42}
43
44impl Cut {
45 #[must_use]
48 pub fn of(tile: &CanonicalTileID, z: u8) -> Option<Cut> {
49 let dz = tile.z.checked_sub(z).filter(|&dz| dz > 0)?;
50 let mask = (1u64 << dz) - 1;
51 Some(Cut { dz, x: (u64::from(tile.x) & mask) as u32, y: (u64::from(tile.y) & mask) as u32 })
52 }
53
54 fn reach(&self, buffer: i64) -> Bounds {
57 let size = 1i64 << self.dz;
58 let edge = |at: u32, end: i64| (i64::from(at) + end) * i64::from(EXTENT);
59 let min = [(edge(self.x, 0) - buffer).div_euclid(size), (edge(self.y, 0) - buffer).div_euclid(size)];
60 let ceil = |at: i64| (at + size - 1).div_euclid(size);
61 let max = [ceil(edge(self.x, 1) + buffer), ceil(edge(self.y, 1) + buffer)];
62 Bounds { min, max }
63 }
64
65 #[must_use]
72 pub(crate) fn geometry(&self, kind: FeatureType, geometry: &GeometryCollection, extent: u32) -> GeometryCollection {
73 let scale = (1u64 << self.dz) as f64;
74 let offset = [f64::from(self.x) * f64::from(EXTENT), f64::from(self.y) * f64::from(EXTENT)];
75 let rings: Vec<Vec<P>> = geometry
76 .iter()
77 .map(|ring| {
78 ring.iter().map(|p| [f64::from(p.x) * scale - offset[0], f64::from(p.y) * scale - offset[1]]).collect()
79 })
80 .collect();
81 let buffer = buffer(extent);
82 let (start, end) = (-buffer as f64, (i64::from(EXTENT) + buffer) as f64);
83 let clipped = clip_on_axis(clip_on_axis(rings, kind, start, end, 0), kind, start, end, 1);
84 let round = |p: P| Point::new(p[0].round() as i16, p[1].round() as i16);
86 GeometryCollection::from(
87 clipped
88 .into_iter()
89 .map(|ring| ring.into_iter().map(round).collect::<GeometryCoordinates>())
90 .collect::<Vec<_>>(),
91 )
92 }
93}
94
95type P = [f64; 2];
97
98fn clip_on_axis(rings: Vec<Vec<P>>, kind: FeatureType, start: f64, end: f64, axis: usize) -> Vec<Vec<P>> {
100 match kind {
101 FeatureType::Point => {
102 rings.into_iter().flatten().filter(|p| (start..=end).contains(&p[axis])).map(|p| vec![p]).collect()
103 }
104 FeatureType::LineString => rings.iter().flat_map(|line| clip_line(line, start, end, axis, false)).collect(),
105 FeatureType::Polygon => rings.iter().flat_map(|ring| clip_line(ring, start, end, axis, true)).collect(),
106 FeatureType::Unknown => Vec::new(),
107 }
108}
109
110fn clip_line(line: &[P], start: f64, end: f64, axis: usize, polygon: bool) -> Vec<Vec<P>> {
113 let Some(&last) = line.last() else { return Vec::new() };
114 let mut slice: Vec<P> = Vec::new();
115 let mut parts = Vec::new();
116 for pair in line.windows(2) {
117 let (p1, p2) = (pair[0], pair[1]);
118 let (a, b) = (p1[axis], p2[axis]);
119 let mut exited = false;
120 if a < start {
121 if b >= start {
122 slice.push(intersection(p1, p2, start, axis));
123 }
124 } else if a > end {
125 if b <= end {
126 slice.push(intersection(p1, p2, end, axis));
127 }
128 } else {
129 slice.push(p1);
130 }
131 if b < start && a >= start {
132 slice.push(intersection(p1, p2, start, axis));
133 exited = true;
134 }
135 if b > end && a <= end {
136 slice.push(intersection(p1, p2, end, axis));
137 exited = true;
138 }
139 if !polygon && exited {
140 parts.push(std::mem::take(&mut slice));
141 }
142 }
143 if (start..=end).contains(&last[axis]) {
144 slice.push(last);
145 }
146 if polygon
147 && let (Some(&first), Some(&closing)) = (slice.first(), slice.last())
148 && first != closing
149 {
150 slice.push(first);
151 }
152 if !slice.is_empty() {
153 parts.push(slice);
154 }
155 parts
156}
157
158fn intersection(p1: P, p2: P, at: f64, axis: usize) -> P {
160 let other = 1 - axis;
161 let t = (at - p1[axis]) / (p2[axis] - p1[axis]);
162 let mut p = [0.0; 2];
163 p[axis] = at;
164 p[other] = p1[other] + (p2[other] - p1[other]) * t;
165 p
166}
167
168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170struct Bounds {
171 min: [i64; 2],
172 max: [i64; 2],
173}
174
175impl Bounds {
176 fn of(geometry: &GeometryCollection) -> Option<Bounds> {
178 let mut points = geometry.iter().flatten();
179 let first = points.next()?;
180 let mut bounds = Bounds { min: [first.x.into(), first.y.into()], max: [first.x.into(), first.y.into()] };
181 for p in points {
182 for (axis, at) in [i64::from(p.x), i64::from(p.y)].into_iter().enumerate() {
183 bounds.min[axis] = bounds.min[axis].min(at);
184 bounds.max[axis] = bounds.max[axis].max(at);
185 }
186 }
187 Some(bounds)
188 }
189
190 fn overlaps(&self, other: &Bounds) -> bool {
191 (0..2).all(|axis| self.min[axis] <= other.max[axis] && other.min[axis] <= self.max[axis])
192 }
193}
194
195pub struct Ancestor {
199 data: TileData,
200 layers: Mutex<HashMap<String, Option<Arc<AncestorLayer>>>>,
202}
203
204struct AncestorLayer {
206 name: String,
207 extent: u32,
209 features: Vec<AncestorFeature>,
210}
211
212pub struct AncestorFeature {
214 kind: FeatureType,
215 id: Identifier,
216 properties: Arc<PropertyMap>,
217 geometry: GeometryCollection,
218 bounds: Option<Bounds>,
220}
221
222impl Ancestor {
223 #[must_use]
224 pub fn new(data: TileData) -> Self {
225 Ancestor { data, layers: Mutex::default() }
226 }
227
228 #[must_use]
229 pub fn data(&self) -> &TileData {
230 &self.data
231 }
232
233 fn layer(&self, name: &str) -> Result<Option<Arc<AncestorLayer>>, TileError> {
235 if let Some(layer) = self.layers.lock().get(name) {
236 return Ok(layer.clone());
237 }
238 let layer = match self.data.layer(name)? {
240 Some(layer) => Some(Arc::new(AncestorLayer::decode(&layer)?)),
241 None => None,
242 };
243 Ok(self.layers.lock().entry(name.to_owned()).or_insert(layer).clone())
244 }
245}
246
247impl AncestorLayer {
248 fn decode(layer: &TileLayer<'_>) -> Result<AncestorLayer, TileError> {
249 let features = (0..layer.len())
250 .map(|index| {
251 let feature = layer.feature(index)?;
252 let geometry = feature.geometry()?.into_owned();
253 Ok(AncestorFeature {
254 kind: feature.feature_type(),
255 id: feature.id(),
256 properties: Arc::new(feature.properties().into_owned()),
257 bounds: Bounds::of(&geometry),
258 geometry,
259 })
260 })
261 .collect::<Result<_, TileError>>()?;
262 Ok(AncestorLayer { name: layer.name().to_owned(), extent: layer.extent(), features })
263 }
264}
265
266pub(crate) struct SharedAncestor;
269
270impl shared::Kind for SharedAncestor {
271 type Value = Ancestor;
272
273 fn write(ancestor: &Ancestor, w: &mut Writer<'_>) {
274 ancestor.data.write(w);
275 }
276
277 fn read(r: &mut Reader<'_>) -> Option<Arc<Ancestor>> {
278 TileData::read(r).map(|data| Arc::new(Ancestor::new(data)))
279 }
280}
281
282impl GeometryTileFeature for AncestorFeature {
283 fn feature_type(&self) -> FeatureType {
284 self.kind
285 }
286
287 fn value_ref(&self, key: &str) -> Option<ValueRef<'_>> {
288 self.properties.get(key).filter(|value| !matches!(value, Value::Null)).map(ValueRef::from)
289 }
290
291 fn properties(&self) -> Cow<'_, PropertyMap> {
292 Cow::Borrowed(&*self.properties)
293 }
294
295 fn id(&self) -> Identifier {
296 self.id.clone()
297 }
298
299 fn geometries(&self) -> Result<Cow<'_, GeometryCollection>, mln_style::error::Error> {
301 Ok(Cow::Borrowed(&self.geometry))
302 }
303}
304
305pub struct CutData {
307 ancestor: Arc<Ancestor>,
308 cut: Cut,
309 layers: Mutex<HashMap<String, Option<Arc<CutLayer>>>>,
311}
312
313pub struct CutLayer {
317 name: String,
318 features: Vec<CutFeature>,
319 ancestor: Arc<AncestorLayer>,
320 cut: Cut,
321}
322
323impl CutLayer {
324 pub(crate) fn name(&self) -> &str {
325 &self.name
326 }
327
328 pub(crate) fn features(&self) -> &[CutFeature] {
329 &self.features
330 }
331
332 #[must_use]
335 pub fn uncut(&self) -> Uncut<'_> {
336 Uncut { layer: self }
337 }
338}
339
340#[derive(Clone, Copy)]
345pub struct Uncut<'a> {
346 layer: &'a CutLayer,
347}
348
349impl<'a> Uncut<'a> {
350 #[must_use]
352 pub fn scale(self) -> f64 {
353 (1u64 << self.layer.cut.dz) as f64
354 }
355
356 #[must_use]
358 pub fn to_cut(self, point: [f64; 2]) -> [f64; 2] {
359 let Cut { x, y, .. } = self.layer.cut;
360 let scale = self.scale();
361 let extent = f64::from(EXTENT);
362 [point[0] * scale - f64::from(x) * extent, point[1] * scale - f64::from(y) * extent]
363 }
364
365 #[must_use]
368 pub fn geometry(self, index: usize) -> Option<&'a GeometryCollection> {
369 let feature = self.layer.features.get(index)?;
370 Some(&self.layer.ancestor.features[feature.ancestor_index].geometry)
371 }
372
373 pub fn nearby(self, distance: i64) -> impl Iterator<Item = &'a AncestorFeature> + 'a {
376 let reach = self.layer.cut.reach(distance);
377 let cut = &self.layer.features;
378 self.layer.ancestor.features.iter().enumerate().filter_map(move |(index, feature)| {
379 let near = feature.bounds.is_some_and(|bounds| bounds.overlaps(&reach));
380 (near && cut.binary_search_by_key(&index, |feature| feature.ancestor_index).is_err()).then_some(feature)
382 })
383 }
384}
385
386pub struct CutFeature {
388 kind: FeatureType,
389 id: Identifier,
390 properties: Arc<PropertyMap>,
392 geometry: GeometryCollection,
393 ancestor_index: usize,
395}
396
397impl CutFeature {
398 pub(crate) fn geometry(&self) -> &GeometryCollection {
399 &self.geometry
400 }
401}
402
403impl GeometryTileFeature for CutFeature {
404 fn feature_type(&self) -> FeatureType {
405 self.kind
406 }
407
408 fn value_ref(&self, key: &str) -> Option<ValueRef<'_>> {
409 self.properties.get(key).filter(|value| !matches!(value, Value::Null)).map(ValueRef::from)
410 }
411
412 fn properties(&self) -> Cow<'_, PropertyMap> {
413 Cow::Borrowed(&*self.properties)
414 }
415
416 fn id(&self) -> Identifier {
417 self.id.clone()
418 }
419
420 fn geometries(&self) -> Result<Cow<'_, GeometryCollection>, mln_style::error::Error> {
421 Ok(Cow::Borrowed(&self.geometry))
422 }
423}
424
425impl CutData {
426 #[must_use]
427 pub fn new(ancestor: Arc<Ancestor>, cut: Cut) -> Self {
428 CutData { ancestor, cut, layers: Mutex::default() }
429 }
430
431 #[must_use]
432 pub(crate) fn ancestor(&self) -> &Arc<Ancestor> {
433 &self.ancestor
434 }
435
436 #[must_use]
437 pub(crate) fn cut(&self) -> Cut {
438 self.cut
439 }
440
441 pub(crate) fn layer(&self, name: &str) -> Result<Option<Arc<CutLayer>>, TileError> {
442 if let Some(layer) = self.layers.lock().get(name) {
443 return Ok(layer.clone());
444 }
445 let layer = self.ancestor.layer(name)?.map(|layer| Arc::new(self.cut_layer(&layer)));
446 Ok(self.layers.lock().entry(name.to_owned()).or_insert(layer).clone())
447 }
448
449 fn cut_layer(&self, layer: &Arc<AncestorLayer>) -> CutLayer {
451 let reach = self.cut.reach(buffer(layer.extent));
452 let features = layer
453 .features
454 .iter()
455 .enumerate()
456 .filter(|(_, feature)| feature.bounds.is_some_and(|bounds| bounds.overlaps(&reach)))
457 .filter_map(|(ancestor_index, feature)| {
458 let geometry = self.cut.geometry(feature.kind, &feature.geometry, layer.extent);
459 (!geometry.is_empty()).then(|| CutFeature {
460 kind: feature.kind,
461 id: feature.id.clone(),
462 properties: Arc::clone(&feature.properties),
463 geometry,
464 ancestor_index,
465 })
466 })
467 .collect();
468 CutLayer { name: layer.name.clone(), features, ancestor: Arc::clone(layer), cut: self.cut }
469 }
470
471 pub(crate) fn has_layer(&self, name: &str) -> Result<bool, TileError> {
472 self.ancestor.data.has_layer(name)
473 }
474
475 pub(crate) fn write(&self, w: &mut Writer<'_>) {
476 shared::write::<SharedAncestor>(&self.ancestor, w);
477 w.push(self.cut.dz);
478 self.cut.x.write(w);
479 self.cut.y.write(w);
480 }
481
482 pub(crate) fn read(r: &mut Reader<'_>) -> Option<Self> {
483 let ancestor = shared::read::<SharedAncestor>(r)?;
484 let cut = Cut { dz: r.byte()?, x: u32::read(r)?, y: u32::read(r)? };
485 Some(CutData::new(ancestor, cut))
486 }
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492
493 fn clip(kind: FeatureType, rings: &[&[(i32, i32)]]) -> Vec<Vec<(i32, i32)>> {
494 let rings =
495 rings.iter().map(|ring| ring.iter().map(|&(x, y)| [f64::from(x), f64::from(y)]).collect()).collect();
496 let clipped = clip_on_axis(clip_on_axis(rings, kind, 0.0, 10.0, 0), kind, 0.0, 10.0, 1);
497 clipped.into_iter().map(|ring| ring.into_iter().map(|p| (p[0] as i32, p[1] as i32)).collect()).collect()
498 }
499
500 #[test]
501 fn a_tile_finds_its_place_in_an_ancestor() {
502 assert_eq!(Cut::of(&CanonicalTileID::new(16, 4 * 10 + 3, 4 * 20 + 1), 14), Some(Cut { dz: 2, x: 3, y: 1 }));
503 assert_eq!(Cut::of(&CanonicalTileID::new(14, 10, 20), 14), None);
504 }
505
506 #[test]
507 fn the_buffer_is_128_units_of_the_layer_or_a_32nd_of_the_tile() {
508 let extent = i64::from(EXTENT);
509 assert_eq!(buffer(4096), extent / 32);
510 assert_eq!(buffer(8192), extent / 32);
511 assert_eq!(buffer(1024), extent / 8);
512 }
513
514 #[test]
515 fn a_cut_reaches_its_buffer_in_the_ancestor() {
516 let quarter = i64::from(EXTENT) / 4;
517 let reach = Cut { dz: 2, x: 1, y: 0 }.reach(256);
518 assert_eq!(reach, Bounds { min: [quarter - 64, -64], max: [2 * quarter + 64, quarter + 64] });
519 }
520
521 #[test]
522 fn a_line_through_the_tile_keeps_its_middle() {
523 assert_eq!(clip(FeatureType::LineString, &[&[(-5, 5), (15, 5)]]), vec![vec![(0, 5), (10, 5)]]);
524 }
525
526 #[test]
527 fn a_line_leaving_and_coming_back_splits() {
528 let parts = clip(FeatureType::LineString, &[&[(2, 2), (2, 20), (8, 20), (8, 2)]]);
529 assert_eq!(parts, vec![vec![(2, 2), (2, 10)], vec![(8, 10), (8, 2)]]);
530 }
531
532 #[test]
533 fn a_ring_around_the_tile_becomes_its_bounds() {
534 let ring = clip(FeatureType::Polygon, &[&[(-5, -5), (15, -5), (15, 15), (-5, 15), (-5, -5)]]);
535 assert_eq!(ring, vec![vec![(10, 0), (10, 10), (0, 10), (0, 0), (10, 0)]]);
536 }
537
538 #[test]
539 fn each_point_inside_is_a_geometry_of_its_own() {
540 let points = clip(FeatureType::Point, &[&[(1, 1), (20, 1), (9, 9)]]);
541 assert_eq!(points, vec![vec![(1, 1)], vec![(9, 9)]]);
542 }
543
544 #[test]
545 fn a_cut_scales_and_moves_its_part_of_the_ancestor() {
546 let half = (EXTENT / 2) as i16;
547 let cut = Cut { dz: 1, x: 1, y: 1 };
548 let line =
549 GeometryCollection::from(vec![vec![Point::new(half + 10, half + 20), Point::new(half + 30, half + 20)]]);
550 let geometry = cut.geometry(FeatureType::LineString, &line, 4096);
551 assert_eq!(geometry[0], vec![Point::new(20, 40), Point::new(60, 40)]);
552 let elsewhere = GeometryCollection::from(vec![vec![Point::new(10, 10), Point::new(30, 10)]]);
553 assert!(cut.geometry(FeatureType::LineString, &elsewhere, 4096).is_empty());
554 }
555
556 #[test]
557 fn the_tiles_cut_from_an_ancestor_share_its_decoded_layer() {
558 let (half, quarter) = ((EXTENT / 2) as i16, (EXTENT / 4) as i16);
559 let road = mln_style::feature::Feature {
560 geometry: Some(geo_types::Geometry::LineString(geo_types::LineString::from(vec![
561 (half - 100, quarter),
562 (half + 100, quarter),
563 ]))),
564 properties: Arc::new(PropertyMap::new()),
565 id: Identifier::Uint(1),
566 };
567 let ancestor = Arc::new(Ancestor::new(TileData::Features(Arc::new(vec![road]))));
568 let decoded = ancestor.layer("roads").unwrap().unwrap();
569 let [west, east] = [0, 1].map(|x| CutData::new(Arc::clone(&ancestor), Cut { dz: 1, x, y: 0 }));
570 let [west, east] = [west, east].map(|cut| cut.layer("roads").unwrap().unwrap());
571
572 assert!(Arc::ptr_eq(&decoded, &ancestor.layer("roads").unwrap().unwrap()), "decoded once");
573 assert!(Arc::ptr_eq(&west.features()[0].properties, &east.features()[0].properties));
574 assert_eq!(
575 west.features()[0].geometry()[0],
576 vec![Point::new(EXTENT as i16 - 200, half), Point::new(EXTENT as i16 + 200, half)]
577 );
578 }
579
580 #[test]
581 fn a_cut_layer_holds_its_features_whole_and_finds_those_near_it() {
582 let half = (EXTENT / 2) as i16;
583 let road = |id: u64, x: i16| mln_style::feature::Feature {
584 geometry: Some(geo_types::Geometry::LineString(geo_types::LineString::from(vec![
585 (x, 100),
586 (x + 100, 100),
587 ]))),
588 properties: Arc::new(PropertyMap::new()),
589 id: Identifier::Uint(id),
590 };
591 let roads = vec![road(0, 100), road(1, half + 300), road(2, half + 1000)];
593 let ancestor = Arc::new(Ancestor::new(TileData::Features(Arc::new(roads))));
594 let layer = CutData::new(ancestor, Cut { dz: 1, x: 0, y: 0 }).layer("roads").unwrap().unwrap();
595 let uncut = layer.uncut();
596
597 assert_eq!(uncut.geometry(0).unwrap()[0], vec![Point::new(100, 100), Point::new(200, 100)]);
598 let near: Vec<_> = uncut.nearby(1000).map(GeometryTileFeature::id).collect();
599 assert_eq!(near, [Identifier::Uint(1)]);
600 assert_eq!(uncut.to_cut([f64::from(half), 10.0]), [f64::from(EXTENT), 20.0]);
601 }
602}