mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-22 18:41:44 +01:00
chore: merge main into m7/bones-spring
This commit is contained in:
commit
2423b42533
47 files changed
+3409
-372
No files matched your search
@@ -101,6 +101,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| ActionScript 3.0 timeline subset: lexer, recursive-descent parser, semicolon insertion, number formatting, lowering to the script IR, the evaluator (types, coercions, operators, `Math`, listeners for enter-frame and keys) | `crates/actions/src/as3/` | ECMA-262 *ECMAScript Language Specification*, 3rd edition (Ecma International, 1999: lexical grammar §7, expressions and statements §11–12, `ToNumber`/`ToString` §9.3, §9.8.1), on which ActionScript 3.0 builds; Adobe's public *ActionScript 3.0 Language Reference* (`MovieClip`, `MouseEvent`, `Event`, `KeyboardEvent`, `flash.ui.Keyboard`, `Math`, `EventDispatcher.addEventListener` and `removeEventListener`, `navigateToURL`) and *Learning ActionScript 3.0* guide for the language's additions and behaviour (ADR 0013) | Public specifications and documentation only; hand-written, no Adobe code, compilers or players; names used nominatively. |
|
||||
| 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)). |
|
||||
| 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/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). |
|
||||
|
||||
@@ -16,6 +16,23 @@
|
||||
effect, blending and filters change on every pose, one undo step, the armature intact.
|
||||
* Headless: `bone.set_translation`, `bone.set_spring`, `bone.enable_springs`, `slide_x` /
|
||||
`slide_y` on `bone.pose`; `bone.info` reports slides, springs and each bone's swing.
|
||||
* **Ease presets, custom eases and saved eases** (ADR 0081, M7).
|
||||
* One ease menu in the timeline header, Properties › Frame and the Motion Editor: No Ease,
|
||||
**Classic Ease** with a strength, and **Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce
|
||||
and Elastic**, each In, Out and In Out, drawn as curves; then your saved eases.
|
||||
* **Custom Ease** window: click the curve to add a point, drag points and handles (one undo
|
||||
step per drag), double-click for smooth or corner, right-click to delete, type a point's
|
||||
time and value, or use the keyboard (`[` `]`, arrows, `S`, `+`, Delete). Overshoot is
|
||||
allowed; time never runs backwards.
|
||||
* **Saved eases** live in the document and are offered to every classic tween and Motion
|
||||
Editor property; **Copy Ease** / **Paste Ease** carry an ease between tweens.
|
||||
* Classic tweens can **ease each property separately** (position, rotation, scale, colour,
|
||||
filters), and instance filters now tween.
|
||||
* Animate files: custom eases of several segments and per-property eases import exactly.
|
||||
* Headless: `ease.info`, `ease.set`, `ease.add_point`, `ease.move_point`, `ease.move_handle`,
|
||||
`ease.delete_point`, `ease.convert_point`, `ease.separate`, `ease.save`, `ease.delete`,
|
||||
`ease.rename`, `ease.list`, `ease.copy`, `ease.paste`; `timeline.set_easing` takes `group`
|
||||
and every ease (`{"saved": name}`, `{"custom": …}`).
|
||||
|
||||
* **Camera, second slice: layer depth, attaching layers and colour** (ADR 0082, M7).
|
||||
* **Layer depth in perspective**: through the camera, a pinhole with a fixed focal length
|
||||
|
||||
@@ -545,7 +545,7 @@ pub fn pose_at(layer: &Layer, frame: u32) -> Option<Pose> {
|
||||
let idx = layer.keyframe_index_at(frame)?;
|
||||
let kf: &Keyframe = layer.keyframes.get(idx)?;
|
||||
let here = kf.pose.allowed(arm);
|
||||
let (Some(tween), None) = (kf.tween, &kf.motion) else { return Some(here) };
|
||||
let (Some(tween), None) = (&kf.tween, &kf.motion) else { return Some(here) };
|
||||
let Some(next) = layer.keyframes.get(idx + 1) else { return Some(here) };
|
||||
if next.start != kf.end() || frame == kf.start {
|
||||
return Some(here);
|
||||
|
||||
+790
-151
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,307 @@
|
||||
use super::*;
|
||||
|
||||
fn all() -> Vec<Easing> {
|
||||
let mut v: Vec<Easing> = Easing::named().collect();
|
||||
v.extend([Easing::Classic(-60.0), Easing::Classic(100.0), Easing::CubicBezier(0.25, 0.1, 0.25, 1.0), Easing::Custom(Arc::new(wave()))]);
|
||||
v
|
||||
}
|
||||
|
||||
/// Three segments that overshoot both ways.
|
||||
fn wave() -> CustomEase {
|
||||
CustomEase::from_flat(&[(0.0, 0.0), (0.1, 0.6), (0.2, 1.3), (0.3, 1.3), (0.4, 1.3), (0.5, -0.2), (0.6, 0.4), (0.7, 1.0), (0.9, 1.0), (1.0, 1.0)].map(|(x, y)| Vec2::new(x, y))).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoints_fixed() {
|
||||
for e in all() {
|
||||
assert!(e.apply(0.0).abs() < 1e-4, "{e:?}");
|
||||
assert!((e.apply(1.0) - 1.0).abs() < 1e-4, "{e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_at_known_times() {
|
||||
use std::f32::consts::PI;
|
||||
let cases: [(Easing, f32, f32); 22] = [
|
||||
(Easing::Linear, 0.3, 0.3),
|
||||
(Easing::QuadIn, 0.5, 0.25),
|
||||
(Easing::QuadOut, 0.5, 0.75),
|
||||
(Easing::QuadInOut, 0.25, 0.125),
|
||||
(Easing::CubicIn, 0.5, 0.125),
|
||||
(Easing::CubicOut, 0.5, 0.875),
|
||||
(Easing::QuartIn, 0.5, 0.0625),
|
||||
(Easing::QuartInOut, 0.75, 0.96875),
|
||||
(Easing::QuintIn, 0.5, 0.03125),
|
||||
(Easing::QuintOut, 0.5, 0.96875),
|
||||
(Easing::SineIn, 0.5, 1.0 - std::f32::consts::FRAC_1_SQRT_2),
|
||||
(Easing::SineOut, 1.0 / 3.0, 0.5),
|
||||
(Easing::SineInOut, 0.25, 0.5 * (1.0 - std::f32::consts::FRAC_1_SQRT_2)),
|
||||
// (c + 1)/8 − c/4 with c = 1.70158: dips below zero first.
|
||||
(Easing::BackIn, 0.5, -0.087_697_5),
|
||||
(Easing::BackOut, 0.5, 1.087_697_5),
|
||||
(Easing::CircIn, 0.6, 0.2),
|
||||
(Easing::CircOut, 0.5, 0.866_025_4),
|
||||
(Easing::BounceOut, 0.5, 0.765_625),
|
||||
(Easing::BounceIn, 0.5, 0.234_375),
|
||||
(Easing::BounceOut, 1.0 / 2.75, 1.0),
|
||||
// −2⁻⁵ · sin(−5.75 · 2π/3) = −1/64; Out is its mirror.
|
||||
(Easing::ElasticIn, 0.5, -0.015_625),
|
||||
(Easing::ElasticOut, 0.5, 1.015_625),
|
||||
];
|
||||
for (e, t, want) in cases {
|
||||
assert!((e.apply(t) - want).abs() < 1e-5, "{e:?} at {t}: {} vs {want}", e.apply(t));
|
||||
}
|
||||
assert!((Easing::Classic(-100.0).apply(0.5) - 0.25).abs() < 1e-6);
|
||||
assert!((Easing::Classic(100.0).apply(0.5) - 0.75).abs() < 1e-6);
|
||||
assert!((Easing::SineIn.apply(1.0 / 3.0) - (1.0 - (PI / 6.0).cos())).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_mirrors_in_and_in_out_is_symmetric() {
|
||||
for f in EaseFamily::ALL {
|
||||
let (i, o, io) = (Easing::preset(f, EaseDir::In), Easing::preset(f, EaseDir::Out), Easing::preset(f, EaseDir::InOut));
|
||||
for k in 0..=40 {
|
||||
let t = k as f32 / 40.0;
|
||||
assert!((o.apply(t) - (1.0 - i.apply(1.0 - t))).abs() < 1e-5, "{f:?} at {t}");
|
||||
assert!((io.apply(t) + io.apply(1.0 - t) - 1.0).abs() < 1e-5, "{f:?} at {t}");
|
||||
assert!((io.apply(t * 0.5) - 0.5 * i.apply(t)).abs() < 1e-5, "{f:?} at {t}");
|
||||
}
|
||||
assert_eq!(Easing::preset(f, EaseDir::In).family(), Some((f, EaseDir::In)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monotonic_families_never_turn_back_and_the_others_overshoot() {
|
||||
for e in all() {
|
||||
let overshoots = matches!(e.family(), Some((EaseFamily::Back | EaseFamily::Elastic, _))) || e.custom().is_some();
|
||||
// Bounce turns back (off the floor) without leaving 0..1.
|
||||
let turns = overshoots || matches!(e.family(), Some((EaseFamily::Bounce, _)));
|
||||
let (mut lo, mut hi, mut prev, mut turned) = (0.0f32, 1.0f32, -1e-6f32, false);
|
||||
for i in 0..=400 {
|
||||
let v = e.apply(i as f32 / 400.0);
|
||||
turned |= v < prev - 1e-4;
|
||||
prev = v;
|
||||
lo = lo.min(v);
|
||||
hi = hi.max(v);
|
||||
}
|
||||
assert_eq!(turned, turns, "{e:?}");
|
||||
assert_eq!(lo < -1e-3 || hi > 1.0 + 1e-3, overshoots, "{e:?}: {lo}..{hi}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_is_clamped() {
|
||||
assert_eq!(Easing::Linear.apply(f32::NAN), 0.0);
|
||||
assert_eq!(Easing::QuadIn.apply(5.0), 1.0);
|
||||
assert_eq!(Easing::ElasticOut.apply(f32::INFINITY), 0.0);
|
||||
assert!(Easing::CubicBezier(f32::NAN, 0.0, 1.0, 1.0).apply(0.5).is_finite());
|
||||
assert!(Easing::Classic(f32::INFINITY).apply(0.5).is_finite());
|
||||
assert!(Easing::Custom(Arc::new(wave())).apply(f32::NAN).is_finite());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bezier_forms_draw_the_same_curves() {
|
||||
// Exact for these.
|
||||
for e in [Easing::Linear, Easing::QuadIn, Easing::QuadOut, Easing::CubicIn, Easing::CubicOut, Easing::BackIn, Easing::BackOut, Easing::Classic(-60.0), Easing::Classic(100.0), Easing::CubicBezier(0.2, 1.4, 0.6, -0.3)] {
|
||||
let (a, b, c, d) = e.as_bezier().unwrap();
|
||||
let bez = Easing::CubicBezier(a, b, c, d);
|
||||
for i in 0..=20 {
|
||||
let t = i as f32 / 20.0;
|
||||
assert!((e.apply(t) - bez.apply(t)).abs() < 1e-3, "{e:?} at {t}");
|
||||
}
|
||||
}
|
||||
for e in [Easing::QuadInOut, Easing::CubicInOut] {
|
||||
let (a, b, c, d) = e.as_bezier().unwrap();
|
||||
let bez = Easing::CubicBezier(a, b, c, d);
|
||||
assert!((0..=20).all(|i| (e.apply(i as f32 / 20.0) - bez.apply(i as f32 / 20.0)).abs() < 0.08), "{e:?}");
|
||||
}
|
||||
// One curve can't draw a bounce or a multi-segment ease.
|
||||
assert_eq!(Easing::BounceOut.as_bezier(), None);
|
||||
assert_eq!(Easing::Custom(Arc::new(wave())).as_bezier(), None);
|
||||
let one = Easing::Custom(Arc::new(CustomEase::from_bezier(0.1, 0.9, 0.3, 1.2)));
|
||||
assert_eq!(one.as_bezier(), Some((0.1, 0.9, 0.3, 1.2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_preset_becomes_a_custom_curve_for_the_graph() {
|
||||
for e in all() {
|
||||
let c = e.to_custom();
|
||||
assert!(c.points().len() <= MAX_EASE_POINTS, "{e:?}");
|
||||
let exact = matches!(e.family(), Some((EaseFamily::Quad | EaseFamily::Cubic | EaseFamily::Back | EaseFamily::Bounce, _))) || e.family().is_none();
|
||||
let tol = if exact { 2e-4 } else { 5e-3 };
|
||||
let mut worst = 0.0f32;
|
||||
for i in 0..=500 {
|
||||
let t = i as f32 / 500.0;
|
||||
worst = worst.max((c.apply(t) - e.apply(t)).abs());
|
||||
}
|
||||
assert!(worst < tol, "{e:?}: off by {worst} with {} points", c.points().len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ease_in_is_slow_at_start() {
|
||||
assert!(Easing::QuadIn.apply(0.25) < 0.25);
|
||||
assert!(Easing::QuadOut.apply(0.25) > 0.25);
|
||||
assert!(Easing::Classic(-100.0).apply(0.25) < 0.25);
|
||||
assert!(Easing::Classic(100.0).apply(0.25) > 0.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_round_trip_and_older_aliases_still_read() {
|
||||
for e in Easing::named() {
|
||||
let n = e.name().unwrap();
|
||||
assert_eq!(Easing::from_name(&n), Some(e.clone()), "{n}");
|
||||
// The file form is the same name.
|
||||
assert_eq!(serde_json::to_string(&e).unwrap(), format!("\"{n}\""));
|
||||
}
|
||||
assert_eq!(Easing::from_name("back in-out"), Some(Easing::BackInOut));
|
||||
assert_eq!(Easing::from_name("ease_in"), Some(Easing::QuadIn));
|
||||
assert_eq!(Easing::from_name("Smooth"), Some(Easing::CubicBezier(0.25, 0.1, 0.25, 1.0)));
|
||||
assert_eq!(Easing::from_name("wobble"), None);
|
||||
assert_eq!(Easing::named().count(), 28);
|
||||
assert_eq!(Easing::BounceInOut.label(), "Bounce In Out");
|
||||
// Older files.
|
||||
let old: Vec<Easing> = serde_json::from_str(r#"["QuadIn", {"Classic": 30.0}, {"CubicBezier": [0.1, 0.2, 0.3, 0.4]}, "Linear"]"#).unwrap();
|
||||
assert_eq!(old, [Easing::QuadIn, Easing::Classic(30.0), Easing::CubicBezier(0.1, 0.2, 0.3, 0.4), Easing::Linear]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_segment_curve_evaluates_continuously_through_its_points() {
|
||||
let c = wave();
|
||||
assert_eq!(c.points().len(), 4);
|
||||
for p in c.points() {
|
||||
assert!((c.apply(p.at.x) - p.at.y).abs() < 1e-5 || p.at.x == 0.0, "{p:?}");
|
||||
}
|
||||
let mut prev = c.apply(0.0);
|
||||
for i in 1..=10_000 {
|
||||
let v = c.apply(i as f32 / 10_000.0);
|
||||
assert!((v - prev).abs() < 2e-3, "a jump at {i}: {prev} → {v}");
|
||||
prev = v;
|
||||
}
|
||||
// Rises past the end value, then falls back below where it was, as drawn.
|
||||
assert!(c.apply(0.3) > 1.2 && c.apply(0.55) < 0.4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_a_point_keeps_the_shape() {
|
||||
let c = wave();
|
||||
let (d, i) = c.insert_at(0.42).unwrap();
|
||||
assert_eq!((d.points().len(), i), (5, 2));
|
||||
assert!(d.points()[2].smooth);
|
||||
for k in 0..=200 {
|
||||
let t = k as f32 / 200.0;
|
||||
assert!((c.apply(t) - d.apply(t)).abs() < 1e-4, "at {t}");
|
||||
}
|
||||
// Not at an end or on a point.
|
||||
assert!(c.insert_at(0.0).is_none() && c.insert_at(1.0).is_none() && c.insert_at(0.3).is_none() && c.insert_at(f32::NAN).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_edits_keep_time_running_forwards() {
|
||||
let c = wave();
|
||||
// Dragging a point past its neighbour stops at the neighbour.
|
||||
let d = c.move_point(1, Vec2::new(0.95, 2.0)).unwrap();
|
||||
assert_eq!(d.points()[1].at, Vec2::new(0.6, 2.0));
|
||||
// The ends don't move.
|
||||
assert!(c.move_point(0, Vec2::new(0.5, 0.5)).is_none() && c.move_point(3, Vec2::new(0.5, 0.5)).is_none());
|
||||
// A handle dragged backwards in time stops at its point.
|
||||
let h = c.move_handle(1, Handle::Out, Vec2::new(0.0, 5.0)).unwrap();
|
||||
assert_eq!(h.points()[1].out.x, 0.0);
|
||||
// A smooth point's other handle turns with it.
|
||||
let s = c.set_smooth(1, true).unwrap();
|
||||
let t = s.move_handle(1, Handle::Out, Vec2::new(0.45, 1.5)).unwrap();
|
||||
let p = t.points()[1];
|
||||
assert!(p.smooth && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-4, "{p:?}");
|
||||
// A corner has its handles on the point.
|
||||
let k = s.set_smooth(1, false).unwrap();
|
||||
assert_eq!((k.points()[1].h_in, k.points()[1].out), (Vec2::ZERO, Vec2::ZERO));
|
||||
// Removing.
|
||||
assert_eq!(c.remove(2).unwrap().points().len(), 3);
|
||||
assert!(c.remove(0).is_none() && c.remove(3).is_none());
|
||||
}
|
||||
|
||||
/// Every segment's x control points lie between its ends, so x never decreases.
|
||||
fn assert_forwards(c: &CustomEase) {
|
||||
let pts = c.points();
|
||||
assert!(pts.len() >= 2 && pts.len() <= MAX_EASE_POINTS);
|
||||
assert_eq!((pts[0].at, pts[pts.len() - 1].at), (Vec2::ZERO, Vec2::new(1.0, 1.0)));
|
||||
for i in 0..pts.len() - 1 {
|
||||
let [a, b, cc, d] = c.segment(i).unwrap();
|
||||
assert!(a.x <= b.x && b.x <= d.x && a.x <= cc.x && cc.x <= d.x, "segment {i}: {a:?} {b:?} {cc:?} {d:?}");
|
||||
for v in [a, b, cc, d] {
|
||||
assert!(v.is_finite() && v.y.abs() <= MAX_EASE_Y + 1e-4);
|
||||
}
|
||||
}
|
||||
for k in 0..=100 {
|
||||
assert!(c.apply(k as f32 / 100.0).is_finite());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn x_stays_monotonic_after_any_edit() {
|
||||
let mut seed = 0x2545_f491_4f6c_dd1du64;
|
||||
let mut rnd = || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % 10_000) as f32 / 10_000.0
|
||||
};
|
||||
let mut c = wave();
|
||||
for _ in 0..3000 {
|
||||
let n = c.points().len();
|
||||
let i = (rnd() * n as f32) as usize % n;
|
||||
let to = Vec2::new(rnd() * 1.6 - 0.3, rnd() * 30.0 - 15.0);
|
||||
let next = match (rnd() * 6.0) as u32 {
|
||||
0 => c.insert_at(rnd()).map(|r| r.0),
|
||||
1 => c.move_point(i, to),
|
||||
2 => c.move_handle(i, Handle::In, to),
|
||||
3 => c.move_handle(i, Handle::Out, to),
|
||||
4 => c.set_smooth(i, rnd() > 0.5),
|
||||
_ => if n > 6 { c.remove(i) } else { None },
|
||||
};
|
||||
if let Some(d) = next {
|
||||
assert_forwards(&d);
|
||||
c = d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_curves_are_repaired() {
|
||||
// NaN, reversed x, out-of-range values and handles reaching backwards.
|
||||
let nan = EasePoint { at: Vec2::new(f32::NAN, 0.5), ..Default::default() };
|
||||
let pts = vec![
|
||||
EasePoint { at: Vec2::new(1.0, 1.0), h_in: Vec2::new(-5.0, f32::INFINITY), ..Default::default() },
|
||||
EasePoint { at: Vec2::new(0.6, 400.0), h_in: Vec2::new(3.0, 0.0), out: Vec2::new(-2.0, 0.0), smooth: true },
|
||||
nan,
|
||||
EasePoint { at: Vec2::new(0.2, -1.0), ..Default::default() },
|
||||
EasePoint { at: Vec2::new(-3.0, 0.0), out: Vec2::new(f32::NAN, 1.0), ..Default::default() },
|
||||
];
|
||||
let c = CustomEase::new(pts);
|
||||
assert_eq!(c.points().len(), 4);
|
||||
assert_forwards(&c);
|
||||
assert_eq!(c.points()[2].at, Vec2::new(0.6, MAX_EASE_Y));
|
||||
// Thousands of points are thinned to the cap, and stay a valid curve.
|
||||
let many: Vec<EasePoint> = (0..20_000).map(|i| EasePoint { at: Vec2::new(((i * 7919) % 20_000) as f32 / 20_000.0, (i as f32 * 0.37).sin()), out: Vec2::new(0.5, 0.0), h_in: Vec2::new(-0.5, 0.0), smooth: false }).collect();
|
||||
let c = CustomEase::new(many);
|
||||
assert_eq!(c.points().len(), MAX_EASE_POINTS);
|
||||
assert_forwards(&c);
|
||||
// Too few points: the line.
|
||||
assert_eq!(CustomEase::new(vec![nan]), CustomEase::linear());
|
||||
// From a file, the same repairs.
|
||||
let f: CustomEase = serde_json::from_str(r#"{"points": [{"at": {"x": 0.9, "y": 3.0}}, {"at": {"x": 0.1, "y": 0.0}, "out": {"x": -1.0, "y": 0.0}}, {"at": {"x": 0.5, "y": 0.5}}]}"#).unwrap();
|
||||
assert_forwards(&f);
|
||||
let e: Easing = serde_json::from_str(r#"{"Custom": {"points": []}}"#).unwrap();
|
||||
assert_eq!(e, Easing::Custom(Arc::new(CustomEase::linear())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_eases_round_trip_through_files_and_flat_lists() {
|
||||
let e = Easing::Custom(Arc::new(wave()));
|
||||
let back: Easing = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
|
||||
assert_eq!(back, e);
|
||||
let flat = wave().to_flat();
|
||||
assert_eq!(flat.len(), 10);
|
||||
assert_eq!(CustomEase::from_flat(&flat), Some(wave()));
|
||||
assert!(CustomEase::from_flat(&flat[..9]).is_none());
|
||||
}
|
||||
+54
-9
@@ -276,12 +276,12 @@ pub(crate) fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&
|
||||
}
|
||||
return Some((kf.start, Cow::Owned(els)));
|
||||
}
|
||||
let Some(tween) = kf.tween else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
||||
let Some(tween) = &kf.tween else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
||||
let Some(next) = layer.keyframes.get(idx + 1) else { return Some((kf.start, Cow::Borrowed(&kf.elements))) };
|
||||
if next.start != kf.end() || frame == kf.start {
|
||||
return Some((kf.start, Cow::Borrowed(&kf.elements)));
|
||||
}
|
||||
let t = tween.easing.apply((frame - kf.start) as f32 / kf.duration.max(1) as f32);
|
||||
let t = Progress::of(tween, (frame - kf.start) as f32 / kf.duration.max(1) as f32);
|
||||
let morph = tween.kind == TweenKind::Shape;
|
||||
let path = guide.map(|g| (g, tween.orient));
|
||||
let pairs = if morph && !kf.hints.is_empty() { crate::hints::hint_pairs(kf, next) } else { Vec::new() };
|
||||
@@ -297,11 +297,42 @@ pub(crate) fn evaluate_tweened<'a>(layer: &'a Layer, frame: u32, guide: Option<&
|
||||
Some((kf.start, Cow::Owned(els)))
|
||||
}
|
||||
|
||||
/// How far a classic tween has gone, eased, for each property group (ADR 0081): `main` for
|
||||
/// what has no group (outlines, fills, strokes, a group's members), the rest each by its
|
||||
/// group's ease (the tween's own when the group has none).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Progress {
|
||||
pub main: f32,
|
||||
pub position: f32,
|
||||
pub rotation: f32,
|
||||
pub scale: f32,
|
||||
pub color: f32,
|
||||
pub filters: f32,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
/// Everything at `t`.
|
||||
pub fn uniform(t: f32) -> Progress {
|
||||
Progress { main: t, position: t, rotation: t, scale: t, color: t, filters: t }
|
||||
}
|
||||
|
||||
/// `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);
|
||||
}
|
||||
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) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpolates two elements; `None` when they cannot tween. With `morph` (a shape tween),
|
||||
/// shapes of different structure blend through [`anicraft_geom::morph`], steered by `hints`
|
||||
/// (shape hints in each element's own space, ADR 0023); otherwise a shape changes only when
|
||||
/// both keyframes share its structure.
|
||||
fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft_geom::Vec2, anicraft_geom::Vec2)], guide: Option<(&PathWalk, bool)>) -> Option<Element> {
|
||||
fn interpolate(a: &Element, b: &Element, pr: Progress, morph: bool, hints: &[(anicraft_geom::Vec2, anicraft_geom::Vec2)], guide: Option<(&PathWalk, bool)>) -> Option<Element> {
|
||||
let t = pr.main;
|
||||
let kind = match (&a.kind, &b.kind) {
|
||||
(ElementKind::Shape(sa), ElementKind::Shape(sb)) => {
|
||||
// Warped on both keyframes (ADR 0079): the pins tween and bend the outline as drawn.
|
||||
@@ -336,7 +367,15 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft
|
||||
};
|
||||
ElementKind::Shape(Shape { path, fill, stroke, fill_rule: sa.fill_rule, merge: sa.merge, warp })
|
||||
}
|
||||
(ElementKind::Symbol { symbol: s1, .. }, ElementKind::Symbol { symbol: s2, .. }) if s1 == s2 => a.kind.clone(),
|
||||
// An instance tweens its filters when both keyframes have the same kinds in the same
|
||||
// order (Animate's rule); otherwise they hold.
|
||||
(ElementKind::Symbol { symbol: s1, filters: fa, .. }, ElementKind::Symbol { symbol: s2, filters: fb, .. }) if s1 == s2 => {
|
||||
let mut k = a.kind.clone();
|
||||
if let (ElementKind::Symbol { filters, .. }, Some(lerped)) = (&mut k, crate::filter::lerp_filters(fa, fb, pr.filters)) {
|
||||
*filters = lerped;
|
||||
}
|
||||
k
|
||||
}
|
||||
// Text tweens its placement and colour effect; the words stay the first keyframe's.
|
||||
(ElementKind::Text(_), ElementKind::Text(_)) => a.kind.clone(),
|
||||
(ElementKind::Camera, ElementKind::Camera) => ElementKind::Camera,
|
||||
@@ -346,7 +385,7 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft
|
||||
let mut members = ma.clone();
|
||||
for (la, lb) in members.layers.iter_mut().zip(&mb.layers) {
|
||||
let (Some(ka), Some(kb)) = (la.keyframe_at(0), lb.keyframe_at(0)) else { continue };
|
||||
let els: Vec<Arc<Element>> = ka.elements.iter().enumerate().map(|(i, x)| kb.elements.get(i).and_then(|y| interpolate(x, y, t, morph, &[], None)).map_or_else(|| x.clone(), Arc::new)).collect();
|
||||
let els: Vec<Arc<Element>> = ka.elements.iter().enumerate().map(|(i, x)| kb.elements.get(i).and_then(|y| interpolate(x, y, Progress::uniform(t), morph, &[], None)).map_or_else(|| x.clone(), Arc::new)).collect();
|
||||
if let Some(k) = Arc::make_mut(la).keyframe_mut(0) {
|
||||
k.elements = els;
|
||||
}
|
||||
@@ -355,11 +394,17 @@ fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, hints: &[(anicraft
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let mut transform = a.transform.decompose().lerp(&b.transform.decompose(), t).compose();
|
||||
if let Some((g, orient)) = guide {
|
||||
transform = follow(g, orient, &a.transform, &b.transform, t, transform);
|
||||
let (da, db) = (a.transform.decompose(), b.transform.decompose());
|
||||
let mut d = da.lerp(&db, pr.position);
|
||||
if pr.rotation != pr.position || pr.scale != pr.position {
|
||||
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);
|
||||
}
|
||||
Some(Element { id: a.id, name: a.name.clone(), transform, color: a.color.lerp(&b.color, t), kind })
|
||||
let mut transform = d.compose();
|
||||
if let Some((g, orient)) = guide {
|
||||
transform = follow(g, orient, &a.transform, &b.transform, pr.position, transform);
|
||||
}
|
||||
Some(Element { id: a.id, name: a.name.clone(), transform, color: a.color.lerp(&b.color, pr.color), kind })
|
||||
}
|
||||
|
||||
/// What a timeline is evaluated inside of.
|
||||
|
||||
@@ -484,3 +484,99 @@ fn shape_hints_survive_a_round_trip_and_old_files_have_none() {
|
||||
let old: Keyframe = serde_json::from_str(r#"{"start":0,"duration":3}"#).unwrap();
|
||||
assert!(old.hints.is_empty());
|
||||
}
|
||||
|
||||
/// A tween from (0, 0), unturned, full size and opaque to (100, 0), half a turn, double size
|
||||
/// and transparent, over 10 frames.
|
||||
fn group_doc(tween: Tween) -> Document {
|
||||
let mut d = Document::default();
|
||||
let mut a = shape_el(10, 0.0);
|
||||
a.color = ColorEffect::Alpha(1.0);
|
||||
let mut b = shape_el(10, 100.0);
|
||||
b.transform = Affine::translate(100.0, 0.0).mul(&Affine::rotate(std::f32::consts::FRAC_PI_2)).mul(&Affine::scale(2.0, 2.0));
|
||||
b.color = ColorEffect::Alpha(0.0);
|
||||
let mut k0 = Keyframe::new(0, 10);
|
||||
k0.elements.push(Arc::new(a));
|
||||
k0.tween = Some(tween);
|
||||
let mut k1 = Keyframe::new(10, 1);
|
||||
k1.elements.push(Arc::new(b));
|
||||
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_tweens_ease_each_property_group_its_own_way() {
|
||||
use crate::EaseGroup;
|
||||
let mut tw = Tween::new(Easing::Linear, TweenKind::Classic);
|
||||
tw.set_ease(EaseGroup::Position, Some(Easing::BounceOut));
|
||||
tw.set_ease(EaseGroup::Scale, Some(Easing::QuadIn));
|
||||
tw.set_ease(EaseGroup::Color, Some(Easing::CubicOut));
|
||||
let d = group_doc(tw.clone());
|
||||
let it = |f| {
|
||||
let dl = evaluate(&d, f);
|
||||
let i = &dl.items[0];
|
||||
(i.transform.decompose(), i.color.mul[3])
|
||||
};
|
||||
let (m, alpha) = it(5);
|
||||
assert!((m.tx - 100.0 * Easing::BounceOut.apply(0.5)).abs() < 1e-2, "position: {}", m.tx);
|
||||
assert!((m.sx - (1.0 + Easing::QuadIn.apply(0.5))).abs() < 1e-3, "scale: {}", m.sx);
|
||||
// Rotation has no ease of its own: the tween's (linear).
|
||||
assert!((m.rotation - std::f32::consts::FRAC_PI_4).abs() < 1e-3, "rotation: {}", m.rotation);
|
||||
assert!((alpha - (1.0 - Easing::CubicOut.apply(0.5))).abs() < 1e-3, "colour: {alpha}");
|
||||
// Groups stay in order, once each; clearing one gives it the tween's ease again.
|
||||
tw.set_ease(EaseGroup::Position, Some(Easing::SineIn));
|
||||
assert_eq!(tw.groups.iter().map(|g| g.0).collect::<Vec<_>>(), [EaseGroup::Position, EaseGroup::Scale, EaseGroup::Color]);
|
||||
tw.set_ease(EaseGroup::Scale, None);
|
||||
assert_eq!(tw.ease(EaseGroup::Scale), &Easing::Linear);
|
||||
// With one ease for everything, every group follows it exactly as before.
|
||||
let one = group_doc(Tween::new(Easing::QuadOut, TweenKind::Classic));
|
||||
let mut same = Tween::new(Easing::QuadOut, TweenKind::Classic);
|
||||
for g in EaseGroup::ALL {
|
||||
same.set_ease(g, Some(Easing::QuadOut));
|
||||
}
|
||||
let both = group_doc(same);
|
||||
for f in 0..=10 {
|
||||
assert_eq!(evaluate(&one, f).items[0].transform, evaluate(&both, f).items[0].transform);
|
||||
}
|
||||
// Older files' tweens (no groups) still read.
|
||||
let t: Tween = serde_json::from_str(r#"{"easing": "QuadIn"}"#).unwrap();
|
||||
assert!(t.groups.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_ease_drives_a_classic_tween() {
|
||||
let c = crate::CustomEase::from_flat(&[(0.0, 0.0), (0.2, 1.5), (0.4, 1.5), (0.5, 1.2), (0.6, 0.9), (0.8, 1.0), (1.0, 1.0)].map(|(x, y)| anicraft_geom::Vec2::new(x, y))).unwrap();
|
||||
let e = Easing::Custom(Arc::new(c.clone()));
|
||||
let d = tween_doc(e);
|
||||
for f in 0..10 {
|
||||
let x = evaluate(&d, f).items[0].transform.translation().x;
|
||||
assert!((x - 100.0 * c.apply(f as f32 / 10.0)).abs() < 1e-2, "frame {f}: {x}");
|
||||
}
|
||||
// It overshoots past the second keyframe and comes back.
|
||||
assert!(evaluate(&d, 5).items[0].transform.translation().x > 100.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_filters_tween_when_they_pair_up() {
|
||||
use crate::Filter;
|
||||
let mut d = Document::default();
|
||||
let sid = SymbolId(90);
|
||||
d.library.push(Arc::new(Symbol { id: sid, name: "Clip".into(), kind: SymbolKind::MovieClip, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(Layer::new(LayerId(91), "x"))] } }));
|
||||
let inst = |filters: Vec<Filter>| Element { id: ElementId(92), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: sid, loop_mode: Default::default(), first_frame: 0, blend: Default::default(), filters, events: Vec::new() } };
|
||||
let blur = |b: f32| Filter::Blur { blur_x: b, blur_y: b, quality: 1 };
|
||||
let mut tw = Tween::new(Easing::Linear, TweenKind::Classic);
|
||||
tw.set_ease(crate::EaseGroup::Filters, Some(Easing::QuadIn));
|
||||
let mut k0 = Keyframe::new(0, 10);
|
||||
k0.elements.push(Arc::new(inst(vec![blur(0.0), Filter::new("glow").unwrap()])));
|
||||
k0.tween = Some(tw);
|
||||
let mut k1 = Keyframe::new(10, 1);
|
||||
k1.elements.push(Arc::new(inst(vec![blur(40.0), Filter::new("glow").unwrap()])));
|
||||
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
|
||||
let filters = |f| match &crate::evaluate_layer_elements(&d.timeline(0).layers[0], f).unwrap().1[0].kind {
|
||||
ElementKind::Symbol { filters, .. } => filters.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
assert_eq!(filters(5)[0], blur(40.0 * 0.25), "eased by the filters group's ease");
|
||||
// Lists that don't pair up hold the first keyframe's.
|
||||
assert_eq!(crate::filter::lerp_filters(&[blur(1.0)], &[Filter::new("glow").unwrap()], 0.5), None);
|
||||
assert_eq!(crate::filter::lerp_filters(&[blur(1.0)], &[blur(1.0), blur(2.0)], 0.5), None);
|
||||
}
|
||||
@@ -401,6 +401,60 @@ impl Filter {
|
||||
}
|
||||
}
|
||||
|
||||
/// The classic tween between two filter lists (ADR 0081): when both have the same kinds in the
|
||||
/// same order, each filter's numbers and colours travel (switches such as Inner and Knockout,
|
||||
/// and the quality, stay the first keyframe's; ramps travel stop by stop when they have as
|
||||
/// many stops). `None` when the lists are equal or don't pair up: the first list holds.
|
||||
pub fn lerp_filters(a: &[Filter], b: &[Filter], t: f32) -> Option<Vec<Filter>> {
|
||||
if a == b || a.len() != b.len() {
|
||||
return None;
|
||||
}
|
||||
a.iter().zip(b).map(|(x, y)| x.lerp(y, t)).collect()
|
||||
}
|
||||
|
||||
fn ramp_lerp(a: &[GradientStop], b: &[GradientStop], t: f32) -> Vec<GradientStop> {
|
||||
if a.len() != b.len() {
|
||||
return a.to_vec();
|
||||
}
|
||||
a.iter().zip(b).map(|(x, y)| GradientStop { offset: anicraft_geom::lerp(x.offset, y.offset, t), color: x.color.lerp(y.color, t) }).collect()
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
/// This filter part way to `o` (see [`lerp_filters`]); `None` when `o` is another kind.
|
||||
pub fn lerp(&self, o: &Filter, t: f32) -> Option<Filter> {
|
||||
use anicraft_geom::lerp as l;
|
||||
Some(match (self, o) {
|
||||
(Filter::Blur { blur_x, blur_y, quality }, Filter::Blur { blur_x: bx, blur_y: by, .. }) => Filter::Blur { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), quality: *quality },
|
||||
(Filter::DropShadow { blur_x, blur_y, strength, quality, angle, distance, color, inner, knockout, hide_object }, Filter::DropShadow { blur_x: bx, blur_y: by, strength: s, angle: an, distance: d, color: c, .. }) => {
|
||||
Filter::DropShadow { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), strength: l(*strength, *s, t), quality: *quality, angle: l(*angle, *an, t), distance: l(*distance, *d, t), color: color.lerp(*c, t), inner: *inner, knockout: *knockout, hide_object: *hide_object }
|
||||
}
|
||||
(Filter::Glow { blur_x, blur_y, strength, quality, color, inner, knockout }, Filter::Glow { blur_x: bx, blur_y: by, strength: s, color: c, .. }) => {
|
||||
Filter::Glow { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), strength: l(*strength, *s, t), quality: *quality, color: color.lerp(*c, t), inner: *inner, knockout: *knockout }
|
||||
}
|
||||
(Filter::Bevel { blur_x, blur_y, strength, quality, angle, distance, shadow_color, highlight_color, side, knockout }, Filter::Bevel { blur_x: bx, blur_y: by, strength: s, angle: an, distance: d, shadow_color: sc, highlight_color: hc, .. }) => Filter::Bevel {
|
||||
blur_x: l(*blur_x, *bx, t),
|
||||
blur_y: l(*blur_y, *by, t),
|
||||
strength: l(*strength, *s, t),
|
||||
quality: *quality,
|
||||
angle: l(*angle, *an, t),
|
||||
distance: l(*distance, *d, t),
|
||||
shadow_color: shadow_color.lerp(*sc, t),
|
||||
highlight_color: highlight_color.lerp(*hc, t),
|
||||
side: *side,
|
||||
knockout: *knockout,
|
||||
},
|
||||
(Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout }, Filter::GradientGlow { blur_x: bx, blur_y: by, strength: s, angle: an, distance: d, stops: st, .. }) => {
|
||||
Filter::GradientGlow { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), strength: l(*strength, *s, t), quality: *quality, angle: l(*angle, *an, t), distance: l(*distance, *d, t), stops: ramp_lerp(stops, st, t), side: *side, knockout: *knockout }
|
||||
}
|
||||
(Filter::GradientBevel { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout }, Filter::GradientBevel { blur_x: bx, blur_y: by, strength: s, angle: an, distance: d, stops: st, .. }) => {
|
||||
Filter::GradientBevel { blur_x: l(*blur_x, *bx, t), blur_y: l(*blur_y, *by, t), strength: l(*strength, *s, t), quality: *quality, angle: l(*angle, *an, t), distance: l(*distance, *d, t), stops: ramp_lerp(stops, st, t), side: *side, knockout: *knockout }
|
||||
}
|
||||
(Filter::AdjustColor { brightness, contrast, saturation, hue }, Filter::AdjustColor { brightness: b, contrast: c, saturation: s, hue: h }) => Filter::AdjustColor { brightness: l(*brightness, *b, t), contrast: l(*contrast, *c, t), saturation: l(*saturation, *s, t), hue: l(*hue, *h, t) },
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -84,7 +84,7 @@ impl Layer {
|
||||
/// Whether keyframe `i` starts a shape tween that runs into the next keyframe.
|
||||
pub fn is_shape_tween(&self, i: usize) -> bool {
|
||||
let (Some(k), Some(next)) = (self.keyframes.get(i), self.keyframes.get(i + 1)) else { return false };
|
||||
k.motion.is_none() && k.tween.is_some_and(|t| t.kind == TweenKind::Shape) && next.start == k.end()
|
||||
k.motion.is_none() && k.tween.as_ref().is_some_and(|t| t.kind == TweenKind::Shape) && next.start == k.end()
|
||||
}
|
||||
|
||||
/// The shape tween whose hints `frame` shows or edits, and which side: a frame inside a
|
||||
|
||||
+96
-5
@@ -35,7 +35,7 @@ pub mod swatch;
|
||||
|
||||
pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, REST_SNAP, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at};
|
||||
pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_decode, base64_encode, decode_png, image_to_png};
|
||||
pub use easing::Easing;
|
||||
pub use easing::{CustomEase, EaseDir, EaseFamily, EasePoint, Easing, Handle, MAX_EASE_NAME, MAX_EASE_POINTS, MAX_EASE_Y, MAX_SAVED_EASES, SavedEase, ease_name};
|
||||
pub use color_effect::{ADVANCED_ADD, ADVANCED_MUL, ColorEffect, ColorStyle, ColorTransform};
|
||||
pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre};
|
||||
pub use library::{FolderId, LibraryEntry, LibraryFolder, LibraryItem, LibraryTree, NameError};
|
||||
@@ -1002,9 +1002,56 @@ pub enum TweenKind {
|
||||
Shape,
|
||||
}
|
||||
|
||||
/// The property groups a classic tween may ease separately (ADR 0081), as Animate's custom
|
||||
/// ease offers them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum EaseGroup {
|
||||
/// Where the object is (and how far along a motion guide).
|
||||
Position,
|
||||
/// Its rotation and skew.
|
||||
Rotation,
|
||||
Scale,
|
||||
/// Its colour effect.
|
||||
Color,
|
||||
Filters,
|
||||
}
|
||||
|
||||
impl EaseGroup {
|
||||
pub const ALL: [EaseGroup; 5] = [EaseGroup::Position, EaseGroup::Rotation, EaseGroup::Scale, EaseGroup::Color, EaseGroup::Filters];
|
||||
|
||||
/// The name commands use (`position`, `rotation`, `scale`, `color`, `filters`).
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
EaseGroup::Position => "position",
|
||||
EaseGroup::Rotation => "rotation",
|
||||
EaseGroup::Scale => "scale",
|
||||
EaseGroup::Color => "color",
|
||||
EaseGroup::Filters => "filters",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_key(k: &str) -> Option<EaseGroup> {
|
||||
let k = k.trim().to_ascii_lowercase();
|
||||
let k = if k == "colour" { "color" } else { k.as_str() };
|
||||
EaseGroup::ALL.into_iter().find(|g| g.key() == k)
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
EaseGroup::Position => "Position",
|
||||
EaseGroup::Rotation => "Rotation",
|
||||
EaseGroup::Scale => "Scale",
|
||||
EaseGroup::Color => "Colour",
|
||||
EaseGroup::Filters => "Filters",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tween from a keyframe to the next one.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Tween {
|
||||
/// The ease of everything, and of each property group without its own.
|
||||
#[serde(default)]
|
||||
pub easing: Easing,
|
||||
#[serde(default, skip_serializing_if = "is_classic")]
|
||||
@@ -1012,6 +1059,37 @@ pub struct Tween {
|
||||
/// On a guided layer: turn with the motion guide as it bends.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub orient: bool,
|
||||
/// Property groups eased their own way (classic tweens; ADR 0081). Empty: one ease for all
|
||||
/// properties.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub groups: Vec<(EaseGroup, Easing)>,
|
||||
}
|
||||
|
||||
impl Tween {
|
||||
/// A tween of `kind` eased by `easing`.
|
||||
pub fn new(easing: Easing, kind: TweenKind) -> Tween {
|
||||
Tween { easing, kind, ..Tween::default() }
|
||||
}
|
||||
|
||||
/// The ease of group `g`: its own, else the tween's.
|
||||
pub fn ease(&self, g: EaseGroup) -> &Easing {
|
||||
self.groups.iter().find(|(x, _)| *x == g).map_or(&self.easing, |(_, e)| e)
|
||||
}
|
||||
|
||||
/// Whether group `g` has its own ease.
|
||||
pub fn has_own(&self, g: EaseGroup) -> bool {
|
||||
self.groups.iter().any(|(x, _)| *x == g)
|
||||
}
|
||||
|
||||
/// Gives group `g` its own ease, or (with `None`) the tween's again. Groups are kept in
|
||||
/// their fixed order, once each.
|
||||
pub fn set_ease(&mut self, g: EaseGroup, e: Option<Easing>) {
|
||||
self.groups.retain(|(x, _)| *x != g);
|
||||
if let Some(e) = e {
|
||||
self.groups.push((g, e));
|
||||
}
|
||||
self.groups.sort_by_key(|(x, _)| EaseGroup::ALL.iter().position(|y| y == x));
|
||||
}
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
@@ -1697,6 +1775,9 @@ pub struct Document {
|
||||
/// How the grid and the guides look (ADR 0076).
|
||||
#[serde(default, skip_serializing_if = "aids_is_default")]
|
||||
pub aids: Arc<Aids>,
|
||||
/// Eases the artist saved by name (ADR 0081), offered with the presets.
|
||||
#[serde(default, skip_serializing_if = "eases_is_empty")]
|
||||
pub eases: Arc<Vec<SavedEase>>,
|
||||
/// Next free id for layers, elements and symbols.
|
||||
pub next_id: u64,
|
||||
}
|
||||
@@ -1734,6 +1815,8 @@ struct DocumentFile {
|
||||
swatches: Arc<Vec<Swatch>>,
|
||||
#[serde(default)]
|
||||
aids: Arc<Aids>,
|
||||
#[serde(default)]
|
||||
eases: Arc<Vec<SavedEase>>,
|
||||
#[serde(default = "first_id")]
|
||||
next_id: u64,
|
||||
}
|
||||
@@ -1744,7 +1827,7 @@ impl From<DocumentFile> for Document {
|
||||
if let Some(tl) = f.timeline {
|
||||
scenes.insert(0, Arc::new(Scene { name: "Scene 1".into(), timeline: tl, guides: Vec::new() }));
|
||||
}
|
||||
Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, publish: f.publish, aids: f.aids, swatches: f.swatches, next_id: f.next_id }
|
||||
Document { stage: f.stage, scenes, library: f.library, bitmaps: f.bitmaps, sounds: f.sounds, library_tree: f.library_tree, document_class: f.document_class, publish: f.publish, aids: f.aids, swatches: f.swatches, eases: f.eases, next_id: f.next_id }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1756,6 +1839,10 @@ fn library_tree_is_empty(t: &Arc<LibraryTree>) -> bool {
|
||||
t.is_empty()
|
||||
}
|
||||
|
||||
fn eases_is_empty(e: &Arc<Vec<SavedEase>>) -> bool {
|
||||
e.is_empty()
|
||||
}
|
||||
|
||||
fn aids_is_default(a: &Arc<Aids>) -> bool {
|
||||
a.is_default()
|
||||
}
|
||||
@@ -1769,13 +1856,13 @@ static NO_TIMELINE: Timeline = Timeline { layers: Vec::new() };
|
||||
|
||||
impl PartialEq for Document {
|
||||
fn eq(&self, o: &Document) -> bool {
|
||||
self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) && arc_eq(&self.publish, &o.publish) && arc_eq(&self.aids, &o.aids) && arc_eq(&self.swatches, &o.swatches)
|
||||
self.stage == o.stage && self.next_id == o.next_id && self.document_class == o.document_class && arcs_eq(&self.scenes, &o.scenes) && arcs_eq(&self.library, &o.library) && arcs_eq(&self.bitmaps, &o.bitmaps) && arcs_eq(&self.sounds, &o.sounds) && arc_eq(&self.library_tree, &o.library_tree) && arc_eq(&self.publish, &o.publish) && arc_eq(&self.aids, &o.aids) && arc_eq(&self.swatches, &o.swatches) && arc_eq(&self.eases, &o.eases)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Document {
|
||||
fn default() -> Self {
|
||||
let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), publish: Arc::default(), aids: Arc::default(), swatches: default_swatches(), next_id: 1 };
|
||||
let mut d = Document { stage: Stage::default(), scenes: vec![Arc::new(Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Arc::default(), document_class: String::new(), publish: Arc::default(), aids: Arc::default(), swatches: default_swatches(), eases: Arc::default(), next_id: 1 };
|
||||
let id = LayerId(d.alloc_id());
|
||||
d.timeline_mut(0).layers.push(Arc::new(Layer::new(id, "Layer 1")));
|
||||
d
|
||||
@@ -1857,6 +1944,10 @@ impl Document {
|
||||
if aids != *self.aids {
|
||||
self.aids = Arc::new(aids);
|
||||
}
|
||||
let eases = easing::sanitized_eases(&self.eases);
|
||||
if eases != *self.eases {
|
||||
self.eases = Arc::new(eases);
|
||||
}
|
||||
let mut max_id = 0u64;
|
||||
let scan = |l: &Layer, max_id: &mut u64| {
|
||||
*max_id = (*max_id).max(l.id.0);
|
||||
|
||||
+10
-10
@@ -312,7 +312,7 @@ impl Props {
|
||||
}
|
||||
|
||||
/// A property keyframe.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PropertyKey {
|
||||
/// Frames from the span's first frame.
|
||||
pub frame: u32,
|
||||
@@ -377,7 +377,7 @@ impl Track {
|
||||
}
|
||||
}
|
||||
Err(i) => {
|
||||
let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or(Easing::Linear, |k| k.ease);
|
||||
let ease = i.checked_sub(1).and_then(|p| self.keys.get(p)).map_or(Easing::Linear, |k| k.ease.clone());
|
||||
if self.keys.len() < MAX_KEYS {
|
||||
self.keys.insert(i, PropertyKey { frame, value, ease });
|
||||
}
|
||||
@@ -1112,9 +1112,9 @@ impl MotionTween {
|
||||
.iter()
|
||||
.filter_map(|t| {
|
||||
let v = t.value_at(frame as f32)?;
|
||||
let ease = t.segment_at(frame).and_then(|i| t.keys.get(i)).map_or(Easing::Linear, |k| k.ease);
|
||||
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 }));
|
||||
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();
|
||||
@@ -1190,7 +1190,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn track(p: Property, keys: &[(u32, f32, Easing)]) -> Track {
|
||||
Track { property: p, keys: keys.iter().map(|&(frame, value, ease)| PropertyKey { frame, value, ease }).collect() }
|
||||
Track { property: p, keys: keys.iter().map(|(frame, value, ease)| PropertyKey { frame: *frame, value: *value, ease: ease.clone() }).collect() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1250,7 +1250,7 @@ mod tests {
|
||||
t.keys[0].ease = Easing::CubicOut;
|
||||
}
|
||||
m.set_key(Property::X, 4, 70.0, 50.0);
|
||||
assert_eq!(m.track(Property::X).map(|t| t.keys[1].ease), Some(Easing::CubicOut));
|
||||
assert_eq!(m.track(Property::X).map(|t| t.keys[1].ease.clone()), Some(Easing::CubicOut));
|
||||
assert!(m.remove_key(Property::X, 4) && !m.remove_key(Property::X, 4));
|
||||
assert!(m.remove_key(Property::X, 0) && m.remove_key(Property::X, 10));
|
||||
assert!(m.tracks.is_empty(), "an emptied track goes");
|
||||
@@ -1347,7 +1347,7 @@ mod tests {
|
||||
/// X 0 → 100 and Y 0 → 100 over frames 0..20 with `ease` on both.
|
||||
fn diagonal(ease: Easing) -> MotionTween {
|
||||
let mut m = MotionTween::new(ElementId(1));
|
||||
m.tracks = vec![track(Property::X, &[(0, 0.0, ease), (20, 100.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, ease), (20, 100.0, Easing::Linear)])];
|
||||
m.tracks = vec![track(Property::X, &[(0, 0.0, ease.clone()), (20, 100.0, Easing::Linear)]), track(Property::Y, &[(0, 0.0, ease), (20, 100.0, Easing::Linear)])];
|
||||
m
|
||||
}
|
||||
|
||||
@@ -1355,7 +1355,7 @@ mod tests {
|
||||
fn a_straight_path_reproduces_linear_and_eased_xy() {
|
||||
let base = el(1, 0.0, 0.0);
|
||||
for ease in [Easing::Linear, Easing::QuadIn, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3)] {
|
||||
let plain = diagonal(ease);
|
||||
let plain = diagonal(ease.clone());
|
||||
let mut m = plain.clone();
|
||||
assert!(m.set_path(&line((0.0, 0.0), (100.0, 100.0)), &Props::of(&base), 20));
|
||||
assert_eq!(m.tracks, plain.tracks, "ends already in place: the keys stay as they were");
|
||||
@@ -1607,7 +1607,7 @@ mod tests {
|
||||
assert!(m.set_path(&p, &Props::of(&base), 20));
|
||||
assert_eq!(m.pin(1, 10, &Props::of(&base)), Ok(()));
|
||||
if let Some(t) = m.track_mut(Property::X) {
|
||||
t.keys[1].ease = second;
|
||||
t.keys[1].ease = second.clone();
|
||||
}
|
||||
let x = m.track(Property::X).cloned().unwrap();
|
||||
for i in 0..=80 {
|
||||
@@ -1702,7 +1702,7 @@ mod tests {
|
||||
let props = Props::of(&base);
|
||||
let mut cases = Vec::new();
|
||||
for ease in [Easing::Linear, Easing::QuadOut, Easing::CubicBezier(0.2, 0.9, 0.4, 1.3), Easing::CubicBezier(0.5, -0.6, 0.5, 1.6)] {
|
||||
let mut m = diagonal(ease);
|
||||
let mut m = diagonal(ease.clone());
|
||||
assert!(m.set_path(&quarter(100.0), &props, 20));
|
||||
cases.push(m.clone());
|
||||
// Position keys in the middle are timing keys, not pins, in ADR 0030 files.
|
||||
|
||||
@@ -41,7 +41,7 @@ fn key(start: u32, duration: u32, elements: Vec<Arc<Element>>, tween: Option<Eas
|
||||
|
||||
/// Builds the demo document: a bouncing ball, a spinning star, a pulsing sun over hills.
|
||||
pub fn demo() -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), next_id: 1 };
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), next_id: 1 };
|
||||
let (w, h) = (1280.0, 720.0);
|
||||
|
||||
// --- library -------------------------------------------------------------------------
|
||||
@@ -85,7 +85,8 @@ pub fn demo() -> Document {
|
||||
let ball_keys = poses
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &(start, (x, y, sx, sy), easing))| {
|
||||
.map(|(i, (start, (x, y, sx, sy), easing))| {
|
||||
let (start, (x, y, sx, sy), easing) = (*start, (*x, *y, *sx, *sy), easing.clone());
|
||||
let next = poses.get(i + 1).map_or(LEN, |p| p.0);
|
||||
let e = Element { id: ball_inst, name: "ball".into(), transform: pose(x, y, sx, sy, 0.0), color: ColorEffect::default(), kind: instance(ball_id) };
|
||||
key(start, next - start, vec![Arc::new(e)], (i + 1 < poses.len()).then_some(easing))
|
||||
@@ -147,7 +148,7 @@ pub fn demo() -> Document {
|
||||
/// whose last frame traces a line and goes back to the menu.
|
||||
pub fn interactive() -> Document {
|
||||
use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, Target};
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), next_id: 1 };
|
||||
let mut d = Document { stage: Stage { width: 1280, height: 720, fps: 24.0, background: Rgba::hex(0x1d2333) }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), next_id: 1 };
|
||||
const LEN: u32 = 36;
|
||||
let solid = |c: u32| Paint::Solid(Rgba::hex(c));
|
||||
|
||||
@@ -211,7 +212,7 @@ pub fn interactive() -> Document {
|
||||
/// `shapes` shapes each, keyed every 12 frames over `frames` frames with classic tweens.
|
||||
/// Every element keeps one `Arc<Path>` across its keyframes, as a real tweened shape does.
|
||||
pub fn stress(layers: u32, shapes: u32, frames: u32) -> Document {
|
||||
let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), next_id: 1 };
|
||||
let mut d = Document { stage: Stage { width: 1920, height: 1080, fps: 24.0, background: Rgba::WHITE }, scenes: vec![Arc::new(crate::Scene::new("Scene 1"))], library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: Default::default(), swatches: Arc::new(crate::swatch::default_set()), eases: Default::default(), next_id: 1 };
|
||||
let (layers, shapes, frames) = (layers.clamp(1, 1000), shapes.clamp(1, 100_000), frames.clamp(1, 10_000));
|
||||
let mut seed = 0x2545_f491_u32;
|
||||
let mut rnd = move || {
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
//! Eases (ADR 0081): the preset library, custom eases edited point by point, eases saved in
|
||||
//! the document, and copy and paste of an ease between tweens.
|
||||
//!
|
||||
//! Every command addresses one ease, the *target*:
|
||||
//!
|
||||
//! * a classic or shape tween's (the span at `layer?`/`frame?`), or with `group` one property
|
||||
//! group's (`position`, `rotation`, `scale`, `color`, `filters`; ADR 0081 §3);
|
||||
//! * a motion tween's property segment (the span at `layer?`/`frame?`, the segment the frame is
|
||||
//! in, of `property`, or every property when it is left out);
|
||||
//! * a saved ease (`saved: name`).
|
||||
//!
|
||||
//! Point edits turn a preset into the custom curve that draws it ([`Easing::to_custom`]) and
|
||||
//! edit that. The curve stays valid whatever is asked (time never runs backwards; values stay
|
||||
//! within bounds; see [`CustomEase`]); an edit that can't apply (moving an end, deleting the
|
||||
//! last point between them) is an error that changes nothing.
|
||||
|
||||
use crate::cmds_timeline::target;
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{CustomEase, EaseGroup, Easing, Handle, LayerId, MAX_SAVED_EASES, Property, SavedEase, Tween, TweenKind, ease_name};
|
||||
use anicraft_geom::Vec2;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("ease.info", "Ease", "", None, "{target: layer?, frame?, group? | property? | saved?} → the ease (as easing params take it), its label, and its curve as points (exact unless the preset is fitted)", false, info as crate::RunFn),
|
||||
c("ease.set", "Set Ease", "", None, "{easing: a preset name | {classic: n} | {bezier: [..]} | {custom: ..} | {saved: name}, layer?, frame?, group? | property? | saved?}", true, set),
|
||||
c("ease.add_point", "Add Ease Point", "", None, "{t: time 0..1 on the curve (its shape stays), layer?, frame?, group? | property? | saved?} → {index}", true, add_point),
|
||||
c("ease.move_point", "Move Ease Point", "", None, "{index, x (time, kept between its neighbours), y (value, may overshoot), layer?, frame?, group? | property? | saved?} (the ends stay at (0, 0) and (1, 1))", true, move_point),
|
||||
c("ease.move_handle", "Move Ease Handle", "", None, "{index, handle: in|out, x, y (absolute; x stays between the point and its neighbour), layer?, frame?, group? | property? | saved?} (a smooth point's other handle turns with it)", true, move_handle),
|
||||
c("ease.delete_point", "Delete Ease Point", "", None, "{index (not an end), layer?, frame?, group? | property? | saved?}", true, delete_point),
|
||||
c("ease.convert_point", "Convert Ease Point", "", None, "{index, smooth: bool (handles in line) or corner (handles on the point), layer?, frame?, group? | property? | saved?}", true, convert_point),
|
||||
c("ease.separate", "Ease Properties Separately", "", None, "{separate: bool, layer?, frame?}: a classic tween with one ease per property group (each starting from the tween's), or one ease for all (the groups' own go)", true, separate),
|
||||
c("ease.save", "Save Ease", "", None, "{name, easing? (default: the target's ease), replace?: bool, layer?, frame?, group? | property?} → saved in the document, offered with the presets", true, save),
|
||||
c("ease.delete", "Delete Saved Ease", "", None, "{name} (tweens using it keep their curves)", true, delete),
|
||||
c("ease.rename", "Rename Saved Ease", "", None, "{name, to}", true, rename),
|
||||
c("ease.list", "Eases", "", None, "{} → the presets (name, label, family, direction) and the eases saved in the document", false, list),
|
||||
c("ease.copy", "Copy Ease", "", None, "{layer?, frame?, group? | property? | saved?}: the ease, for ease.paste", false, copy),
|
||||
c("ease.paste", "Paste Ease", "", None, "{layer?, frame?, group? | property? | saved?}: the copied ease onto this target", true, paste),
|
||||
]
|
||||
}
|
||||
|
||||
/// The one ease a command addresses (see the module docs).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EaseAt {
|
||||
Tween { layer: LayerId, frame: u32, group: Option<EaseGroup> },
|
||||
Motion { layer: LayerId, frame: u32, property: Option<Property> },
|
||||
Saved(String),
|
||||
}
|
||||
|
||||
pub(crate) fn group(p: &Value) -> Result<Option<EaseGroup>> {
|
||||
match opt_str(p, "group")? {
|
||||
None => Ok(None),
|
||||
Some(g) if g.trim().eq_ignore_ascii_case("all") => Ok(None),
|
||||
Some(g) => EaseGroup::from_key(g).map(Some).ok_or_else(|| EngineError::Param(format!("unknown group '{g}' (all, position, rotation, scale, color, filters)"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn property(p: &Value) -> Result<Option<Property>> {
|
||||
match opt_str(p, "property")? {
|
||||
None => Ok(None),
|
||||
Some(k) => Property::from_key(k).map(Some).ok_or_else(|| EngineError::Param(format!("unknown property '{k}'"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ease_target(s: &Session, p: &Value) -> Result<EaseAt> {
|
||||
if let Some(n) = opt_str(p, "saved")? {
|
||||
saved_ease(&s.doc, n)?;
|
||||
return Ok(EaseAt::Saved(n.to_string()));
|
||||
}
|
||||
let (lid, frame) = target(s, p)?;
|
||||
let layer = lid.unwrap_or(s.layer);
|
||||
let l = s.timeline().layer(layer).ok_or_else(|| EngineError::State(format!("no layer with id {}", layer.0)))?;
|
||||
let kf = l.keyframe_at(frame).ok_or_else(|| EngineError::State(format!("frame {} is empty on this layer", frame + 1)))?;
|
||||
if kf.motion.is_some() {
|
||||
if p.get("group").is_some_and(|g| !g.is_null()) {
|
||||
return Err(EngineError::Param("a motion tween eases each property's segments: give 'property', not 'group'".into()));
|
||||
}
|
||||
return Ok(EaseAt::Motion { layer, frame, property: property(p)? });
|
||||
}
|
||||
let Some(t) = &kf.tween else { return Err(EngineError::State(format!("frame {} has no tween; create one first (Insert › Create Classic Tween)", frame + 1))) };
|
||||
let group = group(p)?;
|
||||
if group.is_some() && t.kind == TweenKind::Shape {
|
||||
return Err(EngineError::State("a shape tween has one ease for everything; property groups ease separately in classic tweens".into()));
|
||||
}
|
||||
Ok(EaseAt::Tween { layer, frame, group })
|
||||
}
|
||||
|
||||
pub fn read(s: &Session, at: &EaseAt) -> Result<Easing> {
|
||||
match at {
|
||||
EaseAt::Saved(n) => saved_ease(&s.doc, n),
|
||||
EaseAt::Tween { layer, frame, group } => {
|
||||
let t = s.timeline().layer(*layer).and_then(|l| l.keyframe_at(*frame)).and_then(|k| k.tween.as_ref()).ok_or_else(|| EngineError::State("the tween is gone".into()))?;
|
||||
Ok(group.map_or(&t.easing, |g| t.ease(g)).clone())
|
||||
}
|
||||
EaseAt::Motion { layer, frame, property } => {
|
||||
let kf = s.timeline().layer(*layer).and_then(|l| l.keyframe_at(*frame)).ok_or_else(|| EngineError::State("the tween is gone".into()))?;
|
||||
let m = kf.motion.as_ref().ok_or_else(|| EngineError::State("the motion tween is gone".into()))?;
|
||||
let off = frame.saturating_sub(kf.start);
|
||||
m.tracks.iter().filter(|t| property.is_none_or(|p| p == t.property)).find_map(|t| t.segment_at(off).and_then(|i| t.keys.get(i)).map(|k| k.ease.clone())).ok_or_else(|| not_between(*frame, *property))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn not_between(frame: u32, p: Option<Property>) -> EngineError {
|
||||
EngineError::State(format!("frame {} is not between two property keyframes{}", frame + 1, p.map_or_else(String::new, |o| format!(" of {}", o.label()))))
|
||||
}
|
||||
|
||||
/// Puts `e` on the target; what it set, for the reply.
|
||||
pub(crate) fn write(s: &mut Session, at: &EaseAt, e: Easing) -> Result<Value> {
|
||||
let label = e.label();
|
||||
match at {
|
||||
EaseAt::Saved(n) => {
|
||||
let want = n.to_lowercase();
|
||||
let mut list = (*s.doc.eases).clone();
|
||||
let slot = list.iter_mut().find(|x| x.name.to_lowercase() == want).ok_or_else(|| EngineError::State(format!("no ease is saved as '{n}'")))?;
|
||||
slot.ease = e;
|
||||
let name = slot.name.clone();
|
||||
s.doc.eases = Arc::new(list);
|
||||
Ok(json!({"saved": name, "easing": label}))
|
||||
}
|
||||
EaseAt::Tween { layer, frame, group } => {
|
||||
let l = s.layer_mut(Some(*layer))?;
|
||||
let i = l.keyframe_index_at(*frame).ok_or_else(|| EngineError::State("the tween is gone".into()))?;
|
||||
let t = l.keyframe_mut(i).and_then(|k| k.tween.as_mut()).ok_or_else(|| EngineError::State("the tween is gone".into()))?;
|
||||
match group {
|
||||
Some(g) => t.set_ease(*g, Some(e)),
|
||||
None => t.easing = e,
|
||||
}
|
||||
Ok(json!({"easing": label, "group": group.map_or("all", |g| g.key())}))
|
||||
}
|
||||
EaseAt::Motion { layer, frame, property } => {
|
||||
let l = s.layer_mut(Some(*layer))?;
|
||||
let i = l.keyframe_index_at(*frame).ok_or_else(|| EngineError::State("the tween is gone".into()))?;
|
||||
let kf = l.keyframe_mut(i).ok_or_else(|| EngineError::State("the tween is gone".into()))?;
|
||||
let off = frame.saturating_sub(kf.start);
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("the motion tween is gone".into()))?;
|
||||
let mut set = Vec::new();
|
||||
for t in m.tracks.iter_mut().filter(|t| property.is_none_or(|p| p == t.property)) {
|
||||
if let Some(k) = t.segment_at(off).and_then(|i| t.keys.get_mut(i)) {
|
||||
k.ease = e.clone();
|
||||
set.push(t.property.key());
|
||||
}
|
||||
}
|
||||
if set.is_empty() {
|
||||
return Err(not_between(*frame, *property));
|
||||
}
|
||||
Ok(json!({"easing": label, "properties": set}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An ease's curve for replies: each point and its handles (absolute), and smooth.
|
||||
pub fn points_json(c: &CustomEase) -> Value {
|
||||
Value::Array(c.points().iter().map(|p| json!({"x": p.at.x, "y": p.at.y, "in": [p.at.x + p.h_in.x, p.at.y + p.h_in.y], "out": [p.at.x + p.out.x, p.at.y + p.out.y], "smooth": p.smooth})).collect())
|
||||
}
|
||||
|
||||
fn kind(e: &Easing) -> &'static str {
|
||||
match e {
|
||||
Easing::Classic(_) => "classic",
|
||||
Easing::CubicBezier(..) => "bezier",
|
||||
Easing::Custom(_) => "custom",
|
||||
_ => "preset",
|
||||
}
|
||||
}
|
||||
|
||||
/// The name a saved ease with exactly this curve goes by, if any.
|
||||
pub fn saved_name<'a>(doc: &'a anicraft_doc::Document, e: &Easing) -> Option<&'a str> {
|
||||
doc.eases.iter().find(|x| x.ease == *e).map(|x| x.name.as_str())
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = ease_target(s, p)?;
|
||||
let e = read(s, &at)?;
|
||||
let curve = e.to_custom();
|
||||
let exact = !matches!(e.family(), Some((f, _)) if !matches!(f, anicraft_doc::EaseFamily::Quad | anicraft_doc::EaseFamily::Cubic | anicraft_doc::EaseFamily::Back | anicraft_doc::EaseFamily::Bounce));
|
||||
let mut out = json!({"easing": easing_json(&e), "label": e.label(), "kind": kind(&e), "saved_as": saved_name(&s.doc, &e), "points": points_json(&curve), "exact": exact});
|
||||
if let EaseAt::Tween { layer, frame, .. } = at
|
||||
&& let Some(t) = s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).and_then(|k| k.tween.as_ref())
|
||||
{
|
||||
out["groups"] = Value::Array(t.groups.iter().map(|(g, e)| json!({"group": g.key(), "easing": easing_json(e), "label": e.label()})).collect());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let e = opt_easing_in(&s.doc, p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?;
|
||||
let at = ease_target(s, p)?;
|
||||
write(s, &at, e)
|
||||
}
|
||||
|
||||
/// The target's curve, edited by `f`; `f` saying `None` is the error `why`.
|
||||
fn edit(s: &mut Session, p: &Value, why: &str, f: impl FnOnce(&CustomEase) -> Option<(CustomEase, Value)>) -> Result<Value> {
|
||||
let at = ease_target(s, p)?;
|
||||
let curve = read(s, &at)?.to_custom();
|
||||
let (next, mut reply) = f(&curve).ok_or_else(|| EngineError::State(why.to_string()))?;
|
||||
let n = next.points().len();
|
||||
write(s, &at, Easing::Custom(Arc::new(next)))?;
|
||||
reply["points"] = json!(n);
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
fn index(p: &Value) -> Result<usize> {
|
||||
opt_u32(p, "index")?.map(|i| i as usize).ok_or_else(|| EngineError::Param("param 'index' is required (0 is the start, as ease.info lists the points)".into()))
|
||||
}
|
||||
|
||||
fn add_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let t = f32_req(p, "t")?;
|
||||
edit(s, p, "a point can't go there: inside the curve (0 < t < 1), not on a point, and at most 64 points", |c| c.insert_at(t).map(|(c, i)| (c, json!({"index": i}))))
|
||||
}
|
||||
|
||||
fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (i, x, y) = (index(p)?, f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
edit(s, p, "that point can't move: the ends stay at (0, 0) and (1, 1)", |c| c.move_point(i, Vec2::new(x, y)).map(|d| {
|
||||
let at = d.points().get(i).map_or(Vec2::ZERO, |q| q.at);
|
||||
(d, json!({"index": i, "x": at.x, "y": at.y}))
|
||||
}))
|
||||
}
|
||||
|
||||
fn move_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (i, x, y) = (index(p)?, f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let h = match str_req(p, "handle")?.trim() {
|
||||
"in" => Handle::In,
|
||||
"out" => Handle::Out,
|
||||
other => return Err(EngineError::Param(format!("param 'handle' must be in or out, not '{other}'"))),
|
||||
};
|
||||
edit(s, p, "that point has no such handle (the start has no in handle, the end no out handle)", |c| c.move_handle(i, h, Vec2::new(x, y)).map(|d| (d, json!({"index": i}))))
|
||||
}
|
||||
|
||||
fn delete_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = index(p)?;
|
||||
edit(s, p, "that point can't be deleted: the ends stay", |c| c.remove(i).map(|d| (d, json!({"deleted": i}))))
|
||||
}
|
||||
|
||||
fn convert_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = index(p)?;
|
||||
let smooth = opt_bool(p, "smooth")?.ok_or_else(|| EngineError::Param("param 'smooth' is required (true: smooth, false: corner)".into()))?;
|
||||
edit(s, p, "there is no such point", |c| c.set_smooth(i, smooth).map(|d| (d, json!({"index": i, "smooth": smooth}))))
|
||||
}
|
||||
|
||||
fn separate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let on = opt_bool(p, "separate")?.ok_or_else(|| EngineError::Param("param 'separate' is required".into()))?;
|
||||
let at = ease_target(s, &json!({"layer": p.get("layer"), "frame": p.get("frame")}))?;
|
||||
let EaseAt::Tween { layer, frame, .. } = at else { return Err(EngineError::State("only classic tweens ease property groups separately; a motion tween eases each property already".into())) };
|
||||
if on && s.timeline().layer(layer).and_then(|l| l.keyframe_at(frame)).and_then(|k| k.tween.as_ref()).is_some_and(|t| t.kind == TweenKind::Shape) {
|
||||
return Err(EngineError::State("a shape tween has one ease for everything; property groups ease separately in classic tweens".into()));
|
||||
}
|
||||
let l = s.layer_mut(Some(layer))?;
|
||||
let i = l.keyframe_index_at(frame).ok_or_else(|| EngineError::State("the tween is gone".into()))?;
|
||||
let t: &mut Tween = l.keyframe_mut(i).and_then(|k| k.tween.as_mut()).ok_or_else(|| EngineError::State("the tween is gone".into()))?;
|
||||
if on {
|
||||
for g in EaseGroup::ALL {
|
||||
if !t.has_own(g) {
|
||||
let e = t.easing.clone();
|
||||
t.set_ease(g, Some(e));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
t.groups.clear();
|
||||
}
|
||||
Ok(json!({"separate": on, "groups": t.groups.iter().map(|(g, _)| g.key()).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = ease_name(str_req(p, "name")?).ok_or_else(|| EngineError::Param("param 'name' must have something in it".into()))?;
|
||||
let e = match opt_easing_in(&s.doc, p, "easing")? {
|
||||
Some(e) => e,
|
||||
None => {
|
||||
let at = ease_target(s, p)?;
|
||||
read(s, &at)?
|
||||
}
|
||||
};
|
||||
let replace = opt_bool(p, "replace")?.unwrap_or(false);
|
||||
let mut list = (*s.doc.eases).clone();
|
||||
let full = list.len() >= MAX_SAVED_EASES;
|
||||
match list.iter_mut().find(|x| x.name.to_lowercase() == name.to_lowercase()) {
|
||||
Some(x) if replace => x.ease = e.clone(),
|
||||
Some(x) => return Err(EngineError::State(format!("an ease is already saved as '{}'; pass replace: true to replace it", x.name))),
|
||||
None if full => return Err(EngineError::State(format!("a document keeps at most {MAX_SAVED_EASES} saved eases; delete one first"))),
|
||||
None => list.push(SavedEase { name: name.clone(), ease: e.clone() }),
|
||||
}
|
||||
s.doc.eases = Arc::new(list);
|
||||
Ok(json!({"saved": name, "easing": e.label(), "count": s.doc.eases.len()}))
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_req(p, "name")?;
|
||||
saved_ease(&s.doc, name)?;
|
||||
let want = name.trim().to_lowercase();
|
||||
let mut list = (*s.doc.eases).clone();
|
||||
list.retain(|x| x.name.to_lowercase() != want);
|
||||
s.doc.eases = Arc::new(list);
|
||||
Ok(json!({"deleted": name.trim(), "count": s.doc.eases.len()}))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = str_req(p, "name")?;
|
||||
let to = ease_name(str_req(p, "to")?).ok_or_else(|| EngineError::Param("param 'to' must have something in it".into()))?;
|
||||
saved_ease(&s.doc, name)?;
|
||||
let (from, want) = (name.trim().to_lowercase(), to.to_lowercase());
|
||||
if from != want && s.doc.eases.iter().any(|x| x.name.to_lowercase() == want) {
|
||||
return Err(EngineError::State(format!("an ease is already saved as '{to}'")));
|
||||
}
|
||||
let mut list = (*s.doc.eases).clone();
|
||||
if let Some(x) = list.iter_mut().find(|x| x.name.to_lowercase() == from) {
|
||||
x.name = to.clone();
|
||||
}
|
||||
s.doc.eases = Arc::new(list);
|
||||
Ok(json!({"renamed": name.trim(), "to": to}))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let presets: Vec<Value> = Easing::named()
|
||||
.map(|e| {
|
||||
let (f, d) = e.family().map_or((None, None), |(f, d)| (Some(f.label()), Some(d.label())));
|
||||
json!({"name": e.name(), "label": e.label(), "family": f, "direction": d})
|
||||
})
|
||||
.chain(std::iter::once(json!({"name": "Classic", "label": "Classic Ease", "easing": {"classic": 0}, "strength": "-100 (in) … 100 (out)"})))
|
||||
.collect();
|
||||
let saved: Vec<Value> = s.doc.eases.iter().map(|x| json!({"name": x.name, "label": x.ease.label(), "kind": kind(&x.ease), "easing": easing_json(&x.ease)})).collect();
|
||||
Ok(json!({"presets": presets, "saved": saved}))
|
||||
}
|
||||
|
||||
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = ease_target(s, p)?;
|
||||
let e = read(s, &at)?;
|
||||
let label = e.label();
|
||||
s.ease_clipboard = Some(e);
|
||||
Ok(json!({"copied": label}))
|
||||
}
|
||||
|
||||
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let e = s.ease_clipboard.clone().ok_or_else(|| EngineError::State("no ease has been copied (Copy Ease first)".into()))?;
|
||||
let at = ease_target(s, p)?;
|
||||
write(s, &at, e)
|
||||
}
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
c("motion.set_key", "Property Keyframe", "", None, "{property: x|y|scale_x|scale_y|rotation|skew|alpha|brightness|tint (amount)|tint_red|tint_green|tint_blue (0..255)|red_multiplier|green_multiplier|blue_multiplier|alpha_multiplier (%)|red_offset|green_offset|blue_offset|alpha_offset (-255..255), value (px, %, °), frame?, layer?} (colour properties of several styles compose into Advanced, ADR 0056)", true, set_key as crate::RunFn),
|
||||
c("motion.remove_key", "Remove Property Keyframe", "", None, "{property? (default: every property), frame?, layer?}", true, remove_key),
|
||||
c("motion.set_ease", "Property Ease", "", None, "{easing, property? (default: every property), frame? (inside the segment), layer?}", true, set_ease),
|
||||
c("motion.set_ease", "Property Ease", "", None, "{easing (as timeline.set_easing takes it, saved eases too), property? (default: every property), frame? (inside the segment), layer?}", true, set_ease),
|
||||
c("motion.info", "Motion Tween", "", None, "{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path, its anchors pinned to frames (pins) and where the object is", false, info),
|
||||
c("motion.set_path", "Edit Motion Path", "", None, "{d: SVG path data in stage space (its first subpath; ends are the start and end positions), layer?, frame?}", true, set_path),
|
||||
c("motion.clear_path", "Remove Motion Path", "", None, "{layer?, frame?}: back to the straight path the X/Y curves trace", true, clear_path),
|
||||
@@ -684,22 +684,23 @@ fn remove_key(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn set_ease(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let easing = opt_easing(p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?;
|
||||
let easing = opt_easing_in(&s.doc, p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?;
|
||||
let only = property(p)?;
|
||||
let label = easing.label();
|
||||
let (kf, offset) = motion_span(s, p)?;
|
||||
let start = kf.start;
|
||||
let m = kf.motion.as_mut().ok_or_else(|| EngineError::State("no motion tween here".into()))?;
|
||||
let mut set = Vec::new();
|
||||
for t in m.tracks.iter_mut().filter(|t| only.is_none_or(|o| o == t.property)) {
|
||||
if let Some(k) = t.segment_at(offset).and_then(|i| t.keys.get_mut(i)) {
|
||||
k.ease = easing;
|
||||
k.ease = easing.clone();
|
||||
set.push(t.property.key());
|
||||
}
|
||||
}
|
||||
if set.is_empty() {
|
||||
return Err(EngineError::State(format!("frame {} is not between two property keyframes{}", start + offset + 1, only.map_or_else(String::new, |o| format!(" of {}", o.label())))));
|
||||
}
|
||||
Ok(json!({"easing": easing.label(), "properties": set}))
|
||||
Ok(json!({"easing": label, "properties": set}))
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -714,7 +715,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.tracks
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let keys: Vec<Value> = t.keys.iter().map(|k| json!({"frame": kf.start + k.frame, "value": k.value, "ease": k.ease.label(), "bezier": k.ease.as_bezier()})).collect();
|
||||
let keys: Vec<Value> = t.keys.iter().map(|k| json!({"frame": kf.start + k.frame, "value": k.value, "ease": k.ease.label(), "easing": easing_json(&k.ease), "bezier": k.ease.as_bezier()})).collect();
|
||||
json!({"property": t.property.key(), "label": t.property.label(), "unit": t.property.unit(), "keys": keys})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -31,10 +31,10 @@ const MAX_ELEMENTS: usize = 10_000;
|
||||
/// a namespace this list doesn't know is refused until someone decides (a test checks that
|
||||
/// every registered namespace is known).
|
||||
pub fn plugin_may_call(id: &str) -> std::result::Result<(), &'static str> {
|
||||
const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "warp", "script", "raw", "frames", "find", "explorer"];
|
||||
const DOCUMENT: &[&str] = &["draw", "edit", "element", "symbol", "arrange", "modify", "library", "text", "scene", "path", "paint", "timeline", "layer", "align", "doc", "motion", "sound", "stroke", "tween", "actions", "instance", "camera", "bone", "warp", "script", "raw", "frames", "find", "explorer", "ease"];
|
||||
match id {
|
||||
"edit.undo" | "edit.redo" => Err("a plug-in run is one undo step; it can't undo or redo"),
|
||||
"edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" | "frames.cut" | "frames.copy" | "frames.paste" => {
|
||||
"edit.cut" | "edit.copy" | "edit.paste" | "edit.paste_in_place" | "timeline.cut_frames" | "timeline.copy_frames" | "timeline.paste_frames" | "frames.cut" | "frames.copy" | "frames.paste" | "ease.copy" | "ease.paste" => {
|
||||
Err("plug-ins don't use your clipboard")
|
||||
}
|
||||
_ => match id.split('.').next().unwrap_or("") {
|
||||
|
||||
@@ -16,10 +16,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("timeline.clear_keyframe", "Clear Keyframe", "Insert/Timeline", Some("Shift+F6"), "{layer? | layers?: [..], frame?, count?}", true, clear_keyframe),
|
||||
c("timeline.move_keyframes", "Move Keyframes", "", None, "{layer? | layers?: [..], from, to?, by, layer_by? (rows down; negative = up)}", true, move_keyframes),
|
||||
c("timeline.create_motion_tween", "Create Motion Tween", "Insert", None, "{layer?, frame?} (several objects on the key become one graphic symbol; a one-frame span grows to a second)", true, crate::cmds_motion::create),
|
||||
c("timeline.create_tween", "Create Classic Tween", "Insert", None, "{layer?, frame?, easing?}", true, create_tween),
|
||||
c("timeline.create_shape_tween", "Create Shape Tween", "Insert", None, "{layer?, frame?, easing?}", true, create_shape_tween),
|
||||
c("timeline.create_tween", "Create Classic Tween", "Insert", None, "{layer?, frame?, easing? (as timeline.set_easing takes it)}", true, create_tween),
|
||||
c("timeline.create_shape_tween", "Create Shape Tween", "Insert", None, "{layer?, frame?, easing? (as timeline.set_easing takes it)}", true, create_shape_tween),
|
||||
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, layer?, frame?}", true, set_easing),
|
||||
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}, 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_label", "Frame Label", "", None, "{label, layer?, frame?}", true, set_label),
|
||||
c("timeline.goto", "Go to Frame", "", None, "{frame}", false, goto),
|
||||
@@ -384,7 +384,7 @@ pub(crate) fn insert_keyframe_at(layer: &mut Layer, frame: u32, copy: bool) -> R
|
||||
Some(i) => {
|
||||
let Some(k) = layer.keyframe_mut(i) else { return Ok(()) };
|
||||
let end = k.end();
|
||||
let tween = if copy { k.tween } else { None };
|
||||
let tween = if copy { k.tween.clone() } else { None };
|
||||
// A motion tween split in two keeps moving the same way in both halves.
|
||||
let motion = if copy {
|
||||
k.motion.as_ref().map(|m| {
|
||||
@@ -649,22 +649,23 @@ fn create_shape_tween(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn tween_of_kind(s: &mut Session, p: &Value, kind: TweenKind) -> Result<Value> {
|
||||
let given = opt_easing_in(&s.doc, p, "easing")?;
|
||||
let k = keyframe_mut(s, p)?;
|
||||
// Switching kinds keeps the easing the span already had, unless one is given.
|
||||
let easing = match opt_easing(p, "easing")? {
|
||||
Some(e) => e,
|
||||
None => k.tween.map(|t| t.easing).unwrap_or_default(),
|
||||
};
|
||||
let orient = k.tween.is_some_and(|t| t.orient);
|
||||
// Switching kinds keeps the easing the span already had, unless one is given; a classic
|
||||
// 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 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);
|
||||
k.tween = Some(Tween { easing, kind, orient });
|
||||
let label = easing.label();
|
||||
k.tween = Some(Tween { easing, kind, orient, groups });
|
||||
// Shape hints only mean something to a shape tween.
|
||||
if kind != TweenKind::Shape {
|
||||
k.hints.clear();
|
||||
}
|
||||
let kind = if kind == TweenKind::Shape { "shape" } else { "classic" };
|
||||
Ok(json!({"tween": k.start, "easing": easing.label(), "kind": kind}))
|
||||
Ok(json!({"tween": k.start, "easing": label, "kind": kind}))
|
||||
}
|
||||
|
||||
fn remove_tween(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -676,11 +677,17 @@ fn remove_tween(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn set_easing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let easing = opt_easing(p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?;
|
||||
let easing = opt_easing_in(&s.doc, p, "easing")?.ok_or_else(|| EngineError::Param("param 'easing' is required".into()))?;
|
||||
let group = crate::cmds_ease::group(p)?;
|
||||
let k = keyframe_mut(s, p)?;
|
||||
let t = k.tween.as_mut().ok_or_else(|| EngineError::State("this span has no tween; create one first".into()))?;
|
||||
t.easing = easing;
|
||||
Ok(json!({"easing": easing.label()}))
|
||||
let label = easing.label();
|
||||
match group {
|
||||
Some(_) if t.kind == TweenKind::Shape => return Err(EngineError::State("a shape tween has one ease for everything; property groups ease separately in classic tweens".into())),
|
||||
Some(g) => t.set_ease(g, Some(easing)),
|
||||
None => t.easing = easing,
|
||||
}
|
||||
Ok(json!({"easing": label, "group": group.map_or("all", |g| g.key())}))
|
||||
}
|
||||
|
||||
fn set_label(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//! Eases through the command registry (ADR 0081): presets by name, custom eases edited point by
|
||||
//! point (one undo step per drag), saved eases on classic tweens and motion properties, copy
|
||||
//! and paste, property groups, and the file round trip.
|
||||
|
||||
use super::*;
|
||||
use anicraft_doc::{CustomEase, EaseGroup, Easing, Property, TweenKind};
|
||||
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}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 10 × 10 square at the origin, tweened (classic) 100 to the right over ten frames.
|
||||
fn tweened() -> Session {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
|
||||
run(&mut s, "timeline.goto", json!({"frame": 10}));
|
||||
run(&mut s, "timeline.insert_keyframe", json!({}));
|
||||
run(&mut s, "edit.select_all", json!({}));
|
||||
run(&mut s, "element.translate", json!({"dx": 100, "dy": 0}));
|
||||
run(&mut s, "timeline.create_tween", json!({"frame": 0}));
|
||||
s
|
||||
}
|
||||
|
||||
/// How far the square has moved at frame `f` (it starts centred on x = 5).
|
||||
fn x_at(s: &mut Session, f: u32) -> f32 {
|
||||
s.set_frame(f);
|
||||
s.visible_elements().first().map(|e| e.transform.translation().x - 5.0).unwrap_or(f32::NAN)
|
||||
}
|
||||
|
||||
fn tween(s: &Session) -> anicraft_doc::Tween {
|
||||
s.active_layer().and_then(|l| l.keyframes.first()).and_then(|k| k.tween.clone()).expect("a tween")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_preset_applies_by_name_and_drives_the_tween() {
|
||||
let mut s = tweened();
|
||||
for e in Easing::named() {
|
||||
let name = e.name().unwrap();
|
||||
let v = run(&mut s, "timeline.set_easing", json!({"easing": name, "frame": 0}));
|
||||
assert_eq!(v["easing"], e.label());
|
||||
assert_eq!(tween(&s).easing, e);
|
||||
assert!((x_at(&mut s, 5) - 100.0 * e.apply(0.5)).abs() < 1e-3, "{name}");
|
||||
}
|
||||
run(&mut s, "timeline.set_easing", json!({"easing": {"classic": 100}, "frame": 0}));
|
||||
assert!((x_at(&mut s, 5) - 75.0).abs() < 1e-3);
|
||||
// The list: every named preset and Classic Ease.
|
||||
let l = run(&mut s, "ease.list", json!({}));
|
||||
assert_eq!(l["presets"].as_array().unwrap().len(), 29);
|
||||
assert!(s.execute("timeline.set_easing", &json!({"easing": "Wobbly"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_edits_shape_a_custom_ease_and_a_drag_is_one_undo_step() {
|
||||
let mut s = tweened();
|
||||
// A point on the line keeps the motion as it was; the preset became a custom curve.
|
||||
let v = run(&mut s, "ease.add_point", json!({"t": 0.5, "frame": 0}));
|
||||
assert_eq!((v["index"].as_u64(), v["points"].as_u64()), (Some(1), Some(3)));
|
||||
assert!(matches!(tween(&s).easing, Easing::Custom(_)));
|
||||
assert!((x_at(&mut s, 3) - 30.0).abs() < 1e-2);
|
||||
// Dragging it up and past its neighbour, as a gesture of many moves: one undo step.
|
||||
let steps = s.history_len();
|
||||
s.begin_gesture("Ease point");
|
||||
for k in 0..=20 {
|
||||
run(&mut s, "ease.move_point", json!({"index": 1, "x": 0.5 + k as f32 * 0.05, "y": 0.5 + k as f32 * 0.05, "frame": 0}));
|
||||
}
|
||||
s.end_gesture();
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
let c = tween(&s).easing.custom().cloned().unwrap();
|
||||
assert_eq!(c.points()[1].at, anicraft_geom::Vec2::new(1.0, 1.5), "x stops at the end; y overshoots");
|
||||
assert!(x_at(&mut s, 9) > 100.0, "overshoots past the second keyframe");
|
||||
// Corner, smooth, handles, delete; the ends can't move or go.
|
||||
run(&mut s, "ease.move_point", json!({"index": 1, "x": 0.4, "y": 1.2, "frame": 0}));
|
||||
run(&mut s, "ease.convert_point", json!({"index": 1, "smooth": true, "frame": 0}));
|
||||
run(&mut s, "ease.move_handle", json!({"index": 1, "handle": "out", "x": 0.6, "y": 1.4, "frame": 0}));
|
||||
let p = tween(&s).easing.custom().unwrap().points()[1];
|
||||
assert!(p.smooth && (p.h_in.normalized().dot(p.out.normalized()) + 1.0).abs() < 1e-4);
|
||||
assert!(s.execute("ease.move_point", &json!({"index": 0, "x": 0.5, "y": 0.5, "frame": 0})).is_err());
|
||||
assert!(s.execute("ease.delete_point", &json!({"index": 2, "frame": 0})).is_err());
|
||||
assert!(s.execute("ease.move_handle", &json!({"index": 0, "handle": "in", "x": 0, "y": 0, "frame": 0})).is_err());
|
||||
run(&mut s, "ease.delete_point", json!({"index": 1, "frame": 0}));
|
||||
assert_eq!(tween(&s).easing.custom().unwrap().points().len(), 2);
|
||||
// Undo walks back through the edits.
|
||||
s.undo().unwrap();
|
||||
assert_eq!(tween(&s).easing.custom().unwrap().points().len(), 3);
|
||||
// Info gives the curve as points and the ease as params take it back.
|
||||
let i = run(&mut s, "ease.info", json!({"frame": 0}));
|
||||
assert_eq!(i["kind"], "custom");
|
||||
assert_eq!(i["points"].as_array().unwrap().len(), 3);
|
||||
let back = run(&mut s, "timeline.set_easing", json!({"easing": i["easing"].clone(), "frame": 0}));
|
||||
assert_eq!(back["easing"], "Custom");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_never_runs_backwards_after_any_command_edit() {
|
||||
let mut s = tweened();
|
||||
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
|
||||
let mut rnd = || {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % 10_000) as f64 / 10_000.0
|
||||
};
|
||||
for _ in 0..400 {
|
||||
let n = tween(&s).easing.to_custom().points().len() as f64;
|
||||
let i = (rnd() * n) as u64;
|
||||
let (x, y) = (rnd() * 1.6 - 0.3, rnd() * 30.0 - 15.0);
|
||||
let (id, p) = match (rnd() * 5.0) as u32 {
|
||||
0 => ("ease.add_point", json!({"t": rnd(), "frame": 0})),
|
||||
1 => ("ease.move_point", json!({"index": i, "x": x, "y": y, "frame": 0})),
|
||||
2 => ("ease.move_handle", json!({"index": i, "handle": if rnd() > 0.5 { "in" } else { "out" }, "x": x, "y": y, "frame": 0})),
|
||||
3 => ("ease.convert_point", json!({"index": i, "smooth": rnd() > 0.5, "frame": 0})),
|
||||
_ => ("ease.delete_point", json!({"index": i, "frame": 0})),
|
||||
};
|
||||
let _ = s.execute(id, &p);
|
||||
let c = tween(&s).easing.to_custom();
|
||||
for k in 0..c.points().len() - 1 {
|
||||
let [a, b, cc, d] = c.segment(k).unwrap();
|
||||
assert!(a.x <= d.x && (a.x..=d.x).contains(&b.x) && (a.x..=d.x).contains(&cc.x), "{id} {p}: segment {k}");
|
||||
}
|
||||
assert!((0..=10).all(|f| x_at(&mut s, f).is_finite()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_eases_reach_classic_tweens_and_motion_properties() {
|
||||
let mut s = tweened();
|
||||
run(&mut s, "ease.add_point", json!({"t": 0.3, "frame": 0}));
|
||||
run(&mut s, "ease.move_point", json!({"index": 1, "x": 0.3, "y": 0.9, "frame": 0}));
|
||||
let curve = tween(&s).easing.clone();
|
||||
run(&mut s, "ease.save", json!({"name": " Snap ", "frame": 0}));
|
||||
assert_eq!(s.doc.eases.len(), 1);
|
||||
assert_eq!(s.doc.eases[0].name, "Snap");
|
||||
assert!(s.execute("ease.save", &json!({"name": "snap", "easing": "QuadIn"})).is_err(), "a name is saved once (any case)");
|
||||
run(&mut s, "ease.save", json!({"name": "Bouncy", "easing": "BounceOut"}));
|
||||
// Another tween takes it by name.
|
||||
run(&mut s, "timeline.set_easing", json!({"easing": "Linear", "frame": 0}));
|
||||
run(&mut s, "timeline.set_easing", json!({"easing": {"saved": "snap"}, "frame": 0}));
|
||||
assert_eq!(tween(&s).easing, curve);
|
||||
assert_eq!(cmds_ease::saved_name(&s.doc, &tween(&s).easing), Some("Snap"));
|
||||
// A motion tween's property too.
|
||||
let mut m = Session::default();
|
||||
m.doc.eases = s.doc.eases.clone();
|
||||
run(&mut m, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10}));
|
||||
run(&mut m, "timeline.create_motion_tween", json!({}));
|
||||
run(&mut m, "motion.set_key", json!({"property": "x", "frame": 20, "value": 205}));
|
||||
run(&mut m, "motion.set_ease", json!({"property": "x", "frame": 3, "easing": {"saved": "Bouncy"}}));
|
||||
let ease = m.active_layer().unwrap().keyframes[0].motion.as_ref().unwrap().track(Property::X).unwrap().keys[0].ease.clone();
|
||||
assert_eq!(ease, Easing::BounceOut);
|
||||
// Point edits on a motion segment address it by property.
|
||||
run(&mut m, "ease.add_point", json!({"property": "x", "frame": 3, "t": 0.5}));
|
||||
assert!(matches!(m.active_layer().unwrap().keyframes[0].motion.as_ref().unwrap().track(Property::X).unwrap().keys[0].ease, Easing::Custom(_)));
|
||||
// Edit the saved one directly, rename, delete: tweens keep their curves.
|
||||
run(&mut s, "ease.set", json!({"saved": "Snap", "easing": "SineOut"}));
|
||||
assert_eq!(s.doc.eases[0].ease, Easing::SineOut);
|
||||
assert_eq!(tween(&s).easing, curve, "a tween keeps the curve it was given");
|
||||
run(&mut s, "ease.rename", json!({"name": "snap", "to": "Settle"}));
|
||||
assert!(s.execute("ease.rename", &json!({"name": "Settle", "to": "bouncy"})).is_err());
|
||||
run(&mut s, "ease.delete", json!({"name": "SETTLE"}));
|
||||
assert_eq!(s.doc.eases.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), ["Bouncy"]);
|
||||
assert!(s.execute("timeline.set_easing", &json!({"easing": {"saved": "Settle"}})).is_err());
|
||||
let l = run(&mut s, "ease.list", json!({}));
|
||||
assert_eq!(l["saved"][0]["name"], "Bouncy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_and_paste_an_ease_between_tweens() {
|
||||
let mut s = tweened();
|
||||
run(&mut s, "timeline.set_easing", json!({"easing": "BackOut", "frame": 0}));
|
||||
assert!(s.execute("ease.paste", &json!({"frame": 0})).is_err(), "nothing copied yet");
|
||||
run(&mut s, "ease.copy", json!({"frame": 0}));
|
||||
run(&mut s, "timeline.set_easing", json!({"easing": "Linear", "frame": 0}));
|
||||
let steps = s.history_len();
|
||||
run(&mut s, "ease.paste", json!({"frame": 0, "group": "rotation"}));
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
assert_eq!(tween(&s).ease(EaseGroup::Rotation), &Easing::BackOut);
|
||||
// Copying doesn't change the document.
|
||||
let steps = s.history_len();
|
||||
run(&mut s, "ease.copy", json!({"frame": 0}));
|
||||
assert_eq!(s.history_len(), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_tweens_ease_property_groups_separately() {
|
||||
let mut s = tweened();
|
||||
run(&mut s, "timeline.set_easing", json!({"easing": "QuadIn", "group": "position", "frame": 0}));
|
||||
assert!((x_at(&mut s, 5) - 25.0).abs() < 1e-3, "position eased in");
|
||||
assert_eq!(tween(&s).ease(EaseGroup::Scale), &Easing::Linear);
|
||||
// Separate: every group gets the tween's ease (position keeps its own); one for all clears.
|
||||
run(&mut s, "ease.separate", json!({"separate": true, "frame": 0}));
|
||||
assert_eq!(tween(&s).groups.len(), 5);
|
||||
assert_eq!(tween(&s).ease(EaseGroup::Position), &Easing::QuadIn);
|
||||
run(&mut s, "ease.separate", json!({"separate": false, "frame": 0}));
|
||||
assert!(tween(&s).groups.is_empty());
|
||||
assert!((x_at(&mut s, 5) - 50.0).abs() < 1e-3);
|
||||
// Converting keeps groups on classic tweens; a shape tween has one ease.
|
||||
run(&mut s, "timeline.set_easing", json!({"easing": "QuadIn", "group": "color", "frame": 0}));
|
||||
run(&mut s, "timeline.create_shape_tween", json!({"frame": 0}));
|
||||
assert!(tween(&s).groups.is_empty() && tween(&s).kind == TweenKind::Shape);
|
||||
assert!(s.execute("timeline.set_easing", &json!({"easing": "QuadIn", "group": "color", "frame": 0})).is_err());
|
||||
assert!(s.execute("ease.separate", &json!({"separate": true, "frame": 0})).is_err());
|
||||
assert!(s.execute("timeline.set_easing", &json!({"easing": "QuadIn", "group": "sparkle", "frame": 0})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eases_survive_the_file_round_trip() {
|
||||
let mut s = tweened();
|
||||
run(&mut s, "timeline.set_easing", json!({"easing": {"custom": [[0, 0], [0.2, 1.4], [0.3, 1.4], [0.4, 1.4], [0.6, 0.8], [0.8, 1], [1, 1]]}, "frame": 0}));
|
||||
run(&mut s, "timeline.set_easing", json!({"easing": "ElasticOut", "group": "rotation", "frame": 0}));
|
||||
run(&mut s, "ease.save", json!({"name": "Wave", "frame": 0}));
|
||||
run(&mut s, "ease.save", json!({"name": "Classic 40", "easing": {"classic": 40}}));
|
||||
let text = format::to_json(&s.doc).expect("save");
|
||||
let back = format::from_json(&text).expect("load");
|
||||
assert_eq!(back, s.doc);
|
||||
assert_eq!(back.eases.len(), 2);
|
||||
let t = back.timeline(0).layers[0].keyframes[0].tween.clone().unwrap();
|
||||
assert!(matches!(&t.easing, Easing::Custom(c) if c.points().len() == 3));
|
||||
assert_eq!(t.ease(EaseGroup::Rotation), &Easing::ElasticOut);
|
||||
// A file from before saved eases and custom curves opens unchanged.
|
||||
let old = text.replace("\"eases\":", "\"ignored_eases\":");
|
||||
assert!(format::from_json(&old).expect("older file").eases.is_empty());
|
||||
// A hostile curve in a file is repaired on load, never refused: reversed, out of range.
|
||||
let bad = r#"{"Custom": {"points": [{"at": {"x": 2, "y": 99}}, {"at": {"x": 0.5, "y": -40}, "in": {"x": 5, "y": 0}}, {"at": {"x": -1, "y": 0}}]}}"#;
|
||||
let e: Easing = serde_json::from_str(bad).unwrap();
|
||||
let c = e.custom().unwrap();
|
||||
assert_eq!((c.points().len(), c.points()[1].at.y, c.points()[1].h_in.x), (3, -anicraft_doc::MAX_EASE_Y, 0.0));
|
||||
let _ = CustomEase::linear();
|
||||
}
|
||||
@@ -249,6 +249,6 @@ pub fn unique_bytes(old: &Document, new: &Document) -> usize {
|
||||
|
||||
/// Estimated total bytes of a document (as if nothing were shared). Used for reporting.
|
||||
pub fn document_bytes(doc: &Document) -> usize {
|
||||
let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: doc.aids.clone(), swatches: doc.swatches.clone(), next_id: doc.next_id };
|
||||
let empty = Document { stage: doc.stage, scenes: Vec::new(), library: Vec::new(), bitmaps: Vec::new(), sounds: Vec::new(), library_tree: Default::default(), document_class: String::new(), publish: Default::default(), aids: doc.aids.clone(), swatches: doc.swatches.clone(), eases: doc.eases.clone(), next_id: doc.next_id };
|
||||
unique_bytes(doc, &empty)
|
||||
}
|
||||
@@ -12,6 +12,7 @@ mod cmds_warp;
|
||||
pub mod cmds_brush;
|
||||
mod cmds_camera;
|
||||
mod cmds_draw;
|
||||
pub mod cmds_ease;
|
||||
pub mod cmds_envelope;
|
||||
pub mod cmds_drop;
|
||||
pub mod cmds_erase;
|
||||
@@ -140,6 +141,7 @@ pub fn commands() -> Vec<CommandSpec> {
|
||||
v.extend(cmds_bone::specs());
|
||||
v.extend(cmds_warp::specs());
|
||||
v.extend(cmds_motion::specs());
|
||||
v.extend(cmds_ease::specs());
|
||||
v.extend(cmds_hints::specs());
|
||||
v.extend(cmds_scene::specs());
|
||||
v.extend(cmds_frames::specs());
|
||||
@@ -328,6 +330,8 @@ pub struct Session {
|
||||
pub clipboard: cmds_modify::Clipboard,
|
||||
/// Copied frames (Copy Frames), separate from copied artwork as in Animate.
|
||||
pub frame_clipboard: cmds_frames::FrameClipboard,
|
||||
/// A copied ease (Copy Ease, ADR 0081), for Paste Ease.
|
||||
pub ease_clipboard: Option<anicraft_doc::Easing>,
|
||||
/// A command is editing a motion tween's target (auto-key, ADR 0016).
|
||||
motion_edit: Option<cmds_motion::MotionEdit>,
|
||||
/// Installed WebAssembly plug-ins (ADR 0017). They belong to the session, not the
|
||||
@@ -421,6 +425,7 @@ impl Session {
|
||||
dl_cache: RefCell::new(None),
|
||||
clipboard: cmds_modify::Clipboard::default(),
|
||||
frame_clipboard: cmds_frames::FrameClipboard::default(),
|
||||
ease_clipboard: None,
|
||||
motion_edit: None,
|
||||
plugins: anicraft_plugins::Registry::default(),
|
||||
step_label: None,
|
||||
@@ -991,7 +996,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.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<_>>()), "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();
|
||||
@@ -1090,6 +1095,8 @@ mod tests;
|
||||
#[cfg(test)]
|
||||
mod motion_tests;
|
||||
#[cfg(test)]
|
||||
mod ease_tests;
|
||||
#[cfg(test)]
|
||||
mod color_tests;
|
||||
#[cfg(test)]
|
||||
mod motion_path_tests;
|
||||
|
||||
+64
-16
@@ -2,8 +2,10 @@
|
||||
//! can show, never panics, and rejects non-finite numbers.
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
use anicraft_doc::{Easing, ProfilePreset, Rgba, WidthPoint, WidthProfile};
|
||||
use serde_json::Value;
|
||||
use anicraft_doc::{CustomEase, Document, EasePoint, Easing, ProfilePreset, Rgba, WidthPoint, WidthProfile};
|
||||
use anicraft_geom::Vec2;
|
||||
use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn bad(key: &str, want: &str) -> EngineError {
|
||||
EngineError::Param(format!("param '{key}' must be {want}"))
|
||||
@@ -81,25 +83,17 @@ pub fn opt_u64_list(p: &Value, key: &str) -> Result<Option<Vec<u64>>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Easing from a preset name (`"Linear"`, `"QuadIn"`…), `{"classic": n}` or `{"bezier": [x1,y1,x2,y2]}`.
|
||||
/// Easing from a preset name (`"Linear"`, `"QuadIn"`, `"ElasticOut"`…), `{"classic": n}`,
|
||||
/// `{"bezier": [x1, y1, x2, y2]}` or `{"custom": …}` (a custom ease: `{"points": [{at, in,
|
||||
/// out, smooth}, ..]}` as `ease.info` gives it, or the flat list `[[x, y], ..]` of 3n + 1
|
||||
/// points XFL uses). Saved eases (`{"saved": name}`) need the document: [`opt_easing_in`].
|
||||
pub fn opt_easing(p: &Value, key: &str) -> Result<Option<Easing>> {
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
if v.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(s) = v.as_str() {
|
||||
let e = match s.to_ascii_lowercase().replace(['-', '_', ' '], "").as_str() {
|
||||
"linear" | "none" => Easing::Linear,
|
||||
"quadin" | "easein" => Easing::QuadIn,
|
||||
"quadout" | "easeout" => Easing::QuadOut,
|
||||
"quadinout" | "easeinout" => Easing::QuadInOut,
|
||||
"cubicin" => Easing::CubicIn,
|
||||
"cubicout" => Easing::CubicOut,
|
||||
"cubicinout" => Easing::CubicInOut,
|
||||
"smooth" => Easing::CubicBezier(0.25, 0.1, 0.25, 1.0),
|
||||
_ => return Err(bad(key, "one of Linear, QuadIn, QuadOut, QuadInOut, CubicIn, CubicOut, CubicInOut, Smooth")),
|
||||
};
|
||||
return Ok(Some(e));
|
||||
return Easing::from_name(s).map(Some).ok_or_else(|| bad(key, "a preset name: Linear, Smooth, or a family (Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce, Elastic) with In, Out or InOut, e.g. BackOut"));
|
||||
}
|
||||
if let Some(c) = v.get("classic") {
|
||||
let s = c.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(key, "{\"classic\": -100..100}"))?;
|
||||
@@ -111,7 +105,61 @@ pub fn opt_easing(p: &Value, key: &str) -> Result<Option<Easing>> {
|
||||
return Ok(Some(Easing::CubicBezier(x1.clamp(0.0, 1.0), y1.clamp(-5.0, 5.0), x2.clamp(0.0, 1.0), y2.clamp(-5.0, 5.0))));
|
||||
}
|
||||
}
|
||||
Err(bad(key, "an easing name, {\"classic\": n} or {\"bezier\": [x1, y1, x2, y2]}"))
|
||||
if let Some(c) = v.get("custom") {
|
||||
return custom_ease(c).map(|c| Some(Easing::Custom(Arc::new(c)))).ok_or_else(|| bad(key, "{\"custom\": {\"points\": [{\"at\": {\"x\", \"y\"}, \"in\": {..}, \"out\": {..}, \"smooth\"}, ..]}} or {\"custom\": [[x, y], ..]} (3n + 1 points)"));
|
||||
}
|
||||
Err(bad(key, "an easing name, {\"classic\": n}, {\"bezier\": [x1, y1, x2, y2]}, {\"custom\": …} or {\"saved\": name}"))
|
||||
}
|
||||
|
||||
/// Most points read from a custom ease param before it is thinned to the cap.
|
||||
const MAX_EASE_PARAM: usize = 16_384;
|
||||
|
||||
fn custom_ease(v: &Value) -> Option<CustomEase> {
|
||||
match v {
|
||||
Value::Array(flat) if flat.len() <= MAX_EASE_PARAM * 3 => {
|
||||
let pts: Option<Vec<Vec2>> = flat.iter().map(|q| match q.as_array().map(Vec::as_slice) {
|
||||
Some([x, y]) => Some(Vec2::new(x.as_f64()? as f32, y.as_f64()? as f32)),
|
||||
_ => None,
|
||||
}).collect();
|
||||
CustomEase::from_flat(&pts?)
|
||||
}
|
||||
Value::Object(o) => {
|
||||
let pts = o.get("points")?.as_array()?;
|
||||
if pts.len() > MAX_EASE_PARAM {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_value::<Vec<EasePoint>>(Value::Array(pts.clone())).ok().map(CustomEase::new)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`opt_easing`], and `{"saved": name}` for an ease saved in `doc` (ADR 0081).
|
||||
pub fn opt_easing_in(doc: &Document, p: &Value, key: &str) -> Result<Option<Easing>> {
|
||||
if let Some(name) = p.get(key).and_then(|v| v.get("saved")) {
|
||||
let name = name.as_str().ok_or_else(|| bad(key, "{\"saved\": name}"))?;
|
||||
return saved_ease(doc, name).map(Some);
|
||||
}
|
||||
opt_easing(p, key)
|
||||
}
|
||||
|
||||
/// The ease saved as `name` (any case).
|
||||
pub fn saved_ease(doc: &Document, name: &str) -> Result<Easing> {
|
||||
let want = name.trim().to_lowercase();
|
||||
doc.eases.iter().find(|e| e.name.to_lowercase() == want).map(|e| e.ease.clone()).ok_or_else(|| {
|
||||
let names: Vec<&str> = doc.eases.iter().map(|e| e.name.as_str()).take(20).collect();
|
||||
EngineError::State(if names.is_empty() { format!("no ease is saved as '{name}' (save one with ease.save)") } else { format!("no ease is saved as '{name}' (saved: {})", names.join(", ")) })
|
||||
})
|
||||
}
|
||||
|
||||
/// An ease as commands take it back (see [`opt_easing`]): a name for presets, else its values.
|
||||
pub fn easing_json(e: &Easing) -> Value {
|
||||
match e {
|
||||
Easing::Classic(s) => json!({"classic": s}),
|
||||
Easing::CubicBezier(a, b, c, d) => json!({"bezier": [a, b, c, d]}),
|
||||
Easing::Custom(c) => json!({"custom": serde_json::to_value(&**c).unwrap_or(Value::Null)}),
|
||||
named => named.name().map_or(Value::Null, Value::from),
|
||||
}
|
||||
}
|
||||
|
||||
/// A width profile (ADR 0018): a preset name (`"uniform"`, `"taper_both"`, `"taper_start"`,
|
||||
|
||||
@@ -358,7 +358,7 @@ impl SessionLock {
|
||||
// ----- background writer ------------------------------------------------------------------------
|
||||
|
||||
enum Job {
|
||||
Write { doc: Document, meta: Box<RecoveryMeta>, tag: u64 },
|
||||
Write { doc: Box<Document>, meta: Box<RecoveryMeta>, tag: u64 },
|
||||
Clear { tag: u64 },
|
||||
}
|
||||
|
||||
@@ -412,7 +412,7 @@ impl Autosaver {
|
||||
/// Queues a write of `doc` (a cheap snapshot). Returns its tag.
|
||||
pub fn write(&mut self, doc: Document, original: Option<&Path>) -> u64 {
|
||||
let meta = RecoveryMeta::describe(self.id(), &doc, original);
|
||||
self.send(|tag| Job::Write { doc, meta: Box::new(meta), tag })
|
||||
self.send(|tag| Job::Write { doc: Box::new(doc), meta: Box::new(meta), tag })
|
||||
}
|
||||
|
||||
/// Queues removal of this session's recovery copy (after a save, or when the work is gone).
|
||||
|
||||
@@ -831,6 +831,30 @@ fn panic_hunt_every_command() {
|
||||
json!({"all": true, "filter": "a", "show": {"frames": false, "symbols": "x"}, "expanded": ["s0", 5], "offset": u64::MAX, "limit": u64::MAX}),
|
||||
json!({"all": true, "scope": "scene", "definitions": false, "show": {"frames": false}, "limit": 0}),
|
||||
]);
|
||||
// Eases (ADR 0081): a classic tween with a custom ease of several segments and property
|
||||
// groups of their own, an ease saved and one copied; the fuzz edits, saves and pastes them
|
||||
// with hostile curves (NaN-like and reversed points, thousands of them, ends that move).
|
||||
let mut eased = Session::new(sample::demo());
|
||||
let tl = eased.doc.timeline(0).layers.iter().find(|l| l.keyframes.first().is_some_and(|k| k.tween.is_some() && k.motion.is_none())).map(|l| l.id.0).unwrap();
|
||||
for (id, p) in [
|
||||
("timeline.set_easing", json!({"easing": {"custom": [[0, 0], [0.2, 1.4], [0.3, 1.4], [0.4, 1.4], [0.5, 1.4], [0.6, 0.8], [0.7, 0.8], [0.8, 0.8], [0.9, 1], [1, 1]]}, "frame": 0, "layer": tl})),
|
||||
("ease.separate", json!({"separate": true, "frame": 0, "layer": tl})),
|
||||
("ease.set", json!({"easing": "ElasticOut", "group": "rotation", "frame": 0, "layer": tl})),
|
||||
("ease.save", json!({"name": "Wobble", "easing": "BounceOut"})),
|
||||
("ease.copy", json!({"frame": 0, "layer": tl})),
|
||||
("timeline.goto", json!({"frame": 5})),
|
||||
("layer.select", json!({"layer": tl})),
|
||||
] {
|
||||
eased.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
}
|
||||
hostile.extend([
|
||||
json!({"easing": {"custom": (0..30_000).map(|i| json!([f64::from(i) / 30_000.0, f64::from(i % 7) * 1e30])).collect::<Vec<_>>()}, "t": 0.5, "index": 1, "x": 0.5, "y": 1e30, "handle": "out", "smooth": true, "name": "Wobble", "group": "position"}),
|
||||
json!({"easing": {"custom": {"points": [{"at": {"x": 1, "y": 1}}, {"at": {"x": -5, "y": 1e30}, "in": {"x": 9, "y": -1e30}}, {"at": {"x": 0.5, "y": 0.5}, "out": {"x": -9, "y": 0}}]}}, "saved": "Wobble", "index": 0, "handle": "sideways", "t": 2}),
|
||||
json!({"easing": {"custom": {"points": (0..20_000).map(|i| json!({"at": {"x": f64::from(20_000 - i) / 20_000.0, "y": 0.5}})).collect::<Vec<_>>()}}, "saved": "Wobble", "index": u64::MAX, "x": f64::MAX, "y": f64::MIN}),
|
||||
json!({"easing": {"saved": 3}, "group": "sparkle", "to": "", "name": "a".repeat(500), "replace": "yes", "separate": true}),
|
||||
json!({"easing": {"saved": "Wobble"}, "group": "filters", "name": "Wobble", "replace": true, "to": "wobble", "separate": false, "property": "x", "index": 1, "smooth": false}),
|
||||
json!({"easing": {"custom": [[0, 0], [1, 1]]}, "t": f64::NAN, "index": 1, "handle": "in", "x": -1e7, "y": 1e7, "property": "nope", "saved": ""}),
|
||||
]);
|
||||
// A button open for editing, its hit area drawn over its other states (ADR 0057).
|
||||
let mut button = Session::new(sample::interactive());
|
||||
if let Some(id) = button.doc.library.iter().find(|x| x.kind == anicraft_doc::SymbolKind::Button).map(|x| x.id) {
|
||||
@@ -858,7 +882,7 @@ fn panic_hunt_every_command() {
|
||||
let inner = grouped.visible_elements().into_iter().find(|e| matches!(e.kind, anicraft_doc::ElementKind::Group { .. })).map(|e| e.id.0).unwrap();
|
||||
grouped.execute("symbol.edit", &json!({"id": inner})).unwrap();
|
||||
assert_eq!(grouped.editing.len(), 2, "the fuzz starts inside a group inside a group");
|
||||
for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, shaped, warped, layered, in_symbol, keyed, library, button, grouped] {
|
||||
for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, shaped, warped, layered, in_symbol, keyed, library, button, grouped, eased] {
|
||||
let mut s = start;
|
||||
for spec in commands().iter().filter(|c| !skip(c.id)) {
|
||||
for p in &hostile {
|
||||
@@ -1753,7 +1777,7 @@ fn create_shape_tween_morphs_and_keeps_the_easing() {
|
||||
run(&mut s, "timeline.create_tween", json!({"easing": "ease-in"}));
|
||||
let v = run(&mut s, "timeline.create_shape_tween", json!({}));
|
||||
assert_eq!(v["kind"], "shape");
|
||||
let t = s.active_layer().unwrap().keyframes[0].tween.unwrap();
|
||||
let t = s.active_layer().unwrap().keyframes[0].tween.clone().unwrap();
|
||||
assert_eq!(t.kind, anicraft_doc::TweenKind::Shape);
|
||||
assert_ne!(t.easing, anicraft_doc::Easing::Linear, "switching kinds keeps the easing");
|
||||
// Midway the shape has moved off the square.
|
||||
@@ -1761,7 +1785,7 @@ fn create_shape_tween_morphs_and_keeps_the_easing() {
|
||||
let mid = item.path.bounds().transformed(&item.transform);
|
||||
assert!(mid.max.x > 110.0, "{mid:?}");
|
||||
s.undo().unwrap();
|
||||
assert_eq!(s.active_layer().unwrap().keyframes[0].tween.unwrap().kind, anicraft_doc::TweenKind::Classic);
|
||||
assert_eq!(s.active_layer().unwrap().keyframes[0].tween.clone().unwrap().kind, anicraft_doc::TweenKind::Classic);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1929,7 +1953,7 @@ fn add_motion_guide_steers_the_tween_and_stays_out_of_exports() {
|
||||
// Orient to path, and the guided type.
|
||||
run(&mut s, "layer.select", json!({"layer": art.0}));
|
||||
assert_eq!(run(&mut s, "timeline.set_orient", json!({"orient": true}))["orient"], true);
|
||||
assert!(s.active_layer().unwrap().keyframes[0].tween.unwrap().orient);
|
||||
assert!(s.active_layer().unwrap().keyframes[0].tween.clone().unwrap().orient);
|
||||
assert_eq!(run(&mut s, "layer.set_type", json!({"type": "normal"}))["type"], "normal");
|
||||
assert_eq!(run(&mut s, "layer.set_type", json!({"type": "guided"}))["type"], "guided");
|
||||
// A masked layer can't also follow a guide.
|
||||
|
||||
@@ -99,6 +99,10 @@ const PROBES: &[(&str, u32, f32, f32, u32)] = &[
|
||||
("colour", 12, 280.0, 152.0, 0xAAD8D2),
|
||||
("tweens", 0, 20.0, 25.0, 0xF4A261),
|
||||
("tweens", 12, 300.0, 25.0, 0xF4A261),
|
||||
// Per-property custom eases (ADR 0081): halfway, position's three-segment curve has carried
|
||||
// the ball past its end (x 180) to about 214; at the end it is there, half as big again.
|
||||
("tweens", 6, 214.0, 145.0, 0xF4A261),
|
||||
("tweens", 12, 180.0, 145.0, 0xF4A261),
|
||||
// Masked stripes: inside the spot, and outside it.
|
||||
("masks", 0, 60.0, 22.0, 0x264653),
|
||||
("masks", 0, 60.0, 27.0, 0xFFFFFF),
|
||||
|
||||
@@ -1414,3 +1414,38 @@ fn gradient_options_are_drawn_the_nearest_way_canvas_can() {
|
||||
assert_eq!(r["f"], json!([60, 50]));
|
||||
assert_eq!(r["r"][2], json!(20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_and_per_property_eases_play_in_the_page_as_they_evaluate() {
|
||||
// ADR 0081: a classic tween eased by a custom curve of several segments that overshoots, its
|
||||
// rotation and scale by presets of their own, and a looping movie clip inside tweened with
|
||||
// Elastic; the page plays the same frames, step by step, as the Rust player draws them.
|
||||
use anicraft_doc::{CustomEase, EaseGroup, Easing};
|
||||
let curve = CustomEase::from_flat(&[(0.0, 0.0), (0.2, 1.5), (0.3, 1.5), (0.4, 1.5), (0.5, 1.5), (0.6, 0.6), (0.7, 0.6), (0.8, 0.6), (0.9, 1.0), (1.0, 1.0)].map(|(x, y)| Vec2::new(x, y))).unwrap();
|
||||
let mut tw = Tween::new(Easing::Custom(Arc::new(curve)), anicraft_doc::TweenKind::Classic);
|
||||
tw.set_ease(EaseGroup::Rotation, Some(Easing::BounceOut));
|
||||
tw.set_ease(EaseGroup::Scale, Some(Easing::BackInOut));
|
||||
let mut a = (*rect(1, 0.0, 0.0, 40.0, 40.0, 0x2a9d8f)).clone();
|
||||
a.transform = Affine::translate(20.0, 100.0);
|
||||
let mut b = a.clone();
|
||||
b.transform = Affine::translate(500.0, 160.0).mul(&Affine::rotate(2.5)).mul(&Affine::scale(2.0, 0.5));
|
||||
let mut k0 = Keyframe::new(0, 20);
|
||||
k0.elements = vec![Arc::new(a)];
|
||||
k0.tween = Some(tw);
|
||||
let mut k1 = Keyframe::new(20, 4);
|
||||
k1.elements = vec![Arc::new(b)];
|
||||
let mut inner_a = (*rect(2, 0.0, 0.0, 10.0, 10.0, 0xe76f51)).clone();
|
||||
inner_a.transform = Affine::IDENTITY;
|
||||
let mut inner_b = inner_a.clone();
|
||||
inner_b.transform = Affine::translate(60.0, 0.0);
|
||||
let mut i0 = Keyframe::new(0, 8);
|
||||
i0.elements = vec![Arc::new(inner_a)];
|
||||
i0.tween = Some(Tween::new(Easing::ElasticOut, anicraft_doc::TweenKind::Classic));
|
||||
let mut i1 = Keyframe::new(8, 1);
|
||||
i1.elements = vec![Arc::new(inner_b)];
|
||||
let mut d = Document::default();
|
||||
d.library.push(symbol(50, SymbolKind::MovieClip, vec![layer(51, vec![Arc::new(i0), Arc::new(i1)])]));
|
||||
d.timeline_mut(0).layers = vec![layer(1, vec![Arc::new(k0), Arc::new(k1)]), layer(2, vec![kf(0, 24, vec![inst(3, 50, "", Affine::translate(100.0, 250.0), Vec::new())], vec![], "")])];
|
||||
d.sanitize();
|
||||
compare(&d, &vec![(vec![], vec![]); 30]);
|
||||
}
|
||||
@@ -814,6 +814,35 @@ mod tests {
|
||||
assert!(part["layers"].as_array().unwrap().iter().all(|l| l["ty"] == 4), "transparent: no stage layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_eases_are_baked_frame_by_frame() {
|
||||
// ADR 0081: Lottie's own eases are one cubic per keyframe pair, so a custom curve of
|
||||
// several segments (or Bounce, Elastic) can't map onto them exactly; the outline is
|
||||
// baked at every frame from `evaluate`, so the player shows AniCraft's motion exactly.
|
||||
use anicraft_doc::{ColorEffect, CustomEase, Document, Easing, Element, ElementId, ElementKind, Keyframe, Shape, Tween, TweenKind};
|
||||
use std::sync::Arc;
|
||||
let curve = CustomEase::from_flat(&[(0.0, 0.0), (0.2, 1.4), (0.3, 1.4), (0.4, 1.4), (0.6, 0.5), (0.8, 1.0), (1.0, 1.0)].map(|(x, y)| Vec2::new(x, y))).unwrap();
|
||||
let ease = Easing::Custom(Arc::new(curve));
|
||||
let sq = |x: f32| Arc::new(Element { id: ElementId(70), name: String::new(), transform: Affine::translate(x, 0.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::BLACK))) });
|
||||
let mut doc = Document::default();
|
||||
let mut k0 = Keyframe::new(0, 10);
|
||||
k0.elements = vec![sq(0.0)];
|
||||
k0.tween = Some(Tween::new(ease.clone(), TweenKind::Classic));
|
||||
let mut k1 = Keyframe::new(10, 1);
|
||||
k1.elements = vec![sq(100.0)];
|
||||
std::sync::Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframes = vec![Arc::new(k0), Arc::new(k1)];
|
||||
let v = parse(&to_lottie(&doc, "eased", 0, 10, false));
|
||||
let it = v["layers"][0]["shapes"][0]["it"].as_array().unwrap();
|
||||
let sh = it.iter().find(|i| i["ty"] == "sh").expect("an outline");
|
||||
let keys = sh["ks"]["k"].as_array().unwrap();
|
||||
assert_eq!(keys.len(), 11, "a key at every frame of the eased motion");
|
||||
for k in keys {
|
||||
let t = k["t"].as_u64().unwrap() as f32;
|
||||
let x0 = k["s"][0]["v"][0][0].as_f64().unwrap() as f32;
|
||||
assert!((x0 - 100.0 * ease.apply(t / 10.0)).abs() < 2e-3, "frame {t}: {x0}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_colour_effect_style_is_baked_into_the_colours() {
|
||||
// ADR 0056: Lottie has no colour transform, so the effect is in each fill colour (and
|
||||
|
||||
+65
-17
@@ -23,7 +23,7 @@ use crate::edges::{self, Edge};
|
||||
use crate::xml::{self, Element as X};
|
||||
use anicraft_doc::{
|
||||
Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, ColorTransform, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId,
|
||||
Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, FrameSound, Language, Linkage, ScaleGrid, SoundSync, SourceScript, Spread, MAX_FOCAL,
|
||||
Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, CustomEase, EaseGroup, FrameScript, FrameSound, Language, Linkage, ScaleGrid, SoundSync, SourceScript, Spread, MAX_FOCAL,
|
||||
};
|
||||
use anicraft_geom::{Affine, FillRule, Path, Vec2};
|
||||
use anicraft_text::{FaceMatch, Fonts};
|
||||
@@ -556,7 +556,8 @@ impl<'a> Builder<'a> {
|
||||
if kind == TweenKind::Classic && f.attr("motionTweenRotate").is_some_and(|r| matches!(r.trim(), "clockwise" | "counter-clockwise")) {
|
||||
self.report.skip("tween spins (turned the shortest way)");
|
||||
}
|
||||
k.tween = Some(Tween { easing: self.easing(f), kind, orient });
|
||||
let (easing, groups) = self.easing(f);
|
||||
k.tween = Some(Tween { easing, kind, orient, groups });
|
||||
}
|
||||
Some("motion object") => self.report.skip("motion tweens (kept as keyframes)"),
|
||||
_ => {}
|
||||
@@ -614,26 +615,73 @@ impl<'a> Builder<'a> {
|
||||
Some(FrameScript::Source(Arc::new(script)))
|
||||
}
|
||||
|
||||
/// A tween's ease: the classic single-slider `acceleration`, or a custom ease curve. A
|
||||
/// curve of one segment (four points from (0, 0) to (1, 1)) is a cubic Bézier exactly; a
|
||||
/// longer one, or one per property, is drawn with the slider's ease and reported.
|
||||
fn easing(&mut self, f: &X) -> Easing {
|
||||
/// A tween's ease (ADR 0081): the classic single-slider `acceleration`, or its custom ease
|
||||
/// curves exactly. A curve is `3n + 1` points (each segment's start, two handles, …, the
|
||||
/// end) from (0, 0) to (1, 1); one segment is a cubic Bézier, more a custom ease. With
|
||||
/// `useSingleEaseCurve="false"` each property group (`position`, `rotation`, `scale`,
|
||||
/// `color`, `filters`) has its own curve, and `all` (or the slider) eases the rest.
|
||||
fn easing(&mut self, f: &X) -> (Easing, Vec<(EaseGroup, Easing)>) {
|
||||
let acc = f.f32("acceleration").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
let classic = if acc == 0.0 { Easing::Linear } else { Easing::Classic(acc) };
|
||||
if f.bool("hasCustomEase") != Some(true) {
|
||||
return classic;
|
||||
return (classic, Vec::new());
|
||||
}
|
||||
let curves: Vec<&X> = f.list("tweens").iter().filter(|c| c.name == "CustomEase").collect();
|
||||
let one_curve = f.bool("useSingleEaseCurve") != Some(false) || curves.len() == 1;
|
||||
let bezier = curves.first().filter(|_| one_curve).and_then(|c| {
|
||||
let p: Vec<Vec2> = c.children.iter().filter(|p| p.name == "Point").take(5).map(|p| Vec2::new(p.f32("x").unwrap_or(0.0), p.f32("y").unwrap_or(0.0))).collect();
|
||||
let [a, b, c, d] = p.as_slice() else { return None };
|
||||
let near = |p: &Vec2, x: f32, y: f32| (p.x - x).abs() < 1e-3 && (p.y - y).abs() < 1e-3;
|
||||
(near(a, 0.0, 0.0) && near(d, 1.0, 1.0)).then(|| Easing::CubicBezier(b.x.clamp(0.0, 1.0), b.y.clamp(-10.0, 10.0), c.x.clamp(0.0, 1.0), c.y.clamp(-10.0, 10.0)))
|
||||
});
|
||||
bezier.unwrap_or_else(|| {
|
||||
self.report.skip("custom ease curves (drawn with the simple ease)");
|
||||
classic
|
||||
if curves.is_empty() {
|
||||
self.report.skip("custom eases without their curve (drawn with the simple ease)");
|
||||
return (classic, Vec::new());
|
||||
}
|
||||
let single = f.bool("useSingleEaseCurve") != Some(false) || curves.len() == 1;
|
||||
let mut main = None;
|
||||
let mut groups: Vec<(EaseGroup, Easing)> = Vec::new();
|
||||
for (n, c) in curves.iter().enumerate() {
|
||||
let target = c.attr("target").map_or("all", str::trim);
|
||||
// One curve for everything: the first.
|
||||
if single && n > 0 {
|
||||
break;
|
||||
}
|
||||
let group = if single || target == "all" { None } else { EaseGroup::from_key(target) };
|
||||
if group.is_none() && !single && target != "all" {
|
||||
self.report.skip("custom eases of unknown properties (left out)");
|
||||
continue;
|
||||
}
|
||||
let Some(e) = self.ease_curve(c) else { continue };
|
||||
match group {
|
||||
Some(g) if !groups.iter().any(|(x, _)| *x == g) => groups.push((g, e)),
|
||||
None if main.is_none() => main = Some(e),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut t = Tween { easing: main.unwrap_or(classic), ..Tween::default() };
|
||||
for (g, e) in groups {
|
||||
t.set_ease(g, Some(e));
|
||||
}
|
||||
(t.easing, t.groups)
|
||||
}
|
||||
|
||||
/// One `<CustomEase>` curve; `None` (reported) when its points don't make a curve.
|
||||
fn ease_curve(&mut self, c: &X) -> Option<Easing> {
|
||||
// Far more than a curve keeps (longer ones are thinned), and one more to tell.
|
||||
const MAX_READ: usize = anicraft_doc::MAX_EASE_POINTS * 3 * 16 + 1;
|
||||
let pts: Vec<Vec2> = c.children.iter().filter(|p| p.name == "Point").take(MAX_READ + 1).map(|p| Vec2::new(p.f32("x").unwrap_or(0.0), p.f32("y").unwrap_or(0.0))).collect();
|
||||
if pts.len() > MAX_READ {
|
||||
self.report.skip("custom ease curves too long to read (drawn with the simple ease)");
|
||||
return None;
|
||||
}
|
||||
let Some(curve) = CustomEase::from_flat(&pts) else {
|
||||
self.report.skip("custom ease curves with a broken point list (drawn with the simple ease)");
|
||||
return None;
|
||||
};
|
||||
let near = |p: Option<&Vec2>, x: f32, y: f32| p.is_some_and(|p| (p.x - x).abs() < 1e-3 && (p.y - y).abs() < 1e-3);
|
||||
if !near(pts.first(), 0.0, 0.0) || !near(pts.last(), 1.0, 1.0) {
|
||||
self.report.skip("custom ease curves not from (0, 0) to (1, 1) (ends moved there)");
|
||||
}
|
||||
if pts.len() / 3 + 1 > anicraft_doc::MAX_EASE_POINTS {
|
||||
self.report.skip("custom ease curves over 64 points (thinned)");
|
||||
}
|
||||
Some(match curve.points() {
|
||||
[a, b] => Easing::CubicBezier(a.out.x, a.out.y, b.at.x + b.h_in.x, b.at.y + b.h_in.y),
|
||||
_ => Easing::Custom(Arc::new(curve)),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+25
-11
@@ -88,7 +88,7 @@ fn stage_layers_frames_and_tweens() {
|
||||
assert_eq!(ball.keyframes.len(), 2);
|
||||
assert_eq!((ball.keyframes[0].start, ball.keyframes[0].duration), (0, 10));
|
||||
assert_eq!(ball.keyframes[0].label, "start");
|
||||
assert!(matches!(ball.keyframes[0].tween.map(|t| t.easing), Some(anicraft_doc::Easing::Classic(e)) if e == -50.0));
|
||||
assert!(matches!(ball.keyframes[0].tween.as_ref().map(|t| t.easing.clone()), Some(anicraft_doc::Easing::Classic(e)) if e == -50.0));
|
||||
assert!(doc.timeline(0).layers[1].locked);
|
||||
assert_eq!((doc.timeline(0).layers[0].height(), doc.timeline(0).layers[1].height()), (1, 2), "Layer Properties height");
|
||||
assert_eq!(doc.timeline(0).layers[2].kind, LayerKind::Guide);
|
||||
@@ -238,7 +238,7 @@ fn shape_tweens_come_across_as_shape_tweens() {
|
||||
let doc: &'static str = Box::leak(doc.into_boxed_str());
|
||||
let (d, report) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap();
|
||||
let k = &d.timeline(0).layers[0].keyframes[0];
|
||||
let t = k.tween.expect("a tween");
|
||||
let t = k.tween.clone().expect("a tween");
|
||||
assert_eq!(t.kind, anicraft_doc::TweenKind::Shape);
|
||||
assert!(matches!(t.easing, anicraft_doc::Easing::Classic(a) if a == 40.0));
|
||||
assert!(report.skipped.keys().all(|s| !s.contains("shape tween")), "{:?}", report.skipped);
|
||||
@@ -384,27 +384,41 @@ fn eases_names_and_loop_modes_the_corpus_found_missing() {
|
||||
let frame = |attrs: &str, inner: &str| format!(r#"<DOMFrame index="0" duration="4" tweenType="motion" {attrs}>{inner}<elements><DOMSymbolInstance libraryItemName="Clip" name="my clip" loop="loop reverse"/></elements></DOMFrame><DOMFrame index="4"><elements/></DOMFrame>"#);
|
||||
let pts = |p: &[(f32, f32)]| p.iter().map(|(x, y)| format!(r#"<Point x="{x}" y="{y}"/>"#)).collect::<String>();
|
||||
let layers = [
|
||||
// Seven points: a curve of two segments, drawn with the slider's ease.
|
||||
// Seven points: a curve of two segments, exactly.
|
||||
frame(r#"hasCustomEase="true" acceleration="30""#, &format!(r#"<tweens><CustomEase target="all">{}</CustomEase></tweens>"#, pts(&[(0.0, 0.0), (0.2, 0.0), (0.3, 0.5), (0.5, 0.5), (0.7, 0.5), (0.8, 1.0), (1.0, 1.0)]))),
|
||||
// One curve per property: also the slider's.
|
||||
frame(r#"hasCustomEase="true" useSingleEaseCurve="false""#, &format!(r#"<tweens><CustomEase target="position">{0}</CustomEase><CustomEase target="rotation">{0}</CustomEase></tweens>"#, pts(&[(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (1.0, 1.0)]))),
|
||||
// Said to have a custom ease, with none there.
|
||||
// One curve per property: each its own; the slider eases the rest.
|
||||
frame(r#"hasCustomEase="true" useSingleEaseCurve="false" acceleration="-50""#, &format!(r#"<tweens><CustomEase target="position">{0}</CustomEase><CustomEase target="rotation">{1}</CustomEase><CustomEase target="sparkle">{0}</CustomEase></tweens>"#, pts(&[(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (1.0, 1.0)]), pts(&[(0.0, 0.0), (0.1, 0.4), (0.2, 1.2), (0.4, 1.2), (0.6, 1.2), (0.9, 1.0), (1.0, 1.0)]))),
|
||||
// Said to have a custom ease, with none there; and a broken point list.
|
||||
frame(r#"hasCustomEase="true""#, ""),
|
||||
frame(r#"hasCustomEase="true" acceleration="10""#, &format!(r#"<tweens><CustomEase target="all">{}</CustomEase></tweens>"#, pts(&[(0.0, 0.0), (0.5, 0.0), (1.0, 1.0)]))),
|
||||
];
|
||||
let layers: String = layers.iter().map(|f| format!(r#"<DOMLayer name="L"><frames>{f}</frames></DOMLayer>"#)).collect();
|
||||
let doc = format!(r#"<DOMDocument><symbols><Include href="Clip.xml"/></symbols><timelines><DOMTimeline name="Scene 1"><layers>{layers}</layers></DOMTimeline></timelines></DOMDocument>"#);
|
||||
let doc: &'static str = Box::leak(doc.into_boxed_str());
|
||||
let clip = r#"<DOMSymbolItem name="Clip"><timeline><DOMTimeline name="Clip"/></timeline></DOMSymbolItem>"#;
|
||||
let (d, report) = import(&HashMap::from([("DOMDocument.xml", doc), ("LIBRARY/Clip.xml", clip)])).unwrap();
|
||||
let eases: Vec<anicraft_doc::Easing> = d.timeline(0).layers.iter().map(|l| l.keyframes[0].tween.unwrap().easing).collect();
|
||||
assert_eq!(eases, [anicraft_doc::Easing::Classic(30.0), anicraft_doc::Easing::Linear, anicraft_doc::Easing::Linear]);
|
||||
assert_eq!(report.skipped.get("custom ease curves (drawn with the simple ease)"), Some(&3));
|
||||
use anicraft_doc::{CustomEase, EaseGroup, Easing};
|
||||
let tween = |l: usize| d.timeline(0).layers[l].keyframes[0].tween.clone().unwrap();
|
||||
let v = |p: &[(f32, f32)]| p.iter().map(|(x, y)| anicraft_geom::Vec2::new(*x, *y)).collect::<Vec<_>>();
|
||||
let two = CustomEase::from_flat(&v(&[(0.0, 0.0), (0.2, 0.0), (0.3, 0.5), (0.5, 0.5), (0.7, 0.5), (0.8, 1.0), (1.0, 1.0)])).unwrap();
|
||||
assert_eq!(tween(0).easing, Easing::Custom(std::sync::Arc::new(two)), "a two-segment curve, exactly");
|
||||
assert!((tween(0).easing.apply(0.5) - 0.5).abs() < 1e-5 && tween(0).easing.apply(0.25) < 0.4);
|
||||
let per = tween(1);
|
||||
assert_eq!(per.easing, Easing::Classic(-50.0));
|
||||
assert_eq!(per.ease(EaseGroup::Position), &Easing::CubicBezier(0.5, 0.0, 0.5, 1.0));
|
||||
assert!(matches!(per.ease(EaseGroup::Rotation), Easing::Custom(c) if c.points().len() == 3));
|
||||
assert_eq!((per.has_own(EaseGroup::Scale), per.groups.len()), (false, 2));
|
||||
assert_eq!((tween(2).easing, tween(3).easing), (Easing::Linear, Easing::Classic(10.0)));
|
||||
assert_eq!(report.skipped.get("custom eases of unknown properties (left out)"), Some(&1));
|
||||
assert_eq!(report.skipped.get("custom eases without their curve (drawn with the simple ease)"), Some(&1));
|
||||
assert_eq!(report.skipped.get("custom ease curves with a broken point list (drawn with the simple ease)"), Some(&1));
|
||||
assert!(!report.skipped.contains_key("custom ease curves (drawn with the simple ease)"));
|
||||
assert_eq!(d.library[0].kind, SymbolKind::MovieClip, "no symbolType: a movie clip");
|
||||
let ElementKind::Symbol { loop_mode, .. } = &d.timeline(0).layers[0].keyframes[0].elements[0].kind else { panic!() };
|
||||
assert_eq!(*loop_mode, LoopMode::Loop, "loop reverse plays forward");
|
||||
assert_eq!(report.skipped.get("reverse loop modes (played forward)"), Some(&3));
|
||||
assert_eq!(report.skipped.get("reverse loop modes (played forward)"), Some(&4));
|
||||
assert_eq!(d.timeline(0).layers[0].keyframes[0].elements[0].name, "", "not an identifier: left out");
|
||||
assert_eq!(report.skipped.get("instance names actions can't use (left out)"), Some(&3));
|
||||
assert_eq!(report.skipped.get("instance names actions can't use (left out)"), Some(&4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -208,9 +208,24 @@ fn colour_effects_come_across_in_every_style() {
|
||||
#[test]
|
||||
fn tweens_keep_their_kinds_eases_and_hints() {
|
||||
let (doc, _) = import("tweens");
|
||||
let t = |l: usize| doc.timeline(0).layers[l].keyframes[0].tween.expect("a tween");
|
||||
let t = |l: usize| doc.timeline(0).layers[l].keyframes[0].tween.clone().expect("a tween");
|
||||
assert_eq!((t(0).kind, t(0).easing), (TweenKind::Classic, Easing::Classic(-100.0)));
|
||||
assert_eq!(t(1).easing, Easing::CubicBezier(0.7, 0.0, 0.3, 1.0), "a one-segment custom ease is a cubic Bézier");
|
||||
// Per-property custom eases (ADR 0081): position's of three segments, exactly, overshooting
|
||||
// and settling; scale's of one; the rest linear.
|
||||
use anicraft_doc::EaseGroup;
|
||||
let per = t(5);
|
||||
assert_eq!(per.easing, Easing::Linear);
|
||||
let Easing::Custom(pos) = per.ease(EaseGroup::Position) else { panic!("{per:?}") };
|
||||
let anchors: Vec<(f32, f32)> = pos.points().iter().map(|p| (p.at.x, p.at.y)).collect();
|
||||
assert_eq!(anchors, [(0.0, 0.0), (0.4, 1.3), (0.7, 0.8), (1.0, 1.0)]);
|
||||
assert!((pos.points()[1].h_in.x + 0.15).abs() < 1e-5 && (pos.points()[1].out.x - 0.15).abs() < 1e-5);
|
||||
assert_eq!(per.ease(EaseGroup::Scale), &Easing::CubicBezier(0.8, 0.0, 0.9, 0.5));
|
||||
assert_eq!(per.ease(EaseGroup::Rotation), &Easing::Linear);
|
||||
// At the middle frame the ball is past its end (x 180), still at full size.
|
||||
let el = anicraft_doc::evaluate_layer_elements(&doc.timeline(0).layers[5], 6).unwrap().1[0].clone();
|
||||
let m = el.transform.decompose();
|
||||
assert!(m.tx > 180.0 && (m.sx - (1.0 + 0.5 * Easing::CubicBezier(0.8, 0.0, 0.9, 0.5).apply(0.5))).abs() < 1e-3, "{m:?}");
|
||||
assert_eq!((t(3).kind, t(3).easing), (TweenKind::Shape, Easing::Classic(50.0)));
|
||||
let hints = &doc.timeline(0).layers[3].keyframes[0].hints;
|
||||
assert_eq!(hints.len(), 1);
|
||||
@@ -251,7 +266,7 @@ fn guides_guide_and_never_draw() {
|
||||
let l = &doc.timeline(0).layers;
|
||||
assert_eq!((l[0].kind, l[1].kind), (LayerKind::Guide, LayerKind::Guide));
|
||||
assert_eq!((l[2].parent, l[3].parent), (Some(l[1].id), Some(l[1].id)), "both riders follow the arc");
|
||||
assert!(l[2].keyframes[0].tween.is_some_and(|t| t.orient));
|
||||
assert!(l[2].keyframes[0].tween.as_ref().is_some_and(|t| t.orient));
|
||||
// Half-way the riders are on the arc, well above the straight line between their ends.
|
||||
let mid = evaluate(&doc, 6);
|
||||
let drawn: Vec<_> = mid.items.iter().filter(|i| !i.guide).collect();
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- AniCraft XFL corpus: tweens. Classic tweens (eased in, a custom ease curve, a turn with
|
||||
extra clockwise spins asked for), a shape tween eased out with a shape hint, and a motion
|
||||
tween (kept as keyframes, reported). Self-authored. -->
|
||||
extra clockwise spins asked for, and per-property custom eases of several segments), a
|
||||
shape tween eased out with a shape hint, and a motion tween (kept as keyframes, reported).
|
||||
Self-authored. -->
|
||||
<DOMDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.adobe.com/xfl/2008/" width="320" height="180" frameRate="24" backgroundColor="#FFFFFF">
|
||||
<symbols>
|
||||
<Include href="Ball.xml" loadImmediate="false"/>
|
||||
@@ -111,6 +112,44 @@
|
||||
</DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
<DOMLayer name="Per-property eases" color="#2A9D8F">
|
||||
<frames>
|
||||
<DOMFrame index="0" duration="12" tweenType="motion" motionTweenSnap="true" keyMode="22017" hasCustomEase="true" useSingleEaseCurve="false" acceleration="0">
|
||||
<tweens>
|
||||
<CustomEase target="position">
|
||||
<Point/>
|
||||
<Point x="0.1" y="0.5"/>
|
||||
<Point x="0.25" y="1.3"/>
|
||||
<Point x="0.4" y="1.3"/>
|
||||
<Point x="0.55" y="1.3"/>
|
||||
<Point x="0.6" y="0.8"/>
|
||||
<Point x="0.7" y="0.8"/>
|
||||
<Point x="0.8" y="0.8"/>
|
||||
<Point x="0.9" y="1"/>
|
||||
<Point x="1" y="1"/>
|
||||
</CustomEase>
|
||||
<CustomEase target="scale">
|
||||
<Point/>
|
||||
<Point x="0.8" y="0"/>
|
||||
<Point x="0.9" y="0.5"/>
|
||||
<Point x="1" y="1"/>
|
||||
</CustomEase>
|
||||
</tweens>
|
||||
<elements>
|
||||
<DOMSymbolInstance libraryItemName="Ball" symbolType="graphic" loop="loop">
|
||||
<matrix><Matrix tx="20" ty="145"/></matrix>
|
||||
</DOMSymbolInstance>
|
||||
</elements>
|
||||
</DOMFrame>
|
||||
<DOMFrame index="12" keyMode="9728">
|
||||
<elements>
|
||||
<DOMSymbolInstance libraryItemName="Ball" symbolType="graphic" loop="loop">
|
||||
<matrix><Matrix a="1.5" d="1.5" tx="180" ty="145"/></matrix>
|
||||
</DOMSymbolInstance>
|
||||
</elements>
|
||||
</DOMFrame>
|
||||
</frames>
|
||||
</DOMLayer>
|
||||
</layers>
|
||||
</DOMTimeline>
|
||||
</timelines>
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.1 KiB After Width: | Height: | Size: 2.3 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 3.0 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 3.0 KiB |
@@ -79,7 +79,9 @@ Headless: `timeline.create_motion_tween`, `timeline.remove_tween`, `motion.set_k
|
||||
* Motion paths drawn and edited on the stage, with orient to path, came in ADR 0030.
|
||||
* Tint colour (red, green, blue), brightness and the eight Advanced properties came in ADR
|
||||
0056, with one colour effect style per tween as in Animate (keys in several styles compose).
|
||||
* Not yet (later PRs): dragging keys in time in the Motion Editor, ease presets with
|
||||
strengths and saved custom eases, 3D rotation and position, Split Motion and joining tweens as commands, Lottie
|
||||
* Ease presets (Classic Ease and nine families), custom eases of several segments and saved
|
||||
eases came in ADR 0081; a segment whose ease one Bézier can't draw is shaped in the Custom
|
||||
Ease window.
|
||||
* Not yet (later PRs): dragging keys in time in the Motion Editor, 3D rotation and position, Split Motion and joining tweens as commands, Lottie
|
||||
export of property curves as eased keyframes (it exports frame-accurate hold keys today),
|
||||
and importing motion tweens from XFL (`motionObjectXML`; still reported, kept as keyframes).
|
||||
@@ -78,7 +78,8 @@ hand from the public descriptions of the format.
|
||||
* a **frame comment** (`labelType="comment"`) was imported as a label that actions could
|
||||
go to; it is now left out and reported (anchors stay labels);
|
||||
* a **custom ease** of one segment is now the cubic Bézier it is; longer curves and
|
||||
per-property curves keep the slider's ease and are reported;
|
||||
per-property curves keep the slider's ease and are reported (since ADR 0081 they import
|
||||
exactly, as custom eases and property-group eases);
|
||||
* reverse loop modes play forward and are reported;
|
||||
* what AniCraft draws the nearest way is now reported instead of silently changed: caps and
|
||||
joins other than round (drawn as they are since ADR 0046), gradient and bitmap strokes, repeating and reflecting gradients,
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# ADR 0081: Ease presets, custom eases and saved eases
|
||||
|
||||
* Status: accepted (2026-11-12)
|
||||
* Relates to: roadmap M7 (graph-based easing presets library) and M2 (Motion Editor), ADR 0016
|
||||
(motion tweens; eases as `Easing`), ADR 0035 (XFL corpus; one-segment custom eases), ADR 0003
|
||||
(file format), ADR 0004 (destructive actions), ADR 0028 (HTML canvas export), ADR 0040
|
||||
(interface languages)
|
||||
|
||||
## Context
|
||||
|
||||
Tweens had eight eases: linear, quad and cubic in/out/in-out, the Classic slider and one cubic
|
||||
Bézier. Artists coming from Animate expect its ease library (Classic Ease with a strength, and
|
||||
Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic, each In, Out and In Out), a
|
||||
custom ease drawn as a curve of several segments, eases they can save and reuse, classic tweens
|
||||
eased property group by property group, and the same choices in the Motion Editor. Animate files
|
||||
carry custom eases of several segments and per-property curves; ADR 0035 drew those with the
|
||||
slider's ease and reported them. Behaviour was learned from Adobe's public help pages and from
|
||||
the public XFL descriptions; the ease formulas are the classic public easing equations.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Presets are pure functions of t, one enum.** `Easing` keeps its unit variants (the file and
|
||||
command names, `"QuadIn"` … `"ElasticInOut"`) and adds the 21 new ones, so files from before
|
||||
read unchanged. Each family defines its ease in, `In(t)`; `Out(t) = 1 − In(1 − t)` and
|
||||
`InOut` is In over the first half and Out over the second (Quad and Cubic in-outs are the
|
||||
same curves as before). Back overshoots by about 10 % (c = 1.70158); Elastic is
|
||||
`−2^(10t−10)·sin((10t − 10.75)·2π/3)`; Bounce is four parabolas. Values may leave 0..1;
|
||||
time never does (`t` is clamped).
|
||||
2. **A custom ease is a curve of Bézier segments, stored by value.** `Easing::Custom(Arc<
|
||||
CustomEase>)`: 2 to 64 points from (0, 0) to (1, 1), each with in and out handles (offsets)
|
||||
and a smooth flag. The type keeps itself valid however it is made (a file, a command, an
|
||||
edit): non-finite points go, points sort by x, longer curves are thinned evenly, the ends are
|
||||
pinned, values stay within ±10, and every handle's x lies between its point and the
|
||||
neighbour it reaches towards. That last rule is what keeps time running forwards: a
|
||||
segment whose inner control points lie between its ends in x has a non-decreasing x(s)
|
||||
(`(u − v)² ≤ u(1 − v)` for any `0 ≤ v < u ≤ 1`), so solving x(s) = t has one answer, found
|
||||
by Newton steps inside a shrinking bracket. Edits are methods that return a new valid curve
|
||||
(`insert_at` splits a segment by de Casteljau so the shape is unchanged; `move_point` keeps
|
||||
x between the neighbours; `move_handle` turns a smooth point's other handle; `set_smooth`;
|
||||
`remove`). `Arc` keeps copying a tween cheap; `Easing` is no longer `Copy`.
|
||||
3. **Classic tweens may ease property groups separately.** `Tween.groups` holds the groups with
|
||||
their own ease (Position, Rotation, Scale, Colour, Filters, as Animate's custom ease offers);
|
||||
a group without one follows the tween's. `evaluate` computes one eased progress per group
|
||||
(`Progress`) and interpolates position, rotation and skew, scale, colour effect and filters
|
||||
each with its own; outlines, fills and strokes follow the tween's ease. With no groups the
|
||||
result is bit for bit what it was. Shape tweens keep one ease, as in Animate. Filters now
|
||||
tween in classic tweens when both keyframes list the same kinds in the same order (numbers
|
||||
and colours travel; switches and quality hold), which the Filters group needs.
|
||||
4. **Saved eases live in the document, and applying one copies it.** `Document.eases`: named
|
||||
eases (any kind, usually custom curves), each name once ignoring case, at most 256. A tween
|
||||
given a saved ease gets its curve, not a reference, as Animate's presets do: evaluation stays
|
||||
a function of the layer alone, a deleted or edited saved ease never changes a tween behind
|
||||
the artist's back, and copied frames and pasted symbols need nothing extra. Menus show a
|
||||
tween's curve by the saved name it equals. Deleting a saved ease is a routine, undoable edit
|
||||
(ADR 0004): no tween loses anything.
|
||||
5. **Everything is an `ease.*` command, addressing one ease.** The target is a tween's ease (or
|
||||
one group's, `group`), a motion-tween property's segment (`property`), or a saved ease
|
||||
(`saved`). `ease.info`, `ease.set`, `ease.add_point`, `ease.move_point`, `ease.move_handle`,
|
||||
`ease.delete_point`, `ease.convert_point`, `ease.separate`, `ease.save`, `ease.delete`,
|
||||
`ease.rename`, `ease.list`, `ease.copy`, `ease.paste`. Point edits turn a preset into the
|
||||
curve that draws it (`Easing::to_custom`: exact for linear, Classic, Bézier, Quad, Cubic,
|
||||
Back and Bounce; Circ as two circular arcs; Quart, Quint, Sine and Elastic fitted by value and
|
||||
slope, all within 0.5 %). `timeline.set_easing` (with `group`) and `motion.set_ease` take the
|
||||
same ease params, saved names included. Plug-ins may use every `ease.*` command except copy
|
||||
and paste (the clipboard is the artist's).
|
||||
6. **The interface.** One ease menu everywhere (timeline header, Properties › Frame, Motion
|
||||
Editor): No Ease, Classic Ease, the families as curve thumbnails In / Out / In Out, the saved
|
||||
eases, Edit Ease…. The **Custom Ease** window (non-modal) shows the graph, overshoot
|
||||
included: click the curve to add a point, drag points and handles (one undo step per drag),
|
||||
double-click for smooth/corner, right-click to delete; the selected point's time and value
|
||||
can be typed; with the graph focused `[` `]` pick a point, the arrows move it, `S`, `+` and
|
||||
Delete do the rest, taken before the app's shortcuts so Delete never reaches the stage. It
|
||||
also turns property groups on, saves, copies, pastes and resets. A named preset shows as its
|
||||
curve alone; editing it makes it Custom. The Motion Editor keeps its handles for eases one
|
||||
Bézier draws and opens the window for the rest.
|
||||
7. **XFL custom eases import exactly.** A `<CustomEase>` of 3n + 1 points becomes a cubic Bézier
|
||||
(one segment) or a custom ease; with `useSingleEaseCurve="false"` each target (`position`,
|
||||
`rotation`, `scale`, `color`, `filters`) becomes that group's ease and `all` (or the slider)
|
||||
the tween's. What can't be read is reported: a missing curve, a broken point list, an
|
||||
unknown target, ends not at (0, 0) and (1, 1), more than 64 points (thinned). The corpus'
|
||||
tweens package gains a per-property layer with a three-segment position curve, with golden
|
||||
frames and colour probes.
|
||||
8. **Exports go through `evaluate`.** Lottie bakes every frame (its own eases are one cubic per
|
||||
key pair, which can't draw a multi-segment, Bounce or Elastic curve exactly), and the HTML
|
||||
canvas page plays the frames AniCraft evaluates; a parity test runs a custom, per-group and
|
||||
Elastic movie in the page's JavaScript player against the Rust player step by step.
|
||||
9. **The file format stays version 3.** `eases`, `groups` and the new `Easing` variants are
|
||||
additive (`#[serde(default)]`, skipped when empty). Older files open unchanged. An older
|
||||
build ignores saved eases and property groups, but refuses a file that uses one of the new
|
||||
eases (it can't read the ease), so such files need this build.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Ease presets, custom curves and saved eases are one model across classic tweens, motion
|
||||
tweens, commands, files, XFL and every export.
|
||||
* A saved ease edited later doesn't update the tweens that used it; Animate behaves the same.
|
||||
* Not yet (later PRs): an "update every tween using this ease" action; ease presets shared
|
||||
between documents (a user library in the preferences); Lottie export that maps eases one
|
||||
Bézier can draw onto Lottie's own eases instead of baking; per-property eases of motion
|
||||
tweens imported from XFL (motion tweens themselves still come in as keyframes); 3D property
|
||||
groups; dragging keys in time in the Motion Editor.
|
||||
@@ -44,7 +44,7 @@ AniCraft doesn't save back to `.fla` or XFL.
|
||||
| Document | Stage size, frame rate and colour; every scene, in order |
|
||||
| Layers | Names, colours, visibility, lock, outline, height; guide, mask and folder layers, masks inside folders and symbols too |
|
||||
| Frames | Keyframes and their lengths, frame labels |
|
||||
| Tweens | Classic tweens with their ease (one-curve custom eases exactly), shape tweens with shape hints, motion guides and Orient to path |
|
||||
| Tweens | Classic tweens with their ease (custom eases of any number of points exactly, and eases set per property: position, rotation, scale, colour, filters), shape tweens with shape hints, motion guides and Orient to path |
|
||||
| Drawing | Shapes as merged drawings, drawing objects and groups, rectangle and oval primitives, solid and gradient fills, strokes with caps, joins, miter limit, dashed and dotted styles |
|
||||
| Symbols | Graphics, movie clips and buttons with their own timelines, nested to any depth; Library folders; loop mode and first frame; 9-slice guides |
|
||||
| Instances | Position and transform, instance names, colour effects in every style (Brightness, Tint, Advanced, Alpha), blend modes, all seven filters |
|
||||
@@ -87,7 +87,6 @@ These come across, but look a little different from Animate, and the report coun
|
||||
* ragged, stipple and hatched strokes (drawn solid);
|
||||
* reverse loop modes (played forward) and extra spins on classic tweens (turned the shortest
|
||||
way);
|
||||
* custom eases with more than one curve (drawn with the simple ease);
|
||||
* in text: justified text (drawn left-aligned), first-line indents, superscript and subscript,
|
||||
vertical text, text rendered as HTML, and lines that mix styles (drawn in their main style).
|
||||
A field whose lines use different styles becomes one text block per style, stacked as in
|
||||
|
||||
@@ -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 314 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 (**F1**) 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 328 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 (**F1**) 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.
|
||||
|
||||
@@ -130,9 +130,9 @@ This page is generated from the command registry, so it always matches the versi
|
||||
- **Create Motion Tween** `timeline.create_motion_tween` · changes the document
|
||||
Parameters: `{layer?, frame?} (several objects on the key become one graphic symbol; a one-frame span grows to a second)`
|
||||
- **Create Classic Tween** `timeline.create_tween` · changes the document
|
||||
Parameters: `{layer?, frame?, easing?}`
|
||||
Parameters: `{layer?, frame?, easing? (as timeline.set_easing takes it)}`
|
||||
- **Create Shape Tween** `timeline.create_shape_tween` · changes the document
|
||||
Parameters: `{layer?, frame?, easing?}`
|
||||
Parameters: `{layer?, frame?, easing? (as timeline.set_easing takes it)}`
|
||||
- **Remove Tween** `timeline.remove_tween` · changes the document
|
||||
Parameters: `{layer?, frame?} (a motion tween leaves its object as it is on the first frame)`
|
||||
- **New Layer** `layer.new` · Insert › Timeline · changes the document
|
||||
@@ -300,7 +300,7 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Move Keyframes** `timeline.move_keyframes` · changes the document
|
||||
Parameters: `{layer? | layers?: [..], from, to?, by, layer_by? (rows down; negative = up)}`
|
||||
- **Set Tween Easing** `timeline.set_easing` · changes the document
|
||||
Parameters: `{easing, layer?, frame?}`
|
||||
Parameters: `{easing: a preset name (Linear, QuadIn … ElasticInOut) | {classic: -100..100} | {bezier: [x1, y1, x2, y2]} | {custom: {points: [..]} | [[x, y], ..]} | {saved: name}, 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?}`
|
||||
- **Frame Label** `timeline.set_label` · changes the document
|
||||
@@ -378,7 +378,7 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Remove Property Keyframe** `motion.remove_key` · changes the document
|
||||
Parameters: `{property? (default: every property), frame?, layer?}`
|
||||
- **Property Ease** `motion.set_ease` · changes the document
|
||||
Parameters: `{easing, property? (default: every property), frame? (inside the segment), layer?}`
|
||||
Parameters: `{easing (as timeline.set_easing takes it, saved eases too), property? (default: every property), frame? (inside the segment), layer?}`
|
||||
- **Motion Tween** `motion.info`
|
||||
Parameters: `{layer?, frame?} → the span's properties, keys, eases and values at the frame, its motion path, its anchors pinned to frames (pins) and where the object is`
|
||||
- **Edit Motion Path** `motion.set_path` · changes the document
|
||||
@@ -399,6 +399,34 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
Parameters: `{anchor? (default: a new anchor where the object is), frame? (the frame to pin it to, between the first and last position keys), layer?}: the object passes the anchor exactly on that frame → {anchor, frame, pins}`
|
||||
- **Unpin Motion Path Point** `motion.unpin_point` · changes the document
|
||||
Parameters: `{anchor? | frame?, layer?}: the anchor shapes the path only again; the X/Y keys of its frame go → {anchor, frame, pins}`
|
||||
- **Ease** `ease.info`
|
||||
Parameters: `{target: layer?, frame?, group? | property? | saved?} → the ease (as easing params take it), its label, and its curve as points (exact unless the preset is fitted)`
|
||||
- **Set Ease** `ease.set` · changes the document
|
||||
Parameters: `{easing: a preset name | {classic: n} | {bezier: [..]} | {custom: ..} | {saved: name}, layer?, frame?, group? | property? | saved?}`
|
||||
- **Add Ease Point** `ease.add_point` · changes the document
|
||||
Parameters: `{t: time 0..1 on the curve (its shape stays), layer?, frame?, group? | property? | saved?} → {index}`
|
||||
- **Move Ease Point** `ease.move_point` · changes the document
|
||||
Parameters: `{index, x (time, kept between its neighbours), y (value, may overshoot), layer?, frame?, group? | property? | saved?} (the ends stay at (0, 0) and (1, 1))`
|
||||
- **Move Ease Handle** `ease.move_handle` · changes the document
|
||||
Parameters: `{index, handle: in|out, x, y (absolute; x stays between the point and its neighbour), layer?, frame?, group? | property? | saved?} (a smooth point's other handle turns with it)`
|
||||
- **Delete Ease Point** `ease.delete_point` · changes the document
|
||||
Parameters: `{index (not an end), layer?, frame?, group? | property? | saved?}`
|
||||
- **Convert Ease Point** `ease.convert_point` · changes the document
|
||||
Parameters: `{index, smooth: bool (handles in line) or corner (handles on the point), layer?, frame?, group? | property? | saved?}`
|
||||
- **Ease Properties Separately** `ease.separate` · changes the document
|
||||
Parameters: `{separate: bool, layer?, frame?}: a classic tween with one ease per property group (each starting from the tween's), or one ease for all (the groups' own go)`
|
||||
- **Save Ease** `ease.save` · changes the document
|
||||
Parameters: `{name, easing? (default: the target's ease), replace?: bool, layer?, frame?, group? | property?} → saved in the document, offered with the presets`
|
||||
- **Delete Saved Ease** `ease.delete` · changes the document
|
||||
Parameters: `{name} (tweens using it keep their curves)`
|
||||
- **Rename Saved Ease** `ease.rename` · changes the document
|
||||
Parameters: `{name, to}`
|
||||
- **Eases** `ease.list`
|
||||
Parameters: `{} → the presets (name, label, family, direction) and the eases saved in the document`
|
||||
- **Copy Ease** `ease.copy`
|
||||
Parameters: `{layer?, frame?, group? | property? | saved?}: the ease, for ease.paste`
|
||||
- **Paste Ease** `ease.paste` · changes the document
|
||||
Parameters: `{layer?, frame?, group? | property? | saved?}: the copied ease onto this target`
|
||||
- **Move Shape Hint** `tween.move_hint` · changes the document
|
||||
Parameters: `{hint: a..z, x, y, side?: start|end (default: the side the frame shows), layer?, frame?} (snaps to the nearest shape edge on that keyframe)`
|
||||
- **Remove Shape Hint** `tween.remove_hint` · changes the document
|
||||
|
||||
+58
-13
@@ -39,18 +39,60 @@ artwork.
|
||||
## Easing
|
||||
|
||||
Easing makes motion speed up or slow down instead of moving at one steady pace. Pick an ease
|
||||
for a classic or shape tween in any of these places:
|
||||
for a classic or shape tween in either of these places:
|
||||
|
||||
* the **Easing** menu in the timeline header (it appears while the playhead is in a tween);
|
||||
* **Properties › Frame › Tween**, which also shows a small picture of the curve;
|
||||
* the right-click menu on the span, under **Ease**.
|
||||
* the ease menu in the timeline header (it appears while the playhead is in a tween);
|
||||
* **Properties › Frame › Ease**, which also shows a small picture of the curve (click it to
|
||||
edit the curve).
|
||||
|
||||
The presets are **Linear**, **Ease in (quad)**, **Ease out (quad)**, **Ease in-out (quad)**,
|
||||
**Ease in (cubic)**, **Ease out (cubic)**, **Ease in-out (cubic)** and **Smooth (bezier)**. An
|
||||
"in" ease starts slowly, an "out" ease ends slowly, and "in-out" does both.
|
||||
The menu holds:
|
||||
|
||||
Motion tweens have their own, finer easing per property: see [The Motion
|
||||
Editor](#the-motion-editor).
|
||||
* **No Ease**: a steady pace.
|
||||
* **Classic Ease**: one **Strength**, from −100 (starts slowly) to +100 (ends slowly).
|
||||
* **Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic**, each **In**, **Out** and
|
||||
**In Out**, drawn as small curves. An In ease starts slowly, an Out ease ends slowly, In Out
|
||||
does both. Quad to Quint get steeper in turn; Back overshoots a little and comes back;
|
||||
Bounce lands like a dropped ball; Elastic springs past the end and settles.
|
||||
* The eases you saved in this document (see below).
|
||||
* **Edit Ease…**, which opens the Custom Ease window.
|
||||
|
||||
### Custom eases
|
||||
|
||||
The **Custom Ease** window (Edit Ease…, the ✎ button in Properties, or **Edit Ease…** on the
|
||||
span's right-click menu) shows the ease as a graph: time goes across, progress goes up from
|
||||
0 % (the first keyframe) to 100 % (the next), and the curve may go above or below them for an
|
||||
overshoot or a wind-up.
|
||||
|
||||
* Click the curve to add a point. The shape doesn't change until you move it.
|
||||
* Drag a point, or the handles of the selected point, to shape the curve. Each drag is one
|
||||
undo step. A point can't pass its neighbours, so time never runs backwards.
|
||||
* Double-click a point to make it smooth (handles in line) or a corner. Right-click a point to
|
||||
delete it. The two ends stay where they are.
|
||||
* The selected point's **Time** and **Value** can be typed below the graph.
|
||||
* With the graph focused, the keyboard does the same: `[` and `]` pick a point, the arrows move
|
||||
it (Shift moves ten times further), `S` makes it smooth or a corner, `+` adds a point after
|
||||
it, and Delete removes it.
|
||||
|
||||
Picking a preset and then dragging its curve turns it into a custom ease. **Reset** goes back
|
||||
to No Ease.
|
||||
|
||||
**Ease each property separately** gives a classic tween one ease for each of **Position**,
|
||||
**Rotation**, **Scale**, **Colour** and **Filters**: pick one at the top of the window and
|
||||
shape its curve. Turn it off to use one ease for everything again. (Shape tweens have one
|
||||
ease.)
|
||||
|
||||
### Saving and copying eases
|
||||
|
||||
Type a name beside **Save as** and click **Save** to keep the ease in the document. Saved eases
|
||||
appear in every ease menu, for classic tweens and Motion Editor properties alike. A tween
|
||||
given a saved ease gets a copy of its curve, so changing or deleting the saved ease later
|
||||
doesn't change tweens that already use it. Click a saved ease's name under the buttons to edit
|
||||
it, rename it or delete it.
|
||||
|
||||
**Copy Ease** and **Paste Ease** (in the window, or on the span's right-click menu) carry an
|
||||
ease from one tween, property group or Motion Editor segment to another.
|
||||
|
||||
Motion tweens have their own easing per property: see [The Motion Editor](#the-motion-editor).
|
||||
|
||||
## Shape tweens
|
||||
|
||||
@@ -131,8 +173,10 @@ On the right is the selected property's curve:
|
||||
* double-click to add a key;
|
||||
* click to move the playhead.
|
||||
|
||||
Under **Ease**, pick a preset for the segment at the playhead. **Same for all** gives every
|
||||
property's segment there the same ease. Each drag is one undo step.
|
||||
Under **Ease**, pick a preset or a saved ease for the segment at the playhead, or click ✎ to
|
||||
shape it in the Custom Ease window. Eases that one curve can't draw (Bounce, Elastic, custom
|
||||
eases of several points) show no handles in the graph: shape them in the window. **Same for
|
||||
all** gives every property's segment there the same ease. Each drag is one undo step.
|
||||
|
||||
**Remove Tween** takes the motion tween away, leaving the object as it is on the span's first
|
||||
frame.
|
||||
@@ -198,8 +242,9 @@ Classic tweens can follow a path too, using a motion guide layer. See
|
||||
|
||||
## Tweens in Animate files
|
||||
|
||||
When you open an Animate document, its classic tweens (with their eases), shape tweens and shape
|
||||
hints come across. Motion tweens and their motion paths don't come across from Animate files
|
||||
When you open an Animate document, its classic tweens (with their eases, custom eases of any
|
||||
number of points and eases set per property included), shape tweens and shape hints come
|
||||
across. Motion tweens and their motion paths don't come across from Animate files
|
||||
yet. See [Opening Animate files](opening-animate-files.md).
|
||||
|
||||
## Next steps
|
||||
|
||||
+3
-3
@@ -10,7 +10,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
|---|---|
|
||||
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`<mask>` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 msLine truncated
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markLine truncated
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with **ease presets and custom eases** (ADR 0081: Classic Ease with a strength and Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic In/Out/In Out; custom eases of up to 64 Bézier points in the Custom Ease window, x kept monotonic, overshoot allowed, keyboard operable, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on eveLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, under or over the artwork, snap accuracy up to Always); Snap to Pixels; one snap engine for every drawing tool, the Selection tool's moves and Free Transform's handles (point › guide › line › grid › pixel, guides and grid per axis); stage only, never exported, on the CPU and GPU stage. Headless: `view.rulers`, `view.grid_show/grid_snap/grid_set`, `view.guides_show/guides_lock/guides_snap/guides_set`, `view.guide_add/guide_move/guide_delete/guides_clear`, `view.snap_pixels`, `view.aids`, `moving` on `draw.snap`. *Not yet:* units other than px, a movable ruler origin, a symbol's own guides, guides and grid from Animate files, Snap Align and Edit Snapping, snapping while rotating. bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing Line truncated
|
||||
| Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, 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
|
||||
@@ -35,12 +35,12 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
|---|---|---|
|
||||
| **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). |
|
||||
| **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); ~~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`). |
|
||||
| **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 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); ~~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); 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); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; graph-based easing presets library. |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool; not yet: instances and shapes in one armature, reshaping a bound shape, painted weights); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode; not yet: tilt, textured brushes); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). |
|
||||
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); next: AppImage desktop integration, portable mode, store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline; next: translated guides, search, PDF, context help); ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout; not yet: moving the tools, dragging a floating window back into a dock, several tabs in one floating window, deleting and renaming workspaces, docks collapsed to icons). |
|
||||
|
||||
## Releases
|
||||
|
||||
+31
@@ -491,6 +491,8 @@ pub struct App {
|
||||
pub test_movie: Option<crate::test_movie::TestMovie>,
|
||||
/// Edit Envelope: a keyframe sound's volume per channel, in its own window (ADR 0039).
|
||||
pub envelope: Option<crate::envelope::EnvelopeEditor>,
|
||||
/// The Custom Ease window (ADR 0081), when open.
|
||||
pub ease: Option<crate::ease_editor::EaseEditor>,
|
||||
pub show_shortcuts: bool,
|
||||
/// The window close was intercepted because of unsaved changes.
|
||||
pub close_dialog: bool,
|
||||
@@ -713,6 +715,7 @@ impl App {
|
||||
actions: crate::actions_panel::State::default(),
|
||||
test_movie: None,
|
||||
envelope: None,
|
||||
ease: None,
|
||||
show_shortcuts: false,
|
||||
close_dialog: false,
|
||||
allow_close: false,
|
||||
@@ -1984,6 +1987,32 @@ impl App {
|
||||
self.run("timeline.goto", json!({"frame": 14}));
|
||||
}
|
||||
}
|
||||
Some(which @ ("ease" | "easepreset")) => {
|
||||
// The demo's ball: its classic tween eased by a custom curve of three segments
|
||||
// that overshoots and settles (saved as "Overshoot"), the Custom Ease window open
|
||||
// on it with a point picked; or Elastic Out on its own Position group.
|
||||
let ball = self.s.timeline().layers.iter().find(|l| l.keyframes.first().is_some_and(|k| k.tween.is_some() && k.motion.is_none())).map(|l| l.id.0);
|
||||
if let Some(id) = ball {
|
||||
self.run("layer.select", json!({"layer": id}));
|
||||
self.run("timeline.goto", json!({"frame": 4}));
|
||||
let start = self.s.active_layer().and_then(|l| l.keyframe_at(4)).map_or(0, |k| k.start);
|
||||
let curve = json!([[0, 0], [0.12, 0.6], [0.22, 1.25], [0.38, 1.25], [0.5, 1.25], [0.55, 0.85], [0.66, 0.85], [0.76, 0.85], [0.86, 1.0], [1, 1]]);
|
||||
self.run("timeline.set_easing", json!({"frame": start, "easing": {"custom": curve}}));
|
||||
self.run("ease.save", json!({"frame": start, "name": "Overshoot"}));
|
||||
if which == "easepreset" {
|
||||
self.run("ease.separate", json!({"separate": true, "frame": start}));
|
||||
self.run("timeline.set_easing", json!({"frame": start, "group": "position", "easing": "ElasticOut"}));
|
||||
}
|
||||
self.s.mark_saved();
|
||||
crate::ease_editor::open_here(self);
|
||||
if let Some(ed) = self.ease.as_mut()
|
||||
&& which == "easepreset"
|
||||
{
|
||||
ed.group = Some(anicraft_engine::doc::EaseGroup::Position);
|
||||
}
|
||||
crate::ease_editor::select(self, if which == "ease" { 1 } else { 3 });
|
||||
}
|
||||
}
|
||||
Some("envelope") => {
|
||||
// The beat with a custom envelope (in from the left, out to the right), its
|
||||
// envelope editor open on a selected point, the layer at 80 %.
|
||||
@@ -2904,6 +2933,7 @@ impl App {
|
||||
crate::warp_tool::consume_keys(self, ctx);
|
||||
}
|
||||
crate::library::consume_keys(self, ctx);
|
||||
crate::ease_editor::consume_keys(self, ctx);
|
||||
let mut fire: Vec<&'static str> = Vec::new();
|
||||
let mut tool = None;
|
||||
let mut play = false;
|
||||
@@ -3384,6 +3414,7 @@ impl App {
|
||||
crate::publish_panel::show(self, &ctx);
|
||||
crate::test_movie::show(self, &ctx);
|
||||
crate::envelope::show(self, &ctx);
|
||||
crate::ease_editor::show(self, &ctx);
|
||||
|
||||
// Never lose work on close: intercept it while there are unsaved changes.
|
||||
if self.allow_close {
|
||||
|
||||
@@ -0,0 +1,750 @@
|
||||
//! Eases (ADR 0081): the ease menu every tween shows, and the Custom Ease window.
|
||||
//!
|
||||
//! The menu offers what Animate's ease presets do: No Ease, Classic Ease (one strength slider),
|
||||
//! and the families Quad, Cubic, Quart, Quint, Sine, Back, Circ, Bounce and Elastic, each In,
|
||||
//! Out and In Out as a curve to click; then the eases saved in the document, and Edit Ease….
|
||||
//!
|
||||
//! The Custom Ease window edits one ease: a classic tween's (or, eased separately, one of its
|
||||
//! property groups': Position, Rotation, Scale, Colour, Filters), a motion-tween property's
|
||||
//! segment, or a saved ease. The graph is time across and progress up, overshoot included:
|
||||
//! click the curve to add a point, drag points and their handles, double-click a point to make
|
||||
//! it smooth or a corner, right-click it to delete it. With the graph focused the keyboard does
|
||||
//! the same: `[` `]` pick the previous or next point, the arrows move it (Shift: ten times
|
||||
//! further), `S` makes it smooth or a corner, `+` adds a point after it, Delete removes it. Its
|
||||
//! time and value can also be typed. Each drag is one undo step, and every change is an
|
||||
//! `ease.*` command, so the stage shows it at once.
|
||||
|
||||
use crate::a11y::{self, Named};
|
||||
use crate::app::App;
|
||||
use crate::theme::{SQUARE, T, Type, font, text, with_type};
|
||||
use anicraft_engine::cmds_ease::{ease_target, read, saved_name};
|
||||
use anicraft_engine::doc::{CustomEase, Document, EaseDir, EaseFamily, EaseGroup, Easing, Handle, Property, TweenKind};
|
||||
use anicraft_engine::params::easing_json;
|
||||
use egui::{Align2, Key, Modifiers, Pos2, Rect, Sense, Stroke, WidgetType, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The graph's height, and the room around the curve inside it.
|
||||
const GRAPH_H: f32 = 250.0;
|
||||
const PAD_X: f32 = 34.0;
|
||||
const PAD_Y: f32 = 16.0;
|
||||
/// Pointer distance that takes a point, a handle or the curve.
|
||||
const GRAB: f32 = 8.0;
|
||||
/// A preset's curve in the ease menu.
|
||||
const THUMB: egui::Vec2 = egui::Vec2 { x: 44.0, y: 28.0 };
|
||||
|
||||
/// What the window edits, as the `ease.*` commands address it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EaseTarget {
|
||||
/// The classic or shape tween of the span starting at `frame` on `layer`.
|
||||
Tween { layer: u64, frame: u32 },
|
||||
/// The segment of a motion tween's `property` that `frame` is in.
|
||||
Motion { layer: u64, frame: u32, property: Property },
|
||||
/// A saved ease, by name.
|
||||
Saved(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Drag {
|
||||
/// A point or one of its handles; the value range is frozen so the graph doesn't rescale
|
||||
/// under the pointer.
|
||||
Point { i: usize, lo: f32, hi: f32 },
|
||||
Handle { i: usize, h: Handle, lo: f32, hi: f32 },
|
||||
}
|
||||
|
||||
/// The Custom Ease window's state.
|
||||
pub struct EaseEditor {
|
||||
pub target: EaseTarget,
|
||||
/// The property group shown, for a tween eased group by group.
|
||||
pub group: Option<EaseGroup>,
|
||||
pub selected: Option<usize>,
|
||||
drag: Option<Drag>,
|
||||
/// The name typed to save the ease as.
|
||||
save_name: String,
|
||||
/// The graph's id last frame (its keys are taken before the app's shortcuts).
|
||||
graph: Option<egui::Id>,
|
||||
}
|
||||
|
||||
impl EaseEditor {
|
||||
fn new(target: EaseTarget) -> EaseEditor {
|
||||
EaseEditor { target, group: None, selected: None, drag: None, save_name: String::new(), graph: None }
|
||||
}
|
||||
|
||||
/// The target as command params.
|
||||
fn params(&self) -> Value {
|
||||
match &self.target {
|
||||
EaseTarget::Tween { layer, frame } => match self.group {
|
||||
Some(g) => json!({"layer": layer, "frame": frame, "group": g.key()}),
|
||||
None => json!({"layer": layer, "frame": frame}),
|
||||
},
|
||||
EaseTarget::Motion { layer, frame, property } => json!({"layer": layer, "frame": frame, "property": property.key()}),
|
||||
EaseTarget::Saved(n) => json!({"saved": n}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The target's params with `extra`'s.
|
||||
fn with(&self, extra: Value) -> Value {
|
||||
let mut p = self.params();
|
||||
if let (Some(o), Value::Object(e)) = (p.as_object_mut(), extra) {
|
||||
o.extend(e);
|
||||
}
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the window on the tween at the playhead on the active layer: a classic or shape
|
||||
/// tween's ease, or the selected property's segment of a motion tween.
|
||||
pub fn open_here(app: &mut App) {
|
||||
let Some(layer) = app.s.active_layer() else { return };
|
||||
let Some(k) = layer.keyframe_at(app.s.frame) else {
|
||||
app.status_err(tr!("Select a tweened span to edit its ease"));
|
||||
return;
|
||||
};
|
||||
let (lid, start, motion, tween) = (layer.id.0, k.start, k.motion.is_some(), k.tween.is_some());
|
||||
if motion {
|
||||
let p = app.me_prop;
|
||||
open_motion(app, app.s.frame, p);
|
||||
} else if tween {
|
||||
app.ease = Some(EaseEditor::new(EaseTarget::Tween { layer: lid, frame: start }));
|
||||
} else {
|
||||
app.status_err(tr!("This span has no tween: create a classic or motion tween to ease it"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the window on a motion tween property's segment at `frame` (on the active layer).
|
||||
pub fn open_motion(app: &mut App, frame: u32, property: Property) {
|
||||
let Some(layer) = app.s.active_layer().map(|l| l.id.0) else { return };
|
||||
app.ease = Some(EaseEditor::new(EaseTarget::Motion { layer, frame, property }));
|
||||
}
|
||||
|
||||
/// Selects point `i` (screenshots).
|
||||
pub fn select(app: &mut App, i: usize) {
|
||||
if let Some(ed) = app.ease.as_mut() {
|
||||
ed.selected = Some(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ease the window edits, as the document has it now.
|
||||
fn ease_now(app: &App, ed: &EaseEditor) -> Option<Easing> {
|
||||
let at = ease_target(&app.s, &ed.params()).ok()?;
|
||||
read(&app.s, &at).ok()
|
||||
}
|
||||
|
||||
/// An ease's name as the menus show it: a saved custom curve by its name.
|
||||
pub fn label(doc: &Document, e: &Easing) -> String {
|
||||
if matches!(e, Easing::Custom(_) | Easing::CubicBezier(..))
|
||||
&& let Some(n) = saved_name(doc, e)
|
||||
{
|
||||
return n.to_string();
|
||||
}
|
||||
match e {
|
||||
Easing::Linear => tr!("No Ease").to_string(),
|
||||
Easing::Classic(s) => tr!("Classic Ease {strength}", strength = format!("{s:+.0}")),
|
||||
Easing::CubicBezier(..) | Easing::Custom(_) => tr!("Custom").to_string(),
|
||||
named => named.family().map_or_else(|| tr!("Custom").to_string(), |(f, d)| preset_name(f, d)),
|
||||
}
|
||||
}
|
||||
|
||||
fn preset_name(f: EaseFamily, d: EaseDir) -> String {
|
||||
tr!("{family} {direction}", family = crate::i18n::t(f.label()), direction = crate::i18n::t(d.label()))
|
||||
}
|
||||
|
||||
/// What was picked in the ease menu.
|
||||
pub enum Picked {
|
||||
/// An ease, as the easing param of `timeline.set_easing`, `motion.set_ease` or `ease.set`.
|
||||
Ease(Value),
|
||||
/// Edit Ease…: open the Custom Ease window.
|
||||
Edit,
|
||||
}
|
||||
|
||||
/// The ease menu (see the module docs), showing `current`; `name` is its accessible name.
|
||||
pub fn picker(app: &App, ui: &mut egui::Ui, menu: &str, current: &Easing, width: f32, name: &str) -> Option<Picked> {
|
||||
let mut out = None;
|
||||
let r = egui::ComboBox::from_id_salt(menu).width(width).height(560.0).selected_text(label(&app.s.doc, current)).show_ui(ui, |ui| {
|
||||
ui.set_min_width(4.0 * THUMB.x + 80.0);
|
||||
if ui.selectable_label(*current == Easing::Linear, tr!("No Ease")).clicked() {
|
||||
out = Some(Picked::Ease(json!("Linear")));
|
||||
}
|
||||
let classic = matches!(current, Easing::Classic(_));
|
||||
if ui.selectable_label(classic, tr!("Classic Ease")).on_hover_text(tr!("One strength: −100 eases in, +100 eases out")).clicked() && !classic {
|
||||
out = Some(Picked::Ease(json!({"classic": -50})));
|
||||
}
|
||||
ui.separator();
|
||||
for f in EaseFamily::ALL {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_sized([60.0, THUMB.y], egui::Label::new(text(Type::Label, crate::i18n::t(f.label()))));
|
||||
for d in EaseDir::ALL {
|
||||
let e = Easing::preset(f, d);
|
||||
if thumb(ui, &e, *current == e, &preset_name(f, d)).clicked() {
|
||||
out = Some(Picked::Ease(easing_json(&e)));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if !app.s.doc.eases.is_empty() {
|
||||
ui.separator();
|
||||
ui.label(text(Type::Heading, tr!("Saved eases")));
|
||||
for s in app.s.doc.eases.iter() {
|
||||
if ui.selectable_label(*current == s.ease, &s.name).clicked() {
|
||||
out = Some(Picked::Ease(json!({"saved": s.name})));
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr!("Edit Ease…")).on_hover_text(tr!("Shape the curve point by point, save it, copy it to other tweens")).clicked() {
|
||||
out = Some(Picked::Edit);
|
||||
}
|
||||
});
|
||||
r.response.set_name(name);
|
||||
out
|
||||
}
|
||||
|
||||
/// A preset as a small curve to click.
|
||||
fn thumb(ui: &mut egui::Ui, e: &Easing, on: bool, name: &str) -> egui::Response {
|
||||
let (rect, resp) = ui.allocate_exact_size(THUMB, Sense::click());
|
||||
let p = ui.painter();
|
||||
p.rect_filled(rect, T.rc(), if on { T.accent_dim } else if resp.hovered() { T.hover } else { T.field });
|
||||
plot(p, rect.shrink(4.0), e, -0.35, 1.35, Stroke::new(1.5, if on { T.accent_text } else { T.tween }));
|
||||
a11y::control(ui, &resp, WidgetType::SelectableLabel, name, Some(on));
|
||||
resp.on_hover_text(name)
|
||||
}
|
||||
|
||||
/// `e` drawn into `r`, values `lo..hi` bottom to top.
|
||||
fn plot(p: &egui::Painter, r: Rect, e: &Easing, lo: f32, hi: f32, stroke: Stroke) {
|
||||
let n = (r.width() / 1.5).clamp(16.0, 400.0) as usize;
|
||||
let pts: Vec<Pos2> = (0..=n)
|
||||
.map(|i| {
|
||||
let t = i as f32 / n as f32;
|
||||
pos2(r.left() + t * r.width(), r.bottom() - (e.apply(t) - lo) / (hi - lo).max(1e-6) * r.height())
|
||||
})
|
||||
.collect();
|
||||
p.add(egui::Shape::line(pts, stroke));
|
||||
}
|
||||
|
||||
/// A small plot of `e` (the Properties panel's), opening the window when clicked.
|
||||
pub fn preview(app: &mut App, ui: &mut egui::Ui, e: &Easing) {
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width().min(240.0), 70.0), Sense::click());
|
||||
let (lo, hi) = value_range(&e.to_custom(), e);
|
||||
let p = ui.painter();
|
||||
p.rect_filled(r, T.rc(), if resp.hovered() { T.hover } else { T.field });
|
||||
let inner = r.shrink(8.0);
|
||||
let y = |v: f32| inner.bottom() - (v - lo) / (hi - lo) * inner.height();
|
||||
p.line_segment([pos2(inner.left(), y(0.0)), pos2(inner.right(), y(1.0))], Stroke::new(1.0, T.border));
|
||||
plot(p, inner, e, lo, hi, Stroke::new(2.0, T.tween));
|
||||
a11y::control(ui, &resp, WidgetType::Button, tr!("Edit Ease…"), None);
|
||||
if resp.on_hover_text(tr!("Edit the ease: drag its points and handles")).clicked() {
|
||||
open_here(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// The values the graph shows: the curve, its points and handles, and 0..1, with a margin.
|
||||
fn value_range(c: &CustomEase, e: &Easing) -> (f32, f32) {
|
||||
let (mut lo, mut hi) = (0.0f32, 1.0f32);
|
||||
for i in 0..=200 {
|
||||
let v = e.apply(i as f32 / 200.0);
|
||||
lo = lo.min(v);
|
||||
hi = hi.max(v);
|
||||
}
|
||||
for p in c.points() {
|
||||
for y in [p.at.y, p.at.y + p.h_in.y, p.at.y + p.out.y] {
|
||||
lo = lo.min(y);
|
||||
hi = hi.max(y);
|
||||
}
|
||||
}
|
||||
let m = (hi - lo) * 0.08;
|
||||
(lo - m, hi + m)
|
||||
}
|
||||
|
||||
/// The Custom Ease window, when open.
|
||||
pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(mut ed) = app.ease.take() else { return };
|
||||
// It closes when what it edits goes away (undo, another scene, a removed tween).
|
||||
let Some(ease) = ease_now(app, &ed) else { return };
|
||||
let mut open = true;
|
||||
let title = tr!("Custom Ease");
|
||||
let shown = egui::Window::new(title)
|
||||
.id(egui::Id::new("ease_editor"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
.resizable(true)
|
||||
.default_width(560.0)
|
||||
.min_width(420.0)
|
||||
.show(ctx, |ui| body(app, &mut ed, ui, &ease));
|
||||
a11y::name_title_bar(&shown, title);
|
||||
let esc = ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));
|
||||
if open && !esc {
|
||||
app.ease = Some(ed);
|
||||
}
|
||||
}
|
||||
|
||||
/// What is being eased, in words.
|
||||
fn heading(app: &App, ed: &EaseEditor) -> String {
|
||||
match &ed.target {
|
||||
EaseTarget::Tween { layer, frame } => {
|
||||
let k = app.s.timeline().layer(anicraft_engine::doc::LayerId(*layer)).and_then(|l| l.keyframe_at(*frame).map(|k| (l.name.clone(), k.start, k.end())));
|
||||
let (name, a, b) = k.unwrap_or_default();
|
||||
tr!("Tween on {layer}, frames {a}–{b}", layer = name, a = a + 1, b = b)
|
||||
}
|
||||
EaseTarget::Motion { property, frame, .. } => tr!("Motion tween: {property} at frame {frame}", property = crate::i18n::t(property.label()), frame = frame + 1),
|
||||
EaseTarget::Saved(n) => tr!("Saved ease “{name}”", name = n),
|
||||
}
|
||||
}
|
||||
|
||||
fn body(app: &mut App, ed: &mut EaseEditor, ui: &mut egui::Ui, ease: &Easing) {
|
||||
ui.label(text(Type::Heading, heading(app, ed)));
|
||||
ui.add_space(4.0);
|
||||
// ---- property groups (classic tweens) ----
|
||||
if let EaseTarget::Tween { layer, frame } = ed.target {
|
||||
let tw = app.s.timeline().layer(anicraft_engine::doc::LayerId(layer)).and_then(|l| l.keyframe_at(frame)).and_then(|k| k.tween.clone());
|
||||
if let Some(tw) = tw.filter(|t| t.kind == TweenKind::Classic) {
|
||||
let mut separate = !tw.groups.is_empty();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if crate::theme::checkbox(ui, &mut separate, tr!("Ease each property separately")).on_hover_text(tr!("Position, rotation, scale, colour and filters each with their own ease")).changed() {
|
||||
app.run("ease.separate", json!({"separate": separate, "layer": layer, "frame": frame}));
|
||||
ed.group = separate.then_some(EaseGroup::Position);
|
||||
ed.selected = None;
|
||||
}
|
||||
if separate {
|
||||
ui.add_space(8.0);
|
||||
for g in EaseGroup::ALL {
|
||||
let on = ed.group == Some(g);
|
||||
if ui.selectable_label(on, crate::i18n::t(g.label())).on_hover_text(label(&app.s.doc, tw.ease(g))).clicked() && !on {
|
||||
ed.group = Some(g);
|
||||
ed.selected = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if !separate {
|
||||
ed.group = None;
|
||||
} else if ed.group.is_none() {
|
||||
ed.group = Some(EaseGroup::Position);
|
||||
}
|
||||
}
|
||||
}
|
||||
// ---- the preset menu, the classic strength ----
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(text(Type::Label, tr!("Ease")));
|
||||
match picker(app, ui, "ease_editor_menu", ease, 170.0, tr!("Ease")) {
|
||||
Some(Picked::Ease(e)) => {
|
||||
app.run("ease.set", ed.with(json!({"easing": e})));
|
||||
ed.selected = None;
|
||||
}
|
||||
Some(Picked::Edit) | None => {}
|
||||
}
|
||||
if let Easing::Classic(s) = ease {
|
||||
let mut v = *s;
|
||||
ui.label(text(Type::Label, tr!("Strength")));
|
||||
let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut v).range(-100.0..=100.0).speed(1.0).max_decimals(0))).named(tr!("Classic ease strength"));
|
||||
if r.changed() {
|
||||
crate::panels::live(app, tr_noop!("Ease"), "ease.set", ed.with(json!({"easing": {"classic": v}})));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
// ---- the graph ----
|
||||
graph(app, ed, ui, ease);
|
||||
// ---- the selected point, typed ----
|
||||
let curve = ease.to_custom();
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let n = curve.points().len();
|
||||
match ed.selected.filter(|i| *i < n).and_then(|i| curve.points().get(i).map(|p| (i, *p))) {
|
||||
Some((i, p)) => {
|
||||
ui.label(text(Type::Label, tr!("Point {index} of {count}", index = i + 1, count = n)));
|
||||
let end = i == 0 || i + 1 == n;
|
||||
let (mut x, mut y) = (p.at.x * 100.0, p.at.y * 100.0);
|
||||
ui.add_enabled_ui(!end, |ui| {
|
||||
ui.label(text(Type::Label, tr!("Time")));
|
||||
let rx = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut x).range(0.0..=100.0).speed(0.5).max_decimals(1).suffix(" %"))).named(tr!("Point time"));
|
||||
ui.label(text(Type::Label, tr!("Value")));
|
||||
let ry = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut y).range(-1000.0..=1000.0).speed(0.5).max_decimals(1).suffix(" %"))).named(tr!("Point value"));
|
||||
if rx.changed() || ry.changed() {
|
||||
crate::panels::live(app, tr_noop!("Ease point"), "ease.move_point", ed.with(json!({"index": i, "x": x / 100.0, "y": y / 100.0})));
|
||||
}
|
||||
let mut smooth = p.smooth;
|
||||
if crate::theme::checkbox(ui, &mut smooth, tr!("Smooth")).on_hover_text(tr!("Handles in line (S); off: a corner")).changed() {
|
||||
app.run("ease.convert_point", ed.with(json!({"index": i, "smooth": smooth})));
|
||||
}
|
||||
if ui.button(tr!("Delete Point")).on_hover_text(tr!("Delete or right-click; the ends stay")).clicked() {
|
||||
app.run("ease.delete_point", ed.with(json!({"index": i})));
|
||||
ed.selected = None;
|
||||
}
|
||||
});
|
||||
}
|
||||
None => {
|
||||
ui.label(text(Type::Caption, tr!("Click the curve to add a point; drag points and handles. Keys: [ ] pick a point, arrows move it, S smooth or corner, + add, Delete remove.")));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
// ---- save, copy, paste, reset ----
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let saving_saved = matches!(ed.target, EaseTarget::Saved(_));
|
||||
if !saving_saved {
|
||||
ui.label(text(Type::Label, tr!("Save as")));
|
||||
ui.add(egui::TextEdit::singleline(&mut ed.save_name).desired_width(140.0).hint_text(tr!("Name"))).named(tr!("Saved ease name"));
|
||||
let name = ed.save_name.trim().to_string();
|
||||
let exists = app.s.doc.eases.iter().any(|e| e.name.eq_ignore_ascii_case(&name));
|
||||
let button = if exists { tr!("Replace") } else { tr!("Save") };
|
||||
if ui.add_enabled(!name.is_empty(), egui::Button::new(button)).on_hover_text(tr!("Keep this ease in the document, with the presets, for any tween")).clicked() {
|
||||
app.run("ease.save", ed.with(json!({"name": name, "replace": exists})));
|
||||
}
|
||||
ui.separator();
|
||||
}
|
||||
if ui.button(tr!("Copy Ease")).clicked() {
|
||||
app.run("ease.copy", ed.params());
|
||||
}
|
||||
if ui.add_enabled(app.s.ease_clipboard.is_some(), egui::Button::new(tr!("Paste Ease"))).clicked() {
|
||||
app.run("ease.paste", ed.params());
|
||||
ed.selected = None;
|
||||
}
|
||||
if ui.button(tr!("Reset")).on_hover_text(tr!("No ease: a steady speed")).clicked() {
|
||||
app.run("ease.set", ed.with(json!({"easing": "Linear"})));
|
||||
ed.selected = None;
|
||||
}
|
||||
if let EaseTarget::Saved(n) = ed.target.clone()
|
||||
&& ui.button(tr!("Delete Saved Ease")).on_hover_text(tr!("Tweens using it keep their curves ({undo} to undo)", undo = app.undo_key())).clicked()
|
||||
{
|
||||
app.run("ease.delete", json!({"name": n}));
|
||||
}
|
||||
});
|
||||
if !app.s.doc.eases.is_empty() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(text(Type::Caption, tr!("Saved:")));
|
||||
for s in app.s.doc.eases.iter().map(|s| s.name.clone()).collect::<Vec<_>>() {
|
||||
let on = ed.target == EaseTarget::Saved(s.clone());
|
||||
if ui.selectable_label(on, &s).on_hover_text(tr!("Edit this saved ease")).clicked() && !on {
|
||||
ed.target = EaseTarget::Saved(s);
|
||||
ed.group = None;
|
||||
ed.selected = None;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Screen ↔ ease space of the graph.
|
||||
#[derive(Clone, Copy)]
|
||||
struct View {
|
||||
inner: Rect,
|
||||
lo: f32,
|
||||
hi: f32,
|
||||
}
|
||||
|
||||
impl View {
|
||||
fn at(&self, x: f32, y: f32) -> Pos2 {
|
||||
pos2(self.inner.left() + x * self.inner.width(), self.inner.bottom() - (y - self.lo) / (self.hi - self.lo).max(1e-6) * self.inner.height())
|
||||
}
|
||||
fn time(&self, px: f32) -> f32 {
|
||||
(px - self.inner.left()) / self.inner.width().max(1.0)
|
||||
}
|
||||
fn value(&self, py: f32) -> f32 {
|
||||
self.lo + (self.inner.bottom() - py) / self.inner.height().max(1.0) * (self.hi - self.lo)
|
||||
}
|
||||
}
|
||||
|
||||
fn graph(app: &mut App, ed: &mut EaseEditor, ui: &mut egui::Ui, ease: &Easing) {
|
||||
let curve = ease.to_custom();
|
||||
// A named preset shows as its curve alone (its fitted points would only clutter it);
|
||||
// clicking the curve adds a point and makes it a custom ease to shape.
|
||||
let preset = ease.family().is_some();
|
||||
if preset && ed.drag.is_none() {
|
||||
ed.selected = None;
|
||||
}
|
||||
let pts: &[anicraft_engine::doc::EasePoint] = if preset { &[] } else { curve.points() };
|
||||
let w = ui.available_width().max(320.0);
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(w, GRAPH_H), Sense::click_and_drag());
|
||||
ed.graph = Some(resp.id);
|
||||
// While the graph has focus the arrows move the picked point, not focus.
|
||||
if resp.has_focus() {
|
||||
let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() };
|
||||
ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, filter));
|
||||
}
|
||||
a11y::surface(ui, &resp, &tr!("Ease curve, {count} points. [ and ] pick a point, the arrows move it, S makes it smooth or a corner, + adds one, Delete removes it", count = pts.len()));
|
||||
let (lo, hi) = match ed.drag {
|
||||
Some(Drag::Point { lo, hi, .. } | Drag::Handle { lo, hi, .. }) => (lo, hi),
|
||||
None => value_range(&curve, ease),
|
||||
};
|
||||
let v = View { inner: Rect::from_min_max(rect.min + vec2(PAD_X, PAD_Y), rect.max - vec2(PAD_Y, PAD_Y)), lo, hi };
|
||||
let p = ui.painter_at(rect);
|
||||
p.rect_filled(rect, SQUARE, T.field);
|
||||
// Time quarters, the start and end values, and the straight line for reference.
|
||||
for q in 0..=4 {
|
||||
let x = v.at(q as f32 / 4.0, 0.0).x;
|
||||
p.line_segment([pos2(x, rect.top()), pos2(x, rect.bottom())], Stroke::new(1.0, T.separator));
|
||||
}
|
||||
for (val, tag) in [(0.0, "0%"), (1.0, "100%")] {
|
||||
let y = v.at(0.0, val).y;
|
||||
p.line_segment([pos2(v.inner.left(), y), pos2(v.inner.right(), y)], Stroke::new(1.0, T.border));
|
||||
p.text(pos2(rect.left() + 4.0, y), Align2::LEFT_CENTER, tag, font(Type::DataSmall), T.text_faint);
|
||||
}
|
||||
p.line_segment([v.at(0.0, 0.0), v.at(1.0, 1.0)], Stroke::new(1.0, T.text_faint));
|
||||
plot(&p, v.inner, ease, lo, hi, Stroke::new(2.0, T.tween));
|
||||
// The selected point's handles, then every point.
|
||||
let sel = ed.selected.filter(|i| *i < pts.len());
|
||||
let handles: Vec<(Handle, Pos2)> = sel
|
||||
.and_then(|i| pts.get(i).map(|q| (i, q)))
|
||||
.map(|(i, q)| {
|
||||
let mut hs = Vec::new();
|
||||
if i > 0 {
|
||||
hs.push((Handle::In, v.at(q.at.x + q.h_in.x, q.at.y + q.h_in.y)));
|
||||
}
|
||||
if i + 1 < pts.len() {
|
||||
hs.push((Handle::Out, v.at(q.at.x + q.out.x, q.at.y + q.out.y)));
|
||||
}
|
||||
hs
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if let Some(q) = sel.and_then(|i| pts.get(i)) {
|
||||
let c = v.at(q.at.x, q.at.y);
|
||||
for (_, h) in &handles {
|
||||
p.line_segment([c, *h], Stroke::new(1.0, T.text_faint));
|
||||
p.circle_filled(*h, 4.5, T.tween_shape);
|
||||
p.circle_stroke(*h, 4.5, Stroke::new(1.0, T.ink));
|
||||
}
|
||||
}
|
||||
for (i, q) in pts.iter().enumerate() {
|
||||
let c = v.at(q.at.x, q.at.y);
|
||||
let r = Rect::from_center_size(c, vec2(9.0, 9.0));
|
||||
let picked = sel == Some(i);
|
||||
if q.smooth {
|
||||
p.circle_filled(c, 5.0, if picked { T.accent } else { T.text });
|
||||
p.circle_stroke(c, 5.0, Stroke::new(1.0, T.ink));
|
||||
} else {
|
||||
p.rect_filled(r, SQUARE, if picked { T.accent } else { T.text });
|
||||
p.rect_stroke(r, SQUARE, Stroke::new(1.0, T.ink), egui::StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
// ---- pointer ----
|
||||
let near_point = |pt: Pos2| pts.iter().enumerate().filter(|(_, q)| v.at(q.at.x, q.at.y).distance(pt) <= GRAB).min_by(|a, b| v.at(a.1.at.x, a.1.at.y).distance(pt).total_cmp(&v.at(b.1.at.x, b.1.at.y).distance(pt))).map(|(i, _)| i);
|
||||
let near_handle = |pt: Pos2| handles.iter().find(|(_, h)| h.distance(pt) <= GRAB).map(|(w, _)| *w);
|
||||
let near_curve = |pt: Pos2| {
|
||||
let t = v.time(pt.x);
|
||||
(0.0..=1.0).contains(&t) && (v.at(t, ease.apply(t)).y - pt.y).abs() <= GRAB
|
||||
};
|
||||
if ed.drag.is_none()
|
||||
&& let Some(h) = resp.hover_pos()
|
||||
{
|
||||
if near_handle(h).is_some() || near_point(h).is_some() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
|
||||
} else if near_curve(h) {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
|
||||
}
|
||||
}
|
||||
if resp.drag_started()
|
||||
&& let Some(pt) = ui.input(|i| i.pointer.press_origin())
|
||||
{
|
||||
ed.drag = match (sel, near_handle(pt), near_point(pt)) {
|
||||
(Some(i), Some(h), _) => Some(Drag::Handle { i, h, lo, hi }),
|
||||
(_, _, Some(i)) if i > 0 && i + 1 < pts.len() => Some(Drag::Point { i, lo, hi }),
|
||||
(_, _, Some(i)) => {
|
||||
ed.selected = Some(i);
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(Drag::Point { i, .. }) = ed.drag {
|
||||
ed.selected = Some(i);
|
||||
}
|
||||
if ed.drag.is_some() {
|
||||
app.playing = false;
|
||||
app.s.begin_gesture(tr_noop!("Ease point"));
|
||||
}
|
||||
}
|
||||
if resp.dragged()
|
||||
&& let (Some(d), Some(pt)) = (ed.drag, resp.interact_pointer_pos())
|
||||
{
|
||||
let (x, y) = (v.time(pt.x), v.value(pt.y));
|
||||
match d {
|
||||
Drag::Point { i, .. } => {
|
||||
app.run("ease.move_point", ed.with(json!({"index": i, "x": x, "y": y})));
|
||||
}
|
||||
Drag::Handle { i, h, .. } => {
|
||||
app.run("ease.move_handle", ed.with(json!({"index": i, "handle": if h == Handle::In { "in" } else { "out" }, "x": x, "y": y})));
|
||||
}
|
||||
}
|
||||
}
|
||||
if resp.drag_stopped() && ed.drag.take().is_some() {
|
||||
app.s.end_gesture();
|
||||
}
|
||||
if resp.clicked()
|
||||
&& let Some(pt) = resp.interact_pointer_pos()
|
||||
{
|
||||
match near_point(pt) {
|
||||
Some(i) => ed.selected = Some(i),
|
||||
None if near_curve(pt) => {
|
||||
if let Some(r) = app.run("ease.add_point", ed.with(json!({"t": v.time(pt.x)}))) {
|
||||
ed.selected = r["index"].as_u64().map(|i| i as usize);
|
||||
}
|
||||
}
|
||||
None => ed.selected = None,
|
||||
}
|
||||
}
|
||||
if resp.double_clicked()
|
||||
&& let Some(i) = resp.interact_pointer_pos().and_then(near_point).filter(|i| *i > 0 && *i + 1 < pts.len())
|
||||
&& let Some(q) = pts.get(i)
|
||||
{
|
||||
app.run("ease.convert_point", ed.with(json!({"index": i, "smooth": !q.smooth})));
|
||||
}
|
||||
if resp.secondary_clicked()
|
||||
&& let Some(i) = resp.interact_pointer_pos().and_then(near_point).filter(|i| *i > 0 && *i + 1 < pts.len())
|
||||
{
|
||||
app.run("ease.delete_point", ed.with(json!({"index": i})));
|
||||
ed.selected = None;
|
||||
}
|
||||
resp.on_hover_text_at_pointer(tr!("Click the curve to add a point. Drag a point or handle; double-click a point for smooth or corner, right-click to delete it."));
|
||||
}
|
||||
|
||||
/// The graph's keys, while it has the keyboard (taken before the app's shortcuts, so Delete
|
||||
/// removes a point here rather than artwork on the stage).
|
||||
pub fn consume_keys(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(ed) = app.ease.as_ref() else { return };
|
||||
let Some(id) = ed.graph.filter(|id| ctx.memory(|m| m.has_focus(*id))) else { return };
|
||||
let _ = id;
|
||||
let Some(curve) = ease_now(app, ed).map(|e| e.to_custom()) else { return };
|
||||
let n = curve.points().len();
|
||||
let (prev, next, del, smooth, add, mv) = ctx.input_mut(|i| {
|
||||
let step = if i.modifiers.shift { 0.1 } else { 0.01 };
|
||||
let mut mv = (0.0f32, 0.0f32);
|
||||
for (k, d) in [(Key::ArrowLeft, (-step, 0.0)), (Key::ArrowRight, (step, 0.0)), (Key::ArrowUp, (0.0, step)), (Key::ArrowDown, (0.0, -step))] {
|
||||
if i.consume_key(Modifiers::NONE, k) || i.consume_key(Modifiers::SHIFT, k) {
|
||||
mv = (mv.0 + d.0, mv.1 + d.1);
|
||||
}
|
||||
}
|
||||
let prev = i.consume_key(Modifiers::NONE, Key::OpenBracket);
|
||||
let next = i.consume_key(Modifiers::NONE, Key::CloseBracket);
|
||||
let del = i.consume_key(Modifiers::NONE, Key::Delete) || i.consume_key(Modifiers::NONE, Key::Backspace);
|
||||
let smooth = i.consume_key(Modifiers::NONE, Key::S);
|
||||
let add = i.consume_key(Modifiers::NONE, Key::Plus) || i.consume_key(Modifiers::NONE, Key::Equals) || i.consume_key(Modifiers::SHIFT, Key::Equals) || i.consume_key(Modifiers::NONE, Key::Insert);
|
||||
(prev, next, del, smooth, add, mv)
|
||||
});
|
||||
let Some(ed) = app.ease.as_mut() else { return };
|
||||
let sel = ed.selected.filter(|i| *i < n);
|
||||
if prev || next {
|
||||
ed.selected = Some(match (sel, next) {
|
||||
(None, true) => 0,
|
||||
(None, false) => n.saturating_sub(1),
|
||||
(Some(i), true) => (i + 1).min(n.saturating_sub(1)),
|
||||
(Some(i), false) => i.saturating_sub(1),
|
||||
});
|
||||
return;
|
||||
}
|
||||
let Some(i) = sel else { return };
|
||||
let interior = i > 0 && i + 1 < n;
|
||||
let q = curve.points().get(i).copied();
|
||||
let p = ed.params();
|
||||
let with = |extra: Value| {
|
||||
let mut p = p.clone();
|
||||
if let (Some(o), Value::Object(e)) = (p.as_object_mut(), extra) {
|
||||
o.extend(e);
|
||||
}
|
||||
p
|
||||
};
|
||||
if del && interior {
|
||||
ed.selected = None;
|
||||
app.run("ease.delete_point", with(json!({"index": i})));
|
||||
} else if smooth && interior && let Some(q) = q {
|
||||
app.run("ease.convert_point", with(json!({"index": i, "smooth": !q.smooth})));
|
||||
} else if add && let (Some(a), Some(b)) = (q, curve.points().get(i + 1)) {
|
||||
if let Some(r) = app.run("ease.add_point", with(json!({"t": 0.5 * (a.at.x + b.at.x)})))
|
||||
&& let Some(ed) = app.ease.as_mut()
|
||||
{
|
||||
ed.selected = r["index"].as_u64().map(|i| i as usize);
|
||||
}
|
||||
} else if (mv.0 != 0.0 || mv.1 != 0.0) && interior && let Some(q) = q {
|
||||
app.run("ease.move_point", with(json!({"index": i, "x": q.at.x + mv.0, "y": q.at.y + mv.1})));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_engine::Session;
|
||||
use anicraft_engine::doc::sample;
|
||||
|
||||
fn app(ctx: &egui::Context) -> App {
|
||||
App::with_context(ctx, Session::new(sample::demo()), Some(std::path::PathBuf::from("unused.png")))
|
||||
}
|
||||
|
||||
fn frame(ctx: &egui::Context, app: &mut App, events: Vec<egui::Event>) {
|
||||
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 940.0))), events, ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
consume_keys(app, ui.ctx());
|
||||
show(app, ui.ctx());
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
fn key(k: Key) -> egui::Event {
|
||||
egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
fn points(app: &App) -> usize {
|
||||
app.ease.as_ref().and_then(|ed| ease_now(app, ed)).map_or(0, |e| e.to_custom().points().len())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_draws_and_the_graph_edits_from_the_keyboard() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app(&ctx);
|
||||
app.open_panel(Some("ease"));
|
||||
assert!(app.ease.is_some(), "the demo opens the window on the ball's tween");
|
||||
for _ in 0..3 {
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
}
|
||||
assert!(app.ease.is_some(), "it stays open while drawn");
|
||||
let id = app.ease.as_ref().and_then(|ed| ed.graph).expect("the graph has an id once drawn");
|
||||
ctx.memory_mut(|m| m.request_focus(id));
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
let n = points(&app);
|
||||
assert!(n >= 3);
|
||||
// ] and [ walk the points; + adds one after the picked point; S toggles smooth; arrows
|
||||
// move it; Delete removes it again.
|
||||
frame(&ctx, &mut app, vec![key(Key::CloseBracket)]);
|
||||
frame(&ctx, &mut app, vec![key(Key::OpenBracket)]);
|
||||
let picked = app.ease.as_ref().and_then(|ed| ed.selected);
|
||||
assert!(picked.is_some());
|
||||
frame(&ctx, &mut app, vec![key(Key::Insert)]);
|
||||
assert_eq!(points(&app), n + 1, "a point added");
|
||||
frame(&ctx, &mut app, vec![key(Key::S)]);
|
||||
let at = |app: &App| {
|
||||
let ed = app.ease.as_ref()?;
|
||||
let q = *ease_now(app, ed)?.to_custom().points().get(ed.selected?)?;
|
||||
Some((q.at.x, q.at.y))
|
||||
};
|
||||
let p0 = at(&app).expect("a picked point");
|
||||
frame(&ctx, &mut app, vec![key(Key::ArrowUp)]);
|
||||
frame(&ctx, &mut app, vec![key(Key::ArrowLeft)]);
|
||||
let p1 = at(&app).expect("still picked");
|
||||
assert!(p1.1 > p0.1 && p1.0 < p0.0, "both arrows moved the point (focus stays on the graph): {p0:?} -> {p1:?}");
|
||||
frame(&ctx, &mut app, vec![key(Key::Delete)]);
|
||||
assert_eq!(points(&app), n, "the added point deleted");
|
||||
// Escape closes the window.
|
||||
frame(&ctx, &mut app, vec![key(Key::Escape)]);
|
||||
assert!(app.ease.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_draws_a_group_a_saved_ease_and_closes_when_its_tween_goes() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app(&ctx);
|
||||
app.open_panel(Some("easepreset"));
|
||||
assert!(app.ease.as_ref().is_some_and(|ed| ed.group.is_some()), "the Position group shown");
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
// The saved ease by name.
|
||||
app.ease = Some(EaseEditor::new(EaseTarget::Saved("Overshoot".into())));
|
||||
assert!(heading(&app, app.ease.as_ref().unwrap()).contains("Overshoot"));
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
assert!(app.ease.is_some());
|
||||
// A saved ease that doesn't exist: the window closes.
|
||||
app.ease = Some(EaseEditor::new(EaseTarget::Saved("No such ease".into())));
|
||||
frame(&ctx, &mut app, vec![]);
|
||||
assert!(app.ease.is_none());
|
||||
// No tween at the playhead: nothing opens and the status says why.
|
||||
app.run("layer.new", json!({}));
|
||||
open_here(&mut app);
|
||||
assert!(app.ease.is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values.
|
||||
|
||||
const SOURCES: [(&str, &str); 30] = [
|
||||
const SOURCES: [(&str, &str); 31] = [
|
||||
("ease_editor.rs", include_str!("ease_editor.rs")),
|
||||
("colour.rs", include_str!("colour.rs")),
|
||||
("drop.rs", include_str!("drop.rs")),
|
||||
("recent.rs", include_str!("recent.rs")),
|
||||
|
||||
@@ -123,6 +123,9 @@ fn all_keys() -> BTreeSet<Key> {
|
||||
add(&doc::Easing::Linear.label());
|
||||
doc::Property::ALL.iter().for_each(|p| add(p.label()));
|
||||
doc::ColorStyle::ALL.iter().for_each(|s| add(s.label()));
|
||||
doc::EaseFamily::ALL.iter().for_each(|f| add(f.label()));
|
||||
doc::EaseDir::ALL.iter().for_each(|d| add(d.label()));
|
||||
doc::EaseGroup::ALL.iter().for_each(|g| add(g.label()));
|
||||
doc::ProfilePreset::ALL.iter().for_each(|p| add(p.label()));
|
||||
doc::Cap::ALL.iter().for_each(|c| add(c.label()));
|
||||
doc::Join::ALL.iter().for_each(|j| add(j.label()));
|
||||
|
||||
+2
-1
@@ -45,6 +45,7 @@ mod dialogs;
|
||||
mod dock;
|
||||
mod dock_ui;
|
||||
mod drop;
|
||||
mod ease_editor;
|
||||
mod gpu_stage;
|
||||
mod gradient_tool;
|
||||
mod icons;
|
||||
@@ -255,7 +256,7 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
/// `--help` (the console's text, in English).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// i18n-exempt: the --help console text
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
--shot-width scales the screenshot down to this width (the user guide's pictures)\n\
|
||||
|
||||
+20
-15
@@ -88,8 +88,9 @@ fn value_range(track: Option<&Track>, base: f32, frames: u32, p: Property) -> (f
|
||||
for (i, k) in t.keys.iter().enumerate() {
|
||||
lo = lo.min(k.value);
|
||||
hi = hi.max(k.value);
|
||||
if let Some(n) = t.keys.get(i + 1) {
|
||||
let (_, y1, _, y2) = k.ease.as_bezier();
|
||||
if let Some(n) = t.keys.get(i + 1)
|
||||
&& let Some((_, y1, _, y2)) = k.ease.as_bezier()
|
||||
{
|
||||
for y in [y1, y2] {
|
||||
let v = k.value + (n.value - k.value) * y;
|
||||
lo = lo.min(v);
|
||||
@@ -281,13 +282,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
|
||||
// Keys and the selected segment's handles.
|
||||
let keys: Vec<(u32, f32, Easing)> = track.map(|t| t.keys.iter().filter(|k| k.frame < frames).map(|k| (k.frame, k.value, k.ease)).collect()).unwrap_or_default();
|
||||
let keys: Vec<(u32, f32, Easing)> = track.map(|t| t.keys.iter().filter(|k| k.frame < frames).map(|k| (k.frame, k.value, k.ease.clone())).collect()).unwrap_or_default();
|
||||
// The selected key: the one picked, else the one starting the segment at the playhead.
|
||||
let sel_key = app.me_key.filter(|f| keys.iter().any(|k| k.0 == *f)).or_else(|| keys.iter().rev().find(|k| k.0 <= offset).map(|k| k.0));
|
||||
let handles: Option<[Pos2; 4]> = sel_key.and_then(|f| {
|
||||
let i = keys.iter().position(|k| k.0 == f)?;
|
||||
let (a, b) = (keys.get(i)?, track?.keys.get(i + 1)?);
|
||||
let (x1, y1, x2, y2) = a.2.as_bezier();
|
||||
// Eases one curve can't draw (Bounce, Elastic, custom curves) are shaped in the
|
||||
// Custom Ease window instead.
|
||||
let (x1, y1, x2, y2) = a.2.as_bezier()?;
|
||||
let (f0, f1) = (a.0 as f32, b.frame as f32);
|
||||
let dv = handle_span(a.1, b.value, lo, hi);
|
||||
let at = |x: f32, y: f32| pos2(x_of(f0 + x * (f1 - f0)), y_of(a.1 + y * dv));
|
||||
@@ -364,7 +367,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
&& let Some(i) = t.key_at(frame)
|
||||
&& let (Some(a), Some(b)) = (t.keys.get(i), t.keys.get(i + 1))
|
||||
{
|
||||
let (mut x1, mut y1, mut x2, mut y2) = a.ease.as_bezier();
|
||||
let (mut x1, mut y1, mut x2, mut y2) = a.ease.as_bezier().unwrap_or((1.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0));
|
||||
let span = (b.frame - a.frame).max(1) as f32;
|
||||
let nx = ((f_of(pt.x) - a.frame as f32) / span).clamp(0.0, 1.0);
|
||||
let ny = ((v_of(pt.y) - a.value) / handle_span(a.value, b.value, lo, hi)).clamp(-5.0, 5.0);
|
||||
@@ -448,21 +451,23 @@ fn footer(app: &mut App, ui: &mut egui::Ui, body: Rect, track: Option<&Track>, s
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bar.shrink2(vec2(10.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center)));
|
||||
let ui = &mut child;
|
||||
let p = app.me_prop;
|
||||
let seg = sel_key.zip(track).and_then(|(f, t)| t.key_at(f).filter(|i| *i + 1 < t.keys.len()).and_then(|i| t.keys.get(i)).map(|k| (f, k.ease)));
|
||||
let seg = sel_key.zip(track).and_then(|(f, t)| t.key_at(f).filter(|i| *i + 1 < t.keys.len()).and_then(|i| t.keys.get(i)).map(|k| (f, k.ease.clone())));
|
||||
ui.label(text(Type::Label, tr!("{property} ease", property = crate::i18n::t(p.label()))));
|
||||
match seg {
|
||||
Some((f, ease)) => {
|
||||
egui::ComboBox::from_id_salt("me_ease").width(160.0).selected_text(crate::timeline::easing_label(&ease)).show_ui(ui, |ui| {
|
||||
for (name, e) in Easing::PRESETS {
|
||||
if ui.selectable_label(ease == e, crate::i18n::t(name)).clicked() {
|
||||
app.run("motion.set_ease", json!({"property": p.key(), "frame": start + f, "easing": crate::timeline::easing_param(e)}));
|
||||
}
|
||||
// The presets and the saved eases (ADR 0081); Edit Ease… shapes the segment's curve.
|
||||
match crate::ease_editor::picker(app, ui, "me_ease", &ease, 160.0, tr!("Ease")) {
|
||||
Some(crate::ease_editor::Picked::Ease(e)) => {
|
||||
app.run("motion.set_ease", json!({"property": p.key(), "frame": start + f, "easing": e}));
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Ease"));
|
||||
Some(crate::ease_editor::Picked::Edit) => crate::ease_editor::open_motion(app, start + f, p),
|
||||
None => {}
|
||||
}
|
||||
if ui.button("✎").on_hover_text(tr!("Edit Ease…")).named(tr!("Edit Ease…")).clicked() {
|
||||
crate::ease_editor::open_motion(app, start + f, p);
|
||||
}
|
||||
if ui.button(tr!("Same for all")).on_hover_text(tr!("Give every property's segment at this frame this ease")).clicked() {
|
||||
app.run("motion.set_ease", json!({"frame": start + f, "easing": crate::timeline::easing_param(ease)}));
|
||||
app.run("motion.set_ease", json!({"frame": start + f, "easing": anicraft_engine::params::easing_json(&ease)}));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
|
||||
+27
-28
@@ -5,7 +5,7 @@ use crate::icons::{self, Icon};
|
||||
use crate::theme::{Section, T, TARGET, TOOL_BUTTON, TOOL_ICON, Type, color, section, text, to_color32, with_type};
|
||||
use anicraft_engine::doc::{ColorEffect, ColorStyle, ElementKind, LibraryItem, LineType, MAX_PATH_OFFSET, Paint, Rgba, SymbolKind, TextKind, evaluate_layer_elements};
|
||||
use crate::a11y::{self, Named};
|
||||
use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2};
|
||||
use egui::{Color32, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
// ----- tools --------------------------------------------------------------------------------
|
||||
@@ -2000,19 +2000,34 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L
|
||||
});
|
||||
return;
|
||||
}
|
||||
match k.tween {
|
||||
match k.tween.clone() {
|
||||
Some(t) => {
|
||||
row_prose(ui, tr!("Tween"), |ui| {
|
||||
egui::ComboBox::from_id_salt("prop_ease").width(150.0).selected_text(crate::i18n::t_dyn(&t.easing.label()).into_owned()).show_ui(ui, |ui| {
|
||||
for (name, e) in anicraft_engine::doc::Easing::PRESETS {
|
||||
if ui.selectable_label(t.easing == e, crate::i18n::t(name)).clicked() {
|
||||
app.run("timeline.set_easing", json!({"easing": crate::timeline::easing_param(e)}));
|
||||
}
|
||||
row_prose(ui, tr!("Ease"), |ui| {
|
||||
match crate::ease_editor::picker(app, ui, "prop_ease", &t.easing, 150.0, tr!("Easing")) {
|
||||
Some(crate::ease_editor::Picked::Ease(e)) => {
|
||||
app.run("timeline.set_easing", json!({"easing": e}));
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Easing"));
|
||||
Some(crate::ease_editor::Picked::Edit) => crate::ease_editor::open_here(app),
|
||||
None => {}
|
||||
}
|
||||
if ui.button("✎").on_hover_text(tr!("Edit Ease…")).named(tr!("Edit Ease…")).clicked() {
|
||||
crate::ease_editor::open_here(app);
|
||||
}
|
||||
});
|
||||
// Classic Ease: its strength, as Animate's Ease field.
|
||||
if let anicraft_engine::doc::Easing::Classic(s) = t.easing {
|
||||
let mut v = s;
|
||||
row(ui, tr!("Strength"), |ui| {
|
||||
if ui.add(egui::Slider::new(&mut v, -100.0..=100.0).step_by(1.0)).named(tr!("Classic ease strength")).changed() {
|
||||
live(app, tr_noop!("Ease"), "timeline.set_easing", json!({"easing": {"classic": v}}));
|
||||
}
|
||||
});
|
||||
}
|
||||
// Property groups eased their own way (ADR 0081), named.
|
||||
if !t.groups.is_empty() {
|
||||
let groups: Vec<String> = t.groups.iter().map(|(g, e)| format!("{} {}", crate::i18n::t(g.label()), crate::ease_editor::label(&app.s.doc, e))).collect();
|
||||
ui.label(text(Type::Caption, tr!("Eased separately: {groups}", groups = groups.join(", "))));
|
||||
}
|
||||
let shape = t.kind == anicraft_engine::doc::TweenKind::Shape;
|
||||
row_prose(ui, tr!("Kind"), |ui| {
|
||||
egui::ComboBox::from_id_salt("prop_kind").width(150.0).selected_text(if shape { tr!("Shape") } else { tr!("Classic") }).show_ui(ui, |ui| {
|
||||
@@ -2034,7 +2049,7 @@ fn frame_props(app: &mut App, ui: &mut egui::Ui, layer: &anicraft_engine::doc::L
|
||||
app.run("timeline.set_orient", json!({"orient": orient}));
|
||||
}
|
||||
}
|
||||
ease_curve(ui, t.easing);
|
||||
crate::ease_editor::preview(app, ui, &t.easing);
|
||||
}
|
||||
None => {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
@@ -2587,22 +2602,6 @@ fn line_style_rows(ui: &mut egui::Ui, which: ProfileRow, st: &anicraft_engine::d
|
||||
edit
|
||||
}
|
||||
|
||||
/// Plots the easing curve (output against time).
|
||||
fn ease_curve(ui: &mut egui::Ui, e: anicraft_engine::doc::Easing) {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(ui.available_width().min(240.0), 70.0), Sense::hover());
|
||||
let p = ui.painter();
|
||||
p.rect_filled(r, T.rc(), T.field);
|
||||
let inner = r.shrink(8.0);
|
||||
let pts: Vec<Pos2> = (0..=48)
|
||||
.map(|i| {
|
||||
let t = i as f32 / 48.0;
|
||||
pos2(inner.left() + t * inner.width(), inner.bottom() - e.apply(t) * inner.height())
|
||||
})
|
||||
.collect();
|
||||
p.line_segment([inner.left_bottom(), inner.right_top()], Stroke::new(1.0, T.border));
|
||||
p.add(egui::Shape::line(pts, Stroke::new(2.0, T.tween)));
|
||||
}
|
||||
|
||||
pub(crate) fn library(app: &mut App, ui: &mut egui::Ui) {
|
||||
// Where the panel is, for files dropped on it (ADR 0059).
|
||||
let r = ui.scope(|ui| crate::library::panel(app, ui)).response.rect;
|
||||
|
||||
+21
-42
@@ -4,7 +4,7 @@ use crate::app::App;
|
||||
use crate::icons::{self, Icon};
|
||||
use crate::menus;
|
||||
use crate::theme::{SQUARE, T, TARGET, Type, color, font, text, to_color32, with_type};
|
||||
use anicraft_engine::doc::{Easing, Layer, LayerId, LayerKind, TweenKind};
|
||||
use anicraft_engine::doc::{Layer, LayerId, LayerKind, TweenKind};
|
||||
use crate::a11y::{self, Named};
|
||||
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2};
|
||||
use serde_json::json;
|
||||
@@ -784,7 +784,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
let fill = if motion.is_some() {
|
||||
T.tween_motion
|
||||
} else if tweened {
|
||||
if k.tween.is_some_and(|t| t.kind == TweenKind::Shape) { T.tween_shape } else { T.tween }
|
||||
if k.tween.as_ref().is_some_and(|t| t.kind == TweenKind::Shape) { T.tween_shape } else { T.tween }
|
||||
} else if empty {
|
||||
T.span_empty
|
||||
} else {
|
||||
@@ -1059,20 +1059,22 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
menus::cmd_item(app, ui, "timeline.remove_tween");
|
||||
return;
|
||||
}
|
||||
let tween = here.and_then(|k| k.tween);
|
||||
let tween = here.and_then(|k| k.tween.clone());
|
||||
match tween {
|
||||
Some(t) => {
|
||||
menus::cmd_item(app, ui, "timeline.create_motion_tween");
|
||||
menus::cmd_item(app, ui, if t.kind == TweenKind::Shape { "timeline.create_tween" } else { "timeline.create_shape_tween" });
|
||||
menus::cmd_item(app, ui, "timeline.remove_tween");
|
||||
ui.menu_button(tr!("Ease"), |ui| {
|
||||
for (name, e) in Easing::PRESETS {
|
||||
if ui.selectable_label(t.easing == e, crate::i18n::t(name)).clicked() {
|
||||
app.run("timeline.set_easing", json!({"easing": easing_param(e)}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
// Eases (ADR 0081): the window, and an ease carried from one tween to another.
|
||||
if ui.button(tr!("Edit Ease…")).clicked() {
|
||||
crate::ease_editor::open_here(app);
|
||||
ui.close();
|
||||
}
|
||||
menus::cmd_item(app, ui, "ease.copy");
|
||||
if app.s.ease_clipboard.is_some() {
|
||||
menus::cmd_item(app, ui, "ease.paste");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
menus::cmd_item(app, ui, "timeline.create_motion_tween");
|
||||
@@ -1322,7 +1324,7 @@ pub fn span_text(k: &anicraft_engine::doc::Keyframe, next_adjacent: bool) -> Str
|
||||
let mut parts: Vec<String> = vec![if k.elements.is_empty() { tr!("blank keyframe").to_string() } else { tr!("keyframe").to_string() }];
|
||||
if k.motion.is_some() {
|
||||
parts.push(tr!("motion tween").to_string());
|
||||
} else if let Some(t) = k.tween {
|
||||
} else if let Some(t) = &k.tween {
|
||||
parts.push(match (t.kind, next_adjacent) {
|
||||
(_, false) => tr!("broken tween").to_string(),
|
||||
(TweenKind::Shape, true) => tr!("shape tween").to_string(),
|
||||
@@ -1460,27 +1462,6 @@ pub fn button_states(app: &App) -> Option<[&'static str; 4]> {
|
||||
(open.kind == anicraft_engine::doc::SymbolKind::Button).then(|| [trc!("button state", "Up"), trc!("button state", "Over"), trc!("button state", "Down"), trc!("button state", "Hit")])
|
||||
}
|
||||
|
||||
pub fn easing_label(e: &Easing) -> String {
|
||||
match e {
|
||||
Easing::Classic(s) => tr!("Classic {strength}", strength = format!("{s:+.0}")),
|
||||
other => crate::i18n::t_dyn(&other.label()).into_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn easing_param(e: Easing) -> serde_json::Value {
|
||||
match e {
|
||||
Easing::Linear => json!("Linear"),
|
||||
Easing::QuadIn => json!("QuadIn"),
|
||||
Easing::QuadOut => json!("QuadOut"),
|
||||
Easing::QuadInOut => json!("QuadInOut"),
|
||||
Easing::CubicIn => json!("CubicIn"),
|
||||
Easing::CubicOut => json!("CubicOut"),
|
||||
Easing::CubicInOut => json!("CubicInOut"),
|
||||
Easing::Classic(s) => json!({"classic": s}),
|
||||
Easing::CubicBezier(a, b, c, d) => json!({"bezier": [a, b, c, d]}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The timeline header, left to right: transport, readouts, frame and tween buttons.
|
||||
/// The frame rate as the header shows it: whole rates without decimals ("24 fps"), others
|
||||
/// with as many as they need ("29.97 fps", "12.5 fps").
|
||||
@@ -1518,7 +1499,7 @@ fn header(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
}
|
||||
let here = app.s.active_layer().and_then(|l| l.keyframe_at(app.s.frame));
|
||||
let in_tween = here.and_then(|k| k.tween);
|
||||
let in_tween = here.and_then(|k| k.tween.clone());
|
||||
let in_motion = here.is_some_and(|k| k.motion.is_some());
|
||||
if in_motion {
|
||||
egui::ComboBox::from_id_salt("tl_kind").width(120.0).selected_text(tr!("Motion tween")).show_ui(ui, |ui| {
|
||||
@@ -1538,15 +1519,13 @@ fn header(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
match in_tween.filter(|_| !in_motion) {
|
||||
Some(tw) => {
|
||||
egui::ComboBox::from_id_salt("tl_ease").width(112.0).selected_text(easing_label(&tw.easing)).show_ui(ui, |ui| {
|
||||
for (name, e) in Easing::PRESETS {
|
||||
if ui.selectable_label(tw.easing == e, crate::i18n::t(name)).clicked() {
|
||||
app.run("timeline.set_easing", json!({"easing": easing_param(e)}));
|
||||
}
|
||||
match crate::ease_editor::picker(app, ui, "tl_ease", &tw.easing, 112.0, tr!("Easing")) {
|
||||
Some(crate::ease_editor::Picked::Ease(e)) => {
|
||||
app.run("timeline.set_easing", json!({"easing": e}));
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Easing"));
|
||||
Some(crate::ease_editor::Picked::Edit) => crate::ease_editor::open_here(app),
|
||||
None => {}
|
||||
}
|
||||
// The tween's kind: classic ⇄ shape (keeping the easing), or none.
|
||||
let shape = tw.kind == TweenKind::Shape;
|
||||
egui::ComboBox::from_id_salt("tl_kind").width(104.0).selected_text(if shape { tr!("Shape tween") } else { tr!("Classic tween") }).show_ui(ui, |ui| {
|
||||
|
||||
Reference in new issue
Block a user