mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-26 04:20:56 +01:00
Merge pull request #328 from storytold/m7/brushes-2
feat(brush): tilt, textured brushes, erasing inside symbols, profiles in the merge (M7)
This commit is contained in:
29 files changed
+1393
-110
No files matched your search
@@ -124,6 +124,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| Lottie keyframes and eases (hold keys, cubic Bézier eases with `o`/`i` handles, split position, shape keyframes, group transform order T · R · Skew · S · T(−anchor)); subdividing a cubic at its midpoint (de Casteljau) | `crates/render/src/lottie.rs`, `crates/render/src/lottie_keys.rs`, `crates/engine/tests/lottie_player` | The public Lottie JSON format description (Lottie Animation Community); W3C CSS Easing Functions Level 1 (`cubic-bezier`); de Casteljau's algorithm (public domain mathematics) | Open specifications. Own implementation (ADR 0089). |
|
||||
| Variable-width stroke outlines (trapezoids, outer round joins, caps) | `crates/render/src/stroke.rs` | Standard stroking construction from the public computer-graphics literature | Own implementation (ADR 0018); built-in profiles are AniCraft's own. |
|
||||
| Brush outlines (the swept tip as a signed distance field: exact distance to the convex hull of two tips, L2 for round and L∞ for square tips, minimised in closed form; traced at level zero) | `crates/geom/src/brush.rs` | Standard sweep and distance-field constructions from the public computer-graphics literature; behaviour of Animate's Brush tool learned from Adobe's public help and observation | Own implementation (ADR 0033); no Adobe code or presets. |
|
||||
| Pen tilt (altitude and azimuth as the brush's angle and width), the paper-grain texture and scattered dabs, width profiles carried through the merge by arc length | `crates/geom/src/brush.rs`, `crates/geom/src/planar.rs`, `crates/doc/src/width.rs` | W3C *Pointer Events* (Level 3: `altitudeAngle`, `azimuthAngle`); value noise from the public graphics literature; SplitMix64's finaliser (S. Vigna, public domain); Gauss–Legendre quadrature (public numerical analysis); tilt behaviour learned from Adobe's public help and observation | Own implementation (ADR 0093); no Adobe code, presets or textures. |
|
||||
| Pressure curves (monotone cubic through the curve's points: Fritsch–Butland tangents with the Fritsch–Carlson limits), Paint Brush width profiles simplified by Ramer–Douglas–Peucker, the Chalk brush's worn edge (two-octave value noise from SplitMix64's finaliser, subtracted from the brush's distance field) | `crates/geom/src/pressure.rs`, `crates/geom/src/brush.rs`, `crates/engine/src/cmds_brush.rs` | F. N. Fritsch & R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. (1980); F. N. Fritsch & J. Butland (1984); Ramer (1972) and Douglas & Peucker (1973); S. Vigna's SplitMix64 (public domain); value noise from the public graphics literature; brush library behaviour learned from Adobe's public help and observation | Own implementation (ADR 0068); the built-in brushes are AniCraft's own parameter sets, no Adobe presets. |
|
||||
| Eraser (the swept tip as a fill in the planar merge whose regions are dropped; exact fill areas by Green's theorem with five-point Gauss–Legendre quadrature) and Eyedropper | `crates/engine/src/cmds_erase.rs`, `crates/engine/src/cmds_paint.rs` | Green's theorem and Gauss–Legendre quadrature (public mathematical results); behaviour of Animate's Eraser and Eyedropper learned from Adobe's public help and observation | Own implementation (ADR 0034); no Adobe code or presets. |
|
||||
| WebAssembly plug-in host (module validation, limits, fuel, resumable host calls) | `crates/plugins` | W3C WebAssembly Core Specification 1.0 / 2.0 (W3C Royalty-Free Patent Policy); the `wasmi` interpreter (MIT OR Apache-2.0) | Host model ported from PhotoCraft's filter plug-ins (same project family and licence) and extended with the AniCraft request ABI (ADR 0017). |
|
||||
|
||||
@@ -2,6 +2,22 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Brushes and erasing, second slice: tilt, textured brushes, erasing inside symbols, profiles
|
||||
in the merge** (ADR 0093, M7).
|
||||
* **Pen tilt** shapes the Brush: it turns the tip with the way the pen leans and paints up
|
||||
to twice as wide as it lies down (the Paint Brush too). A mouse is never affected. Desktop
|
||||
systems don't pass tilt on to AniCraft yet, so the Tilt options stay hidden in Properties
|
||||
until a pen reports it; scripts and MCP send it in `draw.brush` points as
|
||||
`[x, y, pressure, altitude, azimuth]`.
|
||||
* **Textured brushes**, still vector: **Texture** lets a fixed paper grain show through the
|
||||
paint, **Scatter** throws dabs either side of the stroke. New built-in brushes **Charcoal**
|
||||
and **Spatter**.
|
||||
* **Variable-width lines are merged drawing**: a line across one, or the Eraser, cuts it, and
|
||||
each piece keeps the widths it had there. Pressured Paint Brush lines are raw now.
|
||||
* **Erased gradients** keep their gradient in place in every piece.
|
||||
* **Erasing inside symbols**: open a symbol or drawing object (double-click) and the Eraser
|
||||
erases its lines and fills; on the stage it keeps them and the status bar says how.
|
||||
* Fix: the curve fitter could send a handle far off on a tiny, nearly closed stretch.
|
||||
* **Surviving graphics card failures, and filters in the Motion Editor** (ADR 0092, M3).
|
||||
* **The stage keeps drawing when the graphics card fails mid-session**: the CPU takes it over
|
||||
at once, the status bar says so, and the graphics card is tried again after 3, 15, 60 and
|
||||
|
||||
@@ -269,6 +269,155 @@ impl ProfilePreset {
|
||||
}
|
||||
}
|
||||
|
||||
impl WidthProfile {
|
||||
/// This profile carried onto a piece of its stroke (ADR 0093): the piece runs along the
|
||||
/// stretches `spans` of `path` (the stroke's path, in path positions: `k + t` is parameter
|
||||
/// `t` of the segment command `k` draws, as `anicraft_geom::planar::Piece::spans` gives
|
||||
/// them; a stretch with `to < from` runs backwards). The piece's width at each place is the
|
||||
/// stroke's width there: every width point inside a stretch moves to the same place on the
|
||||
/// piece (positions are rescaled by arc length), and where the piece starts, ends or jumps
|
||||
/// mid-profile, a point there holds the width it had. Running backwards swaps left and
|
||||
/// right. `None` when the piece has one width.
|
||||
pub fn along(&self, path: &Path, spans: &[[f64; 2]]) -> Option<WidthProfile> {
|
||||
let m = Measure::new(path);
|
||||
let pts = self.points();
|
||||
let (first, last) = (pts.first().map_or(0.0, |p| p.t), pts.last().map_or(1.0, |p| p.t));
|
||||
let inside = |f: f32| f > first + MERGE && f < last - MERGE;
|
||||
// Each stretch: its subpath, and where it starts and ends along it (arc length).
|
||||
let parts: Vec<(usize, f64, f64)> = spans.iter().take(4096).filter_map(|sp| Some((m.locate(sp[0])?, m.locate(sp[1])?))).filter(|(a, b)| a.0 == b.0).map(|(a, b)| (a.0, a.1, b.1)).collect();
|
||||
let total: f64 = parts.iter().map(|(_, a, b)| (b - a).abs()).sum();
|
||||
if !total.is_finite() || total <= 1e-9 {
|
||||
return Some(self.clone());
|
||||
}
|
||||
let mut out: Vec<WidthPoint> = Vec::new();
|
||||
let mut cum = 0.0f64;
|
||||
let side = |f: f32, fwd: bool| {
|
||||
let (l, r) = self.at(f);
|
||||
if fwd { (l, r) } else { (r, l) }
|
||||
};
|
||||
for (i, &(sub, a, b)) in parts.iter().enumerate() {
|
||||
let len = m.sub_len.get(sub).copied().unwrap_or(0.0);
|
||||
if !len.is_finite() || len <= 1e-12 {
|
||||
continue;
|
||||
}
|
||||
let (fa, fb) = ((a / len) as f32, (b / len) as f32);
|
||||
let fwd = b >= a;
|
||||
let q = |s: f64| ((cum + (s - a).abs()) / total) as f32;
|
||||
// Joined to the stretch before it without a jump: its points carry on.
|
||||
let joined_before = i > 0 && parts.get(i - 1).is_some_and(|&(ps, _, pb)| ps == sub && (pb - a).abs() < 1e-6 * len.max(1.0));
|
||||
let joined_after = parts.get(i + 1).is_some_and(|&(ns, na, _)| ns == sub && (na - b).abs() < 1e-6 * len.max(1.0));
|
||||
let mark = |s: f64, f: f32, out: &mut Vec<WidthPoint>| {
|
||||
let (l, r) = side(f, fwd);
|
||||
out.push(WidthPoint::new(q(s), l, r));
|
||||
};
|
||||
// A width point of the stroke's own already sits there.
|
||||
let has_point = |f: f32| pts.iter().any(|p| (p.t - f).abs() < 1e-6);
|
||||
if !joined_before && (i > 0 || inside(fa)) && !has_point(fa) {
|
||||
mark(a, fa, &mut out);
|
||||
}
|
||||
let (lo, hi) = (fa.min(fb) - 1e-6, fa.max(fb) + 1e-6);
|
||||
let within: Vec<&WidthPoint> = pts.iter().filter(|p| p.t >= lo && p.t <= hi).collect();
|
||||
let ordered: Box<dyn Iterator<Item = &&WidthPoint>> = if fwd { Box::new(within.iter()) } else { Box::new(within.iter().rev()) };
|
||||
for p in ordered {
|
||||
let (l, r) = if fwd { (p.left, p.right) } else { (p.right, p.left) };
|
||||
out.push(WidthPoint::new(q(f64::from(p.t) * len), l, r));
|
||||
}
|
||||
if !joined_after && (i + 1 < parts.len() || inside(fb)) && !has_point(fb) {
|
||||
mark(b, fb, &mut out);
|
||||
}
|
||||
cum += (b - a).abs();
|
||||
}
|
||||
if out.len() > MAX_WIDTH_POINTS {
|
||||
// Evenly spaced, the ends kept.
|
||||
let n = out.len();
|
||||
let k = MAX_WIDTH_POINTS;
|
||||
out = (0..k).filter_map(|i| out.get(i * (n - 1) / (k - 1)).copied()).collect();
|
||||
}
|
||||
if out.is_empty() {
|
||||
// No point falls on the piece: it lies where the width holds, one width all along.
|
||||
let f = parts.first().and_then(|&(sub, a, _)| m.sub_len.get(sub).filter(|l| **l > 1e-12).map(|l| (a / l) as f32)).unwrap_or(0.0);
|
||||
let fwd = parts.first().is_none_or(|&(_, a, b)| b >= a);
|
||||
let (l, r) = side(f, fwd);
|
||||
out.push(WidthPoint::new(0.0, l, r));
|
||||
}
|
||||
WidthProfile::new(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Arc lengths along a path's subpaths, by path position.
|
||||
struct Measure {
|
||||
/// Each drawn command: its index, subpath, arc length where it starts, and its curve.
|
||||
segs: Vec<(usize, usize, f64, [Vec2; 4])>,
|
||||
sub_len: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Measure {
|
||||
fn new(path: &Path) -> Measure {
|
||||
use anicraft_geom::PathCmd;
|
||||
let mut segs = Vec::new();
|
||||
let mut sub_len: Vec<f64> = Vec::new();
|
||||
let (mut start, mut cur, mut acc) = (Vec2::ZERO, Vec2::ZERO, 0.0f64);
|
||||
let line = |a: Vec2, b: Vec2| [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b];
|
||||
for (k, c) in path.cmds.iter().enumerate().take(1 << 20) {
|
||||
let curve = match *c {
|
||||
PathCmd::MoveTo(p) => {
|
||||
if !sub_len.is_empty() || !segs.is_empty() {
|
||||
sub_len.push(acc);
|
||||
}
|
||||
(start, cur, acc) = (p, p, 0.0);
|
||||
continue;
|
||||
}
|
||||
PathCmd::LineTo(p) => line(cur, p),
|
||||
PathCmd::QuadTo(q, p) => [cur, cur.lerp(q, 2.0 / 3.0), p.lerp(q, 2.0 / 3.0), p],
|
||||
PathCmd::CubicTo(a, b, p) => [cur, a, b, p],
|
||||
PathCmd::Close => line(cur, start),
|
||||
};
|
||||
segs.push((k, sub_len.len(), acc, curve));
|
||||
acc += cubic_length(&curve, 1.0);
|
||||
cur = curve[3];
|
||||
}
|
||||
sub_len.push(acc);
|
||||
Measure { segs, sub_len }
|
||||
}
|
||||
|
||||
/// The subpath and arc length from its start at path position `u`.
|
||||
fn locate(&self, u: f64) -> Option<(usize, f64)> {
|
||||
if !u.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let k = u.floor();
|
||||
let t = u - k;
|
||||
// Position `k + 1` is the end of command `k`.
|
||||
let (k, t) = if t == 0.0 && k >= 1.0 && !self.segs.iter().any(|s| s.0 as f64 == k) { (k - 1.0, 1.0) } else { (k, t) };
|
||||
let i = self.segs.partition_point(|s| (s.0 as f64) < k);
|
||||
match self.segs.get(i) {
|
||||
Some(&(cmd, sub, at, c)) if cmd as f64 == k => Some((sub, at + cubic_length(&c, t))),
|
||||
// The end of the last command (or of one before a MoveTo).
|
||||
_ => {
|
||||
let &(_, sub, at, c) = self.segs.get(i.checked_sub(1)?)?;
|
||||
(t == 0.0).then(|| (sub, at + cubic_length(&c, 1.0)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Arc length of a cubic from 0 to `t` (composite five-point Gauss–Legendre on 16 pieces).
|
||||
fn cubic_length(c: &[Vec2; 4], t: f64) -> f64 {
|
||||
const G: [(f64, f64); 5] = [(0.046_910_077_030_668, 0.118_463_442_528_094_5), (0.230_765_344_947_158_45, 0.239_314_335_249_683_2), (0.5, 0.284_444_444_444_444_4), (0.769_234_655_052_841_6, 0.239_314_335_249_683_2), (0.953_089_922_969_332, 0.118_463_442_528_094_5)];
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
let p = c.map(|v| (f64::from(v.x), f64::from(v.y)));
|
||||
let speed = |s: f64| {
|
||||
let u = 1.0 - s;
|
||||
let (d0, d1, d2) = (3.0 * u * u, 6.0 * u * s, 3.0 * s * s);
|
||||
let dx = d0 * (p[1].0 - p[0].0) + d1 * (p[2].0 - p[1].0) + d2 * (p[3].0 - p[2].0);
|
||||
let dy = d0 * (p[1].1 - p[0].1) + d1 * (p[2].1 - p[1].1) + d2 * (p[3].1 - p[2].1);
|
||||
(dx * dx + dy * dy).sqrt()
|
||||
};
|
||||
const N: usize = 16;
|
||||
let h = t / N as f64;
|
||||
(0..N).map(|i| G.iter().map(|&(x, w)| w * speed((i as f64 + x) * h)).sum::<f64>() * h).sum()
|
||||
}
|
||||
|
||||
/// The unit normal on the left of direction `d` on a y-down screen (`-d.perp()`).
|
||||
pub fn left_normal(d: Vec2) -> Vec2 {
|
||||
Vec2::new(d.y, -d.x)
|
||||
@@ -403,4 +552,57 @@ mod tests {
|
||||
assert_eq!(sq[0].length(), 40.0);
|
||||
assert!(nearest_on_stroke(&[], Vec2::ZERO).is_none());
|
||||
}
|
||||
|
||||
fn near(a: (f32, f32), b: (f32, f32), tol: f32) -> bool {
|
||||
(a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_piece_of_a_stroke_keeps_the_widths_it_had_there() {
|
||||
// An asymmetric swell along a 100-long line (command 1 draws it).
|
||||
let line = Path::line(Vec2::ZERO, Vec2::new(100.0, 0.0));
|
||||
let p = WidthProfile::new(vec![WidthPoint::new(0.0, 0.5, 1.0), WidthPoint::new(0.4, 3.0, 2.0), WidthPoint::new(1.0, 1.0, 0.25)]).unwrap();
|
||||
// Uncut: the same profile.
|
||||
let whole = p.along(&line, &[[1.0, 2.0]]).unwrap();
|
||||
for (a, b) in whole.points().iter().zip(p.points()) {
|
||||
assert!((a.t - b.t).abs() < 1e-5 && a.left == b.left && a.right == b.right, "{whole:?}");
|
||||
}
|
||||
// The stretch from 20 to 70: its point at 0.4 moves to (40 − 20) / 50 = 0.4 of the piece,
|
||||
// and every place on the piece has the width it had on the stroke.
|
||||
let piece = p.along(&line, &[[1.2, 1.7]]).unwrap();
|
||||
for k in 0..=20 {
|
||||
let u = k as f32 / 20.0;
|
||||
let src = 0.2 + 0.5 * u;
|
||||
assert!(near(piece.at(u), p.at(src), 0.12), "at {u}: {:?} vs {:?}", piece.at(u), p.at(src));
|
||||
}
|
||||
assert!(piece.points().iter().any(|w| (w.t - 0.4).abs() < 1e-4 && w.left == 3.0), "{piece:?}");
|
||||
// Backwards: the far end comes first, and left and right swap.
|
||||
let back = p.along(&line, &[[1.7, 1.2]]).unwrap();
|
||||
for k in 0..=20 {
|
||||
let u = k as f32 / 20.0;
|
||||
let (l, r) = p.at(0.7 - 0.5 * u);
|
||||
assert!(near(back.at(u), (r, l), 0.12), "back at {u}: {:?} vs {:?}", back.at(u), (r, l));
|
||||
}
|
||||
// A piece where the width holds (past the last point) has none of its own.
|
||||
let flat = WidthProfile::new(vec![WidthPoint::new(0.0, 0.0, 0.0), WidthPoint::new(0.5, 2.0, 2.0)]).unwrap();
|
||||
assert!(flat.along(&line, &[[1.6, 2.0]]).is_some_and(|q| q.at(0.0) == (2.0, 2.0) && q.at(1.0) == (2.0, 2.0)));
|
||||
let one = WidthProfile::new(vec![WidthPoint::new(0.0, 0.0, 0.0), WidthPoint::new(0.5, 1.0, 1.0)]).unwrap();
|
||||
assert!(one.along(&line, &[[1.6, 2.0]]).is_none(), "nominal all along: uniform");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pieces_across_segments_and_hostile_spans() {
|
||||
// Two segments of 50 and 50: the stretch 25..75 crosses from command 1 into command 2.
|
||||
let mut path = Path::new();
|
||||
path.move_to(Vec2::ZERO);
|
||||
path.line_to(Vec2::new(50.0, 0.0));
|
||||
path.line_to(Vec2::new(50.0, 50.0));
|
||||
let p = WidthProfile::new(vec![WidthPoint::new(0.0, 1.0, 1.0), WidthPoint::new(1.0, 3.0, 3.0)]).unwrap();
|
||||
let piece = p.along(&path, &[[1.5, 2.0], [2.0, 2.5]]).unwrap();
|
||||
assert!(near(piece.at(0.0), p.at(0.25), 1e-3) && near(piece.at(1.0), p.at(0.75), 1e-3), "{piece:?}");
|
||||
// Positions past the path, not numbers, or nothing: never a panic.
|
||||
let _ = p.along(&path, &[[f64::NAN, 9.0], [-4.0, 1e300]]);
|
||||
assert!(p.along(&path, &[]).is_some());
|
||||
assert!(p.along(&Path::new(), &[[1.0, 2.0]]).is_some());
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{EngineError, Result};
|
||||
use anicraft_geom::brush::{Shaping, Tip, TipShape};
|
||||
use anicraft_geom::brush::{Shaping, TiltResponse, Tip, TipShape};
|
||||
use anicraft_geom::pressure::PressureCurve;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -85,6 +85,14 @@ pub struct BrushPreset {
|
||||
pub spacing: f32,
|
||||
/// A ragged edge, worn in by up to this percentage of the size (0..=50).
|
||||
pub jitter: f32,
|
||||
/// A paper grain of holes through the paint, as a percentage (0..=100; ADR 0093).
|
||||
pub texture: f32,
|
||||
/// Dabs thrown either side of the line, up to this percentage of the size (0..=200).
|
||||
pub scatter: f32,
|
||||
/// The pen's tilt turns the tip (its angle plus the pen's azimuth).
|
||||
pub tilt_angle: bool,
|
||||
/// The pen's tilt widens the tip (up to twice as wide lying flat).
|
||||
pub tilt_width: bool,
|
||||
}
|
||||
|
||||
impl Default for BrushPreset {
|
||||
@@ -104,12 +112,16 @@ impl Default for BrushPreset {
|
||||
taper_end: 0.0,
|
||||
spacing: 0.0,
|
||||
jitter: 0.0,
|
||||
texture: 0.0,
|
||||
scatter: 0.0,
|
||||
tilt_angle: false,
|
||||
tilt_width: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in presets: `(key, name)`, in the order the library shows them.
|
||||
pub const BUILTIN: [(&str, &str); 7] = [
|
||||
pub const BUILTIN: [(&str, &str); 9] = [
|
||||
("pencil", "Pencil"),
|
||||
("ink_pen", "Ink Pen"),
|
||||
("calligraphy", "Flat Calligraphy"),
|
||||
@@ -117,6 +129,8 @@ pub const BUILTIN: [(&str, &str); 7] = [
|
||||
("marker", "Marker"),
|
||||
("chalk", "Chalk"),
|
||||
("dotted", "Dotted"),
|
||||
("charcoal", "Charcoal"),
|
||||
("spatter", "Spatter"),
|
||||
];
|
||||
|
||||
/// A one-line description of each built-in preset, for tooltips.
|
||||
@@ -129,6 +143,8 @@ pub fn builtin_hint(key: &str) -> &'static str {
|
||||
"marker" => "A chisel-tipped marker of one width, whatever the pressure.",
|
||||
"chalk" => "A broad stroke with a ragged, worn edge.",
|
||||
"dotted" => "Round dots spaced along the stroke.",
|
||||
"charcoal" => "A soft, broad stroke with the paper's grain showing through; it follows the pen's tilt.",
|
||||
"spatter" => "Drops of paint thrown either side of the stroke.",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
@@ -145,6 +161,8 @@ pub fn builtin(key: &str) -> Option<BrushPreset> {
|
||||
"marker" => BrushPreset { size: 16.0, shape: Shape::Square, angle: 30.0, roundness: 45.0, smoothing: 40.0, pressure_size: false, ..d },
|
||||
"chalk" => BrushPreset { size: 20.0, roundness: 80.0, angle: 20.0, smoothing: 40.0, jitter: 18.0, ..d },
|
||||
"dotted" => BrushPreset { size: 8.0, smoothing: 60.0, pressure_size: false, spacing: 220.0, ..d },
|
||||
"charcoal" => BrushPreset { size: 24.0, roundness: 60.0, angle: 30.0, smoothing: 45.0, curve: PressureCurve::SOFT, jitter: 8.0, texture: 35.0, tilt_angle: true, tilt_width: true, ..d },
|
||||
"spatter" => BrushPreset { size: 7.0, smoothing: 50.0, spacing: 60.0, scatter: 140.0, ..d },
|
||||
_ => d,
|
||||
})
|
||||
}
|
||||
@@ -167,6 +185,8 @@ impl BrushPreset {
|
||||
self.spacing = self.spacing.max(5.0);
|
||||
}
|
||||
self.jitter = c(self.jitter, 0.0, 50.0, 0.0);
|
||||
self.texture = c(self.texture, 0.0, 100.0, 0.0);
|
||||
self.scatter = c(self.scatter, 0.0, 200.0, 0.0);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -175,7 +195,16 @@ impl BrushPreset {
|
||||
}
|
||||
|
||||
pub fn shaping(&self) -> Shaping {
|
||||
Shaping { taper_start: self.taper_start / 100.0, taper_end: self.taper_end / 100.0, spacing: self.spacing / 100.0, jitter: self.jitter / 100.0 }.sanitized()
|
||||
Shaping {
|
||||
taper_start: self.taper_start / 100.0,
|
||||
taper_end: self.taper_end / 100.0,
|
||||
spacing: self.spacing / 100.0,
|
||||
jitter: self.jitter / 100.0,
|
||||
texture: self.texture / 100.0,
|
||||
scatter: self.scatter / 100.0,
|
||||
tilt: TiltResponse { angle: self.tilt_angle, width: self.tilt_width },
|
||||
}
|
||||
.sanitized()
|
||||
}
|
||||
|
||||
/// The tip's size factor input at a measured pressure: the curve's output when pressure
|
||||
@@ -225,6 +254,10 @@ impl BrushPreset {
|
||||
return Err(EngineError::Param("param 'spacing' must be 0 (a continuous stroke) or from 5 to 1000 %".into()));
|
||||
}
|
||||
b.jitter = r(p, "jitter", 0.0..=50.0, b.jitter)?;
|
||||
b.texture = r(p, "texture", 0.0..=100.0, b.texture)?;
|
||||
b.scatter = r(p, "scatter", 0.0..=200.0, b.scatter)?;
|
||||
b.tilt_angle = opt_bool(p, "tilt_angle")?.unwrap_or(b.tilt_angle);
|
||||
b.tilt_width = opt_bool(p, "tilt_width")?.unwrap_or(b.tilt_width);
|
||||
Ok(b)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,6 +77,8 @@ fn every_preset_paints_within_its_area_bounds() {
|
||||
("chalk", 0.35, 0.55), // its edge worn in
|
||||
// Dots 2.2 sizes apart, each a quarter π of size²: π / 8.8 = 0.357 of length × size.
|
||||
("dotted", 0.33, 0.38),
|
||||
("charcoal", 0.38, 0.52), // a 60 % oval with the paper grain through it
|
||||
("spatter", 0.4, 0.65), // dabs 0.6 sizes apart, 60–100 % of the size, thrown aside
|
||||
];
|
||||
assert_eq!(bounds.len(), BUILTIN.len(), "every built-in has bounds");
|
||||
for (key, lo, hi) in bounds {
|
||||
|
||||
@@ -226,3 +226,84 @@ fn a_calligraphic_stroke_merges_whole() {
|
||||
.collect();
|
||||
assert!(areas[0] > 7000.0 && (areas[0] - areas[1]).abs() < 1.0, "{areas:?}");
|
||||
}
|
||||
|
||||
// ----- ADR 0093: tilt and texture --------------------------------------------------------------
|
||||
|
||||
/// A horizontal drag 200 long at y 100 with the pen held at `altitude` toward `azimuth`.
|
||||
fn tilted(altitude: f32, azimuth: f32) -> Vec<[f32; 5]> {
|
||||
(0..=30).map(|i| [100.0 + 200.0 * i as f32 / 30.0, 100.0, 1.0, altitude, azimuth]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tilt_turns_and_widens_the_tip_and_a_mouse_is_unaffected() {
|
||||
// A flat nib along the drag paints thin; the pen leaning across it (90°) stands it up.
|
||||
let flat = json!({"size": 20, "roundness": 20, "angle": 0, "smoothing": 0});
|
||||
let paint = |extra: Value, pts: Value| {
|
||||
let mut s = blank(true);
|
||||
let mut p = flat.clone();
|
||||
p["points"] = pts;
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
run(&mut s, "draw.brush", p);
|
||||
shapes(&s).remove(0).0
|
||||
};
|
||||
let across = paint(json!({"tilt_angle": true}), json!(tilted(30.0, 90.0)));
|
||||
assert!((bounds(&across).height() - 20.0).abs() < 0.8, "{:?}", bounds(&across));
|
||||
// Off, or without tilt in the points (a mouse), the nib stays as set.
|
||||
let off = paint(json!({}), json!(tilted(30.0, 90.0)));
|
||||
assert!((bounds(&off).height() - 4.0).abs() < 0.8, "{:?}", bounds(&off));
|
||||
let mouse = paint(json!({"tilt_angle": true, "tilt_width": true}), json!(stroke(100.0, 100.0, 300.0, 100.0)));
|
||||
assert_eq!(mouse, paint(json!({}), json!(stroke(100.0, 100.0, 300.0, 100.0))), "no tilt, no change");
|
||||
// Width: a round 10 brush laid flat paints 20 wide (1 + lean), half way down 15.
|
||||
let round = |alt: f32| {
|
||||
let mut s = blank(true);
|
||||
run(&mut s, "draw.brush", json!({"points": tilted(alt, 0.0), "size": 10, "smoothing": 0, "tilt_width": true}));
|
||||
bounds(&shapes(&s).remove(0).0).height()
|
||||
};
|
||||
assert!((round(0.0) - 20.0).abs() < 0.5 && (round(45.0) - 15.0).abs() < 0.5 && (round(90.0) - 10.0).abs() < 0.5, "{} {} {}", round(0.0), round(45.0), round(90.0));
|
||||
// The Paint Brush: tilt widens its stroke's profile.
|
||||
let mut s = blank(true);
|
||||
run(&mut s, "draw.brush", json!({"points": tilted(0.0, 0.0), "size": 6, "as_stroke": true, "tilt_width": true, "pressure_size": false}));
|
||||
let (sh, _) = shapes(&s).remove(0);
|
||||
let prof = sh.stroke.as_ref().and_then(|st| st.profile.clone()).expect("a profile");
|
||||
assert!((prof.at(0.5).0 - 2.0).abs() < 0.02, "{:?}", prof.at(0.5));
|
||||
// Bad tilts are errors; tilt past the ends is clamped.
|
||||
assert!(s.execute("draw.brush", &json!({"points": [[0, 0, 1, "up", 0]]})).is_err());
|
||||
assert!(s.execute("draw.brush", &json!({"points": [[0, 0, 1, 0]]})).is_err(), "altitude without azimuth");
|
||||
run(&mut s, "draw.brush", json!({"points": [[0, 0, 1, -40, 1000]], "tilt_width": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn textured_and_scattered_brushes_paint_vector_fills_that_merge() {
|
||||
let mut s = blank(false);
|
||||
let r = run(&mut s, "draw.brush", json!({"points": stroke(100.0, 200.0, 400.0, 220.0), "preset": "charcoal"}));
|
||||
assert_eq!(r["merged"], true, "raw paint, merged like any other");
|
||||
let raw: Vec<Shape> = shapes(&s).into_iter().map(|(sh, _)| sh).collect();
|
||||
assert!(raw.iter().all(|sh| sh.merge && fill_of(sh).is_some()));
|
||||
let holes: usize = raw.iter().map(|sh| sh.path.cmds.iter().filter(|c| matches!(c, anicraft_geom::PathCmd::MoveTo(_))).count()).sum();
|
||||
assert!(holes > 10, "the paper grain shows through: {holes} loops");
|
||||
// The same stroke again gives the same paint.
|
||||
let mut t = blank(false);
|
||||
run(&mut t, "draw.brush", json!({"points": stroke(100.0, 200.0, 400.0, 220.0), "preset": "charcoal"}));
|
||||
assert_eq!(shapes(&s), shapes(&t));
|
||||
// Spatter throws drops either side; the file keeps them.
|
||||
run(&mut s, "draw.brush", json!({"points": stroke(100.0, 400.0, 400.0, 400.0), "preset": "spatter", "color": BLUE}));
|
||||
let json = crate::format::to_json(&s.doc).unwrap();
|
||||
assert_eq!(crate::format::from_json(&json).unwrap(), s.doc);
|
||||
for p in [json!({"points": [[0, 0]], "texture": 101}), json!({"points": [[0, 0]], "scatter": -1}), json!({"points": [[0, 0]], "tilt_angle": "yes"})] {
|
||||
assert!(s.execute("draw.brush", &p).is_err(), "{p}");
|
||||
}
|
||||
let _ = RED;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pressured_paint_brush_line_is_raw_now() {
|
||||
// ADR 0068 drew these as objects because profiles didn't merge; ADR 0093 merges them.
|
||||
let mut s = blank(false);
|
||||
let pts: Vec<[f32; 3]> = (0..=20).map(|i| [100.0 + 10.0 * i as f32, 100.0, 0.2 + 0.04 * i as f32]).collect();
|
||||
run(&mut s, "draw.brush", json!({"points": pts, "as_stroke": true, "size": 8}));
|
||||
let all = shapes(&s);
|
||||
assert_eq!(all.len(), 1);
|
||||
assert!(all[0].0.merge && all[0].0.stroke.as_ref().is_some_and(|st| st.profile.is_some()));
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, MAX_WIDTH_POINTS, Paint, Rgba, Shape, Stroke, WidthPoint, WidthProfile};
|
||||
use anicraft_geom::planar;
|
||||
use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tip, TipShape, centre_stroke, outline_shaped};
|
||||
use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tilt, Tip, TipShape, centre_stroke, outline_shaped};
|
||||
use anicraft_geom::{Affine, FillRule, Path, PathCmd, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
@@ -20,12 +20,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c(
|
||||
"draw.brush",
|
||||
"Brush Stroke",
|
||||
"{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}",
|
||||
"{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}",
|
||||
true,
|
||||
draw_brush as crate::RunFn,
|
||||
),
|
||||
c("brush.preset_list", "Brush Presets", "{} the built-in brushes and yours, with their settings", false, preset_list),
|
||||
c("brush.preset_save", "Save Brush", "{name, from? (a preset to start from; default: the plain brush), size?, shape?, angle?, roundness?, smoothing?, curve?, pressure_size?, pressure_opacity?, taper_start?, taper_end?, spacing?, jitter? (as draw.brush)} saves a brush of your own (replacing yours of that name; kept in your preferences)", false, preset_save),
|
||||
c("brush.preset_save", "Save Brush", "{name, from? (a preset to start from; default: the plain brush), size?, shape?, angle?, roundness?, smoothing?, curve?, pressure_size?, pressure_opacity?, taper_start?, taper_end?, spacing?, jitter?, texture?, scatter?, tilt_angle?, tilt_width? (as draw.brush)} saves a brush of your own (replacing yours of that name; kept in your preferences)", false, preset_save),
|
||||
c("brush.preset_rename", "Rename Brush", "{name, to}", false, preset_rename),
|
||||
c("brush.preset_delete", "Delete Brush", "{name} deletes a brush of your own (asks first: it can't be undone)", false, preset_delete),
|
||||
c("brush.preset_export", "Export Brushes", "{path, names? (default: all yours)} writes your brushes to a brush set file (JSON)", false, preset_export),
|
||||
@@ -136,7 +136,7 @@ fn paint_region(s: &mut Session, mode: PaintMode, start: Vec2, object: bool) ->
|
||||
}
|
||||
|
||||
pub(crate) fn samples(p: &Value) -> Result<Vec<Sample>> {
|
||||
let bad = || EngineError::Param("param 'points' must be a list of [x, y] or [x, y, pressure]".into());
|
||||
let bad = || EngineError::Param("param 'points' must be a list of [x, y], [x, y, pressure] or [x, y, pressure, altitude, azimuth]".into());
|
||||
let list = p.get("points").and_then(Value::as_array).ok_or_else(bad)?;
|
||||
if list.is_empty() {
|
||||
return Err(EngineError::Param("param 'points' needs at least one point".into()));
|
||||
@@ -146,7 +146,7 @@ pub(crate) fn samples(p: &Value) -> Result<Vec<Sample>> {
|
||||
}
|
||||
list.iter()
|
||||
.map(|v| {
|
||||
let xyp = v.as_array().filter(|a| (2..=3).contains(&a.len())).ok_or_else(bad)?;
|
||||
let xyp = v.as_array().filter(|a| matches!(a.len(), 2 | 3 | 5)).ok_or_else(bad)?;
|
||||
let n = |i: usize| xyp.get(i).and_then(Value::as_f64).map(|f| f as f32).filter(|f| f.is_finite());
|
||||
let at = Vec2::new(n(0).ok_or_else(bad)?, n(1).ok_or_else(bad)?);
|
||||
// Pressure is a measurement: tablets and arithmetic stray a little past 0..1, so it
|
||||
@@ -155,7 +155,19 @@ pub(crate) fn samples(p: &Value) -> Result<Vec<Sample>> {
|
||||
None => 1.0,
|
||||
Some(_) => n(2).ok_or_else(|| EngineError::Param("a point's pressure must be a number from 0 to 1".into()))?.clamp(0.0, 1.0),
|
||||
};
|
||||
Ok(Sample { at, pressure })
|
||||
// Tilt (ADR 0093): the pen's altitude (90 upright .. 0 flat) and azimuth (the way
|
||||
// it leans on the stage, clockwise from +x), both in degrees, as Pointer Events
|
||||
// report them. A measurement too: the altitude is clamped, the azimuth wraps.
|
||||
let tilt = match (xyp.get(3), xyp.get(4)) {
|
||||
(Some(_), Some(_)) => {
|
||||
let bad_tilt = || EngineError::Param("a point's altitude and azimuth must be numbers of degrees".into());
|
||||
let altitude = n(3).filter(|a| a.abs() <= 1e6).ok_or_else(bad_tilt)?.clamp(0.0, 90.0);
|
||||
let azimuth = n(4).filter(|a| a.abs() <= 1e6).ok_or_else(bad_tilt)?;
|
||||
Some(Tilt { altitude, azimuth })
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
Ok(Sample { at, pressure, tilt })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -226,7 +238,7 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let color = Rgba { a: color.a * pressure_opacity(&b, &pts), ..color };
|
||||
let object = object_param(s, p)?;
|
||||
// Pressure through the curve (ADR 0068) before it sizes the tip.
|
||||
let pts: Vec<Sample> = pts.iter().map(|x| Sample { at: x.at, pressure: b.size_pressure(x.pressure) }).collect();
|
||||
let pts: Vec<Sample> = pts.iter().map(|x| Sample { pressure: b.size_pressure(x.pressure), ..*x }).collect();
|
||||
|
||||
// Smoothing and accuracy are screen distances, so a stroke looks the same at any zoom: at 50
|
||||
// the centre line may wander 3.3 screen points from the hand, at 0 a third of a point.
|
||||
|
||||
@@ -111,7 +111,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2,
|
||||
// A gradient or bitmap from the fill swatch is in stage space: with Lock Fill it stays where
|
||||
// it is on the stage, else it is fitted to the new shape (ADR 0074).
|
||||
let fill = fill.map(|f| if s.style.lock_fill || matches!(f, Paint::Solid(_)) { f.transformed(&Affine::translate(-origin.x, -origin.y)) } else { f.fitted(&local.bounds()) });
|
||||
let merge = !object && crate::merge::can_merge(stroke.as_ref());
|
||||
let merge = !object;
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
|
||||
@@ -85,11 +85,22 @@ fn erase(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Erases `eraser` (keyframe space) from the active layer's raw shapes, as `mode` says.
|
||||
pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: Vec2) -> Result<Value> {
|
||||
let nothing = |why: &str| Ok(json!({"erased": false, "mode": mode.key(), "elements": [], "reason": why}));
|
||||
// Nothing may change when nothing is erased (no keyframe made, no undo step).
|
||||
let before = s.doc.clone();
|
||||
let els = s.editable_keyframe()?.elements.clone();
|
||||
let area = eraser.bounds().inflate(2.0 * SNAP);
|
||||
// What the eraser passes over and keeps (ADR 0093): symbols, and drawing objects, groups and
|
||||
// text. Each opens for editing in place, where its raw shapes erase.
|
||||
let kept = kept_under(s, &els, eraser);
|
||||
let nothing = |why: &str| {
|
||||
let why = match kept {
|
||||
(0, 0) => why.to_string(),
|
||||
(_, 0) => "the eraser keeps symbols on the stage; double-click one with the Selection tool (or select it and use Edit Symbols) to erase inside it".to_string(),
|
||||
(0, _) => "the eraser keeps drawing objects; double-click one with the Selection tool to erase inside it".to_string(),
|
||||
_ => "the eraser keeps symbols and drawing objects; double-click one with the Selection tool to erase inside it".to_string(),
|
||||
};
|
||||
Ok(json!({"erased": false, "mode": mode.key(), "elements": [], "reason": why, "kept": {"symbols": kept.0, "objects": kept.1}}))
|
||||
};
|
||||
let touching: Vec<usize> = (0..els.len()).filter(|&i| els.get(i).and_then(|e| mergeable(e).map(|sh| !reach(sh, &e.transform).intersect(&area).is_empty())).unwrap_or(false)).collect();
|
||||
let el = |i: &usize| els.get(*i).map(|e| e.as_ref());
|
||||
let is_fill = |i: &usize| el(i).and_then(mergeable).is_some_and(|sh| sh.fill.is_some());
|
||||
@@ -142,7 +153,32 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start:
|
||||
// What stays selected: the rest of the selection, and what is left of selected shapes.
|
||||
s.selection.retain(|l, id| l != here || !gone.contains(&id));
|
||||
s.selection.extend_on(here, picked);
|
||||
Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0)}))
|
||||
Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0), "kept": {"symbols": kept.0, "objects": kept.1}}))
|
||||
}
|
||||
|
||||
/// How many symbol instances, and how many other elements that are not raw shapes (drawing
|
||||
/// objects, groups, text), the eraser's outline reaches on the keyframe: what it keeps.
|
||||
fn kept_under(s: &Session, els: &[std::sync::Arc<Element>], eraser: &Path) -> (usize, usize) {
|
||||
let area = eraser.bounds();
|
||||
let (mut symbols, mut objects) = (0, 0);
|
||||
for e in els.iter().take(100_000) {
|
||||
if mergeable(e).is_some() || matches!(e.kind, ElementKind::Camera) {
|
||||
continue;
|
||||
}
|
||||
let b = match &e.kind {
|
||||
ElementKind::Shape(sh) => reach(sh, &e.transform),
|
||||
_ => s.element_bounds(e.id),
|
||||
};
|
||||
if b.intersect(&area).is_empty() {
|
||||
continue;
|
||||
}
|
||||
if matches!(e.kind, ElementKind::Symbol { .. }) {
|
||||
symbols += 1;
|
||||
} else {
|
||||
objects += 1;
|
||||
}
|
||||
}
|
||||
(symbols, objects)
|
||||
}
|
||||
|
||||
/// Total fill area and stroke length of raw shapes, in keyframe space. Fill areas are exact
|
||||
|
||||
@@ -228,3 +228,130 @@ fn bad_params_are_errors_and_plug_ins_may_erase() {
|
||||
assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
// ----- ADR 0093: gradients and width profiles through the merge, erasing inside symbols --------
|
||||
|
||||
#[test]
|
||||
fn an_erased_gradient_keeps_its_gradient_in_both_pieces_where_it_was() {
|
||||
let mut s = blank(false);
|
||||
let stops = vec![anicraft_doc::GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, anicraft_doc::GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }];
|
||||
let paint = Paint::linear(Vec2::new(100.0, 100.0), Vec2::new(300.0, 100.0), stops);
|
||||
s.style.fill_paint = Some(paint.clone());
|
||||
s.style.lock_fill = true;
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "stroke": null}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let r = run(&mut s, "draw.erase", json!({"points": stroke(200.0, 60.0, 200.0, 240.0), "size": 20}));
|
||||
assert_eq!(r["erased"], true);
|
||||
let pieces = shapes(&s);
|
||||
assert_eq!(pieces.len(), 2, "cut in two");
|
||||
for (sh, m) in &pieces {
|
||||
let f = sh.fill.as_ref().map(|f| f.transformed(m)).expect("filled");
|
||||
assert!(crate::merge::same_paint(&f, &paint), "the gradient stays in the same place on the stage: {f:?}");
|
||||
}
|
||||
assert!(near(measure(&s).0, 18_000.0, 40.0));
|
||||
// The renderer agrees: left red, right blue, the band empty.
|
||||
let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
let (l, r) = (img.pixel(110, 150).unwrap(), img.pixel(290, 150).unwrap());
|
||||
assert!(l[0] > 0.85 && l[2] < 0.15 && r[2] > 0.85 && r[0] < 0.15, "{l:?} {r:?}");
|
||||
}
|
||||
|
||||
/// The raw strokes on the active layer with their profiles, as (start x, end x, profile).
|
||||
fn profiled(s: &Session) -> Vec<(f32, f32, Option<anicraft_doc::WidthProfile>)> {
|
||||
shapes(s)
|
||||
.into_iter()
|
||||
.filter_map(|(sh, m)| {
|
||||
let st = sh.stroke.as_ref()?;
|
||||
let ends: Vec<Vec2> = sh.path.anchors().iter().map(|p| m.apply(p.1)).collect();
|
||||
Some((ends.first()?.x, ends.last()?.x, st.profile.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_variable_width_stroke_split_by_the_eraser_keeps_its_profile_per_piece() {
|
||||
let mut s = blank(false);
|
||||
s.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth);
|
||||
let source = anicraft_doc::ProfilePreset::TaperBoth.profile().unwrap();
|
||||
run(&mut s, "draw.line", json!({"x0": 100, "y0": 100, "x1": 300, "y1": 100, "stroke": BLACK, "stroke_width": 12}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
assert_eq!(profiled(&s).len(), 1, "a variable-width line is raw (ADR 0093)");
|
||||
let r = run(&mut s, "draw.erase", json!({"points": stroke(150.0, 60.0, 150.0, 140.0), "size": 20}));
|
||||
assert_eq!(r["erased"], true);
|
||||
let pieces = profiled(&s);
|
||||
assert_eq!(pieces.len(), 2, "{pieces:?}");
|
||||
for (x0, x1, prof) in &pieces {
|
||||
let prof = prof.as_ref().expect("each piece keeps a profile");
|
||||
// Every place on the piece has the width it had on the line.
|
||||
for k in 0..=10 {
|
||||
let u = k as f32 / 10.0;
|
||||
let x = x0 + (x1 - x0) * u;
|
||||
let want = source.at((x - 100.0) / 200.0);
|
||||
let got = prof.at(u);
|
||||
assert!((got.0 - want.0).abs() < 0.06 && (got.1 - want.1).abs() < 0.06, "at x {x}: {got:?} vs {want:?} ({x0}..{x1})");
|
||||
}
|
||||
}
|
||||
// The left piece starts at a point and ends wide; erasing nothing changes nothing.
|
||||
let doc = s.doc.clone();
|
||||
let r = run(&mut s, "draw.erase", json!({"points": stroke(150.0, 300.0, 150.0, 340.0), "size": 20}));
|
||||
assert_eq!(r["erased"], false);
|
||||
assert_eq!(s.doc, doc);
|
||||
// A line across a variable-width line cuts it too, the profile following each piece.
|
||||
let mut t = blank(false);
|
||||
t.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth);
|
||||
run(&mut t, "draw.line", json!({"x0": 100, "y0": 100, "x1": 300, "y1": 100, "stroke": BLACK, "stroke_width": 12}));
|
||||
t.style.set_profile(anicraft_doc::ProfilePreset::Uniform);
|
||||
run(&mut t, "draw.line", json!({"x0": 200, "y0": 0, "x1": 200, "y1": 200, "stroke": RED, "stroke_width": 2}));
|
||||
let cut: Vec<_> = profiled(&t).into_iter().filter(|p| p.2.is_some()).collect();
|
||||
assert_eq!(cut.len(), 2, "{cut:?}");
|
||||
// Merging the pieces again (a drop) keeps them as they are.
|
||||
let before = profiled(&t);
|
||||
let ids: Vec<u64> = t.visible_elements().iter().map(|e| e.id.0).collect();
|
||||
t.select_only(ids.iter().map(|i| anicraft_doc::ElementId(*i)));
|
||||
run(&mut t, "draw.drop", json!({}));
|
||||
let after = profiled(&t);
|
||||
assert_eq!(after.len(), before.len());
|
||||
for (a, b) in after.iter().filter(|p| p.2.is_some()).zip(before.iter().filter(|p| p.2.is_some())) {
|
||||
let (pa, pb) = (a.2.as_ref().unwrap(), b.2.as_ref().unwrap());
|
||||
for k in 0..=10 {
|
||||
let u = k as f32 / 10.0;
|
||||
assert!((pa.at(u).0 - pb.at(u).0).abs() < 1e-3, "remerged profile drifted");
|
||||
}
|
||||
}
|
||||
// And the file keeps them.
|
||||
let json = crate::format::to_json(&s.doc).unwrap();
|
||||
assert_eq!(crate::format::from_json(&json).unwrap(), s.doc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_eraser_works_inside_an_open_symbol_and_says_how_on_the_stage() {
|
||||
let mut s = blank(false);
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": BLUE, "stroke": null}));
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "modify.convert_to_symbol", json!({"name": "Card"}));
|
||||
let inst = s.selection.id_list().first().copied().expect("the instance is selected");
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
// On the stage, the symbol is kept, and the reason says how to erase inside it.
|
||||
let (doc, steps) = (s.doc.clone(), s.history_len());
|
||||
let r = run(&mut s, "draw.erase", json!({"points": stroke(200.0, 60.0, 200.0, 240.0), "size": 20}));
|
||||
assert_eq!(r["erased"], false);
|
||||
assert_eq!(r["kept"]["symbols"], 1);
|
||||
assert!(r["reason"].as_str().unwrap().contains("double-click"), "{r}");
|
||||
assert_eq!((s.doc.clone(), s.history_len()), (doc, steps), "no change, no undo step");
|
||||
// Opened in place, its raw shapes erase, in the symbol's own space.
|
||||
run(&mut s, "symbol.edit", json!({"id": inst}));
|
||||
let to_symbol = s.editing.last().map(|l| l.transform).and_then(|m| m.inverse()).unwrap();
|
||||
let pts: Vec<[f32; 2]> = stroke(200.0, 60.0, 200.0, 240.0).into_iter().map(|[x, y]| to_symbol.apply(Vec2::new(x, y))).map(|p| [p.x, p.y]).collect();
|
||||
let r = run(&mut s, "draw.erase", json!({"points": pts, "size": 20}));
|
||||
assert_eq!(r["erased"], true, "{r}");
|
||||
run(&mut s, "symbol.exit", json!({"all": true}));
|
||||
// The instance on the stage shows the cut (the renderer, the oracle).
|
||||
let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
let bg = s.doc.stage.background;
|
||||
let (gap, kept) = (img.pixel(200, 150).unwrap(), img.pixel(150, 150).unwrap());
|
||||
assert!((gap[2] - bg.b).abs() < 0.02 && (gap[0] - bg.r).abs() < 0.02, "{gap:?}");
|
||||
assert!(kept[2] > 0.9, "{kept:?}");
|
||||
// One undo step puts the symbol back whole.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
assert!(img.pixel(200, 150).unwrap()[2] > 0.9);
|
||||
}
|
||||
+24
-12
@@ -19,22 +19,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// A raw shape the merge can take: any fill (solid, gradient or bitmap: the paint is carried
|
||||
/// into each piece, ADR 0042) or none, and a stroke of one width or none. A width profile runs
|
||||
/// along the whole stroke, so cutting it would need its length carried through the merge; those
|
||||
/// strokes stay whole, as objects, for now.
|
||||
/// into each piece, ADR 0042) or none, and any stroke or none. A stroke's width profile is
|
||||
/// carried into each piece of it (ADR 0093): the merge says which stretch of the stroke each
|
||||
/// piece runs along, and the piece keeps the widths it had there.
|
||||
pub(crate) fn mergeable(e: &Element) -> Option<&Shape> {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(s) if s.merge && s.stroke.as_ref().is_none_or(|st| st.profile.is_none()) => Some(s),
|
||||
ElementKind::Shape(s) if s.merge => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a new shape with this style can join the drawing (strokes with a width profile are
|
||||
/// drawn as objects for now).
|
||||
pub(crate) fn can_merge(stroke: Option<&Stroke>) -> bool {
|
||||
stroke.is_none_or(|st| st.profile.is_none())
|
||||
}
|
||||
|
||||
pub(crate) fn reach(s: &Shape, m: &Affine) -> Rect {
|
||||
let pad = s.stroke.as_ref().map_or(0.0, Stroke::reach) * m.mean_scale();
|
||||
s.path.bounds().transformed(m).inflate(pad + 2.0 * SNAP)
|
||||
@@ -140,6 +134,9 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt
|
||||
// Style tables: equal entries are one style to the merge.
|
||||
let mut fills: Vec<(Paint, ColorEffect)> = Vec::new();
|
||||
let mut strokes: Vec<(Stroke, ColorEffect)> = Vec::new();
|
||||
// A stroke with a width profile is a style of its own (its pieces never chain into another
|
||||
// stroke's), with the path its profile runs along (an index into `paths`).
|
||||
let mut profiled: Vec<(u32, usize)> = Vec::new();
|
||||
let mut paths: Vec<Path> = Vec::with_capacity(parts.len());
|
||||
let mut styles: Vec<(Option<u32>, Option<u32>, anicraft_geom::FillRule)> = Vec::with_capacity(parts.len());
|
||||
let mut marked: Vec<bool> = Vec::with_capacity(parts.len());
|
||||
@@ -151,7 +148,17 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt
|
||||
// Gradients and bitmaps are placed in keyframe space, so every piece shows its
|
||||
// part of the paint where it was.
|
||||
let fill = sh.fill.as_ref().map(|f| fill_index(&mut fills, (f.transformed(&e.transform), e.color)));
|
||||
let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (st.scaled(e.transform.mean_scale()), e.color)));
|
||||
let stroke = sh.stroke.clone().map(|st| {
|
||||
let st = (st.scaled(e.transform.mean_scale()), e.color);
|
||||
if st.0.profile.is_some() {
|
||||
strokes.push(st);
|
||||
let i = (strokes.len() - 1) as u32;
|
||||
profiled.push((i, paths.len() - 1));
|
||||
i
|
||||
} else {
|
||||
index_of(&mut strokes, st)
|
||||
}
|
||||
});
|
||||
styles.push((fill, stroke, sh.fill_rule));
|
||||
marked.push(*mark);
|
||||
}
|
||||
@@ -178,7 +185,12 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt
|
||||
(Some(f.clone()), None, *c)
|
||||
} else {
|
||||
let Some((st, c)) = strokes.get(piece.style as usize) else { continue };
|
||||
(None, Some(st.clone()), *c)
|
||||
let mut st = st.clone();
|
||||
// Each piece of a variable-width stroke keeps the widths it had (ADR 0093).
|
||||
if let (Some(profile), Some(path)) = (&st.profile, profiled.iter().find(|(i, _)| *i == piece.style).and_then(|(_, p)| paths.get(*p))) {
|
||||
st.profile = profile.along(path, &piece.spans);
|
||||
}
|
||||
(None, Some(st), *c)
|
||||
};
|
||||
// Local origin at the centre of the piece, as the drawing tools place shapes.
|
||||
let c = piece.path.bounds().center();
|
||||
|
||||
@@ -322,11 +322,11 @@ fn gradient_fills_take_part_in_the_merge() {
|
||||
run(&mut s, "draw.rect", json!({"x": 50, "y": 25, "w": 50, "h": 50, "fill": "#00ff00", "stroke": null}));
|
||||
let g = fills(&s).into_iter().find(|e| fill_color(e).is_none()).unwrap();
|
||||
assert!((area(&g) - (20_000.0 - 2_500.0)).abs() < 1.0);
|
||||
// A width profile still makes an object.
|
||||
// A width profile is raw too (ADR 0093: the merge carries it into each piece).
|
||||
let mut t = raw_session();
|
||||
t.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth);
|
||||
run(&mut t, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0}));
|
||||
assert!(raw(&t).is_empty());
|
||||
assert_eq!(raw(&t).len(), 1);
|
||||
let _ = Affine::IDENTITY;
|
||||
}
|
||||
|
||||
|
||||
+362
-54
@@ -21,6 +21,13 @@
|
||||
//!
|
||||
//! The result is closed loops (outer boundaries and holes) filled with the even-odd rule. The
|
||||
//! grid has at most `MAX_CELLS` cells, so cost and memory are bounded for any input.
|
||||
//!
|
||||
//! **Tilt** (ADR 0093) turns the tip with the pen's azimuth and widens it as the pen leans.
|
||||
//! When the tip turns along a stroke there is no one tip space, so the field is sampled in stage
|
||||
//! space (in tip radii) instead, and each short piece of the stroke measures its distance in its
|
||||
//! own tip space. **Texture** opens a paper grain of holes in the paint, and **scatter** throws
|
||||
//! the dabs either side of the line: both are fixed patterns, so the same stroke always gives
|
||||
//! the same outline, and both are still vector outlines.
|
||||
|
||||
use crate::{Affine, Path, PathCmd, Vec2, fit_curve, trace};
|
||||
|
||||
@@ -64,11 +71,66 @@ impl Tip {
|
||||
}
|
||||
}
|
||||
|
||||
/// One pointer sample: where, and the pen pressure (0..1; a mouse gives 1).
|
||||
/// One pointer sample: where, the pen pressure (0..1; a mouse gives 1) and the pen's tilt
|
||||
/// where the system reports it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Sample {
|
||||
pub at: Vec2,
|
||||
pub pressure: f32,
|
||||
pub tilt: Option<Tilt>,
|
||||
}
|
||||
|
||||
impl Sample {
|
||||
/// A sample with no tilt.
|
||||
pub fn new(at: Vec2, pressure: f32) -> Sample {
|
||||
Sample { at, pressure, tilt: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// A pen's tilt, as the W3C Pointer Events spec gives it (in degrees): `altitude` from 90
|
||||
/// (upright) to 0 (lying on the tablet), and `azimuth`, the direction the pen leans toward on
|
||||
/// the stage, clockwise from the +x axis.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Tilt {
|
||||
pub altitude: f32,
|
||||
pub azimuth: f32,
|
||||
}
|
||||
|
||||
impl Tilt {
|
||||
/// How far the pen leans: 0 upright, 1 flat (`1 − altitude / 90°`).
|
||||
pub fn lean(self) -> f32 {
|
||||
let a = if self.altitude.is_finite() { self.altitude.clamp(0.0, 90.0) } else { 90.0 };
|
||||
1.0 - a / 90.0
|
||||
}
|
||||
/// The lean as a vector toward the azimuth (length [`Tilt::lean`]), which blends smoothly
|
||||
/// between samples and through upright.
|
||||
fn vector(self) -> Vec2 {
|
||||
let az = if self.azimuth.is_finite() { self.azimuth.rem_euclid(360.0).to_radians() } else { 0.0 };
|
||||
Vec2::new(az.cos(), az.sin()) * self.lean()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pen's tilt shapes (Animate's tilt option).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TiltResponse {
|
||||
/// The tip turns with the pen: its angle is the brush's angle plus the azimuth.
|
||||
pub angle: bool,
|
||||
/// The tip widens as the pen leans: by `1 + TILT_WIDTH × lean`.
|
||||
pub width: bool,
|
||||
}
|
||||
|
||||
/// How much wider a flat pen paints than an upright one, as a part of the size.
|
||||
pub const TILT_WIDTH: f32 = 1.0;
|
||||
/// Below this lean the azimuth is too noisy to turn the tip by.
|
||||
const MIN_LEAN: f32 = 0.02;
|
||||
|
||||
/// The tip's angle (degrees) and size factor when the pen leans by `lean` (a vector toward the
|
||||
/// azimuth, length 0..1), for a brush at `angle` (ADR 0093). Analytic: the angle is `angle +
|
||||
/// azimuth`, and the size factor `1 + TILT_WIDTH × |lean|`.
|
||||
pub fn tilted(angle: f32, lean: Vec2, response: TiltResponse) -> (f32, f32) {
|
||||
let l = if lean.is_finite() { lean.length().min(1.0) } else { 0.0 };
|
||||
let turned = if response.angle && l >= MIN_LEAN { angle + lean.y.atan2(lean.x).to_degrees() } else { angle };
|
||||
(turned, if response.width { 1.0 + TILT_WIDTH * l } else { 1.0 })
|
||||
}
|
||||
|
||||
/// The tip's size factor at `pressure`: from `MIN_PRESSURE_SIZE` at none to 1 at full.
|
||||
@@ -91,19 +153,42 @@ pub struct Shaping {
|
||||
/// How far the edge is worn away, as a part of the tip's size (`0..=0.5`): a chalk-like
|
||||
/// ragged edge from a fixed noise pattern, so it is the same every time.
|
||||
pub jitter: f32,
|
||||
/// A paper grain of holes through the paint (`0..=1`: none to most of it), fixed on the
|
||||
/// stage and scaled to the tip's size, as dry media on rough paper (ADR 0093).
|
||||
pub texture: f32,
|
||||
/// Dabs thrown either side of the line, up to this many sizes away (`0..=2`), and varied in
|
||||
/// size: spatter and stipple. A continuous stroke scatters as dabs a quarter size apart.
|
||||
pub scatter: f32,
|
||||
/// What the pen's tilt shapes.
|
||||
pub tilt: TiltResponse,
|
||||
}
|
||||
|
||||
/// Most dabs one stroke stamps (the spacing widens past it).
|
||||
pub const MAX_DABS: usize = 20_000;
|
||||
/// Thinnest a taper makes the tip, as a part of its size.
|
||||
const TAPER_TIP: f32 = 0.05;
|
||||
/// Dab spacing of a scattered stroke that has none of its own, as a part of the size.
|
||||
const SCATTER_SPACING: f32 = 0.25;
|
||||
|
||||
impl Shaping {
|
||||
/// The values clamped to their ranges (not a number reads as none).
|
||||
pub fn sanitized(self) -> Shaping {
|
||||
let c = |v: f32, hi: f32| if v.is_finite() { v.clamp(0.0, hi) } else { 0.0 };
|
||||
let spacing = c(self.spacing, 10.0);
|
||||
Shaping { taper_start: c(self.taper_start, 0.5), taper_end: c(self.taper_end, 0.5), spacing: if spacing > 0.0 { spacing.max(0.05) } else { 0.0 }, jitter: c(self.jitter, 0.5) }
|
||||
Shaping {
|
||||
taper_start: c(self.taper_start, 0.5),
|
||||
taper_end: c(self.taper_end, 0.5),
|
||||
spacing: if spacing > 0.0 { spacing.max(0.05) } else { 0.0 },
|
||||
jitter: c(self.jitter, 0.5),
|
||||
texture: c(self.texture, 1.0),
|
||||
scatter: c(self.scatter, 2.0),
|
||||
tilt: self.tilt,
|
||||
}
|
||||
}
|
||||
|
||||
/// The dab spacing a stroke stamps at (scatter needs dabs).
|
||||
fn dab_spacing(&self) -> f32 {
|
||||
if self.spacing <= 0.0 && self.scatter > 0.0 { SCATTER_SPACING } else { self.spacing }
|
||||
}
|
||||
|
||||
/// The tapers' factor at fraction `u` of the stroke's length.
|
||||
@@ -130,25 +215,51 @@ pub fn centreline(samples: &[Sample], smoothing: f32, flatness: f32) -> Vec<(Vec
|
||||
centreline_shaped(samples, smoothing, flatness, &Shaping::default())
|
||||
}
|
||||
|
||||
/// The centre line with the shaping's tapers applied to the size factors.
|
||||
/// The centre line with the shaping's tapers applied to the size factors (and the tilt's
|
||||
/// widening, when the shaping says tilt shapes the width).
|
||||
pub fn centreline_shaped(samples: &[Sample], smoothing: f32, flatness: f32, shaping: &Shaping) -> Vec<(Vec2, f32)> {
|
||||
centre_points(samples, smoothing, flatness, shaping).into_iter().map(|p| (p.at, p.f)).collect()
|
||||
}
|
||||
|
||||
/// A point of the centre line: where, the tip's size factor, and the pen's lean there (a vector
|
||||
/// toward the azimuth, zero without tilt).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Pt {
|
||||
at: Vec2,
|
||||
f: f32,
|
||||
lean: Vec2,
|
||||
}
|
||||
|
||||
impl Pt {
|
||||
fn lerp(self, o: Pt, t: f32) -> Pt {
|
||||
Pt { at: self.at.lerp(o.at, t), f: self.f + (o.f - self.f) * t, lean: self.lean.lerp(o.lean, t) }
|
||||
}
|
||||
}
|
||||
|
||||
fn centre_points(samples: &[Sample], smoothing: f32, flatness: f32, shaping: &Shaping) -> Vec<Pt> {
|
||||
let shaping = shaping.sanitized();
|
||||
let mut pts: Vec<Vec2> = Vec::with_capacity(samples.len().min(MAX_SAMPLES));
|
||||
let mut press: Vec<f32> = Vec::with_capacity(pts.capacity());
|
||||
let mut leans: Vec<Vec2> = Vec::with_capacity(pts.capacity());
|
||||
let lean_of = |s: &Sample| s.tilt.map_or(Vec2::ZERO, Tilt::vector);
|
||||
for s in samples.iter().take(MAX_SAMPLES).filter(|s| s.at.is_finite()) {
|
||||
if pts.last().is_some_and(|l| l.distance(s.at) <= 1e-4) {
|
||||
// A held pointer: keep the latest pressure.
|
||||
if let Some(p) = press.last_mut() {
|
||||
// A held pointer: keep the latest pressure and tilt.
|
||||
if let (Some(p), Some(l)) = (press.last_mut(), leans.last_mut()) {
|
||||
*p = size_factor(s.pressure);
|
||||
*l = lean_of(s);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
pts.push(s.at);
|
||||
press.push(size_factor(s.pressure));
|
||||
leans.push(lean_of(s));
|
||||
}
|
||||
match (pts.as_slice(), press.as_slice()) {
|
||||
([], _) => return Vec::new(),
|
||||
([p], [f, ..]) => return vec![(*p, *f)],
|
||||
// The tilt's widening multiplies the size factor (ADR 0093).
|
||||
let widen = |f: f32, lean: Vec2| f * tilted(0.0, lean, TiltResponse { angle: false, width: shaping.tilt.width }).1;
|
||||
match (pts.as_slice(), press.as_slice(), leans.as_slice()) {
|
||||
([], _, _) => return Vec::new(),
|
||||
([p], [f, ..], [l, ..]) => return vec![Pt { at: *p, f: widen(*f, *l), lean: *l }],
|
||||
_ => {}
|
||||
}
|
||||
let tol = if smoothing.is_finite() && smoothing > 0.01 { smoothing } else { 0.01 };
|
||||
@@ -182,8 +293,10 @@ pub fn centreline_shaped(samples: &[Sample], smoothing: f32, flatness: f32, shap
|
||||
}
|
||||
let (s0, s1) = (src.get(j).copied().unwrap_or(0.0), src.get(j + 1).copied().unwrap_or(1.0));
|
||||
let (f0, f1) = (press.get(j).copied().unwrap_or(1.0), press.get(j + 1).copied().or(press.get(j).copied()).unwrap_or(1.0));
|
||||
let (l0, l1) = (leans.get(j).copied().unwrap_or(Vec2::ZERO), leans.get(j + 1).copied().or(leans.get(j).copied()).unwrap_or(Vec2::ZERO));
|
||||
let t = if s1 - s0 > 1e-9 { ((u - s0) / (s1 - s0)).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(*p, (f0 + (f1 - f0) * t) * shaping.taper(u))
|
||||
let lean = l0.lerp(l1, t);
|
||||
Pt { at: *p, f: widen((f0 + (f1 - f0) * t) * shaping.taper(u), lean), lean }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -247,8 +360,15 @@ pub fn centre_stroke(samples: &[Sample], shaping: &Shaping, smoothing: f32, flat
|
||||
/// Dabs every `step` stage units along a centre line (the first point always), with the size
|
||||
/// factor where each falls. At most [`MAX_DABS`]: a longer line spaces them wider.
|
||||
pub fn dabs(line: &[(Vec2, f32)], step: f32) -> Vec<(Vec2, f32)> {
|
||||
let total: f32 = line.windows(2).map(|w| if let [a, b] = w { a.0.distance(b.0) } else { 0.0 }).sum();
|
||||
let mut out: Vec<(Vec2, f32)> = line.first().copied().into_iter().collect();
|
||||
let pts: Vec<Pt> = line.iter().map(|&(at, f)| Pt { at, f, lean: Vec2::ZERO }).collect();
|
||||
dab_points(&pts, step).into_iter().map(|(p, _)| (p.at, p.f)).collect()
|
||||
}
|
||||
|
||||
/// [`dabs`] over centre-line points, each with the line's direction there.
|
||||
fn dab_points(line: &[Pt], step: f32) -> Vec<(Pt, Vec2)> {
|
||||
let total: f32 = line.windows(2).map(|w| if let [a, b] = w { a.at.distance(b.at) } else { 0.0 }).sum();
|
||||
let dir0 = line.windows(2).find_map(|w| if let [a, b] = w { Some((b.at - a.at).normalized()).filter(|d| d.is_finite() && d.length() > 0.5) } else { None }).unwrap_or(Vec2::new(1.0, 0.0));
|
||||
let mut out: Vec<(Pt, Vec2)> = line.first().copied().map(|p| (p, dir0)).into_iter().collect();
|
||||
if !(step.is_finite() && step > 1e-3) {
|
||||
return out;
|
||||
}
|
||||
@@ -256,11 +376,12 @@ pub fn dabs(line: &[(Vec2, f32)], step: f32) -> Vec<(Vec2, f32)> {
|
||||
let mut next = step;
|
||||
let mut walked = 0.0;
|
||||
for w in line.windows(2) {
|
||||
let &[(a, fa), (b, fb)] = w else { continue };
|
||||
let l = a.distance(b);
|
||||
let &[a, b] = w else { continue };
|
||||
let l = a.at.distance(b.at);
|
||||
let dir = if l > 1e-9 { (b.at - a.at) * (1.0 / l) } else { dir0 };
|
||||
while next <= walked + l && out.len() < MAX_DABS {
|
||||
let t = if l > 1e-9 { (next - walked) / l } else { 0.0 };
|
||||
out.push((a.lerp(b, t), fa + (fb - fa) * t));
|
||||
out.push((a.lerp(b, t), dir));
|
||||
next += step;
|
||||
}
|
||||
walked += l;
|
||||
@@ -276,25 +397,33 @@ pub fn outline(samples: &[Sample], tip: &Tip, smoothing: f32, tolerance: f32) ->
|
||||
outline_shaped(samples, tip, &Shaping::default(), smoothing, tolerance)
|
||||
}
|
||||
|
||||
/// The outline with tapers, dabs or a ragged edge (ADR 0068).
|
||||
/// The outline with tapers, dabs, a ragged edge, texture, scatter or tilt (ADR 0068, 0093).
|
||||
pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothing: f32, tolerance: f32) -> Path {
|
||||
let shaping = shaping.sanitized();
|
||||
let tol = if tolerance.is_finite() && tolerance > 1e-3 { tolerance } else { 0.25 };
|
||||
let mut line = centreline_shaped(samples, smoothing, tol * 0.25, &shaping);
|
||||
let dabbed = shaping.spacing > 0.0 && line.len() > 1;
|
||||
let mut line = centre_points(samples, smoothing, tol * 0.25, &shaping);
|
||||
let spacing = shaping.dab_spacing();
|
||||
let dabbed = spacing > 0.0 && line.len() > 1;
|
||||
if dabbed {
|
||||
line = dabs(&line, shaping.spacing * tip.size);
|
||||
line = scattered(dab_points(&line, spacing * tip.size), shaping.scatter * tip.size);
|
||||
}
|
||||
let m = tip.to_stage();
|
||||
let Some(inv) = m.inverse().filter(|i| i.is_finite()) else { return Path::new() };
|
||||
if line.is_empty() || !(tip.size.is_finite() && tip.size > 0.0) {
|
||||
return Path::new();
|
||||
}
|
||||
// Tip space, in f64.
|
||||
let q: Vec<(P, f64)> = line.iter().map(|(p, f)| (v64(inv.apply(*p)), f64::from(*f))).collect();
|
||||
// The tip's angle at each point: the brush's, turned by the pen's azimuth (ADR 0093).
|
||||
let angles: Vec<f32> = line.iter().map(|p| tilted(tip.angle, p.lean, TiltResponse { angle: shaping.tilt.angle, width: false }).0).collect();
|
||||
let turns = angles.iter().any(|a| (a - tip.angle).abs() > 1e-3);
|
||||
let round = if tip.roundness.is_finite() { f64::from(tip.roundness.clamp(0.05, 1.0)) } else { 1.0 };
|
||||
let half = if tip.size.is_finite() { tip.size.max(0.0) * 0.5 } else { 0.0 };
|
||||
// The grid's space: the tip's own, or (when the tip turns) the stage in tip radii, where
|
||||
// each piece measures in its own tip space.
|
||||
let m = if turns { Affine::scale(half, half) } else { tip.to_stage() };
|
||||
let Some(inv) = m.inverse().filter(|i| i.is_finite()) else { return Path::new() };
|
||||
// Grid space, in f64, with each point's tip angle (radians).
|
||||
let q: Vec<(P, f64, f64)> = line.iter().zip(&angles).map(|(p, a)| (v64(inv.apply(p.at)), f64::from(p.f), f64::from(*a).to_radians())).collect();
|
||||
let (mut lo, mut hi) = ((f64::INFINITY, f64::INFINITY), (f64::NEG_INFINITY, f64::NEG_INFINITY));
|
||||
let mut fmin: f64 = 1.0;
|
||||
for (p, f) in &q {
|
||||
for (p, f, _) in &q {
|
||||
lo = (lo.0.min(p.0 - f), lo.1.min(p.1 - f));
|
||||
hi = (hi.0.max(p.0 + f), hi.1.max(p.1 + f));
|
||||
fmin = fmin.min(*f);
|
||||
@@ -308,9 +437,12 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
TipShape::Round => 1.0 / 6.0,
|
||||
TipShape::Square => 1.0 / 8.0,
|
||||
};
|
||||
// A ragged edge needs cells finer than its grain.
|
||||
// A ragged edge needs cells finer than its grain, and the paper grain finer still.
|
||||
let fine: f64 = if shaping.jitter > 0.0 { f64::min(fine, 1.0 / 14.0) } else { fine };
|
||||
let mut c: f64 = (fmin / 2.5).min(fine);
|
||||
let fine: f64 = if shaping.texture > 0.0 { f64::min(fine, 1.0 / 18.0) } else { fine };
|
||||
// In stage space the tip's narrow side is `round` radii across.
|
||||
let narrow = if turns { round } else { 1.0 };
|
||||
let mut c: f64 = (fmin / 2.5).min(fine) * narrow;
|
||||
for _ in 0..4 {
|
||||
let cells = ((hi.0 - lo.0) / c + 2.0 * MARGIN + 2.0) * ((hi.1 - lo.1) / c + 2.0 * MARGIN + 2.0);
|
||||
if cells <= MAX_CELLS as f64 {
|
||||
@@ -331,8 +463,11 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
let wear = f64::from(shaping.jitter) * 2.0 / c;
|
||||
let top = 1.0 + MARGIN + wear;
|
||||
// Nothing thinner than a cell, so no part slips between the samples.
|
||||
let pts: Vec<(P, f64)> = thin(&q, c * 0.5).into_iter().map(|(p, f)| (p, f.max(c))).collect();
|
||||
let mut stamp = |a: P, ra: f64, b: P, rb: f64| {
|
||||
let pts: Vec<(P, f64, f64)> = thin(&q, c * 0.5).into_iter().map(|(p, f, a)| (p, f.max(c / narrow), a)).collect();
|
||||
// A piece's frame when the tip turns: grid space to its tip space is a turn by −angle and
|
||||
// a stretch of the narrow side. A distance there times `round` is at most the distance in
|
||||
// the grid, with the same zero level.
|
||||
let mut stamp = |a: P, ra: f64, b: P, rb: f64, turn: Option<(f64, f64)>| {
|
||||
let reach = ra.max(rb) + (MARGIN - 1.0) * c;
|
||||
let (x0, x1) = (((a.0.min(b.0) - reach - origin.0) / c).floor().max(0.0), ((a.0.max(b.0) + reach - origin.0) / c).ceil());
|
||||
let (y0, y1) = (((a.1.min(b.1) - reach - origin.1) / c).floor().max(0.0), ((a.1.max(b.1) + reach - origin.1) / c).ceil());
|
||||
@@ -340,14 +475,21 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
if x1 < x0 || y1 < y0 {
|
||||
return;
|
||||
}
|
||||
let to_tip = |p: P| match turn {
|
||||
Some((cs, sn)) => (p.0 * cs + p.1 * sn, (-p.0 * sn + p.1 * cs) / round),
|
||||
None => p,
|
||||
};
|
||||
let scale = if turn.is_some() { round } else { 1.0 };
|
||||
let (ta, tb) = (to_tip(a), to_tip(b));
|
||||
for y in y0 as usize..=y1 as usize {
|
||||
let py = origin.1 + (y as f64 + 0.5) * c;
|
||||
for x in x0 as usize..=x1 as usize {
|
||||
let px = origin.0 + (x as f64 + 0.5) * c;
|
||||
let tx = to_tip((px, py));
|
||||
let d = match tip.shape {
|
||||
TipShape::Round => round_dist((px, py), a, ra, b, rb),
|
||||
TipShape::Square => square_dist((px, py), a, ra, b, rb),
|
||||
};
|
||||
TipShape::Round => round_dist(tx, ta, ra, tb, rb),
|
||||
TipShape::Square => square_dist(tx, ta, ra, tb, rb),
|
||||
} * scale;
|
||||
let v = (0.5 - d / c).clamp(OUTSIDE, top) as f32;
|
||||
if let Some(cell) = field.get_mut(y * w + x)
|
||||
&& v > *cell
|
||||
@@ -357,18 +499,22 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
}
|
||||
}
|
||||
};
|
||||
let turn_at = |a: f64| turns.then(|| (a.cos(), a.sin()));
|
||||
match pts.as_slice() {
|
||||
[(p, f)] => stamp(*p, *f, *p, *f),
|
||||
_ if dabbed => pts.iter().for_each(|(p, f)| stamp(*p, *f, *p, *f)),
|
||||
[(p, f, a)] => stamp(*p, *f, *p, *f, turn_at(*a)),
|
||||
_ if dabbed => pts.iter().for_each(|(p, f, a)| stamp(*p, *f, *p, *f, turn_at(*a))),
|
||||
_ => {
|
||||
for pair in pts.windows(2) {
|
||||
let &[(a, ra), (b, rb)] = pair else { continue };
|
||||
let &[(a, ra, aa), (b, rb, ab)] = pair else { continue };
|
||||
// Long segments in short pieces, so each one's bounds stay small (the pieces'
|
||||
// sweeps are the segment's).
|
||||
let n = (dist(a, b) / PIECE.max(16.0 * c)).ceil().clamp(1.0, 1e6) as usize;
|
||||
// sweeps are the segment's); a turning tip turns at most 3° a piece.
|
||||
let n = (dist(a, b) / PIECE.max(16.0 * c)).ceil().clamp(1.0, 1e6);
|
||||
let da = half_turn(ab - aa);
|
||||
let n = if turns { n.max((da.abs() / 3f64.to_radians()).ceil()).min(1e6) } else { n } as usize;
|
||||
for i in 0..n {
|
||||
let (t0, t1) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
|
||||
stamp(lerp(a, b, t0), ra + (rb - ra) * t0, lerp(a, b, t1), ra + (rb - ra) * t1);
|
||||
let mid = aa + da * (t0 + t1) * 0.5;
|
||||
stamp(lerp(a, b, t0), ra + (rb - ra) * t0, lerp(a, b, t1), ra + (rb - ra) * t1, turn_at(mid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -385,6 +531,27 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
*v -= (wear * grain((origin.0 + (x + 0.5) * c, origin.1 + (y + 0.5) * c))) as f32;
|
||||
}
|
||||
}
|
||||
if shaping.texture > 0.0 {
|
||||
// The paper grain: where a fixed noise on the stage (in tip radii, so it scales with
|
||||
// the brush) falls below the threshold, the paint has a hole. The noise's slope is about
|
||||
// one per grain, so `(n − τ) × grain` is roughly a distance, which is all the tracing's
|
||||
// interpolation needs.
|
||||
let tau = 0.2 + 0.4 * f64::from(shaping.texture);
|
||||
let unit = 1.0 / f64::from(half).max(1e-9);
|
||||
let grain_cells = PAPER / c;
|
||||
for (i, v) in field.iter_mut().enumerate() {
|
||||
if *v <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let (x, y) = ((i % w) as f64, (i / w) as f64);
|
||||
let st = m.apply(Vec2::new((origin.0 + (x + 0.5) * c) as f32, (origin.1 + (y + 0.5) * c) as f32));
|
||||
let n = paper((f64::from(st.x) * unit, f64::from(st.y) * unit));
|
||||
let hole = ((n - tau) * grain_cells) as f32;
|
||||
if hole < *v {
|
||||
*v = hole;
|
||||
}
|
||||
}
|
||||
}
|
||||
let to_stage = |p: Vec2| m.apply(Vec2::new((origin.0 + f64::from(p.x) * c) as f32, (origin.1 + f64::from(p.y) * c) as f32));
|
||||
// A corner is a turn of 60° over the window either side. Round tips: two cells (their
|
||||
// tightest curve is 2.5 cells, too gentle to count). Square tips: four, so a corner the
|
||||
@@ -396,7 +563,7 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
};
|
||||
let window = (cells * cell_stage).max(tol * 2.0);
|
||||
let mut out = Path::new();
|
||||
for lp in trace::contours(&field, w, h) {
|
||||
for lp in trace::contours(&field, w, h).into_iter().take(MAX_LOOPS) {
|
||||
let stage: Vec<Vec2> = lp.into_iter().map(to_stage).collect();
|
||||
let part = fit_curve(&stage, tol, window, true);
|
||||
if part.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) {
|
||||
@@ -406,6 +573,50 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
|
||||
out
|
||||
}
|
||||
|
||||
/// Most loops one outline keeps (a fine paper grain on a long stroke opens many holes).
|
||||
pub const MAX_LOOPS: usize = 20_000;
|
||||
/// The paper grain's size, in tip radii.
|
||||
const PAPER: f64 = 0.35;
|
||||
|
||||
/// An angle difference (radians) as the shortest turn of a tip that looks the same turned
|
||||
/// half way round: in `-π/2..=π/2`.
|
||||
fn half_turn(d: f64) -> f64 {
|
||||
let pi = std::f64::consts::PI;
|
||||
let d = d.rem_euclid(pi);
|
||||
if d > pi * 0.5 { d - pi } else { d }
|
||||
}
|
||||
|
||||
/// Dabs thrown up to `reach` either side of the line, and varied from 60 to 100 % in size, by
|
||||
/// a fixed hash of each dab's number (so the same stroke scatters the same way).
|
||||
fn scattered(dabs: Vec<(Pt, Vec2)>, reach: f32) -> Vec<Pt> {
|
||||
if !(reach.is_finite() && reach > 0.0) {
|
||||
return dabs.into_iter().map(|(p, _)| p).collect();
|
||||
}
|
||||
dabs.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, (p, dir))| {
|
||||
let (u, v) = (unit_hash(i as u64, 1), unit_hash(i as u64, 2));
|
||||
let side = Vec2::new(-dir.y, dir.x) * ((u as f32 * 2.0 - 1.0) * reach);
|
||||
Pt { at: p.at + side, f: p.f * (0.6 + 0.4 * v as f32), lean: p.lean }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A number in `0..1` from `(i, k)`, the same on every platform (SplitMix64's finaliser).
|
||||
fn unit_hash(i: u64, k: u64) -> f64 {
|
||||
let mut z = i.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ k.wrapping_mul(0xD1B5_4A32_D192_ED03);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^= z >> 31;
|
||||
(z >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
|
||||
/// The paper grain: value noise in `0..1`, two octaves ([`PAPER`] and 0.4 of it), on lattice
|
||||
/// rows of its own (apart from the ragged edge's).
|
||||
fn paper(p: P) -> f64 {
|
||||
grain_octaves(p, PAPER, PAPER * 0.4, 7)
|
||||
}
|
||||
|
||||
type P = (f64, f64);
|
||||
|
||||
/// Cells of free margin round the sweep (the field is sampled this far out).
|
||||
@@ -428,6 +639,13 @@ fn lerp(a: P, b: P, t: f64) -> P {
|
||||
/// Smooth value noise in `0..1` from a fixed integer hash: two octaves, 0.5 and 0.2 tip units
|
||||
/// across. The same point always gives the same value, on every platform.
|
||||
fn grain(p: P) -> f64 {
|
||||
grain_octaves(p, 0.5, 0.2, 0)
|
||||
}
|
||||
|
||||
/// Two octaves of value noise (`big` and `small` across, the big one weighted twice) on lattice
|
||||
/// rows from `layer`: each octave reads rows of its own (`layer` shifts them far apart), so the
|
||||
/// octaves are independent.
|
||||
fn grain_octaves(p: P, big: f64, small: f64, layer: i64) -> f64 {
|
||||
fn hash(x: i64, y: i64) -> f64 {
|
||||
// SplitMix64's finaliser over the lattice point.
|
||||
let mut z = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
|
||||
@@ -436,8 +654,6 @@ fn grain(p: P) -> f64 {
|
||||
z ^= z >> 31;
|
||||
(z >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
// Each octave reads its own lattice rows (`layer` shifts them far apart), so the two
|
||||
// octaves are independent.
|
||||
fn octave(p: P, size: f64, layer: i64) -> f64 {
|
||||
let (u, v) = (p.0 / size, p.1 / size);
|
||||
let (x0, y0) = (u.floor(), v.floor());
|
||||
@@ -448,21 +664,21 @@ fn grain(p: P) -> f64 {
|
||||
let bottom = hash(xi, yi + 1) + (hash(xi + 1, yi + 1) - hash(xi, yi + 1)) * sx;
|
||||
top + (bottom - top) * sy
|
||||
}
|
||||
(octave(p, 0.5, 0) * 2.0 + octave(p, 0.2, 1)) / 3.0
|
||||
(octave(p, big, layer) * 2.0 + octave(p, small, layer + 1)) / 3.0
|
||||
}
|
||||
|
||||
/// Drops points closer than `gap` to the last kept one (the last point always stays).
|
||||
fn thin(q: &[(P, f64)], gap: f64) -> Vec<(P, f64)> {
|
||||
let mut out: Vec<(P, f64)> = Vec::with_capacity(q.len());
|
||||
for (i, &(p, f)) in q.iter().enumerate() {
|
||||
fn thin(q: &[(P, f64, f64)], gap: f64) -> Vec<(P, f64, f64)> {
|
||||
let mut out: Vec<(P, f64, f64)> = Vec::with_capacity(q.len());
|
||||
for (i, &(p, f, a)) in q.iter().enumerate() {
|
||||
let last = i + 1 == q.len();
|
||||
match out.last_mut() {
|
||||
Some((l, lf)) if dist(*l, p) < gap => {
|
||||
Some((l, lf, la)) if dist(*l, p) < gap => {
|
||||
if last {
|
||||
(*l, *lf) = (p, f);
|
||||
(*l, *lf, *la) = (p, f, a);
|
||||
}
|
||||
}
|
||||
_ => out.push((p, f)),
|
||||
_ => out.push((p, f, a)),
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -520,7 +736,7 @@ mod tests {
|
||||
use crate::FillRule;
|
||||
|
||||
fn line(a: Vec2, b: Vec2, n: usize, pressure: impl Fn(f32) -> f32) -> Vec<Sample> {
|
||||
(0..=n).map(|i| i as f32 / n as f32).map(|t| Sample { at: a.lerp(b, t), pressure: pressure(t) }).collect()
|
||||
(0..=n).map(|i| i as f32 / n as f32).map(|t| Sample::new(a.lerp(b, t), pressure(t))).collect()
|
||||
}
|
||||
|
||||
/// Area of an even-odd path (flattened finely).
|
||||
@@ -554,12 +770,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_dab_is_the_tip() {
|
||||
let p = outline(&[Sample { at: Vec2::new(10.0, 10.0), pressure: 1.0 }], &Tip::round(8.0), 1.0, 0.05);
|
||||
let p = outline(&[Sample::new(Vec2::new(10.0, 10.0), 1.0)], &Tip::round(8.0), 1.0, 0.05);
|
||||
let want = std::f32::consts::PI * 16.0;
|
||||
assert!((area(&p) - want).abs() / want < 0.01, "{}", area(&p));
|
||||
// A square tip at 45°: a diamond of the same area as the square.
|
||||
let tip = Tip { shape: TipShape::Square, size: 10.0, angle: 45.0, roundness: 1.0 };
|
||||
let d = outline(&[Sample { at: Vec2::ZERO, pressure: 1.0 }], &tip, 1.0, 0.05);
|
||||
let d = outline(&[Sample::new(Vec2::ZERO, 1.0)], &tip, 1.0, 0.05);
|
||||
assert!((area(&d) - 100.0).abs() < 2.0, "{}", area(&d));
|
||||
assert!(d.contains(Vec2::new(0.0, 6.8), &Affine::IDENTITY, FillRule::EvenOdd), "a corner points down");
|
||||
assert!(!d.contains(Vec2::new(4.6, 4.6), &Affine::IDENTITY, FillRule::EvenOdd), "an unturned square's corner is outside");
|
||||
@@ -580,7 +796,7 @@ mod tests {
|
||||
#[test]
|
||||
fn smoothing_reduces_anchors() {
|
||||
// A shaky hand: a straight drag with jitter.
|
||||
let s: Vec<Sample> = (0..=200).map(|i| Sample { at: Vec2::new(i as f32 * 2.0, ((i * 7919) % 13) as f32 * 0.35), pressure: 1.0 }).collect();
|
||||
let s: Vec<Sample> = (0..=200).map(|i| Sample::new(Vec2::new(i as f32 * 2.0, ((i * 7919) % 13) as f32 * 0.35), 1.0)).collect();
|
||||
let rough = outline(&s, &Tip::round(12.0), 0.3, 0.3);
|
||||
let smooth = outline(&s, &Tip::round(12.0), 6.0, 0.3);
|
||||
let (a, b) = (rough.anchors().len(), smooth.anchors().len());
|
||||
@@ -590,7 +806,7 @@ mod tests {
|
||||
#[test]
|
||||
fn crossing_strokes_leave_holes_and_ellipses_follow_the_angle() {
|
||||
// A loop that closes on itself leaves a hole in the middle.
|
||||
let ring: Vec<Sample> = (0..=72).map(|i| i as f32 / 72.0 * std::f32::consts::TAU).map(|a| Sample { at: Vec2::new(100.0 * a.cos(), 100.0 * a.sin()), pressure: 1.0 }).collect();
|
||||
let ring: Vec<Sample> = (0..=72).map(|i| i as f32 / 72.0 * std::f32::consts::TAU).map(|a| Sample::new(Vec2::new(100.0 * a.cos(), 100.0 * a.sin()), 1.0)).collect();
|
||||
let p = outline(&ring, &Tip::round(10.0), 0.5, 0.2);
|
||||
let loops = p.cmds.iter().filter(|c| matches!(c, PathCmd::MoveTo(_))).count();
|
||||
assert_eq!(loops, 2, "outer edge and hole");
|
||||
@@ -687,13 +903,105 @@ mod tests {
|
||||
assert!(centre_stroke(&s[..1], &Shaping::default(), 1.0, 0.1, 16).0.is_empty(), "a dab is no line");
|
||||
}
|
||||
|
||||
/// The bounds of the curve itself (`Path::bounds` includes control points).
|
||||
trait Tight {
|
||||
fn tight(&self) -> crate::Rect;
|
||||
}
|
||||
impl Tight for Path {
|
||||
fn tight(&self) -> crate::Rect {
|
||||
let mut r = crate::Rect::EMPTY;
|
||||
for pl in self.flatten(&Affine::IDENTITY, 0.05) {
|
||||
pl.points.into_iter().for_each(|x| r.include(x));
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
fn tilted_line(n: usize, len: f32, tilt: impl Fn(f32) -> Tilt) -> Vec<Sample> {
|
||||
(0..=n).map(|i| i as f32 / n as f32).map(|t| Sample { at: Vec2::new(len * t, 0.0), pressure: 1.0, tilt: Some(tilt(t)) }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tilt_maps_to_angle_and_width_analytically() {
|
||||
let both = TiltResponse { angle: true, width: true };
|
||||
let lean = |alt: f32, az: f32| Tilt { altitude: alt, azimuth: az }.vector();
|
||||
// Upright: the brush as set.
|
||||
assert_eq!(tilted(20.0, lean(90.0, 75.0), both), (20.0, 1.0));
|
||||
// Lying flat toward 30°: turned by 30°, twice as wide.
|
||||
let (a, f) = tilted(20.0, lean(0.0, 30.0), both);
|
||||
assert!((a - 50.0).abs() < 1e-3 && (f - 2.0).abs() < 1e-5, "{a} {f}");
|
||||
// Half way down (45°): half the lean, 1.5 × as wide; azimuth 270 is −90.
|
||||
let (a, f) = tilted(0.0, lean(45.0, 270.0), both);
|
||||
assert!((a + 90.0).abs() < 1e-3 && (f - 1.5).abs() < 1e-5, "{a} {f}");
|
||||
// Each part only when asked for.
|
||||
assert_eq!(tilted(10.0, lean(0.0, 30.0), TiltResponse::default()), (10.0, 1.0));
|
||||
assert!((tilted(10.0, lean(0.0, 30.0), TiltResponse { angle: false, width: true }).1 - 2.0).abs() < 1e-5);
|
||||
// Hostile tilts read as upright.
|
||||
assert_eq!(Tilt { altitude: f32::NAN, azimuth: f32::INFINITY }.lean(), 0.0);
|
||||
assert_eq!(tilted(5.0, Vec2::new(f32::NAN, 1.0), both), (5.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tilted_flat_tip_turns_with_the_pen() {
|
||||
let flat = Tip { shape: TipShape::Round, size: 20.0, angle: 0.0, roundness: 0.2 };
|
||||
let turn = Shaping { tilt: TiltResponse { angle: true, width: false }, ..Shaping::default() };
|
||||
// Leaning toward 90° all along: the nib stands across the drag, as a 90° brush does.
|
||||
let across = outline_shaped(&tilted_line(10, 100.0, |_| Tilt { altitude: 30.0, azimuth: 90.0 }), &flat, &turn, 1.0, 0.1);
|
||||
let set = outline(&line(Vec2::ZERO, Vec2::new(100.0, 0.0), 10, |_| 1.0), &Tip { angle: 90.0, ..flat }, 1.0, 0.1);
|
||||
assert!((across.tight().height() - 20.0).abs() < 0.6, "{:?}", across.tight());
|
||||
assert!((area(&across) - area(&set)).abs() / area(&set) < 0.03, "{} vs {}", area(&across), area(&set));
|
||||
// Without the tilt option the pen's lean does nothing.
|
||||
let plain = outline_shaped(&tilted_line(10, 100.0, |_| Tilt { altitude: 30.0, azimuth: 90.0 }), &flat, &Shaping::default(), 1.0, 0.1);
|
||||
assert!((plain.tight().height() - 4.0).abs() < 0.6, "{:?}", plain.tight());
|
||||
// Turning from along the drag (thin) to across it (wide) as it goes.
|
||||
let s = tilted_line(60, 300.0, |t| Tilt { altitude: 20.0, azimuth: 90.0 * t });
|
||||
let p = outline_shaped(&s, &flat, &turn, 1.0, 0.1);
|
||||
let inside = |x: f32, y: f32| p.contains(Vec2::new(x, y), &Affine::IDENTITY, FillRule::EvenOdd);
|
||||
assert!(inside(15.0, 0.0) && !inside(15.0, 4.0), "thin at the start");
|
||||
assert!(inside(290.0, 9.0), "wide at the end");
|
||||
assert_eq!(loops(&p), 1);
|
||||
// Widening: a round 10 tip flat on the paper paints 20 wide.
|
||||
let wide = Shaping { tilt: TiltResponse { angle: false, width: true }, ..Shaping::default() };
|
||||
let w = outline_shaped(&tilted_line(10, 100.0, |_| Tilt { altitude: 0.0, azimuth: 0.0 }), &Tip::round(10.0), &wide, 1.0, 0.1);
|
||||
assert!((w.tight().height() - 20.0).abs() < 0.5, "{:?}", w.tight());
|
||||
assert_eq!(w, outline_shaped(&tilted_line(10, 100.0, |_| Tilt { altitude: 0.0, azimuth: 0.0 }), &Tip::round(10.0), &wide, 1.0, 0.1), "deterministic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_opens_a_fixed_paper_grain_and_scatter_throws_dabs() {
|
||||
let s = line(Vec2::ZERO, Vec2::new(300.0, 30.0), 60, |_| 1.0);
|
||||
let tip = Tip::round(30.0);
|
||||
let plain = outline(&s, &tip, 1.0, 0.2);
|
||||
let sh = Shaping { texture: 0.5, ..Shaping::default() };
|
||||
let p = outline_shaped(&s, &tip, &sh, 1.0, 0.2);
|
||||
let (a, b) = (area(&p), area(&plain));
|
||||
assert!(a < b * 0.9 && a > b * 0.25, "grain takes some of the paint: {a} vs {b}");
|
||||
assert!(loops(&p) > 10, "holes through the paint: {}", loops(&p));
|
||||
assert!(p.tight().width() <= plain.tight().width() + 0.5 && p.tight().height() <= plain.tight().height() + 0.5);
|
||||
assert_eq!(p, outline_shaped(&s, &tip, &sh, 1.0, 0.2), "deterministic");
|
||||
// More texture, less paint.
|
||||
let more = area(&outline_shaped(&s, &tip, &Shaping { texture: 1.0, ..Shaping::default() }, 1.0, 0.2));
|
||||
assert!(more < a, "{more} vs {a}");
|
||||
// Scatter: dabs either side of the line, past the plain stroke's edge.
|
||||
let flat = line(Vec2::ZERO, Vec2::new(300.0, 0.0), 60, |_| 1.0);
|
||||
let sc = Shaping { scatter: 1.5, spacing: 0.8, ..Shaping::default() };
|
||||
let q = outline_shaped(&flat, &Tip::round(10.0), &sc, 1.0, 0.2);
|
||||
assert!(q.tight().height() > 20.0, "{:?}", q.tight());
|
||||
assert!(q.tight().height() < 10.0 + 2.0 * 15.0 + 1.0, "within the scatter's reach: {:?}", q.tight());
|
||||
assert!(loops(&q) > 5);
|
||||
assert_eq!(q, outline_shaped(&flat, &Tip::round(10.0), &sc, 1.0, 0.2), "deterministic");
|
||||
// Scatter on a continuous brush stamps dabs a quarter size apart.
|
||||
let cont = outline_shaped(&flat, &Tip::round(10.0), &Shaping { scatter: 1.0, ..Shaping::default() }, 1.0, 0.2);
|
||||
assert!(cont.tight().height() > 12.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_is_empty_or_bounded() {
|
||||
let wild = Shaping { taper_start: f32::NAN, taper_end: 1e9, spacing: -3.0, jitter: f32::INFINITY };
|
||||
assert_eq!(wild.sanitized(), Shaping { taper_start: 0.0, taper_end: 0.5, spacing: 0.0, jitter: 0.0 });
|
||||
let wild = Shaping { taper_start: f32::NAN, taper_end: 1e9, spacing: -3.0, jitter: f32::INFINITY, texture: f32::NAN, scatter: 1e9, tilt: TiltResponse::default() };
|
||||
assert_eq!(wild.sanitized(), Shaping { taper_start: 0.0, taper_end: 0.5, spacing: 0.0, jitter: 0.0, texture: 0.0, scatter: 2.0, tilt: TiltResponse::default() });
|
||||
let _ = outline_shaped(&line(Vec2::ZERO, Vec2::new(10.0, 0.0), 3, |_| 1.0), &Tip::round(5.0), &Shaping { spacing: 1e-9, jitter: 0.5, ..wild }, 1.0, 1.0);
|
||||
assert!(outline(&[], &Tip::round(10.0), 1.0, 1.0).is_empty());
|
||||
let nan = [Sample { at: Vec2::new(f32::NAN, 0.0), pressure: f32::NAN }];
|
||||
let nan = [Sample::new(Vec2::new(f32::NAN, 0.0), f32::NAN)];
|
||||
assert!(outline(&nan, &Tip::round(10.0), 1.0, 1.0).is_empty());
|
||||
assert!(outline(&line(Vec2::ZERO, Vec2::new(10.0, 0.0), 3, |_| 1.0), &Tip::round(0.0), 1.0, 1.0).is_empty());
|
||||
assert!(outline(&line(Vec2::ZERO, Vec2::new(10.0, 0.0), 3, |_| 1.0), &Tip::round(f32::INFINITY), 1.0, 1.0).is_empty());
|
||||
|
||||
@@ -256,8 +256,11 @@ fn generate(pts: &[P], u: &[f64], t1: P, t2: P) -> [P; 4] {
|
||||
let det1 = x[0] * c[1][1] - x[1] * c[0][1];
|
||||
let (mut al, mut ar) = if det.abs() > 1e-12 { (det1 / det, det0 / det) } else { (0.0, 0.0) };
|
||||
let seg = len(sub(p3, p0));
|
||||
// A handle longer than the points' own length is a bad solve (a nearly closed stretch can
|
||||
// send it far off): fall back, and the error check splits the stretch instead (ADR 0093).
|
||||
let arc: f64 = pts.windows(2).map(|w| len(sub(w[1], w[0]))).sum();
|
||||
// Schneider's fallback when the solve is degenerate or flips a handle.
|
||||
if al < 1e-6 * seg || ar < 1e-6 * seg {
|
||||
if al < 1e-6 * seg || ar < 1e-6 * seg || al > arc || ar > arc {
|
||||
al = seg / 3.0;
|
||||
ar = seg / 3.0;
|
||||
}
|
||||
|
||||
+74
-17
@@ -55,6 +55,19 @@ pub struct Piece {
|
||||
pub item: usize,
|
||||
/// Inside the cutter ([`merge_cut`]); always false from [`merge`].
|
||||
pub inside: bool,
|
||||
/// For a stroke piece: the stretches of its items' paths it runs along, in order, each as
|
||||
/// `[from, to]` in path positions (see [`Piece::position`]); `to < from` where it runs
|
||||
/// backwards. What a width profile needs to follow its stroke into each piece (ADR 0093).
|
||||
/// Empty for fills.
|
||||
pub spans: Vec<[f64; 2]>,
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
/// A place on an item's path as a path position: `k + t` is parameter `t` along the segment
|
||||
/// that command `k` draws (a `Close` draws the closing line).
|
||||
pub fn position(cmd: usize, t: f64) -> f64 {
|
||||
cmd as f64 + t.clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -296,6 +309,15 @@ struct Seg {
|
||||
line: bool,
|
||||
item: usize,
|
||||
stroke: bool,
|
||||
/// Its ends as path positions on its item ([`Piece::position`]).
|
||||
pos: [f64; 2],
|
||||
}
|
||||
|
||||
impl Seg {
|
||||
/// Path position of parameter `t`.
|
||||
fn at(&self, t: f64) -> f64 {
|
||||
self.pos[0] + (self.pos[1] - self.pos[0]) * t
|
||||
}
|
||||
}
|
||||
|
||||
/// Every segment of every item. A filled subpath left open gets its closing edge (unstroked).
|
||||
@@ -306,31 +328,32 @@ fn collect(items: &[Item]) -> Option<Vec<Seg>> {
|
||||
continue;
|
||||
}
|
||||
let stroke = it.stroke.is_some();
|
||||
let mut push = |c: Cubic, line: bool, stroke: bool| {
|
||||
let mut push = |c: Cubic, line: bool, stroke: bool, k: usize| {
|
||||
if !c.iter().all(|p| p.finite()) || hull_len(&c) <= 1e-9 {
|
||||
return;
|
||||
}
|
||||
let k = k as f64;
|
||||
// A segment that comes back to where it began (a loop) is two, so no edge is a loop.
|
||||
if c[0].dist(c[3]) < TOL && hull_len(&c) > 2.0 * TOL {
|
||||
let (a, b) = split(&c, 0.5);
|
||||
segs.push(Seg { c: a, line, item, stroke });
|
||||
segs.push(Seg { c: b, line, item, stroke });
|
||||
segs.push(Seg { c: a, line, item, stroke, pos: [k, k + 0.5] });
|
||||
segs.push(Seg { c: b, line, item, stroke, pos: [k + 0.5, k + 1.0] });
|
||||
} else {
|
||||
segs.push(Seg { c, line, item, stroke });
|
||||
segs.push(Seg { c, line, item, stroke, pos: [k, k + 1.0] });
|
||||
}
|
||||
};
|
||||
let (mut start, mut last) = (P::default(), P::default());
|
||||
let (mut open, mut drawn) = (false, false);
|
||||
let close = |push: &mut dyn FnMut(Cubic, bool, bool), last: P, start: P, stroked: bool| {
|
||||
let close = |push: &mut dyn FnMut(Cubic, bool, bool, usize), last: P, start: P, stroked: bool, k: usize| {
|
||||
if last.dist(start) > 0.0 {
|
||||
push(line_cubic(last, start), true, stroked);
|
||||
push(line_cubic(last, start), true, stroked, k);
|
||||
}
|
||||
};
|
||||
for cmd in &it.path.cmds {
|
||||
for (k, cmd) in it.path.cmds.iter().enumerate() {
|
||||
let to = match *cmd {
|
||||
PathCmd::MoveTo(p) => {
|
||||
if open && drawn && it.fill.is_some() {
|
||||
close(&mut push, last, start, false);
|
||||
close(&mut push, last, start, false, k);
|
||||
}
|
||||
start = P::of(p);
|
||||
last = start;
|
||||
@@ -339,7 +362,7 @@ fn collect(items: &[Item]) -> Option<Vec<Seg>> {
|
||||
}
|
||||
PathCmd::Close => {
|
||||
if open {
|
||||
close(&mut push, last, start, stroke);
|
||||
close(&mut push, last, start, stroke, k);
|
||||
}
|
||||
last = start;
|
||||
(open, drawn) = (false, false);
|
||||
@@ -352,12 +375,12 @@ fn collect(items: &[Item]) -> Option<Vec<Seg>> {
|
||||
}
|
||||
PathCmd::CubicTo(a, b, p) => ([last, P::of(a), P::of(b), P::of(p)], false),
|
||||
};
|
||||
push(to.0, to.1, stroke);
|
||||
push(to.0, to.1, stroke, k);
|
||||
last = to.0[3];
|
||||
(open, drawn) = (true, true);
|
||||
}
|
||||
if open && drawn && it.fill.is_some() {
|
||||
close(&mut push, last, start, false);
|
||||
close(&mut push, last, start, false, it.path.cmds.len());
|
||||
}
|
||||
if segs.len() > MAX_SEGMENTS {
|
||||
return None;
|
||||
@@ -820,7 +843,7 @@ impl Map {
|
||||
None => {
|
||||
let (style, item, inside) = top.get(&g).copied().unwrap_or((0, 0, false));
|
||||
piece_of.insert(g, out.fills.len());
|
||||
out.fills.push(Piece { style, path, item, inside });
|
||||
out.fills.push(Piece { style, path, item, inside, spans: Vec::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -877,17 +900,24 @@ impl Map {
|
||||
let item = halves.iter().filter_map(|&h| stroke_of[h / 2]).max().unwrap_or(0);
|
||||
// A run along the cutter's edge counts as inside it.
|
||||
let inside = halves.iter().any(|&h| cut_edge[h / 2]) || halves.get(halves.len() / 2).is_some_and(|&h| cutter.covers(eval(&self.curve(h), 0.5), FillRule::EvenOdd));
|
||||
out.strokes.push(Piece { style: st, path: self.emit(&halves, closed, segs), item, inside });
|
||||
let (path, spans) = self.emit_spans(&halves, closed, segs);
|
||||
out.strokes.push(Piece { style: st, path, item, inside, spans });
|
||||
}
|
||||
}
|
||||
|
||||
/// A subpath along `halves`: pieces of one segment joined back, straight runs made one line.
|
||||
fn emit(&self, halves: &[Half], closed: bool, segs: &[Seg]) -> Path {
|
||||
self.emit_spans(halves, closed, segs).0
|
||||
}
|
||||
|
||||
/// [`Map::emit`], with the stretches of the items' paths the subpath runs along.
|
||||
fn emit_spans(&self, halves: &[Half], closed: bool, segs: &[Seg]) -> (Path, Vec<[f64; 2]>) {
|
||||
let mut runs: Vec<Run> = Vec::new();
|
||||
for &h in halves {
|
||||
let e = &self.edges[h / 2];
|
||||
let (t0, t1) = if h.is_multiple_of(2) { (e.t[0], e.t[1]) } else { (e.t[1], e.t[0]) };
|
||||
let run = Run { c: self.curve(h), line: e.line, src: e.src, t: [t0, t1] };
|
||||
let spans = segs.get(e.src).map(|s| vec![[s.at(t0), s.at(t1)]]).unwrap_or_default();
|
||||
let run = Run { c: self.curve(h), line: e.line, src: e.src, t: [t0, t1], spans };
|
||||
match runs.last_mut().and_then(|last| last.join(&run, segs)) {
|
||||
Some(j) => {
|
||||
if let Some(last) = runs.last_mut() {
|
||||
@@ -918,10 +948,35 @@ impl Map {
|
||||
if closed && !runs.is_empty() {
|
||||
path.close();
|
||||
}
|
||||
path
|
||||
let mut spans: Vec<[f64; 2]> = Vec::new();
|
||||
for sp in runs.into_iter().flat_map(|r| r.spans) {
|
||||
push_span(&mut spans, sp);
|
||||
}
|
||||
(path, spans)
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `sp` to `spans`, extending the last one when `sp` carries straight on from it.
|
||||
fn push_span(spans: &mut Vec<[f64; 2]>, sp: [f64; 2]) {
|
||||
if let Some(last) = spans.last_mut()
|
||||
&& (last[1] - sp[0]).abs() < 1e-9
|
||||
&& (last[1] >= last[0]) == (sp[1] >= sp[0])
|
||||
{
|
||||
last[1] = sp[1];
|
||||
return;
|
||||
}
|
||||
spans.push(sp);
|
||||
}
|
||||
|
||||
/// Two runs' spans, one after the other.
|
||||
fn joined(a: &[[f64; 2]], b: &[[f64; 2]]) -> Vec<[f64; 2]> {
|
||||
let mut out = a.to_vec();
|
||||
for &sp in b {
|
||||
push_span(&mut out, sp);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
struct Faces {
|
||||
face_of_half: Vec<Option<usize>>,
|
||||
/// A point inside each face.
|
||||
@@ -934,6 +989,8 @@ struct Run {
|
||||
line: bool,
|
||||
src: usize,
|
||||
t: [f64; 2],
|
||||
/// The stretches of item paths it covers ([`Piece::spans`]).
|
||||
spans: Vec<[f64; 2]>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
@@ -943,14 +1000,14 @@ impl Run {
|
||||
if self.src == o.src && self.t[1] == o.t[0] && forward(self) == forward(o) && self.src != usize::MAX {
|
||||
let s = segs.get(self.src)?;
|
||||
let c = pinned(&sub(&s.c, self.t[0], o.t[1]), self.line, self.c[0], o.c[3]);
|
||||
return Some(Run { c, line: self.line, src: self.src, t: [self.t[0], o.t[1]] });
|
||||
return Some(Run { c, line: self.line, src: self.src, t: [self.t[0], o.t[1]], spans: joined(&self.spans, &o.spans) });
|
||||
}
|
||||
if self.line && o.line {
|
||||
let (a, b, c) = (self.c[0], self.c[3], o.c[3]);
|
||||
let d = c.sub(a);
|
||||
let l = d.len();
|
||||
if l > 1e-9 && (d.cross(b.sub(a)) / l).abs() < 0.01 && d.dot(b.sub(a)) > 0.0 && d.dot(c.sub(b)) > 0.0 {
|
||||
return Some(Run { c: line_cubic(a, c), line: true, src: usize::MAX, t: [0.0, 0.0] });
|
||||
return Some(Run { c: line_cubic(a, c), line: true, src: usize::MAX, t: [0.0, 0.0], spans: joined(&self.spans, &o.spans) });
|
||||
}
|
||||
}
|
||||
None
|
||||
|
||||
@@ -370,3 +370,31 @@ fn intersect_clips_to_the_region() {
|
||||
let want = std::f32::consts::PI * 100.0 / 4.0;
|
||||
assert!((area(&quarter) - want).abs() < want * 0.002, "{} vs {want}", area(&quarter));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_pieces_say_which_stretch_of_their_path_they_run_along() {
|
||||
// A line from x 0 to 100, crossed by another at x 30 (crossings start new pieces): its two
|
||||
// pieces run along positions 1.0..1.3 and 1.3..2.0 (command 1 draws it).
|
||||
let a = Path::line(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0));
|
||||
let b = Path::line(Vec2::new(30.0, -50.0), Vec2::new(30.0, 50.0));
|
||||
let m = run(&[stroked(&a, None, 1), stroked(&b, None, 2)]);
|
||||
let mut spans: Vec<[f64; 2]> = m.strokes.iter().filter(|p| p.item == 0).flat_map(|p| p.spans.clone()).collect();
|
||||
spans.sort_by(|x, y| x[0].min(x[1]).total_cmp(&y[0].min(y[1])));
|
||||
assert_eq!(spans.len(), 2, "{m:?}");
|
||||
let lo = |s: [f64; 2]| s[0].min(s[1]);
|
||||
let hi = |s: [f64; 2]| s[0].max(s[1]);
|
||||
assert!((lo(spans[0]) - 1.0).abs() < 1e-6 && (hi(spans[0]) - 1.3).abs() < 1e-3, "{spans:?}");
|
||||
assert!((lo(spans[1]) - 1.3).abs() < 1e-3 && (hi(spans[1]) - 2.0).abs() < 1e-6, "{spans:?}");
|
||||
// A polyline uncut keeps one span over all its segments, and fills carry none.
|
||||
let mut z = Path::new();
|
||||
z.move_to(Vec2::new(0.0, 0.0));
|
||||
z.line_to(Vec2::new(50.0, 0.0));
|
||||
z.cubic_to(Vec2::new(70.0, 0.0), Vec2::new(90.0, 5.0), Vec2::new(100.0, 20.0));
|
||||
let r = rect(200.0, 0.0, 10.0, 10.0);
|
||||
let m = run(&[stroked(&z, None, 1), fill(&r, 3)]);
|
||||
assert_eq!(m.strokes.len(), 1);
|
||||
let sp = &m.strokes[0].spans;
|
||||
assert_eq!(sp.len(), 1, "{sp:?}");
|
||||
assert!((lo(sp[0]) - 1.0).abs() < 1e-9 && (hi(sp[0]) - 3.0).abs() < 1e-9, "{sp:?}");
|
||||
assert!(m.fills.iter().all(|f| f.spans.is_empty()));
|
||||
}
|
||||
@@ -141,3 +141,9 @@ was copied.
|
||||
styles.
|
||||
* An eyedropper cursor.
|
||||
* Showing a gradient in the toolbar swatch.
|
||||
|
||||
## Note (2026-11-13)
|
||||
|
||||
ADR 0093: width-profiled lines and gradient fills erase, each piece keeping its widths or its
|
||||
part of the gradient; inside an open symbol or drawing object the Eraser erases its shapes, and
|
||||
on the stage `draw.erase` reports what it kept (`kept`) with a hint.
|
||||
@@ -152,3 +152,8 @@ was copied: no presets, no shapes and no art brushes.
|
||||
* A live preview through the shaping.
|
||||
* Sharing brushes inside a document.
|
||||
* Animate's brush library import (its format is not public).
|
||||
|
||||
## Note (2026-11-13)
|
||||
|
||||
ADR 0093 adds tilt (per sample, turning and widening the tip), texture and scatter, and the
|
||||
Charcoal and Spatter brushes. Pressured Paint Brush lines are raw now: width profiles merge.
|
||||
@@ -0,0 +1,148 @@
|
||||
# ADR 0093: Tilt, textured brushes, erasing inside symbols, and profiles in the merge
|
||||
|
||||
* Status: accepted (2026-11-13)
|
||||
* Relates to: ADR 0033 (Brush tool), ADR 0034 (Eraser), ADR 0068 (brush library), ADR 0031 and
|
||||
0042 (merge drawing), ADR 0018 (variable-width strokes), ADR 0045 and 0080 (editing in place)
|
||||
|
||||
## Context
|
||||
|
||||
The first brush and eraser slices left four gaps that Animate users notice:
|
||||
|
||||
* **Tilt.** In Animate a leaning pen can turn and widen the brush.
|
||||
* **Textured brushes.** Dry media (charcoal, chalk on rough paper) and spatter.
|
||||
* **Erasing inside symbols.** The Eraser kept symbols whole with no hint of what to do instead.
|
||||
* **Gradients and width profiles in the merge.** A variable-width line was always kept whole,
|
||||
as an object, so the Eraser couldn't touch it and a pressured Paint Brush line was never raw.
|
||||
Gradients already merged (ADR 0042), but nothing tested that a cut keeps them in place.
|
||||
|
||||
We learned the behaviour from Adobe's public help pages and by watching the program. Nothing
|
||||
was copied: no code, presets, textures or brushes.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Tilt is per sample and shapes the tip analytically.**
|
||||
* A sample may carry the pen's tilt as the W3C Pointer Events spec gives it: `altitude` (90°
|
||||
upright to 0° flat) and `azimuth` (the way the pen leans on the stage, clockwise from +x).
|
||||
Over the CLI and MCP a point is `[x, y, pressure, altitude, azimuth]`. Out-of-range
|
||||
altitudes are clamped (it's a measurement), and azimuths wrap.
|
||||
* `lean = 1 − altitude / 90°`. The lean is carried along the centre line as a vector toward
|
||||
the azimuth, so it blends smoothly between samples and through upright.
|
||||
* **Angle** (`tilt_angle`): the tip's angle is the brush's angle plus the azimuth. Below a lean
|
||||
of 0.02 the azimuth is noise, so the brush's own angle holds.
|
||||
* **Width** (`tilt_width`): the size factor is multiplied by `1 + lean` (up to 2× lying flat).
|
||||
For the Paint Brush this goes into its width profile.
|
||||
* A mouse sends no tilt, so it is never affected. Strokes without tilt give exactly the
|
||||
outline they gave before: the same code path, and turning tilt on without tilt in the points changes nothing (tested).
|
||||
|
||||
*The sweep with a turning tip.* ADR 0033's distance field lives in one tip space, which no
|
||||
longer exists once the tip turns. When any point's angle differs from the brush's, the field
|
||||
is sampled in stage space (in tip radii), and the stroke is cut into pieces that turn at most
|
||||
3° each. Each piece measures its distance in its own tip space; that distance times the
|
||||
roundness is a lower bound on the stage distance with the same zero level, which is all the
|
||||
tracing needs. Cells are scaled by the roundness, so a thin nib is still resolved.
|
||||
|
||||
*The platform gap.* winit 0.30 reports tilt only on iOS (`Force::Calibrated`'s
|
||||
`altitude_angle`), and egui 0.36's touch events carry only `force`. No desktop system passes
|
||||
a pen's tilt to the shell yet. The model, the point format and the command params are ready,
|
||||
so scripts, the CLI and MCP can paint with tilt today.
|
||||
|
||||
*Hidden until a pen reports it.* A control that does nothing confuses artists, so
|
||||
Properties shows no Tilt options until a pointer event has carried tilt this session
|
||||
(`App::pen_tilt_seen`, set from `brushtool::frame_tilt`, the one place tilt is read). Then
|
||||
they appear by themselves. Brushes keep their tilt settings either way (Charcoal follows
|
||||
tilt), so a brush set moves between computers unchanged. A UI test checks both states. We didn't add a platform-specific tablet API (Wintab, Windows Ink, NSEvent tilt,
|
||||
XInput2 valuators): that would mean `unsafe`, FFI and a code path per OS for one value. The
|
||||
right place for it is upstream in winit.
|
||||
|
||||
2. **Textured brushes stay vector, from fixed patterns.**
|
||||
* **Texture** (`texture`, 0–100 %) is a paper grain: two-octave value noise, fixed on the
|
||||
stage and measured in tip radii (so it scales with the brush). Where it falls below a
|
||||
threshold of `0.2 + 0.4 × texture`, the paint has a hole. The field takes
|
||||
`min(distance, (noise − threshold) × grain size)`, roughly a distance, so tracing gives
|
||||
clean hole outlines. Holes only ever cut into the paint: the outline never grows. Strokes
|
||||
laid over each other share the grain, as on real paper. Cells are finer (1/18 of a radius)
|
||||
and an outline keeps at most 20,000 loops.
|
||||
* **Scatter** (`scatter`, 0–200 % of the size) throws each dab sideways from the line and
|
||||
sizes it at 60–100 %, both from a fixed hash of the dab's number. A continuous brush with
|
||||
scatter stamps dabs a quarter size apart.
|
||||
* Both are deterministic, and both make ordinary filled shapes that merge, erase, tween and
|
||||
export everywhere.
|
||||
* New built-ins: **Charcoal** (an oval with grain, following tilt) and **Spatter**.
|
||||
|
||||
*Rejected:* bitmap tips and textures. They would need new paint along a path in every
|
||||
renderer and export. Vector paint also renders crisply at any zoom and cost nothing new
|
||||
downstream.
|
||||
|
||||
3. **Width profiles go through the merge.**
|
||||
* Each segment in the planar merge now carries its place on its item's path as a *path
|
||||
position*: `k + t` is parameter `t` along the segment that command `k` draws.
|
||||
* Each stroke piece reports the stretches it runs along (`Piece::spans`, in order,
|
||||
backwards where it runs backwards). Straight-run joins and closed loops are handled.
|
||||
* `WidthProfile::along(path, spans)` (in the model) gives the piece its part of the profile:
|
||||
* every width point inside a stretch moves to the same place on the piece, by arc length
|
||||
(composite Gauss–Legendre on the source's cubics);
|
||||
* where the piece starts, ends or jumps mid-profile, a point holds the width it had;
|
||||
* running backwards swaps left and right;
|
||||
* a piece with one width gets no profile.
|
||||
* A profiled stroke is a stroke style of its own in the merge, so its pieces never chain into
|
||||
another stroke's.
|
||||
* An uncut stroke keeps its profile point for point (tested). Merging the pieces again keeps
|
||||
them (tested).
|
||||
* Lines are still cut by their centre line, as in ADR 0034.
|
||||
* As a result, a variable-width line drawn with Object Drawing off is raw, and so is a
|
||||
pressured Paint Brush line (ADR 0068 drew these as objects).
|
||||
|
||||
4. **Gradients keep their place when cut.** This works through ADR 0042's paint carried into
|
||||
keyframe space. It is now tested: after an erase, each piece's paint mapped to the stage
|
||||
equals the original within a thousandth of a unit, and the renderer shows both ends' colours.
|
||||
|
||||
5. **Erasing inside symbols uses editing in place.**
|
||||
* Inside an open symbol, group or drawing object (ADR 0045, 0073, 0080), `draw.erase` already
|
||||
works on that timeline in its own space, and every instance shows the change. That is now
|
||||
tested: one erase, one undo step.
|
||||
* On the stage, symbols and drawing objects stay whole, as in Animate. `draw.erase` now
|
||||
reports what it passed over and kept (`kept: {symbols, objects}`). When nothing was erased,
|
||||
its reason says to double-click one with the Selection tool. The shell's status bar says
|
||||
the same in a translatable sentence.
|
||||
|
||||
6. **Fix in the curve fitter.** Schneider's least-squares solve could put a handle a hundred
|
||||
times the stretch's length away on a tiny, nearly closed stretch (the grain's small holes
|
||||
found it). A handle longer than the points' own arc length now falls back, and the error
|
||||
check splits the stretch instead. Chalk's ragged outline went from 321 to 245 anchors, with
|
||||
its area within its tested bounds.
|
||||
|
||||
7. **Commands.**
|
||||
* `draw.brush` gains 5-number points, `texture`, `scatter`, `tilt_angle` and `tilt_width`.
|
||||
So does `brush.preset_save`, and brush presets keep them (`#[serde(default)]`: older brush
|
||||
sets and preferences load as before).
|
||||
* There is no new namespace, so the plug-in policy is unchanged (`draw.*` may be called).
|
||||
* Shell: Texture and Scatter for the Brush; Properties › Tilt (Angle for the Brush, Width for
|
||||
both brushes) once a pen has reported tilt.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Measured in release, 32 threads, median of 15, 400-unit wave (`preset_timings`):
|
||||
|
||||
| Stroke | Time | Anchors |
|
||||
| --- | --- | --- |
|
||||
| Charcoal (grain, oval) | 7.2 ms | 896 |
|
||||
| Spatter | 2.6 ms | 395 |
|
||||
| Flat 15 % nib turning 180° with tilt, 201 samples | 21.4 ms | 36 |
|
||||
| Round 10, widening with tilt | 1.5 ms | 16 |
|
||||
| Chalk, before and after the fitter fix | 3.0 → 3.1 ms | 321 → 245 |
|
||||
|
||||
* A textured stroke has many small loops. A very long one may pass the merge's 20,000-segment
|
||||
budget, and then it is added whole as an object (ADR 0031), with nothing lost.
|
||||
* The live preview while dragging still shows the plain tip, without the grain, scatter or
|
||||
turning.
|
||||
* The file format is unchanged. Older files open as they did, and older builds read raw
|
||||
profiled strokes as before (the `merge` flag is ignored there).
|
||||
|
||||
## Not yet
|
||||
|
||||
* Reading tilt from a pen on Windows, macOS and Linux (waits for winit), and so the Tilt
|
||||
options in Properties there.
|
||||
* Bitmap, art and pattern brushes; custom tip shapes.
|
||||
* Eraser pressure, tilt and presets.
|
||||
* A live preview through texture, scatter and tilt.
|
||||
* Erasing symbols on the stage without opening them (Animate doesn't either).
|
||||
+30
-3
@@ -152,6 +152,22 @@ the tip sweeps. A click paints a single dab. The options set the **Size** (or pr
|
||||
The last three never cover lines. With
|
||||
a pen tablet, pressure sets the width, from 10 % to the full size.
|
||||
|
||||
**Texture and scatter.** **Texture** lets a paper grain show through the paint, like charcoal
|
||||
on rough paper; the grain stays put on the stage, so strokes laid over each other share it.
|
||||
**Scatter** throws dabs either side of the stroke and varies their size, for spatter and
|
||||
stipple. Both are still ordinary vector shapes: they merge, erase, scale and export like any
|
||||
other paint, and the same stroke always comes out the same. The **Charcoal** and **Spatter**
|
||||
brushes in the Brush menu use them.
|
||||
|
||||
**Tilt.** Brushes can follow a pen's tilt: the tip turns with the way the pen leans (so a flat
|
||||
nib follows your hand), and paints wider as it leans, up to twice as wide lying flat. A mouse
|
||||
is never affected. Windows, macOS and Linux don't pass a pen's tilt on to AniCraft yet, so the
|
||||
**Tilt** options (**Angle** and **Width**; the Paint Brush has **Width**) stay hidden in
|
||||
Properties. They appear by themselves as soon as a pen reports its tilt. Meanwhile scripts and
|
||||
assistants can paint with tilt: `draw.brush` takes points as `[x, y, pressure, altitude,
|
||||
azimuth]` and `tilt_angle` and `tilt_width` (see [Working headless](working-headless.md)). The
|
||||
**Charcoal** brush follows tilt when there is any.
|
||||
|
||||
**Snapping while you draw**: with **Snap to Objects** on (the magnet under the tools, or **Ctrl+Shift+/**), the Line,
|
||||
Rectangle, Oval, PolyStar and Pen tools snap their points to nearby points, lines and fill
|
||||
edges, within 10 screen pixels. A ring shows where a point will snap.
|
||||
@@ -177,6 +193,10 @@ A line's thickness can change along its length. To give a line a profile, select
|
||||
one under **Width** in Properties: Uniform, Taper both ends, Taper start, Taper end, Bulge or
|
||||
Pinch. Set a profile in a drawing tool's options to make new lines start that way.
|
||||
|
||||
Variable-width lines are merged drawing too. A line drawn across one, or the Eraser, cuts it
|
||||
into pieces, and each piece keeps the widths it had there: a tapered line cut in the middle
|
||||
gives two pieces, each tapering at its outer end.
|
||||
|
||||
For finer control, use the **Width** tool (**U**); the pointer becomes a crosshair. Hover over a
|
||||
line: a white box on it shows where a drag adds a width point, and the line's points show
|
||||
their handles. Drag on the line to make it wider or narrower there, drag a point's handle to
|
||||
@@ -313,7 +333,13 @@ Tick **Faucet** to delete a whole fill or line with a single click. **Erase Ever
|
||||
a double-click on the Eraser tool, clears every visible, unlocked layer at the current frame.
|
||||
It asks first, and you can undo it.
|
||||
|
||||
The Eraser can't erase inside symbols, or lines with a width profile, yet.
|
||||
Gradient fills and variable-width lines erase like any other: each piece that's left keeps its
|
||||
part of the gradient where it was, and its widths along the line.
|
||||
|
||||
On the stage the Eraser leaves symbols and drawing objects alone, and the status bar says so.
|
||||
To erase inside one, **double-click** it with the Selection tool (or select it and press
|
||||
**Ctrl+E**): it opens in place, and the Eraser works on its own lines and fills. A symbol
|
||||
changes everywhere it's used.
|
||||
|
||||
## Transforming artwork
|
||||
|
||||
@@ -496,6 +522,7 @@ without snapping. Rulers, the grid and guides never show in Test Movie or in exp
|
||||
## Not there yet
|
||||
|
||||
Not in AniCraft yet: gradient and bitmap strokes; swatch folders, bitmap swatches and the
|
||||
swatches inside Animate files; moving the Envelope's handles from the keyboard; pen tilt for
|
||||
brushes; erasing inside symbols; and Animate's ragged, stipple and hatched line styles (drawn
|
||||
swatches inside Animate files; moving the Envelope's handles from the keyboard; reading a
|
||||
pen's tilt on Windows, macOS and Linux (the brushes' tilt settings are ready for it); bitmap
|
||||
and art brushes; and Animate's ragged, stipple and hatched line styles (drawn
|
||||
solid when you open an Animate file).
|
||||
@@ -592,11 +592,11 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Movie Explorer** `explorer.tree`
|
||||
Parameters: `{scope?: document (default) | scene, show?: {text?, symbols?, scripts?, media?, frames? (layers and keyframes)} (each default true), definitions?: bool (the Library's symbols; default true), expanded?: [row keys] (default: the top rows), all?: bool (everything open), filter?: text (rows whose names hold it, and the rows above them), offset?, limit? (default 1000, at most 10000)} → {rows: [{key, depth, kind, type?, name, extra, frame?, children, open, go: find.goto params}], total, truncated}`
|
||||
- **Brush Stroke** `draw.brush` · changes the document
|
||||
Parameters: `{points: [[x, y] or [x, y, pressure 0..1 (clamped)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}`
|
||||
Parameters: `{points: [[x, y], [x, y, pressure 0..1 (clamped)] or [x, y, pressure, altitude, azimuth] (the pen's tilt in degrees: altitude 90 upright to 0 flat, azimuth the way it leans, clockwise from +x)], ..] (one point paints a dab), preset? (a brush from brush.preset_list, by key or name: its settings are the defaults for the rest), size? (stage units, default 10), shape?: round|square, angle? (degrees), roundness? (5..100 %, default 100), smoothing? (0..100, default 50), curve?: linear|soft|firm|[[pressure, output], ..] (how pressure maps, both 0..1), pressure_size? (default true: pressure varies the size from 10 to 100 %), pressure_opacity? (default false: the stroke's average pressure sets its opacity), taper_start?, taper_end? (0..50 % of the stroke's length), spacing? (0 continuous, or 5..1000 % of the size between dabs), jitter? (0..50 % of the size: a ragged edge), texture? (0..100 %: a paper grain of holes through the paint), scatter? (0..200 % of the size: dabs thrown either side of the line, varied in size), tilt_angle? (the pen's tilt turns the tip: its angle plus the azimuth), tilt_width? (the pen's tilt widens the tip, up to twice as wide flat; also the Paint Brush's width), as_stroke? (default false; true: the Paint Brush, a variable-width stroke in the stroke colour, editable with the Width tool), mode?: normal|fills|behind|selection|inside (Paint Normal covers fills and lines, Paint Fills leaves lines, Paint Behind paints only empty areas, Paint Selection only inside the selected fills, Paint Inside only inside the fill the stroke starts on or the empty area closed off around it; ADR 0080), color? (default: the fill colour, or the stroke colour as a stroke), unit? (stage units per screen point, default 1: smoothing and accuracy follow it), object?}`
|
||||
- **Brush Presets** `brush.preset_list`
|
||||
Parameters: `{} the built-in brushes and yours, with their settings`
|
||||
- **Save Brush** `brush.preset_save`
|
||||
Parameters: `{name, from? (a preset to start from; default: the plain brush), size?, shape?, angle?, roundness?, smoothing?, curve?, pressure_size?, pressure_opacity?, taper_start?, taper_end?, spacing?, jitter? (as draw.brush)} saves a brush of your own (replacing yours of that name; kept in your preferences)`
|
||||
Parameters: `{name, from? (a preset to start from; default: the plain brush), size?, shape?, angle?, roundness?, smoothing?, curve?, pressure_size?, pressure_opacity?, taper_start?, taper_end?, spacing?, jitter?, texture?, scatter?, tilt_angle?, tilt_width? (as draw.brush)} saves a brush of your own (replacing yours of that name; kept in your preferences)`
|
||||
- **Rename Brush** `brush.preset_rename`
|
||||
Parameters: `{name, to}`
|
||||
- **Delete Brush** `brush.preset_delete`
|
||||
|
||||
+3
-3
@@ -11,7 +11,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`<mask>` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. Filters apply in list order and may be switched off (ADR 0091): `evaluate` leaves switched-off ones out, so every renderer and export draws them as absent. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for boLine truncated
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it; a motion tween's keys stretch in proportion, ADR 0083). Side dock tab strips never run under the panel menu (names shrink with an ellipsis, then the strip scrolls). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a onLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing Line truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing Line truncated
|
||||
| Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. **Exporter and ease plug-ins** (ADR 0088): `kind: "exporter"` declares a format (name, extension, options) and gets evaluated frames (`movie`, `frame`: the flattened display list, never the document), returning the file's bytes from `ac_export` (64 MiB cap, 5·10¹⁰ instructions, 10 min); File › Export lists it with an Export window (options, frames, file, progress bar and Cancel on a worker thread); `file.export_plugin`, `file.export_formats`, `anicraft-cli export --format <id>` and `formats`. `kind: "ease"` declares named eases, `ac_ease(i, t)` sampled into 257 values at load (NaN, unbounded or end-missing eases refused); `Easing::Sampled` keeps the table in the document, so it plays the same without the plug-in; the ease menus list them under Plug-in eases; `{plugin, ease}` easing params. Samples: Plain Text Frames and Stepped Eases, built and run in CI. Not yet: plug-in formats in Publish, bitmaps' pixels and sounds for exporters, ease plug-ins with parameters, background runs of command plug-ins, a binary document view. |
|
||||
| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. **A window of its own on the desktop** (ADR 0062): sized to the stage at 100 % (smaller to fit the screen), titled with the document, back where it was last (not on Wayland, where the desktop places windows), with the keyboard when it opens; Esc or Ctrl+W (⌘W) closes it, Ctrl+Enter restarts it in place, and the editor's Ctrl/Alt shortcuts work from it; floating inside the editor in the web build, where the system can't open windows (it says so), or by choice in Preferences › Test Movie. Not yet: full screen, zoom in the movie window, remembering its size. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; **filters and Subtract/Invert in the page** (ADR 0072: `filters.js`, a port of the renderer's filters run over the group's pixels on a layer that reaches past the canvas by the filters' reach, Subtract and Invert composited per pixel, results kept while the group is unchanged; equal to the oracle's pixels within 9.3e-4 in Boa; 3.4 ms a frame for the demo's filters at 1080p while they change); Web Audio for Event/Start/Stop/Stream sounds; bitmap tints, 9-slice scaling and plug-in frame scripts reported. Not yet: 9-slice in the page, keeping a moving filtered group's pixels, filters off the main thread. **Kept frame scripts** (ADR 0013 tier 1): scripts written in another language (an Animate document's ActionScript) kept verbatim on keyframes with their language, symbol linkage classes and the document class; the Actions panel's **Script** view (monospace editor with line numbers, language, live and undoable), the same "a" marker, Class rows in Properties; `script.set/clear/list/set_class`; **ActionScript timeline subset runs** (ADR 0013 tier 2): a hand-written, bounded lexer and parser (`anicraft_actions::as3`) lower stop/play/go to/next and previous frame and scene on instance-name paths, mouse listeners (click, down, up, roll over and out; named or inline functions, `currentTarget`), `trace` and property settings to the action IR, compiled once per script; anything else is reported with line and column and the script doesn't run (never half-run), `navigateToURL` and the like are ignored and noted; the player keeps listeners per instance, Test Movie's Output says which scripts run and which don't and why, the Script view lists problems in place, the XFL report and `script.list/check` say what runs, and the HTML page runs the same steps (`player.js` checked against the Rust player). **ActionScript small logic** (ADR 0052): scripts compile to a small typed script IR evaluated by the player with fuel (100,000 per script or listener call, 1,000,000 per step; an endless loop or a run-time error stops its script with an Output line and the movie plays on): typed variables (Number, int, uint, Boolean, String, untyped) kept per timeline instance across its frame scripts, expressions as ECMA-262 has them, `if`/`else`, `for`/`while`/`do`, functions with parameters, results and recursion, called from any frame of the same timeline (a timeline-level link step; names that aren't there keep the script from running, said in place), property reads of instances and timelines (`x`, `y`, `alpha`, `visible`, `rotation`, `scaleX/Y`, `currentFrame`, `tLine truncated
|
||||
| Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. |
|
||||
@@ -40,7 +40,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals; not yet: filter colours, quality and switches as tracks, Animate's filter tracks from XFL; filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: instances and shapes in one armature, reshaping at a posed frame); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: instances and shapes in one armature, reshaping at a posed frame); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles) and brush library; ~~tilt, textured brushes, erasing inside symbols, gradients and width profiles in the merge~~ ✅ second slice (ADR 0093: tilt turns and widens the tip per sample, paper-grain texture and scatter as vector paint, Charcoal and Spatter, the Eraser's hint for symbols and objects, width profiles carried into each merged piece; not yet: reading tilt on desktop systems (winit 0.30 reports it only on iOS), bitmap, art and pattern brushes, eraser pressure and presets, the live preview through texture and tilt); ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). |
|
||||
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout), second slice ✅ (ADR 0087: the tools move like any panel, as a slim bar on any side or a tab laid out in columns; floating windows hold several tabs and drag back into a dock by their grip or title bar with the drop targets shown; docks collapse to strips of panel icons with flyouts over the stage (Esc or a click outside closes them); Manage Workspaces renames and deletes your own (built-in ones reset only); every panel fits the narrowest dock (200 pt), form rows wrapping under their label, checked by test in English and the pseudo-locale; not yet: dragging between two windows of their own on mixed-DPI screens verified by hand, panels side by side inside a floating window, columns of groups in one dock, minimum sizes per panel, panel shortcut keys). |
|
||||
|
||||
## Releases
|
||||
@@ -61,7 +61,7 @@ titled with its milestone.
|
||||
| M4 | Text from Animate files | XFL import, text engine (M5 first slice) |
|
||||
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
|
||||
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); next: command macros, or growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~painted weights and reshaping~~ ✅ (ADR 0090), ~~bone springs and joint translation~~ ✅ (ADR 0084), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068); next: Paint Selection/Inside, tilt | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~painted weights and reshaping~~ ✅ (ADR 0090), ~~bone springs and joint translation~~ ✅ (ADR 0084), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068), ~~tilt, texture, profiles in the merge~~ ✅ (ADR 0093); next: reading pen tilt from the toolkit, art brushes | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); ~~accessibility second pass~~ ✅ (ADR 0064); ~~a light theme~~ ✅ (ADR 0077); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~dockable panels and workspaces~~ ✅ first and second slices (ADR 0075, ADR 0087); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe |
|
||||
|
||||
Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and
|
||||
|
||||
+67
@@ -433,6 +433,9 @@ pub struct App {
|
||||
pub filter_naming: crate::panels::FilterNaming,
|
||||
pub brush_samples: Vec<(anicraft_engine::geom::Vec2, Option<f32>)>,
|
||||
pub pen_pressure: Option<f32>,
|
||||
/// Whether a pointer event has carried a pen's tilt this session (ADR 0093). Until one has,
|
||||
/// the brushes' Tilt options stay hidden: they would do nothing.
|
||||
pub pen_tilt_seen: bool,
|
||||
/// Eraser tool options (ADR 0034); its stroke's samples are `brush_samples`.
|
||||
pub eraser: crate::erasertool::EraserOptions,
|
||||
pub bucket_gap: GapSize,
|
||||
@@ -711,6 +714,7 @@ impl App {
|
||||
filter_naming: Default::default(),
|
||||
brush_samples: Vec::new(),
|
||||
pen_pressure: None,
|
||||
pen_tilt_seen: false,
|
||||
eraser: crate::erasertool::EraserOptions::default(),
|
||||
bucket_gap: GapSize::default(),
|
||||
align_to_stage: false,
|
||||
@@ -2049,6 +2053,69 @@ impl App {
|
||||
self.drag = Drag::Eraser;
|
||||
}
|
||||
}
|
||||
Some("tiltbrush") => {
|
||||
// Tilt and textured brushes (ADR 0093) on a new layer: a flat nib whose angle
|
||||
// follows the pen's azimuth as it turns along an S, a round brush widening as the
|
||||
// pen lies down, Charcoal (the paper grain) and Spatter.
|
||||
// Tilt comes in through the command's points, as no
|
||||
// desktop system reports it to the toolkit yet; so Properties shows Texture and
|
||||
// Scatter, and keeps the Tilt options hidden (ADR 0093).
|
||||
self.run("layer.new", json!({"name": "Tilt"}));
|
||||
self.run("draw.object_drawing", json!({"on": false}));
|
||||
let s_curve: Vec<[f32; 5]> = (0..=90)
|
||||
.map(|i| {
|
||||
let t = i as f32 / 90.0;
|
||||
[140.0 + t * 520.0, 200.0 + (t * std::f32::consts::TAU).sin() * 70.0, 1.0, 35.0, 180.0 * t]
|
||||
})
|
||||
.collect();
|
||||
self.run("draw.brush", json!({"points": s_curve, "size": 30, "roundness": 15, "angle": 0, "tilt_angle": true, "color": "#1b2a4a"}));
|
||||
let lying: Vec<[f32; 5]> = (0..=60).map(|i| [140.0 + i as f32 * 8.6, 380.0, 1.0, 90.0 - i as f32 * 1.5, 0.0]).collect();
|
||||
self.run("draw.brush", json!({"points": lying, "size": 14, "tilt_width": true, "color": "#e8553b"}));
|
||||
let wave = |y: f32| -> Vec<[f32; 3]> { (0..=60).map(|i| [140.0 + i as f32 * 8.6, y + (i as f32 * 0.16).sin() * 22.0, 0.4 + 0.6 * (i as f32 / 60.0 * std::f32::consts::PI).sin()]).collect() };
|
||||
self.run("draw.brush", json!({"points": wave(500.0), "preset": "charcoal", "size": 34, "color": "#3a4150"}));
|
||||
self.run("draw.brush", json!({"points": wave(620.0), "preset": "spatter", "size": 9, "color": "#3d8bfd"}));
|
||||
// Sample artwork's labels are document text, not interface text.
|
||||
for (y, text) in [(180.0, "Tilt turns the nib"), (360.0, "Tilt widens the tip"), (470.0, "Charcoal"), (610.0, "Spatter")] { // i18n-exempt: sample text
|
||||
self.run("text.create", json!({"x": 720, "y": y, "text": text, "size": 22, "color": "#f4f1ea"}));
|
||||
}
|
||||
self.run("edit.deselect", json!({}));
|
||||
self.tool = Tool::Brush;
|
||||
if let Some(p) = anicraft_engine::brush_library::builtin("charcoal") {
|
||||
crate::brush_panel::choose(self, &p);
|
||||
}
|
||||
}
|
||||
Some("erasemerge") => {
|
||||
// ADR 0093 on a new layer: a raw gradient rectangle cut in two by the eraser (each
|
||||
// piece keeps its part of the gradient), a variable-width raw line erased across
|
||||
// (each piece keeps its widths), and a symbol the eraser passed over on the stage,
|
||||
// with the hint that says how to erase inside it.
|
||||
self.run("layer.new", json!({"name": "Erased"}));
|
||||
self.run("draw.object_drawing", json!({"on": false}));
|
||||
let stops = vec![anicraft_engine::doc::GradientStop { offset: 0.0, color: anicraft_engine::doc::Rgba::hex(0xe8553b) }, anicraft_engine::doc::GradientStop { offset: 1.0, color: anicraft_engine::doc::Rgba::hex(0x3d8bfd) }];
|
||||
self.s.style.fill_paint = Some(anicraft_engine::doc::Paint::linear(anicraft_engine::geom::Vec2::new(120.0, 0.0), anicraft_engine::geom::Vec2::new(600.0, 0.0), stops));
|
||||
self.s.style.lock_fill = true;
|
||||
self.run("draw.rect", json!({"x": 120, "y": 120, "w": 480, "h": 240, "stroke": null}));
|
||||
self.s.style.fill_paint = None;
|
||||
self.s.style.lock_fill = false;
|
||||
let band: Vec<[f32; 2]> = (0..=60).map(|i| [360.0 + (i as f32 * 0.2).sin() * 40.0, 90.0 + i as f32 * 5.0]).collect();
|
||||
self.run("draw.erase", json!({"points": band, "size": 36}));
|
||||
self.s.style.set_profile(anicraft_engine::doc::ProfilePreset::TaperBoth);
|
||||
self.run("draw.line", json!({"x0": 120, "y0": 480, "x1": 600, "y1": 480, "stroke": "#1b2a4a", "stroke_width": 28}));
|
||||
self.s.style.set_profile(anicraft_engine::doc::ProfilePreset::Uniform);
|
||||
for x in [260.0f32, 440.0] {
|
||||
self.run("draw.erase", json!({"points": [[x, 440.0], [x + 10.0, 520.0]], "size": 44}));
|
||||
}
|
||||
self.run("draw.ellipse", json!({"x": 760, "y": 160, "w": 300, "h": 300, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 4}));
|
||||
self.run("edit.select_all", json!({}));
|
||||
let disc = self.s.visible_elements().iter().filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge && sh.path.bounds().transformed(&e.transform).min.x >= 740.0)).map(|e| e.id.0).collect::<Vec<_>>();
|
||||
self.run("element.select", json!({"ids": disc}));
|
||||
self.run("modify.convert_to_symbol", json!({"name": "Sun"})); // i18n-exempt: a sample symbol name
|
||||
self.run("edit.deselect", json!({}));
|
||||
self.tool = Tool::Eraser;
|
||||
self.eraser = crate::erasertool::EraserOptions { size: 30.0, ..Default::default() };
|
||||
self.brush_samples = (0..=30).map(|i| (anicraft_engine::geom::Vec2::new(720.0 + i as f32 * 12.0, 310.0), None)).collect();
|
||||
crate::erasertool::commit(self, crate::pathtools::Xf { origin: egui::Pos2::ZERO, zoom: 1.0 });
|
||||
}
|
||||
Some("eyedropper") => {
|
||||
// The sample's sky gradient picked with the Eyedropper: the fill swatch holds it.
|
||||
self.run("paint.pick", json!({"x": 640, "y": 40}));
|
||||
|
||||
+19
-1
@@ -312,6 +312,7 @@ pub fn props(app: &mut App, ui: &mut egui::Ui, row: impl Fn(&mut egui::Ui, &str,
|
||||
ui.painter().image(t.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE);
|
||||
});
|
||||
}
|
||||
let tilt_seen = app.pen_tilt_seen;
|
||||
let o = crate::brushtool::options_mut(app);
|
||||
row_prose(ui, tr!("Pressure"), &mut |ui| {
|
||||
crate::theme::checkbox(ui, &mut o.pressure_size, tr!("Size")).on_hover_text(tr!("Pen pressure varies the size, from 10 % to the full size"));
|
||||
@@ -338,8 +339,18 @@ pub fn props(app: &mut App, ui: &mut egui::Ui, row: impl Fn(&mut egui::Ui, &str,
|
||||
});
|
||||
});
|
||||
row_prose(ui, tr!("Mouse"), &mut |ui| {
|
||||
crate::theme::checkbox(ui, &mut o.velocity, tr!("Speed as pressure")).on_hover_text(tr!("Without a pen: drawing faster makes the stroke thinner, as a pen pressed lightly would. Pen tilt is not read yet"));
|
||||
crate::theme::checkbox(ui, &mut o.velocity, tr!("Speed as pressure")).on_hover_text(tr!("Without a pen: drawing faster makes the stroke thinner, as a pen pressed lightly would"));
|
||||
});
|
||||
// Tilt (ADR 0093): shown once a pen has reported its tilt this session. Until then the
|
||||
// options would do nothing, so they stay out of the way (brushes keep their tilt settings).
|
||||
if tilt_seen {
|
||||
row_prose(ui, tr!("Tilt"), &mut |ui| {
|
||||
if !as_stroke {
|
||||
crate::theme::checkbox(ui, &mut o.tilt_angle, tr!("Angle")).on_hover_text(tr!("The pen's tilt turns the tip: the way it leans adds to the brush's angle"));
|
||||
}
|
||||
crate::theme::checkbox(ui, &mut o.tilt_width, tr!("Width")).on_hover_text(tr!("A leaning pen paints wider, up to twice as wide lying flat"));
|
||||
});
|
||||
}
|
||||
row(ui, tr!("Taper"), &mut |ui| {
|
||||
ui.add(egui::DragValue::new(&mut o.taper_start).suffix(" %").speed(0.5).range(0.0..=50.0).max_decimals(0)).named(tr!("Taper at the start")).on_hover_text(tr!("How much of the stroke swells from a point at its start"));
|
||||
ui.add(egui::DragValue::new(&mut o.taper_end).suffix(" %").speed(0.5).range(0.0..=50.0).max_decimals(0)).named(tr!("Taper at the end")).on_hover_text(tr!("How much of the stroke thins to a point at its end"));
|
||||
@@ -359,6 +370,13 @@ pub fn props(app: &mut App, ui: &mut egui::Ui, row: impl Fn(&mut egui::Ui, &str,
|
||||
row(ui, tr!("Rough edge"), &mut |ui| {
|
||||
ui.add(egui::DragValue::new(&mut o.jitter).suffix(" %").speed(0.5).range(0.0..=50.0).max_decimals(0)).named(tr!("Rough edge")).on_hover_text(tr!("Wears the edge in by up to this part of the size, like chalk. The same every time"));
|
||||
});
|
||||
// Textured brushes (ADR 0093): still vector paint.
|
||||
row(ui, tr!("Texture"), &mut |ui| {
|
||||
ui.add(egui::DragValue::new(&mut o.texture).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(0)).named(tr!("Texture")).on_hover_text(tr!("A paper grain shows through the paint, like charcoal on rough paper. The grain stays put on the stage, so strokes over each other share it"));
|
||||
});
|
||||
row(ui, tr!("Scatter"), &mut |ui| {
|
||||
ui.add(egui::DragValue::new(&mut o.scatter).suffix(" %").speed(1.0).range(0.0..=200.0).max_decimals(0)).named(tr!("Scatter")).on_hover_text(tr!("Throws dabs either side of the stroke, up to this part of the size away, and varies their size: spatter and stipple"));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,13 @@ pub struct BrushOptions {
|
||||
pub spacing: f32,
|
||||
/// Percent of the size the edge wears in.
|
||||
pub jitter: f32,
|
||||
/// Percent: the paper grain through the paint (ADR 0093).
|
||||
pub texture: f32,
|
||||
/// Percent of the size dabs are thrown aside.
|
||||
pub scatter: f32,
|
||||
/// What the pen's tilt shapes, where the system reports it.
|
||||
pub tilt_angle: bool,
|
||||
pub tilt_width: bool,
|
||||
}
|
||||
|
||||
impl Default for BrushOptions {
|
||||
@@ -77,6 +84,10 @@ impl BrushOptions {
|
||||
taper_end: p.taper_end,
|
||||
spacing: p.spacing,
|
||||
jitter: p.jitter,
|
||||
texture: p.texture,
|
||||
scatter: p.scatter,
|
||||
tilt_angle: p.tilt_angle,
|
||||
tilt_width: p.tilt_width,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +112,10 @@ impl BrushOptions {
|
||||
taper_end: self.taper_end,
|
||||
spacing: self.spacing,
|
||||
jitter: self.jitter,
|
||||
texture: self.texture,
|
||||
scatter: self.scatter,
|
||||
tilt_angle: self.tilt_angle,
|
||||
tilt_width: self.tilt_width,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,6 +197,23 @@ pub fn frame_pressure(ctx: &egui::Context) -> Option<f32> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The pen's tilt this frame, when the toolkit reports it (ADR 0093). egui 0.36's pointer and
|
||||
/// touch events carry only pressure, and winit 0.30 reports tilt only on iOS, so on the desktop
|
||||
/// this is `None` until they carry it. When it isn't, the Tilt options appear (see
|
||||
/// [`App::pen_tilt_seen`]).
|
||||
pub fn frame_tilt(ctx: &egui::Context) -> Option<anicraft_engine::geom::brush::Tilt> {
|
||||
// No egui event carries a tilt yet; this is where it is read once one does.
|
||||
let _ = ctx;
|
||||
None
|
||||
}
|
||||
|
||||
/// Notes a tilt reported this frame, so the Tilt options show from then on.
|
||||
pub fn note_tilt(app: &mut App, tilt: Option<anicraft_engine::geom::brush::Tilt>) {
|
||||
if tilt.is_some() {
|
||||
app.pen_tilt_seen = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a stroke at stage point `p` at time `now` (seconds). A mouse paints at full
|
||||
/// pressure, or from half pressure when its speed stands in for it.
|
||||
pub fn start(app: &mut App, p: Vec2, pressure: Option<f32>, now: f64) -> Drag {
|
||||
|
||||
+15
-1
@@ -53,8 +53,22 @@ pub fn commit(app: &mut App, xf: Xf) {
|
||||
let o = app.eraser;
|
||||
let params = json!({"points": points(&samples), "size": o.size, "shape": shape_key(o.shape), "mode": o.mode.key(), "unit": xf.unit()});
|
||||
let undo = app.undo_key();
|
||||
// What the stroke passed over and kept (ADR 0093): symbols and drawing objects, which open
|
||||
// in place with a double-click so their own lines and fills can be erased.
|
||||
let kept = |v: &serde_json::Value| (v["kept"]["symbols"].as_u64().unwrap_or(0), v["kept"]["objects"].as_u64().unwrap_or(0));
|
||||
match app.run("draw.erase", params) {
|
||||
Some(v) if v["erased"] == true => app.status_ok(tr!("Erased. {undo} to undo.", undo = undo)),
|
||||
Some(v) if v["erased"] == true => match kept(&v) {
|
||||
(0, 0) => app.status_ok(tr!("Erased. {undo} to undo.", undo = undo)),
|
||||
_ => app.status_ok(tr!("Erased the lines and fills. {undo} to undo. Symbols and drawing objects are kept: double-click one with the Selection tool to erase inside it.", undo = undo)),
|
||||
},
|
||||
Some(v) if kept(&v) != (0, 0) => {
|
||||
let k = kept(&v);
|
||||
app.status_ok(match k {
|
||||
(_, 0) => tr!("Nothing erased: on the stage the Eraser keeps symbols. Double-click one with the Selection tool to erase inside it."),
|
||||
(0, _) => tr!("Nothing erased: the Eraser keeps drawing objects. Double-click one with the Selection tool to erase inside it."),
|
||||
_ => tr!("Nothing erased: the Eraser keeps symbols and drawing objects. Double-click one with the Selection tool to erase inside it."),
|
||||
});
|
||||
}
|
||||
Some(v) => {
|
||||
// The engine's reason is English from below the shell.
|
||||
let why = v["reason"].as_str().map_or(std::borrow::Cow::Borrowed(tr!("nothing to erase there")), crate::i18n::t_dyn);
|
||||
|
||||
+3
-1
@@ -265,7 +265,7 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
/// `--help` (the console's text, in English).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// i18n-exempt: the --help console text
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
--shot-width scales the screenshot down to this width (the user guide's pictures)\n\
|
||||
@@ -426,3 +426,5 @@ mod packaging_tests;
|
||||
mod rulers_tests;
|
||||
#[cfg(test)]
|
||||
mod retime_ui_tests;
|
||||
#[cfg(test)]
|
||||
mod tilt_ui_tests;
|
||||
@@ -337,6 +337,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
let xf = crate::pathtools::Xf { origin, zoom };
|
||||
// Pen pressure, when a tablet reports it (the Brush tool's width follows it).
|
||||
let pressure = crate::brushtool::frame_pressure(ui.ctx());
|
||||
// Tilt, where the toolkit reports it: the brushes' Tilt options show once it has (ADR 0093).
|
||||
crate::brushtool::note_tilt(app, crate::brushtool::frame_tilt(ui.ctx()));
|
||||
let now = ui.input(|i| i.time);
|
||||
// The motion path takes the pointer with the selection tools (ADR 0030): its ends and
|
||||
// handles before the object under them, the path itself only where no object is.
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! The brushes' Tilt options (ADR 0093) show only once a pen has reported its tilt: until then
|
||||
//! they would do nothing.
|
||||
|
||||
use crate::app::{App, Tool};
|
||||
use egui::{Rect, vec2};
|
||||
|
||||
/// The labels drawn in a few frames of the app with the Brush (or the Paint Brush) in hand.
|
||||
fn labels(tool: Tool, tilt_seen: bool) -> Vec<String> {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.enable_accesskit();
|
||||
let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo());
|
||||
let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png")));
|
||||
app.tool = tool;
|
||||
crate::brushtool::note_tilt(&mut app, tilt_seen.then_some(anicraft_engine::geom::brush::Tilt { altitude: 40.0, azimuth: 10.0 }));
|
||||
let mut nodes = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1400.0))), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| app.frame(ui));
|
||||
out.textures_delta.clear();
|
||||
nodes = out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default();
|
||||
}
|
||||
nodes.iter().filter_map(|n| n.label().map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
fn count(labels: &[String], l: &str) -> usize {
|
||||
labels.iter().filter(|x| *x == l).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tilt_options_hide_until_a_pen_reports_tilt() {
|
||||
// The rows around it show, so Properties is drawn.
|
||||
let before = labels(Tool::Brush, false);
|
||||
assert!(before.iter().any(|l| l == "Texture"), "the Brush options are drawn: {before:?}");
|
||||
// No tilt reported: no Tilt row. Once a pen has reported tilt: its Angle and Width.
|
||||
let after = labels(Tool::Brush, true);
|
||||
assert_eq!(count(&after, "Angle"), count(&before, "Angle") + 1);
|
||||
assert_eq!(count(&after, "Width"), count(&before, "Width") + 1);
|
||||
// The Paint Brush has Width only.
|
||||
let (pb0, pb1) = (labels(Tool::PaintBrush, false), labels(Tool::PaintBrush, true));
|
||||
assert_eq!(count(&pb1, "Angle"), count(&pb0, "Angle"));
|
||||
assert_eq!(count(&pb1, "Width"), count(&pb0, "Width") + 1);
|
||||
// On the desktop nothing reports tilt yet.
|
||||
assert!(crate::brushtool::frame_tilt(&egui::Context::default()).is_none());
|
||||
}
|
||||
Reference in new issue
Block a user