From ebca4bd9b78139ca1e7cfd89ee7bf1b99629d8b2 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 20:43:45 -0800 Subject: [PATCH] Split model/comp.rs and model/edit.rs into focused submodules --- crates/model/src/comp.rs | 3188 +--------------------------- crates/model/src/comp/eval.rs | 724 +++++++ crates/model/src/comp/load.rs | 813 +++++++ crates/model/src/comp/math.rs | 520 +++++ crates/model/src/comp/save.rs | 637 ++++++ crates/model/src/comp/tests.rs | 501 +++++ crates/model/src/edit.rs | 1822 +--------------- crates/model/src/edit/clipboard.rs | 696 ++++++ crates/model/src/edit/defaults.rs | 176 ++ crates/model/src/edit/history.rs | 417 ++++ crates/model/src/edit/keyframes.rs | 185 ++ crates/model/src/edit/tests.rs | 359 ++++ 12 files changed, 5065 insertions(+), 4973 deletions(-) create mode 100644 crates/model/src/comp/eval.rs create mode 100644 crates/model/src/comp/load.rs create mode 100644 crates/model/src/comp/math.rs create mode 100644 crates/model/src/comp/save.rs create mode 100644 crates/model/src/comp/tests.rs create mode 100644 crates/model/src/edit/clipboard.rs create mode 100644 crates/model/src/edit/defaults.rs create mode 100644 crates/model/src/edit/history.rs create mode 100644 crates/model/src/edit/keyframes.rs create mode 100644 crates/model/src/edit/tests.rs diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index 2ca57a9c866aecb100493c4b00be58f453e57f90..e40abca9a6f7fbc5e49122a6b3dc4ce186d5aa6b 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -1,11 +1,21 @@ //! Core composition IR, Fusion `.comp` importer, parameter evaluation, and graph editing. -use crate::expr::ExprEngine; -use crate::lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua}; -use crate::spline::{BezierSpline, Gradient, PolyPath, read_vec2}; -use std::collections::{HashMap, HashSet, VecDeque}; +mod eval; +mod load; +mod math; +mod save; +#[cfg(test)] +mod tests; + +pub use math::{GridMesh, MeshPoint}; +pub(crate) use math::{find_raw_tool, find_raw_tool_mut}; +pub(crate) use save::{ensure_table_mut, is_group_kind, param_value_to_lua, vec2_lua}; + +use crate::lua_value::{LuaTable, LuaValue}; +use crate::spline::{BezierSpline, Gradient, PolyPath}; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::AtomicU64; /// Fusion working color bit depth (`DepthFull` / `ChangeDepth.Depth` / generator `Depth`). /// Fusion enum: `0 = Default`, `1 = int8`, `2 = int16`, `3 = float16`, `4 = float32`. @@ -452,522 +462,18 @@ const MODIFIER_TYPES: &[&str] = &[ ]; /// Each loaded comp gets its own revision range so frame-cache keys never collide across reloads. -static NEXT_COMP_REVISION: AtomicU64 = AtomicU64::new(1); -const REVISION_STRIDE: u64 = 1 << 32; +pub(super) static NEXT_COMP_REVISION: AtomicU64 = AtomicU64::new(1); +pub(super) const REVISION_STRIDE: u64 = 1 << 32; /// Max hops through chained expression modifiers / `Node.Param` references before evaluation gives up. -const MAX_EXPR_DEPTH: usize = 16; +pub(super) const MAX_EXPR_DEPTH: usize = 16; pub(crate) fn is_modifier_type(kind: &str) -> bool { MODIFIER_TYPES.contains(&kind) || kind.ends_with("Spline") || kind.ends_with("Modifier") } -impl Comp { - pub fn from_fusion_file(path: impl AsRef) -> Result> { - let path = path.as_ref(); - let bytes = std::fs::read(path)?; - let text = String::from_utf8_lossy(&bytes); - let mut comp = Self::from_fusion_str(&text)?; - comp.path = Some(path.to_path_buf()); - if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { - comp.name = stem.to_owned(); - } - Ok(comp) - } - - pub fn from_fusion_str(text: &str) -> Result { - let root_val = parse_lua(text)?; - let root = root_val - .as_table() - .ok_or_else(|| ParseError { offset: 0, line: 1, message: "comp root is not a table".into() })?; - - let current_time = root.get_f64("CurrentTime").unwrap_or(0.0); - let global_range = root - .get_table("GlobalRange") - .and_then(read_vec2) - .map(|[a, b]| [a as i64, b as i64]) - .unwrap_or([0, 1000]); - let render_range = root - .get_table("RenderRange") - .and_then(read_vec2) - .map(|[a, b]| [a as i64, b as i64]) - .unwrap_or(global_range); - let audio_filename = root.get_str("AudioFilename").map(str::to_owned); - let audio_offset = root.get_f64("AudioOffset").unwrap_or(0.0); - - // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps, Int8) - let mut width = 1920u32; - let mut height = 1080u32; - let mut fps = 30.0_f64; - let mut depth_full = BitDepth::Int8; - let mut explicit_size = false; - if let Some(ff) = root - .get_table("Prefs") - .and_then(|p| p.get_table("Comp")) - .and_then(|c| c.get_table("FrameFormat")) - { - if let Some(w) = ff.get_f64("Width") { - width = w.round().max(1.0) as u32; - explicit_size = true; - } - if let Some(h) = ff.get_f64("Height") { - height = h.round().max(1.0) as u32; - explicit_size = true; - } - if let Some(r) = ff.get_f64("Rate") { - if r > 0.0 { - fps = r; - } - } - if let Some(d) = ff.get_f64("DepthFull").and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) { - depth_full = d; - } - } - - let mut nodes = Vec::new(); - let mut node_by_name = HashMap::new(); - let mut splines = HashMap::new(); - let mut poly_paths = HashMap::new(); - let mut gradient_modifiers = HashMap::new(); - let mut text_modifiers = HashMap::new(); - let mut text_splines = HashMap::new(); - let mut polyline_splines = HashMap::new(); - let mut text_cls = HashMap::new(); - let mut shakes = HashMap::new(); - let mut expression_modifiers = HashMap::new(); - let mut tracker_aliases: Vec<(String, String)> = Vec::new(); - let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new(); - let mut instanced_from: Vec<(NodeId, String)> = Vec::new(); - - if let Some(tools) = root.get_table("Tools") { - parse_tools_table( - tools, - false, - &mut nodes, - &mut node_by_name, - &mut splines, - &mut poly_paths, - &mut gradient_modifiers, - &mut text_modifiers, - &mut text_splines, - &mut polyline_splines, - &mut text_cls, - &mut shakes, - &mut expression_modifiers, - &mut tracker_aliases, - &mut macro_defaults, - &mut instanced_from, - ); - } - - // Resolve TrackerModifier aliases (e.g. `Track1` -> `Track1TrackerPath`) into `poly_paths` - for (tracker_name, src_path) in tracker_aliases { - if let Some(pp) = poly_paths.get(&src_path).cloned() { - poly_paths.insert(tracker_name, pp); - } - } - - // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools. - for (target_op, target_param, val) in macro_defaults { - if let Some(&nid) = node_by_name.get(&target_op) { - let entry = nodes[nid.0].inputs.entry(target_param).or_insert(InputBinding { - value: None, - source_op: None, - source_output: None, - expression: None, - }); - if entry.value.is_none() && entry.source_op.is_none() && entry.expression.is_none() { - entry.value = Some(val); - } - } - } - - // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets - // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`. - let node_inputs_snapshot: Vec<(String, HashMap)> = nodes - .iter() - .map(|n| (n.name.clone(), n.inputs.clone())) - .collect(); - let snap_map: HashMap> = node_inputs_snapshot.into_iter().collect(); - for n in &mut nodes { - if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { - let mut flow_wires = HashMap::new(); - for (in_name, b) in &n.inputs { - if let (Some(inner_op), Some(inner_port)) = (&b.source_op, &b.source_output) { - if let Some(inner_in) = snap_map.get(inner_op).and_then(|m| m.get(inner_port)) { - if let Some(ext_src) = &inner_in.source_op { - // Only connect if ext_src is a visible (non-internal) flow node - if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) { - let port_name = if in_name.starts_with("MainInput") || in_name == "Input" { - "Input".to_owned() - } else { - in_name.clone() - }; - flow_wires.insert( - port_name, - InputBinding { - value: None, - source_op: Some(ext_src.clone()), - source_output: inner_in.source_output.clone(), - expression: None, - }, - ); - } - } - } - } - } - if !flow_wires.is_empty() { - n.inputs = flow_wires; - } - } - } - - // Resolve Fusion tool-level `SourceOp` instanced node inheritance - // (e.g. `Instance_ColorCorrector1_6 = ColorCorrector { SourceOp = "ColorCorrector1_6" }`), - // walking chains up to depth 8 (cycle-safe) while NEVER copying image/mask/scene wires. - if !instanced_from.is_empty() { - let parent_of: HashMap = instanced_from - .iter() - .filter_map(|(nid, master_name)| { - node_by_name - .get(master_name) - .copied() - .filter(|&mid| mid != *nid) - .map(|mid| (*nid, mid)) - }) - .collect(); - let orig_inputs: Vec> = - nodes.iter().map(|n| n.inputs.clone()).collect(); - - for &(nid, _) in &instanced_from { - let mut visited = HashSet::new(); - visited.insert(nid); - let mut blocked: HashSet = HashSet::new(); - let mut cur = nid; - for _depth in 0..8 { - let Some(&pid) = parent_of.get(&cur) else { - break; - }; - if !visited.insert(pid) { - break; - } - let inst_inputs = &mut nodes[nid.0].inputs; - for (inp_name, parent_binding) in &orig_inputs[pid.0] { - if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name) - { - continue; - } - if blocked.contains(inp_name) { - continue; - } - if parent_binding.value.is_none() - && parent_binding.source_op.is_none() - && parent_binding.expression.is_none() - { - // An empty `Param = Input {}` on an ancestor marks a de-instanced - // override to default and stops further inheritance up the chain. - blocked.insert(inp_name.clone()); - continue; - } - if !inst_inputs.contains_key(inp_name) { - inst_inputs.insert(inp_name.clone(), parent_binding.clone()); - } - } - cur = pid; - } - } - } - - // Apply cyclic [0..6] endpoint continuity on LUTBezier splines attached to HueCurves nodes. - const HUE_CURVE_PORTS: &[&str] = &[ - "Hue", - "Sat", - "Lum", - "Red", - "Green", - "Blue", - "RedSuppress", - "GreenSuppress", - "BlueSuppress", - ]; - let mut hue_spline_names: HashSet = HashSet::new(); - for n in &nodes { - if n.kind == "HueCurves" { - for &port in HUE_CURVE_PORTS { - if let Some(sp_name) = n.connected_node(port) { - hue_spline_names.insert(sp_name.to_owned()); - } - } - } - } - for sp_name in hue_spline_names { - if let Some(sp) = splines.get_mut(&sp_name) { - sp.apply_hue_curves_cyclic_ends(); - } - } - - // Infer comp dimensions from first Background/TextPlus if Prefs omitted Width/Height - if !explicit_size { - for n in &nodes { - if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") { - if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) { - if w >= 64.0 && h >= 64.0 { - width = w as u32; - height = h as u32; - break; - } - } - } - } - } - - Ok(Self { - path: None, - name: "Untitled".to_owned(), - width, - height, - fps, - depth_full, - current_time, - global_range, - render_range, - audio_filename, - audio_offset, - nodes, - node_by_name, - splines, - poly_paths, - gradient_modifiers, - text_modifiers, - text_splines, - polyline_splines, - text_cls, - shakes, - expression_modifiers, - raw_root: Some(root.clone()), - revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed), - }) - } - - /// Evaluates an animated `Polyline` spline (`BezierSpline` whose keyframes carry `Value = Polyline { ... }`). - pub fn eval_polyline_spline(&self, name: &str, time: f64) -> Option> { - let (spline, kfs) = self.polyline_splines.get(name)?; - if kfs.is_empty() { - return None; - } - if kfs.len() == 1 || time <= kfs[0].0 { - return Some(kfs[0].1.clone()); - } - if time >= kfs[kfs.len() - 1].0 { - return Some(kfs[kfs.len() - 1].1.clone()); - } - // Fusion stores keyframe index (0, 1, 2, ...) as the spline scalar value for eased shape morphing. - let u = spline.eval(time).clamp(0.0, (kfs.len() - 1) as f64); - let idx = (u.floor() as usize).min(kfs.len() - 2); - let frac = (u - idx as f64).clamp(0.0, 1.0); - let a = &kfs[idx].1; - let b = &kfs[idx + 1].1; - if a.len() != b.len() || frac <= 1e-6 { - return Some(a.clone()); - } - if frac >= 1.0 - 1e-6 { - return Some(b.clone()); - } - let lerp = |x: f64, y: f64| x + (y - x) * frac; - Some( - a.iter() - .zip(b.iter()) - .map(|(pa, pb)| crate::spline::PolyPoint { - x: lerp(pa.x, pb.x), - y: lerp(pa.y, pb.y), - lx: lerp(pa.lx, pb.lx), - ly: lerp(pa.ly, pb.ly), - rx: lerp(pa.rx, pb.rx), - ry: lerp(pa.ry, pb.ry), - linear: pa.linear && pb.linear, - }) - .collect(), - ) - } -} - -#[derive(Clone, Debug, PartialEq)] -pub struct MeshPoint { - pub x: f64, - pub y: f64, - pub l_cx: Option, - pub l_cy: Option, - pub r_cx: Option, - pub r_cy: Option, - pub t_cx: Option, - pub t_cy: Option, - pub b_cx: Option, - pub b_cy: Option, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct GridMesh { - pub cols: usize, - pub rows: usize, - pub delta_r: f64, - pub delta_c: f64, - pub points: Vec, -} - -impl GridMesh { - fn from_lua_table(tbl: &LuaTable) -> Option { - if tbl.tag.as_deref() != Some("Mesh") { - return None; - } - let cols = tbl.get_f64("Col")?.round().max(2.0) as usize; - let pts_tbl = tbl.get_table("Points")?; - let mut points = Vec::new(); - for pval in pts_tbl.positional_values() { - let pt = pval.as_table()?; - points.push(MeshPoint { - x: pt.get_f64("X").unwrap_or(0.0), - y: pt.get_f64("Y").unwrap_or(0.0), - l_cx: pt.get_f64("L_CX"), - l_cy: pt.get_f64("L_CY"), - r_cx: pt.get_f64("R_CX"), - r_cy: pt.get_f64("R_CY"), - t_cx: pt.get_f64("T_CX"), - t_cy: pt.get_f64("T_CY"), - b_cx: pt.get_f64("B_CX"), - b_cy: pt.get_f64("B_CY"), - }); - } - if points.len() < cols * 2 { - return None; - } - let rows = points.len() / cols; - if rows < 2 || rows * cols != points.len() { - return None; - } - let delta_c = tbl.get_f64("DeltaC").unwrap_or(1.0 / (cols - 1) as f64); - let delta_r = tbl.get_f64("DeltaR").unwrap_or(1.0 / (rows - 1) as f64); - Some(Self { - cols, - rows, - delta_r, - delta_c, - points, - }) - } - - fn lerp(&self, other: &Self, frac: f64) -> Self { - if self.cols != other.cols || self.rows != other.rows || self.points.len() != other.points.len() { - return self.clone(); - } - let f = frac.clamp(0.0, 1.0); - let lerp_num = |a: f64, b: f64| a + (b - a) * f; - let lerp_opt = |a: Option, b: Option| match (a, b) { - (Some(x), Some(y)) => Some(lerp_num(x, y)), - (Some(x), None) => Some(x), - (None, Some(y)) => Some(y), - (None, None) => None, - }; - let points = self - .points - .iter() - .zip(other.points.iter()) - .map(|(a, b)| MeshPoint { - x: lerp_num(a.x, b.x), - y: lerp_num(a.y, b.y), - l_cx: lerp_opt(a.l_cx, b.l_cx), - l_cy: lerp_opt(a.l_cy, b.l_cy), - r_cx: lerp_opt(a.r_cx, b.r_cx), - r_cy: lerp_opt(a.r_cy, b.r_cy), - t_cx: lerp_opt(a.t_cx, b.t_cx), - t_cy: lerp_opt(a.t_cy, b.t_cy), - b_cx: lerp_opt(a.b_cx, b.b_cx), - b_cy: lerp_opt(a.b_cy, b.b_cy), - }) - .collect(); - Self { - cols: self.cols, - rows: self.rows, - delta_r: lerp_num(self.delta_r, other.delta_r), - delta_c: lerp_num(self.delta_c, other.delta_c), - points, - } - } -} - -/// Finds a tool/modifier by name in `tools` or any nested `Tools` table (Groups, Macros, curve nodes). -pub(crate) fn find_raw_tool<'a>(tools: &'a LuaTable, target: &str) -> Option<&'a LuaTable> { - if let Some(t) = tools.get_table(target) { - return Some(t); - } - tools - .entries - .iter() - .filter_map(|(_, v)| v.as_table()?.get_table("Tools")) - .find_map(|inner| find_raw_tool(inner, target)) -} - -pub(crate) fn find_raw_tool_mut<'a>(tools: &'a mut LuaTable, target: &str) -> Option<&'a mut LuaTable> { - if tools.get_table(target).is_some() { - return tools.get_table_mut(target); - } - tools - .entries - .iter_mut() - .filter_map(|(_, v)| v.as_table_mut()?.get_table_mut("Tools")) - .find_map(|inner| find_raw_tool_mut(inner, target)) -} impl Comp { - /// Evaluates a `GridWarp` `Mesh` input (static `Mesh { ... }` or animated `BezierSpline` of `Mesh`es). - pub fn eval_grid_mesh(&self, node: &Node, key: &str, time: f64) -> Option { - if let Some(spline_name) = node.inputs.get(key).and_then(|b| b.source_op.as_deref()) { - let tools = self.raw_root.as_ref()?.get_table("Tools")?; - let stbl = find_raw_tool(tools, spline_name)?; - let kfs_tbl = stbl.get_table("KeyFrames")?; - let mut kfs: Vec<(f64, GridMesh)> = Vec::new(); - for (k, v) in &kfs_tbl.entries { - let t = match k { - LuaKey::Index(i) => *i as f64, - LuaKey::Number(n) => *n, - _ => continue, - }; - if let Some(m) = v.as_table().and_then(|kt| kt.get_table("Value")).and_then(GridMesh::from_lua_table) { - kfs.push((t, m)); - } - } - if !kfs.is_empty() { - kfs.sort_by(|a, b| a.0.total_cmp(&b.0)); - if kfs.len() == 1 || time <= kfs[0].0 { - return Some(kfs[0].1.clone()); - } - if time >= kfs[kfs.len() - 1].0 { - return Some(kfs[kfs.len() - 1].1.clone()); - } - let u = self - .splines - .get(spline_name) - .map(|sp| sp.eval(time)) - .unwrap_or(0.0) - .clamp(0.0, (kfs.len() - 1) as f64); - let idx = (u.floor() as usize).min(kfs.len() - 2); - let frac = (u - idx as f64).clamp(0.0, 1.0); - if frac <= 1e-6 { - return Some(kfs[idx].1.clone()); - } - if frac >= 1.0 - 1e-6 { - return Some(kfs[idx + 1].1.clone()); - } - return Some(kfs[idx].1.lerp(&kfs[idx + 1].1, frac)); - } - } - node.raw - .get_table("Inputs")? - .get_table(key)? - .get_table("Value") - .and_then(GridMesh::from_lua_table) - } - pub fn node(&self, id: NodeId) -> &Node { &self.nodes[id.0] } @@ -1036,681 +542,6 @@ impl Comp { out } - /// Evaluates a numeric input on `node` at continuous `time`, checking Expression -> Spline -> Static -> `default`. - pub fn eval_number( - &self, - node: &Node, - param: &str, - time: f64, - default: f64, - expr_engine: &ExprEngine, - ) -> f64 { - self.eval_number_at(node, param, time, default, expr_engine, 0) - } - - fn eval_number_at( - &self, - node: &Node, - param: &str, - time: f64, - default: f64, - expr_engine: &ExprEngine, - depth: usize, - ) -> f64 { - if depth >= MAX_EXPR_DEPTH { - return default; - } - let Some(binding) = node.inputs.get(param) else { - return default; - }; - if let Some(expr) = &binding.expression { - if let Some(v) = self.eval_expr_number(node, expr, time, expr_engine) { - if v.is_finite() { - return v; - } - } - } - if let Some(src) = &binding.source_op { - if let Some(sp) = self.splines.get(src) { - return sp.eval(time); - } - if let Some(sh) = self.shakes.get(src) { - let axis = match binding.source_output.as_deref() { - Some("Y") => 1, - _ => 0, - }; - return self.eval_shake_axis(sh, axis, time, expr_engine); - } - if let Some(em) = self.expression_modifiers.get(src) { - if let Some(v) = self.eval_expr_mod_number( - em, - binding.source_output.as_deref(), - time, - expr_engine, - depth + 1, - ) { - if v.is_finite() { - return v; - } - } - } - } - binding - .value - .as_ref() - .and_then(ParamValue::as_f64) - .unwrap_or(default) - } - - /// Evaluates a 2D point input (`Center`, `Pivot`, etc.) on `node` at `time`. - pub fn eval_point( - &self, - node: &Node, - param: &str, - time: f64, - default: [f64; 2], - expr_engine: &ExprEngine, - ) -> [f64; 2] { - self.eval_point_at(node, param, time, default, expr_engine, 0) - } - - fn eval_point_at( - &self, - node: &Node, - param: &str, - time: f64, - default: [f64; 2], - expr_engine: &ExprEngine, - depth: usize, - ) -> [f64; 2] { - if depth >= MAX_EXPR_DEPTH { - return default; - } - let Some(binding) = node.inputs.get(param) else { - return default; - }; - if let Some(expr) = &binding.expression { - if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) { - return p; - } - } - if let Some(src) = &binding.source_op { - if let Some(pp) = self.poly_paths.get(src) { - let disp = pp - .displacement_op - .as_deref() - .and_then(|d| self.splines.get(d)) - .map(|sp| sp.eval(time)) - .unwrap_or(pp.displacement_value); - return pp.eval_center(disp); - } - if let Some(sh) = self.shakes.get(src) { - let x = self.eval_shake_axis(sh, 0, time, expr_engine); - let y = self.eval_shake_axis(sh, 1, time, expr_engine); - return [x, y]; - } - if let Some(em) = self.expression_modifiers.get(src) { - if let Some(pt) = self.eval_expr_mod_point(em, time, expr_engine, depth + 1) { - if pt[0].is_finite() && pt[1].is_finite() { - return pt; - } - } - } - } - binding - .value - .as_ref() - .and_then(ParamValue::as_point) - .unwrap_or(default) - } - - fn eval_shake_input(&self, sh: &ShakeModifier, key: &str, time: f64, default: f64, expr_engine: &ExprEngine) -> f64 { - let Some(b) = sh.inputs.get(key) else { - return default; - }; - if let Some(expr) = &b.expression { - let mut sp = HashMap::new(); - for (k, ib) in &sh.inputs { - if k == key { - continue; - } - if let Some(src) = &ib.source_op { - if let Some(spl) = self.splines.get(src) { - sp.insert(k.clone(), spl.eval(time)); - continue; - } - } - if let Some(v) = ib.value.as_ref().and_then(ParamValue::as_f64) { - sp.insert(k.clone(), v); - } - } - if let Some(v) = expr_engine.eval_number(expr, time, &sp, &HashMap::new(), &HashMap::new()) { - if v.is_finite() { - return v; - } - } - } - if let Some(src) = &b.source_op { - if let Some(spl) = self.splines.get(src) { - return spl.eval(time); - } - } - b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default) - } - - fn eval_shake_axis(&self, sh: &ShakeModifier, axis: u32, time: f64, expr_engine: &ExprEngine) -> f64 { - let smoothness = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine).max(0.01); - let seed = self.eval_shake_input(sh, "RandomSeed", time, 0.0, expr_engine).round() as i64; - let lock_xy = self.eval_shake_input(sh, "LockXY", time, 1.0, expr_engine) > 0.5; - let (min_v, max_v) = if axis == 0 || lock_xy { - ( - self.eval_shake_input(sh, "XMinimum", time, 0.0, expr_engine), - self.eval_shake_input(sh, "XMaximum", time, 1.0, expr_engine), - ) - } else { - ( - self.eval_shake_input(sh, "YMinimum", time, 0.0, expr_engine), - self.eval_shake_input(sh, "YMaximum", time, 1.0, expr_engine), - ) - }; - // Smooth Catmull-Rom interpolation over seeded lattice points spaced by `smoothness` frames - let u = time / smoothness; - let k = u.floor() as i64; - let f = u - k as f64; - let hash01 = |i: i64| -> f64 { - let mut x = (i.wrapping_mul(0x9E37_79B9_7F4A_7C15u64 as i64) - ^ seed.wrapping_mul(0xBF58_476D_1CE4_E5B9u64 as i64) - ^ ((axis as i64).wrapping_mul(0x94D0_49BB_1331_11EBu64 as i64))) as u64; - x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - x ^= x >> 31; - (x >> 11) as f64 / (1u64 << 53) as f64 - }; - let p0 = hash01(k - 1); - let p1 = hash01(k); - let p2 = hash01(k + 1); - let p3 = hash01(k + 2); - let f2 = f * f; - let f3 = f2 * f; - let cr = 0.5 * ((2.0 * p1) - + (-p0 + p2) * f - + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * f2 - + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * f3); - let t01 = cr.clamp(0.0, 1.0); - min_v + (max_v - min_v) * t01 - } - - fn eval_expr_mod_input_number( - &self, - em: &ExpressionModifier, - keys: &[&str], - time: f64, - default: f64, - expr_engine: &ExprEngine, - depth: usize, - ) -> f64 { - let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else { - return default; - }; - if let Some(expr) = &b.expression { - if let Some(v) = self.eval_modifier_inline_number(expr, time, expr_engine, depth) { - if v.is_finite() { - return v; - } - } - } - if let Some(src) = &b.source_op { - if let Some(spl) = self.splines.get(src) { - return spl.eval(time); - } - if let Some(sh) = self.shakes.get(src) { - let axis = match b.source_output.as_deref() { - Some("Y") => 1, - _ => 0, - }; - return self.eval_shake_axis(sh, axis, time, expr_engine); - } - if depth < MAX_EXPR_DEPTH { - if let Some(sub) = self.expression_modifiers.get(src) { - if let Some(v) = self.eval_expr_mod_number( - sub, - b.source_output.as_deref(), - time, - expr_engine, - depth + 1, - ) { - if v.is_finite() { - return v; - } - } - } - } - } - b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default) - } - - fn eval_expr_mod_input_point( - &self, - em: &ExpressionModifier, - keys: &[&str], - time: f64, - default: [f64; 2], - expr_engine: &ExprEngine, - depth: usize, - ) -> [f64; 2] { - let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else { - return default; - }; - if let Some(expr) = &b.expression { - let trimmed = expr.trim(); - // Direct `NodeName.ParamName` reference to a Point input on another flow node. - if let Some((node_name, param_name)) = trimmed.split_once('.') { - if !param_name.contains('.') && !param_name.contains(' ') { - if let Some(nid) = self.find_node(node_name.trim()) { - return self.eval_point_at(self.node(nid), param_name.trim(), time, default, expr_engine, depth + 1); - } - } - } - let (sp, spts, en) = self.collect_global_expr_env(time); - if let Some(pt) = expr_engine.eval_point(trimmed, time, &sp, &spts, &en) { - if pt[0].is_finite() && pt[1].is_finite() { - return pt; - } - } - } - if let Some(src) = &b.source_op { - if let Some(pp) = self.poly_paths.get(src) { - let disp = pp - .displacement_op - .as_deref() - .and_then(|d| self.splines.get(d)) - .map(|sp| sp.eval(time)) - .unwrap_or(pp.displacement_value); - return pp.eval_center(disp); - } - if let Some(sh) = self.shakes.get(src) { - let x = self.eval_shake_axis(sh, 0, time, expr_engine); - let y = self.eval_shake_axis(sh, 1, time, expr_engine); - return [x, y]; - } - if depth < MAX_EXPR_DEPTH { - if let Some(sub) = self.expression_modifiers.get(src) { - if let Some(pt) = self.eval_expr_mod_point(sub, time, expr_engine, depth + 1) { - if pt[0].is_finite() && pt[1].is_finite() { - return pt; - } - } - } - } - } - b.value.as_ref().and_then(ParamValue::as_point).unwrap_or(default) - } - - fn eval_modifier_inline_number( - &self, - expr: &str, - time: f64, - expr_engine: &ExprEngine, - depth: usize, - ) -> Option { - let trimmed = expr.trim(); - if let Some((node_name, param_name)) = trimmed.split_once('.') { - if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') { - if let Some(nid) = self.find_node(node_name.trim()) { - return Some(self.eval_number_at( - self.node(nid), - param_name.trim(), - time, - 0.0, - expr_engine, - depth + 1, - )); - } - } - } - let (sp, spts, en) = self.collect_global_expr_env(time); - expr_engine.eval_number(trimmed, time, &sp, &spts, &en) - } - - fn collect_global_expr_env( - &self, - time: f64, - ) -> ( - HashMap, - HashMap, - HashMap>, - ) { - let mut env_nodes = HashMap::new(); - for n in &self.nodes { - let mut m = HashMap::new(); - for (k, b) in &n.inputs { - if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { - m.insert(k.clone(), v); - } else if let Some(src) = &b.source_op { - if let Some(sp) = self.splines.get(src) { - m.insert(k.clone(), sp.eval(time)); - } - } - } - if !m.is_empty() { - env_nodes.insert(n.name.clone(), m); - } - } - (HashMap::new(), HashMap::new(), env_nodes) - } - - fn build_expr_mod_vars( - &self, - em: &ExpressionModifier, - time: f64, - expr_engine: &ExprEngine, - depth: usize, - ) -> (HashMap, HashMap) { - let mut vars = HashMap::with_capacity(32); - let mut pts = HashMap::with_capacity(18); - vars.insert("time".to_owned(), time); - vars.insert("pi".to_owned(), std::f64::consts::PI); - vars.insert("e".to_owned(), std::f64::consts::E); - - for i in 1..=9 { - let short = format!("n{i}"); - let long = format!("NumberIn{i}"); - let v = self.eval_expr_mod_input_number( - em, - &[short.as_str(), long.as_str()], - time, - 0.0, - expr_engine, - depth, - ); - vars.insert(short, v); - vars.insert(long, v); - } - for i in 1..=9 { - let short = format!("p{i}"); - let long = format!("PointIn{i}"); - let pt = self.eval_expr_mod_input_point( - em, - &[short.as_str(), long.as_str()], - time, - [0.5, 0.5], - expr_engine, - depth, - ); - vars.insert(format!("p{i}x"), pt[0]); - vars.insert(format!("p{i}y"), pt[1]); - pts.insert(short, pt); - pts.insert(long, pt); - } - for (k, b) in &em.inputs { - if !vars.contains_key(k) { - if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { - vars.insert(k.clone(), v); - } - } - } - (vars, pts) - } - - fn eval_expr_mod_formula( - &self, - formula: &str, - time: f64, - vars: &HashMap, - pts: &HashMap, - expr_engine: &ExprEngine, - ) -> Option { - let trimmed = formula.trim(); - if trimmed.is_empty() { - return None; - } - if let Some(v) = eval_fusion_math_expr(trimmed, vars) { - return Some(v); - } - // Fallback to Lua SimpleExpression engine for Lua-specific formulas - let (_, _, en) = self.collect_global_expr_env(time); - expr_engine.eval_number(trimmed, time, vars, pts, &en) - } - - fn eval_expr_mod_number( - &self, - em: &ExpressionModifier, - source_output: Option<&str>, - time: f64, - expr_engine: &ExprEngine, - depth: usize, - ) -> Option { - if depth >= MAX_EXPR_DEPTH { - return None; - } - let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth); - let key = match source_output { - Some("X") => "PointExpressionX", - Some("Y") => "PointExpressionY", - _ => "NumberExpression", - }; - let formula = em - .inputs - .get(key) - .and_then(|b| b.value.as_ref()) - .and_then(ParamValue::as_str)?; - self.eval_expr_mod_formula(formula, time, &vars, &pts, expr_engine) - } - - fn eval_expr_mod_point( - &self, - em: &ExpressionModifier, - time: f64, - expr_engine: &ExprEngine, - depth: usize, - ) -> Option<[f64; 2]> { - if depth >= MAX_EXPR_DEPTH { - return None; - } - let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth); - let fx = em - .inputs - .get("PointExpressionX") - .and_then(|b| b.value.as_ref()) - .and_then(ParamValue::as_str); - let fy = em - .inputs - .get("PointExpressionY") - .and_then(|b| b.value.as_ref()) - .and_then(ParamValue::as_str); - if fx.is_some() || fy.is_some() { - let x = fx - .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine)) - .unwrap_or(0.5); - let y = fy - .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine)) - .unwrap_or(0.5); - return Some([x, y]); - } - if let Some(fp) = em - .inputs - .get("PointExpression") - .and_then(|b| b.value.as_ref()) - .and_then(ParamValue::as_str) - { - let (_, _, en) = self.collect_global_expr_env(time); - if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) { - return Some(pt); - } - } - None - } - - pub fn eval_text( - &self, - node: &Node, - param: &str, - time: f64, - default: &str, - expr_engine: &ExprEngine, - ) -> String { - let Some(binding) = node.inputs.get(param) else { - return default.to_owned(); - }; - if let Some(expr) = &binding.expression { - let (sp, spts, en) = self.collect_expr_env(node, time); - if let Some(s) = expr_engine.eval_string(expr, time, &sp, &spts, &en) { - return s; - } - } - if let Some(src) = &binding.source_op { - if let Some(kfs) = self.text_splines.get(src) { - if !kfs.is_empty() { - let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1); - return kfs[idx].1.clone(); - } - } - if let Some(txt) = self.text_modifiers.get(src) { - return txt.clone(); - } - } - binding - .value - .as_ref() - .and_then(ParamValue::as_str) - .unwrap_or(default) - .to_owned() - } - - pub fn text_cls_entries(&self, node: &Node, param: &str) -> &[ClsEntry] { - node.inputs - .get(param) - .and_then(|b| b.source_op.as_deref()) - .and_then(|src| self.text_cls.get(src)) - .map(Vec::as_slice) - .unwrap_or(&[]) - } - - pub fn eval_gradient(&self, node: &Node, param: &str, time: f64) -> Option { - let binding = node.inputs.get(param)?; - if let Some(src) = &binding.source_op { - if let Some(kfs) = self.gradient_modifiers.get(src) { - if kfs.is_empty() { - return None; - } - if kfs.len() == 1 || time <= kfs[0].0 { - return Some(kfs[0].1.clone()); - } - let last = &kfs[kfs.len() - 1]; - if time >= last.0 { - return Some(last.1.clone()); - } - let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1); - let (t0, g0) = &kfs[idx]; - let (t1, g1) = &kfs[(idx + 1).min(kfs.len() - 1)]; - let f = ((time - t0) / (t1 - t0).max(1e-9)).clamp(0.0, 1.0) as f32; - // Bake 17 blended stops across [0..1] - let mut stops = Vec::with_capacity(17); - for i in 0..=16 { - let p = i as f64 / 16.0; - let a = g0.sample(p); - let b = g1.sample(p); - stops.push(crate::spline::GradientStop { - pos: p, - rgba: [ - a[0] + (b[0] - a[0]) * f, - a[1] + (b[1] - a[1]) * f, - a[2] + (b[2] - a[2]) * f, - a[3] + (b[3] - a[3]) * f, - ], - }); - } - return Some(Gradient { stops }); - } - } - if let Some(ParamValue::Gradient(g)) = &binding.value { - return Some(g.clone()); - } - None - } - - fn collect_expr_env( - &self, - node: &Node, - time: f64, - ) -> ( - HashMap, - HashMap, - HashMap>, - ) { - let mut self_params = HashMap::new(); - let mut self_points = HashMap::new(); - for (k, b) in &node.inputs { - if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { - self_params.insert(k.clone(), v); - } else if let Some(pt) = b.value.as_ref().and_then(ParamValue::as_point) { - self_points.insert(k.clone(), pt); - } else if let Some(src) = &b.source_op { - if let Some(sp) = self.splines.get(src) { - self_params.insert(k.clone(), sp.eval(time)); - } else if let Some(pp) = self.poly_paths.get(src) { - let disp = pp - .displacement_op - .as_deref() - .and_then(|d| self.splines.get(d)) - .map(|sp| sp.eval(time)) - .unwrap_or(pp.displacement_value); - self_points.insert(k.clone(), pp.eval_center(disp)); - } - } - } - let mut env_nodes = HashMap::new(); - for n in &self.nodes { - let mut m = HashMap::new(); - for (k, b) in &n.inputs { - if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { - m.insert(k.clone(), v); - } else if let Some(src) = &b.source_op { - if let Some(sp) = self.splines.get(src) { - m.insert(k.clone(), sp.eval(time)); - } - } - } - if !m.is_empty() { - env_nodes.insert(n.name.clone(), m); - } - } - (self_params, self_points, env_nodes) - } - - fn eval_expr_number( - &self, - node: &Node, - expr: &str, - time: f64, - expr_engine: &ExprEngine, - ) -> Option { - let needs_nodes = expr.contains('.') - || expr.trim_start().starts_with(':') - || expr - .split(|c: char| !c.is_alphanumeric() && c != '_') - .any(|tok| !tok.is_empty() && node.inputs.contains_key(tok)); - if !needs_nodes { - let empty_self = HashMap::new(); - let empty_pts = HashMap::new(); - let empty_env = HashMap::new(); - return expr_engine.eval_number(expr, time, &empty_self, &empty_pts, &empty_env); - } - let (sp, spts, en) = self.collect_expr_env(node, time); - expr_engine.eval_number(expr, time, &sp, &spts, &en) - } - - fn eval_expr_point( - &self, - node: &Node, - expr: &str, - time: f64, - expr_engine: &ExprEngine, - ) -> Option<[f64; 2]> { - let (sp, spts, en) = self.collect_expr_env(node, time); - expr_engine.eval_point(expr, time, &sp, &spts, &en) - } - /// Connects `src` node's `"Output"` to `dst` node's `port` input (ignores self-loops and cycles). pub fn connect(&mut self, src: NodeId, dst: NodeId, port: &str) { let _ = self.connect_output(src, "Output", dst, port); @@ -1765,673 +596,6 @@ impl Comp { } out } - - /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits, - /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST, - /// preserving all unknown nodes, modifiers, macros, UserControls, Clips, and metadata verbatim. - pub fn sync_to_raw_ast(&self) -> LuaTable { - let mut root = self.raw_root.clone().unwrap_or_else(|| LuaTable { - tag: Some("Composition".to_owned()), - entries: Vec::new(), - }); - - root.set( - LuaKey::Str("CurrentTime".to_owned()), - LuaValue::Number(self.current_time), - ); - root.set( - LuaKey::Str("GlobalRange".to_owned()), - vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64), - ); - root.set( - LuaKey::Str("RenderRange".to_owned()), - vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64), - ); - if let Some(ref af) = self.audio_filename { - root.set( - LuaKey::Str("AudioFilename".to_owned()), - LuaValue::String(af.clone()), - ); - } - if self.audio_offset != 0.0 || root.get("AudioOffset").is_some() { - root.set( - LuaKey::Str("AudioOffset".to_owned()), - LuaValue::Number(self.audio_offset), - ); - } - - // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull) - { - let prefs = ensure_table_mut(&mut root, "Prefs", None); - let comp_prefs = ensure_table_mut(prefs, "Comp", None); - let ff = ensure_table_mut(comp_prefs, "FrameFormat", None); - if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) { - ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64)); - } - if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) { - ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64)); - } - if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) { - ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps)); - } - let existing_depth = ff - .get_f64("DepthFull") - .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) - .unwrap_or(BitDepth::Int8); - if existing_depth != self.depth_full { - ff.set( - LuaKey::Str("DepthFull".to_owned()), - LuaValue::Number((self.depth_full as i32) as f64), - ); - } - } - - // Sync Tools - let tools = ensure_table_mut(&mut root, "Tools", Some("ordered")); - - for node in self.nodes.iter().filter(|n| !n.internal) { - if tools.get_table(&node.name).is_some() { - continue; - } - let mut new_tbl = if node.raw.tag.is_some() { - node.raw.clone() - } else { - LuaTable { tag: None, entries: Vec::new() } - }; - if new_tbl.tag.is_none() { - new_tbl.tag = Some(node.kind.clone()); - } - tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl)); - } - - let mut pool: HashMap<(bool, String), VecDeque<&Node>> = HashMap::new(); - let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new(); - for node in &self.nodes { - pool.entry((node.internal, node.name.clone())).or_default().push_back(node); - if !is_group_kind(&node.kind) { - continue; - } - for (inner_op, inner_port, default) in instance_inputs(&node.raw) { - if let Some(d) = default { - instance_defaults.insert((inner_op, inner_port), d); - } - } - } - self.sync_tools_level(tools, false, &mut pool, &instance_defaults); - - // Sync BezierSpline edits (only touch splines that actually differ from the raw AST) - let mut spline_names: Vec<&String> = self.splines.keys().collect(); - spline_names.sort(); - for spline_name in spline_names { - let spline = &self.splines[spline_name]; - if let Some(tbl) = find_raw_tool_mut(tools, spline_name) { - sync_spline_table(spline_name, spline, tbl); - continue; - } - let mut sp_tbl = LuaTable { - tag: Some("BezierSpline".to_owned()), - entries: Vec::new(), - }; - sp_tbl.set( - LuaKey::Str("SplineColor".to_owned()), - spline_color_lua(spline.color), - ); - sp_tbl.set( - LuaKey::Str("KeyFrames".to_owned()), - LuaValue::Table(build_keyframes_table(spline)), - ); - tools.set(LuaKey::Str(spline_name.clone()), LuaValue::Table(sp_tbl)); - } - - root - } - - /// Syncs one `Tools` table level: drops deleted flow nodes (never modifiers), then syncs each - /// surviving node and recurses into Group/Macro operators' private `Tools`. - fn sync_tools_level<'a>( - &'a self, - tools: &mut LuaTable, - internal: bool, - pool: &mut HashMap<(bool, String), VecDeque<&'a Node>>, - instance_defaults: &HashMap<(&str, &str), ParamValue>, - ) { - tools.entries.retain(|(k, v)| { - let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true }; - is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) - || pool.get(&(internal, name.clone())).is_some_and(|q| !q.is_empty()) - }); - - for (k, v) in &mut tools.entries { - let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue }; - if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) { - continue; - } - let Some(node) = pool.get_mut(&(internal, name.clone())).and_then(VecDeque::pop_front) else { - continue; - }; - self.sync_node_tool(node, tool_tbl, instance_defaults); - if is_group_kind(&node.kind) { - if let Some(inner) = tool_tbl.get_table_mut("Tools") { - self.sync_tools_level(inner, true, pool, instance_defaults); - } - sync_group_wiring(node, tool_tbl); - } - } - } - - fn sync_node_tool( - &self, - node: &Node, - tool_tbl: &mut LuaTable, - instance_defaults: &HashMap<(&str, &str), ParamValue>, - ) { - // ViewInfo.Pos - if let Some(vi) = tool_tbl.get_table_mut("ViewInfo") { - let pos_changed = vi - .get_table("Pos") - .and_then(read_vec2) - .is_none_or(|[x, y]| { - (x as f32 - node.pos[0]).abs() > 1e-4 || (y as f32 - node.pos[1]).abs() > 1e-4 - }); - if pos_changed { - vi.set( - LuaKey::Str("Pos".to_owned()), - vec2_lua(node.pos[0] as f64, node.pos[1] as f64), - ); - } - } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 { - let mut vi = LuaTable { - tag: Some("OperatorInfo".to_owned()), - entries: Vec::new(), - }; - vi.set( - LuaKey::Str("Pos".to_owned()), - vec2_lua(node.pos[0] as f64, node.pos[1] as f64), - ); - tool_tbl.set(LuaKey::Str("ViewInfo".to_owned()), LuaValue::Table(vi)); - } - - // PassThrough - if node.bypassed { - tool_tbl.set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true)); - } else if tool_tbl.get("PassThrough").is_some() { - tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned())); - } - - // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`). - if !is_group_kind(&node.kind) { - let master_inputs = node - .raw - .get_str("SourceOp") - .and_then(|m| self.find_node(m)) - .map(|mid| &self.nodes[mid.0].inputs); - sync_node_inputs(node, master_inputs, instance_defaults, tool_tbl); - } - } - - /// Serializes this composition back to a Blackmagic Fusion `.comp` string. - pub fn to_fusion_string(&self) -> String { - let mut s = self.sync_to_raw_ast().to_fusion_string(); - if !s.ends_with('\n') { - s.push('\n'); - } - s - } - - /// Atomically saves this composition to `path`. - /// If `path` already exists, backs up the original bytes to - /// `/fission-backups/_.comp.bak` and returns `Ok(Some(backup_path))`. - pub fn save_to_file(&self, path: impl AsRef) -> Result, std::io::Error> { - let path = path.as_ref(); - let stem = path - .file_stem() - .and_then(|s| s.to_str()) - .filter(|s| !s.is_empty()) - .unwrap_or("comp"); - - let backup_path = if path.exists() { - let backup_dir = std::env::temp_dir().join("fission-backups"); - std::fs::create_dir_all(&backup_dir)?; - let unix_millis = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_millis()) - .unwrap_or(0); - let backup_file = backup_dir.join(format!("{stem}_{unix_millis}.comp.bak")); - std::fs::copy(path, &backup_file)?; - Some(backup_file) - } else { - None - }; - - let parent = path - .parent() - .filter(|p| !p.as_os_str().is_empty()) - .unwrap_or_else(|| Path::new(".")); - std::fs::create_dir_all(parent)?; - - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - let pid = std::process::id(); - let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp")); - - let serialized = self.to_fusion_string(); - if let Err(e) = std::fs::write(&tmp_path, serialized.as_bytes()) { - let _ = std::fs::remove_file(&tmp_path); - return Err(e); - } - if let Err(e) = std::fs::rename(&tmp_path, path) { - let _ = std::fs::remove_file(&tmp_path); - return Err(e); - } - - Ok(backup_path) - } -} - -pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue { - LuaValue::Table(LuaTable { - tag: None, - entries: vec![ - (LuaKey::Index(1), LuaValue::Number(x)), - (LuaKey::Index(2), LuaValue::Number(y)), - ], - }) -} - -pub(crate) fn ensure_table_mut<'a>(parent: &'a mut LuaTable, key: &str, tag: Option<&str>) -> &'a mut LuaTable { - if parent.get_table(key).is_none() { - parent.set( - LuaKey::Str(key.to_owned()), - LuaValue::Table(LuaTable { - tag: tag.map(str::to_owned), - entries: Vec::new(), - }), - ); - } - parent.get_table_mut(key).expect("table just inserted") -} - -pub(crate) fn param_value_to_lua(v: &ParamValue) -> LuaValue { - match v { - ParamValue::Number(n) => LuaValue::Number(*n), - ParamValue::Point([x, y]) => vec2_lua(*x, *y), - ParamValue::Text(s) => LuaValue::String(s.clone()), - ParamValue::FuId(s) => LuaValue::Table(LuaTable { - tag: Some("FuID".to_owned()), - entries: vec![(LuaKey::Index(1), LuaValue::String(s.clone()))], - }), - ParamValue::Gradient(g) => { - let mut colors = LuaTable::default(); - for stop in &g.stops { - let key = if stop.pos.fract() == 0.0 && stop.pos.abs() < 9_007_199_254_740_992.0 { - LuaKey::Index(stop.pos as i64) - } else { - LuaKey::Number(stop.pos) - }; - colors.entries.push(( - key, - LuaValue::Table(LuaTable { - tag: None, - entries: vec![ - (LuaKey::Index(1), LuaValue::Number(stop.rgba[0] as f64)), - (LuaKey::Index(2), LuaValue::Number(stop.rgba[1] as f64)), - (LuaKey::Index(3), LuaValue::Number(stop.rgba[2] as f64)), - (LuaKey::Index(4), LuaValue::Number(stop.rgba[3] as f64)), - ], - }), - )); - } - LuaValue::Table(LuaTable { - tag: Some("Gradient".to_owned()), - entries: vec![(LuaKey::Str("Colors".to_owned()), LuaValue::Table(colors))], - }) - } - ParamValue::Raw(raw) => raw.clone(), - } -} - -fn user_control_default(raw: &LuaTable, name: &str) -> Option { - let ut = raw.get_table("UserControls")?.get_table(name)?; - let is_point = ut.get_str("LINKID_DataType") == Some("Point") - || ut.get_str("INPID_InputControl") == Some("OffsetControl"); - if is_point { - let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5); - let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5); - Some(ParamValue::Point([dx, dy])) - } else { - ut.get("INP_Default").map(parse_param_value) - } -} - -pub(crate) fn is_group_kind(kind: &str) -> bool { - matches!(kind, "MacroOperator" | "GroupOperator") -} - -/// `(inner_op, inner_port, default)` for each `InstanceInput` exposed by a Group/Macro tool table. -fn instance_inputs(group: &LuaTable) -> impl Iterator)> { - group.get_table("Inputs").into_iter().flat_map(|inputs| { - inputs.entries.iter().filter_map(|(_, v)| { - let t = v.as_table()?; - Some((t.get_str("SourceOp")?, t.get_str("Source")?, t.get("Default").map(parse_param_value))) - }) - }) -} - -/// Writes external wires connected to a Group/Macro node back onto the inner tool inputs that its -/// `InstanceInput`s expose (load surfaces them as `node.inputs`). -fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) { - let exposed: Vec<(String, String, String)> = group_tbl - .get_table("Inputs") - .map(|inputs| { - inputs - .entries - .iter() - .filter_map(|(k, v)| { - let LuaKey::Str(in_name) = k else { return None }; - let t = v.as_table()?; - let port = if in_name.starts_with("MainInput") || in_name == "Input" { - "Input".to_owned() - } else { - in_name.clone() - }; - Some((port, t.get_str("SourceOp")?.to_owned(), t.get_str("Source")?.to_owned())) - }) - .collect() - }) - .unwrap_or_default(); - let Some(inner_tools) = group_tbl.get_table_mut("Tools") else { return }; - for (port, inner_op, inner_port) in exposed { - let desired = node.inputs.get(&port); - // Still the raw InstanceInput binding: nothing was rewired. - if desired.is_some_and(|b| b.source_op.as_deref() == Some(inner_op.as_str())) { - continue; - } - let Some(inner_tbl) = find_raw_tool_mut(inner_tools, &inner_op) else { continue }; - let current = inner_tbl - .get_table("Inputs") - .and_then(|i| i.get_table(&inner_port)) - .map(parse_input_binding); - let wired = |b: &InputBinding| (b.source_op.clone(), b.source_output.clone()); - match desired { - Some(b) if current.as_ref().map(wired) != Some(wired(b)) => { - let input = ensure_table_mut(ensure_table_mut(inner_tbl, "Inputs", None), &inner_port, Some("Input")); - for (key, val) in [("SourceOp", &b.source_op), ("Source", &b.source_output)] { - match val { - Some(v) => input.set(LuaKey::Str(key.to_owned()), LuaValue::String(v.clone())), - None => { - input.remove(&LuaKey::Str(key.to_owned())); - } - } - } - } - None if current.as_ref().is_some_and(|c| c.source_op.is_some()) => { - if let Some(input) = inner_tbl.get_table_mut("Inputs").and_then(|i| i.get_table_mut(&inner_port)) { - input.remove(&LuaKey::Str("SourceOp".to_owned())); - input.remove(&LuaKey::Str("Source".to_owned())); - } - } - _ => {} - } - } -} - -fn sync_node_inputs( - node: &Node, - master_inputs: Option<&HashMap>, - instance_defaults: &HashMap<(&str, &str), ParamValue>, - tool_tbl: &mut LuaTable, -) { - // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`. - if let Some(in_tbl) = tool_tbl.get_table_mut("Inputs") { - in_tbl.entries.retain(|(k, v)| { - let LuaKey::Str(port) = k else { return true }; - if v.as_table().is_none() { - return true; - } - node.inputs.contains_key(port) - }); - } - - // Collect sorted port names for deterministic output when appending new inputs. - let mut ports: Vec<&String> = node.inputs.keys().collect(); - ports.sort(); - - for port in ports { - let binding = &node.inputs[port]; - // Load fills unset inner-tool inputs from the enclosing group's `InstanceInput` default. - if binding.source_op.is_none() - && binding.expression.is_none() - && binding.value.is_some() - && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str())) - && tool_tbl - .get_table("Inputs") - .and_then(|i| i.get_table(port)) - .is_none_or(|t| parse_input_binding(t).value.is_none()) - { - continue; - } - let existing_binding = tool_tbl - .get_table("Inputs") - .and_then(|i| i.get_table(port)) - .map(parse_input_binding); - - if let Some(orig) = existing_binding { - if orig == *binding { - continue; - } - // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools. - if orig.value.is_none() - && orig.source_op.is_none() - && orig.expression.is_none() - && master_inputs.is_some_and(|m| m.get(port) == Some(binding)) - { - continue; - } - let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None); - if let Some(it) = in_tbl.get_table_mut(port) { - if orig.source_op != binding.source_op { - match &binding.source_op { - Some(op) => it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())), - None => { - it.remove(&LuaKey::Str("SourceOp".to_owned())); - } - } - } - if orig.source_output != binding.source_output { - match &binding.source_output { - Some(src) => it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone())), - None => { - it.remove(&LuaKey::Str("Source".to_owned())); - } - } - } - if orig.expression != binding.expression { - match &binding.expression { - Some(expr) => it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone())), - None => { - it.remove(&LuaKey::Str("Expression".to_owned())); - } - } - } - if orig.value != binding.value { - match &binding.value { - Some(val) => it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val)), - None => { - it.remove(&LuaKey::Str("Value".to_owned())); - } - } - } - if it.entries.is_empty() - && binding.value.is_none() - && binding.source_op.is_none() - && binding.source_output.is_none() - && binding.expression.is_none() - { - in_tbl.remove(&LuaKey::Str(port.clone())); - } - } - } else { - // Port did not exist in raw `Inputs`. - if binding.value.is_none() && binding.source_op.is_none() && binding.expression.is_none() { - continue; - } - // Don't pollute `Inputs` with unedited `UserControls` defaults synthesized during load. - if binding.source_op.is_none() - && binding.expression.is_none() - && binding.value.is_some() - && binding.value == user_control_default(&node.raw, port) - { - continue; - } - // Don't duplicate inherited master inputs onto instanced tools. - if let Some(master) = master_inputs { - if master.get(port) == Some(binding) { - continue; - } - } - - let mut it = LuaTable { - tag: Some("Input".to_owned()), - entries: Vec::new(), - }; - if let Some(op) = &binding.source_op { - it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())); - } - if let Some(src) = &binding.source_output { - it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone())); - } - if let Some(val) = &binding.value { - it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val)); - } - if let Some(expr) = &binding.expression { - it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone())); - } - let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None); - in_tbl.set(LuaKey::Str(port.clone()), LuaValue::Table(it)); - } - } -} - -fn spline_color_lua(color: [u8; 3]) -> LuaValue { - LuaValue::Table(LuaTable { - tag: None, - entries: vec![ - (LuaKey::Str("Red".to_owned()), LuaValue::Number(color[0] as f64)), - (LuaKey::Str("Green".to_owned()), LuaValue::Number(color[1] as f64)), - (LuaKey::Str("Blue".to_owned()), LuaValue::Number(color[2] as f64)), - ], - }) -} - -fn build_keyframes_table(spline: &BezierSpline) -> LuaTable { - let mut kfs = spline.keyframes.clone(); - kfs.sort_by(|a, b| a.time.total_cmp(&b.time)); - let mut tbl = LuaTable::default(); - for kf in kfs { - let key = if kf.time.fract() == 0.0 && kf.time.abs() < 9_007_199_254_740_992.0 { - LuaKey::Index(kf.time as i64) - } else { - LuaKey::Number(kf.time) - }; - let mut entry = LuaTable::default(); - entry.entries.push((LuaKey::Index(1), LuaValue::Number(kf.value))); - if let Some([lx, ly]) = kf.lh { - entry.entries.push((LuaKey::Str("LH".to_owned()), vec2_lua(lx, ly))); - } - if let Some([rx, ry]) = kf.rh { - entry.entries.push((LuaKey::Str("RH".to_owned()), vec2_lua(rx, ry))); - } - let mut flags = LuaTable::default(); - if kf.flags.linear { - flags.entries.push((LuaKey::Str("Linear".to_owned()), LuaValue::Bool(true))); - } - if kf.flags.step_in { - flags.entries.push((LuaKey::Str("StepIn".to_owned()), LuaValue::Bool(true))); - } - if kf.flags.step_out { - flags.entries.push((LuaKey::Str("StepOut".to_owned()), LuaValue::Bool(true))); - } - if kf.flags.loop_after { - flags.entries.push((LuaKey::Str("Loop".to_owned()), LuaValue::Bool(true))); - } - if kf.flags.loop_rel { - flags.entries.push((LuaKey::Str("LoopRel".to_owned()), LuaValue::Bool(true))); - } - if kf.flags.ping_pong { - flags.entries.push((LuaKey::Str("PingPong".to_owned()), LuaValue::Bool(true))); - } - if kf.flags.locked_y { - flags.entries.push((LuaKey::Str("LockedY".to_owned()), LuaValue::Bool(true))); - } - if !flags.entries.is_empty() { - entry.entries.push((LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags))); - } - tbl.entries.push((key, LuaValue::Table(entry))); - } - tbl -} - -fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) { - let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl); - if existing.color != spline.color { - tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color)); - } - let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && { - let mut normalized = existing.clone(); - normalized.apply_hue_curves_cyclic_ends(); - normalized.keyframes == spline.keyframes - }; - if existing.keyframes != spline.keyframes && !unchanged_cyclic { - let new_kfs = LuaValue::Table(build_keyframes_table(spline)); - if tbl.tag.as_deref() == Some("LUTBezier") && tbl.get_table("KeyColorSplines").is_some() { - if let Some(kcs) = tbl.get_table_mut("KeyColorSplines") { - kcs.set(LuaKey::Index(0), new_kfs); - } - } else { - tbl.set(LuaKey::Str("KeyFrames".to_owned()), new_kfs); - } - } -} - -fn is_non_inheritable_instance_port( - name: &str, - binding: &InputBinding, - node_by_name: &HashMap, -) -> bool { - if matches!( - name, - "Input" - | "Background" - | "Foreground" - | "EffectMask" - | "MaterialInput" - | "GarbageMatte" - | "SolidMatte" - | "Mask" - | "TrackingMask" - | "RegionMask" - | "MatchReference" - | "MatchMask" - | "Image" - | "Image1" - | "Image2" - | "BlurImage" - | "DisplaceImage" - ) || name.starts_with("SceneInput") - || name.starts_with("MainInput") - { - return true; - } - // Never inherit flow-graph image/scene/material connections targeting another flow node; - // modifiers (`BezierSpline`, `PolyPath`, `Shake`, `Expression`, etc.) are not in `node_by_name`. - binding.value.is_none() - && binding.expression.is_none() - && binding - .source_op - .as_deref() - .is_some_and(|op| node_by_name.contains_key(op)) } pub fn default_main_input_port(kind: &str) -> &'static str { @@ -2442,1319 +606,3 @@ pub fn default_main_input_port(kind: &str) -> &'static str { _ => "Input", } } - -fn parse_input_binding(t: &LuaTable) -> InputBinding { - let source_op = t.get_str("SourceOp").map(str::to_owned); - let source_output = t.get_str("Source").map(str::to_owned); - let expression = t.get_str("Expression").map(str::to_owned); - - let value = t.get("Value").map(parse_param_value); - InputBinding { - value, - source_op, - source_output, - expression, - } -} - -fn parse_param_value(v: &LuaValue) -> ParamValue { - match v { - LuaValue::Number(n) => ParamValue::Number(*n), - LuaValue::Bool(b) => ParamValue::Number(if *b { 1.0 } else { 0.0 }), - LuaValue::String(s) => ParamValue::Text(s.clone()), - LuaValue::Table(t) => match t.tag.as_deref() { - Some("FuID") => ParamValue::FuId( - t.get_index(1) - .and_then(LuaValue::as_str) - .unwrap_or("") - .to_owned(), - ), - Some("Number") => ParamValue::Number(t.get_f64("Value").unwrap_or(0.0)), - Some("Gradient") => ParamValue::Gradient(Gradient::from_lua(t)), - _ => { - if let Some(p) = read_vec2(t) { - ParamValue::Point(p) - } else { - ParamValue::Raw(v.clone()) - } - } - }, - LuaValue::Nil => ParamValue::Raw(LuaValue::Nil), - } -} - -fn try_parse_gradient_keyframes(table: &LuaTable) -> Option> { - let kfs = table.get_table("KeyFrames")?; - let mut grads = Vec::new(); - for (k, v) in &kfs.entries { - let time = match k { - LuaKey::Index(i) => *i as f64, - LuaKey::Number(n) => *n, - _ => continue, - }; - let kt = v.as_table()?; - let val = kt - .get_table("Value") - .or_else(|| kt.get_index(1).and_then(LuaValue::as_table))?; - if val.tag.as_deref() == Some("Gradient") { - grads.push((time, Gradient::from_lua(val))); - } else { - return None; - } - } - if grads.is_empty() { - return None; - } - grads.sort_by(|a, b| a.0.total_cmp(&b.0)); - Some(grads) -} - -fn try_parse_text_keyframes(table: &LuaTable) -> Option> { - let kfs = table.get_table("KeyFrames")?; - let mut texts = Vec::new(); - for (k, v) in &kfs.entries { - let time = match k { - LuaKey::Index(i) => *i as f64, - LuaKey::Number(n) => *n, - _ => continue, - }; - let kt = v.as_table()?; - let val = kt.get_table("Value")?; - if matches!(val.tag.as_deref(), Some("Text" | "StyledText")) { - let s = val.get_str("Value").unwrap_or("").to_owned(); - texts.push((time, s)); - } else { - return None; - } - } - if texts.is_empty() { - return None; - } - texts.sort_by(|a, b| a.0.total_cmp(&b.0)); - Some(texts) -} - -fn try_parse_polyline_keyframes(table: &LuaTable) -> Option)>> { - let kfs = table.get_table("KeyFrames")?; - let mut shapes = Vec::new(); - for (k, v) in &kfs.entries { - let time = match k { - LuaKey::Index(i) => *i as f64, - LuaKey::Number(n) => *n, - _ => continue, - }; - let kt = v.as_table()?; - let val = kt.get_table("Value")?; - if val.tag.as_deref() == Some("Polyline") { - let (_, pts) = PolyPath::parse_polyline_table(val); - shapes.push((time, pts)); - } else { - return None; - } - } - if shapes.is_empty() { - return None; - } - shapes.sort_by(|a, b| a.0.total_cmp(&b.0)); - Some(shapes) -} - -#[allow(clippy::too_many_arguments)] -fn parse_tools_table( - tools: &LuaTable, - is_internal: bool, - nodes: &mut Vec, - node_by_name: &mut HashMap, - splines: &mut HashMap, - poly_paths: &mut HashMap, - gradient_modifiers: &mut HashMap>, - text_modifiers: &mut HashMap, - text_splines: &mut HashMap>, - polyline_splines: &mut HashMap)>)>, - text_cls: &mut HashMap>, - shakes: &mut HashMap, - expression_modifiers: &mut HashMap, - tracker_aliases: &mut Vec<(String, String)>, - macro_defaults: &mut Vec<(String, String, ParamValue)>, - instanced_from: &mut Vec<(NodeId, String)>, -) { - for (key, val) in &tools.entries { - let LuaKey::Str(name) = key else { continue }; - let Some(tbl) = val.as_table() else { continue }; - let kind = tbl.tag.clone().unwrap_or_else(|| "Unknown".to_owned()); - - if kind == "BezierSpline" || kind == "LUTBezier" { - if let Some(grads) = try_parse_gradient_keyframes(tbl) { - gradient_modifiers.insert(name.clone(), grads); - } else if let Some(txts) = try_parse_text_keyframes(tbl) { - text_splines.insert(name.clone(), txts); - } else if let Some(polys) = try_parse_polyline_keyframes(tbl) { - polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), polys)); - } else { - splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); - } - continue; - } - if kind == "PolyPath" || kind == "Path" { - poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl)); - continue; - } - if kind == "TrackerModifier" { - if let Some(in_tbl) = tbl.get_table("Inputs") { - if let Some(src_op) = in_tbl - .get_table("TrackedCenter0") - .and_then(|c| c.get_str("SourceOp")) - { - tracker_aliases.push((name.clone(), src_op.to_owned())); - } else if let Some(p) = in_tbl - .get_table("PatternCenter0") - .and_then(|c| c.get_table("Value")) - .and_then(read_vec2) - { - poly_paths.insert( - name.clone(), - PolyPath { - name: name.clone(), - displacement_op: None, - displacement_value: 0.0, - closed: false, - points: vec![crate::spline::PolyPoint { - x: p[0] - 0.5, - y: p[1] - 0.5, - lx: 0.0, - ly: 0.0, - rx: 0.0, - ry: 0.0, - linear: true, - }], - }, - ); - } - } - continue; - } - if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" { - if let Some(in_tbl) = tbl.get_table("Inputs") { - if let Some(txt) = in_tbl - .get_table("Text") - .or_else(|| in_tbl.get_table("StyledText")) - .and_then(|s| s.get_str("Value")) - { - text_modifiers.insert(name.clone(), txt.to_owned()); - } - if let Some(arr) = in_tbl - .get_table("CharacterLevelStyling") - .and_then(|c| c.get_table("Value")) - .and_then(|v| v.get_table("Array")) - { - let mut entries = Vec::new(); - for (_, ev) in &arr.entries { - let Some(et) = ev.as_table() else { continue }; - let Some(pid) = et.get_index(1).and_then(LuaValue::as_f64) else { continue }; - let Some(s) = et.get_index(2).and_then(LuaValue::as_f64) else { continue }; - let Some(e) = et.get_index(3).and_then(LuaValue::as_f64) else { continue }; - let Some(val) = et.get_f64("Value") else { continue }; - entries.push(ClsEntry { - prop_id: pid.round().max(0.0) as u32, - start: s.round().max(0.0) as usize, - end: e.round().max(0.0) as usize, - value: val as f32, - }); - } - if !entries.is_empty() { - text_cls.insert(name.clone(), entries); - } - } - } - continue; - } - if kind == "Shake" { - let mut inputs = HashMap::new(); - if let Some(in_tbl) = tbl.get_table("Inputs") { - for (ik, iv) in &in_tbl.entries { - let LuaKey::Str(in_name) = ik else { continue }; - let Some(it) = iv.as_table() else { continue }; - inputs.insert(in_name.clone(), parse_input_binding(it)); - } - } - shakes.insert(name.clone(), ShakeModifier { inputs }); - continue; - } - if kind == "Expression" { - let mut inputs = HashMap::new(); - if let Some(in_tbl) = tbl.get_table("Inputs") { - for (ik, iv) in &in_tbl.entries { - let LuaKey::Str(in_name) = ik else { continue }; - let Some(it) = iv.as_table() else { continue }; - inputs.insert(in_name.clone(), parse_input_binding(it)); - } - } - if let Some(uc) = tbl.get_table("UserControls") { - for (uk, uv) in &uc.entries { - let LuaKey::Str(uname) = uk else { continue }; - let Some(ut) = uv.as_table() else { continue }; - let missing = inputs.get(uname).is_none_or(|b| { - b.value.is_none() && b.source_op.is_none() && b.expression.is_none() - }); - if missing { - if let Some(val) = ut.get("INP_Default").map(parse_param_value) { - inputs.insert( - uname.clone(), - InputBinding { - value: Some(val), - source_op: None, - source_output: None, - expression: None, - }, - ); - } - } - } - } - expression_modifiers.insert(name.clone(), ExpressionModifier { inputs }); - continue; - } - if is_modifier_type(&kind) { - if tbl.get_table("KeyFrames").is_some() { - splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); - } - continue; - } - - let pos = tbl - .get_table("ViewInfo") - .and_then(|vi| vi.get_table("Pos")) - .and_then(read_vec2) - .map(|[x, y]| [x as f32, y as f32]) - .unwrap_or([0.0, 0.0]); - let bypassed = tbl.get_bool("PassThrough").unwrap_or(false); - - let mut inputs = HashMap::new(); - if let Some(in_tbl) = tbl.get_table("Inputs") { - for (ik, iv) in &in_tbl.entries { - let LuaKey::Str(in_name) = ik else { continue }; - let Some(it) = iv.as_table() else { continue }; - let binding = parse_input_binding(it); - if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { - if let (Some(src_op), Some(src_param)) = (&binding.source_op, &binding.source_output) { - if let Some(def_v) = it.get("Default") { - macro_defaults.push((src_op.clone(), src_param.clone(), parse_param_value(def_v))); - } - } - } - inputs.insert(in_name.clone(), binding); - } - } - - // Populate defaults declared in Fusion `UserControls` (needed for ShakeTransform, Custom, etc.) - if let Some(uc) = tbl.get_table("UserControls") { - for (uk, uv) in &uc.entries { - let LuaKey::Str(uname) = uk else { continue }; - let Some(ut) = uv.as_table() else { continue }; - let missing = inputs.get(uname).is_none_or(|b| { - b.value.is_none() && b.source_op.is_none() && b.expression.is_none() - }); - if missing { - let is_point = ut.get_str("LINKID_DataType") == Some("Point") - || ut.get_str("INPID_InputControl") == Some("OffsetControl"); - let def_val = if is_point { - let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5); - let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5); - Some(ParamValue::Point([dx, dy])) - } else { - ut.get("INP_Default").map(parse_param_value) - }; - if let Some(val) = def_val { - inputs.insert( - uname.clone(), - InputBinding { - value: Some(val), - source_op: None, - source_output: None, - expression: None, - }, - ); - } - } - } - } - - let mut clips = Vec::new(); - if let Some(clips_tbl) = tbl.get_table("Clips") { - for (_, cv) in &clips_tbl.entries { - if let Some(ct) = cv.as_table() { - if let Some(filename) = ct.get_str("Filename") { - clips.push(ClipSpec { - filename: filename.to_owned(), - alternate_filename: ct.get_str("AlternateFilename").map(str::to_owned), - start_frame: ct.get_f64("StartFrame").unwrap_or(-1.0) as i64, - length: ct.get_f64("Length").map(|v| v as i64), - trim_in: ct.get_f64("TrimIn").unwrap_or(0.0) as i64, - trim_out: ct.get_f64("TrimOut").unwrap_or(0.0) as i64, - global_start: ct.get_f64("GlobalStart").unwrap_or(0.0) as i64, - global_end: ct.get_f64("GlobalEnd").unwrap_or(0.0) as i64, - extend_first: ct.get_f64("ExtendFirst").unwrap_or(0.0) as i64, - extend_last: ct.get_f64("ExtendLast").unwrap_or(0.0) as i64, - loop_clip: ct.get_f64("Loop").unwrap_or(0.0) > 0.5, - reverse: ct.get_bool("Reverse").unwrap_or(false), - }); - } - } - } - } - - if kind == "Saver" && clips.is_empty() { - if let Some(c) = tbl - .get_table("Inputs") - .and_then(|i| i.get_table("Clip")) - .and_then(|c| c.get_table("Value")) - { - if let Some(filename) = c.get_str("Filename") { - clips.push(ClipSpec { - filename: filename.to_owned(), - alternate_filename: None, - start_frame: 0, - length: None, - trim_in: 0, - trim_out: 0, - global_start: 0, - global_end: 0, - extend_first: 0, - extend_last: 0, - loop_clip: false, - reverse: false, - }); - } - } - } - - // ColorCurves and HueCurves embed their LUTBezier splines inside a nested `Tools` table! - if kind == "ColorCurves" || kind == "HueCurves" { - if let Some(inner_tools) = tbl.get_table("Tools") { - parse_tools_table( - inner_tools, - true, - nodes, - node_by_name, - splines, - poly_paths, - gradient_modifiers, - text_modifiers, - text_splines, - polyline_splines, - text_cls, - shakes, - expression_modifiers, - tracker_aliases, - macro_defaults, - instanced_from, - ); - } - } - - let mut macro_output = None; - if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { - let mut out_name: Option = None; - if let Some(outs) = tbl.get_table("Outputs") { - for (_, ov) in &outs.entries { - if let Some(ot) = ov.as_table() { - if let Some(src_op) = ot.get_str("SourceOp") { - out_name = Some(src_op.to_owned()); - break; - } - } - } - } - let inner_start = nodes.len(); - if let Some(inner_tools) = tbl.get_table("Tools") { - parse_tools_table( - inner_tools, - true, - nodes, - node_by_name, - splines, - poly_paths, - gradient_modifiers, - text_modifiers, - text_splines, - polyline_splines, - text_cls, - shakes, - expression_modifiers, - tracker_aliases, - macro_defaults, - instanced_from, - ); - } - if let Some(oname) = out_name { - macro_output = nodes[inner_start..] - .iter() - .find(|n| n.name == oname) - .map(|n| n.id) - .or_else(|| node_by_name.get(&oname).copied()); - } - } - - let id = NodeId(nodes.len()); - // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name. - if !is_internal || !node_by_name.contains_key(name) { - node_by_name.insert(name.clone(), id); - } - if let Some(master) = tbl.get_str("SourceOp") { - instanced_from.push((id, master.to_owned())); - } - nodes.push(Node { - id, - name: name.clone(), - kind, - pos, - bypassed, - internal: is_internal, - macro_output, - inputs, - clips, - raw: tbl.clone(), - }); - } -} - -/// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`. -/// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`. -fn eval_fusion_math_expr(src: &str, vars: &HashMap) -> Option { - struct Parser<'a> { - bytes: &'a [u8], - pos: usize, - vars: &'a HashMap, - } - - impl<'a> Parser<'a> { - fn skip_ws(&mut self) { - while self.pos < self.bytes.len() { - let b = self.bytes[self.pos]; - if b.is_ascii_whitespace() { - self.pos += 1; - } else if b == b'/' && self.bytes.get(self.pos + 1) == Some(&b'/') { - while self.pos < self.bytes.len() && self.bytes[self.pos] != b'\n' { - self.pos += 1; - } - } else { - break; - } - } - } - - fn peek(&mut self) -> Option { - self.skip_ws(); - self.bytes.get(self.pos).copied() - } - - fn eat_str(&mut self, s: &str) -> bool { - self.skip_ws(); - if self.bytes[self.pos..].starts_with(s.as_bytes()) { - self.pos += s.len(); - true - } else { - false - } - } - - fn parse_or(&mut self) -> Option { - let mut v = self.parse_and()?; - loop { - self.skip_ws(); - if self.eat_str("||") || self.eat_str("|") { - let r = self.parse_and()?; - v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 }; - } else { - break; - } - } - Some(v) - } - - fn parse_and(&mut self) -> Option { - let mut v = self.parse_cmp()?; - loop { - self.skip_ws(); - if self.eat_str("&&") || self.eat_str("&") { - let r = self.parse_cmp()?; - v = if v != 0.0 && r != 0.0 { 1.0 } else { 0.0 }; - } else { - break; - } - } - Some(v) - } - - fn parse_cmp(&mut self) -> Option { - let mut v = self.parse_add()?; - loop { - self.skip_ws(); - if self.eat_str("<=") { - let r = self.parse_add()?; - v = if v <= r { 1.0 } else { 0.0 }; - } else if self.eat_str(">=") { - let r = self.parse_add()?; - v = if v >= r { 1.0 } else { 0.0 }; - } else if self.eat_str("==") || self.eat_str("=") { - let r = self.parse_add()?; - v = if (v - r).abs() <= 1e-12 { 1.0 } else { 0.0 }; - } else if self.eat_str("!=") || self.eat_str("~=") || self.eat_str("<>") { - let r = self.parse_add()?; - v = if (v - r).abs() > 1e-12 { 1.0 } else { 0.0 }; - } else if self.eat_str("<") { - let r = self.parse_add()?; - v = if v < r { 1.0 } else { 0.0 }; - } else if self.eat_str(">") { - let r = self.parse_add()?; - v = if v > r { 1.0 } else { 0.0 }; - } else { - break; - } - } - Some(v) - } - - fn parse_add(&mut self) -> Option { - let mut v = self.parse_mul()?; - loop { - match self.peek() { - Some(b'+') => { - self.pos += 1; - v += self.parse_mul()?; - } - Some(b'-') => { - self.pos += 1; - v -= self.parse_mul()?; - } - _ => break, - } - } - Some(v) - } - - fn parse_mul(&mut self) -> Option { - let mut v = self.parse_pow()?; - loop { - match self.peek() { - Some(b'*') => { - self.pos += 1; - v *= self.parse_pow()?; - } - Some(b'/') => { - self.pos += 1; - let r = self.parse_pow()?; - v = if r.abs() < 1e-12 { 0.0 } else { v / r }; - } - Some(b'%') => { - self.pos += 1; - let r = self.parse_pow()?; - v = if r.abs() < 1e-12 { 0.0 } else { v - r * (v / r).floor() }; - } - _ => break, - } - } - Some(v) - } - - fn parse_pow(&mut self) -> Option { - let base = self.parse_unary()?; - if self.peek() == Some(b'^') { - self.pos += 1; - let exp = self.parse_pow()?; - Some(if base > 0.0 { - base.powf(exp) - } else if base == 0.0 { - if exp == 0.0 { 1.0 } else { 0.0 } - } else if (exp - exp.round()).abs() < 1e-6 { - let p = base.abs().powf(exp); - if (exp.round() as i64) & 1 != 0 { -p } else { p } - } else { - 0.0 - }) - } else { - Some(base) - } - } - - fn parse_unary(&mut self) -> Option { - match self.peek() { - Some(b'-') => { - self.pos += 1; - Some(-self.parse_unary()?) - } - Some(b'+') => { - self.pos += 1; - self.parse_unary() - } - Some(b'!') => { - self.pos += 1; - let v = self.parse_unary()?; - Some(if v == 0.0 { 1.0 } else { 0.0 }) - } - _ => self.parse_primary(), - } - } - - fn parse_primary(&mut self) -> Option { - let b = self.peek()?; - if b == b'(' { - self.pos += 1; - let v = self.parse_or()?; - if self.peek() != Some(b')') { - return None; - } - self.pos += 1; - return Some(v); - } - if b.is_ascii_digit() || b == b'.' { - let start = self.pos; - while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { - self.pos += 1; - } - if self.bytes.get(self.pos) == Some(&b'.') { - self.pos += 1; - while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { - self.pos += 1; - } - } - if matches!(self.bytes.get(self.pos), Some(b'e' | b'E')) { - let exp_pos = self.pos; - self.pos += 1; - if matches!(self.bytes.get(self.pos), Some(b'+' | b'-')) { - self.pos += 1; - } - let dig_start = self.pos; - while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { - self.pos += 1; - } - if self.pos == dig_start { - self.pos = exp_pos; - } - } - let s = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?; - return s.parse::().ok(); - } - if b.is_ascii_alphabetic() || b == b'_' { - let start = self.pos; - while self.pos < self.bytes.len() - && (self.bytes[self.pos].is_ascii_alphanumeric() || self.bytes[self.pos] == b'_') - { - self.pos += 1; - } - let ident = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?; - if self.peek() == Some(b'(') { - self.pos += 1; - let mut args = Vec::new(); - if self.peek() != Some(b')') { - loop { - args.push(self.parse_or()?); - if self.peek() == Some(b',') { - self.pos += 1; - } else { - break; - } - } - } - if self.peek() != Some(b')') { - return None; - } - self.pos += 1; - return Self::eval_fn(ident, &args); - } - return self.vars.get(ident).copied(); - } - None - } - - fn eval_fn(name: &str, args: &[f64]) -> Option { - const DEG2RAD: f64 = std::f64::consts::PI / 180.0; - const RAD2DEG: f64 = 180.0 / std::f64::consts::PI; - let a = |i: usize| args.get(i).copied(); - Some(match name { - "sin" => (a(0)? * DEG2RAD).sin(), - "cos" => (a(0)? * DEG2RAD).cos(), - "tan" => (a(0)? * DEG2RAD).tan(), - "asin" => a(0)?.clamp(-1.0, 1.0).asin() * RAD2DEG, - "acos" => a(0)?.clamp(-1.0, 1.0).acos() * RAD2DEG, - "atan" => a(0)?.atan() * RAD2DEG, - "atan2" => a(0)?.atan2(a(1)?) * RAD2DEG, - "sinr" => a(0)?.sin(), - "cosr" => a(0)?.cos(), - "tanr" => a(0)?.tan(), - "asinr" => a(0)?.clamp(-1.0, 1.0).asin(), - "acosr" => a(0)?.clamp(-1.0, 1.0).acos(), - "atanr" => a(0)?.atan(), - "atan2r" => a(0)?.atan2(a(1)?), - "sinh" => a(0)?.sinh(), - "cosh" => a(0)?.cosh(), - "tanh" => a(0)?.tanh(), - "deg" => a(0)? * RAD2DEG, - "rad" => a(0)? * DEG2RAD, - "abs" => a(0)?.abs(), - "sqrt" => a(0)?.max(0.0).sqrt(), - "pow" => a(0)?.powf(a(1)?), - "exp" => a(0)?.exp(), - "log" | "ln" => a(0)?.max(1e-12).ln(), - "log10" => a(0)?.max(1e-12).log10(), - "log2" => a(0)?.max(1e-12).log2(), - "floor" | "int" => a(0)?.floor(), - "ceil" => a(0)?.ceil(), - "round" => a(0)?.round(), - "trunc" => a(0)?.trunc(), - "fract" => a(0)? - a(0)?.floor(), - "sign" => { - let v = a(0)?; - if v > 0.0 { 1.0 } else if v < 0.0 { -1.0 } else { 0.0 } - } - "min" => { - if args.is_empty() { return None; } - args.iter().copied().fold(f64::INFINITY, f64::min) - } - "max" => { - if args.is_empty() { return None; } - args.iter().copied().fold(f64::NEG_INFINITY, f64::max) - } - "clamp" => a(0)?.max(a(1)?).min(a(2)?), - "mod" => { - let (x, y) = (a(0)?, a(1)?); - if y.abs() < 1e-12 { 0.0 } else { x - y * (x / y).floor() } - } - "if" | "iif" => { - if a(0)? != 0.0 { a(1)? } else { a(2)? } - } - "dist" => { - let (x1, y1, x2, y2) = (a(0)?, a(1)?, a(2)?, a(3)?); - ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt() - } - "hypot" => a(0)?.hypot(a(1)?), - "mix" | "lerp" => { - let (x, y, t) = (a(0)?, a(1)?, a(2)?); - x + (y - x) * t - } - "step" => if a(1)? < a(0)? { 0.0 } else { 1.0 }, - "smoothstep" => { - let (e0, e1, x) = (a(0)?, a(1)?, a(2)?); - let denom = e1 - e0; - let t = if denom.abs() < 1e-12 { 0.0 } else { ((x - e0) / denom).clamp(0.0, 1.0) }; - t * t * (3.0 - 2.0 * t) - } - _ => return None, - }) - } - } - - let mut p = Parser { - bytes: src.as_bytes(), - pos: 0, - vars, - }; - let val = p.parse_or()?; - p.skip_ws(); - if p.pos != p.bytes.len() || !val.is_finite() { - return None; - } - Some(val) -} - -#[cfg(test)] -mod expression_modifier_tests { - use super::*; - - #[test] - fn evaluates_standalone_expression_modifier_number_and_chained() { - let src = r#"Composition { - Tools = ordered() { - XF1 = Transform { - Inputs = { - Angle = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", }, - Size = Input { SourceOp = "HourHandExpr", Source = "NumberResult", }, - }, - }, - Clock_MinHandExpr = Expression { - Inputs = { - n1 = Input { Value = 1, }, - n2 = Input { SourceOp = "TimeSpline", Source = "Value", }, - NumberExpression = Input { Value = "if(n1>0.5,floor(-n2)*30,-n2*30)", }, - }, - }, - HourHandExpr = Expression { - Inputs = { - n1 = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", }, - NumberExpression = Input { Value = "n1/12", }, - }, - }, - TimeSpline = BezierSpline { - KeyFrames = { - [0] = { 0.0, Flags = { Linear = true } }, - [10] = { 2.5, Flags = { Linear = true } }, - }, - }, - }, - }"#; - - let comp = Comp::from_fusion_str(src).expect("parse comp"); - assert!(comp.expression_modifiers.contains_key("Clock_MinHandExpr")); - assert!(comp.expression_modifiers.contains_key("HourHandExpr")); - // Expression modifiers are modifiers, not flow nodes - assert!(comp.find_node("Clock_MinHandExpr").is_none()); - - let expr = ExprEngine::new(); - let xf = comp.node(comp.find_node("XF1").unwrap()); - // At t=10: n2 = 2.5, floor(-2.5) = -3.0, -3.0 * 30 = -90.0 - let angle = comp.eval_number(xf, "Angle", 10.0, 0.0, &expr); - assert!((angle - (-90.0)).abs() < 1e-6, "got {angle}"); - // Chained HourHandExpr: n1 / 12 = -90 / 12 = -7.5 - let size = comp.eval_number(xf, "Size", 10.0, 1.0, &expr); - assert!((size - (-7.5)).abs() < 1e-6, "got {size}"); - - // Lossless roundtrip preserves Expression modifiers - let saved = comp.to_fusion_string(); - let reloaded = Comp::from_fusion_str(&saved).expect("reload"); - let r_xf = reloaded.node(reloaded.find_node("XF1").unwrap()); - assert!((reloaded.eval_number(r_xf, "Angle", 10.0, 0.0, &expr) - (-90.0)).abs() < 1e-6); - } - - #[test] - fn evaluates_standalone_expression_modifier_point_and_dist_trig() { - let src = r#"Composition { - Tools = ordered() { - XF1 = Transform { - Inputs = { - Center = Input { SourceOp = "PtExpr", Source = "PointResult", }, - Angle = Input { SourceOp = "TrigExpr", Source = "NumberResult", }, - }, - }, - PtExpr = Expression { - Inputs = { - p1 = Input { Value = { 0.8, 0.2 }, }, - n1 = Input { Value = 10, }, - PointExpressionX = Input { Value = "if(p1x>0.5, 0.5 + time*dist(p1x,p1y,0.5,p1y)/n1, 0.5)", }, - PointExpressionY = Input { Value = "-p1y + p1y*0.5 + 0.5", }, - }, - }, - TrigExpr = Expression { - Inputs = { - NumberIn1 = Input { Value = 90, }, - NumberExpression = Input { Value = "sin(n1) + cos(0) + (1/0)", }, - }, - }, - }, - }"#; - - let comp = Comp::from_fusion_str(src).expect("parse comp"); - let expr = ExprEngine::new(); - let xf = comp.node(comp.find_node("XF1").unwrap()); - // At t=5: dist(0.8,0.2,0.5,0.2) = 0.3, x = 0.5 + 5*0.3/10 = 0.65, y = -0.2 + 0.1 + 0.5 = 0.4 - let pt = comp.eval_point(xf, "Center", 5.0, [0.5, 0.5], &expr); - assert!((pt[0] - 0.65).abs() < 1e-6, "got x={}", pt[0]); - assert!((pt[1] - 0.40).abs() < 1e-6, "got y={}", pt[1]); - // sin(90 deg) + cos(0 deg) + safe_div(1,0) = 1 + 1 + 0 = 2.0 - let ang = comp.eval_number(xf, "Angle", 0.0, 0.0, &expr); - assert!((ang - 2.0).abs() < 1e-6, "got {ang}"); - } - - #[test] - fn resolves_instanced_source_op_inheritance_chains_and_keeps_image_wires_isolated() { - let src = r#"Composition { - Tools = ordered() { - Loader1 = Loader {}, - Transform2 = Transform { - Inputs = { - Input = Input { SourceOp = "Loader1", Source = "Output", }, - }, - }, - Ellipse1 = EllipseMask {}, - ColorCorrector1_6Blend = BezierSpline { - KeyFrames = { - [0] = { 0.25, Flags = { Linear = true } }, - [10] = { 0.75, Flags = { Linear = true } }, - }, - }, - ColorCorrector1_6 = ColorCorrector { - Inputs = { - Blend = Input { SourceOp = "ColorCorrector1_6Blend", Source = "Value", }, - WheelTintAngle1 = Input { Value = -0.434283, }, - WheelHue1 = Input { Value = 0.2, }, - PreDividePostMultiply = Input { Value = 1, }, - Input = Input { SourceOp = "Loader1", Source = "Output", }, - EffectMask = Input { SourceOp = "Ellipse1", Source = "Mask", }, - }, - }, - Instance_ColorCorrector1_6 = ColorCorrector { - SourceOp = "ColorCorrector1_6", - Inputs = { - Input = Input { SourceOp = "Transform2", Source = "Output", }, - EffectMask = Input {}, - WheelTintAngle1 = Input {}, - WheelHue1 = Input { Value = 0.9, }, - }, - }, - Instance_Chained = ColorCorrector { - SourceOp = "Instance_ColorCorrector1_6", - Inputs = { - Input = Input { SourceOp = "Loader1", Source = "Output", }, - }, - }, - CycleA = Blur { - SourceOp = "CycleB", - Inputs = { - XBlurSize = Input { Value = 3.0, }, - }, - }, - CycleB = Blur { - SourceOp = "CycleA", - Inputs = { - YBlurSize = Input { Value = 7.0, }, - }, - }, - }, - }"#; - - let comp = Comp::from_fusion_str(src).expect("parse instanced comp"); - let expr = ExprEngine::new(); - - let inst = comp.node(comp.find_node("Instance_ColorCorrector1_6").unwrap()); - // Empty `WheelTintAngle1 = Input {}` is a de-instanced override (falls back to tool default), - // while omitted params (`Blend`, `PreDividePostMultiply`) inherit from master! - let tint = comp.eval_number(inst, "WheelTintAngle1", 0.0, 0.0, &expr); - assert!(tint.abs() < 1e-6, "de-instanced empty Input {{}} must not inherit master value, got {tint}"); - let blend_t5 = comp.eval_number(inst, "Blend", 5.0, 1.0, &expr); - assert!((blend_t5 - 0.5).abs() < 1e-6, "got {blend_t5}"); - let pdpm = comp.eval_number(inst, "PreDividePostMultiply", 0.0, 0.0, &expr); - assert!((pdpm - 1.0).abs() < 1e-6, "got {pdpm}"); - // Keeps its own explicit override (`WheelHue1 = 0.9`) and its own `Input` wire (`Transform2`)! - let hue = comp.eval_number(inst, "WheelHue1", 0.0, 0.0, &expr); - assert!((hue - 0.9).abs() < 1e-6, "got {hue}"); - assert_eq!(inst.connected_node("Input"), Some("Transform2")); - // NEVER inherits parent's `EffectMask` image/mask wire! - assert_eq!(inst.connected_node("EffectMask"), None); - - // Chained inheritance (`Instance_Chained -> Instance_ColorCorrector1_6 -> ColorCorrector1_6`): - // nearest ancestor wins (`WheelHue1 = 0.9`, and `WheelTintAngle1` was de-instanced by parent), - // grandparent fills remaining omitted params (`Blend`, `PreDividePostMultiply`). - let chained = comp.node(comp.find_node("Instance_Chained").unwrap()); - assert!((comp.eval_number(chained, "WheelHue1", 0.0, 0.0, &expr) - 0.9).abs() < 1e-6); - assert!(comp.eval_number(chained, "WheelTintAngle1", 0.0, 0.0, &expr).abs() < 1e-6); - assert!((comp.eval_number(chained, "Blend", 10.0, 0.0, &expr) - 0.75).abs() < 1e-6); - assert!((comp.eval_number(chained, "PreDividePostMultiply", 0.0, 0.0, &expr) - 1.0).abs() < 1e-6); - assert_eq!(chained.connected_node("Input"), Some("Loader1")); - assert_eq!(chained.connected_node("EffectMask"), None); - - // Cycle safety (`CycleA <-> CycleB` terminates cleanly and cross-inherits missing params) - let cyc_a = comp.node(comp.find_node("CycleA").unwrap()); - let cyc_b = comp.node(comp.find_node("CycleB").unwrap()); - assert!((comp.eval_number(cyc_a, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6); - assert!((comp.eval_number(cyc_a, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6); - assert!((comp.eval_number(cyc_b, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6); - assert!((comp.eval_number(cyc_b, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6); - - // Roundtrip preserves SourceOp inheritance and de-instanced `Input {}` overrides without duplicating master params - let saved = comp.to_fusion_string(); - let reloaded = Comp::from_fusion_str(&saved).expect("reload"); - let r_inst = reloaded.node(reloaded.find_node("Instance_ColorCorrector1_6").unwrap()); - assert!(reloaded.eval_number(r_inst, "WheelTintAngle1", 0.0, 0.0, &expr).abs() < 1e-6); - assert!((reloaded.eval_number(r_inst, "Blend", 5.0, 1.0, &expr) - 0.5).abs() < 1e-6); - assert_eq!(r_inst.connected_node("EffectMask"), None); - } - - #[test] - fn parses_styled_text_and_text_bezier_spline_keyframes() { - let src = r#"Composition { - Tools = ordered() { - Text_1 = TextPlus { - Inputs = { - StyledText = Input { - SourceOp = "Text_1StyledText", - Source = "Value", - }, - }, - }, - Text_1StyledText = BezierSpline { - KeyFrames = { - [10] = { 0, Value = StyledText { Value = "first line" } }, - [20] = { 1, Value = Text { Value = "second line" } }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse styled text spline"); - let expr = ExprEngine::new(); - let node = comp.node(comp.find_node("Text_1").unwrap()); - assert_eq!(comp.eval_text(node, "StyledText", 5.0, "", &expr), "first line"); - assert_eq!(comp.eval_text(node, "StyledText", 10.0, "", &expr), "first line"); - assert_eq!(comp.eval_text(node, "StyledText", 25.0, "", &expr), "second line"); - } - - #[test] - fn source_op_inherits_all_color_corrector_params_and_respects_blend_override() { - // Mirrors repro_seed_110: N4 inherits Wheel*/TintMode/*RGBGain/PreDividePostMultiply - // from N2 while keeping its own `Input` wire and `Blend = 0.75` override. - let src = r#"Composition { - Tools = ordered() { - S0 = Loader {}, - S1 = DaySky {}, - N2 = ColorCorrector { - Inputs = { - Input = Input { SourceOp = "S0", Source = "Output", }, - WheelHue1 = Input { Value = -0.235, }, - WheelSaturation1 = Input { Value = 0.65, }, - WheelTintAngle1 = Input { Value = 0.323, }, - WheelTintLength1 = Input { Value = 0.67, }, - TintMode = Input { Value = 0, }, - MasterRGBGain = Input { Value = 0.65, }, - ShadowsRGBGain = Input { Value = 0.84, }, - HighlightsRGBGain = Input { Value = 0.75, }, - PreDividePostMultiply = Input { Value = 1, }, - Blend = Input { Value = 1.0, }, - }, - }, - N4 = ColorCorrector { - SourceOp = "N2", - Inputs = { - Input = Input { SourceOp = "S1", Source = "Output", }, - Blend = Input { Value = 0.75, }, - }, - }, - N5 = ColorCorrector { - SourceOp = "N2", - Inputs = { - Input = Input { SourceOp = "S1", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse seed 110 style SourceOp"); - let expr = ExprEngine::new(); - let n4 = comp.node(comp.find_node("N4").unwrap()); - assert_eq!(n4.connected_node("Input"), Some("S1")); - assert!((comp.eval_number(n4, "Blend", 1.0, 1.0, &expr) - 0.75).abs() < 1e-6); - assert!((comp.eval_number(n4, "WheelHue1", 1.0, 0.0, &expr) - (-0.235)).abs() < 1e-6); - assert!((comp.eval_number(n4, "WheelSaturation1", 1.0, 1.0, &expr) - 0.65).abs() < 1e-6); - assert!((comp.eval_number(n4, "WheelTintAngle1", 1.0, 0.0, &expr) - 0.323).abs() < 1e-6); - assert!((comp.eval_number(n4, "WheelTintLength1", 1.0, 0.0, &expr) - 0.67).abs() < 1e-6); - assert!((comp.eval_number(n4, "TintMode", 1.0, 2.0, &expr) - 0.0).abs() < 1e-6); - assert!((comp.eval_number(n4, "MasterRGBGain", 1.0, 1.0, &expr) - 0.65).abs() < 1e-6); - assert!((comp.eval_number(n4, "ShadowsRGBGain", 1.0, 1.0, &expr) - 0.84).abs() < 1e-6); - assert!((comp.eval_number(n4, "HighlightsRGBGain", 1.0, 1.0, &expr) - 0.75).abs() < 1e-6); - assert!((comp.eval_number(n4, "PreDividePostMultiply", 1.0, 0.0, &expr) - 1.0).abs() < 1e-6); - - let n5 = comp.node(comp.find_node("N5").unwrap()); - assert!((comp.eval_number(n5, "Blend", 1.0, 0.0, &expr) - 1.0).abs() < 1e-6); - } - - #[test] - fn hue_curves_lut_bezier_applies_cyclic_ends_and_roundtrips_cleanly() { - let src = r#"Composition { - Tools = ordered() { - Bg = Background {}, - HC_RSup = LUTBezier { - SmoothEndsTransition = true, - KeyColorSplines = { - [0] = { - [0] = { 0.5 }, - [2] = { 1.0 }, - [6] = { 0.5 }, - } - }, - }, - CC_Red = LUTBezier { - SmoothEndsTransition = true, - KeyColorSplines = { - [0] = { - [0.0] = { 0.0 }, - [0.5] = { 0.8 }, - [1.0] = { 0.2 }, - } - }, - }, - HC1 = HueCurves { - Inputs = { - Input = Input { SourceOp = "Bg", Source = "Output", }, - RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", }, - }, - }, - CC1 = ColorCurves { - Inputs = { - Input = Input { SourceOp = "Bg", Source = "Output", }, - Red = Input { SourceOp = "CC_Red", Source = "Value", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse HueCurves + ColorCurves"); - let rsup = comp.splines.get("HC_RSup").expect("HC_RSup"); - assert!(rsup.keyframes[2].lh.is_some()); - assert!((rsup.eval(5.0) - 0.4140625).abs() < 1e-3); - - // ColorCurves [0..1] must NOT get cyclic HueCurves wrapping even with SmoothEndsTransition = true. - let cc_red = comp.splines.get("CC_Red").expect("CC_Red"); - assert!((cc_red.eval(1.0) - 0.2).abs() < 1e-6); - assert!((cc_red.eval(0.75) - 0.5).abs() < 1e-6); - - // Lossless roundtrip keeps KeyColorSplines untouched when unedited. - let saved = comp.to_fusion_string(); - assert!(!saved.contains("LH =")); - let reloaded = Comp::from_fusion_str(&saved).expect("reload"); - assert!((reloaded.splines["HC_RSup"].eval(5.0) - rsup.eval(5.0)).abs() < 1e-9); - } - - #[test] - fn comp_eval_number_clamps_loop_spline_before_first_keyframe() { - let src = r#"Composition { - Tools = ordered() { - CG = ColorGain { - Inputs = { - HighHue = Input { SourceOp = "ColorGain1HighHue", Source = "Value", }, - }, - }, - ColorGain1HighHue = BezierSpline { - KeyFrames = { - [4129] = { 0, RH = { 4137.66666666667, 0.333333333333333 }, Flags = { Linear = true, Loop = true } }, - [4155] = { 1, LH = { 4146.33333333333, 0.666666666666667 }, Flags = { Linear = true, Loop = true } }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse underwater loop spline"); - let expr = ExprEngine::new(); - let cg = comp.node(comp.find_node("CG").unwrap()); - assert!((comp.eval_number(cg, "HighHue", 3933.0, 0.0, &expr) - 0.0).abs() < 1e-9); - assert!((comp.eval_number(cg, "HighHue", 4142.0, 0.0, &expr) - 0.5).abs() < 1e-9); - assert!((comp.eval_number(cg, "HighHue", 4155.0, 0.0, &expr) - 0.0).abs() < 1e-9); - assert!((comp.eval_number(cg, "HighHue", 4168.0, 0.0, &expr) - 0.5).abs() < 1e-9); - } - - #[test] - fn cyclic_expression_references_terminate() { - let src = r#"Composition { - Tools = ordered() { - N = Transform { - Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, }, - }, - E = Expression { - Inputs = { - n1 = Input { Expression = "N.Size", }, - NumberExpression = Input { Value = "n1 + 1", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).unwrap(); - let n = comp.node(comp.find_node("N").unwrap()); - let v = comp.eval_number(n, "Size", 0.0, 7.0, &ExprEngine::new()); - assert!(v.is_finite()); - } - - #[test] - fn clamp_with_inverted_bounds_does_not_panic() { - let src = r#"Composition { - Tools = ordered() { - N = Transform { Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, }, }, - E = Expression { - Inputs = { - n1 = Input { Value = 5, }, - NumberExpression = Input { Value = "clamp(n1, 1, 0)", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).unwrap(); - let n = comp.node(comp.find_node("N").unwrap()); - assert_eq!(comp.eval_number(n, "Size", 0.0, 9.0, &ExprEngine::new()), 0.0); - } - - #[test] - fn explicit_frame_format_is_never_overwritten_by_inferred_size() { - let tools = r#"Tools = ordered() { - BG = Background { Inputs = { Width = Input { Value = 1280, }, Height = Input { Value = 720, }, }, }, - }"#; - let explicit = Comp::from_fusion_str(&format!( - "Composition {{ Prefs = {{ Comp = {{ FrameFormat = {{ Width = 1920, Height = 1080, }}, }}, }}, {tools} }}" - )) - .unwrap(); - assert_eq!((explicit.width, explicit.height), (1920, 1080)); - - let inferred = Comp::from_fusion_str(&format!("Composition {{ {tools} }}")).unwrap(); - assert_eq!((inferred.width, inferred.height), (1280, 720)); - } - - #[test] - fn each_loaded_comp_gets_a_distinct_revision_range() { - let src = "Composition { Tools = ordered() { } }"; - let a = Comp::from_fusion_str(src).unwrap(); - let mut b = Comp::from_fusion_str(src).unwrap(); - for _ in 0..1000 { - b.revision += 1; - } - let c = Comp::from_fusion_str(src).unwrap(); - assert!(a.revision != b.revision && b.revision != c.revision && a.revision != c.revision); - assert!(c.revision > b.revision); - } - - const GROUP_COMP: &str = r#"Composition { - Tools = ordered() { - BG = Background { }, - BG2 = Background { }, - Group1 = GroupOperator { - Inputs = { - MainInput1 = InstanceInput { SourceOp = "Inner1", Source = "Input", }, - BlurSize = InstanceInput { SourceOp = "Inner1", Source = "XBlurSize", Default = 3, }, - }, - Outputs = { - MainOutput1 = InstanceOutput { SourceOp = "Inner2", Source = "Output", }, - }, - Tools = ordered() { - Inner1 = Blur { - Inputs = { - Input = Input { SourceOp = "BG", Source = "Output", }, - }, - }, - Inner2 = Transform { - Inputs = { - Input = Input { SourceOp = "Inner1", Source = "Output", }, - Size = Input { Value = 1, }, - }, - }, - Inner3 = Blur { }, - }, - }, - }, -}"#; - - #[test] - fn unedited_group_roundtrips_byte_for_byte() { - let comp = Comp::from_fusion_str(GROUP_COMP).unwrap(); - let tools = |t: &LuaTable| t.get_table("Tools").unwrap().to_fusion_string(); - assert_eq!(tools(&comp.sync_to_raw_ast()), tools(comp.raw_root.as_ref().unwrap())); - } - - #[test] - fn nested_group_edits_and_wiring_survive_save() { - let mut comp = Comp::from_fusion_str(GROUP_COMP).unwrap(); - let group = comp.find_node("Group1").unwrap(); - assert_eq!(comp.node(group).connected_node("Input"), Some("BG")); - - comp.delete_nodes(&[comp.find_node("Inner3").unwrap()]); - let inner2 = comp.find_node("Inner2").unwrap(); - assert!(comp.set_input_value(inner2, "Size", ParamValue::Number(2.5))); - let (group, bg2) = (comp.find_node("Group1").unwrap(), comp.find_node("BG2").unwrap()); - comp.connect_output(bg2, "Output", group, "Input").unwrap(); - - let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); - let inner2 = saved.node(saved.find_node("Inner2").unwrap()); - assert_eq!(inner2.static_number("Size"), Some(2.5)); - assert!(saved.find_node("Inner3").is_none()); - assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), Some("BG2")); - assert_eq!(saved.node(saved.find_node("Group1").unwrap()).connected_node("Input"), Some("BG2")); - // The exposed `Default` stays on the InstanceInput instead of leaking onto Inner1. - let text = comp.to_fusion_string(); - assert_eq!(text.matches("Value = 3").count(), 0, "{text}"); - - let mut comp = saved; - let group = comp.find_node("Group1").unwrap(); - assert!(comp.disconnect(group, "Input")); - let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); - assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), None); - } -} diff --git a/crates/model/src/comp/eval.rs b/crates/model/src/comp/eval.rs new file mode 100644 index 0000000000000000000000000000000000000000..820a0d7e108616b7d05c9a1f63f684dcc0e814e7 --- /dev/null +++ b/crates/model/src/comp/eval.rs @@ -0,0 +1,724 @@ +use super::math::eval_fusion_math_expr; +use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue, ShakeModifier}; +use crate::expr::ExprEngine; +use crate::spline::Gradient; +use std::collections::HashMap; + +impl Comp { + /// Evaluates an animated `Polyline` spline (`BezierSpline` whose keyframes carry `Value = Polyline { ... }`). + pub fn eval_polyline_spline(&self, name: &str, time: f64) -> Option> { + let (spline, kfs) = self.polyline_splines.get(name)?; + if kfs.is_empty() { + return None; + } + if kfs.len() == 1 || time <= kfs[0].0 { + return Some(kfs[0].1.clone()); + } + if time >= kfs[kfs.len() - 1].0 { + return Some(kfs[kfs.len() - 1].1.clone()); + } + // Fusion stores keyframe index (0, 1, 2, ...) as the spline scalar value for eased shape morphing. + let u = spline.eval(time).clamp(0.0, (kfs.len() - 1) as f64); + let idx = (u.floor() as usize).min(kfs.len() - 2); + let frac = (u - idx as f64).clamp(0.0, 1.0); + let a = &kfs[idx].1; + let b = &kfs[idx + 1].1; + if a.len() != b.len() || frac <= 1e-6 { + return Some(a.clone()); + } + if frac >= 1.0 - 1e-6 { + return Some(b.clone()); + } + let lerp = |x: f64, y: f64| x + (y - x) * frac; + Some( + a.iter() + .zip(b.iter()) + .map(|(pa, pb)| crate::spline::PolyPoint { + x: lerp(pa.x, pb.x), + y: lerp(pa.y, pb.y), + lx: lerp(pa.lx, pb.lx), + ly: lerp(pa.ly, pb.ly), + rx: lerp(pa.rx, pb.rx), + ry: lerp(pa.ry, pb.ry), + linear: pa.linear && pb.linear, + }) + .collect(), + ) + } + + /// Evaluates a numeric input on `node` at continuous `time`, checking Expression -> Spline -> Static -> `default`. + pub fn eval_number( + &self, + node: &Node, + param: &str, + time: f64, + default: f64, + expr_engine: &ExprEngine, + ) -> f64 { + self.eval_number_at(node, param, time, default, expr_engine, 0) + } + + fn eval_number_at( + &self, + node: &Node, + param: &str, + time: f64, + default: f64, + expr_engine: &ExprEngine, + depth: usize, + ) -> f64 { + if depth >= MAX_EXPR_DEPTH { + return default; + } + let Some(binding) = node.inputs.get(param) else { + return default; + }; + if let Some(expr) = &binding.expression { + if let Some(v) = self.eval_expr_number(node, expr, time, expr_engine) { + if v.is_finite() { + return v; + } + } + } + if let Some(src) = &binding.source_op { + if let Some(sp) = self.splines.get(src) { + return sp.eval(time); + } + if let Some(sh) = self.shakes.get(src) { + let axis = match binding.source_output.as_deref() { + Some("Y") => 1, + _ => 0, + }; + return self.eval_shake_axis(sh, axis, time, expr_engine); + } + if let Some(em) = self.expression_modifiers.get(src) { + if let Some(v) = self.eval_expr_mod_number( + em, + binding.source_output.as_deref(), + time, + expr_engine, + depth + 1, + ) { + if v.is_finite() { + return v; + } + } + } + } + binding + .value + .as_ref() + .and_then(ParamValue::as_f64) + .unwrap_or(default) + } + + /// Evaluates a 2D point input (`Center`, `Pivot`, etc.) on `node` at `time`. + pub fn eval_point( + &self, + node: &Node, + param: &str, + time: f64, + default: [f64; 2], + expr_engine: &ExprEngine, + ) -> [f64; 2] { + self.eval_point_at(node, param, time, default, expr_engine, 0) + } + + fn eval_point_at( + &self, + node: &Node, + param: &str, + time: f64, + default: [f64; 2], + expr_engine: &ExprEngine, + depth: usize, + ) -> [f64; 2] { + if depth >= MAX_EXPR_DEPTH { + return default; + } + let Some(binding) = node.inputs.get(param) else { + return default; + }; + if let Some(expr) = &binding.expression { + if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) { + return p; + } + } + if let Some(src) = &binding.source_op { + if let Some(pp) = self.poly_paths.get(src) { + let disp = pp + .displacement_op + .as_deref() + .and_then(|d| self.splines.get(d)) + .map(|sp| sp.eval(time)) + .unwrap_or(pp.displacement_value); + return pp.eval_center(disp); + } + if let Some(sh) = self.shakes.get(src) { + let x = self.eval_shake_axis(sh, 0, time, expr_engine); + let y = self.eval_shake_axis(sh, 1, time, expr_engine); + return [x, y]; + } + if let Some(em) = self.expression_modifiers.get(src) { + if let Some(pt) = self.eval_expr_mod_point(em, time, expr_engine, depth + 1) { + if pt[0].is_finite() && pt[1].is_finite() { + return pt; + } + } + } + } + binding + .value + .as_ref() + .and_then(ParamValue::as_point) + .unwrap_or(default) + } + + fn eval_shake_input(&self, sh: &ShakeModifier, key: &str, time: f64, default: f64, expr_engine: &ExprEngine) -> f64 { + let Some(b) = sh.inputs.get(key) else { + return default; + }; + if let Some(expr) = &b.expression { + let mut sp = HashMap::new(); + for (k, ib) in &sh.inputs { + if k == key { + continue; + } + if let Some(src) = &ib.source_op { + if let Some(spl) = self.splines.get(src) { + sp.insert(k.clone(), spl.eval(time)); + continue; + } + } + if let Some(v) = ib.value.as_ref().and_then(ParamValue::as_f64) { + sp.insert(k.clone(), v); + } + } + if let Some(v) = expr_engine.eval_number(expr, time, &sp, &HashMap::new(), &HashMap::new()) { + if v.is_finite() { + return v; + } + } + } + if let Some(src) = &b.source_op { + if let Some(spl) = self.splines.get(src) { + return spl.eval(time); + } + } + b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default) + } + + fn eval_shake_axis(&self, sh: &ShakeModifier, axis: u32, time: f64, expr_engine: &ExprEngine) -> f64 { + let smoothness = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine).max(0.01); + let seed = self.eval_shake_input(sh, "RandomSeed", time, 0.0, expr_engine).round() as i64; + let lock_xy = self.eval_shake_input(sh, "LockXY", time, 1.0, expr_engine) > 0.5; + let (min_v, max_v) = if axis == 0 || lock_xy { + ( + self.eval_shake_input(sh, "XMinimum", time, 0.0, expr_engine), + self.eval_shake_input(sh, "XMaximum", time, 1.0, expr_engine), + ) + } else { + ( + self.eval_shake_input(sh, "YMinimum", time, 0.0, expr_engine), + self.eval_shake_input(sh, "YMaximum", time, 1.0, expr_engine), + ) + }; + // Smooth Catmull-Rom interpolation over seeded lattice points spaced by `smoothness` frames + let u = time / smoothness; + let k = u.floor() as i64; + let f = u - k as f64; + let hash01 = |i: i64| -> f64 { + let mut x = (i.wrapping_mul(0x9E37_79B9_7F4A_7C15u64 as i64) + ^ seed.wrapping_mul(0xBF58_476D_1CE4_E5B9u64 as i64) + ^ ((axis as i64).wrapping_mul(0x94D0_49BB_1331_11EBu64 as i64))) as u64; + x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + x ^= x >> 31; + (x >> 11) as f64 / (1u64 << 53) as f64 + }; + let p0 = hash01(k - 1); + let p1 = hash01(k); + let p2 = hash01(k + 1); + let p3 = hash01(k + 2); + let f2 = f * f; + let f3 = f2 * f; + let cr = 0.5 * ((2.0 * p1) + + (-p0 + p2) * f + + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * f2 + + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * f3); + let t01 = cr.clamp(0.0, 1.0); + min_v + (max_v - min_v) * t01 + } + + fn eval_expr_mod_input_number( + &self, + em: &ExpressionModifier, + keys: &[&str], + time: f64, + default: f64, + expr_engine: &ExprEngine, + depth: usize, + ) -> f64 { + let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else { + return default; + }; + if let Some(expr) = &b.expression { + if let Some(v) = self.eval_modifier_inline_number(expr, time, expr_engine, depth) { + if v.is_finite() { + return v; + } + } + } + if let Some(src) = &b.source_op { + if let Some(spl) = self.splines.get(src) { + return spl.eval(time); + } + if let Some(sh) = self.shakes.get(src) { + let axis = match b.source_output.as_deref() { + Some("Y") => 1, + _ => 0, + }; + return self.eval_shake_axis(sh, axis, time, expr_engine); + } + if depth < MAX_EXPR_DEPTH { + if let Some(sub) = self.expression_modifiers.get(src) { + if let Some(v) = self.eval_expr_mod_number( + sub, + b.source_output.as_deref(), + time, + expr_engine, + depth + 1, + ) { + if v.is_finite() { + return v; + } + } + } + } + } + b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default) + } + + fn eval_expr_mod_input_point( + &self, + em: &ExpressionModifier, + keys: &[&str], + time: f64, + default: [f64; 2], + expr_engine: &ExprEngine, + depth: usize, + ) -> [f64; 2] { + let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else { + return default; + }; + if let Some(expr) = &b.expression { + let trimmed = expr.trim(); + // Direct `NodeName.ParamName` reference to a Point input on another flow node. + if let Some((node_name, param_name)) = trimmed.split_once('.') { + if !param_name.contains('.') && !param_name.contains(' ') { + if let Some(nid) = self.find_node(node_name.trim()) { + return self.eval_point_at(self.node(nid), param_name.trim(), time, default, expr_engine, depth + 1); + } + } + } + let (sp, spts, en) = self.collect_global_expr_env(time); + if let Some(pt) = expr_engine.eval_point(trimmed, time, &sp, &spts, &en) { + if pt[0].is_finite() && pt[1].is_finite() { + return pt; + } + } + } + if let Some(src) = &b.source_op { + if let Some(pp) = self.poly_paths.get(src) { + let disp = pp + .displacement_op + .as_deref() + .and_then(|d| self.splines.get(d)) + .map(|sp| sp.eval(time)) + .unwrap_or(pp.displacement_value); + return pp.eval_center(disp); + } + if let Some(sh) = self.shakes.get(src) { + let x = self.eval_shake_axis(sh, 0, time, expr_engine); + let y = self.eval_shake_axis(sh, 1, time, expr_engine); + return [x, y]; + } + if depth < MAX_EXPR_DEPTH { + if let Some(sub) = self.expression_modifiers.get(src) { + if let Some(pt) = self.eval_expr_mod_point(sub, time, expr_engine, depth + 1) { + if pt[0].is_finite() && pt[1].is_finite() { + return pt; + } + } + } + } + } + b.value.as_ref().and_then(ParamValue::as_point).unwrap_or(default) + } + + fn eval_modifier_inline_number( + &self, + expr: &str, + time: f64, + expr_engine: &ExprEngine, + depth: usize, + ) -> Option { + let trimmed = expr.trim(); + if let Some((node_name, param_name)) = trimmed.split_once('.') { + if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') { + if let Some(nid) = self.find_node(node_name.trim()) { + return Some(self.eval_number_at( + self.node(nid), + param_name.trim(), + time, + 0.0, + expr_engine, + depth + 1, + )); + } + } + } + let (sp, spts, en) = self.collect_global_expr_env(time); + expr_engine.eval_number(trimmed, time, &sp, &spts, &en) + } + + fn collect_global_expr_env( + &self, + time: f64, + ) -> ( + HashMap, + HashMap, + HashMap>, + ) { + let mut env_nodes = HashMap::new(); + for n in &self.nodes { + let mut m = HashMap::new(); + for (k, b) in &n.inputs { + if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { + m.insert(k.clone(), v); + } else if let Some(src) = &b.source_op { + if let Some(sp) = self.splines.get(src) { + m.insert(k.clone(), sp.eval(time)); + } + } + } + if !m.is_empty() { + env_nodes.insert(n.name.clone(), m); + } + } + (HashMap::new(), HashMap::new(), env_nodes) + } + + fn build_expr_mod_vars( + &self, + em: &ExpressionModifier, + time: f64, + expr_engine: &ExprEngine, + depth: usize, + ) -> (HashMap, HashMap) { + let mut vars = HashMap::with_capacity(32); + let mut pts = HashMap::with_capacity(18); + vars.insert("time".to_owned(), time); + vars.insert("pi".to_owned(), std::f64::consts::PI); + vars.insert("e".to_owned(), std::f64::consts::E); + + for i in 1..=9 { + let short = format!("n{i}"); + let long = format!("NumberIn{i}"); + let v = self.eval_expr_mod_input_number( + em, + &[short.as_str(), long.as_str()], + time, + 0.0, + expr_engine, + depth, + ); + vars.insert(short, v); + vars.insert(long, v); + } + for i in 1..=9 { + let short = format!("p{i}"); + let long = format!("PointIn{i}"); + let pt = self.eval_expr_mod_input_point( + em, + &[short.as_str(), long.as_str()], + time, + [0.5, 0.5], + expr_engine, + depth, + ); + vars.insert(format!("p{i}x"), pt[0]); + vars.insert(format!("p{i}y"), pt[1]); + pts.insert(short, pt); + pts.insert(long, pt); + } + for (k, b) in &em.inputs { + if !vars.contains_key(k) { + if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { + vars.insert(k.clone(), v); + } + } + } + (vars, pts) + } + + fn eval_expr_mod_formula( + &self, + formula: &str, + time: f64, + vars: &HashMap, + pts: &HashMap, + expr_engine: &ExprEngine, + ) -> Option { + let trimmed = formula.trim(); + if trimmed.is_empty() { + return None; + } + if let Some(v) = eval_fusion_math_expr(trimmed, vars) { + return Some(v); + } + // Fallback to Lua SimpleExpression engine for Lua-specific formulas + let (_, _, en) = self.collect_global_expr_env(time); + expr_engine.eval_number(trimmed, time, vars, pts, &en) + } + + fn eval_expr_mod_number( + &self, + em: &ExpressionModifier, + source_output: Option<&str>, + time: f64, + expr_engine: &ExprEngine, + depth: usize, + ) -> Option { + if depth >= MAX_EXPR_DEPTH { + return None; + } + let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth); + let key = match source_output { + Some("X") => "PointExpressionX", + Some("Y") => "PointExpressionY", + _ => "NumberExpression", + }; + let formula = em + .inputs + .get(key) + .and_then(|b| b.value.as_ref()) + .and_then(ParamValue::as_str)?; + self.eval_expr_mod_formula(formula, time, &vars, &pts, expr_engine) + } + + fn eval_expr_mod_point( + &self, + em: &ExpressionModifier, + time: f64, + expr_engine: &ExprEngine, + depth: usize, + ) -> Option<[f64; 2]> { + if depth >= MAX_EXPR_DEPTH { + return None; + } + let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth); + let fx = em + .inputs + .get("PointExpressionX") + .and_then(|b| b.value.as_ref()) + .and_then(ParamValue::as_str); + let fy = em + .inputs + .get("PointExpressionY") + .and_then(|b| b.value.as_ref()) + .and_then(ParamValue::as_str); + if fx.is_some() || fy.is_some() { + let x = fx + .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine)) + .unwrap_or(0.5); + let y = fy + .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine)) + .unwrap_or(0.5); + return Some([x, y]); + } + if let Some(fp) = em + .inputs + .get("PointExpression") + .and_then(|b| b.value.as_ref()) + .and_then(ParamValue::as_str) + { + let (_, _, en) = self.collect_global_expr_env(time); + if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) { + return Some(pt); + } + } + None + } + + pub fn eval_text( + &self, + node: &Node, + param: &str, + time: f64, + default: &str, + expr_engine: &ExprEngine, + ) -> String { + let Some(binding) = node.inputs.get(param) else { + return default.to_owned(); + }; + if let Some(expr) = &binding.expression { + let (sp, spts, en) = self.collect_expr_env(node, time); + if let Some(s) = expr_engine.eval_string(expr, time, &sp, &spts, &en) { + return s; + } + } + if let Some(src) = &binding.source_op { + if let Some(kfs) = self.text_splines.get(src) { + if !kfs.is_empty() { + let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1); + return kfs[idx].1.clone(); + } + } + if let Some(txt) = self.text_modifiers.get(src) { + return txt.clone(); + } + } + binding + .value + .as_ref() + .and_then(ParamValue::as_str) + .unwrap_or(default) + .to_owned() + } + + pub fn text_cls_entries(&self, node: &Node, param: &str) -> &[ClsEntry] { + node.inputs + .get(param) + .and_then(|b| b.source_op.as_deref()) + .and_then(|src| self.text_cls.get(src)) + .map(Vec::as_slice) + .unwrap_or(&[]) + } + + pub fn eval_gradient(&self, node: &Node, param: &str, time: f64) -> Option { + let binding = node.inputs.get(param)?; + if let Some(src) = &binding.source_op { + if let Some(kfs) = self.gradient_modifiers.get(src) { + if kfs.is_empty() { + return None; + } + if kfs.len() == 1 || time <= kfs[0].0 { + return Some(kfs[0].1.clone()); + } + let last = &kfs[kfs.len() - 1]; + if time >= last.0 { + return Some(last.1.clone()); + } + let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1); + let (t0, g0) = &kfs[idx]; + let (t1, g1) = &kfs[(idx + 1).min(kfs.len() - 1)]; + let f = ((time - t0) / (t1 - t0).max(1e-9)).clamp(0.0, 1.0) as f32; + // Bake 17 blended stops across [0..1] + let mut stops = Vec::with_capacity(17); + for i in 0..=16 { + let p = i as f64 / 16.0; + let a = g0.sample(p); + let b = g1.sample(p); + stops.push(crate::spline::GradientStop { + pos: p, + rgba: [ + a[0] + (b[0] - a[0]) * f, + a[1] + (b[1] - a[1]) * f, + a[2] + (b[2] - a[2]) * f, + a[3] + (b[3] - a[3]) * f, + ], + }); + } + return Some(Gradient { stops }); + } + } + if let Some(ParamValue::Gradient(g)) = &binding.value { + return Some(g.clone()); + } + None + } + + fn collect_expr_env( + &self, + node: &Node, + time: f64, + ) -> ( + HashMap, + HashMap, + HashMap>, + ) { + let mut self_params = HashMap::new(); + let mut self_points = HashMap::new(); + for (k, b) in &node.inputs { + if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { + self_params.insert(k.clone(), v); + } else if let Some(pt) = b.value.as_ref().and_then(ParamValue::as_point) { + self_points.insert(k.clone(), pt); + } else if let Some(src) = &b.source_op { + if let Some(sp) = self.splines.get(src) { + self_params.insert(k.clone(), sp.eval(time)); + } else if let Some(pp) = self.poly_paths.get(src) { + let disp = pp + .displacement_op + .as_deref() + .and_then(|d| self.splines.get(d)) + .map(|sp| sp.eval(time)) + .unwrap_or(pp.displacement_value); + self_points.insert(k.clone(), pp.eval_center(disp)); + } + } + } + let mut env_nodes = HashMap::new(); + for n in &self.nodes { + let mut m = HashMap::new(); + for (k, b) in &n.inputs { + if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { + m.insert(k.clone(), v); + } else if let Some(src) = &b.source_op { + if let Some(sp) = self.splines.get(src) { + m.insert(k.clone(), sp.eval(time)); + } + } + } + if !m.is_empty() { + env_nodes.insert(n.name.clone(), m); + } + } + (self_params, self_points, env_nodes) + } + + fn eval_expr_number( + &self, + node: &Node, + expr: &str, + time: f64, + expr_engine: &ExprEngine, + ) -> Option { + let needs_nodes = expr.contains('.') + || expr.trim_start().starts_with(':') + || expr + .split(|c: char| !c.is_alphanumeric() && c != '_') + .any(|tok| !tok.is_empty() && node.inputs.contains_key(tok)); + if !needs_nodes { + let empty_self = HashMap::new(); + let empty_pts = HashMap::new(); + let empty_env = HashMap::new(); + return expr_engine.eval_number(expr, time, &empty_self, &empty_pts, &empty_env); + } + let (sp, spts, en) = self.collect_expr_env(node, time); + expr_engine.eval_number(expr, time, &sp, &spts, &en) + } + + fn eval_expr_point( + &self, + node: &Node, + expr: &str, + time: f64, + expr_engine: &ExprEngine, + ) -> Option<[f64; 2]> { + let (sp, spts, en) = self.collect_expr_env(node, time); + expr_engine.eval_point(expr, time, &sp, &spts, &en) + } + +} diff --git a/crates/model/src/comp/load.rs b/crates/model/src/comp/load.rs new file mode 100644 index 0000000000000000000000000000000000000000..3279df0b13e3b4bf75ede48b0b1e042ac6eb0ffb --- /dev/null +++ b/crates/model/src/comp/load.rs @@ -0,0 +1,813 @@ +use super::{ + BitDepth, ClipSpec, ClsEntry, Comp, ExpressionModifier, InputBinding, NEXT_COMP_REVISION, + Node, NodeId, ParamValue, REVISION_STRIDE, ShakeModifier, is_modifier_type, +}; +use crate::lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua}; +use crate::spline::{BezierSpline, Gradient, PolyPath, read_vec2}; +use std::collections::{HashMap, HashSet}; +use std::path::Path; +use std::sync::atomic::Ordering; + +impl Comp { + pub fn from_fusion_file(path: impl AsRef) -> Result> { + let path = path.as_ref(); + let bytes = std::fs::read(path)?; + let text = String::from_utf8_lossy(&bytes); + let mut comp = Self::from_fusion_str(&text)?; + comp.path = Some(path.to_path_buf()); + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { + comp.name = stem.to_owned(); + } + Ok(comp) + } + + pub fn from_fusion_str(text: &str) -> Result { + let root_val = parse_lua(text)?; + let root = root_val + .as_table() + .ok_or_else(|| ParseError { offset: 0, line: 1, message: "comp root is not a table".into() })?; + + let current_time = root.get_f64("CurrentTime").unwrap_or(0.0); + let global_range = root + .get_table("GlobalRange") + .and_then(read_vec2) + .map(|[a, b]| [a as i64, b as i64]) + .unwrap_or([0, 1000]); + let render_range = root + .get_table("RenderRange") + .and_then(read_vec2) + .map(|[a, b]| [a as i64, b as i64]) + .unwrap_or(global_range); + let audio_filename = root.get_str("AudioFilename").map(str::to_owned); + let audio_offset = root.get_f64("AudioOffset").unwrap_or(0.0); + + // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps, Int8) + let mut width = 1920u32; + let mut height = 1080u32; + let mut fps = 30.0_f64; + let mut depth_full = BitDepth::Int8; + let mut explicit_size = false; + if let Some(ff) = root + .get_table("Prefs") + .and_then(|p| p.get_table("Comp")) + .and_then(|c| c.get_table("FrameFormat")) + { + if let Some(w) = ff.get_f64("Width") { + width = w.round().max(1.0) as u32; + explicit_size = true; + } + if let Some(h) = ff.get_f64("Height") { + height = h.round().max(1.0) as u32; + explicit_size = true; + } + if let Some(r) = ff.get_f64("Rate") { + if r > 0.0 { + fps = r; + } + } + if let Some(d) = ff.get_f64("DepthFull").and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) { + depth_full = d; + } + } + + let mut nodes = Vec::new(); + let mut node_by_name = HashMap::new(); + let mut splines = HashMap::new(); + let mut poly_paths = HashMap::new(); + let mut gradient_modifiers = HashMap::new(); + let mut text_modifiers = HashMap::new(); + let mut text_splines = HashMap::new(); + let mut polyline_splines = HashMap::new(); + let mut text_cls = HashMap::new(); + let mut shakes = HashMap::new(); + let mut expression_modifiers = HashMap::new(); + let mut tracker_aliases: Vec<(String, String)> = Vec::new(); + let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new(); + let mut instanced_from: Vec<(NodeId, String)> = Vec::new(); + + if let Some(tools) = root.get_table("Tools") { + parse_tools_table( + tools, + false, + &mut nodes, + &mut node_by_name, + &mut splines, + &mut poly_paths, + &mut gradient_modifiers, + &mut text_modifiers, + &mut text_splines, + &mut polyline_splines, + &mut text_cls, + &mut shakes, + &mut expression_modifiers, + &mut tracker_aliases, + &mut macro_defaults, + &mut instanced_from, + ); + } + + // Resolve TrackerModifier aliases (e.g. `Track1` -> `Track1TrackerPath`) into `poly_paths` + for (tracker_name, src_path) in tracker_aliases { + if let Some(pp) = poly_paths.get(&src_path).cloned() { + poly_paths.insert(tracker_name, pp); + } + } + + // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools. + for (target_op, target_param, val) in macro_defaults { + if let Some(&nid) = node_by_name.get(&target_op) { + let entry = nodes[nid.0].inputs.entry(target_param).or_insert(InputBinding { + value: None, + source_op: None, + source_output: None, + expression: None, + }); + if entry.value.is_none() && entry.source_op.is_none() && entry.expression.is_none() { + entry.value = Some(val); + } + } + } + + // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets + // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`. + let node_inputs_snapshot: Vec<(String, HashMap)> = nodes + .iter() + .map(|n| (n.name.clone(), n.inputs.clone())) + .collect(); + let snap_map: HashMap> = node_inputs_snapshot.into_iter().collect(); + for n in &mut nodes { + if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") { + let mut flow_wires = HashMap::new(); + for (in_name, b) in &n.inputs { + if let (Some(inner_op), Some(inner_port)) = (&b.source_op, &b.source_output) { + if let Some(inner_in) = snap_map.get(inner_op).and_then(|m| m.get(inner_port)) { + if let Some(ext_src) = &inner_in.source_op { + // Only connect if ext_src is a visible (non-internal) flow node + if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) { + let port_name = if in_name.starts_with("MainInput") || in_name == "Input" { + "Input".to_owned() + } else { + in_name.clone() + }; + flow_wires.insert( + port_name, + InputBinding { + value: None, + source_op: Some(ext_src.clone()), + source_output: inner_in.source_output.clone(), + expression: None, + }, + ); + } + } + } + } + } + if !flow_wires.is_empty() { + n.inputs = flow_wires; + } + } + } + + // Resolve Fusion tool-level `SourceOp` instanced node inheritance + // (e.g. `Instance_ColorCorrector1_6 = ColorCorrector { SourceOp = "ColorCorrector1_6" }`), + // walking chains up to depth 8 (cycle-safe) while NEVER copying image/mask/scene wires. + if !instanced_from.is_empty() { + let parent_of: HashMap = instanced_from + .iter() + .filter_map(|(nid, master_name)| { + node_by_name + .get(master_name) + .copied() + .filter(|&mid| mid != *nid) + .map(|mid| (*nid, mid)) + }) + .collect(); + let orig_inputs: Vec> = + nodes.iter().map(|n| n.inputs.clone()).collect(); + + for &(nid, _) in &instanced_from { + let mut visited = HashSet::new(); + visited.insert(nid); + let mut blocked: HashSet = HashSet::new(); + let mut cur = nid; + for _depth in 0..8 { + let Some(&pid) = parent_of.get(&cur) else { + break; + }; + if !visited.insert(pid) { + break; + } + let inst_inputs = &mut nodes[nid.0].inputs; + for (inp_name, parent_binding) in &orig_inputs[pid.0] { + if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name) + { + continue; + } + if blocked.contains(inp_name) { + continue; + } + if parent_binding.value.is_none() + && parent_binding.source_op.is_none() + && parent_binding.expression.is_none() + { + // An empty `Param = Input {}` on an ancestor marks a de-instanced + // override to default and stops further inheritance up the chain. + blocked.insert(inp_name.clone()); + continue; + } + if !inst_inputs.contains_key(inp_name) { + inst_inputs.insert(inp_name.clone(), parent_binding.clone()); + } + } + cur = pid; + } + } + } + + // Apply cyclic [0..6] endpoint continuity on LUTBezier splines attached to HueCurves nodes. + const HUE_CURVE_PORTS: &[&str] = &[ + "Hue", + "Sat", + "Lum", + "Red", + "Green", + "Blue", + "RedSuppress", + "GreenSuppress", + "BlueSuppress", + ]; + let mut hue_spline_names: HashSet = HashSet::new(); + for n in &nodes { + if n.kind == "HueCurves" { + for &port in HUE_CURVE_PORTS { + if let Some(sp_name) = n.connected_node(port) { + hue_spline_names.insert(sp_name.to_owned()); + } + } + } + } + for sp_name in hue_spline_names { + if let Some(sp) = splines.get_mut(&sp_name) { + sp.apply_hue_curves_cyclic_ends(); + } + } + + // Infer comp dimensions from first Background/TextPlus if Prefs omitted Width/Height + if !explicit_size { + for n in &nodes { + if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") { + if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) { + if w >= 64.0 && h >= 64.0 { + width = w as u32; + height = h as u32; + break; + } + } + } + } + } + + Ok(Self { + path: None, + name: "Untitled".to_owned(), + width, + height, + fps, + depth_full, + current_time, + global_range, + render_range, + audio_filename, + audio_offset, + nodes, + node_by_name, + splines, + poly_paths, + gradient_modifiers, + text_modifiers, + text_splines, + polyline_splines, + text_cls, + shakes, + expression_modifiers, + raw_root: Some(root.clone()), + revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed), + }) + } + +} + +fn is_non_inheritable_instance_port( + name: &str, + binding: &InputBinding, + node_by_name: &HashMap, +) -> bool { + if matches!( + name, + "Input" + | "Background" + | "Foreground" + | "EffectMask" + | "MaterialInput" + | "GarbageMatte" + | "SolidMatte" + | "Mask" + | "TrackingMask" + | "RegionMask" + | "MatchReference" + | "MatchMask" + | "Image" + | "Image1" + | "Image2" + | "BlurImage" + | "DisplaceImage" + ) || name.starts_with("SceneInput") + || name.starts_with("MainInput") + { + return true; + } + // Never inherit flow-graph image/scene/material connections targeting another flow node; + // modifiers (`BezierSpline`, `PolyPath`, `Shake`, `Expression`, etc.) are not in `node_by_name`. + binding.value.is_none() + && binding.expression.is_none() + && binding + .source_op + .as_deref() + .is_some_and(|op| node_by_name.contains_key(op)) +} + +pub(super) fn parse_input_binding(t: &LuaTable) -> InputBinding { + let source_op = t.get_str("SourceOp").map(str::to_owned); + let source_output = t.get_str("Source").map(str::to_owned); + let expression = t.get_str("Expression").map(str::to_owned); + + let value = t.get("Value").map(parse_param_value); + InputBinding { + value, + source_op, + source_output, + expression, + } +} + +pub(super) fn parse_param_value(v: &LuaValue) -> ParamValue { + match v { + LuaValue::Number(n) => ParamValue::Number(*n), + LuaValue::Bool(b) => ParamValue::Number(if *b { 1.0 } else { 0.0 }), + LuaValue::String(s) => ParamValue::Text(s.clone()), + LuaValue::Table(t) => match t.tag.as_deref() { + Some("FuID") => ParamValue::FuId( + t.get_index(1) + .and_then(LuaValue::as_str) + .unwrap_or("") + .to_owned(), + ), + Some("Number") => ParamValue::Number(t.get_f64("Value").unwrap_or(0.0)), + Some("Gradient") => ParamValue::Gradient(Gradient::from_lua(t)), + _ => { + if let Some(p) = read_vec2(t) { + ParamValue::Point(p) + } else { + ParamValue::Raw(v.clone()) + } + } + }, + LuaValue::Nil => ParamValue::Raw(LuaValue::Nil), + } +} + +fn try_parse_gradient_keyframes(table: &LuaTable) -> Option> { + let kfs = table.get_table("KeyFrames")?; + let mut grads = Vec::new(); + for (k, v) in &kfs.entries { + let time = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + let kt = v.as_table()?; + let val = kt + .get_table("Value") + .or_else(|| kt.get_index(1).and_then(LuaValue::as_table))?; + if val.tag.as_deref() == Some("Gradient") { + grads.push((time, Gradient::from_lua(val))); + } else { + return None; + } + } + if grads.is_empty() { + return None; + } + grads.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(grads) +} + +fn try_parse_text_keyframes(table: &LuaTable) -> Option> { + let kfs = table.get_table("KeyFrames")?; + let mut texts = Vec::new(); + for (k, v) in &kfs.entries { + let time = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + let kt = v.as_table()?; + let val = kt.get_table("Value")?; + if matches!(val.tag.as_deref(), Some("Text" | "StyledText")) { + let s = val.get_str("Value").unwrap_or("").to_owned(); + texts.push((time, s)); + } else { + return None; + } + } + if texts.is_empty() { + return None; + } + texts.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(texts) +} + +fn try_parse_polyline_keyframes(table: &LuaTable) -> Option)>> { + let kfs = table.get_table("KeyFrames")?; + let mut shapes = Vec::new(); + for (k, v) in &kfs.entries { + let time = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + let kt = v.as_table()?; + let val = kt.get_table("Value")?; + if val.tag.as_deref() == Some("Polyline") { + let (_, pts) = PolyPath::parse_polyline_table(val); + shapes.push((time, pts)); + } else { + return None; + } + } + if shapes.is_empty() { + return None; + } + shapes.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(shapes) +} + +#[allow(clippy::too_many_arguments)] +fn parse_tools_table( + tools: &LuaTable, + is_internal: bool, + nodes: &mut Vec, + node_by_name: &mut HashMap, + splines: &mut HashMap, + poly_paths: &mut HashMap, + gradient_modifiers: &mut HashMap>, + text_modifiers: &mut HashMap, + text_splines: &mut HashMap>, + polyline_splines: &mut HashMap)>)>, + text_cls: &mut HashMap>, + shakes: &mut HashMap, + expression_modifiers: &mut HashMap, + tracker_aliases: &mut Vec<(String, String)>, + macro_defaults: &mut Vec<(String, String, ParamValue)>, + instanced_from: &mut Vec<(NodeId, String)>, +) { + for (key, val) in &tools.entries { + let LuaKey::Str(name) = key else { continue }; + let Some(tbl) = val.as_table() else { continue }; + let kind = tbl.tag.clone().unwrap_or_else(|| "Unknown".to_owned()); + + if kind == "BezierSpline" || kind == "LUTBezier" { + if let Some(grads) = try_parse_gradient_keyframes(tbl) { + gradient_modifiers.insert(name.clone(), grads); + } else if let Some(txts) = try_parse_text_keyframes(tbl) { + text_splines.insert(name.clone(), txts); + } else if let Some(polys) = try_parse_polyline_keyframes(tbl) { + polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), polys)); + } else { + splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); + } + continue; + } + if kind == "PolyPath" || kind == "Path" { + poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl)); + continue; + } + if kind == "TrackerModifier" { + if let Some(in_tbl) = tbl.get_table("Inputs") { + if let Some(src_op) = in_tbl + .get_table("TrackedCenter0") + .and_then(|c| c.get_str("SourceOp")) + { + tracker_aliases.push((name.clone(), src_op.to_owned())); + } else if let Some(p) = in_tbl + .get_table("PatternCenter0") + .and_then(|c| c.get_table("Value")) + .and_then(read_vec2) + { + poly_paths.insert( + name.clone(), + PolyPath { + name: name.clone(), + displacement_op: None, + displacement_value: 0.0, + closed: false, + points: vec![crate::spline::PolyPoint { + x: p[0] - 0.5, + y: p[1] - 0.5, + lx: 0.0, + ly: 0.0, + rx: 0.0, + ry: 0.0, + linear: true, + }], + }, + ); + } + } + continue; + } + if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" { + if let Some(in_tbl) = tbl.get_table("Inputs") { + if let Some(txt) = in_tbl + .get_table("Text") + .or_else(|| in_tbl.get_table("StyledText")) + .and_then(|s| s.get_str("Value")) + { + text_modifiers.insert(name.clone(), txt.to_owned()); + } + if let Some(arr) = in_tbl + .get_table("CharacterLevelStyling") + .and_then(|c| c.get_table("Value")) + .and_then(|v| v.get_table("Array")) + { + let mut entries = Vec::new(); + for (_, ev) in &arr.entries { + let Some(et) = ev.as_table() else { continue }; + let Some(pid) = et.get_index(1).and_then(LuaValue::as_f64) else { continue }; + let Some(s) = et.get_index(2).and_then(LuaValue::as_f64) else { continue }; + let Some(e) = et.get_index(3).and_then(LuaValue::as_f64) else { continue }; + let Some(val) = et.get_f64("Value") else { continue }; + entries.push(ClsEntry { + prop_id: pid.round().max(0.0) as u32, + start: s.round().max(0.0) as usize, + end: e.round().max(0.0) as usize, + value: val as f32, + }); + } + if !entries.is_empty() { + text_cls.insert(name.clone(), entries); + } + } + } + continue; + } + if kind == "Shake" { + let mut inputs = HashMap::new(); + if let Some(in_tbl) = tbl.get_table("Inputs") { + for (ik, iv) in &in_tbl.entries { + let LuaKey::Str(in_name) = ik else { continue }; + let Some(it) = iv.as_table() else { continue }; + inputs.insert(in_name.clone(), parse_input_binding(it)); + } + } + shakes.insert(name.clone(), ShakeModifier { inputs }); + continue; + } + if kind == "Expression" { + let mut inputs = HashMap::new(); + if let Some(in_tbl) = tbl.get_table("Inputs") { + for (ik, iv) in &in_tbl.entries { + let LuaKey::Str(in_name) = ik else { continue }; + let Some(it) = iv.as_table() else { continue }; + inputs.insert(in_name.clone(), parse_input_binding(it)); + } + } + if let Some(uc) = tbl.get_table("UserControls") { + for (uk, uv) in &uc.entries { + let LuaKey::Str(uname) = uk else { continue }; + let Some(ut) = uv.as_table() else { continue }; + let missing = inputs.get(uname).is_none_or(|b| { + b.value.is_none() && b.source_op.is_none() && b.expression.is_none() + }); + if missing { + if let Some(val) = ut.get("INP_Default").map(parse_param_value) { + inputs.insert( + uname.clone(), + InputBinding { + value: Some(val), + source_op: None, + source_output: None, + expression: None, + }, + ); + } + } + } + } + expression_modifiers.insert(name.clone(), ExpressionModifier { inputs }); + continue; + } + if is_modifier_type(&kind) { + if tbl.get_table("KeyFrames").is_some() { + splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); + } + continue; + } + + let pos = tbl + .get_table("ViewInfo") + .and_then(|vi| vi.get_table("Pos")) + .and_then(read_vec2) + .map(|[x, y]| [x as f32, y as f32]) + .unwrap_or([0.0, 0.0]); + let bypassed = tbl.get_bool("PassThrough").unwrap_or(false); + + let mut inputs = HashMap::new(); + if let Some(in_tbl) = tbl.get_table("Inputs") { + for (ik, iv) in &in_tbl.entries { + let LuaKey::Str(in_name) = ik else { continue }; + let Some(it) = iv.as_table() else { continue }; + let binding = parse_input_binding(it); + if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { + if let (Some(src_op), Some(src_param)) = (&binding.source_op, &binding.source_output) { + if let Some(def_v) = it.get("Default") { + macro_defaults.push((src_op.clone(), src_param.clone(), parse_param_value(def_v))); + } + } + } + inputs.insert(in_name.clone(), binding); + } + } + + // Populate defaults declared in Fusion `UserControls` (needed for ShakeTransform, Custom, etc.) + if let Some(uc) = tbl.get_table("UserControls") { + for (uk, uv) in &uc.entries { + let LuaKey::Str(uname) = uk else { continue }; + let Some(ut) = uv.as_table() else { continue }; + let missing = inputs.get(uname).is_none_or(|b| { + b.value.is_none() && b.source_op.is_none() && b.expression.is_none() + }); + if missing { + let is_point = ut.get_str("LINKID_DataType") == Some("Point") + || ut.get_str("INPID_InputControl") == Some("OffsetControl"); + let def_val = if is_point { + let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5); + let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5); + Some(ParamValue::Point([dx, dy])) + } else { + ut.get("INP_Default").map(parse_param_value) + }; + if let Some(val) = def_val { + inputs.insert( + uname.clone(), + InputBinding { + value: Some(val), + source_op: None, + source_output: None, + expression: None, + }, + ); + } + } + } + } + + let mut clips = Vec::new(); + if let Some(clips_tbl) = tbl.get_table("Clips") { + for (_, cv) in &clips_tbl.entries { + if let Some(ct) = cv.as_table() { + if let Some(filename) = ct.get_str("Filename") { + clips.push(ClipSpec { + filename: filename.to_owned(), + alternate_filename: ct.get_str("AlternateFilename").map(str::to_owned), + start_frame: ct.get_f64("StartFrame").unwrap_or(-1.0) as i64, + length: ct.get_f64("Length").map(|v| v as i64), + trim_in: ct.get_f64("TrimIn").unwrap_or(0.0) as i64, + trim_out: ct.get_f64("TrimOut").unwrap_or(0.0) as i64, + global_start: ct.get_f64("GlobalStart").unwrap_or(0.0) as i64, + global_end: ct.get_f64("GlobalEnd").unwrap_or(0.0) as i64, + extend_first: ct.get_f64("ExtendFirst").unwrap_or(0.0) as i64, + extend_last: ct.get_f64("ExtendLast").unwrap_or(0.0) as i64, + loop_clip: ct.get_f64("Loop").unwrap_or(0.0) > 0.5, + reverse: ct.get_bool("Reverse").unwrap_or(false), + }); + } + } + } + } + + if kind == "Saver" && clips.is_empty() { + if let Some(c) = tbl + .get_table("Inputs") + .and_then(|i| i.get_table("Clip")) + .and_then(|c| c.get_table("Value")) + { + if let Some(filename) = c.get_str("Filename") { + clips.push(ClipSpec { + filename: filename.to_owned(), + alternate_filename: None, + start_frame: 0, + length: None, + trim_in: 0, + trim_out: 0, + global_start: 0, + global_end: 0, + extend_first: 0, + extend_last: 0, + loop_clip: false, + reverse: false, + }); + } + } + } + + // ColorCurves and HueCurves embed their LUTBezier splines inside a nested `Tools` table! + if kind == "ColorCurves" || kind == "HueCurves" { + if let Some(inner_tools) = tbl.get_table("Tools") { + parse_tools_table( + inner_tools, + true, + nodes, + node_by_name, + splines, + poly_paths, + gradient_modifiers, + text_modifiers, + text_splines, + polyline_splines, + text_cls, + shakes, + expression_modifiers, + tracker_aliases, + macro_defaults, + instanced_from, + ); + } + } + + let mut macro_output = None; + if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") { + let mut out_name: Option = None; + if let Some(outs) = tbl.get_table("Outputs") { + for (_, ov) in &outs.entries { + if let Some(ot) = ov.as_table() { + if let Some(src_op) = ot.get_str("SourceOp") { + out_name = Some(src_op.to_owned()); + break; + } + } + } + } + let inner_start = nodes.len(); + if let Some(inner_tools) = tbl.get_table("Tools") { + parse_tools_table( + inner_tools, + true, + nodes, + node_by_name, + splines, + poly_paths, + gradient_modifiers, + text_modifiers, + text_splines, + polyline_splines, + text_cls, + shakes, + expression_modifiers, + tracker_aliases, + macro_defaults, + instanced_from, + ); + } + if let Some(oname) = out_name { + macro_output = nodes[inner_start..] + .iter() + .find(|n| n.name == oname) + .map(|n| n.id) + .or_else(|| node_by_name.get(&oname).copied()); + } + } + + let id = NodeId(nodes.len()); + // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name. + if !is_internal || !node_by_name.contains_key(name) { + node_by_name.insert(name.clone(), id); + } + if let Some(master) = tbl.get_str("SourceOp") { + instanced_from.push((id, master.to_owned())); + } + nodes.push(Node { + id, + name: name.clone(), + kind, + pos, + bypassed, + internal: is_internal, + macro_output, + inputs, + clips, + raw: tbl.clone(), + }); + } +} diff --git a/crates/model/src/comp/math.rs b/crates/model/src/comp/math.rs new file mode 100644 index 0000000000000000000000000000000000000000..e62ecb1dc17403f5e3d64db644f552f729fa4d18 --- /dev/null +++ b/crates/model/src/comp/math.rs @@ -0,0 +1,520 @@ +use super::{Comp, Node}; +use crate::lua_value::{LuaKey, LuaTable}; +use std::collections::HashMap; + +#[derive(Clone, Debug, PartialEq)] +pub struct MeshPoint { + pub x: f64, + pub y: f64, + pub l_cx: Option, + pub l_cy: Option, + pub r_cx: Option, + pub r_cy: Option, + pub t_cx: Option, + pub t_cy: Option, + pub b_cx: Option, + pub b_cy: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct GridMesh { + pub cols: usize, + pub rows: usize, + pub delta_r: f64, + pub delta_c: f64, + pub points: Vec, +} + +impl GridMesh { + fn from_lua_table(tbl: &LuaTable) -> Option { + if tbl.tag.as_deref() != Some("Mesh") { + return None; + } + let cols = tbl.get_f64("Col")?.round().max(2.0) as usize; + let pts_tbl = tbl.get_table("Points")?; + let mut points = Vec::new(); + for pval in pts_tbl.positional_values() { + let pt = pval.as_table()?; + points.push(MeshPoint { + x: pt.get_f64("X").unwrap_or(0.0), + y: pt.get_f64("Y").unwrap_or(0.0), + l_cx: pt.get_f64("L_CX"), + l_cy: pt.get_f64("L_CY"), + r_cx: pt.get_f64("R_CX"), + r_cy: pt.get_f64("R_CY"), + t_cx: pt.get_f64("T_CX"), + t_cy: pt.get_f64("T_CY"), + b_cx: pt.get_f64("B_CX"), + b_cy: pt.get_f64("B_CY"), + }); + } + if points.len() < cols * 2 { + return None; + } + let rows = points.len() / cols; + if rows < 2 || rows * cols != points.len() { + return None; + } + let delta_c = tbl.get_f64("DeltaC").unwrap_or(1.0 / (cols - 1) as f64); + let delta_r = tbl.get_f64("DeltaR").unwrap_or(1.0 / (rows - 1) as f64); + Some(Self { + cols, + rows, + delta_r, + delta_c, + points, + }) + } + + fn lerp(&self, other: &Self, frac: f64) -> Self { + if self.cols != other.cols || self.rows != other.rows || self.points.len() != other.points.len() { + return self.clone(); + } + let f = frac.clamp(0.0, 1.0); + let lerp_num = |a: f64, b: f64| a + (b - a) * f; + let lerp_opt = |a: Option, b: Option| match (a, b) { + (Some(x), Some(y)) => Some(lerp_num(x, y)), + (Some(x), None) => Some(x), + (None, Some(y)) => Some(y), + (None, None) => None, + }; + let points = self + .points + .iter() + .zip(other.points.iter()) + .map(|(a, b)| MeshPoint { + x: lerp_num(a.x, b.x), + y: lerp_num(a.y, b.y), + l_cx: lerp_opt(a.l_cx, b.l_cx), + l_cy: lerp_opt(a.l_cy, b.l_cy), + r_cx: lerp_opt(a.r_cx, b.r_cx), + r_cy: lerp_opt(a.r_cy, b.r_cy), + t_cx: lerp_opt(a.t_cx, b.t_cx), + t_cy: lerp_opt(a.t_cy, b.t_cy), + b_cx: lerp_opt(a.b_cx, b.b_cx), + b_cy: lerp_opt(a.b_cy, b.b_cy), + }) + .collect(); + Self { + cols: self.cols, + rows: self.rows, + delta_r: lerp_num(self.delta_r, other.delta_r), + delta_c: lerp_num(self.delta_c, other.delta_c), + points, + } + } +} + +/// Finds a tool/modifier by name in `tools` or any nested `Tools` table (Groups, Macros, curve nodes). +pub(crate) fn find_raw_tool<'a>(tools: &'a LuaTable, target: &str) -> Option<&'a LuaTable> { + if let Some(t) = tools.get_table(target) { + return Some(t); + } + tools + .entries + .iter() + .filter_map(|(_, v)| v.as_table()?.get_table("Tools")) + .find_map(|inner| find_raw_tool(inner, target)) +} + +pub(crate) fn find_raw_tool_mut<'a>(tools: &'a mut LuaTable, target: &str) -> Option<&'a mut LuaTable> { + if tools.get_table(target).is_some() { + return tools.get_table_mut(target); + } + tools + .entries + .iter_mut() + .filter_map(|(_, v)| v.as_table_mut()?.get_table_mut("Tools")) + .find_map(|inner| find_raw_tool_mut(inner, target)) +} + +impl Comp { + /// Evaluates a `GridWarp` `Mesh` input (static `Mesh { ... }` or animated `BezierSpline` of `Mesh`es). + pub fn eval_grid_mesh(&self, node: &Node, key: &str, time: f64) -> Option { + if let Some(spline_name) = node.inputs.get(key).and_then(|b| b.source_op.as_deref()) { + let tools = self.raw_root.as_ref()?.get_table("Tools")?; + let stbl = find_raw_tool(tools, spline_name)?; + let kfs_tbl = stbl.get_table("KeyFrames")?; + let mut kfs: Vec<(f64, GridMesh)> = Vec::new(); + for (k, v) in &kfs_tbl.entries { + let t = match k { + LuaKey::Index(i) => *i as f64, + LuaKey::Number(n) => *n, + _ => continue, + }; + if let Some(m) = v.as_table().and_then(|kt| kt.get_table("Value")).and_then(GridMesh::from_lua_table) { + kfs.push((t, m)); + } + } + if !kfs.is_empty() { + kfs.sort_by(|a, b| a.0.total_cmp(&b.0)); + if kfs.len() == 1 || time <= kfs[0].0 { + return Some(kfs[0].1.clone()); + } + if time >= kfs[kfs.len() - 1].0 { + return Some(kfs[kfs.len() - 1].1.clone()); + } + let u = self + .splines + .get(spline_name) + .map(|sp| sp.eval(time)) + .unwrap_or(0.0) + .clamp(0.0, (kfs.len() - 1) as f64); + let idx = (u.floor() as usize).min(kfs.len() - 2); + let frac = (u - idx as f64).clamp(0.0, 1.0); + if frac <= 1e-6 { + return Some(kfs[idx].1.clone()); + } + if frac >= 1.0 - 1e-6 { + return Some(kfs[idx + 1].1.clone()); + } + return Some(kfs[idx].1.lerp(&kfs[idx + 1].1, frac)); + } + } + node.raw + .get_table("Inputs")? + .get_table(key)? + .get_table("Value") + .and_then(GridMesh::from_lua_table) + } +} + +/// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`. +/// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`. +pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap) -> Option { + struct Parser<'a> { + bytes: &'a [u8], + pos: usize, + vars: &'a HashMap, + } + + impl<'a> Parser<'a> { + fn skip_ws(&mut self) { + while self.pos < self.bytes.len() { + let b = self.bytes[self.pos]; + if b.is_ascii_whitespace() { + self.pos += 1; + } else if b == b'/' && self.bytes.get(self.pos + 1) == Some(&b'/') { + while self.pos < self.bytes.len() && self.bytes[self.pos] != b'\n' { + self.pos += 1; + } + } else { + break; + } + } + } + + fn peek(&mut self) -> Option { + self.skip_ws(); + self.bytes.get(self.pos).copied() + } + + fn eat_str(&mut self, s: &str) -> bool { + self.skip_ws(); + if self.bytes[self.pos..].starts_with(s.as_bytes()) { + self.pos += s.len(); + true + } else { + false + } + } + + fn parse_or(&mut self) -> Option { + let mut v = self.parse_and()?; + loop { + self.skip_ws(); + if self.eat_str("||") || self.eat_str("|") { + let r = self.parse_and()?; + v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 }; + } else { + break; + } + } + Some(v) + } + + fn parse_and(&mut self) -> Option { + let mut v = self.parse_cmp()?; + loop { + self.skip_ws(); + if self.eat_str("&&") || self.eat_str("&") { + let r = self.parse_cmp()?; + v = if v != 0.0 && r != 0.0 { 1.0 } else { 0.0 }; + } else { + break; + } + } + Some(v) + } + + fn parse_cmp(&mut self) -> Option { + let mut v = self.parse_add()?; + loop { + self.skip_ws(); + if self.eat_str("<=") { + let r = self.parse_add()?; + v = if v <= r { 1.0 } else { 0.0 }; + } else if self.eat_str(">=") { + let r = self.parse_add()?; + v = if v >= r { 1.0 } else { 0.0 }; + } else if self.eat_str("==") || self.eat_str("=") { + let r = self.parse_add()?; + v = if (v - r).abs() <= 1e-12 { 1.0 } else { 0.0 }; + } else if self.eat_str("!=") || self.eat_str("~=") || self.eat_str("<>") { + let r = self.parse_add()?; + v = if (v - r).abs() > 1e-12 { 1.0 } else { 0.0 }; + } else if self.eat_str("<") { + let r = self.parse_add()?; + v = if v < r { 1.0 } else { 0.0 }; + } else if self.eat_str(">") { + let r = self.parse_add()?; + v = if v > r { 1.0 } else { 0.0 }; + } else { + break; + } + } + Some(v) + } + + fn parse_add(&mut self) -> Option { + let mut v = self.parse_mul()?; + loop { + match self.peek() { + Some(b'+') => { + self.pos += 1; + v += self.parse_mul()?; + } + Some(b'-') => { + self.pos += 1; + v -= self.parse_mul()?; + } + _ => break, + } + } + Some(v) + } + + fn parse_mul(&mut self) -> Option { + let mut v = self.parse_pow()?; + loop { + match self.peek() { + Some(b'*') => { + self.pos += 1; + v *= self.parse_pow()?; + } + Some(b'/') => { + self.pos += 1; + let r = self.parse_pow()?; + v = if r.abs() < 1e-12 { 0.0 } else { v / r }; + } + Some(b'%') => { + self.pos += 1; + let r = self.parse_pow()?; + v = if r.abs() < 1e-12 { 0.0 } else { v - r * (v / r).floor() }; + } + _ => break, + } + } + Some(v) + } + + fn parse_pow(&mut self) -> Option { + let base = self.parse_unary()?; + if self.peek() == Some(b'^') { + self.pos += 1; + let exp = self.parse_pow()?; + Some(if base > 0.0 { + base.powf(exp) + } else if base == 0.0 { + if exp == 0.0 { 1.0 } else { 0.0 } + } else if (exp - exp.round()).abs() < 1e-6 { + let p = base.abs().powf(exp); + if (exp.round() as i64) & 1 != 0 { -p } else { p } + } else { + 0.0 + }) + } else { + Some(base) + } + } + + fn parse_unary(&mut self) -> Option { + match self.peek() { + Some(b'-') => { + self.pos += 1; + Some(-self.parse_unary()?) + } + Some(b'+') => { + self.pos += 1; + self.parse_unary() + } + Some(b'!') => { + self.pos += 1; + let v = self.parse_unary()?; + Some(if v == 0.0 { 1.0 } else { 0.0 }) + } + _ => self.parse_primary(), + } + } + + fn parse_primary(&mut self) -> Option { + let b = self.peek()?; + if b == b'(' { + self.pos += 1; + let v = self.parse_or()?; + if self.peek() != Some(b')') { + return None; + } + self.pos += 1; + return Some(v); + } + if b.is_ascii_digit() || b == b'.' { + let start = self.pos; + while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { + self.pos += 1; + } + if self.bytes.get(self.pos) == Some(&b'.') { + self.pos += 1; + while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { + self.pos += 1; + } + } + if matches!(self.bytes.get(self.pos), Some(b'e' | b'E')) { + let exp_pos = self.pos; + self.pos += 1; + if matches!(self.bytes.get(self.pos), Some(b'+' | b'-')) { + self.pos += 1; + } + let dig_start = self.pos; + while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { + self.pos += 1; + } + if self.pos == dig_start { + self.pos = exp_pos; + } + } + let s = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?; + return s.parse::().ok(); + } + if b.is_ascii_alphabetic() || b == b'_' { + let start = self.pos; + while self.pos < self.bytes.len() + && (self.bytes[self.pos].is_ascii_alphanumeric() || self.bytes[self.pos] == b'_') + { + self.pos += 1; + } + let ident = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?; + if self.peek() == Some(b'(') { + self.pos += 1; + let mut args = Vec::new(); + if self.peek() != Some(b')') { + loop { + args.push(self.parse_or()?); + if self.peek() == Some(b',') { + self.pos += 1; + } else { + break; + } + } + } + if self.peek() != Some(b')') { + return None; + } + self.pos += 1; + return Self::eval_fn(ident, &args); + } + return self.vars.get(ident).copied(); + } + None + } + + fn eval_fn(name: &str, args: &[f64]) -> Option { + const DEG2RAD: f64 = std::f64::consts::PI / 180.0; + const RAD2DEG: f64 = 180.0 / std::f64::consts::PI; + let a = |i: usize| args.get(i).copied(); + Some(match name { + "sin" => (a(0)? * DEG2RAD).sin(), + "cos" => (a(0)? * DEG2RAD).cos(), + "tan" => (a(0)? * DEG2RAD).tan(), + "asin" => a(0)?.clamp(-1.0, 1.0).asin() * RAD2DEG, + "acos" => a(0)?.clamp(-1.0, 1.0).acos() * RAD2DEG, + "atan" => a(0)?.atan() * RAD2DEG, + "atan2" => a(0)?.atan2(a(1)?) * RAD2DEG, + "sinr" => a(0)?.sin(), + "cosr" => a(0)?.cos(), + "tanr" => a(0)?.tan(), + "asinr" => a(0)?.clamp(-1.0, 1.0).asin(), + "acosr" => a(0)?.clamp(-1.0, 1.0).acos(), + "atanr" => a(0)?.atan(), + "atan2r" => a(0)?.atan2(a(1)?), + "sinh" => a(0)?.sinh(), + "cosh" => a(0)?.cosh(), + "tanh" => a(0)?.tanh(), + "deg" => a(0)? * RAD2DEG, + "rad" => a(0)? * DEG2RAD, + "abs" => a(0)?.abs(), + "sqrt" => a(0)?.max(0.0).sqrt(), + "pow" => a(0)?.powf(a(1)?), + "exp" => a(0)?.exp(), + "log" | "ln" => a(0)?.max(1e-12).ln(), + "log10" => a(0)?.max(1e-12).log10(), + "log2" => a(0)?.max(1e-12).log2(), + "floor" | "int" => a(0)?.floor(), + "ceil" => a(0)?.ceil(), + "round" => a(0)?.round(), + "trunc" => a(0)?.trunc(), + "fract" => a(0)? - a(0)?.floor(), + "sign" => { + let v = a(0)?; + if v > 0.0 { 1.0 } else if v < 0.0 { -1.0 } else { 0.0 } + } + "min" => { + if args.is_empty() { return None; } + args.iter().copied().fold(f64::INFINITY, f64::min) + } + "max" => { + if args.is_empty() { return None; } + args.iter().copied().fold(f64::NEG_INFINITY, f64::max) + } + "clamp" => a(0)?.max(a(1)?).min(a(2)?), + "mod" => { + let (x, y) = (a(0)?, a(1)?); + if y.abs() < 1e-12 { 0.0 } else { x - y * (x / y).floor() } + } + "if" | "iif" => { + if a(0)? != 0.0 { a(1)? } else { a(2)? } + } + "dist" => { + let (x1, y1, x2, y2) = (a(0)?, a(1)?, a(2)?, a(3)?); + ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt() + } + "hypot" => a(0)?.hypot(a(1)?), + "mix" | "lerp" => { + let (x, y, t) = (a(0)?, a(1)?, a(2)?); + x + (y - x) * t + } + "step" => if a(1)? < a(0)? { 0.0 } else { 1.0 }, + "smoothstep" => { + let (e0, e1, x) = (a(0)?, a(1)?, a(2)?); + let denom = e1 - e0; + let t = if denom.abs() < 1e-12 { 0.0 } else { ((x - e0) / denom).clamp(0.0, 1.0) }; + t * t * (3.0 - 2.0 * t) + } + _ => return None, + }) + } + } + + let mut p = Parser { + bytes: src.as_bytes(), + pos: 0, + vars, + }; + let val = p.parse_or()?; + p.skip_ws(); + if p.pos != p.bytes.len() || !val.is_finite() { + return None; + } + Some(val) +} + diff --git a/crates/model/src/comp/save.rs b/crates/model/src/comp/save.rs new file mode 100644 index 0000000000000000000000000000000000000000..06bf5abfeb9556f6e49ba908872e529fcf623904 --- /dev/null +++ b/crates/model/src/comp/save.rs @@ -0,0 +1,637 @@ +use super::load::{parse_input_binding, parse_param_value}; +use super::math::find_raw_tool_mut; +use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type}; +use crate::lua_value::{LuaKey, LuaTable, LuaValue}; +use crate::spline::{BezierSpline, read_vec2}; +use std::collections::{HashMap, VecDeque}; +use std::path::{Path, PathBuf}; + +impl Comp { + /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits, + /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST, + /// preserving all unknown nodes, modifiers, macros, UserControls, Clips, and metadata verbatim. + pub fn sync_to_raw_ast(&self) -> LuaTable { + let mut root = self.raw_root.clone().unwrap_or_else(|| LuaTable { + tag: Some("Composition".to_owned()), + entries: Vec::new(), + }); + + root.set( + LuaKey::Str("CurrentTime".to_owned()), + LuaValue::Number(self.current_time), + ); + root.set( + LuaKey::Str("GlobalRange".to_owned()), + vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64), + ); + root.set( + LuaKey::Str("RenderRange".to_owned()), + vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64), + ); + if let Some(ref af) = self.audio_filename { + root.set( + LuaKey::Str("AudioFilename".to_owned()), + LuaValue::String(af.clone()), + ); + } + if self.audio_offset != 0.0 || root.get("AudioOffset").is_some() { + root.set( + LuaKey::Str("AudioOffset".to_owned()), + LuaValue::Number(self.audio_offset), + ); + } + + // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull) + { + let prefs = ensure_table_mut(&mut root, "Prefs", None); + let comp_prefs = ensure_table_mut(prefs, "Comp", None); + let ff = ensure_table_mut(comp_prefs, "FrameFormat", None); + if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) { + ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64)); + } + if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) { + ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64)); + } + if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) { + ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps)); + } + let existing_depth = ff + .get_f64("DepthFull") + .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) + .unwrap_or(BitDepth::Int8); + if existing_depth != self.depth_full { + ff.set( + LuaKey::Str("DepthFull".to_owned()), + LuaValue::Number((self.depth_full as i32) as f64), + ); + } + } + + // Sync Tools + let tools = ensure_table_mut(&mut root, "Tools", Some("ordered")); + + for node in self.nodes.iter().filter(|n| !n.internal) { + if tools.get_table(&node.name).is_some() { + continue; + } + let mut new_tbl = if node.raw.tag.is_some() { + node.raw.clone() + } else { + LuaTable { tag: None, entries: Vec::new() } + }; + if new_tbl.tag.is_none() { + new_tbl.tag = Some(node.kind.clone()); + } + tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl)); + } + + let mut pool: HashMap<(bool, String), VecDeque<&Node>> = HashMap::new(); + let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new(); + for node in &self.nodes { + pool.entry((node.internal, node.name.clone())).or_default().push_back(node); + if !is_group_kind(&node.kind) { + continue; + } + for (inner_op, inner_port, default) in instance_inputs(&node.raw) { + if let Some(d) = default { + instance_defaults.insert((inner_op, inner_port), d); + } + } + } + self.sync_tools_level(tools, false, &mut pool, &instance_defaults); + + // Sync BezierSpline edits (only touch splines that actually differ from the raw AST) + let mut spline_names: Vec<&String> = self.splines.keys().collect(); + spline_names.sort(); + for spline_name in spline_names { + let spline = &self.splines[spline_name]; + if let Some(tbl) = find_raw_tool_mut(tools, spline_name) { + sync_spline_table(spline_name, spline, tbl); + continue; + } + let mut sp_tbl = LuaTable { + tag: Some("BezierSpline".to_owned()), + entries: Vec::new(), + }; + sp_tbl.set( + LuaKey::Str("SplineColor".to_owned()), + spline_color_lua(spline.color), + ); + sp_tbl.set( + LuaKey::Str("KeyFrames".to_owned()), + LuaValue::Table(build_keyframes_table(spline)), + ); + tools.set(LuaKey::Str(spline_name.clone()), LuaValue::Table(sp_tbl)); + } + + root + } + + /// Syncs one `Tools` table level: drops deleted flow nodes (never modifiers), then syncs each + /// surviving node and recurses into Group/Macro operators' private `Tools`. + fn sync_tools_level<'a>( + &'a self, + tools: &mut LuaTable, + internal: bool, + pool: &mut HashMap<(bool, String), VecDeque<&'a Node>>, + instance_defaults: &HashMap<(&str, &str), ParamValue>, + ) { + tools.entries.retain(|(k, v)| { + let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true }; + is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) + || pool.get(&(internal, name.clone())).is_some_and(|q| !q.is_empty()) + }); + + for (k, v) in &mut tools.entries { + let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue }; + if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) { + continue; + } + let Some(node) = pool.get_mut(&(internal, name.clone())).and_then(VecDeque::pop_front) else { + continue; + }; + self.sync_node_tool(node, tool_tbl, instance_defaults); + if is_group_kind(&node.kind) { + if let Some(inner) = tool_tbl.get_table_mut("Tools") { + self.sync_tools_level(inner, true, pool, instance_defaults); + } + sync_group_wiring(node, tool_tbl); + } + } + } + + fn sync_node_tool( + &self, + node: &Node, + tool_tbl: &mut LuaTable, + instance_defaults: &HashMap<(&str, &str), ParamValue>, + ) { + // ViewInfo.Pos + if let Some(vi) = tool_tbl.get_table_mut("ViewInfo") { + let pos_changed = vi + .get_table("Pos") + .and_then(read_vec2) + .is_none_or(|[x, y]| { + (x as f32 - node.pos[0]).abs() > 1e-4 || (y as f32 - node.pos[1]).abs() > 1e-4 + }); + if pos_changed { + vi.set( + LuaKey::Str("Pos".to_owned()), + vec2_lua(node.pos[0] as f64, node.pos[1] as f64), + ); + } + } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 { + let mut vi = LuaTable { + tag: Some("OperatorInfo".to_owned()), + entries: Vec::new(), + }; + vi.set( + LuaKey::Str("Pos".to_owned()), + vec2_lua(node.pos[0] as f64, node.pos[1] as f64), + ); + tool_tbl.set(LuaKey::Str("ViewInfo".to_owned()), LuaValue::Table(vi)); + } + + // PassThrough + if node.bypassed { + tool_tbl.set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true)); + } else if tool_tbl.get("PassThrough").is_some() { + tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned())); + } + + // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`). + if !is_group_kind(&node.kind) { + let master_inputs = node + .raw + .get_str("SourceOp") + .and_then(|m| self.find_node(m)) + .map(|mid| &self.nodes[mid.0].inputs); + sync_node_inputs(node, master_inputs, instance_defaults, tool_tbl); + } + } + + /// Serializes this composition back to a Blackmagic Fusion `.comp` string. + pub fn to_fusion_string(&self) -> String { + let mut s = self.sync_to_raw_ast().to_fusion_string(); + if !s.ends_with('\n') { + s.push('\n'); + } + s + } + + /// Atomically saves this composition to `path`. + /// If `path` already exists, backs up the original bytes to + /// `/fission-backups/_.comp.bak` and returns `Ok(Some(backup_path))`. + pub fn save_to_file(&self, path: impl AsRef) -> Result, std::io::Error> { + let path = path.as_ref(); + let stem = path + .file_stem() + .and_then(|s| s.to_str()) + .filter(|s| !s.is_empty()) + .unwrap_or("comp"); + + let backup_path = if path.exists() { + let backup_dir = std::env::temp_dir().join("fission-backups"); + std::fs::create_dir_all(&backup_dir)?; + let unix_millis = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis()) + .unwrap_or(0); + let backup_file = backup_dir.join(format!("{stem}_{unix_millis}.comp.bak")); + std::fs::copy(path, &backup_file)?; + Some(backup_file) + } else { + None + }; + + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + std::fs::create_dir_all(parent)?; + + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let pid = std::process::id(); + let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp")); + + let serialized = self.to_fusion_string(); + if let Err(e) = std::fs::write(&tmp_path, serialized.as_bytes()) { + let _ = std::fs::remove_file(&tmp_path); + return Err(e); + } + if let Err(e) = std::fs::rename(&tmp_path, path) { + let _ = std::fs::remove_file(&tmp_path); + return Err(e); + } + + Ok(backup_path) + } +} + +pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue { + LuaValue::Table(LuaTable { + tag: None, + entries: vec![ + (LuaKey::Index(1), LuaValue::Number(x)), + (LuaKey::Index(2), LuaValue::Number(y)), + ], + }) +} + +pub(crate) fn ensure_table_mut<'a>(parent: &'a mut LuaTable, key: &str, tag: Option<&str>) -> &'a mut LuaTable { + if parent.get_table(key).is_none() { + parent.set( + LuaKey::Str(key.to_owned()), + LuaValue::Table(LuaTable { + tag: tag.map(str::to_owned), + entries: Vec::new(), + }), + ); + } + parent.get_table_mut(key).expect("table just inserted") +} + +pub(crate) fn param_value_to_lua(v: &ParamValue) -> LuaValue { + match v { + ParamValue::Number(n) => LuaValue::Number(*n), + ParamValue::Point([x, y]) => vec2_lua(*x, *y), + ParamValue::Text(s) => LuaValue::String(s.clone()), + ParamValue::FuId(s) => LuaValue::Table(LuaTable { + tag: Some("FuID".to_owned()), + entries: vec![(LuaKey::Index(1), LuaValue::String(s.clone()))], + }), + ParamValue::Gradient(g) => { + let mut colors = LuaTable::default(); + for stop in &g.stops { + let key = if stop.pos.fract() == 0.0 && stop.pos.abs() < 9_007_199_254_740_992.0 { + LuaKey::Index(stop.pos as i64) + } else { + LuaKey::Number(stop.pos) + }; + colors.entries.push(( + key, + LuaValue::Table(LuaTable { + tag: None, + entries: vec![ + (LuaKey::Index(1), LuaValue::Number(stop.rgba[0] as f64)), + (LuaKey::Index(2), LuaValue::Number(stop.rgba[1] as f64)), + (LuaKey::Index(3), LuaValue::Number(stop.rgba[2] as f64)), + (LuaKey::Index(4), LuaValue::Number(stop.rgba[3] as f64)), + ], + }), + )); + } + LuaValue::Table(LuaTable { + tag: Some("Gradient".to_owned()), + entries: vec![(LuaKey::Str("Colors".to_owned()), LuaValue::Table(colors))], + }) + } + ParamValue::Raw(raw) => raw.clone(), + } +} + +fn user_control_default(raw: &LuaTable, name: &str) -> Option { + let ut = raw.get_table("UserControls")?.get_table(name)?; + let is_point = ut.get_str("LINKID_DataType") == Some("Point") + || ut.get_str("INPID_InputControl") == Some("OffsetControl"); + if is_point { + let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5); + let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5); + Some(ParamValue::Point([dx, dy])) + } else { + ut.get("INP_Default").map(parse_param_value) + } +} + +pub(crate) fn is_group_kind(kind: &str) -> bool { + matches!(kind, "MacroOperator" | "GroupOperator") +} + +/// `(inner_op, inner_port, default)` for each `InstanceInput` exposed by a Group/Macro tool table. +fn instance_inputs(group: &LuaTable) -> impl Iterator)> { + group.get_table("Inputs").into_iter().flat_map(|inputs| { + inputs.entries.iter().filter_map(|(_, v)| { + let t = v.as_table()?; + Some((t.get_str("SourceOp")?, t.get_str("Source")?, t.get("Default").map(parse_param_value))) + }) + }) +} + +/// Writes external wires connected to a Group/Macro node back onto the inner tool inputs that its +/// `InstanceInput`s expose (load surfaces them as `node.inputs`). +fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) { + let exposed: Vec<(String, String, String)> = group_tbl + .get_table("Inputs") + .map(|inputs| { + inputs + .entries + .iter() + .filter_map(|(k, v)| { + let LuaKey::Str(in_name) = k else { return None }; + let t = v.as_table()?; + let port = if in_name.starts_with("MainInput") || in_name == "Input" { + "Input".to_owned() + } else { + in_name.clone() + }; + Some((port, t.get_str("SourceOp")?.to_owned(), t.get_str("Source")?.to_owned())) + }) + .collect() + }) + .unwrap_or_default(); + let Some(inner_tools) = group_tbl.get_table_mut("Tools") else { return }; + for (port, inner_op, inner_port) in exposed { + let desired = node.inputs.get(&port); + // Still the raw InstanceInput binding: nothing was rewired. + if desired.is_some_and(|b| b.source_op.as_deref() == Some(inner_op.as_str())) { + continue; + } + let Some(inner_tbl) = find_raw_tool_mut(inner_tools, &inner_op) else { continue }; + let current = inner_tbl + .get_table("Inputs") + .and_then(|i| i.get_table(&inner_port)) + .map(parse_input_binding); + let wired = |b: &InputBinding| (b.source_op.clone(), b.source_output.clone()); + match desired { + Some(b) if current.as_ref().map(wired) != Some(wired(b)) => { + let input = ensure_table_mut(ensure_table_mut(inner_tbl, "Inputs", None), &inner_port, Some("Input")); + for (key, val) in [("SourceOp", &b.source_op), ("Source", &b.source_output)] { + match val { + Some(v) => input.set(LuaKey::Str(key.to_owned()), LuaValue::String(v.clone())), + None => { + input.remove(&LuaKey::Str(key.to_owned())); + } + } + } + } + None if current.as_ref().is_some_and(|c| c.source_op.is_some()) => { + if let Some(input) = inner_tbl.get_table_mut("Inputs").and_then(|i| i.get_table_mut(&inner_port)) { + input.remove(&LuaKey::Str("SourceOp".to_owned())); + input.remove(&LuaKey::Str("Source".to_owned())); + } + } + _ => {} + } + } +} + +fn sync_node_inputs( + node: &Node, + master_inputs: Option<&HashMap>, + instance_defaults: &HashMap<(&str, &str), ParamValue>, + tool_tbl: &mut LuaTable, +) { + // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`. + if let Some(in_tbl) = tool_tbl.get_table_mut("Inputs") { + in_tbl.entries.retain(|(k, v)| { + let LuaKey::Str(port) = k else { return true }; + if v.as_table().is_none() { + return true; + } + node.inputs.contains_key(port) + }); + } + + // Collect sorted port names for deterministic output when appending new inputs. + let mut ports: Vec<&String> = node.inputs.keys().collect(); + ports.sort(); + + for port in ports { + let binding = &node.inputs[port]; + // Load fills unset inner-tool inputs from the enclosing group's `InstanceInput` default. + if binding.source_op.is_none() + && binding.expression.is_none() + && binding.value.is_some() + && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str())) + && tool_tbl + .get_table("Inputs") + .and_then(|i| i.get_table(port)) + .is_none_or(|t| parse_input_binding(t).value.is_none()) + { + continue; + } + let existing_binding = tool_tbl + .get_table("Inputs") + .and_then(|i| i.get_table(port)) + .map(parse_input_binding); + + if let Some(orig) = existing_binding { + if orig == *binding { + continue; + } + // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools. + if orig.value.is_none() + && orig.source_op.is_none() + && orig.expression.is_none() + && master_inputs.is_some_and(|m| m.get(port) == Some(binding)) + { + continue; + } + let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None); + if let Some(it) = in_tbl.get_table_mut(port) { + if orig.source_op != binding.source_op { + match &binding.source_op { + Some(op) => it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())), + None => { + it.remove(&LuaKey::Str("SourceOp".to_owned())); + } + } + } + if orig.source_output != binding.source_output { + match &binding.source_output { + Some(src) => it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone())), + None => { + it.remove(&LuaKey::Str("Source".to_owned())); + } + } + } + if orig.expression != binding.expression { + match &binding.expression { + Some(expr) => it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone())), + None => { + it.remove(&LuaKey::Str("Expression".to_owned())); + } + } + } + if orig.value != binding.value { + match &binding.value { + Some(val) => it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val)), + None => { + it.remove(&LuaKey::Str("Value".to_owned())); + } + } + } + if it.entries.is_empty() + && binding.value.is_none() + && binding.source_op.is_none() + && binding.source_output.is_none() + && binding.expression.is_none() + { + in_tbl.remove(&LuaKey::Str(port.clone())); + } + } + } else { + // Port did not exist in raw `Inputs`. + if binding.value.is_none() && binding.source_op.is_none() && binding.expression.is_none() { + continue; + } + // Don't pollute `Inputs` with unedited `UserControls` defaults synthesized during load. + if binding.source_op.is_none() + && binding.expression.is_none() + && binding.value.is_some() + && binding.value == user_control_default(&node.raw, port) + { + continue; + } + // Don't duplicate inherited master inputs onto instanced tools. + if let Some(master) = master_inputs { + if master.get(port) == Some(binding) { + continue; + } + } + + let mut it = LuaTable { + tag: Some("Input".to_owned()), + entries: Vec::new(), + }; + if let Some(op) = &binding.source_op { + it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())); + } + if let Some(src) = &binding.source_output { + it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone())); + } + if let Some(val) = &binding.value { + it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val)); + } + if let Some(expr) = &binding.expression { + it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone())); + } + let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None); + in_tbl.set(LuaKey::Str(port.clone()), LuaValue::Table(it)); + } + } +} + +fn spline_color_lua(color: [u8; 3]) -> LuaValue { + LuaValue::Table(LuaTable { + tag: None, + entries: vec![ + (LuaKey::Str("Red".to_owned()), LuaValue::Number(color[0] as f64)), + (LuaKey::Str("Green".to_owned()), LuaValue::Number(color[1] as f64)), + (LuaKey::Str("Blue".to_owned()), LuaValue::Number(color[2] as f64)), + ], + }) +} + +fn build_keyframes_table(spline: &BezierSpline) -> LuaTable { + let mut kfs = spline.keyframes.clone(); + kfs.sort_by(|a, b| a.time.total_cmp(&b.time)); + let mut tbl = LuaTable::default(); + for kf in kfs { + let key = if kf.time.fract() == 0.0 && kf.time.abs() < 9_007_199_254_740_992.0 { + LuaKey::Index(kf.time as i64) + } else { + LuaKey::Number(kf.time) + }; + let mut entry = LuaTable::default(); + entry.entries.push((LuaKey::Index(1), LuaValue::Number(kf.value))); + if let Some([lx, ly]) = kf.lh { + entry.entries.push((LuaKey::Str("LH".to_owned()), vec2_lua(lx, ly))); + } + if let Some([rx, ry]) = kf.rh { + entry.entries.push((LuaKey::Str("RH".to_owned()), vec2_lua(rx, ry))); + } + let mut flags = LuaTable::default(); + if kf.flags.linear { + flags.entries.push((LuaKey::Str("Linear".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.step_in { + flags.entries.push((LuaKey::Str("StepIn".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.step_out { + flags.entries.push((LuaKey::Str("StepOut".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.loop_after { + flags.entries.push((LuaKey::Str("Loop".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.loop_rel { + flags.entries.push((LuaKey::Str("LoopRel".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.ping_pong { + flags.entries.push((LuaKey::Str("PingPong".to_owned()), LuaValue::Bool(true))); + } + if kf.flags.locked_y { + flags.entries.push((LuaKey::Str("LockedY".to_owned()), LuaValue::Bool(true))); + } + if !flags.entries.is_empty() { + entry.entries.push((LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags))); + } + tbl.entries.push((key, LuaValue::Table(entry))); + } + tbl +} + +fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) { + let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl); + if existing.color != spline.color { + tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color)); + } + let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && { + let mut normalized = existing.clone(); + normalized.apply_hue_curves_cyclic_ends(); + normalized.keyframes == spline.keyframes + }; + if existing.keyframes != spline.keyframes && !unchanged_cyclic { + let new_kfs = LuaValue::Table(build_keyframes_table(spline)); + if tbl.tag.as_deref() == Some("LUTBezier") && tbl.get_table("KeyColorSplines").is_some() { + if let Some(kcs) = tbl.get_table_mut("KeyColorSplines") { + kcs.set(LuaKey::Index(0), new_kfs); + } + } else { + tbl.set(LuaKey::Str("KeyFrames".to_owned()), new_kfs); + } + } +} diff --git a/crates/model/src/comp/tests.rs b/crates/model/src/comp/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..767153c0f3d35c2850cfa9d47d3f4c6c96970f2a --- /dev/null +++ b/crates/model/src/comp/tests.rs @@ -0,0 +1,501 @@ +mod expression_modifier_tests { + use crate::comp::*; + use crate::expr::ExprEngine; + + #[test] + fn evaluates_standalone_expression_modifier_number_and_chained() { + let src = r#"Composition { + Tools = ordered() { + XF1 = Transform { + Inputs = { + Angle = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", }, + Size = Input { SourceOp = "HourHandExpr", Source = "NumberResult", }, + }, + }, + Clock_MinHandExpr = Expression { + Inputs = { + n1 = Input { Value = 1, }, + n2 = Input { SourceOp = "TimeSpline", Source = "Value", }, + NumberExpression = Input { Value = "if(n1>0.5,floor(-n2)*30,-n2*30)", }, + }, + }, + HourHandExpr = Expression { + Inputs = { + n1 = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", }, + NumberExpression = Input { Value = "n1/12", }, + }, + }, + TimeSpline = BezierSpline { + KeyFrames = { + [0] = { 0.0, Flags = { Linear = true } }, + [10] = { 2.5, Flags = { Linear = true } }, + }, + }, + }, + }"#; + + let comp = Comp::from_fusion_str(src).expect("parse comp"); + assert!(comp.expression_modifiers.contains_key("Clock_MinHandExpr")); + assert!(comp.expression_modifiers.contains_key("HourHandExpr")); + // Expression modifiers are modifiers, not flow nodes + assert!(comp.find_node("Clock_MinHandExpr").is_none()); + + let expr = ExprEngine::new(); + let xf = comp.node(comp.find_node("XF1").unwrap()); + // At t=10: n2 = 2.5, floor(-2.5) = -3.0, -3.0 * 30 = -90.0 + let angle = comp.eval_number(xf, "Angle", 10.0, 0.0, &expr); + assert!((angle - (-90.0)).abs() < 1e-6, "got {angle}"); + // Chained HourHandExpr: n1 / 12 = -90 / 12 = -7.5 + let size = comp.eval_number(xf, "Size", 10.0, 1.0, &expr); + assert!((size - (-7.5)).abs() < 1e-6, "got {size}"); + + // Lossless roundtrip preserves Expression modifiers + let saved = comp.to_fusion_string(); + let reloaded = Comp::from_fusion_str(&saved).expect("reload"); + let r_xf = reloaded.node(reloaded.find_node("XF1").unwrap()); + assert!((reloaded.eval_number(r_xf, "Angle", 10.0, 0.0, &expr) - (-90.0)).abs() < 1e-6); + } + + #[test] + fn evaluates_standalone_expression_modifier_point_and_dist_trig() { + let src = r#"Composition { + Tools = ordered() { + XF1 = Transform { + Inputs = { + Center = Input { SourceOp = "PtExpr", Source = "PointResult", }, + Angle = Input { SourceOp = "TrigExpr", Source = "NumberResult", }, + }, + }, + PtExpr = Expression { + Inputs = { + p1 = Input { Value = { 0.8, 0.2 }, }, + n1 = Input { Value = 10, }, + PointExpressionX = Input { Value = "if(p1x>0.5, 0.5 + time*dist(p1x,p1y,0.5,p1y)/n1, 0.5)", }, + PointExpressionY = Input { Value = "-p1y + p1y*0.5 + 0.5", }, + }, + }, + TrigExpr = Expression { + Inputs = { + NumberIn1 = Input { Value = 90, }, + NumberExpression = Input { Value = "sin(n1) + cos(0) + (1/0)", }, + }, + }, + }, + }"#; + + let comp = Comp::from_fusion_str(src).expect("parse comp"); + let expr = ExprEngine::new(); + let xf = comp.node(comp.find_node("XF1").unwrap()); + // At t=5: dist(0.8,0.2,0.5,0.2) = 0.3, x = 0.5 + 5*0.3/10 = 0.65, y = -0.2 + 0.1 + 0.5 = 0.4 + let pt = comp.eval_point(xf, "Center", 5.0, [0.5, 0.5], &expr); + assert!((pt[0] - 0.65).abs() < 1e-6, "got x={}", pt[0]); + assert!((pt[1] - 0.40).abs() < 1e-6, "got y={}", pt[1]); + // sin(90 deg) + cos(0 deg) + safe_div(1,0) = 1 + 1 + 0 = 2.0 + let ang = comp.eval_number(xf, "Angle", 0.0, 0.0, &expr); + assert!((ang - 2.0).abs() < 1e-6, "got {ang}"); + } + + #[test] + fn resolves_instanced_source_op_inheritance_chains_and_keeps_image_wires_isolated() { + let src = r#"Composition { + Tools = ordered() { + Loader1 = Loader {}, + Transform2 = Transform { + Inputs = { + Input = Input { SourceOp = "Loader1", Source = "Output", }, + }, + }, + Ellipse1 = EllipseMask {}, + ColorCorrector1_6Blend = BezierSpline { + KeyFrames = { + [0] = { 0.25, Flags = { Linear = true } }, + [10] = { 0.75, Flags = { Linear = true } }, + }, + }, + ColorCorrector1_6 = ColorCorrector { + Inputs = { + Blend = Input { SourceOp = "ColorCorrector1_6Blend", Source = "Value", }, + WheelTintAngle1 = Input { Value = -0.434283, }, + WheelHue1 = Input { Value = 0.2, }, + PreDividePostMultiply = Input { Value = 1, }, + Input = Input { SourceOp = "Loader1", Source = "Output", }, + EffectMask = Input { SourceOp = "Ellipse1", Source = "Mask", }, + }, + }, + Instance_ColorCorrector1_6 = ColorCorrector { + SourceOp = "ColorCorrector1_6", + Inputs = { + Input = Input { SourceOp = "Transform2", Source = "Output", }, + EffectMask = Input {}, + WheelTintAngle1 = Input {}, + WheelHue1 = Input { Value = 0.9, }, + }, + }, + Instance_Chained = ColorCorrector { + SourceOp = "Instance_ColorCorrector1_6", + Inputs = { + Input = Input { SourceOp = "Loader1", Source = "Output", }, + }, + }, + CycleA = Blur { + SourceOp = "CycleB", + Inputs = { + XBlurSize = Input { Value = 3.0, }, + }, + }, + CycleB = Blur { + SourceOp = "CycleA", + Inputs = { + YBlurSize = Input { Value = 7.0, }, + }, + }, + }, + }"#; + + let comp = Comp::from_fusion_str(src).expect("parse instanced comp"); + let expr = ExprEngine::new(); + + let inst = comp.node(comp.find_node("Instance_ColorCorrector1_6").unwrap()); + // Empty `WheelTintAngle1 = Input {}` is a de-instanced override (falls back to tool default), + // while omitted params (`Blend`, `PreDividePostMultiply`) inherit from master! + let tint = comp.eval_number(inst, "WheelTintAngle1", 0.0, 0.0, &expr); + assert!(tint.abs() < 1e-6, "de-instanced empty Input {{}} must not inherit master value, got {tint}"); + let blend_t5 = comp.eval_number(inst, "Blend", 5.0, 1.0, &expr); + assert!((blend_t5 - 0.5).abs() < 1e-6, "got {blend_t5}"); + let pdpm = comp.eval_number(inst, "PreDividePostMultiply", 0.0, 0.0, &expr); + assert!((pdpm - 1.0).abs() < 1e-6, "got {pdpm}"); + // Keeps its own explicit override (`WheelHue1 = 0.9`) and its own `Input` wire (`Transform2`)! + let hue = comp.eval_number(inst, "WheelHue1", 0.0, 0.0, &expr); + assert!((hue - 0.9).abs() < 1e-6, "got {hue}"); + assert_eq!(inst.connected_node("Input"), Some("Transform2")); + // NEVER inherits parent's `EffectMask` image/mask wire! + assert_eq!(inst.connected_node("EffectMask"), None); + + // Chained inheritance (`Instance_Chained -> Instance_ColorCorrector1_6 -> ColorCorrector1_6`): + // nearest ancestor wins (`WheelHue1 = 0.9`, and `WheelTintAngle1` was de-instanced by parent), + // grandparent fills remaining omitted params (`Blend`, `PreDividePostMultiply`). + let chained = comp.node(comp.find_node("Instance_Chained").unwrap()); + assert!((comp.eval_number(chained, "WheelHue1", 0.0, 0.0, &expr) - 0.9).abs() < 1e-6); + assert!(comp.eval_number(chained, "WheelTintAngle1", 0.0, 0.0, &expr).abs() < 1e-6); + assert!((comp.eval_number(chained, "Blend", 10.0, 0.0, &expr) - 0.75).abs() < 1e-6); + assert!((comp.eval_number(chained, "PreDividePostMultiply", 0.0, 0.0, &expr) - 1.0).abs() < 1e-6); + assert_eq!(chained.connected_node("Input"), Some("Loader1")); + assert_eq!(chained.connected_node("EffectMask"), None); + + // Cycle safety (`CycleA <-> CycleB` terminates cleanly and cross-inherits missing params) + let cyc_a = comp.node(comp.find_node("CycleA").unwrap()); + let cyc_b = comp.node(comp.find_node("CycleB").unwrap()); + assert!((comp.eval_number(cyc_a, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6); + assert!((comp.eval_number(cyc_a, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6); + assert!((comp.eval_number(cyc_b, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6); + assert!((comp.eval_number(cyc_b, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6); + + // Roundtrip preserves SourceOp inheritance and de-instanced `Input {}` overrides without duplicating master params + let saved = comp.to_fusion_string(); + let reloaded = Comp::from_fusion_str(&saved).expect("reload"); + let r_inst = reloaded.node(reloaded.find_node("Instance_ColorCorrector1_6").unwrap()); + assert!(reloaded.eval_number(r_inst, "WheelTintAngle1", 0.0, 0.0, &expr).abs() < 1e-6); + assert!((reloaded.eval_number(r_inst, "Blend", 5.0, 1.0, &expr) - 0.5).abs() < 1e-6); + assert_eq!(r_inst.connected_node("EffectMask"), None); + } + + #[test] + fn parses_styled_text_and_text_bezier_spline_keyframes() { + let src = r#"Composition { + Tools = ordered() { + Text_1 = TextPlus { + Inputs = { + StyledText = Input { + SourceOp = "Text_1StyledText", + Source = "Value", + }, + }, + }, + Text_1StyledText = BezierSpline { + KeyFrames = { + [10] = { 0, Value = StyledText { Value = "first line" } }, + [20] = { 1, Value = Text { Value = "second line" } }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse styled text spline"); + let expr = ExprEngine::new(); + let node = comp.node(comp.find_node("Text_1").unwrap()); + assert_eq!(comp.eval_text(node, "StyledText", 5.0, "", &expr), "first line"); + assert_eq!(comp.eval_text(node, "StyledText", 10.0, "", &expr), "first line"); + assert_eq!(comp.eval_text(node, "StyledText", 25.0, "", &expr), "second line"); + } + + #[test] + fn source_op_inherits_all_color_corrector_params_and_respects_blend_override() { + // Mirrors repro_seed_110: N4 inherits Wheel*/TintMode/*RGBGain/PreDividePostMultiply + // from N2 while keeping its own `Input` wire and `Blend = 0.75` override. + let src = r#"Composition { + Tools = ordered() { + S0 = Loader {}, + S1 = DaySky {}, + N2 = ColorCorrector { + Inputs = { + Input = Input { SourceOp = "S0", Source = "Output", }, + WheelHue1 = Input { Value = -0.235, }, + WheelSaturation1 = Input { Value = 0.65, }, + WheelTintAngle1 = Input { Value = 0.323, }, + WheelTintLength1 = Input { Value = 0.67, }, + TintMode = Input { Value = 0, }, + MasterRGBGain = Input { Value = 0.65, }, + ShadowsRGBGain = Input { Value = 0.84, }, + HighlightsRGBGain = Input { Value = 0.75, }, + PreDividePostMultiply = Input { Value = 1, }, + Blend = Input { Value = 1.0, }, + }, + }, + N4 = ColorCorrector { + SourceOp = "N2", + Inputs = { + Input = Input { SourceOp = "S1", Source = "Output", }, + Blend = Input { Value = 0.75, }, + }, + }, + N5 = ColorCorrector { + SourceOp = "N2", + Inputs = { + Input = Input { SourceOp = "S1", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse seed 110 style SourceOp"); + let expr = ExprEngine::new(); + let n4 = comp.node(comp.find_node("N4").unwrap()); + assert_eq!(n4.connected_node("Input"), Some("S1")); + assert!((comp.eval_number(n4, "Blend", 1.0, 1.0, &expr) - 0.75).abs() < 1e-6); + assert!((comp.eval_number(n4, "WheelHue1", 1.0, 0.0, &expr) - (-0.235)).abs() < 1e-6); + assert!((comp.eval_number(n4, "WheelSaturation1", 1.0, 1.0, &expr) - 0.65).abs() < 1e-6); + assert!((comp.eval_number(n4, "WheelTintAngle1", 1.0, 0.0, &expr) - 0.323).abs() < 1e-6); + assert!((comp.eval_number(n4, "WheelTintLength1", 1.0, 0.0, &expr) - 0.67).abs() < 1e-6); + assert!((comp.eval_number(n4, "TintMode", 1.0, 2.0, &expr) - 0.0).abs() < 1e-6); + assert!((comp.eval_number(n4, "MasterRGBGain", 1.0, 1.0, &expr) - 0.65).abs() < 1e-6); + assert!((comp.eval_number(n4, "ShadowsRGBGain", 1.0, 1.0, &expr) - 0.84).abs() < 1e-6); + assert!((comp.eval_number(n4, "HighlightsRGBGain", 1.0, 1.0, &expr) - 0.75).abs() < 1e-6); + assert!((comp.eval_number(n4, "PreDividePostMultiply", 1.0, 0.0, &expr) - 1.0).abs() < 1e-6); + + let n5 = comp.node(comp.find_node("N5").unwrap()); + assert!((comp.eval_number(n5, "Blend", 1.0, 0.0, &expr) - 1.0).abs() < 1e-6); + } + + #[test] + fn hue_curves_lut_bezier_applies_cyclic_ends_and_roundtrips_cleanly() { + let src = r#"Composition { + Tools = ordered() { + Bg = Background {}, + HC_RSup = LUTBezier { + SmoothEndsTransition = true, + KeyColorSplines = { + [0] = { + [0] = { 0.5 }, + [2] = { 1.0 }, + [6] = { 0.5 }, + } + }, + }, + CC_Red = LUTBezier { + SmoothEndsTransition = true, + KeyColorSplines = { + [0] = { + [0.0] = { 0.0 }, + [0.5] = { 0.8 }, + [1.0] = { 0.2 }, + } + }, + }, + HC1 = HueCurves { + Inputs = { + Input = Input { SourceOp = "Bg", Source = "Output", }, + RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", }, + }, + }, + CC1 = ColorCurves { + Inputs = { + Input = Input { SourceOp = "Bg", Source = "Output", }, + Red = Input { SourceOp = "CC_Red", Source = "Value", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse HueCurves + ColorCurves"); + let rsup = comp.splines.get("HC_RSup").expect("HC_RSup"); + assert!(rsup.keyframes[2].lh.is_some()); + assert!((rsup.eval(5.0) - 0.4140625).abs() < 1e-3); + + // ColorCurves [0..1] must NOT get cyclic HueCurves wrapping even with SmoothEndsTransition = true. + let cc_red = comp.splines.get("CC_Red").expect("CC_Red"); + assert!((cc_red.eval(1.0) - 0.2).abs() < 1e-6); + assert!((cc_red.eval(0.75) - 0.5).abs() < 1e-6); + + // Lossless roundtrip keeps KeyColorSplines untouched when unedited. + let saved = comp.to_fusion_string(); + assert!(!saved.contains("LH =")); + let reloaded = Comp::from_fusion_str(&saved).expect("reload"); + assert!((reloaded.splines["HC_RSup"].eval(5.0) - rsup.eval(5.0)).abs() < 1e-9); + } + + #[test] + fn comp_eval_number_clamps_loop_spline_before_first_keyframe() { + let src = r#"Composition { + Tools = ordered() { + CG = ColorGain { + Inputs = { + HighHue = Input { SourceOp = "ColorGain1HighHue", Source = "Value", }, + }, + }, + ColorGain1HighHue = BezierSpline { + KeyFrames = { + [4129] = { 0, RH = { 4137.66666666667, 0.333333333333333 }, Flags = { Linear = true, Loop = true } }, + [4155] = { 1, LH = { 4146.33333333333, 0.666666666666667 }, Flags = { Linear = true, Loop = true } }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse underwater loop spline"); + let expr = ExprEngine::new(); + let cg = comp.node(comp.find_node("CG").unwrap()); + assert!((comp.eval_number(cg, "HighHue", 3933.0, 0.0, &expr) - 0.0).abs() < 1e-9); + assert!((comp.eval_number(cg, "HighHue", 4142.0, 0.0, &expr) - 0.5).abs() < 1e-9); + assert!((comp.eval_number(cg, "HighHue", 4155.0, 0.0, &expr) - 0.0).abs() < 1e-9); + assert!((comp.eval_number(cg, "HighHue", 4168.0, 0.0, &expr) - 0.5).abs() < 1e-9); + } + + #[test] + fn cyclic_expression_references_terminate() { + let src = r#"Composition { + Tools = ordered() { + N = Transform { + Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, }, + }, + E = Expression { + Inputs = { + n1 = Input { Expression = "N.Size", }, + NumberExpression = Input { Value = "n1 + 1", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let n = comp.node(comp.find_node("N").unwrap()); + let v = comp.eval_number(n, "Size", 0.0, 7.0, &ExprEngine::new()); + assert!(v.is_finite()); + } + + #[test] + fn clamp_with_inverted_bounds_does_not_panic() { + let src = r#"Composition { + Tools = ordered() { + N = Transform { Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, }, }, + E = Expression { + Inputs = { + n1 = Input { Value = 5, }, + NumberExpression = Input { Value = "clamp(n1, 1, 0)", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let n = comp.node(comp.find_node("N").unwrap()); + assert_eq!(comp.eval_number(n, "Size", 0.0, 9.0, &ExprEngine::new()), 0.0); + } + + #[test] + fn explicit_frame_format_is_never_overwritten_by_inferred_size() { + let tools = r#"Tools = ordered() { + BG = Background { Inputs = { Width = Input { Value = 1280, }, Height = Input { Value = 720, }, }, }, + }"#; + let explicit = Comp::from_fusion_str(&format!( + "Composition {{ Prefs = {{ Comp = {{ FrameFormat = {{ Width = 1920, Height = 1080, }}, }}, }}, {tools} }}" + )) + .unwrap(); + assert_eq!((explicit.width, explicit.height), (1920, 1080)); + + let inferred = Comp::from_fusion_str(&format!("Composition {{ {tools} }}")).unwrap(); + assert_eq!((inferred.width, inferred.height), (1280, 720)); + } + + #[test] + fn each_loaded_comp_gets_a_distinct_revision_range() { + let src = "Composition { Tools = ordered() { } }"; + let a = Comp::from_fusion_str(src).unwrap(); + let mut b = Comp::from_fusion_str(src).unwrap(); + for _ in 0..1000 { + b.revision += 1; + } + let c = Comp::from_fusion_str(src).unwrap(); + assert!(a.revision != b.revision && b.revision != c.revision && a.revision != c.revision); + assert!(c.revision > b.revision); + } + + const GROUP_COMP: &str = r#"Composition { + Tools = ordered() { + BG = Background { }, + BG2 = Background { }, + Group1 = GroupOperator { + Inputs = { + MainInput1 = InstanceInput { SourceOp = "Inner1", Source = "Input", }, + BlurSize = InstanceInput { SourceOp = "Inner1", Source = "XBlurSize", Default = 3, }, + }, + Outputs = { + MainOutput1 = InstanceOutput { SourceOp = "Inner2", Source = "Output", }, + }, + Tools = ordered() { + Inner1 = Blur { + Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + }, + }, + Inner2 = Transform { + Inputs = { + Input = Input { SourceOp = "Inner1", Source = "Output", }, + Size = Input { Value = 1, }, + }, + }, + Inner3 = Blur { }, + }, + }, + }, +}"#; + + #[test] + fn unedited_group_roundtrips_byte_for_byte() { + let comp = Comp::from_fusion_str(GROUP_COMP).unwrap(); + let tools = |t: &LuaTable| t.get_table("Tools").unwrap().to_fusion_string(); + assert_eq!(tools(&comp.sync_to_raw_ast()), tools(comp.raw_root.as_ref().unwrap())); + } + + #[test] + fn nested_group_edits_and_wiring_survive_save() { + let mut comp = Comp::from_fusion_str(GROUP_COMP).unwrap(); + let group = comp.find_node("Group1").unwrap(); + assert_eq!(comp.node(group).connected_node("Input"), Some("BG")); + + comp.delete_nodes(&[comp.find_node("Inner3").unwrap()]); + let inner2 = comp.find_node("Inner2").unwrap(); + assert!(comp.set_input_value(inner2, "Size", ParamValue::Number(2.5))); + let (group, bg2) = (comp.find_node("Group1").unwrap(), comp.find_node("BG2").unwrap()); + comp.connect_output(bg2, "Output", group, "Input").unwrap(); + + let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); + let inner2 = saved.node(saved.find_node("Inner2").unwrap()); + assert_eq!(inner2.static_number("Size"), Some(2.5)); + assert!(saved.find_node("Inner3").is_none()); + assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), Some("BG2")); + assert_eq!(saved.node(saved.find_node("Group1").unwrap()).connected_node("Input"), Some("BG2")); + // The exposed `Default` stays on the InstanceInput instead of leaking onto Inner1. + let text = comp.to_fusion_string(); + assert_eq!(text.matches("Value = 3").count(), 0, "{text}"); + + let mut comp = saved; + let group = comp.find_node("Group1").unwrap(); + assert!(comp.disconnect(group, "Input")); + let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); + assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), None); + } +} diff --git a/crates/model/src/edit.rs b/crates/model/src/edit.rs index 5308d24d4851bfb04e1ba8191f43c4d8e6178b2e..798f3b470cf21394ce6c44cfc5f955722ec1b384 100644 --- a/crates/model/src/edit.rs +++ b/crates/model/src/edit.rs @@ -1,23 +1,28 @@ //! Lossless graph & parameter mutation API for `Comp`, plus `CompHistory` undo/redo stack. +mod clipboard; +mod defaults; +mod history; +mod keyframes; +#[cfg(test)] +mod tests; + +pub use history::{CompHistory, DEFAULT_MAX_HISTORY}; + +use clipboard::{rename_expression_idents, rewrite_formulas_deep}; +use defaults::{default_inputs_for_kind, default_view_info_for_kind}; use crate::comp::{ Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut, find_raw_tool, find_raw_tool_mut, is_group_kind, is_modifier_type, param_value_to_lua, vec2_lua, }; -use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident, parse_lua}; -use crate::spline::{BezierSpline, Keyframe}; +use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident}; use std::collections::{HashMap, HashSet, VecDeque}; -/// Default maximum number of undo steps retained by [`CompHistory`]. -pub const DEFAULT_MAX_HISTORY: usize = 128; - -/// Keyframe times closer than this are the same keyframe (matches the Inspector's `keyframe_state`). -const KEYFRAME_EPS: f64 = 1e-4; - /// Expression-modifier inputs whose `Value` is a formula string. -const EXPRESSION_FORMULA_INPUTS: &[&str] = +pub(super) const EXPRESSION_FORMULA_INPUTS: &[&str] = &["NumberExpression", "PointExpressionX", "PointExpressionY", "PointExpression"]; + impl Comp { fn modifier_exists(&self, name: &str) -> bool { self.splines.contains_key(name) @@ -367,182 +372,7 @@ impl Comp { /// Serializes `ids` plus every modifier (spline, path, shake, ...) they reference into /// Fusion's clipboard format: `{ Tools = ordered() { ... }, ActiveTool = "" }`. - /// References to unselected nodes are kept verbatim and dropped again on paste if missing. - pub fn export_fusion_clipboard(&self, ids: &[NodeId]) -> String { - let synced = self.sync_to_raw_ast(); - let root_tools = synced.get_table("Tools"); - let node_names: HashSet<&str> = self.nodes.iter().map(|n| n.name.as_str()).collect(); - let mut picked: Vec<&Node> = Vec::new(); - for &id in ids { - if let Some(n) = self.nodes.get(id.0) { - if !picked.iter().any(|p| p.id == n.id) { - picked.push(n); - } - } - } - let mut tools = LuaTable { - tag: Some("ordered".to_owned()), - entries: Vec::new(), - }; - let mut refs: VecDeque = VecDeque::new(); - for n in &picked { - let raw = root_tools.and_then(|t| find_raw_tool(t, &n.name)).unwrap_or(&n.raw); - let mut found = HashSet::new(); - collect_source_ops_in_table(raw, &mut found); - let mut found: Vec = found.into_iter().collect(); - found.sort(); - refs.extend(found); - tools.set(LuaKey::Str(n.name.clone()), LuaValue::Table(raw.clone())); - } - while let Some(name) = refs.pop_front() { - if tools.get(&name).is_some() || node_names.contains(name.as_str()) { - continue; - } - // Modifiers already nested inside a copied group travel with it. - let nested_in_copy = tools - .entries - .iter() - .filter_map(|(_, v)| v.as_table()?.get_table("Tools")) - .any(|inner| find_raw_tool(inner, &name).is_some()); - let Some(modifier) = root_tools.and_then(|t| find_raw_tool(t, &name)).filter(|_| !nested_in_copy) - else { - continue; - }; - let mut found = HashSet::new(); - collect_source_ops_in_table(modifier, &mut found); - let mut found: Vec = found.into_iter().collect(); - found.sort(); - refs.extend(found); - tools.set(LuaKey::Str(name), LuaValue::Table(modifier.clone())); - } - - let mut doc = LuaTable::default(); - doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools)); - if let Some(first) = picked.first() { - doc.set( - LuaKey::Str("ActiveTool".to_owned()), - LuaValue::String(first.name.clone()), - ); - } - doc.to_fusion_string() - } - - /// Pastes Fusion clipboard Lua (`{ Tools = ordered() { ... } }` or a full `Composition`), - /// renaming colliding tools/modifiers (`Blur1` -> `Blur1_1`), rewiring references among the - /// pasted tools, dropping references to tools that exist nowhere, and shifting each top-level - /// tool's `ViewInfo.Pos` by `offset`. Returns the new top-level flow nodes; on `Err` the comp - /// is untouched. Prefer [`CompHistory::paste_fusion_clipboard`] for an undoable paste. - pub fn paste_fusion_clipboard( - &mut self, - lua_snippet: &str, - offset: (f32, f32), - ) -> Result, String> { - let parsed = parse_lua(lua_snippet).map_err(|e| format!("clipboard is not Fusion Lua: {e}"))?; - let mut tools = parsed - .as_table() - .and_then(|t| t.get_table("Tools")) - .filter(|t| !t.entries.is_empty()) - .cloned() - .ok_or_else(|| "clipboard has no Fusion tools".to_owned())?; - - let mut pasted_names = Vec::new(); - collect_tool_names(&tools, &mut pasted_names); - let pasted_set: HashSet<&str> = pasted_names.iter().map(String::as_str).collect(); - - drop_unknown_source_ops(&mut tools, &mut |name| { - pasted_set.contains(name) || self.is_linkable_external(name) - }); - - let mut reserved: HashSet = self.nodes.iter().map(|n| n.name.clone()).collect(); - let mut renames: HashMap = HashMap::new(); - for name in &pasted_names { - if renames.contains_key(name) { - continue; - } - let fresh = self.generate_unique_name_excluding(name, &reserved); - reserved.insert(fresh.clone()); - renames.insert(name.clone(), fresh); - } - rename_tools(&mut tools, &renames); - - let mut doc = LuaTable { - tag: Some("Composition".to_owned()), - entries: Vec::new(), - }; - doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools)); - let staged = Comp::from_fusion_str(&doc.to_fusion_string()) - .map_err(|e| format!("clipboard tools failed to parse: {e}"))?; - let Some(staged_tools) = doc.get_table("Tools") else { - return Err("clipboard has no Fusion tools".to_owned()); - }; - - let base = self.nodes.len(); - let shift = |id: NodeId| NodeId(base + id.0); - let mut created = Vec::new(); - let mut top_level: HashMap = HashMap::new(); - for mut node in staged.nodes { - node.id = shift(node.id); - node.macro_output = node.macro_output.map(shift); - if !node.internal { - node.pos = [node.pos[0] + offset.0, node.pos[1] + offset.1]; - set_view_info_pos(&mut node.raw, node.pos); - top_level.insert(node.name.clone(), node.raw.clone()); - created.push(node.id); - } - self.nodes.push(node); - } - for (name, id) in staged.node_by_name { - self.node_by_name.entry(name).or_insert(shift(id)); - } - self.splines.extend(staged.splines); - self.poly_paths.extend(staged.poly_paths); - self.gradient_modifiers.extend(staged.gradient_modifiers); - self.text_modifiers.extend(staged.text_modifiers); - self.text_splines.extend(staged.text_splines); - self.polyline_splines.extend(staged.polyline_splines); - self.text_cls.extend(staged.text_cls); - self.shakes.extend(staged.shakes); - self.expression_modifiers.extend(staged.expression_modifiers); - - if let Some(root) = self.raw_root.as_mut() { - let dest = ensure_table_mut(root, "Tools", Some("ordered")); - for (key, value) in &staged_tools.entries { - let LuaKey::Str(name) = key else { continue }; - let table = top_level.remove(name).map_or_else(|| value.clone(), LuaValue::Table); - dest.set(key.clone(), table); - } - } - - self.revision += 1; - Ok(created) - } - - /// Duplicates the selected nodes at `pos + offset` with unique names, as a copy + paste: - /// wires between duplicated nodes are preserved, wires to other nodes stay intact, and owned - /// modifiers and group contents are cloned. Returns the new top-level nodes. - pub fn duplicate_nodes(&mut self, ids: &[NodeId], offset: [f32; 2]) -> Vec { - let snippet = self.export_fusion_clipboard(ids); - self.paste_fusion_clipboard(&snippet, (offset[0], offset[1])).unwrap_or_default() - } - - fn generate_unique_name_excluding(&self, hint: &str, reserved: &HashSet) -> String { - let base = sanitize_lua_ident(hint); - if !self.name_exists(&base) && !reserved.contains(&base) { - return base; - } - let mut idx = 1usize; - loop { - let candidate = format!("{base}_{idx}"); - if !self.name_exists(&candidate) && !reserved.contains(&candidate) { - return candidate; - } - idx += 1; - } - } - - /// Renames `id` to `new_name`, updating `node_by_name`, `raw_root.Tools`, and all `SourceOp` - /// references across every node's `inputs`, `raw` AST tables, and `raw_root`. pub fn rename_node(&mut self, id: NodeId, new_name: &str) -> Result { if id.0 >= self.nodes.len() { return Err(format!("invalid node id {}", id.0)); @@ -895,410 +725,9 @@ impl Comp { set_view_info_pos(&mut n.raw, pos); self.revision += 1; } - - /// Inserts or updates a scalar keyframe at `(frame, value)` on `node`'s `input`. - /// - If `input` is already connected to a `BezierSpline`, updates/inserts the keyframe there. - /// - Otherwise creates a new `BezierSpline` named `` (deduplicated), - /// wires `input` to it (`SourceOp = spline_name, Source = "Value"`), and inserts the keyframe. - /// Returns the spline's name. - pub fn set_keyframe( - &mut self, - node: NodeId, - input: &str, - frame: f64, - value: f64, - ) -> Result { - if node.0 >= self.nodes.len() { - return Err(format!("invalid node id {}", node.0)); - } - if !frame.is_finite() || !value.is_finite() { - return Err("keyframe frame and value must be finite numbers".to_owned()); - } - - let existing_spline = self.nodes[node.0] - .inputs - .get(input) - .and_then(|b| b.source_op.clone()) - .filter(|op| self.splines.contains_key(op)); - - let spline_name = if let Some(sp_name) = existing_spline { - let sp = self.splines.get_mut(&sp_name).expect("spline exists"); - upsert_keyframe(sp, frame, value); - sp_name - } else { - let hint = format!("{}{}", self.nodes[node.0].name, input); - let sp_name = self.generate_unique_name("BezierSpline", Some(&hint)); - let color = default_spline_color(&sp_name); - let spline = BezierSpline { - name: sp_name.clone(), - color, - keyframes: vec![Keyframe::new(frame, value)], - }; - self.splines.insert(sp_name.clone(), spline); - - let n = &mut self.nodes[node.0]; - let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding { - value: None, - source_op: None, - source_output: None, - expression: None, - }); - entry.source_op = Some(sp_name.clone()); - entry.source_output = Some("Value".to_owned()); - - let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None); - let port_tbl = ensure_table_mut(in_tbl, input, Some("Input")); - port_tbl.set( - LuaKey::Str("SourceOp".to_owned()), - LuaValue::String(sp_name.clone()), - ); - port_tbl.set( - LuaKey::Str("Source".to_owned()), - LuaValue::String("Value".to_owned()), - ); - - sp_name - }; - - self.revision += 1; - Ok(spline_name) - } - - /// Removes the keyframe at `frame` from `spline_name`. Returns `true` if a keyframe was deleted. - /// Deleting a spline's last keyframe removes the spline and leaves every input it drove with - /// that keyframe's value as a static `Value`. - pub fn delete_keyframe(&mut self, spline_name: &str, frame: f64) -> bool { - let Some(sp) = self.splines.get_mut(spline_name) else { - return false; - }; - let Some(pos) = sp - .keyframes - .iter() - .position(|kf| (kf.time - frame).abs() < KEYFRAME_EPS) - else { - return false; - }; - let removed = sp.keyframes.remove(pos); - if sp.keyframes.is_empty() { - self.splines.remove(spline_name); - let value = ParamValue::Number(removed.value); - for node in &mut self.nodes { - for (port, binding) in &mut node.inputs { - if binding.source_op.as_deref() != Some(spline_name) { - continue; - } - binding.source_op = None; - binding.source_output = None; - binding.value = Some(value.clone()); - let port_tbl = ensure_table_mut(ensure_table_mut(&mut node.raw, "Inputs", None), port, Some("Input")); - port_tbl.remove(&LuaKey::Str("SourceOp".to_owned())); - port_tbl.remove(&LuaKey::Str("Source".to_owned())); - port_tbl.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&value)); - } - } - if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) { - remove_tools_recursive(tools, &HashSet::from([spline_name.to_owned()])); - } - } - self.revision += 1; - true - } -} - -#[derive(Clone, Debug)] -struct HistoryEntry { - label: String, - snapshot: Comp, - coalesce_key: Option, -} - -/// Snapshot-based undo/redo history stack for [`Comp`] with transaction groups and drag coalescing. -#[derive(Clone, Debug)] -pub struct CompHistory { - undo_stack: VecDeque, - redo_stack: Vec, - max_depth: usize, - active_group: Option<(String, Comp)>, - group_depth: usize, - /// Position in `undo_stack` corresponding to the last saved state (`Some(0)` means clean at - /// depth 0; `None` means the saved state is no longer reachable via undo/redo). - saved_undo_depth: Option, - saved_revision: Option, -} - -impl Default for CompHistory { - fn default() -> Self { - Self::new() - } -} - -impl CompHistory { - pub fn new() -> Self { - Self::with_max_depth(DEFAULT_MAX_HISTORY) - } - - pub fn with_max_depth(max_depth: usize) -> Self { - Self { - undo_stack: VecDeque::new(), - redo_stack: Vec::new(), - max_depth: max_depth.max(1), - active_group: None, - group_depth: 0, - saved_undo_depth: None, - saved_revision: None, - } - } - - pub fn max_depth(&self) -> usize { - self.max_depth - } - - pub fn can_undo(&self) -> bool { - !self.undo_stack.is_empty() - } - - pub fn can_redo(&self) -> bool { - !self.redo_stack.is_empty() - } - - pub fn undo_len(&self) -> usize { - self.undo_stack.len() - } - - pub fn redo_len(&self) -> usize { - self.redo_stack.len() - } - - pub fn undo_label(&self) -> Option<&str> { - self.undo_stack.back().map(|e| e.label.as_str()) - } - - pub fn redo_label(&self) -> Option<&str> { - self.redo_stack.last().map(|e| e.label.as_str()) - } - - pub fn in_group(&self) -> bool { - self.group_depth > 0 - } - - /// Clears all undo/redo entries and any active transaction group. - pub fn clear(&mut self) { - self.undo_stack.clear(); - self.redo_stack.clear(); - self.active_group = None; - self.group_depth = 0; - self.saved_undo_depth = None; - self.saved_revision = None; - } - - /// Records the current state of `comp` as the clean saved point. - pub fn mark_saved(&mut self, comp: &Comp) { - // Edits after a save must never coalesce into the saved undo entry. - self.break_coalescing(); - self.saved_undo_depth = Some(self.undo_stack.len()); - self.saved_revision = Some(comp.revision); - } - - pub fn saved_revision(&self) -> Option { - self.saved_revision - } - - /// Returns `true` if `comp` has unsaved modifications relative to the last [`Self::mark_saved`]. - pub fn is_dirty(&self, comp: &Comp) -> bool { - match self.saved_undo_depth { - Some(depth) if depth == self.undo_stack.len() => { - // If an edit was pushed via coalescing or outside history after mark_saved, - // check whether we're still at the saved depth without an active modified group. - if let Some((_, ref snap)) = self.active_group { - comp.revision != snap.revision - } else { - false - } - } - _ => self.saved_revision != Some(comp.revision), - } - } - - /// Pushes a snapshot of `comp` BEFORE applying a discrete mutation. - /// No-op if currently inside a [`Self::begin_group`] transaction. - pub fn push_snapshot(&mut self, comp: &Comp, label: impl Into) { - if self.group_depth > 0 { - return; - } - self.push_entry(HistoryEntry { - label: label.into(), - snapshot: comp.clone(), - coalesce_key: None, - }); - } - - /// Pushes a snapshot of `comp` BEFORE applying a continuous mutation (such as dragging a node - /// or scrubbing a parameter slider). Consecutive calls with the same `key` coalesce into a - /// single undo step preserving the initial pre-drag snapshot. - /// No-op if currently inside a [`Self::begin_group`] transaction. - pub fn push_coalesced( - &mut self, - comp: &Comp, - label: impl Into, - key: impl Into, - ) { - if self.group_depth > 0 { - return; - } - let key_str = key.into(); - let label_str = label.into(); - if self.redo_stack.is_empty() { - if let Some(top) = self.undo_stack.back_mut() { - if top.coalesce_key.as_deref() == Some(key_str.as_str()) { - top.label = label_str; - return; - } - } - } - self.push_entry(HistoryEntry { - label: label_str, - snapshot: comp.clone(), - coalesce_key: Some(key_str), - }); - } - - /// Breaks coalescing on the top undo entry so subsequent edits with the same key start a new - /// undo step (e.g. on pointer release). - pub fn break_coalescing(&mut self) { - if let Some(top) = self.undo_stack.back_mut() { - top.coalesce_key = None; - } - } - - /// Begins a transaction group. All mutations until the matching [`Self::commit_group`] collapse - /// into a single undo step. Supports nesting. - pub fn begin_group(&mut self, comp: &Comp, label: impl Into) { - if self.group_depth == 0 { - self.active_group = Some((label.into(), comp.clone())); - } - self.group_depth += 1; - } - - /// Commits the current transaction group. When the outermost group closes, pushes one undo - /// entry if `comp.revision` changed since `begin_group`. Returns `true` if an entry was added. - pub fn commit_group(&mut self, comp: &Comp) -> bool { - if self.group_depth == 0 { - return false; - } - self.group_depth -= 1; - if self.group_depth > 0 { - return false; - } - let Some((label, snapshot)) = self.active_group.take() else { - return false; - }; - if comp.revision == snapshot.revision { - return false; - } - self.push_entry(HistoryEntry { - label, - snapshot, - coalesce_key: None, - }); - true - } - - /// Cancels the active transaction group and restores `comp` to its pre-group state. - pub fn cancel_group(&mut self, comp: &mut Comp) -> bool { - if self.group_depth == 0 { - return false; - } - self.group_depth = 0; - let Some((_, snapshot)) = self.active_group.take() else { - return false; - }; - let prev_rev = comp.revision; - restore_snapshot(comp, snapshot); - if comp.revision != prev_rev { - comp.revision = prev_rev.max(comp.revision) + 1; - } - true - } - - /// Undoable [`Comp::paste_fusion_clipboard`]: the whole paste is one undo step, and a failed - /// paste leaves both `comp` and the history untouched. - pub fn paste_fusion_clipboard( - &mut self, - comp: &mut Comp, - lua_snippet: &str, - offset: (f32, f32), - ) -> Result, String> { - self.begin_group(comp, "Paste"); - let pasted = comp.paste_fusion_clipboard(lua_snippet, offset); - self.commit_group(comp); - pasted - } - - /// Undoes the most recent edit, restoring `comp` to the saved snapshot. - /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly. - pub fn undo(&mut self, comp: &mut Comp) -> bool { - if self.group_depth > 0 { - self.group_depth = 1; - self.commit_group(comp); - } - let Some(entry) = self.undo_stack.pop_back() else { - return false; - }; - let prev_rev = comp.revision; - let redo_entry = HistoryEntry { - label: entry.label, - snapshot: comp.clone(), - coalesce_key: None, - }; - self.redo_stack.push(redo_entry); - restore_snapshot(comp, entry.snapshot); - comp.revision = prev_rev.max(comp.revision) + 1; - true - } - - /// Redoes the most recently undone edit. - /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly. - pub fn redo(&mut self, comp: &mut Comp) -> bool { - let Some(entry) = self.redo_stack.pop() else { - return false; - }; - let prev_rev = comp.revision; - let undo_entry = HistoryEntry { - label: entry.label, - snapshot: comp.clone(), - coalesce_key: None, - }; - self.undo_stack.push_back(undo_entry); - restore_snapshot(comp, entry.snapshot); - comp.revision = prev_rev.max(comp.revision) + 1; - true - } - - fn push_entry(&mut self, entry: HistoryEntry) { - // Any saved state that lived in the redo branch is now unreachable. - if let Some(saved_depth) = self.saved_undo_depth { - if saved_depth > self.undo_stack.len() { - self.saved_undo_depth = None; - } - } - self.redo_stack.clear(); - self.undo_stack.push_back(entry); - while self.undo_stack.len() > self.max_depth { - self.undo_stack.pop_front(); - self.saved_undo_depth = self.saved_undo_depth.and_then(|d| d.checked_sub(1)); - } - } -} - -/// Replaces `comp` with `snapshot`, keeping the live file identity so a Save As followed by undo -/// never points Save at the file the snapshot came from. -fn restore_snapshot(comp: &mut Comp, mut snapshot: Comp) { - snapshot.path = comp.path.take(); - snapshot.name = std::mem::take(&mut comp.name); - *comp = snapshot; } -fn sanitize_lua_ident(raw: &str) -> String { +pub(super) fn sanitize_lua_ident(raw: &str) -> String { let mut out = String::with_capacity(raw.len()); for ch in raw.chars() { if ch.is_ascii_alphanumeric() || ch == '_' { @@ -1316,7 +745,7 @@ fn sanitize_lua_ident(raw: &str) -> String { out } -fn collect_node_source_ops(node: &Node, out: &mut HashSet) { +pub(super) fn collect_node_source_ops(node: &Node, out: &mut HashSet) { for binding in node.inputs.values() { if let Some(src) = &binding.source_op { out.insert(src.clone()); @@ -1325,7 +754,7 @@ fn collect_node_source_ops(node: &Node, out: &mut HashSet) { collect_source_ops_in_table(&node.raw, out); } -fn collect_source_ops_in_table(tbl: &LuaTable, out: &mut HashSet) { +pub(super) fn collect_source_ops_in_table(tbl: &LuaTable, out: &mut HashSet) { for (k, v) in &tbl.entries { if let LuaKey::Str(key) = k { if key == "SourceOp" { @@ -1376,7 +805,7 @@ fn count_flow_tools<'a>(tools: &'a LuaTable, out: &mut HashMap<&'a str, usize>) } /// Removes tools named in `names` from `tools` and every nested `Tools` table. -fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet) { +pub(super) fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet) { tools .entries .retain(|(k, _)| !matches!(k, LuaKey::Str(name) if names.contains(name))); @@ -1388,116 +817,8 @@ fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet) { } /// Names of every tool in `tools`, including tools nested in `Tools` tables (macros/groups). -fn collect_tool_names(tools: &LuaTable, out: &mut Vec) { - for (key, value) in &tools.entries { - let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else { - continue; - }; - out.push(name.clone()); - if let Some(inner) = tool.get_table("Tools") { - collect_tool_names(inner, out); - } - } -} -/// Renames tool keys (recursively) and rewrites every reference to them: `SourceOp` values and -/// whole-word identifiers inside `Expression` strings. -fn rename_tools(tools: &mut LuaTable, renames: &HashMap) { - for (key, value) in &mut tools.entries { - let LuaKey::Str(name) = key else { continue }; - if let Some(new) = renames.get(name.as_str()) { - *name = new.clone(); - } - if let Some(tool) = value.as_table_mut() { - rewrite_references(tool, renames); - if let Some(inner) = tool.get_table_mut("Tools") { - rename_tools(inner, renames); - } - } - } -} - -fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap) { - rewrite_formula_values(tbl, renames); - for (key, value) in &mut tbl.entries { - match (key, value) { - (LuaKey::Str(k), LuaValue::String(s)) if k == "SourceOp" => { - if let Some(new) = renames.get(s.as_str()) { - *s = new.clone(); - } - } - (LuaKey::Str(k), LuaValue::String(s)) if k == "Expression" => { - *s = rename_expression_idents(s, renames); - } - (_, LuaValue::Table(sub)) => rewrite_references(sub, renames), - _ => {} - } - } -} - -/// Rewrites the formula strings of an `Expression` modifier table (not recursive). -fn rewrite_formula_values(tbl: &mut LuaTable, renames: &HashMap) { - if tbl.tag.as_deref() != Some("Expression") { - return; - } - let Some(inputs) = tbl.get_table_mut("Inputs") else { return }; - for key in EXPRESSION_FORMULA_INPUTS { - if let Some(LuaValue::String(formula)) = inputs.get_table_mut(key).and_then(|i| i.get_mut("Value")) { - *formula = rename_expression_idents(formula, renames); - } - } -} - -fn rewrite_formulas_deep(tbl: &mut LuaTable, renames: &HashMap) { - rewrite_formula_values(tbl, renames); - for (_, value) in &mut tbl.entries { - if let Some(sub) = value.as_table_mut() { - rewrite_formulas_deep(sub, renames); - } - } -} - -/// Renames whole-word identifiers in `expr`, leaving property names (`Other.Size`) alone. -fn rename_expression_idents(expr: &str, renames: &HashMap) -> String { - let mut out = String::with_capacity(expr.len()); - let mut word = String::new(); - let mut prev = None; - let flush = |word: &mut String, out: &mut String, prev: Option| { - let renamed = renames.get(word.as_str()).filter(|_| prev != Some('.')); - out.push_str(renamed.map_or(word.as_str(), String::as_str)); - word.clear(); - }; - for ch in expr.chars() { - if ch.is_ascii_alphanumeric() || ch == '_' { - word.push(ch); - } else { - flush(&mut word, &mut out, prev); - out.push(ch); - prev = Some(ch); - } - } - flush(&mut word, &mut out, prev); - out -} - -/// Removes `SourceOp`/`Source` pairs whose target fails `exists`, so pasted tools never point at -/// missing operators. -fn drop_unknown_source_ops(tbl: &mut LuaTable, exists: &mut dyn FnMut(&str) -> bool) { - let dangling = tbl - .get_str("SourceOp") - .is_some_and(|name| !exists(name)); - if dangling { - tbl.remove(&LuaKey::Str("SourceOp".to_owned())); - tbl.remove(&LuaKey::Str("Source".to_owned())); - } - for (_, value) in &mut tbl.entries { - if let Some(sub) = value.as_table_mut() { - drop_unknown_source_ops(sub, exists); - } - } -} - -fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) { +pub(super) fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) { let vi = ensure_table_mut(raw, "ViewInfo", Some("OperatorInfo")); vi.set( LuaKey::Str("Pos".to_owned()), @@ -1505,1108 +826,3 @@ fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) { ); } -fn upsert_keyframe(spline: &mut BezierSpline, frame: f64, value: f64) { - if let Some(existing) = spline - .keyframes - .iter_mut() - .find(|kf| (kf.time - frame).abs() < KEYFRAME_EPS) - { - // Handles are absolute coordinates, so they travel with the key. - let (dt, dv) = (frame - existing.time, value - existing.value); - existing.time = frame; - existing.value = value; - for handle in [&mut existing.lh, &mut existing.rh].into_iter().flatten() { - handle[0] += dt; - handle[1] += dv; - } - } else { - spline.keyframes.push(Keyframe::new(frame, value)); - spline.sort(); - } -} - -fn default_spline_color(name: &str) -> [u8; 3] { - // Deterministic vivid Fusion-like spline palette based on name hash. - const PALETTE: &[[u8; 3]] = &[ - [255, 128, 0], - [102, 204, 255], - [170, 238, 102], - [255, 102, 170], - [204, 153, 255], - [255, 221, 85], - ]; - let hash = name - .bytes() - .fold(0usize, |acc, b| acc.wrapping_mul(31).wrapping_add(b as usize)); - PALETTE[hash % PALETTE.len()] -} - -fn default_view_info_for_kind(kind: &str, pos: [f32; 2]) -> LuaTable { - let tag = match kind { - "PipeRouter" => "PipeRouterInfo", - "Underlay" => "UnderlayInfo", - "Note" | "StickyNote" => "StickyNoteInfo", - _ => "OperatorInfo", - }; - let mut vi = LuaTable { - tag: Some(tag.to_owned()), - entries: Vec::new(), - }; - vi.set( - LuaKey::Str("Pos".to_owned()), - vec2_lua(pos[0] as f64, pos[1] as f64), - ); - match kind { - "Underlay" => { - vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(172.0, 166.364)); - } - "Note" | "StickyNote" => { - let mut flags = LuaTable::default(); - flags.set(LuaKey::Str("Expanded".to_owned()), LuaValue::Bool(true)); - vi.set(LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags)); - vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(196.0, 179.364)); - } - _ => {} - } - vi -} - -/// Returns sensible Fusion 21.1 default inputs for common tool classes so Fusion Studio opens -/// newly created nodes cleanly without errors. -fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Vec<(String, ParamValue)> { - let w = width as f64; - let h = height as f64; - let num = |k: &str, v: f64| (k.to_owned(), ParamValue::Number(v)); - let pt = |k: &str, x: f64, y: f64| (k.to_owned(), ParamValue::Point([x, y])); - let txt = |k: &str, s: &str| (k.to_owned(), ParamValue::Text(s.to_owned())); - let fuid = |k: &str, s: &str| (k.to_owned(), ParamValue::FuId(s.to_owned())); - - match kind { - "Background" => vec![ - num("Width", w), - num("Height", h), - num("UseFrameFormatSettings", 1.0), - num("TopLeftRed", 0.0), - num("TopLeftGreen", 0.0), - num("TopLeftBlue", 0.0), - num("TopLeftAlpha", 1.0), - ], - "Merge" => vec![ - num("PerformDepthMerge", 0.0), - pt("Center", 0.5, 0.5), - num("Size", 1.0), - num("Angle", 0.0), - num("Blend", 1.0), - ], - "Transform" => vec![ - pt("Center", 0.5, 0.5), - pt("Pivot", 0.5, 0.5), - num("Size", 1.0), - num("Angle", 0.0), - ], - "Blur" => vec![fuid("Filter", "Fast Gaussian"), num("XBlurSize", 1.0)], - "Glow" => vec![num("XGlowSize", 10.0), num("Glow", 0.8)], - "SoftGlow" => vec![ - fuid("Filter", "Fast Gaussian"), - num("Gain", 2.0), - num("XGlowSize", 10.0), - ], - "BrightnessContrast" => vec![ - num("Gain", 1.0), - num("Lift", 0.0), - num("Gamma", 1.0), - num("Contrast", 0.0), - num("Brightness", 0.0), - num("Saturation", 1.0), - ], - "ColorCorrector" => vec![ - num("WheelSaturation1", 1.0), - num("MasterRGBGain", 1.0), - num("MasterRGBGamma", 1.0), - ], - "ColorGain" => vec![ - num("GainRed", 1.0), - num("GainGreen", 1.0), - num("GainBlue", 1.0), - num("GainAlpha", 1.0), - num("GammaRed", 1.0), - num("GammaGreen", 1.0), - num("GammaBlue", 1.0), - ], - "RectangleMask" => vec![ - num("MaskWidth", w), - num("MaskHeight", h), - pt("PixelAspect", 1.0, 1.0), - pt("Center", 0.5, 0.5), - num("Width", 0.5), - num("Height", 0.5), - num("CornerRadius", 0.0), - num("SoftEdge", 0.0), - ], - "EllipseMask" => vec![ - num("MaskWidth", w), - num("MaskHeight", h), - pt("PixelAspect", 1.0, 1.0), - pt("Center", 0.5, 0.5), - num("Width", 0.5), - num("Height", 0.5), - num("SoftEdge", 0.0), - ], - "PolylineMask" => vec![ - num("MaskWidth", w), - num("MaskHeight", h), - pt("PixelAspect", 1.0, 1.0), - num("SoftEdge", 0.0), - ], - "BitmapMask" => vec![ - num("MaskWidth", w), - num("MaskHeight", h), - pt("PixelAspect", 1.0, 1.0), - fuid("Channel", "Alpha"), - ], - "TextPlus" => vec![ - num("Width", w), - num("Height", h), - num("UseFrameFormatSettings", 1.0), - txt("StyledText", ""), - txt("Font", "Open Sans"), - txt("Style", "Bold"), - num("Size", 0.08), - pt("Center", 0.5, 0.5), - ], - "Loader" => vec![], - "Saver" => vec![num("ProcessWhenBlendIs00", 0.0), num("CreateDir", 1.0)], - "Displace" => vec![ - num("Type", 0.0), - num("XRefraction", 0.0), - num("YRefraction", 0.0), - num("RefractionStrength", 0.0), - ], - "FastNoise" => vec![ - num("Width", w), - num("Height", h), - num("UseFrameFormatSettings", 1.0), - num("Detail", 2.0), - num("Contrast", 1.0), - num("XScale", 2.0), - num("Seethe", 0.0), - ], - "PipeRouter" | "Underlay" => vec![], - "Switch" | "Fuse.Switch" => vec![num("Source", 0.0)], - "TimeStretcher" => vec![num("SourceTime", 0.0), num("InterpolateBetweenFrames", 0.0)], - "TimeSpeed" => vec![num("Speed", 1.0), num("Delay", 0.0)], - "Renderer3D" => vec![ - num("Width", w), - num("Height", h), - num("UseFrameFormatSettings", 1.0), - fuid("RendererType", "RendererOpenGL"), - ], - "Camera3D" => vec![num("FLength", 24.0), num("PlaneOfFocus", 5.0)], - "Merge3D" => vec![num("PassThroughLights", 1.0)], - "Transform3D" => vec![num("Transform3DOp.Scale.X", 1.0)], - "ImagePlane3D" => vec![ - num("SurfacePlaneInputs.Width", 1.0), - num("SurfacePlaneInputs.Height", 1.0), - ], - "Shape3D" => vec![fuid("Shape", "SurfacePlaneInputs")], - "Note" | "StickyNote" => vec![txt("Comments", "")], - _ => vec![], - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::expr::ExprEngine; - use std::path::Path; - - fn sample_comp() -> Comp { - let src = r#"Composition { - CurrentTime = 10, - RenderRange = { 0, 100 }, - GlobalRange = { 0, 100 }, - Prefs = { - Comp = { - FrameFormat = { - Width = 1920, - Height = 1080, - Rate = 24, - DepthFull = 3, - }, - }, - }, - Tools = ordered() { - BG1 = Background { - Inputs = { - Width = Input { Value = 1920, }, - Height = Input { Value = 1080, }, - TopLeftRed = Input { Value = 0.25, }, - }, - ViewInfo = OperatorInfo { Pos = { 100, 50 } }, - }, - BC1 = BrightnessContrast { - Inputs = { - Input = Input { - SourceOp = "BG1", - Source = "Output", - }, - Gain = Input { - SourceOp = "BC1Gain", - Source = "Value", - }, - }, - ViewInfo = OperatorInfo { Pos = { 300, 50 } }, - }, - BC1Gain = BezierSpline { - SplineColor = { Red = 255, Green = 128, Blue = 0 }, - KeyFrames = { - [0] = { 1, Flags = { Linear = true } }, - [30] = { 2, Flags = { Linear = true } }, - }, - }, - SurfaceTracker1 = SurfaceTracker { - Inputs = { - Source = Input { - SourceOp = "BC1", - Source = "Output", - }, - MeshBlob = Input { - Value = TrackingMesh { - Vertices = { 1, 2, 3 }, - }, - }, - }, - ViewInfo = OperatorInfo { Pos = { 500, 50 } }, - }, - }, -}"#; - Comp::from_fusion_str(src).expect("parse sample comp") - } - - #[test] - fn add_node_naming_and_tool_defaults() { - let mut comp = sample_comp(); - let rev0 = comp.revision; - - let t1 = comp.add_node("Transform", None, [120.0, 200.0]); - let t2 = comp.add_node("Transform", None, [240.0, 200.0]); - assert_eq!(comp.node(t1).name, "Transform1"); - assert_eq!(comp.node(t2).name, "Transform2"); - assert_eq!(comp.node(t1).pos, [120.0, 200.0]); - assert!(comp.revision >= rev0 + 2); - - let h0 = comp.add_node("Background", Some("HeroBG"), [0.0, 0.0]); - let h1 = comp.add_node("Background", Some("HeroBG"), [50.0, 0.0]); - let h2 = comp.add_node("Background", Some("HeroBG"), [100.0, 0.0]); - assert_eq!(comp.node(h0).name, "HeroBG"); - assert_eq!(comp.node(h1).name, "HeroBG_1"); - assert_eq!(comp.node(h2).name, "HeroBG_2"); - - // Cover all common Fusion 21.1 tool categories + generic fallback - let kinds = [ - "Background", - "Merge", - "Transform", - "Blur", - "Glow", - "SoftGlow", - "BrightnessContrast", - "ColorCorrector", - "ColorGain", - "RectangleMask", - "EllipseMask", - "PolylineMask", - "BitmapMask", - "TextPlus", - "Loader", - "Saver", - "Displace", - "FastNoise", - "PipeRouter", - "Switch", - "TimeStretcher", - "TimeSpeed", - "Renderer3D", - "Camera3D", - "Merge3D", - "Transform3D", - "ImagePlane3D", - "Shape3D", - "Note", - "Underlay", - "MyCustomThirdPartyTool", - ]; - for (i, kind) in kinds.iter().enumerate() { - let id = comp.add_node(kind, None, [i as f32 * 50.0, 400.0]); - assert_eq!(comp.node(id).kind, *kind); - assert!(comp.node(id).raw.get_table("ViewInfo").is_some()); - } - - // Roundtrip all newly created nodes cleanly - let s = comp.to_fusion_string(); - let reloaded = Comp::from_fusion_str(&s).expect("roundtrip added nodes"); - assert_eq!(reloaded.nodes.len(), comp.nodes.len()); - assert_eq!( - reloaded.node(reloaded.find_node("HeroBG").unwrap()).static_number("Width"), - Some(1920.0) - ); - } - - #[test] - fn connect_cycle_detection_disconnect_and_splice() { - let mut comp = sample_comp(); - let bg = comp.find_node("BG1").unwrap(); - let bc = comp.find_node("BC1").unwrap(); - let st = comp.find_node("SurfaceTracker1").unwrap(); - - // Self-loop rejected - assert!(comp.connect_output(bg, "Output", bg, "EffectMask").is_err()); - // Direct cycle BG1 -> BC1 -> BG1 rejected - assert!(comp.connect_output(bc, "Output", bg, "EffectMask").is_err()); - // Transitive cycle BG1 -> BC1 -> SurfaceTracker1 -> BG1 rejected - assert!(comp.connect_output(st, "Output", bg, "EffectMask").is_err()); - - // Splice a Blur into BG1 -> BC1.Input - let blur = comp.add_node("Blur", None, [200.0, 50.0]); - comp.splice_node_into_pipe(blur, bg, bc, "Input") - .expect("splice blur"); - assert_eq!(comp.node(blur).connected_node("Input"), Some("BG1")); - assert_eq!(comp.node(bc).connected_node("Input"), Some("Blur1")); - - // Disconnect returns true once, then false - assert!(comp.disconnect(bc, "Input")); - assert!(!comp.disconnect(bc, "Input")); - assert_eq!(comp.node(bc).connected_node("Input"), None); - - // Reconnect and verify roundtrip - comp.connect_output(blur, "Output", bc, "Input") - .expect("reconnect"); - let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip"); - assert_eq!( - reloaded.node(reloaded.find_node("BC1").unwrap()).connected_node("Input"), - Some("Blur1") - ); - } - - #[test] - fn params_expressions_passthrough_pos_and_keyframes() { - let mut comp = sample_comp(); - let bc = comp.find_node("BC1").unwrap(); - - assert!(comp.set_input_value(bc, "Gamma", ParamValue::Number(1.45))); - assert!(comp.set_input_expression(bc, "Brightness", Some("time * 0.01".to_owned()))); - assert!(comp.toggle_passthrough(bc)); - comp.set_node_pos(bc, [333.0, 77.0]); - - // Set keyframe on static input -> creates new BezierSpline and wires it - let sp_name = comp.set_keyframe(bc, "Contrast", 0.0, 0.2).expect("kf 0"); - assert_eq!(sp_name, "BC1Contrast"); - let sp_name2 = comp.set_keyframe(bc, "Contrast", 20.0, 0.8).expect("kf 20"); - assert_eq!(sp_name2, sp_name); - // Update existing keyframe at frame 20 - comp.set_keyframe(bc, "Contrast", 20.0, 0.9).expect("update kf 20"); - assert_eq!(comp.splines[&sp_name].keyframes.len(), 2); - - // Evaluate via Comp::eval_number - let expr = ExprEngine::new(); - let val_mid = comp.eval_number(comp.node(bc), "Contrast", 10.0, 0.0, &expr); - assert!((val_mid - 0.55).abs() < 1e-5, "got {val_mid}"); - - // Delete keyframe - assert!(comp.delete_keyframe(&sp_name, 20.0)); - assert!(!comp.delete_keyframe(&sp_name, 20.0)); - assert_eq!(comp.splines[&sp_name].keyframes.len(), 1); - - // Roundtrip - let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip"); - let r_bc = reloaded.node(reloaded.find_node("BC1").unwrap()); - assert!(r_bc.bypassed); - assert_eq!(r_bc.pos, [333.0, 77.0]); - assert_eq!(r_bc.static_number("Gamma"), Some(1.45)); - assert_eq!( - r_bc.inputs.get("Brightness").and_then(|b| b.expression.as_deref()), - Some("time * 0.01") - ); - assert_eq!(r_bc.connected_node("Contrast"), Some("BC1Contrast")); - assert_eq!(reloaded.splines["BC1Contrast"].keyframes.len(), 1); - - // Clear expression and un-bypass - assert!(comp.set_input_expression(bc, "Brightness", None)); - assert!(!comp.toggle_passthrough(bc)); - let reloaded2 = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip 2"); - let r_bc2 = reloaded2.node(reloaded2.find_node("BC1").unwrap()); - assert!(!r_bc2.bypassed); - assert_eq!( - r_bc2.inputs.get("Brightness").and_then(|b| b.expression.as_deref()), - None - ); - } - - #[test] - fn rename_duplicate_and_delete_nodes_roundtrip() { - let mut comp = sample_comp(); - let bg = comp.find_node("BG1").unwrap(); - let bc = comp.find_node("BC1").unwrap(); - - // Rename validation - assert!(comp.rename_node(bg, "").is_err()); - assert!(comp.rename_node(bg, "123Bad").is_err()); - assert!(comp.rename_node(bg, "function").is_err()); - assert!(comp.rename_node(bg, "BC1").is_err()); - - // Rename BG1 -> PlateBG and verify BC1.Input SourceOp is rewritten - let new_name = comp.rename_node(bg, "PlateBG").expect("rename BG1"); - assert_eq!(new_name, "PlateBG"); - assert!(comp.find_node("BG1").is_none()); - assert_eq!(comp.find_node("PlateBG"), Some(bg)); - assert_eq!(comp.node(bc).connected_node("Input"), Some("PlateBG")); - - // Duplicate [PlateBG, BC1] together -> internal wire preserved, BC1Gain spline cloned - let dups = comp.duplicate_nodes(&[bg, bc], [0.0, 150.0]); - assert_eq!(dups.len(), 2); - let dup_bg = dups[0]; - let dup_bc = dups[1]; - assert_eq!(comp.node(dup_bg).name, "PlateBG_1"); - assert_eq!(comp.node(dup_bc).name, "BC1_1"); - assert_eq!(comp.node(dup_bg).pos, [100.0, 200.0]); - assert_eq!(comp.node(dup_bc).connected_node("Input"), Some("PlateBG_1")); - let dup_gain_spline = comp.node(dup_bc).connected_node("Gain").unwrap().to_owned(); - assert_ne!(dup_gain_spline, "BC1Gain"); - assert!(comp.splines.contains_key(&dup_gain_spline)); - - // Share BC1Gain with dup_bg (artificial) vs exclusive spline on dup_bc: - // Deleting dup_bc should prune `dup_gain_spline` while leaving `BC1Gain` intact. - let deleted = comp.delete_nodes(&[dup_bc]); - assert_eq!(deleted, vec!["BC1_1".to_owned()]); - assert!(!comp.splines.contains_key(&dup_gain_spline)); - assert!(comp.splines.contains_key("BC1Gain")); - - // Delete BC1 -> SurfaceTracker1.Source unwired, BC1Gain pruned, NodeId indices compact - let bc_now = comp.find_node("BC1").unwrap(); - let del2 = comp.delete_nodes(&[bc_now]); - assert_eq!(del2, vec!["BC1".to_owned()]); - assert!(!comp.splines.contains_key("BC1Gain")); - for (idx, n) in comp.nodes.iter().enumerate() { - assert_eq!(n.id, NodeId(idx)); - assert_eq!(comp.find_node(&n.name), Some(NodeId(idx))); - } - let st_now = comp.find_node("SurfaceTracker1").unwrap(); - assert_eq!(comp.node(st_now).connected_node("Source"), None); - - // Full roundtrip preserves unknown SurfaceTracker1 verbatim + all structural mutations - let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip"); - assert!(reloaded.find_node("PlateBG").is_some()); - assert!(reloaded.find_node("PlateBG_1").is_some()); - assert!(reloaded.find_node("BC1").is_none()); - assert!(reloaded.find_node("SurfaceTracker1").is_some()); - assert!(!reloaded.splines.contains_key("BC1Gain")); - let r_st = reloaded.node(reloaded.find_node("SurfaceTracker1").unwrap()); - assert_eq!(r_st.connected_node("Source"), None); - assert!( - r_st.raw - .get_table("Inputs") - .and_then(|i| i.get_table("MeshBlob")) - .is_some() - ); - } - - #[test] - fn roundtrip_mutations_on_real_20_falling_comp() { - let path = Path::new("/Volumes/Project/trees/fusion/20_falling.comp"); - if !path.exists() { - return; - } - let mut comp = Comp::from_fusion_file(path).expect("load 20_falling.comp"); - let orig_count = comp.nodes.len(); - - let blur = comp.add_node("Blur", Some("TestGlowBlur"), [1000.0, -500.0]); - let merge19 = comp.find_node("Merge19").expect("Merge19"); - comp.set_input_value(blur, "XBlurSize", ParamValue::Number(4.5)); - comp.set_input_expression(blur, "YBlurSize", Some("XBlurSize * 2".to_owned())); - comp.toggle_passthrough(blur); - let sp = comp - .set_keyframe(blur, "Blend", 2200.0, 0.5) - .expect("keyframe blend"); - comp.set_keyframe(blur, "Blend", 2250.0, 1.0) - .expect("keyframe blend 2"); - comp.connect_output(merge19, "Output", blur, "Input") - .expect("connect Merge19 -> blur"); - comp.rename_node(blur, "TestGlowBlurRenamed") - .expect("rename blur"); - - let serialized = comp.to_fusion_string(); - let reloaded = Comp::from_fusion_str(&serialized).expect("re-parse mutated 20_falling"); - assert_eq!(reloaded.nodes.len(), orig_count + 1); - let r_blur_id = reloaded - .find_node("TestGlowBlurRenamed") - .expect("TestGlowBlurRenamed"); - let r_blur = reloaded.node(r_blur_id); - assert!(r_blur.bypassed); - assert_eq!(r_blur.connected_node("Input"), Some("Merge19")); - assert_eq!(r_blur.static_number("XBlurSize"), Some(4.5)); - assert_eq!( - r_blur.inputs.get("YBlurSize").and_then(|b| b.expression.as_deref()), - Some("XBlurSize * 2") - ); - assert_eq!(reloaded.splines[&sp].keyframes.len(), 2); - } - - #[test] - fn comp_history_undo_redo_coalescing_groups_and_bounds() { - let mut comp = sample_comp(); - let mut history = CompHistory::with_max_depth(3); - history.mark_saved(&comp); - assert!(!history.is_dirty(&comp)); - assert!(!history.can_undo()); - assert!(!history.can_redo()); - - let bg = comp.find_node("BG1").unwrap(); - - // 1. Coalesced drag: 120 frames produce ONE undo step - for i in 1..=120 { - history.push_coalesced(&comp, "Move BG1", format!("drag_node:{}", bg.0)); - comp.set_node_pos(bg, [100.0 + i as f32, 50.0 + i as f32 * 0.5]); - } - history.break_coalescing(); - assert_eq!(history.undo_len(), 1); - assert_eq!(history.undo_label(), Some("Move BG1")); - assert!(history.is_dirty(&comp)); - assert_eq!(comp.node(bg).pos, [220.0, 110.0]); - - // Undo restores original pre-drag position and clears dirty flag - assert!(history.undo(&mut comp)); - assert_eq!(comp.node(bg).pos, [100.0, 50.0]); - assert!(!history.is_dirty(&comp)); - assert!(history.can_redo()); - assert_eq!(history.redo_label(), Some("Move BG1")); - - // Redo restores final dragged position - assert!(history.redo(&mut comp)); - assert_eq!(comp.node(bg).pos, [220.0, 110.0]); - assert!(history.is_dirty(&comp)); - - // 2. Redo invalidation on new edit after undo - assert!(history.undo(&mut comp)); - assert!(history.can_redo()); - history.push_snapshot(&comp, "Add Blur"); - let blur = comp.add_node("Blur", None, [200.0, 100.0]); - assert!(!history.can_redo()); - assert_eq!(history.undo_len(), 1); - - // 3. Transaction group collapses multiple mutations into one undo step - history.begin_group(&comp, "Style Blur"); - comp.set_input_value(blur, "XBlurSize", ParamValue::Number(5.0)); - history.push_snapshot(&comp, "Ignored inside group"); - comp.toggle_passthrough(blur); - assert!(history.commit_group(&comp)); - assert_eq!(history.undo_len(), 2); - assert_eq!(history.undo_label(), Some("Style Blur")); - - // No-op group doesn't push - history.begin_group(&comp, "No-op"); - assert!(!history.commit_group(&comp)); - assert_eq!(history.undo_len(), 2); - - // Cancel group restores pre-group state - history.begin_group(&comp, "Canceled"); - comp.set_node_pos(blur, [999.0, 999.0]); - assert!(history.cancel_group(&mut comp)); - assert_eq!(comp.node(blur).pos, [200.0, 100.0]); - - // 4. Bounded history depth (max_depth = 3) - history.push_snapshot(&comp, "Edit 3"); - comp.set_node_pos(blur, [210.0, 100.0]); - history.push_snapshot(&comp, "Edit 4"); - comp.set_node_pos(blur, [220.0, 100.0]); - assert_eq!(history.undo_len(), 3); - - history.clear(); - assert!(!history.can_undo()); - assert!(!history.can_redo()); - } - - const GROUP_SNIPPET: &str = r#"{ - Tools = ordered() { - Group1 = GroupOperator { - Inputs = { - Input1 = InstanceInput { SourceOp = "Inner1", Source = "Input", }, - }, - Outputs = { - Output1 = InstanceOutput { SourceOp = "Inner1", Source = "Output", }, - }, - ViewInfo = GroupInfo { Pos = { 10, 20 } }, - Tools = ordered() { - Inner1 = Blur { - Inputs = { - XBlurSize = Input { SourceOp = "Inner1Size", Source = "Value", }, - }, - ViewInfo = OperatorInfo { Pos = { 0, 0 } }, - }, - Inner1Size = BezierSpline { - KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, - }, - }, - }, - }, -}"#; - - #[test] - fn export_fusion_clipboard_includes_owned_modifiers_and_internal_wires() { - let comp = sample_comp(); - let bg = comp.find_node("BG1").unwrap(); - let bc = comp.find_node("BC1").unwrap(); - - let both = comp.export_fusion_clipboard(&[bg, bc]); - assert!(both.contains("Tools = ordered()"), "{both}"); - assert!(both.contains("ActiveTool = \"BG1\""), "{both}"); - let parsed = parse_lua(&both).expect("clipboard parses as Lua"); - let tools = parsed.as_table().unwrap().get_table("Tools").unwrap(); - let names: Vec<_> = tools - .entries - .iter() - .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None }) - .collect(); - assert_eq!(names, ["BG1", "BC1", "BC1Gain"]); - assert_eq!( - tools - .get_table("BC1") - .and_then(|t| t.get_table("Inputs")) - .and_then(|i| i.get_table("Input")) - .and_then(|i| i.get_str("SourceOp")), - Some("BG1") - ); - - // Selecting only BC1 keeps its owned spline and leaves the external BG1 reference. - let only_bc = comp.export_fusion_clipboard(&[bc, bc]); - assert!(only_bc.contains("BC1Gain = BezierSpline")); - assert!(!only_bc.contains("BG1 = Background")); - assert!(only_bc.contains("SourceOp = \"BG1\"")); - - // Splines created after load (not yet in `raw_root`) are exported too. - let mut comp = comp; - let sp = comp.set_keyframe(bg, "Width", 0.0, 1.0).unwrap(); - assert!(comp.export_fusion_clipboard(&[bg]).contains(&format!("{sp} = BezierSpline"))); - } - - #[test] - fn paste_dedups_names_and_remaps_internal_wires_and_splines() { - let mut comp = sample_comp(); - let bg = comp.find_node("BG1").unwrap(); - let bc = comp.find_node("BC1").unwrap(); - let snippet = comp.export_fusion_clipboard(&[bg, bc]); - let nodes_before = comp.nodes.len(); - - let ids = comp.paste_fusion_clipboard(&snippet, (60.0, 40.0)).expect("paste"); - assert_eq!(ids.len(), 2); - assert_eq!(comp.nodes.len(), nodes_before + 2); - let (pbg, pbc) = (comp.node(ids[0]), comp.node(ids[1])); - assert_eq!((pbg.name.as_str(), pbc.name.as_str()), ("BG1_1", "BC1_1")); - assert_eq!(pbg.pos, [160.0, 90.0]); - assert_eq!(pbc.pos, [360.0, 90.0]); - assert_eq!(pbc.connected_node("Input"), Some("BG1_1")); - assert_eq!(pbc.connected_node("Gain"), Some("BC1Gain_1")); - assert_eq!(comp.splines["BC1Gain_1"].keyframes.len(), 2); - assert_eq!(comp.splines["BC1Gain"].keyframes.len(), 2); - assert_eq!(comp.find_node("BC1_1"), Some(ids[1])); - assert_eq!(comp.node(bc).connected_node("Input"), Some("BG1")); - - // Pasting again keeps advancing the suffix instead of clobbering earlier pastes. - let again = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap(); - assert_eq!(comp.node(again[0]).name, "BG1_2"); - assert_eq!(comp.node(again[1]).connected_node("Input"), Some("BG1_2")); - - // Everything survives a save/load roundtrip, including the cloned spline and offset. - let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("reload"); - let r_bc = reloaded.node(reloaded.find_node("BC1_1").unwrap()); - assert_eq!(r_bc.pos, [360.0, 90.0]); - assert_eq!(r_bc.connected_node("Input"), Some("BG1_1")); - assert!(reloaded.splines.contains_key("BC1Gain_1")); - } - - #[test] - fn paste_external_references_are_kept_when_present_and_dropped_when_missing() { - let mut comp = sample_comp(); - let bc = comp.find_node("BC1").unwrap(); - let snippet = comp.export_fusion_clipboard(&[bc]); - - let ids = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap(); - assert_eq!(comp.node(ids[0]).connected_node("Input"), Some("BG1")); - - let mut empty = Comp::from_fusion_str("Composition { Tools = ordered() { } }").unwrap(); - let ids = empty.paste_fusion_clipboard(&snippet, (5.0, 5.0)).unwrap(); - let pasted = empty.node(ids[0]); - assert_eq!(pasted.name, "BC1"); - assert_eq!(pasted.connected_node("Input"), None); - assert_eq!(pasted.connected_node("Gain"), Some("BC1Gain")); - assert!(!empty.to_fusion_string().contains("BG1")); - } - - #[test] - fn paste_accepts_full_composition_and_rewrites_expressions() { - let mut comp = sample_comp(); - let snippet = r#"Composition { - Tools = ordered() { - BG1 = Background { Inputs = { Width = Input { Value = 64, } }, }, - T1 = Transform { - Inputs = { - Size = Input { Expression = "BG1.Width / 2 + BG10.Width", }, - Input = Input { SourceOp = "BG1", Source = "Output", }, - }, - }, - }, -}"#; - let ids = comp.paste_fusion_clipboard(snippet, (1.0, 2.0)).unwrap(); - let t1 = comp.node(ids[1]); - assert_eq!(comp.node(ids[0]).name, "BG1_1"); - assert_eq!(comp.node(ids[0]).pos, [1.0, 2.0]); - assert_eq!(t1.connected_node("Input"), Some("BG1_1")); - assert_eq!( - t1.inputs["Size"].expression.as_deref(), - Some("BG1_1.Width / 2 + BG10.Width") - ); - } - - #[test] - fn paste_group_renames_nested_tools_and_remaps_macro_output() { - let mut comp = sample_comp(); - let first = comp.paste_fusion_clipboard(GROUP_SNIPPET, (0.0, 0.0)).unwrap(); - let second = comp.paste_fusion_clipboard(GROUP_SNIPPET, (50.0, 0.0)).unwrap(); - let (g1, g2) = (comp.node(first[0]), comp.node(second[0])); - assert_eq!((g1.name.as_str(), g2.name.as_str()), ("Group1", "Group1_1")); - assert_eq!(g2.pos, [60.0, 20.0]); - - let inner = comp.node(g2.macro_output.expect("macro output")); - assert_eq!(inner.name, "Inner1_1"); - assert!(inner.internal); - assert_eq!(inner.connected_node("XBlurSize"), Some("Inner1Size_1")); - assert!(comp.splines.contains_key("Inner1Size_1")); - assert_eq!(comp.node(g1.macro_output.unwrap()).name, "Inner1"); - assert_eq!(comp.find_node("Group1_1"), Some(second[0])); - assert_eq!(comp.find_node("Inner1_1"), g2.macro_output); - } - - #[test] - fn paste_is_one_undo_step_and_redoable() { - let mut comp = sample_comp(); - let mut history = CompHistory::new(); - let bg = comp.find_node("BG1").unwrap(); - let bc = comp.find_node("BC1").unwrap(); - let snippet = comp.export_fusion_clipboard(&[bg, bc]); - let (nodes, splines) = (comp.nodes.len(), comp.splines.len()); - history.mark_saved(&comp); - - let ids = history - .paste_fusion_clipboard(&mut comp, &snippet, (60.0, 40.0)) - .unwrap(); - assert_eq!(ids.len(), 2); - assert_eq!(history.undo_len(), 1); - assert_eq!(history.undo_label(), Some("Paste")); - assert!(history.is_dirty(&comp)); - - assert!(history.undo(&mut comp)); - assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes, splines)); - assert!(comp.find_node("BG1_1").is_none()); - assert!(!comp.to_fusion_string().contains("BG1_1")); - assert!(!history.can_undo()); - assert!(!history.is_dirty(&comp)); - - assert!(history.redo(&mut comp)); - assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes + 2, splines + 1)); - let pasted = comp.find_node("BC1_1").unwrap(); - assert_eq!(comp.node(pasted).connected_node("Input"), Some("BG1_1")); - assert!(!history.can_redo()); - } - - #[test] - fn paste_rejects_garbage_without_touching_comp_or_history() { - let mut comp = sample_comp(); - let mut history = CompHistory::new(); - let (rev, nodes) = (comp.revision, comp.nodes.len()); - for bad in ["", "hello world", "{ Foo = 1 }", "{ Tools = ordered() { } }", "{ Tools = "] { - assert!(history.paste_fusion_clipboard(&mut comp, bad, (0.0, 0.0)).is_err(), "{bad:?}"); - } - assert_eq!((comp.revision, comp.nodes.len()), (rev, nodes)); - assert!(!history.can_undo()); - assert!(!history.in_group()); - } - - const TWO_GROUPS: &str = r#"Composition { - Tools = ordered() { - BG = Background { }, - GA = GroupOperator { - Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, }, - Tools = ordered() { - Same = Blur { Inputs = { XBlurSize = Input { SourceOp = "SameSize", Source = "Value", }, }, }, - SameSize = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, }, - }, - }, - GB = GroupOperator { - Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, }, - Tools = ordered() { - Same = Blur { }, - }, - }, - }, -}"#; - - fn tool_names(tools: &LuaTable) -> Vec<&str> { - tools - .entries - .iter() - .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None }) - .collect() - } - - #[test] - fn mark_saved_stops_later_edits_coalescing_into_the_saved_step() { - let mut comp = sample_comp(); - let mut history = CompHistory::new(); - let bg = comp.find_node("BG1").unwrap(); - - history.push_coalesced(&comp, "Drag", "drag"); - comp.set_node_pos(bg, [1.0, 1.0]); - history.mark_saved(&comp); - assert!(!history.is_dirty(&comp)); - - history.push_coalesced(&comp, "Drag", "drag"); - comp.set_node_pos(bg, [2.0, 2.0]); - assert_eq!(history.undo_len(), 2); - assert!(history.is_dirty(&comp)); - } - - #[test] - fn undo_and_redo_keep_the_live_file_identity() { - let mut comp = sample_comp(); - comp.path = Some("/tmp/original.comp".into()); - comp.name = "original".to_owned(); - let mut history = CompHistory::new(); - let bg = comp.find_node("BG1").unwrap(); - - history.push_snapshot(&comp, "Move"); - comp.set_node_pos(bg, [9.0, 9.0]); - comp.path = Some("/tmp/save_as.comp".into()); - comp.name = "save_as".to_owned(); - - assert!(history.undo(&mut comp)); - assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as")); - assert!(history.redo(&mut comp)); - assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as")); - } - - #[test] - fn deleting_a_group_removes_its_private_tools_and_modifiers() { - let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); - let g = comp.find_node("Group1").unwrap(); - let deleted = comp.delete_nodes(&[g]); - assert_eq!(deleted, ["Group1", "Inner1"]); - assert!(comp.nodes.is_empty()); - assert!(comp.splines.is_empty()); - assert!(tool_names(comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap()).is_empty()); - } - - #[test] - fn deleting_a_node_keeps_splines_still_used_by_expression_modifiers() { - let src = r#"Composition { - Tools = ordered() { - N = Transform { Inputs = { Angle = Input { SourceOp = "Shared", Source = "Value", }, Size = Input { SourceOp = "E", Source = "NumberResult", }, }, }, - M = Transform { Inputs = { Angle = Input { SourceOp = "Own", Source = "Value", }, Size = Input { SourceOp = "E2", Source = "NumberResult", }, }, }, - E = Expression { Inputs = { n1 = Input { SourceOp = "Shared", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, }, - E2 = Expression { Inputs = { n1 = Input { SourceOp = "Own", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, }, - Shared = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, }, - Own = BezierSpline { KeyFrames = { [0] = { 2, Flags = { Linear = true } } }, }, - }, -}"#; - let mut comp = Comp::from_fusion_str(src).unwrap(); - comp.delete_nodes(&[comp.find_node("M").unwrap()]); - assert!(!comp.expression_modifiers.contains_key("E2")); - assert!(!comp.splines.contains_key("Own")); - assert!(comp.expression_modifiers.contains_key("E")); - assert!(comp.splines.contains_key("Shared")); - - // Deleting the other owner prunes the expression modifier and its spline. - let mut comp = Comp::from_fusion_str(src).unwrap(); - comp.delete_nodes(&[comp.find_node("N").unwrap()]); - assert!(!comp.expression_modifiers.contains_key("E")); - assert!(!comp.splines.contains_key("Shared")); - - // A spline referenced by a surviving (unpruned) expression modifier outlives its owner. - let with_orphan = src.replace("\t},\n}", "\t\tEO = Expression { Inputs = { n1 = Input { SourceOp = \"Shared\", Source = \"Value\", }, }, },\n\t},\n}"); - let mut comp = Comp::from_fusion_str(&with_orphan).unwrap(); - comp.delete_nodes(&[comp.find_node("N").unwrap()]); - assert!(comp.expression_modifiers.contains_key("EO")); - assert!(comp.splines.contains_key("Shared")); - } - - #[test] - fn export_includes_modifiers_nested_in_a_copied_internal_node_once() { - let comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); - let inner = comp.find_node("Inner1").unwrap(); - let clip = comp.export_fusion_clipboard(&[inner]); - let parsed = parse_lua(&clip).unwrap(); - let tools = parsed.as_table().unwrap().get_table("Tools").unwrap(); - assert_eq!(tool_names(tools), ["Inner1", "Inner1Size"]); - - let whole = comp.export_fusion_clipboard(&[comp.find_node("Group1").unwrap()]); - assert_eq!(whole.matches("Inner1Size = BezierSpline").count(), 1, "{whole}"); - } - - #[test] - fn paste_never_links_to_group_private_tools() { - let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); - let snippet = r#"{ Tools = ordered() { T = Transform { Inputs = { - Input = Input { SourceOp = "Inner1", Source = "Output", }, - Mask = Input { SourceOp = "Group1", Source = "Output", }, - Angle = Input { SourceOp = "Inner1Size", Source = "Value", }, - }, }, }, }"#; - let ids = comp.paste_fusion_clipboard(snippet, (0.0, 0.0)).unwrap(); - let t = comp.node(ids[0]); - assert_eq!(t.connected_node("Input"), None); - assert_eq!(t.connected_node("Angle"), None); - assert_eq!(t.connected_node("Mask"), Some("Group1")); - } - - #[test] - fn expression_renames_skip_property_names() { - let renames = HashMap::from([("Size".to_owned(), "Big".to_owned())]); - assert_eq!( - rename_expression_idents("Other.Size + Size.Width * Size", &renames), - "Other.Size + Big.Width * Big" - ); - } - - #[test] - fn rename_and_paste_rewrite_expression_modifier_formulas() { - let src = r#"Composition { - Tools = ordered() { - BG = Background { }, - E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width + Other.BG", }, }, }, - }, -}"#; - let mut comp = Comp::from_fusion_str(src).unwrap(); - let bg = comp.find_node("BG").unwrap(); - comp.rename_node(bg, "Plate").unwrap(); - let formula = |c: &Comp| c.expression_modifiers["E"].inputs["NumberExpression"].value.clone(); - assert_eq!(formula(&comp), Some(ParamValue::Text("Plate.Width + Other.BG".to_owned()))); - assert!(comp.to_fusion_string().contains("Plate.Width + Other.BG")); - - let paste = r#"{ Tools = ordered() { BG = Background { }, E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width", }, }, }, }, }"#; - comp.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap(); - assert_eq!( - comp.expression_modifiers["E_1"].inputs["NumberExpression"].value, - Some(ParamValue::Text("BG.Width".to_owned())) - ); - let mut again = Comp::from_fusion_str(paste).unwrap(); - again.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap(); - assert_eq!( - again.expression_modifiers["E_1"].inputs["NumberExpression"].value, - Some(ParamValue::Text("BG_1.Width".to_owned())) - ); - } - - #[test] - fn renaming_one_groups_private_tool_leaves_same_named_tools_elsewhere() { - let mut comp = Comp::from_fusion_str(TWO_GROUPS).unwrap(); - let (ga, gb) = (comp.find_node("GA").unwrap(), comp.find_node("GB").unwrap()); - let a_same = comp.nodes.iter().position(|n| n.name == "Same" && n.id.0 < ga.0).unwrap(); - assert_eq!(comp.rename_node(NodeId(a_same), "Renamed").unwrap(), "Renamed"); - - let text = comp.to_fusion_string(); - let saved = Comp::from_fusion_str(&text).unwrap(); - let group_tools = |name: &str| { - let g = saved.node(saved.find_node(name).unwrap()); - ( - g.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp").unwrap().to_owned(), - tool_names(find_raw_tool_in(&saved, name)).into_iter().map(str::to_owned).collect::>(), - ) - }; - assert_eq!(group_tools("GA"), ("Renamed".to_owned(), vec!["Renamed".to_owned(), "SameSize".to_owned()])); - assert_eq!(group_tools("GB"), ("Same".to_owned(), vec!["Same".to_owned()])); - assert_eq!(comp.node(gb).name, "GB"); - } - - fn find_raw_tool_in<'a>(comp: &'a Comp, group: &str) -> &'a LuaTable { - let tools = comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap(); - find_raw_tool(tools, group).unwrap().get_table("Tools").unwrap() - } - - #[test] - fn renaming_a_top_level_tool_ignores_groups_with_a_private_tool_of_that_name() { - let src = TWO_GROUPS.replace("BG = Background { },", "BG = Background { },\n\t\tSame = Blur { },"); - let mut comp = Comp::from_fusion_str(&src).unwrap(); - let top = comp.find_node("Same").unwrap(); - assert!(!comp.node(top).internal); - comp.rename_node(top, "Top").unwrap(); - let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); - let ga = saved.node(saved.find_node("GA").unwrap()); - assert_eq!( - ga.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp"), - Some("Same") - ); - assert!(saved.find_node("Top").is_some_and(|id| !saved.node(id).internal)); - } - - #[test] - fn duplicate_nodes_clones_groups_and_curve_modifiers() { - let src = r#"Composition { - Tools = ordered() { - BG = Background { }, - HC = HueCurves { - Inputs = { - Input = Input { SourceOp = "BG", Source = "Output", }, - RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", }, - }, - Tools = ordered() { - HC_RSup = LUTBezier { KeyColorSplines = { [0] = { [0] = { 0.5 }, [6] = { 0.5 } } }, }, - }, - }, - }, -}"#; - let mut comp = Comp::from_fusion_str(src).unwrap(); - let hc = comp.find_node("HC").unwrap(); - let dup = comp.duplicate_nodes(&[hc], [10.0, 0.0]); - assert_eq!(dup.len(), 1); - let d = comp.node(dup[0]); - assert_eq!(d.name, "HC_1"); - assert_eq!(d.connected_node("Input"), Some("BG")); - assert_eq!(d.connected_node("RedSuppress"), Some("HC_RSup_1")); - assert!(comp.splines.contains_key("HC_RSup_1") && comp.splines.contains_key("HC_RSup")); - let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); - assert!(saved.splines.contains_key("HC_RSup_1")); - - let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); - let g = comp.find_node("Group1").unwrap(); - let dup = comp.duplicate_nodes(&[g], [0.0, 80.0]); - let copy = comp.node(dup[0]); - assert_eq!(copy.name, "Group1_1"); - assert_eq!(comp.node(copy.macro_output.unwrap()).name, "Inner1_1"); - assert!(comp.splines.contains_key("Inner1Size_1")); - } - - #[test] - fn updating_a_keyframe_moves_its_handles_with_it() { - let mut comp = sample_comp(); - let bc = comp.find_node("BC1").unwrap(); - comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].lh = Some([20.0, 1.5]); - comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].rh = Some([40.0, 2.5]); - comp.set_keyframe(bc, "Gain", 30.0, 3.0).unwrap(); - let kf = &comp.splines["BC1Gain"].keyframes[1]; - assert_eq!((kf.value, kf.lh, kf.rh), (3.0, Some([20.0, 2.5]), Some([40.0, 3.5]))); - } - - #[test] - fn deleting_the_last_keyframe_keeps_its_value_as_a_static_input() { - let mut comp = sample_comp(); - let bc = comp.find_node("BC1").unwrap(); - // Within the shared 1e-4 tolerance. - assert!(comp.delete_keyframe("BC1Gain", 0.00005)); - assert!(comp.delete_keyframe("BC1Gain", 30.0)); - assert!(!comp.splines.contains_key("BC1Gain")); - assert_eq!(comp.node(bc).connected_node("Gain"), None); - assert_eq!(comp.node(bc).static_number("Gain"), Some(2.0)); - - let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); - let r = saved.node(saved.find_node("BC1").unwrap()); - assert_eq!(r.static_number("Gain"), Some(2.0)); - assert!(!saved.to_fusion_string().contains("BC1Gain")); - } -} diff --git a/crates/model/src/edit/clipboard.rs b/crates/model/src/edit/clipboard.rs new file mode 100644 index 0000000000000000000000000000000000000000..c598ba2efefc97f0bcb3340bb6e41486ba53fd00 --- /dev/null +++ b/crates/model/src/edit/clipboard.rs @@ -0,0 +1,696 @@ +use super::{ + EXPRESSION_FORMULA_INPUTS, collect_source_ops_in_table, sanitize_lua_ident, set_view_info_pos, +}; +use crate::comp::{Comp, Node, NodeId, ensure_table_mut, find_raw_tool}; +use crate::lua_value::{LuaKey, LuaTable, LuaValue, parse_lua}; +use std::collections::{HashMap, HashSet, VecDeque}; + +impl Comp { + pub fn export_fusion_clipboard(&self, ids: &[NodeId]) -> String { + let synced = self.sync_to_raw_ast(); + let root_tools = synced.get_table("Tools"); + let node_names: HashSet<&str> = self.nodes.iter().map(|n| n.name.as_str()).collect(); + + let mut picked: Vec<&Node> = Vec::new(); + for &id in ids { + if let Some(n) = self.nodes.get(id.0) { + if !picked.iter().any(|p| p.id == n.id) { + picked.push(n); + } + } + } + let mut tools = LuaTable { + tag: Some("ordered".to_owned()), + entries: Vec::new(), + }; + let mut refs: VecDeque = VecDeque::new(); + for n in &picked { + let raw = root_tools.and_then(|t| find_raw_tool(t, &n.name)).unwrap_or(&n.raw); + let mut found = HashSet::new(); + collect_source_ops_in_table(raw, &mut found); + let mut found: Vec = found.into_iter().collect(); + found.sort(); + refs.extend(found); + tools.set(LuaKey::Str(n.name.clone()), LuaValue::Table(raw.clone())); + } + while let Some(name) = refs.pop_front() { + if tools.get(&name).is_some() || node_names.contains(name.as_str()) { + continue; + } + // Modifiers already nested inside a copied group travel with it. + let nested_in_copy = tools + .entries + .iter() + .filter_map(|(_, v)| v.as_table()?.get_table("Tools")) + .any(|inner| find_raw_tool(inner, &name).is_some()); + let Some(modifier) = root_tools.and_then(|t| find_raw_tool(t, &name)).filter(|_| !nested_in_copy) + else { + continue; + }; + let mut found = HashSet::new(); + collect_source_ops_in_table(modifier, &mut found); + let mut found: Vec = found.into_iter().collect(); + found.sort(); + refs.extend(found); + tools.set(LuaKey::Str(name), LuaValue::Table(modifier.clone())); + } + + let mut doc = LuaTable::default(); + doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools)); + if let Some(first) = picked.first() { + doc.set( + LuaKey::Str("ActiveTool".to_owned()), + LuaValue::String(first.name.clone()), + ); + } + doc.to_fusion_string() + } + + /// Pastes Fusion clipboard Lua (`{ Tools = ordered() { ... } }` or a full `Composition`), + /// renaming colliding tools/modifiers (`Blur1` -> `Blur1_1`), rewiring references among the + /// pasted tools, dropping references to tools that exist nowhere, and shifting each top-level + /// tool's `ViewInfo.Pos` by `offset`. Returns the new top-level flow nodes; on `Err` the comp + /// is untouched. Prefer [`CompHistory::paste_fusion_clipboard`] for an undoable paste. + pub fn paste_fusion_clipboard( + &mut self, + lua_snippet: &str, + offset: (f32, f32), + ) -> Result, String> { + let parsed = parse_lua(lua_snippet).map_err(|e| format!("clipboard is not Fusion Lua: {e}"))?; + let mut tools = parsed + .as_table() + .and_then(|t| t.get_table("Tools")) + .filter(|t| !t.entries.is_empty()) + .cloned() + .ok_or_else(|| "clipboard has no Fusion tools".to_owned())?; + + let mut pasted_names = Vec::new(); + collect_tool_names(&tools, &mut pasted_names); + let pasted_set: HashSet<&str> = pasted_names.iter().map(String::as_str).collect(); + + drop_unknown_source_ops(&mut tools, &mut |name| { + pasted_set.contains(name) || self.is_linkable_external(name) + }); + + let mut reserved: HashSet = self.nodes.iter().map(|n| n.name.clone()).collect(); + let mut renames: HashMap = HashMap::new(); + for name in &pasted_names { + if renames.contains_key(name) { + continue; + } + let fresh = self.generate_unique_name_excluding(name, &reserved); + reserved.insert(fresh.clone()); + renames.insert(name.clone(), fresh); + } + rename_tools(&mut tools, &renames); + + let mut doc = LuaTable { + tag: Some("Composition".to_owned()), + entries: Vec::new(), + }; + doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools)); + let staged = Comp::from_fusion_str(&doc.to_fusion_string()) + .map_err(|e| format!("clipboard tools failed to parse: {e}"))?; + let Some(staged_tools) = doc.get_table("Tools") else { + return Err("clipboard has no Fusion tools".to_owned()); + }; + + let base = self.nodes.len(); + let shift = |id: NodeId| NodeId(base + id.0); + let mut created = Vec::new(); + let mut top_level: HashMap = HashMap::new(); + for mut node in staged.nodes { + node.id = shift(node.id); + node.macro_output = node.macro_output.map(shift); + if !node.internal { + node.pos = [node.pos[0] + offset.0, node.pos[1] + offset.1]; + set_view_info_pos(&mut node.raw, node.pos); + top_level.insert(node.name.clone(), node.raw.clone()); + created.push(node.id); + } + self.nodes.push(node); + } + for (name, id) in staged.node_by_name { + self.node_by_name.entry(name).or_insert(shift(id)); + } + self.splines.extend(staged.splines); + self.poly_paths.extend(staged.poly_paths); + self.gradient_modifiers.extend(staged.gradient_modifiers); + self.text_modifiers.extend(staged.text_modifiers); + self.text_splines.extend(staged.text_splines); + self.polyline_splines.extend(staged.polyline_splines); + self.text_cls.extend(staged.text_cls); + self.shakes.extend(staged.shakes); + self.expression_modifiers.extend(staged.expression_modifiers); + + if let Some(root) = self.raw_root.as_mut() { + let dest = ensure_table_mut(root, "Tools", Some("ordered")); + for (key, value) in &staged_tools.entries { + let LuaKey::Str(name) = key else { continue }; + let table = top_level.remove(name).map_or_else(|| value.clone(), LuaValue::Table); + dest.set(key.clone(), table); + } + } + + self.revision += 1; + Ok(created) + } + + /// Duplicates the selected nodes at `pos + offset` with unique names, as a copy + paste: + /// wires between duplicated nodes are preserved, wires to other nodes stay intact, and owned + /// modifiers and group contents are cloned. Returns the new top-level nodes. + pub fn duplicate_nodes(&mut self, ids: &[NodeId], offset: [f32; 2]) -> Vec { + let snippet = self.export_fusion_clipboard(ids); + self.paste_fusion_clipboard(&snippet, (offset[0], offset[1])).unwrap_or_default() + } + + fn generate_unique_name_excluding(&self, hint: &str, reserved: &HashSet) -> String { + let base = sanitize_lua_ident(hint); + if !self.name_exists(&base) && !reserved.contains(&base) { + return base; + } + let mut idx = 1usize; + loop { + let candidate = format!("{base}_{idx}"); + if !self.name_exists(&candidate) && !reserved.contains(&candidate) { + return candidate; + } + idx += 1; + } + } +} + +pub(super) fn collect_tool_names(tools: &LuaTable, out: &mut Vec) { + for (key, value) in &tools.entries { + let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else { + continue; + }; + out.push(name.clone()); + if let Some(inner) = tool.get_table("Tools") { + collect_tool_names(inner, out); + } + } +} + +/// Renames tool keys (recursively) and rewrites every reference to them: `SourceOp` values and +/// whole-word identifiers inside `Expression` strings. +pub(super) fn rename_tools(tools: &mut LuaTable, renames: &HashMap) { + for (key, value) in &mut tools.entries { + let LuaKey::Str(name) = key else { continue }; + if let Some(new) = renames.get(name.as_str()) { + *name = new.clone(); + } + if let Some(tool) = value.as_table_mut() { + rewrite_references(tool, renames); + if let Some(inner) = tool.get_table_mut("Tools") { + rename_tools(inner, renames); + } + } + } +} + +pub(super) fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap) { + rewrite_formula_values(tbl, renames); + for (key, value) in &mut tbl.entries { + match (key, value) { + (LuaKey::Str(k), LuaValue::String(s)) if k == "SourceOp" => { + if let Some(new) = renames.get(s.as_str()) { + *s = new.clone(); + } + } + (LuaKey::Str(k), LuaValue::String(s)) if k == "Expression" => { + *s = rename_expression_idents(s, renames); + } + (_, LuaValue::Table(sub)) => rewrite_references(sub, renames), + _ => {} + } + } +} + +/// Rewrites the formula strings of an `Expression` modifier table (not recursive). +pub(super) fn rewrite_formula_values(tbl: &mut LuaTable, renames: &HashMap) { + if tbl.tag.as_deref() != Some("Expression") { + return; + } + let Some(inputs) = tbl.get_table_mut("Inputs") else { return }; + for key in EXPRESSION_FORMULA_INPUTS { + if let Some(LuaValue::String(formula)) = inputs.get_table_mut(key).and_then(|i| i.get_mut("Value")) { + *formula = rename_expression_idents(formula, renames); + } + } +} + +pub(super) fn rewrite_formulas_deep(tbl: &mut LuaTable, renames: &HashMap) { + rewrite_formula_values(tbl, renames); + for (_, value) in &mut tbl.entries { + if let Some(sub) = value.as_table_mut() { + rewrite_formulas_deep(sub, renames); + } + } +} + +/// Renames whole-word identifiers in `expr`, leaving property names (`Other.Size`) alone. +pub(super) fn rename_expression_idents(expr: &str, renames: &HashMap) -> String { + let mut out = String::with_capacity(expr.len()); + let mut word = String::new(); + let mut prev = None; + let flush = |word: &mut String, out: &mut String, prev: Option| { + let renamed = renames.get(word.as_str()).filter(|_| prev != Some('.')); + out.push_str(renamed.map_or(word.as_str(), String::as_str)); + word.clear(); + }; + for ch in expr.chars() { + if ch.is_ascii_alphanumeric() || ch == '_' { + word.push(ch); + } else { + flush(&mut word, &mut out, prev); + out.push(ch); + prev = Some(ch); + } + } + flush(&mut word, &mut out, prev); + out +} + +/// Removes `SourceOp`/`Source` pairs whose target fails `exists`, so pasted tools never point at +/// missing operators. +fn drop_unknown_source_ops(tbl: &mut LuaTable, exists: &mut dyn FnMut(&str) -> bool) { + let dangling = tbl + .get_str("SourceOp") + .is_some_and(|name| !exists(name)); + if dangling { + tbl.remove(&LuaKey::Str("SourceOp".to_owned())); + tbl.remove(&LuaKey::Str("Source".to_owned())); + } + for (_, value) in &mut tbl.entries { + if let Some(sub) = value.as_table_mut() { + drop_unknown_source_ops(sub, exists); + } + } +} + + +#[cfg(test)] +mod tests { + use super::*; + use crate::comp::ParamValue; + use crate::edit::CompHistory; + use crate::edit::tests::{GROUP_SNIPPET, sample_comp}; + + #[test] + fn export_fusion_clipboard_includes_owned_modifiers_and_internal_wires() { + let comp = sample_comp(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + + let both = comp.export_fusion_clipboard(&[bg, bc]); + assert!(both.contains("Tools = ordered()"), "{both}"); + assert!(both.contains("ActiveTool = \"BG1\""), "{both}"); + let parsed = parse_lua(&both).expect("clipboard parses as Lua"); + let tools = parsed.as_table().unwrap().get_table("Tools").unwrap(); + let names: Vec<_> = tools + .entries + .iter() + .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None }) + .collect(); + assert_eq!(names, ["BG1", "BC1", "BC1Gain"]); + assert_eq!( + tools + .get_table("BC1") + .and_then(|t| t.get_table("Inputs")) + .and_then(|i| i.get_table("Input")) + .and_then(|i| i.get_str("SourceOp")), + Some("BG1") + ); + + // Selecting only BC1 keeps its owned spline and leaves the external BG1 reference. + let only_bc = comp.export_fusion_clipboard(&[bc, bc]); + assert!(only_bc.contains("BC1Gain = BezierSpline")); + assert!(!only_bc.contains("BG1 = Background")); + assert!(only_bc.contains("SourceOp = \"BG1\"")); + + // Splines created after load (not yet in `raw_root`) are exported too. + let mut comp = comp; + let sp = comp.set_keyframe(bg, "Width", 0.0, 1.0).unwrap(); + assert!(comp.export_fusion_clipboard(&[bg]).contains(&format!("{sp} = BezierSpline"))); + } + + #[test] + fn paste_dedups_names_and_remaps_internal_wires_and_splines() { + let mut comp = sample_comp(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + let snippet = comp.export_fusion_clipboard(&[bg, bc]); + let nodes_before = comp.nodes.len(); + + let ids = comp.paste_fusion_clipboard(&snippet, (60.0, 40.0)).expect("paste"); + assert_eq!(ids.len(), 2); + assert_eq!(comp.nodes.len(), nodes_before + 2); + let (pbg, pbc) = (comp.node(ids[0]), comp.node(ids[1])); + assert_eq!((pbg.name.as_str(), pbc.name.as_str()), ("BG1_1", "BC1_1")); + assert_eq!(pbg.pos, [160.0, 90.0]); + assert_eq!(pbc.pos, [360.0, 90.0]); + assert_eq!(pbc.connected_node("Input"), Some("BG1_1")); + assert_eq!(pbc.connected_node("Gain"), Some("BC1Gain_1")); + assert_eq!(comp.splines["BC1Gain_1"].keyframes.len(), 2); + assert_eq!(comp.splines["BC1Gain"].keyframes.len(), 2); + assert_eq!(comp.find_node("BC1_1"), Some(ids[1])); + assert_eq!(comp.node(bc).connected_node("Input"), Some("BG1")); + + // Pasting again keeps advancing the suffix instead of clobbering earlier pastes. + let again = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap(); + assert_eq!(comp.node(again[0]).name, "BG1_2"); + assert_eq!(comp.node(again[1]).connected_node("Input"), Some("BG1_2")); + + // Everything survives a save/load roundtrip, including the cloned spline and offset. + let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("reload"); + let r_bc = reloaded.node(reloaded.find_node("BC1_1").unwrap()); + assert_eq!(r_bc.pos, [360.0, 90.0]); + assert_eq!(r_bc.connected_node("Input"), Some("BG1_1")); + assert!(reloaded.splines.contains_key("BC1Gain_1")); + } + + #[test] + fn paste_external_references_are_kept_when_present_and_dropped_when_missing() { + let mut comp = sample_comp(); + let bc = comp.find_node("BC1").unwrap(); + let snippet = comp.export_fusion_clipboard(&[bc]); + + let ids = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap(); + assert_eq!(comp.node(ids[0]).connected_node("Input"), Some("BG1")); + + let mut empty = Comp::from_fusion_str("Composition { Tools = ordered() { } }").unwrap(); + let ids = empty.paste_fusion_clipboard(&snippet, (5.0, 5.0)).unwrap(); + let pasted = empty.node(ids[0]); + assert_eq!(pasted.name, "BC1"); + assert_eq!(pasted.connected_node("Input"), None); + assert_eq!(pasted.connected_node("Gain"), Some("BC1Gain")); + assert!(!empty.to_fusion_string().contains("BG1")); + } + + #[test] + fn paste_accepts_full_composition_and_rewrites_expressions() { + let mut comp = sample_comp(); + let snippet = r#"Composition { + Tools = ordered() { + BG1 = Background { Inputs = { Width = Input { Value = 64, } }, }, + T1 = Transform { + Inputs = { + Size = Input { Expression = "BG1.Width / 2 + BG10.Width", }, + Input = Input { SourceOp = "BG1", Source = "Output", }, + }, + }, + }, +}"#; + let ids = comp.paste_fusion_clipboard(snippet, (1.0, 2.0)).unwrap(); + let t1 = comp.node(ids[1]); + assert_eq!(comp.node(ids[0]).name, "BG1_1"); + assert_eq!(comp.node(ids[0]).pos, [1.0, 2.0]); + assert_eq!(t1.connected_node("Input"), Some("BG1_1")); + assert_eq!( + t1.inputs["Size"].expression.as_deref(), + Some("BG1_1.Width / 2 + BG10.Width") + ); + } + + #[test] + fn paste_group_renames_nested_tools_and_remaps_macro_output() { + let mut comp = sample_comp(); + let first = comp.paste_fusion_clipboard(GROUP_SNIPPET, (0.0, 0.0)).unwrap(); + let second = comp.paste_fusion_clipboard(GROUP_SNIPPET, (50.0, 0.0)).unwrap(); + let (g1, g2) = (comp.node(first[0]), comp.node(second[0])); + assert_eq!((g1.name.as_str(), g2.name.as_str()), ("Group1", "Group1_1")); + assert_eq!(g2.pos, [60.0, 20.0]); + + let inner = comp.node(g2.macro_output.expect("macro output")); + assert_eq!(inner.name, "Inner1_1"); + assert!(inner.internal); + assert_eq!(inner.connected_node("XBlurSize"), Some("Inner1Size_1")); + assert!(comp.splines.contains_key("Inner1Size_1")); + assert_eq!(comp.node(g1.macro_output.unwrap()).name, "Inner1"); + assert_eq!(comp.find_node("Group1_1"), Some(second[0])); + assert_eq!(comp.find_node("Inner1_1"), g2.macro_output); + } + + #[test] + fn paste_is_one_undo_step_and_redoable() { + let mut comp = sample_comp(); + let mut history = CompHistory::new(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + let snippet = comp.export_fusion_clipboard(&[bg, bc]); + let (nodes, splines) = (comp.nodes.len(), comp.splines.len()); + history.mark_saved(&comp); + + let ids = history + .paste_fusion_clipboard(&mut comp, &snippet, (60.0, 40.0)) + .unwrap(); + assert_eq!(ids.len(), 2); + assert_eq!(history.undo_len(), 1); + assert_eq!(history.undo_label(), Some("Paste")); + assert!(history.is_dirty(&comp)); + + assert!(history.undo(&mut comp)); + assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes, splines)); + assert!(comp.find_node("BG1_1").is_none()); + assert!(!comp.to_fusion_string().contains("BG1_1")); + assert!(!history.can_undo()); + assert!(!history.is_dirty(&comp)); + + assert!(history.redo(&mut comp)); + assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes + 2, splines + 1)); + let pasted = comp.find_node("BC1_1").unwrap(); + assert_eq!(comp.node(pasted).connected_node("Input"), Some("BG1_1")); + assert!(!history.can_redo()); + } + + #[test] + fn paste_rejects_garbage_without_touching_comp_or_history() { + let mut comp = sample_comp(); + let mut history = CompHistory::new(); + let (rev, nodes) = (comp.revision, comp.nodes.len()); + for bad in ["", "hello world", "{ Foo = 1 }", "{ Tools = ordered() { } }", "{ Tools = "] { + assert!(history.paste_fusion_clipboard(&mut comp, bad, (0.0, 0.0)).is_err(), "{bad:?}"); + } + assert_eq!((comp.revision, comp.nodes.len()), (rev, nodes)); + assert!(!history.can_undo()); + assert!(!history.in_group()); + } + + const TWO_GROUPS: &str = r#"Composition { + Tools = ordered() { + BG = Background { }, + GA = GroupOperator { + Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, }, + Tools = ordered() { + Same = Blur { Inputs = { XBlurSize = Input { SourceOp = "SameSize", Source = "Value", }, }, }, + SameSize = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, }, + }, + }, + GB = GroupOperator { + Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, }, + Tools = ordered() { + Same = Blur { }, + }, + }, + }, +}"#; + + fn tool_names(tools: &LuaTable) -> Vec<&str> { + tools + .entries + .iter() + .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None }) + .collect() + } + + #[test] + + fn deleting_a_group_removes_its_private_tools_and_modifiers() { + let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); + let g = comp.find_node("Group1").unwrap(); + let deleted = comp.delete_nodes(&[g]); + assert_eq!(deleted, ["Group1", "Inner1"]); + assert!(comp.nodes.is_empty()); + assert!(comp.splines.is_empty()); + assert!(tool_names(comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap()).is_empty()); + } + + #[test] + fn deleting_a_node_keeps_splines_still_used_by_expression_modifiers() { + let src = r#"Composition { + Tools = ordered() { + N = Transform { Inputs = { Angle = Input { SourceOp = "Shared", Source = "Value", }, Size = Input { SourceOp = "E", Source = "NumberResult", }, }, }, + M = Transform { Inputs = { Angle = Input { SourceOp = "Own", Source = "Value", }, Size = Input { SourceOp = "E2", Source = "NumberResult", }, }, }, + E = Expression { Inputs = { n1 = Input { SourceOp = "Shared", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, }, + E2 = Expression { Inputs = { n1 = Input { SourceOp = "Own", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, }, + Shared = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, }, + Own = BezierSpline { KeyFrames = { [0] = { 2, Flags = { Linear = true } } }, }, + }, +}"#; + let mut comp = Comp::from_fusion_str(src).unwrap(); + comp.delete_nodes(&[comp.find_node("M").unwrap()]); + assert!(!comp.expression_modifiers.contains_key("E2")); + assert!(!comp.splines.contains_key("Own")); + assert!(comp.expression_modifiers.contains_key("E")); + assert!(comp.splines.contains_key("Shared")); + + // Deleting the other owner prunes the expression modifier and its spline. + let mut comp = Comp::from_fusion_str(src).unwrap(); + comp.delete_nodes(&[comp.find_node("N").unwrap()]); + assert!(!comp.expression_modifiers.contains_key("E")); + assert!(!comp.splines.contains_key("Shared")); + + // A spline referenced by a surviving (unpruned) expression modifier outlives its owner. + let with_orphan = src.replace("\t},\n}", "\t\tEO = Expression { Inputs = { n1 = Input { SourceOp = \"Shared\", Source = \"Value\", }, }, },\n\t},\n}"); + let mut comp = Comp::from_fusion_str(&with_orphan).unwrap(); + comp.delete_nodes(&[comp.find_node("N").unwrap()]); + assert!(comp.expression_modifiers.contains_key("EO")); + assert!(comp.splines.contains_key("Shared")); + } + + #[test] + fn export_includes_modifiers_nested_in_a_copied_internal_node_once() { + let comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); + let inner = comp.find_node("Inner1").unwrap(); + let clip = comp.export_fusion_clipboard(&[inner]); + let parsed = parse_lua(&clip).unwrap(); + let tools = parsed.as_table().unwrap().get_table("Tools").unwrap(); + assert_eq!(tool_names(tools), ["Inner1", "Inner1Size"]); + + let whole = comp.export_fusion_clipboard(&[comp.find_node("Group1").unwrap()]); + assert_eq!(whole.matches("Inner1Size = BezierSpline").count(), 1, "{whole}"); + } + + #[test] + fn paste_never_links_to_group_private_tools() { + let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); + let snippet = r#"{ Tools = ordered() { T = Transform { Inputs = { + Input = Input { SourceOp = "Inner1", Source = "Output", }, + Mask = Input { SourceOp = "Group1", Source = "Output", }, + Angle = Input { SourceOp = "Inner1Size", Source = "Value", }, + }, }, }, }"#; + let ids = comp.paste_fusion_clipboard(snippet, (0.0, 0.0)).unwrap(); + let t = comp.node(ids[0]); + assert_eq!(t.connected_node("Input"), None); + assert_eq!(t.connected_node("Angle"), None); + assert_eq!(t.connected_node("Mask"), Some("Group1")); + } + + #[test] + fn expression_renames_skip_property_names() { + let renames = HashMap::from([("Size".to_owned(), "Big".to_owned())]); + assert_eq!( + rename_expression_idents("Other.Size + Size.Width * Size", &renames), + "Other.Size + Big.Width * Big" + ); + } + + #[test] + fn rename_and_paste_rewrite_expression_modifier_formulas() { + let src = r#"Composition { + Tools = ordered() { + BG = Background { }, + E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width + Other.BG", }, }, }, + }, +}"#; + let mut comp = Comp::from_fusion_str(src).unwrap(); + let bg = comp.find_node("BG").unwrap(); + comp.rename_node(bg, "Plate").unwrap(); + let formula = |c: &Comp| c.expression_modifiers["E"].inputs["NumberExpression"].value.clone(); + assert_eq!(formula(&comp), Some(ParamValue::Text("Plate.Width + Other.BG".to_owned()))); + assert!(comp.to_fusion_string().contains("Plate.Width + Other.BG")); + + let paste = r#"{ Tools = ordered() { BG = Background { }, E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width", }, }, }, }, }"#; + comp.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap(); + assert_eq!( + comp.expression_modifiers["E_1"].inputs["NumberExpression"].value, + Some(ParamValue::Text("BG.Width".to_owned())) + ); + let mut again = Comp::from_fusion_str(paste).unwrap(); + again.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap(); + assert_eq!( + again.expression_modifiers["E_1"].inputs["NumberExpression"].value, + Some(ParamValue::Text("BG_1.Width".to_owned())) + ); + } + + #[test] + fn renaming_one_groups_private_tool_leaves_same_named_tools_elsewhere() { + let mut comp = Comp::from_fusion_str(TWO_GROUPS).unwrap(); + let (ga, gb) = (comp.find_node("GA").unwrap(), comp.find_node("GB").unwrap()); + let a_same = comp.nodes.iter().position(|n| n.name == "Same" && n.id.0 < ga.0).unwrap(); + assert_eq!(comp.rename_node(NodeId(a_same), "Renamed").unwrap(), "Renamed"); + + let text = comp.to_fusion_string(); + let saved = Comp::from_fusion_str(&text).unwrap(); + let group_tools = |name: &str| { + let g = saved.node(saved.find_node(name).unwrap()); + ( + g.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp").unwrap().to_owned(), + tool_names(find_raw_tool_in(&saved, name)).into_iter().map(str::to_owned).collect::>(), + ) + }; + assert_eq!(group_tools("GA"), ("Renamed".to_owned(), vec!["Renamed".to_owned(), "SameSize".to_owned()])); + assert_eq!(group_tools("GB"), ("Same".to_owned(), vec!["Same".to_owned()])); + assert_eq!(comp.node(gb).name, "GB"); + } + + fn find_raw_tool_in<'a>(comp: &'a Comp, group: &str) -> &'a LuaTable { + let tools = comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap(); + find_raw_tool(tools, group).unwrap().get_table("Tools").unwrap() + } + + #[test] + fn renaming_a_top_level_tool_ignores_groups_with_a_private_tool_of_that_name() { + let src = TWO_GROUPS.replace("BG = Background { },", "BG = Background { },\n\t\tSame = Blur { },"); + let mut comp = Comp::from_fusion_str(&src).unwrap(); + let top = comp.find_node("Same").unwrap(); + assert!(!comp.node(top).internal); + comp.rename_node(top, "Top").unwrap(); + let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); + let ga = saved.node(saved.find_node("GA").unwrap()); + assert_eq!( + ga.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp"), + Some("Same") + ); + assert!(saved.find_node("Top").is_some_and(|id| !saved.node(id).internal)); + } + + #[test] + fn duplicate_nodes_clones_groups_and_curve_modifiers() { + let src = r#"Composition { + Tools = ordered() { + BG = Background { }, + HC = HueCurves { + Inputs = { + Input = Input { SourceOp = "BG", Source = "Output", }, + RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", }, + }, + Tools = ordered() { + HC_RSup = LUTBezier { KeyColorSplines = { [0] = { [0] = { 0.5 }, [6] = { 0.5 } } }, }, + }, + }, + }, +}"#; + let mut comp = Comp::from_fusion_str(src).unwrap(); + let hc = comp.find_node("HC").unwrap(); + let dup = comp.duplicate_nodes(&[hc], [10.0, 0.0]); + assert_eq!(dup.len(), 1); + let d = comp.node(dup[0]); + assert_eq!(d.name, "HC_1"); + assert_eq!(d.connected_node("Input"), Some("BG")); + assert_eq!(d.connected_node("RedSuppress"), Some("HC_RSup_1")); + assert!(comp.splines.contains_key("HC_RSup_1") && comp.splines.contains_key("HC_RSup")); + let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); + assert!(saved.splines.contains_key("HC_RSup_1")); + + let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); + let g = comp.find_node("Group1").unwrap(); + let dup = comp.duplicate_nodes(&[g], [0.0, 80.0]); + let copy = comp.node(dup[0]); + assert_eq!(copy.name, "Group1_1"); + assert_eq!(comp.node(copy.macro_output.unwrap()).name, "Inner1_1"); + assert!(comp.splines.contains_key("Inner1Size_1")); + } +} diff --git a/crates/model/src/edit/defaults.rs b/crates/model/src/edit/defaults.rs new file mode 100644 index 0000000000000000000000000000000000000000..f5642649316c64c66e61e49b89eb6aa19c7baac1 --- /dev/null +++ b/crates/model/src/edit/defaults.rs @@ -0,0 +1,176 @@ +use crate::comp::{ParamValue, vec2_lua}; +use crate::lua_value::{LuaKey, LuaTable, LuaValue}; + +pub(super) fn default_view_info_for_kind(kind: &str, pos: [f32; 2]) -> LuaTable { + let tag = match kind { + "PipeRouter" => "PipeRouterInfo", + "Underlay" => "UnderlayInfo", + "Note" | "StickyNote" => "StickyNoteInfo", + _ => "OperatorInfo", + }; + let mut vi = LuaTable { + tag: Some(tag.to_owned()), + entries: Vec::new(), + }; + vi.set( + LuaKey::Str("Pos".to_owned()), + vec2_lua(pos[0] as f64, pos[1] as f64), + ); + match kind { + "Underlay" => { + vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(172.0, 166.364)); + } + "Note" | "StickyNote" => { + let mut flags = LuaTable::default(); + flags.set(LuaKey::Str("Expanded".to_owned()), LuaValue::Bool(true)); + vi.set(LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags)); + vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(196.0, 179.364)); + } + _ => {} + } + vi +} + +/// Returns sensible Fusion 21.1 default inputs for common tool classes so Fusion Studio opens +/// newly created nodes cleanly without errors. +pub(super) fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Vec<(String, ParamValue)> { + let w = width as f64; + let h = height as f64; + let num = |k: &str, v: f64| (k.to_owned(), ParamValue::Number(v)); + let pt = |k: &str, x: f64, y: f64| (k.to_owned(), ParamValue::Point([x, y])); + let txt = |k: &str, s: &str| (k.to_owned(), ParamValue::Text(s.to_owned())); + let fuid = |k: &str, s: &str| (k.to_owned(), ParamValue::FuId(s.to_owned())); + + match kind { + "Background" => vec![ + num("Width", w), + num("Height", h), + num("UseFrameFormatSettings", 1.0), + num("TopLeftRed", 0.0), + num("TopLeftGreen", 0.0), + num("TopLeftBlue", 0.0), + num("TopLeftAlpha", 1.0), + ], + "Merge" => vec![ + num("PerformDepthMerge", 0.0), + pt("Center", 0.5, 0.5), + num("Size", 1.0), + num("Angle", 0.0), + num("Blend", 1.0), + ], + "Transform" => vec![ + pt("Center", 0.5, 0.5), + pt("Pivot", 0.5, 0.5), + num("Size", 1.0), + num("Angle", 0.0), + ], + "Blur" => vec![fuid("Filter", "Fast Gaussian"), num("XBlurSize", 1.0)], + "Glow" => vec![num("XGlowSize", 10.0), num("Glow", 0.8)], + "SoftGlow" => vec![ + fuid("Filter", "Fast Gaussian"), + num("Gain", 2.0), + num("XGlowSize", 10.0), + ], + "BrightnessContrast" => vec![ + num("Gain", 1.0), + num("Lift", 0.0), + num("Gamma", 1.0), + num("Contrast", 0.0), + num("Brightness", 0.0), + num("Saturation", 1.0), + ], + "ColorCorrector" => vec![ + num("WheelSaturation1", 1.0), + num("MasterRGBGain", 1.0), + num("MasterRGBGamma", 1.0), + ], + "ColorGain" => vec![ + num("GainRed", 1.0), + num("GainGreen", 1.0), + num("GainBlue", 1.0), + num("GainAlpha", 1.0), + num("GammaRed", 1.0), + num("GammaGreen", 1.0), + num("GammaBlue", 1.0), + ], + "RectangleMask" => vec![ + num("MaskWidth", w), + num("MaskHeight", h), + pt("PixelAspect", 1.0, 1.0), + pt("Center", 0.5, 0.5), + num("Width", 0.5), + num("Height", 0.5), + num("CornerRadius", 0.0), + num("SoftEdge", 0.0), + ], + "EllipseMask" => vec![ + num("MaskWidth", w), + num("MaskHeight", h), + pt("PixelAspect", 1.0, 1.0), + pt("Center", 0.5, 0.5), + num("Width", 0.5), + num("Height", 0.5), + num("SoftEdge", 0.0), + ], + "PolylineMask" => vec![ + num("MaskWidth", w), + num("MaskHeight", h), + pt("PixelAspect", 1.0, 1.0), + num("SoftEdge", 0.0), + ], + "BitmapMask" => vec![ + num("MaskWidth", w), + num("MaskHeight", h), + pt("PixelAspect", 1.0, 1.0), + fuid("Channel", "Alpha"), + ], + "TextPlus" => vec![ + num("Width", w), + num("Height", h), + num("UseFrameFormatSettings", 1.0), + txt("StyledText", ""), + txt("Font", "Open Sans"), + txt("Style", "Bold"), + num("Size", 0.08), + pt("Center", 0.5, 0.5), + ], + "Loader" => vec![], + "Saver" => vec![num("ProcessWhenBlendIs00", 0.0), num("CreateDir", 1.0)], + "Displace" => vec![ + num("Type", 0.0), + num("XRefraction", 0.0), + num("YRefraction", 0.0), + num("RefractionStrength", 0.0), + ], + "FastNoise" => vec![ + num("Width", w), + num("Height", h), + num("UseFrameFormatSettings", 1.0), + num("Detail", 2.0), + num("Contrast", 1.0), + num("XScale", 2.0), + num("Seethe", 0.0), + ], + "PipeRouter" | "Underlay" => vec![], + "Switch" | "Fuse.Switch" => vec![num("Source", 0.0)], + "TimeStretcher" => vec![num("SourceTime", 0.0), num("InterpolateBetweenFrames", 0.0)], + "TimeSpeed" => vec![num("Speed", 1.0), num("Delay", 0.0)], + "Renderer3D" => vec![ + num("Width", w), + num("Height", h), + num("UseFrameFormatSettings", 1.0), + fuid("RendererType", "RendererOpenGL"), + ], + "Camera3D" => vec![num("FLength", 24.0), num("PlaneOfFocus", 5.0)], + "Merge3D" => vec![num("PassThroughLights", 1.0)], + "Transform3D" => vec![num("Transform3DOp.Scale.X", 1.0)], + "ImagePlane3D" => vec![ + num("SurfacePlaneInputs.Width", 1.0), + num("SurfacePlaneInputs.Height", 1.0), + ], + "Shape3D" => vec![fuid("Shape", "SurfacePlaneInputs")], + "Note" | "StickyNote" => vec![txt("Comments", "")], + _ => vec![], + } +} + diff --git a/crates/model/src/edit/history.rs b/crates/model/src/edit/history.rs new file mode 100644 index 0000000000000000000000000000000000000000..3c859b36e43413caf46ae761271e082d6f7ea52d --- /dev/null +++ b/crates/model/src/edit/history.rs @@ -0,0 +1,417 @@ +use crate::comp::{Comp, NodeId}; +use std::collections::VecDeque; + +/// Default maximum number of undo steps retained by [`CompHistory`]. +pub const DEFAULT_MAX_HISTORY: usize = 128; + +#[derive(Clone, Debug)] +struct HistoryEntry { + label: String, + snapshot: Comp, + coalesce_key: Option, +} + +/// Snapshot-based undo/redo history stack for [`Comp`] with transaction groups and drag coalescing. +#[derive(Clone, Debug)] +pub struct CompHistory { + undo_stack: VecDeque, + redo_stack: Vec, + max_depth: usize, + active_group: Option<(String, Comp)>, + group_depth: usize, + /// Position in `undo_stack` corresponding to the last saved state (`Some(0)` means clean at + /// depth 0; `None` means the saved state is no longer reachable via undo/redo). + saved_undo_depth: Option, + saved_revision: Option, +} + +impl Default for CompHistory { + fn default() -> Self { + Self::new() + } +} + +impl CompHistory { + pub fn new() -> Self { + Self::with_max_depth(DEFAULT_MAX_HISTORY) + } + + pub fn with_max_depth(max_depth: usize) -> Self { + Self { + undo_stack: VecDeque::new(), + redo_stack: Vec::new(), + max_depth: max_depth.max(1), + active_group: None, + group_depth: 0, + saved_undo_depth: None, + saved_revision: None, + } + } + + pub fn max_depth(&self) -> usize { + self.max_depth + } + + pub fn can_undo(&self) -> bool { + !self.undo_stack.is_empty() + } + + pub fn can_redo(&self) -> bool { + !self.redo_stack.is_empty() + } + + pub fn undo_len(&self) -> usize { + self.undo_stack.len() + } + + pub fn redo_len(&self) -> usize { + self.redo_stack.len() + } + + pub fn undo_label(&self) -> Option<&str> { + self.undo_stack.back().map(|e| e.label.as_str()) + } + + pub fn redo_label(&self) -> Option<&str> { + self.redo_stack.last().map(|e| e.label.as_str()) + } + + pub fn in_group(&self) -> bool { + self.group_depth > 0 + } + + /// Clears all undo/redo entries and any active transaction group. + pub fn clear(&mut self) { + self.undo_stack.clear(); + self.redo_stack.clear(); + self.active_group = None; + self.group_depth = 0; + self.saved_undo_depth = None; + self.saved_revision = None; + } + + /// Records the current state of `comp` as the clean saved point. + pub fn mark_saved(&mut self, comp: &Comp) { + // Edits after a save must never coalesce into the saved undo entry. + self.break_coalescing(); + self.saved_undo_depth = Some(self.undo_stack.len()); + self.saved_revision = Some(comp.revision); + } + + pub fn saved_revision(&self) -> Option { + self.saved_revision + } + + /// Returns `true` if `comp` has unsaved modifications relative to the last [`Self::mark_saved`]. + pub fn is_dirty(&self, comp: &Comp) -> bool { + match self.saved_undo_depth { + Some(depth) if depth == self.undo_stack.len() => { + // If an edit was pushed via coalescing or outside history after mark_saved, + // check whether we're still at the saved depth without an active modified group. + if let Some((_, ref snap)) = self.active_group { + comp.revision != snap.revision + } else { + false + } + } + _ => self.saved_revision != Some(comp.revision), + } + } + + /// Pushes a snapshot of `comp` BEFORE applying a discrete mutation. + /// No-op if currently inside a [`Self::begin_group`] transaction. + pub fn push_snapshot(&mut self, comp: &Comp, label: impl Into) { + if self.group_depth > 0 { + return; + } + self.push_entry(HistoryEntry { + label: label.into(), + snapshot: comp.clone(), + coalesce_key: None, + }); + } + + /// Pushes a snapshot of `comp` BEFORE applying a continuous mutation (such as dragging a node + /// or scrubbing a parameter slider). Consecutive calls with the same `key` coalesce into a + /// single undo step preserving the initial pre-drag snapshot. + /// No-op if currently inside a [`Self::begin_group`] transaction. + pub fn push_coalesced( + &mut self, + comp: &Comp, + label: impl Into, + key: impl Into, + ) { + if self.group_depth > 0 { + return; + } + let key_str = key.into(); + let label_str = label.into(); + if self.redo_stack.is_empty() { + if let Some(top) = self.undo_stack.back_mut() { + if top.coalesce_key.as_deref() == Some(key_str.as_str()) { + top.label = label_str; + return; + } + } + } + self.push_entry(HistoryEntry { + label: label_str, + snapshot: comp.clone(), + coalesce_key: Some(key_str), + }); + } + + /// Breaks coalescing on the top undo entry so subsequent edits with the same key start a new + /// undo step (e.g. on pointer release). + pub fn break_coalescing(&mut self) { + if let Some(top) = self.undo_stack.back_mut() { + top.coalesce_key = None; + } + } + + /// Begins a transaction group. All mutations until the matching [`Self::commit_group`] collapse + /// into a single undo step. Supports nesting. + pub fn begin_group(&mut self, comp: &Comp, label: impl Into) { + if self.group_depth == 0 { + self.active_group = Some((label.into(), comp.clone())); + } + self.group_depth += 1; + } + + /// Commits the current transaction group. When the outermost group closes, pushes one undo + /// entry if `comp.revision` changed since `begin_group`. Returns `true` if an entry was added. + pub fn commit_group(&mut self, comp: &Comp) -> bool { + if self.group_depth == 0 { + return false; + } + self.group_depth -= 1; + if self.group_depth > 0 { + return false; + } + let Some((label, snapshot)) = self.active_group.take() else { + return false; + }; + if comp.revision == snapshot.revision { + return false; + } + self.push_entry(HistoryEntry { + label, + snapshot, + coalesce_key: None, + }); + true + } + + /// Cancels the active transaction group and restores `comp` to its pre-group state. + pub fn cancel_group(&mut self, comp: &mut Comp) -> bool { + if self.group_depth == 0 { + return false; + } + self.group_depth = 0; + let Some((_, snapshot)) = self.active_group.take() else { + return false; + }; + let prev_rev = comp.revision; + restore_snapshot(comp, snapshot); + if comp.revision != prev_rev { + comp.revision = prev_rev.max(comp.revision) + 1; + } + true + } + + /// Undoable [`Comp::paste_fusion_clipboard`]: the whole paste is one undo step, and a failed + /// paste leaves both `comp` and the history untouched. + pub fn paste_fusion_clipboard( + &mut self, + comp: &mut Comp, + lua_snippet: &str, + offset: (f32, f32), + ) -> Result, String> { + self.begin_group(comp, "Paste"); + let pasted = comp.paste_fusion_clipboard(lua_snippet, offset); + self.commit_group(comp); + pasted + } + + /// Undoes the most recent edit, restoring `comp` to the saved snapshot. + /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly. + pub fn undo(&mut self, comp: &mut Comp) -> bool { + if self.group_depth > 0 { + self.group_depth = 1; + self.commit_group(comp); + } + let Some(entry) = self.undo_stack.pop_back() else { + return false; + }; + let prev_rev = comp.revision; + let redo_entry = HistoryEntry { + label: entry.label, + snapshot: comp.clone(), + coalesce_key: None, + }; + self.redo_stack.push(redo_entry); + restore_snapshot(comp, entry.snapshot); + comp.revision = prev_rev.max(comp.revision) + 1; + true + } + + /// Redoes the most recently undone edit. + /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly. + pub fn redo(&mut self, comp: &mut Comp) -> bool { + let Some(entry) = self.redo_stack.pop() else { + return false; + }; + let prev_rev = comp.revision; + let undo_entry = HistoryEntry { + label: entry.label, + snapshot: comp.clone(), + coalesce_key: None, + }; + self.undo_stack.push_back(undo_entry); + restore_snapshot(comp, entry.snapshot); + comp.revision = prev_rev.max(comp.revision) + 1; + true + } + + fn push_entry(&mut self, entry: HistoryEntry) { + // Any saved state that lived in the redo branch is now unreachable. + if let Some(saved_depth) = self.saved_undo_depth { + if saved_depth > self.undo_stack.len() { + self.saved_undo_depth = None; + } + } + self.redo_stack.clear(); + self.undo_stack.push_back(entry); + while self.undo_stack.len() > self.max_depth { + self.undo_stack.pop_front(); + self.saved_undo_depth = self.saved_undo_depth.and_then(|d| d.checked_sub(1)); + } + } +} + +/// Replaces `comp` with `snapshot`, keeping the live file identity so a Save As followed by undo +/// never points Save at the file the snapshot came from. +fn restore_snapshot(comp: &mut Comp, mut snapshot: Comp) { + snapshot.path = comp.path.take(); + snapshot.name = std::mem::take(&mut comp.name); + *comp = snapshot; +} + + +#[cfg(test)] +mod tests { + use super::*; + use crate::comp::ParamValue; + use crate::edit::tests::sample_comp; + use std::path::Path; + + #[test] + fn comp_history_undo_redo_coalescing_groups_and_bounds() { + let mut comp = sample_comp(); + let mut history = CompHistory::with_max_depth(3); + history.mark_saved(&comp); + assert!(!history.is_dirty(&comp)); + assert!(!history.can_undo()); + assert!(!history.can_redo()); + + let bg = comp.find_node("BG1").unwrap(); + + // 1. Coalesced drag: 120 frames produce ONE undo step + for i in 1..=120 { + history.push_coalesced(&comp, "Move BG1", format!("drag_node:{}", bg.0)); + comp.set_node_pos(bg, [100.0 + i as f32, 50.0 + i as f32 * 0.5]); + } + history.break_coalescing(); + assert_eq!(history.undo_len(), 1); + assert_eq!(history.undo_label(), Some("Move BG1")); + assert!(history.is_dirty(&comp)); + assert_eq!(comp.node(bg).pos, [220.0, 110.0]); + + // Undo restores original pre-drag position and clears dirty flag + assert!(history.undo(&mut comp)); + assert_eq!(comp.node(bg).pos, [100.0, 50.0]); + assert!(!history.is_dirty(&comp)); + assert!(history.can_redo()); + assert_eq!(history.redo_label(), Some("Move BG1")); + + // Redo restores final dragged position + assert!(history.redo(&mut comp)); + assert_eq!(comp.node(bg).pos, [220.0, 110.0]); + assert!(history.is_dirty(&comp)); + + // 2. Redo invalidation on new edit after undo + assert!(history.undo(&mut comp)); + assert!(history.can_redo()); + history.push_snapshot(&comp, "Add Blur"); + let blur = comp.add_node("Blur", None, [200.0, 100.0]); + assert!(!history.can_redo()); + assert_eq!(history.undo_len(), 1); + + // 3. Transaction group collapses multiple mutations into one undo step + history.begin_group(&comp, "Style Blur"); + comp.set_input_value(blur, "XBlurSize", ParamValue::Number(5.0)); + history.push_snapshot(&comp, "Ignored inside group"); + comp.toggle_passthrough(blur); + assert!(history.commit_group(&comp)); + assert_eq!(history.undo_len(), 2); + assert_eq!(history.undo_label(), Some("Style Blur")); + + // No-op group doesn't push + history.begin_group(&comp, "No-op"); + assert!(!history.commit_group(&comp)); + assert_eq!(history.undo_len(), 2); + + // Cancel group restores pre-group state + history.begin_group(&comp, "Canceled"); + comp.set_node_pos(blur, [999.0, 999.0]); + assert!(history.cancel_group(&mut comp)); + assert_eq!(comp.node(blur).pos, [200.0, 100.0]); + + // 4. Bounded history depth (max_depth = 3) + history.push_snapshot(&comp, "Edit 3"); + comp.set_node_pos(blur, [210.0, 100.0]); + history.push_snapshot(&comp, "Edit 4"); + comp.set_node_pos(blur, [220.0, 100.0]); + assert_eq!(history.undo_len(), 3); + + history.clear(); + assert!(!history.can_undo()); + assert!(!history.can_redo()); + } + + #[test] + fn mark_saved_stops_later_edits_coalescing_into_the_saved_step() { + let mut comp = sample_comp(); + let mut history = CompHistory::new(); + let bg = comp.find_node("BG1").unwrap(); + + history.push_coalesced(&comp, "Drag", "drag"); + comp.set_node_pos(bg, [1.0, 1.0]); + history.mark_saved(&comp); + assert!(!history.is_dirty(&comp)); + + history.push_coalesced(&comp, "Drag", "drag"); + comp.set_node_pos(bg, [2.0, 2.0]); + assert_eq!(history.undo_len(), 2); + assert!(history.is_dirty(&comp)); + } + + #[test] + fn undo_and_redo_keep_the_live_file_identity() { + let mut comp = sample_comp(); + comp.path = Some("/tmp/original.comp".into()); + comp.name = "original".to_owned(); + let mut history = CompHistory::new(); + let bg = comp.find_node("BG1").unwrap(); + + history.push_snapshot(&comp, "Move"); + comp.set_node_pos(bg, [9.0, 9.0]); + comp.path = Some("/tmp/save_as.comp".into()); + comp.name = "save_as".to_owned(); + + assert!(history.undo(&mut comp)); + assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as")); + assert!(history.redo(&mut comp)); + assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as")); + } +} diff --git a/crates/model/src/edit/keyframes.rs b/crates/model/src/edit/keyframes.rs new file mode 100644 index 0000000000000000000000000000000000000000..7f35028d1c0dd08045815021e8c07aace105267c --- /dev/null +++ b/crates/model/src/edit/keyframes.rs @@ -0,0 +1,185 @@ +use super::remove_tools_recursive; +use crate::comp::{Comp, InputBinding, NodeId, ParamValue, ensure_table_mut, param_value_to_lua}; +use crate::lua_value::{LuaKey, LuaValue}; +use crate::spline::{BezierSpline, Keyframe}; +use std::collections::HashSet; + +/// Keyframe times closer than this are the same keyframe (matches the Inspector's `keyframe_state`). +const KEYFRAME_EPS: f64 = 1e-4; + + +impl Comp { + pub fn set_keyframe( + &mut self, + node: NodeId, + input: &str, + frame: f64, + value: f64, + ) -> Result { + if node.0 >= self.nodes.len() { + return Err(format!("invalid node id {}", node.0)); + } + if !frame.is_finite() || !value.is_finite() { + return Err("keyframe frame and value must be finite numbers".to_owned()); + } + + let existing_spline = self.nodes[node.0] + .inputs + .get(input) + .and_then(|b| b.source_op.clone()) + .filter(|op| self.splines.contains_key(op)); + + let spline_name = if let Some(sp_name) = existing_spline { + let sp = self.splines.get_mut(&sp_name).expect("spline exists"); + upsert_keyframe(sp, frame, value); + sp_name + } else { + let hint = format!("{}{}", self.nodes[node.0].name, input); + let sp_name = self.generate_unique_name("BezierSpline", Some(&hint)); + let color = default_spline_color(&sp_name); + let spline = BezierSpline { + name: sp_name.clone(), + color, + keyframes: vec![Keyframe::new(frame, value)], + }; + self.splines.insert(sp_name.clone(), spline); + + let n = &mut self.nodes[node.0]; + let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding { + value: None, + source_op: None, + source_output: None, + expression: None, + }); + entry.source_op = Some(sp_name.clone()); + entry.source_output = Some("Value".to_owned()); + + let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None); + let port_tbl = ensure_table_mut(in_tbl, input, Some("Input")); + port_tbl.set( + LuaKey::Str("SourceOp".to_owned()), + LuaValue::String(sp_name.clone()), + ); + port_tbl.set( + LuaKey::Str("Source".to_owned()), + LuaValue::String("Value".to_owned()), + ); + + sp_name + }; + + self.revision += 1; + Ok(spline_name) + } + + /// Removes the keyframe at `frame` from `spline_name`. Returns `true` if a keyframe was deleted. + /// Deleting a spline's last keyframe removes the spline and leaves every input it drove with + /// that keyframe's value as a static `Value`. + pub fn delete_keyframe(&mut self, spline_name: &str, frame: f64) -> bool { + let Some(sp) = self.splines.get_mut(spline_name) else { + return false; + }; + let Some(pos) = sp + .keyframes + .iter() + .position(|kf| (kf.time - frame).abs() < KEYFRAME_EPS) + else { + return false; + }; + let removed = sp.keyframes.remove(pos); + if sp.keyframes.is_empty() { + self.splines.remove(spline_name); + let value = ParamValue::Number(removed.value); + for node in &mut self.nodes { + for (port, binding) in &mut node.inputs { + if binding.source_op.as_deref() != Some(spline_name) { + continue; + } + binding.source_op = None; + binding.source_output = None; + binding.value = Some(value.clone()); + let port_tbl = ensure_table_mut(ensure_table_mut(&mut node.raw, "Inputs", None), port, Some("Input")); + port_tbl.remove(&LuaKey::Str("SourceOp".to_owned())); + port_tbl.remove(&LuaKey::Str("Source".to_owned())); + port_tbl.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&value)); + } + } + if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) { + remove_tools_recursive(tools, &HashSet::from([spline_name.to_owned()])); + } + } + self.revision += 1; + true + } +} + +fn upsert_keyframe(spline: &mut BezierSpline, frame: f64, value: f64) { + if let Some(existing) = spline + .keyframes + .iter_mut() + .find(|kf| (kf.time - frame).abs() < KEYFRAME_EPS) + { + // Handles are absolute coordinates, so they travel with the key. + let (dt, dv) = (frame - existing.time, value - existing.value); + existing.time = frame; + existing.value = value; + for handle in [&mut existing.lh, &mut existing.rh].into_iter().flatten() { + handle[0] += dt; + handle[1] += dv; + } + } else { + spline.keyframes.push(Keyframe::new(frame, value)); + spline.sort(); + } +} + +fn default_spline_color(name: &str) -> [u8; 3] { + // Deterministic vivid Fusion-like spline palette based on name hash. + const PALETTE: &[[u8; 3]] = &[ + [255, 128, 0], + [102, 204, 255], + [170, 238, 102], + [255, 102, 170], + [204, 153, 255], + [255, 221, 85], + ]; + let hash = name + .bytes() + .fold(0usize, |acc, b| acc.wrapping_mul(31).wrapping_add(b as usize)); + PALETTE[hash % PALETTE.len()] +} + + +#[cfg(test)] +mod tests { + use super::*; + use crate::edit::tests::sample_comp; + + #[test] + fn updating_a_keyframe_moves_its_handles_with_it() { + let mut comp = sample_comp(); + let bc = comp.find_node("BC1").unwrap(); + comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].lh = Some([20.0, 1.5]); + comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].rh = Some([40.0, 2.5]); + comp.set_keyframe(bc, "Gain", 30.0, 3.0).unwrap(); + let kf = &comp.splines["BC1Gain"].keyframes[1]; + assert_eq!((kf.value, kf.lh, kf.rh), (3.0, Some([20.0, 2.5]), Some([40.0, 3.5]))); + } + + #[test] + fn deleting_the_last_keyframe_keeps_its_value_as_a_static_input() { + let mut comp = sample_comp(); + let bc = comp.find_node("BC1").unwrap(); + // Within the shared 1e-4 tolerance. + assert!(comp.delete_keyframe("BC1Gain", 0.00005)); + assert!(comp.delete_keyframe("BC1Gain", 30.0)); + assert!(!comp.splines.contains_key("BC1Gain")); + assert_eq!(comp.node(bc).connected_node("Gain"), None); + assert_eq!(comp.node(bc).static_number("Gain"), Some(2.0)); + + let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); + let r = saved.node(saved.find_node("BC1").unwrap()); + assert_eq!(r.static_number("Gain"), Some(2.0)); + assert!(!saved.to_fusion_string().contains("BC1Gain")); + } +} diff --git a/crates/model/src/edit/tests.rs b/crates/model/src/edit/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..a6078fc29f06632fd3da0557e9f73b5761de2eb2 --- /dev/null +++ b/crates/model/src/edit/tests.rs @@ -0,0 +1,359 @@ +use super::*; +use crate::expr::ExprEngine; +use std::path::Path; + + pub(super) fn sample_comp() -> Comp { + let src = r#"Composition { + CurrentTime = 10, + RenderRange = { 0, 100 }, + GlobalRange = { 0, 100 }, + Prefs = { + Comp = { + FrameFormat = { + Width = 1920, + Height = 1080, + Rate = 24, + DepthFull = 3, + }, + }, + }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 1920, }, + Height = Input { Value = 1080, }, + TopLeftRed = Input { Value = 0.25, }, + }, + ViewInfo = OperatorInfo { Pos = { 100, 50 } }, + }, + BC1 = BrightnessContrast { + Inputs = { + Input = Input { + SourceOp = "BG1", + Source = "Output", + }, + Gain = Input { + SourceOp = "BC1Gain", + Source = "Value", + }, + }, + ViewInfo = OperatorInfo { Pos = { 300, 50 } }, + }, + BC1Gain = BezierSpline { + SplineColor = { Red = 255, Green = 128, Blue = 0 }, + KeyFrames = { + [0] = { 1, Flags = { Linear = true } }, + [30] = { 2, Flags = { Linear = true } }, + }, + }, + SurfaceTracker1 = SurfaceTracker { + Inputs = { + Source = Input { + SourceOp = "BC1", + Source = "Output", + }, + MeshBlob = Input { + Value = TrackingMesh { + Vertices = { 1, 2, 3 }, + }, + }, + }, + ViewInfo = OperatorInfo { Pos = { 500, 50 } }, + }, + }, +}"#; + Comp::from_fusion_str(src).expect("parse sample comp") + } + + #[test] + fn add_node_naming_and_tool_defaults() { + let mut comp = sample_comp(); + let rev0 = comp.revision; + + let t1 = comp.add_node("Transform", None, [120.0, 200.0]); + let t2 = comp.add_node("Transform", None, [240.0, 200.0]); + assert_eq!(comp.node(t1).name, "Transform1"); + assert_eq!(comp.node(t2).name, "Transform2"); + assert_eq!(comp.node(t1).pos, [120.0, 200.0]); + assert!(comp.revision >= rev0 + 2); + + let h0 = comp.add_node("Background", Some("HeroBG"), [0.0, 0.0]); + let h1 = comp.add_node("Background", Some("HeroBG"), [50.0, 0.0]); + let h2 = comp.add_node("Background", Some("HeroBG"), [100.0, 0.0]); + assert_eq!(comp.node(h0).name, "HeroBG"); + assert_eq!(comp.node(h1).name, "HeroBG_1"); + assert_eq!(comp.node(h2).name, "HeroBG_2"); + + // Cover all common Fusion 21.1 tool categories + generic fallback + let kinds = [ + "Background", + "Merge", + "Transform", + "Blur", + "Glow", + "SoftGlow", + "BrightnessContrast", + "ColorCorrector", + "ColorGain", + "RectangleMask", + "EllipseMask", + "PolylineMask", + "BitmapMask", + "TextPlus", + "Loader", + "Saver", + "Displace", + "FastNoise", + "PipeRouter", + "Switch", + "TimeStretcher", + "TimeSpeed", + "Renderer3D", + "Camera3D", + "Merge3D", + "Transform3D", + "ImagePlane3D", + "Shape3D", + "Note", + "Underlay", + "MyCustomThirdPartyTool", + ]; + for (i, kind) in kinds.iter().enumerate() { + let id = comp.add_node(kind, None, [i as f32 * 50.0, 400.0]); + assert_eq!(comp.node(id).kind, *kind); + assert!(comp.node(id).raw.get_table("ViewInfo").is_some()); + } + + // Roundtrip all newly created nodes cleanly + let s = comp.to_fusion_string(); + let reloaded = Comp::from_fusion_str(&s).expect("roundtrip added nodes"); + assert_eq!(reloaded.nodes.len(), comp.nodes.len()); + assert_eq!( + reloaded.node(reloaded.find_node("HeroBG").unwrap()).static_number("Width"), + Some(1920.0) + ); + } + + #[test] + fn connect_cycle_detection_disconnect_and_splice() { + let mut comp = sample_comp(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + let st = comp.find_node("SurfaceTracker1").unwrap(); + + // Self-loop rejected + assert!(comp.connect_output(bg, "Output", bg, "EffectMask").is_err()); + // Direct cycle BG1 -> BC1 -> BG1 rejected + assert!(comp.connect_output(bc, "Output", bg, "EffectMask").is_err()); + // Transitive cycle BG1 -> BC1 -> SurfaceTracker1 -> BG1 rejected + assert!(comp.connect_output(st, "Output", bg, "EffectMask").is_err()); + + // Splice a Blur into BG1 -> BC1.Input + let blur = comp.add_node("Blur", None, [200.0, 50.0]); + comp.splice_node_into_pipe(blur, bg, bc, "Input") + .expect("splice blur"); + assert_eq!(comp.node(blur).connected_node("Input"), Some("BG1")); + assert_eq!(comp.node(bc).connected_node("Input"), Some("Blur1")); + + // Disconnect returns true once, then false + assert!(comp.disconnect(bc, "Input")); + assert!(!comp.disconnect(bc, "Input")); + assert_eq!(comp.node(bc).connected_node("Input"), None); + + // Reconnect and verify roundtrip + comp.connect_output(blur, "Output", bc, "Input") + .expect("reconnect"); + let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip"); + assert_eq!( + reloaded.node(reloaded.find_node("BC1").unwrap()).connected_node("Input"), + Some("Blur1") + ); + } + + #[test] + fn params_expressions_passthrough_pos_and_keyframes() { + let mut comp = sample_comp(); + let bc = comp.find_node("BC1").unwrap(); + + assert!(comp.set_input_value(bc, "Gamma", ParamValue::Number(1.45))); + assert!(comp.set_input_expression(bc, "Brightness", Some("time * 0.01".to_owned()))); + assert!(comp.toggle_passthrough(bc)); + comp.set_node_pos(bc, [333.0, 77.0]); + + // Set keyframe on static input -> creates new BezierSpline and wires it + let sp_name = comp.set_keyframe(bc, "Contrast", 0.0, 0.2).expect("kf 0"); + assert_eq!(sp_name, "BC1Contrast"); + let sp_name2 = comp.set_keyframe(bc, "Contrast", 20.0, 0.8).expect("kf 20"); + assert_eq!(sp_name2, sp_name); + // Update existing keyframe at frame 20 + comp.set_keyframe(bc, "Contrast", 20.0, 0.9).expect("update kf 20"); + assert_eq!(comp.splines[&sp_name].keyframes.len(), 2); + + // Evaluate via Comp::eval_number + let expr = ExprEngine::new(); + let val_mid = comp.eval_number(comp.node(bc), "Contrast", 10.0, 0.0, &expr); + assert!((val_mid - 0.55).abs() < 1e-5, "got {val_mid}"); + + // Delete keyframe + assert!(comp.delete_keyframe(&sp_name, 20.0)); + assert!(!comp.delete_keyframe(&sp_name, 20.0)); + assert_eq!(comp.splines[&sp_name].keyframes.len(), 1); + + // Roundtrip + let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip"); + let r_bc = reloaded.node(reloaded.find_node("BC1").unwrap()); + assert!(r_bc.bypassed); + assert_eq!(r_bc.pos, [333.0, 77.0]); + assert_eq!(r_bc.static_number("Gamma"), Some(1.45)); + assert_eq!( + r_bc.inputs.get("Brightness").and_then(|b| b.expression.as_deref()), + Some("time * 0.01") + ); + assert_eq!(r_bc.connected_node("Contrast"), Some("BC1Contrast")); + assert_eq!(reloaded.splines["BC1Contrast"].keyframes.len(), 1); + + // Clear expression and un-bypass + assert!(comp.set_input_expression(bc, "Brightness", None)); + assert!(!comp.toggle_passthrough(bc)); + let reloaded2 = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip 2"); + let r_bc2 = reloaded2.node(reloaded2.find_node("BC1").unwrap()); + assert!(!r_bc2.bypassed); + assert_eq!( + r_bc2.inputs.get("Brightness").and_then(|b| b.expression.as_deref()), + None + ); + } + + #[test] + fn rename_duplicate_and_delete_nodes_roundtrip() { + let mut comp = sample_comp(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + + // Rename validation + assert!(comp.rename_node(bg, "").is_err()); + assert!(comp.rename_node(bg, "123Bad").is_err()); + assert!(comp.rename_node(bg, "function").is_err()); + assert!(comp.rename_node(bg, "BC1").is_err()); + + // Rename BG1 -> PlateBG and verify BC1.Input SourceOp is rewritten + let new_name = comp.rename_node(bg, "PlateBG").expect("rename BG1"); + assert_eq!(new_name, "PlateBG"); + assert!(comp.find_node("BG1").is_none()); + assert_eq!(comp.find_node("PlateBG"), Some(bg)); + assert_eq!(comp.node(bc).connected_node("Input"), Some("PlateBG")); + + // Duplicate [PlateBG, BC1] together -> internal wire preserved, BC1Gain spline cloned + let dups = comp.duplicate_nodes(&[bg, bc], [0.0, 150.0]); + assert_eq!(dups.len(), 2); + let dup_bg = dups[0]; + let dup_bc = dups[1]; + assert_eq!(comp.node(dup_bg).name, "PlateBG_1"); + assert_eq!(comp.node(dup_bc).name, "BC1_1"); + assert_eq!(comp.node(dup_bg).pos, [100.0, 200.0]); + assert_eq!(comp.node(dup_bc).connected_node("Input"), Some("PlateBG_1")); + let dup_gain_spline = comp.node(dup_bc).connected_node("Gain").unwrap().to_owned(); + assert_ne!(dup_gain_spline, "BC1Gain"); + assert!(comp.splines.contains_key(&dup_gain_spline)); + + // Share BC1Gain with dup_bg (artificial) vs exclusive spline on dup_bc: + // Deleting dup_bc should prune `dup_gain_spline` while leaving `BC1Gain` intact. + let deleted = comp.delete_nodes(&[dup_bc]); + assert_eq!(deleted, vec!["BC1_1".to_owned()]); + assert!(!comp.splines.contains_key(&dup_gain_spline)); + assert!(comp.splines.contains_key("BC1Gain")); + + // Delete BC1 -> SurfaceTracker1.Source unwired, BC1Gain pruned, NodeId indices compact + let bc_now = comp.find_node("BC1").unwrap(); + let del2 = comp.delete_nodes(&[bc_now]); + assert_eq!(del2, vec!["BC1".to_owned()]); + assert!(!comp.splines.contains_key("BC1Gain")); + for (idx, n) in comp.nodes.iter().enumerate() { + assert_eq!(n.id, NodeId(idx)); + assert_eq!(comp.find_node(&n.name), Some(NodeId(idx))); + } + let st_now = comp.find_node("SurfaceTracker1").unwrap(); + assert_eq!(comp.node(st_now).connected_node("Source"), None); + + // Full roundtrip preserves unknown SurfaceTracker1 verbatim + all structural mutations + let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip"); + assert!(reloaded.find_node("PlateBG").is_some()); + assert!(reloaded.find_node("PlateBG_1").is_some()); + assert!(reloaded.find_node("BC1").is_none()); + assert!(reloaded.find_node("SurfaceTracker1").is_some()); + assert!(!reloaded.splines.contains_key("BC1Gain")); + let r_st = reloaded.node(reloaded.find_node("SurfaceTracker1").unwrap()); + assert_eq!(r_st.connected_node("Source"), None); + assert!( + r_st.raw + .get_table("Inputs") + .and_then(|i| i.get_table("MeshBlob")) + .is_some() + ); + } + + #[test] + fn roundtrip_mutations_on_real_20_falling_comp() { + let path = Path::new("/Volumes/Project/trees/fusion/20_falling.comp"); + if !path.exists() { + return; + } + let mut comp = Comp::from_fusion_file(path).expect("load 20_falling.comp"); + let orig_count = comp.nodes.len(); + + let blur = comp.add_node("Blur", Some("TestGlowBlur"), [1000.0, -500.0]); + let merge19 = comp.find_node("Merge19").expect("Merge19"); + comp.set_input_value(blur, "XBlurSize", ParamValue::Number(4.5)); + comp.set_input_expression(blur, "YBlurSize", Some("XBlurSize * 2".to_owned())); + comp.toggle_passthrough(blur); + let sp = comp + .set_keyframe(blur, "Blend", 2200.0, 0.5) + .expect("keyframe blend"); + comp.set_keyframe(blur, "Blend", 2250.0, 1.0) + .expect("keyframe blend 2"); + comp.connect_output(merge19, "Output", blur, "Input") + .expect("connect Merge19 -> blur"); + comp.rename_node(blur, "TestGlowBlurRenamed") + .expect("rename blur"); + + let serialized = comp.to_fusion_string(); + let reloaded = Comp::from_fusion_str(&serialized).expect("re-parse mutated 20_falling"); + assert_eq!(reloaded.nodes.len(), orig_count + 1); + let r_blur_id = reloaded + .find_node("TestGlowBlurRenamed") + .expect("TestGlowBlurRenamed"); + let r_blur = reloaded.node(r_blur_id); + assert!(r_blur.bypassed); + assert_eq!(r_blur.connected_node("Input"), Some("Merge19")); + assert_eq!(r_blur.static_number("XBlurSize"), Some(4.5)); + assert_eq!( + r_blur.inputs.get("YBlurSize").and_then(|b| b.expression.as_deref()), + Some("XBlurSize * 2") + ); + assert_eq!(reloaded.splines[&sp].keyframes.len(), 2); + } + + pub(super) const GROUP_SNIPPET: &str = r#"{ + Tools = ordered() { + Group1 = GroupOperator { + Inputs = { + Input1 = InstanceInput { SourceOp = "Inner1", Source = "Input", }, + }, + Outputs = { + Output1 = InstanceOutput { SourceOp = "Inner1", Source = "Output", }, + }, + ViewInfo = GroupInfo { Pos = { 10, 20 } }, + Tools = ordered() { + Inner1 = Blur { + Inputs = { + XBlurSize = Input { SourceOp = "Inner1Size", Source = "Value", }, + }, + ViewInfo = OperatorInfo { Pos = { 0, 0 } }, + }, + Inner1Size = BezierSpline { + KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, + }, + }, + }, + }, +}"#; -- 2.54.1