mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 12:03:31 +00:00
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.
This commit is contained in:
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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)
|
||||
),
|
||||
|
||||
@@ -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<Node>| {
|
||||
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<Node>| matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
|
||||
let stroke_only = |m: &Arc<Node>| path(m) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None;
|
||||
let fill_only = |m: &Arc<Node>| 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<f64> {
|
||||
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<tr::SeamFills> {
|
||||
/// 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<tr::SeamFills> {
|
||||
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::<usize>();
|
||||
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<Val
|
||||
let TraceInputs { target, image: img, .. } = inputs;
|
||||
let mut warnings = keep_warnings(&trace, &res);
|
||||
warnings.extend(trace_warnings((img.width, img.height), raster, res.worked_at));
|
||||
// Pixel space of the decoded raster → the image object's pixel space → document.
|
||||
let sx = img.width.max(1) as f64 / raster.0.max(1) as f64;
|
||||
let sy = img.height.max(1) as f64 / raster.1.max(1) as f64;
|
||||
let xf = img.xf * vectorcraft_geom::Affine::scale_non_uniform(sx, sy);
|
||||
let xf = raster_xf(&img, raster);
|
||||
// Document units per raster pixel (stroke widths).
|
||||
let unit = xf.determinant().abs().sqrt();
|
||||
// Seam fills: document units per raster pixel along the direction the image is stretched most,
|
||||
// so that a stroke covers its pixels across an edge at any angle.
|
||||
let seam_unit = {
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (t, det) = (a * a + b * b + c * c + d * d, a * d - b * c);
|
||||
((t + (t * t - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
|
||||
};
|
||||
// Seam fills: strokes when the image is scaled alike in every direction; on an image stretched
|
||||
// more one way, the trace outlined them in raster pixels ([`seams_within`]).
|
||||
let seam_unit = seam_unit(xf);
|
||||
let (npaths, anchors, colors) = (res.paths.len(), res.anchor_count(), res.palette.len());
|
||||
let label = if expand { "Image Trace (Make and Expand)" } else { "Image Trace" };
|
||||
// A library color fills with the swatch's displayed color (its model kept), unlinked.
|
||||
@@ -812,22 +870,37 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
tp.gradient.as_ref().map_or(solid, |g| traced_gradient(g, xf))
|
||||
};
|
||||
// Abutting: the seam fills, in a clip group of their own under every path, clipped to the
|
||||
// image's box.
|
||||
// image's box: strokes, or on an image stretched more one way, their outlines filled.
|
||||
let strokes: Vec<Arc<Node>> = 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::<usize>();
|
||||
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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Node>| {
|
||||
let stroke_only = |m: &Arc<Node>| {
|
||||
let one_paint = |m: &Arc<Node>| {
|
||||
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);
|
||||
|
||||
+3
-2
@@ -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
|
||||
|
||||
@@ -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`.
|
||||
|
||||
Reference in New Issue
Block a user