mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 16:07:33 +00:00
Merge pull request #6903 from dotCooCoo/feat/gradient-repeat
Gradients: repeat or reflect a gradient's stops a set number of times
This commit is contained in:
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand…",
|
||||
["Object"],
|
||||
None,
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
has_selection,
|
||||
expand
|
||||
),
|
||||
@@ -476,11 +476,14 @@ fn gradient_art(d: &mut Document, l: &Node, path: &PathData, bounds: Rect, f: &F
|
||||
let m = GradientMesh::for_path_with(path, FREEFORM_MESH, FREEFORM_MESH, &*gradient_sampler(g, bounds, d.color_mode.model()))?;
|
||||
vec![Node::new(d.alloc_id(), NodeKind::Mesh(m))]
|
||||
} else {
|
||||
// A gradient that repeats or reflects expands as its stops repeated over the box.
|
||||
let (g, runs) = padded_on(g, bounds);
|
||||
let g = &*g;
|
||||
let frame = Frame::new(g, bounds);
|
||||
match to {
|
||||
GradientTo::Mesh => vec![Node::new(d.alloc_id(), NodeKind::Mesh(frame.mesh(&g.gradient)))],
|
||||
GradientTo::Objects(n) => frame
|
||||
.pieces(&g.gradient, n as usize)
|
||||
.pieces(&g.gradient, n as usize, runs)
|
||||
.into_iter()
|
||||
.map(|(shape, (color, opacity))| {
|
||||
let fill = FillLayer { opacity, overprint: f.overprint, ..FillLayer::new(Paint::solid(color)) };
|
||||
@@ -1234,8 +1237,64 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model
|
||||
(super::paint::stored_color(store_in, c), a)
|
||||
});
|
||||
}
|
||||
let (geom, spread) = (g.resolve(bounds), g.gradient.spreader());
|
||||
Box::new(move |p| g.gradient.sample_keep_model(spread(geom.param_at(g.gradient.kind, p)) as f32))
|
||||
}
|
||||
|
||||
/// `g` placed on box `bounds` as a gradient that pads past its ends: a linear, radial or diamond
|
||||
/// gradient that repeats or reflects with its stops repeated as many times as the box needs
|
||||
/// ([`vectorcraft_color::Gradient::padded_over`]), a conic one with its stops repeated around the
|
||||
/// turn ([`vectorcraft_color::Gradient::unrolled`]); others as they are. With it, for the repeated
|
||||
/// stops, where along the vector (0 to 1) their first run starts and how many runs lie evenly from
|
||||
/// there to 1.
|
||||
fn padded_on(g: &GradientPaint, bounds: Rect) -> (std::borrow::Cow<'_, GradientPaint>, Option<(f64, usize)>) {
|
||||
use std::borrow::Cow;
|
||||
if !g.gradient.is_spread() {
|
||||
return (Cow::Borrowed(g), None);
|
||||
}
|
||||
let geom = g.resolve(bounds);
|
||||
Box::new(move |p| g.gradient.sample_keep_model(geom.param_at(g.gradient.kind, p) as f32))
|
||||
match g.gradient.padded_over(&geom, bounds) {
|
||||
Some(p) => {
|
||||
let runs = Some((p.first, p.runs));
|
||||
(Cow::Owned(GradientPaint { gradient: p.gradient, geom: Some(p.geom), angle: p.geom.angle_deg(), ..g.clone() }), runs)
|
||||
}
|
||||
None => {
|
||||
let runs = Some((0.0, g.gradient.repeat_count() as usize));
|
||||
(Cow::Owned(GradientPaint { gradient: g.gradient.unrolled().into_owned(), geom: Some(geom), ..g.clone() }), runs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The edges (gradient parameters, from `lo` to `hi`) of about `n` bands [`Frame::pieces`] cuts:
|
||||
/// evenly spaced, or for stops repeated in `runs` ([`padded_on`]: where the first run starts and
|
||||
/// how many runs lie evenly from there to 1) the same whole number of bands in each run between
|
||||
/// `lo` and `hi` (at least one, about `n` in all), so every run starts on an edge and no band
|
||||
/// holds two runs' colors.
|
||||
fn band_edges(lo: f64, hi: f64, n: usize, runs: Option<(f64, usize)>) -> Vec<f64> {
|
||||
let n = n.max(1);
|
||||
let even = || {
|
||||
let step = (hi - lo) / n as f64;
|
||||
(0..=n).map(|k| lo + k as f64 * step).collect()
|
||||
};
|
||||
let Some((first, count)) = runs.filter(|&(first, count)| count > 0 && (0.0..1.0).contains(&first)) else { return even() };
|
||||
let run = (1.0 - first) / count as f64;
|
||||
let (from, to) = (lo.max(first), hi.min(1.0));
|
||||
let shown = (to - from) / run;
|
||||
if !(shown > 0.0 && shown.is_finite()) {
|
||||
return even();
|
||||
}
|
||||
let step = run / (n as f64 / shown).round().max(1.0);
|
||||
// Both whole numbers of steps from `first`, at most `n` plus the runs shown, plus one.
|
||||
let (k0, k1) = (((from - first) / step).ceil(), ((to - first) / step).floor());
|
||||
let mut edges = vec![lo];
|
||||
for k in (k0 as usize)..(k1 as usize).saturating_add(1) {
|
||||
let t = first + k as f64 * step;
|
||||
if t > edges.last().copied().unwrap_or(lo) + 1e-12 && t < hi - 1e-12 {
|
||||
edges.push(t);
|
||||
}
|
||||
}
|
||||
edges.push(hi);
|
||||
edges
|
||||
}
|
||||
|
||||
/// Where the colour changes along a gradient between parameters `t0` and `t1`: both ends, every
|
||||
@@ -1404,10 +1463,17 @@ impl Frame {
|
||||
/// end, for a radial one, nested ellipses (largest first), for a conic one, wedges around the
|
||||
/// center from each band's start to the seam, for a diamond one, nested squares (largest
|
||||
/// first). Each paints over the ones below except its band, so no seam shows between bands.
|
||||
/// With translucent stops each shape is just its band, so nothing doubles up.
|
||||
fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> {
|
||||
/// With translucent stops each shape is just its band, so nothing doubles up. Stops repeated
|
||||
/// in `runs` ([`padded_on`]) get the same whole number of bands in each run ([`band_edges`]).
|
||||
fn pieces(&self, g: &Gradient, n: usize, runs: Option<(f64, usize)>) -> Vec<(PathData, (Color, f32))> {
|
||||
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
|
||||
let color = |e: &[f64], k: usize| {
|
||||
let (a, b) = (e.get(k).copied().unwrap_or(0.0), e.get(k + 1).copied().unwrap_or(1.0));
|
||||
g.sample_keep_model(((a + b) / 2.0) as f32)
|
||||
};
|
||||
if let Some((geom, b, _)) = &self.conic {
|
||||
// Evenly spaced around the turn, as the wedges are.
|
||||
let n = band_edges(0.0, 1.0, n, runs).len().saturating_sub(1);
|
||||
return geom
|
||||
.conic_wedges(*b, n, opaque)
|
||||
.into_iter()
|
||||
@@ -1419,51 +1485,52 @@ impl Frame {
|
||||
return vec![(shapes::rectangle(*b), g.sample_keep_model(1.0))];
|
||||
};
|
||||
// Nested squares about the center, largest first, as a radial gradient's ellipses.
|
||||
let step = reach / n as f64;
|
||||
let edges = band_edges(0.0, *reach, n, runs);
|
||||
let square = |t: f64| -> SubPath {
|
||||
let pts: Vec<Point> = [0.0, 0.25, 0.5, 0.75].iter().map(|&u| *frame * (diamond_perimeter(u).to_vec2() * t).to_point()).collect();
|
||||
SubPath::polyline(&pts, true)
|
||||
};
|
||||
return (0..n)
|
||||
return (0..edges.len().saturating_sub(1))
|
||||
.rev()
|
||||
.map(|k| {
|
||||
let mut shape = PathData::single(square((k + 1) as f64 * step));
|
||||
let mut shape = PathData::single(square(edges.get(k + 1).copied().unwrap_or(*reach)));
|
||||
if !opaque && k > 0 {
|
||||
let mut hole = square(k as f64 * step);
|
||||
let mut hole = square(edges.get(k).copied().unwrap_or(0.0));
|
||||
hole.reverse();
|
||||
shape.subpaths.push(hole);
|
||||
}
|
||||
(shape, g.sample_keep_model(((k as f64 + 0.5) * step) as f32))
|
||||
(shape, color(&edges, k))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let step = (self.t1 - self.t0) / n as f64;
|
||||
let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32);
|
||||
let edges = band_edges(self.t0, self.t1, n, runs);
|
||||
let bands = edges.len().saturating_sub(1);
|
||||
let edge = |k: usize| edges.get(k).copied().unwrap_or(self.t1);
|
||||
if self.radial {
|
||||
let ellipse = |t: f64| {
|
||||
let c = self.focal + (self.start - self.focal) * t;
|
||||
let m = Affine::new([self.along.x * t, self.along.y * t, self.across.x * t, self.across.y * t, c.x, c.y]);
|
||||
shapes::ellipse(Rect::new(-1.0, -1.0, 1.0, 1.0)).transformed(m)
|
||||
};
|
||||
return (0..n)
|
||||
return (0..bands)
|
||||
.rev()
|
||||
.map(|k| {
|
||||
let mut shape = ellipse((k + 1) as f64 * step);
|
||||
let mut shape = ellipse(edge(k + 1));
|
||||
if !opaque && k > 0 {
|
||||
let mut hole = ellipse(k as f64 * step).subpaths.remove(0);
|
||||
let mut hole = ellipse(edge(k)).subpaths.remove(0);
|
||||
hole.reverse();
|
||||
shape.subpaths.push(hole);
|
||||
}
|
||||
(shape, color(k))
|
||||
(shape, color(&edges, k))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
(0..n)
|
||||
(0..bands)
|
||||
.map(|k| {
|
||||
let a = self.t0 + k as f64 * step;
|
||||
let b = if opaque { self.t1 } else { a + step };
|
||||
let a = edge(k);
|
||||
let b = if opaque { self.t1 } else { edge(k + 1) };
|
||||
let pts = [self.at(a, self.s0), self.at(b, self.s0), self.at(b, self.s1), self.at(a, self.s1)];
|
||||
(PathData::single(SubPath::polyline(&pts, true)), color(k))
|
||||
(PathData::single(SubPath::polyline(&pts, true)), color(&edges, k))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! The Gradient panel and the Gradient tool: in-place gradient edits and the gradient vector.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_color::gradient::MAX_REPEATS;
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint};
|
||||
use vectorcraft_doc::appearance::stroke_paint_bounds;
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, StrokeGradientMode};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
@@ -23,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -129,6 +130,36 @@ fn method_param(p: &Value) -> Parsed<Option<GradientMethod>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `spread` param of `p`, if given: what the gradient paints past the ends of its stops.
|
||||
fn spread_param(p: &Value) -> Parsed<Option<GradientSpread>> {
|
||||
match p.get("spread") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_str().and_then(GradientSpread::parse).map(Some).ok_or_else(|| "`spread` must be pad, repeat or reflect".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `repeats` param of `p`, if given: how many times the stops run along the vector with
|
||||
/// Repeat and Reflect, a whole number from 1 to [`MAX_REPEATS`].
|
||||
fn repeats_param(p: &Value) -> Parsed<Option<u32>> {
|
||||
match p.get("repeats") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v
|
||||
.as_f64()
|
||||
.filter(|n| n.fract() == 0.0 && (1.0..=f64::from(MAX_REPEATS)).contains(n))
|
||||
.map(|n| Some(n as u32))
|
||||
.ok_or_else(|| format!("`repeats` must be a whole number from 1 to {MAX_REPEATS}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// An error when `p` gives a spread other than pad for a gradient of `kind` that has no ends to
|
||||
/// spread past (freeform).
|
||||
fn spread_for(kind: GradientKind, p: &Value) -> Parsed<()> {
|
||||
match spread_param(p)? {
|
||||
Some(s) if !s.is_pad() && kind == GradientKind::Freeform => Err("`spread` applies to linear, radial, conic and diamond gradients".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `v` (params holding `stops`) with each stop that names a `swatch` resolved through `d`
|
||||
/// ([`swatch_solid`]): a global or spot colour or a tint swatch gives the stop its colour, link and
|
||||
/// tint, a process colour just its colour. A stop linked to a swatch that no longer exists keeps
|
||||
@@ -271,6 +302,9 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
|
||||
Some(v) => v.as_bool().ok_or("`dither` must be true or false")?,
|
||||
};
|
||||
gp.gradient.method = method_param(g)?.unwrap_or_default();
|
||||
spread_for(kind, g)?;
|
||||
gp.gradient.spread = spread_param(g)?.unwrap_or_default();
|
||||
gp.gradient.repeats = repeats_param(g)?.unwrap_or(1);
|
||||
gp.angle = f64_or(g, "angle", 0.0);
|
||||
gp.swatch = str_param(g, "swatch").map(str::to_string);
|
||||
let geom = GeomEdit::parse(g)?;
|
||||
@@ -422,6 +456,13 @@ fn apply_gradient_edit_in_model(
|
||||
if let Some(m) = method_param(p)? {
|
||||
gp.gradient.method = m;
|
||||
}
|
||||
spread_for(gp.gradient.kind, p)?;
|
||||
if let Some(sp) = spread_param(p)? {
|
||||
gp.gradient.spread = sp;
|
||||
}
|
||||
if let Some(n) = repeats_param(p)? {
|
||||
gp.gradient.repeats = n;
|
||||
}
|
||||
// Angle and aspect edits keep the focal point in its place in the extent ellipse.
|
||||
let before = gp.geom;
|
||||
if let Some(a) = p.get("angle").and_then(Value::as_f64) {
|
||||
@@ -516,6 +557,18 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
_ => std::borrow::Cow::Borrowed(p),
|
||||
};
|
||||
// A spread for selected gradients leaves a freeform default (which has no ends) as it is.
|
||||
let spreads = matches!(spread_param(p), Ok(Some(sp)) if !sp.is_pad());
|
||||
let for_default = match for_default {
|
||||
q if spreads && !ids.is_empty() && default_kind == Some(GradientKind::Freeform) => {
|
||||
let mut q = q.into_owned();
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.remove("spread");
|
||||
}
|
||||
std::borrow::Cow::Owned(q)
|
||||
}
|
||||
q => q,
|
||||
};
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
|
||||
.map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! The built-in presets are the gradient swatches of the built-in swatch libraries
|
||||
//! ([`vectorcraft_color::libraries`]: the app's own computed palettes), each listed under its
|
||||
//! library's name. Saved presets are kept with the preferences ([`crate::Prefs::gradient_presets`]),
|
||||
//! so every document has them. A preset is the colour ramp (type, stops, method, dither), not a
|
||||
//! so every document has them. A preset is the color ramp (type, stops, method, dither, spread), not a
|
||||
//! placement: applying one edits the gradient in place, as `paint.editGradient` does.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient Presets",
|
||||
[],
|
||||
None,
|
||||
"{} → {presets: [{name, library: the built-in library (theme) it comes from, null for a saved one, builtIn, gradient: {kind, stops, method?, dither?} (as paint.setFill's `gradient`)}]} the Gradient panel's presets: the built-in ones by library, then the saved ones; names are unique",
|
||||
"{} → {presets: [{name, library: the built-in library (theme) it comes from, null for a saved one, builtIn, gradient: {kind, stops, method?, dither?, spread?, repeats?} (as paint.setFill's `gradient`)}]} the Gradient panel's presets: the built-in ones by library, then the saved ones; names are unique",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Gradient Preset",
|
||||
[],
|
||||
None,
|
||||
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops and method, and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient → {name, ids: the objects painted (none: only the default changed)}",
|
||||
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient → {name, ids: the objects painted (none: only the default changed)}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save Gradient Preset",
|
||||
[],
|
||||
None,
|
||||
"{name?: (default: a new \"Gradient Preset N\"; unique, any case, and not a built-in preset's)} save the gradient behind the active proxy (paint.toggleActive picks Fill or Stroke) as a preset, kept with the preferences: its type, stops, method and dither (stops linked to a swatch keep their colour, unlinked) → {name}",
|
||||
"{name?: (default: a new \"Gradient Preset N\"; unique, any case, and not a built-in preset's)} save the gradient behind the active proxy (paint.toggleActive picks Fill or Stroke) as a preset, kept with the preferences: its type, stops, method, dither, spread and repeats (stops linked to a swatch keep their colour, unlinked) → {name}",
|
||||
can_save,
|
||||
save
|
||||
),
|
||||
@@ -90,12 +90,13 @@ fn builtin_presets() -> impl Iterator<Item = GradientPresetEntry> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Do `a` and `b` have the same colour ramp (type, method, dither and stops), swatch links aside?
|
||||
/// Do `a` and `b` have the same color ramp (type, method, dither, spread as it paints and stops),
|
||||
/// swatch links aside?
|
||||
fn same_ramp(a: &Gradient, b: &Gradient) -> bool {
|
||||
let stop = |x: &vectorcraft_color::GradientStop, y: &vectorcraft_color::GradientStop| {
|
||||
(x.offset, x.color, x.opacity, x.midpoint) == (y.offset, y.color, y.opacity, y.midpoint)
|
||||
};
|
||||
(a.kind, a.method, a.dither) == (b.kind, b.method, b.dither)
|
||||
(a.kind, a.method, a.dither, a.painted_spread()) == (b.kind, b.method, b.dither, b.painted_spread())
|
||||
&& a.stops.len() == b.stops.len()
|
||||
&& a.stops.iter().zip(&b.stops).all(|(x, y)| stop(x, y))
|
||||
}
|
||||
@@ -215,6 +216,11 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.insert("kind".into(), json!(g.kind.label().to_lowercase()));
|
||||
o.insert("stops".into(), stops_json(&g.stops));
|
||||
o.insert("method".into(), json!(g.method.label().to_lowercase()));
|
||||
// A freeform preset takes no spread (paint.editGradient refuses one).
|
||||
if g.kind != vectorcraft_color::GradientKind::Freeform {
|
||||
o.insert("spread".into(), json!(g.spread.label().to_lowercase()));
|
||||
o.insert("repeats".into(), json!(g.repeat_count()));
|
||||
}
|
||||
// Dither is a fill's (paint.editGradient refuses it on a stroke).
|
||||
if !stroke {
|
||||
o.insert("dither".into(), json!(g.dither));
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
|
||||
@@ -393,11 +393,12 @@ fn float_key(v: f32) -> Option<u32> {
|
||||
/// keys.
|
||||
type StopKey<'a> = (u32, ColorKey, u32, u32, Option<&'a str>, u32, Option<[u32; 4]>);
|
||||
|
||||
/// A gradient's kind, method, dither and stops, as keys.
|
||||
type GradientKey<'a> = (u8, u8, bool, Vec<StopKey<'a>>);
|
||||
/// A gradient's kind, method, dither, spread and count as it paints them, and stops, as keys.
|
||||
type GradientKey<'a> = (u8, u8, bool, (vectorcraft_color::GradientSpread, u32), Vec<StopKey<'a>>);
|
||||
|
||||
/// A key that is equal for two gradients exactly when the gradients are equal (`==`); `None` when
|
||||
/// any of its numbers is NaN, so the gradient equals no gradient.
|
||||
/// A key that is equal for two gradients exactly when the gradients are equal (`==`), apart from
|
||||
/// a count that a gradient which pads does not use ([`Gradient::painted_spread`]); `None` when any
|
||||
/// of its numbers is NaN, so the gradient equals no gradient.
|
||||
fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> {
|
||||
let kind = match g.kind {
|
||||
GradientKind::Linear => 0,
|
||||
@@ -410,7 +411,7 @@ fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> {
|
||||
GradientMethod::Classic => 0,
|
||||
GradientMethod::Perceptual => 1,
|
||||
};
|
||||
Some((kind, method, g.dither, g.stops.iter().map(stop_key).collect::<Option<_>>()?))
|
||||
Some((kind, method, g.dither, g.painted_spread(), g.stops.iter().map(stop_key).collect::<Option<_>>()?))
|
||||
}
|
||||
|
||||
/// A stop's key for [`gradient_key`]; `None` when any of its numbers is NaN.
|
||||
|
||||
@@ -881,3 +881,134 @@ fn making_a_gradient_diamond_is_one_undo_step() {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id), before);
|
||||
}
|
||||
|
||||
/// `paint.setFill` and `paint.editGradient` take a spread and a count for each kind of gradient
|
||||
/// that has ends; the params give them back, the native format keeps them, and a change is one
|
||||
/// undo step while an edit that changes nothing records none.
|
||||
#[test]
|
||||
fn a_gradient_takes_a_spread_and_a_count() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
for kind in ["linear", "radial", "conic", "diamond"] {
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "spread": "Reflect", "repeats": 4}})).unwrap();
|
||||
let g = fill_gradient(&s, id);
|
||||
assert_eq!((g.gradient.spread, g.gradient.repeats), (GradientSpread::Reflect, 4), "{kind}");
|
||||
let params = vectorcraft_tools::params::gradient_params(&g);
|
||||
assert_eq!((params["spread"].as_str(), params["repeats"].as_u64()), (Some("reflect"), Some(4)), "{kind}");
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).gradient.spread, GradientSpread::Pad, "a new gradient pads");
|
||||
s.execute("paint.setFill", &json!({ "gradient": params })).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).gradient, g.gradient, "{kind}");
|
||||
}
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("paint.editGradient", &json!({"spread": "repeat", "repeats": 2})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one step");
|
||||
let g = fill_gradient(&s, id);
|
||||
assert_eq!((g.gradient.spread, g.gradient.repeats), (GradientSpread::Repeat, 2));
|
||||
s.execute("paint.editGradient", &json!({"spread": "repeat", "repeats": 2})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "nothing changed: no step");
|
||||
s.execute("paint.editGradient", &json!({"spread": "pad"})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).gradient.repeats, 2, "Pad keeps the count for later");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id), g);
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let Paint::Gradient(saved) = back.node(id).unwrap().appearance.fill_paint() else { panic!("the gradient is lost") };
|
||||
assert_eq!((saved.gradient.spread, saved.gradient.repeats), (GradientSpread::Repeat, 2));
|
||||
// The params of a gradient that pads give back the count it keeps.
|
||||
s.execute("paint.editGradient", &json!({"spread": "pad"})).unwrap();
|
||||
let params = vectorcraft_tools::params::gradient_params(&fill_gradient(&s, id));
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("paint.setFill", &json!({ "gradient": params })).unwrap();
|
||||
assert_eq!((fill_gradient(&s, id).gradient.spread, fill_gradient(&s, id).gradient.repeats), (GradientSpread::Pad, 2), "{params}");
|
||||
}
|
||||
|
||||
/// A spread or count a gradient can't take is an error, from every command that sets one, and the
|
||||
/// gradient stays as it was: an unknown spread, a count that is not a whole number from 1 to 100,
|
||||
/// and a spread other than pad on a freeform gradient.
|
||||
#[test]
|
||||
fn a_bad_spread_or_count_is_refused() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "radial", "spread": "repeat", "repeats": 3}})).unwrap();
|
||||
let before = fill_gradient(&s, id);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for bad in [json!({"spread": "mirror"}), json!({"spread": 1}), json!({"spread": true})] {
|
||||
let e = s.execute("paint.editGradient", &bad).unwrap_err().to_string();
|
||||
assert!(e.contains("`spread` must be pad, repeat or reflect"), "{bad}: {e}");
|
||||
}
|
||||
for n in [json!(0), json!(-2), json!(1.5), json!(101), json!(1e9), json!("3"), json!(f64::MAX)] {
|
||||
let e = s.execute("paint.editGradient", &json!({ "repeats": n })).unwrap_err().to_string();
|
||||
assert!(e.contains("`repeats` must be a whole number from 1 to 100"), "{n}: {e}");
|
||||
let e = s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "repeats": n}})).unwrap_err().to_string();
|
||||
assert!(e.contains("`repeats`"), "{n}: {e}");
|
||||
}
|
||||
let freeform = json!({"kind": "freeform", "spread": "reflect"});
|
||||
let e = s.execute("paint.editGradient", &freeform).unwrap_err().to_string();
|
||||
assert!(e.contains("`spread` applies to linear, radial, conic and diamond gradients"), "{e}");
|
||||
let e = s.execute("paint.setFill", &json!({ "gradient": freeform })).unwrap_err().to_string();
|
||||
assert!(e.contains("`spread` applies to"), "{e}");
|
||||
assert_eq!(fill_gradient(&s, id), before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
// Pad on a freeform gradient is allowed (it has nothing to spread), and 100 is the most.
|
||||
s.execute("paint.editGradient", &json!({"repeats": 100})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"kind": "freeform", "spread": "pad"})).unwrap();
|
||||
// A repeating gradient turned freeform: its params, which carry no spread, set it again.
|
||||
s.execute("paint.editGradient", &json!({"kind": "radial", "spread": "reflect"})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"kind": "freeform"})).unwrap();
|
||||
let params = vectorcraft_tools::params::gradient_params(&fill_gradient(&s, id));
|
||||
assert!(params.get("spread").is_none(), "{params}");
|
||||
s.execute("paint.setFill", &json!({ "gradient": params })).unwrap();
|
||||
}
|
||||
|
||||
/// A spread for a selected gradient applies while the gradient used last, the default, is a
|
||||
/// freeform one, which keeps no spread.
|
||||
#[test]
|
||||
fn a_spread_for_a_selected_gradient_leaves_a_freeform_default_alone() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
rect(&mut s, 200.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"ids": [a.0], "spread": "repeat", "repeats": 3})).unwrap();
|
||||
let g = fill_gradient(&s, a);
|
||||
assert_eq!((g.gradient.spread, g.gradient.repeats), (GradientSpread::Repeat, 3));
|
||||
}
|
||||
|
||||
/// A preset keeps its spread and count: saved from a gradient, applied to another object.
|
||||
#[test]
|
||||
fn a_gradient_preset_keeps_its_spread() {
|
||||
use vectorcraft_color::GradientSpread;
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "spread": "reflect", "repeats": 5}})).unwrap();
|
||||
s.execute("gradient.presets.save", &json!({"name": "Fan"})).unwrap();
|
||||
let b = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("gradient.presets.apply", &json!({"name": "Fan"})).unwrap();
|
||||
let g = fill_gradient(&s, b);
|
||||
assert_eq!((g.gradient.kind, g.gradient.spread, g.gradient.repeats), (GradientKind::Conic, GradientSpread::Reflect, 5));
|
||||
assert_eq!(fill_gradient(&s, a).gradient.repeats, 5);
|
||||
}
|
||||
|
||||
/// A gradient set back to Pad keeps its count for later, and still matches a saved preset and a
|
||||
/// swatch of the same gradient; while it repeats, the spread tells them apart.
|
||||
#[test]
|
||||
fn a_padding_gradient_matches_whatever_count_it_keeps() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]});
|
||||
s.execute("paint.setFill", &json!({ "gradient": ramp })).unwrap();
|
||||
s.execute("gradient.presets.save", &json!({"name": "Plain"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Plain", "paint": {"gradient": ramp}})).unwrap();
|
||||
let unused = |s: &mut Session| s.execute("swatch.unused", &json!({})).unwrap()["names"].as_array().unwrap().contains(&json!("Plain"));
|
||||
assert!(!unused(&mut s));
|
||||
s.execute("paint.editGradient", &json!({"spread": "repeat", "repeats": 5})).unwrap();
|
||||
assert_eq!(s.active_saved_gradient_preset(), None, "a repeating gradient is another ramp");
|
||||
assert!(unused(&mut s), "nothing paints the swatch's gradient");
|
||||
s.execute("paint.editGradient", &json!({"spread": "pad"})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, a).gradient.repeats, 5);
|
||||
assert_eq!(s.active_saved_gradient_preset(), Some("Plain"));
|
||||
assert!(!unused(&mut s), "the gradient paints as the swatch does");
|
||||
}
|
||||
|
||||
@@ -464,6 +464,50 @@ fn a_turned_or_flat_diamond_expands_as_the_canvas_draws_it() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient that repeats or reflects expands, into objects or a mesh, as the canvas paints it:
|
||||
/// its stops repeated across the box, for each kind.
|
||||
#[test]
|
||||
fn a_spread_gradient_expands_as_the_canvas_paints_it() {
|
||||
for kind in ["linear", "radial", "conic", "diamond"] {
|
||||
for spread in ["repeat", "reflect"] {
|
||||
for to in [json!({"steps": 240}), json!({"gradient": "mesh"})] {
|
||||
let mut s = session();
|
||||
let gr = json!({"kind": kind, "spread": spread, "repeats": 3, "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]});
|
||||
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false);
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", to.clone());
|
||||
let after = render(&s);
|
||||
// Where Repeat starts the stops again, the hard edge may land a pixel off.
|
||||
assert!(mean_diff(&before, &after) < 4.0, "{kind} {spread} {to}: {}", mean_diff(&before, &after));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient that repeats or reflects expands into the same whole number of objects in each run,
|
||||
/// so each run starts on an object's edge: a sharp step in the middle of each of 7 runs, expanded
|
||||
/// into about 15 objects (2 a run), lands where the canvas paints it.
|
||||
#[test]
|
||||
fn a_spread_gradient_expands_into_whole_bands_for_each_run() {
|
||||
let stops = json!([
|
||||
{"offset": 0, "color": "#ffff00"}, {"offset": 0.5, "color": "#ffff00"},
|
||||
{"offset": 0.5, "color": "#004080"}, {"offset": 1, "color": "#004080"}
|
||||
]);
|
||||
for kind in ["linear", "conic"] {
|
||||
for spread in ["repeat", "reflect"] {
|
||||
let mut s = session();
|
||||
// A conic gradient turns about the box's center.
|
||||
let start = if kind == "conic" { [100, 100] } else { [30, 100] };
|
||||
let gr = json!({"kind": kind, "spread": spread, "repeats": 7, "start": start, "end": [170, 100], "stops": stops});
|
||||
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false);
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", json!({"steps": 15}));
|
||||
let after = render(&s);
|
||||
assert!(mean_diff(&before, &after) < 2.0, "{kind} {spread}: {}", mean_diff(&before, &after));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() {
|
||||
for gradient in [
|
||||
|
||||
Reference in New Issue
Block a user