use std::collections::BTreeSet;
use fontoxide_misc::array_tools::Point;
pub use crate::var::{iup_contour, iup_delta, iup_segment};
use crate::{Error, Result};
const MAX_LOOKBACK: i64 = 8;
fn at(points: &[Point], i: i64) -> Point {
points[if i < 0 { points.len() as i64 + i } else { i } as usize]
}
#[derive(Clone, Copy)]
struct Rounded<'a> {
deltas: &'a [Point],
coords: &'a [Point],
}
fn round_points(points: &[Point]) -> Option<Vec<Point>> {
points
.iter()
.any(|&(x, y)| x != x.floor() || y != y.floor())
.then(|| {
points
.iter()
.map(|&(x, y)| ((x + 0.5).floor(), (y + 0.5).floor()))
.collect()
})
}
fn interpolates(deltas: &[Point], coords: &[Point], i: i64, j: i64, tolerance: f64) -> bool {
let between = (i + 1) as usize..j as usize;
let interp = iup_segment(
&coords[between.clone()],
at(coords, i),
at(deltas, i),
at(coords, j),
at(deltas, j),
);
deltas[between].iter().zip(&interp).all(|(d, p)| {
(d.0 - p.0).hypot(d.1 - p.1) <= tolerance
})
}
fn can_iup_in_between(
deltas: &[Point],
coords: &[Point],
i: i64,
j: i64,
tolerance: f64,
rounded: Option<Rounded<'_>>,
) -> bool {
if !interpolates(deltas, coords, i, j, tolerance) {
return false;
}
match rounded {
None => true,
Some(r) => interpolates(r.deltas, r.coords, i, j, tolerance),
}
}
fn bound_forced_set(deltas: &[Point], coords: &[Point], tolerance: f64) -> BTreeSet<usize> {
let n = deltas.len();
let mut forced = BTreeSet::new();
let get = |p: Point, j: usize| if j == 0 { p.0 } else { p.1 };
for i in (0..n).rev() {
let last = (i + n - 1) % n;
let next = (i + 1) % n;
for j in 0..2 {
let cj = get(coords[i], j);
let dj = get(deltas[i], j);
let (lcj, ldj) = (get(coords[last], j), get(deltas[last], j));
let (ncj, ndj) = (get(coords[next], j), get(deltas[next], j));
let (c1, c2, d1, d2) = if lcj <= ncj {
(lcj, ncj, ldj, ndj)
} else {
(ncj, lcj, ndj, ldj)
};
let mut force = false;
if c1 == c2 {
if (d1 - d2).abs() > tolerance && dj.abs() > tolerance {
force = true;
}
} else if c1 <= cj && cj <= c2 {
if !(d1.min(d2) - tolerance <= dj && dj <= d1.max(d2) + tolerance) {
force = true;
}
} else if d1 != d2 {
if cj < c1 {
if dj.abs() > tolerance
&& (dj - d1).abs() > tolerance
&& ((dj - tolerance < d1) != (d1 < d2))
{
force = true;
}
} else if dj.abs() > tolerance
&& (dj - d2).abs() > tolerance
&& ((d2 < dj + tolerance) != (d1 < d2))
{
force = true;
}
}
if force {
forced.insert(i);
break;
}
}
}
forced
}
struct Dp {
chain: Vec<i64>,
costs: Vec<i64>,
}
impl Dp {
fn chain(&self, i: i64) -> i64 {
self.chain[(i + 1) as usize]
}
fn cost(&self, i: i64) -> i64 {
self.costs[(i + 1) as usize]
}
}
fn optimize_dp(
deltas: &[Point],
coords: &[Point],
forced: &BTreeSet<usize>,
tolerance: f64,
lookback: Option<usize>,
rounded: Option<Rounded<'_>>,
) -> Dp {
let n = deltas.len() as i64;
let lookback = (lookback.map_or(n, |l| l as i64)).min(MAX_LOOKBACK);
let is_forced = |i: i64| i >= 0 && forced.contains(&(i as usize));
let mut dp = Dp {
chain: vec![i64::MIN],
costs: vec![0],
};
for i in 0..n {
let mut best_cost = dp.cost(i - 1) + 1;
dp.costs.push(best_cost);
dp.chain.push(i - 1);
if is_forced(i - 1) {
continue;
}
let stop = (i - lookback).max(-2);
let mut j = i - 2;
while j > stop {
let cost = dp.cost(j) + 1;
if cost < best_cost && can_iup_in_between(deltas, coords, j, i, tolerance, rounded) {
best_cost = cost;
dp.costs[(i + 1) as usize] = cost;
dp.chain[(i + 1) as usize] = j;
}
if is_forced(j) {
break;
}
j -= 1;
}
}
dp
}
#[doc(hidden)]
pub fn iup_contour_bound_forced_set(
deltas: &[Point],
coords: &[Point],
tolerance: f64,
) -> BTreeSet<usize> {
bound_forced_set(deltas, coords, tolerance)
}
#[doc(hidden)]
pub fn iup_contour_optimize_dp(
deltas: &[Point],
coords: &[Point],
forced: &BTreeSet<usize>,
tolerance: f64,
) -> (Vec<i64>, Vec<i64>) {
let dp = optimize_dp(deltas, coords, forced, tolerance, None, None);
(dp.chain, dp.costs)
}
fn rot_list(l: &[Point], k: usize) -> Vec<Point> {
let n = l.len();
let k = k % n;
let mut out = l[n - k..].to_vec();
out.extend_from_slice(&l[..n - k]);
out
}
pub fn iup_contour_optimize(
deltas: &[Point],
coords: &[Point],
tolerance: f64,
) -> Result<Vec<bool>> {
let n = deltas.len();
let negligible = |p: &Point| {
(*p == (0.0, 0.0) && tolerance >= 0.0)
|| (p.0.hypot(p.1) <= tolerance
&& (tolerance < 0.5 || (p.0 + 0.5).floor().hypot((p.1 + 0.5).floor()) <= tolerance))
};
if deltas.iter().all(negligible) {
return Ok(vec![false; n]);
}
if n == 1 {
return Ok(vec![true]);
}
if deltas.iter().all(|d| *d == deltas[0]) {
let mut keep = vec![false; n];
keep[0] = true;
return Ok(keep);
}
let (rounded_deltas, rounded_coords) = match (round_points(deltas), round_points(coords)) {
(None, None) => (None, None),
(d, c) => (
Some(d.unwrap_or_else(|| deltas.to_vec())),
Some(c.unwrap_or_else(|| coords.to_vec())),
),
};
let mut forced = bound_forced_set(deltas, coords, tolerance);
if let (Some(rd), Some(rc)) = (&rounded_deltas, &rounded_coords) {
forced.extend(bound_forced_set(rd, rc, tolerance));
}
let not_subset = || Error::Assertion("forced <= solution".into());
if let Some(&last) = forced.last() {
let k = n - 1 - last;
let rotated_deltas = rot_list(deltas, k);
let rotated_coords = rot_list(coords, k);
let rotated_forced: BTreeSet<usize> = forced.iter().map(|v| (v + k) % n).collect();
let rotated_rounded = rounded_deltas
.as_deref()
.zip(rounded_coords.as_deref())
.map(|(d, c)| (rot_list(d, k), rot_list(c, k)));
let dp = optimize_dp(
&rotated_deltas,
&rotated_coords,
&rotated_forced,
tolerance,
None,
rotated_rounded.as_ref().map(|(d, c)| Rounded {
deltas: d,
coords: c,
}),
);
let mut solution = BTreeSet::new();
let mut i = n as i64 - 1;
while i != -1 {
solution.insert(i as usize);
i = dp.chain(i);
}
if !rotated_forced.is_subset(&solution) {
return Err(not_subset());
}
let mut keep = vec![false; n];
for i in solution {
keep[(i + n - k) % n] = true;
}
Ok(keep)
} else {
let doubled_deltas = [deltas, deltas].concat();
let doubled_coords = [coords, coords].concat();
let doubled_rounded = rounded_deltas
.as_deref()
.zip(rounded_coords.as_deref())
.map(|(d, c)| ([d, d].concat(), [c, c].concat()));
let dp = optimize_dp(
&doubled_deltas,
&doubled_coords,
&forced,
tolerance,
Some(n),
doubled_rounded.as_ref().map(|(d, c)| Rounded {
deltas: d,
coords: c,
}),
);
let n = n as i64;
let mut best: Option<BTreeSet<usize>> = None;
let mut best_cost = n + 1;
for start in n - 1..2 * n - 1 {
let mut solution = BTreeSet::new();
let mut i = start;
while i > start - n {
solution.insert((i % n) as usize);
i = dp.chain(i);
}
if i == start - n {
let cost = dp.cost(start) - dp.cost(start - n);
if cost <= best_cost {
best = Some(solution);
best_cost = cost;
}
}
}
let best = best.ok_or_else(not_subset)?;
Ok((0..n as usize).map(|i| best.contains(&i)).collect())
}
}
pub fn iup_delta_optimize(
deltas: &[Point],
coords: &[Point],
ends: &[usize],
tolerance: f64,
) -> Result<Vec<bool>> {
let expected = ends.last().map_or(0, |e| e + 1) + 4;
if !ends.is_sorted() || coords.len() != expected || deltas.len() != coords.len() {
return Err(Error::Assertion(
"sorted(ends) == ends and len(coords) == (ends[-1] + 1 if ends else 0) + 4".into(),
));
}
let n = coords.len();
let mut out = Vec::with_capacity(n);
let mut start = 0;
for end in ends.iter().copied().chain([n - 4, n - 3, n - 2, n - 1]) {
out.extend(iup_contour_optimize(
&deltas[start..=end],
&coords[start..=end],
tolerance,
)?);
start = end + 1;
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn optimize_keeps_what_interpolation_cannot_give() -> Result<()> {
let coords = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
assert_eq!(
iup_contour_optimize(&[(5.0, 5.0); 4], &coords, 0.5)?,
[true, false, false, false]
);
assert_eq!(
iup_contour_optimize(&[(0.1, 0.1); 4], &coords, 0.5)?,
[false; 4]
);
assert_eq!(
iup_contour_optimize(&[(1.0, 2.0)], &[(0.0, 0.0)], 0.5)?,
[true]
);
let coords = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (50.0, 50.0)];
let deltas = [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (20.0, 30.0)];
assert_eq!(
iup_contour_optimize(&deltas, &coords, 0.5)?,
[false, true, true, true]
);
let coords = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let deltas = [(1.0, 0.0), (2.0, 0.0), (3.0, 5.0), (0.0, 9.0)];
assert_eq!(iup_contour_optimize(&deltas, &coords, 0.5)?, [true; 4]);
let coords = [
(0.0, 0.0),
(10.0, 0.0),
(20.0, 0.0),
(30.0, 0.0),
(40.0, 5.0),
(30.0, 10.0),
(20.0, 10.0),
(10.0, 10.0),
(0.0, 10.0),
];
let deltas = [
(0.0, 0.0),
(1.0, 0.0),
(2.0, 0.0),
(3.0, 0.0),
(9.0, 9.0),
(3.0, 1.0),
(2.0, 1.0),
(1.0, 1.0),
(0.0, 1.0),
];
assert_eq!(
iup_contour_optimize(&deltas, &coords, 0.5)?,
[true, false, false, true, true, true, false, false, false]
);
Ok(())
}
}