geolith-search-builder 0.3.2

Builds geocoding indexes from Overture Maps and OpenStreetMap: Postgres COPY files, Photon and Pelias bulk files, and the search part of a .glx file
Documentation
//! Rings from the ways of an OSM multipolygon or boundary relation.
//!
//! A relation's outline is split over many ways, each a run of points.
//! Ways that share an end point join into one ring; a ring that ends where
//! it started is closed. Inner rings (holes) belong to the smallest outer
//! ring that holds their first point. This is the assembly osmium and
//! Nominatim do before they use a relation's area.

use std::collections::HashMap;

/// A ring or a run of points, as `[lon, lat]`.
pub type Ring = Vec<[f64; 2]>;

/// A point's identity for joining: the bits of both coordinates. Ways that
/// share a node carry the same coordinates bit for bit.
const fn key(point: [f64; 2]) -> (u64, u64) {
    (point[0].to_bits(), point[1].to_bits())
}

/// Joins `ways` end to end into closed rings. A run that cannot be closed
/// (a way is missing from the file) is dropped, as is a ring of fewer than
/// three distinct points.
#[must_use]
pub fn join(ways: Vec<Ring>) -> Vec<Ring> {
    let mut ways: Vec<Option<Ring>> = ways
        .into_iter()
        .map(|way| (way.len() >= 2).then_some(way))
        .collect();
    // Every way by each of its two end points.
    let mut ends: HashMap<(u64, u64), Vec<usize>> = HashMap::with_capacity(ways.len() * 2);
    for (index, way) in ways.iter().enumerate() {
        if let Some(way) = way
            && let (Some(&first), Some(&last)) = (way.first(), way.last())
        {
            ends.entry(key(first)).or_default().push(index);
            ends.entry(key(last)).or_default().push(index);
        }
    }
    let mut rings = Vec::new();
    for start in 0..ways.len() {
        let Some(mut ring) = ways[start].take() else {
            continue;
        };
        while let (Some(&first), Some(&last)) = (ring.first(), ring.last()) {
            if key(first) == key(last) {
                if distinct_points(&ring) >= 3 {
                    rings.push(ring);
                }
                break;
            }
            // The next unused way that touches the open end.
            let next = ends
                .get(&key(last))
                .and_then(|candidates| candidates.iter().copied().find(|&i| ways[i].is_some()));
            let Some(next) = next.and_then(|i| ways[i].take()) else {
                // Cannot be closed.
                break;
            };
            let forward = next.first().is_some_and(|&p| key(p) == key(last));
            if forward {
                ring.extend_from_slice(&next[1..]);
            } else {
                ring.extend(next.iter().rev().skip(1));
            }
        }
    }
    rings
}

/// Points of a closed ring, the closing point not counted twice.
const fn distinct_points(ring: &[[f64; 2]]) -> usize {
    ring.len().saturating_sub(1)
}

/// Twice the signed area of a closed ring (shoelace); its absolute value
/// compares ring sizes.
fn area2(ring: &[[f64; 2]]) -> f64 {
    ring.windows(2)
        .map(|pair| pair[0][0] * pair[1][1] - pair[1][0] * pair[0][1])
        .sum()
}

/// Whether `point` is inside the closed `ring` (ray casting).
#[must_use]
pub fn contains(ring: &[[f64; 2]], point: [f64; 2]) -> bool {
    let mut inside = false;
    for pair in ring.windows(2) {
        let (a, b) = (pair[0], pair[1]);
        if (a[1] > point[1]) != (b[1] > point[1])
            && point[0] < (b[0] - a[0]) * (point[1] - a[1]) / (b[1] - a[1]) + a[0]
        {
            inside = !inside;
        }
    }
    inside
}

/// Polygons from outer and inner ways: each joined outer ring with the joined
/// inner rings whose first point it holds (the smallest such outer ring when
/// several do).
///
/// An inner ring no outer ring holds is dropped.
#[must_use]
pub fn polygons(outer: Vec<Ring>, inner: Vec<Ring>) -> Vec<Vec<Ring>> {
    let mut polygons: Vec<Vec<Ring>> = join(outer).into_iter().map(|ring| vec![ring]).collect();
    for hole in join(inner) {
        let Some(&first) = hole.first() else {
            continue;
        };
        let holder = polygons
            .iter()
            .enumerate()
            .filter(|(_, polygon)| contains(&polygon[0], first))
            .min_by(|(_, a), (_, b)| area2(&a[0]).abs().total_cmp(&area2(&b[0]).abs()))
            .map(|(index, _)| index);
        if let Some(index) = holder {
            polygons[index].push(hole);
        }
    }
    polygons
}

