diff --git a/crates/engine/src/cmd/conceptvector.rs b/crates/engine/src/cmd/conceptvector.rs index 10180b3fdd..469c0c1080 100644 --- a/crates/engine/src/cmd/conceptvector.rs +++ b/crates/engine/src/cmd/conceptvector.rs @@ -469,7 +469,13 @@ fn providers(s: &mut Session, _: &Value) -> Result { fn generate(s: &mut Session, p: &Value) -> Result { let run = ConceptRun::prepare(s, p)?; - let made = run.run(&|_, _| true).map_err(provider_error)?; + // A script's run stops when the script is asked to stop, and keeps no job. + let stop = s.script_in_run.then(|| s.script_interrupt()); + let stopped = || stop.as_ref().is_some_and(|i| i.is_set()); + let made = run.run(&|_, _| !stopped()).map_err(provider_error)?; + if stopped() { + return Err(EngineError::Cancelled); + } run.finish(s, made).ok_or(EngineError::NoDocument) } diff --git a/crates/engine/src/concept_vector/offline.rs b/crates/engine/src/concept_vector/offline.rs index f97bf823c2..57c569e13d 100644 --- a/crates/engine/src/concept_vector/offline.rs +++ b/crates/engine/src/concept_vector/offline.rs @@ -7,10 +7,11 @@ use std::sync::Arc; -use vectorcraft_geom::Affine; +use vectorcraft_geom::kurbo::common::solve_cubic; +use vectorcraft_geom::{Affine, Anchor, CubicBez, ParamCurve, PathData, Point, SubPath}; use vectorcraft_trace as tr; -use super::{Capabilities, MAX_ANCHORS, Output, Parts, ProviderError, Request, Steps, Style, Variation, VectorPath}; +use super::{Capabilities, MAX_ANCHORS, MAX_PATHS, Output, Parts, ProviderError, Request, Steps, Style, Variation, VectorPath}; /// The built-in provider's id. pub const ID: &str = "offline.traceStyles"; @@ -156,12 +157,12 @@ impl super::Provider for TraceStyles { let go_on = |_: u64, _: u64| steps(i as u64, total); let res = tr::trace_watched(&image.raster, p, left, &go_on).map_err(trace_error)?; left = left.saturating_sub(res.anchor_count()); - out.push(image.variation(style, res)); + out.push(image.variation(style, p, res)); } if !steps(total, total) { return Err(ProviderError::Canceled); } - Ok(out) + Ok(with_seams(out)) } /// The image decoded in the first part; then for each style, its color layers found in one @@ -219,21 +220,149 @@ impl Decoded { Ok(Self { raster: Arc::new(raster), back, unit, warnings }) } - /// The variation of `style` that the trace `res` of this image makes. - fn variation(&self, style: &str, res: tr::TraceResult) -> Variation { - let paths = res - .paths - .into_iter() - .map(|tp| { - let path = tp.path.transformed(self.back); - match tp.stroke { - Some(w) => VectorPath { path, fill: None, stroke: Some((tp.color, w * self.unit)), square_caps: tp.square_caps }, - None => VectorPath { path, fill: Some(tp.color), stroke: None, square_caps: false }, - } - }) - .collect(); - Variation { style: style.to_string(), paths, warnings: self.warnings.clone() } + /// The variation of `style` that the trace `res` of this image, made with `params`, makes, and + /// the seam fills of an Abutting trace with fills ([`tr::seam_fills`]) kept inside the image + /// ([`within_image`]), for [`with_seams`] to lay under its paths. + fn variation(&self, style: &str, params: &tr::TraceParams, res: tr::TraceResult) -> Made { + let size = (self.raster.width, self.raster.height); + let seams = tr::seam_fills(&res.paths, params, size).map_or_else(Vec::new, |s| { + s.strokes.into_iter().map(|tp| within_image(tp, size)).filter(|tp| !tp.path.subpaths.is_empty()).map(|tp| self.vector_path(tp)).collect() + }); + let paths = res.paths.into_iter().map(|tp| self.vector_path(tp)).collect(); + Made { variation: Variation { style: style.to_string(), paths, warnings: self.warnings.clone() }, seams } } + + /// Traced path `tp` in the image's own pixels. + fn vector_path(&self, tp: tr::TracedPath) -> VectorPath { + let path = tp.path.transformed(self.back); + match tp.stroke { + Some(w) => VectorPath { path, fill: None, stroke: Some((tp.color, w * self.unit)), square_caps: tp.square_caps }, + None => VectorPath { path, fill: Some(tp.color), stroke: None, square_caps: false }, + } + } +} + +/// A variation made, and the seam fills to lay under its paths. +pub(super) struct Made { + pub(super) variation: Variation, + pub(super) seams: Vec, +} + +/// [`with_seams_within`] [`MAX_ANCHORS`] and [`MAX_PATHS`]. +fn with_seams(made: Vec) -> Vec { + with_seams_within(made, MAX_ANCHORS, MAX_PATHS) +} + +/// The variations `made`, each with its seam fills under its paths, in order, while they fit in +/// the `max_anchors` anchors and `max_paths` paths (each subpath counted as one) left once every +/// variation is counted: the traced paths of every style come first, and a style whose seam fills +/// do not fit goes without them. +pub(super) fn with_seams_within(made: Vec, max_anchors: usize, max_paths: usize) -> Vec { + let subpaths = |paths: &[VectorPath]| paths.iter().map(|p| p.path.subpaths.len().max(1)).sum::(); + let mut anchors = made.iter().map(|m| m.variation.anchors()).sum::(); + let mut paths = made.iter().map(|m| subpaths(&m.variation.paths)).sum::(); + made.into_iter() + .map(|Made { mut variation, seams }| { + let (more_anchors, more_paths) = (seams.iter().map(|p| p.path.anchor_count()).sum::(), subpaths(&seams)); + if !seams.is_empty() && anchors.saturating_add(more_anchors) <= max_anchors && paths.saturating_add(more_paths) <= max_paths { + anchors += more_anchors; + paths += more_paths; + variation.paths.splice(0..0, seams); + } + variation + }) + .collect() +} + +/// Seam stroke `tp` of a `size` raster trimmed to half its width inside the raster's border, +/// so that its stroke, round caps and round joins stay inside the image. The pieces left form +/// open runs; a closed subpath left whole stays closed. +fn within_image(mut tp: tr::TracedPath, size: (u32, u32)) -> tr::TracedPath { + let half = tp.stroke.unwrap_or_default() / 2.0; + let (w, h) = (f64::from(size.0), f64::from(size.1)); + let mut runs: Vec = vec![]; + if !half.is_finite() || half < 0.0 || half * 2.0 > w || half * 2.0 > h { + tp.path = PathData::new(runs); + return tp; + } + let inside = |p: Point| p.x >= half && p.y >= half && p.x <= w - half && p.y <= h - half; + let clamp = |p: Point| Point::new(p.x.clamp(half, w - half), p.y.clamp(half, h - half)); + for sp in &tp.path.subpaths { + let count = sp.segment_count(); + let mut pieces = vec![]; + for k in 0..count { + let c = sp.segment(k); + let mut cuts = vec![0.0, 1.0]; + if ![c.p0, c.p1, c.p2, c.p3].into_iter().all(inside) { + for (p0, p1, p2, p3, side) in [ + (c.p0.x, c.p1.x, c.p2.x, c.p3.x, half), + (c.p0.x, c.p1.x, c.p2.x, c.p3.x, w - half), + (c.p0.y, c.p1.y, c.p2.y, c.p3.y, half), + (c.p0.y, c.p1.y, c.p2.y, c.p3.y, h - half), + ] { + // Intersections with the sides' supporting lines also cover corner crossings. + cuts.extend( + solve_cubic(p0 - side, 3.0 * (p1 - p0), 3.0 * (p0 - 2.0 * p1 + p2), p3 - p0 + 3.0 * (p1 - p2)) + .into_iter() + .filter(|&t| t > 0.0 && t < 1.0), + ); + } + cuts.sort_by(f64::total_cmp); + cuts.dedup(); + } + for pair in cuts.windows(2) { + let (t0, t1) = (pair[0], pair[1]); + pieces.push((k, t0, t1, inside(c.eval(t0 + (t1 - t0) / 2.0)))); + } + } + if pieces.iter().all(|&(_, _, _, kept)| kept) { + if count > 0 { + runs.push(sp.clone()); + } + continue; + } + // Start after a piece left out, so that a run across a closed subpath's first anchor + // stays one run. + let start = if sp.closed { pieces.iter().position(|&(_, _, _, kept)| !kept).map_or(0, |k| k + 1) } else { 0 }; + let mut run: Vec = vec![]; + for j in 0..pieces.len() { + let (k, t0, t1, kept) = pieces[(start + j) % pieces.len()]; + if kept { + let (Some(&a), Some(&b)) = (sp.anchors.get(k), sp.anchors.get((k + 1) % sp.anchors.len())) else { continue }; + let c = sp.segment(k); + let mut c = if t0 == 0.0 && t1 == 1.0 { c } else { c.subsegment(t0..t1) }; + // Remove roundoff at the cut endpoints without constraining the curve's handles. + c.p0 = clamp(c.p0); + c.p3 = clamp(c.p3); + if sp.segment_is_line(k) { + c = CubicBez::new(c.p0, c.p0, c.p3, c.p3); + } + if let Some(last) = run.last_mut() { + last.h_out = c.p1; + } else { + let a = if t0 == 0.0 { a } else { Anchor::corner(c.p0) }; + run.push(Anchor { p: c.p0, h_in: c.p0, h_out: c.p1, ..a }); + } + let b = if t1 == 1.0 { b } else { Anchor::corner(c.p3) }; + run.push(Anchor { p: c.p3, h_in: c.p2, h_out: c.p3, ..b }); + } else if !run.is_empty() { + runs.push(open_run(std::mem::take(&mut run))); + } + } + if !run.is_empty() { + runs.push(open_run(run)); + } + } + tp.path = PathData::new(runs); + tp +} + +/// An open run of anchors: the last one has no handle out. +fn open_run(mut run: Vec) -> SubPath { + if let Some(last) = run.last_mut() { + last.h_out = last.p; + } + SubPath::new(run, false) } /// [`TraceStyles`]' variations made a part at a time. @@ -244,7 +373,7 @@ struct TraceParts { trace: Option, /// The anchor points the styles not made yet may have. left: usize, - out: Vec, + out: Vec, /// The variations or an error have been given. ended: bool, } @@ -272,7 +401,7 @@ impl TraceParts { self.image = Some(Decoded::new(&self.request)?); return Ok(None); }; - let Some(style) = self.request.styles.get(self.out.len()) else { return Ok(Some(std::mem::take(&mut self.out))) }; + let Some(style) = self.request.styles.get(self.out.len()) else { return Ok(Some(with_seams(std::mem::take(&mut self.out)))) }; let trace = match &mut self.trace { Some(t) => t, None => { @@ -282,11 +411,12 @@ impl TraceParts { }; let Some(res) = trace.step().map_err(trace_error)? else { return Ok(None) }; self.trace = None; + let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?; self.left = self.left.saturating_sub(res.anchor_count()); - self.out.push(image.variation(style, res)); + self.out.push(image.variation(style, ¶ms, res)); if self.out.len() < self.request.styles.len() { return Ok(None); } - Ok(Some(std::mem::take(&mut self.out))) + Ok(Some(with_seams(std::mem::take(&mut self.out)))) } } diff --git a/crates/engine/src/concept_vector/tests.rs b/crates/engine/src/concept_vector/tests.rs index b53a0ab2f1..8fb74cab4d 100644 --- a/crates/engine/src/concept_vector/tests.rs +++ b/crates/engine/src/concept_vector/tests.rs @@ -423,6 +423,143 @@ fn malformed_results_panics_and_cancels_keep_no_job_and_change_nothing() { assert_eq!(run.run(&stop_later), Err(ProviderError::Canceled)); } +/// A script asked to stop stops a generate it runs, which keeps no job and changes nothing. +#[test] +fn a_stopped_script_stops_generate_and_keeps_no_job() { + let (mut s, _) = doc_with(&art()); + let (before, depth) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + s.script_in_run = true; + let stop = s.script_interrupt(); + stop.set(); + let r = generate(&mut s, json!({"provider": ID, "styles": ["flatColor"]})); + stop.clear(); + s.script_in_run = false; + assert!(matches!(r, Err(crate::EngineError::Cancelled)), "{r:?}"); + assert!(s.doc().unwrap().doc == before && undo_len(&s) == depth); + assert!(s.execute("conceptVector.results", &json!({"job": 1})).is_err(), "no job kept"); + // Outside a script, the same request makes its job. + assert_eq!(generate(&mut s, json!({"provider": ID, "styles": ["flatColor"]})).unwrap()["state"], "done"); +} + +/// Flat Color's abutting fills get seam fills under them: strokes in the colors of the fills, +/// before every fill. Detailed Color stacks its fills and gets none. +#[test] +fn flat_color_lays_seam_fills_under_its_abutting_fills() { + let raster = art(); + let req = |style: &str| Request { + image: Arc::new(raster.encode_png()), + width: raster.width, + height: raster.height, + prompt: None, + styles: vec![style.to_string()], + detail: 50, + output: Output::Vector, + }; + let made = |style: &str| offline::TraceStyles.generate(&req(style), &|_, _| true).unwrap().remove(0); + let flat = made("flatColor"); + check_result(&req("flatColor"), std::slice::from_ref(&flat)).unwrap(); + let seams = flat.paths.iter().take_while(|p| p.fill.is_none()).count(); + assert!(seams > 0, "no seam fills"); + let fills: Vec<_> = flat.paths.iter().skip(seams).map(|p| p.fill).collect(); + assert!(!fills.is_empty() && fills.iter().all(Option::is_some), "the fills follow the seam fills"); + let fill_colors: std::collections::BTreeSet<_> = fills.into_iter().flatten().collect(); + for p in flat.paths.iter().take(seams) { + let (color, width) = p.stroke.expect("a seam fill is a stroke"); + assert!(fill_colors.contains(&color) && width > 0.0, "{color:?} {width}"); + } + let detailed = made("detailedColor"); + assert!(!detailed.paths.is_empty() && detailed.paths.iter().all(|p| p.stroke.is_none()), "stacked fills get no seam fills"); +} + +/// Seam fills are laid only in what the traced paths of every style leave of the limits, in the +/// styles' order: a style whose seam fills do not fit goes without them, and a later trace never +/// fails for an earlier style's seam fills. +#[test] +fn seam_fills_fit_in_what_every_styles_paths_leave() { + let line = |n: usize, fill: Option<[u8; 3]>, stroke: Option<([u8; 3], f64)>| VectorPath { + path: PathData::single(SubPath::polyline(&(0..n).map(|i| Point::new(i as f64, 1.0)).collect::>(), false)), + fill, + stroke, + square_caps: false, + }; + let made = || { + ["a", "b"] + .map(|style| offline::Made { + variation: Variation { style: style.into(), paths: vec![line(3, Some([9, 9, 9]), None)], warnings: vec![] }, + seams: vec![line(2, None, Some(([9, 9, 9], 1.0)))], + }) + .into_iter() + .collect::>() + }; + let seamed = |v: &[Variation]| v.iter().map(|v| v.paths.first().is_some_and(|p| p.stroke.is_some())).collect::>(); + // 6 anchors traced: the first style's 2 seam anchors fit in 9, the second's do not. + let v = offline::with_seams_within(made(), 9, 100); + assert_eq!(seamed(&v), [true, false]); + assert_eq!(v.first().map(|v| v.paths.len()), Some(2), "the seam fill goes under the traced path"); + // 7 anchors: the first style's seam fills would take the room the second style's trace has. + assert_eq!(seamed(&offline::with_seams_within(made(), 7, 100)), [false, false]); + // Paths count too: 2 traced, one more fits in 3. + assert_eq!(seamed(&offline::with_seams_within(made(), 100, 3)), [true, false]); + assert_eq!(seamed(&offline::with_seams_within(made(), 100, 100)), [true, true]); +} + +/// Seam fills stay inside the image: where two colors meet at its border, the part of the seam +/// fill whose stroke would reach past the border is left out, and the rest is kept. +#[test] +fn seam_fills_stay_inside_the_image() { + // A red block against the top border, on white. + let raster = Raster::from_fn(80, 60, |x, y| if (20..60).contains(&x) && y < 30 { [220, 30, 30, 255] } else { [255, 255, 255, 255] }); + let req = Request { + image: Arc::new(raster.encode_png()), + width: raster.width, + height: raster.height, + prompt: None, + styles: vec!["flatColor".into()], + detail: 50, + output: Output::Vector, + }; + let flat = offline::TraceStyles.generate(&req, &|_, _| true).unwrap().remove(0); + let seams: Vec<_> = flat.paths.iter().filter(|p| p.fill.is_none()).collect(); + assert!(!seams.is_empty(), "the block's lower edge keeps its seam fill"); + for p in seams { + let half = p.stroke.map_or(0.0, |(_, w)| w / 2.0); + for (_, _, a) in p.path.anchors() { + for q in [a.p, a.h_in, a.h_out] { + assert!(q.x >= half && q.y >= half && q.x <= 80.0 - half && q.y <= 60.0 - half, "{q:?} reaches past the border"); + } + } + } +} + +/// A shared edge from the top border to the bottom keeps its interior seam fill. +#[test] +fn seam_fills_keep_the_interior_of_a_split_image_edge() { + let raster = Raster::from_fn(80, 60, |x, _| if x < 40 { [220, 30, 30, 255] } else { [30, 60, 220, 255] }); + let req = Request { + image: Arc::new(raster.encode_png()), + width: raster.width, + height: raster.height, + prompt: None, + styles: vec!["flatColor".into()], + detail: 50, + output: Output::Vector, + }; + let flat = offline::TraceStyles.generate(&req, &|_, _| true).unwrap().remove(0); + let seams: Vec<_> = flat.paths.iter().filter(|p| p.fill.is_none()).collect(); + assert!(!seams.is_empty(), "the shared edge keeps its seam fill"); + for p in seams { + let (_, width) = p.stroke.expect("a seam fill is a stroke"); + let half = width / 2.0; + for (_, _, a) in p.path.anchors() { + assert!( + a.p.x >= half && a.p.y >= half && a.p.x <= f64::from(raster.width) - half && a.p.y <= f64::from(raster.height) - half, + "{:?} reaches past the border", + a.p + ); + } + } +} + /// A part at a time (the web build's way): the built-in provider decodes the image in one part, /// finds a style's color layers in another and traces one layer a part (all of them in one part /// for a style that stacks them), and makes the variations diff --git a/docs/mcp.md b/docs/mcp.md index 8390dc3a91..08f9e5d765 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7007,7 +7007,8 @@ already walks Image Trace. Short agent entry points: and `grayTones` with Image Trace on this computer; it takes no prompt and makes vector art only. A provider is used only when it is named: an unknown one is an error, and so is one that takes no image, makes no vector art, or does not support a non-empty `prompt`, each with that reason; no other provider is used in its place. Results are vector - art, so `output` other than `"vector"` is an error for every provider. + art, so `output` other than `"vector"` is an error for every provider. `flatColor` traces abutting fills and lays + seam fills under them, as Image Trace's Abutting method with Fills does, when they fit within the limits below. `conceptVector.generate {id?, provider, styles: [style id…], detail?: 0-100, prompt?, output?: "vector"}` makes one variation of the image (or unexpanded Image Trace object) for each of 1 to 8 different styles and keeps them as a job of the session; it does not change the document and is not journaled. A source that is locked or hidden, itself or by a @@ -7017,7 +7018,8 @@ already walks Image Trace. Short agent entry points: and 1,000,000 anchor points in all. The reply lists each variation's `style`, `label`, `paths`, `anchors`, `bounds` in the image's pixels and `warnings` (for example that a large image was traced scaled down to 16 megapixels). `conceptVector.results {job}` returns the job again, and `conceptVector.cancel {job}` drops - its variations. The session keeps the 4 newest jobs until their document closes. A script that ends with an error, + its variations. The session keeps the 4 newest jobs until their document closes. A `conceptVector.generate` in a + script stops when the script is asked to stop, and keeps no job. A script that ends with an error, like a batch, leaves the jobs as they were: the jobs it made are dropped, and a job it canceled, or whose document it closed, is kept. `conceptVector.insert {job, variations: [style id…]}` puts a group of each chosen variation, named after its style and