mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
// Polygon fixup runs on i_overlay. Ring classification
// and the conversions to and from longitude/latitude are in
// `mln_style::feature`, where expressions reach them.

use i_overlay::core::fill_rule::FillRule;
use i_overlay::core::overlay::{Overlay, ShapeType};
use i_overlay::core::overlay_rule::OverlayRule;
use i_overlay::i_float::int::point::IntPoint;
use mln_style::crs::WorldMapping;
use mln_style::feature::{
    Feature, GeometryCollection, GeometryCoordinates, GeometryTileFeature, convert_geometry, signed_area,
};
use mln_style::geometry::Point;
use mln_style::tile_id::CanonicalTileID;

use crate::tile::TileError;

/// Repairs the rings of a polygon from a version 1 vector tile, whose spec
/// doesn't require them to be wound or simple: unions them with an even-odd
/// fill. Gives each polygon's outer ring, wound clockwise with y down as
/// version 2 wants, followed by its holes, wound the other way; every ring
/// is closed.
#[must_use]
pub(crate) fn fixup_polygons(rings: &GeometryCollection) -> GeometryCollection {
    let mut overlay = Overlay::new(rings.iter().map(Vec::len).sum());
    for ring in rings.iter() {
        overlay.add_path_iter(ring.iter().map(|p| IntPoint::new(i32::from(p.x), i32::from(p.y))), ShapeType::Subject);
    }

    let mut result = GeometryCollection::new();
    for shape in overlay.overlay(OverlayRule::Subject, FillRule::EvenOdd) {
        for contour in shape {
            // The union's vertices lie within the input's bounding box, so
            // they fit an i16.
            let mut ring: GeometryCoordinates = contour.iter().map(|p| Point::new(p.x as i16, p.y as i16)).collect();
            if let Some(&first) = ring.first() {
                ring.push(first);
            }
            result.push(ring);
        }
    }
    result
}

/// Truncates `polygon` to its `max_holes` largest inner rings by absolute
/// area. The order of the kept rings is unspecified, and so is which of
/// several rings tied at the cut is kept.
pub fn limit_holes(polygon: &mut GeometryCollection, max_holes: u32) {
    let max_holes = max_holes as usize;
    if polygon.len() > 1 + max_holes {
        polygon[1..].select_nth_unstable_by(max_holes, |a, b| signed_area(b).abs().total_cmp(&signed_area(a).abs()));
        polygon.truncate(1 + max_holes);
    }
}

/// Converts a feature of `tile_id` whose geometry is `geometries` to a
/// `Feature` in longitude/latitude, with its properties and id: through
/// `world`, the mapping of the map whose tile it is, from that map's world
/// square. Fails as [`convert_geometry`] does.
pub(crate) fn convert_feature(
    feature: &dyn GeometryTileFeature,
    geometries: &GeometryCollection,
    tile_id: &CanonicalTileID,
    world: &WorldMapping,
) -> Result<Feature<f64>, TileError> {
    let geometry = convert_geometry(feature.feature_type(), geometries, tile_id, world)?;
    let mut converted = Feature::new(geometry);
    converted.properties = feature.properties().into_owned();
    converted.id = feature.id();
    Ok(converted)
}

#[cfg(test)]
mod tests {
    use mln_style::feature::classify_rings;

    use super::*;

    fn ring(points: &[(i16, i16)]) -> GeometryCoordinates {
        points.iter().map(|&(x, y)| Point::new(x, y)).collect()
    }

    fn collection(rings: &[&[(i16, i16)]]) -> GeometryCollection {
        GeometryCollection::from(rings.iter().map(|r| ring(r)).collect::<Vec<_>>())
    }

    fn test_signed_area(ring: &GeometryCoordinates) -> f64 {
        signed_area(ring)
    }

    /// The (outer ring, hole count) of each polygon, with every ring
    /// closed and wound as `fixup_polygons` promises.
    fn fixed_polygons(rings: &[&[(i16, i16)]]) -> Vec<(GeometryCoordinates, usize)> {
        let fixed = fixup_polygons(&collection(rings));
        let polygons = classify_rings(&fixed);
        for polygon in &polygons {
            for (i, ring) in polygon.iter().enumerate() {
                assert_eq!(ring.first(), ring.last(), "{ring:?}");
                assert_eq!(signed_area(ring) > 0.0, i == 0, "{ring:?}");
            }
        }
        polygons.iter().map(|polygon| (polygon[0].clone(), polygon.len() - 1)).collect()
    }