/// Whether `point` is inside any of `polygons`, outside its holes.
#[must_use]
pub fn polygons_contain(polygons: &[Vec<Ring>], point: [f64; 2]) -> bool {
    polygons.iter().any(|polygon| {
        polygon.first().is_some_and(|outer| contains(outer, point))
            && !polygon.iter().skip(1).any(|hole| contains(hole, point))
    })
}

/// The total area of `polygons` in square degrees, holes taken out; for
/// choosing the smallest of several matches.
#[must_use]
pub fn polygons_area(polygons: &[Vec<Ring>]) -> f64 {
    polygons
        .iter()
        .map(|polygon| {
            let outer = polygon.first().map_or(0.0, |ring| area2(ring).abs());
            let holes: f64 = polygon.iter().skip(1).map(|ring| area2(ring).abs()).sum();
            (outer - holes) / 2.0
        })
        .sum()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A unit square split over three ways, one of them reversed: they join
    /// into one closed ring that visits every corner once.
    #[test]
    fn ways_join_into_a_closed_ring() {
        let ways = vec![
            vec![[0.0, 0.0], [1.0, 0.0]],
            // Reversed: runs from (0, 1) back to (1, 1).
            vec![[0.0, 1.0], [1.0, 1.0]],
            vec![[1.0, 0.0], [1.0, 1.0]],
            vec![[0.0, 1.0], [0.0, 0.0]],
        ];
        let rings = join(ways);
        assert_eq!(
            rings,
            vec![vec![
                [0.0, 0.0],
                [1.0, 0.0],
                [1.0, 1.0],
                [0.0, 1.0],
                [0.0, 0.0]
            ]]
        );
    }

    #[test]
    fn an_open_run_is_dropped() {
        // Three sides of a square: the fourth way is not in the file.
        let ways = vec![
            vec![[0.0, 0.0], [1.0, 0.0]],
            vec![[1.0, 0.0], [1.0, 1.0]],
            vec![[1.0, 1.0], [0.0, 1.0]],
        ];
        assert!(join(ways).is_empty());
    }

    #[test]
    fn a_way_closed_on_its_own_is_a_ring() {
        let square = vec![[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [0.0, 0.0]];
        assert_eq!(join(vec![square.clone()]), vec![square]);
    }

    /// Two outer squares, side 10 and side 2; a hole at (1, 1) to (2, 2)
    /// lies inside both and belongs to the smaller one, the one that holds
    /// it most tightly.
    #[test]
    fn a_hole_belongs_to_the_smallest_outer_ring_that_holds_it() {
        let big = vec![
            [0.0, 0.0],
            [10.0, 0.0],
            [10.0, 10.0],
            [0.0, 10.0],
            [0.0, 0.0],
        ];
        let small = vec![[0.5, 0.5], [2.5, 0.5], [2.5, 2.5], [0.5, 2.5], [0.5, 0.5]];
        let hole = vec![[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0], [1.0, 1.0]];
        let far = vec![[50.0, 50.0], [51.0, 50.0], [51.0, 51.0], [50.0, 50.0]];
        let polygons = polygons(vec![big.clone(), small.clone()], vec![hole.clone(), far]);
        assert_eq!(polygons, vec![vec![big], vec![small, hole]]);
    }

    #[test]
    fn containment_and_area_take_out_the_holes() {
        let outer = vec![[0.0, 0.0], [4.0, 0.0], [4.0, 4.0], [0.0, 4.0], [0.0, 0.0]];
        let hole = vec![[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0], [1.0, 1.0]];
        let polygon = vec![vec![outer, hole]];
        assert!(polygons_contain(&polygon, [3.0, 3.0]));
        assert!(!polygons_contain(&polygon, [1.5, 1.5]));
        assert!(!polygons_contain(&polygon, [5.0, 1.0]));
        // 16 - 1 square degrees.
        assert!((polygons_area(&polygon) - 15.0).abs() < 1e-12);
    }
}