Skip to main content

geolith/tile/
feature_merge.rs

1//! Merging of same-attribute features within one tile layer.
2//!
3//! A port of Planetiler's `FeatureMerge`
4//! (`planetiler-core/src/main/java/com/onthegomap/planetiler/FeatureMerge.java`):
5//! [`merge_line_strings`] is `mergeLineStrings` and [`merge_nearby_polygons`]
6//! is `mergeNearbyPolygons`. Parameters are in Planetiler's units, pixels of
7//! a 256 px tile, so the per-layer numbers can be copied from the
8//! protomaps basemap's `postProcess` methods; one pixel is
9//! [`UNITS_PER_PIXEL`] tile units.
10//!
11//! Ported and modified from Planetiler
12//! (<https://github.com/onthegomap/planetiler>), Copyright 2021 Michael Barry
13//! and Planetiler Contributors, licensed under the Apache License, Version
14//! 2.0; see `NOTICE.md`.
15//!
16//! Output order follows Planetiler: features that are not of the merged
17//! geometry type keep their input order, then one feature per attribute
18//! group, in order of each group's first feature. A merged feature keeps the
19//! id and sort key of its group's first feature. (Planetiler rewrites the id
20//! to end in 0 because its ids encode the OSM element type in the last
21//! digit; geolith ids do not, so the id is kept as is.)
22
23use std::collections::HashMap;
24use std::sync::Arc;
25
26use geo::{
27    Area, BoundingRect, Buffer, Coord as GeoCoord, Distance, Euclidean, Intersects, LineString,
28    MultiPolygon, Polygon, Validation, algorithm::buffer::BufferStyle, unary_union,
29};
30use rstar::{AABB, RTree, primitives::GeomWithData, primitives::Rectangle};
31
32use crate::geometry::line_merge::{Coord, LineMergeOptions, merge_lines};
33use crate::tile::feature::{GeomType, PropValue, TILE_EXTENT, TileFeature};
34use crate::tile::mvt;
35
36/// Tile units per Planetiler pixel: a 4096-unit tile is 256 px wide.
37pub const UNITS_PER_PIXEL: f64 = TILE_EXTENT as f64 / 256.0;
38
39/// JTS's default mitre limit of 5, as the minimum corner angle that
40/// `i_overlay`'s `LineJoin::Miter` takes: a mitre is `1 / sin(angle / 2)`
41/// half-widths long, so a limit of 5 is `2 * asin(1 / 5)`.
42fn mitre_angle() -> f64 {
43    2.0 * (0.2f64).asin()
44}
45
46/// Settings for [`merge_line_strings`], in pixels.
47#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct LineMerge {
49    /// Drop merged lines shorter than this.
50    pub min_length: f64,
51    /// Simplify merged lines with this tolerance.
52    pub tolerance: f64,
53    /// Drop detail more than this far outside the tile; negative keeps all.
54    pub buffer: f64,
55    /// Simplify a group even when it has only one feature.
56    pub resimplify: bool,
57}
58
59/// Settings for [`merge_nearby_polygons`], in pixels.
60#[derive(Debug, Clone, Copy, PartialEq)]
61pub struct PolygonMerge {
62    /// Drop polygons whose area is at most this, in square pixels.
63    pub min_area: f64,
64    /// Drop holes whose area is at most this, in square pixels.
65    pub min_hole_area: f64,
66    /// Merge polygons that are at most this far apart.
67    pub min_dist: f64,
68    /// Grow then shrink merged polygons by this much, joining near misses.
69    pub buffer: f64,
70}
71
72/// A hashable view of a property value; floats compare by bits, as Java's
73/// `Double.equals` does.
74#[derive(Debug, Clone, PartialEq, Eq, Hash)]
75enum ValueKey<'a> {
76    Str(&'a str),
77    F64(u64),
78    I64(i64),
79    U64(u64),
80    Bool(bool),
81}
82
83/// The attribute set of a feature, order-insensitive like a Java `Map`.
84fn attr_key(properties: &[(String, PropValue)]) -> Vec<(&str, ValueKey<'_>)> {
85    let mut key: Vec<(&str, ValueKey<'_>)> = properties
86        .iter()
87        .map(|(k, v)| {
88            let value = match v {
89                PropValue::Str(s) => ValueKey::Str(s),
90                PropValue::F64(f) => ValueKey::F64(f.to_bits()),
91                PropValue::I64(i) => ValueKey::I64(*i),
92                PropValue::U64(u) => ValueKey::U64(*u),
93                PropValue::Bool(b) => ValueKey::Bool(*b),
94            };
95            (k.as_str(), value)
96        })
97        .collect();
98    key.sort_by(|a, b| a.0.cmp(b.0));
99    key
100}
101
102/// Split `features` into those of `geom_type`, grouped by identical
103/// attributes in order of first appearance, and all others in input order.
104fn group_by_attrs(
105    features: &[TileFeature],
106    geom_type: GeomType,
107) -> (Vec<&TileFeature>, Vec<Vec<&TileFeature>>) {
108    let mut others = Vec::new();
109    let mut groups: Vec<Vec<&TileFeature>> = Vec::new();
110    let mut index: HashMap<Vec<(&str, ValueKey<'_>)>, usize> = HashMap::new();
111    for feature in features {
112        if feature.geom_type != geom_type {
113            others.push(feature);
114            continue;
115        }
116        let key = attr_key(&feature.properties);
117        let slot = *index.entry(key).or_insert_with(|| {
118            groups.push(Vec::new());
119            groups.len() - 1
120        });
121        groups[slot].push(feature);
122    }
123    (others, groups)
124}
125
126fn with_geometry(feature: &TileFeature, geometry: Vec<u32>) -> TileFeature {
127    TileFeature {
128        layer: feature.layer,
129        id: feature.id,
130        geom_type: feature.geom_type,
131        geometry,
132        properties: Arc::clone(&feature.properties),
133        sort_key: feature.sort_key,
134    }
135}
136
137/// Planetiler's `Hilbert.hilbertXYToIndex`.
138#[must_use]
139const fn hilbert_xy_to_index(level: u32, x: u32, y: u32) -> u32 {
140    let x = x << (16 - level);
141    let y = y << (16 - level);
142
143    let a1 = x ^ y;
144    let b1 = 0xFFFF ^ a1;
145    let c1 = 0xFFFF ^ (x | y);
146    let d1 = x & (y ^ 0xFFFF);
147
148    let mut ha = a1 | (b1 >> 1);
149    let mut hb = (a1 >> 1) ^ a1;
150    let mut hc = ((c1 >> 1) ^ (b1 & (d1 >> 1))) ^ c1;
151    let mut hd = ((a1 & (c1 >> 1)) ^ (d1 >> 1)) ^ d1;
152
153    let (a2, b2, c2, d2) = (ha, hb, hc, hd);
154    ha = (a2 & (a2 >> 2)) ^ (b2 & (b2 >> 2));
155    hb = (a2 & (b2 >> 2)) ^ (b2 & ((a2 ^ b2) >> 2));
156    hc ^= (a2 & (c2 >> 2)) ^ (b2 & (d2 >> 2));
157    hd ^= (b2 & (c2 >> 2)) ^ ((a2 ^ b2) & (d2 >> 2));
158
159    let (a3, b3, c3, d3) = (ha, hb, hc, hd);
160    ha = (a3 & (a3 >> 4)) ^ (b3 & (b3 >> 4));
161    hb = (a3 & (b3 >> 4)) ^ (b3 & ((a3 ^ b3) >> 4));
162    hc ^= (a3 & (c3 >> 4)) ^ (b3 & (d3 >> 4));
163    hd ^= (b3 & (c3 >> 4)) ^ ((a3 ^ b3) & (d3 >> 4));
164
165    let (a4, b4, c4, d4) = (ha, hb, hc, hd);
166    hc ^= (a4 & (c4 >> 8)) ^ (b4 & (d4 >> 8));
167    hd ^= (b4 & (c4 >> 8)) ^ ((a4 ^ b4) & (d4 >> 8));
168
169    let a = hc ^ (hc >> 1);
170    let b = hd ^ (hd >> 1);
171    let i0 = x ^ y;
172    let i1 = b | (0xFFFF ^ (i0 | a));
173    ((interleave(i1) << 1) | interleave(i0)) >> (32 - 2 * level)
174}
175
176const fn interleave(mut t: u32) -> u32 {
177    t = (t | (t << 8)) & 0x00FF_00FF;
178    t = (t | (t << 4)) & 0x0F0F_0F0F;
179    t = (t | (t << 2)) & 0x3333_3333;
180    (t | (t << 1)) & 0x5555_5555
181}
182
183/// Planetiler's `VectorTile.hilbertIndex`: the order of a geometry's first
184/// coordinate on a level-15 Hilbert curve.
185fn hilbert_index(first: Coord) -> u32 {
186    let zigzag = |v: i32| ((v << 1) ^ (v >> 31)) as u32;
187    hilbert_xy_to_index(15, zigzag(first.0), zigzag(first.1))
188}
189
190/// Merge same-attribute linestrings: Planetiler's `mergeLineStrings`, with
191/// stroke merging on and loops and stubs limited by `min_length`.
192#[must_use]
193pub fn merge_line_strings(features: &[TileFeature], params: &LineMerge) -> Vec<TileFeature> {
194    let (others, groups) = group_by_attrs(features, GeomType::Line);
195    let mut result: Vec<TileFeature> = Vec::with_capacity(others.len() + groups.len());
196    result.extend(others.into_iter().cloned());
197
198    let min_length = params.min_length * UNITS_PER_PIXEL;
199    let options = LineMergeOptions {
200        min_length,
201        loop_min_length: min_length,
202        stub_min_length: params.min_length.min(0.5) * UNITS_PER_PIXEL,
203        tolerance: params.tolerance * UNITS_PER_PIXEL,
204        merge_strokes: true,
205    };
206    let buffer = params.buffer * UNITS_PER_PIXEL;
207
208    for group in groups {
209        let first = group[0];
210        if group.len() == 1
211            && params.buffer <= 0.0
212            && params.min_length <= 0.0
213            && (!params.resimplify || params.tolerance <= 0.0)
214        {
215            result.push(first.clone());
216            continue;
217        }
218        let lines: Vec<Vec<Coord>> = group
219            .iter()
220            .flat_map(|f| mvt::decode_commands(&f.geometry))
221            .collect();
222        let mut segments: Vec<Vec<Coord>> = Vec::new();
223        for line in merge_lines(&lines, &options) {
224            if params.buffer >= 0.0 {
225                remove_detail_outside_tile(&line, buffer, &mut segments);
226            } else {
227                segments.push(line);
228            }
229        }
230        if segments.is_empty() {
231            continue;
232        }
233        segments.sort_by_key(|s| hilbert_index(s[0]));
234        result.push(with_geometry(first, mvt::encode_multilinestring(&segments)));
235    }
236    result
237}
238
239/// Keep the parts of `line` with at least one end inside the tile grown by
240/// `buffer` units; a run of segments with both ends outside is cut out.
241fn remove_detail_outside_tile(line: &[Coord], buffer: f64, out: &mut Vec<Vec<Coord>>) {
242    let (min, max) = (-buffer, f64::from(TILE_EXTENT) + buffer);
243    let touches = |a: Coord, b: Coord| {
244        let (x0, x1) = (f64::from(a.0.min(b.0)), f64::from(a.0.max(b.0)));
245        let (y0, y1) = (f64::from(a.1.min(b.1)), f64::from(a.1.max(b.1)));
246        x1 >= min && x0 <= max && y1 >= min && y0 <= max
247    };
248    let mut current: Vec<Coord> = Vec::new();
249    let mut was_in = false;
250    for w in line.windows(2) {
251        let now_in = touches(w[0], w[1]);
252        if now_in || was_in {
253            current.push(w[0]);
254        } else if !current.is_empty() {
255            // The segment before this one touched the tile and pushed a
256            // point after the one that opened the run, so it has two.
257            out.push(std::mem::take(&mut current));
258        }
259        was_in = now_in;
260    }
261    if let [.., a, b] = line
262        && (touches(*a, *b) || was_in)
263    {
264        current.push(*b);
265    }
266    if current.len() >= 2 {
267        out.push(current);
268    }
269}
270
271/// Decode polygon commands into polygons: each exterior ring (positive
272/// area in the MVT formula) starts a polygon, and the rings after it until
273/// the next exterior are its holes.
274fn decode_polygons(geometry: &[u32]) -> Vec<Polygon<f64>> {
275    let mut polygons: Vec<(Vec<Coord>, Vec<Vec<Coord>>)> = Vec::new();
276    for ring in mvt::decode_commands(geometry) {
277        if ring.len() < 3 {
278            continue;
279        }
280        if shoelace(&ring) > 0 {
281            polygons.push((ring, Vec::new()));
282        } else if let Some((_, holes)) = polygons.last_mut() {
283            holes.push(ring);
284        }
285    }
286    polygons
287        .into_iter()
288        .map(|(exterior, holes)| {
289            Polygon::new(
290                to_line_string(&exterior),
291                holes.iter().map(|h| to_line_string(h)).collect(),
292            )
293        })
294        .collect()
295}
296
297fn to_line_string(ring: &[Coord]) -> LineString<f64> {
298    LineString::from(
299        ring.iter()
300            .map(|&(x, y)| GeoCoord {
301                x: f64::from(x),
302                y: f64::from(y),
303            })
304            .collect::<Vec<_>>(),
305    )
306}
307
308/// Twice the signed area by the MVT spec's surveyor's formula: positive for
309/// an exterior ring (clockwise on screen, Y down).
310fn shoelace(ring: &[Coord]) -> i64 {
311    let n = ring.len();
312    (0..n)
313        .map(|i| {
314            let (x0, y0) = ring[i];
315            let (x1, y1) = ring[(i + 1) % n];
316            i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0)
317        })
318        .sum()
319}
320
321/// Round a ring to tile units, dropping repeats and the closing point.
322fn snap_ring(ring: &LineString<f64>) -> Vec<Coord> {
323    let mut out: Vec<Coord> = Vec::with_capacity(ring.0.len());
324    for c in &ring.0 {
325        let p = (c.x.round() as i32, c.y.round() as i32);
326        if out.last() != Some(&p) {
327            out.push(p);
328        }
329    }
330    if out.len() > 1 && out.first() == out.last() {
331        out.pop();
332    }
333    out
334}
335
336/// Planetiler's `snapAndFixPolygon`: round to the tile grid, and repair the
337/// result if rounding made it invalid.
338fn snap_and_fix(merged: &MultiPolygon<f64>) -> MultiPolygon<f64> {
339    let snapped: Vec<Polygon<f64>> = merged
340        .0
341        .iter()
342        .filter_map(|p| {
343            let exterior = snap_ring(p.exterior());
344            if exterior.len() < 3 {
345                return None;
346            }
347            let holes = p
348                .interiors()
349                .iter()
350                .map(snap_ring)
351                .filter(|h| h.len() >= 3)
352                .map(|h| to_line_string(&h))
353                .collect();
354            Some(Polygon::new(to_line_string(&exterior), holes))
355        })
356        .collect();
357    let snapped = MultiPolygon(snapped);
358    if snapped.is_valid() {
359        snapped
360    } else {
361        // A self-union rebuilds the rings, the way JTS's GeometryFixer does.
362        unary_union(snapped.0.iter())
363    }
364}
365
366fn envelope_area(mp: &MultiPolygon<f64>) -> f64 {
367    mp.bounding_rect().map_or(0.0, |r| r.width() * r.height())
368}
369
370/// Grow each polygon by `buffer`, union them, then shrink the union back:
371/// Planetiler's `bufferUnionUnbuffer`, including its fallback when the
372/// shrink loses area (see locationtech/jts#1183).
373fn buffer_union_unbuffer(buffer: f64, group: &[&MultiPolygon<f64>]) -> MultiPolygon<f64> {
374    let style = |d: f64| {
375        BufferStyle::new(d).line_join(geo::algorithm::buffer::LineJoin::Miter(mitre_angle()))
376    };
377    buffer_union_unbuffer_with(buffer, group, |g, d| g.buffer_with_style(style(d)))
378}
379
380/// [`buffer_union_unbuffer`] with the buffer operation passed in, so the
381/// fallback for a buffer that loses area can be tested: geo's buffer does
382/// not have the JTS bug the fallback exists for.
383fn buffer_union_unbuffer_with(
384    buffer: f64,
385    group: &[&MultiPolygon<f64>],
386    buffer_by: impl Fn(&MultiPolygon<f64>, f64) -> MultiPolygon<f64>,
387) -> MultiPolygon<f64> {
388    let mut max_area_before = 0.0f64;
389    let mut buffered: Vec<Polygon<f64>> = Vec::new();
390    for geometry in group {
391        max_area_before = max_area_before.max(geometry.unsigned_area());
392        buffered.extend(buffer_by(geometry, buffer).0);
393    }
394    let before_union = MultiPolygon(buffered);
395    let union = unary_union(before_union.0.iter());
396    let mut merged = buffer_by(&union, -buffer);
397
398    let px2 = UNITS_PER_PIXEL * UNITS_PER_PIXEL;
399    if max_area_before > 100.0 * px2 {
400        let area_after = merged.unsigned_area();
401        if area_after < max_area_before * 0.95 {
402            let merged2 = buffer_by(&before_union, -buffer);
403            let area_after2 = merged2.unsigned_area();
404            if area_after2 < max_area_before * 0.95 {
405                return unary_union(group.iter().flat_map(|g| g.0.iter()));
406            }
407            // Planetiler also checks `area_after2 > area_after`, which holds
408            // here: area_after2 is at least the 95% that area_after is under.
409            merged = merged2;
410        }
411    }
412    merged
413}
414
415/// Connected groups of geometries at most `min_dist` apart (Planetiler's
416/// `groupPolygonsByProximity`), each group's members ascending and groups in
417/// order of their lowest member.
418///
419/// A union-find replaces Planetiler's adjacency list: a pair already in one
420/// group is never measured, and intersecting geometries are accepted before
421/// any exact distance is computed, so dense layers (thousands of landcover
422/// polygons in one low-zoom tile) do not pay for every pair.
423fn group_by_proximity(geometries: &[MultiPolygon<f64>], min_dist: f64) -> Vec<Vec<usize>> {
424    let envelopes: Vec<Option<AABB<[f64; 2]>>> = geometries
425        .iter()
426        .map(|g| {
427            g.bounding_rect()
428                .map(|r| AABB::from_corners([r.min().x, r.min().y], [r.max().x, r.max().y]))
429        })
430        .collect();
431    let tree = RTree::bulk_load(
432        envelopes
433            .iter()
434            .enumerate()
435            .filter_map(|(i, e)| {
436                e.map(|e| {
437                    let (lo, hi) = (e.lower(), e.upper());
438                    GeomWithData::new(
439                        Rectangle::from_corners(
440                            [lo[0] - min_dist, lo[1] - min_dist],
441                            [hi[0] + min_dist, hi[1] + min_dist],
442                        ),
443                        i,
444                    )
445                })
446            })
447            .collect(),
448    );
449
450    let mut parent: Vec<usize> = (0..geometries.len()).collect();
451    const fn find(parent: &mut [usize], mut i: usize) -> usize {
452        while parent[i] != i {
453            parent[i] = parent[parent[i]];
454            i = parent[i];
455        }
456        i
457    }
458    for (i, envelope) in envelopes.iter().enumerate() {
459        let Some(envelope) = envelope else { continue };
460        for candidate in tree.locate_in_envelope_intersecting(*envelope) {
461            let j = candidate.data;
462            if j <= i {
463                continue;
464            }
465            let (ri, rj) = (find(&mut parent, i), find(&mut parent, j));
466            if ri == rj {
467                continue;
468            }
469            let near = geometries[i].intersects(&geometries[j])
470                || (min_dist > 0.0
471                    && Euclidean.distance(&geometries[i], &geometries[j]) <= min_dist);
472            if near {
473                // The lower root wins, so a group's root is its lowest member.
474                let (lo, hi) = if ri < rj { (ri, rj) } else { (rj, ri) };
475                parent[hi] = lo;
476            }
477        }
478    }
479
480    let mut slot: HashMap<usize, usize> = HashMap::new();
481    let mut groups: Vec<Vec<usize>> = Vec::new();
482    for i in 0..geometries.len() {
483        let root = find(&mut parent, i);
484        let g = *slot.entry(root).or_insert_with(|| {
485            groups.push(Vec::new());
486            groups.len() - 1
487        });
488        groups[g].push(i);
489    }
490    groups
491}
492
493/// Planetiler's `extractPolygons`: keep polygons whose exterior area is
494/// over `min_area` and holes over `min_hole_area` (both in units squared),
495/// and replace an exterior that covers the whole tile with a canonical
496/// square so filled tiles are byte-identical and deduplicate.
497fn extract_polygons(
498    merged: &MultiPolygon<f64>,
499    min_area: f64,
500    min_hole_area: f64,
501) -> Vec<Vec<Vec<Coord>>> {
502    let mut out = Vec::new();
503    for polygon in &merged.0 {
504        let mut exterior = snap_ring(polygon.exterior());
505        let outer_area = (shoelace(&exterior) as f64 / 2.0).abs();
506        if exterior.len() < 3 || outer_area <= min_area {
507            continue;
508        }
509        if let Some(fill) = canonical_fill(outer_area, &exterior) {
510            exterior = fill;
511        }
512        let mut rings = vec![orient(exterior, true)];
513        for hole in polygon.interiors() {
514            let hole = snap_ring(hole);
515            let hole_area = (shoelace(&hole) as f64 / 2.0).abs();
516            if hole.len() >= 3 && (min_hole_area <= 0.0 || hole_area > min_hole_area) {
517                rings.push(orient(hole, false));
518            }
519        }
520        out.push(rings);
521    }
522    out
523}
524
525/// Wind a ring per the MVT spec: exteriors positive, holes negative.
526fn orient(mut ring: Vec<Coord>, exterior: bool) -> Vec<Coord> {
527    if (shoelace(&ring) > 0) != exterior {
528        ring.reverse();
529    }
530    ring
531}
532
533/// If `ring` covers the whole tile, the canonical square it should become:
534/// Planetiler's `isFill` and `createFill`.
535fn canonical_fill(outer_area: f64, ring: &[Coord]) -> Option<Vec<Coord>> {
536    const LEFT: u8 = 1;
537    const RIGHT: u8 = 2;
538    const TOP: u8 = 4;
539    const BOTTOM: u8 = 8;
540    let extent = f64::from(TILE_EXTENT);
541    if outer_area < extent * extent {
542        return None;
543    }
544    let proposed = (outer_area.sqrt() - extent) / 2.0;
545    let (min, max) = (-(proposed * 0.9), extent + proposed * 0.9);
546    let side = |(x, y): Coord| {
547        let (x, y) = (f64::from(x), f64::from(y));
548        let horizontal = if x < min {
549            LEFT
550        } else if x > max {
551            RIGHT
552        } else {
553            0
554        };
555        let vertical = if y < min {
556            TOP
557        } else if y > max {
558            BOTTOM
559        } else {
560            0
561        };
562        horizontal | vertical
563    };
564    let mut visited = 0u8;
565    let mut closed = ring.to_vec();
566    closed.push(ring[0]);
567    for w in closed.windows(2) {
568        let (a, b) = (side(w[0]), side(w[1]));
569        visited |= a;
570        if a & b == 0 {
571            // The segment crosses the tile, so the ring does not enclose it.
572            return None;
573        }
574    }
575    if visited != LEFT | RIGHT | TOP | BOTTOM {
576        return None;
577    }
578    let (lo, hi) = (
579        (-proposed).round() as i32,
580        (extent + proposed).round() as i32,
581    );
582    Some(vec![(lo, lo), (hi, lo), (hi, hi), (lo, hi)])
583}
584
585/// Merge same-attribute polygons that are within `min_dist` of each other:
586/// Planetiler's `mergeNearbyPolygons`.
587#[must_use]
588pub fn merge_nearby_polygons(features: &[TileFeature], params: &PolygonMerge) -> Vec<TileFeature> {
589    let (others, groups) = group_by_attrs(features, GeomType::Polygon);
590    let mut result: Vec<TileFeature> = Vec::with_capacity(others.len() + groups.len());
591    result.extend(others.into_iter().cloned());
592
593    let px2 = UNITS_PER_PIXEL * UNITS_PER_PIXEL;
594    let min_area = params.min_area * px2;
595    let min_hole_area = params.min_hole_area * px2;
596    let min_dist = params.min_dist * UNITS_PER_PIXEL;
597    let buffer = params.buffer * UNITS_PER_PIXEL;
598
599    for group in groups {
600        let first = group[0];
601        let geometries: Vec<MultiPolygon<f64>> = group
602            .iter()
603            .map(|f| MultiPolygon(decode_polygons(&f.geometry)))
604            .collect();
605        let mut polygons: Vec<Vec<Vec<Coord>>> = Vec::new();
606        for members in group_by_proximity(&geometries, min_dist) {
607            let merged = if members.len() > 1 {
608                let parts: Vec<&MultiPolygon<f64>> =
609                    members.iter().map(|&i| &geometries[i]).collect();
610                let merged = if buffer > 0.0 {
611                    buffer_union_unbuffer(buffer, &parts)
612                } else {
613                    unary_union(parts.iter().flat_map(|g| g.0.iter()))
614                };
615                if envelope_area(&merged) < min_area {
616                    continue;
617                }
618                snap_and_fix(&merged)
619            } else {
620                let single = geometries[members[0]].clone();
621                if envelope_area(&single) < min_area {
622                    continue;
623                }
624                single
625            };
626            polygons.extend(extract_polygons(&merged, min_area, min_hole_area));
627        }
628        if polygons.is_empty() {
629            continue;
630        }
631        polygons.sort_by_key(|rings| hilbert_index(rings[0][0]));
632        let rings: Vec<Vec<Coord>> = polygons.into_iter().flatten().collect();
633        result.push(with_geometry(first, mvt::encode_polygon(&rings)));
634    }
635    result
636}
637
638#[cfg(test)]
639mod tests {
640    use super::*;
641    use crate::layer::Layer;
642
643    fn props(kind: &str) -> Arc<Vec<(String, PropValue)>> {
644        Arc::new(vec![("kind".to_string(), PropValue::Str(kind.to_string()))])
645    }
646
647    fn line(id: u64, kind: &str, coords: &[Coord]) -> TileFeature {
648        TileFeature {
649            layer: Layer::Roads,
650            id,
651            geom_type: GeomType::Line,
652            geometry: mvt::encode_linestring(coords),
653            properties: props(kind),
654            sort_key: id as i32,
655        }
656    }
657
658    fn square(x: i32, y: i32, size: i32) -> Vec<Coord> {
659        // Clockwise on screen: an exterior ring.
660        vec![(x, y), (x + size, y), (x + size, y + size), (x, y + size)]
661    }
662
663    fn polygon(id: u64, kind: &str, rings: &[Vec<Coord>]) -> TileFeature {
664        TileFeature {
665            layer: Layer::Buildings,
666            id,
667            geom_type: GeomType::Polygon,
668            geometry: mvt::encode_polygon(rings),
669            properties: props(kind),
670            sort_key: id as i32,
671        }
672    }
673
674    fn is_kind(f: &TileFeature, kind: &str) -> bool {
675        f.properties[0].1 == PropValue::Str(kind.to_string())
676    }
677
678    fn total_area(f: &TileFeature) -> f64 {
679        decode_polygons(&f.geometry)
680            .iter()
681            .map(geo::Area::unsigned_area)
682            .sum()
683    }
684
685    const NO_LIMITS: LineMerge = LineMerge {
686        min_length: 0.0,
687        tolerance: -1.0,
688        buffer: -1.0,
689        resimplify: false,
690    };
691
692    #[test]
693    fn hilbert_index_matches_planetiler_for_the_level_1_quadrants() {
694        // Level-1 Hilbert curve order: (0,0)=0, (0,1)=1, (1,1)=2, (1,0)=3.
695        assert_eq!(hilbert_xy_to_index(1, 0, 0), 0);
696        assert_eq!(hilbert_xy_to_index(1, 0, 1), 1);
697        assert_eq!(hilbert_xy_to_index(1, 1, 1), 2);
698        assert_eq!(hilbert_xy_to_index(1, 1, 0), 3);
699    }
700
701    #[test]
702    fn lines_with_the_same_attributes_merge_into_one_feature() {
703        let features = vec![
704            line(1, "major", &[(0, 0), (100, 0)]),
705            line(2, "minor", &[(0, 50), (100, 50)]),
706            line(3, "major", &[(100, 0), (200, 0)]),
707        ];
708        let merged = merge_line_strings(&features, &NO_LIMITS);
709        assert_eq!(merged.len(), 2);
710        let major = merged.iter().find(|f| is_kind(f, "major")).expect("major");
711        assert_eq!(major.id, 1, "the group keeps its first feature's id");
712        let parts = mvt::decode_commands(&major.geometry);
713        assert_eq!(parts, vec![vec![(0, 0), (100, 0), (200, 0)]]);
714        let minor = merged.iter().find(|f| is_kind(f, "minor")).expect("minor");
715        assert_eq!(
716            mvt::decode_commands(&minor.geometry),
717            vec![vec![(0, 50), (100, 50)]]
718        );
719    }
720
721    #[test]
722    fn attribute_order_does_not_split_a_group() {
723        let a = Arc::new(vec![
724            ("kind".to_string(), PropValue::Str("x".into())),
725            ("level".to_string(), PropValue::I64(1)),
726        ]);
727        let b = Arc::new(vec![
728            ("level".to_string(), PropValue::I64(1)),
729            ("kind".to_string(), PropValue::Str("x".into())),
730        ]);
731        let mut first = line(1, "x", &[(0, 0), (10, 0)]);
732        first.properties = a;
733        let mut second = line(2, "x", &[(10, 0), (20, 0)]);
734        second.properties = b;
735        assert_eq!(merge_line_strings(&[first, second], &NO_LIMITS).len(), 1);
736    }
737
738    #[test]
739    fn a_lone_line_is_passed_through_when_nothing_could_change_it() {
740        let features = vec![line(7, "major", &[(0, 0), (5, 5), (10, 0)])];
741        let merged = merge_line_strings(&features, &NO_LIMITS);
742        assert_eq!(merged, features);
743    }
744
745    #[test]
746    fn non_line_features_keep_their_place_ahead_of_the_merged_groups() {
747        let point = TileFeature {
748            layer: Layer::Roads,
749            id: 9,
750            geom_type: GeomType::Point,
751            geometry: mvt::encode_points(&[(5, 5)]),
752            properties: props("label"),
753            sort_key: 0,
754        };
755        let features = vec![line(1, "major", &[(0, 0), (10, 0)]), point.clone()];
756        let merged = merge_line_strings(&features, &NO_LIMITS);
757        assert_eq!(
758            merged[0], point,
759            "Planetiler emits the pass-through features first"
760        );
761    }
762
763    #[test]
764    fn lines_shorter_than_the_minimum_are_dropped() {
765        // 0.5 px = 8 units; a 4-unit line goes, an 80-unit line stays.
766        let features = vec![
767            line(1, "major", &[(0, 0), (4, 0)]),
768            line(2, "major", &[(1000, 1000), (1080, 1000)]),
769        ];
770        let params = LineMerge {
771            min_length: 0.5,
772            ..NO_LIMITS
773        };
774        let merged = merge_line_strings(&features, &params);
775        assert_eq!(merged.len(), 1);
776        assert_eq!(
777            mvt::decode_commands(&merged[0].geometry),
778            vec![vec![(1000, 1000), (1080, 1000)]]
779        );
780    }
781
782    #[test]
783    fn detail_well_outside_the_tile_is_cut_but_edge_crossings_kept() {
784        // Runs from inside the tile to 10,000 units past its right edge,
785        // with a vertex every 1000. With a 4 px (64 unit) buffer only the
786        // part up to the first vertex past the edge survives.
787        let coords: Vec<Coord> = (0..15).map(|i| (3000 + i * 1000, 100)).collect();
788        let params = LineMerge {
789            buffer: 4.0,
790            ..NO_LIMITS
791        };
792        let merged = merge_line_strings(&[line(1, "major", &coords)], &params);
793        let parts = mvt::decode_commands(&merged[0].geometry);
794        assert_eq!(parts, vec![vec![(3000, 100), (4000, 100), (5000, 100)]]);
795    }
796
797    #[test]
798    fn touching_polygons_with_the_same_attributes_become_one() {
799        let params = PolygonMerge {
800            min_area: 0.0,
801            min_hole_area: 0.0,
802            min_dist: 0.0,
803            buffer: 0.0,
804        };
805        let features = vec![
806            polygon(1, "building", &[square(0, 0, 100)]),
807            polygon(2, "building", &[square(100, 0, 100)]),
808            polygon(3, "other", &[square(1000, 1000, 100)]),
809        ];
810        let merged = merge_nearby_polygons(&features, &params);
811        assert_eq!(merged.len(), 2);
812        let building = merged
813            .iter()
814            .find(|f| is_kind(f, "building"))
815            .expect("building");
816        let polygons = decode_polygons(&building.geometry);
817        assert_eq!(polygons.len(), 1, "the two squares share an edge");
818        assert!((total_area(building) - 20_000.0).abs() < 1e-6);
819    }
820
821    #[test]
822    fn near_polygons_merge_through_the_buffer_and_keep_their_area() {
823        // Two 160-unit squares 4 units apart (a quarter pixel). With a
824        // 0.5 px buffer they join; the gap is filled, so the area grows by
825        // the 4 x 160 strip and no more.
826        let params = PolygonMerge {
827            min_area: 0.0,
828            min_hole_area: 0.0,
829            min_dist: 0.5,
830            buffer: 0.5,
831        };
832        let features = vec![
833            polygon(1, "building", &[square(0, 0, 160)]),
834            polygon(2, "building", &[square(164, 0, 160)]),
835        ];
836        let merged = merge_nearby_polygons(&features, &params);
837        assert_eq!(merged.len(), 1);
838        assert_eq!(decode_polygons(&merged[0].geometry).len(), 1);
839        let area = total_area(&merged[0]);
840        assert!(
841            (area - (2.0 * 160.0 * 160.0 + 4.0 * 160.0)).abs() < 200.0,
842            "{area}"
843        );
844    }
845
846    #[test]
847    fn far_polygons_stay_separate_parts_of_one_feature() {
848        let params = PolygonMerge {
849            min_area: 0.0,
850            min_hole_area: 0.0,
851            min_dist: 0.5,
852            buffer: 0.5,
853        };
854        let features = vec![
855            polygon(1, "building", &[square(0, 0, 160)]),
856            polygon(2, "building", &[square(2000, 2000, 160)]),
857        ];
858        let merged = merge_nearby_polygons(&features, &params);
859        assert_eq!(merged.len(), 1);
860        assert_eq!(decode_polygons(&merged[0].geometry).len(), 2);
861    }
862
863    #[test]
864    fn holes_survive_a_merge_and_tiny_ones_are_dropped() {
865        let big_hole = vec![(100, 100), (100, 300), (300, 300), (300, 100)];
866        let tiny_hole = vec![(500, 500), (500, 502), (502, 502), (502, 500)];
867        let params = PolygonMerge {
868            min_area: 1.0,
869            min_hole_area: 1.0,
870            min_dist: 0.0,
871            buffer: 0.0,
872        };
873        let features = vec![
874            polygon(
875                1,
876                "water",
877                &[square(0, 0, 1000), big_hole.clone(), tiny_hole],
878            ),
879            polygon(2, "water", &[square(1000, 0, 1000)]),
880        ];
881        let merged = merge_nearby_polygons(&features, &params);
882        let polygons = decode_polygons(&merged[0].geometry);
883        assert_eq!(polygons.len(), 1);
884        assert_eq!(
885            polygons[0].interiors().len(),
886            1,
887            "only the 200 x 200 hole is kept"
888        );
889        // MVT winding: the exterior has positive area, the hole negative.
890        let signs: Vec<bool> = mvt::decode_commands(&merged[0].geometry)
891            .iter()
892            .map(|ring| shoelace(ring) > 0)
893            .collect();
894        assert_eq!(signs, [true, false]);
895        let expected = 2.0 * 1000.0 * 1000.0 - 200.0 * 200.0;
896        assert!((total_area(&merged[0]) - expected).abs() < 1e-6);
897    }
898
899    #[test]
900    fn polygons_at_or_under_the_minimum_area_are_dropped() {
901        // 1 px^2 = 256 units^2; a 10 x 10 square (100) goes.
902        let params = PolygonMerge {
903            min_area: 1.0,
904            min_hole_area: 1.0,
905            min_dist: 0.0,
906            buffer: 0.0,
907        };
908        let features = vec![polygon(1, "building", &[square(0, 0, 10)])];
909        assert!(merge_nearby_polygons(&features, &params).is_empty());
910    }
911
912    fn params(min_area: f64, min_dist: f64, buffer: f64) -> PolygonMerge {
913        PolygonMerge {
914            min_area,
915            min_hole_area: 0.0,
916            min_dist,
917            buffer,
918        }
919    }
920
921    fn with_props(mut feature: TileFeature, value: PropValue) -> TileFeature {
922        feature.properties = Arc::new(vec![("v".to_string(), value)]);
923        feature
924    }
925
926    #[test]
927    fn every_property_type_groups_by_value() {
928        // Two lines with one value join; a third with another value, though
929        // it touches them, stays apart. 0.0 and -0.0 differ, as Java's
930        // `Double.equals` has them.
931        let pairs = [
932            (PropValue::Str("a".into()), PropValue::Str("b".into())),
933            (PropValue::F64(0.0), PropValue::F64(-0.0)),
934            (PropValue::I64(-1), PropValue::I64(1)),
935            (PropValue::U64(1), PropValue::U64(2)),
936            (PropValue::Bool(true), PropValue::Bool(false)),
937        ];
938        for (same, other) in pairs {
939            let features = vec![
940                with_props(line(1, "x", &[(0, 0), (10, 0)]), same.clone()),
941                with_props(line(2, "x", &[(10, 0), (20, 0)]), same.clone()),
942                with_props(line(3, "x", &[(20, 0), (30, 0)]), other.clone()),
943            ];
944            let merged = merge_line_strings(&features, &NO_LIMITS);
945            assert_eq!(merged.len(), 2, "{same:?} vs {other:?}");
946            let joined = merged
947                .iter()
948                .find(|f| f.properties[0].1 == same)
949                .expect("the first group");
950            assert_eq!(
951                mvt::decode_commands(&joined.geometry),
952                vec![vec![(0, 0), (10, 0), (20, 0)]],
953                "{same:?}"
954            );
955        }
956    }
957
958    #[test]
959    fn a_lone_line_is_resimplified_only_when_asked() {
960        // The midpoint is 4 units off the chord, under the 1 px (16 unit)
961        // tolerance.
962        let features = vec![line(1, "major", &[(0, 0), (100, 4), (200, 0)])];
963        let keep = LineMerge {
964            tolerance: 1.0,
965            ..NO_LIMITS
966        };
967        assert_eq!(merge_line_strings(&features, &keep), features);
968        let resimplify = LineMerge {
969            resimplify: true,
970            ..keep
971        };
972        let merged = merge_line_strings(&features, &resimplify);
973        assert_eq!(
974            mvt::decode_commands(&merged[0].geometry),
975            vec![vec![(0, 0), (200, 0)]]
976        );
977    }
978
979    #[test]
980    fn a_group_whose_lines_are_all_too_short_disappears() {
981        // 0.5 px = 8 units; the 4-unit minor line is the whole minor group.
982        let features = vec![
983            line(1, "minor", &[(0, 0), (4, 0)]),
984            line(2, "major", &[(0, 100), (80, 100)]),
985        ];
986        let params = LineMerge {
987            min_length: 0.5,
988            ..NO_LIMITS
989        };
990        let merged = merge_line_strings(&features, &params);
991        assert_eq!(merged.len(), 1);
992        assert!(is_kind(&merged[0], "major"));
993    }
994
995    #[test]
996    fn rings_that_cannot_form_a_polygon_are_dropped() {
997        // MVT ClosePath is command 7 with count 1: (1 << 3) | 7.
998        const CLOSE_PATH: u32 = 15;
999        let mut two_points = mvt::encode_linestring(&[(0, 0), (10, 0)]);
1000        two_points.push(CLOSE_PATH);
1001        // A hole (negative area) before any exterior has nothing to cut.
1002        let mut stray_hole_first = mvt::encode_polygon(&[vec![(0, 0), (0, 50), (50, 50), (50, 0)]]);
1003        stray_hole_first.extend(mvt::encode_polygon(&[square(0, 0, 100)]));
1004        // A two-point ring after an exterior is no hole either.
1005        stray_hole_first.extend(two_points.iter().copied());
1006        let polygons = decode_polygons(&stray_hole_first);
1007        assert_eq!(polygons.len(), 1);
1008        assert!(polygons[0].interiors().is_empty());
1009        assert!(decode_polygons(&two_points).is_empty());
1010
1011        // A feature with no usable ring has no bounding box; it takes no
1012        // part in the merge and the other feature comes through whole.
1013        let mut degenerate = polygon(1, "building", &[]);
1014        degenerate.geometry = two_points;
1015        let features = vec![degenerate, polygon(2, "building", &[square(0, 0, 100)])];
1016        let merged = merge_nearby_polygons(&features, &params(0.0, 0.5, 0.0));
1017        assert_eq!(merged.len(), 1);
1018        assert!((total_area(&merged[0]) - 10_000.0).abs() < 1e-6);
1019    }
1020
1021    #[test]
1022    fn snapping_rounds_drops_repeats_and_the_closing_point() {
1023        let ring = LineString::from(vec![
1024            (0.2, 0.1),
1025            (0.4, 0.3),
1026            (10.2, 0.0),
1027            (10.0, 9.8),
1028            (0.1, 0.2),
1029        ]);
1030        assert_eq!(snap_ring(&ring), vec![(0, 0), (10, 0), (10, 10)]);
1031        let dot = LineString::from(vec![(0.1, 0.1), (0.2, 0.2), (0.1, 0.1)]);
1032        assert_eq!(snap_ring(&dot), vec![(0, 0)]);
1033    }
1034
1035    #[test]
1036    fn snapping_drops_slivers_and_repairs_rings_it_made_invalid() {
1037        let sliver = Polygon::new(
1038            LineString::from(vec![(0.0, 0.0), (10.0, 0.0), (10.0, 0.2), (0.0, 0.2)]),
1039            vec![],
1040        );
1041        let block = Polygon::new(
1042            LineString::from(vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]),
1043            vec![],
1044        );
1045        let fixed = snap_and_fix(&MultiPolygon(vec![sliver, block]));
1046        assert_eq!(fixed.0.len(), 1);
1047        assert!((fixed.unsigned_area() - 10_000.0).abs() < 1e-9);
1048
1049        // The spike at (5.4, 0.4) clears the bottom edge, but rounds onto
1050        // it at (5, 0): the snapped ring touches itself. Repaired, it is the
1051        // two triangles either side of the touch, 25 square units each.
1052        let spike = Polygon::new(
1053            LineString::from(vec![
1054                (0.0, 0.0),
1055                (10.0, 0.0),
1056                (10.0, 10.0),
1057                (5.4, 0.4),
1058                (0.0, 10.0),
1059            ]),
1060            vec![],
1061        );
1062        assert!(spike.is_valid());
1063        let fixed = snap_and_fix(&MultiPolygon(vec![spike]));
1064        assert!(fixed.is_valid(), "{fixed:?}");
1065        assert!((fixed.unsigned_area() - 50.0).abs() < 1e-9, "{fixed:?}");
1066    }
1067
1068    #[test]
1069    fn a_chain_of_touching_polygons_is_one_group_in_any_order() {
1070        // C touches A and B, but A and B are 100 units apart: A and B only
1071        // join through C, which comes last.
1072        let features = vec![
1073            polygon(1, "building", &[square(0, 0, 100)]),
1074            polygon(2, "building", &[square(200, 0, 100)]),
1075            polygon(3, "building", &[square(100, 0, 100)]),
1076        ];
1077        let merged = merge_nearby_polygons(&features, &params(0.0, 0.0, 0.0));
1078        assert_eq!(decode_polygons(&merged[0].geometry).len(), 1);
1079        assert!((total_area(&merged[0]) - 30_000.0).abs() < 1e-6);
1080
1081        // B and C each share an edge with A and meet each other at a
1082        // corner, so by the time B and C are compared they are one group.
1083        let features = vec![
1084            polygon(1, "building", &[square(0, 0, 200)]),
1085            polygon(2, "building", &[square(200, 100, 100)]),
1086            polygon(3, "building", &[square(100, 200, 100)]),
1087        ];
1088        let merged = merge_nearby_polygons(&features, &params(0.0, 0.0, 0.0));
1089        assert_eq!(decode_polygons(&merged[0].geometry).len(), 1);
1090        assert!((total_area(&merged[0]) - 60_000.0).abs() < 1e-6);
1091    }
1092
1093    #[test]
1094    fn diagonal_neighbours_farther_than_min_dist_stay_apart() {
1095        // With min_dist 0.5 px (8 units) the boxes are 6 units apart on each
1096        // axis, so they are candidates, but the nearest corners are
1097        // sqrt(6^2 + 6^2), about 8.49 units, apart.
1098        let features = vec![
1099            polygon(1, "building", &[square(0, 0, 100)]),
1100            polygon(2, "building", &[square(106, 106, 100)]),
1101        ];
1102        let merged = merge_nearby_polygons(&features, &params(0.0, 0.5, 0.0));
1103        assert_eq!(decode_polygons(&merged[0].geometry).len(), 2);
1104        assert!((total_area(&merged[0]) - 20_000.0).abs() < 1e-6);
1105    }
1106
1107    #[test]
1108    fn proximity_is_the_true_distance_not_the_box_distance() {
1109        // The same diagonal pair: boxes 6 units apart on each axis, corners
1110        // sqrt(72), about 8.49, apart. They group at a min_dist of 8.5 but
1111        // not at 8.4, though both distances put the boxes in reach.
1112        let pair = [block(0.0, 0.0, 100.0), block(106.0, 106.0, 100.0)];
1113        assert_eq!(group_by_proximity(&pair, 8.4), vec![vec![0], vec![1]]);
1114        assert_eq!(group_by_proximity(&pair, 8.5), vec![vec![0, 1]]);
1115    }
1116
1117    #[test]
1118    fn a_merge_under_the_minimum_area_is_dropped() {
1119        // Two 5 x 5 squares: merged, a 10 x 5 box of 50 units^2, under the
1120        // 1 px^2 (256 units^2) minimum.
1121        let tiny = vec![
1122            polygon(1, "building", &[square(0, 0, 5)]),
1123            polygon(2, "building", &[square(5, 0, 5)]),
1124        ];
1125        assert!(merge_nearby_polygons(&tiny, &params(1.0, 0.0, 0.0)).is_empty());
1126
1127        // An L of two 100 x 2 bars: its 100 x 100 box passes the 2 px^2
1128        // (512 units^2) minimum, but its area, 2 * 200 - 4 = 396, does not.
1129        let bars = vec![
1130            polygon(1, "building", &[vec![(0, 0), (100, 0), (100, 2), (0, 2)]]),
1131            polygon(2, "building", &[vec![(0, 0), (2, 0), (2, 100), (0, 100)]]),
1132        ];
1133        assert!(merge_nearby_polygons(&bars, &params(2.0, 0.0, 0.0)).is_empty());
1134        let merged = merge_nearby_polygons(&bars, &params(1.0, 0.0, 0.0));
1135        assert!((total_area(&merged[0]) - 396.0).abs() < 1e-6);
1136    }
1137
1138    #[test]
1139    fn rings_are_wound_as_the_mvt_spec_requires() {
1140        // Clockwise on screen (Y down) is positive by the surveyor's formula.
1141        let clockwise = square(0, 0, 10);
1142        let counter: Vec<Coord> = clockwise.iter().rev().copied().collect();
1143        assert_eq!(orient(counter.clone(), true), clockwise);
1144        assert_eq!(orient(clockwise.clone(), true), clockwise);
1145        assert_eq!(orient(clockwise.clone(), false), counter);
1146        assert_eq!(orient(counter.clone(), false), counter);
1147    }
1148
1149    /// The real buffer, except that shrinking a single polygon loses it,
1150    /// or, with `always`, that every shrink does: the JTS failure the
1151    /// fallback guards against.
1152    fn lossy(always: bool) -> impl Fn(&MultiPolygon<f64>, f64) -> MultiPolygon<f64> {
1153        move |g, d| {
1154            if d < 0.0 && (always || g.0.len() == 1) {
1155                MultiPolygon(vec![])
1156            } else {
1157                g.buffer_with_style(
1158                    BufferStyle::new(d)
1159                        .line_join(geo::algorithm::buffer::LineJoin::Miter(mitre_angle())),
1160                )
1161            }
1162        }
1163    }
1164
1165    fn block(x: f64, y: f64, size: f64) -> MultiPolygon<f64> {
1166        MultiPolygon(vec![Polygon::new(
1167            LineString::from(vec![
1168                (x, y),
1169                (x + size, y),
1170                (x + size, y + size),
1171                (x, y + size),
1172            ]),
1173            vec![],
1174        )])
1175    }
1176
1177    #[test]
1178    fn a_shrink_that_loses_area_falls_back_as_planetiler_does() {
1179        // Two 200 x 200 squares (40,000 units^2, over the 100 px^2 =
1180        // 25,600 floor) 4 units apart, grown and shrunk by 8.
1181        let (a, b) = (block(0.0, 0.0, 200.0), block(204.0, 0.0, 200.0));
1182
1183        // The union's shrink is lost; shrinking the grown squares one by
1184        // one keeps each square, so that is used instead.
1185        let merged = buffer_union_unbuffer_with(8.0, &[&a, &b], lossy(false));
1186        assert_eq!(merged.0.len(), 2);
1187        assert!(
1188            (merged.unsigned_area() - 80_000.0).abs() < 1.0,
1189            "{merged:?}"
1190        );
1191
1192        // Both shrinks are lost: the plain union of the inputs is kept.
1193        let merged = buffer_union_unbuffer_with(8.0, &[&a, &b], lossy(true));
1194        assert_eq!(merged, unary_union(a.0.iter().chain(b.0.iter())));
1195        assert!((merged.unsigned_area() - 80_000.0).abs() < 1e-9);
1196
1197        // Under the floor nothing is checked: 100 x 100 squares (10,000
1198        // units^2) keep the lossy result.
1199        let (a, b) = (block(0.0, 0.0, 100.0), block(104.0, 0.0, 100.0));
1200        assert!(
1201            buffer_union_unbuffer_with(8.0, &[&a, &b], lossy(true))
1202                .0
1203                .is_empty()
1204        );
1205    }
1206
1207    #[test]
1208    fn only_a_ring_round_all_four_sides_is_a_fill() {
1209        // 4296 units square, 100 past each tile edge, with extra vertices
1210        // mid-way along the top and left edges: still a fill.
1211        let ring = vec![
1212            (-100, -100),
1213            (2000, -100),
1214            (4196, -100),
1215            (4196, 4196),
1216            (-100, 4196),
1217            (-100, 2000),
1218        ];
1219        let area = (shoelace(&ring) as f64 / 2.0).abs();
1220        assert_eq!(area, 4296.0 * 4296.0);
1221        assert_eq!(
1222            canonical_fill(area, &ring),
1223            Some(vec![(-100, -100), (4196, -100), (4196, 4196), (-100, 4196)])
1224        );
1225
1226        // A notch down to (2000, 2000) crosses into the tile.
1227        let notched = vec![
1228            (-100, -100),
1229            (2000, -100),
1230            (2000, 2000),
1231            (2100, -100),
1232            (4196, -100),
1233            (4196, 4196),
1234            (-100, 4196),
1235        ];
1236        let area = (shoelace(&notched) as f64 / 2.0).abs();
1237        assert!(area >= 4096.0 * 4096.0);
1238        assert_eq!(canonical_fill(area, &notched), None);
1239
1240        // Bigger than the tile, but wholly off its left side.
1241        let left = vec![
1242            (-100_000, 0),
1243            (-90_000, 0),
1244            (-90_000, 2000),
1245            (-100_000, 2000),
1246        ];
1247        let area = (shoelace(&left) as f64 / 2.0).abs();
1248        assert!(area >= 4096.0 * 4096.0);
1249        assert_eq!(canonical_fill(area, &left), None);
1250    }
1251
1252    #[test]
1253    fn a_polygon_covering_the_tile_becomes_the_canonical_fill() {
1254        let params = PolygonMerge {
1255            min_area: 1.0,
1256            min_hole_area: 1.0,
1257            min_dist: 0.0,
1258            buffer: 0.0,
1259        };
1260        // Two halves of a square overhanging the tile by 100 units each
1261        // side, with an extra vertex on one edge.
1262        let left = vec![(-100, -100), (2048, -100), (2048, 4196), (-100, 4196)];
1263        let right = vec![
1264            (2048, -100),
1265            (3000, -100),
1266            (4196, -100),
1267            (4196, 4196),
1268            (2048, 4196),
1269        ];
1270        let features = vec![polygon(1, "earth", &[left]), polygon(2, "earth", &[right])];
1271        let merged = merge_nearby_polygons(&features, &params);
1272        let rings = mvt::decode_commands(&merged[0].geometry);
1273        assert_eq!(
1274            rings,
1275            vec![vec![(-100, -100), (4196, -100), (4196, 4196), (-100, 4196)]]
1276        );
1277    }
1278}