mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
A seam stroke's width was scaled by the square root of the image's scale, so on an image stretched more one way its caps could reach past the image. The provider now outlines each trimmed seam stroke in the traced raster's pixels, with butt caps and round joins as Image Trace does, and maps the filled outline back like the other paths, so the seam fills stay inside the image whatever its transform.
441 lines
19 KiB
Rust
441 lines
19 KiB
Rust
//! The built-in provider: Concept to Vector styles made with Image Trace on this computer.
|
||
//!
|
||
//! Each style is a fixed set of Image Trace settings of VectorCraft's own, and Detail (0 to 100)
|
||
//! moves its Paths, Noise and color count within that style's range. The image is decoded once and
|
||
//! traced once per style; an image over [`MAX_PIXELS`] is scaled down first, aspect kept, and
|
||
//! each variation says so. The paths are mapped back to the image's own pixel size.
|
||
|
||
use std::sync::Arc;
|
||
|
||
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, MAX_PATHS, Output, Parts, ProviderError, Request, Steps, Style, Variation, VectorPath};
|
||
|
||
/// The built-in provider's id.
|
||
pub const ID: &str = "offline.traceStyles";
|
||
|
||
/// The most pixels the built-in provider traces an image at (16 megapixels).
|
||
pub const MAX_PIXELS: u64 = 16 << 20;
|
||
|
||
/// The built-in provider's styles, in the order it lists them.
|
||
pub const STYLES: [Style; 5] = [
|
||
Style { id: "outline", label: "Outline" },
|
||
Style { id: "inkLines", label: "Ink Lines" },
|
||
Style { id: "flatColor", label: "Flat Color" },
|
||
Style { id: "detailedColor", label: "Detailed Color" },
|
||
Style { id: "grayTones", label: "Gray Tones" },
|
||
];
|
||
|
||
/// Concept to Vector styles made with Image Trace ([`ID`]).
|
||
pub struct TraceStyles;
|
||
|
||
/// `lo` at Detail 0 to `hi` at Detail 100.
|
||
fn between(lo: f64, hi: f64, t: f64) -> f64 {
|
||
lo + (hi - lo) * t
|
||
}
|
||
|
||
/// The trace settings of style `id` at Detail `detail` (0 to 100); `None` for an id that isn't one
|
||
/// of [`STYLES`].
|
||
pub fn style_params(id: &str, detail: u8) -> Option<tr::TraceParams> {
|
||
let t = f64::from(detail.min(100)) / 100.0;
|
||
let noise = |lo: f64, hi: f64| between(hi, lo, t).round().max(1.0) as u32;
|
||
let count = |lo: f64, hi: f64| between(lo, hi, t).round() as u32;
|
||
let base = tr::TraceParams { shapes: false, gradients: false, auto_grouping: false, ..tr::TraceParams::default() };
|
||
Some(match id {
|
||
// Black stroked lines only: thin lines as center lines, wider areas as outlines.
|
||
"outline" => {
|
||
tr::TraceParams { fills: false, strokes: true, ignore_white: true, paths: between(50.0, 90.0, t), noise: noise(4.0, 40.0), ..base }
|
||
}
|
||
// Black filled ink on no background, the straight runs straightened.
|
||
"inkLines" => tr::TraceParams {
|
||
ignore_white: true,
|
||
snap_curves_to_lines: true,
|
||
paths: between(50.0, 95.0, t),
|
||
corners: 80.0,
|
||
noise: noise(4.0, 30.0),
|
||
..base
|
||
},
|
||
// A few flat colors, abutting.
|
||
"flatColor" => tr::TraceParams {
|
||
mode: tr::Mode::Color,
|
||
colors: count(3.0, 8.0),
|
||
paths: between(40.0, 80.0, t),
|
||
corners: 60.0,
|
||
noise: noise(8.0, 40.0),
|
||
snap_curves_to_lines: true,
|
||
..base
|
||
},
|
||
// Many colors, stacked so no hairline gaps show.
|
||
"detailedColor" => tr::TraceParams {
|
||
mode: tr::Mode::Color,
|
||
colors: count(12.0, 32.0),
|
||
paths: between(70.0, 95.0, t),
|
||
corners: 40.0,
|
||
noise: noise(2.0, 12.0),
|
||
method: tr::Method::Overlapping,
|
||
..base
|
||
},
|
||
// Grays, stacked.
|
||
"grayTones" => tr::TraceParams {
|
||
mode: tr::Mode::Grayscale,
|
||
colors: count(4.0, 12.0),
|
||
paths: between(55.0, 90.0, t),
|
||
corners: 50.0,
|
||
noise: noise(4.0, 20.0),
|
||
method: tr::Method::Overlapping,
|
||
..base
|
||
},
|
||
_ => return None,
|
||
})
|
||
}
|
||
|
||
/// `img` box-filtered down to at most [`MAX_PIXELS`], aspect kept; `img` itself when it fits.
|
||
fn fit(img: tr::Raster) -> tr::Raster {
|
||
fit_within(img, MAX_PIXELS)
|
||
}
|
||
|
||
/// `img` box-filtered down to at most `max` pixels (at least 1), aspect kept as far as a side of
|
||
/// at least one pixel allows; `img` itself when it fits.
|
||
pub(super) fn fit_within(img: tr::Raster, max: u64) -> tr::Raster {
|
||
let (w, h) = (u64::from(img.width), u64::from(img.height));
|
||
let max = max.max(1);
|
||
if w * h <= max || w == 0 || h == 0 {
|
||
return img;
|
||
}
|
||
let k = (max as f64 / (w * h) as f64).sqrt();
|
||
// A side that rounds down to one pixel leaves the other side the whole budget, no more.
|
||
let nh = ((h as f64 * k).floor() as u64).clamp(1, h.min(max));
|
||
let nw = ((w as f64 * k).floor() as u64).clamp(1, w.min(max / nh)) as u32;
|
||
let nh = nh as u32;
|
||
let mut rgba = Vec::with_capacity(nw as usize * nh as usize * 4);
|
||
for y in 0..nh {
|
||
let (y0, y1) = (u64::from(y) * h / u64::from(nh), (u64::from(y + 1) * h / u64::from(nh)).max(u64::from(y) * h / u64::from(nh) + 1));
|
||
for x in 0..nw {
|
||
let (x0, x1) = (u64::from(x) * w / u64::from(nw), (u64::from(x + 1) * w / u64::from(nw)).max(u64::from(x) * w / u64::from(nw) + 1));
|
||
// Each pixel's color is weighted by its alpha. A box with nothing opaque in it is clear black.
|
||
let mut sum = [0u64; 4];
|
||
for sy in y0..y1.min(h) {
|
||
for sx in x0..x1.min(w) {
|
||
let [r, g, b, a] = img.pixel(sx as u32, sy as u32).map(u64::from);
|
||
sum = [sum[0] + r * a, sum[1] + g * a, sum[2] + b * a, sum[3] + a];
|
||
}
|
||
}
|
||
let n = ((y1.min(h) - y0) * (x1.min(w) - x0)).max(1);
|
||
let alpha = sum[3];
|
||
let color = |s: u64| s.checked_div(alpha).map_or(0, |c| c.min(255) as u8);
|
||
rgba.extend([color(sum[0]), color(sum[1]), color(sum[2]), (alpha / n) as u8]);
|
||
}
|
||
}
|
||
tr::Raster { width: nw, height: nh, rgba }
|
||
}
|
||
|
||
impl super::Provider for TraceStyles {
|
||
fn id(&self) -> &'static str {
|
||
ID
|
||
}
|
||
|
||
fn name(&self) -> &'static str {
|
||
"Offline Image Trace Styles"
|
||
}
|
||
|
||
fn capabilities(&self) -> Capabilities {
|
||
Capabilities { image_input: true, vector_output: true, prompt: false, raster_output: false, offline: true, styles: STYLES.to_vec() }
|
||
}
|
||
|
||
fn generate(&self, request: &Request, steps: Steps) -> Result<Vec<Variation>, ProviderError> {
|
||
let params = checked(request)?;
|
||
let total = params.len() as u64;
|
||
if !steps(0, total) {
|
||
return Err(ProviderError::Canceled);
|
||
}
|
||
let image = Decoded::new(request)?;
|
||
let mut left = MAX_ANCHORS;
|
||
let mut out = Vec::with_capacity(params.len());
|
||
for (i, (style, p)) in request.styles.iter().zip(¶ms).enumerate() {
|
||
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, p, res));
|
||
}
|
||
if !steps(total, total) {
|
||
return Err(ProviderError::Canceled);
|
||
}
|
||
Ok(with_seams(out))
|
||
}
|
||
|
||
/// The image decoded in the first part; then for each style, its color layers found in one
|
||
/// part and each layer traced in a part of its own ([`tr::TraceSteps`]), or all of them in
|
||
/// one part where the style stacks them (Overlapping with Fills).
|
||
fn parts(&self, request: &Request) -> Option<Box<dyn Parts>> {
|
||
Some(Box::new(TraceParts { request: request.clone(), image: None, trace: None, left: MAX_ANCHORS, out: vec![], ended: false }))
|
||
}
|
||
}
|
||
|
||
/// The trace settings of each of `request`'s styles; an error for a prompt, an output other than
|
||
/// vector art, or a style that isn't one of [`STYLES`]. The host refuses these first; a direct
|
||
/// caller gets the same answer.
|
||
fn checked(request: &Request) -> Result<Vec<tr::TraceParams>, ProviderError> {
|
||
let pid = ID;
|
||
if request.prompt.is_some() || request.output != Output::Vector {
|
||
return Err(ProviderError::Unsupported(format!("`{pid}` takes no prompt and makes vector art only")));
|
||
}
|
||
request
|
||
.styles
|
||
.iter()
|
||
.map(|s| style_params(s, request.detail))
|
||
.collect::<Option<_>>()
|
||
.ok_or_else(|| ProviderError::InvalidInput(format!("`styles` must list 1 to 8 different style ids of `{pid}` (see conceptVector.providers)")))
|
||
}
|
||
|
||
fn trace_error(e: tr::TraceError) -> ProviderError {
|
||
match e {
|
||
tr::TraceError::Cancelled => ProviderError::Canceled,
|
||
tr::TraceError::TooComplex { .. } => ProviderError::ResourceLimit(MAX_ANCHORS),
|
||
e => ProviderError::InvalidInput(e.to_string()),
|
||
}
|
||
}
|
||
|
||
/// A request's image decoded for tracing, with what maps its traced paths back.
|
||
struct Decoded {
|
||
raster: Arc<tr::Raster>,
|
||
/// The decoded raster's pixels → the image's own pixel space.
|
||
back: Affine,
|
||
unit: f64,
|
||
warnings: Vec<String>,
|
||
}
|
||
|
||
impl Decoded {
|
||
/// `request`'s image decoded, scaled down to at most [`MAX_PIXELS`].
|
||
fn new(request: &Request) -> Result<Self, ProviderError> {
|
||
let raster = fit(tr::Raster::decode_to_fit(&request.image).map_err(|e| ProviderError::InvalidInput(e.to_string()))?);
|
||
let mut warnings = vec![];
|
||
let (iw, ih) = (request.width.max(1), request.height.max(1));
|
||
if u64::from(raster.width) * u64::from(raster.height) < u64::from(iw) * u64::from(ih) {
|
||
warnings.push(format!("The image was traced at {} × {} pixels, scaled down from {iw} × {ih}.", raster.width, raster.height));
|
||
}
|
||
let back = Affine::scale_non_uniform(f64::from(iw) / f64::from(raster.width.max(1)), f64::from(ih) / f64::from(raster.height.max(1)));
|
||
let unit = back.determinant().abs().sqrt();
|
||
Ok(Self { raster: Arc::new(raster), back, unit, warnings })
|
||
}
|
||
|
||
/// 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`]) trimmed inside the
|
||
/// image ([`within_image`]) and outlined in raster pixels before mapping them back, 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| {
|
||
let mut tp = within_image(tp, size);
|
||
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,
|
||
);
|
||
}
|
||
tp
|
||
})
|
||
.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 outlined seam fills to lay under its paths.
|
||
pub(super) struct Made {
|
||
pub(super) variation: Variation,
|
||
pub(super) seams: Vec<VectorPath>,
|
||
}
|
||
|
||
/// [`with_seams_within`] [`MAX_ANCHORS`] and [`MAX_PATHS`].
|
||
fn with_seams(made: Vec<Made>) -> Vec<Variation> {
|
||
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<Made>, max_anchors: usize, max_paths: usize) -> Vec<Variation> {
|
||
let subpaths = |paths: &[VectorPath]| paths.iter().map(|p| p.path.subpaths.len().max(1)).sum::<usize>();
|
||
let mut anchors = made.iter().map(|m| m.variation.anchors()).sum::<usize>();
|
||
let mut paths = made.iter().map(|m| subpaths(&m.variation.paths)).sum::<usize>();
|
||
made.into_iter()
|
||
.map(|Made { mut variation, seams }| {
|
||
let (more_anchors, more_paths) = (seams.iter().map(|p| p.path.anchor_count()).sum::<usize>(), 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 outline with butt caps and round joins stays 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<SubPath> = 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<Anchor> = 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<Anchor>) -> 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.
|
||
struct TraceParts {
|
||
request: Request,
|
||
image: Option<Decoded>,
|
||
/// The trace of the style after those in `out`, once started.
|
||
trace: Option<tr::TraceSteps>,
|
||
/// The anchor points the styles not made yet may have.
|
||
left: usize,
|
||
out: Vec<Made>,
|
||
/// The variations or an error have been given.
|
||
ended: bool,
|
||
}
|
||
|
||
impl Parts for TraceParts {
|
||
/// After the variations or an error, each call gives `None`.
|
||
fn step(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
|
||
if self.ended {
|
||
return Ok(None);
|
||
}
|
||
let part = self.next_part();
|
||
self.ended = !matches!(part, Ok(None));
|
||
part
|
||
}
|
||
|
||
fn styles_done(&self) -> usize {
|
||
self.out.len()
|
||
}
|
||
}
|
||
|
||
impl TraceParts {
|
||
fn next_part(&mut self) -> Result<Option<Vec<Variation>>, ProviderError> {
|
||
let Some(image) = &self.image else {
|
||
checked(&self.request)?;
|
||
self.image = Some(Decoded::new(&self.request)?);
|
||
return Ok(None);
|
||
};
|
||
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 => {
|
||
let params = style_params(style, self.request.detail).ok_or(ProviderError::InvalidResult)?;
|
||
self.trace.insert(tr::TraceSteps::new(Arc::clone(&image.raster), params, self.left))
|
||
}
|
||
};
|
||
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, ¶ms, res));
|
||
if self.out.len() < self.request.styles.len() {
|
||
return Ok(None);
|
||
}
|
||
Ok(Some(with_seams(std::mem::take(&mut self.out))))
|
||
}
|
||
}
|