From 58f11291237ac8a940284fc047e5359dc7a1f042 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 09:56:35 -0800 Subject: [PATCH] Cut Path: the cut ends are selected with one set call Cut Path at Selected Anchor Points cleared the selection and then added each cut path in turn, and each add searched the paths already added, so selecting the cut ends took time that grows with the square of the number of cut paths. The command now selects them with one Selection::set call, which skips repeats through a hash set and keeps the order in which each path first appears, and then adds each cut end's anchor. The selection is the same in every field; a new test compares it with the one-by-one build on open, closed and multi-subpath cuts, long lists and an empty list. The gain shows on large documents. With the 8 middle anchors of each of 5,000 open paths of 10 anchors selected, building the selection of 40,000 cut ends takes 9.7 ms instead of 232 ms of CPU time, and with 2,000 paths 3.2 ms instead of 39 ms (medians of 7 runs of the new cut_path_select_bench example, both ways in one process). --- .../engine/examples/cut_path_select_bench.rs | 167 ++++++++++++++++++ crates/engine/src/cmd/path.rs | 75 +++++++- docs/target-app-parity.md | 1 + 3 files changed, 238 insertions(+), 5 deletions(-) create mode 100644 crates/engine/examples/cut_path_select_bench.rs diff --git a/crates/engine/examples/cut_path_select_bench.rs b/crates/engine/examples/cut_path_select_bench.rs new file mode 100644 index 0000000000..1deed62e6f --- /dev/null +++ b/crates/engine/examples/cut_path_select_bench.rs @@ -0,0 +1,167 @@ +//! `cargo run --release -p vectorcraft-engine --example cut_path_select_bench` prints the time +//! Cut Path at Selected Anchor Points takes to select the cut ends, on synthetic documents of 500, +//! 2,000 and 5,000 open paths of 10 anchors each with the 8 anchors between the ends of each +//! direct-selected, and on one path of 2,000 open subpaths selected the same way. For each it times two ways of building the same +//! selection from the cut ends: clearing the selection and adding each path in turn (each add looks +//! through the paths already added), and one `Selection::set` call followed by the anchors. It +//! checks that both give the same selection, every field, before it times them, and then times the +//! whole command once per run on the 2,000-path document. +//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run +//! builds the selection 20 times, and each row is the median time of one build. On Linux the times are the CPU time of the main thread, which runs everything, in +//! ms; elsewhere they are wall times. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + +/// The anchors of each path, or of each subpath of the one compound path. +const ANCHORS: usize = 10; + +/// The builds of the selection in each timed run; a row gives the time of one build. +const REPS: usize = 20; + +/// What the command selects for one cut end: the path and its anchor (subpath, anchor). +type Pick = (NodeId, (usize, usize)); + +/// A way of building the selection from the cut ends. +type Rebuild = fn(&mut Selection, &[Pick]); + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only). +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise. +fn measure(f: impl FnOnce()) -> f64 { + match thread_cpu_ns() { + Some(start) => { + f(); + thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6) + } + None => { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + } + } +} + +/// The selection built by clearing it and adding each path in turn. +fn one_by_one(sel: &mut Selection, picked: &[Pick]) { + sel.clear(); + for (id, a) in picked { + sel.add(*id); + sel.anchors.entry(*id).or_default().insert(*a); + } +} + +/// The selection built with one `Selection::set` call, as the command builds it. +fn one_call(sel: &mut Selection, picked: &[Pick]) { + sel.set(picked.iter().map(|(id, _)| *id)); + for (id, a) in picked { + sel.anchors.entry(*id).or_default().insert(*a); + } +} + +fn exec(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// An open subpath of [`ANCHORS`] corner anchors 10 pt apart along row `row`. +fn row(row: usize) -> SubPath { + let y = row as f64 * 20.0; + SubPath::new((0..ANCHORS).map(|i| Anchor::corner(Point::new(i as f64 * 10.0, y))).collect(), false) +} + +/// A session with the paths in `paths` and every anchor of theirs but the two ends of each +/// subpath direct-selected (a path with all its anchors selected counts as selected whole). +fn fixture(paths: Vec) -> Session { + let mut doc = Document::new(1600.0, 1200.0); + let l = doc.layers.first().map(|l| l.id); + let mut items = vec![]; + for pd in paths { + let id = doc.alloc_id(); + let refs: Vec<[usize; 2]> = + pd.subpaths.iter().enumerate().flat_map(|(si, sp)| (1..sp.anchors.len().saturating_sub(1)).map(move |ai| [si, ai])).collect(); + doc.insert(l, usize::MAX, Node::path(id, pd, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap(); + items.push(json!({"id": id.0, "anchors": refs})); + } + let mut s = Session::new(); + s.add_document(doc, None); + exec(&mut s, "select.anchorsMany", json!({"items": items})); + s +} + +/// The cut ends the command selects, in the order it selects them: read back from the selection it +/// leaves, which holds each cut path once in that order. +fn picked_after_cut(s: &Session) -> Vec { + let sel = &s.doc().unwrap().selection; + sel.objects.iter().flat_map(|id| sel.anchors[id].iter().map(move |a| (*id, *a))).collect() +} + +fn bench(name: &str, paths: impl Fn() -> Vec) { + let mut s = fixture(paths()); + exec(&mut s, "path.cutAtAnchors", json!({})); + let picked = picked_after_cut(&s); + let mut start = Selection::default(); + one_by_one(&mut start, &[(NodeId(u64::MAX), (0, 3))]); + let (mut a, mut b) = (start.clone(), start.clone()); + one_by_one(&mut a, &picked); + one_call(&mut b, &picked); + assert_eq!(a, b, "both ways give the same selection"); + assert_eq!(b, s.doc().unwrap().selection, "the command gives that selection"); + let (mut old, mut new) = (vec![], vec![]); + for i in 0..iters() { + let run = |f: Rebuild, out: &mut Vec| { + let ms = measure(|| { + for _ in 0..REPS { + let mut sel = start.clone(); + f(&mut sel, black_box(&picked)); + black_box(&sel); + } + }); + out.push(ms / REPS as f64); + }; + if i % 2 == 0 { + run(one_by_one, &mut old); + run(one_call, &mut new); + } else { + run(one_call, &mut new); + run(one_by_one, &mut old); + } + } + let (old, new) = (median(old), median(new)); + println!(" {name:<44} {:>7} {:>6} {old:>12.3} {new:>12.3} {:>8.1}x", picked.len(), b.objects.len(), old / new); +} + +fn main() { + let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" }; + println!(" {:<44} {:>7} {:>6} {:>12} {:>12} {:>9}", "document", "picked", "ids", format!("add, {unit}"), format!("set, {unit}"), "speedup"); + for n in [500, 2_000, 5_000] { + bench(&format!("{n} open paths, {ANCHORS} anchors each"), || (0..n).map(|i| PathData::single(row(i))).collect()); + } + bench("one path of 2,000 open subpaths", || vec![PathData::new((0..2_000).map(row).collect())]); + let whole: Vec = (0..iters()) + .map(|_| { + let mut s = fixture((0..2_000).map(|i| PathData::single(row(i))).collect()); + measure(|| drop(black_box(exec(&mut s, "path.cutAtAnchors", json!({}))))) + }) + .collect(); + println!(" path.cutAtAnchors, 2,000 open paths, whole command: {:.3} {unit}", median(whole)); +} diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 8ae3b46426..6c06b52c6c 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1874,20 +1874,85 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result { } cut.finish(d)?; // Each cut leaves one of its two coincident anchors selected, so a drag pulls the ends apart. - sel.clear(); - for (id, a) in picked { - sel.add(id); - sel.anchors.entry(id).or_default().insert(a); - } + select_cut_ends(sel, &picked); Ok(all) })?; Ok(super::draw2::ids_json(&ids)) } +/// Replaces the selection with the anchors in `picked`: each id once, in the order it first +/// appears, with every anchor listed for it. An empty `picked` clears the selection. +fn select_cut_ends(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) { + sel.set(picked.iter().map(|(id, _)| *id)); + for (id, a) in picked { + sel.anchors.entry(*id).or_default().insert(*a); + } +} + #[cfg(test)] mod tests { use super::*; + /// `select_cut_ends` by clearing the selection and adding each id in turn, kept as the + /// reference the one-call version must match. + fn select_cut_ends_one_by_one(sel: &mut Selection, picked: &[(NodeId, (usize, usize))]) { + sel.clear(); + for (id, a) in picked { + sel.add(*id); + sel.anchors.entry(*id).or_default().insert(*a); + } + } + + /// A selection with every field set, the art made since the last deselect included. + fn busy_selection() -> Selection { + Selection { + objects: vec![NodeId(90), NodeId(91)], + anchors: [(NodeId(90), [(0, 3)].into())].into(), + segments: [(NodeId(91), [(0, 1)].into())].into(), + key: Some(NodeId(90)), + target: Some(NodeId(91)), + slices: vec![NodeId(92)], + guides: vec![NodeId(93)], + key_guide: Some(NodeId(93)), + key_anchor: Some((NodeId(90), (0, 3))), + symbol_part: Some(vectorcraft_doc::SymbolPart { instance: NodeId(94), path: vec![0, 2] }), + on_path_member: Some(NodeId(95)), + new_art: Arc::new([NodeId(90), NodeId(97)].into()), + } + } + + /// The cut ends of open paths, of an opened closed path, of a path of several subpaths (one id + /// with several anchors, first seen before other ids), long lists and an empty one give the + /// same selection, every field, as clearing it and adding each id in turn. + #[test] + fn selecting_cut_ends_matches_adding_them_one_by_one() { + let n = NodeId; + let mut cases: Vec> = vec![ + vec![], + vec![(n(1), (0, 0)), (n(2), (0, 0))], + vec![(n(5), (0, 0))], + vec![(n(7), (0, 0)), (n(3), (1, 0)), (n(8), (0, 0)), (n(3), (2, 0)), (n(7), (0, 0)), (n(3), (0, 0))], + ]; + let mut rng = Lcg(11); + for len in [50, 2_000] { + cases.push((0..len).map(|_| (n(rng.below(300) + 1), (rng.below(4) as usize, 0))).collect()); + } + for picked in &cases { + for start in [Selection::default(), busy_selection()] { + let (mut ours, mut theirs) = (start.clone(), start.clone()); + select_cut_ends(&mut ours, picked); + select_cut_ends_one_by_one(&mut theirs, picked); + assert_eq!(ours, theirs, "{picked:?}"); + assert_eq!(ours.new_art, start.new_art); + } + } + let mut sel = busy_selection(); + select_cut_ends(&mut sel, &cases[3]); + assert_eq!(sel.objects, [n(7), n(3), n(8)]); + assert_eq!(sel.anchors[&n(3)].iter().collect::>(), [&(0, 0), &(1, 0), &(2, 0)]); + assert_eq!((sel.anchors.len(), sel.key, sel.target, sel.symbol_part.is_some()), (3, None, None, false)); + } + /// `merge_coincident` removing each merged anchor from the vector straight away, kept as the /// reference the one-pass version must match. fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option) -> usize { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 04f9907fec..77e836fdea 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2092,6 +2092,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Overprint Preview or Separations Preview on, the renderer keeps the art it prepared for the preview from one frame to the next. It prepares again the objects that changed, and all of the art when Discard White Overprint changes or, with Separations Preview, when the plates shown, the proof setup, the swatches, the Spot Colors option or the color settings change or a profile is loaded. It draws the other objects from the art, geometry and stroke outlines it kept for them. Pathfinder › Merge and the `pathfinder.merge` group effect find the faces of every fill in a few contour passes over the arrangement, as Trim and Crop do, instead of one pass for each distinct fill. The output paths and their order are the same. With 8,000 squares that do not touch, each with its own fill, Merge takes 72 to 107 ms instead of 17 to 32 s (release build). The Pathfinder panel, Offset Path, Clean Up, Divide Objects Below, Make and Release Blend, Envelope Distort's Make and Release, Repeat (Radial, Grid, Mirror and Release), Vector Halftone, New and Redefine Symbol, Delete Symbol, erasing with the Symbol Sprayer, Rasterize, Convert to Artboards, Flatten Transparency, Clear Guides, Shape Builder, Live Paint, Release Image Trace, Make and Release Opacity Mask, Delete with direct-selected anchor points, Remove Anchor Points, Cut Path, and the Shaper, Knife, Eraser, Path Eraser, Line Cut, Rectangle Cut, Mirror & Cut and Blob Brush tools add and remove objects in one pass over each layer or group they change, and Outline Stroke and Expand write each new object in the place of the object it replaces (#1429). + Cut Path at Selected Anchor Points (`path.cutAtAnchors`) selects the cut ends with one selection call, which skips paths already selected through a hash set, instead of adding each cut path in turn and searching the paths already added. The selection is the same, every field (`selecting_cut_ends_matches_adding_them_one_by_one`). With the 8 middle anchors of each of 5,000 open paths of 10 anchors selected, building the selection of 40,000 cut ends takes 9.7 ms instead of 232 ms of CPU time, and with 2,000 paths 3.2 ms instead of 39 ms; at 500 paths both take 3 ms or less (medians of 7 runs, `cargo run --release -p vectorcraft-engine --example cut_path_select_bench`). Scores and hours unchanged. Offset Path looks up the segments near each candidate hole or island in a tree of the source path's segment bounds when it decides whether to drop that contour, instead of testing the bounds of every segment. The output paths are the same. On compound and open paths of 25,000 to 40,000 anchors with 6,400 to 11,976 candidate contours, that check takes 11 to 13 ms instead of 140 to 649 ms (medians of five interleaved runs). The limit on overlapping segment pairs is the same, so a path that stops with "Offset Path: the path is too complex to offset" still stops there. Offset Path on several selected paths, or on a group of them, works out their offsets on as many threads as the computer has logical CPUs (one thread on the web and for a single path), and then makes the new objects one after another in the selection's order. The new objects, their ids, their stacking, the selection and the undo step are the same as when the paths were offset one at a time, and when more than one path fails, the error is the one for the first of them in that order (`tests::pathops::offset_path_of_several_objects_keeps_their_order`, `tests::pathops::offset_path_works_on_several_threads_in_order`, `tests::pathops::offset_path_stops_after_the_first_failure`). Finding the distinct regions of an arrangement lists the shapes that cover each region instead of keeping a flag for every shape, so that step's time follows how many shapes cover each region rather than how many shapes there are. Divide, Hard Mix, Soft Mix, Shape Builder, Flatten Transparency, trapping, Intertwine and the Pathfinder effects are among the commands that use that step. The regions, their order and the output are the same. Divide on 3,000 overlapping rectangles takes 0.84 to 1.13 billion CPU cycles on its thread instead of 1.25 to 1.46 billion (dev build, six runs of each, alternating, while other builds were running).