From faf1d99e4a0650b5c660daa908a657743e2e4fac Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Mon, 2 Nov 2026 21:55:19 +0530 Subject: [PATCH 01/83] Fix #2869: disclose selected effects with arrow keys --- crates/ui-egui/src/menus/shortcuts.rs | 4 + crates/ui-egui/src/panels/effect_controls.rs | 1 + .../src/panels/effect_controls/panel.rs | 22 ++++ crates/ui-egui/tests/it/ui_effect_controls.rs | 102 ++++++++++++++++++ 4 files changed, 129 insertions(+) diff --git a/crates/ui-egui/src/menus/shortcuts.rs b/crates/ui-egui/src/menus/shortcuts.rs index 4ef1e64fb..65542e56f 100644 --- a/crates/ui-egui/src/menus/shortcuts.rs +++ b/crates/ui-egui/src/menus/shortcuts.rs @@ -403,6 +403,10 @@ fn handle_shortcuts_impl(app: &mut EffectcraftApp, ctx: &egui::Context, tab_only if app.dialog.is_some() { continue; } + if !mods.any() && crate::panels::effect_controls::handle_disclosure_key(app, key) { + ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, key)); + continue; + } // Enter in the Project panel renames the selected item (handled by the panel). // In Effects & Presets and the Render Queue Enter applies or opens the row (handled by the // panel), not the layer rename. diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs index d9706f147..6e71c6850 100644 --- a/crates/ui-egui/src/panels/effect_controls.rs +++ b/crates/ui-egui/src/panels/effect_controls.rs @@ -36,6 +36,7 @@ mod viewer; pub(crate) use common::gesture_key; pub use common::{choose_files_after_apply, reveal_applied}; +pub(crate) use panel::handle_disclosure_key; pub use panel::{show, start_rename}; pub(crate) use rows::toggle_pick; pub use viewer::viewer_hook; diff --git a/crates/ui-egui/src/panels/effect_controls/panel.rs b/crates/ui-egui/src/panels/effect_controls/panel.rs index 122a6abf7..0d81029e6 100644 --- a/crates/ui-egui/src/panels/effect_controls/panel.rs +++ b/crates/ui-egui/src/panels/effect_controls/panel.rs @@ -3,6 +3,28 @@ use super::editors::{curves_editor, editor_height, histogram_only, levels_editor use super::rows::{FxScope, group_rows, toggle_closed}; use super::{Align2, Color32, EffectcraftApp, EvalCtx, GroupKind, Icon, Layer, PropGroup, Rect, Sense, Stroke, Tokens, json, pos2, vec2, widgets}; +/// Plain Left/Right disclose selected effect headers before global layer nudges run. +pub(crate) fn handle_disclosure_key(app: &mut EffectcraftApp, key: egui::Key) -> bool { + if app.ui.focused != crate::dock::PanelKind::EffectControls || !matches!(key, egui::Key::ArrowLeft | egui::Key::ArrowRight) { + return false; + } + let Some(comp) = app.session.active_comp() else { return false }; + let Some(layer) = app.session.state.selected_layers.first().and_then(|id| comp.layer(*id)) else { return false }; + let Some(effects) = layer.effects() else { return false }; + let mut handled = false; + for g in effects.groups() { + if matches!(&g.kind, GroupKind::Effect { .. }) && app.session.state.selected_props.contains(&(layer.id, g.uid)) { + if key == egui::Key::ArrowLeft { + app.ui.fx_closed.insert(g.uid); + } else { + app.ui.fx_closed.remove(&g.uid); + } + handled = true; + } + } + handled +} + // --------------------------------------------------------------------------------------------- /// Open the rename field on effect `uid` (Enter with the effect selected), name selected. diff --git a/crates/ui-egui/tests/it/ui_effect_controls.rs b/crates/ui-egui/tests/it/ui_effect_controls.rs index d6138ba5c..3de502a5b 100644 --- a/crates/ui-egui/tests/it/ui_effect_controls.rs +++ b/crates/ui-egui/tests/it/ui_effect_controls.rs @@ -90,6 +90,108 @@ fn click(h: &mut Harness<'_, EffectcraftApp>, pos: egui::Pos2) { h.step(); } +fn header_arrow_harness() -> (Harness<'static, EffectcraftApp>, LayerId, [(u64, u64); 3]) { + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "Disclosure", "width": 32, "height": 18, "frameRate": 30, "duration": 2})).unwrap(); + let lid = s.execute("layer.newSolid", json!({"name": "Controls", "color": "#40b080"})).unwrap()["layer"].as_u64().unwrap(); + let mut effects = [(0, 0); 3]; + for pair in &mut effects { + let fx = s.execute("effect.apply", json!({"layers": [lid], "effect": "Point Control"})).unwrap()["effects"][0].as_u64().unwrap(); + let prop = layer(&s, lid).props.find_group(fx).unwrap().get("point").unwrap().uid; + *pair = (fx, prop); + } + s.state.selected_props.clear(); + let mut app = EffectcraftApp::new(s); + app.show_panel(PanelKind::EffectControls); + app.toggle_maximize(PanelKind::EffectControls); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).with_step_dt(1.0 / 60.0).build_eframe(|_| app); + h.run_steps(4); + (h, LayerId(lid), effects) +} + +fn header_arrow_key(h: &mut Harness<'_, EffectcraftApp>, key: egui::Key, modifiers: egui::Modifiers) { + h.key_press_modifiers(modifiers, key); + h.run_steps(2); +} + +#[test] +fn effect_header_arrows_collapse_and_expand_without_editing_the_document() { + let (mut h, lid, [(fx, prop), (_, other), _]) = header_arrow_harness(); + let at = rect_of(&h, &format!("effectControls.effect.{fx}.name")).center(); + click(&mut h, at); + assert_eq!(h.state().ui.focused, PanelKind::EffectControls); + assert_eq!(h.state().session.state.selected_props, vec![(lid, fx)]); + let project = serde_json::to_value(&h.state().session.project).unwrap(); + let time = h.state().session.time(); + let undo = h.state().session.history.undo.len(); + let redo = h.state().session.history.redo.len(); + for key in [egui::Key::ArrowLeft, egui::Key::ArrowLeft, egui::Key::ArrowRight, egui::Key::ArrowRight] { + header_arrow_key(&mut h, key, egui::Modifiers::NONE); + assert_eq!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_some(), key == egui::Key::ArrowRight); + assert!(h.state().auto.find(&format!("effectControls.row.{other}")).is_some(), "unselected effect stays open"); + assert_eq!(h.state().session.state.selected_props, vec![(lid, fx)]); + assert_eq!(serde_json::to_value(&h.state().session.project).unwrap(), project); + assert_eq!(h.state().session.time(), time); + assert_eq!((h.state().session.history.undo.len(), h.state().session.history.redo.len()), (undo, redo)); + } +} + +#[test] +fn effect_header_arrows_only_disclose_selected_headers_on_the_displayed_layer() { + let (mut h, lid, [(first, _), (second, _), (third, prop)]) = header_arrow_harness(); + h.state_mut().session.state.selected_props = vec![(lid, first), (lid, second), (LayerId(0), third), (lid, u64::MAX)]; + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert_eq!(h.state().ui.fx_closed.iter().copied().collect::>(), vec![first, second]); + assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_some()); + header_arrow_key(&mut h, egui::Key::ArrowRight, egui::Modifiers::NONE); + assert!(h.state().ui.fx_closed.is_empty()); + + // A parameter selection, stale header, or header on another layer must still fall through. + h.state_mut().session.state.selected_props = vec![(lid, prop), (LayerId(0), first), (lid, u64::MAX)]; + let before = serde_json::to_value(&h.state().session.project).unwrap(); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert!(h.state().ui.fx_closed.is_empty()); + assert_ne!(serde_json::to_value(&h.state().session.project).unwrap(), before, "the existing layer nudge still runs"); +} + +#[test] +fn effect_header_arrows_preserve_modified_shortcuts_and_keyboard_ownership() { + let (mut h, lid, [(fx, _), _, _]) = header_arrow_harness(); + h.state_mut().session.state.selected_props = vec![(lid, fx)]; + let time = h.state().session.time(); + header_arrow_key(&mut h, egui::Key::ArrowRight, egui::Modifiers::COMMAND); + assert!(h.state().session.time() > time, "Cmd/Ctrl+Right still advances a frame"); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::COMMAND); + assert_eq!(h.state().session.time(), time); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::SHIFT); + assert!(h.state().ui.fx_closed.is_empty(), "Shift+Left does not collapse effects"); + h.state_mut().ui.focused = PanelKind::Composition; + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert!(h.state().ui.fx_closed.is_empty(), "another panel owns the arrows"); + h.state_mut().ui.focused = PanelKind::EffectControls; + h.state_mut().dialog = Some(effectcraft_ui_egui::Dialog::About); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert!(h.state().ui.fx_closed.is_empty(), "a dialog owns the arrows"); + h.state_mut().dialog = None; + h.run_steps(3); + let at = rect_of(&h, &format!("effectControls.effect.{fx}.name")).center(); + h.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + h.step(); + } + h.run_steps(2); + assert!(egui::Popup::is_any_open(&h.ctx), "the effect context menu is open"); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert!(h.state().ui.fx_closed.is_empty(), "the context menu owns the arrows"); + header_arrow_key(&mut h, egui::Key::Escape, egui::Modifiers::NONE); + double_click(&mut h, at); + assert!(h.ctx.egui_wants_keyboard_input(), "the rename field owns the keyboard"); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert!(h.state().ui.fx_closed.is_empty(), "Left moves the text caret instead of collapsing"); + assert!(h.state().auto.find(&format!("effectControls.effect.{fx}.nameEdit")).is_some()); +} + #[test] fn effect_controls_widgets_register_automation_ids() { let (app, x) = app(); From c5bf611909d5647cb1d45218310a6b860b1d1873 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Mon, 2 Nov 2026 22:10:35 +0530 Subject: [PATCH 02/83] #2817: allow reopening manually drawn paths --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/mask.rs | 2 +- crates/engine/src/cmd/paths.rs | 4 + crates/engine/src/cmd/paths/closed.rs | 125 ++++++++++++++++++ crates/engine/src/menus.rs | 3 +- crates/engine/src/menus/tests.rs | 38 ++++++ crates/engine/src/tests/viewer.rs | 179 ++++++++++++++++++++++++++ crates/ui-egui/src/i18n.rs | 30 +++-- 8 files changed, 367 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/cmd/paths/closed.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 1168c431b..acd991fb2 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -47,7 +47,7 @@ mod nav_more; pub mod paint; pub mod panels_cmds; pub(crate) mod path_nulls; -mod paths; +pub(crate) mod paths; mod project_items; pub(crate) mod prop; mod prop_groups; diff --git a/crates/engine/src/cmd/mask.rs b/crates/engine/src/cmd/mask.rs index 778dfb54c..d7a1c1dbe 100644 --- a/crates/engine/src/cmd/mask.rs +++ b/crates/engine/src/cmd/mask.rs @@ -644,7 +644,7 @@ pub fn specs() -> Vec { cmd!("mask.new", "New Mask from Points", [], None, "{layer?, vertices: [[x,y]…], inTangents?, outTangents?, closed?, mode?}", has_layers, new_mask), cmd!("mask.addVertex", "Add Mask Vertex", [], None, "{layer?, mask, point: [x,y], in?, out?, index?}", has_layers, add_vertex), cmd!("mask.setVertex", "Set Mask Vertex", [], None, "{layer?, mask, index, point?, in?, out?, merge?}", has_layers, set_vertex), - cmd!("mask.setClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{layer?, mask, closed?}", has_layers, set_closed), + cmd!("mask.setClosed", "Closed", [], None, "{layer?, mask, closed?}", has_layers, set_closed), cmd!("mask.selectVertices", "Select Mask Vertices", [], None, "{vertices: [{layer, mask, index}], add?, toggle?}", has_comp, select_vertices), cmd!("mask.moveVertices", "Move Mask Vertices", [], None, "{vertices?: [{layer, mask, index}], delta: [dx,dy], merge?}", has_vertices, move_vertices), cmd!("mask.deleteVertices", "Delete Mask Vertices", [], None, "{vertices?}", has_vertices, delete_vertices), diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs index 8364f67ec..2f1e1051b 100644 --- a/crates/engine/src/cmd/paths.rs +++ b/crates/engine/src/cmd/paths.rs @@ -12,6 +12,9 @@ use super::layer_menu::target_masks; use super::{CommandSpec, b_p, bad, f_p, has_comp, has_layers, layer_mut, layer_p, merge_p, str_p}; use crate::{EngineError, Result, Session, VertexRef, cmd}; +mod closed; +pub(crate) use closed::selected_paths_closed; + // ---------------------------------------------------------------- RotoBezier /// Automatic (RotoBezier) tangents: each vertex's tangents follow the line through its @@ -547,6 +550,7 @@ fn ungroup_shapes(s: &mut Session, p: &Value) -> Result { pub fn specs() -> Vec { vec![ + cmd!("path.toggleClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{}", closed::has_paths, closed::toggle_closed), cmd!("path.rotoBezier", "RotoBezier", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?, value?}", has_layers, roto_bezier), cmd!("path.convertToBezier", "Convert To Bezier Path", ["Layer", "Mask and Shape Path"], None, "{layer?, mask?}", has_layers, convert_to_bezier), cmd!("path.groupShapes", "Group Shapes", ["Layer"], Some("Cmd+G"), "{layer?, items?: [uid]}", has_shape_items, group_shapes), diff --git a/crates/engine/src/cmd/paths/closed.rs b/crates/engine/src/cmd/paths/closed.rs new file mode 100644 index 000000000..d3cd8c1ef --- /dev/null +++ b/crates/engine/src/cmd/paths/closed.rs @@ -0,0 +1,125 @@ +//! The selection-aware Closed menu action. Explicit edits retain `mask.setClosed`'s API. + +use effectcraft_keyframe::Value as KV; +use effectcraft_project::{GroupKind, Layer, LayerId, PropGroup, Uid}; +use effectcraft_time::Tick; +use serde_json::{Value, json}; + +use super::super::{bad, layer_mut}; +use crate::{EngineError, Result, Session, VertexRef}; + +const MAX_DEPTH: usize = 128; + +struct Target { + layer: LayerId, + route: Vec, + closed: bool, +} + +struct Selection { + vertices: Vec, + props: Vec<(LayerId, Uid)>, + time: Tick, +} + +/// A route uses checked child access and never recurses through an input-controlled tree. +fn group_at_mut<'a>(mut group: &'a mut PropGroup, route: &[usize]) -> Option<&'a mut PropGroup> { + for &index in route { + group = group.children.get_mut(index)?.as_group_mut()?; + } + Some(group) +} + +fn targets(s: &Session) -> Result> { + let comp = s.active_comp().ok_or(EngineError::NoComp)?; + // Layer navigation and insertion can retain point/property selections on other layers. + let selection = Selection { + vertices: s.state.selected_vertices.iter().filter(|v| s.state.selected_layers.contains(&v.layer)).copied().collect(), + props: s.state.selected_props.iter().filter(|(lid, _)| s.state.selected_layers.contains(lid)).copied().collect(), + time: s.time(), + }; + let mut targets = Vec::new(); + for layer in comp.layers.iter() { + let selected_layer = if !selection.vertices.is_empty() { + selection.vertices.iter().any(|v| v.layer == layer.id) + } else if !selection.props.is_empty() { + selection.props.iter().any(|(lid, _)| *lid == layer.id) + } else { + s.state.selected_layers.contains(&layer.id) + }; + if !selected_layer || layer.switches.locked { + continue; + } + collect(&selection, layer, &layer.props, &mut Vec::new(), selection.props.is_empty(), &mut targets)?; + } + if targets.is_empty() { + return Err(bad("path.toggleClosed", "select an unlocked mask or Bezier shape path")); + } + Ok(targets) +} + +fn collect(selection: &Selection, layer: &Layer, group: &PropGroup, route: &mut Vec, inherited: bool, targets: &mut Vec) -> Result<()> { + if route.len() > MAX_DEPTH { + return Err(bad("path.toggleClosed", "path group nesting exceeds 128 levels")); + } + if matches!(group.kind, GroupKind::Mask { locked: true, .. }) { + return Ok(()); + } + let selected = inherited || selection.props.contains(&(layer.id, group.uid)); + if super::super::mask::is_path_group(group) + && let Some(prop) = group.get("path") + && let KV::Path(path) = prop.value_at(layer.layer_time(selection.time)) + { + let selected = if selection.vertices.is_empty() { + selected || selection.props.contains(&(layer.id, prop.uid)) + } else { + selection.vertices.iter().any(|v| v.layer == layer.id && v.mask == group.uid && v.index < path.vertices.len()) + }; + if selected { + targets.push(Target { layer: layer.id, route: route.clone(), closed: path.closed }); + } + return Ok(()); + } + for (index, child) in group.children.iter().enumerate() { + let Some(child) = child.as_group() else { continue }; + route.push(index); + collect(selection, layer, child, route, selected, targets)?; + route.pop(); + } + Ok(()) +} + +pub(crate) fn selected_paths_closed(s: &Session) -> Option { + targets(s).ok().map(|targets| targets.iter().all(|target| target.closed)) +} + +pub(super) fn has_paths(s: &Session) -> std::result::Result<(), String> { + targets(s).map(|_| ()).map_err(|error| error.to_string()) +} + +pub(super) fn toggle_closed(s: &mut Session, _: &Value) -> Result { + let targets = targets(s)?; + let closed = !targets.iter().all(|target| target.closed); + let cid = s.active_comp_id().ok_or(EngineError::NoComp)?; + let time = s.time(); + s.edit("Closed", None, |project, _| { + for target in &targets { + let layer = layer_mut(project, cid, target.layer)?; + let time = layer.layer_time(time); + let group = group_at_mut(&mut layer.props, &target.route).ok_or_else(|| bad("path.toggleClosed", "the selected path no longer exists"))?; + let roto = super::is_roto(group); + let prop = group.get_mut("path").ok_or_else(|| bad("path.toggleClosed", "the selected group has no path"))?; + let KV::Path(mut path) = prop.value_at(time) else { return Err(bad("path.toggleClosed", "the selected value is not a path")) }; + if path.closed == closed { + continue; + } + path.closed = closed; + if roto { + super::roto_smooth(&mut path); + } + prop.set_value_at(time, KV::Path(path)); + } + Ok(()) + })?; + Ok(json!({"paths": targets.len(), "closed": closed})) +} diff --git a/crates/engine/src/menus.rs b/crates/engine/src/menus.rs index a7418ae58..813097828 100644 --- a/crates/engine/src/menus.rs +++ b/crates/engine/src/menus.rs @@ -314,6 +314,7 @@ pub fn checked(s: &Session, command: &str, params: &Value) -> Option { let layer = s.state.selected_layers.first().and_then(|l| comp.layer(*l)); let pstr = |k: &str| params.get(k).and_then(Value::as_str); match command { + "path.toggleClosed" => crate::cmd::paths::selected_paths_closed(s), "layer.setBlendMode" => { let want = effectcraft_color::BlendMode::from_name(pstr("mode")?)?; Some(layer?.blend_mode == want) @@ -820,7 +821,7 @@ Layer Hide Locked Masks | layer.mask.hideLocked Mask and Shape Path RotoBezier | path.rotoBezier - Closed | mask.setClosed + Closed | path.toggleClosed Convert To Bezier Path | path.convertToBezier Set First Vertex | path.setFirstVertex Free Transform Points | path.freeTransform diff --git a/crates/engine/src/menus/tests.rs b/crates/engine/src/menus/tests.rs index 913a0e92e..02c825bf9 100644 --- a/crates/engine/src/menus/tests.rs +++ b/crates/engine/src/menus/tests.rs @@ -140,6 +140,44 @@ fn checked_reflects_layer_state() { assert_eq!(checked(&s, "file.save", &serde_json::json!({})), None); } +#[test] +fn closed_menu_opens_and_recloses_a_manual_shape() { + use serde_json::json; + let mut s = crate::Session::default(); + s.execute("comp.new", json!({"width": 320, "height": 180})).unwrap(); + let r = s + .execute( + "shape.newPath", + json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true, + "inTangents": [[0, -12], [-8, 0], [0, -6]], "outTangents": [[12, 0], [0, 8], [-6, 0]]}), + ) + .unwrap(); + let lid = effectcraft_project::LayerId(r["layer"].as_u64().unwrap()); + let uid = r["path"].as_u64().unwrap(); + let path = + |s: &crate::Session| s.active_comp().unwrap().layer(lid).unwrap().props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone(); + let original = path(&s); + for mac in [true, false] { + let (_, entry) = + platform_entries(mac).into_iter().find(|(p, e)| p.iter().map(String::as_str).eq(["Layer", "Mask and Shape Path"]) && e.label == "Closed").unwrap(); + assert!(s.is_enabled(&entry.command)); + assert_eq!(checked(&s, &entry.command, &entry.params), Some(true)); + s.execute(&entry.command, entry.params.clone()).unwrap(); + let mut opened = original.clone(); + opened.closed = false; + assert_eq!(path(&s), opened); + assert!(!effectcraft_path::to_kurbo(&path(&s)).elements().contains(&effectcraft_path::PathEl::ClosePath)); + assert_eq!(checked(&s, &entry.command, &entry.params), Some(false)); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(path(&s), original); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(path(&s), opened); + s.execute(&entry.command, entry.params).unwrap(); + assert_eq!(path(&s), original); + assert!(effectcraft_path::to_kurbo(&path(&s)).elements().contains(&effectcraft_path::PathEl::ClosePath)); + } +} + /// `cargo test -p effectcraft-engine dump_specs -- --ignored --nocapture`: every command as TSV. #[test] #[ignore] diff --git a/crates/engine/src/tests/viewer.rs b/crates/engine/src/tests/viewer.rs index ef2bd8acc..36e3b0537 100644 --- a/crates/engine/src/tests/viewer.rs +++ b/crates/engine/src/tests/viewer.rs @@ -286,6 +286,185 @@ fn shape_path(s: &Session, lid: u64, uid: u64) -> effectcraft_keyframe::ShapePat l.props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone() } +#[test] +fn toggle_closed_respects_path_and_vertex_selection() { + let mut s = comp(); + let a = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let lid = a["layer"].as_u64().unwrap(); + let a = a["path"].as_u64().unwrap(); + let b = s.execute("shape.newPath", json!({"layer": lid, "vertices": [[10, 10], [90, 10], [90, 90]], "closed": true})).unwrap()["path"].as_u64().unwrap(); + let leaf = layer(&s, lid).props.find_group(a).unwrap().get("path").unwrap().uid; + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(lid), leaf)]; + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, lid, a).closed); + assert!(shape_path(&s, lid, b).closed, "an unselected sibling stays closed"); + s.state.selected_props = vec![(LayerId(lid), b)]; + s.state.selected_vertices = vec![crate::VertexRef { layer: LayerId(lid), mask: a, index: 1 }]; + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(shape_path(&s, lid, a).closed, "vertices take precedence over property selection"); + assert!(shape_path(&s, lid, b).closed); + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(lid), a), (LayerId(lid), leaf), (LayerId(lid), b)]; + let r = s.execute("path.toggleClosed", json!({})).unwrap(); + assert_eq!(r["paths"], json!(2)); + assert!(!shape_path(&s, lid, a).closed); + assert!(!shape_path(&s, lid, b).closed); + s.execute("edit.undo", json!({})).unwrap(); + assert!(shape_path(&s, lid, a).closed); + assert!(shape_path(&s, lid, b).closed, "all paths undo in one step"); + s.execute("mask.setClosed", json!({"layer": lid, "mask": a, "closed": false})).unwrap(); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(shape_path(&s, lid, a).closed); + assert!(shape_path(&s, lid, b).closed, "a mixed selection closes all paths"); + s.state.selected_props.clear(); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, lid, a).closed); + assert!(!shape_path(&s, lid, b).closed, "layer selection addresses all editable paths"); +} + +#[test] +fn toggle_closed_ignores_selections_retained_on_other_layers() { + let mut s = comp(); + let a = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let (a_layer, a_path) = (a["layer"].as_u64().unwrap(), a["path"].as_u64().unwrap()); + let b_layer = s.execute("layer.newShape", json!({"kind": "none"})).unwrap()["layer"].as_u64().unwrap(); + assert!(s.state.selected_vertices.iter().any(|v| v.layer == LayerId(a_layer)), "insertion retains old vertices"); + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + assert!(shape_path(&s, a_layer, a_path).closed); + + let b_path = + s.execute("shape.newPath", json!({"layer": b_layer, "vertices": [[0, 0], [50, 0], [50, 50]], "closed": true})).unwrap()["path"].as_u64().unwrap(); + s.execute("prop.select", json!({"layer": b_layer, "prop": b_path})).unwrap(); + s.execute("layer.selectNext", json!({})).unwrap(); + assert_eq!(s.state.selected_layers, vec![LayerId(a_layer)]); + assert!(s.state.selected_vertices.iter().any(|v| v.layer == LayerId(b_layer)), "navigation retains old vertices"); + assert!(s.state.selected_props.contains(&(LayerId(b_layer), b_path))); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(true)); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, a_layer, a_path).closed); + assert!(shape_path(&s, b_layer, b_path).closed, "the deselected layer stays unchanged"); + s.execute("layer.selectPrevious", json!({})).unwrap(); + assert_eq!(s.state.selected_layers, vec![LayerId(b_layer)]); + s.execute("prop.select", json!({"layer": b_layer, "path": "transform/position"})).unwrap(); + assert!(!s.is_enabled("path.toggleClosed"), "a non-path property does not select sibling paths"); + s.execute("layer.selectNext", json!({})).unwrap(); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(shape_path(&s, a_layer, a_path).closed, "a property retained on another layer cannot block this layer"); + assert!(shape_path(&s, b_layer, b_path).closed); +} + +#[test] +fn toggle_closed_rejects_locked_stale_and_nonpath_selection() { + let mut s = comp(); + let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let (lid, uid) = (r["layer"].as_u64().unwrap(), r["path"].as_u64().unwrap()); + let before = s.project.clone(); + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(lid), u64::MAX)]; + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + assert!(s.project.same_content(&before)); + s.state.selected_props.clear(); + s.state.selected_vertices = vec![crate::VertexRef { layer: LayerId(lid), mask: uid, index: usize::MAX }]; + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + s.state.selected_vertices.clear(); + let cid = s.active_comp_id().unwrap(); + std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap().switches.locked = true; + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + assert!(shape_path(&s, lid, uid).closed); + s.execute("layer.newShape", json!({"kind": "rect"})).unwrap(); + s.state.selected_props.clear(); + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); +} + +#[test] +fn toggle_closed_handles_masks_and_preserves_explicit_set_closed() { + let mut s = comp(); + let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap(); + let uid = s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); + let path = |s: &Session| layer(s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone(); + let original = path(&s); + s.state.selected_props = vec![(LayerId(lid), uid)]; + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!path(&s).closed); + s.execute("mask.setClosed", json!({"layer": lid, "mask": uid})).unwrap(); + assert_eq!(path(&s), original, "explicit API still defaults to closed"); + s.execute("mask.setClosed", json!({"layer": lid, "mask": uid, "closed": false})).unwrap(); + assert!(!path(&s).closed); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert_eq!(path(&s), original); + let cid = s.active_comp_id().unwrap(); + let g = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap().props.find_group_mut(uid).unwrap(); + if let effectcraft_project::GroupKind::Mask { locked, .. } = &mut g.kind { + *locked = true; + } + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + assert_eq!(path(&s), original); +} + +#[test] +fn toggle_closed_edits_layer_time_and_roundtrips() { + use effectcraft_keyframe::Keyframe; + let mut s = comp(); + let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let (lid, uid) = (r["layer"].as_u64().unwrap(), r["path"].as_u64().unwrap()); + let cid = s.active_comp_id().unwrap(); + let original = shape_path(&s, lid, uid); + let second = Tick::from_seconds_f64(1.0); + let layer = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap(); + layer.start_time = second; + layer.stretch = 200.0; + let prop = layer.props.find_group_mut(uid).unwrap().get_mut("path").unwrap(); + prop.keys = vec![Keyframe::new(Tick::ZERO, KV::Path(original.clone())), Keyframe::new(second, KV::Path(original.clone()))]; + let keys = prop.keys.clone(); + s.execute("time.set", json!({"time": 3.0})).unwrap(); + s.execute("path.toggleClosed", json!({})).unwrap(); + let prop = s.project.comp(cid).unwrap().layer(LayerId(lid)).unwrap().props.find_group(uid).unwrap().get("path").unwrap(); + assert_eq!(prop.keys.len(), 2); + assert_eq!(prop.keys[0], keys[0], "the other keyframe is untouched"); + let mut opened = original; + opened.closed = false; + assert_eq!(prop.value_at(second), KV::Path(opened.clone())); + assert!(prop.value_at(Tick::from_seconds_f64(0.5)).as_path().unwrap().closed, "the earlier segment keeps its closedness"); + let bytes = serde_json::to_vec(&*s.project).unwrap(); + let restored: effectcraft_project::Project = serde_json::from_slice(&bytes).unwrap(); + let prop = restored.comp(cid).unwrap().layer(LayerId(lid)).unwrap().props.find_group(uid).unwrap().get("path").unwrap(); + assert_eq!(prop.value_at(second), KV::Path(opened)); + s.execute("time.set", json!({"time": 2.0})).unwrap(); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(true)); + s.execute("time.set", json!({"time": 3.0})).unwrap(); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(false)); +} + +#[test] +fn toggle_closed_rejects_excessive_group_nesting_without_an_edit() { + use effectcraft_project::build::{self, Ids}; + let mut s = comp(); + let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let lid = LayerId(r["layer"].as_u64().unwrap()); + let cid = s.active_comp_id().unwrap(); + let project = std::sync::Arc::make_mut(&mut s.project); + let mut next = project.next_id; + let contents = project.comp_mut(cid).unwrap().layer_mut(lid).unwrap().props.sub_mut("contents").unwrap(); + let node = contents.children.first_mut().unwrap(); + let mut nested = node.as_group().unwrap().clone(); + for _ in 0..130 { + nested = build::shape_group(&mut Ids(&mut next), "Nested", vec![nested]); + } + *node = effectcraft_project::Node::Group(nested); + project.next_id = next; + let before = s.project.clone(); + assert!(!s.is_enabled("path.toggleClosed")); + assert!(s.execute("path.toggleClosed", json!({})).is_err()); + assert!(s.project.same_content(&before)); +} + #[test] fn shape_pen_builds_shape_group_and_renders() { let mut s = comp(); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index fe676163e..18ffe2725 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -699,7 +699,7 @@ const SIMPLIFIED_CHINESE: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "隐藏锁定的蒙版"), ("", "Mask and Shape Path", "蒙版和形状路径"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "已关闭"), + ("path.toggleClosed", "Closed", "已关闭"), ("path.convertToBezier", "Convert To Bezier Path", "转换为贝塞尔曲线路径"), ("path.setFirstVertex", "Set First Vertex", "设置第一个顶点"), ("path.freeTransform", "Free Transform Points", "自由变换点"), @@ -1333,7 +1333,7 @@ const SWEDISH: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "Dölj låsta masker"), ("", "Mask and Shape Path", "Mask- och formbana"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "Sluten"), + ("path.toggleClosed", "Closed", "Sluten"), ("path.convertToBezier", "Convert To Bezier Path", "Konvertera till Bezierbana"), ("path.setFirstVertex", "Set First Vertex", "Ange första hörnpunkt"), ("path.freeTransform", "Free Transform Points", "Fri transformering av punkter"), @@ -1973,7 +1973,7 @@ const TRADITIONAL_CHINESE: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "隱藏鎖定的遮色片"), ("", "Mask and Shape Path", "遮色片和形狀路徑"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "封閉"), + ("path.toggleClosed", "Closed", "封閉"), ("path.convertToBezier", "Convert To Bezier Path", "轉換為貝茲路徑"), ("path.setFirstVertex", "Set First Vertex", "設定第一個頂點"), ("path.freeTransform", "Free Transform Points", "自由變換點"), @@ -2608,7 +2608,7 @@ const JAPANESE: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "ロックしたマスクを非表示"), ("", "Mask and Shape Path", "マスクとシェイプのパス"), ("path.rotoBezier", "RotoBezier", "ロトベジェ"), - ("mask.setClosed", "Closed", "閉じたパス"), + ("path.toggleClosed", "Closed", "閉じたパス"), ("path.convertToBezier", "Convert To Bezier Path", "ベジェパスに変換"), ("path.setFirstVertex", "Set First Vertex", "最初の頂点を設定"), ("path.freeTransform", "Free Transform Points", "ポイントを自由変形"), @@ -3246,7 +3246,7 @@ const UKRAINIAN: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "Приховати заблоковані маски"), ("", "Mask and Shape Path", "Контур маски та фігури"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "Замкнений"), + ("path.toggleClosed", "Closed", "Замкнений"), ("path.convertToBezier", "Convert To Bezier Path", "Перетворити на контур Безьє"), ("path.setFirstVertex", "Set First Vertex", "Задати першу вершину"), ("path.freeTransform", "Free Transform Points", "Вільне трансформування точок"), @@ -3885,7 +3885,7 @@ const SPANISH: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "Ocultar máscaras bloqueadas"), ("", "Mask and Shape Path", "Trazado de máscara y de forma"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "Cerrado"), + ("path.toggleClosed", "Closed", "Cerrado"), ("path.convertToBezier", "Convert To Bezier Path", "Convertir en trazado Bézier"), ("path.setFirstVertex", "Set First Vertex", "Establecer primer vértice"), ("path.freeTransform", "Free Transform Points", "Transformar puntos libremente"), @@ -4522,7 +4522,7 @@ const PORTUGUESE: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "Ocultar máscaras bloqueadas"), ("", "Mask and Shape Path", "Caminho da máscara e da forma"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "Fechado"), + ("path.toggleClosed", "Closed", "Fechado"), ("path.convertToBezier", "Convert To Bezier Path", "Converter em caminho Bézier"), ("path.setFirstVertex", "Set First Vertex", "Definir primeiro vértice"), ("path.freeTransform", "Free Transform Points", "Pontos de transformação livre"), @@ -5166,7 +5166,7 @@ const RUSSIAN: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "Скрыть заблокированные маски"), ("", "Mask and Shape Path", "Контур маски и фигуры"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "Замкнутый"), + ("path.toggleClosed", "Closed", "Замкнутый"), ("path.convertToBezier", "Convert To Bezier Path", "Преобразовать в кривую Безье"), ("path.setFirstVertex", "Set First Vertex", "Задать первую вершину"), ("path.freeTransform", "Free Transform Points", "Свободное трансформирование точек"), @@ -5803,7 +5803,7 @@ const FRENCH: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "Masquer les masques verrouillés"), ("", "Mask and Shape Path", "Trajectoire de masque et de forme"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "Fermé"), + ("path.toggleClosed", "Closed", "Fermé"), ("path.convertToBezier", "Convert To Bezier Path", "Convertir en trajectoire Bézier"), ("path.setFirstVertex", "Set First Vertex", "Définir le premier sommet"), ("path.freeTransform", "Free Transform Points", "Transformation libre des points"), @@ -6440,7 +6440,7 @@ const GERMAN: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "Gesperrte Masken ausblenden"), ("", "Mask and Shape Path", "Masken- und Formpfad"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "Geschlossen"), + ("path.toggleClosed", "Closed", "Geschlossen"), ("path.convertToBezier", "Convert To Bezier Path", "In Bézier-Pfad konvertieren"), ("path.setFirstVertex", "Set First Vertex", "Ersten Scheitelpunkt festlegen"), ("path.freeTransform", "Free Transform Points", "Punkte frei transformieren"), @@ -7076,7 +7076,7 @@ const POLISH: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "Ukryj zablokowane maski"), ("", "Mask and Shape Path", "Ścieżka maski i kształtu"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "Zamknięta"), + ("path.toggleClosed", "Closed", "Zamknięta"), ("path.convertToBezier", "Convert To Bezier Path", "Konwertuj na ścieżkę Béziera"), ("path.setFirstVertex", "Set First Vertex", "Ustaw pierwszy wierzchołek"), ("path.freeTransform", "Free Transform Points", "Swobodne przekształcanie punktów"), @@ -7712,7 +7712,7 @@ const CZECH: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "Skrýt zamknuté masky"), ("", "Mask and Shape Path", "Cesta masky a tvaru"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "Uzavřená"), + ("path.toggleClosed", "Closed", "Uzavřená"), ("path.convertToBezier", "Convert To Bezier Path", "Převést na Bézierovu cestu"), ("path.setFirstVertex", "Set First Vertex", "Nastavit první vrchol"), ("path.freeTransform", "Free Transform Points", "Volně transformovat body"), @@ -8345,7 +8345,7 @@ const GEORGIAN: &[(&str, &str, &str)] = &[ ("layer.mask.hideLocked", "Hide Locked Masks", "ჩაკეტილი ნიღბების დამალვა"), ("", "Mask and Shape Path", "ნიღაბი და ფიგურის ტრაექტორია"), ("path.rotoBezier", "RotoBezier", "RotoBezier"), - ("mask.setClosed", "Closed", "შეკრული"), + ("path.toggleClosed", "Closed", "შეკრული"), ("path.convertToBezier", "Convert To Bezier Path", "ბეზიეს ტრაექტორიად გარდაქმნა"), ("path.setFirstVertex", "Set First Vertex", "პირველი წვეროს დაყენება"), ("path.freeTransform", "Free Transform Points", "წერტილების თავისუფალი გარდაქმნა"), @@ -9215,12 +9215,16 @@ mod tests { alt_shortcuts: Vec::new(), }; let new_comp = menu_entry("comp.new", "New Composition..."); + let closed_path = menu_entry("path.toggleClosed", "Closed"); let undo = menu_entry("edit.undo", "Undo"); for code in CATALOG_CODES { app.session.execute("prefs.set", json!({"key":"general.language", "value":code})).unwrap(); let drawn = entry(&app, &new_comp, new_comp.label.clone()); assert_eq!(drawn, label(&app, "comp.new", "New Composition..."), "{code}"); assert_ne!(drawn, new_comp.label, "{code}: the menu entry is drawn in English"); + let closed_label = entry(&app, &closed_path, closed_path.label.clone()); + assert_eq!(closed_label, label(&app, "path.toggleClosed", "Closed"), "{code}"); + assert_ne!(closed_label, closed_path.label, "{code}: Closed is drawn in English"); } app.session.execute("prefs.set", json!({"key":"general.language", "value":"ru"})).unwrap(); assert_eq!(entry(&app, &undo, "Can't Undo".into()), "Нечего отменять"); From 81d585e381d9aabec87ebdfb4ecb77963972c26d Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Mon, 2 Nov 2026 22:14:13 +0530 Subject: [PATCH 03/83] Fix #2869: preserve arrows when Effect Controls is hidden --- .../src/panels/effect_controls/panel.rs | 9 ++++- crates/ui-egui/tests/it/ui_effect_controls.rs | 35 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/effect_controls/panel.rs b/crates/ui-egui/src/panels/effect_controls/panel.rs index 0d81029e6..4932ddd21 100644 --- a/crates/ui-egui/src/panels/effect_controls/panel.rs +++ b/crates/ui-egui/src/panels/effect_controls/panel.rs @@ -2,10 +2,17 @@ use super::common::{Actions, PARAM_NAME_X, ROW, effect_active, selected_layer}; use super::editors::{curves_editor, editor_height, histogram_only, levels_editor, object_matte_editor, roto_editor, warp_editor}; use super::rows::{FxScope, group_rows, toggle_closed}; use super::{Align2, Color32, EffectcraftApp, EvalCtx, GroupKind, Icon, Layer, PropGroup, Rect, Sense, Stroke, Tokens, json, pos2, vec2, widgets}; +use crate::dock::{PanelKind, WorkspaceExt as _}; /// Plain Left/Right disclose selected effect headers before global layer nudges run. pub(crate) fn handle_disclosure_key(app: &mut EffectcraftApp, key: egui::Key) -> bool { - if app.ui.focused != crate::dock::PanelKind::EffectControls || !matches!(key, egui::Key::ArrowLeft | egui::Key::ArrowRight) { + let panel = PanelKind::EffectControls; + if app.ui.focused != panel + || app.ui.start_screen + || !app.ui.dock.is_visible(panel) + || (app.ui.dock.is_docked(panel) && app.ui.maximized.is_some_and(|m| m != panel && app.ui.dock.is_docked(m))) + || !matches!(key, egui::Key::ArrowLeft | egui::Key::ArrowRight) + { return false; } let Some(comp) = app.session.active_comp() else { return false }; diff --git a/crates/ui-egui/tests/it/ui_effect_controls.rs b/crates/ui-egui/tests/it/ui_effect_controls.rs index 3de502a5b..6710b6603 100644 --- a/crates/ui-egui/tests/it/ui_effect_controls.rs +++ b/crates/ui-egui/tests/it/ui_effect_controls.rs @@ -154,6 +154,41 @@ fn effect_header_arrows_only_disclose_selected_headers_on_the_displayed_layer() assert_ne!(serde_json::to_value(&h.state().session.project).unwrap(), before, "the existing layer nudge still runs"); } +#[test] +fn effect_header_arrows_ignore_hidden_panels_with_stale_focus() { + for hidden in ["closed", "maximized", "home"] { + let (mut h, lid, [(fx, _), _, _]) = header_arrow_harness(); + h.state_mut().session.state.selected_props = vec![(lid, fx)]; + match hidden { + "closed" => h.state_mut().close_panel(PanelKind::EffectControls), + "maximized" => h.state_mut().toggle_maximize(PanelKind::Composition), + _ => h.state_mut().ui.start_screen = true, + } + h.run_steps(2); + assert_eq!(h.state().ui.focused, PanelKind::EffectControls, "{hidden}: stale focus is preserved"); + assert!(h.state().auto.find("panel.EffectControls").is_none(), "{hidden}: Effect Controls is hidden"); + let x = |h: &Harness<'_, EffectcraftApp>| layer(&h.state().session, lid.0).props.prop("transform/position").unwrap().value.as_vec3()[0]; + let before = x(&h); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert!(h.state().ui.fx_closed.is_empty(), "{hidden}: hidden effects keep their disclosure state"); + assert!(x(&h) < before, "{hidden}: Left still nudges the layer"); + } +} + +#[test] +fn effect_header_arrows_work_in_floating_panel_beside_maximized_panel() { + let (mut h, lid, [(fx, prop), _, _]) = header_arrow_harness(); + h.state_mut().apply_dock(craft_ui::docking::Action::Float { panel: PanelKind::EffectControls, rect: [40.0, 40.0, 600.0, 400.0] }).unwrap(); + h.state_mut().toggle_maximize(PanelKind::Composition); + h.state_mut().session.state.selected_props = vec![(lid, fx)]; + h.run_steps(3); + assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_some()); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_none()); + header_arrow_key(&mut h, egui::Key::ArrowRight, egui::Modifiers::NONE); + assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_some()); +} + #[test] fn effect_header_arrows_preserve_modified_shortcuts_and_keyboard_ownership() { let (mut h, lid, [(fx, _), _, _]) = header_arrow_harness(); From 2b1b68855798f23ec473408ad01fc144f313f3cd Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Mon, 2 Nov 2026 22:16:19 +0530 Subject: [PATCH 04/83] #2817: honor combined path and shape group selections --- crates/engine/src/cmd/paths/closed.rs | 20 +++++++++----------- crates/engine/src/tests/viewer.rs | 27 ++++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/paths/closed.rs b/crates/engine/src/cmd/paths/closed.rs index d3cd8c1ef..268e68843 100644 --- a/crates/engine/src/cmd/paths/closed.rs +++ b/crates/engine/src/cmd/paths/closed.rs @@ -38,19 +38,18 @@ fn targets(s: &Session) -> Result> { props: s.state.selected_props.iter().filter(|(lid, _)| s.state.selected_layers.contains(lid)).copied().collect(), time: s.time(), }; + let whole_layers = selection.vertices.is_empty() && selection.props.is_empty(); let mut targets = Vec::new(); for layer in comp.layers.iter() { - let selected_layer = if !selection.vertices.is_empty() { - selection.vertices.iter().any(|v| v.layer == layer.id) - } else if !selection.props.is_empty() { - selection.props.iter().any(|(lid, _)| *lid == layer.id) - } else { + let selected_layer = if whole_layers { s.state.selected_layers.contains(&layer.id) + } else { + selection.vertices.iter().any(|v| v.layer == layer.id) || selection.props.iter().any(|(lid, _)| *lid == layer.id) }; if !selected_layer || layer.switches.locked { continue; } - collect(&selection, layer, &layer.props, &mut Vec::new(), selection.props.is_empty(), &mut targets)?; + collect(&selection, layer, &layer.props, &mut Vec::new(), whole_layers, &mut targets)?; } if targets.is_empty() { return Err(bad("path.toggleClosed", "select an unlocked mask or Bezier shape path")); @@ -70,11 +69,10 @@ fn collect(selection: &Selection, layer: &Layer, group: &PropGroup, route: &mut && let Some(prop) = group.get("path") && let KV::Path(path) = prop.value_at(layer.layer_time(selection.time)) { - let selected = if selection.vertices.is_empty() { - selected || selection.props.contains(&(layer.id, prop.uid)) - } else { - selection.vertices.iter().any(|v| v.layer == layer.id && v.mask == group.uid && v.index < path.vertices.len()) - }; + // Property selection also selects its points; both describe the selected paths. + let selected = selected + || selection.props.contains(&(layer.id, prop.uid)) + || selection.vertices.iter().any(|v| v.layer == layer.id && v.mask == group.uid && v.index < path.vertices.len()); if selected { targets.push(Target { layer: layer.id, route: route.clone(), closed: path.closed }); } diff --git a/crates/engine/src/tests/viewer.rs b/crates/engine/src/tests/viewer.rs index 36e3b0537..a9cd5c646 100644 --- a/crates/engine/src/tests/viewer.rs +++ b/crates/engine/src/tests/viewer.rs @@ -302,7 +302,7 @@ fn toggle_closed_respects_path_and_vertex_selection() { s.state.selected_props = vec![(LayerId(lid), b)]; s.state.selected_vertices = vec![crate::VertexRef { layer: LayerId(lid), mask: a, index: 1 }]; s.execute("path.toggleClosed", json!({})).unwrap(); - assert!(shape_path(&s, lid, a).closed, "vertices take precedence over property selection"); + assert!(shape_path(&s, lid, a).closed, "selected points and properties both describe target paths"); assert!(shape_path(&s, lid, b).closed); s.state.selected_vertices.clear(); s.state.selected_props = vec![(LayerId(lid), a), (LayerId(lid), leaf), (LayerId(lid), b)]; @@ -323,6 +323,31 @@ fn toggle_closed_respects_path_and_vertex_selection() { assert!(!shape_path(&s, lid, b).closed, "layer selection addresses all editable paths"); } +#[test] +fn toggle_closed_combines_property_and_shape_group_selections() { + let mut s = comp(); + let a = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); + let (lid, a_path) = (a["layer"].as_u64().unwrap(), a["path"].as_u64().unwrap()); + let b = s.execute("shape.newPath", json!({"layer": lid, "vertices": [[10, 10], [90, 10], [90, 90]], "closed": true})).unwrap(); + let (b_path, b_group) = (b["path"].as_u64().unwrap(), b["group"].as_u64().unwrap()); + let c_path = + s.execute("shape.newPath", json!({"layer": lid, "vertices": [[20, 20], [80, 20], [80, 80]], "closed": true})).unwrap()["path"].as_u64().unwrap(); + s.execute("prop.select", json!({"layer": lid, "prop": a_path})).unwrap(); + s.execute("prop.select", json!({"layer": lid, "prop": b_group, "add": true})).unwrap(); + assert!(s.state.selected_vertices.iter().all(|v| v.mask == a_path), "only the path property implies selected vertices"); + assert!(!s.state.selected_vertices.is_empty()); + assert!(s.state.selected_props.contains(&(LayerId(lid), b_group))); + let result = s.execute("path.toggleClosed", json!({})).unwrap(); + assert_eq!(result["paths"], json!(2)); + assert!(!shape_path(&s, lid, a_path).closed); + assert!(!shape_path(&s, lid, b_path).closed, "the added shape group is included alongside implied vertices"); + assert!(shape_path(&s, lid, c_path).closed, "unselected sibling stays unchanged"); + s.execute("edit.undo", json!({})).unwrap(); + assert!(shape_path(&s, lid, a_path).closed); + assert!(shape_path(&s, lid, b_path).closed, "both selected paths undo together"); + assert!(shape_path(&s, lid, c_path).closed); +} + #[test] fn toggle_closed_ignores_selections_retained_on_other_layers() { let mut s = comp(); From b60f231fe9153e911a6ad980078a77f697eeb8e9 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 11 Nov 2026 16:29:25 +0530 Subject: [PATCH 05/83] #3087: keep an effect without a counterpart as a placeholder Third-party plug-ins and pseudo effects (expression controls) were dropped on import, so expressions reading them broke. Such an effect now arrives as an effect group whose effect id is its After Effects match name: it renders nothing, like a missing plug-in, and is listed by Find Missing Effects. It holds the effect's parameters flat, named as in After Effects, with their values, keys and expressions in the units After Effects' expressions read. It is still reported (once per match name, "kept without rendering") and counted in imported.placeholderEffects. The parameters and popup items kept are bounded per import. Co-Authored-By: Claude Opus 5.5 --- crates/aep/src/import.rs | 4 +- crates/aep/src/import/effects.rs | 87 +++++---- crates/aep/src/import/placeholder.rs | 166 +++++++++++++++++ crates/aep/src/import/report.rs | 7 + crates/aep/tests/it/import.rs | 1 + crates/aep/tests/it/import/placeholders.rs | 200 +++++++++++++++++++++ crates/expr/src/tests.rs | 18 ++ docs/aep-import.md | 20 ++- 8 files changed, 461 insertions(+), 42 deletions(-) create mode 100644 crates/aep/src/import/placeholder.rs create mode 100644 crates/aep/tests/it/import/placeholders.rs diff --git a/crates/aep/src/import.rs b/crates/aep/src/import.rs index fae3b3256..20a4b7b1e 100644 --- a/crates/aep/src/import.rs +++ b/crates/aep/src/import.rs @@ -14,7 +14,8 @@ //! missing-footage placeholders). `docs/aep-import.md` has the full list. //! //! What does not arrive is **reported**, never dropped silently: [`ImportReport`] counts other -//! effects (by match name) and unimported effect parameters, unusable masks, layer style +//! effects (by match name; they arrive as placeholders that render nothing, with their parameters +//! for expressions) and unimported effect parameters, unusable masks, layer style //! features, text layer features, shape items, unsupported blend modes and transform //! properties, simplified keyframes and unreadable data per [`LossCategory`]. By default the import //! is refused when anything would be lost ([`ImportOptions::allow_losses`] lifts that); a refusal @@ -30,6 +31,7 @@ mod effects; mod lumetri; mod markers; mod masks; +mod placeholder; mod props; mod puppet; mod report; diff --git a/crates/aep/src/import/effects.rs b/crates/aep/src/import/effects.rs index 1ab4b208a..86faac76a 100644 --- a/crates/aep/src/import/effects.rs +++ b/crates/aep/src/import/effects.rs @@ -1,7 +1,8 @@ //! Effects: a table maps an After Effects effect (its match name) and its parameters (by their -//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Effects and -//! parameters outside the table are reported in [`LossCategory::Effects`] by match name, never -//! dropped silently. +//! index in `parT`) to an EffectCraft effect, a parameter id and a unit conversion. Parameters +//! outside the table are reported in [`LossCategory::Effects`] by match name, never dropped +//! silently. An effect outside it arrives as a placeholder holding its parameters (`placeholder.rs`) +//! and is reported too. //! //! Every conversion is backed by the corpus (`docs/aep-format.md` 3.7, cases 356-450, 511-516): //! @@ -82,44 +83,29 @@ pub(crate) fn import_effects<'f, 'a>( continue; } let shown = fx.display_name().unwrap_or_else(|| fx.match_name().to_string()); - let Some(map) = EFFECTS.iter().find(|m| m.match_name == fx.match_name()) else { - col.lose_unmapped_effect(fx.match_name(), format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name())); - continue; - }; - let Some(spec) = effectcraft_effects::find(map.effect) else { - col.lose_unmapped_effect(fx.match_name(), format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name())); - continue; - }; + let found = EFFECTS.iter().find(|m| m.match_name == fx.match_name()).and_then(|m| Some((m, effectcraft_effects::find(m.effect)?))); + let lost = format!("{}: '{}' has the effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()); if defs.source(&fx) == DefinitionSource::Missing { - col.lose( - LossCategory::Effects, - format!("{}: '{}' has the effect '{shown}' ({}) without readable parameter definitions, not imported", cx.comp, cx.layer, fx.match_name()), - ); + match found { + Some(_) => col.lose(LossCategory::Effects, format!("{lost} without readable parameter definitions, not imported")), + None => col.lose_unmapped_effect(fx.match_name(), lost), + } continue; } - let size = [f64::from(cx.size.0), f64::from(cx.size.1)]; - let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size); - match fx.enabled() { - Some(on) => group.enabled = on, - None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)), - } let params = defs.params(&fx); - // Borrowed definitions (another instance's or the project copy) may not name every value - // record this instance has: such a record has nothing to import into, so it is reported. - if params.first().is_some_and(|p| p.borrowed_definition) { - let defined: std::collections::HashSet<&str> = params.iter().map(|p| p.match_name.as_str()).collect(); - for name in fx.value_record_names().iter().filter(|n| !defined.contains(n.as_str())) { - col.lose( - LossCategory::Effects, - format!( - "{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported", - cx.comp, - cx.layer, - fx.match_name() - ), - ); - } - } + report_records_without_definition(&fx, ¶ms, cx, &shown, col); + let Some((map, spec)) = found else { + // No counterpart: kept as a placeholder that renders nothing, for expressions (#3087). + let mut group = crate::import::placeholder::placeholder(&fx, ¶ms, cx, &shown, ids, refs, col); + set_enabled(&fx, &mut group, cx, &shown, col); + col.lose_unmapped_effect(fx.match_name(), format!("{lost}, kept without rendering")); + col.imported.placeholder_effects = col.imported.placeholder_effects.saturating_add(1); + target.children.push(Node::Group(group)); + continue; + }; + let size = [f64::from(cx.size.0), f64::from(cx.size.1)]; + let mut group = effectcraft_effects::instantiate(spec, ids, &shown, size); + set_enabled(&fx, &mut group, cx, &shown, col); if map.extra == Extra::Lumetri { crate::import::lumetri::import_lumetri(&fx, ¶ms, cx, &shown, ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col }); } else if map.extra == Extra::Cryptomatte { @@ -134,6 +120,29 @@ pub(crate) fn import_effects<'f, 'a>( } } +/// The effect's fx switch. +fn set_enabled(fx: &AepEffect<'_, '_>, group: &mut PropGroup, cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) { + match fx.enabled() { + Some(on) => group.enabled = on, + None => col.lose(LossCategory::DamagedData, format!("{}: '{}': the fx switch of '{shown}' is unreadable, imported switched on", cx.comp, cx.layer)), + } +} + +/// Borrowed definitions (another instance's or the project copy) may not name every value record +/// this instance has: such a record has nothing to import into, so it is reported. +fn report_records_without_definition(fx: &AepEffect<'_, '_>, params: &[EffectParam<'_, '_>], cx: &LayerCtx<'_>, shown: &str, col: &mut Collector) { + if !params.first().is_some_and(|p| p.borrowed_definition) { + return; + } + let defined: std::collections::HashSet<&str> = params.iter().map(|p| p.match_name.as_str()).collect(); + for name in fx.value_record_names().iter().filter(|n| !defined.contains(n.as_str())) { + col.lose( + LossCategory::Effects, + format!("{}: '{}' effect '{shown}' ({}): the value record {name} has no parameter definition, not imported", cx.comp, cx.layer, fx.match_name()), + ); + } +} + /// Parameters that never carry a value to import. pub(crate) fn carries_nothing(p: &EffectParam<'_, '_>) -> bool { matches!(p.kind, ParamKind::Button | ParamKind::NoData | ParamKind::GroupStart | ParamKind::GroupEnd) || (p.index == 0 && p.kind == ParamKind::Layer) @@ -364,7 +373,7 @@ fn report_beyond_limit<'v>(limit: Option<(f64, f64)>, values: impl Iterator, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) { +pub(crate) fn import_layer_ref(p: &EffectParam<'_, '_>, target: &str, own: bool, cx: &LayerCtx<'_>, names: (&str, &str), out: ParamOut<'_>) { let (here, label) = names; let ParamOut { group, refs, col } = out; // After Effects hands the named layer's source to the effect, without its masks and effects @@ -799,7 +808,7 @@ fn px(v: f64) -> String { /// A decoded value in EffectCraft's units, `None` when it does not fit the kind or is not a valid /// number. -fn convert(value: ParamValue, kind: Kind) -> Option { +pub(crate) fn convert(value: ParamValue, kind: Kind) -> Option { let raw = match (value, kind) { // The reader gives colours as ARGB fractions; `Kind` takes the stored 0..255. (ParamValue::Argb(c), Kind::EffectColor) => c.map(|x| x * 255.0).to_vec(), diff --git a/crates/aep/src/import/placeholder.rs b/crates/aep/src/import/placeholder.rs new file mode 100644 index 000000000..4e9fd8047 --- /dev/null +++ b/crates/aep/src/import/placeholder.rs @@ -0,0 +1,166 @@ +//! Placeholders: an effect with no EffectCraft counterpart (a third-party plug-in, a pseudo effect +//! of expression controls) arrives as an effect group that renders nothing, as a missing plug-in +//! does. Its effect id is the After Effects match name, so Find Missing Effects lists it. It holds +//! the effect's parameters, flat and named as in After Effects, each with its value, keys and +//! expression, so expressions that read them (`effect("Settings")("Speed")`) keep working. It is +//! still reported, once per match name. +//! +//! The values keep After Effects' units, the ones its expressions read: sliders and angles as +//! stored, points in layer pixels, colours RGBA 0..1, checkboxes on / off, popups as EffectCraft's +//! 0-based items over the file's items in order (expressions read them 1-based, as After Effects +//! does). Layer parameters name their layer. Paths and arbitrary data are not kept (reported when +//! they hold something). +//! +//! The parameters a placeholder holds are bounded per import ([`MAX_COST`]): definitions can be +//! shared by many instances, so a small file could otherwise ask for very many properties. + +use effectcraft_keyframe::Value; +use effectcraft_project::build::Ids; +use effectcraft_project::{GroupKind, Node, ParamUi, PropGroup, Property}; + +use crate::import::effects::{LayerCtx, ParamOut, PendingLayerRef, carries_nothing, convert, import_layer_ref, param_label}; +use crate::import::props::{Kind, import_expression, import_keys}; +use crate::import::report::{Collector, LossCategory}; +use crate::{Effect as AepEffect, EffectParam, ParamKind, ParamValue}; + +/// Most placeholder properties and popup items one import creates. +pub(crate) const MAX_COST: usize = 200_000; + +/// Most items read from one placeholder popup. +const MAX_POPUP_ITEMS: usize = 1024; + +/// The placeholder of `fx`, with `params` (its parameter definitions) as properties. +pub(crate) fn placeholder( + fx: &AepEffect<'_, '_>, + params: &[EffectParam<'_, '_>], + cx: &LayerCtx<'_>, + shown: &str, + ids: &mut Ids<'_>, + refs: &mut Vec, + col: &mut Collector, +) -> PropGroup { + let mut group = ids.group(fx.match_name(), shown); + group.kind = GroupKind::Effect { effect: fx.match_name().to_string() }; + let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()); + for p in params.iter().filter(|p| !carries_nothing(p)) { + if col.placeholder_cost >= MAX_COST { + // Once the budget is spent nothing more is built (definitions shared by many instances + // would otherwise still be walked item by item). + col.lose(LossCategory::Effects, format!("{here}: parameters past the import's {MAX_COST} placeholder parameters not kept")); + break; + } + let label = param_label(p); + let Some((kind, ui, default)) = shape(p, cx.size) else { + if p.stored().is_some() { + col.lose(LossCategory::Effects, format!("{here}: parameter {label} not kept (type {:?})", p.kind)); + } + continue; + }; + let items = match &ui { + ParamUi::Popup { options } => options.len(), + _ => 0, + }; + let cost = col.placeholder_cost.saturating_add(items).saturating_add(1); + if cost > MAX_COST { + col.lose(LossCategory::Effects, format!("{here}: parameter {label} not kept (past the import's {MAX_COST} placeholder parameters)")); + continue; + } + col.placeholder_cost = cost; + let mut prop = Property::new(ids.alloc(), ¶m_id(p), p.name.trim(), default).with_ui(ui); + prop.spatial = p.kind == ParamKind::Point; + prop.hold_only = matches!(p.kind, ParamKind::Checkbox | ParamKind::Popup | ParamKind::Layer); + match kind { + Some(kind) => { + fill(p, &mut prop, kind, cx, (&here, &label), col); + group.children.push(Node::Prop(prop)); + } + // A layer parameter: the layer it names (set once every layer exists, by its uid). + None => { + let id = format!("@{}", prop.uid); + group.children.push(Node::Prop(prop)); + import_layer_ref(p, &id, true, cx, (&here, &label), ParamOut { group: &mut group, refs: &mut *refs, col: &mut *col }); + } + } + } + group +} + +/// How parameter `p` is held on a layer `size` big: its unit conversion (`None` for a layer +/// parameter), its control and its value until one is read. `None` for a type that is not kept. +fn shape(p: &EffectParam<'_, '_>, size: (u32, u32)) -> Option<(Option, ParamUi, Value)> { + let (kind, ui, default) = match p.kind { + ParamKind::IntSlider | ParamKind::FixedSlider | ParamKind::FloatSlider => (Kind::EffectNumber(1.0), ParamUi::Number, Value::Scalar(0.0)), + ParamKind::Angle => (Kind::EffectNumber(1.0), ParamUi::Angle, Value::Scalar(0.0)), + ParamKind::Checkbox => (Kind::EffectBool, ParamUi::Checkbox, Value::Bool(false)), + ParamKind::Color => (Kind::EffectColor, ParamUi::Color, Value::Color([0.0, 0.0, 0.0, 1.0])), + ParamKind::Point => (Kind::EffectPoint(f64::from(size.0), f64::from(size.1)), ParamUi::Point, Value::Vec2([0.0, 0.0])), + ParamKind::Layer => return Some((None, ParamUi::Layer, Value::Layer(None))), + ParamKind::Popup => { + // The file's items, separators (`(-`) included: After Effects counts them. + let options: Vec = match &p.items { + Some(items) => items.iter().take(MAX_POPUP_ITEMS).cloned().collect(), + None => (1..=usize::from(p.popup_item_count()?).min(MAX_POPUP_ITEMS)).map(|i| format!("Item {i}")).collect(), + }; + let n = u32::try_from(options.len()).ok().filter(|n| *n > 0)?; + (Kind::EffectPopup(n), ParamUi::Popup { options }, Value::Enum(0)) + } + _ => return None, + }; + Some((Some(kind), ui, default)) +} + +/// The property id of `p`: its match name when that is one segment of a property path (a +/// third-party effect's `CC Cylinder-0003`), else `param` (a pseudo effect's +/// `Pseudo/0.25-0001`: `/` and `.` separate path segments). Expressions also find it by its name. +fn param_id(p: &EffectParam<'_, '_>) -> String { + let plain = !p.match_name.is_empty() && p.match_name.chars().all(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')); + if plain { p.match_name.clone() } else { format!("param{}", p.index) } +} + +/// Sets `prop` from `p`: its expression, then its keys or its value (the record, else the `pard` +/// default). `names` is `(here, label)` for the report. +fn fill(p: &EffectParam<'_, '_>, prop: &mut Property, kind: Kind, cx: &LayerCtx<'_>, names: (&str, &str), col: &mut Collector) { + let (here, label) = names; + if let Some(stored) = p.stored() { + import_expression(&stored, prop, col); + } + if p.is_animated() { + let Some(stored) = p.stored() else { return }; + if kind == Kind::EffectBool { + // Keys on a checkbox are not sampled by the corpus. + col.lose(LossCategory::Effects, format!("{here}: the keyframes of parameter {label} are not kept (not decoded)")); + return; + } + let before = prop.keys.len(); + import_keys(&stored, kind, cx.layer, &p.match_name, cx.tm, prop, col); + if prop.keys.len() == before { + col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} has no readable keyframe")); + } + return; + } + let value = match (p.stored(), p.recorded_value()) { + (Some(_), Some(v)) => v, + (Some(_), None) => { + col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds an unreadable value")); + return; + } + // A borrowed popup's default slot holds another copy's selection (docs/aep-format.md 3.7). + (None, _) if p.kind == ParamKind::Popup && p.borrowed_definition => { + col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not known (shared definition), the first item used")); + return; + } + // A popup's default slot can hold 0, no item (After Effects' save of a project it opened). + (None, _) => match p.pard_default() { + Some(ParamValue::Index(0)) => { + col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the default item is not stored, the first item used")); + return; + } + Some(v) => v, + None => return, + }, + }; + match convert(value, kind) { + Some(v) => prop.value = v, + None => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds a value that is not valid ({value:?})")), + } +} diff --git a/crates/aep/src/import/report.rs b/crates/aep/src/import/report.rs index 2825b61b3..8b3599266 100644 --- a/crates/aep/src/import/report.rs +++ b/crates/aep/src/import/report.rs @@ -156,6 +156,10 @@ pub struct Imported { /// in [`LossCategory::Effects`]). #[serde(default)] pub effects: usize, + /// Effects with no counterpart, kept as placeholders that render nothing (their parameters, + /// for expressions; each is also in [`LossCategory::Effects`]). + #[serde(default)] + pub placeholder_effects: usize, /// Layer styles (Drop Shadow, Stroke, ...), one per style on a layer. #[serde(default)] pub layer_styles: usize, @@ -273,6 +277,9 @@ pub(crate) struct Collector { /// many instances there were. They get a line each in [`Collector::finish`], so one that /// comes after the example lines are used up is still named (#3365). unmapped_effects: BTreeMap, + /// The properties and popup items the placeholders of this import hold so far (at most + /// `placeholder::MAX_COST`). + pub placeholder_cost: usize, } /// How many different unmapped effects get a line of their own (a file names at most this many). diff --git a/crates/aep/tests/it/import.rs b/crates/aep/tests/it/import.rs index 2535edcff..240c3ea0f 100644 --- a/crates/aep/tests/it/import.rs +++ b/crates/aep/tests/it/import.rs @@ -22,6 +22,7 @@ mod lumetri; mod markers; mod masks; mod mattes; +mod placeholders; mod puppet; mod resaved_defaults; mod robustness; diff --git a/crates/aep/tests/it/import/placeholders.rs b/crates/aep/tests/it/import/placeholders.rs new file mode 100644 index 000000000..847060f93 --- /dev/null +++ b/crates/aep/tests/it/import/placeholders.rs @@ -0,0 +1,200 @@ +//! #3087: an effect with no EffectCraft counterpart (a third-party plug-in, a pseudo effect of +//! expression controls) arrives as a placeholder holding its parameters, so expressions that read +//! them keep working; it renders nothing and is still reported. Each effect is built into +//! `synthetic.aep` (`fx_inject`) in place of its Glow, on the 8 x 8 sequence layer. + +use crate::import::fx_inject::{Default, Fx, bytes_with, import_bytes, losses, other, popup, run, slider, v}; +use effectcraft_aep::import::LossCategory; +use effectcraft_aep::{Body, Chunk, ParamKind as K, parse, write}; +use effectcraft_keyframe::Value; +use effectcraft_project::{GroupKind, ParamUi, PropGroup}; + +/// A third-party effect with one parameter of each kept kind, inside a twirl-down group. +fn third_party(values: Vec<(usize, f64)>, keys: Vec<(usize, Vec<(i32, f64)>)>) -> Fx { + Fx { + match_name: "CC Cylinder", + name: "CC Cylinder", + defs: vec![ + other(K::GroupStart, "Light", Default::None), + slider(K::FloatSlider, "Radius (%)", 30.0, (0.0, 30000.0)), + other(K::GroupEnd, "", Default::None), + other(K::Angle, "Rotation X", Default::Number(12.5)), + other(K::Checkbox, "Wire", Default::Number(1.0)), + other(K::Color, "Light Color", Default::Color([255, 51, 102, 204])), + other(K::Point, "Position", Default::Point(0.25, 0.5)), + popup("Render", 1, &["Full", "(-", "Outside", "Inside"]), + slider(K::IntSlider, "Count", 3.0, (0.0, 50.0)), + ], + values, + data: vec![], + keys, + } +} + +fn placeholder_of(fx: &Fx) -> (PropGroup, effectcraft_aep::import::ImportResult) { + let (g, r) = run(fx, fx.match_name); + (g.expect("the placeholder"), r) +} + +#[test] +fn an_effect_without_a_counterpart_is_kept_with_its_values() { + // Radius 37.5 and Render "Outside" (3: the separator counts) stored, the rest at defaults. + let (g, r) = placeholder_of(&third_party(vec![(2, 37.5), (8, 3.0)], vec![])); + assert_eq!(g.kind, GroupKind::Effect { effect: "CC Cylinder".into() }); + assert_eq!(g.name, "CC Cylinder"); + let names: Vec<(&str, &str)> = g.props().map(|p| (p.match_id.as_str(), p.name.as_str())).collect(); + assert_eq!( + names, + [ + ("CC Cylinder-0002", "Radius (%)"), + ("CC Cylinder-0004", "Rotation X"), + ("CC Cylinder-0005", "Wire"), + ("CC Cylinder-0006", "Light Color"), + ("CC Cylinder-0007", "Position"), + ("CC Cylinder-0008", "Render"), + ("CC Cylinder-0009", "Count"), + ], + "flat, in order, without the group markers" + ); + assert_eq!(v(&g, "CC Cylinder-0002"), Value::Scalar(37.5)); + assert_eq!(v(&g, "CC Cylinder-0004"), Value::Scalar(12.5)); + assert_eq!(v(&g, "CC Cylinder-0005"), Value::Bool(true)); + let Value::Color(c) = v(&g, "CC Cylinder-0006") else { panic!("a colour") }; + assert!(c.iter().zip([0.2, 0.4, 0.8, 1.0]).all(|(a, b)| (a - b).abs() < 1e-6), "{c:?}"); + assert_eq!(v(&g, "CC Cylinder-0007"), Value::Vec2([2.0, 4.0]), "layer pixels"); + assert_eq!(v(&g, "CC Cylinder-0008"), Value::Enum(2), "item 3 of 4, 0-based"); + assert_eq!(v(&g, "CC Cylinder-0009"), Value::Scalar(3.0)); + let render = g.prop("CC Cylinder-0008").unwrap(); + assert_eq!(render.ui, ParamUi::Popup { options: ["Full", "(-", "Outside", "Inside"].map(String::from).to_vec() }); + // Still reported, once, and counted apart from the imported effects. + let found = losses(&r, LossCategory::Effects, "CC Cylinder"); + assert!(found.len() == 1 && found[0].ends_with("has the effect 'CC Cylinder' (CC Cylinder), kept without rendering"), "{found:?}"); + assert_eq!((r.report.imported.placeholder_effects, r.report.imported.effects), (1, 1), "the placeholder and the Levels"); +} + +#[test] +fn keys_and_expressions_of_a_placeholder_are_kept() { + let fx = third_party(vec![(4, 12.5)], vec![(2, vec![(0, 10.0), (25, 20.0)])]); + let bytes = with_expression(&bytes_with(&fx), "CC Cylinder-0004", "time * 90"); + let (g, _) = import_bytes(&bytes, "CC Cylinder"); + let g = g.unwrap(); + let radius = g.prop("CC Cylinder-0002").unwrap(); + assert_eq!(radius.keys.iter().map(|k| k.value.clone()).collect::>(), [Value::Scalar(10.0), Value::Scalar(20.0)]); + let angle = g.prop("CC Cylinder-0004").unwrap(); + assert_eq!(angle.expr.as_ref().map(|e| (e.text.as_str(), e.enabled)), Some(("time * 90", true))); +} + +/// A pseudo effect's parameter match names (`Pseudo/0.25-0001`) are no property path segment: +/// its parameters are `param`, found by their names. +#[test] +fn a_pseudo_effect_is_kept_with_its_parameter_names() { + let fx = Fx { + match_name: "Pseudo/0.25", + name: "Settings", + defs: vec![slider(K::FloatSlider, "Speed", 1.0, (0.0, 100.0)), popup("Mode", 2, &["A", "B"])], + values: vec![(1, 4.0)], + data: vec![], + keys: vec![], + }; + let (g, r) = placeholder_of(&fx); + assert_eq!(g.prop("param1").map(|p| (p.name.as_str(), p.value.clone())), Some(("Speed", Value::Scalar(4.0)))); + assert_eq!(g.prop("param2").map(|p| (p.name.as_str(), p.value.clone())), Some(("Mode", Value::Enum(1)))); + assert_eq!(losses(&r, LossCategory::Effects, "Pseudo/0.25").len(), 1); +} + +/// A popup whose definition is borrowed (the project copy) and has no value record: its default +/// slot holds another copy's selection, so the first item is used and that is reported. +#[test] +fn a_borrowed_popup_without_a_record_takes_the_first_item_and_is_reported() { + let bytes = without_instance_definitions(&bytes_with(&third_party(vec![], vec![]))); + let (g, r) = import_bytes(&bytes, "CC Cylinder"); + assert_eq!(v(&g.unwrap(), "CC Cylinder-0008"), Value::Enum(0)); + let found = losses(&r, LossCategory::Effects, "CC Cylinder"); + assert!(found.iter().any(|d| d.contains("Render") && d.contains("default item is not known")), "{found:?}"); +} + +/// A popup default slot of 0 (no item; After Effects' save of a project it opened) takes the first +/// item and is reported, not read as damaged data. +#[test] +fn a_popup_default_of_no_item_takes_the_first_item() { + let fx = Fx { match_name: "Some Fx", name: "Some", defs: vec![popup("Mode", 0, &["A", "B"])], values: vec![], data: vec![], keys: vec![] }; + let (g, r) = placeholder_of(&fx); + assert_eq!(v(&g, "Some Fx-0001"), Value::Enum(0)); + let found = losses(&r, LossCategory::Effects, "Some Fx"); + assert!(found.iter().any(|d| d.contains("default item is not stored")), "{found:?}"); + assert!(losses(&r, LossCategory::DamagedData, "Some Fx").is_empty()); +} + +/// Many large popups stay within the import's budget: what is beyond is reported, not kept. +#[test] +fn a_hostile_placeholder_stays_bounded() { + let items: &'static [&'static str] = Box::leak((0..1000).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::>().into_boxed_slice()); + let fx = Fx { match_name: "Big Fx", name: "Big", defs: (0..300).map(|_| popup("P", 1, items)).collect(), values: vec![], data: vec![], keys: vec![] }; + let (g, r) = placeholder_of(&fx); + let kept = g.props().count(); + assert!(kept > 0 && kept < 300, "{kept}"); + assert!(g.props().map(|p| if let ParamUi::Popup { options } = &p.ui { options.len() + 1 } else { 1 }).sum::() <= 200_000); + assert!(losses(&r, LossCategory::Effects, "Big Fx").iter().any(|d| d.contains("placeholder parameters"))); +} + +/// `bytes` with the expression `text` on the parameter record `param` (enabled: `tdb4` byte 120 +/// 1, docs/aep-format.md 3.6). +fn with_expression(bytes: &[u8], param: &str, text: &str) -> Vec { + let mut file = parse(bytes).unwrap(); + let mut done = 0; + edit(&mut file.chunks, false, &mut |c, _| { + let Body::List { children, .. } = &mut c.body else { return }; + let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(param.as_bytes()))) else { + return; + }; + let Some(Body::List { children: record, .. }) = children.get_mut(at + 1).map(|k| &mut k.body) else { return }; + for k in record.iter_mut().filter(|k| k.is(b"tdb4")) { + if let Body::Data(d) = &mut k.body + && let Some(b) = d.to_mut().get_mut(120) + { + *b = 1; + } + } + record.push(Chunk::data(*b"Utf8", text.as_bytes().to_vec())); + done += 1; + }); + assert!(done >= 1); + write(&file).unwrap() +} + +/// `bytes` with the layer's instance of `CC Cylinder` stripped of its own definitions (an empty +/// `parT`): it borrows the project copy's (`EfdG`). +fn without_instance_definitions(bytes: &[u8]) -> Vec { + let mut file = parse(bytes).unwrap(); + let mut done = 0; + edit(&mut file.chunks, false, &mut |c, in_project_copy| { + let Body::List { children, .. } = &mut c.body else { return }; + if in_project_copy { + return; + } + let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(&b"CC Cylinder"[..]))) + else { + return; + }; + let Some(sspc) = children.get_mut(at + 1).filter(|k| k.is_list(b"sspc")) else { return }; + for k in sspc.children_mut() { + if let Body::List { list_type, children } = &mut k.body + && list_type == b"parT" + { + children.clear(); + done += 1; + } + } + }); + assert_eq!(done, 1, "one instance"); + write(&file).unwrap() +} + +/// Calls `f` on every chunk with whether it is inside the project's effect definitions (`EfdG`). +fn edit(chunks: &mut [Chunk<'_>], in_efdg: bool, f: &mut dyn FnMut(&mut Chunk<'_>, bool)) { + for c in chunks { + let inside = in_efdg || c.is_list(b"EfdG"); + f(c, inside); + edit(c.children_mut(), inside, f); + } +} diff --git a/crates/expr/src/tests.rs b/crates/expr/src/tests.rs index d16f1dd54..f6d07bedc 100644 --- a/crates/expr/src/tests.rs +++ b/crates/expr/src/tests.rs @@ -1376,6 +1376,24 @@ fn checkbox_and_dropdown_results() { assert_close!(f.ev(f.b, ROT, "effect('Dropdown Menu Control')('Menu') * 10", 0.0).unwrap().as_f64(), 10.0); } +/// An effect EffectCraft does not have (an imported After Effects placeholder, #3087) is read by +/// name like any other: its parameters by their names, a popup 1-based. +#[test] +fn an_unknown_effects_parameters_are_read_by_name() { + let mut f = fx(); + let g = group_push(&mut f.p, |ids| { + let mut g = ids.group("Pseudo/0.25", "Settings"); + g.kind = effectcraft_project::GroupKind::Effect { effect: "Pseudo/0.25".into() }; + g.children.push(ids.prop("param1", "Speed", Value::Scalar(3.0)).into()); + g.children.push(ids.prop("param2", "Mode", Value::Enum(1)).into()); + g + }); + f.layer_mut(f.b).props.sub_mut("effects").unwrap().children.push(g.into()); + assert_close!(f.ev(f.b, ROT, "effect('Settings')('Speed') * 2", 0.0).unwrap().as_f64(), 6.0); + assert_close!(f.ev(f.b, ROT, "effect('Settings')('Mode') * 10", 0.0).unwrap().as_f64(), 20.0); + assert_close!(f.ev(f.b, ROT, "effect('Settings')(1)", 0.0).unwrap().as_f64(), 3.0); +} + #[test] fn syntax_error_reports_line() { let f = fx(); diff --git a/docs/aep-import.md b/docs/aep-import.md index c704e0a89..b4c37646f 100644 --- a/docs/aep-import.md +++ b/docs/aep-import.md @@ -1,6 +1,6 @@ # After Effects project import -> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-10 · **Change:** dropped projects and projects picked in File ▸ Import ▸ File… import as projects, several asked about one at a time; `file.import` hands them to `file.importAep`; the menu entries are named Adobe After Effects Project… (#3103); before that: After Effects' Puppet arrives as EffectCraft's Puppet without its meshes and pins, which are reported mesh by mesh (#3093; the storage is not sampled yet, aep-format 3.7); before that: Lumetri Color's master RGB curve, Hue vs Sat curve and colour wheels are imported (1200 presets made by hand); before that: Lumetri Color is imported (1200: every slider, checkbox and popup with a counterpart, by match name, also from records in the default state; switched-off sections, LUTs, looks, undecoded curves and wheels are reported); before that: the report names the After Effects version a file is written for and the one that wrote it (`aeVersion`); copies saved as 25.x and 24.x import like the 2026 save; before that: Curves and Mesh Warp are imported (961-965, 985; FORMAT S of the corpus); before that: a shape item's eye switch is imported (bit 0 of its group flags, 986 / 987: a switched-off Fill under Trim Paths is no longer drawn, render equal to After Effects), and a layer style's (switch group `tdsb` 0, 988); before that: a negative time stretch (Time Reverse Layer) is imported: in and out point in order, the layer plays backwards (981-983: render equal to After Effects at 7 points); before that: After Effects' None on Compound Blur, Displacement Map and Set Matte arrives as an explicit None (`NO_LAYER`), not as the owning layer; before that: layer styles are imported (the nine styles and Blending Options, 951-979; Global Light becomes the composition's); before that: the 27 effects of round 3 are in the table (`effectcraft_aep::effect_map`); before that: a layer of a clip, sequence or sound ends at its source's end (After Effects ends it there when it opens a project, read-back test f1), unless it is remapped or looped or runs less than a frame past; before that: keys of shape colours are read (the reader took their 152-byte spatial records for plain ones: `tdb4` byte 7 is 0 there, 854); before that: the effect table moved to `effectcraft_aep::effect_map`; point defaults in percent and a popup default slot of 0 (After Effects' save of a project it opened, e1 / e2 re-saves) are read; before that: the justification of right-to-left paragraphs is read relative to the direction (t7); before that: 24 more layer blend modes (906, 907); before that: 27 more effects are imported (batch 6: 903-905), with layer parameters; before that: a Rec. 709 working space also sets the output space (After Effects renders in the working space, 902); before that: a mask whose path was never set arrives as the source rectangle (900, 901); before that: Offset Paths' Copy Offset arrives as EffectCraft's (After Effects' value minus 1, 828); before that: project settings, image sequences, conformed clips and effect instance names are imported, next to the mattes, shapes, text settings and animators, effects, markers, time remapping, cameras and lights); before that: parallel and ambient lights (701, 702) and keyed Orientation (703) are imported; before that: masks on text and shape layers (705, 706: AE vs EffectCraft render 12 and 0 of 5184 points, glyph edges) and Merge Paths, Offset Paths, Repeater (707-710, 731; merge renders equal but for edges; Repeater copy opacity and Offset Paths' outline differ in EffectCraft's renderer) are imported; before that: keyframes: the ease of Anchor Point, effect point, effect colour and mask path keys is imported (597-599, 700, 730: within 0.5 px of After Effects' read-backs); before that: effects: Directional Blur, Radial Blur, CC Radial Blur, Venetian Blinds, Channel Blur, Black & White, Tritone, Luma Key, Simple Choker, Matte Choker and Transform are imported (711-723; render checks: CC Radial Blur and Channel Blur equal, Directional Blur within 5/255; Venetian Blinds, Radial Blur, Black & White (8/255), Tritone (19/255), Luma Key, Matte Choker and Transform differ in EffectCraft's renderer, see STATUS); before that: text: character and paragraph settings (stroke, scales, baseline shift, kerning, ligatures, tsume, indents, spacing, justified text, composer, direction, vertical text; 538-578) and text animators with range selectors (579-594, 114) are imported; render checks 594 (keyed range selector at 0 / 0.5 / 1 / 1.5 / 2.5 s), 595, 596 equal but for glyph edges; before that: cameras, spot and point lights, X / Y Rotation and Orientation, Timewarp and expressions on effect parameters are imported (render checks 486, 535-537 equal but for edges; 488 differs by 5.25 %, cause in EffectCraft's renderer not isolated); before that: text: superscript and subscript are imported (526-528); before that: effects: Invert, Fast Box Blur, Gaussian Blur, Drop Shadow, Glow, Fill, Hue/Saturation, Levels and five expression controls are imported, popups are mapped by item name, checkbox defaults come from the file; before that: shape layers are imported (groups, paths, paints, trim paths, round corners; 451-484, 519 added); before that: markers and Time Remapping are imported (509, 510 added); before that: track mattes are imported (402-408); before that: text: automatic leading is verified (400); effects: Exposure is imported (Channels, all twelve sliders, Bypass, keys), next to Tint and Gradient Ramp; before that: text: U+0003 is a paragraph break (386, 387); before that: a stored text Anchor Point is pixels (385, now V); before that: effects: Tint and Gradient Ramp are imported (all parameters and keys), other effects stay reported; `.aepx` is accepted; text layers are imported (Source Text with style runs, paragraphs and box text; fonts by PostScript name, missing fonts listed); layer styles are reported; before that: layer masks · **Target:** Adobe After Effects 2026 +> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-11 · **Change:** an effect without a counterpart arrives as a placeholder with its parameters, values, keys and expressions; it renders nothing and is still reported (#3087); before that: dropped projects and projects picked in File ▸ Import ▸ File… import as projects, several asked about one at a time; `file.import` hands them to `file.importAep`; the menu entries are named Adobe After Effects Project… (#3103); before that: After Effects' Puppet arrives as EffectCraft's Puppet without its meshes and pins, which are reported mesh by mesh (#3093; the storage is not sampled yet, aep-format 3.7); before that: Lumetri Color's master RGB curve, Hue vs Sat curve and colour wheels are imported (1200 presets made by hand); before that: Lumetri Color is imported (1200: every slider, checkbox and popup with a counterpart, by match name, also from records in the default state; switched-off sections, LUTs, looks, undecoded curves and wheels are reported); before that: the report names the After Effects version a file is written for and the one that wrote it (`aeVersion`); copies saved as 25.x and 24.x import like the 2026 save; before that: Curves and Mesh Warp are imported (961-965, 985; FORMAT S of the corpus); before that: a shape item's eye switch is imported (bit 0 of its group flags, 986 / 987: a switched-off Fill under Trim Paths is no longer drawn, render equal to After Effects), and a layer style's (switch group `tdsb` 0, 988); before that: a negative time stretch (Time Reverse Layer) is imported: in and out point in order, the layer plays backwards (981-983: render equal to After Effects at 7 points); before that: After Effects' None on Compound Blur, Displacement Map and Set Matte arrives as an explicit None (`NO_LAYER`), not as the owning layer; before that: layer styles are imported (the nine styles and Blending Options, 951-979; Global Light becomes the composition's); before that: the 27 effects of round 3 are in the table (`effectcraft_aep::effect_map`); before that: a layer of a clip, sequence or sound ends at its source's end (After Effects ends it there when it opens a project, read-back test f1), unless it is remapped or looped or runs less than a frame past; before that: keys of shape colours are read (the reader took their 152-byte spatial records for plain ones: `tdb4` byte 7 is 0 there, 854); before that: the effect table moved to `effectcraft_aep::effect_map`; point defaults in percent and a popup default slot of 0 (After Effects' save of a project it opened, e1 / e2 re-saves) are read; before that: the justification of right-to-left paragraphs is read relative to the direction (t7); before that: 24 more layer blend modes (906, 907); before that: 27 more effects are imported (batch 6: 903-905), with layer parameters; before that: a Rec. 709 working space also sets the output space (After Effects renders in the working space, 902); before that: a mask whose path was never set arrives as the source rectangle (900, 901); before that: Offset Paths' Copy Offset arrives as EffectCraft's (After Effects' value minus 1, 828); before that: project settings, image sequences, conformed clips and effect instance names are imported, next to the mattes, shapes, text settings and animators, effects, markers, time remapping, cameras and lights); before that: parallel and ambient lights (701, 702) and keyed Orientation (703) are imported; before that: masks on text and shape layers (705, 706: AE vs EffectCraft render 12 and 0 of 5184 points, glyph edges) and Merge Paths, Offset Paths, Repeater (707-710, 731; merge renders equal but for edges; Repeater copy opacity and Offset Paths' outline differ in EffectCraft's renderer) are imported; before that: keyframes: the ease of Anchor Point, effect point, effect colour and mask path keys is imported (597-599, 700, 730: within 0.5 px of After Effects' read-backs); before that: effects: Directional Blur, Radial Blur, CC Radial Blur, Venetian Blinds, Channel Blur, Black & White, Tritone, Luma Key, Simple Choker, Matte Choker and Transform are imported (711-723; render checks: CC Radial Blur and Channel Blur equal, Directional Blur within 5/255; Venetian Blinds, Radial Blur, Black & White (8/255), Tritone (19/255), Luma Key, Matte Choker and Transform differ in EffectCraft's renderer, see STATUS); before that: text: character and paragraph settings (stroke, scales, baseline shift, kerning, ligatures, tsume, indents, spacing, justified text, composer, direction, vertical text; 538-578) and text animators with range selectors (579-594, 114) are imported; render checks 594 (keyed range selector at 0 / 0.5 / 1 / 1.5 / 2.5 s), 595, 596 equal but for glyph edges; before that: cameras, spot and point lights, X / Y Rotation and Orientation, Timewarp and expressions on effect parameters are imported (render checks 486, 535-537 equal but for edges; 488 differs by 5.25 %, cause in EffectCraft's renderer not isolated); before that: text: superscript and subscript are imported (526-528); before that: effects: Invert, Fast Box Blur, Gaussian Blur, Drop Shadow, Glow, Fill, Hue/Saturation, Levels and five expression controls are imported, popups are mapped by item name, checkbox defaults come from the file; before that: shape layers are imported (groups, paths, paints, trim paths, round corners; 451-484, 519 added); before that: markers and Time Remapping are imported (509, 510 added); before that: track mattes are imported (402-408); before that: text: automatic leading is verified (400); effects: Exposure is imported (Channels, all twelve sliders, Bypass, keys), next to Tint and Gradient Ramp; before that: text: U+0003 is a paragraph break (386, 387); before that: a stored text Anchor Point is pixels (385, now V); before that: effects: Tint and Gradient Ramp are imported (all parameters and keys), other effects stay reported; `.aepx` is accepted; text layers are imported (Source Text with style runs, paragraphs and box text; fonts by PostScript name, missing fonts listed); layer styles are reported; before that: layer masks · **Target:** Adobe After Effects 2026 File ▸ Import ▸ Adobe After Effects Project… (`file.importAep`) reads an `.aep` or its XML form `.aepx` and adds its items to the open project, in a folder named after the file (as After Effects does when it imports a project). @@ -318,6 +318,22 @@ parameter gets the file's value: `approximated_keyframes`. - **The fx switch** of each instance (the `tdsb` of its value group: 1 on, 0 off; `fx-switch.aep`) is imported and exported, and so is an expression on a stored effect parameter (its text and its switch). +- **Effects without a counterpart** (third-party plug-ins, pseudo effects of expression controls, + `Pseudo/…`) arrive as **placeholders** (#3087): an effect group whose effect id is the After + Effects match name. Like a missing plug-in it renders nothing and is listed by Find Missing + Effects. It holds the effect's parameters flat (without the twirl-down group markers), named as + in After Effects, each with its value, keys and expression, in the units After Effects' + expressions read (sliders and angles as stored, points in layer pixels, colours, checkboxes, + popups over the file's items with separators, read 1-based; layer parameters name their layer, + without a record the layer itself as for Layer Control), + so expressions that read them (`effect("Settings")("Speed")`) keep working. A parameter's id is + its match name (`CC Cylinder-0003`), or `param` when that name is no path segment (a + pseudo effect's `Pseudo/0.25-0001`). Paths and arbitrary data are not kept; a popup whose + definition is borrowed, or whose default slot holds no item, and that has no value record takes + its first item (reported). One import keeps at + most 200 000 placeholder parameters and popup items (a popup at most 1024 items); the rest is + reported. A placeholder is still reported in `effects` and counted in + `imported.placeholderEffects`; .aep export reports it and leaves it out. ## What is reported @@ -327,7 +343,7 @@ parameter gets the file's value: | Category | Counted | |---|---| -| `effects` | each effect on an imported layer that is not in the table (by name and match name); for an imported effect: each stored parameter outside the table, a parameter whose type or valid maximum differs from the table, keys or an expression on a layer parameter, an effect without readable parameter definitions | +| `effects` | each effect on an imported layer that is not in the table (by name and match name; it arrives as a placeholder, "kept without rendering", unless it has no readable parameter definitions); for an imported effect: each stored parameter outside the table, a parameter whose type or valid maximum differs from the table, keys or an expression on a layer parameter, an effect without readable parameter definitions | | `masks` | a mask that is not imported because its path cannot be used (a Mask Path entry without shapes, a mask on a text or shape layer whose path was never set (its default is not sampled), unreadable, no vertices, a point count that is not a multiple of three, more than 65 536 vertices, numbers that are not finite), a mask mode code outside the seven known ones (imported as Add) | | `layer_styles` | per layer: a style in switch state 3 (not sampled; state 0 is imported as a style switched off, 988), Pattern Overlay, an unknown style or parameter, a gradient (`GCst`, not decoded: EffectCraft's default gradient stays), keys on a popup or checkbox, a value that does not fit, styles on a layer that takes none here (adjustment, camera, light) | | `markers` | a marker with an unknown cue type (imported as an event cue) | From e2e341301120de3393798c2b952a3ac090a207e5 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 11 Nov 2026 16:21:47 +0530 Subject: [PATCH 06/83] #3087: an item made from one Photoshop layer shows that layer Footage made from one layer of a layered .psd showed the whole document and was named after the file. Its opti (tag 8BPS) stores the layer: the record index (BE i32 at 14, -1 for the merged image), the bounds (LE i32 at 78-93) and the name (UTF-8 at 344). The item now shows that layer as EffectCraft's own Photoshop import does (at its own size with Retain Layer Sizes), named /. A layer without pixels (an adjustment layer) keeps the merged image and is reported. --- crates/aep/src/container.rs | 2 +- crates/aep/src/container/footage.rs | 78 ++++++++++++++++++++- crates/aep/src/import/build.rs | 28 +++++++- crates/aep/src/import/report.rs | 3 +- crates/aep/src/lib.rs | 8 +-- crates/aep/tests/it/container/robustness.rs | 1 + crates/aep/tests/it/import/synthetic.rs | 65 +++++++++++++++++ docs/aep-format.md | 3 +- docs/aep-import.md | 6 +- 9 files changed, 180 insertions(+), 14 deletions(-) diff --git a/crates/aep/src/container.rs b/crates/aep/src/container.rs index 531d74843..77511fcf1 100644 --- a/crates/aep/src/container.rs +++ b/crates/aep/src/container.rs @@ -44,7 +44,7 @@ pub use camera::{CameraPosition, DEFAULT_CAMERA_ZOOM}; pub use chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk}; pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue}; pub use error::AepError; -pub use footage::{Footage, SequenceInfo}; +pub use footage::{Footage, PsdLayer, SequenceInfo}; pub use header::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Quality, Rational, Renderer}; pub use keys::{ExpressionFlags, Interpolation, KeyEase, KeyframeKind, SpatialKey}; pub use masks::{Mask, MaskAtom, MaskMode, PathVertex, ShapePath}; diff --git a/crates/aep/src/container/footage.rs b/crates/aep/src/container/footage.rs index da0369d64..7a3782d79 100644 --- a/crates/aep/src/container/footage.rs +++ b/crates/aep/src/container/footage.rs @@ -1,7 +1,7 @@ //! Item ids and labels, footage items (solids and files), precomp linkage, and the name and size //! of a layer's source. -use crate::container::bytes::{be_f32, be_f64, be_u32, cstr, le_u32, text}; +use crate::container::bytes::{be_f32, be_f64, be_i32, be_u32, cstr, le_u32, text, until_nul}; use crate::container::chunk::Chunk; use crate::container::header::Rational; use crate::container::typed::{Item, ItemKind, Layer, Project}; @@ -45,6 +45,48 @@ pub struct Footage { /// True when the alias points at a folder (`"target_is_folder":true`): an image sequence is ONE /// item whose alias is its folder and whose `opti` holds the first file name. pub is_sequence: bool, + /// The one layer of a Photoshop file the item shows; `None` for the merged image and for + /// any other footage. + pub psd_layer: Option, +} + +/// One layer of a Photoshop file shown by a footage item, from its `opti` (tag `8BPS`, +/// docs/aep-format.md 3.3): the layer record's index as a big-endian `i32` at byte 14 (-1 for the +/// merged image), its bounds top, left, bottom, right as little-endian `i32` at 78, 82, 86 and +/// 90, and its name (UTF-8, NUL terminated) from byte 344. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PsdLayer { + /// The layer record's position in the file (bottom of the stack = 0). + pub index: u32, + pub name: String, + /// Top, left, bottom, right in document pixels; all 0 for a layer without pixels (an + /// adjustment layer). + pub bounds: [i32; 4], +} + +/// Most bytes of a Photoshop layer name read. +const MAX_NAME: usize = 1024; + +impl PsdLayer { + /// The bounds' width and height; `None` when they are empty. + pub fn size(&self) -> Option<(u32, u32)> { + let [top, left, bottom, right] = self.bounds; + let w = u32::try_from(i64::from(right) - i64::from(left)).ok().filter(|w| *w > 0)?; + let h = u32::try_from(i64::from(bottom) - i64::from(top)).ok().filter(|h| *h > 0)?; + Some((w, h)) + } + + /// The layer an `opti` names; `None` for another tag, the merged image or a cut record. + fn read(opti: &[u8]) -> Option { + if opti.get(..4) != Some(&b"8BPS"[..]) { + return None; + } + let index = u32::try_from(be_i32(opti, 14)?).ok()?; + let le_i32 = |at| le_u32(opti, at).map(|v| i32::from_le_bytes(v.to_le_bytes())); + // (After Effects writes 602 bytes; a longer hostile name is cut.) + let name = opti.get(344..).map(|b| text(until_nul(b.get(..MAX_NAME).unwrap_or(b)))).unwrap_or_default(); + Some(Self { index, name, bounds: [le_i32(78)?, le_i32(82)?, le_i32(86)?, le_i32(90)?] }) + } } impl Footage { @@ -330,6 +372,7 @@ impl<'f, 'a> Item<'f, 'a> { file_size: be_u32(sspc, 208).unwrap_or(0), audio_sample_rate: be_f64(sspc, 160).filter(|r| r.is_finite() && *r > 0.0), is_sequence, + psd_layer: PsdLayer::read(opti), }) } @@ -370,7 +413,38 @@ impl<'f, 'a> Project<'f, 'a> { #[cfg(test)] mod tests { - use super::json_string; + use super::{PsdLayer, json_string}; + + /// A 602-byte Photoshop `opti` naming layer `index` with `bounds` and `name`. + fn opti(index: i32, bounds: [i32; 4], name: &[u8]) -> Vec { + let mut b = vec![0u8; 602]; + b[..4].copy_from_slice(b"8BPS"); + b[14..18].copy_from_slice(&index.to_be_bytes()); + for (i, v) in bounds.iter().enumerate() { + b[78 + 4 * i..82 + 4 * i].copy_from_slice(&v.to_le_bytes()); + } + b[344..344 + name.len()].copy_from_slice(name); + b + } + + #[test] + fn a_photoshop_layer_reads_its_index_bounds_and_name() { + let l = PsdLayer::read(&opti(7, [749, 800, 764, 848], "tést".as_bytes())).unwrap(); + assert_eq!((l.index, l.name.as_str(), l.bounds, l.size()), (7, "tést", [749, 800, 764, 848], Some((48, 15)))); + // The merged image, another tag, a cut record: no layer. + assert_eq!(PsdLayer::read(&opti(-1, [0; 4], b"x")), None); + let mut other = opti(1, [0; 4], b"x"); + other[..4].copy_from_slice(b"Soli"); + assert_eq!(PsdLayer::read(&other), None); + assert_eq!(PsdLayer::read(&opti(1, [0; 4], b"x")[..80]), None); + // A cut name, and no name at all. + assert_eq!(PsdLayer::read(&opti(1, [0; 4], b"x")[..345]).unwrap().name, "x"); + assert_eq!(PsdLayer::read(&opti(1, [0; 4], b"x")[..300]).unwrap().name, ""); + // A layer without pixels has no size; extreme bounds do not overflow. + assert_eq!(PsdLayer::read(&opti(2, [0; 4], b"")).unwrap().size(), None); + assert_eq!(PsdLayer::read(&opti(2, [i32::MIN, i32::MIN, i32::MAX, i32::MAX], b"")).unwrap().size(), Some((u32::MAX, u32::MAX))); + assert_eq!(PsdLayer::read(&opti(2, [i32::MAX, 0, i32::MIN, 1], b"")).unwrap().size(), None); + } #[test] fn reads_a_string_with_escapes() { diff --git a/crates/aep/src/import/build.rs b/crates/aep/src/import/build.rs index 7d5b902f1..9da8bb39a 100644 --- a/crates/aep/src/import/build.rs +++ b/crates/aep/src/import/build.rs @@ -12,7 +12,8 @@ use effectcraft_color::{BlendMode, Label}; use effectcraft_keyframe::Value; use effectcraft_project::build::{self, Ids}; use effectcraft_project::{ - AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, TrackMatte, + AutoOrient, Comp, Footage, FootageKind, ItemId, ItemKind, Layer, LayerId, LayerSource, LightKind, MatteKind, Project, Quality, Solid, SourceLayer, + TrackMatte, }; use effectcraft_time::Tick; @@ -216,7 +217,17 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_ let aep_id = item.id(); // An item without a stored name shows its file's name, a sequence `shot_[0101-0103].exr` // (126, 603-607). - let name = if name.is_empty() { default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string()) } else { name }; + // One layer of a Photoshop file is `/`, as EffectCraft's own Photoshop import + // names it (#3087). + let name = if name.is_empty() { + let file = default_footage_name(item, &f).unwrap_or_else(|| "Footage".to_string()); + match &f.psd_layer { + Some(l) if !l.name.is_empty() => format!("{}/{file}", l.name), + _ => file, + } + } else { + name + }; if f.is_solid { // A null object's placeholder solid is not an item here. if aep_id.is_some_and(|i| null_only.contains(&i)) { @@ -299,6 +310,7 @@ fn import_footage(project: &mut Project, cx: &mut Ctx<'_>, item: &AepItem<'_, '_ missing: !present, placed_page, sequence, + layer: source_layer(&f, &name, &mut cx.col), ..Footage::default() }; // The native frame rate and the stored duration of sequences and clips (352, 603, 606). @@ -338,6 +350,18 @@ fn is_placed_page_path(path: &str) -> bool { matches!(ext.as_deref(), Some("pdf" | "ai")) } +/// The Photoshop layer a footage item shows (#3087): at its own bounds when the item is as big +/// as they are (Retain Layer Sizes), else on the document. A layer without pixels (an adjustment +/// layer) keeps the merged image and is reported. +fn source_layer(f: &crate::Footage, name: &str, col: &mut Collector) -> Option { + let l = f.psd_layer.as_ref()?; + let Some(size) = l.size() else { + col.lose(LossCategory::UnsupportedItems, format!("footage '{name}': a Photoshop layer without pixels (an adjustment layer), the merged image used")); + return None; + }; + Some(SourceLayer { index: l.index, name: l.name.clone(), layer_size: size == (f.width, f.height), ..SourceLayer::default() }) +} + /// The name After Effects shows for a footage item that stores none: the file's name, or for a /// sequence the name with the frame range (`shot_[0101-0103].exr`). fn default_footage_name(item: &AepItem<'_, '_>, f: &crate::Footage) -> Option { diff --git a/crates/aep/src/import/report.rs b/crates/aep/src/import/report.rs index 2825b61b3..454b2991b 100644 --- a/crates/aep/src/import/report.rs +++ b/crates/aep/src/import/report.rs @@ -56,7 +56,8 @@ pub enum LossCategory { /// Layers that could not be imported for another reason (unknown layer type, missing or /// unsupported source, precomposition loop). UnsupportedLayers, - /// Project items of a kind that is not imported. + /// Project items of a kind that is not imported, and items made from a Photoshop layer + /// without pixels (they show the merged image). UnsupportedItems, /// Data that could not be read (damaged headers, unreadable keyframes). DamagedData, diff --git a/crates/aep/src/lib.rs b/crates/aep/src/lib.rs index 4bcdbab9e..cb4b9ff60 100644 --- a/crates/aep/src/lib.rs +++ b/crates/aep/src/lib.rs @@ -20,8 +20,8 @@ pub use container::{ GradientType, HueSaturationData, Interpolation, Item, ItemKind, Justification, KernRun, KeyEase, KeyLayout, KeyList, Keyframe, KeyframeKind, LIST, Layer, LayerHeader, LayerRef, LayerType, LevelsData, LightType, Limits, ListHeader, Marker, Mask, MaskAtom, MaskMode, MatteMode, MeshData, NESTED_IDS, Orientation, OrientationKey, ParagraphRun, ParamKind, ParamValue, PathVertex, PolystarType, Project, ProjectSettings, PropEntry, PropGroup, PropNode, - Property, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin, StyleRun, - TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk, WorkingSpace, - curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx, read_aepx_with_limits, style_map, - write, write_to, + Property, PsdLayer, Quality, Rational, Renderer, SequenceInfo, ShapeDetail, ShapeGroup, ShapeItem, ShapePath, SpatialKey, Stroke, StrokeCap, StrokeJoin, + StyleRun, TextBox, TextDocument, TextValue, TimeBase, TimeDisplay, TimeRemap, TimeRemapKey, TrackMatte, Tracked, Transform, ValueSource, Walk, + WorkingSpace, curve_lut, effect_map, identifier_channel_type, is_aepx, parse, parse_any, parse_text_dict, parse_with_limits, read_aepx, + read_aepx_with_limits, style_map, write, write_to, }; diff --git a/crates/aep/tests/it/container/robustness.rs b/crates/aep/tests/it/container/robustness.rs index 5c3422a10..0c887b8c4 100644 --- a/crates/aep/tests/it/container/robustness.rs +++ b/crates/aep/tests/it/container/robustness.rs @@ -720,6 +720,7 @@ fn extreme_values_in_the_batch_3_fields() { file_size: 0, audio_sample_rate: None, is_sequence: true, + psd_layer: None, }; for (num, den, rate) in [(3i64, 30i64, 30u32), (3, 0, 30), (-3, 30, 30), (i64::MAX, 1, u32::MAX), (i64::MIN, -1, u32::MAX), (1, i64::MAX, 1), (0, 1, 0)] { let f = Footage { duration: Some(Rational { num, den }), native_frame_rate: rate, ..base.clone() }; diff --git a/crates/aep/tests/it/import/synthetic.rs b/crates/aep/tests/it/import/synthetic.rs index 8e4c28f16..f1c36110c 100644 --- a/crates/aep/tests/it/import/synthetic.rs +++ b/crates/aep/tests/it/import/synthetic.rs @@ -842,3 +842,68 @@ fn a_default_state_colour_record_holds_the_value() { assert_eq!(colour(&default_state), colour(&written)); assert_ne!(colour(&default_state), colour(&unchanged), "the recorded colour, not the default"); } + +/// The project with its png item made one layer of a Photoshop file `art.psd`: the `opti` of +/// docs/aep-format.md 3.3 (tag `8BPS`, the layer index at 14, its bounds at 78-94, its name at +/// 344) and the item `size` big. +fn as_psd_layer(index: i32, bounds: [i32; 4], name: &str, size: (u32, u32)) -> Vec { + let mut opti = vec![0u8; 602]; + opti[..4].copy_from_slice(b"8BPS"); + opti[14..18].copy_from_slice(&index.to_be_bytes()); + for (i, v) in bounds.iter().enumerate() { + opti[78 + 4 * i..82 + 4 * i].copy_from_slice(&v.to_le_bytes()); + } + opti[344..344 + name.len()].copy_from_slice(name.as_bytes()); + let alias = br#"{"fullpath":"C:\\x\\art.psd","platform":1,"target_is_folder":false}"#.to_vec(); + mutate(&mut |c| { + if !c.is_list(b"Pin ") { + return; + } + let Body::List { children, .. } = &mut c.body else { return }; + if !children.iter().any(|k| k.is(b"opti") && k.bytes().is_some_and(|d| d.get(..4) == Some(&b"png!"[..]))) { + return; + } + // No sequence naming between the alias and the `opti`. + children.retain(|k| k.is(b"sspc") || k.is(b"opti") || k.is_list(b"Als2")); + for k in children.iter_mut() { + if k.is(b"opti") { + k.body = Body::Data(opti.clone().into()); + } else if k.is(b"sspc") { + set_data(k, 30, &size.0.to_be_bytes()); + set_data(k, 34, &size.1.to_be_bytes()); + } + } + visit(children, &mut |k| { + if k.is(b"alas") { + k.body = Body::Data(alias.clone().into()); + } + }); + }) +} + +/// #3087: an item made from one layer of a Photoshop file shows that layer, named +/// `/`; it showed the whole document, named after the file. Item as big as the layer: +/// Retain Layer Sizes; as big as the document: the layer on the document. +#[test] +fn a_photoshop_layer_item_shows_its_layer() { + for (size, layer_size) in [((48, 15), true), ((1000, 1000), false)] { + let (p, r) = run(&as_psd_layer(7, [749, 800, 764, 848], "Tëst", size), true); + r.unwrap(); + let (name, f) = p.items.values().find_map(|i| if let ItemKind::Footage(f) = &i.kind { Some((i.name.clone(), f.clone())) } else { None }).unwrap(); + assert_eq!(name, "Tëst/art.psd"); + let l = f.layer.expect("the layer"); + assert_eq!((l.index, l.name.as_str(), l.layer_size, (f.width, f.height)), (7, "Tëst", layer_size, size)); + } +} + +/// #3087: a Photoshop layer without pixels (an adjustment layer) keeps the merged image and is +/// reported; the merged image itself (index -1) is no layer. +#[test] +fn a_photoshop_layer_without_pixels_keeps_the_merged_image() { + let (p, r) = run(&as_psd_layer(4, [0; 4], "Levels 1", (1000, 1000)), true); + let found = losses(&r.unwrap(), LossCategory::UnsupportedItems); + assert!(found.iter().any(|d| d.contains("'Levels 1/art.psd'") && d.contains("without pixels")), "{found:?}"); + assert_eq!(the_footage(&p).layer, None); + let (p, _) = run(&as_psd_layer(-1, [0; 4], "", (1000, 1000)), true); + assert_eq!(the_footage(&p).layer, None); +} diff --git a/docs/aep-format.md b/docs/aep-format.md index 8830a869e..2b4dae27f 100644 --- a/docs/aep-format.md +++ b/docs/aep-format.md @@ -1,6 +1,6 @@ # After Effects project format (`.aep`) -> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-07 · **Change:** Puppet (`ADBE FreePin3`, 3.7): the property tree from an external scripting listing, **?** until a byte sample exists (#3093); before that: footage: an image sequence without a filename prefix stores only the suffix `Utf8`, and one imported with Force alphabetical order stores its file list in `LIST StVc` / `StVS` (section 3, footage); before that: versions: `svap` is the version that wrote the file, `head` bytes 4 to 7 the version it is written for, and what a Save a Copy As 25.x / 24.x of After Effects 2026 changes (section 1, "Versions"); before that: the stretch numerator is signed (a negative one reverses the layer, 981-983); layer styles (3.12b, 950-980); before that: footage: `sspc@118` of an image sequence is its folder's modification time (860, read-back x1-x3); before that: text: paragraph `/24`, `/35` and style `/68` are neutral for 0 and 1 (732-734, edited in place); before that: keyframes: the ease of mask path keys (599, 700), the spatial speed unit of fractional values (597, 598, 730); before that: text: character and paragraph settings, manual kerning, vertical text, `/nil` is neutral (S17: 538-578, 595, 596); before that: cameras, lights and 3D rotations (S16: the auto Position of a two-node camera is where After Effects renders it, 537; camera and light defaults read back 255, 256; Orientation `otst/otda` 488), Timewarp (529-533), an expression on an effect parameter (534); before that: text: style slot /13 is superscript / subscript (526-528; every scripted text of the corpus is superscript), wrapping box text 517; before that: effects of batch 5 (409-450, 511-516: integer sliders, checkbox defaults in `pard`, arbitrary data of Hue/Saturation and Levels, the parameters of Invert, Fast Box Blur, Gaussian Blur, Drop Shadow, Glow; section 3.7); before that: shape items of batch 5 (451-484, 519: ellipse, fill and stroke opacity, fill rule, group transform, shape layer anchor, trim paths, rectangle roundness, polystar fields, gradient default, nested groups, the defaults of every item; section 3.9); before that: track mattes: mode at `ldta` byte 107 and the matte layer id at byte 160 (cases 402-408, section 3.1); before that: text: automatic leading is verified (400); Exposure (`ADBE Exposure2`, cases 389-397): group start / end parameter types 13 / 14, float slider valid minimum and slider range (section 3.7); before that: text: U+0003 is a paragraph break (386, 387); before that: a stored text Anchor Point is pixels (385, now V); before that: the XML form `.aepx` is read into the same chunk tree (section 1, "The XML form"); the `head` save counter is a `u32` at byte 16; text documents for the importer (stroke colour, automatic leading, the font of each run, the undecoded-slot check, the text-layer Anchor Point, the Source Text record); before that: third round of verified field layouts (explicit-default semantics, type-major bezier ease, exact time stretch and in / out points, Time Remapping state, comp pixel aspect / shutter phase / display start, Point default, Layer Control None, dropdown selection, one `mkif` per mask, polystar and radial gradient records, text styles, camera and light options, marker cue data, audio and image-sequence footage) added to the typed view of `effectcraft-aep` · **Target:** Adobe After Effects 2026 +> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-11 · **Change:** footage: the Photoshop layer an item shows (`opti` tag `8BPS`, section 3.3, issue 3087); before that: Puppet (`ADBE FreePin3`, 3.7): the property tree from an external scripting listing, **?** until a byte sample exists (#3093); before that: footage: an image sequence without a filename prefix stores only the suffix `Utf8`, and one imported with Force alphabetical order stores its file list in `LIST StVc` / `StVS` (section 3, footage); before that: versions: `svap` is the version that wrote the file, `head` bytes 4 to 7 the version it is written for, and what a Save a Copy As 25.x / 24.x of After Effects 2026 changes (section 1, "Versions"); before that: the stretch numerator is signed (a negative one reverses the layer, 981-983); layer styles (3.12b, 950-980); before that: footage: `sspc@118` of an image sequence is its folder's modification time (860, read-back x1-x3); before that: text: paragraph `/24`, `/35` and style `/68` are neutral for 0 and 1 (732-734, edited in place); before that: keyframes: the ease of mask path keys (599, 700), the spatial speed unit of fractional values (597, 598, 730); before that: text: character and paragraph settings, manual kerning, vertical text, `/nil` is neutral (S17: 538-578, 595, 596); before that: cameras, lights and 3D rotations (S16: the auto Position of a two-node camera is where After Effects renders it, 537; camera and light defaults read back 255, 256; Orientation `otst/otda` 488), Timewarp (529-533), an expression on an effect parameter (534); before that: text: style slot /13 is superscript / subscript (526-528; every scripted text of the corpus is superscript), wrapping box text 517; before that: effects of batch 5 (409-450, 511-516: integer sliders, checkbox defaults in `pard`, arbitrary data of Hue/Saturation and Levels, the parameters of Invert, Fast Box Blur, Gaussian Blur, Drop Shadow, Glow; section 3.7); before that: shape items of batch 5 (451-484, 519: ellipse, fill and stroke opacity, fill rule, group transform, shape layer anchor, trim paths, rectangle roundness, polystar fields, gradient default, nested groups, the defaults of every item; section 3.9); before that: track mattes: mode at `ldta` byte 107 and the matte layer id at byte 160 (cases 402-408, section 3.1); before that: text: automatic leading is verified (400); Exposure (`ADBE Exposure2`, cases 389-397): group start / end parameter types 13 / 14, float slider valid minimum and slider range (section 3.7); before that: text: U+0003 is a paragraph break (386, 387); before that: a stored text Anchor Point is pixels (385, now V); before that: the XML form `.aepx` is read into the same chunk tree (section 1, "The XML form"); the `head` save counter is a `u32` at byte 16; text documents for the importer (stroke colour, automatic leading, the font of each run, the undecoded-slot check, the text-layer Anchor Point, the Source Text record); before that: third round of verified field layouts (explicit-default semantics, type-major bezier ease, exact time stretch and in / out points, Time Remapping state, comp pixel aspect / shutter phase / display start, Point default, Layer Control None, dropdown selection, one `mkif` per mask, polystar and radial gradient records, text styles, camera and light options, marker cue data, audio and image-sequence footage) added to the typed view of `effectcraft-aep` · **Target:** Adobe After Effects 2026 What `crates/aep` ([`effectcraft-aep`](../crates/aep/README.md)) reads and writes, and the evidence for each statement. Everything here was observed on project files we generated ourselves; no @@ -263,6 +263,7 @@ property of `L` after 229 and 230). The corpus manifest calls the classic render | footage size | `Pin /sspc` | 30, 34 | u32, u32 | width, height in pixels | 000 (1920 x 1080), 022 (100 x 100 null), 126 (8 x 8), 211, 212, 259 | V | | footage name | `Pin /opti` | 26 (solid), 58 (file) | ASCII, NUL terminated | the item's own `Utf8` name is empty for footage | 000 (`L`), 022 (`Null 1`), 126 (`test8x8.png`), 211 (`S100`), 259 (`Blue`) | V | | **solid colour** | `Pin /opti` | 10, 14, 18, 22 | 4 x f32 | ARGB, 0..1: red [1, 0, 0] is `1, 1, 0, 0`, blue [0, 0, 1] is `1, 0, 0, 1` | 000, 259 | V | +| **Photoshop layer** | `Pin /opti` (tag `8BPS`) | 14; 78, 82, 86, 90; 344 | i32 BE; 4 x i32 **LE**; UTF-8, NUL terminated | an item made from one layer of a `.psd`: the layer record's index in the file (bottom of the stack = 0; -1 is the merged image), the layer's bounds top, left, bottom, right in document pixels (all 0 for a layer without pixels, such as an adjustment layer) and the layer's name. The item's size (`sspc` 30 / 34) is the bounds' size with Retain Layer Sizes, else the document's. `Footage::psd_layer` | the project of issue 3087: ten layers, each index, bounds and name equal to the `.psd`'s layer record at that position (`Layer 1` `[9, -346, 1083, 1086]`, item 1432 x 1074; `test` `[749, 800, 764, 848]`, item 48 x 15) | V | | file path | `Pin /Als2/alas` | key `fullpath` | JSON string | alias JSON of a file footage item | 126 (the fixture holds a neutral path) | V | | precomp linkage | `Layr/ldta` | 40 | u32 | the layer's source id is the id of the precomp's item | 124 | V | diff --git a/docs/aep-import.md b/docs/aep-import.md index c704e0a89..32e19fd42 100644 --- a/docs/aep-import.md +++ b/docs/aep-import.md @@ -1,6 +1,6 @@ # After Effects project import -> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-10 · **Change:** dropped projects and projects picked in File ▸ Import ▸ File… import as projects, several asked about one at a time; `file.import` hands them to `file.importAep`; the menu entries are named Adobe After Effects Project… (#3103); before that: After Effects' Puppet arrives as EffectCraft's Puppet without its meshes and pins, which are reported mesh by mesh (#3093; the storage is not sampled yet, aep-format 3.7); before that: Lumetri Color's master RGB curve, Hue vs Sat curve and colour wheels are imported (1200 presets made by hand); before that: Lumetri Color is imported (1200: every slider, checkbox and popup with a counterpart, by match name, also from records in the default state; switched-off sections, LUTs, looks, undecoded curves and wheels are reported); before that: the report names the After Effects version a file is written for and the one that wrote it (`aeVersion`); copies saved as 25.x and 24.x import like the 2026 save; before that: Curves and Mesh Warp are imported (961-965, 985; FORMAT S of the corpus); before that: a shape item's eye switch is imported (bit 0 of its group flags, 986 / 987: a switched-off Fill under Trim Paths is no longer drawn, render equal to After Effects), and a layer style's (switch group `tdsb` 0, 988); before that: a negative time stretch (Time Reverse Layer) is imported: in and out point in order, the layer plays backwards (981-983: render equal to After Effects at 7 points); before that: After Effects' None on Compound Blur, Displacement Map and Set Matte arrives as an explicit None (`NO_LAYER`), not as the owning layer; before that: layer styles are imported (the nine styles and Blending Options, 951-979; Global Light becomes the composition's); before that: the 27 effects of round 3 are in the table (`effectcraft_aep::effect_map`); before that: a layer of a clip, sequence or sound ends at its source's end (After Effects ends it there when it opens a project, read-back test f1), unless it is remapped or looped or runs less than a frame past; before that: keys of shape colours are read (the reader took their 152-byte spatial records for plain ones: `tdb4` byte 7 is 0 there, 854); before that: the effect table moved to `effectcraft_aep::effect_map`; point defaults in percent and a popup default slot of 0 (After Effects' save of a project it opened, e1 / e2 re-saves) are read; before that: the justification of right-to-left paragraphs is read relative to the direction (t7); before that: 24 more layer blend modes (906, 907); before that: 27 more effects are imported (batch 6: 903-905), with layer parameters; before that: a Rec. 709 working space also sets the output space (After Effects renders in the working space, 902); before that: a mask whose path was never set arrives as the source rectangle (900, 901); before that: Offset Paths' Copy Offset arrives as EffectCraft's (After Effects' value minus 1, 828); before that: project settings, image sequences, conformed clips and effect instance names are imported, next to the mattes, shapes, text settings and animators, effects, markers, time remapping, cameras and lights); before that: parallel and ambient lights (701, 702) and keyed Orientation (703) are imported; before that: masks on text and shape layers (705, 706: AE vs EffectCraft render 12 and 0 of 5184 points, glyph edges) and Merge Paths, Offset Paths, Repeater (707-710, 731; merge renders equal but for edges; Repeater copy opacity and Offset Paths' outline differ in EffectCraft's renderer) are imported; before that: keyframes: the ease of Anchor Point, effect point, effect colour and mask path keys is imported (597-599, 700, 730: within 0.5 px of After Effects' read-backs); before that: effects: Directional Blur, Radial Blur, CC Radial Blur, Venetian Blinds, Channel Blur, Black & White, Tritone, Luma Key, Simple Choker, Matte Choker and Transform are imported (711-723; render checks: CC Radial Blur and Channel Blur equal, Directional Blur within 5/255; Venetian Blinds, Radial Blur, Black & White (8/255), Tritone (19/255), Luma Key, Matte Choker and Transform differ in EffectCraft's renderer, see STATUS); before that: text: character and paragraph settings (stroke, scales, baseline shift, kerning, ligatures, tsume, indents, spacing, justified text, composer, direction, vertical text; 538-578) and text animators with range selectors (579-594, 114) are imported; render checks 594 (keyed range selector at 0 / 0.5 / 1 / 1.5 / 2.5 s), 595, 596 equal but for glyph edges; before that: cameras, spot and point lights, X / Y Rotation and Orientation, Timewarp and expressions on effect parameters are imported (render checks 486, 535-537 equal but for edges; 488 differs by 5.25 %, cause in EffectCraft's renderer not isolated); before that: text: superscript and subscript are imported (526-528); before that: effects: Invert, Fast Box Blur, Gaussian Blur, Drop Shadow, Glow, Fill, Hue/Saturation, Levels and five expression controls are imported, popups are mapped by item name, checkbox defaults come from the file; before that: shape layers are imported (groups, paths, paints, trim paths, round corners; 451-484, 519 added); before that: markers and Time Remapping are imported (509, 510 added); before that: track mattes are imported (402-408); before that: text: automatic leading is verified (400); effects: Exposure is imported (Channels, all twelve sliders, Bypass, keys), next to Tint and Gradient Ramp; before that: text: U+0003 is a paragraph break (386, 387); before that: a stored text Anchor Point is pixels (385, now V); before that: effects: Tint and Gradient Ramp are imported (all parameters and keys), other effects stay reported; `.aepx` is accepted; text layers are imported (Source Text with style runs, paragraphs and box text; fonts by PostScript name, missing fonts listed); layer styles are reported; before that: layer masks · **Target:** Adobe After Effects 2026 +> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-11 · **Change:** an item made from one layer of a Photoshop file shows that layer (#3087); before that: dropped projects and projects picked in File ▸ Import ▸ File… import as projects, several asked about one at a time; `file.import` hands them to `file.importAep`; the menu entries are named Adobe After Effects Project… (#3103); before that: After Effects' Puppet arrives as EffectCraft's Puppet without its meshes and pins, which are reported mesh by mesh (#3093; the storage is not sampled yet, aep-format 3.7); before that: Lumetri Color's master RGB curve, Hue vs Sat curve and colour wheels are imported (1200 presets made by hand); before that: Lumetri Color is imported (1200: every slider, checkbox and popup with a counterpart, by match name, also from records in the default state; switched-off sections, LUTs, looks, undecoded curves and wheels are reported); before that: the report names the After Effects version a file is written for and the one that wrote it (`aeVersion`); copies saved as 25.x and 24.x import like the 2026 save; before that: Curves and Mesh Warp are imported (961-965, 985; FORMAT S of the corpus); before that: a shape item's eye switch is imported (bit 0 of its group flags, 986 / 987: a switched-off Fill under Trim Paths is no longer drawn, render equal to After Effects), and a layer style's (switch group `tdsb` 0, 988); before that: a negative time stretch (Time Reverse Layer) is imported: in and out point in order, the layer plays backwards (981-983: render equal to After Effects at 7 points); before that: After Effects' None on Compound Blur, Displacement Map and Set Matte arrives as an explicit None (`NO_LAYER`), not as the owning layer; before that: layer styles are imported (the nine styles and Blending Options, 951-979; Global Light becomes the composition's); before that: the 27 effects of round 3 are in the table (`effectcraft_aep::effect_map`); before that: a layer of a clip, sequence or sound ends at its source's end (After Effects ends it there when it opens a project, read-back test f1), unless it is remapped or looped or runs less than a frame past; before that: keys of shape colours are read (the reader took their 152-byte spatial records for plain ones: `tdb4` byte 7 is 0 there, 854); before that: the effect table moved to `effectcraft_aep::effect_map`; point defaults in percent and a popup default slot of 0 (After Effects' save of a project it opened, e1 / e2 re-saves) are read; before that: the justification of right-to-left paragraphs is read relative to the direction (t7); before that: 24 more layer blend modes (906, 907); before that: 27 more effects are imported (batch 6: 903-905), with layer parameters; before that: a Rec. 709 working space also sets the output space (After Effects renders in the working space, 902); before that: a mask whose path was never set arrives as the source rectangle (900, 901); before that: Offset Paths' Copy Offset arrives as EffectCraft's (After Effects' value minus 1, 828); before that: project settings, image sequences, conformed clips and effect instance names are imported, next to the mattes, shapes, text settings and animators, effects, markers, time remapping, cameras and lights); before that: parallel and ambient lights (701, 702) and keyed Orientation (703) are imported; before that: masks on text and shape layers (705, 706: AE vs EffectCraft render 12 and 0 of 5184 points, glyph edges) and Merge Paths, Offset Paths, Repeater (707-710, 731; merge renders equal but for edges; Repeater copy opacity and Offset Paths' outline differ in EffectCraft's renderer) are imported; before that: keyframes: the ease of Anchor Point, effect point, effect colour and mask path keys is imported (597-599, 700, 730: within 0.5 px of After Effects' read-backs); before that: effects: Directional Blur, Radial Blur, CC Radial Blur, Venetian Blinds, Channel Blur, Black & White, Tritone, Luma Key, Simple Choker, Matte Choker and Transform are imported (711-723; render checks: CC Radial Blur and Channel Blur equal, Directional Blur within 5/255; Venetian Blinds, Radial Blur, Black & White (8/255), Tritone (19/255), Luma Key, Matte Choker and Transform differ in EffectCraft's renderer, see STATUS); before that: text: character and paragraph settings (stroke, scales, baseline shift, kerning, ligatures, tsume, indents, spacing, justified text, composer, direction, vertical text; 538-578) and text animators with range selectors (579-594, 114) are imported; render checks 594 (keyed range selector at 0 / 0.5 / 1 / 1.5 / 2.5 s), 595, 596 equal but for glyph edges; before that: cameras, spot and point lights, X / Y Rotation and Orientation, Timewarp and expressions on effect parameters are imported (render checks 486, 535-537 equal but for edges; 488 differs by 5.25 %, cause in EffectCraft's renderer not isolated); before that: text: superscript and subscript are imported (526-528); before that: effects: Invert, Fast Box Blur, Gaussian Blur, Drop Shadow, Glow, Fill, Hue/Saturation, Levels and five expression controls are imported, popups are mapped by item name, checkbox defaults come from the file; before that: shape layers are imported (groups, paths, paints, trim paths, round corners; 451-484, 519 added); before that: markers and Time Remapping are imported (509, 510 added); before that: track mattes are imported (402-408); before that: text: automatic leading is verified (400); effects: Exposure is imported (Channels, all twelve sliders, Bypass, keys), next to Tint and Gradient Ramp; before that: text: U+0003 is a paragraph break (386, 387); before that: a stored text Anchor Point is pixels (385, now V); before that: effects: Tint and Gradient Ramp are imported (all parameters and keys), other effects stay reported; `.aepx` is accepted; text layers are imported (Source Text with style runs, paragraphs and box text; fonts by PostScript name, missing fonts listed); layer styles are reported; before that: layer masks · **Target:** Adobe After Effects 2026 File ▸ Import ▸ Adobe After Effects Project… (`file.importAep`) reads an `.aep` or its XML form `.aepx` and adds its items to the open project, in a folder named after the file (as After Effects does when it imports a project). @@ -70,7 +70,7 @@ outside the sampled ones keeps the current value and is reported as `project set | Shape layers | groups (nested, with anchor, position, scale, skew, skew axis, rotation, opacity), rectangle (size, position, roundness), ellipse (size, position), polystar (star or polygon, points, position, rotation, radii, roundness), bezier path (vertices and tangents in layer pixels, path keys), fill (colour, opacity, fill rule), stroke (colour, opacity, width, cap, join, miter limit), gradient fill and stroke (linear or radial, start and end point; the default white-to-black colours), trim paths (start, end, offset, trim multiple shapes), round corners (radius), merge paths (mode; 707, 708), offset paths (amount, line join, miter limit, copies, copy offset; 710; After Effects offsets copy *i* by Amount x (*i* + Copy Offset), default 1, EffectCraft by Amount x (*i* + 1 + copyOffset), so the copy offset arrives 1 less, also its keys; an expression on it is kept and reported; 826-828, 828 renders equal to After Effects on every grid point), repeater (copies, offset, composite, transform; 709), in file order, with keyframes and expressions, the operators' defaults as After Effects reads them back (731); the layer anchor in pixels; 238-242, 330-333, 451-484, 519, 705-710, 731 | | Markers | layer and composition markers: time (layer time for layer markers, exact frames), duration (1/600 s units, 509, 510), comment, chapter, URL, frame target, label, cue point (name, event or navigation, parameters); 122, 123, 249, 347-349, 509, 510 | | Time Remapping | an enabled remap becomes the `timeRemap` property (source seconds, keys in layer time with their interpolation and ease, expression), first in the layer's properties as Layer > Time > Enable Time Remapping puts it; 319, 354 | -| Footage | a link to the stored path; **missing-footage placeholder** when the path does not exist where the import runs (listed in `missingFootage`), a normal link when it does. The importer never opens footage. **An image sequence** (its alias is the folder) becomes a sequence of its files, named from the stored numbering (`shot_0101.exr` .. `shot_0103.exr` in 603, `seq_001.png` .. in 353), at its native frame rate; the first file is the footage's path and the one checked. Sequences and clips take the stored native frame rate and duration (603, 606). A sequence of more than 100 000 frames, or beyond a million file names in one import, links only its first file and is reported | +| Footage | a link to the stored path; **missing-footage placeholder** when the path does not exist where the import runs (listed in `missingFootage`), a normal link when it does. The importer never opens footage. **An image sequence** (its alias is the folder) becomes a sequence of its files, named from the stored numbering (`shot_0101.exr` .. `shot_0103.exr` in 603, `seq_001.png` .. in 353), at its native frame rate; the first file is the footage's path and the one checked. Sequences and clips take the stored native frame rate and duration (603, 606). A sequence of more than 100 000 frames, or beyond a million file names in one import, links only its first file and is reported. **One layer of a Photoshop file** shows that layer (`Footage::layer`: its index and name; at its own size with Retain Layer Sizes, else on the document) and is named `/` unless the item has a name; a layer without pixels (an adjustment layer) keeps the merged image and is reported | Units, the "absent = default" rule and the keyframe templates are the reader's ([aep-format.md](aep-format.md), sections 3.3–3.6). The importer converts them to EffectCraft's: @@ -341,7 +341,7 @@ parameter gets the file's value: | `parent_links` | a parent that was not imported (a skipped camera, a missing layer) or that forms a loop | | `track_mattes` | a track matte of unknown mode, whose matte layer was not imported or does not exist, a layer matted by itself, or a matte of the older "layer above" form on the top layer | | `unsupported_layers` | an unknown layer type, a layer without a usable source, a precomposition loop (the layer is cut) | -| `unsupported_items` | a project item of an unknown kind | +| `unsupported_items` | a project item of an unknown kind; an item made from a Photoshop layer without pixels (it shows the merged image) | | `damaged_data` | a header, key or value that could not be read, numbers that are not finite or beyond ±1e9 (default used); an unreadable text document (the text layer is imported with empty text), damaged style runs | `limitations` states what the reader cannot see at all, so it can be neither imported nor counted: From a44b042fce81adfe5520acc693c3328274470367 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 11 Nov 2026 17:00:44 +0530 Subject: [PATCH 07/83] #3087: report the items a placeholder popup cuts A popup of more than 1024 items kept only the first 1024 without a word, and a valid selection past them was reported as damaged data. The cut is now reported, and such a selection takes the first item and says so. Co-Authored-By: Claude Opus 5.5 --- crates/aep/src/import/placeholder.rs | 20 ++++++++++++++++---- crates/aep/tests/it/import/placeholders.rs | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/aep/src/import/placeholder.rs b/crates/aep/src/import/placeholder.rs index 4e9fd8047..01d845f24 100644 --- a/crates/aep/src/import/placeholder.rs +++ b/crates/aep/src/import/placeholder.rs @@ -60,6 +60,9 @@ pub(crate) fn placeholder( ParamUi::Popup { options } => options.len(), _ => 0, }; + if p.kind == ParamKind::Popup && popup_len(p).is_some_and(|n| n > items) { + col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the items past the first {MAX_POPUP_ITEMS} not kept")); + } let cost = col.placeholder_cost.saturating_add(items).saturating_add(1); if cost > MAX_COST { col.lose(LossCategory::Effects, format!("{here}: parameter {label} not kept (past the import's {MAX_COST} placeholder parameters)")); @@ -99,7 +102,7 @@ fn shape(p: &EffectParam<'_, '_>, size: (u32, u32)) -> Option<(Option, Par // The file's items, separators (`(-`) included: After Effects counts them. let options: Vec = match &p.items { Some(items) => items.iter().take(MAX_POPUP_ITEMS).cloned().collect(), - None => (1..=usize::from(p.popup_item_count()?).min(MAX_POPUP_ITEMS)).map(|i| format!("Item {i}")).collect(), + None => (1..=popup_len(p)?.min(MAX_POPUP_ITEMS)).map(|i| format!("Item {i}")).collect(), }; let n = u32::try_from(options.len()).ok().filter(|n| *n > 0)?; (Kind::EffectPopup(n), ParamUi::Popup { options }, Value::Enum(0)) @@ -109,6 +112,11 @@ fn shape(p: &EffectParam<'_, '_>, size: (u32, u32)) -> Option<(Option, Par Some((Some(kind), ui, default)) } +/// How many items a popup has: the file's names, else the count in its definition. +fn popup_len(p: &EffectParam<'_, '_>) -> Option { + p.items.as_ref().map(Vec::len).or_else(|| p.popup_item_count().map(usize::from)) +} + /// The property id of `p`: its match name when that is one segment of a property path (a /// third-party effect's `CC Cylinder-0003`), else `param` (a pseudo effect's /// `Pseudo/0.25-0001`: `/` and `.` separate path segments). Expressions also find it by its name. @@ -159,8 +167,12 @@ fn fill(p: &EffectParam<'_, '_>, prop: &mut Property, kind: Kind, cx: &LayerCtx< None => return, }, }; - match convert(value, kind) { - Some(v) => prop.value = v, - None => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds a value that is not valid ({value:?})")), + match (convert(value, kind), value) { + (Some(v), _) => prop.value = v, + // An item of the file that is past the ones kept (reported with the cut): the first item. + (None, ParamValue::Index(i)) if usize::try_from(i).is_ok_and(|i| i > MAX_POPUP_ITEMS && popup_len(p).is_some_and(|n| i <= n)) => { + col.lose(LossCategory::Effects, format!("{here}: parameter {label}: item {i} is past the items kept, the first item used")); + } + (None, _) => col.lose(LossCategory::DamagedData, format!("{here}: parameter {label} holds a value that is not valid ({value:?})")), } } diff --git a/crates/aep/tests/it/import/placeholders.rs b/crates/aep/tests/it/import/placeholders.rs index 847060f93..9afccd6b9 100644 --- a/crates/aep/tests/it/import/placeholders.rs +++ b/crates/aep/tests/it/import/placeholders.rs @@ -125,6 +125,22 @@ fn a_popup_default_of_no_item_takes_the_first_item() { assert!(losses(&r, LossCategory::DamagedData, "Some Fx").is_empty()); } +/// A popup past the 1024 items kept: the cut is reported, and a selection among the cut items +/// takes the first item and is reported as such, not as damaged data. +#[test] +fn a_popup_past_the_items_kept_is_reported() { + let items: &'static [&'static str] = Box::leak((0..1100).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::>().into_boxed_slice()); + let fx = Fx { match_name: "Long Fx", name: "Long", defs: vec![popup("Pick", 1, items)], values: vec![(1, 1050.0)], data: vec![], keys: vec![] }; + let (g, r) = placeholder_of(&fx); + let pick = g.prop("Long Fx-0001").unwrap(); + assert_eq!(pick.value, Value::Enum(0)); + assert!(matches!(&pick.ui, ParamUi::Popup { options } if options.len() == 1024)); + let found = losses(&r, LossCategory::Effects, "Long Fx"); + assert!(found.iter().any(|d| d.contains("past the first 1024")), "{found:?}"); + assert!(found.iter().any(|d| d.contains("item 1050 is past the items kept")), "{found:?}"); + assert!(losses(&r, LossCategory::DamagedData, "Long Fx").is_empty()); +} + /// Many large popups stay within the import's budget: what is beyond is reported, not kept. #[test] fn a_hostile_placeholder_stays_bounded() { From a6fba29c3e881e9dd187552d07df0043b7b761b3 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 11 Nov 2026 21:42:54 +0530 Subject: [PATCH 08/83] #3087: report a Photoshop layer whose framing the item's size cannot tell An item as big as its layer's bounds was taken for Retain Layer Sizes. When the layer is also as big as the document but not at its corner, a document-framed item has the same size, so it may show shifted. The opti record holds the document's size at bytes 32 and 36 (1000, 1000 in every record of the issue's project, the .psd's size); with it, that case is reported. The layer still shows at its own bounds. --- crates/aep/src/container/footage.rs | 25 ++++++++++++++++++++++--- crates/aep/src/import/build.rs | 13 +++++++++++-- crates/aep/tests/it/import/synthetic.rs | 22 ++++++++++++++++++++-- docs/aep-format.md | 4 ++-- docs/aep-import.md | 4 ++-- 5 files changed, 57 insertions(+), 11 deletions(-) diff --git a/crates/aep/src/container/footage.rs b/crates/aep/src/container/footage.rs index 7a3782d79..8fca7c27b 100644 --- a/crates/aep/src/container/footage.rs +++ b/crates/aep/src/container/footage.rs @@ -52,8 +52,9 @@ pub struct Footage { /// One layer of a Photoshop file shown by a footage item, from its `opti` (tag `8BPS`, /// docs/aep-format.md 3.3): the layer record's index as a big-endian `i32` at byte 14 (-1 for the -/// merged image), its bounds top, left, bottom, right as little-endian `i32` at 78, 82, 86 and -/// 90, and its name (UTF-8, NUL terminated) from byte 344. +/// merged image), the document's sides as little-endian `u32` at 32 and 36, its bounds top, left, +/// bottom, right as little-endian `i32` at 78, 82, 86 and 90, and its name (UTF-8, NUL +/// terminated) from byte 344. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PsdLayer { /// The layer record's position in the file (bottom of the stack = 0). @@ -62,6 +63,9 @@ pub struct PsdLayer { /// Top, left, bottom, right in document pixels; all 0 for a layer without pixels (an /// adjustment layer). pub bounds: [i32; 4], + /// The document's two sides (bytes 32 and 36; which one is the width is not sampled: the one + /// file read has a square document). 0 when not stored. + pub document: [u32; 2], } /// Most bytes of a Photoshop layer name read. @@ -76,6 +80,12 @@ impl PsdLayer { Some((w, h)) } + /// Whether the document is `size` big, its sides in either order. + pub fn document_is(&self, size: (u32, u32)) -> bool { + let [a, b] = self.document; + a > 0 && b > 0 && ((a, b) == size || (b, a) == size) + } + /// The layer an `opti` names; `None` for another tag, the merged image or a cut record. fn read(opti: &[u8]) -> Option { if opti.get(..4) != Some(&b"8BPS"[..]) { @@ -85,7 +95,8 @@ impl PsdLayer { let le_i32 = |at| le_u32(opti, at).map(|v| i32::from_le_bytes(v.to_le_bytes())); // (After Effects writes 602 bytes; a longer hostile name is cut.) let name = opti.get(344..).map(|b| text(until_nul(b.get(..MAX_NAME).unwrap_or(b)))).unwrap_or_default(); - Some(Self { index, name, bounds: [le_i32(78)?, le_i32(82)?, le_i32(86)?, le_i32(90)?] }) + let document = [le_u32(opti, 32).unwrap_or(0), le_u32(opti, 36).unwrap_or(0)]; + Some(Self { index, name, bounds: [le_i32(78)?, le_i32(82)?, le_i32(86)?, le_i32(90)?], document }) } } @@ -444,6 +455,14 @@ mod tests { assert_eq!(PsdLayer::read(&opti(2, [0; 4], b"")).unwrap().size(), None); assert_eq!(PsdLayer::read(&opti(2, [i32::MIN, i32::MIN, i32::MAX, i32::MAX], b"")).unwrap().size(), Some((u32::MAX, u32::MAX))); assert_eq!(PsdLayer::read(&opti(2, [i32::MAX, 0, i32::MIN, 1], b"")).unwrap().size(), None); + // The document's size, its sides in either order; none when not stored. + let mut doc = opti(0, [0, 0, 1000, 800], b""); + doc[32..36].copy_from_slice(&800u32.to_le_bytes()); + doc[36..40].copy_from_slice(&1000u32.to_le_bytes()); + let l = PsdLayer::read(&doc).unwrap(); + assert_eq!(l.document, [800, 1000]); + assert!(l.document_is((800, 1000)) && l.document_is((1000, 800)) && !l.document_is((800, 800))); + assert!(!PsdLayer::read(&opti(0, [0; 4], b"")).unwrap().document_is((0, 0))); } #[test] diff --git a/crates/aep/src/import/build.rs b/crates/aep/src/import/build.rs index 9da8bb39a..2804d365b 100644 --- a/crates/aep/src/import/build.rs +++ b/crates/aep/src/import/build.rs @@ -352,14 +352,23 @@ fn is_placed_page_path(path: &str) -> bool { /// The Photoshop layer a footage item shows (#3087): at its own bounds when the item is as big /// as they are (Retain Layer Sizes), else on the document. A layer without pixels (an adjustment -/// layer) keeps the merged image and is reported. +/// layer) keeps the merged image and is reported. So is a layer as big as the document but not at +/// its corner: the item's size fits both framings, and its bounds are used. fn source_layer(f: &crate::Footage, name: &str, col: &mut Collector) -> Option { let l = f.psd_layer.as_ref()?; let Some(size) = l.size() else { col.lose(LossCategory::UnsupportedItems, format!("footage '{name}': a Photoshop layer without pixels (an adjustment layer), the merged image used")); return None; }; - Some(SourceLayer { index: l.index, name: l.name.clone(), layer_size: size == (f.width, f.height), ..SourceLayer::default() }) + let layer_size = size == (f.width, f.height); + let [top, left, ..] = l.bounds; + if layer_size && (top, left) != (0, 0) && l.document_is(size) { + col.lose( + LossCategory::UnsupportedItems, + format!("footage '{name}': a Photoshop layer as big as the document but at ({left}, {top}), shown at its own bounds (Retain Layer Sizes assumed)"), + ); + } + Some(SourceLayer { index: l.index, name: l.name.clone(), layer_size, ..SourceLayer::default() }) } /// The name After Effects shows for a footage item that stores none: the file's name, or for a diff --git a/crates/aep/tests/it/import/synthetic.rs b/crates/aep/tests/it/import/synthetic.rs index 0c9e79446..0c00088a5 100644 --- a/crates/aep/tests/it/import/synthetic.rs +++ b/crates/aep/tests/it/import/synthetic.rs @@ -844,12 +844,14 @@ fn a_default_state_colour_record_holds_the_value() { } /// The project with its png item made one layer of a Photoshop file `art.psd`: the `opti` of -/// docs/aep-format.md 3.3 (tag `8BPS`, the layer index at 14, its bounds at 78-94, its name at -/// 344) and the item `size` big. +/// docs/aep-format.md 3.3 (tag `8BPS`, the layer index at 14, a 1000 x 1000 document at 32 and 36, +/// its bounds at 78-94, its name at 344) and the item `size` big. fn as_psd_layer(index: i32, bounds: [i32; 4], name: &str, size: (u32, u32)) -> Vec { let mut opti = vec![0u8; 602]; opti[..4].copy_from_slice(b"8BPS"); opti[14..18].copy_from_slice(&index.to_be_bytes()); + opti[32..36].copy_from_slice(&1000u32.to_le_bytes()); + opti[36..40].copy_from_slice(&1000u32.to_le_bytes()); for (i, v) in bounds.iter().enumerate() { opti[78 + 4 * i..82 + 4 * i].copy_from_slice(&v.to_le_bytes()); } @@ -896,6 +898,22 @@ fn a_photoshop_layer_item_shows_its_layer() { } } +/// A layer as big as the document but off its corner fits both framings: shown at its own bounds +/// and reported. One at the corner, or bigger than the document, reads one way and is not. +#[test] +fn a_photoshop_layer_as_big_as_the_document_off_its_corner_is_reported() { + let framing = |bounds, size| { + let (p, r) = run(&as_psd_layer(3, bounds, "Moved", size), true); + let found = losses(&r.unwrap(), LossCategory::UnsupportedItems); + (the_footage(&p).layer.map(|l| l.layer_size), found.iter().any(|d| d.contains("'Moved/art.psd'") && d.contains("as big as the document"))) + }; + assert_eq!(framing([5, 10, 1005, 1010], (1000, 1000)), (Some(true), true)); + assert_eq!(framing([0, 0, 1000, 1000], (1000, 1000)), (Some(true), false)); + assert_eq!(framing([9, -346, 1083, 1086], (1432, 1074)), (Some(true), false)); + // An item of another size frames the layer on the document: no ambiguity. + assert_eq!(framing([5, 10, 1005, 1010], (800, 800)), (Some(false), false)); +} + /// #3087: a Photoshop layer without pixels (an adjustment layer) keeps the merged image and is /// reported; the merged image itself (index -1) is no layer. #[test] diff --git a/docs/aep-format.md b/docs/aep-format.md index 2b4dae27f..0b73dcfd5 100644 --- a/docs/aep-format.md +++ b/docs/aep-format.md @@ -1,6 +1,6 @@ # After Effects project format (`.aep`) -> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-11 · **Change:** footage: the Photoshop layer an item shows (`opti` tag `8BPS`, section 3.3, issue 3087); before that: Puppet (`ADBE FreePin3`, 3.7): the property tree from an external scripting listing, **?** until a byte sample exists (#3093); before that: footage: an image sequence without a filename prefix stores only the suffix `Utf8`, and one imported with Force alphabetical order stores its file list in `LIST StVc` / `StVS` (section 3, footage); before that: versions: `svap` is the version that wrote the file, `head` bytes 4 to 7 the version it is written for, and what a Save a Copy As 25.x / 24.x of After Effects 2026 changes (section 1, "Versions"); before that: the stretch numerator is signed (a negative one reverses the layer, 981-983); layer styles (3.12b, 950-980); before that: footage: `sspc@118` of an image sequence is its folder's modification time (860, read-back x1-x3); before that: text: paragraph `/24`, `/35` and style `/68` are neutral for 0 and 1 (732-734, edited in place); before that: keyframes: the ease of mask path keys (599, 700), the spatial speed unit of fractional values (597, 598, 730); before that: text: character and paragraph settings, manual kerning, vertical text, `/nil` is neutral (S17: 538-578, 595, 596); before that: cameras, lights and 3D rotations (S16: the auto Position of a two-node camera is where After Effects renders it, 537; camera and light defaults read back 255, 256; Orientation `otst/otda` 488), Timewarp (529-533), an expression on an effect parameter (534); before that: text: style slot /13 is superscript / subscript (526-528; every scripted text of the corpus is superscript), wrapping box text 517; before that: effects of batch 5 (409-450, 511-516: integer sliders, checkbox defaults in `pard`, arbitrary data of Hue/Saturation and Levels, the parameters of Invert, Fast Box Blur, Gaussian Blur, Drop Shadow, Glow; section 3.7); before that: shape items of batch 5 (451-484, 519: ellipse, fill and stroke opacity, fill rule, group transform, shape layer anchor, trim paths, rectangle roundness, polystar fields, gradient default, nested groups, the defaults of every item; section 3.9); before that: track mattes: mode at `ldta` byte 107 and the matte layer id at byte 160 (cases 402-408, section 3.1); before that: text: automatic leading is verified (400); Exposure (`ADBE Exposure2`, cases 389-397): group start / end parameter types 13 / 14, float slider valid minimum and slider range (section 3.7); before that: text: U+0003 is a paragraph break (386, 387); before that: a stored text Anchor Point is pixels (385, now V); before that: the XML form `.aepx` is read into the same chunk tree (section 1, "The XML form"); the `head` save counter is a `u32` at byte 16; text documents for the importer (stroke colour, automatic leading, the font of each run, the undecoded-slot check, the text-layer Anchor Point, the Source Text record); before that: third round of verified field layouts (explicit-default semantics, type-major bezier ease, exact time stretch and in / out points, Time Remapping state, comp pixel aspect / shutter phase / display start, Point default, Layer Control None, dropdown selection, one `mkif` per mask, polystar and radial gradient records, text styles, camera and light options, marker cue data, audio and image-sequence footage) added to the typed view of `effectcraft-aep` · **Target:** Adobe After Effects 2026 +> **Last reviewed:** 2026-11-05 · **Last updated:** 2026-11-11 · **Change:** footage: the Photoshop layer an item shows and its document's size (`opti` tag `8BPS`, section 3.3, issue 3087); before that: Puppet (`ADBE FreePin3`, 3.7): the property tree from an external scripting listing, **?** until a byte sample exists (#3093); before that: footage: an image sequence without a filename prefix stores only the suffix `Utf8`, and one imported with Force alphabetical order stores its file list in `LIST StVc` / `StVS` (section 3, footage); before that: versions: `svap` is the version that wrote the file, `head` bytes 4 to 7 the version it is written for, and what a Save a Copy As 25.x / 24.x of After Effects 2026 changes (section 1, "Versions"); before that: the stretch numerator is signed (a negative one reverses the layer, 981-983); layer styles (3.12b, 950-980); before that: footage: `sspc@118` of an image sequence is its folder's modification time (860, read-back x1-x3); before that: text: paragraph `/24`, `/35` and style `/68` are neutral for 0 and 1 (732-734, edited in place); before that: keyframes: the ease of mask path keys (599, 700), the spatial speed unit of fractional values (597, 598, 730); before that: text: character and paragraph settings, manual kerning, vertical text, `/nil` is neutral (S17: 538-578, 595, 596); before that: cameras, lights and 3D rotations (S16: the auto Position of a two-node camera is where After Effects renders it, 537; camera and light defaults read back 255, 256; Orientation `otst/otda` 488), Timewarp (529-533), an expression on an effect parameter (534); before that: text: style slot /13 is superscript / subscript (526-528; every scripted text of the corpus is superscript), wrapping box text 517; before that: effects of batch 5 (409-450, 511-516: integer sliders, checkbox defaults in `pard`, arbitrary data of Hue/Saturation and Levels, the parameters of Invert, Fast Box Blur, Gaussian Blur, Drop Shadow, Glow; section 3.7); before that: shape items of batch 5 (451-484, 519: ellipse, fill and stroke opacity, fill rule, group transform, shape layer anchor, trim paths, rectangle roundness, polystar fields, gradient default, nested groups, the defaults of every item; section 3.9); before that: track mattes: mode at `ldta` byte 107 and the matte layer id at byte 160 (cases 402-408, section 3.1); before that: text: automatic leading is verified (400); Exposure (`ADBE Exposure2`, cases 389-397): group start / end parameter types 13 / 14, float slider valid minimum and slider range (section 3.7); before that: text: U+0003 is a paragraph break (386, 387); before that: a stored text Anchor Point is pixels (385, now V); before that: the XML form `.aepx` is read into the same chunk tree (section 1, "The XML form"); the `head` save counter is a `u32` at byte 16; text documents for the importer (stroke colour, automatic leading, the font of each run, the undecoded-slot check, the text-layer Anchor Point, the Source Text record); before that: third round of verified field layouts (explicit-default semantics, type-major bezier ease, exact time stretch and in / out points, Time Remapping state, comp pixel aspect / shutter phase / display start, Point default, Layer Control None, dropdown selection, one `mkif` per mask, polystar and radial gradient records, text styles, camera and light options, marker cue data, audio and image-sequence footage) added to the typed view of `effectcraft-aep` · **Target:** Adobe After Effects 2026 What `crates/aep` ([`effectcraft-aep`](../crates/aep/README.md)) reads and writes, and the evidence for each statement. Everything here was observed on project files we generated ourselves; no @@ -263,7 +263,7 @@ property of `L` after 229 and 230). The corpus manifest calls the classic render | footage size | `Pin /sspc` | 30, 34 | u32, u32 | width, height in pixels | 000 (1920 x 1080), 022 (100 x 100 null), 126 (8 x 8), 211, 212, 259 | V | | footage name | `Pin /opti` | 26 (solid), 58 (file) | ASCII, NUL terminated | the item's own `Utf8` name is empty for footage | 000 (`L`), 022 (`Null 1`), 126 (`test8x8.png`), 211 (`S100`), 259 (`Blue`) | V | | **solid colour** | `Pin /opti` | 10, 14, 18, 22 | 4 x f32 | ARGB, 0..1: red [1, 0, 0] is `1, 1, 0, 0`, blue [0, 0, 1] is `1, 0, 0, 1` | 000, 259 | V | -| **Photoshop layer** | `Pin /opti` (tag `8BPS`) | 14; 78, 82, 86, 90; 344 | i32 BE; 4 x i32 **LE**; UTF-8, NUL terminated | an item made from one layer of a `.psd`: the layer record's index in the file (bottom of the stack = 0; -1 is the merged image), the layer's bounds top, left, bottom, right in document pixels (all 0 for a layer without pixels, such as an adjustment layer) and the layer's name. The item's size (`sspc` 30 / 34) is the bounds' size with Retain Layer Sizes, else the document's. `Footage::psd_layer` | the project of issue 3087: ten layers, each index, bounds and name equal to the `.psd`'s layer record at that position (`Layer 1` `[9, -346, 1083, 1086]`, item 1432 x 1074; `test` `[749, 800, 764, 848]`, item 48 x 15) | V | +| **Photoshop layer** | `Pin /opti` (tag `8BPS`) | 14; 32, 36; 78, 82, 86, 90; 344 | i32 BE; 2 x u32 **LE**; 4 x i32 **LE**; UTF-8, NUL terminated | an item made from one layer of a `.psd`: the layer record's index in the file (bottom of the stack = 0; -1 is the merged image), the document's two sides (which is the width: **?**, the one sample is square), the layer's bounds top, left, bottom, right in document pixels (all 0 for a layer without pixels, such as an adjustment layer) and the layer's name. The item's size (`sspc` 30 / 34) is the bounds' size with Retain Layer Sizes, else the document's. `Footage::psd_layer` | the project of issue 3087: ten layers, each index, bounds and name equal to the `.psd`'s layer record at that position (`Layer 1` `[9, -346, 1083, 1086]`, item 1432 x 1074; `test` `[749, 800, 764, 848]`, item 48 x 15; 32 and 36 hold 1000, 1000 in every record, the `.psd`'s size) | V | | file path | `Pin /Als2/alas` | key `fullpath` | JSON string | alias JSON of a file footage item | 126 (the fixture holds a neutral path) | V | | precomp linkage | `Layr/ldta` | 40 | u32 | the layer's source id is the id of the precomp's item | 124 | V | diff --git a/docs/aep-import.md b/docs/aep-import.md index d2a418b85..9f9f8b2b0 100644 --- a/docs/aep-import.md +++ b/docs/aep-import.md @@ -70,7 +70,7 @@ outside the sampled ones keeps the current value and is reported as `project set | Shape layers | groups (nested, with anchor, position, scale, skew, skew axis, rotation, opacity), rectangle (size, position, roundness), ellipse (size, position), polystar (star or polygon, points, position, rotation, radii, roundness), bezier path (vertices and tangents in layer pixels, path keys), fill (colour, opacity, fill rule), stroke (colour, opacity, width, cap, join, miter limit), gradient fill and stroke (linear or radial, start and end point; the default white-to-black colours), trim paths (start, end, offset, trim multiple shapes), round corners (radius), merge paths (mode; 707, 708), offset paths (amount, line join, miter limit, copies, copy offset; 710; After Effects offsets copy *i* by Amount x (*i* + Copy Offset), default 1, EffectCraft by Amount x (*i* + 1 + copyOffset), so the copy offset arrives 1 less, also its keys; an expression on it is kept and reported; 826-828, 828 renders equal to After Effects on every grid point), repeater (copies, offset, composite, transform; 709), in file order, with keyframes and expressions, the operators' defaults as After Effects reads them back (731); the layer anchor in pixels; 238-242, 330-333, 451-484, 519, 705-710, 731 | | Markers | layer and composition markers: time (layer time for layer markers, exact frames), duration (1/600 s units, 509, 510), comment, chapter, URL, frame target, label, cue point (name, event or navigation, parameters); 122, 123, 249, 347-349, 509, 510 | | Time Remapping | an enabled remap becomes the `timeRemap` property (source seconds, keys in layer time with their interpolation and ease, expression), first in the layer's properties as Layer > Time > Enable Time Remapping puts it; 319, 354 | -| Footage | a link to the stored path; **missing-footage placeholder** when the path does not exist where the import runs (listed in `missingFootage`), a normal link when it does. The importer never opens footage. **An image sequence** (its alias is the folder) becomes a sequence of its files, named from the stored numbering (`shot_0101.exr` .. `shot_0103.exr` in 603, `seq_001.png` .. in 353), at its native frame rate; the first file is the footage's path and the one checked. Sequences and clips take the stored native frame rate and duration (603, 606). A sequence of more than 100 000 frames, or beyond a million file names in one import, links only its first file and is reported. **One layer of a Photoshop file** shows that layer (`Footage::layer`: its index and name; at its own size with Retain Layer Sizes, else on the document) and is named `/` unless the item has a name; a layer without pixels (an adjustment layer) keeps the merged image and is reported | +| Footage | a link to the stored path; **missing-footage placeholder** when the path does not exist where the import runs (listed in `missingFootage`), a normal link when it does. The importer never opens footage. **An image sequence** (its alias is the folder) becomes a sequence of its files, named from the stored numbering (`shot_0101.exr` .. `shot_0103.exr` in 603, `seq_001.png` .. in 353), at its native frame rate; the first file is the footage's path and the one checked. Sequences and clips take the stored native frame rate and duration (603, 606). A sequence of more than 100 000 frames, or beyond a million file names in one import, links only its first file and is reported. **One layer of a Photoshop file** shows that layer (`Footage::layer`: its index and name; at its own size with Retain Layer Sizes, else on the document) and is named `/` unless the item has a name; a layer without pixels (an adjustment layer) keeps the merged image and is reported; so is a layer as big as the document but not at its corner, which the item's size does not tell apart (shown at its own size) | Units, the "absent = default" rule and the keyframe templates are the reader's ([aep-format.md](aep-format.md), sections 3.3–3.6). The importer converts them to EffectCraft's: @@ -345,7 +345,7 @@ for the `unlisted` ones. The categories: | `parent_links` | a parent that was not imported (a skipped camera, a missing layer) or that forms a loop | | `track_mattes` | a track matte of unknown mode, whose matte layer was not imported or does not exist, a layer matted by itself, or a matte of the older "layer above" form on the top layer | | `unsupported_layers` | an unknown layer type, a layer without a usable source, a precomposition loop (the layer is cut) | -| `unsupported_items` | a project item of an unknown kind; an item made from a Photoshop layer without pixels (it shows the merged image) | +| `unsupported_items` | a project item of an unknown kind; an item made from a Photoshop layer without pixels (it shows the merged image), or from one as big as the document but not at its corner (shown at its own size) | | `damaged_data` | a header, key or value that could not be read, numbers that are not finite or beyond ±1e9 (default used); an unreadable text document (the text layer is imported with empty text), damaged style runs | `limitations` states what the reader cannot see at all, so it can be neither imported nor counted: From 14d04536aafb34b41e6eff305f197cd2ae938438 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Wed, 11 Nov 2026 22:02:46 +0530 Subject: [PATCH 09/83] #3087: report a Photoshop layer item as big as neither its layer nor the document Such an item is shown on the document, which the size does not confirm; it is now reported in unsupported_items, when the opti stores the document's size. --- crates/aep/src/import/build.rs | 9 ++++++++- crates/aep/tests/it/import/synthetic.rs | 17 ++++++++++------- docs/aep-import.md | 4 ++-- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/crates/aep/src/import/build.rs b/crates/aep/src/import/build.rs index 2804d365b..f6ac69cda 100644 --- a/crates/aep/src/import/build.rs +++ b/crates/aep/src/import/build.rs @@ -353,7 +353,8 @@ fn is_placed_page_path(path: &str) -> bool { /// The Photoshop layer a footage item shows (#3087): at its own bounds when the item is as big /// as they are (Retain Layer Sizes), else on the document. A layer without pixels (an adjustment /// layer) keeps the merged image and is reported. So is a layer as big as the document but not at -/// its corner: the item's size fits both framings, and its bounds are used. +/// its corner (the item's size fits both framings; its bounds are used), and an item as big as +/// neither (the document is used). fn source_layer(f: &crate::Footage, name: &str, col: &mut Collector) -> Option { let l = f.psd_layer.as_ref()?; let Some(size) = l.size() else { @@ -361,6 +362,12 @@ fn source_layer(f: &crate::Footage, name: &str, col: &mut Collector) -> Option 0) && !l.document_is((f.width, f.height)) { + col.lose( + LossCategory::UnsupportedItems, + format!("footage '{name}': {} x {} is neither the Photoshop layer's size nor the document's, shown on the document", f.width, f.height), + ); + } let [top, left, ..] = l.bounds; if layer_size && (top, left) != (0, 0) && l.document_is(size) { col.lose( diff --git a/crates/aep/tests/it/import/synthetic.rs b/crates/aep/tests/it/import/synthetic.rs index 0c00088a5..d1c030401 100644 --- a/crates/aep/tests/it/import/synthetic.rs +++ b/crates/aep/tests/it/import/synthetic.rs @@ -899,19 +899,22 @@ fn a_photoshop_layer_item_shows_its_layer() { } /// A layer as big as the document but off its corner fits both framings: shown at its own bounds -/// and reported. One at the corner, or bigger than the document, reads one way and is not. +/// and reported. One at the corner, or bigger than the document, reads one way and is not. An item +/// as big as neither is shown on the document and reported. #[test] fn a_photoshop_layer_as_big_as_the_document_off_its_corner_is_reported() { let framing = |bounds, size| { let (p, r) = run(&as_psd_layer(3, bounds, "Moved", size), true); let found = losses(&r.unwrap(), LossCategory::UnsupportedItems); - (the_footage(&p).layer.map(|l| l.layer_size), found.iter().any(|d| d.contains("'Moved/art.psd'") && d.contains("as big as the document"))) + let said = |what: &str| found.iter().any(|d| d.contains("'Moved/art.psd'") && d.contains(what)); + (the_footage(&p).layer.map(|l| l.layer_size), said("as big as the document"), said("neither the Photoshop layer's size")) }; - assert_eq!(framing([5, 10, 1005, 1010], (1000, 1000)), (Some(true), true)); - assert_eq!(framing([0, 0, 1000, 1000], (1000, 1000)), (Some(true), false)); - assert_eq!(framing([9, -346, 1083, 1086], (1432, 1074)), (Some(true), false)); - // An item of another size frames the layer on the document: no ambiguity. - assert_eq!(framing([5, 10, 1005, 1010], (800, 800)), (Some(false), false)); + assert_eq!(framing([5, 10, 1005, 1010], (1000, 1000)), (Some(true), true, false)); + assert_eq!(framing([0, 0, 1000, 1000], (1000, 1000)), (Some(true), false, false)); + assert_eq!(framing([9, -346, 1083, 1086], (1432, 1074)), (Some(true), false, false)); + assert_eq!(framing([749, 800, 764, 848], (1000, 1000)), (Some(false), false, false)); + // An item as big as neither the layer nor the document: shown on the document, reported. + assert_eq!(framing([5, 10, 1005, 1010], (800, 800)), (Some(false), false, true)); } /// #3087: a Photoshop layer without pixels (an adjustment layer) keeps the merged image and is diff --git a/docs/aep-import.md b/docs/aep-import.md index 9f9f8b2b0..1adc88153 100644 --- a/docs/aep-import.md +++ b/docs/aep-import.md @@ -70,7 +70,7 @@ outside the sampled ones keeps the current value and is reported as `project set | Shape layers | groups (nested, with anchor, position, scale, skew, skew axis, rotation, opacity), rectangle (size, position, roundness), ellipse (size, position), polystar (star or polygon, points, position, rotation, radii, roundness), bezier path (vertices and tangents in layer pixels, path keys), fill (colour, opacity, fill rule), stroke (colour, opacity, width, cap, join, miter limit), gradient fill and stroke (linear or radial, start and end point; the default white-to-black colours), trim paths (start, end, offset, trim multiple shapes), round corners (radius), merge paths (mode; 707, 708), offset paths (amount, line join, miter limit, copies, copy offset; 710; After Effects offsets copy *i* by Amount x (*i* + Copy Offset), default 1, EffectCraft by Amount x (*i* + 1 + copyOffset), so the copy offset arrives 1 less, also its keys; an expression on it is kept and reported; 826-828, 828 renders equal to After Effects on every grid point), repeater (copies, offset, composite, transform; 709), in file order, with keyframes and expressions, the operators' defaults as After Effects reads them back (731); the layer anchor in pixels; 238-242, 330-333, 451-484, 519, 705-710, 731 | | Markers | layer and composition markers: time (layer time for layer markers, exact frames), duration (1/600 s units, 509, 510), comment, chapter, URL, frame target, label, cue point (name, event or navigation, parameters); 122, 123, 249, 347-349, 509, 510 | | Time Remapping | an enabled remap becomes the `timeRemap` property (source seconds, keys in layer time with their interpolation and ease, expression), first in the layer's properties as Layer > Time > Enable Time Remapping puts it; 319, 354 | -| Footage | a link to the stored path; **missing-footage placeholder** when the path does not exist where the import runs (listed in `missingFootage`), a normal link when it does. The importer never opens footage. **An image sequence** (its alias is the folder) becomes a sequence of its files, named from the stored numbering (`shot_0101.exr` .. `shot_0103.exr` in 603, `seq_001.png` .. in 353), at its native frame rate; the first file is the footage's path and the one checked. Sequences and clips take the stored native frame rate and duration (603, 606). A sequence of more than 100 000 frames, or beyond a million file names in one import, links only its first file and is reported. **One layer of a Photoshop file** shows that layer (`Footage::layer`: its index and name; at its own size with Retain Layer Sizes, else on the document) and is named `/` unless the item has a name; a layer without pixels (an adjustment layer) keeps the merged image and is reported; so is a layer as big as the document but not at its corner, which the item's size does not tell apart (shown at its own size) | +| Footage | a link to the stored path; **missing-footage placeholder** when the path does not exist where the import runs (listed in `missingFootage`), a normal link when it does. The importer never opens footage. **An image sequence** (its alias is the folder) becomes a sequence of its files, named from the stored numbering (`shot_0101.exr` .. `shot_0103.exr` in 603, `seq_001.png` .. in 353), at its native frame rate; the first file is the footage's path and the one checked. Sequences and clips take the stored native frame rate and duration (603, 606). A sequence of more than 100 000 frames, or beyond a million file names in one import, links only its first file and is reported. **One layer of a Photoshop file** shows that layer (`Footage::layer`: its index and name; at its own size with Retain Layer Sizes, else on the document) and is named `/` unless the item has a name; a layer without pixels (an adjustment layer) keeps the merged image and is reported; so is a layer as big as the document but not at its corner, which the item's size does not tell apart (shown at its own size), and an item as big as neither the layer nor the document (shown on the document) | Units, the "absent = default" rule and the keyframe templates are the reader's ([aep-format.md](aep-format.md), sections 3.3–3.6). The importer converts them to EffectCraft's: @@ -345,7 +345,7 @@ for the `unlisted` ones. The categories: | `parent_links` | a parent that was not imported (a skipped camera, a missing layer) or that forms a loop | | `track_mattes` | a track matte of unknown mode, whose matte layer was not imported or does not exist, a layer matted by itself, or a matte of the older "layer above" form on the top layer | | `unsupported_layers` | an unknown layer type, a layer without a usable source, a precomposition loop (the layer is cut) | -| `unsupported_items` | a project item of an unknown kind; an item made from a Photoshop layer without pixels (it shows the merged image), or from one as big as the document but not at its corner (shown at its own size) | +| `unsupported_items` | a project item of an unknown kind; an item made from a Photoshop layer without pixels (it shows the merged image), or from one as big as the document but not at its corner (shown at its own size), or an item as big as neither the layer nor the document (shown on the document) | | `damaged_data` | a header, key or value that could not be read, numbers that are not finite or beyond ±1e9 (default used); an unreadable text document (the text layer is imported with empty text), damaged style runs | `limitations` states what the reader cannot see at all, so it can be neither imported nor counted: From d503b26e21997042a3eae50d8ed6e6547098b962 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 10:43:41 +0530 Subject: [PATCH 10/83] #3493: Apply Color LUT reads a LUT file again once it changes on disk load_lut kept the first result for a path for the life of the process: an edited file, or one created after a failed load, was never read again. Each file-backed entry now keeps the file's size and modification time and is read again once they move; inline .cube text stays cached by content. The cache keeps at most 32 LUTs (least recently used goes first). --- crates/effects/src/lib.rs | 2 +- crates/effects/src/utility.rs | 190 +++++++++++++++++++++++++++++++--- 2 files changed, 175 insertions(+), 17 deletions(-) diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 532bb28c9..9105f4587 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -129,7 +129,7 @@ pub use sim2::{ CausticsSetup, FoamDisc, FoamEnv, FoamPlan, Piece, PiecePlan, PieceTex, PixelPlan, WavePlan, Waves, caustics_setup, foam_full_plan, piece_plan, pixel_plan, wave_world_plan, }; -pub use utility::{Lut, load_lut}; +pub use utility::{Lut, check_lut_files, load_lut, lut_file, lut_generation, lut_params}; pub use vr::{equi_dir as vr_equi_dir, rotation as vr_rotation}; /// Effect categories in Effects & Presets order. diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index f0275eab1..2c663ebca 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -2,7 +2,8 @@ //! lookup tables (.cube). use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use effectcraft_color::luminance; use effectcraft_keyframe::Value; @@ -330,28 +331,119 @@ impl Lut { } } -type LutCache = Mutex>>>; +/// A LUT file's size and modification time when it was read (`None`: inline text, or a file +/// that could not be described). A file whose stamp moved is read again (#3493). +type FileStamp = Option<(u64, Option)>; -/// Load (and cache) a LUT from inline `.cube` text or a file path. +/// At most this many LUTs (files and inline texts) are kept; the least recently used goes first. +const MAX_CACHED_LUTS: usize = 32; + +/// A parsed LUT (or the failure to parse one) and what it was read from. +struct CachedLut { + stamp: FileStamp, + lut: Option>, + used: u64, +} + +/// [`load_lut`]'s cache, by parameter text. +#[derive(Default)] +struct LutCache { + map: HashMap, + clock: u64, +} + +/// How often a cached LUT file was found changed on disk ([`lut_generation`]). +static GENERATION: AtomicU64 = AtomicU64::new(0); + +fn lut_cache() -> std::sync::MutexGuard<'static, LutCache> { + static CACHE: OnceLock> = OnceLock::new(); + CACHE.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner) +} + +/// The stamp of the file at `path` now: one `metadata` call. +fn file_stamp(path: &str) -> FileStamp { + std::fs::metadata(path).ok().map(|md| (md.len(), md.modified().ok())) +} + +/// The parameters (paths in the effect's group) of `effect` that [`load_lut`] reads. +pub fn lut_params(effect: &str) -> &'static [&'static str] { + match effect { + "ec.utility.applylut" => &["lut"], + "ec.color.lumetri" => &["basicCorrection/inputLutFile", "creative/lookFile"], + _ => &[], + } +} + +/// The file a LUT parameter names; `None` for inline `.cube` text or an empty parameter. +pub fn lut_file(src: &str) -> Option<&str> { + // `.cube` text always spans lines (a size header, then data rows); a path never does, even one + // whose file name contains `LUT_` (#3454). Trimmed, so a trailing newline is still a path. + let path = src.trim(); + (!path.is_empty() && !path.contains('\n')).then_some(path) +} + +/// Changes each time a LUT file [`load_lut`] read is found changed on disk (by [`load_lut`] +/// itself or [`check_lut_files`]): frames made before then may show the old LUT. +pub fn lut_generation() -> u64 { + GENERATION.load(Ordering::Acquire) +} + +/// Look at every LUT file in the cache (one `metadata` call each) and forget the ones that changed +/// on disk since they were read, so the next [`load_lut`] reads them again. Returns +/// [`lut_generation`]. +pub fn check_lut_files() -> u64 { + let files: Vec<(String, FileStamp)> = lut_cache().map.iter().filter_map(|(src, e)| Some((lut_file(src)?.to_string(), e.stamp))).collect(); + // (stamped without the lock: a file on a slow share must not hold up renders) + let changed: Vec = files.into_iter().filter(|(path, stamp)| file_stamp(path) != *stamp).map(|(path, _)| path).collect(); + if !changed.is_empty() { + let mut c = lut_cache(); + c.map.retain(|src, _| lut_file(src).is_none_or(|p| !changed.iter().any(|c| c == p))); + GENERATION.fetch_add(1, Ordering::AcqRel); + } + lut_generation() +} + +/// Load (and cache) a LUT from inline `.cube` text or a file path. A file is stamped (one +/// `metadata` call) on every load and read again once its size or modification time moved, so a +/// file edited, created, deleted or repaired on disk is followed; inline text is its own content. +/// An edit that keeps both the size and the modification time can't be told apart. pub fn load_lut(src: &str) -> Option> { if src.trim().is_empty() { return None; } - static CACHE: OnceLock = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - if let Ok(m) = cache.lock() - && let Some(v) = m.get(src) - { - return v.clone(); + let file = lut_file(src); + let stamp = file.and_then(file_stamp); + let seen = { + let mut c = lut_cache(); + c.clock += 1; + let now = c.clock; + match c.map.get_mut(src) { + Some(e) if e.stamp == stamp => { + e.used = now; + return e.lut.clone(); + } + Some(e) => Some(e.stamp), + None => None, + } + }; + // (read and parsed without the lock; a file written after it was stamped has a newer stamp, + // and is read again next time) + let lut = match file { + Some(path) => std::fs::read_to_string(path).ok().and_then(|t| parse_cube(&t)), + None => parse_cube(src), } - // `.cube` text always spans lines (a size header, then data rows); a path never does, even one - // whose file name contains `LUT_` (#3454). Trimmed, as the path is, so a trailing newline is a path. - let inline = src.trim().contains('\n'); - let parsed = if inline { parse_cube(src) } else { std::fs::read_to_string(src.trim()).ok().and_then(|t| parse_cube(&t)) }.map(Arc::new); - if let Ok(mut m) = cache.lock() { - m.insert(src.to_string(), parsed.clone()); + .map(Arc::new); + let mut c = lut_cache(); + if seen.is_some_and(|s| s != stamp) { + GENERATION.fetch_add(1, Ordering::AcqRel); } - parsed + let used = c.clock; + c.map.insert(src.to_string(), CachedLut { stamp, lut: lut.clone(), used }); + while c.map.len() > MAX_CACHED_LUTS { + let Some(oldest) = c.map.iter().min_by_key(|(_, e)| e.used).map(|(k, _)| k.clone()) else { break }; + c.map.remove(&oldest); + } + lut } fn apply_lut(ctx: &EffectCtx, mut b: Buf) -> Buf { @@ -500,6 +592,72 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + /// #3493: a LUT file was read once per process; an edited or newly created file never loaded. + #[test] + fn a_lut_file_is_read_again_once_it_changes() { + const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n"; + const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n"; + let dir = std::env::temp_dir().join(format!("ec-fx-3493-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let write = |name: &str, text: &str, secs: u64| { + let path = dir.join(name); + std::fs::write(&path, text).unwrap(); + let f = std::fs::File::options().write(true).open(&path).unwrap(); + f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap(); + path.to_string_lossy().into_owned() + }; + let at = |src: &str| load_lut(src).map(|l| l.apply([0.5; 3])); + let edited = write("edited.cube", BLACK, 1_000); + assert_eq!(at(&edited), Some([0.0; 3])); + write("edited.cube", WHITE, 2_000); + assert_eq!(at(&edited), Some([1.0; 3]), "an edited file, same size"); + let created = dir.join("created.cube").to_string_lossy().into_owned(); + assert_eq!(at(&created), None); + write("created.cube", WHITE, 1_000); + assert_eq!(at(&created), Some([1.0; 3]), "a file created after a failed load"); + let repaired = write("repaired.cube", "not a lut", 1_000); + assert_eq!(at(&repaired), None); + write("repaired.cube", WHITE, 2_000); + assert_eq!(at(&repaired), Some([1.0; 3]), "a repaired file"); + std::fs::remove_file(&repaired).unwrap(); + assert_eq!(at(&repaired), None, "a deleted file"); + // Inline text is its own content: the same text is the same LUT. + let inline = load_lut(BLACK).unwrap(); + assert!(Arc::ptr_eq(&inline, &load_lut(BLACK).unwrap())); + std::fs::remove_dir_all(&dir).unwrap(); + } + + /// A file that changed is noticed without a render loading it, and the generation that tells + /// frames made before it apart moves. + #[test] + fn check_lut_files_forgets_a_changed_file() { + let dir = std::env::temp_dir().join(format!("ec-fx-3493-check-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("grade.cube"); + std::fs::write(&path, identity_cube(2)).unwrap(); + let src = path.to_string_lossy().into_owned(); + assert!(load_lut(&src).is_some()); + let before = check_lut_files(); + assert!(lut_cache().map.contains_key(&src), "an unchanged file stays"); + std::fs::write(&path, identity_cube(3)).unwrap(); + assert!(check_lut_files() > before); + assert!(!lut_cache().map.contains_key(&src), "a changed file is read again"); + assert_eq!(load_lut(&src).map(|l| l.n3), Some(3)); + std::fs::remove_dir_all(&dir).unwrap(); + } + + /// The cache keeps at most [`MAX_CACHED_LUTS`] LUTs, the least recently used going first. + #[test] + fn the_lut_cache_is_bounded() { + let first = load_lut(&identity_cube(2)).unwrap(); + for i in 0..MAX_CACHED_LUTS + 8 { + let text = format!("TITLE \"bounded {i}\"\n{}", identity_cube(2)); + assert!(load_lut(&text).is_some()); + assert!(lut_cache().map.len() <= MAX_CACHED_LUTS); + } + assert!(!Arc::ptr_eq(&first, &load_lut(&identity_cube(2)).unwrap()), "the oldest was let go"); + } + #[test] fn one_d_lut_with_domain() { let lut = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n1 1 1\n0 0 0\n").unwrap(); From 6780c65671f70ca0828a9b584b0c33695927e910 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 10:44:57 +0530 Subject: [PATCH 11/83] #3456: write the footage in analysis signatures field by field The Warp Stabilizer, 3D Camera Tracker and Roto Brush signatures hashed the footage item's derived Debug text, so every new Footage field changed every signature and dropped every saved analysis (placed_page did in 0.23). Write the same text from a named list of fields instead: a new field no longer compiles until it is decided there. Pin the text in a test. --- crates/engine/src/analysis/warp.rs | 97 ++++++++++++++++++- crates/engine/src/tests.rs | 1 + .../engine/src/tests/legacy_analysis_keys.rs | 22 +++++ 3 files changed, 115 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/tests/legacy_analysis_keys.rs diff --git a/crates/engine/src/analysis/warp.rs b/crates/engine/src/analysis/warp.rs index 0ab576d2c..b88d9df38 100644 --- a/crates/engine/src/analysis/warp.rs +++ b/crates/engine/src/analysis/warp.rs @@ -17,7 +17,7 @@ use std::sync::{Arc, Mutex}; use effectcraft_effects::warp_stab::{self, ANALYSIS, ANALYSIS_KEY}; use effectcraft_keyframe::Value; -use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Project, PropGroup, Uid}; +use effectcraft_project::{Footage, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Project, PropGroup, Uid}; use effectcraft_raster::Image; use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, Renderer}; use effectcraft_time::Tick; @@ -112,7 +112,7 @@ fn fnv(s: &str) -> u64 { pub fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String { let src = match &layer.source { LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) { - Some(ItemKind::Footage(f)) => format!("{f:?}"), + Some(ItemKind::Footage(f)) => footage_text(f, true), Some(ItemKind::Solid(s)) => format!("{s:?}"), Some(ItemKind::Comp(c)) => format!("{}x{}@{:?}/{:?}", c.width, c.height, c.frame_rate, c.duration), _ => String::new(), @@ -127,9 +127,96 @@ pub fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String { pub(crate) fn signature_before_placed_page(p: &Project, comp: ItemId, layer: &Layer) -> Option { let LayerSource::Footage { item } = &layer.source else { return None }; let ItemKind::Footage(footage) = &p.item(*item)?.kind else { return None }; - let src = format!("{footage:?}"); - let old = src.strip_suffix(", placed_page: false }")?; - Some(signature_with_source(p, comp, layer, &format!("{old} }}"))) + if footage.placed_page { + return None; + } + Some(signature_with_source(p, comp, layer, &footage_text(footage, false))) +} + +/// A footage item in a signature: its fields as `Debug` wrote them in 0.23, the text saved +/// analysis keys were hashed from (without `placed_page` before 0.23). It is written out here so +/// that a new `Footage` field doesn't change every signature and drop every saved analysis. +pub(crate) fn footage_text(f: &Footage, placed_page: bool) -> String { + format!("{:?}", FootageText { f, placed_page }) +} + +struct FootageText<'a> { + f: &'a Footage, + placed_page: bool, +} + +impl std::fmt::Debug for FootageText<'_> { + fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Every field is named, so a new one doesn't compile until it is decided here. A new field + // that changes the frames goes last, written only when it isn't its default, so keys saved + // before it still match. A new field that doesn't change the frames stays out. + let Footage { + path, + kind, + width, + height, + pixel_aspect, + frame_rate, + native_rate, + duration, + has_video, + has_audio, + alpha, + premul_color, + loop_count, + codec, + missing, + sequence, + color_profile, + layer, + fields, + invert_alpha, + linear_light, + preserve_rgb, + cineon, + data, + page, + alphabetical, + start_timecode, + file_timecode, + markers, + placed_page, + } = self.f; + let mut d = out.debug_struct("Footage"); + d.field("path", path) + .field("kind", kind) + .field("width", width) + .field("height", height) + .field("pixel_aspect", pixel_aspect) + .field("frame_rate", frame_rate) + .field("native_rate", native_rate) + .field("duration", duration) + .field("has_video", has_video) + .field("has_audio", has_audio) + .field("alpha", alpha) + .field("premul_color", premul_color) + .field("loop_count", loop_count) + .field("codec", codec) + .field("missing", missing) + .field("sequence", sequence) + .field("color_profile", color_profile) + .field("layer", layer) + .field("fields", fields) + .field("invert_alpha", invert_alpha) + .field("linear_light", linear_light) + .field("preserve_rgb", preserve_rgb) + .field("cineon", cineon) + .field("data", data) + .field("page", page) + .field("alphabetical", alphabetical) + .field("start_timecode", start_timecode) + .field("file_timecode", file_timecode) + .field("markers", markers); + if self.placed_page { + d.field("placed_page", placed_page); + } + d.finish() + } } fn signature_with_source(p: &Project, comp: ItemId, layer: &Layer, src: &str) -> String { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 19953053e..8d33ee3d4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -27,6 +27,7 @@ mod key_metadata_order; mod key_time; mod keyframe_text; mod keylight; +mod legacy_analysis_keys; mod limits; mod lottie; mod m137; diff --git a/crates/engine/src/tests/legacy_analysis_keys.rs b/crates/engine/src/tests/legacy_analysis_keys.rs new file mode 100644 index 000000000..f4e442050 --- /dev/null +++ b/crates/engine/src/tests/legacy_analysis_keys.rs @@ -0,0 +1,22 @@ +//! Warp Stabilizer and 3D Camera Tracker analyses saved by an earlier release keep matching +//! their footage after an edit that doesn't change it (#3456), and a real change still clears them. + +/// The footage text analysis keys are hashed from, as 0.23 saved it. A new `Footage` field must +/// not change it (or every saved analysis is dropped again). +#[test] +fn footage_signature_text_is_pinned() { + use effectcraft_project::{Footage, FootageKind}; + let f = Footage { + path: "clip.mp4".into(), + kind: FootageKind::Video, + width: 160, + height: 120, + invert_alpha: true, + page: 2, + placed_page: true, + ..Footage::default() + }; + let fields = r#"path: "clip.mp4", kind: Video, width: 160, height: 120, pixel_aspect: 1.0, frame_rate: FrameRate { num: 30, den: 1 }, native_rate: None, duration: Tick(0), has_video: false, has_audio: false, alpha: Straight, premul_color: [0.0, 0.0, 0.0], loop_count: 1, codec: "", missing: false, sequence: [], color_profile: None, layer: None, fields: Off, invert_alpha: true, linear_light: false, preserve_rgb: false, cineon: CineonSettings { log_conversion: false, converted_black: 0.0, converted_white: 1023.0, black: 95.0, white: 685.0, gamma: 1.7, rolloff: 20.0, units: TenBit }, data: None, page: 2, alphabetical: false, start_timecode: None, file_timecode: None, markers: []"#; + assert_eq!(crate::warp::footage_text(&f, true), format!("Footage {{ {fields}, placed_page: true }}")); + assert_eq!(crate::warp::footage_text(&f, false), format!("Footage {{ {fields} }}")); +} From 6a78d94a5b733a5f2837ce7c4a210adaca0802b8 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 10:51:27 +0530 Subject: [PATCH 12/83] #3493: key cached layers and frames on the LUT files they read A layer graded with Apply Color LUT or Lumetri's Input LUT and Look was cached by the parameter text alone, so the same frame kept showing the old LUT from memory and from the disk cache after the file changed. A layer's cache key (and the key of a layer reading it, through a precomp too) now holds each LUT file's size and modification time, and a render lists the LUT files it read, so a frame kept on disk made with an older file is not used. --- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/lut_files.rs | 154 ++++++++++++++++++++++++ crates/render/src/cache/dependencies.rs | 2 + crates/render/src/pipeline.rs | 9 ++ crates/render/src/reads.rs | 17 +++ 5 files changed, 183 insertions(+) create mode 100644 crates/engine/src/tests/lut_files.rs diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 19953053e..4a5c32b63 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -29,6 +29,7 @@ mod keyframe_text; mod keylight; mod limits; mod lottie; +mod lut_files; mod m137; mod m145; mod markers; diff --git a/crates/engine/src/tests/lut_files.rs b/crates/engine/src/tests/lut_files.rs new file mode 100644 index 000000000..9388e64bd --- /dev/null +++ b/crates/engine/src/tests/lut_files.rs @@ -0,0 +1,154 @@ +//! A LUT file that changes on disk renders again (#3493): Apply Color LUT and Lumetri's Input +//! LUT name a `.cube` file; an edit to it, or a file created, deleted or repaired, shows on the +//! next render of the same frame, from warm layer caches in memory and on disk, through a precomp +//! and a layer reading that precomp, and a frame kept on disk made with the old file is refused. + +use std::path::Path; +use std::time::{Duration, UNIX_EPOCH}; + +use serde_json::{Value, json}; + +use crate::Session; +use crate::render::RenderOpts; +use effectcraft_project::ItemId; +use effectcraft_render::disk_cache::{DiskCache, comp_content_key, frame_key}; +use effectcraft_render::reads::ReadLog; +use effectcraft_time::Tick; + +/// Every input to black, or to white (1D, two entries: the same size, so only the modification +/// time tells the two apart). +const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n"; +const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n"; +const GREY: f32 = 128.0 / 255.0; + +/// Write `text` to `path` with its modification time `secs` after the epoch. +fn write(path: &Path, text: &str, secs: u64) { + std::fs::write(path, text).unwrap(); + let f = std::fs::File::options().write(true).open(path).unwrap(); + f.set_modified(UNIX_EPOCH + Duration::from_secs(secs)).unwrap(); +} + +/// A session, its layer buffers written to a disk cache in `disk` when given. +fn session(disk: Option<&Path>) -> Session { + let mut s = Session::default(); + if let Some(dir) = disk { + s.execute_checked("prefs.set", json!({"values": {"disk.diskCacheFolder": dir.to_string_lossy(), "disk.diskCacheEnabled": true}})).unwrap(); + s.disk_cache.as_ref().unwrap().set_min_layer_ms(0); + } + s +} + +/// Comp "Grade": a grey solid graded by `effect` (`params` set on it). Comp "Shot" shows it as a +/// precomp layer, under a solid that copies the precomp's channels (Set Channels): that layer is +/// cached with what the precomp shows. Returns (Grade, Shot). +fn shot(s: &mut Session, effect: &str, params: &[(&str, Value)]) -> (ItemId, ItemId) { + s.execute_checked("comp.new", json!({"name": "Shot", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap(); + let shot = s.active_comp_id().unwrap(); + let plate = s.execute_checked("layer.newSolid", json!({"name": "Plate", "color": "#808080", "width": 8, "height": 8})).unwrap()["layer"].clone(); + s.execute_checked("effect.apply", json!({"layer": plate, "effect": effect})).unwrap(); + for (path, value) in params { + s.execute_checked("prop.set", json!({"layer": plate, "path": format!("effects/#1/{path}"), "value": value})).unwrap(); + } + let pre = s.execute_checked("layer.precompose", json!({"layers": [plate], "name": "Grade"})).unwrap(); + let grade = ItemId(pre["comp"].as_u64().unwrap()); + let copy = s.execute_checked("layer.newSolid", json!({"name": "Copy", "color": "#00ff00", "width": 8, "height": 8})).unwrap()["layer"].clone(); + s.execute_checked("effect.apply", json!({"layer": copy, "effect": "Set Channels"})).unwrap(); + for i in 1..=3 { + s.execute_checked("prop.set", json!({"layer": copy, "path": format!("effects/#1/sourceLayer{i}"), "value": pre["layer"]})).unwrap(); + } + (grade, shot) +} + +/// The red and green of the centre of both comps' first frame. +fn colours(s: &Session, (grade, shot): (ItemId, ItemId)) -> [f32; 4] { + let at = |comp| { + let img = s.render(comp, Tick::ZERO, RenderOpts::default()); + img.get(i64::from(img.width / 2), i64::from(img.height / 2)) + }; + let (g, c) = (at(grade), at(shot)); + [g[0], g[1], c[0], c[1]] +} + +#[track_caller] +fn assert_all(got: [f32; 4], want: f32) { + assert!(got.iter().all(|v| (v - want).abs() < 0.01), "{got:?}, want {want}"); +} + +#[test] +fn an_edited_lut_file_renders_again_from_warm_caches() { + let dir = tempfile::tempdir().unwrap(); + let lut = dir.path().join("grade.cube"); + write(&lut, BLACK, 1_000); + let mut s = session(None); + let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]); + assert_all(colours(&s, comps), 0.0); + let misses = s.layer_cache.stats().misses; + assert_all(colours(&s, comps), 0.0); + assert_eq!(s.layer_cache.stats().misses, misses, "an unchanged file keeps the cached layers"); + // A frame on disk made with the file names it. + let frames = DiskCache::open(dir.path().join("frames"), 1 << 30).unwrap(); + let key = frame_key(comp_content_key(&s.project, comps.1), 0, 1000, 0); + let log = ReadLog::new(); + let mut r = s.renderer(RenderOpts::default()); + r.reads = Some(&log); + let _ = r.comp_frame(comps.1, Tick::ZERO); + let files = log.into_files(); + assert!(files.get(&lut.to_string_lossy()).is_some(), "the render notes the LUT file: {files:?}"); + frames.put_frame_now(key, 1, 1, &[0; 4], &files); + assert!(frames.get_frame(key, None).is_some()); + let generation = effectcraft_effects::lut_generation(); + write(&lut, WHITE, 2_000); + assert_all(colours(&s, comps), 1.0); + assert!(effectcraft_effects::lut_generation() > generation, "the viewer's frames made before are dropped"); + assert!(frames.get_frame(key, None).is_none(), "the frame on disk made with the old file"); +} + +#[test] +fn an_edited_lut_file_is_not_served_from_the_disk_cache() { + let dir = tempfile::tempdir().unwrap(); + let (lut, disk) = (dir.path().join("grade.cube"), dir.path().join("cache")); + write(&lut, BLACK, 1_000); + let mut s = session(Some(&disk)); + let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]); + assert_all(colours(&s, comps), 0.0); + let dc = s.disk_cache.clone().unwrap(); + dc.flush(); + assert!(dc.stats().entries > 0, "layer buffers written"); + let project = s.project.clone(); + drop((s, dc)); + // A restart on the same cache, after the file changed. + write(&lut, WHITE, 2_000); + let mut s = session(Some(&disk)); + s.project = project; + s.bump(); + assert_all(colours(&s, comps), 1.0); +} + +#[test] +fn a_lut_file_created_deleted_or_repaired_renders_again() { + let dir = tempfile::tempdir().unwrap(); + let lut = dir.path().join("later.cube"); + let mut s = session(None); + let comps = shot(&mut s, "Apply Color LUT", &[("lut", json!(lut.to_string_lossy()))]); + assert_all(colours(&s, comps), GREY); + write(&lut, WHITE, 1_000); + assert_all(colours(&s, comps), 1.0); + std::fs::remove_file(&lut).unwrap(); + assert_all(colours(&s, comps), GREY); + write(&lut, "not a LUT", 2_000); + assert_all(colours(&s, comps), GREY); + write(&lut, BLACK, 3_000); + assert_all(colours(&s, comps), 0.0); +} + +#[test] +fn lumetri_follows_its_input_lut_file() { + let dir = tempfile::tempdir().unwrap(); + let lut = dir.path().join("input.cube"); + write(&lut, BLACK, 1_000); + let mut s = session(None); + let comps = shot(&mut s, "Lumetri Color", &[("basicCorrection/inputLut", json!(1)), ("basicCorrection/inputLutFile", json!(lut.to_string_lossy()))]); + assert_all(colours(&s, comps), 0.0); + write(&lut, WHITE, 2_000); + assert_all(colours(&s, comps), 1.0); +} diff --git a/crates/render/src/cache/dependencies.rs b/crates/render/src/cache/dependencies.rs index dc4216098..4d5dfb5e9 100644 --- a/crates/render/src/cache/dependencies.rs +++ b/crates/render/src/cache/dependencies.rs @@ -33,6 +33,8 @@ impl Dependencies<'_> { { for g in fx.groups().take(limit.unwrap_or(usize::MAX)).filter(|g| g.enabled) { self.group(ctx, layer, g, 0)?; + // A LUT file edited on disk changes the pixels without an edit (#3493). + crate::reads::lut_files(ctx, layer, g).hash(self.h); } } self.other_times = previous; diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index b1ec0ca02..900a06e2a 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -757,6 +757,15 @@ impl<'a> Renderer<'a> { return; } let Some(fx) = layer.effects() else { return }; + // The LUT files the stack reads go to this render's files: a frame on disk made with one + // that changed since is not used (#3493). + if let Some(log) = self.reads { + for g in fx.groups().take(limit).filter(|g| g.enabled) { + for f in super::reads::lut_files(ctx, layer, g) { + log.note(f); + } + } + } let lt = layer.layer_time(ctx.time); let layer_size = ctx.effect_bounds(layer).0; // #659 / #1205: an authored layer's buffer spans only its painted content. Effects that diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index ed97e50fd..9021f1e42 100644 --- a/crates/render/src/reads.rs +++ b/crates/render/src/reads.rs @@ -65,6 +65,23 @@ impl ReadFile { } } +/// The LUT files effect `g` of `layer` reads at the context time (Apply Color LUT, Lumetri's +/// Input LUT and Look), each with its identity now. A layer's cache key holds them and a render +/// notes them, so what was made with a file that changed since is not used (#3493). +pub(crate) fn lut_files(ctx: &crate::EvalCtx, layer: &effectcraft_project::Layer, g: &effectcraft_project::PropGroup) -> Vec { + let effectcraft_project::GroupKind::Effect { effect } = &g.kind else { return Vec::new() }; + effectcraft_effects::lut_params(effect) + .iter() + .filter_map(|param| match ctx.value(layer, g.prop(param)?) { + effectcraft_keyframe::Value::Str(src) => { + let path = effectcraft_effects::lut_file(&src)?; + Some(ReadFile::new(path, FileStamp::native(path).unwrap_or(FileStamp::Missing))) + } + _ => None, + }) + .collect() +} + /// At most this many files are listed per render or cached buffer; more mark the list /// incomplete (a comp reading more files than this for one frame is not checked file by file). pub const MAX_READ_FILES: usize = 4096; From a4d09521156328b0e9a6f53c26a889aa8816596f Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 10:51:32 +0530 Subject: [PATCH 13/83] #3087: stop building placeholders once the import's budget is spent A parameter past the budget was skipped and the next one tried, so the rest of the effect, and every later effect without a counterpart, still read its shared definitions and built popup items. The first parameter that does not fit now ends the budget; a later effect without a counterpart is reported on its own line without reading its definitions. The docs now say that a placeholder's layer parameters report their keys and expression. --- crates/aep/src/import/effects.rs | 6 +++ crates/aep/src/import/placeholder.rs | 19 +++++--- crates/aep/tests/it/import/placeholders.rs | 50 ++++++++++++++++++++++ docs/aep-import.md | 6 ++- 4 files changed, 72 insertions(+), 9 deletions(-) diff --git a/crates/aep/src/import/effects.rs b/crates/aep/src/import/effects.rs index 01e704b53..b276c39c0 100644 --- a/crates/aep/src/import/effects.rs +++ b/crates/aep/src/import/effects.rs @@ -92,6 +92,12 @@ pub(crate) fn import_effects<'f, 'a>( } continue; } + if found.is_none() && col.placeholder_cost >= crate::import::placeholder::MAX_COST { + // The import's placeholder budget is spent: the definitions (shared by many instances) + // are not read again. Its own line: grouped, it would read as kept. + col.lose(LossCategory::Effects, format!("{lost}, not kept (past the import's placeholder parameters)")); + continue; + } let params = defs.params(&fx); report_records_without_definition(&fx, ¶ms, cx, &shown, col); let Some((map, spec)) = found else { diff --git a/crates/aep/src/import/placeholder.rs b/crates/aep/src/import/placeholder.rs index 01d845f24..59b0865ac 100644 --- a/crates/aep/src/import/placeholder.rs +++ b/crates/aep/src/import/placeholder.rs @@ -8,11 +8,12 @@ //! The values keep After Effects' units, the ones its expressions read: sliders and angles as //! stored, points in layer pixels, colours RGBA 0..1, checkboxes on / off, popups as EffectCraft's //! 0-based items over the file's items in order (expressions read them 1-based, as After Effects -//! does). Layer parameters name their layer. Paths and arbitrary data are not kept (reported when -//! they hold something). +//! does). Layer parameters name their layer (their keys and expression are reported). Paths and +//! arbitrary data are not kept (reported when they hold something). //! //! The parameters a placeholder holds are bounded per import ([`MAX_COST`]): definitions can be -//! shared by many instances, so a small file could otherwise ask for very many properties. +//! shared by many instances, so a small file could otherwise ask for very many properties. Once +//! the budget is spent, later effects without a counterpart are reported without a placeholder. use effectcraft_keyframe::Value; use effectcraft_project::build::Ids; @@ -44,8 +45,6 @@ pub(crate) fn placeholder( let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()); for p in params.iter().filter(|p| !carries_nothing(p)) { if col.placeholder_cost >= MAX_COST { - // Once the budget is spent nothing more is built (definitions shared by many instances - // would otherwise still be walked item by item). col.lose(LossCategory::Effects, format!("{here}: parameters past the import's {MAX_COST} placeholder parameters not kept")); break; } @@ -65,8 +64,14 @@ pub(crate) fn placeholder( } let cost = col.placeholder_cost.saturating_add(items).saturating_add(1); if cost > MAX_COST { - col.lose(LossCategory::Effects, format!("{here}: parameter {label} not kept (past the import's {MAX_COST} placeholder parameters)")); - continue; + // The budget is spent: nothing more is built, here or in later effects (definitions + // shared by many instances would otherwise still be walked item by item). + col.lose( + LossCategory::Effects, + format!("{here}: parameter {label} and the ones after it not kept (past the import's {MAX_COST} placeholder parameters)"), + ); + col.placeholder_cost = MAX_COST; + break; } col.placeholder_cost = cost; let mut prop = Property::new(ids.alloc(), ¶m_id(p), p.name.trim(), default).with_ui(ui); diff --git a/crates/aep/tests/it/import/placeholders.rs b/crates/aep/tests/it/import/placeholders.rs index 9afccd6b9..ee119869f 100644 --- a/crates/aep/tests/it/import/placeholders.rs +++ b/crates/aep/tests/it/import/placeholders.rs @@ -153,6 +153,56 @@ fn a_hostile_placeholder_stays_bounded() { assert!(losses(&r, LossCategory::Effects, "Big Fx").iter().any(|d| d.contains("placeholder parameters"))); } +/// Two instances of an effect whose parameters fill the import's budget: the first keeps what fits +/// and stops at the first parameter past it; the second is reported without a placeholder (its +/// shared definitions are not read again). +#[test] +fn an_effect_past_the_spent_budget_gets_no_placeholder() { + let items: &'static [&'static str] = Box::leak((0..1000).map(|i| &*Box::leak(format!("I{i}").into_boxed_str())).collect::>().into_boxed_slice()); + let fx = Fx { match_name: "Big Fx", name: "Big", defs: (0..300).map(|_| popup("P", 1, items)).collect(), values: vec![], data: vec![], keys: vec![] }; + let bytes = twice(&bytes_with(&fx), "Big Fx"); + let mut project = effectcraft_project::Project::default(); + let none = |_: &str| false; + let r = effectcraft_aep::import::import( + &mut project, + &bytes, + &effectcraft_aep::import::ImportOptions { allow_losses: true, ..effectcraft_aep::import::ImportOptions::new(&none) }, + ) + .unwrap(); + let placeholders: Vec = project + .comps() + .flat_map(|(_, c)| c.layers.iter()) + .filter_map(|l| l.props.sub("effects")) + .flat_map(|fx| fx.children.iter().filter_map(|n| n.as_group()).filter(|g| g.match_id == "Big Fx").map(|g| g.props().count()).collect::>()) + .collect(); + // 199 popups of 1000 items (1001 each) fit in 200 000; the 200th stops the first instance. + assert_eq!(placeholders, [199]); + let found = losses(&r, LossCategory::Effects, "Big Fx"); + assert_eq!(found.iter().filter(|d| d.contains("and the ones after it not kept")).count(), 1, "{found:?}"); + assert!(found.iter().any(|d| d.contains("not kept (past the import's placeholder parameters)")), "{found:?}"); +} + +/// `bytes` with the layer's instance of `match_name` (its `tdmn` and `sspc`) repeated after it. +fn twice(bytes: &[u8], match_name: &str) -> Vec { + let mut file = parse(bytes).unwrap(); + let mut done = 0; + edit(&mut file.chunks, false, &mut |c, in_project_copy| { + let Body::List { children, .. } = &mut c.body else { return }; + if in_project_copy { + return; + } + let Some(at) = children.iter().position(|k| k.is(b"tdmn") && k.bytes().is_some_and(|b| b.split(|x| *x == 0).next() == Some(match_name.as_bytes()))) + else { + return; + }; + let pair: Vec> = children[at..at + 2].to_vec(); + children.splice(at + 2..at + 2, pair); + done += 1; + }); + assert_eq!(done, 1, "one instance"); + write(&file).unwrap() +} + /// `bytes` with the expression `text` on the parameter record `param` (enabled: `tdb4` byte 120 /// 1, docs/aep-format.md 3.6). fn with_expression(bytes: &[u8], param: &str, text: &str) -> Vec { diff --git a/docs/aep-import.md b/docs/aep-import.md index bd7ffa21d..e76468962 100644 --- a/docs/aep-import.md +++ b/docs/aep-import.md @@ -325,14 +325,16 @@ parameter gets the file's value: in After Effects, each with its value, keys and expression, in the units After Effects' expressions read (sliders and angles as stored, points in layer pixels, colours, checkboxes, popups over the file's items with separators, read 1-based; layer parameters name their layer, - without a record the layer itself as for Layer Control), + without a record the layer itself as for Layer Control, and their keys and expression are + reported), so expressions that read them (`effect("Settings")("Speed")`) keep working. A parameter's id is its match name (`CC Cylinder-0003`), or `param` when that name is no path segment (a pseudo effect's `Pseudo/0.25-0001`). Paths and arbitrary data are not kept; a popup whose definition is borrowed, or whose default slot holds no item, and that has no value record takes its first item (reported). One import keeps at most 200 000 placeholder parameters and popup items (a popup at most 1024 items); the rest is - reported. A placeholder is still reported in `effects` and counted in + reported, and once that is spent a later effect without a counterpart arrives without a + placeholder (reported). A placeholder is still reported in `effects` and counted in `imported.placeholderEffects`; .aep export reports it and leaves it out. ## What is reported From cd08781aab3210103793549b3a4565d1aa7a63d7 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 10:56:39 +0530 Subject: [PATCH 14/83] #3456: keep Warp Stabilizer and 3D Camera Tracker analyses saved before 0.23 Their keys were compared only with today's signature, so the first edit of a project saved by 0.22 (even adding it to the render queue, as effectcraft-cli render does) cleared both analyses and queued them again, and lost them when the footage was offline. One check, warp::key_matches, now accepts a key made from today's signature or from the one 0.22 wrote for the same frames, and keeps it. Warp Stabilizer, the 3D Camera Tracker and Roto Brush all use it. The regression test opens a project saved by the released 0.22.0 CLI. --- ATTRIBUTION.md | 1 + crates/engine/src/analysis/camera_track.rs | 13 +- crates/engine/src/analysis/roto.rs | 8 +- crates/engine/src/analysis/warp.rs | 14 +- .../src/tests/fixtures/tracked-0.22.ecproj | 1593 +++++++++++++++++ .../fixtures/tracked-0.22.ecproj.attribution | 8 + .../engine/src/tests/legacy_analysis_keys.rs | 76 + 7 files changed, 1700 insertions(+), 13 deletions(-) create mode 100644 crates/engine/src/tests/fixtures/tracked-0.22.ecproj create mode 100644 crates/engine/src/tests/fixtures/tracked-0.22.ecproj.attribution diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index b463e79ea..3aa429a53 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -134,6 +134,7 @@ configuration from these Apache-2.0 projects: | Asset | Author | Source | Licence | |---|---|---|---| | `crates/engine/src/tests/fixtures/object-matte-0.22.ecproj` | lisn0 | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | +| `crates/engine/src/tests/fixtures/tracked-0.22.ecproj` | arnav-hiwarkar | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | ## First-party brand marks diff --git a/crates/engine/src/analysis/camera_track.rs b/crates/engine/src/analysis/camera_track.rs index 29961f533..d6a79b791 100644 --- a/crates/engine/src/analysis/camera_track.rs +++ b/crates/engine/src/analysis/camera_track.rs @@ -124,8 +124,17 @@ fn str_of(g: &PropGroup, m: &str) -> String { /// What a tracker's tracks are made from: the layer's frames and Detailed Analysis. fn tracks_key(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> String { + tracks_key_of(signature(project, cid, l), g) +} + +fn tracks_key_of(signature: String, g: &PropGroup) -> String { let detailed = effectcraft_effects::warp_stab::param(&static_params(g), "advanced/detailedAnalysis").is_some_and(Value::as_bool); - format!("{}{}", signature(project, cid, l), if detailed { "+detailed" } else { "" }) + format!("{signature}{}", if detailed { "+detailed" } else { "" }) +} + +/// Whether the tracker's saved tracks are made from the layer's current frames and settings. +fn tracks_match(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> bool { + crate::warp::key_matches(project, cid, l, &str_of(g, TRACKS_KEY), |s| tracks_key_of(s, g)) } /// Parameters of an instance from static values (the tracker's settings are not animated). @@ -165,7 +174,7 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId, let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id)); for g in fx.groups().filter(|g| is_tracker(g)) { let tracked = !str_of(g, TRACKS).is_empty(); - if tracked && str_of(g, TRACKS_KEY) != tracks_key(after, *cid, l, g) { + if tracked && !tracks_match(after, *cid, l, g) { clears.push((*cid, l.id, g.uid, true)); todo.push((*cid, l.id, g.uid)); } else if tracked && str_of(g, SOLVE_KEY) != ct::solve_key(&ct::settings(&static_params(g))) { diff --git a/crates/engine/src/analysis/roto.rs b/crates/engine/src/analysis/roto.rs index 246c8899c..89d3e1609 100644 --- a/crates/engine/src/analysis/roto.rs +++ b/crates/engine/src/analysis/roto.rs @@ -222,12 +222,6 @@ pub fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String { input_key_with_signature(crate::warp::signature(p, comp, layer), layer, uid) } -/// Recognize the input key serialized before 0.23 without re-keying its frozen matte. -fn input_key_before_placed_page(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> Option { - let signature = crate::warp::signature_before_placed_page(p, comp, layer)?; - Some(input_key_with_signature(signature, layer, uid)) -} - fn input_key_with_signature(mut s: String, layer: &Layer, uid: Uid) -> String { if let Some(m) = layer.masks() { s.push_str(&format!("{m:?}")); @@ -258,7 +252,7 @@ pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerI let old = before.comp(*cid).and_then(|bc| bc.layer(l.id)).and_then(|ol| ol.props.find_group(g.uid)); let saved_key = str_of(g, INPUT_KEY); // Keep a matching old key: the frozen cache itself also hashes that key. - if saved_key != key && input_key_before_placed_page(after, *cid, l, g.uid).as_deref() != Some(saved_key.as_str()) { + if !crate::warp::key_matches(after, *cid, l, &saved_key, |s| input_key_with_signature(s, l, g.uid)) { set.push((*cid, l.id, g.uid, key)); todo.push((*cid, l.id, g.uid)); } else if old.is_none_or(|o| guard_of(o) != guard_of(g)) { diff --git a/crates/engine/src/analysis/warp.rs b/crates/engine/src/analysis/warp.rs index b88d9df38..20b88d45d 100644 --- a/crates/engine/src/analysis/warp.rs +++ b/crates/engine/src/analysis/warp.rs @@ -122,9 +122,16 @@ pub fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String { signature_with_source(p, comp, layer, &src) } +/// Whether `saved`, a key an analysis of `layer` was saved with, is for the layer's current frames. +/// `key` makes such a key from a signature. A key made from the signature an earlier release wrote +/// for the same frames matches too: keep it rather than rewrite it (analysing writes today's). +pub(crate) fn key_matches(p: &Project, comp: ItemId, layer: &Layer, saved: &str, key: impl Fn(String) -> String) -> bool { + key(signature(p, comp, layer)) == saved || signature_before_placed_page(p, comp, layer).is_some_and(|s| key(s) == saved) +} + /// Before `Footage::placed_page` was added in 0.23, the persisted signature hashed the -/// same Debug representation without that last field. Only ordinary footage can match it. -pub(crate) fn signature_before_placed_page(p: &Project, comp: ItemId, layer: &Layer) -> Option { +/// same footage text without that last field. Only ordinary footage can match it. +fn signature_before_placed_page(p: &Project, comp: ItemId, layer: &Layer) -> Option { let LayerSource::Footage { item } = &layer.source else { return None }; let ItemKind::Footage(footage) = &p.item(*item)?.kind else { return None }; if footage.placed_page { @@ -256,11 +263,10 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId, if !fx.groups().any(is_warp) { continue; } - let sig = signature(after, *cid, l); let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id)); for g in fx.groups().filter(|g| is_warp(g)) { let analysed = !str_of(g, ANALYSIS).is_empty(); - if analysed && str_of(g, ANALYSIS_KEY) != sig { + if analysed && !key_matches(after, *cid, l, &str_of(g, ANALYSIS_KEY), |s| s) { clear.push((*cid, l.id, g.uid)); todo.push((*cid, l.id, g.uid)); } else if !analysed && old_layer.and_then(|ol| ol.props.find_group(g.uid)).is_none() { diff --git a/crates/engine/src/tests/fixtures/tracked-0.22.ecproj b/crates/engine/src/tests/fixtures/tracked-0.22.ecproj new file mode 100644 index 000000000..8e1d21b40 --- /dev/null +++ b/crates/engine/src/tests/fixtures/tracked-0.22.ecproj @@ -0,0 +1,1593 @@ +{ + "savedBy": "0.22.0", + "activeComp": 2, + "openComps": [ + 2 + ], + "schema": 2, + "settings": { + "bit_depth": "Bpc8", + "linearize": false, + "working_space": null, + "blend_linear": false, + "time_display": "Timecode", + "frame_start": 0, + "audio_sample_rate": 48000, + "gpu_acceleration": true, + "color_engine": "Adobe", + "hdr": "Clip", + "output_space": null, + "working_gamma": 2.2 + }, + "items": { + "1": { + "id": 1, + "name": "effectcraft-3456-shake.mp4", + "label": "Aqua", + "comment": "", + "parent": null, + "kind": { + "type": "Footage", + "path": "/tmp/effectcraft-3456-shake.mp4", + "kind": "Video", + "width": 160, + "height": 120, + "pixel_aspect": 1.0, + "frame_rate": { + "num": 12, + "den": 1 + }, + "native_rate": null, + "duration": 254016000000, + "has_video": true, + "has_audio": false, + "alpha": "Ignore", + "premul_color": [ + 0.0, + 0.0, + 0.0 + ], + "loop_count": 1, + "codec": "H.264 (High)", + "missing": false, + "color_profile": "Rec709" + } + }, + "2": { + "id": 2, + "name": "effectcraft-3456-shake", + "label": "Sandstone", + "comment": "", + "parent": null, + "kind": { + "type": "Comp", + "width": 160, + "height": 120, + "pixel_aspect": 1.0, + "frame_rate": { + "num": 12, + "den": 1 + }, + "duration": 254016000000, + "display_start": 0, + "background": [ + 0.0, + 0.0, + 0.0 + ], + "work_area": [ + 0, + 254016000000 + ], + "layers": [ + { + "id": 3, + "name": "effectcraft-3456-shake.mp4", + "source": { + "type": "Footage", + "item": 1 + }, + "label": "Aqua", + "comment": "", + "start_time": 0, + "in_point": 0, + "out_point": 254016000000, + "stretch": 100.0, + "switches": { + "video": true, + "audio": true, + "solo": false, + "locked": false, + "shy": false, + "collapse": false, + "quality": "Best", + "sampling": "Bilinear", + "effects": true, + "frame_blend": "Off", + "motion_blur": false, + "adjustment": false, + "three_d": false, + "guide": false + }, + "blend_mode": "Normal", + "preserve_transparency": false, + "track_matte": null, + "parent": null, + "markers": [], + "auto_orient": "Off", + "props": { + "uid": 4, + "match": "layer", + "name": "effectcraft-3456-shake.mp4", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Group", + "uid": 5, + "match": "masks", + "name": "Masks", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [] + }, + { + "node": "Group", + "uid": 6, + "match": "effects", + "name": "Effects", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Group", + "uid": 26, + "match": "ec.distort.warpstabilizer", + "name": "Warp Stabilizer", + "kind": { + "kind": "Effect", + "effect": "ec.distort.warpstabilizer" + }, + "enabled": true, + "children": [ + { + "node": "Group", + "uid": 28, + "match": "stabilization", + "name": "Stabilization", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 27, + "match": "result", + "name": "Result", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Smooth Motion", + "No Motion" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 29, + "match": "smoothness", + "name": "Smoothness", + "value": { + "t": "Scalar", + "v": 50.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 100.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 30, + "match": "method", + "name": "Method", + "value": { + "t": "Enum", + "v": 3 + }, + "ui": { + "kind": "Popup", + "options": [ + "Position", + "Position, Scale, Rotation", + "Perspective", + "Subspace Warp" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 31, + "match": "preserveScale", + "name": "Preserve Scale", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Group", + "uid": 33, + "match": "borders", + "name": "Borders", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 32, + "match": "framing", + "name": "Framing", + "value": { + "t": "Enum", + "v": 2 + }, + "ui": { + "kind": "Popup", + "options": [ + "Stabilize Only", + "Stabilize, Crop", + "Stabilize, Crop, Auto-scale", + "Stabilize, Synthesize Edges" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Group", + "uid": 35, + "match": "autoScale", + "name": "Auto-scale", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 34, + "match": "maximumScale", + "name": "Maximum Scale", + "value": { + "t": "Scalar", + "v": 150.0 + }, + "ui": { + "kind": "Slider", + "min": 100.0, + "max": 1000.0, + "slider_min": 100.0, + "slider_max": 200.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 36, + "match": "actionSafeMargin", + "name": "Action-safe Margin", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 45.0, + "slider_min": 0.0, + "slider_max": 20.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Prop", + "uid": 37, + "match": "additionalScale", + "name": "Additional Scale", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 1.0, + "max": 1000.0, + "slider_min": 50.0, + "slider_max": 150.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Group", + "uid": 39, + "match": "advanced", + "name": "Advanced", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 38, + "match": "detailedAnalysis", + "name": "Detailed Analysis", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 40, + "match": "rollingShutterRipple", + "name": "Rolling Shutter Ripple", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Automatic Reduction", + "Enhanced Reduction" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 41, + "match": "cropLessSmoothMore", + "name": "Crop Less <-> Smooth More", + "value": { + "t": "Scalar", + "v": 50.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 100.0, + "slider_min": 0.0, + "slider_max": 100.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 42, + "match": "synthesizeInputRange", + "name": "Synthesis Input Range (seconds)", + "value": { + "t": "Scalar", + "v": 1.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 10.0, + "slider_min": 0.0, + "slider_max": 5.0, + "decimals": 2 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 43, + "match": "synthesizeEdgeFeather", + "name": "Synthesis Edge Feather", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 100.0, + "slider_min": 0.0, + "slider_max": 100.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Group", + "uid": 45, + "match": "edgeCropping", + "name": "Synthesis Edge Cropping", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 44, + "match": "left", + "name": "Left", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 50.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 46, + "match": "top", + "name": "Top", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 50.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 47, + "match": "right", + "name": "Right", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 50.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 48, + "match": "bottom", + "name": "Bottom", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 50.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Prop", + "uid": 49, + "match": "hideWarningBanner", + "name": "Hide Warning Banner", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 50, + "match": "showTrackPoints", + "name": "Show Track Points", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 51, + "match": "trackPointSize", + "name": "Track Point Size", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 200.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Prop", + "uid": 52, + "match": "analysis", + "name": "Analysis", + "value": { + "t": "Str", + "v": "{\"version\":2,\"start\":0.0,\"frameDuration\":0.08333333333333333,\"size\":[160.0,120.0],\"detailed\":false,\"frames\":[{\"t\":[0.0,0.0],\"s\":[1.0,0.0,0.0,0.0],\"h\":[1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0],\"inliers\":0,\"features\":0},{\"t\":[-22.388798410890686,30.01868418985143],\"s\":[0.9277781961008736,-0.04422418749279422,-15.523833932787909,35.6091856999425],\"h\":[0.9277781961008736,0.04422418749279422,-15.523833932787909,-0.04422418749279422,0.9277781961008736,35.6091856999425,0.0,0.0],\"inliers\":9,\"features\":15,\"points\":[[92.3,107.9],[95.2,95.7],[92.2,103.7],[74.2,53.6],[74.3,37.4],[99.3,90.7],[82.6,41.5],[82.5,55.5],[88.5,43.5]]},{\"t\":[23.98122532957055,-1.9084399677775892],\"s\":[0.9063620953625465,-0.04409531016401132,30.797313797392007,5.599646102270199],\"h\":[0.7965841302132126,0.29995334448297317,20.168498543438005,-0.0740592055495628,1.046481410433727,-0.473260319309297,-0.002014895402579317,0.0023197947752658875],\"inliers\":10,\"features\":24,\"points\":[[118.4,97.1],[124.8,102.9],[100.5,51.5],[127.3,63.9],[127.5,45.0],[106.1,39.6],[106.2,53.7],[113.7,56.7],[52.5,35.6],[116.8,43.6]]},{\"t\":[11.687620662467452,-7.932031814223215],\"s\":[0.9951636472613027,0.0038103578382923703,12.438092774450126,-8.118641076572445],\"h\":[1.643484923435082,-0.7137632860918511,-2.5905208024072124,0.3548180400361871,0.46037059943190983,-10.538467107984474,0.004219805542554225,-0.0059212698862967],\"inliers\":9,\"features\":18,\"points\":[[132.6,73.5],[131.5,85.1],[106.5,41.5],[138.4,70.5],[143.4,74.0],[112.0,43.6],[122.5,47.5],[130.2,49.8],[149.3,58.5]]},{\"t\":[-30.310403914516613,33.907848152443364],\"s\":[1.007168616747288,0.0037069147029014813,-31.056396618707396,33.11324659331262],\"h\":[0.6198845159470996,0.0005618559126509149,-3.178267007922358,-0.13009530252511717,0.7726770220834841,43.55009577470153,-0.001720398359559105,0.00004737533435711085],\"inliers\":6,\"features\":6,\"points\":[[83.4,78.4],[111.5,91.5],[111.5,72.5],[89.0,80.3],[94.7,83.3],[92.1,67.5]]},{\"t\":[-5.583259809628714,-21.883441966142215],\"s\":[1.0031742036915483,-0.0014807972400717364,-6.0689262496146625,-22.023221544860448],\"h\":[1.1420296883900174,-0.04739597390990014,-10.605302345116598,0.09741208494601904,0.9834838974219691,-26.601790074159226,0.0009113645792746124,-0.0004613682942006241],\"inliers\":12,\"features\":26,\"points\":[[44.4,0.4],[95.7,91.4],[102.5,90.5],[96.9,82.3],[102.8,85.5],[102.6,81.2],[97.1,78.5],[127.8,90.7],[128.5,80.1],[108.6,91.2],[108.5,79.5],[105.0,77.7]]},{\"t\":[27.686733462643232,8.049769635251877],\"s\":[0.929460928303922,0.035973851378530715,35.6798165298027,9.23027450987749],\"h\":[1.008918148822829,0.1261308536278953,23.55178846805191,-0.030309790827892834,1.108836841709476,6.4896286706810855,-0.0005830225271129425,0.0013957761568033347],\"inliers\":9,\"features\":24,\"points\":[[55.5,112.5],[100.6,55.5],[100.6,69.5],[106.2,57.5],[106.1,71.6],[113.5,74.5],[76.4,61.6],[76.6,45.5],[116.6,61.6]]},{\"t\":[-2.1632428252979565,18.033956762750776],\"s\":[0.9823494564274133,-0.03858067520697906,-3.292485287213367,25.146037618301847],\"h\":[0.9579598760613574,-0.13114734456280325,2.830816183351523,0.009276438160611545,0.8429238585075404,27.816268384517308,0.00010866570427004524,-0.0010986404477924933],\"inliers\":9,\"features\":25,\"points\":[[10.2,63.8],[4.5,45.5],[53.4,60.9],[106.6,83.4],[106.6,97.6],[58.5,80.5],[71.6,85.4],[76.7,86.4],[112.4,85.5]]},{\"t\":[-30.66640840418232,-21.989852679037867],\"s\":[1.0156367307051672,0.004551071962152525,-31.763785052482092,-23.691591888755113],\"h\":[1.0156367307051672,-0.004551071962152525,-31.763785052482092,0.004551071962152525,1.0156367307051672,-23.691591888755113,0.0,0.0],\"inliers\":6,\"features\":9,\"points\":[[65.6,55.5],[68.5,58.4],[76.3,61.6],[58.5,55.9],[78.5,77.7],[43.4,48.3]]},{\"t\":[5.708740901092206,24.075281194659254],\"s\":[1.0135826886534363,-0.10515588147251018,-1.1163514746928627,27.59825643107368],\"h\":[1.1505001196625904,-0.004492526279963958,-0.5319258967829654,-0.025738957694540945,0.966887539263372,28.15190307627249,0.0007845902586792284,-0.00031935492918067597],\"inliers\":9,\"features\":24,\"points\":[[104.6,97.7],[104.8,101.6],[108.5,88.8],[103.9,89.0],[116.1,92.7],[112.4,87.8],[113.2,96.3],[47.3,72.5],[46.4,87.5]]},{\"t\":[27.779201319161004,9.926771642811133],\"s\":[0.9890321818477387,0.0013711446087583204,28.575284295787874,10.772618168795788],\"h\":[1.061498205619746,0.009950102807178602,26.602191497678987,0.03562744518371215,1.0470570180393335,7.3128067380884545,0.00040746752749711983,0.00013875206582740715],\"inliers\":19,\"features\":31,\"points\":[[101.5,91.5],[100.5,107.5],[95.4,104.6],[93.2,89.4],[62.5,94.4],[108.2,95.5],[108.2,109.3],[114.0,97.5],[89.2,102.5],[61.5,75.5],[70.5,80.5],[89.3,88.3],[114.9,111.1],[69.5,95.5],[66.5,78.5],[82.3,100.6],[76.5,82.5],[82.5,84.4],[119.1,112.0]]},{\"t\":[-18.08353148330616,-15.925984647541327],\"s\":[0.9665330472023047,-0.007772653084006622,-14.505725243709165,-11.14686987633948],\"h\":[1.396312496581232,-0.10268053165320767,-33.15101241390654,0.021275151660258673,1.173514724589782,-24.185902320422414,0.001847437675107323,-0.0003034312788189646],\"inliers\":9,\"features\":23,\"points\":[[119.3,75.5],[116.5,84.0],[121.6,82.9],[128.5,87.4],[127.6,83.0],[124.8,80.6],[128.7,71.5],[71.6,86.5],[58.4,66.5]]}],\"tracks\":[{\"id\":0,\"start\":0,\"pts\":[[121.5,16.5],[101.4,48.2],[127.2,46.6],[141.2,40.2],[111.2,74.3],[105.1,58.7],[135.1,68.5]]},{\"id\":1,\"start\":0,\"pts\":[[107.5,26.5],[85.4,56.6],[108.9,54.9],[121.0,46.9],[90.3,80.7],[82.3,64.9],[109.6,73.1],[105.7,97.1]]}]}" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 53, + "match": "analysisKey", + "name": "Analysis Key", + "value": { + "t": "Str", + "v": "f87b8df2e353c28e" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Group", + "uid": 54, + "match": "ec.perspective.cameratracker", + "name": "3D Camera Tracker", + "kind": { + "kind": "Effect", + "effect": "ec.perspective.cameratracker" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 55, + "match": "shotType", + "name": "Shot Type", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Fixed Angle of View", + "Variable Zoom", + "Specify Angle of View" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 56, + "match": "horizontalAngleOfView", + "name": "Horizontal Angle of View", + "value": { + "t": "Scalar", + "v": 40.0 + }, + "ui": { + "kind": "Slider", + "min": 1.0, + "max": 170.0, + "slider_min": 10.0, + "slider_max": 120.0, + "decimals": 1 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 57, + "match": "showTrackPoints", + "name": "Show Track Points", + "value": { + "t": "Enum", + "v": 1 + }, + "ui": { + "kind": "Popup", + "options": [ + "2D Source", + "3D Solved" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 58, + "match": "renderTrackPoints", + "name": "Render Track Points", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 59, + "match": "trackPointSize", + "name": "Track Point Size", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 1000.0, + "slider_min": 0.0, + "slider_max": 300.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 60, + "match": "targetSize", + "name": "Target Size", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 1.0, + "max": 1000.0, + "slider_min": 10.0, + "slider_max": 300.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Group", + "uid": 62, + "match": "advanced", + "name": "Advanced", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 61, + "match": "solveMethod", + "name": "Solve Method", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Auto Detect", + "Typical", + "Mostly Flat Scene", + "Tripod Pan" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 63, + "match": "methodUsed", + "name": "Method Used", + "value": { + "t": "Str", + "v": "Tripod Pan" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 64, + "match": "averageError", + "name": "Average Error", + "value": { + "t": "Scalar", + "v": 0.48427435472856495 + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 65, + "match": "detailedAnalysis", + "name": "Detailed Analysis", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 66, + "match": "lensDistortion", + "name": "Solve Lens Distortion", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 67, + "match": "undistort", + "name": "Undistort Footage", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 68, + "match": "autoDeletePoints", + "name": "Auto-delete Points Across Time", + "value": { + "t": "Bool", + "v": true + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 69, + "match": "hideWarningBanner", + "name": "Hide Warning Banner", + "value": { + "t": "Bool", + "v": false + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Prop", + "uid": 70, + "match": "tracks", + "name": "Tracks", + "value": { + "t": "Str", + "v": "{\"version\":1,\"size\":[160.0,120.0],\"start\":0.0,\"frameDuration\":0.08333333333333333,\"frames\":12,\"factor\":1.0,\"detailed\":false,\"tracks\":[{\"id\":0,\"start\":0,\"pts\":[[77.5,21.5],[63.0,42.02],[84.44,46.2],[94.51,43.46],[76.29,65.76],[77.07,73.7],[83.0,80.68],[85.69,85.86],[87.92,90.96],[89.4,99.49],[90.13,103.45],[90.97,109.78]]},{\"id\":1,\"start\":0,\"pts\":[[137.5,41.5],[125.34,65.53],[144.58,68.06],[155.96,64.9],[137.55,87.17]]},{\"id\":2,\"start\":0,\"pts\":[[103.5,9.5],[85.74,29.12],[104.73,32.21],[110.44,21.58],[92.15,43.67]]},{\"id\":3,\"start\":0,\"pts\":[[104.5,29.5],[85.9,50.12],[103.93,52.29],[109.88,48.47],[92.18,70.78]]},{\"id\":4,\"start\":0,\"pts\":[[135.5,18.5],[123.93,41.77],[143.14,45.58],[156.62,36.13],[137.86,58.99],[138.18,64.4],[142.35,72.76]]},{\"id\":5,\"start\":0,\"pts\":[[145.5,43.5],[136.49,68.62],[152.24,70.07]]},{\"id\":6,\"start\":0,\"pts\":[[68.5,16.5],[54.6,38.04],[75.81,40.97],[85.89,39.76],[67.52,62.45],[65.27,69.0]]},{\"id\":7,\"start\":0,\"pts\":[[126.5,18.5],[111.0,39.74],[128.76,42.63],[136.89,32.11],[117.68,54.39]]},{\"id\":8,\"start\":1,\"pts\":[[62.5,17.5],[85.58,22.87],[94.22,13.25],[75.42,35.02],[75.53,43.03],[82.19,51.59],[83.63,56.75],[86.42,64.01],[88.28,72.0],[89.17,76.16],[88.59,83.65]]},{\"id\":9,\"start\":1,\"pts\":[[114.5,106.5],[136.85,100.86],[147.03,92.4]]},{\"id\":10,\"start\":1,\"pts\":[[72.5,23.5],[97.31,29.7],[103.74,19.02],[85.16,40.96],[87.87,50.25],[90.99,56.84],[95.55,64.14],[94.95,69.09],[98.79,80.06],[99.53,84.17],[96.16,89.83]]},{\"id\":11,\"start\":1,\"pts\":[[105.5,56.5],[123.21,58.51],[130.67,54.61],[112.22,76.63],[107.86,82.64],[110.99,88.56],[110.29,92.35],[107.8,96.22],[105.42,105.58],[106.34,109.09],[103.49,114.69]]},{\"id\":12,\"start\":1,\"pts\":[[48.5,14.5],[74.56,20.81],[80.17,10.47],[60.5,31.52]]},{\"id\":13,\"start\":1,\"pts\":[[56.5,17.5],[79.51,23.22],[88.21,13.13],[69.38,34.7],[69.5,43.04],[76.12,50.88],[77.6,55.88],[80.34,63.05],[82.34,69.83],[83.23,74.02],[82.59,80.86]]},{\"id\":14,\"start\":1,\"pts\":[[111.5,56.5],[129.28,58.38],[136.92,54.94]]},{\"id\":15,\"start\":2,\"pts\":[[111.5,35.5],[116.71,24.74],[98.61,46.94],[95.39,52.62],[97.78,59.24]]},{\"id\":16,\"start\":2,\"pts\":[[111.5,54.5],[116.45,50.61],[98.85,72.82],[95.85,78.52],[98.15,84.77]]},{\"id\":17,\"start\":2,\"pts\":[[35.5,25.5],[51.37,25.98],[29.35,47.25],[34.79,58.33],[37.82,64.46],[35.7,68.67]]},{\"id\":18,\"start\":2,\"pts\":[[65.5,37.5],[73.16,34.37],[53.32,56.61]]},{\"id\":19,\"start\":3,\"pts\":[[139.5,91.5],[121.67,103.33],[122.29,98.68],[128.91,94.42],[130.04,88.08],[132.48,82.73],[132.69,85.66],[135.56,80.73],[133.86,80.34]]},{\"id\":20,\"start\":3,\"pts\":[[128.5,27.5],[109.77,49.81],[105.68,55.33]]},{\"id\":21,\"start\":4,\"pts\":[[132.5,108.5],[134.61,103.06],[139.18,98.97]]},{\"id\":22,\"start\":4,\"pts\":[[12.5,44.5],[15.77,54.38],[21.97,62.49],[23.19,67.31],[25.95,73.59],[32.15,76.64],[31.59,80.8],[37.46,83.52]]},{\"id\":23,\"start\":5,\"pts\":[[88.5,76.5],[91.53,82.49],[96.99,88.67],[96.31,92.35]]},{\"id\":24,\"start\":5,\"pts\":[[23.5,26.5],[34.16,36.76],[31.29,40.39]]},{\"id\":25,\"start\":5,\"pts\":[[29.5,29.5],[41.15,39.45],[37.02,43.33],[44.0,51.94]]},{\"id\":26,\"start\":5,\"pts\":[[16.5,25.5],[25.23,35.61],[24.0,39.41],[27.82,47.95],[34.62,50.88],[34.62,55.8],[39.37,61.06]]},{\"id\":27,\"start\":5,\"pts\":[[12.5,21.5],[20.78,30.91],[20.0,35.48],[23.13,42.77],[30.29,46.76],[30.38,51.79],[34.65,56.39]]},{\"id\":28,\"start\":5,\"pts\":[[115.5,82.5],[118.64,88.43],[118.09,93.19],[117.39,96.49],[114.83,106.78],[114.88,110.08]]},{\"id\":29,\"start\":5,\"pts\":[[122.5,61.5],[124.31,67.9],[123.88,72.08],[123.44,76.68],[120.82,86.9],[120.84,90.61],[117.85,97.98]]},{\"id\":30,\"start\":5,\"pts\":[[120.5,66.5],[122.86,72.98],[122.45,77.21],[121.98,81.49]]},{\"id\":31,\"start\":7,\"pts\":[[130.5,110.5],[132.07,103.93],[132.1,107.25],[134.31,101.57],[134.08,101.95]]},{\"id\":32,\"start\":7,\"pts\":[[144.5,87.5],[147.64,81.13],[147.29,84.43]]},{\"id\":33,\"start\":7,\"pts\":[[149.5,87.5],[151.62,81.15],[151.6,83.45]]},{\"id\":34,\"start\":7,\"pts\":[[141.5,109.5],[142.65,102.86],[144.73,106.45]]},{\"id\":35,\"start\":7,\"pts\":[[130.5,105.5],[132.21,97.98],[132.16,101.56]]},{\"id\":36,\"start\":7,\"pts\":[[46.5,46.5],[46.28,52.04],[53.71,58.71],[53.81,63.25]]},{\"id\":37,\"start\":7,\"pts\":[[63.5,78.5],[60.78,82.81],[61.38,87.33],[61.18,91.39],[60.13,92.98]]},{\"id\":38,\"start\":7,\"pts\":[[147.5,79.5],[148.79,73.74],[148.89,76.93],[152.13,71.83],[150.74,73.15]]},{\"id\":39,\"start\":8,\"pts\":[[110.5,73.5],[108.69,82.44],[109.4,86.46],[105.45,92.92]]},{\"id\":40,\"start\":8,\"pts\":[[37.5,75.5],[39.63,77.92],[39.24,82.09],[46.3,85.66]]},{\"id\":41,\"start\":9,\"pts\":[[72.5,92.5],[72.19,96.59],[71.1,99.0]]},{\"id\":42,\"start\":9,\"pts\":[[71.5,66.5],[71.58,70.65],[69.4,74.61]]},{\"id\":43,\"start\":9,\"pts\":[[42.5,52.5],[42.63,57.29],[48.81,63.22]]},{\"id\":44,\"start\":9,\"pts\":[[65.5,63.5],[65.9,67.71],[62.84,71.25]]},{\"id\":45,\"start\":9,\"pts\":[[54.5,84.5],[54.33,88.51],[54.49,89.47]]},{\"id\":46,\"start\":9,\"pts\":[[93.5,108.5],[94.19,112.24],[95.37,117.47]]}]}" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 71, + "match": "tracksKey", + "name": "Tracks Key", + "value": { + "t": "Str", + "v": "f87b8df2e353c28e" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 72, + "match": "solve", + "name": "Solve", + "value": { + "t": "Str", + "v": "{\"version\":1,\"size\":[160.0,120.0],\"start\":0.0,\"frameDuration\":0.08333333333333333,\"shot\":\"fixedAngle\",\"methodUsed\":\"tripodPan\",\"averageError\":0.48427435472856495,\"frames\":[{\"rot\":[0.0,0.0,0.0],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.020706432791589117,-0.008075142299053078,-0.06077723052316193],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.023015120128512003,0.005766803085062508,-0.05310541732098104],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.0170200841043793,0.014154804924310056,-0.050762146721755434],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.03356753265765158,-0.00032501028659040183,-0.05939089867356119],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.03943129932097289,0.0005848011077747351,-0.08866812978617226],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.04587385659719372,0.00556317017360105,-0.0922903070481816],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.04943028885690781,0.006586719185689197,-0.1030177435734751],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.05420648867299307,0.008981748111204299,-0.12219539780340982],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.06013167434751454,0.009061063842010806,-0.02749230328481726],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.06324873745045556,0.009255262692673143,-0.0355321639175462],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true},{\"rot\":[-0.06618656945718411,0.009319774678589094,-0.015189163276848288],\"center\":[0.0,0.0,0.0],\"focal\":1307.4062971457863,\"solved\":true}],\"points\":[{\"id\":0,\"pos\":[-0.001884543346613208,-0.029037452307042782,0.9806051370981879],\"error\":0.56470084,\"first\":0,\"last\":11},{\"id\":1,\"pos\":[0.04710854544038102,-0.015334858559503525,1.0773487523110807],\"error\":0.4844214,\"first\":0,\"last\":4},{\"id\":2,\"pos\":[0.015277830948334362,-0.04530698241035739,1.0393293228690133],\"error\":0.3392279,\"first\":0,\"last\":4},{\"id\":3,\"pos\":[0.013625157539074177,-0.028048508549162222,1.005205908477461],\"error\":0.27458376,\"first\":0,\"last\":4},{\"id\":4,\"pos\":[0.04631029390834158,-0.03435434088491794,1.0740657193502177],\"error\":0.58201736,\"first\":0,\"last\":6},{\"id\":5,\"pos\":[0.053943894461564695,-0.013610066623604573,1.082119350918587],\"error\":0.33030823,\"first\":0,\"last\":2},{\"id\":6,\"pos\":[-0.008886582549498147,-0.03423365291632946,1.0500072858529375],\"error\":0.5071384,\"first\":0,\"last\":5},{\"id\":7,\"pos\":[0.03502079415367347,-0.03650999899856251,1.0590501262399414],\"error\":0.3427207,\"first\":0,\"last\":4},{\"id\":8,\"pos\":[-0.0010752140340087664,-0.05237350807489353,0.9970760865042246],\"error\":0.35491616,\"first\":1,\"last\":11},{\"id\":9,\"pos\":[0.04045532180900739,0.011287908043101045,1.1118602867055563],\"error\":0.35821888,\"first\":1,\"last\":3},{\"id\":12,\"pos\":[-0.012247058383356772,-0.05711454082770741,1.026095977383411],\"error\":0.7576372,\"first\":1,\"last\":4},{\"id\":13,\"pos\":[-0.0057782770174717585,-0.05312155593792027,1.002454847850506],\"error\":0.543182,\"first\":1,\"last\":11},{\"id\":14,\"pos\":[0.03444063369446883,-0.02322488536327569,1.0525377480568132],\"error\":0.5363785,\"first\":1,\"last\":3},{\"id\":15,\"pos\":[0.016549051463405264,-0.04448675703801009,1.039611880351983],\"error\":0.31473064,\"first\":2,\"last\":6},{\"id\":16,\"pos\":[0.015561268129555224,-0.024177980474891878,1.0505609541603724],\"error\":0.448273,\"first\":2,\"last\":6},{\"id\":17,\"pos\":[-0.037387500298151244,-0.046978366490905726,1.0292596184739917],\"error\":0.5814284,\"first\":2,\"last\":7},{\"id\":18,\"pos\":[-0.018963958767977365,-0.03840654941654895,1.029868839109744],\"error\":0.62771547,\"first\":2,\"last\":4},{\"id\":20,\"pos\":[0.025824410036239483,-0.04221331533850395,1.051265936102142],\"error\":0.2203965,\"first\":3,\"last\":5},{\"id\":22,\"pos\":[-0.04851356310948073,-0.04922371159135405,1.0148030992016972],\"error\":0.60021263,\"first\":4,\"last\":11},{\"id\":23,\"pos\":[0.0036124978633337353,-0.027413664985930772,0.9671987963193897],\"error\":0.2763749,\"first\":5,\"last\":8},{\"id\":24,\"pos\":[-0.040597577069465214,-0.0703196502868751,1.0235859186232383],\"error\":0.20348576,\"first\":5,\"last\":7},{\"id\":26,\"pos\":[-0.04416469175733074,-0.0698384544617488,1.0211428377131564],\"error\":0.7978787,\"first\":5,\"last\":11},{\"id\":27,\"pos\":[-0.04818954744569584,-0.07416243876625056,1.013378662747375],\"error\":0.6526291,\"first\":5,\"last\":11},{\"id\":36,\"pos\":[-0.02865646311969018,-0.06261471940209673,1.0103266984710924],\"error\":0.47229937,\"first\":7,\"last\":10},{\"id\":37,\"pos\":[-0.022363582487320836,-0.038494993762751006,0.9688013952945587],\"error\":0.5830236,\"first\":7,\"last\":11},{\"id\":39,\"pos\":[0.012856414034624068,-0.040629816490058715,0.9569374661053799],\"error\":0.26666406,\"first\":8,\"last\":11},{\"id\":40,\"pos\":[-0.039487212277480116,-0.04718518517554586,0.9962321113853498],\"error\":0.48472655,\"first\":8,\"last\":11},{\"id\":41,\"pos\":[-0.014270376399443,-0.03389203058278074,0.9480752077612952],\"error\":0.79931283,\"first\":9,\"last\":11},{\"id\":42,\"pos\":[-0.014596706636024855,-0.05446828640367654,0.9808373411559306],\"error\":0.021755833,\"first\":9,\"last\":11},{\"id\":43,\"pos\":[-0.03666075088242092,-0.06654420263172509,0.9970944504474955],\"error\":0.20362298,\"first\":9,\"last\":11},{\"id\":44,\"pos\":[-0.01908451035407613,-0.057350036080083884,0.9896103813509345],\"error\":0.18076603,\"first\":9,\"last\":11},{\"id\":45,\"pos\":[-0.028179725825267236,-0.04186664641926184,0.9918891096090983],\"error\":0.24652581,\"first\":9,\"last\":11},{\"id\":46,\"pos\":[0.0010670642752641536,-0.018463010859931878,0.8064992130555431],\"error\":0.7289736,\"first\":9,\"last\":11}]}" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 73, + "match": "solveKey", + "name": "Solve Key", + "value": { + "t": "Str", + "v": "FixedAngle||Auto|[]" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 74, + "match": "deleted", + "name": "Deleted Points", + "value": { + "t": "Str", + "v": "" + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 75, + "match": "camera", + "name": "Camera Layer", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Hidden" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + } + ] + }, + { + "node": "Group", + "uid": 15, + "match": "transform", + "name": "Transform", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 7, + "match": "anchor", + "name": "Anchor Point", + "value": { + "t": "Vec3", + "v": [ + 80.0, + 60.0, + 0.0 + ] + }, + "ui": { + "kind": "Point" + }, + "spatial": true, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 2, + "static_only": false + }, + { + "node": "Prop", + "uid": 8, + "match": "position", + "name": "Position", + "value": { + "t": "Vec3", + "v": [ + 80.0, + 60.0, + 0.0 + ] + }, + "ui": { + "kind": "Point" + }, + "spatial": true, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 2, + "static_only": false + }, + { + "node": "Prop", + "uid": 9, + "match": "scale", + "name": "Scale", + "value": { + "t": "Vec3", + "v": [ + 100.0, + 100.0, + 100.0 + ] + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 2, + "static_only": false + }, + { + "node": "Prop", + "uid": 10, + "match": "orientation", + "name": "Orientation", + "value": { + "t": "Vec3", + "v": [ + 0.0, + 0.0, + 0.0 + ] + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": true, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 11, + "match": "rotationX", + "name": "X Rotation", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": true, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 12, + "match": "rotationY", + "name": "Y Rotation", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": true, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 13, + "match": "rotation", + "name": "Rotation", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 14, + "match": "opacity", + "name": "Opacity", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Slider", + "min": 0.0, + "max": 100.0, + "slider_min": 0.0, + "slider_max": 100.0, + "decimals": 0 + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + }, + { + "node": "Group", + "uid": 16, + "match": "materialOptions", + "name": "Material Options", + "kind": { + "kind": "Plain" + }, + "enabled": true, + "children": [ + { + "node": "Prop", + "uid": 17, + "match": "castsShadows", + "name": "Casts Shadows", + "value": { + "t": "Enum", + "v": 0 + }, + "ui": { + "kind": "Popup", + "options": [ + "Off", + "On", + "Only" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 18, + "match": "lightTransmission", + "name": "Light Transmission", + "value": { + "t": "Scalar", + "v": 0.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 19, + "match": "acceptsShadows", + "name": "Accepts Shadows", + "value": { + "t": "Enum", + "v": 1 + }, + "ui": { + "kind": "Popup", + "options": [ + "Off", + "On", + "Only" + ] + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 20, + "match": "acceptsLights", + "name": "Accepts Lights", + "value": { + "t": "Bool", + "v": true + }, + "ui": { + "kind": "Checkbox" + }, + "spatial": false, + "hold_only": true, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 21, + "match": "ambient", + "name": "Ambient", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 22, + "match": "diffuse", + "name": "Diffuse", + "value": { + "t": "Scalar", + "v": 50.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 23, + "match": "specularIntensity", + "name": "Specular Intensity", + "value": { + "t": "Scalar", + "v": 50.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 24, + "match": "specularShininess", + "name": "Specular Shininess", + "value": { + "t": "Scalar", + "v": 5.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + { + "node": "Prop", + "uid": 25, + "match": "metal", + "name": "Metal", + "value": { + "t": "Scalar", + "v": 100.0 + }, + "ui": { + "kind": "Percent" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + ] + } + ] + } + } + ], + "markers": [], + "shutter_angle": 180.0, + "shutter_phase": -90.0, + "motion_blur_samples": 16, + "motion_blur_adaptive_limit": 128, + "renderer": "Classic3D", + "hide_shy": false, + "enable_motion_blur": true, + "enable_frame_blending": true, + "draft_3d": false, + "preserve_frame_rate": false, + "preserve_resolution": false, + "poster_time": 0, + "global_light": { + "angle": { + "uid": 0, + "match": "globalLightAngle", + "name": "Global Light Angle", + "value": { + "t": "Scalar", + "v": 120.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + }, + "altitude": { + "uid": 0, + "match": "globalLightAltitude", + "name": "Global Light Altitude", + "value": { + "t": "Scalar", + "v": 30.0 + }, + "ui": { + "kind": "Angle" + }, + "spatial": false, + "hold_only": false, + "three_d_only": false, + "two_d_only": false, + "shown_dims": 0, + "static_only": false + } + } + } + } + }, + "next_id": 76 +} \ No newline at end of file diff --git a/crates/engine/src/tests/fixtures/tracked-0.22.ecproj.attribution b/crates/engine/src/tests/fixtures/tracked-0.22.ecproj.attribution new file mode 100644 index 000000000..611f620f9 --- /dev/null +++ b/crates/engine/src/tests/fixtures/tracked-0.22.ecproj.attribution @@ -0,0 +1,8 @@ +asset: tracked-0.22.ecproj +title: One clip with an analysed Warp Stabilizer and 3D Camera Tracker from EffectCraft 0.22.0 +author: arnav-hiwarkar +source: original work +license: MIT OR Apache-2.0 +license-file: ../../../../../LICENSE-MIT +added: 2026-11-12 by arnav-hiwarkar +notes: Saved by the released 0.22.0 CLI after importing a generated 160x120, 12-frame shaking crop of an ffmpeg testsrc2 pattern, applying both effects and analysing them. The source path is a generic test path; the video is not needed by the tests, which only check that the saved analyses are kept or cleared. diff --git a/crates/engine/src/tests/legacy_analysis_keys.rs b/crates/engine/src/tests/legacy_analysis_keys.rs index f4e442050..95f789968 100644 --- a/crates/engine/src/tests/legacy_analysis_keys.rs +++ b/crates/engine/src/tests/legacy_analysis_keys.rs @@ -1,6 +1,82 @@ //! Warp Stabilizer and 3D Camera Tracker analyses saved by an earlier release keep matching //! their footage after an edit that doesn't change it (#3456), and a real change still clears them. +use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY}; +use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY}; +use effectcraft_keyframe::Value; +use effectcraft_project::{ItemId, LayerId, Project}; +use serde_json::json; + +use crate::Session; + +const FOOTAGE: ItemId = ItemId(1); +const COMP: ItemId = ItemId(2); +const CLIP: LayerId = LayerId(3); +const WARP: u64 = 26; +const TRACKER: u64 = 54; + +/// The analysis (as its length and a hash: it's long) and key of the Warp Stabilizer and the +/// 3D Camera Tracker. +fn saved(s: &Session) -> [(usize, u64, String); 2] { + use std::hash::{Hash, Hasher}; + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let get = |uid: u64, data: &str, key: &str| { + let params = crate::camera_track::static_params(layer.props.find_group(uid).unwrap()); + let text = |id: &str| match params.get(id) { + Some(Value::Str(s)) => s.clone(), + other => panic!("{id}: {other:?}"), + }; + let analysis = text(data); + let mut h = std::collections::hash_map::DefaultHasher::new(); + analysis.hash(&mut h); + (analysis.len(), h.finish(), text(key)) + }; + [get(WARP, ANALYSIS, ANALYSIS_KEY), get(TRACKER, TRACKS, TRACKS_KEY)] +} + +fn open(json: &str) -> Session { + let mut s = Session::default(); + s.replace_project(Project::from_json(json).unwrap(), None); + s.open_comp(COMP); + s +} + +#[test] +fn analyses_saved_by_0_22_survive_edits_that_keep_their_frames() { + // Saved by the released 0.22.0 CLI after analysing both effects; its footage is offline here. + let mut s = open(include_str!("fixtures/tracked-0.22.ecproj")); + let before = saved(&s); + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + for (len, _, key) in &before { + assert!(*len > 0); + // The key predates Footage::placed_page, so it isn't today's signature. + assert_ne!(key, &crate::warp::signature(&s.project, COMP, layer)); + } + + // Adding to the render queue edits the project, as `effectcraft-cli render` does. + s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap(); + assert_eq!(saved(&s), before); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + + // Saved and reopened (by this version), the old keys are kept and still match. + let mut s = open(&s.project.to_json()); + s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap(); + assert_eq!(saved(&s), before); + + // Other frames, from other timing or a reinterpreted footage item: both analyses are + // cleared, and undo brings them back. + let cleared = |s: &Session| saved(s).iter().all(|(len, _, key)| *len == 0 && key.is_empty()); + s.execute_checked("layer.timing", json!({"layer": CLIP.0, "out": 0.5})).unwrap(); + assert!(cleared(&s)); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + s.execute_checked("file.interpretFootage", json!({"items": [FOOTAGE.0], "invertAlpha": true})).unwrap(); + assert!(cleared(&s)); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); +} + /// The footage text analysis keys are hashed from, as 0.23 saved it. A new `Footage` field must /// not change it (or every saved analysis is dropped again). #[test] From e36e25512d16d802a16cd164c0ce193912854544 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 10:56:40 +0530 Subject: [PATCH 15/83] #3456: solve again from 3D Camera Tracker tracks saved before 0.23 Analysing a tracker reused its saved tracks only when their key was today's, so solving a 0.22 project again (after a Solve Method change) tracked the footage again, and failed when it was offline. --- crates/engine/src/analysis/camera_track.rs | 2 +- .../engine/src/tests/legacy_analysis_keys.rs | 22 ++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/analysis/camera_track.rs b/crates/engine/src/analysis/camera_track.rs index d6a79b791..378f42dd1 100644 --- a/crates/engine/src/analysis/camera_track.rs +++ b/crates/engine/src/analysis/camera_track.rs @@ -334,7 +334,7 @@ impl Session { let key = tracks_key(&self.project, comp, l, g); let settings = ct::settings(¶ms); let solve_key = ct::solve_key(&settings); - let tracks = ct::tracks(¶ms).filter(|_| str_of(g, TRACKS_KEY) == key); + let tracks = ct::tracks(¶ms).filter(|_| tracks_match(&self.project, comp, l, g)); let n = times.len(); let work = CamWork { project: self.project.clone(), diff --git a/crates/engine/src/tests/legacy_analysis_keys.rs b/crates/engine/src/tests/legacy_analysis_keys.rs index 95f789968..291188a17 100644 --- a/crates/engine/src/tests/legacy_analysis_keys.rs +++ b/crates/engine/src/tests/legacy_analysis_keys.rs @@ -1,7 +1,7 @@ //! Warp Stabilizer and 3D Camera Tracker analyses saved by an earlier release keep matching //! their footage after an edit that doesn't change it (#3456), and a real change still clears them. -use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY}; +use effectcraft_effects::camera_tracker::{SOLVE, TRACKS, TRACKS_KEY}; use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY}; use effectcraft_keyframe::Value; use effectcraft_project::{ItemId, LayerId, Project}; @@ -77,6 +77,26 @@ fn analyses_saved_by_0_22_survive_edits_that_keep_their_frames() { assert_eq!(saved(&s), before); } +/// Solving again reuses the 0.22 tracks rather than tracking the (here offline) footage again. +#[test] +fn camera_tracker_solves_again_from_tracks_saved_by_0_22() { + let mut s = open(include_str!("fixtures/tracked-0.22.ecproj")); + let tracks = saved(&s)[1].clone(); + let solve = |s: &Session| { + let g = s.project.comp(COMP).unwrap().layer(CLIP).unwrap().props.find_group(TRACKER).unwrap(); + crate::camera_track::static_params(g).get(SOLVE).cloned().unwrap() + }; + // Another solve method, and back, clears the solve and keeps the tracks. + for method in [1, 0] { + s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "effects/#2/advanced/solveMethod", "value": method})).unwrap(); + } + assert_eq!(solve(&s), Value::Str(String::new())); + assert_eq!(saved(&s)[1], tracks); + s.execute_checked("camera.analyze", json!({"layer": CLIP.0, "effect": TRACKER, "wait": true})).unwrap(); + assert!(matches!(solve(&s), Value::Str(v) if !v.is_empty())); + assert_eq!(saved(&s)[1], tracks); +} + /// The footage text analysis keys are hashed from, as 0.23 saved it. A new `Footage` field must /// not change it (or every saved analysis is dropped again). #[test] From 98b8e69f7ff997e1c28d19a4a661d68499b7e41c Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 11:00:10 +0530 Subject: [PATCH 16/83] #3087: name each effect the placeholder budget skips A skipped instance was reported through the capped detail list, so past 20 effect losses it was only counted. It now goes through the per-effect grouping under a key of its own, so it is named like any effect without a counterpart and is not merged into a kept instance's line. --- crates/aep/src/import/effects.rs | 6 ++++-- crates/aep/tests/it/import/placeholders.rs | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/import/effects.rs b/crates/aep/src/import/effects.rs index b276c39c0..45ea70840 100644 --- a/crates/aep/src/import/effects.rs +++ b/crates/aep/src/import/effects.rs @@ -94,8 +94,10 @@ pub(crate) fn import_effects<'f, 'a>( } if found.is_none() && col.placeholder_cost >= crate::import::placeholder::MAX_COST { // The import's placeholder budget is spent: the definitions (shared by many instances) - // are not read again. Its own line: grouped, it would read as kept. - col.lose(LossCategory::Effects, format!("{lost}, not kept (past the import's placeholder parameters)")); + // are not read again. Named like any effect without a counterpart, in a group of its + // own (with the kept instances it would read as kept). + let key = format!("{} (not kept)", fx.match_name()); + col.lose_unmapped_effect(&key, format!("{lost}, not kept (past the import's placeholder parameters)")); continue; } let params = defs.params(&fx); diff --git a/crates/aep/tests/it/import/placeholders.rs b/crates/aep/tests/it/import/placeholders.rs index ee119869f..afa323065 100644 --- a/crates/aep/tests/it/import/placeholders.rs +++ b/crates/aep/tests/it/import/placeholders.rs @@ -180,6 +180,7 @@ fn an_effect_past_the_spent_budget_gets_no_placeholder() { let found = losses(&r, LossCategory::Effects, "Big Fx"); assert_eq!(found.iter().filter(|d| d.contains("and the ones after it not kept")).count(), 1, "{found:?}"); assert!(found.iter().any(|d| d.contains("not kept (past the import's placeholder parameters)")), "{found:?}"); + assert!(found.iter().any(|d| d.contains("kept without rendering") && !d.contains("more like it")), "the kept instance alone: {found:?}"); } /// `bytes` with the layer's instance of `match_name` (its `tdmn` and `sspc`) repeated after it. From 21665966259c27c1d039a10719a43f7dbb7cf789 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 11:01:32 +0530 Subject: [PATCH 17/83] #3493: drop the viewer's frames once a LUT file in use changes Renders now follow a LUT file, but the viewer and RAM preview kept the frames already rendered with the old one. A small worker stamps the LUT files in use every two seconds and wakes the interface when one changed; the interface then drops its frames, and a frame whose render started before the change is not kept when it finishes. --- crates/engine/src/footage.rs | 1 + crates/engine/src/footage/lut_reload.rs | 84 +++++++++++++++++++++++++ crates/engine/src/lib.rs | 1 + crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/frame.rs | 15 +++++ crates/ui-egui/src/frames.rs | 15 ++++- crates/ui-egui/src/frames/tests.rs | 23 +++++++ crates/ui-egui/src/lib.rs | 4 ++ 8 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/footage/lut_reload.rs diff --git a/crates/engine/src/footage.rs b/crates/engine/src/footage.rs index b921dd128..d64afcaf7 100644 --- a/crates/engine/src/footage.rs +++ b/crates/engine/src/footage.rs @@ -1,6 +1,7 @@ pub mod doc_path; pub mod footage_check; pub mod footage_reload; +pub mod lut_reload; pub mod media_browser; pub mod media_cache; pub mod sequence; diff --git a/crates/engine/src/footage/lut_reload.rs b/crates/engine/src/footage/lut_reload.rs new file mode 100644 index 000000000..96cb14c4a --- /dev/null +++ b/crates/engine/src/footage/lut_reload.rs @@ -0,0 +1,84 @@ +//! LUT files that change on disk (#3493). +//! +//! A render follows a LUT file by itself: [`effectcraft_effects::load_lut`] stamps the file and +//! reads it again once it changed, and a layer's cache key holds the stamp. What the desktop app +//! keeps of earlier renders, the frames of its viewer and RAM preview, is dropped when +//! [`effectcraft_effects::lut_generation`] moves. The [`Watcher`] looks at the LUT files in use +//! every two seconds, so an edit shows without anything rendering first, and wakes the interface +//! only when one changed. + +use std::sync::mpsc::{RecvTimeoutError, SyncSender}; +use std::time::Duration; + +/// Moves each time a LUT file in use was found changed on disk: frames rendered before may show +/// the old LUT ([`effectcraft_effects::lut_generation`]). +pub fn generation() -> u64 { + effectcraft_effects::lut_generation() +} + +/// How often the LUT files in use are stamped. +pub const INTERVAL: Duration = Duration::from_secs(2); + +/// A worker thread that stamps the LUT files in use ([`effectcraft_effects::check_lut_files`]) +/// and runs `wake` when one changed. Dropping the watcher ends the thread. +pub struct Watcher { + _stop: SyncSender<()>, +} + +impl Watcher { + /// Start the worker. `None` where there are no threads (the web app, whose LUTs don't come + /// from files) or one couldn't be started. + pub fn start(wake: impl Fn() + Send + 'static) -> Option { + Self::start_with(wake, INTERVAL) + } + + /// [`Watcher::start`] stamping every `every` (tests). + pub fn start_with(wake: impl Fn() + Send + 'static, every: Duration) -> Option { + if cfg!(target_arch = "wasm32") { + return None; + } + let (tx, rx) = std::sync::mpsc::sync_channel::<()>(1); + std::thread::Builder::new() + .name("lut-watch".into()) + .spawn(move || { + let mut seen = effectcraft_effects::lut_generation(); + // (ends once the watcher, the only sender, is dropped) + while let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(every) { + let now = effectcraft_effects::check_lut_files(); + if now != seen { + seen = now; + wake(); + } + } + }) + .ok()?; + Some(Watcher { _stop: tx }) + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + /// A LUT file edited on disk wakes the interface without a render loading it. + #[test] + fn an_edited_lut_file_wakes_the_interface() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("watched.cube"); + std::fs::write(&path, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap(); + let src = path.to_string_lossy().into_owned(); + assert!(effectcraft_effects::load_lut(&src).is_some()); + let before = effectcraft_effects::lut_generation(); + let (tx, rx) = std::sync::mpsc::channel(); + let _watcher = Watcher::start_with( + move || { + let _ = tx.send(()); + }, + Duration::from_millis(10), + ) + .unwrap(); + std::fs::write(&path, "LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n").unwrap(); + rx.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!(effectcraft_effects::lut_generation() > before); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f8edfbe08..0b7608756 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -61,6 +61,7 @@ pub use effectcraft_track as track; pub use footage::doc_path; pub use footage::footage_check; pub use footage::footage_reload; +pub use footage::lut_reload; pub use footage::media_browser; pub use footage::media_cache; pub use footage::sequence; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 66387bc31..bf5964ba6 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -97,6 +97,8 @@ impl EffectcraftApp { gpu_failure_applied: None, footage_watcher: None, footage_watch_key: None, + lut_watcher: None, + lut_generation: effectcraft_engine::lut_reload::generation(), device_lost_close: None, dialog_answers: std::sync::mpsc::channel(), file_dialogs: FileDialogsUp::default(), diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index c3a5bfbf6..c76e3f410 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -654,6 +654,21 @@ impl EffectcraftApp { ctx.request_repaint_after(std::time::Duration::from_secs(10)); } self.tick_footage_reload(ctx); + self.tick_lut_files(ctx); + } + + /// A LUT file in use changed on disk (#3493): the frames kept were rendered with the old one. + /// Renders read it again by themselves; the watcher wakes the interface when no render did. + fn tick_lut_files(&mut self, ctx: &egui::Context) { + if self.lut_watcher.is_none() { + let wake = ctx.clone(); + self.lut_watcher = effectcraft_engine::lut_reload::Watcher::start(move || wake.request_repaint()); + } + let generation = effectcraft_engine::lut_reload::generation(); + if generation != self.lut_generation { + self.lut_generation = generation; + self.frames.clear_stale(); + } } /// One background worker tracks source availability and optional content reloads. It wakes diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index a0c2f94b5..ccc4123d2 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -298,6 +298,9 @@ struct Cache { playhead: Option, /// Scale of the frame on screen (the newest urgent request): frames of other scales go first. scale: Option, + /// Frames whose render started before this are not kept: a source file they read changed + /// since ([`Frames::clear_stale`]). + stale_before: Option, } impl Cache { @@ -768,7 +771,7 @@ impl Frames { #[cfg(target_arch = "wasm32")] let queue = Queue::default(); Frames { - cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, gpu_bytes: 0, budget: 3 << 30, gpu_budget: GPU_BUDGET, gpu_pressure: None, gpu_adjusted: None, playhead: None, scale: None })), + cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, gpu_bytes: 0, budget: 3 << 30, gpu_budget: GPU_BUDGET, gpu_pressure: None, gpu_adjusted: None, playhead: None, scale: None, stale_before: None })), inflight: Arc::new(Mutex::new(HashSet::new())), queue: Arc::new(Mutex::new(queue)), #[cfg(not(target_arch = "wasm32"))] @@ -1403,6 +1406,15 @@ impl Frames { } } + /// Drop every frame, and the ones still rendering when they finish: a source file changed on + /// disk (a LUT file, #3493), and a render that started before may have read the old one. + pub fn clear_stale(&self) { + self.clear(); + if let Ok(mut c) = self.cache.lock() { + c.stale_before = Some(web_time::Instant::now()); + } + } + /// The playing preview's position (`None` when no preview plays): prefetch renders the /// frames it reaches first before the others, evictions spare the frames it shows next, and /// queued prefetch frames of its series it no longer reaches are dropped (#595). @@ -1899,6 +1911,7 @@ impl Worker { } if let Ok(mut c) = self.cache.lock() && (!img.is_gpu() || !self.gpu_retired.load(Ordering::Acquire)) + && c.stale_before.is_none_or(|at| t0 >= at) { c.insert_with(key, img, files, since); } diff --git a/crates/ui-egui/src/frames/tests.rs b/crates/ui-egui/src/frames/tests.rs index 45398de21..d6bf56a20 100644 --- a/crates/ui-egui/src/frames/tests.rs +++ b/crates/ui-egui/src/frames/tests.rs @@ -218,6 +218,29 @@ fn retirement_reaches_existing_workers_and_keeps_cpu_frames_and_completion_live( assert!(frames.queue.lock().unwrap().running.is_empty()); } +/// #3493: a LUT file changed on disk drops the frames kept, and a frame whose render started +/// before is not kept when it finishes (it may have read the old file); one started after is. +#[test] +fn clear_stale_drops_kept_frames_and_ones_rendering() { + let frames = Frames::default(); + let worker = frames.worker(); + let kept = key(1, 0, 0); + insert(&frames, kept); + let (late, fresh) = (key(1, 1, 0), key(1, 2, 0)); + let started = web_time::Instant::now(); + frames.clear_stale(); + assert!(!frames.is_cached(&kept)); + for k in [late, fresh] { + frames.inflight.lock().unwrap().insert(k); + frames.queue.lock().unwrap().running.insert(k); + } + worker.finish_key(late, false, img(), None, None, started); + assert!(!frames.is_cached(&late), "a render started before the change"); + worker.finish_key(fresh, false, img(), None, None, web_time::Instant::now()); + assert!(frames.is_cached(&fresh), "a render started after it"); + assert_eq!(frames.inflight(), 0, "both jobs are released"); +} + fn key(content: u64, frame: i64, opts: u64) -> FrameKey { FrameKey { revision: content, content, comp: 1, frame, scale: 1000, view: 0, opts } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2e911ea54..699f68e0f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -373,6 +373,10 @@ pub struct EffectcraftApp { footage_watcher: Option, /// The project revision and preference the watched set was last computed for. footage_watch_key: Option<(u64, String, bool)>, + /// The worker that stamps the LUT files in use ([`Self::tick_lut_files`], #3493). + lut_watcher: Option, + /// The LUT generation the frames kept were rendered at ([`effectcraft_engine::lut_reload::generation`]). + lut_generation: u64, /// The graphics device was lost and the window is closing (see `close_after_device_loss`); /// `true` keeps crash recovery for the next launch. device_lost_close: Option, From 58fcfeb54dad13c0b62a8f80f8a8fc7c5008e083 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 11:04:21 +0530 Subject: [PATCH 18/83] #3456: test that placed-page footage doesn't match a 0.22 key 0.22 keys are hashed without placed_page, so only footage that isn't placed as a page may match them. --- crates/engine/src/tests/legacy_analysis_keys.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/engine/src/tests/legacy_analysis_keys.rs b/crates/engine/src/tests/legacy_analysis_keys.rs index 291188a17..06a05cc77 100644 --- a/crates/engine/src/tests/legacy_analysis_keys.rs +++ b/crates/engine/src/tests/legacy_analysis_keys.rs @@ -75,6 +75,15 @@ fn analyses_saved_by_0_22_survive_edits_that_keep_their_frames() { assert!(cleared(&s)); s.execute_checked("edit.undo", json!({})).unwrap(); assert_eq!(saved(&s), before); + // Footage framed as a placed page has other frames too, though 0.22 had no such field. + s.edit("place page", None, |p, _| { + if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(FOOTAGE).map(|i| &mut i.kind) { + f.placed_page = true; + } + Ok(()) + }) + .unwrap(); + assert!(cleared(&s)); } /// Solving again reuses the 0.22 tracks rather than tracking the (here offline) footage again. From 63aca62574e6ba27db589b9a7751fce9f35f47a3 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 11:13:12 +0530 Subject: [PATCH 19/83] #3493: follow LUT files whose LUT left the cache; bound it by bytes too The watcher stamped only the files whose parsed LUT was still cached, so with more LUTs than the cache keeps, an edit to an evicted one left the viewer's frames stale. The cache now remembers the stamp each LUT file was last read with (bounded separately), and keeps at most 64 LUTs and 512 MiB of tables. Frames finishing while the viewer empties its cache are refused. --- crates/effects/src/utility.rs | 123 ++++++++++++++++++++++++++-------- crates/ui-egui/src/frames.rs | 3 +- 2 files changed, 98 insertions(+), 28 deletions(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index 2c663ebca..1995c2881 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -335,24 +335,63 @@ impl Lut { /// that could not be described). A file whose stamp moved is read again (#3493). type FileStamp = Option<(u64, Option)>; -/// At most this many LUTs (files and inline texts) are kept; the least recently used goes first. -const MAX_CACHED_LUTS: usize = 32; +/// At most this many parsed LUTs (files and inline texts) are kept, and at most +/// [`MAX_CACHED_BYTES`] of them; the least recently used go first. +const MAX_CACHED_LUTS: usize = 64; +const MAX_CACHED_BYTES: usize = 512 << 20; + +/// At most this many LUT files are followed by [`check_lut_files`] beyond the ones whose LUT is +/// kept: the frames made with a LUT that left the cache are still dropped when its file changes. +const MAX_FOLLOWED_FILES: usize = 1024; /// A parsed LUT (or the failure to parse one) and what it was read from. struct CachedLut { stamp: FileStamp, lut: Option>, used: u64, + /// The parsed tables and the parameter text, counted against [`MAX_CACHED_BYTES`]. + bytes: usize, } -/// [`load_lut`]'s cache, by parameter text. +/// [`load_lut`]'s cache, by parameter text, and the stamp each LUT file was last read with. #[derive(Default)] struct LutCache { map: HashMap, + files: HashMap, clock: u64, + bytes: usize, } -/// How often a cached LUT file was found changed on disk ([`lut_generation`]). +impl LutCache { + /// Forget the LUT kept for `src`. + fn remove(&mut self, src: &str) { + if let Some(e) = self.map.remove(src) { + self.bytes = self.bytes.saturating_sub(e.bytes); + } + } + + /// Note that the file at `path` was read with `stamp`: a different stamp than the last read's + /// means it changed on disk, and frames made before may show the old LUT. + fn read_file(&mut self, path: &str, stamp: FileStamp) { + if self.files.insert(path.to_string(), stamp).is_some_and(|old| old != stamp) { + GENERATION.fetch_add(1, Ordering::AcqRel); + } + if self.files.len() > MAX_FOLLOWED_FILES { + let map = &self.map; + self.files.retain(|p, _| map.keys().any(|src| lut_file(src) == Some(p.as_str()))); + } + } + + /// Keep at most [`MAX_CACHED_LUTS`] LUTs and [`MAX_CACHED_BYTES`], always the one for `keep`. + fn evict(&mut self, keep: &str) { + while self.map.len() > MAX_CACHED_LUTS || (self.bytes > MAX_CACHED_BYTES && self.map.len() > 1) { + let Some(oldest) = self.map.iter().filter(|(k, _)| k.as_str() != keep).min_by_key(|(_, e)| e.used).map(|(k, _)| k.clone()) else { break }; + self.remove(&oldest); + } + } +} + +/// How often a LUT file was found changed on disk ([`lut_generation`]). static GENERATION: AtomicU64 = AtomicU64::new(0); fn lut_cache() -> std::sync::MutexGuard<'static, LutCache> { @@ -388,17 +427,25 @@ pub fn lut_generation() -> u64 { GENERATION.load(Ordering::Acquire) } -/// Look at every LUT file in the cache (one `metadata` call each) and forget the ones that changed -/// on disk since they were read, so the next [`load_lut`] reads them again. Returns -/// [`lut_generation`]. +/// Look at every LUT file read (one `metadata` call each) and forget the LUTs of the ones that +/// changed on disk since, so the next [`load_lut`] reads them again. Returns [`lut_generation`]. pub fn check_lut_files() -> u64 { - let files: Vec<(String, FileStamp)> = lut_cache().map.iter().filter_map(|(src, e)| Some((lut_file(src)?.to_string(), e.stamp))).collect(); + let files: Vec<(String, FileStamp)> = lut_cache().files.iter().map(|(p, s)| (p.clone(), *s)).collect(); // (stamped without the lock: a file on a slow share must not hold up renders) - let changed: Vec = files.into_iter().filter(|(path, stamp)| file_stamp(path) != *stamp).map(|(path, _)| path).collect(); + let changed: Vec<(String, FileStamp, FileStamp)> = + files.into_iter().filter_map(|(path, old)| Some(file_stamp(&path)).filter(|now| *now != old).map(|now| (path, old, now))).collect(); if !changed.is_empty() { let mut c = lut_cache(); - c.map.retain(|src, _| lut_file(src).is_none_or(|p| !changed.iter().any(|c| c == p))); - GENERATION.fetch_add(1, Ordering::AcqRel); + for (path, old, now) in changed { + // (a render that read the file meanwhile has noted its new stamp already) + if c.files.get(&path) == Some(&old) { + let stale: Vec = c.map.keys().filter(|src| lut_file(src) == Some(path.as_str())).cloned().collect(); + for src in stale { + c.remove(&src); + } + c.read_file(&path, now); + } + } } lut_generation() } @@ -413,19 +460,17 @@ pub fn load_lut(src: &str) -> Option> { } let file = lut_file(src); let stamp = file.and_then(file_stamp); - let seen = { + { let mut c = lut_cache(); c.clock += 1; let now = c.clock; - match c.map.get_mut(src) { - Some(e) if e.stamp == stamp => { - e.used = now; - return e.lut.clone(); - } - Some(e) => Some(e.stamp), - None => None, + if let Some(e) = c.map.get_mut(src) + && e.stamp == stamp + { + e.used = now; + return e.lut.clone(); } - }; + } // (read and parsed without the lock; a file written after it was stamped has a newer stamp, // and is read again next time) let lut = match file { @@ -433,16 +478,17 @@ pub fn load_lut(src: &str) -> Option> { None => parse_cube(src), } .map(Arc::new); + let tables = lut.as_ref().map_or(0, |l| l.d1.len().saturating_add(l.d3.len()).saturating_mul(std::mem::size_of::<[f32; 3]>())); + let bytes = tables.saturating_add(src.len()); let mut c = lut_cache(); - if seen.is_some_and(|s| s != stamp) { - GENERATION.fetch_add(1, Ordering::AcqRel); + if let Some(path) = file { + c.read_file(path, stamp); } + c.remove(src); let used = c.clock; - c.map.insert(src.to_string(), CachedLut { stamp, lut: lut.clone(), used }); - while c.map.len() > MAX_CACHED_LUTS { - let Some(oldest) = c.map.iter().min_by_key(|(_, e)| e.used).map(|(k, _)| k.clone()) else { break }; - c.map.remove(&oldest); - } + c.map.insert(src.to_string(), CachedLut { stamp, lut: lut.clone(), used, bytes }); + c.bytes = c.bytes.saturating_add(bytes); + c.evict(src); lut } @@ -656,6 +702,29 @@ mod tests { assert!(lut_cache().map.len() <= MAX_CACHED_LUTS); } assert!(!Arc::ptr_eq(&first, &load_lut(&identity_cube(2)).unwrap()), "the oldest was let go"); + let c = lut_cache(); + assert_eq!(c.bytes, c.map.values().map(|e| e.bytes).sum::(), "the bytes kept add up"); + assert!(c.bytes <= MAX_CACHED_BYTES); + } + + /// A LUT file whose LUT left the cache is still followed: its frames are dropped when it + /// changes, though no render loads it again first. + #[test] + fn a_file_whose_lut_left_the_cache_is_still_followed() { + let dir = std::env::temp_dir().join(format!("ec-fx-3493-evicted-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("old.cube"); + std::fs::write(&path, identity_cube(2)).unwrap(); + let src = path.to_string_lossy().into_owned(); + assert!(load_lut(&src).is_some()); + for i in 0..MAX_CACHED_LUTS + 8 { + assert!(load_lut(&format!("TITLE \"evict {i}\"\n{}", identity_cube(2))).is_some()); + } + assert!(!lut_cache().map.contains_key(&src), "its LUT left the cache"); + std::fs::write(&path, identity_cube(3)).unwrap(); + check_lut_files(); + assert_eq!(lut_cache().files.get(&src), Some(&file_stamp(&src)), "the change was noticed"); + std::fs::remove_dir_all(&dir).unwrap(); } #[test] diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index ccc4123d2..6d99a8cd2 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -1409,10 +1409,11 @@ impl Frames { /// Drop every frame, and the ones still rendering when they finish: a source file changed on /// disk (a LUT file, #3493), and a render that started before may have read the old one. pub fn clear_stale(&self) { - self.clear(); + // (marked first: a frame finishing while the cache is emptied is refused, not kept) if let Ok(mut c) = self.cache.lock() { c.stale_before = Some(web_time::Instant::now()); } + self.clear(); } /// The playing preview's position (`None` when no preview plays): prefetch renders the From 82c2a23f0793c6c0aa1deeaea8aa926336a0cd51 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 11:29:57 +0530 Subject: [PATCH 20/83] #3493: keep following the LUT file just read past the followed-files limit Past 1024 followed files, the trim kept only files with a cached LUT and dropped the one being noted (its LUT is cached right after), so a later edit to it went unnoticed. The tests start from an empty folder. --- crates/effects/src/utility.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index 1995c2881..8d9c38927 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -378,7 +378,7 @@ impl LutCache { } if self.files.len() > MAX_FOLLOWED_FILES { let map = &self.map; - self.files.retain(|p, _| map.keys().any(|src| lut_file(src) == Some(p.as_str()))); + self.files.retain(|p, _| p.as_str() == path || map.keys().any(|src| lut_file(src) == Some(p.as_str()))); } } @@ -644,6 +644,7 @@ mod tests { const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n"; const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n"; let dir = std::env::temp_dir().join(format!("ec-fx-3493-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let write = |name: &str, text: &str, secs: u64| { let path = dir.join(name); @@ -678,6 +679,7 @@ mod tests { #[test] fn check_lut_files_forgets_a_changed_file() { let dir = std::env::temp_dir().join(format!("ec-fx-3493-check-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("grade.cube"); std::fs::write(&path, identity_cube(2)).unwrap(); @@ -695,13 +697,15 @@ mod tests { /// The cache keeps at most [`MAX_CACHED_LUTS`] LUTs, the least recently used going first. #[test] fn the_lut_cache_is_bounded() { - let first = load_lut(&identity_cube(2)).unwrap(); + // (text no other test loads: a load elsewhere would make it recently used) + let oldest = format!("TITLE \"bounded first\"\n{}", identity_cube(2)); + let first = load_lut(&oldest).unwrap(); for i in 0..MAX_CACHED_LUTS + 8 { let text = format!("TITLE \"bounded {i}\"\n{}", identity_cube(2)); assert!(load_lut(&text).is_some()); assert!(lut_cache().map.len() <= MAX_CACHED_LUTS); } - assert!(!Arc::ptr_eq(&first, &load_lut(&identity_cube(2)).unwrap()), "the oldest was let go"); + assert!(!Arc::ptr_eq(&first, &load_lut(&oldest).unwrap()), "the oldest was let go"); let c = lut_cache(); assert_eq!(c.bytes, c.map.values().map(|e| e.bytes).sum::(), "the bytes kept add up"); assert!(c.bytes <= MAX_CACHED_BYTES); @@ -712,6 +716,7 @@ mod tests { #[test] fn a_file_whose_lut_left_the_cache_is_still_followed() { let dir = std::env::temp_dir().join(format!("ec-fx-3493-evicted-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("old.cube"); std::fs::write(&path, identity_cube(2)).unwrap(); @@ -727,6 +732,22 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + /// Past [`MAX_FOLLOWED_FILES`], the file just read is still followed. + #[test] + fn the_file_just_read_stays_followed_past_the_limit() { + let dir = std::env::temp_dir().join(format!("ec-fx-3493-many-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for i in 0..MAX_FOLLOWED_FILES + 8 { + let path = dir.join(format!("{i}.cube")); + std::fs::write(&path, identity_cube(2)).unwrap(); + let src = path.to_string_lossy().into_owned(); + assert!(load_lut(&src).is_some()); + assert!(lut_cache().files.contains_key(&src), "{i}: the file just read"); + } + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn one_d_lut_with_domain() { let lut = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n1 1 1\n0 0 0\n").unwrap(); From d036127bf4076e16af45909c713529284a34aac1 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 11:29:57 +0530 Subject: [PATCH 21/83] #3493: key a layer reading a precomp on the LUT file its override names A precomp instance whose Essential Property names another LUT file renders with that file, but a layer reading the instance through a layer parameter was keyed on the nested comp's own file, so editing the overriding file left that layer cached. --- crates/engine/src/tests/lut_files.rs | 34 +++++++++++++++++++++++++ crates/render/src/cache/dependencies.rs | 11 ++++++++ 2 files changed, 45 insertions(+) diff --git a/crates/engine/src/tests/lut_files.rs b/crates/engine/src/tests/lut_files.rs index 9388e64bd..57d163b36 100644 --- a/crates/engine/src/tests/lut_files.rs +++ b/crates/engine/src/tests/lut_files.rs @@ -152,3 +152,37 @@ fn lumetri_follows_its_input_lut_file() { write(&lut, WHITE, 2_000); assert_all(colours(&s, comps), 1.0); } + +/// A precomp instance whose Essential Property names another LUT file follows that file, also +/// for a layer that reads the instance through a layer parameter. +#[test] +fn an_overridden_lut_file_renders_again() { + let dir = tempfile::tempdir().unwrap(); + let (base, overridden) = (dir.path().join("base.cube"), dir.path().join("override.cube")); + write(&base, WHITE, 1_000); + write(&overridden, BLACK, 1_000); + let mut s = session(None); + s.execute_checked("comp.new", json!({"name": "Grade", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap(); + let grade = s.active_comp_id().unwrap(); + let plate = s.execute_checked("layer.newSolid", json!({"name": "Plate", "color": "#808080", "width": 8, "height": 8})).unwrap()["layer"].clone(); + s.execute_checked("effect.apply", json!({"layer": plate, "effect": "Apply Color LUT"})).unwrap(); + s.execute_checked("prop.set", json!({"layer": plate, "path": "effects/#1/lut", "value": base.to_string_lossy()})).unwrap(); + let control = s.execute_checked("essential.addProperty", json!({"layer": plate, "path": "effects/#1/lut", "name": "LUT"})).unwrap()["controls"][0].clone(); + s.execute_checked("comp.new", json!({"name": "Shot", "width": 8, "height": 8, "frameRate": 24, "duration": 1})).unwrap(); + let shot = s.active_comp_id().unwrap(); + let instance = s.execute_checked("layer.addItem", json!({"item": grade.0})).unwrap()["layer"].clone(); + s.execute_checked("essential.set", json!({"layer": instance, "control": control, "value": overridden.to_string_lossy()})).unwrap(); + let copy = s.execute_checked("layer.newSolid", json!({"name": "Copy", "color": "#00ff00", "width": 8, "height": 8})).unwrap()["layer"].clone(); + s.execute_checked("effect.apply", json!({"layer": copy, "effect": "Set Channels"})).unwrap(); + for i in 1..=3 { + s.execute_checked("prop.set", json!({"layer": copy, "path": format!("effects/#1/sourceLayer{i}"), "value": instance})).unwrap(); + } + let centre = |s: &Session| { + let img = s.render(shot, Tick::ZERO, RenderOpts::default()); + let p = img.get(i64::from(img.width / 2), i64::from(img.height / 2)); + [p[0], p[1], p[0], p[1]] + }; + assert_all(centre(&s), 0.0); + write(&overridden, WHITE, 2_000); + assert_all(centre(&s), 1.0); +} diff --git a/crates/render/src/cache/dependencies.rs b/crates/render/src/cache/dependencies.rs index 4d5dfb5e9..5e8a8845b 100644 --- a/crates/render/src/cache/dependencies.rs +++ b/crates/render/src/cache/dependencies.rs @@ -171,6 +171,17 @@ impl Dependencies<'_> { ItemKind::Comp(comp) => { let time = ctx.source_time(layer); time.0.hash(self.h); + // The nested layers are walked without this instance's Essential + // Properties overrides, which the render applies: a LUT file one of + // them names is read too (#3493). + for o in crate::fx_host::essential_overrides(ctx, layer) { + if let effectcraft_keyframe::Value::Str(src) = &o.value + && let Some(path) = effectcraft_effects::lut_file(src) + { + crate::reads::ReadFile::new(path, crate::reads::FileStamp::native(path).unwrap_or(crate::reads::FileStamp::Missing)) + .hash(self.h); + } + } let nested = EvalCtx::new(ctx.project, item, comp, time); for child in &comp.layers { self.layer(&nested, child)?; From dc3e5245c2ca9a2f1e64a4452d7f3dccb1d3d064 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 11:29:57 +0530 Subject: [PATCH 22/83] #3493: show the frame again in the viewers once a LUT file changes The viewers replace their picture only when the frame key changes, and a frame rendered again after a LUT change had the same key, so the old look stayed on screen. The viewer frame keys carry the LUT generation (in memory only), which also leaves frames still rendering with the old LUT unasked for, so the refusal of late frames is no longer needed. --- crates/engine/src/footage/lut_reload.rs | 8 +++- crates/ui-egui/src/app/frame.rs | 4 +- crates/ui-egui/src/app/viewer_frames.rs | 50 ++++++++++++++++++++++++- crates/ui-egui/src/frames.rs | 16 +------- crates/ui-egui/src/frames/tests.rs | 23 ------------ 5 files changed, 60 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/footage/lut_reload.rs b/crates/engine/src/footage/lut_reload.rs index 96cb14c4a..54211eac0 100644 --- a/crates/engine/src/footage/lut_reload.rs +++ b/crates/engine/src/footage/lut_reload.rs @@ -16,6 +16,12 @@ pub fn generation() -> u64 { effectcraft_effects::lut_generation() } +/// Stamp the LUT files in use now ([`effectcraft_effects::check_lut_files`]): the ones that +/// changed are read again by the next render. Returns [`generation`]. +pub fn check() -> u64 { + effectcraft_effects::check_lut_files() +} + /// How often the LUT files in use are stamped. pub const INTERVAL: Duration = Duration::from_secs(2); @@ -44,7 +50,7 @@ impl Watcher { let mut seen = effectcraft_effects::lut_generation(); // (ends once the watcher, the only sender, is dropped) while let Err(RecvTimeoutError::Timeout) = rx.recv_timeout(every) { - let now = effectcraft_effects::check_lut_files(); + let now = check(); if now != seen { seen = now; wake(); diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index c76e3f410..488b3c5ef 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -659,6 +659,8 @@ impl EffectcraftApp { /// A LUT file in use changed on disk (#3493): the frames kept were rendered with the old one. /// Renders read it again by themselves; the watcher wakes the interface when no render did. + /// The frame keys carry the generation ([`Self::frame_series`]), so the viewers show the + /// frames rendered again, and a frame still rendering with the old LUT is never asked for. fn tick_lut_files(&mut self, ctx: &egui::Context) { if self.lut_watcher.is_none() { let wake = ctx.clone(); @@ -667,7 +669,7 @@ impl EffectcraftApp { let generation = effectcraft_engine::lut_reload::generation(); if generation != self.lut_generation { self.lut_generation = generation; - self.frames.clear_stale(); + self.frames.clear(); } } diff --git a/crates/ui-egui/src/app/viewer_frames.rs b/crates/ui-egui/src/app/viewer_frames.rs index fe3ad8abb..d7c02a99c 100644 --- a/crates/ui-egui/src/app/viewer_frames.rs +++ b/crates/ui-egui/src/app/viewer_frames.rs @@ -128,7 +128,7 @@ impl EffectcraftApp { frame: 0, scale: (scale * 1000.0).round() as u32, view: self.view_hash(comp), - opts: frames::opts_hash(&self.frame_opts(comp, scale)) ^ self.roto_model_stamp(), + opts: frames::opts_hash(&self.frame_opts(comp, scale)) ^ self.roto_model_stamp() ^ self.lut_stamp(), } } @@ -142,6 +142,13 @@ impl EffectcraftApp { h.finish() | 1 } + /// Changes when a LUT file in use changed on disk (#3493): the frame on screen and the ones + /// still rendering were made with the old LUT, so the new ones must not share their keys + /// (the viewers show a frame again only when its key changes). 0 until a LUT file changes. + fn lut_stamp(&self) -> u64 { + self.lut_generation.wrapping_mul(0x9e37_79b9_7f4a_7c15) + } + /// The frame series the viewer of `comp` shows now (its scale, view and options, for the /// comp's current content): what the cache bars count. pub fn shown_series(&self, comp: ItemId) -> FrameKey { @@ -238,3 +245,44 @@ impl EffectcraftApp { request(&self.frames, &self.render_source(), key, comp, t, opts); } } + +#[cfg(test)] +mod tests { + /// #3493: the viewer shows the frame again once the LUT file it was graded with changes, + /// though its key was otherwise the same (same project revision, frame and options). + #[test] + fn the_viewer_shows_a_lut_file_changed_on_disk() { + let dir = tempfile::tempdir().unwrap(); + let lut = dir.path().join("viewer.cube"); + let write = |text: &str, secs: u64| { + std::fs::write(&lut, text).unwrap(); + let f = std::fs::File::options().write(true).open(&lut).unwrap(); + f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap(); + }; + write("LUT_1D_SIZE 2\n0 0 0\n0 0 0\n", 1_000); + let mut session = effectcraft_engine::Session::default(); + session.execute("comp.new", serde_json::json!({"width": 64, "height": 36, "duration": 2})).unwrap(); + session.execute("layer.newSolid", serde_json::json!({"color": "#808080"})).unwrap(); + session.execute("effect.apply", serde_json::json!({"layer": 1, "effect": "Apply Color LUT"})).unwrap(); + session.execute("prop.set", serde_json::json!({"layer": 1, "path": "effects/#1/lut", "value": lut.to_string_lossy()})).unwrap(); + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_| crate::EffectcraftApp::new(session)); + let centre = |h: &egui_kittest::Harness<'_, crate::EffectcraftApp>| { + h.state().viewer_image.as_ref().map(|img| img.pixels[img.pixels.len() / 2 + img.size[0] / 2].r()) + }; + let settle = |h: &mut egui_kittest::Harness<'_, crate::EffectcraftApp>, want: u8| { + for _ in 0..400 { + h.step(); + if centre(h) == Some(want) { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the viewer shows {:?}, not {want}", centre(h)); + }; + settle(&mut harness, 0); + write("LUT_1D_SIZE 2\n1 1 1\n1 1 1\n", 2_000); + // (what the app's watcher does every two seconds) + effectcraft_engine::lut_reload::check(); + settle(&mut harness, 255); + } +} diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rs index 6d99a8cd2..a0c2f94b5 100644 --- a/crates/ui-egui/src/frames.rs +++ b/crates/ui-egui/src/frames.rs @@ -298,9 +298,6 @@ struct Cache { playhead: Option, /// Scale of the frame on screen (the newest urgent request): frames of other scales go first. scale: Option, - /// Frames whose render started before this are not kept: a source file they read changed - /// since ([`Frames::clear_stale`]). - stale_before: Option, } impl Cache { @@ -771,7 +768,7 @@ impl Frames { #[cfg(target_arch = "wasm32")] let queue = Queue::default(); Frames { - cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, gpu_bytes: 0, budget: 3 << 30, gpu_budget: GPU_BUDGET, gpu_pressure: None, gpu_adjusted: None, playhead: None, scale: None, stale_before: None })), + cache: Arc::new(Mutex::new(Cache { map: HashMap::new(), order: VecDeque::new(), bytes: 0, gpu_bytes: 0, budget: 3 << 30, gpu_budget: GPU_BUDGET, gpu_pressure: None, gpu_adjusted: None, playhead: None, scale: None })), inflight: Arc::new(Mutex::new(HashSet::new())), queue: Arc::new(Mutex::new(queue)), #[cfg(not(target_arch = "wasm32"))] @@ -1406,16 +1403,6 @@ impl Frames { } } - /// Drop every frame, and the ones still rendering when they finish: a source file changed on - /// disk (a LUT file, #3493), and a render that started before may have read the old one. - pub fn clear_stale(&self) { - // (marked first: a frame finishing while the cache is emptied is refused, not kept) - if let Ok(mut c) = self.cache.lock() { - c.stale_before = Some(web_time::Instant::now()); - } - self.clear(); - } - /// The playing preview's position (`None` when no preview plays): prefetch renders the /// frames it reaches first before the others, evictions spare the frames it shows next, and /// queued prefetch frames of its series it no longer reaches are dropped (#595). @@ -1912,7 +1899,6 @@ impl Worker { } if let Ok(mut c) = self.cache.lock() && (!img.is_gpu() || !self.gpu_retired.load(Ordering::Acquire)) - && c.stale_before.is_none_or(|at| t0 >= at) { c.insert_with(key, img, files, since); } diff --git a/crates/ui-egui/src/frames/tests.rs b/crates/ui-egui/src/frames/tests.rs index d6bf56a20..45398de21 100644 --- a/crates/ui-egui/src/frames/tests.rs +++ b/crates/ui-egui/src/frames/tests.rs @@ -218,29 +218,6 @@ fn retirement_reaches_existing_workers_and_keeps_cpu_frames_and_completion_live( assert!(frames.queue.lock().unwrap().running.is_empty()); } -/// #3493: a LUT file changed on disk drops the frames kept, and a frame whose render started -/// before is not kept when it finishes (it may have read the old file); one started after is. -#[test] -fn clear_stale_drops_kept_frames_and_ones_rendering() { - let frames = Frames::default(); - let worker = frames.worker(); - let kept = key(1, 0, 0); - insert(&frames, kept); - let (late, fresh) = (key(1, 1, 0), key(1, 2, 0)); - let started = web_time::Instant::now(); - frames.clear_stale(); - assert!(!frames.is_cached(&kept)); - for k in [late, fresh] { - frames.inflight.lock().unwrap().insert(k); - frames.queue.lock().unwrap().running.insert(k); - } - worker.finish_key(late, false, img(), None, None, started); - assert!(!frames.is_cached(&late), "a render started before the change"); - worker.finish_key(fresh, false, img(), None, None, web_time::Instant::now()); - assert!(frames.is_cached(&fresh), "a render started after it"); - assert_eq!(frames.inflight(), 0, "both jobs are released"); -} - fn key(content: u64, frame: i64, opts: u64) -> FrameKey { FrameKey { revision: content, content, comp: 1, frame, scale: 1000, view: 0, opts } } From 63520598a016b407ed457a56bf679f4d3437f862 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 11:36:40 +0530 Subject: [PATCH 23/83] #3493: test the followed-files limit on a cache of its own The test filled the shared cache past the limit, which could let go of a file another test running alongside still follows. --- crates/effects/src/utility.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index 8d9c38927..9d5fec491 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -732,20 +732,17 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } - /// Past [`MAX_FOLLOWED_FILES`], the file just read is still followed. + /// Past [`MAX_FOLLOWED_FILES`], the file just read is still followed (a cache of its own: + /// the shared one's followed files belong to the other tests too). #[test] fn the_file_just_read_stays_followed_past_the_limit() { - let dir = std::env::temp_dir().join(format!("ec-fx-3493-many-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); + let mut c = LutCache::default(); for i in 0..MAX_FOLLOWED_FILES + 8 { - let path = dir.join(format!("{i}.cube")); - std::fs::write(&path, identity_cube(2)).unwrap(); - let src = path.to_string_lossy().into_owned(); - assert!(load_lut(&src).is_some()); - assert!(lut_cache().files.contains_key(&src), "{i}: the file just read"); + let path = format!("/followed/{i}.cube"); + c.read_file(&path, Some((1, None))); + assert!(c.files.contains_key(&path), "{i}: the file just read"); } - std::fs::remove_dir_all(&dir).unwrap(); + assert!(c.files.len() <= MAX_FOLLOWED_FILES, "the others no longer cached are let go"); } #[test] From 8a2b4cc63388c8c8c47381524c7314216313f92c Mon Sep 17 00:00:00 2001 From: ash Date: Thu, 12 Nov 2026 11:37:26 +0530 Subject: [PATCH 24/83] #2796: ScriptUI panel bars hide while the window fits its dock (#2880) A docked panel's solid bars, once shown, took their width from the viewport, so a window that exactly filled its dock stayed too large and kept its bars. The bars are now hidden while the window fits its dock (to the whole point, #2585) and stay solid when it overflows (#269). --- crates/ui-egui/src/panels/scriptui_view.rs | 99 +++++++++++++++++++++- 1 file changed, 96 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/scriptui_view.rs b/crates/ui-egui/src/panels/scriptui_view.rs index 038ed5e15..2e34757bf 100644 --- a/crates/ui-egui/src/panels/scriptui_view.rs +++ b/crates/ui-egui/src/panels/scriptui_view.rs @@ -608,9 +608,8 @@ pub fn panel(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect, id: u32) { ui.data_mut(|d| d.insert_temp(told, dock)); acts.push(Act::Resize(id, dock)); } - let content = rect; - egui::ScrollArea::both().id_salt(("scriptui-panel", id)).max_width(content.width()).max_height(content.height()).show(ui, |ui| { - let (r, _) = ui.allocate_exact_size(vec2(w.root.bounds[2] as f32, w.root.bounds[3] as f32), Sense::hover()); + let window = vec2(w.root.bounds[2] as f32, w.root.bounds[3] as f32); + panel_scroll(ui, ("scriptui-panel", id), rect.size(), window, |ui, r| { draw_children(app, ui, r.min, id, &w.root, &mut acts); mouse_events(ui, r.min, r.intersect(ui.clip_rect()), id, &w.root, !modal, &mut acts); }); @@ -619,6 +618,36 @@ pub fn panel(app: &mut EffectcraftApp, ui: &mut egui::Ui, rect: Rect, id: u32) { perform(app, &ctx, acts); } +/// The scroll area a docked ScriptUI panel shows its `window`-sized window in, at most `dock` +/// big, with the app's scroll style (solid bars, #269). `body` draws the window in the rect it is +/// given. +fn panel_scroll( + ui: &mut egui::Ui, + salt: impl std::hash::Hash + std::fmt::Debug, + dock: egui::Vec2, + window: egui::Vec2, + body: impl FnOnce(&mut egui::Ui, Rect) -> R, +) -> egui::scroll_area::ScrollAreaOutput { + egui::ScrollArea::both().id_salt(salt).max_width(dock.x).max_height(dock.y).scroll_bar_visibility(panel_bars(dock, window)).show(ui, |ui| { + let (r, _) = ui.allocate_exact_size(window, Sense::hover()); + body(ui, r) + }) +} + +/// Whether a docked panel's scroll bars may show: never while its window fits the dock. +/// +/// The fit is decided from the window and the dock, not from what the scroll area has left. A +/// solid bar, once shown, takes its width from the viewport, so a window that exactly fills its +/// dock was "too large" for the narrower viewport and its bars never went away (#2796). The fit +/// rounds the dock up to the whole point, as egui's scroll area does, because the script is told +/// its dock's size rounded (#2585) and its window can be a fraction of a point bigger. A window +/// that overflows only one way still gets both bars: the first one's width hides the edge of a +/// window laid out at the dock's full size, and the second one scrolls to it. +fn panel_bars(dock: egui::Vec2, window: egui::Vec2) -> egui::scroll_area::ScrollBarVisibility { + use egui::scroll_area::ScrollBarVisibility; + if window.x <= dock.x.ceil() && window.y <= dock.y.ceil() { ScrollBarVisibility::AlwaysHidden } else { ScrollBarVisibility::VisibleWhenNeeded } +} + /// Tab title of a script panel. pub fn panel_title(app: &EffectcraftApp, id: u32) -> Option { app.session.script_ui.window(id).map(|w| if w.title.is_empty() { w.script.clone() } else { w.title.clone() }) @@ -640,6 +669,70 @@ pub fn sync_panels(app: &mut EffectcraftApp) { mod tests { use super::*; + const DOCK: egui::Vec2 = egui::vec2(300.0, 200.0); + + /// Twelve frames of a ScriptUI panel docked in `dock`, with the app's solid scroll bars + /// (#269): its window is `first` big on the first frame and `then` big after that. The last + /// frame's scroll output (viewport and content size). + fn panel_frames(dock: egui::Vec2, first: egui::Vec2, then: egui::Vec2) -> (Rect, egui::Vec2) { + let ctx = egui::Context::default(); + ctx.all_styles_mut(|s| s.spacing.scroll = egui::style::ScrollStyle::solid()); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 600.0)); + let mut last = (Rect::NOTHING, egui::Vec2::ZERO); + for frame in 0..12 { + let window = if frame == 0 { first } else { then }; + let input = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(frame) * 0.1), predicted_dt: 0.1, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + let mut panel = ui.new_child(UiBuilder::new().max_rect(Rect::from_min_size(egui::Pos2::ZERO, dock))); + let o = panel_scroll(&mut panel, "panel-test", dock, window, |_, _| ()); + last = (o.inner_rect, o.content_size); + }); + // Nothing paints these frames, and egui expects their texture uploads to be consumed. + out.textures_delta.clear(); + } + last + } + + /// #2796: a solid bar, once shown, took its width from the viewport, so a window that exactly + /// fills its dock stayed "too large" for what was left and kept its bars for good. A window + /// that overflowed for one frame (a dock dragged smaller before the script learns its size) + /// and then fits gets the whole dock back. + #[test] + fn a_panel_whose_window_fits_hides_its_bars() { + let (viewport, _) = panel_frames(DOCK, DOCK + vec2(40.0, 40.0), DOCK); + assert_eq!(viewport.size(), DOCK, "the bars go away once the window fits"); + } + + /// The script is told its dock's size rounded (#2585), so in a dock a fraction of a pixel + /// smaller its window is that fraction bigger. That still fits. + #[test] + fn a_panel_in_a_fractional_dock_hides_its_bars() { + let dock = vec2(299.6, 199.6); + let (viewport, _) = panel_frames(dock, dock + vec2(40.0, 40.0), DOCK); + // egui snaps rects to 1/32 of a point; a bar would take 10 points. + assert!((viewport.size() - dock).length() < 0.05, "a window within the whole pixel fits ({viewport:?})"); + } + + /// #269 holds: a window bigger than its dock keeps solid bars that take their room from the + /// panel, and scrolls. + #[test] + fn a_panel_whose_window_is_too_big_keeps_its_solid_bars() { + let big = DOCK + vec2(120.0, 80.0); + let (viewport, content) = panel_frames(DOCK, big, big); + let bar = egui::style::ScrollStyle::solid().allocated_width(); + assert_eq!(viewport.size(), DOCK - vec2(bar, bar), "solid bars on both axes"); + assert_eq!(content, big, "the whole window is scrollable"); + } + + #[test] + fn panel_bars_only_show_for_a_window_bigger_than_its_dock() { + use egui::scroll_area::ScrollBarVisibility::{AlwaysHidden, VisibleWhenNeeded}; + assert_eq!(panel_bars(DOCK, DOCK), AlwaysHidden); + assert_eq!(panel_bars(vec2(299.4, 199.4), DOCK), AlwaysHidden); + assert_eq!(panel_bars(DOCK, DOCK + vec2(1.0, 0.0)), VisibleWhenNeeded); + assert_eq!(panel_bars(DOCK, DOCK + vec2(0.0, 1.0)), VisibleWhenNeeded); + } + /// Script colours are sRGB, not linear: `#2B2B2B` drew as RGB 114 when read as linear light. #[test] fn draw_colours_are_srgb() { From 0da7691d9d367c6d688d0f2602dec64d3284d8df Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 13:06:51 +0530 Subject: [PATCH 25/83] #3087: give a placeholder a match id that is one path segment A pseudo effect's match name (Pseudo/0.25) was its group's match id, so a match path to its parameters (keyframe paste, pick whip) was cut apart at '/' and '.' and found nothing. The effect id stays the match name. --- crates/aep/src/import/placeholder.rs | 18 +++++++++++++++--- crates/aep/tests/it/import/fx_inject.rs | 15 ++++++++++----- crates/aep/tests/it/import/placeholders.rs | 7 +++++++ 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/aep/src/import/placeholder.rs b/crates/aep/src/import/placeholder.rs index 59b0865ac..a12ffa6c5 100644 --- a/crates/aep/src/import/placeholder.rs +++ b/crates/aep/src/import/placeholder.rs @@ -40,7 +40,9 @@ pub(crate) fn placeholder( refs: &mut Vec, col: &mut Collector, ) -> PropGroup { - let mut group = ids.group(fx.match_name(), shown); + // The effect id is the match name; the group's match id is one segment of a property path + // (a pseudo effect's `Pseudo/0.25` would be cut apart), so match paths find its parameters. + let mut group = ids.group(&segment(fx.match_name()), shown); group.kind = GroupKind::Effect { effect: fx.match_name().to_string() }; let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()); for p in params.iter().filter(|p| !carries_nothing(p)) { @@ -126,8 +128,18 @@ fn popup_len(p: &EffectParam<'_, '_>) -> Option { /// third-party effect's `CC Cylinder-0003`), else `param` (a pseudo effect's /// `Pseudo/0.25-0001`: `/` and `.` separate path segments). Expressions also find it by its name. fn param_id(p: &EffectParam<'_, '_>) -> String { - let plain = !p.match_name.is_empty() && p.match_name.chars().all(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')); - if plain { p.match_name.clone() } else { format!("param{}", p.index) } + if !p.match_name.is_empty() && p.match_name.chars().all(plain) { p.match_name.clone() } else { format!("param{}", p.index) } +} + +/// Whether `c` can stand in one segment of a property path (`/`, `.`, `#` and `@` mean more). +fn plain(c: char) -> bool { + c.is_alphanumeric() || matches!(c, ' ' | '-' | '_') +} + +/// `name` as one segment of a property path: other characters become `_` (`Pseudo/0.25` is +/// `Pseudo_0_25`). +fn segment(name: &str) -> String { + name.chars().map(|c| if plain(c) { c } else { '_' }).collect() } /// Sets `prop` from `p`: its expression, then its keys or its value (the record, else the `pard` diff --git a/crates/aep/tests/it/import/fx_inject.rs b/crates/aep/tests/it/import/fx_inject.rs index ae61794d3..535e82483 100644 --- a/crates/aep/tests/it/import/fx_inject.rs +++ b/crates/aep/tests/it/import/fx_inject.rs @@ -10,7 +10,7 @@ use effectcraft_aep::import::{ImportOptions, ImportResult, LossCategory, import}; use effectcraft_aep::{Body, Chunk, ParamKind, ParamValue, Project as AepProject, parse, write}; use effectcraft_keyframe::Value; -use effectcraft_project::{Project, PropGroup}; +use effectcraft_project::{GroupKind, Project, PropGroup}; const SYNTHETIC: &[u8] = include_bytes!("../../fixtures/synthetic.aep"); @@ -274,10 +274,15 @@ pub fn import_bytes(bytes: &[u8], effect: &str) -> (Option, ImportRes let mut project = Project::default(); let none = |_: &str| false; let r = import(&mut project, bytes, &ImportOptions { allow_losses: true, ..ImportOptions::new(&none) }).unwrap(); - let g = project - .comps() - .flat_map(|(_, c)| c.layers.iter()) - .find_map(|l| l.props.sub("effects").and_then(|fx| fx.children.iter().filter_map(|n| n.as_group()).find(|g| g.match_id == effect).cloned())); + let g = project.comps().flat_map(|(_, c)| c.layers.iter()).find_map(|l| { + l.props.sub("effects").and_then(|fx| { + fx.children + .iter() + .filter_map(|n| n.as_group()) + .find(|g| g.match_id == effect || matches!(&g.kind, GroupKind::Effect { effect: e } if e == effect)) + .cloned() + }) + }); (g, r) } diff --git a/crates/aep/tests/it/import/placeholders.rs b/crates/aep/tests/it/import/placeholders.rs index afa323065..679d508af 100644 --- a/crates/aep/tests/it/import/placeholders.rs +++ b/crates/aep/tests/it/import/placeholders.rs @@ -100,6 +100,13 @@ fn a_pseudo_effect_is_kept_with_its_parameter_names() { assert_eq!(g.prop("param1").map(|p| (p.name.as_str(), p.value.clone())), Some(("Speed", Value::Scalar(4.0)))); assert_eq!(g.prop("param2").map(|p| (p.name.as_str(), p.value.clone())), Some(("Mode", Value::Enum(1)))); assert_eq!(losses(&r, LossCategory::Effects, "Pseudo/0.25").len(), 1); + // The effect id stays the match name (Find Missing Effects, expressions); the group's match id + // is one path segment, so a match path (keyframe paste, pick whip) finds its parameters again. + assert_eq!(g.kind, GroupKind::Effect { effect: "Pseudo/0.25".into() }); + let speed = g.prop("param1").map(|p| p.uid); + let layer = PropGroup::new(0, "layer", "Layer").with(PropGroup::new(0, "effects", "Effects").with(g)); + let path = speed.and_then(|u| layer.match_path_of(u)); + assert_eq!(path.as_deref().and_then(|p| layer.prop(p)).map(|p| p.name.as_str()), Some("Speed"), "{path:?}"); } /// A popup whose definition is borrowed (the project copy) and has no value record: its default From 6f8c39d5f40e4d599ddefacab17855e178e97f2b Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 13:06:51 +0530 Subject: [PATCH 26/83] #3087: expressions find an effect by its After Effects match name effect("Pseudo/0.25") and thisLayer("Effects")("Pseudo/0.25") now match a placeholder's effect id, now that its match id is one path segment. --- crates/expr/src/host.rs | 5 ++++- crates/expr/src/tests.rs | 7 +++++-- docs/aep-import.md | 3 ++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/expr/src/host.rs b/crates/expr/src/host.rs index 43400ea1d..de2afd2ac 100644 --- a/crates/expr/src/host.rs +++ b/crates/expr/src/host.rs @@ -9,7 +9,7 @@ use effectcraft_geom::{Mat3, Mat4}; use effectcraft_keyframe::Value; -use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, PropGroup, Property}; +use effectcraft_project::{Comp, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, PropGroup, Property}; use effectcraft_render::EvalCtx; use effectcraft_time::Tick; @@ -283,6 +283,9 @@ fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> { .find(|n| n.match_id() == m) .or_else(|| g.children.iter().find(|n| n.name().eq_ignore_ascii_case(name))) .or_else(|| g.children.iter().find(|n| compact(n.name()) == c || compact(n.match_id()) == c)) + // An effect by its After Effects match name, an imported placeholder's effect id + // (`effect("Pseudo/0.25")`; its match id is one path segment, `Pseudo_0_25`). + .or_else(|| g.children.iter().find(|n| matches!(n.as_group().map(|g| &g.kind), Some(GroupKind::Effect { effect }) if effect == name))) } } } diff --git a/crates/expr/src/tests.rs b/crates/expr/src/tests.rs index f6d07bedc..96db71a6b 100644 --- a/crates/expr/src/tests.rs +++ b/crates/expr/src/tests.rs @@ -1377,12 +1377,13 @@ fn checkbox_and_dropdown_results() { } /// An effect EffectCraft does not have (an imported After Effects placeholder, #3087) is read by -/// name like any other: its parameters by their names, a popup 1-based. +/// name like any other: its parameters by their names, a popup 1-based. It is also found by its +/// After Effects match name, its effect id (the group's match id is one path segment). #[test] fn an_unknown_effects_parameters_are_read_by_name() { let mut f = fx(); let g = group_push(&mut f.p, |ids| { - let mut g = ids.group("Pseudo/0.25", "Settings"); + let mut g = ids.group("Pseudo_0_25", "Settings"); g.kind = effectcraft_project::GroupKind::Effect { effect: "Pseudo/0.25".into() }; g.children.push(ids.prop("param1", "Speed", Value::Scalar(3.0)).into()); g.children.push(ids.prop("param2", "Mode", Value::Enum(1)).into()); @@ -1392,6 +1393,8 @@ fn an_unknown_effects_parameters_are_read_by_name() { assert_close!(f.ev(f.b, ROT, "effect('Settings')('Speed') * 2", 0.0).unwrap().as_f64(), 6.0); assert_close!(f.ev(f.b, ROT, "effect('Settings')('Mode') * 10", 0.0).unwrap().as_f64(), 20.0); assert_close!(f.ev(f.b, ROT, "effect('Settings')(1)", 0.0).unwrap().as_f64(), 3.0); + assert_close!(f.ev(f.b, ROT, "effect('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0); + assert_close!(f.ev(f.b, ROT, "thisLayer('Effects')('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0); } #[test] diff --git a/docs/aep-import.md b/docs/aep-import.md index 9d44006b2..08efa6123 100644 --- a/docs/aep-import.md +++ b/docs/aep-import.md @@ -320,7 +320,8 @@ parameter gets the file's value: is imported and exported, and so is an expression on a stored effect parameter (its text and its switch). - **Effects without a counterpart** (third-party plug-ins, pseudo effects of expression controls, `Pseudo/…`) arrive as **placeholders** (#3087): an effect group whose effect id is the After - Effects match name. Like a missing plug-in it renders nothing and is listed by Find Missing + Effects match name (expressions also find it by that name, `effect("Pseudo/0.25")`; its match id + is that name as one path segment, `Pseudo_0_25`). Like a missing plug-in it renders nothing and is listed by Find Missing Effects. It holds the effect's parameters flat (without the twirl-down group markers), named as in After Effects, each with its value, keys and expression, in the units After Effects' expressions read (sliders and angles as stored, points in layer pixels, colours, checkboxes, From a2ada5a5feeef838271728851975479582efeb53 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 13:14:16 +0530 Subject: [PATCH 27/83] #3087: count every parameter a placeholder walks, and popup names by length A definition of parameters that are not kept, shared by many instances, was walked again for each one without spending the budget; long popup item names were kept per instance with each item counted once. --- crates/aep/src/import/placeholder.rs | 28 +++++++++++++++------- crates/aep/tests/it/import/placeholders.rs | 23 ++++++++++++++++++ docs/aep-import.md | 3 ++- 3 files changed, 45 insertions(+), 9 deletions(-) diff --git a/crates/aep/src/import/placeholder.rs b/crates/aep/src/import/placeholder.rs index a12ffa6c5..4186c9e28 100644 --- a/crates/aep/src/import/placeholder.rs +++ b/crates/aep/src/import/placeholder.rs @@ -11,8 +11,9 @@ //! does). Layer parameters name their layer (their keys and expression are reported). Paths and //! arbitrary data are not kept (reported when they hold something). //! -//! The parameters a placeholder holds are bounded per import ([`MAX_COST`]): definitions can be -//! shared by many instances, so a small file could otherwise ask for very many properties. Once +//! The parameters placeholders walk, kept or not, and their popup items (by name length) are +//! bounded per import ([`MAX_COST`]): definitions can be shared by many instances, so a small file +//! could otherwise ask for very many properties. Once //! the budget is spent, later effects without a counterpart are reported without a placeholder. use effectcraft_keyframe::Value; @@ -24,12 +25,16 @@ use crate::import::props::{Kind, import_expression, import_keys}; use crate::import::report::{Collector, LossCategory}; use crate::{Effect as AepEffect, EffectParam, ParamKind, ParamValue}; -/// Most placeholder properties and popup items one import creates. +/// Most placeholder parameters (kept or not) and popup items one import walks. pub(crate) const MAX_COST: usize = 200_000; /// Most items read from one placeholder popup. const MAX_POPUP_ITEMS: usize = 1024; +/// A popup item costs one more for each of these bytes in its name, so the names kept stay +/// bounded too. +const NAME_BYTES: usize = 16; + /// The placeholder of `fx`, with `params` (its parameter definitions) as properties. pub(crate) fn placeholder( fx: &AepEffect<'_, '_>, @@ -45,26 +50,33 @@ pub(crate) fn placeholder( let mut group = ids.group(&segment(fx.match_name()), shown); group.kind = GroupKind::Effect { effect: fx.match_name().to_string() }; let here = format!("{}: '{}' effect '{shown}' ({})", cx.comp, cx.layer, fx.match_name()); - for p in params.iter().filter(|p| !carries_nothing(p)) { + for p in params { + // Every parameter walked counts, kept or not: a definition shared by many instances is + // otherwise walked again for each one. + if carries_nothing(p) { + col.placeholder_cost = col.placeholder_cost.saturating_add(1).min(MAX_COST); + continue; + } if col.placeholder_cost >= MAX_COST { col.lose(LossCategory::Effects, format!("{here}: parameters past the import's {MAX_COST} placeholder parameters not kept")); break; } let label = param_label(p); let Some((kind, ui, default)) = shape(p, cx.size) else { + col.placeholder_cost = col.placeholder_cost.saturating_add(1); if p.stored().is_some() { col.lose(LossCategory::Effects, format!("{here}: parameter {label} not kept (type {:?})", p.kind)); } continue; }; - let items = match &ui { - ParamUi::Popup { options } => options.len(), - _ => 0, + let (items, names) = match &ui { + ParamUi::Popup { options } => (options.len(), options.iter().map(|o| 1 + o.len() / NAME_BYTES).fold(0, usize::saturating_add)), + _ => (0, 0), }; if p.kind == ParamKind::Popup && popup_len(p).is_some_and(|n| n > items) { col.lose(LossCategory::Effects, format!("{here}: parameter {label}: the items past the first {MAX_POPUP_ITEMS} not kept")); } - let cost = col.placeholder_cost.saturating_add(items).saturating_add(1); + let cost = col.placeholder_cost.saturating_add(names).saturating_add(1); if cost > MAX_COST { // The budget is spent: nothing more is built, here or in later effects (definitions // shared by many instances would otherwise still be walked item by item). diff --git a/crates/aep/tests/it/import/placeholders.rs b/crates/aep/tests/it/import/placeholders.rs index 679d508af..01f1cbc43 100644 --- a/crates/aep/tests/it/import/placeholders.rs +++ b/crates/aep/tests/it/import/placeholders.rs @@ -190,6 +190,29 @@ fn an_effect_past_the_spent_budget_gets_no_placeholder() { assert!(found.iter().any(|d| d.contains("kept without rendering") && !d.contains("more like it")), "the kept instance alone: {found:?}"); } +/// Parameters a placeholder does not keep (markers, arbitrary data) still spend the budget: a +/// definition of very many of them, shared by many instances, is not walked again for each one. +#[test] +fn parameters_not_kept_still_spend_the_budget() { + let defs = (0..200_000).map(|i| other(if i % 2 == 0 { K::NoData } else { K::ArbitraryData }, "X", Default::None)).collect(); + let fx = Fx { match_name: "Odd Fx", name: "Odd", defs, values: vec![], data: vec![], keys: vec![] }; + let (_, r) = import_bytes(&twice(&bytes_with(&fx), "Odd Fx"), "Odd Fx"); + let found = losses(&r, LossCategory::Effects, "Odd Fx"); + assert!(found.iter().any(|d| d.contains("not kept (past the import's placeholder parameters)")), "{found:?}"); +} + +/// Long popup item names spend the budget by their length, so the names kept stay bounded. +#[test] +fn long_popup_item_names_spend_the_budget() { + let long = "x".repeat(1600); + let items: &'static [&'static str] = + Box::leak((0..1024).map(|i| &*Box::leak(format!("{long}{i}").into_boxed_str())).collect::>().into_boxed_slice()); + let fx = Fx { match_name: "Long Fx", name: "Long", defs: vec![popup("A", 1, items), popup("B", 1, items)], values: vec![], data: vec![], keys: vec![] }; + let (g, r) = placeholder_of(&fx); + assert_eq!(g.props().count(), 1); + assert!(losses(&r, LossCategory::Effects, "Long Fx").iter().any(|d| d.contains("placeholder parameters"))); +} + /// `bytes` with the layer's instance of `match_name` (its `tdmn` and `sspc`) repeated after it. fn twice(bytes: &[u8], match_name: &str) -> Vec { let mut file = parse(bytes).unwrap(); diff --git a/docs/aep-import.md b/docs/aep-import.md index 08efa6123..ffaa3f733 100644 --- a/docs/aep-import.md +++ b/docs/aep-import.md @@ -333,7 +333,8 @@ parameter gets the file's value: pseudo effect's `Pseudo/0.25-0001`). Paths and arbitrary data are not kept; a popup whose definition is borrowed, or whose default slot holds no item, and that has no value record takes its first item (reported). One import keeps at - most 200 000 placeholder parameters and popup items (a popup at most 1024 items); the rest is + most 200 000 placeholder parameters and popup items (a popup at most 1024 items; parameters it + does not keep count, and an item one more per 16 bytes of its name); the rest is reported, and once that is spent a later effect without a counterpart arrives without a placeholder (reported). A placeholder is still reported in `effects` and counted in `imported.placeholderEffects`; .aep export reports it and leaves it out. From 24df676af52966dbe5ce1ca8961b098b5c6f229b Mon Sep 17 00:00:00 2001 From: Sean Hawkey <62113798+GenuineMoron@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:10:56 +0800 Subject: [PATCH 28/83] Expressions, Scripting: a layer's property numbers and match names follow After Effects (#3528) (#3529) * Expressions, Scripting: a layer's property numbers follow After Effects In After Effects a layer's top-level number reaches the same group on every layer of a kind: Marker is 1, and slots the layer has not used yet (Time Remap, Motion Trackers, Layer Styles, Data, Sets...) keep their place. EffectCraft numbered only the groups a layer holds, without Marker, so `layer(n)` and `layer.property(n)` reached a different group, and the numbers moved as groups were added. Rigs that read a palette by number, such as `comp("Palette").layer(1)(4)(n)(1)` on a shape layer, read Transform instead of Effects; their `try` fell back to the stored value and every linked colour rendered near-black, with no expression error. `effectcraft_project::ae_order` holds After Effects' slot order per layer kind, observed in After Effects 26.3 from a script (`layer.property(i).matchName`) and from an expression (`thisComp.layer(..)(i).name`) on new layers of each kind. The expression host and the scripting model resolve a layer's numbers through it: 1 is the markers, a used slot is its group, an unused one is an empty group (never null, so loops over `numProperties` are safe). `numProperties` at layer level and `propertyIndex` of top-level groups are After Effects' numbers too. 3D model and primitive layers keep EffectCraft's own numbers. * Expressions: a layer's top-level groups by After Effects match name `thisLayer("ADBE Effect Parade")`, as scripts such as Karton write their expressions, reaches the group through the same table as the layer's numbers: Effects, or an empty group for a slot the layer has not used, and `("ADBE Marker")` the markers. * Expressions, Scripting: review follow-ups for After Effects layer numbers - An enabled Time Remap (a top-level property) reports After Effects' number 2 as its propertyIndex. - In scripting, an unused slot resolves to the same empty group by match name (`property("ADBE Layer Styles")`) as by number (`property(7)`). - The empty group is callable like any group: `layer.property(7)(1)` is null, not a TypeError. --- crates/expr/src/host.rs | 59 +++++++-- crates/expr/src/prelude.js | 2 + crates/expr/src/tests.rs | 1 + crates/expr/src/tests/ae_layer_order.rs | 98 +++++++++++++++ crates/project/src/ae_order.rs | 139 ++++++++++++++++++++++ crates/project/src/lib.rs | 1 + crates/script/src/model.rs | 26 +++- crates/script/src/prelude.js | 36 ++++++ crates/script/src/tests.rs | 1 + crates/script/src/tests/ae_layer_order.rs | 121 +++++++++++++++++++ 10 files changed, 472 insertions(+), 12 deletions(-) create mode 100644 crates/expr/src/tests/ae_layer_order.rs create mode 100644 crates/project/src/ae_order.rs create mode 100644 crates/script/src/tests/ae_layer_order.rs diff --git a/crates/expr/src/host.rs b/crates/expr/src/host.rs index 43400ea1d..fb0d1e07f 100644 --- a/crates/expr/src/host.rs +++ b/crates/expr/src/host.rs @@ -9,6 +9,7 @@ use effectcraft_geom::{Mat3, Mat4}; use effectcraft_keyframe::Value; +use effectcraft_project::ae_order::{self, AeChild}; use effectcraft_project::{Comp, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, PropGroup, Property}; use effectcraft_render::EvalCtx; use effectcraft_time::Tick; @@ -272,6 +273,19 @@ fn node_resp(path: String, n: &Node, index: usize) -> Resp { ]) } +/// A top-level slot the layer has no node for, as group data: `@marker` (the markers, built by the +/// prelude) or `@absent` (an empty group, as After Effects shows an unused slot). +fn slot_resp(path: &str, s: &ae_order::AeSlot, index: usize) -> Resp { + Resp::List(vec![ + Resp::Str(path.into()), + Resp::Bool(true), + Resp::Str(s.name.into()), + Resp::Str(s.match_name.into()), + Resp::Num(0.0), + Resp::Num(index as f64), + ]) +} + fn find_child<'g>(g: &'g PropGroup, key: &Key) -> Option<&'g Node> { match key { Key::Index(i) => usize::try_from(*i).ok().filter(|i| *i >= 1).and_then(|i| g.children.get(i - 1)), @@ -348,7 +362,36 @@ impl<'a> Resolver<'a> { let uid = segs.get(keep - 1)?.strip_prefix('@')?.parse::().ok()?; let index = parent.children.iter().position(|c| c.uid() == uid)?; let n = parent.children.get(index)?; - Some(node_resp(group_path, n, index + 1)) + // A top-level group's number is After Effects' (see `ae_order`). + let number = if keep == 1 { ae_order::ae_index(l, n.match_id()) } else { None }.unwrap_or(index + 1); + Some(node_resp(group_path, n, number)) + } + + /// A child of a layer (`group` empty) or of one of its groups, by name or 1-based number. + fn child(&self, comp: u64, layer: u64, group: &str, key: &Key) -> Option { + let l = self.layer(comp, layer)?; + // A layer's numbers are After Effects' (Marker is 1, unused groups keep their slot), and so + // are its match names (`thisLayer("ADBE Effect Parade")`, as scripts such as Karton write). + let slot = match key { + Key::Index(i) => usize::try_from(*i).ok(), + Key::Name(name) => ae_order::ae_index_of_match_name(l, name), + }; + if group.is_empty() + && ae_order::ae_slots(&l.source).is_some() + && let Some(i) = slot + { + return Some(match ae_order::ae_child(l, i)? { + AeChild::Node(n) => node_resp(format!("@{}", n.uid()), n, i), + AeChild::Marker => slot_resp("@marker", &ae_order::MARKER, 1), + AeChild::Absent(s) => slot_resp("@absent", s, i), + }); + } + let g = if group.is_empty() { &l.props } else { l.props.group(group)? }; + let n = find_child(g, key)?; + let index = if group.is_empty() { ae_order::ae_index(l, n.match_id()) } else { None } + .unwrap_or_else(|| g.children.iter().position(|c| c.uid() == n.uid()).unwrap_or(0) + 1); + let path = if group.is_empty() { format!("@{}", n.uid()) } else { format!("{group}/@{}", n.uid()) }; + Some(node_resp(path, n, index)) } fn try_resolve(&self, req: &Req) -> Option { @@ -403,14 +446,7 @@ impl<'a> Resolver<'a> { Resp::Bool(l.switches.video), ]) } - Req::Child { comp, layer, group, key } => { - let l = self.layer(*comp, *layer)?; - let g = if group.is_empty() { &l.props } else { l.props.group(group)? }; - let n = find_child(g, key)?; - let index = g.children.iter().position(|c| c.uid() == n.uid()).unwrap_or(0) + 1; - let path = if group.is_empty() { format!("@{}", n.uid()) } else { format!("{group}/@{}", n.uid()) }; - node_resp(path, n, index) - } + Req::Child { comp, layer, group, key } => return self.child(*comp, *layer, group, key), Req::Ancestor { comp, layer, path, up } => return self.ancestor(*comp, *layer, path, *up), Req::PropInfo { comp, layer, path } => { let (l, p) = self.prop(*comp, *layer, path)?; @@ -423,7 +459,10 @@ impl<'a> Resolver<'a> { Some(g) => l.props.group(g)?, None => &l.props, }; - g.children.iter().position(|n| format!("@{}", n.uid()) == last).map(|i| i + 1) + let i = g.children.iter().position(|n| format!("@{}", n.uid()) == last)?; + // A top-level property (an enabled Time Remap) has After Effects' number. + let top = if parent.is_none() { g.children.get(i).and_then(|n| ae_order::ae_index(l, n.match_id())) } else { None }; + Some(top.unwrap_or(i + 1)) }); Resp::List(vec![ Resp::Str(p.name.clone()), diff --git a/crates/expr/src/prelude.js b/crates/expr/src/prelude.js index 9307973d8..a57145568 100644 --- a/crates/expr/src/prelude.js +++ b/crates/expr/src/prelude.js @@ -495,6 +495,8 @@ function __mod(a, d) { return ((a % d) + d) % d; } function __child(c, l, group, key) { var info = __h(__CHILD, c, l, group, key); if (info === null) return undefined; + // `thisLayer(1)` is the layer's markers, as in After Effects (see `ae_order`). + if (group === '' && info[0] === '@marker') return new Markers(c, l); return info[1] ? __mkGroup(c, l, info) : __mkProp(c, l, info[0]); } diff --git a/crates/expr/src/tests.rs b/crates/expr/src/tests.rs index d16f1dd54..f206a4320 100644 --- a/crates/expr/src/tests.rs +++ b/crates/expr/src/tests.rs @@ -2025,6 +2025,7 @@ fn an_expression_cant_change_the_prelude_for_the_next() { } } +mod ae_layer_order; mod property_group; /// Timing harness for the prelude's cost on the evaluation path. Ignored: it is a measurement, not diff --git a/crates/expr/src/tests/ae_layer_order.rs b/crates/expr/src/tests/ae_layer_order.rs new file mode 100644 index 000000000..dc97a991c --- /dev/null +++ b/crates/expr/src/tests/ae_layer_order.rs @@ -0,0 +1,98 @@ +//! A layer's top-level numbers are After Effects' (`project::ae_order`): Marker is 1, and slots the +//! layer does not use (Time Remap, Motion Trackers, Layer Styles…) keep their place. Rigs that read +//! a palette by number, such as `comp("Palette").layer(1)(4)(n)(1)` on a shape layer, failed +//! silently before: `(4)` reached Transform, the expression's `try` fell back to the stored value and +//! every linked colour rendered near-black. + +use super::*; +use effectcraft_project::Property; + +/// The fixture with a Slider Control (value 7) on layer "Shape". +fn with_shape_slider() -> Fx { + let mut f = fx(); + let spec = effectcraft_effects::find("ec.control.slider").unwrap(); + let mut slider = group_push(&mut f.p, |ids| effectcraft_effects::instantiate(spec, ids, "Swatch 1", [20.0, 20.0])); + slider.prop_mut("slider").unwrap().value = Value::Scalar(7.0); + f.layer_mut(f.shape).props.sub_mut("effects").unwrap().children.push(slider.into()); + f +} + +fn yes(f: &Fx, cond: &str) -> f64 { + f.num(&format!("({cond}) ? 1 : 0"), 0.0) +} + +#[test] +fn effects_by_number_on_a_shape_layer_is_four() { + let f = with_shape_slider(); + // The Ray Dynamic Color lookup: layer(1)(4)(swatch)(1). + assert_close!(f.num("thisComp.layer('Shape')(4)(1)(1)", 0.0), 7.0); + assert_close!(f.num("try { thisComp.layer('Shape')(4)(1)(1) } catch (e) { -1 }", 0.0), 7.0); +} + +#[test] +fn effects_by_number_on_a_solid_is_five() { + let f = fx(); + assert_close!(f.num("thisComp.layer('A')(5)(1)(1)", 0.0), 42.0); + assert_close!(f.num("thisComp.layer('A')(5)('Slider Control')('Slider')", 0.0), 42.0); +} + +#[test] +fn top_level_names_follow_after_effects() { + let f = fx(); + assert_close!(yes(&f, "thisComp.layer('A')(4).name == 'Masks'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('A')(5).name == 'Effects'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('A')(6).name == 'Transform'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('Shape')(2).name == 'Contents'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('Shape')(5).name == 'Transform'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('Title')(2).name == 'Text'"), 1.0); + assert_close!(yes(&f, "thisComp.layer('Title')(4).name == 'Effects'"), 1.0); + assert_close!(f.num("thisComp.layer('A')(6)('Position')[0]", 0.0), 50.0); +} + +#[test] +fn one_is_the_markers() { + let f = fx(); + assert_close!(f.num("thisComp.layer('A')(1).numKeys", 0.0), 2.0); + assert_close!(f.num("thisComp.layer('A')(1).key(2).time", 0.0), 4.0); +} + +#[test] +fn an_unused_slot_is_an_empty_group() { + let f = fx(); + // Layer Styles (7) and Data (12) exist in After Effects before they are used. + assert_close!(yes(&f, "thisComp.layer('A')(7).name == 'Layer Styles'"), 1.0); + assert_close!(f.num("thisComp.layer('A')(12).numProperties", 0.0), 0.0); + assert_close!(f.num("try { thisComp.layer('A')(12)(1); 1 } catch (e) { -1 }", 0.0), -1.0); + // Past the last slot there is nothing. + assert_close!(f.num("try { thisComp.layer('A')(16); 1 } catch (e) { -1 }", 0.0), -1.0); +} + +#[test] +fn property_index_of_a_top_level_group_is_after_effects() { + let f = fx(); + assert_close!(f.num("thisComp.layer('A').effect('Slider Control').propertyGroup(1).propertyIndex", 0.0), 5.0); + assert_close!(f.num("thisComp.layer('A')('Transform').propertyIndex", 0.0), 6.0); + assert_close!(f.num("thisComp.layer('Shape')('Contents').propertyIndex", 0.0), 2.0); +} + +#[test] +fn top_level_groups_by_after_effects_match_name() { + // Karton's expressions: thisLayer("ADBE Effect Parade")("…"). + let f = with_shape_slider(); + assert_close!(f.num("thisComp.layer('A')('ADBE Effect Parade')('Slider Control')('Slider')", 0.0), 42.0); + assert_close!(f.num("thisComp.layer('Shape')('ADBE Effect Parade')(1)(1)", 0.0), 7.0); + assert_close!(f.num("thisComp.layer('A')('ADBE Transform Group')('Position')[0]", 0.0), 50.0); + assert_close!(f.num("thisComp.layer('A')('ADBE Marker').numKeys", 0.0), 2.0); + assert_close!(f.num("thisComp.layer('A')('ADBE Effect Parade').propertyIndex", 0.0), 5.0); +} + +#[test] +fn an_enabled_time_remap_is_number_two() { + // Enabled Time Remap is a property at the top of the tree; After Effects numbers it 2. + let mut f = fx(); + let uid = f.p.next_id; + f.p.next_id += 1; + f.layer_mut(f.a).props.children.insert(0, Property::new(uid, "timeRemap", "Time Remap", Value::Scalar(0.0)).into()); + assert_close!(f.num("thisComp.layer('A')('Time Remap').propertyIndex", 0.0), 2.0); + assert_close!(f.num("thisComp.layer('A')(2).propertyIndex", 0.0), 2.0); +} diff --git a/crates/project/src/ae_order.rs b/crates/project/src/ae_order.rs new file mode 100644 index 000000000..b6dce1d44 --- /dev/null +++ b/crates/project/src/ae_order.rs @@ -0,0 +1,139 @@ +//! After Effects' numeric order of a layer's top-level property groups. +//! +//! In After Effects `thisLayer(4)` and `layer.property(4)` reach the same group on every layer of a +//! kind, whatever the layer holds: Marker is always 1, and the groups a layer has not used yet +//! (Time Remap, Motion Trackers, Layer Styles…) still take their slot. EffectCraft's tree holds only +//! the groups a layer has, without Marker, so its own positions differ and move as groups are +//! added. Rigs that address groups by number (`comp("Palette").layer(1)(4)(n)(1)`) read the wrong +//! group, or none, unless numbers go through this table. +//! +//! The order was observed in After Effects 26.3 by reading `layer.property(i).matchName` from a +//! script and `thisComp.layer(..)(i).name` from an expression on new layers of each kind; both +//! agree. 3D model and primitive layers have no table: their numbers stay EffectCraft's own. + +use crate::{Layer, LayerSource, Node}; + +/// One top-level slot in After Effects' order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AeSlot { + /// The group's match id in EffectCraft's tree, or `""` when EffectCraft has no such group. + pub match_id: &'static str, + /// The display name After Effects gives the slot. + pub name: &'static str, + /// After Effects' match name for the slot. + pub match_name: &'static str, +} + +const fn slot(match_id: &'static str, name: &'static str, match_name: &'static str) -> AeSlot { + AeSlot { match_id, name, match_name } +} + +/// The marker slot: number 1 on every layer. Markers are a field of [`Layer`], not a tree node. +pub const MARKER: AeSlot = slot("marker", "Marker", "ADBE Marker"); + +/// Footage, solid, adjustment, precomp and null layers. +const AV: &[AeSlot] = &[ + MARKER, + slot("timeRemap", "Time Remap", "ADBE Time Remapping"), + slot("motionTrackers", "Motion Trackers", "ADBE MTrackers"), + slot("masks", "Masks", "ADBE Mask Parade"), + slot("effects", "Effects", "ADBE Effect Parade"), + slot("transform", "Transform", "ADBE Transform Group"), + slot("layerStyles", "Layer Styles", "ADBE Layer Styles"), + slot("", "Geometry Options", "ADBE Plane Options Group"), + slot("geometryOptions", "Geometry Options", "ADBE Extrsn Options Group"), + slot("materialOptions", "Material Options", "ADBE Material Options Group"), + slot("audio", "Audio", "ADBE Audio Group"), + slot("", "Data", "ADBE Data Group"), + slot("", "Essential Properties", "ADBE Layer Overrides"), + slot("", "Sets", "ADBE Layer Sets"), + slot("", "Source Options", "ADBE Source Options Group"), +]; + +const TEXT: &[AeSlot] = &[ + MARKER, + slot("text", "Text", "ADBE Text Properties"), + slot("masks", "Masks", "ADBE Mask Parade"), + slot("effects", "Effects", "ADBE Effect Parade"), + slot("transform", "Transform", "ADBE Transform Group"), + slot("layerStyles", "Layer Styles", "ADBE Layer Styles"), + slot("geometryOptions", "Geometry Options", "ADBE Extrsn Options Group"), + slot("materialOptions", "Material Options", "ADBE Material Options Group"), + slot("audio", "Audio", "ADBE Audio Group"), + slot("", "Sets", "ADBE Layer Sets"), +]; + +const SHAPE: &[AeSlot] = &[ + MARKER, + slot("contents", "Contents", "ADBE Root Vectors Group"), + slot("masks", "Masks", "ADBE Mask Parade"), + slot("effects", "Effects", "ADBE Effect Parade"), + slot("transform", "Transform", "ADBE Transform Group"), + slot("layerStyles", "Layer Styles", "ADBE Layer Styles"), + slot("geometryOptions", "Geometry Options", "ADBE Extrsn Options Group"), + slot("materialOptions", "Material Options", "ADBE Material Options Group"), + slot("audio", "Audio", "ADBE Audio Group"), + slot("", "Sets", "ADBE Layer Sets"), +]; + +const CAMERA: &[AeSlot] = + &[MARKER, slot("transform", "Transform", "ADBE Transform Group"), slot("cameraOptions", "Camera Options", "ADBE Camera Options Group")]; + +const LIGHT: &[AeSlot] = &[MARKER, slot("transform", "Transform", "ADBE Transform Group"), slot("lightOptions", "Light Options", "ADBE Light Options Group")]; + +/// After Effects' top-level slots for a layer of this kind, or `None` for 3D model and primitive +/// layers, which keep EffectCraft's own numbers. +pub fn ae_slots(source: &LayerSource) -> Option<&'static [AeSlot]> { + match source { + LayerSource::Footage { .. } | LayerSource::Comp { .. } | LayerSource::Solid { .. } | LayerSource::Null => Some(AV), + LayerSource::Text => Some(TEXT), + LayerSource::Shape => Some(SHAPE), + LayerSource::Camera => Some(CAMERA), + LayerSource::Light { .. } => Some(LIGHT), + LayerSource::Model { .. } | LayerSource::Primitive { .. } => None, + } +} + +/// What After Effects' top-level number `index` (1-based) reaches on `layer`. +#[derive(Clone, Copy, Debug)] +pub enum AeChild<'a> { + /// The layer's markers (number 1). + Marker, + /// A group or property the layer has. + Node(&'a Node), + /// A slot After Effects always has and this layer does not (an empty group there). + Absent(&'static AeSlot), +} + +/// The top-level node After Effects' number `index` (1-based) reaches, or `None` when the number is +/// past the last slot or the layer kind has no table ([`ae_slots`]). +pub fn ae_child(layer: &Layer, index: usize) -> Option> { + let s = ae_slots(&layer.source)?.get(index.checked_sub(1)?)?; + if *s == MARKER { + return Some(AeChild::Marker); + } + if s.match_id.is_empty() { + return Some(AeChild::Absent(s)); + } + Some(layer.props.children.iter().find(|n| n.match_id() == s.match_id).map_or(AeChild::Absent(s), AeChild::Node)) +} + +/// After Effects' 1-based number for the top-level node with this match id, when it has one. +pub fn ae_index(layer: &Layer, match_id: &str) -> Option { + if match_id.is_empty() { + return None; + } + ae_slots(&layer.source)?.iter().position(|s| s.match_id == match_id).map(|i| i + 1) +} + +/// How many top-level properties After Effects counts on `layer` (`numProperties`), or `None` for +/// layer kinds without a table. +pub fn ae_count(layer: &Layer) -> Option { + ae_slots(&layer.source).map(<[AeSlot]>::len) +} + +/// After Effects' 1-based number for the top-level slot with this After Effects match name +/// (`ADBE Effect Parade`), when the layer kind has one. +pub fn ae_index_of_match_name(layer: &Layer, match_name: &str) -> Option { + ae_slots(&layer.source)?.iter().position(|s| s.match_name == match_name).map(|i| i + 1) +} diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index 6d0a72976..9f5f399e0 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -6,6 +6,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod ae_order; pub mod build; pub mod essential; mod file_check; diff --git a/crates/script/src/model.rs b/crates/script/src/model.rs index e662c1cdc..62f3a8557 100644 --- a/crates/script/src/model.rs +++ b/crates/script/src/model.rs @@ -5,6 +5,7 @@ use effectcraft_engine::Session; use effectcraft_engine::color::Label; use effectcraft_keyframe::{Interp, TextDoc, Value as KV}; +use effectcraft_project::ae_order::{self, AeChild}; use effectcraft_project::{Comp, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Node, ParamUi, PropGroup}; use effectcraft_render::EvalCtx; use effectcraft_time::Tick; @@ -318,7 +319,8 @@ fn indexed_parade(g: &PropGroup) -> bool { fn node_json(c: &Comp, l: &Layer, uid: u64) -> R { if uid == 0 || uid == l.props.uid { - let n = l.props.children.len(); + // After Effects' count (every slot, used or not); 3D model layers count their own groups. + let n = ae_order::ae_count(l).unwrap_or(l.props.children.len()); return Ok(json!({ "uid": l.props.uid, "kind": "group", "name": l.name, "matchName": matchnames::layer(&l.source), "matchId": "layer", "index": c.index_of(l.id).unwrap_or(0), "depth": 0, "parent": null, "isLayer": true, "numProperties": n, @@ -329,7 +331,8 @@ fn node_json(c: &Comp, l: &Layer, uid: u64) -> R { let ch = chain(l, uid).ok_or("the property no longer exists (it was deleted)")?; let node = *ch.last().ok_or("bad property")?; let parent_group: &PropGroup = if ch.len() >= 2 { ch[ch.len() - 2].as_group().ok_or("bad tree")? } else { &l.props }; - let index = parent_group.children.iter().position(|x| x.uid() == uid).map(|i| i + 1).unwrap_or(0); + let top = if ch.len() == 1 { ae_order::ae_index(l, node.match_id()) } else { None }; + let index = top.unwrap_or_else(|| parent_group.children.iter().position(|x| x.uid() == uid).map(|i| i + 1).unwrap_or(0)); let parent_uid = if ch.len() >= 2 { ch[ch.len() - 2].uid() } else { l.props.uid }; let match_name = matchnames::node(&ch); let instance_parent = indexed_parade(parent_group) && ch.len() >= 2 || (ch.len() == 2 && ch[0].match_id() == "contents"); @@ -475,6 +478,25 @@ fn child(s: &Session, a: &J) -> R { let uid = u(a, "uid").unwrap_or(0); let g: &PropGroup = if uid == 0 || uid == l.props.uid { &l.props } else { l.props.find_group(uid).ok_or("not a property group")? }; let key = a.get("key").cloned().unwrap_or(J::Null); + // A layer's numbers and match names are After Effects' (Marker is 1, unused groups keep their + // slot and resolve to the same empty group by number or by match name). + let slot = match &key { + J::Number(n) => Some(n.as_u64().and_then(|i| usize::try_from(i).ok())), + J::String(name) => ae_order::ae_index_of_match_name(l, name).map(Some), + _ => None, + }; + if std::ptr::eq(g, &l.props) + && ae_order::ae_slots(&l.source).is_some() + && let Some(slot) = slot + { + let Some(i) = slot else { return Ok(J::Null) }; + return match ae_order::ae_child(l, i) { + Some(AeChild::Node(n)) => node_json(c, l, n.uid()), + Some(AeChild::Marker) => Ok(json!({"marker": true})), + Some(AeChild::Absent(s)) => Ok(json!({"absent": true, "name": s.name, "matchName": s.match_name, "index": i})), + None => Ok(J::Null), + }; + } let found = match &key { J::Number(n) => n.as_u64().and_then(|i| g.children.get((i as usize).checked_sub(1)?)), J::String(k) => find_child(l, g, k, NESTED_CHILD_DEPTH), diff --git a/crates/script/src/prelude.js b/crates/script/src/prelude.js index 5adab6eec..4b65a5298 100644 --- a/crates/script/src/prelude.js +++ b/crates/script/src/prelude.js @@ -653,10 +653,46 @@ TextDocument.prototype = { function __propOf(layer, info) { if (!info) return null; if (info.isLayer) return layer; + if (info.marker) return layer.marker; + if (info.absent) return __absentGroup(layer, info); if (info.kind === "group") return info.isMask ? new MaskPropertyGroup(layer, info.uid) : new PropertyGroup(layer, info.uid); return new Property(layer, info.uid); } +// A top-level slot After Effects always has and this layer does not use yet (Layer Styles before +// any style, Data, Sets…): an empty group, so loops over `numProperties` meet no null. +function __absentGroup(layer, info) { + var g = { + __kind: "PropertyGroup", + get name() { return info.name; }, + get matchName() { return info.matchName; }, + get propertyIndex() { return info.index; }, + get propertyDepth() { return 1; }, + get propertyType() { return PropertyType.NAMED_GROUP; }, + get parentProperty() { return layer; }, + get numProperties() { return 0; }, + get enabled() { return true; }, + get active() { return layer.enabled; }, + get canSetEnabled() { return false; }, + get isModified() { return false; }, + get isEffect() { return false; }, + get isMask() { return false; }, + get elided() { return false; }, + get selected() { return false; }, + property: function () { return null; }, + propertyGroup: function (n) { return n === undefined || n === 1 ? layer : null; }, + canAddProperty: function () { return false; }, + addProperty: function (n) { throw __err("Can not add \"" + n + "\" to \"" + info.name + "\""); }, + toString: function () { return "[object PropertyGroup]"; }, + }; + // Callable like any group: `layer.property(7)(1)` is `.property(1)`, null. + var f = function (k) { return g.property(k); }; + delete f.name; + delete f.length; + for (const k of Object.getOwnPropertyNames(g)) Object.defineProperty(f, k, Object.getOwnPropertyDescriptor(g, k)); + return f; +} + function PropertyBase() {} PropertyBase.prototype = { __info: function () { return __get("node", { comp: this.__layer.__comp, layer: this.__layer.__id, uid: this.__uid }); }, diff --git a/crates/script/src/tests.rs b/crates/script/src/tests.rs index 800ccdde7..8995b8202 100644 --- a/crates/script/src/tests.rs +++ b/crates/script/src/tests.rs @@ -10,6 +10,7 @@ use serde_json::{Value, json}; use crate::{Outcome, run_code}; +mod ae_layer_order; mod callable; mod ease_presets; mod evalfile; diff --git a/crates/script/src/tests/ae_layer_order.rs b/crates/script/src/tests/ae_layer_order.rs new file mode 100644 index 000000000..869ce348a --- /dev/null +++ b/crates/script/src/tests/ae_layer_order.rs @@ -0,0 +1,121 @@ +//! `layer.property(n)` and the layer's `numProperties` use After Effects' top-level numbers +//! (`project::ae_order`): Marker is 1 and unused slots keep their place as empty groups, so a loop +//! over `numProperties` meets every slot and never a null. + +use std::sync::Arc; + +use effectcraft_engine::Session; +use serde_json::json; + +use crate::{Outcome, run_code}; + +fn session() -> Session { + let mut s = Session { expr: Some(Arc::new(effectcraft_expr::Expressions)), expr_check: Some(effectcraft_expr::check_syntax), ..Default::default() }; + crate::install(&mut s); + s +} + +fn ok(s: &mut Session, code: &str) -> Outcome { + let o = run_code(s, code, "test.jsx"); + assert!(o.error.is_none(), "script failed: {:?}\noutput: {:?}", o.error, o.output); + o +} + +#[test] +fn layer_numbers_follow_after_effects() { + let mut s = session(); + let o = ok( + &mut s, + r#" + var c = app.project.items.addComp("M", 200, 200, 1, 2, 30); + var solid = c.layers.addSolid([1, 1, 1], "S", 200, 200, 1); + solid.Effects.addProperty("ADBE Slider Control"); + var shape = c.layers.addShape(); + var text = c.layers.addText("t"); + var cam = c.layers.addCamera("Cam", [100, 100]); + function names(l) { var o = []; for (var i = 1; i <= l.numProperties; i++) o.push(l.property(i).matchName); return o; } + [names(solid), names(shape), names(text), names(cam), + solid.property(5)(1)(1).value, solid.property(5).propertyIndex, solid.property("Effects").propertyIndex, + solid.property(1) === solid.marker || solid.property(1).matchName, solid.property(16)] + "#, + ); + let av = [ + "ADBE Marker", + "ADBE Time Remapping", + "ADBE MTrackers", + "ADBE Mask Parade", + "ADBE Effect Parade", + "ADBE Transform Group", + "ADBE Layer Styles", + "ADBE Plane Options Group", + "ADBE Extrsn Options Group", + "ADBE Material Options Group", + "ADBE Audio Group", + "ADBE Data Group", + "ADBE Layer Overrides", + "ADBE Layer Sets", + "ADBE Source Options Group", + ]; + let vector = |first: &str| { + json!([ + "ADBE Marker", + first, + "ADBE Mask Parade", + "ADBE Effect Parade", + "ADBE Transform Group", + "ADBE Layer Styles", + "ADBE Extrsn Options Group", + "ADBE Material Options Group", + "ADBE Audio Group", + "ADBE Layer Sets" + ]) + }; + let r = o.result.as_array().unwrap(); + assert_eq!(r[0], json!(av), "solid"); + assert_eq!(r[1], vector("ADBE Root Vectors Group"), "shape"); + assert_eq!(r[2], vector("ADBE Text Properties"), "text"); + assert_eq!(r[3], json!(["ADBE Marker", "ADBE Transform Group", "ADBE Camera Options Group"]), "camera"); + assert_eq!(r[4], json!(0), "the slider's value through property(5)"); + assert_eq!(r[5], json!(5)); + assert_eq!(r[6], json!(5), "propertyIndex by name is After Effects' too"); + assert_eq!(r[7], json!("ADBE Marker")); + assert_eq!(r[8], json!(null), "past the last slot"); +} + +#[test] +fn walking_every_property_meets_no_null() { + let mut s = session(); + let o = ok( + &mut s, + r#" + var c = app.project.items.addComp("M", 200, 200, 1, 2, 30); + var l = c.layers.addShape(); + var n = 0; + function walk(g) { + for (var i = 1; i <= g.numProperties; i++) { + var p = g.property(i); + if (p === null) throw new Error("null at " + i + " of " + g.name); + if (p.propertyType === PropertyType.PROPERTY) n++; else walk(p); + } + } + walk(l); + n > 0 + "#, + ); + assert_eq!(o.result, json!(true)); +} + +#[test] +fn an_unused_slot_is_the_same_by_number_and_match_name_and_callable() { + let mut s = session(); + let o = ok( + &mut s, + r#" + var c = app.project.items.addComp("M", 200, 200, 1, 2, 30); + var l = c.layers.addSolid([1, 1, 1], "S", 200, 200, 1); + var byName = l.property("ADBE Layer Styles"), byNumber = l.property(7); + [byName !== null && byName.matchName, byName !== null && byName.numProperties, byNumber.propertyIndex, l.property(7)(1), l(12).name] + "#, + ); + assert_eq!(o.result, json!(["ADBE Layer Styles", 0, 7, null, "Data"])); +} From 04bbc67528f7c2579ec66332d07e522e32e217ea Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 13:42:53 +0530 Subject: [PATCH 29/83] #3087: test a placeholder found by its match name under ADBE Effect Parade --- crates/expr/src/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/expr/src/tests.rs b/crates/expr/src/tests.rs index 93e66e68f..a80f47b82 100644 --- a/crates/expr/src/tests.rs +++ b/crates/expr/src/tests.rs @@ -1395,6 +1395,7 @@ fn an_unknown_effects_parameters_are_read_by_name() { assert_close!(f.ev(f.b, ROT, "effect('Settings')(1)", 0.0).unwrap().as_f64(), 3.0); assert_close!(f.ev(f.b, ROT, "effect('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0); assert_close!(f.ev(f.b, ROT, "thisLayer('Effects')('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0); + assert_close!(f.ev(f.b, ROT, "thisLayer('ADBE Effect Parade')('Pseudo/0.25')('Speed')", 0.0).unwrap().as_f64(), 3.0); } #[test] From e7a396856def9b69ab89d813d440f3e8eb82240e Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 13:54:03 +0530 Subject: [PATCH 30/83] #3087: a placeholder's float slider keeps its range It arrived as a plain number, so Effect Controls neither dragged it over its slider range nor clamped an edit to its valid range, as After Effects does. --- crates/aep/src/import/placeholder.rs | 13 ++++++++++++- crates/aep/tests/it/import/placeholders.rs | 18 ++++++++++++++++++ docs/aep-import.md | 2 +- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/import/placeholder.rs b/crates/aep/src/import/placeholder.rs index 4186c9e28..2fc40b71b 100644 --- a/crates/aep/src/import/placeholder.rs +++ b/crates/aep/src/import/placeholder.rs @@ -111,7 +111,7 @@ pub(crate) fn placeholder( /// parameter), its control and its value until one is read. `None` for a type that is not kept. fn shape(p: &EffectParam<'_, '_>, size: (u32, u32)) -> Option<(Option, ParamUi, Value)> { let (kind, ui, default) = match p.kind { - ParamKind::IntSlider | ParamKind::FixedSlider | ParamKind::FloatSlider => (Kind::EffectNumber(1.0), ParamUi::Number, Value::Scalar(0.0)), + ParamKind::IntSlider | ParamKind::FixedSlider | ParamKind::FloatSlider => (Kind::EffectNumber(1.0), slider_ui(p), Value::Scalar(0.0)), ParamKind::Angle => (Kind::EffectNumber(1.0), ParamUi::Angle, Value::Scalar(0.0)), ParamKind::Checkbox => (Kind::EffectBool, ParamUi::Checkbox, Value::Bool(false)), ParamKind::Color => (Kind::EffectColor, ParamUi::Color, Value::Color([0.0, 0.0, 0.0, 1.0])), @@ -131,6 +131,17 @@ fn shape(p: &EffectParam<'_, '_>, size: (u32, u32)) -> Option<(Option, Par Some((Some(kind), ui, default)) } +/// A slider's control: a float slider's valid range and drag range when they are ranges (only a +/// float slider's are decoded), else a plain number. +fn slider_ui(p: &EffectParam<'_, '_>) -> ParamUi { + match (p.valid_min(), p.valid_max(), p.slider_range()) { + (Some(min), Some(max), Some((smin, smax))) if [min, max, smin, smax].iter().all(|v| v.is_finite()) && min <= max && smin <= smax => { + ParamUi::Slider { min, max, slider_min: smin.clamp(min, max), slider_max: smax.clamp(min, max), decimals: 2 } + } + _ => ParamUi::Number, + } +} + /// How many items a popup has: the file's names, else the count in its definition. fn popup_len(p: &EffectParam<'_, '_>) -> Option { p.items.as_ref().map(Vec::len).or_else(|| p.popup_item_count().map(usize::from)) diff --git a/crates/aep/tests/it/import/placeholders.rs b/crates/aep/tests/it/import/placeholders.rs index 01f1cbc43..1a8ec697e 100644 --- a/crates/aep/tests/it/import/placeholders.rs +++ b/crates/aep/tests/it/import/placeholders.rs @@ -109,6 +109,24 @@ fn a_pseudo_effect_is_kept_with_its_parameter_names() { assert_eq!(path.as_deref().and_then(|p| layer.prop(p)).map(|p| p.name.as_str()), Some("Speed"), "{path:?}"); } +/// A float slider keeps its valid range and slider range, so Effect Controls drags and clamps it +/// as After Effects does; a range that is not a range stays a plain number. +#[test] +fn a_float_slider_keeps_its_range() { + let fx = Fx { + match_name: "Pseudo/r", + name: "Rig", + defs: vec![slider(K::FloatSlider, "Speed", 1.0, (-10.0, 100.0)), slider(K::FloatSlider, "Odd", 1.0, (5.0, 1.0))], + values: vec![], + data: vec![], + keys: vec![], + }; + let (g, _) = placeholder_of(&fx); + let ui = |id: &str| g.prop(id).map(|p| p.ui.clone()); + assert_eq!(ui("param1"), Some(ParamUi::Slider { min: -10.0, max: 100.0, slider_min: -10.0, slider_max: 100.0, decimals: 2 })); + assert_eq!(ui("param2"), Some(ParamUi::Number)); +} + /// A popup whose definition is borrowed (the project copy) and has no value record: its default /// slot holds another copy's selection, so the first item is used and that is reported. #[test] diff --git a/docs/aep-import.md b/docs/aep-import.md index ffaa3f733..8fc01d5ca 100644 --- a/docs/aep-import.md +++ b/docs/aep-import.md @@ -324,7 +324,7 @@ parameter gets the file's value: is that name as one path segment, `Pseudo_0_25`). Like a missing plug-in it renders nothing and is listed by Find Missing Effects. It holds the effect's parameters flat (without the twirl-down group markers), named as in After Effects, each with its value, keys and expression, in the units After Effects' - expressions read (sliders and angles as stored, points in layer pixels, colours, checkboxes, + expressions read (sliders and angles as stored, a float slider with its range, points in layer pixels, colours, checkboxes, popups over the file's items with separators, read 1-based; layer parameters name their layer, without a record the layer itself as for Layer Control, and their keys and expression are reported), From d361a6cb4e09b80471dd6cf2b2edc98c36526bed Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 13:56:45 +0530 Subject: [PATCH 31/83] #3534, #3536: pin analysis keys saved by 0.24.1 A fixture keyed by the current release: Warp Stabilizer, 3D Camera Tracker and Roto Brush keys keep matching through edits that keep the frames, undo and save/reopen, and real changes still clear them. --- ATTRIBUTION.md | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/analysis_signature.rs | 94 +++++++++++++++++++ .../src/tests/fixtures/analysed-0.24.ecproj | 1 + .../fixtures/analysed-0.24.ecproj.attribution | 8 ++ 5 files changed, 105 insertions(+) create mode 100644 crates/engine/src/tests/analysis_signature.rs create mode 100644 crates/engine/src/tests/fixtures/analysed-0.24.ecproj create mode 100644 crates/engine/src/tests/fixtures/analysed-0.24.ecproj.attribution diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 3aa429a53..f1ea2a95d 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -133,6 +133,7 @@ configuration from these Apache-2.0 projects: | Asset | Author | Source | Licence | |---|---|---|---| +| `crates/engine/src/tests/fixtures/analysed-0.24.ecproj` | arnav-hiwarkar | Original work, synthetic project keyed by EffectCraft 0.24.1 | MIT OR Apache-2.0 | | `crates/engine/src/tests/fixtures/object-matte-0.22.ecproj` | lisn0 | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | | `crates/engine/src/tests/fixtures/tracked-0.22.ecproj` | arnav-hiwarkar | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ab4b5b8da..0422e95b4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -27,6 +27,7 @@ mod key_metadata_order; mod key_time; mod keyframe_text; mod keylight; +mod analysis_signature; mod legacy_analysis_keys; mod limits; mod lottie; diff --git a/crates/engine/src/tests/analysis_signature.rs b/crates/engine/src/tests/analysis_signature.rs new file mode 100644 index 000000000..7429c4035 --- /dev/null +++ b/crates/engine/src/tests/analysis_signature.rs @@ -0,0 +1,94 @@ +//! Warp Stabilizer, 3D Camera Tracker and Roto Brush keys saved by 0.24 keep matching their +//! layer's frames after edits that don't change them, and a real change still clears them. + +use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY}; +use effectcraft_effects::roto::{FROZEN, INPUT_KEY}; +use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY}; +use effectcraft_keyframe::Value; +use effectcraft_project::{ItemId, LayerId, Project}; +use serde_json::json; + +use crate::Session; + +const COMP: ItemId = ItemId(2); +const CLIP: LayerId = LayerId(3); +const WARP: u64 = 26; +const TRACKER: u64 = 54; +const ROTO: u64 = 86; + +/// Saved by 0.24.1 (before #3534/#3536): the clip of `tracked-0.22.ecproj` with Time Remap, a +/// mask, a Gaussian Blur and a Roto Brush, its analyses replaced by short stand-ins. The keys +/// are the ones that version computed for it. +const ANALYSED_0_24: &str = include_str!("fixtures/analysed-0.24.ecproj"); +const SIGNATURE_0_24: &str = "03efb7c4b0f27b65"; +const ROTO_INPUT_0_24: &str = "7b319ce93027617c"; + +fn open(json: &str) -> Session { + let mut s = Session::default(); + s.replace_project(Project::from_json(json).unwrap(), None); + s.open_comp(COMP); + s +} + +/// The (data, key) of the Warp Stabilizer, the 3D Camera Tracker and the Roto Brush. +fn saved(s: &Session) -> [(String, String); 3] { + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let get = |uid: u64, data: &str, key: &str| { + let params = crate::camera_track::static_params(layer.props.find_group(uid).unwrap()); + let text = |id: &str| match params.get(id) { + Some(Value::Str(s)) => s.clone(), + other => panic!("{id}: {other:?}"), + }; + (text(data), text(key)) + }; + [get(WARP, ANALYSIS, ANALYSIS_KEY), get(TRACKER, TRACKS, TRACKS_KEY), get(ROTO, FROZEN, INPUT_KEY)] +} + +fn add_to_render_queue(s: &mut Session) { + s.execute_checked("renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})).unwrap(); +} + +#[test] +fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() { + let mut s = open(ANALYSED_0_24); + let before = saved(&s); + assert_eq!(before[0], ("saved analysis".into(), SIGNATURE_0_24.into())); + assert_eq!(before[1], ("saved tracks".into(), SIGNATURE_0_24.into())); + assert_eq!(before[2], ("saved frozen".into(), ROTO_INPUT_0_24.into())); + + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + + // Saved and reopened, the keys still match. + let mut s = open(&s.project.to_json()); + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + + // Other frames: all three are cleared (the Roto Brush gets a new key), and undo brings them back. + s.execute_checked("layer.timing", json!({"layer": CLIP.0, "out": 0.25})).unwrap(); + let after = saved(&s); + assert_eq!(after[0], (String::new(), String::new())); + assert_eq!(after[1], (String::new(), String::new())); + assert_eq!(after[2].0, ""); + assert_ne!(after[2].1, ROTO_INPUT_0_24); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + + // Time Remap is part of the frames. + s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "timeRemap", "value": 0.3})).unwrap(); + assert!(saved(&s).iter().all(|(data, _)| data.is_empty())); + s.execute_checked("edit.undo", json!({})).unwrap(); + + // The Roto Brush's input also has the layer's masks and the effects above it. + s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "effects/#3/blurriness", "value": 4})).unwrap(); + let after = saved(&s); + assert_eq!(after[2].0, ""); + assert_ne!(after[2].1, ROTO_INPUT_0_24); + s.execute_checked("edit.undo", json!({})).unwrap(); + s.execute_checked("prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3})).unwrap(); + assert_eq!(saved(&s)[2].0, ""); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); +} diff --git a/crates/engine/src/tests/fixtures/analysed-0.24.ecproj b/crates/engine/src/tests/fixtures/analysed-0.24.ecproj new file mode 100644 index 000000000..e99b4acc0 --- /dev/null +++ b/crates/engine/src/tests/fixtures/analysed-0.24.ecproj @@ -0,0 +1 @@ +{"schema":2,"settings":{"bit_depth":"Bpc8","linearize":false,"working_space":null,"blend_linear":false,"time_display":"Timecode","frame_start":0,"audio_sample_rate":48000,"gpu_acceleration":true,"color_engine":"Adobe","hdr":"Clip","output_space":null,"working_gamma":2.2},"items":{"1":{"id":1,"name":"effectcraft-3456-shake.mp4","label":"Aqua","comment":"","parent":null,"kind":{"type":"Footage","path":"/tmp/effectcraft-3456-shake.mp4","kind":"Video","width":160,"height":120,"pixel_aspect":1.0,"frame_rate":{"num":12,"den":1},"native_rate":null,"duration":254016000000,"has_video":true,"has_audio":false,"alpha":"Ignore","premul_color":[0.0,0.0,0.0],"loop_count":1,"codec":"H.264 (High)","missing":false,"color_profile":"Rec709"}},"2":{"id":2,"name":"effectcraft-3456-shake","label":"Sandstone","comment":"","parent":null,"kind":{"type":"Comp","width":160,"height":120,"pixel_aspect":1.0,"frame_rate":{"num":12,"den":1},"duration":254016000000,"display_start":0,"background":[0.0,0.0,0.0],"work_area":[0,254016000000],"layers":[{"id":3,"name":"effectcraft-3456-shake.mp4","source":{"type":"Footage","item":1},"label":"Aqua","comment":"","start_time":0,"in_point":0,"out_point":254016000000,"stretch":100.0,"switches":{"video":true,"audio":true,"solo":false,"locked":false,"shy":false,"collapse":false,"quality":"Best","sampling":"Bilinear","effects":true,"frame_blend":"Off","motion_blur":false,"adjustment":false,"three_d":false,"guide":false},"blend_mode":"Normal","preserve_transparency":false,"track_matte":null,"parent":null,"markers":[],"auto_orient":"Off","props":{"uid":4,"match":"layer","name":"effectcraft-3456-shake.mp4","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":76,"match":"timeRemap","name":"Time Remap","value":{"t":"Scalar","v":0.0},"keys":[{"time":0,"value":{"t":"Scalar","v":0.2},"in_interp":"Linear","out_interp":"Linear","in_ease":[],"out_ease":[],"continuous":false,"auto_bezier":false,"spatial_in":[0.0,0.0,0.0],"spatial_out":[0.0,0.0,0.0],"spatial_auto":true,"spatial_continuous":false,"roving":false},{"time":254016000000,"value":{"t":"Scalar","v":1.0},"in_interp":"Linear","out_interp":"Linear","in_ease":[],"out_ease":[],"continuous":false,"auto_bezier":false,"spatial_in":[0.0,0.0,0.0],"spatial_out":[0.0,0.0,0.0],"spatial_auto":true,"spatial_continuous":false,"roving":false}],"ui":{"kind":"Number"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":5,"match":"masks","name":"Masks","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Group","uid":77,"match":"mask","name":"Mask 1","kind":{"kind":"Mask","mode":"Add","inverted":false,"color":[177,180,79],"locked":false,"motion_blur":"SameAsLayer","feather_falloff":"Smooth","roto_bezier":false},"enabled":true,"children":[{"node":"Prop","uid":78,"match":"path","name":"Mask Path","value":{"t":"Path","v":{"vertices":[[10.0,10.0],[120.0,10.0],[120.0,100.0],[10.0,100.0]],"in_tangents":[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]],"out_tangents":[[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]],"closed":false}},"ui":{"kind":"Path"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":79,"match":"feather","name":"Mask Feather","value":{"t":"Vec2","v":[0.0,0.0]},"ui":{"kind":"Pixels"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":80,"match":"opacity","name":"Mask Opacity","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":81,"match":"expansion","name":"Mask Expansion","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Pixels"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]}]},{"node":"Group","uid":6,"match":"effects","name":"Effects","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Group","uid":26,"match":"ec.distort.warpstabilizer","name":"Warp Stabilizer","kind":{"kind":"Effect","effect":"ec.distort.warpstabilizer"},"enabled":true,"children":[{"node":"Group","uid":28,"match":"stabilization","name":"Stabilization","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":27,"match":"result","name":"Result","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Smooth Motion","No Motion"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":29,"match":"smoothness","name":"Smoothness","value":{"t":"Scalar","v":50.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":30,"match":"method","name":"Method","value":{"t":"Enum","v":3},"ui":{"kind":"Popup","options":["Position","Position, Scale, Rotation","Perspective","Subspace Warp"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":31,"match":"preserveScale","name":"Preserve Scale","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":33,"match":"borders","name":"Borders","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":32,"match":"framing","name":"Framing","value":{"t":"Enum","v":2},"ui":{"kind":"Popup","options":["Stabilize Only","Stabilize, Crop","Stabilize, Crop, Auto-scale","Stabilize, Synthesize Edges"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":35,"match":"autoScale","name":"Auto-scale","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":34,"match":"maximumScale","name":"Maximum Scale","value":{"t":"Scalar","v":150.0},"ui":{"kind":"Slider","min":100.0,"max":1000.0,"slider_min":100.0,"slider_max":200.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":36,"match":"actionSafeMargin","name":"Action-safe Margin","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":45.0,"slider_min":0.0,"slider_max":20.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":37,"match":"additionalScale","name":"Additional Scale","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":1.0,"max":1000.0,"slider_min":50.0,"slider_max":150.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":39,"match":"advanced","name":"Advanced","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":38,"match":"detailedAnalysis","name":"Detailed Analysis","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":40,"match":"rollingShutterRipple","name":"Rolling Shutter Ripple","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Automatic Reduction","Enhanced Reduction"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":41,"match":"cropLessSmoothMore","name":"Crop Less <-> Smooth More","value":{"t":"Scalar","v":50.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":42,"match":"synthesizeInputRange","name":"Synthesis Input Range (seconds)","value":{"t":"Scalar","v":1.0},"ui":{"kind":"Slider","min":0.0,"max":10.0,"slider_min":0.0,"slider_max":5.0,"decimals":2},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":43,"match":"synthesizeEdgeFeather","name":"Synthesis Edge Feather","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":45,"match":"edgeCropping","name":"Synthesis Edge Cropping","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":44,"match":"left","name":"Left","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":50.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":46,"match":"top","name":"Top","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":50.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":47,"match":"right","name":"Right","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":50.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":48,"match":"bottom","name":"Bottom","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":50.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":49,"match":"hideWarningBanner","name":"Hide Warning Banner","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":50,"match":"showTrackPoints","name":"Show Track Points","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":51,"match":"trackPointSize","name":"Track Point Size","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":200.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":52,"match":"analysis","name":"Analysis","value":{"t":"Str","v":"saved analysis"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":53,"match":"analysisKey","name":"Analysis Key","value":{"t":"Str","v":"03efb7c4b0f27b65"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":54,"match":"ec.perspective.cameratracker","name":"3D Camera Tracker","kind":{"kind":"Effect","effect":"ec.perspective.cameratracker"},"enabled":true,"children":[{"node":"Prop","uid":55,"match":"shotType","name":"Shot Type","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Fixed Angle of View","Variable Zoom","Specify Angle of View"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":56,"match":"horizontalAngleOfView","name":"Horizontal Angle of View","value":{"t":"Scalar","v":40.0},"ui":{"kind":"Slider","min":1.0,"max":170.0,"slider_min":10.0,"slider_max":120.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":57,"match":"showTrackPoints","name":"Show Track Points","value":{"t":"Enum","v":1},"ui":{"kind":"Popup","options":["2D Source","3D Solved"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":58,"match":"renderTrackPoints","name":"Render Track Points","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":59,"match":"trackPointSize","name":"Track Point Size","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":1000.0,"slider_min":0.0,"slider_max":300.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":60,"match":"targetSize","name":"Target Size","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":1.0,"max":1000.0,"slider_min":10.0,"slider_max":300.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":62,"match":"advanced","name":"Advanced","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":61,"match":"solveMethod","name":"Solve Method","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Auto Detect","Typical","Mostly Flat Scene","Tripod Pan"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":63,"match":"methodUsed","name":"Method Used","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":64,"match":"averageError","name":"Average Error","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":65,"match":"detailedAnalysis","name":"Detailed Analysis","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":66,"match":"lensDistortion","name":"Solve Lens Distortion","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":67,"match":"undistort","name":"Undistort Footage","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":68,"match":"autoDeletePoints","name":"Auto-delete Points Across Time","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":69,"match":"hideWarningBanner","name":"Hide Warning Banner","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":70,"match":"tracks","name":"Tracks","value":{"t":"Str","v":"saved tracks"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":71,"match":"tracksKey","name":"Tracks Key","value":{"t":"Str","v":"03efb7c4b0f27b65"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":72,"match":"solve","name":"Solve","value":{"t":"Str","v":"saved solve"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":73,"match":"solveKey","name":"Solve Key","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":74,"match":"deleted","name":"Deleted Points","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":75,"match":"camera","name":"Camera Layer","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":82,"match":"ec.blur.gaussian","name":"Gaussian Blur","kind":{"kind":"Effect","effect":"ec.blur.gaussian"},"enabled":true,"children":[{"node":"Prop","uid":83,"match":"blurriness","name":"Blurriness","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":3000.0,"slider_min":0.0,"slider_max":50.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":84,"match":"dimensions","name":"Blur Dimensions","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Horizontal and Vertical","Horizontal","Vertical"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":85,"match":"repeatEdge","name":"Repeat Edge Pixels","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":86,"match":"ec.matte.rotobrush","name":"Roto Brush & Refine Edge","kind":{"kind":"Effect","effect":"ec.matte.rotobrush"},"enabled":true,"children":[{"node":"Prop","uid":87,"match":"version","name":"Version","value":{"t":"Enum","v":2},"ui":{"kind":"Popup","options":["1.0","2.0","3.0"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":88,"match":"quality","name":"Quality","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Standard","Best"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":90,"match":"rotoBrushPropagation","name":"Roto Brush Propagation","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":89,"match":"searchRadius","name":"Search Radius","value":{"t":"Scalar","v":15.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":50.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":91,"match":"motionThreshold","name":"Motion Threshold","value":{"t":"Scalar","v":10.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":92,"match":"motionDamping","name":"Motion Damping","value":{"t":"Scalar","v":20.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":93,"match":"viewSearchRegion","name":"View Search Region","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":95,"match":"rotoBrushMatte","name":"Roto Brush Matte","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":94,"match":"feather","name":"Feather","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":20.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":96,"match":"contrast","name":"Contrast","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":97,"match":"shiftEdge","name":"Shift Edge","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":-100.0,"max":100.0,"slider_min":-100.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":98,"match":"reduceChatter","name":"Reduce Chatter","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":99,"match":"object","name":"Show Object","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":32.0,"slider_min":0.0,"slider_max":32.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":101,"match":"refineEdgeMatte","name":"Refine Edge Matte","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":100,"match":"smooth","name":"Smooth","value":{"t":"Scalar","v":1.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":10.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":102,"match":"feather","name":"Feather","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":20.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":103,"match":"contrast","name":"Contrast","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":104,"match":"shiftEdge","name":"Shift Edge","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":-100.0,"max":100.0,"slider_min":-100.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":105,"match":"reduceChatter","name":"Reduce Chatter","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":106,"match":"useMotionBlur","name":"Use Motion Blur","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":108,"match":"motionBlur","name":"Motion Blur","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":107,"match":"motionBlurSamples","name":"Samples","value":{"t":"Scalar","v":11.0},"ui":{"kind":"Slider","min":1.0,"max":64.0,"slider_min":1.0,"slider_max":32.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":109,"match":"shutterAngle","name":"Shutter Angle","value":{"t":"Scalar","v":180.0},"ui":{"kind":"Slider","min":0.0,"max":720.0,"slider_min":0.0,"slider_max":360.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":110,"match":"higherQuality","name":"Higher Quality","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Prop","uid":111,"match":"decontaminateEdgeColors","name":"Decontaminate Edge Colors","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Group","uid":113,"match":"decontamination","name":"Decontamination","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":112,"match":"decontaminationAmount","name":"Decontamination Amount","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":114,"match":"extendWhereSmoothed","name":"Extend Where Smoothed","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":115,"match":"increaseDecontaminationRadius","name":"Increase Decontamination Radius","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":20.0,"decimals":1},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":116,"match":"viewDecontaminationMap","name":"View Decontamination Map","value":{"t":"Bool","v":false},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]}]},{"node":"Prop","uid":117,"match":"strokes","name":"Strokes","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":118,"match":"inputKey","name":"Input Key","value":{"t":"Str","v":"7b319ce93027617c"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":119,"match":"frozen","name":"Frozen","value":{"t":"Str","v":"saved frozen"},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":120,"match":"tracked","name":"Tracked","value":{"t":"Str","v":""},"ui":{"kind":"Hidden"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]}]},{"node":"Group","uid":15,"match":"transform","name":"Transform","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":7,"match":"anchor","name":"Anchor Point","value":{"t":"Vec3","v":[80.0,60.0,0.0]},"ui":{"kind":"Point"},"spatial":true,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":2,"static_only":false},{"node":"Prop","uid":8,"match":"position","name":"Position","value":{"t":"Vec3","v":[80.0,60.0,0.0]},"ui":{"kind":"Point"},"spatial":true,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":2,"static_only":false},{"node":"Prop","uid":9,"match":"scale","name":"Scale","value":{"t":"Vec3","v":[100.0,100.0,100.0]},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":2,"static_only":false},{"node":"Prop","uid":10,"match":"orientation","name":"Orientation","value":{"t":"Vec3","v":[0.0,0.0,0.0]},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":true,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":11,"match":"rotationX","name":"X Rotation","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":true,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":12,"match":"rotationY","name":"Y Rotation","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":true,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":13,"match":"rotation","name":"Rotation","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":14,"match":"opacity","name":"Opacity","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Slider","min":0.0,"max":100.0,"slider_min":0.0,"slider_max":100.0,"decimals":0},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]},{"node":"Group","uid":16,"match":"materialOptions","name":"Material Options","kind":{"kind":"Plain"},"enabled":true,"children":[{"node":"Prop","uid":17,"match":"castsShadows","name":"Casts Shadows","value":{"t":"Enum","v":0},"ui":{"kind":"Popup","options":["Off","On","Only"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":18,"match":"lightTransmission","name":"Light Transmission","value":{"t":"Scalar","v":0.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":19,"match":"acceptsShadows","name":"Accepts Shadows","value":{"t":"Enum","v":1},"ui":{"kind":"Popup","options":["Off","On","Only"]},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":20,"match":"acceptsLights","name":"Accepts Lights","value":{"t":"Bool","v":true},"ui":{"kind":"Checkbox"},"spatial":false,"hold_only":true,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":21,"match":"ambient","name":"Ambient","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":22,"match":"diffuse","name":"Diffuse","value":{"t":"Scalar","v":50.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":23,"match":"specularIntensity","name":"Specular Intensity","value":{"t":"Scalar","v":50.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":24,"match":"specularShininess","name":"Specular Shininess","value":{"t":"Scalar","v":5.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},{"node":"Prop","uid":25,"match":"metal","name":"Metal","value":{"t":"Scalar","v":100.0},"ui":{"kind":"Percent"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}]}]}}],"markers":[],"shutter_angle":180.0,"shutter_phase":-90.0,"motion_blur_samples":16,"motion_blur_adaptive_limit":128,"renderer":"Classic3D","hide_shy":false,"enable_motion_blur":true,"enable_frame_blending":true,"draft_3d":false,"preserve_frame_rate":false,"preserve_resolution":false,"poster_time":0,"global_light":{"angle":{"uid":0,"match":"globalLightAngle","name":"Global Light Angle","value":{"t":"Scalar","v":120.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false},"altitude":{"uid":0,"match":"globalLightAltitude","name":"Global Light Altitude","value":{"t":"Scalar","v":30.0},"ui":{"kind":"Angle"},"spatial":false,"hold_only":false,"three_d_only":false,"two_d_only":false,"shown_dims":0,"static_only":false}}}}},"next_id":121} \ No newline at end of file diff --git a/crates/engine/src/tests/fixtures/analysed-0.24.ecproj.attribution b/crates/engine/src/tests/fixtures/analysed-0.24.ecproj.attribution new file mode 100644 index 000000000..06e8915f4 --- /dev/null +++ b/crates/engine/src/tests/fixtures/analysed-0.24.ecproj.attribution @@ -0,0 +1,8 @@ +asset: analysed-0.24.ecproj +title: The tracked-0.22 clip with Time Remap, a mask, Gaussian Blur and Roto Brush, keyed by EffectCraft 0.24.1 +author: arnav-hiwarkar +source: original work +license: MIT OR Apache-2.0 +license-file: ../../../../../LICENSE-MIT +added: 2026-11-12 by arnav-hiwarkar +notes: Made from tracked-0.22.ecproj with 0.24.1 engine commands (enable Time Remap, a rectangle mask, Gaussian Blur and Roto Brush), its saved analyses replaced by short stand-in strings, and the Warp Stabilizer, 3D Camera Tracker and Roto Brush keys that 0.24.1 computed for it. Written as compact JSON. No media is needed: the tests only check that the keys are kept or cleared. From 54d53fff766352a2e60f48f563a7a4fc0b1468c2 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:08:57 +0530 Subject: [PATCH 32/83] #3536: one explicit analysis signature for Warp Stabilizer, 3D Camera Tracker and Roto Brush analysis::frames_key writes what a layer's frames are made of field by field: every struct and enum it writes is destructured or matched in full and each variant is a fixed word, so a new field doesn't compile until it is decided and a rename doesn't change keys. Names, labels, UI hints and markers are left out. Roto Brush's Input Key writes masks and the effects above it the same way, instead of their Debug text. Keys saved by 0.22-0.24 are recognised by the old code, moved unchanged to frames_key::legacy, and kept rather than rewritten (frozen mattes hash them). --- crates/engine/src/analysis.rs | 1 + crates/engine/src/analysis/camera_track.rs | 5 +- crates/engine/src/analysis/frames_key.rs | 547 ++++++++++++++++++ .../engine/src/analysis/frames_key/legacy.rs | 144 +++++ crates/engine/src/analysis/roto.rs | 33 +- crates/engine/src/analysis/warp.rs | 147 +---- crates/engine/src/tests.rs | 2 +- crates/engine/src/tests/analysis_signature.rs | 68 +++ .../engine/src/tests/legacy_analysis_keys.rs | 6 +- 9 files changed, 777 insertions(+), 176 deletions(-) create mode 100644 crates/engine/src/analysis/frames_key.rs create mode 100644 crates/engine/src/analysis/frames_key/legacy.rs diff --git a/crates/engine/src/analysis.rs b/crates/engine/src/analysis.rs index fa2b8b4ec..a1adb6dac 100644 --- a/crates/engine/src/analysis.rs +++ b/crates/engine/src/analysis.rs @@ -1,4 +1,5 @@ pub mod camera_track; +pub(crate) mod frames_key; pub mod mask_track; pub mod models; pub mod roto; diff --git a/crates/engine/src/analysis/camera_track.rs b/crates/engine/src/analysis/camera_track.rs index 378f42dd1..43f7e1746 100644 --- a/crates/engine/src/analysis/camera_track.rs +++ b/crates/engine/src/analysis/camera_track.rs @@ -26,9 +26,10 @@ use effectcraft_track::camtrack::linalg::{self, Similarity, V3}; use effectcraft_track::camtrack::{AnalyzeOpts, CameraSolve, CameraTracks, SolveSettings, Target, TrackAnalyzer}; use serde::Serialize; +use crate::analysis::frames_key::{self, signature}; use crate::offload::JobKind; use crate::tracking::lock; -use crate::warp::{analysis_times, signature}; +use crate::warp::analysis_times; use crate::{Event, Session}; /// Live analysis progress (serde for agents / the control channel). @@ -134,7 +135,7 @@ fn tracks_key_of(signature: String, g: &PropGroup) -> String { /// Whether the tracker's saved tracks are made from the layer's current frames and settings. fn tracks_match(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> bool { - crate::warp::key_matches(project, cid, l, &str_of(g, TRACKS_KEY), |s| tracks_key_of(s, g)) + frames_key::key_matches(project, cid, l, &str_of(g, TRACKS_KEY), |s, _| tracks_key_of(s, g)) } /// Parameters of an instance from static values (the tracker's settings are not animated). diff --git a/crates/engine/src/analysis/frames_key.rs b/crates/engine/src/analysis/frames_key.rs new file mode 100644 index 000000000..e093c8aed --- /dev/null +++ b/crates/engine/src/analysis/frames_key.rs @@ -0,0 +1,547 @@ +//! What an analysis of a layer is made from, as one key shared by the Warp Stabilizer, the 3D +//! Camera Tracker and Roto Brush / Object Matte. +//! +//! The key hashes a text this module writes field by field. Every struct and enum it writes is +//! destructured or matched in full, and each variant is written as a fixed word. A new field or +//! variant doesn't compile until it is decided here: written if it changes the layer's frames, +//! left out (with a reason) if it doesn't. Renaming a field or variant doesn't change keys. The +//! text leaves out observations (whether footage is available) and data that never changes pixels +//! (names, labels, UI hints, markers), so they never drop saved analyses (#3534, #3536). +//! +//! Keys saved by 0.22–0.24 hashed derived `Debug` text instead. [`legacy`] still recognises +//! them, and a matching saved key is kept rather than rewritten: frozen Roto Brush mattes and +//! segmentations hash the saved key itself. + +use std::fmt::Write as _; + +use effectcraft_color::ColorSpace; +use effectcraft_keyframe::{Ease, FeatherPoint, Gradient, Interp, Keyframe, ShapePath, Value}; +use effectcraft_project::{ + AlphaMode, CineonSettings, CineonUnits, Expression, FeatherFalloff, FieldOrder, Footage, FootageKind, GroupKind, ItemId, ItemKind, Layer, LayerSource, + LightKind, MaskMode, MaskMotionBlur, Node, PrimitiveKind, Project, PropGroup, Property, Solid, SourceLayer, Uid, +}; +use effectcraft_time::{FrameRate, Tick}; + +pub(crate) mod legacy; + +/// The version of the text, its first word: a later change to what it writes bumps it. +const VERSION: &str = "frames/1"; + +/// Property groups nest a few levels (effect ▸ group ▸ property); deeper trees are cut here. +const MAX_DEPTH: usize = 32; + +fn fnv(s: &str) -> u64 { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in s.as_bytes() { + h ^= *b as u64; + h = h.wrapping_mul(0x0100_0000_01b3); + } + h +} + +fn hex(s: &str) -> String { + format!("{:016x}", fnv(s)) +} + +/// Which signature a key is made from: today's, or one an earlier release saved. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Era { + Current, + Legacy, +} + +/// The signature of `layer`'s frames: its source (and the source item), In/Out, start time, +/// stretch, Time Remap and the comp frame rate. Warp Stabilizer and 3D Camera Tracker keys are +/// made from it. +pub(crate) fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String { + hex(&signature_text(p, comp, layer)) +} + +/// The text [`signature`] hashes. +pub(crate) fn signature_text(p: &Project, comp: ItemId, layer: &Layer) -> String { + let mut t = Text::new(); + t.word(VERSION); + t.layer_frames(p, comp, layer); + t.0 +} + +/// A Roto Brush's (or Object Matte's) Input Key: the layer's frames, its masks and the effects +/// above the instance `uid`. +pub(crate) fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String { + input_key_of(signature(p, comp, layer), layer, uid) +} + +/// An Input Key from a [`signature`]. +pub(crate) fn input_key_of(signature: String, layer: &Layer, uid: Uid) -> String { + let mut t = Text::new(); + t.word(VERSION); + t.word(&signature); + t.inputs_above(layer, uid); + hex(&t.0) +} + +/// Whether `saved`, a key saved with an analysis of `layer`, is for the layer's current frames. +/// `key` makes such a key from a signature of the given era. A key an earlier release saved for +/// the same frames matches too: keep it rather than rewrite it (analysing writes today's). +pub(crate) fn key_matches(p: &Project, comp: ItemId, layer: &Layer, saved: &str, key: impl Fn(String, Era) -> String) -> bool { + key(signature(p, comp, layer), Era::Current) == saved || legacy::signatures(p, comp, layer).into_iter().any(|s| key(s, Era::Legacy) == saved) +} + +/// The text a key is hashed from. Fields are `name=value;`; strings are quoted and escaped, so +/// no value can end its field early. +struct Text(String); + +impl Text { + fn new() -> Text { + Text(String::new()) + } + + fn word(&mut self, w: &str) { + self.0.push_str(w); + self.0.push(';'); + } + + fn field(&mut self, name: &str, value: impl std::fmt::Display) { + let _ = write!(self.0, "{name}={value};"); + } + + fn str(&mut self, name: &str, s: &str) { + let _ = write!(self.0, "{name}={s:?};"); + } + + fn num(&mut self, name: &str, v: f64) { + let _ = write!(self.0, "{name}={v:?};"); + } + + fn nums(&mut self, name: &str, v: &[f64]) { + let _ = write!(self.0, "{name}={v:?};"); + } + + fn floats(&mut self, name: &str, v: &[f32]) { + let _ = write!(self.0, "{name}={v:?};"); + } + + fn opt(&mut self, name: &str, v: Option<&T>, write: impl FnOnce(&mut Text, &T)) { + match v { + Some(v) => { + let _ = write!(self.0, "{name}{{"); + write(self, v); + self.0.push_str("};"); + } + None => self.word(&format!("{name}=none")), + } + } + + fn tick(&mut self, name: &str, t: Tick) { + self.field(name, t.0); + } + + fn rate(&mut self, name: &str, r: FrameRate) { + let FrameRate { num, den } = r; + let _ = write!(self.0, "{name}={num}/{den};"); + } + + /// What a layer's frames are made of, before its masks and effects. + fn layer_frames(&mut self, p: &Project, comp: ItemId, layer: &Layer) { + self.layer_source(&layer.source); + if let Some(item) = layer.source.item() { + match p.item(item).map(|i| &i.kind) { + Some(ItemKind::Footage(f)) => self.footage(f), + Some(ItemKind::Solid(s)) => self.solid(s), + // A precomp's own contents aren't in the signature yet (#3535). + Some(ItemKind::Comp(c)) => { + self.word("comp"); + self.field("w", c.width); + self.field("h", c.height); + self.rate("rate", c.frame_rate); + self.tick("duration", c.duration); + } + Some(ItemKind::Folder) | None => self.word("item=none"), + } + } + self.tick("in", layer.in_point); + self.tick("out", layer.out_point); + self.tick("start", layer.start_time); + self.num("stretch", layer.stretch); + self.opt("timeRemap", layer.props.get("timeRemap"), |t, pr| t.property(pr)); + self.opt("compRate", p.comp(comp).map(|c| &c.frame_rate), |t, r| t.rate("rate", *r)); + } + + fn layer_source(&mut self, s: &LayerSource) { + match s { + LayerSource::Footage { item } => self.field("footage", item.0), + LayerSource::Comp { item } => self.field("comp", item.0), + LayerSource::Solid { item } => self.field("solid", item.0), + LayerSource::Model { item } => self.field("model", item.0), + LayerSource::Text => self.word("text"), + LayerSource::Shape => self.word("shape"), + LayerSource::Null => self.word("null"), + LayerSource::Camera => self.word("camera"), + LayerSource::Light { kind } => self.field( + "light", + match kind { + LightKind::Parallel => "parallel", + LightKind::Spot => "spot", + LightKind::Point => "point", + LightKind::Ambient => "ambient", + LightKind::Environment => "environment", + }, + ), + LayerSource::Primitive { kind } => self.field( + "primitive", + match kind { + PrimitiveKind::Cube => "cube", + PrimitiveKind::Sphere => "sphere", + PrimitiveKind::Plane => "plane", + PrimitiveKind::Torus => "torus", + PrimitiveKind::Cone => "cone", + PrimitiveKind::Cylinder => "cylinder", + }, + ), + } + } + + fn solid(&mut self, s: &Solid) { + let Solid { color, width, height, pixel_aspect } = s; + self.word("solid"); + self.floats("color", color); + self.field("w", width); + self.field("h", height); + self.num("par", *pixel_aspect); + } + + fn footage(&mut self, f: &Footage) { + let Footage { + path, + kind, + width, + height, + pixel_aspect, + frame_rate, + native_rate, + duration, + has_video, + has_audio, + alpha, + premul_color, + loop_count, + codec, + missing, + sequence, + color_profile, + layer, + fields, + invert_alpha, + linear_light, + preserve_rgb, + cineon, + data, + page, + alphabetical, + start_timecode, + file_timecode, + // Markers annotate the footage; they never change its frames. + markers: _, + placed_page, + } = f; + self.word("footage"); + self.str("path", path); + self.field( + "kind", + match kind { + FootageKind::Video => "video", + FootageKind::Still => "still", + FootageKind::Sequence => "sequence", + FootageKind::Audio => "audio", + FootageKind::Model => "model", + FootageKind::Data => "data", + }, + ); + self.field("w", width); + self.field("h", height); + self.num("par", *pixel_aspect); + self.rate("rate", *frame_rate); + self.opt("nativeRate", native_rate.as_ref(), |t, r| t.rate("rate", *r)); + self.tick("duration", *duration); + self.field("video", has_video); + self.field("audio", has_audio); + self.field( + "alpha", + match alpha { + AlphaMode::Straight => "straight", + AlphaMode::Premultiplied => "premultiplied", + AlphaMode::Ignore => "ignore", + }, + ); + self.floats("matte", premul_color); + self.field("loop", loop_count); + self.str("codec", codec); + self.field("missing", missing); + self.field("frames", sequence.len()); + for s in sequence { + self.str("file", s); + } + self.opt("profile", color_profile.as_ref(), |t, c| t.word(color_space(*c))); + self.opt("layer", layer.as_ref(), |t, l| t.source_layer(l)); + self.field( + "fields", + match fields { + FieldOrder::Off => "off", + FieldOrder::UpperFirst => "upper", + FieldOrder::LowerFirst => "lower", + }, + ); + self.field("invertAlpha", invert_alpha); + self.field("linearLight", linear_light); + self.field("preserveRgb", preserve_rgb); + self.cineon(cineon); + self.opt("data", data.as_ref(), |t, d| t.str("text", d)); + self.field("page", page); + self.field("alphabetical", alphabetical); + self.opt("startTimecode", start_timecode.as_ref(), |t, v| t.field("frame", v)); + self.opt("fileTimecode", file_timecode.as_ref(), |t, v| t.field("frame", v)); + self.field("placedPage", placed_page); + } + + fn source_layer(&mut self, l: &SourceLayer) { + let SourceLayer { index, name, layer_size, embedded, placed } = l; + self.field("index", index); + // The layer is found by its index; the name only labels it. + let _ = name; + self.field("layerSize", layer_size); + self.opt("embedded", embedded.as_ref(), |t, e| t.str("id", e)); + self.field("placed", placed); + } + + fn cineon(&mut self, c: &CineonSettings) { + let CineonSettings { log_conversion, converted_black, converted_white, black, white, gamma, rolloff, units } = c; + self.word("cineon"); + self.field("log", log_conversion); + self.floats("points", &[*converted_black, *converted_white, *black, *white, *gamma, *rolloff]); + self.field( + "units", + match units { + CineonUnits::TenBit => "10bit", + CineonUnits::EightBit => "8bit", + CineonUnits::Float => "float", + }, + ); + } + + /// The layer's masks and the effects above the instance `uid`: what the effect's input is + /// made of besides the layer's frames. + fn inputs_above(&mut self, layer: &Layer, uid: Uid) { + if let Some(m) = layer.masks() { + self.word("masks"); + self.group(m, 0); + } + if let Some(fx) = layer.effects() { + self.word("effects"); + for g in fx.groups().take_while(|g| g.uid != uid) { + self.group(g, 0); + } + } + } + + fn group(&mut self, g: &PropGroup, depth: usize) { + // The uid, name and colour label identify and label the group; they never change pixels. + let PropGroup { uid: _, match_id, name: _, kind, enabled, label: _, children } = g; + if depth >= MAX_DEPTH { + self.word("tooDeep"); + return; + } + self.str("group", match_id); + self.group_kind(kind); + self.field("enabled", enabled); + for c in children { + match c { + Node::Prop(p) => self.property(p), + Node::Group(g) => self.group(g, depth + 1), + } + } + self.word("end"); + } + + fn group_kind(&mut self, k: &GroupKind) { + match k { + GroupKind::Plain => self.word("plain"), + GroupKind::Indexed => self.word("indexed"), + // A mask's colour and lock only show it in the UI. + GroupKind::Mask { mode, inverted, color: _, locked: _, motion_blur, feather_falloff, roto_bezier } => { + self.field( + "mask", + match mode { + MaskMode::None => "none", + MaskMode::Add => "add", + MaskMode::Subtract => "subtract", + MaskMode::Intersect => "intersect", + MaskMode::Lighten => "lighten", + MaskMode::Darken => "darken", + MaskMode::Difference => "difference", + }, + ); + self.field("inverted", inverted); + self.field( + "motionBlur", + match motion_blur { + MaskMotionBlur::SameAsLayer => "layer", + MaskMotionBlur::On => "on", + MaskMotionBlur::Off => "off", + }, + ); + self.field( + "falloff", + match feather_falloff { + FeatherFalloff::Smooth => "smooth", + FeatherFalloff::Linear => "linear", + }, + ); + self.field("rotoBezier", roto_bezier); + } + GroupKind::Effect { effect } => self.str("effect", effect), + // A motion tracker's settings say how to track, not how to draw the layer. + GroupKind::Tracker { settings: _ } => self.word("tracker"), + GroupKind::Essential { overridden } => { + self.word("essential"); + for u in overridden { + self.field("overridden", u); + } + } + } + } + + fn property(&mut self, pr: &Property) { + // The uid, name and UI hints identify and show the property; the 2D/3D-only and + // hold-only flags say where and how it can be edited, not what it evaluates to. + let Property { + uid: _, + match_id, + name: _, + value, + keys, + expr, + ui: _, + spatial, + hold_only: _, + three_d_only: _, + two_d_only: _, + shown_dims: _, + static_only: _, + } = pr; + self.str("prop", match_id); + self.value(value); + self.field("spatial", spatial); + for k in keys { + self.keyframe(k); + } + self.opt("expr", expr.as_ref(), |t, e| { + let Expression { text, enabled } = e; + t.str("text", text); + t.field("enabled", enabled); + }); + } + + fn keyframe(&mut self, k: &Keyframe) { + // A key's colour label only shows it in the UI. + let Keyframe { + time, + value, + in_interp, + out_interp, + in_ease, + out_ease, + continuous, + auto_bezier, + spatial_in, + spatial_out, + spatial_auto, + spatial_continuous, + roving, + label: _, + muted, + } = k; + self.tick("key", *time); + self.value(value); + self.field("interp", format_args!("{}/{}", interp(*in_interp), interp(*out_interp))); + for (side, eases) in [("inEase", in_ease), ("outEase", out_ease)] { + for e in eases { + let Ease { speed, influence } = e; + self.nums(side, &[*speed, *influence]); + } + } + self.field("continuous", continuous); + self.field("autoBezier", auto_bezier); + self.nums("spatialIn", spatial_in); + self.nums("spatialOut", spatial_out); + self.field("spatialAuto", spatial_auto); + self.field("spatialContinuous", spatial_continuous); + self.field("roving", roving); + self.field("muted", muted); + } + + fn value(&mut self, v: &Value) { + match v { + Value::Scalar(x) => self.num("scalar", *x), + Value::Vec2(x) => self.nums("vec2", x), + Value::Vec3(x) => self.nums("vec3", x), + Value::Color(x) => self.nums("color", x), + Value::Bool(b) => self.field("bool", b), + Value::Enum(i) => self.field("enum", i), + Value::Path(p) => self.shape_path(p), + // A text document has dozens of fields and no place in what a key covers today (a + // text layer's Source Text is not under its masks or effects): its project-file form. + Value::Text(d) => self.str("text", &serde_json::to_string(d).unwrap_or_default()), + Value::Layer(l) => self.opt("layer", l.as_ref(), |t, id| t.field("id", id)), + Value::Gradient(g) => { + let Gradient { colors, opacities } = g; + self.word("gradient"); + for (at, c) in colors { + self.num("stop", *at); + self.floats("rgba", c); + } + for (at, o) in opacities { + self.num("stop", *at); + self.floats("opacity", &[*o]); + } + } + Value::Str(s) => self.str("str", s), + } + } + + fn shape_path(&mut self, p: &ShapePath) { + let ShapePath { vertices, in_tangents, out_tangents, closed, feather } = p; + self.word("path"); + for (name, points) in [("v", vertices), ("in", in_tangents), ("out", out_tangents)] { + for pt in points { + self.nums(name, pt); + } + } + self.field("closed", closed); + for f in feather { + let FeatherPoint { segment, t, radius, tension } = f; + self.field("featherSegment", segment); + self.nums("feather", &[*t, *radius, *tension]); + } + } +} + +fn interp(i: Interp) -> &'static str { + match i { + Interp::Linear => "linear", + Interp::Bezier => "bezier", + Interp::Hold => "hold", + } +} + +fn color_space(c: ColorSpace) -> &'static str { + match c { + ColorSpace::Srgb => "srgb", + ColorSpace::Rec709 => "rec709", + ColorSpace::Rec2020 => "rec2020", + ColorSpace::DisplayP3 => "p3", + ColorSpace::AcesCg => "acescg", + ColorSpace::Aces2065 => "aces2065", + ColorSpace::Rec2100Pq => "rec2100pq", + ColorSpace::Rec2100Hlg => "rec2100hlg", + } +} diff --git a/crates/engine/src/analysis/frames_key/legacy.rs b/crates/engine/src/analysis/frames_key/legacy.rs new file mode 100644 index 000000000..6147883ae --- /dev/null +++ b/crates/engine/src/analysis/frames_key/legacy.rs @@ -0,0 +1,144 @@ +//! Signatures as 0.22–0.24 wrote them, to recognise the keys those releases saved. Nothing new is +//! keyed with them. They hash derived `Debug` text, so `tests::analysis_signature` pins keys +//! those releases saved: if a type change alters this text, write that part out here. + +use effectcraft_project::{Footage, ItemId, ItemKind, Layer, LayerSource, Project, Uid}; + +use super::fnv; + +/// The signatures a saved key of `layer` may have been made from. Before `Footage::placed_page` +/// was added in 0.23, the footage text ended without that field. +pub(crate) fn signatures(p: &Project, comp: ItemId, layer: &Layer) -> Vec { + let src = match &layer.source { + LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) { + Some(ItemKind::Footage(f)) => { + let mut out = Vec::with_capacity(2); + out.push(signature_with_source(p, comp, layer, &footage_text(f, f.missing, true))); + if matches!(layer.source, LayerSource::Footage { .. }) && !f.placed_page { + out.push(signature_with_source(p, comp, layer, &footage_text(f, f.missing, false))); + } + return out; + } + Some(ItemKind::Solid(s)) => format!("{s:?}"), + Some(ItemKind::Comp(c)) => format!("{}x{}@{:?}/{:?}", c.width, c.height, c.frame_rate, c.duration), + _ => String::new(), + }, + _ => String::new(), + }; + vec![signature_with_source(p, comp, layer, &src)] +} + +/// A Roto Brush Input Key as 0.22–0.24 made it from a [`signatures`] entry. +pub(crate) fn input_key_of(mut s: String, layer: &Layer, uid: Uid) -> String { + if let Some(m) = layer.masks() { + s.push_str(&format!("{m:?}")); + } + if let Some(fx) = layer.effects() { + for g in fx.groups() { + if g.uid == uid { + break; + } + s.push_str(&format!("{g:?}")); + } + } + format!("{:016x}", fnv(&s)) +} + +/// A footage item as 0.23–0.24 wrote it into a signature (without `placed_page` before 0.23), +/// with `missing` in place of the item's. +pub(crate) fn footage_text(f: &Footage, missing: bool, placed_page: bool) -> String { + format!("{:?}", FootageText { f, missing, placed_page }) +} + +struct FootageText<'a> { + f: &'a Footage, + missing: bool, + placed_page: bool, +} + +impl std::fmt::Debug for FootageText<'_> { + fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Every field is named so that a new one doesn't compile until it is decided here: a new + // field was never in these keys, so it stays out. + let Footage { + path, + kind, + width, + height, + pixel_aspect, + frame_rate, + native_rate, + duration, + has_video, + has_audio, + alpha, + premul_color, + loop_count, + codec, + missing: _, + sequence, + color_profile, + layer, + fields, + invert_alpha, + linear_light, + preserve_rgb, + cineon, + data, + page, + alphabetical, + start_timecode, + file_timecode, + markers, + placed_page, + } = self.f; + let mut d = out.debug_struct("Footage"); + d.field("path", path) + .field("kind", kind) + .field("width", width) + .field("height", height) + .field("pixel_aspect", pixel_aspect) + .field("frame_rate", frame_rate) + .field("native_rate", native_rate) + .field("duration", duration) + .field("has_video", has_video) + .field("has_audio", has_audio) + .field("alpha", alpha) + .field("premul_color", premul_color) + .field("loop_count", loop_count) + .field("codec", codec) + .field("missing", &self.missing) + .field("sequence", sequence) + .field("color_profile", color_profile) + .field("layer", layer) + .field("fields", fields) + .field("invert_alpha", invert_alpha) + .field("linear_light", linear_light) + .field("preserve_rgb", preserve_rgb) + .field("cineon", cineon) + .field("data", data) + .field("page", page) + .field("alphabetical", alphabetical) + .field("start_timecode", start_timecode) + .field("file_timecode", file_timecode) + .field("markers", markers); + if self.placed_page { + d.field("placed_page", placed_page); + } + d.finish() + } +} + +fn signature_with_source(p: &Project, comp: ItemId, layer: &Layer, src: &str) -> String { + let rate = p.comp(comp).map(|c| format!("{:?}", c.frame_rate)).unwrap_or_default(); + let s = format!( + "{:?}|{src}|{:?}|{:?}|{:?}|{}|{:?}|{rate}", + layer.source, + layer.in_point, + layer.out_point, + layer.start_time, + layer.stretch, + layer.props.get("timeRemap") + ); + format!("{:016x}", fnv(&s)) +} diff --git a/crates/engine/src/analysis/roto.rs b/crates/engine/src/analysis/roto.rs index 89d3e1609..4a79f5aa0 100644 --- a/crates/engine/src/analysis/roto.rs +++ b/crates/engine/src/analysis/roto.rs @@ -31,6 +31,7 @@ use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, RenderOpt use effectcraft_time::Tick; use serde::{Deserialize, Serialize}; +use crate::analysis::frames_key::{self, Era}; use crate::tracking::lock; use crate::{Event, Session}; @@ -207,34 +208,10 @@ fn set_str(g: &mut PropGroup, m: &str, v: String) { } } -fn fnv(s: &str) -> u64 { - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for b in s.as_bytes() { - h ^= *b as u64; - h = h.wrapping_mul(0x0100_0000_01b3); - } - h -} - /// What the effect's input frames are made of: the layer's source and timing, its masks and the /// effects above the Roto Brush. pub fn input_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String { - input_key_with_signature(crate::warp::signature(p, comp, layer), layer, uid) -} - -fn input_key_with_signature(mut s: String, layer: &Layer, uid: Uid) -> String { - if let Some(m) = layer.masks() { - s.push_str(&format!("{m:?}")); - } - if let Some(fx) = layer.effects() { - for g in fx.groups() { - if g.uid == uid { - break; - } - s.push_str(&format!("{g:?}")); - } - } - format!("{:016x}", fnv(&s)) + frames_key::input_key(p, comp, layer, uid) } /// After an edit: refresh Input Keys (Roto Brush and Object Matte); frozen mattes made from @@ -252,7 +229,11 @@ pub(crate) fn sync(before: &Project, after: &mut Project) -> Vec<(ItemId, LayerI let old = before.comp(*cid).and_then(|bc| bc.layer(l.id)).and_then(|ol| ol.props.find_group(g.uid)); let saved_key = str_of(g, INPUT_KEY); // Keep a matching old key: the frozen cache itself also hashes that key. - if !crate::warp::key_matches(after, *cid, l, &saved_key, |s| input_key_with_signature(s, l, g.uid)) { + let key_of = |s, era| match era { + Era::Current => frames_key::input_key_of(s, l, g.uid), + Era::Legacy => frames_key::legacy::input_key_of(s, l, g.uid), + }; + if !frames_key::key_matches(after, *cid, l, &saved_key, key_of) { set.push((*cid, l.id, g.uid, key)); todo.push((*cid, l.id, g.uid)); } else if old.is_none_or(|o| guard_of(o) != guard_of(g)) { diff --git a/crates/engine/src/analysis/warp.rs b/crates/engine/src/analysis/warp.rs index 20b88d45d..1985f0ca0 100644 --- a/crates/engine/src/analysis/warp.rs +++ b/crates/engine/src/analysis/warp.rs @@ -17,13 +17,14 @@ use std::sync::{Arc, Mutex}; use effectcraft_effects::warp_stab::{self, ANALYSIS, ANALYSIS_KEY}; use effectcraft_keyframe::Value; -use effectcraft_project::{Footage, GroupKind, ItemId, ItemKind, Layer, LayerId, LayerSource, Project, PropGroup, Uid}; +use effectcraft_project::{GroupKind, ItemId, ItemKind, Layer, LayerId, Project, PropGroup, Uid}; use effectcraft_raster::Image; use effectcraft_render::{EvalCtx, ExprHost, FootageSource, LayerCache, Renderer}; use effectcraft_time::Tick; use effectcraft_track::stabilize::{AnalyzeOpts, Analyzer, WarpAnalysis}; use serde::Serialize; +use crate::analysis::frames_key::{self, signature}; use crate::tracking::lock; use crate::{Event, Session}; @@ -98,148 +99,6 @@ pub(crate) struct WarpWork { pub times: Vec, } -fn fnv(s: &str) -> u64 { - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for b in s.as_bytes() { - h ^= *b as u64; - h = h.wrapping_mul(0x0100_0000_01b3); - } - h -} - -/// What an analysis of `layer` depends on (its frames): source (and the footage item's -/// interpretation), In/Out, start time, stretch, Time Remap and the comp frame rate. -pub fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String { - let src = match &layer.source { - LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) { - Some(ItemKind::Footage(f)) => footage_text(f, true), - Some(ItemKind::Solid(s)) => format!("{s:?}"), - Some(ItemKind::Comp(c)) => format!("{}x{}@{:?}/{:?}", c.width, c.height, c.frame_rate, c.duration), - _ => String::new(), - }, - _ => String::new(), - }; - signature_with_source(p, comp, layer, &src) -} - -/// Whether `saved`, a key an analysis of `layer` was saved with, is for the layer's current frames. -/// `key` makes such a key from a signature. A key made from the signature an earlier release wrote -/// for the same frames matches too: keep it rather than rewrite it (analysing writes today's). -pub(crate) fn key_matches(p: &Project, comp: ItemId, layer: &Layer, saved: &str, key: impl Fn(String) -> String) -> bool { - key(signature(p, comp, layer)) == saved || signature_before_placed_page(p, comp, layer).is_some_and(|s| key(s) == saved) -} - -/// Before `Footage::placed_page` was added in 0.23, the persisted signature hashed the -/// same footage text without that last field. Only ordinary footage can match it. -fn signature_before_placed_page(p: &Project, comp: ItemId, layer: &Layer) -> Option { - let LayerSource::Footage { item } = &layer.source else { return None }; - let ItemKind::Footage(footage) = &p.item(*item)?.kind else { return None }; - if footage.placed_page { - return None; - } - Some(signature_with_source(p, comp, layer, &footage_text(footage, false))) -} - -/// A footage item in a signature: its fields as `Debug` wrote them in 0.23, the text saved -/// analysis keys were hashed from (without `placed_page` before 0.23). It is written out here so -/// that a new `Footage` field doesn't change every signature and drop every saved analysis. -pub(crate) fn footage_text(f: &Footage, placed_page: bool) -> String { - format!("{:?}", FootageText { f, placed_page }) -} - -struct FootageText<'a> { - f: &'a Footage, - placed_page: bool, -} - -impl std::fmt::Debug for FootageText<'_> { - fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - // Every field is named, so a new one doesn't compile until it is decided here. A new field - // that changes the frames goes last, written only when it isn't its default, so keys saved - // before it still match. A new field that doesn't change the frames stays out. - let Footage { - path, - kind, - width, - height, - pixel_aspect, - frame_rate, - native_rate, - duration, - has_video, - has_audio, - alpha, - premul_color, - loop_count, - codec, - missing, - sequence, - color_profile, - layer, - fields, - invert_alpha, - linear_light, - preserve_rgb, - cineon, - data, - page, - alphabetical, - start_timecode, - file_timecode, - markers, - placed_page, - } = self.f; - let mut d = out.debug_struct("Footage"); - d.field("path", path) - .field("kind", kind) - .field("width", width) - .field("height", height) - .field("pixel_aspect", pixel_aspect) - .field("frame_rate", frame_rate) - .field("native_rate", native_rate) - .field("duration", duration) - .field("has_video", has_video) - .field("has_audio", has_audio) - .field("alpha", alpha) - .field("premul_color", premul_color) - .field("loop_count", loop_count) - .field("codec", codec) - .field("missing", missing) - .field("sequence", sequence) - .field("color_profile", color_profile) - .field("layer", layer) - .field("fields", fields) - .field("invert_alpha", invert_alpha) - .field("linear_light", linear_light) - .field("preserve_rgb", preserve_rgb) - .field("cineon", cineon) - .field("data", data) - .field("page", page) - .field("alphabetical", alphabetical) - .field("start_timecode", start_timecode) - .field("file_timecode", file_timecode) - .field("markers", markers); - if self.placed_page { - d.field("placed_page", placed_page); - } - d.finish() - } -} - -fn signature_with_source(p: &Project, comp: ItemId, layer: &Layer, src: &str) -> String { - let rate = p.comp(comp).map(|c| format!("{:?}", c.frame_rate)).unwrap_or_default(); - let s = format!( - "{:?}|{src}|{:?}|{:?}|{:?}|{}|{:?}|{rate}", - layer.source, - layer.in_point, - layer.out_point, - layer.start_time, - layer.stretch, - layer.props.get("timeRemap") - ); - format!("{:016x}", fnv(&s)) -} - fn is_warp(g: &PropGroup) -> bool { matches!(&g.kind, GroupKind::Effect { effect } if effect == warp_stab::ID) } @@ -266,7 +125,7 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId, let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id)); for g in fx.groups().filter(|g| is_warp(g)) { let analysed = !str_of(g, ANALYSIS).is_empty(); - if analysed && !key_matches(after, *cid, l, &str_of(g, ANALYSIS_KEY), |s| s) { + if analysed && !frames_key::key_matches(after, *cid, l, &str_of(g, ANALYSIS_KEY), |s, _| s) { clear.push((*cid, l.id, g.uid)); todo.push((*cid, l.id, g.uid)); } else if !analysed && old_layer.and_then(|ol| ol.props.find_group(g.uid)).is_none() { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0422e95b4..eddeeb7ef 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1,6 +1,7 @@ mod add_item_options; mod aep_export; mod aep_import; +mod analysis_signature; mod anim_presets; mod anim_tools; mod aux_footage; @@ -27,7 +28,6 @@ mod key_metadata_order; mod key_time; mod keyframe_text; mod keylight; -mod analysis_signature; mod legacy_analysis_keys; mod limits; mod lottie; diff --git a/crates/engine/src/tests/analysis_signature.rs b/crates/engine/src/tests/analysis_signature.rs index 7429c4035..98612bee4 100644 --- a/crates/engine/src/tests/analysis_signature.rs +++ b/crates/engine/src/tests/analysis_signature.rs @@ -92,3 +92,71 @@ fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() { s.execute_checked("edit.undo", json!({})).unwrap(); assert_eq!(saved(&s), before); } + +/// The text keys are made from today, written field by field (#3536). It changes only when this +/// test is changed with it: a new field of a type it writes doesn't compile until it is decided +/// in `analysis::frames_key`, and renaming a field or variant doesn't change it. +#[test] +fn signature_text_is_pinned() { + let s = open(ANALYSED_0_24); + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let key = r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=video;w=160;h=120;par=1.0;rate=12/1;nativeRate=none;duration=254016000000;video=true;audio=false;alpha=ignore;matte=[0.0, 0.0, 0.0];loop=1;codec="H.264 (High)";missing=false;frames=0;profile{rec709;};layer=none;fields=off;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=false;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=10bit;data=none;page=0;alphabetical=false;startTimecode=none;fileTimecode=none;placedPage=false;in=0;out=254016000000;start=0;stretch=100.0;timeRemap{prop="timeRemap";scalar=0.0;spatial=false;key=0;scalar=0.2;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;key=254016000000;scalar=1.0;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;expr=none;};compRate{rate=12/1;};"#; + assert_eq!(crate::analysis::frames_key::signature_text(&s.project, COMP, layer), key); +} + +/// Keys made today (after analysing again) match through edits, undo and save/reopen too, and +/// renaming or relabelling never drops them. +#[test] +fn todays_keys_survive_edits_that_keep_their_frames() { + let mut s = open(ANALYSED_0_24); + // Analysing again writes today's keys. + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let signature = crate::analysis::frames_key::signature(&s.project, COMP, layer); + let input = crate::roto::input_key(&s.project, COMP, layer, ROTO); + assert_ne!(signature, SIGNATURE_0_24); + s.edit("analyse", None, |p, _| { + let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap(); + for (uid, id, key) in [(WARP, ANALYSIS_KEY, &signature), (TRACKER, TRACKS_KEY, &signature), (ROTO, INPUT_KEY, &input)] { + l.props.find_group_mut(uid).unwrap().get_mut(id).unwrap().value = Value::Str(key.clone()); + } + Ok(()) + }) + .unwrap(); + // The Roto Brush's key covers the effects above it: the Warp Stabilizer's new key changed it. + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let input = crate::roto::input_key(&s.project, COMP, layer, ROTO); + s.edit("roto key", None, |p, _| { + let g = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(ROTO).unwrap(); + g.get_mut(INPUT_KEY).unwrap().value = Value::Str(input.clone()); + g.get_mut(FROZEN).unwrap().value = Value::Str("saved frozen".into()); + Ok(()) + }) + .unwrap(); + let before = saved(&s); + assert_eq!(before[0].1, signature); + assert_eq!(before[2], ("saved frozen".into(), input)); + + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); + let mut s = open(&s.project.to_json()); + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + // Names and labels only show things. + s.execute_checked("layer.rename", json!({"layer": CLIP.0, "name": "Renamed"})).unwrap(); + s.edit("rename", None, |p, _| { + let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap(); + l.props.find_group_mut(82).unwrap().name = "Soft".into(); + if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.markers.push(effectcraft_project::Marker::default()); + } + Ok(()) + }) + .unwrap(); + assert_eq!(saved(&s), before); + + // A real change still clears them. + s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap(); + assert!(saved(&s).iter().all(|(data, _)| data.is_empty())); +} diff --git a/crates/engine/src/tests/legacy_analysis_keys.rs b/crates/engine/src/tests/legacy_analysis_keys.rs index 06a05cc77..6cdb125d3 100644 --- a/crates/engine/src/tests/legacy_analysis_keys.rs +++ b/crates/engine/src/tests/legacy_analysis_keys.rs @@ -50,7 +50,7 @@ fn analyses_saved_by_0_22_survive_edits_that_keep_their_frames() { for (len, _, key) in &before { assert!(*len > 0); // The key predates Footage::placed_page, so it isn't today's signature. - assert_ne!(key, &crate::warp::signature(&s.project, COMP, layer)); + assert_ne!(key, &crate::analysis::frames_key::signature(&s.project, COMP, layer)); } // Adding to the render queue edits the project, as `effectcraft-cli render` does. @@ -122,6 +122,6 @@ fn footage_signature_text_is_pinned() { ..Footage::default() }; let fields = r#"path: "clip.mp4", kind: Video, width: 160, height: 120, pixel_aspect: 1.0, frame_rate: FrameRate { num: 30, den: 1 }, native_rate: None, duration: Tick(0), has_video: false, has_audio: false, alpha: Straight, premul_color: [0.0, 0.0, 0.0], loop_count: 1, codec: "", missing: false, sequence: [], color_profile: None, layer: None, fields: Off, invert_alpha: true, linear_light: false, preserve_rgb: false, cineon: CineonSettings { log_conversion: false, converted_black: 0.0, converted_white: 1023.0, black: 95.0, white: 685.0, gamma: 1.7, rolloff: 20.0, units: TenBit }, data: None, page: 2, alphabetical: false, start_timecode: None, file_timecode: None, markers: []"#; - assert_eq!(crate::warp::footage_text(&f, true), format!("Footage {{ {fields}, placed_page: true }}")); - assert_eq!(crate::warp::footage_text(&f, false), format!("Footage {{ {fields} }}")); + assert_eq!(crate::analysis::frames_key::legacy::footage_text(&f, false, true), format!("Footage {{ {fields}, placed_page: true }}")); + assert_eq!(crate::analysis::frames_key::legacy::footage_text(&f, false, false), format!("Footage {{ {fields} }}")); } From 54cf31f841b4cd9b5eb7f61b75f08484633b10f0 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:10:23 +0530 Subject: [PATCH 33/83] #3534: footage going offline no longer drops saved analyses Whether a footage file is there is an observation (footage.check sets Footage::missing without an edit), not part of the footage. The signature leaves it out, and keys saved by 0.22-0.24, which hashed it, are recognised with the file either online or offline. Warp Stabilizer, 3D Camera Tracker and Roto Brush analyses are kept through the next edit while the footage is offline and after it comes back. --- crates/engine/src/analysis/frames_key.rs | 5 ++- .../engine/src/analysis/frames_key/legacy.rs | 15 ++++--- crates/engine/src/tests/analysis_signature.rs | 40 ++++++++++++++++++- 3 files changed, 51 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/analysis/frames_key.rs b/crates/engine/src/analysis/frames_key.rs index e093c8aed..1b141c53e 100644 --- a/crates/engine/src/analysis/frames_key.rs +++ b/crates/engine/src/analysis/frames_key.rs @@ -226,7 +226,9 @@ impl Text { premul_color, loop_count, codec, - missing, + // Whether the file is there is an observation (`footage.check`), not an edit: an + // offline file is the same footage, and its analyses stay valid (#3534). + missing: _, sequence, color_profile, layer, @@ -276,7 +278,6 @@ impl Text { self.floats("matte", premul_color); self.field("loop", loop_count); self.str("codec", codec); - self.field("missing", missing); self.field("frames", sequence.len()); for s in sequence { self.str("file", s); diff --git a/crates/engine/src/analysis/frames_key/legacy.rs b/crates/engine/src/analysis/frames_key/legacy.rs index 6147883ae..882c82d80 100644 --- a/crates/engine/src/analysis/frames_key/legacy.rs +++ b/crates/engine/src/analysis/frames_key/legacy.rs @@ -6,16 +6,19 @@ use effectcraft_project::{Footage, ItemId, ItemKind, Layer, LayerSource, Project use super::fnv; -/// The signatures a saved key of `layer` may have been made from. Before `Footage::placed_page` -/// was added in 0.23, the footage text ended without that field. +/// The signatures a saved key of `layer` may have been made from. The footage's availability is +/// tried both ways: those releases hashed it, though it isn't part of the footage (#3534). Before +/// `Footage::placed_page` was added in 0.23, the footage text ended without that field. pub(crate) fn signatures(p: &Project, comp: ItemId, layer: &Layer) -> Vec { let src = match &layer.source { LayerSource::Footage { item } | LayerSource::Solid { item } | LayerSource::Comp { item } => match p.item(*item).map(|i| &i.kind) { Some(ItemKind::Footage(f)) => { - let mut out = Vec::with_capacity(2); - out.push(signature_with_source(p, comp, layer, &footage_text(f, f.missing, true))); - if matches!(layer.source, LayerSource::Footage { .. }) && !f.placed_page { - out.push(signature_with_source(p, comp, layer, &footage_text(f, f.missing, false))); + let mut out = Vec::with_capacity(4); + for missing in [false, true] { + out.push(signature_with_source(p, comp, layer, &footage_text(f, missing, true))); + if matches!(layer.source, LayerSource::Footage { .. }) && !f.placed_page { + out.push(signature_with_source(p, comp, layer, &footage_text(f, missing, false))); + } } return out; } diff --git a/crates/engine/src/tests/analysis_signature.rs b/crates/engine/src/tests/analysis_signature.rs index 98612bee4..58a930998 100644 --- a/crates/engine/src/tests/analysis_signature.rs +++ b/crates/engine/src/tests/analysis_signature.rs @@ -100,7 +100,7 @@ fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() { fn signature_text_is_pinned() { let s = open(ANALYSED_0_24); let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); - let key = r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=video;w=160;h=120;par=1.0;rate=12/1;nativeRate=none;duration=254016000000;video=true;audio=false;alpha=ignore;matte=[0.0, 0.0, 0.0];loop=1;codec="H.264 (High)";missing=false;frames=0;profile{rec709;};layer=none;fields=off;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=false;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=10bit;data=none;page=0;alphabetical=false;startTimecode=none;fileTimecode=none;placedPage=false;in=0;out=254016000000;start=0;stretch=100.0;timeRemap{prop="timeRemap";scalar=0.0;spatial=false;key=0;scalar=0.2;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;key=254016000000;scalar=1.0;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;expr=none;};compRate{rate=12/1;};"#; + let key = r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=video;w=160;h=120;par=1.0;rate=12/1;nativeRate=none;duration=254016000000;video=true;audio=false;alpha=ignore;matte=[0.0, 0.0, 0.0];loop=1;codec="H.264 (High)";frames=0;profile{rec709;};layer=none;fields=off;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=false;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=10bit;data=none;page=0;alphabetical=false;startTimecode=none;fileTimecode=none;placedPage=false;in=0;out=254016000000;start=0;stretch=100.0;timeRemap{prop="timeRemap";scalar=0.0;spatial=false;key=0;scalar=0.2;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;key=254016000000;scalar=1.0;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;expr=none;};compRate{rate=12/1;};"#; assert_eq!(crate::analysis::frames_key::signature_text(&s.project, COMP, layer), key); } @@ -143,6 +143,14 @@ fn todays_keys_survive_edits_that_keep_their_frames() { let mut s = open(&s.project.to_json()); add_to_render_queue(&mut s); assert_eq!(saved(&s), before); + // Offline and back online (#3534). + for missing in [true, false] { + if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.missing = missing; + } + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + } // Names and labels only show things. s.execute_checked("layer.rename", json!({"layer": CLIP.0, "name": "Renamed"})).unwrap(); s.edit("rename", None, |p, _| { @@ -160,3 +168,33 @@ fn todays_keys_survive_edits_that_keep_their_frames() { s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap(); assert!(saved(&s).iter().all(|(data, _)| data.is_empty())); } + +/// Footage going offline (or coming back) is an observation, not an edit: the next edit keeps +/// every analysis (#3534). +#[test] +fn offline_footage_keeps_analyses() { + let mut s = open(ANALYSED_0_24); + let before = saved(&s); + let missing = |s: &Session| matches!(&s.project.item(ItemId(1)).unwrap().kind, effectcraft_project::ItemKind::Footage(f) if f.missing); + // The fixture's footage path doesn't exist here: the check marks it missing. + let r = s.execute_checked("footage.check", json!({"wait": true})).unwrap(); + assert_eq!(r["missing"], 1, "{r}"); + assert!(missing(&s)); + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + + // Saved and reopened while offline, then back online. + let mut s = open(&s.project.to_json()); + assert!(missing(&s)); + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.missing = false; + } + add_to_render_queue(&mut s); + assert_eq!(saved(&s), before); + + // A real change while offline still clears them. + s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap(); + assert!(saved(&s).iter().all(|(data, _)| data.is_empty())); +} From a19ffbc0db668bc64b3338db7585fbc8736272a7 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:10:55 +0530 Subject: [PATCH 34/83] #3534, #3536: docs: the Warp Stabilizer and Roto Brush keys come from analysis::frames_key --- crates/engine/src/analysis/roto.rs | 4 ++-- crates/engine/src/analysis/warp.rs | 9 +++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/analysis/roto.rs b/crates/engine/src/analysis/roto.rs index 4a79f5aa0..cb67005f8 100644 --- a/crates/engine/src/analysis/roto.rs +++ b/crates/engine/src/analysis/roto.rs @@ -8,8 +8,8 @@ //! (`Renderer::layer_input`, source → masks → the effects above it). `roto.freeze` runs the same //! pass and stores the final mattes in the effect (one undo step). `sync`, run after every //! edit, keeps each instance's hidden Input Key equal to a signature of what its frames are made -//! of (the layer's source and timing, its masks and the effects above it) and drops frozen -//! mattes made from other frames. +//! of (the layer's source and timing, its masks and the effects above it: `analysis::frames_key`), +//! and drops frozen mattes made from other frames. Footage going offline keeps them. //! //! Object Matte instances run through the same jobs (`objectMatte.propagate` / `.freeze`): the //! frames are [`om::job_frames`] around the reference frame, each segmented through diff --git a/crates/engine/src/analysis/warp.rs b/crates/engine/src/analysis/warp.rs index 1985f0ca0..610e994ca 100644 --- a/crates/engine/src/analysis/warp.rs +++ b/crates/engine/src/analysis/warp.rs @@ -6,10 +6,11 @@ //! analyzer (step 1 of 2, "Analyzing in background"); step 2 ("Stabilizing") derives the //! stabilization plan once to validate and cache the result. When the job finishes, the analysis is //! written into the effect's hidden Analysis parameter as one undo step, together with a key of -//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap). Edits that -//! change those clear the analysis (`invalidate`, run after every edit) and queue the effect -//! for re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses -//! automatically too). +//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap; the key is +//! `analysis::frames_key`'s, shared with the 3D Camera Tracker and Roto Brush). Edits that change +//! those clear the analysis (`invalidate`, run after every edit) and queue the effect for +//! re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses +//! automatically too). Footage going offline is not such a change. use crate::offload::{JobKind, rate}; use std::sync::atomic::{AtomicBool, Ordering}; From 1c8d20a12fde6cb53a424b699e4dabfb00ca2cec Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:19:24 +0530 Subject: [PATCH 35/83] #3534: test a key 0.24.1 saved while the footage was offline; the frames key doc says what is read in full --- crates/engine/src/analysis/frames_key.rs | 11 +++--- crates/engine/src/tests/analysis_signature.rs | 36 +++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/analysis/frames_key.rs b/crates/engine/src/analysis/frames_key.rs index 1b141c53e..44eb93d57 100644 --- a/crates/engine/src/analysis/frames_key.rs +++ b/crates/engine/src/analysis/frames_key.rs @@ -1,10 +1,13 @@ //! What an analysis of a layer is made from, as one key shared by the Warp Stabilizer, the 3D //! Camera Tracker and Roto Brush / Object Matte. //! -//! The key hashes a text this module writes field by field. Every struct and enum it writes is -//! destructured or matched in full, and each variant is written as a fixed word. A new field or -//! variant doesn't compile until it is decided here: written if it changes the layer's frames, -//! left out (with a reason) if it doesn't. Renaming a field or variant doesn't change keys. The +//! The key hashes a text this module writes field by field. The source item (footage and its +//! settings, solid), the Time Remap property and the masks and effect groups (their properties, +//! keyframes and values) are destructured or matched in full, and each variant is written as a +//! fixed word: a new field or variant doesn't compile until it is decided here, written if it +//! changes the layer's frames, left out (with a reason) if it doesn't. Renaming a field or variant +//! doesn't change keys. Of the layer and of a precomp, only the fields named in `layer_frames` are +//! read (a precomp's contents are #3535). The //! text leaves out observations (whether footage is available) and data that never changes pixels //! (names, labels, UI hints, markers), so they never drop saved analyses (#3534, #3536). //! diff --git a/crates/engine/src/tests/analysis_signature.rs b/crates/engine/src/tests/analysis_signature.rs index 58a930998..96323e6be 100644 --- a/crates/engine/src/tests/analysis_signature.rs +++ b/crates/engine/src/tests/analysis_signature.rs @@ -198,3 +198,39 @@ fn offline_footage_keeps_analyses() { s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap(); assert!(saved(&s).iter().all(|(data, _)| data.is_empty())); } + +/// A key 0.24.1 saved while the footage was offline (it hashed the availability) matches too, +/// online or offline. 0.24.1 gave the Roto Brush this Input Key when the fixture's footage went +/// offline and an edit cleared the other two analyses. +#[test] +fn keys_saved_by_0_24_while_offline_still_match() { + const ROTO_INPUT_0_24_OFFLINE: &str = "6183fdd46b514259"; + let mut s = open(ANALYSED_0_24); + s.edit("offline", None, |p, _| { + if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.missing = true; + } + let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap(); + // What 0.24.1's edit cleared then. + use effectcraft_effects::camera_tracker::{AVERAGE_ERROR, METHOD_USED, SOLVE, SOLVE_KEY}; + for (uid, id) in + [(WARP, ANALYSIS), (WARP, ANALYSIS_KEY), (TRACKER, SOLVE), (TRACKER, SOLVE_KEY), (TRACKER, METHOD_USED), (TRACKER, TRACKS), (TRACKER, TRACKS_KEY)] + { + l.props.find_group_mut(uid).unwrap().prop_mut(id).unwrap().value = Value::Str(String::new()); + } + l.props.find_group_mut(TRACKER).unwrap().prop_mut(AVERAGE_ERROR).unwrap().value = Value::Scalar(0.0); + let g = l.props.find_group_mut(ROTO).unwrap(); + g.get_mut(INPUT_KEY).unwrap().value = Value::Str(ROTO_INPUT_0_24_OFFLINE.into()); + Ok(()) + }) + .unwrap(); + let roto = |s: &Session| saved(s)[2].clone(); + assert_eq!(roto(&s), ("saved frozen".into(), ROTO_INPUT_0_24_OFFLINE.into())); + for missing in [true, false] { + if let Some(effectcraft_project::ItemKind::Footage(f)) = std::sync::Arc::make_mut(&mut s.project).item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.missing = missing; + } + add_to_render_queue(&mut s); + assert_eq!(roto(&s), ("saved frozen".into(), ROTO_INPUT_0_24_OFFLINE.into())); + } +} From 0547c51e476bc161262a09f4124c7562feb227ba Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:33:21 +0530 Subject: [PATCH 36/83] #3538: test that OCIO transform files and configs are read again once they change --- crates/effects/src/ocio/tests.rs | 40 +++++++++++++++++++++++ crates/effects/src/ocio_config/tests.rs | 42 +++++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/crates/effects/src/ocio/tests.rs b/crates/effects/src/ocio/tests.rs index fe93dd25a..e17fd782a 100644 --- a/crates/effects/src/ocio/tests.rs +++ b/crates/effects/src/ocio/tests.rs @@ -396,3 +396,43 @@ fn color_stabilizer_samples_the_reference_at_the_points_reference_positions() { assert!((o(x) - (a + b * v(x))).abs() < 1e-3, "x {x}"); } } + +/// Writes `text` to `dir/name` with modification time `secs` (so an edit within the file system's +/// time resolution still moves the stamp), returning the path. +fn write_dated(dir: &std::path::Path, name: &str, text: &str, secs: u64) -> String { + let path = dir.join(name); + std::fs::write(&path, text).unwrap(); + let f = std::fs::File::options().write(true).open(&path).unwrap(); + f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap(); + path.to_string_lossy().into_owned() +} + +/// #3538: OCIO File Transform read a file once per process; an edited, created, repaired or +/// deleted file was never followed. +#[test] +fn an_ocio_transform_file_is_read_again_once_it_changes() { + const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n"; + const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n"; + let dir = std::env::temp_dir().join(format!("ec-fx-3538-file-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let at = |src: &str| load_file(src).map(|x| x.apply([0.5; 3], 1, false, "")); + let edited = write_dated(dir.as_path(), "edited.cube", BLACK, 1_000); + assert_eq!(at(&edited), Some([0.0; 3])); + write_dated(dir.as_path(), "edited.cube", WHITE, 2_000); + assert_eq!(at(&edited), Some([1.0; 3]), "an edited file, same size"); + let created = dir.as_path().join("created.cube").to_string_lossy().into_owned(); + assert_eq!(at(&created), None); + write_dated(dir.as_path(), "created.cube", WHITE, 1_000); + assert_eq!(at(&created), Some([1.0; 3]), "a file created after a failed load"); + let repaired = write_dated(dir.as_path(), "repaired.cube", "not a lut", 1_000); + assert_eq!(at(&repaired), None); + write_dated(dir.as_path(), "repaired.cube", WHITE, 2_000); + assert_eq!(at(&repaired), Some([1.0; 3]), "a repaired file"); + std::fs::remove_file(&repaired).unwrap(); + assert_eq!(at(&repaired), None, "a deleted file"); + // Inline text is its own content: the same text is the same transform. + let inline = load_file(BLACK).unwrap(); + assert!(Arc::ptr_eq(&inline, &load_file(BLACK).unwrap())); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/effects/src/ocio_config/tests.rs b/crates/effects/src/ocio_config/tests.rs index b616e6263..c36e467ea 100644 --- a/crates/effects/src/ocio_config/tests.rs +++ b/crates/effects/src/ocio_config/tests.rs @@ -410,3 +410,45 @@ fn builtin_styles() { fn rgb_white_xyz() -> [f64; 3] { [D65[0] / D65[1], 1.0, (1.0 - D65[0] - D65[1]) / D65[1]] } + +/// #3538: a custom `.ocio` config, and the LUTs it reads, were read once per process. +#[test] +fn an_ocio_config_and_its_luts_are_read_again_once_they_change() { + const BLACK: &str = "LUT_1D_SIZE 2\n0 0 0\n0 0 0\n"; + const WHITE: &str = "LUT_1D_SIZE 2\n1 1 1\n1 1 1\n"; + let dir = std::env::temp_dir().join(format!("ec-fx-3538-config-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(dir.as_path().join("luts")).unwrap(); + let write = |name: &str, text: &str, secs: u64| { + let path = dir.as_path().join(name); + std::fs::write(&path, text).unwrap(); + let f = std::fs::File::options().write(true).open(&path).unwrap(); + f.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs)).unwrap(); + path.to_string_lossy().into_owned() + }; + let config = |space: &str| { + format!( + "ocio_profile_version: 2\nsearch_path: luts\nroles:\n scene_linear: lin\ncolorspaces:\n - !\n name: lin\n - !\n name: {space}\n to_reference: ! {{src: grade.cube, interpolation: linear}}\n - !\n name: later\n to_reference: ! {{src: later.cube, interpolation: linear}}\n" + ) + }; + let src = dir.as_path().join("config.ocio").to_string_lossy().into_owned(); + assert!(load_config(&src).is_err(), "no config yet"); + write("config.ocio", &config("graded"), 1_000); + write("luts/grade.cube", BLACK, 1_000); + let to_lin = |space: &str| { + let c = load_config(&src).unwrap(); + c.convert(c.space(space).unwrap(), c.space("lin").unwrap(), [0.5; 3]) + }; + assert_eq!(to_lin("graded"), [0.0; 3], "a config created after a failed load"); + write("luts/grade.cube", WHITE, 2_000); + assert_eq!(to_lin("graded"), [1.0; 3], "a LUT the config reads, edited"); + assert_eq!(to_lin("later"), [0.5; 3], "a LUT not there yet passes through"); + write("luts/later.cube", BLACK, 1_000); + assert_eq!(to_lin("later"), [0.0; 3], "a LUT the config reads, created"); + write("config.ocio", &config("regraded"), 2_000); + assert!(load_config(&src).unwrap().space("regraded").is_some(), "an edited config"); + std::fs::remove_file(&src).unwrap(); + assert!(load_config(&src).is_err(), "a deleted config"); + std::fs::remove_dir_all(&dir).unwrap(); +} From e04ae226a915d7d50eb869174a082ef533f87c5b Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:37:02 +0530 Subject: [PATCH 37/83] #3536: the frames key writes group and property names, and the uid of a property with an expression Expressions find effects by name and read names (thisProperty.name, propertyGroup(1).name), and seed random/wiggle with the property uid, so both can change the frames. The Debug-based key had them. --- crates/engine/src/analysis/frames_key.rs | 34 +++++++---------- crates/engine/src/tests/analysis_signature.rs | 38 ++++++++++++++++--- 2 files changed, 47 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/analysis/frames_key.rs b/crates/engine/src/analysis/frames_key.rs index 44eb93d57..248b3b4f5 100644 --- a/crates/engine/src/analysis/frames_key.rs +++ b/crates/engine/src/analysis/frames_key.rs @@ -9,7 +9,7 @@ //! doesn't change keys. Of the layer and of a precomp, only the fields named in `layer_frames` are //! read (a precomp's contents are #3535). The //! text leaves out observations (whether footage is available) and data that never changes pixels -//! (names, labels, UI hints, markers), so they never drop saved analyses (#3534, #3536). +//! (colour labels, UI hints, markers), so they never drop saved analyses (#3534, #3536). //! //! Keys saved by 0.22–0.24 hashed derived `Debug` text instead. [`legacy`] still recognises //! them, and a matching saved key is kept rather than rewritten: frozen Roto Brush mattes and @@ -348,13 +348,15 @@ impl Text { } fn group(&mut self, g: &PropGroup, depth: usize) { - // The uid, name and colour label identify and label the group; they never change pixels. - let PropGroup { uid: _, match_id, name: _, kind, enabled, label: _, children } = g; + // Expressions find effects and groups by name (`effect("Blur")`, `propertyGroup(1).name`). + // The uid and colour label never change pixels. + let PropGroup { uid: _, match_id, name, kind, enabled, label: _, children } = g; if depth >= MAX_DEPTH { self.word("tooDeep"); return; } self.str("group", match_id); + self.str("name", name); self.group_kind(kind); self.field("enabled", enabled); for c in children { @@ -415,24 +417,16 @@ impl Text { } fn property(&mut self, pr: &Property) { - // The uid, name and UI hints identify and show the property; the 2D/3D-only and - // hold-only flags say where and how it can be edited, not what it evaluates to. - let Property { - uid: _, - match_id, - name: _, - value, - keys, - expr, - ui: _, - spatial, - hold_only: _, - three_d_only: _, - two_d_only: _, - shown_dims: _, - static_only: _, - } = pr; + // Expressions read the name (`thisProperty.name`) and seed `random`/`wiggle` with the + // uid: the uid is written for a property with an expression. UI hints and the 2D/3D-only + // and hold-only flags say where and how it can be edited, not what it evaluates to. + let Property { uid, match_id, name, value, keys, expr, ui: _, spatial, hold_only: _, three_d_only: _, two_d_only: _, shown_dims: _, static_only: _ } = + pr; self.str("prop", match_id); + self.str("name", name); + if expr.is_some() { + self.field("uid", uid); + } self.value(value); self.field("spatial", spatial); for k in keys { diff --git a/crates/engine/src/tests/analysis_signature.rs b/crates/engine/src/tests/analysis_signature.rs index 96323e6be..b73c79edd 100644 --- a/crates/engine/src/tests/analysis_signature.rs +++ b/crates/engine/src/tests/analysis_signature.rs @@ -100,7 +100,7 @@ fn analyses_saved_by_0_24_survive_edits_that_keep_their_frames() { fn signature_text_is_pinned() { let s = open(ANALYSED_0_24); let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); - let key = r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=video;w=160;h=120;par=1.0;rate=12/1;nativeRate=none;duration=254016000000;video=true;audio=false;alpha=ignore;matte=[0.0, 0.0, 0.0];loop=1;codec="H.264 (High)";frames=0;profile{rec709;};layer=none;fields=off;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=false;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=10bit;data=none;page=0;alphabetical=false;startTimecode=none;fileTimecode=none;placedPage=false;in=0;out=254016000000;start=0;stretch=100.0;timeRemap{prop="timeRemap";scalar=0.0;spatial=false;key=0;scalar=0.2;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;key=254016000000;scalar=1.0;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;expr=none;};compRate{rate=12/1;};"#; + let key = r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=video;w=160;h=120;par=1.0;rate=12/1;nativeRate=none;duration=254016000000;video=true;audio=false;alpha=ignore;matte=[0.0, 0.0, 0.0];loop=1;codec="H.264 (High)";frames=0;profile{rec709;};layer=none;fields=off;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=false;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=10bit;data=none;page=0;alphabetical=false;startTimecode=none;fileTimecode=none;placedPage=false;in=0;out=254016000000;start=0;stretch=100.0;timeRemap{prop="timeRemap";name="Time Remap";scalar=0.0;spatial=false;key=0;scalar=0.2;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;key=254016000000;scalar=1.0;interp=linear/linear;continuous=false;autoBezier=false;spatialIn=[0.0, 0.0, 0.0];spatialOut=[0.0, 0.0, 0.0];spatialAuto=true;spatialContinuous=false;roving=false;muted=false;expr=none;};compRate{rate=12/1;};"#; assert_eq!(crate::analysis::frames_key::signature_text(&s.project, COMP, layer), key); } @@ -151,11 +151,10 @@ fn todays_keys_survive_edits_that_keep_their_frames() { add_to_render_queue(&mut s); assert_eq!(saved(&s), before); } - // Names and labels only show things. - s.execute_checked("layer.rename", json!({"layer": CLIP.0, "name": "Renamed"})).unwrap(); - s.edit("rename", None, |p, _| { + // Colour labels and footage markers only show things. + s.edit("label", None, |p, _| { let l = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap(); - l.props.find_group_mut(82).unwrap().name = "Soft".into(); + l.props.find_group_mut(82).unwrap().label = Some(effectcraft_color::Label::Yellow); if let Some(effectcraft_project::ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) { f.markers.push(effectcraft_project::Marker::default()); } @@ -163,6 +162,16 @@ fn todays_keys_survive_edits_that_keep_their_frames() { }) .unwrap(); assert_eq!(saved(&s), before); + // Expressions find effects by name: renaming the effect above the Roto Brush is a change for it. + s.edit("rename", None, |p, _| { + p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(82).unwrap().name = "Soft".into(); + Ok(()) + }) + .unwrap(); + assert_eq!(saved(&s)[..2], before[..2]); + assert_eq!(saved(&s)[2].0, ""); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(saved(&s), before); // A real change still clears them. s.execute_checked("file.interpretFootage", json!({"items": [1], "invertAlpha": true})).unwrap(); @@ -234,3 +243,22 @@ fn keys_saved_by_0_24_while_offline_still_match() { assert_eq!(roto(&s), ("saved frozen".into(), ROTO_INPUT_0_24_OFFLINE.into())); } } + +/// Expressions seed `random` and `wiggle` with the property's uid: a Time Remap with an expression +/// keys its uid (a duplicated layer gets new uids), one without doesn't. +#[test] +fn an_expression_keys_its_property_uid() { + let s = open(ANALYSED_0_24); + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap().clone(); + let text = |l: &effectcraft_project::Layer| crate::analysis::frames_key::signature_text(&s.project, COMP, l); + let renumbered = |l: &effectcraft_project::Layer| { + let mut l = l.clone(); + l.props.get_mut("timeRemap").unwrap().uid += 1000; + l + }; + assert_eq!(text(&renumbered(&layer)), text(&layer)); + let mut with_expr = layer.clone(); + with_expr.props.get_mut("timeRemap").unwrap().expr = + Some(effectcraft_project::Expression { text: "seedRandom(0, true); random(0, 1)".into(), enabled: true }); + assert_ne!(text(&renumbered(&with_expr)), text(&with_expr)); +} From ef137cb2ce4e28824f6f08c5821573f96d65a766 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:43:54 +0530 Subject: [PATCH 38/83] #3538: OCIO transform files and configs follow their files through #3493's LUT cache Move the LUT cache that follows files by size and modification time into effects::file_cache and use it for ocio::lut::load_file and ocio_config::load_config. A config's entry depends on the .ocio file, the LUTs its FileTransforms read and the search-path places it looked for missing ones. check_lut_files and lut_generation now cover all three caches. --- crates/effects/src/file_cache.rs | 415 ++++++++++++++++++++++++ crates/effects/src/lib.rs | 4 +- crates/effects/src/ocio.rs | 4 +- crates/effects/src/ocio/lut.rs | 50 +-- crates/effects/src/ocio_config.rs | 56 ++-- crates/effects/src/ocio_config/tests.rs | 23 ++ crates/effects/src/utility.rs | 198 +++-------- 7 files changed, 546 insertions(+), 204 deletions(-) create mode 100644 crates/effects/src/file_cache.rs diff --git a/crates/effects/src/file_cache.rs b/crates/effects/src/file_cache.rs new file mode 100644 index 000000000..2bcbefede --- /dev/null +++ b/crates/effects/src/file_cache.rs @@ -0,0 +1,415 @@ +//! Caches of what effects read from files named by a parameter (a LUT, an OCIO transform file, an +//! OCIO config), keyed by the parameter text and checked against the files each result was read +//! from (#3493, #3538). +//! +//! A cached result remembers every file its load read, with the file's size and modification time +//! (its stamp) taken before reading, including the files a nested cached load read (a config's +//! `FileTransform` LUTs) and files looked for but missing. Each lookup stamps those files again +//! (one `metadata` call each) and loads again once one moved, so a file edited, created, deleted or +//! repaired on disk is followed. Inline text reads no file and is its own content. An edit that keeps +//! both the size and the modification time can't be told apart. +//! +//! Every file read is also followed by [`check_lut_files`], and [`lut_generation`] moves when one is +//! found changed: the viewers and frame caches drop the frames made before. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; +use std::time::SystemTime; + +/// A file's size and modification time when it was read (`None`: missing, or a file that could +/// not be described). A file whose stamp moved is read again. +pub(crate) type FileStamp = Option<(u64, Option)>; + +/// The files a load read and their stamps. +type Files = Vec<(String, FileStamp)>; + +/// At most this many files are followed by [`check_lut_files`]; the least recently read go first. +const MAX_FOLLOWED_FILES: usize = 1024; + +/// One cached result and what it was read from. +struct Entry { + files: Files, + value: V, + used: u64, + /// The result's size estimate and the parameter text, counted against the cache's byte bound. + bytes: usize, +} + +/// Results by parameter text, at most `max_entries` and `max_bytes` of them, the least recently +/// used going first. +pub(crate) struct SourceCache { + map: HashMap>, + clock: u64, + bytes: usize, + max_entries: usize, + max_bytes: usize, +} + +impl SourceCache { + pub(crate) fn new(max_entries: usize, max_bytes: usize) -> Self { + SourceCache { map: HashMap::new(), clock: 0, bytes: 0, max_entries, max_bytes } + } + + fn remove(&mut self, src: &str) { + if let Some(e) = self.map.remove(src) { + self.bytes = self.bytes.saturating_sub(e.bytes); + } + } + + /// Forget the results read from `path`. + fn forget_file(&mut self, path: &str) { + let stale: Vec = self.map.iter().filter(|(_, e)| e.files.iter().any(|(p, _)| p == path)).map(|(k, _)| k.clone()).collect(); + for src in stale { + self.remove(&src); + } + } + + /// Keep within the bounds, always the result for `keep`. + fn evict(&mut self, keep: &str) { + while self.map.len() > self.max_entries || (self.bytes > self.max_bytes && self.map.len() > 1) { + let Some(oldest) = self.map.iter().filter(|(k, _)| k.as_str() != keep).min_by_key(|(_, e)| e.used).map(|(k, _)| k.clone()) else { break }; + self.remove(&oldest); + } + } + + /// The files the result cached for `src` was read from. + pub(crate) fn files(&self, src: &str) -> Option> { + self.map.get(src).map(|e| e.files.iter().map(|(p, _)| p.clone()).collect()) + } + + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.map.len() + } + + #[cfg(test)] + pub(crate) fn contains(&self, src: &str) -> bool { + self.map.contains_key(src) + } + + #[cfg(test)] + pub(crate) fn bytes(&self) -> (usize, usize, usize) { + (self.bytes, self.map.values().map(|e| e.bytes).sum(), self.max_bytes) + } +} + +/// Lock a cache; a panic elsewhere while it was held leaves a usable map. +pub(crate) fn lock(cache: &Mutex>) -> MutexGuard<'_, SourceCache> { + cache.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A cache that registers with [`check_lut_files`] on first use. +pub(crate) struct Registered { + cache: OnceLock>>, + max_entries: usize, + max_bytes: usize, +} + +impl Registered { + pub(crate) const fn new(max_entries: usize, max_bytes: usize) -> Self { + Registered { cache: OnceLock::new(), max_entries, max_bytes } + } + + pub(crate) fn get(&'static self) -> &'static Mutex> { + self.cache.get_or_init(|| { + registry().push(self); + Mutex::new(SourceCache::new(self.max_entries, self.max_bytes)) + }) + } +} + +/// A cache [`check_lut_files`] tells to forget the results read from a changed file. +trait ForgetFile: Sync { + fn forget_file(&self, path: &str); + /// Add the files the cached results were read from to `out`. + fn held_files(&self, out: &mut HashSet); +} + +impl ForgetFile for Registered { + fn forget_file(&self, path: &str) { + if let Some(c) = self.cache.get() { + lock(c).forget_file(path); + } + } + + fn held_files(&self, out: &mut HashSet) { + if let Some(c) = self.cache.get() { + out.extend(lock(c).map.values().flat_map(|e| e.files.iter().map(|(p, _)| p.clone()))); + } + } +} + +fn registry() -> MutexGuard<'static, Vec<&'static dyn ForgetFile>> { + static REGISTRY: OnceLock>> = OnceLock::new(); + REGISTRY.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner) +} + +thread_local! { + /// The files read by the loads running on this thread, innermost last. + static READING: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// Note that the running load read (or looked for) `path`, stamped `stamp`. +pub(crate) fn note_file(path: &str, stamp: FileStamp) { + READING.with(|r| { + if let Ok(mut r) = r.try_borrow_mut() + && let Some(top) = r.last_mut() + && !top.iter().any(|(p, _)| p == path) + { + top.push((path.to_string(), stamp)); + } + }); +} + +/// Pops the files of a load when it ends, even by a panic. +struct Reading { + popped: bool, +} + +impl Reading { + fn start() -> Reading { + READING.with(|r| { + if let Ok(mut r) = r.try_borrow_mut() { + r.push(Vec::new()); + } + }); + Reading { popped: false } + } + + fn pop() -> Option { + READING.with(|r| r.try_borrow_mut().ok().and_then(|mut r| r.pop())) + } + + fn files(mut self) -> Files { + self.popped = true; + Self::pop().unwrap_or_default() + } +} + +impl Drop for Reading { + fn drop(&mut self) { + if !self.popped { + let _ = Self::pop(); + } + } +} + +/// The stamp of the file at `path` now: one `metadata` call. +pub(crate) fn file_stamp(path: &str) -> FileStamp { + std::fs::metadata(path).ok().map(|md| (md.len(), md.modified().ok())) +} + +/// Read the text file at `path` for the running load, stamped before reading (a file written +/// after it was stamped has a newer stamp, and is read again next time). +pub(crate) fn read(path: &str) -> std::io::Result { + note_file(path, file_stamp(path)); + std::fs::read_to_string(path) +} + +/// Note that the running load looked for `path` and did not find it: it loads again once the file +/// appears. +pub(crate) fn note_missing(path: &str) { + note_file(path, None); +} + +/// The result cached for `src`, or `load`'s (and its size estimate in bytes), cached. `load` reads +/// files with [`read`] (and notes the ones it looked for with [`note_missing`]); no lock is held +/// while it runs or while the files are stamped. +pub(crate) fn cached(cache: &Mutex>, src: &str, load: impl FnOnce() -> (V, usize)) -> V { + let files = lock(cache).map.get(src).map(|e| e.files.clone()); + let stale = files.is_some(); + if let Some(files) = files + && files.iter().all(|(p, s)| file_stamp(p) == *s) + { + let mut c = lock(cache); + c.clock += 1; + let now = c.clock; + if let Some(e) = c.map.get_mut(src) + && e.files == files + { + e.used = now; + let value = e.value.clone(); + drop(c); + // (an enclosing load depends on these files too) + for (p, s) in &files { + note_file(p, *s); + } + return value; + } + } + let reading = Reading::start(); + let (value, size) = load(); + let files = reading.files(); + follow(&files, stale); + for (p, s) in &files { + note_file(p, *s); + } + let bytes = size.saturating_add(src.len()); + let mut c = lock(cache); + c.clock += 1; + let used = c.clock; + c.remove(src); + c.map.insert(src.to_string(), Entry { files, value: value.clone(), used, bytes }); + c.bytes = c.bytes.saturating_add(bytes); + c.evict(src); + value +} + +/// How often a file a cached load read was found changed on disk ([`lut_generation`]). +static GENERATION: AtomicU64 = AtomicU64::new(0); + +/// The files followed by [`check_lut_files`]: the stamp each was last read with, and when. +#[derive(Default)] +struct Followed { + files: HashMap, + clock: u64, +} + +fn followed() -> MutexGuard<'static, Followed> { + static FOLLOWED: OnceLock> = OnceLock::new(); + FOLLOWED.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner) +} + +impl Followed { + /// Note that `files` were read with these stamps; true when one has a different stamp than + /// its last read's: a file changed on disk. + fn read(&mut self, files: &Files) -> bool { + let mut moved = false; + for (path, stamp) in files { + self.clock += 1; + let now = self.clock; + if self.files.insert(path.clone(), (*stamp, now)).is_some_and(|(old, _)| old != *stamp) { + moved = true; + } + } + moved + } + + /// Keep at most [`MAX_FOLLOWED_FILES`], letting go of the least recently read first but never + /// of a file in `held` (a cached result was read from it) or in `files` (just read). + fn trim(&mut self, held: &HashSet, files: &Files) { + while self.files.len() > MAX_FOLLOWED_FILES { + let Some(oldest) = self + .files + .iter() + .filter(|(p, _)| !held.contains(p.as_str()) && !files.iter().any(|(f, _)| f == *p)) + .min_by_key(|(_, (_, used))| *used) + .map(|(p, _)| p.clone()) + else { + break; + }; + self.files.remove(&oldest); + } + } +} + +/// The files the registered caches' results were read from. +fn held_files() -> HashSet { + let caches: Vec<&'static dyn ForgetFile> = registry().clone(); + let mut out = HashSet::new(); + for c in caches { + c.held_files(&mut out); + } + out +} + +/// Note that `files` were read with these stamps. A file read with a different stamp than last +/// time, or a load replacing a result whose files moved (`stale`), means a file changed on disk, +/// and frames made before may show the old contents. +fn follow(files: &Files, stale: bool) { + let (moved, over) = { + let mut f = followed(); + (f.read(files), f.files.len() > MAX_FOLLOWED_FILES) + }; + if over { + // (gathered without the followed files' lock: no two of these locks are ever nested) + let held = held_files(); + followed().trim(&held, files); + } + if moved || stale { + GENERATION.fetch_add(1, Ordering::AcqRel); + } +} + +/// Changes each time a file a cached load read is found changed on disk (by a load itself or +/// [`check_lut_files`]): frames made before then may show the old contents. +pub fn lut_generation() -> u64 { + GENERATION.load(Ordering::Acquire) +} + +/// Look at every file read (one `metadata` call each) and forget the results read from the ones +/// that changed on disk since, so the next load reads them again. Returns [`lut_generation`]. +pub fn check_lut_files() -> u64 { + let files: Vec<(String, FileStamp)> = followed().files.iter().map(|(p, (s, _))| (p.clone(), *s)).collect(); + // (stamped without the lock: a file on a slow share must not hold up renders) + let changed: Vec<(String, FileStamp, FileStamp)> = + files.into_iter().filter_map(|(path, old)| Some(file_stamp(&path)).filter(|now| *now != old).map(|now| (path, old, now))).collect(); + let caches: Vec<&'static dyn ForgetFile> = registry().clone(); + for (path, old, now) in changed { + { + let mut f = followed(); + // (a render that read the file meanwhile has noted its new stamp already) + match f.files.get_mut(&path) { + Some((s, _)) if *s == old => *s = now, + _ => continue, + } + } + for c in &caches { + c.forget_file(&path); + } + GENERATION.fetch_add(1, Ordering::AcqRel); + } + lut_generation() +} + +#[cfg(test)] +pub(crate) fn followed_stamp(path: &str) -> Option { + followed().files.get(path).map(|(s, _)| *s) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Past [`MAX_FOLLOWED_FILES`], the file just read is still followed (a list of its own: the + /// shared one's files belong to the other tests too). + #[test] + fn the_file_just_read_stays_followed_past_the_limit() { + let mut f = Followed::default(); + let held: HashSet = ["/followed/0.cube".to_string()].into(); + for i in 0..MAX_FOLLOWED_FILES + 8 { + let files = vec![(format!("/followed/{i}.cube"), Some((1, None)))]; + assert!(!f.read(&files)); + f.trim(&held, &files); + assert!(f.files.contains_key(&files[0].0), "{i}: the file just read"); + assert!(f.files.len() <= MAX_FOLLOWED_FILES); + } + assert!(f.files.contains_key("/followed/0.cube"), "a file a cached result was read from"); + assert!(!f.files.contains_key("/followed/1.cube"), "the least recently read other"); + assert!(f.read(&vec![("/followed/1030.cube".into(), Some((2, None)))]), "a moved stamp"); + } + + /// A nested cached load's files count for the enclosing load. + #[test] + fn an_enclosing_load_depends_on_a_nested_loads_files() { + static INNER: Registered = Registered::new(8, 1 << 20); + static OUTER: Registered = Registered::new(8, 1 << 20); + let v = cached(OUTER.get(), "outer", || { + note_missing("/nested/outer-own.cube"); + let inner = cached(INNER.get(), "inner", || { + note_missing("/nested/inner.cube"); + (7, 0) + }); + (inner, 0) + }); + assert_eq!(v, 7); + let files = lock(OUTER.get()).files("outer").unwrap(); + assert_eq!(files, vec!["/nested/outer-own.cube".to_string(), "/nested/inner.cube".to_string()]); + // A hit on the inner result still reports its files to a new enclosing load. + let w = cached(OUTER.get(), "outer 2", || (cached(INNER.get(), "inner", || (0, 0)), 0)); + assert_eq!(w, 7); + assert_eq!(lock(OUTER.get()).files("outer 2").unwrap(), vec!["/nested/inner.cube".to_string()]); + } +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 9105f4587..26b0008ef 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -39,6 +39,7 @@ mod keying2; pub mod keylight; mod matte; +mod file_cache; pub mod migrate; mod misc; pub mod mocha_shape; @@ -123,13 +124,14 @@ pub use channel3d::{ crypto_layer_name, crypto_layer_named, extractor_aux_channel, extractor_own_channel, id_color, is_extractor_copy, matte_only_px, reads_aux, selection_hashes, }; +pub use file_cache::{check_lut_files, lut_generation}; pub use ocio::{ColorOp, Straight, Tf, color_program}; pub use sim::{Acc, Blob, Bubble, Post, Shape, Sprite, SpritePlan, Tint, bubble_list, bubble_sample_bounds, drizzle_drops, mercury_blobs, sprite_plan}; pub use sim2::{ CausticsSetup, FoamDisc, FoamEnv, FoamPlan, Piece, PiecePlan, PieceTex, PixelPlan, WavePlan, Waves, caustics_setup, foam_full_plan, piece_plan, pixel_plan, wave_world_plan, }; -pub use utility::{Lut, check_lut_files, load_lut, lut_file, lut_generation, lut_params}; +pub use utility::{Lut, load_lut, lut_file, lut_files, lut_params}; pub use vr::{equi_dir as vr_equi_dir, rotation as vr_rotation}; /// Effect categories in Effects & Presets order. diff --git a/crates/effects/src/ocio.rs b/crates/effects/src/ocio.rs index 2daa9857d..febbc163c 100644 --- a/crates/effects/src/ocio.rs +++ b/crates/effects/src/ocio.rs @@ -24,8 +24,7 @@ //! * Configuration ▸ Custom reads a `.ocio` file instead ([`crate::ocio_config`]); what it can't //! apply is reported by [`warning`]. -use std::collections::HashMap; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::Arc; use effectcraft_color::ColorSpace; use effectcraft_color::space::{invert, mul, mul_vec, rgb_to_xyz}; @@ -51,6 +50,7 @@ pub use effects::parse_looks; pub use effects::{color_stabilizer_maps, warning}; #[cfg(test)] use effects::{tonemap, tonemap_inv}; +pub(crate) use lut::cached_files; pub use lut::{FileXform, load_file}; #[cfg(test)] pub use lut::{parse_file, parse_spi1d, parse_spi3d, parse_spimtx}; diff --git a/crates/effects/src/ocio/lut.rs b/crates/effects/src/ocio/lut.rs index de931a411..daa584278 100644 --- a/crates/effects/src/ocio/lut.rs +++ b/crates/effects/src/ocio/lut.rs @@ -1,5 +1,6 @@ use super::cdl::{Cdl, parse_cdl_xml}; -use super::{Arc, HashMap, Lut, Mutex, OnceLock, parse_cube}; +use super::{Arc, Lut, parse_cube}; +use crate::file_cache::{self, Registered}; // ---------------------------------------------------------------- LUT files @@ -264,33 +265,38 @@ pub fn parse_file(text: &str, ext: &str) -> Option { parse_3dl(text).map(|lut| FileXform::Lut { lut, shaper: None }) } -type FileCache = Mutex>>>; +/// [`load_file`]'s cache, by parameter text (bounded like [`crate::load_lut`]'s). +static FILES: Registered>> = Registered::new(64, 512 << 20); -/// Load (and cache) a transform from a file path or inline content. +/// The files the transform cached for `src` was read from. +pub(crate) fn cached_files(src: &str) -> Option> { + file_cache::lock(FILES.get()).files(src) +} + +/// Load (and cache) a transform from a file path or inline content. A file is stamped (one +/// `metadata` call) on every load and read again once its size or modification time moved (see +/// [`crate::file_cache`]); inline content is its own content. pub fn load_file(src: &str) -> Option> { let src_t = src.trim(); if src_t.is_empty() { return None; } - static CACHE: OnceLock = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - if let Ok(m) = cache.lock() - && let Some(v) = m.get(src) - { - return v.clone(); - } - let inline = src.contains('\n'); - let parsed = if inline { - parse_file(src, "") - } else { - let ext = std::path::Path::new(src_t).extension().and_then(std::ffi::OsStr::to_str).unwrap_or(""); - std::fs::read_to_string(src_t).ok().and_then(|t| parse_file(&t, ext)) - } - .map(Arc::new); - if let Ok(mut m) = cache.lock() { - m.insert(src.to_string(), parsed.clone()); - } - parsed + file_cache::cached(FILES.get(), src, || { + let parsed = if src.contains('\n') { + parse_file(src, "") + } else { + let ext = std::path::Path::new(src_t).extension().and_then(std::ffi::OsStr::to_str).unwrap_or(""); + file_cache::read(src_t).ok().and_then(|t| parse_file(&t, ext)) + } + .map(Arc::new); + let bytes = match parsed.as_deref() { + Some(FileXform::Lut { lut, shaper }) => crate::utility::lut_bytes(lut) + .saturating_add(shaper.as_ref().map_or(0, |s| s.iter().map(Vec::len).sum::().saturating_mul(std::mem::size_of::<(f32, f32)>()))), + Some(FileXform::Cdl(c)) => c.len().saturating_mul(std::mem::size_of::<(String, Cdl)>()), + Some(FileXform::Matrix { .. }) | None => 0, + }; + (parsed, bytes) + }) } impl FileXform { diff --git a/crates/effects/src/ocio_config.rs b/crates/effects/src/ocio_config.rs index e31281ede..17e61d4b1 100644 --- a/crates/effects/src/ocio_config.rs +++ b/crates/effects/src/ocio_config.rs @@ -42,9 +42,10 @@ //! resolving named transforms [`MAX_NAMED_DEPTH`] levels down or past [`MAX_OPS`] steps //! (a config that refers to itself in a loop), so a hostile config can't exhaust the stack. -use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::Arc; + +use crate::file_cache::{self, Registered}; use super::ocio::{ACES_CG, ACES2065_1, Cdl, D65, FileXform, P3, REC709, REC2020, Space, Tf, load_file, matrix, sp}; @@ -882,13 +883,21 @@ fn resolve(src: &str, dir: &Path, search: &[String]) -> Option { if src.trim().is_empty() { return None; } + // (a candidate not there is noted: the config is read again once it appears) + let found = |c: PathBuf| { + let there = c.exists(); + if !there { + file_cache::note_missing(&c.to_string_lossy()); + } + there.then_some(c) + }; let p = Path::new(src); if p.is_absolute() { - return p.exists().then(|| p.to_path_buf()); + return found(p.to_path_buf()); } let mut dirs: Vec = search.iter().map(|s| dir.join(s)).collect(); dirs.push(dir.to_path_buf()); - dirs.into_iter().map(|d| d.join(src)).find(|c| c.exists()) + dirs.into_iter().map(|d| d.join(src)).find_map(found) } // ---------------------------------------------------------------- the config @@ -1338,33 +1347,34 @@ impl<'c> Build<'c> { } } -type ConfigCache = Mutex, String>>>; +/// [`load_config`]'s cache, by parameter text. +static CONFIGS: Registered, String>> = Registered::new(16, 64 << 20); + +/// The files the config cached for `src` was read from: the `.ocio` file, the files its +/// `FileTransform`s read and the places it looked for missing ones. +pub(crate) fn cached_files(src: &str) -> Option> { + file_cache::lock(CONFIGS.get()).files(src) +} /// Load (and cache) a config from a `.ocio` path or the config text itself; why not, when it -/// can't be read. +/// can't be read. The config file and the files its `FileTransform`s read are stamped (one +/// `metadata` call each) on every load, and the config is read again once one of them moved or a +/// missing one appeared (see [`crate::file_cache`]). pub fn load_config(src: &str) -> Result, String> { let t = src.trim(); if t.is_empty() { return Err("no config file chosen".into()); } - static CACHE: OnceLock = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - if let Ok(m) = cache.lock() - && let Some(v) = m.get(src) - { - return v.clone(); - } - let parsed = if src.contains('\n') { - Config::parse(src, Path::new(".")) - } else { + file_cache::cached(CONFIGS.get(), src, || { + if src.contains('\n') { + return (Config::parse(src, Path::new(".")).map(Arc::new), 0); + } let p = Path::new(t); - std::fs::read_to_string(p).map_err(|e| format!("{t}: {e}")).and_then(|text| Config::parse(&text, p.parent().unwrap_or(Path::new(".")))) - } - .map(Arc::new); - if let Ok(mut m) = cache.lock() { - m.insert(src.to_string(), parsed.clone()); - } - parsed + match file_cache::read(t) { + Ok(text) => (Config::parse(&text, p.parent().unwrap_or(Path::new("."))).map(Arc::new), text.len()), + Err(e) => (Err(format!("{t}: {e}")), 0), + } + }) } #[cfg(test)] diff --git a/crates/effects/src/ocio_config/tests.rs b/crates/effects/src/ocio_config/tests.rs index c36e467ea..ec34b6723 100644 --- a/crates/effects/src/ocio_config/tests.rs +++ b/crates/effects/src/ocio_config/tests.rs @@ -452,3 +452,26 @@ fn an_ocio_config_and_its_luts_are_read_again_once_they_change() { assert!(load_config(&src).is_err(), "a deleted config"); std::fs::remove_dir_all(&dir).unwrap(); } + +/// A LUT a cached config read that changes is noticed without a render loading the config (the +/// interface's watcher), and the config's files name it (frame and layer cache keys hold them). +#[test] +fn check_lut_files_notices_a_configs_lut() { + let dir = std::env::temp_dir().join(format!("ec-fx-3538-check-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let lut = dir.join("watched.cube"); + std::fs::write(&lut, "LUT_1D_SIZE 2\n0 0 0\n1 1 1\n").unwrap(); + let config = dir.join("config.ocio"); + std::fs::write(&config, "ocio_profile_version: 2\ncolorspaces:\n - !\n name: lin\n - !\n name: graded\n to_reference: ! {src: watched.cube}\n").unwrap(); + let src = config.to_string_lossy().into_owned(); + assert!(load_config(&src).is_ok()); + let files = crate::lut_files(&src); + assert!(files.contains(&lut.to_string_lossy().into_owned()), "{files:?}"); + let before = crate::check_lut_files(); + assert!(cached_files(&src).is_some(), "an unchanged config stays"); + std::fs::write(&lut, "LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n").unwrap(); + assert!(crate::check_lut_files() > before); + assert!(cached_files(&src).is_none(), "a config whose LUT changed is read again"); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index 9d5fec491..d735dc286 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -1,10 +1,9 @@ //! Utility effects: bounds growth, HDR inspection/compression, Cineon log conversion and colour //! lookup tables (.cube). -use std::collections::HashMap; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, OnceLock, PoisonError}; +use std::sync::Arc; +use crate::file_cache::{self, Registered}; use effectcraft_color::luminance; use effectcraft_keyframe::Value; use effectcraft_project::ParamUi; @@ -331,84 +330,22 @@ impl Lut { } } -/// A LUT file's size and modification time when it was read (`None`: inline text, or a file -/// that could not be described). A file whose stamp moved is read again (#3493). -type FileStamp = Option<(u64, Option)>; - /// At most this many parsed LUTs (files and inline texts) are kept, and at most /// [`MAX_CACHED_BYTES`] of them; the least recently used go first. const MAX_CACHED_LUTS: usize = 64; const MAX_CACHED_BYTES: usize = 512 << 20; -/// At most this many LUT files are followed by [`check_lut_files`] beyond the ones whose LUT is -/// kept: the frames made with a LUT that left the cache are still dropped when its file changes. -const MAX_FOLLOWED_FILES: usize = 1024; +/// [`load_lut`]'s cache, by parameter text. +static LUTS: Registered>> = Registered::new(MAX_CACHED_LUTS, MAX_CACHED_BYTES); -/// A parsed LUT (or the failure to parse one) and what it was read from. -struct CachedLut { - stamp: FileStamp, - lut: Option>, - used: u64, - /// The parsed tables and the parameter text, counted against [`MAX_CACHED_BYTES`]. - bytes: usize, -} - -/// [`load_lut`]'s cache, by parameter text, and the stamp each LUT file was last read with. -#[derive(Default)] -struct LutCache { - map: HashMap, - files: HashMap, - clock: u64, - bytes: usize, -} - -impl LutCache { - /// Forget the LUT kept for `src`. - fn remove(&mut self, src: &str) { - if let Some(e) = self.map.remove(src) { - self.bytes = self.bytes.saturating_sub(e.bytes); - } - } - - /// Note that the file at `path` was read with `stamp`: a different stamp than the last read's - /// means it changed on disk, and frames made before may show the old LUT. - fn read_file(&mut self, path: &str, stamp: FileStamp) { - if self.files.insert(path.to_string(), stamp).is_some_and(|old| old != stamp) { - GENERATION.fetch_add(1, Ordering::AcqRel); - } - if self.files.len() > MAX_FOLLOWED_FILES { - let map = &self.map; - self.files.retain(|p, _| p.as_str() == path || map.keys().any(|src| lut_file(src) == Some(p.as_str()))); - } - } - - /// Keep at most [`MAX_CACHED_LUTS`] LUTs and [`MAX_CACHED_BYTES`], always the one for `keep`. - fn evict(&mut self, keep: &str) { - while self.map.len() > MAX_CACHED_LUTS || (self.bytes > MAX_CACHED_BYTES && self.map.len() > 1) { - let Some(oldest) = self.map.iter().filter(|(k, _)| k.as_str() != keep).min_by_key(|(_, e)| e.used).map(|(k, _)| k.clone()) else { break }; - self.remove(&oldest); - } - } -} - -/// How often a LUT file was found changed on disk ([`lut_generation`]). -static GENERATION: AtomicU64 = AtomicU64::new(0); - -fn lut_cache() -> std::sync::MutexGuard<'static, LutCache> { - static CACHE: OnceLock> = OnceLock::new(); - CACHE.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner) -} - -/// The stamp of the file at `path` now: one `metadata` call. -fn file_stamp(path: &str) -> FileStamp { - std::fs::metadata(path).ok().map(|md| (md.len(), md.modified().ok())) -} - -/// The parameters (paths in the effect's group) of `effect` that [`load_lut`] reads. +/// The parameters (paths in the effect's group) of `effect` that name a file an effect reads +/// through a cache that follows it ([`load_lut`], the OCIO file transforms and configs). pub fn lut_params(effect: &str) -> &'static [&'static str] { match effect { "ec.utility.applylut" => &["lut"], "ec.color.lumetri" => &["basicCorrection/inputLutFile", "creative/lookFile"], + "ec.color.ociofile" => &["file"], + "ec.color.ociocolorspace" | "ec.color.ociodisplay" => &["configFile"], _ => &[], } } @@ -421,75 +358,37 @@ pub fn lut_file(src: &str) -> Option<&str> { (!path.is_empty() && !path.contains('\n')).then_some(path) } -/// Changes each time a LUT file [`load_lut`] read is found changed on disk (by [`load_lut`] -/// itself or [`check_lut_files`]): frames made before then may show the old LUT. -pub fn lut_generation() -> u64 { - GENERATION.load(Ordering::Acquire) -} - -/// Look at every LUT file read (one `metadata` call each) and forget the LUTs of the ones that -/// changed on disk since, so the next [`load_lut`] reads them again. Returns [`lut_generation`]. -pub fn check_lut_files() -> u64 { - let files: Vec<(String, FileStamp)> = lut_cache().files.iter().map(|(p, s)| (p.clone(), *s)).collect(); - // (stamped without the lock: a file on a slow share must not hold up renders) - let changed: Vec<(String, FileStamp, FileStamp)> = - files.into_iter().filter_map(|(path, old)| Some(file_stamp(&path)).filter(|now| *now != old).map(|now| (path, old, now))).collect(); - if !changed.is_empty() { - let mut c = lut_cache(); - for (path, old, now) in changed { - // (a render that read the file meanwhile has noted its new stamp already) - if c.files.get(&path) == Some(&old) { - let stale: Vec = c.map.keys().filter(|src| lut_file(src) == Some(path.as_str())).cloned().collect(); - for src in stale { - c.remove(&src); - } - c.read_file(&path, now); - } - } - } - lut_generation() +/// The files a [`lut_params`] parameter set to `src` reads: the ones its cached result was read +/// from (an OCIO config's also the LUTs it names, and the places it looked for missing ones), else +/// the file it names. +pub fn lut_files(src: &str) -> Vec { + crate::ocio_config::cached_files(src) + .or_else(|| crate::ocio::cached_files(src)) + .or_else(|| file_cache::lock(LUTS.get()).files(src)) + .unwrap_or_else(|| lut_file(src).map(str::to_string).into_iter().collect()) } /// Load (and cache) a LUT from inline `.cube` text or a file path. A file is stamped (one -/// `metadata` call) on every load and read again once its size or modification time moved, so a -/// file edited, created, deleted or repaired on disk is followed; inline text is its own content. -/// An edit that keeps both the size and the modification time can't be told apart. +/// `metadata` call) on every load and read again once its size or modification time moved (see +/// [`crate::file_cache`]); inline text is its own content. pub fn load_lut(src: &str) -> Option> { if src.trim().is_empty() { return None; } - let file = lut_file(src); - let stamp = file.and_then(file_stamp); - { - let mut c = lut_cache(); - c.clock += 1; - let now = c.clock; - if let Some(e) = c.map.get_mut(src) - && e.stamp == stamp - { - e.used = now; - return e.lut.clone(); + file_cache::cached(LUTS.get(), src, || { + let lut = match lut_file(src) { + Some(path) => file_cache::read(path).ok().and_then(|t| parse_cube(&t)), + None => parse_cube(src), } - } - // (read and parsed without the lock; a file written after it was stamped has a newer stamp, - // and is read again next time) - let lut = match file { - Some(path) => std::fs::read_to_string(path).ok().and_then(|t| parse_cube(&t)), - None => parse_cube(src), - } - .map(Arc::new); - let tables = lut.as_ref().map_or(0, |l| l.d1.len().saturating_add(l.d3.len()).saturating_mul(std::mem::size_of::<[f32; 3]>())); - let bytes = tables.saturating_add(src.len()); - let mut c = lut_cache(); - if let Some(path) = file { - c.read_file(path, stamp); - } - c.remove(src); - let used = c.clock; - c.map.insert(src.to_string(), CachedLut { stamp, lut: lut.clone(), used, bytes }); - c.bytes = c.bytes.saturating_add(bytes); - c.evict(src); - lut + .map(Arc::new); + let bytes = lut.as_ref().map_or(0, |l| lut_bytes(l)); + (lut, bytes) + }) +} + +/// The size of a LUT's tables. +pub(crate) fn lut_bytes(l: &Lut) -> usize { + l.d1.len().saturating_add(l.d3.len()).saturating_mul(std::mem::size_of::<[f32; 3]>()) } fn apply_lut(ctx: &EffectCtx, mut b: Buf) -> Buf { @@ -685,11 +584,11 @@ mod tests { std::fs::write(&path, identity_cube(2)).unwrap(); let src = path.to_string_lossy().into_owned(); assert!(load_lut(&src).is_some()); - let before = check_lut_files(); - assert!(lut_cache().map.contains_key(&src), "an unchanged file stays"); + let before = crate::check_lut_files(); + assert!(file_cache::lock(LUTS.get()).contains(&src), "an unchanged file stays"); std::fs::write(&path, identity_cube(3)).unwrap(); - assert!(check_lut_files() > before); - assert!(!lut_cache().map.contains_key(&src), "a changed file is read again"); + assert!(crate::check_lut_files() > before); + assert!(!file_cache::lock(LUTS.get()).contains(&src), "a changed file is read again"); assert_eq!(load_lut(&src).map(|l| l.n3), Some(3)); std::fs::remove_dir_all(&dir).unwrap(); } @@ -703,12 +602,12 @@ mod tests { for i in 0..MAX_CACHED_LUTS + 8 { let text = format!("TITLE \"bounded {i}\"\n{}", identity_cube(2)); assert!(load_lut(&text).is_some()); - assert!(lut_cache().map.len() <= MAX_CACHED_LUTS); + assert!(file_cache::lock(LUTS.get()).len() <= MAX_CACHED_LUTS); } assert!(!Arc::ptr_eq(&first, &load_lut(&oldest).unwrap()), "the oldest was let go"); - let c = lut_cache(); - assert_eq!(c.bytes, c.map.values().map(|e| e.bytes).sum::(), "the bytes kept add up"); - assert!(c.bytes <= MAX_CACHED_BYTES); + let (bytes, sum, max) = file_cache::lock(LUTS.get()).bytes(); + assert_eq!(bytes, sum, "the bytes kept add up"); + assert!(bytes <= max); } /// A LUT file whose LUT left the cache is still followed: its frames are dropped when it @@ -725,26 +624,13 @@ mod tests { for i in 0..MAX_CACHED_LUTS + 8 { assert!(load_lut(&format!("TITLE \"evict {i}\"\n{}", identity_cube(2))).is_some()); } - assert!(!lut_cache().map.contains_key(&src), "its LUT left the cache"); + assert!(!file_cache::lock(LUTS.get()).contains(&src), "its LUT left the cache"); std::fs::write(&path, identity_cube(3)).unwrap(); - check_lut_files(); - assert_eq!(lut_cache().files.get(&src), Some(&file_stamp(&src)), "the change was noticed"); + crate::check_lut_files(); + assert_eq!(file_cache::followed_stamp(&src), Some(file_cache::file_stamp(&src)), "the change was noticed"); std::fs::remove_dir_all(&dir).unwrap(); } - /// Past [`MAX_FOLLOWED_FILES`], the file just read is still followed (a cache of its own: - /// the shared one's followed files belong to the other tests too). - #[test] - fn the_file_just_read_stays_followed_past_the_limit() { - let mut c = LutCache::default(); - for i in 0..MAX_FOLLOWED_FILES + 8 { - let path = format!("/followed/{i}.cube"); - c.read_file(&path, Some((1, None))); - assert!(c.files.contains_key(&path), "{i}: the file just read"); - } - assert!(c.files.len() <= MAX_FOLLOWED_FILES, "the others no longer cached are let go"); - } - #[test] fn one_d_lut_with_domain() { let lut = parse_cube("LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 2 2 2\n1 1 1\n0 0 0\n").unwrap(); From a700c5c8dbc3de214a615b1dea5d75fde5b545e4 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:43:54 +0530 Subject: [PATCH 39/83] #3538: layer keys and render reads include OCIO files and a config's LUTs --- crates/engine/src/tests/lut_files.rs | 40 +++++++++++++++++++++++++ crates/render/src/cache/dependencies.rs | 7 ++--- crates/render/src/reads.rs | 23 ++++++++++---- 3 files changed, 59 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/tests/lut_files.rs b/crates/engine/src/tests/lut_files.rs index 57d163b36..0153a9997 100644 --- a/crates/engine/src/tests/lut_files.rs +++ b/crates/engine/src/tests/lut_files.rs @@ -186,3 +186,43 @@ fn an_overridden_lut_file_renders_again() { write(&overridden, WHITE, 2_000); assert_all(centre(&s), 1.0); } + +/// #3538: OCIO File Transform and a custom OCIO config (and the LUT it names) follow their files +/// through warm layer caches, and a render notes the config's LUT for the disk cache. +#[test] +fn ocio_files_render_again_from_warm_caches() { + let dir = tempfile::tempdir().unwrap(); + let (lut, config, grade) = (dir.path().join("file.cube"), dir.path().join("config.ocio"), dir.path().join("luts/grade.cube")); + std::fs::create_dir_all(dir.path().join("luts")).unwrap(); + write(&lut, BLACK, 1_000); + write(&grade, BLACK, 1_000); + let text = "ocio_profile_version: 2\nsearch_path: luts\nroles:\n scene_linear: lin\ncolorspaces:\n - !\n name: lin\n - !\n name: graded\n to_reference: ! {src: grade.cube, interpolation: linear}\n"; + write(&config, text, 1_000); + let mut s = session(None); + let file = shot(&mut s, "OCIO File Transform", &[("file", json!(lut.to_string_lossy()))]); + let custom = shot( + &mut s, + "OCIO Color Space Transform", + &[("config", json!(1)), ("configFile", json!(config.to_string_lossy())), ("sourceName", json!("graded")), ("destinationName", json!("lin"))], + ); + assert_all(colours(&s, file), 0.0); + assert_all(colours(&s, custom), 0.0); + // (the first key of a config's layer can't know the LUTs it names before it is read) + assert_all(colours(&s, custom), 0.0); + let misses = s.layer_cache.stats().misses; + assert_all(colours(&s, file), 0.0); + assert_all(colours(&s, custom), 0.0); + assert_eq!(s.layer_cache.stats().misses, misses, "unchanged files keep the cached layers"); + let log = ReadLog::new(); + let mut r = s.renderer(RenderOpts::default()); + r.reads = Some(&log); + let _ = r.comp_frame(custom.1, Tick::ZERO); + let files = log.into_files(); + assert!(files.get(&grade.to_string_lossy()).is_some(), "the render notes the config's LUT: {files:?}"); + let generation = effectcraft_effects::lut_generation(); + write(&lut, WHITE, 2_000); + assert_all(colours(&s, file), 1.0); + write(&grade, WHITE, 2_000); + assert_all(colours(&s, custom), 1.0); + assert!(effectcraft_effects::lut_generation() > generation, "the viewer's frames made before are dropped"); +} diff --git a/crates/render/src/cache/dependencies.rs b/crates/render/src/cache/dependencies.rs index 5e8a8845b..6f14ddcde 100644 --- a/crates/render/src/cache/dependencies.rs +++ b/crates/render/src/cache/dependencies.rs @@ -175,11 +175,8 @@ impl Dependencies<'_> { // Properties overrides, which the render applies: a LUT file one of // them names is read too (#3493). for o in crate::fx_host::essential_overrides(ctx, layer) { - if let effectcraft_keyframe::Value::Str(src) = &o.value - && let Some(path) = effectcraft_effects::lut_file(src) - { - crate::reads::ReadFile::new(path, crate::reads::FileStamp::native(path).unwrap_or(crate::reads::FileStamp::Missing)) - .hash(self.h); + if let effectcraft_keyframe::Value::Str(src) = &o.value { + crate::reads::source_files(src).hash(self.h); } } let nested = EvalCtx::new(ctx.project, item, comp, time); diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index 9021f1e42..73b7ce830 100644 --- a/crates/render/src/reads.rs +++ b/crates/render/src/reads.rs @@ -65,20 +65,31 @@ impl ReadFile { } } -/// The LUT files effect `g` of `layer` reads at the context time (Apply Color LUT, Lumetri's -/// Input LUT and Look), each with its identity now. A layer's cache key holds them and a render +/// The files effect `g` of `layer` reads at the context time (Apply Color LUT, Lumetri's Input +/// LUT and Look, OCIO File Transform, a custom OCIO config and its LUTs: see +/// [`effectcraft_effects::lut_params`]), each with its identity now. A layer's cache key holds them and a render /// notes them, so what was made with a file that changed since is not used (#3493). pub(crate) fn lut_files(ctx: &crate::EvalCtx, layer: &effectcraft_project::Layer, g: &effectcraft_project::PropGroup) -> Vec { let effectcraft_project::GroupKind::Effect { effect } = &g.kind else { return Vec::new() }; effectcraft_effects::lut_params(effect) .iter() .filter_map(|param| match ctx.value(layer, g.prop(param)?) { - effectcraft_keyframe::Value::Str(src) => { - let path = effectcraft_effects::lut_file(&src)?; - Some(ReadFile::new(path, FileStamp::native(path).unwrap_or(FileStamp::Missing))) - } + effectcraft_keyframe::Value::Str(src) => Some(source_files(&src)), _ => None, }) + .flatten() + .collect() +} + +/// The files a file parameter set to `src` reads (an OCIO config's also the LUTs it names, #3538), +/// each with its identity now. +pub(crate) fn source_files(src: &str) -> Vec { + effectcraft_effects::lut_files(src) + .into_iter() + .map(|path| { + let stamp = FileStamp::native(&path).unwrap_or(FileStamp::Missing); + ReadFile::new(path, stamp) + }) .collect() } From 94ab5d77cf2e4a1fb2dd4775deffa5f7aef6ce3e Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:47:05 +0530 Subject: [PATCH 40/83] #3536: pin the key text of non-default footage, source layer, Cineon, colour space and solid values; every mask mode keys apart --- crates/engine/src/tests/analysis_signature.rs | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/crates/engine/src/tests/analysis_signature.rs b/crates/engine/src/tests/analysis_signature.rs index b73c79edd..045e279de 100644 --- a/crates/engine/src/tests/analysis_signature.rs +++ b/crates/engine/src/tests/analysis_signature.rs @@ -262,3 +262,54 @@ fn an_expression_keys_its_property_uid() { Some(effectcraft_project::Expression { text: "seedRandom(0, true); random(0, 1)".into(), enabled: true }); assert_ne!(text(&renumbered(&with_expr)), text(&with_expr)); } + +/// Non-default values of the types the key writes are written as their fixed words (#3536). +#[test] +fn nested_values_are_written_as_fixed_words() { + use effectcraft_project::{ + AlphaMode, CineonUnits, FieldOrder, FootageKind, GroupKind, ItemKind, LayerSource, MaskMode, MaskMotionBlur, Solid, SourceLayer, + }; + let mut s = open(ANALYSED_0_24); + let p = std::sync::Arc::make_mut(&mut s.project); + if let Some(ItemKind::Footage(f)) = p.item_mut(ItemId(1)).map(|i| &mut i.kind) { + f.kind = FootageKind::Sequence; + f.sequence = vec!["a_0001.png".into(), "a_0002.png".into()]; + f.alpha = AlphaMode::Premultiplied; + f.premul_color = [0.5, 0.25, 1.0]; + f.fields = FieldOrder::UpperFirst; + f.cineon.units = CineonUnits::Float; + f.cineon.log_conversion = true; + f.color_profile = Some(effectcraft_color::ColorSpace::DisplayP3); + f.layer = Some(SourceLayer { index: 3, name: "Sky".into(), layer_size: true, embedded: Some("id-7".into()), placed: true }); + f.native_rate = Some(effectcraft_time::FrameRate { num: 30000, den: 1001 }); + f.start_timecode = Some(42); + f.data = Some("{\"k\":1}".into()); + } + let layer = p.comp(COMP).unwrap().layer(CLIP).unwrap().clone(); + let text = crate::analysis::frames_key::signature_text(p, COMP, &layer); + let footage = text.split(";in=").next().unwrap(); + assert_eq!( + footage, + r#"frames/1;footage=1;footage;path="/tmp/effectcraft-3456-shake.mp4";kind=sequence;w=160;h=120;par=1.0;rate=12/1;nativeRate{rate=30000/1001;};duration=254016000000;video=true;audio=false;alpha=premultiplied;matte=[0.5, 0.25, 1.0];loop=1;codec="H.264 (High)";frames=2;file="a_0001.png";file="a_0002.png";profile{p3;};layer{index=3;layerSize=true;embedded{id="id-7";};placed=true;};fields=upper;invertAlpha=false;linearLight=false;preserveRgb=false;cineon;log=true;points=[0.0, 1023.0, 95.0, 685.0, 1.7, 20.0];units=float;data{text="{\"k\":1}";};page=0;alphabetical=false;startTimecode{frame=42;};fileTimecode=none;placedPage=false"# + ); + + let solid = p.add_item("Solid", Default::default(), None, ItemKind::Solid(Solid { color: [1.0, 0.5, 0.0], width: 64, height: 48, pixel_aspect: 2.0 })); + let mut on_solid = layer.clone(); + on_solid.source = LayerSource::Solid { item: solid }; + let text = crate::analysis::frames_key::signature_text(p, COMP, &on_solid); + assert_eq!(text.split(";in=").next().unwrap(), format!("frames/1;solid={};solid;color=[1.0, 0.5, 0.0];w=64;h=48;par=2.0", solid.0)); + + // Every mask mode and motion blur setting gives its own Input Key. + let mask = layer.masks().unwrap().groups().next().unwrap().uid; + let mut keys = std::collections::BTreeSet::new(); + for mode in MaskMode::ALL { + for blur in [MaskMotionBlur::SameAsLayer, MaskMotionBlur::On, MaskMotionBlur::Off] { + let mut l = layer.clone(); + if let GroupKind::Mask { mode: m, motion_blur, .. } = &mut l.props.find_group_mut(mask).unwrap().kind { + (*m, *motion_blur) = (mode, blur); + } + keys.insert(crate::analysis::frames_key::input_key(p, COMP, &l, ROTO)); + } + } + assert_eq!(keys.len(), MaskMode::ALL.len() * 3); +} From 57990d9a47843b2d316e242e571b3d4e29cb9427 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:48:30 +0530 Subject: [PATCH 41/83] #3535: Warp Stabilizer and 3D Camera Tracker keys cover the layer's masks and the effects above them Their analyses are made from the layer's input to the effect (masks, then the effects above it), but the key covered only the layer's frames, so a mask or effect edit kept a stale analysis. frames_key::analysis_key adds the masks, the effects above the instance and the Effects switch. Keys saved before (frames only) stay valid while each edit keeps the input. --- crates/engine/src/analysis/camera_track.rs | 24 ++-- crates/engine/src/analysis/frames_key.rs | 47 ++++++++ crates/engine/src/analysis/warp.rs | 13 ++- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/analysis_inputs.rs | 128 +++++++++++++++++++++ crates/engine/src/tests/mask_warp.rs | 9 ++ 6 files changed, 205 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/tests/analysis_inputs.rs diff --git a/crates/engine/src/analysis/camera_track.rs b/crates/engine/src/analysis/camera_track.rs index 43f7e1746..8209af543 100644 --- a/crates/engine/src/analysis/camera_track.rs +++ b/crates/engine/src/analysis/camera_track.rs @@ -26,7 +26,7 @@ use effectcraft_track::camtrack::linalg::{self, Similarity, V3}; use effectcraft_track::camtrack::{AnalyzeOpts, CameraSolve, CameraTracks, SolveSettings, Target, TrackAnalyzer}; use serde::Serialize; -use crate::analysis::frames_key::{self, signature}; +use crate::analysis::frames_key; use crate::offload::JobKind; use crate::tracking::lock; use crate::warp::analysis_times; @@ -82,7 +82,7 @@ pub struct CameraJob { pub comp: ItemId, pub layer: LayerId, pub effect: Uid, - /// The layer signature the tracks are made from, and the solve settings key. + /// What the tracks are made from (`tracks_key`), and the solve settings key. key: String, solve_key: String, } @@ -123,19 +123,21 @@ fn str_of(g: &PropGroup, m: &str) -> String { } } -/// What a tracker's tracks are made from: the layer's frames and Detailed Analysis. +/// What a tracker's tracks are made from: its input (the layer's frames under its masks and the +/// effects above it, `frames_key::analysis_key`) and Detailed Analysis. fn tracks_key(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> String { - tracks_key_of(signature(project, cid, l), g) + tracks_key_of(frames_key::analysis_key(project, cid, l, g.uid), g) } -fn tracks_key_of(signature: String, g: &PropGroup) -> String { +fn tracks_key_of(input: String, g: &PropGroup) -> String { let detailed = effectcraft_effects::warp_stab::param(&static_params(g), "advanced/detailedAnalysis").is_some_and(Value::as_bool); - format!("{signature}{}", if detailed { "+detailed" } else { "" }) + format!("{input}{}", if detailed { "+detailed" } else { "" }) } -/// Whether the tracker's saved tracks are made from the layer's current frames and settings. -fn tracks_match(project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> bool { - frames_key::key_matches(project, cid, l, &str_of(g, TRACKS_KEY), |s, _| tracks_key_of(s, g)) +/// Whether the tracker's saved tracks are made from its current input and settings, after an +/// edit from `before` to `project` ([`frames_key::analysis_key_matches`]). +fn tracks_match(before: &Project, project: &Project, cid: ItemId, l: &Layer, g: &PropGroup) -> bool { + frames_key::analysis_key_matches(before, project, cid, l, g.uid, &str_of(g, TRACKS_KEY), |k| tracks_key_of(k, g)) } /// Parameters of an instance from static values (the tracker's settings are not animated). @@ -175,7 +177,7 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId, let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id)); for g in fx.groups().filter(|g| is_tracker(g)) { let tracked = !str_of(g, TRACKS).is_empty(); - if tracked && !tracks_match(after, *cid, l, g) { + if tracked && !tracks_match(before, after, *cid, l, g) { clears.push((*cid, l.id, g.uid, true)); todo.push((*cid, l.id, g.uid)); } else if tracked && str_of(g, SOLVE_KEY) != ct::solve_key(&ct::settings(&static_params(g))) { @@ -335,7 +337,7 @@ impl Session { let key = tracks_key(&self.project, comp, l, g); let settings = ct::settings(¶ms); let solve_key = ct::solve_key(&settings); - let tracks = ct::tracks(¶ms).filter(|_| tracks_match(&self.project, comp, l, g)); + let tracks = ct::tracks(¶ms).filter(|_| tracks_match(&self.project, &self.project, comp, l, g)); let n = times.len(); let work = CamWork { project: self.project.clone(), diff --git a/crates/engine/src/analysis/frames_key.rs b/crates/engine/src/analysis/frames_key.rs index 44eb93d57..7fc97f89e 100644 --- a/crates/engine/src/analysis/frames_key.rs +++ b/crates/engine/src/analysis/frames_key.rs @@ -83,6 +83,53 @@ pub(crate) fn input_key_of(signature: String, layer: &Layer, uid: Uid) -> String hex(&t.0) } +/// The first word of an [`analysis_key`]'s text: a later change to what it writes bumps it. +const ANALYSIS_VERSION: &str = "analysis/1"; + +/// What a Warp Stabilizer or 3D Camera Tracker, the instance `uid` of `layer`, analyses: its +/// input, the layer's frames ([`signature`]) under its masks and the effects above it (#3535). +/// The instance's own settings and the effects below it are not part of it. +pub(crate) fn analysis_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String { + let mut t = Text::new(); + t.word(ANALYSIS_VERSION); + t.word(&signature(p, comp, layer)); + // The Effects switch turns the effects above on or off (it has none when it is the first). + if layer.effects().and_then(|fx| fx.groups().next()).is_some_and(|g| g.uid != uid) { + t.field("effectsSwitch", layer.switches.effects); + } + t.inputs_above(layer, uid); + hex(&t.0) +} + +/// Whether `saved`, the key saved with the analysis of instance `uid` of `layer` in `after`, is +/// for its current input ([`analysis_key`]). `key` makes the saved form from an input key or a +/// frames signature (the tracker adds its Detailed Analysis). +/// +/// Keys saved before #3535 hashed only the layer's frames ([`signature`], or a [`legacy`] one). +/// Such a key is taken to be for the input the layer had when it was opened, and stays valid +/// while each edit (from `before` to `after`) keeps the input: the first edit that changes it +/// clears the analysis. A layer or instance new in `after` (pasted, opened) keeps such a key +/// while its frames match. +pub(crate) fn analysis_key_matches( + before: &Project, + after: &Project, + comp: ItemId, + layer: &Layer, + uid: Uid, + saved: &str, + key: impl Fn(String) -> String, +) -> bool { + let now = analysis_key(after, comp, layer, uid); + if key(now.clone()) == saved { + return true; + } + let old = before.comp(comp).and_then(|c| c.layer(layer.id)).filter(|l| l.props.find_group(uid).is_some()); + match old { + Some(old) => key_matches(before, comp, old, saved, |s, _| key(s)) && analysis_key(before, comp, old, uid) == now, + None => key_matches(after, comp, layer, saved, |s, _| key(s)), + } +} + /// Whether `saved`, a key saved with an analysis of `layer`, is for the layer's current frames. /// `key` makes such a key from a signature of the given era. A key an earlier release saved for /// the same frames matches too: keep it rather than rewrite it (analysing writes today's). diff --git a/crates/engine/src/analysis/warp.rs b/crates/engine/src/analysis/warp.rs index 610e994ca..10b9a0ac1 100644 --- a/crates/engine/src/analysis/warp.rs +++ b/crates/engine/src/analysis/warp.rs @@ -6,8 +6,9 @@ //! analyzer (step 1 of 2, "Analyzing in background"); step 2 ("Stabilizing") derives the //! stabilization plan once to validate and cache the result. When the job finishes, the analysis is //! written into the effect's hidden Analysis parameter as one undo step, together with a key of -//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap; the key is -//! `analysis::frames_key`'s, shared with the 3D Camera Tracker and Roto Brush). Edits that change +//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap, its masks and +//! the effects above the Warp Stabilizer: `analysis::frames_key::analysis_key`, shared with the 3D +//! Camera Tracker). Edits that change //! those clear the analysis (`invalidate`, run after every edit) and queue the effect for //! re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses //! automatically too). Footage going offline is not such a change. @@ -25,7 +26,7 @@ use effectcraft_time::Tick; use effectcraft_track::stabilize::{AnalyzeOpts, Analyzer, WarpAnalysis}; use serde::Serialize; -use crate::analysis::frames_key::{self, signature}; +use crate::analysis::frames_key; use crate::tracking::lock; use crate::{Event, Session}; @@ -71,7 +72,7 @@ pub struct WarpJob { pub comp: ItemId, pub layer: LayerId, pub effect: Uid, - /// The layer signature the analysis is made from. + /// What the analysis is made from (`frames_key::analysis_key`). key: String, } @@ -126,7 +127,7 @@ pub(crate) fn invalidate(before: &Project, after: &mut Project) -> Vec<(ItemId, let old_layer = before.comp(*cid).and_then(|bc| bc.layer(l.id)); for g in fx.groups().filter(|g| is_warp(g)) { let analysed = !str_of(g, ANALYSIS).is_empty(); - if analysed && !frames_key::key_matches(after, *cid, l, &str_of(g, ANALYSIS_KEY), |s, _| s) { + if analysed && !frames_key::analysis_key_matches(before, after, *cid, l, g.uid, &str_of(g, ANALYSIS_KEY), |k| k) { clear.push((*cid, l.id, g.uid)); todo.push((*cid, l.id, g.uid)); } else if !analysed && old_layer.and_then(|ol| ol.props.find_group(g.uid)).is_none() { @@ -305,7 +306,7 @@ impl Session { detailed, times, }; - let key = signature(&self.project, comp, l); + let key = frames_key::analysis_key(&self.project, comp, l, effect); if !wait && self.offloads() { drop(work); self.offload_analysis(crate::offload::WorkerJob::Warp { comp, layer, effect })?; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index eddeeb7ef..b2964916f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1,6 +1,7 @@ mod add_item_options; mod aep_export; mod aep_import; +mod analysis_inputs; mod analysis_signature; mod anim_presets; mod anim_tools; diff --git a/crates/engine/src/tests/analysis_inputs.rs b/crates/engine/src/tests/analysis_inputs.rs new file mode 100644 index 000000000..414ff0939 --- /dev/null +++ b/crates/engine/src/tests/analysis_inputs.rs @@ -0,0 +1,128 @@ +//! Warp Stabilizer and 3D Camera Tracker analyses follow their input: the layer's frames, its +//! masks, the effects above them and a precomp's contents (#3535). Edits that leave the input +//! as it was (effects below, names, labels) keep them. + +use effectcraft_effects::camera_tracker::{TRACKS, TRACKS_KEY}; +use effectcraft_effects::warp_stab::{ANALYSIS, ANALYSIS_KEY}; +use effectcraft_keyframe::Value; +use effectcraft_project::{ItemId, LayerId, Project}; +use serde_json::{Value as Json, json}; + +use crate::Session; + +const COMP: ItemId = ItemId(2); +const CLIP: LayerId = LayerId(3); +const WARP: u64 = 26; +const TRACKER: u64 = 54; + +/// `tracked-0.22.ecproj`'s clip with a mask and, in order, a Warp Stabilizer, a 3D Camera +/// Tracker, a Gaussian Blur and a Roto Brush. +const ANALYSED: &str = include_str!("fixtures/analysed-0.24.ecproj"); + +fn open(json: &str) -> Session { + let mut s = Session::default(); + s.replace_project(Project::from_json(json).unwrap(), None); + s.open_comp(COMP); + s +} + +/// Which keys an analysis saves. +#[derive(Clone, Copy, Debug)] +enum Saved { + /// Today's: the input to the instance. + Input, + /// Before #3535: the layer's frames only (still recognised). + Frames, +} + +/// The key an analysis of instance `uid` (no Detailed Analysis) saves. +fn key(p: &Project, uid: u64, saved: Saved) -> String { + let layer = p.comp(COMP).unwrap().layer(CLIP).unwrap(); + match saved { + Saved::Input => crate::analysis::frames_key::analysis_key(p, COMP, layer, uid), + Saved::Frames => crate::analysis::frames_key::signature(p, COMP, layer), + } +} + +/// Give the Warp Stabilizer and the tracker an analysis of the clip as it is now, saved with +/// `saved` keys, and reopen the project. +fn analyse(s: &mut Session, saved: Saved) { + let mut p = (*s.project).clone(); + let set = |p: &mut Project, uid: u64, data: &str, id: &str, key: &str| { + let g = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.find_group_mut(uid).unwrap(); + g.prop_mut(data).unwrap().value = Value::Str(format!("saved {data}")); + g.prop_mut(id).unwrap().value = Value::Str(key.into()); + }; + // The Warp Stabilizer is above the tracker: its analysis is part of the tracker's input. + let k = key(&p, WARP, saved); + set(&mut p, WARP, ANALYSIS, ANALYSIS_KEY, &k); + let k = key(&p, TRACKER, saved); + set(&mut p, TRACKER, TRACKS, TRACKS_KEY, &k); + *s = open(&p.to_json()); + run(s, "renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})); + assert_eq!(analysed(s), [true, true], "{saved:?}"); +} + +/// Whether the Warp Stabilizer and the tracker still have their analysis. +fn analysed(s: &Session) -> [bool; 2] { + let layer = s.project.comp(COMP).unwrap().layer(CLIP).unwrap(); + let has = |uid: u64, id: &str| matches!(&layer.props.find_group(uid).unwrap().prop(id).unwrap().value, Value::Str(s) if !s.is_empty()); + [has(WARP, ANALYSIS), has(TRACKER, TRACKS)] +} + +fn run(s: &mut Session, cmd: &str, params: Json) -> Json { + s.execute_checked(cmd, params).unwrap() +} + +fn undo(s: &mut Session) { + run(s, "edit.undo", json!({})); +} + +/// An edit, its effect on the two analyses, and that undo brings them back. +fn check(s: &mut Session, cmd: &str, params: Json, kept: [bool; 2]) { + assert_eq!(analysed(s), [true, true], "before {cmd} {params}"); + run(s, cmd, params.clone()); + assert_eq!(analysed(s), kept, "{cmd} {params}"); + undo(s); + assert_eq!(analysed(s), [true, true], "undo of {cmd} {params}"); +} + +#[test] +fn masks_and_effects_above_are_part_of_the_input() { + for saved in [Saved::Input, Saved::Frames] { + masks_and_effects_above(saved); + } +} + +fn masks_and_effects_above(saved: Saved) { + let mut s = open(ANALYSED); + analyse(&mut s, saved); + // The layer's mask is under every effect. + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3}), [false, false]); + // The Warp Stabilizer is above the tracker: its settings change the tracker's input only. + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#1/stabilization/smoothness", "value": 20}), [true, false]); + // The Gaussian Blur and the Roto Brush are below both. + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#3/blurriness", "value": 4}), [true, true]); + run(&mut s, "layer.rename", json!({"layer": CLIP.0, "name": "Renamed"})); + assert_eq!(analysed(&s), [true, true]); + // The Effects switch turns the Warp Stabilizer (above the tracker) off. + check(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": false}), [true, false]); + + // An effect moved above the Warp Stabilizer is part of both inputs, and its settings too. + s.edit("blur first", None, |p, _| { + let fx = p.comp_mut(COMP).unwrap().layer_mut(CLIP).unwrap().props.sub_mut("effects").unwrap(); + let blur = fx.children.remove(2); + fx.children.insert(0, blur); + Ok(()) + }) + .unwrap(); + assert_eq!(analysed(&s), [false, false]); + analyse(&mut s, saved); + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#1/blurriness", "value": 4}), [false, false]); + + // Saved and reopened, they still match, and a mask edit still clears them. + let mut s = open(&s.project.to_json()); + run(&mut s, "renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})); + assert_eq!(analysed(&s), [true, true]); + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3}), [false, false]); +} diff --git a/crates/engine/src/tests/mask_warp.rs b/crates/engine/src/tests/mask_warp.rs index 5387fe562..e884091a5 100644 --- a/crates/engine/src/tests/mask_warp.rs +++ b/crates/engine/src/tests/mask_warp.rs @@ -391,6 +391,15 @@ fn warp_analysis_invalidates_and_cancels() { let fx = r["effect"].as_u64().unwrap(); let cid = s.active_comp_id().unwrap(); assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], true); + // A mask is part of the analysed input (#3535): drawing one clears the analysis, undo keeps it. + s.execute_checked("mask.new", json!({"layer": clip.0, "vertices": [[10, 10], [200, 10], [200, 150]]})).unwrap(); + assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], false); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], true); + // An effect below it isn't. + s.execute_checked("effect.apply", json!({"layers": [clip.0], "effect": "ec.blur.gaussian"})).unwrap(); + assert_eq!(s.execute("warp.status", json!({})).unwrap()["analyzed"], true); + s.execute_checked("edit.undo", json!({})).unwrap(); // Trimming the layer clears the analysis and queues it again. s.execute("layer.timing", json!({"layers": [clip.0], "out": 0.8})).unwrap(); let st = s.execute("warp.status", json!({})).unwrap(); From 51b8521eb3fb7c1d845218f666733ba17c3fc4ed Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:53:09 +0530 Subject: [PATCH 42/83] #3539: test that the viewers show a still reloaded at the same size --- crates/ui-egui/src/app/viewer_frames.rs | 50 +++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/crates/ui-egui/src/app/viewer_frames.rs b/crates/ui-egui/src/app/viewer_frames.rs index d7c02a99c..a76c88b2d 100644 --- a/crates/ui-egui/src/app/viewer_frames.rs +++ b/crates/ui-egui/src/app/viewer_frames.rs @@ -285,4 +285,54 @@ mod tests { effectcraft_engine::lut_reload::check(); settle(&mut harness, 255); } + + /// #3539: a still re-saved at the same size and reloaded as changed on disk keeps the project + /// as it was (same revision and content key); the viewers showed the old picture, the new + /// frame having the key of the one on screen. A reload's purge gives the frames new keys, once. + #[test] + fn the_viewers_show_a_still_reloaded_at_the_same_size() { + let dir = tempfile::tempdir().unwrap(); + let png = dir.path().join("still.png"); + let save = |rgb: [u8; 3]| image::RgbaImage::from_pixel(64, 36, image::Rgba([rgb[0], rgb[1], rgb[2], 255])).save(&png).unwrap(); + save([255, 0, 0]); + let mut session = effectcraft_host::session(); + session.execute("comp.new", serde_json::json!({"width": 64, "height": 36, "duration": 2})).unwrap(); + let cid = session.active_comp_id().unwrap(); + let item = session.execute("file.import", serde_json::json!({"paths": [png.to_string_lossy()]})).unwrap()["items"][0].clone(); + session.execute("layer.addItem", serde_json::json!({"item": item})).unwrap(); + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_| crate::EffectcraftApp::new(session)); + let centre = |h: &egui_kittest::Harness<'_, crate::EffectcraftApp>| { + h.state().viewer_image.as_ref().map(|img| img.pixels[img.pixels.len() / 2 + img.size[0] / 2].r()) + }; + let settle = |h: &mut egui_kittest::Harness<'_, crate::EffectcraftApp>, want: u8| { + for _ in 0..400 { + h.step(); + if centre(h) == Some(want) { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the viewer shows {:?}, not {want}", centre(h)); + }; + settle(&mut harness, 255); + // (every viewer, passive ones too, asks for its frame by this key) + let key = |h: &egui_kittest::Harness<'_, crate::EffectcraftApp>| h.state().frame_key(cid, 0, 1.0); + let before = key(&harness); + harness.step(); + assert_eq!(key(&harness), before, "no purge, the same key: nothing is uploaded again"); + // Reload Footage Changed on Disk: the app's watcher saw the file's stamp move. + let path = png.to_string_lossy().into_owned(); + let stamps = |n| vec![(path.clone(), Some((n, u128::from(n))))]; + effectcraft_engine::footage_reload::apply_stamps(&mut harness.state_mut().session, stamps(1)).unwrap(); + save([0, 0, 255]); + let revision = harness.state().session.revision; + let reloaded = effectcraft_engine::footage_reload::apply_stamps(&mut harness.state_mut().session, stamps(2)).unwrap(); + assert_eq!(reloaded["files"], 1, "{reloaded}"); + assert_eq!(harness.state().session.revision, revision, "the project is as it was"); + settle(&mut harness, 0); + let after = key(&harness); + assert_ne!(after, before, "the reloaded frame has a key of its own"); + harness.step(); + assert_eq!(key(&harness), after, "one new key per purge"); + } } From 385b9530a1f6310556351e0cdb84f6f49deee4e6 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:00:14 +0530 Subject: [PATCH 43/83] #3535: Warp Stabilizer and 3D Camera Tracker keys cover a precomp's contents On a precomp layer the key covered only the nested comp's size, rate and duration, so an edit inside the precomp kept a stale analysis. The key now writes the precomp layer's Essential Properties and what its comp draws, field by field and recursively. Each comp is written once per key and nesting is capped, so shared, deep or cyclic precomps are keyed in bounded time. Docs say what clears an analysis. --- crates/engine/src/analysis/frames_key.rs | 204 +++++++++++++++++++-- crates/engine/src/analysis/warp.rs | 7 +- crates/engine/src/tests/analysis_inputs.rs | 69 +++++++ crates/engine/src/tests/camera_track.rs | 9 + docs/agents.md | 8 +- 5 files changed, 276 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/analysis/frames_key.rs b/crates/engine/src/analysis/frames_key.rs index 7fc97f89e..9e80a9dc7 100644 --- a/crates/engine/src/analysis/frames_key.rs +++ b/crates/engine/src/analysis/frames_key.rs @@ -2,26 +2,29 @@ //! Camera Tracker and Roto Brush / Object Matte. //! //! The key hashes a text this module writes field by field. The source item (footage and its -//! settings, solid), the Time Remap property and the masks and effect groups (their properties, -//! keyframes and values) are destructured or matched in full, and each variant is written as a -//! fixed word: a new field or variant doesn't compile until it is decided here, written if it -//! changes the layer's frames, left out (with a reason) if it doesn't. Renaming a field or variant -//! doesn't change keys. Of the layer and of a precomp, only the fields named in `layer_frames` are -//! read (a precomp's contents are #3535). The -//! text leaves out observations (whether footage is available) and data that never changes pixels -//! (names, labels, UI hints, markers), so they never drop saved analyses (#3534, #3536). +//! settings, solid), the Time Remap property, the masks and effect groups (their properties, +//! keyframes and values) and a precomp's comp and layers are destructured or matched in full, and +//! each variant is written as a fixed word (or, for an enum the project file names, its name +//! there): a new field or variant doesn't compile until it is decided here, written if it changes +//! the layer's frames, left out (with a reason) if it doesn't. Renaming a field or variant doesn't +//! change keys. Of the analysed layer itself, only the fields named in `layer_frames` and +//! [`analysis_key`] are read. The text leaves out observations (whether footage is available) and +//! data that never changes pixels (names, labels, UI hints, markers), so they never drop saved +//! analyses (#3534, #3536). //! //! Keys saved by 0.22–0.24 hashed derived `Debug` text instead. [`legacy`] still recognises //! them, and a matching saved key is kept rather than rewritten: frozen Roto Brush mattes and //! segmentations hash the saved key itself. +use std::collections::HashSet; use std::fmt::Write as _; use effectcraft_color::ColorSpace; use effectcraft_keyframe::{Ease, FeatherPoint, Gradient, Interp, Keyframe, ShapePath, Value}; use effectcraft_project::{ - AlphaMode, CineonSettings, CineonUnits, Expression, FeatherFalloff, FieldOrder, Footage, FootageKind, GroupKind, ItemId, ItemKind, Layer, LayerSource, - LightKind, MaskMode, MaskMotionBlur, Node, PrimitiveKind, Project, PropGroup, Property, Solid, SourceLayer, Uid, + AlphaMode, CineonSettings, CineonUnits, Comp, Expression, FeatherFalloff, FieldOrder, Footage, FootageKind, GroupKind, ItemId, ItemKind, Layer, + LayerSource, LightKind, Marker, MaskMode, MaskMotionBlur, Node, PrimitiveKind, Project, PropGroup, Property, Solid, SourceLayer, Switches, TrackMatte, Uid, + essential, styles::GlobalLight, }; use effectcraft_time::{FrameRate, Tick}; @@ -33,6 +36,10 @@ const VERSION: &str = "frames/1"; /// Property groups nest a few levels (effect ▸ group ▸ property); deeper trees are cut here. const MAX_DEPTH: usize = 32; +/// Precomps nest deeper than the renderer draws them (16) only in broken projects; deeper +/// contents are cut here. +const MAX_NESTING: usize = 32; + fn fnv(s: &str) -> u64 { let mut h: u64 = 0xcbf2_9ce4_8422_2325; for b in s.as_bytes() { @@ -54,7 +61,7 @@ pub(crate) enum Era { } /// The signature of `layer`'s frames: its source (and the source item), In/Out, start time, -/// stretch, Time Remap and the comp frame rate. Warp Stabilizer and 3D Camera Tracker keys are +/// stretch, Time Remap and the comp frame rate. Roto Brush Input Keys and [`analysis_key`] are /// made from it. pub(crate) fn signature(p: &Project, comp: ItemId, layer: &Layer) -> String { hex(&signature_text(p, comp, layer)) @@ -87,8 +94,9 @@ pub(crate) fn input_key_of(signature: String, layer: &Layer, uid: Uid) -> String const ANALYSIS_VERSION: &str = "analysis/1"; /// What a Warp Stabilizer or 3D Camera Tracker, the instance `uid` of `layer`, analyses: its -/// input, the layer's frames ([`signature`]) under its masks and the effects above it (#3535). -/// The instance's own settings and the effects below it are not part of it. +/// input, the layer's frames ([`signature`]) under its masks and the effects above it, and a +/// precomp's contents (#3535). The instance's own settings and the effects below it are not part +/// of it. pub(crate) fn analysis_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) -> String { let mut t = Text::new(); t.word(ANALYSIS_VERSION); @@ -98,6 +106,7 @@ pub(crate) fn analysis_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) - t.field("effectsSwitch", layer.switches.effects); } t.inputs_above(layer, uid); + t.precomp(p, comp, layer); hex(&t.0) } @@ -198,7 +207,7 @@ impl Text { match p.item(item).map(|i| &i.kind) { Some(ItemKind::Footage(f)) => self.footage(f), Some(ItemKind::Solid(s)) => self.solid(s), - // A precomp's own contents aren't in the signature yet (#3535). + // Its contents are in an [`analysis_key`], not here: Roto Brush keys are made from this. Some(ItemKind::Comp(c)) => { self.word("comp"); self.field("w", c.width); @@ -394,6 +403,173 @@ impl Text { } } + /// A precomp layer's contents: its Essential Properties (they set values inside it) and what + /// its comp draws, nested precomps included. + fn precomp(&mut self, p: &Project, comp: ItemId, layer: &Layer) { + let LayerSource::Comp { item } = layer.source else { return }; + if let Some(e) = layer.props.group(essential::GROUP) { + self.word("essential"); + self.group(e, 0); + } + // A precomp never draws the comp it is in. + let mut seen = HashSet::from([comp]); + self.comp_contents(p, item, 0, &mut seen); + } + + /// What comp `id` draws. Each comp is written once per key, where it is first reached; a + /// later reference (a comp used twice, or a cycle) writes only its id, so the work is bounded + /// by the size of the project. + fn comp_contents(&mut self, p: &Project, id: ItemId, depth: usize, seen: &mut HashSet) { + self.field("contents", id.0); + // Before `seen`: a comp first reached too deep is written in full where it is shallower. + if depth >= MAX_NESTING { + self.word("tooDeep"); + return; + } + if !seen.insert(id) { + self.word("seen"); + return; + } + let Some(ItemKind::Comp(c)) = p.item(id).map(|i| &i.kind) else { + self.word("none"); + return; + }; + let Comp { + width, + height, + pixel_aspect, + frame_rate, + duration, + display_start, + background, + // The work area, Hide Shy, the viewer's Resolution and guides, and the poster frame + // only show the comp or say what to preview; they never change its frames. + work_area: _, + layers, + markers, + shutter_angle, + shutter_phase, + motion_blur_samples, + motion_blur_adaptive_limit, + renderer, + hide_shy: _, + enable_motion_blur, + enable_frame_blending, + draft_3d, + preserve_frame_rate, + preserve_resolution, + poster_time: _, + global_light, + guides: _, + essential, + resolution: _, + } = &**c; + self.field("w", width); + self.field("h", height); + self.num("par", *pixel_aspect); + self.rate("rate", *frame_rate); + self.tick("duration", *duration); + self.tick("displayStart", *display_start); + self.floats("background", background); + self.timing_markers(markers); + self.nums("shutter", &[*shutter_angle, *shutter_phase]); + self.field("samples", format_args!("{motion_blur_samples}/{motion_blur_adaptive_limit}")); + self.form("renderer", renderer); + self.field("motionBlur", enable_motion_blur); + self.field("frameBlending", enable_frame_blending); + self.field("draft3d", draft_3d); + self.field("preserveRate", preserve_frame_rate); + self.field("preserveResolution", preserve_resolution); + let GlobalLight { angle, altitude } = global_light; + self.property(angle); + self.property(altitude); + self.opt("essentialGraphics", essential.as_ref(), |t, e| t.form("definition", e)); + for l in layers.iter() { + self.nested_layer(p, l, depth, seen); + } + self.word("end"); + } + + /// A layer of a precomp. + fn nested_layer(&mut self, p: &Project, l: &Layer, depth: usize, seen: &mut HashSet) { + let Layer { + id, + // Names, labels and comments only show the layer. (An expression can find a layer + // by its name, as it can an effect, which the key leaves out too.) + name: _, + name_follows_text: _, + source, + label: _, + comment: _, + start_time, + in_point, + out_point, + stretch, + switches, + blend_mode, + preserve_transparency, + track_matte, + parent, + // Layer markers annotate it; Lock Markers protects them. + markers: _, + markers_locked: _, + auto_orient, + environment, + environment_background, + props, + } = l; + self.field("layer", id.0); + self.layer_source(source); + if let Some(item) = source.item() { + match p.item(item).map(|i| &i.kind) { + Some(ItemKind::Footage(f)) => self.footage(f), + Some(ItemKind::Solid(s)) => self.solid(s), + Some(ItemKind::Comp(_)) => self.comp_contents(p, item, depth.saturating_add(1), seen), + Some(ItemKind::Folder) | None => self.word("item=none"), + } + } + self.tick("in", *in_point); + self.tick("out", *out_point); + self.tick("start", *start_time); + self.num("stretch", *stretch); + self.switches(switches); + self.form("blend", blend_mode); + self.field("preserveTransparency", preserve_transparency); + self.opt("matte", track_matte.as_ref(), |t, m| { + let TrackMatte { layer, kind } = m; + t.field("layer", layer.0); + t.form("kind", kind); + }); + self.opt("parent", parent.as_ref(), |t, id| t.field("id", id.0)); + self.form("autoOrient", auto_orient); + self.field("environment", format_args!("{environment}/{environment_background}")); + self.group(props, 0); + } + + fn switches(&mut self, s: &Switches) { + // Lock and Shy only protect and hide the layer in the Timeline. + let Switches { video, audio, solo, locked: _, shy: _, collapse, quality, sampling, effects, frame_blend, motion_blur, adjustment, three_d, guide } = s; + self.field("switches", format_args!("{video}/{audio}/{solo}/{collapse}/{effects}/{motion_blur}/{adjustment}/{three_d}/{guide}")); + self.form("quality", quality); + self.form("sampling", sampling); + self.form("frameBlend", frame_blend); + } + + /// A comp's protected markers with a duration: they set its timing (Responsive Design). + /// Other markers annotate it. + fn timing_markers(&mut self, markers: &[Marker]) { + for m in markers.iter().filter(|m| m.protected && m.duration > Tick::ZERO) { + self.tick("timingMarker", m.time); + self.tick("for", m.duration); + } + } + + /// A value in its project-file form: enums the project file names, and the Essential Graphics + /// definition. + fn form(&mut self, name: &str, v: &T) { + self.str(name, &serde_json::to_string(v).unwrap_or_default()); + } + fn group(&mut self, g: &PropGroup, depth: usize) { // The uid, name and colour label identify and label the group; they never change pixels. let PropGroup { uid: _, match_id, name: _, kind, enabled, label: _, children } = g; diff --git a/crates/engine/src/analysis/warp.rs b/crates/engine/src/analysis/warp.rs index 10b9a0ac1..45af7f172 100644 --- a/crates/engine/src/analysis/warp.rs +++ b/crates/engine/src/analysis/warp.rs @@ -6,10 +6,9 @@ //! analyzer (step 1 of 2, "Analyzing in background"); step 2 ("Stabilizing") derives the //! stabilization plan once to validate and cache the result. When the job finishes, the analysis is //! written into the effect's hidden Analysis parameter as one undo step, together with a key of -//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap, its masks and -//! the effects above the Warp Stabilizer: `analysis::frames_key::analysis_key`, shared with the 3D -//! Camera Tracker). Edits that change -//! those clear the analysis (`invalidate`, run after every edit) and queue the effect for +//! what it was made from (the layer's source, In/Out, start, stretch and Time Remap, its masks, the +//! effects above the Warp Stabilizer and a precomp's contents: `analysis::frames_key::analysis_key`, +//! shared with the 3D Camera Tracker). Edits that change those clear the analysis (`invalidate`, run after every edit) and queue the effect for //! re-analysis, which frontends start with [`Session::poll_warp`] (After Effects re-analyses //! automatically too). Footage going offline is not such a change. diff --git a/crates/engine/src/tests/analysis_inputs.rs b/crates/engine/src/tests/analysis_inputs.rs index 414ff0939..ee75bead2 100644 --- a/crates/engine/src/tests/analysis_inputs.rs +++ b/crates/engine/src/tests/analysis_inputs.rs @@ -126,3 +126,72 @@ fn masks_and_effects_above(saved: Saved) { assert_eq!(analysed(&s), [true, true]); check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "masks/#1/expansion", "value": 3}), [false, false]); } +#[test] +fn a_precomps_contents_are_part_of_the_input() { + for saved in [Saved::Input, Saved::Frames] { + precomp_contents(saved); + } +} + +fn precomp_contents(saved: Saved) { + let mut s = open(ANALYSED); + // Pre-compose the clip, leaving its masks and effects on the precomp layer. + let r = run(&mut s, "layer.precompose", json!({"layers": [CLIP.0], "mode": "leave"})); + let inner = ItemId(r["comp"].as_u64().unwrap()); + let inner_layer = |s: &Session, comp: ItemId| s.project.comp(comp).unwrap().layers[0].id.0; + let clip = inner_layer(&s, inner); + analyse(&mut s, saved); + // Edits inside the precomp change the frames. + check(&mut s, "prop.set", json!({"comp": inner.0, "layer": clip, "path": "transform/opacity", "value": 50}), [false, false]); + check(&mut s, "effect.apply", json!({"comp": inner.0, "layers": [clip], "effect": "ec.blur.gaussian"}), [false, false]); + check(&mut s, "layer.timing", json!({"comp": inner.0, "layers": [clip], "out": 0.25}), [false, false]); + // A name, label or comment inside it doesn't. + run(&mut s, "layer.rename", json!({"comp": inner.0, "layer": clip, "name": "Inner"})); + assert_eq!(analysed(&s), [true, true]); + + // A precomp inside the precomp: its contents too. + let r = run(&mut s, "layer.precompose", json!({"comp": inner.0, "layers": [clip], "mode": "leave"})); + let deeper = ItemId(r["comp"].as_u64().unwrap()); + assert_eq!(analysed(&s), [false, false], "pre-composing inside the precomp changes its contents"); + analyse(&mut s, saved); + let clip = inner_layer(&s, deeper); + check(&mut s, "prop.set", json!({"comp": deeper.0, "layer": clip, "path": "transform/opacity", "value": 50}), [false, false]); + + // Saved and reopened, they still match, and an edit inside still clears them. + let mut s = open(&s.project.to_json()); + run(&mut s, "renderQueue.add", json!({"comp": COMP.0, "format": "png", "output": "frame.png"})); + assert_eq!(analysed(&s), [true, true]); + check(&mut s, "prop.set", json!({"comp": deeper.0, "layer": clip, "path": "transform/opacity", "value": 50}), [false, false]); +} + +/// Precomps used many times, nested deeply or (in a broken project) in a cycle are keyed in +/// bounded time, and an edit deep inside still changes the key. +#[test] +fn shared_deep_and_cyclic_precomps_are_keyed_in_bounded_time() { + use effectcraft_color::Label; + use effectcraft_project::{ItemKind, LayerSource}; + let mut s = open(ANALYSED); + let r = run(&mut s, "layer.precompose", json!({"layers": [CLIP.0], "mode": "leave"})); + let inner = ItemId(r["comp"].as_u64().unwrap()); + let mut p = (*s.project).clone(); + let template = p.comp(inner).unwrap().clone(); + // 40 comps, each drawing the next one twice (2^40 paths if each were walked), the last + // drawing the first. + let ids: Vec = (0..40).map(|i| p.add_item(&format!("Nest {i}"), Label::default(), None, ItemKind::Comp(template.clone().into()))).collect(); + for (i, id) in ids.iter().enumerate() { + let next = ids[(i + 1) % ids.len()]; + let mut layer = template.layers[0].clone(); + layer.source = LayerSource::Comp { item: next }; + let c = p.comp_mut(*id).unwrap(); + c.layers.push(layer.clone()); + layer.id = LayerId(layer.id.0 + 1000); + c.layers.push(layer); + } + p.comp_mut(inner).unwrap().layers[0].source = LayerSource::Comp { item: ids[0] }; + let key = |p: &Project| crate::analysis::frames_key::analysis_key(p, COMP, p.comp(COMP).unwrap().layer(CLIP).unwrap(), WARP); + let start = std::time::Instant::now(); + let before = key(&p); + assert!(start.elapsed() < std::time::Duration::from_secs(2), "{:?}", start.elapsed()); + p.comp_mut(ids[10]).unwrap().background = [1.0, 0.0, 0.0]; + assert_ne!(key(&p), before); +} diff --git a/crates/engine/src/tests/camera_track.rs b/crates/engine/src/tests/camera_track.rs index 3ca8578a9..77829e7f9 100644 --- a/crates/engine/src/tests/camera_track.rs +++ b/crates/engine/src/tests/camera_track.rs @@ -252,6 +252,15 @@ fn invalidation_resolve_cancel_and_undo() { assert_eq!(status(&mut s)["analyzed"], false); assert!(s.redo()); assert_eq!(status(&mut s)["solved"], true); + // A mask is part of the tracked input (#3535): drawing one clears the tracks, undo keeps them. + s.execute_checked("mask.new", json!({"layer": clip.0, "vertices": [[10, 10], [200, 10], [200, 150]]})).unwrap(); + assert_eq!(status(&mut s)["analyzed"], false); + s.execute_checked("edit.undo", json!({})).unwrap(); + assert_eq!(status(&mut s)["solved"], true); + // An effect below the tracker isn't. + s.execute_checked("effect.apply", json!({"layers": [clip.0], "effect": "ec.blur.gaussian"})).unwrap(); + assert_eq!(status(&mut s)["solved"], true); + s.execute_checked("edit.undo", json!({})).unwrap(); // Changing the Solve Method keeps the tracks and only re-solves. s.execute_checked("prop.set", json!({"layer": clip.0, "path": "effects/#1/advanced/solveMethod", "value": 1})).unwrap(); diff --git a/docs/agents.md b/docs/agents.md index 06f9bedae..66025b479 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -492,8 +492,9 @@ between the layer's In and Out points in the background ("Analyzing in backgroun then "Stabilizing..."; `warp.status` reports `progress`, `banner`, whether the effect is `analyzed`, and the current frame's `warp` matrix, `autoScale` and `crop`); `warp.cancel` stops it without writing anything. The analysis is stored in the effect (saved with the project) and is -one undo step; trimming, slipping, time-remapping or replacing the layer's source clears it and -the app re-analyses automatically (headless: run `warp.analyze` again). Settings are ordinary +one undo step; trimming, slipping, time-remapping or replacing the layer's source, editing its +masks, the effects above the Warp Stabilizer or, on a precomp layer, the precomp's contents +clears it and the app re-analyses automatically (headless: run `warp.analyze` again). Settings are ordinary properties under the instance's groups, e.g. `effects/#1/stabilization/result` (0 Smooth Motion, 1 No Motion), `effects/#1/stabilization/smoothness`, `effects/#1/stabilization/method`, `effects/#1/borders/framing` (0 Stabilize Only … 3 Stabilize, Synthesize Edges), @@ -540,7 +541,8 @@ Each edit is one undo step; the first create adds the one-node "3D Tracker Camer startFrame?: 1, includePoints?: true}` exports the solve as an executable Blender scene script: baked camera/lens/focus, synced video background, points and ground. See [Blender camera export](blender-camera-export.md) for framing, assumptions and limitations. -Changing the layer's frames clears the analysis; changing `effects/#1/shotType`, +Changing the layer's frames, masks, the effects above the tracker or a precomp's contents +clears the analysis; changing `effects/#1/shotType`, `effects/#1/horizontalAngleOfView`, `effects/#1/advanced/solveMethod` re-solves the stored tracks. ```sh From 216fc6052d0b238ad0db14a0b0e7a4a48558d757 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 14:52:53 +0530 Subject: [PATCH 44/83] #3470, #3471, #3472, #3473, #3474, #3475, #3476, #3477, #3478, #3479, #3480, #3483, #3484, #3487, #3488, #3489, #3490, #3491: guard effect hard ranges against After Effects' recorded ranges A test walks every effect parameter the .aep table maps to a recorded After Effects definition (fx_defs) and checks that the effect's hard range (ParamUi::Slider min..max, what prop.set and the value editors clamp to) covers After Effects' valid range, converted to EffectCraft's units the way the importer converts values. Conv::number_scale is that conversion, now shared by the importer and the test. The parameters still narrower are allow-listed by issue (#3460-#3492); the test fails on a new narrower parameter and on a row that is no longer needed, so the list shrinks as the issues are fixed. --- crates/aep/src/container/effect_map.rs | 13 +++ crates/aep/src/export/fx_defs.rs | 138 +++++++++++++++++++++++++ crates/aep/src/import/effects.rs | 17 +-- 3 files changed, 154 insertions(+), 14 deletions(-) diff --git a/crates/aep/src/container/effect_map.rs b/crates/aep/src/container/effect_map.rs index 49a53d2e7..29274fc68 100644 --- a/crates/aep/src/container/effect_map.rs +++ b/crates/aep/src/container/effect_map.rs @@ -38,6 +38,19 @@ pub enum Conv { Skip, } +impl Conv { + /// For a number (`Percent`, `Plain`, `Factor`): what a stored value is multiplied by to give + /// the value here. `None` for every other conversion. + pub fn number_scale(self) -> Option { + match self { + Conv::Percent { valid_max } => Some(100.0 / valid_max), + Conv::Plain { .. } => Some(1.0), + Conv::Factor { factor, .. } => Some(factor), + _ => None, + } + } +} + // After Effects' popup items as the corpus stores them (`pdnm`). /// 368. pub const RAMP_SHAPE: &[&str] = &["Linear Ramp", "Radial Ramp"]; diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index e8464bada..346f20462 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -707,3 +707,141 @@ pub(crate) static FX_DEFS: &[FxDef] = &[ p(BUILT_IN, 9, &[], None, None, None, 0x00000000), ]), ]; + +#[cfg(test)] +mod tests { + use super::*; + use crate::container::effect_map::by_match_name; + use effectcraft_project::ParamUi; + + /// Effect parameters whose hard range (`ParamUi::Slider` min..max, which `prop.set` and the + /// value editors clamp to) is still narrower than After Effects' recorded valid range, each + /// with the open issue that tracks it: (effect, parameter, issue). Remove a row when its + /// issue is fixed; the test fails on a row that is no longer needed. + #[rustfmt::skip] + const KNOWN_NARROWER: &[(&str, &str, u32)] = &[ + ("ec.blur.gaussian", "blurriness", 3460), + ("ec.blur.fastbox", "radius", 3461), + ("ec.blur.channel", "redBlurriness", 3462), + ("ec.blur.channel", "greenBlurriness", 3462), + ("ec.blur.channel", "blueBlurriness", 3462), + ("ec.blur.channel", "alphaBlurriness", 3462), + ("ec.obsolete.gaussianlegacy", "blurriness", 3463), + ("ec.perspective.dropshadow", "softness", 3464), + ("ec.blur.compound", "maximumBlur", 3465), + ("ec.blur.sharpen", "amount", 3466), + ("ec.blur.radial", "amount", 3467), + ("ec.blur.ccradial", "amount", 3468), + ("ec.distort.turbulentdisplace", "amount", 3469), + ("ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 3470), + ("ec.distort.transform", "scaleHeight", 3471), + ("ec.distort.transform", "scaleWidth", 3471), + ("ec.transition.venetian", "width", 3472), + ("ec.transition.venetian", "feather", 3473), + ("ec.transition.radialwipe", "feather", 3474), + ("ec.generate.beam", "startThickness", 3475), + ("ec.generate.beam", "endThickness", 3475), + ("ec.generate.grid", "border", 3476), + ("ec.stylize.scatter", "amount", 3477), + ("ec.generate.fourcolor", "blend", 3478), + ("ec.generate.fourcolor", "jitter", 3479), + ("ec.color.changecolor", "hueTransform", 3480), + ("ec.time.pixelmotionblur", "shutterAngle", 3481), + ("ec.time.pixelmotionblur", "shutterSamples", 3482), + ("ec.noise.noisehls", "hue", 3483), + ("ec.noise.noisehls", "lightness", 3483), + ("ec.noise.noisehls", "saturation", 3483), + ("ec.noise.noisehls", "grainSize", 3484), + ("ec.noise.fractal", "subSettings/subInfluence", 3485), + ("ec.noise.fractal", "subSettings/subScaling", 3486), + ("ec.color.levelsic", "rgb/rgbInBlack", 3487), + ("ec.color.levelsic", "red/redInBlack", 3487), + ("ec.color.levelsic", "green/greenInBlack", 3487), + ("ec.color.levelsic", "blue/blueInBlack", 3487), + ("ec.color.levelsic", "alpha/alphaInBlack", 3487), + ("ec.color.levelsic", "rgb/rgbInWhite", 3488), + ("ec.color.levelsic", "red/redInWhite", 3488), + ("ec.color.levelsic", "green/greenInWhite", 3488), + ("ec.color.levelsic", "blue/blueInWhite", 3488), + ("ec.color.levelsic", "alpha/alphaInWhite", 3488), + ("ec.color.levelsic", "rgb/rgbOutBlack", 3489), + ("ec.color.levelsic", "red/redOutBlack", 3489), + ("ec.color.levelsic", "green/greenOutBlack", 3489), + ("ec.color.levelsic", "blue/blueOutBlack", 3489), + ("ec.color.levelsic", "alpha/alphaOutBlack", 3489), + ("ec.color.levelsic", "rgb/rgbOutWhite", 3490), + ("ec.color.levelsic", "red/redOutWhite", 3490), + ("ec.color.levelsic", "green/greenOutWhite", 3490), + ("ec.color.levelsic", "blue/blueOutWhite", 3490), + ("ec.color.levelsic", "alpha/alphaOutWhite", 3490), + ("ec.color.levelsic", "rgb/rgbGamma", 3491), + ("ec.color.levelsic", "red/redGamma", 3491), + ("ec.color.levelsic", "green/greenGamma", 3491), + ("ec.color.levelsic", "blue/blueGamma", 3491), + ("ec.color.levelsic", "alpha/alphaGamma", 3491), + ("ec.distort.ccpowerpin", "expandTop", 3492), + ("ec.distort.ccpowerpin", "expandLeft", 3492), + ("ec.distort.ccpowerpin", "expandRight", 3492), + ("ec.distort.ccpowerpin", "expandBottom", 3492), + ]; + + /// `a` is at most `b`, allowing for the `f32` the recorded bounds were read from. + fn at_most(a: f64, b: f64) -> bool { + a <= b + 1e-6 * a.abs().max(b.abs()).max(1.0) + } + + /// Every effect parameter the .aep table maps to a recorded After Effects definition accepts + /// at least After Effects' valid range, converted to EffectCraft's units the way the importer + /// converts values (`Conv::number_scale`). Only `ParamUi::Slider` limits values (`prop.set`, + /// the Effect Controls and Timeline editors); other controls take any number. A mapping with + /// a declared narrower range (`ParamMap::limit`) must match the effect's range instead. + #[test] + fn effect_hard_ranges_cover_recorded_after_effects_ranges() { + let mut problems = Vec::new(); + let mut narrower = Vec::new(); + for fx in FX_DEFS { + let Some(map) = by_match_name(fx.match_name) else { continue }; + let Some(spec) = effectcraft_effects::find(map.effect) else { + problems.push(format!("{}: no effect {}", fx.match_name, map.effect)); + continue; + }; + for pm in map.params { + let Some(scale) = pm.conv.number_scale() else { continue }; + let at = format!("{} {}", map.effect, pm.target); + let Some(ps) = spec.params.iter().find(|p| p.id == pm.target) else { + problems.push(format!("{at}: not a parameter of the effect")); + continue; + }; + // Other controls take any number. + let ParamUi::Slider { min, max, .. } = &ps.ui else { continue }; + let Some(def) = fx.params.get(pm.index) else { + problems.push(format!("{at}: no recorded definition at parT {}", pm.index)); + continue; + }; + let (Some(lo), Some(hi)) = (def.valid_min, def.valid_max) else { + problems.push(format!("{at}: no recorded valid range")); + continue; + }; + let (lo, hi) = (lo * scale, hi * scale); + if let Some(limit) = pm.limit { + if limit != (*min, *max) { + problems.push(format!("{at}: declared limit {limit:?} is not the effect's range {min}..{max}")); + } + } else if !(at_most(*min, lo) && at_most(hi, *max)) { + narrower.push((map.effect, pm.target, format!("{at}: {min}..{max} excludes After Effects' {lo}..{hi}"))); + } + } + } + for (effect, param, why) in &narrower { + if !KNOWN_NARROWER.iter().any(|(e, p, _)| e == effect && p == param) { + problems.push(why.clone()); + } + } + for (effect, param, issue) in KNOWN_NARROWER { + if !narrower.iter().any(|(e, p, _)| e == effect && p == param) { + problems.push(format!("{effect} {param}: covers After Effects' range now (or is not mapped); remove it from KNOWN_NARROWER (#{issue})")); + } + } + assert!(problems.is_empty(), "{}", problems.join("\n")); + } +} diff --git a/crates/aep/src/import/effects.rs b/crates/aep/src/import/effects.rs index 45ea70840..11d975cd8 100644 --- a/crates/aep/src/import/effects.rs +++ b/crates/aep/src/import/effects.rs @@ -259,23 +259,12 @@ pub(crate) fn import_mapped(p: &EffectParam<'_, '_>, m: &ParamMap, cx: &LayerCtx Conv::Checkbox => Kind::EffectBool, // Handled above. Conv::LayerRef { .. } | Conv::Skip => return, - Conv::Percent { valid_max } => { + Conv::Percent { valid_max } | Conv::Plain { valid_max } | Conv::Factor { valid_max, .. } => { if !checked(valid_max, col) { return; } - Kind::EffectNumber(100.0 / valid_max) - } - Conv::Plain { valid_max } => { - if !checked(valid_max, col) { - return; - } - Kind::EffectNumber(1.0) - } - Conv::Factor { valid_max, factor } => { - if !checked(valid_max, col) { - return; - } - Kind::EffectNumber(factor) + let Some(scale) = m.conv.number_scale() else { return }; + Kind::EffectNumber(scale) } }; // Grouped parameters are addressed by path (`master/exposure`). From 4d24233505250d0dd062fc30101d4cd6fa75ef38 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:07:44 +0530 Subject: [PATCH 45/83] #3538: a custom config not read yet is read for its LUT files --- crates/effects/src/ocio_config/tests.rs | 3 ++- crates/effects/src/utility.rs | 10 ++++++++-- crates/engine/src/tests/lut_files.rs | 15 +++++++-------- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/crates/effects/src/ocio_config/tests.rs b/crates/effects/src/ocio_config/tests.rs index ec34b6723..31cac56c2 100644 --- a/crates/effects/src/ocio_config/tests.rs +++ b/crates/effects/src/ocio_config/tests.rs @@ -465,9 +465,10 @@ fn check_lut_files_notices_a_configs_lut() { let config = dir.join("config.ocio"); std::fs::write(&config, "ocio_profile_version: 2\ncolorspaces:\n - !\n name: lin\n - !\n name: graded\n to_reference: ! {src: watched.cube}\n").unwrap(); let src = config.to_string_lossy().into_owned(); - assert!(load_config(&src).is_ok()); + // A config not read yet is read: its files name its LUT from the first render on. let files = crate::lut_files(&src); assert!(files.contains(&lut.to_string_lossy().into_owned()), "{files:?}"); + assert!(load_config(&src).is_ok()); let before = crate::check_lut_files(); assert!(cached_files(&src).is_some(), "an unchanged config stays"); std::fs::write(&lut, "LUT_1D_SIZE 3\n0 0 0\n0.5 0.5 0.5\n1 1 1\n").unwrap(); diff --git a/crates/effects/src/utility.rs b/crates/effects/src/utility.rs index d735dc286..afb430e1d 100644 --- a/crates/effects/src/utility.rs +++ b/crates/effects/src/utility.rs @@ -359,9 +359,15 @@ pub fn lut_file(src: &str) -> Option<&str> { } /// The files a [`lut_params`] parameter set to `src` reads: the ones its cached result was read -/// from (an OCIO config's also the LUTs it names, and the places it looked for missing ones), else -/// the file it names. +/// from (an OCIO config's also the LUTs it names, and the places it looked for missing ones; an +/// `.ocio` config not read yet is read), else the file it names. pub fn lut_files(src: &str) -> Vec { + // A config not read yet is read now: the LUTs it names are its files from the first render. + if crate::ocio_config::cached_files(src).is_none() + && lut_file(src).is_some_and(|p| std::path::Path::new(p).extension().is_some_and(|e| e.eq_ignore_ascii_case("ocio"))) + { + let _ = crate::ocio_config::load_config(src); + } crate::ocio_config::cached_files(src) .or_else(|| crate::ocio::cached_files(src)) .or_else(|| file_cache::lock(LUTS.get()).files(src)) diff --git a/crates/engine/src/tests/lut_files.rs b/crates/engine/src/tests/lut_files.rs index 0153a9997..98c95652a 100644 --- a/crates/engine/src/tests/lut_files.rs +++ b/crates/engine/src/tests/lut_files.rs @@ -205,20 +205,19 @@ fn ocio_files_render_again_from_warm_caches() { "OCIO Color Space Transform", &[("config", json!(1)), ("configFile", json!(config.to_string_lossy())), ("sourceName", json!("graded")), ("destinationName", json!("lin"))], ); - assert_all(colours(&s, file), 0.0); - assert_all(colours(&s, custom), 0.0); - // (the first key of a config's layer can't know the LUTs it names before it is read) - assert_all(colours(&s, custom), 0.0); - let misses = s.layer_cache.stats().misses; - assert_all(colours(&s, file), 0.0); - assert_all(colours(&s, custom), 0.0); - assert_eq!(s.layer_cache.stats().misses, misses, "unchanged files keep the cached layers"); + // A render notes the LUT the config names (a frame on disk is made of it too). let log = ReadLog::new(); let mut r = s.renderer(RenderOpts::default()); r.reads = Some(&log); let _ = r.comp_frame(custom.1, Tick::ZERO); let files = log.into_files(); assert!(files.get(&grade.to_string_lossy()).is_some(), "the render notes the config's LUT: {files:?}"); + assert_all(colours(&s, file), 0.0); + assert_all(colours(&s, custom), 0.0); + let misses = s.layer_cache.stats().misses; + assert_all(colours(&s, file), 0.0); + assert_all(colours(&s, custom), 0.0); + assert_eq!(s.layer_cache.stats().misses, misses, "unchanged files keep the cached layers"); let generation = effectcraft_effects::lut_generation(); write(&lut, WHITE, 2_000); assert_all(colours(&s, file), 1.0); From 9831d70bfa40cadbb302f39855ce325a9f17925b Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:11:13 +0530 Subject: [PATCH 46/83] #3539: a cache purge gives the viewers' frames new keys Reload Footage Changed on Disk of a file whose metadata didn't change keeps the project's revision; PurgeCaches emptied the viewer frame cache but the new frame came back under the key of the one on screen, so neither the Composition viewer nor the passive viewers uploaded it. Count purges and mix the count into the frame key's options, as #3493 does with the LUT generation. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/frame.rs | 6 +++++- crates/ui-egui/src/app/viewer_frames.rs | 10 +++++++++- crates/ui-egui/src/lib.rs | 2 ++ 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bf5964ba6..518f4e809 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -99,6 +99,7 @@ impl EffectcraftApp { footage_watch_key: None, lut_watcher: None, lut_generation: effectcraft_engine::lut_reload::generation(), + purges: 0, device_lost_close: None, dialog_answers: std::sync::mpsc::channel(), file_dialogs: FileDialogsUp::default(), diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 488b3c5ef..b78c38c73 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -151,7 +151,11 @@ impl EffectcraftApp { self.ui.status = e; } } - effectcraft_engine::Event::PurgeCaches => self.frames.clear(), + effectcraft_engine::Event::PurgeCaches => { + self.frames.clear(); + // (frames made after it get keys of their own: see `Self::purge_stamp`) + self.purges = self.purges.wrapping_add(1); + } effectcraft_engine::Event::CopyImage { width, height, rgba } => { if let Err(e) = copy_image(ctx, width, height, &rgba) { self.ui.status = e; diff --git a/crates/ui-egui/src/app/viewer_frames.rs b/crates/ui-egui/src/app/viewer_frames.rs index a76c88b2d..d9e6e84f2 100644 --- a/crates/ui-egui/src/app/viewer_frames.rs +++ b/crates/ui-egui/src/app/viewer_frames.rs @@ -128,7 +128,7 @@ impl EffectcraftApp { frame: 0, scale: (scale * 1000.0).round() as u32, view: self.view_hash(comp), - opts: frames::opts_hash(&self.frame_opts(comp, scale)) ^ self.roto_model_stamp() ^ self.lut_stamp(), + opts: frames::opts_hash(&self.frame_opts(comp, scale)) ^ self.roto_model_stamp() ^ self.lut_stamp() ^ self.purge_stamp(), } } @@ -149,6 +149,14 @@ impl EffectcraftApp { self.lut_generation.wrapping_mul(0x9e37_79b9_7f4a_7c15) } + /// Changes when the caches are purged (Event::PurgeCaches: footage reloaded, Purge): the + /// frames on screen and the ones still rendering may show the files as they were, and a reload + /// that changes no metadata keeps the project's revision, so the new frames must not share + /// their keys (#3539; the viewers show a frame again only when its key changes). 0 until then. + fn purge_stamp(&self) -> u64 { + self.purges.wrapping_mul(0xc2b2_ae3d_27d4_eb4f) + } + /// The frame series the viewer of `comp` shows now (its scale, view and options, for the /// comp's current content): what the cache bars count. pub fn shown_series(&self, comp: ItemId) -> FrameKey { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 699f68e0f..1558ce743 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -377,6 +377,8 @@ pub struct EffectcraftApp { lut_watcher: Option, /// The LUT generation the frames kept were rendered at ([`effectcraft_engine::lut_reload::generation`]). lut_generation: u64, + /// How many times the caches were purged ([`Self::purge_stamp`]). + purges: u64, /// The graphics device was lost and the window is closing (see `close_after_device_loss`); /// `true` keeps crash recovery for the next launch. device_lost_close: Option, From 39a3b565d81fdda97ade8babfa62f23ee8ac4374 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:11:21 +0530 Subject: [PATCH 47/83] #3487, #3488, #3489, #3490, #3491: Levels (Individual Controls): levels and gamma take After Effects' ranges Input/Output Black and White of every channel take -10000..10000 and Gamma goes down to 0 (it keeps its wider maximum, 10), After Effects' recorded valid ranges in the same units (the .aep mapping is Conv::Plain). Defaults and the 0..1 / 0.1..3 sliders are unchanged. Gamma 0 renders as the existing 0.01 floor, an exponent of 100, so an HDR value a few times Input White would overflow f32 and an infinite curve times an empty output range is NaN. The curve is now bounded at +-1e6 on the CPU (Lv::apply) and the GPU (fxt_lv), so the output stays finite over the whole range; values below the bound are unchanged. The engine regression (tests/effect_ranges.rs) sets both ends of each row through prop.set, checks undo/redo, save and reopen, and that a project saved with the narrower ranges opens with the new ones and its values. --- crates/aep/src/export/fx_defs.rs | 25 ---- crates/effects/src/color2.rs | 22 +++- crates/effects/src/color2/tests.rs | 29 +++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/effect_ranges.rs | 148 +++++++++++++++++++++++ crates/gpu/src/shaders/fx_tone.wgsl | 4 +- crates/gpu/src/tests/fx_tone.rs | 11 ++ 7 files changed, 208 insertions(+), 32 deletions(-) create mode 100644 crates/engine/src/tests/effect_ranges.rs diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 346f20462..92ff7c20c 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -754,31 +754,6 @@ mod tests { ("ec.noise.noisehls", "grainSize", 3484), ("ec.noise.fractal", "subSettings/subInfluence", 3485), ("ec.noise.fractal", "subSettings/subScaling", 3486), - ("ec.color.levelsic", "rgb/rgbInBlack", 3487), - ("ec.color.levelsic", "red/redInBlack", 3487), - ("ec.color.levelsic", "green/greenInBlack", 3487), - ("ec.color.levelsic", "blue/blueInBlack", 3487), - ("ec.color.levelsic", "alpha/alphaInBlack", 3487), - ("ec.color.levelsic", "rgb/rgbInWhite", 3488), - ("ec.color.levelsic", "red/redInWhite", 3488), - ("ec.color.levelsic", "green/greenInWhite", 3488), - ("ec.color.levelsic", "blue/blueInWhite", 3488), - ("ec.color.levelsic", "alpha/alphaInWhite", 3488), - ("ec.color.levelsic", "rgb/rgbOutBlack", 3489), - ("ec.color.levelsic", "red/redOutBlack", 3489), - ("ec.color.levelsic", "green/greenOutBlack", 3489), - ("ec.color.levelsic", "blue/blueOutBlack", 3489), - ("ec.color.levelsic", "alpha/alphaOutBlack", 3489), - ("ec.color.levelsic", "rgb/rgbOutWhite", 3490), - ("ec.color.levelsic", "red/redOutWhite", 3490), - ("ec.color.levelsic", "green/greenOutWhite", 3490), - ("ec.color.levelsic", "blue/blueOutWhite", 3490), - ("ec.color.levelsic", "alpha/alphaOutWhite", 3490), - ("ec.color.levelsic", "rgb/rgbGamma", 3491), - ("ec.color.levelsic", "red/redGamma", 3491), - ("ec.color.levelsic", "green/greenGamma", 3491), - ("ec.color.levelsic", "blue/blueGamma", 3491), - ("ec.color.levelsic", "alpha/alphaGamma", 3491), ("ec.distort.ccpowerpin", "expandTop", 3492), ("ec.distort.ccpowerpin", "expandLeft", 3492), ("ec.distort.ccpowerpin", "expandRight", 3492), diff --git a/crates/effects/src/color2.rs b/crates/effects/src/color2.rs index 6639e649e..ad370ea1d 100644 --- a/crates/effects/src/color2.rs +++ b/crates/effects/src/color2.rs @@ -252,10 +252,17 @@ impl Lv { if clip_w { t = t.min(1.0); } - self.ob + (self.ow - self.ob) * crate::color_fx::levels_gamma(t, self.g.max(0.01)) + let curve = crate::color_fx::levels_gamma(t, self.g.max(0.01)).clamp(-LEVELS_IC_CURVE_LIMIT, LEVELS_IC_CURVE_LIMIT); + self.ob + (self.ow - self.ob) * curve } } +/// How far Levels (Individual Controls)' curve may reach, far beyond any image value: with gamma +/// down to 0 (rendered as 0.01, an exponent of 100) an HDR value a few times Input White would +/// overflow `f32`, and an infinite curve times an empty output range is NaN. Bounded, the output +/// stays finite over the whole valid range (levels ±10000). The GPU (`fxt_lv`) uses the same. +const LEVELS_IC_CURVE_LIMIT: f32 = 1e6; + fn levels_ic(ctx: &EffectCtx, mut b: Buf) -> Buf { let lv = LV_IDS.map(|ids| Lv { ib: ctx.params.f(ids[0]) as f32, @@ -978,11 +985,14 @@ fn cc_kernel(ctx: &EffectCtx, mut b: Buf) -> Buf { pub fn specs() -> Vec { let mut lv_params = Vec::new(); for (ids, names) in LV_IDS.iter().zip(LV_NAMES.iter()) { - lv_params.push(p(ids[0], names[0], num(0.0), slider(-1.0, 2.0, 0.0, 1.0, 3))); - lv_params.push(p(ids[1], names[1], num(1.0), slider(-1.0, 2.0, 0.0, 1.0, 3))); - lv_params.push(p(ids[2], names[2], num(1.0), slider(0.1, 10.0, 0.1, 3.0, 2))); - lv_params.push(p(ids[3], names[3], num(0.0), slider(-1.0, 2.0, 0.0, 1.0, 3))); - lv_params.push(p(ids[4], names[4], num(1.0), slider(-1.0, 2.0, 0.0, 1.0, 3))); + // After Effects' valid ranges (#3487-#3491): levels -10000..10000 and gamma from 0 (the + // renderer floors it at 0.01); gamma keeps its wider maximum. The sliders stay 0..1. + let level = || slider(-10000.0, 10000.0, 0.0, 1.0, 3); + lv_params.push(p(ids[0], names[0], num(0.0), level())); + lv_params.push(p(ids[1], names[1], num(1.0), level())); + lv_params.push(p(ids[2], names[2], num(1.0), slider(0.0, 10.0, 0.1, 3.0, 2))); + lv_params.push(p(ids[3], names[3], num(0.0), level())); + lv_params.push(p(ids[4], names[4], num(1.0), level())); } lv_params.push(p("clipToOutputBlack", "Clip To Output Black", Value::Enum(2), popup(&crate::color_fx::LEVELS_CLIP))); lv_params.push(p("clipToOutputWhite", "Clip To Output White", Value::Enum(2), popup(&crate::color_fx::LEVELS_CLIP))); diff --git a/crates/effects/src/color2/tests.rs b/crates/effects/src/color2/tests.rs index 5f57692a0..069d4c9f7 100644 --- a/crates/effects/src/color2/tests.rs +++ b/crates/effects/src/color2/tests.rs @@ -270,6 +270,35 @@ fn levels_ic_clip_popups() { assert!(run("ec.color.levelsic", &img, &off).data[0][0] > 1.5); } +/// #3487-#3491: over After Effects' valid ranges (levels ±10000, gamma from 0) the output stays +/// finite: gamma 0 renders as 0.01, whose curve on an HDR value overflows `f32` unbounded. +#[test] +fn levels_ic_stays_finite_over_the_whole_range() { + let img = Image::filled(2, 2, [3.0, 0.5, -2.0, 1.0]); + for (ib, iw, ob, ow) in [ + (0.0, 1.0, 0.0, 1.0), + (0.0, 1.0, 1.0, 1.0), + (-10000.0, 10000.0, -10000.0, 10000.0), + (10000.0, -10000.0, 10000.0, -10000.0), + (0.0, 1e-3, -10000.0, 10000.0), + ] { + let lv = [ + ("rgb/rgbInBlack", num(ib)), + ("rgb/rgbInWhite", num(iw)), + ("rgb/rgbGamma", num(0.0)), + ("rgb/rgbOutBlack", num(ob)), + ("rgb/rgbOutWhite", num(ow)), + ("clipToOutputBlack", Value::Enum(0)), + ("clipToOutputWhite", Value::Enum(0)), + ]; + let out = run("ec.color.levelsic", &img, &lv); + assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{ib} {iw} {ob} {ow}: {:?}", out.data[0]); + } + // Gamma 0 is the limit of a small gamma: below Input White the curve goes to 0. + let dark = run("ec.color.levelsic", &Image::filled(1, 1, [0.5, 0.5, 0.5, 1.0]), &[("rgb/rgbGamma", num(0.0))]); + assert!(dark.data[0][0] < 1e-6, "{:?}", dark.data[0]); +} + /// A host whose other layers and other frames are a fixed image. struct ImgHost(Image); impl crate::EffectHost for ImgHost { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ab4b5b8da..054ece456 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -12,6 +12,7 @@ mod crypto_pick; mod delete_keys; mod disk_cache; mod display_pass; +mod effect_ranges; mod effects; mod essential; mod essential_more; diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs new file mode 100644 index 000000000..3581f4411 --- /dev/null +++ b/crates/engine/src/tests/effect_ranges.rs @@ -0,0 +1,148 @@ +//! Effect parameters take the whole valid range After Effects records for them (fx_defs in the +//! aep crate), end to end: `prop.set` keeps both ends, undo and redo restore them, and a saved +//! project reopens with them. The aep crate's +//! `effect_hard_ranges_cover_recorded_after_effects_ranges` checks the ranges themselves +//! against that table. + +use effectcraft_project::{LayerId, Node, ParamUi, PropGroup}; +use serde_json::{Value, json}; + +use crate::Session; + +/// (issue, effect, parameter path, lowest, highest): the ends of After Effects' valid range, +/// in EffectCraft's units, each outside the range the effect accepted before the issue. +#[rustfmt::skip] +const ROWS: &[(u32, &str, &str, f64, f64)] = &[ + (3487, "ec.color.levelsic", "rgb/rgbInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "rgb/rgbInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "rgb/rgbOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "rgb/rgbOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "rgb/rgbGamma", 0.0, 10.0), + (3487, "ec.color.levelsic", "red/redInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "red/redInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "red/redOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "red/redOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "red/redGamma", 0.0, 10.0), + (3487, "ec.color.levelsic", "green/greenInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "green/greenInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "green/greenOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "green/greenOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "green/greenGamma", 0.0, 10.0), + (3487, "ec.color.levelsic", "blue/blueInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "blue/blueInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "blue/blueOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "blue/blueOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "blue/blueGamma", 0.0, 10.0), + (3487, "ec.color.levelsic", "alpha/alphaInBlack", -10000.0, 10000.0), + (3488, "ec.color.levelsic", "alpha/alphaInWhite", -10000.0, 10000.0), + (3489, "ec.color.levelsic", "alpha/alphaOutBlack", -10000.0, 10000.0), + (3490, "ec.color.levelsic", "alpha/alphaOutWhite", -10000.0, 10000.0), + (3491, "ec.color.levelsic", "alpha/alphaGamma", 0.0, 10.0), +]; + +fn path(effect: &str, param: &str) -> String { + format!("effects/{effect}/{param}") +} + +fn read(s: &mut Session, layer: u64, effect: &str, param: &str) -> f64 { + let got = s.execute("prop.get", json!({"layer": layer, "path": path(effect, param)})).unwrap(); + got["value"].as_f64().unwrap_or_else(|| panic!("{effect} {param}: {got}")) +} + +fn set(s: &mut Session, layer: u64, effect: &str, param: &str, v: f64) -> Value { + s.execute("prop.set", json!({"layer": layer, "path": path(effect, param), "value": v})).unwrap() +} + +/// A composition with two solids, each with one instance of every effect in [`ROWS`]. +fn session() -> (Session, u64, u64) { + let mut s = Session::default(); + s.execute("comp.new", json!({"name": "Main", "width": 320, "height": 180, "frameRate": 30, "duration": 2})).unwrap(); + let mut layers = [0; 2]; + for l in &mut layers { + *l = s.execute("layer.newSolid", json!({"color": "#808080", "width": 64, "height": 36})).unwrap()["layer"].as_u64().unwrap(); + let mut effects: Vec<&str> = ROWS.iter().map(|r| r.1).collect(); + effects.dedup(); + for e in effects { + s.execute("effect.apply", json!({"layers": [*l], "effect": e})).unwrap(); + } + } + (s, layers[0], layers[1]) +} + +/// Both ends of every row survive `prop.set`, undo / redo, and a save and reopen. +#[test] +fn effect_parameters_keep_both_ends_of_the_after_effects_range() { + let (mut s, low, high) = session(); + for &(issue, e, p, lo, hi) in ROWS { + assert_eq!(set(&mut s, high, e, p, lo), json!(lo), "#{issue} {e} {p}: prop.set reply"); + assert_eq!(read(&mut s, high, e, p), lo, "#{issue} {e} {p}"); + set(&mut s, high, e, p, hi); + assert_eq!(read(&mut s, high, e, p), hi, "#{issue} {e} {p}"); + assert!(s.undo()); + assert_eq!(read(&mut s, high, e, p), lo, "#{issue} {e} {p}: undo"); + assert!(s.redo()); + assert_eq!(read(&mut s, high, e, p), hi, "#{issue} {e} {p}: redo"); + set(&mut s, low, e, p, lo); + } + let dir = std::env::temp_dir().join(format!("ec-effect-ranges-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("ranges.ecproj").to_string_lossy().to_string(); + s.execute("file.save", json!({"path": file})).unwrap(); + let mut s2 = Session::default(); + s2.execute("file.open", json!({"path": file})).unwrap(); + let _ = std::fs::remove_dir_all(dir); + for &(issue, e, p, lo, hi) in ROWS { + assert_eq!(read(&mut s2, low, e, p), lo, "#{issue} {e} {p}: reopened"); + assert_eq!(read(&mut s2, high, e, p), hi, "#{issue} {e} {p}: reopened"); + } +} + +/// A project saved while these ranges were narrower stored that range with each instance +/// (`ParamUi`) and values clamped to it: opening it takes the effect's current range and keeps +/// the stored values, so the new ends can be set. +#[test] +fn projects_saved_with_the_narrower_ranges_open_with_the_new_ones() { + let (mut s, low, _) = session(); + let cid = s.active_comp_id().unwrap(); + let mut old = (*s.project).clone(); + let stored: Vec = ROWS.iter().map(|&(_, e, p, ..)| read(&mut s, low, e, p)).collect(); + { + let effectcraft_project::ItemKind::Comp(comp) = &mut old.items.get_mut(&cid).unwrap().kind else { panic!("not a composition") }; + let l = std::sync::Arc::make_mut(comp).layers.find_mut(|l| l.id == LayerId(low)).unwrap(); + for (&(_, e, p, ..), v) in ROWS.iter().zip(&stored) { + let g = l.props.sub_mut("effects").unwrap().children.iter_mut().find_map(|n| match n { + Node::Group(g) if g.match_id == e => Some(g), + _ => None, + }); + let pr = prop_mut(g.unwrap(), p).unwrap_or_else(|| panic!("{e} {p}")); + // The narrowest stored range that still holds the stored value. + pr.ui = ParamUi::Slider { min: *v, max: *v, slider_min: *v, slider_max: *v, decimals: 1 }; + } + } + let dir = std::env::temp_dir().join(format!("ec-effect-ranges-old-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("old.ecproj").to_string_lossy().to_string(); + std::fs::write(&file, old.to_json()).unwrap(); + let mut s2 = Session::default(); + s2.execute("file.open", json!({"path": file})).unwrap(); + let _ = std::fs::remove_dir_all(dir); + for (&(issue, e, p, lo, hi), v) in ROWS.iter().zip(&stored) { + assert_eq!(read(&mut s2, low, e, p), *v, "#{issue} {e} {p}: the stored value is kept"); + let spec = effectcraft_effects::find(e).unwrap().params.iter().find(|q| q.id == p).unwrap(); + let uid = s2.execute("prop.get", json!({"layer": low, "path": path(e, p)})).unwrap()["uid"].as_u64().unwrap(); + let layer = s2.project.comp(cid).unwrap().layer(LayerId(low)).unwrap(); + assert_eq!(layer.props.find(uid).unwrap().ui, spec.ui, "#{issue} {e} {p}: the range is refreshed"); + set(&mut s2, low, e, p, lo); + assert_eq!(read(&mut s2, low, e, p), lo, "#{issue} {e} {p}"); + set(&mut s2, low, e, p, hi); + assert_eq!(read(&mut s2, low, e, p), hi, "#{issue} {e} {p}"); + } +} + +/// The property at `path` (`group/param`) in an effect instance. +fn prop_mut<'a>(g: &'a mut PropGroup, path: &str) -> Option<&'a mut effectcraft_project::Property> { + match path.split_once('/') { + None => g.get_mut(path), + Some((first, rest)) => prop_mut(g.sub_mut(first)?, rest), + } +} diff --git a/crates/gpu/src/shaders/fx_tone.wgsl b/crates/gpu/src/shaders/fx_tone.wgsl index bb206adbd..fb7dfe42b 100644 --- a/crates/gpu/src/shaders/fx_tone.wgsl +++ b/crates/gpu/src/shaders/fx_tone.wgsl @@ -40,7 +40,9 @@ fn fxt_lv(i: u32, v: f32, clip_b: bool, clip_w: bool) -> f32 { if (clip_w) { t = min(t, 1.0); } - return data[o + 3u] + (data[o + 4u] - data[o + 3u]) * fxt_gamma(t, max(data[o + 2u], 0.01)); + // color2::LEVELS_IC_CURVE_LIMIT keeps the curve finite. + let curve = clamp(fxt_gamma(t, max(data[o + 2u], 0.01)), -1e6, 1e6); + return data[o + 3u] + (data[o + 4u] - data[o + 3u]) * curve; } // color_fx::level (data offset o: ib, iw, g, ob, ow, clip black, clip white). diff --git a/crates/gpu/src/tests/fx_tone.rs b/crates/gpu/src/tests/fx_tone.rs index 40bc9483f..ca80f3836 100644 --- a/crates/gpu/src/tests/fx_tone.rs +++ b/crates/gpu/src/tests/fx_tone.rs @@ -29,6 +29,17 @@ fn levels_and_gamma() { ); effect_case("ec.color.levelsic", &[("green/greenInBlack", n(0.2)), ("green/greenInWhite", n(0.6)), ("clipToOutputWhite", e(0))]); effect_case("ec.color.levelsic", &[("alpha/alphaOutBlack", n(0.3))]); + // #3487-#3491: the ends of the valid ranges, the curve bounded where gamma 0 would overflow. + effect_case( + "ec.color.levelsic", + &[ + ("rgb/rgbInWhite", n(0.2)), + ("rgb/rgbGamma", n(0.0)), + ("red/redOutBlack", n(-10000.0)), + ("blue/blueOutWhite", n(10000.0)), + ("clipToOutputWhite", e(0)), + ], + ); effect_case("ec.color.levels", &[("redInBlack", n(0.1)), ("greenGamma", n(1.5)), ("blueOutWhite", n(0.7)), ("inWhite", n(0.9))]); effect_case("ec.color.levels", &[("alphaInWhite", n(0.6)), ("redInWhite", n(0.5)), ("redClipToOutputWhite", e(0))]); effect_case("ec.color.gammapedestalgain", &[("redGamma", n(1.4)), ("greenPedestal", n(0.1)), ("blueGain", n(0.8))]); From 363a800d3f65a113aae7d442b47583b39b60cf47 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:14:34 +0530 Subject: [PATCH 48/83] #3478, #3479: 4-Color Gradient: Blend and Jitter take After Effects' ranges Blend goes up to 10000 (it keeps its minimum of 1, below After Effects' 5) and Jitter up to 500 %, After Effects' recorded valid ranges in the same units. Defaults and sliders are unchanged. The CPU and GPU renderers capped Jitter's dither at 100 %, so higher values would be stored but render as 100. Both now take it from one function, four_color_jitter, which keeps the dither linear up to 500 %. Blend 10000 is a finite softening (Blend squared) at the same cost. Jitter was written as "percent" in keyframe text because its range was 0..100; a UNITS row keeps that unit. --- crates/aep/src/export/fx_defs.rs | 2 -- crates/effects/src/generate.rs | 28 +++++++++++++++++-- crates/effects/src/lib.rs | 2 +- .../src/interchange/keyframe_text_effects.rs | 1 + crates/engine/src/tests/effect_ranges.rs | 7 +++-- crates/engine/src/tests/keyframe_text.rs | 18 ++++++++++++ crates/gpu/src/fx_generate.rs | 2 +- crates/gpu/src/tests/fx_generate.rs | 2 ++ 8 files changed, 53 insertions(+), 9 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 92ff7c20c..cc80eaaaa 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -743,8 +743,6 @@ mod tests { ("ec.generate.beam", "endThickness", 3475), ("ec.generate.grid", "border", 3476), ("ec.stylize.scatter", "amount", 3477), - ("ec.generate.fourcolor", "blend", 3478), - ("ec.generate.fourcolor", "jitter", 3479), ("ec.color.changecolor", "hueTransform", 3480), ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), diff --git a/crates/effects/src/generate.rs b/crates/effects/src/generate.rs index ae0d61861..47a6d6314 100644 --- a/crates/effects/src/generate.rs +++ b/crates/effects/src/generate.rs @@ -121,11 +121,17 @@ pub fn four_color_softening(blend: f64, scale: f64) -> f64 { (b * b).max(1e-6) } +/// 4-Color Gradient's Jitter (percent, up to After Effects' 500 %) as the dither's strength: 1 at +/// 100 %, a few code values of noise per unit. +pub fn four_color_jitter(jitter: f64) -> f32 { + (jitter / 100.0).clamp(0.0, 5.0) as f32 +} + fn four_color(ctx: &EffectCtx, mut b: Buf) -> Buf { let pts: Vec<((f64, f64), [f32; 4])> = (1..=4).map(|i| (b.to_px(ctx.params.v2(&format!("positionsColors/point{i}"))), ctx.params.color(&format!("positionsColors/color{i}")))).collect(); let k = four_color_softening(ctx.params.f("blend"), b.scale); - let jitter = (ctx.params.f("jitter") / 100.0).clamp(0.0, 1.0) as f32; + let jitter = four_color_jitter(ctx.params.f("jitter")); let op = ctx.params.f("opacity") as f32 / 100.0; let mode = ctx.params.e("blendingMode"); let seed = ctx.seed; @@ -349,8 +355,9 @@ pub fn specs() -> Vec { p("positionsColors/color3", "Color 3", col(1.0, 0.0, 1.0), ParamUi::Color), p("positionsColors/point4", "Point 4", pt(0.9, 0.9), ParamUi::Point), p("positionsColors/color4", "Color 4", col(0.0, 0.0, 1.0), ParamUi::Color), - p("blend", "Blend", num(100.0), slider(1.0, 1000.0, 1.0, 1000.0, 1)), - p("jitter", "Jitter", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 1)), + // After Effects' valid ranges (#3478, #3479); Blend keeps its lower minimum (1, not 5). + p("blend", "Blend", num(100.0), slider(1.0, 10000.0, 1.0, 1000.0, 1)), + p("jitter", "Jitter", num(0.0), slider(0.0, 500.0, 0.0, 100.0, 1)), p("opacity", "Opacity", num(100.0), slider(0.0, 100.0, 0.0, 100.0, 1)), p("blendingMode", "Blending Mode", Value::Enum(0), popup(&GEN_BLEND_MODES[..18])), ], @@ -465,6 +472,21 @@ mod generator_tests { } } + /// #3479: Jitter goes up to After Effects' 500 %, and more jitter dithers more (the dither + /// stopped growing at 100 %). + #[test] + fn four_color_jitter_grows_up_to_five_hundred_percent() { + let img = Image::filled(32, 32, [0.0, 0.0, 0.0, 1.0]); + let spread = |jitter: f64| { + let o = run_fx("ec.generate.fourcolor", &[("jitter", num(jitter))], img.clone(), 0.0, EffectEnv::default()).img; + let flat = run_fx("ec.generate.fourcolor", &[], img.clone(), 0.0, EffectEnv::default()).img; + o.data.iter().zip(&flat.data).map(|(a, b)| (a[0] - b[0]).abs()).fold(0.0f32, f32::max) + }; + let (at100, at500) = (spread(100.0), spread(500.0)); + assert!(at100 > 0.0 && at500 > 4.0 * at100, "{at100} {at500}"); + assert!(at500 < 0.2, "a few code values: {at500}"); + } + /// After Effects 2026, 4-Color Gradient defaults (yellow, green, magenta, blue at 10 % / 90 % /// of a 1920 × 1080 layer) at Blend 100 and 300, here on a tenth-size layer with Blend 10 /// and 30 (the weights scale with the layer): colours at AE pixels (10x + 5, 10y + 5). diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 9105f4587..e030c6748 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -99,7 +99,7 @@ pub use sim3::{PgBlit, PgPlan, playground_plan, playground_state}; pub use stylize2::strobe_on; // CPU helpers the GPU kernels share (effectcraft-gpu). pub use blur2::{CAMERA_LENS_MAX_RADIUS, camera_lens_plain, camera_lens_radius, camera_lens_spans, radial_fast_pad}; -pub use generate::{four_color_softening, gen_mode}; +pub use generate::{four_color_jitter, four_color_softening, gen_mode}; pub use generate2::pattern_kind as cell_pattern_kind; pub use generate2::{BoltSeg, Contour, Ghost, RadioPlan, Wave, flare_ghosts, lightning_segments, radio_plan}; pub use generate3::{ diff --git a/crates/engine/src/interchange/keyframe_text_effects.rs b/crates/engine/src/interchange/keyframe_text_effects.rs index 83f5b6c20..94d81afcc 100644 --- a/crates/engine/src/interchange/keyframe_text_effects.rs +++ b/crates/engine/src/interchange/keyframe_text_effects.rs @@ -273,6 +273,7 @@ pub(crate) const UNITS: &[(&str, &str, &str)] = &[ ("ec.distort.wavewarp", "width", "percent"), ("ec.distort.wavewarp", "speed", "pixels"), ("ec.generate.fourcolor", "blend", "percent"), + ("ec.generate.fourcolor", "jitter", "percent"), ("ec.generate.advancedlightning", "coreSettings/coreRadius", ""), ("ec.generate.advancedlightning", "glowSettings/glowRadius", "percent"), ("ec.generate.advancedlightning", "alphaObstacle", "pixels"), diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 3581f4411..cb4d4ea24 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -9,8 +9,9 @@ use serde_json::{Value, json}; use crate::Session; -/// (issue, effect, parameter path, lowest, highest): the ends of After Effects' valid range, -/// in EffectCraft's units, each outside the range the effect accepted before the issue. +/// (issue, effect, parameter path, lowest, highest): the ends of the range the effect now accepts, +/// in EffectCraft's units: After Effects' valid range, or wider where EffectCraft already was. +/// At least one end of each is outside the range accepted before the issue. #[rustfmt::skip] const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3487, "ec.color.levelsic", "rgb/rgbInBlack", -10000.0, 10000.0), @@ -38,6 +39,8 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3489, "ec.color.levelsic", "alpha/alphaOutBlack", -10000.0, 10000.0), (3490, "ec.color.levelsic", "alpha/alphaOutWhite", -10000.0, 10000.0), (3491, "ec.color.levelsic", "alpha/alphaGamma", 0.0, 10.0), + (3478, "ec.generate.fourcolor", "blend", 1.0, 10000.0), + (3479, "ec.generate.fourcolor", "jitter", 0.0, 500.0), ]; fn path(effect: &str, param: &str) -> String { diff --git a/crates/engine/src/tests/keyframe_text.rs b/crates/engine/src/tests/keyframe_text.rs index 30d3b436e..81d9487d9 100644 --- a/crates/engine/src/tests/keyframe_text.rs +++ b/crates/engine/src/tests/keyframe_text.rs @@ -480,3 +480,21 @@ fn camera_light_and_material_options_are_written_as_after_effects_does() { assert!(text.contains(block), "{block}in\n{text}"); } } + +/// The unit column of `name`'s block in copied keyframe text. +fn unit_of<'a>(text: &'a str, name: &str) -> &'a str { + let mut lines = text.lines().skip_while(|l| !l.contains(&format!("\t{name} #"))); + lines.next().unwrap_or_else(|| panic!("no {name} in\n{text}")); + lines.next().and_then(|l| l.strip_prefix("\tFrame\t")).and_then(|l| l.strip_suffix('\t')).unwrap_or_else(|| panic!("{name} in\n{text}")) +} + +/// Widening a 0..100 slider to After Effects' range (#3479, #3483, #3484) keeps the unit the +/// keyframe text writes for it. +#[test] +fn widened_effect_ranges_keep_their_keyframe_text_units() { + let (mut s, l) = session(); + s.execute("effect.apply", json!({"layer": l.0, "effect": "ec.generate.fourcolor"})).unwrap(); + let text = copy_props(&mut s, l, &["effects/#1/blend", "effects/#1/jitter"]); + assert_eq!(unit_of(&text, "Blend"), "percent"); + assert_eq!(unit_of(&text, "Jitter"), "percent"); +} diff --git a/crates/gpu/src/fx_generate.rs b/crates/gpu/src/fx_generate.rs index 893208a15..2dda38f45 100644 --- a/crates/gpu/src/fx_generate.rs +++ b/crates/gpu/src/fx_generate.rs @@ -385,7 +385,7 @@ fn four_color(e: &mut Enc, ctx: &EffectCtx, b: GBuf) -> Option { p.f[4 + i] = ctx.params.color(&format!("positionsColors/color{}", i + 1)); } let k = effectcraft_effects::four_color_softening(ctx.params.f("blend"), b.scale); - let jitter = (ctx.params.f("jitter") / 100.0).clamp(0.0, 1.0) as f32; + let jitter = effectcraft_effects::four_color_jitter(ctx.params.f("jitter")); p.u[0] = [gen_mode(ctx.params.e("blendingMode")), ctx.seed, 0, 0]; p.f[8] = [k as f32, jitter, ctx.params.f("opacity") as f32 / 100.0, 0.0]; run(e, "gen_fourcolor", &p, b, None, None) diff --git a/crates/gpu/src/tests/fx_generate.rs b/crates/gpu/src/tests/fx_generate.rs index d12920797..d7e05e047 100644 --- a/crates/gpu/src/tests/fx_generate.rs +++ b/crates/gpu/src/tests/fx_generate.rs @@ -167,6 +167,8 @@ fn generators() { effect_case("ec.generate.fourcolor", &[]); effect_case("ec.generate.fourcolor", &[("blend", n(40.0)), ("jitter", n(50.0)), ("opacity", n(80.0)), ("blendingMode", e(3))]); effect_case("ec.generate.fourcolor", &[("blend", n(600.0)), ("blendingMode", e(16)), ("positionsColors/point2", pt(30.0, 20.0))]); + // #3478, #3479: the top of After Effects' ranges. + effect_case("ec.generate.fourcolor", &[("blend", n(10000.0)), ("jitter", n(500.0))]); } #[test] From 36eecad00f7a52b2ba9500651c26967ccb361acd Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:30:14 +0530 Subject: [PATCH 49/83] #3538: a cached config's size counts the LUTs it holds --- crates/effects/src/file_cache.rs | 43 ++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/crates/effects/src/file_cache.rs b/crates/effects/src/file_cache.rs index 2bcbefede..88fb75bbd 100644 --- a/crates/effects/src/file_cache.rs +++ b/crates/effects/src/file_cache.rs @@ -147,15 +147,16 @@ fn registry() -> MutexGuard<'static, Vec<&'static dyn ForgetFile>> { } thread_local! { - /// The files read by the loads running on this thread, innermost last. - static READING: RefCell> = const { RefCell::new(Vec::new()) }; + /// The loads running on this thread, innermost last: the files each read, and the bytes of + /// the cached results it holds (a config holds the LUTs its `FileTransform`s loaded). + static READING: RefCell> = const { RefCell::new(Vec::new()) }; } /// Note that the running load read (or looked for) `path`, stamped `stamp`. pub(crate) fn note_file(path: &str, stamp: FileStamp) { READING.with(|r| { if let Ok(mut r) = r.try_borrow_mut() - && let Some(top) = r.last_mut() + && let Some((top, _)) = r.last_mut() && !top.iter().any(|(p, _)| p == path) { top.push((path.to_string(), stamp)); @@ -163,6 +164,17 @@ pub(crate) fn note_file(path: &str, stamp: FileStamp) { }); } +/// Note that the running load holds a cached result of `bytes`. +fn note_bytes(bytes: usize) { + READING.with(|r| { + if let Ok(mut r) = r.try_borrow_mut() + && let Some((_, held)) = r.last_mut() + { + *held = held.saturating_add(bytes); + } + }); +} + /// Pops the files of a load when it ends, even by a panic. struct Reading { popped: bool, @@ -172,17 +184,18 @@ impl Reading { fn start() -> Reading { READING.with(|r| { if let Ok(mut r) = r.try_borrow_mut() { - r.push(Vec::new()); + r.push((Vec::new(), 0)); } }); Reading { popped: false } } - fn pop() -> Option { + fn pop() -> Option<(Files, usize)> { READING.with(|r| r.try_borrow_mut().ok().and_then(|mut r| r.pop())) } - fn files(mut self) -> Files { + /// The files the load read, and the bytes of the cached results it holds. + fn finish(mut self) -> (Files, usize) { self.popped = true; Self::pop().unwrap_or_default() } @@ -230,23 +243,27 @@ pub(crate) fn cached(cache: &Mutex>, src: &str, load: i && e.files == files { e.used = now; - let value = e.value.clone(); + let (value, bytes) = (e.value.clone(), e.bytes); drop(c); - // (an enclosing load depends on these files too) + // (an enclosing load depends on these files too, and holds this result) for (p, s) in &files { note_file(p, *s); } + note_bytes(bytes); return value; } } let reading = Reading::start(); let (value, size) = load(); - let files = reading.files(); + let (files, held) = reading.finish(); follow(&files, stale); for (p, s) in &files { note_file(p, *s); } - let bytes = size.saturating_add(src.len()); + // (what it holds counts against this cache's bound too: another cache letting go of it + // frees nothing while this result keeps it) + let bytes = size.saturating_add(held).saturating_add(src.len()); + note_bytes(bytes); let mut c = lock(cache); c.clock += 1; let used = c.clock; @@ -400,16 +417,20 @@ mod tests { note_missing("/nested/outer-own.cube"); let inner = cached(INNER.get(), "inner", || { note_missing("/nested/inner.cube"); - (7, 0) + (7, 100) }); (inner, 0) }); assert_eq!(v, 7); let files = lock(OUTER.get()).files("outer").unwrap(); + let held = |src: &str| lock(OUTER.get()).map.get(src).map(|e| e.bytes); + // ("inner" is 5 bytes, its result 100: "outer" holds it, on a load and on a hit alike) + assert_eq!(held("outer"), Some(100 + 5 + "outer".len()), "the result an enclosing load holds counts"); assert_eq!(files, vec!["/nested/outer-own.cube".to_string(), "/nested/inner.cube".to_string()]); // A hit on the inner result still reports its files to a new enclosing load. let w = cached(OUTER.get(), "outer 2", || (cached(INNER.get(), "inner", || (0, 0)), 0)); assert_eq!(w, 7); assert_eq!(lock(OUTER.get()).files("outer 2").unwrap(), vec!["/nested/inner.cube".to_string()]); + assert_eq!(held("outer 2"), Some(100 + 5 + "outer 2".len())); } } From 244f9bd846d1b94f47a392e4f46618b6db3f85c1 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:46:48 +0530 Subject: [PATCH 50/83] #3483, #3484: Noise HLS: amounts and Grain Size take After Effects' ranges Hue, Lightness and Saturation go up to 1000 % and Grain Size down to 0 (it keeps its wider maximum, 100), After Effects' recorded valid ranges in the same units. Noise HLS Auto shares the controls and widens with them. Defaults and sliders are unchanged. The renderers need no change: hue wraps, lightness and saturation clamp per pixel after the noise is added, and Grain Size is floored at 0.1 px on the CPU and the GPU, so the new values cost the same and stay finite. The amounts were written as "percent" in keyframe text because their range was 0..100, and Grain Size would become "percent" at 0..100; UNITS rows keep the units they had. --- crates/aep/src/export/fx_defs.rs | 4 --- crates/effects/src/noise.rs | 32 ++++++++++++++++--- .../src/interchange/keyframe_text_effects.rs | 9 ++++++ crates/engine/src/tests/effect_ranges.rs | 8 +++++ crates/engine/src/tests/keyframe_text.rs | 8 +++++ crates/gpu/src/tests/fx_noise.rs | 2 ++ 6 files changed, 55 insertions(+), 8 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index cc80eaaaa..90db58758 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -746,10 +746,6 @@ mod tests { ("ec.color.changecolor", "hueTransform", 3480), ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), - ("ec.noise.noisehls", "hue", 3483), - ("ec.noise.noisehls", "lightness", 3483), - ("ec.noise.noisehls", "saturation", 3483), - ("ec.noise.noisehls", "grainSize", 3484), ("ec.noise.fractal", "subSettings/subInfluence", 3485), ("ec.noise.fractal", "subSettings/subScaling", 3486), ("ec.distort.ccpowerpin", "expandTop", 3492), diff --git a/crates/effects/src/noise.rs b/crates/effects/src/noise.rs index 09217f831..246910cd5 100644 --- a/crates/effects/src/noise.rs +++ b/crates/effects/src/noise.rs @@ -766,10 +766,12 @@ pub fn specs() -> Vec { let hls_common = || { vec![ p("noise", "Noise", Value::Enum(0), popup(&["Uniform", "Squared", "Grain"])), - p("hue", "Hue", num(0.0), pct()), - p("lightness", "Lightness", num(0.0), pct()), - p("saturation", "Saturation", num(0.0), pct()), - p("grainSize", "Grain Size", num(1.0), slider(0.1, 100.0, 0.5, 10.0, 2)), + // After Effects' valid ranges (#3483, #3484): the amounts go to 1000 %, Grain Size + // down to 0 (the renderer floors it at 0.1 px) and keeps its wider maximum. + p("hue", "Hue", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), + p("lightness", "Lightness", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), + p("saturation", "Saturation", num(0.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), + p("grainSize", "Grain Size", num(1.0), slider(0.0, 100.0, 0.5, 10.0, 2)), ] }; let mut hls = hls_common(); @@ -967,6 +969,28 @@ mod tests { assert_eq!(still.img, img); } + /// #3483, #3484: amounts above 100 % keep adding noise, and Grain Size 0 renders (floored at + /// 0.1 px) with finite output, for both effects. + #[test] + fn noise_hls_takes_after_effects_ranges() { + let mut img = Image::new(16, 16); + for (i, p) in img.data.iter_mut().enumerate() { + *p = premul([0.6, 0.3, (i % 7) as f32 / 7.0], 1.0); + } + for id in ["ec.noise.noisehls", "ec.noise.noisehlsauto"] { + let at = |amount: f64, grain: f64| { + let vals = + [("noise", Value::Enum(2)), ("hue", num(amount)), ("lightness", num(amount)), ("saturation", num(amount)), ("grainSize", num(grain))]; + run(id, &vals, img.clone(), 0.0).img + }; + let (low, high) = (at(100.0, 1.0), at(1000.0, 1.0)); + assert_ne!(low, high, "{id}"); + for out in [high, at(1000.0, 0.0)] { + assert!(out.data.iter().flatten().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{id}"); + } + } + } + #[test] fn add_grain_keeps_flat_mean() { let out = run("ec.noise.addgrain", &[("tweaking/intensity", num(2.0)), ("application/blendingMode", Value::Enum(2))], gray(64, 64, 0.5), 0.0); diff --git a/crates/engine/src/interchange/keyframe_text_effects.rs b/crates/engine/src/interchange/keyframe_text_effects.rs index 94d81afcc..7b0658f61 100644 --- a/crates/engine/src/interchange/keyframe_text_effects.rs +++ b/crates/engine/src/interchange/keyframe_text_effects.rs @@ -318,6 +318,15 @@ pub(crate) const UNITS: &[(&str, &str, &str)] = &[ ("ec.matte.rotobrush", "refineEdgeMatte/shiftEdge", "percent"), ("ec.matte.rotobrush", "refineEdgeMatte/decontamination/increaseDecontaminationRadius", ""), ("ec.matte.simplechoker", "chokeMatte", "pixels"), + // Their ranges were 0..100 (#3483, #3484). + ("ec.noise.noisehls", "hue", "percent"), + ("ec.noise.noisehls", "lightness", "percent"), + ("ec.noise.noisehls", "saturation", "percent"), + ("ec.noise.noisehls", "grainSize", ""), + ("ec.noise.noisehlsauto", "hue", "percent"), + ("ec.noise.noisehlsauto", "lightness", "percent"), + ("ec.noise.noisehlsauto", "saturation", "percent"), + ("ec.noise.noisehlsauto", "grainSize", ""), ("ec.noise.fractal", "transform/scale", "percent"), ("ec.noise.fractal", "transform/scaleWidth", "percent"), ("ec.noise.fractal", "transform/scaleHeight", "percent"), diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index cb4d4ea24..9c0c336ec 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -41,6 +41,14 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3491, "ec.color.levelsic", "alpha/alphaGamma", 0.0, 10.0), (3478, "ec.generate.fourcolor", "blend", 1.0, 10000.0), (3479, "ec.generate.fourcolor", "jitter", 0.0, 500.0), + (3483, "ec.noise.noisehls", "hue", 0.0, 1000.0), + (3483, "ec.noise.noisehls", "lightness", 0.0, 1000.0), + (3483, "ec.noise.noisehls", "saturation", 0.0, 1000.0), + (3484, "ec.noise.noisehls", "grainSize", 0.0, 100.0), + (3483, "ec.noise.noisehlsauto", "hue", 0.0, 1000.0), + (3483, "ec.noise.noisehlsauto", "lightness", 0.0, 1000.0), + (3483, "ec.noise.noisehlsauto", "saturation", 0.0, 1000.0), + (3484, "ec.noise.noisehlsauto", "grainSize", 0.0, 100.0), ]; fn path(effect: &str, param: &str) -> String { diff --git a/crates/engine/src/tests/keyframe_text.rs b/crates/engine/src/tests/keyframe_text.rs index 81d9487d9..a299899eb 100644 --- a/crates/engine/src/tests/keyframe_text.rs +++ b/crates/engine/src/tests/keyframe_text.rs @@ -497,4 +497,12 @@ fn widened_effect_ranges_keep_their_keyframe_text_units() { let text = copy_props(&mut s, l, &["effects/#1/blend", "effects/#1/jitter"]); assert_eq!(unit_of(&text, "Blend"), "percent"); assert_eq!(unit_of(&text, "Jitter"), "percent"); + for fx in ["ec.noise.noisehls", "ec.noise.noisehlsauto"] { + let (mut s, l) = session(); + s.execute("effect.apply", json!({"layer": l.0, "effect": fx})).unwrap(); + let text = copy_props(&mut s, l, &["effects/#1/hue", "effects/#1/lightness", "effects/#1/saturation", "effects/#1/grainSize"]); + for (name, unit) in [("Hue", "percent"), ("Lightness", "percent"), ("Saturation", "percent"), ("Grain Size", "")] { + assert_eq!(unit_of(&text, name), unit, "{fx} {name}"); + } + } } diff --git a/crates/gpu/src/tests/fx_noise.rs b/crates/gpu/src/tests/fx_noise.rs index 7d13004ee..006128c73 100644 --- a/crates/gpu/src/tests/fx_noise.rs +++ b/crates/gpu/src/tests/fx_noise.rs @@ -164,6 +164,8 @@ fn noise_alpha_and_hls() { effect_case("ec.noise.noisehls", &[("hue", n(30.0)), ("lightness", n(20.0)), ("saturation", n(40.0))]); effect_case("ec.noise.noisehls", &[("noise", e(1)), ("lightness", n(50.0)), ("noisePhase", n(200.0))]); effect_case("ec.noise.noisehls", &[("noise", e(2)), ("hue", n(60.0)), ("saturation", n(25.0)), ("grainSize", n(3.0))]); + // #3483, #3484: the ends of After Effects' ranges. + effect_case("ec.noise.noisehls", &[("noise", e(2)), ("hue", n(1000.0)), ("lightness", n(1000.0)), ("saturation", n(1000.0)), ("grainSize", n(0.0))]); effect_case("ec.noise.noisehlsauto", &[("noise", e(0)), ("hue", n(20.0)), ("lightness", n(30.0)), ("noiseAnimationSpeed", n(7.0))]); } From ce4db788960c51317ea5b26e0a8ca06d66c0f5f3 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:47:14 +0530 Subject: [PATCH 51/83] #3480: Change Color: Hue Transform takes After Effects' range Hue Transform takes -1800..1800 degrees, After Effects' recorded valid range in the same units. The CPU and GPU renderers wrap the hue (rem_euclid / fract_euclid), so five turns render like the hue they end on, at the same cost. Default and slider are unchanged. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/color3.rs | 2 +- crates/engine/src/tests/effect_ranges.rs | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 90db58758..865d1fef2 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -743,7 +743,6 @@ mod tests { ("ec.generate.beam", "endThickness", 3475), ("ec.generate.grid", "border", 3476), ("ec.stylize.scatter", "amount", 3477), - ("ec.color.changecolor", "hueTransform", 3480), ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), ("ec.noise.fractal", "subSettings/subInfluence", 3485), diff --git a/crates/effects/src/color3.rs b/crates/effects/src/color3.rs index d0d398100..6548fdbdb 100644 --- a/crates/effects/src/color3.rs +++ b/crates/effects/src/color3.rs @@ -809,7 +809,7 @@ pub fn specs() -> Vec { "Change Color", vec![ p("view", "View", Value::Enum(0), popup(&["Corrected Layer", "Color Correction Mask"])), - p("hueTransform", "Hue Transform", num(0.0), slider(-360.0, 360.0, -180.0, 180.0, 1)), + p("hueTransform", "Hue Transform", num(0.0), slider(-1800.0, 1800.0, -180.0, 180.0, 1)), p("lightnessTransform", "Lightness Transform", num(0.0), bipolar()), p("saturationTransform", "Saturation Transform", num(0.0), bipolar()), p("colorToChange", "Color To Change", col(0.8, 0.2, 0.2), ParamUi::Color), diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 9c0c336ec..08a57fa3b 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -49,6 +49,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3483, "ec.noise.noisehlsauto", "lightness", 0.0, 1000.0), (3483, "ec.noise.noisehlsauto", "saturation", 0.0, 1000.0), (3484, "ec.noise.noisehlsauto", "grainSize", 0.0, 100.0), + (3480, "ec.color.changecolor", "hueTransform", -1800.0, 1800.0), ]; fn path(effect: &str, param: &str) -> String { From 85f47ec072ce70bc5958d42929f313587d394e2c Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:47:14 +0530 Subject: [PATCH 52/83] #3476: Grid: Border takes After Effects' range Border takes 0..2000, After Effects' recorded valid range in the same units (pixels). The CPU and GPU renderers compute the border per pixel in closed form, so a wider border costs the same; one wider than the cells covers them. Default and slider are unchanged. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/generate.rs | 2 +- crates/engine/src/tests/effect_ranges.rs | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 865d1fef2..d65448651 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -741,7 +741,6 @@ mod tests { ("ec.transition.radialwipe", "feather", 3474), ("ec.generate.beam", "startThickness", 3475), ("ec.generate.beam", "endThickness", 3475), - ("ec.generate.grid", "border", 3476), ("ec.stylize.scatter", "amount", 3477), ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), diff --git a/crates/effects/src/generate.rs b/crates/effects/src/generate.rs index 47a6d6314..d8d47a7c7 100644 --- a/crates/effects/src/generate.rs +++ b/crates/effects/src/generate.rs @@ -391,7 +391,7 @@ pub fn specs() -> Vec { p("corner", "Corner", pt(0.1, 0.1), ParamUi::Point), p("width", "Width", num(64.0), slider(1.0, 4000.0, 1.0, 400.0, 1)), p("height", "Height", num(64.0), slider(1.0, 4000.0, 1.0, 400.0, 1)), - p("border", "Border", num(2.0), slider(0.0, 400.0, 0.0, 40.0, 1)), + p("border", "Border", num(2.0), slider(0.0, 2000.0, 0.0, 40.0, 1)), p("feather/featherWidth", "Width", num(0.0), slider(0.0, 1000.0, 0.0, 50.0, 1)), p("feather/featherHeight", "Height", num(0.0), slider(0.0, 1000.0, 0.0, 50.0, 1)), p("invertGrid", "Invert Grid", Value::Bool(false), ParamUi::Checkbox), diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 08a57fa3b..76d7610d3 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -50,6 +50,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3483, "ec.noise.noisehlsauto", "saturation", 0.0, 1000.0), (3484, "ec.noise.noisehlsauto", "grainSize", 0.0, 100.0), (3480, "ec.color.changecolor", "hueTransform", -1800.0, 1800.0), + (3476, "ec.generate.grid", "border", 0.0, 2000.0), ]; fn path(effect: &str, param: &str) -> String { From 29c76bb6b4104a9275d22ec9bd14d5e081317f5d Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:47:14 +0530 Subject: [PATCH 53/83] #3472, #3473: Venetian Blinds: Width and Feather take After Effects' ranges Width takes 1..32000 and Feather 0..32000, After Effects' recorded valid ranges in the same units (pixels). The work stays bounded: the renderers floor the width at 1 buffer pixel, sum at most 40 Gaussian terms per pixel, and above 8 widths the feather is the even veil (venetian_cover; the GPU hands that case to the CPU, as before). Default and slider are unchanged. --- crates/aep/src/export/fx_defs.rs | 2 -- crates/effects/src/misc.rs | 4 ++-- crates/engine/src/tests/effect_ranges.rs | 2 ++ 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index d65448651..7f1bd8c21 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -736,8 +736,6 @@ mod tests { ("ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 3470), ("ec.distort.transform", "scaleHeight", 3471), ("ec.distort.transform", "scaleWidth", 3471), - ("ec.transition.venetian", "width", 3472), - ("ec.transition.venetian", "feather", 3473), ("ec.transition.radialwipe", "feather", 3474), ("ec.generate.beam", "startThickness", 3475), ("ec.generate.beam", "endThickness", 3475), diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index 65951ad97..a1037c693 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -930,8 +930,8 @@ pub fn specs() -> Vec { vec![ p("completion", "Transition Completion", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 0)), p("direction", "Direction", num(90.0), ParamUi::Angle), - p("width", "Width", num(30.0), slider(2.0, 1000.0, 2.0, 200.0, 0)), - p("feather", "Feather", num(0.0), slider(0.0, 100.0, 0.0, 100.0, 1)), + p("width", "Width", num(30.0), slider(1.0, 32000.0, 2.0, 200.0, 0)), + p("feather", "Feather", num(0.0), slider(0.0, 32000.0, 0.0, 100.0, 1)), ], venetian, ), diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 76d7610d3..73cb0e5db 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -51,6 +51,8 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3484, "ec.noise.noisehlsauto", "grainSize", 0.0, 100.0), (3480, "ec.color.changecolor", "hueTransform", -1800.0, 1800.0), (3476, "ec.generate.grid", "border", 0.0, 2000.0), + (3472, "ec.transition.venetian", "width", 1.0, 32000.0), + (3473, "ec.transition.venetian", "feather", 0.0, 32000.0), ]; fn path(effect: &str, param: &str) -> String { From a08240155ccec5977a384af0c6dd735d97783860 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:47:14 +0530 Subject: [PATCH 54/83] #3474: Radial Wipe: Feather takes After Effects' range Feather takes 0..32000, After Effects' recorded valid range in the same units. The CPU and GPU renderers evaluate the feather per pixel in closed form (a Gaussian of the distance to the wedge, radial_wipe_alpha), so a wide feather costs the same and stays finite. Default and slider are unchanged. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/misc.rs | 2 +- crates/engine/src/tests/effect_ranges.rs | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 7f1bd8c21..a741397ff 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -736,7 +736,6 @@ mod tests { ("ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 3470), ("ec.distort.transform", "scaleHeight", 3471), ("ec.distort.transform", "scaleWidth", 3471), - ("ec.transition.radialwipe", "feather", 3474), ("ec.generate.beam", "startThickness", 3475), ("ec.generate.beam", "endThickness", 3475), ("ec.stylize.scatter", "amount", 3477), diff --git a/crates/effects/src/misc.rs b/crates/effects/src/misc.rs index a1037c693..9c7131657 100644 --- a/crates/effects/src/misc.rs +++ b/crates/effects/src/misc.rs @@ -919,7 +919,7 @@ pub fn specs() -> Vec { p("startAngle", "Start Angle", num(0.0), ParamUi::Angle), p("center", "Wipe Center", Value::Vec2([0.5, 0.5]), ParamUi::Point), p("wipe", "Wipe", Value::Enum(0), popup(&["Clockwise", "Counterclockwise", "Both"])), - p("feather", "Feather", num(0.0), slider(0.0, 360.0, 0.0, 50.0, 1)), + p("feather", "Feather", num(0.0), slider(0.0, 32000.0, 0.0, 50.0, 1)), ], radial_wipe, ), diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 73cb0e5db..3ba91dc5f 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -53,6 +53,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3476, "ec.generate.grid", "border", 0.0, 2000.0), (3472, "ec.transition.venetian", "width", 1.0, 32000.0), (3473, "ec.transition.venetian", "feather", 0.0, 32000.0), + (3474, "ec.transition.radialwipe", "feather", 0.0, 32000.0), ]; fn path(effect: &str, param: &str) -> String { From c4cd9f1c2eff1e19d0848c6114da2f97450de93a Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:47:15 +0530 Subject: [PATCH 55/83] #3477: Scatter: Scatter Amount takes After Effects' range Scatter Amount takes 0..1000, After Effects' recorded valid range in the same units (pixels); the slider stays 0..127. The CPU and GPU renderers move each pixel by one random offset of up to the amount, so a larger amount costs the same; samples outside the layer are transparent. Default and slider are unchanged. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/stylize2.rs | 2 +- crates/engine/src/tests/effect_ranges.rs | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index a741397ff..3c7464009 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -738,7 +738,6 @@ mod tests { ("ec.distort.transform", "scaleWidth", 3471), ("ec.generate.beam", "startThickness", 3475), ("ec.generate.beam", "endThickness", 3475), - ("ec.stylize.scatter", "amount", 3477), ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), ("ec.noise.fractal", "subSettings/subInfluence", 3485), diff --git a/crates/effects/src/stylize2.rs b/crates/effects/src/stylize2.rs index 247854352..a2de2c35e 100644 --- a/crates/effects/src/stylize2.rs +++ b/crates/effects/src/stylize2.rs @@ -612,7 +612,7 @@ pub fn specs() -> Vec { "ec.stylize.scatter", "Scatter", vec![ - p("amount", "Scatter Amount", num(0.0), slider(0.0, 127.0, 0.0, 127.0, 1)), + p("amount", "Scatter Amount", num(0.0), slider(0.0, 1000.0, 0.0, 127.0, 1)), p("grain", "Grain", Value::Enum(0), popup(&["Both", "Horizontal", "Vertical"])), p("randomizeEveryFrame", "Scatter Randomness", Value::Bool(false), ParamUi::Checkbox), ], diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 3ba91dc5f..c783478fb 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -54,6 +54,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3472, "ec.transition.venetian", "width", 1.0, 32000.0), (3473, "ec.transition.venetian", "feather", 0.0, 32000.0), (3474, "ec.transition.radialwipe", "feather", 0.0, 32000.0), + (3477, "ec.stylize.scatter", "amount", 0.0, 1000.0), ]; fn path(effect: &str, param: &str) -> String { From 3bd7de6ad8b7ff4903f03d3810ad32a0d2ba9a72 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:47:15 +0530 Subject: [PATCH 56/83] #3475: Beam: Starting and Ending Thickness take After Effects' range Starting and Ending Thickness take 0..4000, After Effects' recorded valid range in the same units (pixels). The CPU and GPU renderers draw the beam per pixel from its distance to the segment, within the layer's buffer, so a thicker beam costs the same. Default and slider are unchanged. --- crates/aep/src/export/fx_defs.rs | 2 -- crates/effects/src/generate2.rs | 4 ++-- crates/engine/src/tests/effect_ranges.rs | 2 ++ 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 3c7464009..e35f7c6fc 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -736,8 +736,6 @@ mod tests { ("ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 3470), ("ec.distort.transform", "scaleHeight", 3471), ("ec.distort.transform", "scaleWidth", 3471), - ("ec.generate.beam", "startThickness", 3475), - ("ec.generate.beam", "endThickness", 3475), ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), ("ec.noise.fractal", "subSettings/subInfluence", 3485), diff --git a/crates/effects/src/generate2.rs b/crates/effects/src/generate2.rs index ad80cb9cd..6bf5443fc 100644 --- a/crates/effects/src/generate2.rs +++ b/crates/effects/src/generate2.rs @@ -1111,8 +1111,8 @@ pub fn specs() -> Vec { p("endPoint", "Ending Point", pt(0.75, 0.5), ParamUi::Point), p("length", "Length", num(25.0), pct()), p("time", "Time", num(0.0), pct()), - p("startThickness", "Starting Thickness", num(8.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), - p("endThickness", "Ending Thickness", num(8.0), slider(0.0, 1000.0, 0.0, 100.0, 1)), + p("startThickness", "Starting Thickness", num(8.0), slider(0.0, 4000.0, 0.0, 100.0, 1)), + p("endThickness", "Ending Thickness", num(8.0), slider(0.0, 4000.0, 0.0, 100.0, 1)), p("softness", "Softness", num(20.0), pct()), p("insideColor", "Inside Color", col(1.0, 1.0, 1.0), ParamUi::Color), p("outsideColor", "Outside Color", col(0.4, 0.4, 1.0), ParamUi::Color), diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index c783478fb..320e1378f 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -55,6 +55,8 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3473, "ec.transition.venetian", "feather", 0.0, 32000.0), (3474, "ec.transition.radialwipe", "feather", 0.0, 32000.0), (3477, "ec.stylize.scatter", "amount", 0.0, 1000.0), + (3475, "ec.generate.beam", "startThickness", 0.0, 4000.0), + (3475, "ec.generate.beam", "endThickness", 0.0, 4000.0), ]; fn path(effect: &str, param: &str) -> String { From 74bcb30540c770670c982de1cbab554f3b408d0a Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:47:15 +0530 Subject: [PATCH 57/83] #3471: Transform: Scale Height and Scale Width take After Effects' range Scale Height and Scale Width take -30000..30000 %, After Effects' recorded valid range in the same units. The CPU and GPU share the matrix (transform_matrix_px) and the buffer growth, which is capped at 16 Mpx (transform_grow; the CPU test already renders 100000 %), so larger scales stay bounded. Default and slider are unchanged. --- crates/aep/src/export/fx_defs.rs | 2 -- crates/effects/src/distort.rs | 4 ++-- crates/engine/src/tests/effect_ranges.rs | 2 ++ 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index e35f7c6fc..82d21666a 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -734,8 +734,6 @@ mod tests { ("ec.blur.ccradial", "amount", 3468), ("ec.distort.turbulentdisplace", "amount", 3469), ("ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 3470), - ("ec.distort.transform", "scaleHeight", 3471), - ("ec.distort.transform", "scaleWidth", 3471), ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), ("ec.noise.fractal", "subSettings/subInfluence", 3485), diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index 610f73f4c..59d4aad01 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -506,8 +506,8 @@ pub fn specs() -> Vec { p("anchor", "Anchor Point", pt(0.5, 0.5), ParamUi::Point), p("position", "Position", pt(0.5, 0.5), ParamUi::Point), p("uniform", "Uniform Scale", Value::Bool(true), ParamUi::Checkbox), - p("scaleHeight", "Scale Height", num(100.0), slider(-10000.0, 10000.0, 0.0, 600.0, 1)), - p("scaleWidth", "Scale Width", num(100.0), slider(-10000.0, 10000.0, 0.0, 600.0, 1)), + p("scaleHeight", "Scale Height", num(100.0), slider(-30000.0, 30000.0, 0.0, 600.0, 1)), + p("scaleWidth", "Scale Width", num(100.0), slider(-30000.0, 30000.0, 0.0, 600.0, 1)), p("skew", "Skew", num(0.0), slider(-70.0, 70.0, -70.0, 70.0, 1)), p("skewAxis", "Skew Axis", num(0.0), ParamUi::Angle), p("rotation", "Rotation", num(0.0), ParamUi::Angle), diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 320e1378f..9b3eb1414 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -57,6 +57,8 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3477, "ec.stylize.scatter", "amount", 0.0, 1000.0), (3475, "ec.generate.beam", "startThickness", 0.0, 4000.0), (3475, "ec.generate.beam", "endThickness", 0.0, 4000.0), + (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), + (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), ]; fn path(effect: &str, param: &str) -> String { From 98d82ae761bd465f7797fcbc20b0a0509f9dcd8c Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:47:15 +0530 Subject: [PATCH 58/83] #3470: Turbulent Displace: Random Seed takes After Effects' range Random Seed takes 0..100000, After Effects' recorded valid range (and what the other effects' Random Seed already takes). The CPU and GPU hash it the same way with wrapping u32 arithmetic, so any seed costs the same. Default and slider are unchanged. --- crates/aep/src/export/fx_defs.rs | 1 - crates/effects/src/distort2.rs | 2 +- crates/engine/src/tests/effect_ranges.rs | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/aep/src/export/fx_defs.rs b/crates/aep/src/export/fx_defs.rs index 82d21666a..338e00fc5 100644 --- a/crates/aep/src/export/fx_defs.rs +++ b/crates/aep/src/export/fx_defs.rs @@ -733,7 +733,6 @@ mod tests { ("ec.blur.radial", "amount", 3467), ("ec.blur.ccradial", "amount", 3468), ("ec.distort.turbulentdisplace", "amount", 3469), - ("ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 3470), ("ec.time.pixelmotionblur", "shutterAngle", 3481), ("ec.time.pixelmotionblur", "shutterSamples", 3482), ("ec.noise.fractal", "subSettings/subInfluence", 3485), diff --git a/crates/effects/src/distort2.rs b/crates/effects/src/distort2.rs index bbd8738a8..611cb6dcf 100644 --- a/crates/effects/src/distort2.rs +++ b/crates/effects/src/distort2.rs @@ -743,7 +743,7 @@ pub fn specs() -> Vec { p("evolution", "Evolution", num(0.0), ParamUi::Angle), p("evolutionOptions/cycleEvolution", "Cycle Evolution", Value::Bool(false), ParamUi::Checkbox), p("evolutionOptions/cycle", "Cycle (in Revolutions)", num(1.0), slider(1.0, 1000.0, 1.0, 20.0, 0)), - p("evolutionOptions/randomSeed", "Random Seed", num(0.0), slider(0.0, 10000.0, 0.0, 1000.0, 0)), + p("evolutionOptions/randomSeed", "Random Seed", num(0.0), slider(0.0, 100000.0, 0.0, 1000.0, 0)), p("pinning", "Pinning", Value::Enum(1), popup(&TURBULENT_PINNING)), p("resizeLayer", "Resize Layer", Value::Bool(false), ParamUi::Checkbox), ], diff --git a/crates/engine/src/tests/effect_ranges.rs b/crates/engine/src/tests/effect_ranges.rs index 9b3eb1414..7deaaa911 100644 --- a/crates/engine/src/tests/effect_ranges.rs +++ b/crates/engine/src/tests/effect_ranges.rs @@ -59,6 +59,7 @@ const ROWS: &[(u32, &str, &str, f64, f64)] = &[ (3475, "ec.generate.beam", "endThickness", 0.0, 4000.0), (3471, "ec.distort.transform", "scaleHeight", -30000.0, 30000.0), (3471, "ec.distort.transform", "scaleWidth", -30000.0, 30000.0), + (3470, "ec.distort.turbulentdisplace", "evolutionOptions/randomSeed", 0.0, 100000.0), ]; fn path(effect: &str, param: &str) -> String { From 64c28b56d74855428ab7707e636847aa0bf5a8f3 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 15:47:50 +0530 Subject: [PATCH 59/83] #3535: docs: which key covers what, why markers and audio are or aren't keyed --- crates/engine/src/analysis/frames_key.rs | 16 ++++++++++------ crates/engine/src/tests/analysis_inputs.rs | 2 +- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/analysis/frames_key.rs b/crates/engine/src/analysis/frames_key.rs index b6c542666..c43b3e92b 100644 --- a/crates/engine/src/analysis/frames_key.rs +++ b/crates/engine/src/analysis/frames_key.rs @@ -1,5 +1,6 @@ -//! What an analysis of a layer is made from, as one key shared by the Warp Stabilizer, the 3D -//! Camera Tracker and Roto Brush / Object Matte. +//! What an analysis of a layer is made from. One writer keys the Warp Stabilizer and the 3D +//! Camera Tracker ([`analysis_key`]: frames, masks, effects above, a precomp's contents) and Roto +//! Brush / Object Matte ([`input_key`]: frames, masks, effects above). //! //! The key hashes a text this module writes field by field. The source item (footage and its //! settings, solid), the Time Remap property, the masks and effect groups (their properties, @@ -9,7 +10,8 @@ //! the layer's frames, left out (with a reason) if it doesn't. Renaming a field or variant doesn't //! change keys. Of the analysed layer itself, only the fields named in `layer_frames` and //! [`analysis_key`] are read. The text leaves out observations (whether footage is available) and -//! data that never changes pixels (colour labels, UI hints, markers), so they never drop saved +//! data that never changes pixels (colour labels, UI hints, markers but a comp's timing markers; +//! only expressions read the others), so they never drop saved //! analyses (#3534, #3536). //! //! Keys saved by 0.22–0.24 hashed derived `Debug` text instead. [`legacy`] still recognises @@ -510,7 +512,8 @@ impl Text { preserve_transparency, track_matte, parent, - // Layer markers annotate it; Lock Markers protects them. + // Layer markers annotate it (only expressions read them, as for the analysed layer); + // Lock Markers protects them. markers: _, markers_locked: _, auto_orient, @@ -549,7 +552,8 @@ impl Text { } fn switches(&mut self, s: &Switches) { - // Lock and Shy only protect and hide the layer in the Timeline. + // Lock and Shy only protect and hide the layer in the Timeline. Audio is written (as are + // the Audio group and audio effects, in the property tree): a waveform effect can draw it. let Switches { video, audio, solo, locked: _, shy: _, collapse, quality, sampling, effects, frame_blend, motion_blur, adjustment, three_d, guide } = s; self.field("switches", format_args!("{video}/{audio}/{solo}/{collapse}/{effects}/{motion_blur}/{adjustment}/{three_d}/{guide}")); self.form("quality", quality); @@ -558,7 +562,7 @@ impl Text { } /// A comp's protected markers with a duration: they set its timing (Responsive Design). - /// Other markers annotate it. + /// Other markers annotate it; only expressions read them. fn timing_markers(&mut self, markers: &[Marker]) { for m in markers.iter().filter(|m| m.protected && m.duration > Tick::ZERO) { self.tick("timingMarker", m.time); diff --git a/crates/engine/src/tests/analysis_inputs.rs b/crates/engine/src/tests/analysis_inputs.rs index 5eb75c115..a6722a731 100644 --- a/crates/engine/src/tests/analysis_inputs.rs +++ b/crates/engine/src/tests/analysis_inputs.rs @@ -15,7 +15,7 @@ const CLIP: LayerId = LayerId(3); const WARP: u64 = 26; const TRACKER: u64 = 54; -/// `tracked-0.22.ecproj`'s clip with a mask and, in order, a Warp Stabilizer, a 3D Camera +/// `analysed-0.24.ecproj`: the clip of `tracked-0.22.ecproj` with a mask and, in order, a Warp Stabilizer, a 3D Camera /// Tracker, a Gaussian Blur and a Roto Brush. const ANALYSED: &str = include_str!("fixtures/analysed-0.24.ecproj"); From c41d889686e898980a55d7b4e8cce9235a803729 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 16:14:55 +0530 Subject: [PATCH 60/83] #3470, #3471, #3472, #3473, #3474, #3475, #3476, #3477, #3478, #3479, #3480, #3483, #3484, #3487, #3488, #3489, #3490, #3491: docs: effect ranges in the parity revision history --- docs/effects-parity.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/effects-parity.md b/docs/effects-parity.md index c7f850834..93bdf4792 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -64,6 +64,7 @@ the GPU is performance, not parity. | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | Parameters take After Effects' recorded valid ranges (hard range; defaults and sliders unchanged): Levels (Individual Controls) levels −10000..10000 and Gamma from 0; 4-Color Gradient Blend to 10000 and Jitter to 500 %; Change Color Hue Transform ±1800°; Noise HLS (and Auto) amounts to 1000 % and Grain Size from 0; Grid Border to 2000; Venetian Blinds Width 1..32000 and Feather to 32000; Radial Wipe Feather to 32000; Scatter Amount to 1000; Beam thicknesses to 4000; Transform Scale ±30000 %; Turbulent Displace Random Seed to 100000. A test checks every mapped parameter's range against the recorded table (CPU and GPU) | | 2026-10-19 | minor | Glow (original colours): bright pass per channel, 8 × (value − threshold + 0.061), measured against After Effects 2026 (CPU and GPU) | | 2026-10-19 | minor | Glow (colour channels): the glow covers the layer's blurred alpha, blur σ = 0.384 × radius, measured against After Effects 2026 renders (CPU and GPU) | | 2026-10-19 | minor | Radial Blur repeats the edge instead of sampling transparency outside the layer, measured against After Effects 2026 renders (CPU; Radial Blur has no GPU path) | From acf60eeaf3b05be46a354a18b1704a31ca024e7c Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 16:24:17 +0530 Subject: [PATCH 61/83] #3487, #3488, #3489, #3490, #3491: Levels (Individual Controls): bound the curve only where it would overflow The 1e6 bound also capped curves that were finite before (gamma 0.1 on an HDR value 4 x Input White is 4^10, about 1.05e6). The bound is now 1e30: 1e30 times the widest output range (2e4) is still finite, and every curve below it renders as before. A test pins 4^10. --- crates/effects/src/color2.rs | 11 ++++++----- crates/effects/src/color2/tests.rs | 4 ++++ crates/gpu/src/shaders/fx_tone.wgsl | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/effects/src/color2.rs b/crates/effects/src/color2.rs index ad370ea1d..9df44d76f 100644 --- a/crates/effects/src/color2.rs +++ b/crates/effects/src/color2.rs @@ -257,11 +257,12 @@ impl Lv { } } -/// How far Levels (Individual Controls)' curve may reach, far beyond any image value: with gamma -/// down to 0 (rendered as 0.01, an exponent of 100) an HDR value a few times Input White would -/// overflow `f32`, and an infinite curve times an empty output range is NaN. Bounded, the output -/// stays finite over the whole valid range (levels ±10000). The GPU (`fxt_lv`) uses the same. -const LEVELS_IC_CURVE_LIMIT: f32 = 1e6; +/// How far Levels (Individual Controls)' curve may reach: with gamma down to 0 (rendered as 0.01, +/// an exponent of 100) an HDR value a few times Input White overflows `f32`, and an infinite curve +/// times an empty output range is NaN. 1e30 times the widest output range (2e4) is still finite +/// (`f32::MAX` is 3.4e38), and every curve that was finite before stays as it was below it. The +/// GPU (`fxt_lv`) uses the same. +const LEVELS_IC_CURVE_LIMIT: f32 = 1e30; fn levels_ic(ctx: &EffectCtx, mut b: Buf) -> Buf { let lv = LV_IDS.map(|ids| Lv { diff --git a/crates/effects/src/color2/tests.rs b/crates/effects/src/color2/tests.rs index 069d4c9f7..76338dd98 100644 --- a/crates/effects/src/color2/tests.rs +++ b/crates/effects/src/color2/tests.rs @@ -294,6 +294,10 @@ fn levels_ic_stays_finite_over_the_whole_range() { let out = run("ec.color.levelsic", &img, &lv); assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{ib} {iw} {ob} {ow}: {:?}", out.data[0]); } + // The bound only stops the overflow: an HDR value that was finite before keeps its level + // (gamma 0.1 at 4 x Input White: 4^10). + let bright = run("ec.color.levelsic", &Image::filled(1, 1, [4.0, 4.0, 4.0, 1.0]), &[("rgb/rgbGamma", num(0.1)), ("clipToOutputWhite", Value::Enum(0))]); + assert_eq!(bright.data[0][0], 4.0f32.powf(10.0)); // Gamma 0 is the limit of a small gamma: below Input White the curve goes to 0. let dark = run("ec.color.levelsic", &Image::filled(1, 1, [0.5, 0.5, 0.5, 1.0]), &[("rgb/rgbGamma", num(0.0))]); assert!(dark.data[0][0] < 1e-6, "{:?}", dark.data[0]); diff --git a/crates/gpu/src/shaders/fx_tone.wgsl b/crates/gpu/src/shaders/fx_tone.wgsl index fb7dfe42b..bcd23baa7 100644 --- a/crates/gpu/src/shaders/fx_tone.wgsl +++ b/crates/gpu/src/shaders/fx_tone.wgsl @@ -41,7 +41,7 @@ fn fxt_lv(i: u32, v: f32, clip_b: bool, clip_w: bool) -> f32 { t = min(t, 1.0); } // color2::LEVELS_IC_CURVE_LIMIT keeps the curve finite. - let curve = clamp(fxt_gamma(t, max(data[o + 2u], 0.01)), -1e6, 1e6); + let curve = clamp(fxt_gamma(t, max(data[o + 2u], 0.01)), -1e30, 1e30); return data[o + 3u] + (data[o + 4u] - data[o + 3u]) * curve; } From c0387ea18ada7a31870705a583c9f12aa991ab88 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 16:24:17 +0530 Subject: [PATCH 62/83] #3470, #3472, #3473, #3474, #3475, #3476, #3477, #3480, #3483, #3484, #3487-#3491: test the ends of the new ranges on the GPU CPU / GPU comparisons at the new ends for Venetian Blinds (width 1, width and feather 32000), Radial Wipe (feather 32000), Grid (border 2000), Scatter (1000), Beam (4000), Change Color (1710 degrees) and Turbulent Displace (seed 100000). The comparison counts infinity on both sides as equal, so Levels (Individual Controls) gets a direct check that the GPU's output is finite at the ends of its ranges. The Noise HLS test asserts the spec's ranges, so it fails without them. --- crates/effects/src/noise.rs | 4 ++++ crates/gpu/src/tests/fx_distort.rs | 2 ++ crates/gpu/src/tests/fx_gen2.rs | 2 ++ crates/gpu/src/tests/fx_generate.rs | 7 +++++++ crates/gpu/src/tests/fx_stylize.rs | 2 ++ crates/gpu/src/tests/fx_tone.rs | 32 +++++++++++++++++++++++++++++ 6 files changed, 49 insertions(+) diff --git a/crates/effects/src/noise.rs b/crates/effects/src/noise.rs index 246910cd5..fde24b537 100644 --- a/crates/effects/src/noise.rs +++ b/crates/effects/src/noise.rs @@ -978,6 +978,10 @@ mod tests { *p = premul([0.6, 0.3, (i % 7) as f32 / 7.0], 1.0); } for id in ["ec.noise.noisehls", "ec.noise.noisehlsauto"] { + for (param, lo, hi) in [("hue", 0.0, 1000.0), ("lightness", 0.0, 1000.0), ("saturation", 0.0, 1000.0), ("grainSize", 0.0, 100.0)] { + let ui = &crate::find(id).unwrap().params.iter().find(|p| p.id == param).unwrap().ui; + assert!(matches!(ui, ParamUi::Slider { min, max, .. } if *min == lo && *max == hi), "{id} {param}: {ui:?}"); + } let at = |amount: f64, grain: f64| { let vals = [("noise", Value::Enum(2)), ("hue", num(amount)), ("lightness", num(amount)), ("saturation", num(amount)), ("grainSize", num(grain))]; diff --git a/crates/gpu/src/tests/fx_distort.rs b/crates/gpu/src/tests/fx_distort.rs index 1b8621408..6fc18f3c9 100644 --- a/crates/gpu/src/tests/fx_distort.rs +++ b/crates/gpu/src/tests/fx_distort.rs @@ -38,6 +38,8 @@ fn twirl_bulge_ripple_wave_warp() { #[test] fn turbulent_displace_and_cc_lens() { effect_case("ec.distort.turbulentdisplace", &[("size", n(30.0)), ("amount", n(20.0))]); + // #3470: After Effects' maximum Random Seed. + effect_case("ec.distort.turbulentdisplace", &[("size", n(30.0)), ("amount", n(20.0)), ("evolutionOptions/randomSeed", n(100000.0))]); effect_case( "ec.distort.turbulentdisplace", &[("displacement", e(1)), ("complexity", n(3.5)), ("evolution", n(90.0)), ("size", n(25.0)), ("pinning", e(2)), ("resizeLayer", on())], diff --git a/crates/gpu/src/tests/fx_gen2.rs b/crates/gpu/src/tests/fx_gen2.rs index 620cced13..1c19725e1 100644 --- a/crates/gpu/src/tests/fx_gen2.rs +++ b/crates/gpu/src/tests/fx_gen2.rs @@ -40,6 +40,8 @@ fn closed_form() { env_case("ec.generate.beam", &[]); env_case("ec.generate.beam", &[("length", n(70.0)), ("time", n(40.0)), ("softness", n(0.0)), ("perspective3d", off()), ("compositeOnOriginal", off())]); env_case("ec.generate.beam", &[("startThickness", n(3.0)), ("endThickness", n(20.0)), ("insideColor", c(0.3, 0.9, 1.0))]); + // #3475: After Effects' maximum thickness. + env_case("ec.generate.beam", &[("startThickness", n(0.0)), ("endThickness", n(4000.0))]); env_case("ec.generate.lensflare", &[]); env_case("ec.generate.lensflare", &[("lensType", e(1)), ("flareCenter", pt(50.0, 30.0)), ("blendWithOriginal", n(30.0))]); env_case("ec.generate.lensflare", &[("lensType", e(2)), ("flareBrightness", n(160.0))]); diff --git a/crates/gpu/src/tests/fx_generate.rs b/crates/gpu/src/tests/fx_generate.rs index d7e05e047..f8482b5ab 100644 --- a/crates/gpu/src/tests/fx_generate.rs +++ b/crates/gpu/src/tests/fx_generate.rs @@ -83,6 +83,11 @@ fn wipes() { effect_case("ec.transition.radialwipe", &[("completion", n(45.0)), ("wipe", e(1)), ("center", pt(30.2, 19.6))]); effect_case("ec.transition.radialwipe", &[("completion", n(60.0)), ("wipe", e(2)), ("startAngle", n(-40.0)), ("feather", n(3.0))]); effect_case("ec.transition.radialwipe", &[("completion", n(0.0)), ("feather", n(20.0))]); + // #3472-#3474: the ends of After Effects' ranges (a Feather wider than 8 blinds is the CPU's + // even veil). + effect_case("ec.transition.venetian", &[("completion", n(40.0)), ("width", n(1.0)), ("feather", n(6.0))]); + effect_case("ec.transition.venetian", &[("completion", n(40.0)), ("width", n(32000.0)), ("feather", n(32000.0))]); + effect_case("ec.transition.radialwipe", &[("completion", n(40.0)), ("feather", n(32000.0))]); effect_case("ec.transition.gradientwipe", &[("completion", n(40.0))]); effect_case("ec.transition.gradientwipe", &[("completion", n(55.0)), ("softness", n(30.0)), ("invert", b(true))]); effect_case("ec.transition.gradientwipe", &[("completion", n(100.0))]); @@ -147,6 +152,8 @@ fn generators() { ); effect_case("ec.generate.checkerboard", &[("sizeFrom", e(0)), ("corner", pt(16.0, 11.0)), ("color", c(0.9, 0.3, 0.1)), ("blendingMode", e(1))]); effect_case("ec.generate.grid", &[("width", n(12.0)), ("border", n(3.0))]); + // #3476: a border wider than the cells (After Effects' maximum). + effect_case("ec.generate.grid", &[("width", n(12.0)), ("border", n(2000.0))]); effect_case( "ec.generate.grid", &[ diff --git a/crates/gpu/src/tests/fx_stylize.rs b/crates/gpu/src/tests/fx_stylize.rs index 63d93f207..8c6c7be33 100644 --- a/crates/gpu/src/tests/fx_stylize.rs +++ b/crates/gpu/src/tests/fx_stylize.rs @@ -109,6 +109,8 @@ fn arbitrary_map_signed_fractional_and_near_zero_wraps() { #[test] fn scatter_brush_strokes() { effect_case("ec.stylize.scatter", &[("amount", n(5.0))]); + // #3477: After Effects' maximum, far beyond the layer. + effect_case("ec.stylize.scatter", &[("amount", n(1000.0))]); effect_case("ec.stylize.scatter", &[("amount", n(3.0)), ("grain", e(1))]); effect_case("ec.stylize.scatter", &[("amount", n(7.0)), ("grain", e(2)), ("randomizeEveryFrame", on())]); effect_case("ec.stylize.brushstrokes", &[]); diff --git a/crates/gpu/src/tests/fx_tone.rs b/crates/gpu/src/tests/fx_tone.rs index ca80f3836..3083f5949 100644 --- a/crates/gpu/src/tests/fx_tone.rs +++ b/crates/gpu/src/tests/fx_tone.rs @@ -81,6 +81,8 @@ fn colour_replacement() { &[("amount", n(100.0)), ("color", c(0.8, 0.4, 0.3)), ("matchColors", e(1)), ("tolerance", n(5.0)), ("edgeSoftness", n(30.0))], ); effect_case("ec.color.changecolor", &[("hueTransform", n(90.0)), ("colorToChange", c(0.7, 0.5, 0.4)), ("matchingSoftness", n(20.0))]); + // #3480: near the top of After Effects' range (four and three quarter turns). + effect_case("ec.color.changecolor", &[("hueTransform", n(1710.0)), ("colorToChange", c(0.7, 0.5, 0.4)), ("matchingSoftness", n(20.0))]); effect_case( "ec.color.changecolor", &[ @@ -199,3 +201,33 @@ fn color_stabilizer() { fn gradient_ramp_matches_the_cpu() { effect_case("ec.generate.gradientramp", &[]); } + +/// #3487-#3491: at the ends of the valid ranges the GPU's Levels (Individual Controls) output is +/// finite (the CPU / GPU comparison counts infinity on both sides as equal). +#[test] +fn levels_ic_is_finite_at_the_ends_of_its_ranges() { + let Some(g) = crate::tests::gpu() else { return }; + let spec = effectcraft_effects::find("ec.color.levelsic").unwrap(); + let size = [16.0, 8.0]; + let mut params = + effectcraft_effects::Params { values: spec.params.iter().map(|ps| (ps.id.to_string(), effectcraft_effects::default_value(ps, size))).collect() }; + for (k, v) in [ + ("rgb/rgbInWhite", n(0.2)), + ("rgb/rgbGamma", n(0.0)), + ("red/redOutBlack", n(-10000.0)), + ("blue/blueOutWhite", n(10000.0)), + ("green/greenOutWhite", n(0.0)), + ("clipToOutputWhite", e(0)), + ] { + params.values.insert(k.to_string(), v); + } + let mut img = crate::tests::pattern(7, 16, 8); + for p in &mut img.data { + *p = p.map(|v| v * 3.0); + } + let buf = effectcraft_effects::Buf { img, offset: [0.0, 0.0], scale: 1.0 }; + let ctx = effectcraft_effects::EffectCtx { params: ¶ms, time: 0.0, layer_size: size, seed: 1, adjustment: false, env: Default::default() }; + let out = effectcraft_render::Accelerator::effects(g, &[effectcraft_render::FxStep { spec, ctx }], &buf, None) + .expect("the GPU runs Levels (Individual Controls)"); + assert!(out.img.data.iter().flatten().all(|v| v.is_finite()), "{:?}", out.img.data.iter().find(|p| p.iter().any(|v| !v.is_finite()))); +} From 28c63ce72807015de358d39f4c4c99cee09d3149 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 16:30:24 +0530 Subject: [PATCH 63/83] #3535: the analysis key leaves out the effects above while the Effects switch is off The renderer skips the whole effect stack then, so editing those effects doesn't change the analysed frames. Roto Brush Input Keys keep their text. --- crates/engine/src/analysis/frames_key.rs | 11 +++++++---- crates/engine/src/tests/analysis_inputs.rs | 7 +++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/analysis/frames_key.rs b/crates/engine/src/analysis/frames_key.rs index c43b3e92b..abbafde67 100644 --- a/crates/engine/src/analysis/frames_key.rs +++ b/crates/engine/src/analysis/frames_key.rs @@ -88,7 +88,7 @@ pub(crate) fn input_key_of(signature: String, layer: &Layer, uid: Uid) -> String let mut t = Text::new(); t.word(VERSION); t.word(&signature); - t.inputs_above(layer, uid); + t.inputs_above(layer, uid, true); hex(&t.0) } @@ -107,7 +107,8 @@ pub(crate) fn analysis_key(p: &Project, comp: ItemId, layer: &Layer, uid: Uid) - if layer.effects().and_then(|fx| fx.groups().next()).is_some_and(|g| g.uid != uid) { t.field("effectsSwitch", layer.switches.effects); } - t.inputs_above(layer, uid); + // While it is off the renderer skips the whole effect stack: the effects above draw nothing. + t.inputs_above(layer, uid, layer.switches.effects); t.precomp(p, comp, layer); hex(&t.0) } @@ -392,14 +393,16 @@ impl Text { /// The layer's masks and the effects above the instance `uid`: what the effect's input is /// made of besides the layer's frames. - fn inputs_above(&mut self, layer: &Layer, uid: Uid) { + /// `effects`: whether to write the effects (a Roto Brush Input Key always does: frozen mattes + /// hash the saved key, so it keeps its text). + fn inputs_above(&mut self, layer: &Layer, uid: Uid, effects: bool) { if let Some(m) = layer.masks() { self.word("masks"); self.group(m, 0); } if let Some(fx) = layer.effects() { self.word("effects"); - for g in fx.groups().take_while(|g| g.uid != uid) { + for g in fx.groups().take_while(|g| effects && g.uid != uid) { self.group(g, 0); } } diff --git a/crates/engine/src/tests/analysis_inputs.rs b/crates/engine/src/tests/analysis_inputs.rs index a6722a731..b45b38eda 100644 --- a/crates/engine/src/tests/analysis_inputs.rs +++ b/crates/engine/src/tests/analysis_inputs.rs @@ -107,6 +107,13 @@ fn masks_and_effects_above(saved: Saved) { assert_eq!(analysed(&s), [true, true]); // The Effects switch turns the Warp Stabilizer (above the tracker) off. check(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": false}), [true, false]); + // While it is off, the effects above draw nothing: editing them keeps the analyses. + run(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": false})); + analyse(&mut s, saved); + check(&mut s, "prop.set", json!({"layer": CLIP.0, "path": "effects/#1/stabilization/smoothness", "value": 20}), [true, true]); + run(&mut s, "layer.setSwitch", json!({"layers": [CLIP.0], "switch": "effects", "value": true})); + assert_eq!(analysed(&s), [true, false]); + analyse(&mut s, saved); // An effect moved above the Warp Stabilizer is part of both inputs, and its settings too. s.edit("blur first", None, |p, _| { From 047b912fc58ecface93af11ce75411b2eda6122a Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 16:35:08 +0530 Subject: [PATCH 64/83] #3487, #3488, #3489, #3490, #3491: Levels (Individual Controls): GPU saturates the curve before pow can overflow WGSL leaves the result of an overflowing pow indeterminate, so clamping after it did not guarantee the CPU's 1e30 bound on every backend. A curve past the bound (log2|t| / gamma > 99.7) now saturates to +-1e30 without calling pow; between 1e30 and 2^99.7 the clamp gives the same 1e30, so the GPU matches the CPU everywhere. --- crates/gpu/src/shaders/fx_tone.wgsl | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/gpu/src/shaders/fx_tone.wgsl b/crates/gpu/src/shaders/fx_tone.wgsl index bcd23baa7..a47d5df59 100644 --- a/crates/gpu/src/shaders/fx_tone.wgsl +++ b/crates/gpu/src/shaders/fx_tone.wgsl @@ -40,8 +40,12 @@ fn fxt_lv(i: u32, v: f32, clip_b: bool, clip_w: bool) -> f32 { if (clip_w) { t = min(t, 1.0); } - // color2::LEVELS_IC_CURVE_LIMIT keeps the curve finite. - let curve = clamp(fxt_gamma(t, max(data[o + 2u], 0.01)), -1e30, 1e30); + // color2::LEVELS_IC_CURVE_LIMIT keeps the curve finite. WGSL leaves an overflowing pow + // indeterminate, so a curve past the bound saturates before pow: |t|^(1/g) > 1e30 once + // log2|t| / g > 99.66; between 1e30 and 2^99.7 the clamp gives the same 1e30. + let g = max(data[o + 2u], 0.01); + let saturate = abs(t) > 1.0 && log2(abs(t)) / g > 99.7; + let curve = select(clamp(fxt_gamma(t, g), -1e30, 1e30), sign(t) * 1e30, saturate); return data[o + 3u] + (data[o + 4u] - data[o + 3u]) * curve; } From f88d0d0a8ddc9ae0feea24af8082381b6423a8fd Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 16:37:09 +0530 Subject: [PATCH 65/83] #3487, #3488, #3489, #3490, #3491: Levels (Individual Controls): skip the overflowing pow with a branch WGSL's select evaluates both of its arguments, so the previous commit still ran the overflowing pow and only discarded it. An explicit branch now skips the power for a curve past the bound. --- crates/gpu/src/shaders/fx_tone.wgsl | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/gpu/src/shaders/fx_tone.wgsl b/crates/gpu/src/shaders/fx_tone.wgsl index a47d5df59..9472d63f0 100644 --- a/crates/gpu/src/shaders/fx_tone.wgsl +++ b/crates/gpu/src/shaders/fx_tone.wgsl @@ -43,9 +43,12 @@ fn fxt_lv(i: u32, v: f32, clip_b: bool, clip_w: bool) -> f32 { // color2::LEVELS_IC_CURVE_LIMIT keeps the curve finite. WGSL leaves an overflowing pow // indeterminate, so a curve past the bound saturates before pow: |t|^(1/g) > 1e30 once // log2|t| / g > 99.66; between 1e30 and 2^99.7 the clamp gives the same 1e30. + // A branch, not select: select evaluates both sides, so pow would still run. let g = max(data[o + 2u], 0.01); - let saturate = abs(t) > 1.0 && log2(abs(t)) / g > 99.7; - let curve = select(clamp(fxt_gamma(t, g), -1e30, 1e30), sign(t) * 1e30, saturate); + var curve = sign(t) * 1e30; + if (!(abs(t) > 1.0 && log2(abs(t)) / g > 99.7)) { + curve = clamp(fxt_gamma(t, g), -1e30, 1e30); + } return data[o + 3u] + (data[o + 4u] - data[o + 3u]) * curve; } From 6e1dd081477709371bde8be31a62117cd8f737bb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:29:14 -0500 Subject: [PATCH 66/83] Import: a 3D model's left-out textures reach the user as an import warning * Import: a model's left-out parts reach the user as an import warning (Model::warnings, Importer::probe_noting) * Import: a model's left-out parts reach the user as an import warning --- crates/engine/src/cmd/file.rs | 10 +++++++--- crates/engine/src/services.rs | 5 +++++ crates/engine/src/tests/session.rs | 19 +++++++++++++++++++ crates/host/src/lib.rs | 3 +++ crates/media/src/lib.rs | 2 +- crates/media/src/probe.rs | 14 ++++++++++++++ crates/model/src/gltf.rs | 2 +- crates/model/src/lib.rs | 7 +++++++ 8 files changed, 57 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 890a9def1..d0158a286 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -319,15 +319,19 @@ impl Prober { return f.map(|footage| Probed { name, footage, ask_alpha: false, warning: None }).map_err(fail); } let importer = self.importer.as_ref().ok_or_else(|| fail("media import is not available in this build".into()))?; - let mut f = crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?; - let mut warning = None; + // What the file's own import left out (a model's textures over the limits) is a warning too. + let (mut f, mut warning) = match src { + Source::File(_) => importer.probe_noting(path).map_err(fail)?, + _ => (crate::sequence::probe(importer.as_ref(), src, self.sequence_rate).map_err(fail)?, None), + }; // Settings ▸ Import ▸ Report Missing Frames (numbered sequences). if f.kind == FootageKind::Sequence && !f.alphabetical && self.report_missing_frames && let Some(gaps) = crate::sequence::missing_report(&f.sequence) { - warning = Some(format!("{name}: {gaps} (the previous frame is held)")); + let gaps = format!("{name}: {gaps} (the previous frame is held)"); + warning = Some(warning.map_or(gaps.clone(), |w| format!("{w}; {gaps}"))); } // Settings ▸ Import ▸ Interpret Unlabeled Alpha As: images only (a 3D model renders its // own alpha, and audio and data have none). diff --git a/crates/engine/src/services.rs b/crates/engine/src/services.rs index 5658df107..fe95f5300 100644 --- a/crates/engine/src/services.rs +++ b/crates/engine/src/services.rs @@ -106,6 +106,11 @@ pub trait Importer: Send + Sync { /// Probe one file and return footage metadata. Image sequences are the engine's /// ([`sequence`]): it groups numbered stills and probes their first file here. fn probe(&self, path: &str) -> std::result::Result; + /// [`probe`](Self::probe), and what the import left out of the file (a 3D model's textures + /// over the limits), which the import shows the user. + fn probe_noting(&self, path: &str) -> std::result::Result<(effectcraft_project::Footage, Option), String> { + self.probe(path).map(|f| (f, None)) + } /// A footage file's bytes are now at `path` (extracted from a template): hosts whose media /// layer reads from memory (the browser) register them; file-based ones need nothing. fn register(&self, _path: &str, _data: &[u8]) {} diff --git a/crates/engine/src/tests/session.rs b/crates/engine/src/tests/session.rs index b253640e7..020c2daf0 100644 --- a/crates/engine/src/tests/session.rs +++ b/crates/engine/src/tests/session.rs @@ -96,6 +96,25 @@ fn imported_files_go_into_the_comp_where_they_were_dropped() { assert!(s.execute("layer.addItem", json!({"item": "a.png", "position": [1.0]})).is_err(), "position needs x and y"); } +/// What an import left out of a file (a 3D model's textures over the limits) comes back in the +/// import's `warnings`. +#[test] +fn what_an_import_left_out_is_a_warning() { + use effectcraft_project::{Footage, FootageKind}; + struct Probe; + impl crate::Importer for Probe { + fn probe(&self, path: &str) -> Result { + Ok(Footage { path: path.into(), kind: FootageKind::Model, ..Default::default() }) + } + fn probe_noting(&self, path: &str) -> Result<(Footage, Option), String> { + Ok((self.probe(path)?, Some(format!("{path}: texture `a.png` left out")))) + } + } + let mut s = Session { importer: Some(std::sync::Arc::new(Probe)), ..Default::default() }; + let r = s.execute("file.import", json!({"paths": ["/m/scene.obj"]})).unwrap(); + assert_eq!(r["warnings"], json!(["/m/scene.obj: texture `a.png` left out"])); +} + /// #270: files dropped or picked in the Import dialog (`file.import {background}`) are probed in /// a background job that says which file it is reading and how many are left; then they arrive /// in one undo step, all selected, with a count. The same file imported again arrives again. diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index 843a06123..7212fd730 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -20,6 +20,9 @@ impl Importer for MediaImporter { fn probe(&self, path: &str) -> Result { effectcraft_media::probe(path).map_err(|e| e.to_string()) } + fn probe_noting(&self, path: &str) -> Result<(Footage, Option), String> { + effectcraft_media::probe_noting(path).map_err(|e| e.to_string()) + } } /// Render Queue export via `effectcraft-export`: to the file system, or to `sink` (the web app diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 0b509c45f..454c3705f 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -33,7 +33,7 @@ mod webp_anim; /// Video decoder counters (time in decoders, samples decoded, seeks, cache hits), for benchmarks. pub use filmcraft_codecs::{GopStats, gop_stats}; pub use pool::{DEFAULT_BUDGET, MediaPool, PoolStats}; -pub use probe::{DEFAULT_SEQUENCE_RATE, probe, probe_bytes, probe_model}; +pub use probe::{DEFAULT_SEQUENCE_RATE, probe, probe_bytes, probe_model, probe_noting}; /// Errors from probing or decoding footage. #[derive(Debug, thiserror::Error)] diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 2c7b2a402..2a734b7d5 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -43,11 +43,25 @@ fn side_file_reader(model: &Path) -> impl Fn(&str) -> Option> + use<> { } } +thread_local! { + /// What the last model probed on this thread left out (see [`probe_noting`]). + static MODEL_WARNING: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// [`probe`], and what the import left out of the file (a 3D model's textures over the limits), +/// for the user. +pub fn probe_noting(path: impl AsRef) -> Result<(Footage, Option)> { + MODEL_WARNING.with(|w| w.borrow_mut().take()); + let f = probe(path)?; + Ok((f, MODEL_WARNING.with(|w| w.borrow_mut().take()))) +} + /// Probe a 3D model (glTF 2.0 / OBJ / STL / FBX): a [`FootageKind::Model`] item whose duration is its /// longest animation. `resolve` reads sibling resources. pub fn probe_model(path: &str, bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result { let m = effectcraft_model::load(path, bytes, resolve).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; let s = m.summary(); + MODEL_WARNING.with(|w| *w.borrow_mut() = (!m.warnings.is_empty()).then(|| format!("{path}: {}", m.warnings.join("; ")))); let dur = s.animations.iter().map(|a| a.1).fold(0.0f64, f64::max); let codec = match effectcraft_model::format_of(path) { Some("obj") => "OBJ", diff --git a/crates/model/src/gltf.rs b/crates/model/src/gltf.rs index c0b736359..79dab1ddc 100644 --- a/crates/model/src/gltf.rs +++ b/crates/model/src/gltf.rs @@ -536,7 +536,7 @@ pub(crate) fn parse_with_budget(bytes: &[u8], resolve: &dyn Fn(&str) -> Option String { diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 19a0d37f3..2a7374a05 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -68,6 +68,11 @@ impl Texture { pub fn solid(c: [f32; 4]) -> Texture { Texture { width: 1, height: 1, data: vec![c], wrap: [Wrap::Repeat; 2] } } + /// The pixel size an image claims, read from its header without decoding it. + pub fn dimensions(bytes: &[u8]) -> Result<(u32, u32)> { + let reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| perr(format!("image: {e}")))?; + reader.into_dimensions().map_err(|e| perr(format!("image: {e}"))) + } /// Decode a PNG or JPEG. pub fn decode(bytes: &[u8]) -> Result { let img = image::load_from_memory(bytes).map_err(|e| perr(format!("image: {e}")))?.to_rgba32f(); @@ -512,6 +517,8 @@ pub struct Model { pub cameras: Vec, /// Punctual lights embedded in the file (glTF `KHR_lights_punctual`). pub lights: Vec, + /// Parts of the file the import left out (textures over the limits), for the user. + pub warnings: Vec, } /// A camera embedded in a model file. From 9f93ac03faa3f623d485f8310b53b0b0eeb8c5e3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:29:20 -0500 Subject: [PATCH 67/83] Text layout: a wrapped line finds its glyphs and end caret by bisection * Text layout: a wrapped line finds its glyphs and end caret by bisection * Fix merge of layout tests --- crates/text/src/layout.rs | 37 +++++++++++++++++++++++++++++---- crates/text/src/layout/tests.rs | 19 +++++++++++++++++ 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index acf292889..9eb19d919 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -378,6 +378,34 @@ struct Item { range: Range, rtl: bool, glyphs: Vec, + /// Whether the glyphs' clusters never decrease (`Some(true)`) or never increase + /// (`Some(false)`) along `glyphs`: the glyphs of a cluster range are then contiguous. + cluster_order: Option, +} + +impl Item { + fn new(range: Range, rtl: bool, glyphs: Vec) -> Self { + let cluster_order = if glyphs.windows(2).all(|w| w[0].cluster <= w[1].cluster) { + Some(true) + } else if glyphs.windows(2).all(|w| w[0].cluster >= w[1].cluster) { + Some(false) + } else { + None + }; + Self { range, rtl, glyphs, cluster_order } + } + + /// The glyphs whose cluster lies in `run`, in glyph order, found by bisection when the clusters + /// are ordered (a line of a long paragraph otherwise scanned the whole item). + fn glyphs_in(&self, run: &Range) -> impl Iterator { + let g = &self.glyphs; + let (lo, hi) = match self.cluster_order { + Some(true) => (g.partition_point(|x| x.cluster < run.start), g.partition_point(|x| x.cluster < run.end)), + Some(false) => (g.partition_point(|x| x.cluster >= run.end), g.partition_point(|x| x.cluster >= run.start)), + None => (0, g.len()), + }; + g[lo..hi].iter().filter(|x| run.contains(&x.cluster)) + } } fn upper_single(c: char) -> char { @@ -929,7 +957,7 @@ impl<'a> Para<'a> { idx.reverse(); } for k in idx { - for g in self.items[k].glyphs.iter().filter(|g| run.contains(&g.cluster)) { + for g in self.items[k].glyphs_in(&run) { let st = &self.runs[g.run].1; let x0 = pen; pen += g.pre; @@ -990,9 +1018,10 @@ impl<'a> Para<'a> { } } // end of line caret - let end_x = match self.chars.iter().rev().find(|c| c.0 < r.end && c.0 >= r.start) { + let last_char = self.chars.partition_point(|c| c.0 < r.end).checked_sub(1).and_then(|i| self.chars.get(i)).filter(|c| c.0 >= r.start); + let end_x = match last_char { Some(c) => { - let cs = cluster_starts.iter().rev().find(|s| **s <= c.0).copied(); + let cs = cluster_starts.partition_point(|s| *s <= c.0).checked_sub(1).and_then(|i| cluster_starts.get(i)).copied(); match cs.and_then(|s| extents.get(&s)) { Some(&(x0, x1, rtl)) => { if rtl { @@ -1095,7 +1124,7 @@ fn build_items(text: &str, chars: &[CharInfo], runs: &[(Range, TextStyle) let mut glyphs = shape_item(&sub, rtl, face, size, style, si, form); space_item(&mut glyphs, style, text, true); let end = if j < chars.len() { chars[j].0 } else { text.len() }; - items.push(Item { range: chars[i].0..end, rtl, glyphs }); + items.push(Item::new(chars[i].0..end, rtl, glyphs)); i = j; } items diff --git a/crates/text/src/layout/tests.rs b/crates/text/src/layout/tests.rs index c467cb5f9..bf275cad8 100644 --- a/crates/text/src/layout/tests.rs +++ b/crates/text/src/layout/tests.rs @@ -506,6 +506,25 @@ fn a_later_vertical_run_keeps_the_first_line_baseline() { assert!((mixed.lines[0].baseline - plain.lines[0].baseline).abs() < 1e-3, "{} vs {}", mixed.lines[0].baseline, plain.lines[0].baseline); } +/// `Item::glyphs_in` finds a cluster range by bisection when the clusters are ordered, and agrees +/// with a full scan for ascending, descending and unordered clusters. +#[test] +fn item_glyphs_in_matches_a_full_scan() { + let glyph = |cluster| ShapedGlyph { face: 0, id: cluster as u32, cluster, adv: 1.0, pre: 0.0, dx: 0.0, dy: 0.0, size: 10.0, run: 0, rise: 0.0 }; + let asc: Vec = vec![0, 0, 1, 3, 3, 3, 5, 8]; + let desc: Vec = asc.iter().rev().copied().collect(); + let mixed: Vec = vec![3, 0, 5, 1, 8, 3, 0, 3]; + for (clusters, order) in [(&asc, Some(true)), (&desc, Some(false)), (&mixed, None)] { + let item = Item::new(0..9, false, clusters.iter().map(|&c| glyph(c)).collect()); + assert_eq!(item.cluster_order, order); + for (a, b) in [(0, 9), (0, 1), (1, 4), (3, 4), (4, 9), (6, 8), (9, 9), (2, 3)] { + let got: Vec = item.glyphs_in(&(a..b)).map(|g| g.cluster).collect(); + let want: Vec = clusters.iter().copied().filter(|c| (a..b).contains(c)).collect(); + assert_eq!(got, want, "{clusters:?} {a}..{b}"); + } + } +} + #[test] fn run_lookup_by_bisection_matches_the_scan() { let scan = |runs: &[(Range, TextStyle)], b: usize| { From bdc56ca75e1c29aa4791e968dc2dd87730ad7785 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:29:25 -0500 Subject: [PATCH 68/83] Timewarp: bound the motion search's total work by coarsening the vector grid * Timewarp: bound the motion search's total comparisons by coarsening the vector grid * Timewarp: coarsen within the frame, keep the pyramid depth and the window inside the frame --- crates/raster/src/flow.rs | 73 +++++++++++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 7 deletions(-) diff --git a/crates/raster/src/flow.rs b/crates/raster/src/flow.rs index 4fdf0e060..3a4a9d6f8 100644 --- a/crates/raster/src/flow.rs +++ b/crates/raster/src/flow.rs @@ -113,16 +113,63 @@ pub fn block_flow(a: &Image, b: &Image, block: u32, radius: i32) -> Flow { block_flow_window(a, b, block, block, radius) } +/// Largest coarse search radius honoured (the effects use at most 64). +const MAX_RADIUS: i32 = 1024; +/// Upper bound on the pixel comparisons of one motion search (about 4·10¹²: minutes of work on +/// many cores). A finer vector grid than this allows is made coarser, by doubling the tile. +const MAX_SEARCH_WORK: f64 = 4.4e12; + +/// The pixel comparisons [`block_flow_window`] makes for tiles of `bs`: every tile, at every +/// pyramid level, tries its candidate vectors with a `window`-sized block, then refines. +/// The pyramid depth follows the requested tile `fine`, not the coarsened one, so a coarser vector +/// grid keeps the full search range. +fn search_work(w: usize, h: usize, bs: usize, fine: usize, win: i64, radius: i64) -> f64 { + let tiles = (w.div_ceil(bs).max(1) as f64) * (h.div_ceil(bs).max(1) as f64); + let reach = (fine as i64).max(win) as usize * 2; + let (mut lw, mut lh, mut top) = (w, h, 0u32); + while top < 3 && lw / 2 >= reach && lh / 2 >= reach { + (lw, lh, top) = (lw / 2, lh / 2, top + 1); + } + let mut per_tile = 5.0 * (win * win) as f64; + for level in 0..=top { + let lbs = (win >> level).max(4) as f64; + let (seeds, r) = if level == top { (1.0, radius as f64) } else { (6.0, 1.0) }; + per_tile += seeds * (2.0 * r + 1.0).powi(2) * lbs * lbs; + } + tiles * per_tile +} + +/// The tile size and radius to search with: `tile`, doubled (while it still fits the frame) and +/// then, if that is not enough, the radius halved, until the search is within [`MAX_SEARCH_WORK`]. +fn planned(w: usize, h: usize, tile: usize, win: i64, radius: i64) -> (usize, i64) { + let (mut bs, mut r) = (tile, radius); + while bs * 2 <= w.min(h) && search_work(w, h, bs, tile, win, r) > MAX_SEARCH_WORK { + bs *= 2; + } + while r > 1 && search_work(w, h, bs, tile, win, r) > MAX_SEARCH_WORK { + r /= 2; + } + (bs, r) +} + /// [`block_flow`] with separate vector spacing and matching window: one vector per /// `tile × tile` tile, each matched with the `window × window` block centred on its tile /// (Timewarp's Vector Detail and Block Size). pub fn block_flow_window(a: &Image, b: &Image, tile: u32, window: u32, radius: i32) -> Flow { - let bs = tile.max(2) as usize; // The matching cost per vector grows with the window's area; 512 is far above any block size the effects offer. let win = i64::from(window.clamp(4, 512)); + let radius = radius.min(MAX_RADIUS); + let fine = tile.max(2) as usize; + let (bs, radius) = planned(a.width as usize, a.height as usize, fine, win, i64::from(radius)); + let coarse = bs != fine; // Window origin relative to the tile origin. let wo = bs as i64 / 2 - win / 2; let (w, h) = (a.width as usize, a.height as usize); + // A coarsened grid's last (partial) tiles keep their window inside the frame. + let origin = |c: i64, dim: usize| { + let o = c * bs as i64 + wo; + if coarse { o.clamp(0, (dim as i64 - win).max(0)) } else { o } + }; let cols = w.div_ceil(bs).max(1); let rows = h.div_ceil(bs).max(1); let mut flow = Flow { width: a.width, height: a.height, block: bs as u32, cols, rows, v: vec![[0.0; 2]; cols * rows] }; @@ -132,7 +179,7 @@ pub fn block_flow_window(a: &Image, b: &Image, tile: u32, window: u32, radius: i // Pyramids (level 0 = full resolution); stop while blocks still fit. let mut pa = vec![Plane::luma(a)]; let mut pb = vec![Plane::luma(b)]; - while pa.len() < 4 && pa.last().is_some_and(|p| p.w / 2 >= (bs as i64).max(win) as usize * 2 && p.h / 2 >= (bs as i64).max(win) as usize * 2) { + while pa.len() < 4 && pa.last().is_some_and(|p| p.w / 2 >= (fine as i64).max(win) as usize * 2 && p.h / 2 >= (fine as i64).max(win) as usize * 2) { let (na, nb) = (pa.last().map(Plane::half), pb.last().map(Plane::half)); pa.extend(na); pb.extend(nb); @@ -145,14 +192,14 @@ pub fn block_flow_window(a: &Image, b: &Image, tile: u32, window: u32, radius: i let k = 1i64 << level; // The block covers the tile's footprint at this level (at least 4 pixels). let lbs = (win / k).max(4); - let r = if level == top { radius as i64 } else { 1 }; + let r = if level == top { radius } else { 1 }; let prev = cur.clone(); cur = (0..cols * rows) .into_par_iter() .map(|i| { let (c, rr) = ((i % cols) as i64, (i / cols) as i64); - let bx = (c * bs as i64 + wo) / k; - let by = (rr * bs as i64 + wo) / k; + let bx = origin(c, w) / k; + let by = origin(rr, h) / k; // Candidates: this tile's and its neighbours' vectors from the coarser level. let mut seeds: Vec<[i64; 2]> = vec![[0, 0]]; if level != top { @@ -185,12 +232,11 @@ pub fn block_flow_window(a: &Image, b: &Image, tile: u32, window: u32, radius: i } // Sub-pixel refinement (parabola through the SAD of the neighbours) at full resolution. let (la, lb) = (&pa[0], &pb[0]); - let bsi = bs as i64; let wsi = win; let fine: Vec<[f32; 2]> = (0..cols * rows) .into_par_iter() .map(|i| { - let (bx, by) = ((i % cols) as i64 * bsi + wo, (i / cols) as i64 * bsi + wo); + let (bx, by) = (origin((i % cols) as i64, w), origin((i / cols) as i64, h)); let d = cur[i]; let e0 = sad(la, lb, bx, by, wsi, d[0], d[1]); let fit = |em: f32, ep: f32| { @@ -296,6 +342,19 @@ mod tests { s / n as f32 } + #[test] + fn a_fine_vector_grid_with_a_huge_window_is_made_coarser() { + // 8K frame, a vector per 2 px, a 512-px window and a 1024-px search: far past the budget. + let (t, r) = super::planned(7680, 4320, 2, 512, 1024); + assert!(t > 2 && t <= 4320 && super::search_work(7680, 4320, t, 2, 512, r) <= super::MAX_SEARCH_WORK, "{t} {r}"); + // The tile stays inside the frame, and the pyramid (search range) follows the requested tile. + let (t, _) = super::planned(7680, 4320, 2, 512, 710); + assert!(t <= 4320); + // Pixel Motion Blur's finest grid with its largest search keeps its grid on a 1080p frame. + assert_eq!(super::planned(1920, 1080, 2, 16, 64), (2, 64)); + assert_eq!(super::planned(1920, 1080, 8, 64, 4), (8, 4)); + } + #[test] fn a_huge_matching_window_is_held_to_the_cap() { let (a, b) = (texture(520, 520, 0.0), texture(520, 520, 2.0)); From 2b30f53e7a7b9b78c96c1f02340ff64286fce59b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:29:31 -0500 Subject: [PATCH 69/83] Export: Skip Existing keeps a frame already in the overflow folder * Export: Skip Existing keeps a frame already in the overflow folder * Export: Skip Existing checks every overflow folder before a frame is placed --- crates/export/src/lib.rs | 2 +- crates/export/src/pipeline.rs | 14 +++++++ crates/export/tests/it/render_settings.rs | 48 +++++++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs index 2687eadad..d9af7b2aa 100644 --- a/crates/export/src/lib.rs +++ b/crates/export/src/lib.rs @@ -321,7 +321,7 @@ async fn sequence(cx: &Cx<'_>, comp: &Comp, w: u32, h: u32, st: &mut State<'_>) let mut i = 0; while i < st.total { let end = (i + batch).min(st.total); - let ks: Vec = (i..end).filter(|k| !(cx.settings.skip_existing && out::exists(cx.sink, &sequence_path(cx.path, f0 + *k as i64)))).collect(); + let ks: Vec = (i..end).filter(|k| !(cx.settings.skip_existing && cx.frame_exists(&sequence_path(cx.path, f0 + *k as i64)))).collect(); let written: Vec> = cx .frames(comp, ks, |k, img| { let path = sequence_path(cx.path, f0 + k as i64); diff --git a/crates/export/src/pipeline.rs b/crates/export/src/pipeline.rs index d447e0980..a0e4980ec 100644 --- a/crates/export/src/pipeline.rs +++ b/crates/export/src/pipeline.rs @@ -894,6 +894,20 @@ impl<'a> Cx<'a> { } } + /// Whether Skip Existing finds `path` already written: at its own place or, with Use Storage + /// Overflow, in any overflow folder (checked before a frame is placed, so a skipped frame + /// reserves no quota). + pub fn frame_exists(&self, path: &str) -> bool { + if out::exists(self.sink, path) { + return true; + } + if !self.job.settings.storage_overflow { + return false; + } + let Some(name) = std::path::Path::new(path).file_name() else { return false }; + self.job.options.overflow.iter().any(|dir| out::exists(self.sink, &std::path::Path::new(dir).join(name).to_string_lossy())) + } + /// Where a file goes: `path`, or (Use Storage Overflow) the first overflow folder with room /// for `bytes` when the quota hook says the output volume is full. pub fn place(&self, path: &str, bytes: u64) -> String { diff --git a/crates/export/tests/it/render_settings.rs b/crates/export/tests/it/render_settings.rs index 99e3d9c19..ddad4336e 100644 --- a/crates/export/tests/it/render_settings.rs +++ b/crates/export/tests/it/render_settings.rs @@ -444,6 +444,54 @@ fn cancelled_export_removes_only_files_it_opened() { std::fs::remove_dir_all(dir).unwrap(); } +/// Skip Existing keeps a frame that is already in the overflow folder the frame is placed in +/// (it checked only the primary destination, then truncated the overflow file). +#[test] +fn skip_existing_keeps_a_frame_in_the_overflow_folder() { + use std::path::PathBuf; + // Room only in the second overflow folder; the frame already sits in the first (which is full). + struct Overflow(PathBuf); + impl StorageQuota for Overflow { + fn has_room(&self, path: &str, _: u64) -> bool { + std::path::Path::new(path).starts_with(&self.0) + } + } + let guard = tempfile::tempdir().unwrap(); + let (dir, full, over) = (guard.path().to_path_buf(), guard.path().join("full"), guard.path().join("over")); + std::fs::create_dir_all(&full).unwrap(); + std::fs::create_dir_all(&over).unwrap(); + std::fs::write(full.join("clip_00000.png"), b"keep").unwrap(); + let quota = Overflow(over.clone()); + let (p, cid) = project(FrameRate::new(25, 1), |_, _| {}); + let settings = RenderSettings { skip_existing: true, storage_overflow: true, ..Default::default() }; + let om = OutputModule::for_format(OutputFormat::PngSequence); + let path = dir.join("clip_[#####].png"); + let result = export( + &Job { + project: &p, + footage: &NoFootage, + expr: None, + accel: None, + comp: cid, + settings: &settings, + output: &om, + path: path.to_str().unwrap(), + sink: None, + nested_switches: true, + options: JobOptions { + storage: Some("a), + overflow: vec![full.to_string_lossy().into_owned(), over.to_string_lossy().into_owned()], + ..Default::default() + }, + }, + &mut |_| true, + ); + assert!(result.is_ok(), "{result:?}"); + assert_eq!(std::fs::read(full.join("clip_00000.png")).unwrap(), b"keep"); + assert!(!over.join("clip_00000.png").exists(), "no duplicate in another overflow folder"); + assert!(over.join("clip_00001.png").exists(), "the other frames are still written"); +} + /// A GPU compositor stand-in that renders every frame solid green (the CPU draws the bar and the /// block on black) and keeps Auto's timing history. #[derive(Default)] From 4d6036265b5bbdc9690a72fcabd4671e10b84580 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:29:38 -0500 Subject: [PATCH 70/83] Convert Expression to Keyframes: refuse layers of more than 2^18 frames * fix(engine): refuse to convert an expression on a layer of more than 2^18 frames * address review: refuse a non-positive frame duration; count a partial last frame; check every selected layer before converting * Convert Expression to Keyframes: cap at 2^20 frames (a 3-hour 60 fps comp is 648,000) --- crates/engine/src/cmd/prop.rs | 31 ++++++++++++++++++++++++++++- crates/engine/src/tests/timeline.rs | 25 +++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/prop.rs b/crates/engine/src/cmd/prop.rs index b23e73575..761a295b2 100644 --- a/crates/engine/src/cmd/prop.rs +++ b/crates/engine/src/cmd/prop.rs @@ -1370,6 +1370,13 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result { if sel.is_empty() { return Err(bad(CMD, "no `path` given and no selected property has an expression")); } + // Every layer is checked before the first is converted: a refusal leaves them all as they were. + let step = comp.frame_duration().0; + for (lid, _) in &sel { + if let Some(l) = comp.layer(*lid) { + check_convertible(step, l)?; + } + } let mut n = 0; for (lid, uid) in sel { n += convert_one_expr(s, cid, lid, uid)?.as_u64().unwrap_or(0); @@ -1380,14 +1387,36 @@ fn convert_expr_to_keys(s: &mut Session, p: &Value) -> Result { convert_one_expr(s, cid, lid, uid) } +/// Most keyframes Convert Expression to Keyframes makes: 2^20, 4.8 hours at 60 fps (After Effects +/// compositions run to 3 hours, 648,000 frames at 60 fps). +const MAX_CONVERTED_KEYS: u64 = 1 << 20; +const _: () = assert!(MAX_CONVERTED_KEYS >= 3 * 3600 * 60); + +/// One evaluation and one key per frame of the layer: its In and Out points and the composition's +/// frame duration are saved data, so the step must advance and the count (a partial last frame +/// rounded up, as the loop steps, in 128 bits) is checked before any key is made. +fn check_convertible(step: i64, layer: &Layer) -> Result<()> { + const CMD: &str = "prop.convertExpressionToKeyframes"; + if step <= 0 { + return Err(bad(CMD, "the composition's frame duration is not positive")); + } + let (step, span) = (i128::from(step), i128::from(layer.out_point.0) - i128::from(layer.in_point.0)); + let frames = if span > 0 { (span + step - 1) / step } else { 0 }; + if frames > i128::from(MAX_CONVERTED_KEYS) { + return Err(bad(CMD, format!("the layer spans {frames} frames; at most {MAX_CONVERTED_KEYS} are converted"))); + } + Ok(()) +} + /// Replaces the expression on one property with keyframes sampled from its evaluated values. /// Returns the number of properties converted. fn convert_one_expr(s: &mut Session, cid: ItemId, lid: LayerId, uid: Uid) -> Result { let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone(); let layer = comp.layer(lid).ok_or(EngineError::NoComp)?.clone(); let pr = layer.props.find(uid).ok_or_else(|| bad("prop.convertExpressionToKeyframes", "no property"))?.clone(); - let mut keys = vec![]; let fd = comp.frame_duration(); + check_convertible(fd.0, &layer)?; + let mut keys = vec![]; let mut t = layer.in_point; while t < layer.out_point { let ctx = effectcraft_render::EvalCtx { diff --git a/crates/engine/src/tests/timeline.rs b/crates/engine/src/tests/timeline.rs index b5a44239b..291ad884e 100644 --- a/crates/engine/src/tests/timeline.rs +++ b/crates/engine/src/tests/timeline.rs @@ -1581,3 +1581,28 @@ fn a_typed_component_moves_its_follow_components_by_each_layers_own_change() { let keys: Vec> = prop(&s, b, "audio/levels").keys.iter().map(|k| k.value.components()).collect(); assert_eq!(keys, vec![vec![-20.0, -30.0], vec![-4.0, -34.0]], "B's 1 s key rises 6 dB on both channels"); } + +#[test] +fn convert_expression_to_keyframes_refuses_a_layer_of_millions_of_frames() { + let (mut s, l) = setup(); + s.execute("prop.setExpression", json!({"layer": l, "path": "transform/rotation", "expression": "value"})).unwrap(); + // A saved Out point a million seconds after the In point. + let cid = s.active_comp_id().unwrap(); + std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(effectcraft_project::LayerId(l)).unwrap().out_point = + effectcraft_time::Tick::from_seconds_f64(1e6); + let e = s.execute("prop.convertExpressionToKeyframes", json!({"layer": l, "path": "transform/rotation"})).unwrap_err().to_string(); + assert!(e.contains("at most"), "{e}"); + assert!(prop(&s, l, "transform/rotation").keys.is_empty()); +} + +#[test] +fn convert_expression_to_keyframes_refuses_a_zero_frame_duration() { + let (mut s, l) = setup(); + s.execute("prop.setExpression", json!({"layer": l, "path": "transform/rotation", "expression": "value"})).unwrap(); + // A saved frame rate of 0/1 s has a frame duration of 0: the sampling loop never advanced. + let cid = s.active_comp_id().unwrap(); + std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().frame_rate.den = 0; + let e = s.execute("prop.convertExpressionToKeyframes", json!({"layer": l, "path": "transform/rotation"})).unwrap_err().to_string(); + assert!(e.contains("frame duration"), "{e}"); + assert!(prop(&s, l, "transform/rotation").keys.is_empty()); +} From a287044644fa917b8bb36a4495d80522817698f5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:29:46 -0500 Subject: [PATCH 71/83] Media: check still, EXR channel, GIF and WebP canvas sizes before allocating * fix(media): check still, EXR channel, GIF and WebP canvas sizes before allocating * address review: GIF frame allocation limit, lower wasm32 still limit, no EXR fallback after a size-limit error * address review: the 2^25-pixel still limit also applies on 32-bit native targets * Media: raise the still pixel limit to 2^28 (16384 x 16384) on 64-bit targets --- crates/media/src/gif_anim.rs | 38 ++++++++++++++++++++++++++- crates/media/src/pool.rs | 2 ++ crates/media/src/probe.rs | 49 +++++++++++++++++++++++++++++++++++ crates/media/src/webp_anim.rs | 21 +++++++++++++++ 4 files changed, 109 insertions(+), 1 deletion(-) diff --git a/crates/media/src/gif_anim.rs b/crates/media/src/gif_anim.rs index 09c0cda34..d201c8b7e 100644 --- a/crates/media/src/gif_anim.rs +++ b/crates/media/src/gif_anim.rs @@ -93,7 +93,18 @@ impl Anim { if crate::webp_anim::is_webp(bytes) { return crate::webp_anim::load(bytes); } - let dec = GifDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?; + let mut dec = GifDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?; + // A frame may be far larger than the canvas, and the decoder allocates its buffer before + // decoding it: no single buffer may pass what all the frames may hold. + let mut limits = image::Limits::no_limits(); + limits.max_alloc = Some(MAX_BYTES as u64); + image::ImageDecoder::set_limits(&mut dec, limits).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?; + // The decoder allocates the full logical canvas for the first frame, however small the + // frames themselves are: check it before decoding any. + let (w, h) = image::ImageDecoder::dimensions(&dec); + if u64::from(w) * u64::from(h) * 4 > MAX_BYTES as u64 { + return Err(MediaError::Unsupported(format!("GIF canvas of {w}×{h} is too large to hold in memory"))); + } let (mut frames, mut starts) = (Vec::new(), Vec::new()); let (mut at, mut size) = (0i64, 0usize); for frame in dec.into_frames() { @@ -179,6 +190,17 @@ mod tests { assert_eq!(colour_at(&pool, &f, 5.0), [0.0, 0.0, 1.0]); } + #[test] + fn a_frame_far_larger_than_the_canvas_is_refused_before_it_is_allocated() { + // A 1×1 canvas and a 20000×20000 frame (1.6 GB of RGBA); the data itself is not there. + let mut bytes = b"GIF89a".to_vec(); + // (a two-entry global colour table, so the frame gets as far as its buffer) + bytes.extend([1, 0, 1, 0, 0x80, 0, 0, 0, 0, 0, 255, 255, 255]); + bytes.extend([0x2c, 0, 0, 0, 0, 0x20, 0x4e, 0x20, 0x4e, 0, 2, 0]); + let e = crate::gif_anim::Anim::load(&bytes).err().expect("refused").to_string(); + assert!(e.to_lowercase().contains("memory"), "{e}"); + } + #[test] fn a_zero_delay_is_ten_hundredths_like_in_browsers() { let f = probe_bytes("a.gif", gif(&[(RED, 0), (GREEN, 1)]).into()).unwrap(); @@ -212,4 +234,18 @@ mod tests { assert!(pool.frame_at(&f, Tick::ZERO).is_err()); let _ = probe_bytes("a.gif", bytes.into()); } + + #[test] + fn a_huge_canvas_is_refused_before_decoding() { + // A 65535×65535 logical screen (16 GiB of RGBA) holding one 1×1 frame. + let mut out = Vec::new(); + { + let mut enc = gif::Encoder::new(&mut out, u16::MAX, u16::MAX, &[]).unwrap(); + for _ in 0..2 { + enc.write_frame(&gif::Frame::from_rgb(1, 1, &RED)).unwrap(); + } + } + let e = super::Anim::load(&out).err().unwrap(); + assert!(e.to_string().contains("too large"), "{e}"); + } } diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index e35ff37fc..872e4fdfa 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -1011,6 +1011,8 @@ impl Inner { crate::exr_channels::count_decode(false); match crate::probe::load_oriented(&bytes, crate::still_format(path, &bytes)) { Ok(img) => Ok(dynamic_to_image(&img, op)), + // Over the size limit: the layered fallback would allocate its planes anyway. + Err(e @ image::ImageError::Limits(_)) => Err(MediaError::Decode(format!("{path}: {e}"))), // A multi-layer OpenEXR file without an unnamed RGB layer: its colour layer. Err(e) => crate::exr_channels::layered_picture(path, bytes, &file, op, shared) .map_err(|why| MediaError::Decode(format!("{path}: {}", why.unwrap_or_else(|| e.to_string())))), diff --git a/crates/media/src/probe.rs b/crates/media/src/probe.rs index 2a734b7d5..194eebc47 100644 --- a/crates/media/src/probe.rs +++ b/crates/media/src/probe.rs @@ -9,6 +9,15 @@ use image::metadata::Orientation; use crate::{MediaError, Result, ext_of, rate_from_fc}; +/// Most pixels a still may decode to: 4 GiB as the renderer's float RGBA (2^28, 16384 × 16384; +/// 150-megapixel medium-format frames, stitched panoramas and large scans decode). A browser tab's +/// wasm32 heap can't hold one allocation that large (and the decoded input beside it): 512 MiB +/// there, and on 32-bit targets, where one allocation may not pass `isize::MAX` (2 GiB). +#[cfg(not(any(target_arch = "wasm32", target_pointer_width = "32")))] +pub(crate) const MAX_STILL_PIXELS: u64 = 1 << 28; +#[cfg(any(target_arch = "wasm32", target_pointer_width = "32"))] +pub(crate) const MAX_STILL_PIXELS: u64 = 1 << 25; + /// Frame rate given to image sequences on import (After Effects' default preference). pub const DEFAULT_SEQUENCE_RATE: FrameRate = FrameRate::FPS_30; @@ -305,6 +314,12 @@ pub(crate) fn load_oriented(bytes: &[u8], fmt: Option) -> im None => image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?, }; let mut dec = reader.into_decoder()?; + // `from_decoder` skips the reader's allocation limit, and some decoders (BMP) allocate + // whatever size their header claims: refuse a still the renderer could not hold as floats. + let (w, h) = dec.dimensions(); + if u64::from(w) * u64::from(h) > MAX_STILL_PIXELS { + return Err(image::ImageError::Limits(image::error::LimitError::from_kind(image::error::LimitErrorKind::DimensionError))); + } let orientation = dec.orientation().unwrap_or(Orientation::NoTransforms); let mut img = image::DynamicImage::from_decoder(dec)?; img.apply_orientation(orientation); @@ -378,6 +393,23 @@ fn averaged_rate(timescale: u32, durations: impl Iterator) -> Option mod tests { use super::*; + #[test] + fn a_still_larger_than_the_renderer_holds_is_refused_before_decoding() { + // A 24-bit BMP header claiming 20000×20000 pixels (within the BMP decoder's own limit) + // over no pixel data. + let mut bmp = b"BM".to_vec(); + bmp.extend(54u32.to_le_bytes()); + bmp.extend([0u8; 4]); + bmp.extend(54u32.to_le_bytes()); + bmp.extend(40u32.to_le_bytes()); + bmp.extend(20_000i32.to_le_bytes()); + bmp.extend(20_000i32.to_le_bytes()); + bmp.extend(1u16.to_le_bytes()); + bmp.extend(24u16.to_le_bytes()); + bmp.extend([0u8; 24]); + assert!(matches!(load_oriented(&bmp, Some(image::ImageFormat::Bmp)), Err(image::ImageError::Limits(_)))); + } + /// #2592: an encoder-delayed H.264 track's edit list shows 75 frames at 25 fps (3 s at a /// 1000 timescale), though its media runs a frame longer; empty edits and no edits leave it. #[test] @@ -469,4 +501,21 @@ mod tests { assert_eq!(averaged_rate(u32::MAX, [u32::MAX; 300].into_iter()), None); assert_eq!(video_rate(b"not a movie"), None); } + + /// A 150-megapixel still (a medium-format frame) is not refused for its size: only its (absent) + /// pixel data fails, not the dimension check. A still past the limit is. + #[cfg(not(any(target_arch = "wasm32", target_pointer_width = "32")))] + #[test] + fn stills_up_to_the_limit_pass_the_size_check() { + let bmp = |w: u32, h: u32| { + let mut b = vec![b'B', b'M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 40, 0, 0, 0]; + b.extend_from_slice(&w.to_le_bytes()); + b.extend_from_slice(&h.to_le_bytes()); + b.extend_from_slice(&[1, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + b + }; + let limit = |e: image::ImageError| matches!(e, image::ImageError::Limits(_)); + assert!(!load_oriented(&bmp(14_000, 10_800), None).err().is_some_and(limit), "150 MP passes the check"); + assert!(load_oriented(&bmp(20_000, 20_000), None).err().is_some_and(limit), "400 MP is refused"); + } } diff --git a/crates/media/src/webp_anim.rs b/crates/media/src/webp_anim.rs index 9420be1ed..f0784d1e3 100644 --- a/crates/media/src/webp_anim.rs +++ b/crates/media/src/webp_anim.rs @@ -157,6 +157,11 @@ pub(crate) fn load(bytes: &[u8]) -> Result { return Err(MediaError::Unsupported(format!("animated WebP of {} frames of {}×{} is too large to hold in memory", h.delays.len(), h.width, h.height))); } let dec = WebPDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("WebP: {e}")))?; + // The budget above used the canvas this file's header scan found; the decoder must agree, or + // a second VP8X header could make it allocate a far larger canvas. + if image::ImageDecoder::dimensions(&dec) != (h.width, h.height) { + return Err(MediaError::Decode("WebP: conflicting canvas sizes".into())); + } let (mut frames, mut delays, mut size) = (Vec::new(), Vec::new(), 0usize); for frame in dec.into_frames() { let frame = match frame { @@ -326,4 +331,20 @@ mod tests { let e = super::load(&bytes).err().unwrap(); assert!(e.to_string().contains("too large"), "{e}"); } + + #[test] + fn conflicting_canvas_headers_are_refused() { + // The first VP8X claims 16384×16384; a second one, which the header scan keeps, 1×1. + let mut bytes = webp(1, 1, &[(RED, 50); 2]); + bytes[24..27].copy_from_slice(&u24(16383)); + bytes[27..30].copy_from_slice(&u24(16383)); + let mut small = vec![0x12, 0, 0, 0]; + small.extend_from_slice(&u24(0)); + small.extend_from_slice(&u24(0)); + let second = chunk(b"VP8X", &small); + bytes.splice(30..30, second.iter().copied()); + let riff = u32::try_from(bytes.len() - 8).unwrap(); + bytes[4..8].copy_from_slice(&riff.to_le_bytes()); + assert!(super::load(&bytes).is_err()); + } } From 075aa03ebe33ab19aee291470e063de1d2159d66 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:29:56 -0500 Subject: [PATCH 72/83] Render: memoized audio detection, bounded stretch, preroll, waveform, cache entries, 3D bounds, solids and selector time * Render: memoized audio detection, bounded stretch, preroll, waveform, cache entries, 3D bounds, solids and selector time comp_has_audio walked a precomp again for every layer using it; each comp is answered once. A tiny stored stretch made one audio block fetch a vast source range; playback speed is capped at 100x. Effect preroll is capped at 10 s. Waveforms stop where the audio ends and summarise at most a day. Disk cache entries are decompressed only when their stated size matches what their dimensions need (and at most 1 GiB). Advanced 3D triangle bounds are clamped on both sides before narrowing. Solids larger than 16 Mpx are made at a lower scale. A camera-facing layer's parent recursion is bounded. A layer's Expression Selectors share one time allowance. A disk cache folder under the temp folder is made private and may not be a link. * address review: audio detection by breadth-first search, private cache folder resolved before the temp check, oversized layers not written, solid cap after rounding, selector static amount, viewport i32 clamp * address review: private-folder check skips the temp folder itself; override value in expression fallback; assert alias cache opens * address review: refuse the shared temp folder itself as a disk cache folder * address review: shared counted selector budget, 30 s preroll, cache hardening (shared temp roots, matte discard, exact LZ4 length, render version 7), orient nesting guard --- crates/render/src/audio.rs | 105 ++++++++++++--- crates/render/src/disk_cache.rs | 171 ++++++++++++++++++++++-- crates/render/src/eval.rs | 2 +- crates/render/src/pipeline.rs | 28 +++- crates/render/src/tests.rs | 14 ++ crates/render/src/text.rs | 59 +++++++- crates/render/src/text/tests.rs | 9 ++ crates/render/src/three_d/adv/raster.rs | 11 +- crates/render/src/three_d/camera.rs | 28 +++- 9 files changed, 383 insertions(+), 44 deletions(-) diff --git a/crates/render/src/audio.rs b/crates/render/src/audio.rs index 00342847d..2c1538133 100644 --- a/crates/render/src/audio.rs +++ b/crates/render/src/audio.rs @@ -24,6 +24,15 @@ use crate::{EvalCtx, ExprHost, FootageSource}; const MAX_DEPTH: usize = 16; +/// The fastest a layer's audio plays (a Stretch of 1%). +const MAX_SPEED: f64 = 100.0; + +/// The most effect preroll (history before a block) mixed, in seconds, across a layer's effects. +const MAX_PREROLL_SECONDS: f64 = 30.0; + +/// The longest footage a waveform summarises (a day). +const MAX_PEAK_SECONDS: i64 = 24 * 3600; + /// `frames` stereo sample frames of `comp`'s mix from comp time `start` at `rate` Hz, /// interleaved (L R L R …). pub fn mix_comp(project: &Project, footage: &dyn FootageSource, expr: Option<&dyn ExprHost>, comp: ItemId, start: Tick, frames: usize, rate: u32) -> Vec { @@ -35,22 +44,29 @@ pub fn mix_comp(project: &Project, footage: &dyn FootageSource, expr: Option<&dy /// Whether the comp has anything audible (footage with audio, a sound generator, or a precomp /// that has). pub fn comp_has_audio(project: &Project, comp: ItemId) -> bool { - fn walk(project: &Project, comp: ItemId, depth: usize) -> bool { - let Some(c) = project.comp(comp) else { return false }; - depth < MAX_DEPTH - && c.layers.iter().any(|l| { - l.switches.audio - && (generates(l) - || match &l.source { - LayerSource::Footage { item } => { - matches!(project.item(*item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if f.has_audio && !f.missing) - } - LayerSource::Comp { item } => walk(project, *item, depth + 1), - _ => false, - }) - }) + // Breadth first, so each comp is looked at once and at its shallowest level: a comp reached + // first through a long chain (past MAX_DEPTH) is still found by a shorter route, and a cycle + // cannot hide a result (nothing is cached as "silent" while it is being explored). + let mut seen = std::collections::HashSet::from([comp]); + let mut level = vec![comp]; + for _ in 0..MAX_DEPTH { + let mut next = vec![]; + for id in level { + let Some(c) = project.comp(id) else { continue }; + for l in c.layers.iter().filter(|l| l.switches.audio) { + match &l.source { + _ if generates(l) => return true, + LayerSource::Footage { item } if matches!(project.item(*item).map(|i| &i.kind), Some(ItemKind::Footage(f)) if f.has_audio && !f.missing) => { + return true; + } + LayerSource::Comp { item } if seen.insert(*item) => next.push(*item), + _ => {} + } + } + } + level = next; } - walk(project, comp, 0) + false } /// Enabled audio effects of a layer (in stack order) with their effect ids. @@ -157,7 +173,7 @@ impl MixEnv<'_> { let m = b - a; // Within ±1 % to ±9900 % (#3247): a stretch of 1e-300 % set in memory read about // usize::MAX source samples for one block. - let speed = 100.0 / l.effective_stretch(); + let speed = (100.0 / l.effective_stretch()).min(MAX_SPEED); let src_n = ((m as f64 * speed).ceil() as usize).max(1); let lt = l.layer_time(sample_tick(i0 + a as i64, rate)); let buf = match &l.source { @@ -213,7 +229,7 @@ impl MixEnv<'_> { return self.layer_raw(l, i0, n, false); } let reversed = fx.iter().any(|(id, _, _)| audio_fx::reverses(id)); - let pre_s: f64 = fx.iter().map(|(id, _, p)| audio_fx::preroll(id, p)).sum(); + let pre_s: f64 = fx.iter().map(|(id, _, p)| audio_fx::preroll(id, p)).sum::().clamp(0.0, MAX_PREROLL_SECONDS); let pre = (pre_s * self.rate as f64).ceil() as usize; let b0 = i0 - pre as i64; let mut buf = self.layer_raw(l, b0, n + pre, reversed); @@ -342,12 +358,14 @@ pub fn footage_peaks(footage: &dyn FootageSource, item: ItemId, f: &effectcraft_ let bin = (64usize).max(4000 / bins_per_sec as usize); let rate = bin as u32 * bins_per_sec; let chunk = bin * bins_per_sec as usize; - let total = units_ceil(duration, rate).max(0) as usize; + // The stated duration comes from the project: at most a day is summarised, and the summary + // ends where the audio does. + let total = units_ceil(duration, rate).clamp(0, MAX_PEAK_SECONDS.saturating_mul(rate as i64)) as usize; let mut out = Vec::with_capacity(total / bin + 1); let mut i = 0usize; while i < total { let n = chunk.min(total - i); - let buf = footage.audio(item, f, sample_tick(i as i64, rate), n, rate).unwrap_or_else(|| vec![0.0; n * 2]); + let Some(buf) = footage.audio(item, f, sample_tick(i as i64, rate), n, rate) else { break }; out.extend(peak_summary(&buf, bin)); i += n; } @@ -375,6 +393,55 @@ mod tests { } } + #[test] + fn audio_detection_answers_each_comp_once() { + // Twenty levels, each comp holding two layers of the one below: 2^20 walks without a + // memo, and all silent. A cycle is answered too. + let mut p = Project::default(); + let mk = |p: &mut Project, layers: Vec| { + let mut c = Comp::new(8, 8, FrameRate::new(25, 1), Tick::from_seconds_f64(1.0)); + c.layers = layers.into(); + p.add_item("C", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(c.into())) + }; + let base = Comp::new(8, 8, FrameRate::new(25, 1), Tick::from_seconds_f64(1.0)); + let mut below = mk(&mut p, vec![]); + for _ in 0..20 { + let a = build::layer(&mut p, &base, "a", LayerSource::Comp { item: below }, (0, 0), None); + let b = build::layer(&mut p, &base, "b", LayerSource::Comp { item: below }, (0, 0), None); + below = mk(&mut p, vec![a, b]); + } + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || tx.send(comp_has_audio(&p, below)).ok()); + assert!(!rx.recv_timeout(std::time::Duration::from_secs(20)).expect("detection finishes")); + } + + #[test] + fn audio_found_by_a_short_route_is_not_hidden_by_a_deep_one() { + let mut p = Project::default(); + let base = Comp::new(8, 8, FrameRate::new(25, 1), Tick::from_seconds_f64(1.0)); + let mk = |p: &mut Project, layers: Vec| { + let mut c = base.clone(); + c.layers = layers.into(); + p.add_item("C", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(c.into())) + }; + let f = Footage { kind: FootageKind::Audio, has_audio: true, ..Default::default() }; + let fid = p.add_item("x.wav", effectcraft_color::Label::SeaFoam, None, ItemKind::Footage(f)); + let sound = build::layer(&mut p, &base, "s", LayerSource::Footage { item: fid }, (0, 0), None); + let audible = mk(&mut p, vec![sound]); + // A chain of MAX_DEPTH comps ends in `audible` one level past what is searched; the root + // reaches `audible` directly as well, after the chain. + let mut chain = audible; + for _ in 0..MAX_DEPTH { + let l = build::layer(&mut p, &base, "c", LayerSource::Comp { item: chain }, (0, 0), None); + chain = mk(&mut p, vec![l]); + } + assert!(!comp_has_audio(&p, chain), "too deep to be found"); + let via_chain = build::layer(&mut p, &base, "chain", LayerSource::Comp { item: chain }, (0, 0), None); + let direct = build::layer(&mut p, &base, "direct", LayerSource::Comp { item: audible }, (0, 0), None); + let root = mk(&mut p, vec![via_chain, direct]); + assert!(comp_has_audio(&p, root)); + } + #[test] fn mixes_layers_with_levels_and_in_out() { let mut p = Project::default(); diff --git a/crates/render/src/disk_cache.rs b/crates/render/src/disk_cache.rs index 5c34348fe..3674b2667 100644 --- a/crates/render/src/disk_cache.rs +++ b/crates/render/src/disk_cache.rs @@ -483,12 +483,54 @@ pub fn default_folder() -> PathBuf { if let Some(x) = std::env::var_os("XDG_CACHE_HOME") { return PathBuf::from(x).join("effectcraft/disk-cache"); } - home.map(|h| h.join(".cache/effectcraft/disk-cache")).unwrap_or_else(|| std::env::temp_dir().join("effectcraft-disk-cache")) + // Without a home folder: a per-user folder in the shared temp folder, made private by `open`. + let user = std::env::var("USER").or_else(|_| std::env::var("USERNAME")).unwrap_or_default(); + home.map(|h| h.join(".cache/effectcraft/disk-cache")).unwrap_or_else(|| std::env::temp_dir().join(format!("effectcraft-disk-cache-{user}"))) +} + +/// A cache folder in the shared temp folder must be ours alone: not a link someone placed there, +/// and private (setting the mode fails unless we own it), so another user cannot redirect the +/// cache's writes and clean-up or read its files. +#[cfg(unix)] +fn make_private(folder: &Path) -> std::io::Result<()> { + use std::os::unix::fs::PermissionsExt; + // Judge the folder as written and as it resolves (a relative path, a link or an alias such as + // /tmp -> /private/tmp can all land in the shared temp folder). + // The shared roots: the process's temp folder (`TMPDIR`) and the system's own, which a cache + // configured by path lands in whatever `TMPDIR` says. + let roots: Vec = [std::env::temp_dir(), PathBuf::from("/tmp"), PathBuf::from("/var/tmp")] + .into_iter() + .flat_map(|t| { + let real = t.canonicalize().unwrap_or_else(|_| t.clone()); + [t, real] + }) + .collect(); + let given = std::path::absolute(folder).unwrap_or_else(|_| folder.to_path_buf()); + let real = folder.canonicalize().unwrap_or_else(|_| given.clone()); + // The shared folder itself is not ours to change or to keep a cache in: refused. + if [&given, &real].iter().any(|p| roots.contains(p)) { + return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "the disk cache folder is the shared temp folder")); + } + // Only folders inside it are made private. + if ![&given, &real].iter().any(|p| roots.iter().any(|t| p.starts_with(t) && **p != *t)) { + return Ok(()); + } + if std::fs::symlink_metadata(folder)?.file_type().is_symlink() { + return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "the disk cache folder is a link")); + } + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o700)) +} + +#[cfg(not(unix))] +fn make_private(_: &Path) -> std::io::Result<()> { + Ok(()) } impl DiskCache { /// Open (or create) the cache in `folder`, holding at most `max_bytes`. pub fn open(folder: impl AsRef, max_bytes: u64) -> std::io::Result> { + std::fs::create_dir_all(folder.as_ref())?; + make_private(folder.as_ref())?; let dir = folder.as_ref().join(VERSION); std::fs::create_dir_all(&dir)?; let dc = Arc::new(DiskCache { @@ -1145,8 +1187,9 @@ impl DiskCache { /// started at. /// The buffer is shared, and encoded on the writer thread. pub fn put_layer(&self, key: u128, buf: &Arc, files: &EntryFiles, since: u64) { - // (no room on the disk: refused before the buffer is queued and compressed) - if self.contains(Kind::Layer, key) || !self.accepts_writes() { + // (no room on the disk, or a buffer no entry could hold: refused before it is queued and + // compressed) + if !layer_fits(buf.img.data.len()) || self.contains(Kind::Layer, key) || !self.accepts_writes() { return; } self.count_encode(); @@ -1155,6 +1198,9 @@ impl DiskCache { /// Write a layer buffer synchronously (tests); a list that can't be stored is not. pub fn put_layer_now(&self, key: u128, buf: &Buf, files: &ReadFiles) { + if !layer_fits(buf.img.data.len()) { + return; + } if let Some(files) = EntryFiles::of(files, None) { self.write_format(Kind::Layer, key, FORMAT_LAYER_FILES, &with_files(&files, encode_layer(buf))); } @@ -1163,8 +1209,12 @@ impl DiskCache { /// A segmentation (chain key, scale) written by [`DiskCache::put_seg`]. pub fn get_seg(&self, key: u64, scale: f64) -> Option { let p = self.read(Kind::Matte, seg_key(key, scale))?; - let raw = lz4_flex::decompress_size_prepended(&p).ok()?; - effectcraft_effects::roto::FrameSeg::from_bytes(&raw) + let seg = decompress_checked(&p, None).and_then(|raw| effectcraft_effects::roto::FrameSeg::from_bytes(&raw)); + if seg.is_none() { + // A rejected entry would otherwise stay indexed and keep `put_seg` from replacing it. + self.discard(Kind::Matte, seg_key(key, scale)); + } + seg } /// Queue a segmentation for writing. @@ -1403,16 +1453,38 @@ fn encode_frame(w: u32, h: u32, rgba: &[u8]) -> Vec { out } +/// The most bytes one cache entry decompresses to (a 16384² frame of 8-bit RGBA): the size an +/// entry states is checked against it, and against what the entry's dimensions need, before +/// anything is allocated. +const MAX_ENTRY_BYTES: usize = 1 << 30; + +/// An LZ4 payload with its stated size prepended, decompressed only when that size is +/// `expected` (any size up to [`MAX_ENTRY_BYTES`] when `None`). +fn decompress_checked(p: &[u8], expected: Option) -> Option> { + let size = u32::from_le_bytes(p.get(..4)?.try_into().ok()?) as usize; + if size > MAX_ENTRY_BYTES || expected.is_some_and(|e| e != size) { + return None; + } + // A block that ends short of the size it states is damaged: callers index by that size. + lz4_flex::decompress(p.get(4..)?, size).ok().filter(|raw| raw.len() == size) +} + fn decode_frame(p: &[u8]) -> Option { if p.len() < 8 { return None; } let w = u32::from_le_bytes(p[0..4].try_into().ok()?); let h = u32::from_le_bytes(p[4..8].try_into().ok()?); - let rgba = lz4_flex::decompress_size_prepended(&p[8..]).ok()?; + let rgba = decompress_checked(&p[8..], Some((w as usize).checked_mul(h as usize)?.checked_mul(4)?))?; (rgba.len() == w as usize * h as usize * 4).then_some(Frame8 { width: w, height: h, rgba }) } +/// Whether a layer of `pixels` pixels (16 bytes each, decompressed) is within what a cache entry +/// may hold: a larger one could never be read back, so it is not compressed or written. +fn layer_fits(pixels: usize) -> bool { + pixels.checked_mul(16).is_some_and(|b| b <= MAX_ENTRY_BYTES) +} + /// Half floats with their low and high bytes in planes (per channel), then LZ4: the high bytes /// (sign, exponent) repeat a lot, mixed with the low ones LZ4 finds little. fn encode_frame_f16(w: u32, h: u32, rgba: &[u16]) -> Vec { @@ -1440,10 +1512,7 @@ fn decode_frame_f16(p: &[u8]) -> Option { let w = u32::from_le_bytes(p[0..4].try_into().ok()?); let h = u32::from_le_bytes(p[4..8].try_into().ok()?); let n = (w as usize).checked_mul(h as usize)?; - let planes = lz4_flex::decompress_size_prepended(&p[8..]).ok()?; - if planes.len() != n.checked_mul(8)? { - return None; - } + let planes = decompress_checked(&p[8..], Some(n.checked_mul(8)?))?; let mut rgba = vec![0u16; n * 4]; for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { for (c, v) in px.iter_mut().enumerate() { @@ -1486,9 +1555,9 @@ fn decode_layer(p: &[u8]) -> Option { let f = |i: usize| -> Option { Some(f64::from_le_bytes(p[i..i + 8].try_into().ok()?)) }; let offset = [f(8)?, f(16)?]; let scale = f(24)?; - let planes = lz4_flex::decompress_size_prepended(&p[32..]).ok()?; let n = (w as usize).checked_mul(h as usize)?; - if planes.len() != n.checked_mul(16)? { + let planes = decompress_checked(&p[32..], Some(n.checked_mul(16)?))?; + if planes.len() != n * 16 { return None; } let mut img = Image::new(w, h); @@ -1507,7 +1576,7 @@ fn decode_layer(p: &[u8]) -> Option { // ---------------------------------------------------------------- content keys /// Bump when rendering changes in a way that makes old disk entries wrong. -const RENDER_VERSION: &str = "effectcraft-render-6"; +const RENDER_VERSION: &str = "effectcraft-render-7"; /// Feeds the `Debug` form of `v` into the hash, followed by a separator byte. fn hash_debug(h: &mut Hash128, v: &impl std::fmt::Debug) { @@ -1619,6 +1688,82 @@ pub fn frame_key(content: u128, frame: i64, scale_milli: u32, view: u64) -> u128 mod tests { use super::*; + #[cfg(unix)] + #[test] + fn a_cache_folder_in_the_temp_folder_is_made_private_and_never_a_link() { + use std::os::unix::fs::PermissionsExt; + let d = tmpdir("private"); + let dc = DiskCache::open(&d, 1 << 20).unwrap(); + assert_eq!(std::fs::metadata(&d).unwrap().permissions().mode() & 0o777, 0o700); + drop(dc); + let link = tmpdir("link-private-temp"); + std::os::unix::fs::symlink(&d, &link).unwrap(); + assert!(DiskCache::open(&link, 1 << 20).is_err()); + let _ = std::fs::remove_file(&link); + let _ = std::fs::remove_dir_all(&d); + } + + #[cfg(unix)] + #[test] + fn the_shared_temp_folder_itself_is_refused_as_a_cache_folder() { + let tmp = std::env::temp_dir(); + assert!(DiskCache::open(&tmp, 1 << 20).is_err()); + } + + #[cfg(unix)] + #[test] + fn a_folder_that_resolves_into_the_temp_folder_is_made_private() { + use std::os::unix::fs::PermissionsExt; + // `/link` names a folder in the temp folder only through the link. + let real = tmpdir("alias-real"); + std::fs::create_dir_all(&real).unwrap(); + let link = std::env::current_dir().unwrap().join(format!("effectcraft-alias-link-{}", std::process::id())); + let _ = std::fs::remove_file(&link); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let dc = DiskCache::open(link.join("cache"), 1 << 20).unwrap(); + let mode = std::fs::metadata(real.join("cache")).map(|m| m.permissions().mode() & 0o777); + drop(dc); + let _ = std::fs::remove_file(&link); + let _ = std::fs::remove_dir_all(&real); + assert_eq!(mode.unwrap(), 0o700); + } + + #[test] + fn layers_too_big_to_read_back_are_not_written() { + assert!(layer_fits(MAX_ENTRY_BYTES / 16)); + assert!(!layer_fits(MAX_ENTRY_BYTES / 16 + 1)); + assert!(!layer_fits(10_000 * 10_000)); + assert!(!layer_fits(usize::MAX)); + } + + #[test] + fn an_entry_stating_a_size_its_dimensions_do_not_need_is_not_decompressed() { + // A 2×2 frame whose payload states 3 GiB: refused before any allocation. + let mut p = 2u32.to_le_bytes().to_vec(); + p.extend_from_slice(&2u32.to_le_bytes()); + p.extend_from_slice(&(3u32 << 30).to_le_bytes()); + p.extend_from_slice(&[0; 16]); + assert!(decode_frame(&p).is_none()); + assert!(decompress_checked(&p[8..], None).is_none()); + // A well-formed entry still decodes. + let ok = encode_frame(2, 2, &[7; 16]); + assert_eq!(decode_frame(&ok).map(|f| f.rgba), Some(vec![7; 16])); + } + + #[test] + fn a_block_shorter_than_the_size_it_states_is_rejected() { + // The payload states 100 bytes but holds a valid block of 10: `lz4_flex` returns the 10. + let mut p = 100u32.to_le_bytes().to_vec(); + p.extend_from_slice(&lz4_flex::block::compress(&[5u8; 10])); + assert!(decompress_checked(&p, None).is_none()); + // A half-float frame whose planes come up short is refused, not indexed past. + let mut f16 = 2u32.to_le_bytes().to_vec(); + f16.extend_from_slice(&2u32.to_le_bytes()); + f16.extend_from_slice(&32u32.to_le_bytes()); + f16.extend_from_slice(&lz4_flex::block::compress(&[1u8; 8])); + assert!(decode_frame_f16(&f16).is_none()); + } + fn tmpdir(name: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("effectcraft-disk-cache-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); diff --git a/crates/render/src/eval.rs b/crates/render/src/eval.rs index 41e6132d3..a9abefb16 100644 --- a/crates/render/src/eval.rs +++ b/crates/render/src/eval.rs @@ -283,7 +283,7 @@ impl<'a> EvalCtx<'a> { } impl crate::PropertyOverride { - fn value(&self, layer: &Layer, prop: &Property, time: Tick) -> Value { + pub(crate) fn value(&self, layer: &Layer, prop: &Property, time: Tick) -> Value { if self.font { // A Font control merges only the font into the target text, as // `essential::with_overrides` does. diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 900a06e2a..c0f4c8dd9 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -56,6 +56,29 @@ pub struct MediaOverride { pub(crate) item: ItemId, } +/// The most pixels a solid layer's buffer holds (as the other layer buffers are held to). +const MAX_SOLID_PIXELS: f64 = 16.0e6; + +/// The scale and whole-pixel size of a `width`×`height` solid rendered at `scale`, lowered until +/// the rounded size (each side at least one pixel) is within [`MAX_SOLID_PIXELS`]. +pub(crate) fn solid_size(width: u32, height: u32, mut scale: f64) -> (f64, u32, u32) { + let size = |s: f64| (((width as f64 * s).ceil() as u32).max(1), ((height as f64 * s).ceil() as u32).max(1)); + // Rounding up leaves an elongated solid over the cap after one step; each step shrinks the + // overshoot geometrically, so a few are enough. + for i in 0..64 { + let (w, h) = size(scale); + let area = w as f64 * h as f64; + if area <= MAX_SOLID_PIXELS { + break; + } + // The first step is the exact area ratio; later ones undershoot a little so rounding up + // cannot leave the size stuck just over the cap. + scale *= (MAX_SOLID_PIXELS / area).sqrt() * if i == 0 { 1.0 } else { 0.99 }; + } + let (w, h) = size(scale); + (scale, w, h) +} + impl MediaOverride { /// A Media Replacement of `layer`'s footage by `item`. pub fn new(layer: LayerId, item: ItemId) -> Self { @@ -899,8 +922,9 @@ impl<'a> Renderer<'a> { match &layer.source { LayerSource::Solid { item } => { let ItemKind::Solid(sol) = &self.project.item(*item)?.kind else { return None }; - let w = ((sol.width as f64 * s).ceil() as u32).max(1); - let h = ((sol.height as f64 * s).ceil() as u32).max(1); + // One colour: a solid larger than MAX_SOLID_PIXELS is made at a lower scale (the + // buffer carries it) instead of allocating gigabytes for a uniform plane. + let (s, w, h) = solid_size(sol.width, sol.height, s); if layer.switches.adjustment { return Some(Buf { img: Image::filled(w, h, [1.0; 4]), offset: [0.0; 2], scale: s }); } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 4cfa35d0b..2d0f90ac5 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -2002,3 +2002,17 @@ fn a_copy_of_an_overridden_clip_is_not_served_the_keyed_clips_pixels() { assert_same(&render(&keyed, Some(&cache)), &render(&keyed, None), "the keyed clip's copy"); assert_same(&render(&overridden, Some(&cache)), &render(&overridden, None), "the overridden clip's copy"); } + +#[test] +fn elongated_solids_stay_within_the_pixel_cap_after_rounding() { + use crate::pipeline::solid_size; + // 1 × 100 million at full scale: rounding up used to leave 40 million pixels. + for (w, h) in [(1u32, 100_000_000u32), (100_000_000, 1), (u32::MAX, u32::MAX), (1, u32::MAX)] { + let (s, pw, ph) = solid_size(w, h, 1.0); + assert!(s > 0.0 && f64::from(pw) * f64::from(ph) <= 16.0e6, "{w}x{h} -> {pw}x{ph} at {s}"); + } + // A solid within the cap keeps its scale; an over-cap square is lowered by the exact ratio. + assert_eq!(solid_size(4000, 4000, 1.0), (1.0, 4000, 4000)); + let (s, pw, ph) = solid_size(5000, 5000, 1.0); + assert!((s - 0.8).abs() < 0.01 && pw * ph <= 16_000_000); +} diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs index 1e95bbc11..eef5b4067 100644 --- a/crates/render/src/text.rs +++ b/crates/render/src/text.rs @@ -198,6 +198,35 @@ pub fn in_index_units(layer: &Layer, uid: effectcraft_project::Uid) -> bool { /// Selection of every glyph by an animator's selectors, per dimension. pub fn animator_selection(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, lay: &TextLayout) -> Vec<[f64; 3]> { + animator_selection_within(ctx, layer, anim, lay, &SelectorBudget::new()) +} + +/// The Expression Selector evaluations one layer's animators may run in all: counted, not timed, +/// so the same frame renders the same on every machine. +pub struct SelectorBudget(std::cell::Cell); + +impl SelectorBudget { + pub fn new() -> SelectorBudget { + SelectorBudget(std::cell::Cell::new(MAX_SELECTOR_EVALS)) + } + + /// Take one evaluation; `false` when none are left. + fn take(&self) -> bool { + let left = self.0.get(); + self.0.set(left.saturating_sub(1)); + left > 0 + } +} + +impl Default for SelectorBudget { + fn default() -> Self { + Self::new() + } +} + +/// [`animator_selection`] drawing its Expression Selector evaluations from `budget`, which the +/// caller shares across the layer's animators. +pub fn animator_selection_within(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, lay: &TextLayout, budget: &SelectorBudget) -> Vec<[f64; 3]> { let sels: Vec<&PropGroup> = anim.sub("selectors").map(|s| s.groups().filter(|g| g.enabled).collect()).unwrap_or_default(); if sels.is_empty() { // No selectors: every character is fully affected. @@ -250,13 +279,31 @@ pub fn animator_selection(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, lay: & { log.mark_unkeyed(); } - let stat = ctx.v3(layer, sel, "amount", [100.0; 3]); + // The keyframed amount, read without running its expression (the fallback when the + // expression cannot run); an Essential Property override still applies. + let stat = if prop.has_expression() { + // The expression is not run here, but an Essential Property override still wins over the base value. + match ctx.property_overrides.iter().rev().find(|o| o.layer == layer.id && o.prop == prop.uid) { + Some(o) => o.value(layer, prop, ctx.time), + None => prop.value_at(layer.layer_time(ctx.time)), + } + } else { + ctx.value(layer, prop) + } + .as_vec3(); + // One allowance for the whole layer (`budget`, shared by its animators): the + // expression runs per character, so a slow expression on a long text is stopped + // once it has failed or the layer's evaluations pass MAX_SELECTOR_EVALS. + let stopped = std::cell::Cell::new(false); Box::new(move |i, n, prev| { let pv = prev.map(|x| x * 100.0); // Without an expression engine: the static amount scales the selection. let fallback = [0, 1, 2].map(|d| stat[d] * prev[d]); - let r = match ctx.expr.filter(|_| prop.has_expression()) { - Some(h) => h.eval_text_selector(ctx, layer, prop, i, n, pv).unwrap_or(fallback), + let r = match ctx.expr.filter(|_| prop.has_expression() && !stopped.get() && budget.take()) { + Some(h) => h.eval_text_selector(ctx, layer, prop, i, n, pv).unwrap_or_else(|_| { + stopped.set(true); + fallback + }), None => fallback, }; r.map(|x| (x / 100.0).clamp(-1.0, 1.0)) @@ -282,13 +329,17 @@ pub fn animator_selection(ctx: &EvalCtx, layer: &Layer, anim: &PropGroup, lay: & acc } +/// The most Expression Selector evaluations one layer's animators run across all its characters +/// (a text of 32,768 characters under one expression selector, or fewer under several). +const MAX_SELECTOR_EVALS: usize = 32_768; /// Evaluate animators for every glyph. pub fn char_transforms(ctx: &EvalCtx, layer: &Layer, text: &PropGroup, lay: &TextLayout) -> Vec { let mut out = vec![CharXf::default(); lay.glyphs.len()]; let Some(anims) = text.sub("animators") else { return out }; + let budget = SelectorBudget::new(); for anim in anims.groups().filter(|g| g.enabled) { let Some(props) = anim.sub("properties") else { continue }; - let sel = animator_selection(ctx, layer, anim, lay); + let sel = animator_selection_within(ctx, layer, anim, lay, &budget); let get = |m: &str| props.get(m).map(|p| ctx.value(layer, p).components()); let get1 = |m: &str| props.get(m).map(|p| ctx.value(layer, p).as_f64()); let c3 = |v: Vec, d: f64| [v.first().copied().unwrap_or(d), v.get(1).copied().unwrap_or(d), v.get(2).copied().unwrap_or(d)]; diff --git a/crates/render/src/text/tests.rs b/crates/render/src/text/tests.rs index 9b52d3098..bbc1cd28e 100644 --- a/crates/render/src/text/tests.rs +++ b/crates/render/src/text/tests.rs @@ -802,3 +802,12 @@ fn text_notes_the_font_files_it_draws_with() { assert!(files.is_complete(), "{files:?}"); assert_eq!(files.get(&font.to_string_lossy()), Some(stamp), "{files:?}"); } + +#[test] +fn selector_evaluations_are_counted_across_the_layer_not_timed() { + let b = SelectorBudget(std::cell::Cell::new(3)); + // Taken by any animator's selectors in turn; the fourth finds none, and stays none. + assert!([b.take(), b.take(), b.take()].iter().all(|t| *t)); + assert!(!b.take() && !b.take()); + assert_eq!(SelectorBudget::new().0.get(), MAX_SELECTOR_EVALS); +} diff --git a/crates/render/src/three_d/adv/raster.rs b/crates/render/src/three_d/adv/raster.rs index 1c37a6267..f0d6028f9 100644 --- a/crates/render/src/three_d/adv/raster.rs +++ b/crates/render/src/three_d/adv/raster.rs @@ -126,11 +126,14 @@ fn setup(s: &Scene, clip: &[[f32; 4]], range: std::ops::Range) -> Vec= bbox[2] || bbox[1] >= bbox[3] { continue; diff --git a/crates/render/src/three_d/camera.rs b/crates/render/src/three_d/camera.rs index 6aee50a78..18f6dfe8a 100644 --- a/crates/render/src/three_d/camera.rs +++ b/crates/render/src/three_d/camera.rs @@ -302,6 +302,13 @@ pub fn auto_orient_2d(ctx: &EvalCtx, layer: &Layer) -> f64 { path_tangent(ctx, layer).map(|t| t.y.atan2(t.x).to_degrees()).unwrap_or(0.0) } +/// The most camera-facing layers whose parents are evaluated inside one another. +const MAX_ORIENT_NESTING: usize = 8; + +thread_local! { + static ORIENT_NESTING: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Whether `id` is `layer` or one of its parents. fn in_parent_chain(ctx: &EvalCtx, layer: &Layer, id: effectcraft_project::LayerId) -> bool { let mut cur = Some(layer); @@ -336,8 +343,27 @@ pub fn auto_orient_3d(ctx: &EvalCtx, layer: &Layer, pos: Vec3) -> Option { if ctx.comp.active_camera(ctx.time).is_some_and(|c| in_parent_chain(ctx, c, layer.id)) { return None; } + // The parent's world matrix evaluates the parent's own orientation: a parent cycle + // of camera-facing layers would recurse without end, and a chain of them is walked + // again from every link. Past MAX_ORIENT_NESTING the layer keeps its Orientation. + let nesting = ORIENT_NESTING.with(|n| n.get()); + if nesting >= MAX_ORIENT_NESTING { + return None; + } + // Restored when this scope ends, a panic unwinding through it included (the CPU retry + // after one must not start with a raised count). + struct Restore(usize); + impl Drop for Restore { + fn drop(&mut self) { + ORIENT_NESTING.with(|n| n.set(self.0)); + } + } + ORIENT_NESTING.with(|n| n.set(nesting + 1)); + let restore = Restore(nesting); + let parent = parent_world(ctx, layer); + drop(restore); let eye = active_camera(ctx).eye; - let e = parent_world(ctx, layer).inverse().unwrap_or(Mat4::IDENTITY).apply(eye); + let e = parent.inverse().unwrap_or(Mat4::IDENTITY).apply(eye); let d = pos - e; (d.length() > 1e-9).then(|| basis_rotation(d, vec3(0.0, 1.0, 0.0))) } From cb5bc81d2826095e8b298d147d543b24fa163a31 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:30:03 -0500 Subject: [PATCH 73/83] Automation: refuse Watch Folder and Edit Original while file access is confined * fix(automation): refuse Watch Folder and Edit Original while file access is confined --- crates/automation/src/confine.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/automation/src/confine.rs b/crates/automation/src/confine.rs index 0407ba756..dda0a406c 100644 --- a/crates/automation/src/confine.rs +++ b/crates/automation/src/confine.rs @@ -65,6 +65,8 @@ const REFUSED: &[&str] = &[ "file.revealInFinder", "layer.openSource", "help.revealLogFile", + // Hands the footage file to the platform's default application. + "edit.editOriginal", "file.autoSave", // The Plug-in Library downloads code, installs it to load at start-up and reads `file://` catalogs. "library.refresh", @@ -73,6 +75,10 @@ const REFUSED: &[&str] = &[ "library.uninstall", "library.loadInstalled", "library.preview", + // Watch Folder renders the projects it finds to the outputs they name and writes status + // files into the watched folder: neither is a path the agent gives, so neither is checked. + "file.watchFolder", + "file.watchFolder.poll", ]; /// Most numbered folders `check_render_folder` inspects for one output; more are refused. @@ -91,7 +97,6 @@ const READS: &[(&str, &[&str])] = &[ ("file.replaceFootage", &["path"]), ("file.relinkFootage", &["folder"]), ("file.setProxy", &["path"]), - ("file.watchFolder", &["folder"]), ("anim.applyPreset", &["path"]), ("anim.applyRecentPreset", &["path"]), ("keys.rpfCameraImport", &["path"]), @@ -105,7 +110,6 @@ const READS: &[(&str, &[&str])] = &[ // unchecked. ("essential.templateInfo", &["path"]), ("file.importProject", &["path"]), - ("file.watchFolder.poll", &["folder"]), ("footage.relink", &["path"]), ("layer.newModel", &["path"]), ("mediaBrowser.fileInfo", &["path"]), @@ -785,6 +789,16 @@ mod tests { assert!(read(&footage(&inside)).1.is_complete()); } + #[test] + fn watch_folder_and_edit_original_are_refused_while_confined() { + let dir = std::env::temp_dir(); + let c = Confinement::new(std::slice::from_ref(&dir), std::slice::from_ref(&dir)).unwrap(); + for id in ["file.watchFolder", "file.watchFolder.poll", "edit.editOriginal"] { + let e = c.check_command(id, &serde_json::json!({"folder": dir.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("not available while file access is confined"), "{id}: {e}"); + } + } + #[test] fn relative_and_outside_paths_of_newly_listed_commands_are_refused() { let base = std::env::temp_dir().join(format!("ec-confine-1243-{}", std::process::id())); From 740afc28691d78b2c505db35ed97e9864b57adda Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 06:30:20 -0500 Subject: [PATCH 74/83] FBX: records stay within their parent; textures, materials and links are indexed * fix(model): FBX records stay within their parent, and textures, materials and links are indexed A binary child record could end past its parent: the parent's end was then restored and the child's tail parsed again. A failed array decompression printed the decompressed bytes in the error. Texture objects aliasing one embedded Video or file each decoded and kept their own pixels, outside the import budget. Each polygon scanned the primitive groups for its material, and each object scanned every connection for its children. * address review: FBX textures: key image cache by the source used, charge decoded size before decoding, propagate budget errors * Import: a model's left-out parts reach the user as an import warning (Model::warnings, Importer::probe_noting) * Import: a model's left-out parts reach the user as an import warning * FBX: textures past the limits are left out with an import warning, not a failed import; 2^29-pixel allowance --- crates/model/src/fbx.rs | 160 ++++++++++++++++++++++++---------- crates/model/src/fbx/tests.rs | 109 +++++++++++++++++++++++ 2 files changed, 221 insertions(+), 48 deletions(-) diff --git a/crates/model/src/fbx.rs b/crates/model/src/fbx.rs index bca387ff2..4f952847c 100644 --- a/crates/model/src/fbx.rs +++ b/crates/model/src/fbx.rs @@ -36,6 +36,12 @@ const MAX_ARRAY_BYTES: usize = 1 << 30; /// wire type) plus the meshes built from them (#1234). const MAX_IMPORT_BYTES: usize = 1 << 31; +/// Most pixels one texture may hold (8192 × 8192) and all the textures of one import together +/// (2^29: 8 GiB as float RGBA, thirty-two 4K maps). A texture past a limit is left out and the +/// import says so. +const MAX_TEXTURE_PIXELS: u64 = 1 << 26; +const MAX_TEXTURE_IMPORT_PIXELS: u64 = 1 << 29; + /// What is left of an import's memory budget. struct Budget(std::cell::Cell); @@ -230,7 +236,7 @@ impl Bin<'_> { } let mut out = vec![]; while *pos < end { - match self.record(pos, depth)? { + match self.record(pos, end, depth)? { Some(n) => out.push(n), None => break, } @@ -238,8 +244,9 @@ impl Bin<'_> { Ok(out) } - /// One node record; `None` for the null record that closes a list. - fn record(&self, pos: &mut usize, depth: usize) -> Result> { + /// One node record ending within `limit` (the enclosing record's end); `None` for the null + /// record that closes a list. + fn record(&self, pos: &mut usize, limit: usize, depth: usize) -> Result> { let start = *pos; let end = Self::to_usize(self.offset(pos)?)?; let nprops = self.offset(pos)?; @@ -248,7 +255,9 @@ impl Bin<'_> { if end == 0 && nprops == 0 && plen == 0 && nlen == 0 { return Ok(None); } - if end <= start || end > self.d.len() { + // A child reaching past its parent would be parsed again once the parent's end is + // restored. + if end <= start || end > limit.min(self.d.len()) { return Err(perr(format!("FBX: bad record end {end} at byte {start}"))); } let name = String::from_utf8_lossy(self.take(pos, nlen)?).into_owned(); @@ -302,7 +311,8 @@ impl Bin<'_> { let data = sub.take(pos, clen)?; let raw = match enc { 0 => data.to_vec(), - 1 => miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, want).map_err(|e| perr(format!("FBX: array zlib: {e:?}")))?, + // The status only: the error's Debug form prints what was decompressed. + 1 => miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, want).map_err(|e| perr(format!("FBX: array zlib: {:?}", e.status)))?, e => return Err(perr(format!("FBX: unknown array encoding {e}"))), }; let raw = raw.get(..want).ok_or_else(|| perr("FBX: array shorter than its length"))?; @@ -334,7 +344,7 @@ fn read_binary(bytes: &[u8], budget: &Budget) -> Result<(u32, Vec)> { let bin = Bin { d: bytes, wide: version >= 7500, budget }; let mut nodes = vec![]; while pos < bytes.len() { - match bin.record(&mut pos, 0) { + match bin.record(&mut pos, bytes.len(), 0) { Ok(Some(n)) => nodes.push(n), Ok(None) => break, // A damaged tail (footer, padding) after complete sections is ignored. @@ -651,6 +661,7 @@ fn build_mesh(name: &str, geom: &FbxNode, materials: &[usize], with_normal_maps: type Key = (u32, [u32; 3], [u32; 2]); let mut prims: Vec<(Option, Primitive, HashMap, Vec)> = vec![]; + let mut prim_of: HashMap, usize> = HashMap::new(); let mut corners: Vec<(usize, usize)> = vec![]; let mut poly = 0usize; for (pv, &raw) in pvi.iter().enumerate() { @@ -671,13 +682,10 @@ fn build_mesh(name: &str, geom: &FbxNode, materials: &[usize], with_normal_maps: materials.get(usize::try_from(k).ok()?).copied() }); let slot = slot.or_else(|| materials.first().copied()); - let at = match prims.iter().position(|p| p.0 == slot) { - Some(i) => i, - None => { - prims.push((slot, Primitive { material: slot, ..Default::default() }, HashMap::new(), vec![])); - prims.len() - 1 - } - }; + let at = *prim_of.entry(slot).or_insert_with(|| { + prims.push((slot, Primitive { material: slot, ..Default::default() }, HashMap::new(), vec![])); + prims.len() - 1 + }); let Some((_, prim, map, need)) = prims.get_mut(at) else { continue }; let mut ids = Vec::with_capacity(poly_corners.len()); for &(pv, v) in &poly_corners { @@ -816,6 +824,12 @@ fn parse_within(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, limit: links.push((a, b, e.str_at(3))); } } + // The same links by parent, so each object finds its children without scanning them all. + let mut children_of: HashMap)>> = HashMap::new(); + for &(a, b, prop) in &links { + children_of.entry(b).or_default().push((a, prop)); + } + let children_of = |id: i64| children_of.get(&id).map(Vec::as_slice).unwrap_or_default().iter().copied(); let model_ids: Vec = objects.children.iter().filter(|o| o.name == "Model").filter_map(|o| o.prop(0)?.as_i64()).collect(); let mut node_of: HashMap = HashMap::new(); @@ -851,43 +865,91 @@ fn parse_within(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, limit: let mut textures: Vec> = vec![]; let mut material_of: HashMap = HashMap::new(); let mut texture_of: HashMap> = HashMap::new(); - let mut load_texture = |tid: i64, textures: &mut Vec>| -> Option { + // Decoded images by the source actually used (embedded Video id, else the resolved file + // name): Texture objects aliasing one image share its pixels instead of each keeping a copy. + let mut image_of: HashMap<(Option, String), Option> = HashMap::new(); + // Textures have their own allowance (pixels, as `Texture::decode_within` counts them); the + // memory budget is for the file's own records. + let mut texture_pixels_left = MAX_TEXTURE_IMPORT_PIXELS; + let mut warnings: Vec = vec![]; + // Ok(None): no usable image (the material goes untextured). Err: the memory budget ran out. + let mut load_texture = |tid: i64, textures: &mut Vec>| -> Result> { if let Some(t) = texture_of.get(&tid) { - return *t; + return Ok(*t); } - let t = (|| { - let tex = by_id.get(&tid)?; - let embedded = links.iter().filter(|l| l.1 == tid && kind(l.0) == Some("Video")).find_map(|l| { - let content = by_id.get(&l.0)?.child("Content")?; - match content.props.first()? { - Prop::Bytes(b) if !b.is_empty() => Some(b.clone()), - Prop::Str(_) => { - let s: String = content.props.iter().filter_map(Prop::as_str).collect(); - base64(&s).filter(|b| !b.is_empty()) - } - _ => None, + let Some(tex) = by_id.get(&tid) else { + texture_of.insert(tid, None); + return Ok(None); + }; + let videos: Vec = children_of(tid).filter(|l| kind(l.0) == Some("Video")).map(|l| l.0).collect(); + let files: Vec = ["RelativeFilename", "FileName"].iter().filter_map(|k| Some(tex.child(k)?.str_at(0)?.replace('\\', "/"))).collect(); + let embedded = videos.iter().find_map(|&v| { + let content = by_id.get(&v)?.child("Content")?; + let bytes = match content.props.first()? { + Prop::Bytes(b) if !b.is_empty() => Some(b.clone()), + Prop::Str(_) => { + let s: String = content.props.iter().filter_map(Prop::as_str).collect(); + base64(&s).filter(|b| !b.is_empty()) } - }); - let bytes = embedded.or_else(|| { - ["RelativeFilename", "FileName"].iter().find_map(|k| { - let f = tex.child(k)?.str_at(0)?.replace('\\', "/"); - resolve(&f).or_else(|| resolve(f.rsplit('/').next()?)) - }) - })?; - let t = Texture::decode(&bytes).ok()?; - textures.push(Arc::new(t)); - Some(textures.len() - 1) - })(); + _ => None, + }?; + Some(((Some(v), String::new()), bytes)) + }); + let source = embedded.or_else(|| { + files.iter().find_map(|f| { + let g = resolve(f).map(|b| (f.clone(), b)).or_else(|| { + let base = f.rsplit('/').next()?; + Some((base.to_string(), resolve(base)?)) + })?; + Some(((None, g.0), g.1)) + }) + }); + let t = match source { + None => None, + Some((key, bytes)) => match image_of.get(&key) { + Some(i) => *i, + None => { + // Charge the decoded size before decoding, so a small file claiming huge + // dimensions is refused before its pixels are allocated. A texture past the + // limits is left out (the material goes untextured) and the import says so. + let loaded = Texture::dimensions(&bytes).and_then(|(w, h)| { + let pixels = u64::from(w) * u64::from(h); + if pixels > MAX_TEXTURE_PIXELS { + return Err(perr(format!("a {w}×{h} texture (at most {MAX_TEXTURE_PIXELS} pixels)"))); + } + if pixels > texture_pixels_left { + return Err(perr(format!("a {w}×{h} texture: the model's textures would hold more than {MAX_TEXTURE_IMPORT_PIXELS} pixels"))); + } + let t = Texture::decode(&bytes)?; + texture_pixels_left -= pixels; + Ok(t) + }); + let i = match loaded { + Ok(t) => { + textures.push(Arc::new(t)); + Some(textures.len() - 1) + } + Err(e) => { + log::warn!("model: FBX texture left out: {e}"); + warnings.push(format!("texture left out: {e}")); + None + } + }; + image_of.insert(key, i); + i + } + }, + }; texture_of.insert(tid, t); - t + Ok(t) }; - let mut material_index = |mid: i64, materials: &mut Vec, textures: &mut Vec>| -> Option { + let mut material_index = |mid: i64, materials: &mut Vec, textures: &mut Vec>| -> Result> { if let Some(&m) = material_of.get(&mid) { - return Some(m); + return Ok(Some(m)); } - let node = by_id.get(&mid)?; + let Some(node) = by_id.get(&mid) else { return Ok(None) }; let mut m = material(short_name(node.str_at(1).unwrap_or("")), node); - for &(tid, _, prop) in links.iter().filter(|l| l.1 == mid && kind(l.0) == Some("Texture")) { + for (tid, prop) in children_of(mid).filter(|l| kind(l.0) == Some("Texture")) { let slot = match prop { Some("DiffuseColor") => &mut m.base_color_tex, Some("NormalMap") => &mut m.normal_tex, @@ -895,7 +957,7 @@ fn parse_within(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, limit: _ => continue, }; if slot.is_none() { - *slot = load_texture(tid, textures).map(|texture| TexRef { texture, uv_set: 0 }); + *slot = load_texture(tid, textures)?.map(|texture| TexRef { texture, uv_set: 0 }); } } if m.emissive_tex.is_some() && m.emissive == [0.0; 3] { @@ -903,7 +965,7 @@ fn parse_within(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, limit: } materials.push(m); material_of.insert(mid, materials.len() - 1); - Some(materials.len() - 1) + Ok(Some(materials.len() - 1)) }; // One mesh per Model with Mesh geometry (material slots are per Model). Models instancing the @@ -912,10 +974,12 @@ fn parse_within(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, limit: let mut mesh_of: HashMap<(i64, Vec), usize> = HashMap::new(); for &id in &model_ids { let Some(&ni) = node_of.get(&id) else { continue }; - let Some(gid) = links.iter().find(|l| l.1 == id && kind(l.0) == Some("Geometry")).map(|l| l.0) else { continue }; + let Some(gid) = children_of(id).find(|l| kind(l.0) == Some("Geometry")).map(|l| l.0) else { continue }; let Some(geom) = by_id.get(&gid) else { continue }; - let mats: Vec = - links.iter().filter(|l| l.1 == id && kind(l.0) == Some("Material")).filter_map(|l| material_index(l.0, &mut materials, &mut textures)).collect(); + let mut mats: Vec = vec![]; + for (mid, _) in children_of(id).filter(|l| kind(l.0) == Some("Material")) { + mats.extend(material_index(mid, &mut materials, &mut textures)?); + } let name = nodes.get(ni).map(|n| n.name.clone()).unwrap_or_default(); let mesh_index = match mesh_of.get(&(gid, mats.clone())) { Some(&i) => i, @@ -947,7 +1011,7 @@ fn parse_within(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, limit: if meshes.is_empty() { return Err(perr("FBX file without meshes")); } - Ok(Model { meshes, nodes, roots: vec![0], materials, textures, ..Model::default() }) + Ok(Model { meshes, nodes, roots: vec![0], materials, textures, warnings, ..Model::default() }) } #[cfg(test)] diff --git a/crates/model/src/fbx/tests.rs b/crates/model/src/fbx/tests.rs index 1ba1978ba..fcd34c4f0 100644 --- a/crates/model/src/fbx/tests.rs +++ b/crates/model/src/fbx/tests.rs @@ -409,3 +409,112 @@ fn fbx_models_instancing_one_geometry_share_its_mesh() { assert!(parse_within(instanced_scene().as_bytes(), &|_| None, values + 2 * mesh).is_ok()); assert!(parse_within(instanced_scene().as_bytes(), &|_| None, values + mesh).is_err()); } + +#[test] +fn binary_child_record_past_its_parent_is_an_error() { + let parent = FbxNode { name: "P".into(), props: vec![], children: vec![FbxNode { name: "C".into(), props: vec![], children: vec![] }] }; + let after = FbxNode { name: "Q".into(), props: vec![Prop::Int(1)], children: vec![] }; + let mut bin = write_binary(&[parent, after], 7400, false); + assert_eq!(read(&bin).unwrap().1.len(), 2); + // `P` starts after the magic and version; `C` after P's 12-byte header, name length and name. + let p = BINARY_MAGIC.len() + 4; + let p_end = u32::from_le_bytes(bin[p..p + 4].try_into().unwrap()); + let c = p + 14; + bin[c..c + 4].copy_from_slice(&(p_end + 1).to_le_bytes()); + assert!(read(&bin).unwrap_err().to_string().contains("bad record end")); +} + +#[test] +fn texture_aliases_of_one_image_share_its_pixels() { + let png = { + let img = image::RgbaImage::from_pixel(2, 1, image::Rgba([0, 255, 0, 255])); + let mut b = std::io::Cursor::new(vec![]); + img.write_to(&mut b, image::ImageFormat::Png).unwrap(); + b.into_inner() + }; + let objects = r#" + Texture: 600, "Texture::Base", "" { + RelativeFilename: "maps\base.png" + } + Texture: 700, "Texture::Base again", "" { + RelativeFilename: "maps\base.png" + } +} +Connections: {"#; + let doc = ASCII + .replace("}\nConnections: {", objects) + .replace("C: \"OO\",500,300\n", "C: \"OO\",500,300\n\tC: \"OP\",600,400, \"DiffuseColor\"\n\tC: \"OP\",700,500, \"DiffuseColor\"\n"); + let resolve = |uri: &str| (uri == "maps/base.png").then(|| png.clone()); + let m = parse(doc.as_bytes(), &resolve).unwrap(); + assert_eq!(m.textures.len(), 1); + assert!(m.materials.iter().all(|x| x.base_color_tex.map(|t| t.texture) == Some(0))); + // Textures have their own allowance: a tight record budget does not drop them. + let (_, nodes) = read(doc.as_bytes()).unwrap(); + let values = value_bytes(&nodes).unwrap(); + let mesh = mesh_bytes(&m.meshes[0]).unwrap(); + assert_eq!(parse_within(doc.as_bytes(), &resolve, values + mesh).unwrap().textures.len(), 1); + assert!(m.warnings.is_empty()); +} + +/// A PNG that is only a header claiming `w`×`h` pixels (an empty data chunk follows). +fn png_header_only(w: u32, h: u32) -> Vec { + fn chunk(png: &mut Vec, ty: &[u8], data: &[u8]) { + let body = [ty, data].concat(); + let mut crc = 0xFFFF_FFFFu32; + for &b in &body { + crc ^= u32::from(b); + for _ in 0..8 { + crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; + } + } + png.extend((data.len() as u32).to_be_bytes()); + png.extend(&body); + png.extend((!crc).to_be_bytes()); + } + let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; + chunk(&mut png, b"IHDR", &[w.to_be_bytes(), h.to_be_bytes(), [8, 6, 0, 0]].concat().iter().copied().chain([0]).collect::>()); + chunk(&mut png, b"IDAT", &[]); + png +} + +#[test] +fn a_texture_past_the_limits_is_left_out_with_a_warning_not_a_failed_import() { + let objects = r#" + Texture: 600, "Texture::Base", "" { + RelativeFilename: "maps\base.png" + } +} +Connections: {"#; + let doc = ASCII.replace("}\nConnections: {", objects).replace("C: \"OO\",500,300\n", "C: \"OO\",500,300\n\tC: \"OP\",600,400, \"DiffuseColor\"\n"); + // 30000×30000 pixels would take ~14 GiB; the header alone is refused, before anything is allocated. + let huge = png_header_only(30000, 30000); + let resolve = |_: &str| Some(huge.clone()); + let m = parse(doc.as_bytes(), &resolve).unwrap(); + assert!(m.textures.is_empty() && m.materials.iter().all(|x| x.base_color_tex.is_none())); + assert!(m.warnings.iter().any(|w| w.contains("30000")), "{:?}", m.warnings); +} + +#[test] +fn texture_files_resolving_to_one_image_share_it() { + let png = { + let img = image::RgbaImage::from_pixel(2, 1, image::Rgba([0, 255, 0, 255])); + let mut b = std::io::Cursor::new(vec![]); + img.write_to(&mut b, image::ImageFormat::Png).unwrap(); + b.into_inner() + }; + let objects = r#" + Texture: 600, "Texture::Base", "" { + RelativeFilename: "maps\base.png" + } + Texture: 700, "Texture::Other spelling", "" { + RelativeFilename: "missing\base.png" + FileName: "maps\base.png" + } +} +Connections: {"#; + let doc = ASCII + .replace("}\nConnections: {", objects) + .replace("C: \"OO\",500,300\n", "C: \"OO\",500,300\n\tC: \"OP\",600,400, \"DiffuseColor\"\n\tC: \"OP\",700,500, \"DiffuseColor\"\n"); + let resolve = |uri: &str| (uri == "maps/base.png").then(|| png.clone()); + assert_eq!(parse(doc.as_bytes(), &resolve).unwrap().textures.len(), 1); +} From 63fda85a512f20023b473c53aa858e15ee12c01b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 07:00:15 -0500 Subject: [PATCH 75/83] 3D models: bound and share decoded textures, share skin matrices, index OBJ materials * fix(model): share decoded textures and skin matrices, bound texture pixels, index OBJ materials Texture::decode expanded any image to float RGBA without a size check. Repeated mtllib lines reparsed the library and decoded its textures again; glTF textures with a non-default sampler each copied their image's pixels; every instance of a skin built its own joint matrices. OBJ usemtl and faces scanned the growing material and primitive lists, and contour grouping kept every ancestor of every contour. * address review: keep largest contours and dedupe mtllib by set * address review: contour depth counts containers, glTF wrap copies and FBX textures share the import pixel budget * address review: holes go to the innermost outline; glTF wrap variants keyed by decoded image * address review: create every outline slot before attaching holes * Import: a model's left-out parts reach the user as an import warning (Model::warnings, Importer::probe_noting) * Models: left-out textures are import warnings; the import texture budget is 2^29 pixels * Import: a model's left-out parts reach the user as an import warning (Model::warnings, Importer::probe_noting) * Import: a model's left-out parts reach the user as an import warning * FBX textures move to #2955 (it reworks the same code) --- crates/model/src/extrude.rs | 62 ++++++++++++--- crates/model/src/gltf.rs | 85 ++++++++++++++++---- crates/model/src/lib.rs | 51 +++++++++--- crates/model/src/obj.rs | 66 +++++++++++----- crates/model/src/tests.rs | 151 ++++++++++++++++++++++++++++++++++++ 5 files changed, 356 insertions(+), 59 deletions(-) diff --git a/crates/model/src/extrude.rs b/crates/model/src/extrude.rs index 114606b95..71d550367 100644 --- a/crates/model/src/extrude.rs +++ b/crates/model/src/extrude.rs @@ -96,10 +96,14 @@ fn point_in(p: P, c: &[P]) -> bool { inside } +/// Most contours grouped into outlines; containment is tested pairwise, so the smallest are dropped. +pub const MAX_CONTOURS: usize = 10_000; + /// Group closed contours into outlines by nesting depth (even depth = outer, odd = hole of the -/// innermost containing outer contour). Degenerate contours are dropped. +/// innermost containing outer contour). Degenerate contours are dropped, as are the smallest +/// past [`MAX_CONTOURS`] (a kept hole always keeps its larger container). pub fn group_contours(contours: Vec>) -> Vec { - let cs: Vec> = contours + let mut cs: Vec> = contours .into_iter() .map(|mut c| { c.dedup(); @@ -110,26 +114,60 @@ pub fn group_contours(contours: Vec>) -> Vec { }) .filter(|c| c.len() >= 3 && signed_area(c).abs() > 1e-9) .collect(); + if cs.len() > MAX_CONTOURS { + log::warn!("model: {} contours, grouping the {MAX_CONTOURS} largest", cs.len()); + // Keep the largest, in their original order. + let area: Vec = cs.iter().map(|c| signed_area(c).abs()).collect(); + let mut keep: Vec = (0..cs.len()).collect(); + keep.sort_by(|&a, &b| area[b].total_cmp(&area[a])); + keep.truncate(MAX_CONTOURS); + keep.sort_unstable(); + cs = keep.into_iter().map(|i| std::mem::take(&mut cs[i])).collect(); + } let n = cs.len(); let area: Vec = cs.iter().map(|c| signed_area(c).abs()).collect(); - // Containers of each contour (by a vertex inside; nested contours do not cross). - let parents: Vec> = (0..n) + let bounds: Vec<[P; 2]> = cs + .iter() + .map(|c| c.iter().fold([[f64::MAX; 2], [f64::MIN; 2]], |[lo, hi], p| [[lo[0].min(p[0]), lo[1].min(p[1])], [hi[0].max(p[0]), hi[1].max(p[1])]])) + .collect(); + // The containers of each contour: the larger contours holding a vertex of it (nested contours + // do not cross); the bounding box must hold the vertex first. Depth is their count, so + // overlapping (non-nested) paths keep every container they sit inside. + let containers = |i: usize, only: &dyn Fn(usize) -> bool| -> Vec { + let p = cs[i][0]; + (0..n) + .filter(|&j| j != i && area[j] > area[i] && only(j)) + .filter(|&j| (bounds[j][0][0]..=bounds[j][1][0]).contains(&p[0]) && (bounds[j][0][1]..=bounds[j][1][1]).contains(&p[1])) + .filter(|&j| point_in(p, &cs[j])) + .collect() + }; + let depth: Vec = (0..n).map(|i| containers(i, &|_| true).len()).collect(); + // A hole belongs to the innermost containing contour that is itself an outline: with + // overlapping paths the smallest container can be a hole, which has no outline to take it. + let parent: Vec> = (0..n) .map(|i| { - let probe = cs[i][0]; - (0..n).filter(|&j| j != i && area[j] > area[i] && point_in(probe, &cs[j])).collect() + if depth[i].is_multiple_of(2) { + None + } else { + containers(i, &|j| depth[j].is_multiple_of(2)).into_iter().min_by(|&a, &b| area[a].total_cmp(&area[b])) + } }) .collect(); let mut outlines: Vec = vec![]; let mut slot = vec![usize::MAX; n]; let mut order: Vec = (0..n).collect(); - order.sort_by_key(|&i| parents[i].len()); - for i in order { - let depth = parents[i].len(); - if depth.is_multiple_of(2) { + order.sort_by_key(|&i| depth[i]); + // Every outline gets its slot before any hole is attached: with overlapping paths a hole's + // parent can be deeper than the hole itself. + for &i in &order { + if depth[i].is_multiple_of(2) { slot[i] = outlines.len(); outlines.push(Outline { outer: cs[i].clone(), holes: vec![] }); - } else if let Some(&p) = parents[i].iter().filter(|&&j| parents[j].len() == depth - 1).min_by(|&&a, &&b| area[a].total_cmp(&area[b])) - && slot[p] != usize::MAX + } + } + for &i in &order { + if !depth[i].is_multiple_of(2) + && let Some(p) = parent[i] { outlines[slot[p]].holes.push(cs[i].clone()); } diff --git a/crates/model/src/gltf.rs b/crates/model/src/gltf.rs index 79dab1ddc..d55c39455 100644 --- a/crates/model/src/gltf.rs +++ b/crates/model/src/gltf.rs @@ -11,12 +11,14 @@ //! `KHR_lights_punctual` lights (directional, point, spot). Sparse accessors and morph targets //! are ignored. +use std::collections::HashMap; use std::{cell::Cell, sync::Arc}; use serde_json::Value; use crate::{ - AlphaMode, Animation, Channel, ChannelPath, Interp, Mat4, Material, Mesh, Model, ModelError, Node, Primitive, Result, Skin, TexRef, Texture, Wrap, perr, + AlphaMode, Animation, Channel, ChannelPath, Interp, MAX_IMPORT_TEXTURE_PIXELS, Mat4, Material, Mesh, Model, ModelError, Node, Primitive, Result, Skin, + TexRef, Texture, Wrap, perr, }; const GLB_MAGIC: u32 = 0x4654_6C67; @@ -352,19 +354,41 @@ pub(crate) fn parse_with_budget(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>> = vec![]; - for im in arr(&j, "images") { - let data = if let Some(u) = im.get("uri").and_then(Value::as_str) { - load_uri(u, resolve).ok() - } else if let Some(bv) = idx(im, "bufferView") { - arr(&j, "bufferViews").get(bv).and_then(|v| { - let b = d.buffers.get(idx(v, "buffer").unwrap_or(0))?; - let o = idx(v, "byteOffset").unwrap_or(0); - b.get(o..o.checked_add(idx(v, "byteLength").unwrap_or(0))?).map(<[u8]>::to_vec) - }) - } else { - None + // Images naming one source decode once, and all of them within one pixel budget. + let mut image_of: HashMap>> = HashMap::new(); + let mut pixels_left = MAX_IMPORT_TEXTURE_PIXELS; + let mut warnings: Vec = vec![]; + for (n, im) in arr(&j, "images").iter().enumerate() { + let (uri, view) = (im.get("uri").and_then(Value::as_str), idx(im, "bufferView")); + let key = match (uri, view) { + (Some(u), _) => format!("uri:{u}"), + (None, Some(bv)) => format!("bufferView:{bv}"), + (None, None) => { + images.push(None); + continue; + } }; - images.push(data.and_then(|b| Texture::decode(&b).ok()).map(Arc::new)); + let image = image_of.entry(key).or_insert_with(|| { + let data = if let Some(u) = uri { + load_uri(u, resolve).ok() + } else { + arr(&j, "bufferViews").get(view.unwrap_or(usize::MAX)).and_then(|v| { + let b = d.buffers.get(idx(v, "buffer").unwrap_or(0))?; + let o = idx(v, "byteOffset").unwrap_or(0); + b.get(o..o.checked_add(idx(v, "byteLength").unwrap_or(0))?).map(<[u8]>::to_vec) + }) + }; + match data.map(|b| Texture::decode_within(&b, &mut pixels_left)) { + Some(Ok(t)) => Some(Arc::new(t)), + Some(Err(e)) => { + log::warn!("model: glTF image {n} left out: {e}"); + warnings.push(format!("image {n} left out: {e}")); + None + } + None => None, + } + }); + images.push(image.clone()); } let wrap = |v: u64| match v { 33071 => Wrap::Clamp, @@ -373,18 +397,45 @@ pub(crate) fn parse_with_budget(bytes: &[u8], resolve: &dyn Fn(&str) -> Option> = vec![]; let mut tex_map: Vec> = vec![]; + // One texture per decoded image and wrapping: repeated references share it instead of copying + // the pixels. The image is keyed by its allocation, so image entries naming the same file + // (which share one decode) also share their wrap variants. + let mut texture_of: HashMap<(usize, [Wrap; 2]), usize> = HashMap::new(); for t in arr(&j, "textures") { let Some(img) = idx(t, "source").and_then(|s| images.get(s).cloned().flatten()) else { tex_map.push(None); continue; }; + let src = Arc::as_ptr(&img) as usize; let samp = idx(t, "sampler").and_then(|s| arr(&j, "samplers").get(s)); let ws = samp.and_then(|s| s.get("wrapS")).and_then(Value::as_u64).unwrap_or(10497); let wt = samp.and_then(|s| s.get("wrapT")).and_then(Value::as_u64).unwrap_or(10497); let w = [wrap(ws), wrap(wt)]; - let tex = if img.wrap == w { img } else { Arc::new(Texture { wrap: w, ..(*img).clone() }) }; - tex_map.push(Some(textures.len())); - textures.push(tex); + let i = match texture_of.get(&(src, w)) { + Some(&i) => i, + None => { + let tex = if img.wrap == w { + img + } else { + // A wrap variant copies the pixels, so it is charged to the import budget too; + // one that does not fit is left out like an undecodable image. + let cost = u64::from(img.width) * u64::from(img.height); + if cost > pixels_left { + warnings.push(format!( + "a texture with another wrap mode left out: the model's textures would hold more than {MAX_IMPORT_TEXTURE_PIXELS} pixels" + )); + tex_map.push(None); + continue; + } + pixels_left -= cost; + Arc::new(Texture { wrap: w, ..(*img).clone() }) + }; + textures.push(tex); + texture_of.insert((src, w), textures.len() - 1); + textures.len() - 1 + } + }; + tex_map.push(Some(i)); } let tref = |v: Option<&Value>| -> Option { let v = v?; @@ -536,7 +587,7 @@ pub(crate) fn parse_with_budget(bytes: &[u8], resolve: &dyn Fn(&str) -> Option String { diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 2a7374a05..b95a9f487 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -46,7 +46,7 @@ pub(crate) fn perr(s: impl Into) -> ModelError { } /// Texture coordinate wrapping (glTF sampler wrap modes). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum Wrap { #[default] Repeat, @@ -64,6 +64,12 @@ pub struct Texture { pub wrap: [Wrap; 2], } +/// Most pixels one texture may hold (8192 × 8192: 1 GiB as float RGBA). +pub const MAX_TEXTURE_PIXELS: u64 = 1 << 26; +/// Most pixels the textures of one import may hold together (8 GiB as float RGBA: thirty-two 4K +/// maps). A texture past it is left out and the import says so (`Model::warnings`). +pub const MAX_IMPORT_TEXTURE_PIXELS: u64 = 1 << 29; + impl Texture { pub fn solid(c: [f32; 4]) -> Texture { Texture { width: 1, height: 1, data: vec![c], wrap: [Wrap::Repeat; 2] } @@ -75,8 +81,23 @@ impl Texture { } /// Decode a PNG or JPEG. pub fn decode(bytes: &[u8]) -> Result { - let img = image::load_from_memory(bytes).map_err(|e| perr(format!("image: {e}")))?.to_rgba32f(); + Self::decode_within(bytes, &mut MAX_IMPORT_TEXTURE_PIXELS.clone()) + } + /// [`decode`](Self::decode), of at most [`MAX_TEXTURE_PIXELS`], taking the pixels from `pixels_left`, an import's remaining + /// texture budget, before the image is decoded. + pub fn decode_within(bytes: &[u8], pixels_left: &mut u64) -> Result { + let err = |e: image::ImageError| perr(format!("image: {e}")); + let (w, h) = Self::dimensions(bytes)?; + let pixels = w as u64 * h as u64; + if pixels > MAX_TEXTURE_PIXELS { + return Err(ModelError::Unsupported(format!("a {w}×{h} texture (at most {MAX_TEXTURE_PIXELS} pixels)"))); + } + if pixels > *pixels_left { + return Err(ModelError::Unsupported(format!("a {w}×{h} texture: the model's textures would hold more than {MAX_IMPORT_TEXTURE_PIXELS} pixels"))); + } + let img = image::load_from_memory(bytes).map_err(err)?.to_rgba32f(); let (w, h) = (img.width(), img.height()); + *pixels_left -= pixels; let data = img.pixels().map(|p| p.0).collect(); Ok(Texture { width: w, height: h, data, wrap: [Wrap::Repeat; 2] }) } @@ -577,8 +598,9 @@ pub struct Instance<'m> { pub mesh: &'m Mesh, /// Node → model space. pub world: Mat4, - /// Skinned meshes: joint matrices (model space, `joint_world × inverse_bind`). - pub joints: Option>, + /// Skinned meshes: joint matrices (model space, `joint_world × inverse_bind`), shared by + /// the instances of one skin. + pub joints: Option>>, } impl Model { @@ -629,6 +651,8 @@ impl Model { let mut seen = vec![false; self.nodes.len()]; let mut stack: Vec = self.roots.clone(); let mut out = vec![]; + // The pose is one for the whole scene, so every instance of a skin shares its matrices. + let mut joints_of: std::collections::HashMap>> = std::collections::HashMap::new(); while let Some(i) = stack.pop() { if i >= self.nodes.len() || seen[i] { continue; @@ -636,12 +660,19 @@ impl Model { seen[i] = true; let n = &self.nodes[i]; if let Some(m) = n.mesh.and_then(|m| self.meshes.get(m)) { - let joints = n.skin.and_then(|s| self.skins.get(s)).map(|s| { - s.joints - .iter() - .enumerate() - .map(|(k, &j)| world.get(j).copied().unwrap_or(Mat4::IDENTITY) * s.inverse_bind.get(k).copied().unwrap_or(Mat4::IDENTITY)) - .collect() + let joints = n.skin.and_then(|si| self.skins.get(si).map(|s| (si, s))).map(|(si, s)| { + joints_of + .entry(si) + .or_insert_with(|| { + Arc::new( + s.joints + .iter() + .enumerate() + .map(|(k, &j)| world.get(j).copied().unwrap_or(Mat4::IDENTITY) * s.inverse_bind.get(k).copied().unwrap_or(Mat4::IDENTITY)) + .collect(), + ) + }) + .clone() }); // Skinned vertices are placed by their joints alone (glTF: the node transform of // a skinned mesh is ignored). diff --git a/crates/model/src/obj.rs b/crates/model/src/obj.rs index 22d9877a2..c9d364fc7 100644 --- a/crates/model/src/obj.rs +++ b/crates/model/src/obj.rs @@ -9,10 +9,10 @@ //! Phong exponent `Ns` (`sqrt(2 / (Ns + 2))`) and metallic 0; `map_Kd`, `map_Ke`, //! `map_Bump`/`bump`/`norm` load base colour, emissive and normal textures. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use crate::{AlphaMode, Material, Mesh, Model, Primitive, Result, TexRef, Texture, perr}; +use crate::{AlphaMode, MAX_IMPORT_TEXTURE_PIXELS, Material, Mesh, Model, Primitive, Result, TexRef, Texture, perr}; /// The last component of a referenced path, treating `\` as a separator too: a path from a /// machine of another kind (`C:\textures\checker.png`) still finds `checker.png` next to the @@ -39,24 +39,41 @@ fn resolve_reference(resolve: &dyn Fn(&str) -> Option>, name: &str) -> O None } -/// Parse MTL text into named materials (textures appended to `textures`). -pub fn parse_mtl(text: &str, resolve: &dyn Fn(&str) -> Option>, textures: &mut Vec>) -> Vec { +/// The textures an OBJ import has decoded, by reference, and the pixels it may still decode. +pub struct TextureCache { + loaded: HashMap>, + pixels_left: u64, + /// Textures left out, for the user. + pub warnings: Vec, +} + +impl Default for TextureCache { + fn default() -> Self { + TextureCache { loaded: HashMap::new(), pixels_left: MAX_IMPORT_TEXTURE_PIXELS, warnings: vec![] } + } +} + +/// Parse MTL text into named materials (textures appended to `textures`, decoded once per +/// reference through `cache`). +pub fn parse_mtl(text: &str, resolve: &dyn Fn(&str) -> Option>, textures: &mut Vec>, cache: &mut TextureCache) -> Vec { let mut out: Vec = vec![]; - let mut loaded: HashMap> = HashMap::new(); + let TextureCache { loaded, pixels_left, warnings } = cache; let mut tex = |name: &str, textures: &mut Vec>| -> Option { let key = name.trim().to_string(); let t = *loaded.entry(key.clone()).or_insert_with(|| { let Some(b) = resolve_reference(resolve, &key) else { log::warn!("model: texture `{key}` was not found next to the model"); + warnings.push(format!("texture `{key}` was not found next to the model")); return None; }; - match Texture::decode(&b) { + match Texture::decode_within(&b, pixels_left) { Ok(t) => { textures.push(Arc::new(t)); Some(textures.len() - 1) } Err(e) => { log::warn!("model: cannot decode texture `{key}`: {e}"); + warnings.push(format!("texture `{key}` left out: {e}")); None } } @@ -151,9 +168,13 @@ pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result< let mut vt: Vec<[f32; 2]> = vec![]; let mut vn: Vec<[f32; 3]> = vec![]; let mut materials: Vec = vec![]; + let mut material_of: HashMap = HashMap::new(); let mut textures: Vec> = vec![]; + let mut cache = TextureCache::default(); + let mut libraries: HashSet = HashSet::new(); // One primitive per material, in order of first use. let mut prims: Vec<(Option, Primitive, HashMap, Vec)> = vec![]; + let mut prim_of: HashMap, usize> = HashMap::new(); let mut current: Option = None; let mut smooth = 0u32; let mut flat_id = 1u32 << 31; @@ -181,11 +202,18 @@ pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result< } "mtllib" => { let name = line["mtllib".len()..].trim(); + // A library named again is already loaded. + if !libraries.insert(name.to_string()) { + continue; + } let mut found = false; for file in std::iter::once(name).chain(name.split_whitespace()).chain(sibling_name(name)) { if let Some(b) = resolve(file) { - let mut ms = parse_mtl(&String::from_utf8_lossy(&b), resolve, &mut textures); - materials.append(&mut ms); + let ms = parse_mtl(&String::from_utf8_lossy(&b), resolve, &mut textures, &mut cache); + for m in ms { + material_of.entry(m.name.clone()).or_insert(materials.len()); + materials.push(m); + } found = true; break; } @@ -196,12 +224,11 @@ pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result< } "usemtl" => { let name = line["usemtl".len()..].trim(); - current = materials.iter().position(|m| m.name == name); - if current.is_none() { + current = Some(*material_of.entry(name.to_string()).or_insert_with(|| { // Unknown material: a named grey default. materials.push(Material { name: name.to_string(), metallic: 0.0, roughness: 0.5, base_color: [0.8, 0.8, 0.8, 1.0], ..Material::default() }); - current = Some(materials.len() - 1); - } + materials.len() - 1 + })); } "f" => { if rest.len() < 3 { @@ -234,13 +261,10 @@ pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result< } else { smooth }; - let slot = match prims.iter().position(|p| p.0 == current) { - Some(i) => i, - None => { - prims.push((current, Primitive { material: current, ..Default::default() }, HashMap::new(), vec![])); - prims.len() - 1 - } - }; + let slot = *prim_of.entry(current).or_insert_with(|| { + prims.push((current, Primitive { material: current, ..Default::default() }, HashMap::new(), vec![])); + prims.len() - 1 + }); let (_, prim, map, need) = &mut prims[slot]; let mut ids = vec![]; for (vi, ti, ni) in refs { @@ -290,7 +314,9 @@ pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result< } mesh.primitives.push(p); } - Ok(Model::single(mesh, materials).with_textures(textures)) + let mut model = Model::single(mesh, materials).with_textures(textures); + model.warnings = cache.warnings; + Ok(model) } impl Model { diff --git a/crates/model/src/tests.rs b/crates/model/src/tests.rs index 5ee6a6950..fd3576afe 100644 --- a/crates/model/src/tests.rs +++ b/crates/model/src/tests.rs @@ -432,6 +432,58 @@ fn contours_group_into_outlines_by_nesting() { assert_eq!(g.iter().map(|o| o.holes.len()).sum::(), 2); } +#[test] +fn overlapping_contours_keep_every_container_in_their_depth() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; + // C's first vertex lies inside both A and B, which overlap without nesting: C is two deep, + // an outer contour, not a hole cut out of B. + let g = group_contours(vec![rect(0.0, 0.0, 10.0, 10.0), rect(5.0, -2.0, 13.0, 8.0), rect(9.0, 1.0, 12.0, 2.0)]); + assert_eq!(g.len(), 3); + assert_eq!(g.iter().map(|o| o.holes.len()).sum::(), 0); +} + +#[test] +fn a_contour_inside_a_hole_takes_the_innermost_outline_not_the_hole() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; + // A and B overlap; C lies in A only (a hole of A); D lies in A, B and C (three deep, a hole). + // The smallest container of D is the hole C, which has no outline of its own: D goes to B. + let g = group_contours(vec![rect(0.0, 0.0, 10.0, 10.0), rect(5.0, -2.0, 13.0, 8.0), rect(1.0, 1.0, 9.0, 9.0), rect(6.0, 2.0, 7.0, 3.0)]); + assert_eq!(g.len(), 2); + assert_eq!(g.iter().map(|o| o.holes.len()).collect::>(), [1, 1], "C is a hole of A, D a hole of B (not dropped)"); +} + +#[test] +fn a_hole_whose_outline_is_deeper_than_it_is_still_attached() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]; + // D is three deep and its innermost outline A four deep: A's slot must exist before D is attached. + let a = rect(0.0, 0.0, 10.0, 10.0); + let g = group_contours(vec![ + a.clone(), + rect(-1.0, -1.0, 20.0, 20.0), + rect(-2.0, -2.0, 25.0, 25.0), + rect(5.0, 5.0, 6.0, 6.0), + rect(-100.0, -100.0, 3.0, 3.0), + rect(-0.5, -1000.0, 0.5, 1000.0), + ]); + let o = g.iter().find(|o| o.outer == a).expect("A is an outline"); + assert_eq!(o.holes.len(), 1, "D is a hole of A"); +} + +#[test] +fn gltf_images_naming_one_file_share_their_wrap_variants() { + let png = { + let img = image::RgbaImage::from_fn(2, 2, |x, y| if (x + y) % 2 == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) }); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + // Two image entries with one URI share a decode; two textures clamp it, so they share one copy. + let doc = br#"{"asset":{"version":"2.0"},"images":[{"uri":"t.png"},{"uri":"t.png"}], + "samplers":[{"wrapS":33071,"wrapT":33071}],"textures":[{"source":0,"sampler":0},{"source":1,"sampler":0}]}"#; + let m = gltf::parse(doc, &|u| (u == "t.png").then(|| png.clone())).unwrap(); + assert_eq!(m.textures.len(), 1, "one clamped copy for both textures"); +} + #[test] fn gltf_cameras_and_punctual_lights() { let doc = r#"{ @@ -731,3 +783,102 @@ fn gltf_strip_expansion_is_charged_to_the_read_budget() { let e = crate::gltf::parse_with_budget(doc.as_bytes(), &|_| None, 5000).err().unwrap_or_else(|| panic!("imported")); assert!(e.to_string().contains("more than 5000 components"), "{e}"); } + +#[test] +fn texture_decoding_is_charged_to_the_import_budget() { + let png = { + let img = image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 255, 0, 255])); + let mut b = std::io::Cursor::new(vec![]); + img.write_to(&mut b, image::ImageFormat::Png).unwrap(); + b.into_inner() + }; + let mut left = 4; + assert_eq!(Texture::decode_within(&png, &mut left).unwrap().data.len(), 4); + assert_eq!(left, 0); + assert!(matches!(Texture::decode_within(&png, &mut left), Err(ModelError::Unsupported(_)))); +} + +#[test] +fn obj_repeated_material_libraries_and_textures_load_once() { + let png = { + let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([0, 255, 0, 255])); + let mut b = std::io::Cursor::new(vec![]); + img.write_to(&mut b, image::ImageFormat::Png).unwrap(); + b.into_inner() + }; + let mtl = b"newmtl A\nmap_Kd t.png\nnewmtl B\nmap_Kd t.png\n".to_vec(); + let src = b"mtllib m.mtl\nmtllib m.mtl\nv 0 0 0\nv 1 0 0\nv 0 1 0\nusemtl A\nf 1 2 3\nusemtl B\nf 1 2 3\nusemtl A\nf 1 2 3\n"; + let m = obj::parse(src, &|name| match name { + "m.mtl" => Some(mtl.clone()), + "t.png" => Some(png.clone()), + _ => None, + }) + .unwrap(); + assert_eq!(m.materials.iter().map(|m| m.name.as_str()).collect::>(), ["A", "B"]); + assert_eq!(m.textures.len(), 1); + assert_eq!(m.meshes[0].primitives.iter().map(|p| (p.material, p.triangle_count())).collect::>(), [(Some(0), 2), (Some(1), 1)]); +} + +#[test] +fn gltf_textures_naming_one_image_share_it() { + let doc = String::from_utf8(fixture("quad.gltf")).unwrap(); + // Three textures of one image: the fixture's sampler, the same sampler again, no sampler. + let doc = doc.replace( + "\"textures\": [\n {\n \"source\": 0,\n \"sampler\": 0\n }\n ]", + "\"textures\": [{\"source\": 0, \"sampler\": 0}, {\"source\": 0, \"sampler\": 0}, {\"source\": 0}]", + ); + let m = gltf::parse(doc.as_bytes(), &|_| None).unwrap(); + assert_eq!(m.textures.len(), 2); + assert_eq!(m.textures[0].wrap, [Wrap::Clamp, Wrap::Repeat]); + assert_eq!(m.textures[1].wrap, [Wrap::Repeat, Wrap::Repeat]); +} + +#[test] +fn instances_of_one_skin_share_its_joint_matrices() { + let p = mesh(PrimitiveKind::Plane, &PrimParams { size: [2.0, 2.0, 0.0], ..Default::default() }); + let mut m = Model::single(Mesh { name: "s".into(), primitives: vec![p] }, vec![Material::default()]); + m.nodes[0].skin = Some(0); + m.nodes.push(Node { mesh: Some(0), skin: Some(0), ..Node::default() }); + m.roots = vec![0, 1]; + m.skins.push(Skin { joints: vec![0], inverse_bind: vec![Mat4::IDENTITY] }); + let inst = m.instances(None, 0.0); + assert_eq!(inst.len(), 2); + assert!(Arc::ptr_eq(inst[0].joints.as_ref().unwrap(), inst[1].joints.as_ref().unwrap())); +} + +#[test] +fn contour_grouping_is_bounded() { + let sq = |x: f64, y: f64, s: f64| vec![[x, y], [x + s, y], [x + s, y + s], [x, y + s]]; + let n = extrude::MAX_CONTOURS + 1; + let cs: Vec> = (0..n).map(|i| sq(i as f64 * 2.0, 0.0, 1.0)).collect(); + let g = group_contours(cs); + assert_eq!(g.len(), extrude::MAX_CONTOURS); + assert!(g.iter().all(|o| o.holes.is_empty())); +} + +/// A texture the import leaves out (too large, or not an image) is named in `Model::warnings`, +/// which the import shows the user; the model still loads. +#[test] +fn left_out_textures_are_reported_as_import_warnings() { + // A 24-bit BMP header claiming 9000×9000 (81 MP, over one texture's limit) over no pixel data. + let mut big = b"BM".to_vec(); + big.extend_from_slice(&[0; 8]); + big.extend_from_slice(&54u32.to_le_bytes()); + big.extend_from_slice(&40u32.to_le_bytes()); + big.extend_from_slice(&9000u32.to_le_bytes()); + big.extend_from_slice(&9000u32.to_le_bytes()); + big.extend_from_slice(&[1, 0, 24, 0]); + big.extend_from_slice(&[0; 24]); + let mtl = b"newmtl A\nmap_Kd big.bmp\nnewmtl B\nmap_Kd junk.png\nnewmtl C\nmap_Kd gone.png\n".to_vec(); + let src = b"mtllib m.mtl\nv 0 0 0\nv 1 0 0\nv 0 1 0\nusemtl A\nf 1 2 3\n"; + let m = obj::parse(src, &|name| match name { + "m.mtl" => Some(mtl.clone()), + "big.bmp" => Some(big.clone()), + "junk.png" => Some(b"not an image".to_vec()), + _ => None, + }) + .unwrap(); + assert!(m.textures.is_empty()); + let all = m.warnings.join("|"); + assert!(all.contains("big.bmp") && all.contains("junk.png") && all.contains("gone.png"), "{all}"); +} From 36aa437d3497074a1997e154854900466c97a5e1 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 18:20:05 +0530 Subject: [PATCH 76/83] #2817: pin RotoBezier tangents, mixed checkmark and static paths for Closed --- crates/engine/src/tests/viewer.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/engine/src/tests/viewer.rs b/crates/engine/src/tests/viewer.rs index a3d61a7c0..36fa846e4 100644 --- a/crates/engine/src/tests/viewer.rs +++ b/crates/engine/src/tests/viewer.rs @@ -374,6 +374,7 @@ fn toggle_closed_respects_path_and_vertex_selection() { assert!(shape_path(&s, lid, a).closed); assert!(shape_path(&s, lid, b).closed, "all paths undo in one step"); s.execute("mask.setClosed", json!({"layer": lid, "mask": a, "closed": false})).unwrap(); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(false), "a mixed selection is unchecked"); s.execute("path.toggleClosed", json!({})).unwrap(); assert!(shape_path(&s, lid, a).closed); assert!(shape_path(&s, lid, b).closed, "a mixed selection closes all paths"); @@ -477,6 +478,7 @@ fn toggle_closed_handles_masks_and_preserves_explicit_set_closed() { s.state.selected_props = vec![(LayerId(lid), uid)]; s.execute("path.toggleClosed", json!({})).unwrap(); assert!(!path(&s).closed); + assert!(layer(&s, lid).props.find_group(uid).unwrap().get("path").unwrap().keys.is_empty(), "a static path gains no keyframe"); s.execute("mask.setClosed", json!({"layer": lid, "mask": uid})).unwrap(); assert_eq!(path(&s), original, "explicit API still defaults to closed"); s.execute("mask.setClosed", json!({"layer": lid, "mask": uid, "closed": false})).unwrap(); @@ -493,6 +495,26 @@ fn toggle_closed_handles_masks_and_preserves_explicit_set_closed() { assert_eq!(path(&s), original); } +#[test] +fn toggle_closed_recomputes_roto_bezier_tangents() { + let mut s = comp(); + let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap(); + let uid = + s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100], [0, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); + s.execute("path.rotoBezier", json!({"layer": lid, "value": true})).unwrap(); + let path = |s: &Session| layer(s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone(); + let closed = path(&s); + assert_ne!(closed.out_tangents[0], [0.0; 2], "a closed RotoBezier path has tangents at every vertex"); + s.state.selected_props = vec![(LayerId(lid), uid)]; + s.execute("path.toggleClosed", json!({})).unwrap(); + let open = path(&s); + assert!(!open.closed); + assert_eq!((open.in_tangents[0], open.out_tangents[3]), ([0.0; 2], [0.0; 2]), "open ends lose their automatic tangents"); + assert_ne!(open.out_tangents[1], [0.0; 2]); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert_eq!(path(&s), closed, "reclosing restores the closed RotoBezier tangents"); +} + #[test] fn toggle_closed_edits_layer_time_and_roundtrips() { use effectcraft_keyframe::Keyframe; From d7011a36b8dbae2c9d926d70b2cdbf28fe2ed8ee Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 18:22:21 +0530 Subject: [PATCH 77/83] #2817: Closed falls back to the layer's paths when the selection names none Selecting a non-path property (Position) or a stale selection disabled Closed, unlike RotoBezier and the other Mask and Shape Path commands, which fall back to every mask of the selected layers. A selected mask property (Feather, Opacity, Expansion) now selects its mask. A selected locked mask still counts as a match, so it never falls back to its unlocked siblings. --- crates/engine/src/cmd/paths/closed.rs | 51 ++++++++++++++++----------- crates/engine/src/tests/viewer.rs | 28 ++++++++++----- 2 files changed, 50 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/paths/closed.rs b/crates/engine/src/cmd/paths/closed.rs index 268e68843..12ccb10ac 100644 --- a/crates/engine/src/cmd/paths/closed.rs +++ b/crates/engine/src/cmd/paths/closed.rs @@ -1,7 +1,7 @@ //! The selection-aware Closed menu action. Explicit edits retain `mask.setClosed`'s API. use effectcraft_keyframe::Value as KV; -use effectcraft_project::{GroupKind, Layer, LayerId, PropGroup, Uid}; +use effectcraft_project::{GroupKind, Layer, LayerId, Node, PropGroup, Uid}; use effectcraft_time::Tick; use serde_json::{Value, json}; @@ -14,6 +14,7 @@ struct Target { layer: LayerId, route: Vec, closed: bool, + editable: bool, } struct Selection { @@ -30,58 +31,66 @@ fn group_at_mut<'a>(mut group: &'a mut PropGroup, route: &[usize]) -> Option<&'a Some(group) } +/// The selected paths on the selected layers, else every path of those layers (as the other +/// Mask and Shape Path commands do). Locked layers and masks count as matches, so selecting one +/// never falls back to its siblings, and are then left out. fn targets(s: &Session) -> Result> { let comp = s.active_comp().ok_or(EngineError::NoComp)?; + let on_selected = |lid: &LayerId| s.state.selected_layers.contains(lid); // Layer navigation and insertion can retain point/property selections on other layers. let selection = Selection { - vertices: s.state.selected_vertices.iter().filter(|v| s.state.selected_layers.contains(&v.layer)).copied().collect(), - props: s.state.selected_props.iter().filter(|(lid, _)| s.state.selected_layers.contains(lid)).copied().collect(), + vertices: s.state.selected_vertices.iter().filter(|v| on_selected(&v.layer)).copied().collect(), + props: s.state.selected_props.iter().filter(|(lid, _)| on_selected(lid)).copied().collect(), time: s.time(), }; - let whole_layers = selection.vertices.is_empty() && selection.props.is_empty(); let mut targets = Vec::new(); - for layer in comp.layers.iter() { - let selected_layer = if whole_layers { - s.state.selected_layers.contains(&layer.id) - } else { - selection.vertices.iter().any(|v| v.layer == layer.id) || selection.props.iter().any(|(lid, _)| *lid == layer.id) - }; - if !selected_layer || layer.switches.locked { - continue; + for whole_layers in [false, true] { + for layer in comp.layers.iter().filter(|l| on_selected(&l.id)) { + collect(&selection, layer, &layer.props, &mut Vec::new(), whole_layers, layer.switches.locked, &mut targets)?; + } + if !targets.is_empty() { + break; } - collect(&selection, layer, &layer.props, &mut Vec::new(), whole_layers, &mut targets)?; } + targets.retain(|target| target.editable); if targets.is_empty() { return Err(bad("path.toggleClosed", "select an unlocked mask or Bezier shape path")); } Ok(targets) } -fn collect(selection: &Selection, layer: &Layer, group: &PropGroup, route: &mut Vec, inherited: bool, targets: &mut Vec) -> Result<()> { +fn collect( + selection: &Selection, + layer: &Layer, + group: &PropGroup, + route: &mut Vec, + inherited: bool, + locked: bool, + targets: &mut Vec, +) -> Result<()> { if route.len() > MAX_DEPTH { return Err(bad("path.toggleClosed", "path group nesting exceeds 128 levels")); } - if matches!(group.kind, GroupKind::Mask { locked: true, .. }) { - return Ok(()); - } + let locked = locked || matches!(group.kind, GroupKind::Mask { locked: true, .. }); let selected = inherited || selection.props.contains(&(layer.id, group.uid)); if super::super::mask::is_path_group(group) && let Some(prop) = group.get("path") && let KV::Path(path) = prop.value_at(layer.layer_time(selection.time)) { - // Property selection also selects its points; both describe the selected paths. + // Selecting any of a path group's properties (Mask Path, Feather, Opacity…) or its points + // selects the path. let selected = selected - || selection.props.contains(&(layer.id, prop.uid)) + || group.children.iter().any(|c| matches!(c, Node::Prop(p) if selection.props.contains(&(layer.id, p.uid)))) || selection.vertices.iter().any(|v| v.layer == layer.id && v.mask == group.uid && v.index < path.vertices.len()); if selected { - targets.push(Target { layer: layer.id, route: route.clone(), closed: path.closed }); + targets.push(Target { layer: layer.id, route: route.clone(), closed: path.closed, editable: !locked }); } return Ok(()); } for (index, child) in group.children.iter().enumerate() { let Some(child) = child.as_group() else { continue }; route.push(index); - collect(selection, layer, child, route, selected, targets)?; + collect(selection, layer, child, route, selected, locked, targets)?; route.pop(); } Ok(()) diff --git a/crates/engine/src/tests/viewer.rs b/crates/engine/src/tests/viewer.rs index 36fa846e4..45517e3cd 100644 --- a/crates/engine/src/tests/viewer.rs +++ b/crates/engine/src/tests/viewer.rs @@ -434,7 +434,10 @@ fn toggle_closed_ignores_selections_retained_on_other_layers() { s.execute("layer.selectPrevious", json!({})).unwrap(); assert_eq!(s.state.selected_layers, vec![LayerId(b_layer)]); s.execute("prop.select", json!({"layer": b_layer, "path": "transform/position"})).unwrap(); - assert!(!s.is_enabled("path.toggleClosed"), "a non-path property does not select sibling paths"); + assert_eq!(crate::menus::checked(&s, "path.toggleClosed", &json!({})), Some(true), "a non-path property falls back to the layer's paths"); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, b_layer, b_path).closed); + s.execute("edit.undo", json!({})).unwrap(); s.execute("layer.selectNext", json!({})).unwrap(); s.execute("path.toggleClosed", json!({})).unwrap(); assert!(shape_path(&s, a_layer, a_path).closed, "a property retained on another layer cannot block this layer"); @@ -442,20 +445,22 @@ fn toggle_closed_ignores_selections_retained_on_other_layers() { } #[test] -fn toggle_closed_rejects_locked_stale_and_nonpath_selection() { +fn toggle_closed_falls_back_from_stale_selection_and_rejects_locked_or_pathless_layers() { let mut s = comp(); let r = s.execute("shape.newPath", json!({"vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap(); let (lid, uid) = (r["layer"].as_u64().unwrap(), r["path"].as_u64().unwrap()); let before = s.project.clone(); s.state.selected_vertices.clear(); s.state.selected_props = vec![(LayerId(lid), u64::MAX)]; - assert!(!s.is_enabled("path.toggleClosed")); - assert!(s.execute("path.toggleClosed", json!({})).is_err()); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, lid, uid).closed, "a stale property selection falls back to the layer's paths"); + s.execute("edit.undo", json!({})).unwrap(); assert!(s.project.same_content(&before)); s.state.selected_props.clear(); s.state.selected_vertices = vec![crate::VertexRef { layer: LayerId(lid), mask: uid, index: usize::MAX }]; - assert!(!s.is_enabled("path.toggleClosed")); - assert!(s.execute("path.toggleClosed", json!({})).is_err()); + s.execute("path.toggleClosed", json!({})).unwrap(); + assert!(!shape_path(&s, lid, uid).closed, "a stale vertex selection falls back to the layer's paths"); + s.execute("edit.undo", json!({})).unwrap(); s.state.selected_vertices.clear(); let cid = s.active_comp_id().unwrap(); std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap().switches.locked = true; @@ -475,10 +480,16 @@ fn toggle_closed_handles_masks_and_preserves_explicit_set_closed() { let uid = s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); let path = |s: &Session| layer(s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone(); let original = path(&s); - s.state.selected_props = vec![(LayerId(lid), uid)]; + let other = s.execute("mask.new", json!({"layer": lid, "vertices": [[10, 10], [90, 10], [90, 90]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); + let other_closed = |s: &Session| layer(s, lid).props.find_group(other).unwrap().get("path").unwrap().value.as_path().unwrap().closed; + let feather = layer(&s, lid).props.find_group(uid).unwrap().get("feather").unwrap().uid; + s.state.selected_vertices.clear(); + s.state.selected_props = vec![(LayerId(lid), feather)]; s.execute("path.toggleClosed", json!({})).unwrap(); - assert!(!path(&s).closed); + assert!(!path(&s).closed, "selecting Mask Feather selects its mask"); + assert!(other_closed(&s), "an unselected mask stays closed"); assert!(layer(&s, lid).props.find_group(uid).unwrap().get("path").unwrap().keys.is_empty(), "a static path gains no keyframe"); + s.state.selected_props = vec![(LayerId(lid), uid)]; s.execute("mask.setClosed", json!({"layer": lid, "mask": uid})).unwrap(); assert_eq!(path(&s), original, "explicit API still defaults to closed"); s.execute("mask.setClosed", json!({"layer": lid, "mask": uid, "closed": false})).unwrap(); @@ -493,6 +504,7 @@ fn toggle_closed_handles_masks_and_preserves_explicit_set_closed() { assert!(!s.is_enabled("path.toggleClosed")); assert!(s.execute("path.toggleClosed", json!({})).is_err()); assert_eq!(path(&s), original); + assert!(other_closed(&s), "a selected locked mask does not fall back to its unlocked siblings"); } #[test] From 0ccfd669fb7636f00cff00c0bb21cca15c6d2838 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 18:24:01 +0530 Subject: [PATCH 78/83] #2817: Closed fits short tangent lists like mask.setClosed --- crates/engine/src/cmd/paths/closed.rs | 2 ++ crates/engine/src/tests/viewer.rs | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/crates/engine/src/cmd/paths/closed.rs b/crates/engine/src/cmd/paths/closed.rs index 12ccb10ac..5689020d3 100644 --- a/crates/engine/src/cmd/paths/closed.rs +++ b/crates/engine/src/cmd/paths/closed.rs @@ -120,6 +120,8 @@ pub(super) fn toggle_closed(s: &mut Session, _: &Value) -> Result { if path.closed == closed { continue; } + // As `mask.setClosed`: a path read from a file may have fewer tangents than vertices (#1250). + path.fit_tangents(); path.closed = closed; if roto { super::roto_smooth(&mut path); diff --git a/crates/engine/src/tests/viewer.rs b/crates/engine/src/tests/viewer.rs index 45517e3cd..19d96a75e 100644 --- a/crates/engine/src/tests/viewer.rs +++ b/crates/engine/src/tests/viewer.rs @@ -527,6 +527,25 @@ fn toggle_closed_recomputes_roto_bezier_tangents() { assert_eq!(path(&s), closed, "reclosing restores the closed RotoBezier tangents"); } +#[test] +fn toggle_closed_fits_short_tangent_lists_like_set_closed() { + let mut s = comp(); + let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap(); + let uid = s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); + let cid = s.active_comp_id().unwrap(); + let layer_mut = std::sync::Arc::make_mut(&mut s.project).comp_mut(cid).unwrap().layer_mut(LayerId(lid)).unwrap(); + let prop = layer_mut.props.find_group_mut(uid).unwrap().get_mut("path").unwrap(); + let KV::Path(path) = &mut prop.value else { panic!("not a path") }; + // A file can store fewer tangents than vertices (#1250). + path.in_tangents.clear(); + path.out_tangents.truncate(1); + s.state.selected_props = vec![(LayerId(lid), uid)]; + s.execute("path.toggleClosed", json!({})).unwrap(); + let path = layer(&s, lid).props.find_group(uid).unwrap().get("path").unwrap().value.as_path().unwrap().clone(); + assert!(!path.closed); + assert_eq!((path.in_tangents.len(), path.out_tangents.len()), (3, 3)); +} + #[test] fn toggle_closed_edits_layer_time_and_roundtrips() { use effectcraft_keyframe::Keyframe; From 97fc3eca549d021d9f81287f451ed2d5e54e8ad9 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 18:33:27 +0530 Subject: [PATCH 79/83] #2869: test Effect Controls arrows only where the panel is on screen Replace the floating-beside-maximized case (a maximized frame hides floating windows too) with hidden and on-screen cases, wait for the rename field the way the other rename tests do, and keep viewer text editing's arrows. --- crates/ui-egui/tests/it/ui_effect_controls.rs | 60 +++++++++++++++---- 1 file changed, 47 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/tests/it/ui_effect_controls.rs b/crates/ui-egui/tests/it/ui_effect_controls.rs index 159dc8a12..ff76a1cb7 100644 --- a/crates/ui-egui/tests/it/ui_effect_controls.rs +++ b/crates/ui-egui/tests/it/ui_effect_controls.rs @@ -156,12 +156,18 @@ fn effect_header_arrows_only_disclose_selected_headers_on_the_displayed_layer() #[test] fn effect_header_arrows_ignore_hidden_panels_with_stale_focus() { - for hidden in ["closed", "maximized", "home"] { + // A maximized frame hides every other frame and every floating window, so a floating Effect + // Controls is hidden too. + for hidden in ["closed", "maximized", "floating under maximized", "home"] { let (mut h, lid, [(fx, _), _, _]) = header_arrow_harness(); h.state_mut().session.state.selected_props = vec![(lid, fx)]; match hidden { "closed" => h.state_mut().close_panel(PanelKind::EffectControls), "maximized" => h.state_mut().toggle_maximize(PanelKind::Composition), + "floating under maximized" => { + h.state_mut().apply_dock(craft_ui::docking::Action::Float { panel: PanelKind::EffectControls, rect: [40.0, 40.0, 600.0, 400.0] }).unwrap(); + h.state_mut().toggle_maximize(PanelKind::Composition); + } _ => h.state_mut().ui.start_screen = true, } h.run_steps(2); @@ -176,17 +182,28 @@ fn effect_header_arrows_ignore_hidden_panels_with_stale_focus() { } #[test] -fn effect_header_arrows_work_in_floating_panel_beside_maximized_panel() { - let (mut h, lid, [(fx, prop), _, _]) = header_arrow_harness(); - h.state_mut().apply_dock(craft_ui::docking::Action::Float { panel: PanelKind::EffectControls, rect: [40.0, 40.0, 600.0, 400.0] }).unwrap(); - h.state_mut().toggle_maximize(PanelKind::Composition); - h.state_mut().session.state.selected_props = vec![(lid, fx)]; - h.run_steps(3); - assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_some()); - header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); - assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_none()); - header_arrow_key(&mut h, egui::Key::ArrowRight, egui::Modifiers::NONE); - assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_some()); +fn effect_header_arrows_work_wherever_effect_controls_is_on_screen() { + for place in ["floating", "tab of a maximized frame"] { + let (mut h, lid, [(fx, prop), _, _]) = header_arrow_harness(); + h.state_mut().toggle_maximize(PanelKind::EffectControls); + if place == "floating" { + h.state_mut().apply_dock(craft_ui::docking::Action::Float { panel: PanelKind::EffectControls, rect: [40.0, 40.0, 600.0, 400.0] }).unwrap(); + } else { + let placement = craft_ui::docking::Placement::Tab { before: None }; + h.state_mut().apply_dock(craft_ui::docking::Action::Move { panel: PanelKind::EffectControls, anchor: PanelKind::Composition, placement }).unwrap(); + h.state_mut().toggle_maximize(PanelKind::Composition); + assert_eq!(h.state().ui.maximized, Some(PanelKind::Composition), "the frame was maximized from its Composition tab"); + } + // The moved tab is the front one; clicking it focuses it. + h.state_mut().ui.focused = PanelKind::EffectControls; + h.state_mut().session.state.selected_props = vec![(lid, fx)]; + h.run_steps(3); + assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_some(), "{place}: Effect Controls is on screen"); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_none(), "{place}: Left collapses"); + header_arrow_key(&mut h, egui::Key::ArrowRight, egui::Modifiers::NONE); + assert!(h.state().auto.find(&format!("effectControls.row.{prop}")).is_some(), "{place}: Right expands"); + } } #[test] @@ -220,13 +237,30 @@ fn effect_header_arrows_preserve_modified_shortcuts_and_keyboard_ownership() { header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); assert!(h.state().ui.fx_closed.is_empty(), "the context menu owns the arrows"); header_arrow_key(&mut h, egui::Key::Escape, egui::Modifiers::NONE); + h.run_steps(3); + assert!(!egui::Popup::is_any_open(&h.ctx), "Escape closed the context menu"); double_click(&mut h, at); - assert!(h.ctx.egui_wants_keyboard_input(), "the rename field owns the keyboard"); + h.run_steps(3); + assert!(h.state().auto.find(&format!("effectControls.effect.{fx}.nameEdit")).is_some(), "the rename field is open"); header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); assert!(h.state().ui.fx_closed.is_empty(), "Left moves the text caret instead of collapsing"); assert!(h.state().auto.find(&format!("effectControls.effect.{fx}.nameEdit")).is_some()); } +#[test] +fn effect_header_arrows_leave_viewer_text_editing_alone() { + let (mut h, lid, [(fx, _), _, _]) = header_arrow_harness(); + let text = h.state_mut().session.execute("layer.newText", json!({"text": "abcdef"})).unwrap()["layer"].as_u64().unwrap(); + h.state_mut().session.execute("text.edit", json!({"layer": text, "caret": 3})).unwrap(); + h.state_mut().session.state.selected_layers = vec![lid]; + h.state_mut().session.state.selected_props = vec![(lid, fx)]; + h.state_mut().show_panel(PanelKind::EffectControls); + h.run_steps(2); + assert!(h.state().session.state.text_edit.is_some(), "the text is still being edited"); + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert!(h.state().ui.fx_closed.is_empty(), "the text edit owns the arrows"); +} + #[test] fn effect_controls_widgets_register_automation_ids() { let (app, x) = app(); From 6079a2ee068d5678246ec5e9b852c22dbcfc2cb8 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 18:33:27 +0530 Subject: [PATCH 80/83] #2869: disclose effects only while Effect Controls is drawn Decide visibility from the panels drawn last frame instead of re-deriving the maximize rule: a maximized frame shows its front tab, which may be Effect Controls, and hides floating windows. Leave arrows to viewer text editing. --- crates/ui-egui/src/lib.rs | 4 ++-- crates/ui-egui/src/panels/effect_controls/panel.rs | 8 ++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1558ce743..cd0ac4307 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -409,8 +409,8 @@ pub struct EffectcraftApp { applied_prefs: Option<(u64, Option)>, /// A previous run that didn't exit cleanly (shown by `Dialog::Recovery`). pub recovery: Option, - /// Docked groups laid out last frame: (active panel, group rect) — `~` maximizes the one - /// under the pointer. + /// Panels drawn last frame, docked and floating: (panel, body rect). `~` maximizes the one + /// under the pointer; Effect Controls' arrow keys work only while it is on screen. pub(crate) dock_rects: Vec<(PanelKind, egui::Rect)>, /// The floating panels' OS windows that drew a panel last frame; one that is gone releases /// its IME state. diff --git a/crates/ui-egui/src/panels/effect_controls/panel.rs b/crates/ui-egui/src/panels/effect_controls/panel.rs index 45c3d2e33..1904600df 100644 --- a/crates/ui-egui/src/panels/effect_controls/panel.rs +++ b/crates/ui-egui/src/panels/effect_controls/panel.rs @@ -4,13 +4,17 @@ use super::rows::{FxScope, group_rows, toggle_closed}; use super::{Align2, Color32, EffectcraftApp, EvalCtx, GroupKind, Icon, Layer, PropGroup, Rect, Sense, Stroke, Tokens, json, pos2, vec2, widgets}; use crate::dock::{PanelKind, WorkspaceExt as _}; -/// Plain Left/Right disclose selected effect headers before global layer nudges run. +/// Plain Right / Left Arrow expand / collapse the selected effects, as in After Effects, before +/// the arrows' layer nudge runs. Only while Effect Controls has the focus and is on screen: the +/// front tab of its frame, drawn last frame (a maximized frame hides every other frame and every +/// floating window), not behind Home. With no effect header selected the arrows still nudge. pub(crate) fn handle_disclosure_key(app: &mut EffectcraftApp, key: egui::Key) -> bool { let panel = PanelKind::EffectControls; if app.ui.focused != panel || app.ui.start_screen + || app.session.state.text_edit.is_some() || !app.ui.dock.is_visible(panel) - || (app.ui.dock.is_docked(panel) && app.ui.maximized.is_some_and(|m| m != panel && app.ui.dock.is_docked(m))) + || !app.dock_rects.iter().any(|(p, _)| *p == panel) || !matches!(key, egui::Key::ArrowLeft | egui::Key::ArrowRight) { return false; From 5b3a469181abcae911591e5ff0863db572a957ea Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 18:36:20 +0530 Subject: [PATCH 81/83] #2817: read the selection in place and name the Closed tests for what they prove --- crates/engine/src/cmd/paths/closed.rs | 18 +++++++----------- crates/engine/src/tests/viewer.rs | 4 ++-- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/paths/closed.rs b/crates/engine/src/cmd/paths/closed.rs index 5689020d3..90ff7e737 100644 --- a/crates/engine/src/cmd/paths/closed.rs +++ b/crates/engine/src/cmd/paths/closed.rs @@ -17,9 +17,9 @@ struct Target { editable: bool, } -struct Selection { - vertices: Vec, - props: Vec<(LayerId, Uid)>, +struct Selection<'a> { + vertices: &'a [VertexRef], + props: &'a [(LayerId, Uid)], time: Tick, } @@ -36,16 +36,12 @@ fn group_at_mut<'a>(mut group: &'a mut PropGroup, route: &[usize]) -> Option<&'a /// never falls back to its siblings, and are then left out. fn targets(s: &Session) -> Result> { let comp = s.active_comp().ok_or(EngineError::NoComp)?; - let on_selected = |lid: &LayerId| s.state.selected_layers.contains(lid); - // Layer navigation and insertion can retain point/property selections on other layers. - let selection = Selection { - vertices: s.state.selected_vertices.iter().filter(|v| on_selected(&v.layer)).copied().collect(), - props: s.state.selected_props.iter().filter(|(lid, _)| on_selected(lid)).copied().collect(), - time: s.time(), - }; + let selection = Selection { vertices: &s.state.selected_vertices, props: &s.state.selected_props, time: s.time() }; let mut targets = Vec::new(); for whole_layers in [false, true] { - for layer in comp.layers.iter().filter(|l| on_selected(&l.id)) { + // Only selected layers: navigation and insertion can retain point/property selections + // on other layers, and every match below is per layer. + for layer in comp.layers.iter().filter(|l| s.state.selected_layers.contains(&l.id)) { collect(&selection, layer, &layer.props, &mut Vec::new(), whole_layers, layer.switches.locked, &mut targets)?; } if !targets.is_empty() { diff --git a/crates/engine/src/tests/viewer.rs b/crates/engine/src/tests/viewer.rs index 19d96a75e..a356aa192 100644 --- a/crates/engine/src/tests/viewer.rs +++ b/crates/engine/src/tests/viewer.rs @@ -395,7 +395,7 @@ fn toggle_closed_combines_property_and_shape_group_selections() { s.execute("shape.newPath", json!({"layer": lid, "vertices": [[20, 20], [80, 20], [80, 80]], "closed": true})).unwrap()["path"].as_u64().unwrap(); s.execute("prop.select", json!({"layer": lid, "prop": a_path})).unwrap(); s.execute("prop.select", json!({"layer": lid, "prop": b_group, "add": true})).unwrap(); - assert!(s.state.selected_vertices.iter().all(|v| v.mask == a_path), "only the path property implies selected vertices"); + assert!(s.state.selected_vertices.iter().all(|v| v.mask == a_path), "only the selected path group implies selected vertices"); assert!(!s.state.selected_vertices.is_empty()); assert!(s.state.selected_props.contains(&(LayerId(lid), b_group))); let result = s.execute("path.toggleClosed", json!({})).unwrap(); @@ -528,7 +528,7 @@ fn toggle_closed_recomputes_roto_bezier_tangents() { } #[test] -fn toggle_closed_fits_short_tangent_lists_like_set_closed() { +fn toggle_closed_fits_short_tangent_lists() { let mut s = comp(); let lid = s.execute("layer.newSolid", json!({})).unwrap()["layer"].as_u64().unwrap(); let uid = s.execute("mask.new", json!({"layer": lid, "vertices": [[0, 0], [100, 0], [100, 100]], "closed": true})).unwrap()["mask"].as_u64().unwrap(); From ce11fbf75f4ffa2906534637bfb8fd44671e1881 Mon Sep 17 00:00:00 2001 From: arnav-hiwarkar Date: Thu, 12 Nov 2026 18:40:39 +0530 Subject: [PATCH 82/83] #2869: prove Left still collapses once viewer text editing ends --- crates/ui-egui/tests/it/ui_effect_controls.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/ui_effect_controls.rs b/crates/ui-egui/tests/it/ui_effect_controls.rs index ff76a1cb7..8f2910e43 100644 --- a/crates/ui-egui/tests/it/ui_effect_controls.rs +++ b/crates/ui-egui/tests/it/ui_effect_controls.rs @@ -194,7 +194,7 @@ fn effect_header_arrows_work_wherever_effect_controls_is_on_screen() { h.state_mut().toggle_maximize(PanelKind::Composition); assert_eq!(h.state().ui.maximized, Some(PanelKind::Composition), "the frame was maximized from its Composition tab"); } - // The moved tab is the front one; clicking it focuses it. + // The moved tab is the front one; focus it as a click on it would. h.state_mut().ui.focused = PanelKind::EffectControls; h.state_mut().session.state.selected_props = vec![(lid, fx)]; h.run_steps(3); @@ -259,6 +259,9 @@ fn effect_header_arrows_leave_viewer_text_editing_alone() { assert!(h.state().session.state.text_edit.is_some(), "the text is still being edited"); header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); assert!(h.state().ui.fx_closed.is_empty(), "the text edit owns the arrows"); + h.state_mut().session.state.text_edit = None; + header_arrow_key(&mut h, egui::Key::ArrowLeft, egui::Modifiers::NONE); + assert_eq!(h.state().ui.fx_closed.iter().copied().collect::>(), vec![fx], "with the edit over, Left collapses the effect"); } #[test] From 4035d181329e847d7a57bf3d059502ea2c91b560 Mon Sep 17 00:00:00 2001 From: Altynzhan Karybai Date: Fri, 13 Nov 2026 01:12:42 +0500 Subject: [PATCH 83/83] SVG: support static pattern fills and strokes (#2732) * fix(svg): support static SVG patterns * fix(svg): cache patterns per viewport * fix(svg): share cached pattern content * fix(svg): harden pattern cache keys * fix(svg): harden pattern inheritance and caching * Preserve SVG pattern fallback paint * Format SVG pattern fallback conversion * Harden SVG pattern resource bounds * Fix SVG pattern test formatting * fix(svg): bound hostile path and raster work * Bound SVG ellipse expansion * fix(ui-egui): suppress clippy warnings on wasm target Rename unused `frame` parameter to `_frame` in draw_inner since pointer_wrap::finish_native is cfg'd out on wasm32. Guard State::disabled field with #[cfg(any(not(target_arch = "wasm32"), test))] so it only exists where it's read (finish_frame on native + tests). * fix: resolve clippy warnings blocking CI - Rename unused `frame` parameter to `_frame` in draw_inner (wasm target) - Guard State::disabled field with cfg(native + test) (wasm target) - Replace chunks_exact(2) with as_chunks::<2>() in SVG polyline/polygon parsing * fix(svg): budget raster work by affected region and report refusals Address review on #2732: the finite-work guards charged the whole canvas, dropping valid sparse art (8x8 image scaled to 1px on 2049x2049, 2x2 rect under a 1,028-element clip on 512x512, one of six 2x2 rects sharing a 1x1 pattern on 3840x2160). - Build fill/stroke/image/clip coverage over the device region only and charge that region; remaining whole-canvas passes are charged to a render-wide pixel budget (caps are not raised). - Add try_rasterize/try_rasterize_with returning RasterError; rasterize keeps its signature. media layered decode now surfaces refusals. - Pattern content reached through href inherits styles from the owning pattern; device_region falls back to the full canvas on non-finite input. - Document new items and the limits in the svg README; regression tests. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/engine/src/interchange/vector.rs | 66 +- crates/engine/src/tests/vector_import.rs | 35 + crates/media/src/layered.rs | 27 +- crates/media/src/pool.rs | 16 +- crates/svg/Cargo.toml | 2 +- crates/svg/README.md | 24 +- crates/svg/src/color.rs | 1 + crates/svg/src/lib.rs | 609 +++++++++++-- crates/svg/src/pathdata.rs | 255 ++++-- crates/svg/src/raster.rs | 1001 ++++++++++++++++++++-- crates/svg/src/tests.rs | 671 ++++++++++++++- crates/ui-egui/src/app/frame.rs | 4 +- crates/ui-egui/src/pointer_wrap.rs | 7 +- 13 files changed, 2486 insertions(+), 232 deletions(-) diff --git a/crates/engine/src/interchange/vector.rs b/crates/engine/src/interchange/vector.rs index 569e8e5bc..64ef00253 100644 --- a/crates/engine/src/interchange/vector.rs +++ b/crates/engine/src/interchange/vector.rs @@ -8,6 +8,7 @@ use effectcraft_project::{Comp, ItemId, Layer, LayerSource, MaskMode, Project, P use effectcraft_svg::{Affine, Doc, Geom, GradientKind, Node, Paint}; use kurbo::{BezPath, Point}; +/// Convert a kurbo path into shape path property groups. fn shape_paths(ids: &mut Ids, path: &BezPath) -> Vec { effectcraft_path::from_kurbo(path) .into_iter() @@ -20,6 +21,7 @@ fn shape_paths(ids: &mut Ids, path: &BezPath) -> Vec { .collect() } +/// Uniform scale factor of a transform (square root of its determinant magnitude). fn det_scale(m: Affine) -> f64 { let c = m.as_coeffs(); (c[0] * c[3] - c[1] * c[2]).abs().sqrt() @@ -31,6 +33,7 @@ fn axis_aligned(m: Affine) -> Option<(f64, f64, f64, f64)> { (c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && c[0] > 0.0 && c[3] > 0.0).then_some((c[0], c[3], c[4], c[5])) } +/// Convert an SVG gradient into the engine's gradient value. fn gradient_value(g: &effectcraft_svg::Gradient) -> Gradient { Gradient { colors: g.stops.iter().map(|(o, c)| (*o, [c[0] as f32, c[1] as f32, c[2] as f32, 1.0])).collect(), @@ -52,6 +55,7 @@ fn gradient_points(g: &effectcraft_svg::Gradient, m: Affine, bbox: kurbo::Rect) } } +/// Convert one SVG shape under transform `m` into shape-layer items. fn shape_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine) -> Vec { use kurbo::Shape as _; let mut items = vec![]; @@ -72,48 +76,60 @@ fn shape_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine) -> Vec build::shape_stroke(ids, [c[0], c[1], c[2], 1.0], width), + let paint = match &st.paint { + Paint::Color(c) => Some(build::shape_stroke(ids, [c[0], c[1], c[2], 1.0], width)), Paint::Gradient(gr) => { let (radial, a, b) = gradient_points(gr, m, bbox); - build::shape_gradient_stroke(ids, radial, a, b, gradient_value(gr), width) + Some(build::shape_gradient_stroke(ids, radial, a, b, gradient_value(gr), width)) } + // Editable shape layers do not yet have a pattern paint operator. Keep the geometry + // and any retained fallback as solid paint; SVG footage retains the rasterised pattern. + Paint::Pattern(pattern) => pattern.fallback.map(|c| build::shape_stroke(ids, [c[0], c[1], c[2], c[3]], width)), }; - set(&mut g, "opacity", Value::Scalar(st.opacity * 100.0)); - set(&mut g, "cap", Value::Enum(st.cap as u32)); - set(&mut g, "join", Value::Enum(st.join as u32)); - set(&mut g, "miter", Value::Scalar(st.miter)); - if let Some((d, off)) = &st.dash - && let Some(dg) = g.sub_mut("dashes") - { - let k = det_scale(m); - set(dg, "dash", Value::Scalar(d.first().copied().unwrap_or(0.0) * k)); - set(dg, "gap", Value::Scalar(d.get(1).or(d.first()).copied().unwrap_or(0.0) * k)); - set(dg, "offset", Value::Scalar(off * k)); + if let Some(mut g) = paint { + set(&mut g, "opacity", Value::Scalar(st.opacity * 100.0)); + set(&mut g, "cap", Value::Enum(st.cap as u32)); + set(&mut g, "join", Value::Enum(st.join as u32)); + set(&mut g, "miter", Value::Scalar(st.miter)); + if let Some((d, off)) = &st.dash + && let Some(dg) = g.sub_mut("dashes") + { + let k = det_scale(m); + set(dg, "dash", Value::Scalar(d.first().copied().unwrap_or(0.0) * k)); + set(dg, "gap", Value::Scalar(d.get(1).or(d.first()).copied().unwrap_or(0.0) * k)); + set(dg, "offset", Value::Scalar(off * k)); + } + items.push(g); } - items.push(g); } if let Some(f) = &s.fill { - let mut g = match f { - Paint::Color(c) => build::shape_fill(ids, [c[0], c[1], c[2], 1.0]), + let paint = match f { + Paint::Color(c) => Some(build::shape_fill(ids, [c[0], c[1], c[2], 1.0])), Paint::Gradient(gr) => { let (radial, a, b) = gradient_points(gr, m, bbox); - build::shape_gradient_fill(ids, radial, a, b, gradient_value(gr)) + Some(build::shape_gradient_fill(ids, radial, a, b, gradient_value(gr))) } + // Pattern artwork is preserved in rasterised SVG footage; editable shapes keep only + // any retained fallback as solid paint. + Paint::Pattern(pattern) => pattern.fallback.map(|c| build::shape_fill(ids, [c[0], c[1], c[2], c[3]])), }; - set(&mut g, "opacity", Value::Scalar(s.fill_opacity * 100.0)); - set(&mut g, "rule", Value::Enum(u32::from(s.fill_rule == effectcraft_svg::FillRule::EvenOdd))); - items.push(g); + if let Some(mut g) = paint { + set(&mut g, "opacity", Value::Scalar(s.fill_opacity * 100.0)); + set(&mut g, "rule", Value::Enum(u32::from(s.fill_rule == effectcraft_svg::FillRule::EvenOdd))); + items.push(g); + } } items } +/// Set a child property's value if present. fn set(g: &mut PropGroup, k: &str, v: Value) { if let Some(p) = g.get_mut(k) { p.value = v; } } +/// Wrap items in a named shape group with the given opacity (0..1). fn group(ids: &mut Ids, name: &str, items: Vec, opacity: f64) -> PropGroup { let mut g = build::shape_group(ids, name, items); if let Some(p) = g.prop_mut("transform/opacity") { @@ -165,6 +181,7 @@ fn clipped_items(ids: &mut Ids, s: &effectcraft_svg::Shape, m: Affine, clips: &[ /// [`shapes_from_vector`]). Images are skipped (Layer ▸ Create makes them footage layers, see /// [`split_at_images`]); soft masks are not converted. pub fn svg_contents(ids: &mut Ids, doc: &Doc) -> Vec { + /// Convert nodes to property groups, applying transform `m` and clip paths. fn walk(ids: &mut Ids, nodes: &[Node], m: Affine, clips: &[BezPath]) -> Vec { let mut out = vec![]; for n in nodes.iter().rev() { @@ -406,6 +423,7 @@ fn copy_transform(proj: &mut Project, src: &Layer, dst: &mut Layer) { } } +/// Copy timing and parenting from `src` to `dst`. fn like_source(dst: &mut Layer, src: &Layer) { dst.start_time = src.start_time; dst.in_point = src.in_point; @@ -418,13 +436,17 @@ fn like_source(dst: &mut Layer, src: &Layer) { /// A raster image of a vector document (Create Shapes from Vector Layer makes it a footage /// layer: shape layers have no images). pub struct VectorImage { + /// Image name. pub name: String, + /// Pixel width. pub width: u32, + /// Pixel height. pub height: u32, /// Straight RGBA8. pub rgba: std::sync::Arc>, /// Image pixels → document pixels. pub transform: Affine, + /// Opacity, 0..1. pub opacity: f64, /// Inside a clipping group or under a soft mask (not carried over). pub clipped: bool, @@ -432,6 +454,7 @@ pub struct VectorImage { /// The document's images, bottom first, and how many soft-masked groups it has. pub fn vector_images(doc: &Doc) -> (Vec, usize) { + /// Collect images from a group tree, counting soft-masked groups. fn walk(g: &effectcraft_svg::Group, m: Affine, opacity: f64, clipped: bool, out: &mut Vec, masks: &mut usize) { let m = m * g.transform; let opacity = opacity * g.opacity; @@ -467,6 +490,7 @@ pub fn vector_images(doc: &Doc) -> (Vec, usize) { /// layers and image footage layers can stack in the document's order. One more segment than /// images. pub fn split_at_images(doc: &Doc) -> Vec { + /// Count the images in a group tree. fn count(g: &effectcraft_svg::Group) -> usize { g.children .iter() diff --git a/crates/engine/src/tests/vector_import.rs b/crates/engine/src/tests/vector_import.rs index 2f41b16b2..6372ffb35 100644 --- a/crates/engine/src/tests/vector_import.rs +++ b/crates/engine/src/tests/vector_import.rs @@ -320,6 +320,41 @@ fn paste_svg_markup_as_a_shape_layer() { assert_eq!(s.active_comp().unwrap().layers.len(), 1); } +#[test] +fn pasted_svg_pattern_keeps_geometry_and_editable_fallback_paint() { + let (mut s, _) = text_session(); + let svg = r##" + + + + + + + + "##; + let result = s.execute_checked("edit.pasteSvg", json!({"svg": svg})).unwrap(); + let layer_id = effectcraft_project::LayerId(result["layer"].as_u64().unwrap()); + let layer = s.active_comp().unwrap().layer(layer_id).unwrap(); + let shape = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned").unwrap(); + let items: Vec<_> = shape.sub("contents").unwrap().groups().collect(); + assert!(items.iter().any(|item| item.match_id == "rect"), "the editable geometry remains"); + let fill = items.iter().find(|item| item.match_id == "fill").expect("fallback fill remains editable"); + assert_eq!(fill.get("color").unwrap().value, KV::Color([1.0, 0.0, 0.0, 0.5])); + let stroke = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned-stroke").unwrap(); + let items: Vec<_> = stroke.sub("contents").unwrap().groups().collect(); + assert!(items.iter().any(|item| item.match_id == "path"), "the editable stroke path remains"); + let stroke = items.iter().find(|item| item.match_id == "stroke").expect("fallback stroke remains editable"); + assert_eq!(stroke.get("color").unwrap().value, KV::Color([0.0, 0.0, 1.0, 0.25])); + let no_fallback = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned-no-fallback").unwrap(); + let items: Vec<_> = no_fallback.sub("contents").unwrap().groups().collect(); + assert!(items.iter().any(|item| item.match_id == "rect"), "the editable geometry remains without a fallback"); + assert!(!items.iter().any(|item| item.match_id == "fill"), "pattern paint without a fallback is omitted"); + let no_fallback_stroke = layer.props.sub("contents").unwrap().groups().find(|g| g.name == "patterned-stroke-no-fallback").unwrap(); + let items: Vec<_> = no_fallback_stroke.sub("contents").unwrap().groups().collect(); + assert!(items.iter().any(|item| item.match_id == "path"), "the editable stroke geometry remains without a fallback"); + assert!(!items.iter().any(|item| item.match_id == "stroke"), "pattern stroke without a fallback is omitted"); +} + #[test] fn paste_svg_rejects_text_that_is_not_usable_svg() { let (mut s, _) = text_session(); diff --git a/crates/media/src/layered.rs b/crates/media/src/layered.rs index 64ade9394..adc23cf31 100644 --- a/crates/media/src/layered.rs +++ b/crates/media/src/layered.rs @@ -119,7 +119,7 @@ pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) - if u64::from(w) * u64::from(h) > u64::from(MAX_VECTOR_SIDE) * u64::from(MAX_VECTOR_SIDE) { return Err(MediaError::Decode(format!("{path}: {w}×{h} pixels is larger than vector footage can be drawn ({MAX_VECTOR_SIDE}×{MAX_VECTOR_SIDE})"))); } - let img = effectcraft_svg::rasterize_with(&doc, w, h, to_image); + let img = effectcraft_svg::try_rasterize_with(&doc, w, h, to_image).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; // The rasteriser produces premultiplied pixels already. let _ = op; return Ok(Some(img)); @@ -132,10 +132,15 @@ const MAX_VECTOR_SIDE: u32 = 16384; /// The vector footage `footage` (of the file `path` with these `bytes`) rasterised at `scale` × /// its size as [`effectcraft_render::vector_fit`] draws it (Continuously Rasterize). -pub(crate) fn rasterize_vector(path: &str, bytes: &[u8], footage: &Footage, scale: f64) -> Option { +/// +/// `None` when the file cannot be read as a vector document. `Some(Err(_))` when a render budget +/// refused part of the drawing (for example a layer scaled past the surface limit), so the caller +/// can report it instead of showing a partial or empty image as if it were complete. +pub(crate) fn rasterize_vector(path: &str, bytes: &[u8], footage: &Footage, scale: f64) -> Option> { let doc = footage_doc(path, bytes, footage)?.ok()?; let ((sw, sh), to_image) = fit(&doc, footage, scale); - Some(effectcraft_svg::rasterize_with(&doc, sw.clamp(1, MAX_VECTOR_SIDE), sh.clamp(1, MAX_VECTOR_SIDE), to_image)) + let drawn = effectcraft_svg::try_rasterize_with(&doc, sw.clamp(1, MAX_VECTOR_SIDE), sh.clamp(1, MAX_VECTOR_SIDE), to_image); + Some(drawn.map_err(|e| MediaError::Decode(format!("{path}: {e}")))) } /// The page framing of vector footage: as After Effects places it for footage from an After @@ -173,6 +178,18 @@ mod tests { assert_eq!((img.width, img.height), (40, 20)); } + /// Continuously Rasterize reports a layer scaled past the render budget as an error instead of + /// returning a partial or empty image, and still draws the same layer at an ordinary scale. + #[test] + fn rasterizing_vector_footage_past_the_budget_is_reported() { + let svg = br#""#; + let footage = probe("scaled.svg", svg).unwrap().unwrap(); + let ok = rasterize_vector("scaled.svg", svg, &footage, 1.0).unwrap().unwrap(); + assert_eq!((ok.width, ok.height), (100, 100)); + let e = rasterize_vector("scaled.svg", svg, &footage, 1000.0).unwrap().err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("scaled.svg"), "{e}"); + } + /// A 200 × 100 pt page: red left half, blue right half. fn halves_pdf() -> Vec { effectcraft_pdf::write::pdf( @@ -214,7 +231,7 @@ mod tests { (footage.width, footage.height) = (100, 80); let unplaced = decode("art.ai", &pdf, &footage, op).unwrap().unwrap(); assert!(unplaced == own, "not placed: drawn as before"); - assert_eq!(rasterize_vector("art.ai", &pdf, &footage, 0.5).map(|i| (i.width, i.height)), Some((100, 50))); + assert_eq!(rasterize_vector("art.ai", &pdf, &footage, 0.5).and_then(|r| r.ok()).map(|i| (i.width, i.height)), Some((100, 50))); footage.placed_page = true; let img = decode("art.ai", &pdf, &footage, op).unwrap().unwrap(); @@ -226,7 +243,7 @@ mod tests { assert!(is_blue(img.get(x, y)), "blue at ({x}, {y}): {:?}", img.get(x, y)); } - let sharp = rasterize_vector("art.ai", &pdf, &footage, 2.0).unwrap(); + let sharp = rasterize_vector("art.ai", &pdf, &footage, 2.0).unwrap().unwrap(); assert_eq!((sharp.width, sharp.height), (200, 160)); assert!(is_red(sharp.get(50, 155)) && is_blue(sharp.get(150, 155))); // Placed at the page's own size: 1:1. diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index 872e4fdfa..f5d109797 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -1110,7 +1110,7 @@ impl FootageSource for MediaPool { } fn problem(&self, footage: &Footage) -> Option { - if footage.missing || footage.kind != FootageKind::Video { + if footage.missing || (footage.kind != FootageKind::Video && !effectcraft_render::is_vector_footage(footage)) { return None; } lock(&self.inner.problems).get(footage.path.as_str()).cloned() @@ -1121,7 +1121,19 @@ impl FootageSource for MediaPool { return None; } let bytes = self.inner.read(&footage.path).ok()?; - crate::layered::rasterize_vector(&footage.path, &bytes, footage, scale).map(Arc::new) + let path: Arc = footage.path.as_str().into(); + match crate::layered::rasterize_vector(&footage.path, &bytes, footage, scale)? { + Ok(img) => { + lock(&self.inner.problems).remove(&path); + Some(Arc::new(img)) + } + // Refused by a render budget (a layer scaled too far): no frame, with the reason + // reported through `problem` rather than showing a partial image as complete. + Err(e) => { + self.inner.note_problem(&path, "", &e); + None + } + } } fn set_aux_footage(&self, paths: &[String]) { diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 03cacaa7b..e542bed47 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "effectcraft-svg" -description = "SVG import: parses SVG 1.1 / SVG 2 static vector content (paths, basic shapes, groups, transforms, use, CSS styles, solid and gradient fills/strokes, opacity) and rasterises it at any scale" +description = "SVG import: parses SVG 1.1 / SVG 2 static vector content (paths, basic shapes, groups, transforms, use, CSS styles, solid, gradient and pattern fills/strokes, opacity) and rasterises it at any scale" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/svg/README.md b/crates/svg/README.md index 862bd01d0..f39156f22 100644 --- a/crates/svg/README.md +++ b/crates/svg/README.md @@ -18,9 +18,31 @@ here, plus **CSS Color Module Level 3** for colour keywords and functions: `stroke-opacity`, `opacity`, `display`, `visibility`, `color`/`currentColor`; - `linearGradient` and `radialGradient` (with `fx`/`fy` focal point), `gradientUnits`, `gradientTransform`, `spreadMethod`, `href` inheritance of stops and attributes; +- static (non-animated) `` fill/stroke with `patternUnits`, `patternContentUnits`, `patternTransform`, + tile `x`/`y`/`width`/`height`, local `href`/`xlink:href` inheritance and solid paints on + supported shape/group children; - styling through presentation attributes, the `style` attribute and `