Skip to content

EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust

Merge main into M13.11 (bokeh kernel_spans/blur_levels, Essential Graphics as_type controls with mirrors and links)

Brandon Thomasdc132bc21975
diff --cc crates/engine/src/commands/essential.rs
index 305c3f7e4,d7340f685..cbffdc21f
--- a/crates/engine/src/commands/essential.rs
+++ b/crates/engine/src/commands/essential.rs
@@@ -88,8 -88,14 +88,17 @@@ fn add_property(s: &mut Session, p: &Va
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);
- // A property already in the panel is added again as a mirror (`mirror: false`: skipped).
+ // `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)
+ }
+ };
++ // A property already in the panel (as the same kind of control) is added again as a mirror
++ // (`mirror: false`: skipped).
+ let mirror = b_p(p, "mirror").unwrap_or(true);
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)?;
@@@ -97,113 -103,37 +106,129 @@@
if control_type(pr).is_none() {
return Err(bad(C, format!("`{}` can't be added to Essential Graphics (unsupported property type)", pr.name)));
}
- let existing = s.project.comp(*cid).and_then(|c| c.essential.as_ref()).and_then(|e| e.driver_of(*lid, *uid)).map(|c| (c.id, c.name.clone()));
- let kind = match existing {
+ // 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;
- }
- let name = rename.clone().unwrap_or_else(|| match as_type {
++ let eg = s.project.comp(*cid).and_then(|c| c.essential.as_ref());
++ let existing = eg
++ .and_then(|e| e.control_for_as(*lid, *uid, as_type).or_else(|| as_type.is_none().then(|| e.driver_of(*lid, *uid)).flatten()))
++ .map(|c| (c.id, c.name.clone()));
++ let (kind, as_type) = match existing {
+ Some(_) if !mirror => continue,
- Some((of, _)) => EgKind::Mirror { of },
- None => EgKind::Property { layer: *lid, prop: *uid, links: vec![] },
++ Some((of, _)) => (EgKind::Mirror { of }, None),
++ None => (EgKind::Property { layer: *lid, prop: *uid, links: vec![] }, as_type),
+ };
- let name = rename.clone().or(existing.map(|e| e.1)).unwrap_or_else(|| pr.name.clone());
- added.push((*cid, kind, name));
++ let name = rename.clone().or(existing.map(|e| e.1)).unwrap_or_else(|| match as_type {
+ Some(ControlType::Font) => format!("{} Font", l.name),
+ _ => pr.name.clone(),
+ });
- added.push((*cid, *lid, *uid, name, as_type));
++ added.push((*cid, kind, 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, kind, name)) in added.iter().enumerate() {
- for (k, (cid, lid, uid, name, as_type)) in added.iter().enumerate() {
++ for (k, (cid, kind, 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: kind.clone() }, 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 };
++ let ctl = EgControl { id, name: name.clone(), kind: kind.clone(), as_type: *as_type };
+ insert(eg, ctl, group, index.map(|i| i + k), C)?;
ids.push(id);
}
Ok(ids)
})?;
- Ok(json!({"controls": ids}))
+ let mirrors: Vec<u64> = ids.iter().zip(&added).filter(|(_, a)| matches!(a.1, EgKind::Mirror { .. })).map(|(i, _)| *i).collect();
+ Ok(json!({"controls": ids, "mirrors": mirrors}))
+}
-
+/// Add a mirror of a property control (the same property shown again, e.g. in another group).
+fn add_mirror(s: &mut Session, p: &Value) -> Result<Value> {
+ const C: &str = "essential.addMirror";
+ let cid = eg_comp(s, p)?;
+ let of = control_p(p, C)?;
+ let eg = s.project.comp(cid).and_then(|c| c.essential.clone()).unwrap_or_default();
+ let master =
+ eg.resolve(of).filter(|c| matches!(c.kind, EgKind::Property { .. })).ok_or_else(|| bad(C, format!("control {of} is not a property control")))?;
+ let (of, master_name) = (master.id, master.name.clone());
+ let name = str_p(p, "name").map(str::to_string).unwrap_or(master_name);
+ 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 id = s.edit("Add Mirror to Essential Graphics", None, |proj, _| {
+ let id = proj.alloc();
- insert(eg_of(proj, cid)?, EgControl { id, name, kind: EgKind::Mirror { of } }, group, index, C)?;
++ insert(eg_of(proj, cid)?, EgControl { id, name, kind: EgKind::Mirror { of }, as_type: None }, group, index, C)?;
+ Ok(id)
+ })?;
+ Ok(json!({"control": id, "of": of}))
+}
+
+/// The property a link command names: `{layer, path|prop}` or the first selected property.
+fn link_target(s: &Session, p: &Value, cmd: &str) -> Result<(ItemId, LayerId, Uid)> {
+ if p.get("path").is_some() || p.get("prop").is_some() {
+ return super::prop::prop_ref(s, p, cmd);
+ }
+ let cid = comp_id(s, p)?;
+ selected_leaf_props(s)
+ .into_iter()
+ .next()
+ .map(|(l, u)| (cid, l, u))
+ .ok_or_else(|| bad(cmd, "select a property in the timeline (or give `layer` and `path`)"))
+}
+
+/// Make a property control drive another property too (same kind of value).
+fn link_property(s: &mut Session, p: &Value) -> Result<Value> {
+ const C: &str = "essential.linkProperty";
+ let cid = eg_comp(s, p)?;
+ let control = control_p(p, C)?;
+ let (pc, lid, uid) = link_target(s, p, C)?;
+ if pc != cid {
+ return Err(bad(C, "the property must be in the Essential Graphics composition"));
+ }
+ let eg = s.project.comp(cid).and_then(|c| c.essential.clone()).unwrap_or_default();
+ let ctl = eg.resolve(control).ok_or_else(|| bad(C, format!("no control {control}")))?.clone();
++ if ctl.as_type == Some(ControlType::Font) {
++ return Err(bad(C, "a Font control can't drive other properties"));
++ }
+ let (main, _) = essential::source_prop(&s.project, cid, &ctl).ok_or_else(|| bad(C, format!("control {control} is not a property control")))?;
+ let main = main.props.find(match ctl.kind {
+ EgKind::Property { prop, .. } => prop,
+ _ => 0,
+ });
+ let target = s.project.comp(cid).and_then(|c| c.layer(lid)).and_then(|l| l.props.find(uid)).ok_or_else(|| bad(C, "no such property"))?;
+ if !main.is_some_and(|m| essential::linkable(m, target)) {
+ return Err(bad(C, format!("`{}` is not the same kind of property as the control", target.name)));
+ }
+ if let Some(d) = eg.driver_of(lid, uid) {
+ return Err(bad(C, format!("`{}` is already driven by control {}", target.name, d.id)));
+ }
+ let id = ctl.id;
+ s.edit("Link Property to Essential Graphics Control", None, |proj, _| {
+ if let Some(EgControl { kind: EgKind::Property { links, .. }, .. }) = eg_of(proj, cid)?.find_mut(id) {
+ links.push(essential::EgLink { layer: lid, prop: uid });
+ }
+ Ok(())
+ })?;
+ Ok(json!({"control": id, "layer": lid.0, "prop": uid}))
+}
+
+fn unlink_property(s: &mut Session, p: &Value) -> Result<Value> {
+ const C: &str = "essential.unlinkProperty";
+ let cid = eg_comp(s, p)?;
+ let control = control_p(p, C)?;
+ let (_, lid, uid) = link_target(s, p, C)?;
+ let eg = s.project.comp(cid).and_then(|c| c.essential.clone()).unwrap_or_default();
+ let id = eg.resolve(control).map(|c| c.id).ok_or_else(|| bad(C, format!("no control {control}")))?;
+ s.edit("Unlink Property from Essential Graphics Control", None, |proj, _| match eg_of(proj, cid)?.find_mut(id) {
+ Some(EgControl { kind: EgKind::Property { links, .. }, .. }) if links.iter().any(|k| k.layer == lid && k.prop == uid) => {
+ links.retain(|k| !(k.layer == lid && k.prop == uid));
+ Ok(())
+ }
+ _ => Err(bad(C, "the property is not linked to this control")),
+ })?;
+ Ok(json!({"control": id, "layer": lid.0, "prop": uid}))
}
fn control_type(pr: &effectcraft_project::Property) -> Option<ControlType> {
@@@ -399,24 -387,9 +492,27 @@@ fn control_json(project: &Project, cid
"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(),
+ "links": links,
+ "mirrors": project.comp(cid).and_then(|c| c.essential.as_ref()).map(|e| e.mirrors_of(c.id)).unwrap_or_default(),
+ })
+ }
+ EgKind::Mirror { of } => {
++ // Shown as its master (same kind of control).
++ let master = project.comp(cid).and_then(|x| x.essential.as_ref()).and_then(|e| e.resolve(c.id)).cloned();
+ let src = essential::source_prop(project, cid, c);
++ let ty = |pr| master.as_ref().and_then(|m| essential::effective_type(m, pr));
+ json!({
+ "id": c.id, "name": c.name, "kind": "mirror", "of": of,
+ "layer": src.map(|(l, _)| l.id.0),
+ "prop": src.map(|(_, pr)| pr.uid),
+ "layerName": src.map(|(l, _)| l.name.clone()),
+ "path": src.and_then(|(l, pr)| super::match_path_of(&l.props, pr.uid)),
- "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)| ty(pr)),
++ "value": src.map(|(_, pr)| value_json(ty(pr), &pr.value_at(Tick::ZERO))),
+ "missing": src.is_none(),
})
}
EgKind::Media { layer } => json!({
@@@ -602,34 -570,40 +704,44 @@@ fn push_to_comp(s: &mut Session, p: &Va
let l = s.project.comp(cid).and_then(|c| c.layer(lid)).cloned().ok_or(EngineError::NoComp)?;
let mut writes = vec![];
for (control, uid) in &ts {
- let (Some(ctl), Some(pr)) = (eg.find(*control), l.props.find(*uid)) else { continue };
+ // A mirror pushes into its master's properties.
+ let (Some(ctl), Some(pr)) = (eg.resolve(*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) => {
++ 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);
- // the source property's keys are in the inner layer's time.
- let keys: Vec<_> = pr
- .keys
- .iter()
- .map(|k| {
- let mut k = k.clone();
- k.time = inner.layer_time(k.time);
- k
- })
- .collect();
- if let Some(target) = inner.props.find_mut(*prop) {
- target.value = pr.value.clone();
- target.keys = keys;
+ EgKind::Property { .. } => {
+ for (layer, prop) in kind.targets() {
+ let Some(inner) = sc.layer_mut(layer) else { continue };
+ // Instance keys are in the precomp layer's time (= the source comp's
+ // time); the source property's keys are in the inner layer's time.
+ let keys: Vec<_> = pr
+ .keys
+ .iter()
+ .map(|k| {
+ let mut k = k.clone();
+ k.time = inner.layer_time(k.time);
+ k
+ })
+ .collect();
+ if let Some(target) = inner.props.find_mut(prop) {
+ target.value = pr.value.clone();
+ target.keys = keys;
+ }
}
}
++
EgKind::Media { layer } => {
if let Some(inner) = sc.layer_mut(*layer) {
inner.source = LayerSource::Footage { item: ItemId(pr.value.as_f64().max(0.0) as u64) };
@@@ -869,7 -843,7 +981,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?, mirror?: bool (a property already present is added as a mirror; default true)}",
- "{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)}",
++ "{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), mirror?: bool (a property already present is added as a mirror; default true)}",
has_selected_props,
add_property
),
diff --cc crates/engine/src/tests_essential_more.rs
index 000000000,314f7b6d0..a8d8dc808
mode 000000,100644..100644
--- a/crates/engine/src/tests_essential_more.rs
+++ b/crates/engine/src/tests_essential_more.rs
@@@ -1,0 -1,94 +1,104 @@@
+ //! 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.
++ // Adding the same font control again adds nothing with `mirror: false` (else a mirror of
++ // it); 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()
++ s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font", "mirror": false})).unwrap()["controls"]
++ .as_array()
++ .unwrap()
++ .is_empty()
+ );
++ let m = s.execute("essential.addProperty", json!({"layer": text, "path": "text/sourceText", "as": "font"})).unwrap();
++ assert_eq!(m["mirrors"].as_array().unwrap().len(), 1);
++ let ml = s.execute("essential.list", json!({})).unwrap();
++ let mirror = ml["controls"].as_array().unwrap().iter().find(|c| c["kind"] == "mirror").unwrap().clone();
++ assert_eq!((mirror["of"].as_u64(), mirror["type"].as_str()), (Some(f), Some("font")));
++ s.execute("edit.undo", json!({})).unwrap();
+ 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");
+ }
diff --cc crates/gpu/src/adv3d.rs
index 93352fe34,6e428c846..677db3e5f
--- a/crates/gpu/src/adv3d.rs
+++ b/crates/gpu/src/adv3d.rs
@@@ -342,381 -316,3 +342,381 @@@ pub(crate) fn render(g: &GpuContext, s
.collect();
Some(Target { width: s.width, height: s.height, color, depth })
}
+
+// ---------------------------------------------------------------- after the rasteriser
+
+/// Compute kernels of `adv3d.wgsl` (resolve, motion-blur accumulation, depth of field,
+/// encoding, compositing, wireframes) with their shared bind group layout and the placeholder
+/// resources bound to the slots a kernel doesn't use.
+pub(crate) struct Post {
+ bgl: wgpu::BindGroupLayout,
+ kernels: Vec<(&'static str, wgpu::ComputePipeline)>,
+ /// Placeholders for bindings 3–9 (distinct buffers: writable bindings must not alias).
+ dummy_bufs: Vec<wgpu::Buffer>,
+ dummy_color: wgpu::TextureView,
+ dummy_z: wgpu::TextureView,
+ dummy_out: wgpu::TextureView,
+}
+
+const KERNELS: &[&str] = &["resolve", "radius_of", "boost", "prefix_rows", "gather", "finish", "wire"];
+
+impl Post {
+ fn new(device: &wgpu::Device) -> Post {
+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("effectcraft advanced 3d post"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("shaders/adv3d.wgsl").into()),
+ });
+ let tex = |binding| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: false },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ };
+ let buf = |binding, read_only| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None },
+ count: None,
+ };
+ let entries = [
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
+ count: None,
+ },
+ tex(1),
+ tex(2),
+ buf(3, false),
+ buf(4, false),
+ buf(5, false),
+ buf(6, true),
+ buf(7, false),
+ buf(8, false),
+ buf(9, false),
+ wgpu::BindGroupLayoutEntry {
+ binding: 10,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::StorageTexture {
+ access: wgpu::StorageTextureAccess::WriteOnly,
+ format: crate::context::FORMAT,
+ view_dimension: wgpu::TextureViewDimension::D2,
+ },
+ count: None,
+ },
+ ];
+ let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("advanced 3d post"), entries: &entries });
+ let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("advanced 3d post"),
+ bind_group_layouts: &[Some(&bgl)],
+ immediate_size: 0,
+ });
+ let kernels = KERNELS
+ .iter()
+ .map(|k| {
+ let p = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some(k),
+ layout: Some(&layout),
+ module: &module,
+ entry_point: Some(k),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ (*k, p)
+ })
+ .collect();
+ let dummy_bufs = (3..=9)
+ .map(|_| {
+ device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("adv3d dummy"),
+ size: 16,
+ usage: wgpu::BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ })
+ })
+ .collect();
+ let tex1 = |format, usage| {
+ device
+ .create_texture(&wgpu::TextureDescriptor {
+ label: Some("adv3d dummy"),
+ size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format,
+ usage,
+ view_formats: &[],
+ })
+ .create_view(&Default::default())
+ };
+ Post {
+ bgl,
+ kernels,
+ dummy_bufs,
+ dummy_color: tex1(COLOR, wgpu::TextureUsages::TEXTURE_BINDING),
+ dummy_z: tex1(DEPTH_OUT, wgpu::TextureUsages::TEXTURE_BINDING),
+ dummy_out: tex1(crate::context::FORMAT, wgpu::TextureUsages::STORAGE_BINDING),
+ }
+ }
+}
+
+/// The resources of one post kernel dispatch (unset slots get placeholders).
+#[derive(Default)]
+struct Binds<'b> {
+ color: Option<&'b wgpu::TextureView>,
+ z: Option<&'b wgpu::TextureView>,
+ /// Bindings 3–9: acc, depth, src, table, radius, range, prefix.
+ bufs: [Option<&'b wgpu::Buffer>; 7],
+ out: Option<&'b wgpu::TextureView>,
+}
+
+/// Uniform block of the post kernels (`Post` in `adv3d.wgsl`).
+fn params(u0: [u32; 4], f0: [f32; 4]) -> Vec<u8> {
+ let mut v: Vec<u8> = u0.iter().flat_map(|x| x.to_le_bytes()).collect();
+ v.extend([0u8; 16]);
+ v.extend(f0.iter().flat_map(|x| x.to_le_bytes()));
+ v.extend([0u8; 16]);
+ v
+}
+
+fn dispatch(e: &mut Enc, kernel: &str, u0: [u32; 4], f0: [f32; 4], b: Binds, groups: (u32, u32)) {
+ let g = e.g;
+ let post = &pipes(g).post;
+ let Some((_, pipe)) = post.kernels.iter().find(|(k, _)| *k == kernel) else { return };
+ let ub = g.device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, contents: &params(u0, f0), usage: wgpu::BufferUsages::UNIFORM });
+ let mut entries = vec![
+ wgpu::BindGroupEntry { binding: 0, resource: ub.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(b.color.unwrap_or(&post.dummy_color)) },
+ wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(b.z.unwrap_or(&post.dummy_z)) },
+ ];
+ for (i, buf) in b.bufs.iter().enumerate() {
+ entries.push(wgpu::BindGroupEntry { binding: 3 + i as u32, resource: buf.unwrap_or(&post.dummy_bufs[i]).as_entire_binding() });
+ }
+ entries.push(wgpu::BindGroupEntry { binding: 10, resource: wgpu::BindingResource::TextureView(b.out.unwrap_or(&post.dummy_out)) });
+ let bg = g.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some(kernel), layout: &post.bgl, entries: &entries });
+ let enc = e.encoder();
+ let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(kernel), timestamp_writes: None });
+ pass.set_pipeline(pipe);
+ pass.set_bind_group(0, &bg, &[]);
+ pass.dispatch_workgroups(groups.0.max(1), groups.1.max(1), 1);
+}
+
+fn pixel_groups(w: u32, h: u32) -> (u32, u32) {
+ (w.div_ceil(16), h.div_ceil(16))
+}
+
+fn storage_buf(g: &GpuContext, size: u64, label: &str) -> wgpu::Buffer {
+ g.device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some(label),
+ size: size.max(16),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ })
+}
+
+/// Read a storage buffer back (submits and waits).
+fn read_buffer(e: &mut Enc, buf: &wgpu::Buffer, size: u64) -> Option<Vec<u8>> {
+ if !e.g.can_readback() {
+ return None;
+ }
+ let rb = e.g.device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("adv3d readback"),
+ size,
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ e.encoder().copy_buffer_to_buffer(buf, 0, &rb, 0, size);
+ e.submit();
+ let (tx, rx) = std::sync::mpsc::channel();
+ rb.map_async(wgpu::MapMode::Read, .., move |r| {
+ let _ = tx.send(r);
+ });
+ e.g.device.poll(wgpu::PollType::wait_indefinitely()).ok()?;
+ rx.recv().ok()?.ok()?;
+ let out = rb.get_mapped_range(..).ok()?.to_vec();
+ rb.unmap();
+ Some(out)
+}
+
+/// A resolved run on the GPU: premultiplied linear (or working-space) colour and camera depth
+/// (`BIG` where nothing was drawn), one entry per output pixel.
+struct Resolved {
+ acc: wgpu::Buffer,
+ depth: wgpu::Buffer,
+ width: u32,
+ height: u32,
+}
+
+/// The rasteriser's "nothing drawn" depth on the GPU (∞ on the CPU).
+const BIG: f32 = 3.0e38;
+
+/// Rasterise every motion-blur sub-sample of a prepared run, resolve and average them, then
+/// apply the depth of field (`render_prepared`'s steps). `None` = can't run here (sizes,
+/// limits, or a depth of field without readback); `Some(None)` = nothing drawn.
+fn resolve_run(e: &mut Enc, prep: &Prepared) -> Option<Option<Resolved>> {
+ let (w, h) = prep.out;
+ let g = e.g;
+ if !g.fits(w, h) || (prep.dof.is_some() && !g.can_readback()) {
+ return None;
+ }
+ let px = w as u64 * h as u64;
+ let max = g.device.limits().max_storage_buffer_binding_size;
+ if px * 16 > max {
+ return None;
+ }
+ let acc = storage_buf(g, px * 16, "adv3d acc");
+ let depth = storage_buf(g, px * 4, "adv3d depth");
+ let n = prep.samples.max(1);
+ let weight = if n <= 1 { 1.0 } else { 1.0 / n as f32 };
+ let mut first = true;
+ for i in 0..n {
+ let s = prep.scene(i);
+ if s.indices.is_empty() {
+ continue;
+ }
+ if s.width != w * s.ssaa.max(1) || s.height != h * s.ssaa.max(1) {
+ return None;
+ }
+ let (color, zout) = raster_into(e, &s)?;
+ let (cv, zv) = (color.create_view(&Default::default()), zout.create_view(&Default::default()));
+ let b = Binds { color: Some(&cv), z: Some(&zv), bufs: [Some(&acc), Some(&depth), None, None, None, None, None], out: None };
+ dispatch(e, "resolve", [w, h, s.ssaa.max(1), first as u32], [weight, 0.0, 0.0, 0.0], b, pixel_groups(w, h));
+ first = false;
+ // One sub-sample's targets alive at a time.
+ e.submit();
+ }
+ if first {
+ return Some(None);
+ }
+ if let Some(dof) = &prep.dof {
+ depth_of_field(e, &acc, &depth, (w, h), dof, prep.scale)?;
+ }
+ Some(Some(Resolved { acc, depth, width: w, height: h }))
+}
+
+/// `adv::depth_of_field` on the resolved buffers: radii, highlights, prefix sums, the iris
+/// gather at the levels around each pixel's radius. The result replaces `acc`.
+fn depth_of_field(e: &mut Enc, acc: &wgpu::Buffer, depth: &wgpu::Buffer, (w, h): (u32, u32), dof: &Dof, scale: f64) -> Option<()> {
+ let g = e.g;
+ let px = w as u64 * h as u64;
+ if (w as u64 + 1) * h as u64 * 16 > g.device.limits().max_storage_buffer_binding_size {
+ return None;
+ }
+ let radius = storage_buf(g, px * 4, "adv3d radius");
+ let mut init = Vec::with_capacity(16);
+ for v in [f32::INFINITY.to_bits(), 0, 0, 0] {
+ init.extend_from_slice(&v.to_le_bytes());
+ }
+ let range = g.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("adv3d radius range"),
+ contents: &init,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+ let f0 = [dof.focus as f32, dof.aperture as f32, dof.blur_level as f32, scale as f32];
+ let b = Binds { bufs: [None, Some(depth), None, None, Some(&radius), Some(&range), None], ..Default::default() };
+ dispatch(e, "radius_of", [w, h, 0, 0], f0, b, pixel_groups(w, h));
+ let rb = read_buffer(e, &range, 16)?;
+ let lo = f32::from_bits(u32::from_le_bytes([rb[0], rb[1], rb[2], rb[3]]));
+ let hi = f32::from_bits(u32::from_le_bytes([rb[4], rb[5], rb[6], rb[7]]));
+ if hi < 0.5 {
+ return Some(());
+ }
- let Some(levels) = bokeh::progressive_levels(lo, hi) else { return Some(()) };
++ let Some(levels) = bokeh::blur_levels(&[lo, hi]) else { return Some(()) };
+ // Level headers, then every level's weighted spans.
+ let mut heads: Vec<[f32; 4]> = vec![];
+ let mut spans: Vec<[f32; 4]> = vec![];
+ for &r in &levels {
- match bokeh::kernel(&dof.iris, r as f64) {
++ match bokeh::kernel_spans(&dof.iris, r as f64) {
+ Some((kernels, norm)) => {
+ let first = levels.len() + spans.len();
+ for (wt, sp) in &kernels {
+ spans.extend(sp.iter().map(|&(dy, x0, x1)| [dy as f32, x0 as f32, x1 as f32, *wt]));
+ }
+ let count = levels.len() + spans.len() - first;
+ heads.push([first as f32, count as f32, 1.0 / norm, 0.0]);
+ }
+ None => heads.push([0.0, 0.0, 0.0, 1.0]),
+ }
+ }
+ let table: Vec<u8> = heads.iter().chain(&spans).flatten().flat_map(|x| x.to_le_bytes()).collect();
+ if table.len() as u64 > g.device.limits().max_storage_buffer_binding_size {
+ return None;
+ }
+ let table = e.bytes(table);
+ let src = storage_buf(g, px * 16, "adv3d dof source");
+ let prefix = storage_buf(g, (w as u64 + 1) * h as u64 * 16, "adv3d prefix");
+ let hl = dof.highlight;
+ let b = Binds { bufs: [Some(acc), None, Some(&src), None, Some(&radius), None, None], ..Default::default() };
+ dispatch(e, "boost", [w, h, 0, 0], [hl.gain as f32, hl.threshold as f32, hl.saturation as f32, 0.0], b, pixel_groups(w, h));
+ let b = Binds { bufs: [None, None, Some(&src), None, None, None, Some(&prefix)], ..Default::default() };
+ dispatch(e, "prefix_rows", [w, h, 0, 0], [0.0; 4], b, (h.div_ceil(64), 1));
+ let b = Binds { bufs: [Some(acc), None, Some(&src), Some(&table), Some(&radius), None, Some(&prefix)], ..Default::default() };
+ dispatch(e, "gather", [w, h, levels.len() as u32, 0], [lo, hi, 0.0, 0.0], b, pixel_groups(w, h));
+ e.submit();
+ Some(())
+}
+
+/// The resolved run as an image in the canvas's encoding, composited over `canvas` when given.
+fn finish(e: &mut Enc, r: &Resolved, encode: bool, canvas: Option<&GpuImage>) -> GpuImage {
+ let out = e.image(r.width, r.height);
+ let ov = out.texture.create_view(&Default::default());
+ let cv = canvas.map(|c| c.texture.create_view(&Default::default()));
+ let b = Binds { color: cv.as_ref(), bufs: [Some(&r.acc), None, None, None, None, None, None], out: Some(&ov), ..Default::default() };
+ dispatch(e, "finish", [r.width, r.height, encode as u32, canvas.is_some() as u32], [0.0; 4], b, pixel_groups(r.width, r.height));
+ out
+}
+
+/// [`effectcraft_render::Accelerator::render_3d`]: the whole prepared run on the GPU, read
+/// back.
+pub(crate) fn render_prepared(g: &GpuContext, prep: &Prepared) -> Option<Rendered> {
+ if !g.can_readback() {
+ return None;
+ }
+ let mut e = Enc::new(g);
+ let Some(r) = resolve_run(&mut e, prep)? else { return Some(None) };
+ let img = finish(&mut e, &r, !prep.linear, None);
+ let img = e.download(&img)?;
+ let px = r.width as u64 * r.height as u64;
+ let db = read_buffer(&mut e, &r.depth, px * 4)?;
+ let depth = db
+ .chunks_exact(4)
+ .map(|c| {
+ let z = f32::from_le_bytes([c[0], c[1], c[2], c[3]]);
+ if z >= BIG * 0.5 { f32::INFINITY } else { z }
+ })
+ .collect();
+ Some(Some((img, depth)))
+}
+
+/// Draw a prepared run over the GPU canvas (the compositor's walk; no readback unless the
+/// depth of field needs its radius range). `None` = render it on the CPU.
+pub(crate) fn draw_run(e: &mut Enc, prep: &Prepared, canvas: &GpuImage) -> Option<GpuImage> {
+ if (canvas.width, canvas.height) != prep.out {
+ return None;
+ }
+ match resolve_run(e, prep)? {
+ None => Some(canvas.clone()),
+ Some(r) => Some(finish(e, &r, !prep.linear, Some(canvas))),
+ }
+}
+
+/// Wireframe-quality layer outlines: `canvas` with `pixels` set to opaque white
+/// ([`effectcraft_render::Renderer::wireframe_pixels`]).
+pub(crate) fn wireframe(e: &mut Enc, canvas: &GpuImage, pixels: &[(u32, u32)]) -> GpuImage {
+ let out = e.image(canvas.width, canvas.height);
+ e.copy_into(canvas, &out, 0, 0);
+ if pixels.is_empty() {
+ return out;
+ }
+ let table: Vec<u8> = pixels.iter().flat_map(|&(x, y)| [x as f32, y as f32, 0.0, 0.0]).flat_map(f32::to_le_bytes).collect();
+ let table = e.bytes(table);
+ let ov = out.texture.create_view(&Default::default());
+ let b = Binds { bufs: [None, None, None, Some(&table), None, None, None], out: Some(&ov), ..Default::default() };
+ let n = pixels.len() as u32;
+ dispatch(e, "wire", [n, 0, 0, 0], [0.0; 4], b, (n.div_ceil(64), 1));
+ out
+}
diff --cc crates/project/src/essential.rs
index bbf3b62c6,71a38a0c8..fcf2cfb3b
--- a/crates/project/src/essential.rs
+++ b/crates/project/src/essential.rs
@@@ -172,46 -213,18 +230,51 @@@ impl EssentialGraphics
},
}
}
- /// The control exposing property `prop` of `layer` (its main property), if any.
+ /// The control exposing property `prop` of `layer`, if any.
pub fn control_for(&self, layer: LayerId, prop: Uid) -> Option<&EgControl> {
- self.flat().into_iter().find(|c| matches!(c.kind, EgKind::Property { layer: l, prop: p } if l == layer && p == prop))
+ self.flat().into_iter().find(|c| matches!(c.kind, EgKind::Property { layer: l, prop: p, .. } if l == layer && p == prop))
}
+ /// The control exposing property `prop` of `layer` as `as_type` (`None` = its natural
+ /// control): a property can have one control of each kind (Source Text as Text and Font).
+ pub fn control_for_as(&self, layer: LayerId, prop: Uid, as_type: Option<ControlType>) -> Option<&EgControl> {
- self.flat().into_iter().find(|c| c.as_type == as_type && matches!(c.kind, EgKind::Property { layer: l, prop: p } if l == layer && p == prop))
++ self.flat().into_iter().find(|c| c.as_type == as_type && matches!(c.kind, EgKind::Property { layer: l, prop: p, .. } if l == layer && p == prop))
++ }
+ /// The property control a property drives: its main property or one of its links.
+ pub fn driver_of(&self, layer: LayerId, prop: Uid) -> Option<&EgControl> {
+ self.flat().into_iter().find(|c| match &c.kind {
+ EgKind::Property { layer: l, prop: p, links } => (*l == layer && *p == prop) || links.iter().any(|k| k.layer == layer && k.prop == prop),
+ _ => false,
+ })
+ }
+ /// The control a mirror shows (following mirrors of mirrors); the control itself otherwise.
+ pub fn resolve(&self, id: u64) -> Option<&EgControl> {
+ let mut c = self.find(id)?;
+ for _ in 0..8 {
+ match c.kind {
+ EgKind::Mirror { of } => c = self.find(of)?,
+ _ => return Some(c),
+ }
+ }
+ None
+ }
+ /// Mirrors of control `id`.
+ pub fn mirrors_of(&self, id: u64) -> Vec<u64> {
+ self.flat().into_iter().filter(|c| matches!(c.kind, EgKind::Mirror { .. }) && self.resolve(c.id).is_some_and(|m| m.id == id)).map(|c| c.id).collect()
}
- /// Controls an instance can override (properties and media; not comments or groups).
+ /// Controls an instance can override (properties, mirrors and media; not comments or
+ /// groups).
pub fn has_instance_controls(&self) -> bool {
- self.flat().iter().any(|c| matches!(c.kind, EgKind::Property { .. } | EgKind::Media { .. }))
+ self.flat().iter().any(|c| matches!(c.kind, EgKind::Property { .. } | EgKind::Mirror { .. } | EgKind::Media { .. }))
+ }
+}
+
+impl EgKind {
+ /// Every property a property control drives: the main one, then the links.
+ pub fn targets(&self) -> Vec<(LayerId, Uid)> {
+ match self {
+ EgKind::Property { layer, prop, links } => std::iter::once((*layer, *prop)).chain(links.iter().map(|k| (k.layer, k.prop))).collect(),
+ _ => vec![],
+ }
}
}
@@@ -253,77 -258,6 +316,78 @@@ pub fn source_prop<'a>(project: &'a Pro
Some((l, l.props.find(prop)?))
}
+/// The linked properties of a property control that exist in `project`: (layer, property).
+pub fn linked_props<'a>(project: &'a Project, comp: ItemId, c: &EgControl) -> Vec<(&'a Layer, &'a Property)> {
+ let Some(cm) = project.comp(comp) else { return vec![] };
+ match &c.kind {
+ EgKind::Property { links, .. } => links.iter().filter_map(|k| cm.layer(k.layer).and_then(|l| l.props.find(k.prop).map(|p| (l, p)))).collect(),
+ _ => vec![],
+ }
+}
+
+/// Whether property `b` can be driven by a control showing `a` (the same kind of value).
+pub fn linkable(a: &Property, b: &Property) -> bool {
+ control_type(a).is_some() && control_type(a) == control_type(b) && std::mem::discriminant(&a.value) == std::mem::discriminant(&b.value)
+}
+
+/// The properties a control drives stay equal: when this edit (`before` → `p`) changed one of
+/// them, its value and keyframes (moved to each layer's time) go to all the others; otherwise
+/// the main property's do.
+fn sync_links(before: &Project, p: &mut Project) {
+ let ids: Vec<ItemId> = p.comps().map(|(i, _)| *i).collect();
+ for cid in ids {
+ let Some(comp) = p.comp(cid) else { continue };
+ let Some(eg) = &comp.essential else { continue };
+ let old = before.comp(cid);
+ let mut writes: Vec<(LayerId, Uid, Value, Vec<crate::Keyframe>)> = vec![];
+ for c in eg.flat() {
+ let targets = c.kind.targets();
- if targets.len() < 2 {
++ // Font controls take only the font: they never drive whole values.
++ if targets.len() < 2 || c.as_type == Some(ControlType::Font) {
+ continue;
+ }
+ let get = |cm: &crate::Comp, (l, u): (LayerId, Uid)| cm.layer(l).and_then(|l| l.props.find(u).cloned());
+ let changed = |t: (LayerId, Uid)| match (get(comp, t), old.and_then(|o| get(o, t))) {
+ (Some(a), Some(b)) => a.value != b.value || a.keys != b.keys,
+ _ => false,
+ };
+ // The edited property leads (the main one when several changed).
+ let lead = targets.iter().copied().find(|t| changed(*t)).filter(|t| !changed(targets[0]) || *t == targets[0]).unwrap_or(targets[0]);
+ let Some(src_l) = comp.layer(lead.0) else { continue };
+ let Some(src) = src_l.props.find(lead.1) else { continue };
+ for k in targets.iter().filter(|t| **t != lead) {
+ let Some(l) = comp.layer(k.0) else { continue };
+ let Some(dst) = l.props.find(k.1) else { continue };
+ if !linkable(src, dst) {
+ continue;
+ }
+ let keys: Vec<_> = src
+ .keys
+ .iter()
+ .map(|kf| {
+ let mut kf = kf.clone();
+ kf.time = l.layer_time(src_l.comp_time(kf.time));
+ kf
+ })
+ .collect();
+ if dst.value != src.value || dst.keys != keys {
+ writes.push((k.0, k.1, src.value.clone(), keys));
+ }
+ }
+ }
+ if writes.is_empty() {
+ continue;
+ }
+ let Some(c) = p.comp_mut(cid) else { continue };
+ for (lid, uid, v, keys) in writes {
+ if let Some(pr) = c.layer_mut(lid).and_then(|l| l.props.find_mut(uid)) {
+ pr.value = v;
+ pr.keys = keys;
+ }
+ }
+ }
+}
+
/// The footage item a media control shows by default (the layer's own source).
pub fn source_media(project: &Project, comp: ItemId, c: &EgControl) -> Option<ItemId> {
let EgKind::Media { layer } = c.kind else { return None };
@@@ -590,17 -448,27 +654,31 @@@ pub fn with_overrides(project: &Project
let mut p = project.clone();
let c = p.comp_mut(comp)?;
let mut any = false;
- for o in overrides {
- // A mirror's value is its master's.
+ // Whole values first, then Font controls (which change only the font of whatever text the
- // instance shows).
- let is_font = |o: &&Override| eg.find(o.control).is_some_and(|c| c.as_type == Some(ControlType::Font));
++ // instance shows). A mirror acts as its master control.
++ let is_font = |o: &&Override| eg.resolve(o.control).is_some_and(|c| c.as_type == Some(ControlType::Font));
+ let ordered = overrides.iter().filter(|o| !is_font(o)).chain(overrides.iter().filter(is_font));
+ for o in ordered {
- let Some(ctl) = eg.find(o.control) else { continue };
- match ctl.kind {
- EgKind::Property { layer, prop } if ctl.as_type == Some(ControlType::Font) => {
- if let Some(pr) = c.layer_mut(layer).and_then(|l| l.props.find_mut(prop)) {
- merge_font(&mut pr.value, &o.value);
- for k in &mut pr.keys {
- merge_font(&mut k.value, &o.value);
+ let Some(ctl) = eg.resolve(o.control) else { continue };
+ match &ctl.kind {
++ EgKind::Property { .. } if ctl.as_type == Some(ControlType::Font) => {
++ for (layer, prop) in ctl.kind.targets() {
++ if let Some(pr) = c.layer_mut(layer).and_then(|l| l.props.find_mut(prop)) {
++ merge_font(&mut pr.value, &o.value);
++ for k in &mut pr.keys {
++ merge_font(&mut k.value, &o.value);
++ }
++ any = true;
+ }
- any = true;
+ }
+ }
- EgKind::Property { layer, prop } => {
- if let Some(pr) = c.layer_mut(layer).and_then(|l| l.props.find_mut(prop)) {
- pr.keys.clear();
- pr.value = o.value.clone();
- any = true;
+ EgKind::Property { .. } => {
+ for (layer, prop) in ctl.kind.targets() {
+ if let Some(pr) = c.layer_mut(layer).and_then(|l| l.props.find_mut(prop)) {
+ pr.keys.clear();
+ pr.value = o.value.clone();
+ any = true;
+ }
}
}
EgKind::Media { layer } => {
diff --cc crates/script/src/prelude.js
index 9fde823dd,897beeaaa..c06bc9bfa
--- a/crates/script/src/prelude.js
+++ b/crates/script/src/prelude.js
@@@ -1366,38 -1433,46 +1433,46 @@@ CompItem.prototype.constructor = CompIt
};
P.openInViewer = function () { __call("comp.open", { comp: this.__id }); return null; };
P.duplicate = function () { return __item(__call("project.duplicate", { items: [this.__id] }).items[0]); };
- // Essential Graphics template: name, controllers (property, mirror and media controls in
- // panel order, 1-based) and export.
- P.__egControllers = function () {
+ // Essential Graphics (templates are EffectCraft's open .ectemplate files).
+ P.__eg = function () { return __call("essential.list", { comp: this.__id }); };
+ P.__controllers = function () {
var out = [];
- (function go(v) {
- for (var i = 0; i < v.length; i++) {
- if (v[i].kind === "group") go(v[i].children || []);
- else if (v[i].kind !== "comment") out.push(v[i]);
+ (function walk(list) {
+ for (var i = 0; i < list.length; i++) {
- if (list[i].kind === "property" || list[i].kind === "media") out.push(list[i]);
++ if (list[i].kind === "property" || list[i].kind === "mirror" || list[i].kind === "media") out.push(list[i]);
+ if (list[i].children) walk(list[i].children);
}
- })(__call("essential.list", { comp: this.__id }).controls || []);
+ })(this.__eg().controls);
return out;
};
- def("motionGraphicsTemplateName", function () { return __call("essential.list", { comp: this.__id }).name; }, function (v) {
+ def("motionGraphicsTemplateName", function () { return this.__eg().name; }, function (v) {
__call("essential.setName", { comp: this.__id, name: String(v) });
});
- def("motionGraphicsTemplateControllerCount", function () { return this.__egControllers().length; });
+ def("motionGraphicsTemplateControllerCount", function () { return this.__controllers().length; });
P.getMotionGraphicsTemplateControllerName = function (i) {
- var c = this.__egControllers()[__num(i, "index") - 1];
- if (!c) throw __err("controller index out of range");
- return c.name;
+ var c = this.__controllers();
+ i = __num(i, "index");
+ if (i < 1 || i > c.length) throw __err("controller index " + i + " is out of range 1.." + c.length);
+ return c[i - 1].name;
};
P.setMotionGraphicsControllerName = function (i, name) {
- var c = this.__egControllers()[__num(i, "index") - 1];
- if (!c) throw __err("controller index out of range");
- __call("essential.rename", { comp: this.__id, control: c.id, name: String(name) });
+ var c = this.__controllers();
+ i = __num(i, "index");
+ if (i < 1 || i > c.length) throw __err("controller index " + i + " is out of range 1.." + c.length);
+ __call("essential.rename", { comp: this.__id, control: c[i - 1].id, name: String(name) });
return String(name);
};
+ P.openInEssentialGraphics = function () { __call("comp.openInEssentialGraphics", { comp: this.__id }); };
P.exportAsMotionGraphicsTemplate = function (overwrite, path) {
- if (path === undefined) return false;
- var p = path && path.fsName !== undefined ? path.fsName : String(path);
- if (!overwrite && new File(p).exists) return false;
- try { __call("essential.exportTemplate", { comp: this.__id, path: p }); return true; } catch (e) { return false; }
+ var f = __str(path);
+ if (!f) return false;
+ if (!/\.[A-Za-z0-9]+$/.test(f)) f += ".ectemplate";
+ if (!overwrite && JSON.parse(__file("exists", f)) === true) return false;
+ if (this.__controllers().length === 0) return false;
+ // The file gate applies to templates too.
+ __file("write", f, "");
+ __call("essential.exportTemplate", { comp: this.__id, path: f });
+ return true;
};
})();
diff --cc crates/script/src/tests.rs
index c9a42692b,458f2b41d..151ab57f5
--- a/crates/script/src/tests.rs
+++ b/crates/script/src/tests.rs
@@@ -446,41 -446,3 +446,28 @@@ fn layer_switches_timing_and_comp_setti
let o = ok(&mut s, "var n = app.project.numItems; app.project.item(1).remove(); n - app.project.numItems");
assert_eq!(o.result, json!(1));
}
+
+#[test]
+fn motion_graphics_template_hooks_add_mirrors_and_controllers() {
+ let mut s = session();
- let dir = std::env::temp_dir().join(format!("effectcraft-eg-script-{}", std::process::id()));
- let _ = std::fs::create_dir_all(&dir);
- let path = dir.join("card.ectemplate");
+ let o = ok(
+ &mut s,
- &format!(
- r#"
++ r#"
+ var comp = app.project.items.addComp("Card", 64, 64, 1, 2, 30);
+ var bg = comp.layers.addSolid([1, 1, 1], "BG", 64, 64, 1);
+ var op = bg.transform.opacity;
+ var r = [op.canAddToMotionGraphicsTemplate(comp), op.addToMotionGraphicsTemplateAs(comp, "Fade")];
- // Again: a mirror of the same property.
++ // Again: a mirror of the same property (a controller of its own).
+ r.push(op.addToMotionGraphicsTemplate(comp));
+ r.push(comp.motionGraphicsTemplateControllerCount);
+ r.push(comp.getMotionGraphicsTemplateControllerName(1), comp.getMotionGraphicsTemplateControllerName(2));
+ comp.setMotionGraphicsControllerName(2, "Fade Again");
- comp.motionGraphicsTemplateName = "Lower Card";
- r.push(comp.getMotionGraphicsTemplateControllerName(2), comp.motionGraphicsTemplateName);
- // A property of another comp can't be added.
- var other = app.project.items.addComp("Other", 64, 64, 1, 2, 30);
- r.push(op.canAddToMotionGraphicsTemplate(other));
- r.push(comp.exportAsMotionGraphicsTemplate(true, new File("{}")));
++ r.push(comp.getMotionGraphicsTemplateControllerName(2));
+ r
+ "#,
- path.to_string_lossy()
- ),
+ );
- assert_eq!(o.result, json!([true, true, true, 2, "Fade", "Fade", "Fade Again", "Lower Card", false, true]));
++ assert_eq!(o.result, json!([true, true, true, 2, "Fade", "Fade", "Fade Again"]));
+ let (_, c) = comp_named(&s, "Card");
+ let eg = c.essential.as_ref().unwrap();
+ assert!(matches!(eg.controls[1].kind, effectcraft_engine::project::essential::EgKind::Mirror { of } if of == eg.controls[0].id));
- assert!(path.exists());
- let _ = std::fs::remove_dir_all(&dir);
+}
diff --cc crates/ui-egui/src/panels/essential.rs
index 3f8f1985e,b22263b9d..0ccc46e6b
--- a/crates/ui-egui/src/panels/essential.rs
+++ b/crates/ui-egui/src/panels/essential.rs
@@@ -4,13 -4,10 +4,14 @@@
//! be exposed) and the template name.
//! - The controls: drag a property name from the timeline onto the list (or Animation ▸ Add
//! Property to Essential Graphics); each shows as a text / colour / slider / checkbox / point /
- //! angle / dropdown control editing the source property; rename by double-clicking the name;
+ //! angle / dropdown control editing the source property (Add Selected As: Source Text as a font
+ //! control, Scale as one uniform slider); rename by double-clicking the name;
//! reorder with ▲▼, remove with ✕; groups and comments from Add Formatting; Media
//! Replacement for the selected footage layer.
+//! - **Mirrors and links**: adding a property that is already in the panel adds a *mirror*
+//! (same value, its own name and place); a control's ⋯ menu adds a mirror, links the selected
+//! timeline property (the control then drives both) or unlinks one. Mirrors and linked
+//! controls are badged (`essential.control.<id>.badge`, `.menu`).
//! - **Export Template…** writes an open `.ectemplate`.
//! - With a precomp layer that has Essential Properties selected, its instance values: edit them
//! (overrides), Revert or Push to Comp.
@@@ -205,7 -198,7 +219,14 @@@ fn controls(app: &mut EffectcraftApp, u
match src {
Some((layer, lt, p)) => {
let v = p.value_at(lt);
- if let Some(nv) = value_widget(app, ui, &format!("essential.control.{}.value", c.id), &p, &v) {
- if let Some(nv) = value_widget(app, ui, &format!("essential.control.{}.value", c.id), essential::effective_type(c, &p), &p, &v) {
++ if let Some(nv) = value_widget(
++ app,
++ ui,
++ &format!("essential.control.{}.value", c.id),
++ essential::effective_type(eg.resolve(c.id).unwrap_or(c), &p),
++ &p,
++ &v,
++ ) {
actions.push((
"prop.set".into(),
json!({"comp": cid.0, "layer": layer, "prop": p.uid, "value": nv, "merge": format!("eg-{}", c.id)}),
@@@ -440,7 -445,7 +503,7 @@@ fn instance(app: &mut EffectcraftApp, u
}
_ => {
let v = p.value_at(lt);
- if let Some(nv) = value_widget(app, ui, &auto, &p, &v) {
- if let Some(nv) = value_widget(app, ui, &auto, essential::effective_type(c, &p), &p, &v) {
++ if let Some(nv) = value_widget(app, ui, &auto, essential::effective_type(eg.resolve(c.id).unwrap_or(c), &p), &p, &v) {
actions.push((
"essential.set".into(),
json!({"layer": layer.id.0, "control": c.id, "value": nv, "merge": format!("egi-{}-{}", layer.id.0, c.id)}),