M6.7: roto brush segmentation + propagation
Graph-cut segmentation (Boykov-Kolmogorov max-flow, GrabCut GMMs, coarse to fine), optical-flow propagation with band re-segmentation, correction strokes, Roto Brush & Refine Edge effect with content-keyed derived cache, roto.* commands (stroke/propagate/span/freeze/unfreeze/clearStrokes/ cancel/options/status), refine-edge matting (guided filter + closed-form) and decontamination, Freeze job. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e911cc5c93
commit
07330bca6b
@@ -525,6 +525,9 @@ fn purge_caches(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.snapshot = None;
|
||||
s.state.viewer.show_snapshot = false;
|
||||
}
|
||||
if matches!(what.as_str(), "all" | "image" | "memory" | "memoryAndDisk") {
|
||||
effectcraft_effects::roto::purge();
|
||||
}
|
||||
s.events.push(crate::Event::PurgeCaches);
|
||||
s.toast(format!("Purged {what} cache"));
|
||||
Ok(json!({"purged": what}))
|
||||
|
||||
@@ -28,6 +28,7 @@ mod prop;
|
||||
pub mod puppet;
|
||||
mod query;
|
||||
mod render_queue;
|
||||
pub mod roto_cmds;
|
||||
mod settings;
|
||||
mod stubs;
|
||||
mod styles;
|
||||
@@ -129,6 +130,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(track::specs());
|
||||
v.extend(mask_interp::specs());
|
||||
v.extend(warp_cmds::specs());
|
||||
v.extend(roto_cmds::specs());
|
||||
v.extend(paint::specs());
|
||||
v.extend(puppet::specs());
|
||||
v.extend(settings::specs());
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
//! Roto Brush & Refine Edge commands: strokes (the Roto Brush and Refine Edge tools in the Layer
|
||||
//! panel), propagation, the segmentation span, Freeze / Unfreeze, tool options and status.
|
||||
//!
|
||||
//! `roto.stroke` records a stroke into the layer's Roto Brush & Refine Edge effect (applying the
|
||||
//! effect on the first stroke, as After Effects does); the first foreground stroke sets the base
|
||||
//! frame and a span of 20 frames each side. Strokes on a frozen effect are refused (Unfreeze
|
||||
//! first). Every edit is one undo step.
|
||||
|
||||
use effectcraft_effects::roto::{self as fx, FROZEN, Stroke, StrokeKind};
|
||||
use effectcraft_keyframe::Value as KV;
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{ItemId, Layer, LayerId, PropGroup, Uid};
|
||||
use effectcraft_track::roto::{RotoData, iou, rle};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, always, b_p, bad, f_p, has_comp, layer_mut, layer_p, str_p};
|
||||
use crate::roto::{self as rt, Direction, RotoOptions, RotoTask, VIEWS, is_roto, params_static};
|
||||
use crate::{EngineError, Result, Session, cmd, query};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"roto.stroke",
|
||||
"Roto Brush Stroke",
|
||||
[],
|
||||
None,
|
||||
"{layer?, kind?: fg|bg|refine|refineErase, points: [[x, y], …] (layer pixels), frame? (layer frame; default current), radius? (layer px; default the tool's diameter / 2), effect?}",
|
||||
has_comp,
|
||||
stroke
|
||||
),
|
||||
cmd!(
|
||||
"roto.propagate",
|
||||
"Propagate Roto Brush",
|
||||
[],
|
||||
None,
|
||||
"{layer?, effect?, direction?: forward|backward|both, to? (layer frame: extend the span), wait?: block until done}",
|
||||
has_comp,
|
||||
propagate
|
||||
),
|
||||
cmd!("roto.span", "Set Segmentation Span", [], None, "{layer?, effect?, start?, end? (layer frames)}", has_comp, span),
|
||||
cmd!("roto.freeze", "Freeze", [], None, "{layer?, effect?, wait?}", has_comp, freeze),
|
||||
cmd!("roto.unfreeze", "Unfreeze", [], None, "{layer?, effect?}", has_comp, unfreeze),
|
||||
cmd!("roto.clearStrokes", "Remove Roto Brush Strokes", [], None, "{layer?, effect?, frame? (only this layer frame), kind?}", has_comp, clear_strokes),
|
||||
cmd!("roto.cancel", "Stop Roto Brush", [], None, "{}", is_running, |s, _| Ok(json!({"stopped": s.stop_roto()}))),
|
||||
cmd!(
|
||||
"roto.options",
|
||||
"Roto Brush Options",
|
||||
[],
|
||||
None,
|
||||
"{diameter?, refineDiameter?, view?: alphaBoundary|alpha|alphaOverlay|none, overlayColor?: [r,g,b], overlayOpacity?, boundaryColor?: [r,g,b], autoPropagate?}",
|
||||
always,
|
||||
options
|
||||
),
|
||||
query!(
|
||||
"roto.status",
|
||||
"Roto Brush Status",
|
||||
"{layer?, effect?, frame? (layer frame: also report its matte), matte?: include the matte (RLE, base64), compute?: compute the frame if needed, compareTo?: RLE matte to report the IoU against}",
|
||||
status
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn is_running(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.is_roto_running() { Ok(()) } else { Err("no Roto Brush job is running".into()) }
|
||||
}
|
||||
|
||||
/// The Roto Brush instance targeted by `p`: `layer` / `effect` (uid, name or 1-based index),
|
||||
/// else a selected one, else the first on the selected (or any) layer.
|
||||
pub(crate) fn roto_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(fxg) = 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);
|
||||
fxg.groups().find(|g| g.uid == n).or_else(|| fxg.groups().nth((n as usize).saturating_sub(1)))
|
||||
}
|
||||
Some(Value::String(name)) => fxg.groups().find(|g| &g.name == name),
|
||||
_ => s
|
||||
.state
|
||||
.selected_props
|
||||
.iter()
|
||||
.find_map(|(l, u)| (*l == lid).then(|| fxg.groups().find(|g| g.uid == *u && is_roto(g))).flatten())
|
||||
.or_else(|| fxg.groups().find(|g| is_roto(g))),
|
||||
};
|
||||
if let Some(g) = g.filter(|g| is_roto(g)) {
|
||||
return Ok((cid, lid, g.uid));
|
||||
}
|
||||
if p.get("layer").is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(bad(cmd, "no Roto Brush & Refine Edge effect found (paint a stroke with the Roto Brush tool first)"))
|
||||
}
|
||||
|
||||
fn group(s: &Session, cid: ItemId, lid: LayerId, uid: Uid) -> Result<(&Layer, &PropGroup)> {
|
||||
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
|
||||
let g = l.props.find_group(uid).ok_or_else(|| EngineError::Other("the effect is gone".into()))?;
|
||||
Ok((l, g))
|
||||
}
|
||||
|
||||
fn data_of(g: &PropGroup) -> RotoData {
|
||||
fx::data(¶ms_static(g)).as_ref().clone()
|
||||
}
|
||||
|
||||
fn frozen_of(g: &PropGroup) -> bool {
|
||||
matches!(g.get(FROZEN).map(|p| &p.value), Some(KV::Str(s)) if !s.is_empty())
|
||||
}
|
||||
|
||||
/// Write an instance's data (one undo step).
|
||||
fn write_data(s: &mut Session, label: &str, cid: ItemId, lid: LayerId, uid: Uid, d: &RotoData) -> Result<()> {
|
||||
let j = d.to_json();
|
||||
s.edit(label, None, |proj, _| {
|
||||
let g = layer_mut(proj, cid, lid)?.props.find_group_mut(uid).ok_or_else(|| EngineError::Other("the effect is gone".into()))?;
|
||||
if let Some(pr) = g.get_mut(fx::STROKES) {
|
||||
pr.value = KV::Str(j);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Current layer frame of `layer` (or `frame` from the params).
|
||||
fn frame_p(s: &Session, p: &Value, cid: ItemId, layer: &Layer) -> i64 {
|
||||
if let Some(f) = f_p(p, "frame") {
|
||||
return f.round() as i64;
|
||||
}
|
||||
let comp = s.project.comp(cid);
|
||||
let fps = comp.map(|c| c.frame_rate.as_f64()).unwrap_or(30.0);
|
||||
fx::frame_of(layer.layer_time(s.time_of(cid)).seconds(), fps)
|
||||
}
|
||||
|
||||
fn points_p(p: &Value, cmd: &str) -> Result<Vec<[f64; 2]>> {
|
||||
let raw = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing `points` [[x, y], …] (layer pixels)"))?;
|
||||
let mut v = vec![];
|
||||
for q in raw {
|
||||
let a = q.as_array().ok_or_else(|| bad(cmd, "each point is [x, y]"))?;
|
||||
let (Some(x), Some(y)) = (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64)) else {
|
||||
return Err(bad(cmd, "each point is [x, y]"));
|
||||
};
|
||||
v.push([x, y]);
|
||||
}
|
||||
if v.is_empty() {
|
||||
return Err(bad(cmd, "`points` is empty"));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "roto.stroke";
|
||||
let (cid, lid) = match roto_p(s, p, cmd) {
|
||||
Ok((c, l, _)) => (c, l),
|
||||
Err(_) => layer_p(s, p, cmd)?,
|
||||
};
|
||||
let kind = match str_p(p, "kind") {
|
||||
Some(k) => StrokeKind::from_name(k).ok_or_else(|| bad(cmd, format!("unknown kind `{k}` (fg | bg | refine | refineErase)")))?,
|
||||
None => StrokeKind::Fg,
|
||||
};
|
||||
let points = points_p(p, cmd)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let layer = comp.layer(lid).ok_or_else(|| bad(cmd, "no layer"))?;
|
||||
if !layer.has_video() || layer.switches.adjustment || layer.effects().is_none() {
|
||||
return Err(bad(cmd, "the Roto Brush works on footage, solid and composition layers"));
|
||||
}
|
||||
let frame = frame_p(s, p, cid, layer);
|
||||
let limits = rt::frame_limits(comp, layer);
|
||||
if frame < limits[0] || frame > limits[1] {
|
||||
return Err(bad(cmd, format!("frame {frame} is outside the layer ({}–{})", limits[0], limits[1])));
|
||||
}
|
||||
let o = &s.state.roto;
|
||||
let def_r = if matches!(kind, StrokeKind::Refine | StrokeKind::RefineErase) { o.refine_diameter / 2.0 } else { o.diameter / 2.0 };
|
||||
let radius = f_p(p, "radius").unwrap_or(def_r).clamp(0.5, 2500.0);
|
||||
let size = rt::layer_size(&s.project, comp, layer);
|
||||
// The instance: the requested / first one, else a new one.
|
||||
let existing = roto_p(s, p, cmd).ok().filter(|(c, l, _)| *c == cid && *l == lid).map(|x| x.2);
|
||||
if let Some(uid) = existing {
|
||||
let (_, g) = group(s, cid, lid, uid)?;
|
||||
if frozen_of(g) {
|
||||
return Err(bad(cmd, "the Roto Brush is frozen: Unfreeze it to edit strokes"));
|
||||
}
|
||||
}
|
||||
if existing.is_none() && !kind.is_segmentation() {
|
||||
return Err(bad(cmd, "draw a foreground stroke with the Roto Brush tool first"));
|
||||
}
|
||||
let st = Stroke { kind, frame, radius, points };
|
||||
let label = if kind.is_segmentation() { "Roto Brush Stroke" } else { "Refine Edge Stroke" };
|
||||
let (uid, d) = s.edit(label, None, |proj, _| {
|
||||
let mut next = proj.next_id;
|
||||
let l = layer_mut(proj, cid, lid)?;
|
||||
let fxg = l.props.sub_mut("effects").ok_or_else(|| bad(cmd, "this layer has no effects"))?;
|
||||
let uid = match existing {
|
||||
Some(u) => u,
|
||||
None => {
|
||||
let spec = effectcraft_effects::find(fx::ID).ok_or_else(|| EngineError::Other("Roto Brush effect missing".into()))?;
|
||||
let n = fxg.groups().filter(|g| is_roto(g)).count();
|
||||
let name = if n == 0 { spec.name.to_string() } else { format!("{} {}", spec.name, n + 1) };
|
||||
let g = effectcraft_effects::instantiate(spec, &mut Ids(&mut next), &name, size);
|
||||
let u = g.uid;
|
||||
fxg.children.push(g.into());
|
||||
u
|
||||
}
|
||||
};
|
||||
let g = fxg.find_group_mut(uid).ok_or_else(|| bad(cmd, "effect gone"))?;
|
||||
let mut d = data_of(g);
|
||||
d.add(st, fx::DEFAULT_SPAN, limits);
|
||||
if let Some(pr) = g.get_mut(fx::STROKES) {
|
||||
pr.value = KV::Str(d.to_json());
|
||||
}
|
||||
proj.next_id = proj.next_id.max(next);
|
||||
Ok((uid, d))
|
||||
})?;
|
||||
if !s.state.selected_props.iter().any(|(l, u)| *l == lid && *u == uid) {
|
||||
s.state.selected_layers = vec![lid];
|
||||
}
|
||||
Ok(json!({
|
||||
"layer": lid.0, "effect": uid, "frame": frame, "kind": kind, "radius": radius,
|
||||
"base": d.base, "span": d.span, "strokes": d.strokes.len(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn propagate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "roto.propagate";
|
||||
let (cid, lid, uid) = roto_p(s, p, cmd)?;
|
||||
let dir = match str_p(p, "direction") {
|
||||
Some(d) => Direction::from_name(d).ok_or_else(|| bad(cmd, format!("unknown direction `{d}` (forward | backward | both)")))?,
|
||||
None => Direction::Both,
|
||||
};
|
||||
if let Some(to) = f_p(p, "to") {
|
||||
let to = to.round() as i64;
|
||||
let (l, g) = group(s, cid, lid, uid)?;
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let lim = rt::frame_limits(comp, l);
|
||||
let mut d = data_of(g);
|
||||
let to = to.clamp(lim[0], lim[1]);
|
||||
let before = d.span;
|
||||
d.span[0] = d.span[0].min(to);
|
||||
d.span[1] = d.span[1].max(to);
|
||||
if d.span != before {
|
||||
if frozen_of(g) {
|
||||
return Err(bad(cmd, "the Roto Brush is frozen: Unfreeze it to change the span"));
|
||||
}
|
||||
write_data(s, "Extend Segmentation Span", cid, lid, uid, &d)?;
|
||||
}
|
||||
}
|
||||
let wait = b_p(p, "wait").unwrap_or(false);
|
||||
let n = s.start_roto(cid, lid, uid, RotoTask::Propagate, dir, wait).map_err(|e| bad(cmd, e))?;
|
||||
let mut out = json!({"layer": lid.0, "effect": uid, "frames": n, "running": s.is_roto_running(), "progress": s.roto_progress()});
|
||||
if wait {
|
||||
out["status"] = status(s, &json!({"layer": lid.0, "effect": uid, "comp": cid.0}))?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn span(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "roto.span";
|
||||
let (cid, lid, uid) = roto_p(s, p, cmd)?;
|
||||
let (l, g) = group(s, cid, lid, uid)?;
|
||||
if frozen_of(g) {
|
||||
return Err(bad(cmd, "the Roto Brush is frozen: Unfreeze it to change the span"));
|
||||
}
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let lim = rt::frame_limits(comp, l);
|
||||
let mut d = data_of(g);
|
||||
let base = d.base.ok_or_else(|| bad(cmd, "no strokes yet"))?;
|
||||
let first = d.strokes.iter().map(|s| s.frame).min().unwrap_or(base);
|
||||
let last = d.strokes.iter().map(|s| s.frame).max().unwrap_or(base);
|
||||
if let Some(a) = f_p(p, "start") {
|
||||
d.span[0] = (a.round() as i64).clamp(lim[0], first);
|
||||
}
|
||||
if let Some(b) = f_p(p, "end") {
|
||||
d.span[1] = (b.round() as i64).clamp(last, lim[1]);
|
||||
}
|
||||
write_data(s, "Segmentation Span", cid, lid, uid, &d)?;
|
||||
Ok(json!({"layer": lid.0, "effect": uid, "span": d.span, "base": base}))
|
||||
}
|
||||
|
||||
fn freeze(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "roto.freeze";
|
||||
let (cid, lid, uid) = roto_p(s, p, cmd)?;
|
||||
let wait = b_p(p, "wait").unwrap_or(false);
|
||||
let n = s.start_roto(cid, lid, uid, RotoTask::Freeze, Direction::Both, wait).map_err(|e| bad(cmd, e))?;
|
||||
let (_, g) = group(s, cid, lid, uid)?;
|
||||
Ok(json!({"layer": lid.0, "effect": uid, "frames": n, "running": s.is_roto_running(), "frozen": frozen_of(g), "progress": s.roto_progress()}))
|
||||
}
|
||||
|
||||
fn unfreeze(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "roto.unfreeze";
|
||||
let (cid, lid, uid) = roto_p(s, p, cmd)?;
|
||||
let (_, g) = group(s, cid, lid, uid)?;
|
||||
if !frozen_of(g) {
|
||||
return Ok(json!({"layer": lid.0, "effect": uid, "frozen": false}));
|
||||
}
|
||||
s.edit("Unfreeze", None, |proj, _| {
|
||||
let g = layer_mut(proj, cid, lid)?.props.find_group_mut(uid).ok_or_else(|| EngineError::Other("the effect is gone".into()))?;
|
||||
if let Some(pr) = g.get_mut(FROZEN) {
|
||||
pr.value = KV::Str(String::new());
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"layer": lid.0, "effect": uid, "frozen": false}))
|
||||
}
|
||||
|
||||
fn clear_strokes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "roto.clearStrokes";
|
||||
let (cid, lid, uid) = roto_p(s, p, cmd)?;
|
||||
let (_, g) = group(s, cid, lid, uid)?;
|
||||
if frozen_of(g) {
|
||||
return Err(bad(cmd, "the Roto Brush is frozen: Unfreeze it to edit strokes"));
|
||||
}
|
||||
let mut d = data_of(g);
|
||||
let frame = f_p(p, "frame").map(|f| f.round() as i64);
|
||||
let kind = match str_p(p, "kind") {
|
||||
Some(k) => Some(StrokeKind::from_name(k).ok_or_else(|| bad(cmd, format!("unknown kind `{k}`")))?),
|
||||
None => None,
|
||||
};
|
||||
let n0 = d.strokes.len();
|
||||
d.strokes.retain(|st| !(frame.is_none_or(|f| st.frame == f) && kind.is_none_or(|k| st.kind == k)));
|
||||
if d.strokes.iter().all(|s| !s.kind.is_segmentation()) {
|
||||
d.base = None;
|
||||
} else if d.base.is_some_and(|b| !d.strokes.iter().any(|s| s.frame == b && s.kind.is_segmentation())) {
|
||||
// The base moves to the earliest remaining stroked frame.
|
||||
d.base = d.strokes.iter().filter(|s| s.kind.is_segmentation()).map(|s| s.frame).min();
|
||||
}
|
||||
let removed = n0 - d.strokes.len();
|
||||
if removed > 0 {
|
||||
write_data(s, "Remove Roto Brush Strokes", cid, lid, uid, &d)?;
|
||||
}
|
||||
Ok(json!({"layer": lid.0, "effect": uid, "removed": removed, "strokes": d.strokes.len(), "base": d.base}))
|
||||
}
|
||||
|
||||
fn options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "roto.options";
|
||||
let mut o: RotoOptions = s.state.roto.clone();
|
||||
for (k, f) in [("diameter", &mut o.diameter as &mut f64), ("refineDiameter", &mut o.refine_diameter), ("overlayOpacity", &mut o.overlay_opacity)] {
|
||||
if let Some(v) = f_p(p, k) {
|
||||
*f = v;
|
||||
}
|
||||
}
|
||||
o.diameter = o.diameter.clamp(1.0, 5000.0);
|
||||
o.refine_diameter = o.refine_diameter.clamp(1.0, 5000.0);
|
||||
o.overlay_opacity = o.overlay_opacity.clamp(0.0, 100.0);
|
||||
if let Some(v) = str_p(p, "view") {
|
||||
let v = VIEWS.iter().find(|x| x.eq_ignore_ascii_case(v)).ok_or_else(|| bad(cmd, format!("unknown view `{v}` ({})", VIEWS.join(" | "))))?;
|
||||
o.view = v.to_string();
|
||||
}
|
||||
for (k, c) in [("overlayColor", &mut o.overlay_color), ("boundaryColor", &mut o.boundary_color)] {
|
||||
if let Some(a) = p.get(k).and_then(Value::as_array) {
|
||||
if a.len() < 3 {
|
||||
return Err(bad(cmd, format!("`{k}` is [r, g, b] (0–1)")));
|
||||
}
|
||||
for (i, v) in a.iter().take(3).enumerate() {
|
||||
c[i] = v.as_f64().unwrap_or(0.0).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(b) = b_p(p, "autoPropagate") {
|
||||
o.auto_propagate = b;
|
||||
}
|
||||
s.state.roto = o.clone();
|
||||
Ok(serde_json::to_value(o).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
fn status(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.poll_roto(false);
|
||||
let mut out =
|
||||
json!({"running": s.is_roto_running(), "progress": s.roto_progress(), "banner": s.roto_progress().map(|p| p.banner()), "options": s.state.roto});
|
||||
let Ok((cid, lid, uid)) = roto_p(s, p, "roto.status") else { return Ok(out) };
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
|
||||
let (layer, g) = group(s, cid, lid, uid)?;
|
||||
let (layer, g) = (layer.clone(), g.clone());
|
||||
let d = data_of(&g);
|
||||
let computed = s.roto_computed(cid, lid, uid);
|
||||
out["layer"] = json!(lid.0);
|
||||
out["effect"] = json!(uid);
|
||||
out["base"] = json!(d.base);
|
||||
out["span"] = json!(d.span);
|
||||
out["strokes"] = json!(d.strokes.len());
|
||||
out["strokeFrames"] = json!(d.stroke_frames());
|
||||
out["computed"] = json!(computed.iter().filter(|(_, c)| **c).map(|(f, _)| *f).collect::<Vec<_>>());
|
||||
out["frozen"] = json!(frozen_of(&g));
|
||||
out["pending"] = json!(s.roto_pending.contains(&(cid, lid, uid)));
|
||||
out["limits"] = json!(rt::frame_limits(&comp, &layer));
|
||||
let frame = frame_p(s, p, cid, &layer);
|
||||
out["frame"] = json!(frame);
|
||||
let want_matte = b_p(p, "matte").unwrap_or(false);
|
||||
let compute = b_p(p, "compute").unwrap_or(want_matte);
|
||||
if (p.get("frame").is_some() || want_matte) && d.in_span(frame) {
|
||||
let size = rt::layer_size(&s.project, &comp, &layer);
|
||||
let fps = comp.frame_rate.as_f64();
|
||||
let ps = params_static(&g);
|
||||
let chain = fx::Chain::new(&ps, size, fps, 1.0);
|
||||
let seg = match chain.keys.get(&frame).and_then(|k| fx::cached(*k, 1.0)) {
|
||||
Some(sg) => Some(sg),
|
||||
None if compute => {
|
||||
let index = layer.effects().and_then(|f| f.groups().position(|x| x.uid == uid)).unwrap_or(0);
|
||||
let mut src = rt::FrameSource::new(&s.project, s.footage.as_ref(), s.expr.as_deref(), &s.layer_cache, cid, &comp, &layer, index, size);
|
||||
chain.ensure(frame, &mut |f| src.get(f), &|| false)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(sg) = seg {
|
||||
out["area"] = json!(sg.area());
|
||||
out["centroid"] = json!(sg.centroid());
|
||||
out["size"] = json!([sg.w, sg.h]);
|
||||
out["refineArea"] = json!(sg.refine.iter().filter(|v| **v != 0).count());
|
||||
if want_matte {
|
||||
out["matte"] = json!(rle::encode(&sg.matte));
|
||||
}
|
||||
if let Some(gt) = p.get("compareTo").and_then(Value::as_str).and_then(rle::decode) {
|
||||
out["iou"] = json!(iou(&sg.matte, >));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -17,6 +17,7 @@ pub mod mask_track;
|
||||
pub mod menus;
|
||||
pub mod prefs;
|
||||
pub mod render_queue;
|
||||
pub mod roto;
|
||||
mod session_settings;
|
||||
pub mod shortcuts;
|
||||
pub mod tracking;
|
||||
@@ -41,6 +42,7 @@ pub use effectcraft_project as project;
|
||||
pub use effectcraft_render as render;
|
||||
pub use effectcraft_text as text;
|
||||
pub use effectcraft_time as time;
|
||||
pub use effectcraft_track as track;
|
||||
pub use render_queue::{ExportJob, ExportResult, Exporter, JobState};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -176,6 +178,9 @@ pub struct EditorState {
|
||||
/// Paint and Brushes panel options (Brush, Clone Stamp and Eraser tools).
|
||||
#[serde(default)]
|
||||
pub paint: commands::paint::PaintOptions,
|
||||
/// Roto Brush and Refine Edge tool options.
|
||||
#[serde(default)]
|
||||
pub roto: roto::RotoOptions,
|
||||
/// Puppet tool options for new meshes.
|
||||
#[serde(default)]
|
||||
pub puppet: commands::puppet::PuppetOptions,
|
||||
@@ -263,6 +268,10 @@ pub struct Session {
|
||||
pub warp_job: Option<warp::WarpJob>,
|
||||
/// Warp Stabilizers waiting for (re-)analysis: (comp, layer, effect uid).
|
||||
pub warp_pending: Vec<(ItemId, LayerId, Uid)>,
|
||||
/// The running (or finished, not yet polled) Roto Brush propagation / Freeze.
|
||||
pub roto_job: Option<roto::RotoJob>,
|
||||
/// Roto Brush instances edited since their last propagation: (comp, layer, effect uid).
|
||||
pub roto_pending: Vec<(ItemId, LayerId, Uid)>,
|
||||
pub events: Vec<Event>,
|
||||
/// Commands executed: (id, params).
|
||||
pub journal: Vec<(String, Value)>,
|
||||
@@ -308,6 +317,8 @@ impl Default for Session {
|
||||
mask_job: None,
|
||||
warp_job: None,
|
||||
warp_pending: vec![],
|
||||
roto_job: None,
|
||||
roto_pending: vec![],
|
||||
events: vec![],
|
||||
journal: vec![],
|
||||
layer_cache: Arc::new(LayerCache::default()),
|
||||
@@ -374,6 +385,12 @@ impl Session {
|
||||
self.warp_pending.push(w);
|
||||
}
|
||||
}
|
||||
// Roto Brush Input Keys follow the frames; edited instances propagate again.
|
||||
for r in roto::sync(&before, &mut p) {
|
||||
if !self.roto_pending.contains(&r) {
|
||||
self.roto_pending.push(r);
|
||||
}
|
||||
}
|
||||
let same = merge.is_some() && merge.map(str::to_string) == self.history.merge_key;
|
||||
if !same {
|
||||
self.history.undo.push((label.to_string(), before));
|
||||
@@ -551,6 +568,9 @@ impl Session {
|
||||
self.stop_warp();
|
||||
self.warp_job = None;
|
||||
self.warp_pending.clear();
|
||||
self.stop_roto();
|
||||
self.roto_job = None;
|
||||
self.roto_pending.clear();
|
||||
p.fix_next_id();
|
||||
self.project = Arc::new(p);
|
||||
self.history = History::default();
|
||||
@@ -615,3 +635,5 @@ pub fn text_families() -> Vec<String> {
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests_paint;
|
||||
#[cfg(test)]
|
||||
mod tests_roto;
|
||||
|
||||
@@ -0,0 +1,569 @@
|
||||
//! Roto Brush & Refine Edge runtime: propagation and Freeze jobs, Input Key maintenance and the
|
||||
//! tool options.
|
||||
//!
|
||||
//! Segmentations are derived data in `effectcraft_effects::roto`'s content-keyed cache (see that
|
||||
//! module). `roto.propagate` fills it at full resolution in the background (or blocking with
|
||||
//! `wait`), frame by frame outward from the base frame, rendering the effect's input
|
||||
//! (`Renderer::layer_input`, source → masks → the effects above it). `roto.freeze` runs the same
|
||||
//! pass and stores the final mattes in the effect (one undo step). [`sync`], run after every
|
||||
//! edit, keeps each instance's hidden Input Key equal to a signature of what its frames are made
|
||||
//! of (the layer's source and timing, its masks and the effects above it) and drops frozen
|
||||
//! mattes made from other frames.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_effects::roto::{self as fx, FROZEN, FrozenCache, INPUT_KEY};
|
||||
use effectcraft_effects::{Params, flatten_params};
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, Project, PropGroup, Uid};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, RenderOpts, Renderer};
|
||||
use effectcraft_time::Tick;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::tracking::lock;
|
||||
use crate::{Event, Session};
|
||||
|
||||
/// Roto Brush / Refine Edge tool options (serde: `roto.options`).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct RotoOptions {
|
||||
/// Roto Brush tip diameter (layer pixels).
|
||||
pub diameter: f64,
|
||||
/// Refine Edge tip diameter (layer pixels).
|
||||
pub refine_diameter: f64,
|
||||
/// Layer panel view: `alphaBoundary` (pink outline), `alpha`, `alphaOverlay`, `none`.
|
||||
pub view: String,
|
||||
/// Alpha Overlay colour (straight RGB 0–1) and opacity (percent).
|
||||
pub overlay_color: [f64; 3],
|
||||
pub overlay_opacity: f64,
|
||||
/// Alpha Boundary colour.
|
||||
pub boundary_color: [f64; 3],
|
||||
/// Start propagating in the background after each stroke.
|
||||
pub auto_propagate: bool,
|
||||
}
|
||||
|
||||
impl Default for RotoOptions {
|
||||
fn default() -> Self {
|
||||
RotoOptions {
|
||||
diameter: 20.0,
|
||||
refine_diameter: 10.0,
|
||||
view: "alphaBoundary".into(),
|
||||
overlay_color: [1.0, 0.0, 0.0],
|
||||
overlay_opacity: 50.0,
|
||||
boundary_color: [1.0, 0.25, 0.75],
|
||||
auto_propagate: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const VIEWS: [&str; 4] = ["alphaBoundary", "alpha", "alphaOverlay", "none"];
|
||||
|
||||
/// What a job does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum RotoTask {
|
||||
Propagate,
|
||||
Freeze,
|
||||
}
|
||||
|
||||
/// Which way to propagate.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Direction {
|
||||
Forward,
|
||||
Backward,
|
||||
#[default]
|
||||
Both,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
pub fn from_name(s: &str) -> Option<Direction> {
|
||||
Some(match s.to_ascii_lowercase().as_str() {
|
||||
"forward" | "fwd" => Direction::Forward,
|
||||
"backward" | "back" => Direction::Backward,
|
||||
"both" | "all" => Direction::Both,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Live job progress (serde for agents / the control channel).
|
||||
#[derive(Clone, Debug, Default, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RotoProgress {
|
||||
pub task: Option<RotoTask>,
|
||||
pub done: u64,
|
||||
pub total: u64,
|
||||
pub elapsed: f64,
|
||||
pub fps: f64,
|
||||
pub finished: bool,
|
||||
pub cancelled: bool,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl RotoProgress {
|
||||
pub fn banner(&self) -> String {
|
||||
let pc = (100 * self.done).checked_div(self.total).unwrap_or(0);
|
||||
match self.task {
|
||||
Some(RotoTask::Freeze) => format!("Freezing Roto Brush & Refine Edge: {pc}%"),
|
||||
_ => format!("Propagating Roto Brush: {pc}%"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct RotoShared {
|
||||
pub cancel: AtomicBool,
|
||||
pub state: Mutex<RotoProgress>,
|
||||
frozen: Mutex<Option<FrozenCache>>,
|
||||
}
|
||||
|
||||
pub struct RotoJob {
|
||||
pub shared: Arc<RotoShared>,
|
||||
thread: Option<std::thread::JoinHandle<()>>,
|
||||
pub comp: ItemId,
|
||||
pub layer: LayerId,
|
||||
pub effect: Uid,
|
||||
pub task: RotoTask,
|
||||
/// The strokes the job was started with (a Freeze result is dropped when they changed).
|
||||
strokes: String,
|
||||
}
|
||||
|
||||
impl RotoJob {
|
||||
pub fn is_finished(&self) -> bool {
|
||||
lock(&self.shared.state).finished
|
||||
}
|
||||
pub fn progress(&self) -> RotoProgress {
|
||||
lock(&self.shared.state).clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_roto(g: &PropGroup) -> bool {
|
||||
matches!(&g.kind, GroupKind::Effect { effect } if effect == fx::ID)
|
||||
}
|
||||
|
||||
fn str_of(g: &PropGroup, m: &str) -> String {
|
||||
match g.get(m).map(|p| &p.value) {
|
||||
Some(Value::Str(s)) => s.clone(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_str(g: &mut PropGroup, m: &str, v: String) {
|
||||
if let Some(p) = g.get_mut(m) {
|
||||
p.value = Value::Str(v);
|
||||
p.keys.clear();
|
||||
}
|
||||
}
|
||||
|
||||
fn fnv(s: &str) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in s.as_bytes() {
|
||||
h ^= *b as u64;
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// What the effect's input frames are made of: the layer's source and timing, its masks and the
|
||||
/// effects above the Roto Brush.
|
||||
pub fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String {
|
||||
let mut s = crate::warp::signature(p, comp, layer);
|
||||
if let Some(m) = layer.masks() {
|
||||
s.push_str(&format!("{m:?}"));
|
||||
}
|
||||
if let Some(fx) = layer.effects() {
|
||||
for g in fx.groups() {
|
||||
if g.uid == uid {
|
||||
break;
|
||||
}
|
||||
s.push_str(&format!("{g:?}"));
|
||||
}
|
||||
}
|
||||
format!("{:016x}", fnv(&s))
|
||||
}
|
||||
|
||||
/// After an edit: refresh Input Keys; frozen mattes made from other frames are dropped.
|
||||
/// Returns the instances whose segmentation changed (to propagate again).
|
||||
pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerId, Uid)> {
|
||||
let mut todo = vec![];
|
||||
let mut set = vec![];
|
||||
for (cid, it) in &after.items {
|
||||
let ItemKind::Comp(c) = &it.kind else { continue };
|
||||
for l in &c.layers {
|
||||
let Some(fxg) = l.effects() else { continue };
|
||||
for g in fxg.groups().filter(|g| is_roto(g)) {
|
||||
let key = input_key(after, *cid, l, g.uid);
|
||||
let old = before.comp(*cid).and_then(|bc| bc.layer(l.id)).and_then(|ol| ol.props.find_group(g.uid));
|
||||
if str_of(g, INPUT_KEY) != key {
|
||||
set.push((*cid, l.id, g.uid, key));
|
||||
todo.push((*cid, l.id, g.uid));
|
||||
} else if old.is_none_or(|o| str_of(o, fx::STROKES) != str_of(g, fx::STROKES)) {
|
||||
todo.push((*cid, l.id, g.uid));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (cid, lid, uid, key) in set {
|
||||
if let Some(g) = after.comp_mut(cid).and_then(|c| c.layer_mut(lid)).and_then(|l| l.props.find_group_mut(uid)) {
|
||||
let had = !str_of(g, INPUT_KEY).is_empty();
|
||||
set_str(g, INPUT_KEY, key);
|
||||
if had {
|
||||
set_str(g, FROZEN, String::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
todo.retain(|(c, l, u)| {
|
||||
after.comp(*c).and_then(|c| c.layer(*l)).and_then(|l| l.props.find_group(*u)).is_some_and(|g| !fx::data(¶ms_static(g)).is_empty())
|
||||
});
|
||||
todo
|
||||
}
|
||||
|
||||
/// Parameters of an instance with static values (strokes and keys are never animated).
|
||||
pub(crate) fn params_static(g: &PropGroup) -> Params {
|
||||
flatten_params(g, &mut |p| p.value.clone())
|
||||
}
|
||||
|
||||
/// Evaluated parameters of an instance at comp time `t`.
|
||||
pub(crate) fn params_at(p: &Project, cid: ItemId, layer: &Layer, g: &PropGroup, t: Tick, expr: Option<&dyn ExprHost>) -> Params {
|
||||
match p.comp(cid) {
|
||||
Some(c) => {
|
||||
let ctx = EvalCtx { expr, ..EvalCtx::new(p, cid, c, t) };
|
||||
flatten_params(g, &mut |pr| ctx.value(layer, pr))
|
||||
}
|
||||
None => params_static(g),
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer's source size (layer pixels).
|
||||
pub(crate) fn layer_size(p: &Project, comp: &effectcraft_project::Comp, layer: &Layer) -> [f64; 2] {
|
||||
let (w, h) = effectcraft_render::source_size(p, layer);
|
||||
if w == 0 { [comp.width as f64, comp.height as f64] } else { [w as f64, h as f64] }
|
||||
}
|
||||
|
||||
/// First and last layer frame of the layer inside the comp (inclusive).
|
||||
pub fn frame_limits(comp: &effectcraft_project::Comp, layer: &Layer) -> [i64; 2] {
|
||||
let fps = comp.frame_rate.as_f64().max(1e-6);
|
||||
let lo = layer.layer_time(layer.in_point.max(Tick::ZERO)).seconds();
|
||||
let hi = layer.layer_time(layer.out_point.min(comp.duration)).seconds();
|
||||
let a = fx::frame_of(lo, fps);
|
||||
let b = (fx::frame_of(hi, fps) - 1).max(a);
|
||||
[a, b]
|
||||
}
|
||||
|
||||
/// Comp time of layer frame `f`.
|
||||
pub(crate) fn comp_time_of(comp: &effectcraft_project::Comp, layer: &Layer, f: i64) -> Tick {
|
||||
layer.comp_time(comp.frame_rate.tick_of(f))
|
||||
}
|
||||
|
||||
/// What the worker needs, detached from the session.
|
||||
struct Work {
|
||||
project: Arc<Project>,
|
||||
footage: Arc<dyn FootageSource>,
|
||||
expr: Option<Arc<dyn ExprHost>>,
|
||||
cache: Arc<LayerCache>,
|
||||
comp: ItemId,
|
||||
layer: LayerId,
|
||||
effect_index: usize,
|
||||
params: Params,
|
||||
size: [f64; 2],
|
||||
fps: f64,
|
||||
frames: Vec<i64>,
|
||||
task: RotoTask,
|
||||
}
|
||||
|
||||
/// Renders the effect's input frames for a worker, keeping the last few.
|
||||
pub(crate) struct FrameSource<'a> {
|
||||
r: Renderer<'a>,
|
||||
ctx0: EvalCtx<'a>,
|
||||
comp: &'a effectcraft_project::Comp,
|
||||
layer: &'a Layer,
|
||||
index: usize,
|
||||
size: [f64; 2],
|
||||
memo: HashMap<i64, Arc<Image>>,
|
||||
}
|
||||
|
||||
impl<'a> FrameSource<'a> {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new(
|
||||
project: &'a Project,
|
||||
footage: &'a dyn FootageSource,
|
||||
expr: Option<&'a dyn ExprHost>,
|
||||
cache: &'a LayerCache,
|
||||
cid: ItemId,
|
||||
comp: &'a effectcraft_project::Comp,
|
||||
layer: &'a Layer,
|
||||
index: usize,
|
||||
size: [f64; 2],
|
||||
) -> FrameSource<'a> {
|
||||
let mut r = Renderer::new(project, footage, RenderOpts { scale: 1.0, ..Default::default() });
|
||||
r.expr = expr;
|
||||
r.cache = Some(cache);
|
||||
let ctx0 = EvalCtx { expr, ..EvalCtx::new(project, cid, comp, Tick::ZERO) };
|
||||
FrameSource { r, ctx0, comp, layer, index, size, memo: HashMap::new() }
|
||||
}
|
||||
|
||||
pub(crate) fn get(&mut self, f: i64) -> Option<Arc<Image>> {
|
||||
if let Some(i) = self.memo.get(&f) {
|
||||
return Some(i.clone());
|
||||
}
|
||||
let t = comp_time_of(self.comp, self.layer, f);
|
||||
let buf = self.r.layer_input(&self.ctx0.at(t), self.layer, self.index)?;
|
||||
let buf = if (buf.scale - 1.0).abs() > 1e-9 && buf.scale > 0.0 {
|
||||
let w = (buf.img.width as f64 / buf.scale).round().max(1.0) as u32;
|
||||
let h = (buf.img.height as f64 / buf.scale).round().max(1.0) as u32;
|
||||
effectcraft_effects::Buf {
|
||||
img: effectcraft_raster::resample(&buf.img, w, h),
|
||||
offset: [buf.offset[0] / buf.scale, buf.offset[1] / buf.scale],
|
||||
scale: 1.0,
|
||||
}
|
||||
} else {
|
||||
(*buf).clone()
|
||||
};
|
||||
let img = Arc::new(fx::layer_grid(&buf, self.size));
|
||||
if self.memo.len() > 4 {
|
||||
self.memo.clear();
|
||||
}
|
||||
self.memo.insert(f, img.clone());
|
||||
Some(img)
|
||||
}
|
||||
}
|
||||
|
||||
fn run_work(w: Work, shared: &RotoShared) {
|
||||
let t0 = web_time::Instant::now();
|
||||
let fail = |msg: &str| {
|
||||
let mut s = lock(&shared.state);
|
||||
s.error = Some(msg.to_string());
|
||||
s.finished = true;
|
||||
};
|
||||
let Some(comp) = w.project.comp(w.comp) else { return fail("composition missing") };
|
||||
let Some(layer) = comp.layer(w.layer) else { return fail("layer missing") };
|
||||
let mut src = FrameSource::new(&w.project, w.footage.as_ref(), w.expr.as_deref(), &w.cache, w.comp, comp, layer, w.effect_index, w.size);
|
||||
{
|
||||
let mut s = lock(&shared.state);
|
||||
s.task = Some(w.task);
|
||||
s.total = w.frames.len() as u64;
|
||||
}
|
||||
let cancel = || shared.cancel.load(Ordering::Relaxed);
|
||||
let chain = fx::Chain::new(&w.params, w.size, w.fps, 1.0);
|
||||
let mut frozen = FrozenCache { key: fx::frozen_key(&w.params, w.size, w.fps), ..Default::default() };
|
||||
for (k, f) in w.frames.iter().enumerate() {
|
||||
if cancel() {
|
||||
let mut s = lock(&shared.state);
|
||||
s.cancelled = true;
|
||||
s.finished = true;
|
||||
return;
|
||||
}
|
||||
let mut get = |g: i64| src.get(g);
|
||||
let ok = match w.task {
|
||||
RotoTask::Propagate => chain.ensure(*f, &mut get, &cancel).is_some(),
|
||||
RotoTask::Freeze => match fx::frame_matte(&w.params, w.size, w.fps, *f, &mut get, &cancel) {
|
||||
Some((a, b)) => {
|
||||
if let Some(img) = src.get(*f) {
|
||||
frozen.size = [img.width as usize, img.height as usize];
|
||||
}
|
||||
frozen.frames.insert(*f, fx::freeze_frame(&a, &b));
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
};
|
||||
if !ok && !cancel() {
|
||||
return fail(&format!("frame {f} could not be segmented"));
|
||||
}
|
||||
let mut s = lock(&shared.state);
|
||||
s.done = k as u64 + 1;
|
||||
s.elapsed = t0.elapsed().as_secs_f64();
|
||||
s.fps = if s.elapsed > 0.0 { s.done as f64 / s.elapsed } else { 0.0 };
|
||||
}
|
||||
if w.task == RotoTask::Freeze {
|
||||
*lock(&shared.frozen) = Some(frozen);
|
||||
}
|
||||
let mut s = lock(&shared.state);
|
||||
s.elapsed = t0.elapsed().as_secs_f64();
|
||||
s.finished = true;
|
||||
}
|
||||
|
||||
/// Frames to compute, outward from the base frame.
|
||||
pub(crate) fn job_frames(d: &effectcraft_track::roto::RotoData, dir: Direction) -> Vec<i64> {
|
||||
let Some(base) = d.base else { return vec![] };
|
||||
let mut v = vec![base];
|
||||
if dir != Direction::Backward {
|
||||
v.extend(base + 1..=d.span[1]);
|
||||
}
|
||||
if dir != Direction::Forward {
|
||||
v.extend((d.span[0]..base).rev());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn is_roto_running(&self) -> bool {
|
||||
self.roto_job.as_ref().is_some_and(|j| !j.is_finished())
|
||||
}
|
||||
|
||||
pub fn roto_progress(&self) -> Option<RotoProgress> {
|
||||
self.roto_job.as_ref().map(|j| j.progress())
|
||||
}
|
||||
|
||||
/// (comp, layer, effect uid, task) of the running job.
|
||||
pub fn roto_target(&self) -> Option<(ItemId, LayerId, Uid, RotoTask)> {
|
||||
self.roto_job.as_ref().map(|j| (j.comp, j.layer, j.effect, j.task))
|
||||
}
|
||||
|
||||
pub fn stop_roto(&mut self) -> bool {
|
||||
match &self.roto_job {
|
||||
Some(j) if !j.is_finished() => {
|
||||
j.shared.cancel.store(true, Ordering::Relaxed);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start propagating (or freezing) Roto Brush `effect` on `layer`. `wait`: block until done
|
||||
/// (wasm32 always does). Returns the number of frames.
|
||||
pub fn start_roto(&mut self, comp: ItemId, layer: LayerId, effect: Uid, task: RotoTask, dir: Direction, wait: bool) -> Result<usize, String> {
|
||||
if self.is_roto_running() {
|
||||
if !wait {
|
||||
return Err("a Roto Brush job is already running".into());
|
||||
}
|
||||
self.stop_roto();
|
||||
if let Some(mut j) = self.roto_job.take()
|
||||
&& let Some(t) = j.thread.take()
|
||||
{
|
||||
let _ = t.join();
|
||||
}
|
||||
}
|
||||
self.poll_roto_job();
|
||||
self.roto_pending.retain(|x| *x != (comp, layer, effect));
|
||||
let c = self.project.comp(comp).ok_or("no composition")?;
|
||||
let l = c.layer(layer).ok_or("no layer")?;
|
||||
let fxg = l.effects().ok_or("the layer has no effects")?;
|
||||
let index = fxg.groups().position(|g| g.uid == effect).ok_or("no such effect")?;
|
||||
let g = fxg.groups().nth(index).filter(|g| is_roto(g)).ok_or("not a Roto Brush & Refine Edge effect")?;
|
||||
let size = layer_size(&self.project, c, l);
|
||||
let fps = c.frame_rate.as_f64();
|
||||
let pstat = params_static(g);
|
||||
let d = fx::data(&pstat);
|
||||
if d.is_empty() {
|
||||
return Err("draw a foreground stroke with the Roto Brush tool first".into());
|
||||
}
|
||||
let t = comp_time_of(c, l, d.base.unwrap_or(0));
|
||||
let params = params_at(&self.project, comp, l, g, t, self.expr.as_deref());
|
||||
let frames = job_frames(&d, if task == RotoTask::Freeze { Direction::Both } else { dir });
|
||||
let n = frames.len();
|
||||
let work = Work {
|
||||
project: self.project.clone(),
|
||||
footage: self.footage.clone(),
|
||||
expr: self.expr.clone(),
|
||||
cache: self.layer_cache.clone(),
|
||||
comp,
|
||||
layer,
|
||||
effect_index: index,
|
||||
params,
|
||||
size,
|
||||
fps,
|
||||
frames,
|
||||
task,
|
||||
};
|
||||
let strokes = str_of(g, fx::STROKES);
|
||||
let wait = wait || cfg!(target_arch = "wasm32");
|
||||
let shared = Arc::new(RotoShared::default());
|
||||
let thread = if wait {
|
||||
run_work(work, &shared);
|
||||
None
|
||||
} else {
|
||||
let sh = shared.clone();
|
||||
Some(std::thread::Builder::new().name("roto".into()).spawn(move || run_work(work, &sh)).map_err(|e| e.to_string())?)
|
||||
};
|
||||
self.roto_job = Some(RotoJob { shared, thread, comp, layer, effect, task, strokes });
|
||||
self.events.push(Event::ProjectChanged { revision: self.revision });
|
||||
self.poll_roto_job();
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Finish a done job: Freeze writes the frozen mattes (one undo step).
|
||||
fn poll_roto_job(&mut self) -> bool {
|
||||
let Some(job) = &self.roto_job else { return false };
|
||||
if !job.is_finished() {
|
||||
return false;
|
||||
}
|
||||
let mut job = self.roto_job.take().expect("job");
|
||||
if let Some(t) = job.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
let st = job.progress();
|
||||
if let Some(e) = &st.error {
|
||||
self.events.push(Event::Toast { message: format!("Roto Brush: {e}"), error: true });
|
||||
self.bump();
|
||||
return true;
|
||||
}
|
||||
if st.cancelled {
|
||||
self.events.push(Event::Toast { message: "Roto Brush: stopped".into(), error: false });
|
||||
self.bump();
|
||||
return true;
|
||||
}
|
||||
match job.task {
|
||||
RotoTask::Propagate => {
|
||||
self.events.push(Event::Toast { message: format!("Roto Brush: propagated {} frame(s) in {:.1} s", st.done, st.elapsed), error: false });
|
||||
// Rendered frames depend on the cache: redraw.
|
||||
self.bump();
|
||||
}
|
||||
RotoTask::Freeze => {
|
||||
let Some(fc) = lock(&job.shared.frozen).take() else { return true };
|
||||
let (cid, lid, uid, strokes) = (job.comp, job.layer, job.effect, job.strokes.clone());
|
||||
let r = self.edit("Freeze", None, |p, _| {
|
||||
let g = p
|
||||
.comp_mut(cid)
|
||||
.and_then(|c| c.layer_mut(lid))
|
||||
.and_then(|l| l.props.find_group_mut(uid))
|
||||
.ok_or_else(|| crate::EngineError::Other("the Roto Brush effect was removed".into()))?;
|
||||
if str_of(g, fx::STROKES) != strokes {
|
||||
return Err(crate::EngineError::Other("the strokes changed while freezing".into()));
|
||||
}
|
||||
set_str(g, FROZEN, fc.to_json());
|
||||
Ok(())
|
||||
});
|
||||
let msg = match r {
|
||||
Ok(()) => format!("Roto Brush: froze {} frame(s) in {:.1} s", fc.frames.len(), st.elapsed),
|
||||
Err(e) => format!("Roto Brush: {e}"),
|
||||
};
|
||||
self.events.push(Event::Toast { message: msg, error: false });
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Frontends call this every frame: finishes jobs and (with `auto`) propagates edited
|
||||
/// instances in the background.
|
||||
pub fn poll_roto(&mut self, auto: bool) -> bool {
|
||||
let changed = self.poll_roto_job();
|
||||
if auto && self.roto_job.is_none() && self.state.roto.auto_propagate {
|
||||
while let Some((c, l, e)) = self.roto_pending.first().copied() {
|
||||
self.roto_pending.remove(0);
|
||||
if self.start_roto(c, l, e, RotoTask::Propagate, Direction::Both, false).is_ok() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The computed frames of an instance (full resolution), by layer frame.
|
||||
pub fn roto_computed(&self, comp: ItemId, layer: LayerId, effect: Uid) -> BTreeMap<i64, bool> {
|
||||
let mut out = BTreeMap::new();
|
||||
let Some(c) = self.project.comp(comp) else { return out };
|
||||
let Some(l) = c.layer(layer) else { return out };
|
||||
let Some(g) = l.props.find_group(effect) else { return out };
|
||||
let ps = params_static(g);
|
||||
let ch = fx::Chain::new(&ps, layer_size(&self.project, c, l), c.frame_rate.as_f64(), 1.0);
|
||||
for f in ch.keys.keys() {
|
||||
out.insert(*f, ch.is_cached(*f, 1.0));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//! Roto Brush & Refine Edge end to end through the commands, on synthetic footage: a textured
|
||||
//! disk moving over a textured background.
|
||||
|
||||
use effectcraft_project::LayerId;
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_render::RenderOpts;
|
||||
use effectcraft_track::roto::rle;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
use crate::tests_track::{H, W, frame_time, setup};
|
||||
|
||||
const R: f64 = 40.0;
|
||||
|
||||
fn noise(x: f64, y: f64, seed: u32) -> f64 {
|
||||
fn h(i: i64, j: i64, s: u32) -> f64 {
|
||||
let mut v = (i.wrapping_mul(73856093) ^ j.wrapping_mul(19349663) ^ (s as i64).wrapping_mul(83492791)) as u64;
|
||||
v ^= v >> 13;
|
||||
v = v.wrapping_mul(0x5bd1e995);
|
||||
v ^= v >> 15;
|
||||
(v % 10_000) as f64 / 10_000.0
|
||||
}
|
||||
let mut out = 0.0;
|
||||
for (cell, amp) in [(9.0, 0.6), (3.5, 0.4)] {
|
||||
let (fx, fy) = (x / cell, y / cell);
|
||||
let (i, j) = (fx.floor() as i64, fy.floor() as i64);
|
||||
let (tx, ty) = (fx - i as f64, fy - j as f64);
|
||||
let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty));
|
||||
let a = h(i, j, seed) + (h(i + 1, j, seed) - h(i, j, seed)) * sx;
|
||||
let b = h(i, j + 1, seed) + (h(i + 1, j + 1, seed) - h(i, j + 1, seed)) * sx;
|
||||
out += amp * (a + (b - a) * sy);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Disk centre on frame `f`.
|
||||
fn center(f: u32) -> [f64; 2] {
|
||||
let t = f as f64;
|
||||
[90.0 + 4.0 * t, 110.0 + 1.5 * t + 5.0 * (t * 0.3).sin()]
|
||||
}
|
||||
|
||||
/// Disk centre with a jump at frame 8 (propagation loses it there).
|
||||
fn jumping(f: u32) -> [f64; 2] {
|
||||
if f < 8 { center(f) } else { [230.0 + 2.0 * (f - 8) as f64, 150.0] }
|
||||
}
|
||||
|
||||
fn draw(c: [f64; 2]) -> Image {
|
||||
let mut img = Image::new(W, H);
|
||||
for y in 0..H {
|
||||
for x in 0..W {
|
||||
let p = [x as f64 + 0.5, y as f64 + 0.5];
|
||||
let d = (p[0] - c[0]).hypot(p[1] - c[1]);
|
||||
let a = (R + 0.5 - d).clamp(0.0, 1.0) as f32;
|
||||
let n = noise(p[0] - c[0], p[1] - c[1], 11);
|
||||
let f = [(0.75 + 0.25 * n) as f32, (0.35 + 0.3 * n) as f32, (0.1 + 0.15 * n) as f32];
|
||||
let (bn, bm) = (noise(p[0], p[1], 5), noise(p[0] * 1.7, p[1] * 1.7, 9));
|
||||
let b = [(0.05 + 0.25 * bm) as f32, (0.3 + 0.4 * bn) as f32, (0.45 + 0.4 * bm) as f32];
|
||||
img.set(x, y, [f[0] * a + b[0] * (1.0 - a), f[1] * a + b[1] * (1.0 - a), f[2] * a + b[2] * (1.0 - a), 1.0]);
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
fn gt(c: [f64; 2]) -> String {
|
||||
let m: Vec<u8> = (0..W * H).map(|i| (((i % W) as f64 + 0.5 - c[0]).hypot((i / W) as f64 + 0.5 - c[1]) <= R) as u8).collect();
|
||||
rle::encode(&m)
|
||||
}
|
||||
|
||||
fn line(a: [f64; 2], b: [f64; 2]) -> Value {
|
||||
json!((0..=8).map(|k| [a[0] + (b[0] - a[0]) * k as f64 / 8.0, a[1] + (b[1] - a[1]) * k as f64 / 8.0]).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// A session with the clip (the Track solid removed) and foreground / background strokes on
|
||||
/// frame 0. `name`: the footage file name (segmentations are cached process-wide by content key,
|
||||
/// which includes the footage's identity: different clips need different names).
|
||||
fn painted(path: fn(u32) -> [f64; 2], name: &str) -> (Session, LayerId, u64) {
|
||||
let (mut s, clip, solid) = setup(move |f| draw(path(f)));
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
s.edit("remove solid", None, |p, _| {
|
||||
p.comp_mut(cid).unwrap().layers.retain(|l| l.id != solid);
|
||||
for it in p.items.values_mut() {
|
||||
if let effectcraft_project::ItemKind::Footage(f) = &mut it.kind {
|
||||
f.path = name.into();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("time.set", json!({"time": 0})).unwrap();
|
||||
let c = path(0);
|
||||
let r =
|
||||
s.execute_checked("roto.stroke", json!({"layer": clip.0, "points": line([c[0] - 22.0, c[1] - 8.0], [c[0] + 22.0, c[1] + 8.0]), "radius": 6})).unwrap();
|
||||
let uid = r["effect"].as_u64().unwrap();
|
||||
assert_eq!(r["base"], 0);
|
||||
assert_eq!(r["span"], json!([0, 20]));
|
||||
for (a, b) in [([c[0] - 60.0, c[1] - 58.0], [c[0] + 70.0, c[1] - 58.0]), ([c[0] + 70.0, c[1] + 58.0], [c[0] - 60.0, c[1] + 58.0])] {
|
||||
s.execute_checked("roto.stroke", json!({"layer": clip.0, "kind": "bg", "points": line(a, b), "radius": 6})).unwrap();
|
||||
}
|
||||
(s, clip, uid)
|
||||
}
|
||||
|
||||
/// Drop an instance's derived segmentations from the process-wide cache.
|
||||
fn forget(s: &Session, clip: LayerId, uid: u64) {
|
||||
let comp = s.active_comp().unwrap();
|
||||
let l = comp.layer(clip).unwrap();
|
||||
let g = l.props.find_group(uid).unwrap();
|
||||
let size = crate::roto::layer_size(&s.project, comp, l);
|
||||
let ch = effectcraft_effects::roto::Chain::new(&crate::roto::params_static(g), size, comp.frame_rate.as_f64(), 1.0);
|
||||
effectcraft_effects::roto::forget(ch.keys.values().copied());
|
||||
}
|
||||
|
||||
fn iou_at(s: &mut Session, clip: LayerId, f: u32, c: [f64; 2]) -> f64 {
|
||||
let st = s.execute("roto.status", json!({"layer": clip.0, "frame": f, "compute": true, "compareTo": gt(c)})).unwrap();
|
||||
st["iou"].as_f64().unwrap_or_else(|| panic!("no matte on frame {f}: {st}"))
|
||||
}
|
||||
|
||||
fn alpha_at(s: &Session, f: u32) -> Vec<f32> {
|
||||
let img = s.render(s.active_comp_id().unwrap(), frame_time(f), RenderOpts { scale: 1.0, ..Default::default() });
|
||||
img.data.iter().map(|p| p[3]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roto_brush_segments_and_propagates() {
|
||||
let (mut s, clip, uid) = painted(center, "disk-a.mov");
|
||||
let l = s.active_comp().unwrap().layer(clip).unwrap().clone();
|
||||
assert_eq!(l.effects().unwrap().groups().filter(|g| crate::roto::is_roto(g)).count(), 1, "one effect for all strokes");
|
||||
let j0 = iou_at(&mut s, clip, 0, center(0));
|
||||
assert!(j0 > 0.95, "base frame IoU {j0}");
|
||||
// Propagate the span (blocking).
|
||||
let r = s.execute_checked("roto.propagate", json!({"layer": clip.0, "direction": "both", "wait": true})).unwrap();
|
||||
assert_eq!(r["frames"], 21, "{r}");
|
||||
assert_eq!(r["status"]["computed"].as_array().unwrap().len(), 21);
|
||||
let mut worst: f64 = 1.0;
|
||||
for f in 0..=20 {
|
||||
worst = worst.min(iou_at(&mut s, clip, f, center(f)));
|
||||
}
|
||||
assert!(worst > 0.9, "worst IoU over the span {worst}");
|
||||
// The render applies the matte; outside the span the layer is transparent.
|
||||
let a = alpha_at(&s, 12);
|
||||
let c = center(12);
|
||||
let mut wrong = 0;
|
||||
for (i, v) in a.iter().enumerate() {
|
||||
let d = (((i as u32 % W) as f64 + 0.5 - c[0]).hypot((i as u32 / W) as f64 + 0.5 - c[1])) - R;
|
||||
if (d < -3.0 && *v < 0.5) || (d > 3.0 && *v > 0.5) {
|
||||
wrong += 1;
|
||||
}
|
||||
}
|
||||
assert!(wrong < 150, "{wrong} wrong pixels in the render");
|
||||
assert!(alpha_at(&s, 23).iter().all(|v| *v == 0.0));
|
||||
// Extending the span propagates further.
|
||||
let r = s.execute("roto.propagate", json!({"layer": clip.0, "direction": "forward", "to": 24, "wait": true})).unwrap();
|
||||
assert_eq!(r["status"]["span"], json!([0, 24]));
|
||||
assert!(iou_at(&mut s, clip, 24, center(24)) > 0.9);
|
||||
// Undo / redo of strokes and the span.
|
||||
let n = |s: &Session| {
|
||||
let st = s.active_comp().unwrap().layer(clip).unwrap().props.find_group(uid).unwrap().get(effectcraft_effects::roto::STROKES).unwrap().value.clone();
|
||||
match st {
|
||||
effectcraft_keyframe::Value::Str(j) => effectcraft_track::roto::RotoData::from_json(&j),
|
||||
_ => panic!(),
|
||||
}
|
||||
};
|
||||
assert_eq!(n(&s).span, [0, 24]);
|
||||
assert!(s.undo());
|
||||
assert_eq!(n(&s).span, [0, 20]);
|
||||
assert_eq!(n(&s).strokes.len(), 3);
|
||||
assert!(s.undo());
|
||||
assert_eq!(n(&s).strokes.len(), 2);
|
||||
assert!(s.redo());
|
||||
assert!(s.redo());
|
||||
assert_eq!(n(&s).strokes.len(), 3);
|
||||
assert_eq!(n(&s).span, [0, 24]);
|
||||
// Serde keeps the strokes; the reopened project renders the same matte.
|
||||
let back = effectcraft_project::Project::from_json(&s.project.to_json()).unwrap();
|
||||
let g = back.comp(s.active_comp_id().unwrap()).unwrap().layer(clip).unwrap().props.find_group(uid).unwrap().clone();
|
||||
assert_eq!(
|
||||
crate::roto::params_static(&g).get("strokes"),
|
||||
crate::roto::params_static(s.active_comp().unwrap().layer(clip).unwrap().props.find_group(uid).unwrap()).get("strokes")
|
||||
);
|
||||
// Bad parameters are reported.
|
||||
assert!(s.execute_checked("roto.stroke", json!({"layer": clip.0, "kind": "sideways", "points": [[1, 1]]})).is_err());
|
||||
assert!(s.execute_checked("roto.propagate", json!({"layer": clip.0, "bogus": 1})).is_err());
|
||||
assert!(s.execute_checked("roto.stroke", json!({"layer": clip.0, "points": [[1, 1]], "frame": 99})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn correction_strokes_restart_propagation() {
|
||||
let (mut s, clip, _) = painted(jumping, "disk-jump.mov");
|
||||
s.execute("roto.propagate", json!({"layer": clip.0, "wait": true})).unwrap();
|
||||
assert!(iou_at(&mut s, clip, 6, jumping(6)) > 0.9);
|
||||
let bad = iou_at(&mut s, clip, 8, jumping(8));
|
||||
assert!(bad < 0.5, "the jump should break propagation ({bad})");
|
||||
// Correct frame 8: paint the disk in and its old place out.
|
||||
let (c, old) = (jumping(8), center(8));
|
||||
s.execute("roto.stroke", json!({"layer": clip.0, "frame": 8, "points": line([c[0] - 20.0, c[1]], [c[0] + 20.0, c[1]]), "radius": 6})).unwrap();
|
||||
s.execute(
|
||||
"roto.stroke",
|
||||
json!({"layer": clip.0, "frame": 8, "kind": "bg", "points": line([old[0] - 15.0, old[1] - 15.0], [old[0] + 15.0, old[1] + 15.0]), "radius": 8}),
|
||||
)
|
||||
.unwrap();
|
||||
let st = s.execute("roto.status", json!({"layer": clip.0})).unwrap();
|
||||
let computed: Vec<i64> = serde_json::from_value(st["computed"].clone()).unwrap();
|
||||
assert!(computed.contains(&7) && !computed.contains(&8) && !computed.contains(&9), "frames from the correction on are recomputed: {computed:?}");
|
||||
assert_eq!(st["strokeFrames"], json!([0, 8]));
|
||||
s.execute("roto.propagate", json!({"layer": clip.0, "direction": "forward", "wait": true})).unwrap();
|
||||
for f in 8..=20 {
|
||||
let j = iou_at(&mut s, clip, f, jumping(f));
|
||||
assert!(j > 0.9, "frame {f}: IoU {j}");
|
||||
}
|
||||
// Clearing the correction brings the bad frame back.
|
||||
let r = s.execute("roto.clearStrokes", json!({"layer": clip.0, "frame": 8})).unwrap();
|
||||
assert_eq!(r["removed"], 2);
|
||||
assert!(iou_at(&mut s, clip, 8, jumping(8)) < 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn freeze_caches_the_mattes() {
|
||||
let (mut s, clip, uid) = painted(center, "disk-freeze.mov");
|
||||
// A refine band along the edge on the base frame.
|
||||
let c = center(0);
|
||||
let ring: Vec<[f64; 2]> = (0..=40).map(|k| k as f64 / 40.0 * std::f64::consts::TAU).map(|a| [c[0] + R * a.cos(), c[1] + R * a.sin()]).collect();
|
||||
s.execute_checked("roto.stroke", json!({"layer": clip.0, "kind": "refine", "points": ring, "radius": 5})).unwrap();
|
||||
s.execute("roto.span", json!({"layer": clip.0, "end": 3})).unwrap();
|
||||
let live: Vec<Vec<f32>> = (0..=3).map(|f| alpha_at(&s, f)).collect();
|
||||
// Freeze in the background and wait for it.
|
||||
let r = s.execute_checked("roto.freeze", json!({"layer": clip.0})).unwrap();
|
||||
assert_eq!(r["frames"], 4);
|
||||
let t0 = std::time::Instant::now();
|
||||
while s.roto_job.is_some() {
|
||||
assert!(t0.elapsed().as_secs() < 300);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
s.poll_roto(false);
|
||||
}
|
||||
let st = s.execute("roto.status", json!({"layer": clip.0})).unwrap();
|
||||
assert_eq!(st["frozen"], true, "{st}");
|
||||
// Frozen renders match the live ones (8-bit alpha), even without the derived segmentations.
|
||||
forget(&s, clip, uid);
|
||||
s.layer_cache = Default::default();
|
||||
for (f, want) in live.iter().enumerate() {
|
||||
let got = alpha_at(&s, f as u32);
|
||||
let worst = got.iter().zip(want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
|
||||
assert!(worst <= 1.0 / 255.0 + 1e-4, "frame {f}: {worst}");
|
||||
}
|
||||
assert!(st["computed"].as_array().unwrap().len() >= 4);
|
||||
// Frozen effects refuse strokes; Unfreeze is undoable.
|
||||
assert!(s.execute("roto.stroke", json!({"layer": clip.0, "points": [[10, 10]]})).is_err());
|
||||
s.execute("roto.unfreeze", json!({"layer": clip.0})).unwrap();
|
||||
assert_eq!(s.execute("roto.status", json!({"layer": clip.0})).unwrap()["frozen"], false);
|
||||
assert!(s.undo());
|
||||
assert_eq!(s.execute("roto.status", json!({"layer": clip.0})).unwrap()["frozen"], true);
|
||||
// Changing the source frames (the layer's timing) drops the frozen mattes.
|
||||
let cid = s.active_comp_id().unwrap();
|
||||
s.edit("shift", None, |p, _| {
|
||||
let l = p.comp_mut(cid).unwrap().layer_mut(clip).unwrap();
|
||||
l.start_time = frame_time(1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(s.execute("roto.status", json!({"layer": clip.0, "effect": uid})).unwrap()["frozen"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn propagation_is_deterministic_and_runs_in_background() {
|
||||
let (mut s, clip, uid) = painted(center, "disk-bg.mov");
|
||||
s.execute("roto.span", json!({"layer": clip.0, "end": 5})).unwrap();
|
||||
s.execute("roto.propagate", json!({"layer": clip.0})).unwrap();
|
||||
let t0 = std::time::Instant::now();
|
||||
while s.roto_job.is_some() {
|
||||
assert!(t0.elapsed().as_secs() < 300);
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
s.poll_roto(false);
|
||||
}
|
||||
let st = s.execute("roto.status", json!({"layer": clip.0})).unwrap();
|
||||
assert_eq!(st["computed"], json!([0, 1, 2, 3, 4, 5]), "{st}");
|
||||
let a = s.execute("roto.status", json!({"layer": clip.0, "frame": 5, "matte": true})).unwrap()["matte"].clone();
|
||||
// Recomputing from scratch gives the same matte.
|
||||
forget(&s, clip, uid);
|
||||
let b = s.execute("roto.status", json!({"layer": clip.0, "frame": 5, "matte": true})).unwrap()["matte"].clone();
|
||||
assert!(a.is_string());
|
||||
assert_eq!(a, b);
|
||||
// Tool options.
|
||||
let o = s.execute_checked("roto.options", json!({"diameter": 30, "view": "alphaOverlay"})).unwrap();
|
||||
assert_eq!(o["view"], "alphaOverlay");
|
||||
assert_eq!(s.state.roto.diameter, 30.0);
|
||||
assert!(s.execute("roto.options", json!({"view": "sideways"})).is_err());
|
||||
// The default radius follows the tool diameter.
|
||||
let r = s.execute("roto.stroke", json!({"layer": clip.0, "points": [[90, 110]]})).unwrap();
|
||||
assert_eq!(r["radius"], 15.0);
|
||||
}
|
||||
Reference in New Issue
Block a user