Skip to main content

mln_engine/tile/
geometry_tile_data.rs

1// Polygon fixup runs on i_overlay. Ring classification
2// and the conversions to and from longitude/latitude are in
3// `mln_style::feature`, where expressions reach them.
4
5use geometry::Point;
6use i_overlay::core::fill_rule::FillRule;
7use i_overlay::core::overlay::{Overlay, ShapeType};
8use i_overlay::core::overlay_rule::OverlayRule;
9use i_overlay::i_float::int::point::IntPoint;
10use mln_style::crs::WorldMapping;
11use mln_style::feature::{
12    Feature, GeometryCollection, GeometryCoordinates, GeometryTileFeature, convert_geometry, signed_area,
13};
14use mln_style::tile_id::CanonicalTileID;
15
16use crate::tile::TileError;
17
18/// Repairs the rings of a polygon from a version 1 vector tile, whose spec
19/// doesn't require them to be wound or simple: unions them with an even-odd
20/// fill. Gives each polygon's outer ring, wound clockwise with y down as
21/// version 2 wants, followed by its holes, wound the other way; every ring
22/// is closed.
23#[must_use]
24pub(crate) fn fixup_polygons(rings: &GeometryCollection) -> GeometryCollection {
25    let mut overlay = Overlay::new(rings.iter().map(Vec::len).sum());
26    for ring in rings.iter() {
27        overlay.add_path_iter(ring.iter().map(|p| IntPoint::new(i32::from(p.x), i32::from(p.y))), ShapeType::Subject);
28    }
29
30    let mut result = GeometryCollection::new();
31    for shape in overlay.overlay(OverlayRule::Subject, FillRule::EvenOdd) {
32        for contour in shape {
33            // The union's vertices lie within the input's bounding box, so
34            // they fit an i16.
35            let mut ring: GeometryCoordinates = contour.iter().map(|p| Point::new(p.x as i16, p.y as i16)).collect();
36            if let Some(&first) = ring.first() {
37                ring.push(first);
38            }
39            result.push(ring);
40        }
41    }
42    result
43}
44
45/// Truncates `polygon` to its `max_holes` largest inner rings by absolute
46/// area. The order of the kept rings is unspecified, and so is which of
47/// several rings tied at the cut is kept.
48pub fn limit_holes(polygon: &mut GeometryCollection, max_holes: u32) {
49    let max_holes = max_holes as usize;
50    if polygon.len() > 1 + max_holes {
51        polygon[1..].select_nth_unstable_by(max_holes, |a, b| signed_area(b).abs().total_cmp(&signed_area(a).abs()));
52        polygon.truncate(1 + max_holes);
53    }
54}
55
56/// Converts a feature of `tile_id` whose geometry is `geometries` to a
57/// `Feature` in longitude/latitude, with its properties and id: through
58/// `world`, the mapping of the map whose tile it is, from that map's world
59/// square. Fails as [`convert_geometry`] does.
60pub(crate) fn convert_feature(
61    feature: &dyn GeometryTileFeature,
62    geometries: &GeometryCollection,
63    tile_id: &CanonicalTileID,
64    world: &WorldMapping,
65) -> Result<Feature<f64>, TileError> {
66    let geometry = convert_geometry(feature.feature_type(), geometries, tile_id, world)?;
67    let mut converted = Feature::new(geometry);
68    converted.properties = feature.properties().into_owned();
69    converted.id = feature.id();
70    Ok(converted)
71}
72
73#[cfg(test)]
74mod tests {
75    use mln_style::feature::classify_rings;
76
77    use super::*;
78
79    fn ring(points: &[(i16, i16)]) -> GeometryCoordinates {
80        points.iter().map(|&(x, y)| Point::new(x, y)).collect()
81    }
82
83    fn collection(rings: &[&[(i16, i16)]]) -> GeometryCollection {
84        GeometryCollection::from(rings.iter().map(|r| ring(r)).collect::<Vec<_>>())
85    }
86
87    fn test_signed_area(ring: &GeometryCoordinates) -> f64 {
88        signed_area(ring)
89    }
90
91    /// The (outer ring, hole count) of each polygon, with every ring
92    /// closed and wound as `fixup_polygons` promises.
93    fn fixed_polygons(rings: &[&[(i16, i16)]]) -> Vec<(GeometryCoordinates, usize)> {
94        let fixed = fixup_polygons(&collection(rings));
95        let polygons = classify_rings(&fixed);
96        for polygon in &polygons {
97            for (i, ring) in polygon.iter().enumerate() {
98                assert_eq!(ring.first(), ring.last(), "{ring:?}");
99                assert_eq!(signed_area(ring) > 0.0, i == 0, "{ring:?}");
100            }
101        }
102        polygons.iter().map(|polygon| (polygon[0].clone(), polygon.len() - 1)).collect()
103    }
104
105    #[test]
106    fn fixup_polygons_rewinds_rings() {
107        // Two outer rings wound opposite ways, and a hole wound as its
108        // outer ring is.
109        let polygons = fixed_polygons(&[
110            &[(0, 0), (0, 40), (40, 40), (40, 0), (0, 0)],
111            &[(10, 10), (10, 20), (20, 20), (20, 10), (10, 10)],
112            &[(50, 0), (90, 0), (90, 40), (50, 40), (50, 0)],
113        ]);
114        assert_eq!(polygons.len(), 2);
115        let mut holes: Vec<usize> = polygons.iter().map(|(_, holes)| *holes).collect();
116        holes.sort_unstable();
117        assert_eq!(holes, [0, 1]);
118    }
119
120    #[test]
121    fn fixup_polygons_splits_a_self_intersecting_ring() {
122        let polygons = fixed_polygons(&[&[(0, 0), (20, 20), (20, 0), (0, 20), (0, 0)]]);
123        assert_eq!(polygons.len(), 2);
124        for (outer, holes) in &polygons {
125            assert_eq!(*holes, 0);
126            assert_eq!(outer.len(), 4, "a closed triangle: {outer:?}");
127            // Twice the triangle's area.
128            assert_eq!(signed_area(outer), 200.0);
129        }
130    }
131
132    // gtest: GeometryTileData.limitHoles1
133    #[test]
134    fn limit_holes1() {
135        let mut polygon = collection(&[
136            &[(0, 0), (0, 40), (40, 40), (40, 0), (0, 0)],
137            &[(30, 30), (32, 30), (32, 32), (30, 30)],
138            &[(10, 10), (20, 10), (20, 20), (10, 10)],
139        ]);
140
141        limit_holes(&mut polygon, 1);
142
143        // output: polygon 1 has 1 exterior, 1 interior
144        assert_eq!(polygon.len(), 2);
145
146        // ensure we've kept the right rings (ones with largest areas)
147        assert_eq!(polygon[0][0].x, 0);
148        assert_eq!(polygon[1][0].x, 10);
149    }
150
151    // gtest: GeometryTileData.limitHoles2
152    #[test]
153    fn limit_holes2() {
154        let mut polygon = collection(&[
155            &[(0, 0), (0, 40), (40, 40), (40, 0), (0, 0)],
156            &[(10, 10), (20, 10), (20, 20), (10, 10)],
157            &[(30, 30), (32, 30), (32, 32), (30, 30)],
158        ]);
159
160        limit_holes(&mut polygon, 1);
161
162        // output: polygon 1 has 1 exterior, 1 interior
163        assert_eq!(polygon.len(), 2);
164
165        // ensure we've kept the right rings (ones with largest areas)
166        assert_eq!(polygon[0][0].x, 0);
167        assert_eq!(polygon[1][0].x, 10);
168    }
169
170    // gtest: GeometryTileData.limitHoles3
171    #[test]
172    fn limit_holes3() {
173        // real world polygon with interior rings with negative areas
174        // that need to be sorted in `limitHoles` by comparing absolute
175        // area not signed
176        let mut polygon = collection(&[
177            &[
178                (7336, -248),
179                (7304, -248),
180                (7272, -168),
181                (7176, -200),
182                (7080, -136),
183                (7048, -56),
184                (7128, -8),
185                (7176, -56),
186                (7288, -56),
187                (7316, 0),
188                (6918, 0),
189                (6904, -40),
190                (6984, -72),
191                (6952, -88),
192                (6952, -168),
193                (6888, -88),
194                (6856, -88),
195                (6856, -8),
196                (6872, 0),
197                (6170, 0),
198                (6184, -40),
199                (6136, -72),
200                (6104, -56),
201                (6132, 0),
202                (6028, 0),
203                (6104, -152),
204                (6184, -200),
205                (6206, -256),
206                (6272, -256),
207                (6264, -248),
208                (6248, -120),
209                (6280, -136),
210                (6280, -232),
211                (6288, -256),
212                (6790, -256),
213                (6792, -248),
214                (6800, -256),
215                (7058, -256),
216                (7064, -248),
217                (7096, -256),
218                (7338, -256),
219                (7336, -248),
220            ],
221            &[(6344, -104), (6264, -8), (6392, -72), (6360, -200), (6344, -104)],
222            &[(6744, -24), (6760, -72), (6728, -104), (6744, -24)],
223            &[(6616, -104), (6648, -88), (6632, -72), (6664, -56), (6664, -120), (6616, -104)],
224        ]);
225
226        // make a copy for later testing
227        let original = polygon.clone();
228
229        assert_eq!(polygon.len(), 4);
230        assert_eq!(test_signed_area(&polygon[0]), 515_360.0); // exterior
231        assert_eq!(test_signed_area(&polygon[1]), -12288.0); // biggest interior ring
232        assert_eq!(test_signed_area(&polygon[2]), -2048.0); // smallest interior ring
233        assert_eq!(test_signed_area(&polygon[3]), -3072.0); // second largest interior ring
234
235        limit_holes(&mut polygon, 2);
236
237        // output: polygon 1 has 1 exterior, 2 interior
238        assert_eq!(polygon.len(), 3);
239
240        // ensure we've kept the exterior ring
241        assert_eq!(original[0], polygon[0]);
242
243        // ensure we've kept the two largest interior rings, in either order
244        assert!(polygon[1..].contains(&original[1]));
245        assert!(polygon[1..].contains(&original[3]));
246    }
247}