use crate::GeometryError;
use crate::ops::certified_twice_area_edges;
use crate::types::{CoordSeq, LinearRing, Polygon, validate_hole_placement};
use crate::types3d::LinearRing3d;
#[derive(Clone, Debug, PartialEq)]
pub struct Polygon3d {
exterior: LinearRing3d,
holes: Vec<LinearRing3d>,
}
impl Polygon3d {
pub fn new(exterior: LinearRing3d, holes: Vec<LinearRing3d>) -> Result<Self, GeometryError> {
let exterior_xy = xy_projection(&exterior)?;
let nz = checked_nz(&exterior_xy)?;
if nz < 0.0 {
return Err(GeometryError::IncorrectWindingOrder);
}
let mut holes_xy = Vec::with_capacity(holes.len());
for (i, hole) in holes.iter().enumerate() {
let hole_xy = xy_projection(hole)?;
let nz = checked_nz(&hole_xy)?;
if nz > 0.0 {
return Err(GeometryError::IncorrectHoleWindingOrder { hole_index: i });
}
holes_xy.push(hole_xy);
}
validate_hole_placement(&exterior_xy, &holes_xy)?;
Ok(Self { exterior, holes })
}
pub fn new_simple(exterior: LinearRing3d) -> Result<Self, GeometryError> {
Self::new(exterior, vec![])
}
pub fn exterior(&self) -> &LinearRing3d {
&self.exterior
}
pub fn holes(&self) -> &[LinearRing3d] {
&self.holes
}
pub fn num_holes(&self) -> usize {
self.holes.len()
}
pub(crate) fn xy_projection(&self) -> Result<Polygon, GeometryError> {
let exterior = xy_projection(&self.exterior)?;
let holes = self
.holes
.iter()
.map(xy_projection)
.collect::<Result<Vec<_>, _>>()?;
Polygon::new(exterior, holes)
}
}
fn xy_projection(ring: &LinearRing3d) -> Result<LinearRing, GeometryError> {
let coords = ring.coords().iter().map(|c| c.to_2d()).collect();
LinearRing::new(CoordSeq::new(coords)).map_err(|_| GeometryError::DegenerateRing)
}
fn checked_nz(ring_xy: &LinearRing) -> Result<f64, GeometryError> {
let twice = certified_twice_area_edges(ring_xy.edges());
if !twice.is_finite() {
return Err(GeometryError::NonFiniteResult);
}
if twice == 0.0 {
return Err(GeometryError::DegenerateRing);
}
Ok(twice)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(
clippy::float_cmp,
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::range_plus_one,
clippy::no_effect_underscore_binding
)]
mod tests {
use super::*;
use crate::types3d::{Coord3d, CoordSeq3d};
fn ring(pts: &[(f64, f64, f64)]) -> LinearRing3d {
LinearRing3d::new(CoordSeq3d::new(
pts.iter().map(|&(x, y, z)| Coord3d::new(x, y, z)).collect(),
))
.unwrap()
}
fn ccw_square() -> LinearRing3d {
ring(&[
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0),
(1.0, 1.0, 0.0),
(0.0, 1.0, 0.0),
])
}
fn cw_square() -> LinearRing3d {
ring(&[
(0.0, 0.0, 0.0),
(0.0, 1.0, 0.0),
(1.0, 1.0, 0.0),
(1.0, 0.0, 0.0),
])
}
fn cw_inner() -> LinearRing3d {
ring(&[
(0.25, 0.25, 0.0),
(0.25, 0.75, 0.0),
(0.75, 0.75, 0.0),
(0.75, 0.25, 0.0),
])
}
fn ccw_inner() -> LinearRing3d {
ring(&[
(0.25, 0.25, 0.0),
(0.75, 0.25, 0.0),
(0.75, 0.75, 0.0),
(0.25, 0.75, 0.0),
])
}
#[test]
fn accepts_ccw_exterior_with_cw_hole() {
let p = Polygon3d::new(ccw_square(), vec![cw_inner()]).unwrap();
assert_eq!(p.num_holes(), 1);
assert_eq!(p.holes().len(), 1);
assert_eq!(*p.exterior(), ccw_square());
}
#[test]
fn rejects_cw_exterior_ring() {
let err = Polygon3d::new_simple(cw_square()).unwrap_err();
assert_eq!(err, GeometryError::IncorrectWindingOrder);
}
#[test]
fn rejects_ccw_hole_ring_with_index() {
let err = Polygon3d::new(ccw_square(), vec![cw_inner(), ccw_inner()]).unwrap_err();
assert_eq!(
err,
GeometryError::IncorrectHoleWindingOrder { hole_index: 1 }
);
}
#[test]
fn rejects_near_zero_normal_ring() {
let r = ring(&[(0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (2.0, 2.0, 2.0)]);
assert_eq!(r.newell_normal(), [0.0, 0.0, 0.0]);
assert_eq!(
Polygon3d::new_simple(r).unwrap_err(),
GeometryError::DegenerateRing
);
}
#[test]
fn rejects_degenerate_hole() {
let r = ring(&[(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0)]);
assert_eq!(
Polygon3d::new(ccw_square(), vec![r]).unwrap_err(),
GeometryError::DegenerateRing
);
}
#[test]
fn vertical_ring_is_rejected_as_degenerate() {
let r = ring(&[
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0),
(1.0, 0.0, 1.0),
(0.0, 0.0, 1.0),
]);
assert_eq!(
Polygon3d::new_simple(r).unwrap_err(),
GeometryError::DegenerateRing
);
}
#[test]
fn z_values_do_not_change_winding_for_horizontal_offsets() {
let r = ring(&[
(0.0, 0.0, 7.0),
(1.0, 0.0, 7.0),
(1.0, 1.0, 7.0),
(0.0, 1.0, 7.0),
]);
assert!(Polygon3d::new_simple(r).is_ok());
}
#[test]
fn tilted_plane_winding_follows_xy_projection() {
let ccw = ring(&[
(0.0, 0.0, 0.0),
(1.0, 0.0, 1.0),
(1.0, 1.0, 1.0),
(0.0, 1.0, 0.0),
]);
assert!(Polygon3d::new_simple(ccw).is_ok());
let cw = ring(&[
(0.0, 1.0, 0.0),
(1.0, 1.0, 1.0),
(1.0, 0.0, 1.0),
(0.0, 0.0, 0.0),
]);
assert_eq!(
Polygon3d::new_simple(cw).unwrap_err(),
GeometryError::IncorrectWindingOrder
);
}
fn ring_perimeter(ring: &LinearRing3d) -> f64 {
ring.edges()
.map(|(a, b)| (b.x - a.x).hypot(b.y - a.y).hypot(b.z - a.z))
.sum()
}
fn native_checked_nz(r: &LinearRing3d) -> Result<f64, GeometryError> {
let nz = r.newell_normal()[2];
if (nz * 0.5).abs() < f64::EPSILON * ring_perimeter(r) * ring_perimeter(r) {
return Err(GeometryError::DegenerateRing);
}
Ok(nz)
}
fn state_plane_slivers() -> [LinearRing3d; 2] {
[
ring(&[
(
1_449_864.908_798_434_8,
549_999.994_734_418_9,
718.970_082_803_438_8,
),
(
1_449_729.817_614_475_3,
549_999.989_468_837_3,
644.439_972_030_012_4,
),
(
1_449_999.999_962_733_4,
549_999.999_999_999_8,
878.229_677_691_913_4,
),
]),
ring(&[
(
1_450_364.025_170_730_7,
550_000.010_303_409_4,
652.734_002_687_942_4,
),
(1_449_999.999_993_060_7, 550_000.0, 570.035_090_337_130_4),
(
1_450_182.012_582_091,
550_000.005_151_704_7,
574.906_760_078_228_8,
),
]),
]
}
fn reversed(r: &LinearRing3d) -> LinearRing3d {
let mut v: Vec<Coord3d> = r.coords().iter().copied().collect();
v.reverse();
LinearRing3d::new(CoordSeq3d::new(v)).unwrap()
}
#[test]
fn state_plane_slivers_are_counterclockwise_and_their_reversals_clockwise() {
for r in state_plane_slivers() {
assert!(Polygon3d::new_simple(r.clone()).is_ok());
let rev = reversed(&r);
assert_eq!(
Polygon3d::new_simple(rev.clone()).unwrap_err(),
GeometryError::IncorrectWindingOrder
);
let around = ring(&[
(1_449_000.0, 549_000.0, 0.0),
(1_451_000.0, 549_000.0, 0.0),
(1_451_000.0, 551_000.0, 0.0),
(1_449_000.0, 551_000.0, 0.0),
]);
assert!(Polygon3d::new(around, vec![rev]).is_ok());
}
}
#[test]
fn the_native_sum_asserted_the_wrong_sign_on_the_slivers() {
for r in state_plane_slivers() {
let old = native_checked_nz(&r).unwrap();
assert!(old < 0.0, "native nz = {old:e}");
let xy = xy_projection(&r).unwrap();
assert!(checked_nz(&xy).unwrap() > 0.0);
}
}
#[test]
fn the_native_sum_refused_a_ring_two_hundred_times_the_threshold() {
let h = 2f64.powi(-33);
let ccw = ring(&[
(1_450_000.0, 550_000.0, 700.0),
(1_450_016.0, 550_016.0, 650.0),
(1_450_008.0, 550_008.0 + h, 720.0),
]);
let cw = reversed(&ccw);
for r in [&ccw, &cw] {
assert_eq!(
native_checked_nz(r).unwrap_err(),
GeometryError::DegenerateRing
);
assert_eq!(r.newell_normal()[2], 0.0);
}
assert!(Polygon3d::new_simple(ccw).is_ok());
assert_eq!(
Polygon3d::new_simple(cw).unwrap_err(),
GeometryError::IncorrectWindingOrder
);
}
#[test]
fn a_sliver_at_1e9_has_its_exact_sign_in_either_order() {
let o = 1.0e9_f64;
let ccw = ring(&[
(o, o, 1.0),
(o + 4.0, o + 1.0, 2.0),
(o + 3.0, o + 1.0, 3.0),
]);
let cw = ring(&[
(o, o, 1.0),
(o + 3.0, o + 1.0, 3.0),
(o + 4.0, o + 1.0, 2.0),
]);
let xy = xy_projection(&ccw).unwrap();
assert_eq!(checked_nz(&xy).unwrap(), 1.0);
let xy = xy_projection(&cw).unwrap();
assert_eq!(checked_nz(&xy).unwrap(), -1.0);
assert!(Polygon3d::new_simple(ccw).is_ok());
assert_eq!(
Polygon3d::new_simple(cw).unwrap_err(),
GeometryError::IncorrectWindingOrder
);
}
#[test]
fn an_exactly_collinear_ring_far_from_the_origin_is_degenerate() {
let o = 1.0e9_f64;
let r = ring(&[
(o, o, 5.0),
(o + 1.0, o + 1.0, 6.0),
(o + 2.0, o + 2.0, 7.0),
]);
assert_eq!(
Polygon3d::new_simple(r).unwrap_err(),
GeometryError::DegenerateRing
);
}
#[test]
fn an_overflowing_projected_area_is_non_finite_not_accepted() {
let r = ring(&[
(0.0, 0.0, 0.0),
(1e200, 0.0, 0.0),
(1e200, 1e200, 0.0),
(0.0, 1e200, 0.0),
]);
assert_eq!(
Polygon3d::new_simple(r).unwrap_err(),
GeometryError::NonFiniteResult
);
}
#[test]
fn a_hole_outside_the_exterior_is_refused() {
let outside = ring(&[
(2.0, 0.0, 1.0),
(2.0, 1.0, 1.0),
(3.0, 1.0, 1.0),
(3.0, 0.0, 1.0),
]);
assert_eq!(
Polygon3d::new(ccw_square(), vec![cw_inner(), outside]).unwrap_err(),
GeometryError::HoleNotInsideExterior { hole_index: 1 }
);
}
#[test]
fn a_hole_crossing_the_exterior_is_refused() {
let crossing = ring(&[
(0.5, 0.25, 0.0),
(0.5, 0.75, 0.0),
(1.5, 0.75, 0.0),
(1.5, 0.25, 0.0),
]);
assert_eq!(
Polygon3d::new(ccw_square(), vec![crossing]).unwrap_err(),
GeometryError::HoleNotInsideExterior { hole_index: 0 }
);
}
#[test]
fn overlapping_holes_are_refused_with_the_pair() {
let shifted = ring(&[
(0.5, 0.5, 9.0),
(0.5, 0.9, 9.0),
(0.9, 0.9, 9.0),
(0.9, 0.5, 9.0),
]);
assert_eq!(
Polygon3d::new(ccw_square(), vec![cw_inner(), shifted]).unwrap_err(),
GeometryError::OverlappingHoles {
first: 0,
second: 1
}
);
}
#[test]
fn two_separate_holes_at_different_heights_are_accepted() {
let a = ring(&[
(0.1, 0.1, 0.0),
(0.1, 0.4, 0.0),
(0.4, 0.4, 0.0),
(0.4, 0.1, 0.0),
]);
let b = ring(&[
(0.6, 0.6, 50.0),
(0.6, 0.9, 50.0),
(0.9, 0.9, 50.0),
(0.9, 0.6, 50.0),
]);
let p = Polygon3d::new(ccw_square(), vec![a, b]).unwrap();
assert_eq!(p.num_holes(), 2);
}
#[test]
fn a_hole_touching_the_exterior_at_a_vertex_is_accepted() {
let touching = ring(&[(0.0, 0.0, 0.0), (0.25, 0.5, 0.0), (0.5, 0.25, 0.0)]);
assert!(Polygon3d::new(ccw_square(), vec![touching]).is_ok());
}
#[test]
fn a_ring_with_a_vertical_edge_is_degenerate() {
let r = ring(&[
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0),
(1.0, 0.0, 5.0),
(1.0, 1.0, 5.0),
(0.0, 1.0, 5.0),
]);
assert_eq!(
Polygon3d::new_simple(r).unwrap_err(),
GeometryError::DegenerateRing
);
let hole = ring(&[
(0.25, 0.25, 0.0),
(0.25, 0.75, 0.0),
(0.25, 0.75, 3.0),
(0.75, 0.75, 3.0),
(0.75, 0.25, 3.0),
]);
assert_eq!(
Polygon3d::new(ccw_square(), vec![hole]).unwrap_err(),
GeometryError::DegenerateRing
);
}
#[test]
fn the_xy_projection_is_the_polygon_without_z() {
let p = Polygon3d::new(ccw_square(), vec![cw_inner()]).unwrap();
let q = p.xy_projection().unwrap();
assert_eq!(q.num_holes(), 1);
let c: Vec<(f64, f64)> = q.exterior().coords().iter().map(|c| (c.x, c.y)).collect();
assert_eq!(c, vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]);
}
#[test]
fn new_simple_equivalent_to_new_with_empty_holes() {
assert_eq!(
Polygon3d::new_simple(ccw_square()).unwrap(),
Polygon3d::new(ccw_square(), vec![]).unwrap()
);
}
}