use crate::GeometryError;
use crate::exact::kernel::first_self_contact;
use crate::types::{
Coord2d, CoordSeq, LineString, LinearRing, MaybeVouched, MultiLineString, MultiPolygon,
Polygon, Unvouched, UnvouchedReason,
};
pub(super) fn segment_distance(p: Coord2d, a: Coord2d, b: Coord2d) -> Option<f64> {
let (abx, aby) = (b.x - a.x, b.y - a.y);
let (apx, apy) = (p.x - a.x, p.y - a.y);
let len = abx.hypot(aby);
let d = if len == 0.0 {
apx.hypot(apy)
} else {
let dot = apx * abx + apy * aby;
let len2 = len * len;
if !dot.is_finite() || !len2.is_finite() {
return None;
}
if dot <= 0.0 {
apx.hypot(apy)
} else if dot >= len2 {
(p.x - b.x).hypot(p.y - b.y)
} else {
(abx * apy - aby * apx).abs() / len
}
};
d.is_finite().then_some(d)
}
fn mark_chain(pts: &[Coord2d], lo: usize, hi: usize, tolerance: f64, keep: &mut [bool]) {
keep[lo] = true;
keep[hi] = true;
let mut stack = vec![(lo, hi)];
while let Some((lo, hi)) = stack.pop() {
if hi <= lo + 1 {
continue;
}
let (a, b) = (pts[lo], pts[hi]);
let mut best: Option<(usize, f64)> = None;
let mut unknown: Option<usize> = None;
for (i, &p) in pts.iter().enumerate().take(hi).skip(lo + 1) {
match segment_distance(p, a, b) {
None => {
unknown.get_or_insert(i);
}
Some(d) => {
if best.is_none_or(|(_, bd)| d > bd) {
best = Some((i, d));
}
}
}
}
let split = match (unknown, best) {
(Some(i), _) => Some(i),
(None, Some((i, d))) if d > tolerance => Some(i),
_ => None,
};
if let Some(i) = split {
keep[i] = true;
stack.push((lo, i));
stack.push((i, hi));
}
}
}
fn simplify_chain(pts: &[Coord2d], tolerance: f64) -> Vec<Coord2d> {
if pts.len() < 3 {
return pts.to_vec();
}
let mut keep = vec![false; pts.len()];
mark_chain(pts, 0, pts.len() - 1, tolerance, &mut keep);
pts.iter()
.zip(&keep)
.filter(|(_, k)| **k)
.map(|(p, _)| *p)
.collect()
}
fn simplify_ring(pts: &[Coord2d], tolerance: f64) -> Vec<Coord2d> {
let n = pts.len();
if n < 3 {
return pts.to_vec();
}
let anchor = pts[0];
let mut far = 1;
let mut far_d = -1.0;
for (i, &p) in pts.iter().enumerate().skip(1) {
match segment_distance(p, anchor, anchor) {
None => {
far = i;
break;
}
Some(d) if d > far_d => {
far = i;
far_d = d;
}
Some(_) => {}
}
}
let mut keep = vec![false; n];
mark_chain(pts, 0, far, tolerance, &mut keep);
let mut second: Vec<Coord2d> = pts[far..].to_vec();
second.push(pts[0]);
let mut keep2 = vec![false; second.len()];
mark_chain(&second, 0, second.len() - 1, tolerance, &mut keep2);
for (k, &kept) in keep2.iter().enumerate().take(second.len() - 1) {
if kept {
keep[far + k] = true;
}
}
pts.iter()
.zip(&keep)
.filter(|(_, k)| **k)
.map(|(p, _)| *p)
.collect()
}
pub(super) fn check_tolerance(tolerance: f64) -> Result<(), GeometryError> {
if tolerance.is_finite() && tolerance >= 0.0 {
Ok(())
} else {
Err(GeometryError::InvalidTolerance { tolerance })
}
}
fn simplified_rings(polygon: &Polygon, tolerance: f64) -> Result<Vec<LinearRing>, GeometryError> {
core::iter::once(polygon.exterior())
.chain(polygon.holes())
.map(|r| {
LinearRing::new(CoordSeq::new(simplify_ring(
r.coords().as_slice(),
tolerance,
)))
})
.collect()
}
fn self_contact(rings: &[LinearRing]) -> Option<(usize, (usize, usize))> {
rings
.iter()
.enumerate()
.find_map(|(ring, r)| first_self_contact(r.coords().as_slice()).map(|edges| (ring, edges)))
}
fn build_polygon(
polygon: &Polygon,
tolerance: f64,
) -> Result<MaybeVouched<Polygon>, GeometryError> {
let mut rings = simplified_rings(polygon, tolerance)?;
let contact = self_contact(&rings);
let exterior = rings.remove(0);
let built = Polygon::new(exterior, rings)?;
Ok(match contact {
None => MaybeVouched::Vouched(built),
Some((0, edges)) => MaybeVouched::Unvouched(Unvouched::new(
built,
UnvouchedReason::SelfIntersecting { edges },
)),
Some((ring, edges)) => MaybeVouched::Unvouched(Unvouched::new(
built,
UnvouchedReason::RingSelfIntersecting { ring, edges },
)),
})
}
impl Polygon {
pub fn simplify(&self, tolerance: f64) -> Result<Polygon, GeometryError> {
check_tolerance(tolerance)?;
if tolerance == 0.0 {
return Ok(self.clone());
}
build_polygon(self, tolerance)?.vouched()
}
pub fn simplify_unvouched(
&self,
tolerance: f64,
) -> Result<MaybeVouched<Polygon>, GeometryError> {
check_tolerance(tolerance)?;
if tolerance == 0.0 {
return Ok(MaybeVouched::Vouched(self.clone()));
}
build_polygon(self, tolerance)
}
}
impl MultiPolygon {
pub fn simplify(&self, tolerance: f64) -> Result<MultiPolygon, GeometryError> {
check_tolerance(tolerance)?;
if tolerance == 0.0 {
return Ok(self.clone());
}
build_multipolygon(self, tolerance)?.vouched()
}
pub fn simplify_unvouched(
&self,
tolerance: f64,
) -> Result<MaybeVouched<MultiPolygon>, GeometryError> {
check_tolerance(tolerance)?;
if tolerance == 0.0 {
return Ok(MaybeVouched::Vouched(self.clone()));
}
build_multipolygon(self, tolerance)
}
}
fn build_multipolygon(
mp: &MultiPolygon,
tolerance: f64,
) -> Result<MaybeVouched<MultiPolygon>, GeometryError> {
let mut parts = Vec::with_capacity(mp.num_polygons());
let mut first_defect: Option<UnvouchedReason> = None;
for (part, p) in mp.polygons().iter().enumerate() {
match build_polygon(p, tolerance)? {
MaybeVouched::Vouched(q) => parts.push(q),
MaybeVouched::Unvouched(u) => {
let (q, reason) = u.into_parts();
if first_defect.is_none() {
let (ring, edges) = match reason {
UnvouchedReason::SelfIntersecting { edges } => (0, edges),
UnvouchedReason::RingSelfIntersecting { ring, edges } => (ring, edges),
other => {
return Err(GeometryError::Unvouched {
reason: other,
inputs: vec![part],
});
}
};
first_defect =
Some(UnvouchedReason::PartSelfIntersecting { part, ring, edges });
}
parts.push(q);
}
}
}
let built = MultiPolygon::new(parts)?;
Ok(match first_defect {
None => MaybeVouched::Vouched(built),
Some(reason) => MaybeVouched::Unvouched(Unvouched::new(built, reason)),
})
}
fn simplify_line_coords(pts: &[Coord2d], tolerance: f64) -> Vec<Coord2d> {
let n = pts.len();
if n >= 4 && pts[0] == pts[n - 1] {
let mut out = simplify_ring(&pts[..n - 1], tolerance);
out.push(pts[0]);
return out;
}
simplify_chain(pts, tolerance)
}
impl LineString {
pub fn simplify(&self, tolerance: f64) -> Result<LineString, GeometryError> {
check_tolerance(tolerance)?;
if tolerance == 0.0 {
return Ok(self.clone());
}
LineString::new(CoordSeq::new(simplify_line_coords(
self.coords().as_slice(),
tolerance,
)))
}
}
impl MultiLineString {
pub fn simplify(&self, tolerance: f64) -> Result<MultiLineString, GeometryError> {
check_tolerance(tolerance)?;
if tolerance == 0.0 {
return Ok(self.clone());
}
self.line_strings()
.iter()
.map(|l| l.simplify(tolerance))
.collect::<Result<Vec<_>, _>>()
.map(MultiLineString::new)
}
}
#[cfg(test)]
mod tests;