use arithmetica::Sign;
use super::{Kind, PreparedPolygonal};
use crate::error::GeometryError;
use crate::exact::kernel::orient;
use crate::index::EdgeRef;
use crate::topology::label::Location;
use crate::types::{Coord2d, Envelope};
impl PreparedPolygonal {
pub fn locate_on_line(&self, y: f64, xs: &[f64]) -> Result<Vec<Location>, GeometryError> {
if !y.is_finite() {
return Err(GeometryError::NonFiniteCoordinate {
coord_index: 0,
axis: 1,
});
}
if let Some(i) = xs.iter().position(|x| !x.is_finite()) {
return Err(GeometryError::NonFiniteCoordinate {
coord_index: i,
axis: 0,
});
}
if xs.windows(2).all(|w| w[0] <= w[1]) {
return Ok(self.locate_sorted(y, xs));
}
let mut order: Vec<usize> = (0..xs.len()).collect();
order.sort_unstable_by(|&i, &j| xs[i].total_cmp(&xs[j]));
let sorted: Vec<f64> = order.iter().map(|&i| xs[i]).collect();
let located = self.locate_sorted(y, &sorted);
let mut out = vec![Location::Exterior; xs.len()];
for (k, &i) in order.iter().enumerate() {
out[i] = located[k];
}
Ok(out)
}
fn locate_sorted(&self, y: f64, xs: &[f64]) -> Vec<Location> {
let n = xs.len();
let parts = self.mask.polygons();
if n == 0 || parts.is_empty() {
return vec![Location::Exterior; n];
}
let mut base = Vec::with_capacity(parts.len() + 1);
base.push(0usize);
for p in parts {
base.push(base[base.len() - 1] + 1 + p.holes().len());
}
let mut boundary = vec![false; n];
let mut toggles: Vec<(usize, usize)> = Vec::new();
self.for_edges_on_row(y, |r, a, b| {
place_edge(a, b, y, xs, &mut boundary, |end| {
toggles.push((end, base[r.part] + r.ring));
});
});
toggles.sort_unstable_by_key(|t| core::cmp::Reverse(t.0));
let mut odd = vec![false; base[parts.len()]];
let mut ext_odd = vec![false; parts.len()];
let mut odd_holes = vec![0usize; parts.len()];
let mut inside_parts = 0usize;
let part_of = |ring: usize| base.partition_point(|&b| b <= ring) - 1;
let mut next = 0;
let mut out = vec![Location::Exterior; n];
for i in (0..n).rev() {
while next < toggles.len() && toggles[next].0 > i {
let ring = toggles[next].1;
next += 1;
let part = part_of(ring);
let was = ext_odd[part] && odd_holes[part] == 0;
odd[ring] = !odd[ring];
if ring == base[part] {
ext_odd[part] = odd[ring];
} else if odd[ring] {
odd_holes[part] += 1;
} else {
odd_holes[part] -= 1;
}
let now = ext_odd[part] && odd_holes[part] == 0;
if now && !was {
inside_parts += 1;
} else if was && !now {
inside_parts -= 1;
}
}
out[i] = if boundary[i] {
Location::Boundary
} else if inside_parts > 0 {
Location::Interior
} else {
Location::Exterior
};
}
out
}
fn for_edges_on_row(&self, y: f64, mut visit: impl FnMut(EdgeRef, Coord2d, Coord2d)) {
let Some(env) = self.envelope else {
return;
};
if y < env.min().y || y > env.max().y {
return;
}
match &self.kind {
Kind::Simple { edge_index, .. } => {
let row = Envelope::new(Coord2d::new(env.min().x, y), Coord2d::new(env.max().x, y));
let Ok(row) = row else {
return;
};
edge_index.candidates(&row, |r| {
let (a, b) = self.edge(r);
visit(r, a, b);
});
}
Kind::Small(_) | Kind::Delegating(_) => {
for (part, p) in self.mask.polygons().iter().enumerate() {
let rings = core::iter::once(p.exterior()).chain(p.holes().iter());
for (ring, rg) in rings.enumerate() {
for (edge, (a, b)) in rg.edges().enumerate() {
if a.y.min(b.y) <= y && a.y.max(b.y) >= y {
visit(EdgeRef { part, ring, edge }, a, b);
}
}
}
}
}
}
}
}
#[allow(clippy::float_cmp)]
fn place_edge(
a: Coord2d,
b: Coord2d,
y: f64,
xs: &[f64],
boundary: &mut [bool],
mut toggle: impl FnMut(usize),
) {
if a.y == b.y {
let (lo, hi) = if a.x <= b.x { (a.x, b.x) } else { (b.x, a.x) };
let from = xs.partition_point(|&x| x < lo);
let to = xs.partition_point(|&x| x <= hi);
for flag in &mut boundary[from..to] {
*flag = true;
}
return;
}
let left = if b.y > a.y {
Sign::Positive
} else {
Sign::Negative
};
let sign = |x: f64| orient(a, b, Coord2d::new(x, y));
let (lo, hi) = if a.x <= b.x { (a.x, b.x) } else { (b.x, a.x) };
let first = xs.partition_point(|&x| x < lo);
let last = first + xs[first..].partition_point(|&x| x <= hi);
let zero_from = first + xs[first..last].partition_point(|&x| sign(x) == left);
let zero_to = zero_from + xs[zero_from..last].partition_point(|&x| sign(x) == Sign::Zero);
for flag in &mut boundary[zero_from..zero_to] {
*flag = true;
}
if (a.y > y) != (b.y > y) {
toggle(zero_from);
}
}