M6.6: mask tracking + mask interpolation; M12.5: Warp Stabilizer

Mask tracking (track.mask, background job with progress/cancel, one undo
step, Mask Path keys; Tracker panel mask mode; Layer > Mask > Track Mask),
Mask Interpolation panel + mask.interpolate, and the Warp Stabilizer
effect (Effect > Distort, AE parameter groups, warp.analyze/cancel/status,
analysis stored in the effect, invalidation on source/in/out/remap edits,
viewer banner, crop/auto-scale/synthesize edges, track points).
Adds the effects -> track same-layer edge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 21:14:29 -04:00
co-authored by Claude Opus 5.5
parent 4bcf1f447c
commit 9645ff9a66
27 changed files with 2560 additions and 50 deletions
+390
View File
@@ -0,0 +1,390 @@
//! Mask tracking (Layer ▸ Mask ▸ Track Mask, the Tracker panel in mask mode) and Smart Mask
//! Interpolation (Window ▸ Mask Interpolation).
use effectcraft_keyframe::{Keyframe, ShapePath, Value as KV};
use effectcraft_path::interp::{self, AddVertices, InterpOpts, Matching};
use effectcraft_project::{Layer, LayerId, Uid};
use effectcraft_time::Tick;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::{CommandSpec, b_p, bad, f_p, has_comp, layer_mut, layer_p, str_p};
use crate::mask_track::{MaskMethod, MaskWork};
use crate::tracking::Direction;
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"track.mask",
"Track Mask",
["Animation"],
None,
"{layer?, mask?: uid|index|name, method?: position|positionScale|positionScaleRotation|positionScaleRotationSkew|perspective, direction?: forward|backward|frameForward|frameBackward, start? (s), end? (s), wait?: block until done}",
has_mask,
track_mask
),
cmd!(
"track.maskMethod",
"Mask Tracking Method",
[],
None,
"{method: position|positionScale|positionScaleRotation|positionScaleRotationSkew|perspective}",
super::always,
mask_method
),
cmd!(
"mask.interpolate",
"Apply Mask Interpolation",
[],
None,
"{layer?, mask?, times?: [from, to] (s; default the selected Mask Path keys), keyframeRate?: n|auto, keyframeFields?, linearVertexPaths?, bendingResistance? (0-100), quality? (0-100), addVertices?: n|false, addVerticesUnit?: pixels|total|percent, matchingMethod?: auto|curve|polyline, oneToOne?, firstVerticesMatch?}",
has_comp,
interpolate
),
cmd!(
"mask.interpolationOptions",
"Mask Interpolation Options",
[],
None,
"{keyframeRate?: n|auto, keyframeFields?, linearVertexPaths?, bendingResistance?, quality?, addVertices?: n|false, addVerticesUnit?: pixels|total|percent, matchingMethod?: auto|curve|polyline, oneToOne?, firstVerticesMatch?}",
super::always,
interp_options
),
]
}
// ---------------------------------------------------------------- mask tracking
/// The mask a command works on: `mask` (uid, 1-based index or name), else the selected mask
/// (Timeline selection or selected vertices), else the layer's only mask.
pub(crate) fn mask_uid(s: &Session, layer: &Layer, p: &Value) -> Option<Uid> {
let masks = layer.masks()?;
if let Some(k) = p.get("mask") {
return match k {
Value::Number(n) => {
let n = n.as_u64()?;
masks.groups().find(|g| g.uid == n).or_else(|| masks.groups().nth((n as usize).checked_sub(1)?)).map(|g| g.uid)
}
Value::String(name) => masks.groups().find(|g| &g.name == name).map(|g| g.uid),
_ => None,
};
}
let is_mask = |u: Uid| masks.groups().any(|g| g.uid == u);
if let Some(u) = s.state.selected_props.iter().filter(|(l, _)| *l == layer.id).map(|(_, u)| *u).find(|u| is_mask(*u)) {
return Some(u);
}
// A selected Mask Path property selects its mask.
if let Some(u) = s
.state
.selected_props
.iter()
.filter(|(l, _)| *l == layer.id)
.find_map(|(_, u)| masks.groups().find(|g| g.get("path").is_some_and(|pr| pr.uid == *u)).map(|g| g.uid))
{
return Some(u);
}
if let Some(v) = s.state.selected_vertices.iter().find(|v| v.layer == layer.id && is_mask(v.mask)) {
return Some(v.mask);
}
let mut it = masks.groups();
match (it.next(), it.next()) {
(Some(g), None) => Some(g.uid),
_ => None,
}
}
/// The selected layer and mask, if any (the Tracker panel's mask mode).
pub fn selected_mask(s: &Session) -> Option<(LayerId, Uid)> {
let comp = s.active_comp()?;
for lid in &s.state.selected_layers {
let Some(l) = comp.layer(*lid) else { continue };
let explicit =
s.state.selected_props.iter().any(|(pl, u)| *pl == *lid && l.masks().is_some_and(|m| m.find_group(*u).is_some() || m.find(*u).is_some()))
|| s.state.selected_vertices.iter().any(|v| v.layer == *lid);
if explicit && let Some(u) = mask_uid(s, l, &json!({})) {
return Some((*lid, u));
}
}
None
}
fn has_mask(s: &Session) -> std::result::Result<(), String> {
has_comp(s)?;
selected_mask(s).map(|_| ()).ok_or_else(|| "select a mask to track".into())
}
fn method_p(p: &Value, cmd: &str) -> Result<Option<MaskMethod>> {
match str_p(p, "method") {
Some(m) => MaskMethod::from_name(m)
.map(Some)
.ok_or_else(|| bad(cmd, format!("unknown method `{m}` (position|positionScale|positionScaleRotation|positionScaleRotationSkew|perspective)"))),
None => Ok(None),
}
}
fn mask_method(s: &mut Session, p: &Value) -> Result<Value> {
let m = method_p(p, "track.maskMethod")?.ok_or_else(|| bad("track.maskMethod", "missing `method`"))?;
s.state.mask_track_method = m;
s.bump();
Ok(json!(m.id()))
}
fn track_mask(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "track.mask";
let (cid, lid) = match p.get("layer") {
Some(_) => layer_p(s, p, CMD)?,
None => match selected_mask(s) {
Some((l, _)) => (s.active_comp_id().ok_or(EngineError::NoComp)?, l),
None => layer_p(s, p, CMD)?,
},
};
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
let uid = mask_uid(s, layer, p).ok_or_else(|| bad(CMD, format!("layer `{}` has no such mask (select one or pass `mask`)", layer.name)))?;
if !layer.has_video() || matches!(layer.source, effectcraft_project::LayerSource::Text | effectcraft_project::LayerSource::Shape) {
return Err(bad(CMD, "the layer has no pixels to track"));
}
let method = method_p(p, CMD)?.unwrap_or(s.state.mask_track_method);
let dir = match str_p(p, "direction") {
Some(d) => Direction::from_name(d).ok_or_else(|| bad(CMD, "direction: forward|backward|frameForward|frameBackward"))?,
None => Direction::Forward,
};
let now = comp.frame_rate.snap_nearest(if s.state.active_comp == Some(cid) { s.time() } else { Tick::ZERO });
let start = f_p(p, "start").map(|v| comp.frame_rate.snap_nearest(Tick::from_seconds_f64(v)));
let end = f_p(p, "end").map(|v| comp.frame_rate.snap_nearest(Tick::from_seconds_f64(v)));
let times = super::track::analysis_times(comp, layer, dir, now, start, end);
if times.len() < 2 {
return Err(bad(CMD, "nothing to track in that direction (at the layer's end)"));
}
let mg = layer.props.find_group(uid).ok_or_else(|| bad(CMD, "no mask"))?;
let KV::Path(path) = mg.get("path").map(|pr| pr.value_at(layer.layer_time(times[0]))).unwrap_or(KV::Scalar(0.0)) else {
return Err(bad(CMD, "the mask has no path"));
};
if path.len() < 2 {
return Err(bad(CMD, "the mask needs at least two vertices"));
}
let work = MaskWork {
project: s.project.clone(),
footage: s.footage.clone(),
expr: s.expr.clone(),
cache: s.layer_cache.clone(),
comp: cid,
layer: lid,
path,
method,
times: times.clone(),
};
s.state.mask_track_method = method;
let wait = b_p(p, "wait").unwrap_or(false);
s.start_mask_track(work, uid, dir, wait).map_err(EngineError::Other)?;
let prog = s.mask_track_progress();
Ok(json!({
"mask": uid,
"method": method.id(),
"frames": times.len() - 1,
"start": times[0].seconds(),
"end": times.last().map(|t| t.seconds()),
"running": s.is_mask_tracking(),
"progress": prog,
}))
}
// ---------------------------------------------------------------- mask interpolation
/// Mask Interpolation panel options (kept in the editor state, serde for agents).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct MaskInterpOptions {
/// Keyframes per second; `None` = Auto (the comp frame rate).
pub keyframe_rate: Option<f64>,
/// Keyframe Fields (doubles the rate).
pub keyframe_fields: bool,
pub linear_vertex_paths: bool,
pub bending_resistance: f64,
pub quality: f64,
/// Add Mask Shape Vertices (value, unit: pixels | total | percent).
pub add_vertices: Option<f64>,
pub add_vertices_unit: String,
pub matching_method: String,
pub one_to_one: bool,
pub first_vertices_match: bool,
}
impl Default for MaskInterpOptions {
fn default() -> Self {
MaskInterpOptions {
keyframe_rate: None,
keyframe_fields: false,
linear_vertex_paths: false,
bending_resistance: 50.0,
quality: 50.0,
add_vertices: Some(5.0),
add_vertices_unit: "pixels".into(),
matching_method: "auto".into(),
one_to_one: false,
first_vertices_match: true,
}
}
}
impl MaskInterpOptions {
pub fn interp(&self) -> InterpOpts {
InterpOpts {
linear: self.linear_vertex_paths,
bending_resistance: self.bending_resistance.clamp(0.0, 100.0),
quality: self.quality.clamp(0.0, 100.0),
add_vertices: self.add_vertices.map(|v| match self.add_vertices_unit.as_str() {
"total" => AddVertices::Total(v.round().max(2.0) as usize),
"percent" => AddVertices::Percent(v),
_ => AddVertices::Pixels(v),
}),
matching: match self.matching_method.as_str() {
"curve" => Matching::Curve,
"polyline" => Matching::Polyline,
_ => Matching::Auto,
},
one_to_one: self.one_to_one,
first_vertices_match: self.first_vertices_match,
}
}
}
/// Merge option parameters into `o`.
fn apply_options(o: &mut MaskInterpOptions, p: &Value, cmd: &str) -> Result<()> {
match p.get("keyframeRate") {
Some(Value::String(s)) if s.eq_ignore_ascii_case("auto") => o.keyframe_rate = None,
Some(Value::Null) => o.keyframe_rate = None,
Some(v) => o.keyframe_rate = Some(v.as_f64().filter(|r| *r > 0.0).ok_or_else(|| bad(cmd, "keyframeRate: a positive number or \"auto\""))?.min(1000.0)),
None => {}
}
for (k, f) in [
("keyframeFields", &mut o.keyframe_fields),
("linearVertexPaths", &mut o.linear_vertex_paths),
("oneToOne", &mut o.one_to_one),
("firstVerticesMatch", &mut o.first_vertices_match),
] {
if let Some(v) = b_p(p, k) {
*f = v;
}
}
if let Some(v) = f_p(p, "bendingResistance") {
o.bending_resistance = v.clamp(0.0, 100.0);
}
if let Some(v) = f_p(p, "quality") {
o.quality = v.clamp(0.0, 100.0);
}
match p.get("addVertices") {
Some(Value::Bool(false)) | Some(Value::Null) => o.add_vertices = None,
Some(Value::Bool(true)) => o.add_vertices = Some(o.add_vertices.unwrap_or(5.0)),
Some(v) => o.add_vertices = Some(v.as_f64().filter(|x| *x > 0.0).ok_or_else(|| bad(cmd, "addVertices: a positive number or false"))?),
None => {}
}
if let Some(u) = str_p(p, "addVerticesUnit") {
let u = u.to_ascii_lowercase();
o.add_vertices_unit = match u.as_str() {
"pixels" | "px" | "pixelsbetweenvertices" => "pixels",
"total" | "totalvertices" => "total",
"percent" | "%" | "percentageofoutline" => "percent",
_ => return Err(bad(cmd, "addVerticesUnit: pixels|total|percent")),
}
.into();
}
if let Some(m) = str_p(p, "matchingMethod") {
let m = m.to_ascii_lowercase();
if !["auto", "curve", "polyline"].contains(&m.as_str()) {
return Err(bad(cmd, "matchingMethod: auto|curve|polyline"));
}
o.matching_method = m;
}
Ok(())
}
fn interp_options(s: &mut Session, p: &Value) -> Result<Value> {
let mut o = s.state.mask_interp.clone();
apply_options(&mut o, p, "mask.interpolationOptions")?;
s.state.mask_interp = o.clone();
s.bump();
Ok(serde_json::to_value(o).unwrap_or(Value::Null))
}
fn interpolate(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "mask.interpolate";
let mut o = s.state.mask_interp.clone();
apply_options(&mut o, p, CMD)?;
// The layer: given, else the layer of selected Mask Path keys, else the selection.
let cid = super::comp_id(s, p)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let lid = match p.get("layer") {
Some(v) => super::resolve_layer(comp, v).ok_or_else(|| bad(CMD, format!("no layer {v}")))?,
None => match s.state.selected_keys.iter().find(|k| comp.layer(k.layer).is_some_and(|l| l.masks().is_some_and(|m| m.find(k.prop).is_some()))) {
Some(k) => k.layer,
None => layer_p(s, p, CMD)?.1,
},
};
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
let masks = layer.masks().ok_or_else(|| bad(CMD, "the layer has no masks"))?;
let uid = match p.get("mask") {
Some(_) => mask_uid(s, layer, p),
None => s
.state
.selected_keys
.iter()
.filter(|k| k.layer == lid)
.find_map(|k| masks.groups().find(|g| g.get("path").is_some_and(|pr| pr.uid == k.prop)).map(|g| g.uid))
.or_else(|| mask_uid(s, layer, p)),
}
.ok_or_else(|| bad(CMD, "no such mask (select two Mask Path keyframes or pass `mask`)"))?;
let mg = layer.props.find_group(uid).ok_or_else(|| bad(CMD, "no mask"))?;
let path_prop = mg.get("path").ok_or_else(|| bad(CMD, "the mask has no path"))?;
// Key times (layer time): explicit, else selected keys on this Mask Path.
let mut times: Vec<Tick> = match p.get("times").and_then(Value::as_array) {
Some(a) => {
let ts: Vec<Tick> = a.iter().filter_map(Value::as_f64).map(|t| layer.layer_time(comp.frame_rate.snap_nearest(Tick::from_seconds_f64(t)))).collect();
ts.into_iter().filter_map(|t| path_prop.keys.iter().find(|k| (k.time.0 - t.0).abs() <= comp.frame_duration().0 / 2).map(|k| k.time)).collect()
}
None => s.state.selected_keys.iter().filter(|k| k.layer == lid && k.prop == path_prop.uid).map(|k| k.time).collect(),
};
times.sort();
times.dedup();
if times.len() < 2 {
return Err(bad(CMD, "select two or more Mask Path keyframes (or pass `times` of existing keys)"));
}
let rate = o.keyframe_rate.unwrap_or_else(|| comp.frame_rate.as_f64()) * if o.keyframe_fields { 2.0 } else { 1.0 };
let step = Tick::from_seconds_f64(1.0 / rate.max(0.01));
let opts = o.interp();
let shapes: Vec<ShapePath> = times.iter().filter_map(|t| path_prop.keys.iter().find(|k| k.time == *t).and_then(|k| k.value.as_path().cloned())).collect();
if shapes.len() != times.len() {
return Err(bad(CMD, "the selected keys must be Mask Path keys"));
}
// (time, shape) for every new or replaced key.
let mut out: Vec<(Tick, ShapePath)> = vec![];
let mut vertices = 0;
for i in 0..times.len() - 1 {
let (t0, t1) = (times[i], times[i + 1]);
let (a, b) = interp::correspond(&shapes[i], &shapes[i + 1], &opts);
vertices = vertices.max(a.len());
out.push((t0, a.clone()));
let mut t = t0 + step;
while t1.0 - t.0 > step.0 / 4 {
let u = (t.0 - t0.0) as f64 / (t1.0 - t0.0) as f64;
out.push((t, interp::interpolate(&a, &b, u, &opts)));
t += step;
}
out.push((t1, b));
}
let created = out.len() - times.len().min(out.len());
let (first, last) = (times[0], times[times.len() - 1]);
s.state.mask_interp = o;
s.edit("Mask Interpolation", None, |proj, _| {
let l = layer_mut(proj, cid, lid)?;
let pr = l.props.find_group_mut(uid).and_then(|g| g.get_mut("path")).ok_or_else(|| bad(CMD, "no mask path"))?;
// Keys strictly inside the interpolated span are replaced.
pr.keys.retain(|k| k.time <= first || k.time >= last || times.contains(&k.time));
for (t, sp) in &out {
effectcraft_keyframe::set_key(&mut pr.keys, Keyframe::new(*t, KV::Path(sp.clone())));
}
Ok(())
})?;
Ok(json!({"mask": uid, "keys": created, "vertices": vertices, "rate": rate}))
}
+4
View File
@@ -20,6 +20,7 @@ mod link;
mod lottie;
mod markers;
mod mask;
pub mod mask_interp;
pub mod paint;
mod paths;
mod project_items;
@@ -37,6 +38,7 @@ mod time;
mod track;
mod view;
pub mod viewer_cmds;
mod warp_cmds;
#[cfg(test)]
pub(crate) use mask::split_segment as split_segment_for_tests;
@@ -125,6 +127,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(comp_more::specs());
v.extend(frontend::specs());
v.extend(track::specs());
v.extend(mask_interp::specs());
v.extend(warp_cmds::specs());
v.extend(paint::specs());
v.extend(puppet::specs());
v.extend(settings::specs());
-2
View File
@@ -60,8 +60,6 @@ pub fn specs() -> Vec<CommandSpec> {
stub!("keys.rpfCameraImport", "RPF Camera Import", ["Animation", "Keyframe Assistant"], "{}"),
stub!("text.animatorFontAxes", "Variable Font Axes", ["Animation", "Animate Text"], "{}"),
stub!("track.camera", "Track Camera", ["Animation"], "{}"),
stub!("track.warpStabilizer", "Warp Stabilizer VFX", ["Animation"], "{}"),
stub!("track.mask", "Track Mask", ["Animation"], "{}"),
// Workspaces and panels that don't exist yet.
stub!("window.unavailablePanel", "Panel", [], "{panel}"),
]
+33 -25
View File
@@ -69,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_track,
analyze
),
cmd!("track.stop", "Stop Analysis", [], None, "{}", is_tracking, |s, _| Ok(json!({"stopped": s.stop_track()}))),
cmd!("track.stop", "Stop Analysis", [], None, "{}", is_tracking, |s, _| Ok(json!({"stopped": s.stop_track() | s.stop_mask_track() | s.stop_warp()}))),
cmd!("track.apply", "Apply", [], None, "{layer?, tracker?, dimensions?: xy|x|y}", has_track, apply),
cmd!("track.reset", "Reset", [], None, "{layer?, tracker?}", has_track, reset),
cmd!("track.delete", "Delete Tracker", [], None, "{layer?, tracker?}", has_track, delete),
@@ -105,7 +105,7 @@ fn has_track(s: &Session) -> std::result::Result<(), String> {
}
fn is_tracking(s: &Session) -> std::result::Result<(), String> {
if s.is_tracking() { Ok(()) } else { Err("no track analysis is running".into()) }
if s.is_tracking() || s.is_mask_tracking() || s.is_warp_analyzing() { Ok(()) } else { Err("no track analysis is running".into()) }
}
// ---------- addressing ----------
@@ -432,31 +432,10 @@ fn analyze(s: &mut Session, p: &V) -> Result<V> {
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
let (tg, settings) = layer.tracker(uid).ok_or_else(|| bad("track.analyze", "no tracker"))?;
let fd = comp.frame_duration();
let now = comp.frame_rate.snap_nearest(if s.state.active_comp == Some(cid) { s.time() } else { Tick::ZERO });
let start = f_p(p, "start").map(|v| comp.frame_rate.snap_nearest(Tick::from_seconds_f64(v)));
let end = f_p(p, "end").map(|v| comp.frame_rate.snap_nearest(Tick::from_seconds_f64(v)));
let lo = layer.in_point.max(Tick::ZERO);
let hi = layer.out_point.min(comp.duration) - fd;
let mut times = vec![];
match dir {
Direction::Forward | Direction::FrameForward => {
let mut t = start.unwrap_or(now).clamp(lo, hi);
let stop = if dir == Direction::FrameForward { t + fd } else { end.unwrap_or(hi).min(hi) };
while t <= stop && t <= hi {
times.push(t);
t += fd;
}
}
Direction::Backward | Direction::FrameBackward => {
let mut t = end.unwrap_or(now).clamp(lo, hi);
let stop = if dir == Direction::FrameBackward { t - fd } else { start.unwrap_or(lo).max(lo) };
while t >= stop && t >= lo {
times.push(t);
t -= fd;
}
}
}
let times = analysis_times(comp, layer, dir, now, start, end);
if times.len() < 2 {
return Err(bad("track.analyze", "nothing to analyze in that direction (at the layer's end)"));
}
@@ -489,6 +468,34 @@ fn analyze(s: &mut Session, p: &V) -> Result<V> {
}))
}
/// Comp times to analyse from the CTI (`now`) in `dir`, bounded by `start` / `end` and the
/// layer's In/Out points; the first is the start frame.
pub(crate) fn analysis_times(comp: &effectcraft_project::Comp, layer: &Layer, dir: Direction, now: Tick, start: Option<Tick>, end: Option<Tick>) -> Vec<Tick> {
let fd = comp.frame_duration();
let lo = layer.in_point.max(Tick::ZERO);
let hi = layer.out_point.min(comp.duration) - fd;
let mut times = vec![];
match dir {
Direction::Forward | Direction::FrameForward => {
let mut t = start.unwrap_or(now).clamp(lo, hi);
let stop = if dir == Direction::FrameForward { t + fd } else { end.unwrap_or(hi).min(hi) };
while t <= stop && t <= hi {
times.push(t);
t += fd;
}
}
Direction::Backward | Direction::FrameBackward => {
let mut t = end.unwrap_or(now).clamp(lo, hi);
let stop = if dir == Direction::FrameBackward { t - fd } else { start.unwrap_or(lo).max(lo) };
while t >= stop && t >= lo {
times.push(t);
t -= fd;
}
}
}
times
}
fn apply(s: &mut Session, p: &V) -> Result<V> {
let (cid, lid, uid) = current(s, p, "track.apply")?;
let dims = match str_p(p, "dimensions") {
@@ -560,9 +567,10 @@ fn delete(s: &mut Session, p: &V) -> Result<V> {
fn status(s: &mut Session, p: &V) -> Result<V> {
s.poll_track();
s.poll_mask_track();
let progress = s.track_progress();
let cur = current(s, p, "track.status").ok();
let mut out = json!({"running": s.is_tracking(), "progress": progress});
let mut out = json!({"running": s.is_tracking() || s.is_mask_tracking(), "progress": progress, "mask": s.mask_track_progress(), "maskMethod": s.state.mask_track_method.id()});
if let Some((cid, lid, uid)) = cur
&& let Some(layer) = s.project.comp(cid).and_then(|c| c.layer(lid))
&& let Some((g, st)) = layer.tracker(uid)
+131
View File
@@ -0,0 +1,131 @@
//! Warp Stabilizer commands (Effect ▸ Distort ▸ Warp Stabilizer's Analyze / Cancel, Animation ▸
//! Warp Stabilizer VFX, the Tracker panel button) and its status query.
use effectcraft_project::{GroupKind, ItemId, Layer, LayerId, PropGroup, Uid};
use serde_json::{Value, json};
use super::{CommandSpec, b_p, bad, has_comp, layer_p};
use crate::{EngineError, Result, Session, cmd, query};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("track.warpStabilizer", "Warp Stabilizer VFX", ["Animation"], None, "{layer?, wait?}", can_stabilize, warp_apply),
cmd!("warp.analyze", "Analyze", [], None, "{layer?, effect?: uid|name|index, wait?: block until done}", has_comp, warp_analyze),
cmd!("warp.cancel", "Cancel", [], None, "{}", is_analyzing, |s, _| Ok(json!({"stopped": s.stop_warp()}))),
query!("warp.status", "Warp Stabilizer Status", "{layer?, effect?}", warp_status),
]
}
// ---------------------------------------------------------------- Warp Stabilizer
fn can_stabilize(s: &Session) -> std::result::Result<(), String> {
has_comp(s)?;
let c = s.active_comp().ok_or("no composition is open")?;
match s.state.selected_layers.first().and_then(|l| c.layer(*l)) {
Some(l) if l.has_video() && !l.switches.adjustment => Ok(()),
Some(_) => Err("Warp Stabilizer needs a footage or composition layer".into()),
None => Err("select a layer to stabilize".into()),
}
}
fn is_analyzing(s: &Session) -> std::result::Result<(), String> {
if s.is_warp_analyzing() { Ok(()) } else { Err("no Warp Stabilizer analysis is running".into()) }
}
fn is_warp(g: &PropGroup) -> bool {
matches!(&g.kind, GroupKind::Effect { effect } if effect == effectcraft_effects::warp_stab::ID)
}
/// (comp, layer, effect uid) of a Warp Stabilizer: `layer` / `effect` (uid, name or 1-based
/// index among the layer's effects), else a selected one, else the layer's first.
fn warp_p(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
let cid = super::comp_id(s, p)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let candidates: Vec<LayerId> = match p.get("layer") {
Some(v) => vec![super::resolve_layer(comp, v).ok_or_else(|| bad(cmd, format!("no layer {v}")))?],
None => {
let mut v: Vec<LayerId> = s.state.selected_props.iter().map(|(l, _)| *l).collect();
v.extend(s.state.selected_layers.iter().copied());
v.extend(comp.layers.iter().map(|l| l.id));
v
}
};
for lid in candidates {
let Some(fx) = comp.layer(lid).and_then(Layer::effects) else { continue };
let g = match p.get("effect") {
Some(Value::Number(n)) => {
let n = n.as_u64().unwrap_or(0);
fx.groups().find(|g| g.uid == n).or_else(|| fx.groups().nth((n as usize).saturating_sub(1)))
}
Some(Value::String(name)) => fx.groups().find(|g| &g.name == name),
_ => s
.state
.selected_props
.iter()
.find_map(|(l, u)| (*l == lid).then(|| fx.groups().find(|g| g.uid == *u && is_warp(g))).flatten())
.or_else(|| fx.groups().find(|g| is_warp(g))),
};
if let Some(g) = g.filter(|g| is_warp(g)) {
return Ok((cid, lid, g.uid));
}
if p.get("layer").is_some() {
break;
}
}
Err(bad(cmd, "no Warp Stabilizer found (apply Effect ▸ Distort ▸ Warp Stabilizer first)"))
}
fn warp_analyze(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, lid, uid) = warp_p(s, p, "warp.analyze")?;
let wait = b_p(p, "wait").unwrap_or(false);
let n = s.start_warp(cid, lid, uid, wait).map_err(EngineError::Other)?;
let mut out = json!({"layer": lid.0, "effect": uid, "frames": n, "running": s.is_warp_analyzing(), "progress": s.warp_progress()});
if wait {
out["status"] = warp_status(s, &json!({"layer": lid.0, "effect": uid, "comp": cid.0}))?;
}
Ok(out)
}
/// Animation ▸ Warp Stabilizer VFX / the Tracker panel button: apply the effect to the selected
/// layer and start analysing it.
fn warp_apply(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, lid) = layer_p(s, p, "track.warpStabilizer")?;
let r = s.execute("effect.apply", json!({"effect": effectcraft_effects::warp_stab::ID, "layers": [lid.0], "comp": cid.0}))?;
let uid = r["effects"].get(0).and_then(Value::as_u64).ok_or_else(|| EngineError::Other("the effect could not be applied".into()))?;
let wait = b_p(p, "wait").unwrap_or(false);
let n = s.start_warp(cid, lid, uid, wait).map_err(EngineError::Other)?;
Ok(json!({"layer": lid.0, "effect": uid, "frames": n, "running": s.is_warp_analyzing(), "progress": s.warp_progress()}))
}
fn warp_status(s: &mut Session, p: &Value) -> Result<Value> {
s.poll_warp(false);
let mut out = json!({"running": s.is_warp_analyzing(), "progress": s.warp_progress(), "banner": s.warp_progress().map(|p| p.banner())});
let Ok((cid, lid, uid)) = warp_p(s, p, "warp.status") else { return Ok(out) };
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
let g = layer.props.find_group(uid).ok_or(EngineError::NoComp)?;
let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, comp, s.time_of(cid));
let params = effectcraft_effects::flatten_params(g, &mut |pr| ctx.value(layer, pr));
let analysis = effectcraft_effects::warp_stab::analysis(&params);
out["layer"] = json!(lid.0);
out["effect"] = json!(uid);
out["analyzed"] = json!(analysis.is_some());
out["pending"] = json!(s.warp_pending.contains(&(cid, lid, uid)));
if let Some(a) = analysis {
out["frames"] = json!(a.frames.len());
out["size"] = json!(a.size);
let lt = layer.layer_time(s.time_of(cid)).seconds();
if let Some((k, _, plan)) = effectcraft_effects::warp_stab::plan_at(&params, lt) {
let m = plan.warps[k].0;
out["frame"] = json!(k);
out["autoScale"] = json!(plan.auto_scale * 100.0);
out["crop"] = json!(plan.crop);
out["validFraction"] = json!(plan.valid_fraction);
out["warp"] = json!(m);
let pts = &a.frames[k];
out["features"] = json!(pts.features);
out["inliers"] = json!(pts.inliers);
}
}
Ok(out)
}