feat(doc): shape hints on shape tween keyframes, honoured by evaluate (M2)

This commit is contained in:
Tanish Manku committed 2026-11-09 04:42:22 -07:00
1 parent 42f8304e0e
commit 440261f04b
4 files changed
+262 -8

No files matched your search

+16 -6
View File
@@ -153,20 +153,30 @@ pub fn evaluate_guided<'a>(layer: &'a Layer, frame: u32, guide: Option<&PathWalk
let t = tween.easing.apply((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 els = kf.elements.iter().enumerate().map(|(i, a)| next.elements.get(i).and_then(|b| interpolate(a, b, t, morph, path)).map_or_else(|| a.clone(), Arc::new)).collect();
let pairs = if morph && !kf.hints.is_empty() { crate::hints::hint_pairs(kf, next) } else { Vec::new() };
let els = kf
.elements
.iter()
.enumerate()
.map(|(i, a)| {
let hints: Vec<_> = pairs.iter().filter(|h| h.0 == i).map(|h| (h.1, h.2)).collect();
next.elements.get(i).and_then(|b| interpolate(a, b, t, morph, &hints, path)).map_or_else(|| a.clone(), Arc::new)
})
.collect();
Some((kf.start, Cow::Owned(els)))
}
/// Interpolates two elements; `None` when they cannot tween. With `morph` (a shape tween),
/// shapes of different structure blend through [`anicraft_geom::morph`]; otherwise a shape
/// changes only when both keyframes share its structure.
fn interpolate(a: &Element, b: &Element, t: f32, morph: bool, guide: Option<(&PathWalk, bool)>) -> Option<Element> {
/// 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> {
let kind = match (&a.kind, &b.kind) {
(ElementKind::Shape(sa), ElementKind::Shape(sb)) => {
let path = if Arc::ptr_eq(&sa.path, &sb.path) {
let path = if Arc::ptr_eq(&sa.path, &sb.path) && hints.is_empty() {
sa.path.clone()
} else if morph {
anicraft_geom::morph::morph(&sa.path, &sb.path, t).map(Arc::new).unwrap_or_else(|| sa.path.clone())
anicraft_geom::morph::morph_hinted(&sa.path, &sb.path, hints, t).map(Arc::new).unwrap_or_else(|| sa.path.clone())
} else {
sa.path.lerp(&sb.path, t).map(Arc::new).unwrap_or_else(|| sa.path.clone())
};
+70
View File
@@ -393,3 +393,73 @@ fn motion_tweens_survive_a_file_round_trip_and_old_files_have_none() {
assert!(evaluate(&d2, f).items.iter().all(|i| i.transform.is_finite()));
}
}
/// A square on frame 0 shape-tweening to a circle on frame 10 (the square moved 200 right,
/// so element transforms count too).
fn square_to_circle(hints: Vec<crate::ShapeHint>) -> Document {
let mut d = Document::default();
let el = |id, x, path| Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, 0.0), color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(path, Paint::Solid(Rgba::BLACK))) };
let mut k0 = Keyframe::new(0, 10);
k0.elements.push(Arc::new(el(1, 0.0, Path::rect(0.0, 0.0, 100.0, 100.0))));
k0.tween = Some(Tween { easing: Easing::Linear, kind: TweenKind::Shape, ..Default::default() });
k0.hints = hints;
let mut k1 = Keyframe::new(10, 1);
k1.elements.push(Arc::new(el(1, 200.0, Path::ellipse(50.0, 50.0, 50.0, 50.0))));
layer0(&mut d).keyframes = vec![Arc::new(k0), Arc::new(k1)];
d
}
fn has_anchor(p: &Path, m: &Affine, q: anicraft_geom::Vec2) -> bool {
p.cmds.iter().any(|c| match *c {
anicraft_geom::PathCmd::MoveTo(a) | anicraft_geom::PathCmd::CubicTo(_, _, a) => m.apply(a).distance(q) < 1e-2,
_ => false,
})
}
#[test]
fn shape_hints_carry_the_hinted_corner_where_asked() {
use anicraft_geom::Vec2;
let (corner, bottom) = (Vec2::new(0.0, 0.0), Vec2::new(250.0, 100.0));
let hinted = square_to_circle(vec![crate::ShapeHint { start: corner, end: bottom }]);
let at = |d: &Document, f| {
let dl = evaluate(d, f);
let i = &dl.items[0];
((*i.path).clone(), i.transform)
};
// Halfway the corner is exactly halfway along its way (stage space).
let (p, m) = at(&hinted, 5);
assert!(has_anchor(&p, &m, corner.lerp(bottom, 0.5)), "{p:?}");
// Without the hint it goes elsewhere.
let (p, m) = at(&square_to_circle(Vec::new()), 5);
assert!(!has_anchor(&p, &m, corner.lerp(bottom, 0.5)));
// An unplaced hint (off the outline, as when just added) changes nothing.
let off = square_to_circle(vec![crate::ShapeHint { start: Vec2::new(50.0, 50.0), end: bottom }]);
let plain = square_to_circle(Vec::new());
assert_eq!(*evaluate(&off, 5).items[0].path, *evaluate(&plain, 5).items[0].path);
// The keyframes themselves are untouched by hints.
assert_eq!(*evaluate(&hinted, 0).items[0].path, Path::rect(0.0, 0.0, 100.0, 100.0));
// Placement and the hinted tween lookup.
let l = &hinted.timeline(0).layers[0];
assert_eq!(l.hint_tween_at(0), Some((0, crate::HintSide::Start)));
assert_eq!(l.hint_tween_at(9), Some((0, crate::HintSide::Start)));
assert_eq!(l.hint_tween_at(10), Some((0, crate::HintSide::End)));
assert_eq!(crate::placed_on(&l.keyframes[0].elements, corner), Some(0));
assert_eq!(crate::placed_on(&l.keyframes[1].elements, bottom), Some(0));
assert_eq!(crate::placed_on(&l.keyframes[0].elements, Vec2::new(50.0, 50.0)), None);
assert!(crate::shapes_centre(&l.keyframes[1].elements).unwrap().distance(Vec2::new(250.0, 50.0)) < 1e-3);
}
#[test]
fn shape_hints_survive_a_round_trip_and_old_files_have_none() {
let d = square_to_circle(vec![crate::ShapeHint { start: anicraft_geom::Vec2::new(0.0, 0.0), end: anicraft_geom::Vec2::new(250.0, 100.0) }]);
let k = &d.timeline(0).layers[0].keyframes[0];
let json = serde_json::to_string(&**k).unwrap();
assert!(json.contains("\"hints\""));
let back: Keyframe = serde_json::from_str(&json).unwrap();
assert_eq!(back, **k);
// A keyframe without hints writes none, and a file from before hints reads with none.
let plain = serde_json::to_string(&Keyframe::new(0, 1)).unwrap();
assert!(!plain.contains("hints"));
let old: Keyframe = serde_json::from_str(r#"{"start":0,"duration":3}"#).unwrap();
assert!(old.hints.is_empty());
}
+169
View File
@@ -0,0 +1,169 @@
//! Shape hints (ADR 0023): lettered points that steer a shape tween's morph.
//!
//! A hint lives on the keyframe that starts the shape tween: a point on that keyframe's
//! outline and the point on the next keyframe's outline it becomes, both in the layer's own
//! space. Whether a point is *placed* is never stored: it is placed while it lies on a shape's
//! outline (within [`HINT_TOLERANCE`]). A hint just added sits at the shapes' centre, so it is
//! unplaced until dragged onto an edge; an edit that moves the edge away unplaces it again.
//! The morph uses only hints placed on both keyframes, on the same pair of shapes.
use crate::{Element, ElementKind, Keyframe, Layer, TweenKind};
use anicraft_geom::{Rect, Vec2, morph};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
/// Most hints a shape tween holds: one per letter, `a` to `z`.
pub const MAX_SHAPE_HINTS: usize = morph::MAX_HINTS;
/// How far (in layer units) a hint may sit from an outline and still count as placed on it.
pub const HINT_TOLERANCE: f32 = 0.5;
/// One shape hint: where it sits on the start keyframe and on the end keyframe (layer space).
/// Its letter is its position in the list.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ShapeHint {
pub start: anicraft_geom::Vec2,
pub end: anicraft_geom::Vec2,
}
/// The letter of hint `i` (`a` for the first).
pub fn hint_letter(i: usize) -> char {
char::from(b'a' + (i.min(25) as u8))
}
/// The hint index for a letter (`a`..`z`, either case).
pub fn hint_index(letter: &str) -> Option<usize> {
let mut it = letter.chars();
let c = it.next()?.to_ascii_lowercase();
if it.next().is_some() || !c.is_ascii_lowercase() {
return None;
}
Some((c as u8 - b'a') as usize)
}
/// Which keyframe of a shape tween a hint point belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HintSide {
Start,
End,
}
impl HintSide {
pub fn key(self) -> &'static str {
match self {
HintSide::Start => "start",
HintSide::End => "end",
}
}
pub fn from_key(k: &str) -> Option<HintSide> {
match k {
"start" => Some(HintSide::Start),
"end" => Some(HintSide::End),
_ => None,
}
}
}
impl ShapeHint {
pub fn at(&self, side: HintSide) -> Vec2 {
match side {
HintSide::Start => self.start,
HintSide::End => self.end,
}
}
pub fn at_mut(&mut self, side: HintSide) -> &mut Vec2 {
match side {
HintSide::Start => &mut self.start,
HintSide::End => &mut self.end,
}
}
}
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()
}
/// The shape tween whose hints `frame` shows or edits, and which side: a frame inside a
/// shape tween's span is its start side; the first frame of the keyframe a shape tween
/// ends on is its end side (unless that keyframe starts a shape tween of its own).
pub fn hint_tween_at(&self, frame: u32) -> Option<(usize, HintSide)> {
let i = self.keyframe_index_at(frame)?;
if self.is_shape_tween(i) {
return Some((i, HintSide::Start));
}
let k = self.keyframes.get(i)?;
let prev = i.checked_sub(1)?;
(k.start == frame && self.is_shape_tween(prev)).then_some((prev, HintSide::End))
}
/// The keyframe a side of shape tween `i` shows: `i` itself, or the next one.
pub fn hint_keyframe(&self, i: usize, side: HintSide) -> Option<&Keyframe> {
self.keyframes.get(if side == HintSide::Start { i } else { i + 1 }).map(|k| &**k)
}
}
/// The shape outline among `elements` nearest `p` (layer space): the element's index, the
/// point on its outline and the distance. Only shapes take hints.
pub fn nearest_outline(elements: &[Arc<Element>], p: Vec2) -> Option<(usize, Vec2, f32)> {
let mut best: Option<(usize, Vec2, f32)> = None;
for (i, e) in elements.iter().enumerate() {
let ElementKind::Shape(s) = &e.kind else { continue };
let Some(inv) = e.transform.inverse() else { continue };
let Some((q, _)) = morph::nearest_point(&s.path, inv.apply(p)) else { continue };
let q = e.transform.apply(q);
let d = q.distance(p);
if d.is_finite() && best.is_none_or(|b| d < b.2) {
best = Some((i, q, d));
}
}
best
}
/// The shape element hint point `p` is placed on, if it lies on an outline.
pub fn placed_on(elements: &[Arc<Element>], p: Vec2) -> Option<usize> {
nearest_outline(elements, p).filter(|b| b.2 <= HINT_TOLERANCE).map(|b| b.0)
}
/// The centre of the shapes among `elements` (layer space): where a new hint appears.
pub fn shapes_centre(elements: &[Arc<Element>]) -> Option<Vec2> {
let r = elements.iter().fold(Rect::EMPTY, |r, e| match &e.kind {
ElementKind::Shape(s) => r.union(&s.path.transformed(&e.transform).bounds()),
_ => r,
});
(!r.is_empty() && r.center().is_finite()).then(|| r.center())
}
/// The hints a shape tween from `kf` to `next` applies: those placed on the same element pair
/// on both keyframes, as that pair's index and the points in each element's own coordinates.
pub(crate) fn hint_pairs(kf: &Keyframe, next: &Keyframe) -> Vec<(usize, Vec2, Vec2)> {
kf.hints
.iter()
.take(MAX_SHAPE_HINTS)
.filter_map(|h| {
let i = placed_on(&kf.elements, h.start)?;
(placed_on(&next.elements, h.end)? == i).then_some(())?;
let (a, b) = (kf.elements.get(i)?, next.elements.get(i)?);
Some((i, a.transform.inverse()?.apply(h.start), b.transform.inverse()?.apply(h.end)))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn letters_round_trip() {
assert_eq!(hint_letter(0), 'a');
assert_eq!(hint_letter(25), 'z');
assert_eq!(hint_index("a"), Some(0));
assert_eq!(hint_index("Z"), Some(25));
for bad in ["", "ab", "1", "é", "-"] {
assert_eq!(hint_index(bad), None, "{bad}");
}
}
}
+7 -2
View File
@@ -10,6 +10,7 @@ mod bitmap;
mod filter;
mod easing;
mod eval;
mod hints;
pub mod motion;
pub mod path_table;
pub mod width;
@@ -19,6 +20,7 @@ pub mod sound;
pub use filter::{Filter, MAX_BLUR, MAX_QUALITY};
pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png};
pub use easing::Easing;
pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre};
pub use motion::{MotionTween, Property, PropertyKey, Props, Track};
pub use sound::{FrameSound, Sound, SoundFormat, SoundId, SoundSync};
pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile};
@@ -543,6 +545,9 @@ pub struct Keyframe {
/// or a motion tween, never both; commands keep it so, and a motion tween wins.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub motion: Option<MotionTween>,
/// Shape hints for the shape tween this keyframe starts (ADR 0023), `a` first.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hints: Vec<ShapeHint>,
#[serde(default)]
pub label: String,
/// The sound that starts (or, for Stop, ends) on this keyframe (ADR 0020).
@@ -552,13 +557,13 @@ pub struct Keyframe {
impl PartialEq for Keyframe {
fn eq(&self, o: &Keyframe) -> bool {
self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.label == o.label && self.sound == o.sound && arcs_eq(&self.elements, &o.elements)
self.start == o.start && self.duration == o.duration && self.tween == o.tween && self.motion == o.motion && self.hints == o.hints && self.label == o.label && self.sound == o.sound && arcs_eq(&self.elements, &o.elements)
}
}
impl Keyframe {
pub fn new(start: u32, duration: u32) -> Self {
Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, motion: None, label: String::new(), sound: None }
Keyframe { start, duration: duration.max(1), elements: Vec::new(), tween: None, motion: None, hints: Vec::new(), label: String::new(), sound: None }
}
/// Mutable access to the elements whose ids satisfy `pick`, cloning only those.
pub fn elements_mut_where(&mut self, mut pick: impl FnMut(ElementId) -> bool) -> Vec<&mut Element> {