M5.16: Key Light: keyer eyedroppers pick from the effect input (effect.pickColor); "keylight" search
- effect.pickColor {effect, param|prop, x, y (layer px), average?}: the colour of the effect's
input at a point, set on the parameter (one undo step). Keying effects' Effect Controls
eyedroppers use it, since the shown frame is already keyed; Ctrl/Cmd+click averages 5x5.
- effects::aliases / name_matches: Effects & Presets and effect.list (MCP list_effects) find
Key Light by After Effects' name ("Keylight (1.2)").
- End-to-end test: a green-screen plate with an uneven screen, spill and soft edges keyed via
effect.apply "Keylight (1.2)", pick, Clip Black / White and a render; UI eyedropper test.
- Docs: parity, agents (green-screen recipe).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
47f2a5a3e6
commit
73b2607c9a
@@ -4,7 +4,7 @@ use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{GroupKind, LayerId, PropGroup, Uid};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, b_p, bad, has_layers, layer_mut, layers_p, str_p};
|
||||
use super::{CommandSpec, b_p, bad, f_p, has_layers, layer_mut, layers_p, str_p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
/// `effect.plugins.list`: the registered plug-in effects (WebAssembly or Rust).
|
||||
@@ -132,6 +132,52 @@ fn find_fx(s: &Session, p: &Value, cmd: &str) -> Result<(effectcraft_project::It
|
||||
Ok((cid, lid, g.uid))
|
||||
}
|
||||
|
||||
/// A colour parameter's eyedropper on a keyer (Effect Controls): the colour of the effect's input
|
||||
/// (the layer's pixels before this effect, so a keyed screen can still be picked) at a
|
||||
/// layer-space point, set on the parameter. `average` takes the 5 × 5 pixels around it.
|
||||
fn pick_color(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "effect.pickColor";
|
||||
let (cid, lid, fx_uid) = find_fx(s, p, cmd)?;
|
||||
let (Some(x), Some(y)) = (f_p(p, "x"), f_p(p, "y")) else { return Err(bad(cmd, "missing `x` / `y` (layer pixels)")) };
|
||||
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
|
||||
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
|
||||
let fx = layer.effects().ok_or_else(|| bad(cmd, "no effects"))?;
|
||||
let index = fx.groups().position(|g| g.uid == fx_uid).ok_or_else(|| bad(cmd, "no such effect"))?;
|
||||
let g = fx.groups().nth(index).ok_or_else(|| bad(cmd, "no such effect"))?;
|
||||
let prop = match (p.get("prop").and_then(Value::as_u64), str_p(p, "param")) {
|
||||
(Some(uid), _) => g.find(uid),
|
||||
(None, Some(path)) => g.prop(path),
|
||||
_ => return Err(bad(cmd, "missing `param` (e.g. `screenColour`) or `prop` (uid)")),
|
||||
}
|
||||
.filter(|pr| pr.ui == effectcraft_project::ParamUi::Color)
|
||||
.ok_or_else(|| bad(cmd, "not a colour parameter of this effect"))?;
|
||||
let t = super::time_p(s, p, Some(comp));
|
||||
let ctx = effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref(), footage: None };
|
||||
let mut r = effectcraft_render::Renderer::new(&s.project, &*s.footage, effectcraft_render::RenderOpts::default());
|
||||
r.expr = s.expr.as_deref();
|
||||
r.cache = Some(&s.layer_cache);
|
||||
let buf = r.layer_input(&ctx, layer, index).ok_or_else(|| bad(cmd, "this layer has no pixels"))?;
|
||||
let (px, py) = buf.to_px([x, y]);
|
||||
let (cx, cy) = (px.floor() as i64, py.floor() as i64);
|
||||
let rad = if b_p(p, "average") == Some(true) { 2 } else { 0 };
|
||||
let mut sum = [0.0f32; 4];
|
||||
for yy in cy.saturating_sub(rad)..=cy.saturating_add(rad) {
|
||||
for xx in cx.saturating_sub(rad)..=cx.saturating_add(rad) {
|
||||
// Outside the layer reads as transparent.
|
||||
let c = buf.img.get(xx, yy);
|
||||
(0..4).for_each(|i| sum[i] += c[i]);
|
||||
}
|
||||
}
|
||||
if sum[3] <= 1e-6 {
|
||||
return Err(bad(cmd, "nothing to sample there (transparent or outside the layer)"));
|
||||
}
|
||||
// Straight colour of the (averaged) premultiplied pixels.
|
||||
let color: Vec<f64> = (0..3).map(|i| (sum[i] / sum[3]).clamp(0.0, 1.0) as f64).chain([1.0]).collect();
|
||||
let uid = prop.uid;
|
||||
s.execute("prop.set", json!({"comp": cid.0, "layer": lid.0, "prop": uid, "value": color}))?;
|
||||
Ok(json!({"prop": uid, "color": color}))
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cid = super::comp_id(s, p)?;
|
||||
let fx = effects_p(s, p, "effect.remove")?;
|
||||
@@ -355,11 +401,11 @@ fn last(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let filter = str_p(p, "filter").map(str::to_ascii_lowercase);
|
||||
let filter = str_p(p, "filter").map(str::to_lowercase);
|
||||
let v: Vec<Value> = effectcraft_effects::all()
|
||||
.into_iter()
|
||||
.filter(|e| {
|
||||
filter.as_ref().is_none_or(|f| e.name.to_ascii_lowercase().contains(f) || e.id.contains(f.as_str()) || e.category.to_ascii_lowercase().contains(f))
|
||||
filter.as_ref().is_none_or(|f| effectcraft_effects::name_matches(e, f) || e.id.contains(f.as_str()) || e.category.to_ascii_lowercase().contains(f))
|
||||
})
|
||||
.map(|e| {
|
||||
json!({"id": e.id, "name": e.name, "category": e.category, "gpu": e.gpu, "float": e.float, "params": e.params.iter().map(|p| json!({"id": p.id, "name": p.name, "default": p.default.to_json()})).collect::<Vec<_>>()})
|
||||
@@ -371,6 +417,15 @@ fn list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("effect.apply", "Apply Effect", [], None, "{effect: id|name (e.g. Gaussian Blur), layers?}", has_layers, apply),
|
||||
cmd!(
|
||||
"effect.pickColor",
|
||||
"Pick Effect Colour",
|
||||
[],
|
||||
None,
|
||||
"{layer?, effect?: index|uid|name, param: id (e.g. screenColour) | prop: uid, x, y (layer px), average?: bool (5×5), time?} — the colour of the effect's input there",
|
||||
has_layers,
|
||||
pick_color
|
||||
),
|
||||
cmd!("effect.applyLast", "Last Effect", ["Effect"], Some("Cmd+Alt+Shift+E"), "{layers?}", has_layers, last),
|
||||
cmd!("effect.removeAll", "Remove All", ["Effect"], Some("Cmd+Shift+E"), "{layers?}", has_layers, remove_all),
|
||||
cmd!("effect.remove", "Remove Effect", [], None, "{layer?, effect: index|uid|name}", has_layers, remove),
|
||||
|
||||
@@ -954,6 +954,8 @@ mod tests_fidelity;
|
||||
#[cfg(test)]
|
||||
mod tests_frame_export;
|
||||
#[cfg(test)]
|
||||
mod tests_keylight;
|
||||
#[cfg(test)]
|
||||
mod tests_lottie;
|
||||
#[cfg(test)]
|
||||
mod tests_m137;
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Key Light end to end: a green-screen plate (uneven screen, a subject with green spill and a
|
||||
//! soft edge) keyed through the commands an agent uses: `effect.apply` by its After Effects name,
|
||||
//! `effect.pickColor` on the screen (the effect's input, as the eyedropper does) and a render.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use effectcraft_project::{Footage, FootageKind, ItemId};
|
||||
use effectcraft_raster::Image;
|
||||
use effectcraft_time::{FrameRate, Tick};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::Session;
|
||||
use crate::render::{FootageSource, RenderOpts};
|
||||
|
||||
const W: u32 = 96;
|
||||
const H: u32 = 64;
|
||||
const SKIN: [f32; 3] = [0.86, 0.62, 0.52];
|
||||
|
||||
/// The plate's straight colour and alpha (opaque everywhere) at a pixel.
|
||||
fn plate(x: u32, y: u32) -> [f32; 3] {
|
||||
// Screen: a slightly uneven, noisy green.
|
||||
let noise = (((x * 7919 + y * 104_729) % 97) as f32 / 97.0 - 0.5) * 0.02;
|
||||
let screen = [0.18 + noise, 0.66 + (x as f32 / W as f32 - 0.5) * 0.04 + noise, 0.30 - noise];
|
||||
let r = ((x as f32 + 0.5 - 48.0).powi(2) + (y as f32 + 0.5 - 32.0).powi(2)).sqrt();
|
||||
// Subject: skin, with green spill in its outer 3 px and a 3 px soft edge.
|
||||
let mut subject = SKIN;
|
||||
if r > 13.0 {
|
||||
subject[1] += 0.12;
|
||||
}
|
||||
let a = ((19.0 - r) / 3.0).clamp(0.0, 1.0);
|
||||
[0, 1, 2].map(|i| subject[i] * a + screen[i] * (1.0 - a))
|
||||
}
|
||||
|
||||
struct Plate;
|
||||
|
||||
impl FootageSource for Plate {
|
||||
fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option<Arc<Image>> {
|
||||
let mut img = Image::new(W, H);
|
||||
for y in 0..H {
|
||||
for x in 0..W {
|
||||
let c = plate(x, y);
|
||||
img.set(x, y, [c[0], c[1], c[2], 1.0]);
|
||||
}
|
||||
}
|
||||
Some(Arc::new(img))
|
||||
}
|
||||
}
|
||||
|
||||
struct Probe;
|
||||
impl crate::Importer for Probe {
|
||||
fn probe(&self, path: &str) -> Result<Footage, String> {
|
||||
Ok(Footage {
|
||||
path: path.into(),
|
||||
kind: FootageKind::Still,
|
||||
width: W,
|
||||
height: H,
|
||||
has_video: true,
|
||||
frame_rate: FrameRate::from_f64(24.0),
|
||||
duration: Tick::ZERO,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn keyed() -> (Session, ItemId) {
|
||||
let mut s = Session { footage: Arc::new(Plate), importer: Some(Arc::new(Probe)), ..Default::default() };
|
||||
let item = s.execute("file.import", json!({"paths": ["/plates/greenscreen.png"]})).unwrap()["items"][0].as_u64().unwrap();
|
||||
s.execute("comp.new", json!({"name": "Key", "width": W, "height": H, "frameRate": 24, "duration": 1})).unwrap();
|
||||
let c = s.active_comp_id().unwrap();
|
||||
s.execute("layer.addItem", json!({"item": item})).unwrap();
|
||||
// After Effects' name finds it; MCP's add_effect / list_effects go through the same lookup.
|
||||
let r = s.execute_checked("effect.apply", json!({"effect": "Keylight (1.2)"})).unwrap();
|
||||
assert_eq!(r["effect"], "ec.keying.keylight");
|
||||
(s, c)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_light_removes_a_green_screen() {
|
||||
let (mut s, c) = keyed();
|
||||
let steps = s.history.undo.len();
|
||||
// The default screen colour (pure green) already keys the screen, so the shown frame is
|
||||
// transparent there; the eyedropper samples the effect's input instead.
|
||||
let picked = s.execute_checked("effect.pickColor", json!({"effect": 1, "param": "screenColour", "x": 6, "y": 6, "average": true})).unwrap();
|
||||
let col: Vec<f64> = picked["color"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
|
||||
let want = plate(6, 6);
|
||||
assert!((0..3).all(|i| (col[i] - want[i] as f64).abs() < 0.02), "{col:?} vs {want:?}");
|
||||
let tree = s.execute("layer.tree", json!({})).unwrap().to_string();
|
||||
assert!(tree.contains("Screen Colour"), "{tree}");
|
||||
// One undo step.
|
||||
assert_eq!(s.history.undo.len(), steps + 1);
|
||||
// Clean the matte as one does in Screen Matte view: Clip Black for the uneven screen, Clip
|
||||
// White for the spill's partial transparency.
|
||||
for (path, v) in [("effects/#1/screenMatte/clipBlack", 10), ("effects/#1/screenMatte/clipWhite", 85)] {
|
||||
s.execute_checked("prop.set", json!({"path": path, "value": v})).unwrap();
|
||||
}
|
||||
|
||||
let img = s.render(c, Tick::ZERO, RenderOpts::default());
|
||||
let px = |x, y| img.get(x, y);
|
||||
// The whole screen goes (corners, both ends of the gradient, noise).
|
||||
for (x, y) in [(1, 1), (94, 1), (1, 62), (94, 62), (20, 32), (76, 32)] {
|
||||
assert!(px(x, y)[3] < 0.03, "screen at {x},{y}: {:?}", px(x, y));
|
||||
}
|
||||
// The subject stays, with its colour.
|
||||
let fg = px(48, 32);
|
||||
assert!(fg[3] > 0.99 && (0..3).all(|i| (fg[i] - SKIN[i]).abs() < 0.02), "{fg:?}");
|
||||
// Spill on the subject's edge is suppressed: no green cast left.
|
||||
let sp = px(48, 32 - 14);
|
||||
assert!(sp[3] > 0.99 && sp[1] <= 0.5 * (sp[0] + sp[2]) + 0.01, "spill {sp:?}");
|
||||
// The soft edge keeps partial alpha, and its recovered colour has no green fringe.
|
||||
let e = px(48, 32 - 18);
|
||||
assert!(e[3] > 0.15 && e[3] < 0.85, "edge {e:?}");
|
||||
let a = e[3];
|
||||
assert!(e[1] / a <= 0.5 * (e[0] + e[2]) / a + 0.02, "edge fringe {e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pick_color_rejects_bad_targets_and_screen_matte_view_shows_the_key() {
|
||||
let (mut s, c) = keyed();
|
||||
// Not a colour parameter / outside the layer.
|
||||
assert!(s.execute_checked("effect.pickColor", json!({"effect": 1, "param": "screenGain", "x": 6, "y": 6})).is_err());
|
||||
assert!(s.execute_checked("effect.pickColor", json!({"effect": 1, "param": "screenColour", "x": -50, "y": 6})).is_err());
|
||||
assert!(s.execute_checked("effect.pickColor", json!({"effect": 1, "param": "screenColour", "x": 1e300, "y": -1e300, "average": true})).is_err());
|
||||
assert!(s.execute_checked("effect.pickColor", json!({"effect": 1, "param": "screenColour"})).is_err());
|
||||
s.execute_checked("effect.pickColor", json!({"effect": 1, "param": "screenColour", "x": 90, "y": 60})).unwrap();
|
||||
// View ▸ Screen Matte: black screen (once Clip Black takes the uneven screen), white subject.
|
||||
for (path, v) in [("effects/#1/view", 4), ("effects/#1/screenMatte/clipBlack", 25)] {
|
||||
s.execute_checked("prop.set", json!({"path": path, "value": v})).unwrap();
|
||||
}
|
||||
let img = s.render(c, Tick::ZERO, RenderOpts::default());
|
||||
assert!(img.get(2, 2)[0] < 0.03 && img.get(48, 32)[0] > 0.97, "{:?} {:?}", img.get(2, 2), img.get(48, 32));
|
||||
// The Effects & Presets / list_effects search finds it by After Effects' name too.
|
||||
let list = s.execute("effect.list", json!({"filter": "Keylight (1.2)"})).unwrap();
|
||||
assert_eq!(list.as_array().map(|a| a.len()), Some(1), "{list}");
|
||||
assert_eq!(list[0]["id"], "ec.keying.keylight");
|
||||
}
|
||||
Reference in New Issue
Block a user