use arithmetica::{Sign, orient2d};
use crate::types::Coord2d;
use crate::types::LinearRing;
#[inline]
pub(crate) fn orient(a: Coord2d, b: Coord2d, c: Coord2d) -> Sign {
orient2d([a.x, a.y], [b.x, b.y], [c.x, c.y]).unwrap_or(Sign::Zero)
}
pub(crate) fn on_segment(p: Coord2d, a: Coord2d, b: Coord2d) -> bool {
p.x >= a.x.min(b.x)
&& p.x <= a.x.max(b.x)
&& p.y >= a.y.min(b.y)
&& p.y <= a.y.max(b.y)
&& orient(a, b, p) == Sign::Zero
}
pub(crate) fn segments_properly_cross(a: Coord2d, b: Coord2d, c: Coord2d, d: Coord2d) -> bool {
let d1 = orient(c, d, a);
let d2 = orient(c, d, b);
if d1 == Sign::Zero || d2 == Sign::Zero || d1 == d2 {
return false;
}
let d3 = orient(a, b, c);
let d4 = orient(a, b, d);
d3 != Sign::Zero && d4 != Sign::Zero && d3 != d4
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RingLocation {
Inside,
OnBoundary,
Outside,
}
pub(crate) fn ring_contains_off_boundary(p: Coord2d, ring: &LinearRing) -> bool {
let mut inside = false;
for (a, b) in ring.edges() {
if edge_crosses_ray(a, b, p) {
inside = !inside;
}
}
inside
}
pub(crate) fn edge_crosses_ray(a: Coord2d, b: Coord2d, p: Coord2d) -> bool {
if (a.y > p.y) == (b.y > p.y) {
return false;
}
let s = orient(a, b, p);
if b.y > a.y {
s == Sign::Positive
} else {
s == Sign::Negative
}
}
pub(crate) fn locate_in_ring(p: Coord2d, ring: &LinearRing) -> RingLocation {
if ring.edges().any(|(a, b)| on_segment(p, a, b)) {
return RingLocation::OnBoundary;
}
if ring_contains_off_boundary(p, ring) {
RingLocation::Inside
} else {
RingLocation::Outside
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RingPlacement {
Inside,
Outside,
Crossing,
SharedEdge,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum SubEdgeSide {
Inside,
Outside,
Along,
}
fn sub_edge_side(s: Coord2d, e: Coord2d, outer: &LinearRing) -> SubEdgeSide {
for p in [s, e] {
match locate_in_ring(p, outer) {
RingLocation::Inside => return SubEdgeSide::Inside,
RingLocation::Outside => return SubEdgeSide::Outside,
RingLocation::OnBoundary => {}
}
}
if edge_along_boundary(s, e, outer) {
return SubEdgeSide::Along;
}
if chord_departs_inward(s, e, outer) {
SubEdgeSide::Inside
} else {
SubEdgeSide::Outside
}
}
fn cuts_along(a: Coord2d, b: Coord2d, outer: &LinearRing) -> Vec<Coord2d> {
let mut cuts: Vec<Coord2d> = outer
.coords()
.as_slice()
.iter()
.copied()
.filter(|&v| v != a && v != b && on_segment(v, a, b))
.collect();
#[allow(clippy::float_cmp)] let key = |c: &Coord2d| if a.x == b.x { c.y } else { c.x };
let forward = key(&b) > key(&a);
cuts.sort_by(|p, q| {
let o = key(p).total_cmp(&key(q));
if forward { o } else { o.reverse() }
});
cuts.dedup();
cuts
}
pub fn place_ring(inner: &LinearRing, outer: &LinearRing) -> RingPlacement {
if rings_properly_cross(inner, outer) {
return RingPlacement::Crossing;
}
let (mut inside, mut outside, mut along) = (false, false, false);
for (a, b) in inner.edges() {
let mut s = a;
for e in cuts_along(a, b, outer)
.into_iter()
.chain(core::iter::once(b))
{
match sub_edge_side(s, e, outer) {
SubEdgeSide::Inside => inside = true,
SubEdgeSide::Outside => outside = true,
SubEdgeSide::Along => along = true,
}
s = e;
}
}
if along {
RingPlacement::SharedEdge
} else if inside && outside {
RingPlacement::Crossing
} else if inside {
RingPlacement::Inside
} else {
RingPlacement::Outside
}
}
pub(crate) fn first_self_contact(v: &[Coord2d]) -> Option<(usize, usize)> {
if v.len() < 3 {
return Some((0, 0));
}
self_contacts(v, true).first().copied()
}
pub(crate) fn self_contacts(v: &[Coord2d], first_only: bool) -> Vec<(usize, usize)> {
if v.len() > SWEEP_MIN_VERTICES {
return self_contacts_sweep(v, first_only);
}
self_contacts_scan(v, first_only)
}
const SWEEP_MIN_VERTICES: usize = 64;
fn self_contacts_scan(v: &[Coord2d], first_only: bool) -> Vec<(usize, usize)> {
let n = v.len();
let mut found = Vec::new();
if n < 3 {
return found;
}
let edge = |i: usize| (v[i], v[(i + 1) % n]);
let boxes_meet = |(a, b): (Coord2d, Coord2d), (c, d): (Coord2d, Coord2d)| {
a.x.min(b.x) <= c.x.max(d.x)
&& c.x.min(d.x) <= a.x.max(b.x)
&& a.y.min(b.y) <= c.y.max(d.y)
&& c.y.min(d.y) <= a.y.max(b.y)
};
for i in 0..n {
let (a, b) = edge(i);
let (_, c) = edge((i + 1) % n);
if on_segment(c, a, b) || on_segment(a, b, c) {
found.push((i, (i + 1) % n));
if first_only {
return found;
}
}
for j in (i + 2)..n {
if i == 0 && j == n - 1 {
continue; }
let (c, d) = edge(j);
if !boxes_meet((a, b), (c, d)) {
continue;
}
if segments_properly_cross(a, b, c, d)
|| on_segment(a, c, d)
|| on_segment(b, c, d)
|| on_segment(c, a, b)
|| on_segment(d, a, b)
{
found.push((i, j));
if first_only {
return found;
}
}
}
}
found
}
fn self_contacts_sweep(v: &[Coord2d], first_only: bool) -> Vec<(usize, usize)> {
let n = v.len();
let edge = |i: usize| (v[i], v[(i + 1) % n]);
let lo: Vec<f64> = (0..n).map(|i| v[i].x.min(v[(i + 1) % n].x)).collect();
let hi: Vec<f64> = (0..n).map(|i| v[i].x.max(v[(i + 1) % n].x)).collect();
let lo_x = |i: usize| lo[i];
let hi_x = |i: usize| hi[i];
let mut found: Vec<(usize, u8, usize)> = Vec::new();
for i in 0..n {
let (a, b) = edge(i);
let (_, c) = edge((i + 1) % n);
if on_segment(c, a, b) || on_segment(a, b, c) {
found.push((i, 0, (i + 1) % n));
}
}
let mut order: Vec<usize> = (0..n).collect();
order.sort_by(|&i, &j| lo_x(i).total_cmp(&lo_x(j)));
let mut active: Vec<usize> = Vec::new();
for &k in &order {
let x = lo_x(k);
active.retain(|&i| hi_x(i) >= x);
let (a, b) = edge(k);
for &m in &active {
let (i, j) = (k.min(m), k.max(m));
if j < i + 2 || (i == 0 && j == n - 1) {
continue; }
let (c, d) = edge(m);
if a.y.min(b.y) > c.y.max(d.y) || c.y.min(d.y) > a.y.max(b.y) {
continue;
}
let ((p, q), (r, t)) = (edge(i), edge(j));
if segments_properly_cross(p, q, r, t)
|| on_segment(p, r, t)
|| on_segment(q, r, t)
|| on_segment(r, p, q)
|| on_segment(t, p, q)
{
found.push((i, 1, j));
}
}
active.push(k);
}
found.sort_unstable();
if first_only {
found.truncate(1);
}
found.into_iter().map(|(i, _, j)| (i, j)).collect()
}
pub(crate) fn rings_properly_cross(a: &LinearRing, b: &LinearRing) -> bool {
let b_edges: Vec<(Coord2d, Coord2d)> = b.edges().collect();
a.edges().any(|(p, q)| {
b_edges
.iter()
.any(|&(r, s)| segments_properly_cross(p, q, r, s))
})
}
pub(crate) fn rings_interior_disjoint(a: &LinearRing, b: &LinearRing) -> bool {
place_ring(a, b) == RingPlacement::Outside && place_ring(b, a) == RingPlacement::Outside
}
fn sub_edges(
inner: &LinearRing,
outer: &LinearRing,
) -> Vec<(usize, Coord2d, Coord2d, SubEdgeSide)> {
let mut out = Vec::new();
for (i, (a, b)) in inner.edges().enumerate() {
let mut s = a;
for e in cuts_along(a, b, outer)
.into_iter()
.chain(core::iter::once(b))
{
out.push((i, s, e, sub_edge_side(s, e, outer)));
s = e;
}
}
out
}
fn edge_holding(p: Coord2d, ring: &LinearRing) -> Option<usize> {
ring.edges().position(|(a, b)| on_segment(p, a, b))
}
pub(crate) fn contact_witness(inner: &LinearRing, outer: &LinearRing) -> Option<(usize, usize)> {
let pieces = sub_edges(inner, outer);
for &(i, s, e, side) in &pieces {
if side == SubEdgeSide::Along
&& let Some(j) = outer
.edges()
.position(|(p, q)| on_segment(s, p, q) && on_segment(e, p, q))
{
return Some((i, j));
}
}
let outer_edges: Vec<(Coord2d, Coord2d)> = outer.edges().collect();
for (i, (a, b)) in inner.edges().enumerate() {
if let Some(j) = outer_edges
.iter()
.position(|&(c, d)| segments_properly_cross(a, b, c, d))
{
return Some((i, j));
}
}
let n = pieces.len();
for k in 0..n {
let prev = pieces[(k + n - 1) % n].3;
let (i, s, _, side) = pieces[k];
if prev != side
&& let Some(j) = edge_holding(s, outer)
{
return Some((i, j));
}
}
for (i, (a, b)) in inner.edges().enumerate() {
if let Some(j) = outer_edges.iter().position(|&(c, d)| {
segments_properly_cross(a, b, c, d)
|| on_segment(a, c, d)
|| on_segment(b, c, d)
|| on_segment(c, a, b)
|| on_segment(d, a, b)
}) {
return Some((i, j));
}
}
None
}
pub(crate) fn same_point_set(a: &LinearRing, b: &LinearRing) -> bool {
sub_edges(a, b)
.iter()
.all(|&(_, _, _, side)| side == SubEdgeSide::Along)
&& sub_edges(b, a)
.iter()
.all(|&(_, _, _, side)| side == SubEdgeSide::Along)
}
pub(crate) fn ring_touch_points(a: &LinearRing, b: &LinearRing) -> Vec<Coord2d> {
let mut points: Vec<Coord2d> = Vec::new();
let candidates = a
.coords()
.as_slice()
.iter()
.filter(|&&v| locate_in_ring(v, b) == RingLocation::OnBoundary)
.chain(
b.coords()
.as_slice()
.iter()
.filter(|&&v| locate_in_ring(v, a) == RingLocation::OnBoundary),
);
for &p in candidates {
if !points.contains(&p) {
points.push(p);
}
}
points
}
fn edge_along_boundary(a: Coord2d, b: Coord2d, ring: &LinearRing) -> bool {
ring.edges()
.any(|(p, q)| on_segment(a, p, q) && on_segment(b, p, q))
}
fn chord_departs_inward(a: Coord2d, b: Coord2d, ring: &LinearRing) -> bool {
let ccw = ring.signed_area() > 0.0;
let inward = |s: Sign| -> bool {
match s {
Sign::Positive => ccw,
Sign::Negative => !ccw,
Sign::Zero => false,
}
};
let pts = ring.coords().as_slice();
let n = pts.len();
if let Some(k) = pts.iter().position(|&v| v == a) {
let p = pts[(k + n - 1) % n];
let q = pts[(k + 1) % n];
let convex = inward(orient(p, a, q));
let left_of_in = inward(orient(p, a, b));
let left_of_out = inward(orient(a, q, b));
return if convex {
left_of_in && left_of_out
} else {
left_of_in || left_of_out
};
}
for (p, q) in ring.edges() {
if on_segment(a, p, q) {
return inward(orient(p, q, b));
}
}
false
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(
clippy::float_cmp,
clippy::unreadable_literal,
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::types::CoordSeq;
fn c(x: f64, y: f64) -> Coord2d {
Coord2d::new(x, y)
}
fn ring(pts: &[(f64, f64)]) -> LinearRing {
LinearRing::new(CoordSeq::new(pts.iter().map(|&(x, y)| c(x, y)).collect())).unwrap()
}
fn unit_square() -> LinearRing {
ring(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])
}
#[test]
fn proper_crossing_is_detected_and_touching_is_not() {
assert!(segments_properly_cross(
c(0.0, 0.0),
c(4.0, 4.0),
c(0.0, 4.0),
c(4.0, 0.0)
));
assert!(!segments_properly_cross(
c(0.0, 0.0),
c(4.0, 0.0),
c(2.0, 0.0),
c(2.0, 3.0)
));
assert!(!segments_properly_cross(
c(0.0, 0.0),
c(3.0, 3.0),
c(3.0, 3.0),
c(6.0, 0.0)
));
assert!(!segments_properly_cross(
c(0.0, 0.0),
c(4.0, 0.0),
c(2.0, 0.0),
c(6.0, 0.0)
));
assert!(!segments_properly_cross(
c(0.0, 0.0),
c(4.0, 0.0),
c(0.0, 1.0),
c(4.0, 1.0)
));
}
#[test]
fn locate_in_ring_distinguishes_all_three() {
let r = unit_square();
assert_eq!(locate_in_ring(c(5.0, 5.0), &r), RingLocation::Inside);
assert_eq!(locate_in_ring(c(15.0, 5.0), &r), RingLocation::Outside);
assert_eq!(locate_in_ring(c(10.0, 5.0), &r), RingLocation::OnBoundary);
assert_eq!(
locate_in_ring(c(0.0, 0.0), &r),
RingLocation::OnBoundary,
"vertex"
);
assert_eq!(
locate_in_ring(c(5.0, 10.0 - 1e-9), &r),
RingLocation::Inside
);
assert_eq!(locate_in_ring(c(-1.0, 10.0), &r), RingLocation::Outside);
}
#[test]
fn locate_is_winding_agnostic() {
let cw = ring(&[(0.0, 0.0), (0.0, 10.0), (10.0, 10.0), (10.0, 0.0)]);
assert_eq!(locate_in_ring(c(5.0, 5.0), &cw), RingLocation::Inside);
assert_eq!(locate_in_ring(c(15.0, 5.0), &cw), RingLocation::Outside);
}
#[test]
fn place_ring_covers_the_four_pictures() {
let outer = unit_square();
let inside = ring(&[(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)]);
let disjoint = ring(&[(20.0, 20.0), (24.0, 20.0), (24.0, 24.0), (20.0, 24.0)]);
let overlapping = ring(&[(5.0, 5.0), (15.0, 5.0), (15.0, 15.0), (5.0, 15.0)]);
let containing = ring(&[(-5.0, -5.0), (15.0, -5.0), (15.0, 15.0), (-5.0, 15.0)]);
assert_eq!(place_ring(&inside, &outer), RingPlacement::Inside);
assert_eq!(place_ring(&disjoint, &outer), RingPlacement::Outside);
assert_eq!(place_ring(&overlapping, &outer), RingPlacement::Crossing);
assert_eq!(
place_ring(&containing, &outer),
RingPlacement::Outside,
"a ring that surrounds `outer` has every vertex outside it"
);
assert_eq!(
place_ring(&outer, &containing),
RingPlacement::Inside,
"and from the other side, `outer` is inside it"
);
}
#[test]
fn touching_at_a_vertex_is_still_inside() {
let outer = unit_square();
let touching = ring(&[(0.0, 0.0), (3.0, 1.0), (1.0, 3.0)]);
assert_eq!(place_ring(&touching, &outer), RingPlacement::Inside);
}
#[test]
fn identical_rings_share_their_whole_boundary_and_are_not_disjoint() {
let a = unit_square();
let b = unit_square();
assert_eq!(place_ring(&a, &b), RingPlacement::SharedEdge);
assert!(!rings_interior_disjoint(&a, &b));
}
#[test]
fn disjointness_requires_both_directions() {
let big = unit_square();
let small = ring(&[(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)]);
assert_eq!(place_ring(&big, &small), RingPlacement::Outside);
assert!(!rings_interior_disjoint(&big, &small));
let far = ring(&[(20.0, 20.0), (24.0, 20.0), (24.0, 24.0), (20.0, 24.0)]);
assert!(rings_interior_disjoint(&big, &far));
}
#[test]
fn rings_touching_at_one_vertex_are_disjoint() {
let a = ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)]);
let b = ring(&[(4.0, 4.0), (8.0, 4.0), (8.0, 8.0), (4.0, 8.0)]);
assert!(rings_interior_disjoint(&a, &b));
}
#[test]
fn regression_offset_properties_case_2_hole_crosses_exterior() {
let ext = ring(&[
(-4.003133454020272, 16.42962109085804),
(-9.590873621482961, -8.093162064591926),
(-15.530846932663101, -34.6057195833789),
]);
let hole = ring(&[
(-3.1430959461392274e-17, -0.17110217402152594),
(-5.647170630321792, 6.915789436662523e-16),
(3.41673958700421e-16, 5.579959200290364),
(2.949389742165336, 0.0),
]);
assert_ne!(place_ring(&hole, &ext), RingPlacement::Inside);
}
#[test]
fn an_inscribed_diamond_is_inside_the_square() {
let square_cw = ring(&[(2.0, 2.0), (2.0, 6.0), (6.0, 6.0), (6.0, 2.0)]);
let diamond_ccw = ring(&[(6.0, 4.0), (4.0, 6.0), (2.0, 4.0), (4.0, 2.0)]);
assert_eq!(place_ring(&diamond_ccw, &square_cw), RingPlacement::Inside);
assert_eq!(place_ring(&square_cw, &diamond_ccw), RingPlacement::Outside);
let square_ccw = ring(&[(2.0, 2.0), (6.0, 2.0), (6.0, 6.0), (2.0, 6.0)]);
assert_eq!(place_ring(&diamond_ccw, &square_ccw), RingPlacement::Inside);
}
#[test]
fn rings_touching_a_concave_ring_at_every_vertex_are_classified_by_every_edge() {
let concave = ring(&[(0.0, 0.0), (8.0, 0.0), (8.0, 8.0), (4.0, 4.0), (0.0, 8.0)]);
let notch = ring(&[(4.0, 4.0), (6.0, 6.0), (2.0, 6.0)]);
assert_eq!(place_ring(¬ch, &concave), RingPlacement::SharedEdge);
let spans = ring(&[(4.0, 0.0), (6.0, 6.0), (2.0, 6.0)]);
assert_eq!(place_ring(&spans, &concave), RingPlacement::Crossing);
let below = ring(&[(4.0, 4.0), (0.0, 2.0), (8.0, 2.0)]);
assert_eq!(place_ring(&below, &concave), RingPlacement::Inside);
}
#[test]
fn a_ring_leaving_through_two_boundary_vertices_is_crossing() {
let l = ring(&[
(0.0, 0.0),
(8.0, 0.0),
(8.0, 4.0),
(4.0, 4.0),
(4.0, 8.0),
(0.0, 8.0),
]);
let tri = ring(&[(3.0, 3.0), (4.0, 6.0), (6.0, 4.0)]);
assert_eq!(place_ring(&tri, &l), RingPlacement::Crossing);
}
#[test]
fn a_ring_passing_through_a_reflex_vertex_is_crossing() {
let l = ring(&[
(0.0, 0.0),
(8.0, 0.0),
(8.0, 4.0),
(4.0, 4.0),
(4.0, 8.0),
(0.0, 8.0),
]);
let tri = ring(&[(2.0, 2.0), (6.0, 6.0), (2.0, 6.0)]);
assert_eq!(place_ring(&tri, &l), RingPlacement::Crossing);
let touch = ring(&[(2.0, 2.0), (4.0, 4.0), (2.0, 6.0)]);
assert_eq!(place_ring(&touch, &l), RingPlacement::Inside);
}
#[test]
fn a_chord_through_a_reflex_vertex_is_cut_there() {
let u = ring(&[
(0., 0.),
(12., 0.),
(12., 8.),
(8., 8.),
(8., 2.),
(4., 2.),
(4., 8.),
(0., 8.),
]);
let tri = ring(&[(0., 0.), (8., 4.), (12., 1.)]);
assert_eq!(place_ring(&tri, &u), RingPlacement::Crossing);
}
#[test]
fn rings_sharing_an_edge_stretch_are_shared_edge_not_disjoint() {
let a = ring(&[(1.0, 2.0), (1.0, 6.0), (3.0, 6.0), (3.0, 2.0)]);
let b = ring(&[(3.0, 4.0), (3.0, 6.0), (6.0, 6.0), (6.0, 4.0)]);
assert_eq!(place_ring(&a, &b), RingPlacement::SharedEdge);
assert!(!rings_interior_disjoint(&a, &b));
let hole = ring(&[(0.0, 2.0), (0.0, 4.0), (3.0, 4.0), (3.0, 2.0)]);
assert_eq!(place_ring(&hole, &unit_square()), RingPlacement::SharedEdge);
}
fn coords(pts: &[(f64, f64)]) -> Vec<Coord2d> {
pts.iter().map(|&(x, y)| Coord2d::new(x, y)).collect()
}
#[test]
fn collinear_consecutive_vertices_are_simple() {
let v = coords(&[
(0.0, 0.0),
(2.0, 0.0),
(4.0, 0.0),
(4.0, 4.0),
(4.0, 6.0),
(0.0, 6.0),
]);
assert_eq!(first_self_contact(&v), None);
}
#[test]
fn a_pinched_ring_is_not_simple() {
let v = coords(&[
(0.0, 0.0),
(6.0, 0.0),
(6.0, 6.0),
(3.0, 3.0),
(4.0, 2.0),
(2.0, 2.0),
(3.0, 3.0),
(0.0, 6.0),
]);
assert!(first_self_contact(&v).is_some());
}
#[test]
fn a_proper_crossing_is_still_caught() {
let v = coords(&[(0.0, 0.0), (2.0, 2.0), (2.0, 0.0), (0.0, 2.0)]);
assert!(first_self_contact(&v).is_some());
}
#[test]
fn the_sweep_reports_what_the_double_loop_reports() {
let mut state = 0x5EED_5EEDu64;
let mut next = || {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
state >> 33
};
let mut with_contacts = 0;
for case in 0..300 {
let n = 65 + (next() % 200) as usize;
let span = if case % 3 == 0 { 6 } else { 40 };
let mut v: Vec<Coord2d> = (0..n)
.map(|_| Coord2d::new((next() % span) as f64, (next() % span) as f64))
.collect();
v.dedup();
if v.len() <= SWEEP_MIN_VERTICES {
continue;
}
let all = self_contacts_sweep(&v, false);
assert_eq!(all, self_contacts_scan(&v, false), "case {case}");
assert_eq!(
self_contacts_sweep(&v, true),
self_contacts_scan(&v, true),
"case {case}"
);
with_contacts += usize::from(!all.is_empty());
}
let ring: Vec<Coord2d> = (0..400)
.map(|k| {
let t = std::f64::consts::TAU * f64::from(k) / 400.0;
Coord2d::new(1000.0 * t.cos(), 1000.0 * t.sin())
})
.collect();
assert!(self_contacts_sweep(&ring, false).is_empty());
assert!(self_contacts_scan(&ring, false).is_empty());
assert!(with_contacts > 200);
}
}