Merge main into M13.4 (codec completion)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-03 09:24:05 -04:00
co-authored by Claude Opus 5.5
181 changed files with 28985 additions and 1712 deletions
+285
View File
@@ -0,0 +1,285 @@
//! Align panel: `layer.align {edge, to}` and `layer.distribute {mode}`.
//!
//! Layers are aligned by their content bounds in comp space (source size, text glyphs, shape
//! contents through the layer's transform and its parents'). Each layer moves by a comp-space
//! offset that is converted into its parent's space before it is added to Position (Separate
//! Dimensions writes X/Y Position), at the current time (a key when Position is animated). All
//! moves are one undo step.
use effectcraft_geom::{Mat4, Vec3};
use effectcraft_keyframe::Value as KValue;
use effectcraft_project::{ItemId, LayerId};
use effectcraft_render::EvalCtx;
use serde_json::{Value, json};
use super::{CommandSpec, bad, has_layers, layer_mut, layers_p, str_p};
use crate::{EngineError, Result, Session, cmd};
/// A layer's comp-space bounds and how a comp-space offset maps into its Position.
struct Placed {
id: LayerId,
/// `[x0, y0, x1, y1]` in comp space.
b: [f64; 4],
/// Comp space → the parent's space (the space Position lives in).
to_parent: Mat4,
}
fn placed(s: &Session, cid: ItemId, ids: &[LayerId]) -> Result<Vec<Placed>> {
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let ctx = EvalCtx { footage: Some(s.footage.as_ref()), expr: s.expr.as_deref(), ..EvalCtx::new(&s.project, cid, comp, s.time()) };
let mut out = vec![];
for &id in ids {
let Some(l) = comp.layer(id) else { continue };
if l.transform().is_none() {
continue;
}
let Some(b) = effectcraft_render::content_bounds(&ctx, l) else { continue };
let w = ctx.world_matrix(l);
let pts = [[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]].map(|p| w.apply(Vec3::from([p[0], p[1], 0.0])));
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for p in pts {
x0 = x0.min(p.x);
y0 = y0.min(p.y);
x1 = x1.max(p.x);
y1 = y1.max(p.y);
}
// Parent chain: world(layer) = local(pn) ⋯ local(p1) · local(layer).
let mut par = Mat4::IDENTITY;
let mut cur = l.parent;
let mut guard = 0;
while let Some(pid) = cur {
guard += 1;
let Some(p) = comp.layer(pid).filter(|_| guard < 64) else { break };
par = ctx.local_matrix(p) * par;
cur = p.parent;
}
let to_parent = par.inverse().unwrap_or(Mat4::IDENTITY);
out.push(Placed { id, b: [x0, y0, x1, y1], to_parent });
}
Ok(out)
}
/// Move layers by comp-space offsets, as one undo step.
fn apply_moves(s: &mut Session, cid: ItemId, label: &str, moves: Vec<(LayerId, Mat4, [f64; 2])>) -> Result<Value> {
let t = s.time();
let moved: Vec<u64> = moves.iter().filter(|m| m.2[0].abs() > 1e-9 || m.2[1].abs() > 1e-9).map(|m| m.0.0).collect();
s.edit(label, None, |proj, _| {
for (lid, to_parent, d) in &moves {
if d[0].abs() <= 1e-9 && d[1].abs() <= 1e-9 {
continue;
}
let o = to_parent.apply(Vec3::from([0.0, 0.0, 0.0]));
let q = to_parent.apply(Vec3::from([d[0], d[1], 0.0]));
let dp = [q.x - o.x, q.y - o.y, q.z - o.z];
let l = layer_mut(proj, cid, *lid)?;
let lt = l.layer_time(t);
let three = l.is_3d();
let tr = l.transform_mut().ok_or_else(|| bad("layer.align", "layer has no transform"))?;
if tr.get("positionX").is_some() {
let dims = if three { 3 } else { 2 };
for (k, m) in ["positionX", "positionY", "positionZ"].iter().enumerate().take(dims) {
if let Some(pr) = tr.get_mut(m) {
let v = pr.value_at(lt).as_f64() + dp[k];
pr.set_value_at(lt, KValue::Scalar(v));
}
}
} else if let Some(pr) = tr.get_mut("position") {
let cur = pr.value_at(lt);
let a = cur.to_json();
let get = |k: usize| a.get(k).and_then(Value::as_f64).unwrap_or(0.0);
let nv = json!([get(0) + dp[0], get(1) + dp[1], get(2) + if three { dp[2] } else { 0.0 }]);
if let Some(v) = cur.coerce_json(&nv) {
pr.set_value_at(lt, v);
}
}
}
Ok(())
})?;
Ok(json!({"moved": moved}))
}
const EDGES: &str = "left|hcenter|right|top|vcenter|bottom";
/// The coordinate of an edge (or centre) of bounds; `true` for horizontal edges.
fn edge_of(b: &[f64; 4], edge: &str) -> Option<(f64, bool)> {
Some(match edge {
"left" => (b[0], true),
"hcenter" | "horizontalCenter" => ((b[0] + b[2]) * 0.5, true),
"right" => (b[2], true),
"top" => (b[1], false),
"vcenter" | "verticalCenter" => ((b[1] + b[3]) * 0.5, false),
"bottom" => (b[3], false),
_ => return None,
})
}
fn align(s: &mut Session, p: &Value) -> Result<Value> {
let c = "layer.align";
let edge = str_p(p, "edge").ok_or_else(|| bad(c, format!("missing `edge` ({EDGES})")))?;
let to = str_p(p, "to").unwrap_or("composition");
let (cid, ids) = layers_p(s, p)?;
let items = placed(s, cid, &ids)?;
if items.is_empty() {
return Err(bad(c, "no layers with bounds to align"));
}
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let target: [f64; 4] = match to {
"composition" | "comp" => [0.0, 0.0, comp.width as f64, comp.height as f64],
"selection" => {
if items.len() < 2 {
return Err(bad(c, "aligning to the selection needs two or more layers"));
}
items.iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |a, it| {
[a[0].min(it.b[0]), a[1].min(it.b[1]), a[2].max(it.b[2]), a[3].max(it.b[3])]
})
}
x => return Err(bad(c, format!("unknown `to` `{x}` (selection|composition)"))),
};
let (goal, horiz) = edge_of(&target, edge).ok_or_else(|| bad(c, format!("unknown edge `{edge}` ({EDGES})")))?;
let moves = items
.into_iter()
.map(|it| {
let (v, _) = edge_of(&it.b, edge).unwrap_or((goal, horiz));
let d = if horiz { [goal - v, 0.0] } else { [0.0, goal - v] };
(it.id, it.to_parent, d)
})
.collect();
apply_moves(s, cid, "Align Layers", moves)
}
fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
let c = "layer.distribute";
let mode = str_p(p, "mode").or(str_p(p, "edge")).ok_or_else(|| bad(c, format!("missing `mode` ({EDGES})")))?;
let (cid, ids) = layers_p(s, p)?;
let mut items = placed(s, cid, &ids)?;
if items.len() < 3 {
return Err(bad(c, "distributing needs three or more layers"));
}
edge_of(&items[0].b, mode).ok_or_else(|| bad(c, format!("unknown mode `{mode}` ({EDGES})")))?;
let key = |it: &Placed| edge_of(&it.b, mode).map_or(0.0, |e| e.0);
items.sort_by(|a, b| key(a).total_cmp(&key(b)));
let (first, last) = (key(&items[0]), key(&items[items.len() - 1]));
let n = items.len() - 1;
let horiz = edge_of(&items[0].b, mode).is_some_and(|e| e.1);
let moves = items
.iter()
.enumerate()
.map(|(i, it)| {
let goal = first + (last - first) * i as f64 / n as f64;
let dv = goal - key(it);
(it.id, it.to_parent, if horiz { [dv, 0.0] } else { [0.0, dv] })
})
.collect();
apply_moves(s, cid, "Distribute Layers", moves)
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"layer.align",
"Align Layers",
[],
None,
"{edge: left|hcenter|right|top|vcenter|bottom, to?: composition|selection (default composition), layers?}",
has_layers,
align
),
cmd!(
"layer.distribute",
"Distribute Layers",
[],
None,
"{mode: left|hcenter|right|top|vcenter|bottom (edges or centres), layers?}",
has_layers,
distribute
),
]
}
#[cfg(test)]
mod tests {
use super::*;
fn session() -> Session {
let mut s = Session::default();
s.execute("comp.new", json!({"width": 400, "height": 300, "duration": 2})).unwrap();
s
}
fn solid(s: &mut Session, name: &str, w: u32, h: u32, pos: [f64; 2]) -> u64 {
let id = s.execute("layer.newSolid", json!({"name": name, "width": w, "height": h})).unwrap()["layer"].as_u64().unwrap();
s.execute("prop.set", json!({"layer": id, "path": "transform/position", "value": [pos[0], pos[1], 0.0]})).unwrap();
id
}
fn bounds(s: &Session, id: u64) -> [f64; 4] {
let cid = s.active_comp_id().unwrap();
placed(s, cid, &[LayerId(id)]).unwrap()[0].b
}
#[test]
fn align_to_composition_and_selection_is_one_undo_step() {
let mut s = session();
let a = solid(&mut s, "A", 50, 40, [100.0, 100.0]);
let b = solid(&mut s, "B", 80, 20, [250.0, 180.0]);
s.execute("layer.align", json!({"edge": "left", "layers": [a, b]})).unwrap();
assert!(bounds(&s, a)[0].abs() < 1e-6 && bounds(&s, b)[0].abs() < 1e-6);
// One step undoes both.
s.execute("edit.undo", json!({})).unwrap();
assert!((bounds(&s, a)[0] - 75.0).abs() < 1e-6);
assert!((bounds(&s, b)[0] - 210.0).abs() < 1e-6);
s.execute("layer.align", json!({"edge": "bottom", "to": "composition", "layers": [a, b]})).unwrap();
assert!((bounds(&s, a)[3] - 300.0).abs() < 1e-6 && (bounds(&s, b)[3] - 300.0).abs() < 1e-6);
s.execute("edit.undo", json!({})).unwrap();
// Selection: to the selection's right edge (B's) and vertical centre.
s.execute("layer.align", json!({"edge": "right", "to": "selection", "layers": [a, b]})).unwrap();
assert!((bounds(&s, a)[2] - 290.0).abs() < 1e-6 && (bounds(&s, b)[2] - 290.0).abs() < 1e-6);
s.execute("layer.align", json!({"edge": "vcenter", "to": "selection", "layers": [a, b]})).unwrap();
let (ca, cb) = (bounds(&s, a), bounds(&s, b));
assert!(((ca[1] + ca[3]) / 2.0 - (cb[1] + cb[3]) / 2.0).abs() < 1e-6);
assert!(s.execute("layer.align", json!({"edge": "left", "to": "selection", "layers": [a]})).is_err());
assert!(s.execute("layer.align", json!({"edge": "diagonal", "layers": [a]})).is_err());
}
#[test]
fn align_honours_parent_scale_and_rotation() {
let mut s = session();
let parent = solid(&mut s, "P", 10, 10, [200.0, 150.0]);
s.execute("prop.set", json!({"layer": parent, "path": "transform/scale", "value": [200.0, 200.0, 100.0]})).unwrap();
s.execute("prop.set", json!({"layer": parent, "path": "transform/rotation", "value": 90.0})).unwrap();
let child = solid(&mut s, "C", 20, 10, [30.0, 10.0]);
s.execute("layer.setParent", json!({"layers": [child], "parent": parent})).unwrap();
s.execute("layer.align", json!({"edge": "top", "layers": [child]})).unwrap();
assert!(bounds(&s, child)[1].abs() < 1e-6, "{:?}", bounds(&s, child));
s.execute("layer.align", json!({"edge": "hcenter", "layers": [child]})).unwrap();
let b = bounds(&s, child);
assert!(((b[0] + b[2]) / 2.0 - 200.0).abs() < 1e-6 && b[1].abs() < 1e-6);
}
#[test]
fn distribute_edges_and_centres() {
let mut s = session();
let a = solid(&mut s, "A", 20, 20, [50.0, 50.0]);
let b = solid(&mut s, "B", 60, 20, [90.0, 100.0]);
let c = solid(&mut s, "C", 20, 20, [350.0, 200.0]);
s.execute("layer.distribute", json!({"mode": "hcenter", "layers": [a, b, c]})).unwrap();
let cx = |id| {
let b = bounds(&s, id);
(b[0] + b[2]) / 2.0
};
assert!((cx(b) - 200.0).abs() < 1e-6 && (cx(a) - 50.0).abs() < 1e-6 && (cx(c) - 350.0).abs() < 1e-6);
s.execute("layer.distribute", json!({"mode": "top", "layers": [a, b, c]})).unwrap();
assert!((bounds(&s, b)[1] - 115.0).abs() < 1e-6);
assert!(s.execute("layer.distribute", json!({"mode": "top", "layers": [a, b]})).is_err());
}
#[test]
fn separated_position() {
let mut s = session();
let a = solid(&mut s, "A", 40, 40, [100.0, 100.0]);
s.execute("prop.separateDimensions", json!({"layer": a, "value": true})).unwrap();
assert!(s.active_comp().unwrap().layers.iter().any(|l| l.transform().is_some_and(|t| t.get("positionX").is_some())));
s.execute("layer.align", json!({"edge": "right", "layers": [a]})).unwrap();
assert!((bounds(&s, a)[2] - 400.0).abs() < 1e-6);
}
}
+4 -4
View File
@@ -395,7 +395,7 @@ fn report(s: &mut Session, p: &Value) -> Result<Value> {
/// Orientation (degrees, AE order) of a camera whose +X, +Y (down) and +Z axes point along the
/// given world directions: searched over quarter turns, which is all the cube faces need.
fn orientation_for_axes(x: Vec3, y: Vec3, z: Vec3) -> [f64; 3] {
pub(crate) fn orientation_for_axes(x: Vec3, y: Vec3, z: Vec3) -> [f64; 3] {
let mut best = ([0.0; 3], f64::MAX);
for a in 0..4 {
for b in 0..4 {
@@ -416,7 +416,7 @@ fn orientation_for_axes(x: Vec3, y: Vec3, z: Vec3) -> [f64; 3] {
/// Cube faces in the VR Converter's order (+X, −X, +Y, −Y, +Z, −Z): name, forward, right and up
/// in the VR convention (X right, Y up, Z front).
const FACES: [(&str, [f64; 3], [f64; 3], [f64; 3]); 6] = [
pub(crate) const FACES: [(&str, [f64; 3], [f64; 3], [f64; 3]); 6] = [
("Right", [1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]),
("Left", [-1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
("Top", [0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0]),
@@ -425,10 +425,10 @@ const FACES: [(&str, [f64; 3], [f64; 3], [f64; 3]); 6] = [
("Back", [0.0, 0.0, -1.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
];
/// (column, row) of each face in the 3:2 cube map.
const CELLS_3X2: [(u32, u32); 6] = [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1)];
pub(crate) const CELLS_3X2: [(u32, u32); 6] = [(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1)];
/// VR world direction → After Effects world (Y down).
fn ae(v: [f64; 3]) -> Vec3 {
pub(crate) fn ae(v: [f64; 3]) -> Vec3 {
vec3(v[0], -v[1], v[2])
}
+1 -1
View File
@@ -33,7 +33,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
continue;
};
let bytes = s.services.read_file(&f.path).map_err(|e| EngineError::Other(format!("cannot read {}: {e}", f.path)))?;
let doc = crate::vector::vector_doc(&f.path, &bytes, f.layer.as_ref())
let doc = crate::vector::vector_doc(&f.path, &bytes, f.layer.as_ref(), f.page)
.unwrap_or_else(|| Err(format!("{}: not a vector file", f.path)))
.map_err(EngineError::Other)?;
let id = s.edit("Create Shapes from Vector Layer", None, |proj, st| {
+129 -16
View File
@@ -88,6 +88,14 @@ fn add_property(s: &mut Session, p: &Value) -> Result<Value> {
let group = p.get("group").and_then(Value::as_u64);
let index = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
let rename = str_p(p, "name").map(str::to_string);
// `as`: show the property as another control (Source Text as `font`, Scale as `scale`).
let as_type = match str_p(p, "as") {
None => None,
Some(a) => {
let t = ControlType::parse(a).ok_or_else(|| bad(C, format!("as: font|scale|text|color|slider|checkbox|point|angle|dropdown, not `{a}`")))?;
Some(t)
}
};
let mut added = vec![];
for (cid, lid, uid) in &targets {
let l = s.project.comp(*cid).and_then(|c| c.layer(*lid)).ok_or(EngineError::NoComp)?;
@@ -95,20 +103,32 @@ fn add_property(s: &mut Session, p: &Value) -> Result<Value> {
if control_type(pr).is_none() {
return Err(bad(C, format!("`{}` can't be added to Essential Graphics (unsupported property type)", pr.name)));
}
if s.project.comp(*cid).and_then(|c| c.essential.as_ref()).is_some_and(|e| e.control_for(*lid, *uid).is_some()) {
// The natural control needs no `as`.
let as_type = as_type.filter(|t| control_type(pr) != Some(*t));
if let Some(t) = as_type
&& !essential::can_show_as(pr, t)
{
return Err(bad(C, format!("`{}` can't be shown as a {} control", pr.name, t.label())));
}
if s.project.comp(*cid).and_then(|c| c.essential.as_ref()).is_some_and(|e| e.control_for_as(*lid, *uid, as_type).is_some()) {
continue;
}
added.push((*cid, *lid, *uid, rename.clone().unwrap_or_else(|| pr.name.clone())));
let name = rename.clone().unwrap_or_else(|| match as_type {
Some(ControlType::Font) => format!("{} Font", l.name),
_ => pr.name.clone(),
});
added.push((*cid, *lid, *uid, name, as_type));
}
let ids = s.edit("Add Property to Essential Graphics", None, |proj, st| {
if let Some((cid, ..)) = added.first() {
st.essential_primary.get_or_insert(*cid);
}
let mut ids = vec![];
for (k, (cid, lid, uid, name)) in added.iter().enumerate() {
for (k, (cid, lid, uid, name, as_type)) in added.iter().enumerate() {
let id = proj.alloc();
let eg = eg_of(proj, *cid)?;
insert(eg, EgControl { id, name: name.clone(), kind: EgKind::Property { layer: *lid, prop: *uid } }, group, index.map(|i| i + k), C)?;
let ctl = EgControl { id, name: name.clone(), kind: EgKind::Property { layer: *lid, prop: *uid }, as_type: *as_type };
insert(eg, ctl, group, index.map(|i| i + k), C)?;
ids.push(id);
}
Ok(ids)
@@ -120,6 +140,39 @@ fn control_type(pr: &effectcraft_project::Property) -> Option<ControlType> {
essential::control_type(pr)
}
/// A Font control's value for `prop.set`: `cur` (a Source Text value) with the font family,
/// style and size from `v` (`{font?, style?, size?}` or a family name). `None` when `cur` is
/// not text.
pub fn font_value(cur: &KV, v: &Value) -> Option<Value> {
let KV::Text(doc) = cur else { return None };
let mut d = (**doc).clone();
match v {
Value::String(f) => d.font = f.clone(),
Value::Object(o) => {
if let Some(f) = o.get("font").and_then(Value::as_str) {
d.font = f.to_string();
}
if let Some(st) = o.get("style").and_then(Value::as_str) {
d.style = st.to_string();
}
if let Some(z) = o.get("size").and_then(Value::as_f64) {
d.size = z.max(0.1);
}
}
_ => return None,
}
serde_json::to_value(&d).ok()
}
/// A control's value for agents: Font controls show `{font, style, size}`, the rest the
/// property's value.
fn value_json(ty: Option<ControlType>, v: &KV) -> Value {
match (ty, v) {
(Some(ControlType::Font), KV::Text(d)) => json!({"font": d.font, "style": d.style, "size": d.size}),
_ => v.to_json(),
}
}
/// Media Replacement for a footage layer.
fn add_media(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.addMedia";
@@ -137,7 +190,7 @@ fn add_media(s: &mut Session, p: &Value) -> Result<Value> {
if eg.flat().iter().any(|c| matches!(c.kind, EgKind::Media { layer } if layer == lid)) {
return Err(bad(C, "this layer already has a Media Replacement control"));
}
insert(eg, EgControl { id, name, kind: EgKind::Media { layer: lid } }, group, None, C)?;
insert(eg, EgControl { id, name, kind: EgKind::Media { layer: lid }, as_type: None }, group, None, C)?;
Ok(id)
})?;
Ok(json!({"control": id}))
@@ -150,7 +203,7 @@ fn add_group(s: &mut Session, p: &Value) -> Result<Value> {
let id = s.edit("Add Essential Graphics Group", None, |proj, st| {
st.essential_primary.get_or_insert(cid);
let id = proj.alloc();
insert(eg_of(proj, cid)?, EgControl { id, name, kind: EgKind::Group { children: vec![] } }, None, index, "essential.addGroup")?;
insert(eg_of(proj, cid)?, EgControl { id, name, kind: EgKind::Group { children: vec![] }, as_type: None }, None, index, "essential.addGroup")?;
Ok(id)
})?;
Ok(json!({"control": id}))
@@ -163,7 +216,13 @@ fn add_comment(s: &mut Session, p: &Value) -> Result<Value> {
let id = s.edit("Add Essential Graphics Comment", None, |proj, st| {
st.essential_primary.get_or_insert(cid);
let id = proj.alloc();
insert(eg_of(proj, cid)?, EgControl { id, name: "Comment".into(), kind: EgKind::Comment { text } }, group, None, "essential.addComment")?;
insert(
eg_of(proj, cid)?,
EgControl { id, name: "Comment".into(), kind: EgKind::Comment { text }, as_type: None },
group,
None,
"essential.addComment",
)?;
Ok(id)
})?;
Ok(json!({"control": id}))
@@ -262,6 +321,35 @@ fn edit_dropdown(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"prop": uid, "items": items}))
}
/// Composition ▸ Open in Essential Graphics.
fn open_in_eg(s: &mut Session, p: &Value) -> Result<Value> {
let cid = comp_id(s, p)?;
s.state.essential_primary = Some(cid);
s.bump();
s.events.push(crate::Event::Frontend { command: "window.panel".into(), params: json!({"panel": "essentialGraphics"}) });
let name = s.project.item(cid).map(|i| i.name.clone()).unwrap_or_default();
Ok(json!({"comp": cid.0, "name": name}))
}
/// Whether a property can be exposed (`property.canAddToMotionGraphicsTemplate`).
fn can_add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.canAdd";
let (cid, lid, uid) = super::prop::prop_ref(s, p, C)?;
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
let pr = l.props.find(uid).ok_or_else(|| bad(C, "no such property"))?;
let as_type = str_p(p, "as").and_then(ControlType::parse);
let ty = match as_type {
Some(t) if essential::can_show_as(pr, t) => Some(t),
Some(t) => return Ok(json!({"ok": false, "reason": format!("`{}` can't be shown as a {} control", pr.name, t.label())})),
None => control_type(pr),
};
let in_eg = super::match_path_of(&l.props, uid).is_some_and(|m| m.starts_with(essential::GROUP));
Ok(match ty {
Some(t) if !in_eg => json!({"ok": true, "type": t}),
_ => json!({"ok": false, "reason": format!("`{}` can't be added to Essential Graphics (unsupported property type)", pr.name)}),
})
}
fn solo_supported(s: &mut Session, p: &Value) -> Result<Value> {
let on = b_p(p, "on").unwrap_or(!s.state.essential_solo);
s.state.essential_solo = on;
@@ -299,8 +387,8 @@ fn control_json(project: &Project, cid: ItemId, c: &EgControl) -> Value {
"id": c.id, "name": c.name, "kind": "property", "layer": layer.0, "prop": prop,
"layerName": src.map(|(l, _)| l.name.clone()),
"path": src.and_then(|(l, _)| super::match_path_of(&l.props, *prop)),
"type": src.and_then(|(_, pr)| essential::control_type(pr)),
"value": src.map(|(_, pr)| pr.value_at(Tick::ZERO).to_json()),
"type": src.and_then(|(_, pr)| essential::effective_type(c, pr)),
"value": src.map(|(_, pr)| value_json(essential::effective_type(c, pr), &pr.value_at(Tick::ZERO))),
"missing": src.is_none(),
})
}
@@ -384,8 +472,8 @@ fn instance_json(s: &mut Session, p: &Value) -> Result<Value> {
"control": c.id, "name": c.name, "kind": kind,
"uid": pr.as_ref().map(|x| x.uid),
"path": pr.as_ref().and_then(|x| super::match_path_of(&l.props, x.uid)),
"value": pr.as_ref().map(|x| x.value_at(l.layer_time(t)).to_json()),
"type": pr.as_ref().and_then(essential::control_type).or((kind == "media").then_some(ControlType::Media)),
"value": pr.as_ref().map(|x| value_json(essential::effective_type(c, x), &x.value_at(l.layer_time(t)))),
"type": pr.as_ref().and_then(|x| essential::effective_type(c, x)).or((kind == "media").then_some(ControlType::Media)),
"overridden": pr.as_ref().is_some_and(|x| over.contains(&x.uid)),
}));
}
@@ -395,7 +483,7 @@ fn instance_json(s: &mut Session, p: &Value) -> Result<Value> {
/// Set an instance's value for a control (`value`, or `item` for Media Replacement).
fn set_override(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "essential.set";
let (cid, lid, _) = instance(s, p, C)?;
let (cid, lid, src) = instance(s, p, C)?;
let control = control_p(p, C)?;
let uid = master_uid(s, cid, lid, control).ok_or_else(|| bad(C, format!("no control {control} on this instance")))?;
if let Some(item) = p.get("item") {
@@ -414,7 +502,13 @@ fn set_override(s: &mut Session, p: &Value) -> Result<Value> {
})?;
return Ok(json!({"control": control, "item": item.0}));
}
let mut q = json!({"comp": cid.0, "layer": lid.0, "prop": uid, "value": p.get("value").cloned().ok_or_else(|| bad(C, "missing `value` (or `item`)"))?});
let mut value = p.get("value").cloned().ok_or_else(|| bad(C, "missing `value` (or `item`)"))?;
let as_type = s.project.comp(src).and_then(|c| c.essential.as_ref()).and_then(|e| e.find(control)).and_then(|c| c.as_type);
if as_type == Some(ControlType::Font) {
let cur = s.project.comp(cid).and_then(|c| c.layer(lid)).and_then(|l| l.props.find(uid)).map(|pr| pr.value.clone()).unwrap_or(KV::Scalar(0.0));
value = font_value(&cur, &value).ok_or_else(|| bad(C, "a Font control takes {font?, style?, size?} or a font family name"))?;
}
let mut q = json!({"comp": cid.0, "layer": lid.0, "prop": uid, "value": value});
if let Some(m) = p.get("merge") {
q["merge"] = m.clone();
}
@@ -477,12 +571,21 @@ fn push_to_comp(s: &mut Session, p: &Value) -> Result<Value> {
let mut writes = vec![];
for (control, uid) in &ts {
let (Some(ctl), Some(pr)) = (eg.find(*control), l.props.find(*uid)) else { continue };
writes.push((ctl.kind.clone(), pr.clone()));
writes.push((ctl.kind.clone(), pr.clone(), ctl.as_type));
}
s.edit("Push Override Values to Source", None, |proj, _| {
let sc = proj.comp_mut(src).ok_or(EngineError::NoComp)?;
for (kind, pr) in &writes {
for (kind, pr, as_type) in &writes {
match kind {
// A Font control writes only the font (the source keeps its text and keys).
EgKind::Property { layer, prop } if *as_type == Some(ControlType::Font) => {
if let Some(target) = sc.layer_mut(*layer).and_then(|l| l.props.find_mut(*prop)) {
essential::merge_font(&mut target.value, &pr.value);
for k in &mut target.keys {
essential::merge_font(&mut k.value, &pr.value);
}
}
}
EgKind::Property { layer, prop } => {
let Some(inner) = sc.layer_mut(*layer) else { continue };
// Instance keys are in the precomp layer's time (= the source comp's time);
@@ -740,7 +843,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Property to Essential Graphics",
["Animation"],
None,
"{comp?, layer?, path?|prop?: uid (default: the selected properties), name?, group?: control id, index?}",
"{comp?, layer?, path?|prop?: uid (default: the selected properties), name?, group?: control id, index?, as?: font (Source Text font family/style/size) | scale (uniform Scale)}",
has_selected_props,
add_property
),
@@ -774,6 +877,16 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("essential.revert", "Revert", [], None, "{layer, control? (default: all overridden)}", has_instance, revert),
cmd!("effect.editDropdown", "Edit Dropdown Menu", [], None, "{layer, path?|prop?, items: [string]}", has_comp, edit_dropdown),
query!("essential.list", "Essential Graphics controls", "{comp?, supported?: bool}", list),
query!("essential.canAdd", "Can Add Property to Essential Graphics", "{layer, path|prop, as?} → {ok, type?, reason?}", can_add),
cmd!(
"comp.openInEssentialGraphics",
"Open in Essential Graphics",
["Composition"],
None,
"{comp?} → makes it the Essential Graphics panel's Primary composition and shows the panel",
has_comp,
open_in_eg
),
query!("essential.instance", "Essential Properties of a precomp layer", "{layer}", instance_json),
query!("essential.templateInfo", "Read a template's manifest", "{path}", template_info),
]
+38 -7
View File
@@ -102,6 +102,14 @@ pub(crate) fn import(s: &mut Session, p: &Value) -> Result<Value> {
"compositionLayerSizes" | "compositionRetainLayerSizes" | "layerSizes" => Some(true),
other => return Err(bad("file.import", format!("importAs: footage|composition|compositionLayerSizes, not `{other}`"))),
};
// PDF / Illustrator: which page (1-based, as in the Import dialog).
let page = match p.get("page") {
None | Some(Value::Null) => 0,
Some(v) => match v.as_u64().or_else(|| v.as_f64().filter(|x| x.fract() == 0.0 && *x >= 1.0).map(|x| x as u64)) {
Some(n) if n >= 1 => (n - 1) as u32,
_ => return Err(bad("file.import", "page: a page number from 1")),
},
};
let mut paths = paths;
let mut out_comps = vec![];
let mut ids = vec![];
@@ -113,7 +121,7 @@ pub(crate) fn import(s: &mut Session, p: &Value) -> Result<Value> {
Ok(b) if effectcraft_psd::is_psd(&b) => b,
Ok(b) if effectcraft_pdf::sniff(&b).is_some() && !path.to_ascii_lowercase().ends_with(".svg") => {
// PDF / Illustrator / EPS: one layer per file layer.
match import_vector_comp(s, &path, &b) {
match import_vector_comp(s, &path, &b, page) {
Ok((comp, items)) => {
out_comps.push(comp);
ids.extend(items);
@@ -185,13 +193,31 @@ pub(crate) fn import(s: &mut Session, p: &Value) -> Result<Value> {
f.frame_rate = r;
f.duration = r.tick_of(frames.max(1));
}
// Page: another page of a PDF / Illustrator file.
if page > 0 && matches!(f.codec.as_str(), "PDF" | "AI") {
match s
.services
.read_file(path)
.map_err(|e| e.to_string())
.and_then(|b| effectcraft_pdf::parse_page(&b, page as usize).map_err(|e| e.to_string()))
{
Ok(doc) => {
(f.width, f.height) = doc.pixel_size();
f.page = page;
}
Err(e) => {
errors.push(format!("{path}: {e}"));
continue;
}
}
}
// Choose Layer: one layer of a Photoshop document (document-sized).
if let Some(sel) = &psd_layer
&& f.codec == "PSD"
{
match s.services.read_file(path).ok().and_then(|b| effectcraft_psd::Psd::parse(b).ok()).and_then(|d| find_psd_layer(&d, sel)) {
Some((index, name)) => {
f.layer = Some(effectcraft_project::SourceLayer { index: index as u32, name, layer_size: false, embedded: None })
f.layer = Some(effectcraft_project::SourceLayer { index: index as u32, name, layer_size: false, embedded: None, placed: false })
}
None => {
errors.push(format!("{path}: no layer {sel}"));
@@ -210,6 +236,7 @@ pub(crate) fn import(s: &mut Session, p: &Value) -> Result<Value> {
let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or(path.clone());
let name = match &f.layer {
Some(l) => format!("{}/{name}", l.name),
None if f.page > 0 => format!("{name} (Page {})", f.page + 1),
None => name,
};
let label = match f.kind {
@@ -298,14 +325,18 @@ pub(crate) fn import_psd_comp(s: &mut Session, path: &str, bytes: Vec<u8>, retai
Ok((r.comp.0, items, r.warnings))
}
/// Import a PDF / Illustrator / EPS file as a composition (one undo step). Returns (comp, items).
fn import_vector_comp(s: &mut Session, path: &str, bytes: &[u8]) -> Result<(u64, Vec<u64>)> {
let name = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Vector".into());
/// Import page `page` of a PDF / Illustrator / EPS file as a composition (one undo step).
/// Returns (comp, items).
fn import_vector_comp(s: &mut Session, path: &str, bytes: &[u8], page: u32) -> Result<(u64, Vec<u64>)> {
let mut name = std::path::Path::new(path).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "Vector".into());
if page > 0 {
name = format!("{name} (Page {})", page + 1);
}
let rate = effectcraft_time::FrameRate::FPS_29_97;
let secs = if s.prefs.import.still_footage == "seconds" { s.prefs.import.still_seconds } else { 10.0 };
let duration = rate.snap_nearest(effectcraft_time::Tick::from_seconds_f64(secs));
let (comp, folder, items) = s.edit("Import", None, |proj, st| {
let r = crate::vector::import_vector_comp(proj, path, bytes, &name, rate, duration).map_err(EngineError::Other)?;
let r = crate::vector::import_vector_comp(proj, path, bytes, &name, page, rate, duration).map_err(EngineError::Other)?;
st.project_selection = vec![r.0];
Ok(r)
})?;
@@ -478,7 +509,7 @@ pub fn specs() -> Vec<CommandSpec> {
"File...",
["File", "Import"],
Some("Cmd+I"),
"{paths: [string], importAs?: footage|composition|compositionLayerSizes (Photoshop, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As)}",
"{paths: [string], importAs?: footage|composition|compositionLayerSizes (Photoshop, PDF, Illustrator and EPS files), layer?: name|index (footage of one Photoshop layer), page?: number from 1 (PDF / Illustrator page), drag?: bool (dropped files: Settings ▸ Import ▸ Default Drag Import As)}",
always,
import
),
+240
View File
@@ -0,0 +1,240 @@
//! Composition ▸ Save Frame As ▸ Photoshop Layers… and ProEXR…: the current frame with every
//! visible layer kept apart.
//!
//! - **Photoshop Layers** writes a layered PSD (crates/psd's writer): one pixel layer per comp
//! layer, each rendered in isolation (solo, Normal mode, 100% opacity) and cropped to its
//! pixels, carrying the layer's blend mode and opacity, plus the flattened frame as the merged
//! image. Photoshop (and EffectCraft's PSD import) rebuild the frame from the layers.
//! - **ProEXR** writes one multi-layer OpenEXR (half-float-free, 32-bit float, linear light,
//! premultiplied): the composite as `R`, `G`, `B`, `A` plus one `<layer name>.R/G/B/A` channel
//! set per layer (the layer-prefixed channel convention multi-layer EXR readers use).
use effectcraft_color::BlendMode;
use effectcraft_project::{ItemId, LayerId, Project};
use effectcraft_raster::Image;
use effectcraft_render::{Backend, RenderOpts, Renderer};
use effectcraft_time::Tick;
use serde_json::{Value, json};
use super::{CommandSpec, bad, comp_id, f_p, has_comp, str_p};
use crate::{EngineError, Result, Session, cmd};
/// One isolated layer of a frame: name, blend mode, opacity (0..1), premultiplied pixels.
struct Isolated {
name: String,
blend: BlendMode,
opacity: f64,
image: Image,
}
fn render_with(s: &Session, project: &Project, comp: ItemId, t: Tick, scale: f64) -> Image {
let opts = RenderOpts {
scale,
backend: Backend::Auto,
nested_switches: s.prefs.general.switches_affect_nested_comps,
draft_shadows: s.prefs.three_d.realtime_shadows,
..Default::default()
};
let mut r = Renderer::new(project, s.footage.as_ref(), opts);
r.expr = s.expr.as_deref();
r.accel = s.accel.as_deref();
r.comp_frame(comp, t)
}
/// The comp frame and each visible layer rendered alone (top layer first).
fn isolate(s: &Session, cid: ItemId, t: Tick, scale: f64) -> Result<(Image, Vec<Isolated>)> {
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let full = render_with(s, &s.project, cid, t, scale);
let any_solo = comp.layers.iter().any(|l| l.switches.solo && l.has_video());
let ids: Vec<LayerId> = comp
.layers
.iter()
.filter(|l| l.has_video() && l.is_active_at(t) && !l.switches.adjustment && !l.switches.guide && !l.environment && (!any_solo || l.switches.solo))
.map(|l| l.id)
.collect();
let mut out = vec![];
for id in ids {
let mut p: Project = (*s.project).clone();
let Some(c) = p.comp_mut(cid) else { continue };
let mut info = None;
for l in c.layers.iter_mut() {
l.switches.solo = l.id == id;
if l.id == id {
let lt = l.layer_time(t);
let opacity = l.props.prop("transform/opacity").map(|o| o.value_at(lt).as_f64() / 100.0).unwrap_or(1.0);
info = Some((l.name.clone(), l.blend_mode, opacity.clamp(0.0, 1.0)));
l.blend_mode = BlendMode::Normal;
if let Some(o) = l.props.prop_mut("transform/opacity") {
o.keys.clear();
o.expr = None;
o.value = effectcraft_keyframe::Value::Scalar(100.0);
}
}
}
let Some((name, blend, opacity)) = info else { continue };
let image = render_with(s, &p, cid, t, scale);
out.push(Isolated { name, blend, opacity, image });
}
Ok((full, out))
}
fn straight(p: [f32; 4]) -> [f32; 4] {
if p[3] <= 0.0 { [0.0; 4] } else { [p[0] / p[3], p[1] / p[3], p[2] / p[3], p[3].min(1.0)] }
}
/// The Photoshop key of a blend mode (Normal for modes Photoshop lacks).
pub fn psd_blend_key(m: BlendMode) -> [u8; 4] {
const KEYS: [&[u8; 4]; 26] = [
b"diss", b"dark", b"mul ", b"idiv", b"lbrn", b"dkCl", b"lite", b"scrn", b"div ", b"lddg", b"lgCl", b"over", b"sLit", b"hLit", b"vLit", b"lLit",
b"pLit", b"hMix", b"diff", b"smud", b"fsub", b"fdiv", b"hue ", b"sat ", b"colr", b"lum ",
];
KEYS.iter().find(|k| crate::psd_import::blend_mode(std::str::from_utf8(&k[..]).unwrap_or("")) == m).map(|k| **k).unwrap_or(*b"norm")
}
/// The bounding box of non-transparent pixels (`None` when empty).
fn alpha_bounds(img: &Image) -> Option<(u32, u32, u32, u32)> {
let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0);
for y in 0..img.height {
for x in 0..img.width {
if img.data[(y * img.width + x) as usize][3] > 0.5 / 255.0 {
x0 = x0.min(x);
y0 = y0.min(y);
x1 = x1.max(x + 1);
y1 = y1.max(y + 1);
}
}
}
(x1 > x0).then_some((x0, y0, x1, y1))
}
/// The layered PSD bytes of a frame.
pub fn layered_psd(s: &Session, cid: ItemId, t: Tick, scale: f64) -> Result<(Vec<u8>, usize, u32, u32)> {
use effectcraft_psd::Rect;
use effectcraft_psd::write::{WDoc, WLayer, write};
let (full, layers) = isolate(s, cid, t, scale)?;
let mut doc = WDoc::new(full.width, full.height);
let n = layers.len();
// File order is bottom first.
for l in layers.into_iter().rev() {
let mut w = match alpha_bounds(&l.image) {
Some((x0, y0, x1, y1)) => {
let mut px = Vec::with_capacity(((x1 - x0) * (y1 - y0)) as usize);
for y in y0..y1 {
for x in x0..x1 {
px.push(straight(l.image.data[(y * l.image.width + x) as usize]));
}
}
WLayer::pixels(&l.name, Rect::new(x0 as i32, y0 as i32, (x1 - x0) as i32, (y1 - y0) as i32), px)
}
None => WLayer::pixels(&l.name, Rect::default(), vec![]),
};
w.blend = psd_blend_key(l.blend);
w.opacity = (l.opacity * 255.0).round() as u8;
doc.layers.push(w);
}
doc.composite = Some(full.data.iter().map(|p| straight(*p)).collect());
Ok((write(&doc), n, full.width, full.height))
}
fn srgb_to_linear(c: f32) -> f32 {
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
}
/// A unique EXR layer name (no dots: they separate the layer from the channel).
fn exr_name(name: &str, used: &mut Vec<String>) -> String {
let base: String = name.chars().map(|c| if c == '.' || c.is_control() { '_' } else { c }).collect();
let base = if base.trim().is_empty() { "Layer".to_string() } else { base };
let mut n = base.clone();
let mut k = 2;
while used.contains(&n) {
n = format!("{base} {k}");
k += 1;
}
used.push(n.clone());
n
}
/// The multi-layer EXR bytes of a frame and the channel names.
pub fn layered_exr(s: &Session, cid: ItemId, t: Tick, scale: f64) -> Result<(Vec<u8>, Vec<String>, u32, u32)> {
use exr::prelude::*;
let (full, layers) = isolate(s, cid, t, scale)?;
let (w, h) = (full.width as usize, full.height as usize);
let planes = |img: &effectcraft_raster::Image| -> [Vec<f32>; 4] {
let mut out: [Vec<f32>; 4] = Default::default();
for p in &img.data {
let sp = straight(*p);
let a = sp[3];
for c in 0..3 {
out[c].push(srgb_to_linear(sp[c].clamp(0.0, 1.0)) * a);
}
out[3].push(a);
}
out
};
let mut channels = vec![];
let mut names = vec![];
let mut push = |prefix: &str, img: &effectcraft_raster::Image| {
for (c, data) in ["R", "G", "B", "A"].iter().zip(planes(img)) {
let n = if prefix.is_empty() { c.to_string() } else { format!("{prefix}.{c}") };
names.push(n.clone());
channels.push(AnyChannel::new(n.as_str(), FlatSamples::F32(data)));
}
};
push("", &full);
let mut used = vec![];
for l in &layers {
let n = exr_name(&l.name, &mut used);
push(&n, &l.image);
}
let layer = Layer::new((w, h), LayerAttributes::default(), Encoding::SMALL_LOSSLESS, AnyChannels::sort(channels.into()));
let mut buf = std::io::Cursor::new(Vec::new());
Image::from_layer(layer).write().to_buffered(&mut buf).map_err(|e| EngineError::Other(format!("EXR encoding failed: {e}")))?;
Ok((buf.into_inner(), names, full.width, full.height))
}
fn frame_args(s: &Session, p: &Value, cmd: &str, ext: &str) -> Result<(String, ItemId, Tick, f64)> {
let path = str_p(p, "path").ok_or_else(|| bad(cmd, format!("missing `path` (.{ext})")))?.to_string();
let cid = comp_id(s, p)?;
let t = f_p(p, "time").map(Tick::from_seconds_f64).unwrap_or(s.time());
let scale = f_p(p, "scale").unwrap_or(1.0).clamp(0.01, 4.0);
Ok((path, cid, t, scale))
}
fn save_psd(s: &mut Session, p: &Value) -> Result<Value> {
let (path, cid, t, scale) = frame_args(s, p, "comp.saveFrameAsPsd", "psd")?;
let (bytes, n, w, h) = layered_psd(s, cid, t, scale)?;
s.services.write_file(&path, &bytes).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
s.toast(format!("Saved {n} layers to {path}"));
Ok(json!({"path": path, "layers": n, "width": w, "height": h, "time": t.seconds()}))
}
fn save_exr(s: &mut Session, p: &Value) -> Result<Value> {
let (path, cid, t, scale) = frame_args(s, p, "comp.saveFrameAsExr", "exr")?;
let (bytes, channels, w, h) = layered_exr(s, cid, t, scale)?;
s.services.write_file(&path, &bytes).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
s.toast(format!("Saved a multi-layer EXR to {path}"));
Ok(json!({"path": path, "channels": channels, "width": w, "height": h, "time": t.seconds()}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"comp.saveFrameAsPsd",
"Photoshop Layers...",
["Composition", "Save Frame As"],
None,
"{path (.psd), comp?, time?, scale?} → a layered PSD: one layer per visible comp layer (blend mode, opacity) + the merged frame",
has_comp,
save_psd
),
cmd!(
"comp.saveFrameAsExr",
"ProEXR...",
["Composition", "Save Frame As"],
None,
"{path (.exr), comp?, time?, scale?} → a multi-layer OpenEXR: composite R,G,B,A + `<layer>.R/G/B/A` per layer (linear, premultiplied)",
has_comp,
save_exr
),
]
}
+9 -2
View File
@@ -36,7 +36,14 @@ pub fn specs() -> Vec<CommandSpec> {
fe!("app.templates", "Templates", [], None, "{kind: renderSettings|outputModule}", always),
fe!("app.find", "Find", ["File"], Some("Cmd+F"), "{query?}", always),
// Preview.
fe!("playback.toggle", "Play Current Preview", ["Composition", "Preview"], Some("Space"), "{}", has_comp),
fe!(
"playback.toggle",
"Play Current Preview",
["Composition", "Preview"],
Some("Space"),
"{shortcut?: spacebar|shiftSpacebar|numpad0|shiftNumpad0|altNumpad0 (whose Preview panel options to use; default spacebar)}",
has_comp
),
fe!("playback.cacheWhenIdle", "Cache Frames When Idle", ["Composition", "Preview"], None, "{value?}", always),
fe!("playback.audio", "Audio", ["Composition", "Preview"], None, "{value?: include audio in previews}", always),
// Viewer.
@@ -63,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show Panel",
[],
None,
"{panel: project|effectControls|composition|layer|timeline|info|audio|preview|effectsPresets|properties|character|paragraph|align|tracker|wiggler|smoother|motionSketch|paint|brushes|renderQueue|flowchart|history|markers|tools|lumetriScopes|footage|mediaBrowser|metadata|progress|contentAwareFill}",
"{panel: project|effectControls|composition|layer|timeline|info|audio|preview|effectsPresets|properties|character|paragraph|align|tracker|wiggler|smoother|motionSketch|paint|brushes|renderQueue|flowchart|history|markers|tools|lumetriScopes|footage|mediaBrowser|metadata|progress|contentAwareFill|createNullsFromPaths|vrCompEditor}",
always
),
fe!(
+6
View File
@@ -35,6 +35,12 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("help.website", "ArtCraft Website", ["Help"], None, "{}", always, |s, _| open(s, links::WEBSITE.into())),
cmd!("help.appPage", "EffectCraft Home Page", ["Help"], None, "{}", always, |s, _| open(s, links::APP_PAGE.into())),
cmd!("help.github", "EffectCraft on GitHub", ["Help"], None, "{}", always, |s, _| open(s, links::GITHUB.into())),
cmd!("help.onlineTutorials", "Online Tutorials...", ["Help"], None, "{}", always, |s, _| open(s, links::APP_PAGE.into())),
cmd!("help.inAppTutorials", "In-App Tutorials...", ["Help"], None, "{} → the Home screen's Learn tab", always, |s, p| super::frontend(
s,
"help.inAppTutorials",
p
)),
cmd!("help.reportIssue", "Provide Feedback...", ["Help"], None, "{}", always, |s, _| open(s, links::ISSUES.into())),
cmd!(
"help.sibling",
+1 -1
View File
@@ -1163,7 +1163,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Text",
[],
None,
"{layer?, range?: [start, end] (characters; default all), text?, font?, style?, size?, fill?, stroke?, applyFill?, applyStroke?, strokeWidth?, tracking?, leading?: px|\"auto\", baselineShift? px, hScale? %, vScale? %, tsume? %, fauxBold?, fauxItalic?, allCaps?, smallCaps?, baseline?: normal|superscript|subscript, superscript?, subscript?, kerning?: metrics|optical|number, ligatures?, OpenType: discretionaryLigatures?, contextualAlternates?, stylisticAlternates?, stylisticSets?: [1–20], ss01…ss20?, swash?, titling?, ordinals?, fractions?, allSmallCaps?, figureStyle?: default|lining|oldStyle, figureWidth?: default|proportional|tabular, figures?, justify?: left|center|right|justifyLeft|justifyCenter|justifyRight|justifyAll, indentLeft?, indentRight?, indentFirst?, spaceBefore?, spaceAfter?, direction?: ltr|rtl, composer?: everyLine|singleLine, hangingPunctuation?, strokeOverFill?, box?: [x,y,w,h]|null (layer space), vertical?}",
"{layer?, range?: [start, end] (characters; default all), text?, font?, style?, size?, fill?, stroke?, applyFill?, applyStroke?, strokeWidth?, tracking?, leading?: px|\"auto\", baselineShift? px, hScale? %, vScale? %, tsume? %, fauxBold?, fauxItalic?, allCaps?, smallCaps?, baseline?: normal|superscript|subscript, superscript?, subscript?, kerning?: metrics|optical|number, ligatures?, OpenType: discretionaryLigatures?, contextualAlternates?, stylisticAlternates?, stylisticSets?: [1–20], ss01…ss20?, swash?, titling?, ordinals?, fractions?, allSmallCaps?, figureStyle?: default|lining|oldStyle, figureWidth?: default|proportional|tabular, figures?, variations?: {tag: value} (variable font axes; null resets), justify?: left|center|right|justifyLeft|justifyCenter|justifyRight|justifyAll, indentLeft?, indentRight?, indentFirst?, spaceBefore?, spaceAfter?, direction?: ltr|rtl, composer?: everyLine|singleLine, hangingPunctuation?, strokeOverFill?, box?: [x,y,w,h]|null (layer space), vertical?}",
has_layers,
set_text
),
+15 -2
View File
@@ -1,11 +1,12 @@
//! The command registry. Ids follow After Effects' menu structure; every menu item, panel button,
//! shortcut and viewer/timeline gesture maps to one of these.
mod align;
mod align_data;
mod anim;
pub mod anim_tools;
mod animation;
mod app_more;
pub(crate) mod app_more;
mod autotrace;
mod camera_cmds;
mod comp;
@@ -20,6 +21,7 @@ mod file;
pub(crate) mod file_more;
mod focus;
pub mod footage_panel;
pub(crate) mod frame_export;
mod frontend;
mod help;
mod key_labels;
@@ -28,7 +30,7 @@ mod keys_more;
mod layer;
mod layer_menu;
mod layer_time;
mod link;
pub(crate) mod link;
mod liquify;
mod lottie;
mod markers;
@@ -37,6 +39,7 @@ pub mod mask_interp;
pub(crate) mod model3d;
pub mod paint;
pub mod panels_cmds;
pub(crate) mod path_nulls;
mod paths;
mod project_items;
mod prop;
@@ -60,7 +63,10 @@ pub mod time;
mod track;
mod view;
pub mod viewer_cmds;
pub(crate) mod vpe;
pub(crate) mod vr_editor;
mod warp_cmds;
pub(crate) mod watch_folder;
#[cfg(test)]
pub(crate) use app_more::report_text as report_text_for_tests;
pub(crate) use app_more::view_command;
@@ -161,6 +167,11 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(file_more::specs());
v.extend(lottie::specs());
v.extend(comp_more::specs());
v.extend(frame_export::specs());
v.extend(watch_folder::specs());
v.extend(vpe::specs());
v.extend(path_nulls::specs());
v.extend(vr_editor::specs());
v.extend(frontend::specs());
v.extend(track::specs());
v.extend(mask_interp::specs());
@@ -182,9 +193,11 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(autotrace::specs());
v.extend(scene_detect::specs());
v.extend(align_data::specs());
v.extend(align::specs());
v.extend(content_fill::specs());
v.extend(stubs::specs());
v.extend(crate::learn::specs());
v.extend(crate::preview::specs());
v
})
}
+55 -13
View File
@@ -29,38 +29,61 @@ fn jobs_wait(s: &mut Session, _: &Value) -> Result<Value> {
// ---------------------------------------------------------------- Media Browser
fn browser_dir(s: &Session, p: &Value) -> String {
str_p(p, "path").map(str::to_string).or_else(|| s.state.media_browser.folder.clone()).unwrap_or_else(mb::home)
fn browser(s: &Session) -> Result<std::sync::Arc<dyn mb::Browser>> {
s.media_browser().ok_or_else(|| EngineError::Other("the Media Browser is not available in this build".into()))
}
fn browser_dir(s: &Session, b: &dyn mb::Browser, p: &Value) -> String {
str_p(p, "path").map(str::to_string).or_else(|| s.state.media_browser.folder.clone()).unwrap_or_else(|| b.home())
}
fn browser_list(s: &mut Session, p: &Value) -> Result<Value> {
let dir = browser_dir(s, p);
let b = browser(s)?;
let dir = browser_dir(s, b.as_ref(), p);
let only = b_p(p, "importableOnly").unwrap_or(s.state.media_browser.importable_only);
let entries = mb::list(&dir, only).map_err(EngineError::Other)?;
Ok(json!({"path": dir, "parent": mb::parent(&dir), "entries": entries, "favorites": s.state.media_browser.favorites}))
let entries = b.list(&dir, only).map_err(EngineError::Other)?;
let places: Vec<Value> = b.places().into_iter().map(|(name, path)| json!({"name": name, "path": path})).collect();
let actions: Vec<Value> = b.actions().into_iter().map(|(id, label)| json!({"id": id, "label": label})).collect();
Ok(json!({
"path": dir,
"parent": b.parent(&dir),
"entries": entries,
"favorites": s.state.media_browser.favorites,
"places": places,
"actions": actions,
}))
}
fn browser_enabled(_: &Session) -> std::result::Result<(), String> {
if mb::available() { Ok(()) } else { Err("the Media Browser needs the desktop app".into()) }
fn browser_enabled(s: &Session) -> std::result::Result<(), String> {
if s.media_browser().is_some() { Ok(()) } else { Err("the Media Browser is not available in this build".into()) }
}
fn browser_go(s: &mut Session, p: &Value) -> Result<Value> {
let b = browser(s)?;
let dir = match str_p(p, "path") {
Some("..") => s.state.media_browser.folder.clone().and_then(|d| mb::parent(&d)).unwrap_or_else(mb::home),
Some("..") => s.state.media_browser.folder.clone().and_then(|d| b.parent(&d)).unwrap_or_else(|| b.home()),
Some(d) => d.to_string(),
None => mb::home(),
None => b.home(),
};
if let Some(b) = b_p(p, "importableOnly") {
s.state.media_browser.importable_only = b;
if let Some(v) = b_p(p, "importableOnly") {
s.state.media_browser.importable_only = v;
}
// Validate before switching.
mb::list(&dir, false).map_err(EngineError::Other)?;
b.list(&dir, false).map_err(EngineError::Other)?;
s.state.media_browser.folder = Some(dir.clone());
browser_list(s, &json!({"path": dir}))
}
/// A browser-specific toolbar action (web: Open Folder…, Add Files…).
fn browser_action(s: &mut Session, p: &Value) -> Result<Value> {
let b = browser(s)?;
let id = str_p(p, "action").ok_or_else(|| bad("mediaBrowser.action", "missing `action`"))?;
b.action(id).map_err(|e| bad("mediaBrowser.action", e))
}
fn browser_favorite(s: &mut Session, p: &Value, add: bool) -> Result<Value> {
let dir = browser_dir(s, p);
let b = browser(s)?;
let dir = browser_dir(s, b.as_ref(), p);
let favs = &mut s.state.media_browser.favorites;
favs.retain(|f| f != &dir);
if add {
@@ -71,6 +94,16 @@ fn browser_favorite(s: &mut Session, p: &Value, add: bool) -> Result<Value> {
fn browser_import(s: &mut Session, p: &Value) -> Result<Value> {
let paths = p.get("paths").or(p.get("path")).cloned().ok_or_else(|| bad("mediaBrowser.import", "missing `paths`"))?;
// Files the browser still has to read (the web app's opened folders): imported when they
// arrive.
let list: Vec<String> = match &paths {
Value::String(one) => vec![one.clone()],
Value::Array(a) => a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect(),
_ => vec![],
};
if !browser(s)?.fetch(&list, p) {
return Ok(json!({"pending": true, "paths": list}));
}
let r = s.execute("file.import", json!({"paths": paths}))?;
// Add to the active comp (drag into the timeline).
if b_p(p, "addToComp").unwrap_or(false)
@@ -201,6 +234,15 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("mediaBrowser.addFavorite", "Add to Favorites", [], None, "{path?}", browser_enabled, |s, p| browser_favorite(s, p, true)),
cmd!("mediaBrowser.removeFavorite", "Remove from Favorites", [], None, "{path?}", browser_enabled, |s, p| browser_favorite(s, p, false)),
cmd!("mediaBrowser.import", "Import", [], None, "{paths, addToComp?}", browser_enabled, browser_import),
cmd!(
"mediaBrowser.action",
"Media Browser Action",
[],
None,
"{action}: an action from mediaBrowser.list's `actions` (web: openFolder, addFiles, uploadFolder)",
browser_enabled,
browser_action
),
query!("mediaBrowser.fileInfo", "File Info", "{path}", file_info),
query!("item.metadata", "Metadata", "{item?: id|name}", metadata),
cmd!("project.setProjectComment", "Project Comment", [], None, "{comment}", always, project_comment),
+217
View File
@@ -0,0 +1,217 @@
//! Window ▸ Create Nulls From Paths: our own panel (and these commands) linking a mask or shape
//! path to null layers with expressions, in three ways:
//!
//! - **Points Follow Nulls** (`paths.pointsFollowNulls`): one null per vertex, placed on it; the
//! path's expression rebuilds it from the nulls (`createPath` of each null's position brought
//! into the path's layer with `fromComp`), so moving a null moves its vertex.
//! - **Nulls Follow Points** (`paths.nullsFollowPoints`): one null per vertex whose Position
//! expression follows the vertex (`toComp(path.points()[i])`), for attaching things to an
//! animated path.
//! - **Trace Path** (`paths.tracePath`): one null with a Progress slider (keyframed 0 → 100 % over
//! the layer's span, optionally looping) whose Position follows `pointOnPath(progress)`.
//!
//! The path is `path`/`prop` of `layer`, else the selected path property, else the layer's first
//! mask or shape path. Each command is one undo step.
use effectcraft_geom::vec2;
use effectcraft_keyframe::Value as KV;
use effectcraft_project::{ItemId, LayerId, Uid};
use serde_json::{Value, json};
use super::{CommandSpec, b_p, bad, comp_id, has_layers};
use crate::{EngineError, Result, Session, cmd};
fn quote(s: &str) -> String {
serde_json::to_string(s).unwrap_or_else(|_| format!("\"{s}\""))
}
/// The target path property: (comp, layer, uid).
fn target(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
if p.get("path").is_some() || p.get("prop").is_some() {
let r = super::prop::prop_ref(s, p, cmd)?;
let is_path = s.project.comp(r.0).and_then(|c| c.layer(r.1)).and_then(|l| l.props.find(r.2)).is_some_and(|pr| matches!(pr.value, KV::Path(_)));
return if is_path { Ok(r) } else { Err(bad(cmd, "that property is not a mask or shape path")) };
}
let cid = comp_id(s, p)?;
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
// A selected path property.
for (l, u) in super::selected_leaf_props(s) {
if comp.layer(l).and_then(|ly| ly.props.find(u)).is_some_and(|pr| matches!(pr.value, KV::Path(_))) {
return Ok((cid, l, u));
}
}
// The first path of `layer` (or of the first selected layer).
let lid = match p.get("layer") {
Some(_) => super::layer_p(s, p, cmd)?.1,
None => *s.state.selected_layers.first().ok_or_else(|| bad(cmd, "select a layer with a mask or shape path"))?,
};
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
let mut found = None;
layer.props.walk("", &mut |_, pr| {
if found.is_none() && matches!(pr.value, KV::Path(_)) && !matches!(pr.ui, effectcraft_project::ParamUi::Hidden) {
found = Some(pr.uid);
}
});
found.map(|u| (cid, lid, u)).ok_or_else(|| bad(cmd, format!("`{}` has no mask or shape path", layer.name)))
}
/// What the commands need about the path: its vertices in comp space (now), the path value, the
/// expression reference to it and its layer's name.
struct PathInfo {
comp_pts: Vec<[f64; 2]>,
path: effectcraft_keyframe::ShapePath,
reference: String,
layer_name: String,
prop_name: String,
span: (f64, f64),
}
fn info(s: &Session, cid: ItemId, lid: LayerId, uid: Uid, cmd: &str) -> Result<PathInfo> {
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
let layer = comp.layer(lid).ok_or(EngineError::NoComp)?;
let pr = layer.props.find(uid).ok_or_else(|| bad(cmd, "no such property"))?;
let t = s.time();
let ctx = effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref(), footage: Some(s.footage.as_ref()) };
let KV::Path(path) = ctx.value(layer, pr) else { return Err(bad(cmd, "that property is not a path")) };
if path.vertices.is_empty() {
return Err(bad(cmd, "the path has no vertices"));
}
let m = ctx.layer_to_comp(layer).0;
let comp_pts = path
.vertices
.iter()
.map(|v| {
let q = m.apply(vec2(v[0], v[1]));
[q.x, q.y]
})
.collect();
// Seen from another layer (the nulls).
let mut other = layer.clone();
other.id = LayerId(u64::MAX);
other.name = "\u{0}".into();
let reference = super::link::reference(comp, &other, layer, uid, true).ok_or_else(|| bad(cmd, "can't reference that path"))?;
let prop_name = layer.props.name_path_of(uid).and_then(|n| n.split('/').rev().nth(1).map(str::to_string)).unwrap_or_else(|| pr.name.clone());
Ok(PathInfo { comp_pts, path, reference, layer_name: layer.name.clone(), prop_name, span: (layer.in_point.seconds(), layer.out_point.seconds()) })
}
/// A new null at `at` (comp space) named `name`, made unique in the comp (expressions find
/// layers by name). Returns (layer id, name).
fn new_null(s: &mut Session, cid: ItemId, name: &str, at: [f64; 2]) -> Result<(u64, String)> {
let taken = |n: &str| s.project.comp(cid).is_some_and(|c| c.layers.iter().any(|l| l.name == n));
let mut name = name.to_string();
let base = name.clone();
let mut k = 2;
while taken(&name) {
name = format!("{base} {k}");
k += 1;
}
let r = s.execute("layer.newNull", json!({"comp": cid.0, "name": name}))?;
let id = r.get("layer").and_then(Value::as_u64).ok_or_else(|| EngineError::Other("no null layer".into()))?;
s.execute("prop.set", json!({"comp": cid.0, "layer": id, "path": "transform/position", "value": at}))?;
Ok((id, name))
}
fn nulls_follow_points(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "paths.nullsFollowPoints";
let (cid, lid, uid) = target(s, p, C)?;
let pi = info(s, cid, lid, uid, C)?;
let nulls = super::app_more::grouped(s, "Nulls Follow Points", |s| {
let mut out = vec![];
for (i, at) in pi.comp_pts.iter().enumerate() {
let (id, _) = new_null(s, cid, &format!("{}: {} [{}]", pi.layer_name, pi.prop_name, i + 1), *at)?;
let e = format!("var src = thisComp.layer({});\nvar p = src.toComp({}.points()[{i}]);\n[p[0], p[1]]", quote(&pi.layer_name), pi.reference);
s.execute("prop.setExpression", json!({"comp": cid.0, "layer": id, "path": "transform/position", "expression": e}))?;
out.push(id);
}
Ok(out)
})?;
Ok(json!({"nulls": nulls, "layer": lid.0, "prop": uid}))
}
fn points_follow_nulls(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "paths.pointsFollowNulls";
let (cid, lid, uid) = target(s, p, C)?;
let pi = info(s, cid, lid, uid, C)?;
let nulls = super::app_more::grouped(s, "Points Follow Nulls", |s| {
let mut out = vec![];
let mut names = vec![];
for (i, at) in pi.comp_pts.iter().enumerate() {
let name = format!("{}: {} [{}]", pi.layer_name, pi.prop_name, i + 1);
let (id, name) = new_null(s, cid, &name, *at)?;
out.push(id);
names.push(quote(&name));
}
let arr = |v: &[[f64; 2]]| serde_json::to_string(v).unwrap_or_else(|_| "[]".into());
let e = format!(
"var nulls = [{}];\nvar pts = [];\nfor (var i = 0; i < nulls.length; i++) {{\n var n = thisComp.layer(nulls[i]);\n var q = fromComp(n.toComp(n.transform.anchorPoint));\n pts.push([q[0], q[1]]);\n}}\ncreatePath(pts, {}, {}, {})",
names.join(", "),
arr(&pi.path.in_tangents),
arr(&pi.path.out_tangents),
pi.path.closed
);
s.execute("prop.setExpression", json!({"comp": cid.0, "layer": lid.0, "prop": uid, "expression": e}))?;
Ok(out)
})?;
Ok(json!({"nulls": nulls, "layer": lid.0, "prop": uid}))
}
fn trace_path(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "paths.tracePath";
let (cid, lid, uid) = target(s, p, C)?;
let pi = info(s, cid, lid, uid, C)?;
let looping = b_p(p, "loop").unwrap_or(false);
let nid = super::app_more::grouped(s, "Trace Path", |s| {
let (id, _) = new_null(s, cid, &format!("Trace {}: {}", pi.layer_name, pi.prop_name), pi.comp_pts[0])?;
s.execute("effect.apply", json!({"comp": cid.0, "layers": [id], "effect": "ec.control.slider"}))?;
let fx = s.project.comp(cid).and_then(|c| c.layer(LayerId(id))).and_then(|l| l.props.group("effects/#1")).map(|g| g.uid);
if let Some(fx) = fx {
s.execute("prop.renameGroup", json!({"comp": cid.0, "layer": id, "prop": fx, "name": "Progress"}))?;
}
let (a, b) = pi.span;
s.execute("prop.addKey", json!({"comp": cid.0, "layer": id, "path": "effects/#1/slider", "time": a, "value": 0.0}))?;
s.execute("prop.addKey", json!({"comp": cid.0, "layer": id, "path": "effects/#1/slider", "time": b.max(a), "value": 100.0}))?;
if looping {
s.execute("prop.setExpression", json!({"comp": cid.0, "layer": id, "path": "effects/#1/slider", "expression": "loopOut(\"cycle\")"}))?;
}
let e = format!(
"var src = thisComp.layer({});\nvar p = src.toComp({}.pointOnPath(effect(\"Progress\")(\"Slider\") / 100));\n[p[0], p[1]]",
quote(&pi.layer_name),
pi.reference
);
s.execute("prop.setExpression", json!({"comp": cid.0, "layer": id, "path": "transform/position", "expression": e}))?;
Ok(id)
})?;
Ok(json!({"null": nid, "layer": lid.0, "prop": uid}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"paths.pointsFollowNulls",
"Points Follow Nulls",
[],
None,
"{layer?, path?|prop?} → a null per vertex; the path follows them (expression)",
has_layers,
points_follow_nulls
),
cmd!(
"paths.nullsFollowPoints",
"Nulls Follow Points",
[],
None,
"{layer?, path?|prop?} → a null per vertex following it (Position expressions)",
has_layers,
nulls_follow_points
),
cmd!(
"paths.tracePath",
"Trace Path",
[],
None,
"{layer?, path?|prop?, loop?: bool} → a null moving along the path (Progress slider)",
has_layers,
trace_path
),
]
}
+2 -2
View File
@@ -188,7 +188,7 @@ pub fn specs() -> Vec<CommandSpec> {
crate::query!(
"scriptui.get",
"Script Window Controls",
"{window?: id | title} → {id, title, kind, root: {id, type, name, text, value, checked, items, selection, bounds, enabled, children…}}",
"{window?: id | title} → {id, title, kind, root: {id, type, name, text, value, checked, items, selection, bounds, enabled, draw (onDraw paint list), children…}}",
scriptui::get
),
cmd!(
@@ -205,7 +205,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Script Window Control",
[],
None,
"{window?, widget, value: text | number | bool | item index | item text} (edit text, sliders, checkboxes, lists) → fires onChanging / onChange",
"{window?, widget, value: text | number | bool | item index | item text, changing?: bool (a live update: each keystroke / slider step; fires onChanging only)} (edit text, sliders, checkboxes, lists) → fires onChanging / onChange",
always,
scriptui::set
),
+29
View File
@@ -0,0 +1,29 @@
//! File ▸ Import ▸ Vanishing Point (.vpe): present in the menu like After Effects', but always
//! disabled. The `.vpe` exchange format Photoshop's Vanishing Point filter writes has no public
//! specification, and EffectCraft implements formats only from published specs (clean room), so
//! the entry explains that instead of importing. See docs/parity.md.
use serde_json::Value;
use super::{CommandSpec, bad};
use crate::{Result, Session, cmd};
/// Why the entry is disabled (shown as its tooltip).
pub const WHY: &str =
"Vanishing Point Exchange (.vpe) files can't be imported: the format has no public specification, and EffectCraft only implements documented formats";
fn import(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("file.importVanishingPoint", WHY))
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"file.importVanishingPoint",
"Vanishing Point (.vpe)...",
["File", "Import"],
None,
"{} (always disabled: undocumented format)",
|_| Err(WHY.into()),
import
)]
}
+167
View File
@@ -0,0 +1,167 @@
//! Window ▸ VR Comp Editor: our own panel over the VR environments Composition ▸ VR ▸ Create VR
//! Environment builds (an equirectangular output comp ← a 3:2 cube map ← six face comps, each
//! with a 90° camera). It lists the environments and edits the 360 view's camera orientation:
//! the six face cameras turn together, so the whole equirectangular output rotates (pan / tilt /
//! roll the viewer's starting direction) without touching the scene.
//!
//! The view orientation is not stored separately: it is read back from the Front camera
//! (`camera = view × face base`), so editing a camera by hand shows up here too.
use effectcraft_geom::{Mat4, vec3};
use effectcraft_project::{GroupKind, ItemId, LayerId, LayerSource, Project};
use serde_json::{Value, json};
use super::app_more::{CELLS_3X2, FACES, ae, grouped, orientation_for_axes};
use super::{CommandSpec, always, bad};
use crate::{EngineError, Result, Session, cmd, query};
/// A VR environment: its output comp, cube map and the face cameras in [`FACES`] order.
pub struct VrEnv {
pub output: ItemId,
pub cube: ItemId,
pub faces: [(ItemId, LayerId); 6],
}
/// The VR environments of a project.
pub fn environments(p: &Project) -> Vec<VrEnv> {
let mut out = vec![];
for (oid, oc) in p.comps() {
for l in &oc.layers {
let LayerSource::Comp { item: cube } = l.source else { continue };
let vr = l.effects().is_some_and(|fx| fx.groups().any(|g| matches!(&g.kind, GroupKind::Effect { effect } if effect == "ec.vr.converter")));
if !vr {
continue;
}
let Some(cc) = p.comp(cube) else { continue };
let size = (cc.width / 3).max(1) as f64;
let mut faces: [Option<(ItemId, LayerId)>; 6] = [None; 6];
for fl in &cc.layers {
let LayerSource::Comp { item: face } = fl.source else { continue };
let pos = fl.props.prop("transform/position").map(|x| x.value.components()).unwrap_or_default();
let (Some(x), Some(y)) = (pos.first(), pos.get(1)) else { continue };
let cell = ((x / size).floor().max(0.0) as u32, (y / size).floor().max(0.0) as u32);
let Some(i) = CELLS_3X2.iter().position(|c| *c == cell) else { continue };
let cam = p.comp(face).and_then(|fc| fc.layers.iter().find(|x| x.is_camera())).map(|x| x.id);
if let Some(cam) = cam {
faces[i] = Some((face, cam));
}
}
if faces.iter().all(Option::is_some) {
out.push(VrEnv { output: *oid, cube, faces: faces.map(|f| f.unwrap_or((ItemId(0), LayerId(0)))) });
}
}
}
out
}
fn base(i: usize) -> [f64; 3] {
let (_, fw, r, u) = FACES[i];
orientation_for_axes(ae(r), ae([-u[0], -u[1], -u[2]]), ae(fw))
}
fn orient(o: [f64; 3]) -> Mat4 {
Mat4::orientation(vec3(o[0], o[1], o[2]))
}
fn transpose(m: Mat4) -> Mat4 {
let mut t = Mat4::IDENTITY;
for r in 0..3 {
for c in 0..3 {
t.0[r][c] = m.0[c][r];
}
}
t
}
fn norm(a: f64) -> f64 {
let r = a.rem_euclid(360.0);
let r = if (r - 360.0).abs() < 1e-7 { 0.0 } else { r };
(r * 1e6).round() / 1e6
}
/// Orientation angles (X, Y, Z degrees, applied X then Y then Z) of a rotation matrix.
pub fn euler(m: Mat4) -> [f64; 3] {
let m = m.0;
let y = (-m[2][0]).clamp(-1.0, 1.0).asin();
let (x, z) = if y.cos().abs() > 1e-6 { (m[2][1].atan2(m[2][2]), m[1][0].atan2(m[0][0])) } else { ((-m[1][2]).atan2(m[1][1]), 0.0) };
[norm(x.to_degrees()), norm(y.to_degrees()), norm(z.to_degrees())]
}
/// The current view orientation of an environment (from its Front camera).
fn view_of(p: &Project, env: &VrEnv) -> [f64; 3] {
let (fc, cam) = env.faces[4];
let o = p.comp(fc).and_then(|c| c.layer(cam)).and_then(|l| l.props.prop("transform/orientation")).map(|x| x.value.components()).unwrap_or_default();
let o = [o.first().copied().unwrap_or(0.0), o.get(1).copied().unwrap_or(0.0), o.get(2).copied().unwrap_or(0.0)];
euler(orient(o) * transpose(orient(base(4))))
}
fn env_json(p: &Project, e: &VrEnv) -> Value {
let name = |i: ItemId| p.item(i).map(|x| x.name.clone()).unwrap_or_default();
json!({
"output": e.output.0, "name": name(e.output), "cubeMap": e.cube.0,
"faces": e.faces.iter().enumerate().map(|(i, (c, cam))| json!({"face": FACES[i].0, "comp": c.0, "camera": cam.0})).collect::<Vec<_>>(),
"view": view_of(p, e),
})
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!(environments(&s.project).iter().map(|e| env_json(&s.project, e)).collect::<Vec<_>>()))
}
/// The environment `comp` (its output, cube map or a face comp), else the active comp's, else
/// the only one.
fn env_p(s: &Session, p: &Value, cmd: &str) -> Result<VrEnv> {
let envs = environments(&s.project);
let want = p.get("comp").and_then(Value::as_u64).map(ItemId).or(s.state.active_comp);
let hit = |e: &VrEnv, c: ItemId| e.output == c || e.cube == c || e.faces.iter().any(|f| f.0 == c);
let i = want.and_then(|c| envs.iter().position(|e| hit(e, c))).or((envs.len() == 1).then_some(0));
let i = i.ok_or_else(|| {
bad(cmd, if envs.is_empty() { "no VR environment (Composition ▸ VR ▸ Create VR Environment…)" } else { "give `comp`: a VR environment's output comp" })
})?;
envs.into_iter().nth(i).ok_or(EngineError::NoComp)
}
fn set_view(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "comp.vr.setView";
let env = env_p(s, p, C)?;
let mut o = view_of(&s.project, &env);
match p.get("orientation") {
Some(Value::Array(a)) => {
for (k, v) in a.iter().take(3).enumerate() {
o[k] = v.as_f64().ok_or_else(|| bad(C, "orientation: [x, y, z] degrees"))?;
}
}
Some(_) => return Err(bad(C, "orientation: [x, y, z] degrees")),
None => {}
}
// Pan (Y), tilt (X) and roll (Z) by name.
for (k, i) in [("tilt", 0), ("pan", 1), ("roll", 2)] {
if let Some(v) = p.get(k).and_then(Value::as_f64) {
o[i] = v;
}
}
let v = orient(o);
grouped(s, "VR View Orientation", |s| {
for (i, (fc, cam)) in env.faces.iter().enumerate() {
let e = euler(v * orient(base(i)));
s.execute("prop.set", json!({"comp": fc.0, "layer": cam.0, "path": "transform/orientation", "value": e}))?;
}
Ok(())
})?;
Ok(json!({"output": env.output.0, "view": view_of(&s.project, &env)}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
query!("comp.vr.environments", "VR Environments", "{} → [{output, name, cubeMap, faces: [{face, comp, camera}], view: [x, y, z]}]", list),
cmd!(
"comp.vr.setView",
"VR View Orientation",
[],
None,
"{comp? (an environment's output / cube map / face comp), orientation?: [x, y, z] degrees, pan?, tilt?, roll?} → turns the six face cameras together",
always,
set_view
),
]
}
+154
View File
@@ -0,0 +1,154 @@
//! File ▸ Watch Folder…: render farm without a farm. EffectCraft watches a folder for project
//! files (`.ecproj`, at the top level or one folder down, e.g. the folders File ▸ Dependencies ▸
//! Collect Files writes) whose Render Queue has queued items, renders them, and writes a status
//! file next to each project (`<project>.status.json`: `rendering`, then `done` or `failed`, with
//! every item's status and output path). A project with a status file is not picked up again;
//! delete the status file to render it once more.
//!
//! [`poll`] does one pass and is what the frontends call on a timer while a folder is watched
//! (`file.watchFolder.poll`); it is headless and synchronous, so tests and the CLI use it
//! directly.
use std::path::{Path, PathBuf};
use effectcraft_project::render_queue::RenderStatus;
use serde_json::{Value, json};
use super::{CommandSpec, always, bad, str_p};
use crate::{Result, Session, cmd};
/// The status file of a project.
pub fn status_path(project: &Path) -> PathBuf {
let mut s = project.as_os_str().to_owned();
s.push(".status.json");
PathBuf::from(s)
}
/// Projects in `folder` (and its direct subfolders) without a status file, sorted.
pub fn pending(folder: &Path) -> std::io::Result<Vec<PathBuf>> {
let mut out = vec![];
let scan = |dir: &Path, out: &mut Vec<PathBuf>, subdirs: &mut Vec<PathBuf>| -> std::io::Result<()> {
for e in std::fs::read_dir(dir)? {
let p = e?.path();
if p.is_dir() {
subdirs.push(p);
} else if p.extension().is_some_and(|x| x.eq_ignore_ascii_case("ecproj")) && !status_path(&p).exists() {
out.push(p);
}
}
Ok(())
};
let mut subdirs = vec![];
scan(folder, &mut out, &mut subdirs)?;
for d in subdirs {
let mut ignore = vec![];
let _ = scan(&d, &mut out, &mut ignore);
}
out.sort();
Ok(out)
}
fn write_status(path: &Path, v: &Value) {
let _ = std::fs::write(status_path(path), serde_json::to_vec_pretty(v).unwrap_or_default());
}
fn now() -> u64 {
web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// Render one project (in its own session sharing `host`'s services) and write its status.
fn render_project(host: &Session, path: &Path) -> Value {
let name = path.to_string_lossy().to_string();
write_status(path, &json!({"project": name, "state": "rendering", "started": now()}));
let mut s = Session { services: host.services.clone(), footage: host.footage.clone(), expr: host.expr.clone(), ..Default::default() };
s.importer = host.importer.clone();
s.exporter = host.exporter.clone();
s.accel = host.accel.clone();
s.prefs = host.prefs.clone();
let result = (|| -> std::result::Result<Value, String> {
s.execute("file.open", json!({"path": name})).map_err(|e| e.to_string())?;
let queued = s.project.render_queue.iter().filter(|i| i.render && i.status == RenderStatus::Queued).count();
if queued == 0 {
return Ok(json!({"state": "done", "items": [], "note": "nothing queued"}));
}
s.start_render(true)?;
let items: Vec<Value> = s
.project
.render_queue
.iter()
.map(|i| {
json!({
"comp": s.project.item(i.comp).map(|c| c.name.clone()),
"status": i.status.label(),
"error": if let RenderStatus::Failed(e) = &i.status { Some(e.clone()) } else { None },
"output": i.last_output,
})
})
.collect();
let failed = s.project.render_queue.iter().any(|i| matches!(i.status, RenderStatus::Failed(_)));
Ok(json!({"state": if failed { "failed" } else { "done" }, "items": items}))
})();
let mut v = match result {
Ok(v) => v,
Err(e) => json!({"state": "failed", "error": e, "items": []}),
};
v["project"] = json!(name);
v["finished"] = json!(now());
write_status(path, &v);
v
}
/// One pass over `folder`: render every new project; returns their statuses.
pub fn poll(s: &mut Session, folder: &str) -> std::result::Result<Vec<Value>, String> {
let projects = pending(Path::new(folder)).map_err(|e| format!("cannot read {folder}: {e}"))?;
Ok(projects.iter().map(|p| render_project(s, p)).collect())
}
fn watch(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "file.watchFolder";
if p.get("stop").and_then(Value::as_bool) == Some(true) {
s.state.watch_folder = None;
s.bump();
return Ok(json!({"watching": null}));
}
let folder = str_p(p, "folder").or(str_p(p, "path")).ok_or_else(|| bad(C, "missing `folder`"))?.to_string();
if !Path::new(&folder).is_dir() {
return Err(bad(C, format!("{folder} is not a folder")));
}
s.state.watch_folder = Some(folder.clone());
s.bump();
// The first pass right away.
let done = poll(s, &folder).map_err(|e| bad(C, e))?;
s.toast(format!("Watching {folder}"));
Ok(json!({"watching": folder, "rendered": done}))
}
fn poll_cmd(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "file.watchFolder.poll";
let folder = str_p(p, "folder").map(str::to_string).or_else(|| s.state.watch_folder.clone()).ok_or_else(|| bad(C, "no folder is being watched"))?;
let done = poll(s, &folder).map_err(|e| bad(C, e))?;
Ok(json!({"watching": folder, "rendered": done}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"file.watchFolder",
"Watch Folder...",
["File"],
None,
"{folder, stop?: bool} → watches the folder for .ecproj files with queued renders, renders them and writes `<project>.status.json`",
always,
watch
),
cmd!(
"file.watchFolder.poll",
"Poll Watch Folder",
[],
None,
"{folder? (default: the watched one)} → renders new projects now: [{project, state: done|failed, items: [{comp, status, output}]}]",
|s: &Session| if s.state.watch_folder.is_some() { Ok(()) } else { Err("no folder is being watched".into()) },
poll_cmd
),
]
}
+19
View File
@@ -24,7 +24,9 @@ pub mod media_cache;
pub mod menus;
pub mod offload;
pub mod prefs;
pub mod preview;
pub mod psd_import;
pub mod remote;
pub mod render_queue;
pub mod roto;
pub mod scriptui;
@@ -218,6 +220,10 @@ pub struct EditorState {
/// Essential Graphics can expose).
#[serde(default)]
pub essential_solo: bool,
/// File ▸ Watch Folder: the folder being watched for projects to render (frontends call
/// `file.watchFolder.poll` periodically while it is set).
#[serde(default)]
pub watch_folder: Option<String>,
/// The Footage panel: the footage shown, its time and In/Out marks (source time).
#[serde(default)]
pub footage_panel: Option<commands::footage_panel::FootageView>,
@@ -348,6 +354,11 @@ pub struct Session {
pub offload: Option<Arc<dyn offload::Offload>>,
/// Analyses running in the [`Session::offload`] worker.
pub offloaded: Vec<offload::OffloadedJob>,
/// What the Media Browser browses (`None`: the local file system where there is one).
pub browser: Option<Arc<dyn media_browser::Browser>>,
/// Offloaded jobs that ended, newest last (kind, error): how a caller waiting for one
/// (`wait: true` over the control channel in the browser) learns its outcome.
pub offload_log: Vec<(offload::JobKind, Option<String>)>,
/// Generic background tasks (Content-Aware Fill, Scene Edit Detection), see [`jobs`].
pub tasks: Vec<jobs::Task>,
/// Finished tasks, newest last (Progress panel, `jobs.list`).
@@ -420,6 +431,8 @@ impl Default for Session {
applied_nested_switches: None,
offload: None,
offloaded: vec![],
offload_log: vec![],
browser: None,
tasks: vec![],
job_log: vec![],
next_task_id: 1,
@@ -787,12 +800,18 @@ mod tests_effects;
#[cfg(test)]
mod tests_essential;
#[cfg(test)]
mod tests_essential_more;
#[cfg(test)]
mod tests_face;
#[cfg(test)]
mod tests_fidelity;
#[cfg(test)]
mod tests_frame_export;
#[cfg(test)]
mod tests_lottie;
#[cfg(test)]
mod tests_m137;
#[cfg(test)]
mod tests_m145;
#[cfg(test)]
mod tests_markers;
+178 -4
View File
@@ -1,10 +1,16 @@
//! Media Browser (Window ▸ Media Browser): browse the local file system for footage, keep
//! favourite folders, read file metadata, and import (`file.import`). Desktop only: the web build
//! has no file system to browse ([`available`] is false there).
//! Media Browser (Window ▸ Media Browser): browse for footage, keep favourite folders, read file
//! metadata, and import (`file.import`).
//!
//! What it browses is a [`Browser`]: the local file system on the desktop ([`FsBrowser`]); in the
//! web app, a virtual tree ([`VirtualTree`]) of the browser's storage and of folders the user
//! opened through the File System Access API, whose files are read only when imported
//! ([`Browser::fetch`]).
//!
//! Also the metadata the Metadata panel shows for project items and files (codec, size, rate,
//! duration, colour profile, dates).
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -25,11 +31,153 @@ pub struct BrowserState {
pub importable_only: bool,
}
/// Whether this build can browse files.
/// Whether this build can browse the local file system ([`FsBrowser`]).
pub fn available() -> bool {
!cfg!(target_arch = "wasm32")
}
/// Where the Media Browser browses.
pub trait Browser: Send + Sync {
/// The folder shown first.
fn home(&self) -> String;
/// Places listed above the favourites: (name, folder). The default is Home.
fn places(&self) -> Vec<(String, String)> {
vec![("Home".into(), self.home())]
}
/// A folder's entries: folders first, then files, by name.
fn list(&self, dir: &str, importable_only: bool) -> Result<Vec<Entry>, String>;
/// The folder above `dir`.
fn parent(&self, dir: &str) -> Option<String> {
parent(dir)
}
/// Make `paths` readable by the importer. `false`: they are being fetched, and the host runs
/// `mediaBrowser.import` with `params` again once they are (the web app reads opened folders'
/// files on demand).
fn fetch(&self, paths: &[String], params: &Value) -> bool {
let _ = (paths, params);
true
}
/// Extra toolbar actions: (id, label), run by `mediaBrowser.action`.
fn actions(&self) -> Vec<(String, String)> {
vec![]
}
fn action(&self, id: &str) -> Result<Value, String> {
Err(format!("unknown Media Browser action `{id}`"))
}
}
/// The local file system (desktop).
pub struct FsBrowser;
impl Browser for FsBrowser {
fn home(&self) -> String {
home()
}
fn list(&self, dir: &str, importable_only: bool) -> Result<Vec<Entry>, String> {
list(dir, importable_only)
}
}
impl crate::Session {
/// What the Media Browser browses: [`crate::Session::browser`], else the local file system
/// where this build has one.
pub fn media_browser(&self) -> Option<std::sync::Arc<dyn Browser>> {
self.browser.clone().or_else(|| available().then(|| std::sync::Arc::new(FsBrowser) as std::sync::Arc<dyn Browser>))
}
}
/// One entry of a [`VirtualTree`].
#[derive(Clone, Debug, PartialEq)]
struct VNode {
/// What importing it reads (`None`: a folder).
import: Option<String>,
size: u64,
modified: Option<u64>,
}
/// A browsable tree of virtual paths (`/Folder/sub/file.mov`), each file standing for an
/// importable path (the web app's file table, or a file of an opened folder).
#[derive(Clone, Debug, Default)]
pub struct VirtualTree {
nodes: BTreeMap<String, VNode>,
}
fn vparent(path: &str) -> Option<&str> {
if path == "/" || path.is_empty() {
return None;
}
let p = path.trim_end_matches('/');
match p.rfind('/') {
Some(0) => Some("/"),
Some(i) => Some(&p[..i]),
None => None,
}
}
impl VirtualTree {
/// Add a folder (and the folders above it).
pub fn add_dir(&mut self, path: &str) {
let mut cur = Some(path.trim_end_matches('/'));
while let Some(p) = cur.filter(|p| !p.is_empty() && *p != "/") {
self.nodes.entry(p.to_string()).or_insert(VNode { import: None, size: 0, modified: None });
cur = vparent(p);
}
}
/// Add a file shown at `path` that imports `import`.
pub fn add_file(&mut self, path: &str, import: &str, size: u64, modified: Option<u64>) {
if let Some(p) = vparent(path) {
self.add_dir(p);
}
self.nodes.insert(path.to_string(), VNode { import: Some(import.to_string()), size, modified });
}
/// Remove `path` and everything under it.
pub fn remove(&mut self, path: &str) {
let pre = format!("{}/", path.trim_end_matches('/'));
self.nodes.retain(|k, _| k != path && !k.starts_with(&pre));
}
pub fn is_dir(&self, path: &str) -> bool {
path == "/" || self.nodes.get(path.trim_end_matches('/')).is_some_and(|n| n.import.is_none())
}
/// What a file shown at `path` imports.
pub fn import_path(&self, path: &str) -> Option<&str> {
self.nodes.get(path).and_then(|n| n.import.as_deref())
}
pub fn list(&self, dir: &str, importable_only: bool) -> Result<Vec<Entry>, String> {
let dir = if dir.len() > 1 { dir.trim_end_matches('/') } else { dir };
if !self.is_dir(dir) {
return Err(format!("{dir}: no such folder"));
}
let mut out: Vec<Entry> = self
.nodes
.iter()
.filter(|(k, _)| vparent(k) == Some(dir))
.filter_map(|(k, n)| {
let name = k.rsplit('/').next().unwrap_or(k).to_string();
let kind = n.import.as_deref().and_then(kind_of);
if importable_only && n.import.is_some() && kind.is_none() {
return None;
}
Some(Entry {
name,
// Folders browse by their virtual path; files import their own path.
path: n.import.clone().unwrap_or_else(|| k.clone()),
is_dir: n.import.is_none(),
size: n.size,
modified: n.modified,
kind,
})
})
.collect();
out.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())));
Ok(out)
}
}
/// One directory entry.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -261,6 +409,32 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn virtual_tree_lists_like_a_folder() {
let mut t = VirtualTree::default();
t.add_file("/Browser Storage/clip.mov", "/clip.mov", 10, Some(5));
t.add_file("/Folders/Shoot/B/b.png", "/Folders/Shoot/B/b.png", 3, None);
t.add_file("/Folders/Shoot/a.wav", "/Folders/Shoot/a.wav", 4, None);
t.add_file("/Folders/Shoot/notes.txt", "/Folders/Shoot/notes.txt", 1, None);
t.add_dir("/Folders/Empty");
let names = |t: &VirtualTree, d: &str, only: bool| t.list(d, only).unwrap().into_iter().map(|e| e.name).collect::<Vec<_>>();
assert_eq!(names(&t, "/", false), ["Browser Storage", "Folders"]);
assert_eq!(names(&t, "/Folders", false), ["Empty", "Shoot"]);
assert_eq!(names(&t, "/Folders/Shoot", false), ["B", "a.wav", "notes.txt"]);
assert_eq!(names(&t, "/Folders/Shoot/", true), ["B", "a.wav"]);
let e = &t.list("/Browser Storage", false).unwrap()[0];
assert_eq!((e.path.as_str(), e.size, e.modified, e.kind, e.is_dir), ("/clip.mov", 10, Some(5), Some("video"), false));
let d = &t.list("/Folders", false).unwrap()[1];
assert_eq!((d.path.as_str(), d.is_dir), ("/Folders/Shoot", true));
assert_eq!(t.import_path("/Browser Storage/clip.mov"), Some("/clip.mov"));
assert!(t.list("/Folders/Shoot/a.wav", false).is_err(), "a file is not a folder");
assert!(t.list("/Nope", false).is_err());
t.remove("/Folders/Shoot");
assert_eq!(names(&t, "/Folders", false), ["Empty"]);
assert_eq!(vparent("/a"), Some("/"));
assert_eq!(vparent("/"), None);
}
#[test]
fn iso_dates() {
assert_eq!(iso_date(0), "1970-01-01T00:00:00Z");
+10
View File
@@ -505,6 +505,7 @@ File
Placeholder... | file.importPlaceholder
Solid... | file.importSolid
Lottie... | file.importLottie
Vanishing Point (.vpe)... | file.importVanishingPoint
Essential Graphics Template... | essential.importTemplate
Import Recent Footage
@dynamic:recentFootage
@@ -528,6 +529,7 @@ File
Find Missing Effects | file.findMissing {"what":"effects"}
Find Missing Fonts | file.findMissing {"what":"fonts"}
Find Missing Footage | file.findMissing {"what":"footage"}
Watch Folder... | file.watchFolder
---
Scripts
@dynamic:scripts
@@ -664,9 +666,12 @@ Composition
Audio | playback.audio
Save Frame As
File... | comp.saveFrameAs
Photoshop Layers... | comp.saveFrameAsPsd
ProEXR... | comp.saveFrameAsExr
Pre-render... | render.preRender
Save Current Preview... | render.saveCurrentPreview
---
Open in Essential Graphics | comp.openInEssentialGraphics
Responsive Design — Time
Create Intro | comp.responsiveTime {"op":"intro"}
Create Outro | comp.responsiveTime {"op":"outro"}
@@ -1165,6 +1170,8 @@ Window
Timeline | window.panel {"panel":"timeline"}
@dynamic:openViewers
---
Create Nulls From Paths | window.panel {"panel":"createNullsFromPaths"}
VR Comp Editor | window.panel {"panel":"vrCompEditor"}
@dynamic:scriptPanels
Help
EffectCraft Help... | help.docs {"page":"help"} | F1
@@ -1174,6 +1181,9 @@ Help
Animation Presets... | anim.browsePresets
Keyboard Shortcuts... | app.keyboardShortcuts
---
In-App Tutorials... | help.inAppTutorials
Online Tutorials... | help.onlineTutorials
---
System Compatibility Report... | help.systemReport
Enable Logging | help.enableLogging
Reveal Logging File | help.revealLogFile
+121 -9
View File
@@ -16,10 +16,11 @@
//! | Track Motion / Stabilize Motion | the tracker analysis | the tracker group |
//! | Mask tracking | the mask track | the mask group |
//! | Roto Brush Freeze | the freeze | the effect group |
//! | Roto Brush propagation | the propagation | segmentations ([`WorkerReply::Segs`], streamed while it runs) go into the page's segmentation cache |
//! | 3D Camera Tracker analysis | [`Session::start_camera`] | the effect's property group |
//!
//! Roto Brush propagation fills the session's segmentation cache rather than the project, so it
//! keeps running on the UI thread.
//! Viewer frames go to a separate, long-lived frame worker fed with project diffs
//! ([`crate::remote`]).
//!
//! Cancelling terminates the worker: what an analysis tracked so far is dropped and the Render
//! Queue item being rendered becomes "User Stopped".
@@ -76,6 +77,13 @@ pub enum WorkerJob {
layer: LayerId,
effect: Uid,
},
/// Roto Brush propagation: the segmentations come back as [`WorkerReply::Segs`].
RotoPropagate {
comp: ItemId,
layer: LayerId,
effect: Uid,
direction: crate::roto::Direction,
},
Track {
comp: ItemId,
layer: LayerId,
@@ -103,6 +111,7 @@ impl WorkerJob {
WorkerJob::Warp { .. } => JobKind::Warp,
WorkerJob::Camera { .. } => JobKind::Camera,
WorkerJob::RotoFreeze { .. } => JobKind::RotoFreeze,
WorkerJob::RotoPropagate { .. } => JobKind::RotoPropagate,
WorkerJob::Track { .. } => JobKind::Track,
WorkerJob::MaskTrack { .. } => JobKind::MaskTrack,
}
@@ -112,9 +121,10 @@ impl WorkerJob {
pub fn target(&self) -> Option<(ItemId, LayerId, Uid)> {
match *self {
WorkerJob::Render { .. } => None,
WorkerJob::Warp { comp, layer, effect } | WorkerJob::Camera { comp, layer, effect } | WorkerJob::RotoFreeze { comp, layer, effect } => {
Some((comp, layer, effect))
}
WorkerJob::Warp { comp, layer, effect }
| WorkerJob::Camera { comp, layer, effect }
| WorkerJob::RotoFreeze { comp, layer, effect }
| WorkerJob::RotoPropagate { comp, layer, effect, .. } => Some((comp, layer, effect)),
WorkerJob::Track { comp, layer, tracker, .. } => Some((comp, layer, tracker)),
WorkerJob::MaskTrack { comp, layer, mask, .. } => Some((comp, layer, mask)),
}
@@ -128,6 +138,7 @@ pub enum JobKind {
Warp,
Camera,
RotoFreeze,
RotoPropagate,
Track,
MaskTrack,
}
@@ -140,6 +151,7 @@ impl JobKind {
JobKind::Warp => "Warp Stabilizer Analysis",
JobKind::Camera => "3D Camera Tracker Analysis",
JobKind::RotoFreeze => "Freeze",
JobKind::RotoPropagate => "Roto Brush Propagation",
JobKind::Track => "Analyze Track",
JobKind::MaskTrack => "Track Mask",
}
@@ -170,6 +182,10 @@ pub enum WorkerReply {
group: Box<PropGroup>,
message: String,
},
/// Roto Brush segmentations computed so far (propagation), not sent before.
Segs {
segs: Vec<SegData>,
},
Failed {
error: String,
},
@@ -177,6 +193,41 @@ pub enum WorkerReply {
Done,
}
/// One full-resolution Roto Brush segmentation: its chain key and the base64 of
/// [`effectcraft_track::roto::FrameSeg::to_bytes`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SegData {
pub key: u64,
pub data: String,
}
impl SegData {
pub fn new(key: u64, seg: &effectcraft_track::roto::FrameSeg) -> SegData {
SegData { key, data: effectcraft_track::roto::rle::base64_encode(&seg.to_bytes()) }
}
/// Put the segmentation into this instance's cache (what the Roto Brush effect renders from).
pub fn store(&self) -> bool {
let Some(seg) = effectcraft_track::roto::rle::base64_decode(&self.data).and_then(|b| effectcraft_track::roto::FrameSeg::from_bytes(&b)) else {
return false;
};
effectcraft_effects::roto::store(self.key, 1.0, Arc::new(seg));
true
}
}
/// The full-resolution segmentations of `keys` that are cached here and not in `sent` yet.
pub fn segs_to_send(keys: &[u64], sent: &mut std::collections::HashSet<u64>) -> Vec<SegData> {
let new: Vec<(u64, Arc<effectcraft_track::roto::FrameSeg>)> =
keys.iter().filter(|k| !sent.contains(k)).filter_map(|k| effectcraft_effects::roto::cached(*k, 1.0).map(|s| (*k, s))).collect();
new.into_iter()
.map(|(k, s)| {
sent.insert(k);
SegData::new(k, &s)
})
.collect()
}
/// Replies waiting for the UI thread.
#[derive(Default)]
pub struct Inbox(Mutex<Vec<WorkerReply>>);
@@ -292,6 +343,7 @@ fn run_job(s: &mut Session, job: WorkerJob, post: Post) -> Result<(), String> {
WorkerJob::RotoFreeze { comp, layer, effect } => analysis(s, kind, target, post, |s| {
s.start_roto(comp, layer, effect, crate::roto::RotoTask::Freeze, crate::roto::Direction::Both, true).map(|_| ())
}),
WorkerJob::RotoPropagate { comp, layer, effect, direction } => propagate(s, comp, layer, effect, direction, post),
WorkerJob::Track { comp, layer, tracker, direction, settings, points, times } => analysis(s, kind, target, post, |s| {
let work = crate::tracking::Work {
project: s.project.clone(),
@@ -323,6 +375,38 @@ fn run_job(s: &mut Session, job: WorkerJob, post: Post) -> Result<(), String> {
}
}
/// Roto Brush propagation in a worker: the segmentations stream back (at most every 250 ms)
/// as they are computed, so stopping the job keeps what was propagated.
fn propagate(s: &mut Session, comp: ItemId, layer: LayerId, effect: Uid, dir: crate::roto::Direction, post: Post) -> Result<(), String> {
let keys: Vec<u64> = s.roto_chain(comp, layer, effect).map(|c| c.keys.values().copied().collect()).ok_or("no Roto Brush strokes")?;
let sent = Rc::new(RefCell::new(std::collections::HashSet::new()));
let (p, k2, s2) = (post.clone(), keys.clone(), sent.clone());
let mut last = None::<web_time::Instant>;
let hook = Box::new(move |done: u64, total: u64| {
if last.is_none_or(|t: web_time::Instant| t.elapsed().as_millis() >= 250) {
last = Some(web_time::Instant::now());
let segs = segs_to_send(&k2, &mut s2.borrow_mut());
if !segs.is_empty() {
p(WorkerReply::Segs { segs });
}
p(WorkerReply::Progress { done, total });
}
});
s.events.clear();
with_hook(hook, || s.start_roto(comp, layer, effect, crate::roto::RotoTask::Propagate, dir, true))?;
let segs = segs_to_send(&keys, &mut sent.borrow_mut());
if !segs.is_empty() {
post(WorkerReply::Segs { segs });
}
if let Some(e) = s.events.iter().find_map(|e| match e {
Event::Toast { message, error: true } => Some(message.clone()),
_ => None,
}) {
return Err(e);
}
Ok(())
}
fn analysis(
s: &mut Session,
kind: JobKind,
@@ -398,6 +482,8 @@ pub struct OffloadedJob {
pub uid: Uid,
pub inbox: Arc<Inbox>,
pub progress: OffloadProgress,
/// Segmentations received (Roto Brush propagation).
pub segs: u64,
started: web_time::Instant,
}
@@ -432,7 +518,17 @@ impl Session {
let inbox = Arc::new(Inbox::default());
let req = WorkerRequest { id, project: self.project.to_json(), files: footage_files(&self.project), job };
off.start(req, inbox.clone())?;
self.offloaded.push(OffloadedJob { id, kind, comp, layer, uid, inbox, progress: OffloadProgress::default(), started: web_time::Instant::now() });
self.offloaded.push(OffloadedJob {
id,
kind,
comp,
layer,
uid,
inbox,
progress: OffloadProgress::default(),
segs: 0,
started: web_time::Instant::now(),
});
self.events.push(Event::ProjectChanged { revision: self.revision });
Ok(())
}
@@ -469,6 +565,12 @@ impl Session {
j.progress.total = total;
}
WorkerReply::Group { comp, layer, group, message } => results.push((j.kind, comp, layer, group, message)),
WorkerReply::Segs { segs } => {
for sd in &segs {
sd.store();
}
j.segs += segs.len() as u64;
}
WorkerReply::Failed { error } => j.progress.error = Some(error),
WorkerReply::Done => j.progress.finished = true,
WorkerReply::Render { .. } | WorkerReply::Item { .. } => {}
@@ -495,17 +597,25 @@ impl Session {
let mut done = vec![];
self.offloaded.retain(|j| {
if j.progress.finished {
done.push((j.kind, j.progress.clone()));
done.push((j.kind, j.progress.clone(), j.segs));
}
!j.progress.finished
});
for (kind, p) in done {
for (kind, p, segs) in done {
changed = true;
self.offload_log.push((kind, p.error.clone().or_else(|| p.cancelled.then(|| "stopped".to_string()))));
if self.offload_log.len() > 32 {
self.offload_log.remove(0);
}
if let Some(e) = p.error {
self.events.push(Event::Toast { message: format!("{}: {e}", kind.label()), error: true });
} else if p.cancelled {
self.events.push(Event::Toast { message: format!("{} stopped", kind.label()), error: false });
let kept = if segs > 0 { format!(" ({segs} frame(s) kept)") } else { String::new() };
self.events.push(Event::Toast { message: format!("{} stopped{kept}", kind.label()), error: false });
} else if kind == JobKind::RotoPropagate {
self.events.push(Event::Toast { message: format!("Roto Brush: propagated {} frame(s) in {:.1} s", segs, p.elapsed), error: false });
}
// Rendered frames depend on the result (an analysis' group, the segmentation cache).
self.bump();
}
changed
@@ -567,6 +677,7 @@ mod tests {
WorkerJob::Warp { comp, layer: LayerId(3), effect: 9 },
WorkerJob::RotoFreeze { comp, layer: LayerId(3), effect: 9 },
WorkerJob::Camera { comp, layer: LayerId(3), effect: 9 },
WorkerJob::RotoPropagate { comp, layer: LayerId(3), effect: 9, direction: crate::roto::Direction::Forward },
WorkerJob::Track {
comp,
layer: LayerId(1),
@@ -606,6 +717,7 @@ mod tests {
WorkerReply::Item { update: ItemUpdate::Finished { id: 3, status: RenderStatus::Failed("x".into()), seconds: 1.5, output: Some("/a.gif".into()) } },
WorkerReply::Progress { done: 1, total: 2 },
WorkerReply::Group { comp, layer: LayerId(1), group: Box::new(g), message: "ok".into() },
WorkerReply::Segs { segs: vec![SegData::new(5, &effectcraft_track::roto::FrameSeg::empty(4, 3))] },
WorkerReply::Failed { error: "boom".into() },
WorkerReply::Done,
] {
+4
View File
@@ -281,6 +281,8 @@ pub struct Prefs {
pub recent_presets: Vec<String>,
/// Character panel: recently used font families, newest first.
pub recent_fonts: Vec<String>,
/// Preview panel: every shortcut's options.
pub preview: crate::preview::PreviewSettings,
/// Top-level keys this version doesn't know (kept for newer versions).
#[serde(flatten)]
pub extra: Extra,
@@ -312,6 +314,7 @@ impl Default for Prefs {
recent_footage: vec![],
recent_presets: vec![],
recent_fonts: vec![],
preview: crate::preview::PreviewSettings::default(),
extra: Extra::new(),
}
}
@@ -446,6 +449,7 @@ impl Prefs {
recent_footage: std::mem::take(&mut self.recent_footage),
recent_presets: std::mem::take(&mut self.recent_presets),
recent_fonts: std::mem::take(&mut self.recent_fonts),
preview: std::mem::take(&mut self.preview),
..d
};
return Ok(());
+550
View File
@@ -0,0 +1,550 @@
//! Preview panel settings (After Effects' Preview panel): five keyboard shortcuts (Spacebar,
//! Shift+Spacebar, Numpad 0, Shift+Numpad 0, Alt+Numpad 0), each with its own saved options —
//! what to include (video, audio, overlays, layer controls), Loop, Cache Before Playback, Range,
//! Play From, Frame Rate, Skip, Resolution, Full Screen, "If caching, play cached frames" and
//! "Move time to preview time".
//!
//! The settings live in [`crate::prefs::Prefs::preview`] (saved with the other settings).
//! [`plan`] turns one shortcut's options, a comp and the current time into the frames to play;
//! the frontend's playback loop follows the plan.
//!
//! Commands: `playback.settings.get {shortcut?}`, `playback.settings.set {shortcut?, values?,
//! <field>: value…, current?}`.
use effectcraft_project::Comp;
use effectcraft_time::Tick;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::commands::{CommandSpec, always, bad, str_p};
use crate::{Result, Session, cmd, query};
/// A Preview panel shortcut.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PreviewShortcut {
#[default]
Spacebar,
ShiftSpacebar,
Numpad0,
ShiftNumpad0,
AltNumpad0,
}
impl PreviewShortcut {
pub const ALL: [PreviewShortcut; 5] = [Self::Spacebar, Self::ShiftSpacebar, Self::Numpad0, Self::ShiftNumpad0, Self::AltNumpad0];
pub fn label(self) -> &'static str {
match self {
Self::Spacebar => "Spacebar",
Self::ShiftSpacebar => "Shift+Spacebar",
Self::Numpad0 => "Numpad 0",
Self::ShiftNumpad0 => "Shift+Numpad 0",
Self::AltNumpad0 => "Alt+Numpad 0",
}
}
pub fn id(self) -> &'static str {
match self {
Self::Spacebar => "spacebar",
Self::ShiftSpacebar => "shiftSpacebar",
Self::Numpad0 => "numpad0",
Self::ShiftNumpad0 => "shiftNumpad0",
Self::AltNumpad0 => "altNumpad0",
}
}
/// From an id (`shiftSpacebar`) or a label (`Shift+Spacebar`).
pub fn parse(s: &str) -> Option<Self> {
let k = s.to_ascii_lowercase().replace([' ', '+', '-', '_'], "");
Self::ALL.into_iter().find(|x| x.id().to_ascii_lowercase() == k || x.label().to_ascii_lowercase().replace([' ', '+'], "") == k)
}
}
/// Range of a preview.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PreviewRange {
WorkArea,
#[default]
WorkAreaExtended,
EntireDuration,
/// The pre-roll before and post-roll after the current time.
AroundCurrentTime,
}
impl PreviewRange {
pub const ALL: [PreviewRange; 4] = [Self::WorkArea, Self::WorkAreaExtended, Self::EntireDuration, Self::AroundCurrentTime];
pub fn label(self) -> &'static str {
match self {
Self::WorkArea => "Work Area",
Self::WorkAreaExtended => "Work Area Extended By Current Time",
Self::EntireDuration => "Entire Duration",
Self::AroundCurrentTime => "Play Around Current Time",
}
}
}
/// Where playback starts.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PlayFrom {
RangeStart,
#[default]
CurrentTime,
}
impl PlayFrom {
pub const ALL: [PlayFrom; 2] = [Self::RangeStart, Self::CurrentTime];
pub fn label(self) -> &'static str {
match self {
Self::RangeStart => "Range Start",
Self::CurrentTime => "Current Time",
}
}
}
/// Resolution of a preview (Auto: the viewer's own).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum PreviewResolution {
#[default]
Auto,
Full,
Half,
Third,
Quarter,
/// Every n-th pixel ([`PreviewPreset::custom_resolution`]).
Custom,
}
impl PreviewResolution {
pub const ALL: [PreviewResolution; 6] = [Self::Auto, Self::Full, Self::Half, Self::Third, Self::Quarter, Self::Custom];
pub fn label(self) -> &'static str {
match self {
Self::Auto => "Auto",
Self::Full => "Full",
Self::Half => "Half",
Self::Third => "Third",
Self::Quarter => "Quarter",
Self::Custom => "Custom",
}
}
/// Pixel step (1 Full … 4 Quarter, `custom` for Custom); `None` for Auto.
pub fn factor(self, custom: u32) -> Option<u32> {
match self {
Self::Auto => None,
Self::Full => Some(1),
Self::Half => Some(2),
Self::Third => Some(3),
Self::Quarter => Some(4),
Self::Custom => Some(custom.clamp(1, 40)),
}
}
}
/// The options of one shortcut.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PreviewPreset {
pub include_video: bool,
pub include_audio: bool,
/// Grids, guides and safe margins stay visible while playing.
pub include_overlays: bool,
/// Layer handles, paths and motion paths stay visible while playing.
pub include_layer_controls: bool,
#[serde(rename = "loop")]
pub loop_: bool,
/// Render the whole range before playing it.
pub cache_before_playback: bool,
pub range: PreviewRange,
/// Play Around Current Time: seconds before and after the current time.
pub pre_roll: f64,
pub post_roll: f64,
pub play_from: PlayFrom,
/// Frames per second; `None` = Auto (the comp's rate).
pub frame_rate: Option<f64>,
/// Frames skipped between the frames played (0 = every frame).
pub skip: u32,
pub resolution: PreviewResolution,
/// Custom resolution: render every n-th pixel (1–40).
pub custom_resolution: u32,
/// Play in a full-screen viewer.
pub full_screen: bool,
/// With Cache Before Playback, pressing the shortcut again while caching plays the frames
/// already cached.
pub play_cached_frames: bool,
/// When the preview stops, the current time moves to the last frame shown (off: it returns
/// to where the preview started).
pub move_time_to_preview_time: bool,
}
impl Default for PreviewPreset {
fn default() -> Self {
PreviewPreset {
include_video: true,
include_audio: true,
include_overlays: true,
include_layer_controls: false,
loop_: true,
cache_before_playback: false,
range: PreviewRange::WorkAreaExtended,
pre_roll: 2.0,
post_roll: 2.0,
play_from: PlayFrom::CurrentTime,
frame_rate: None,
skip: 0,
resolution: PreviewResolution::Auto,
custom_resolution: 2,
full_screen: false,
play_cached_frames: true,
move_time_to_preview_time: true,
}
}
}
impl PreviewPreset {
/// The factory options of a shortcut.
pub fn default_for(s: PreviewShortcut) -> Self {
let d = PreviewPreset::default();
match s {
PreviewShortcut::Spacebar => d,
// A lighter preview: every other frame.
PreviewShortcut::ShiftSpacebar => PreviewPreset { skip: 1, ..d },
PreviewShortcut::Numpad0 => PreviewPreset { range: PreviewRange::WorkArea, play_from: PlayFrom::RangeStart, ..d },
PreviewShortcut::ShiftNumpad0 => {
PreviewPreset { range: PreviewRange::WorkArea, play_from: PlayFrom::RangeStart, skip: 1, resolution: PreviewResolution::Half, ..d }
}
// Audio only.
PreviewShortcut::AltNumpad0 => PreviewPreset { include_video: false, range: PreviewRange::WorkArea, play_from: PlayFrom::RangeStart, ..d },
}
}
fn normalize(&mut self) {
self.pre_roll = if self.pre_roll.is_finite() { self.pre_roll.clamp(0.0, 3600.0) } else { 2.0 };
self.post_roll = if self.post_roll.is_finite() { self.post_roll.clamp(0.0, 3600.0) } else { 2.0 };
self.frame_rate = self.frame_rate.filter(|r| r.is_finite() && *r > 0.0).map(|r| r.clamp(0.01, 999.0));
self.skip = self.skip.min(99);
self.custom_resolution = self.custom_resolution.clamp(1, 40);
if !self.include_video && !self.include_audio {
self.include_video = true;
}
}
}
/// The Preview panel: the shortcut shown in the panel and every shortcut's options.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PreviewSettings {
/// The shortcut whose options the panel shows (and the play button uses).
pub current: PreviewShortcut,
pub spacebar: PreviewPreset,
pub shift_spacebar: PreviewPreset,
pub numpad0: PreviewPreset,
pub shift_numpad0: PreviewPreset,
pub alt_numpad0: PreviewPreset,
}
impl Default for PreviewSettings {
fn default() -> Self {
use PreviewShortcut as S;
PreviewSettings {
current: S::Spacebar,
spacebar: PreviewPreset::default_for(S::Spacebar),
shift_spacebar: PreviewPreset::default_for(S::ShiftSpacebar),
numpad0: PreviewPreset::default_for(S::Numpad0),
shift_numpad0: PreviewPreset::default_for(S::ShiftNumpad0),
alt_numpad0: PreviewPreset::default_for(S::AltNumpad0),
}
}
}
impl PreviewSettings {
pub fn get(&self, s: PreviewShortcut) -> &PreviewPreset {
match s {
PreviewShortcut::Spacebar => &self.spacebar,
PreviewShortcut::ShiftSpacebar => &self.shift_spacebar,
PreviewShortcut::Numpad0 => &self.numpad0,
PreviewShortcut::ShiftNumpad0 => &self.shift_numpad0,
PreviewShortcut::AltNumpad0 => &self.alt_numpad0,
}
}
pub fn get_mut(&mut self, s: PreviewShortcut) -> &mut PreviewPreset {
match s {
PreviewShortcut::Spacebar => &mut self.spacebar,
PreviewShortcut::ShiftSpacebar => &mut self.shift_spacebar,
PreviewShortcut::Numpad0 => &mut self.numpad0,
PreviewShortcut::ShiftNumpad0 => &mut self.shift_numpad0,
PreviewShortcut::AltNumpad0 => &mut self.alt_numpad0,
}
}
/// The options of the shortcut shown in the panel.
pub fn active(&self) -> &PreviewPreset {
self.get(self.current)
}
}
/// What a preview plays: frames `start..=end` (comp frames), starting at `first`, every
/// `step`-th frame, `fps` frames shown per second.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PreviewPlan {
pub start: i64,
pub end: i64,
pub first: i64,
pub step: i64,
/// Comp frames advanced per second of playback (the frame rate; Skip doesn't change speed).
pub fps: f64,
pub looping: bool,
pub cache_first: bool,
pub video: bool,
pub audio: bool,
/// Where the current time goes when the preview stops without moving it.
pub origin: Tick,
}
impl PreviewPlan {
/// The frame shown `elapsed` seconds after the start; `None` once a non-looping preview has
/// played to its end.
pub fn frame_at(&self, elapsed: f64) -> Option<i64> {
let n = ((elapsed.max(0.0) * self.fps) / self.step as f64).floor() as i64;
self.frame_after(self.first, n)
}
/// The frame `n` played frames after `from` (wrapping when looping).
pub fn frame_after(&self, from: i64, n: i64) -> Option<i64> {
let f = from + n * self.step;
if f <= self.end {
return Some(f);
}
if !self.looping {
return None;
}
// Loop back to the range start on the skip grid.
let len = ((self.end - self.start) / self.step + 1).max(1);
let past = (f - self.end - 1) / self.step;
Some(self.start + past.rem_euclid(len) * self.step)
}
/// Every frame the preview shows, in range order.
pub fn frames(&self) -> impl Iterator<Item = i64> + '_ {
(self.start..=self.end).step_by(self.step.max(1) as usize)
}
}
/// The plan of a preview of `comp` with options `p`, started at comp time `now`.
pub fn plan(p: &PreviewPreset, comp: &Comp, now: Tick) -> PreviewPlan {
let fr = comp.frame_rate;
let last = fr.frame_at(comp.duration - comp.frame_duration()).max(0);
let cur = fr.frame_at(now).clamp(0, last);
let (wa, wb) = (fr.frame_at(comp.work_area.0), fr.frame_at(comp.work_area.1 - comp.frame_duration()));
let (wa, wb) = (wa.clamp(0, last), wb.clamp(0, last).max(wa.clamp(0, last)));
let (start, end) = match p.range {
PreviewRange::WorkArea => (wa, wb),
PreviewRange::WorkAreaExtended => (wa.min(cur), wb.max(cur)),
PreviewRange::EntireDuration => (0, last),
PreviewRange::AroundCurrentTime => {
let pre = (p.pre_roll * fr.as_f64()).round() as i64;
let post = (p.post_roll * fr.as_f64()).round() as i64;
((cur - pre).max(0), (cur + post).min(last))
}
};
let step = p.skip as i64 + 1;
let first = match p.play_from {
PlayFrom::RangeStart => start,
// From the current time when it is inside the range (and not on its last frame).
PlayFrom::CurrentTime if cur >= start && cur < end => start + (cur - start) / step * step,
PlayFrom::CurrentTime => start,
};
PreviewPlan {
start,
end,
first,
step,
fps: p.frame_rate.unwrap_or_else(|| fr.as_f64()),
looping: p.loop_,
cache_first: p.cache_before_playback,
video: p.include_video,
audio: p.include_audio,
origin: now,
}
}
fn shortcut_p(s: &Session, p: &Value, cmd: &str) -> Result<PreviewShortcut> {
match str_p(p, "shortcut") {
Some(k) => {
PreviewShortcut::parse(k).ok_or_else(|| bad(cmd, format!("unknown shortcut `{k}` (spacebar|shiftSpacebar|numpad0|shiftNumpad0|altNumpad0)")))
}
None => Ok(s.prefs.preview.current),
}
}
fn get(s: &mut Session, p: &Value) -> Result<Value> {
let sc = shortcut_p(s, p, "playback.settings.get")?;
let mut out = serde_json::to_value(s.prefs.preview.get(sc)).map_err(|e| bad("playback.settings.get", e.to_string()))?;
out["shortcut"] = json!(sc.id());
out["current"] = json!(s.prefs.preview.current.id());
if let Some(c) = s.active_comp() {
let pl = plan(s.prefs.preview.get(sc), c, s.time());
out["plan"] = json!({"start": pl.start, "end": pl.end, "first": pl.first, "step": pl.step, "fps": pl.fps});
}
Ok(out)
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let c = "playback.settings.set";
let sc = shortcut_p(s, p, c)?;
let mut fields = serde_json::Map::new();
if let Some(Value::Object(m)) = p.get("values") {
fields.extend(m.clone());
}
if let Value::Object(m) = p {
for (k, v) in m {
if !matches!(k.as_str(), "shortcut" | "values" | "current" | "reset") {
fields.insert(k.clone(), v.clone());
}
}
}
let mut next = s.prefs.preview.clone();
if p.get("reset").and_then(Value::as_bool) == Some(true) {
*next.get_mut(sc) = PreviewPreset::default_for(sc);
}
let mut cur = serde_json::to_value(next.get(sc)).map_err(|e| bad(c, e.to_string()))?;
for (k, v) in fields {
if cur.get(&k).is_none() {
return Err(bad(c, format!("unknown preview setting `{k}`")));
}
// Frame rate: a number, or "auto"/null.
let v = if k == "frameRate" && (v.is_null() || v.as_str().is_some_and(|x| x.eq_ignore_ascii_case("auto"))) { Value::Null } else { v };
cur[k.as_str()] = v;
}
let mut pr: PreviewPreset = serde_json::from_value(cur).map_err(|e| bad(c, e.to_string()))?;
pr.normalize();
*next.get_mut(sc) = pr;
if let Some(k) = str_p(p, "current") {
next.current = PreviewShortcut::parse(k).ok_or_else(|| bad(c, format!("unknown shortcut `{k}`")))?;
} else if p.get("shortcut").is_some() && p.as_object().is_some_and(|m| m.len() == 1) {
// `{shortcut}` alone shows that shortcut in the panel.
next.current = sc;
}
s.prefs.preview = next;
s.save_prefs();
get(s, &json!({"shortcut": sc.id()}))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
query!(
"playback.settings.get",
"Preview Settings",
"{shortcut?: spacebar|shiftSpacebar|numpad0|shiftNumpad0|altNumpad0 (default: the one shown in the Preview panel)} → options + plan {start, end, first, step, fps}",
get
),
cmd!(
"playback.settings.set",
"Change Preview Settings",
[],
None,
"{shortcut?, current?: shortcut shown in the panel, reset?: bool, values?: {…}, includeVideo?, includeAudio?, includeOverlays?, includeLayerControls?, loop?, cacheBeforePlayback?, range?: workArea|workAreaExtended|entireDuration|aroundCurrentTime, preRoll?, postRoll?: seconds, playFrom?: rangeStart|currentTime, frameRate?: fps|\"auto\", skip?, resolution?: auto|full|half|third|quarter|custom, customResolution?, fullScreen?, playCachedFrames?, moveTimeToPreviewTime?}",
always,
set
),
]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Session;
fn comp_session() -> Session {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "C", "width": 320, "height": 180, "frameRate": 24, "duration": 10})).unwrap();
s
}
#[test]
fn ranges_and_play_from() {
let mut s = comp_session();
let mut c = s.active_comp().unwrap().clone();
c.work_area = (Tick::from_seconds_f64(2.0), Tick::from_seconds_f64(4.0));
let at = |sec: f64| Tick::from_seconds_f64(sec);
let mut p = PreviewPreset { range: PreviewRange::WorkArea, play_from: PlayFrom::RangeStart, ..Default::default() };
let pl = plan(&p, &c, at(1.0));
assert_eq!((pl.start, pl.end, pl.first), (48, 95, 48));
// Extended by the current time (before the work area).
p.range = PreviewRange::WorkAreaExtended;
let pl = plan(&p, &c, at(1.0));
assert_eq!((pl.start, pl.end), (24, 95));
// ... and after it.
let pl = plan(&p, &c, at(6.0));
assert_eq!((pl.start, pl.end), (48, 144));
p.range = PreviewRange::EntireDuration;
p.play_from = PlayFrom::CurrentTime;
let pl = plan(&p, &c, at(5.0));
assert_eq!((pl.start, pl.end, pl.first), (0, 239, 120));
p.range = PreviewRange::AroundCurrentTime;
p.pre_roll = 1.0;
p.post_roll = 0.5;
let pl = plan(&p, &c, at(5.0));
assert_eq!((pl.start, pl.end, pl.first), (96, 132, 120));
// Pre-roll clamps at the comp start.
let pl = plan(&p, &c, at(0.25));
assert_eq!(pl.start, 0);
s.execute("playback.settings.set", json!({"range": "workArea"})).unwrap();
}
#[test]
fn skip_rate_and_loop() {
let s = comp_session();
let c = s.active_comp().unwrap().clone();
let p = PreviewPreset { range: PreviewRange::EntireDuration, play_from: PlayFrom::RangeStart, skip: 2, frame_rate: Some(12.0), ..Default::default() };
let pl = plan(&p, &c, Tick::ZERO);
assert_eq!(pl.step, 3);
assert_eq!(pl.fps, 12.0);
// 12 comp frames per second, every third shown.
assert_eq!(pl.frame_at(0.0), Some(0));
assert_eq!(pl.frame_at(0.26), Some(3));
assert_eq!(pl.frame_at(1.0), Some(12));
assert!(pl.frames().all(|f| f % 3 == 0));
// Loop wraps onto the skip grid; no loop ends.
assert_eq!(pl.frame_after(237, 1), Some(0));
let pl = PreviewPlan { looping: false, ..pl };
assert_eq!(pl.frame_after(237, 1), None);
}
#[test]
fn settings_commands_round_trip() {
let mut s = comp_session();
let r = s.execute("playback.settings.get", json!({})).unwrap();
assert_eq!(r["shortcut"], "spacebar");
assert_eq!(r["range"], "workAreaExtended");
// Each shortcut keeps its own options.
let r = s
.execute("playback.settings.set", json!({"shortcut": "shiftNumpad0", "skip": 3, "frameRate": 15, "resolution": "quarter", "loop": false}))
.unwrap();
assert_eq!(r["skip"], 3);
assert_eq!(r["frameRate"], 15.0);
assert_eq!(r["plan"]["step"], 4);
let sp = s.execute("playback.settings.get", json!({"shortcut": "Spacebar"})).unwrap();
assert_eq!(sp["skip"], 0);
assert_eq!(sp["frameRate"], Value::Null);
// Auto rate, panel shortcut, reset.
s.execute("playback.settings.set", json!({"shortcut": "shiftNumpad0", "frameRate": "auto", "current": "shiftNumpad0"})).unwrap();
assert_eq!(s.prefs.preview.current, PreviewShortcut::ShiftNumpad0);
assert_eq!(s.prefs.preview.shift_numpad0.frame_rate, None);
assert!(s.execute("playback.settings.set", json!({"bogus": 1})).is_err());
assert!(s.execute("playback.settings.set", json!({"shortcut": "f13"})).is_err());
s.execute("playback.settings.set", json!({"shortcut": "shiftNumpad0", "reset": true})).unwrap();
assert_eq!(s.prefs.preview.shift_numpad0, PreviewPreset::default_for(PreviewShortcut::ShiftNumpad0));
// Persisted with the settings.
let v: Value = serde_json::from_str(&s.prefs.to_json()).unwrap();
assert_eq!(v["preview"]["current"], "shiftNumpad0");
let back: crate::prefs::Prefs = serde_json::from_value(v).unwrap();
assert_eq!(back.preview, s.prefs.preview);
}
#[test]
fn shortcut_names() {
for s in PreviewShortcut::ALL {
assert_eq!(PreviewShortcut::parse(s.id()), Some(s));
assert_eq!(PreviewShortcut::parse(s.label()), Some(s));
}
}
}
+22 -3
View File
@@ -158,7 +158,7 @@ fn footage_item(proj: &mut Project, cx: &mut Ctx, index: usize, name: &str) -> (
missing: false,
sequence: vec![],
color_profile: None,
layer: Some(SourceLayer { index: index as u32, name: name.to_string(), layer_size: retain && !l.rect.is_empty(), embedded: None }),
layer: Some(SourceLayer { index: index as u32, name: name.to_string(), layer_size: retain && !l.rect.is_empty(), embedded: None, placed: false }),
..Default::default()
};
let id = proj.add_item(&format!("{name}/{file}"), Label::Lavender, Some(cx.folder), ItemKind::Footage(f));
@@ -191,8 +191,20 @@ fn smart_object_layer(proj: &mut Project, cx: &mut Ctx, comp: &Comp, index: usiz
let pl = &cx.psd.layers[index];
let so = pl.smart_object.clone()?;
let data = cx.psd.linked_data(&so.uuid)?;
let (w, h) = embedded_size(&so, data).filter(|s| s.0 > 0 && s.1 > 0)?;
let (cw, ch) = embedded_size(&so, data).filter(|s| s.0 > 0 && s.1 > 0)?;
let file = cx.psd.linked.iter().find(|f| f.uuid == so.uuid).map(|f| f.name.clone()).unwrap_or_default();
// Perspective quads and warps are baked over the placed bounds, at up to 4× the document
// resolution when the embedded content has that much detail.
let bake = so.needs_bake();
let (w, h, k, bounds) = if bake {
let bb = so.placed_bounds(cw as f64, ch as f64);
let area = ((bb[2] - bb[0]) * (bb[3] - bb[1])).max(1.0);
let k = ((cw as f64 * ch as f64) / area).sqrt().clamp(1.0, 4.0);
let (w, h) = so.placed_size(cw as f64, ch as f64, k);
(w, h, k, bb)
} else {
(cw, ch, 1.0, [0.0; 4])
};
let f = Footage {
path: cx.path.to_string(),
kind: FootageKind::Still,
@@ -204,13 +216,20 @@ fn smart_object_layer(proj: &mut Project, cx: &mut Ctx, comp: &Comp, index: usiz
alpha: AlphaMode::Straight,
loop_count: 1,
codec: if effectcraft_psd::is_psd(data) { "PSD".into() } else { "PSD (embedded image)".into() },
layer: Some(SourceLayer { index: index as u32, name: name.to_string(), layer_size: true, embedded: Some(so.uuid.clone()) }),
layer: Some(SourceLayer { index: index as u32, name: name.to_string(), layer_size: true, embedded: Some(so.uuid.clone()), placed: bake }),
..Default::default()
};
let label = if file.is_empty() { name.to_string() } else { file };
let id = proj.add_item(&format!("{label} (Smart Object)"), Label::Lavender, Some(cx.folder), ItemKind::Footage(f));
cx.items.push(id);
let mut l = build::layer(proj, comp, name, LayerSource::Footage { item: id }, (w, h), None);
if bake {
// The baked pixels cover the placed bounds: centred there, scaled back to 1×.
let c = [bounds[0] + w as f64 / k / 2.0, bounds[1] + h as f64 / k / 2.0];
set_vec2(&mut l, "transform/position", c);
set_vec2(&mut l, "transform/scale", [100.0 / k, 100.0 / k]);
return Some(l);
}
let (c, sx, sy, rot) = so.placement(w as f64, h as f64);
set_vec2(&mut l, "transform/position", c);
set_vec2(&mut l, "transform/scale", [sx * 100.0, sy * 100.0]);
+384
View File
@@ -0,0 +1,384 @@
//! Viewer frames rendered by another engine instance (the browser's frame worker).
//!
//! The page keeps no frame threads (a wasm build without shared memory has one thread per
//! instance), so the web app renders viewer frames in a long-lived Web Worker that holds a
//! replica of the project. The page sends the replica **project diffs** rather than the whole
//! project per edit, then render requests; the worker answers each with the frame's pixels.
//!
//! - [`diff`] / [`patch`]: a structural JSON diff of the serialized project (object members
//! added, changed or removed; arrays element-wise when their length is unchanged, else
//! replaced). Lossless (unlike JSON Merge Patch, `null` values survive).
//! - [`Mirror`] (page side): what the worker holds; turns the next project revision into a
//! [`FrameMsg::Sync`] (a full project the first time, a diff afterwards).
//! - [`FrameServer`] (worker side): applies syncs, relayed Roto Brush segmentations and render
//! requests, and renders frames as premultiplied RGBA8 ([`rgba8_premultiplied`]).
//!
//! The transport (structured-clone messages, transferable pixel buffers) is the web crate's;
//! everything here is portable and tested natively.
use std::sync::Arc;
use effectcraft_project::{ItemId, Project};
use effectcraft_render::{ExprHost, FootageSource, Image, LayerCache, RenderOpts, Renderer};
use effectcraft_time::Tick;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::offload::SegData;
/// One step of a path into a JSON document.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Step {
Key(String),
Index(usize),
}
/// One change: set the value at `path` (creating or replacing the member/element), or remove
/// the object member at `path` (`value` absent).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Op {
pub path: Vec<Step>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<Value>,
}
/// The changes that turn `old` into `new` (empty when equal).
pub fn diff(old: &Value, new: &Value) -> Vec<Op> {
let mut ops = vec![];
diff_into(old, new, &mut vec![], &mut ops);
ops
}
fn diff_into(old: &Value, new: &Value, path: &mut Vec<Step>, ops: &mut Vec<Op>) {
if old == new {
return;
}
match (old, new) {
(Value::Object(a), Value::Object(b)) => {
for (k, va) in a {
path.push(Step::Key(k.clone()));
match b.get(k) {
Some(vb) => diff_into(va, vb, path, ops),
None => ops.push(Op { path: path.clone(), value: None }),
}
path.pop();
}
for (k, vb) in b {
if !a.contains_key(k) {
path.push(Step::Key(k.clone()));
ops.push(Op { path: path.clone(), value: Some(vb.clone()) });
path.pop();
}
}
}
(Value::Array(a), Value::Array(b)) if a.len() == b.len() => {
for (i, (va, vb)) in a.iter().zip(b).enumerate() {
path.push(Step::Index(i));
diff_into(va, vb, path, ops);
path.pop();
}
}
_ => ops.push(Op { path: path.clone(), value: Some(new.clone()) }),
}
}
/// Apply [`diff`]'s changes to `doc`.
pub fn patch(doc: &mut Value, ops: &[Op]) -> Result<(), String> {
for op in ops {
let Some((last, parents)) = op.path.split_last() else {
*doc = op.value.clone().ok_or("cannot remove the document")?;
continue;
};
let mut cur = &mut *doc;
for st in parents {
cur = match (st, cur) {
(Step::Key(k), Value::Object(m)) => m.get_mut(k).ok_or_else(|| format!("no member `{k}`"))?,
(Step::Index(i), Value::Array(a)) => a.get_mut(*i).ok_or_else(|| format!("no element {i}"))?,
_ => return Err("path does not match the document".into()),
};
}
match (last, cur, &op.value) {
(Step::Key(k), Value::Object(m), Some(v)) => {
m.insert(k.clone(), v.clone());
}
(Step::Key(k), Value::Object(m), None) => {
m.remove(k);
}
(Step::Index(i), Value::Array(a), Some(v)) => *a.get_mut(*i).ok_or_else(|| format!("no element {i}"))? = v.clone(),
_ => return Err("path does not match the document".into()),
}
}
Ok(())
}
/// Page → frame worker.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum FrameMsg {
/// The whole project (JSON) at `revision`.
Project { revision: u64, project: String },
/// Changes from the worker's revision `from` to `revision`.
Patch { from: u64, revision: u64, ops: Vec<Op> },
/// Render a frame of the current project.
Render { id: u64, revision: u64, comp: ItemId, time: Tick, opts: Box<RenderOpts> },
/// Roto Brush segmentations computed elsewhere (a propagation worker).
Segs { segs: Vec<SegData> },
/// Drop cached layer buffers (Edit ▸ Purge).
Purge,
}
/// Frame worker → page. A [`FrameReply::Frame`]'s pixels travel next to the message (a
/// transferable buffer in the browser).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum FrameReply {
/// Premultiplied RGBA8 pixels of request `id`, rendered in `ms` milliseconds.
Frame { id: u64, width: u32, height: u32, ms: f64 },
/// Request `id` was not rendered (`stale`: the worker holds another revision).
Failed { id: u64, error: String, stale: bool },
/// A sync could not be applied: the page must send the whole project again.
Resync { error: String },
}
/// The page's record of a worker's replica.
#[derive(Default)]
pub struct Mirror {
sent: Option<(u64, Value)>,
}
impl Mirror {
/// The revision the worker holds.
pub fn revision(&self) -> Option<u64> {
self.sent.as_ref().map(|s| s.0)
}
/// Forget the replica (the next sync sends the whole project).
pub fn reset(&mut self) {
self.sent = None;
}
/// The message that brings the worker to `revision` of `project` (`None` when it has it).
pub fn sync(&mut self, revision: u64, project: &Project) -> Option<FrameMsg> {
if self.revision() == Some(revision) {
return None;
}
let v = serde_json::to_value(project).unwrap_or(Value::Null);
let msg = match self.sent.take() {
Some((from, old)) => FrameMsg::Patch { from, revision, ops: diff(&old, &v) },
None => FrameMsg::Project { revision, project: v.to_string() },
};
self.sent = Some((revision, v));
Some(msg)
}
}
/// Premultiplied f32 → premultiplied RGBA8 (colour clamped to alpha), as the viewer shows it.
pub fn rgba8_premultiplied(img: &Image) -> Vec<u8> {
let mut out = Vec::with_capacity(img.data.len() * 4);
for p in &img.data {
let a = p[3].clamp(0.0, 1.0);
let c = |v: f32| (v.clamp(0.0, a) * 255.0 + 0.5) as u8;
out.extend_from_slice(&[c(p[0]), c(p[1]), c(p[2]), (a * 255.0 + 0.5) as u8]);
}
out
}
/// The worker's side: a project replica and what rendering needs.
pub struct FrameServer {
pub footage: Arc<dyn FootageSource>,
pub expr: Option<Arc<dyn ExprHost>>,
pub cache: Arc<LayerCache>,
doc: Value,
project: Option<Arc<Project>>,
revision: Option<u64>,
}
impl FrameServer {
pub fn new(footage: Arc<dyn FootageSource>, expr: Option<Arc<dyn ExprHost>>) -> FrameServer {
FrameServer { footage, expr, cache: Arc::new(LayerCache::default()), doc: Value::Null, project: None, revision: None }
}
pub fn revision(&self) -> Option<u64> {
self.revision
}
pub fn project(&self) -> Option<&Arc<Project>> {
self.project.as_ref()
}
fn load(&mut self, revision: u64) -> Result<(), String> {
let p = Project::from_json(&self.doc.to_string()).map_err(|e| e.to_string())?;
self.project = Some(Arc::new(p));
self.revision = Some(revision);
Ok(())
}
/// Handle one message; returns the replies with their pixels.
pub fn handle(&mut self, msg: FrameMsg) -> Vec<(FrameReply, Option<Vec<u8>>)> {
match msg {
FrameMsg::Project { revision, project } => {
let r = serde_json::from_str(&project).map_err(|e| e.to_string()).and_then(|v| {
self.doc = v;
self.load(revision)
});
match r {
Ok(()) => vec![],
Err(e) => self.lost(e),
}
}
FrameMsg::Patch { from, revision, ops } => {
if self.revision != Some(from) {
return self.lost(format!("the replica is at {:?}, the patch starts at {from}", self.revision));
}
match patch(&mut self.doc, &ops).and_then(|_| self.load(revision)) {
Ok(()) => vec![],
Err(e) => self.lost(e),
}
}
FrameMsg::Segs { segs } => {
for s in &segs {
s.store();
}
vec![]
}
FrameMsg::Purge => {
self.cache.clear();
vec![]
}
FrameMsg::Render { id, revision, comp, time, opts } => {
let fail = |error: String, stale: bool| vec![(FrameReply::Failed { id, error, stale }, None)];
if self.revision != Some(revision) {
return fail(format!("the replica is at {:?}, not {revision}", self.revision), true);
}
let Some(p) = self.project.clone() else { return fail("no project".into(), true) };
if p.comp(comp).is_none() {
return fail(format!("no composition {}", comp.0), false);
}
let t0 = web_time::Instant::now();
let mut r = Renderer::new(&p, self.footage.as_ref(), *opts);
r.expr = self.expr.as_deref();
r.cache = Some(&self.cache);
let img = r.comp_frame(comp, time);
let ms = t0.elapsed().as_secs_f64() * 1000.0;
vec![(FrameReply::Frame { id, width: img.width, height: img.height, ms }, Some(rgba8_premultiplied(&img)))]
}
}
}
fn lost(&mut self, error: String) -> Vec<(FrameReply, Option<Vec<u8>>)> {
self.doc = Value::Null;
self.project = None;
self.revision = None;
vec![(FrameReply::Resync { error }, None)]
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Session;
use serde_json::json;
fn round<T: Serialize + for<'de> Deserialize<'de>>(v: &T) -> T {
serde_json::from_str(&serde_json::to_string(v).unwrap()).unwrap()
}
#[test]
fn diff_and_patch_round_trip() {
let a = json!({"a": 1, "b": [1, 2, {"c": null}], "d": {"e": "x", "f": [1]}, "g": null});
let b = json!({"a": 2, "b": [1, 3, {"c": 4}], "d": {"f": [1, 2]}, "g": null, "h": {"i": null}});
let ops = diff(&a, &b);
assert!(!ops.is_empty());
let mut x = a.clone();
patch(&mut x, &round(&ops)).unwrap();
assert_eq!(x, b);
// Removal and the reverse direction.
let mut y = b.clone();
patch(&mut y, &diff(&b, &a)).unwrap();
assert_eq!(y, a);
assert!(diff(&a, &a).is_empty());
// A whole-document change.
let mut z = json!(1);
patch(&mut z, &diff(&json!(1), &json!([1]))).unwrap();
assert_eq!(z, json!([1]));
// A patch for another document fails cleanly.
assert!(patch(&mut json!(3), &diff(&a, &b)).is_err());
}
fn server(s: &Session) -> FrameServer {
FrameServer::new(s.footage.clone(), s.expr.clone())
}
/// Pixels the page itself would render.
fn local(s: &Session, comp: ItemId, t: Tick, opts: RenderOpts) -> Vec<u8> {
let mut r = Renderer::new(&s.project, s.footage.as_ref(), opts);
r.expr = s.expr.as_deref();
rgba8_premultiplied(&r.comp_frame(comp, t))
}
#[test]
fn replica_follows_edits_through_diffs_and_renders_the_same_frames() {
let mut s = Session::default();
s.execute("file.openDemoProject", json!({})).unwrap();
let comp = s.active_comp_id().unwrap();
let opts = RenderOpts { scale: 0.25, guides: true, ..Default::default() };
let mut m = Mirror::default();
let mut w = server(&s);
let send = |m: FrameMsg, w: &mut FrameServer| w.handle(round(&m));
// First sync: the whole project.
let first = m.sync(s.revision, &s.project).unwrap();
assert!(matches!(first, FrameMsg::Project { .. }));
assert!(send(first, &mut w).is_empty());
assert!(m.sync(s.revision, &s.project).is_none(), "nothing new");
let t = Tick::from_seconds_f64(1.0);
let render = |w: &mut FrameServer, rev: u64, id: u64| w.handle(round(&FrameMsg::Render { id, revision: rev, comp, time: t, opts: Box::new(opts) }));
let out = render(&mut w, s.revision, 1);
let (FrameReply::Frame { id, width, height, .. }, Some(px)) = &out[0] else { panic!("{:?}", out[0].0) };
assert_eq!((*id, *width as usize * *height as usize * 4), (1, px.len()));
assert_eq!(*px, local(&s, comp, t, opts));
// An edit travels as a small diff; the replica renders the edited frame.
s.execute("layer.newSolid", json!({"color": "#ff8800", "name": "Orange"})).unwrap();
let msg = m.sync(s.revision, &s.project).unwrap();
let FrameMsg::Patch { ops, .. } = &msg else { panic!("expected a patch") };
assert!(!ops.is_empty() && serde_json::to_string(ops).unwrap().len() < s.project.to_json().len() / 2);
assert!(send(msg, &mut w).is_empty());
assert_eq!(**w.project().unwrap(), *s.project);
let out = render(&mut w, s.revision, 2);
assert_eq!(out[0].1.as_deref(), Some(&local(&s, comp, t, opts)[..]));
// A request for another revision is refused as stale.
let out = render(&mut w, s.revision + 7, 3);
assert!(matches!(out[0].0, FrameReply::Failed { id: 3, stale: true, .. }));
// A patch from the wrong base asks for a resync; the mirror then sends the project.
let bad = FrameMsg::Patch { from: 999, revision: 1000, ops: vec![] };
assert!(matches!(send(bad, &mut w)[0].0, FrameReply::Resync { .. }));
m.reset();
assert!(matches!(m.sync(s.revision, &s.project), Some(FrameMsg::Project { .. })));
}
#[test]
fn frame_messages_round_trip() {
for m in [
FrameMsg::Purge,
FrameMsg::Segs { segs: vec![SegData { key: 7, data: "AAAA".into() }] },
FrameMsg::Render {
id: 3,
revision: 4,
comp: ItemId(2),
time: Tick::from_seconds_f64(0.5),
opts: Box::new(RenderOpts { scale: 0.5, draft: true, roi: Some([1.0, 2.0, 3.0, 4.0]), ..Default::default() }),
},
] {
let a = serde_json::to_string(&m).unwrap();
assert_eq!(serde_json::to_string(&round(&m)).unwrap(), a);
assert!(a.starts_with("{\"type\":"), "{a}");
}
for r in [
FrameReply::Frame { id: 1, width: 2, height: 3, ms: 4.5 },
FrameReply::Failed { id: 1, error: "x".into(), stale: true },
FrameReply::Resync { error: "y".into() },
] {
assert_eq!(round(&r), r);
}
}
}
+29 -12
View File
@@ -3,7 +3,8 @@
//!
//! 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
//! `wait`; in the browser the background is a Web Worker whose segmentations stream back,
//! [`crate::offload`]), 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
@@ -403,16 +404,21 @@ pub(crate) fn job_frames(d: &effectcraft_track::roto::RotoData, dir: Direction)
}
impl Session {
/// The Roto Brush job running in a worker (Freeze or propagation), with its task.
fn offloaded_roto(&self) -> Option<(&crate::offload::OffloadedJob, RotoTask)> {
self.offloaded(JobKind::RotoFreeze).map(|j| (j, RotoTask::Freeze)).or_else(|| self.offloaded(JobKind::RotoPropagate).map(|j| (j, RotoTask::Propagate)))
}
pub fn is_roto_running(&self) -> bool {
self.roto_job.as_ref().is_some_and(|j| !j.is_finished()) || self.offloaded(JobKind::RotoFreeze).is_some()
self.roto_job.as_ref().is_some_and(|j| !j.is_finished()) || self.offloaded_roto().is_some()
}
pub fn roto_progress(&self) -> Option<RotoProgress> {
self.roto_job.as_ref().map(|j| j.progress()).or_else(|| {
self.offloaded(JobKind::RotoFreeze).map(|j| {
self.offloaded_roto().map(|(j, task)| {
let p = &j.progress;
RotoProgress {
task: Some(RotoTask::Freeze),
task: Some(task),
done: p.done,
total: p.total,
elapsed: p.elapsed,
@@ -425,14 +431,22 @@ impl Session {
/// (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))
.or_else(|| self.offloaded(JobKind::RotoFreeze).map(|j| (j.comp, j.layer, j.uid, RotoTask::Freeze)))
self.roto_job.as_ref().map(|j| (j.comp, j.layer, j.effect, j.task)).or_else(|| self.offloaded_roto().map(|(j, task)| (j.comp, j.layer, j.uid, task)))
}
/// The segmentation chain a propagation of `effect` computes (its frames' cache keys).
pub fn roto_chain(&self, comp: ItemId, layer: LayerId, effect: Uid) -> Option<fx::Chain> {
let c = self.project.comp(comp)?;
let l = c.layer(layer)?;
let g = l.effects()?.groups().find(|g| g.uid == effect && is_roto(g))?;
let d = fx::data(&params_static(g));
let t = comp_time_of(c, l, d.base?);
let params = params_at(&self.project, comp, l, g, t, self.expr.as_deref());
Some(fx::Chain::new(&params, layer_size(&self.project, c, l), c.frame_rate.as_f64(), 1.0))
}
pub fn stop_roto(&mut self) -> bool {
if self.cancel_offloaded(JobKind::RotoFreeze) {
if self.cancel_offloaded(JobKind::RotoFreeze) || self.cancel_offloaded(JobKind::RotoPropagate) {
return true;
}
match &self.roto_job {
@@ -491,9 +505,12 @@ impl Session {
task,
};
let strokes = str_of(g, fx::STROKES);
if !wait && task == RotoTask::Freeze && self.offloads() {
if !wait && self.offloads() {
drop(work);
self.offload_analysis(crate::offload::WorkerJob::RotoFreeze { comp, layer, effect })?;
self.offload_analysis(match task {
RotoTask::Freeze => crate::offload::WorkerJob::RotoFreeze { comp, layer, effect },
RotoTask::Propagate => crate::offload::WorkerJob::RotoPropagate { comp, layer, effect, direction: dir },
})?;
return Ok(n);
}
let wait = wait || cfg!(target_arch = "wasm32");
@@ -567,7 +584,7 @@ impl Session {
/// 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 {
if auto && self.roto_job.is_none() && self.offloaded_roto().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() {
+121 -1
View File
@@ -112,9 +112,103 @@ pub struct Widget {
pub handlers: Vec<String>,
/// The active tab of a tabbed panel (child index).
pub active_tab: usize,
/// What the control's `onDraw` handler painted (ScriptUIGraphics), in control coordinates.
/// Frontends paint it instead of the control's default look, unless it contains
/// [`DrawOp::Os`] (`drawOSControl()`), which draws the default look first.
pub draw: Vec<DrawOp>,
pub children: Vec<Widget>,
}
/// One segment of a ScriptUIGraphics path (control coordinates, pixels).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "k")]
pub enum PathSeg {
/// `moveTo(x, y)`: starts a new subpath.
M { x: f64, y: f64 },
/// `lineTo(x, y)`.
L { x: f64, y: f64 },
/// `rectPath(x, y, w, h)`: a closed rectangle subpath.
R { x: f64, y: f64, w: f64, h: f64 },
/// `ellipsePath(x, y, w, h)`: a closed ellipse inscribed in the rectangle.
E { x: f64, y: f64, w: f64, h: f64 },
/// `closePath()`.
Z,
}
/// One paint call of an `onDraw` handler. Colours are straight RGBA in 0..1; `None` is a theme
/// colour (a brush or pen made from a theme colour name).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "camelCase")]
pub enum DrawOp {
/// `fillPath(brush, path)`.
Fill { color: Option<[f32; 4]>, path: Vec<PathSeg> },
/// `strokePath(pen, path)`.
Stroke { color: Option<[f32; 4]>, width: f64, path: Vec<PathSeg> },
/// `drawString(text, pen, x, y, font)`: `(x, y)` is the text's top-left.
Text {
text: String,
color: Option<[f32; 4]>,
x: f64,
y: f64,
size: f64,
#[serde(default)]
style: String,
},
/// `drawOSControl()`: the control's default look.
Os,
/// `drawImage(image, x, y, w?, h?)` (drawn as a placeholder frame).
Image { x: f64, y: f64, w: f64, h: f64 },
}
impl PathSeg {
/// The subpaths of `path` as polylines (ellipses flattened to `n` segments), each with
/// whether it is closed.
pub fn polylines(path: &[PathSeg], n: usize) -> Vec<(Vec<[f64; 2]>, bool)> {
fn flush(cur: &mut Vec<[f64; 2]>, out: &mut Vec<(Vec<[f64; 2]>, bool)>, closed: bool) {
if cur.len() > 1 {
out.push((std::mem::take(cur), closed));
} else {
cur.clear();
}
}
let mut out = vec![];
let mut cur: Vec<[f64; 2]> = vec![];
for seg in path {
match *seg {
PathSeg::M { x, y } => {
flush(&mut cur, &mut out, false);
cur.push([x, y]);
}
PathSeg::L { x, y } => cur.push([x, y]),
PathSeg::Z => {
let start = cur.first().copied();
flush(&mut cur, &mut out, true);
// Drawing continues from the subpath's start.
cur.extend(start);
}
PathSeg::R { x, y, w, h } => {
flush(&mut cur, &mut out, false);
out.push((vec![[x, y], [x + w, y], [x + w, y + h], [x, y + h]], true));
}
PathSeg::E { x, y, w, h } => {
flush(&mut cur, &mut out, false);
let (cx, cy, rx, ry) = (x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0);
let n = n.max(8);
let pts = (0..n)
.map(|i| {
let a = i as f64 / n as f64 * std::f64::consts::TAU;
[cx + rx * a.cos(), cy + ry * a.sin()]
})
.collect();
out.push((pts, true));
}
}
}
flush(&mut cur, &mut out, false);
out
}
}
impl Widget {
pub fn find(&self, id: u32) -> Option<&Widget> {
if self.id == id {
@@ -493,7 +587,8 @@ pub(crate) fn set(s: &mut Session, p: &Value) -> Result<Value> {
let i = w.items.iter().position(|it| it == t).ok_or_else(|| crate::commands::bad(c, format!("no item `{t}` (items: {:?})", w.items)))?;
value = json!(i);
}
dispatch(s, ScriptUiEvent { window, widget, kind: "change".into(), value })
let kind = if p.get("changing").and_then(Value::as_bool) == Some(true) { "changing" } else { "change" };
dispatch(s, ScriptUiEvent { window, widget, kind: kind.into(), value })
}
/// `scriptui.close`: close a window (a dialog's `show()` returns `result`, default 2 = Cancel).
@@ -557,6 +652,31 @@ mod tests {
assert_eq!(win.root.lookup(&json!(1)).unwrap().id, 1);
}
#[test]
fn draw_lists_flatten_to_polylines_and_round_trip() {
let path = vec![
PathSeg::M { x: 0.0, y: 0.0 },
PathSeg::L { x: 10.0, y: 0.0 },
PathSeg::L { x: 10.0, y: 10.0 },
PathSeg::Z,
PathSeg::R { x: 1.0, y: 2.0, w: 3.0, h: 4.0 },
PathSeg::E { x: 0.0, y: 0.0, w: 20.0, h: 10.0 },
];
let lines = PathSeg::polylines(&path, 16);
assert_eq!(lines.len(), 3);
assert_eq!(lines[0], (vec![[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]], true));
assert_eq!(lines[1].0[2], [4.0, 6.0]);
assert_eq!(lines[2].0.len(), 16);
assert!((lines[2].0[0][0] - 20.0).abs() < 1e-9 && (lines[2].0[4][1] - 10.0).abs() < 1e-9);
let op = DrawOp::Fill { color: Some([1.0, 0.0, 0.0, 1.0]), path };
let j = serde_json::to_value(&op).unwrap();
assert_eq!(j["op"], "fill");
assert_eq!(j["path"][0], json!({"k": "M", "x": 0.0, "y": 0.0}));
assert_eq!(serde_json::from_value::<DrawOp>(j).unwrap(), op);
let t: DrawOp = serde_json::from_value(json!({"op": "text", "text": "Hi", "color": null, "x": 1, "y": 2, "size": 14})).unwrap();
assert!(matches!(t, DrawOp::Text { size, .. } if size == 14.0));
}
#[test]
fn publish_replaces_a_hosts_windows() {
let mut ui = ScriptUi::default();
+5 -1
View File
@@ -48,8 +48,12 @@ impl Session {
if !s.is_empty() {
return Some(std::path::PathBuf::from(s));
}
// (the browser has no file system: no default folder there)
if self.config.is_none() || cfg!(target_arch = "wasm32") {
return None;
}
let base = effectcraft_render::disk_cache::default_folder();
self.config.is_some().then(|| base.parent().map(|p| p.join(name)).unwrap_or_else(|| base.join(name)))
Some(base.parent().map(|p| p.join(name)).unwrap_or_else(|| base.join(name)))
}
/// Settings ▸ Disk ▸ Database and Cache Folder (media cache: audio waveform summaries).
+94
View File
@@ -0,0 +1,94 @@
//! Essential Graphics Font and uniform Scale controls, Composition ▸ Open in Essential Graphics.
use effectcraft_keyframe::Value as KV;
use effectcraft_project::essential::{self, ControlType};
use serde_json::json;
use crate::{Event, Session};
#[test]
fn font_and_scale_controls_override_per_instance() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Title", "width": 64, "height": 64, "frameRate": 30, "duration": 1})).unwrap();
let title = s.active_comp_id().unwrap();
let text = s.execute("layer.newText", json!({"text": "Hello"})).unwrap()["layer"].as_u64().unwrap();
// Source Text: as text and as font; Scale as one slider.
let t = s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText"})).unwrap()["controls"][0].as_u64().unwrap();
let f = s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font"})).unwrap()["controls"][0].as_u64().unwrap();
let sc = s.execute("essential.addProperty", json!({"layer": text, "path": "transform/scale", "as": "scale"})).unwrap()["controls"][0].as_u64().unwrap();
// Adding the same font control again is a no-op; opacity can't be a font.
assert!(
s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font"})).unwrap()["controls"].as_array().unwrap().is_empty()
);
assert!(s.execute("essential.addProperty", json!({"layer": text, "path": "transform/opacity", "as": "font"})).is_err());
assert_eq!(s.execute("essential.canAdd", json!({"layer": text, "path": "transform/opacity", "as": "font"})).unwrap()["ok"], false);
assert_eq!(s.execute("essential.canAdd", json!({"layer": text, "path": "transform/scale", "as": "scale"})).unwrap()["type"], "scale");
let l = s.execute("essential.list", json!({})).unwrap();
let types: Vec<&str> = l["controls"].as_array().unwrap().iter().map(|c| c["type"].as_str().unwrap()).collect();
assert_eq!(types, ["text", "font", "scale"]);
assert!(l["controls"][1]["value"]["size"].as_f64().unwrap() > 0.0);
let eg = s.project.comp(title).unwrap().essential.clone().unwrap();
assert_eq!(eg.find(f).unwrap().as_type, Some(ControlType::Font));
// Survives save / load (serde).
let j = serde_json::to_value(&eg).unwrap();
assert_eq!(serde_json::from_value::<essential::EssentialGraphics>(j).unwrap(), eg);
// An instance: change the text, then the font and the scale.
s.execute("comp.new", json!({"name": "Main", "width": 64, "height": 64, "frameRate": 30, "duration": 1})).unwrap();
let inst = s.execute("layer.addItem", json!({"item": title.0})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.select", json!({"layers": [inst]})).unwrap();
s.execute("essential.set", json!({"layer": inst, "control": t, "value": "Bye"})).unwrap();
s.execute("essential.set", json!({"layer": inst, "control": f, "value": {"font": "Serif Test", "size": 40}})).unwrap();
s.execute("essential.set", json!({"layer": inst, "control": sc, "value": 50})).unwrap();
let i = s.execute("essential.instance", json!({"layer": inst})).unwrap();
assert_eq!(i["controls"][1]["value"]["font"], "Serif Test");
assert_eq!(i["controls"][1]["value"]["size"], 40.0);
assert_eq!(i["controls"][1]["overridden"], true);
assert_eq!(i["controls"][2]["type"], "scale");
assert_eq!(i["controls"][2]["value"][0], 50.0);
assert_eq!(i["controls"][2]["value"][1], 50.0);
// What the instance renders: the overridden text with the overridden font, scaled.
let layer = s.active_comp().unwrap().layer(effectcraft_project::LayerId(inst)).unwrap().clone();
let over: Vec<essential::Override> = {
let g = essential::group(&layer).unwrap();
let mut v = vec![];
g.walk("", &mut |_, p| {
if let Some(c) = essential::control_of(&p.match_id) {
v.push(essential::Override { control: c, value: p.value.clone() });
}
});
v
};
let p = essential::with_overrides(&s.project, title, &over).unwrap();
let src = p.comp(title).unwrap().layer(effectcraft_project::LayerId(text)).unwrap();
match src.props.prop("text/sourceText").map(|x| &x.value) {
Some(KV::Text(d)) => assert_eq!((d.text.as_str(), d.font.as_str(), d.size), ("Bye", "Serif Test", 40.0)),
o => panic!("{o:?}"),
}
// Push to Comp with only the font: the source keeps its own text.
s.execute("essential.revert", json!({"layer": inst, "control": t})).unwrap();
s.execute("essential.pushToComp", json!({"layer": inst, "control": f})).unwrap();
let srcl = s.project.comp(title).unwrap().layer(effectcraft_project::LayerId(text)).unwrap();
match srcl.props.prop("text/sourceText").map(|x| &x.value) {
Some(KV::Text(d)) => assert_eq!((d.text.as_str(), d.font.as_str()), ("Hello", "Serif Test")),
o => panic!("{o:?}"),
}
}
#[test]
fn open_in_essential_graphics_sets_the_primary_comp() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "A", "width": 32, "height": 32, "duration": 1})).unwrap();
let a = s.active_comp_id().unwrap();
s.execute("comp.new", json!({"name": "B", "width": 32, "height": 32, "duration": 1})).unwrap();
s.drain_events();
let r = s.execute("comp.openInEssentialGraphics", json!({"comp": a.0})).unwrap();
assert_eq!(r["name"], "A");
assert_eq!(s.state.essential_primary, Some(a));
assert!(
s.drain_events()
.iter()
.any(|e| matches!(e, Event::Frontend { command, params } if command == "window.panel" && params["panel"] == "essentialGraphics"))
);
assert_eq!(s.execute("essential.list", json!({})).unwrap()["name"], "A");
}
+78
View File
@@ -0,0 +1,78 @@
//! Composition ▸ Save Frame As ▸ Photoshop Layers… / ProEXR….
use serde_json::json;
use crate::Session;
fn out_dir(name: &str) -> std::path::PathBuf {
let d = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out").join(name);
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// A 32×32 comp: a red full-frame solid under a 16×16 blue Multiply solid at 50%.
fn frame() -> Session {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Frame", "width": 32, "height": 32, "frameRate": 24, "duration": 1})).unwrap();
s.execute("layer.newSolid", json!({"name": "Red", "color": "#ff0000"})).unwrap();
let blue = s.execute("layer.newSolid", json!({"name": "Blue.Box", "color": "#0000ff", "width": 16, "height": 16})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setBlendMode", json!({"layers": [blue], "mode": "Multiply"})).unwrap();
s.execute("prop.set", json!({"layer": blue, "path": "transform/opacity", "value": 50})).unwrap();
s
}
#[test]
fn photoshop_layers_writes_one_psd_layer_per_comp_layer() {
let mut s = frame();
let dir = out_dir("frame-psd");
let path = dir.join("frame.psd").to_string_lossy().to_string();
let r = s.execute("comp.saveFrameAsPsd", json!({"path": path})).unwrap();
assert_eq!(r["layers"], 2);
let psd = effectcraft_psd::Psd::parse(std::fs::read(&path).unwrap()).unwrap();
assert_eq!((psd.width, psd.height), (32, 32));
let names: Vec<&str> = psd.layers.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, ["Red", "Blue.Box"], "bottom first");
let blue = &psd.layers[1];
assert_eq!(blue.blend_key(), "mul ");
assert_eq!(blue.opacity, 128);
// Cropped to its pixels (16×16, centred) and rendered at full opacity.
assert_eq!((blue.rect.left, blue.rect.top, blue.rect.width(), blue.rect.height()), (8, 8, 16, 16));
assert_eq!(psd.layers[0].blend_key(), "norm");
assert_eq!(psd.layers[0].opacity, 255);
// The merged image is the comp frame: red × (50% blue multiply) in the middle.
let m = psd.composite().unwrap();
let mid = m.data[16 * 32 + 16];
assert!(mid[0] > 0.4 && mid[0] < 0.6 && mid[2] < 0.05, "{mid:?}");
let corner = m.data[0];
assert!(corner[0] > 0.99 && corner[2] < 0.01, "{corner:?}");
// The menu has it.
assert!(crate::commands::find("comp.saveFrameAsPsd").is_some());
}
#[test]
fn proexr_writes_layer_prefixed_channels_and_the_composite() {
use exr::prelude::*;
let mut s = frame();
let dir = out_dir("frame-exr");
let path = dir.join("frame.exr").to_string_lossy().to_string();
let r = s.execute("comp.saveFrameAsExr", json!({"path": path})).unwrap();
let names: Vec<&str> = r["channels"].as_array().unwrap().iter().map(|c| c.as_str().unwrap()).collect();
assert_eq!(names.len(), 12);
assert!(names.contains(&"R") && names.contains(&"A") && names.contains(&"Red.R") && names.contains(&"Blue_Box.B"), "{names:?}");
let img = read().no_deep_data().largest_resolution_level().all_channels().all_layers().all_attributes().from_file(&path).unwrap();
let layer = &img.layer_data[0];
assert_eq!((layer.size.0, layer.size.1), (32, 32));
let ch = |n: &str| layer.channel_data.list.iter().find(|c| c.name.to_string() == n).unwrap_or_else(|| panic!("no channel {n}"));
let at = |n: &str, x: usize, y: usize| match &ch(n).sample_data {
FlatSamples::F32(v) => v[y * 32 + x],
o => panic!("{o:?}"),
};
// The blue layer alone: blue inside its box, transparent outside.
assert!((at("Blue_Box.B", 16, 16) - 1.0).abs() < 1e-3);
assert_eq!(at("Blue_Box.A", 0, 0), 0.0);
assert!((at("Red.R", 0, 0) - 1.0).abs() < 1e-3);
// Composite: opaque everywhere.
assert!((at("A", 16, 16) - 1.0).abs() < 1e-3);
assert!(at("R", 16, 16) < 0.5, "multiplied by 50% blue (linear)");
}
+167
View File
@@ -0,0 +1,167 @@
//! M13.7 menu items: File ▸ Watch Folder, Import ▸ Vanishing Point (disabled), Create Nulls From
//! Paths, VR Comp Editor and Help ▸ In-App / Online Tutorials.
use std::sync::Arc;
use serde_json::json;
use crate::rq_tests::MockExporter;
use crate::{Event, Session};
fn out_dir(name: &str) -> std::path::PathBuf {
let d = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/test-out").join(name);
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn watch_folder_renders_queued_projects_and_writes_status() {
let dir = out_dir("watch-folder");
let ex = Arc::new(MockExporter { log: Default::default() });
// A project with a queued render, and one (in a subfolder) with nothing queued.
let mut a = Session { exporter: Some(ex.clone()), ..Default::default() };
a.execute("comp.new", json!({"name": "Shot", "width": 32, "height": 32, "frameRate": 10, "duration": 0.5})).unwrap();
a.execute("renderQueue.add", json!({})).unwrap();
let pa = dir.join("a.ecproj");
a.execute("file.saveAs", json!({"path": pa.to_string_lossy()})).unwrap();
std::fs::create_dir_all(dir.join("collected")).unwrap();
let mut b = Session::default();
b.execute("comp.new", json!({"name": "Idle", "width": 32, "height": 32, "duration": 1})).unwrap();
let pb = dir.join("collected/b.ecproj");
b.execute("file.saveAs", json!({"path": pb.to_string_lossy()})).unwrap();
let mut host = Session { exporter: Some(ex.clone()), ..Default::default() };
assert!(!host.is_enabled("file.watchFolder.poll"));
let r = host.execute("file.watchFolder", json!({"folder": dir.to_string_lossy()})).unwrap();
let done = r["rendered"].as_array().unwrap();
assert_eq!(done.len(), 2, "{r}");
assert_eq!(host.state.watch_folder.as_deref(), Some(dir.to_string_lossy().as_ref()));
let st: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("a.ecproj.status.json")).unwrap()).unwrap();
assert_eq!(st["state"], "done", "{st}");
assert_eq!(st["items"][0]["comp"], "Shot");
assert_eq!(st["items"][0]["status"], "Done");
assert_eq!(ex.log.lock().unwrap().len(), 1);
let st: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("collected/b.ecproj.status.json")).unwrap()).unwrap();
assert_eq!(st["note"], "nothing queued");
// Rendered projects are not picked up again; deleting the status file re-renders.
assert!(host.execute("file.watchFolder.poll", json!({})).unwrap()["rendered"].as_array().unwrap().is_empty());
std::fs::remove_file(dir.join("a.ecproj.status.json")).unwrap();
assert_eq!(host.execute("file.watchFolder.poll", json!({})).unwrap()["rendered"].as_array().unwrap().len(), 1);
assert_eq!(ex.log.lock().unwrap().len(), 2);
// A broken project fails with a status, not an error.
std::fs::write(dir.join("broken.ecproj"), b"not a project").unwrap();
let r = host.execute("file.watchFolder.poll", json!({})).unwrap();
assert_eq!(r["rendered"][0]["state"], "failed");
host.execute("file.watchFolder", json!({"stop": true})).unwrap();
assert!(host.state.watch_folder.is_none());
assert!(host.execute("file.watchFolder", json!({"folder": "/no/such/folder"})).is_err());
}
#[test]
fn vanishing_point_import_is_disabled_with_a_reason() {
let mut s = Session::default();
assert!(!s.is_enabled("file.importVanishingPoint"));
let spec = crate::commands::find("file.importVanishingPoint").unwrap();
assert!((spec.enabled)(&s).unwrap_err().contains("public specification"));
assert!(s.execute("file.importVanishingPoint", json!({})).is_err());
}
#[test]
fn help_tutorials() {
let mut s = Session::default();
s.drain_events();
s.execute("help.onlineTutorials", json!({})).unwrap();
s.execute("help.inAppTutorials", json!({})).unwrap();
let ev = s.drain_events();
assert!(ev.iter().any(|e| matches!(e, Event::OpenUrl(u) if u == crate::links::APP_PAGE)));
assert!(ev.iter().any(|e| matches!(e, Event::Frontend { command, .. } if command == "help.inAppTutorials")));
}
/// A comp with a 2D solid at (50, 40) carrying a square mask.
fn masked() -> (Session, u64) {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Paths", "width": 100, "height": 80, "frameRate": 10, "duration": 1})).unwrap();
let l = s.execute("layer.newSolid", json!({"name": "Plate", "color": "#808080", "width": 40, "height": 40})).unwrap()["layer"].as_u64().unwrap();
s.execute("mask.new", json!({"layer": l, "vertices": [[0, 0], [40, 0], [40, 40], [0, 40]], "closed": true})).unwrap();
(s, l)
}
#[test]
fn nulls_follow_points_and_points_follow_nulls() {
let (mut s, l) = masked();
s.execute("layer.select", json!({"layers": [l]})).unwrap();
let r = s.execute("paths.nullsFollowPoints", json!({})).unwrap();
let nulls: Vec<u64> = r["nulls"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
assert_eq!(nulls.len(), 4);
let comp = s.active_comp().unwrap().clone();
let n2 = comp.layer(effectcraft_project::LayerId(nulls[2])).unwrap();
assert_eq!(n2.name, "Plate: Mask 1 [3]");
// Placed on the vertex in comp space (the 40×40 solid is centred at (50, 40)).
let pos = n2.props.prop("transform/position").unwrap();
assert_eq!(&pos.value.components()[..2], &[70.0, 60.0]);
let e = pos.expr.as_ref().unwrap().text.clone();
assert!(e.contains("thisComp.layer(\"Plate\")") && e.contains(".points()[2]"), "{e}");
// One undo step.
assert!(s.undo());
assert_eq!(s.active_comp().unwrap().layers.len(), 1);
let r = s.execute("paths.pointsFollowNulls", json!({"layer": l, "path": "masks/#1/path"})).unwrap();
assert_eq!(r["nulls"].as_array().unwrap().len(), 4);
let comp = s.active_comp().unwrap().clone();
let plate = comp.layer(effectcraft_project::LayerId(l)).unwrap();
let e = plate.props.prop("masks/#1/path").unwrap().expr.as_ref().unwrap().text.clone();
assert!(e.contains("createPath(pts") && e.contains("\"Plate: Mask 1 [1]\"") && e.contains("fromComp"), "{e}");
// Not a path → error.
assert!(s.execute("paths.nullsFollowPoints", json!({"layer": l, "path": "transform/opacity"})).is_err());
}
#[test]
fn trace_path_adds_a_progress_null() {
let (mut s, l) = masked();
let r = s.execute("paths.tracePath", json!({"layer": l, "loop": true})).unwrap();
let n = r["null"].as_u64().unwrap();
let comp = s.active_comp().unwrap().clone();
let null = comp.layer(effectcraft_project::LayerId(n)).unwrap();
let slider = null.props.prop("effects/#1/slider").unwrap();
assert_eq!(slider.keys.len(), 2);
assert_eq!(slider.keys[1].value.as_f64(), 100.0);
assert!(slider.expr.as_ref().unwrap().text.contains("loopOut"));
assert_eq!(null.props.group("effects/#1").unwrap().name, "Progress");
assert!(null.props.prop("transform/position").unwrap().expr.as_ref().unwrap().text.contains("pointOnPath(effect(\"Progress\")(\"Slider\") / 100)"));
}
#[test]
fn vr_comp_editor_turns_the_face_cameras_together() {
let mut s = Session::default();
s.execute("comp.new", json!({"name": "Scene", "width": 64, "height": 64, "frameRate": 10, "duration": 1})).unwrap();
s.execute("layer.newSolid", json!({"name": "Wall", "color": "#ff0000"})).unwrap();
s.execute("comp.vr.createEnvironment", json!({"size": 64})).unwrap();
let envs = s.execute("comp.vr.environments", json!({})).unwrap();
assert_eq!(envs.as_array().unwrap().len(), 1, "{envs}");
let env = &envs[0];
assert_eq!(env["name"], "Scene VR Output");
assert_eq!(env["faces"].as_array().unwrap().len(), 6);
let view = env["view"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>();
assert!(view.iter().all(|v| v.abs() < 1e-6 || (v - 360.0).abs() < 1e-6), "{view:?}");
let out = env["output"].as_u64().unwrap();
let r = s.execute("comp.vr.setView", json!({"comp": out, "pan": 30.0})).unwrap();
let v = r["view"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>();
assert!((v[1] - 30.0).abs() < 1e-6 && v[0].abs() < 1e-6 && v[2].abs() < 1e-6, "{v:?}");
// Every face camera turned: Front by 30° about Y.
let front = &env["faces"][4];
let fc = s.project.comp(effectcraft_project::ItemId(front["comp"].as_u64().unwrap())).unwrap();
let cam = fc.layer(effectcraft_project::LayerId(front["camera"].as_u64().unwrap())).unwrap();
let o = cam.props.prop("transform/orientation").unwrap().value.components();
assert!((o[1] - 30.0).abs() < 1e-6, "{o:?}");
// One undo step back to the start.
assert!(s.undo());
let envs = s.execute("comp.vr.environments", json!({})).unwrap();
assert!(envs[0]["view"][1].as_f64().unwrap().abs() < 1e-6);
// Round trip of the Euler decomposition.
for o in [[10.0, 20.0, 30.0], [350.0, 45.0, 5.0], [0.0, 0.0, 270.0]] {
let m = effectcraft_geom::Mat4::orientation(effectcraft_geom::vec3(o[0], o[1], o[2]));
let e = crate::commands::vr_editor::euler(m);
assert!(e.iter().zip(o).all(|(a, b)| (a - b).abs() < 1e-6), "{o:?} → {e:?}");
}
}
+61
View File
@@ -516,3 +516,64 @@ fn panels_commands_are_wired() {
assert!(s.is_enabled(id), "{id}");
}
}
/// A browser like the web app's: a virtual tree whose files are read on demand.
#[derive(Default)]
struct VirtualBrowser {
tree: Mutex<crate::media_browser::VirtualTree>,
fetched: Mutex<Vec<String>>,
actions: Mutex<Vec<String>>,
}
impl crate::media_browser::Browser for VirtualBrowser {
fn home(&self) -> String {
"/Browser Storage".into()
}
fn places(&self) -> Vec<(String, String)> {
vec![("Browser Storage".into(), self.home()), ("Shoot".into(), "/Folders/Shoot".into())]
}
fn list(&self, dir: &str, only: bool) -> Result<Vec<crate::media_browser::Entry>, String> {
self.tree.lock().unwrap().list(dir, only)
}
fn fetch(&self, paths: &[String], _: &Value) -> bool {
// Opened folders' files arrive later.
let pending: Vec<String> = paths.iter().filter(|p| p.starts_with("/Folders/")).cloned().collect();
self.fetched.lock().unwrap().extend(pending.iter().cloned());
pending.is_empty()
}
fn actions(&self) -> Vec<(String, String)> {
vec![("openFolder".into(), "Open Folder…".into())]
}
fn action(&self, id: &str) -> Result<Value, String> {
self.actions.lock().unwrap().push(id.into());
Ok(json!({"pending": true}))
}
}
#[test]
fn media_browser_over_a_virtual_tree() {
let b = Arc::new(VirtualBrowser::default());
{
let mut t = b.tree.lock().unwrap();
t.add_dir("/Browser Storage");
t.add_file("/Folders/Shoot/a.csv", "/Folders/Shoot/a.csv", 12, Some(1));
}
let mut s = Session { browser: Some(b.clone()), ..Default::default() };
let r = s.execute("mediaBrowser.list", json!({})).unwrap();
assert_eq!(r["path"], "/Browser Storage");
assert_eq!(r["places"][1]["path"], "/Folders/Shoot");
assert_eq!(r["actions"][0]["id"], "openFolder");
let r = s.execute("mediaBrowser.go", json!({"path": "/Folders/Shoot"})).unwrap();
assert_eq!(r["entries"][0]["name"], "a.csv");
assert_eq!(r["parent"], "/Folders");
assert!(s.execute("mediaBrowser.go", json!({"path": "/Nope"})).is_err());
// Importing a file that is not read yet: pending (the host imports it once it arrives).
let r = s.execute("mediaBrowser.import", json!({"paths": ["/Folders/Shoot/a.csv"]})).unwrap();
assert_eq!(r["pending"], true);
assert_eq!(*b.fetched.lock().unwrap(), ["/Folders/Shoot/a.csv"]);
assert!(s.project.items.values().all(|i| !matches!(i.kind, ItemKind::Footage(_))));
let r = s.execute("mediaBrowser.action", json!({"action": "openFolder"})).unwrap();
assert_eq!(r["pending"], true);
assert_eq!(*b.actions.lock().unwrap(), ["openFolder"]);
assert!(s.execute("mediaBrowser.action", json!({})).is_err());
}
+49
View File
@@ -286,3 +286,52 @@ fn propagation_is_deterministic_and_runs_in_background() {
let r = s.execute("roto.stroke", json!({"layer": clip.0, "points": [[90, 110]]})).unwrap();
assert_eq!(r["radius"], 15.0);
}
/// Runs offloaded jobs at once in a second session sharing the footage, through JSON (what the
/// browser's Web Worker does, minus the thread).
struct InlineWorker(std::sync::Arc<dyn effectcraft_render::FootageSource>);
impl crate::offload::Offload for InlineWorker {
fn start(&self, req: crate::offload::WorkerRequest, inbox: std::sync::Arc<crate::offload::Inbox>) -> Result<(), String> {
let req: crate::offload::WorkerRequest = serde_json::from_str(&serde_json::to_string(&req).unwrap()).unwrap();
let mut w = Session { footage: self.0.clone(), ..Default::default() };
let post: crate::offload::Post = std::rc::Rc::new(move |r| inbox.push(serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap()));
crate::offload::run_request(&mut w, req, &post);
Ok(())
}
fn cancel(&self, _: u64) {}
}
#[test]
fn offloaded_propagation_streams_segmentations_back() {
let (mut s, clip, uid) = painted(center, "disk-offload.mov");
s.execute("roto.span", json!({"layer": clip.0, "end": 5})).unwrap();
s.offload = Some(std::sync::Arc::new(InlineWorker(s.footage.clone())));
let r = s.execute("roto.propagate", json!({"layer": clip.0})).unwrap();
assert_eq!(r["frames"], 6, "{r}");
assert!(s.roto_job.is_none(), "offloaded, not on a thread");
assert!(s.is_roto_running());
assert_eq!(s.roto_progress().unwrap().task, Some(crate::roto::RotoTask::Propagate));
assert_eq!(s.roto_target().map(|t| (t.1, t.2)), Some((clip, uid)));
assert!(s.jobs().iter().any(|j| j.id == "roto"));
// The worker has its own segmentation cache: here nothing is computed until its replies
// are applied.
forget(&s, clip, uid);
assert_eq!(s.execute("roto.status", json!({"layer": clip.0})).unwrap()["computed"], json!([]));
let rev = s.revision;
assert!(s.poll_offload());
assert!(!s.is_roto_running());
assert!(s.revision > rev, "frames are redrawn");
let st = s.execute("roto.status", json!({"layer": clip.0})).unwrap();
assert_eq!(st["computed"], json!([0, 1, 2, 3, 4, 5]), "{st}");
assert!(s.events.iter().any(|e| matches!(e, crate::Event::Toast { message, error: false } if message.contains("propagated 6 frame"))));
// The matte matches one computed here.
let a = s.execute("roto.status", json!({"layer": clip.0, "frame": 5, "matte": true})).unwrap()["matte"].clone();
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);
// `wait` still runs here.
s.execute("roto.propagate", json!({"layer": clip.0, "wait": true})).unwrap();
assert!(s.offloaded.is_empty());
}
+45
View File
@@ -326,6 +326,51 @@ fn variable_font_axes_animator() {
let _ = info;
}
#[test]
fn variable_font_axes_in_the_character_style() {
let mut s = comp(600, 200);
let t = s.execute("layer.newText", json!({"text": "Hamburg", "size": 60})).unwrap()["layer"].as_u64().unwrap();
// The attribute round-trips and is undoable even for static fonts (it is kept, unused).
s.execute("layer.setText", json!({"layer": t, "variations": {"wght": 650}})).unwrap();
let d = crate::commands::text_edit::layer_doc(&s, LayerId(t)).unwrap();
assert_eq!(d.style_at(0).variations, vec![("wght".to_string(), 650.0)]);
assert_eq!(effectcraft_keyframe::text_doc::char_style_json(&d.style_at(0))["variations"], json!({"wght": 650.0}));
s.execute("layer.setText", json!({"layer": t, "range": [0, 3], "variations": {"wght": null}})).unwrap();
let d = crate::commands::text_edit::layer_doc(&s, LayerId(t)).unwrap();
assert!(d.style_at(0).variations.is_empty() && !d.style_at(5).variations.is_empty());
s.execute("edit.undo", json!({})).unwrap();
s.execute("edit.undo", json!({})).unwrap();
assert!(crate::commands::text_edit::layer_doc(&s, LayerId(t)).unwrap().style_at(0).variations.is_empty());
assert!(s.execute("layer.setText", json!({"layer": t, "variations": 3})).is_err());
let Some((face, axes)) = effectcraft_text::variable::find_variable_face() else {
eprintln!("no variable font installed: rendering check skipped");
return;
};
let info = effectcraft_text::fonts::face(face).info.clone();
if effectcraft_text::resolve(&info.family, &info.style).face != face {
eprintln!("variable face not reachable by family/style: skipped");
return;
}
s.execute("layer.setText", json!({"layer": t, "font": info.family, "style": info.style})).unwrap();
let a = axes.iter().find(|a| a.tag == "wght" && a.max > a.min).or_else(|| axes.iter().find(|a| a.max > a.min)).unwrap().clone();
let geom = |s: &Session| {
let cid = s.active_comp_id().unwrap();
let comp = s.project.comp(cid).unwrap();
let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, comp, s.time());
let l = comp.layer(LayerId(t)).unwrap();
let paths = effectcraft_render::text::glyph_paths(&ctx, l);
let area: f64 = paths.iter().map(|(p, _)| effectcraft_text::kurbo::Shape::area(p).abs()).sum();
let right = paths.iter().map(|(p, _)| effectcraft_text::kurbo::Shape::bounding_box(p).x1).fold(f64::MIN, f64::max);
(area, right)
};
s.execute("layer.setText", json!({"layer": t, "variations": {a.tag.trim_end(): a.min}})).unwrap();
let lo = geom(&s);
s.execute("layer.setText", json!({"layer": t, "variations": {a.tag.trim_end(): a.max}})).unwrap();
let hi = geom(&s);
assert!((hi.0 - lo.0).abs() > 1.0, "{} outlines {lo:?} → {hi:?}", a.tag);
assert!((hi.1 - lo.1).abs() > 0.5, "{} advances {lo:?} → {hi:?}", a.tag);
}
#[test]
fn camera_focus_commands_undo_and_serde() {
let mut s = comp(400, 300);
+132 -16
View File
@@ -122,48 +122,147 @@ fn group(ids: &mut Ids, name: &str, items: Vec<PropGroup>, opacity: f64) -> Prop
g
}
/// A Merge Paths item in `mode` (0 Merge, 3 Intersect).
fn merge_item(ids: &mut Ids, mode: u32) -> Option<PropGroup> {
let mut g = build::shape_simple_op(ids, "merge")?;
set(&mut g, "mode", Value::Enum(mode));
Some(g)
}
/// A shape inside clipping groups: its geometry merged into one compound path (an inner group
/// with Merge Paths), the clip paths, and Merge Paths ▸ Intersect before its paint, so the fill
/// is exactly the clipped area. Open stroked paths stay unclipped (an intersection would close
/// them).
fn clipped_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine, clips: &[BezPath]) -> Vec<PropGroup> {
let items = shape_items(ids, s, m);
let path = s.geom.to_path();
let closed = path.elements().iter().any(|e| matches!(e, kurbo::PathEl::ClosePath)) || s.fill.is_some();
if clips.is_empty() || !closed {
return items;
}
let (geom, paint): (Vec<PropGroup>, Vec<PropGroup>) =
items.into_iter().partition(|g| !matches!(g.match_id.as_str(), "fill" | "stroke" | "gfill" | "gstroke"));
let mut inner = geom;
inner.extend(merge_item(ids, 0));
let mut out = vec![build::shape_group(ids, "Clipped Path", inner)];
for (i, c) in clips.iter().enumerate() {
let mut parts = shape_paths(ids, c);
parts.extend(merge_item(ids, 0));
out.push(build::shape_group(ids, &format!("Clip Path {}", i + 1), parts));
}
out.extend(merge_item(ids, 3));
out.extend(paint);
out
}
/// Shape layer contents for an SVG document, in document pixels (transforms are baked into the
/// geometry; group and element opacity go to the group transforms). Top of the paint order first.
/// geometry; group and element opacity go to the group transforms, blend modes to the groups'
/// Blend Mode). Top of the paint order first.
///
/// Clipping groups (PDF / Illustrator clipping masks): shapes inside them are intersected with
/// the clip paths through Merge Paths ▸ Intersect (see [`clipped_items`]). Clips enclosing the
/// whole document are layer masks instead ([`vector_clip_masks`], used by
/// [`shapes_from_vector`]). Images and soft masks are not converted.
pub fn svg_contents(ids: &mut Ids, doc: &Doc) -> Vec<PropGroup> {
fn walk(ids: &mut Ids, nodes: &[Node], m: Affine) -> Vec<PropGroup> {
fn walk(ids: &mut Ids, nodes: &[Node], m: Affine, clips: &[BezPath]) -> Vec<PropGroup> {
let mut out = vec![];
for n in nodes.iter().rev() {
match n {
Node::Group(g) => {
let items = walk(ids, &g.children, m * g.transform);
let gm = m * g.transform;
let mut inner_clips = clips.to_vec();
inner_clips.extend(g.clip.iter().map(|(p, _)| gm * p.clone()));
let items = walk(ids, &g.children, gm, &inner_clips);
if !items.is_empty() {
out.push(group(ids, &g.name, items, g.opacity));
let mut grp = group(ids, &g.name, items, g.opacity);
if g.blend != effectcraft_svg::BlendMode::Normal {
set(&mut grp, "blend", Value::Enum(blend_index(g.blend)));
}
out.push(grp);
}
}
Node::Shape(s) => {
let items = shape_items(ids, s, m * s.transform);
let sm = m * s.transform;
let items = if clips.is_empty() { shape_items(ids, s, sm) } else { clipped_items(ids, s, sm, clips) };
if !items.is_empty() {
out.push(group(ids, &s.name, items, s.opacity));
}
}
Node::Image(_) => {}
}
}
out
}
let root = &doc.root;
let items = walk(ids, &root.children, root.transform);
let mut clips = vec![];
clips.extend(root.clip.iter().map(|(p, _)| root.transform * p.clone()));
let items = walk(ids, &root.children, root.transform, &clips);
if (root.opacity - 1.0).abs() > 1e-9 { vec![group(ids, "svg", items, root.opacity)] } else { items }
}
/// The shape-layer Blend Mode index of an SVG / PDF blend mode.
fn blend_index(b: effectcraft_svg::BlendMode) -> u32 {
use effectcraft_color::BlendMode as P;
use effectcraft_svg::BlendMode as S;
let p = match b {
S::Normal => P::Normal,
S::Multiply => P::Multiply,
S::Screen => P::Screen,
S::Overlay => P::Overlay,
S::Darken => P::Darken,
S::Lighten => P::Lighten,
S::ColorDodge => P::ColorDodge,
S::ColorBurn => P::ColorBurn,
S::HardLight => P::HardLight,
S::SoftLight => P::SoftLight,
S::Difference => P::Difference,
S::Exclusion => P::Exclusion,
S::Hue => P::Hue,
S::Saturation => P::Saturation,
S::Color => P::Color,
S::Luminosity => P::Luminosity,
};
P::ALL.iter().position(|x| *x == p).unwrap_or(0) as u32
}
/// Clips that enclose the whole document (on a chain of single-child groups from the root, as
/// an Illustrator artboard clip or a PDF page clip), in document pixels, and the document with
/// those clips removed: Create Shapes from Vector Layer makes them layer masks.
pub fn vector_clip_masks(doc: &Doc) -> (Vec<BezPath>, Doc) {
let mut out = doc.clone();
let mut masks = vec![];
let mut m = Affine::IDENTITY;
let mut g = &mut out.root;
loop {
m *= g.transform;
for (p, _) in g.clip.drain(..) {
masks.push(m * p);
}
if g.children.len() != 1 {
break;
}
match &mut g.children[0] {
Node::Group(sub) if sub.mask.is_none() && sub.blend == effectcraft_svg::BlendMode::Normal => g = sub,
_ => break,
}
}
(masks, out)
}
/// Whether footage is a vector file (SVG / PDF / AI / EPS).
pub fn is_vector(f: &effectcraft_project::Footage) -> bool {
effectcraft_render::is_vector_footage(f) || f.path.to_ascii_lowercase().ends_with(".svg")
}
/// The vector document of an SVG / PDF / AI / EPS file (`None` for other formats), restricted
/// to one layer when `layer` names it.
pub fn vector_doc(path: &str, bytes: &[u8], layer: Option<&effectcraft_project::SourceLayer>) -> Option<Result<Doc, String>> {
/// The vector document of an SVG / PDF / AI / EPS file (`None` for other formats): page
/// `page` of a PDF, restricted to one layer when `layer` names it.
pub fn vector_doc(path: &str, bytes: &[u8], layer: Option<&effectcraft_project::SourceLayer>, page: u32) -> Option<Result<Doc, String>> {
if path.to_ascii_lowercase().ends_with(".svg") || effectcraft_svg::looks_like_svg(bytes) {
return Some(effectcraft_svg::parse(bytes).map_err(|e| format!("{path}: {e}")));
}
effectcraft_pdf::sniff(bytes)?;
Some(
effectcraft_pdf::parse(bytes)
effectcraft_pdf::parse_page(bytes, page as usize)
.map(|d| match layer {
Some(l) => effectcraft_pdf::layer_doc(&d, l.index as usize),
None => d,
@@ -172,20 +271,21 @@ pub fn vector_doc(path: &str, bytes: &[u8], layer: Option<&effectcraft_project::
)
}
/// Import a PDF / Illustrator / EPS document as a composition the size of its page: one footage
/// item per file layer (each showing only that layer, continuously rasterisable), top layer
/// first. Returns (comp, folder, items).
/// Import page `page` of a PDF / Illustrator / EPS document as a composition the size of the
/// page: one footage item per file layer (each showing only that layer, continuously
/// rasterisable), top layer first. Returns (comp, folder, items).
pub fn import_vector_comp(
proj: &mut Project,
path: &str,
bytes: &[u8],
name: &str,
page: u32,
rate: effectcraft_time::FrameRate,
duration: effectcraft_time::Tick,
) -> Result<(ItemId, ItemId, Vec<ItemId>), String> {
use effectcraft_color::Label;
use effectcraft_project::{AlphaMode, Footage, FootageKind, ItemKind, SourceLayer};
let doc = effectcraft_pdf::parse(bytes).map_err(|e| format!("{path}: {e}"))?;
let doc = effectcraft_pdf::parse_page(bytes, page as usize).map_err(|e| format!("{path}: {e}"))?;
let codec = effectcraft_pdf::codec(path, bytes).unwrap_or("PDF");
let (w, h) = doc.pixel_size();
let file = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
@@ -206,6 +306,7 @@ pub fn import_vector_comp(
loop_count: 1,
codec: codec.into(),
layer: Some(SourceLayer { index: i as u32, name: lname.clone(), layer_size: false, ..Default::default() }),
page,
..Default::default()
};
let id = proj.add_item(&format!("{lname}/{file}"), Label::Lavender, Some(folder), ItemKind::Footage(f));
@@ -239,13 +340,28 @@ fn like_source(dst: &mut Layer, src: &Layer) {
dst.switches.three_d = src.switches.three_d;
}
/// Layer ▸ Create ▸ Create Shapes from Vector Layer: `doc` is the SVG shown by `src`.
/// Layer ▸ Create ▸ Create Shapes from Vector Layer: `doc` is the SVG shown by `src`. A clip
/// enclosing the whole document becomes the layer's masks (Add, then Intersect); nested clips
/// are kept with Merge Paths (see [`svg_contents`]).
pub fn shapes_from_vector(proj: &mut Project, comp: &Comp, src: &Layer, doc: &Doc) -> Layer {
let mut l = build::layer(proj, comp, &format!("{} Outlines", src.name), LayerSource::Shape, (0, 0), None);
let items = svg_contents(&mut Ids(&mut proj.next_id), doc);
let (clips, doc) = vector_clip_masks(doc);
let mut ids = Ids(&mut proj.next_id);
let items = svg_contents(&mut ids, &doc);
if let Some(c) = l.props.sub_mut("contents") {
c.children.extend(items.into_iter().map(Into::into));
}
let mut n = 0;
for (k, clip) in clips.iter().enumerate() {
for sp in effectcraft_path::from_kurbo(clip) {
n += 1;
let mode = if k == 0 { MaskMode::Add } else { MaskMode::Intersect };
let mk = build::mask(&mut ids, &format!("Mask {n}"), sp, mode, [255, 255, 0]);
if let Some(masks) = l.props.sub_mut("masks") {
masks.children.push(mk.into());
}
}
}
copy_transform(proj, src, &mut l);
like_source(&mut l, src);
l.name = comp.unique_layer_name(&format!("{} Outlines", src.name));