use core::cmp::Ordering;
use crate::exact::{RingPlacement, place_ring};
use crate::types::{Coord2d, CoordSeq, LinearRing, Polygon};
use super::angular::ccw_cmp;
pub(in crate::ops) type Key = (u64, u64);
pub(in crate::ops) fn key(c: Coord2d) -> Key {
((c.x + 0.0).to_bits(), (c.y + 0.0).to_bits())
}
pub(super) fn edge_key(a: Coord2d, b: Coord2d) -> (Key, Key) {
let (ka, kb) = (key(a), key(b));
if ka <= kb { (ka, kb) } else { (kb, ka) }
}
pub(in crate::ops) fn seq_cmp(a: &[Coord2d], b: &[Coord2d]) -> Ordering {
for (x, y) in a.iter().zip(b) {
let c = coord_exact_cmp(*x, *y);
if c != Ordering::Equal {
return c;
}
}
a.len().cmp(&b.len())
}
pub(in crate::ops) fn coord_exact_cmp(a: Coord2d, b: Coord2d) -> Ordering {
a.x.partial_cmp(&b.x)
.unwrap_or(Ordering::Equal)
.then(a.y.partial_cmp(&b.y).unwrap_or(Ordering::Equal))
}
pub(super) struct HalfEdges<'a> {
coords: &'a [Coord2d],
from: Vec<usize>,
out_start: Vec<usize>,
out: Vec<usize>,
pos: Vec<usize>,
}
impl<'a> HalfEdges<'a> {
pub(super) fn new(coords: &'a [Coord2d], edges: &[(usize, usize)]) -> Self {
let mut from = Vec::with_capacity(2 * edges.len());
for &(a, b) in edges {
from.push(a);
from.push(b);
}
let mut out_start = vec![0_usize; coords.len() + 1];
for &v in &from {
out_start[v + 1] += 1;
}
for v in 0..coords.len() {
out_start[v + 1] += out_start[v];
}
let mut fill = out_start.clone();
let mut out = vec![0_usize; from.len()];
for (h, &v) in from.iter().enumerate() {
out[fill[v]] = h;
fill[v] += 1;
}
let to = |h: usize| from[h ^ 1];
for v in 0..coords.len() {
out[out_start[v]..out_start[v + 1]]
.sort_by(|&h, &k| ccw_cmp(coords[v], coords[to(h)], coords[to(k)]));
}
let mut pos = vec![0; from.len()];
for v in 0..coords.len() {
for (i, &h) in out[out_start[v]..out_start[v + 1]].iter().enumerate() {
pos[h] = i;
}
}
Self {
coords,
from,
out_start,
out,
pos,
}
}
pub(super) fn len(&self) -> usize {
self.from.len()
}
pub(super) fn coord(&self, v: usize) -> Coord2d {
self.coords[v]
}
pub(super) fn origin(&self, h: usize) -> usize {
self.from[h]
}
pub(super) fn vertex_count(&self) -> usize {
self.coords.len()
}
fn next(&self, h: usize) -> usize {
let twin = h ^ 1;
let v = self.from[twin];
let list = &self.out[self.out_start[v]..self.out_start[v + 1]];
list[(self.pos[twin] + list.len() - 1) % list.len()]
}
pub(super) fn for_each_walk(
&self,
starts: impl IntoIterator<Item = usize>,
mut f: impl FnMut(&[usize]),
) {
let mut seen = vec![false; self.len()];
let mut walk = Vec::new();
for s in starts {
if seen[s] {
continue;
}
walk.clear();
let mut h = s;
while !seen[h] {
seen[h] = true;
walk.push(h);
h = self.next(h);
}
f(&walk);
}
}
}
pub(super) struct LoopSplitter {
at: Vec<usize>,
stack: Vec<usize>,
}
impl LoopSplitter {
const NONE: usize = usize::MAX;
pub(super) fn new(vertices: usize) -> Self {
Self {
at: vec![Self::NONE; vertices],
stack: Vec::new(),
}
}
pub(super) fn split(
&mut self,
walk: impl IntoIterator<Item = usize>,
mut f: impl FnMut(&[usize]),
) {
for v in walk {
let p = self.at[v];
if p != Self::NONE {
for &u in &self.stack[p..] {
self.at[u] = Self::NONE;
}
f(&self.stack[p..]);
self.stack.truncate(p);
}
self.at[v] = self.stack.len();
self.stack.push(v);
}
for &u in &self.stack {
self.at[u] = Self::NONE;
}
if !self.stack.is_empty() {
f(&self.stack);
}
self.stack.clear();
}
}
pub(super) fn ring_of(g: &HalfEdges<'_>, lp: &[usize]) -> Option<LinearRing> {
let start = (0..lp.len())
.min_by(|&i, &j| coord_exact_cmp(g.coord(lp[i]), g.coord(lp[j])).then(i.cmp(&j)))
.unwrap_or(0);
let coords: Vec<Coord2d> = lp[start..]
.iter()
.chain(&lp[..start])
.map(|&v| g.coord(v))
.collect();
LinearRing::new(CoordSeq::new(coords)).ok()
}
pub(super) fn runs_counterclockwise(ring: &LinearRing) -> bool {
let c = ring.coords().as_slice();
crate::exact::kernel::orient(c[c.len() - 1], c[0], c[1]) == arithmetica::Sign::Positive
}
pub(super) fn assemble(
shells: Vec<(LinearRing, f64)>,
holes: Vec<LinearRing>,
) -> (Vec<Result<Polygon, LinearRing>>, Vec<LinearRing>) {
let rings: Vec<&LinearRing> = shells.iter().map(|(r, _)| r).collect();
let mut owned: Vec<Vec<LinearRing>> = vec![Vec::new(); shells.len()];
let mut orphans = Vec::new();
for hole in holes {
match innermost(&rings, &hole) {
Some(i) => owned[i].push(hole),
None => orphans.push(hole),
}
}
let polys = shells
.into_iter()
.zip(owned)
.map(|((shell, area), mut hs)| {
if hs.is_empty() {
return Polygon::from_exterior_with_area(shell, area);
}
hs.sort_by(|a, b| seq_cmp(a.coords().as_slice(), b.coords().as_slice()));
Polygon::new_or_exterior(shell, hs)
})
.collect();
(polys, orphans)
}
fn innermost(shells: &[&LinearRing], hole: &LinearRing) -> Option<usize> {
let he = hole.envelope().ok()?;
let candidates: Vec<usize> = (0..shells.len())
.filter(|&i| {
shells[i].envelope().is_ok_and(|e| e.contains_envelope(&he))
&& place_ring(hole, shells[i]) == RingPlacement::Inside
})
.collect();
candidates.iter().copied().find(|&c| {
candidates
.iter()
.all(|&d| d == c || place_ring(shells[d], shells[c]) != RingPlacement::Inside)
})
}