Merge branch 'main' into worktree-agent-a758de7c5b6efcc3d

# Conflicts:
#	crates/effects/src/lib.rs
#	crates/render/src/lib.rs
#	docs/parity.md
This commit is contained in:
Brandon Thomas
2026-10-02 21:48:49 -04:00
77 changed files with 9531 additions and 75 deletions
+1
View File
@@ -125,6 +125,7 @@ fn settings(s: &mut Session, p: &Value) -> Result<Value> {
}
let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
apply_settings(c, p);
super::model3d::sync_geometry_options(proj, cid);
Ok(())
})?;
let c = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+1 -1
View File
@@ -110,7 +110,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
let label = match f.kind {
FootageKind::Still | FootageKind::Sequence => Label::Lavender,
FootageKind::Audio => Label::SeaFoam,
FootageKind::Video => Label::Aqua,
FootageKind::Video | FootageKind::Model => Label::Aqua,
};
let id = proj.add_item(&name, label, None, ItemKind::Footage(f));
ids.push(id.0);
+8 -1
View File
@@ -24,7 +24,11 @@ pub(crate) fn color_p(p: &Value, k: &str) -> Option<[f32; 3]> {
}
/// Insert a new layer above the selection (or at the top) and select it.
pub(crate) fn insert_layer(proj: &mut Project, st: &mut crate::EditorState, cid: ItemId, layer: Layer) -> Result<LayerId> {
pub(crate) fn insert_layer(proj: &mut Project, st: &mut crate::EditorState, cid: ItemId, mut layer: Layer) -> Result<LayerId> {
// Text and shape layers in Advanced 3D comps get Geometry Options (extrusion, bevels).
if proj.comp(cid).is_some_and(|c| c.renderer == effectcraft_project::Renderer::Advanced3D) {
super::model3d::add_geometry_options(&mut proj.next_id, &mut layer);
}
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
let at = st.selected_layers.first().and_then(|id| comp.layers.iter().position(|l| l.id == *id)).unwrap_or(0);
let id = layer.id;
@@ -235,6 +239,9 @@ fn add_item(s: &mut Session, p: &Value) -> Result<Value> {
let d = (s.prefs.import.still_footage == "seconds").then(|| Tick::from_seconds_f64(s.prefs.import.still_seconds));
(LayerSource::Footage { item }, (f.width, f.height), d)
}
ItemKind::Footage(f) if f.kind == effectcraft_project::FootageKind::Model => {
return super::model3d::new_model(s, &serde_json::json!({"comp": cid.0, "item": item.0, "time": f_p(p, "time")}));
}
ItemKind::Footage(f) => (LayerSource::Footage { item }, (f.width, f.height), Some(f.duration)),
ItemKind::Solid(so) => (LayerSource::Solid { item }, (so.width, so.height), None),
ItemKind::Folder => return Err(bad("layer.addItem", "folders can't be layers")),
+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}))
}
+6
View File
@@ -21,6 +21,8 @@ mod liquify;
mod lottie;
mod markers;
mod mask;
pub mod mask_interp;
pub(crate) mod model3d;
pub mod paint;
mod paths;
mod project_items;
@@ -38,6 +40,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;
@@ -100,6 +103,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(layer::specs());
v.extend(styles::specs());
v.extend(three_d::specs());
v.extend(model3d::specs());
v.extend(text_anim::specs());
v.extend(text_edit::specs());
v.extend(layer_time::specs());
@@ -126,6 +130,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(liquify::specs());
+397
View File
@@ -0,0 +1,397 @@
//! Advanced 3D: model layers (File ▸ Import of glTF/OBJ, Layer ▸ New ▸ 3D primitives), the
//! comp renderer switch, Layer ▸ Environment Layer, Geometry Options for extruded text and
//! shapes, and Layer ▸ Material commands.
use effectcraft_keyframe::Value as KV;
use effectcraft_project::build::{self, Ids};
use effectcraft_project::{FootageKind, ItemId, ItemKind, Layer, LayerSource, Node, PrimitiveKind, PropGroup, Renderer};
use effectcraft_time::Tick;
use serde_json::{Value, json};
use super::layer::{color_p, insert_layer};
use super::{CommandSpec, b_p, bad, comp_id, f_p, has_comp, has_layers, layer_mut, layer_p, layers_p, str_p};
use crate::{EngineError, Result, Session, cmd};
// ---------------------------------------------------------------- geometry options
/// Add Geometry Options (Bevel Style, Bevel Depth, Hole Bevel Depth, Extrusion Depth) to a text
/// or shape layer that has none.
pub(crate) fn add_geometry_options(next_id: &mut u64, l: &mut Layer) {
if !matches!(l.source, LayerSource::Text | LayerSource::Shape) || l.props.sub("geometryOptions").is_some() {
return;
}
let g = build::extrusion_geometry_options(&mut Ids(next_id));
// After Transform, like After Effects.
let at = l.props.children.iter().position(|c| c.match_id() == "transform").map_or(l.props.children.len(), |i| i + 1);
l.props.children.insert(at, g.into());
}
/// Advanced 3D comps: give every text and shape layer Geometry Options.
pub(crate) fn sync_geometry_options(proj: &mut effectcraft_project::Project, cid: ItemId) {
if proj.comp(cid).is_none_or(|c| c.renderer != Renderer::Advanced3D) {
return;
}
let mut next = proj.next_id;
if let Some(c) = proj.comp_mut(cid) {
for l in &mut c.layers {
add_geometry_options(&mut next, l);
}
}
proj.next_id = next;
}
fn renderer_p(p: &Value, cmd: &str) -> Result<Renderer> {
let v = str_p(p, "renderer").or_else(|| str_p(p, "value")).ok_or_else(|| bad(cmd, "missing `renderer` (advanced3d|classic3d)"))?;
match v.to_ascii_lowercase().replace([' ', '_', '-'], "").as_str() {
"advanced3d" | "advanced" => Ok(Renderer::Advanced3D),
"classic3d" | "classic" => Ok(Renderer::Classic3D),
_ => Err(bad(cmd, format!("renderer: advanced3d|classic3d, not `{v}`"))),
}
}
fn comp_renderer(s: &mut Session, p: &Value) -> Result<Value> {
let cid = comp_id(s, p)?;
if p.get("renderer").is_none() && p.get("value").is_none() {
let r = s.project.comp(cid).ok_or(EngineError::NoComp)?.renderer;
return Ok(json!({"renderer": renderer_id(r)}));
}
let r = renderer_p(p, "comp.renderer")?;
s.edit("Change Renderer", None, |proj, _| {
proj.comp_mut(cid).ok_or(EngineError::NoComp)?.renderer = r;
sync_geometry_options(proj, cid);
Ok(())
})?;
Ok(json!({"renderer": renderer_id(r)}))
}
fn renderer_id(r: Renderer) -> &'static str {
match r {
Renderer::Advanced3D => "advanced3d",
Renderer::Classic3D => "classic3d",
}
}
// ---------------------------------------------------------------- model layers
/// Set a property's value at comp time `t` (adds a key when it is animated).
fn set_at(l: &mut Layer, path: &str, t: Tick, v: KV) -> bool {
let lt = l.layer_time(t);
match l.props.prop_mut(path) {
Some(pr) => {
pr.set_value_at(lt, v);
true
}
None => false,
}
}
/// New 3D model layer from a model footage item (`item`) or a file (`path`, imported first).
pub(crate) fn new_model(s: &mut Session, p: &Value) -> Result<Value> {
let cid = comp_id(s, p)?;
let item = match (p.get("item"), str_p(p, "path")) {
(Some(Value::Number(n)), _) => ItemId(n.as_u64().unwrap_or(0)),
(Some(Value::String(name)), _) => s.project.find_by_name(name).map(|i| i.id).ok_or_else(|| bad("layer.newModel", format!("no item `{name}`")))?,
(_, Some(path)) => {
let r = s.execute("file.import", json!({"paths": [path]}))?;
let id = r.get("items").and_then(|a| a.get(0)).and_then(Value::as_u64);
let err = r.get("errors").and_then(|e| e.get(0)).and_then(Value::as_str).unwrap_or("import failed").to_string();
ItemId(id.ok_or_else(|| bad("layer.newModel", err))?)
}
_ => *s.state.project_selection.first().ok_or_else(|| bad("layer.newModel", "missing `item` or `path`"))?,
};
let it = s.project.item(item).ok_or_else(|| bad("layer.newModel", "no such item"))?.clone();
let ItemKind::Footage(f) = &it.kind else { return Err(bad("layer.newModel", format!("`{}` is not a 3D model", it.name))) };
if f.kind != FootageKind::Model {
return Err(bad("layer.newModel", format!("`{}` is not a 3D model", it.name)));
}
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
// Fit the model to half the comp height, and list its animation clips.
let model = s.footage.model(item, f);
let (scale, clips) = match &model {
Some(m) => {
let ext = m.bounds().map_or(1.0, |(lo, hi)| (0..3).map(|k| hi[k] - lo[k]).fold(0.0f64, f64::max));
let scale = if ext > 1e-9 { comp.height as f64 * 0.5 / ext } else { 100.0 };
let clips = m.animations.iter().enumerate().map(|(i, a)| if a.name.is_empty() { format!("Animation {}", i + 1) } else { a.name.clone() }).collect();
(scale, clips)
}
None => (100.0, vec![]),
};
let name = str_p(p, "name").unwrap_or(&it.name).to_string();
let fr = comp.frame_rate;
let start = fr.snap_nearest(f_p(p, "time").map(Tick::from_seconds_f64).unwrap_or(Tick::ZERO));
let id = s.edit("New 3D Model Layer", None, |proj, st| {
let mut l = build::layer(proj, &comp, &name, LayerSource::Model { item }, (comp.width, comp.height), None);
let g = build::model_geometry_options(&mut Ids(&mut proj.next_id), scale, &clips);
if let Some(slot) = l.props.children.iter_mut().find(|c| c.match_id() == "geometryOptions") {
*slot = g.into();
}
l.start_time = start;
l.in_point = start;
l.out_point = comp.duration.max(start + fr.frame_duration());
insert_layer(proj, st, cid, l)
})?;
Ok(json!({"layer": id.0, "item": item.0}))
}
fn kind_p(p: &Value, cmd: &str) -> Result<PrimitiveKind> {
let k = str_p(p, "kind").or_else(|| str_p(p, "type")).ok_or_else(|| bad(cmd, "missing `kind` (cube|sphere|plane|torus|cone|cylinder)"))?;
PrimitiveKind::parse(k).ok_or_else(|| bad(cmd, format!("kind: cube|sphere|plane|torus|cone|cylinder, not `{k}`")))
}
/// Parse Material Options parameters onto a layer at comp time `t`.
fn apply_material(l: &mut Layer, p: &Value, t: Tick, cmd: &str) -> Result<usize> {
let mut n = 0;
let tri = |v: &Value| -> Option<u32> {
match v {
Value::Bool(b) => Some(*b as u32),
Value::Number(x) => x.as_u64().map(|x| x.min(2) as u32),
Value::String(s) => match s.to_ascii_lowercase().as_str() {
"off" | "false" => Some(0),
"on" | "true" => Some(1),
"only" => Some(2),
_ => None,
},
_ => None,
}
};
for k in ["castsShadows", "acceptsShadows"] {
if let Some(v) = p.get(k) {
let e = tri(v).ok_or_else(|| bad(cmd, format!("{k}: off|on|only")))?;
n += set_at(l, &format!("materialOptions/{k}"), t, KV::Enum(e)) as usize;
}
}
for k in ["acceptsLights", "appearsInReflections"] {
if let Some(v) = b_p(p, k) {
n += set_at(l, &format!("materialOptions/{k}"), t, KV::Bool(v)) as usize;
}
}
for k in ["lightTransmission", "ambient", "diffuse", "specularIntensity", "specularShininess", "metal", "metallic", "roughness"] {
if let Some(v) = f_p(p, k) {
n += set_at(l, &format!("materialOptions/{k}"), t, KV::Scalar(v)) as usize;
}
}
for k in ["baseColor", "emissive"] {
if let Some(c) = color_p(p, k) {
n += set_at(l, &format!("materialOptions/{k}"), t, KV::Color([c[0] as f64, c[1] as f64, c[2] as f64, 1.0])) as usize;
}
}
Ok(n)
}
fn new_primitive(s: &mut Session, p: &Value) -> Result<Value> {
let cid = comp_id(s, p)?;
let kind = kind_p(p, "layer.newPrimitive")?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
let name = str_p(p, "name").map(str::to_string).unwrap_or_else(|| kind.label().to_string());
let t = super::time_p(s, p, Some(&comp));
let id = s.edit(&format!("New {}", kind.label()), None, |proj, st| {
let mut l = build::layer(proj, &comp, &name, LayerSource::Primitive { kind }, (comp.width, comp.height), None);
for k in ["width", "height", "depth", "radius", "tubeRadius", "segments", "rings"] {
if let Some(v) = f_p(p, k) {
set_at(&mut l, &format!("geometryOptions/{k}"), t, KV::Scalar(v.max(0.0)));
}
}
if let Some(pos) = p.get("position").and_then(Value::as_array) {
let g = |i: usize| pos.get(i).and_then(Value::as_f64).unwrap_or(0.0);
set_at(&mut l, "transform/position", t, KV::Vec3([g(0), g(1), g(2)]));
}
apply_material(&mut l, p, t, "layer.newPrimitive")?;
insert_layer(proj, st, cid, l)
})?;
// Primitives are drawn by the Advanced 3D renderer.
let advanced = s.project.comp(cid).is_some_and(|c| c.renderer == Renderer::Advanced3D);
Ok(json!({"layer": id.0, "kind": kind.label(), "advanced3d": advanced}))
}
// ---------------------------------------------------------------- environment layer
fn environment(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, ids) = layers_p(s, p)?;
if ids.is_empty() {
return Err(bad("layer.environment", "select a footage or composition layer"));
}
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
for id in &ids {
let l = comp.layer(*id).ok_or(EngineError::NoComp)?;
if !l.source.is_av() || l.source.is_model() {
return Err(bad("layer.environment", format!("`{}` can't be an environment layer (use a footage, comp or solid layer)", l.name)));
}
}
let on = b_p(p, "on").unwrap_or_else(|| !comp.layer(ids[0]).is_some_and(|l| l.environment));
s.edit("Environment Layer", None, |proj, _| {
for id in &ids {
let l = layer_mut(proj, cid, *id)?;
l.environment = on;
if on {
l.switches.three_d = true;
}
}
Ok(())
})?;
Ok(json!({"environment": on, "layers": ids.iter().map(|l| l.0).collect::<Vec<_>>()}))
}
// ---------------------------------------------------------------- materials
fn material_set(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, ids) = layers_p(s, p)?;
if ids.is_empty() {
return Err(bad("material.set", "no `layers` given and no layer selected"));
}
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
let t = super::time_p(s, p, Some(&comp));
let n = s.edit("Material Options", None, |proj, _| {
let mut n = 0;
for id in &ids {
n += apply_material(layer_mut(proj, cid, *id)?, p, t, "material.set")?;
}
Ok(n)
})?;
if n == 0 {
return Err(bad(
"material.set",
"no Material Options property matched (castsShadows, acceptsShadows, acceptsLights, baseColor, metallic, roughness, …)",
));
}
Ok(json!({"set": n}))
}
/// Fresh Material Options for a layer.
fn default_material(next: &mut u64, l: &Layer) -> Option<PropGroup> {
let ids = &mut Ids(next);
match l.source {
LayerSource::Primitive { .. } => Some(build::model_material_options(ids, true)),
LayerSource::Model { .. } => Some(build::model_material_options(ids, false)),
_ if l.source.is_av() => Some(build::material_options(ids)),
_ => None,
}
}
fn replace_material(l: &mut Layer, g: PropGroup) {
match l.props.children.iter_mut().find(|c| c.match_id() == "materialOptions") {
Some(slot) => *slot = Node::Group(g),
None => l.props.children.push(g.into()),
}
}
fn material_reset(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, ids) = layers_p(s, p)?;
if ids.is_empty() {
return Err(bad("material.reset", "no `layers` given and no layer selected"));
}
s.edit("Reset Material", None, |proj, _| {
let mut next = proj.next_id;
for id in &ids {
let l = layer_mut(proj, cid, *id)?;
if let Some(g) = default_material(&mut next, l) {
replace_material(l, g);
}
}
proj.next_id = next;
Ok(())
})?;
Ok(json!({"layers": ids.iter().map(|l| l.0).collect::<Vec<_>>()}))
}
/// Duplicate and Assign Material: the first layer's Material Options are copied onto the other
/// selected layers of the same kind.
fn material_duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, ids) = layers_p(s, p)?;
if ids.len() < 2 {
return Err(bad("material.duplicateAssign", "select the source layer first, then the layers to assign its material to"));
}
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let src = comp
.layer(ids[0])
.and_then(|l| l.props.sub("materialOptions"))
.cloned()
.ok_or_else(|| bad("material.duplicateAssign", "the first layer has no material"))?;
let n = s.edit("Duplicate and Assign Material", None, |proj, _| {
let mut n = 0;
for id in &ids[1..] {
let l = layer_mut(proj, cid, *id)?;
let Some(dst) = l.props.sub("materialOptions") else { continue };
// Property sets differ (models, primitives, cards): copy the values they share.
let mut g = dst.clone();
for c in g.children.iter_mut() {
if let Node::Prop(d) = c
&& let Some(sv) = src.get(&d.match_id)
{
d.value = sv.value.clone();
d.keys = sv.keys.clone();
d.expr = sv.expr.clone();
}
}
replace_material(l, g);
n += 1;
}
Ok(n)
})?;
Ok(json!({"assigned": n}))
}
fn material_reveal(s: &mut Session, p: &Value) -> Result<Value> {
let (cid, lid) = layer_p(s, p, "material.revealSource")?;
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
let LayerSource::Model { item } = l.source else { return Err(bad("material.revealSource", "the layer's material is its own (not from a model file)")) };
s.state.project_selection = vec![item];
Ok(json!({"item": item.0}))
}
fn has_model_or_layers(s: &Session) -> std::result::Result<(), String> {
has_layers(s)
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"layer.newModel",
"3D Model Layer",
[],
None,
"{item?: id or name of a 3D model footage item, path?: a .gltf, .glb or .obj file to import, name?, time? (s)}",
has_comp,
new_model
),
cmd!(
"layer.new3dPrimitive",
"3D Primitive",
[],
None,
"{kind: cube|sphere|plane|torus|cone|cylinder, name?, width?, height?, depth?, radius?, tubeRadius?, segments?, rings?, position? [x,y,z], baseColor?, metallic?, roughness?, emissive?, castsShadows?, acceptsShadows?, acceptsLights?}",
has_comp,
new_primitive
),
cmd!(
"layer.newPrimitive",
"New 3D Primitive",
[],
None,
"{kind: cube|sphere|plane|torus|cone|cylinder, name?, width?, height?, depth?, radius?, tubeRadius?, segments?, rings?, position? [x,y,z], baseColor?, metallic?, roughness?, emissive?, castsShadows?, acceptsShadows?, acceptsLights?}",
has_comp,
new_primitive
),
cmd!("comp.renderer", "Renderer", [], None, "{renderer?: advanced3d|classic3d (omit to read), value?}", has_comp, comp_renderer),
cmd!("layer.environment", "Environment Layer", ["Layer"], None, "{layers?, on?}", has_layers, environment),
cmd!(
"material.set",
"Material Options",
[],
None,
"{layers?, castsShadows?: off|on|only, acceptsShadows?: off|on|only, acceptsLights?, appearsInReflections?, lightTransmission?, ambient?, diffuse?, specularIntensity?, specularShininess?, metal?, baseColor?, metallic?, roughness?, emissive?, time?}",
has_layers,
material_set
),
cmd!("material.revealSource", "Reveal Material Source in Project", ["Layer", "Material"], None, "{layer?}", has_layers, material_reveal),
cmd!("material.reset", "Reset Material", ["Layer", "Material"], None, "{layers?}", has_model_or_layers, material_reset),
cmd!(
"material.duplicateAssign",
"Duplicate and Assign Material",
["Layer", "Material"],
None,
"{layers? (first = source)}",
has_layers,
material_duplicate
),
]
}
-7
View File
@@ -29,11 +29,9 @@ pub fn specs() -> Vec<CommandSpec> {
stub!("keys.selectLabelGroup", "Select Keyframe Label Group", [], "{scope}"),
// Layer ▸ New (3D / content-aware fill).
stub!("layer.newContentAwareFill", "Content-Aware Fill Layer...", ["Layer", "New"], "{}"),
stub!("layer.new3dPrimitive", "3D Primitive", [], "{kind: cube|sphere|plane|torus|cone|cylinder}"),
// Mask options not in the mask model yet; pen / vertex editing (timeline milestone).
// Time (timeline milestone).
stub!("layer.alignVideoToData", "Align Video to Data", ["Layer", "Time"], "{}"),
stub!("layer.environment", "Environment Layer", ["Layer"], "{}"),
stub!("layer.create", "Create", [], "{op}"),
stub!("layer.autoTrace", "Auto-trace...", ["Layer"], "{}"),
stub!("layer.sceneEditDetection", "Scene Edit Detection...", ["Layer"], "{}"),
@@ -47,9 +45,6 @@ pub fn specs() -> Vec<CommandSpec> {
stub!("light.fromModel", "Create Lights from 3D Model", ["Layer", "Light"], "{}"),
stub!("light.controlWithCamera", "Control Light with Camera", ["Layer", "Light"], "{}"),
stub!("light.environmentBackground", "Create Environment Light Background Layer", ["Layer", "Light"], "{}"),
stub!("material.revealSource", "Reveal Material Source in Project", ["Layer", "Material"], "{}"),
stub!("material.reset", "Reset Material", ["Layer", "Material"], "{}"),
stub!("material.duplicateAssign", "Duplicate and Assign Material", ["Layer", "Material"], "{}"),
stub!("view.3d.default", "Default", ["View", "Switch 3D View"], "{}"),
stub!("view.splitLockedViewer", "Split with New Locked Viewer", ["View"], "{}"),
// Color management.
@@ -60,8 +55,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)
}