mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-20 09:23:10 +01:00
Merge pull request #8732 from storytold/train/carry7739
Symbols: the Symbol Shifter, Sizer, Stainer and Styler take Shift (#7739)
This commit is contained in:
17 files changed
+1012
-70
No files matched your search
@@ -500,11 +500,73 @@ impl Document {
|
||||
self.patterns.iter_mut().find(|p| p.name == name)
|
||||
}
|
||||
|
||||
/// The [`Self::unknown`] key that holds each symbol set's Symbol Set Density, `{set id: density}`.
|
||||
/// [`Self::reid`] gives a copy of a set in this document the density recorded for its source, and
|
||||
/// [`Self::carry_set_densities`] gives a pasted set the density recorded for it at Copy.
|
||||
pub const SYMBOL_SET_DENSITY_KEY: &'static str = "symbolSetDensity";
|
||||
|
||||
/// The Symbol Set Densities recorded for `nodes` and their descendants, by id.
|
||||
pub fn set_densities_of(&self, nodes: &[Node]) -> std::collections::BTreeMap<NodeId, serde_json::Value> {
|
||||
let Some(serde_json::Value::Object(record)) = self.unknown.get(Self::SYMBOL_SET_DENSITY_KEY) else { return Default::default() };
|
||||
let mut out = std::collections::BTreeMap::new();
|
||||
let mut stack: Vec<&Node> = nodes.iter().collect();
|
||||
while let Some(n) = stack.pop() {
|
||||
if let Some(v) = record.get(&n.id.0.to_string()) {
|
||||
out.insert(n.id, v.clone());
|
||||
}
|
||||
stack.extend(n.children().into_iter().flatten().map(|c| &**c));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Record for `copy`, a [`Self::reid`] copy of `source`, and its descendants the Symbol Set
|
||||
/// Densities that `densities` holds for `source` and its descendants, and none for those it
|
||||
/// holds none for (whatever [`Self::reid`] recorded).
|
||||
pub fn carry_set_densities(&mut self, source: &Node, copy: &Node, densities: &std::collections::BTreeMap<NodeId, serde_json::Value>) {
|
||||
if densities.is_empty() && !self.unknown.contains_key(Self::SYMBOL_SET_DENSITY_KEY) {
|
||||
return;
|
||||
}
|
||||
let mut pairs = vec![(source, copy)];
|
||||
while let Some((s, c)) = pairs.pop() {
|
||||
match densities.get(&s.id) {
|
||||
Some(v) => {
|
||||
if let serde_json::Value::Object(m) =
|
||||
self.unknown.entry(Self::SYMBOL_SET_DENSITY_KEY).or_insert_with(|| serde_json::Value::Object(Default::default()))
|
||||
{
|
||||
m.insert(c.id.0.to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) {
|
||||
m.remove(&c.id.0.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(sc), Some(cc)) = (s.children(), c.children()) {
|
||||
pairs.extend(sc.iter().zip(cc.iter()).map(|(a, b)| (&**a, &**b)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deep-clone `node` with fresh ids for it and all descendants, its images' own pixels taken
|
||||
/// in ([`Self::adopt_pixels`]).
|
||||
pub fn reid(&mut self, node: &Node) -> Node {
|
||||
let mut n = node.clone();
|
||||
n.id = self.alloc_id();
|
||||
// A copy of a symbol set keeps the Symbol Set Density recorded for its source, when the source
|
||||
// is this document's node with that id; a node from another document may share the id of an
|
||||
// unrelated set here.
|
||||
let density = self
|
||||
.unknown
|
||||
.get(Self::SYMBOL_SET_DENSITY_KEY)
|
||||
.and_then(|m| m.get(node.id.0.to_string()))
|
||||
.filter(|_| self.node(node.id) == Some(node))
|
||||
.cloned();
|
||||
if let Some(v) = density
|
||||
&& let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY)
|
||||
{
|
||||
m.insert(n.id.0.to_string(), v);
|
||||
}
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
self.adopt_image_pixels(im);
|
||||
}
|
||||
|
||||
@@ -686,6 +686,43 @@ fn reid_gives_fresh_ids() {
|
||||
assert!(!ids.contains(&a) && !ids.contains(&b));
|
||||
}
|
||||
|
||||
/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from
|
||||
/// another document with the same id does not.
|
||||
#[test]
|
||||
fn reid_copies_the_set_density_of_the_documents_own_node() {
|
||||
let (mut d, a, _) = doc_with_rects();
|
||||
d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 }));
|
||||
let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned();
|
||||
let own = d.node(a).cloned().unwrap();
|
||||
let copy = d.reid(&own);
|
||||
assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0)));
|
||||
let foreign = Node::group(a, vec![]);
|
||||
let copy = d.reid(&foreign);
|
||||
assert_eq!(density(&d, copy.id), None);
|
||||
}
|
||||
|
||||
/// A pasted copy and its descendants take the densities recorded at Copy, and none where Copy
|
||||
/// recorded none, whatever [`Document::reid`] found for an identical node in the document.
|
||||
#[test]
|
||||
fn carry_set_densities_gives_the_densities_recorded_at_copy() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 }));
|
||||
let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned();
|
||||
let (na, nb) = (d.node(a).cloned().unwrap(), d.node(b).cloned().unwrap());
|
||||
// Copy recorded nothing for `a`: the copy reid gave a density loses it.
|
||||
let copy = d.reid(&na);
|
||||
assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0)));
|
||||
d.carry_set_densities(&na, ©, &Default::default());
|
||||
assert_eq!(density(&d, copy.id), None);
|
||||
// Copy recorded 7 for `b` inside a group: the group's copy has none, and `b`'s copy has 7.
|
||||
let g = d.alloc_id();
|
||||
let group = Node::group(g, vec![Arc::new(nb)]);
|
||||
let copy = d.reid(&group);
|
||||
d.carry_set_densities(&group, ©, &[(b, serde_json::json!(7.0))].into_iter().collect());
|
||||
let inner = copy.children().unwrap()[0].id;
|
||||
assert_eq!((density(&d, copy.id), density(&d, inner)), (None, Some(serde_json::json!(7.0))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setup_round_trips_and_old_files_load() {
|
||||
let (mut d, _, _) = doc_with_rects();
|
||||
|
||||
@@ -362,7 +362,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbol Sprayer",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
|
||||
"{points: [[x,y]…] (a third value is a number or null and is not used), name?, radius?: 40, density?: 1..10 (5; a number outside 1..10 is taken as the nearer end), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one with an amount above 0, at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
|
||||
has_doc,
|
||||
symbol_spray
|
||||
),
|
||||
@@ -380,7 +380,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Symbolism Tool",
|
||||
[],
|
||||
None,
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error",
|
||||
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way; style without `shift`: from none to the userDefined amount); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size as it is. With `proportional` false a drag resizes along its own direction, the width by the drag's horizontal share and the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. The style goes on by the brush's strength at each sample, and a stroke's samples add up. With `alt` and without `shift`, userDefined and random style remove all of an instance's appearance items under the brush at once, whatever the brush's strength. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, each already at the tool's limit, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error",
|
||||
has_doc,
|
||||
symbol_adjust
|
||||
),
|
||||
|
||||
@@ -86,8 +86,9 @@ pub(super) fn spacing(density: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written
|
||||
/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it.
|
||||
const SET_DENSITY_KEY: &str = "symbolSetDensity";
|
||||
/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it, and copied to a
|
||||
/// copy of a set by [`Document::reid`].
|
||||
const SET_DENSITY_KEY: &str = Document::SYMBOL_SET_DENSITY_KEY;
|
||||
|
||||
/// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded).
|
||||
fn set_density_of(d: &Document, set: NodeId) -> Option<f64> {
|
||||
@@ -261,7 +262,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option<Mean> {
|
||||
cos += l.angle.cos();
|
||||
opacity += l.opacity;
|
||||
middle += l.center.to_vec2();
|
||||
if let Some((p, o)) = &l.fill {
|
||||
// A fill at no opacity shows nothing: it is no stain or style, and its paint is not taken.
|
||||
if let Some((p, o)) = &l.fill
|
||||
&& *o > 0.0
|
||||
{
|
||||
amount += o;
|
||||
let far = l.center.distance(at);
|
||||
if paint.is_none_or(|(_, nearest)| far < nearest) {
|
||||
|
||||
@@ -118,6 +118,20 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
|
||||
v
|
||||
}
|
||||
|
||||
/// The symbol instances in `nodes` and inside them, each once, in the order a walk of each node in
|
||||
/// turn first reaches them.
|
||||
fn instances_in<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> Vec<NodeId> {
|
||||
let (mut v, mut seen) = (vec![], std::collections::HashSet::new());
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && seen.insert(c.id) {
|
||||
v.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`.
|
||||
fn art_symbols(n: &Node, out: &mut Vec<String>) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
|
||||
@@ -917,11 +931,12 @@ fn samples(p: &Value, cmd: &str) -> Result<Vec<(Point, f64)>> {
|
||||
let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?;
|
||||
let mut v = Vec::with_capacity(a.len());
|
||||
for q in a {
|
||||
let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
|
||||
// The pressure is checked first: a point skipped for its coordinates still has a bad one refused.
|
||||
let pressure = match q.get(2) {
|
||||
None | Some(Value::Null) => 1.0,
|
||||
Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?,
|
||||
};
|
||||
let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
|
||||
v.push((Point::new(x, y), pressure.clamp(0.0, 1.0)));
|
||||
}
|
||||
if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) {
|
||||
@@ -930,13 +945,15 @@ fn samples(p: &Value, cmd: &str) -> Result<Vec<(Point, f64)>> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// The fill of the graphic style `p` names with `style`, else of the document's first style after
|
||||
/// the default one.
|
||||
/// The fill of the graphic style `p` names with `style`, else (no name, or one the document has no
|
||||
/// style for, such as the Symbol Styler's style from another document) of the document's first
|
||||
/// style after the default one.
|
||||
fn style_paint(d: &Document, p: &Value) -> Option<Paint> {
|
||||
match str_param(p, "style") {
|
||||
Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()),
|
||||
None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()),
|
||||
}
|
||||
str_param(p, "style")
|
||||
.and_then(|n| d.graphic_styles.iter().find(|g| g.name == n))
|
||||
.or(d.graphic_styles.get(1))
|
||||
.or(d.graphic_styles.first())
|
||||
.map(|g| g.appearance.fill_paint())
|
||||
}
|
||||
|
||||
/// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree).
|
||||
@@ -976,7 +993,7 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let style = style_paint(&st.doc, p);
|
||||
// Style: User Defined uses the style `style` names, so one the document does not have is an error.
|
||||
if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) {
|
||||
if let Some(n) = str_param(p, "style").filter(|n| !modes.style && !st.doc.graphic_styles.iter().any(|g| g.name == *n)) {
|
||||
return Err(bad(C, format!("unknown graphic style `{n}`")));
|
||||
}
|
||||
let size = natural_size(&st.doc, &name);
|
||||
@@ -1129,6 +1146,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let use_pressure = switch_or(p, "usePressure", false, C)?;
|
||||
let proportional = switch_or(p, "proportional", true, C)?;
|
||||
let affects_density = switch_or(p, "affectsDensity", false, C)?;
|
||||
let shift = switch_or(p, "shift", false, C)?;
|
||||
// The Symbol Shifter has no Method.
|
||||
let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? };
|
||||
// Refused while an object of a dynamic instance's art is selected: the instance stays as it is.
|
||||
@@ -1141,20 +1159,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let style_paint = style_paint(&st.doc, p);
|
||||
let candidates: Vec<NodeId> = {
|
||||
let d = &st.doc;
|
||||
let mut v = vec![];
|
||||
if st.selection.is_empty() {
|
||||
v = instances_of(d, None);
|
||||
} else {
|
||||
for id in &st.selection.objects {
|
||||
if let Some(n) = d.node(*id) {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) {
|
||||
v.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut v =
|
||||
if st.selection.is_empty() { instances_of(d, None) } else { instances_in(st.selection.objects.iter().filter_map(|id| d.node(*id))) };
|
||||
let editable = d.editable();
|
||||
v.retain(|id| editable(*id));
|
||||
v
|
||||
@@ -1172,12 +1178,39 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// for the whole stroke (and for every preview of it).
|
||||
let first = pts.first().map_or(Point::ZERO, |(q, _)| *q);
|
||||
let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 };
|
||||
// Shift with the Symbol Shifter: the instances under the brush come one place forward among
|
||||
// their siblings (with `alt`, go one place backward), once for the whole stroke.
|
||||
if tool == "shift" && shift {
|
||||
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| {
|
||||
let under: std::collections::HashSet<NodeId> = candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
d.node(*id).and_then(instance_center).is_some_and(|c| {
|
||||
pts.iter().any(|(q, pressure)| (if use_pressure { *pressure } else { intensity }) > 0.0 && c.distance(*q) < radius)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let moved = restack(d, &under, alt)?;
|
||||
Ok((moved, moved > 0))
|
||||
})?;
|
||||
return Ok(json!({ "count": count }));
|
||||
}
|
||||
// Shift with the Symbol Stainer or the Symbol Styler: the paint an instance's stain or style
|
||||
// moves toward, and the share of the brush's strength it moves by. Shift with the Symbol Sizer
|
||||
// keeps the instances where they are, Resizing Affects Density included.
|
||||
let recolor = match tool.as_str() {
|
||||
"stain" if shift => Some((Paint::solid(color), 0.15)),
|
||||
"style" if shift => Some((style_paint.clone().unwrap_or(Paint::solid(color)), 1.0)),
|
||||
_ => None,
|
||||
};
|
||||
let spread = affects_density && !shift;
|
||||
// No undo step when no instance changes (none under the brush, or Average with each at the mean).
|
||||
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| {
|
||||
let mut touched = std::collections::BTreeSet::new();
|
||||
let mut sides = Sides::new();
|
||||
for (j, (q, pressure)) in pts.iter().enumerate() {
|
||||
let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO };
|
||||
let delta = j.checked_sub(1).and_then(|i| pts.get(i)).map_or(Vec2::ZERO, |(prev, _)| *q - *prev);
|
||||
// Use Pressure Pen: the pen's pressure at the point is the intensity there.
|
||||
let strength = if use_pressure { *pressure } else { intensity };
|
||||
// Average: the mean of the instances under the brush, as they are at this point.
|
||||
@@ -1198,6 +1231,14 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if w <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
// Shift with the Symbol Stainer or the Symbol Styler: the instance keeps the amount
|
||||
// of its stain or style, and its paint moves toward the color or the style. An
|
||||
// instance without one, or without a size, is left as it is.
|
||||
if let Some((to, step)) = &recolor {
|
||||
let fill = d.node(*id).and_then(|n| look(d, n, &mut sides)).and_then(|l| l.fill);
|
||||
touched.extend(recolor_keeping_amount(d, *id, fill, to, step * w).then_some(*id));
|
||||
continue;
|
||||
}
|
||||
// Average needs the instance's own values, so it leaves an instance without a size
|
||||
// as it is; the other methods change it as before.
|
||||
// The instance's own values are read for Average only.
|
||||
@@ -1261,8 +1302,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
n.transform(about(Affine::scale_non_uniform(kx, ky)), false);
|
||||
// Resizing Affects Density: instances move away from the brush's center as
|
||||
// they grow and toward it as they shrink.
|
||||
if affects_density {
|
||||
// they grow and toward it as they shrink. Shift keeps the instances where
|
||||
// they are, so the set's density stays as it was.
|
||||
if spread {
|
||||
n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false);
|
||||
}
|
||||
}
|
||||
@@ -1280,9 +1322,10 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"stain" | "style" => {
|
||||
let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) };
|
||||
let (paint, o) = match &avg {
|
||||
// Toward the mean amount, keeping the stain or style the instance has.
|
||||
// Toward the mean amount, keeping the stain or style the instance has
|
||||
// (one at no opacity is none).
|
||||
Some((t, look)) => {
|
||||
let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o));
|
||||
let (own, cur) = look.fill.clone().filter(|(_, o)| *o > 0.0).map_or((None, 0.0), |(p, o)| (Some(p), o));
|
||||
(own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32)
|
||||
}
|
||||
// Alt with the Symbol Styler removes the instance's appearance.
|
||||
@@ -1292,11 +1335,11 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => {
|
||||
let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0);
|
||||
// The style goes on gradually, by the brush's strength there: in
|
||||
// full at the center at full intensity or pressure.
|
||||
let step = match (tool.as_str(), method) {
|
||||
// Random: the instance's share of the style, scaled by the
|
||||
// brush strength there.
|
||||
("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32,
|
||||
("style", _) => 1.0,
|
||||
("style", Method::Random) => (w * share / 2.0) as f32,
|
||||
("style", _) => w as f32,
|
||||
_ => (0.15 * w * share) as f32,
|
||||
};
|
||||
(paint, if alt { cur - step } else { cur + step })
|
||||
@@ -1324,9 +1367,108 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// An instance the stroke moved away and back again is not counted.
|
||||
// An instance the stroke moved away and back again, or reached but left as it was (at a
|
||||
// limit already), is not counted.
|
||||
touched.retain(|id| d.node(*id) != orig.node(*id));
|
||||
Ok((touched.len(), !touched.is_empty()))
|
||||
})?;
|
||||
Ok(json!({ "count": count }))
|
||||
}
|
||||
|
||||
/// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount)
|
||||
/// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's
|
||||
/// other appearance items stay as they are. A paint with no form between it and `to` (a solid
|
||||
/// color and a pattern, say) takes `to` at once, so repeated strokes below half strength still
|
||||
/// reach it. An instance without a stain or style, or one whose paint does not change, is left as
|
||||
/// it is. Returns whether it changed.
|
||||
fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool {
|
||||
use vectorcraft_doc::blend::lerp_paint;
|
||||
let Some((own, _)) = fill.filter(|(_, o)| *o > 0.0) else { return false };
|
||||
let t = t.clamp(0.0, 1.0) as f32;
|
||||
let mut paint = lerp_paint(&own, to, t);
|
||||
// `lerp_paint` switches such a pair halfway, so just below half it still gives `own`.
|
||||
if paint == own && t > 0.0 && lerp_paint(&own, to, 0.49) == own {
|
||||
paint = to.clone();
|
||||
}
|
||||
if paint == own {
|
||||
return false;
|
||||
}
|
||||
let Some(f) = d.node_mut(id).and_then(|n| n.appearance.fill_mut()) else { return false };
|
||||
f.paint = paint;
|
||||
true
|
||||
}
|
||||
|
||||
/// Bring each of `ids` one place forward among its siblings past a sibling that is not one of them
|
||||
/// (`back`: one place backward). Ones already in front of (behind) every other sibling stay, and
|
||||
/// so do the clipping path of a clip group and the ruler guides above a layer's art. Returns how
|
||||
/// many moved.
|
||||
fn restack(d: &mut Document, ids: &std::collections::HashSet<NodeId>, back: bool) -> Result<usize> {
|
||||
let parents: std::collections::BTreeSet<Option<NodeId>> = ids.iter().map(|id| d.parent_of(*id)).collect();
|
||||
let mut moved = 0;
|
||||
for par in parents {
|
||||
let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips));
|
||||
let ch = d.children_mut(par)?;
|
||||
let len = Node::guide_run_start(ch);
|
||||
if len <= floor + 1 {
|
||||
continue;
|
||||
}
|
||||
let picked = |n: &Arc<Node>| ids.contains(&n.id);
|
||||
if back {
|
||||
for i in floor + 1..len {
|
||||
if picked(&ch[i]) && !picked(&ch[i - 1]) {
|
||||
ch.swap(i - 1, i);
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for i in (floor..len - 1).rev() {
|
||||
if picked(&ch[i]) && !picked(&ch[i + 1]) {
|
||||
ch.swap(i, i + 1);
|
||||
moved += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn instance(id: u64) -> Arc<Node> {
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }))
|
||||
}
|
||||
|
||||
/// The instances come out in the order a search of the list built so far gives: nested
|
||||
/// groups, a group listed twice, a member listed after its group and one listed before it.
|
||||
#[test]
|
||||
fn instances_in_matches_searching_the_list_so_far() {
|
||||
let groups: Vec<Node> = (0..40u64)
|
||||
.map(|g| {
|
||||
let base = g * 100;
|
||||
let mut children: Vec<Arc<Node>> = (0..40).map(|i| instance(base + i)).collect();
|
||||
let inner = (40..50).map(|i| instance(base + i)).collect();
|
||||
children.insert(20, Arc::new(Node::group(NodeId(base + 90), inner)));
|
||||
children.push(Arc::new(Node::group(NodeId(base + 91), vec![])));
|
||||
Node::group(NodeId(base + 99), children)
|
||||
})
|
||||
.collect();
|
||||
let early = Node::new(NodeId(1_245), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
|
||||
let late = Node::new(NodeId(305), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
|
||||
let nodes: Vec<&Node> = std::iter::once(&early).chain(&groups).chain([&groups[0], &late, &groups[7]]).collect();
|
||||
let mut searched = vec![];
|
||||
for n in &nodes {
|
||||
n.walk(&mut |c| {
|
||||
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !searched.contains(&c.id) {
|
||||
searched.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
let found = instances_in(nodes.iter().copied());
|
||||
assert_eq!(found, searched);
|
||||
assert_eq!(found.len(), 2_000);
|
||||
assert_eq!(found[0], NodeId(1_245));
|
||||
assert!(instances_in([]).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,9 @@ pub struct Clipboard {
|
||||
/// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on
|
||||
/// no layer: pasting puts them on the layer new art goes to, moved as the objects are.
|
||||
pub guides: Vec<vectorcraft_doc::Guide>,
|
||||
/// The Symbol Set Density recorded at Copy for each copied symbol set, by its id in
|
||||
/// [`Self::nodes`]: a pasted set packs from it.
|
||||
pub set_densities: BTreeMap<NodeId, Value>,
|
||||
/// The RGB and CMYK profiles the objects' colors showed through in the document they were
|
||||
/// copied from (its assigned profiles, else the working spaces then), by name; none for objects
|
||||
/// from outside an open document. Paste compares them with the destination's
|
||||
@@ -484,6 +487,7 @@ impl Clipboard {
|
||||
})
|
||||
.collect(),
|
||||
guides: self.guides.clone(),
|
||||
set_densities: self.set_densities.clone(),
|
||||
source_profiles: self.source_profiles.clone(),
|
||||
colors_converted: self.colors_converted,
|
||||
}
|
||||
|
||||
@@ -1161,6 +1161,7 @@ impl Clipboard {
|
||||
char_styles: pick(Res::CharStyle, &src.char_styles),
|
||||
para_styles: pick(Res::ParaStyle, &src.para_styles),
|
||||
brushes,
|
||||
set_densities: src.set_densities_of(&nodes),
|
||||
nodes,
|
||||
..Default::default()
|
||||
}
|
||||
|
||||
@@ -1568,6 +1568,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for xf in placements {
|
||||
for (k, n) in clip.nodes.iter().enumerate() {
|
||||
let mut c = d.reid(n);
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c);
|
||||
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
|
||||
if xf != Affine::IDENTITY {
|
||||
|
||||
@@ -202,6 +202,7 @@ mod symbol_nine_slice;
|
||||
mod symbolbounds;
|
||||
mod symboledit;
|
||||
mod symbolism_options;
|
||||
mod symbolism_shift;
|
||||
mod symbollib;
|
||||
mod tangent_line;
|
||||
mod targeting;
|
||||
|
||||
@@ -180,6 +180,48 @@ fn average_at_the_mean_adds_no_undo_step() {
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
|
||||
/// An instance the brush reaches but leaves as it is (the Symbol Screener with Alt on an opaque
|
||||
/// instance, or without Alt on one at the lowest opacity it gives) is not counted, and a stroke
|
||||
/// that changes no instance adds no undo step.
|
||||
#[test]
|
||||
fn an_instance_left_as_it_is_is_not_counted() {
|
||||
let mut s = session();
|
||||
let (opaque, faint) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
|
||||
s.execute("transparency.set", &json!({"ids": [faint.0], "opacity": 5})).unwrap();
|
||||
let before = state(&s);
|
||||
let r = adjust(&mut s, json!({"tool": "screen", "points": [[100, 150]], "radius": 30, "intensity": 10, "alt": true}));
|
||||
assert_eq!(r["count"], 0, "Alt on an opaque instance");
|
||||
let r = adjust(&mut s, json!({"tool": "screen", "points": [[300, 150]], "radius": 30, "intensity": 10}));
|
||||
assert_eq!(r["count"], 0, "an instance at 5%");
|
||||
assert!(state(&s) == before, "a stroke that changes nothing changed the document or its history");
|
||||
// A stroke over both counts only the instance it changes.
|
||||
let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 150, "intensity": 10}));
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(node(&s, opaque).opacity < 1.0 && node(&s, faint).opacity == 0.05);
|
||||
}
|
||||
|
||||
/// Average gives an opacity below 5% when that is the mean: the Symbol Sprayer's new instance and
|
||||
/// the Symbol Screener's instances take the mean of the instances under the brush.
|
||||
#[test]
|
||||
fn average_keeps_a_mean_opacity_below_five_percent() {
|
||||
let mut s = session();
|
||||
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
|
||||
let first = members(&s, set)[0];
|
||||
s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 2})).unwrap();
|
||||
s.select(|_, sel| sel.set([set])).unwrap();
|
||||
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[215, 150]], "radius": 30})).unwrap();
|
||||
let sprayed = *members(&s, set).last().unwrap();
|
||||
assert!((node(&s, sprayed).opacity - 0.02).abs() < 1e-6, "{}", node(&s, sprayed).opacity);
|
||||
// Two instances at 0% and 4%: Average brings both toward 2%, and neither goes past it.
|
||||
let mut s = session();
|
||||
let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0));
|
||||
s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 0})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [b.0], "opacity": 4})).unwrap();
|
||||
adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"}));
|
||||
let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity);
|
||||
assert!(pa > 0.0 && pa <= 0.02 + 1e-6 && (0.02 - 1e-6..0.04).contains(&pb), "{pa} {pb}");
|
||||
}
|
||||
|
||||
/// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing.
|
||||
#[test]
|
||||
fn average_evens_out_the_stain_and_the_spacing() {
|
||||
@@ -279,6 +321,38 @@ fn an_unknown_method_is_refused() {
|
||||
assert_eq!(center(&s, a), Point::new(200.0, 150.0));
|
||||
}
|
||||
|
||||
/// `tool.setOption` refuses a Symbolism Tools Options value of the wrong kind or name, and the
|
||||
/// tool's options stay as they were.
|
||||
#[test]
|
||||
fn tool_set_option_refuses_bad_symbolism_options() {
|
||||
let mut s = session();
|
||||
let before = s.tool_options_of("symbolSizer");
|
||||
for (key, bad, want) in [
|
||||
("method", json!("smooth"), "`method` must be one of userDefined, average, random"),
|
||||
("sprayStain", json!("random"), "`sprayStain` must be one of average, userDefined"),
|
||||
("usePressure", json!("yes"), "`usePressure` must be true or false"),
|
||||
("diameter", json!("big"), "`diameter` must be a number from 2 to 2000"),
|
||||
("style", json!(3), "`style` must be a string or null"),
|
||||
("diameter", json!(1), "`diameter` must be a number from 2 to 2000"),
|
||||
] {
|
||||
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {key: bad}}));
|
||||
assert_eq!(r, Err(want.to_string()), "{key}");
|
||||
assert_eq!(s.tool_options_of("symbolSizer"), before, "{key}");
|
||||
}
|
||||
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {"method": "random", "sprayStain": "userDefined"}})).unwrap();
|
||||
assert_eq!((r["method"].as_str(), r["sprayStain"].as_str()), (Some("random"), Some("userDefined")));
|
||||
// Every option the options dialog sends is taken, together.
|
||||
let all = json!({
|
||||
"diameter": 100.0, "intensity": 6.0, "density": 4.0, "usePressure": true, "method": "average", "showBrush": false,
|
||||
"sprayScrunch": "userDefined", "spraySize": "userDefined", "spraySpin": "userDefined", "sprayScreen": "userDefined",
|
||||
"sprayStain": "average", "sprayStyle": "userDefined", "proportional": false, "affectsDensity": true,
|
||||
});
|
||||
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": all})).unwrap();
|
||||
for (key, v) in all.as_object().unwrap() {
|
||||
assert_eq!(&r[key], v, "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is
|
||||
/// not used. A pressure that isn't a number is an error.
|
||||
#[test]
|
||||
@@ -316,6 +390,13 @@ fn pen_pressure_is_the_intensity_with_use_pressure() {
|
||||
json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}),
|
||||
"a point's pressure must be a number, not \"hard\"",
|
||||
);
|
||||
// Also on a point without coordinates, beside one that has them.
|
||||
refused(
|
||||
&mut s,
|
||||
"symbol.adjust",
|
||||
json!({"tool": tool, "points": [[200, 150], [null, 0, "bad"]], "usePressure": true}),
|
||||
"a point's pressure must be a number, not \"bad\"",
|
||||
);
|
||||
}
|
||||
for key in ["usePressure", "proportional", "affectsDensity"] {
|
||||
let mut p = json!({"tool": "size", "points": [[200, 150]]});
|
||||
@@ -644,6 +725,45 @@ fn set_density_starts_from_the_density_a_set_was_sprayed_at() {
|
||||
assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a));
|
||||
}
|
||||
|
||||
/// A set duplicated packs from the density recorded for its source, and a pasted set from the
|
||||
/// density its source had at Copy: after Cut, after the source is given another density, and in
|
||||
/// another document.
|
||||
#[test]
|
||||
fn a_copied_set_packs_from_the_density_of_its_source() {
|
||||
for copy in ["duplicate", "paste", "cut", "changed after copy", "other document"] {
|
||||
let mut s = session();
|
||||
let row: Vec<Value> = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect();
|
||||
let set =
|
||||
NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
s.select(|_, sel| sel.set([set])).unwrap();
|
||||
let first = match copy {
|
||||
"duplicate" => "edit.duplicate",
|
||||
"cut" => "edit.cut",
|
||||
_ => "edit.copy",
|
||||
};
|
||||
s.execute(first, &json!({})).unwrap();
|
||||
if copy == "changed after copy" {
|
||||
s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap();
|
||||
}
|
||||
if copy == "other document" {
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
}
|
||||
if copy != "duplicate" {
|
||||
s.execute("edit.paste", &json!({})).unwrap();
|
||||
}
|
||||
let copied = s.doc().unwrap().selection.objects.clone();
|
||||
assert!(copied.len() == 1 && (copy == "other document" || copied[0] != set), "{copy}: {copied:?}");
|
||||
let ids = members(&s, copied[0]);
|
||||
let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::<Vec<_>>();
|
||||
let was = xs(&s);
|
||||
let middle = was.iter().sum::<f64>() / 4.0;
|
||||
s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [copied[0].0]})).unwrap();
|
||||
for (before, after) in was.iter().zip(xs(&s)) {
|
||||
assert!((after - (middle + (before - middle) * 0.25 / 0.95)).abs() < 1e-9, "{copy}: {before} -> {after}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of one instance takes the new density without moving, as one undo step, so a later change
|
||||
/// packs it from that density; setting the density it already has adds no undo step.
|
||||
#[test]
|
||||
@@ -719,6 +839,102 @@ fn set_density_refuses_bad_densities_and_objects_without_a_set() {
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
|
||||
/// The Symbol Styler applies the style gradually, by the brush's strength at the instance: the pen
|
||||
/// pressure with Use Pressure Pen, else the intensity, less toward the brush's edge. Random gives
|
||||
/// each instance a share of that amount.
|
||||
#[test]
|
||||
fn the_styler_applies_the_style_by_the_brushs_strength() {
|
||||
let styled = |extra: Value, x: f64| {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 100.0, 150.0);
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
let mut p = json!({"tool": "style", "points": [[x, 150]], "radius": 10, "style": "Blue"});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
adjust(&mut s, p);
|
||||
node(&s, a).appearance.fill().map_or(0.0, |f| f.opacity)
|
||||
};
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 1e-6;
|
||||
assert!(near(styled(json!({"intensity": 10}), 100.0), 1.0), "full strength at the center");
|
||||
assert!(near(styled(json!({"intensity": 5}), 100.0), 0.5));
|
||||
assert!(near(styled(json!({"intensity": 10}), 105.0), 0.5), "half way to the edge");
|
||||
assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 0.25]]}), 100.0), 0.25));
|
||||
assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 1.0]]}), 100.0), 1.0));
|
||||
assert_eq!(styled(json!({"usePressure": true, "points": [[100, 150, 0.0]]}), 100.0), 0.0, "no pressure, no style");
|
||||
// Random: instances the same distance from the point take different amounts, each from none to
|
||||
// the User Defined amount there (0.25: pressure 0.5, half way to the brush's edge).
|
||||
let mut s = session();
|
||||
let ring: Vec<NodeId> = (0..6)
|
||||
.map(|i| {
|
||||
let a = f64::from(i) * std::f64::consts::TAU / 6.0;
|
||||
dot(&mut s, 100.0 + 5.0 * a.cos(), 150.0 + 5.0 * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
adjust(&mut s, json!({"tool": "style", "points": [[100, 150, 0.5]], "radius": 10, "usePressure": true, "method": "random", "style": "Blue"}));
|
||||
let amounts: Vec<f32> = ring.iter().map(|a| node(&s, *a).appearance.fill().map_or(0.0, |f| f.opacity)).collect();
|
||||
assert!(amounts.iter().all(|a| *a <= 0.25 + 1e-6), "{amounts:?}");
|
||||
assert!(amounts.iter().any(|a| *a > 0.0), "{amounts:?}");
|
||||
assert!(amounts.iter().any(|a| (a - amounts[0]).abs() > 1e-6), "{amounts:?}");
|
||||
}
|
||||
|
||||
/// A sprayed instance's Average stain is the stain of the nearest instance whose stain shows: one
|
||||
/// at no opacity is passed over and counts as no stain in the mean amount.
|
||||
#[test]
|
||||
fn average_spray_passes_over_a_stain_at_no_opacity() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let mut s = session();
|
||||
let set =
|
||||
NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [130, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
|
||||
let ids = members(&s, set);
|
||||
assert_eq!(ids.len(), 2);
|
||||
s.edit("Stains", |d, _| {
|
||||
for (id, color, amount) in [(ids[0], Color::rgb(1.0, 0.0, 0.0), 0.0), (ids[1], Color::rgb(0.0, 0.0, 1.0), 1.0)] {
|
||||
let n = d.node_mut(id).unwrap();
|
||||
n.appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Fill(_)));
|
||||
let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
|
||||
f.opacity = amount;
|
||||
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 40})).unwrap();
|
||||
let new: Vec<NodeId> = members(&s, set).into_iter().filter(|id| !ids.contains(id)).collect();
|
||||
assert_eq!(new.len(), 1);
|
||||
let f = node(&s, new[0]).appearance.fill().cloned().unwrap();
|
||||
assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
assert!((f.opacity - 0.5).abs() < 1e-6, "{}", f.opacity);
|
||||
}
|
||||
|
||||
/// The Symbol Shifter moves an instance whose transform flattens it (it has no size), as it moves
|
||||
/// any other, and counts it.
|
||||
#[test]
|
||||
fn the_shifter_moves_an_instance_without_a_size() {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 200.0, 150.0);
|
||||
s.edit("Flatten", |d, _| {
|
||||
if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) {
|
||||
*xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [210, 150]], "radius": 40, "intensity": 10}));
|
||||
assert_eq!(r["count"], 1);
|
||||
assert!(center(&s, a).x > 200.0, "{:?}", center(&s, a));
|
||||
// Average has no mean of such instances to move toward: it leaves them as they are.
|
||||
let (before, x) = (state(&s), center(&s, a).x);
|
||||
let r = adjust(&mut s, json!({"tool": "screen", "method": "average", "points": [[x, 150]], "radius": 40, "intensity": 10}));
|
||||
assert_eq!(r["count"], 0);
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
|
||||
/// An instance with no size is shifted and screened as before; only Average, which needs its size,
|
||||
/// leaves it as it is.
|
||||
#[test]
|
||||
@@ -759,6 +975,29 @@ fn an_instance_without_a_size_is_changed_by_every_method_but_average() {
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
|
||||
/// Average Stainer: an instance whose stain is at no opacity has no stain of its own, so it takes
|
||||
/// the stain the mean picks, not its hidden paint.
|
||||
#[test]
|
||||
fn average_stain_replaces_a_stain_at_no_opacity() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let mut s = session();
|
||||
let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 120.0, 150.0));
|
||||
s.edit("Stains", |d, _| {
|
||||
for (id, color, amount) in [(a, Color::rgb(1.0, 0.0, 0.0), 0.0), (b, Color::rgb(0.0, 0.0, 1.0), 1.0)] {
|
||||
let n = d.node_mut(id).unwrap();
|
||||
let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color));
|
||||
f.opacity = amount;
|
||||
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
adjust(&mut s, json!({"tool": "stain", "method": "average", "points": [[100, 150]], "radius": 40, "intensity": 10}));
|
||||
let f = node(&s, a).appearance.fill().cloned().unwrap();
|
||||
assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
assert!(f.opacity > 0.0, "{}", f.opacity);
|
||||
}
|
||||
|
||||
/// A stroke that leaves every instance under the brush as it is (each already at full stain, or
|
||||
/// at the least opacity) counts none and adds no undo step.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
//! The symbolism tools' Shift forms in `symbol.adjust {shift}`: the Symbol Shifter's stacking
|
||||
//! order, the Symbol Sizer keeping the set's density, and the Symbol Stainer and Symbol Styler
|
||||
//! keeping their amount while the color or style changes.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use crate::*;
|
||||
|
||||
/// A document with the 20 pt square symbol "Dot" and nothing selected.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Dot"})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// An instance of Dot centered on (`x`, `y`), not selected.
|
||||
fn dot(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap());
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn center(s: &Session, id: NodeId) -> Point {
|
||||
match node(s, id).kind {
|
||||
NodeKind::SymbolInstance { xf, .. } => xf * Point::ZERO,
|
||||
other => panic!("not an instance: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn width(s: &Session, id: NodeId) -> f64 {
|
||||
node(s, id).geometric_bounds().unwrap().width()
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn state(s: &Session) -> (Document, usize) {
|
||||
((*s.doc().unwrap().doc).clone(), undo_len(s))
|
||||
}
|
||||
|
||||
fn adjust(s: &mut Session, p: Value) -> Value {
|
||||
s.execute("symbol.adjust", &p).unwrap()
|
||||
}
|
||||
|
||||
/// The children of symbol set `set`, in stacking order (the first is at the back).
|
||||
fn members(s: &Session, set: NodeId) -> Vec<NodeId> {
|
||||
node(s, set).children().unwrap().iter().map(|c| c.id).collect()
|
||||
}
|
||||
|
||||
/// The instance's fill: its color as RGB and its amount.
|
||||
fn fill(s: &Session, id: NodeId) -> Option<([f32; 3], f32)> {
|
||||
node(s, id).appearance.fill().map(|f| (f.paint.color().map_or([0.0; 3], |c| c.to_rgb()), f.opacity))
|
||||
}
|
||||
|
||||
/// A symbol set of four instances in a row at x = 40, 120, 200 and 280, selected.
|
||||
fn row(s: &mut Session) -> (NodeId, Vec<NodeId>) {
|
||||
let pts: Vec<Value> = (0..4).map(|i| json!([40.0 + 80.0 * f64::from(i), 150.0])).collect();
|
||||
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": pts, "radius": 4})).unwrap()["id"].as_u64().unwrap());
|
||||
let ids = members(s, set);
|
||||
assert_eq!(ids.len(), 4);
|
||||
(set, ids)
|
||||
}
|
||||
|
||||
/// Shift-click with the Symbol Shifter brings the instances under the brush one place forward in
|
||||
/// the set, and Alt+Shift-click sends them one place backward, without moving them on the canvas.
|
||||
#[test]
|
||||
fn shift_click_with_the_shifter_changes_the_stacking_order() {
|
||||
let mut s = session();
|
||||
let (set, ids) = row(&mut s);
|
||||
let centers: Vec<Point> = ids.iter().map(|id| center(&s, *id)).collect();
|
||||
let click = |s: &mut Session, x: f64, alt: bool| {
|
||||
adjust(s, json!({"tool": "shift", "points": [[x, 150]], "radius": 10, "intensity": 10, "shift": true, "alt": alt}))["count"].clone()
|
||||
};
|
||||
let steps = undo_len(&s);
|
||||
assert_eq!(click(&mut s, 120.0, false), 1);
|
||||
assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
|
||||
assert_eq!(undo_len(&s), steps + 1, "one undo step");
|
||||
assert_eq!(ids.iter().map(|id| center(&s, *id)).collect::<Vec<_>>(), centers, "nothing moves on the canvas");
|
||||
assert_eq!(click(&mut s, 120.0, false), 1);
|
||||
assert_eq!(members(&s, set), [ids[0], ids[2], ids[3], ids[1]]);
|
||||
// Already in front of the others: nothing changes and no undo step is added.
|
||||
let before = state(&s);
|
||||
assert_eq!(click(&mut s, 120.0, false), 0);
|
||||
assert!(state(&s) == before);
|
||||
// Alt sends it back one place at a time; at the back it stays.
|
||||
assert_eq!(click(&mut s, 120.0, true), 1);
|
||||
assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]);
|
||||
click(&mut s, 120.0, true);
|
||||
click(&mut s, 120.0, true);
|
||||
assert_eq!(members(&s, set), [ids[1], ids[0], ids[2], ids[3]]);
|
||||
assert_eq!(click(&mut s, 120.0, true), 0);
|
||||
// Two instances under the brush move together past the next one.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let both = adjust(&mut s, json!({"tool": "shift", "points": [[40, 150], [120, 150]], "radius": 10, "intensity": 10, "shift": true}));
|
||||
assert_eq!(both["count"], 2);
|
||||
assert_eq!(members(&s, set), [ids[2], ids[0], ids[1], ids[3]]);
|
||||
// Without Shift a drag moves the instances, as before.
|
||||
adjust(&mut s, json!({"tool": "shift", "points": [[280, 150], [290, 150]], "radius": 30, "intensity": 10}));
|
||||
assert!(center(&s, ids[3]).x > centers[3].x);
|
||||
}
|
||||
|
||||
/// Shift with the Symbol Sizer resizes the instances and keeps their centers where they are, even
|
||||
/// with Resizing Affects Density.
|
||||
#[test]
|
||||
fn shift_with_the_sizer_keeps_the_density() {
|
||||
let at = |affects: bool, shift: bool| {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 220.0, 150.0);
|
||||
adjust(
|
||||
&mut s,
|
||||
json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "affectsDensity": affects, "shift": shift}),
|
||||
);
|
||||
(center(&s, a), width(&s, a))
|
||||
};
|
||||
let (moved, _) = at(true, false);
|
||||
assert!(moved.x > 220.5, "{moved:?}");
|
||||
let (kept, grown) = at(true, true);
|
||||
assert!((kept.x - 220.0).abs() < 1e-9 && (kept.y - 150.0).abs() < 1e-9 && grown > 20.5, "{kept:?} {grown}");
|
||||
// It resizes as the Sizer does with Resizing Affects Density off.
|
||||
assert_eq!(at(false, false), (kept, grown));
|
||||
assert_eq!(at(false, true), (kept, grown));
|
||||
}
|
||||
|
||||
/// Shift with the Symbol Stainer keeps the stain's amount and moves its color toward the fill
|
||||
/// color; an instance without a stain is left as it is.
|
||||
#[test]
|
||||
fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() {
|
||||
let mut s = session();
|
||||
let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0));
|
||||
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150], [100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
|
||||
let (red, amount) = fill(&s, a).unwrap();
|
||||
assert!(amount > 0.2 && red[0] > 0.99 && red[2] < 0.01, "{red:?} {amount}");
|
||||
// A second fill below the stain, which Shift leaves as it is.
|
||||
s.edit("Add fill", |d, _| {
|
||||
let n = d.node_mut(a).unwrap();
|
||||
let lower = n.appearance.fill().unwrap().clone();
|
||||
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { opacity: 0.5, ..lower }));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let lower = node(&s, a).appearance.items[0].clone();
|
||||
let stain = |s: &mut Session, x: f64| {
|
||||
adjust(s, json!({"tool": "stain", "points": [[x, 150], [x, 150]], "radius": 5, "intensity": 10, "color": "#0000ff", "shift": true}))
|
||||
};
|
||||
assert_eq!(stain(&mut s, 100.0)["count"], 1);
|
||||
let (color, kept) = fill(&s, a).unwrap();
|
||||
assert_eq!(kept, amount, "the amount stays");
|
||||
assert!(color[0] < red[0] && color[2] > 0.01, "toward blue: {color:?}");
|
||||
assert_eq!((node(&s, a).appearance.items.len(), &node(&s, a).appearance.items[0]), (2, &lower), "the other fill stays");
|
||||
// More strokes go on toward blue, with the amount still the same.
|
||||
for _ in 0..30 {
|
||||
stain(&mut s, 100.0);
|
||||
}
|
||||
let (bluer, kept) = fill(&s, a).unwrap();
|
||||
assert_eq!(kept, amount);
|
||||
assert!(bluer[2] > 0.9 && bluer[0] < 0.1, "{bluer:?}");
|
||||
// Alt has no effect with Shift.
|
||||
let green = json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#00ff00", "shift": true});
|
||||
adjust(&mut s, green.clone());
|
||||
let plain = fill(&s, a);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let mut with_alt = green;
|
||||
with_alt["alt"] = json!(true);
|
||||
adjust(&mut s, with_alt);
|
||||
assert_eq!(fill(&s, a), plain);
|
||||
// No stain on b: nothing changes and no undo step is added.
|
||||
let before = state(&s);
|
||||
assert_eq!(stain(&mut s, 300.0)["count"], 0);
|
||||
assert!(state(&s) == before && fill(&s, b).is_none());
|
||||
}
|
||||
|
||||
/// Shift with the Symbol Styler keeps the amount of the instance's stain or style and moves its
|
||||
/// fill toward the selected style's fill.
|
||||
#[test]
|
||||
fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 100.0, 150.0);
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
// A red stain at part strength.
|
||||
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
|
||||
let (red, amount) = fill(&s, a).unwrap();
|
||||
assert!(red[0] > 0.99 && amount > 0.0 && amount < 0.5, "{red:?} {amount}");
|
||||
// Half the brush's strength at a point 2.5 pt from the instance: half way to blue.
|
||||
adjust(&mut s, json!({"tool": "style", "points": [[102.5, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
|
||||
let (mixed, kept) = fill(&s, a).unwrap();
|
||||
assert_eq!(kept, amount);
|
||||
assert!(mixed[0] < 0.99 && mixed[2] > 0.01, "{mixed:?}");
|
||||
// At the brush's center with full intensity it takes the style's fill.
|
||||
adjust(&mut s, json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true}));
|
||||
let (blue, kept) = fill(&s, a).unwrap();
|
||||
assert_eq!(kept, amount);
|
||||
assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}");
|
||||
}
|
||||
|
||||
/// A stain or style with no form between it and the new paint (a pattern and a solid color) takes
|
||||
/// the new paint at once, at any strength, and keeps its amount.
|
||||
#[test]
|
||||
fn shift_changes_a_paint_that_has_no_form_in_between() {
|
||||
use vectorcraft_color::Paint;
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 100.0, 150.0);
|
||||
s.edit("Pattern fill", |d, _| {
|
||||
let mut f = vectorcraft_doc::FillLayer::new(Paint::Pattern { pattern: "Tile".into(), xf: Default::default() });
|
||||
f.opacity = 0.4;
|
||||
d.node_mut(a).unwrap().appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
// Low intensity, near the brush's edge: far below half strength.
|
||||
let r = adjust(&mut s, json!({"tool": "stain", "points": [[104, 150]], "radius": 5, "intensity": 1, "color": "#ff0000", "shift": true}));
|
||||
assert_eq!(r["count"], 1);
|
||||
let f = node(&s, a).appearance.fill().cloned().unwrap();
|
||||
assert_eq!(f.opacity, 0.4, "the amount stays");
|
||||
assert!(f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.99), "{:?}", f.paint);
|
||||
}
|
||||
|
||||
/// A style name the document has no style for (the Styler's style from another document, or one
|
||||
/// since renamed or deleted) moves the fill toward the document's first style after the default
|
||||
/// one, as no name does, and the stain's amount stays.
|
||||
#[test]
|
||||
fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let styled = |style: Option<&str>| {
|
||||
let mut s = session();
|
||||
let a = dot(&mut s, 100.0, 150.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"}));
|
||||
let mut p = json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "shift": true});
|
||||
if let Some(n) = style {
|
||||
p["style"] = json!(n);
|
||||
}
|
||||
let stained = node(&s, a).appearance.fill().map(|f| f.opacity);
|
||||
adjust(&mut s, p);
|
||||
let f = node(&s, a).appearance.fill().cloned().unwrap();
|
||||
assert_eq!(Some(f.opacity), stained, "the amount stays");
|
||||
let first = s.doc().unwrap().doc.graphic_styles[1].appearance.fill_paint();
|
||||
(f.paint, first)
|
||||
};
|
||||
let (missing, first) = styled(Some("No Such Style"));
|
||||
let (none, _) = styled(None);
|
||||
assert_eq!(missing, none);
|
||||
// The paint is the first style's, not the active fill color.
|
||||
assert_eq!(none, first);
|
||||
assert_ne!(none, Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
|
||||
}
|
||||
|
||||
/// A `shift` that is not true, false or null is refused and changes nothing.
|
||||
#[test]
|
||||
fn a_bad_shift_is_refused() {
|
||||
let mut s = session();
|
||||
dot(&mut s, 100.0, 150.0);
|
||||
for tool in ["shift", "size", "stain", "style"] {
|
||||
let before = state(&s);
|
||||
let r = s.execute("symbol.adjust", &json!({"tool": tool, "points": [[100, 150]], "shift": "yes"}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "`shift` must be true or false"), "{tool}: {r:?}");
|
||||
assert!(state(&s) == before);
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,9 @@ const ROWS: &[Row] = &[
|
||||
"affectsDensity",
|
||||
],
|
||||
),
|
||||
// The graphic style the Symbol Styler and the Symbol Sprayer's User Defined Style apply, set
|
||||
// from the Graphic Styles panel.
|
||||
(&["symbolSprayer", "symbolStyler"], Some("symbolismStyle"), &["style"]),
|
||||
(&["mirrorCut"], None, &["axis", "keep"]),
|
||||
(&["puppetWarp"], None, &["showMesh", "expand"]),
|
||||
(&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]),
|
||||
|
||||
@@ -48,6 +48,8 @@ pub struct SymbolismTool {
|
||||
active: bool,
|
||||
hover: Option<Point>,
|
||||
alt: bool,
|
||||
/// Shift was held when the drag began (the Shifter, Sizer, Stainer and Styler have a Shift form).
|
||||
shift: bool,
|
||||
/// Brush diameter in points.
|
||||
pub diameter: f64,
|
||||
/// 1..10.
|
||||
@@ -113,6 +115,7 @@ impl SymbolismTool {
|
||||
active: false,
|
||||
hover: None,
|
||||
alt: false,
|
||||
shift: false,
|
||||
diameter: 80.0,
|
||||
intensity: 5.0,
|
||||
density: 5.0,
|
||||
@@ -196,6 +199,9 @@ impl SymbolismTool {
|
||||
v["proportional"] = json!(self.proportional);
|
||||
v["affectsDensity"] = json!(self.affects_density);
|
||||
}
|
||||
if self.shift && matches!(tool, "shift" | "size" | "stain" | "style") {
|
||||
v["shift"] = json!(true);
|
||||
}
|
||||
("symbol.adjust".into(), v)
|
||||
}
|
||||
}
|
||||
@@ -230,6 +236,7 @@ impl Tool for SymbolismTool {
|
||||
self.previewed = 1;
|
||||
self.active = true;
|
||||
self.alt = ev.mods.alt;
|
||||
self.shift = ev.mods.shift;
|
||||
let (c, v) = self.command(cx);
|
||||
vec![Action::Begin(self.label().into()), Action::Preview(c, v)]
|
||||
}
|
||||
@@ -577,6 +584,39 @@ mod tests {
|
||||
assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}");
|
||||
}
|
||||
|
||||
/// A drag begun with Shift sends `shift` with the Shifter, Sizer, Stainer and Styler, and only
|
||||
/// with them; one begun without it sends none.
|
||||
#[test]
|
||||
fn shift_reaches_the_tools_that_have_a_shift_form() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let cx = cx(&d, &s, &p);
|
||||
let shifted = Mods { shift: true, ..Default::default() };
|
||||
for (id, sends) in [
|
||||
("symbolShifter", true),
|
||||
("symbolSizer", true),
|
||||
("symbolStainer", true),
|
||||
("symbolStyler", true),
|
||||
("symbolScruncher", false),
|
||||
("symbolSpinner", false),
|
||||
("symbolScreener", false),
|
||||
("symbolSprayer", false),
|
||||
] {
|
||||
let mut t = SymbolismTool::new(id);
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0).with_mods(shifted));
|
||||
let Action::Preview(_, v) = &a[1] else { panic!("{a:?}") };
|
||||
assert_eq!(v.get("shift"), sends.then_some(&json!(true)), "{id}");
|
||||
// The drag keeps the Shift it began with.
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 5.0));
|
||||
let Action::Preview(_, v) = &a[0] else { panic!("{a:?}") };
|
||||
assert_eq!(v.get("shift"), sends.then_some(&json!(true)), "{id} drag");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 60.0, 5.0));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0));
|
||||
let Action::Preview(_, v) = &a[1] else { panic!("{a:?}") };
|
||||
assert!(v.get("shift").is_none(), "{id} without Shift: {v}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Use Pressure Pen a drag sample where the pen stays is kept when the pressure changes;
|
||||
/// without it, or with the same pressure, the drag keeps thinning the samples by distance.
|
||||
#[test]
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_tools::settings::SYMBOLISM;
|
||||
|
||||
use super::{DialogResult, DialogSpec, form, set_tool_options_and_close};
|
||||
use super::{DialogResult, DialogSpec, form, modal, set_tool_options_and_close};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
@@ -55,6 +55,13 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value {
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
// The rows scroll when the window is shorter than they are, so the heading and the buttons
|
||||
// stay in view.
|
||||
modal::scrolled_rows(ui, "symbolism-options-rows", |ui| rows(app, ui, d));
|
||||
false
|
||||
}
|
||||
|
||||
fn rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let unit = app.session.general_unit();
|
||||
// The tool whose options show below (the eight tools share one toolbar icon, so they are listed
|
||||
// by name).
|
||||
@@ -107,10 +114,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
ui.add_space(10.0);
|
||||
form::check(ui, d, "showBrush", tl!("Show Brush Size and Intensity"));
|
||||
false
|
||||
}
|
||||
|
||||
/// The selected symbol sets that can be edited (not locked or hidden).
|
||||
/// The selected symbol sets that can be edited (a locked or hidden one keeps its density).
|
||||
fn selected_sets(app: &VectorcraftApp) -> Vec<u64> {
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
let editable = st.doc.editable();
|
||||
@@ -123,39 +129,42 @@ fn selected_sets(app: &VectorcraftApp) -> Vec<u64> {
|
||||
}
|
||||
|
||||
/// OK: set the brush the Symbolism tools share, after giving a new Symbol Set Density to the
|
||||
/// selected symbol sets. Every option is checked first, so a value the tools refuse (a number out
|
||||
/// of its range included) leaves the symbol sets and the options as they are.
|
||||
/// selected symbol sets. A value outside its range is refused and changes nothing.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
|
||||
let mut values: Map<String, Value> =
|
||||
NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect();
|
||||
// The checkboxes and choices as the fields hold them, so a value the tools do not have is refused.
|
||||
values.extend(SWITCHES.iter().chain(&SPRAY).chain(&["method"]).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))));
|
||||
// An option `tool.setOption` refuses leaves the symbol sets as they are too.
|
||||
// Each value goes to the check as it is stored, so one of the wrong kind is refused rather than
|
||||
// read as 0 or false. A number stored as text is read as the field reads it, and other text is
|
||||
// refused.
|
||||
let stored = |k: &str| match d.fields.get(k) {
|
||||
Some(Value::String(s)) => Some(vectorcraft_doc::Unit::Points.parse(s).map_or_else(|| json!(s), |n| json!(n))),
|
||||
v => v.cloned(),
|
||||
};
|
||||
let mut values: Map<String, Value> = NUMBERS.iter().filter_map(|k| Some((k.to_string(), stored(k)?))).collect();
|
||||
values.extend(SWITCHES.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))));
|
||||
values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k)))));
|
||||
// A tool or a value `tool.setOption` refuses changes no density either: the values go through
|
||||
// both of its checks, the kinds and then each option's range, before the density changes.
|
||||
let tool = d.str("tool");
|
||||
if !SYMBOLISM.contains(&tool.as_str()) {
|
||||
return Err(format!("unknown tool `{tool}`"));
|
||||
}
|
||||
// A number, or text that reads as one (a length with its unit for the diameter).
|
||||
let readable = |v: &Value| match v {
|
||||
Value::Number(_) => true,
|
||||
Value::String(s) => vectorcraft_doc::Unit::Points.parse(s).is_some(),
|
||||
_ => false,
|
||||
};
|
||||
if let Some(k) = NUMBERS.iter().chain(&[DENSITY_WAS]).find(|k| d.fields.get(**k).is_some_and(|v| !readable(v))) {
|
||||
return Err(format!("`{k}` must be a number"));
|
||||
}
|
||||
vectorcraft_tools::symbolism::check_options(&tool, &values)?;
|
||||
vectorcraft_tools::option_check::check_values(&vectorcraft_tools::symbolism::SymbolismTool::new(&tool), &values)?;
|
||||
// The density the sets had when the dialog opened is read as a number too.
|
||||
if stored(DENSITY_WAS).is_some_and(|v| !v.is_number()) {
|
||||
return Err(format!("`{DENSITY_WAS}` must be a number"));
|
||||
}
|
||||
let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0));
|
||||
let sets = selected_sets(app);
|
||||
if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() {
|
||||
app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?;
|
||||
}
|
||||
set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values }))
|
||||
set_tool_options_and_close(app, json!({ "tool": tool, "values": values }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
@@ -168,6 +177,39 @@ mod tests {
|
||||
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
|
||||
}
|
||||
|
||||
/// In a short window the rows scroll, and the heading, OK and Cancel stay on the screen.
|
||||
#[test]
|
||||
fn the_buttons_stay_in_view_in_a_short_window() {
|
||||
let mut app = app();
|
||||
app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap();
|
||||
let mut fonts = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state(
|
||||
move |ui, app: &mut VectorcraftApp| {
|
||||
if !std::mem::replace(&mut fonts, true) {
|
||||
crate::theme::install_fonts(ui.ctx());
|
||||
return;
|
||||
}
|
||||
super::super::show(app, ui.ctx());
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
for (physical, zoom) in [(egui::vec2(1366.0, 768.0), 1.5), (egui::vec2(1280.0, 720.0), 1.5), (egui::vec2(800.0, 600.0), 1.0)] {
|
||||
h.ctx.set_zoom_factor(zoom);
|
||||
for _ in 0..12 {
|
||||
h.set_size(physical / zoom);
|
||||
h.run_steps(1);
|
||||
}
|
||||
let screen = h.ctx.content_rect();
|
||||
let heading = h.get_by_role_and_label(egui::accesskit::Role::Label, "Symbolism Tools Options").rect();
|
||||
assert!(screen.contains_rect(heading), "{physical:?} at {zoom}: the heading {heading:?} in {screen:?}");
|
||||
for label in ["OK", "Cancel"] {
|
||||
let rect = h.get_by_label(label).rect();
|
||||
assert!(screen.contains_rect(rect), "{physical:?} at {zoom}: {label} {rect:?} in {screen:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_symbolism_tools_share_the_options_ok_sets() {
|
||||
let mut app = app();
|
||||
@@ -280,6 +322,56 @@ mod tests {
|
||||
app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap();
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!((width(&app), undo(&app)), (was, steps));
|
||||
// An option that `tool.setOption` refuses changes neither the density nor the set.
|
||||
app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap();
|
||||
let fields = &mut app.ui.dialog.as_mut().unwrap().fields;
|
||||
fields.insert("density".into(), json!(9));
|
||||
fields.insert("method".into(), json!("smooth"));
|
||||
assert!(super::super::confirm(&mut app).is_err());
|
||||
assert_eq!((width(&app), undo(&app)), (was, steps));
|
||||
assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(5.0));
|
||||
// So does a checkbox or a number stored as a value of the wrong kind, or a number outside its
|
||||
// range.
|
||||
for (k, v) in [
|
||||
("diameter", json!(1)),
|
||||
("intensity", json!(11)),
|
||||
("usePressure", json!("invalid")),
|
||||
("proportional", json!(1)),
|
||||
("intensity", json!("strong")),
|
||||
("diameter", json!(true)),
|
||||
("tool", json!("pen")),
|
||||
("tool", json!(null)),
|
||||
] {
|
||||
app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap();
|
||||
let fields = &mut app.ui.dialog.as_mut().unwrap().fields;
|
||||
fields.insert("density".into(), json!(9));
|
||||
fields.insert(k.into(), v);
|
||||
assert!(super::super::confirm(&mut app).is_err(), "{k}");
|
||||
assert_eq!((width(&app), undo(&app)), (was, steps), "{k}");
|
||||
let o = app.session.tool_options_of("symbolSizer");
|
||||
assert_eq!((o["density"].as_f64(), o["usePressure"].as_bool()), (Some(5.0), Some(false)), "{k}");
|
||||
}
|
||||
// A selected set that is locked keeps its density, and OK still sets the options.
|
||||
let lock = |app: &mut VectorcraftApp, on: bool| {
|
||||
app.session
|
||||
.edit("Lock", |d, _| {
|
||||
d.node_mut(vectorcraft_doc::NodeId(set)).unwrap().locked = on;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
lock(&mut app, true);
|
||||
let steps_locked = undo(&app);
|
||||
app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(8));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!((width(&app), undo(&app)), (was, steps_locked));
|
||||
assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(8.0));
|
||||
lock(&mut app, false);
|
||||
app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(5));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
let steps = undo(&app);
|
||||
// A higher density packs the set closer, as one undo step.
|
||||
app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(9));
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
//! (Small and Large List View), shown on a square or on type; a style with no fill and no stroke
|
||||
//! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the
|
||||
//! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from
|
||||
//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one;
|
||||
//! double-click opens Graphic Style Options. Dragging a style moves it in the list (dropped on
|
||||
//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one. The
|
||||
//! style last clicked into the selection is the one the Symbol Styler and the Symbol Sprayer's User
|
||||
//! Defined Style apply. Double-click opens
|
||||
//! Graphic Style Options. Dragging a style moves it in the list (dropped on
|
||||
//! another style with Alt held, replaces that style with its look), applies it
|
||||
//! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a
|
||||
//! copy of it and of the styles highlighted with it at the end of the list; art dragged off the
|
||||
@@ -552,6 +554,11 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) {
|
||||
Some(Click::Pick(name, m)) => {
|
||||
let order: Vec<&str> = s.d.graphic_styles.iter().map(|g| g.name.as_str()).collect();
|
||||
let sel = super::swatches::click_selection(ui, "gs-anchor", selected(ui.ctx(), s.d), &order, &name, m);
|
||||
// The style clicked into the selection is the one the Symbol Styler and the Symbol
|
||||
// Sprayer's User Defined Style apply (the two share it).
|
||||
if sel.contains(&name) {
|
||||
app.run("tool.setOption", json!({"tool": "symbolStyler", "values": {"style": name}})).ok();
|
||||
}
|
||||
set_pstate(ui.ctx(), "gs-sel", sel);
|
||||
// A plain click also applies the style (with nothing selected the next object drawn
|
||||
// takes it); Shift and Cmd/Ctrl clicks only select.
|
||||
@@ -1689,15 +1696,23 @@ mod tests {
|
||||
selected(&ctx, &app.session.active().unwrap().doc.clone())
|
||||
};
|
||||
let linked = |app: &VectorcraftApp| app.session.selection_graphic_style().map(|(g, _)| g.name.clone());
|
||||
// A plain click applies the style and selects it alone.
|
||||
let styler = |app: &VectorcraftApp| app.session.tool_options_of("symbolStyler")["style"].as_str().map(str::to_string);
|
||||
// A plain click applies the style and selects it alone; the Symbol Styler takes it.
|
||||
assert_eq!(click(&mut app, 0, egui::Modifiers::NONE), [n[0].clone()]);
|
||||
assert_eq!(linked(&app).as_ref(), Some(&n[0]));
|
||||
assert_eq!(styler(&app).as_ref(), Some(&n[0]));
|
||||
// Shift-click selects from that style to the clicked one, and applies nothing.
|
||||
assert_eq!(click(&mut app, 3, egui::Modifiers::SHIFT), n[..4]);
|
||||
assert_eq!(linked(&app).as_ref(), Some(&n[0]));
|
||||
// Cmd/Ctrl-click removes a selected style and adds it back.
|
||||
assert_eq!(styler(&app).as_ref(), Some(&n[3]));
|
||||
// Cmd/Ctrl-click removes a selected style and adds it back; the Styler keeps its style
|
||||
// while one is removed.
|
||||
assert_eq!(click(&mut app, 2, egui::Modifiers::COMMAND), [n[0].clone(), n[1].clone(), n[3].clone()]);
|
||||
assert_eq!(styler(&app).as_ref(), Some(&n[3]));
|
||||
assert_eq!(click(&mut app, 2, egui::Modifiers::COMMAND), [n[0].clone(), n[1].clone(), n[3].clone(), n[2].clone()]);
|
||||
assert_eq!(styler(&app).as_ref(), Some(&n[2]));
|
||||
// The Symbol Sprayer's User Defined Style applies the same style.
|
||||
assert_eq!(app.session.tool_options_of("symbolSprayer")["style"].as_str(), Some(n[2].as_str()));
|
||||
// Shift-click extends from the style Cmd/Ctrl-clicked last.
|
||||
click(&mut app, 0, egui::Modifiers::NONE);
|
||||
click(&mut app, 2, egui::Modifiers::COMMAND);
|
||||
|
||||
+35
-8
@@ -3892,23 +3892,34 @@ already walks Image Trace. Short agent entry points:
|
||||
[the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)):
|
||||
`symbol.adjust` takes `method` (`userDefined`, `average` or `random`; not used by `shift`), `usePressure` with
|
||||
`points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size`
|
||||
`proportional` (true) and `affectsDensity` (false). `symbol.spray` takes `attributes`
|
||||
`proportional` (true) and `affectsDensity` (false). With `tool: style`, the style goes on by the brush's strength at
|
||||
each instance: one sample applies it in full only at the brush's center at intensity 10 or full pressure, and the
|
||||
samples of a stroke add up (two samples at the center at intensity 5 apply it in full). With `alt`, `userDefined`
|
||||
and `random` remove all of an instance's appearance items under the brush at once, whatever the brush's strength.
|
||||
A `style` name the document
|
||||
has no graphic style for counts as none (the document's first style after the default one). The Symbol Styler and the
|
||||
Symbol Sprayer (its User Defined Style) send the style last clicked into the Graphic Styles panel's selection. `tool.setOption` on a symbolism tool refuses a `method` or
|
||||
Symbol Sprayer option that is not one of its names, a non-number `diameter`, `intensity` or `density`, a
|
||||
`diameter` outside 2..2000 or an `intensity` or `density` outside 1..10, a non-boolean switch, and a `symbol` or
|
||||
`style` that is neither a name nor null, and sets none of the values. The options dialog's OK checks the same way
|
||||
before it changes any symbol set's density.
|
||||
`symbol.spray` takes `attributes`
|
||||
`{scrunch?, size?, spin?, screen?, stain?, style?}`, each `average` or `userDefined`, with `color`, `keepModel` and
|
||||
`style` for the User Defined stain and style (with `style: userDefined`, a `style` the document does not have is an
|
||||
error). `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol
|
||||
sets a new Symbol Set Density. VectorCraft's own rules:
|
||||
- `random` gives each instance its own share of the tool's change for the whole stroke, from none of it to twice
|
||||
it (the Spinner: a turn either way), the same each time the stroke is applied.
|
||||
it (the Spinner: a turn either way; the Styler without `shift`: from none to the `userDefined` amount), the same
|
||||
each time the stroke is applied.
|
||||
- `average` moves each instance's value toward the mean of the instances within the brush at that point: the
|
||||
Scruncher its distance from their middle toward their mean distance, the Sizer the geometric mean of their sizes
|
||||
on the page, whatever their symbols, the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity.
|
||||
`alt` does not reverse it. An instance already at the mean is left as it is, and no undo step is added when
|
||||
no instance changes. The Screener's average, and the opacity a sprayed instance takes as its average, can be
|
||||
below the 5% that the Screener otherwise stops at.
|
||||
- With `userDefined` the Styler gives each instance under the brush the whole style, whatever the intensity or the
|
||||
pen pressure; `random` scales each instance's share by the brush strength there.
|
||||
- With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the
|
||||
height) and one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows
|
||||
- With `proportional` false a drag resizes along its own direction: the width by the drag's horizontal share and
|
||||
the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike), and
|
||||
one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows
|
||||
and toward it as it shrinks.
|
||||
- A sprayed instance's `average` values are the means of the selected set's instances within `radius` of the
|
||||
stroke point: their spacing, size on the page (of any symbol), rotation and opacity, and the stain or style of
|
||||
@@ -3918,15 +3929,31 @@ already walks Image Trace. Short agent entry points:
|
||||
- `symbol.setDensity` moves each instance of a set along the line from the middle of the set's instances, to
|
||||
(1.15 − 0.1·`to`) / (1.15 − 0.1·`from`) of its distance from it (each factor at least 0.1), as one undo step, and
|
||||
adds none when no instance moves and every set already has density `to`. `from` is the density each set was
|
||||
created at or last given, and the `from` passed applies only to a set without one (a group named "Symbol Set" by
|
||||
created at or last given (a set duplicated has its source's, and a pasted set the one its source had at Copy),
|
||||
and the `from` passed applies only to a set without one (a group named "Symbol Set" by
|
||||
hand); every set then has density `to`, also one whose instances do not move (one instance, or each locked). A
|
||||
locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the
|
||||
instances moved.
|
||||
- A `method` or an attribute outside these values, a point's third number that isn't a number (in `symbol.spray`
|
||||
too, which does not use it), a `from` or `to` of `symbol.setDensity` outside 1..10, or no symbol set among its
|
||||
objects, is an error and changes nothing.
|
||||
objects, is an error and changes nothing. `symbol.spray` takes a `density` number outside 1..10 as the nearer end.
|
||||
- Average leaves an instance without a size (a scale of 0) as it is; the other methods change it. A stroke that
|
||||
changes no instance counts none and adds no undo step.
|
||||
- The symbolism tools with Shift held ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199),
|
||||
[the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)) send
|
||||
`shift: true` with `symbol.adjust`: a Shift-click with the Symbol Shifter brings the instances under the brush
|
||||
forward in the stacking order and Alt+Shift sends them backward; the Symbol Sizer keeps the set's density while it
|
||||
resizes; the Symbol Stainer and the Symbol Styler keep the amount of stain or style and move the color or style
|
||||
toward the current fill or the selected style. VectorCraft's own rules:
|
||||
- The Shifter moves each instance within `radius` of any stroke point one place forward among its siblings (with
|
||||
`alt`, one place backward), past the next one that is not under the brush, once for the whole stroke. It does not
|
||||
move them on the canvas. It returns `{count}`, the instances that moved.
|
||||
- The Sizer keeps each instance's center where it is, even with `affectsDensity`.
|
||||
- The Stainer moves an instance's paint toward `color` by the tool's amount at its distance from the point, and the
|
||||
Styler toward the style by the brush's strength there, whatever `method` is. A paint with no form between it and
|
||||
the new one (a solid color and a pattern) takes the new one at once. An instance without a stain or style is left
|
||||
as it is, and `alt` has no effect.
|
||||
- No undo step is added when nothing moves or changes.
|
||||
- Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's
|
||||
art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}`
|
||||
names the object by `path`, child indices in paint order from the art's root down through its groups (`[]` is the
|
||||
|
||||
@@ -1234,7 +1234,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`.
|
||||
- **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged).
|
||||
- **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`.
|
||||
- **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`.
|
||||
- **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off; with them, two strokes change from before: a Sprayer stroke over instances of the selected set gives its new instances their mean values, and the Symbol Styler applies the style by the brush's strength, so a click at the brush's center at the default intensity 5 applies it at half opacity instead of in full, and a stroke's samples add up; the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`.
|
||||
- **Symbolism tools with Shift** ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)): a Shift-click with the Symbol Shifter brings the instances under the brush forward in the stacking order and Alt+Shift-click sends them backward; the Symbol Sizer with Shift keeps the set's density while it resizes; the Symbol Stainer and the Symbol Styler with Shift keep the amount of stain or style and move the color or style toward the current fill or the selected style (`symbol.adjust {shift}`). VectorCraft's own rules: the Shifter moves each instance one place among its siblings, once per stroke, without moving it on the canvas; the Sizer keeps each instance's center, even with Resizing Affects Density; a stain or style with no form between it and the new paint (a solid color and a pattern) takes the new paint at once; an instance without a stain or style is left as it is, and Alt has no effect on the Stainer or the Styler with Shift. The selected style is the one last clicked into the Graphic Styles panel's selection. Tests: `crates/engine/src/tests/symbolism_shift.rs`, `symbolism::tests::shift_reaches_the_tools_that_have_a_shift_form`, `panels::graphic_styles::tests::shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style`.
|
||||
- **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`.
|
||||
- **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged).
|
||||
- **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust); Engraving adds fine-line hatching art brushes (Fine Hatching, Dense Hatching, Tapered Hatching, Broken Hatching). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`.
|
||||
|
||||
Reference in new issue
Block a user