diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 9c25427846..0ee84dc32c 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -187,8 +187,9 @@ impl Document { /// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint /// visited once even when an id is inside another). pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize { + let listed: HashSet = ids.iter().copied().collect(); let roots: Vec = - ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect(); let mut n = 0; let mut g = relink(f); for id in roots { @@ -844,6 +845,77 @@ mod tests { assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + /// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set. + fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize { + let roots: Vec = + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + let mut n = 0; + let mut g = relink(f); + for id in roots { + let Some(node) = d.node(id) else { continue }; + if let Some((new, count)) = map_node(node, &mut g) + && let Some(slot) = d.node_mut(id) + { + *slot = new; + n += count; + } + } + n + } + + #[test] + fn mapping_within_ids_matches_a_search_of_the_ids() { + // Two layers: the first holds group `outer` (group `inner` with two rectangles, and a + // rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color. + let mut d = Document::new(100.0, 100.0); + let first = d.layers[0].id; + let second = d.alloc_id(); + d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap(); + let rect = |d: &mut Document, i: u8| { + let id = d.alloc_id(); + let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0); + (id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0)))) + }; + let (r1, n1) = rect(&mut d, 1); + let (r2, n2) = rect(&mut d, 2); + let (r3, n3) = rect(&mut d, 3); + let (r4, n4) = rect(&mut d, 4); + let (r5, n5) = rect(&mut d, 5); + let (inner, outer) = (d.alloc_id(), d.alloc_id()); + let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]); + d.insert(Some(first), usize::MAX, outer_node).unwrap(); + d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap(); + d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap(); + let missing = NodeId(u64::MAX); + let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing]; + // Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none. + let mut lists: Vec> = vec![vec![]]; + let mut shorter: Vec> = vec![vec![]]; + for _ in 0..3 { + shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect(); + lists.extend(shorter.iter().cloned()); + } + assert_eq!(lists.len(), 1 + 10 + 100 + 1000); + for ids in &lists { + // A callback that changes every paint it visits, so a paint visited twice counts twice. + let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| { + let mut d = d.clone(); + let mut visits = vec![]; + let n = map(&mut d, ids, &mut |c, s, t| { + visits.push((*c, s.clone(), *t)); + *s = Some(format!("{}", visits.len())); + *t *= 0.5; + true + }); + (n, visits, d.layers) + }; + let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f)); + let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f)); + assert_eq!(by_set, by_search, "{ids:?}"); + } + } + /// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree. fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { n.walk(&mut |m| { diff --git a/crates/engine/examples/link_colors_bench.rs b/crates/engine/examples/link_colors_bench.rs new file mode 100644 index 0000000000..d403339706 --- /dev/null +++ b/crates/engine/examples/link_colors_bench.rs @@ -0,0 +1,217 @@ +//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time +//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used +//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and +//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and +//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to. +//! For each it times two ways of finding the selected objects that no other selected object holds: a +//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids +//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both +//! give the same count, visit the same paints in the same order and leave the same document as +//! `map_solid_paints_in` before it times them. +//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10 +//! fresh copies of the document, and each row is the median time of one call. 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::collections::{HashMap, HashSet}; +use std::hint::black_box; +use std::sync::Arc; +use std::time::Instant; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Rect, shapes}; + +/// The colors the rectangles use, each with a swatch to link to. +const COLORS: usize = 50; + +/// The calls in each timed run; a row gives the time of one call. +const REPS: usize = 10; + +/// A way of finding the ids that no other listed id holds. +type Roots = fn(&Document, &[NodeId]) -> Vec; + +/// A way of applying a link function to the paints of the listed ids, returning the count changed. +type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a; + +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 + } + } +} + +/// Color `i` of [`COLORS`]: each has its own red value. +fn color(i: usize) -> Color { + Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25) +} + +/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models. +fn red_bits(c: &Color) -> u32 { + match c { + Color::Rgb { r, .. } => r.to_bits(), + _ => u32::MAX, + } +} + +/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor. +fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect() +} + +/// [`roots_by_search`] with each ancestor looked up in a set of the ids. +fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec { + let listed: HashSet = ids.iter().copied().collect(); + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect() +} + +/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed +/// paint put in place: the work of `map_solid_paints_in`. +fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize { + let mut n = 0; + for id in roots(d, ids) { + let Some(mut node) = d.node(id).cloned() else { continue }; + let count = map_node_solid_paints(&mut node, f); + if count > 0 + && let Some(slot) = d.node_mut(id) + { + *slot = node; + n += count; + } + } + n +} + +/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global +/// swatches, recording each paint visited. Returns the count and the visits. +fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option)>) { + let names: HashMap = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect(); + let mut visits = vec![]; + let n = map(d, ids, &mut |c, s, _| { + visits.push((*c, s.clone())); + match names.get(&red_bits(c)) { + Some(name) if s.is_none() => { + *s = Some(name.clone()); + true + } + _ => false, + } + }); + (n, visits) +} + +fn rect(d: &mut Document, i: usize) -> Arc { + let id = d.alloc_id(); + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)); + let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0); + Arc::new(Node::path(id, r, a)) +} + +/// `n` rectangles in the first layer, all selected. +fn flat(n: usize) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for i in 0..n { + let node = rect(&mut d, i); + ids.push(node.id); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap(); + } + (d, ids) +} + +/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with +/// `groups` the two groups above each of them too, listed first. +fn nested(groups: bool) -> (Document, Vec) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let (mut outer_ids, mut leaves) = (vec![], vec![]); + for g in 0..1_000 { + let rects: Vec> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect(); + leaves.extend(rects.iter().map(|r| r.id)); + let inner = Node::group(d.alloc_id(), rects); + let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]); + if groups { + outer_ids.extend([outer.id, inner.id]); + } + d.insert(Some(l), usize::MAX, outer).unwrap(); + } + outer_ids.extend(leaves); + (d, outer_ids) +} + +fn bench(name: &str, (doc, ids): (Document, Vec)) { + let mut shipped = doc.clone(); + let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f)); + for roots in [roots_by_search as Roots, roots_by_set] { + let mut d = doc.clone(); + let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f)); + assert_eq!(got, want, "{name}: the same count and visits"); + assert_eq!(d.layers, shipped.layers, "{name}: the same document"); + } + let (mut old, mut new, mut real) = (vec![], vec![], vec![]); + let timed = |map: &mut Map| { + let mut docs = vec![doc.clone(); REPS]; + measure(|| { + for d in &mut docs { + black_box(link(d, black_box(&ids), &mut *map)); + } + }) / REPS as f64 + }; + for i in 0..iters() { + let run = |roots: Roots, out: &mut Vec| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f))); + if i % 2 == 0 { + run(roots_by_search, &mut old); + run(roots_by_set, &mut new); + } else { + run(roots_by_set, &mut new); + run(roots_by_search, &mut old); + } + real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f))); + } + let (old, new, real) = (median(old), median(new), median(real)); + println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new); +} + +fn main() { + let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" }; + println!( + " {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}", + "document", + "ids", + "linked", + format!("search, {unit}"), + format!("set, {unit}"), + format!("shipped, {unit}"), + "speedup" + ); + bench("2,000 rectangles in one layer", flat(2_000)); + bench("20,000 rectangles in one layer", flat(20_000)); + bench("5,000 rectangles in 1,000 groups of groups", nested(false)); + bench("the same with the 2,000 groups listed first", nested(true)); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..cbc0446812 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1726,6 +1726,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. + When Add Used Colors and New Color Group link the selected art's paints to global swatches, they look each selected object's groups and layer up in a set of the selected ids instead of searching the whole selection for each one, so linking 20,000 selected rectangles takes 16 ms of CPU time instead of 128 ms (`cargo run --release -p vectorcraft-engine --example link_colors_bench`). The same paints are linked, in the same order. Evidence: `mapping_within_ids_matches_a_search_of_the_ids` in `crates/doc/src/swatches.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels.