Skip to content

VectorCraft: An open-source, vector art tool written by scratch in pure Rust

#1172: edit a large selection in time linear in the document, not quadratic

arhammusheer4b260c364d73
diff --git a/apps/vectorcraft-cli/src/perf.rs b/apps/vectorcraft-cli/src/perf.rs
index 41da4abc6..afafd6db3 100644
--- a/apps/vectorcraft-cli/src/perf.rs
+++ b/apps/vectorcraft-cli/src/perf.rs
@@ -113,11 +113,117 @@ fn edit_drags(n: usize) -> Result<(f64, f64), String> {
Ok((handle, segment))
}
+/// Resident memory of this process in MB (`ps`), if available.
+fn rss_mb() -> Option<f64> {
+ let pid = std::process::id().to_string();
+ let out = std::process::Command::new("ps").args(["-o", "rss=", "-p", &pid]).output().ok().filter(|o| o.status.success())?;
+ String::from_utf8_lossy(&out.stdout).trim().parse::<f64>().ok().map(|kb| kb / 1024.0)
+}
+
+/// `--deep`: tracked rows (no budget yet) for work the budgets above don't reach: editing a whole
+/// selection, live effects, every Pathfinder operation, typing in a long story, and memory.
+fn deep(n: usize) -> Result<(), String> {
+ let err = |e: vectorcraft_engine::EngineError| e.to_string();
+ let mut rows: Vec<(String, f64)> = vec![];
+ let mut mem: Vec<(String, f64)> = vec![];
+ let mut note = |what: &str| {
+ if let Some(m) = rss_mb() {
+ mem.push((what.to_string(), m));
+ }
+ };
+ note("start");
+ // Editing every object of an n-path document.
+ let mut s = vectorcraft_engine::Session::new();
+ s.add_document(synthetic(n)?, None);
+ note("document built");
+ rows.push((format!("select all, {n} paths"), median_ms(3, || drop(s.execute("select.all", &json!({}))))));
+ rows.push((format!("nudge the selection ({n} paths)"), median_ms(5, || drop(s.execute("object.move", &json!({"dx": 1, "dy": 0}))))));
+ rows.push((format!("undo a nudge ({n} paths)"), median_ms(5, || drop(s.execute("edit.undo", &json!({}))))));
+ rows.push((format!("redo a nudge ({n} paths)"), median_ms(5, || drop(s.execute("edit.redo", &json!({}))))));
+ // Dragging the whole selection with the Selection tool: one pointer move (the preview).
+ {
+ use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind};
+ use vectorcraft_geom::Vec2;
+ let view = vectorcraft_engine::ViewInfo { zoom: 1.0, ..Default::default() };
+ let first = s.doc().map_err(err)?.selection.objects.first().copied();
+ let at = first.and_then(|id| s.doc().ok()?.doc.node(id)?.geometric_bounds()).map(|b| b.center());
+ if let Some(down) = at {
+ let ev = |kind, dx: f64| PointerEvent { kind, pos: down + Vec2::new(dx, 0.0), mods: Mods::default(), pressure: 1.0 };
+ s.select_tool("selection", view).map_err(err)?;
+ s.pointer(&ev(PointerKind::Down, 0.0), view).map_err(err)?;
+ let mut dx = 0.0;
+ rows.push((
+ format!("drag the selection, per move ({n} paths)"),
+ median_ms(5, || {
+ dx += 2.0;
+ let _ = s.pointer(&ev(PointerKind::Drag, dx), view);
+ }),
+ ));
+ s.pointer(&ev(PointerKind::Up, dx), view).map_err(err)?;
+ }
+ }
+ for _ in 0..40 {
+ s.execute("object.move", &json!({"dx": 1, "dy": 0})).map_err(err)?;
+ }
+ note("after 45 whole-selection edits");
+ drop(s);
+ // Live effects on 2,000 paths: render a page whose every object has the effect.
+ let opts = RenderOptions::default();
+ for (fx, params) in [("path.offsetPath", json!({"offset": 3})), ("distort.roughen", json!({"size": 5, "relative": true}))] {
+ let mut s = vectorcraft_engine::Session::new();
+ s.add_document(synthetic(2000)?, None);
+ s.execute("select.all", &json!({})).map_err(err)?;
+ s.execute("effect.apply", &json!({"effect": fx, "params": params})).map_err(err)?;
+ let doc = s.doc().map_err(err)?.doc.clone();
+ let mut r = Renderer::new();
+ r.render(&doc, 2880, 1800, Affine::scale(1.6), &opts);
+ rows.push((format!("render, 2,000 paths with {fx} (warm)"), median_ms(5, || drop(r.render(&doc, 2880, 1800, Affine::scale(1.6), &opts)))));
+ }
+ note("after live effects");
+ // Every Pathfinder operation on 300 overlapping paths.
+ for op in ["unite", "intersect", "exclude", "minusFront", "minusBack", "divide", "trim", "merge", "crop", "outline"] {
+ let ms = median_ms(1, || {
+ let mut s = vectorcraft_engine::Session::new();
+ if let Ok(d) = synthetic(300) {
+ s.add_document(d, None);
+ let _ = s.execute("select.all", &json!({})).and_then(|_| s.execute(&format!("object.pathfinder.{op}"), &json!({})));
+ }
+ });
+ rows.push((format!("Pathfinder {op}, 300 paths"), ms));
+ }
+ note("after Pathfinder");
+ // Typing one character in the middle of a 20,000-character area-type story.
+ let mut s = vectorcraft_engine::Session::new();
+ s.add_document(Document::new(1600.0, 1200.0), None);
+ let text: String = (0..2000).map(|i| if i % 12 == 11 { "paragraph.\n" } else { "lorem ips " }).collect();
+ let id = s.execute("text.create", &json!({"x": 20, "y": 20, "text": text, "size": 10, "area": {"width": 1500, "height": 1100}})).map_err(err)?;
+ let id = id.get("id").cloned().unwrap_or(json!(0));
+ let mut at = 10_000;
+ rows.push((
+ "type one character, 20,000-character area text".into(),
+ median_ms(9, || {
+ at += 1;
+ let _ = s.execute("text.editRange", &json!({"id": id, "start": at, "end": at, "insert": "x"}));
+ }),
+ ));
+ note("after typing");
+ outln!(" tracked (no budget yet)");
+ for (name, ms) in &rows {
+ outln!(" {name:<52} {ms:>10.2} ms");
+ }
+ for (what, mb) in &mem {
+ outln!(" memory {what:<45} {mb:>8.0} MB");
+ }
+ Ok(())
+}
+
pub fn run(args: &[String]) -> Result<(), String> {
let mut n = 50_000usize;
+ let mut want_deep = false;
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
+ "--deep" => want_deep = true,
"--paths" => n = it.next().and_then(|v| v.parse().ok()).ok_or("--paths needs a number")?,
other => return Err(format!("unknown perf option `{other}`")),
}
@@ -200,6 +306,9 @@ pub fn run(args: &[String]) -> Result<(), String> {
if let Some(e) = failed {
return Err(e);
}
+ if want_deep {
+ deep(n)?;
+ }
let mut over = 0;
outln!(" {:<40} {:>10} {:>10}", "", "measured", "budget");
diff --git a/crates/doc/src/assets.rs b/crates/doc/src/assets.rs
index ec84333a6..3c4451d54 100644
--- a/crates/doc/src/assets.rs
+++ b/crates/doc/src/assets.rs
@@ -50,7 +50,9 @@ impl Document {
/// `ids` that are in the document, back to front.
pub fn paint_order(&self, ids: impl IntoIterator<Item = NodeId>) -> Vec<NodeId> {
- let mut v: Vec<(Vec<usize>, NodeId)> = ids.into_iter().filter_map(|id| self.index_path(id).map(|p| (p, id))).collect();
+ let ids: Vec<NodeId> = ids.into_iter().collect();
+ let paths = self.index_paths(ids.iter().copied());
+ let mut v: Vec<(Vec<usize>, NodeId)> = ids.into_iter().filter_map(|id| paths.get(&id).map(|p| (p.clone(), id))).collect();
v.sort();
v.into_iter().map(|(_, id)| id).collect()
}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 259512b8e..7825de13e 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -795,6 +795,72 @@ impl Document {
find(&self.layers, id, &mut p).then_some(p)
}
+ /// [`Document::index_path`] of every id in `ids` that is in the tree, in one walk of it: an
+ /// edit of many objects looks them all up for the cost of one search instead of one each. Like
+ /// `index_path`, an id that appears twice maps to its first place in tree order.
+ pub fn index_paths(&self, ids: impl IntoIterator<Item = NodeId>) -> std::collections::HashMap<NodeId, Vec<usize>> {
+ use std::collections::{HashMap, HashSet};
+ fn walk(nodes: &[Arc<Node>], want: &HashSet<NodeId>, path: &mut Vec<usize>, out: &mut HashMap<NodeId, Vec<usize>>) -> bool {
+ for (i, n) in nodes.iter().enumerate() {
+ path.push(i);
+ if want.contains(&n.id) && !out.contains_key(&n.id) {
+ out.insert(n.id, path.clone());
+ if out.len() == want.len() {
+ return true;
+ }
+ }
+ if let Some(ch) = n.children()
+ && walk(ch, want, path, out)
+ {
+ return true;
+ }
+ path.pop();
+ }
+ false
+ }
+ let want: HashSet<NodeId> = ids.into_iter().collect();
+ let mut out = HashMap::with_capacity(want.len());
+ if !want.is_empty() {
+ walk(&self.layers, &want, &mut Vec::new(), &mut out);
+ }
+ out
+ }
+
+ /// The node at index path `path` (as [`Document::index_path`] gives it).
+ pub fn node_at(&self, path: &[usize]) -> Option<&Node> {
+ let (first, rest) = path.split_first()?;
+ let mut cur: &Node = self.layers.get(*first)?;
+ for &i in rest {
+ cur = cur.children()?.get(i)?;
+ }
+ Some(cur)
+ }
+
+ /// Mutable access to the node at index path `path`; clones the Arc path (copy-on-write), as
+ /// [`Document::node_mut`] does.
+ pub fn node_mut_at(&mut self, path: &[usize]) -> Option<&mut Node> {
+ let (first, rest) = path.split_first()?;
+ let mut cur: &mut Arc<Node> = self.layers.get_mut(*first)?;
+ for &i in rest {
+ cur = Arc::make_mut(cur).children_mut()?.get_mut(i)?;
+ }
+ Some(Arc::make_mut(cur))
+ }
+
+ /// [`Document::ancestry`] of the node at index path `path`.
+ pub fn ancestry_at(&self, path: &[usize]) -> Option<Vec<NodeId>> {
+ let mut out = Vec::with_capacity(path.len());
+ let mut nodes = &self.layers;
+ for &i in path {
+ let n = nodes.get(i)?;
+ out.push(n.id);
+ if let Some(ch) = n.children() {
+ nodes = ch;
+ }
+ }
+ Some(out)
+ }
+
/// Ids from the top-level layer down to `id` inclusive.
pub fn ancestry(&self, id: NodeId) -> Option<Vec<NodeId>> {
let path = self.index_path(id)?;
@@ -1391,6 +1457,8 @@ mod tests {
}
}
+#[cfg(test)]
+mod tests_lookups;
#[cfg(test)]
mod tests_slices;
#[cfg(test)]
diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs
index 2726d1490..d89144656 100644
--- a/crates/doc/src/selection.rs
+++ b/crates/doc/src/selection.rs
@@ -62,9 +62,9 @@ impl Selection {
}
pub fn set(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
- for id in ids {
- self.add(id);
- }
+ // What `add` per id does after a clear, without its linear duplicate check per id.
+ let mut seen = std::collections::HashSet::new();
+ self.objects.extend(ids.into_iter().filter(|id| seen.insert(*id)));
}
pub fn add(&mut self, id: NodeId) {
self.target = None;
@@ -118,10 +118,13 @@ impl Selection {
}
/// Drop ids that no longer exist or are no longer editable.
pub fn prune(&mut self, doc: &Document) {
- self.objects.retain(|id| doc.node(*id).is_some());
- self.anchors.retain(|id, _| doc.node(*id).is_some());
+ // Every id this looks up, found in one walk of the tree.
+ let ids = self.objects.iter().chain(self.anchors.keys()).copied().chain(self.key).chain(self.target);
+ let found = doc.index_paths(ids);
+ self.objects.retain(|id| found.contains_key(id));
+ self.anchors.retain(|id, _| found.contains_key(id));
// The key object stays while another selected object lies outside it.
- let keep = self.key.and_then(|k| doc.node(k)).is_some_and(|n| {
+ let keep = self.key.and_then(|k| found.get(&k)).and_then(|p| doc.node_at(p)).is_some_and(|n| {
let mut inside = BTreeSet::new();
n.walk(&mut |c| {
inside.insert(c.id);
@@ -131,7 +134,7 @@ impl Selection {
if !keep {
self.key = None;
}
- if self.target.is_some_and(|t| doc.node(t).is_none()) {
+ if self.target.is_some_and(|t| !found.contains_key(&t)) {
self.target = None;
}
self.slices.retain(|id| doc.is_slice(*id));
diff --git a/crates/doc/src/tests_lookups.rs b/crates/doc/src/tests_lookups.rs
new file mode 100644
index 000000000..3dff6215f
--- /dev/null
+++ b/crates/doc/src/tests_lookups.rs
@@ -0,0 +1,80 @@
+//! The batched lookups ([`Document::index_paths`], `node_at`, `node_mut_at`, `ancestry_at`) agree
+//! with the one-id ones on nested trees with missing and duplicated ids.
+use super::*;
+use vectorcraft_geom::shapes;
+
+/// Layers with paths and groups nested `depth` deep; every 7th id is reused (a damaged file), so
+/// first-in-tree-order matters.
+fn tree(seed: u64) -> (Document, Vec<NodeId>) {
+ let mut d = Document::new(612.0, 792.0);
+ let mut r = seed | 1;
+ let mut next = |n: u64| {
+ r ^= r << 13;
+ r ^= r >> 7;
+ r ^= r << 17;
+ r % n
+ };
+ let mut ids = vec![];
+ let leaf = |d: &mut Document, ids: &mut Vec<NodeId>| {
+ let id = if ids.len() % 7 == 6 { ids[ids.len() / 2] } else { d.alloc_id() };
+ ids.push(id);
+ Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
+ };
+ for l in 0..3 {
+ let lid = d.alloc_id();
+ let mut layer = Node::layer(lid, &format!("L{l}"), LayerColor::Preset(0));
+ ids.push(lid);
+ for _ in 0..(5 + next(10)) {
+ let child = if next(3) == 0 {
+ let mut inner: Vec<Arc<Node>> = (0..(1 + next(4))).map(|_| leaf(&mut d, &mut ids)).collect();
+ for _ in 0..next(3) {
+ let gid = d.alloc_id();
+ ids.push(gid);
+ inner = vec![Arc::new(Node::group(gid, inner))];
+ }
+ let gid = d.alloc_id();
+ ids.push(gid);
+ Arc::new(Node::group(gid, inner))
+ } else {
+ leaf(&mut d, &mut ids)
+ };
+ if let Some(ch) = layer.children_mut() {
+ ch.push(child);
+ }
+ }
+ d.layers.push(Arc::new(layer));
+ }
+ ids.push(NodeId(999_999)); // not in the tree
+ (d, ids)
+}
+
+#[test]
+fn batched_lookups_match_one_at_a_time() {
+ for seed in 1..40 {
+ let (d, ids) = tree(seed);
+ let paths = d.index_paths(ids.iter().copied());
+ for id in &ids {
+ assert_eq!(paths.get(id).cloned(), d.index_path(*id), "seed {seed} id {id:?}");
+ let p = paths.get(id);
+ assert_eq!(p.and_then(|p| d.node_at(p)).map(|n| n as *const Node), d.node(*id).map(|n| n as *const Node), "seed {seed} node {id:?}");
+ assert_eq!(p.and_then(|p| d.ancestry_at(p)), d.ancestry(*id), "seed {seed} ancestry {id:?}");
+ }
+ // A subset, and nothing.
+ let some: Vec<NodeId> = ids.iter().copied().step_by(3).collect();
+ let sub = d.index_paths(some.iter().copied());
+ assert!(some.iter().all(|id| sub.get(id).cloned() == d.index_path(*id)));
+ assert!(d.index_paths(std::iter::empty()).is_empty());
+ // Mutable access reaches the same node as node_mut, copy-on-write.
+ let mut a = d.clone();
+ let mut b = d.clone();
+ for id in ids.iter().step_by(5) {
+ if let Some(n) = a.node_mut(*id) {
+ n.opacity = 0.25;
+ }
+ if let Some(n) = d.index_path(*id).and_then(|p| b.node_mut_at(&p)) {
+ n.opacity = 0.25;
+ }
+ }
+ assert_eq!(serde_json::to_string(&a).ok(), serde_json::to_string(&b).ok(), "seed {seed}");
+ }
+}
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index e5e94c109..c6201b7b8 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -251,22 +251,29 @@ pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
/// The top-level objects among `ids` (in paint order): compound-path members stand for their
/// compound, and ids whose ancestor is also listed, and layers, are dropped.
pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
+ // Every id's place in the tree, found in one walk (a lookup per id is a walk per id).
+ let paths = doc.index_paths(ids.iter().copied());
// A compound-path member acts as its compound (compounds are one object).
- let mut sel: Vec<NodeId> = ids
+ let mut sel: Vec<(NodeId, Option<Vec<usize>>)> = ids
.into_iter()
- .map(|id| match doc.parent_of(id).and_then(|p| doc.node(p).map(|n| (p, n))) {
- Some((p, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) => p,
- _ => id,
+ .map(|id| {
+ let path = paths.get(&id);
+ let parent = path.and_then(|p| p.split_last()).map(|(_, up)| up).filter(|up| !up.is_empty());
+ match parent.and_then(|up| doc.node_at(up).map(|n| (up, n))) {
+ Some((up, n)) if matches!(n.kind, vectorcraft_doc::NodeKind::Compound { .. }) => (n.id, Some(up.to_vec())),
+ _ => (id, path.cloned()),
+ }
})
.collect();
- sel.dedup();
+ sel.dedup_by_key(|(id, _)| *id);
+ let listed: std::collections::HashSet<NodeId> = sel.iter().map(|(id, _)| *id).collect();
sel.iter()
- .copied()
- .filter(|id| {
- let anc = doc.ancestry(*id).unwrap_or_default();
- !anc[..anc.len().saturating_sub(1)].iter().any(|a| sel.contains(a))
+ .filter(|(_, path)| {
+ let anc = path.as_deref().and_then(|p| doc.ancestry_at(p)).unwrap_or_default();
+ !anc[..anc.len().saturating_sub(1)].iter().any(|a| listed.contains(a))
})
- .filter(|id| doc.node(*id).is_some_and(|n| !n.is_layer()))
+ .filter(|(_, path)| path.as_deref().and_then(|p| doc.node_at(p)).is_some_and(|n| !n.is_layer()))
+ .map(|(id, _)| *id)
.collect()
}
diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs
index ba3e580b7..5c75c1a98 100644
--- a/crates/engine/src/cmd/object.rs
+++ b/crates/engine/src/cmd/object.rs
@@ -242,7 +242,8 @@ pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) ->
let on = bool_or(p, "patterns", s.prefs.transform_pattern_tiles);
let d = &s.doc()?.doc;
let mut uses = false;
- for n in ids.iter().filter_map(|id| d.node(*id)) {
+ let paths = d.index_paths(ids.iter().copied());
+ for n in ids.iter().filter_map(|id| paths.get(id)).filter_map(|p| d.node_at(p)) {
n.walk(&mut |c| uses |= vectorcraft_doc::pattern::uses_pattern(c, None));
}
if uses {
@@ -263,14 +264,16 @@ pub(crate) fn apply_transform(s: &mut Session, label: &str, ids: Vec<NodeId>, xf
// nothing: the document and its undo history stay as they are, and Transform Again repeats it.
// With a copy, the reply lists the copies, and there are none.
let d = &s.doc()?.doc;
- let none = ids.iter().all(|id| d.node(*id).is_none());
+ let none = d.index_paths(ids.iter().copied()).is_empty();
let ids = if none || (!copy && xf == Affine::IDENTITY) {
if copy { vec![] } else { ids }
} else {
s.edit(label, |d, sel| {
let targets = if copy { duplicate_in(d, sel, &ids, Affine::IDENTITY)? } else { ids.clone() };
+ // Transforms don't move nodes in the tree, so the paths found up front stay right.
+ let paths = d.index_paths(targets.iter().copied());
for id in &targets {
- if let Some(n) = d.node_mut(*id)
+ if let Some(n) = paths.get(id).and_then(|p| d.node_mut_at(p))
&& !(areas && resize_type_area(n, xf))
{
n.transform(xf, sc);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index f3041d6cb..fc819f783 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -421,9 +421,10 @@ fn strip_replay_only(id: &str, p: &mut Value) {
/// have finite, in-range geometry, so saved files always reload and renderers never see NaN/∞.
fn doc_sane(d: &Document, sel: &Selection) -> bool {
let ok = |r: vectorcraft_geom::Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD);
- d.artboards.iter().all(|a| ok(a.rect))
- && d.guides.iter().all(|g| g.pos.is_finite() && g.pos.abs() <= MAX_COORD)
- && sel.objects.iter().all(|id| d.node(*id).and_then(|n| n.geometric_bounds()).is_none_or(ok))
+ d.artboards.iter().all(|a| ok(a.rect)) && d.guides.iter().all(|g| g.pos.is_finite() && g.pos.abs() <= MAX_COORD) && {
+ let paths = d.index_paths(sel.objects.iter().copied());
+ sel.objects.iter().all(|id| paths.get(id).and_then(|p| d.node_at(p)).and_then(|n| n.geometric_bounds()).is_none_or(ok))
+ }
}
/// Where new art goes (Illustrator's drawing modes, Shift+D cycles).