From cf2de372c9e847991c7fe88e00f87085c4ce9a65 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 01:35:05 -0800 Subject: [PATCH 1/5] Image Trace: seam fills are clipped to the image and skip live shapes - The Seam Fills group is a clip group whose clipping path is the image's box, so a stroke that ends at the image's border stays inside it, and so do the trace's bounds. Where a shared edge ends at, or runs within 0.75 image pixels of, a transparent area or a color left out, its stroke can reach up to 0.75 image pixels into it. - Paths that became live shapes take no part. - Expand by color names the seam fills' group when it was moved above a path, instead of the Auto Grouping message. - Outline views leave the group out. - Canceling a trace run also stops it before the seam fills are found. Docs: docs/mcp.md, the params text, docs/target-app-parity.md. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/buildcmds/trace.rs | 72 +++++++---- crates/engine/src/tests/build.rs | 67 +++++++++- crates/render/src/renderer/nodes.rs | 14 ++- crates/trace/src/lib.rs | 2 +- crates/trace/src/seam.rs | 151 ++++++++++++++++------- docs/mcp.md | 22 ++-- docs/target-app-parity.md | 2 +- 8 files changed, 244 insertions(+), 88 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 66c9ec8fc4..817a34f6c8 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path, clipped to the image's box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index e9288918e8..e1b524dc8d 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -22,20 +22,21 @@ fn is_trace_group(n: &Node) -> bool { && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) } -/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]). +/// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]). const SEAM_FILLS_NAME: &str = "Seam Fills"; -/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths -/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto -/// Grouping groups hold filled paths.) +/// Whether `n` can be a trace's seam fills group: a clip group named as one, or a clip group whose +/// members after the clipping path are stroked paths without fills, so that it is still found +/// after it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) fn is_seam_fills(n: &Node) -> bool { let stroke_only = |m: &Arc| { matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None }; - matches!(n.kind, NodeKind::Group { clip: false, .. }) - && (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only))) + let NodeKind::Group { clip: true, children } = &n.kind else { return false }; + n.name.as_deref() == Some(SEAM_FILLS_NAME) + || children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(stroke_only)) } const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor"; @@ -410,7 +411,8 @@ fn by_color_param(cmd: &str, p: &Value) -> Result { /// starts another group of that paint, which keeps the stacking order of those items. Items /// farther apart can still share antialiased pixels at small view or raster-export scales, so /// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is, -/// under every other group. Any other group among `items` (Auto Grouping) is refused. +/// under every other group; above another item it is refused. Any other group among `items` (Auto +/// Grouping) is refused. fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result>> { use std::collections::{BTreeMap, HashMap}; use std::ops::Bound::{Excluded, Unbounded}; @@ -464,6 +466,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result> = BTreeMap::new(); let mut all_boxes: BTreeMap> = BTreeMap::new(); for (item, bounds) in items { + if is_seam_fills(&item) { + return Err(bad(cmd, "byColor needs the seam fills' group under every path: move it to the bottom or delete it")); + } if matches!(item.kind, NodeKind::Group { .. }) { return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); } @@ -630,12 +635,12 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { } /// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam -/// fills ([`seams_within`]). +/// fills, if any ([`seams_within`]). pub struct Traced { inputs: TraceInputs, raster: (u32, u32), res: tr::TraceResult, - seams: Vec, + seams: Option, } impl Traced { @@ -659,18 +664,23 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64 tr::TraceError::Cancelled => EngineError::Cancelled, e => EngineError::Other(e.to_string()), })?; - let seams = seams_within(&res, params, MAX_TRACE_ANCHORS); - Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams }) + if !steps(0, 0) { + return Err(EngineError::Cancelled); + } + let size = (raster.width, raster.height); + let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS); + Ok(Traced { inputs: inputs.clone(), raster: size, res, seams }) } -/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam -/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the -/// paths, so a trace whose paths have more than half of `max` gets none. -fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec { - if res.anchor_count() > max / 2 { - return vec![]; +/// The seam fills of `res`, traced with `params` from a `size` raster ([`tr::seam_fills`]), while +/// the paths, the seam fills' strokes and their clip together stay within `max` anchors: the +/// strokes have at most as many anchors as the paths and the clip has four, so a trace whose paths +/// have more than half of `max` less two gets none. +fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, size: (u32, u32), max: usize) -> Option { + if res.anchor_count().saturating_mul(2).saturating_add(4) > max { + return None; } - tr::seam_fills(&res.paths, params) + tr::seam_fills(&res.paths, params, size) } /// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`] @@ -801,9 +811,11 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result> = seam_fills + // Abutting: the seam fills, in a clip group of their own under every path, clipped to the + // image's box. + let strokes: Vec> = seam_fills .iter() + .flat_map(|f| &f.strokes) .filter_map(|tp| { let width = tp.stroke?; let mut n = shape_node(d, tp.path.transformed(xf), None); @@ -819,8 +831,13 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Node .unwrap() } -/// The traced paths of an Image Trace object: its children but the image and the seam fills. +/// The traced paths of an Image Trace object: its children but the image and the seam fills' +/// clip group (a trace makes no other clip group). fn traced_paths(n: &Node) -> Vec> { - n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_)) && c.name.as_deref() != Some("Seam Fills")).cloned().collect() + n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_) | NodeKind::Group { clip: true, .. })).cloned().collect() } #[test] @@ -6092,7 +6093,12 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { assert!(matches!(kids[0].kind, NodeKind::Image(_))); let group = seams(&n).unwrap(); assert!(Arc::ptr_eq(&group, &kids[1]), "the seam fills come under the paths"); - let strokes = group.children().unwrap(); + assert!(matches!(group.kind, NodeKind::Group { clip: true, .. }), "{group:?}"); + // The two paths cover the image, so the strokes are clipped to its box. + let (clip, strokes) = group.children().unwrap().split_first().unwrap(); + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}"); + let cb = outline(clip).0.bounds().unwrap(); + assert!([cb.x0, cb.y0, cb.x1 - 80.0, cb.y1 - 40.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); assert_eq!(strokes.len(), 1); assert_eq!(strokes[0].appearance.fill_paint(), Paint::None); let AppearanceItem::Stroke(layer) = &strokes[0].appearance.items[0] else { panic!("{:?}", strokes[0].appearance) }; @@ -6110,6 +6116,14 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { assert_eq!(names.len(), 3, "{names:?}"); assert_eq!(names[0], "Edges", "{names:?}"); assert_eq!(n.children().unwrap()[0].id, group.id); + // Above a path, the seam fills' group is refused by name, not as an Auto Grouping group. + let (mut s, _, r) = made("abutting", "imageTrace.make", false); + let g = NodeId(r["id"].as_u64().unwrap()); + let kids = node(&s, g).children().unwrap().clone(); + s.execute("object.arrange.bringToFront", &json!({"ids": [kids[1].id.0]})).unwrap(); + assert_eq!(node(&s, g).children().unwrap().last().map(|c| c.id), Some(kids[1].id)); + let e = s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap_err().to_string(); + assert!(e.contains("seam fills") && !e.contains("Auto Grouping"), "{e}"); let (mut s, img, _) = made("abutting", "imageTrace.make", false); assert_eq!(ids(&s.execute("imageTrace.release", &json!({})).unwrap()), vec![img]); // Make and Expand by color too. @@ -6124,8 +6138,28 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5)); let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap(); - let AppearanceItem::Stroke(layer) = &group.children().unwrap()[0].appearance.items[0] else { panic!("{group:?}") }; + let AppearanceItem::Stroke(layer) = &group.children().unwrap()[1].appearance.items[0] else { panic!("{group:?}") }; assert!((layer.width - 4.5).abs() < 1e-9, "{}", layer.width); + // White left out: the strokes are still clipped to the image's box. + let band = vectorcraft_trace::Raster::from_fn(24, 16, |x, y| match ((4..12).contains(&y), x < 12) { + (false, _) => [255; 4], + (true, true) => [200, 30, 30, 255], + (true, false) => [30, 30, 200, 255], + }); + let mut s = session(); + add_image(&mut s, &band, Affine::IDENTITY); + let r = s + .execute( + "imageTrace.make", + &json!({"params": {"mode": "color", "palette": "limited", "colors": 3, "method": "abutting", "ignoreWhite": true}}), + ) + .unwrap(); + assert_eq!(r["paths"], 2, "{r}"); + let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap(); + let clip = &group.children().unwrap()[0]; + assert!(matches!(clip.kind, NodeKind::Path { .. }), "{clip:?}"); + let cb = outline(clip).0.bounds().unwrap(); + assert!([cb.x0, cb.y0, cb.x1 - 24.0, cb.y1 - 16.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); } /// Expand by color: each color's paths in a group of their own, named by the color, the groups @@ -7188,6 +7222,31 @@ fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { } } +/// Outline views draw the traced paths' outlines and leave out an Abutting trace's seam fills +/// (their clipping box and strokes). +#[test] +fn image_trace_outline_view_leaves_out_the_seam_fills() { + let mut s = session(); + // Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×. + let art = vectorcraft_trace::Raster::from_fn(60, 40, |x, y| match ((10..50).contains(&x) && (10..30).contains(&y), x < 30) { + (false, _) => [0, 0, 0, 0], + (true, true) => [200, 30, 30, 255], + (true, false) => [30, 30, 200, 255], + }); + add_image(&mut s, &art, Affine::translate((50.0, 50.0)) * Affine::scale(2.0)); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let g = NodeId(r["id"].as_u64().unwrap()); + assert!(node(&s, g).children().unwrap().iter().any(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })), "seam fills"); + s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlines"})).unwrap(); + let screen = render_doc(&s, true); + // The image's top edge (y = 50), away from the art: nothing drawn. + for x in [60, 110, 160] { + assert!(screen.pixel(x, 50)[0] > 245 && screen.pixel(x, 51)[0] > 245, "x = {x}: {:?}", screen.pixel(x, 50)); + } + // The art's left edge (x = 70) is outlined. + assert!((68..=72).any(|x| screen.pixel(x, 90)[0] < 128)); +} + /// #569: merging the regions of a rosette of unfilled ellipses (each off the centre, petals /// overlapping) merges every region the drags touch into one shape whose outline is only the /// merged area's border: no edge between merged regions stays in, as a stray line or a spur. diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 37f3fbf4f7..c3dae5c07f 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -653,7 +653,19 @@ impl Renderer { if view.shows_outlines() { let opts = RenderOptions { outline: true, ..f.opts.clone() }; let frame = Frame { opts: &opts, ..*f }; - for c in shapes { + // An Abutting trace's seam fills hold no traced outline: a clip group named "Seam Fills" + // of stroked paths without fills. + let seam_fills = |c: &Arc| { + let stroke_only = |m: &Arc| { + matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && m.appearance.fill_paint().is_none() + && !m.appearance.stroke_paint().is_none() + }; + c.name.as_deref() == Some("Seam Fills") + && matches!(&c.kind, NodeKind::Group { clip: true, children } + if children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(stroke_only))) + }; + for c in shapes.iter().filter(|c| !seam_fills(c)) { self.draw_outline_member(ctx, &frame, c); } } diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index b489e4dd82..7bb59c79b1 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -72,7 +72,7 @@ pub use gradient::TracedGradient; pub use mosaic::mosaic; pub use opaque::{ALPHA_MAX_DECODE_BYTES, OUTLINE_MAX_ANCHORS, OUTLINE_MAX_PIXELS, decode_alpha, opaque_outline}; pub use quantize::{FULL_TONE_MAX, Quantized, TRANSPARENT, denoise, quantize}; -pub use seam::{SEAM_WIDTH, seam_fills}; +pub use seam::{SeamFills, seam_fills}; pub use shapes::TracedShape; use subpixel::Crack; diff --git a/crates/trace/src/seam.rs b/crates/trace/src/seam.rs index 5a1ffa96c5..b17d1dd6da 100644 --- a/crates/trace/src/seam.rs +++ b/crates/trace/src/seam.rs @@ -6,19 +6,38 @@ //! under every path, fills those pixels with that color: drawing the two paths over it then gives //! each pixel the colors of the two paths in the shares each covers. The paths themselves are not //! changed, and an edge a path shares with no other path (the image's border, a transparent area, -//! a color left out) gets no stroke. +//! a color left out) gets no stroke. The strokes are clipped to the image's box. Where a shared +//! edge ends at, or runs within half the stroke's width of, a transparent area or a color left +//! out, its stroke can reach that far into that area. use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; -use super::params::{Method, Mode, TraceParams}; -use super::pipeline::TracedPath; +use crate::{Method, Mode, TraceParams, TracedPath}; /// How wide each seam fill's stroke is, in pixels: it covers every pixel the shared edge passes /// through, at any angle (a pixel's corner is up to 0.71 px from a line through it). -pub const SEAM_WIDTH: f64 = 1.5; +const SEAM_WIDTH: f64 = 1.5; + +/// The seam fills of an Abutting trace ([`seam_fills`]). +#[derive(Clone, Debug, PartialEq)] +pub struct SeamFills { + /// For each color, one path stroked 1.5 pixels wide along the edges where a filled path of + /// that color meets a filled path drawn after it, with `color` and `gradient` that path's; the + /// paths with a gradient get one each. Bottom-most first, as the paths they lie under. + pub strokes: Vec, + /// The area to clip `strokes` to, in the same pixel coordinates: the image's box. + pub clip: PathData, +} + +impl SeamFills { + /// The anchors of the strokes and the clip together. + pub fn anchor_count(&self) -> usize { + self.strokes.iter().map(|s| s.path.anchor_count()).sum::() + self.clip.anchor_count() + } +} /// A segment, the same for the segment and the segment run backwards: two 64-bit hashes of its /// points' bits, 16 bytes a segment instead of 64. Two different segments with the same key would @@ -36,18 +55,23 @@ fn key(a: &Anchor, b: &Anchor) -> Key { (u128::from(hash(0)) << 64) | u128::from(hash(1)) } -/// The seam fills of a trace made with `params`: for Abutting with Fills (not Flat Logo), thin -/// strokes to draw under every path of `paths` (bottom-most first). For each color, one path -/// stroked [`SEAM_WIDTH`] pixels wide along the edges where a filled path of that color meets a -/// filled path drawn after it, with `color` and `gradient` that path's; the paths with a gradient -/// get one each. Bottom-most first, as the paths they lie under. The stroke has at most as many -/// anchors as `paths` (each of its segments is a segment of a path), and finding them keeps about -/// 40 bytes for each segment of `paths` while it runs. Empty for any other trace. -pub fn seam_fills(paths: &[TracedPath], params: &TraceParams) -> Vec { +/// The seam fills of a trace of a `size` (width, height in pixels) image made with `params`, for +/// Abutting with Fills (not Flat Logo): strokes to draw under every path of `paths` (bottom-most +/// first), clipped to the image's box. Filled paths that became a live shape (Shapes) take no part: +/// their outline is not the traced one. The strokes have at most as many anchors as `paths` (each +/// of their segments is a segment of a path), and the clip has four; finding them keeps about 40 +/// bytes for each segment of `paths` while it runs. `None` for any other trace, or when no filled +/// paths share an edge. +pub fn seam_fills(paths: &[TracedPath], params: &TraceParams, size: (u32, u32)) -> Option { if params.method != Method::Abutting || !params.fills || params.mode == Mode::Logo { - return vec![]; + return None; } - fills(paths) + fills(paths, size) +} + +/// Whether `p` takes part in the seam fills: filled, and drawn with its traced outline. +fn filled(p: &TracedPath) -> bool { + p.stroke.is_none() && p.shape.is_none() } /// The segments of `sp`: each anchor and the one after it (back to the first, if closed). @@ -57,11 +81,11 @@ fn segments(sp: &SubPath) -> impl Iterator { (0..count).filter_map(move |k| Some((sp.anchors.get(k)?, sp.anchors.get((k + 1) % n)?))) } -/// [`seam_fills`] of Abutting `paths`, whatever the settings. -fn fills(paths: &[TracedPath]) -> Vec { +/// [`seam_fills`] of Abutting `paths` traced from a `size` image, whatever the settings. +fn fills(paths: &[TracedPath], size: (u32, u32)) -> Option { // For each segment, the first path it is in, and whether another path has it too. let mut owner: HashMap = HashMap::new(); - for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) { + for (i, p) in paths.iter().enumerate().filter(|(_, p)| filled(p)) { for sp in &p.path.subpaths { for (a, b) in segments(sp).filter(|(a, b)| a.p != b.p) { let e = owner.entry(key(a, b)).or_insert((i, false)); @@ -74,11 +98,10 @@ fn fills(paths: &[TracedPath]) -> Vec { // One fill per color (per path, for a gradient), in the order of the first path it lies under. let mut out: Vec = vec![]; let mut by_color: HashMap<[u8; 3], usize> = HashMap::new(); - for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) { + for (i, p) in paths.iter().enumerate().filter(|(_, p)| filled(p)) { let mut runs: Vec = vec![]; for sp in &p.path.subpaths { - let lower = |a: &Anchor, b: &Anchor| a.p != b.p && owner.get(&key(a, b)) == Some(&(i, true)); - let marks: Vec = segments(sp).map(|(a, b)| lower(a, b)).collect(); + let marks: Vec = segments(sp).map(|(a, b)| a.p != b.p && owner.get(&key(a, b)) == Some(&(i, true))).collect(); let n = sp.anchors.len(); if marks.is_empty() { continue; @@ -129,7 +152,12 @@ fn fills(paths: &[TracedPath]) -> Vec { } } } - out + if out.is_empty() { + return None; + } + let (w, h) = (f64::from(size.0), f64::from(size.1)); + let clip = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)], true)); + Some(SeamFills { strokes: out, clip }) } /// An open run of anchors: the last one has no handle out. @@ -143,13 +171,18 @@ fn open_run(mut run: Vec) -> SubPath { #[cfg(test)] mod tests { use super::*; - use crate::{Method, Mode, Raster, TraceParams, trace}; + use crate::{Method, Mode, Raster, TraceParams, TracedGradient, TracedShape, trace}; fn polygon(rings: &[&[(f64, f64)]], color: u8) -> TracedPath { let subpaths = rings.iter().map(|r| SubPath::polyline(&r.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), true)).collect(); TracedPath { path: PathData::new(subpaths), color: [color; 3], pixels: 1, stroke: None, shape: None, gradient: None, square_caps: false } } + /// The strokes of [`fills`] for `paths` in a box that no test path reaches the border of. + fn strokes(paths: &[TracedPath]) -> Vec { + fills(paths, (100, 100)).map(|f| f.strokes).unwrap_or_default() + } + fn points(sp: &SubPath) -> Vec<(f64, f64)> { sp.anchors.iter().map(|a| (a.p.x, a.p.y)).collect() } @@ -163,7 +196,7 @@ mod tests { fn a_shared_edge_gets_a_stroke_in_the_color_of_the_path_drawn_first() { let left = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10); let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); - let fills = fills(&[left.clone(), right.clone()]); + let fills = strokes(&[left.clone(), right.clone()]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!((fills[0].color, fills[0].stroke, fills[0].gradient.as_ref()), ([10; 3], Some(SEAM_WIDTH), None)); assert_eq!(fills[0].path.subpaths.len(), 1); @@ -171,7 +204,7 @@ mod tests { assert!(!sp.closed); assert_eq!(points(sp), [(2.0, 0.0), (2.0, 2.0)]); // Drawn the other way round, the stroke takes the other color. - let swapped = super::fills(&[right, left]); + let swapped = strokes(&[right, left]); assert_eq!(swapped.len(), 1); assert_eq!((swapped[0].color, points(&swapped[0].path.subpaths[0])), ([20; 3], vec![(2.0, 2.0), (2.0, 0.0)])); } @@ -181,7 +214,7 @@ mod tests { let hole: &[(f64, f64)] = &[(2.0, 2.0), (2.0, 4.0), (4.0, 4.0), (4.0, 2.0)]; let around = polygon(&[&[(0.0, 0.0), (6.0, 0.0), (6.0, 6.0), (0.0, 6.0)], hole], 10); let island = polygon(&[&[(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)]], 20); - let fills = fills(&[around, island]); + let fills = strokes(&[around, island]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!(fills[0].color, [10; 3]); assert_eq!(fills[0].path.subpaths.len(), 1); @@ -195,7 +228,7 @@ mod tests { // at the same point. let left = polygon(&[&[(2.0, 1.0), (2.0, 2.0), (0.0, 2.0), (0.0, 0.0), (2.0, 0.0)]], 10); let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0), (2.0, 1.0)]], 20); - let fills = fills(&[left, right]); + let fills = strokes(&[left, right]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!(fills[0].path.subpaths.len(), 1); assert_eq!(points(&fills[0].path.subpaths[0]), [(2.0, 0.0), (2.0, 1.0), (2.0, 2.0)]); @@ -204,11 +237,15 @@ mod tests { #[test] fn edges_shared_with_no_other_filled_path_get_no_stroke() { let square = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10); - assert_eq!(fills(std::slice::from_ref(&square)), []); - // A stroked line along the square's edge is not a filled neighbour. - let mut line = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); - line.stroke = Some(1.0); - assert_eq!(fills(&[square, line]), []); + assert_eq!(fills(std::slice::from_ref(&square), (100, 100)), None); + // A stroked path along the square's edge is not a filled neighbor. + let mut stroked = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); + stroked.stroke = Some(1.0); + assert_eq!(fills(&[square.clone(), stroked], (100, 100)), None); + // Nor is a path drawn as a live shape, whose outline is not the traced one. + let mut shape = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); + shape.shape = Some(TracedShape::Rectangle { center: Point::new(3.0, 1.0), width: 2.0, height: 2.0, radius: 0.0, rotation: 0.0 }); + assert_eq!(fills(&[square, shape], (100, 100)), None); } #[test] @@ -216,9 +253,34 @@ mod tests { let a = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10); let b = polygon(&[&[(0.0, 4.0), (2.0, 4.0), (2.0, 6.0), (0.0, 6.0)]], 10); let c = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 6.0), (2.0, 6.0), (2.0, 4.0), (2.0, 2.0)]], 20); - let fills = fills(&[a, b, c]); + let fills = strokes(&[a.clone(), b.clone(), c.clone()]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!(fills[0].path.subpaths.iter().map(points).collect::>(), [vec![(2.0, 0.0), (2.0, 2.0)], vec![(2.0, 4.0), (2.0, 6.0)]]); + // With a gradient each, the two paths of one color get a stroke each, with their gradient. + let ramp = |to: u8| TracedGradient { start: Point::new(0.0, 0.0), end: Point::new(2.0, 0.0), stops: vec![(0.0, [10; 3]), (1.0, [to; 3])] }; + let (mut a, mut b) = (a, b); + (a.gradient, b.gradient) = (Some(ramp(30)), Some(ramp(40))); + let fills = strokes(&[a.clone(), b.clone(), c]); + assert_eq!(fills.len(), 2, "{fills:?}"); + assert_eq!(fills.iter().map(|f| f.gradient.clone()).collect::>(), [a.gradient, b.gradient]); + assert_eq!( + fills.iter().map(|f| points(&f.path.subpaths[0])).collect::>(), + [vec![(2.0, 0.0), (2.0, 2.0)], vec![(2.0, 4.0), (2.0, 6.0)]] + ); + } + + #[test] + fn the_strokes_are_clipped_to_the_images_box() { + // A diagonal edge meeting the border: a corner of the stroke's butt end reaches past the + // box, and the clip is the box. + let lower = polygon(&[&[(0.0, 0.0), (3.0, 0.0), (1.0, 2.0), (0.0, 2.0)]], 10); + let upper = polygon(&[&[(3.0, 0.0), (4.0, 0.0), (4.0, 2.0), (1.0, 2.0)]], 20); + let diagonal = fills(&[lower, upper], (4, 2)).unwrap(); + assert_eq!(points(&diagonal.strokes[0].path.subpaths[0]), [(3.0, 0.0), (1.0, 2.0)]); + assert_eq!(diagonal.clip.subpaths.len(), 1); + assert!(diagonal.clip.subpaths[0].closed); + assert_eq!(points(&diagonal.clip.subpaths[0]), [(0.0, 0.0), (4.0, 0.0), (4.0, 2.0), (0.0, 2.0)]); + assert_eq!(diagonal.anchor_count(), 2 + 4); } /// Two colors side by side, the edge between them anti-aliased at `x = 10.4`. @@ -239,9 +301,9 @@ mod tests { let params = color(Method::Abutting); let res = trace(&two_colors(), ¶ms); assert_eq!(res.paths.len(), 2, "{res:?}"); - let seams = seam_fills(&res.paths, ¶ms); - assert_eq!(seams.len(), 1, "{seams:?}"); - let seam = &seams[0]; + let fills = seam_fills(&res.paths, ¶ms, (24, 16)).unwrap(); + assert_eq!(fills.strokes.len(), 1, "{fills:?}"); + let seam = &fills.strokes[0]; assert_eq!((seam.color, seam.stroke), (res.paths[0].color, Some(SEAM_WIDTH))); // Every piece of the stroke is a piece of both paths, and it runs from the image's top to // its bottom along the edge, not along the image's border. @@ -253,25 +315,28 @@ mod tests { } let ys: Vec = seam.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p.y)).collect(); assert_eq!((ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)), (0.0, 16.0)); + // The clip is the image's box. + let corners: Vec<(f64, f64)> = fills.clip.subpaths.iter().flat_map(points).collect(); + assert_eq!(corners, [(0.0, 0.0), (24.0, 0.0), (24.0, 16.0), (0.0, 16.0)]); } #[test] fn only_abutting_fills_get_seam_strokes() { - let seams = |img: &Raster, params: &TraceParams| seam_fills(&trace(img, params).paths, params); + let seams = |img: &Raster, params: &TraceParams| seam_fills(&trace(img, params).paths, params, (img.width, img.height)); let img = two_colors(); - assert_eq!(seams(&img, &color(Method::Overlapping)), []); - assert_eq!(seams(&img, &TraceParams { fills: false, strokes: true, ..color(Method::Abutting) }), []); + assert_eq!(seams(&img, &color(Method::Overlapping)), None); + assert_eq!(seams(&img, &TraceParams { fills: false, strokes: true, ..color(Method::Abutting) }), None); // Flat Logo's shapes are stacked, whatever the method says. let abutting = trace(&img, &color(Method::Abutting)); - assert_eq!(seam_fills(&abutting.paths, &TraceParams { mode: Mode::Logo, ..color(Method::Abutting) }), []); - // A color left out leaves no neighbour: a dark bar on white, with Ignore White. + assert_eq!(seam_fills(&abutting.paths, &TraceParams { mode: Mode::Logo, ..color(Method::Abutting) }, (24, 16)), None); + // A color left out leaves no neighbor: a dark bar on white, with Ignore White. let bar = Raster::from_fn(24, 16, |x, _| if (8..16).contains(&x) { [0, 0, 0, 255] } else { [255; 4] }); let bw = TraceParams { mode: Mode::BlackAndWhite, method: Method::Abutting, ignore_white: true, ..TraceParams::default() }; let res = trace(&bar, &bw); assert_eq!(res.paths.len(), 1, "{res:?}"); - assert_eq!(seam_fills(&res.paths, &bw), []); + assert_eq!(seam_fills(&res.paths, &bw, (24, 16)), None); // Both colors traced, the bar's two sides are shared. - let both = seams(&bar, &TraceParams { ignore_white: false, ..bw }); - assert_eq!(both.iter().map(|s| s.path.subpaths.len()).sum::(), 2, "{both:?}"); + let both = seams(&bar, &TraceParams { ignore_white: false, ..bw }).unwrap(); + assert_eq!(both.strokes.iter().map(|s| s.path.subpaths.len()).sum::(), 2, "{both:?}"); } } diff --git a/docs/mcp.md b/docs/mcp.md index 87b1dc7ab4..47569c5492 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3829,16 +3829,18 @@ already walks Image Trace. Short agent entry points: black ring around a white disc around a black dot, black gets two groups. `layer.releaseToLayers` on the expanded group then gives each group a sublayer. A trace made with `autoGrouping` is refused. Expanding by color also refuses a trace with a live Pathfinder effect. - An Abutting trace with Fills (not Flat Logo) also holds a group named `Seam Fills` under its paths: for each color, a - stroke 1.5 image pixels wide (at the image's larger scale, when it is stretched more one way) with butt caps and round joins along the edges where a filled path of that color meets a - filled path drawn after it, in that color (a gradient path's stroke takes its gradient). Without it, a renderer that - anti-aliases each path on its own shows a light hairline along every shared edge. The traced paths and their shared - edges are the same with or without it, and edges against the image's border, a transparent area or a color left out - get no stroke. A trace whose paths have more than half of the trace's anchor limit (8,000,000, 2,000,000 on the web) - has no seam fills, so that paths and seam fills together stay within the limit. Both Expand commands keep the group, and `byColor` leaves it under every color's group. The strokes - are separate objects: after Expand, recoloring, moving or deleting a traced path leaves them as they are, and deleting - the group removes them. The reply's - `paths` and `anchors` count the traced paths only. + An Abutting trace with Fills (not Flat Logo) also holds a clip group named `Seam Fills` under its paths. For each + color it holds one stroke along the edges where a filled path of that color meets a filled path drawn after it, in + that color (a gradient path's stroke takes its gradient), with butt caps and round joins. The stroke is 1.5 image + pixels wide, VectorCraft's own width, at the image's larger scale when the image is stretched more one way. The group + clips the strokes to the image's box. Where a shared edge ends at, or runs within 0.75 image pixels of, a transparent + area or a color left out, its stroke can reach up to 0.75 image pixels into that area. Paths that became live shapes + (`shapes`) take no part. The traced paths and their shared edges are the same with or without the group. A trace + whose paths have more than about half of the trace's anchor limit (8,000,000, 2,000,000 on the web) has no seam + fills. Both Expand commands keep the group, and `byColor` leaves it under every color's group; `byColor` refuses a + trace whose seam fills' group was moved above a path. The strokes are separate objects, in a trace and after Expand: + recoloring, moving or deleting a traced path leaves them as they are, and deleting the group removes them. The + reply's `paths` and `anchors` count the traced paths only. With `keepColors` in `params`, the reply's `warnings` name each listed color that no traced color matches, and say when nothing was traced. `imageTrace.presets.save {name?, newName?, preset?, enhanced?, params?}` saves tracing settings as a preset kept with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2c05c6860a..6c0866af32 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1510,7 +1510,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Document Library color groups:** with Document Swatches, the panel's Colors menu and `"colorGroup"` trace with one color group's colors instead of every swatch, as the public panel documentation describes Document Library; code-drawn tests in `crates/engine` and the panel. - **Image Trace, Document Library colors:** with Document Swatches, traced fills and strokes use the displayed colors of process, global, spot and tint swatches without links, so editing a swatch leaves the trace unchanged; swatch-library colors are also unlinked; code-drawn tests in `crates/engine`. - **Image Trace, flattened slivers:** in a Color, Grayscale or Black and White trace with Fills, a traced region whose outline straightens onto one line (a single pixel, or a one-pixel row along an edge, its pieces shared with the regions beside it) is left out instead of becoming a selectable path with no area, which paints nothing. Snap Curves To Lines straightens more outlines, so it leaves out more of these. Without Fills, the region's 1 px stroke draws it, and it is kept. Code-drawn tests in `crates/trace`. -- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` group under its paths, with 1.5 px strokes along the edges two filled paths share, in the lower path's color (VectorCraft's own width), so renderers that anti-alias each path on its own show no light hairline along those edges. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` in `crates/engine`. Scores and hours unchanged. +- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` clip group under its paths, with strokes along the edges two filled paths share, in the lower path's color, 1.5 image pixels wide (VectorCraft's own width) and clipped to the image's box. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` in `crates/engine`. - **Image Trace, Auto Color rare colours:** the Automatic palette keeps colours too rare for its area count when they are distinct (Oklab) and drawn as coherent regions, at most six, protected from mixed-colour merging and Noise; code-drawn stem, highlight, low-contrast and scattered-noise tests (see [quality notes](image-trace-quality.md#auto-color-keeps-rare-colours)). - **Image Trace, nearly flat dark grounds:** with a Limited palette of 9 to 16 colors (16 Colors, and Document Library without swatches), by VectorCraft's own rule, a cut whose two sides both have a dark gray mean (Oklab lightness under 0.30, chroma under 0.03) and lie less than 0.03 apart in Oklab has its gain scaled by (distance / 0.03)². A near-black ground with faint noise then traces in one color, and the color it would have taken goes to another cut. Code-drawn tests `a_nearly_flat_dark_ground_keeps_one_color`, `only_a_limited_palette_of_nine_to_sixteen_colors_weighs_alike_sides` and `a_dark_colored_figure_on_a_nearly_flat_dark_ground_keeps_its_color` in `crates/trace`. - **Image Trace, Document Library keeps neutral tones neutral:** each pixel takes the library color nearest in Oklab with differences in hue and chroma counted three times, so a gray or a muted brown traces as a neutral library color instead of a saturated one of similar lightness; a code-drawn test of gray and brown patches with a black, light and blue library in `crates/trace`. From 1ead2bf80979458bf76b4d057efeefb7f1ef6ba7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:07:43 -0800 Subject: [PATCH 2/5] Image Trace: seam fills on a stretched image stay within 0.75 image px of their edge On an image stretched more one way than another, a seam stroke was as wide as 1.5 pixels at the larger scale, so across the less stretched direction it reached far past its edge: on a 40 x 20 image scaled 20x across, a stroke along a horizontal edge covered 15 pixels on each side, over transparent rows too. On such an image, the seam fills are now each stroke's outline in image pixels (butt caps, round joins), filled with the stroke's paint. An image scaled alike in every direction keeps strokes. The anchor limit counts the outlines' anchors. Outline views and Expand by color recognize a seam fills group of filled outlines as they do one of strokes, and Expand by color again recognizes the unclipped seam fills group of a trace made before the seam fills were clipped. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/buildcmds/trace.rs | 189 ++++++++++++++++++----- crates/engine/src/tests/build.rs | 124 ++++++++++++--- crates/render/src/renderer/nodes.rs | 10 +- docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 6 files changed, 261 insertions(+), 71 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 817a34f6c8..7a0aa54d32 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path, clipped to the image's box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index e1b524dc8d..3288883013 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -26,17 +26,26 @@ fn is_trace_group(n: &Node) -> bool { const SEAM_FILLS_NAME: &str = "Seam Fills"; /// Whether `n` can be a trace's seam fills group: a clip group named as one, or a clip group whose -/// members after the clipping path are stroked paths without fills, so that it is still found -/// after it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) +/// members after the clipping path are all stroked paths without fills, or all filled paths +/// without strokes (the strokes' outlines, on a stretched image), so that it is still found after +/// it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) Traces made +/// before the seam fills were clipped hold a group without a clip: one named as seam fills, or one +/// of stroked paths without fills. (Auto Grouping groups hold filled paths.) fn is_seam_fills(n: &Node) -> bool { - let stroke_only = |m: &Arc| { - matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) - && m.appearance.fill_paint() == Paint::None - && m.appearance.stroke_paint() != Paint::None - }; - let NodeKind::Group { clip: true, children } = &n.kind else { return false }; - n.name.as_deref() == Some(SEAM_FILLS_NAME) - || children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(stroke_only)) + let path = |m: &Arc| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); + let stroke_only = |m: &Arc| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None; + let fill_only = |m: &Arc| path(m) && m.appearance.fill_paint() != Paint::None && m.appearance.stroke_paint() == Paint::None; + let named = n.name.as_deref() == Some(SEAM_FILLS_NAME); + match &n.kind { + NodeKind::Group { clip: true, children } => { + named + || children + .split_first() + .is_some_and(|(_, members)| !members.is_empty() && (members.iter().all(stroke_only) || members.iter().all(fill_only))) + } + NodeKind::Group { clip: false, children } => named || (!children.is_empty() && children.iter().all(stroke_only)), + _ => false, + } } const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor"; @@ -668,19 +677,75 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64 return Err(EngineError::Cancelled); } let size = (raster.width, raster.height); - let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS); + let outlined = seam_unit(raster_xf(&inputs.image, size)).is_none(); + let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS, outlined); Ok(Traced { inputs: inputs.clone(), raster: size, res, seams }) } +/// Pixel space of a `size` raster decoded from `img` → the image object's pixel space → document. +fn raster_xf(img: &ImageObject, size: (u32, u32)) -> vectorcraft_geom::Affine { + let sx = img.width.max(1) as f64 / size.0.max(1) as f64; + let sy = img.height.max(1) as f64 / size.1.max(1) as f64; + img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy) +} + +/// Document units per raster pixel for the seam fills' strokes when `xf` scales every direction +/// alike, so that a stroke 1.5 pixels wide covers 0.75 pixels on each side of its edge at any +/// angle; `None` when `xf` stretches one direction more than another (or is degenerate), where a +/// stroke of any one width would cover more pixels across some edges than across others. +fn seam_unit(xf: vectorcraft_geom::Affine) -> Option { + let [a, b, c, d, _, _] = xf.as_coeffs(); + let (t, det) = (a * a + b * b + c * c + d * d, a * d - b * c); + let root = (t * t - 4.0 * det * det).max(0.0).sqrt(); + let (most, least) = (((t + root) / 2.0).sqrt(), ((t - root).max(0.0) / 2.0).sqrt()); + (most.is_finite() && most > 0.0 && most - least <= 1e-9 * most).then_some(most) +} + /// The seam fills of `res`, traced with `params` from a `size` raster ([`tr::seam_fills`]), while -/// the paths, the seam fills' strokes and their clip together stay within `max` anchors: the -/// strokes have at most as many anchors as the paths and the clip has four, so a trace whose paths -/// have more than half of `max` less two gets none. -fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, size: (u32, u32), max: usize) -> Option { +/// the paths, the seam fills and their clip together stay within `max` anchors. With `outlined`, +/// each stroke is replaced by a filled path, its outline in raster pixels ([`outlined_seam`]), +/// for an image stretched more one way than another ([`seam_unit`]). The strokes have at most as +/// many anchors as the paths and the clip has four, so a trace whose paths have more than half of +/// `max` less two gets none. Outlines, which have more anchors, are counted as each is made, and +/// none is made when [`SEAM_OUTLINE_ANCHORS`] times the strokes' anchors would not fit, or once +/// those made so far no longer fit. +fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, size: (u32, u32), max: usize, outlined: bool) -> Option { if res.anchor_count().saturating_mul(2).saturating_add(4) > max { return None; } - tr::seam_fills(&res.paths, params, size) + let mut seams = tr::seam_fills(&res.paths, params, size)?; + if outlined { + let strokes = seams.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); + let estimate = strokes.saturating_mul(SEAM_OUTLINE_ANCHORS).saturating_add(seams.clip.anchor_count()); + if res.anchor_count().saturating_add(estimate) > max { + return None; + } + let mut total = res.anchor_count().saturating_add(seams.clip.anchor_count()); + for tp in &mut seams.strokes { + outlined_seam(tp); + total = total.saturating_add(tp.path.anchor_count()); + if total > max { + return None; + } + } + seams.strokes.retain(|tp| !tp.path.is_empty()); + if seams.strokes.is_empty() { + return None; + } + } + Some(seams) +} + +/// About how many anchors a seam stroke's outline ([`outlined_seam`]) has for each anchor of the +/// stroke: both sides of each segment and a round join at each anchor. Curves can take more. +const SEAM_OUTLINE_ANCHORS: usize = 6; + +/// Replace a seam stroke `tp` by the area it covers, as a filled path in the same raster pixels: +/// butt caps and round joins, as the strokes have. +fn outlined_seam(tp: &mut tr::TracedPath) { + if let Some(width) = tp.stroke.take() { + tp.path = vectorcraft_pathops::outline_stroke(&tp.path, width, vectorcraft_pathops::Cap::Butt, vectorcraft_pathops::Join::Round, 4.0); + } } /// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`] @@ -767,19 +832,12 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result> = seam_fills .iter() .flat_map(|f| &f.strokes) .filter_map(|tp| { - let width = tp.stroke?; - let mut n = shape_node(d, tp.path.transformed(xf), None); - n.appearance = Appearance { - items: vec![AppearanceItem::Stroke(StrokeLayer { - cap: LineCap::Butt, - join: LineJoin::Round, - ..StrokeLayer::new(paint_of(tp), width * seam_unit) - })], - ..Default::default() + let outline = match (tp.stroke, seam_unit) { + (Some(width), Some(u)) => { + let mut n = shape_node(d, tp.path.transformed(xf), None); + n.appearance = Appearance { + items: vec![AppearanceItem::Stroke(StrokeLayer { + cap: LineCap::Butt, + join: LineJoin::Round, + ..StrokeLayer::new(paint_of(tp), width * u) + })], + ..Default::default() + } + .into(); + return Some(Arc::new(n)); + } + (Some(_), None) => { + let mut outlined = tp.clone(); + outlined_seam(&mut outlined); + outlined.path + } + (None, _) => tp.path.clone(), + }; + if outline.is_empty() { + return None; } - .into(); + let mut n = shape_node(d, outline.transformed(xf), None); + n.appearance = fill_only(paint_of(tp)).into(); Some(Arc::new(n)) }) .collect(); @@ -1187,7 +1260,7 @@ mod color_group_tests { #[cfg(test)] mod trace_limit_tests { - use super::{MAX_TRACE_ANCHORS, keep_warnings, seams_within, trace_warnings}; + use super::{MAX_TRACE_ANCHORS, SEAM_OUTLINE_ANCHORS, keep_warnings, seams_within, trace_warnings}; use vectorcraft_trace as tr; #[test] @@ -1205,9 +1278,43 @@ mod trace_limit_tests { let anchors = res.anchor_count(); assert!(anchors + all.as_ref().map_or(0, tr::SeamFills::anchor_count) <= 2 * anchors + 4); // Twice the paths' anchors and the clip's four leave room for any seam fills. - assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 4), all); + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 4, false), all); // One anchor short of that: none. - assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 3), None); + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 3, false), None); + // Outlined, the seam fills are filled paths, within SEAM_OUTLINE_ANCHORS of the strokes' + // anchors each. + let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); + let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true).unwrap(); + assert!(outlined.strokes.iter().all(|tp| tp.stroke.is_none() && !tp.path.is_empty()), "{outlined:?}"); + let n = strokes(all.as_ref().unwrap()); + assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); + // A staircase edge: the outline's round joins give it more anchors than the paths have. The + // outlines are made only when SEAM_OUTLINE_ANCHORS times the strokes' anchors fit. + let img = tr::Raster::from_fn(32, 32, |x, y| if x < y / 4 * 4 + 4 { [200, 40, 50, 255] } else { [30, 90, 200, 255] }); + let params = tr::TraceParams { corners: 100.0, ..params }; + let res = tr::trace(&img, ¶ms); + let anchors = res.anchor_count(); + let all = tr::seam_fills(&res.paths, ¶ms, (32, 32)).unwrap(); + let n = strokes(&all); + let outlined = seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true).unwrap(); + assert!(strokes(&outlined) > anchors, "{} outline anchors, {anchors} in the paths", strokes(&outlined)); + assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); + let fits = anchors + SEAM_OUTLINE_ANCHORS * n + 4; + assert!(fits > 2 * anchors + 4, "{fits}, {anchors} in the paths"); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits, true), Some(outlined)); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, true), None); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, false), Some(all)); + } + + #[test] + fn seams_are_strokes_only_where_the_image_is_scaled_alike_every_way() { + use vectorcraft_geom::Affine; + assert_eq!(super::seam_unit(Affine::scale(2.0)), Some(2.0)); + let turned = super::seam_unit(Affine::rotate(0.7) * Affine::scale(3.0)).unwrap(); + assert!((turned - 3.0).abs() < 1e-9, "{turned}"); + assert_eq!(super::seam_unit(Affine::scale_non_uniform(20.0, 1.0)), None); + assert_eq!(super::seam_unit(Affine::scale_non_uniform(1.0, 0.0)), None); + assert_eq!(super::seam_unit(Affine::scale(0.0)), None); } #[test] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 00b6ff4efd..99cf65cdff 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -6133,13 +6133,6 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { // Overlapping paths are stacked: no seam fills. let (s, _, r) = made("overlapping", "imageTrace.make", false); assert!(seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).is_none()); - // An image stretched 3× across and squeezed to half height: 1.5 pixels at the larger scale. - let mut s = session(); - add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5)); - let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); - let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap(); - let AppearanceItem::Stroke(layer) = &group.children().unwrap()[1].appearance.items[0] else { panic!("{group:?}") }; - assert!((layer.width - 4.5).abs() < 1e-9, "{}", layer.width); // White left out: the strokes are still clipped to the image's box. let band = vectorcraft_trace::Raster::from_fn(24, 16, |x, y| match ((4..12).contains(&y), x < 12) { (false, _) => [255; 4], @@ -6162,6 +6155,92 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { assert!([cb.x0, cb.y0, cb.x1 - 24.0, cb.y1 - 16.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); } +/// On an image stretched more one way than another, the seam fills are the strokes' outlines in +/// image pixels, filled: on an image stretched 20× across, the one along a horizontal edge covers +/// 0.75 image pixels on each side of it, as on an image scaled alike both ways, and does not reach +/// across the transparent rows above the edge. +#[test] +fn image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge() { + // Red beside blue, the edge between them anti-aliased, on an image stretched 3× across and + // squeezed to half height: the outline is 1.5 pixels (4.5 points) across the vertical edge. + let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| { + let share = (16.4 - f64::from(x)).clamp(0.0, 1.0); + let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8; + [mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255] + }); + let mut s = session(); + add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5)); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let n = node(&s, NodeId(r["id"].as_u64().unwrap())); + let kids = n.children().unwrap(); + assert_eq!(kids[1].name.as_deref(), Some("Seam Fills")); + let fill = &kids[1].children().unwrap()[1]; + assert_eq!(fill.appearance.stroke_paint(), Paint::None, "{:?}", fill.appearance); + assert_eq!(fill.appearance.fill_paint(), kids[2].appearance.fill_paint(), "the lower path's color"); + let bb = outline(fill).0.bounds().unwrap(); + assert!((bb.width() - 4.5).abs() < 0.05 && bb.y0.abs() < 1e-6 && (bb.y1 - 10.0).abs() < 1e-6, "{bb:?}"); + // Rows 0 to 5 transparent, 5 to 10 red, 10 to 20 blue. + let art = vectorcraft_trace::Raster::from_fn(40, 20, |_, y| match y { + 0..5 => [0, 0, 0, 0], + 5..10 => [200, 30, 30, 255], + _ => [30, 30, 200, 255], + }); + let mut s = session(); + add_image(&mut s, &art, Affine::scale_non_uniform(20.0, 1.0)); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let n = node(&s, NodeId(r["id"].as_u64().unwrap())); + let group = n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned().unwrap(); + let (_, members) = group.children().unwrap().split_first().unwrap(); + assert!(!members.is_empty(), "{group:?}"); + for m in members { + // What the member covers: its outline, grown by half its stroke's width. + let half = m.appearance.items.iter().fold(0.0_f64, |w, it| match it { + AppearanceItem::Stroke(l) => w.max(l.width / 2.0), + _ => w, + }); + let bb = outline(m).0.bounds().unwrap(); + let (y0, y1) = (bb.y0 - half, bb.y1 + half); + assert!(y0 > 9.25 - 1e-6 && y1 < 10.75 + 1e-6, "covers y {y0} to {y1}: {m:?}"); + } + // Renamed, the group of filled outlines is still the seam fills: Expand by color keeps it under + // every color's group. + s.execute("layer.setProps", &json!({"id": group.id.0, "name": "Edges"})).unwrap(); + s.execute("imageTrace.expand", &json!({"id": n.id.0, "byColor": true})).unwrap(); + assert_eq!(node(&s, n.id).children().unwrap()[0].id, group.id); +} + +/// A trace made before the seam fills were clipped holds them in a group without a clip: Expand by +/// color keeps that group under every color's group too, named or renamed. +#[test] +fn image_trace_expand_by_color_keeps_unclipped_seam_fills() { + let art = vectorcraft_trace::Raster::from_fn(40, 20, |x, _| { + let share = (16.4 - f64::from(x)).clamp(0.0, 1.0); + let mix = |a: f64, b: f64| (a * share + b * (1.0 - share)).round() as u8; + [mix(200.0, 30.0), mix(40.0, 90.0), mix(50.0, 200.0), 255] + }); + for name in [Some("Seam Fills"), None] { + let mut s = session(); + add_image(&mut s, &art, Affine::scale(2.0)); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let g = NodeId(r["id"].as_u64().unwrap()); + // The seam fills as such a trace holds them: the strokes alone, in a plain group. + let seams = node(&s, g).children().unwrap()[1].clone(); + let NodeKind::Group { clip: true, children } = &seams.kind else { panic!("{seams:?}") }; + let mut legacy = Node::group(seams.id, children[1..].to_vec()); + legacy.name = name.map(Into::into); + s.edit("legacy", |d, _| { + let NodeKind::Group { children, .. } = &mut d.node_mut(g).unwrap().kind else { panic!("trace group") }; + children[1] = Arc::new(legacy); + Ok(()) + }) + .unwrap(); + s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap(); + let kids = node(&s, g).children().unwrap().clone(); + assert_eq!(kids.len(), 3, "{name:?}: {kids:?}"); + assert_eq!(kids[0].id, seams.id, "{name:?}"); + } +} + /// Expand by color: each color's paths in a group of their own, named by the color, the groups /// stacked by the lowest path in each and the art drawn as before; Release to Layers then gives a /// sublayer for each color. @@ -7223,28 +7302,31 @@ fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { } /// Outline views draw the traced paths' outlines and leave out an Abutting trace's seam fills -/// (their clipping box and strokes). +/// (their clipping box and strokes, or on a stretched image the strokes' filled outlines). #[test] fn image_trace_outline_view_leaves_out_the_seam_fills() { - let mut s = session(); - // Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×. + // Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×, + // then 2× across and 2.5× down. let art = vectorcraft_trace::Raster::from_fn(60, 40, |x, y| match ((10..50).contains(&x) && (10..30).contains(&y), x < 30) { (false, _) => [0, 0, 0, 0], (true, true) => [200, 30, 30, 255], (true, false) => [30, 30, 200, 255], }); - add_image(&mut s, &art, Affine::translate((50.0, 50.0)) * Affine::scale(2.0)); - let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); - let g = NodeId(r["id"].as_u64().unwrap()); - assert!(node(&s, g).children().unwrap().iter().any(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })), "seam fills"); - s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlines"})).unwrap(); - let screen = render_doc(&s, true); - // The image's top edge (y = 50), away from the art: nothing drawn. - for x in [60, 110, 160] { - assert!(screen.pixel(x, 50)[0] > 245 && screen.pixel(x, 51)[0] > 245, "x = {x}: {:?}", screen.pixel(x, 50)); + for scale in [Affine::scale(2.0), Affine::scale_non_uniform(2.0, 2.5)] { + let mut s = session(); + add_image(&mut s, &art, Affine::translate((50.0, 50.0)) * scale); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let g = NodeId(r["id"].as_u64().unwrap()); + assert!(node(&s, g).children().unwrap().iter().any(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })), "seam fills"); + s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlines"})).unwrap(); + let screen = render_doc(&s, true); + // The image's top edge (y = 50), away from the art: nothing drawn. + for x in [60, 110, 160] { + assert!(screen.pixel(x, 50)[0] > 245 && screen.pixel(x, 51)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 50)); + } + // The art's left edge (x = 70) is outlined. + assert!((68..=72).any(|x| screen.pixel(x, 90)[0] < 128), "{scale:?}"); } - // The art's left edge (x = 70) is outlined. - assert!((68..=72).any(|x| screen.pixel(x, 90)[0] < 128)); } /// #569: merging the regions of a rosette of unfilled ellipses (each off the centre, petals diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index c3dae5c07f..d259e637f1 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -654,16 +654,16 @@ impl Renderer { let opts = RenderOptions { outline: true, ..f.opts.clone() }; let frame = Frame { opts: &opts, ..*f }; // An Abutting trace's seam fills hold no traced outline: a clip group named "Seam Fills" - // of stroked paths without fills. + // of paths that are each stroked without a fill or (on a stretched image, the strokes' + // outlines) filled without a stroke. let seam_fills = |c: &Arc| { - let stroke_only = |m: &Arc| { + let one_paint = |m: &Arc| { matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) - && m.appearance.fill_paint().is_none() - && !m.appearance.stroke_paint().is_none() + && m.appearance.fill_paint().is_none() != m.appearance.stroke_paint().is_none() }; c.name.as_deref() == Some("Seam Fills") && matches!(&c.kind, NodeKind::Group { clip: true, children } - if children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(stroke_only))) + if children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(one_paint))) }; for c in shapes.iter().filter(|c| !seam_fills(c)) { self.draw_outline_member(ctx, &frame, c); diff --git a/docs/mcp.md b/docs/mcp.md index 47569c5492..471efe995d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3832,8 +3832,9 @@ already walks Image Trace. Short agent entry points: An Abutting trace with Fills (not Flat Logo) also holds a clip group named `Seam Fills` under its paths. For each color it holds one stroke along the edges where a filled path of that color meets a filled path drawn after it, in that color (a gradient path's stroke takes its gradient), with butt caps and round joins. The stroke is 1.5 image - pixels wide, VectorCraft's own width, at the image's larger scale when the image is stretched more one way. The group - clips the strokes to the image's box. Where a shared edge ends at, or runs within 0.75 image pixels of, a transparent + pixels wide, VectorCraft's own width. On an image stretched more one way than another, the group holds each stroke's + outline in image pixels as a filled path instead; the outline covers 0.75 image pixels on each side of its edge. The + group clips the strokes to the image's box. Where a shared edge ends at, or runs within 0.75 image pixels of, a transparent area or a color left out, its stroke can reach up to 0.75 image pixels into that area. Paths that became live shapes (`shapes`) take no part. The traced paths and their shared edges are the same with or without the group. A trace whose paths have more than about half of the trace's anchor limit (8,000,000, 2,000,000 on the web) has no seam diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6c0866af32..217de41cd7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1510,7 +1510,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Document Library color groups:** with Document Swatches, the panel's Colors menu and `"colorGroup"` trace with one color group's colors instead of every swatch, as the public panel documentation describes Document Library; code-drawn tests in `crates/engine` and the panel. - **Image Trace, Document Library colors:** with Document Swatches, traced fills and strokes use the displayed colors of process, global, spot and tint swatches without links, so editing a swatch leaves the trace unchanged; swatch-library colors are also unlinked; code-drawn tests in `crates/engine`. - **Image Trace, flattened slivers:** in a Color, Grayscale or Black and White trace with Fills, a traced region whose outline straightens onto one line (a single pixel, or a one-pixel row along an edge, its pieces shared with the regions beside it) is left out instead of becoming a selectable path with no area, which paints nothing. Snap Curves To Lines straightens more outlines, so it leaves out more of these. Without Fills, the region's 1 px stroke draws it, and it is kept. Code-drawn tests in `crates/trace`. -- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` clip group under its paths, with strokes along the edges two filled paths share, in the lower path's color, 1.5 image pixels wide (VectorCraft's own width) and clipped to the image's box. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` in `crates/engine`. +- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` clip group under its paths, with strokes along the edges two filled paths share, in the lower path's color, 1.5 image pixels wide (VectorCraft's own width) and clipped to the image's box; on an image stretched more one way than another, each stroke's outline in image pixels is a filled path instead. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` and `image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge` in `crates/engine`. - **Image Trace, Auto Color rare colours:** the Automatic palette keeps colours too rare for its area count when they are distinct (Oklab) and drawn as coherent regions, at most six, protected from mixed-colour merging and Noise; code-drawn stem, highlight, low-contrast and scattered-noise tests (see [quality notes](image-trace-quality.md#auto-color-keeps-rare-colours)). - **Image Trace, nearly flat dark grounds:** with a Limited palette of 9 to 16 colors (16 Colors, and Document Library without swatches), by VectorCraft's own rule, a cut whose two sides both have a dark gray mean (Oklab lightness under 0.30, chroma under 0.03) and lie less than 0.03 apart in Oklab has its gain scaled by (distance / 0.03)². A near-black ground with faint noise then traces in one color, and the color it would have taken goes to another cut. Code-drawn tests `a_nearly_flat_dark_ground_keeps_one_color`, `only_a_limited_palette_of_nine_to_sixteen_colors_weighs_alike_sides` and `a_dark_colored_figure_on_a_nearly_flat_dark_ground_keeps_its_color` in `crates/trace`. - **Image Trace, Document Library keeps neutral tones neutral:** each pixel takes the library color nearest in Oklab with differences in hue and chroma counted three times, so a gray or a muted brown traces as a neutral library color instead of a saturated one of similar lightness; a code-drawn test of gray and brown patches with a black, light and blue library in `crates/trace`. From c207c08edb07d54a75de6b7867c7e73c41650390 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 14:02:29 -0800 Subject: [PATCH 3/5] Image Trace: seam strokes on images scaled alike, and canceling while outlining Whether a trace's seam fills are strokes or outlines now depends on the image object's own transform. A raster decoded scaled down to fit has its two sides rounded separately, so it was scaled a little differently across and down and every such trace got outlines. The stroke width now uses the smaller scale of the raster, so a stroke still covers at most 0.75 pixels on each side of its edge. The check for an even scale compares the axes' lengths and angle directly, without a square root of a small difference. Outlining the seam strokes now stops when the trace is canceled, checking every 64 strokes. A stroke that reaches the make step without an outline on a stretched image is left out rather than outlined outside the anchor limit. docs/mcp.md: the group clips the strokes or outlines. --- crates/engine/src/cmd/buildcmds/trace.rs | 160 ++++++++++++++++------- crates/engine/src/tests/build.rs | 14 +- docs/mcp.md | 20 +-- 3 files changed, 135 insertions(+), 59 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 3288883013..8e470f56cd 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -677,8 +677,8 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64 return Err(EngineError::Cancelled); } let size = (raster.width, raster.height); - let outlined = seam_unit(raster_xf(&inputs.image, size)).is_none(); - let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS, outlined); + let outlined = seam_unit(inputs.image.xf, raster_xf(&inputs.image, size)).is_none(); + let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS, outlined, steps)?; Ok(Traced { inputs: inputs.clone(), raster: size, res, seams }) } @@ -689,51 +689,94 @@ fn raster_xf(img: &ImageObject, size: (u32, u32)) -> vectorcraft_geom::Affine { img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy) } -/// Document units per raster pixel for the seam fills' strokes when `xf` scales every direction -/// alike, so that a stroke 1.5 pixels wide covers 0.75 pixels on each side of its edge at any -/// angle; `None` when `xf` stretches one direction more than another (or is degenerate), where a -/// stroke of any one width would cover more pixels across some edges than across others. -fn seam_unit(xf: vectorcraft_geom::Affine) -> Option { +/// Whether `xf` scales every direction alike (turning and mirroring allowed): its axes keep equal +/// lengths and stay at right angles. +fn scales_alike(xf: vectorcraft_geom::Affine) -> bool { let [a, b, c, d, _, _] = xf.as_coeffs(); - let (t, det) = (a * a + b * b + c * c + d * d, a * d - b * c); - let root = (t * t - 4.0 * det * det).max(0.0).sqrt(); - let (most, least) = (((t + root) / 2.0).sqrt(), ((t - root).max(0.0) / 2.0).sqrt()); - (most.is_finite() && most > 0.0 && most - least <= 1e-9 * most).then_some(most) + let (across, down) = (a * a + b * b, c * c + d * d); + let t = across + down; + t.is_finite() && t > 0.0 && (across - down).abs() <= 1e-9 * t && (a * c + b * d).abs() <= 1e-9 * t +} + +/// The smallest length that `xf` scales a unit vector to (its smaller singular value): the +/// difference of the lengths of its turning part and its stretching part. +fn least_scale(xf: vectorcraft_geom::Affine) -> f64 { + let [a, b, c, d, _, _] = xf.as_coeffs(); + let turning = ((a + d) / 2.0).hypot((b - c) / 2.0); + let stretching = ((a - d) / 2.0).hypot((b + c) / 2.0); + (turning - stretching).abs() +} + +/// Document units per raster pixel for the seam fills' strokes when the image object's transform +/// `img_xf` scales every direction alike: the smaller scale of the raster-to-document transform +/// `xf`, so that a stroke 1.5 pixels wide covers at most 0.75 pixels on each side of its edge at +/// any angle. (A raster decoded scaled down to fit can be scaled a little differently across and +/// down, as each side is rounded.) `None` when `img_xf` stretches one direction more than another +/// or is degenerate, where a stroke of any one width would cover more pixels across some edges +/// than across others. +fn seam_unit(img_xf: vectorcraft_geom::Affine, xf: vectorcraft_geom::Affine) -> Option { + let least = least_scale(xf); + (scales_alike(img_xf) && least.is_finite() && least > 0.0).then_some(least) } /// The seam fills of `res`, traced with `params` from a `size` raster ([`tr::seam_fills`]), while /// the paths, the seam fills and their clip together stay within `max` anchors. With `outlined`, -/// each stroke is replaced by a filled path, its outline in raster pixels ([`outlined_seam`]), +/// each stroke is replaced by a filled path, its outline in raster pixels ([`outline_seams`]), /// for an image stretched more one way than another ([`seam_unit`]). The strokes have at most as /// many anchors as the paths and the clip has four, so a trace whose paths have more than half of /// `max` less two gets none. Outlines, which have more anchors, are counted as each is made, and /// none is made when [`SEAM_OUTLINE_ANCHORS`] times the strokes' anchors would not fit, or once -/// those made so far no longer fit. -fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, size: (u32, u32), max: usize, outlined: bool) -> Option { +/// those made so far no longer fit. [`EngineError::Cancelled`] once `steps` answers `false`. +fn seams_within( + res: &tr::TraceResult, + params: &tr::TraceParams, + size: (u32, u32), + max: usize, + outlined: bool, + steps: &(dyn Fn(u64, u64) -> bool + Sync), +) -> Result> { if res.anchor_count().saturating_mul(2).saturating_add(4) > max { - return None; + return Ok(None); } - let mut seams = tr::seam_fills(&res.paths, params, size)?; + let Some(mut seams) = tr::seam_fills(&res.paths, params, size) else { return Ok(None) }; if outlined { let strokes = seams.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); let estimate = strokes.saturating_mul(SEAM_OUTLINE_ANCHORS).saturating_add(seams.clip.anchor_count()); if res.anchor_count().saturating_add(estimate) > max { - return None; + return Ok(None); } - let mut total = res.anchor_count().saturating_add(seams.clip.anchor_count()); - for tp in &mut seams.strokes { - outlined_seam(tp); - total = total.saturating_add(tp.path.anchor_count()); - if total > max { - return None; - } + let budget = max.saturating_sub(res.anchor_count()).saturating_sub(seams.clip.anchor_count()); + if !outline_seams(&mut seams.strokes, budget, steps)? { + return Ok(None); } seams.strokes.retain(|tp| !tp.path.is_empty()); if seams.strokes.is_empty() { - return None; + return Ok(None); } } - Some(seams) + Ok(Some(seams)) +} + +/// How many seam strokes [`outline_seams`] outlines between asking whether to go on. +const SEAM_OUTLINE_STEP: usize = 64; + +/// Outline each of `strokes` ([`outlined_seam`]) while the outlines' anchors stay within `budget`, +/// asking `steps` every [`SEAM_OUTLINE_STEP`] strokes whether to go on → whether every outline +/// fits (it stops at the first that does not), or [`EngineError::Cancelled`] once `steps` +/// answers `false`. +fn outline_seams(strokes: &mut [tr::TracedPath], budget: usize, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result { + let mut total = 0usize; + for (i, tp) in strokes.iter_mut().enumerate() { + if i % SEAM_OUTLINE_STEP == 0 && !steps(0, 0) { + return Err(EngineError::Cancelled); + } + outlined_seam(tp); + total = total.saturating_add(tp.path.anchor_count()); + if total > budget { + return Ok(false); + } + } + Ok(true) } /// About how many anchors a seam stroke's outline ([`outlined_seam`]) has for each anchor of the @@ -837,7 +880,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result { - let mut outlined = tp.clone(); - outlined_seam(&mut outlined); - outlined.path - } + // The trace leaves strokes only for an image scaled alike in every direction, + // with these same inputs; a stroke is left out here rather than outlined + // outside the anchor limit. + (Some(_), None) => return None, (None, _) => tp.path.clone(), }; if outline.is_empty() { @@ -1260,7 +1302,7 @@ mod color_group_tests { #[cfg(test)] mod trace_limit_tests { - use super::{MAX_TRACE_ANCHORS, SEAM_OUTLINE_ANCHORS, keep_warnings, seams_within, trace_warnings}; + use super::{MAX_TRACE_ANCHORS, SEAM_OUTLINE_ANCHORS, keep_warnings, outline_seams, seams_within, trace_warnings}; use vectorcraft_trace as tr; #[test] @@ -1277,14 +1319,15 @@ mod trace_limit_tests { assert!(all.is_some(), "{res:?}"); let anchors = res.anchor_count(); assert!(anchors + all.as_ref().map_or(0, tr::SeamFills::anchor_count) <= 2 * anchors + 4); + let go = |_: u64, _: u64| true; // Twice the paths' anchors and the clip's four leave room for any seam fills. - assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 4, false), all); + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 4, false, &go).unwrap(), all); // One anchor short of that: none. - assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 3, false), None); + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 3, false, &go).unwrap(), None); // Outlined, the seam fills are filled paths, within SEAM_OUTLINE_ANCHORS of the strokes' // anchors each. let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); - let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true).unwrap(); + let outlined = seams_within(&res, ¶ms, (24, 16), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap(); assert!(outlined.strokes.iter().all(|tp| tp.stroke.is_none() && !tp.path.is_empty()), "{outlined:?}"); let n = strokes(all.as_ref().unwrap()); assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); @@ -1296,25 +1339,50 @@ mod trace_limit_tests { let anchors = res.anchor_count(); let all = tr::seam_fills(&res.paths, ¶ms, (32, 32)).unwrap(); let n = strokes(&all); - let outlined = seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true).unwrap(); + let outlined = seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap(); assert!(strokes(&outlined) > anchors, "{} outline anchors, {anchors} in the paths", strokes(&outlined)); assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); let fits = anchors + SEAM_OUTLINE_ANCHORS * n + 4; assert!(fits > 2 * anchors + 4, "{fits}, {anchors} in the paths"); - assert_eq!(seams_within(&res, ¶ms, (32, 32), fits, true), Some(outlined)); - assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, true), None); - assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, false), Some(all)); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits, true, &go).unwrap(), Some(outlined.clone())); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, true, &go).unwrap(), None); + assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, false, &go).unwrap(), Some(all.clone())); + // The outlines are counted as each is made: they stop at the first one past the budget, so + // outlines with more anchors than the estimate allows are refused too. + let need = strokes(&outlined); + assert!(outline_seams(&mut all.strokes.clone(), need, &go).unwrap()); + assert!(!outline_seams(&mut all.strokes.clone(), need - 1, &go).unwrap()); + // Canceled while outlining: the run stops. + let stop = |_: u64, _: u64| false; + assert!(matches!(seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &stop), Err(super::EngineError::Cancelled))); + assert!(matches!(outline_seams(&mut all.strokes.clone(), need, &stop), Err(super::EngineError::Cancelled))); } #[test] fn seams_are_strokes_only_where_the_image_is_scaled_alike_every_way() { + use super::seam_unit; use vectorcraft_geom::Affine; - assert_eq!(super::seam_unit(Affine::scale(2.0)), Some(2.0)); - let turned = super::seam_unit(Affine::rotate(0.7) * Affine::scale(3.0)).unwrap(); - assert!((turned - 3.0).abs() < 1e-9, "{turned}"); - assert_eq!(super::seam_unit(Affine::scale_non_uniform(20.0, 1.0)), None); - assert_eq!(super::seam_unit(Affine::scale_non_uniform(1.0, 0.0)), None); - assert_eq!(super::seam_unit(Affine::scale(0.0)), None); + assert_eq!(seam_unit(Affine::scale(2.0), Affine::scale(2.0)), Some(2.0)); + assert_eq!(seam_unit(Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0]), Affine::new([-2.0, 0.0, 0.0, 2.0, 5.0, 7.0])), Some(2.0)); + // Turned and scaled alike at any angle, rounding included. + for k in [0.5, 1.0, 3.0, 17.0] { + for i in 0..2000 { + let xf = Affine::rotate(f64::from(i) * std::f64::consts::TAU / 2000.0) * Affine::scale(k); + let unit = seam_unit(xf, xf); + assert!(unit.is_some_and(|u| (u - k).abs() < 1e-9 * k), "{unit:?} at step {i}, scale {k}"); + } + } + let xf = Affine::rotate(0.0496) * Affine::scale(0.5); + assert!(seam_unit(xf, xf).is_some()); + // A raster decoded scaled down to fit (10000 × 7000 pixels as 9791 × 6853) of an image placed + // at 2×: strokes, at the smaller scale. + let (sx, sy) = (10000.0 / 9791.0, 7000.0 / 6853.0); + let unit = seam_unit(Affine::scale(2.0), Affine::scale(2.0) * Affine::scale_non_uniform(sx, sy)).unwrap(); + assert!((unit - 2.0 * f64::min(sx, sy)).abs() < 1e-12, "{unit}"); + assert_eq!(seam_unit(Affine::scale_non_uniform(20.0, 1.0), Affine::scale_non_uniform(20.0, 1.0)), None); + assert_eq!(seam_unit(Affine::skew(0.5, 0.0), Affine::skew(0.5, 0.0)), None); + assert_eq!(seam_unit(Affine::scale_non_uniform(1.0, 0.0), Affine::scale_non_uniform(1.0, 0.0)), None); + assert_eq!(seam_unit(Affine::scale(0.0), Affine::scale(0.0)), None); } #[test] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 99cf65cdff..d4b3d47df7 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -7306,18 +7306,26 @@ fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { #[test] fn image_trace_outline_view_leaves_out_the_seam_fills() { // Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×, - // then 2× across and 2.5× down. + // or 2× across and 2.5× down. let art = vectorcraft_trace::Raster::from_fn(60, 40, |x, y| match ((10..50).contains(&x) && (10..30).contains(&y), x < 30) { (false, _) => [0, 0, 0, 0], (true, true) => [200, 30, 30, 255], (true, false) => [30, 30, 200, 255], }); - for scale in [Affine::scale(2.0), Affine::scale_non_uniform(2.0, 2.5)] { + for (scale, stretched) in [(Affine::scale(2.0), false), (Affine::scale_non_uniform(2.0, 2.5), true)] { let mut s = session(); add_image(&mut s, &art, Affine::translate((50.0, 50.0)) * scale); let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); let g = NodeId(r["id"].as_u64().unwrap()); - assert!(node(&s, g).children().unwrap().iter().any(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })), "seam fills"); + let seams = + node(&s, g).children().unwrap().iter().find(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })).cloned().expect("seam fills"); + // Strokes, or on the stretched image their outlines, filled. + let members = &seams.children().unwrap()[1..]; + assert!(!members.is_empty()); + for m in members { + let (fill, stroke) = (m.appearance.fill_paint(), m.appearance.stroke_paint()); + assert_eq!((fill != Paint::None, stroke != Paint::None), (stretched, !stretched), "{scale:?}: {fill:?}, {stroke:?}"); + } s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlines"})).unwrap(); let screen = render_doc(&s, true); // The image's top edge (y = 50), away from the art: nothing drawn. diff --git a/docs/mcp.md b/docs/mcp.md index 471efe995d..6d6caa3015 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3832,16 +3832,16 @@ already walks Image Trace. Short agent entry points: An Abutting trace with Fills (not Flat Logo) also holds a clip group named `Seam Fills` under its paths. For each color it holds one stroke along the edges where a filled path of that color meets a filled path drawn after it, in that color (a gradient path's stroke takes its gradient), with butt caps and round joins. The stroke is 1.5 image - pixels wide, VectorCraft's own width. On an image stretched more one way than another, the group holds each stroke's - outline in image pixels as a filled path instead; the outline covers 0.75 image pixels on each side of its edge. The - group clips the strokes to the image's box. Where a shared edge ends at, or runs within 0.75 image pixels of, a transparent - area or a color left out, its stroke can reach up to 0.75 image pixels into that area. Paths that became live shapes - (`shapes`) take no part. The traced paths and their shared edges are the same with or without the group. A trace - whose paths have more than about half of the trace's anchor limit (8,000,000, 2,000,000 on the web) has no seam - fills. Both Expand commands keep the group, and `byColor` leaves it under every color's group; `byColor` refuses a - trace whose seam fills' group was moved above a path. The strokes are separate objects, in a trace and after Expand: - recoloring, moving or deleting a traced path leaves them as they are, and deleting the group removes them. The - reply's `paths` and `anchors` count the traced paths only. + pixels wide, VectorCraft's own width. On an image stretched more one way than another, the group holds each + stroke's outline in image pixels as a filled path instead; the outline covers 0.75 image pixels on each side of its + edge. The group clips the strokes or outlines to the image's box. Where a shared edge ends at, or runs within 0.75 + image pixels of, a transparent area or a color left out, its stroke can reach up to 0.75 image pixels into that + area. Paths that became live shapes (`shapes`) take no part. The traced paths and their shared edges are the same + with or without the group. A trace whose paths have more than about half of the trace's anchor limit (8,000,000, + 2,000,000 on the web) has no seam fills. Both Expand commands keep the group, and `byColor` leaves it under every + color's group; `byColor` refuses a trace whose seam fills' group was moved above a path. The strokes are separate + objects, in a trace and after Expand: recoloring, moving or deleting a traced path leaves them as they are, and + deleting the group removes them. The reply's `paths` and `anchors` count the traced paths only. With `keepColors` in `params`, the reply's `warnings` name each listed color that no traced color matches, and say when nothing was traced. `imageTrace.presets.save {name?, newName?, preset?, enhanced?, params?}` saves tracing settings as a preset kept with From dbf0927385f2a31e718c501b9daad4e63c7d80b6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 14:31:51 -0800 Subject: [PATCH 4/5] Image Trace: the seam fills' clip stays within the traced paths' box The Seam Fills group's clipping path was the image's box. A group with a clip is measured by its clipping path, so on a trace with transparent or ignored margins the expanded trace measured as the whole image, and selection, alignment and resizing used that box. The clipping path is now the image's box cut to the box of the traced paths: on a turned image it has up to eight corners, and the anchor limit counts eight for it. docs/mcp.md, the params text and the progress line describe the clip. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/buildcmds/trace.rs | 100 +++++++++++++++++------ crates/engine/src/tests/build.rs | 44 ++++++---- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 5 files changed, 111 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 7a0aa54d32..d523577ae8 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 8e470f56cd..a2ac857903 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -723,10 +723,11 @@ fn seam_unit(img_xf: vectorcraft_geom::Affine, xf: vectorcraft_geom::Affine) -> /// the paths, the seam fills and their clip together stay within `max` anchors. With `outlined`, /// each stroke is replaced by a filled path, its outline in raster pixels ([`outline_seams`]), /// for an image stretched more one way than another ([`seam_unit`]). The strokes have at most as -/// many anchors as the paths and the clip has four, so a trace whose paths have more than half of -/// `max` less two gets none. Outlines, which have more anchors, are counted as each is made, and -/// none is made when [`SEAM_OUTLINE_ANCHORS`] times the strokes' anchors would not fit, or once -/// those made so far no longer fit. [`EngineError::Cancelled`] once `steps` answers `false`. +/// many anchors as the paths and the clip at most [`SEAM_CLIP_ANCHORS`], so a trace whose paths +/// have more than half of `max` less four gets none. Outlines, which have more anchors, are +/// counted as each is made, and none is made when [`SEAM_OUTLINE_ANCHORS`] times the strokes' +/// anchors would not fit, or once those made so far no longer fit. [`EngineError::Cancelled`] +/// once `steps` answers `false`. fn seams_within( res: &tr::TraceResult, params: &tr::TraceParams, @@ -735,17 +736,17 @@ fn seams_within( outlined: bool, steps: &(dyn Fn(u64, u64) -> bool + Sync), ) -> Result> { - if res.anchor_count().saturating_mul(2).saturating_add(4) > max { + if res.anchor_count().saturating_mul(2).saturating_add(SEAM_CLIP_ANCHORS) > max { return Ok(None); } let Some(mut seams) = tr::seam_fills(&res.paths, params, size) else { return Ok(None) }; if outlined { let strokes = seams.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); - let estimate = strokes.saturating_mul(SEAM_OUTLINE_ANCHORS).saturating_add(seams.clip.anchor_count()); + let estimate = strokes.saturating_mul(SEAM_OUTLINE_ANCHORS).saturating_add(SEAM_CLIP_ANCHORS); if res.anchor_count().saturating_add(estimate) > max { return Ok(None); } - let budget = max.saturating_sub(res.anchor_count()).saturating_sub(seams.clip.anchor_count()); + let budget = max.saturating_sub(res.anchor_count()).saturating_sub(SEAM_CLIP_ANCHORS); if !outline_seams(&mut seams.strokes, budget, steps)? { return Ok(None); } @@ -757,6 +758,10 @@ fn seams_within( Ok(Some(seams)) } +/// The most anchors the seam fills' clip has: the image's box cut to the box of the traced paths +/// ([`within_box`]), four corners and at most four more where the image is turned. +const SEAM_CLIP_ANCHORS: usize = 8; + /// How many seam strokes [`outline_seams`] outlines between asking whether to go on. const SEAM_OUTLINE_STEP: usize = 64; @@ -913,7 +918,8 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result> = seam_fills .iter() .flat_map(|f| &f.strokes) @@ -946,16 +952,6 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result = f.clip.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| xf * a.p)).collect(); + let inside = within_box(&corners, art); + if inside.len() >= 3 { + let mut clip = shape_node(d, vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&inside, true)), None); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let members = std::iter::once(Arc::new(clip)).chain(strokes).collect(); + let mut g = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + g.name = Some(SEAM_FILLS_NAME.into()); + children.push(Arc::new(g)); + } + } children.extend(grouped(d, traced, &res.parents)); if group_by_color { children = color_groups(c, d, children)?; @@ -1003,6 +1016,28 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Vec { + let sides: [&dyn Fn(Point) -> f64; 4] = [&|p| p.x - r.x0, &|p| r.x1 - p.x, &|p| p.y - r.y0, &|p| r.y1 - p.y]; + let mut out = poly.to_vec(); + for side in sides { + let corners = std::mem::take(&mut out); + for (k, &p) in corners.iter().enumerate() { + let Some(&q) = corners.get((k + 1) % corners.len()) else { continue }; + let (dp, dq) = (side(p), side(q)); + if dp >= 0.0 { + out.push(p); + } + if (dp > 0.0 && dq < 0.0) || (dp < 0.0 && dq > 0.0) { + out.push(p + (q - p) * (dp / (dp - dq))); + } + } + } + out +} + /// Images larger than this on a side are traced, but more slowly: the trace says so. pub const LARGE_TRACE_SIDE: u32 = 1500; @@ -1302,7 +1337,7 @@ mod color_group_tests { #[cfg(test)] mod trace_limit_tests { - use super::{MAX_TRACE_ANCHORS, SEAM_OUTLINE_ANCHORS, keep_warnings, outline_seams, seams_within, trace_warnings}; + use super::{MAX_TRACE_ANCHORS, SEAM_CLIP_ANCHORS, SEAM_OUTLINE_ANCHORS, keep_warnings, outline_seams, seams_within, trace_warnings}; use vectorcraft_trace as tr; #[test] @@ -1318,12 +1353,12 @@ mod trace_limit_tests { let all = tr::seam_fills(&res.paths, ¶ms, (24, 16)); assert!(all.is_some(), "{res:?}"); let anchors = res.anchor_count(); - assert!(anchors + all.as_ref().map_or(0, tr::SeamFills::anchor_count) <= 2 * anchors + 4); + assert!(anchors + all.as_ref().map_or(0, tr::SeamFills::anchor_count) <= 2 * anchors + SEAM_CLIP_ANCHORS); let go = |_: u64, _: u64| true; - // Twice the paths' anchors and the clip's four leave room for any seam fills. - assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 4, false, &go).unwrap(), all); + // Twice the paths' anchors and the clip's eight at most leave room for any seam fills. + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS, false, &go).unwrap(), all); // One anchor short of that: none. - assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + 3, false, &go).unwrap(), None); + assert_eq!(seams_within(&res, ¶ms, (24, 16), 2 * anchors + SEAM_CLIP_ANCHORS - 1, false, &go).unwrap(), None); // Outlined, the seam fills are filled paths, within SEAM_OUTLINE_ANCHORS of the strokes' // anchors each. let strokes = |f: &tr::SeamFills| f.strokes.iter().map(|tp| tp.path.anchor_count()).sum::(); @@ -1342,8 +1377,8 @@ mod trace_limit_tests { let outlined = seams_within(&res, ¶ms, (32, 32), MAX_TRACE_ANCHORS, true, &go).unwrap().unwrap(); assert!(strokes(&outlined) > anchors, "{} outline anchors, {anchors} in the paths", strokes(&outlined)); assert!(strokes(&outlined) <= SEAM_OUTLINE_ANCHORS * n, "{} outline anchors, {n} stroke anchors", strokes(&outlined)); - let fits = anchors + SEAM_OUTLINE_ANCHORS * n + 4; - assert!(fits > 2 * anchors + 4, "{fits}, {anchors} in the paths"); + let fits = anchors + SEAM_OUTLINE_ANCHORS * n + SEAM_CLIP_ANCHORS; + assert!(fits > 2 * anchors + SEAM_CLIP_ANCHORS, "{fits}, {anchors} in the paths"); assert_eq!(seams_within(&res, ¶ms, (32, 32), fits, true, &go).unwrap(), Some(outlined.clone())); assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, true, &go).unwrap(), None); assert_eq!(seams_within(&res, ¶ms, (32, 32), fits - 1, false, &go).unwrap(), Some(all.clone())); @@ -1358,6 +1393,21 @@ mod trace_limit_tests { assert!(matches!(outline_seams(&mut all.strokes.clone(), need, &stop), Err(super::EngineError::Cancelled))); } + #[test] + fn within_box_cuts_a_turned_box_to_a_box() { + use vectorcraft_geom::{Point, Rect}; + // A square turned by 45° in a smaller box: each side cuts a corner off, 8 corners. + let diamond = [Point::new(0.0, -10.0), Point::new(10.0, 0.0), Point::new(0.0, 10.0), Point::new(-10.0, 0.0)]; + let cut = super::within_box(&diamond, Rect::new(-6.0, -6.0, 6.0, 6.0)); + assert_eq!(cut.len(), 8, "{cut:?}"); + assert!(cut.iter().all(|p| p.x.abs() <= 6.0 + 1e-12 && p.y.abs() <= 6.0 + 1e-12 && p.x.abs() + p.y.abs() <= 10.0 + 1e-12), "{cut:?}"); + // A corner on a side is kept once. + let square = [Point::new(0.0, 0.0), Point::new(4.0, 0.0), Point::new(4.0, 4.0), Point::new(0.0, 4.0)]; + assert_eq!(super::within_box(&square, Rect::new(0.0, 0.0, 4.0, 4.0)), square.to_vec()); + assert_eq!(super::within_box(&square, Rect::new(1.0, 0.0, 4.0, 4.0)).len(), 4); + assert!(super::within_box(&square, Rect::new(5.0, 5.0, 6.0, 6.0)).is_empty()); + } + #[test] fn seams_are_strokes_only_where_the_image_is_scaled_alike_every_way() { use super::seam_unit; diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index d4b3d47df7..722cee04fe 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -6133,26 +6133,40 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { // Overlapping paths are stacked: no seam fills. let (s, _, r) = made("overlapping", "imageTrace.make", false); assert!(seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).is_none()); - // White left out: the strokes are still clipped to the image's box. +} + +/// With white left out, the seam fills are clipped to the image's box within the traced paths' +/// box, so the expanded trace measures as its paths do, also on a turned image. +#[test] +fn image_trace_seam_fills_stay_within_the_traced_paths_box() { + let seams = |n: &Node| n.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Seam Fills")).cloned(); let band = vectorcraft_trace::Raster::from_fn(24, 16, |x, y| match ((4..12).contains(&y), x < 12) { (false, _) => [255; 4], (true, true) => [200, 30, 30, 255], (true, false) => [30, 30, 200, 255], }); - let mut s = session(); - add_image(&mut s, &band, Affine::IDENTITY); - let r = s - .execute( - "imageTrace.make", - &json!({"params": {"mode": "color", "palette": "limited", "colors": 3, "method": "abutting", "ignoreWhite": true}}), - ) - .unwrap(); - assert_eq!(r["paths"], 2, "{r}"); - let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap(); - let clip = &group.children().unwrap()[0]; - assert!(matches!(clip.kind, NodeKind::Path { .. }), "{clip:?}"); - let cb = outline(clip).0.bounds().unwrap(); - assert!([cb.x0, cb.y0, cb.x1 - 24.0, cb.y1 - 16.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); + for xf in [Affine::IDENTITY, Affine::translate((100.0, 100.0)) * Affine::rotate(0.5)] { + let mut s = session(); + add_image(&mut s, &band, xf); + let r = s + .execute( + "imageTrace.makeAndExpand", + &json!({"params": {"mode": "color", "palette": "limited", "colors": 3, "method": "abutting", "ignoreWhite": true}}), + ) + .unwrap(); + assert_eq!(r["paths"], 2, "{r}"); + let n = node(&s, NodeId(r["id"].as_u64().unwrap())); + let group = seams(&n).unwrap(); + let clip = &group.children().unwrap()[0]; + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}"); + let cb = outline(clip).0.bounds().unwrap(); + let paths = n.children().unwrap()[1..].iter().filter_map(|c| c.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert_eq!(n.geometric_bounds(), Some(paths), "{xf:?}"); + assert!(cb.x0 >= paths.x0 - 1e-9 && cb.y0 >= paths.y0 - 1e-9 && cb.x1 <= paths.x1 + 1e-9 && cb.y1 <= paths.y1 + 1e-9, "{xf:?}: {cb:?}"); + if xf == Affine::IDENTITY { + assert!([cb.x0, cb.y0 - 4.0, cb.x1 - 24.0, cb.y1 - 12.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); + } + } } /// On an image stretched more one way than another, the seam fills are the strokes' outlines in diff --git a/docs/mcp.md b/docs/mcp.md index 6d6caa3015..31536f4d6c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3834,10 +3834,11 @@ already walks Image Trace. Short agent entry points: that color (a gradient path's stroke takes its gradient), with butt caps and round joins. The stroke is 1.5 image pixels wide, VectorCraft's own width. On an image stretched more one way than another, the group holds each stroke's outline in image pixels as a filled path instead; the outline covers 0.75 image pixels on each side of its - edge. The group clips the strokes or outlines to the image's box. Where a shared edge ends at, or runs within 0.75 - image pixels of, a transparent area or a color left out, its stroke can reach up to 0.75 image pixels into that - area. Paths that became live shapes (`shapes`) take no part. The traced paths and their shared edges are the same - with or without the group. A trace whose paths have more than about half of the trace's anchor limit (8,000,000, + edge. The group clips the strokes or outlines to the image's box within the box of the traced paths, and its + bounds lie within that box. Where a shared edge ends at, or runs within 0.75 image pixels of, a + transparent area or a color left out, its stroke can reach up to 0.75 image pixels into that area. Paths that + became live shapes (`shapes`) take no part. The traced paths and their shared edges are the same with or without + the group. A trace whose paths have more than about half of the trace's anchor limit (8,000,000, 2,000,000 on the web) has no seam fills. Both Expand commands keep the group, and `byColor` leaves it under every color's group; `byColor` refuses a trace whose seam fills' group was moved above a path. The strokes are separate objects, in a trace and after Expand: recoloring, moving or deleting a traced path leaves them as they are, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 217de41cd7..b52bcc7b5c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1510,7 +1510,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Document Library color groups:** with Document Swatches, the panel's Colors menu and `"colorGroup"` trace with one color group's colors instead of every swatch, as the public panel documentation describes Document Library; code-drawn tests in `crates/engine` and the panel. - **Image Trace, Document Library colors:** with Document Swatches, traced fills and strokes use the displayed colors of process, global, spot and tint swatches without links, so editing a swatch leaves the trace unchanged; swatch-library colors are also unlinked; code-drawn tests in `crates/engine`. - **Image Trace, flattened slivers:** in a Color, Grayscale or Black and White trace with Fills, a traced region whose outline straightens onto one line (a single pixel, or a one-pixel row along an edge, its pieces shared with the regions beside it) is left out instead of becoming a selectable path with no area, which paints nothing. Snap Curves To Lines straightens more outlines, so it leaves out more of these. Without Fills, the region's 1 px stroke draws it, and it is kept. Code-drawn tests in `crates/trace`. -- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` clip group under its paths, with strokes along the edges two filled paths share, in the lower path's color, 1.5 image pixels wide (VectorCraft's own width) and clipped to the image's box; on an image stretched more one way than another, each stroke's outline in image pixels is a filled path instead. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` and `image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge` in `crates/engine`. +- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` clip group under its paths, with strokes along the edges two filled paths share, in the lower path's color, 1.5 image pixels wide (VectorCraft's own width) and clipped to the image's box within the traced paths' box; on an image stretched more one way than another, each stroke's outline in image pixels is a filled path instead. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` and `image_trace_seam_fills_on_a_stretched_image_stay_near_their_edge` in `crates/engine`. - **Image Trace, Auto Color rare colours:** the Automatic palette keeps colours too rare for its area count when they are distinct (Oklab) and drawn as coherent regions, at most six, protected from mixed-colour merging and Noise; code-drawn stem, highlight, low-contrast and scattered-noise tests (see [quality notes](image-trace-quality.md#auto-color-keeps-rare-colours)). - **Image Trace, nearly flat dark grounds:** with a Limited palette of 9 to 16 colors (16 Colors, and Document Library without swatches), by VectorCraft's own rule, a cut whose two sides both have a dark gray mean (Oklab lightness under 0.30, chroma under 0.03) and lie less than 0.03 apart in Oklab has its gain scaled by (distance / 0.03)². A near-black ground with faint noise then traces in one color, and the color it would have taken goes to another cut. Code-drawn tests `a_nearly_flat_dark_ground_keeps_one_color`, `only_a_limited_palette_of_nine_to_sixteen_colors_weighs_alike_sides` and `a_dark_colored_figure_on_a_nearly_flat_dark_ground_keeps_its_color` in `crates/trace`. - **Image Trace, Document Library keeps neutral tones neutral:** each pixel takes the library color nearest in Oklab with differences in hue and chroma counted three times, so a gray or a muted brown traces as a neutral library color instead of a saturated one of similar lightness; a code-drawn test of gray and brown patches with a black, light and blue library in `crates/trace`. From b1b5e86e5756c9ec49a8a237942598bab60de0b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:56:01 -0800 Subject: [PATCH 5/5] Image Trace: Outline view leaves out renamed seam fills Outline views left out an Abutting trace's seam fills only while their clip group kept the name "Seam Fills". Renamed, the group drew its clipping box and, on a stretched image, the outlines of its filled seam bands. The group is now also left out when it is still the lowest traced shape, where the trace puts it. The outline-view test samples inside the seam band beside the shared edge on the stretched image, and checks that renaming the group leaves the view unchanged. --- crates/engine/src/tests/build.rs | 11 ++++++++++- crates/render/src/renderer/nodes.rs | 13 +++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 91c1ad7814..46821e7173 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -7737,7 +7737,8 @@ fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { } /// Outline views draw the traced paths' outlines and leave out an Abutting trace's seam fills -/// (their clipping box and strokes, or on a stretched image the strokes' filled outlines). +/// (their clipping box and strokes, or on a stretched image the strokes' filled outlines), renamed +/// too. #[test] fn image_trace_outline_view_leaves_out_the_seam_fills() { // Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×, @@ -7769,6 +7770,14 @@ fn image_trace_outline_view_leaves_out_the_seam_fills() { } // The art's left edge (x = 70) is outlined. assert!((68..=72).any(|x| screen.pixel(x, 90)[0] < 128), "{scale:?}"); + // Beside the red and blue paths' shared edge (x = 110), inside the seam band (1.5 units + // each side on the stretched image) but off the traced outlines (x = 109 and 110): nothing. + for x in [108, 111] { + assert!(screen.pixel(x, 100)[0] > 245, "{scale:?}, x = {x}: {:?}", screen.pixel(x, 100)); + } + // Renamed, the group is still left out: the view draws as it did. + s.execute("layer.setProps", &json!({"id": seams.id.0, "name": "Edges"})).unwrap(); + assert!(render_doc(&s, true).pixels == screen.pixels, "{scale:?}: renamed seam fills drawn"); } } diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index d259e637f1..8e18b3a045 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -653,19 +653,20 @@ impl Renderer { if view.shows_outlines() { let opts = RenderOptions { outline: true, ..f.opts.clone() }; let frame = Frame { opts: &opts, ..*f }; - // An Abutting trace's seam fills hold no traced outline: a clip group named "Seam Fills" - // of paths that are each stroked without a fill or (on a stretched image, the strokes' - // outlines) filled without a stroke. - let seam_fills = |c: &Arc| { + // An Abutting trace's seam fills hold no traced outline: a clip group of paths that are + // each stroked without a fill or (on a stretched image, the strokes' outlines) filled + // without a stroke, named "Seam Fills" or, renamed, still the lowest shape, where the + // trace puts it. + let seam_fills = |i: usize, c: &Arc| { let one_paint = |m: &Arc| { matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && m.appearance.fill_paint().is_none() != m.appearance.stroke_paint().is_none() }; - c.name.as_deref() == Some("Seam Fills") + (i == 0 || c.name.as_deref() == Some("Seam Fills")) && matches!(&c.kind, NodeKind::Group { clip: true, children } if children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(one_paint))) }; - for c in shapes.iter().filter(|c| !seam_fills(c)) { + for (_, c) in shapes.iter().enumerate().filter(|(i, c)| !seam_fills(*i, c)) { self.draw_outline_member(ctx, &frame, c); } }