From b57d3393eb6f3dc14cfbde0260816440fca08ee0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:09:31 -0800 Subject: [PATCH] Smooth: a drag's segment search stays within its piece limit however many curved segments are in reach A Smooth drag gave each curved segment in reach at least one measured piece of its share of MAX_REACH_PIECES, measured the whole of every curved segment it passed, counted or not, and charged a segment's own share one piece per call while each halving measured two, so the total grew past the limit when more curved segments than the limit were in reach, and a long curve measured a few pieces more than its share. path.smoothRegion now keeps one count of the pieces the whole drag may measure past the first measurement of each curved segment. A piece is halved only when two pieces are left both in the segment's share and in the drag's count, and both halves are taken from each before either is measured. A drag measures at most 131,072 pieces plus one for each curved segment it searches, the segments in reach still share the search equally whatever order they come in, and a segment searched after the count runs out is still found in reach at its middle or its point nearest the drag. Docs: docs/mcp.md (path.smoothRegion), docs/target-app-parity.md. --- crates/engine/src/cmd/draw2/smooth.rs | 161 ++++++++++++++++++++++---- docs/mcp.md | 5 + docs/target-app-parity.md | 1 + 3 files changed, 142 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..e0a539d2a6 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -402,11 +402,18 @@ fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath { } /// Pieces of curve that one Smooth drag measures against the drag while it searches the segments -/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach, -/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach -/// of the drag. +/// under it ([`reach_samples`]), besides the whole of each curved segment, which is measured once +/// however many there are: a drag measures no more than this many pieces plus one for each curved +/// segment of the paths it searches. Shared equally by the curved segments that come within its +/// reach, it is enough to search 300,000 pt of curve within the default reach of the drag. const MAX_REACH_PIECES: usize = 1 << 17; +#[cfg(test)] +thread_local! { + /// Tests: how many pieces of curve [`reach_samples`] measured against a drag on this thread. + static PIECES_MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The box around the control points of `s`, which holds all of `s`. fn control_box(s: CubicBez) -> Rect { Rect::from_points(s.p0, s.p1).union_pt(s.p2).union_pt(s.p3) @@ -486,13 +493,24 @@ fn segments_in_reach(pd: &PathData, pts: &[Point], radius: f64) -> usize { /// Samples along the part of `c` from `t0` to `t1`, in order: (t, whether the point there is within /// `radius` of the stretches `of` of the drag `pts`). A piece no stretch comes near gives one sample /// out of reach; the others are halved until their control polygon is no longer than half the -/// reach, or until `budget` pieces have been measured, and then give one sample: in reach at the -/// piece's middle or at its place nearest the drag when either is in reach, otherwise out of reach -/// at its middle. Each piece measures only the stretches near +/// reach, or until fewer than the two halves are left in this segment's `budget` or in `shared`, +/// the pieces the whole drag may still measure past the first piece of each segment, and then give +/// one sample: in reach at the piece's middle or at its place nearest the drag when either is in +/// reach, otherwise out of reach at its middle. Both halves of a piece are taken from `budget` and +/// from `shared` before either is measured, so a search measures no more than one piece besides +/// what it takes from them. Each piece measures only the stretches near /// the piece it was cut from, so a long drag along a long curve costs about one pass over the drag /// per halving, plus the stretches near each piece. -fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usize]), radius: f64, budget: &mut usize, out: &mut Vec<(f64, bool)>) { - *budget = budget.saturating_sub(1); +fn reach_samples( + c: CubicBez, + (t0, t1): (f64, f64), + (pts, of): (&[Point], &[usize]), + radius: f64, + (budget, shared): (&mut usize, &mut usize), + out: &mut Vec<(f64, bool)>, +) { + #[cfg(test)] + PIECES_MEASURED.set(PIECES_MEASURED.get() + 1); let s = c.subsegment(t0..t1); let mid = 0.5 * (t0 + t1); let near = stretches_near(pts, of, control_box(s), radius); @@ -501,7 +519,7 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz return; } let len = s.p0.distance(s.p1) + s.p1.distance(s.p2) + s.p2.distance(s.p3); - if len <= (radius / 2.0).max(1e-3) || *budget == 0 || mid <= t0 || mid >= t1 { + if len <= (radius / 2.0).max(1e-3) || *budget < 2 || *shared < 2 || mid <= t0 || mid >= t1 { // The piece's middle, or the place on it nearest the drag when the middle is out of reach. let sample = if dist_to_stretches(pts, &near, c.eval(mid)) <= radius { (mid, true) @@ -512,8 +530,10 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz out.push(sample); return; } - reach_samples(c, (t0, mid), (pts, &near), radius, budget, out); - reach_samples(c, (mid, t1), (pts, &near), radius, budget, out); + *budget -= 2; + *shared -= 2; + reach_samples(c, (t0, mid), (pts, &near), radius, (&mut *budget, &mut *shared), out); + reach_samples(c, (mid, t1), (pts, &near), radius, (budget, shared), out); } /// `sp` cut where the reach `radius` of the drag `pts` crosses its curved segments, and whether each @@ -522,8 +542,11 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz /// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a /// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between /// stay as they are. A segment is searched no more than half the reach apart where it comes within -/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment. -fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubPath, Vec) { +/// the reach of the drag ([`reach_samples`]): each curved segment is measured whole, and then up +/// to `share` more pieces of it are measured while the drag's `shared` pieces last, so the segments +/// in reach share the search equally whatever order they come in, and a segment searched after +/// the pieces run out is still found where its middle or its place nearest the drag is in reach. +fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, (share, shared): (usize, &mut usize)) -> (SubPath, Vec) { let near = |q: Point| dist_to_polyline(pts, q) <= radius; let n = sp.anchors.len(); let marked: Vec = sp.anchors.iter().map(|a| near(a.p)).collect(); @@ -535,7 +558,7 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP } let c = sp.segment(i); let (mut samples, mut budget) = (vec![], share); - reach_samples(c, (0.0, 1.0), (pts, &all), radius, &mut budget, &mut samples); + reach_samples(c, (0.0, 1.0), (pts, &all), radius, (&mut budget, &mut *shared), &mut samples); // Stretches of samples alike, in order: (in reach, first, last). let mut runs: Vec<(bool, usize, usize)> = vec![]; for (k, s) in samples.iter().enumerate() { @@ -580,14 +603,15 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP /// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach. /// A closed path whose first anchor is in reach starts at the point of the refitted path nearest -/// that anchor's place (VectorCraft's own rule). -fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option { +/// that anchor's place (VectorCraft's own rule). `search` is each curved segment's share of the +/// drag's search and the pieces the drag has left ([`mark_reached`]). +fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, search: (usize, &mut usize), tol: f64, sigma: f64) -> Option { if sp.anchors.len() < 2 { return None; } let near = &|q: Point| dist_to_polyline(pts, q) <= radius; // A drag along a segment smooths it even when its anchors are out of reach. - let (sp, marked) = mark_reached(sp, pts, radius, share); + let (sp, marked) = mark_reached(sp, pts, radius, search); let sp = &sp; if !marked.iter().any(|m| *m) { return None; @@ -743,15 +767,17 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) { paths.push((id, path_of(&st.doc, id)?.0)); } - // Each curved segment in reach gets the same share of the search, whatever order they come in. + // Each curved segment in reach gets the same share of the search, whatever order they come in, + // and all of them together measure no more than `MAX_REACH_PIECES` pieces past their first. let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &pts, radius)).sum(); let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1); + let mut shared = MAX_REACH_PIECES; for (id, pd) in paths { let mut changed = false; let subs: Vec = pd .subpaths .iter() - .map(|sp| match smooth_subpath(sp, &pts, radius, share, tol, sigma) { + .map(|sp| match smooth_subpath(sp, &pts, radius, (share, &mut shared), tol, sigma) { Some(n) if n != *sp && n.anchors.len() >= 2 => { changed = true; n @@ -1094,19 +1120,104 @@ mod tests { assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring()); } + /// How many pieces `f` makes [`reach_samples`] measure on this thread. + fn pieces_measured(f: impl FnOnce()) -> usize { + let before = PIECES_MEASURED.get(); + f(); + PIECES_MEASURED.get() - before + } + /// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more - /// pieces than the budget it is given, and a search with none left gives one sample. + /// than one piece besides the drag's `MAX_REACH_PIECES`, counting the pieces it halves as well + /// as those it samples, and a search with none of the drag's pieces left measures the curve + /// once and gives one sample, whatever share of its own it has. #[test] fn searching_a_segment_under_a_drag_stays_within_its_budget() { let c = CubicBez::new(Point::new(0.0, 0.0), Point::new(300000.0, 0.0), Point::new(700000.0, 0.0), Point::new(1000000.0, 0.0)); let pts: Vec = (0..1000).map(|i| Point::new(f64::from(i) * 1000.0, 0.0)).collect(); let all = drag_stretches(&pts); - let mut budget = MAX_REACH_PIECES; + let (mut budget, mut shared) = (MAX_REACH_PIECES, MAX_REACH_PIECES); let (mut first, mut second) = (vec![], vec![]); - reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut first); - reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut second); - assert!(first.len() <= MAX_REACH_PIECES, "{} samples", first.len()); - assert_eq!((budget, second.len()), (0, 1), "the budget is spent, so the next search gives one sample"); + let measured = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut budget, &mut shared), &mut first)); + assert!(measured <= MAX_REACH_PIECES + 1, "{measured} pieces measured"); + assert!(first.len() <= measured && first.len() > 1, "{} samples", first.len()); + assert!(shared < 2, "{shared} pieces left"); + let mut fresh = MAX_REACH_PIECES; + let again = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut fresh, &mut shared), &mut second)); + assert_eq!((again, second.len()), (1, 1), "the drag's pieces are spent, so the next search gives one sample"); + } + + /// One curved segment `w` pt wide from `(x, y)`, bowed `h` pt up. + fn bow((x, y): (f64, f64), w: f64, h: f64) -> CubicBez { + CubicBez::new(Point::new(x, y), Point::new(x + w / 3.0, y + h), Point::new(x + 2.0 * w / 3.0, y + h), Point::new(x + w, y)) + } + + /// An open subpath of the curved segments `segs`, each starting where the one before ends. + fn chain(segs: &[CubicBez]) -> SubPath { + let mut anchors: Vec = vec![]; + for s in segs { + match anchors.last_mut() { + Some(last) => *last = Anchor::with_handles(s.p0, last.h_in, s.p1), + None => anchors.push(Anchor::with_handles(s.p0, s.p0, s.p1)), + } + anchors.push(Anchor::with_handles(s.p3, s.p2, s.p3)); + } + SubPath::new(anchors, false) + } + + /// A drag along two subpaths of 21,845 curved segments 100 pt long each, which share the search + /// three pieces to a segment, and past a third of 1,000 curved segments far from the drag: every + /// segment is measured whole and the whole drag measures no more than `MAX_REACH_PIECES` pieces + /// past those, though each segment in reach would halve its pieces while its share lasts. Each + /// segment in reach, the last one included, is halved once with its share of three, so the + /// segments searched first leave the later ones their share. + #[test] + fn a_drag_over_many_curved_segments_measures_at_most_its_pieces_past_the_first_of_each() { + let row = |(x, y): (f64, f64), n: u32| chain(&(0..n).map(|i| bow((x + f64::from(i) * 100.0, y), 100.0, 8.0)).collect::>()); + let subs = [row((0.0, 0.0), 21_845), row((3_000_000.0, 0.0), 21_845), row((0.0, 1e6), 1000)]; + let pts = [Point::new(-10.0, 0.0), Point::new(6_000_000.0, 0.0)]; + let segments: usize = subs.iter().map(SubPath::segment_count).sum(); + assert_eq!(segments, 2 * 21_845 + 1000); + let in_reach = segments_in_reach(&PathData::new(subs.to_vec()), &pts, 12.0); + assert_eq!(in_reach, 2 * 21_845, "the far segments are not counted"); + let share = (MAX_REACH_PIECES / in_reach).max(1); + assert_eq!(share, 3); + let mut shared = MAX_REACH_PIECES; + let mut marks = vec![]; + let measured = pieces_measured(|| { + for sp in &subs { + marks.push(mark_reached(sp, &pts, 12.0, (share, &mut shared)).1); + } + }); + assert!(measured >= segments && measured <= segments + MAX_REACH_PIECES, "{measured} pieces measured for {segments} segments"); + assert_eq!((measured, shared), (segments + 2 * in_reach, MAX_REACH_PIECES - 2 * in_reach), "every segment in reach is halved once"); + assert!(marks[0].iter().all(|m| *m), "the first path's anchors are all on the drag"); + } + + /// More than `MAX_REACH_PIECES` short curved segments in reach are each measured once, and a + /// segment searched after the drag's pieces are spent is still found in reach where only a + /// narrow stretch of it, away from its middle, comes near the drag. + #[test] + fn every_curved_segment_is_searched_after_the_drags_pieces_run_out() { + let n = 140_000; + let tiny = chain(&(0..n).map(|i| bow((f64::from(i) * 4.0, 0.0), 4.0, 1.0)).collect::>()); + let pts = [Point::new(0.0, 0.0), Point::new(f64::from(n) * 4.0, 0.0)]; + let share = (MAX_REACH_PIECES / segments_in_reach(&PathData::single(tiny.clone()), &pts, 12.0).max(1)).max(1); + let mut shared = MAX_REACH_PIECES; + let measured = pieces_measured(|| { + mark_reached(&tiny, &pts, 12.0, (share, &mut shared)); + }); + assert_eq!(measured, 140_000, "each segment is measured whole once"); + // An arch 1,000 pt wide and 300 pt high, with the drag on it a quarter of the way along. + let arch = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 400.0), Point::new(1000.0, 400.0), Point::new(1000.0, 0.0)); + let sp = chain(&[arch]); + let hit = [arch.eval(0.25)]; + assert!(dist_to_polyline(&hit, arch.eval(0.5)) > 12.0, "the arch's middle is out of reach"); + let mut spent = 0; + let (out, marked) = mark_reached(&sp, &hit, 12.0, (MAX_REACH_PIECES, &mut spent)); + assert_eq!(out.anchors.len(), 3, "{out:?}"); + assert_eq!(marked, vec![false, true, false]); + assert!(out.anchors[1].p.distance(hit[0]) <= 12.0, "{out:?}"); } /// A small piece of curve is measured only against the few stretches of a drag of 100,000 diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..b80eab886b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7171,6 +7171,11 @@ own, and the corner keeps its place and the directions the path arrives and leav `fidelity`. A call that changes no anchor returns `{ids: [], before: 0, after: 0}` and adds no undo step. The 57.5° threshold is VectorCraft's own value. +`path.smoothRegion` measures each curved segment of the paths it searches once whole against `points`, and cuts all of +them together into no more than 131,072 further pieces while it finds where `radius` reaches them, shared equally by +the segments in reach. A segment searched after those pieces run out is still smoothed where its middle, or its point +nearest `points`, is within `radius`. The limit is VectorCraft's own value. + In the desktop app, Object › Path › Smooth, the canvas context menu's Smooth… (listed while the selection holds a path) and the Contextual Task Bar's Smooth (with a path selected whole with the Direct Selection tool) open the slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` with field `level`) at the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..311bfabf6b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1552,6 +1552,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. + A Smooth drag measures each curved segment of the paths it searches once whole, and cuts all of them together into no more than 131,072 further pieces, shared equally by the segments in its reach, however many curved segments it passes over (`path.smoothRegion`). A segment searched after those pieces run out is still smoothed where its middle, or its point nearest the drag, is in reach. The limit is VectorCraft's own (engine tests `a_drag_over_many_curved_segments_measures_at_most_its_pieces_past_the_first_of_each` and `every_curved_segment_is_searched_after_the_drags_pieces_run_out`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`).