    #[test]
    fn fixup_polygons_rewinds_rings() {
        // Two outer rings wound opposite ways, and a hole wound as its
        // outer ring is.
        let polygons = fixed_polygons(&[
            &[(0, 0), (0, 40), (40, 40), (40, 0), (0, 0)],
            &[(10, 10), (10, 20), (20, 20), (20, 10), (10, 10)],
            &[(50, 0), (90, 0), (90, 40), (50, 40), (50, 0)],
        ]);
        assert_eq!(polygons.len(), 2);
        let mut holes: Vec<usize> = polygons.iter().map(|(_, holes)| *holes).collect();
        holes.sort_unstable();
        assert_eq!(holes, [0, 1]);
    }

    #[test]
    fn fixup_polygons_splits_a_self_intersecting_ring() {
        let polygons = fixed_polygons(&[&[(0, 0), (20, 20), (20, 0), (0, 20), (0, 0)]]);
        assert_eq!(polygons.len(), 2);
        for (outer, holes) in &polygons {
            assert_eq!(*holes, 0);
            assert_eq!(outer.len(), 4, "a closed triangle: {outer:?}");
            // Twice the triangle's area.
            assert_eq!(signed_area(outer), 200.0);
        }
    }

    #[test]
    fn limit_holes_keeps_the_largest_holes_in_any_order() {
        let outer: &[(i16, i16)] = &[(0, 0), (0, 40), (40, 40), (40, 0), (0, 0)];
        let small: &[(i16, i16)] = &[(30, 30), (32, 30), (32, 32), (30, 30)];
        let large: &[(i16, i16)] = &[(10, 10), (20, 10), (20, 20), (10, 10)];
        for rings in [[outer, small, large], [outer, large, small]] {
            let mut polygon = collection(&rings);
            limit_holes(&mut polygon, 1);
            assert_eq!(polygon.len(), 2);
            assert_eq!((polygon[0][0].x, polygon[1][0].x), (0, 10));
        }
    }

    #[test]
    fn limit_holes_compares_the_areas_of_holes_wound_either_way() {
        // real world polygon with interior rings with negative areas
        // that need to be sorted in `limit_holes` by comparing absolute
        // area not signed
        let mut polygon = collection(&[
            &[
                (7336, -248),
                (7304, -248),
                (7272, -168),
                (7176, -200),
                (7080, -136),
                (7048, -56),
                (7128, -8),
                (7176, -56),
                (7288, -56),
                (7316, 0),
                (6918, 0),
                (6904, -40),
                (6984, -72),
                (6952, -88),
                (6952, -168),
                (6888, -88),
                (6856, -88),
                (6856, -8),
                (6872, 0),
                (6170, 0),
                (6184, -40),
                (6136, -72),
                (6104, -56),
                (6132, 0),
                (6028, 0),
                (6104, -152),
                (6184, -200),
                (6206, -256),
                (6272, -256),
                (6264, -248),
                (6248, -120),
                (6280, -136),
                (6280, -232),
                (6288, -256),
                (6790, -256),
                (6792, -248),
                (6800, -256),
                (7058, -256),
                (7064, -248),
                (7096, -256),
                (7338, -256),
                (7336, -248),
            ],
            &[(6344, -104), (6264, -8), (6392, -72), (6360, -200), (6344, -104)],
            &[(6744, -24), (6760, -72), (6728, -104), (6744, -24)],
            &[(6616, -104), (6648, -88), (6632, -72), (6664, -56), (6664, -120), (6616, -104)],
        ]);

        // make a copy for later testing
        let original = polygon.clone();

        assert_eq!(polygon.len(), 4);
        assert_eq!(test_signed_area(&polygon[0]), 515_360.0); // exterior
        assert_eq!(test_signed_area(&polygon[1]), -12288.0); // biggest interior ring
        assert_eq!(test_signed_area(&polygon[2]), -2048.0); // smallest interior ring
        assert_eq!(test_signed_area(&polygon[3]), -3072.0); // second largest interior ring

        limit_holes(&mut polygon, 2);

        // output: polygon 1 has 1 exterior, 2 interior
        assert_eq!(polygon.len(), 3);

        // ensure we've kept the exterior ring
        assert_eq!(original[0], polygon[0]);

        // ensure we've kept the two largest interior rings, in either order
        assert!(polygon[1..].contains(&original[1]));
        assert!(polygon[1..].contains(&original[3]));
    }
}