Merge main into M13.10

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-03 08:59:35 -04:00
co-authored by Claude Opus 5.5
112 changed files with 16049 additions and 478 deletions
+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
),
]
}
+1 -1
View File
@@ -70,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
),
+12 -2
View File
@@ -6,7 +6,7 @@ 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;
@@ -21,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;
@@ -29,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;
@@ -38,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;
@@ -61,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;
@@ -162,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());
+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
),
]
}
+10
View File
@@ -220,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>,
@@ -794,12 +798,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;
+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
+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]);
+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();
+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:?}");
}
}
+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));