M13.15: qa scenarios 1-4 (kinetic type, shape logo, compositing, tracking) and fixes
engine.batch + MCP batch tool; layer.newText/newShape name; prop.get evaluated expression value; keys.select by path with errors; @uid paths; plain-JSON gradients; addShapeItem/effect.apply return paths; unknown layers error; conform rescales footage duration; render log name for [###]; render_frame transparent; clearer mask errors; truncated groups in flat get_layer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
95766755f3
commit
fecf054e5f
@@ -17,3 +17,4 @@ image = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
effectcraft-script = { workspace = true }
|
||||
effectcraft-host = { workspace = true }
|
||||
|
||||
@@ -67,16 +67,25 @@ impl Backend {
|
||||
/// Render a comp frame (comp time `time` seconds, default the CTI) as PNG, longest side at most
|
||||
/// `max_side` (0 = full size).
|
||||
pub fn render(&mut self, comp: Option<&Value>, time: Option<f64>, max_side: u32) -> Result<Frame> {
|
||||
self.render_with(comp, time, max_side, false)
|
||||
}
|
||||
|
||||
/// [`Backend::render`]; `transparent` keeps the frame's alpha instead of compositing it over
|
||||
/// the comp's background colour.
|
||||
pub fn render_with(&mut self, comp: Option<&Value>, time: Option<f64>, max_side: u32, transparent: bool) -> Result<Frame> {
|
||||
match self {
|
||||
Backend::Headless(s) => {
|
||||
let cid = s.resolve_comp(comp).map_err(|_| no_comp(comp))?;
|
||||
let t = time.map(Tick::from_seconds_f64).unwrap_or_else(|| s.time());
|
||||
let (w, h, rgba) = s.render_rgba8(cid, t, max_side)?;
|
||||
let (w, h, rgba) = s.render_rgba8_alpha(cid, t, max_side, transparent)?;
|
||||
let png = encode_png(w, h, rgba, max_side)?;
|
||||
Ok(Frame { png, comp: json!(cid.0), time: t.seconds(), width: w, height: h })
|
||||
}
|
||||
Backend::Bridge(b) => {
|
||||
let mut p = json!({"max_side": max_side, "base64": true});
|
||||
if transparent {
|
||||
p["transparent"] = json!(true);
|
||||
}
|
||||
if let Some(t) = time {
|
||||
p["time"] = json!(t);
|
||||
}
|
||||
|
||||
@@ -159,6 +159,11 @@ fn get_comp(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
|
||||
/// Flatten a `layer.tree` property tree into `[{path, type, value, keys?, expression?}]`.
|
||||
fn flatten(node: &Value, out: &mut Vec<Value>) {
|
||||
// A group cut off by `depth` stays visible (instead of vanishing from the flat list).
|
||||
if node.get("truncated").and_then(Value::as_bool) == Some(true) {
|
||||
out.push(json!({"path": node["path"], "type": "group", "name": node["name"], "truncated": true}));
|
||||
return;
|
||||
}
|
||||
match node.get("children").and_then(Value::as_array) {
|
||||
Some(ch) => ch.iter().for_each(|c| flatten(c, out)),
|
||||
None => {
|
||||
@@ -259,7 +264,8 @@ fn add_keyframe(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
|
||||
fn render_frame(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let max_side = get(a, "max_side").and_then(Value::as_u64).unwrap_or(960) as u32;
|
||||
let f = b.render(get(a, "comp"), get(a, "time").and_then(Value::as_f64), max_side)?;
|
||||
let transparent = get(a, "transparent").and_then(Value::as_bool).unwrap_or(false);
|
||||
let f = b.render_with(get(a, "comp"), get(a, "time").and_then(Value::as_f64), max_side, transparent)?;
|
||||
let mut info = json!({"comp": f.comp, "time": f.time, "width": f.width, "height": f.height});
|
||||
if let Some(p) = get(a, "path").and_then(Value::as_str) {
|
||||
std::fs::write(p, &f.png).map_err(|e| Error::Other(format!("cannot write {p}: {e}")))?;
|
||||
@@ -341,6 +347,15 @@ fn history_tool(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
json_reply(b.exec("edit.history.list", json!({}))?)
|
||||
}
|
||||
|
||||
fn batch_tool(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
let steps = need(a, "steps")?;
|
||||
let steps = match steps {
|
||||
Value::String(_) => params_of(Some(steps))?,
|
||||
v => v.clone(),
|
||||
};
|
||||
json_reply(b.exec("engine.batch", obj(&[("steps", Some(&steps)), ("label", get(a, "label")), ("atomic", get(a, "atomic"))]))?)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bridge-only tools
|
||||
|
||||
fn screenshot(b: &mut Backend, a: &Value) -> Result<Reply> {
|
||||
@@ -524,7 +539,8 @@ static TOOLS: &[ToolDef] = &[
|
||||
"time": {"type": "number", "description": "Comp time in seconds (default: current time)."},
|
||||
"max_side": {"type": "integer", "description": "Longest side in pixels (default 960; 0 = full comp size)."},
|
||||
"path": {"type": "string", "description": "Also write the PNG here."},
|
||||
"inline": {"type": "boolean", "description": "Include the image in the reply (default true)."}
|
||||
"inline": {"type": "boolean", "description": "Include the image in the reply (default true)."},
|
||||
"transparent": {"type": "boolean", "description": "Keep the frame's alpha (RGBA PNG, as an RGB + Alpha render writes it) instead of compositing over the comp's background colour."}
|
||||
}),
|
||||
&[],
|
||||
)
|
||||
@@ -681,4 +697,20 @@ static TOOLS: &[ToolDef] = &[
|
||||
schema: || schema(json!({"method": {"type": "string"}, "params": {"type": "object", "additionalProperties": true}}), &["method"]),
|
||||
run: control,
|
||||
},
|
||||
ToolDef {
|
||||
name: "batch",
|
||||
description: "Run several engine commands in one call as ONE undo step (engine.batch). Later steps can use earlier results: a string param \"$N\" or \"$N.key\" is step N's result (1-based), e.g. create a layer, then key and style it: {\"steps\":[{\"command\":\"layer.newText\",\"params\":{\"text\":\"Hi\",\"name\":\"Title\"}},{\"command\":\"prop.addKey\",\"params\":{\"layer\":\"$1.layer\",\"path\":\"transform/opacity\",\"time\":0,\"value\":0}},{\"command\":\"effect.apply\",\"params\":{\"layer\":\"$1.layer\",\"effect\":\"Glow\"}}]}. Returns {steps, results}. If a step fails the whole batch is rolled back (unless atomic: false) and the error names the step.",
|
||||
bridge_only: false,
|
||||
schema: || {
|
||||
schema(
|
||||
json!({
|
||||
"steps": {"type": "array", "items": {"type": "object", "properties": {"command": {"type": "string"}, "params": {"type": "object", "additionalProperties": true}}, "required": ["command"]}},
|
||||
"label": {"type": "string", "description": "Undo step name (default Batch)."},
|
||||
"atomic": {"type": "boolean", "description": "Roll everything back when a step fails (default true)."}
|
||||
}),
|
||||
&["steps"],
|
||||
)
|
||||
},
|
||||
run: batch_tool,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Scenario 3 — compositing: an imported image sequence and a layered PSD (as a composition),
|
||||
//! a blend mode, a track matte, an adjustment layer (Lumetri + Glow) limited by a feathered,
|
||||
//! expanded mask, a camera with depth of field and a light in Classic 3D and Advanced 3D; then
|
||||
//! ProRes 4444 and WebM VP9 renders with alpha, read back through import.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::harness::{Img, Qa, coverage, luma, mean_diff};
|
||||
|
||||
fn px(img: &Img, x: u32, y: u32) -> [u8; 4] {
|
||||
img.get_pixel(x, y).0
|
||||
}
|
||||
|
||||
/// A 12-frame PNG sequence of an orange ball crossing a blue background.
|
||||
fn write_sequence(qa: &Qa) -> String {
|
||||
std::fs::create_dir_all(qa.dir.join("seq")).unwrap();
|
||||
for f in 0..12u32 {
|
||||
let cx = 20.0 + f as f64 * 10.0;
|
||||
let img = image::RgbaImage::from_fn(160, 90, |x, y| {
|
||||
let d = ((x as f64 - cx).powi(2) + (y as f64 - 45.0).powi(2)).sqrt();
|
||||
if d < 15.0 { image::Rgba([255, 170, 0, 255]) } else { image::Rgba([32, 64, 96, 255]) }
|
||||
});
|
||||
img.save(qa.dir.join(format!("seq/ball_{f:03}.png"))).unwrap();
|
||||
}
|
||||
qa.path("seq/ball_000.png")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compositing_matte_blend_adjustment_3d_and_alpha_renders() {
|
||||
let mut qa = Qa::new("compositing");
|
||||
|
||||
// Footage: the sequence, and a layered PSD written by the app itself (Save Frame As ▸
|
||||
// Photoshop Layers) from a small comp.
|
||||
let seq = write_sequence(&qa);
|
||||
let imp = qa.exec("file.import", json!({"paths": [seq]}));
|
||||
let seq_item = imp["items"][0].clone();
|
||||
let project = qa.tool("get_project", json!({}));
|
||||
let it = project["items"].as_array().unwrap().iter().find(|i| i["id"] == seq_item).unwrap().clone();
|
||||
assert_eq!(it["type"], "Image Sequence", "{it}");
|
||||
// Sequences import at 30 fps (Settings ▸ Import); these frames were made for 12.
|
||||
assert!((it["duration"].as_f64().unwrap() - 0.4).abs() < 1e-6, "{it}");
|
||||
qa.exec("file.interpretFootage", json!({"items": [seq_item.clone()], "frameRate": 12}));
|
||||
let project = qa.tool("get_project", json!({}));
|
||||
let it = project["items"].as_array().unwrap().iter().find(|i| i["id"] == seq_item).unwrap().clone();
|
||||
assert!((it["duration"].as_f64().unwrap() - 1.0).abs() < 1e-6, "12 frames at 12 fps: {it}");
|
||||
qa.exec("comp.new", json!({"name": "Art", "width": 160, "height": 90, "frameRate": 12, "duration": 1}));
|
||||
qa.exec("layer.newSolid", json!({"name": "Gray", "color": "#606060", "width": 80, "height": 90}));
|
||||
qa.tool("set_property", json!({"layer": "Gray", "path": "transform/position", "value": [120, 45]}));
|
||||
qa.exec("layer.newShape", json!({"kind": "rect", "name": "Bar", "size": [160, 10], "fill": "#00ff00", "position": [80, 10]}));
|
||||
let psd = qa.path("art.psd");
|
||||
let saved = qa.exec("comp.saveFrameAsPsd", json!({"path": psd, "comp": "Art", "time": 0}));
|
||||
assert_eq!(saved["layers"], 2, "{saved}");
|
||||
let pimp = qa.exec("file.import", json!({"paths": [psd], "importAs": "composition"}));
|
||||
let psd_comp = pimp["comps"][0].clone();
|
||||
let pc = qa.tool("get_comp", json!({"comp": psd_comp.clone()}));
|
||||
let names: Vec<&str> = pc["layers"].as_array().unwrap().iter().map(|l| l["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Bar", "Gray"], "the PSD's layers, top first: {pc}");
|
||||
|
||||
// The main comp.
|
||||
let main = qa.exec("comp.new", json!({"name": "Main", "width": 160, "height": 90, "frameRate": 12, "duration": 1}))["comp"].clone();
|
||||
qa.exec("layer.addItem", json!({"item": seq_item}));
|
||||
let a = qa.frame(None, 0.0);
|
||||
let b = qa.frame(None, 0.5);
|
||||
assert!(mean_diff(&a, &b) > 1.0, "the sequence plays");
|
||||
assert_eq!(px(&a, 20, 45)[..3], [255, 170, 0], "frame 0: the ball at x=20");
|
||||
assert_eq!(px(&b, 80, 45)[..3], [255, 170, 0], "frame 6 at 0.5 s: the ball at x=80");
|
||||
|
||||
let art = qa.exec("layer.addItem", json!({"item": psd_comp.clone()}))["layer"].clone();
|
||||
let normal = qa.frame(None, 0.5);
|
||||
qa.exec("layer.setBlendMode", json!({"layers": [art.clone()], "mode": "Screen"}));
|
||||
let screen = qa.frame(None, 0.5);
|
||||
// Screen over the blue background: brighter than both inputs (0x60 gray over 0x20,0x40,0x60).
|
||||
let (n, s) = (px(&normal, 140, 60), px(&screen, 140, 60));
|
||||
assert_eq!(n[..3], [0x60, 0x60, 0x60], "Normal shows the gray");
|
||||
for c in 0..3 {
|
||||
assert!(s[c] > n[c] && s[c] > [32, 64, 96][c], "Screen brightens channel {c}: {s:?}");
|
||||
}
|
||||
|
||||
// Track matte: a magenta solid seen only through text.
|
||||
qa.exec("layer.newText", json!({"text": "MATTE", "name": "Matte", "size": 40, "fill": "#ffffff"}));
|
||||
qa.exec("layer.newSolid", json!({"name": "Fill", "color": "#ff00ff", "width": 160, "height": 90}));
|
||||
let magenta = |p: &image::Rgba<u8>| p[0] > 230 && p[1] < 30 && p[2] > 230;
|
||||
let full = coverage(&qa.frame(None, 0.5), magenta);
|
||||
assert!(full > 0.95);
|
||||
qa.exec("layer.setTrackMatte", json!({"layer": "Fill", "matte": "Matte", "kind": "alpha"}));
|
||||
let matted = qa.frame(None, 0.5);
|
||||
let m = coverage(&matted, magenta);
|
||||
assert!(m > 0.03 && m < 0.4, "magenta only inside the glyphs: {m}");
|
||||
assert!(coverage(&matted, |p| p[0] > 250 && p[1] > 250 && p[2] > 250) < 0.002, "the matte layer itself is hidden");
|
||||
let info = qa.tool("get_comp", json!({}));
|
||||
let fill = info["layers"].as_array().unwrap().iter().find(|l| l["name"] == "Fill").unwrap().clone();
|
||||
assert_eq!(fill["trackMatte"]["kind"], "Alpha Matte");
|
||||
qa.exec("layer.setSwitch", json!({"layers": ["Fill", "Matte"], "switch": "video", "value": false}));
|
||||
|
||||
// Adjustment layer: Lumetri exposure, inside a feathered, expanded elliptical mask; then Glow.
|
||||
qa.exec("layer.newAdjustment", json!({"name": "Grade"}));
|
||||
let fx = qa.exec("effect.apply", json!({"effect": "Lumetri Color", "layers": ["Grade"]}));
|
||||
assert_eq!(fx["paths"], json!(["effects/#1"]), "effect.apply answers with the instance path: {fx}");
|
||||
qa.tool("set_property", json!({"layer": "Grade", "path": "effects/#1/basicCorrection/tone/exposure", "value": 2}));
|
||||
let before = qa.frame(None, 0.5);
|
||||
let e = qa.exec_err("layer.mask.set", json!({"layer": "Grade", "field": "feather", "value": 10}));
|
||||
assert!(e.contains("layer.addMask"), "the error says how to make a mask: {e}");
|
||||
let mk = qa.exec("layer.addMask", json!({"layer": "Grade", "shape": "ellipse", "rect": [40, 20, 80, 50]}));
|
||||
assert!(mk["mask"].is_u64(), "{mk}");
|
||||
let hard = qa.frame(None, 0.5);
|
||||
let lum = |i: &Img, x, y| luma(i.get_pixel(x, y));
|
||||
assert!(lum(&hard, 80, 45) > lum(&before, 80, 45) - 1.0 && lum(&hard, 5, 5) < lum(&before, 5, 5) - 10.0, "the mask limits the grade to the ellipse");
|
||||
qa.exec("layer.mask.set", json!({"layer": "Grade", "field": "expansion", "value": 8}));
|
||||
let grown = qa.frame(None, 0.5);
|
||||
let bright = |i: &Img, base: &Img| {
|
||||
let mut n = 0;
|
||||
for (x, y, p) in i.enumerate_pixels() {
|
||||
if luma(p) > luma(base.get_pixel(x, y)) + 20.0 {
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
n
|
||||
};
|
||||
assert!(bright(&grown, &normal) > bright(&hard, &normal) + 100, "expansion grows the graded area");
|
||||
qa.exec("layer.mask.set", json!({"layer": "Grade", "field": "feather", "value": 20}));
|
||||
let soft = qa.frame(None, 0.5);
|
||||
// At the ellipse's edge (x = 40 − 8): feathered is in between none and full.
|
||||
let (edge_hard, edge_soft) = (lum(&grown, 33, 45), lum(&soft, 33, 45));
|
||||
assert!((edge_hard - edge_soft).abs() > 5.0, "feather softens the edge: {edge_hard} vs {edge_soft}");
|
||||
qa.exec("effect.apply", json!({"effect": "Glow", "layers": ["Grade"]}));
|
||||
let glow = qa.frame(None, 0.5);
|
||||
assert!(mean_diff(&soft, &glow) > 0.5, "Glow changes the frame");
|
||||
|
||||
// 3D stage: a near and a far card, a camera with depth of field, a light.
|
||||
let stage = qa.exec("comp.new", json!({"name": "Stage", "width": 160, "height": 90, "frameRate": 12, "duration": 1}))["comp"].clone();
|
||||
qa.exec("layer.newSolid", json!({"name": "Near", "color": "#ff4040", "width": 40, "height": 40}));
|
||||
qa.exec("layer.newSolid", json!({"name": "Far", "color": "#40ff40", "width": 40, "height": 40}));
|
||||
qa.exec("layer.setSwitch", json!({"layers": ["Near", "Far"], "switch": "threeD", "value": true}));
|
||||
qa.tool("set_property", json!({"layer": "Near", "path": "transform/position", "value": [50, 45, 0]}));
|
||||
qa.tool("set_property", json!({"layer": "Far", "path": "transform/position", "value": [110, 45, 300]}));
|
||||
let cam = qa.exec("layer.newCamera", json!({"name": "Cam", "preset": "50mm", "dof": false}))["layer"].clone();
|
||||
let sharp = qa.frame(None, 0.0);
|
||||
qa.tool("set_property", json!({"layer": cam.clone(), "path": "cameraOptions/dof", "value": true}));
|
||||
let zoom = qa.tool("get_property", json!({"layer": cam.clone(), "path": "cameraOptions/zoom"}))["value"].as_f64().unwrap();
|
||||
qa.tool("set_property", json!({"layer": cam.clone(), "path": "cameraOptions/focusDistance", "value": zoom}));
|
||||
qa.tool("set_property", json!({"layer": cam.clone(), "path": "cameraOptions/aperture", "value": 40}));
|
||||
let dof = qa.frame(None, 0.0);
|
||||
let green = |p: &image::Rgba<u8>| p[1] > 200 && p[0] < 120;
|
||||
let red = |p: &image::Rgba<u8>| p[0] > 200 && p[1] < 120;
|
||||
assert!(coverage(&dof, green) < coverage(&sharp, green) * 0.8, "the far card defocuses");
|
||||
assert!((coverage(&dof, red) - coverage(&sharp, red)).abs() < 0.02, "the card at the focus distance stays sharp");
|
||||
// A light behind the near card leaves it dark; in front, lit.
|
||||
let light = qa.exec("layer.newLight", json!({"kind": "Point", "name": "Key", "intensity": 100, "position": [50, 45, 400]}))["layer"].clone();
|
||||
let back = qa.frame(None, 0.0);
|
||||
qa.tool("set_property", json!({"layer": light, "path": "transform/position", "value": [50, 45, -150]}));
|
||||
let front = qa.frame(None, 0.0);
|
||||
assert!(lum(&back, 50, 45) < 30.0 && lum(&front, 50, 45) > 60.0, "lighting: {} vs {}", lum(&back, 50, 45), lum(&front, 50, 45));
|
||||
let classic = front;
|
||||
assert_eq!(qa.exec("comp.renderer", json!({"renderer": "advanced3d"}))["renderer"], "advanced3d");
|
||||
let advanced = qa.frame(None, 0.0);
|
||||
assert!(mean_diff(&classic, &advanced) > 0.2, "Advanced 3D renders the stage its own way");
|
||||
assert!(lum(&advanced, 50, 45) > 60.0, "Advanced 3D still lights the card");
|
||||
|
||||
// Renders with alpha: the stage has no background layer, so most of it is transparent.
|
||||
let mov = qa.path("stage.mov");
|
||||
let webm = qa.path("stage.webm");
|
||||
qa.exec("renderQueue.add", json!({"comp": stage.clone(), "format": "prores", "proresProfile": "4444", "channels": "rgba", "output": mov}));
|
||||
qa.exec("renderQueue.add", json!({"comp": stage.clone(), "format": "webm", "channels": "rgba", "output": webm}));
|
||||
let done = qa.exec("renderQueue.render", json!({"wait": true}));
|
||||
assert!(done["items"].as_array().unwrap().iter().all(|i| i["status"] == "Done"), "{done}");
|
||||
let reference = qa.tool("render_frame", json!({"comp": stage.clone(), "time": 0, "transparent": true, "inline": false}));
|
||||
assert_eq!(reference["width"], 160);
|
||||
let refa = alpha_frame(&mut qa, stage.clone());
|
||||
assert!(px(&refa, 2, 2)[3] < 40 && px(&refa, 50, 45)[3] == 255, "render_frame transparent keeps alpha: {:?} {:?}", px(&refa, 2, 2), px(&refa, 50, 45));
|
||||
for (path, decodes_alpha) in [(mov, true), (webm, false)] {
|
||||
let r = qa.exec("file.import", json!({"paths": [path]}));
|
||||
assert_eq!(r["errors"], json!([]));
|
||||
assert_eq!(r["unlabeledAlpha"], r["items"], "{path}: the importer sees an alpha channel");
|
||||
let c = qa.exec("file.newCompFromSelection", json!({}))["comps"][0].clone();
|
||||
let f = alpha_frame(&mut qa, c.clone());
|
||||
// The opaque card decodes to the stage's colours (lossy codecs, so loosely).
|
||||
let (got, want) = (px(&f, 50, 45), px(&refa, 50, 45));
|
||||
assert!((0..3).all(|c| got[c].abs_diff(want[c]) < 12), "{path} decodes to the stage: {got:?} vs {want:?}");
|
||||
if decodes_alpha {
|
||||
assert!(mean_diff(&qa.frame(Some(c.clone()), 0.0), &qa.frame(Some(stage.clone()), 0.0)) < 8.0, "{path} composites like the stage");
|
||||
assert!(px(&f, 2, 2)[3] < 40 && px(&f, 50, 45)[3] > 250, "{path}: transparent corners, opaque card");
|
||||
}
|
||||
// (WebM: FilmCraft's Matroska reader flags VP9 alpha but does not decode its
|
||||
// BlockAdditional alpha stream yet, so the frames come back opaque.)
|
||||
}
|
||||
let _ = main;
|
||||
}
|
||||
|
||||
fn alpha_frame(qa: &mut Qa, comp: Value) -> Img {
|
||||
let c = qa.try_tool("render_frame", json!({"comp": comp, "time": 0, "max_side": 0, "transparent": true})).unwrap();
|
||||
let png = effectcraft_automation::base64::decode(c[0]["data"].as_str().unwrap()).unwrap();
|
||||
image::load_from_memory(&png).unwrap().to_rgba8()
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! A motion designer's seat: an MCP server over a fully wired headless session, spoken to in
|
||||
//! JSON-RPC exactly as an MCP client would (`tools/call` lines in, replies out), plus pixel
|
||||
//! helpers for asserting on what was rendered.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use effectcraft_automation::{Backend, McpServer, base64};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub struct Qa {
|
||||
mcp: McpServer,
|
||||
next_id: u64,
|
||||
pub dir: PathBuf,
|
||||
}
|
||||
|
||||
pub type Img = image::RgbaImage;
|
||||
|
||||
impl Qa {
|
||||
/// A fresh headless MCP session and an empty scratch folder for its files.
|
||||
pub fn new(name: &str) -> Qa {
|
||||
let dir = std::env::temp_dir().join(format!("effectcraft-qa-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut qa = Qa { mcp: McpServer::new(Backend::headless(effectcraft_host::session())), next_id: 0, dir };
|
||||
let init = qa.rpc("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "qa", "version": "0"}}));
|
||||
assert_eq!(init["serverInfo"]["name"], "effectcraft");
|
||||
qa
|
||||
}
|
||||
|
||||
/// A path inside the scratch folder.
|
||||
pub fn path(&self, rel: &str) -> String {
|
||||
self.dir.join(rel).to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn rpc(&mut self, method: &str, params: Value) -> Value {
|
||||
self.next_id += 1;
|
||||
let line = json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params}).to_string();
|
||||
let reply: Value = serde_json::from_str(&self.mcp.handle_line(&line).expect("a reply")).expect("JSON reply");
|
||||
assert_eq!(reply["id"], self.next_id);
|
||||
assert!(reply.get("error").is_none(), "{method}: {reply}");
|
||||
reply["result"].clone()
|
||||
}
|
||||
|
||||
/// Call a tool; `Err(message)` when it reports `isError`.
|
||||
pub fn try_tool(&mut self, name: &str, args: Value) -> Result<Vec<Value>, String> {
|
||||
let r = self.rpc("tools/call", json!({"name": name, "arguments": args}));
|
||||
let content = r["content"].as_array().cloned().unwrap_or_default();
|
||||
if r["isError"].as_bool() == Some(true) {
|
||||
return Err(content.first().and_then(|c| c["text"].as_str()).unwrap_or("").to_string());
|
||||
}
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
/// Call a tool that answers JSON; panics with the tool's message if it fails.
|
||||
pub fn tool(&mut self, name: &str, args: Value) -> Value {
|
||||
match self.try_tool(name, args.clone()) {
|
||||
Ok(c) => serde_json::from_str(c[0]["text"].as_str().expect("text content")).expect("JSON text"),
|
||||
Err(e) => panic!("{name} {args}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `execute_command`.
|
||||
pub fn exec(&mut self, command: &str, params: Value) -> Value {
|
||||
self.tool("execute_command", json!({"command": command, "params": params}))
|
||||
}
|
||||
|
||||
/// `execute_command` expected to fail; returns the message.
|
||||
pub fn exec_err(&mut self, command: &str, params: Value) -> String {
|
||||
match self.try_tool("execute_command", json!({"command": command, "params": params})) {
|
||||
Ok(c) => panic!("{command} {params} should fail, got {c:?}"),
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
|
||||
/// `render_frame` at full size, decoded.
|
||||
pub fn frame(&mut self, comp: Option<Value>, time: f64) -> Img {
|
||||
let mut args = json!({"time": time, "max_side": 0});
|
||||
if let Some(c) = comp {
|
||||
args["comp"] = c;
|
||||
}
|
||||
let c = self.try_tool("render_frame", args).unwrap_or_else(|e| panic!("render_frame: {e}"));
|
||||
assert_eq!(c[0]["type"], "image");
|
||||
let png = base64::decode(c[0]["data"].as_str().unwrap()).expect("base64");
|
||||
image::load_from_memory(&png).expect("PNG").to_rgba8()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Qa {
|
||||
fn drop(&mut self) {
|
||||
if !std::thread::panicking() {
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fraction of pixels matching `f`.
|
||||
pub fn coverage(img: &Img, f: impl Fn(&image::Rgba<u8>) -> bool) -> f64 {
|
||||
img.pixels().filter(|p| f(p)).count() as f64 / (img.width() * img.height()).max(1) as f64
|
||||
}
|
||||
|
||||
/// Mean absolute difference per channel (0–255) of two same-size images.
|
||||
pub fn mean_diff(a: &Img, b: &Img) -> f64 {
|
||||
assert_eq!(a.dimensions(), b.dimensions());
|
||||
let s: u64 = a.as_raw().iter().zip(b.as_raw()).map(|(x, y)| x.abs_diff(*y) as u64).sum();
|
||||
s as f64 / a.as_raw().len() as f64
|
||||
}
|
||||
|
||||
/// Centroid (x, y) of the pixels matching `f`.
|
||||
pub fn centroid(img: &Img, f: impl Fn(&image::Rgba<u8>) -> bool) -> Option<(f64, f64)> {
|
||||
let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0);
|
||||
for (x, y, p) in img.enumerate_pixels() {
|
||||
if f(p) {
|
||||
sx += x as f64;
|
||||
sy += y as f64;
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
(n > 0.0).then(|| (sx / n, sy / n))
|
||||
}
|
||||
|
||||
pub fn luma(p: &image::Rgba<u8>) -> f64 {
|
||||
0.2126 * p[0] as f64 + 0.7152 * p[1] as f64 + 0.0722 * p[2] as f64
|
||||
}
|
||||
|
||||
pub fn load(path: impl AsRef<Path>) -> Img {
|
||||
image::open(path.as_ref()).unwrap_or_else(|e| panic!("{}: {e}", path.as_ref().display())).to_rgba8()
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! Scenario 1 — kinetic typography: text layers with per-character animators, range and wiggly
|
||||
//! selectors, expressions (wiggle, valueAtTime, pick-whip links), motion blur, a time-remapped
|
||||
//! precomp; rendered to an H.264 MP4 and a PNG sequence, both checked by re-importing them.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::harness::{Qa, centroid, coverage, luma, mean_diff};
|
||||
|
||||
#[test]
|
||||
fn kinetic_typography() {
|
||||
let mut qa = Qa::new("kinetic");
|
||||
let comp = qa.exec("comp.new", json!({"name": "Kinetic", "width": 160, "height": 90, "frameRate": 12, "duration": 2}))["comp"].clone();
|
||||
|
||||
// Title: named at creation (one call), characters fly in from above with a range selector.
|
||||
let title = qa.exec("layer.newText", json!({"text": "MOVE", "name": "Title", "size": 36, "fill": "#ffffff"}))["layer"].clone();
|
||||
assert!(title.is_u64(), "layer.newText returns the new layer's id");
|
||||
let anim = qa.exec("layer.addTextAnimator", json!({"layer": "Title", "properties": ["position", "opacity"]}));
|
||||
assert!(anim["animator"].is_u64());
|
||||
qa.tool("set_property", json!({"layer": "Title", "path": "text/animators/#1/properties/position", "value": [0, -60, 0]}));
|
||||
qa.tool("set_property", json!({"layer": "Title", "path": "text/animators/#1/properties/opacity", "value": 0}));
|
||||
let off = qa.tool(
|
||||
"add_keyframe",
|
||||
json!({"layer": "Title", "path": "text/animators/#1/selectors/#1/offset", "keys": [{"time": 0, "value": 0}, {"time": 1, "value": 100}], "interpolation": "easyEase"}),
|
||||
);
|
||||
assert_eq!(off["keys"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(off["keys"][0]["out"], "Bezier", "easy ease makes Bezier keys");
|
||||
// A second, wiggly selector (Mode: Intersect) jitters the amounts; pinned to 100 % here so
|
||||
// frames stay predictable, then checked to really wiggle once released.
|
||||
let wig = qa.exec("layer.addTextSelector", json!({"layer": "Title", "animator": 1, "kind": "wiggly"}));
|
||||
assert!(wig["selector"].is_u64());
|
||||
qa.tool("set_property", json!({"layer": "Title", "path": "text/animators/#1/selectors/wigglySelector/minAmount", "value": 100}));
|
||||
qa.tool("add_keyframe", json!({"layer": "Title", "path": "transform/position", "keys": [{"time": 0, "value": [40, 50]}, {"time": 2, "value": [120, 50]}]}));
|
||||
qa.exec("layer.setSwitch", json!({"layers": ["Title"], "switch": "motionBlur", "value": true}));
|
||||
assert_eq!(qa.exec("comp.setSwitch", json!({"switch": "motionBlur", "value": true})), json!(true));
|
||||
|
||||
// Sub line: pick-whip link, wiggle, valueAtTime.
|
||||
qa.exec("layer.newText", json!({"text": "type", "name": "Sub", "size": 18, "fill": "#ffcc00"}));
|
||||
let pos =
|
||||
qa.tool("set_property", json!({"layer": "Sub", "path": "transform/position", "expression": "thisComp.layer(\"Title\").transform.position + [0, 30]"}));
|
||||
assert_eq!(pos["evaluated"], json!([40.0, 80.0, 0.0]), "the reply shows the expression's result: {pos}");
|
||||
qa.tool("set_property", json!({"layer": "Sub", "path": "transform/rotation", "expression": "wiggle(4, 20)"}));
|
||||
qa.tool(
|
||||
"set_property",
|
||||
json!({"layer": "Sub", "path": "transform/scale", "expression": "var x = thisComp.layer(\"Title\").transform.position.valueAtTime(time - 0.5)[0]; [x, x]"}),
|
||||
);
|
||||
let p = qa.tool("get_property", json!({"layer": "Sub", "path": "transform/position", "time": 1}));
|
||||
assert_eq!(p["evaluated"], json!([80.0, 80.0, 0.0]), "{p}");
|
||||
let r1 = qa.tool("get_property", json!({"layer": "Sub", "path": "transform/rotation", "time": 1}))["evaluated"].as_f64().unwrap();
|
||||
let r2 = qa.tool("get_property", json!({"layer": "Sub", "path": "transform/rotation", "time": 1.5}))["evaluated"].as_f64().unwrap();
|
||||
assert!(r1 != r2 && r1.abs() <= 20.0 && r2.abs() <= 20.0, "wiggle moves within its amplitude: {r1} {r2}");
|
||||
let s = qa.tool("get_property", json!({"layer": "Sub", "path": "transform/scale", "time": 1.5}));
|
||||
assert_eq!(s["evaluated"], json!([80.0, 80.0, 100.0]), "valueAtTime(time - 0.5) of the title's x: {s}");
|
||||
let bad = qa.tool("set_property", json!({"layer": "Sub", "path": "transform/opacity", "expression": "thisComp.layer(\"Nope\").transform.opacity"}));
|
||||
assert!(bad["expressionError"].is_string(), "a broken expression reports why: {bad}");
|
||||
qa.tool("set_property", json!({"layer": "Sub", "path": "transform/opacity", "expression": ""}));
|
||||
|
||||
// The characters arrive over time: little title coverage at the start, all of it at 1 s.
|
||||
let white = |p: &image::Rgba<u8>| p[0] > 180 && p[1] > 180 && p[2] > 180;
|
||||
let f0 = qa.frame(None, 0.0);
|
||||
let f1 = qa.frame(None, 1.2);
|
||||
let (c0, c1) = (coverage(&f0, white), coverage(&f1, white));
|
||||
assert!(c1 > 0.02, "the title's glyphs are drawn at 1.2 s: {c1}");
|
||||
assert!(c0 < c1 * 0.5, "the range selector hides the characters at 0 s: {c0} vs {c1}");
|
||||
let cx = centroid(&f1, white).unwrap().0;
|
||||
assert!((cx - 88.0).abs() < 12.0, "title follows its position keys (x≈88 at 1.2 s): {cx}");
|
||||
qa.tool("set_property", json!({"layer": "Title", "path": "text/animators/#1/selectors/wigglySelector/minAmount", "value": -100}));
|
||||
let jitter = qa.frame(None, 0.0);
|
||||
assert!(coverage(&jitter, white) > c0 + 0.002, "the wiggly selector lets some characters through at 0 s");
|
||||
qa.tool("undo", json!({}));
|
||||
|
||||
// A precomp of everything, time-remapped to play backwards.
|
||||
let pre = qa.exec("layer.precompose", json!({"layers": ["Title", "Sub"], "name": "Type Pre", "mode": "move"}));
|
||||
assert!(pre["comp"].is_u64() && pre["layer"].is_u64(), "{pre}");
|
||||
qa.exec("layer.enableTimeRemap", json!({"layers": [pre["layer"].clone()], "value": true}));
|
||||
qa.tool("add_keyframe", json!({"layer": pre["layer"].clone(), "path": "timeRemap", "keys": [{"time": 0, "value": 1.9}, {"time": 1.9, "value": 0}]}));
|
||||
let fwd = qa.frame(Some(pre["comp"].clone()), 1.6);
|
||||
let rev = qa.frame(Some(comp.clone()), 0.3);
|
||||
assert!(mean_diff(&fwd, &rev) < 1.0, "time remap 0.3 s → 1.6 s of the precomp");
|
||||
|
||||
// Render: H.264 and a PNG sequence through the render queue.
|
||||
let mp4 = qa.path("kinetic.mp4");
|
||||
let seq = qa.path("seq/kin_[####].png");
|
||||
let a = qa.exec("renderQueue.add", json!({"comp": "Kinetic", "format": "h264", "output": mp4}));
|
||||
assert_eq!(a["frames"], 24);
|
||||
qa.exec("renderQueue.add", json!({"comp": "Kinetic", "format": "png", "output": seq}));
|
||||
let done = qa.exec("renderQueue.render", json!({"wait": true}));
|
||||
for it in done["items"].as_array().unwrap() {
|
||||
assert_eq!(it["status"], "Done", "{it}");
|
||||
}
|
||||
let frames: Vec<_> =
|
||||
std::fs::read_dir(qa.dir.join("seq")).unwrap().filter_map(|e| e.ok()).filter(|e| e.path().extension().is_some_and(|x| x == "png")).collect();
|
||||
assert_eq!(frames.len(), 24, "one PNG per frame");
|
||||
let first = crate::harness::load(qa.dir.join("seq/kin_0000.png"));
|
||||
let last = crate::harness::load(qa.dir.join("seq/kin_0023.png"));
|
||||
assert!(mean_diff(&first, &last) > 1.0, "the sequence changes over time");
|
||||
|
||||
// Re-import the movie and look at it like footage.
|
||||
let imp = qa.exec("file.import", json!({"paths": [mp4]}));
|
||||
assert_eq!(imp["errors"], json!([]), "{imp}");
|
||||
let vc = qa.exec("file.newCompFromSelection", json!({}))["comps"][0].clone();
|
||||
let info = qa.tool("get_comp", json!({"comp": vc.clone()}));
|
||||
assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(160), Some(90)));
|
||||
assert!((info["duration"].as_f64().unwrap() - 2.0).abs() < 0.01, "{info}");
|
||||
let m0 = qa.frame(Some(vc.clone()), 0.0);
|
||||
let m1 = qa.frame(Some(vc.clone()), 1.25);
|
||||
assert!(mean_diff(&m0, &m1) > 1.0, "the movie's frames differ over time");
|
||||
// The decoded movie matches the comp (lossy, so loosely).
|
||||
let ref1 = qa.frame(Some(comp.clone()), 1.25);
|
||||
assert!(mean_diff(&m1, &ref1) < 12.0, "decoded H.264 ≈ the comp: {}", mean_diff(&m1, &ref1));
|
||||
let bright = |p: &image::Rgba<u8>| luma(p) > 150.0;
|
||||
assert!(coverage(&m1, bright) > 0.01, "glyphs survive encoding");
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! M13.15 end-to-end QA: realistic projects built only through the agent interfaces (MCP tools
|
||||
//! over JSON-RPC, the same commands the CLI and control channel run), asserting on rendered
|
||||
//! pixels and written files rather than on command success alone.
|
||||
|
||||
mod compositing;
|
||||
mod harness;
|
||||
mod kinetic;
|
||||
mod shapes;
|
||||
mod tracking;
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Scenario 2 — a shape-layer logo: merge paths, offset paths, a gradient fill and a repeater
|
||||
//! inside the mark, a trim-paths ring with eased keys (Keyframe Velocity), both parented to a
|
||||
//! rotating null; exported to Lottie, re-imported, and compared frame by frame.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::harness::{Qa, centroid, coverage, mean_diff};
|
||||
|
||||
fn white(p: &image::Rgba<u8>) -> bool {
|
||||
p[0] > 200 && p[1] > 200 && p[2] > 200
|
||||
}
|
||||
fn bluish(p: &image::Rgba<u8>) -> bool {
|
||||
p[2] > 150 && p[0] < 120
|
||||
}
|
||||
fn yellowish(p: &image::Rgba<u8>) -> bool {
|
||||
p[0] > 150 && p[1] > 150 && p[2] < 110
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_logo_with_lottie_round_trip() {
|
||||
let mut qa = Qa::new("shapes");
|
||||
qa.exec("comp.new", json!({"name": "Logo", "width": 160, "height": 160, "frameRate": 12, "duration": 2}));
|
||||
qa.exec("layer.newNull", json!({"name": "Ctrl"}));
|
||||
|
||||
// The mark: a square merged with a circle, grown by Offset Paths, gradient-filled, repeated.
|
||||
qa.exec("layer.newShape", json!({"kind": "rect", "size": [30, 30], "name": "Mark", "fill": "#ff0000", "position": [80, 80]}));
|
||||
let ell = qa.exec("layer.addShapeItem", json!({"layer": "Mark", "kind": "ellipse", "group": "contents/group"}));
|
||||
assert_eq!(ell["path"], "contents/group/contents/ellipse", "addShapeItem answers with the new item's path: {ell}");
|
||||
let base = ell["path"].as_str().unwrap().trim_end_matches("/ellipse").to_string();
|
||||
qa.tool("set_property", json!({"layer": "Mark", "path": format!("{base}/ellipse/position"), "value": [15, 15]}));
|
||||
qa.tool("set_property", json!({"layer": "Mark", "path": format!("{base}/ellipse/size"), "value": [24, 24]}));
|
||||
qa.exec("layer.addShapeItem", json!({"layer": "Mark", "kind": "merge", "group": "contents/group"}));
|
||||
let off = qa.exec("layer.addShapeItem", json!({"layer": "Mark", "kind": "offset", "group": "contents/group"}));
|
||||
qa.tool("set_property", json!({"layer": "Mark", "path": format!("{}/amount", off["path"].as_str().unwrap()), "value": 3}));
|
||||
let gf = qa.exec("layer.addShapeItem", json!({"layer": "Mark", "kind": "gfill", "group": "contents/group"}))["path"].as_str().unwrap().to_string();
|
||||
qa.tool("set_property", json!({"layer": "Mark", "path": format!("{base}/fill/opacity"), "value": 0}));
|
||||
// Gradients as plain JSON (a list of colour stops), not only the tagged form get returns.
|
||||
let g = qa.tool("set_property", json!({"layer": "Mark", "path": format!("{gf}/colors"), "value": ["#0080ff", "#ffff00"]}));
|
||||
assert_eq!(g["type"], "gradient");
|
||||
qa.tool("set_property", json!({"layer": "Mark", "path": format!("{gf}/start"), "value": [-20, 0]}));
|
||||
qa.tool("set_property", json!({"layer": "Mark", "path": format!("{gf}/end"), "value": [30, 0]}));
|
||||
let rep = qa.exec("layer.addShapeItem", json!({"layer": "Mark", "kind": "repeater"}))["path"].as_str().unwrap().to_string();
|
||||
qa.tool("set_property", json!({"layer": "Mark", "path": format!("{rep}/transform/position"), "value": [0, 0]}));
|
||||
qa.tool("set_property", json!({"layer": "Mark", "path": format!("{rep}/transform/rotation"), "value": 120}));
|
||||
|
||||
// The ring: a stroke drawn on by Trim Paths, eased with Keyframe Velocity.
|
||||
qa.exec("layer.newShape", json!({"kind": "ellipse", "size": [120, 120], "name": "Ring", "strokeWidth": 5, "stroke": "#ffffff", "position": [80, 80]}));
|
||||
qa.tool("set_property", json!({"layer": "Ring", "path": "contents/group/contents/fill/opacity", "value": 0}));
|
||||
let trim = qa.exec("layer.addShapeItem", json!({"layer": "Ring", "kind": "trim"}))["path"].as_str().unwrap().to_string();
|
||||
let end = format!("{trim}/end");
|
||||
qa.tool("add_keyframe", json!({"layer": "Ring", "path": end, "keys": [{"time": 0, "value": 0}, {"time": 1, "value": 100}]}));
|
||||
let linear = qa.tool("get_property", json!({"layer": "Ring", "path": end, "time": 0.25}))["value"].as_f64().unwrap();
|
||||
assert!((linear - 25.0).abs() < 1e-6);
|
||||
// Keys selected by path (not only by uid), then Keyframe Velocity: speed 0, 33 % influence.
|
||||
assert_eq!(qa.exec("keys.select", json!({"keys": [{"layer": "Ring", "path": end, "time": 0}]})), json!(1));
|
||||
qa.exec("keys.velocity", json!({"outSpeed": 0, "outInfluence": 33.33}));
|
||||
assert_eq!(qa.exec("keys.select", json!({"keys": [{"layer": "Ring", "path": end, "time": 1}]})), json!(1));
|
||||
qa.exec("keys.velocity", json!({"inSpeed": 0, "inInfluence": 33.33}));
|
||||
let eased = qa.tool("get_property", json!({"layer": "Ring", "path": end, "time": 0.25}))["value"].as_f64().unwrap();
|
||||
assert!(eased < 20.0, "eased keys start slowly: {eased}");
|
||||
let mid = qa.tool("get_property", json!({"layer": "Ring", "path": end, "time": 0.5}))["value"].as_f64().unwrap();
|
||||
assert!((mid - 50.0).abs() < 1.0, "symmetric ease passes 50 % at the middle: {mid}");
|
||||
// A key reference that matches nothing is an error, not an empty selection.
|
||||
let e = qa.exec_err("keys.select", json!({"keys": [{"layer": "Ring", "path": "contents/nope", "time": 0}]}));
|
||||
assert!(e.contains("no such property"), "{e}");
|
||||
|
||||
// Parent both to the null and spin it.
|
||||
qa.exec("layer.setParent", json!({"layers": ["Ring", "Mark"], "parent": "Ctrl"}));
|
||||
let e = qa.exec_err("layer.setParent", json!({"layers": ["Rnig"], "parent": "Ctrl"}));
|
||||
assert!(e.contains("no layer"), "a misspelt layer is reported: {e}");
|
||||
qa.tool("add_keyframe", json!({"layer": "Ctrl", "path": "transform/rotation", "keys": [{"time": 0, "value": 0}, {"time": 2, "value": 90}]}));
|
||||
|
||||
let f0 = qa.frame(None, 0.0);
|
||||
let f05 = qa.frame(None, 0.5);
|
||||
let f15 = qa.frame(None, 1.5);
|
||||
let ring = |f: &image::RgbaImage| coverage(f, white);
|
||||
assert!(ring(&f0) < 0.002, "trim end 0 draws no ring: {}", ring(&f0));
|
||||
let (half, full) = (ring(&f05), ring(&f15));
|
||||
assert!(full > 0.03 && (half / full - 0.5).abs() < 0.1, "half the ring at 0.5 s: {half} vs {full}");
|
||||
assert!(coverage(&f15, bluish) > 0.005 && coverage(&f15, yellowish) > 0.005, "the gradient's two ends are both visible");
|
||||
// The repeater makes three copies around the layer's anchor (the comp centre): the mark's
|
||||
// centroid stays near the centre.
|
||||
let c = centroid(&f15, |p| bluish(p) || yellowish(p)).unwrap();
|
||||
assert!((c.0 - 80.0).abs() < 12.0 && (c.1 - 80.0).abs() < 12.0, "three copies balance around the centre: {c:?}");
|
||||
// The null's rotation turns the mark.
|
||||
let a = centroid(&f05, yellowish).unwrap();
|
||||
let b = centroid(&f15, yellowish).unwrap();
|
||||
assert!((a.0 - b.0).abs() + (a.1 - b.1).abs() > 2.0, "the parent's rotation moves the children: {a:?} {b:?}");
|
||||
|
||||
// Lottie out and back in: the same frames.
|
||||
let path = qa.path("logo.json");
|
||||
let ex = qa.exec("file.exportLottie", json!({"comp": "Logo", "path": path}));
|
||||
assert!(ex["bytes"].as_u64().unwrap() > 500, "{ex}");
|
||||
let im = qa.exec("file.importLottie", json!({"path": path}));
|
||||
let lc = im["comp"].clone();
|
||||
assert!(lc.is_u64(), "{im}");
|
||||
for (t, orig) in [(0.0, &f0), (0.5, &f05), (1.5, &f15)] {
|
||||
let back = qa.frame(Some(lc.clone()), t);
|
||||
let d = mean_diff(orig, &back);
|
||||
assert!(d < 1.5, "Lottie round trip at {t} s differs by {d}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Scenario 4 — tracking and roto on synthetic footage: a point track applied to a null, Warp
|
||||
//! Stabilizer on a shaking plate, Roto Brush propagation and Content-Aware Fill, each checked
|
||||
//! numerically against the known motion.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::harness::{Qa, luma};
|
||||
|
||||
const N: u32 = 12;
|
||||
|
||||
/// Deterministic texture (value noise) so trackers have features to lock onto.
|
||||
fn texture(x: i64, y: i64) -> u8 {
|
||||
let h = |x: i64, y: i64| {
|
||||
let mut v = (x.wrapping_mul(374_761_393) ^ y.wrapping_mul(668_265_263)) as u64;
|
||||
v = (v ^ (v >> 13)).wrapping_mul(1_274_126_177);
|
||||
((v ^ (v >> 16)) & 0xff) as u8
|
||||
};
|
||||
let (cx, cy) = (x.div_euclid(6), y.div_euclid(6));
|
||||
40 + h(cx, cy) / 3
|
||||
}
|
||||
|
||||
/// Where the square is on frame `f`.
|
||||
fn square_center(f: u32) -> (f64, f64) {
|
||||
(40.0 + f as f64 * 6.0, 45.0 + f as f64 * 1.0)
|
||||
}
|
||||
|
||||
/// A textured plate with a white, black-dotted square moving right; or (`shake`) the plate
|
||||
/// itself jittering by a known offset per frame.
|
||||
fn write_plate(qa: &Qa, dir: &str, shake: bool) -> String {
|
||||
std::fs::create_dir_all(qa.dir.join(dir)).unwrap();
|
||||
for f in 0..N {
|
||||
let (sx, sy) = if shake { shake_offset(f) } else { (0, 0) };
|
||||
let (cx, cy) = square_center(f);
|
||||
let img = image::RgbaImage::from_fn(160, 90, |x, y| {
|
||||
let (px, py) = (x as i64 - sx, y as i64 - sy);
|
||||
if !shake && (x as f64 - cx).abs() < 10.0 && (y as f64 - cy).abs() < 10.0 {
|
||||
// The object: white with a dark centre dot (a trackable feature).
|
||||
let dot = (x as f64 - cx).abs() < 3.0 && (y as f64 - cy).abs() < 3.0;
|
||||
return if dot { image::Rgba([20, 20, 20, 255]) } else { image::Rgba([250, 250, 250, 255]) };
|
||||
}
|
||||
let v = texture(px, py);
|
||||
image::Rgba([v, v / 2 + 30, 255 - v, 255])
|
||||
});
|
||||
img.save(qa.dir.join(format!("{dir}/f_{f:03}.png"))).unwrap();
|
||||
}
|
||||
qa.path(&format!("{dir}/f_000.png"))
|
||||
}
|
||||
|
||||
fn shake_offset(f: u32) -> (i64, i64) {
|
||||
[(0, 0), (3, -2), (-2, 3), (4, 1), (-3, -3), (2, 2), (-4, 0), (1, -4), (3, 3), (-2, -1), (0, 4), (-3, 2)][f as usize]
|
||||
}
|
||||
|
||||
/// Import a sequence at 12 fps and make a comp of it; returns (comp, layer).
|
||||
fn plate_comp(qa: &mut Qa, first: &str, name: &str) -> (Value, Value) {
|
||||
let item = qa.exec("file.import", json!({"paths": [first]}))["items"][0].clone();
|
||||
qa.exec("file.interpretFootage", json!({"items": [item.clone()], "frameRate": 12}));
|
||||
let comp = qa.exec("comp.new", json!({"name": name, "width": 160, "height": 90, "frameRate": 12, "duration": 1}))["comp"].clone();
|
||||
let layer = qa.exec("layer.addItem", json!({"item": item}))["layer"].clone();
|
||||
(comp, layer)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_track_to_null() {
|
||||
let mut qa = Qa::new("track");
|
||||
let first = write_plate(&qa, "plate", false);
|
||||
let (_, plate) = plate_comp(&mut qa, &first, "Track");
|
||||
let follow = qa.exec("layer.newNull", json!({"name": "Follow"}))["layer"].clone();
|
||||
// Track the plate; the Motion Target is the null.
|
||||
qa.exec("track.new", json!({"layer": plate.clone(), "kind": "transform", "target": follow.clone()}));
|
||||
let (cx, cy) = square_center(0);
|
||||
qa.exec("track.setPoint", json!({"layer": plate.clone(), "point": 1, "center": [cx, cy], "featureSize": [24, 24], "searchSize": [48, 48], "time": 0}));
|
||||
qa.exec("time.set", json!({"time": 0}));
|
||||
qa.exec("track.analyze", json!({"layer": plate.clone(), "direction": "forward", "wait": true}));
|
||||
let st = qa.exec("track.status", json!({"layer": plate.clone()}));
|
||||
assert!(st.to_string().contains("featureCenter") || st.is_object(), "{st}");
|
||||
qa.exec("track.apply", json!({"layer": plate.clone(), "dimensions": "xy"}));
|
||||
// The null now follows the square, frame by frame, to within a pixel.
|
||||
for f in [0u32, 5, 11] {
|
||||
let t = f as f64 / 12.0;
|
||||
let p = qa.tool("get_property", json!({"layer": follow.clone(), "path": "transform/position", "time": t}));
|
||||
let v = p["value"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect::<Vec<_>>();
|
||||
let (ex, ey) = square_center(f);
|
||||
assert!((v[0] - ex).abs() < 1.0 && (v[1] - ey).abs() < 1.0, "frame {f}: null at {v:?}, square at ({ex}, {ey})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warp_stabilizer_steadies_a_shaking_plate() {
|
||||
let mut qa = Qa::new("warp");
|
||||
let first = write_plate(&qa, "shake", true);
|
||||
let (_, plate) = plate_comp(&mut qa, &first, "Shaky");
|
||||
let jitter = |qa: &mut Qa| {
|
||||
// Mean frame-to-frame difference over the middle of the frame (borders may be cropped
|
||||
// or scaled).
|
||||
let frames: Vec<_> = (0..N).map(|f| qa.frame(None, f as f64 / 12.0)).collect();
|
||||
let mut s = 0.0;
|
||||
for w in frames.windows(2) {
|
||||
let mut d = 0.0;
|
||||
for y in 25..65 {
|
||||
for x in 40..120 {
|
||||
d += (luma(w[0].get_pixel(x, y)) - luma(w[1].get_pixel(x, y))).abs();
|
||||
}
|
||||
}
|
||||
s += d / (40.0 * 80.0);
|
||||
}
|
||||
s / (N - 1) as f64
|
||||
};
|
||||
let before = jitter(&mut qa);
|
||||
qa.exec("track.warpStabilizer", json!({"layer": plate.clone(), "wait": true}));
|
||||
qa.tool("set_property", json!({"layer": plate.clone(), "path": "effects/#1/stabilization/result", "value": 1}));
|
||||
let st = qa.exec("warp.status", json!({"layer": plate.clone()}));
|
||||
assert_eq!(st["analyzed"], true, "{st}");
|
||||
let after = jitter(&mut qa);
|
||||
assert!(after < before * 0.5, "No Motion stabilisation removes most of the shake: {before} → {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roto_brush_propagates_and_content_aware_fill_removes_the_object() {
|
||||
let mut qa = Qa::new("roto");
|
||||
let first = write_plate(&qa, "plate", false);
|
||||
let (_, plate) = plate_comp(&mut qa, &first, "Roto");
|
||||
// Paint the square as foreground and the plate around it as background on frame 0.
|
||||
let (cx, cy) = square_center(0);
|
||||
qa.exec(
|
||||
"roto.stroke",
|
||||
json!({"layer": plate.clone(), "kind": "fg", "frame": 0, "radius": 3, "points": [[cx - 5.0, cy - 5.0], [cx + 5.0, cy + 5.0], [cx - 5.0, cy + 5.0]]}),
|
||||
);
|
||||
qa.exec(
|
||||
"roto.stroke",
|
||||
json!({"layer": plate.clone(), "kind": "bg", "frame": 0, "radius": 4, "points": [[5, 5], [150, 5], [150, 85], [5, 85], [5, 5], [cx + 25.0, cy]]}),
|
||||
);
|
||||
qa.exec("roto.propagate", json!({"layer": plate.clone(), "direction": "forward", "to": N - 1, "wait": true}));
|
||||
for f in [0u32, 6, 11] {
|
||||
let st = qa.exec("roto.status", json!({"layer": plate.clone(), "frame": f, "compute": true}));
|
||||
let (ex, ey) = square_center(f);
|
||||
let c = st["centroid"].as_array().unwrap_or_else(|| panic!("frame {f}: {st}"));
|
||||
let (mx, my) = (c[0].as_f64().unwrap(), c[1].as_f64().unwrap());
|
||||
assert!((mx - ex).abs() < 3.0 && (my - ey).abs() < 3.0, "frame {f}: matte centroid ({mx}, {my}) vs square ({ex}, {ey})");
|
||||
let area = st["area"].as_f64().unwrap();
|
||||
assert!((area - 400.0).abs() < 160.0, "frame {f}: matte area {area} ≈ 20×20");
|
||||
}
|
||||
|
||||
// Content-Aware Fill: a mask around the object's path, Object fill, then the square is gone.
|
||||
let roto_fx = qa.exec("effect.remove", json!({"layer": plate.clone(), "effect": 1}));
|
||||
let _ = roto_fx;
|
||||
qa.exec("layer.addMask", json!({"layer": plate.clone(), "shape": "rect", "rect": [20, 25, 120, 40], "mode": "Subtract"}));
|
||||
let caf =
|
||||
qa.exec("layer.newContentAwareFill", json!({"layer": plate.clone(), "method": "object", "range": "entire", "outputDir": qa.path("caf"), "wait": true}));
|
||||
assert!(caf["layer"].is_u64() || caf.is_object(), "{caf}");
|
||||
for f in [0u32, 6] {
|
||||
let img = qa.frame(None, f as f64 / 12.0);
|
||||
let (ex, ey) = square_center(f);
|
||||
let p = img.get_pixel(ex as u32 + 6, ey as u32 + 6);
|
||||
assert!(luma(p) < 200.0, "frame {f}: the white square is filled with plate texture: {p:?}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user