diff --git a/Cargo.lock b/Cargo.lock index 4f74f10fc4..7f6a975bae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1206,7 +1206,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1239,6 +1239,15 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "craft-ps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=a80c0f25f1c4767374a27a444fbf95e3e8162e14#a80c0f25f1c4767374a27a444fbf95e3e8162e14" +dependencies = [ + "flate2", + "kurbo 0.13.1", +] + [[package]] name = "craft-psd" version = "0.1.0" @@ -1253,7 +1262,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "fax", "hayro-ccitt", @@ -2507,7 +2516,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "brotli", "hayro-postscript", @@ -2516,7 +2525,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2534,7 +2543,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2552,12 +2561,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "flate2", "hayro-ccitt", @@ -3357,7 +3366,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3466,7 +3475,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd#a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" +source = "git+https://github.com/storytold/craft-libs?rev=0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e#0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6856,6 +6865,7 @@ dependencies = [ "craft-eps", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", "craft-pdf", + "craft-ps", "craft-stream-codecs", "encoding_rs", "fax", diff --git a/Cargo.toml b/Cargo.toml index 89d6328ea7..53f5ee619b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", default-features = false, features = ["interpret", "write"] } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["serde"] } @@ -38,8 +38,9 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a499742a93 craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a80c0f25f1c4767374a27a444fbf95e3e8162e14", default-features = false, features = ["write"] } craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd", features = ["egui"] } # internal @@ -181,13 +182,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "0cca4ac66f9f4576b3acc5f84d7a2a2ae9fb943e" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index 996c963c11..9be00b4b21 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -192,14 +192,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { // A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops // are written mirrored about the seam instead. let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored()); - let stop = |s: &crate::GradientStop| { - let at = if mirrored { 1.0 - s.offset } else { s.offset }; - format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0) + let stop = |&(t, c, o): &(f32, Color, f32)| { + let at = if mirrored { 1.0 - t } else { t }; + format!("{} {}%", css_color(&c, o), at * 100.0) }; - // Stops that repeat or reflect run that many times across the box. + // Stops that repeat or reflect run that many times across the box. CSS mixes + // hex colors evenly in sRGB between two stops + // (https://www.w3.org/TR/css-color-4/#interpolation-space), so an off-center + // midpoint and the curve of a Perceptual or hue gradient are written as stops + // of their own, each with its color and opacity. A gradient that would need + // more than `MAX_SPREAD_STOPS` stops that way is written with its own stops. let unrolled = g.gradient.unrolled(); - let stops: Vec = - if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() }; + let expanded: Vec<(f32, Color, f32)> = if unrolled.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_none() { + unrolled.expanded_stops() + } else { + unrolled.stops.iter().map(|s| (s.offset, s.color, s.opacity)).collect() + }; + let stops: Vec = if mirrored { expanded.iter().rev().map(stop).collect() } else { expanded.iter().map(stop).collect() }; match g.gradient.kind { GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")), // CSS sweeps clockwise from straight up; the angle is counted counterclockwise diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index f3de69baf9..bbbae16a53 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -284,6 +284,99 @@ fn css_writes_spread_gradient_swatches_with_their_stops_repeated() { } } +/// The color and opacity a written CSS gradient value has at `p` (0..1 along its stops), by the +/// CSS rule (https://www.w3.org/TR/css-images-3/#coloring-gradient-line): between two stops the +/// color mixes evenly with premultiplied alpha, in sRGB for hex colors +/// (https://www.w3.org/TR/css-color-4/#interpolation-space); before the first stop and after the +/// last the end colors hold. +fn css_gradient_at(value: &str, p: f64) -> ([f64; 3], f64) { + let list = value.split_once(", ").map_or("", |(_, rest)| rest).trim_end_matches(')'); + let stops: Vec<([f64; 3], f64, f64)> = list + .split(", ") + .map(|stop| { + let (hex, at) = stop.split_once(' ').unwrap_or_else(|| panic!("stop {stop:?}")); + let byte = |i: usize| hex.get(1 + 2 * i..3 + 2 * i).map_or(255.0, |h| f64::from(u8::from_str_radix(h, 16).unwrap())); + let at: f64 = at.trim_end_matches('%').parse().unwrap(); + ([byte(0), byte(1), byte(2)].map(|v| v / 255.0), byte(3) / 255.0, at / 100.0) + }) + .collect(); + let p = p.clamp(stops[0].2, stops[stops.len() - 1].2); + let i = stops.windows(2).position(|w| p <= w[1].2).unwrap_or(0); + let ((c0, a0, p0), (c1, a1, p1)) = (stops[i], stops[i + 1]); + let w = if p1 > p0 { (p - p0) / (p1 - p0) } else { 1.0 }; + let a = a0 + (a1 - a0) * w; + let c = std::array::from_fn(|k| if a > 0.0 { (c0[k] * a0 + (c1[k] * a1 - c0[k] * a0) * w) / a } else { 0.0 }); + (c, a) +} + +/// A gradient swatch's CSS draws, by the CSS rule, the colors and opacity the swatch has: an +/// off-center midpoint and the curve of a Perceptual or hue gradient are written as stops of their +/// own, also on a reflected and a mirrored conic swatch. +#[test] +fn css_gradient_swatches_draw_their_midpoints_and_curves() { + let check = |label: &str, gp: GradientPaint, at: &dyn Fn(f64) -> f64| { + let lib = SwatchLibrary { + name: "x".into(), + swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(gp.clone())), global: false, spot: false }], + groups: vec![], + }; + let text = written(&lib, PaletteFormat::Css); + let value = text.lines().find_map(|l| l.trim().strip_prefix("--x: ")).unwrap_or_else(|| panic!("{text}")).trim_end_matches(';'); + for i in 0..64 { + let p = (f64::from(i) + 0.5) / 64.0; + let (css, css_alpha) = css_gradient_at(value, p); + let (color, opacity) = gp.gradient.sample(at(p) as f32); + let want = color.to_rgb(); + let off = (0..3).map(|k| (css[k] - f64::from(want[k])).abs()).fold((css_alpha - f64::from(opacity)).abs(), f64::max); + assert!(off < 2.0 / 255.0, "{label} at {p}: {css:?} {css_alpha} vs {want:?} {opacity}: {value}"); + } + }; + let ramp = |method| Gradient { + method, + ..Gradient::new( + GradientKind::Linear, + vec![GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::rgb8(255, 0, 0)) }, GradientStop::new(1.0, Color::rgb8(0, 0, 255))], + ) + }; + for method in crate::GradientMethod::ALL { + check(&format!("{method:?}"), GradientPaint::new(ramp(method)), &|p| p); + } + // Opacity through an off-center midpoint, on one color so premultiplying does not change it. + let fade = Gradient::new( + GradientKind::Linear, + vec![ + GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::BLACK) }, + GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) }, + ], + ); + check("fade", GradientPaint::new(fade), &|p| p); + let reflected = Gradient { spread: crate::GradientSpread::Reflect, repeats: 2, ..ramp(crate::GradientMethod::Classic) }; + let spread = reflected.spreader(); + check("reflect", GradientPaint::new(reflected), &spread); + let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..ramp(crate::GradientMethod::HueClockwise) }); + conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None }); + check("mirrored conic", conic, &|p| 1.0 - p); +} + +/// A gradient swatch whose curve would need more than `MAX_SPREAD_STOPS` stops is written with its +/// own stops. +#[test] +fn css_gradient_swatches_keep_their_stop_count_bounded() { + let n = 4000; + let stops = (0..n) + .map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 255, 255) })) + .collect(); + let g = Gradient { method: crate::GradientMethod::HueClockwise, ..Gradient::new(GradientKind::Linear, stops) }; + assert!(g.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_some(), "the curve needs more stops than allowed"); + let lib = SwatchLibrary { + name: "x".into(), + swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(GradientPaint::new(g))), global: false, spot: false }], + groups: vec![], + }; + let text = written(&lib, PaletteFormat::Css); + assert_eq!(text.matches('%').count(), n, "one stop for each of the gradient's own"); +} + #[test] fn holds_counts_the_swatches_each_format_writes() { // `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group. diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 54130788e1..f4a307cd5c 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -752,6 +752,18 @@ impl Document { /// [`Document::locked_artboards`] leaving out artboard `index`. pub fn locked_artboards_except(&self, index: usize) -> LockedArtboards<'_> { + self.locks_except(index, false) + } + + /// [`Document::locked_artboards`] starting with the symbol art boxes earlier hit tests kept + /// ([`Document::kept_symbol_boxes`]). Kept boxes made after it keep its measurements too + /// ([`crate::symbols::KeptBoxes::keeping`]). + pub(crate) fn locked_artboards_kept(&self) -> LockedArtboards<'_> { + self.locks_except(usize::MAX, true) + } + + /// [`Document::locked_artboards_except`], with `kept` measuring with kept art boxes. + fn locks_except(&self, index: usize, kept: bool) -> LockedArtboards<'_> { // Art flush with an edge from outside can overlap it by a rounding error, as in // `art_bounds_on` (#1295). let rects: Vec = @@ -770,7 +782,9 @@ impl Document { if let Some(layer) = self.pattern_edit.as_ref().filter(|_| !rects.is_empty()).and_then(|e| self.layers.iter().find(|l| l.id == e.layer)) { objects(layer, &mut pattern_art); } - LockedArtboards { rects, symbols: self.symbol_boxes(), new_art: self.new_art.get(), pattern_art, held: Default::default() } + // Nothing is measured without a locked artboard. + let symbols = if kept && !rects.is_empty() { self.symbol_boxes_from_kept() } else { self.symbol_boxes() }; + LockedArtboards { rects, symbols, new_art: self.new_art.get(), pattern_art, held: Default::default() } } /// Is `id` on a locked artboard ([`LockedArtboards::holds_id`])? A layer or sublayer is on none. diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index ab571e50b2..3b415ef1ed 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -451,8 +451,9 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip /// outline, as a click there hits it. pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option { let _walk = ArtWalk::open(); - let symbols = doc.symbol_boxes(); - let locks = doc.locked_artboards(); + // The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs. + let locks = doc.locked_artboards_kept(); + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); selected.iter().rev().copied().find(|&id| { let Some(chain) = doc.ancestry(id) else { return false }; let nodes: Vec<&Node> = chain.iter().filter_map(|a| doc.node(*a)).collect(); @@ -520,7 +521,9 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option Vec { let _walk = ArtWalk::open(); - let symbols = doc.symbol_boxes(); + let symbols = doc.kept_symbol_boxes(); let mut out = Vec::new(); if let Some(scope) = opt.scope && let Some(isolated) = doc.node(scope) @@ -725,7 +727,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count(); h }; - let locks = doc.locked_artboards(); + let locks = doc.locked_artboards_kept(); let on_locked = |id: NodeId| { editable_only && !locks.is_empty() @@ -733,7 +735,8 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No && doc.node(id).is_some_and(|n| locks.holds(n)) }; let skip = &|id| skip(id) || on_locked(id); - let symbols = doc.symbol_boxes(); + // `locks` copies the kept art boxes that `symbols` takes, and `symbols` keeps theirs. + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); // Isolation mode: only what is inside the isolated container hits. The art around it is // locked, and clicks pass through it (#833). if editable_only @@ -801,6 +804,12 @@ pub fn set_clip_region(f: ClipRegion) { let _ = CLIP_REGION.set(f); } +/// What the regions of clipping paths with live effects depend on outside the document: the +/// registered [`LiveInputs`] now, and whether a [`ClipRegion`] is registered. +pub(crate) fn clip_region_inputs() -> (u64, bool) { + (live_inputs(), CLIP_REGION.get().is_some()) +} + /// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only /// then can the registered [`ClipRegion`] find a geometry effect in it. fn has_effects(clip: &Node) -> bool { @@ -1620,7 +1629,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { let _walk = ArtWalk::open(); let art = InstanceArt::of(doc, inst)?; - let symbols = doc.symbol_boxes(); + let symbols = doc.kept_symbol_boxes(); let mut path = vec![]; let outline = opt.outline || below_preview_off(doc, inst, opt.scope); let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false }; @@ -2042,7 +2051,9 @@ fn previews_off(n: &Node) -> bool { fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { let _walk = ArtWalk::open(); let mut out = Vec::new(); - let symbols = doc.symbol_boxes(); + // The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs. + let locks = doc.locked_artboards_kept(); + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); // The objects the marquee may touch ([`Top`]). let tops: Vec = match scope.and_then(|s| doc.node(s)) { // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the @@ -2284,7 +2295,6 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } } } - let locks = doc.locked_artboards(); for (t, r, outline, edge, drawn) in tops { if !t.visible || t.locked || locks.holds_id(t.id) { continue; diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index cd4798c76c..a616080bce 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -608,6 +608,18 @@ impl Node { } } + /// [`Self::walk`] that ends at the first node for which `f` returns [`std::ops::ControlFlow::Break`]: no + /// node after it is visited, and the break is returned. + pub fn try_walk<'a, B>(&'a self, f: &mut impl FnMut(&'a Node) -> std::ops::ControlFlow) -> std::ops::ControlFlow { + f(self)?; + if let Some(ch) = self.children() { + for c in ch { + c.try_walk(f)?; + } + } + std::ops::ControlFlow::Continue(()) + } + /// Count of nodes in this subtree, ruler guides left out. pub fn count(&self) -> usize { let mut n = 0; diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index db21762f61..789e0f66b2 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -805,3 +805,31 @@ fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() { assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice)); assert_eq!(calls, 0); } + +/// `try_walk` visits in `walk`'s order and visits nothing after the node that breaks it: not its +/// children, its later siblings or its ancestors' later siblings. +#[test] +fn try_walk_ends_at_the_break() { + use std::ops::ControlFlow; + let leaf = |id| Arc::new(Node::group(NodeId(id), vec![])); + let inner = Node::group(NodeId(2), vec![leaf(3), leaf(4), leaf(5)]); + let root = Node::group(NodeId(1), vec![Arc::new(inner), leaf(6), leaf(7)]); + let mut all = vec![]; + root.walk(&mut |n| all.push(n.id)); + let mut seen = vec![]; + assert_eq!( + root.try_walk(&mut |n| { + seen.push(n.id); + ControlFlow::<()>::Continue(()) + }), + ControlFlow::Continue(()) + ); + assert_eq!(seen, all, "without a break it visits what walk visits, in the same order"); + seen.clear(); + let flow = root.try_walk(&mut |n| { + seen.push(n.id); + if n.id == NodeId(3) { ControlFlow::Break(n.id) } else { ControlFlow::Continue(()) } + }); + assert_eq!(flow, ControlFlow::Break(NodeId(3))); + assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]); +} diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index b6090f8993..db8e6f930c 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -45,6 +45,32 @@ fn remove_all_does_what_removing_each_does() { assert_eq!(none, s); } +#[test] +fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() { + for kept in [false, true] { + let mut s = Selection::default(); + for i in 1..=4 { + s.add(NodeId(i)); + } + s.anchors.insert(NodeId(2), BTreeSet::from([(0, 0), (0, 1)])); + s.anchors.insert(NodeId(3), BTreeSet::from([(0, 2)])); + s.key_anchor = Some((NodeId(2), (0, 0))); + s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] }); + s.guides = vec![NodeId(10)]; + s.key_guide = Some(NodeId(10)); + let ids = if kept { [NodeId(3), NodeId(8), NodeId(3)] } else { [NodeId(2), NodeId(8), NodeId(2)] }; + let mut one_by_one = s.clone(); + for id in ids { + one_by_one.remove(id); + } + let mut all = s.clone(); + all.remove_all(ids); + assert_eq!(all, one_by_one); + assert_eq!(all.key_anchor.is_some(), kept); + assert_eq!((all.symbol_part.clone(), all.guides.clone(), all.key_guide), (None, vec![NodeId(10)], Some(NodeId(10)))); + } +} + #[test] fn guides_are_selected_on_their_own() { let mut s = Selection::default(); diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 6d2c14a102..9c25427846 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -8,6 +8,7 @@ //! change; [`Document::map_paints`] replaces whole paints of any kind in the same places. use std::collections::{HashMap, HashSet}; +use std::ops::ControlFlow; use std::sync::Arc; use vectorcraft_color::swatch::REGISTRATION; @@ -340,18 +341,39 @@ fn map_style_paint(attrs: &mut serde_json::Map, key: /// and gradient stops (with their link), a dynamic symbol instance's own paints /// ([`override_paints`]), then mesh points (unlinked), in paint order. pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { - n.walk(&mut |m| { + let _ = try_node_colors::<()>(n, &mut |c, s| { + f(c, s); + ControlFlow::Continue(()) + }); +} + +/// Whether the subtree of `n` holds any color [`node_colors`] visits. It stops at the first one. +pub fn node_has_colors(n: &Node) -> bool { + try_node_colors(n, &mut |_, _| ControlFlow::Break(())).is_break() +} + +/// [`node_colors`] that ends at the first color for which `f` returns [`ControlFlow::Break`]: no +/// paint or node after it is visited. +fn try_node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>) -> ControlFlow) -> ControlFlow { + n.try_walk(&mut |m| { for p in node_paints(m).chain(override_paints(m)) { match p { - Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()), - Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())), + Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref())?, + Paint::Gradient(g) => { + for s in &g.gradient.stops { + f(&s.color, s.swatch.as_deref())?; + } + } _ => {} } } if let NodeKind::Mesh(mesh) = &m.kind { - mesh.points.iter().for_each(|p| f(&p.color, None)); + for p in &mesh.points { + f(&p.color, None)?; + } } - }); + ControlFlow::Continue(()) + }) } fn item_paint(it: &AppearanceItem) -> &Paint { @@ -821,4 +843,216 @@ mod tests { node_colors(d.node(b).unwrap(), &mut |c, s| colors.push((*c, s.map(str::to_string)))); assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + + /// 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| { + for p in node_paints(m).chain(override_paints(m)) { + match p { + Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()), + Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())), + _ => {} + } + } + if let NodeKind::Mesh(mesh) = &m.kind { + mesh.points.iter().for_each(|p| f(&p.color, None)); + } + }); + } + + /// Whether [`full_walk`] finds a color in `n`. + fn full_walk_has_colors(n: &Node) -> bool { + let mut found = false; + full_walk(n, &mut |_, _| found = true); + found + } + + /// The colors of `n` by [`full_walk`], in order. + fn full_walk_colors(n: &Node) -> Vec<(Color, Option)> { + let mut out = vec![]; + full_walk(n, &mut |c, s| out.push((*c, s.map(str::to_string)))); + out + } + + fn square(id: u64, fill: Paint, stroke: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, stroke, 1.0)) + } + + fn holder(id: u64, kind: fn(Vec>) -> NodeKind, children: Vec) -> Node { + Node::new(NodeId(id), kind(children.into_iter().map(Arc::new).collect())) + } + + /// One node of each kind of paint [`node_colors`] reads or skips, with whether it shows a color. + fn color_cases() -> Vec<(&'static str, Node, bool)> { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let gradient = |stops: usize| { + let mut g = vectorcraft_color::Gradient::default(); + g.stops.truncate(stops); + Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g))) + }; + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY }; + let area = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let mesh = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap(); + let mut empty_mesh = mesh.clone(); + empty_mesh.points.clear(); + let text = |fill: Paint| { + let style = crate::CharStyle { fill, stroke: Paint::None, ..Default::default() }; + let mut n = + Node::new(NodeId(20), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Hi", style)))); + n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + n + }; + let image = |colorize: Option| { + let im = crate::ImageObject { + key: "k".into(), + width: 2, + height: 2, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(NodeId(21), NodeKind::Image(Box::new(im))); + n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + n.extras_mut().colorize = colorize.map(Box::new); + n + }; + let overridden = |fill: Option| { + let mut n = square(22, Paint::None, Paint::None); + n.extras_mut().symbol_overrides = vec![crate::SymbolOverride { path: vec![0], fill, ..Default::default() }]; + n + }; + let masked = { + let mut n = square(23, Paint::None, Paint::None); + n.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(square(24, red.clone(), Paint::None), true))); + n + }; + let group = |children| NodeKind::Group { children, clip: false }; + let clip = |children| NodeKind::Group { children, clip: true }; + let compound = |children| NodeKind::Compound { children, rule: Default::default() }; + let blend = |children| NodeKind::Blend { children, spec: Default::default() }; + let blank = |id| square(id, Paint::None, Paint::None); + vec![ + ("no paint", blank(1), false), + ("solid fill", square(2, red.clone(), Paint::None), true), + ("solid stroke", square(3, Paint::None, red.clone()), true), + ("pattern only", square(4, pattern.clone(), pattern.clone()), false), + ("gradient without stops", square(5, gradient(0), Paint::None), false), + ("gradient with stops", square(6, gradient(2), Paint::None), true), + ("mesh with points", Node::new(NodeId(7), NodeKind::Mesh(mesh)), true), + ("mesh without points", Node::new(NodeId(8), NodeKind::Mesh(empty_mesh)), false), + ("text run fill", text(red.clone()), true), + ("text without paint", text(Paint::None), false), + ("image colorize", image(Some(red.clone())), true), + ("image without colorize", image(None), false), + ("image with a pattern colorize", image(Some(pattern.clone())), false), + ("symbol override fill", overridden(Some(red.clone())), true), + ("symbol override without paint", overridden(None), false), + ("color only in the opacity mask", masked, false), + ("group, color first", holder(30, group, vec![square(31, red.clone(), Paint::None), blank(32), blank(33)]), true), + ("group, color last", holder(34, group, vec![blank(35), blank(36), square(37, red.clone(), Paint::None)]), true), + ("group without color", holder(38, group, vec![blank(39), blank(40)]), false), + ("clip group", holder(41, clip, vec![blank(42), square(43, red.clone(), Paint::None)]), true), + ("compound shape", holder(44, compound, vec![blank(45), square(46, gradient(3), Paint::None)]), true), + ("blend", holder(47, blend, vec![blank(48), blank(49)]), false), + ( + "nested groups, color deepest", + holder(50, group, vec![blank(51), holder(52, group, vec![holder(53, group, vec![blank(54), square(55, red.clone(), Paint::None)])])]), + true, + ), + ] + } + + #[test] + fn has_colors_matches_the_full_walk() { + for (label, n, expected) in color_cases() { + let all = full_walk_colors(&n); + assert_eq!(node_has_colors(&n), full_walk_has_colors(&n), "{label}"); + assert_eq!(full_walk_has_colors(&n), !all.is_empty(), "{label}"); + assert_eq!(node_has_colors(&n), expected, "{label}"); + let mut listed = vec![]; + node_colors(&n, &mut |c, s| listed.push((*c, s.map(str::to_string)))); + assert_eq!(listed, all, "{label}: node_colors lists the same colors in the same order"); + } + } + + #[test] + fn has_colors_stops_at_the_first_color() { + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let mut stops = vectorcraft_color::Gradient::default(); + stops.stops.push(stops.stops[0].clone()); + let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(stops))); + let mut later = vec![square(2, gradient, red.clone())]; + later.extend((3..100).map(|id| square(id, red.clone(), red.clone()))); + let n = holder(1, |children| NodeKind::Group { children, clip: false }, later); + let (mut colors, mut nodes) = (0, 0); + let flow = try_node_colors(&n, &mut |_, _| { + colors += 1; + ControlFlow::Break(()) + }); + assert!(flow.is_break()); + assert_eq!(colors, 1, "the first gradient stop ends the walk: no later stop, stroke or object is read"); + let flow = n.try_walk(&mut |m| { + nodes += 1; + if node_paints(m).next().is_some() { ControlFlow::Break(()) } else { ControlFlow::Continue(()) } + }); + assert!(flow.is_break()); + assert_eq!(nodes, 2, "the group, then its first member: none of the 97 after it"); + } + + /// Times [`node_has_colors`] against the full walk it replaces on one group of 100,000 paths, alternating the two in + /// one process: `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture has_colors_timing`. + #[test] + #[ignore = "a timing, not a check"] + fn has_colors_timing() { + /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere. + fn clock(start: std::time::Instant) -> u128 { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos()) + } + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let count = 100_000u64; + let group = |colored: &dyn Fn(u64) -> bool| { + let children = + (0..count).map(|i| if colored(i) { square(i + 1, red.clone(), Paint::None) } else { square(i + 1, Paint::None, Paint::None) }); + holder(0, |children| NodeKind::Group { children, clip: false }, children.collect()) + }; + let cases = [ + ("every path filled", group(&|_| true)), + ("only the last path filled", group(&|i| i == count - 1)), + ("no path filled", group(&|_| false)), + ]; + let start = std::time::Instant::now(); + println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" }); + // The time per call of `f` on `n`: batches of calls double until one takes at least 100 ms. + let per_call = |f: fn(&Node) -> bool, n: &Node| { + let mut calls = 1u32; + loop { + let t = clock(start); + for _ in 0..calls { + std::hint::black_box(f(std::hint::black_box(n))); + } + let spent = clock(start) - t; + if spent >= 100_000_000 || calls >= 1 << 30 { + return (spent as f64 / f64::from(calls), calls); + } + calls *= 2; + } + }; + for (label, n) in &cases { + assert_eq!(full_walk_has_colors(n), node_has_colors(n), "{label}"); + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + old.push(per_call(full_walk_has_colors, n)); + new.push(per_call(node_has_colors, n)); + } + old.sort_by(|a, b| a.0.total_cmp(&b.0)); + new.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (o, nw) = (old[3], new[3]); + println!( + "{label}: full walk {:.1} ns per call ({} calls), node_has_colors {:.1} ns per call ({} calls), median of 7 runs", + o.0, o.1, nw.0, nw.1 + ); + } + } } diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 99a65ae1f7..a1d34e6adb 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -107,6 +107,134 @@ pub struct SymbolBoxes<'a> { consulted: RefCell>>, } +/// What the art boxes and nesting depths of a document's symbols depend on: each symbol's name and +/// art, the symbols' 9-slice guides (which symbols' art holds instances placed through guides), and +/// the inputs of the live geometry effects of clipping paths ([`crate::hit::set_clip_region`]). +/// Symbol sizes only move art placed through guides, which is measured on each call. Each symbol's +/// art is held by a weak pointer. While a weak pointer to an art's allocation is held, nothing else +/// can be at that address, and the art can't be changed in place (`Arc::make_mut` moves it), so art +/// changed in any way no longer matches, as in the cache of `Document::inline_cycles`. +struct KeptKey { + symbols: Vec<(String, std::sync::Weak)>, + guides: Option, + inputs: (u64, bool), +} + +impl KeptKey { + /// The key of the document's 9-slice guides. + const GUIDES: &str = crate::symbol_nine_slice::SYMBOL_NINE_SLICE; + + fn of(doc: &Document, inputs: (u64, bool)) -> Self { + KeptKey { + symbols: doc.symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(), + guides: doc.unknown.get(Self::GUIDES).cloned(), + inputs, + } + } + + /// Does this describe `doc`'s symbols as they are now, with inputs `inputs`? + fn is_of(&self, doc: &Document, inputs: (u64, bool)) -> bool { + self.inputs == inputs + && self.symbols.len() == doc.symbols.len() + && self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)) && *name == s.name) + && self.guides.as_ref() == doc.unknown.get(Self::GUIDES) + } + + fn same(&self, other: &KeptKey) -> bool { + self.inputs == other.inputs + && self.symbols.len() == other.symbols.len() + && self.symbols.iter().zip(&other.symbols).all(|((n, a), (m, b))| a.ptr_eq(b) && n == m) + && self.guides == other.guides + } +} + +/// Art boxes, nesting depths and the name index measured by boxes made by +/// [`Document::kept_symbol_boxes`], kept for the next ones made for the same symbols. +struct Kept { + key: KeptKey, + names: Option>, + measured: HashMap>, + depths: HashMap>, +} + +/// How many sets of symbols [`Document::kept_symbol_boxes`] keeps measurements for on each thread: +/// clicks can alternate between two open documents. +const KEPT_SETS: usize = 2; + +thread_local! { + /// The measurements [`Document::kept_symbol_boxes`] keeps, the latest first. + static KEPT: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// [`SymbolBoxes`] made by [`Document::kept_symbol_boxes`], which keep their measurements for the +/// next ones when dropped. +pub(crate) struct KeptBoxes<'a> { + boxes: SymbolBoxes<'a>, + /// What the measurements depend on, under which they are kept. + key: Option, + /// Other boxes of the same document whose measurements are kept with these + /// ([`Self::keeping`]). + also: Option<&'a SymbolBoxes<'a>>, +} + +impl<'a> std::ops::Deref for KeptBoxes<'a> { + type Target = SymbolBoxes<'a>; + + fn deref(&self) -> &SymbolBoxes<'a> { + &self.boxes + } +} + +impl<'a> KeptBoxes<'a> { + /// These boxes, which also keep the art boxes and nesting depths `other` has measured when + /// dropped. `other` measures the same document, as the boxes of + /// [`Document::locked_artboards_kept`] do. + pub(crate) fn keeping(mut self, other: &'a SymbolBoxes<'a>) -> Self { + self.also = Some(other); + self + } +} + +impl Drop for KeptBoxes<'_> { + /// Keeps the measurements, adding them to those kept for the same symbols by other boxes alive + /// at the same time. Art boxes of symbols whose art holds instances of symbols with 9-slice + /// guides are left out: measuring them places art within a budget the boxes share + /// ([`SymbolBoxes::sliced_visual`]). + fn drop(&mut self) { + let Some(key) = self.key.take() else { return }; + let b = &self.boxes; + let mut measured = b.measured.take(); + let mut depths = b.depths.take(); + if let Some(other) = self.also { + for (name, a) in other.measured.borrow().iter() { + measured.entry(name.clone()).or_insert(*a); + } + for (name, d) in other.depths.borrow().iter() { + depths.entry(name.clone()).or_insert(*d); + } + } + measured.retain(|_, a| a.is_none_or(|a| !a.sliced)); + let mut kept = Kept { key, names: b.names.get().cloned(), measured, depths }; + // Nothing is kept while the thread ends or the list is in use. + let _ = KEPT.try_with(|k| { + if let Ok(mut k) = k.try_borrow_mut() { + if let Some(i) = k.iter().position(|e| e.key.same(&kept.key)) { + let other = k.remove(i); + kept.names = kept.names.or(other.names); + for (name, a) in other.measured { + kept.measured.entry(name).or_insert(a); + } + for (name, d) in other.depths { + kept.depths.entry(name).or_insert(d); + } + } + k.insert(0, kept); + k.truncate(KEPT_SETS); + } + }); + } +} + impl Document { /// [`SymbolBoxes`] for this document's symbols, none measured yet. pub fn symbol_boxes(&self) -> SymbolBoxes<'_> { @@ -131,6 +259,56 @@ impl Document { } } + /// [`Self::symbol_boxes`] that start with the art boxes, nesting depths and name index measured + /// by the last such boxes made on this thread for the same symbols, and keep theirs for the next + /// ones when dropped. The measurements are made again when a symbol's name or art, the symbols' + /// 9-slice guides, or the inputs of the live geometry effects of clipping paths have + /// changed since. Measurements for the last [`KEPT_SETS`] sets of symbols are kept. + pub(crate) fn kept_symbol_boxes(&self) -> KeptBoxes<'_> { + self.kept_boxes(false) + } + + /// [`Self::symbol_boxes`] that start with a copy of the measurements + /// [`Self::kept_symbol_boxes`] would start with, and keep nothing themselves. + pub(crate) fn symbol_boxes_from_kept(&self) -> SymbolBoxes<'_> { + let mut kept = self.kept_boxes(true); + kept.key = None; + std::mem::replace(&mut kept.boxes, self.symbol_boxes()) + } + + /// [`Self::kept_symbol_boxes`], taking the kept measurements, or with `copy` copying them. + fn kept_boxes(&self, copy: bool) -> KeptBoxes<'_> { + let mut boxes = self.symbol_boxes(); + let inputs = crate::hit::clip_region_inputs(); + let found = KEPT + .try_with(|k| { + let mut k = k.try_borrow_mut().ok()?; + let i = k.iter().position(|e| e.key.is_of(self, inputs))?; + if copy { + let e = k.get(i)?; + let key = KeptKey { symbols: e.key.symbols.clone(), guides: e.key.guides.clone(), inputs }; + Some(Kept { key, names: e.names.clone(), measured: e.measured.clone(), depths: e.depths.clone() }) + } else { + Some(k.remove(i)) + } + }) + .ok() + .flatten(); + let key = match found { + Some(e) => { + if let Some(names) = e.names { + // The boxes were just made, so no index is set yet. + let _ = boxes.names.set(names); + } + *boxes.measured.get_mut() = e.measured; + *boxes.depths.get_mut() = e.depths; + e.key + } + None => KeptKey::of(self, inputs), + }; + KeptBoxes { boxes, key: Some(key), also: None } + } + /// Each symbol name of this document → the index of the first symbol of that name (the one a /// name finds). pub(crate) fn symbol_names(&self) -> SymbolNames { @@ -148,6 +326,8 @@ impl Document { thread_local! { /// How many symbols [`Document::symbol_names`] has read on this thread. pub(crate) static SYMBOLS_READ: Cell = const { Cell::new(0) }; + /// How many art boxes [`SymbolBoxes::art`] has measured on this thread. + static ART_BOXES_MEASURED: Cell = const { Cell::new(0) }; } impl<'a> SymbolBoxes<'a> { @@ -218,6 +398,8 @@ impl<'a> SymbolBoxes<'a> { pub(crate) fn art(&self, name: &str) -> Option { let cached = self.measured.borrow().get(name).copied(); let b = cached.unwrap_or_else(|| { + #[cfg(test)] + ART_BOXES_MEASURED.with(|c| c.set(c.get() + 1)); let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten(); self.measured.borrow_mut().insert(name.to_string(), b); b @@ -584,10 +766,10 @@ fn art_box(art: &Arc, symbols: &SymbolBoxes) -> Option { #[cfg(test)] mod tests { use vectorcraft_color::{Color, Paint}; - use vectorcraft_geom::shapes; + use vectorcraft_geom::{Point, shapes}; use super::*; - use crate::{Appearance, Symbol}; + use crate::{Appearance, NodeId, Symbol}; /// A rectangle filled black, with a `stroke` pt black stroke (0: none). fn rect(d: &mut Document, r: Rect, stroke: f64) -> Node { @@ -911,4 +1093,192 @@ mod tests { assert_eq!(s.effects_reach("Leaf", [2.0, 0.0, 0.0, 2.0], &measure(7.0)), 7.0); assert_eq!(runs.get(), MAX_REACHES + 2); } + + /// How many art boxes `f` measures on this thread. + fn art_boxes_measured(f: impl FnOnce()) -> usize { + let before = ART_BOXES_MEASURED.with(Cell::get); + f(); + ART_BOXES_MEASURED.with(Cell::get) - before + } + + /// A document with symbols "S 0" to "S 9", each a 10 × 10 square around the origin, and an + /// instance of each at (40 i + 20, 20). + fn ten_symbols() -> Document { + let mut d = Document::new(400.0, 100.0); + let layer = d.layers.first().map(|l| l.id); + for i in 0..10 { + let square = rect(&mut d, Rect::new(-5.0, -5.0, 5.0, 5.0), 0.0); + symbol(&mut d, &format!("S {i}"), vec![square]); + let at = instance(&mut d, &format!("S {i}"), Affine::translate((40.0 * f64::from(i) + 20.0, 20.0))); + d.insert(layer, usize::MAX, at).unwrap(); + } + d + } + + #[test] + fn hit_tests_measure_each_symbols_art_once_while_the_symbols_stay_the_same() { + use crate::hit::{self, HitOptions}; + let d = ten_symbols(); + let clicks = || { + for i in 0..10 { + let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0); + assert!(hit::hit_test(&d, p, HitOptions::default()).is_some(), "instance {i} is hit"); + assert_eq!(hit::objects_at(&d, p, HitOptions::default(), None).len(), 1); + } + assert_eq!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).len(), 10); + }; + let first = art_boxes_measured(clicks); + assert_eq!(first, 10, "each symbol's art box measured once"); + assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again"); + } + + #[test] + fn hit_tests_measure_a_symbol_again_after_it_changes() { + use crate::hit::{self, HitOptions}; + let mut d = ten_symbols(); + // Past the square of "S 1" at (60, 20). + let past = Point::new(71.0, 20.0); + assert!(hit::hit_test(&d, past, HitOptions::default()).is_none()); + // The art grows 3 times in place: no other copy of it is held in the document. + Arc::make_mut(&mut d.symbols[1].art).transform(Affine::scale(3.0), false); + let measured = art_boxes_measured(|| assert!(hit::hit_test(&d, past, HitOptions::default()).is_some(), "the grown art is hit")); + assert!(measured > 0); + // New art for "S 2", 40 wide. + let wide = rect(&mut d, Rect::new(-20.0, -5.0, 20.0, 5.0), 0.0); + d.symbols[2].art = Arc::new(wide); + assert!(hit::hit_test(&d, Point::new(115.0, 20.0), HitOptions::default()).is_some(), "the new art is hit"); + // "S 3" renamed: its instance now shows the 20 × 20 square. + d.symbols[3].name = "Renamed".into(); + assert!(hit::hit_test(&d, Point::new(148.0, 28.0), HitOptions::default()).is_some(), "the square is hit"); + assert_eq!(hits(&d), fresh_hits(&d)); + } + + /// What clicks on a grid over `d` hit, and what a marquee over it selects. + fn hits(d: &Document) -> (Vec>>, Vec) { + use crate::hit::{self, HitOptions}; + let mut clicks = Vec::new(); + for y in (0..400).step_by(5) { + for x in (0..400).step_by(5) { + let p = Point::new(f64::from(x), f64::from(y)); + clicks.push(hit::hit_test(d, p, HitOptions::default()).map(|h| h.ancestry)); + } + } + (clicks, hit::marquee(d, Rect::new(0.0, 0.0, 400.0, 400.0), None, false)) + } + + /// [`hits`] with no measurements kept from earlier hit tests. + fn fresh_hits(d: &Document) -> (Vec>>, Vec) { + KEPT.with_borrow_mut(Vec::clear); + hits(d) + } + + /// A bar in a panel with or without 9-slice guides, in a holder whose instance at (50, 50) is + /// scaled 2 times across. With the guides, the bar draws from x 30 to 210 and y 90 to 110; without + /// them, from x 70 to 190, inside the panel's frame from x 50 to 250 and y 50 to 150. + fn sliced_holder(guides: bool) -> Document { + let mut d = Document::new(400.0, 400.0); + let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0); + symbol(&mut d, "Bar", vec![bar]); + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); + let inner = instance(&mut d, "Bar", Affine::IDENTITY); + symbol(&mut d, "Panel", vec![frame, inner]); + if guides { + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + } + let panel = instance(&mut d, "Panel", Affine::IDENTITY); + symbol(&mut d, "Holder", vec![panel]); + let layer = d.layers.first().map(|l| l.id); + let holder = instance(&mut d, "Holder", Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(2.0, 1.0)); + d.insert(layer, usize::MAX, holder).unwrap(); + d + } + + #[test] + fn hit_tests_follow_new_9_slice_guides_and_symbol_sizes() { + use crate::hit::{self, HitOptions}; + let mut d = sliced_holder(false); + // Left of the frame, where only the bar placed through the guides draws. + let left = Point::new(40.0, 100.0); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_none()); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_some(), "the bar placed through the guides is hit"); + assert_eq!(hits(&d), fresh_hits(&d)); + let before = hits(&d); + d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [200.0, 100.0] })); + let after = hits(&d); + assert_ne!(after, before, "the size moves the guides"); + assert_eq!(after, fresh_hits(&d)); + } + + #[test] + fn hit_tests_measure_symbols_holding_9_slice_instances_on_each_call() { + use crate::hit::{self, HitOptions}; + let d = sliced_holder(true); + let left = Point::new(40.0, 100.0); + assert!(hit::hit_test(&d, left, HitOptions::default()).is_some()); + // The holder's art holds an instance of a symbol with guides; the panel's art holds none. + KEPT.with_borrow(|k| { + let measured = &k[0].measured; + assert!(measured.contains_key("Panel") && !measured.contains_key("Holder"), "{:?}", measured.keys()); + }); + let again = art_boxes_measured(|| assert!(hit::hit_test(&d, left, HitOptions::default()).is_some())); + assert!(again > 0, "the holder's art box measured again"); + } + + #[test] + fn kept_measurements_depend_on_the_inputs_of_clipping_path_effects() { + let d = ten_symbols(); + let key = KeptKey::of(&d, (0, false)); + assert!(key.is_of(&d, (0, false))); + assert!(!key.is_of(&d, (1, false)), "live inputs changed"); + assert!(!key.is_of(&d, (0, true)), "a clip region registered"); + } + + #[test] + fn hit_tests_with_a_locked_artboard_measure_each_symbols_art_once() { + use crate::hit::{self, HitOptions}; + let mut d = ten_symbols(); + d.artboards[0].locked = true; + let clicks = || { + for i in 0..10 { + let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0); + assert!(hit::hit_test(&d, p, HitOptions::default()).is_none(), "instance {i} is on the locked artboard"); + assert!(hit::objects_at(&d, p, HitOptions::default(), None).is_empty()); + } + }; + assert!(art_boxes_measured(clicks) >= 10, "each symbol's art box measured"); + assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again"); + // A marquee passes over the objects on a locked artboard without measuring them itself: only + // its locks measure their art. + let mut d = ten_symbols(); + d.artboards[0].locked = true; + let marquee = || assert!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).is_empty()); + assert_eq!(art_boxes_measured(marquee), 10, "each symbol's art box measured once"); + assert_eq!(art_boxes_measured(marquee), 0, "art boxes measured again"); + } + + #[test] + fn hit_tests_hold_no_symbol_art() { + use crate::hit::{self, HitOptions}; + let d = ten_symbols(); + drop(hit::hit_test(&d, Point::new(20.0, 20.0), HitOptions::default())); + assert!(KEPT.with_borrow(|k| !k.is_empty())); + assert!(d.symbols.iter().all(|s| Arc::strong_count(&s.art) == 1), "only the document holds the symbols' art"); + } + + #[test] + fn hit_tests_keep_the_measurements_of_two_sets_of_symbols() { + use crate::hit::{self, HitOptions}; + let docs = [ten_symbols(), ten_symbols(), ten_symbols()]; + let p = Point::new(20.0, 20.0); + for d in &docs { + drop(hit::hit_test(d, p, HitOptions::default())); + } + assert_eq!(KEPT.with_borrow(Vec::len), KEPT_SETS); + // The last two are kept, the first is measured again. + let kept = art_boxes_measured(|| docs[1..].iter().for_each(|d| drop(hit::hit_test(d, p, HitOptions::default())))); + assert_eq!(kept, 0); + let first = art_boxes_measured(|| drop(hit::hit_test(&docs[0], p, HitOptions::default()))); + assert!(first > 0); + } } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 5e95244e26..274f9bdcc4 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -720,7 +720,9 @@ fn moved_type_group(n: &Node) -> Option { /// Type in a clipping path, other type that [`moved_type`] doesn't copy, and type inside live /// objects or inside groups with Pathfinder or geometry effects or fills and strokes that paint, is /// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of -/// them. `None` when no type stays type. +/// them. `None` when no type stays type, and for a group or layer whose copies each carry the raster +/// effects listed before their Transform effect ([`crate::outer_effects`]), which is baked as the +/// canvas draws it ([`evaluate_container`]). fn container_keeping_type(d: &Document, n: &Node) -> Option { fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) { if !clipping { @@ -756,7 +758,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option { } } } - if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || has_pathfinder(n) || has_own_paint(n) { + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) + || has_pathfinder(n) + || has_own_paint(n) + || crate::reshape::copied_container_raster_at(n).is_some() + { return None; } let fx = geometry_effects(n); diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 63215d897d..9531159e01 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -832,11 +832,15 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, is_guide: &impl /// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live /// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and /// a Pathfinder operation or compound shape takes the symbol instances among its members as their -/// symbols' art from `doc`. +/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before +/// it gives each copy those raster effects ([`copied_container`]). pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { if !is_container(n) { return None; } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + return Some(copied_container(doc, n, t)); + } let pathfinder = has_pathfinder(n); let fx = crate::reshape::geometry_effects(n); let paint = has_own_paint(n); @@ -901,6 +905,63 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { Some(m) } +/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), +/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one +/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the +/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, +/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, +/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around +/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. +/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden +/// and locked as their containers were. +fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { + let mut m = n.clone(); + let mut guides = vec![]; + take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); + let mut source = m.clone(); + source.appearance.effects = n.appearance.effects.get(..t).unwrap_or_default().to_vec(); + // With no geometry effect before the Transform effect, `evaluate_container` leaves the members' + // own effects live (it only paints the group's own fills and strokes): the members are drawn + // first, so their effects apply before the copies are made. + if crate::reshape::geometry_effects(&source).is_empty() { + source = crate::reshape::outlined_members(doc, &source); + // The members' raster effects follow the group's own Transform effects as well. + let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); + members_as_drawn(doc, &mut source); + } + let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| { + let mut p = source.clone(); + p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects); + p + }); + // The piece is one copy: the transparency, opacity mask and guides stay on the art. + piece.name = None; + piece.visible = true; + piece.locked = false; + (piece.opacity, piece.blend, piece.isolate) = (1.0, Default::default(), false); + piece.extras_mut().mask = None; + // The copies are made about the piece's bounds, measured first: a layer leaves its hidden + // members out of them, and a group does not. + let bounds = piece.geometric_bounds(); + // A layer's copies are groups in it. + if let NodeKind::Layer { children, clip, .. } = &mut piece.kind { + piece.kind = NodeKind::Group { children: std::mem::take(children), clip: *clip }; + } + let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece, bounds); + let copies = art.children().cloned().unwrap_or_default(); + if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut m.kind { + *children = copies; + *clip = false; + } + m.appearance.items.clear(); + m.appearance.contents_index = None; + m.appearance.effects = effects; + if let Some(ch) = m.children_mut() { + ch.extend(guides); + } + m +} + /// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every /// depth of its groups and layers, by the art it draws ([`evaluate_container`], /// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members diff --git a/crates/effects/src/preview.rs b/crates/effects/src/preview.rs index ad36ab56dc..8d330a606b 100644 --- a/crates/effects/src/preview.rs +++ b/crates/effects/src/preview.rs @@ -1,4 +1,4 @@ -//! Use Preview Bounds: objects measured as they are drawn, with their geometry effects. +//! Use Preview Bounds: objects measured as they are drawn, with geometry and projected 3D effects. //! //! [`drawn_art`] gives an object whose geometry effects change what it draws as plain art. A path //! or compound path is given as its effected geometry, and a fill or stroke with geometry effects @@ -11,12 +11,15 @@ //! ([`expanded_live_group`]), with each of those objects given as its own art. A clip group or //! layer whose clipping path has strokes with geometry effects is given as that path's geometry //! before its effects, which the renderer clips by, and those strokes as drawn. Fills and -//! strokes that paint nothing (hidden, or painted None) are left out. [`bounds_of`], +//! strokes that paint nothing (hidden, or painted None) are left out. Extrude & Bevel, Revolve, +//! Inflate and Rotate are measured by the same projected vector art the renderer draws, with +//! any geometry effects after projection applied to that art; [`drawn_art`], which clicks and +//! marquees use, leaves 3D effects unprojected. [`bounds_of`], //! [`oriented_bounds`] and [`anchor_bounds`] measure the visual bounds of that art, strokes //! included, where [`Document::bounds_of`], [`Document::oriented_bounds`] and //! [`Selection::anchor_bounds`] measure the objects themselves. Raster effects (shadows, glows, //! blurs) are not measured. In one object, the art of at most 4,096 symbol instances is measured -//! with its geometry effects, and the other instances in it are measured without them. +//! with its geometry and 3D effects, and the other instances in it are measured without them. //! [`bounds_of_with`], [`oriented_bounds_with`] and [`anchor_bounds_with`] measure as these do and, //! with [`Measure::glyphs`], take point type by the ink of its glyphs (Measure Type by Glyph Bounds). @@ -31,12 +34,12 @@ use vectorcraft_geom::{Affine, PathData, Rect, Shape, union_opt}; use crate::group::has_own_paint; use crate::reshape::{geometry_effects, leaf_geometry}; use crate::{ - GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_transform_art, - needs_outline, outline_art, paints, reshape, + GeomContext, apply_geometry_with, evaluate_container, expanded_live_group, has_geometry, has_item_geometry, has_pathfinder, has_revolve, + has_solid, has_transform_art, needs_outline, outline_art, paints, reshape, revolve_art_in, solid_art_in, }; -/// Most symbol instances in one object whose art [`Drawn`] measures with its geometry effects: -/// past it, the other instances in the object are measured without geometry effects. +/// Most symbol instances in one object whose art [`Drawn`] measures with geometry or 3D effects: +/// past it, the other instances in the object are measured without those effects. const MAX_INSTANCES: usize = 4096; /// The bounds of `ids`: with `preview`, their visual bounds as drawn ([`visual_bounds`]), else @@ -191,8 +194,8 @@ pub fn laid_out_ink(layout: &vectorcraft_text::TextLayout, t: &vectorcraft_doc:: .fold(layout.ink_bounds(), |acc, (_, bar)| union_opt(acc, Some(bar.bounding_box()))) } -/// The visual bounds of `n` as drawn: those of its [`drawn_art`], else -/// [`Node::visual_bounds_with`]. +/// The visual bounds of `n` as drawn: those of its [`drawn_art`] with its 3D effects projected, +/// else [`Node::visual_bounds_with`]. pub fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { Drawn::new(symbols).visual_bounds(n) } @@ -204,31 +207,45 @@ pub fn bounds_in(symbols: &SymbolBoxes, n: &Node, a: Affine) -> Option { } /// `n` as plain art with the geometry effects in it applied, at every depth, symbol instances -/// measured by `symbols`. Raster effects stay on the art. A group, layer or intertwine without a -/// clip is rebuilt with the drawn art of each member that has one. A clip group or layer becomes a -/// group of its clipping path without strokes and the drawn art of the path's strokes, when they -/// have one. `None` when no geometry effect in `n` changes what it draws. +/// measured by `symbols`, for clicks and marquees. Raster effects stay on the art. A group, layer or +/// intertwine without a clip is rebuilt with the drawn art of each member that has one. A clip group +/// or layer becomes a group of its clipping path without strokes and the drawn art of the path's +/// strokes, when they have one. 3D effects stay on the art unprojected, so each object in it keeps +/// its own id. `None` when no geometry effect in `n` changes what it draws. pub fn drawn_art(symbols: &SymbolBoxes, n: &Node) -> Option { - Drawn::new(symbols).drawn_art(n) + Drawn::without_3d(symbols).drawn_art(n) } -/// Whether [`drawn_art`] gives `n` art of its own, or would give one to an object in it. A symbol -/// instance in `n` counts when its symbol's art has a geometry effect. +/// Whether `n` is measured by art of its own with Use Preview Bounds, or an object in it is: a +/// geometry or 3D effect in it changes what it draws. A symbol instance in `n` counts when its +/// symbol's art has geometry or 3D effects. pub fn draws_geometry(symbols: &SymbolBoxes, n: &Node) -> bool { Drawn::new(symbols).draws_geometry(n) } -/// One measurement: whether the art of each symbol checked so far draws geometry, by symbol name, -/// and how many more instances' art it measures with its geometry effects in the current object ([`MAX_INSTANCES`]). +/// One measurement: whether each symbol checked so far draws geometry or 3D art, by symbol name, +/// and how many more instances it measures with those effects in the current object ([`MAX_INSTANCES`]). +/// With `three_d` false, 3D effects are left on the art unprojected ([`drawn_art`]). struct Drawn<'s, 'd> { symbols: &'s SymbolBoxes<'d>, draws: RefCell>, left: Cell, + three_d: bool, } impl<'s, 'd> Drawn<'s, 'd> { fn new(symbols: &'s SymbolBoxes<'d>) -> Self { - Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES) } + Drawn { symbols, draws: RefCell::default(), left: Cell::new(MAX_INSTANCES), three_d: true } + } + + /// A measurement that projects no 3D effect, for clicks and marquees ([`drawn_art`]). + fn without_3d(symbols: &'s SymbolBoxes<'d>) -> Self { + Drawn { three_d: false, ..Self::new(symbols) } + } + + /// Whether `n` has a 3D effect of its own that this measurement projects. + fn projects(&self, n: &Node) -> bool { + self.three_d && (has_revolve(n) || has_solid(n)) } /// Sets the count of instances left back to [`MAX_INSTANCES`], for the next object. @@ -273,6 +290,7 @@ impl<'s, 'd> Drawn<'s, 'd> { let mut found = false; n.walk(&mut |c| { found = found + || self.projects(c) || match &c.kind { NodeKind::SymbolInstance { symbol, .. } => !geometry_effects(c).is_empty() || self.symbol_draws(symbol), _ => reshapes(c), @@ -292,14 +310,29 @@ impl<'s, 'd> Drawn<'s, 'd> { d } - /// The art the geometry effects of `n` itself give it, or that a symbol instance gets from the - /// geometry effects in its symbol's art. A group or layer with fills or strokes of its own that + /// The art the geometry or 3D effects of `n` itself give it, or that a symbol instance gets from + /// those effects in its symbol's art, with the instance's appearance overrides applied. + /// A group or layer with fills or strokes of its own that /// paint, around members with geometry effects, is evaluated too: its fills and strokes paint /// the members' geometry before their effects. A blend, envelope or repeat whose objects have /// geometry effects is evaluated as the renderer evaluates it ([`expanded_live_group`]), and /// the objects in its evaluated art keep their geometry effects. `None` when it has none, and /// for a symbol instance past [`MAX_INSTANCES`]. fn own_art(&self, n: &Node) -> Option { + let doc = Some(self.symbols.document()); + // A symbol instance with a 3D effect of its own counts toward MAX_INSTANCES before its art is built. + let counted = matches!(n.kind, NodeKind::SymbolInstance { .. }) && self.projects(n); + if counted { + let left = self.left.get().checked_sub(1)?; + self.left.set(left); + } + if self.three_d + && let Some(art) = revolve_art_in(doc, n).or_else(|| solid_art_in(doc, n)) + { + // The builders retain later geometry on the projected group. Measure it after that + // geometry too; item-level effects are handled by the ordinary member traversal. + return Some(self.own_art(&art).unwrap_or(art)); + } let inner = || n.children().is_some_and(|ch| ch.iter().any(|c| self.draws_geometry(c))); let painted = || has_own_paint(n) && inner(); match &n.kind { @@ -312,9 +345,14 @@ impl<'s, 'd> Drawn<'s, 'd> { if geometry_effects(n).is_empty() && !self.symbol_draws(symbol) { return None; } - let left = self.left.get().checked_sub(1)?; - self.left.set(left); + if !counted { + let left = self.left.get().checked_sub(1)?; + self.left.set(left); + } let art = self.symbols.measure_art(symbol, Arc::clone)?; + // Paint overrides can remove a projected surface or change its stroke outline. + let art = + if n.extras().symbol_overrides.is_empty() { art } else { Arc::new(vectorcraft_doc::symbol_overrides::dynamic_art(&art, n)) }; // An instance in perspective is projected by `reshape`. let doc = Some(self.symbols.document()); reshape(doc, n, Some(&*art)).or_else(|| outline_art(doc, n, Some(&*art))) diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 441e78e9e2..50ecc6b549 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -208,6 +208,110 @@ pub(crate) fn copied_raster_at(n: &Node) -> Option { (carried && !excluded).then_some(t) } +/// Where the own effects of `n`, a group or layer, split so that each copy of a Transform effect +/// carries the raster effects listed before that effect ([`crate::evaluate_container`]), as those of +/// a path split ([`copied_raster_at`]): the index of the last visible Transform effect that makes +/// copies, when a visible raster effect that follows a Transform effect is listed before it and +/// every other visible effect before it is a geometry effect or such a raster effect. `None` +/// otherwise, and for a compound shape, a Shaper group, a group or layer with a Pathfinder effect, a +/// linked opacity mask, a 3D effect, Crop Marks, Vector Halftone, a live-effect plug-in that paints +/// what it returns, a perspective, or a fill or stroke that paints with geometry effects of its own. +pub(crate) fn copied_container_raster_at(n: &Node) -> Option { + if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let effects = &n.appearance.effects; + // Checked first: this runs for every group and layer drawn. + if !effects.iter().any(|e| e.visible && crate::raster::follows(&e.id)) || !effects.iter().any(|e| e.visible && e.id == "distort.transform") { + return None; + } + let t = effects.iter().rposition(|e| { + e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0 + })?; + let before = effects.get(..t)?; + let carried = before.iter().any(|e| e.visible && crate::raster::follows(&e.id)) + && before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id)); + let excluded = n.is_compound_shape() + || n.extras().shaper.is_some() + || crate::has_pathfinder(n) + || n.extras().mask.as_ref().is_some_and(|m| m.linked) + || crate::has_solid(n) + || crate::has_revolve(n) + || crate::has_crop_marks(n) + || crate::addons::halftone::has_halftone(n) + || effects.iter().any(|e| painted_plugin(e).is_some()) + || n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) + || n.projection().is_some(); + (carried && !excluded).then_some(t) +} + +/// `piece`, the art that the effects of `n` (a group or layer whose own effects split at `t`, +/// [`copied_container_raster_at`]) before the Transform effect at `t` make of it, with the raster +/// effects among them as its own, copied by that Transform effect: a group with `n`'s id holding +/// the copies, the last copy lowest and the original on top, each copy's own raster effects moved, +/// turned, reflected and scaled with it ([`crate::raster::follow_contents`]), once, whatever Scale +/// Strokes & Effects says. The members' own raster effects in each copy stay as a Transform effect +/// that copies a group leaves them. The geometry effects after `t` then reshape all the copies as +/// one piece. The copies stop where [`copy_art`]'s do, each with its raster effects. The copies +/// inside `piece` that an earlier copying Transform effect of `n` made, which carry `n`'s id, have +/// their raster effects moved, turned, reflected and scaled with each copy in the same way +/// ([`follow_carried`]). The copies are made about `bounds`, the piece's bounds. Returns the art +/// and the raster effects from `t` on, as they ran. +pub(crate) fn copied_container_art(doc: Option<&Document>, n: &Node, t: usize, piece: Node, bounds: Option) -> (Node, Vec) { + let rest = n.appearance.effects.get(t..).unwrap_or_default(); + let own = piece.appearance.effects.clone(); + let original = piece.clone(); + let mut art = Node::group(n.id, vec![Arc::new(piece)]); + if let (Some(e), Some(bounds)) = (rest.first(), bounds) { + let params = merged_params(&e.id, &e.params); + let (m, copies) = crate::distort::transform_map(bounds, ¶ms, n.id.0); + let max = Budget::EFFECTS.at_least(art_cost(&art)); + copy_art(&mut art, m, copies, copy_scaling(crate::distort::TransformOptions::of(¶ms)), max); + if let Some(children) = art.children_mut() { + // The original is last, and each copy above it is mapped once more by `m`. + let step = m.with_translation(vectorcraft_geom::Vec2::ZERO); + let mut a = Affine::IDENTITY; + for (k, c) in children.iter_mut().rev().enumerate() { + // Each copy is the piece in a group of its own: the piece takes its place. + if let Some([one]) = c.children().map(Vec::as_slice) { + *c = one.clone(); + } + if k > 0 { + a *= step; + // Scale Strokes & Effects scaled the copy's own effects with it: they follow + // its map from their values on the original instead. + let copy = Arc::make_mut(c); + copy.appearance.effects = own.clone(); + crate::raster::follow_contents(&mut copy.appearance.effects, a, Affine::IDENTITY); + follow_carried(copy, &original, n.id, a); + } + } + } + } + let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect(); + let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (false, false), doc); + let mut ran = n.appearance.effects.clone(); + if carry.skipped() { + carry.hide_skipped(&mut ran); + } + let effects = crate::raster::without_geometry(ran.get(t..).unwrap_or_default()); + (art, effects) +} + +/// Give the members of `copy` with `id` (the copies that an earlier copying Transform effect of a +/// group or layer made, [`copied_container_art`]), at every depth below such members, the raster +/// effects of the matching members of `original`, the piece `copy` was made from, made to follow +/// `a` ([`crate::raster::follow_contents`]). +fn follow_carried(copy: &mut Node, original: &Node, id: NodeId, a: Affine) { + let (Some(ch), Some(was)) = (copy.children_mut(), original.children()) else { return }; + for (c, w) in ch.iter_mut().zip(was).filter(|(c, w)| w.id == id && c.id == id) { + let c = Arc::make_mut(c); + c.appearance.effects = w.appearance.effects.clone(); + crate::raster::follow_contents(&mut c.appearance.effects, a, Affine::IDENTITY); + follow_carried(c, w, id, a); + } +} + /// Is `e` a visible live-effect plug-in whose manifest declares `paintOutput`: its id's plug-in id, /// else `None`. fn painted_plugin(e: &Effect) -> Option<&str> { @@ -1172,9 +1276,10 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou /// The effects of `n` that paint around its whole art: all of its own, or from the Transform effect /// on for a path, compound path, type, image or symbol instance whose copies each carry the raster -/// effects listed before it ([`copied_raster_at`]). +/// effects listed before it ([`copied_raster_at`]) and for a group or layer whose copies do +/// ([`copied_container_raster_at`]). pub fn outer_effects(n: &Node) -> &[Effect] { - match copied_raster_at(n) { + match copied_raster_at(n).or_else(|| copied_container_raster_at(n)) { Some(t) => n.appearance.effects.get(t..).unwrap_or_default(), None => &n.appearance.effects, } diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index e463fb5332..dcb6ef9cfb 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -781,7 +781,7 @@ fn a_groups_transform_moves_its_members_shadows() { } /// A group's Transform effect that makes copies or moves at random leaves its members' shadows as -/// they are, as it leaves the shadows listed before it in its own effects. +/// they are. #[test] fn a_groups_copying_transform_leaves_its_members_shadows() { for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] { @@ -792,6 +792,204 @@ fn a_groups_copying_transform_leaves_its_members_shadows() { } } +/// A layer of `members` with `effects` of its own. +fn layer(id: u64, members: Vec, effects: Vec) -> Node { + let mut l = Node::layer(NodeId(id), "Layer", vectorcraft_doc::LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + *ch = members.into_iter().map(std::sync::Arc::new).collect(); + } + l.appearance.effects = effects; + l +} + +/// The offset and blur of the Drop Shadow that each member of `art` draws of its own, in order. +fn copy_shadows(art: &Node) -> Vec<(f64, f64, f64)> { + art.children().into_iter().flatten().map(|c| drawn_shadow(&c.appearance.effects)).collect() +} + +fn close_all(a: &[(f64, f64, f64)], b: &[(f64, f64, f64)]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| close(*x, *y)) +} + +/// A group's or layer's Transform effect that makes copies gives each copy the shadow listed +/// before it, moved, turned, reflected and scaled with that copy, the last copy lowest: drawn and +/// baked. Each copy is a group holding all the members, which carry no shadow of their own, and +/// the art paints none around all the copies. With Scale Strokes & Effects on, the shadow is not +/// scaled a second time. A layer's art stays a layer. +#[test] +fn each_copy_of_a_groups_or_layers_transform_effect_carries_the_shadow_listed_before_it() { + let cases = [ + (json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0, 4.0); 3]), + // A turn of 90° counterclockwise on screen takes an offset to the right to one upward. + (json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0, 4.0), (0.0, -10.0, 4.0), (10.0, 0.0, 4.0)]), + (json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0, 4.0), (10.0, 0.0, 4.0)]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]), + (json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}), vec![(20.0, 0.0, 8.0), (10.0, 0.0, 4.0)]), + ]; + for (params, want) in cases { + let offsets: Vec<(f64, f64)> = want.iter().map(|w| (w.0, w.1)).collect(); + for container in ["group", "layer"] { + let members = vec![square(101, vec![]), square(102, vec![])]; + let effects = vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]; + let n = if container == "group" { group(100, members, effects) } else { layer(100, members, effects) }; + assert!(crate::outer_effects(&n).iter().all(|e| e.id != "stylize.dropShadow"), "{params}: {container}"); + let art = crate::evaluate_container(None, &n).unwrap(); + assert_eq!(matches!(art.kind, vectorcraft_doc::NodeKind::Layer { .. }), container == "layer", "{params}: {container}"); + assert!(raster_effects(&art.appearance.effects).is_empty(), "{params}: {container} {:?}", art.appearance.effects); + let drawn = copy_shadows(&art); + assert!(close_all(&drawn, &want), "{params}: {container} {drawn:?}"); + assert_eq!(shadows_in(&art).len(), want.len(), "{params}: {container}: the members draw none"); + for c in art.children().into_iter().flatten() { + assert!(matches!(c.kind, vectorcraft_doc::NodeKind::Group { .. }) && paths_in(c) == 2, "{params}: {container} {c:?}"); + } + let b = baked(n); + assert!(near(&shadows_in(&b), &offsets), "{params}: {container} baked {:?}", shadows_in(&b)); + } + } +} + +/// A group's copying Transform effect leaves its members' own shadows on each copy as they are, +/// and a shadow listed after it paints once around all the copies. A clip group's copies each clip +/// and carry the shadow, and the art clips nothing. A Transform effect that makes no copies, or has +/// Transform Objects off, leaves the group's shadows on the group. +#[test] +fn a_groups_copying_transform_leaves_member_and_later_shadows_where_they_paint() { + let g = group( + 110, + vec![square(111, vec![shadow(5.0, 5.0, 0.0)]), square(112, vec![])], + vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)], + ); + assert_eq!(crate::outer_effects(&g).len(), 2); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (5.0, 5.0), (10.0, 0.0), (5.0, 5.0)]), "{:?}", shadows_in(&art)); + + let mut clip = square(121, vec![]); + if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut g = group(120, vec![clip, square(122, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))]); + if let vectorcraft_doc::NodeKind::Group { clip, .. } = &mut g.kind { + *clip = true; + } + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(!art.clips()); + assert!(art.children().into_iter().flatten().all(|c| c.clips()), "{art:?}"); + assert!(close_all(©_shadows(&art), &[(10.0, 0.0, 0.0), (10.0, 0.0, 0.0)]), "{:?}", copy_shadows(&art)); + + for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] { + let g = group(130, vec![square(131, vec![]), square(132, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]); + assert_eq!(crate::outer_effects(&g).len(), 2, "{params}"); + let art = crate::evaluate_container(None, &g).unwrap(); + assert_eq!(raster_effects(&art.appearance.effects).len(), 1, "{params}: the group keeps its shadow"); + } +} + +/// Copies of a group that stop at the effect budget each keep their shadow: no copy goes without +/// one, and no shadow is left without its copy. +#[test] +fn a_groups_copies_past_the_budget_each_keep_their_shadow() { + let g = group(140, vec![path_node(141, wavy(30_000), vec![])], vec![shadow(1.0, 0.5, 0.0), transform(json!({"moveV": 50, "copies": 1000}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + let paths = paths_in(&art); + assert!(paths > 1 && paths < 1001, "{paths}"); + assert_eq!(shadows_in(&art).len(), paths); +} + +/// A layer's ruler guides stay once above the copies of its Transform effect, and carry no shadow. +#[test] +fn a_layers_guides_stay_once_above_copies_that_carry_its_shadow() { + let guide = Node::new(NodeId(152), vectorcraft_doc::NodeKind::RulerGuide { vertical: true, pos: 3.0, artboard: None }); + let l = layer(150, vec![square(151, vec![]), guide], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 2}))]); + let art = crate::evaluate_container(None, &l).unwrap(); + let ch = art.children().unwrap(); + assert_eq!(ch.len(), 4, "three copies, then the guide"); + assert!(ch[3].is_ruler_guide() && ch.iter().filter(|c| c.is_ruler_guide()).count() == 1); + assert_eq!(shadows_in(&art).len(), 3); +} + +/// The bounds of every node with `id` under `art`, in order. +fn bounds_of(art: &Node, id: u64) -> Vec { + let mut out = vec![]; + art.walk(&mut |m| { + if m.id == NodeId(id) + && let Some(b) = m.geometric_bounds() + { + out.push(b); + } + }); + out +} + +fn rects_near(a: &[Rect], b: &[Rect]) -> bool { + let near = |p: f64, q: f64| (p - q).abs() < 1e-6; + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| near(p.x0, q.x0) && near(p.y0, q.y0) && near(p.x1, q.x1) && near(p.y1, q.y1)) +} + +/// A group with a fill of its own and only a shadow before its copying Transform effect applies +/// its members' own effects before it copies them, as a group without a fill does: a member's own +/// move is turned with each copy. +#[test] +fn a_painted_groups_copies_take_their_members_own_effects_first() { + let members = || vec![square(171, vec![transform(json!({"moveH": 40}))]), square(172, vec![])]; + let effects = || vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1}))]; + let plain = crate::evaluate_container(None, &group(170, members(), effects())).unwrap(); + let mut painted = group(170, members(), effects()); + *painted.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + painted.appearance.effects = effects(); + let art = crate::evaluate_container(None, &painted).unwrap(); + let (want, got) = (bounds_of(&plain, 171), bounds_of(&art, 171)); + assert!(!want.is_empty()); + assert!(rects_near(&got, &want), "{got:?} {want:?}"); +} + +/// A layer's copies are made about the bounds of its visible members, as the layer measures them: +/// a hidden member does not move the center that a reflected copy turns about. +#[test] +fn a_layers_copies_leave_its_hidden_members_out_of_their_reference() { + let mut hidden = path_node(182, shapes::rectangle(Rect::new(1000.0, 0.0, 1050.0, 50.0)), vec![]); + hidden.visible = false; + let l = layer(180, vec![square(181, vec![]), hidden], vec![shadow(10.0, 0.0, 0.0), transform(json!({"reflectX": true, "copies": 1}))]); + let art = crate::evaluate_container(None, &l).unwrap(); + let got = bounds_of(&art, 181); + assert!(rects_near(&got, &[Rect::new(0.0, 0.0, 50.0, 50.0); 2]), "{got:?}"); +} + +/// A shadow carried by the copies of an earlier copying Transform effect of a group turns with each +/// copy of a later one, drawn and baked. +#[test] +fn a_groups_later_copying_transform_turns_the_shadows_of_earlier_copies() { + let g = || { + group( + 190, + vec![square(191, vec![])], + vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1})), transform(json!({"rotate": 90, "copies": 1}))], + ) + }; + let want = [(0.0, -10.0), (0.0, -10.0), (10.0, 0.0), (10.0, 0.0)]; + let art = crate::evaluate_container(None, &g()).unwrap(); + assert!(near(&shadows_in(&art), &want), "{:?}", shadows_in(&art)); + let b = baked(g()); + assert!(near(&shadows_in(&b), &want), "baked {:?}", shadows_in(&b)); +} + +/// A group holding type whose Transform effect only moves its copies, baked for export, gives each +/// copy the shadow listed before that effect, as the canvas draws it, rather than keeping the type +/// as type under one shadow around all the copies. Built without fonts, type lays out no glyphs +/// and the test is skipped. +#[test] +fn a_baked_group_with_type_keeps_a_shadow_on_each_copy() { + use vectorcraft_doc::text::{CharStyle, TextObject}; + let style = CharStyle { size: 40.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let words = Node::new(NodeId(161), vectorcraft_doc::NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + if !crate::outline_text(&words).is_some_and(|o| paths_in(&o) > 0) { + eprintln!("skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)"); + return; + } + let g = group(160, vec![words, square(162, vec![])], vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 150, "copies": 1}))]); + let b = baked(g); + assert!(near(&shadows_in(&b), &[(10.0, 0.0), (10.0, 0.0)]), "{:?}", shadows_in(&b)); +} + /// The Transform effects inside a group apply before the group's: a member's own turn of 90° /// applies to its shadow before the group's uneven scale does, for the member's own shadow, its /// fill's shadow, and the shadow of a member of a nested group that has the turn. diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index 89f3893b24..7a92ff130a 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -5,15 +5,16 @@ use super::{ // ---------- brushes ---------- -/// Brushable nodes (paths and compound paths) under `ids`. +/// Brushable nodes (paths and compound paths) under `ids`, in walk order, each listed once where it is first reached. pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec { let mut out = vec![]; + let mut seen = std::collections::HashSet::new(); for id in ids { let Some(n) = d.node(*id) else { continue }; n.walk(&mut |c| { let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); - if own && !in_compound && !out.contains(&c.id) { + if own && !in_compound && seen.insert(c.id) { out.push(c.id); } }); @@ -748,3 +749,92 @@ pub(super) fn brush_freehand(s: &mut Session, p: &Value) -> Result { let checked = crate::schemas::check(spec, p, s.replaying())?; crate::cmd::draw2::freehand_brushed(s, checked.as_ref().unwrap_or(p), name.as_deref()) } + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::Appearance; + use vectorcraft_geom::PathData; + + /// The collector with a linear search of its output, kept to compare results with. + fn listed_targets(d: &Document, ids: &[NodeId]) -> Vec { + let mut out = vec![]; + for id in ids { + let Some(n) = d.node(*id) else { continue }; + n.walk(&mut |c| { + let own = matches!(c.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }); + let in_compound = d.parent_of(c.id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + if own && !in_compound && !out.contains(&c.id) { + out.push(c.id); + } + }); + } + out + } + + fn path(d: &mut Document) -> Node { + Node::path(d.alloc_id(), PathData::default(), Appearance::default()) + } + + fn compound(d: &mut Document, children: Vec) -> Node { + Node::new(d.alloc_id(), NodeKind::Compound { children: children.into_iter().map(Arc::new).collect(), rule: Default::default() }) + } + + fn add(d: &mut Document, node: Node) -> NodeId { + let layer = d.layers.first().map(|l| l.id); + d.insert(layer, usize::MAX, node).unwrap() + } + + #[test] + fn brush_targets_list_each_target_once_in_first_reached_order() { + let mut d = Document::new(400.0, 300.0); + let a = path(&mut d); + let a = add(&mut d, a); + let mut guide = path(&mut d); + if let NodeKind::Path { guide: g, .. } = &mut guide.kind { + *g = true; + } + let guide = add(&mut d, guide); + let mut clip = path(&mut d); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let clip = add(&mut d, clip); + // A group holding a path and a compound path of two members. + let p1 = path(&mut d); + let p1_id = p1.id; + let (m1, m2) = (path(&mut d), path(&mut d)); + let m1_id = m1.id; + let cp1 = compound(&mut d, vec![m1, m2]); + let cp1_id = cp1.id; + let group = Node::group(d.alloc_id(), vec![Arc::new(p1), Arc::new(cp1)]); + let group = add(&mut d, group); + // A compound path holding a compound path. + let m3 = path(&mut d); + let cp3 = compound(&mut d, vec![m3]); + let cp3_id = cp3.id; + let cp2 = compound(&mut d, vec![cp3]); + let cp2 = add(&mut d, cp2); + + let ids = [cp1_id, a, group, p1_id, a, guide, clip, m1_id, cp2, cp3_id, NodeId(u64::MAX)]; + let got = brush_targets(&d, &ids); + assert_eq!(got, [cp1_id, a, p1_id, cp2], "repeats keep their first place; guides, clipping paths and compound members are left out"); + assert_eq!(got, listed_targets(&d, &ids)); + assert!(brush_targets(&d, &[]).is_empty()); + + // Many paths in groups, each group listed with some of its members. + let mut ids = vec![]; + for _ in 0..50 { + let members: Vec = (0..20).map(|_| path(&mut d)).collect(); + let member_ids: Vec = members.iter().map(|m| m.id).collect(); + let g = Node::group(d.alloc_id(), members.into_iter().map(Arc::new).collect()); + let g = add(&mut d, g); + ids.push(member_ids[7]); + ids.push(g); + ids.push(member_ids[3]); + } + let got = brush_targets(&d, &ids); + assert_eq!(got.len(), 50 * 20); + assert_eq!(got, listed_targets(&d, &ids)); + } +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f38e23bb5d..5ed472b39a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1189,9 +1189,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); } if is_explicit { - for id in &ids { - sel.remove(*id); - } + sel.remove_all(ids.iter().copied()); sel.prune(d); } else { sel.clear(); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index cbe942183a..f21adcbc10 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -1238,6 +1238,69 @@ fn expand_node_except( } } +/// Replace `n`, a group or layer whose Transform effect's copies each carry the raster effects +/// listed before it ([`effects::outer_effects`]), with its art ([`effects::evaluate_container`]): +/// the copies become groups of their own with those effects, and they and what they hold get ids +/// of their own, so they expand as its members do; the raster effects after the Transform effect +/// stay on `n`. A copy that repeats an id ([`repeats_an_id`]) and holds a random Transform effect +/// ([`has_seeded`]) expands before its ids change ([`expand_in_place`]), as [`expand_pieces`] does, +/// and `members` gets what that expansion lists, by the copy's new id. `kept` gets the new id of +/// each copy of an object `skip` lists, and `out` gets `n` unless `listed` says it is there. +/// Returns whether `n` changed; any other object stays as it is. `Err`, with `n` as it is, when +/// such a copy still holds a random Transform effect after the raster budget left part of it as +/// it is: its new ids would give that effect another seed. +fn copies_carrying_raster( + d: &mut Document, + n: &mut Node, + (brushes, skip): (&[vectorcraft_brush::Brush], &[NodeId]), + kept: &mut Vec, + members: &mut std::collections::HashMap>, + (out, listed): (&mut Vec, &mut bool), + raster: &mut RasterBudget, +) -> std::result::Result { + if !carries_copies(n) { + return Ok(false); + } + let Some(mut m) = effects::evaluate_container(Some(&*d), n) else { return Ok(false) }; + let mut seen = std::collections::HashSet::from([n.id]); + for c in m.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) { + let c = Arc::make_mut(c); + let left = raster.left; + let mut expanded = (has_seeded(c) && repeats_an_id(c, &seen)).then(|| expand_in_place(d, c, brushes, skip, raster)); + if expanded.is_some() && raster.left > left && has_seeded(c) { + return Err(OverBudget); + } + let mut was = vec![]; + if !skip.is_empty() { + c.walk(&mut |n| was.push(n.id)); + } + fresh_ids_listed(d, c, &mut seen, expanded.as_deref_mut().unwrap_or_default()); + // A copy of an object `skip` lists is left as it is too. + let mut at = 0; + c.walk(&mut |n| { + if was.get(at).is_some_and(|old| *old != n.id && skip.contains(old)) { + kept.push(n.id); + } + at += 1; + }); + if let Some(expanded) = expanded { + members.insert(c.id, expanded); + } + } + if !*listed { + out.push((n.id, 0)); + *listed = true; + } + *n = m; + Ok(true) +} + +/// Is `n` a group or layer whose Transform effect's copies each carry the raster effects listed +/// before it ([`copies_carrying_raster`])? +fn carries_copies(n: &Node) -> bool { + is_container(n) && effects::outer_effects(n).len() != n.appearance.effects.len() +} + /// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when /// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk /// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded. @@ -1267,10 +1330,13 @@ fn expanded_node( } _ => None, }; - // The embedded images before the adjustment, when the raster budget may yet leave `n` as it - // is: the recolored copies the adjustment adds then go again. - let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) + // The embedded images before the adjustment and the expansions of the copies + // ([`copies_carrying_raster`]), when the raster budget may yet leave `n` as it is: the + // recolored copies and the images those add then go again. + let images_before = ((effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty()) || carries_copies(&n)) .then(|| d.images.keys().cloned().collect::>()); + // What the raster budget had left before those expansions: it gets back what they took. + let budget_before = (raster.images, raster.pixels); if effects::has_adjustment(&n) && let Some(m) = effects::adjust_in_document(d, &n, symbol_art) { @@ -1316,23 +1382,30 @@ fn expanded_node( } return Some(m); } + // New ids of the copies of objects `skip` lists among the members. + let mut kept = vec![]; + // Members of a group or layer that `expand_pieces` or `copies_carrying_raster` expanded, by id, + // with what their expansion lists. + let mut members = std::collections::HashMap::new(); + let copies = copies_carrying_raster(d, &mut n, (brushes, skip), &mut kept, &mut members, (out, &mut listed_n), raster); // Raster effects whose image would go past the budget stay: so does the object, with what is - // inside it and its color adjustments (a symbol instance stays an instance of its symbol). - let Ok(image) = raster_image(d, &n, raster) else { + // inside it and its color adjustments (a symbol instance stays an instance of its symbol), and + // so does a group or layer whose copies keep a random Transform effect the budget left. + let Ok(image) = copies.and_then(|copied| { + changed |= copied; + raster_image(d, &n, raster) + }) else { out.truncate(listed_before); if let Some(keys) = images_before { d.images.retain(|k, _| keys.contains(k)); } + (raster.images, raster.pixels) = budget_before; return None; }; let mut v = n.clone(); rasterfx::strip_raster(&mut v, false); let mut stroke_art = |d: &mut Document, path: &PathData, rule: FillRule, st: &StrokeLayer| super::pathops::outlined_stroke(d, brushes, path, rule, st); - // Members of a group or layer that `expand_pieces` expanded, by id, with what their expansion lists. - let mut members = std::collections::HashMap::new(); - // New ids of the copies of objects `skip` lists among those members. - let mut kept = vec![]; let expanded = match image { // Blur, feather and inner glow change the object itself: it becomes the image (a layer // keeps it as its only member). @@ -1344,7 +1417,7 @@ fn expanded_node( } else if container { // A group's or layer's own fills and strokes become art among its members. effects::evaluate_container(Some(&*d), &v).map(|mut m| { - members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster); + members.extend(expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster)); m }) } else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 5a1146f28f..d035c24860 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -1150,3 +1150,42 @@ fn an_image_past_the_pixels_left_stays_unmade() { let mut budget = super::RasterBudget { images: 0, pixels, left: 0 }; assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left"); } + +/// A group whose Transform effect's copies each carry the drop shadow listed before it, with a +/// symbol instance whose random Transform effect takes its seed from the instance's id, stays as it +/// is when the raster budget has no image left for a copy's shadow, with none left or with one for +/// the first copy's: the copies keep the ids their random moves are drawn with, the group draws as +/// before, and the document holds no image the first copy's expansion made, nor the budget its +/// charge. +#[test] +fn copies_the_raster_budget_leaves_keep_their_random_moves() { + let (mut s, id) = session_with_rect(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let id = NodeId(s.execute("symbol.new", &json!({"name": "Box"})).unwrap()["id"].as_u64().unwrap()); + let random = json!({"moveH": 40, "moveV": 40, "random": true}); + s.execute("effect.apply", &json!({"ids": [id.0], "effect": "distort.transform", "params": random})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "stylize.dropShadow", "params": shadow})).unwrap(); + s.execute("effect.apply", &json!({"ids": [g.0], "effect": "distort.transform", "params": {"moveV": 150, "copies": 1}})).unwrap(); + let draw = |d: &vectorcraft_doc::Document| { + vectorcraft_render::Renderer::new().render(d, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels + }; + for images in [0, 1] { + let mut d = s.doc().unwrap().doc.as_ref().clone(); + let before = d.node(g).cloned().unwrap(); + assert!(effects::outer_effects(&before).len() < before.appearance.effects.len(), "each copy carries the shadow"); + let (drawn, keys) = (draw(&d), d.images.keys().cloned().collect::>()); + + let mut budget = super::RasterBudget { images, pixels: u64::MAX, left: 0 }; + let mut out = vec![]; + super::expand_node(&mut d, g, &[], &mut out, &mut budget); + assert!(budget.left > 0, "{images}: a copy's shadow is left"); + assert!(out.is_empty(), "{images}: nothing expands: {out:?}"); + assert_eq!(d.node(g), Some(&before), "{images}: the group stays as it is"); + assert!(draw(&d) == drawn, "{images}: the group draws as before"); + assert_eq!(d.images.keys().cloned().collect::>(), keys, "{images}: no image is added"); + assert_eq!((budget.images, budget.pixels), (images, u64::MAX), "{images}: the budget gets back what the copies took"); + } +} diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index ccd3439730..818aaa632f 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,