Symbols: Average sizes are sizes on the page, and a pen pressure change where the pen stays is kept

The Sizer's and the Sprayer's Average compare each instance's size on the page, so a set that
holds instances of different symbols meets at their mean drawn size. A symbol without a recorded
size is measured by its art, once per command. With Size: Average and no instance under the brush,
a sprayed instance has its symbol's own size whatever `scale` is, and new instances are spaced by
the size they are placed at. With Use Pressure Pen, a drag sample at the same position is kept when
the pressure changes by 0.05 or more.
This commit is contained in:
dotCooCoo
2026-11-18 17:34:48 -08:00
parent 3ef0e5e588
commit bae4defa45
5 changed files with 179 additions and 29 deletions
+39 -12
View File
@@ -4,8 +4,10 @@
use std::collections::HashMap;
use super::symbols::{instance_center, is_symbol_set};
use super::{Affine, Document, EngineError, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, Vec2, bad, ids_json, json, named_ids};
use super::symbols::{instance_center, is_symbol_set, stored_natural_size};
use super::{
Affine, Document, EngineError, HALF, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, Vec2, bad, ids_json, json, named_ids,
};
/// Method: how the Scruncher, Sizer, Spinner, Stainer, Screener and Styler adjust instances.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -114,8 +116,8 @@ pub(super) fn record_set_density(d: &mut Document, sets: &[NodeId], density: f64
#[derive(Clone, Debug)]
pub(super) struct Look {
pub center: Point,
/// Its size as a share of its symbol's own size (1: the symbol's size).
pub scale: f64,
/// Its size on the page: the side of a square with its area, the same measure for every symbol.
pub size: f64,
/// Its rotation in radians.
pub angle: f64,
pub opacity: f64,
@@ -123,8 +125,12 @@ pub(super) struct Look {
pub fill: Option<(Paint, f64)>,
}
/// The [`natural_side`] of each symbol measured so far in one command, so that one measure serves
/// every instance of the symbol.
pub(super) type Sides = HashMap<String, f64>;
/// The [`Look`] of instance `n` (None for another object, or an instance without a size).
pub(super) fn look(d: &Document, n: &Node) -> Option<Look> {
pub(super) fn look(d: &Document, n: &Node, sides: &mut Sides) -> Option<Look> {
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None };
let [a, b, c, e, ..] = xf.as_coeffs();
let natural = d.symbol_natural_xf(symbol).as_coeffs();
@@ -133,20 +139,41 @@ pub(super) fn look(d: &Document, n: &Node) -> Option<Look> {
if !(scale.is_finite() && scale > 0.0) {
return None;
}
let side = match sides.get(symbol) {
Some(side) => *side,
None => *sides.entry(symbol.clone()).or_insert_with(|| natural_side(d, symbol)),
};
let size = scale * side;
if !(size.is_finite() && size > 0.0) {
return None;
}
Some(Look {
center: instance_center(n)?,
scale,
size,
angle: b.atan2(a),
opacity: f64::from(n.opacity),
fill: n.appearance.fill().map(|f| (f.paint.clone(), f64::from(f.opacity))),
})
}
/// The [`Look::size`] of an instance of symbol `name` at the symbol's own size. A symbol without a
/// recorded size draws its art at the art's own size, so its art is measured.
pub(super) fn natural_side(d: &Document, name: &str) -> f64 {
let recorded = stored_natural_size(d, name).is_some_and(|(w, h)| w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0);
// Each side's root first, so that a huge size does not overflow.
let art = (!recorded).then(|| d.symbol_art_bounds(name)).flatten().map(|r| r.width().sqrt() * r.height().sqrt());
if let Some(side) = art.filter(|s| s.is_finite() && *s > 0.0) {
return side;
}
let natural = d.symbol_natural_xf(name).as_coeffs();
2.0 * HALF * natural[0].abs().max(1e-9).sqrt() * natural[3].abs().max(1e-9).sqrt()
}
/// The mean of the [`Look`]s of the instances under the brush.
#[derive(Clone, Debug)]
pub(super) struct Mean {
/// The geometric mean of the sizes.
pub scale: f64,
/// The geometric mean of the sizes ([`Look::size`]).
pub size: f64,
/// The mean direction of the rotations.
pub angle: f64,
pub opacity: f64,
@@ -226,10 +253,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option<Mean> {
return None;
}
let n = looks.len() as f64;
let (mut log_scale, mut sin, mut cos, mut opacity, mut amount, mut middle) = (0.0, 0.0, 0.0, 0.0, 0.0, Vec2::ZERO);
let (mut log_size, mut sin, mut cos, mut opacity, mut amount, mut middle) = (0.0, 0.0, 0.0, 0.0, 0.0, Vec2::ZERO);
let mut paint: Option<(&Paint, f64)> = None;
for l in looks {
log_scale += l.scale.ln();
log_size += l.size.ln();
sin += l.angle.sin();
cos += l.angle.cos();
opacity += l.opacity;
@@ -248,7 +275,7 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option<Mean> {
// One instance under the brush has no spacing there.
let gap = (with_gap && looks.len() > 1).then(|| nearest_gaps(looks).iter().sum::<f64>() / n);
Some(Mean {
scale: (log_scale / n).exp(),
size: (log_size / n).exp(),
angle,
opacity: opacity / n,
amount: amount / n,
@@ -386,7 +413,7 @@ mod tests {
use super::*;
fn at(x: f64, y: f64) -> Look {
Look { center: Point::new(x, y), scale: 1.0, angle: 0.0, opacity: 1.0, fill: None }
Look { center: Point::new(x, y), size: 20.0, angle: 0.0, opacity: 1.0, fill: None }
}
/// The distance from each instance in `from` to the nearest other one in `refs`, measured
+29 -11
View File
@@ -1,5 +1,5 @@
use super::dynamic::{fit_overrides, type_id, type_param};
use super::symbolism::{Grid, Mean, Method, look, mean, method_param, record_set_density, spacing, spray_modes, wrap_angle};
use super::symbolism::{Grid, Mean, Method, Sides, look, mean, method_param, natural_side, record_set_density, spacing, spray_modes, wrap_angle};
use super::{
Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result,
SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json,
@@ -1005,12 +1005,27 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
}
return Ok(json!({ "count": n }));
}
// Keep instances at least this far apart along the stroke (denser = closer).
let min_gap = size.0.max(size.1) * scale * spacing(density);
let side = natural_side(&st.doc, &name);
// The symbol's longest side as drawn at its own size: its art's, when it has no recorded size.
let recorded = stored_natural_size(&st.doc, &name).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0);
let extent = match recorded {
Some((w, h)) => w.max(h),
None => {
let art = st.doc.symbol_art_bounds(&name).map(|r| r.width().max(r.height()));
art.filter(|e| e.is_finite() && *e > 0.0).unwrap_or(size.0.max(size.1))
}
};
// The scale a new instance is placed at, before the User Defined size jitter. Size: Average is
// the mean size on the page under the brush, of any symbol, or the symbol's own size with none
// there (not `scale`).
let placed_scale = |near: Option<&Mean>| {
if modes.size { near.map(|m| m.size / side).filter(|k| k.is_finite() && *k > 0.0).unwrap_or(1.0) } else { scale }
};
// The instances the selected set has, for the values a new one takes as their average.
let existing = set.filter(|_| modes.any_average()).map(|g| {
let d = &st.doc;
let looks = d.node(g).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| look(d, c)).collect();
let mut sides = Sides::new();
let looks = d.node(g).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| look(d, c, &mut sides)).collect();
Grid::new(looks, radius)
});
// Each instance to add: where, the mean of the set's instances under the brush there, and the
@@ -1020,6 +1035,9 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
let (jx, jy, _) = jitter(i, *q);
let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5);
let near = existing.as_ref().and_then(|g| g.mean(*q, radius, modes.scrunch));
// Keep instances at least this far apart along the stroke (denser = closer), by the size
// the instance is placed at.
let min_gap = extent * placed_scale(near.as_ref()) * spacing(density);
// Scrunch: Average spaces new instances as the ones under the brush are spaced.
let gap = near.as_ref().and_then(|m| m.gap).filter(|_| modes.scrunch).unwrap_or(min_gap);
if placed.last().is_some_and(|(l, ..)| l.distance(c) < gap) && i > 0 {
@@ -1036,9 +1054,8 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
let (_, _, js) = jitter(i + 7, *c);
let near = near.as_ref();
// User Defined: the symbol's own size, turned the way the stroke runs, opaque, stained
// with the fill color and given the style, each in full. Size: Average is the mean size
// under the brush, or the symbol's own size with none there, without the size jitter.
let k = if modes.size { near.map_or(scale, |m| m.scale) } else { scale * (1.0 + js * 0.1) };
// with the fill color and given the style, each in full. Size: Average has no size jitter.
let k = if modes.size { placed_scale(near) } else { scale * (1.0 + js * 0.1) };
let angle = if modes.spin { near.map_or(0.0, |m| m.angle) } else { along.map_or(0.0, |v| v.atan2()) };
let turn = Affine::translate(c.to_vec2()) * Affine::rotate(angle) * Affine::translate(-c.to_vec2());
let id = d.alloc_id();
@@ -1158,6 +1175,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
// 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 };
// Use Pressure Pen: the pen's pressure at the point is the intensity there.
@@ -1166,7 +1184,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
let target = (method == Method::Average)
.then(|| {
let under = |n: &&Node| instance_center(n).is_some_and(|c| c.distance(*q) <= radius);
let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n))).collect();
let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n, &mut sides))).collect();
mean(&looks.iter().collect::<Vec<_>>(), *q, false)
})
.flatten();
@@ -1183,7 +1201,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
// 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.
let own = (method == Method::Average).then(|| d.node(*id).and_then(|n| look(d, n))).flatten();
let own = (method == Method::Average).then(|| d.node(*id).and_then(|n| look(d, n, &mut sides))).flatten();
let avg = match (method, &target, own) {
(Method::Average, Some(t), Some(cur)) => Some((t, cur)),
// No mean under the brush (every instance there without a size), or none of
@@ -1197,7 +1215,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
let out = (c - t.middle).hypot();
out <= 1e-9 || (t.reach - out).abs() < 1e-9
}
"size" => (t.scale / cur.scale - 1.0).abs() < 1e-9,
"size" => (t.size / cur.size - 1.0).abs() < 1e-9,
"spin" => wrap_angle(t.angle - cur.angle).abs() < 1e-9,
"stain" | "style" => {
(t.amount - cur.fill.as_ref().map_or(0.0, |f| f.1)).abs() < 1e-6 && (cur.fill.is_some() || t.paint.is_none())
@@ -1228,7 +1246,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
}
"size" => {
let k = match &avg {
Some((t, cur)) => (t.scale / cur.scale).powf(w.min(1.0)),
Some((t, cur)) => (t.size / cur.size).powf(w.min(1.0)),
None => (1.0 + 0.08 * w).powf(if alt { -share } else { share }),
};
// Without Proportional Resizing a drag resizes along its own direction: a
@@ -440,6 +440,77 @@ fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() {
assert_eq!(angle(&s, level), 0.0, "Average, with no instance under the brush");
}
/// Size: Average is a size on the page, the same measure for every symbol: a 20 pt symbol sprayed
/// beside an 80 pt one is 80 pt, and the Sizer brings the two to 40 pt. With no instance under the
/// brush a sprayed instance has its symbol's own size, whatever `scale` is.
#[test]
fn average_sizes_are_sizes_on_the_page_for_every_symbol() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap();
s.execute("symbol.new", &json!({"name": "Big"})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
let set = NodeId(s.execute("symbol.spray", &json!({"name": "Big", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap());
let big = members(&s, set)[0];
assert!((bounds(&s, big).width() - 80.0).abs() < 1e-9);
let spray = |s: &mut Session, at: Value| {
s.execute("symbol.spray", &json!({"name": "Dot", "points": at, "radius": 30, "scale": 2})).unwrap();
*members(s, set).last().unwrap()
};
let near = spray(&mut s, json!([[215, 150]]));
assert!((bounds(&s, near).width() - 80.0).abs() < 1e-9, "{}", bounds(&s, near).width());
let far = spray(&mut s, json!([[350, 40]]));
assert!((bounds(&s, far).width() - 20.0).abs() < 1e-9, "{}", bounds(&s, far).width());
// The Sizer: an unscaled Dot and an unscaled Big meet at the geometric mean of 20 and 80.
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap();
s.execute("symbol.new", &json!({"name": "Big"})).unwrap();
s.select(|_, sel| sel.clear()).unwrap();
let small = dot(&mut s, 200.0, 150.0);
let big = NodeId(s.execute("symbol.place", &json!({"name": "Big", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.clear()).unwrap();
let between = json!([[210, 150], [210, 150], [210, 150], [210, 150], [210, 150], [210, 150]]);
adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"}));
let (ws, wb) = (bounds(&s, small).width(), bounds(&s, big).width());
assert!(ws > 30.0 && wb < 55.0 && (ws * wb / 1600.0 - 1.0).abs() < 1e-9, "{ws} {wb}");
// A symbol without a recorded size is measured by its art: here 80 pt art drawn at its own size.
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 20, "height": 20})).unwrap();
s.execute("symbol.new", &json!({"name": "Loose"})).unwrap();
s.edit("Forget size", |d, _| {
if let Some(m) = d.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).and_then(Value::as_object_mut) {
m.remove("Loose");
}
for sym in d.symbols.iter_mut().filter(|sym| sym.name == "Loose") {
std::sync::Arc::make_mut(&mut sym.art).transform(Affine::scale(4.0), false);
}
Ok(())
})
.unwrap();
s.select(|_, sel| sel.clear()).unwrap();
let small = dot(&mut s, 200.0, 150.0);
let loose = NodeId(s.execute("symbol.place", &json!({"name": "Loose", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap());
s.select(|_, sel| sel.clear()).unwrap();
// Its width as drawn, measured by its symbol's art.
let drawn = |s: &Session| {
let d = &s.doc().unwrap().doc;
node(s, loose).geometric_bounds_with(&d.symbol_boxes()).unwrap().width()
};
assert!((drawn(&s) - 80.0).abs() < 1e-9, "{}", drawn(&s));
adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"}));
let (ws, wl) = (bounds(&s, small).width(), drawn(&s));
assert!(ws > 30.0 && wl < 55.0, "{ws} {wl}");
// A new set sprayed with Size: Average is spaced by the size it is placed at, not by `scale`.
s.select(|_, sel| sel.clear()).unwrap();
let stroke: Vec<Value> = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 20.0])).collect();
let r = s.execute("symbol.spray", &json!({"name": "Dot", "points": stroke, "radius": 2, "scale": 100})).unwrap();
assert!(r["count"].as_u64().unwrap() > 5, "{r}");
// The 80 pt art of a symbol without a recorded size spaces new instances by its own size.
s.select(|_, sel| sel.clear()).unwrap();
let stroke: Vec<Value> = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 280.0])).collect();
let r = s.execute("symbol.spray", &json!({"name": "Loose", "points": stroke, "radius": 2})).unwrap();
assert!(r["count"].as_u64().unwrap() <= 5, "{r}");
}
/// Spin: Average turns a new instance to the mean direction of the instances under the brush, and
/// Scrunch: Average spaces new instances as those under the brush are spaced.
#[test]
+34 -1
View File
@@ -236,8 +236,12 @@ impl Tool for SymbolismTool {
PointerKind::Drag if self.active => {
// Sprayer: thin the samples to a fraction of the brush; others: every few pixels.
let step = if self.id == "symbolSprayer" { (self.diameter * 0.15).max(cx.tol(3.0)) } else { cx.tol(3.0) };
// With Use Pressure Pen a change of pressure of at least 0.05 is kept where the pen
// stays (the Sprayer does not use the pressure).
let pressed = self.use_pressure && self.id != "symbolSprayer";
let thinned = self.points.last().is_some_and(|(l, f)| l.distance(p) < step && !(pressed && (sample.1 - f).abs() >= 0.05));
// Each preview carries every point so far: a long drag stops growing and previews less often.
if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|(l, _)| l.distance(p) < step) {
if self.points.len() >= MAX_STROKE_SAMPLES || thinned {
return vec![];
}
self.points.push(sample);
@@ -573,6 +577,35 @@ mod tests {
assert!(v["method"] == "random" && v.get("proportional").is_none(), "{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]
fn a_pressure_change_where_the_pen_stays_is_kept() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let stroke = |use_pressure: bool, pressures: [f32; 3]| {
let mut t = SymbolismTool::new("symbolSizer");
t.set_option("usePressure", &json!(use_pressure));
let at = |kind, pressure| PointerEvent { pressure, ..PointerEvent::new(kind, 5.0, 5.0) };
let events =
[(PointerKind::Down, pressures[0]), (PointerKind::Drag, pressures[1]), (PointerKind::Drag, pressures[2]), (PointerKind::Up, 0.0)];
// The points of the last preview, the one the drag commits.
let mut last = Value::Null;
for (kind, pressure) in events {
for a in t.pointer(&cx, &at(kind, pressure)) {
if let Action::Preview(_, v) = a {
last = v["points"].clone();
}
}
}
last
};
assert_eq!(stroke(true, [0.0, 1.0, 1.0]), json!([[5.0, 5.0, 0.0], [5.0, 5.0, 1.0]]));
assert_eq!(stroke(true, [0.5, 0.52, 0.5]), json!([[5.0, 5.0, 0.5]]));
assert_eq!(stroke(false, [0.0, 1.0, 1.0]), json!([[5.0, 5.0]]));
}
/// The Sprayer sends its six options as `attributes`, and the fill color only while Stain is
/// User Defined.
#[test]
+6 -5
View File
@@ -3790,8 +3790,8 @@ already walks Image Trace. Short agent entry points:
- `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.
- `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,
the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity.
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.
@@ -3801,9 +3801,10 @@ already walks Image Trace. Short agent entry points:
height) 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, rotation and opacity, and the stain or style of the nearest one that has one,
at the mean amount. With no instance there it has the symbol's size, no rotation, full opacity and no stain or
style. `attributes` left out means `average` for all six.
stroke point: their spacing, size on the page (of any symbol), rotation and opacity, and the stain or style of
the nearest one that has one, at the mean amount. With no instance there it has the symbol's own size (not
`scale`), no rotation, full opacity and no stain or style. New instances are spaced by the size they are placed
at. `attributes` left out means `average` for all six.
- `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