M13.16: puppet Follow-Through — puppet.follow (Puppet tool bar ▸ Follow-Through…) makes pins trail a leader pin for hair, cloth and overlapping action: each follower's Position adds the leader's displacement from rest delayed by delay (the k-th nearest by k × delay with Cascade), scaled by Amount, keeping its own keyframes; leader = the first selected pin, followers = the others; one undo step; reachable over MCP (execute_command)

This commit is contained in:
bflatastic
2026-10-04 00:19:26 +07:00
parent 6ec177de83
commit a02bcc8441
8 changed files with 172 additions and 2 deletions
+73 -1
View File
@@ -2,7 +2,8 @@
//! Overlap pins), mesh options, and a query of the current mesh for overlays and agents.
//!
//! Pins are selected like properties (`puppet.selectPins`; Edit ▸ Clear / Delete removes the
//! selected pins, not their layer).
//! selected pins, not their layer). Follow-Through (`puppet.follow`) makes pins trail a leader pin
//! with a delay, for hair, cloth and overlapping action.
//!
//! Pin positions are layer space. A new pin is attached to the mesh under it: the click is
//! mapped back through the current deformation to the rest mesh (its hidden rest position), and
@@ -523,6 +524,68 @@ fn record_pin(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"keys": n, "start": start.seconds(), "end": end.seconds(), "frames": nframes + 1}))
}
/// Follow-Through (hair, cloth, tails, overlapping action): each follower pin trails the leader
/// pin's motion by a delay, through an expression on its Position. The followers nearest the
/// leader trail least; with `cascade` the k-th nearest trails k × `delay`, otherwise all trail by
/// `delay`. `amount` (%) scales the motion they inherit; their own keyframes still add on top.
/// The leader is `leader`, else the first selected pin; the followers are `pins`, else the other
/// selected pins of the leader's layer. One undo step.
fn follow(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "puppet.follow";
let (cid, lid, leader, mut followers) = match p.get("leader") {
Some(k) => {
let (cid, lid) = layer_p(s, p, cmd)?;
let leader = pin_uid(s, cid, lid, k, cmd)?;
let rest: Vec<Uid> = pins_p(s, p, cmd)?.into_iter().filter(|(_, l, u)| *l == lid && *u != leader).map(|x| x.2).collect();
(cid, lid, leader, rest)
}
None => {
let sel = pins_p(s, p, cmd)?;
let (cid, lid, leader) = sel[0];
(cid, lid, leader, sel.iter().skip(1).filter(|(_, l, _)| *l == lid).map(|x| x.2).collect())
}
};
followers.dedup();
if followers.is_empty() {
return Err(bad(cmd, "select the leader pin first, then the pins that follow it (or pass `leader` and `pins`)"));
}
let delay = f_p(p, "delay").unwrap_or(0.1).clamp(0.0, 10.0);
let amount = f_p(p, "amount").unwrap_or(100.0) / 100.0;
let cascade = super::b_p(p, "cascade").unwrap_or(true);
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
// (Position uid, rest) of a pin that moves.
let moving = |uid: Uid| -> Result<(Uid, [f64; 2], String)> {
let g = layer.props.find_group(uid).ok_or_else(|| bad(cmd, "pin gone"))?;
if !PinKind::from_index(g.get("kind").map(|k| k.value.as_enum()).unwrap_or(0)).moves() {
return Err(bad(cmd, format!("`{}` has no Position (only Position and Advanced pins follow or lead)", g.name)));
}
let pos = g.get("position").ok_or_else(|| bad(cmd, "the pin has no Position"))?;
Ok((pos.uid, g.get("rest").map(|r| r.value.as_vec2()).unwrap_or([0.0; 2]), g.name.clone()))
};
let (lead_pos, lead_rest, lead_name) = moving(leader)?;
let reference = super::link::reference(comp, layer, layer, lead_pos, true).ok_or_else(|| bad(cmd, "can't reference the leader pin"))?;
let mut rigs = followers.iter().map(|u| moving(*u).map(|(pos, rest, _)| (*u, pos, rest))).collect::<Result<Vec<_>>>()?;
let dist = |r: [f64; 2]| (r[0] - lead_rest[0]).hypot(r[1] - lead_rest[1]);
rigs.sort_by(|a, b| dist(a.2).total_cmp(&dist(b.2)));
let out = super::app_more::grouped(s, "Follow-Through", |s| {
let mut out = vec![];
for (k, (pin, pos, _)) in rigs.iter().enumerate() {
let d = if cascade { delay * (k + 1) as f64 } else { delay };
let e = format!(
"// Follow-Through: trails {} by {d} s\nvar lead = {reference};\nvalue + (lead.valueAtTime(time - {d}) - [{}, {}]) * {amount}",
serde_json::to_string(&lead_name).unwrap_or_default(),
lead_rest[0],
lead_rest[1]
);
s.execute("prop.setExpression", json!({"comp": cid.0, "layer": lid.0, "prop": pos, "expression": e}))?;
out.push(json!({"pin": pin, "delay": d}));
}
Ok(out)
})?;
Ok(json!({"leader": leader, "pins": out}))
}
/// Record Options (the Puppet tool's Record Options… dialog): `speed`, `smoothing`,
/// `useDraftDeformation`, `showMesh`. Returns the options.
fn record_options(s: &mut Session, p: &Value) -> Result<Value> {
@@ -615,6 +678,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_comp,
record_pin
),
cmd!(
"puppet.follow",
"Follow-Through...",
[],
None,
"{layer?, leader?: uid | name (default: the first selected pin), pins?: [uid | name…] (default: the other selected pins), delay? (s, 0.1), amount? (%, 100), cascade? (true: the k-th nearest pin trails k × delay)}",
has_comp,
follow
),
cmd!(
"puppet.recordOptions",
"Record Options...",
+25
View File
@@ -312,6 +312,31 @@ fn puppet_pins_rig_to_nulls_both_ways() {
assert!(s.execute("paths.tracePath", json!({"layer": id})).is_err());
}
#[test]
fn puppet_follow_through_trails_the_leader_by_cascading_delays() {
let (mut s, id) = setup();
let lead = s.execute("puppet.addPin", json!({"layer": id, "position": [10, 30]})).unwrap()["pin"].clone();
let far = s.execute("puppet.addPin", json!({"layer": id, "position": [90, 30]})).unwrap()["pin"].clone();
let near = s.execute("puppet.addPin", json!({"layer": id, "position": [50, 30]})).unwrap()["pin"].clone();
let pos_uid = |s: &Session, pin: &Value| layer_of(s, id).props.find_group(pin.as_u64().unwrap()).unwrap().get("position").unwrap().uid;
// Leader first, then the followers (in any order): nearer pins trail less.
s.execute("puppet.selectPins", json!({"layer": id, "pins": [lead, far, near]})).unwrap();
let steps = s.history.undo.len();
let r = s.execute("puppet.follow", json!({"delay": 0.2})).unwrap();
assert_eq!(s.history.undo.len(), steps + 1, "one undo step");
assert_eq!(r["leader"], lead);
assert_eq!(r["pins"], json!([{"pin": near, "delay": 0.2}, {"pin": far, "delay": 0.4}]));
let e = expr_of(&s, id, pos_uid(&s, &far));
assert!(e.contains("(\"Puppet Pin 1\")(\"Position\")") && e.contains("valueAtTime(time - 0.4)") && e.contains("- [10, 30]) * 1"), "{e}");
// Without cascade every follower trails by the same delay; `amount` scales the motion.
s.execute("puppet.follow", json!({"layer": id, "leader": "Puppet Pin 1", "pins": [far, near], "delay": 0.25, "amount": 50, "cascade": false})).unwrap();
assert!(expr_of(&s, id, pos_uid(&s, &far)).contains("valueAtTime(time - 0.25)") && expr_of(&s, id, pos_uid(&s, &far)).contains("* 0.5"));
// Errors: no followers, or a pin without a Position.
assert!(s.execute("puppet.follow", json!({"layer": id, "leader": "Puppet Pin 1", "pins": [lead]})).is_err());
let bend = s.execute("puppet.addPin", json!({"layer": id, "kind": "bend", "position": [30, 30]})).unwrap()["pin"].clone();
assert!(s.execute("puppet.follow", json!({"layer": id, "leader": "Puppet Pin 1", "pins": [bend]})).is_err());
}
#[test]
fn project_with_paint_and_puppet_round_trips() {
let (mut s, id) = setup();