Merge pull request #450 from storytold/m1/pen-and-squash

feat(pen): Pen parity (break, adjust, add, delete, continue) and tweens that keep area (M1)
This commit is contained in:
Tanish Manku authored and GitHub committed 2026-11-18 05:34:21 -07:00
commit 4488b2cdfd
26 files changed
+1635 -79

No files matched your search

+2
View File
@@ -109,6 +109,8 @@ OR Apache-2.0) is noted in the table.
| Cubic-Bézier easing (CSS model) | `crates/doc/src/easing.rs` | W3C CSS Easing Functions Level 1 | W3C Royalty-Free Patent Policy. |
| SVG path data syntax (file format v2) | `crates/geom/src/path.rs` | W3C SVG 1.1 / 2 | W3C Royalty-Free Patent Policy. |
| Ease presets: In/Out/In Out of Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic | `crates/doc/src/easing.rs` | The classic public easing equations (R. Penner, *Programming Macromedia Flash MX*, 2002, ch. 7, "Motion, Tweening, and Easing"; widely republished); Animate's set of eases from its public user guide | Our own implementation of the formulas (ADR 0081); Circ's curve drawn as circular arcs by the standard cubic arc approximation (handle length 4/3·tan(θ/4)). |
| Keep area: geometric (log-linear) interpolation of scale, `a·(b/a)^t`, so the product of two axes is kept (ADR 0115) | `crates/geom/src/lib.rs`, `crates/doc/src/eval.rs`, `crates/doc/src/motion.rs` | Public mathematical result (interpolation on a logarithmic scale); the squash-and-stretch principle as described in F. Thomas and O. Johnston, *The Illusion of Life* (1981); user issue #408 | Own implementation. |
| Pen tool behaviour on the last point and on drawn paths (corner, adjust, add, delete, continue) | `src/pathtools.rs`, `crates/engine/src/cmds_path.rs` | Adobe's public user guide for the Pen tool and a user's description of it (issue #319), by observation | Clean-room: behaviour only, our own code and pointer marks (ADR 0115). |
| Marching-squares contour tracing (Paint Bucket regions, Brush outlines) | `crates/geom/src/trace.rs` | Lorensen & Cline (1987); public algorithm | Ported from PhotoCraft's mask tracer (same project family and licence) and reviewed. |
| Chamfer distance transform (3-4) and flood fill | `crates/engine/src/cmds_paint.rs` | G. Borgefors, *Distance transformations in digital images* (1986); public algorithms | Gap closing, and growing fills under their outlines. |
| ZIP archive reading (`.fla`) | `crates/xfl/src/zip.rs`, `crates/xfl/src/end_record.rs`, `crates/xfl/tests/support/fla.rs` | PKWARE APPNOTE.TXT 6.3 (published ZIP specification), the Info-ZIP Unicode path extra field (0x7075, Info-ZIP `proginfo/extrafld.txt`); CRC-32 by slicing by 8 (M. Kounavis and F. Berry, "A Systematic Approach to Building High Performance Software-based CRC Generators", IEEE ISCC 2005); inflate by `miniz_oxide` (MIT OR Zlib OR Apache-2.0) | Stored and deflate entries, ZIP64, data descriptors, CP437 and UTF-8 names; no encryption (ADR 0054). |
+24
View File
@@ -2,6 +2,30 @@
## Unreleased
* **Pen tool improvements** (fixes #319, ADR 0115, M1): the Pen now does what Animate's does
on the point you just placed and on paths you drew earlier.
* **Click the last point** to make it a corner, so the next segment leaves it sharp; click
it again, double-click, or press Enter or Esc to finish. **Drag from it** for a new
handle. **Alt-drag it** to draw its curve again, with the old curve in view until you
let go.
* **Shift** keeps new points and handles on steps of 45°, and the segment your next click
would add is previewed as it will curve.
* **On a selected path**: click a smooth point to make it a corner and a corner to delete
it, click the outline to add a point, and click an open end to carry on drawing the same
path (its other end closes it). **Ctrl-click** (⌘) selects a path with the Pen.
* A mark beside the pointer says what a click will do: plus, minus, caret, ring, slash or
square.
* Headless, CLI and MCP: `path.extend` continues an open path from either end.
* Not yet: continuing a merged line as the same stroke, and real pen cursors.
* **Keep area for squash and stretch** (fixes #408, ADR 0115, M1): a **Keep area** checkbox
on classic, shape and motion tweens (Properties › Frame, and the Motion Editor). The tween
scales width and height geometrically, so a squash from 100 × 100 % to 200 × 50 % passes
through 141 × 71 % and keeps its area on every frame, where it used to bulge by 12.5 %.
* On a motion tween, stretch one direction and the other follows by itself; the Motion
Editor draws the curve it follows. Key it yourself at any time.
* Off by default and per tween. Tweens without it, and older files, play exactly as before.
* Every export shows it. Headless, CLI and MCP: `timeline.set_keep_area`.
* **Layer parenting** (fixes #388, ADR 0113, M7): a layer can follow another layer, as in
Animate, so a forearm moves with the upper arm while each keeps its own tweens.
* **Parenting view** in the timeline: the tree button beside **Layers** (or View › Parenting
+12 -3
View File
@@ -317,22 +317,24 @@ pub struct Progress {
pub scale: f32,
pub color: f32,
pub filters: f32,
/// The scale axes move geometrically (the tween's Keep area, ADR 0115).
pub keep_area: bool,
}
impl Progress {
/// Everything at `t`.
pub fn uniform(t: f32) -> Progress {
Progress { main: t, position: t, rotation: t, scale: t, color: t, filters: t }
Progress { main: t, position: t, rotation: t, scale: t, color: t, filters: t, keep_area: false }
}
/// `tween` at linear progress `t`.
pub fn of(tween: &crate::Tween, t: f32) -> Progress {
let main = tween.easing.apply(t);
if tween.groups.is_empty() {
return Progress::uniform(main);
return Progress { keep_area: tween.keep_area, ..Progress::uniform(main) };
}
let g = |g: crate::EaseGroup| if tween.has_own(g) { tween.ease(g).apply(t) } else { main };
Progress { main, position: g(crate::EaseGroup::Position), rotation: g(crate::EaseGroup::Rotation), scale: g(crate::EaseGroup::Scale), color: g(crate::EaseGroup::Color), filters: g(crate::EaseGroup::Filters) }
Progress { main, position: g(crate::EaseGroup::Position), rotation: g(crate::EaseGroup::Rotation), scale: g(crate::EaseGroup::Scale), color: g(crate::EaseGroup::Color), filters: g(crate::EaseGroup::Filters), keep_area: tween.keep_area }
}
}
@@ -536,6 +538,13 @@ fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(an
let (r, s) = (da.lerp(&db, pr.rotation), da.lerp(&db, pr.scale));
(d.rotation, d.skew, d.sx, d.sy) = (r.rotation, r.skew, s.sx, s.sy);
}
// Keep area (ADR 0115): each scale axis goes geometrically from its key to the next, so
// the area (sx · sy; skew and rotation don't change it) of two keys that share it stays on
// every frame, and eases smoothly from one to the other when they don't.
if pr.keep_area {
d.sx = anicraft_geom::lerp_geometric(da.sx, db.sx, pr.scale);
d.sy = anicraft_geom::lerp_geometric(da.sy, db.sy, pr.scale);
}
let mut transform = d.compose();
// An instance with a transformation point (ADR 0111) turns, scales and skews about it: the
// point travels from where the first keyframe has it to where the next does, and the
+94
View File
@@ -738,3 +738,97 @@ fn raw_stroke_runs_with_different_colour_effects_keep_them_in_a_shape_tween() {
assert_eq!(by(2).color, ColorEffect::Alpha(0.5).transform(), "the later run lost its alpha");
assert_eq!(by(1).color, ColorEffect::None.transform(), "the first run took the later run's colour");
}
/// A classic tween from scale `a` to scale `b` (with a turn and a skew at the end), eased.
fn squash_doc(a: (f32, f32), b: (f32, f32), easing: Easing, keep_area: bool) -> Document {
let at = |s: (f32, f32), rot: f32, skew: f32, x: f32| {
let mut e = shape_el(10, 0.0);
e.transform = anicraft_geom::Decomposed { tx: x, ty: 5.0, sx: s.0, sy: s.1, rotation: rot, skew }.compose();
e
};
let mut d = Document::default();
let mut k0 = Keyframe::new(0, 12);
k0.elements.push(Arc::new(at(a, 0.0, 0.0, 0.0)));
k0.tween = Some(Tween { easing, keep_area, ..Default::default() });
let mut k1 = Keyframe::new(12, 1);
k1.elements.push(Arc::new(at(b, 0.6, 0.3, 80.0)));
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
d
}
/// The area factor of a transform: its determinant.
fn area(m: &Affine) -> f32 {
m.m[0] * m.m[3] - m.m[1] * m.m[2]
}
#[test]
fn keep_area_holds_the_area_on_every_frame_of_a_classic_tween() {
// Issue #408: 100 x 100 % to 200 x 50 %. Straight lines bulge to 112.5 % halfway.
let plain = squash_doc((1.0, 1.0), (2.0, 0.5), Easing::Linear, false);
assert!((area(&evaluate(&plain, 6).items[0].transform) - 1.125).abs() < 1e-4);
for easing in [Easing::Linear, Easing::QuadIn, Easing::BackOut, Easing::ElasticOut, Easing::Classic(-60.0)] {
let d = squash_doc((1.0, 1.0), (2.0, 0.5), easing.clone(), true);
for f in 0..=12 {
let a = area(&evaluate(&d, f).items[0].transform);
assert!((a - 1.0).abs() < 2e-5, "{easing:?} frame {f}: area {a}");
}
}
// Halfway is about 141 x 71 %; the turn, the skew and the move tween as before.
let d = squash_doc((1.0, 1.0), (2.0, 0.5), Easing::Linear, true);
let (mid, was) = (evaluate(&d, 6).items[0].transform.decompose(), evaluate(&plain, 6).items[0].transform.decompose());
assert!((mid.sx - std::f32::consts::SQRT_2).abs() < 1e-4 && (mid.sy - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-4, "{mid:?}");
assert!((mid.rotation - was.rotation).abs() < 1e-5 && (mid.skew - was.skew).abs() < 1e-5 && (mid.tx - was.tx).abs() < 1e-4);
// The keys themselves show exactly as they are.
assert_eq!(evaluate(&d, 0).items[0].transform, evaluate(&plain, 0).items[0].transform);
assert_eq!(evaluate(&d, 12).items[0].transform, evaluate(&plain, 12).items[0].transform);
}
#[test]
fn keep_area_between_keys_of_different_areas_changes_it_smoothly_and_flips_fall_back() {
// 1 to 4 times the area: each frame multiplies it by the same factor.
let d = squash_doc((1.0, 1.0), (4.0, 1.0), Easing::Linear, true);
let a = |f| area(&evaluate(&d, f).items[0].transform);
for f in 0..12 {
assert!((a(f + 1) / a(f) - 4f32.powf(1.0 / 12.0)).abs() < 1e-4, "frame {f}");
}
// An axis that flips between the keys can't go geometrically: it tweens as before.
let (flip, plain) = (squash_doc((1.0, 1.0), (-1.0, 2.0), Easing::Linear, true), squash_doc((1.0, 1.0), (-1.0, 2.0), Easing::Linear, false));
for f in 0..=12 {
let (m, p) = (evaluate(&flip, f).items[0].transform, evaluate(&plain, f).items[0].transform);
assert!(m.is_finite());
let (dm, dp) = (m.decompose(), p.decompose());
// Whichever axis the decomposition gives the flip to, the other one went geometrically
// or the same; nothing blows up and the ends agree.
if f == 0 || f == 12 {
assert_eq!(m, p, "frame {f}");
}
assert!(dm.sx.is_finite() && dm.sy.is_finite() && dp.sx.is_finite());
}
}
#[test]
fn keep_area_off_is_bit_exact_with_a_tween_that_never_had_it_and_files_stay_small() {
// Off (the default) takes the same code path as before: every frame identical, bit by bit.
for easing in [Easing::Linear, Easing::QuadInOut, Easing::BounceOut] {
let off = squash_doc((1.0, 1.5), (2.5, 0.25), easing.clone(), false);
let mut old = off.clone();
// A file from before Keep area has no such key: it reads as off.
let json = serde_json::to_string(&old).unwrap();
assert!(!json.contains("keep_area"), "off isn't written");
old = serde_json::from_str(&json).unwrap();
for f in 0..=12 {
let (x, y) = (evaluate(&off, f).items[0].transform, evaluate(&old, f).items[0].transform);
assert_eq!(x.m.map(f32::to_bits), y.m.map(f32::to_bits), "{easing:?} frame {f}");
if (1..12).contains(&f) {
let k = &off.scenes[0].timeline.layers[0].keyframes;
let d = (k[0].elements[0].transform.decompose(), k[1].elements[0].transform.decompose());
let t = easing.apply(f as f32 / 12.0);
assert_eq!(x.m.map(f32::to_bits), d.0.lerp(&d.1, t).compose().m.map(f32::to_bits), "the straight lerp of before, frame {f}");
}
}
}
// On round-trips.
let on = squash_doc((1.0, 1.0), (2.0, 0.5), Easing::Linear, true);
let back: Document = serde_json::from_str(&serde_json::to_string(&on).unwrap()).unwrap();
assert!(back.scenes[0].timeline.layers[0].keyframes[0].tween.as_ref().unwrap().keep_area);
}
+4
View File
@@ -1190,6 +1190,10 @@ pub struct Tween {
/// properties.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub groups: Vec<(EaseGroup, Easing)>,
/// Keep area (ADR 0115): the two scale axes move geometrically instead of in straight
/// lines, so squash and stretch between keys of one area keeps that area on every frame.
#[serde(default, skip_serializing_if = "is_false")]
pub keep_area: bool,
}
impl Tween {
+147 -5
View File
@@ -426,6 +426,12 @@ impl Track {
/// The value at `frame` (fractional frames sample the curve between frames): the first
/// key's value before it, the last key's after it, the segment's ease in between.
pub fn value_at(&self, frame: f32) -> Option<f32> {
self.sample(frame, false)
}
/// [`Track::value_at`], going geometrically between keys when `geometric` (a scale track
/// of a tween that keeps area, ADR 0115) instead of in a straight line.
pub fn sample(&self, frame: f32, geometric: bool) -> Option<f32> {
let first = self.keys.first()?;
let last = self.keys.last()?;
if !frame.is_finite() || frame <= first.frame as f32 {
@@ -444,6 +450,9 @@ impl Track {
}
let span = (b.frame - a.frame).max(1) as f32;
let t = a.ease.apply((frame - a.frame as f32) / span);
if geometric {
return Some(anicraft_geom::lerp_geometric(a.value, b.value, t));
}
Some(a.value + (b.value - a.value) * t)
}
@@ -546,6 +555,10 @@ pub struct MotionTween {
/// Anchors between the ends pinned to frames (ADR 0049), by frame; both frames and anchors
/// increase. Files from before pins have none: only the ends are pinned.
pub pins: Vec<Pin>,
/// Keep area (ADR 0115): the scale curves go geometrically between their keys, and a
/// scale axis without keys of its own follows the other inversely, so the area the object
/// has on the span's first frame stays. See [`MotionTween::scale_at`].
pub keep_area: bool,
}
/// A [`MotionTween`] as files hold it.
@@ -563,20 +576,22 @@ struct TweenFile {
orient: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pins: Vec<Pin>,
#[serde(default, skip_serializing_if = "is_false")]
keep_area: bool,
}
impl From<TweenFile> for MotionTween {
fn from(f: TweenFile) -> MotionTween {
let mut tracks = f.tracks;
tracks.extend(f.filter_tracks);
MotionTween { target: f.target, tracks, path: f.path, orient: f.orient, pins: f.pins }
MotionTween { target: f.target, tracks, path: f.path, orient: f.orient, pins: f.pins, keep_area: f.keep_area }
}
}
impl From<MotionTween> for TweenFile {
fn from(m: MotionTween) -> TweenFile {
let (filter_tracks, tracks) = m.tracks.into_iter().partition(|t| t.property.is_filter());
TweenFile { target: m.target, tracks, filter_tracks, path: m.path, orient: m.orient, pins: m.pins }
TweenFile { target: m.target, tracks, filter_tracks, path: m.path, orient: m.orient, pins: m.pins, keep_area: m.keep_area }
}
}
@@ -732,7 +747,7 @@ impl OnPath<'_> {
impl MotionTween {
pub fn new(target: ElementId) -> MotionTween {
MotionTween { target, tracks: Vec::new(), path: None, orient: false, pins: Vec::new() }
MotionTween { target, tracks: Vec::new(), path: None, orient: false, pins: Vec::new(), keep_area: false }
}
/// The first and last frames holding an X or Y key.
@@ -1178,9 +1193,66 @@ impl MotionTween {
out.set(t.property, v);
}
}
if self.keep_area {
let (sx, sy) = self.scale_at(base, frame);
out.set(Property::ScaleX, sx);
out.set(Property::ScaleY, sy);
}
out
}
/// Scale X and Y (percent) at `frame`, as the tween shows them. Without Keep area these
/// are the two curves. With it (ADR 0115):
///
/// * each curve goes geometrically between its keys, so keys of one area keep it on the
/// frames between them;
/// * an axis that isn't animated (no track, or fewer than two keys) follows the animated
/// one inversely, holding the area of the span's first frame: stretch one axis and the
/// other squashes by itself.
pub fn scale_at(&self, base: &Props, frame: f32) -> (f32, f32) {
let geo = self.keep_area;
let v = |p: Property, f: f32| self.track(p).and_then(|t| t.sample(f, geo)).unwrap_or(base.get(p));
let (x, y) = (v(Property::ScaleX, frame), v(Property::ScaleY, frame));
if !geo {
return (x, y);
}
let animated = |p: Property| self.track(p).is_some_and(|t| t.keys.len() >= 2);
// `follower` at its own (constant) value times how far the driver has shrunk.
let derived = |driver: Property, now: f32, follower: f32| {
let start = v(driver, 0.0);
let d = follower * start / now;
if now != 0.0 && d.is_finite() { Property::ScaleX.clamp(d) } else { follower }
};
match (animated(Property::ScaleX), animated(Property::ScaleY)) {
(true, false) => (x, derived(Property::ScaleX, x, y)),
(false, true) => (derived(Property::ScaleY, y, x), y),
_ => (x, y),
}
}
/// Property `p` at `frame` as the tween shows it: its curve (the object's own value where
/// it has none), or for a scale axis of a tween that keeps area the curve
/// [`MotionTween::scale_at`] derives. What the Motion Editor draws.
pub fn shown_value(&self, base: &Props, p: Property, frame: f32) -> f32 {
match p {
Property::ScaleX if self.keep_area => self.scale_at(base, frame).0,
Property::ScaleY if self.keep_area => self.scale_at(base, frame).1,
p => self.track(p).and_then(|t| t.value_at(frame)).unwrap_or(base.get(p)),
}
}
/// Whether Keep area derives `p` from the other scale axis (it has no curve of its own to
/// edit while the other axis is animated).
pub fn is_derived(&self, p: Property) -> bool {
let animated = |p: Property| self.track(p).is_some_and(|t| t.keys.len() >= 2);
self.keep_area
&& match p {
Property::ScaleX => !animated(Property::ScaleX) && animated(Property::ScaleY),
Property::ScaleY => !animated(Property::ScaleY) && animated(Property::ScaleX),
_ => false,
}
}
/// The target as it looks `frame` frames into the span. Untracked properties keep the
/// base's exact transform and colour effect.
pub fn apply(&self, base: &Element, frame: f32) -> Element {
@@ -1311,14 +1383,15 @@ impl MotionTween {
.tracks
.iter()
.filter_map(|t| {
let v = t.value_at(frame as f32)?;
// A scale curve of a tween that keeps area is cut where it shows (ADR 0115).
let v = t.sample(frame as f32, self.keep_area && matches!(t.property, Property::ScaleX | Property::ScaleY))?;
let ease = t.segment_at(frame).and_then(|i| t.keys.get(i)).map_or(Easing::Linear, |k| k.ease.clone());
let mut keys = vec![PropertyKey { frame: 0, value: v, ease }];
keys.extend(t.keys.iter().filter(|k| k.frame > frame).map(|k| PropertyKey { frame: k.frame - frame, ..k.clone() }));
Some(Track { property: t.property, keys })
})
.collect();
let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient, pins: Vec::new() };
let mut tail = MotionTween { target: self.target, tracks, path: None, orient: self.orient, pins: Vec::new(), keep_area: self.keep_area };
let Some(op) = self.on_path(base) else { return tail };
let f = frame as f32;
match op.walk().tail(op.distance(f)) {
@@ -1411,6 +1484,75 @@ mod tests {
Track { property: p, keys: keys.iter().map(|(frame, value, ease)| PropertyKey { frame: *frame, value: *value, ease: ease.clone() }).collect() }
}
/// Scale X and Y (percent) of `m`'s target at `frame`, and their product.
fn scale(m: &MotionTween, base: &Element, frame: f32) -> (f32, f32, f32) {
let d = m.apply(base, frame).transform.decompose();
(d.sx * 100.0, d.sy * 100.0, d.sx * d.sy)
}
#[test]
fn keep_area_goes_geometrically_between_scale_keys() {
// Issue #408 on a motion tween: both axes keyed, 100 x 100 % to 200 x 50 % and back.
let base = el(1, 0.0, 0.0);
let mut m = MotionTween::new(ElementId(1));
m.tracks = vec![
track(Property::ScaleX, &[(0, 100.0, Easing::QuadOut), (10, 200.0, Easing::BackIn), (20, 100.0, Easing::Linear)]),
track(Property::ScaleY, &[(0, 100.0, Easing::QuadOut), (10, 50.0, Easing::BackIn), (20, 100.0, Easing::Linear)]),
];
assert!((scale(&m, &base, 5.0).2 - 1.0).abs() > 0.05, "straight lines bulge");
let before: Vec<_> = (0..=20).map(|f| m.apply(&base, f as f32).transform.m.map(f32::to_bits)).collect();
m.keep_area = true;
for f in 0..=40 {
let (x, y, a) = scale(&m, &base, f as f32 / 2.0);
assert!((a - 1.0).abs() < 2e-5, "frame {}: {x} x {y} = {a}", f as f32 / 2.0);
}
// The keys show as they are, and the option round-trips through a file.
assert_eq!(scale(&m, &base, 10.0).0, 200.0);
let back: MotionTween = serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap();
assert_eq!(back, m);
// Off again: bit for bit what it was, and nothing about it in the file.
m.keep_area = false;
assert_eq!((0..=20).map(|f| m.apply(&base, f as f32).transform.m.map(f32::to_bits)).collect::<Vec<_>>(), before);
assert!(!serde_json::to_string(&m).unwrap().contains("keep_area"));
}
#[test]
fn keep_area_makes_an_unkeyed_scale_axis_follow_the_other_inversely() {
// Only Scale X is keyed: Scale Y is derived so the first frame's area (150 % x 80 %)
// stays, whatever the ease does (Back overshoots).
let mut base = el(1, 0.0, 0.0);
base.transform = Decomposed { tx: 3.0, ty: 4.0, sx: 1.5, sy: 0.8, rotation: 0.4, skew: 0.0 }.compose();
let mut m = MotionTween::new(ElementId(1));
m.tracks = vec![track(Property::ScaleX, &[(0, 150.0, Easing::BackOut), (8, 300.0, Easing::Linear), (16, 60.0, Easing::Linear)])];
m.keep_area = true;
let props = Props::of(&base);
assert!(m.is_derived(Property::ScaleY) && !m.is_derived(Property::ScaleX));
for f in 0..=32 {
let f = f as f32 / 2.0;
let (x, y, a) = scale(&m, &base, f);
assert!((a - 1.2).abs() < 1e-4, "frame {f}: {x} x {y} = {a}");
// The Motion Editor draws the derived curve from the same numbers.
assert!((m.shown_value(&props, Property::ScaleY, f) - y).abs() < 1e-2, "frame {f}");
}
assert!((scale(&m, &base, 8.0).1 - 40.0).abs() < 1e-3, "twice as wide, half as tall");
// Cutting the span keeps what shows on both sides.
let tail = m.split_at(&props, 10);
let tail_base = m.apply(&base, 10.0);
for f in 10..=16 {
let (a, b) = (scale(&m, &base, f as f32), scale(&tail, &tail_base, (f - 10) as f32));
assert!((a.0 - b.0).abs() < 1e-2 && (a.1 - b.1).abs() < 1e-2, "frame {f}: {a:?} vs {b:?}");
}
// Y keyed too: both curves are the user's, nothing is derived.
m.tracks.push(track(Property::ScaleY, &[(0, 80.0, Easing::Linear), (16, 80.0, Easing::Linear)]));
assert!(!m.is_derived(Property::ScaleY));
assert!((scale(&m, &base, 8.0).1 - 80.0).abs() < 1e-3);
// A driver through zero or a flip never divides by zero.
m.tracks = vec![track(Property::ScaleX, &[(0, 100.0, Easing::Linear), (10, -100.0, Easing::Linear)])];
for f in 0..=10 {
assert!(m.apply(&base, f as f32).transform.is_finite(), "frame {f}");
}
}
#[test]
fn a_track_holds_before_and_after_and_eases_between() {
let t = track(Property::X, &[(4, 100.0, Easing::Linear), (8, 200.0, Easing::QuadIn), (12, 0.0, Easing::Linear)]);
+1 -1
View File
@@ -226,7 +226,7 @@ impl MotionTween {
keys.truncate(super::MAX_KEYS);
tracks.push(Track { property: p, keys });
}
Some(MotionTween { target: self.target, tracks, path: None, orient: self.orient, pins: Vec::new() })
Some(MotionTween { target: self.target, tracks, path: None, orient: self.orient, pins: Vec::new(), keep_area: self.keep_area })
}
}
+7 -1
View File
@@ -115,6 +115,12 @@ pub(crate) fn finish_edit(s: &mut Session, e: MotionEdit) {
if !d.is_finite() || d.abs() <= 1e-4 {
continue;
}
// Keep area (ADR 0115): a scale axis that follows the other has no curve of its own. A
// tool that drags the other axis puts this one back where the gesture found it (its
// resting value), which isn't an edit of it: it goes on following.
if m.is_derived(p) && (now_dec.get(p) - m.track(p).and_then(|t| t.value_at(e.offset as f32)).unwrap_or(base_props.get(p))).abs() <= 1e-3 {
continue;
}
let v = was.get(p) + d;
if e.offset == 0 && m.track(p).is_none() {
new_base.set(p, v);
@@ -886,5 +892,5 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let anchors: Vec<[f32; 2]> = m.path.clone().or_else(|| base.and_then(|b| m.path_from_tracks(&b))).map(|p| p.anchors().into_iter().map(|(_, q)| [q.x, q.y]).collect()).unwrap_or_default();
// And those tied to frames, ends included (ADR 0049).
let pins = base.map_or(Value::Array(Vec::new()), |b| pins_json(m, kf.start, &b));
Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path, "anchors": anchors, "pins": pins, "orient": m.orient}))
Ok(json!({"layer": lid.0, "start": kf.start, "frames": kf.duration, "target": m.target.0, "tracks": tracks, "values": values, "position": position, "path": path, "anchors": anchors, "pins": pins, "orient": m.orient, "keep_area": m.keep_area}))
}
+105
View File
@@ -32,6 +32,15 @@ pub fn specs() -> Vec<CommandSpec> {
c("path.add_point", "Add Anchor Point", "", None, "{id, x, y, slop?}", true, add_point),
c("path.delete_points", "Delete Anchor Points", "", None, "{id, cmds: [..]}", true, delete_points),
c("path.convert_point", "Convert Anchor Point", "", None, "{id, cmd, smooth: bool}", true, convert_point),
c(
"path.extend",
"Continue Path",
"",
None,
"{id, d: SVG path data (stage space) of the new piece, drawn away from the end it continues, end?: \"end\" | \"start\" (default end), close?: bool}: continues an open path (one subpath, not closed) from one of its ends, as the Pen does (ADR 0115). The piece joins the path's own end point (its M is where the pen started and isn't kept); with close the path is closed after it",
true,
extend,
),
]
}
@@ -261,3 +270,99 @@ fn convert_point(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"changed": changed}))
})
}
/// `cmds` (a move and segments, one open subpath) drawn the other way round.
fn reversed_open(cmds: &[PathCmd]) -> Vec<PathCmd> {
let mut out = Vec::with_capacity(cmds.len());
let mut it = cmds.iter().rev().peekable();
if let Some(end) = cmds.iter().rev().find_map(|c| match *c {
PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => Some(p),
PathCmd::Close => None,
}) {
out.push(PathCmd::MoveTo(end));
}
while let Some(c) = it.next() {
// Each segment now ends where it started: the anchor of the command before it.
let Some(start) = it.peek().and_then(|prev| match **prev {
PathCmd::MoveTo(p) | PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => Some(p),
PathCmd::Close => None,
}) else {
break;
};
match *c {
PathCmd::LineTo(_) => out.push(PathCmd::LineTo(start)),
PathCmd::QuadTo(q, _) => out.push(PathCmd::QuadTo(q, start)),
PathCmd::CubicTo(c1, c2, _) => out.push(PathCmd::CubicTo(c2, c1, start)),
PathCmd::MoveTo(_) | PathCmd::Close => {}
}
}
out
}
/// Continue Path (ADR 0115): the Pen picks up an open path at one of its ends and draws on.
fn extend(s: &mut Session, p: &Value) -> Result<Value> {
let d = str_req(p, "d")?;
if d.len() > 4_000_000 {
return Err(EngineError::Param("param 'd' is too long".into()));
}
let piece = anicraft_geom::svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?;
let at_start = match opt_str(p, "end")?.unwrap_or("end") {
"end" => false,
"start" => true,
other => return Err(EngineError::Param(format!("param 'end' must be \"end\" or \"start\", not '{other}'"))),
};
let close = opt_bool(p, "close")?.unwrap_or(false);
let one_open = |path: &Path| matches!(path.cmds.first(), Some(PathCmd::MoveTo(_))) && !path.cmds.iter().skip(1).any(|c| matches!(c, PathCmd::MoveTo(_) | PathCmd::Close));
if !one_open(&piece) || piece.cmds.len() < 2 {
return Err(EngineError::Param("param 'd' must be one open piece: a move, then at least one segment".into()));
}
edit_shape(s, p, |sh, m| {
let inv = m.inverse().ok_or_else(|| EngineError::State("the shape is scaled to zero".into()))?;
let path = Arc::make_mut(&mut sh.path);
if !one_open(path) || path.cmds.len() < 2 {
return Err(EngineError::State("only an open path can be continued (this one is closed or has several parts)".into()));
}
if path.cmds.len() + piece.cmds.len() > MAX_CMDS {
return Err(EngineError::Param(format!("path has more than {MAX_CMDS} commands")));
}
let local = piece.transformed(&inv);
if !local.cmds.iter().all(|c| match *c {
PathCmd::MoveTo(a) | PathCmd::LineTo(a) => a.is_finite(),
PathCmd::QuadTo(a, b) => a.is_finite() && b.is_finite(),
PathCmd::CubicTo(a, b, c) => a.is_finite() && b.is_finite() && c.is_finite(),
PathCmd::Close => true,
}) {
return Err(EngineError::Param("the piece is too large".into()));
}
let before = path.clone();
if at_start {
// The piece was drawn away from the start: turned round, it arrives there, and
// the path goes on from its own first point as it always did.
let mut cmds = reversed_open(&local.cmds);
let Some(PathCmd::MoveTo(first)) = path.cmds.first().copied() else { return Err(EngineError::State("the path has no start".into())) };
if let Some(PathCmd::LineTo(a) | PathCmd::QuadTo(_, a) | PathCmd::CubicTo(_, _, a)) = cmds.last_mut() {
*a = first;
}
cmds.extend(path.cmds.iter().skip(1).copied());
path.cmds = cmds;
} else {
path.cmds.extend(local.cmds.iter().skip(1).copied());
}
if close {
// A piece that ends on the path's other end (the Pen clicked it) meets it exactly.
let start = path.cmds.first().and_then(|c| if let PathCmd::MoveTo(a) = *c { Some(a) } else { None });
if let (Some(start), Some(PathCmd::LineTo(a) | PathCmd::QuadTo(_, a) | PathCmd::CubicTo(_, _, a))) = (start, path.cmds.last_mut())
&& m.apply(*a).distance(m.apply(start)) <= 0.01
{
*a = start;
}
path.cmds.push(PathCmd::Close);
path.close_explicitly();
}
if let Err(e) = check_path(path) {
*path = before;
return Err(e);
}
Ok(json!({"cmds": path.cmds.len(), "closed": close}))
})
}
+27 -1
View File
@@ -22,6 +22,15 @@ pub fn specs() -> Vec<CommandSpec> {
c("timeline.remove_tween", "Remove Tween", "Insert", None, "{layer?, frame?} (a motion tween leaves its object as it is on the first frame)", true, remove_tween),
c("timeline.set_easing", "Set Tween Easing", "", None, "{easing: a preset name (Linear, QuadIn … ElasticInOut) | {classic: -100..100} | {bezier: [x1, y1, x2, y2]} | {custom: {points: [..]} | [[x, y], ..]} | {saved: name} | {plugin: id, ease: id} (an ease plug-in's; the tween keeps its sampled curve), group?: all|position|rotation|scale|color|filters (classic tweens: that property group's own ease), layer?, frame?}", true, set_easing),
c("timeline.set_orient", "Orient to Path", "", None, "{orient: bool, layer?, frame?}", true, set_orient),
c(
"timeline.set_keep_area",
"Keep Area",
"",
None,
"{keep_area: bool, layer?, frame?}: squash and stretch that keeps the object's area (ADR 0115). The span's tween (classic, shape or motion) moves scale X and Y geometrically between keys instead of in straight lines, so keys of one area keep it on every frame; on a motion tween a scale axis without keys of its own follows the other inversely. Off by default",
true,
set_keep_area,
),
c("timeline.set_label", "Frame Label", "", None, "{label, layer?, frame?}", true, set_label),
c("timeline.goto", "Go to Frame", "", None, "{frame}", false, goto),
c("timeline.next_frame", "Next Frame", "Control", Some("."), "{}", false, |s, _| step(s, 1)),
@@ -130,6 +139,22 @@ fn set_orient(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"orient": orient}))
}
/// Keep area (ADR 0115): the span's tween, of any kind, scales geometrically.
fn set_keep_area(s: &mut Session, p: &Value) -> Result<Value> {
let on = opt_bool(p, "keep_area")?.ok_or_else(|| EngineError::Param("param 'keep_area' (true or false) is required".into()))?;
let k = keyframe_mut(s, p)?;
let kind = if let Some(m) = k.motion.as_mut() {
m.keep_area = on;
"motion"
} else if let Some(t) = k.tween.as_mut() {
t.keep_area = on;
if t.kind == TweenKind::Shape { "shape" } else { "classic" }
} else {
return Err(EngineError::State("this span has no tween; create one first".into()));
};
Ok(json!({"keep_area": on, "tween": kind}))
}
fn set_layer_type(s: &mut Session, p: &Value) -> Result<Value> {
let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId);
set_type(s, id, str_req(p, "type")?)?;
@@ -713,11 +738,12 @@ fn tween_of_kind(s: &mut Session, p: &Value, kind: TweenKind) -> Result<Value> {
// tween keeps its property groups' eases (a shape tween has one ease, as in Animate).
let easing = given.unwrap_or_else(|| k.tween.as_ref().map(|t| t.easing.clone()).unwrap_or_default());
let orient = k.tween.as_ref().is_some_and(|t| t.orient);
let keep_area = k.tween.as_ref().is_some_and(|t| t.keep_area);
let groups = if kind == TweenKind::Classic { k.tween.as_ref().map(|t| t.groups.clone()).unwrap_or_default() } else { Vec::new() };
// It replaces a motion tween, keeping the object as it is on the first frame.
crate::cmds_motion::bake_first_frame(k);
let label = easing.label();
k.tween = Some(Tween { easing, kind, orient, groups });
k.tween = Some(Tween { easing, kind, orient, groups, keep_area });
// Shape hints only mean something to a shape tween.
if kind != TweenKind::Shape {
k.hints.clear();
+111
View File
@@ -0,0 +1,111 @@
//! Keep area (ADR 0115, issue #408) through the command registry: classic and motion tweens,
//! the keys a transform records while an axis follows, undo and the file round trip.
use super::*;
use anicraft_doc::Property;
use serde_json::json;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
match s.execute(id, &p) {
Ok(v) => v,
Err(e) => panic!("{id} {p}: {e}"),
}
}
/// Scale X, scale Y and their product for the one element at `frame`.
fn scale(s: &mut Session, frame: u32) -> (f32, f32, f32) {
s.set_frame(frame);
let d = s.visible_elements().first().map(|e| e.transform.decompose()).expect("an element");
(d.sx, d.sy, d.sx * d.sy)
}
/// A square that a classic tween takes from 100 x 100 % to 200 x 50 % over 12 frames.
fn squashed() -> Session {
let mut s = Session::default();
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 40, "h": 40}));
run(&mut s, "timeline.insert_keyframe", json!({"frame": 12}));
s.set_frame(12);
run(&mut s, "edit.select_all", json!({}));
run(&mut s, "element.set_transform", json!({"sx": 2.0, "sy": 0.5}));
s.set_frame(0);
run(&mut s, "timeline.create_tween", json!({}));
s
}
#[test]
fn a_classic_tween_keeps_its_area_on_every_frame_and_off_is_what_it_was() {
let mut s = squashed();
let before: Vec<_> = (0..=12).map(|f| scale(&mut s, f)).collect();
assert!((before[6].2 - 1.125).abs() < 1e-4, "the bulge of issue #408: {:?}", before[6]);
s.set_frame(3);
assert_eq!(run(&mut s, "timeline.set_keep_area", json!({"keep_area": true})), json!({"keep_area": true, "tween": "classic"}));
for f in 0..=12 {
let (x, y, a) = scale(&mut s, f);
assert!((a - 1.0).abs() < 2e-5, "frame {f}: {x} x {y} = {a}");
}
let mid = scale(&mut s, 6);
assert!((mid.0 - 2f32.sqrt()).abs() < 1e-4 && (mid.1 - 0.5f32.sqrt()).abs() < 1e-4, "{mid:?}");
// It survives a change of ease and of kind, and the file.
run(&mut s, "timeline.set_easing", json!({"easing": "QuadIn", "frame": 0}));
run(&mut s, "timeline.create_shape_tween", json!({"frame": 0}));
run(&mut s, "timeline.create_tween", json!({"frame": 0}));
assert!((scale(&mut s, 5).2 - 1.0).abs() < 2e-5);
let back = format::from_json(&format::to_json(&s.doc).expect("save")).expect("load");
assert!(back.scenes[0].timeline.layers[0].keyframes[0].tween.as_ref().is_some_and(|t| t.keep_area));
// One undo step each; off again is bit for bit the tween of before.
run(&mut s, "timeline.set_easing", json!({"easing": "Linear", "frame": 0}));
run(&mut s, "timeline.set_keep_area", json!({"keep_area": false, "frame": 0}));
assert_eq!((0..=12).map(|f| scale(&mut s, f)).collect::<Vec<_>>(), before);
assert!(!format::to_json(&s.doc).expect("save").contains("keep_area"));
run(&mut s, "edit.undo", json!({}));
assert!((scale(&mut s, 6).2 - 1.0).abs() < 2e-5, "undo puts Keep area back");
}
#[test]
fn keep_area_needs_a_tween_and_a_true_or_false() {
let mut s = Session::default();
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 40, "h": 40}));
assert!(s.execute("timeline.set_keep_area", &json!({"keep_area": true})).is_err(), "no tween on the span");
run(&mut s, "timeline.create_motion_tween", json!({}));
assert!(s.execute("timeline.set_keep_area", &json!({})).is_err());
assert!(s.execute("timeline.set_keep_area", &json!({"keep_area": "yes"})).is_err());
assert_eq!(run(&mut s, "timeline.set_keep_area", json!({"keep_area": true}))["tween"], "motion");
assert_eq!(run(&mut s, "motion.info", json!({}))["keep_area"], true);
}
#[test]
fn on_a_motion_tween_the_other_axis_squashes_by_itself_until_it_is_keyed() {
let mut s = Session::default();
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 40, "h": 40}));
run(&mut s, "timeline.create_motion_tween", json!({}));
run(&mut s, "timeline.set_keep_area", json!({"keep_area": true}));
// Stretch the width at frame 12: only Scale X is keyed, and the height follows.
s.set_frame(12);
run(&mut s, "element.set_transform", json!({"sx": 2.0}));
let m = |s: &Session| s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.motion.clone()).expect("motion tween");
assert!(m(&s).track(Property::ScaleY).is_none());
for f in 0..=23 {
let (x, y, a) = scale(&mut s, f);
assert!((a - 1.0).abs() < 1e-4, "frame {f}: {x} x {y} = {a}");
}
assert!((scale(&mut s, 12).1 - 0.5).abs() < 1e-4);
// A transform handle dragged on: each step sets the width and puts the height back where
// the drag found it (100 %). That isn't an edit of the height, which goes on following.
s.set_frame(12);
run(&mut s, "element.set_transform", json!({"sx": 2.5, "sy": 1.0}));
assert!(m(&s).track(Property::ScaleY).is_none(), "{:?}", m(&s).tracks);
let at = scale(&mut s, 12);
assert!((at.0 - 2.5).abs() < 1e-4 && (at.1 - 0.4).abs() < 1e-4, "{at:?}");
// Setting the height to something of its own keys it: both curves are the animator's now,
// geometric between their keys.
s.set_frame(12);
run(&mut s, "element.set_transform", json!({"sy": 0.8}));
assert!(m(&s).track(Property::ScaleY).is_some());
let at = scale(&mut s, 12);
assert!((at.0 - 2.5).abs() < 1e-4 && (at.1 - 0.8).abs() < 1e-4, "{at:?}");
let mid = scale(&mut s, 6);
assert!((mid.0 - 2.5f32.sqrt()).abs() < 1e-3 && (mid.1 - 0.8f32.sqrt()).abs() < 1e-3, "{mid:?}");
// The file keeps it.
let back = format::from_json(&format::to_json(&s.doc).expect("save")).expect("load");
assert!(back.scenes[0].timeline.layers[0].keyframes[0].motion.as_ref().is_some_and(|m| m.keep_area));
}
+3 -1
View File
@@ -1277,7 +1277,7 @@ impl Session {
.map(|l| {
json!({
"id": l.id.0, "name": l.name, "visible": l.visible, "locked": l.locked, "volume": l.volume, "muted": l.muted,
"keyframes": l.keyframes.iter().map(|k| json!({"start": k.start, "duration": k.duration, "elements": k.elements.len(), "tween": k.tween.as_ref().map(|t| t.easing.label()), "motion": k.motion.as_ref().map(|m| m.tracks.iter().map(|t| t.property.key()).collect::<Vec<_>>()), "sound": k.sound.as_ref().map(|f| json!({"sound": f.sound.0, "sync": f.sync.key(), "repeat": f.repeat, "loop": f.looping, "effect": f.effect.key()})), "script": k.script.as_ref().map(anicraft_doc::FrameScript::describe)})).collect::<Vec<_>>()
"keyframes": l.keyframes.iter().map(|k| json!({"start": k.start, "duration": k.duration, "elements": k.elements.len(), "tween": k.tween.as_ref().map(|t| t.easing.label()), "motion": k.motion.as_ref().map(|m| m.tracks.iter().map(|t| t.property.key()).collect::<Vec<_>>()), "keep_area": k.motion.as_ref().map_or(k.tween.as_ref().is_some_and(|t| t.keep_area), |m| m.keep_area), "sound": k.sound.as_ref().map(|f| json!({"sound": f.sound.0, "sync": f.sync.key(), "repeat": f.repeat, "loop": f.looping, "effect": f.effect.key()})), "script": k.script.as_ref().map(anicraft_doc::FrameScript::describe)})).collect::<Vec<_>>()
})
})
.collect();
@@ -1376,6 +1376,8 @@ mod tests;
#[cfg(test)]
mod parenting_tests;
#[cfg(test)]
mod keep_area_tests;
#[cfg(test)]
mod motion_tests;
#[cfg(test)]
+47
View File
@@ -2574,3 +2574,50 @@ fn bevel_and_gradient_filters_render_save_and_export() {
// Lottie reports them, as it does every filter.
assert!(anicraft_render::lottie::to_lottie(&s.doc, "f", 0, 0, false).report.keys().any(|k| k.starts_with("filters")));
}
/// The stage-space anchors of shape `id`.
fn stage_anchors(s: &Session, id: u64) -> Vec<(f32, f32)> {
let p = shape_path(s, id);
(0..p.cmds.len()).filter(|&c| p.point(c, 0).is_some()).map(|c| stage_anchor(s, id, c)).map(|q| (q.x.round(), q.y.round())).collect()
}
#[test]
fn path_extend_continues_an_open_path_from_either_end_and_closes_it() {
// ADR 0115: the Pen picks an open drawing object up at an end and draws on.
let mut s = Session::default();
run(&mut s, "draw.path", json!({"d": "M0 0 L100 0 L100 50", "object": true}));
let id = s.selection.ids().next().unwrap().0;
// Moved and turned, so stage space isn't the shape's own.
run(&mut s, "element.translate", json!({"dx": 20, "dy": 10}));
assert_eq!(stage_anchors(&s, id), [(20.0, 10.0), (120.0, 10.0), (120.0, 60.0)]);
// From its end: the piece's start is the end point, and its segments are appended.
let v = run(&mut s, "path.extend", json!({"id": id, "d": "M120 60 C120 90 90 110 60 110 L20 110"}));
assert_eq!(v["closed"], false);
assert_eq!(stage_anchors(&s, id), [(20.0, 10.0), (120.0, 10.0), (120.0, 60.0), (60.0, 110.0), (20.0, 110.0)]);
assert!(matches!(shape_path(&s, id).cmds[3], anicraft_geom::PathCmd::CubicTo(..)), "the curve is kept");
// From its start: drawn away from it, joined so the path keeps its direction.
run(&mut s, "path.extend", json!({"id": id, "d": "M20 10 L-30 10 C-30 30 -30 50 -30 60", "end": "start"}));
assert_eq!(stage_anchors(&s, id), [(-30.0, 60.0), (-30.0, 10.0), (20.0, 10.0), (120.0, 10.0), (120.0, 60.0), (60.0, 110.0), (20.0, 110.0)]);
assert!(matches!(shape_path(&s, id).cmds[1], anicraft_geom::PathCmd::CubicTo(..)));
// One undo step each.
run(&mut s, "edit.undo", json!({}));
assert_eq!(stage_anchors(&s, id).len(), 5);
// Onto its own other end, closing it.
let v = run(&mut s, "path.extend", json!({"id": id, "d": "M20 110 L20 10", "close": true}));
assert_eq!(v["closed"], true);
let p = shape_path(&s, id);
assert!(matches!(p.cmds.last(), Some(anicraft_geom::PathCmd::Close)));
assert_eq!(p.editable_anchors().len(), 5, "the closing point is the start, once");
// A closed path has no end to continue, and hostile pieces are refused without a change.
let before = shape_path(&s, id);
for bad in [json!({"id": id, "d": "M0 0 L10 10"}), json!({"id": id, "d": "L10 10"}), json!({"id": id, "d": "M0 0"}), json!({"id": id, "d": "M0 0 L1 1 M5 5 L6 6"}), json!({"id": id, "d": "M0 0 L10 10", "end": "middle"}), json!({"d": "M0 0 L10 10"}), json!({"id": id, "d": 5})] {
assert!(s.execute("path.extend", &bad).is_err(), "{bad}");
}
assert_eq!(shape_path(&s, id), before);
let mut s = Session::default();
run(&mut s, "draw.path", json!({"d": "M0 0 L100 0", "object": true}));
let id = s.selection.ids().next().unwrap().0;
assert!(s.execute("path.extend", &json!({"id": id, "d": "M100 0 L1e30 0"})).is_err(), "too large");
assert!(s.execute("path.extend", &json!({"id": id, "d": "M100 0 L100 0 Z"})).is_err(), "a closed piece");
assert_eq!(stage_anchors(&s, id), [(0.0, 0.0), (100.0, 0.0)]);
}
+42
View File
@@ -171,10 +171,52 @@ pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
a + (b - a) * t
}
/// Geometric interpolation of scalars: `a · (b / a)^t`, the straight line between them on a
/// logarithmic scale, so equal steps of `t` multiply by equal factors. Two scale axes moved
/// this way keep the product of their ends on the way (ADR 0115). It needs both ends on the
/// same side of zero; ends that differ in sign, a zero end or anything not finite fall back
/// to [`lerp`]. Exactly `a` at 0 and `b` at 1; outside 0..=1 it goes on in the same ratio and
/// never crosses zero.
pub fn lerp_geometric(a: f32, b: f32, t: f32) -> f32 {
if t == 0.0 {
return a;
}
if t == 1.0 {
return b;
}
if a.is_finite() && b.is_finite() && t.is_finite() && a * b > 0.0 {
let v = a * (b / a).powf(t);
if v.is_finite() {
return v;
}
}
lerp(a, b, t)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn geometric_lerp_keeps_the_product_of_two_axes() {
// 100 % x 100 % to 200 % x 50 %: the halfway frame is about 141 % x 71 %.
let (x, y) = (lerp_geometric(1.0, 2.0, 0.5), lerp_geometric(1.0, 0.5, 0.5));
assert!((x - std::f32::consts::SQRT_2).abs() < 1e-6 && (y - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-6, "{x} {y}");
for i in -10..=20 {
let t = i as f32 / 10.0;
let p = lerp_geometric(3.0, 0.75, t) * lerp_geometric(0.5, 2.0, t);
assert!((p - 1.5).abs() < 1e-5, "t {t}: {p}");
}
// The ends exactly; a flipped axis keeps its sign.
assert_eq!((lerp_geometric(3.0, 7.0, 0.0), lerp_geometric(3.0, 7.0, 1.0)), (3.0, 7.0));
assert!((lerp_geometric(-1.0, -4.0, 0.5) + 2.0).abs() < 1e-6);
// Through zero, from zero, or not finite: the straight line.
assert_eq!(lerp_geometric(-1.0, 1.0, 0.25), lerp(-1.0, 1.0, 0.25));
assert_eq!(lerp_geometric(0.0, 2.0, 0.5), 1.0);
assert!(lerp_geometric(1.0, f32::INFINITY, 0.5).is_infinite());
assert!(lerp_geometric(1e-30, 1e30, 5.0).is_finite());
}
#[test]
fn flat_rects_transform_and_empty_ones_stay_empty() {
let flat = Rect::new(-10.0, 0.0, 10.0, 0.0);
+23
View File
@@ -1278,6 +1278,29 @@ mod tests {
}
}
#[test]
fn a_tween_that_keeps_area_is_baked_frame_by_frame() {
// ADR 0115: no cubic ease draws a geometric scale curve, so the check of ADR 0089
// refuses eased keys and the export holds every frame's own scale: the area a Lottie
// player shows is the one `evaluate` gives, on every frame.
use anicraft_doc::Easing;
use std::sync::Arc;
let mut doc = tweened(Affine::translate(50.0, 60.0), Affine::translate(50.0, 60.0).mul(&Affine::scale(2.0, 0.5)), Easing::Linear, false);
let l = Arc::make_mut(&mut doc.timeline_mut(0).layers[0]);
Arc::make_mut(&mut l.keyframes[0]).tween.as_mut().unwrap().keep_area = true;
let e = to_lottie(&doc, "squash", 0, 14, false);
let v = parse(&e);
let it = items(&v, 0);
let s = keys_of(&it.last().unwrap()["s"]);
assert!(s.len() >= 10, "a key a frame: {}", s.len());
for f in 0..=14 {
let got = crate::lottie_keys::value_at(&s, f64::from(f)).unwrap();
let want = evaluate(&doc, f).items[0].transform.decompose();
assert!((got[0] - f64::from(want.sx) * 100.0).abs() < 2e-2 && (got[1] - f64::from(want.sy) * 100.0).abs() < 2e-2, "frame {f}: {got:?} vs {want:?}");
assert!((got[0] * got[1] - 10_000.0).abs() < 5.0, "frame {f}: the area stays ({got:?})");
}
}
#[test]
fn turning_and_growing_are_transform_keys() {
use anicraft_doc::Easing;
+1 -1
View File
@@ -765,7 +765,7 @@ impl<'a> Builder<'a> {
self.report.skip("tween spins (turned the shortest way)");
}
let (easing, groups) = self.easing(f);
k.tween = Some(Tween { easing, kind, orient, groups });
k.tween = Some(Tween { easing, kind, orient, groups, keep_area: false });
}
craft_xfl::document::TweenType::MotionObject => self.report.skip("motion tweens (kept as keyframes)"),
craft_xfl::document::TweenType::Other => {}
@@ -0,0 +1,139 @@
# ADR 0115: Pen parity and tweens that keep area
* Status: accepted (2026-11-18)
* Relates to: ADR 0038 (motion path points), ADR 0042, 0045 (Subselection and raw points),
ADR 0016 (motion tweens), ADR 0081 (eases per property group), ADR 0083 (Motion Editor),
ADR 0089 (Lottie keyframes), user issues #319 and #408, roadmap M1
## Context
Two requests from animators coming from Animate.
**The Pen (#319).** AniCraft's Pen placed corners, pulled mirrored handles and closed a path
on its first point. It lacked what Animate's Pen does on the point just drawn and on paths
already there: clicking the last point to break its handles (so the next segment leaves it as
a sharp corner), Alt-dragging it to draw its curve again, and, on a drawn path, the pointer
that says "click here to make a corner / delete this point / add a point". Behaviour was
learned from the issue's description and Adobe's public help pages for the Pen; nothing was
copied.
**Keep area (#408).** A tween moves scale X and scale Y in straight lines. From 100 × 100 % to
200 × 50 % the halfway frame is 150 × 75 %: 12.5 % more area than either key, so a squash
bulges. Animators hide it with extra keys.
## Decision
### The Pen
1. **On the last point** of the path being drawn:
* a **click** takes its handle ahead away, keeping the one behind: the curve arriving
stays, the next segment starts as a corner. On a point with no handle ahead the click
**finishes** the open path, so a double-click still finishes, as before;
* a **drag** from it pulls a new handle ahead alone;
* **Alt-drag** draws both of its handles again. The segment as it was stays in view,
faint, until the button is let go.
2. **Shift** keeps a new point on a multiple of 45° from the point before, and a handle on a
multiple of 45° from its point. It wins over snapping, as it does for the Line tool.
3. **The segment a click would add** is previewed as it will curve, from the last point's
handle, not as a straight dashed line.
4. **On a path whose points show** (a selected drawing object or selected merged shapes),
with no path being drawn:
* a click on a **smooth point** makes it a corner; a click on a **corner** deletes it (so
two clicks delete a smooth point, as in Animate);
* a click on the **outline** between points adds a point (Alt-click still does, and is the
only way on a motion path);
* a click on an **end of an open drawing object** picks the path up: the Pen draws on from
there, and finishing extends that object instead of adding another. Clicking its other
end closes it.
**Ctrl-click (⌘)** selects the path under the pointer, so its points show.
5. **Only selected paths are edited.** A click on an unselected line starts a new path there,
as it always did. In merge drawing, starting a line on another line (a T-junction) is the
common case, and Animate behaves the same way: its Pen edits the paths whose points are
showing. A path just drawn is left unselected for the same reason.
6. **Pointer marks.** egui has no pen cursors, so the stage draws a mark by the crosshair: a
plus (add), a minus (delete), a caret (make a corner), a ring (close), a slash (continue)
and a square (finish). They are drawn in the selection colour over white, from the theme.
7. **Commands.** The shell holds only the path under construction (view state). Every
document change is an existing command (`draw.path`, `path.add_point`,
`path.convert_point`, `path.delete_points`, `raw.add_point`, `raw.convert_points`,
`raw.delete_points`) or the new **`path.extend {id, d, end?: "end" | "start", close?}`**,
which continues an open path (one subpath, not closed) with a piece given in stage space.
The piece's own start is not kept: it joins the path's end exactly. From the start, the
piece is turned round and put in front, so the path keeps its direction (stroke profiles
and dashes run the same way as before). A refused piece leaves the path as it was.
The interaction is split into `pen_press`, `pen_drag`, `pen_release` and `pen_hover`, which
take positions and modifier keys and are tested without an egui event loop.
### Keep area
1. **A flag per tween**: `Tween.keep_area` and `MotionTween.keep_area`, `#[serde(default)]`
and not written when false. Files without it are byte-for-byte as before, and older files
open. One command sets it on whatever tween the span has:
**`timeline.set_keep_area {keep_area, layer?, frame?}`**.
2. **Scale moves geometrically.** With the flag on, each scale axis goes from its key to the
next as `a · (b / a)^t` (`geom::lerp_geometric`) in place of `a + (b − a) · t`, where `t`
is the eased progress of the scale group (ADR 0081) or of the property key's segment. The
product of two axes moved this way is the geometric interpolation of the keys' products,
so **keys of one area keep that area on every frame**, exactly up to rounding (tested to
2 · 10⁻⁵), and keys of different areas change it by an even ratio. Rotation, skew and
position are untouched (the area factor of the matrix is `sx · sy`).
* An ease that overshoots (Back, Elastic) extrapolates in the same ratio and never
crosses zero.
* An axis whose keys differ in sign (a flip through zero), or with a zero key, can't go
geometrically and tweens linearly as before. A flipped axis that stays flipped keeps its
sign.
3. **On a motion tween, an axis without keys follows.** A motion tween keys each property on
its own, so an animator who stretches only the width has said nothing about the height.
With Keep area, a scale axis that isn't animated (no track, or fewer than two keys) is
derived from the animated one: `follower · driver(0) / driver(f)`, which holds the area of
the span's first frame. When both axes have keys, both curves are the animator's and
rule 2 applies. `MotionTween::scale_at` is the one place this is computed; `props_at`,
`apply`, `split_at` and the Motion Editor use it.
4. **A drag of one axis doesn't key the follower.** Transform tools set both scale factors
on every step of a drag, putting the untouched axis back where the gesture found it. To
the key recorder that looked like an edit of the follower (it shows a derived value), and
the first step of a drag would have ended the following. So, while an axis follows, an
edit that leaves it at its own resting value is not keyed. Setting it to anything else
keys it, and from then on it is the animator's.
5. **`evaluate` stays pure**, and off is bit-exact: the flag adds a branch after the existing
interpolation and nothing changes when it is false (tested bit for bit against the lerp
of before, for classic and motion tweens).
6. **The Motion Editor draws what plays**: a scale curve of a tween that keeps area is
sampled through `shown_value`, so it shows the geometric curve between keys, or the
derived curve of a following axis with a note saying which axis it follows. Properties and
the Motion Editor's footer have the **Keep area** checkbox.
7. **Exports bake it.** Every exporter samples `evaluate` per frame. The Lottie exporter
writes eased keys only where they reproduce the sampled frames (ADR 0089); no cubic ease
draws a geometric curve, so it falls back to one hold key per frame by its own check
(tested).
## Alternatives considered
* **Linear on one axis and the inverse on the other** (`sy = area / sx`) for classic tweens.
It ignores the end key's second axis and jumps at the end key when the keys differ in area.
The geometric form is symmetric, reaches both keys, and is what #408 asks for.
* **Editing any path under the Pen, selected or not.** Simpler to discover, but it would
break starting a path on existing artwork, the usual way to draw in merge mode.
* **A custom OS cursor** for the Pen's states. egui has none; a mark beside the crosshair
says the same and needs no platform code.
* **A new document field for "derived" scale keys.** Not needed: the derived curve is a
function of the keys already there.
## Consequences
* Two more fields in the file format, both absent when off.
* `Progress` (the classic tween's eased progress per group) carries `keep_area`.
* The Pen's click on a smooth last point now makes it a corner instead of finishing; a second
click, a double-click on a corner, Enter or Esc finish. The tool's hint says so.
* Retiming a motion tween that keeps area (`motion/retime.rs`) inserts keys at the straight
line's value, not the geometric one. Splitting a span is exact.
## Not in this slice
* Continuing a merged (raw) line as the same stroke: a path started on its end merges with it
as any touching stroke does.
* Keep area per property key or per segment; a "volume" control that exaggerates the squash.
* Keep area when importing Animate files (XFL has no such option).
* Pen cursors as real OS cursors; converting a corner back to smooth by dragging from it with
the Pen (Subselection's Make Smooth does it).
+26 -3
View File
@@ -130,9 +130,32 @@ unlocked layer at once. **Edit › Deselect All** is **Ctrl+Shift+A**.
### The Pen
The **Pen** (**P**) draws precise Bézier curves. Click to place corner points, or drag to pull
out smooth handles (**Alt** moves one handle on its own). Click the first point to close the
shape; **Enter**, **Esc** or a click on the last point finishes an open line. **Backspace**
takes back the last point, and **Alt**-click on a line or a selected shape adds a point to it.
out smooth handles (**Alt** moves one handle on its own). A dashed line shows the segment your
next click would add. Hold **Shift** to keep a new point, or a handle, on steps of 45°. Click
the first point to close the shape; **Enter**, **Esc** or a double-click finishes an open
line. **Backspace** takes back the last point.
A small mark beside the pointer tells you what a click will do.
On the point you just placed:
* **Click it** (caret mark) to make it a corner: the curve arriving stays as it is, and the
next segment leaves the point straight. Click it again (square mark) to finish the line.
* **Drag from it** to pull a new handle for the next segment only.
* **Alt-drag it** to draw its curve again. The curve as it was stays in view until you let go.
On a path you drew earlier, select it first: **Ctrl**-click it with the Pen (**⌘** on macOS),
or use the Selection tool. Its points show. Then:
* Click a **smooth point** (caret mark) to make it a corner. Click a **corner** (minus mark) to
delete it.
* Click the **outline** between two points (plus mark) to add a point.
* Click an **end of an open path** (slash mark) to carry on drawing it. Click its other end
(ring mark) to close it. This works on drawing objects; in merge drawing, a line started on
another line's end joins it anyway.
A path that isn't selected is left alone, so you can start a new line on top of it.
**Alt**-click still adds a point to a selected shape, a merged line or a motion path.
### The Brush
+5 -1
View File
@@ -1,6 +1,6 @@
# Command reference
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 376 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 378 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
This page is generated from the command registry, so it always matches the version of AniCraft it came with.
@@ -335,6 +335,8 @@ These commands have no menu item: the panels, the stage and the timeline use the
Parameters: `{easing: a preset name (Linear, QuadIn … ElasticInOut) | {classic: -100..100} | {bezier: [x1, y1, x2, y2]} | {custom: {points: [..]} | [[x, y], ..]} | {saved: name} | {plugin: id, ease: id} (an ease plug-in's; the tween keeps its sampled curve), group?: all|position|rotation|scale|color|filters (classic tweens: that property group's own ease), layer?, frame?}`
- **Orient to Path** `timeline.set_orient` · changes the document
Parameters: `{orient: bool, layer?, frame?}`
- **Keep Area** `timeline.set_keep_area` · changes the document
Parameters: `{keep_area: bool, layer?, frame?}: squash and stretch that keeps the object's area (ADR 0115). The span's tween (classic, shape or motion) moves scale X and Y geometrically between keys instead of in straight lines, so keys of one area keep it on every frame; on a motion tween a scale axis without keys of its own follows the other inversely. Off by default`
- **Frame Label** `timeline.set_label` · changes the document
Parameters: `{label, layer?, frame?}`
- **Go to Frame** `timeline.goto`
@@ -591,6 +593,8 @@ These commands have no menu item: the panels, the stage and the timeline use the
Parameters: `{id, cmds: [..]}`
- **Convert Anchor Point** `path.convert_point` · changes the document
Parameters: `{id, cmd, smooth: bool}`
- **Continue Path** `path.extend` · changes the document
Parameters: `{id, d: SVG path data (stage space) of the new piece, drawn away from the end it continues, end?: "end" | "start" (default end), close?: bool}: continues an open path (one subpath, not closed) from one of its ends, as the Pen does (ADR 0115). The piece joins the path's own end point (its M is where the pen started and isn't kept); with close the path is closed after it`
- **Bend Segment** `path.bend_segment` · changes the document
Parameters: ``{x, y, dx, dy, id?, cmd?, t?, slop?, merge?: bool} the segment at (x, y) (of shape `id`, else the one there) bends so that point moves by (dx, dy), its ends staying; a raw shape's copies of the edge bend with it and merge again (unless merge is false)``
- **Move Point** `raw.move_point` · changes the document
+18
View File
@@ -36,6 +36,24 @@ AniCraft adds a keyframe there for you.
To take a tween away, choose **Insert › Remove Tween**. The frames keep the first keyframe's
artwork.
### Squash and stretch that keeps its area
A ball squashed to half its height should spread to twice its width, and stay that full on
the way. A tween normally moves width and height in straight lines, so the frames in between
come out bigger than either keyframe. Turn on **Keep area** in **Properties › Frame** and the
tween scales the way a squash does: from 100 × 100 % to 200 × 50 %, the halfway frame is about
141 × 71 %, and the area is the same on every frame.
* It works on classic, shape and motion tweens, one tween at a time, and is off until you turn
it on. Your eases apply as before.
* If the two keyframes have different areas, the area changes smoothly from one to the other.
* An object that is flipped on one keyframe and not on the other tweens the usual way.
* On a **motion tween** you only need to key one direction. Stretch the width at a later
frame and the height squashes by itself to keep the area of the first frame. Key the height
too whenever you want to set it yourself. The Motion Editor has the same **Keep area**
checkbox and draws the curve the height follows.
* Every export shows the same squash.
## Easing
Easing makes motion speed up or slow down instead of moving at one steady pace. Pick an ease
+2 -2
View File
@@ -15,7 +15,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va
| 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. **A stroke is covered as one outline** (ADR 0110): the stroker builds each run of segments as an outline and unites the loops, so pixels where its pieces used to overlap (round joins and caps, the joints of wide curves, dashes that run together, a line crossing itself) are no longer up to half a pixel too dark, on the CPU and the GPU stage alike; a line with corners, flat or square ends is drawn pixel for pixel as its Convert Lines to Fills fill, a curved or round one within the 0.1 px flattening (not yet: one geometry for both on curves, a per-stroke outline cache, dashes measured along the curve). **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**: theLine 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) (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). **Layers by drag and all at once** (M8, from the issue tracker): drag a layer by its name to reorder it or drop it on a folder (a line shows where it lands; folders, masks and guides move whole; one undo step; `layer.move {before | after | into}`), the eye, padlock and outline square above the layer names act on every layer (`all` on the three toggles), and the line between the layer names and the frames drags (150–600 pt, kept in the preferences). Not yet: several selected layers dragged together, dragging a layer onto another scene. 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 tLine 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), **skew** by dragging the line between two handles (the opposite edge stays, Alt about the centre; outside PR #176), 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; pasted raw shapes float, selected, until they are deselected, and Paste takes a picture copied in another app as a bitmap, ADR 0108; not yet: vectors copied in other apps). Free Transform: not yet a transformation point you can move (it is the box's centre) or a box that turns with a rotated object. **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 widthLine 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), **skew** by dragging the line between two handles (the opposite edge stays, Alt about the centre; outside PR #176), 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; pasted raw shapes float, selected, until they are deselected, and Paste takes a picture copied in another app as a bitmap, ADR 0108; not yet: vectors copied in other apps). Free Transform: not yet a transformation point you can move (it is the box's centre) or a box that turns with a rotated object. **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 widthLine 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. **Live control** (ADR 0104, `docs/control-protocol.md`): `anicraft --control <port>` and `anicraft-cli mcp --bridge <port>` run the same tools on the open window, on this computer only, with a per-run token in `control.json`. |
@@ -39,7 +39,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va
| M | Theme | Exit criteria |
|---|---|---|
| **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. |
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅; ~~groups, Combine Objects, Selection-tool modifiers~~ ✅ first slice (ADR 0073); ~~gradient editor, Gradient Transform tool and Lock Fill~~ ✅ (ADR 0074: the colour picker sets a fill's type, with a keyboard-operable stop bar, overflow, Linear RGB, focal point and bitmap fills; the Gradient Transform tool (F)); ~~rulers, grid and guides with one snap engine~~ ✅ first slice (ADR 0076); ~~Modify › Shape (Convert Lines to Fills, Expand Fill, Soften Fill Edges), the colour picker's eyedropper and transformation origins for several objects~~ ✅ first slice (ADR 0109); ~~a movable transformation point, a selection box that turns with the object, and layer opacity~~ ✅ first slice (ADR 0111). |
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅; ~~groups, Combine Objects, Selection-tool modifiers~~ ✅ first slice (ADR 0073); ~~gradient editor, Gradient Transform tool and Lock Fill~~ ✅ (ADR 0074: the colour picker sets a fill's type, with a keyboard-operable stop bar, overflow, Linear RGB, focal point and bitmap fills; the Gradient Transform tool (F)); ~~rulers, grid and guides with one snap engine~~ ✅ first slice (ADR 0076); ~~Modify › Shape (Convert Lines to Fills, Expand Fill, Soften Fill Edges), the colour picker's eyedropper and transformation origins for several objects~~ ✅ first slice (ADR 0109); ~~a movable transformation point, a selection box that turns with the object, and layer opacity~~ ✅ first slice (ADR 0111). **Pen parity and Keep area** (ADR 0115, #319, #408): the Pen makes its last point a corner on a click, pulls a new handle or redraws the curve (Alt) from it, keeps 45° steps with Shift, previews the next segment as it curves, and on a selected path converts and deletes points, adds them on the outline and continues an open drawing object from either end (`path.extend`), with a mark by the pointer for each; tweens of any kind take **Keep area** (`timeline.set_keep_area`): scale goes geometrically between keys so keys of one area keep it on every frame, an unkeyed scale axis of a motion tween follows the other, the Motion Editor draws the derived curve and exports bake it. Not yet: continuing a merged line as the same stroke, OS pen cursors, Keep area per segment. |
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016; the ease presets, saved and custom eases of ADR 0081 per segment); ~~Motion Editor and timeline retiming, Split/Join Motion~~ ✅ (ADR 0083); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~stroke coverage as one union, no double-darkening~~ ✅ (ADR 0110: one outline per stroke from the oracle, so both renderers follow; 2,000 outlined shapes at 1080p 9.3 → 9.0 ms, self-crossing scribbles +4 to 8 %; not yet: stroke and converted fill from the same curves, an outline cache); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); ~~surviving GPU failures mid-session~~ ✅ (ADR 0092: the stage drops to the CPU at once and retries the GPU after 3, 15, 60 and 300 s or on a resize; the window's device gets an error handler and a loss callback instead of wgpu's panic, a failing surface is reconfigured then recreated, and a lost window device autosaves, reopens the window a safer way and makes the next 3 starts try it late; not yet: recreating the window's device in place, which eframe doesn't offer); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. |
| **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). |
+38 -2
View File
@@ -135,7 +135,7 @@ impl Tool {
match self {
Tool::Select => tr_noop!("Click to select, drag to move, drag on empty space to marquee-select. Shift adds to the selection."),
Tool::Subselect => tr_noop!("Click a shape to show its points; on a merged drawing, the points of everything connected to it. Drag points or handles to reshape (a shared point moves every shape that has it; a smooth point's handles stay in line, Alt moves one alone); drag a line or fill to move everything connected. Shift adds to the point selection, drag on empty space to marquee points, arrow keys nudge them. Double-click an edge to add a point, Delete removes points, and right-click makes a point smooth or a corner. A motion path's points edit the same way (its ends stay)."),
Tool::Pen => tr_noop!("Click to place corner points, drag to pull smooth handles (Alt moves one handle). Click the first point to close; Enter, Esc or a click on the last point finishes. Backspace removes the last point. Alt-click a selected shape, a merged drawing's line or a motion path to add a point to it. Points snap to points and lines while Snap to Objects is on."),
Tool::Pen => tr_noop!("Click to place corner points, drag to pull smooth handles (Alt moves one handle, Shift keeps 45° steps). Click the first point to close; Enter, Esc or a double-click finishes. Click the last point to make it a corner, drag from it for a new handle, Alt-drag it to draw its curve again; Backspace removes it. On a selected path: click a point to make it a corner and again to delete it, click the outline to add a point, click an open end to continue it. Ctrl-click a path to select it. Points snap to points and lines while Snap to Objects is on."),
Tool::Text => tr_noop!("Click to type new text, or click text to edit it. Esc or a click elsewhere finishes. The options set the font, size and colour; double-click text with the Selection tool to edit it too."),
Tool::Pencil => tr_noop!("Drag to draw freehand. The options bar sets Smooth, Straighten or Ink."),
Tool::Brush => tr_noop!("Drag to paint filled shapes in the fill colour (a click paints a dab). [ and ] change the size; the options set the brush, its shape, pressure, smoothing and paint mode."),
@@ -3007,6 +3007,42 @@ impl App {
self.me_prop = anicraft_engine::doc::Property::Y;
self.me_key = None;
}
Some("keeparea") => {
// Keep area (ADR 0115): the Star layer's span as a motion tween that stretches
// the star to twice its width half way; its height isn't keyed and follows.
// The Motion Editor shows the derived Scale Y curve.
self.run("layer.select", json!({"index": 1}));
if let Some(target) = self.run("timeline.create_motion_tween", json!({"frame": 0})).and_then(|_| self.run("motion.info", json!({"frame": 0}))).and_then(|v| v["target"].as_u64()) {
self.run("timeline.set_keep_area", json!({"keep_area": true}));
self.run("timeline.goto", json!({"frame": 24}));
self.run("element.select", json!({"ids": [target]}));
self.run("element.set_transform", json!({"sx": 2.0}));
self.s.mark_saved();
}
self.run("timeline.goto", json!({"frame": 12}));
self.frame_sel = Some(timeline::FrameSel::cell(self.s.layer, 12));
self.show_panel(crate::dock::Panel::MotionEditor);
self.me_prop = anicraft_engine::doc::Property::ScaleY;
self.me_key = None;
}
Some("penpoints") => {
// The Pen on a selected open path (ADR 0115): its points show, and its end has
// been picked up to draw on from, with the last curve being drawn again (Alt),
// the segment as it was still in view.
self.tool = Tool::Pen;
self.s.style.object_drawing = true;
if let Some(id) = self.run("draw.path", json!({"d": "M120 260 C160 180 240 180 280 260 L360 260", "object": true, "fill": null})).and_then(|_| self.s.selection.ids().next()).map(|id| id.0) {
self.s.mark_saved();
let v = |x: f32, y: f32| anicraft_engine::geom::Vec2::new(x, y);
let was = [v(440.0, 200.0), v(400.0, 190.0), v(480.0, 210.0)];
self.pen = Some(pathtools::PenPath {
knots: vec![[v(360.0, 260.0); 3], [v(440.0, 200.0), v(430.0, 250.0), v(450.0, 150.0)]],
dragging: true,
grip: pathtools::PenGrip::Adjust { was },
extends: Some((anicraft_engine::doc::ElementId(id), false)),
});
}
}
Some("pen") => {
// A pen path still being drawn: a corner, a smooth point with handles, a corner.
self.tool = Tool::Pen;
@@ -3014,7 +3050,7 @@ impl App {
let mut curve = k(260.0, 140.0);
curve[1] = anicraft_engine::geom::Vec2::new(220.0, 180.0);
curve[2] = anicraft_engine::geom::Vec2::new(300.0, 100.0);
self.pen = Some(pathtools::PenPath { knots: vec![k(120.0, 160.0), curve, k(380.0, 150.0)], dragging: false });
self.pen = Some(pathtools::PenPath { knots: vec![k(120.0, 160.0), curve, k(380.0, 150.0)], ..Default::default() });
}
_ => {}
}
+38 -7
View File
@@ -405,6 +405,21 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
Some(MeDrag::Key { lo, hi, lane: false, .. } | MeDrag::Handle { lo, hi, .. }) => (lo, hi),
_ => value_range(track, own(p), frames, p),
};
// Keep area (ADR 0115): a scale curve shows as the tween plays it, geometric between its
// keys, or derived from the other axis when it has no keys of its own.
let kept = m.keep_area && matches!(p, Property::ScaleX | Property::ScaleY);
let shown = |f: f32| if kept { m.shown_value(&base, p, f) } else { track.and_then(|t| t.value_at(f)).unwrap_or(own(p)) };
let (lo, hi) = if kept && app.me_drag.is_none() {
let (mut a, mut b) = (lo, hi);
for f in 0..frames.max(1) {
let v = shown(f as f32);
(a, b) = (a.min(v), b.max(v));
}
let pad = if a < lo || b > hi { (b - a).max(1.0) * 0.08 } else { 0.0 };
(if a < lo { a - pad } else { lo }, if b > hi { b + pad } else { hi })
} else {
(lo, hi)
};
let last = frames.saturating_sub(1).max(1) as f32;
// Wider on the left: the value labels sit there, clear of the first key.
let inner = Rect::from_min_max(graph.min + vec2(PAD * 2.0, PAD * 0.75), graph.max - vec2(PAD, PAD * 0.75));
@@ -452,13 +467,25 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
let mut x = inner.left();
while x <= inner.right() + 0.5 {
let f = f_of(x);
let v = track.and_then(|t| t.value_at(f)).unwrap_or(own(p));
pts.push(pos2(x, y_of(v)));
pts.push(pos2(x, y_of(shown(f))));
x += 2.0;
}
gp.add(egui::Shape::line(pts, Stroke::new(2.0, if track.is_some() { T.tween_motion } else { T.text_faint })));
let derived = m.is_derived(p);
gp.add(egui::Shape::line(pts, Stroke::new(2.0, if track.is_some() || derived { T.tween_motion } else { T.text_faint })));
gp.text(pos2(graph.right() - 8.0, graph.top() + 6.0), Align2::RIGHT_TOP, format!("{label} · {}", fmt(p, now_of(p))), font(Type::Data), color(Type::Data));
if track.is_none() {
if kept {
// Say why the curve isn't the straight line between its keys.
let note = match (derived, p) {
(true, Property::ScaleX) => tr!("Keep area: follows Scale Y"),
(true, _) => tr!("Keep area: follows Scale X"),
(false, _) => tr!("Keep area"),
};
gp.text(pos2(graph.right() - 8.0, graph.top() + 24.0), Align2::RIGHT_TOP, note, font(Type::Caption), color(Type::Caption));
}
if derived {
// No keys of its own, but it moves: say what moves it and how to take it over.
gp.text(pos2(graph.center().x, graph.top() + 44.0), Align2::CENTER_CENTER, tr!("{property} has no keyframes: Keep area moves it against the other scale axis. Click ◇ or drag its value to key it yourself.", property = label), font(Type::Caption), color(Type::Caption));
} else if track.is_none() {
gp.text(graph.center(), Align2::CENTER_CENTER, tr!("{property} has no keyframes: it stays {value}. Click ◇ or drag its value to key it here.", property = label, value = fmt(p, own(p))), font(Type::Caption), color(Type::Caption));
}
// A colour's channel: the whole colour over the span, along the bottom of the graph, so
@@ -707,7 +734,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
{
// A key on the curve where it is now (the motion doesn't change until it is dragged).
let f = to_frame(pt.x);
let v = track.and_then(|t| t.value_at((f - start) as f32)).unwrap_or(own(p));
let v = shown((f - start) as f32);
if app.run("motion.set_key", json!({"property": p.key(), "frame": f, "value": v})).is_some() {
app.me_key = Some(f - start);
}
@@ -720,7 +747,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
};
}
footer(app, ui, body, track, sel_key, start, &rows, &label);
footer(app, ui, body, track, sel_key, start, &rows, &label, m.keep_area);
}
/// The name of the object's filter at `slot` (Animate's, for the list and screen readers).
@@ -886,7 +913,7 @@ fn diamond(p: &egui::Painter, c: Pos2, r: f32, fill: Color32, stroke: Stroke) {
/// The ease of the selected segment, and the tween's own actions.
#[allow(clippy::too_many_arguments)]
fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, sel_key: Option<u32>, start: u32, rows: &[Property], label: &str) {
fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, sel_key: Option<u32>, start: u32, rows: &[Property], label: &str, keep_area: bool) {
let bar = Rect::from_min_max(pos2(body.left(), body.bottom() - FOOTER_H), body.right_bottom());
ui.painter().rect_filled(bar, SQUARE, T.panel_alt);
ui.painter().line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, T.border));
@@ -936,6 +963,10 @@ fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, s
.response
.on_hover_text(tr!("List a colour effect style's properties here; keying one adds it to the tween"));
}
let mut keep = keep_area;
if crate::theme::checkbox(ui, &mut keep, tr!("Keep area")).on_hover_text(tr!("Squash and stretch without growing: scale goes geometrically between keys, and a scale axis without keys follows the other so the area stays")).named(tr!("Keep area")).changed() {
app.run("timeline.set_keep_area", json!({"keep_area": keep, "frame": start}));
}
if ui.button(tr!("Remove Tween")).on_hover_text(tr!("The object stays as it is on the span's first frame ({undo} to undo)", undo = app.undo_key())).clicked() {
app.run("timeline.remove_tween", json!({}));
}
+10
View File
@@ -2816,6 +2816,11 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L
if crate::theme::checkbox(ui, &mut orient, tr!("Orient to path")).on_hover_text(tr!("Turn the object as its motion path turns")).named(tr!("Orient to path")).changed() {
app.run("motion.orient", json!({"orient": orient}));
}
// Keep area (ADR 0115): squash and stretch that doesn't grow.
let mut keep = m.keep_area;
if crate::theme::checkbox(ui, &mut keep, tr!("Keep area")).on_hover_text(tr!("Squash and stretch without growing: scale goes geometrically between keys, and a scale axis without keys follows the other so the area stays")).named(tr!("Keep area")).changed() {
app.run("timeline.set_keep_area", json!({"keep_area": keep}));
}
ui.horizontal(|ui| {
if ui.button(tr!("Motion Editor")).on_hover_text(tr!("Edit the property curves and eases")).clicked() {
app.show_panel(crate::dock::Panel::MotionEditor);
@@ -2875,6 +2880,11 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L
app.run("timeline.set_orient", json!({"orient": orient}));
}
}
// Keep area (ADR 0115): squash and stretch that doesn't grow.
let mut keep = t.keep_area;
if crate::theme::checkbox(ui, &mut keep, tr!("Keep area")).on_hover_text(tr!("Squash and stretch without growing: scale goes geometrically between keys, so keys of one area keep it on every frame")).named(tr!("Keep area")).changed() {
app.run("timeline.set_keep_area", json!({"keep_area": keep}));
}
crate::ease_editor::preview(app, ui, &t.easing);
}
None => {
+708 -50
View File
@@ -45,11 +45,31 @@ const PICK: f32 = 6.0;
// ----- Pen ---------------------------------------------------------------------------------
/// What the press that started the current Pen drag took hold of (ADR 0115).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum PenGrip {
/// A new knot: dragging pulls its mirrored handles (Alt: only the one ahead).
#[default]
New,
/// The last knot: a click takes its handle ahead away (the next segment leaves it as a
/// corner) or, when it has none, finishes the path; a drag pulls a new handle ahead alone.
Last { moved: bool },
/// The end of the path being continued: a drag pulls its handle ahead, a click does nothing.
Out,
/// Alt on the last knot: its handles are drawn again. `was` is the knot as it was, drawn
/// as a ghost until the button is let go.
Adjust { was: [Vec2; 3] },
}
/// Pen path under construction: knots as `[anchor, in, out]` in stage space.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PenPath {
pub knots: Vec<[Vec2; 3]>,
pub dragging: bool,
pub grip: PenGrip,
/// The open drawing object this path continues, and whether from its start (ADR 0115):
/// the first knot is that end, and finishing extends the object instead of adding one.
pub extends: Option<(ElementId, bool)>,
}
impl PenPath {
@@ -80,68 +100,360 @@ impl PenPath {
}
}
/// Pointer handling for the Pen. Runs on raw press/release (not egui's drag threshold), so a
/// quick click places a point exactly where it was pressed.
pub fn pen_input(app: &mut App, ui: &egui::Ui, resp: &egui::Response, xf: Xf) {
let (pressed, down, alt) = ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_down(), i.modifiers.alt));
let Some(pos) = resp.interact_pointer_pos().or_else(|| resp.hover_pos()) else { return };
let p = xf.to_stage(pos);
// Alt-click on a path, with no path being drawn, adds a point to it: the motion path first
// (ADR 0038), then a selected shape's outline.
if pressed && resp.hovered() && alt && app.pen.as_ref().is_none_or(|pen| pen.knots.is_empty()) {
/// The modifier keys the Pen reads.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PenMods {
/// Break the handle pair; on the last knot, draw its handles again; on a path, add a point.
pub alt: bool,
/// Keep the new segment, or the handle, on a multiple of 45°.
pub shift: bool,
/// Ctrl (⌘ on macOS): select the path under the pointer, to show its points.
pub command: bool,
}
/// What a Pen click here would do: the mark drawn by the pointer, as Animate's Pen cursors
/// tell it (issue #319).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PenHover {
/// Place a point.
Place,
/// Close the path on its first point.
Close,
/// Finish the open path (the last point, which has no handle ahead).
Finish,
/// Take the handles away: the last point's handle ahead, or a smooth point's pair.
Corner,
/// Draw the last point's handles again (Alt).
Adjust,
/// Add a point on the path.
Add,
/// Delete the point.
Delete,
/// Continue the open path from this end.
Continue,
}
/// `p` moved onto the nearest multiple of 45° around `from` (Shift), at the distance the
/// pointer is along that direction.
pub fn constrain_45(from: Vec2, p: Vec2) -> Vec2 {
let d = p - from;
if !d.is_finite() || d.length() < 1e-6 {
return p;
}
let step = std::f32::consts::FRAC_PI_4;
let a = (d.y.atan2(d.x) / step).round() * step;
let dir = Vec2::new(a.cos(), a.sin());
from + dir * (d.x * dir.x + d.y * dir.y)
}
/// A point of a path that shows its points, under the Pen.
#[derive(Clone, Copy, Debug, PartialEq)]
enum PenTarget {
/// An anchor of a selected drawing object: smooth (it has a handle), and the end of an
/// open path it is, if any (`Some(true)`: the start).
Anchor { id: ElementId, cmd: usize, smooth: bool, end: Option<bool> },
/// A shared anchor of the selected raw shapes.
RawAnchor { at: Vec2, smooth: bool },
/// The outline of a selected shape, drawing object or raw, between its points.
Segment,
}
/// Whether `path` is one open run of segments, the kind the Pen can continue.
fn is_open(path: &Path) -> bool {
path.cmds.len() >= 2 && matches!(path.cmds.first(), Some(PathCmd::MoveTo(_))) && !path.cmds.iter().skip(1).any(|c| matches!(c, PathCmd::MoveTo(_) | PathCmd::Close))
}
/// What of the paths showing their points (the selected shapes on the active layer) is at
/// screen point `at`.
fn pen_target(app: &App, at: Pos2, xf: Xf) -> Option<PenTarget> {
let near = |q: Vec2| xf.to_screen(q).distance(at) <= PICK;
let sp = xf.to_stage(at);
let slop = PICK * xf.unit();
let shapes = selected_shapes(app);
for (id, path, m) in &shapes {
if let Some((cmd, q)) = path.editable_anchors().into_iter().find(|(_, q)| near(m.apply(*q))) {
let smooth = shown_handles(path, [cmd].into_iter()).iter().any(|&(c, slot, _)| path.point(c, slot).is_some_and(|h| h.distance(q) > 1e-4));
let end = if !is_open(path) {
None
} else if cmd == 0 {
Some(true)
} else if cmd + 1 == path.cmds.len() {
Some(false)
} else {
None
};
return Some(PenTarget::Anchor { id: *id, cmd, smooth, end });
}
}
let raw = raw_selected(app);
if !raw.is_empty() {
let pts = app.s.raw_points(&raw);
if let Some(q) = pts.anchors.iter().copied().filter(|q| near(*q)).min_by(|a, b| xf.to_screen(*a).distance(at).total_cmp(&xf.to_screen(*b).distance(at))) {
let smooth = pts.handles.iter().any(|h| h.anchor.distance(q) <= SNAP && h.at.distance(h.anchor) > SNAP);
return Some(PenTarget::RawAnchor { at: q, smooth });
}
}
if shapes.iter().any(|(_, path, m)| path.nearest_segment(sp, m).is_some_and(|(_, _, d)| d <= slop)) {
return Some(PenTarget::Segment);
}
let on_raw = app.s.visible_elements().iter().filter(|e| raw.contains(&e.id)).take(512).any(|e| match &e.kind {
ElementKind::Shape(sh) => sh.path.nearest_segment(sp, &e.transform).is_some_and(|(_, _, d)| d <= slop),
_ => false,
});
on_raw.then_some(PenTarget::Segment)
}
/// Where the path being continued ends on its far side (stage space), if it still exists.
fn far_end(app: &App, pen: &PenPath) -> Option<Vec2> {
let (id, at_start) = pen.extends?;
let els = app.s.visible_elements();
let e = els.iter().find(|e| e.id == id)?;
let ElementKind::Shape(sh) = &e.kind else { return None };
let q = if at_start { sh.path.point(sh.path.cmds.len().checked_sub(1)?, ANCHOR) } else { sh.path.point(0, ANCHOR) }?;
Some(e.transform.apply(q))
}
/// What a click at screen point `at` would do (no button down).
pub fn pen_hover(app: &App, at: Pos2, xf: Xf, mods: PenMods) -> PenHover {
let p = xf.to_stage(at);
let tol = PICK * xf.unit();
if let Some(pen) = app.pen.as_ref().filter(|pen| !pen.knots.is_empty()) {
let n = pen.knots.len();
if n >= 2 && far_end(app, pen).is_some_and(|q| q.distance(p) <= tol) {
return PenHover::Close;
}
if n >= 2 && pen.extends.is_none() && pen.knots.first().is_some_and(|k| k[0].distance(p) <= tol) {
return PenHover::Close;
}
if let Some(k) = pen.knots.last().filter(|k| k[0].distance(p) <= tol) {
return match () {
_ if mods.alt => PenHover::Adjust,
_ if k[2] != k[0] => PenHover::Corner,
_ if n >= 2 => PenHover::Finish,
_ => PenHover::Place,
};
}
return PenHover::Place;
}
if mods.command {
return PenHover::Place;
}
match pen_target(app, at, xf) {
Some(PenTarget::Anchor { end: Some(_), .. }) => PenHover::Continue,
Some(PenTarget::Anchor { smooth: true, .. } | PenTarget::RawAnchor { smooth: true, .. }) => PenHover::Corner,
Some(PenTarget::Anchor { .. } | PenTarget::RawAnchor { .. }) => PenHover::Delete,
Some(PenTarget::Segment) => PenHover::Add,
None => PenHover::Place,
}
}
/// A Pen press on a path that shows its points, with no path being drawn (ADR 0115): an end
/// of an open drawing object is picked up to draw on from, a smooth point becomes a corner, a
/// corner is deleted, and the outline between points gets a point. False when the press was
/// on none of them (it starts a new path).
fn pen_press_on_path(app: &mut App, at: Pos2, xf: Xf) -> bool {
let undo = app.undo_key();
match pen_target(app, at, xf) {
Some(PenTarget::Anchor { id, cmd, end: Some(at_start), .. }) => {
let Some((_, path, m)) = selected_shapes(app).into_iter().find(|(e, _, _)| *e == id) else { return false };
// The end as a knot: its handle behind is the last segment's, so a handle pulled
// ahead can be seen against it.
let (Some(a), behind) = (path.point(cmd, ANCHOR), if at_start { path.point(1, C1) } else { path.point(cmd, C2) }) else { return false };
let a = m.apply(a);
let knot = [a, behind.map_or(a, |h| m.apply(h)), a];
app.pen = Some(PenPath { knots: vec![knot], dragging: true, grip: PenGrip::Out, extends: Some((id, at_start)) });
app.status_ok(tr!("Continuing the path: click to add points, Enter to finish."));
true
}
Some(PenTarget::Anchor { id, cmd, smooth: true, .. }) => {
if app.run("path.convert_point", json!({"id": id.0, "cmd": cmd, "smooth": false})).is_some() {
app.status_ok(tr!("Made a corner point. Click it again to delete it. {undo} to undo.", undo = undo));
}
true
}
Some(PenTarget::Anchor { id, cmd, .. }) => {
if app.run("path.delete_points", json!({"id": id.0, "cmds": [cmd]})).is_some() {
app.status_ok(trn!("Deleted {n} point. {undo} to undo.", "Deleted {n} points. {undo} to undo.", 1, undo = undo));
}
true
}
Some(PenTarget::RawAnchor { at: q, smooth }) => {
app.raw_anchors = vec![q];
if smooth {
raw_convert(app, false);
app.status_ok(tr!("Made a corner point. Click it again to delete it. {undo} to undo.", undo = undo));
} else {
raw_delete(app);
}
app.raw_anchors.clear();
true
}
Some(PenTarget::Segment) => add_point_on_selected(app, at, xf),
None => false,
}
}
/// Ctrl-click (⌘ on macOS) with the Pen: the path there is selected, so its points show and
/// the Pen can edit them; over nothing, the selection is dropped.
fn pen_select(app: &mut App, at: Pos2, xf: Xf) {
let sp = xf.to_stage(at);
if !raw_show_at(app, sp, false, xf) {
app.run("element.pick", json!({"x": sp.x, "y": sp.y}));
}
}
/// The Pen's button went down at screen point `at`.
pub fn pen_press(app: &mut App, at: Pos2, xf: Xf, mods: PenMods) {
let p = xf.to_stage(at);
let idle = app.pen.as_ref().is_none_or(|pen| pen.knots.is_empty());
if idle {
app.pen = None;
if crate::motion_path::pen_alt_click(app, pos, xf) || add_point_on_selected(app, pos, xf) {
// Alt-click on a path adds a point to it: the motion path first (ADR 0038), then a
// selected shape's outline.
if mods.alt && (crate::motion_path::pen_alt_click(app, at, xf) || add_point_on_selected(app, at, xf)) {
return;
}
if mods.command {
pen_select(app, at, xf);
return;
}
if !mods.alt && pen_press_on_path(app, at, xf) {
return;
}
}
if pressed && resp.hovered() {
let tol = PICK * xf.unit();
let pen = app.pen.get_or_insert_with(PenPath::default);
let n = pen.knots.len();
if n >= 2 && pen.knots.first().is_some_and(|k| k[0].distance(p) <= tol) {
commit_pen(app, true);
return;
}
if n >= 2 && pen.knots.last().is_some_and(|k| k[0].distance(p) <= tol) {
commit_pen(app, false);
return;
}
// A new knot snaps to points, lines and fill edges (ADR 0045); handles never do.
let p = crate::stage::snap_draw(app, pos2(p.x, p.y), xf.zoom);
let p = Vec2::new(p.x, p.y);
let Some(pen) = app.pen.as_mut() else { return };
pen.knots.push([p; 3]);
let tol = PICK * xf.unit();
let far = app.pen.as_ref().and_then(|pen| far_end(app, pen));
let pen = app.pen.get_or_insert_with(PenPath::default);
let n = pen.knots.len();
// The other end of the path being continued: a point there, and the path is closed.
if let Some(q) = far.filter(|q| n >= 2 && q.distance(p) <= tol) {
pen.knots.push([q; 3]);
commit_pen(app, true);
return;
}
if n >= 2 && pen.extends.is_none() && pen.knots.first().is_some_and(|k| k[0].distance(p) <= tol) {
commit_pen(app, true);
return;
}
if let Some(k) = pen.knots.last().filter(|k| k[0].distance(p) <= tol) {
pen.grip = if mods.alt { PenGrip::Adjust { was: *k } } else { PenGrip::Last { moved: false } };
pen.dragging = true;
return;
}
// A new knot snaps to points, lines and fill edges (ADR 0045); handles never do. Shift
// keeps the segment on a multiple of 45° from the knot before, and wins over snapping.
let prev = pen.knots.last().map(|k| k[0]);
let p = match prev.filter(|_| mods.shift) {
Some(from) => {
app.snap_ring = None;
constrain_45(from, p)
}
None => {
let q = crate::stage::snap_draw(app, pos2(p.x, p.y), xf.zoom);
Vec2::new(q.x, q.y)
}
};
let Some(pen) = app.pen.as_mut() else { return };
if !down {
pen.dragging = false;
return;
}
if pen.dragging
&& let Some(k) = pen.knots.last_mut()
{
let a = k[0];
if a.distance(p) * xf.zoom < 2.0 {
// A press that barely moved is a corner.
*k = [a; 3];
} else {
k[2] = p;
if !alt {
k[1] = a * 2.0 - p;
pen.knots.push([p; 3]);
pen.grip = PenGrip::New;
pen.dragging = true;
}
/// The pointer moved to screen point `at` with the Pen's button down.
pub fn pen_drag(app: &mut App, at: Pos2, xf: Xf, mods: PenMods) {
let Some(pen) = app.pen.as_mut().filter(|pen| pen.dragging) else { return };
let grip = pen.grip;
let Some(k) = pen.knots.last_mut() else { return };
let a = k[0];
let p = xf.to_stage(at);
// A press that barely moved is a click.
let moved = a.distance(p) * xf.zoom >= 2.0;
let p = if mods.shift { constrain_45(a, p) } else { p };
match grip {
PenGrip::New => {
if !moved {
*k = [a; 3];
} else {
k[2] = p;
if !mods.alt {
k[1] = a * 2.0 - p;
}
}
}
PenGrip::Last { moved: was_moved } => {
if moved || was_moved {
k[2] = p;
pen.grip = PenGrip::Last { moved: true };
}
}
PenGrip::Out => {
if moved {
k[2] = p;
}
}
PenGrip::Adjust { was } => {
*k = if moved { [a, a * 2.0 - p, p] } else { was };
}
}
}
/// Finishes the Pen path as a shape (one undo step). Fewer than two knots are dropped.
/// The Pen's button was let go.
pub fn pen_release(app: &mut App) {
let Some(pen) = app.pen.as_mut() else { return };
if !pen.dragging {
return;
}
pen.dragging = false;
let grip = std::mem::take(&mut pen.grip);
if grip != (PenGrip::Last { moved: false }) {
return;
}
// A click on the last knot: its handle ahead goes (the next segment starts as a corner,
// issue #319); with none to take, the click finishes the path, as a double-click does.
let n = pen.knots.len();
match pen.knots.last_mut() {
Some(k) if k[2] != k[0] => {
k[2] = k[0];
app.status_ok(tr!("The next segment starts as a corner. Click the point again, or press Enter, to finish."));
}
Some(_) if n >= 2 => commit_pen(app, false),
_ => {}
}
}
/// Pointer handling for the Pen. Runs on raw press/release (not egui's drag threshold), so a
/// quick click places a point exactly where it was pressed.
pub fn pen_input(app: &mut App, ui: &egui::Ui, resp: &egui::Response, xf: Xf) {
let (pressed, down, m) = ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_down(), i.modifiers));
let mods = PenMods { alt: m.alt, shift: m.shift, command: m.command };
// Off the stage there is nothing to do: a button let go out there is seen when the
// pointer comes back.
let Some(pos) = resp.interact_pointer_pos().or_else(|| resp.hover_pos()) else { return };
if pressed && resp.hovered() {
pen_press(app, pos, xf, mods);
} else if down {
pen_drag(app, pos, xf, mods);
} else {
pen_release(app);
}
}
/// Finishes the Pen path as a shape (one undo step), or as more of the path it continues.
/// Fewer than two knots are dropped.
pub fn commit_pen(app: &mut App, closed: bool) {
let Some(pen) = app.pen.take() else { return };
if pen.knots.len() < 2 {
return;
}
app.draw("draw.path", json!({"d": pen.to_svg(closed)}));
match pen.extends {
// The object stays selected: its points go on showing under the Pen.
Some((id, at_start)) => {
app.run("path.extend", json!({"id": id.0, "d": pen.to_svg(false), "end": if at_start { "start" } else { "end" }, "close": closed}));
}
None => {
app.draw("draw.path", json!({"d": pen.to_svg(closed)}));
}
}
}
// ----- Pencil ------------------------------------------------------------------------------
@@ -767,11 +1079,47 @@ fn anchor_box(painter: &egui::Painter, c: Pos2, filled: bool) {
painter.rect_stroke(r, 0.0, Stroke::new(1.0, T.selection), StrokeKind::Middle);
}
/// The mark by the Pen's pointer for what a click would do: a plus (add a point), a minus
/// (delete it), a caret (make it a corner), a ring (close the path), a slash (continue the
/// path), a square (finish). Drawn in the selection colour over white, so it reads on any
/// artwork.
fn pen_mark(painter: &egui::Painter, c: Pos2, what: PenHover) {
let r = 4.0;
let strokes = [Stroke::new(3.5, Color32::WHITE), Stroke::new(1.5, T.selection)];
let lines: &[[egui::Vec2; 2]] = match what {
PenHover::Place | PenHover::Adjust => return,
PenHover::Add => &[[vec2(-r, 0.0), vec2(r, 0.0)], [vec2(0.0, -r), vec2(0.0, r)]],
PenHover::Delete => &[[vec2(-r, 0.0), vec2(r, 0.0)]],
PenHover::Corner => &[[vec2(-r, r), vec2(0.0, -r)], [vec2(0.0, -r), vec2(r, r)]],
PenHover::Continue => &[[vec2(-r, r), vec2(r, -r)]],
PenHover::Close => {
for s in strokes {
painter.circle_stroke(c, r, s);
}
return;
}
PenHover::Finish => {
for s in strokes {
painter.rect_stroke(Rect::from_center_size(c, vec2(2.0 * r - 1.0, 2.0 * r - 1.0)), 0.0, s, StrokeKind::Middle);
}
return;
}
};
for s in strokes {
for [a, b] in lines {
painter.line_segment([c + *a, c + *b], s);
}
}
}
/// Path tool overlays: point editing on selected shapes, the Pen path being drawn and the
/// Pencil stroke in progress.
pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Pos2>) {
let line = Stroke::new(1.0, T.selection);
if app.tool == Tool::Subselect {
// The Pen shows the points of the selected paths too, while it isn't drawing one: it adds,
// converts and deletes them, and continues an open path from its end (ADR 0115).
let pen_idle = app.tool == Tool::Pen && app.pen.as_ref().is_none_or(|pen| pen.knots.is_empty());
if app.tool == Tool::Subselect || pen_idle {
draw_raw(app, painter, xf);
for (id, path, m) in selected_shapes(app) {
let to_px = Affine::translate(xf.origin.x, xf.origin.y).mul(&Affine::scale(xf.zoom, xf.zoom)).mul(&m);
@@ -802,14 +1150,27 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Po
}
}
painter.add(egui::Shape::line(pts, stroke));
let first = pen.knots.first().map(|k| xf.to_screen(k[0]));
// Alt on the last knot draws its handles again: the segment as it was stays in view
// until the button is let go (issue #319).
if let (PenGrip::Adjust { was }, Some(prev)) = (pen.grip, pen.knots.len().checked_sub(2).and_then(|i| pen.knots.get(i))) {
let ghost: Vec<Pos2> = (0..=16).map(|k| xf.to_screen(bezier(prev[0], prev[2], was[1], was[0], k as f32 / 16.0))).collect();
painter.add(egui::Shape::line(ghost, Stroke::new(1.0, T.selection.gamma_multiply(0.45))));
}
if let (Some(last), Some(h)) = (pen.knots.last(), hover)
&& !pen.dragging
{
painter.add(egui::Shape::dashed_line(&[xf.to_screen(last[0]), h], line, 4.0, 3.0));
// Closing cue: a ring on the first point when a click would close the path.
// The segment a click here would add, as it would curve (Shift: on 45°).
let shift = painter.ctx().input(|i| i.modifiers.shift);
let to = if shift { constrain_45(last[0], xf.to_stage(h)) } else { xf.to_stage(h) };
let ahead: Vec<Pos2> = (0..=16).map(|k| xf.to_screen(bezier(last[0], last[2], to, to, k as f32 / 16.0))).collect();
painter.add(egui::Shape::dashed_line(&ahead, line, 4.0, 3.0));
// Closing cue: a ring on the point a click would close the path on.
let close_on = match pen.extends {
Some(_) => far_end(app, pen),
None => pen.knots.first().map(|k| k[0]),
};
if pen.knots.len() >= 2
&& let Some(f) = first
&& let Some(f) = close_on.map(|q| xf.to_screen(q))
&& f.distance(h) <= PICK
{
painter.circle_stroke(f, 6.0, Stroke::new(1.5, T.selection));
@@ -828,6 +1189,16 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Po
anchor_box(painter, c, last);
}
}
// What a click would do, by the pointer (Animate's Pen cursors, issue #319).
if app.tool == Tool::Pen
&& app.drag == Drag::None
&& let Some(h) = hover
&& app.pen.as_ref().is_none_or(|pen| !pen.dragging)
{
let m = painter.ctx().input(|i| i.modifiers);
let what = pen_hover(app, h, xf, PenMods { alt: m.alt, shift: m.shift, command: m.command });
pen_mark(painter, h + vec2(13.0, 13.0), what);
}
if app.drag == Drag::Pencil && app.pencil.len() > 1 {
let w = (app.s.style.stroke_width * xf.zoom).max(1.0);
let pts: Vec<Pos2> = app.pencil.iter().map(|p| xf.to_screen(*p)).collect();
@@ -845,7 +1216,7 @@ mod tests {
#[test]
fn pen_svg_is_straight_for_corners_and_curved_for_handles() {
let mut pen = PenPath { knots: vec![knot(0.0, 0.0), knot(100.0, 0.0), knot(100.0, 50.0)], dragging: false };
let mut pen = PenPath { knots: vec![knot(0.0, 0.0), knot(100.0, 0.0), knot(100.0, 50.0)], ..Default::default() };
assert_eq!(pen.to_svg(false), "M0 0 L100 0 L100 50");
assert_eq!(pen.to_svg(true), "M0 0 L100 0 L100 50 Z");
pen.knots[1] = [Vec2::new(100.0, 0.0), Vec2::new(80.0, -10.0), Vec2::new(120.0, 10.0)];
@@ -856,6 +1227,293 @@ mod tests {
assert!(s.execute("draw.path", &json!({"d": pen.to_svg(true)})).is_ok());
}
/// The Pen (ADR 0115, issue #319) on a headless app, stage and screen coordinates the same.
mod pen {
use super::*;
const XF: Xf = Xf { origin: Pos2::ZERO, zoom: 1.0 };
const NONE: PenMods = PenMods { alt: false, shift: false, command: false };
const ALT: PenMods = PenMods { alt: true, shift: false, command: false };
const SHIFT: PenMods = PenMods { alt: false, shift: true, command: false };
const CTRL: PenMods = PenMods { alt: false, shift: false, command: true };
fn app() -> App {
let ctx = egui::Context::default();
let session = anicraft_engine::Session::new(anicraft_engine::doc::Document::default());
let mut app = App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png")));
app.tool = Tool::Pen;
app.view.zoom = 1.0;
// Drawing objects: one path is one element (merge drawing splits it at corners).
app.s.style.object_drawing = true;
app
}
fn v(x: f32, y: f32) -> Vec2 {
Vec2::new(x, y)
}
fn click(app: &mut App, x: f32, y: f32, mods: PenMods) {
pen_press(app, pos2(x, y), XF, mods);
pen_release(app);
}
fn drag(app: &mut App, from: (f32, f32), to: (f32, f32), mods: PenMods) {
pen_press(app, pos2(from.0, from.1), XF, mods);
pen_drag(app, pos2(to.0, to.1), XF, mods);
pen_release(app);
}
fn knots(app: &App) -> Vec<[Vec2; 3]> {
app.pen.as_ref().map(|p| p.knots.clone()).unwrap_or_default()
}
/// The one shape on the stage: its id and its path in stage space.
fn shape(app: &App) -> (ElementId, Path) {
let els = app.s.visible_elements();
assert_eq!(els.len(), 1, "one shape");
let ElementKind::Shape(sh) = &els[0].kind else { panic!("a shape") };
(els[0].id, sh.path.transformed(&els[0].transform))
}
fn anchors(p: &Path) -> Vec<(f32, f32)> {
p.editable_anchors().into_iter().map(|(_, q)| (q.x.round(), q.y.round())).collect()
}
/// An open drawing object, selected, so the Pen shows its points.
fn with_object(d: &str) -> App {
let mut app = app();
app.run("draw.path", json!({"d": d, "object": true}));
let (el, _) = shape(&app);
app.run("element.select", json!({"ids": [el.0]}));
assert!(app.s.selection.contains(app.s.layer, el));
app
}
#[test]
fn clicks_place_corners_drags_pull_mirrored_handles_and_alt_breaks_the_pair() {
let mut app = app();
click(&mut app, 10.0, 10.0, NONE);
drag(&mut app, (100.0, 10.0), (130.0, 40.0), NONE);
assert_eq!(knots(&app), vec![[v(10.0, 10.0); 3], [v(100.0, 10.0), v(70.0, -20.0), v(130.0, 40.0)]]);
// Alt while dragging a new knot moves only the handle ahead.
pen_press(&mut app, pos2(200.0, 10.0), XF, NONE);
pen_drag(&mut app, pos2(220.0, 10.0), XF, NONE);
pen_drag(&mut app, pos2(200.0, 50.0), XF, ALT);
pen_release(&mut app);
assert_eq!(knots(&app)[2], [v(200.0, 10.0), v(180.0, 10.0), v(200.0, 50.0)]);
// A press that barely moves stays a corner.
drag(&mut app, (300.0, 10.0), (301.0, 10.5), NONE);
assert_eq!(knots(&app)[3], [v(300.0, 10.0); 3]);
}
#[test]
fn shift_keeps_segments_and_handles_on_45_degree_steps() {
let mut app = app();
click(&mut app, 100.0, 100.0, NONE);
// Nearly horizontal: the point lands on the horizontal through the knot before.
click(&mut app, 200.0, 108.0, SHIFT);
assert_eq!(knots(&app)[1][0], v(200.0, 100.0));
// Nearly diagonal: on the 45° line, at the pointer's distance along it.
click(&mut app, 260.0, 150.0, SHIFT);
let k = knots(&app)[2][0];
assert!(((k.x - 200.0) - (k.y - 100.0)).abs() < 1e-3 && (k.x - 255.0).abs() < 1e-3, "{k:?}");
// A handle pulled with Shift is vertical here, and its twin mirrors it.
pen_press(&mut app, pos2(400.0, 100.0), XF, NONE);
pen_drag(&mut app, pos2(404.0, 160.0), XF, SHIFT);
pen_release(&mut app);
let k = knots(&app)[3];
assert!((k[2].x - 400.0).abs() < 1e-3 && (k[2].y - 160.0).abs() < 1e-3 && (k[1].y - 40.0).abs() < 1e-3, "{k:?}");
for (from, p) in [(v(0.0, 0.0), v(10.0, 1.0)), (v(5.0, 5.0), v(-20.0, 31.0)), (v(1.0, 2.0), v(1.0, 2.0)), (v(0.0, 0.0), v(f32::NAN, 1.0))] {
let q = constrain_45(from, p);
let d = q - from;
assert!(!d.is_finite() || d.length() < 1e-6 || (d.x.abs() < 1e-3 || d.y.abs() < 1e-3 || (d.x.abs() - d.y.abs()).abs() < 1e-3), "{from:?} {p:?} -> {q:?}");
}
}
#[test]
fn a_click_on_the_last_point_breaks_its_handle_then_finishes() {
// Issue #319, Break Handles: the next segment leaves the point as a sharp corner.
let mut app = app();
click(&mut app, 10.0, 100.0, NONE);
drag(&mut app, (100.0, 100.0), (140.0, 60.0), NONE);
assert_eq!(pen_hover(&app, pos2(101.0, 99.0), XF, NONE), PenHover::Corner);
click(&mut app, 101.0, 99.0, NONE);
assert_eq!(knots(&app)[1], [v(100.0, 100.0), v(60.0, 140.0), v(100.0, 100.0)], "the handle behind stays, the one ahead is gone");
assert_eq!(pen_hover(&app, pos2(100.0, 100.0), XF, NONE), PenHover::Finish);
click(&mut app, 200.0, 100.0, NONE);
// A click on the (corner) last point finishes the open path: one shape.
click(&mut app, 200.0, 100.0, NONE);
assert!(app.pen.is_none());
let (_, p) = shape(&app);
assert_eq!(anchors(&p), [(10.0, 100.0), (100.0, 100.0), (200.0, 100.0)]);
assert!(matches!(p.cmds[1], PathCmd::CubicTo(..)) && matches!(p.cmds[2], PathCmd::LineTo(_)), "curved in, straight out: {:?}", p.cmds);
}
#[test]
fn a_drag_from_the_last_point_pulls_a_new_handle_ahead_alone() {
let mut app = app();
click(&mut app, 10.0, 100.0, NONE);
drag(&mut app, (100.0, 100.0), (140.0, 60.0), NONE);
drag(&mut app, (100.0, 100.0), (100.0, 160.0), NONE);
assert_eq!(knots(&app)[1], [v(100.0, 100.0), v(60.0, 140.0), v(100.0, 160.0)]);
assert_eq!(knots(&app).len(), 2, "no point was added, and the path isn't finished");
}
#[test]
fn alt_drag_on_the_last_point_draws_its_segment_again() {
// Issue #319, Adjust Last Node: the segment as it was shows until the release.
let mut app = app();
click(&mut app, 10.0, 100.0, NONE);
drag(&mut app, (100.0, 100.0), (140.0, 60.0), NONE);
let was = knots(&app)[1];
assert_eq!(pen_hover(&app, pos2(100.0, 100.0), XF, ALT), PenHover::Adjust);
pen_press(&mut app, pos2(100.0, 100.0), XF, ALT);
assert_eq!(app.pen.as_ref().map(|p| p.grip), Some(PenGrip::Adjust { was }), "the ghost");
pen_drag(&mut app, pos2(100.0, 150.0), XF, ALT);
assert_eq!(knots(&app)[1], [v(100.0, 100.0), v(100.0, 50.0), v(100.0, 150.0)]);
// Back onto the point: nothing changes.
pen_drag(&mut app, pos2(100.5, 100.0), XF, ALT);
assert_eq!(knots(&app)[1], was);
pen_drag(&mut app, pos2(130.0, 100.0), XF, ALT);
pen_release(&mut app);
assert_eq!(knots(&app), vec![[v(10.0, 100.0); 3], [v(100.0, 100.0), v(70.0, 100.0), v(130.0, 100.0)]]);
assert_eq!(app.pen.as_ref().map(|p| (p.grip, p.dragging)), Some((PenGrip::New, false)));
}
#[test]
fn the_first_point_closes_with_a_hint_and_keys_finish_or_step_back() {
let mut app = app();
click(&mut app, 10.0, 10.0, NONE);
click(&mut app, 110.0, 10.0, NONE);
click(&mut app, 110.0, 90.0, NONE);
assert_eq!(pen_hover(&app, pos2(12.0, 11.0), XF, NONE), PenHover::Close);
assert_eq!(pen_hover(&app, pos2(60.0, 60.0), XF, NONE), PenHover::Place);
click(&mut app, 12.0, 11.0, NONE);
assert!(app.pen.is_none());
let (_, p) = shape(&app);
assert!(matches!(p.cmds.last(), Some(PathCmd::Close)));
assert_eq!(anchors(&p).len(), 3);
// Esc finishes an open path; Backspace takes the last point back.
let ctx = egui::Context::default();
let key = |app: &mut App, key: Key| {
let mut input = egui::RawInput::default();
input.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
let mut out = ctx.run_ui(input, |ui| consume_keys(app, ui.ctx()));
out.textures_delta.clear();
};
click(&mut app, 300.0, 10.0, NONE);
click(&mut app, 400.0, 10.0, NONE);
click(&mut app, 400.0, 90.0, NONE);
key(&mut app, Key::Backspace);
assert_eq!(knots(&app).len(), 2);
key(&mut app, Key::Escape);
assert!(app.pen.is_none());
assert_eq!(app.s.visible_elements().len(), 2, "the open path is kept");
}
#[test]
fn on_a_selected_path_a_click_converts_then_deletes_a_point_and_adds_one_on_the_outline() {
// Issue #319, Add/Remove Nodes: caret, then minus, on a point; plus on a segment.
let mut app = with_object("M0 100 C30 40 70 40 100 100 C130 160 170 160 200 100 L300 100");
let at = pos2(100.0, 100.0);
assert_eq!(pen_hover(&app, at, XF, NONE), PenHover::Corner);
click(&mut app, at.x, at.y, NONE);
assert!(app.pen.is_none(), "no path was started");
let (_, p) = shape(&app);
assert_eq!(anchors(&p).len(), 4);
assert_eq!(pen_hover(&app, at, XF, NONE), PenHover::Delete, "a corner now: {:?}", p.cmds);
click(&mut app, at.x, at.y, NONE);
assert_eq!(anchors(&shape(&app).1), [(0.0, 100.0), (200.0, 100.0), (300.0, 100.0)]);
// The outline between points takes a point; away from it a click starts a path.
assert_eq!(pen_hover(&app, pos2(250.0, 101.0), XF, NONE), PenHover::Add);
click(&mut app, 250.0, 101.0, NONE);
assert_eq!(anchors(&shape(&app).1), [(0.0, 100.0), (200.0, 100.0), (250.0, 100.0), (300.0, 100.0)]);
assert!(app.pen.is_none());
assert_eq!(pen_hover(&app, pos2(250.0, 300.0), XF, NONE), PenHover::Place);
// Each was one undo step.
for n in [3, 4, 4] {
app.run("edit.undo", json!({}));
assert_eq!(anchors(&shape(&app).1).len(), n);
}
}
#[test]
fn an_unselected_path_is_drawn_over_and_ctrl_click_selects_it() {
let mut app = with_object("M0 100 L100 100 L200 100");
app.run("edit.deselect", json!({}));
// Its points aren't showing: the Pen starts a path there (a T-junction, say).
assert_eq!(pen_hover(&app, pos2(100.0, 100.0), XF, NONE), PenHover::Place);
click(&mut app, 100.0, 100.0, NONE);
assert_eq!(knots(&app).len(), 1);
app.pen = None;
// Ctrl-click selects it, and now the Pen edits it.
click(&mut app, 150.0, 100.0, CTRL);
assert!(app.pen.is_none() && app.s.selection.len() == 1);
assert_eq!(pen_hover(&app, pos2(100.0, 100.0), XF, NONE), PenHover::Delete);
assert_eq!(pen_hover(&app, pos2(150.0, 100.0), XF, NONE), PenHover::Add);
click(&mut app, 400.0, 400.0, CTRL);
assert!(app.s.selection.is_empty(), "Ctrl-click on nothing lets go");
}
#[test]
fn an_open_end_is_continued_and_the_other_end_closes_the_path() {
let mut app = with_object("M0 100 L100 100 C130 100 150 80 150 50");
let (id, _) = shape(&app);
assert_eq!(pen_hover(&app, pos2(150.0, 50.0), XF, NONE), PenHover::Continue);
assert_eq!(pen_hover(&app, pos2(0.0, 100.0), XF, NONE), PenHover::Continue);
// Press on the end and pull a handle ahead, then two more points, then finish.
drag(&mut app, (150.0, 50.0), (150.0, 20.0), NONE);
let pen = app.pen.clone().expect("continuing");
assert_eq!(pen.extends, Some((id, false)));
assert_eq!(pen.knots, vec![[v(150.0, 50.0), v(150.0, 80.0), v(150.0, 20.0)]]);
click(&mut app, 200.0, 0.0, NONE);
click(&mut app, 300.0, 0.0, NONE);
commit_pen(&mut app, false);
let (same, p) = shape(&app);
assert_eq!(same, id, "the same object, longer");
assert_eq!(anchors(&p), [(0.0, 100.0), (100.0, 100.0), (150.0, 50.0), (200.0, 0.0), (300.0, 0.0)]);
assert!(matches!(p.cmds[3], PathCmd::CubicTo(..)), "the handle pulled from the end curves the join");
// From the start, round to the other end: the ring shows there and the path closes.
click(&mut app, 0.0, 100.0, NONE);
assert_eq!(app.pen.as_ref().and_then(|p| p.extends), Some((id, true)));
click(&mut app, 0.0, 200.0, NONE);
assert_eq!(pen_hover(&app, pos2(300.0, 1.0), XF, NONE), PenHover::Close);
assert_eq!(pen_hover(&app, pos2(0.0, 100.0), XF, NONE), PenHover::Place, "its own first knot doesn't close it");
click(&mut app, 300.0, 1.0, NONE);
assert!(app.pen.is_none());
let (same, p) = shape(&app);
assert_eq!(same, id);
assert!(matches!(p.cmds.last(), Some(PathCmd::Close)), "{:?}", p.cmds);
assert_eq!(anchors(&p).len(), 6);
// Closed, it has no end to continue: its points convert and delete.
assert_eq!(pen_hover(&app, pos2(300.0, 0.0), XF, NONE), PenHover::Delete);
// Two undo steps take both continuations back.
app.run("edit.undo", json!({}));
app.run("edit.undo", json!({}));
assert_eq!(anchors(&shape(&app).1).len(), 3);
}
#[test]
fn the_pen_edits_the_points_of_selected_merged_drawings() {
let mut app = app();
app.run("draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000", "object": false}));
app.run("edit.deselect", json!({}));
assert_eq!(pen_hover(&app, pos2(100.0, 0.0), XF, NONE), PenHover::Place, "not selected: a path starts here");
click(&mut app, 50.0, 0.0, CTRL);
assert!(!app.s.selection.is_empty());
assert_eq!(raw_shown(&app).anchors.len(), 4);
assert_eq!(pen_hover(&app, pos2(50.0, 0.0), XF, NONE), PenHover::Add);
click(&mut app, 50.0, 0.0, NONE);
assert!(app.pen.is_none());
assert_eq!(raw_shown(&app).anchors.len(), 5);
// A corner point is deleted: the outline closes up across it.
assert_eq!(pen_hover(&app, pos2(100.0, 0.0), XF, NONE), PenHover::Delete);
click(&mut app, 100.0, 0.0, NONE);
assert_eq!(raw_shown(&app).anchors.len(), 4);
assert!(app.pen.is_none());
}
}
/// Subselection on a merged drawing (ADR 0042), on a headless app: a raw rectangle with
/// its outline at the stage origin, stage and screen coordinates the same.
mod raw {
+1 -1
View File
@@ -425,7 +425,7 @@ mod tests {
assert!(!app.s.is_dirty(), "the edit has not reached Session yet");
assert!(!safe_to_install(&app), "restarting would discard the text buffer");
app.text_edit = None;
app.pen = Some(crate::pathtools::PenPath { knots: vec![[anicraft_engine::geom::Vec2::ZERO; 3]], dragging: false });
app.pen = Some(crate::pathtools::PenPath { knots: vec![[anicraft_engine::geom::Vec2::ZERO; 3]], ..Default::default() });
assert!(!app.s.is_dirty());
assert!(!safe_to_install(&app), "an unfinished Pen path is also pending work");
app.pen = None;