mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 15:26:12 +00:00
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.
This commit is contained in:
@@ -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<f64> {
|
||||
/// 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<f64> {
|
||||
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<tr::SeamFills> {
|
||||
/// 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<Option<tr::SeamFills>> {
|
||||
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::<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;
|
||||
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<bool> {
|
||||
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<Val
|
||||
let unit = xf.determinant().abs().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 seam_unit = seam_unit(img.xf, 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.
|
||||
@@ -889,11 +932,10 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
.into();
|
||||
return Some(Arc::new(n));
|
||||
}
|
||||
(Some(_), None) => {
|
||||
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::<usize>();
|
||||
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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
+10
-10
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user