mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-25 03:53:23 +01:00
feat(geom): midpoint snapping, marquee cutter and shared-edge editing (M1)
planar: anchors within SNAP meet at their midpoint and a point landing on a line goes onto it (the line stays), as issue #42 section 4 describes; merge_cut cuts along a closed outline that never comes out and marks each piece inside or outside it. raw: bend an edge and make every copy of it in other paths follow, split a path where another shape ends on it, nearest point on a cubic.
This commit is contained in:
1 parent
978cc3aa9f
commit
ff4528df62
4 files changed
+426
-20
No files matched your search
@@ -10,6 +10,7 @@ pub mod clip;
|
||||
pub mod edit;
|
||||
pub mod morph;
|
||||
pub mod planar;
|
||||
pub mod raw;
|
||||
mod fit;
|
||||
mod path;
|
||||
pub mod svg;
|
||||
|
||||
+107
-20
@@ -2,8 +2,9 @@
|
||||
//!
|
||||
//! The shapes, bottom to top, are cut into a planar map:
|
||||
//! - every segment is cut where it meets another (exact sub-curves by de Casteljau);
|
||||
//! - points closer than [`SNAP`] become one vertex, and pieces that run along each other become
|
||||
//! one edge;
|
||||
//! - points closer than [`SNAP`] become one vertex (anchors meet at their midpoint; a point that
|
||||
//! lands on a line goes onto it, and the line stays), and pieces that run along each other
|
||||
//! become one edge;
|
||||
//! - each face of the map takes the fill of the topmost shape covering it (winding at a point
|
||||
//! inside the face).
|
||||
//!
|
||||
@@ -52,6 +53,8 @@ pub struct Piece {
|
||||
pub style: u32,
|
||||
pub path: Path,
|
||||
pub item: usize,
|
||||
/// Inside the cutter ([`merge_cut`]); always false from [`merge`].
|
||||
pub inside: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -62,7 +65,28 @@ pub struct Merged {
|
||||
|
||||
/// Merges `items` (bottom to top). `None` when there is too much to merge at once.
|
||||
pub fn merge(items: &[Item]) -> Option<Merged> {
|
||||
let segs = collect(items)?;
|
||||
merge_with(items, None)
|
||||
}
|
||||
|
||||
/// [`merge`], also cutting everything along `cutter` (a closed outline that only cuts, such as
|
||||
/// the Selection tool's marquee, ADR 0041): fills are split at its edges and stroke runs end
|
||||
/// there, nothing of the cutter itself comes out, and each piece says whether it lies inside it.
|
||||
pub fn merge_cut(items: &[Item], cutter: &Path) -> Option<Merged> {
|
||||
merge_with(items, Some(cutter))
|
||||
}
|
||||
|
||||
/// The item number the cutter's segments carry.
|
||||
const CUTTER: usize = usize::MAX;
|
||||
|
||||
fn merge_with(items: &[Item], cutter: Option<&Path>) -> Option<Merged> {
|
||||
let mut segs = collect(items)?;
|
||||
if let Some(path) = cutter {
|
||||
let edge = Item { path, fill: None, fill_rule: FillRule::EvenOdd, stroke: Some(0) };
|
||||
segs.extend(collect(&[edge])?.into_iter().map(|s| Seg { item: CUTTER, ..s }));
|
||||
if segs.len() > MAX_SEGMENTS {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let splits = cut(&segs)?;
|
||||
let map = Map::build(&segs, &splits);
|
||||
Some(map.output(items, &segs))
|
||||
@@ -448,12 +472,44 @@ struct Map {
|
||||
slot: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Greedy clustering: a point joins the first vertex within [`TOL`], so none moves farther.
|
||||
/// Greedy clustering: a point joins the nearest vertex whose first point is within [`TOL`].
|
||||
struct Verts {
|
||||
pts: Vec<P>,
|
||||
grid: HashMap<(i64, i64), Vec<usize>>,
|
||||
}
|
||||
|
||||
/// What fell into one vertex, to decide where it goes (issue #42: anchor points closer than
|
||||
/// [`SNAP`] meet at their midpoint; a point that lands on a line goes onto it, and the line stays).
|
||||
#[derive(Default)]
|
||||
struct Cluster {
|
||||
/// A point inside a segment, away from its ends (where an end lies on a line, or lines
|
||||
/// cross): the vertex stays there.
|
||||
on_line: Option<P>,
|
||||
/// Segment ends, each position once.
|
||||
ends: Vec<P>,
|
||||
}
|
||||
|
||||
impl Cluster {
|
||||
fn add(&mut self, p: P, end: bool, on_line: bool) {
|
||||
if on_line {
|
||||
self.on_line.get_or_insert(p);
|
||||
} else if end && !self.ends.iter().any(|q| q.dist(p) < 1e-9) && self.ends.len() < 64 {
|
||||
self.ends.push(p);
|
||||
}
|
||||
}
|
||||
fn place(&self, seed: P) -> P {
|
||||
if let Some(p) = self.on_line {
|
||||
return p;
|
||||
}
|
||||
if self.ends.is_empty() {
|
||||
return seed;
|
||||
}
|
||||
let n = self.ends.len() as f64;
|
||||
let sum = self.ends.iter().fold(P::default(), |s, p| s.add(*p));
|
||||
sum.mul(1.0 / n)
|
||||
}
|
||||
}
|
||||
|
||||
impl Verts {
|
||||
fn cell(p: P) -> (i64, i64) {
|
||||
((p.x / TOL).floor() as i64, (p.y / TOL).floor() as i64)
|
||||
@@ -491,13 +547,35 @@ fn pinned(c: &Cubic, line: bool, a: P, b: P) -> Cubic {
|
||||
impl Map {
|
||||
fn build(segs: &[Seg], splits: &[Vec<f64>]) -> Map {
|
||||
let mut vs = Verts { pts: Vec::new(), grid: HashMap::new() };
|
||||
// Every cut point into a vertex first, then each vertex placed (see `Cluster`), so the
|
||||
// pieces are pinned to where their vertices end up.
|
||||
let mut clusters: Vec<Cluster> = Vec::new();
|
||||
let mut ids: Vec<Vec<usize>> = Vec::with_capacity(segs.len());
|
||||
for (s, ts) in segs.iter().zip(splits) {
|
||||
let mut row = Vec::with_capacity(ts.len());
|
||||
for &t in ts {
|
||||
let end = t <= 0.0 || t >= 1.0;
|
||||
let p = if t <= 0.0 { s.c[0] } else if t >= 1.0 { s.c[3] } else { eval(&s.c, t) };
|
||||
let v = vs.at(p);
|
||||
if clusters.len() <= v {
|
||||
clusters.resize_with(v + 1, Cluster::default);
|
||||
}
|
||||
let on_line = !end && p.dist(s.c[0]) >= TOL && p.dist(s.c[3]) >= TOL;
|
||||
clusters[v].add(p, end, on_line);
|
||||
row.push(v);
|
||||
}
|
||||
ids.push(row);
|
||||
}
|
||||
for (p, c) in vs.pts.iter_mut().zip(&clusters) {
|
||||
*p = c.place(*p);
|
||||
}
|
||||
let mut edges: Vec<Edge> = Vec::new();
|
||||
let mut by_ends: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
|
||||
for (si, (s, ts)) in segs.iter().zip(splits).enumerate() {
|
||||
for w in ts.windows(2) {
|
||||
for (si, ((s, ts), row)) in segs.iter().zip(splits).zip(&ids).enumerate() {
|
||||
for (w, v) in ts.windows(2).zip(row.windows(2)) {
|
||||
let (t0, t1) = (w[0], w[1]);
|
||||
let c = sub(&s.c, t0, t1);
|
||||
let (a, b) = (vs.at(c[0]), vs.at(c[3]));
|
||||
let (a, b) = (v[0], v[1]);
|
||||
if a == b {
|
||||
continue; // shorter than SNAP (longer loops were halved when collected)
|
||||
}
|
||||
@@ -655,16 +733,19 @@ impl Map {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(e, edge)| {
|
||||
let z = edge.strokes.iter().copied().max()?;
|
||||
let z = edge.strokes.iter().copied().filter(|&i| i < items.len()).max()?;
|
||||
let (l, r) = (face(2 * e), face(2 * e + 1));
|
||||
let hidden = l.zip(r).is_some_and(|(l, r)| covers[l].iter().any(|&i| i > z && covers[r].contains(&i)));
|
||||
(!hidden).then_some(z)
|
||||
})
|
||||
.collect();
|
||||
// The cutter's edges divide like a stroke that never shows.
|
||||
let cut_edge: Vec<bool> = self.edges.iter().map(|e| e.strokes.contains(&CUTTER)).collect();
|
||||
let cutter = Region::new(segs, CUTTER, cut_edge.contains(&true));
|
||||
// Faces of one fill with no stroke between them are one region.
|
||||
let mut group = Dsu::new(samples.len());
|
||||
for (e, stroke) in stroke_of.iter().enumerate() {
|
||||
if let (None, Some(l), Some(r)) = (stroke, face(2 * e), face(2 * e + 1))
|
||||
if let (None, false, Some(l), Some(r)) = (stroke, cut_edge[e], face(2 * e), face(2 * e + 1))
|
||||
&& l != r
|
||||
&& fill_of(l).map(|f| f.0) == fill_of(r).map(|f| f.0)
|
||||
&& fill_of(l).is_some()
|
||||
@@ -674,11 +755,13 @@ impl Map {
|
||||
}
|
||||
let roots = group.roots();
|
||||
let gid = |f: Option<usize>| f.filter(|&f| fill_of(f).is_some()).and_then(|f| roots.get(f).copied());
|
||||
// Each region's style and topmost item.
|
||||
let mut top: HashMap<usize, (u32, usize)> = HashMap::new();
|
||||
for f in 0..samples.len() {
|
||||
// Each region's style and topmost item, and whether it is inside the cutter (the
|
||||
// cutter's edges bound every region, so one sample tells).
|
||||
let mut top: HashMap<usize, (u32, usize, bool)> = HashMap::new();
|
||||
for (f, sample) in samples.iter().enumerate() {
|
||||
if let (Some(g), Some((style, item))) = (gid(Some(f)), fill_of(f)) {
|
||||
let t = top.entry(g).or_insert((style, item));
|
||||
let inside = sample.is_some_and(|p| cutter.covers(p, FillRule::EvenOdd));
|
||||
let t = top.entry(g).or_insert((style, item, inside));
|
||||
t.1 = t.1.max(item);
|
||||
}
|
||||
}
|
||||
@@ -708,25 +791,27 @@ impl Map {
|
||||
match piece_of.get(&g) {
|
||||
Some(&i) => out.fills[i].path.cmds.extend(path.cmds),
|
||||
None => {
|
||||
let (style, item) = top.get(&g).copied().unwrap_or((0, 0));
|
||||
let (style, item, inside) = top.get(&g).copied().unwrap_or((0, 0, false));
|
||||
piece_of.insert(g, out.fills.len());
|
||||
out.fills.push(Piece { style, path, item });
|
||||
out.fills.push(Piece { style, path, item, inside });
|
||||
}
|
||||
}
|
||||
}
|
||||
self.strokes(items, &stroke_of, segs, &mut out);
|
||||
self.strokes(items, &stroke_of, &cut_edge, &cutter, segs, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Visible strokes, chained through vertices where exactly two of one style meet smoothly.
|
||||
fn strokes(&self, items: &[Item], stroke_of: &[Option<usize>], segs: &[Seg], out: &mut Merged) {
|
||||
/// Visible strokes, chained through vertices where exactly two of one style meet smoothly
|
||||
/// (and never across the cutter).
|
||||
fn strokes(&self, items: &[Item], stroke_of: &[Option<usize>], cut_edge: &[bool], cutter: &Region, segs: &[Seg], out: &mut Merged) {
|
||||
let style = |e: usize| stroke_of[e].and_then(|z| items[z].stroke);
|
||||
let shown: Vec<Vec<Half>> = self.around.iter().map(|l| l.iter().copied().filter(|&h| style(h / 2).is_some()).collect()).collect();
|
||||
let on_cut: Vec<bool> = self.around.iter().map(|l| l.iter().any(|&h| cut_edge[h / 2])).collect();
|
||||
// The half that carries on from `h` at its end, if the run goes on.
|
||||
let carry = |h: Half| -> Option<Half> {
|
||||
let v = self.dest(h);
|
||||
let list = &shown[v];
|
||||
if list.len() != 2 {
|
||||
if list.len() != 2 || on_cut[v] {
|
||||
return None;
|
||||
}
|
||||
let n = list.iter().copied().find(|&o| o != (h ^ 1))?;
|
||||
@@ -763,7 +848,9 @@ impl Map {
|
||||
h = n;
|
||||
}
|
||||
let item = halves.iter().filter_map(|&h| stroke_of[h / 2]).max().unwrap_or(0);
|
||||
out.strokes.push(Piece { style: st, path: self.emit(&halves, closed, segs), item });
|
||||
// A run along the cutter's edge counts as inside it.
|
||||
let inside = halves.iter().any(|&h| cut_edge[h / 2]) || halves.get(halves.len() / 2).is_some_and(|&h| cutter.covers(eval(&self.curve(h), 0.5), FillRule::EvenOdd));
|
||||
out.strokes.push(Piece { style: st, path: self.emit(&halves, closed, segs), item, inside });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -256,3 +256,77 @@ fn a_search_that_runs_out_of_steps_declines_the_merge() {
|
||||
let (a, b) = (arc(100.0), arc(100.3));
|
||||
assert_eq!(merge(&[stroked(&a, None, 1), stroked(&b, None, 1)]).map(|m| m.strokes.len()), Some(2));
|
||||
}
|
||||
|
||||
// ----- snapping within SNAP and cutting (ADR 0041) -----------------------------------------------
|
||||
|
||||
fn ends(p: &Path) -> Vec<Vec2> {
|
||||
p.anchors().into_iter().map(|(_, v)| v).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchors_within_snap_meet_at_their_midpoint() {
|
||||
// Issue #42 §4: two ends 0.1 apart (a keyboard nudge's reach) become one point halfway.
|
||||
let a = Path::line(Vec2::new(0.0, 0.0), Vec2::new(50.0, 0.0));
|
||||
let b = Path::line(Vec2::new(50.1, 0.1), Vec2::new(50.1, 50.0));
|
||||
let m = run(&[stroked(&a, None, 1), stroked(&b, None, 1)]);
|
||||
assert_eq!(m.strokes.len(), 2, "{m:?}");
|
||||
let mid = Vec2::new(50.05, 0.05);
|
||||
for s in &m.strokes {
|
||||
assert!(ends(&s.path).iter().any(|p| p.distance(mid) < 1e-4), "{:?}", s.path);
|
||||
}
|
||||
// A fill corner and a line end too: the corner moves halfway, so the outline stays closed.
|
||||
let r = rect(0.0, 0.0, 10.0, 10.0);
|
||||
let l = Path::line(Vec2::new(10.12, 10.0), Vec2::new(30.0, 30.0));
|
||||
let m = run(&[fill(&r, 1), stroked(&l, None, 2)]);
|
||||
let corner = Vec2::new(10.06, 10.0);
|
||||
assert!(m.fills.iter().any(|f| ends(&f.path).iter().any(|p| p.distance(corner) < 1e-4)), "{m:?}");
|
||||
assert!(m.strokes.iter().any(|s| ends(&s.path).iter().any(|p| p.distance(corner) < 1e-4)), "{m:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_end_near_a_line_goes_onto_it_and_the_line_stays_straight() {
|
||||
// Issue #42 §4: "an anchor point snaps to a line without modifying it".
|
||||
let a = Path::line(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0));
|
||||
let b = Path::line(Vec2::new(40.0, 0.15), Vec2::new(40.0, 60.0));
|
||||
let m = run(&[stroked(&a, None, 1), stroked(&b, None, 1)]);
|
||||
// The long line is cut where the other meets it (a T), and every piece stays on y = 0.
|
||||
let flat: Vec<&Piece> = m.strokes.iter().filter(|s| ends(&s.path).iter().all(|p| p.y.abs() < 1e-4)).collect();
|
||||
assert_eq!(flat.len(), 2, "{m:?}");
|
||||
assert!(m.strokes.iter().any(|s| ends(&s.path).iter().any(|p| p.distance(Vec2::new(40.0, 0.0)) < 1e-4) && ends(&s.path).iter().any(|p| p.y > 59.0)), "the end moved onto the line: {m:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cutter_splits_fills_and_strokes_and_the_parts_add_up() {
|
||||
let r = rect(0.0, 0.0, 100.0, 80.0);
|
||||
let marquee = rect(60.0, -10.0, 100.0, 50.0);
|
||||
let m = merge_cut(&[stroked(&r, Some(1), 2)], &marquee).unwrap_or_default();
|
||||
// The fill in two: 40 × 40 inside (the marquee is x 60–160, y −10–40), the rest outside,
|
||||
// adding up to the whole.
|
||||
let inside: f32 = m.fills.iter().filter(|p| p.inside).map(|p| area(&p.path)).sum();
|
||||
let outside: f32 = m.fills.iter().filter(|p| !p.inside).map(|p| area(&p.path)).sum();
|
||||
assert!(near(inside, 40.0 * 40.0, 0.5), "{inside}");
|
||||
assert!(near(inside + outside, 8000.0, 0.5), "{}", inside + outside);
|
||||
assert!(m.fills.iter().all(|p| p.style == 1));
|
||||
// Nothing of the marquee comes out: only the rectangle's own sides, cut where it crosses
|
||||
// them (the top and the right side are cut there).
|
||||
let len = |p: &Path| p.flatten(&crate::Affine::IDENTITY, 0.01).iter().map(|pl| pl.points.windows(2).map(|w| w[0].distance(w[1])).sum::<f32>()).sum::<f32>();
|
||||
let total: f32 = m.strokes.iter().map(|s| len(&s.path)).sum();
|
||||
assert!(near(total, 360.0, 0.05), "{total}");
|
||||
let inner: f32 = m.strokes.iter().filter(|s| s.inside).map(|s| len(&s.path)).sum();
|
||||
assert!(near(inner, 40.0 + 40.0, 0.05), "the top's right 40 and the right side's upper 40: {inner}");
|
||||
assert!(m.strokes.iter().all(|s| s.style == 2));
|
||||
// Without a cutter nothing is inside.
|
||||
assert!(run(&[stroked(&r, Some(1), 2)]).fills.iter().all(|p| !p.inside));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cutter_over_a_curve_cuts_exact_pieces() {
|
||||
let c = Path::ellipse(0.0, 0.0, 50.0, 50.0);
|
||||
let marquee = rect(-100.0, -100.0, 100.0, 100.0);
|
||||
let m = merge_cut(&[fill(&c, 1)], &marquee).unwrap_or_default();
|
||||
let inside: f32 = m.fills.iter().filter(|p| p.inside).map(|p| area(&p.path)).sum();
|
||||
let all: f32 = m.fills.iter().map(|p| area(&p.path)).sum();
|
||||
// A quarter of the disc, to within the ellipse's Bézier approximation.
|
||||
assert!(near(inside * 4.0, all, 1.0), "{inside} of {all}");
|
||||
assert_eq!(m.fills.len(), 2);
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
//! Editing raw shapes that share edges and points (ADR 0041). A layer's merged drawing is one
|
||||
//! element per fill region and per stroke run (ADR 0031), so a corner or an edge they share is
|
||||
//! stored once in each of them. Bending an edge or moving a point with the Selection tool has to
|
||||
//! change every copy the same way, so the drawing stays joined. These are the pure parts: finding
|
||||
//! the copies of an edge in a path and replacing them, making sure a path has an anchor where
|
||||
//! another shape ends, and the nearest point on a curve (for snapping).
|
||||
|
||||
use crate::walk::cubic_point;
|
||||
use crate::{Affine, Path, PathCmd, Vec2};
|
||||
|
||||
/// A cubic Bézier segment: start, two control points, end.
|
||||
pub type Cubic = [Vec2; 4];
|
||||
|
||||
/// Most commands one pass looks at (keeps an edit's cost bounded).
|
||||
const MAX_CMDS: usize = 100_000;
|
||||
|
||||
/// Segment `cmd` of `path` as a cubic from where it starts (lines and quadratics raised exactly).
|
||||
/// `None` for anything that is not a segment.
|
||||
pub fn segment_cubic(path: &Path, cmd: usize) -> Option<Cubic> {
|
||||
let s = path.segment_start(cmd)?;
|
||||
Some(match *path.cmds.get(cmd)? {
|
||||
PathCmd::LineTo(p) => [s, s.lerp(p, 1.0 / 3.0), s.lerp(p, 2.0 / 3.0), p],
|
||||
PathCmd::QuadTo(c, p) => [s, s.lerp(c, 2.0 / 3.0), p.lerp(c, 2.0 / 3.0), p],
|
||||
PathCmd::CubicTo(a, b, p) => [s, a, b, p],
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `c` mapped by `m` (an affine map takes control points to control points exactly).
|
||||
pub fn transform(c: &Cubic, m: &Affine) -> Cubic {
|
||||
c.map(|p| m.apply(p))
|
||||
}
|
||||
|
||||
/// `c` with its point at `t` moved by `d` and its ends kept: the smallest moves of the two
|
||||
/// control points that carry that point exactly, as [`Path::bend_segment`] does.
|
||||
pub fn bend(c: &Cubic, t: f32, d: Vec2) -> Option<Cubic> {
|
||||
let mut p = Path::new();
|
||||
p.move_to(c[0]).cubic_to(c[1], c[2], c[3]);
|
||||
if !p.bend_segment(1, t, d) {
|
||||
return None;
|
||||
}
|
||||
segment_cubic(&p, 1).filter(|b| b.iter().all(|q| q.is_finite()))
|
||||
}
|
||||
|
||||
fn split(c: &Cubic, t: f32) -> (Cubic, Cubic) {
|
||||
let (a, b, d) = (c[0].lerp(c[1], t), c[1].lerp(c[2], t), c[2].lerp(c[3], t));
|
||||
let (e, f) = (a.lerp(b, t), b.lerp(d, t));
|
||||
let m = e.lerp(f, t);
|
||||
([c[0], a, e, m], [m, f, d, c[3]])
|
||||
}
|
||||
|
||||
/// The part of `c` from `t0` to `t1` (reversed when `t1 < t0`).
|
||||
pub fn sub(c: &Cubic, t0: f32, t1: f32) -> Cubic {
|
||||
if t1 < t0 {
|
||||
let r = sub(c, t1, t0);
|
||||
return [r[3], r[2], r[1], r[0]];
|
||||
}
|
||||
let left = if t1 >= 1.0 { *c } else { split(c, t1.max(0.0)).0 };
|
||||
if t0 <= 0.0 || t1 <= 0.0 {
|
||||
return left;
|
||||
}
|
||||
split(&left, (t0 / t1).clamp(0.0, 1.0)).1
|
||||
}
|
||||
|
||||
/// The parameter on `c` nearest `p`, and the distance.
|
||||
pub fn nearest(c: &Cubic, p: Vec2) -> (f32, f32) {
|
||||
const N: usize = 32;
|
||||
let mut best = (0.0f32, f32::INFINITY);
|
||||
for i in 0..=N {
|
||||
let t = i as f32 / N as f32;
|
||||
let d = cubic_point(c, t).distance(p);
|
||||
if d < best.1 {
|
||||
best = (t, d);
|
||||
}
|
||||
}
|
||||
// Golden-section search around the best sample.
|
||||
let (mut lo, mut hi) = ((best.0 - 1.0 / N as f32).max(0.0), (best.0 + 1.0 / N as f32).min(1.0));
|
||||
const G: f32 = 0.618_034;
|
||||
for _ in 0..30 {
|
||||
let (m1, m2) = (hi - (hi - lo) * G, lo + (hi - lo) * G);
|
||||
if cubic_point(c, m1).distance(p) < cubic_point(c, m2).distance(p) {
|
||||
hi = m2;
|
||||
} else {
|
||||
lo = m1;
|
||||
}
|
||||
}
|
||||
let t = 0.5 * (lo + hi);
|
||||
let d = cubic_point(c, t).distance(p);
|
||||
if d < best.1 { (t, d) } else { best }
|
||||
}
|
||||
|
||||
fn bounds_meet(a: &Cubic, b: &Cubic, pad: f32) -> bool {
|
||||
let lo = |c: &Cubic| c.iter().fold(Vec2::new(f32::INFINITY, f32::INFINITY), |m, p| Vec2::new(m.x.min(p.x), m.y.min(p.y)));
|
||||
let hi = |c: &Cubic| c.iter().fold(Vec2::new(f32::NEG_INFINITY, f32::NEG_INFINITY), |m, p| Vec2::new(m.x.max(p.x), m.y.max(p.y)));
|
||||
let (al, ah, bl, bh) = (lo(a), hi(a), lo(b), hi(b));
|
||||
al.x <= bh.x + pad && bl.x <= ah.x + pad && al.y <= bh.y + pad && bl.y <= ah.y + pad
|
||||
}
|
||||
|
||||
/// Where `c` runs along `of`: the parameters on `of` of its two ends, when both ends and three
|
||||
/// points between lie within `tol` of it and it is not a single point there.
|
||||
fn along(c: &Cubic, of: &Cubic, tol: f32) -> Option<(f32, f32)> {
|
||||
let (u0, d0) = nearest(of, c[0]);
|
||||
let (u1, d1) = nearest(of, c[3]);
|
||||
if d0 > tol || d1 > tol || (u1 - u0).abs() < 1e-4 {
|
||||
return None;
|
||||
}
|
||||
[0.25, 0.5, 0.75].iter().all(|&t| nearest(of, cubic_point(c, t)).1 <= tol).then_some((u0, u1))
|
||||
}
|
||||
|
||||
/// `piece` with its ends moved onto `a` and `b`, the handles moving with them (the anchors of a
|
||||
/// path stay exactly where they were, so it stays joined to its neighbours).
|
||||
fn pinned(piece: &Cubic, a: Vec2, b: Vec2) -> PathCmd {
|
||||
PathCmd::CubicTo(piece[1] + (a - piece[0]), piece[2] + (b - piece[3]), b)
|
||||
}
|
||||
|
||||
/// Replaces every stretch of `path` that runs along `old` with the same stretch of `new` (the
|
||||
/// edge `old` bent into `new`; their ends are the same). A segment lying along part of `old`
|
||||
/// takes that part of `new`; a segment that `old` lies along part of is split at `old`'s ends
|
||||
/// first. Returns how many segments changed.
|
||||
pub fn follow(path: &mut Path, old: &Cubic, new: &Cubic, tol: f32) -> usize {
|
||||
if !(tol.is_finite() && tol > 0.0) || !old.iter().chain(new).all(|p| p.is_finite()) {
|
||||
return 0;
|
||||
}
|
||||
let mut changed = 0;
|
||||
let mut k = 0;
|
||||
while k < path.cmds.len().min(MAX_CMDS) {
|
||||
let Some(s) = segment_cubic(path, k) else {
|
||||
k += 1;
|
||||
continue;
|
||||
};
|
||||
if !bounds_meet(&s, old, tol) {
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some((u0, u1)) = along(&s, old, tol) {
|
||||
// All of this segment is a stretch of the edge.
|
||||
if let Some(c) = path.cmds.get_mut(k) {
|
||||
*c = pinned(&sub(new, u0, u1), s[0], s[3]);
|
||||
changed += 1;
|
||||
}
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
let Some((s0, s1)) = along(old, &s, tol) else {
|
||||
k += 1;
|
||||
continue;
|
||||
};
|
||||
// The edge is a stretch of this (longer) segment: cut it out and replace it.
|
||||
let (lo, hi) = (s0.min(s1), s0.max(s1));
|
||||
const END: f32 = 1e-4;
|
||||
if hi < 1.0 - END && !path.split_segment(k, hi) {
|
||||
k += 1;
|
||||
continue;
|
||||
}
|
||||
let mid = if lo > END && path.split_segment(k, lo / hi.max(END)) { k + 1 } else { k };
|
||||
if let (Some(m), Some(start)) = (segment_cubic(path, mid), path.segment_start(mid)) {
|
||||
let piece = if s0 <= s1 { *new } else { [new[3], new[2], new[1], new[0]] };
|
||||
if let Some(c) = path.cmds.get_mut(mid) {
|
||||
*c = pinned(&piece, start, m[3]);
|
||||
changed += 1;
|
||||
}
|
||||
}
|
||||
k = mid + 1;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The anchors of `path` at `p` (within `tol`), as the commands that name them. When none is
|
||||
/// there but a segment passes within `tol` (another shape ends on this one's edge), the segment
|
||||
/// is split there first, so the point can move with the shapes that end on it.
|
||||
pub fn anchors_at(path: &mut Path, p: Vec2, tol: f32) -> Vec<usize> {
|
||||
let near = |path: &Path| path.editable_anchors().into_iter().filter(|(_, q)| q.distance(p) <= tol).map(|(i, _)| i).collect::<Vec<_>>();
|
||||
let found = near(path);
|
||||
if !found.is_empty() || path.cmds.len() >= MAX_CMDS {
|
||||
return found;
|
||||
}
|
||||
match path.nearest_segment(p, &Affine::IDENTITY) {
|
||||
Some((cmd, t, d)) if d <= tol && t > 0.0 && t < 1.0 && path.split_segment(cmd, t) => vec![cmd],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn line(a: (f32, f32), b: (f32, f32)) -> Cubic {
|
||||
let (a, b) = (Vec2::new(a.0, a.1), Vec2::new(b.0, b.1));
|
||||
[a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bent_edge_passes_through_the_dragged_point_and_keeps_its_ends() {
|
||||
let c = line((0.0, 0.0), (90.0, 0.0));
|
||||
let Some(b) = bend(&c, 0.5, Vec2::new(0.0, 30.0)) else { panic!("no bend") };
|
||||
assert_eq!((b[0], b[3]), (c[0], c[3]));
|
||||
assert!(cubic_point(&b, 0.5).distance(Vec2::new(45.0, 30.0)) < 1e-3, "{:?}", cubic_point(&b, 0.5));
|
||||
// Off centre too: the grabbed point goes exactly where the pointer took it.
|
||||
let Some(b) = bend(&c, 0.2, Vec2::new(5.0, -12.0)) else { panic!("no bend") };
|
||||
assert!(cubic_point(&b, 0.2).distance(Vec2::new(23.0, -12.0)) < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_copy_of_an_edge_follows_a_bend() {
|
||||
// A fill's outline (a rectangle) shares its top edge with a stroke drawn the other way.
|
||||
let mut fill = Path::rect(0.0, 0.0, 90.0, 60.0);
|
||||
fill.close_explicitly();
|
||||
let old = line((90.0, 0.0), (0.0, 0.0));
|
||||
let Some(new) = bend(&old, 0.5, Vec2::new(0.0, -20.0)) else { panic!("no bend") };
|
||||
assert_eq!(follow(&mut fill, &old, &new, 0.2), 1);
|
||||
// The top now bulges up through (45, −20); the other sides are untouched.
|
||||
let top = fill.cmds.iter().position(|c| matches!(c, PathCmd::CubicTo(..))).and_then(|k| segment_cubic(&fill, k));
|
||||
let Some(top) = top else { panic!("no curve: {:?}", fill.cmds) };
|
||||
assert!(cubic_point(&top, 0.5).distance(Vec2::new(45.0, -20.0)) < 1e-3);
|
||||
assert_eq!(fill.cmds.iter().filter(|c| matches!(c, PathCmd::LineTo(_))).count(), 3);
|
||||
// A longer segment that the edge is part of is cut at the edge's ends.
|
||||
let mut long = Path::line(Vec2::new(-30.0, 0.0), Vec2::new(120.0, 0.0));
|
||||
assert_eq!(follow(&mut long, &old, &new, 0.2), 1);
|
||||
assert_eq!(long.cmds.len(), 4, "{:?}", long.cmds);
|
||||
let a = long.anchors().into_iter().map(|(_, p)| p).collect::<Vec<_>>();
|
||||
assert!(a.iter().any(|p| p.distance(Vec2::ZERO) < 1e-3) && a.iter().any(|p| p.distance(Vec2::new(90.0, 0.0)) < 1e-3), "{a:?}");
|
||||
let Some(mid) = segment_cubic(&long, 2) else { panic!() };
|
||||
assert!(cubic_point(&mid, 0.5).distance(Vec2::new(45.0, -20.0)) < 1e-2, "{:?}", cubic_point(&mid, 0.5));
|
||||
// Something merely nearby is left alone.
|
||||
let mut other = Path::line(Vec2::new(0.0, 5.0), Vec2::new(90.0, 5.0));
|
||||
assert_eq!(follow(&mut other, &old, &new, 0.2), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_gets_an_anchor_where_another_ends_on_it() {
|
||||
let mut p = Path::line(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0));
|
||||
assert_eq!(anchors_at(&mut p, Vec2::new(100.05, 0.0), 0.2), vec![1], "an end that is there");
|
||||
assert_eq!(anchors_at(&mut p, Vec2::new(40.0, 0.1), 0.2), vec![1], "split there");
|
||||
assert_eq!(p.cmds.len(), 3);
|
||||
assert!(anchors_at(&mut p, Vec2::new(40.0, 5.0), 0.2).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearest_finds_the_closest_point_on_a_curve() {
|
||||
let c = [Vec2::new(0.0, 0.0), Vec2::new(0.0, 50.0), Vec2::new(100.0, 50.0), Vec2::new(100.0, 0.0)];
|
||||
let (t, d) = nearest(&c, Vec2::new(50.0, 60.0));
|
||||
assert!((t - 0.5).abs() < 1e-3 && (d - 22.5).abs() < 1e-2, "{t} {d}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user