use std::path::Path;
use geojson::{GeoJson, Geometry, GeometryValue, Position};
use geolith::error::{GeolithError, Result};
use crate::terrain::source::Bounds;
const BANDS_PER_DEGREE: f64 = 20.0;
#[derive(Debug, Clone, Copy)]
struct Edge {
lon0: f64,
lat0: f64,
lon1: f64,
lat1: f64,
}
#[derive(Debug, Clone)]
pub struct ClipMask {
bounds: Bounds,
edges: Vec<Edge>,
bands: Vec<Vec<u32>>,
}
impl ClipMask {
pub fn from_geojson(path: &Path) -> Result<Self> {
let text = std::fs::read_to_string(path)?;
let geojson: GeoJson = text
.parse()
.map_err(|e| GeolithError::GeoJson(format!("{}: {e}", path.display())))?;
let mut rings = Vec::with_capacity(64);
match geojson {
GeoJson::FeatureCollection(fc) => {
for feature in fc.features {
if let Some(geometry) = feature.geometry {
collect_rings(&geometry, &mut rings);
}
}
}
GeoJson::Feature(feature) => {
if let Some(geometry) = feature.geometry {
collect_rings(&geometry, &mut rings);
}
}
GeoJson::Geometry(geometry) => collect_rings(&geometry, &mut rings),
}
Self::from_rings(&rings).ok_or_else(|| {
GeolithError::GeoJson(format!("{}: no Polygon or MultiPolygon", path.display()))
})
}
#[must_use]
pub fn from_rings(rings: &[Vec<[f64; 2]>]) -> Option<Self> {
let mut edges = Vec::with_capacity(rings.iter().map(Vec::len).sum());
for ring in rings.iter().filter(|r| r.len() >= 3) {
for (i, a) in ring.iter().enumerate() {
let b = ring[(i + 1) % ring.len()];
if a[1] != b[1] {
edges.push(Edge {
lon0: a[0],
lat0: a[1],
lon1: b[0],
lat1: b[1],
});
}
}
}
if edges.is_empty() {
return None;
}
let bounds = edges.iter().fold(
(
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
),
|b, e| {
(
b.0.min(e.lon0).min(e.lon1),
b.1.min(e.lat0).min(e.lat1),
b.2.max(e.lon0).max(e.lon1),
b.3.max(e.lat0).max(e.lat1),
)
},
);
let band_count = ((bounds.3 - bounds.1) * BANDS_PER_DEGREE).ceil() as usize + 1;
let mut bands = vec![Vec::new(); band_count];
let band_of = |lat: f64| ((lat - bounds.1) * BANDS_PER_DEGREE) as usize;
for (index, edge) in edges.iter().enumerate() {
let (lo, hi) = (edge.lat0.min(edge.lat1), edge.lat0.max(edge.lat1));
let index = u32::try_from(index).ok()?;
for band in &mut bands[band_of(lo)..=band_of(hi).min(band_count - 1)] {
band.push(index);
}
}
Some(Self {
bounds,
edges,
bands,
})
}
#[must_use]
pub const fn bounds(&self) -> Bounds {
self.bounds
}
#[must_use]
pub fn may_intersect(&self, bounds: Bounds) -> bool {
let b = self.bounds;
b.0 <= bounds.2 && bounds.0 <= b.2 && b.1 <= bounds.3 && bounds.1 <= b.3
}
#[must_use]
pub fn crossings(&self, lat: f64) -> Vec<f64> {
if lat < self.bounds.1 || lat > self.bounds.3 {
return Vec::new();
}
let band = (((lat - self.bounds.1) * BANDS_PER_DEGREE) as usize).min(self.bands.len() - 1);
let mut xs: Vec<f64> = self.bands[band]
.iter()
.filter_map(|&i| {
let e = self.edges[i as usize];
let crosses = (e.lat0 <= lat) != (e.lat1 <= lat);
crosses.then(|| e.lon0 + (lat - e.lat0) / (e.lat1 - e.lat0) * (e.lon1 - e.lon0))
})
.collect();
xs.sort_by(f64::total_cmp);
xs
}
#[must_use]
pub fn contains(&self, lon: f64, lat: f64) -> bool {
inside(&self.crossings(lat), lon)
}
}
#[must_use]
pub fn inside(crossings: &[f64], lon: f64) -> bool {
crossings.partition_point(|&x| x <= lon) % 2 == 1
}
fn collect_rings(geometry: &Geometry, rings: &mut Vec<Vec<[f64; 2]>>) {
let ring = |r: &Vec<Position>| -> Vec<[f64; 2]> {
r.iter()
.filter(|p| p.len() >= 2)
.map(|p| [p[0], p[1]])
.collect()
};
match &geometry.value {
GeometryValue::Polygon { coordinates } => rings.extend(coordinates.iter().map(ring)),
GeometryValue::MultiPolygon { coordinates } => {
rings.extend(coordinates.iter().flatten().map(ring));
}
GeometryValue::GeometryCollection { geometries } => {
for g in geometries {
collect_rings(g, rings);
}
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn mask() -> ClipMask {
ClipMask::from_rings(&[
vec![
[0.0, 0.0],
[10.0, 0.0],
[10.0, 10.0],
[0.0, 10.0],
[0.0, 0.0],
],
vec![[4.0, 4.0], [6.0, 4.0], [6.0, 6.0], [4.0, 6.0]],
vec![[20.0, 5.0], [21.0, 5.0], [21.0, 6.0], [20.0, 6.0]],
])
.expect("mask")
}
#[test]
fn points_inside_outside_in_the_hole_and_on_the_island() {
let m = mask();
assert!(m.contains(1.0, 1.0));
assert!(m.contains(9.5, 5.0));
assert!(!m.contains(5.0, 5.0), "hole");
assert!(!m.contains(15.0, 5.5), "gap between square and island");
assert!(m.contains(20.5, 5.5), "island");
assert!(!m.contains(-1.0, 5.0));
assert!(!m.contains(5.0, 11.0), "above the bounds");
assert!(!m.contains(5.0, -0.5), "below the bounds");
}
#[test]
fn crossings_list_every_boundary_on_a_row() {
assert_eq!(mask().crossings(5.5), vec![0.0, 4.0, 6.0, 10.0, 20.0, 21.0]);
assert_eq!(mask().crossings(2.0), vec![0.0, 10.0]);
}
#[test]
fn a_row_through_a_vertex_counts_it_once() {
let m = ClipMask::from_rings(&[vec![[0.0, 5.0], [5.0, 0.0], [10.0, 5.0], [5.0, 10.0]]])
.expect("diamond");
assert_eq!(m.crossings(5.0).len() % 2, 0);
assert!(m.contains(5.0, 5.0));
assert!(m.contains(5.0, 9.0));
assert!(!m.contains(1.0, 9.0));
}
#[test]
fn bounds_and_bbox_test() {
let m = mask();
assert_eq!(m.bounds(), (0.0, 0.0, 21.0, 10.0));
assert!(m.may_intersect((9.0, 9.0, 12.0, 12.0)));
assert!(!m.may_intersect((30.0, 0.0, 31.0, 1.0)));
}
#[test]
fn rings_without_area_give_no_mask() {
assert!(ClipMask::from_rings(&[]).is_none());
assert!(ClipMask::from_rings(&[vec![[0.0, 0.0], [1.0, 0.0]]]).is_none());
assert!(
ClipMask::from_rings(&[vec![[0.0, 1.0], [1.0, 1.0], [2.0, 1.0]]]).is_none(),
"a flat ring has no edge that crosses a row"
);
}
#[test]
fn geojson_feature_collection_feature_and_geometry_all_load() {
let dir = tempfile::tempdir().expect("tempdir");
let square = r#"{"type":"Polygon","coordinates":[[[0,0],[2,0],[2,2],[0,2],[0,0]]]}"#;
let multi = r#"{"type":"MultiPolygon","coordinates":[[[[0,0],[2,0],[2,2],[0,2],[0,0]]]]}"#;
let cases = [
square.to_string(),
format!(r#"{{"type":"Feature","properties":{{}},"geometry":{multi}}}"#),
format!(
r#"{{"type":"FeatureCollection","features":[{{"type":"Feature","properties":{{}},"geometry":{{"type":"GeometryCollection","geometries":[{square},{{"type":"Point","coordinates":[9,9]}}]}}}},{{"type":"Feature","properties":{{}},"geometry":null}}]}}"#
),
];
for (i, text) in cases.iter().enumerate() {
let path = dir.path().join(format!("{i}.geojson"));
std::fs::write(&path, text).expect("write");
let m = ClipMask::from_geojson(&path).expect("loads");
assert!(m.contains(1.0, 1.0), "case {i}");
assert!(!m.contains(3.0, 1.0), "case {i}");
}
}
#[test]
fn geojson_without_a_polygon_or_unparseable_is_an_error() {
let dir = tempfile::tempdir().expect("tempdir");
let point = dir.path().join("point.geojson");
std::fs::write(&point, r#"{"type":"Point","coordinates":[1,1]}"#).expect("write");
assert!(ClipMask::from_geojson(&point).is_err());
let junk = dir.path().join("junk.geojson");
std::fs::write(&junk, "not json").expect("write");
assert!(ClipMask::from_geojson(&junk).is_err());
}
}