Merge main into M13.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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])
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
]
|
||||
|
||||
@@ -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
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -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!(
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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
|
||||
)]
|
||||
}
|
||||
@@ -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
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
),
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user