authoravatarclover caruso<git@paperclover.net>2026-11-30 20:43:45-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 20:54:09-08:00
logebca4bd9b78139ca1e7cfd89ee7bf1b99629d8b2
treeab73363bc86308b91a27129cb915dc5795f4eadf
parent9c00057b07397a81c13f866dbc14fb0ae0d1399a
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Split model/comp.rs and model/edit.rs into focused submodules


12 files changed, 5066 insertions(+), 4974 deletions(-)

crates/model/src/comp.rs+19-3171
...@@ -1,11 +1,21 @@...@@ -1,11 +1,21 @@
1//! Core composition IR, Fusion `.comp` importer, parameter evaluation, and graph editing.1//! Core composition IR, Fusion `.comp` importer, parameter evaluation, and graph editing.
22
3use crate::expr::ExprEngine;3mod eval;
4use crate::lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua};4mod load;
5use crate::spline::{BezierSpline, Gradient, PolyPath, read_vec2};5mod math;
6use std::collections::{HashMap, HashSet, VecDeque};6mod save;
7#[cfg(test)]
8mod tests;
9
10pub use math::{GridMesh, MeshPoint};
11pub(crate) use math::{find_raw_tool, find_raw_tool_mut};
12pub(crate) use save::{ensure_table_mut, is_group_kind, param_value_to_lua, vec2_lua};
13
14use crate::lua_value::{LuaTable, LuaValue};
15use crate::spline::{BezierSpline, Gradient, PolyPath};
16use std::collections::{HashMap, HashSet};
7use std::path::{Path, PathBuf};17use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicU64, Ordering};18use std::sync::atomic::AtomicU64;
919
10/// Fusion working color bit depth (`DepthFull` / `ChangeDepth.Depth` / generator `Depth`).20/// Fusion working color bit depth (`DepthFull` / `ChangeDepth.Depth` / generator `Depth`).
11/// Fusion enum: `0 = Default`, `1 = int8`, `2 = int16`, `3 = float16`, `4 = float32`.21/// Fusion enum: `0 = Default`, `1 = int8`, `2 = int16`, `3 = float16`, `4 = float32`.
...@@ -452,522 +462,18 @@ const MODIFIER_TYPES: &[&str] = &[...@@ -452,522 +462,18 @@ const MODIFIER_TYPES: &[&str] = &[
452];462];
453463
454/// Each loaded comp gets its own revision range so frame-cache keys never collide across reloads.464/// Each loaded comp gets its own revision range so frame-cache keys never collide across reloads.
455static NEXT_COMP_REVISION: AtomicU64 = AtomicU64::new(1);465pub(super) static NEXT_COMP_REVISION: AtomicU64 = AtomicU64::new(1);
456const REVISION_STRIDE: u64 = 1 << 32;466pub(super) const REVISION_STRIDE: u64 = 1 << 32;
457467
458/// Max hops through chained expression modifiers / `Node.Param` references before evaluation gives up.468/// Max hops through chained expression modifiers / `Node.Param` references before evaluation gives up.
459const MAX_EXPR_DEPTH: usize = 16;469pub(super) const MAX_EXPR_DEPTH: usize = 16;
460470
461pub(crate) fn is_modifier_type(kind: &str) -> bool {471pub(crate) fn is_modifier_type(kind: &str) -> bool {
462 MODIFIER_TYPES.contains(&kind) || kind.ends_with("Spline") || kind.ends_with("Modifier")472 MODIFIER_TYPES.contains(&kind) || kind.ends_with("Spline") || kind.ends_with("Modifier")
463}473}
464474
465impl Comp {
466 pub fn from_fusion_file(path: impl AsRef<Path>) -> Result<Self, Box<dyn std::error::Error>> {
467 let path = path.as_ref();
468 let bytes = std::fs::read(path)?;
469 let text = String::from_utf8_lossy(&bytes);
470 let mut comp = Self::from_fusion_str(&text)?;
471 comp.path = Some(path.to_path_buf());
472 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
473 comp.name = stem.to_owned();
474 }
475 Ok(comp)
476 }
477
478 pub fn from_fusion_str(text: &str) -> Result<Self, ParseError> {
479 let root_val = parse_lua(text)?;
480 let root = root_val
481 .as_table()
482 .ok_or_else(|| ParseError { offset: 0, line: 1, message: "comp root is not a table".into() })?;
483
484 let current_time = root.get_f64("CurrentTime").unwrap_or(0.0);
485 let global_range = root
486 .get_table("GlobalRange")
487 .and_then(read_vec2)
488 .map(|[a, b]| [a as i64, b as i64])
489 .unwrap_or([0, 1000]);
490 let render_range = root
491 .get_table("RenderRange")
492 .and_then(read_vec2)
493 .map(|[a, b]| [a as i64, b as i64])
494 .unwrap_or(global_range);
495 let audio_filename = root.get_str("AudioFilename").map(str::to_owned);
496 let audio_offset = root.get_f64("AudioOffset").unwrap_or(0.0);
497
498 // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps, Int8)
499 let mut width = 1920u32;
500 let mut height = 1080u32;
501 let mut fps = 30.0_f64;
502 let mut depth_full = BitDepth::Int8;
503 let mut explicit_size = false;
504 if let Some(ff) = root
505 .get_table("Prefs")
506 .and_then(|p| p.get_table("Comp"))
507 .and_then(|c| c.get_table("FrameFormat"))
508 {
509 if let Some(w) = ff.get_f64("Width") {
510 width = w.round().max(1.0) as u32;
511 explicit_size = true;
512 }
513 if let Some(h) = ff.get_f64("Height") {
514 height = h.round().max(1.0) as u32;
515 explicit_size = true;
516 }
517 if let Some(r) = ff.get_f64("Rate") {
518 if r > 0.0 {
519 fps = r;
520 }
521 }
522 if let Some(d) = ff.get_f64("DepthFull").and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) {
523 depth_full = d;
524 }
525 }
526
527 let mut nodes = Vec::new();
528 let mut node_by_name = HashMap::new();
529 let mut splines = HashMap::new();
530 let mut poly_paths = HashMap::new();
531 let mut gradient_modifiers = HashMap::new();
532 let mut text_modifiers = HashMap::new();
533 let mut text_splines = HashMap::new();
534 let mut polyline_splines = HashMap::new();
535 let mut text_cls = HashMap::new();
536 let mut shakes = HashMap::new();
537 let mut expression_modifiers = HashMap::new();
538 let mut tracker_aliases: Vec<(String, String)> = Vec::new();
539 let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new();
540 let mut instanced_from: Vec<(NodeId, String)> = Vec::new();
541
542 if let Some(tools) = root.get_table("Tools") {
543 parse_tools_table(
544 tools,
545 false,
546 &mut nodes,
547 &mut node_by_name,
548 &mut splines,
549 &mut poly_paths,
550 &mut gradient_modifiers,
551 &mut text_modifiers,
552 &mut text_splines,
553 &mut polyline_splines,
554 &mut text_cls,
555 &mut shakes,
556 &mut expression_modifiers,
557 &mut tracker_aliases,
558 &mut macro_defaults,
559 &mut instanced_from,
560 );
561 }
562
563 // Resolve TrackerModifier aliases (e.g. `Track1` -> `Track1TrackerPath`) into `poly_paths`
564 for (tracker_name, src_path) in tracker_aliases {
565 if let Some(pp) = poly_paths.get(&src_path).cloned() {
566 poly_paths.insert(tracker_name, pp);
567 }
568 }
569
570 // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools.
571 for (target_op, target_param, val) in macro_defaults {
572 if let Some(&nid) = node_by_name.get(&target_op) {
573 let entry = nodes[nid.0].inputs.entry(target_param).or_insert(InputBinding {
574 value: None,
575 source_op: None,
576 source_output: None,
577 expression: None,
578 });
579 if entry.value.is_none() && entry.source_op.is_none() && entry.expression.is_none() {
580 entry.value = Some(val);
581 }
582 }
583 }
584
585 // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets
586 // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`.
587 let node_inputs_snapshot: Vec<(String, HashMap<String, InputBinding>)> = nodes
588 .iter()
589 .map(|n| (n.name.clone(), n.inputs.clone()))
590 .collect();
591 let snap_map: HashMap<String, HashMap<String, InputBinding>> = node_inputs_snapshot.into_iter().collect();
592 for n in &mut nodes {
593 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
594 let mut flow_wires = HashMap::new();
595 for (in_name, b) in &n.inputs {
596 if let (Some(inner_op), Some(inner_port)) = (&b.source_op, &b.source_output) {
597 if let Some(inner_in) = snap_map.get(inner_op).and_then(|m| m.get(inner_port)) {
598 if let Some(ext_src) = &inner_in.source_op {
599 // Only connect if ext_src is a visible (non-internal) flow node
600 if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) {
601 let port_name = if in_name.starts_with("MainInput") || in_name == "Input" {
602 "Input".to_owned()
603 } else {
604 in_name.clone()
605 };
606 flow_wires.insert(
607 port_name,
608 InputBinding {
609 value: None,
610 source_op: Some(ext_src.clone()),
611 source_output: inner_in.source_output.clone(),
612 expression: None,
613 },
614 );
615 }
616 }
617 }
618 }
619 }
620 if !flow_wires.is_empty() {
621 n.inputs = flow_wires;
622 }
623 }
624 }
625
626 // Resolve Fusion tool-level `SourceOp` instanced node inheritance
627 // (e.g. `Instance_ColorCorrector1_6 = ColorCorrector { SourceOp = "ColorCorrector1_6" }`),
628 // walking chains up to depth 8 (cycle-safe) while NEVER copying image/mask/scene wires.
629 if !instanced_from.is_empty() {
630 let parent_of: HashMap<NodeId, NodeId> = instanced_from
631 .iter()
632 .filter_map(|(nid, master_name)| {
633 node_by_name
634 .get(master_name)
635 .copied()
636 .filter(|&mid| mid != *nid)
637 .map(|mid| (*nid, mid))
638 })
639 .collect();
640 let orig_inputs: Vec<HashMap<String, InputBinding>> =
641 nodes.iter().map(|n| n.inputs.clone()).collect();
642
643 for &(nid, _) in &instanced_from {
644 let mut visited = HashSet::new();
645 visited.insert(nid);
646 let mut blocked: HashSet<String> = HashSet::new();
647 let mut cur = nid;
648 for _depth in 0..8 {
649 let Some(&pid) = parent_of.get(&cur) else {
650 break;
651 };
652 if !visited.insert(pid) {
653 break;
654 }
655 let inst_inputs = &mut nodes[nid.0].inputs;
656 for (inp_name, parent_binding) in &orig_inputs[pid.0] {
657 if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name)
658 {
659 continue;
660 }
661 if blocked.contains(inp_name) {
662 continue;
663 }
664 if parent_binding.value.is_none()
665 && parent_binding.source_op.is_none()
666 && parent_binding.expression.is_none()
667 {
668 // An empty `Param = Input {}` on an ancestor marks a de-instanced
669 // override to default and stops further inheritance up the chain.
670 blocked.insert(inp_name.clone());
671 continue;
672 }
673 if !inst_inputs.contains_key(inp_name) {
674 inst_inputs.insert(inp_name.clone(), parent_binding.clone());
675 }
676 }
677 cur = pid;
678 }
679 }
680 }
681
682 // Apply cyclic [0..6] endpoint continuity on LUTBezier splines attached to HueCurves nodes.
683 const HUE_CURVE_PORTS: &[&str] = &[
684 "Hue",
685 "Sat",
686 "Lum",
687 "Red",
688 "Green",
689 "Blue",
690 "RedSuppress",
691 "GreenSuppress",
692 "BlueSuppress",
693 ];
694 let mut hue_spline_names: HashSet<String> = HashSet::new();
695 for n in &nodes {
696 if n.kind == "HueCurves" {
697 for &port in HUE_CURVE_PORTS {
698 if let Some(sp_name) = n.connected_node(port) {
699 hue_spline_names.insert(sp_name.to_owned());
700 }
701 }
702 }
703 }
704 for sp_name in hue_spline_names {
705 if let Some(sp) = splines.get_mut(&sp_name) {
706 sp.apply_hue_curves_cyclic_ends();
707 }
708 }
709
710 // Infer comp dimensions from first Background/TextPlus if Prefs omitted Width/Height
711 if !explicit_size {
712 for n in &nodes {
713 if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") {
714 if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) {
715 if w >= 64.0 && h >= 64.0 {
716 width = w as u32;
717 height = h as u32;
718 break;
719 }
720 }
721 }
722 }
723 }
724
725 Ok(Self {
726 path: None,
727 name: "Untitled".to_owned(),
728 width,
729 height,
730 fps,
731 depth_full,
732 current_time,
733 global_range,
734 render_range,
735 audio_filename,
736 audio_offset,
737 nodes,
738 node_by_name,
739 splines,
740 poly_paths,
741 gradient_modifiers,
742 text_modifiers,
743 text_splines,
744 polyline_splines,
745 text_cls,
746 shakes,
747 expression_modifiers,
748 raw_root: Some(root.clone()),
749 revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed),
750 })
751 }
752
753 /// Evaluates an animated `Polyline` spline (`BezierSpline` whose keyframes carry `Value = Polyline { ... }`).
754 pub fn eval_polyline_spline(&self, name: &str, time: f64) -> Option<Vec<crate::spline::PolyPoint>> {
755 let (spline, kfs) = self.polyline_splines.get(name)?;
756 if kfs.is_empty() {
757 return None;
758 }
759 if kfs.len() == 1 || time <= kfs[0].0 {
760 return Some(kfs[0].1.clone());
761 }
762 if time >= kfs[kfs.len() - 1].0 {
763 return Some(kfs[kfs.len() - 1].1.clone());
764 }
765 // Fusion stores keyframe index (0, 1, 2, ...) as the spline scalar value for eased shape morphing.
766 let u = spline.eval(time).clamp(0.0, (kfs.len() - 1) as f64);
767 let idx = (u.floor() as usize).min(kfs.len() - 2);
768 let frac = (u - idx as f64).clamp(0.0, 1.0);
769 let a = &kfs[idx].1;
770 let b = &kfs[idx + 1].1;
771 if a.len() != b.len() || frac <= 1e-6 {
772 return Some(a.clone());
773 }
774 if frac >= 1.0 - 1e-6 {
775 return Some(b.clone());
776 }
777 let lerp = |x: f64, y: f64| x + (y - x) * frac;
778 Some(
779 a.iter()
780 .zip(b.iter())
781 .map(|(pa, pb)| crate::spline::PolyPoint {
782 x: lerp(pa.x, pb.x),
783 y: lerp(pa.y, pb.y),
784 lx: lerp(pa.lx, pb.lx),
785 ly: lerp(pa.ly, pb.ly),
786 rx: lerp(pa.rx, pb.rx),
787 ry: lerp(pa.ry, pb.ry),
788 linear: pa.linear && pb.linear,
789 })
790 .collect(),
791 )
792 }
793}
794
795#[derive(Clone, Debug, PartialEq)]
796pub struct MeshPoint {
797 pub x: f64,
798 pub y: f64,
799 pub l_cx: Option<f64>,
800 pub l_cy: Option<f64>,
801 pub r_cx: Option<f64>,
802 pub r_cy: Option<f64>,
803 pub t_cx: Option<f64>,
804 pub t_cy: Option<f64>,
805 pub b_cx: Option<f64>,
806 pub b_cy: Option<f64>,
807}
808
809#[derive(Clone, Debug, PartialEq)]
810pub struct GridMesh {
811 pub cols: usize,
812 pub rows: usize,
813 pub delta_r: f64,
814 pub delta_c: f64,
815 pub points: Vec<MeshPoint>,
816}
817
818impl GridMesh {
819 fn from_lua_table(tbl: &LuaTable) -> Option<Self> {
820 if tbl.tag.as_deref() != Some("Mesh") {
821 return None;
822 }
823 let cols = tbl.get_f64("Col")?.round().max(2.0) as usize;
824 let pts_tbl = tbl.get_table("Points")?;
825 let mut points = Vec::new();
826 for pval in pts_tbl.positional_values() {
827 let pt = pval.as_table()?;
828 points.push(MeshPoint {
829 x: pt.get_f64("X").unwrap_or(0.0),
830 y: pt.get_f64("Y").unwrap_or(0.0),
831 l_cx: pt.get_f64("L_CX"),
832 l_cy: pt.get_f64("L_CY"),
833 r_cx: pt.get_f64("R_CX"),
834 r_cy: pt.get_f64("R_CY"),
835 t_cx: pt.get_f64("T_CX"),
836 t_cy: pt.get_f64("T_CY"),
837 b_cx: pt.get_f64("B_CX"),
838 b_cy: pt.get_f64("B_CY"),
839 });
840 }
841 if points.len() < cols * 2 {
842 return None;
843 }
844 let rows = points.len() / cols;
845 if rows < 2 || rows * cols != points.len() {
846 return None;
847 }
848 let delta_c = tbl.get_f64("DeltaC").unwrap_or(1.0 / (cols - 1) as f64);
849 let delta_r = tbl.get_f64("DeltaR").unwrap_or(1.0 / (rows - 1) as f64);
850 Some(Self {
851 cols,
852 rows,
853 delta_r,
854 delta_c,
855 points,
856 })
857 }
858
859 fn lerp(&self, other: &Self, frac: f64) -> Self {
860 if self.cols != other.cols || self.rows != other.rows || self.points.len() != other.points.len() {
861 return self.clone();
862 }
863 let f = frac.clamp(0.0, 1.0);
864 let lerp_num = |a: f64, b: f64| a + (b - a) * f;
865 let lerp_opt = |a: Option<f64>, b: Option<f64>| match (a, b) {
866 (Some(x), Some(y)) => Some(lerp_num(x, y)),
867 (Some(x), None) => Some(x),
868 (None, Some(y)) => Some(y),
869 (None, None) => None,
870 };
871 let points = self
872 .points
873 .iter()
874 .zip(other.points.iter())
875 .map(|(a, b)| MeshPoint {
876 x: lerp_num(a.x, b.x),
877 y: lerp_num(a.y, b.y),
878 l_cx: lerp_opt(a.l_cx, b.l_cx),
879 l_cy: lerp_opt(a.l_cy, b.l_cy),
880 r_cx: lerp_opt(a.r_cx, b.r_cx),
881 r_cy: lerp_opt(a.r_cy, b.r_cy),
882 t_cx: lerp_opt(a.t_cx, b.t_cx),
883 t_cy: lerp_opt(a.t_cy, b.t_cy),
884 b_cx: lerp_opt(a.b_cx, b.b_cx),
885 b_cy: lerp_opt(a.b_cy, b.b_cy),
886 })
887 .collect();
888 Self {
889 cols: self.cols,
890 rows: self.rows,
891 delta_r: lerp_num(self.delta_r, other.delta_r),
892 delta_c: lerp_num(self.delta_c, other.delta_c),
893 points,
894 }
895 }
896}
897
898/// Finds a tool/modifier by name in `tools` or any nested `Tools` table (Groups, Macros, curve nodes).
899pub(crate) fn find_raw_tool<'a>(tools: &'a LuaTable, target: &str) -> Option<&'a LuaTable> {
900 if let Some(t) = tools.get_table(target) {
901 return Some(t);
902 }
903 tools
904 .entries
905 .iter()
906 .filter_map(|(_, v)| v.as_table()?.get_table("Tools"))
907 .find_map(|inner| find_raw_tool(inner, target))
908}
909
910pub(crate) fn find_raw_tool_mut<'a>(tools: &'a mut LuaTable, target: &str) -> Option<&'a mut LuaTable> {
911 if tools.get_table(target).is_some() {
912 return tools.get_table_mut(target);
913 }
914 tools
915 .entries
916 .iter_mut()
917 .filter_map(|(_, v)| v.as_table_mut()?.get_table_mut("Tools"))
918 .find_map(|inner| find_raw_tool_mut(inner, target))
919}
920475
921impl Comp {476impl Comp {
922 /// Evaluates a `GridWarp` `Mesh` input (static `Mesh { ... }` or animated `BezierSpline` of `Mesh`es).
923 pub fn eval_grid_mesh(&self, node: &Node, key: &str, time: f64) -> Option<GridMesh> {
924 if let Some(spline_name) = node.inputs.get(key).and_then(|b| b.source_op.as_deref()) {
925 let tools = self.raw_root.as_ref()?.get_table("Tools")?;
926 let stbl = find_raw_tool(tools, spline_name)?;
927 let kfs_tbl = stbl.get_table("KeyFrames")?;
928 let mut kfs: Vec<(f64, GridMesh)> = Vec::new();
929 for (k, v) in &kfs_tbl.entries {
930 let t = match k {
931 LuaKey::Index(i) => *i as f64,
932 LuaKey::Number(n) => *n,
933 _ => continue,
934 };
935 if let Some(m) = v.as_table().and_then(|kt| kt.get_table("Value")).and_then(GridMesh::from_lua_table) {
936 kfs.push((t, m));
937 }
938 }
939 if !kfs.is_empty() {
940 kfs.sort_by(|a, b| a.0.total_cmp(&b.0));
941 if kfs.len() == 1 || time <= kfs[0].0 {
942 return Some(kfs[0].1.clone());
943 }
944 if time >= kfs[kfs.len() - 1].0 {
945 return Some(kfs[kfs.len() - 1].1.clone());
946 }
947 let u = self
948 .splines
949 .get(spline_name)
950 .map(|sp| sp.eval(time))
951 .unwrap_or(0.0)
952 .clamp(0.0, (kfs.len() - 1) as f64);
953 let idx = (u.floor() as usize).min(kfs.len() - 2);
954 let frac = (u - idx as f64).clamp(0.0, 1.0);
955 if frac <= 1e-6 {
956 return Some(kfs[idx].1.clone());
957 }
958 if frac >= 1.0 - 1e-6 {
959 return Some(kfs[idx + 1].1.clone());
960 }
961 return Some(kfs[idx].1.lerp(&kfs[idx + 1].1, frac));
962 }
963 }
964 node.raw
965 .get_table("Inputs")?
966 .get_table(key)?
967 .get_table("Value")
968 .and_then(GridMesh::from_lua_table)
969 }
970
971 pub fn node(&self, id: NodeId) -> &Node {477 pub fn node(&self, id: NodeId) -> &Node {
972 &self.nodes[id.0]478 &self.nodes[id.0]
973 }479 }
...@@ -1036,681 +542,6 @@ impl Comp {...@@ -1036,681 +542,6 @@ impl Comp {
1036 out542 out
1037 }543 }
1038544
1039 /// Evaluates a numeric input on `node` at continuous `time`, checking Expression -> Spline -> Static -> `default`.
1040 pub fn eval_number(
1041 &self,
1042 node: &Node,
1043 param: &str,
1044 time: f64,
1045 default: f64,
1046 expr_engine: &ExprEngine,
1047 ) -> f64 {
1048 self.eval_number_at(node, param, time, default, expr_engine, 0)
1049 }
1050
1051 fn eval_number_at(
1052 &self,
1053 node: &Node,
1054 param: &str,
1055 time: f64,
1056 default: f64,
1057 expr_engine: &ExprEngine,
1058 depth: usize,
1059 ) -> f64 {
1060 if depth >= MAX_EXPR_DEPTH {
1061 return default;
1062 }
1063 let Some(binding) = node.inputs.get(param) else {
1064 return default;
1065 };
1066 if let Some(expr) = &binding.expression {
1067 if let Some(v) = self.eval_expr_number(node, expr, time, expr_engine) {
1068 if v.is_finite() {
1069 return v;
1070 }
1071 }
1072 }
1073 if let Some(src) = &binding.source_op {
1074 if let Some(sp) = self.splines.get(src) {
1075 return sp.eval(time);
1076 }
1077 if let Some(sh) = self.shakes.get(src) {
1078 let axis = match binding.source_output.as_deref() {
1079 Some("Y") => 1,
1080 _ => 0,
1081 };
1082 return self.eval_shake_axis(sh, axis, time, expr_engine);
1083 }
1084 if let Some(em) = self.expression_modifiers.get(src) {
1085 if let Some(v) = self.eval_expr_mod_number(
1086 em,
1087 binding.source_output.as_deref(),
1088 time,
1089 expr_engine,
1090 depth + 1,
1091 ) {
1092 if v.is_finite() {
1093 return v;
1094 }
1095 }
1096 }
1097 }
1098 binding
1099 .value
1100 .as_ref()
1101 .and_then(ParamValue::as_f64)
1102 .unwrap_or(default)
1103 }
1104
1105 /// Evaluates a 2D point input (`Center`, `Pivot`, etc.) on `node` at `time`.
1106 pub fn eval_point(
1107 &self,
1108 node: &Node,
1109 param: &str,
1110 time: f64,
1111 default: [f64; 2],
1112 expr_engine: &ExprEngine,
1113 ) -> [f64; 2] {
1114 self.eval_point_at(node, param, time, default, expr_engine, 0)
1115 }
1116
1117 fn eval_point_at(
1118 &self,
1119 node: &Node,
1120 param: &str,
1121 time: f64,
1122 default: [f64; 2],
1123 expr_engine: &ExprEngine,
1124 depth: usize,
1125 ) -> [f64; 2] {
1126 if depth >= MAX_EXPR_DEPTH {
1127 return default;
1128 }
1129 let Some(binding) = node.inputs.get(param) else {
1130 return default;
1131 };
1132 if let Some(expr) = &binding.expression {
1133 if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) {
1134 return p;
1135 }
1136 }
1137 if let Some(src) = &binding.source_op {
1138 if let Some(pp) = self.poly_paths.get(src) {
1139 let disp = pp
1140 .displacement_op
1141 .as_deref()
1142 .and_then(|d| self.splines.get(d))
1143 .map(|sp| sp.eval(time))
1144 .unwrap_or(pp.displacement_value);
1145 return pp.eval_center(disp);
1146 }
1147 if let Some(sh) = self.shakes.get(src) {
1148 let x = self.eval_shake_axis(sh, 0, time, expr_engine);
1149 let y = self.eval_shake_axis(sh, 1, time, expr_engine);
1150 return [x, y];
1151 }
1152 if let Some(em) = self.expression_modifiers.get(src) {
1153 if let Some(pt) = self.eval_expr_mod_point(em, time, expr_engine, depth + 1) {
1154 if pt[0].is_finite() && pt[1].is_finite() {
1155 return pt;
1156 }
1157 }
1158 }
1159 }
1160 binding
1161 .value
1162 .as_ref()
1163 .and_then(ParamValue::as_point)
1164 .unwrap_or(default)
1165 }
1166
1167 fn eval_shake_input(&self, sh: &ShakeModifier, key: &str, time: f64, default: f64, expr_engine: &ExprEngine) -> f64 {
1168 let Some(b) = sh.inputs.get(key) else {
1169 return default;
1170 };
1171 if let Some(expr) = &b.expression {
1172 let mut sp = HashMap::new();
1173 for (k, ib) in &sh.inputs {
1174 if k == key {
1175 continue;
1176 }
1177 if let Some(src) = &ib.source_op {
1178 if let Some(spl) = self.splines.get(src) {
1179 sp.insert(k.clone(), spl.eval(time));
1180 continue;
1181 }
1182 }
1183 if let Some(v) = ib.value.as_ref().and_then(ParamValue::as_f64) {
1184 sp.insert(k.clone(), v);
1185 }
1186 }
1187 if let Some(v) = expr_engine.eval_number(expr, time, &sp, &HashMap::new(), &HashMap::new()) {
1188 if v.is_finite() {
1189 return v;
1190 }
1191 }
1192 }
1193 if let Some(src) = &b.source_op {
1194 if let Some(spl) = self.splines.get(src) {
1195 return spl.eval(time);
1196 }
1197 }
1198 b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default)
1199 }
1200
1201 fn eval_shake_axis(&self, sh: &ShakeModifier, axis: u32, time: f64, expr_engine: &ExprEngine) -> f64 {
1202 let smoothness = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine).max(0.01);
1203 let seed = self.eval_shake_input(sh, "RandomSeed", time, 0.0, expr_engine).round() as i64;
1204 let lock_xy = self.eval_shake_input(sh, "LockXY", time, 1.0, expr_engine) > 0.5;
1205 let (min_v, max_v) = if axis == 0 || lock_xy {
1206 (
1207 self.eval_shake_input(sh, "XMinimum", time, 0.0, expr_engine),
1208 self.eval_shake_input(sh, "XMaximum", time, 1.0, expr_engine),
1209 )
1210 } else {
1211 (
1212 self.eval_shake_input(sh, "YMinimum", time, 0.0, expr_engine),
1213 self.eval_shake_input(sh, "YMaximum", time, 1.0, expr_engine),
1214 )
1215 };
1216 // Smooth Catmull-Rom interpolation over seeded lattice points spaced by `smoothness` frames
1217 let u = time / smoothness;
1218 let k = u.floor() as i64;
1219 let f = u - k as f64;
1220 let hash01 = |i: i64| -> f64 {
1221 let mut x = (i.wrapping_mul(0x9E37_79B9_7F4A_7C15u64 as i64)
1222 ^ seed.wrapping_mul(0xBF58_476D_1CE4_E5B9u64 as i64)
1223 ^ ((axis as i64).wrapping_mul(0x94D0_49BB_1331_11EBu64 as i64))) as u64;
1224 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
1225 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
1226 x ^= x >> 31;
1227 (x >> 11) as f64 / (1u64 << 53) as f64
1228 };
1229 let p0 = hash01(k - 1);
1230 let p1 = hash01(k);
1231 let p2 = hash01(k + 1);
1232 let p3 = hash01(k + 2);
1233 let f2 = f * f;
1234 let f3 = f2 * f;
1235 let cr = 0.5 * ((2.0 * p1)
1236 + (-p0 + p2) * f
1237 + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * f2
1238 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * f3);
1239 let t01 = cr.clamp(0.0, 1.0);
1240 min_v + (max_v - min_v) * t01
1241 }
1242
1243 fn eval_expr_mod_input_number(
1244 &self,
1245 em: &ExpressionModifier,
1246 keys: &[&str],
1247 time: f64,
1248 default: f64,
1249 expr_engine: &ExprEngine,
1250 depth: usize,
1251 ) -> f64 {
1252 let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else {
1253 return default;
1254 };
1255 if let Some(expr) = &b.expression {
1256 if let Some(v) = self.eval_modifier_inline_number(expr, time, expr_engine, depth) {
1257 if v.is_finite() {
1258 return v;
1259 }
1260 }
1261 }
1262 if let Some(src) = &b.source_op {
1263 if let Some(spl) = self.splines.get(src) {
1264 return spl.eval(time);
1265 }
1266 if let Some(sh) = self.shakes.get(src) {
1267 let axis = match b.source_output.as_deref() {
1268 Some("Y") => 1,
1269 _ => 0,
1270 };
1271 return self.eval_shake_axis(sh, axis, time, expr_engine);
1272 }
1273 if depth < MAX_EXPR_DEPTH {
1274 if let Some(sub) = self.expression_modifiers.get(src) {
1275 if let Some(v) = self.eval_expr_mod_number(
1276 sub,
1277 b.source_output.as_deref(),
1278 time,
1279 expr_engine,
1280 depth + 1,
1281 ) {
1282 if v.is_finite() {
1283 return v;
1284 }
1285 }
1286 }
1287 }
1288 }
1289 b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default)
1290 }
1291
1292 fn eval_expr_mod_input_point(
1293 &self,
1294 em: &ExpressionModifier,
1295 keys: &[&str],
1296 time: f64,
1297 default: [f64; 2],
1298 expr_engine: &ExprEngine,
1299 depth: usize,
1300 ) -> [f64; 2] {
1301 let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else {
1302 return default;
1303 };
1304 if let Some(expr) = &b.expression {
1305 let trimmed = expr.trim();
1306 // Direct `NodeName.ParamName` reference to a Point input on another flow node.
1307 if let Some((node_name, param_name)) = trimmed.split_once('.') {
1308 if !param_name.contains('.') && !param_name.contains(' ') {
1309 if let Some(nid) = self.find_node(node_name.trim()) {
1310 return self.eval_point_at(self.node(nid), param_name.trim(), time, default, expr_engine, depth + 1);
1311 }
1312 }
1313 }
1314 let (sp, spts, en) = self.collect_global_expr_env(time);
1315 if let Some(pt) = expr_engine.eval_point(trimmed, time, &sp, &spts, &en) {
1316 if pt[0].is_finite() && pt[1].is_finite() {
1317 return pt;
1318 }
1319 }
1320 }
1321 if let Some(src) = &b.source_op {
1322 if let Some(pp) = self.poly_paths.get(src) {
1323 let disp = pp
1324 .displacement_op
1325 .as_deref()
1326 .and_then(|d| self.splines.get(d))
1327 .map(|sp| sp.eval(time))
1328 .unwrap_or(pp.displacement_value);
1329 return pp.eval_center(disp);
1330 }
1331 if let Some(sh) = self.shakes.get(src) {
1332 let x = self.eval_shake_axis(sh, 0, time, expr_engine);
1333 let y = self.eval_shake_axis(sh, 1, time, expr_engine);
1334 return [x, y];
1335 }
1336 if depth < MAX_EXPR_DEPTH {
1337 if let Some(sub) = self.expression_modifiers.get(src) {
1338 if let Some(pt) = self.eval_expr_mod_point(sub, time, expr_engine, depth + 1) {
1339 if pt[0].is_finite() && pt[1].is_finite() {
1340 return pt;
1341 }
1342 }
1343 }
1344 }
1345 }
1346 b.value.as_ref().and_then(ParamValue::as_point).unwrap_or(default)
1347 }
1348
1349 fn eval_modifier_inline_number(
1350 &self,
1351 expr: &str,
1352 time: f64,
1353 expr_engine: &ExprEngine,
1354 depth: usize,
1355 ) -> Option<f64> {
1356 let trimmed = expr.trim();
1357 if let Some((node_name, param_name)) = trimmed.split_once('.') {
1358 if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') {
1359 if let Some(nid) = self.find_node(node_name.trim()) {
1360 return Some(self.eval_number_at(
1361 self.node(nid),
1362 param_name.trim(),
1363 time,
1364 0.0,
1365 expr_engine,
1366 depth + 1,
1367 ));
1368 }
1369 }
1370 }
1371 let (sp, spts, en) = self.collect_global_expr_env(time);
1372 expr_engine.eval_number(trimmed, time, &sp, &spts, &en)
1373 }
1374
1375 fn collect_global_expr_env(
1376 &self,
1377 time: f64,
1378 ) -> (
1379 HashMap<String, f64>,
1380 HashMap<String, [f64; 2]>,
1381 HashMap<String, HashMap<String, f64>>,
1382 ) {
1383 let mut env_nodes = HashMap::new();
1384 for n in &self.nodes {
1385 let mut m = HashMap::new();
1386 for (k, b) in &n.inputs {
1387 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
1388 m.insert(k.clone(), v);
1389 } else if let Some(src) = &b.source_op {
1390 if let Some(sp) = self.splines.get(src) {
1391 m.insert(k.clone(), sp.eval(time));
1392 }
1393 }
1394 }
1395 if !m.is_empty() {
1396 env_nodes.insert(n.name.clone(), m);
1397 }
1398 }
1399 (HashMap::new(), HashMap::new(), env_nodes)
1400 }
1401
1402 fn build_expr_mod_vars(
1403 &self,
1404 em: &ExpressionModifier,
1405 time: f64,
1406 expr_engine: &ExprEngine,
1407 depth: usize,
1408 ) -> (HashMap<String, f64>, HashMap<String, [f64; 2]>) {
1409 let mut vars = HashMap::with_capacity(32);
1410 let mut pts = HashMap::with_capacity(18);
1411 vars.insert("time".to_owned(), time);
1412 vars.insert("pi".to_owned(), std::f64::consts::PI);
1413 vars.insert("e".to_owned(), std::f64::consts::E);
1414
1415 for i in 1..=9 {
1416 let short = format!("n{i}");
1417 let long = format!("NumberIn{i}");
1418 let v = self.eval_expr_mod_input_number(
1419 em,
1420 &[short.as_str(), long.as_str()],
1421 time,
1422 0.0,
1423 expr_engine,
1424 depth,
1425 );
1426 vars.insert(short, v);
1427 vars.insert(long, v);
1428 }
1429 for i in 1..=9 {
1430 let short = format!("p{i}");
1431 let long = format!("PointIn{i}");
1432 let pt = self.eval_expr_mod_input_point(
1433 em,
1434 &[short.as_str(), long.as_str()],
1435 time,
1436 [0.5, 0.5],
1437 expr_engine,
1438 depth,
1439 );
1440 vars.insert(format!("p{i}x"), pt[0]);
1441 vars.insert(format!("p{i}y"), pt[1]);
1442 pts.insert(short, pt);
1443 pts.insert(long, pt);
1444 }
1445 for (k, b) in &em.inputs {
1446 if !vars.contains_key(k) {
1447 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
1448 vars.insert(k.clone(), v);
1449 }
1450 }
1451 }
1452 (vars, pts)
1453 }
1454
1455 fn eval_expr_mod_formula(
1456 &self,
1457 formula: &str,
1458 time: f64,
1459 vars: &HashMap<String, f64>,
1460 pts: &HashMap<String, [f64; 2]>,
1461 expr_engine: &ExprEngine,
1462 ) -> Option<f64> {
1463 let trimmed = formula.trim();
1464 if trimmed.is_empty() {
1465 return None;
1466 }
1467 if let Some(v) = eval_fusion_math_expr(trimmed, vars) {
1468 return Some(v);
1469 }
1470 // Fallback to Lua SimpleExpression engine for Lua-specific formulas
1471 let (_, _, en) = self.collect_global_expr_env(time);
1472 expr_engine.eval_number(trimmed, time, vars, pts, &en)
1473 }
1474
1475 fn eval_expr_mod_number(
1476 &self,
1477 em: &ExpressionModifier,
1478 source_output: Option<&str>,
1479 time: f64,
1480 expr_engine: &ExprEngine,
1481 depth: usize,
1482 ) -> Option<f64> {
1483 if depth >= MAX_EXPR_DEPTH {
1484 return None;
1485 }
1486 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
1487 let key = match source_output {
1488 Some("X") => "PointExpressionX",
1489 Some("Y") => "PointExpressionY",
1490 _ => "NumberExpression",
1491 };
1492 let formula = em
1493 .inputs
1494 .get(key)
1495 .and_then(|b| b.value.as_ref())
1496 .and_then(ParamValue::as_str)?;
1497 self.eval_expr_mod_formula(formula, time, &vars, &pts, expr_engine)
1498 }
1499
1500 fn eval_expr_mod_point(
1501 &self,
1502 em: &ExpressionModifier,
1503 time: f64,
1504 expr_engine: &ExprEngine,
1505 depth: usize,
1506 ) -> Option<[f64; 2]> {
1507 if depth >= MAX_EXPR_DEPTH {
1508 return None;
1509 }
1510 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
1511 let fx = em
1512 .inputs
1513 .get("PointExpressionX")
1514 .and_then(|b| b.value.as_ref())
1515 .and_then(ParamValue::as_str);
1516 let fy = em
1517 .inputs
1518 .get("PointExpressionY")
1519 .and_then(|b| b.value.as_ref())
1520 .and_then(ParamValue::as_str);
1521 if fx.is_some() || fy.is_some() {
1522 let x = fx
1523 .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine))
1524 .unwrap_or(0.5);
1525 let y = fy
1526 .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine))
1527 .unwrap_or(0.5);
1528 return Some([x, y]);
1529 }
1530 if let Some(fp) = em
1531 .inputs
1532 .get("PointExpression")
1533 .and_then(|b| b.value.as_ref())
1534 .and_then(ParamValue::as_str)
1535 {
1536 let (_, _, en) = self.collect_global_expr_env(time);
1537 if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) {
1538 return Some(pt);
1539 }
1540 }
1541 None
1542 }
1543
1544 pub fn eval_text(
1545 &self,
1546 node: &Node,
1547 param: &str,
1548 time: f64,
1549 default: &str,
1550 expr_engine: &ExprEngine,
1551 ) -> String {
1552 let Some(binding) = node.inputs.get(param) else {
1553 return default.to_owned();
1554 };
1555 if let Some(expr) = &binding.expression {
1556 let (sp, spts, en) = self.collect_expr_env(node, time);
1557 if let Some(s) = expr_engine.eval_string(expr, time, &sp, &spts, &en) {
1558 return s;
1559 }
1560 }
1561 if let Some(src) = &binding.source_op {
1562 if let Some(kfs) = self.text_splines.get(src) {
1563 if !kfs.is_empty() {
1564 let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1);
1565 return kfs[idx].1.clone();
1566 }
1567 }
1568 if let Some(txt) = self.text_modifiers.get(src) {
1569 return txt.clone();
1570 }
1571 }
1572 binding
1573 .value
1574 .as_ref()
1575 .and_then(ParamValue::as_str)
1576 .unwrap_or(default)
1577 .to_owned()
1578 }
1579
1580 pub fn text_cls_entries(&self, node: &Node, param: &str) -> &[ClsEntry] {
1581 node.inputs
1582 .get(param)
1583 .and_then(|b| b.source_op.as_deref())
1584 .and_then(|src| self.text_cls.get(src))
1585 .map(Vec::as_slice)
1586 .unwrap_or(&[])
1587 }
1588
1589 pub fn eval_gradient(&self, node: &Node, param: &str, time: f64) -> Option<Gradient> {
1590 let binding = node.inputs.get(param)?;
1591 if let Some(src) = &binding.source_op {
1592 if let Some(kfs) = self.gradient_modifiers.get(src) {
1593 if kfs.is_empty() {
1594 return None;
1595 }
1596 if kfs.len() == 1 || time <= kfs[0].0 {
1597 return Some(kfs[0].1.clone());
1598 }
1599 let last = &kfs[kfs.len() - 1];
1600 if time >= last.0 {
1601 return Some(last.1.clone());
1602 }
1603 let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1);
1604 let (t0, g0) = &kfs[idx];
1605 let (t1, g1) = &kfs[(idx + 1).min(kfs.len() - 1)];
1606 let f = ((time - t0) / (t1 - t0).max(1e-9)).clamp(0.0, 1.0) as f32;
1607 // Bake 17 blended stops across [0..1]
1608 let mut stops = Vec::with_capacity(17);
1609 for i in 0..=16 {
1610 let p = i as f64 / 16.0;
1611 let a = g0.sample(p);
1612 let b = g1.sample(p);
1613 stops.push(crate::spline::GradientStop {
1614 pos: p,
1615 rgba: [
1616 a[0] + (b[0] - a[0]) * f,
1617 a[1] + (b[1] - a[1]) * f,
1618 a[2] + (b[2] - a[2]) * f,
1619 a[3] + (b[3] - a[3]) * f,
1620 ],
1621 });
1622 }
1623 return Some(Gradient { stops });
1624 }
1625 }
1626 if let Some(ParamValue::Gradient(g)) = &binding.value {
1627 return Some(g.clone());
1628 }
1629 None
1630 }
1631
1632 fn collect_expr_env(
1633 &self,
1634 node: &Node,
1635 time: f64,
1636 ) -> (
1637 HashMap<String, f64>,
1638 HashMap<String, [f64; 2]>,
1639 HashMap<String, HashMap<String, f64>>,
1640 ) {
1641 let mut self_params = HashMap::new();
1642 let mut self_points = HashMap::new();
1643 for (k, b) in &node.inputs {
1644 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
1645 self_params.insert(k.clone(), v);
1646 } else if let Some(pt) = b.value.as_ref().and_then(ParamValue::as_point) {
1647 self_points.insert(k.clone(), pt);
1648 } else if let Some(src) = &b.source_op {
1649 if let Some(sp) = self.splines.get(src) {
1650 self_params.insert(k.clone(), sp.eval(time));
1651 } else if let Some(pp) = self.poly_paths.get(src) {
1652 let disp = pp
1653 .displacement_op
1654 .as_deref()
1655 .and_then(|d| self.splines.get(d))
1656 .map(|sp| sp.eval(time))
1657 .unwrap_or(pp.displacement_value);
1658 self_points.insert(k.clone(), pp.eval_center(disp));
1659 }
1660 }
1661 }
1662 let mut env_nodes = HashMap::new();
1663 for n in &self.nodes {
1664 let mut m = HashMap::new();
1665 for (k, b) in &n.inputs {
1666 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
1667 m.insert(k.clone(), v);
1668 } else if let Some(src) = &b.source_op {
1669 if let Some(sp) = self.splines.get(src) {
1670 m.insert(k.clone(), sp.eval(time));
1671 }
1672 }
1673 }
1674 if !m.is_empty() {
1675 env_nodes.insert(n.name.clone(), m);
1676 }
1677 }
1678 (self_params, self_points, env_nodes)
1679 }
1680
1681 fn eval_expr_number(
1682 &self,
1683 node: &Node,
1684 expr: &str,
1685 time: f64,
1686 expr_engine: &ExprEngine,
1687 ) -> Option<f64> {
1688 let needs_nodes = expr.contains('.')
1689 || expr.trim_start().starts_with(':')
1690 || expr
1691 .split(|c: char| !c.is_alphanumeric() && c != '_')
1692 .any(|tok| !tok.is_empty() && node.inputs.contains_key(tok));
1693 if !needs_nodes {
1694 let empty_self = HashMap::new();
1695 let empty_pts = HashMap::new();
1696 let empty_env = HashMap::new();
1697 return expr_engine.eval_number(expr, time, &empty_self, &empty_pts, &empty_env);
1698 }
1699 let (sp, spts, en) = self.collect_expr_env(node, time);
1700 expr_engine.eval_number(expr, time, &sp, &spts, &en)
1701 }
1702
1703 fn eval_expr_point(
1704 &self,
1705 node: &Node,
1706 expr: &str,
1707 time: f64,
1708 expr_engine: &ExprEngine,
1709 ) -> Option<[f64; 2]> {
1710 let (sp, spts, en) = self.collect_expr_env(node, time);
1711 expr_engine.eval_point(expr, time, &sp, &spts, &en)
1712 }
1713
1714 /// Connects `src` node's `"Output"` to `dst` node's `port` input (ignores self-loops and cycles).545 /// Connects `src` node's `"Output"` to `dst` node's `port` input (ignores self-loops and cycles).
1715 pub fn connect(&mut self, src: NodeId, dst: NodeId, port: &str) {546 pub fn connect(&mut self, src: NodeId, dst: NodeId, port: &str) {
1716 let _ = self.connect_output(src, "Output", dst, port);547 let _ = self.connect_output(src, "Output", dst, port);
...@@ -1765,674 +596,7 @@ impl Comp {...@@ -1765,674 +596,7 @@ impl Comp {
1765 }596 }
1766 out597 out
1767 }598 }
1768599}
1769 /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits,
1770 /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST,
1771 /// preserving all unknown nodes, modifiers, macros, UserControls, Clips, and metadata verbatim.
1772 pub fn sync_to_raw_ast(&self) -> LuaTable {
1773 let mut root = self.raw_root.clone().unwrap_or_else(|| LuaTable {
1774 tag: Some("Composition".to_owned()),
1775 entries: Vec::new(),
1776 });
1777
1778 root.set(
1779 LuaKey::Str("CurrentTime".to_owned()),
1780 LuaValue::Number(self.current_time),
1781 );
1782 root.set(
1783 LuaKey::Str("GlobalRange".to_owned()),
1784 vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64),
1785 );
1786 root.set(
1787 LuaKey::Str("RenderRange".to_owned()),
1788 vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64),
1789 );
1790 if let Some(ref af) = self.audio_filename {
1791 root.set(
1792 LuaKey::Str("AudioFilename".to_owned()),
1793 LuaValue::String(af.clone()),
1794 );
1795 }
1796 if self.audio_offset != 0.0 || root.get("AudioOffset").is_some() {
1797 root.set(
1798 LuaKey::Str("AudioOffset".to_owned()),
1799 LuaValue::Number(self.audio_offset),
1800 );
1801 }
1802
1803 // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull)
1804 {
1805 let prefs = ensure_table_mut(&mut root, "Prefs", None);
1806 let comp_prefs = ensure_table_mut(prefs, "Comp", None);
1807 let ff = ensure_table_mut(comp_prefs, "FrameFormat", None);
1808 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {
1809 ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64));
1810 }
1811 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {
1812 ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64));
1813 }
1814 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {
1815 ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps));
1816 }
1817 let existing_depth = ff
1818 .get_f64("DepthFull")
1819 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
1820 .unwrap_or(BitDepth::Int8);
1821 if existing_depth != self.depth_full {
1822 ff.set(
1823 LuaKey::Str("DepthFull".to_owned()),
1824 LuaValue::Number((self.depth_full as i32) as f64),
1825 );
1826 }
1827 }
1828
1829 // Sync Tools
1830 let tools = ensure_table_mut(&mut root, "Tools", Some("ordered"));
1831
1832 for node in self.nodes.iter().filter(|n| !n.internal) {
1833 if tools.get_table(&node.name).is_some() {
1834 continue;
1835 }
1836 let mut new_tbl = if node.raw.tag.is_some() {
1837 node.raw.clone()
1838 } else {
1839 LuaTable { tag: None, entries: Vec::new() }
1840 };
1841 if new_tbl.tag.is_none() {
1842 new_tbl.tag = Some(node.kind.clone());
1843 }
1844 tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl));
1845 }
1846
1847 let mut pool: HashMap<(bool, String), VecDeque<&Node>> = HashMap::new();
1848 let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new();
1849 for node in &self.nodes {
1850 pool.entry((node.internal, node.name.clone())).or_default().push_back(node);
1851 if !is_group_kind(&node.kind) {
1852 continue;
1853 }
1854 for (inner_op, inner_port, default) in instance_inputs(&node.raw) {
1855 if let Some(d) = default {
1856 instance_defaults.insert((inner_op, inner_port), d);
1857 }
1858 }
1859 }
1860 self.sync_tools_level(tools, false, &mut pool, &instance_defaults);
1861
1862 // Sync BezierSpline edits (only touch splines that actually differ from the raw AST)
1863 let mut spline_names: Vec<&String> = self.splines.keys().collect();
1864 spline_names.sort();
1865 for spline_name in spline_names {
1866 let spline = &self.splines[spline_name];
1867 if let Some(tbl) = find_raw_tool_mut(tools, spline_name) {
1868 sync_spline_table(spline_name, spline, tbl);
1869 continue;
1870 }
1871 let mut sp_tbl = LuaTable {
1872 tag: Some("BezierSpline".to_owned()),
1873 entries: Vec::new(),
1874 };
1875 sp_tbl.set(
1876 LuaKey::Str("SplineColor".to_owned()),
1877 spline_color_lua(spline.color),
1878 );
1879 sp_tbl.set(
1880 LuaKey::Str("KeyFrames".to_owned()),
1881 LuaValue::Table(build_keyframes_table(spline)),
1882 );
1883 tools.set(LuaKey::Str(spline_name.clone()), LuaValue::Table(sp_tbl));
1884 }
1885
1886 root
1887 }
1888
1889 /// Syncs one `Tools` table level: drops deleted flow nodes (never modifiers), then syncs each
1890 /// surviving node and recurses into Group/Macro operators' private `Tools`.
1891 fn sync_tools_level<'a>(
1892 &'a self,
1893 tools: &mut LuaTable,
1894 internal: bool,
1895 pool: &mut HashMap<(bool, String), VecDeque<&'a Node>>,
1896 instance_defaults: &HashMap<(&str, &str), ParamValue>,
1897 ) {
1898 tools.entries.retain(|(k, v)| {
1899 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true };
1900 is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown"))
1901 || pool.get(&(internal, name.clone())).is_some_and(|q| !q.is_empty())
1902 });
1903
1904 for (k, v) in &mut tools.entries {
1905 let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue };
1906 if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) {
1907 continue;
1908 }
1909 let Some(node) = pool.get_mut(&(internal, name.clone())).and_then(VecDeque::pop_front) else {
1910 continue;
1911 };
1912 self.sync_node_tool(node, tool_tbl, instance_defaults);
1913 if is_group_kind(&node.kind) {
1914 if let Some(inner) = tool_tbl.get_table_mut("Tools") {
1915 self.sync_tools_level(inner, true, pool, instance_defaults);
1916 }
1917 sync_group_wiring(node, tool_tbl);
1918 }
1919 }
1920 }
1921
1922 fn sync_node_tool(
1923 &self,
1924 node: &Node,
1925 tool_tbl: &mut LuaTable,
1926 instance_defaults: &HashMap<(&str, &str), ParamValue>,
1927 ) {
1928 // ViewInfo.Pos
1929 if let Some(vi) = tool_tbl.get_table_mut("ViewInfo") {
1930 let pos_changed = vi
1931 .get_table("Pos")
1932 .and_then(read_vec2)
1933 .is_none_or(|[x, y]| {
1934 (x as f32 - node.pos[0]).abs() > 1e-4 || (y as f32 - node.pos[1]).abs() > 1e-4
1935 });
1936 if pos_changed {
1937 vi.set(
1938 LuaKey::Str("Pos".to_owned()),
1939 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
1940 );
1941 }
1942 } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 {
1943 let mut vi = LuaTable {
1944 tag: Some("OperatorInfo".to_owned()),
1945 entries: Vec::new(),
1946 };
1947 vi.set(
1948 LuaKey::Str("Pos".to_owned()),
1949 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
1950 );
1951 tool_tbl.set(LuaKey::Str("ViewInfo".to_owned()), LuaValue::Table(vi));
1952 }
1953
1954 // PassThrough
1955 if node.bypassed {
1956 tool_tbl.set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true));
1957 } else if tool_tbl.get("PassThrough").is_some() {
1958 tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned()));
1959 }
1960
1961 // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`).
1962 if !is_group_kind(&node.kind) {
1963 let master_inputs = node
1964 .raw
1965 .get_str("SourceOp")
1966 .and_then(|m| self.find_node(m))
1967 .map(|mid| &self.nodes[mid.0].inputs);
1968 sync_node_inputs(node, master_inputs, instance_defaults, tool_tbl);
1969 }
1970 }
1971
1972 /// Serializes this composition back to a Blackmagic Fusion `.comp` string.
1973 pub fn to_fusion_string(&self) -> String {
1974 let mut s = self.sync_to_raw_ast().to_fusion_string();
1975 if !s.ends_with('\n') {
1976 s.push('\n');
1977 }
1978 s
1979 }
1980
1981 /// Atomically saves this composition to `path`.
1982 /// If `path` already exists, backs up the original bytes to
1983 /// `<temp_dir>/fission-backups/<stem>_<unix_millis>.comp.bak` and returns `Ok(Some(backup_path))`.
1984 pub fn save_to_file(&self, path: impl AsRef<Path>) -> Result<Option<PathBuf>, std::io::Error> {
1985 let path = path.as_ref();
1986 let stem = path
1987 .file_stem()
1988 .and_then(|s| s.to_str())
1989 .filter(|s| !s.is_empty())
1990 .unwrap_or("comp");
1991
1992 let backup_path = if path.exists() {
1993 let backup_dir = std::env::temp_dir().join("fission-backups");
1994 std::fs::create_dir_all(&backup_dir)?;
1995 let unix_millis = std::time::SystemTime::now()
1996 .duration_since(std::time::UNIX_EPOCH)
1997 .map(|d| d.as_millis())
1998 .unwrap_or(0);
1999 let backup_file = backup_dir.join(format!("{stem}_{unix_millis}.comp.bak"));
2000 std::fs::copy(path, &backup_file)?;
2001 Some(backup_file)
2002 } else {
2003 None
2004 };
2005
2006 let parent = path
2007 .parent()
2008 .filter(|p| !p.as_os_str().is_empty())
2009 .unwrap_or_else(|| Path::new("."));
2010 std::fs::create_dir_all(parent)?;
2011
2012 let nanos = std::time::SystemTime::now()
2013 .duration_since(std::time::UNIX_EPOCH)
2014 .map(|d| d.as_nanos())
2015 .unwrap_or(0);
2016 let pid = std::process::id();
2017 let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp"));
2018
2019 let serialized = self.to_fusion_string();
2020 if let Err(e) = std::fs::write(&tmp_path, serialized.as_bytes()) {
2021 let _ = std::fs::remove_file(&tmp_path);
2022 return Err(e);
2023 }
2024 if let Err(e) = std::fs::rename(&tmp_path, path) {
2025 let _ = std::fs::remove_file(&tmp_path);
2026 return Err(e);
2027 }
2028
2029 Ok(backup_path)
2030 }
2031}
2032
2033pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue {
2034 LuaValue::Table(LuaTable {
2035 tag: None,
2036 entries: vec![
2037 (LuaKey::Index(1), LuaValue::Number(x)),
2038 (LuaKey::Index(2), LuaValue::Number(y)),
2039 ],
2040 })
2041}
2042
2043pub(crate) fn ensure_table_mut<'a>(parent: &'a mut LuaTable, key: &str, tag: Option<&str>) -> &'a mut LuaTable {
2044 if parent.get_table(key).is_none() {
2045 parent.set(
2046 LuaKey::Str(key.to_owned()),
2047 LuaValue::Table(LuaTable {
2048 tag: tag.map(str::to_owned),
2049 entries: Vec::new(),
2050 }),
2051 );
2052 }
2053 parent.get_table_mut(key).expect("table just inserted")
2054}
2055
2056pub(crate) fn param_value_to_lua(v: &ParamValue) -> LuaValue {
2057 match v {
2058 ParamValue::Number(n) => LuaValue::Number(*n),
2059 ParamValue::Point([x, y]) => vec2_lua(*x, *y),
2060 ParamValue::Text(s) => LuaValue::String(s.clone()),
2061 ParamValue::FuId(s) => LuaValue::Table(LuaTable {
2062 tag: Some("FuID".to_owned()),
2063 entries: vec![(LuaKey::Index(1), LuaValue::String(s.clone()))],
2064 }),
2065 ParamValue::Gradient(g) => {
2066 let mut colors = LuaTable::default();
2067 for stop in &g.stops {
2068 let key = if stop.pos.fract() == 0.0 && stop.pos.abs() < 9_007_199_254_740_992.0 {
2069 LuaKey::Index(stop.pos as i64)
2070 } else {
2071 LuaKey::Number(stop.pos)
2072 };
2073 colors.entries.push((
2074 key,
2075 LuaValue::Table(LuaTable {
2076 tag: None,
2077 entries: vec![
2078 (LuaKey::Index(1), LuaValue::Number(stop.rgba[0] as f64)),
2079 (LuaKey::Index(2), LuaValue::Number(stop.rgba[1] as f64)),
2080 (LuaKey::Index(3), LuaValue::Number(stop.rgba[2] as f64)),
2081 (LuaKey::Index(4), LuaValue::Number(stop.rgba[3] as f64)),
2082 ],
2083 }),
2084 ));
2085 }
2086 LuaValue::Table(LuaTable {
2087 tag: Some("Gradient".to_owned()),
2088 entries: vec![(LuaKey::Str("Colors".to_owned()), LuaValue::Table(colors))],
2089 })
2090 }
2091 ParamValue::Raw(raw) => raw.clone(),
2092 }
2093}
2094
2095fn user_control_default(raw: &LuaTable, name: &str) -> Option<ParamValue> {
2096 let ut = raw.get_table("UserControls")?.get_table(name)?;
2097 let is_point = ut.get_str("LINKID_DataType") == Some("Point")
2098 || ut.get_str("INPID_InputControl") == Some("OffsetControl");
2099 if is_point {
2100 let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5);
2101 let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5);
2102 Some(ParamValue::Point([dx, dy]))
2103 } else {
2104 ut.get("INP_Default").map(parse_param_value)
2105 }
2106}
2107
2108pub(crate) fn is_group_kind(kind: &str) -> bool {
2109 matches!(kind, "MacroOperator" | "GroupOperator")
2110}
2111
2112/// `(inner_op, inner_port, default)` for each `InstanceInput` exposed by a Group/Macro tool table.
2113fn instance_inputs(group: &LuaTable) -> impl Iterator<Item = (&str, &str, Option<ParamValue>)> {
2114 group.get_table("Inputs").into_iter().flat_map(|inputs| {
2115 inputs.entries.iter().filter_map(|(_, v)| {
2116 let t = v.as_table()?;
2117 Some((t.get_str("SourceOp")?, t.get_str("Source")?, t.get("Default").map(parse_param_value)))
2118 })
2119 })
2120}
2121
2122/// Writes external wires connected to a Group/Macro node back onto the inner tool inputs that its
2123/// `InstanceInput`s expose (load surfaces them as `node.inputs`).
2124fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) {
2125 let exposed: Vec<(String, String, String)> = group_tbl
2126 .get_table("Inputs")
2127 .map(|inputs| {
2128 inputs
2129 .entries
2130 .iter()
2131 .filter_map(|(k, v)| {
2132 let LuaKey::Str(in_name) = k else { return None };
2133 let t = v.as_table()?;
2134 let port = if in_name.starts_with("MainInput") || in_name == "Input" {
2135 "Input".to_owned()
2136 } else {
2137 in_name.clone()
2138 };
2139 Some((port, t.get_str("SourceOp")?.to_owned(), t.get_str("Source")?.to_owned()))
2140 })
2141 .collect()
2142 })
2143 .unwrap_or_default();
2144 let Some(inner_tools) = group_tbl.get_table_mut("Tools") else { return };
2145 for (port, inner_op, inner_port) in exposed {
2146 let desired = node.inputs.get(&port);
2147 // Still the raw InstanceInput binding: nothing was rewired.
2148 if desired.is_some_and(|b| b.source_op.as_deref() == Some(inner_op.as_str())) {
2149 continue;
2150 }
2151 let Some(inner_tbl) = find_raw_tool_mut(inner_tools, &inner_op) else { continue };
2152 let current = inner_tbl
2153 .get_table("Inputs")
2154 .and_then(|i| i.get_table(&inner_port))
2155 .map(parse_input_binding);
2156 let wired = |b: &InputBinding| (b.source_op.clone(), b.source_output.clone());
2157 match desired {
2158 Some(b) if current.as_ref().map(wired) != Some(wired(b)) => {
2159 let input = ensure_table_mut(ensure_table_mut(inner_tbl, "Inputs", None), &inner_port, Some("Input"));
2160 for (key, val) in [("SourceOp", &b.source_op), ("Source", &b.source_output)] {
2161 match val {
2162 Some(v) => input.set(LuaKey::Str(key.to_owned()), LuaValue::String(v.clone())),
2163 None => {
2164 input.remove(&LuaKey::Str(key.to_owned()));
2165 }
2166 }
2167 }
2168 }
2169 None if current.as_ref().is_some_and(|c| c.source_op.is_some()) => {
2170 if let Some(input) = inner_tbl.get_table_mut("Inputs").and_then(|i| i.get_table_mut(&inner_port)) {
2171 input.remove(&LuaKey::Str("SourceOp".to_owned()));
2172 input.remove(&LuaKey::Str("Source".to_owned()));
2173 }
2174 }
2175 _ => {}
2176 }
2177 }
2178}
2179
2180fn sync_node_inputs(
2181 node: &Node,
2182 master_inputs: Option<&HashMap<String, InputBinding>>,
2183 instance_defaults: &HashMap<(&str, &str), ParamValue>,
2184 tool_tbl: &mut LuaTable,
2185) {
2186 // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`.
2187 if let Some(in_tbl) = tool_tbl.get_table_mut("Inputs") {
2188 in_tbl.entries.retain(|(k, v)| {
2189 let LuaKey::Str(port) = k else { return true };
2190 if v.as_table().is_none() {
2191 return true;
2192 }
2193 node.inputs.contains_key(port)
2194 });
2195 }
2196
2197 // Collect sorted port names for deterministic output when appending new inputs.
2198 let mut ports: Vec<&String> = node.inputs.keys().collect();
2199 ports.sort();
2200
2201 for port in ports {
2202 let binding = &node.inputs[port];
2203 // Load fills unset inner-tool inputs from the enclosing group's `InstanceInput` default.
2204 if binding.source_op.is_none()
2205 && binding.expression.is_none()
2206 && binding.value.is_some()
2207 && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str()))
2208 && tool_tbl
2209 .get_table("Inputs")
2210 .and_then(|i| i.get_table(port))
2211 .is_none_or(|t| parse_input_binding(t).value.is_none())
2212 {
2213 continue;
2214 }
2215 let existing_binding = tool_tbl
2216 .get_table("Inputs")
2217 .and_then(|i| i.get_table(port))
2218 .map(parse_input_binding);
2219
2220 if let Some(orig) = existing_binding {
2221 if orig == *binding {
2222 continue;
2223 }
2224 // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools.
2225 if orig.value.is_none()
2226 && orig.source_op.is_none()
2227 && orig.expression.is_none()
2228 && master_inputs.is_some_and(|m| m.get(port) == Some(binding))
2229 {
2230 continue;
2231 }
2232 let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None);
2233 if let Some(it) = in_tbl.get_table_mut(port) {
2234 if orig.source_op != binding.source_op {
2235 match &binding.source_op {
2236 Some(op) => it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())),
2237 None => {
2238 it.remove(&LuaKey::Str("SourceOp".to_owned()));
2239 }
2240 }
2241 }
2242 if orig.source_output != binding.source_output {
2243 match &binding.source_output {
2244 Some(src) => it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone())),
2245 None => {
2246 it.remove(&LuaKey::Str("Source".to_owned()));
2247 }
2248 }
2249 }
2250 if orig.expression != binding.expression {
2251 match &binding.expression {
2252 Some(expr) => it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone())),
2253 None => {
2254 it.remove(&LuaKey::Str("Expression".to_owned()));
2255 }
2256 }
2257 }
2258 if orig.value != binding.value {
2259 match &binding.value {
2260 Some(val) => it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val)),
2261 None => {
2262 it.remove(&LuaKey::Str("Value".to_owned()));
2263 }
2264 }
2265 }
2266 if it.entries.is_empty()
2267 && binding.value.is_none()
2268 && binding.source_op.is_none()
2269 && binding.source_output.is_none()
2270 && binding.expression.is_none()
2271 {
2272 in_tbl.remove(&LuaKey::Str(port.clone()));
2273 }
2274 }
2275 } else {
2276 // Port did not exist in raw `Inputs`.
2277 if binding.value.is_none() && binding.source_op.is_none() && binding.expression.is_none() {
2278 continue;
2279 }
2280 // Don't pollute `Inputs` with unedited `UserControls` defaults synthesized during load.
2281 if binding.source_op.is_none()
2282 && binding.expression.is_none()
2283 && binding.value.is_some()
2284 && binding.value == user_control_default(&node.raw, port)
2285 {
2286 continue;
2287 }
2288 // Don't duplicate inherited master inputs onto instanced tools.
2289 if let Some(master) = master_inputs {
2290 if master.get(port) == Some(binding) {
2291 continue;
2292 }
2293 }
2294
2295 let mut it = LuaTable {
2296 tag: Some("Input".to_owned()),
2297 entries: Vec::new(),
2298 };
2299 if let Some(op) = &binding.source_op {
2300 it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone()));
2301 }
2302 if let Some(src) = &binding.source_output {
2303 it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone()));
2304 }
2305 if let Some(val) = &binding.value {
2306 it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val));
2307 }
2308 if let Some(expr) = &binding.expression {
2309 it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone()));
2310 }
2311 let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None);
2312 in_tbl.set(LuaKey::Str(port.clone()), LuaValue::Table(it));
2313 }
2314 }
2315}
2316
2317fn spline_color_lua(color: [u8; 3]) -> LuaValue {
2318 LuaValue::Table(LuaTable {
2319 tag: None,
2320 entries: vec![
2321 (LuaKey::Str("Red".to_owned()), LuaValue::Number(color[0] as f64)),
2322 (LuaKey::Str("Green".to_owned()), LuaValue::Number(color[1] as f64)),
2323 (LuaKey::Str("Blue".to_owned()), LuaValue::Number(color[2] as f64)),
2324 ],
2325 })
2326}
2327
2328fn build_keyframes_table(spline: &BezierSpline) -> LuaTable {
2329 let mut kfs = spline.keyframes.clone();
2330 kfs.sort_by(|a, b| a.time.total_cmp(&b.time));
2331 let mut tbl = LuaTable::default();
2332 for kf in kfs {
2333 let key = if kf.time.fract() == 0.0 && kf.time.abs() < 9_007_199_254_740_992.0 {
2334 LuaKey::Index(kf.time as i64)
2335 } else {
2336 LuaKey::Number(kf.time)
2337 };
2338 let mut entry = LuaTable::default();
2339 entry.entries.push((LuaKey::Index(1), LuaValue::Number(kf.value)));
2340 if let Some([lx, ly]) = kf.lh {
2341 entry.entries.push((LuaKey::Str("LH".to_owned()), vec2_lua(lx, ly)));
2342 }
2343 if let Some([rx, ry]) = kf.rh {
2344 entry.entries.push((LuaKey::Str("RH".to_owned()), vec2_lua(rx, ry)));
2345 }
2346 let mut flags = LuaTable::default();
2347 if kf.flags.linear {
2348 flags.entries.push((LuaKey::Str("Linear".to_owned()), LuaValue::Bool(true)));
2349 }
2350 if kf.flags.step_in {
2351 flags.entries.push((LuaKey::Str("StepIn".to_owned()), LuaValue::Bool(true)));
2352 }
2353 if kf.flags.step_out {
2354 flags.entries.push((LuaKey::Str("StepOut".to_owned()), LuaValue::Bool(true)));
2355 }
2356 if kf.flags.loop_after {
2357 flags.entries.push((LuaKey::Str("Loop".to_owned()), LuaValue::Bool(true)));
2358 }
2359 if kf.flags.loop_rel {
2360 flags.entries.push((LuaKey::Str("LoopRel".to_owned()), LuaValue::Bool(true)));
2361 }
2362 if kf.flags.ping_pong {
2363 flags.entries.push((LuaKey::Str("PingPong".to_owned()), LuaValue::Bool(true)));
2364 }
2365 if kf.flags.locked_y {
2366 flags.entries.push((LuaKey::Str("LockedY".to_owned()), LuaValue::Bool(true)));
2367 }
2368 if !flags.entries.is_empty() {
2369 entry.entries.push((LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags)));
2370 }
2371 tbl.entries.push((key, LuaValue::Table(entry)));
2372 }
2373 tbl
2374}
2375
2376fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) {
2377 let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl);
2378 if existing.color != spline.color {
2379 tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color));
2380 }
2381 let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && {
2382 let mut normalized = existing.clone();
2383 normalized.apply_hue_curves_cyclic_ends();
2384 normalized.keyframes == spline.keyframes
2385 };
2386 if existing.keyframes != spline.keyframes && !unchanged_cyclic {
2387 let new_kfs = LuaValue::Table(build_keyframes_table(spline));
2388 if tbl.tag.as_deref() == Some("LUTBezier") && tbl.get_table("KeyColorSplines").is_some() {
2389 if let Some(kcs) = tbl.get_table_mut("KeyColorSplines") {
2390 kcs.set(LuaKey::Index(0), new_kfs);
2391 }
2392 } else {
2393 tbl.set(LuaKey::Str("KeyFrames".to_owned()), new_kfs);
2394 }
2395 }
2396}
2397
2398fn is_non_inheritable_instance_port(
2399 name: &str,
2400 binding: &InputBinding,
2401 node_by_name: &HashMap<String, NodeId>,
2402) -> bool {
2403 if matches!(
2404 name,
2405 "Input"
2406 | "Background"
2407 | "Foreground"
2408 | "EffectMask"
2409 | "MaterialInput"
2410 | "GarbageMatte"
2411 | "SolidMatte"
2412 | "Mask"
2413 | "TrackingMask"
2414 | "RegionMask"
2415 | "MatchReference"
2416 | "MatchMask"
2417 | "Image"
2418 | "Image1"
2419 | "Image2"
2420 | "BlurImage"
2421 | "DisplaceImage"
2422 ) || name.starts_with("SceneInput")
2423 || name.starts_with("MainInput")
2424 {
2425 return true;
2426 }
2427 // Never inherit flow-graph image/scene/material connections targeting another flow node;
2428 // modifiers (`BezierSpline`, `PolyPath`, `Shake`, `Expression`, etc.) are not in `node_by_name`.
2429 binding.value.is_none()
2430 && binding.expression.is_none()
2431 && binding
2432 .source_op
2433 .as_deref()
2434 .is_some_and(|op| node_by_name.contains_key(op))
2435}
2436600
2437pub fn default_main_input_port(kind: &str) -> &'static str {601pub fn default_main_input_port(kind: &str) -> &'static str {
2438 match kind {602 match kind {
...@@ -2442,1319 +606,3 @@ pub fn default_main_input_port(kind: &str) -> &'static str {...@@ -2442,1319 +606,3 @@ pub fn default_main_input_port(kind: &str) -> &'static str {
2442 _ => "Input",606 _ => "Input",
2443 }607 }
2444}608}
2445
2446fn parse_input_binding(t: &LuaTable) -> InputBinding {
2447 let source_op = t.get_str("SourceOp").map(str::to_owned);
2448 let source_output = t.get_str("Source").map(str::to_owned);
2449 let expression = t.get_str("Expression").map(str::to_owned);
2450
2451 let value = t.get("Value").map(parse_param_value);
2452 InputBinding {
2453 value,
2454 source_op,
2455 source_output,
2456 expression,
2457 }
2458}
2459
2460fn parse_param_value(v: &LuaValue) -> ParamValue {
2461 match v {
2462 LuaValue::Number(n) => ParamValue::Number(*n),
2463 LuaValue::Bool(b) => ParamValue::Number(if *b { 1.0 } else { 0.0 }),
2464 LuaValue::String(s) => ParamValue::Text(s.clone()),
2465 LuaValue::Table(t) => match t.tag.as_deref() {
2466 Some("FuID") => ParamValue::FuId(
2467 t.get_index(1)
2468 .and_then(LuaValue::as_str)
2469 .unwrap_or("")
2470 .to_owned(),
2471 ),
2472 Some("Number") => ParamValue::Number(t.get_f64("Value").unwrap_or(0.0)),
2473 Some("Gradient") => ParamValue::Gradient(Gradient::from_lua(t)),
2474 _ => {
2475 if let Some(p) = read_vec2(t) {
2476 ParamValue::Point(p)
2477 } else {
2478 ParamValue::Raw(v.clone())
2479 }
2480 }
2481 },
2482 LuaValue::Nil => ParamValue::Raw(LuaValue::Nil),
2483 }
2484}
2485
2486fn try_parse_gradient_keyframes(table: &LuaTable) -> Option<Vec<(f64, Gradient)>> {
2487 let kfs = table.get_table("KeyFrames")?;
2488 let mut grads = Vec::new();
2489 for (k, v) in &kfs.entries {
2490 let time = match k {
2491 LuaKey::Index(i) => *i as f64,
2492 LuaKey::Number(n) => *n,
2493 _ => continue,
2494 };
2495 let kt = v.as_table()?;
2496 let val = kt
2497 .get_table("Value")
2498 .or_else(|| kt.get_index(1).and_then(LuaValue::as_table))?;
2499 if val.tag.as_deref() == Some("Gradient") {
2500 grads.push((time, Gradient::from_lua(val)));
2501 } else {
2502 return None;
2503 }
2504 }
2505 if grads.is_empty() {
2506 return None;
2507 }
2508 grads.sort_by(|a, b| a.0.total_cmp(&b.0));
2509 Some(grads)
2510}
2511
2512fn try_parse_text_keyframes(table: &LuaTable) -> Option<Vec<(f64, String)>> {
2513 let kfs = table.get_table("KeyFrames")?;
2514 let mut texts = Vec::new();
2515 for (k, v) in &kfs.entries {
2516 let time = match k {
2517 LuaKey::Index(i) => *i as f64,
2518 LuaKey::Number(n) => *n,
2519 _ => continue,
2520 };
2521 let kt = v.as_table()?;
2522 let val = kt.get_table("Value")?;
2523 if matches!(val.tag.as_deref(), Some("Text" | "StyledText")) {
2524 let s = val.get_str("Value").unwrap_or("").to_owned();
2525 texts.push((time, s));
2526 } else {
2527 return None;
2528 }
2529 }
2530 if texts.is_empty() {
2531 return None;
2532 }
2533 texts.sort_by(|a, b| a.0.total_cmp(&b.0));
2534 Some(texts)
2535}
2536
2537fn try_parse_polyline_keyframes(table: &LuaTable) -> Option<Vec<(f64, Vec<crate::spline::PolyPoint>)>> {
2538 let kfs = table.get_table("KeyFrames")?;
2539 let mut shapes = Vec::new();
2540 for (k, v) in &kfs.entries {
2541 let time = match k {
2542 LuaKey::Index(i) => *i as f64,
2543 LuaKey::Number(n) => *n,
2544 _ => continue,
2545 };
2546 let kt = v.as_table()?;
2547 let val = kt.get_table("Value")?;
2548 if val.tag.as_deref() == Some("Polyline") {
2549 let (_, pts) = PolyPath::parse_polyline_table(val);
2550 shapes.push((time, pts));
2551 } else {
2552 return None;
2553 }
2554 }
2555 if shapes.is_empty() {
2556 return None;
2557 }
2558 shapes.sort_by(|a, b| a.0.total_cmp(&b.0));
2559 Some(shapes)
2560}
2561
2562#[allow(clippy::too_many_arguments)]
2563fn parse_tools_table(
2564 tools: &LuaTable,
2565 is_internal: bool,
2566 nodes: &mut Vec<Node>,
2567 node_by_name: &mut HashMap<String, NodeId>,
2568 splines: &mut HashMap<String, BezierSpline>,
2569 poly_paths: &mut HashMap<String, PolyPath>,
2570 gradient_modifiers: &mut HashMap<String, Vec<(f64, Gradient)>>,
2571 text_modifiers: &mut HashMap<String, String>,
2572 text_splines: &mut HashMap<String, Vec<(f64, String)>>,
2573 polyline_splines: &mut HashMap<String, (BezierSpline, Vec<(f64, Vec<crate::spline::PolyPoint>)>)>,
2574 text_cls: &mut HashMap<String, Vec<ClsEntry>>,
2575 shakes: &mut HashMap<String, ShakeModifier>,
2576 expression_modifiers: &mut HashMap<String, ExpressionModifier>,
2577 tracker_aliases: &mut Vec<(String, String)>,
2578 macro_defaults: &mut Vec<(String, String, ParamValue)>,
2579 instanced_from: &mut Vec<(NodeId, String)>,
2580) {
2581 for (key, val) in &tools.entries {
2582 let LuaKey::Str(name) = key else { continue };
2583 let Some(tbl) = val.as_table() else { continue };
2584 let kind = tbl.tag.clone().unwrap_or_else(|| "Unknown".to_owned());
2585
2586 if kind == "BezierSpline" || kind == "LUTBezier" {
2587 if let Some(grads) = try_parse_gradient_keyframes(tbl) {
2588 gradient_modifiers.insert(name.clone(), grads);
2589 } else if let Some(txts) = try_parse_text_keyframes(tbl) {
2590 text_splines.insert(name.clone(), txts);
2591 } else if let Some(polys) = try_parse_polyline_keyframes(tbl) {
2592 polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), polys));
2593 } else {
2594 splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl));
2595 }
2596 continue;
2597 }
2598 if kind == "PolyPath" || kind == "Path" {
2599 poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl));
2600 continue;
2601 }
2602 if kind == "TrackerModifier" {
2603 if let Some(in_tbl) = tbl.get_table("Inputs") {
2604 if let Some(src_op) = in_tbl
2605 .get_table("TrackedCenter0")
2606 .and_then(|c| c.get_str("SourceOp"))
2607 {
2608 tracker_aliases.push((name.clone(), src_op.to_owned()));
2609 } else if let Some(p) = in_tbl
2610 .get_table("PatternCenter0")
2611 .and_then(|c| c.get_table("Value"))
2612 .and_then(read_vec2)
2613 {
2614 poly_paths.insert(
2615 name.clone(),
2616 PolyPath {
2617 name: name.clone(),
2618 displacement_op: None,
2619 displacement_value: 0.0,
2620 closed: false,
2621 points: vec![crate::spline::PolyPoint {
2622 x: p[0] - 0.5,
2623 y: p[1] - 0.5,
2624 lx: 0.0,
2625 ly: 0.0,
2626 rx: 0.0,
2627 ry: 0.0,
2628 linear: true,
2629 }],
2630 },
2631 );
2632 }
2633 }
2634 continue;
2635 }
2636 if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" {
2637 if let Some(in_tbl) = tbl.get_table("Inputs") {
2638 if let Some(txt) = in_tbl
2639 .get_table("Text")
2640 .or_else(|| in_tbl.get_table("StyledText"))
2641 .and_then(|s| s.get_str("Value"))
2642 {
2643 text_modifiers.insert(name.clone(), txt.to_owned());
2644 }
2645 if let Some(arr) = in_tbl
2646 .get_table("CharacterLevelStyling")
2647 .and_then(|c| c.get_table("Value"))
2648 .and_then(|v| v.get_table("Array"))
2649 {
2650 let mut entries = Vec::new();
2651 for (_, ev) in &arr.entries {
2652 let Some(et) = ev.as_table() else { continue };
2653 let Some(pid) = et.get_index(1).and_then(LuaValue::as_f64) else { continue };
2654 let Some(s) = et.get_index(2).and_then(LuaValue::as_f64) else { continue };
2655 let Some(e) = et.get_index(3).and_then(LuaValue::as_f64) else { continue };
2656 let Some(val) = et.get_f64("Value") else { continue };
2657 entries.push(ClsEntry {
2658 prop_id: pid.round().max(0.0) as u32,
2659 start: s.round().max(0.0) as usize,
2660 end: e.round().max(0.0) as usize,
2661 value: val as f32,
2662 });
2663 }
2664 if !entries.is_empty() {
2665 text_cls.insert(name.clone(), entries);
2666 }
2667 }
2668 }
2669 continue;
2670 }
2671 if kind == "Shake" {
2672 let mut inputs = HashMap::new();
2673 if let Some(in_tbl) = tbl.get_table("Inputs") {
2674 for (ik, iv) in &in_tbl.entries {
2675 let LuaKey::Str(in_name) = ik else { continue };
2676 let Some(it) = iv.as_table() else { continue };
2677 inputs.insert(in_name.clone(), parse_input_binding(it));
2678 }
2679 }
2680 shakes.insert(name.clone(), ShakeModifier { inputs });
2681 continue;
2682 }
2683 if kind == "Expression" {
2684 let mut inputs = HashMap::new();
2685 if let Some(in_tbl) = tbl.get_table("Inputs") {
2686 for (ik, iv) in &in_tbl.entries {
2687 let LuaKey::Str(in_name) = ik else { continue };
2688 let Some(it) = iv.as_table() else { continue };
2689 inputs.insert(in_name.clone(), parse_input_binding(it));
2690 }
2691 }
2692 if let Some(uc) = tbl.get_table("UserControls") {
2693 for (uk, uv) in &uc.entries {
2694 let LuaKey::Str(uname) = uk else { continue };
2695 let Some(ut) = uv.as_table() else { continue };
2696 let missing = inputs.get(uname).is_none_or(|b| {
2697 b.value.is_none() && b.source_op.is_none() && b.expression.is_none()
2698 });
2699 if missing {
2700 if let Some(val) = ut.get("INP_Default").map(parse_param_value) {
2701 inputs.insert(
2702 uname.clone(),
2703 InputBinding {
2704 value: Some(val),
2705 source_op: None,
2706 source_output: None,
2707 expression: None,
2708 },
2709 );
2710 }
2711 }
2712 }
2713 }
2714 expression_modifiers.insert(name.clone(), ExpressionModifier { inputs });
2715 continue;
2716 }
2717 if is_modifier_type(&kind) {
2718 if tbl.get_table("KeyFrames").is_some() {
2719 splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl));
2720 }
2721 continue;
2722 }
2723
2724 let pos = tbl
2725 .get_table("ViewInfo")
2726 .and_then(|vi| vi.get_table("Pos"))
2727 .and_then(read_vec2)
2728 .map(|[x, y]| [x as f32, y as f32])
2729 .unwrap_or([0.0, 0.0]);
2730 let bypassed = tbl.get_bool("PassThrough").unwrap_or(false);
2731
2732 let mut inputs = HashMap::new();
2733 if let Some(in_tbl) = tbl.get_table("Inputs") {
2734 for (ik, iv) in &in_tbl.entries {
2735 let LuaKey::Str(in_name) = ik else { continue };
2736 let Some(it) = iv.as_table() else { continue };
2737 let binding = parse_input_binding(it);
2738 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {
2739 if let (Some(src_op), Some(src_param)) = (&binding.source_op, &binding.source_output) {
2740 if let Some(def_v) = it.get("Default") {
2741 macro_defaults.push((src_op.clone(), src_param.clone(), parse_param_value(def_v)));
2742 }
2743 }
2744 }
2745 inputs.insert(in_name.clone(), binding);
2746 }
2747 }
2748
2749 // Populate defaults declared in Fusion `UserControls` (needed for ShakeTransform, Custom, etc.)
2750 if let Some(uc) = tbl.get_table("UserControls") {
2751 for (uk, uv) in &uc.entries {
2752 let LuaKey::Str(uname) = uk else { continue };
2753 let Some(ut) = uv.as_table() else { continue };
2754 let missing = inputs.get(uname).is_none_or(|b| {
2755 b.value.is_none() && b.source_op.is_none() && b.expression.is_none()
2756 });
2757 if missing {
2758 let is_point = ut.get_str("LINKID_DataType") == Some("Point")
2759 || ut.get_str("INPID_InputControl") == Some("OffsetControl");
2760 let def_val = if is_point {
2761 let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5);
2762 let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5);
2763 Some(ParamValue::Point([dx, dy]))
2764 } else {
2765 ut.get("INP_Default").map(parse_param_value)
2766 };
2767 if let Some(val) = def_val {
2768 inputs.insert(
2769 uname.clone(),
2770 InputBinding {
2771 value: Some(val),
2772 source_op: None,
2773 source_output: None,
2774 expression: None,
2775 },
2776 );
2777 }
2778 }
2779 }
2780 }
2781
2782 let mut clips = Vec::new();
2783 if let Some(clips_tbl) = tbl.get_table("Clips") {
2784 for (_, cv) in &clips_tbl.entries {
2785 if let Some(ct) = cv.as_table() {
2786 if let Some(filename) = ct.get_str("Filename") {
2787 clips.push(ClipSpec {
2788 filename: filename.to_owned(),
2789 alternate_filename: ct.get_str("AlternateFilename").map(str::to_owned),
2790 start_frame: ct.get_f64("StartFrame").unwrap_or(-1.0) as i64,
2791 length: ct.get_f64("Length").map(|v| v as i64),
2792 trim_in: ct.get_f64("TrimIn").unwrap_or(0.0) as i64,
2793 trim_out: ct.get_f64("TrimOut").unwrap_or(0.0) as i64,
2794 global_start: ct.get_f64("GlobalStart").unwrap_or(0.0) as i64,
2795 global_end: ct.get_f64("GlobalEnd").unwrap_or(0.0) as i64,
2796 extend_first: ct.get_f64("ExtendFirst").unwrap_or(0.0) as i64,
2797 extend_last: ct.get_f64("ExtendLast").unwrap_or(0.0) as i64,
2798 loop_clip: ct.get_f64("Loop").unwrap_or(0.0) > 0.5,
2799 reverse: ct.get_bool("Reverse").unwrap_or(false),
2800 });
2801 }
2802 }
2803 }
2804 }
2805
2806 if kind == "Saver" && clips.is_empty() {
2807 if let Some(c) = tbl
2808 .get_table("Inputs")
2809 .and_then(|i| i.get_table("Clip"))
2810 .and_then(|c| c.get_table("Value"))
2811 {
2812 if let Some(filename) = c.get_str("Filename") {
2813 clips.push(ClipSpec {
2814 filename: filename.to_owned(),
2815 alternate_filename: None,
2816 start_frame: 0,
2817 length: None,
2818 trim_in: 0,
2819 trim_out: 0,
2820 global_start: 0,
2821 global_end: 0,
2822 extend_first: 0,
2823 extend_last: 0,
2824 loop_clip: false,
2825 reverse: false,
2826 });
2827 }
2828 }
2829 }
2830
2831 // ColorCurves and HueCurves embed their LUTBezier splines inside a nested `Tools` table!
2832 if kind == "ColorCurves" || kind == "HueCurves" {
2833 if let Some(inner_tools) = tbl.get_table("Tools") {
2834 parse_tools_table(
2835 inner_tools,
2836 true,
2837 nodes,
2838 node_by_name,
2839 splines,
2840 poly_paths,
2841 gradient_modifiers,
2842 text_modifiers,
2843 text_splines,
2844 polyline_splines,
2845 text_cls,
2846 shakes,
2847 expression_modifiers,
2848 tracker_aliases,
2849 macro_defaults,
2850 instanced_from,
2851 );
2852 }
2853 }
2854
2855 let mut macro_output = None;
2856 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {
2857 let mut out_name: Option<String> = None;
2858 if let Some(outs) = tbl.get_table("Outputs") {
2859 for (_, ov) in &outs.entries {
2860 if let Some(ot) = ov.as_table() {
2861 if let Some(src_op) = ot.get_str("SourceOp") {
2862 out_name = Some(src_op.to_owned());
2863 break;
2864 }
2865 }
2866 }
2867 }
2868 let inner_start = nodes.len();
2869 if let Some(inner_tools) = tbl.get_table("Tools") {
2870 parse_tools_table(
2871 inner_tools,
2872 true,
2873 nodes,
2874 node_by_name,
2875 splines,
2876 poly_paths,
2877 gradient_modifiers,
2878 text_modifiers,
2879 text_splines,
2880 polyline_splines,
2881 text_cls,
2882 shakes,
2883 expression_modifiers,
2884 tracker_aliases,
2885 macro_defaults,
2886 instanced_from,
2887 );
2888 }
2889 if let Some(oname) = out_name {
2890 macro_output = nodes[inner_start..]
2891 .iter()
2892 .find(|n| n.name == oname)
2893 .map(|n| n.id)
2894 .or_else(|| node_by_name.get(&oname).copied());
2895 }
2896 }
2897
2898 let id = NodeId(nodes.len());
2899 // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name.
2900 if !is_internal || !node_by_name.contains_key(name) {
2901 node_by_name.insert(name.clone(), id);
2902 }
2903 if let Some(master) = tbl.get_str("SourceOp") {
2904 instanced_from.push((id, master.to_owned()));
2905 }
2906 nodes.push(Node {
2907 id,
2908 name: name.clone(),
2909 kind,
2910 pos,
2911 bypassed,
2912 internal: is_internal,
2913 macro_output,
2914 inputs,
2915 clips,
2916 raw: tbl.clone(),
2917 });
2918 }
2919}
2920
2921/// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`.
2922/// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`.
2923fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> Option<f64> {
2924 struct Parser<'a> {
2925 bytes: &'a [u8],
2926 pos: usize,
2927 vars: &'a HashMap<String, f64>,
2928 }
2929
2930 impl<'a> Parser<'a> {
2931 fn skip_ws(&mut self) {
2932 while self.pos < self.bytes.len() {
2933 let b = self.bytes[self.pos];
2934 if b.is_ascii_whitespace() {
2935 self.pos += 1;
2936 } else if b == b'/' && self.bytes.get(self.pos + 1) == Some(&b'/') {
2937 while self.pos < self.bytes.len() && self.bytes[self.pos] != b'\n' {
2938 self.pos += 1;
2939 }
2940 } else {
2941 break;
2942 }
2943 }
2944 }
2945
2946 fn peek(&mut self) -> Option<u8> {
2947 self.skip_ws();
2948 self.bytes.get(self.pos).copied()
2949 }
2950
2951 fn eat_str(&mut self, s: &str) -> bool {
2952 self.skip_ws();
2953 if self.bytes[self.pos..].starts_with(s.as_bytes()) {
2954 self.pos += s.len();
2955 true
2956 } else {
2957 false
2958 }
2959 }
2960
2961 fn parse_or(&mut self) -> Option<f64> {
2962 let mut v = self.parse_and()?;
2963 loop {
2964 self.skip_ws();
2965 if self.eat_str("||") || self.eat_str("|") {
2966 let r = self.parse_and()?;
2967 v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 };
2968 } else {
2969 break;
2970 }
2971 }
2972 Some(v)
2973 }
2974
2975 fn parse_and(&mut self) -> Option<f64> {
2976 let mut v = self.parse_cmp()?;
2977 loop {
2978 self.skip_ws();
2979 if self.eat_str("&&") || self.eat_str("&") {
2980 let r = self.parse_cmp()?;
2981 v = if v != 0.0 && r != 0.0 { 1.0 } else { 0.0 };
2982 } else {
2983 break;
2984 }
2985 }
2986 Some(v)
2987 }
2988
2989 fn parse_cmp(&mut self) -> Option<f64> {
2990 let mut v = self.parse_add()?;
2991 loop {
2992 self.skip_ws();
2993 if self.eat_str("<=") {
2994 let r = self.parse_add()?;
2995 v = if v <= r { 1.0 } else { 0.0 };
2996 } else if self.eat_str(">=") {
2997 let r = self.parse_add()?;
2998 v = if v >= r { 1.0 } else { 0.0 };
2999 } else if self.eat_str("==") || self.eat_str("=") {
3000 let r = self.parse_add()?;
3001 v = if (v - r).abs() <= 1e-12 { 1.0 } else { 0.0 };
3002 } else if self.eat_str("!=") || self.eat_str("~=") || self.eat_str("<>") {
3003 let r = self.parse_add()?;
3004 v = if (v - r).abs() > 1e-12 { 1.0 } else { 0.0 };
3005 } else if self.eat_str("<") {
3006 let r = self.parse_add()?;
3007 v = if v < r { 1.0 } else { 0.0 };
3008 } else if self.eat_str(">") {
3009 let r = self.parse_add()?;
3010 v = if v > r { 1.0 } else { 0.0 };
3011 } else {
3012 break;
3013 }
3014 }
3015 Some(v)
3016 }
3017
3018 fn parse_add(&mut self) -> Option<f64> {
3019 let mut v = self.parse_mul()?;
3020 loop {
3021 match self.peek() {
3022 Some(b'+') => {
3023 self.pos += 1;
3024 v += self.parse_mul()?;
3025 }
3026 Some(b'-') => {
3027 self.pos += 1;
3028 v -= self.parse_mul()?;
3029 }
3030 _ => break,
3031 }
3032 }
3033 Some(v)
3034 }
3035
3036 fn parse_mul(&mut self) -> Option<f64> {
3037 let mut v = self.parse_pow()?;
3038 loop {
3039 match self.peek() {
3040 Some(b'*') => {
3041 self.pos += 1;
3042 v *= self.parse_pow()?;
3043 }
3044 Some(b'/') => {
3045 self.pos += 1;
3046 let r = self.parse_pow()?;
3047 v = if r.abs() < 1e-12 { 0.0 } else { v / r };
3048 }
3049 Some(b'%') => {
3050 self.pos += 1;
3051 let r = self.parse_pow()?;
3052 v = if r.abs() < 1e-12 { 0.0 } else { v - r * (v / r).floor() };
3053 }
3054 _ => break,
3055 }
3056 }
3057 Some(v)
3058 }
3059
3060 fn parse_pow(&mut self) -> Option<f64> {
3061 let base = self.parse_unary()?;
3062 if self.peek() == Some(b'^') {
3063 self.pos += 1;
3064 let exp = self.parse_pow()?;
3065 Some(if base > 0.0 {
3066 base.powf(exp)
3067 } else if base == 0.0 {
3068 if exp == 0.0 { 1.0 } else { 0.0 }
3069 } else if (exp - exp.round()).abs() < 1e-6 {
3070 let p = base.abs().powf(exp);
3071 if (exp.round() as i64) & 1 != 0 { -p } else { p }
3072 } else {
3073 0.0
3074 })
3075 } else {
3076 Some(base)
3077 }
3078 }
3079
3080 fn parse_unary(&mut self) -> Option<f64> {
3081 match self.peek() {
3082 Some(b'-') => {
3083 self.pos += 1;
3084 Some(-self.parse_unary()?)
3085 }
3086 Some(b'+') => {
3087 self.pos += 1;
3088 self.parse_unary()
3089 }
3090 Some(b'!') => {
3091 self.pos += 1;
3092 let v = self.parse_unary()?;
3093 Some(if v == 0.0 { 1.0 } else { 0.0 })
3094 }
3095 _ => self.parse_primary(),
3096 }
3097 }
3098
3099 fn parse_primary(&mut self) -> Option<f64> {
3100 let b = self.peek()?;
3101 if b == b'(' {
3102 self.pos += 1;
3103 let v = self.parse_or()?;
3104 if self.peek() != Some(b')') {
3105 return None;
3106 }
3107 self.pos += 1;
3108 return Some(v);
3109 }
3110 if b.is_ascii_digit() || b == b'.' {
3111 let start = self.pos;
3112 while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
3113 self.pos += 1;
3114 }
3115 if self.bytes.get(self.pos) == Some(&b'.') {
3116 self.pos += 1;
3117 while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
3118 self.pos += 1;
3119 }
3120 }
3121 if matches!(self.bytes.get(self.pos), Some(b'e' | b'E')) {
3122 let exp_pos = self.pos;
3123 self.pos += 1;
3124 if matches!(self.bytes.get(self.pos), Some(b'+' | b'-')) {
3125 self.pos += 1;
3126 }
3127 let dig_start = self.pos;
3128 while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
3129 self.pos += 1;
3130 }
3131 if self.pos == dig_start {
3132 self.pos = exp_pos;
3133 }
3134 }
3135 let s = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?;
3136 return s.parse::<f64>().ok();
3137 }
3138 if b.is_ascii_alphabetic() || b == b'_' {
3139 let start = self.pos;
3140 while self.pos < self.bytes.len()
3141 && (self.bytes[self.pos].is_ascii_alphanumeric() || self.bytes[self.pos] == b'_')
3142 {
3143 self.pos += 1;
3144 }
3145 let ident = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?;
3146 if self.peek() == Some(b'(') {
3147 self.pos += 1;
3148 let mut args = Vec::new();
3149 if self.peek() != Some(b')') {
3150 loop {
3151 args.push(self.parse_or()?);
3152 if self.peek() == Some(b',') {
3153 self.pos += 1;
3154 } else {
3155 break;
3156 }
3157 }
3158 }
3159 if self.peek() != Some(b')') {
3160 return None;
3161 }
3162 self.pos += 1;
3163 return Self::eval_fn(ident, &args);
3164 }
3165 return self.vars.get(ident).copied();
3166 }
3167 None
3168 }
3169
3170 fn eval_fn(name: &str, args: &[f64]) -> Option<f64> {
3171 const DEG2RAD: f64 = std::f64::consts::PI / 180.0;
3172 const RAD2DEG: f64 = 180.0 / std::f64::consts::PI;
3173 let a = |i: usize| args.get(i).copied();
3174 Some(match name {
3175 "sin" => (a(0)? * DEG2RAD).sin(),
3176 "cos" => (a(0)? * DEG2RAD).cos(),
3177 "tan" => (a(0)? * DEG2RAD).tan(),
3178 "asin" => a(0)?.clamp(-1.0, 1.0).asin() * RAD2DEG,
3179 "acos" => a(0)?.clamp(-1.0, 1.0).acos() * RAD2DEG,
3180 "atan" => a(0)?.atan() * RAD2DEG,
3181 "atan2" => a(0)?.atan2(a(1)?) * RAD2DEG,
3182 "sinr" => a(0)?.sin(),
3183 "cosr" => a(0)?.cos(),
3184 "tanr" => a(0)?.tan(),
3185 "asinr" => a(0)?.clamp(-1.0, 1.0).asin(),
3186 "acosr" => a(0)?.clamp(-1.0, 1.0).acos(),
3187 "atanr" => a(0)?.atan(),
3188 "atan2r" => a(0)?.atan2(a(1)?),
3189 "sinh" => a(0)?.sinh(),
3190 "cosh" => a(0)?.cosh(),
3191 "tanh" => a(0)?.tanh(),
3192 "deg" => a(0)? * RAD2DEG,
3193 "rad" => a(0)? * DEG2RAD,
3194 "abs" => a(0)?.abs(),
3195 "sqrt" => a(0)?.max(0.0).sqrt(),
3196 "pow" => a(0)?.powf(a(1)?),
3197 "exp" => a(0)?.exp(),
3198 "log" | "ln" => a(0)?.max(1e-12).ln(),
3199 "log10" => a(0)?.max(1e-12).log10(),
3200 "log2" => a(0)?.max(1e-12).log2(),
3201 "floor" | "int" => a(0)?.floor(),
3202 "ceil" => a(0)?.ceil(),
3203 "round" => a(0)?.round(),
3204 "trunc" => a(0)?.trunc(),
3205 "fract" => a(0)? - a(0)?.floor(),
3206 "sign" => {
3207 let v = a(0)?;
3208 if v > 0.0 { 1.0 } else if v < 0.0 { -1.0 } else { 0.0 }
3209 }
3210 "min" => {
3211 if args.is_empty() { return None; }
3212 args.iter().copied().fold(f64::INFINITY, f64::min)
3213 }
3214 "max" => {
3215 if args.is_empty() { return None; }
3216 args.iter().copied().fold(f64::NEG_INFINITY, f64::max)
3217 }
3218 "clamp" => a(0)?.max(a(1)?).min(a(2)?),
3219 "mod" => {
3220 let (x, y) = (a(0)?, a(1)?);
3221 if y.abs() < 1e-12 { 0.0 } else { x - y * (x / y).floor() }
3222 }
3223 "if" | "iif" => {
3224 if a(0)? != 0.0 { a(1)? } else { a(2)? }
3225 }
3226 "dist" => {
3227 let (x1, y1, x2, y2) = (a(0)?, a(1)?, a(2)?, a(3)?);
3228 ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt()
3229 }
3230 "hypot" => a(0)?.hypot(a(1)?),
3231 "mix" | "lerp" => {
3232 let (x, y, t) = (a(0)?, a(1)?, a(2)?);
3233 x + (y - x) * t
3234 }
3235 "step" => if a(1)? < a(0)? { 0.0 } else { 1.0 },
3236 "smoothstep" => {
3237 let (e0, e1, x) = (a(0)?, a(1)?, a(2)?);
3238 let denom = e1 - e0;
3239 let t = if denom.abs() < 1e-12 { 0.0 } else { ((x - e0) / denom).clamp(0.0, 1.0) };
3240 t * t * (3.0 - 2.0 * t)
3241 }
3242 _ => return None,
3243 })
3244 }
3245 }
3246
3247 let mut p = Parser {
3248 bytes: src.as_bytes(),
3249 pos: 0,
3250 vars,
3251 };
3252 let val = p.parse_or()?;
3253 p.skip_ws();
3254 if p.pos != p.bytes.len() || !val.is_finite() {
3255 return None;
3256 }
3257 Some(val)
3258}
3259
3260#[cfg(test)]
3261mod expression_modifier_tests {
3262 use super::*;
3263
3264 #[test]
3265 fn evaluates_standalone_expression_modifier_number_and_chained() {
3266 let src = r#"Composition {
3267 Tools = ordered() {
3268 XF1 = Transform {
3269 Inputs = {
3270 Angle = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", },
3271 Size = Input { SourceOp = "HourHandExpr", Source = "NumberResult", },
3272 },
3273 },
3274 Clock_MinHandExpr = Expression {
3275 Inputs = {
3276 n1 = Input { Value = 1, },
3277 n2 = Input { SourceOp = "TimeSpline", Source = "Value", },
3278 NumberExpression = Input { Value = "if(n1>0.5,floor(-n2)*30,-n2*30)", },
3279 },
3280 },
3281 HourHandExpr = Expression {
3282 Inputs = {
3283 n1 = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", },
3284 NumberExpression = Input { Value = "n1/12", },
3285 },
3286 },
3287 TimeSpline = BezierSpline {
3288 KeyFrames = {
3289 [0] = { 0.0, Flags = { Linear = true } },
3290 [10] = { 2.5, Flags = { Linear = true } },
3291 },
3292 },
3293 },
3294 }"#;
3295
3296 let comp = Comp::from_fusion_str(src).expect("parse comp");
3297 assert!(comp.expression_modifiers.contains_key("Clock_MinHandExpr"));
3298 assert!(comp.expression_modifiers.contains_key("HourHandExpr"));
3299 // Expression modifiers are modifiers, not flow nodes
3300 assert!(comp.find_node("Clock_MinHandExpr").is_none());
3301
3302 let expr = ExprEngine::new();
3303 let xf = comp.node(comp.find_node("XF1").unwrap());
3304 // At t=10: n2 = 2.5, floor(-2.5) = -3.0, -3.0 * 30 = -90.0
3305 let angle = comp.eval_number(xf, "Angle", 10.0, 0.0, &expr);
3306 assert!((angle - (-90.0)).abs() < 1e-6, "got {angle}");
3307 // Chained HourHandExpr: n1 / 12 = -90 / 12 = -7.5
3308 let size = comp.eval_number(xf, "Size", 10.0, 1.0, &expr);
3309 assert!((size - (-7.5)).abs() < 1e-6, "got {size}");
3310
3311 // Lossless roundtrip preserves Expression modifiers
3312 let saved = comp.to_fusion_string();
3313 let reloaded = Comp::from_fusion_str(&saved).expect("reload");
3314 let r_xf = reloaded.node(reloaded.find_node("XF1").unwrap());
3315 assert!((reloaded.eval_number(r_xf, "Angle", 10.0, 0.0, &expr) - (-90.0)).abs() < 1e-6);
3316 }
3317
3318 #[test]
3319 fn evaluates_standalone_expression_modifier_point_and_dist_trig() {
3320 let src = r#"Composition {
3321 Tools = ordered() {
3322 XF1 = Transform {
3323 Inputs = {
3324 Center = Input { SourceOp = "PtExpr", Source = "PointResult", },
3325 Angle = Input { SourceOp = "TrigExpr", Source = "NumberResult", },
3326 },
3327 },
3328 PtExpr = Expression {
3329 Inputs = {
3330 p1 = Input { Value = { 0.8, 0.2 }, },
3331 n1 = Input { Value = 10, },
3332 PointExpressionX = Input { Value = "if(p1x>0.5, 0.5 + time*dist(p1x,p1y,0.5,p1y)/n1, 0.5)", },
3333 PointExpressionY = Input { Value = "-p1y + p1y*0.5 + 0.5", },
3334 },
3335 },
3336 TrigExpr = Expression {
3337 Inputs = {
3338 NumberIn1 = Input { Value = 90, },
3339 NumberExpression = Input { Value = "sin(n1) + cos(0) + (1/0)", },
3340 },
3341 },
3342 },
3343 }"#;
3344
3345 let comp = Comp::from_fusion_str(src).expect("parse comp");
3346 let expr = ExprEngine::new();
3347 let xf = comp.node(comp.find_node("XF1").unwrap());
3348 // 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
3349 let pt = comp.eval_point(xf, "Center", 5.0, [0.5, 0.5], &expr);
3350 assert!((pt[0] - 0.65).abs() < 1e-6, "got x={}", pt[0]);
3351 assert!((pt[1] - 0.40).abs() < 1e-6, "got y={}", pt[1]);
3352 // sin(90 deg) + cos(0 deg) + safe_div(1,0) = 1 + 1 + 0 = 2.0
3353 let ang = comp.eval_number(xf, "Angle", 0.0, 0.0, &expr);
3354 assert!((ang - 2.0).abs() < 1e-6, "got {ang}");
3355 }
3356
3357 #[test]
3358 fn resolves_instanced_source_op_inheritance_chains_and_keeps_image_wires_isolated() {
3359 let src = r#"Composition {
3360 Tools = ordered() {
3361 Loader1 = Loader {},
3362 Transform2 = Transform {
3363 Inputs = {
3364 Input = Input { SourceOp = "Loader1", Source = "Output", },
3365 },
3366 },
3367 Ellipse1 = EllipseMask {},
3368 ColorCorrector1_6Blend = BezierSpline {
3369 KeyFrames = {
3370 [0] = { 0.25, Flags = { Linear = true } },
3371 [10] = { 0.75, Flags = { Linear = true } },
3372 },
3373 },
3374 ColorCorrector1_6 = ColorCorrector {
3375 Inputs = {
3376 Blend = Input { SourceOp = "ColorCorrector1_6Blend", Source = "Value", },
3377 WheelTintAngle1 = Input { Value = -0.434283, },
3378 WheelHue1 = Input { Value = 0.2, },
3379 PreDividePostMultiply = Input { Value = 1, },
3380 Input = Input { SourceOp = "Loader1", Source = "Output", },
3381 EffectMask = Input { SourceOp = "Ellipse1", Source = "Mask", },
3382 },
3383 },
3384 Instance_ColorCorrector1_6 = ColorCorrector {
3385 SourceOp = "ColorCorrector1_6",
3386 Inputs = {
3387 Input = Input { SourceOp = "Transform2", Source = "Output", },
3388 EffectMask = Input {},
3389 WheelTintAngle1 = Input {},
3390 WheelHue1 = Input { Value = 0.9, },
3391 },
3392 },
3393 Instance_Chained = ColorCorrector {
3394 SourceOp = "Instance_ColorCorrector1_6",
3395 Inputs = {
3396 Input = Input { SourceOp = "Loader1", Source = "Output", },
3397 },
3398 },
3399 CycleA = Blur {
3400 SourceOp = "CycleB",
3401 Inputs = {
3402 XBlurSize = Input { Value = 3.0, },
3403 },
3404 },
3405 CycleB = Blur {
3406 SourceOp = "CycleA",
3407 Inputs = {
3408 YBlurSize = Input { Value = 7.0, },
3409 },
3410 },
3411 },
3412 }"#;
3413
3414 let comp = Comp::from_fusion_str(src).expect("parse instanced comp");
3415 let expr = ExprEngine::new();
3416
3417 let inst = comp.node(comp.find_node("Instance_ColorCorrector1_6").unwrap());
3418 // Empty `WheelTintAngle1 = Input {}` is a de-instanced override (falls back to tool default),
3419 // while omitted params (`Blend`, `PreDividePostMultiply`) inherit from master!
3420 let tint = comp.eval_number(inst, "WheelTintAngle1", 0.0, 0.0, &expr);
3421 assert!(tint.abs() < 1e-6, "de-instanced empty Input {{}} must not inherit master value, got {tint}");
3422 let blend_t5 = comp.eval_number(inst, "Blend", 5.0, 1.0, &expr);
3423 assert!((blend_t5 - 0.5).abs() < 1e-6, "got {blend_t5}");
3424 let pdpm = comp.eval_number(inst, "PreDividePostMultiply", 0.0, 0.0, &expr);
3425 assert!((pdpm - 1.0).abs() < 1e-6, "got {pdpm}");
3426 // Keeps its own explicit override (`WheelHue1 = 0.9`) and its own `Input` wire (`Transform2`)!
3427 let hue = comp.eval_number(inst, "WheelHue1", 0.0, 0.0, &expr);
3428 assert!((hue - 0.9).abs() < 1e-6, "got {hue}");
3429 assert_eq!(inst.connected_node("Input"), Some("Transform2"));
3430 // NEVER inherits parent's `EffectMask` image/mask wire!
3431 assert_eq!(inst.connected_node("EffectMask"), None);
3432
3433 // Chained inheritance (`Instance_Chained -> Instance_ColorCorrector1_6 -> ColorCorrector1_6`):
3434 // nearest ancestor wins (`WheelHue1 = 0.9`, and `WheelTintAngle1` was de-instanced by parent),
3435 // grandparent fills remaining omitted params (`Blend`, `PreDividePostMultiply`).
3436 let chained = comp.node(comp.find_node("Instance_Chained").unwrap());
3437 assert!((comp.eval_number(chained, "WheelHue1", 0.0, 0.0, &expr) - 0.9).abs() < 1e-6);
3438 assert!(comp.eval_number(chained, "WheelTintAngle1", 0.0, 0.0, &expr).abs() < 1e-6);
3439 assert!((comp.eval_number(chained, "Blend", 10.0, 0.0, &expr) - 0.75).abs() < 1e-6);
3440 assert!((comp.eval_number(chained, "PreDividePostMultiply", 0.0, 0.0, &expr) - 1.0).abs() < 1e-6);
3441 assert_eq!(chained.connected_node("Input"), Some("Loader1"));
3442 assert_eq!(chained.connected_node("EffectMask"), None);
3443
3444 // Cycle safety (`CycleA <-> CycleB` terminates cleanly and cross-inherits missing params)
3445 let cyc_a = comp.node(comp.find_node("CycleA").unwrap());
3446 let cyc_b = comp.node(comp.find_node("CycleB").unwrap());
3447 assert!((comp.eval_number(cyc_a, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6);
3448 assert!((comp.eval_number(cyc_a, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6);
3449 assert!((comp.eval_number(cyc_b, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6);
3450 assert!((comp.eval_number(cyc_b, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6);
3451
3452 // Roundtrip preserves SourceOp inheritance and de-instanced `Input {}` overrides without duplicating master params
3453 let saved = comp.to_fusion_string();
3454 let reloaded = Comp::from_fusion_str(&saved).expect("reload");
3455 let r_inst = reloaded.node(reloaded.find_node("Instance_ColorCorrector1_6").unwrap());
3456 assert!(reloaded.eval_number(r_inst, "WheelTintAngle1", 0.0, 0.0, &expr).abs() < 1e-6);
3457 assert!((reloaded.eval_number(r_inst, "Blend", 5.0, 1.0, &expr) - 0.5).abs() < 1e-6);
3458 assert_eq!(r_inst.connected_node("EffectMask"), None);
3459 }
3460
3461 #[test]
3462 fn parses_styled_text_and_text_bezier_spline_keyframes() {
3463 let src = r#"Composition {
3464 Tools = ordered() {
3465 Text_1 = TextPlus {
3466 Inputs = {
3467 StyledText = Input {
3468 SourceOp = "Text_1StyledText",
3469 Source = "Value",
3470 },
3471 },
3472 },
3473 Text_1StyledText = BezierSpline {
3474 KeyFrames = {
3475 [10] = { 0, Value = StyledText { Value = "first line" } },
3476 [20] = { 1, Value = Text { Value = "second line" } },
3477 },
3478 },
3479 },
3480 }"#;
3481 let comp = Comp::from_fusion_str(src).expect("parse styled text spline");
3482 let expr = ExprEngine::new();
3483 let node = comp.node(comp.find_node("Text_1").unwrap());
3484 assert_eq!(comp.eval_text(node, "StyledText", 5.0, "", &expr), "first line");
3485 assert_eq!(comp.eval_text(node, "StyledText", 10.0, "", &expr), "first line");
3486 assert_eq!(comp.eval_text(node, "StyledText", 25.0, "", &expr), "second line");
3487 }
3488
3489 #[test]
3490 fn source_op_inherits_all_color_corrector_params_and_respects_blend_override() {
3491 // Mirrors repro_seed_110: N4 inherits Wheel*/TintMode/*RGBGain/PreDividePostMultiply
3492 // from N2 while keeping its own `Input` wire and `Blend = 0.75` override.
3493 let src = r#"Composition {
3494 Tools = ordered() {
3495 S0 = Loader {},
3496 S1 = DaySky {},
3497 N2 = ColorCorrector {
3498 Inputs = {
3499 Input = Input { SourceOp = "S0", Source = "Output", },
3500 WheelHue1 = Input { Value = -0.235, },
3501 WheelSaturation1 = Input { Value = 0.65, },
3502 WheelTintAngle1 = Input { Value = 0.323, },
3503 WheelTintLength1 = Input { Value = 0.67, },
3504 TintMode = Input { Value = 0, },
3505 MasterRGBGain = Input { Value = 0.65, },
3506 ShadowsRGBGain = Input { Value = 0.84, },
3507 HighlightsRGBGain = Input { Value = 0.75, },
3508 PreDividePostMultiply = Input { Value = 1, },
3509 Blend = Input { Value = 1.0, },
3510 },
3511 },
3512 N4 = ColorCorrector {
3513 SourceOp = "N2",
3514 Inputs = {
3515 Input = Input { SourceOp = "S1", Source = "Output", },
3516 Blend = Input { Value = 0.75, },
3517 },
3518 },
3519 N5 = ColorCorrector {
3520 SourceOp = "N2",
3521 Inputs = {
3522 Input = Input { SourceOp = "S1", Source = "Output", },
3523 },
3524 },
3525 },
3526 }"#;
3527 let comp = Comp::from_fusion_str(src).expect("parse seed 110 style SourceOp");
3528 let expr = ExprEngine::new();
3529 let n4 = comp.node(comp.find_node("N4").unwrap());
3530 assert_eq!(n4.connected_node("Input"), Some("S1"));
3531 assert!((comp.eval_number(n4, "Blend", 1.0, 1.0, &expr) - 0.75).abs() < 1e-6);
3532 assert!((comp.eval_number(n4, "WheelHue1", 1.0, 0.0, &expr) - (-0.235)).abs() < 1e-6);
3533 assert!((comp.eval_number(n4, "WheelSaturation1", 1.0, 1.0, &expr) - 0.65).abs() < 1e-6);
3534 assert!((comp.eval_number(n4, "WheelTintAngle1", 1.0, 0.0, &expr) - 0.323).abs() < 1e-6);
3535 assert!((comp.eval_number(n4, "WheelTintLength1", 1.0, 0.0, &expr) - 0.67).abs() < 1e-6);
3536 assert!((comp.eval_number(n4, "TintMode", 1.0, 2.0, &expr) - 0.0).abs() < 1e-6);
3537 assert!((comp.eval_number(n4, "MasterRGBGain", 1.0, 1.0, &expr) - 0.65).abs() < 1e-6);
3538 assert!((comp.eval_number(n4, "ShadowsRGBGain", 1.0, 1.0, &expr) - 0.84).abs() < 1e-6);
3539 assert!((comp.eval_number(n4, "HighlightsRGBGain", 1.0, 1.0, &expr) - 0.75).abs() < 1e-6);
3540 assert!((comp.eval_number(n4, "PreDividePostMultiply", 1.0, 0.0, &expr) - 1.0).abs() < 1e-6);
3541
3542 let n5 = comp.node(comp.find_node("N5").unwrap());
3543 assert!((comp.eval_number(n5, "Blend", 1.0, 0.0, &expr) - 1.0).abs() < 1e-6);
3544 }
3545
3546 #[test]
3547 fn hue_curves_lut_bezier_applies_cyclic_ends_and_roundtrips_cleanly() {
3548 let src = r#"Composition {
3549 Tools = ordered() {
3550 Bg = Background {},
3551 HC_RSup = LUTBezier {
3552 SmoothEndsTransition = true,
3553 KeyColorSplines = {
3554 [0] = {
3555 [0] = { 0.5 },
3556 [2] = { 1.0 },
3557 [6] = { 0.5 },
3558 }
3559 },
3560 },
3561 CC_Red = LUTBezier {
3562 SmoothEndsTransition = true,
3563 KeyColorSplines = {
3564 [0] = {
3565 [0.0] = { 0.0 },
3566 [0.5] = { 0.8 },
3567 [1.0] = { 0.2 },
3568 }
3569 },
3570 },
3571 HC1 = HueCurves {
3572 Inputs = {
3573 Input = Input { SourceOp = "Bg", Source = "Output", },
3574 RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", },
3575 },
3576 },
3577 CC1 = ColorCurves {
3578 Inputs = {
3579 Input = Input { SourceOp = "Bg", Source = "Output", },
3580 Red = Input { SourceOp = "CC_Red", Source = "Value", },
3581 },
3582 },
3583 },
3584 }"#;
3585 let comp = Comp::from_fusion_str(src).expect("parse HueCurves + ColorCurves");
3586 let rsup = comp.splines.get("HC_RSup").expect("HC_RSup");
3587 assert!(rsup.keyframes[2].lh.is_some());
3588 assert!((rsup.eval(5.0) - 0.4140625).abs() < 1e-3);
3589
3590 // ColorCurves [0..1] must NOT get cyclic HueCurves wrapping even with SmoothEndsTransition = true.
3591 let cc_red = comp.splines.get("CC_Red").expect("CC_Red");
3592 assert!((cc_red.eval(1.0) - 0.2).abs() < 1e-6);
3593 assert!((cc_red.eval(0.75) - 0.5).abs() < 1e-6);
3594
3595 // Lossless roundtrip keeps KeyColorSplines untouched when unedited.
3596 let saved = comp.to_fusion_string();
3597 assert!(!saved.contains("LH ="));
3598 let reloaded = Comp::from_fusion_str(&saved).expect("reload");
3599 assert!((reloaded.splines["HC_RSup"].eval(5.0) - rsup.eval(5.0)).abs() < 1e-9);
3600 }
3601
3602 #[test]
3603 fn comp_eval_number_clamps_loop_spline_before_first_keyframe() {
3604 let src = r#"Composition {
3605 Tools = ordered() {
3606 CG = ColorGain {
3607 Inputs = {
3608 HighHue = Input { SourceOp = "ColorGain1HighHue", Source = "Value", },
3609 },
3610 },
3611 ColorGain1HighHue = BezierSpline {
3612 KeyFrames = {
3613 [4129] = { 0, RH = { 4137.66666666667, 0.333333333333333 }, Flags = { Linear = true, Loop = true } },
3614 [4155] = { 1, LH = { 4146.33333333333, 0.666666666666667 }, Flags = { Linear = true, Loop = true } },
3615 },
3616 },
3617 },
3618 }"#;
3619 let comp = Comp::from_fusion_str(src).expect("parse underwater loop spline");
3620 let expr = ExprEngine::new();
3621 let cg = comp.node(comp.find_node("CG").unwrap());
3622 assert!((comp.eval_number(cg, "HighHue", 3933.0, 0.0, &expr) - 0.0).abs() < 1e-9);
3623 assert!((comp.eval_number(cg, "HighHue", 4142.0, 0.0, &expr) - 0.5).abs() < 1e-9);
3624 assert!((comp.eval_number(cg, "HighHue", 4155.0, 0.0, &expr) - 0.0).abs() < 1e-9);
3625 assert!((comp.eval_number(cg, "HighHue", 4168.0, 0.0, &expr) - 0.5).abs() < 1e-9);
3626 }
3627
3628 #[test]
3629 fn cyclic_expression_references_terminate() {
3630 let src = r#"Composition {
3631 Tools = ordered() {
3632 N = Transform {
3633 Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, },
3634 },
3635 E = Expression {
3636 Inputs = {
3637 n1 = Input { Expression = "N.Size", },
3638 NumberExpression = Input { Value = "n1 + 1", },
3639 },
3640 },
3641 },
3642 }"#;
3643 let comp = Comp::from_fusion_str(src).unwrap();
3644 let n = comp.node(comp.find_node("N").unwrap());
3645 let v = comp.eval_number(n, "Size", 0.0, 7.0, &ExprEngine::new());
3646 assert!(v.is_finite());
3647 }
3648
3649 #[test]
3650 fn clamp_with_inverted_bounds_does_not_panic() {
3651 let src = r#"Composition {
3652 Tools = ordered() {
3653 N = Transform { Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, }, },
3654 E = Expression {
3655 Inputs = {
3656 n1 = Input { Value = 5, },
3657 NumberExpression = Input { Value = "clamp(n1, 1, 0)", },
3658 },
3659 },
3660 },
3661 }"#;
3662 let comp = Comp::from_fusion_str(src).unwrap();
3663 let n = comp.node(comp.find_node("N").unwrap());
3664 assert_eq!(comp.eval_number(n, "Size", 0.0, 9.0, &ExprEngine::new()), 0.0);
3665 }
3666
3667 #[test]
3668 fn explicit_frame_format_is_never_overwritten_by_inferred_size() {
3669 let tools = r#"Tools = ordered() {
3670 BG = Background { Inputs = { Width = Input { Value = 1280, }, Height = Input { Value = 720, }, }, },
3671 }"#;
3672 let explicit = Comp::from_fusion_str(&format!(
3673 "Composition {{ Prefs = {{ Comp = {{ FrameFormat = {{ Width = 1920, Height = 1080, }}, }}, }}, {tools} }}"
3674 ))
3675 .unwrap();
3676 assert_eq!((explicit.width, explicit.height), (1920, 1080));
3677
3678 let inferred = Comp::from_fusion_str(&format!("Composition {{ {tools} }}")).unwrap();
3679 assert_eq!((inferred.width, inferred.height), (1280, 720));
3680 }
3681
3682 #[test]
3683 fn each_loaded_comp_gets_a_distinct_revision_range() {
3684 let src = "Composition { Tools = ordered() { } }";
3685 let a = Comp::from_fusion_str(src).unwrap();
3686 let mut b = Comp::from_fusion_str(src).unwrap();
3687 for _ in 0..1000 {
3688 b.revision += 1;
3689 }
3690 let c = Comp::from_fusion_str(src).unwrap();
3691 assert!(a.revision != b.revision && b.revision != c.revision && a.revision != c.revision);
3692 assert!(c.revision > b.revision);
3693 }
3694
3695 const GROUP_COMP: &str = r#"Composition {
3696 Tools = ordered() {
3697 BG = Background { },
3698 BG2 = Background { },
3699 Group1 = GroupOperator {
3700 Inputs = {
3701 MainInput1 = InstanceInput { SourceOp = "Inner1", Source = "Input", },
3702 BlurSize = InstanceInput { SourceOp = "Inner1", Source = "XBlurSize", Default = 3, },
3703 },
3704 Outputs = {
3705 MainOutput1 = InstanceOutput { SourceOp = "Inner2", Source = "Output", },
3706 },
3707 Tools = ordered() {
3708 Inner1 = Blur {
3709 Inputs = {
3710 Input = Input { SourceOp = "BG", Source = "Output", },
3711 },
3712 },
3713 Inner2 = Transform {
3714 Inputs = {
3715 Input = Input { SourceOp = "Inner1", Source = "Output", },
3716 Size = Input { Value = 1, },
3717 },
3718 },
3719 Inner3 = Blur { },
3720 },
3721 },
3722 },
3723}"#;
3724
3725 #[test]
3726 fn unedited_group_roundtrips_byte_for_byte() {
3727 let comp = Comp::from_fusion_str(GROUP_COMP).unwrap();
3728 let tools = |t: &LuaTable| t.get_table("Tools").unwrap().to_fusion_string();
3729 assert_eq!(tools(&comp.sync_to_raw_ast()), tools(comp.raw_root.as_ref().unwrap()));
3730 }
3731
3732 #[test]
3733 fn nested_group_edits_and_wiring_survive_save() {
3734 let mut comp = Comp::from_fusion_str(GROUP_COMP).unwrap();
3735 let group = comp.find_node("Group1").unwrap();
3736 assert_eq!(comp.node(group).connected_node("Input"), Some("BG"));
3737
3738 comp.delete_nodes(&[comp.find_node("Inner3").unwrap()]);
3739 let inner2 = comp.find_node("Inner2").unwrap();
3740 assert!(comp.set_input_value(inner2, "Size", ParamValue::Number(2.5)));
3741 let (group, bg2) = (comp.find_node("Group1").unwrap(), comp.find_node("BG2").unwrap());
3742 comp.connect_output(bg2, "Output", group, "Input").unwrap();
3743
3744 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
3745 let inner2 = saved.node(saved.find_node("Inner2").unwrap());
3746 assert_eq!(inner2.static_number("Size"), Some(2.5));
3747 assert!(saved.find_node("Inner3").is_none());
3748 assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), Some("BG2"));
3749 assert_eq!(saved.node(saved.find_node("Group1").unwrap()).connected_node("Input"), Some("BG2"));
3750 // The exposed `Default` stays on the InstanceInput instead of leaking onto Inner1.
3751 let text = comp.to_fusion_string();
3752 assert_eq!(text.matches("Value = 3").count(), 0, "{text}");
3753
3754 let mut comp = saved;
3755 let group = comp.find_node("Group1").unwrap();
3756 assert!(comp.disconnect(group, "Input"));
3757 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
3758 assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), None);
3759 }
3760}
crates/model/src/comp/eval.rs created+724
...@@ -0,0 +1,724 @@
1use super::math::eval_fusion_math_expr;
2use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue, ShakeModifier};
3use crate::expr::ExprEngine;
4use crate::spline::Gradient;
5use std::collections::HashMap;
6
7impl Comp {
8 /// Evaluates an animated `Polyline` spline (`BezierSpline` whose keyframes carry `Value = Polyline { ... }`).
9 pub fn eval_polyline_spline(&self, name: &str, time: f64) -> Option<Vec<crate::spline::PolyPoint>> {
10 let (spline, kfs) = self.polyline_splines.get(name)?;
11 if kfs.is_empty() {
12 return None;
13 }
14 if kfs.len() == 1 || time <= kfs[0].0 {
15 return Some(kfs[0].1.clone());
16 }
17 if time >= kfs[kfs.len() - 1].0 {
18 return Some(kfs[kfs.len() - 1].1.clone());
19 }
20 // Fusion stores keyframe index (0, 1, 2, ...) as the spline scalar value for eased shape morphing.
21 let u = spline.eval(time).clamp(0.0, (kfs.len() - 1) as f64);
22 let idx = (u.floor() as usize).min(kfs.len() - 2);
23 let frac = (u - idx as f64).clamp(0.0, 1.0);
24 let a = &kfs[idx].1;
25 let b = &kfs[idx + 1].1;
26 if a.len() != b.len() || frac <= 1e-6 {
27 return Some(a.clone());
28 }
29 if frac >= 1.0 - 1e-6 {
30 return Some(b.clone());
31 }
32 let lerp = |x: f64, y: f64| x + (y - x) * frac;
33 Some(
34 a.iter()
35 .zip(b.iter())
36 .map(|(pa, pb)| crate::spline::PolyPoint {
37 x: lerp(pa.x, pb.x),
38 y: lerp(pa.y, pb.y),
39 lx: lerp(pa.lx, pb.lx),
40 ly: lerp(pa.ly, pb.ly),
41 rx: lerp(pa.rx, pb.rx),
42 ry: lerp(pa.ry, pb.ry),
43 linear: pa.linear && pb.linear,
44 })
45 .collect(),
46 )
47 }
48
49 /// Evaluates a numeric input on `node` at continuous `time`, checking Expression -> Spline -> Static -> `default`.
50 pub fn eval_number(
51 &self,
52 node: &Node,
53 param: &str,
54 time: f64,
55 default: f64,
56 expr_engine: &ExprEngine,
57 ) -> f64 {
58 self.eval_number_at(node, param, time, default, expr_engine, 0)
59 }
60
61 fn eval_number_at(
62 &self,
63 node: &Node,
64 param: &str,
65 time: f64,
66 default: f64,
67 expr_engine: &ExprEngine,
68 depth: usize,
69 ) -> f64 {
70 if depth >= MAX_EXPR_DEPTH {
71 return default;
72 }
73 let Some(binding) = node.inputs.get(param) else {
74 return default;
75 };
76 if let Some(expr) = &binding.expression {
77 if let Some(v) = self.eval_expr_number(node, expr, time, expr_engine) {
78 if v.is_finite() {
79 return v;
80 }
81 }
82 }
83 if let Some(src) = &binding.source_op {
84 if let Some(sp) = self.splines.get(src) {
85 return sp.eval(time);
86 }
87 if let Some(sh) = self.shakes.get(src) {
88 let axis = match binding.source_output.as_deref() {
89 Some("Y") => 1,
90 _ => 0,
91 };
92 return self.eval_shake_axis(sh, axis, time, expr_engine);
93 }
94 if let Some(em) = self.expression_modifiers.get(src) {
95 if let Some(v) = self.eval_expr_mod_number(
96 em,
97 binding.source_output.as_deref(),
98 time,
99 expr_engine,
100 depth + 1,
101 ) {
102 if v.is_finite() {
103 return v;
104 }
105 }
106 }
107 }
108 binding
109 .value
110 .as_ref()
111 .and_then(ParamValue::as_f64)
112 .unwrap_or(default)
113 }
114
115 /// Evaluates a 2D point input (`Center`, `Pivot`, etc.) on `node` at `time`.
116 pub fn eval_point(
117 &self,
118 node: &Node,
119 param: &str,
120 time: f64,
121 default: [f64; 2],
122 expr_engine: &ExprEngine,
123 ) -> [f64; 2] {
124 self.eval_point_at(node, param, time, default, expr_engine, 0)
125 }
126
127 fn eval_point_at(
128 &self,
129 node: &Node,
130 param: &str,
131 time: f64,
132 default: [f64; 2],
133 expr_engine: &ExprEngine,
134 depth: usize,
135 ) -> [f64; 2] {
136 if depth >= MAX_EXPR_DEPTH {
137 return default;
138 }
139 let Some(binding) = node.inputs.get(param) else {
140 return default;
141 };
142 if let Some(expr) = &binding.expression {
143 if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) {
144 return p;
145 }
146 }
147 if let Some(src) = &binding.source_op {
148 if let Some(pp) = self.poly_paths.get(src) {
149 let disp = pp
150 .displacement_op
151 .as_deref()
152 .and_then(|d| self.splines.get(d))
153 .map(|sp| sp.eval(time))
154 .unwrap_or(pp.displacement_value);
155 return pp.eval_center(disp);
156 }
157 if let Some(sh) = self.shakes.get(src) {
158 let x = self.eval_shake_axis(sh, 0, time, expr_engine);
159 let y = self.eval_shake_axis(sh, 1, time, expr_engine);
160 return [x, y];
161 }
162 if let Some(em) = self.expression_modifiers.get(src) {
163 if let Some(pt) = self.eval_expr_mod_point(em, time, expr_engine, depth + 1) {
164 if pt[0].is_finite() && pt[1].is_finite() {
165 return pt;
166 }
167 }
168 }
169 }
170 binding
171 .value
172 .as_ref()
173 .and_then(ParamValue::as_point)
174 .unwrap_or(default)
175 }
176
177 fn eval_shake_input(&self, sh: &ShakeModifier, key: &str, time: f64, default: f64, expr_engine: &ExprEngine) -> f64 {
178 let Some(b) = sh.inputs.get(key) else {
179 return default;
180 };
181 if let Some(expr) = &b.expression {
182 let mut sp = HashMap::new();
183 for (k, ib) in &sh.inputs {
184 if k == key {
185 continue;
186 }
187 if let Some(src) = &ib.source_op {
188 if let Some(spl) = self.splines.get(src) {
189 sp.insert(k.clone(), spl.eval(time));
190 continue;
191 }
192 }
193 if let Some(v) = ib.value.as_ref().and_then(ParamValue::as_f64) {
194 sp.insert(k.clone(), v);
195 }
196 }
197 if let Some(v) = expr_engine.eval_number(expr, time, &sp, &HashMap::new(), &HashMap::new()) {
198 if v.is_finite() {
199 return v;
200 }
201 }
202 }
203 if let Some(src) = &b.source_op {
204 if let Some(spl) = self.splines.get(src) {
205 return spl.eval(time);
206 }
207 }
208 b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default)
209 }
210
211 fn eval_shake_axis(&self, sh: &ShakeModifier, axis: u32, time: f64, expr_engine: &ExprEngine) -> f64 {
212 let smoothness = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine).max(0.01);
213 let seed = self.eval_shake_input(sh, "RandomSeed", time, 0.0, expr_engine).round() as i64;
214 let lock_xy = self.eval_shake_input(sh, "LockXY", time, 1.0, expr_engine) > 0.5;
215 let (min_v, max_v) = if axis == 0 || lock_xy {
216 (
217 self.eval_shake_input(sh, "XMinimum", time, 0.0, expr_engine),
218 self.eval_shake_input(sh, "XMaximum", time, 1.0, expr_engine),
219 )
220 } else {
221 (
222 self.eval_shake_input(sh, "YMinimum", time, 0.0, expr_engine),
223 self.eval_shake_input(sh, "YMaximum", time, 1.0, expr_engine),
224 )
225 };
226 // Smooth Catmull-Rom interpolation over seeded lattice points spaced by `smoothness` frames
227 let u = time / smoothness;
228 let k = u.floor() as i64;
229 let f = u - k as f64;
230 let hash01 = |i: i64| -> f64 {
231 let mut x = (i.wrapping_mul(0x9E37_79B9_7F4A_7C15u64 as i64)
232 ^ seed.wrapping_mul(0xBF58_476D_1CE4_E5B9u64 as i64)
233 ^ ((axis as i64).wrapping_mul(0x94D0_49BB_1331_11EBu64 as i64))) as u64;
234 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
235 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
236 x ^= x >> 31;
237 (x >> 11) as f64 / (1u64 << 53) as f64
238 };
239 let p0 = hash01(k - 1);
240 let p1 = hash01(k);
241 let p2 = hash01(k + 1);
242 let p3 = hash01(k + 2);
243 let f2 = f * f;
244 let f3 = f2 * f;
245 let cr = 0.5 * ((2.0 * p1)
246 + (-p0 + p2) * f
247 + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * f2
248 + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * f3);
249 let t01 = cr.clamp(0.0, 1.0);
250 min_v + (max_v - min_v) * t01
251 }
252
253 fn eval_expr_mod_input_number(
254 &self,
255 em: &ExpressionModifier,
256 keys: &[&str],
257 time: f64,
258 default: f64,
259 expr_engine: &ExprEngine,
260 depth: usize,
261 ) -> f64 {
262 let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else {
263 return default;
264 };
265 if let Some(expr) = &b.expression {
266 if let Some(v) = self.eval_modifier_inline_number(expr, time, expr_engine, depth) {
267 if v.is_finite() {
268 return v;
269 }
270 }
271 }
272 if let Some(src) = &b.source_op {
273 if let Some(spl) = self.splines.get(src) {
274 return spl.eval(time);
275 }
276 if let Some(sh) = self.shakes.get(src) {
277 let axis = match b.source_output.as_deref() {
278 Some("Y") => 1,
279 _ => 0,
280 };
281 return self.eval_shake_axis(sh, axis, time, expr_engine);
282 }
283 if depth < MAX_EXPR_DEPTH {
284 if let Some(sub) = self.expression_modifiers.get(src) {
285 if let Some(v) = self.eval_expr_mod_number(
286 sub,
287 b.source_output.as_deref(),
288 time,
289 expr_engine,
290 depth + 1,
291 ) {
292 if v.is_finite() {
293 return v;
294 }
295 }
296 }
297 }
298 }
299 b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default)
300 }
301
302 fn eval_expr_mod_input_point(
303 &self,
304 em: &ExpressionModifier,
305 keys: &[&str],
306 time: f64,
307 default: [f64; 2],
308 expr_engine: &ExprEngine,
309 depth: usize,
310 ) -> [f64; 2] {
311 let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else {
312 return default;
313 };
314 if let Some(expr) = &b.expression {
315 let trimmed = expr.trim();
316 // Direct `NodeName.ParamName` reference to a Point input on another flow node.
317 if let Some((node_name, param_name)) = trimmed.split_once('.') {
318 if !param_name.contains('.') && !param_name.contains(' ') {
319 if let Some(nid) = self.find_node(node_name.trim()) {
320 return self.eval_point_at(self.node(nid), param_name.trim(), time, default, expr_engine, depth + 1);
321 }
322 }
323 }
324 let (sp, spts, en) = self.collect_global_expr_env(time);
325 if let Some(pt) = expr_engine.eval_point(trimmed, time, &sp, &spts, &en) {
326 if pt[0].is_finite() && pt[1].is_finite() {
327 return pt;
328 }
329 }
330 }
331 if let Some(src) = &b.source_op {
332 if let Some(pp) = self.poly_paths.get(src) {
333 let disp = pp
334 .displacement_op
335 .as_deref()
336 .and_then(|d| self.splines.get(d))
337 .map(|sp| sp.eval(time))
338 .unwrap_or(pp.displacement_value);
339 return pp.eval_center(disp);
340 }
341 if let Some(sh) = self.shakes.get(src) {
342 let x = self.eval_shake_axis(sh, 0, time, expr_engine);
343 let y = self.eval_shake_axis(sh, 1, time, expr_engine);
344 return [x, y];
345 }
346 if depth < MAX_EXPR_DEPTH {
347 if let Some(sub) = self.expression_modifiers.get(src) {
348 if let Some(pt) = self.eval_expr_mod_point(sub, time, expr_engine, depth + 1) {
349 if pt[0].is_finite() && pt[1].is_finite() {
350 return pt;
351 }
352 }
353 }
354 }
355 }
356 b.value.as_ref().and_then(ParamValue::as_point).unwrap_or(default)
357 }
358
359 fn eval_modifier_inline_number(
360 &self,
361 expr: &str,
362 time: f64,
363 expr_engine: &ExprEngine,
364 depth: usize,
365 ) -> Option<f64> {
366 let trimmed = expr.trim();
367 if let Some((node_name, param_name)) = trimmed.split_once('.') {
368 if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') {
369 if let Some(nid) = self.find_node(node_name.trim()) {
370 return Some(self.eval_number_at(
371 self.node(nid),
372 param_name.trim(),
373 time,
374 0.0,
375 expr_engine,
376 depth + 1,
377 ));
378 }
379 }
380 }
381 let (sp, spts, en) = self.collect_global_expr_env(time);
382 expr_engine.eval_number(trimmed, time, &sp, &spts, &en)
383 }
384
385 fn collect_global_expr_env(
386 &self,
387 time: f64,
388 ) -> (
389 HashMap<String, f64>,
390 HashMap<String, [f64; 2]>,
391 HashMap<String, HashMap<String, f64>>,
392 ) {
393 let mut env_nodes = HashMap::new();
394 for n in &self.nodes {
395 let mut m = HashMap::new();
396 for (k, b) in &n.inputs {
397 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
398 m.insert(k.clone(), v);
399 } else if let Some(src) = &b.source_op {
400 if let Some(sp) = self.splines.get(src) {
401 m.insert(k.clone(), sp.eval(time));
402 }
403 }
404 }
405 if !m.is_empty() {
406 env_nodes.insert(n.name.clone(), m);
407 }
408 }
409 (HashMap::new(), HashMap::new(), env_nodes)
410 }
411
412 fn build_expr_mod_vars(
413 &self,
414 em: &ExpressionModifier,
415 time: f64,
416 expr_engine: &ExprEngine,
417 depth: usize,
418 ) -> (HashMap<String, f64>, HashMap<String, [f64; 2]>) {
419 let mut vars = HashMap::with_capacity(32);
420 let mut pts = HashMap::with_capacity(18);
421 vars.insert("time".to_owned(), time);
422 vars.insert("pi".to_owned(), std::f64::consts::PI);
423 vars.insert("e".to_owned(), std::f64::consts::E);
424
425 for i in 1..=9 {
426 let short = format!("n{i}");
427 let long = format!("NumberIn{i}");
428 let v = self.eval_expr_mod_input_number(
429 em,
430 &[short.as_str(), long.as_str()],
431 time,
432 0.0,
433 expr_engine,
434 depth,
435 );
436 vars.insert(short, v);
437 vars.insert(long, v);
438 }
439 for i in 1..=9 {
440 let short = format!("p{i}");
441 let long = format!("PointIn{i}");
442 let pt = self.eval_expr_mod_input_point(
443 em,
444 &[short.as_str(), long.as_str()],
445 time,
446 [0.5, 0.5],
447 expr_engine,
448 depth,
449 );
450 vars.insert(format!("p{i}x"), pt[0]);
451 vars.insert(format!("p{i}y"), pt[1]);
452 pts.insert(short, pt);
453 pts.insert(long, pt);
454 }
455 for (k, b) in &em.inputs {
456 if !vars.contains_key(k) {
457 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
458 vars.insert(k.clone(), v);
459 }
460 }
461 }
462 (vars, pts)
463 }
464
465 fn eval_expr_mod_formula(
466 &self,
467 formula: &str,
468 time: f64,
469 vars: &HashMap<String, f64>,
470 pts: &HashMap<String, [f64; 2]>,
471 expr_engine: &ExprEngine,
472 ) -> Option<f64> {
473 let trimmed = formula.trim();
474 if trimmed.is_empty() {
475 return None;
476 }
477 if let Some(v) = eval_fusion_math_expr(trimmed, vars) {
478 return Some(v);
479 }
480 // Fallback to Lua SimpleExpression engine for Lua-specific formulas
481 let (_, _, en) = self.collect_global_expr_env(time);
482 expr_engine.eval_number(trimmed, time, vars, pts, &en)
483 }
484
485 fn eval_expr_mod_number(
486 &self,
487 em: &ExpressionModifier,
488 source_output: Option<&str>,
489 time: f64,
490 expr_engine: &ExprEngine,
491 depth: usize,
492 ) -> Option<f64> {
493 if depth >= MAX_EXPR_DEPTH {
494 return None;
495 }
496 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
497 let key = match source_output {
498 Some("X") => "PointExpressionX",
499 Some("Y") => "PointExpressionY",
500 _ => "NumberExpression",
501 };
502 let formula = em
503 .inputs
504 .get(key)
505 .and_then(|b| b.value.as_ref())
506 .and_then(ParamValue::as_str)?;
507 self.eval_expr_mod_formula(formula, time, &vars, &pts, expr_engine)
508 }
509
510 fn eval_expr_mod_point(
511 &self,
512 em: &ExpressionModifier,
513 time: f64,
514 expr_engine: &ExprEngine,
515 depth: usize,
516 ) -> Option<[f64; 2]> {
517 if depth >= MAX_EXPR_DEPTH {
518 return None;
519 }
520 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
521 let fx = em
522 .inputs
523 .get("PointExpressionX")
524 .and_then(|b| b.value.as_ref())
525 .and_then(ParamValue::as_str);
526 let fy = em
527 .inputs
528 .get("PointExpressionY")
529 .and_then(|b| b.value.as_ref())
530 .and_then(ParamValue::as_str);
531 if fx.is_some() || fy.is_some() {
532 let x = fx
533 .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine))
534 .unwrap_or(0.5);
535 let y = fy
536 .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine))
537 .unwrap_or(0.5);
538 return Some([x, y]);
539 }
540 if let Some(fp) = em
541 .inputs
542 .get("PointExpression")
543 .and_then(|b| b.value.as_ref())
544 .and_then(ParamValue::as_str)
545 {
546 let (_, _, en) = self.collect_global_expr_env(time);
547 if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) {
548 return Some(pt);
549 }
550 }
551 None
552 }
553
554 pub fn eval_text(
555 &self,
556 node: &Node,
557 param: &str,
558 time: f64,
559 default: &str,
560 expr_engine: &ExprEngine,
561 ) -> String {
562 let Some(binding) = node.inputs.get(param) else {
563 return default.to_owned();
564 };
565 if let Some(expr) = &binding.expression {
566 let (sp, spts, en) = self.collect_expr_env(node, time);
567 if let Some(s) = expr_engine.eval_string(expr, time, &sp, &spts, &en) {
568 return s;
569 }
570 }
571 if let Some(src) = &binding.source_op {
572 if let Some(kfs) = self.text_splines.get(src) {
573 if !kfs.is_empty() {
574 let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1);
575 return kfs[idx].1.clone();
576 }
577 }
578 if let Some(txt) = self.text_modifiers.get(src) {
579 return txt.clone();
580 }
581 }
582 binding
583 .value
584 .as_ref()
585 .and_then(ParamValue::as_str)
586 .unwrap_or(default)
587 .to_owned()
588 }
589
590 pub fn text_cls_entries(&self, node: &Node, param: &str) -> &[ClsEntry] {
591 node.inputs
592 .get(param)
593 .and_then(|b| b.source_op.as_deref())
594 .and_then(|src| self.text_cls.get(src))
595 .map(Vec::as_slice)
596 .unwrap_or(&[])
597 }
598
599 pub fn eval_gradient(&self, node: &Node, param: &str, time: f64) -> Option<Gradient> {
600 let binding = node.inputs.get(param)?;
601 if let Some(src) = &binding.source_op {
602 if let Some(kfs) = self.gradient_modifiers.get(src) {
603 if kfs.is_empty() {
604 return None;
605 }
606 if kfs.len() == 1 || time <= kfs[0].0 {
607 return Some(kfs[0].1.clone());
608 }
609 let last = &kfs[kfs.len() - 1];
610 if time >= last.0 {
611 return Some(last.1.clone());
612 }
613 let idx = kfs.partition_point(|(kt, _)| *kt <= time).saturating_sub(1);
614 let (t0, g0) = &kfs[idx];
615 let (t1, g1) = &kfs[(idx + 1).min(kfs.len() - 1)];
616 let f = ((time - t0) / (t1 - t0).max(1e-9)).clamp(0.0, 1.0) as f32;
617 // Bake 17 blended stops across [0..1]
618 let mut stops = Vec::with_capacity(17);
619 for i in 0..=16 {
620 let p = i as f64 / 16.0;
621 let a = g0.sample(p);
622 let b = g1.sample(p);
623 stops.push(crate::spline::GradientStop {
624 pos: p,
625 rgba: [
626 a[0] + (b[0] - a[0]) * f,
627 a[1] + (b[1] - a[1]) * f,
628 a[2] + (b[2] - a[2]) * f,
629 a[3] + (b[3] - a[3]) * f,
630 ],
631 });
632 }
633 return Some(Gradient { stops });
634 }
635 }
636 if let Some(ParamValue::Gradient(g)) = &binding.value {
637 return Some(g.clone());
638 }
639 None
640 }
641
642 fn collect_expr_env(
643 &self,
644 node: &Node,
645 time: f64,
646 ) -> (
647 HashMap<String, f64>,
648 HashMap<String, [f64; 2]>,
649 HashMap<String, HashMap<String, f64>>,
650 ) {
651 let mut self_params = HashMap::new();
652 let mut self_points = HashMap::new();
653 for (k, b) in &node.inputs {
654 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
655 self_params.insert(k.clone(), v);
656 } else if let Some(pt) = b.value.as_ref().and_then(ParamValue::as_point) {
657 self_points.insert(k.clone(), pt);
658 } else if let Some(src) = &b.source_op {
659 if let Some(sp) = self.splines.get(src) {
660 self_params.insert(k.clone(), sp.eval(time));
661 } else if let Some(pp) = self.poly_paths.get(src) {
662 let disp = pp
663 .displacement_op
664 .as_deref()
665 .and_then(|d| self.splines.get(d))
666 .map(|sp| sp.eval(time))
667 .unwrap_or(pp.displacement_value);
668 self_points.insert(k.clone(), pp.eval_center(disp));
669 }
670 }
671 }
672 let mut env_nodes = HashMap::new();
673 for n in &self.nodes {
674 let mut m = HashMap::new();
675 for (k, b) in &n.inputs {
676 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
677 m.insert(k.clone(), v);
678 } else if let Some(src) = &b.source_op {
679 if let Some(sp) = self.splines.get(src) {
680 m.insert(k.clone(), sp.eval(time));
681 }
682 }
683 }
684 if !m.is_empty() {
685 env_nodes.insert(n.name.clone(), m);
686 }
687 }
688 (self_params, self_points, env_nodes)
689 }
690
691 fn eval_expr_number(
692 &self,
693 node: &Node,
694 expr: &str,
695 time: f64,
696 expr_engine: &ExprEngine,
697 ) -> Option<f64> {
698 let needs_nodes = expr.contains('.')
699 || expr.trim_start().starts_with(':')
700 || expr
701 .split(|c: char| !c.is_alphanumeric() && c != '_')
702 .any(|tok| !tok.is_empty() && node.inputs.contains_key(tok));
703 if !needs_nodes {
704 let empty_self = HashMap::new();
705 let empty_pts = HashMap::new();
706 let empty_env = HashMap::new();
707 return expr_engine.eval_number(expr, time, &empty_self, &empty_pts, &empty_env);
708 }
709 let (sp, spts, en) = self.collect_expr_env(node, time);
710 expr_engine.eval_number(expr, time, &sp, &spts, &en)
711 }
712
713 fn eval_expr_point(
714 &self,
715 node: &Node,
716 expr: &str,
717 time: f64,
718 expr_engine: &ExprEngine,
719 ) -> Option<[f64; 2]> {
720 let (sp, spts, en) = self.collect_expr_env(node, time);
721 expr_engine.eval_point(expr, time, &sp, &spts, &en)
722 }
723
724}
crates/model/src/comp/load.rs created+813
...@@ -0,0 +1,813 @@
1use super::{
2 BitDepth, ClipSpec, ClsEntry, Comp, ExpressionModifier, InputBinding, NEXT_COMP_REVISION,
3 Node, NodeId, ParamValue, REVISION_STRIDE, ShakeModifier, is_modifier_type,
4};
5use crate::lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua};
6use crate::spline::{BezierSpline, Gradient, PolyPath, read_vec2};
7use std::collections::{HashMap, HashSet};
8use std::path::Path;
9use std::sync::atomic::Ordering;
10
11impl Comp {
12 pub fn from_fusion_file(path: impl AsRef<Path>) -> Result<Self, Box<dyn std::error::Error>> {
13 let path = path.as_ref();
14 let bytes = std::fs::read(path)?;
15 let text = String::from_utf8_lossy(&bytes);
16 let mut comp = Self::from_fusion_str(&text)?;
17 comp.path = Some(path.to_path_buf());
18 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
19 comp.name = stem.to_owned();
20 }
21 Ok(comp)
22 }
23
24 pub fn from_fusion_str(text: &str) -> Result<Self, ParseError> {
25 let root_val = parse_lua(text)?;
26 let root = root_val
27 .as_table()
28 .ok_or_else(|| ParseError { offset: 0, line: 1, message: "comp root is not a table".into() })?;
29
30 let current_time = root.get_f64("CurrentTime").unwrap_or(0.0);
31 let global_range = root
32 .get_table("GlobalRange")
33 .and_then(read_vec2)
34 .map(|[a, b]| [a as i64, b as i64])
35 .unwrap_or([0, 1000]);
36 let render_range = root
37 .get_table("RenderRange")
38 .and_then(read_vec2)
39 .map(|[a, b]| [a as i64, b as i64])
40 .unwrap_or(global_range);
41 let audio_filename = root.get_str("AudioFilename").map(str::to_owned);
42 let audio_offset = root.get_f64("AudioOffset").unwrap_or(0.0);
43
44 // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps, Int8)
45 let mut width = 1920u32;
46 let mut height = 1080u32;
47 let mut fps = 30.0_f64;
48 let mut depth_full = BitDepth::Int8;
49 let mut explicit_size = false;
50 if let Some(ff) = root
51 .get_table("Prefs")
52 .and_then(|p| p.get_table("Comp"))
53 .and_then(|c| c.get_table("FrameFormat"))
54 {
55 if let Some(w) = ff.get_f64("Width") {
56 width = w.round().max(1.0) as u32;
57 explicit_size = true;
58 }
59 if let Some(h) = ff.get_f64("Height") {
60 height = h.round().max(1.0) as u32;
61 explicit_size = true;
62 }
63 if let Some(r) = ff.get_f64("Rate") {
64 if r > 0.0 {
65 fps = r;
66 }
67 }
68 if let Some(d) = ff.get_f64("DepthFull").and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) {
69 depth_full = d;
70 }
71 }
72
73 let mut nodes = Vec::new();
74 let mut node_by_name = HashMap::new();
75 let mut splines = HashMap::new();
76 let mut poly_paths = HashMap::new();
77 let mut gradient_modifiers = HashMap::new();
78 let mut text_modifiers = HashMap::new();
79 let mut text_splines = HashMap::new();
80 let mut polyline_splines = HashMap::new();
81 let mut text_cls = HashMap::new();
82 let mut shakes = HashMap::new();
83 let mut expression_modifiers = HashMap::new();
84 let mut tracker_aliases: Vec<(String, String)> = Vec::new();
85 let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new();
86 let mut instanced_from: Vec<(NodeId, String)> = Vec::new();
87
88 if let Some(tools) = root.get_table("Tools") {
89 parse_tools_table(
90 tools,
91 false,
92 &mut nodes,
93 &mut node_by_name,
94 &mut splines,
95 &mut poly_paths,
96 &mut gradient_modifiers,
97 &mut text_modifiers,
98 &mut text_splines,
99 &mut polyline_splines,
100 &mut text_cls,
101 &mut shakes,
102 &mut expression_modifiers,
103 &mut tracker_aliases,
104 &mut macro_defaults,
105 &mut instanced_from,
106 );
107 }
108
109 // Resolve TrackerModifier aliases (e.g. `Track1` -> `Track1TrackerPath`) into `poly_paths`
110 for (tracker_name, src_path) in tracker_aliases {
111 if let Some(pp) = poly_paths.get(&src_path).cloned() {
112 poly_paths.insert(tracker_name, pp);
113 }
114 }
115
116 // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools.
117 for (target_op, target_param, val) in macro_defaults {
118 if let Some(&nid) = node_by_name.get(&target_op) {
119 let entry = nodes[nid.0].inputs.entry(target_param).or_insert(InputBinding {
120 value: None,
121 source_op: None,
122 source_output: None,
123 expression: None,
124 });
125 if entry.value.is_none() && entry.source_op.is_none() && entry.expression.is_none() {
126 entry.value = Some(val);
127 }
128 }
129 }
130
131 // For MacroOperator/GroupOperator Flow display: wire external inputs from inner InstanceInput targets
132 // so Flow shows `Transform1 -> Invert -> Merge2` cleanly while `engine` follows `macro_output`.
133 let node_inputs_snapshot: Vec<(String, HashMap<String, InputBinding>)> = nodes
134 .iter()
135 .map(|n| (n.name.clone(), n.inputs.clone()))
136 .collect();
137 let snap_map: HashMap<String, HashMap<String, InputBinding>> = node_inputs_snapshot.into_iter().collect();
138 for n in &mut nodes {
139 if matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator") {
140 let mut flow_wires = HashMap::new();
141 for (in_name, b) in &n.inputs {
142 if let (Some(inner_op), Some(inner_port)) = (&b.source_op, &b.source_output) {
143 if let Some(inner_in) = snap_map.get(inner_op).and_then(|m| m.get(inner_port)) {
144 if let Some(ext_src) = &inner_in.source_op {
145 // Only connect if ext_src is a visible (non-internal) flow node
146 if node_by_name.get(ext_src).is_some_and(|&id| !snap_map.is_empty() && id != n.id) {
147 let port_name = if in_name.starts_with("MainInput") || in_name == "Input" {
148 "Input".to_owned()
149 } else {
150 in_name.clone()
151 };
152 flow_wires.insert(
153 port_name,
154 InputBinding {
155 value: None,
156 source_op: Some(ext_src.clone()),
157 source_output: inner_in.source_output.clone(),
158 expression: None,
159 },
160 );
161 }
162 }
163 }
164 }
165 }
166 if !flow_wires.is_empty() {
167 n.inputs = flow_wires;
168 }
169 }
170 }
171
172 // Resolve Fusion tool-level `SourceOp` instanced node inheritance
173 // (e.g. `Instance_ColorCorrector1_6 = ColorCorrector { SourceOp = "ColorCorrector1_6" }`),
174 // walking chains up to depth 8 (cycle-safe) while NEVER copying image/mask/scene wires.
175 if !instanced_from.is_empty() {
176 let parent_of: HashMap<NodeId, NodeId> = instanced_from
177 .iter()
178 .filter_map(|(nid, master_name)| {
179 node_by_name
180 .get(master_name)
181 .copied()
182 .filter(|&mid| mid != *nid)
183 .map(|mid| (*nid, mid))
184 })
185 .collect();
186 let orig_inputs: Vec<HashMap<String, InputBinding>> =
187 nodes.iter().map(|n| n.inputs.clone()).collect();
188
189 for &(nid, _) in &instanced_from {
190 let mut visited = HashSet::new();
191 visited.insert(nid);
192 let mut blocked: HashSet<String> = HashSet::new();
193 let mut cur = nid;
194 for _depth in 0..8 {
195 let Some(&pid) = parent_of.get(&cur) else {
196 break;
197 };
198 if !visited.insert(pid) {
199 break;
200 }
201 let inst_inputs = &mut nodes[nid.0].inputs;
202 for (inp_name, parent_binding) in &orig_inputs[pid.0] {
203 if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name)
204 {
205 continue;
206 }
207 if blocked.contains(inp_name) {
208 continue;
209 }
210 if parent_binding.value.is_none()
211 && parent_binding.source_op.is_none()
212 && parent_binding.expression.is_none()
213 {
214 // An empty `Param = Input {}` on an ancestor marks a de-instanced
215 // override to default and stops further inheritance up the chain.
216 blocked.insert(inp_name.clone());
217 continue;
218 }
219 if !inst_inputs.contains_key(inp_name) {
220 inst_inputs.insert(inp_name.clone(), parent_binding.clone());
221 }
222 }
223 cur = pid;
224 }
225 }
226 }
227
228 // Apply cyclic [0..6] endpoint continuity on LUTBezier splines attached to HueCurves nodes.
229 const HUE_CURVE_PORTS: &[&str] = &[
230 "Hue",
231 "Sat",
232 "Lum",
233 "Red",
234 "Green",
235 "Blue",
236 "RedSuppress",
237 "GreenSuppress",
238 "BlueSuppress",
239 ];
240 let mut hue_spline_names: HashSet<String> = HashSet::new();
241 for n in &nodes {
242 if n.kind == "HueCurves" {
243 for &port in HUE_CURVE_PORTS {
244 if let Some(sp_name) = n.connected_node(port) {
245 hue_spline_names.insert(sp_name.to_owned());
246 }
247 }
248 }
249 }
250 for sp_name in hue_spline_names {
251 if let Some(sp) = splines.get_mut(&sp_name) {
252 sp.apply_hue_curves_cyclic_ends();
253 }
254 }
255
256 // Infer comp dimensions from first Background/TextPlus if Prefs omitted Width/Height
257 if !explicit_size {
258 for n in &nodes {
259 if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") {
260 if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) {
261 if w >= 64.0 && h >= 64.0 {
262 width = w as u32;
263 height = h as u32;
264 break;
265 }
266 }
267 }
268 }
269 }
270
271 Ok(Self {
272 path: None,
273 name: "Untitled".to_owned(),
274 width,
275 height,
276 fps,
277 depth_full,
278 current_time,
279 global_range,
280 render_range,
281 audio_filename,
282 audio_offset,
283 nodes,
284 node_by_name,
285 splines,
286 poly_paths,
287 gradient_modifiers,
288 text_modifiers,
289 text_splines,
290 polyline_splines,
291 text_cls,
292 shakes,
293 expression_modifiers,
294 raw_root: Some(root.clone()),
295 revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed),
296 })
297 }
298
299}
300
301fn is_non_inheritable_instance_port(
302 name: &str,
303 binding: &InputBinding,
304 node_by_name: &HashMap<String, NodeId>,
305) -> bool {
306 if matches!(
307 name,
308 "Input"
309 | "Background"
310 | "Foreground"
311 | "EffectMask"
312 | "MaterialInput"
313 | "GarbageMatte"
314 | "SolidMatte"
315 | "Mask"
316 | "TrackingMask"
317 | "RegionMask"
318 | "MatchReference"
319 | "MatchMask"
320 | "Image"
321 | "Image1"
322 | "Image2"
323 | "BlurImage"
324 | "DisplaceImage"
325 ) || name.starts_with("SceneInput")
326 || name.starts_with("MainInput")
327 {
328 return true;
329 }
330 // Never inherit flow-graph image/scene/material connections targeting another flow node;
331 // modifiers (`BezierSpline`, `PolyPath`, `Shake`, `Expression`, etc.) are not in `node_by_name`.
332 binding.value.is_none()
333 && binding.expression.is_none()
334 && binding
335 .source_op
336 .as_deref()
337 .is_some_and(|op| node_by_name.contains_key(op))
338}
339
340pub(super) fn parse_input_binding(t: &LuaTable) -> InputBinding {
341 let source_op = t.get_str("SourceOp").map(str::to_owned);
342 let source_output = t.get_str("Source").map(str::to_owned);
343 let expression = t.get_str("Expression").map(str::to_owned);
344
345 let value = t.get("Value").map(parse_param_value);
346 InputBinding {
347 value,
348 source_op,
349 source_output,
350 expression,
351 }
352}
353
354pub(super) fn parse_param_value(v: &LuaValue) -> ParamValue {
355 match v {
356 LuaValue::Number(n) => ParamValue::Number(*n),
357 LuaValue::Bool(b) => ParamValue::Number(if *b { 1.0 } else { 0.0 }),
358 LuaValue::String(s) => ParamValue::Text(s.clone()),
359 LuaValue::Table(t) => match t.tag.as_deref() {
360 Some("FuID") => ParamValue::FuId(
361 t.get_index(1)
362 .and_then(LuaValue::as_str)
363 .unwrap_or("")
364 .to_owned(),
365 ),
366 Some("Number") => ParamValue::Number(t.get_f64("Value").unwrap_or(0.0)),
367 Some("Gradient") => ParamValue::Gradient(Gradient::from_lua(t)),
368 _ => {
369 if let Some(p) = read_vec2(t) {
370 ParamValue::Point(p)
371 } else {
372 ParamValue::Raw(v.clone())
373 }
374 }
375 },
376 LuaValue::Nil => ParamValue::Raw(LuaValue::Nil),
377 }
378}
379
380fn try_parse_gradient_keyframes(table: &LuaTable) -> Option<Vec<(f64, Gradient)>> {
381 let kfs = table.get_table("KeyFrames")?;
382 let mut grads = Vec::new();
383 for (k, v) in &kfs.entries {
384 let time = match k {
385 LuaKey::Index(i) => *i as f64,
386 LuaKey::Number(n) => *n,
387 _ => continue,
388 };
389 let kt = v.as_table()?;
390 let val = kt
391 .get_table("Value")
392 .or_else(|| kt.get_index(1).and_then(LuaValue::as_table))?;
393 if val.tag.as_deref() == Some("Gradient") {
394 grads.push((time, Gradient::from_lua(val)));
395 } else {
396 return None;
397 }
398 }
399 if grads.is_empty() {
400 return None;
401 }
402 grads.sort_by(|a, b| a.0.total_cmp(&b.0));
403 Some(grads)
404}
405
406fn try_parse_text_keyframes(table: &LuaTable) -> Option<Vec<(f64, String)>> {
407 let kfs = table.get_table("KeyFrames")?;
408 let mut texts = Vec::new();
409 for (k, v) in &kfs.entries {
410 let time = match k {
411 LuaKey::Index(i) => *i as f64,
412 LuaKey::Number(n) => *n,
413 _ => continue,
414 };
415 let kt = v.as_table()?;
416 let val = kt.get_table("Value")?;
417 if matches!(val.tag.as_deref(), Some("Text" | "StyledText")) {
418 let s = val.get_str("Value").unwrap_or("").to_owned();
419 texts.push((time, s));
420 } else {
421 return None;
422 }
423 }
424 if texts.is_empty() {
425 return None;
426 }
427 texts.sort_by(|a, b| a.0.total_cmp(&b.0));
428 Some(texts)
429}
430
431fn try_parse_polyline_keyframes(table: &LuaTable) -> Option<Vec<(f64, Vec<crate::spline::PolyPoint>)>> {
432 let kfs = table.get_table("KeyFrames")?;
433 let mut shapes = Vec::new();
434 for (k, v) in &kfs.entries {
435 let time = match k {
436 LuaKey::Index(i) => *i as f64,
437 LuaKey::Number(n) => *n,
438 _ => continue,
439 };
440 let kt = v.as_table()?;
441 let val = kt.get_table("Value")?;
442 if val.tag.as_deref() == Some("Polyline") {
443 let (_, pts) = PolyPath::parse_polyline_table(val);
444 shapes.push((time, pts));
445 } else {
446 return None;
447 }
448 }
449 if shapes.is_empty() {
450 return None;
451 }
452 shapes.sort_by(|a, b| a.0.total_cmp(&b.0));
453 Some(shapes)
454}
455
456#[allow(clippy::too_many_arguments)]
457fn parse_tools_table(
458 tools: &LuaTable,
459 is_internal: bool,
460 nodes: &mut Vec<Node>,
461 node_by_name: &mut HashMap<String, NodeId>,
462 splines: &mut HashMap<String, BezierSpline>,
463 poly_paths: &mut HashMap<String, PolyPath>,
464 gradient_modifiers: &mut HashMap<String, Vec<(f64, Gradient)>>,
465 text_modifiers: &mut HashMap<String, String>,
466 text_splines: &mut HashMap<String, Vec<(f64, String)>>,
467 polyline_splines: &mut HashMap<String, (BezierSpline, Vec<(f64, Vec<crate::spline::PolyPoint>)>)>,
468 text_cls: &mut HashMap<String, Vec<ClsEntry>>,
469 shakes: &mut HashMap<String, ShakeModifier>,
470 expression_modifiers: &mut HashMap<String, ExpressionModifier>,
471 tracker_aliases: &mut Vec<(String, String)>,
472 macro_defaults: &mut Vec<(String, String, ParamValue)>,
473 instanced_from: &mut Vec<(NodeId, String)>,
474) {
475 for (key, val) in &tools.entries {
476 let LuaKey::Str(name) = key else { continue };
477 let Some(tbl) = val.as_table() else { continue };
478 let kind = tbl.tag.clone().unwrap_or_else(|| "Unknown".to_owned());
479
480 if kind == "BezierSpline" || kind == "LUTBezier" {
481 if let Some(grads) = try_parse_gradient_keyframes(tbl) {
482 gradient_modifiers.insert(name.clone(), grads);
483 } else if let Some(txts) = try_parse_text_keyframes(tbl) {
484 text_splines.insert(name.clone(), txts);
485 } else if let Some(polys) = try_parse_polyline_keyframes(tbl) {
486 polyline_splines.insert(name.clone(), (BezierSpline::from_lua(name.clone(), tbl), polys));
487 } else {
488 splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl));
489 }
490 continue;
491 }
492 if kind == "PolyPath" || kind == "Path" {
493 poly_paths.insert(name.clone(), PolyPath::from_lua(name.clone(), tbl));
494 continue;
495 }
496 if kind == "TrackerModifier" {
497 if let Some(in_tbl) = tbl.get_table("Inputs") {
498 if let Some(src_op) = in_tbl
499 .get_table("TrackedCenter0")
500 .and_then(|c| c.get_str("SourceOp"))
501 {
502 tracker_aliases.push((name.clone(), src_op.to_owned()));
503 } else if let Some(p) = in_tbl
504 .get_table("PatternCenter0")
505 .and_then(|c| c.get_table("Value"))
506 .and_then(read_vec2)
507 {
508 poly_paths.insert(
509 name.clone(),
510 PolyPath {
511 name: name.clone(),
512 displacement_op: None,
513 displacement_value: 0.0,
514 closed: false,
515 points: vec![crate::spline::PolyPoint {
516 x: p[0] - 0.5,
517 y: p[1] - 0.5,
518 lx: 0.0,
519 ly: 0.0,
520 rx: 0.0,
521 ry: 0.0,
522 linear: true,
523 }],
524 },
525 );
526 }
527 }
528 continue;
529 }
530 if kind == "StyledTextCLS" || kind == "CharacterLevelStyling" {
531 if let Some(in_tbl) = tbl.get_table("Inputs") {
532 if let Some(txt) = in_tbl
533 .get_table("Text")
534 .or_else(|| in_tbl.get_table("StyledText"))
535 .and_then(|s| s.get_str("Value"))
536 {
537 text_modifiers.insert(name.clone(), txt.to_owned());
538 }
539 if let Some(arr) = in_tbl
540 .get_table("CharacterLevelStyling")
541 .and_then(|c| c.get_table("Value"))
542 .and_then(|v| v.get_table("Array"))
543 {
544 let mut entries = Vec::new();
545 for (_, ev) in &arr.entries {
546 let Some(et) = ev.as_table() else { continue };
547 let Some(pid) = et.get_index(1).and_then(LuaValue::as_f64) else { continue };
548 let Some(s) = et.get_index(2).and_then(LuaValue::as_f64) else { continue };
549 let Some(e) = et.get_index(3).and_then(LuaValue::as_f64) else { continue };
550 let Some(val) = et.get_f64("Value") else { continue };
551 entries.push(ClsEntry {
552 prop_id: pid.round().max(0.0) as u32,
553 start: s.round().max(0.0) as usize,
554 end: e.round().max(0.0) as usize,
555 value: val as f32,
556 });
557 }
558 if !entries.is_empty() {
559 text_cls.insert(name.clone(), entries);
560 }
561 }
562 }
563 continue;
564 }
565 if kind == "Shake" {
566 let mut inputs = HashMap::new();
567 if let Some(in_tbl) = tbl.get_table("Inputs") {
568 for (ik, iv) in &in_tbl.entries {
569 let LuaKey::Str(in_name) = ik else { continue };
570 let Some(it) = iv.as_table() else { continue };
571 inputs.insert(in_name.clone(), parse_input_binding(it));
572 }
573 }
574 shakes.insert(name.clone(), ShakeModifier { inputs });
575 continue;
576 }
577 if kind == "Expression" {
578 let mut inputs = HashMap::new();
579 if let Some(in_tbl) = tbl.get_table("Inputs") {
580 for (ik, iv) in &in_tbl.entries {
581 let LuaKey::Str(in_name) = ik else { continue };
582 let Some(it) = iv.as_table() else { continue };
583 inputs.insert(in_name.clone(), parse_input_binding(it));
584 }
585 }
586 if let Some(uc) = tbl.get_table("UserControls") {
587 for (uk, uv) in &uc.entries {
588 let LuaKey::Str(uname) = uk else { continue };
589 let Some(ut) = uv.as_table() else { continue };
590 let missing = inputs.get(uname).is_none_or(|b| {
591 b.value.is_none() && b.source_op.is_none() && b.expression.is_none()
592 });
593 if missing {
594 if let Some(val) = ut.get("INP_Default").map(parse_param_value) {
595 inputs.insert(
596 uname.clone(),
597 InputBinding {
598 value: Some(val),
599 source_op: None,
600 source_output: None,
601 expression: None,
602 },
603 );
604 }
605 }
606 }
607 }
608 expression_modifiers.insert(name.clone(), ExpressionModifier { inputs });
609 continue;
610 }
611 if is_modifier_type(&kind) {
612 if tbl.get_table("KeyFrames").is_some() {
613 splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl));
614 }
615 continue;
616 }
617
618 let pos = tbl
619 .get_table("ViewInfo")
620 .and_then(|vi| vi.get_table("Pos"))
621 .and_then(read_vec2)
622 .map(|[x, y]| [x as f32, y as f32])
623 .unwrap_or([0.0, 0.0]);
624 let bypassed = tbl.get_bool("PassThrough").unwrap_or(false);
625
626 let mut inputs = HashMap::new();
627 if let Some(in_tbl) = tbl.get_table("Inputs") {
628 for (ik, iv) in &in_tbl.entries {
629 let LuaKey::Str(in_name) = ik else { continue };
630 let Some(it) = iv.as_table() else { continue };
631 let binding = parse_input_binding(it);
632 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {
633 if let (Some(src_op), Some(src_param)) = (&binding.source_op, &binding.source_output) {
634 if let Some(def_v) = it.get("Default") {
635 macro_defaults.push((src_op.clone(), src_param.clone(), parse_param_value(def_v)));
636 }
637 }
638 }
639 inputs.insert(in_name.clone(), binding);
640 }
641 }
642
643 // Populate defaults declared in Fusion `UserControls` (needed for ShakeTransform, Custom, etc.)
644 if let Some(uc) = tbl.get_table("UserControls") {
645 for (uk, uv) in &uc.entries {
646 let LuaKey::Str(uname) = uk else { continue };
647 let Some(ut) = uv.as_table() else { continue };
648 let missing = inputs.get(uname).is_none_or(|b| {
649 b.value.is_none() && b.source_op.is_none() && b.expression.is_none()
650 });
651 if missing {
652 let is_point = ut.get_str("LINKID_DataType") == Some("Point")
653 || ut.get_str("INPID_InputControl") == Some("OffsetControl");
654 let def_val = if is_point {
655 let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5);
656 let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5);
657 Some(ParamValue::Point([dx, dy]))
658 } else {
659 ut.get("INP_Default").map(parse_param_value)
660 };
661 if let Some(val) = def_val {
662 inputs.insert(
663 uname.clone(),
664 InputBinding {
665 value: Some(val),
666 source_op: None,
667 source_output: None,
668 expression: None,
669 },
670 );
671 }
672 }
673 }
674 }
675
676 let mut clips = Vec::new();
677 if let Some(clips_tbl) = tbl.get_table("Clips") {
678 for (_, cv) in &clips_tbl.entries {
679 if let Some(ct) = cv.as_table() {
680 if let Some(filename) = ct.get_str("Filename") {
681 clips.push(ClipSpec {
682 filename: filename.to_owned(),
683 alternate_filename: ct.get_str("AlternateFilename").map(str::to_owned),
684 start_frame: ct.get_f64("StartFrame").unwrap_or(-1.0) as i64,
685 length: ct.get_f64("Length").map(|v| v as i64),
686 trim_in: ct.get_f64("TrimIn").unwrap_or(0.0) as i64,
687 trim_out: ct.get_f64("TrimOut").unwrap_or(0.0) as i64,
688 global_start: ct.get_f64("GlobalStart").unwrap_or(0.0) as i64,
689 global_end: ct.get_f64("GlobalEnd").unwrap_or(0.0) as i64,
690 extend_first: ct.get_f64("ExtendFirst").unwrap_or(0.0) as i64,
691 extend_last: ct.get_f64("ExtendLast").unwrap_or(0.0) as i64,
692 loop_clip: ct.get_f64("Loop").unwrap_or(0.0) > 0.5,
693 reverse: ct.get_bool("Reverse").unwrap_or(false),
694 });
695 }
696 }
697 }
698 }
699
700 if kind == "Saver" && clips.is_empty() {
701 if let Some(c) = tbl
702 .get_table("Inputs")
703 .and_then(|i| i.get_table("Clip"))
704 .and_then(|c| c.get_table("Value"))
705 {
706 if let Some(filename) = c.get_str("Filename") {
707 clips.push(ClipSpec {
708 filename: filename.to_owned(),
709 alternate_filename: None,
710 start_frame: 0,
711 length: None,
712 trim_in: 0,
713 trim_out: 0,
714 global_start: 0,
715 global_end: 0,
716 extend_first: 0,
717 extend_last: 0,
718 loop_clip: false,
719 reverse: false,
720 });
721 }
722 }
723 }
724
725 // ColorCurves and HueCurves embed their LUTBezier splines inside a nested `Tools` table!
726 if kind == "ColorCurves" || kind == "HueCurves" {
727 if let Some(inner_tools) = tbl.get_table("Tools") {
728 parse_tools_table(
729 inner_tools,
730 true,
731 nodes,
732 node_by_name,
733 splines,
734 poly_paths,
735 gradient_modifiers,
736 text_modifiers,
737 text_splines,
738 polyline_splines,
739 text_cls,
740 shakes,
741 expression_modifiers,
742 tracker_aliases,
743 macro_defaults,
744 instanced_from,
745 );
746 }
747 }
748
749 let mut macro_output = None;
750 if matches!(kind.as_str(), "MacroOperator" | "GroupOperator") {
751 let mut out_name: Option<String> = None;
752 if let Some(outs) = tbl.get_table("Outputs") {
753 for (_, ov) in &outs.entries {
754 if let Some(ot) = ov.as_table() {
755 if let Some(src_op) = ot.get_str("SourceOp") {
756 out_name = Some(src_op.to_owned());
757 break;
758 }
759 }
760 }
761 }
762 let inner_start = nodes.len();
763 if let Some(inner_tools) = tbl.get_table("Tools") {
764 parse_tools_table(
765 inner_tools,
766 true,
767 nodes,
768 node_by_name,
769 splines,
770 poly_paths,
771 gradient_modifiers,
772 text_modifiers,
773 text_splines,
774 polyline_splines,
775 text_cls,
776 shakes,
777 expression_modifiers,
778 tracker_aliases,
779 macro_defaults,
780 instanced_from,
781 );
782 }
783 if let Some(oname) = out_name {
784 macro_output = nodes[inner_start..]
785 .iter()
786 .find(|n| n.name == oname)
787 .map(|n| n.id)
788 .or_else(|| node_by_name.get(&oname).copied());
789 }
790 }
791
792 let id = NodeId(nodes.len());
793 // Don't overwrite an already-registered top-level node name if an internal macro reuses a local name.
794 if !is_internal || !node_by_name.contains_key(name) {
795 node_by_name.insert(name.clone(), id);
796 }
797 if let Some(master) = tbl.get_str("SourceOp") {
798 instanced_from.push((id, master.to_owned()));
799 }
800 nodes.push(Node {
801 id,
802 name: name.clone(),
803 kind,
804 pos,
805 bypassed,
806 internal: is_internal,
807 macro_output,
808 inputs,
809 clips,
810 raw: tbl.clone(),
811 });
812 }
813}
crates/model/src/comp/math.rs created+520
...@@ -0,0 +1,520 @@
1use super::{Comp, Node};
2use crate::lua_value::{LuaKey, LuaTable};
3use std::collections::HashMap;
4
5#[derive(Clone, Debug, PartialEq)]
6pub struct MeshPoint {
7 pub x: f64,
8 pub y: f64,
9 pub l_cx: Option<f64>,
10 pub l_cy: Option<f64>,
11 pub r_cx: Option<f64>,
12 pub r_cy: Option<f64>,
13 pub t_cx: Option<f64>,
14 pub t_cy: Option<f64>,
15 pub b_cx: Option<f64>,
16 pub b_cy: Option<f64>,
17}
18
19#[derive(Clone, Debug, PartialEq)]
20pub struct GridMesh {
21 pub cols: usize,
22 pub rows: usize,
23 pub delta_r: f64,
24 pub delta_c: f64,
25 pub points: Vec<MeshPoint>,
26}
27
28impl GridMesh {
29 fn from_lua_table(tbl: &LuaTable) -> Option<Self> {
30 if tbl.tag.as_deref() != Some("Mesh") {
31 return None;
32 }
33 let cols = tbl.get_f64("Col")?.round().max(2.0) as usize;
34 let pts_tbl = tbl.get_table("Points")?;
35 let mut points = Vec::new();
36 for pval in pts_tbl.positional_values() {
37 let pt = pval.as_table()?;
38 points.push(MeshPoint {
39 x: pt.get_f64("X").unwrap_or(0.0),
40 y: pt.get_f64("Y").unwrap_or(0.0),
41 l_cx: pt.get_f64("L_CX"),
42 l_cy: pt.get_f64("L_CY"),
43 r_cx: pt.get_f64("R_CX"),
44 r_cy: pt.get_f64("R_CY"),
45 t_cx: pt.get_f64("T_CX"),
46 t_cy: pt.get_f64("T_CY"),
47 b_cx: pt.get_f64("B_CX"),
48 b_cy: pt.get_f64("B_CY"),
49 });
50 }
51 if points.len() < cols * 2 {
52 return None;
53 }
54 let rows = points.len() / cols;
55 if rows < 2 || rows * cols != points.len() {
56 return None;
57 }
58 let delta_c = tbl.get_f64("DeltaC").unwrap_or(1.0 / (cols - 1) as f64);
59 let delta_r = tbl.get_f64("DeltaR").unwrap_or(1.0 / (rows - 1) as f64);
60 Some(Self {
61 cols,
62 rows,
63 delta_r,
64 delta_c,
65 points,
66 })
67 }
68
69 fn lerp(&self, other: &Self, frac: f64) -> Self {
70 if self.cols != other.cols || self.rows != other.rows || self.points.len() != other.points.len() {
71 return self.clone();
72 }
73 let f = frac.clamp(0.0, 1.0);
74 let lerp_num = |a: f64, b: f64| a + (b - a) * f;
75 let lerp_opt = |a: Option<f64>, b: Option<f64>| match (a, b) {
76 (Some(x), Some(y)) => Some(lerp_num(x, y)),
77 (Some(x), None) => Some(x),
78 (None, Some(y)) => Some(y),
79 (None, None) => None,
80 };
81 let points = self
82 .points
83 .iter()
84 .zip(other.points.iter())
85 .map(|(a, b)| MeshPoint {
86 x: lerp_num(a.x, b.x),
87 y: lerp_num(a.y, b.y),
88 l_cx: lerp_opt(a.l_cx, b.l_cx),
89 l_cy: lerp_opt(a.l_cy, b.l_cy),
90 r_cx: lerp_opt(a.r_cx, b.r_cx),
91 r_cy: lerp_opt(a.r_cy, b.r_cy),
92 t_cx: lerp_opt(a.t_cx, b.t_cx),
93 t_cy: lerp_opt(a.t_cy, b.t_cy),
94 b_cx: lerp_opt(a.b_cx, b.b_cx),
95 b_cy: lerp_opt(a.b_cy, b.b_cy),
96 })
97 .collect();
98 Self {
99 cols: self.cols,
100 rows: self.rows,
101 delta_r: lerp_num(self.delta_r, other.delta_r),
102 delta_c: lerp_num(self.delta_c, other.delta_c),
103 points,
104 }
105 }
106}
107
108/// Finds a tool/modifier by name in `tools` or any nested `Tools` table (Groups, Macros, curve nodes).
109pub(crate) fn find_raw_tool<'a>(tools: &'a LuaTable, target: &str) -> Option<&'a LuaTable> {
110 if let Some(t) = tools.get_table(target) {
111 return Some(t);
112 }
113 tools
114 .entries
115 .iter()
116 .filter_map(|(_, v)| v.as_table()?.get_table("Tools"))
117 .find_map(|inner| find_raw_tool(inner, target))
118}
119
120pub(crate) fn find_raw_tool_mut<'a>(tools: &'a mut LuaTable, target: &str) -> Option<&'a mut LuaTable> {
121 if tools.get_table(target).is_some() {
122 return tools.get_table_mut(target);
123 }
124 tools
125 .entries
126 .iter_mut()
127 .filter_map(|(_, v)| v.as_table_mut()?.get_table_mut("Tools"))
128 .find_map(|inner| find_raw_tool_mut(inner, target))
129}
130
131impl Comp {
132 /// Evaluates a `GridWarp` `Mesh` input (static `Mesh { ... }` or animated `BezierSpline` of `Mesh`es).
133 pub fn eval_grid_mesh(&self, node: &Node, key: &str, time: f64) -> Option<GridMesh> {
134 if let Some(spline_name) = node.inputs.get(key).and_then(|b| b.source_op.as_deref()) {
135 let tools = self.raw_root.as_ref()?.get_table("Tools")?;
136 let stbl = find_raw_tool(tools, spline_name)?;
137 let kfs_tbl = stbl.get_table("KeyFrames")?;
138 let mut kfs: Vec<(f64, GridMesh)> = Vec::new();
139 for (k, v) in &kfs_tbl.entries {
140 let t = match k {
141 LuaKey::Index(i) => *i as f64,
142 LuaKey::Number(n) => *n,
143 _ => continue,
144 };
145 if let Some(m) = v.as_table().and_then(|kt| kt.get_table("Value")).and_then(GridMesh::from_lua_table) {
146 kfs.push((t, m));
147 }
148 }
149 if !kfs.is_empty() {
150 kfs.sort_by(|a, b| a.0.total_cmp(&b.0));
151 if kfs.len() == 1 || time <= kfs[0].0 {
152 return Some(kfs[0].1.clone());
153 }
154 if time >= kfs[kfs.len() - 1].0 {
155 return Some(kfs[kfs.len() - 1].1.clone());
156 }
157 let u = self
158 .splines
159 .get(spline_name)
160 .map(|sp| sp.eval(time))
161 .unwrap_or(0.0)
162 .clamp(0.0, (kfs.len() - 1) as f64);
163 let idx = (u.floor() as usize).min(kfs.len() - 2);
164 let frac = (u - idx as f64).clamp(0.0, 1.0);
165 if frac <= 1e-6 {
166 return Some(kfs[idx].1.clone());
167 }
168 if frac >= 1.0 - 1e-6 {
169 return Some(kfs[idx + 1].1.clone());
170 }
171 return Some(kfs[idx].1.lerp(&kfs[idx + 1].1, frac));
172 }
173 }
174 node.raw
175 .get_table("Inputs")?
176 .get_table(key)?
177 .get_table("Value")
178 .and_then(GridMesh::from_lua_table)
179 }
180}
181
182/// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`.
183/// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`.
184pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> Option<f64> {
185 struct Parser<'a> {
186 bytes: &'a [u8],
187 pos: usize,
188 vars: &'a HashMap<String, f64>,
189 }
190
191 impl<'a> Parser<'a> {
192 fn skip_ws(&mut self) {
193 while self.pos < self.bytes.len() {
194 let b = self.bytes[self.pos];
195 if b.is_ascii_whitespace() {
196 self.pos += 1;
197 } else if b == b'/' && self.bytes.get(self.pos + 1) == Some(&b'/') {
198 while self.pos < self.bytes.len() && self.bytes[self.pos] != b'\n' {
199 self.pos += 1;
200 }
201 } else {
202 break;
203 }
204 }
205 }
206
207 fn peek(&mut self) -> Option<u8> {
208 self.skip_ws();
209 self.bytes.get(self.pos).copied()
210 }
211
212 fn eat_str(&mut self, s: &str) -> bool {
213 self.skip_ws();
214 if self.bytes[self.pos..].starts_with(s.as_bytes()) {
215 self.pos += s.len();
216 true
217 } else {
218 false
219 }
220 }
221
222 fn parse_or(&mut self) -> Option<f64> {
223 let mut v = self.parse_and()?;
224 loop {
225 self.skip_ws();
226 if self.eat_str("||") || self.eat_str("|") {
227 let r = self.parse_and()?;
228 v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 };
229 } else {
230 break;
231 }
232 }
233 Some(v)
234 }
235
236 fn parse_and(&mut self) -> Option<f64> {
237 let mut v = self.parse_cmp()?;
238 loop {
239 self.skip_ws();
240 if self.eat_str("&&") || self.eat_str("&") {
241 let r = self.parse_cmp()?;
242 v = if v != 0.0 && r != 0.0 { 1.0 } else { 0.0 };
243 } else {
244 break;
245 }
246 }
247 Some(v)
248 }
249
250 fn parse_cmp(&mut self) -> Option<f64> {
251 let mut v = self.parse_add()?;
252 loop {
253 self.skip_ws();
254 if self.eat_str("<=") {
255 let r = self.parse_add()?;
256 v = if v <= r { 1.0 } else { 0.0 };
257 } else if self.eat_str(">=") {
258 let r = self.parse_add()?;
259 v = if v >= r { 1.0 } else { 0.0 };
260 } else if self.eat_str("==") || self.eat_str("=") {
261 let r = self.parse_add()?;
262 v = if (v - r).abs() <= 1e-12 { 1.0 } else { 0.0 };
263 } else if self.eat_str("!=") || self.eat_str("~=") || self.eat_str("<>") {
264 let r = self.parse_add()?;
265 v = if (v - r).abs() > 1e-12 { 1.0 } else { 0.0 };
266 } else if self.eat_str("<") {
267 let r = self.parse_add()?;
268 v = if v < r { 1.0 } else { 0.0 };
269 } else if self.eat_str(">") {
270 let r = self.parse_add()?;
271 v = if v > r { 1.0 } else { 0.0 };
272 } else {
273 break;
274 }
275 }
276 Some(v)
277 }
278
279 fn parse_add(&mut self) -> Option<f64> {
280 let mut v = self.parse_mul()?;
281 loop {
282 match self.peek() {
283 Some(b'+') => {
284 self.pos += 1;
285 v += self.parse_mul()?;
286 }
287 Some(b'-') => {
288 self.pos += 1;
289 v -= self.parse_mul()?;
290 }
291 _ => break,
292 }
293 }
294 Some(v)
295 }
296
297 fn parse_mul(&mut self) -> Option<f64> {
298 let mut v = self.parse_pow()?;
299 loop {
300 match self.peek() {
301 Some(b'*') => {
302 self.pos += 1;
303 v *= self.parse_pow()?;
304 }
305 Some(b'/') => {
306 self.pos += 1;
307 let r = self.parse_pow()?;
308 v = if r.abs() < 1e-12 { 0.0 } else { v / r };
309 }
310 Some(b'%') => {
311 self.pos += 1;
312 let r = self.parse_pow()?;
313 v = if r.abs() < 1e-12 { 0.0 } else { v - r * (v / r).floor() };
314 }
315 _ => break,
316 }
317 }
318 Some(v)
319 }
320
321 fn parse_pow(&mut self) -> Option<f64> {
322 let base = self.parse_unary()?;
323 if self.peek() == Some(b'^') {
324 self.pos += 1;
325 let exp = self.parse_pow()?;
326 Some(if base > 0.0 {
327 base.powf(exp)
328 } else if base == 0.0 {
329 if exp == 0.0 { 1.0 } else { 0.0 }
330 } else if (exp - exp.round()).abs() < 1e-6 {
331 let p = base.abs().powf(exp);
332 if (exp.round() as i64) & 1 != 0 { -p } else { p }
333 } else {
334 0.0
335 })
336 } else {
337 Some(base)
338 }
339 }
340
341 fn parse_unary(&mut self) -> Option<f64> {
342 match self.peek() {
343 Some(b'-') => {
344 self.pos += 1;
345 Some(-self.parse_unary()?)
346 }
347 Some(b'+') => {
348 self.pos += 1;
349 self.parse_unary()
350 }
351 Some(b'!') => {
352 self.pos += 1;
353 let v = self.parse_unary()?;
354 Some(if v == 0.0 { 1.0 } else { 0.0 })
355 }
356 _ => self.parse_primary(),
357 }
358 }
359
360 fn parse_primary(&mut self) -> Option<f64> {
361 let b = self.peek()?;
362 if b == b'(' {
363 self.pos += 1;
364 let v = self.parse_or()?;
365 if self.peek() != Some(b')') {
366 return None;
367 }
368 self.pos += 1;
369 return Some(v);
370 }
371 if b.is_ascii_digit() || b == b'.' {
372 let start = self.pos;
373 while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
374 self.pos += 1;
375 }
376 if self.bytes.get(self.pos) == Some(&b'.') {
377 self.pos += 1;
378 while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
379 self.pos += 1;
380 }
381 }
382 if matches!(self.bytes.get(self.pos), Some(b'e' | b'E')) {
383 let exp_pos = self.pos;
384 self.pos += 1;
385 if matches!(self.bytes.get(self.pos), Some(b'+' | b'-')) {
386 self.pos += 1;
387 }
388 let dig_start = self.pos;
389 while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() {
390 self.pos += 1;
391 }
392 if self.pos == dig_start {
393 self.pos = exp_pos;
394 }
395 }
396 let s = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?;
397 return s.parse::<f64>().ok();
398 }
399 if b.is_ascii_alphabetic() || b == b'_' {
400 let start = self.pos;
401 while self.pos < self.bytes.len()
402 && (self.bytes[self.pos].is_ascii_alphanumeric() || self.bytes[self.pos] == b'_')
403 {
404 self.pos += 1;
405 }
406 let ident = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?;
407 if self.peek() == Some(b'(') {
408 self.pos += 1;
409 let mut args = Vec::new();
410 if self.peek() != Some(b')') {
411 loop {
412 args.push(self.parse_or()?);
413 if self.peek() == Some(b',') {
414 self.pos += 1;
415 } else {
416 break;
417 }
418 }
419 }
420 if self.peek() != Some(b')') {
421 return None;
422 }
423 self.pos += 1;
424 return Self::eval_fn(ident, &args);
425 }
426 return self.vars.get(ident).copied();
427 }
428 None
429 }
430
431 fn eval_fn(name: &str, args: &[f64]) -> Option<f64> {
432 const DEG2RAD: f64 = std::f64::consts::PI / 180.0;
433 const RAD2DEG: f64 = 180.0 / std::f64::consts::PI;
434 let a = |i: usize| args.get(i).copied();
435 Some(match name {
436 "sin" => (a(0)? * DEG2RAD).sin(),
437 "cos" => (a(0)? * DEG2RAD).cos(),
438 "tan" => (a(0)? * DEG2RAD).tan(),
439 "asin" => a(0)?.clamp(-1.0, 1.0).asin() * RAD2DEG,
440 "acos" => a(0)?.clamp(-1.0, 1.0).acos() * RAD2DEG,
441 "atan" => a(0)?.atan() * RAD2DEG,
442 "atan2" => a(0)?.atan2(a(1)?) * RAD2DEG,
443 "sinr" => a(0)?.sin(),
444 "cosr" => a(0)?.cos(),
445 "tanr" => a(0)?.tan(),
446 "asinr" => a(0)?.clamp(-1.0, 1.0).asin(),
447 "acosr" => a(0)?.clamp(-1.0, 1.0).acos(),
448 "atanr" => a(0)?.atan(),
449 "atan2r" => a(0)?.atan2(a(1)?),
450 "sinh" => a(0)?.sinh(),
451 "cosh" => a(0)?.cosh(),
452 "tanh" => a(0)?.tanh(),
453 "deg" => a(0)? * RAD2DEG,
454 "rad" => a(0)? * DEG2RAD,
455 "abs" => a(0)?.abs(),
456 "sqrt" => a(0)?.max(0.0).sqrt(),
457 "pow" => a(0)?.powf(a(1)?),
458 "exp" => a(0)?.exp(),
459 "log" | "ln" => a(0)?.max(1e-12).ln(),
460 "log10" => a(0)?.max(1e-12).log10(),
461 "log2" => a(0)?.max(1e-12).log2(),
462 "floor" | "int" => a(0)?.floor(),
463 "ceil" => a(0)?.ceil(),
464 "round" => a(0)?.round(),
465 "trunc" => a(0)?.trunc(),
466 "fract" => a(0)? - a(0)?.floor(),
467 "sign" => {
468 let v = a(0)?;
469 if v > 0.0 { 1.0 } else if v < 0.0 { -1.0 } else { 0.0 }
470 }
471 "min" => {
472 if args.is_empty() { return None; }
473 args.iter().copied().fold(f64::INFINITY, f64::min)
474 }
475 "max" => {
476 if args.is_empty() { return None; }
477 args.iter().copied().fold(f64::NEG_INFINITY, f64::max)
478 }
479 "clamp" => a(0)?.max(a(1)?).min(a(2)?),
480 "mod" => {
481 let (x, y) = (a(0)?, a(1)?);
482 if y.abs() < 1e-12 { 0.0 } else { x - y * (x / y).floor() }
483 }
484 "if" | "iif" => {
485 if a(0)? != 0.0 { a(1)? } else { a(2)? }
486 }
487 "dist" => {
488 let (x1, y1, x2, y2) = (a(0)?, a(1)?, a(2)?, a(3)?);
489 ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt()
490 }
491 "hypot" => a(0)?.hypot(a(1)?),
492 "mix" | "lerp" => {
493 let (x, y, t) = (a(0)?, a(1)?, a(2)?);
494 x + (y - x) * t
495 }
496 "step" => if a(1)? < a(0)? { 0.0 } else { 1.0 },
497 "smoothstep" => {
498 let (e0, e1, x) = (a(0)?, a(1)?, a(2)?);
499 let denom = e1 - e0;
500 let t = if denom.abs() < 1e-12 { 0.0 } else { ((x - e0) / denom).clamp(0.0, 1.0) };
501 t * t * (3.0 - 2.0 * t)
502 }
503 _ => return None,
504 })
505 }
506 }
507
508 let mut p = Parser {
509 bytes: src.as_bytes(),
510 pos: 0,
511 vars,
512 };
513 let val = p.parse_or()?;
514 p.skip_ws();
515 if p.pos != p.bytes.len() || !val.is_finite() {
516 return None;
517 }
518 Some(val)
519}
520
crates/model/src/comp/save.rs created+637
...@@ -0,0 +1,637 @@
1use super::load::{parse_input_binding, parse_param_value};
2use super::math::find_raw_tool_mut;
3use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};
4use crate::lua_value::{LuaKey, LuaTable, LuaValue};
5use crate::spline::{BezierSpline, read_vec2};
6use std::collections::{HashMap, VecDeque};
7use std::path::{Path, PathBuf};
8
9impl Comp {
10 /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits,
11 /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST,
12 /// preserving all unknown nodes, modifiers, macros, UserControls, Clips, and metadata verbatim.
13 pub fn sync_to_raw_ast(&self) -> LuaTable {
14 let mut root = self.raw_root.clone().unwrap_or_else(|| LuaTable {
15 tag: Some("Composition".to_owned()),
16 entries: Vec::new(),
17 });
18
19 root.set(
20 LuaKey::Str("CurrentTime".to_owned()),
21 LuaValue::Number(self.current_time),
22 );
23 root.set(
24 LuaKey::Str("GlobalRange".to_owned()),
25 vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64),
26 );
27 root.set(
28 LuaKey::Str("RenderRange".to_owned()),
29 vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64),
30 );
31 if let Some(ref af) = self.audio_filename {
32 root.set(
33 LuaKey::Str("AudioFilename".to_owned()),
34 LuaValue::String(af.clone()),
35 );
36 }
37 if self.audio_offset != 0.0 || root.get("AudioOffset").is_some() {
38 root.set(
39 LuaKey::Str("AudioOffset".to_owned()),
40 LuaValue::Number(self.audio_offset),
41 );
42 }
43
44 // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull)
45 {
46 let prefs = ensure_table_mut(&mut root, "Prefs", None);
47 let comp_prefs = ensure_table_mut(prefs, "Comp", None);
48 let ff = ensure_table_mut(comp_prefs, "FrameFormat", None);
49 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {
50 ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64));
51 }
52 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {
53 ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64));
54 }
55 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {
56 ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps));
57 }
58 let existing_depth = ff
59 .get_f64("DepthFull")
60 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
61 .unwrap_or(BitDepth::Int8);
62 if existing_depth != self.depth_full {
63 ff.set(
64 LuaKey::Str("DepthFull".to_owned()),
65 LuaValue::Number((self.depth_full as i32) as f64),
66 );
67 }
68 }
69
70 // Sync Tools
71 let tools = ensure_table_mut(&mut root, "Tools", Some("ordered"));
72
73 for node in self.nodes.iter().filter(|n| !n.internal) {
74 if tools.get_table(&node.name).is_some() {
75 continue;
76 }
77 let mut new_tbl = if node.raw.tag.is_some() {
78 node.raw.clone()
79 } else {
80 LuaTable { tag: None, entries: Vec::new() }
81 };
82 if new_tbl.tag.is_none() {
83 new_tbl.tag = Some(node.kind.clone());
84 }
85 tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl));
86 }
87
88 let mut pool: HashMap<(bool, String), VecDeque<&Node>> = HashMap::new();
89 let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new();
90 for node in &self.nodes {
91 pool.entry((node.internal, node.name.clone())).or_default().push_back(node);
92 if !is_group_kind(&node.kind) {
93 continue;
94 }
95 for (inner_op, inner_port, default) in instance_inputs(&node.raw) {
96 if let Some(d) = default {
97 instance_defaults.insert((inner_op, inner_port), d);
98 }
99 }
100 }
101 self.sync_tools_level(tools, false, &mut pool, &instance_defaults);
102
103 // Sync BezierSpline edits (only touch splines that actually differ from the raw AST)
104 let mut spline_names: Vec<&String> = self.splines.keys().collect();
105 spline_names.sort();
106 for spline_name in spline_names {
107 let spline = &self.splines[spline_name];
108 if let Some(tbl) = find_raw_tool_mut(tools, spline_name) {
109 sync_spline_table(spline_name, spline, tbl);
110 continue;
111 }
112 let mut sp_tbl = LuaTable {
113 tag: Some("BezierSpline".to_owned()),
114 entries: Vec::new(),
115 };
116 sp_tbl.set(
117 LuaKey::Str("SplineColor".to_owned()),
118 spline_color_lua(spline.color),
119 );
120 sp_tbl.set(
121 LuaKey::Str("KeyFrames".to_owned()),
122 LuaValue::Table(build_keyframes_table(spline)),
123 );
124 tools.set(LuaKey::Str(spline_name.clone()), LuaValue::Table(sp_tbl));
125 }
126
127 root
128 }
129
130 /// Syncs one `Tools` table level: drops deleted flow nodes (never modifiers), then syncs each
131 /// surviving node and recurses into Group/Macro operators' private `Tools`.
132 fn sync_tools_level<'a>(
133 &'a self,
134 tools: &mut LuaTable,
135 internal: bool,
136 pool: &mut HashMap<(bool, String), VecDeque<&'a Node>>,
137 instance_defaults: &HashMap<(&str, &str), ParamValue>,
138 ) {
139 tools.entries.retain(|(k, v)| {
140 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true };
141 is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown"))
142 || pool.get(&(internal, name.clone())).is_some_and(|q| !q.is_empty())
143 });
144
145 for (k, v) in &mut tools.entries {
146 let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue };
147 if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) {
148 continue;
149 }
150 let Some(node) = pool.get_mut(&(internal, name.clone())).and_then(VecDeque::pop_front) else {
151 continue;
152 };
153 self.sync_node_tool(node, tool_tbl, instance_defaults);
154 if is_group_kind(&node.kind) {
155 if let Some(inner) = tool_tbl.get_table_mut("Tools") {
156 self.sync_tools_level(inner, true, pool, instance_defaults);
157 }
158 sync_group_wiring(node, tool_tbl);
159 }
160 }
161 }
162
163 fn sync_node_tool(
164 &self,
165 node: &Node,
166 tool_tbl: &mut LuaTable,
167 instance_defaults: &HashMap<(&str, &str), ParamValue>,
168 ) {
169 // ViewInfo.Pos
170 if let Some(vi) = tool_tbl.get_table_mut("ViewInfo") {
171 let pos_changed = vi
172 .get_table("Pos")
173 .and_then(read_vec2)
174 .is_none_or(|[x, y]| {
175 (x as f32 - node.pos[0]).abs() > 1e-4 || (y as f32 - node.pos[1]).abs() > 1e-4
176 });
177 if pos_changed {
178 vi.set(
179 LuaKey::Str("Pos".to_owned()),
180 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
181 );
182 }
183 } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 {
184 let mut vi = LuaTable {
185 tag: Some("OperatorInfo".to_owned()),
186 entries: Vec::new(),
187 };
188 vi.set(
189 LuaKey::Str("Pos".to_owned()),
190 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
191 );
192 tool_tbl.set(LuaKey::Str("ViewInfo".to_owned()), LuaValue::Table(vi));
193 }
194
195 // PassThrough
196 if node.bypassed {
197 tool_tbl.set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true));
198 } else if tool_tbl.get("PassThrough").is_some() {
199 tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned()));
200 }
201
202 // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`).
203 if !is_group_kind(&node.kind) {
204 let master_inputs = node
205 .raw
206 .get_str("SourceOp")
207 .and_then(|m| self.find_node(m))
208 .map(|mid| &self.nodes[mid.0].inputs);
209 sync_node_inputs(node, master_inputs, instance_defaults, tool_tbl);
210 }
211 }
212
213 /// Serializes this composition back to a Blackmagic Fusion `.comp` string.
214 pub fn to_fusion_string(&self) -> String {
215 let mut s = self.sync_to_raw_ast().to_fusion_string();
216 if !s.ends_with('\n') {
217 s.push('\n');
218 }
219 s
220 }
221
222 /// Atomically saves this composition to `path`.
223 /// If `path` already exists, backs up the original bytes to
224 /// `<temp_dir>/fission-backups/<stem>_<unix_millis>.comp.bak` and returns `Ok(Some(backup_path))`.
225 pub fn save_to_file(&self, path: impl AsRef<Path>) -> Result<Option<PathBuf>, std::io::Error> {
226 let path = path.as_ref();
227 let stem = path
228 .file_stem()
229 .and_then(|s| s.to_str())
230 .filter(|s| !s.is_empty())
231 .unwrap_or("comp");
232
233 let backup_path = if path.exists() {
234 let backup_dir = std::env::temp_dir().join("fission-backups");
235 std::fs::create_dir_all(&backup_dir)?;
236 let unix_millis = std::time::SystemTime::now()
237 .duration_since(std::time::UNIX_EPOCH)
238 .map(|d| d.as_millis())
239 .unwrap_or(0);
240 let backup_file = backup_dir.join(format!("{stem}_{unix_millis}.comp.bak"));
241 std::fs::copy(path, &backup_file)?;
242 Some(backup_file)
243 } else {
244 None
245 };
246
247 let parent = path
248 .parent()
249 .filter(|p| !p.as_os_str().is_empty())
250 .unwrap_or_else(|| Path::new("."));
251 std::fs::create_dir_all(parent)?;
252
253 let nanos = std::time::SystemTime::now()
254 .duration_since(std::time::UNIX_EPOCH)
255 .map(|d| d.as_nanos())
256 .unwrap_or(0);
257 let pid = std::process::id();
258 let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp"));
259
260 let serialized = self.to_fusion_string();
261 if let Err(e) = std::fs::write(&tmp_path, serialized.as_bytes()) {
262 let _ = std::fs::remove_file(&tmp_path);
263 return Err(e);
264 }
265 if let Err(e) = std::fs::rename(&tmp_path, path) {
266 let _ = std::fs::remove_file(&tmp_path);
267 return Err(e);
268 }
269
270 Ok(backup_path)
271 }
272}
273
274pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue {
275 LuaValue::Table(LuaTable {
276 tag: None,
277 entries: vec![
278 (LuaKey::Index(1), LuaValue::Number(x)),
279 (LuaKey::Index(2), LuaValue::Number(y)),
280 ],
281 })
282}
283
284pub(crate) fn ensure_table_mut<'a>(parent: &'a mut LuaTable, key: &str, tag: Option<&str>) -> &'a mut LuaTable {
285 if parent.get_table(key).is_none() {
286 parent.set(
287 LuaKey::Str(key.to_owned()),
288 LuaValue::Table(LuaTable {
289 tag: tag.map(str::to_owned),
290 entries: Vec::new(),
291 }),
292 );
293 }
294 parent.get_table_mut(key).expect("table just inserted")
295}
296
297pub(crate) fn param_value_to_lua(v: &ParamValue) -> LuaValue {
298 match v {
299 ParamValue::Number(n) => LuaValue::Number(*n),
300 ParamValue::Point([x, y]) => vec2_lua(*x, *y),
301 ParamValue::Text(s) => LuaValue::String(s.clone()),
302 ParamValue::FuId(s) => LuaValue::Table(LuaTable {
303 tag: Some("FuID".to_owned()),
304 entries: vec![(LuaKey::Index(1), LuaValue::String(s.clone()))],
305 }),
306 ParamValue::Gradient(g) => {
307 let mut colors = LuaTable::default();
308 for stop in &g.stops {
309 let key = if stop.pos.fract() == 0.0 && stop.pos.abs() < 9_007_199_254_740_992.0 {
310 LuaKey::Index(stop.pos as i64)
311 } else {
312 LuaKey::Number(stop.pos)
313 };
314 colors.entries.push((
315 key,
316 LuaValue::Table(LuaTable {
317 tag: None,
318 entries: vec![
319 (LuaKey::Index(1), LuaValue::Number(stop.rgba[0] as f64)),
320 (LuaKey::Index(2), LuaValue::Number(stop.rgba[1] as f64)),
321 (LuaKey::Index(3), LuaValue::Number(stop.rgba[2] as f64)),
322 (LuaKey::Index(4), LuaValue::Number(stop.rgba[3] as f64)),
323 ],
324 }),
325 ));
326 }
327 LuaValue::Table(LuaTable {
328 tag: Some("Gradient".to_owned()),
329 entries: vec![(LuaKey::Str("Colors".to_owned()), LuaValue::Table(colors))],
330 })
331 }
332 ParamValue::Raw(raw) => raw.clone(),
333 }
334}
335
336fn user_control_default(raw: &LuaTable, name: &str) -> Option<ParamValue> {
337 let ut = raw.get_table("UserControls")?.get_table(name)?;
338 let is_point = ut.get_str("LINKID_DataType") == Some("Point")
339 || ut.get_str("INPID_InputControl") == Some("OffsetControl");
340 if is_point {
341 let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5);
342 let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5);
343 Some(ParamValue::Point([dx, dy]))
344 } else {
345 ut.get("INP_Default").map(parse_param_value)
346 }
347}
348
349pub(crate) fn is_group_kind(kind: &str) -> bool {
350 matches!(kind, "MacroOperator" | "GroupOperator")
351}
352
353/// `(inner_op, inner_port, default)` for each `InstanceInput` exposed by a Group/Macro tool table.
354fn instance_inputs(group: &LuaTable) -> impl Iterator<Item = (&str, &str, Option<ParamValue>)> {
355 group.get_table("Inputs").into_iter().flat_map(|inputs| {
356 inputs.entries.iter().filter_map(|(_, v)| {
357 let t = v.as_table()?;
358 Some((t.get_str("SourceOp")?, t.get_str("Source")?, t.get("Default").map(parse_param_value)))
359 })
360 })
361}
362
363/// Writes external wires connected to a Group/Macro node back onto the inner tool inputs that its
364/// `InstanceInput`s expose (load surfaces them as `node.inputs`).
365fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) {
366 let exposed: Vec<(String, String, String)> = group_tbl
367 .get_table("Inputs")
368 .map(|inputs| {
369 inputs
370 .entries
371 .iter()
372 .filter_map(|(k, v)| {
373 let LuaKey::Str(in_name) = k else { return None };
374 let t = v.as_table()?;
375 let port = if in_name.starts_with("MainInput") || in_name == "Input" {
376 "Input".to_owned()
377 } else {
378 in_name.clone()
379 };
380 Some((port, t.get_str("SourceOp")?.to_owned(), t.get_str("Source")?.to_owned()))
381 })
382 .collect()
383 })
384 .unwrap_or_default();
385 let Some(inner_tools) = group_tbl.get_table_mut("Tools") else { return };
386 for (port, inner_op, inner_port) in exposed {
387 let desired = node.inputs.get(&port);
388 // Still the raw InstanceInput binding: nothing was rewired.
389 if desired.is_some_and(|b| b.source_op.as_deref() == Some(inner_op.as_str())) {
390 continue;
391 }
392 let Some(inner_tbl) = find_raw_tool_mut(inner_tools, &inner_op) else { continue };
393 let current = inner_tbl
394 .get_table("Inputs")
395 .and_then(|i| i.get_table(&inner_port))
396 .map(parse_input_binding);
397 let wired = |b: &InputBinding| (b.source_op.clone(), b.source_output.clone());
398 match desired {
399 Some(b) if current.as_ref().map(wired) != Some(wired(b)) => {
400 let input = ensure_table_mut(ensure_table_mut(inner_tbl, "Inputs", None), &inner_port, Some("Input"));
401 for (key, val) in [("SourceOp", &b.source_op), ("Source", &b.source_output)] {
402 match val {
403 Some(v) => input.set(LuaKey::Str(key.to_owned()), LuaValue::String(v.clone())),
404 None => {
405 input.remove(&LuaKey::Str(key.to_owned()));
406 }
407 }
408 }
409 }
410 None if current.as_ref().is_some_and(|c| c.source_op.is_some()) => {
411 if let Some(input) = inner_tbl.get_table_mut("Inputs").and_then(|i| i.get_table_mut(&inner_port)) {
412 input.remove(&LuaKey::Str("SourceOp".to_owned()));
413 input.remove(&LuaKey::Str("Source".to_owned()));
414 }
415 }
416 _ => {}
417 }
418 }
419}
420
421fn sync_node_inputs(
422 node: &Node,
423 master_inputs: Option<&HashMap<String, InputBinding>>,
424 instance_defaults: &HashMap<(&str, &str), ParamValue>,
425 tool_tbl: &mut LuaTable,
426) {
427 // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`.
428 if let Some(in_tbl) = tool_tbl.get_table_mut("Inputs") {
429 in_tbl.entries.retain(|(k, v)| {
430 let LuaKey::Str(port) = k else { return true };
431 if v.as_table().is_none() {
432 return true;
433 }
434 node.inputs.contains_key(port)
435 });
436 }
437
438 // Collect sorted port names for deterministic output when appending new inputs.
439 let mut ports: Vec<&String> = node.inputs.keys().collect();
440 ports.sort();
441
442 for port in ports {
443 let binding = &node.inputs[port];
444 // Load fills unset inner-tool inputs from the enclosing group's `InstanceInput` default.
445 if binding.source_op.is_none()
446 && binding.expression.is_none()
447 && binding.value.is_some()
448 && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str()))
449 && tool_tbl
450 .get_table("Inputs")
451 .and_then(|i| i.get_table(port))
452 .is_none_or(|t| parse_input_binding(t).value.is_none())
453 {
454 continue;
455 }
456 let existing_binding = tool_tbl
457 .get_table("Inputs")
458 .and_then(|i| i.get_table(port))
459 .map(parse_input_binding);
460
461 if let Some(orig) = existing_binding {
462 if orig == *binding {
463 continue;
464 }
465 // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools.
466 if orig.value.is_none()
467 && orig.source_op.is_none()
468 && orig.expression.is_none()
469 && master_inputs.is_some_and(|m| m.get(port) == Some(binding))
470 {
471 continue;
472 }
473 let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None);
474 if let Some(it) = in_tbl.get_table_mut(port) {
475 if orig.source_op != binding.source_op {
476 match &binding.source_op {
477 Some(op) => it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())),
478 None => {
479 it.remove(&LuaKey::Str("SourceOp".to_owned()));
480 }
481 }
482 }
483 if orig.source_output != binding.source_output {
484 match &binding.source_output {
485 Some(src) => it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone())),
486 None => {
487 it.remove(&LuaKey::Str("Source".to_owned()));
488 }
489 }
490 }
491 if orig.expression != binding.expression {
492 match &binding.expression {
493 Some(expr) => it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone())),
494 None => {
495 it.remove(&LuaKey::Str("Expression".to_owned()));
496 }
497 }
498 }
499 if orig.value != binding.value {
500 match &binding.value {
501 Some(val) => it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val)),
502 None => {
503 it.remove(&LuaKey::Str("Value".to_owned()));
504 }
505 }
506 }
507 if it.entries.is_empty()
508 && binding.value.is_none()
509 && binding.source_op.is_none()
510 && binding.source_output.is_none()
511 && binding.expression.is_none()
512 {
513 in_tbl.remove(&LuaKey::Str(port.clone()));
514 }
515 }
516 } else {
517 // Port did not exist in raw `Inputs`.
518 if binding.value.is_none() && binding.source_op.is_none() && binding.expression.is_none() {
519 continue;
520 }
521 // Don't pollute `Inputs` with unedited `UserControls` defaults synthesized during load.
522 if binding.source_op.is_none()
523 && binding.expression.is_none()
524 && binding.value.is_some()
525 && binding.value == user_control_default(&node.raw, port)
526 {
527 continue;
528 }
529 // Don't duplicate inherited master inputs onto instanced tools.
530 if let Some(master) = master_inputs {
531 if master.get(port) == Some(binding) {
532 continue;
533 }
534 }
535
536 let mut it = LuaTable {
537 tag: Some("Input".to_owned()),
538 entries: Vec::new(),
539 };
540 if let Some(op) = &binding.source_op {
541 it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone()));
542 }
543 if let Some(src) = &binding.source_output {
544 it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone()));
545 }
546 if let Some(val) = &binding.value {
547 it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val));
548 }
549 if let Some(expr) = &binding.expression {
550 it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone()));
551 }
552 let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None);
553 in_tbl.set(LuaKey::Str(port.clone()), LuaValue::Table(it));
554 }
555 }
556}
557
558fn spline_color_lua(color: [u8; 3]) -> LuaValue {
559 LuaValue::Table(LuaTable {
560 tag: None,
561 entries: vec![
562 (LuaKey::Str("Red".to_owned()), LuaValue::Number(color[0] as f64)),
563 (LuaKey::Str("Green".to_owned()), LuaValue::Number(color[1] as f64)),
564 (LuaKey::Str("Blue".to_owned()), LuaValue::Number(color[2] as f64)),
565 ],
566 })
567}
568
569fn build_keyframes_table(spline: &BezierSpline) -> LuaTable {
570 let mut kfs = spline.keyframes.clone();
571 kfs.sort_by(|a, b| a.time.total_cmp(&b.time));
572 let mut tbl = LuaTable::default();
573 for kf in kfs {
574 let key = if kf.time.fract() == 0.0 && kf.time.abs() < 9_007_199_254_740_992.0 {
575 LuaKey::Index(kf.time as i64)
576 } else {
577 LuaKey::Number(kf.time)
578 };
579 let mut entry = LuaTable::default();
580 entry.entries.push((LuaKey::Index(1), LuaValue::Number(kf.value)));
581 if let Some([lx, ly]) = kf.lh {
582 entry.entries.push((LuaKey::Str("LH".to_owned()), vec2_lua(lx, ly)));
583 }
584 if let Some([rx, ry]) = kf.rh {
585 entry.entries.push((LuaKey::Str("RH".to_owned()), vec2_lua(rx, ry)));
586 }
587 let mut flags = LuaTable::default();
588 if kf.flags.linear {
589 flags.entries.push((LuaKey::Str("Linear".to_owned()), LuaValue::Bool(true)));
590 }
591 if kf.flags.step_in {
592 flags.entries.push((LuaKey::Str("StepIn".to_owned()), LuaValue::Bool(true)));
593 }
594 if kf.flags.step_out {
595 flags.entries.push((LuaKey::Str("StepOut".to_owned()), LuaValue::Bool(true)));
596 }
597 if kf.flags.loop_after {
598 flags.entries.push((LuaKey::Str("Loop".to_owned()), LuaValue::Bool(true)));
599 }
600 if kf.flags.loop_rel {
601 flags.entries.push((LuaKey::Str("LoopRel".to_owned()), LuaValue::Bool(true)));
602 }
603 if kf.flags.ping_pong {
604 flags.entries.push((LuaKey::Str("PingPong".to_owned()), LuaValue::Bool(true)));
605 }
606 if kf.flags.locked_y {
607 flags.entries.push((LuaKey::Str("LockedY".to_owned()), LuaValue::Bool(true)));
608 }
609 if !flags.entries.is_empty() {
610 entry.entries.push((LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags)));
611 }
612 tbl.entries.push((key, LuaValue::Table(entry)));
613 }
614 tbl
615}
616
617fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) {
618 let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl);
619 if existing.color != spline.color {
620 tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color));
621 }
622 let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && {
623 let mut normalized = existing.clone();
624 normalized.apply_hue_curves_cyclic_ends();
625 normalized.keyframes == spline.keyframes
626 };
627 if existing.keyframes != spline.keyframes && !unchanged_cyclic {
628 let new_kfs = LuaValue::Table(build_keyframes_table(spline));
629 if tbl.tag.as_deref() == Some("LUTBezier") && tbl.get_table("KeyColorSplines").is_some() {
630 if let Some(kcs) = tbl.get_table_mut("KeyColorSplines") {
631 kcs.set(LuaKey::Index(0), new_kfs);
632 }
633 } else {
634 tbl.set(LuaKey::Str("KeyFrames".to_owned()), new_kfs);
635 }
636 }
637}
crates/model/src/comp/tests.rs created+501
...@@ -0,0 +1,501 @@
1mod expression_modifier_tests {
2 use crate::comp::*;
3 use crate::expr::ExprEngine;
4
5 #[test]
6 fn evaluates_standalone_expression_modifier_number_and_chained() {
7 let src = r#"Composition {
8 Tools = ordered() {
9 XF1 = Transform {
10 Inputs = {
11 Angle = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", },
12 Size = Input { SourceOp = "HourHandExpr", Source = "NumberResult", },
13 },
14 },
15 Clock_MinHandExpr = Expression {
16 Inputs = {
17 n1 = Input { Value = 1, },
18 n2 = Input { SourceOp = "TimeSpline", Source = "Value", },
19 NumberExpression = Input { Value = "if(n1>0.5,floor(-n2)*30,-n2*30)", },
20 },
21 },
22 HourHandExpr = Expression {
23 Inputs = {
24 n1 = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", },
25 NumberExpression = Input { Value = "n1/12", },
26 },
27 },
28 TimeSpline = BezierSpline {
29 KeyFrames = {
30 [0] = { 0.0, Flags = { Linear = true } },
31 [10] = { 2.5, Flags = { Linear = true } },
32 },
33 },
34 },
35 }"#;
36
37 let comp = Comp::from_fusion_str(src).expect("parse comp");
38 assert!(comp.expression_modifiers.contains_key("Clock_MinHandExpr"));
39 assert!(comp.expression_modifiers.contains_key("HourHandExpr"));
40 // Expression modifiers are modifiers, not flow nodes
41 assert!(comp.find_node("Clock_MinHandExpr").is_none());
42
43 let expr = ExprEngine::new();
44 let xf = comp.node(comp.find_node("XF1").unwrap());
45 // At t=10: n2 = 2.5, floor(-2.5) = -3.0, -3.0 * 30 = -90.0
46 let angle = comp.eval_number(xf, "Angle", 10.0, 0.0, &expr);
47 assert!((angle - (-90.0)).abs() < 1e-6, "got {angle}");
48 // Chained HourHandExpr: n1 / 12 = -90 / 12 = -7.5
49 let size = comp.eval_number(xf, "Size", 10.0, 1.0, &expr);
50 assert!((size - (-7.5)).abs() < 1e-6, "got {size}");
51
52 // Lossless roundtrip preserves Expression modifiers
53 let saved = comp.to_fusion_string();
54 let reloaded = Comp::from_fusion_str(&saved).expect("reload");
55 let r_xf = reloaded.node(reloaded.find_node("XF1").unwrap());
56 assert!((reloaded.eval_number(r_xf, "Angle", 10.0, 0.0, &expr) - (-90.0)).abs() < 1e-6);
57 }
58
59 #[test]
60 fn evaluates_standalone_expression_modifier_point_and_dist_trig() {
61 let src = r#"Composition {
62 Tools = ordered() {
63 XF1 = Transform {
64 Inputs = {
65 Center = Input { SourceOp = "PtExpr", Source = "PointResult", },
66 Angle = Input { SourceOp = "TrigExpr", Source = "NumberResult", },
67 },
68 },
69 PtExpr = Expression {
70 Inputs = {
71 p1 = Input { Value = { 0.8, 0.2 }, },
72 n1 = Input { Value = 10, },
73 PointExpressionX = Input { Value = "if(p1x>0.5, 0.5 + time*dist(p1x,p1y,0.5,p1y)/n1, 0.5)", },
74 PointExpressionY = Input { Value = "-p1y + p1y*0.5 + 0.5", },
75 },
76 },
77 TrigExpr = Expression {
78 Inputs = {
79 NumberIn1 = Input { Value = 90, },
80 NumberExpression = Input { Value = "sin(n1) + cos(0) + (1/0)", },
81 },
82 },
83 },
84 }"#;
85
86 let comp = Comp::from_fusion_str(src).expect("parse comp");
87 let expr = ExprEngine::new();
88 let xf = comp.node(comp.find_node("XF1").unwrap());
89 // 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
90 let pt = comp.eval_point(xf, "Center", 5.0, [0.5, 0.5], &expr);
91 assert!((pt[0] - 0.65).abs() < 1e-6, "got x={}", pt[0]);
92 assert!((pt[1] - 0.40).abs() < 1e-6, "got y={}", pt[1]);
93 // sin(90 deg) + cos(0 deg) + safe_div(1,0) = 1 + 1 + 0 = 2.0
94 let ang = comp.eval_number(xf, "Angle", 0.0, 0.0, &expr);
95 assert!((ang - 2.0).abs() < 1e-6, "got {ang}");
96 }
97
98 #[test]
99 fn resolves_instanced_source_op_inheritance_chains_and_keeps_image_wires_isolated() {
100 let src = r#"Composition {
101 Tools = ordered() {
102 Loader1 = Loader {},
103 Transform2 = Transform {
104 Inputs = {
105 Input = Input { SourceOp = "Loader1", Source = "Output", },
106 },
107 },
108 Ellipse1 = EllipseMask {},
109 ColorCorrector1_6Blend = BezierSpline {
110 KeyFrames = {
111 [0] = { 0.25, Flags = { Linear = true } },
112 [10] = { 0.75, Flags = { Linear = true } },
113 },
114 },
115 ColorCorrector1_6 = ColorCorrector {
116 Inputs = {
117 Blend = Input { SourceOp = "ColorCorrector1_6Blend", Source = "Value", },
118 WheelTintAngle1 = Input { Value = -0.434283, },
119 WheelHue1 = Input { Value = 0.2, },
120 PreDividePostMultiply = Input { Value = 1, },
121 Input = Input { SourceOp = "Loader1", Source = "Output", },
122 EffectMask = Input { SourceOp = "Ellipse1", Source = "Mask", },
123 },
124 },
125 Instance_ColorCorrector1_6 = ColorCorrector {
126 SourceOp = "ColorCorrector1_6",
127 Inputs = {
128 Input = Input { SourceOp = "Transform2", Source = "Output", },
129 EffectMask = Input {},
130 WheelTintAngle1 = Input {},
131 WheelHue1 = Input { Value = 0.9, },
132 },
133 },
134 Instance_Chained = ColorCorrector {
135 SourceOp = "Instance_ColorCorrector1_6",
136 Inputs = {
137 Input = Input { SourceOp = "Loader1", Source = "Output", },
138 },
139 },
140 CycleA = Blur {
141 SourceOp = "CycleB",
142 Inputs = {
143 XBlurSize = Input { Value = 3.0, },
144 },
145 },
146 CycleB = Blur {
147 SourceOp = "CycleA",
148 Inputs = {
149 YBlurSize = Input { Value = 7.0, },
150 },
151 },
152 },
153 }"#;
154
155 let comp = Comp::from_fusion_str(src).expect("parse instanced comp");
156 let expr = ExprEngine::new();
157
158 let inst = comp.node(comp.find_node("Instance_ColorCorrector1_6").unwrap());
159 // Empty `WheelTintAngle1 = Input {}` is a de-instanced override (falls back to tool default),
160 // while omitted params (`Blend`, `PreDividePostMultiply`) inherit from master!
161 let tint = comp.eval_number(inst, "WheelTintAngle1", 0.0, 0.0, &expr);
162 assert!(tint.abs() < 1e-6, "de-instanced empty Input {{}} must not inherit master value, got {tint}");
163 let blend_t5 = comp.eval_number(inst, "Blend", 5.0, 1.0, &expr);
164 assert!((blend_t5 - 0.5).abs() < 1e-6, "got {blend_t5}");
165 let pdpm = comp.eval_number(inst, "PreDividePostMultiply", 0.0, 0.0, &expr);
166 assert!((pdpm - 1.0).abs() < 1e-6, "got {pdpm}");
167 // Keeps its own explicit override (`WheelHue1 = 0.9`) and its own `Input` wire (`Transform2`)!
168 let hue = comp.eval_number(inst, "WheelHue1", 0.0, 0.0, &expr);
169 assert!((hue - 0.9).abs() < 1e-6, "got {hue}");
170 assert_eq!(inst.connected_node("Input"), Some("Transform2"));
171 // NEVER inherits parent's `EffectMask` image/mask wire!
172 assert_eq!(inst.connected_node("EffectMask"), None);
173
174 // Chained inheritance (`Instance_Chained -> Instance_ColorCorrector1_6 -> ColorCorrector1_6`):
175 // nearest ancestor wins (`WheelHue1 = 0.9`, and `WheelTintAngle1` was de-instanced by parent),
176 // grandparent fills remaining omitted params (`Blend`, `PreDividePostMultiply`).
177 let chained = comp.node(comp.find_node("Instance_Chained").unwrap());
178 assert!((comp.eval_number(chained, "WheelHue1", 0.0, 0.0, &expr) - 0.9).abs() < 1e-6);
179 assert!(comp.eval_number(chained, "WheelTintAngle1", 0.0, 0.0, &expr).abs() < 1e-6);
180 assert!((comp.eval_number(chained, "Blend", 10.0, 0.0, &expr) - 0.75).abs() < 1e-6);
181 assert!((comp.eval_number(chained, "PreDividePostMultiply", 0.0, 0.0, &expr) - 1.0).abs() < 1e-6);
182 assert_eq!(chained.connected_node("Input"), Some("Loader1"));
183 assert_eq!(chained.connected_node("EffectMask"), None);
184
185 // Cycle safety (`CycleA <-> CycleB` terminates cleanly and cross-inherits missing params)
186 let cyc_a = comp.node(comp.find_node("CycleA").unwrap());
187 let cyc_b = comp.node(comp.find_node("CycleB").unwrap());
188 assert!((comp.eval_number(cyc_a, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6);
189 assert!((comp.eval_number(cyc_a, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6);
190 assert!((comp.eval_number(cyc_b, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6);
191 assert!((comp.eval_number(cyc_b, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6);
192
193 // Roundtrip preserves SourceOp inheritance and de-instanced `Input {}` overrides without duplicating master params
194 let saved = comp.to_fusion_string();
195 let reloaded = Comp::from_fusion_str(&saved).expect("reload");
196 let r_inst = reloaded.node(reloaded.find_node("Instance_ColorCorrector1_6").unwrap());
197 assert!(reloaded.eval_number(r_inst, "WheelTintAngle1", 0.0, 0.0, &expr).abs() < 1e-6);
198 assert!((reloaded.eval_number(r_inst, "Blend", 5.0, 1.0, &expr) - 0.5).abs() < 1e-6);
199 assert_eq!(r_inst.connected_node("EffectMask"), None);
200 }
201
202 #[test]
203 fn parses_styled_text_and_text_bezier_spline_keyframes() {
204 let src = r#"Composition {
205 Tools = ordered() {
206 Text_1 = TextPlus {
207 Inputs = {
208 StyledText = Input {
209 SourceOp = "Text_1StyledText",
210 Source = "Value",
211 },
212 },
213 },
214 Text_1StyledText = BezierSpline {
215 KeyFrames = {
216 [10] = { 0, Value = StyledText { Value = "first line" } },
217 [20] = { 1, Value = Text { Value = "second line" } },
218 },
219 },
220 },
221 }"#;
222 let comp = Comp::from_fusion_str(src).expect("parse styled text spline");
223 let expr = ExprEngine::new();
224 let node = comp.node(comp.find_node("Text_1").unwrap());
225 assert_eq!(comp.eval_text(node, "StyledText", 5.0, "", &expr), "first line");
226 assert_eq!(comp.eval_text(node, "StyledText", 10.0, "", &expr), "first line");
227 assert_eq!(comp.eval_text(node, "StyledText", 25.0, "", &expr), "second line");
228 }
229
230 #[test]
231 fn source_op_inherits_all_color_corrector_params_and_respects_blend_override() {
232 // Mirrors repro_seed_110: N4 inherits Wheel*/TintMode/*RGBGain/PreDividePostMultiply
233 // from N2 while keeping its own `Input` wire and `Blend = 0.75` override.
234 let src = r#"Composition {
235 Tools = ordered() {
236 S0 = Loader {},
237 S1 = DaySky {},
238 N2 = ColorCorrector {
239 Inputs = {
240 Input = Input { SourceOp = "S0", Source = "Output", },
241 WheelHue1 = Input { Value = -0.235, },
242 WheelSaturation1 = Input { Value = 0.65, },
243 WheelTintAngle1 = Input { Value = 0.323, },
244 WheelTintLength1 = Input { Value = 0.67, },
245 TintMode = Input { Value = 0, },
246 MasterRGBGain = Input { Value = 0.65, },
247 ShadowsRGBGain = Input { Value = 0.84, },
248 HighlightsRGBGain = Input { Value = 0.75, },
249 PreDividePostMultiply = Input { Value = 1, },
250 Blend = Input { Value = 1.0, },
251 },
252 },
253 N4 = ColorCorrector {
254 SourceOp = "N2",
255 Inputs = {
256 Input = Input { SourceOp = "S1", Source = "Output", },
257 Blend = Input { Value = 0.75, },
258 },
259 },
260 N5 = ColorCorrector {
261 SourceOp = "N2",
262 Inputs = {
263 Input = Input { SourceOp = "S1", Source = "Output", },
264 },
265 },
266 },
267 }"#;
268 let comp = Comp::from_fusion_str(src).expect("parse seed 110 style SourceOp");
269 let expr = ExprEngine::new();
270 let n4 = comp.node(comp.find_node("N4").unwrap());
271 assert_eq!(n4.connected_node("Input"), Some("S1"));
272 assert!((comp.eval_number(n4, "Blend", 1.0, 1.0, &expr) - 0.75).abs() < 1e-6);
273 assert!((comp.eval_number(n4, "WheelHue1", 1.0, 0.0, &expr) - (-0.235)).abs() < 1e-6);
274 assert!((comp.eval_number(n4, "WheelSaturation1", 1.0, 1.0, &expr) - 0.65).abs() < 1e-6);
275 assert!((comp.eval_number(n4, "WheelTintAngle1", 1.0, 0.0, &expr) - 0.323).abs() < 1e-6);
276 assert!((comp.eval_number(n4, "WheelTintLength1", 1.0, 0.0, &expr) - 0.67).abs() < 1e-6);
277 assert!((comp.eval_number(n4, "TintMode", 1.0, 2.0, &expr) - 0.0).abs() < 1e-6);
278 assert!((comp.eval_number(n4, "MasterRGBGain", 1.0, 1.0, &expr) - 0.65).abs() < 1e-6);
279 assert!((comp.eval_number(n4, "ShadowsRGBGain", 1.0, 1.0, &expr) - 0.84).abs() < 1e-6);
280 assert!((comp.eval_number(n4, "HighlightsRGBGain", 1.0, 1.0, &expr) - 0.75).abs() < 1e-6);
281 assert!((comp.eval_number(n4, "PreDividePostMultiply", 1.0, 0.0, &expr) - 1.0).abs() < 1e-6);
282
283 let n5 = comp.node(comp.find_node("N5").unwrap());
284 assert!((comp.eval_number(n5, "Blend", 1.0, 0.0, &expr) - 1.0).abs() < 1e-6);
285 }
286
287 #[test]
288 fn hue_curves_lut_bezier_applies_cyclic_ends_and_roundtrips_cleanly() {
289 let src = r#"Composition {
290 Tools = ordered() {
291 Bg = Background {},
292 HC_RSup = LUTBezier {
293 SmoothEndsTransition = true,
294 KeyColorSplines = {
295 [0] = {
296 [0] = { 0.5 },
297 [2] = { 1.0 },
298 [6] = { 0.5 },
299 }
300 },
301 },
302 CC_Red = LUTBezier {
303 SmoothEndsTransition = true,
304 KeyColorSplines = {
305 [0] = {
306 [0.0] = { 0.0 },
307 [0.5] = { 0.8 },
308 [1.0] = { 0.2 },
309 }
310 },
311 },
312 HC1 = HueCurves {
313 Inputs = {
314 Input = Input { SourceOp = "Bg", Source = "Output", },
315 RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", },
316 },
317 },
318 CC1 = ColorCurves {
319 Inputs = {
320 Input = Input { SourceOp = "Bg", Source = "Output", },
321 Red = Input { SourceOp = "CC_Red", Source = "Value", },
322 },
323 },
324 },
325 }"#;
326 let comp = Comp::from_fusion_str(src).expect("parse HueCurves + ColorCurves");
327 let rsup = comp.splines.get("HC_RSup").expect("HC_RSup");
328 assert!(rsup.keyframes[2].lh.is_some());
329 assert!((rsup.eval(5.0) - 0.4140625).abs() < 1e-3);
330
331 // ColorCurves [0..1] must NOT get cyclic HueCurves wrapping even with SmoothEndsTransition = true.
332 let cc_red = comp.splines.get("CC_Red").expect("CC_Red");
333 assert!((cc_red.eval(1.0) - 0.2).abs() < 1e-6);
334 assert!((cc_red.eval(0.75) - 0.5).abs() < 1e-6);
335
336 // Lossless roundtrip keeps KeyColorSplines untouched when unedited.
337 let saved = comp.to_fusion_string();
338 assert!(!saved.contains("LH ="));
339 let reloaded = Comp::from_fusion_str(&saved).expect("reload");
340 assert!((reloaded.splines["HC_RSup"].eval(5.0) - rsup.eval(5.0)).abs() < 1e-9);
341 }
342
343 #[test]
344 fn comp_eval_number_clamps_loop_spline_before_first_keyframe() {
345 let src = r#"Composition {
346 Tools = ordered() {
347 CG = ColorGain {
348 Inputs = {
349 HighHue = Input { SourceOp = "ColorGain1HighHue", Source = "Value", },
350 },
351 },
352 ColorGain1HighHue = BezierSpline {
353 KeyFrames = {
354 [4129] = { 0, RH = { 4137.66666666667, 0.333333333333333 }, Flags = { Linear = true, Loop = true } },
355 [4155] = { 1, LH = { 4146.33333333333, 0.666666666666667 }, Flags = { Linear = true, Loop = true } },
356 },
357 },
358 },
359 }"#;
360 let comp = Comp::from_fusion_str(src).expect("parse underwater loop spline");
361 let expr = ExprEngine::new();
362 let cg = comp.node(comp.find_node("CG").unwrap());
363 assert!((comp.eval_number(cg, "HighHue", 3933.0, 0.0, &expr) - 0.0).abs() < 1e-9);
364 assert!((comp.eval_number(cg, "HighHue", 4142.0, 0.0, &expr) - 0.5).abs() < 1e-9);
365 assert!((comp.eval_number(cg, "HighHue", 4155.0, 0.0, &expr) - 0.0).abs() < 1e-9);
366 assert!((comp.eval_number(cg, "HighHue", 4168.0, 0.0, &expr) - 0.5).abs() < 1e-9);
367 }
368
369 #[test]
370 fn cyclic_expression_references_terminate() {
371 let src = r#"Composition {
372 Tools = ordered() {
373 N = Transform {
374 Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, },
375 },
376 E = Expression {
377 Inputs = {
378 n1 = Input { Expression = "N.Size", },
379 NumberExpression = Input { Value = "n1 + 1", },
380 },
381 },
382 },
383 }"#;
384 let comp = Comp::from_fusion_str(src).unwrap();
385 let n = comp.node(comp.find_node("N").unwrap());
386 let v = comp.eval_number(n, "Size", 0.0, 7.0, &ExprEngine::new());
387 assert!(v.is_finite());
388 }
389
390 #[test]
391 fn clamp_with_inverted_bounds_does_not_panic() {
392 let src = r#"Composition {
393 Tools = ordered() {
394 N = Transform { Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, }, },
395 E = Expression {
396 Inputs = {
397 n1 = Input { Value = 5, },
398 NumberExpression = Input { Value = "clamp(n1, 1, 0)", },
399 },
400 },
401 },
402 }"#;
403 let comp = Comp::from_fusion_str(src).unwrap();
404 let n = comp.node(comp.find_node("N").unwrap());
405 assert_eq!(comp.eval_number(n, "Size", 0.0, 9.0, &ExprEngine::new()), 0.0);
406 }
407
408 #[test]
409 fn explicit_frame_format_is_never_overwritten_by_inferred_size() {
410 let tools = r#"Tools = ordered() {
411 BG = Background { Inputs = { Width = Input { Value = 1280, }, Height = Input { Value = 720, }, }, },
412 }"#;
413 let explicit = Comp::from_fusion_str(&format!(
414 "Composition {{ Prefs = {{ Comp = {{ FrameFormat = {{ Width = 1920, Height = 1080, }}, }}, }}, {tools} }}"
415 ))
416 .unwrap();
417 assert_eq!((explicit.width, explicit.height), (1920, 1080));
418
419 let inferred = Comp::from_fusion_str(&format!("Composition {{ {tools} }}")).unwrap();
420 assert_eq!((inferred.width, inferred.height), (1280, 720));
421 }
422
423 #[test]
424 fn each_loaded_comp_gets_a_distinct_revision_range() {
425 let src = "Composition { Tools = ordered() { } }";
426 let a = Comp::from_fusion_str(src).unwrap();
427 let mut b = Comp::from_fusion_str(src).unwrap();
428 for _ in 0..1000 {
429 b.revision += 1;
430 }
431 let c = Comp::from_fusion_str(src).unwrap();
432 assert!(a.revision != b.revision && b.revision != c.revision && a.revision != c.revision);
433 assert!(c.revision > b.revision);
434 }
435
436 const GROUP_COMP: &str = r#"Composition {
437 Tools = ordered() {
438 BG = Background { },
439 BG2 = Background { },
440 Group1 = GroupOperator {
441 Inputs = {
442 MainInput1 = InstanceInput { SourceOp = "Inner1", Source = "Input", },
443 BlurSize = InstanceInput { SourceOp = "Inner1", Source = "XBlurSize", Default = 3, },
444 },
445 Outputs = {
446 MainOutput1 = InstanceOutput { SourceOp = "Inner2", Source = "Output", },
447 },
448 Tools = ordered() {
449 Inner1 = Blur {
450 Inputs = {
451 Input = Input { SourceOp = "BG", Source = "Output", },
452 },
453 },
454 Inner2 = Transform {
455 Inputs = {
456 Input = Input { SourceOp = "Inner1", Source = "Output", },
457 Size = Input { Value = 1, },
458 },
459 },
460 Inner3 = Blur { },
461 },
462 },
463 },
464}"#;
465
466 #[test]
467 fn unedited_group_roundtrips_byte_for_byte() {
468 let comp = Comp::from_fusion_str(GROUP_COMP).unwrap();
469 let tools = |t: &LuaTable| t.get_table("Tools").unwrap().to_fusion_string();
470 assert_eq!(tools(&comp.sync_to_raw_ast()), tools(comp.raw_root.as_ref().unwrap()));
471 }
472
473 #[test]
474 fn nested_group_edits_and_wiring_survive_save() {
475 let mut comp = Comp::from_fusion_str(GROUP_COMP).unwrap();
476 let group = comp.find_node("Group1").unwrap();
477 assert_eq!(comp.node(group).connected_node("Input"), Some("BG"));
478
479 comp.delete_nodes(&[comp.find_node("Inner3").unwrap()]);
480 let inner2 = comp.find_node("Inner2").unwrap();
481 assert!(comp.set_input_value(inner2, "Size", ParamValue::Number(2.5)));
482 let (group, bg2) = (comp.find_node("Group1").unwrap(), comp.find_node("BG2").unwrap());
483 comp.connect_output(bg2, "Output", group, "Input").unwrap();
484
485 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
486 let inner2 = saved.node(saved.find_node("Inner2").unwrap());
487 assert_eq!(inner2.static_number("Size"), Some(2.5));
488 assert!(saved.find_node("Inner3").is_none());
489 assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), Some("BG2"));
490 assert_eq!(saved.node(saved.find_node("Group1").unwrap()).connected_node("Input"), Some("BG2"));
491 // The exposed `Default` stays on the InstanceInput instead of leaking onto Inner1.
492 let text = comp.to_fusion_string();
493 assert_eq!(text.matches("Value = 3").count(), 0, "{text}");
494
495 let mut comp = saved;
496 let group = comp.find_node("Group1").unwrap();
497 assert!(comp.disconnect(group, "Input"));
498 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
499 assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), None);
500 }
501}
crates/model/src/edit.rs+19-1803
...@@ -1,23 +1,28 @@...@@ -1,23 +1,28 @@
1//! Lossless graph & parameter mutation API for `Comp`, plus `CompHistory` undo/redo stack.1//! Lossless graph & parameter mutation API for `Comp`, plus `CompHistory` undo/redo stack.
22
3mod clipboard;
4mod defaults;
5mod history;
6mod keyframes;
7#[cfg(test)]
8mod tests;
9
10pub use history::{CompHistory, DEFAULT_MAX_HISTORY};
11
12use clipboard::{rename_expression_idents, rewrite_formulas_deep};
13use defaults::{default_inputs_for_kind, default_view_info_for_kind};
3use crate::comp::{14use crate::comp::{
4 Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut,15 Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut,
5 find_raw_tool, find_raw_tool_mut, is_group_kind, is_modifier_type, param_value_to_lua, vec2_lua,16 find_raw_tool, find_raw_tool_mut, is_group_kind, is_modifier_type, param_value_to_lua, vec2_lua,
6};17};
7use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident, parse_lua};18use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident};
8use crate::spline::{BezierSpline, Keyframe};
9use std::collections::{HashMap, HashSet, VecDeque};19use std::collections::{HashMap, HashSet, VecDeque};
1020
11/// Default maximum number of undo steps retained by [`CompHistory`].
12pub const DEFAULT_MAX_HISTORY: usize = 128;
13
14/// Keyframe times closer than this are the same keyframe (matches the Inspector's `keyframe_state`).
15const KEYFRAME_EPS: f64 = 1e-4;
16
17/// Expression-modifier inputs whose `Value` is a formula string.21/// Expression-modifier inputs whose `Value` is a formula string.
18const EXPRESSION_FORMULA_INPUTS: &[&str] =22pub(super) const EXPRESSION_FORMULA_INPUTS: &[&str] =
19 &["NumberExpression", "PointExpressionX", "PointExpressionY", "PointExpression"];23 &["NumberExpression", "PointExpressionX", "PointExpressionY", "PointExpression"];
2024
25
21impl Comp {26impl Comp {
22 fn modifier_exists(&self, name: &str) -> bool {27 fn modifier_exists(&self, name: &str) -> bool {
23 self.splines.contains_key(name)28 self.splines.contains_key(name)
...@@ -367,182 +372,7 @@ impl Comp {...@@ -367,182 +372,7 @@ impl Comp {
367372
368 /// Serializes `ids` plus every modifier (spline, path, shake, ...) they reference into373 /// Serializes `ids` plus every modifier (spline, path, shake, ...) they reference into
369 /// Fusion's clipboard format: `{ Tools = ordered() { ... }, ActiveTool = "<first>" }`.374 /// Fusion's clipboard format: `{ Tools = ordered() { ... }, ActiveTool = "<first>" }`.
370 /// References to unselected nodes are kept verbatim and dropped again on paste if missing.
371 pub fn export_fusion_clipboard(&self, ids: &[NodeId]) -> String {
372 let synced = self.sync_to_raw_ast();
373 let root_tools = synced.get_table("Tools");
374 let node_names: HashSet<&str> = self.nodes.iter().map(|n| n.name.as_str()).collect();
375
376 let mut picked: Vec<&Node> = Vec::new();
377 for &id in ids {
378 if let Some(n) = self.nodes.get(id.0) {
379 if !picked.iter().any(|p| p.id == n.id) {
380 picked.push(n);
381 }
382 }
383 }
384 let mut tools = LuaTable {
385 tag: Some("ordered".to_owned()),
386 entries: Vec::new(),
387 };
388 let mut refs: VecDeque<String> = VecDeque::new();
389 for n in &picked {
390 let raw = root_tools.and_then(|t| find_raw_tool(t, &n.name)).unwrap_or(&n.raw);
391 let mut found = HashSet::new();
392 collect_source_ops_in_table(raw, &mut found);
393 let mut found: Vec<String> = found.into_iter().collect();
394 found.sort();
395 refs.extend(found);
396 tools.set(LuaKey::Str(n.name.clone()), LuaValue::Table(raw.clone()));
397 }
398 while let Some(name) = refs.pop_front() {
399 if tools.get(&name).is_some() || node_names.contains(name.as_str()) {
400 continue;
401 }
402 // Modifiers already nested inside a copied group travel with it.
403 let nested_in_copy = tools
404 .entries
405 .iter()
406 .filter_map(|(_, v)| v.as_table()?.get_table("Tools"))
407 .any(|inner| find_raw_tool(inner, &name).is_some());
408 let Some(modifier) = root_tools.and_then(|t| find_raw_tool(t, &name)).filter(|_| !nested_in_copy)
409 else {
410 continue;
411 };
412 let mut found = HashSet::new();
413 collect_source_ops_in_table(modifier, &mut found);
414 let mut found: Vec<String> = found.into_iter().collect();
415 found.sort();
416 refs.extend(found);
417 tools.set(LuaKey::Str(name), LuaValue::Table(modifier.clone()));
418 }
419
420 let mut doc = LuaTable::default();
421 doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools));
422 if let Some(first) = picked.first() {
423 doc.set(
424 LuaKey::Str("ActiveTool".to_owned()),
425 LuaValue::String(first.name.clone()),
426 );
427 }
428 doc.to_fusion_string()
429 }
430
431 /// Pastes Fusion clipboard Lua (`{ Tools = ordered() { ... } }` or a full `Composition`),
432 /// renaming colliding tools/modifiers (`Blur1` -> `Blur1_1`), rewiring references among the
433 /// pasted tools, dropping references to tools that exist nowhere, and shifting each top-level
434 /// tool's `ViewInfo.Pos` by `offset`. Returns the new top-level flow nodes; on `Err` the comp
435 /// is untouched. Prefer [`CompHistory::paste_fusion_clipboard`] for an undoable paste.
436 pub fn paste_fusion_clipboard(
437 &mut self,
438 lua_snippet: &str,
439 offset: (f32, f32),
440 ) -> Result<Vec<NodeId>, String> {
441 let parsed = parse_lua(lua_snippet).map_err(|e| format!("clipboard is not Fusion Lua: {e}"))?;
442 let mut tools = parsed
443 .as_table()
444 .and_then(|t| t.get_table("Tools"))
445 .filter(|t| !t.entries.is_empty())
446 .cloned()
447 .ok_or_else(|| "clipboard has no Fusion tools".to_owned())?;
448
449 let mut pasted_names = Vec::new();
450 collect_tool_names(&tools, &mut pasted_names);
451 let pasted_set: HashSet<&str> = pasted_names.iter().map(String::as_str).collect();
452
453 drop_unknown_source_ops(&mut tools, &mut |name| {
454 pasted_set.contains(name) || self.is_linkable_external(name)
455 });
456
457 let mut reserved: HashSet<String> = self.nodes.iter().map(|n| n.name.clone()).collect();
458 let mut renames: HashMap<String, String> = HashMap::new();
459 for name in &pasted_names {
460 if renames.contains_key(name) {
461 continue;
462 }
463 let fresh = self.generate_unique_name_excluding(name, &reserved);
464 reserved.insert(fresh.clone());
465 renames.insert(name.clone(), fresh);
466 }
467 rename_tools(&mut tools, &renames);
468
469 let mut doc = LuaTable {
470 tag: Some("Composition".to_owned()),
471 entries: Vec::new(),
472 };
473 doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools));
474 let staged = Comp::from_fusion_str(&doc.to_fusion_string())
475 .map_err(|e| format!("clipboard tools failed to parse: {e}"))?;
476 let Some(staged_tools) = doc.get_table("Tools") else {
477 return Err("clipboard has no Fusion tools".to_owned());
478 };
479
480 let base = self.nodes.len();
481 let shift = |id: NodeId| NodeId(base + id.0);
482 let mut created = Vec::new();
483 let mut top_level: HashMap<String, LuaTable> = HashMap::new();
484 for mut node in staged.nodes {
485 node.id = shift(node.id);
486 node.macro_output = node.macro_output.map(shift);
487 if !node.internal {
488 node.pos = [node.pos[0] + offset.0, node.pos[1] + offset.1];
489 set_view_info_pos(&mut node.raw, node.pos);
490 top_level.insert(node.name.clone(), node.raw.clone());
491 created.push(node.id);
492 }
493 self.nodes.push(node);
494 }
495 for (name, id) in staged.node_by_name {
496 self.node_by_name.entry(name).or_insert(shift(id));
497 }
498 self.splines.extend(staged.splines);
499 self.poly_paths.extend(staged.poly_paths);
500 self.gradient_modifiers.extend(staged.gradient_modifiers);
501 self.text_modifiers.extend(staged.text_modifiers);
502 self.text_splines.extend(staged.text_splines);
503 self.polyline_splines.extend(staged.polyline_splines);
504 self.text_cls.extend(staged.text_cls);
505 self.shakes.extend(staged.shakes);
506 self.expression_modifiers.extend(staged.expression_modifiers);
507
508 if let Some(root) = self.raw_root.as_mut() {
509 let dest = ensure_table_mut(root, "Tools", Some("ordered"));
510 for (key, value) in &staged_tools.entries {
511 let LuaKey::Str(name) = key else { continue };
512 let table = top_level.remove(name).map_or_else(|| value.clone(), LuaValue::Table);
513 dest.set(key.clone(), table);
514 }
515 }
516
517 self.revision += 1;
518 Ok(created)
519 }
520
521 /// Duplicates the selected nodes at `pos + offset` with unique names, as a copy + paste:
522 /// wires between duplicated nodes are preserved, wires to other nodes stay intact, and owned
523 /// modifiers and group contents are cloned. Returns the new top-level nodes.
524 pub fn duplicate_nodes(&mut self, ids: &[NodeId], offset: [f32; 2]) -> Vec<NodeId> {
525 let snippet = self.export_fusion_clipboard(ids);
526 self.paste_fusion_clipboard(&snippet, (offset[0], offset[1])).unwrap_or_default()
527 }
528
529 fn generate_unique_name_excluding(&self, hint: &str, reserved: &HashSet<String>) -> String {
530 let base = sanitize_lua_ident(hint);
531 if !self.name_exists(&base) && !reserved.contains(&base) {
532 return base;
533 }
534 let mut idx = 1usize;
535 loop {
536 let candidate = format!("{base}_{idx}");
537 if !self.name_exists(&candidate) && !reserved.contains(&candidate) {
538 return candidate;
539 }
540 idx += 1;
541 }
542 }
543375
544 /// Renames `id` to `new_name`, updating `node_by_name`, `raw_root.Tools`, and all `SourceOp`
545 /// references across every node's `inputs`, `raw` AST tables, and `raw_root`.
546 pub fn rename_node(&mut self, id: NodeId, new_name: &str) -> Result<String, String> {376 pub fn rename_node(&mut self, id: NodeId, new_name: &str) -> Result<String, String> {
547 if id.0 >= self.nodes.len() {377 if id.0 >= self.nodes.len() {
548 return Err(format!("invalid node id {}", id.0));378 return Err(format!("invalid node id {}", id.0));
...@@ -895,410 +725,9 @@ impl Comp {...@@ -895,410 +725,9 @@ impl Comp {
895 set_view_info_pos(&mut n.raw, pos);725 set_view_info_pos(&mut n.raw, pos);
896 self.revision += 1;726 self.revision += 1;
897 }727 }
898
899 /// Inserts or updates a scalar keyframe at `(frame, value)` on `node`'s `input`.
900 /// - If `input` is already connected to a `BezierSpline`, updates/inserts the keyframe there.
901 /// - Otherwise creates a new `BezierSpline` named `<NodeName><InputName>` (deduplicated),
902 /// wires `input` to it (`SourceOp = spline_name, Source = "Value"`), and inserts the keyframe.
903 /// Returns the spline's name.
904 pub fn set_keyframe(
905 &mut self,
906 node: NodeId,
907 input: &str,
908 frame: f64,
909 value: f64,
910 ) -> Result<String, String> {
911 if node.0 >= self.nodes.len() {
912 return Err(format!("invalid node id {}", node.0));
913 }
914 if !frame.is_finite() || !value.is_finite() {
915 return Err("keyframe frame and value must be finite numbers".to_owned());
916 }
917
918 let existing_spline = self.nodes[node.0]
919 .inputs
920 .get(input)
921 .and_then(|b| b.source_op.clone())
922 .filter(|op| self.splines.contains_key(op));
923
924 let spline_name = if let Some(sp_name) = existing_spline {
925 let sp = self.splines.get_mut(&sp_name).expect("spline exists");
926 upsert_keyframe(sp, frame, value);
927 sp_name
928 } else {
929 let hint = format!("{}{}", self.nodes[node.0].name, input);
930 let sp_name = self.generate_unique_name("BezierSpline", Some(&hint));
931 let color = default_spline_color(&sp_name);
932 let spline = BezierSpline {
933 name: sp_name.clone(),
934 color,
935 keyframes: vec![Keyframe::new(frame, value)],
936 };
937 self.splines.insert(sp_name.clone(), spline);
938
939 let n = &mut self.nodes[node.0];
940 let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding {
941 value: None,
942 source_op: None,
943 source_output: None,
944 expression: None,
945 });
946 entry.source_op = Some(sp_name.clone());
947 entry.source_output = Some("Value".to_owned());
948
949 let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None);
950 let port_tbl = ensure_table_mut(in_tbl, input, Some("Input"));
951 port_tbl.set(
952 LuaKey::Str("SourceOp".to_owned()),
953 LuaValue::String(sp_name.clone()),
954 );
955 port_tbl.set(
956 LuaKey::Str("Source".to_owned()),
957 LuaValue::String("Value".to_owned()),
958 );
959
960 sp_name
961 };
962
963 self.revision += 1;
964 Ok(spline_name)
965 }
966
967 /// Removes the keyframe at `frame` from `spline_name`. Returns `true` if a keyframe was deleted.
968 /// Deleting a spline's last keyframe removes the spline and leaves every input it drove with
969 /// that keyframe's value as a static `Value`.
970 pub fn delete_keyframe(&mut self, spline_name: &str, frame: f64) -> bool {
971 let Some(sp) = self.splines.get_mut(spline_name) else {
972 return false;
973 };
974 let Some(pos) = sp
975 .keyframes
976 .iter()
977 .position(|kf| (kf.time - frame).abs() < KEYFRAME_EPS)
978 else {
979 return false;
980 };
981 let removed = sp.keyframes.remove(pos);
982 if sp.keyframes.is_empty() {
983 self.splines.remove(spline_name);
984 let value = ParamValue::Number(removed.value);
985 for node in &mut self.nodes {
986 for (port, binding) in &mut node.inputs {
987 if binding.source_op.as_deref() != Some(spline_name) {
988 continue;
989 }
990 binding.source_op = None;
991 binding.source_output = None;
992 binding.value = Some(value.clone());
993 let port_tbl = ensure_table_mut(ensure_table_mut(&mut node.raw, "Inputs", None), port, Some("Input"));
994 port_tbl.remove(&LuaKey::Str("SourceOp".to_owned()));
995 port_tbl.remove(&LuaKey::Str("Source".to_owned()));
996 port_tbl.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&value));
997 }
998 }
999 if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) {
1000 remove_tools_recursive(tools, &HashSet::from([spline_name.to_owned()]));
1001 }
1002 }
1003 self.revision += 1;
1004 true
1005 }
1006}
1007
1008#[derive(Clone, Debug)]
1009struct HistoryEntry {
1010 label: String,
1011 snapshot: Comp,
1012 coalesce_key: Option<String>,
1013}
1014
1015/// Snapshot-based undo/redo history stack for [`Comp`] with transaction groups and drag coalescing.
1016#[derive(Clone, Debug)]
1017pub struct CompHistory {
1018 undo_stack: VecDeque<HistoryEntry>,
1019 redo_stack: Vec<HistoryEntry>,
1020 max_depth: usize,
1021 active_group: Option<(String, Comp)>,
1022 group_depth: usize,
1023 /// Position in `undo_stack` corresponding to the last saved state (`Some(0)` means clean at
1024 /// depth 0; `None` means the saved state is no longer reachable via undo/redo).
1025 saved_undo_depth: Option<usize>,
1026 saved_revision: Option<u64>,
1027}
1028
1029impl Default for CompHistory {
1030 fn default() -> Self {
1031 Self::new()
1032 }
1033}
1034
1035impl CompHistory {
1036 pub fn new() -> Self {
1037 Self::with_max_depth(DEFAULT_MAX_HISTORY)
1038 }
1039
1040 pub fn with_max_depth(max_depth: usize) -> Self {
1041 Self {
1042 undo_stack: VecDeque::new(),
1043 redo_stack: Vec::new(),
1044 max_depth: max_depth.max(1),
1045 active_group: None,
1046 group_depth: 0,
1047 saved_undo_depth: None,
1048 saved_revision: None,
1049 }
1050 }
1051
1052 pub fn max_depth(&self) -> usize {
1053 self.max_depth
1054 }
1055
1056 pub fn can_undo(&self) -> bool {
1057 !self.undo_stack.is_empty()
1058 }
1059
1060 pub fn can_redo(&self) -> bool {
1061 !self.redo_stack.is_empty()
1062 }
1063
1064 pub fn undo_len(&self) -> usize {
1065 self.undo_stack.len()
1066 }
1067
1068 pub fn redo_len(&self) -> usize {
1069 self.redo_stack.len()
1070 }
1071
1072 pub fn undo_label(&self) -> Option<&str> {
1073 self.undo_stack.back().map(|e| e.label.as_str())
1074 }
1075
1076 pub fn redo_label(&self) -> Option<&str> {
1077 self.redo_stack.last().map(|e| e.label.as_str())
1078 }
1079
1080 pub fn in_group(&self) -> bool {
1081 self.group_depth > 0
1082 }
1083
1084 /// Clears all undo/redo entries and any active transaction group.
1085 pub fn clear(&mut self) {
1086 self.undo_stack.clear();
1087 self.redo_stack.clear();
1088 self.active_group = None;
1089 self.group_depth = 0;
1090 self.saved_undo_depth = None;
1091 self.saved_revision = None;
1092 }
1093
1094 /// Records the current state of `comp` as the clean saved point.
1095 pub fn mark_saved(&mut self, comp: &Comp) {
1096 // Edits after a save must never coalesce into the saved undo entry.
1097 self.break_coalescing();
1098 self.saved_undo_depth = Some(self.undo_stack.len());
1099 self.saved_revision = Some(comp.revision);
1100 }
1101
1102 pub fn saved_revision(&self) -> Option<u64> {
1103 self.saved_revision
1104 }
1105
1106 /// Returns `true` if `comp` has unsaved modifications relative to the last [`Self::mark_saved`].
1107 pub fn is_dirty(&self, comp: &Comp) -> bool {
1108 match self.saved_undo_depth {
1109 Some(depth) if depth == self.undo_stack.len() => {
1110 // If an edit was pushed via coalescing or outside history after mark_saved,
1111 // check whether we're still at the saved depth without an active modified group.
1112 if let Some((_, ref snap)) = self.active_group {
1113 comp.revision != snap.revision
1114 } else {
1115 false
1116 }
1117 }
1118 _ => self.saved_revision != Some(comp.revision),
1119 }
1120 }
1121
1122 /// Pushes a snapshot of `comp` BEFORE applying a discrete mutation.
1123 /// No-op if currently inside a [`Self::begin_group`] transaction.
1124 pub fn push_snapshot(&mut self, comp: &Comp, label: impl Into<String>) {
1125 if self.group_depth > 0 {
1126 return;
1127 }
1128 self.push_entry(HistoryEntry {
1129 label: label.into(),
1130 snapshot: comp.clone(),
1131 coalesce_key: None,
1132 });
1133 }
1134
1135 /// Pushes a snapshot of `comp` BEFORE applying a continuous mutation (such as dragging a node
1136 /// or scrubbing a parameter slider). Consecutive calls with the same `key` coalesce into a
1137 /// single undo step preserving the initial pre-drag snapshot.
1138 /// No-op if currently inside a [`Self::begin_group`] transaction.
1139 pub fn push_coalesced(
1140 &mut self,
1141 comp: &Comp,
1142 label: impl Into<String>,
1143 key: impl Into<String>,
1144 ) {
1145 if self.group_depth > 0 {
1146 return;
1147 }
1148 let key_str = key.into();
1149 let label_str = label.into();
1150 if self.redo_stack.is_empty() {
1151 if let Some(top) = self.undo_stack.back_mut() {
1152 if top.coalesce_key.as_deref() == Some(key_str.as_str()) {
1153 top.label = label_str;
1154 return;
1155 }
1156 }
1157 }
1158 self.push_entry(HistoryEntry {
1159 label: label_str,
1160 snapshot: comp.clone(),
1161 coalesce_key: Some(key_str),
1162 });
1163 }
1164
1165 /// Breaks coalescing on the top undo entry so subsequent edits with the same key start a new
1166 /// undo step (e.g. on pointer release).
1167 pub fn break_coalescing(&mut self) {
1168 if let Some(top) = self.undo_stack.back_mut() {
1169 top.coalesce_key = None;
1170 }
1171 }
1172
1173 /// Begins a transaction group. All mutations until the matching [`Self::commit_group`] collapse
1174 /// into a single undo step. Supports nesting.
1175 pub fn begin_group(&mut self, comp: &Comp, label: impl Into<String>) {
1176 if self.group_depth == 0 {
1177 self.active_group = Some((label.into(), comp.clone()));
1178 }
1179 self.group_depth += 1;
1180 }
1181
1182 /// Commits the current transaction group. When the outermost group closes, pushes one undo
1183 /// entry if `comp.revision` changed since `begin_group`. Returns `true` if an entry was added.
1184 pub fn commit_group(&mut self, comp: &Comp) -> bool {
1185 if self.group_depth == 0 {
1186 return false;
1187 }
1188 self.group_depth -= 1;
1189 if self.group_depth > 0 {
1190 return false;
1191 }
1192 let Some((label, snapshot)) = self.active_group.take() else {
1193 return false;
1194 };
1195 if comp.revision == snapshot.revision {
1196 return false;
1197 }
1198 self.push_entry(HistoryEntry {
1199 label,
1200 snapshot,
1201 coalesce_key: None,
1202 });
1203 true
1204 }
1205
1206 /// Cancels the active transaction group and restores `comp` to its pre-group state.
1207 pub fn cancel_group(&mut self, comp: &mut Comp) -> bool {
1208 if self.group_depth == 0 {
1209 return false;
1210 }
1211 self.group_depth = 0;
1212 let Some((_, snapshot)) = self.active_group.take() else {
1213 return false;
1214 };
1215 let prev_rev = comp.revision;
1216 restore_snapshot(comp, snapshot);
1217 if comp.revision != prev_rev {
1218 comp.revision = prev_rev.max(comp.revision) + 1;
1219 }
1220 true
1221 }
1222
1223 /// Undoable [`Comp::paste_fusion_clipboard`]: the whole paste is one undo step, and a failed
1224 /// paste leaves both `comp` and the history untouched.
1225 pub fn paste_fusion_clipboard(
1226 &mut self,
1227 comp: &mut Comp,
1228 lua_snippet: &str,
1229 offset: (f32, f32),
1230 ) -> Result<Vec<NodeId>, String> {
1231 self.begin_group(comp, "Paste");
1232 let pasted = comp.paste_fusion_clipboard(lua_snippet, offset);
1233 self.commit_group(comp);
1234 pasted
1235 }
1236
1237 /// Undoes the most recent edit, restoring `comp` to the saved snapshot.
1238 /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly.
1239 pub fn undo(&mut self, comp: &mut Comp) -> bool {
1240 if self.group_depth > 0 {
1241 self.group_depth = 1;
1242 self.commit_group(comp);
1243 }
1244 let Some(entry) = self.undo_stack.pop_back() else {
1245 return false;
1246 };
1247 let prev_rev = comp.revision;
1248 let redo_entry = HistoryEntry {
1249 label: entry.label,
1250 snapshot: comp.clone(),
1251 coalesce_key: None,
1252 };
1253 self.redo_stack.push(redo_entry);
1254 restore_snapshot(comp, entry.snapshot);
1255 comp.revision = prev_rev.max(comp.revision) + 1;
1256 true
1257 }
1258
1259 /// Redoes the most recently undone edit.
1260 /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly.
1261 pub fn redo(&mut self, comp: &mut Comp) -> bool {
1262 let Some(entry) = self.redo_stack.pop() else {
1263 return false;
1264 };
1265 let prev_rev = comp.revision;
1266 let undo_entry = HistoryEntry {
1267 label: entry.label,
1268 snapshot: comp.clone(),
1269 coalesce_key: None,
1270 };
1271 self.undo_stack.push_back(undo_entry);
1272 restore_snapshot(comp, entry.snapshot);
1273 comp.revision = prev_rev.max(comp.revision) + 1;
1274 true
1275 }
1276
1277 fn push_entry(&mut self, entry: HistoryEntry) {
1278 // Any saved state that lived in the redo branch is now unreachable.
1279 if let Some(saved_depth) = self.saved_undo_depth {
1280 if saved_depth > self.undo_stack.len() {
1281 self.saved_undo_depth = None;
1282 }
1283 }
1284 self.redo_stack.clear();
1285 self.undo_stack.push_back(entry);
1286 while self.undo_stack.len() > self.max_depth {
1287 self.undo_stack.pop_front();
1288 self.saved_undo_depth = self.saved_undo_depth.and_then(|d| d.checked_sub(1));
1289 }
1290 }
1291}728}
1292729
1293/// Replaces `comp` with `snapshot`, keeping the live file identity so a Save As followed by undo730pub(super) fn sanitize_lua_ident(raw: &str) -> String {
1294/// never points Save at the file the snapshot came from.
1295fn restore_snapshot(comp: &mut Comp, mut snapshot: Comp) {
1296 snapshot.path = comp.path.take();
1297 snapshot.name = std::mem::take(&mut comp.name);
1298 *comp = snapshot;
1299}
1300
1301fn sanitize_lua_ident(raw: &str) -> String {
1302 let mut out = String::with_capacity(raw.len());731 let mut out = String::with_capacity(raw.len());
1303 for ch in raw.chars() {732 for ch in raw.chars() {
1304 if ch.is_ascii_alphanumeric() || ch == '_' {733 if ch.is_ascii_alphanumeric() || ch == '_' {
...@@ -1316,7 +745,7 @@ fn sanitize_lua_ident(raw: &str) -> String {...@@ -1316,7 +745,7 @@ fn sanitize_lua_ident(raw: &str) -> String {
1316 out745 out
1317}746}
1318747
1319fn collect_node_source_ops(node: &Node, out: &mut HashSet<String>) {748pub(super) fn collect_node_source_ops(node: &Node, out: &mut HashSet<String>) {
1320 for binding in node.inputs.values() {749 for binding in node.inputs.values() {
1321 if let Some(src) = &binding.source_op {750 if let Some(src) = &binding.source_op {
1322 out.insert(src.clone());751 out.insert(src.clone());
...@@ -1325,7 +754,7 @@ fn collect_node_source_ops(node: &Node, out: &mut HashSet<String>) {...@@ -1325,7 +754,7 @@ fn collect_node_source_ops(node: &Node, out: &mut HashSet<String>) {
1325 collect_source_ops_in_table(&node.raw, out);754 collect_source_ops_in_table(&node.raw, out);
1326}755}
1327756
1328fn collect_source_ops_in_table(tbl: &LuaTable, out: &mut HashSet<String>) {757pub(super) fn collect_source_ops_in_table(tbl: &LuaTable, out: &mut HashSet<String>) {
1329 for (k, v) in &tbl.entries {758 for (k, v) in &tbl.entries {
1330 if let LuaKey::Str(key) = k {759 if let LuaKey::Str(key) = k {
1331 if key == "SourceOp" {760 if key == "SourceOp" {
...@@ -1376,7 +805,7 @@ fn count_flow_tools<'a>(tools: &'a LuaTable, out: &mut HashMap<&'a str, usize>)...@@ -1376,7 +805,7 @@ fn count_flow_tools<'a>(tools: &'a LuaTable, out: &mut HashMap<&'a str, usize>)
1376}805}
1377806
1378/// Removes tools named in `names` from `tools` and every nested `Tools` table.807/// Removes tools named in `names` from `tools` and every nested `Tools` table.
1379fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet<String>) {808pub(super) fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet<String>) {
1380 tools809 tools
1381 .entries810 .entries
1382 .retain(|(k, _)| !matches!(k, LuaKey::Str(name) if names.contains(name)));811 .retain(|(k, _)| !matches!(k, LuaKey::Str(name) if names.contains(name)));
...@@ -1388,116 +817,8 @@ fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet<String>) {...@@ -1388,116 +817,8 @@ fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet<String>) {
1388}817}
1389818
1390/// Names of every tool in `tools`, including tools nested in `Tools` tables (macros/groups).819/// Names of every tool in `tools`, including tools nested in `Tools` tables (macros/groups).
1391fn collect_tool_names(tools: &LuaTable, out: &mut Vec<String>) {
1392 for (key, value) in &tools.entries {
1393 let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else {
1394 continue;
1395 };
1396 out.push(name.clone());
1397 if let Some(inner) = tool.get_table("Tools") {
1398 collect_tool_names(inner, out);
1399 }
1400 }
1401}
1402
1403/// Renames tool keys (recursively) and rewrites every reference to them: `SourceOp` values and
1404/// whole-word identifiers inside `Expression` strings.
1405fn rename_tools(tools: &mut LuaTable, renames: &HashMap<String, String>) {
1406 for (key, value) in &mut tools.entries {
1407 let LuaKey::Str(name) = key else { continue };
1408 if let Some(new) = renames.get(name.as_str()) {
1409 *name = new.clone();
1410 }
1411 if let Some(tool) = value.as_table_mut() {
1412 rewrite_references(tool, renames);
1413 if let Some(inner) = tool.get_table_mut("Tools") {
1414 rename_tools(inner, renames);
1415 }
1416 }
1417 }
1418}
1419
1420fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
1421 rewrite_formula_values(tbl, renames);
1422 for (key, value) in &mut tbl.entries {
1423 match (key, value) {
1424 (LuaKey::Str(k), LuaValue::String(s)) if k == "SourceOp" => {
1425 if let Some(new) = renames.get(s.as_str()) {
1426 *s = new.clone();
1427 }
1428 }
1429 (LuaKey::Str(k), LuaValue::String(s)) if k == "Expression" => {
1430 *s = rename_expression_idents(s, renames);
1431 }
1432 (_, LuaValue::Table(sub)) => rewrite_references(sub, renames),
1433 _ => {}
1434 }
1435 }
1436}
1437
1438/// Rewrites the formula strings of an `Expression` modifier table (not recursive).
1439fn rewrite_formula_values(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
1440 if tbl.tag.as_deref() != Some("Expression") {
1441 return;
1442 }
1443 let Some(inputs) = tbl.get_table_mut("Inputs") else { return };
1444 for key in EXPRESSION_FORMULA_INPUTS {
1445 if let Some(LuaValue::String(formula)) = inputs.get_table_mut(key).and_then(|i| i.get_mut("Value")) {
1446 *formula = rename_expression_idents(formula, renames);
1447 }
1448 }
1449}
1450
1451fn rewrite_formulas_deep(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
1452 rewrite_formula_values(tbl, renames);
1453 for (_, value) in &mut tbl.entries {
1454 if let Some(sub) = value.as_table_mut() {
1455 rewrite_formulas_deep(sub, renames);
1456 }
1457 }
1458}
1459
1460/// Renames whole-word identifiers in `expr`, leaving property names (`Other.Size`) alone.
1461fn rename_expression_idents(expr: &str, renames: &HashMap<String, String>) -> String {
1462 let mut out = String::with_capacity(expr.len());
1463 let mut word = String::new();
1464 let mut prev = None;
1465 let flush = |word: &mut String, out: &mut String, prev: Option<char>| {
1466 let renamed = renames.get(word.as_str()).filter(|_| prev != Some('.'));
1467 out.push_str(renamed.map_or(word.as_str(), String::as_str));
1468 word.clear();
1469 };
1470 for ch in expr.chars() {
1471 if ch.is_ascii_alphanumeric() || ch == '_' {
1472 word.push(ch);
1473 } else {
1474 flush(&mut word, &mut out, prev);
1475 out.push(ch);
1476 prev = Some(ch);
1477 }
1478 }
1479 flush(&mut word, &mut out, prev);
1480 out
1481}
1482
1483/// Removes `SourceOp`/`Source` pairs whose target fails `exists`, so pasted tools never point at
1484/// missing operators.
1485fn drop_unknown_source_ops(tbl: &mut LuaTable, exists: &mut dyn FnMut(&str) -> bool) {
1486 let dangling = tbl
1487 .get_str("SourceOp")
1488 .is_some_and(|name| !exists(name));
1489 if dangling {
1490 tbl.remove(&LuaKey::Str("SourceOp".to_owned()));
1491 tbl.remove(&LuaKey::Str("Source".to_owned()));
1492 }
1493 for (_, value) in &mut tbl.entries {
1494 if let Some(sub) = value.as_table_mut() {
1495 drop_unknown_source_ops(sub, exists);
1496 }
1497 }
1498}
1499820
1500fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) {821pub(super) fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) {
1501 let vi = ensure_table_mut(raw, "ViewInfo", Some("OperatorInfo"));822 let vi = ensure_table_mut(raw, "ViewInfo", Some("OperatorInfo"));
1502 vi.set(823 vi.set(
1503 LuaKey::Str("Pos".to_owned()),824 LuaKey::Str("Pos".to_owned()),
...@@ -1505,1108 +826,3 @@ fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) {...@@ -1505,1108 +826,3 @@ fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) {
1505 );826 );
1506}827}
1507828
1508fn upsert_keyframe(spline: &mut BezierSpline, frame: f64, value: f64) {
1509 if let Some(existing) = spline
1510 .keyframes
1511 .iter_mut()
1512 .find(|kf| (kf.time - frame).abs() < KEYFRAME_EPS)
1513 {
1514 // Handles are absolute coordinates, so they travel with the key.
1515 let (dt, dv) = (frame - existing.time, value - existing.value);
1516 existing.time = frame;
1517 existing.value = value;
1518 for handle in [&mut existing.lh, &mut existing.rh].into_iter().flatten() {
1519 handle[0] += dt;
1520 handle[1] += dv;
1521 }
1522 } else {
1523 spline.keyframes.push(Keyframe::new(frame, value));
1524 spline.sort();
1525 }
1526}
1527
1528fn default_spline_color(name: &str) -> [u8; 3] {
1529 // Deterministic vivid Fusion-like spline palette based on name hash.
1530 const PALETTE: &[[u8; 3]] = &[
1531 [255, 128, 0],
1532 [102, 204, 255],
1533 [170, 238, 102],
1534 [255, 102, 170],
1535 [204, 153, 255],
1536 [255, 221, 85],
1537 ];
1538 let hash = name
1539 .bytes()
1540 .fold(0usize, |acc, b| acc.wrapping_mul(31).wrapping_add(b as usize));
1541 PALETTE[hash % PALETTE.len()]
1542}
1543
1544fn default_view_info_for_kind(kind: &str, pos: [f32; 2]) -> LuaTable {
1545 let tag = match kind {
1546 "PipeRouter" => "PipeRouterInfo",
1547 "Underlay" => "UnderlayInfo",
1548 "Note" | "StickyNote" => "StickyNoteInfo",
1549 _ => "OperatorInfo",
1550 };
1551 let mut vi = LuaTable {
1552 tag: Some(tag.to_owned()),
1553 entries: Vec::new(),
1554 };
1555 vi.set(
1556 LuaKey::Str("Pos".to_owned()),
1557 vec2_lua(pos[0] as f64, pos[1] as f64),
1558 );
1559 match kind {
1560 "Underlay" => {
1561 vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(172.0, 166.364));
1562 }
1563 "Note" | "StickyNote" => {
1564 let mut flags = LuaTable::default();
1565 flags.set(LuaKey::Str("Expanded".to_owned()), LuaValue::Bool(true));
1566 vi.set(LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags));
1567 vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(196.0, 179.364));
1568 }
1569 _ => {}
1570 }
1571 vi
1572}
1573
1574/// Returns sensible Fusion 21.1 default inputs for common tool classes so Fusion Studio opens
1575/// newly created nodes cleanly without errors.
1576fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Vec<(String, ParamValue)> {
1577 let w = width as f64;
1578 let h = height as f64;
1579 let num = |k: &str, v: f64| (k.to_owned(), ParamValue::Number(v));
1580 let pt = |k: &str, x: f64, y: f64| (k.to_owned(), ParamValue::Point([x, y]));
1581 let txt = |k: &str, s: &str| (k.to_owned(), ParamValue::Text(s.to_owned()));
1582 let fuid = |k: &str, s: &str| (k.to_owned(), ParamValue::FuId(s.to_owned()));
1583
1584 match kind {
1585 "Background" => vec![
1586 num("Width", w),
1587 num("Height", h),
1588 num("UseFrameFormatSettings", 1.0),
1589 num("TopLeftRed", 0.0),
1590 num("TopLeftGreen", 0.0),
1591 num("TopLeftBlue", 0.0),
1592 num("TopLeftAlpha", 1.0),
1593 ],
1594 "Merge" => vec![
1595 num("PerformDepthMerge", 0.0),
1596 pt("Center", 0.5, 0.5),
1597 num("Size", 1.0),
1598 num("Angle", 0.0),
1599 num("Blend", 1.0),
1600 ],
1601 "Transform" => vec![
1602 pt("Center", 0.5, 0.5),
1603 pt("Pivot", 0.5, 0.5),
1604 num("Size", 1.0),
1605 num("Angle", 0.0),
1606 ],
1607 "Blur" => vec![fuid("Filter", "Fast Gaussian"), num("XBlurSize", 1.0)],
1608 "Glow" => vec![num("XGlowSize", 10.0), num("Glow", 0.8)],
1609 "SoftGlow" => vec![
1610 fuid("Filter", "Fast Gaussian"),
1611 num("Gain", 2.0),
1612 num("XGlowSize", 10.0),
1613 ],
1614 "BrightnessContrast" => vec![
1615 num("Gain", 1.0),
1616 num("Lift", 0.0),
1617 num("Gamma", 1.0),
1618 num("Contrast", 0.0),
1619 num("Brightness", 0.0),
1620 num("Saturation", 1.0),
1621 ],
1622 "ColorCorrector" => vec![
1623 num("WheelSaturation1", 1.0),
1624 num("MasterRGBGain", 1.0),
1625 num("MasterRGBGamma", 1.0),
1626 ],
1627 "ColorGain" => vec![
1628 num("GainRed", 1.0),
1629 num("GainGreen", 1.0),
1630 num("GainBlue", 1.0),
1631 num("GainAlpha", 1.0),
1632 num("GammaRed", 1.0),
1633 num("GammaGreen", 1.0),
1634 num("GammaBlue", 1.0),
1635 ],
1636 "RectangleMask" => vec![
1637 num("MaskWidth", w),
1638 num("MaskHeight", h),
1639 pt("PixelAspect", 1.0, 1.0),
1640 pt("Center", 0.5, 0.5),
1641 num("Width", 0.5),
1642 num("Height", 0.5),
1643 num("CornerRadius", 0.0),
1644 num("SoftEdge", 0.0),
1645 ],
1646 "EllipseMask" => vec![
1647 num("MaskWidth", w),
1648 num("MaskHeight", h),
1649 pt("PixelAspect", 1.0, 1.0),
1650 pt("Center", 0.5, 0.5),
1651 num("Width", 0.5),
1652 num("Height", 0.5),
1653 num("SoftEdge", 0.0),
1654 ],
1655 "PolylineMask" => vec![
1656 num("MaskWidth", w),
1657 num("MaskHeight", h),
1658 pt("PixelAspect", 1.0, 1.0),
1659 num("SoftEdge", 0.0),
1660 ],
1661 "BitmapMask" => vec![
1662 num("MaskWidth", w),
1663 num("MaskHeight", h),
1664 pt("PixelAspect", 1.0, 1.0),
1665 fuid("Channel", "Alpha"),
1666 ],
1667 "TextPlus" => vec![
1668 num("Width", w),
1669 num("Height", h),
1670 num("UseFrameFormatSettings", 1.0),
1671 txt("StyledText", ""),
1672 txt("Font", "Open Sans"),
1673 txt("Style", "Bold"),
1674 num("Size", 0.08),
1675 pt("Center", 0.5, 0.5),
1676 ],
1677 "Loader" => vec![],
1678 "Saver" => vec![num("ProcessWhenBlendIs00", 0.0), num("CreateDir", 1.0)],
1679 "Displace" => vec![
1680 num("Type", 0.0),
1681 num("XRefraction", 0.0),
1682 num("YRefraction", 0.0),
1683 num("RefractionStrength", 0.0),
1684 ],
1685 "FastNoise" => vec![
1686 num("Width", w),
1687 num("Height", h),
1688 num("UseFrameFormatSettings", 1.0),
1689 num("Detail", 2.0),
1690 num("Contrast", 1.0),
1691 num("XScale", 2.0),
1692 num("Seethe", 0.0),
1693 ],
1694 "PipeRouter" | "Underlay" => vec![],
1695 "Switch" | "Fuse.Switch" => vec![num("Source", 0.0)],
1696 "TimeStretcher" => vec![num("SourceTime", 0.0), num("InterpolateBetweenFrames", 0.0)],
1697 "TimeSpeed" => vec![num("Speed", 1.0), num("Delay", 0.0)],
1698 "Renderer3D" => vec![
1699 num("Width", w),
1700 num("Height", h),
1701 num("UseFrameFormatSettings", 1.0),
1702 fuid("RendererType", "RendererOpenGL"),
1703 ],
1704 "Camera3D" => vec![num("FLength", 24.0), num("PlaneOfFocus", 5.0)],
1705 "Merge3D" => vec![num("PassThroughLights", 1.0)],
1706 "Transform3D" => vec![num("Transform3DOp.Scale.X", 1.0)],
1707 "ImagePlane3D" => vec![
1708 num("SurfacePlaneInputs.Width", 1.0),
1709 num("SurfacePlaneInputs.Height", 1.0),
1710 ],
1711 "Shape3D" => vec![fuid("Shape", "SurfacePlaneInputs")],
1712 "Note" | "StickyNote" => vec![txt("Comments", "")],
1713 _ => vec![],
1714 }
1715}
1716
1717#[cfg(test)]
1718mod tests {
1719 use super::*;
1720 use crate::expr::ExprEngine;
1721 use std::path::Path;
1722
1723 fn sample_comp() -> Comp {
1724 let src = r#"Composition {
1725 CurrentTime = 10,
1726 RenderRange = { 0, 100 },
1727 GlobalRange = { 0, 100 },
1728 Prefs = {
1729 Comp = {
1730 FrameFormat = {
1731 Width = 1920,
1732 Height = 1080,
1733 Rate = 24,
1734 DepthFull = 3,
1735 },
1736 },
1737 },
1738 Tools = ordered() {
1739 BG1 = Background {
1740 Inputs = {
1741 Width = Input { Value = 1920, },
1742 Height = Input { Value = 1080, },
1743 TopLeftRed = Input { Value = 0.25, },
1744 },
1745 ViewInfo = OperatorInfo { Pos = { 100, 50 } },
1746 },
1747 BC1 = BrightnessContrast {
1748 Inputs = {
1749 Input = Input {
1750 SourceOp = "BG1",
1751 Source = "Output",
1752 },
1753 Gain = Input {
1754 SourceOp = "BC1Gain",
1755 Source = "Value",
1756 },
1757 },
1758 ViewInfo = OperatorInfo { Pos = { 300, 50 } },
1759 },
1760 BC1Gain = BezierSpline {
1761 SplineColor = { Red = 255, Green = 128, Blue = 0 },
1762 KeyFrames = {
1763 [0] = { 1, Flags = { Linear = true } },
1764 [30] = { 2, Flags = { Linear = true } },
1765 },
1766 },
1767 SurfaceTracker1 = SurfaceTracker {
1768 Inputs = {
1769 Source = Input {
1770 SourceOp = "BC1",
1771 Source = "Output",
1772 },
1773 MeshBlob = Input {
1774 Value = TrackingMesh {
1775 Vertices = { 1, 2, 3 },
1776 },
1777 },
1778 },
1779 ViewInfo = OperatorInfo { Pos = { 500, 50 } },
1780 },
1781 },
1782}"#;
1783 Comp::from_fusion_str(src).expect("parse sample comp")
1784 }
1785
1786 #[test]
1787 fn add_node_naming_and_tool_defaults() {
1788 let mut comp = sample_comp();
1789 let rev0 = comp.revision;
1790
1791 let t1 = comp.add_node("Transform", None, [120.0, 200.0]);
1792 let t2 = comp.add_node("Transform", None, [240.0, 200.0]);
1793 assert_eq!(comp.node(t1).name, "Transform1");
1794 assert_eq!(comp.node(t2).name, "Transform2");
1795 assert_eq!(comp.node(t1).pos, [120.0, 200.0]);
1796 assert!(comp.revision >= rev0 + 2);
1797
1798 let h0 = comp.add_node("Background", Some("HeroBG"), [0.0, 0.0]);
1799 let h1 = comp.add_node("Background", Some("HeroBG"), [50.0, 0.0]);
1800 let h2 = comp.add_node("Background", Some("HeroBG"), [100.0, 0.0]);
1801 assert_eq!(comp.node(h0).name, "HeroBG");
1802 assert_eq!(comp.node(h1).name, "HeroBG_1");
1803 assert_eq!(comp.node(h2).name, "HeroBG_2");
1804
1805 // Cover all common Fusion 21.1 tool categories + generic fallback
1806 let kinds = [
1807 "Background",
1808 "Merge",
1809 "Transform",
1810 "Blur",
1811 "Glow",
1812 "SoftGlow",
1813 "BrightnessContrast",
1814 "ColorCorrector",
1815 "ColorGain",
1816 "RectangleMask",
1817 "EllipseMask",
1818 "PolylineMask",
1819 "BitmapMask",
1820 "TextPlus",
1821 "Loader",
1822 "Saver",
1823 "Displace",
1824 "FastNoise",
1825 "PipeRouter",
1826 "Switch",
1827 "TimeStretcher",
1828 "TimeSpeed",
1829 "Renderer3D",
1830 "Camera3D",
1831 "Merge3D",
1832 "Transform3D",
1833 "ImagePlane3D",
1834 "Shape3D",
1835 "Note",
1836 "Underlay",
1837 "MyCustomThirdPartyTool",
1838 ];
1839 for (i, kind) in kinds.iter().enumerate() {
1840 let id = comp.add_node(kind, None, [i as f32 * 50.0, 400.0]);
1841 assert_eq!(comp.node(id).kind, *kind);
1842 assert!(comp.node(id).raw.get_table("ViewInfo").is_some());
1843 }
1844
1845 // Roundtrip all newly created nodes cleanly
1846 let s = comp.to_fusion_string();
1847 let reloaded = Comp::from_fusion_str(&s).expect("roundtrip added nodes");
1848 assert_eq!(reloaded.nodes.len(), comp.nodes.len());
1849 assert_eq!(
1850 reloaded.node(reloaded.find_node("HeroBG").unwrap()).static_number("Width"),
1851 Some(1920.0)
1852 );
1853 }
1854
1855 #[test]
1856 fn connect_cycle_detection_disconnect_and_splice() {
1857 let mut comp = sample_comp();
1858 let bg = comp.find_node("BG1").unwrap();
1859 let bc = comp.find_node("BC1").unwrap();
1860 let st = comp.find_node("SurfaceTracker1").unwrap();
1861
1862 // Self-loop rejected
1863 assert!(comp.connect_output(bg, "Output", bg, "EffectMask").is_err());
1864 // Direct cycle BG1 -> BC1 -> BG1 rejected
1865 assert!(comp.connect_output(bc, "Output", bg, "EffectMask").is_err());
1866 // Transitive cycle BG1 -> BC1 -> SurfaceTracker1 -> BG1 rejected
1867 assert!(comp.connect_output(st, "Output", bg, "EffectMask").is_err());
1868
1869 // Splice a Blur into BG1 -> BC1.Input
1870 let blur = comp.add_node("Blur", None, [200.0, 50.0]);
1871 comp.splice_node_into_pipe(blur, bg, bc, "Input")
1872 .expect("splice blur");
1873 assert_eq!(comp.node(blur).connected_node("Input"), Some("BG1"));
1874 assert_eq!(comp.node(bc).connected_node("Input"), Some("Blur1"));
1875
1876 // Disconnect returns true once, then false
1877 assert!(comp.disconnect(bc, "Input"));
1878 assert!(!comp.disconnect(bc, "Input"));
1879 assert_eq!(comp.node(bc).connected_node("Input"), None);
1880
1881 // Reconnect and verify roundtrip
1882 comp.connect_output(blur, "Output", bc, "Input")
1883 .expect("reconnect");
1884 let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip");
1885 assert_eq!(
1886 reloaded.node(reloaded.find_node("BC1").unwrap()).connected_node("Input"),
1887 Some("Blur1")
1888 );
1889 }
1890
1891 #[test]
1892 fn params_expressions_passthrough_pos_and_keyframes() {
1893 let mut comp = sample_comp();
1894 let bc = comp.find_node("BC1").unwrap();
1895
1896 assert!(comp.set_input_value(bc, "Gamma", ParamValue::Number(1.45)));
1897 assert!(comp.set_input_expression(bc, "Brightness", Some("time * 0.01".to_owned())));
1898 assert!(comp.toggle_passthrough(bc));
1899 comp.set_node_pos(bc, [333.0, 77.0]);
1900
1901 // Set keyframe on static input -> creates new BezierSpline and wires it
1902 let sp_name = comp.set_keyframe(bc, "Contrast", 0.0, 0.2).expect("kf 0");
1903 assert_eq!(sp_name, "BC1Contrast");
1904 let sp_name2 = comp.set_keyframe(bc, "Contrast", 20.0, 0.8).expect("kf 20");
1905 assert_eq!(sp_name2, sp_name);
1906 // Update existing keyframe at frame 20
1907 comp.set_keyframe(bc, "Contrast", 20.0, 0.9).expect("update kf 20");
1908 assert_eq!(comp.splines[&sp_name].keyframes.len(), 2);
1909
1910 // Evaluate via Comp::eval_number
1911 let expr = ExprEngine::new();
1912 let val_mid = comp.eval_number(comp.node(bc), "Contrast", 10.0, 0.0, &expr);
1913 assert!((val_mid - 0.55).abs() < 1e-5, "got {val_mid}");
1914
1915 // Delete keyframe
1916 assert!(comp.delete_keyframe(&sp_name, 20.0));
1917 assert!(!comp.delete_keyframe(&sp_name, 20.0));
1918 assert_eq!(comp.splines[&sp_name].keyframes.len(), 1);
1919
1920 // Roundtrip
1921 let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip");
1922 let r_bc = reloaded.node(reloaded.find_node("BC1").unwrap());
1923 assert!(r_bc.bypassed);
1924 assert_eq!(r_bc.pos, [333.0, 77.0]);
1925 assert_eq!(r_bc.static_number("Gamma"), Some(1.45));
1926 assert_eq!(
1927 r_bc.inputs.get("Brightness").and_then(|b| b.expression.as_deref()),
1928 Some("time * 0.01")
1929 );
1930 assert_eq!(r_bc.connected_node("Contrast"), Some("BC1Contrast"));
1931 assert_eq!(reloaded.splines["BC1Contrast"].keyframes.len(), 1);
1932
1933 // Clear expression and un-bypass
1934 assert!(comp.set_input_expression(bc, "Brightness", None));
1935 assert!(!comp.toggle_passthrough(bc));
1936 let reloaded2 = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip 2");
1937 let r_bc2 = reloaded2.node(reloaded2.find_node("BC1").unwrap());
1938 assert!(!r_bc2.bypassed);
1939 assert_eq!(
1940 r_bc2.inputs.get("Brightness").and_then(|b| b.expression.as_deref()),
1941 None
1942 );
1943 }
1944
1945 #[test]
1946 fn rename_duplicate_and_delete_nodes_roundtrip() {
1947 let mut comp = sample_comp();
1948 let bg = comp.find_node("BG1").unwrap();
1949 let bc = comp.find_node("BC1").unwrap();
1950
1951 // Rename validation
1952 assert!(comp.rename_node(bg, "").is_err());
1953 assert!(comp.rename_node(bg, "123Bad").is_err());
1954 assert!(comp.rename_node(bg, "function").is_err());
1955 assert!(comp.rename_node(bg, "BC1").is_err());
1956
1957 // Rename BG1 -> PlateBG and verify BC1.Input SourceOp is rewritten
1958 let new_name = comp.rename_node(bg, "PlateBG").expect("rename BG1");
1959 assert_eq!(new_name, "PlateBG");
1960 assert!(comp.find_node("BG1").is_none());
1961 assert_eq!(comp.find_node("PlateBG"), Some(bg));
1962 assert_eq!(comp.node(bc).connected_node("Input"), Some("PlateBG"));
1963
1964 // Duplicate [PlateBG, BC1] together -> internal wire preserved, BC1Gain spline cloned
1965 let dups = comp.duplicate_nodes(&[bg, bc], [0.0, 150.0]);
1966 assert_eq!(dups.len(), 2);
1967 let dup_bg = dups[0];
1968 let dup_bc = dups[1];
1969 assert_eq!(comp.node(dup_bg).name, "PlateBG_1");
1970 assert_eq!(comp.node(dup_bc).name, "BC1_1");
1971 assert_eq!(comp.node(dup_bg).pos, [100.0, 200.0]);
1972 assert_eq!(comp.node(dup_bc).connected_node("Input"), Some("PlateBG_1"));
1973 let dup_gain_spline = comp.node(dup_bc).connected_node("Gain").unwrap().to_owned();
1974 assert_ne!(dup_gain_spline, "BC1Gain");
1975 assert!(comp.splines.contains_key(&dup_gain_spline));
1976
1977 // Share BC1Gain with dup_bg (artificial) vs exclusive spline on dup_bc:
1978 // Deleting dup_bc should prune `dup_gain_spline` while leaving `BC1Gain` intact.
1979 let deleted = comp.delete_nodes(&[dup_bc]);
1980 assert_eq!(deleted, vec!["BC1_1".to_owned()]);
1981 assert!(!comp.splines.contains_key(&dup_gain_spline));
1982 assert!(comp.splines.contains_key("BC1Gain"));
1983
1984 // Delete BC1 -> SurfaceTracker1.Source unwired, BC1Gain pruned, NodeId indices compact
1985 let bc_now = comp.find_node("BC1").unwrap();
1986 let del2 = comp.delete_nodes(&[bc_now]);
1987 assert_eq!(del2, vec!["BC1".to_owned()]);
1988 assert!(!comp.splines.contains_key("BC1Gain"));
1989 for (idx, n) in comp.nodes.iter().enumerate() {
1990 assert_eq!(n.id, NodeId(idx));
1991 assert_eq!(comp.find_node(&n.name), Some(NodeId(idx)));
1992 }
1993 let st_now = comp.find_node("SurfaceTracker1").unwrap();
1994 assert_eq!(comp.node(st_now).connected_node("Source"), None);
1995
1996 // Full roundtrip preserves unknown SurfaceTracker1 verbatim + all structural mutations
1997 let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip");
1998 assert!(reloaded.find_node("PlateBG").is_some());
1999 assert!(reloaded.find_node("PlateBG_1").is_some());
2000 assert!(reloaded.find_node("BC1").is_none());
2001 assert!(reloaded.find_node("SurfaceTracker1").is_some());
2002 assert!(!reloaded.splines.contains_key("BC1Gain"));
2003 let r_st = reloaded.node(reloaded.find_node("SurfaceTracker1").unwrap());
2004 assert_eq!(r_st.connected_node("Source"), None);
2005 assert!(
2006 r_st.raw
2007 .get_table("Inputs")
2008 .and_then(|i| i.get_table("MeshBlob"))
2009 .is_some()
2010 );
2011 }
2012
2013 #[test]
2014 fn roundtrip_mutations_on_real_20_falling_comp() {
2015 let path = Path::new("/Volumes/Project/trees/fusion/20_falling.comp");
2016 if !path.exists() {
2017 return;
2018 }
2019 let mut comp = Comp::from_fusion_file(path).expect("load 20_falling.comp");
2020 let orig_count = comp.nodes.len();
2021
2022 let blur = comp.add_node("Blur", Some("TestGlowBlur"), [1000.0, -500.0]);
2023 let merge19 = comp.find_node("Merge19").expect("Merge19");
2024 comp.set_input_value(blur, "XBlurSize", ParamValue::Number(4.5));
2025 comp.set_input_expression(blur, "YBlurSize", Some("XBlurSize * 2".to_owned()));
2026 comp.toggle_passthrough(blur);
2027 let sp = comp
2028 .set_keyframe(blur, "Blend", 2200.0, 0.5)
2029 .expect("keyframe blend");
2030 comp.set_keyframe(blur, "Blend", 2250.0, 1.0)
2031 .expect("keyframe blend 2");
2032 comp.connect_output(merge19, "Output", blur, "Input")
2033 .expect("connect Merge19 -> blur");
2034 comp.rename_node(blur, "TestGlowBlurRenamed")
2035 .expect("rename blur");
2036
2037 let serialized = comp.to_fusion_string();
2038 let reloaded = Comp::from_fusion_str(&serialized).expect("re-parse mutated 20_falling");
2039 assert_eq!(reloaded.nodes.len(), orig_count + 1);
2040 let r_blur_id = reloaded
2041 .find_node("TestGlowBlurRenamed")
2042 .expect("TestGlowBlurRenamed");
2043 let r_blur = reloaded.node(r_blur_id);
2044 assert!(r_blur.bypassed);
2045 assert_eq!(r_blur.connected_node("Input"), Some("Merge19"));
2046 assert_eq!(r_blur.static_number("XBlurSize"), Some(4.5));
2047 assert_eq!(
2048 r_blur.inputs.get("YBlurSize").and_then(|b| b.expression.as_deref()),
2049 Some("XBlurSize * 2")
2050 );
2051 assert_eq!(reloaded.splines[&sp].keyframes.len(), 2);
2052 }
2053
2054 #[test]
2055 fn comp_history_undo_redo_coalescing_groups_and_bounds() {
2056 let mut comp = sample_comp();
2057 let mut history = CompHistory::with_max_depth(3);
2058 history.mark_saved(&comp);
2059 assert!(!history.is_dirty(&comp));
2060 assert!(!history.can_undo());
2061 assert!(!history.can_redo());
2062
2063 let bg = comp.find_node("BG1").unwrap();
2064
2065 // 1. Coalesced drag: 120 frames produce ONE undo step
2066 for i in 1..=120 {
2067 history.push_coalesced(&comp, "Move BG1", format!("drag_node:{}", bg.0));
2068 comp.set_node_pos(bg, [100.0 + i as f32, 50.0 + i as f32 * 0.5]);
2069 }
2070 history.break_coalescing();
2071 assert_eq!(history.undo_len(), 1);
2072 assert_eq!(history.undo_label(), Some("Move BG1"));
2073 assert!(history.is_dirty(&comp));
2074 assert_eq!(comp.node(bg).pos, [220.0, 110.0]);
2075
2076 // Undo restores original pre-drag position and clears dirty flag
2077 assert!(history.undo(&mut comp));
2078 assert_eq!(comp.node(bg).pos, [100.0, 50.0]);
2079 assert!(!history.is_dirty(&comp));
2080 assert!(history.can_redo());
2081 assert_eq!(history.redo_label(), Some("Move BG1"));
2082
2083 // Redo restores final dragged position
2084 assert!(history.redo(&mut comp));
2085 assert_eq!(comp.node(bg).pos, [220.0, 110.0]);
2086 assert!(history.is_dirty(&comp));
2087
2088 // 2. Redo invalidation on new edit after undo
2089 assert!(history.undo(&mut comp));
2090 assert!(history.can_redo());
2091 history.push_snapshot(&comp, "Add Blur");
2092 let blur = comp.add_node("Blur", None, [200.0, 100.0]);
2093 assert!(!history.can_redo());
2094 assert_eq!(history.undo_len(), 1);
2095
2096 // 3. Transaction group collapses multiple mutations into one undo step
2097 history.begin_group(&comp, "Style Blur");
2098 comp.set_input_value(blur, "XBlurSize", ParamValue::Number(5.0));
2099 history.push_snapshot(&comp, "Ignored inside group");
2100 comp.toggle_passthrough(blur);
2101 assert!(history.commit_group(&comp));
2102 assert_eq!(history.undo_len(), 2);
2103 assert_eq!(history.undo_label(), Some("Style Blur"));
2104
2105 // No-op group doesn't push
2106 history.begin_group(&comp, "No-op");
2107 assert!(!history.commit_group(&comp));
2108 assert_eq!(history.undo_len(), 2);
2109
2110 // Cancel group restores pre-group state
2111 history.begin_group(&comp, "Canceled");
2112 comp.set_node_pos(blur, [999.0, 999.0]);
2113 assert!(history.cancel_group(&mut comp));
2114 assert_eq!(comp.node(blur).pos, [200.0, 100.0]);
2115
2116 // 4. Bounded history depth (max_depth = 3)
2117 history.push_snapshot(&comp, "Edit 3");
2118 comp.set_node_pos(blur, [210.0, 100.0]);
2119 history.push_snapshot(&comp, "Edit 4");
2120 comp.set_node_pos(blur, [220.0, 100.0]);
2121 assert_eq!(history.undo_len(), 3);
2122
2123 history.clear();
2124 assert!(!history.can_undo());
2125 assert!(!history.can_redo());
2126 }
2127
2128 const GROUP_SNIPPET: &str = r#"{
2129 Tools = ordered() {
2130 Group1 = GroupOperator {
2131 Inputs = {
2132 Input1 = InstanceInput { SourceOp = "Inner1", Source = "Input", },
2133 },
2134 Outputs = {
2135 Output1 = InstanceOutput { SourceOp = "Inner1", Source = "Output", },
2136 },
2137 ViewInfo = GroupInfo { Pos = { 10, 20 } },
2138 Tools = ordered() {
2139 Inner1 = Blur {
2140 Inputs = {
2141 XBlurSize = Input { SourceOp = "Inner1Size", Source = "Value", },
2142 },
2143 ViewInfo = OperatorInfo { Pos = { 0, 0 } },
2144 },
2145 Inner1Size = BezierSpline {
2146 KeyFrames = { [0] = { 1, Flags = { Linear = true } } },
2147 },
2148 },
2149 },
2150 },
2151}"#;
2152
2153 #[test]
2154 fn export_fusion_clipboard_includes_owned_modifiers_and_internal_wires() {
2155 let comp = sample_comp();
2156 let bg = comp.find_node("BG1").unwrap();
2157 let bc = comp.find_node("BC1").unwrap();
2158
2159 let both = comp.export_fusion_clipboard(&[bg, bc]);
2160 assert!(both.contains("Tools = ordered()"), "{both}");
2161 assert!(both.contains("ActiveTool = \"BG1\""), "{both}");
2162 let parsed = parse_lua(&both).expect("clipboard parses as Lua");
2163 let tools = parsed.as_table().unwrap().get_table("Tools").unwrap();
2164 let names: Vec<_> = tools
2165 .entries
2166 .iter()
2167 .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None })
2168 .collect();
2169 assert_eq!(names, ["BG1", "BC1", "BC1Gain"]);
2170 assert_eq!(
2171 tools
2172 .get_table("BC1")
2173 .and_then(|t| t.get_table("Inputs"))
2174 .and_then(|i| i.get_table("Input"))
2175 .and_then(|i| i.get_str("SourceOp")),
2176 Some("BG1")
2177 );
2178
2179 // Selecting only BC1 keeps its owned spline and leaves the external BG1 reference.
2180 let only_bc = comp.export_fusion_clipboard(&[bc, bc]);
2181 assert!(only_bc.contains("BC1Gain = BezierSpline"));
2182 assert!(!only_bc.contains("BG1 = Background"));
2183 assert!(only_bc.contains("SourceOp = \"BG1\""));
2184
2185 // Splines created after load (not yet in `raw_root`) are exported too.
2186 let mut comp = comp;
2187 let sp = comp.set_keyframe(bg, "Width", 0.0, 1.0).unwrap();
2188 assert!(comp.export_fusion_clipboard(&[bg]).contains(&format!("{sp} = BezierSpline")));
2189 }
2190
2191 #[test]
2192 fn paste_dedups_names_and_remaps_internal_wires_and_splines() {
2193 let mut comp = sample_comp();
2194 let bg = comp.find_node("BG1").unwrap();
2195 let bc = comp.find_node("BC1").unwrap();
2196 let snippet = comp.export_fusion_clipboard(&[bg, bc]);
2197 let nodes_before = comp.nodes.len();
2198
2199 let ids = comp.paste_fusion_clipboard(&snippet, (60.0, 40.0)).expect("paste");
2200 assert_eq!(ids.len(), 2);
2201 assert_eq!(comp.nodes.len(), nodes_before + 2);
2202 let (pbg, pbc) = (comp.node(ids[0]), comp.node(ids[1]));
2203 assert_eq!((pbg.name.as_str(), pbc.name.as_str()), ("BG1_1", "BC1_1"));
2204 assert_eq!(pbg.pos, [160.0, 90.0]);
2205 assert_eq!(pbc.pos, [360.0, 90.0]);
2206 assert_eq!(pbc.connected_node("Input"), Some("BG1_1"));
2207 assert_eq!(pbc.connected_node("Gain"), Some("BC1Gain_1"));
2208 assert_eq!(comp.splines["BC1Gain_1"].keyframes.len(), 2);
2209 assert_eq!(comp.splines["BC1Gain"].keyframes.len(), 2);
2210 assert_eq!(comp.find_node("BC1_1"), Some(ids[1]));
2211 assert_eq!(comp.node(bc).connected_node("Input"), Some("BG1"));
2212
2213 // Pasting again keeps advancing the suffix instead of clobbering earlier pastes.
2214 let again = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap();
2215 assert_eq!(comp.node(again[0]).name, "BG1_2");
2216 assert_eq!(comp.node(again[1]).connected_node("Input"), Some("BG1_2"));
2217
2218 // Everything survives a save/load roundtrip, including the cloned spline and offset.
2219 let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("reload");
2220 let r_bc = reloaded.node(reloaded.find_node("BC1_1").unwrap());
2221 assert_eq!(r_bc.pos, [360.0, 90.0]);
2222 assert_eq!(r_bc.connected_node("Input"), Some("BG1_1"));
2223 assert!(reloaded.splines.contains_key("BC1Gain_1"));
2224 }
2225
2226 #[test]
2227 fn paste_external_references_are_kept_when_present_and_dropped_when_missing() {
2228 let mut comp = sample_comp();
2229 let bc = comp.find_node("BC1").unwrap();
2230 let snippet = comp.export_fusion_clipboard(&[bc]);
2231
2232 let ids = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap();
2233 assert_eq!(comp.node(ids[0]).connected_node("Input"), Some("BG1"));
2234
2235 let mut empty = Comp::from_fusion_str("Composition { Tools = ordered() { } }").unwrap();
2236 let ids = empty.paste_fusion_clipboard(&snippet, (5.0, 5.0)).unwrap();
2237 let pasted = empty.node(ids[0]);
2238 assert_eq!(pasted.name, "BC1");
2239 assert_eq!(pasted.connected_node("Input"), None);
2240 assert_eq!(pasted.connected_node("Gain"), Some("BC1Gain"));
2241 assert!(!empty.to_fusion_string().contains("BG1"));
2242 }
2243
2244 #[test]
2245 fn paste_accepts_full_composition_and_rewrites_expressions() {
2246 let mut comp = sample_comp();
2247 let snippet = r#"Composition {
2248 Tools = ordered() {
2249 BG1 = Background { Inputs = { Width = Input { Value = 64, } }, },
2250 T1 = Transform {
2251 Inputs = {
2252 Size = Input { Expression = "BG1.Width / 2 + BG10.Width", },
2253 Input = Input { SourceOp = "BG1", Source = "Output", },
2254 },
2255 },
2256 },
2257}"#;
2258 let ids = comp.paste_fusion_clipboard(snippet, (1.0, 2.0)).unwrap();
2259 let t1 = comp.node(ids[1]);
2260 assert_eq!(comp.node(ids[0]).name, "BG1_1");
2261 assert_eq!(comp.node(ids[0]).pos, [1.0, 2.0]);
2262 assert_eq!(t1.connected_node("Input"), Some("BG1_1"));
2263 assert_eq!(
2264 t1.inputs["Size"].expression.as_deref(),
2265 Some("BG1_1.Width / 2 + BG10.Width")
2266 );
2267 }
2268
2269 #[test]
2270 fn paste_group_renames_nested_tools_and_remaps_macro_output() {
2271 let mut comp = sample_comp();
2272 let first = comp.paste_fusion_clipboard(GROUP_SNIPPET, (0.0, 0.0)).unwrap();
2273 let second = comp.paste_fusion_clipboard(GROUP_SNIPPET, (50.0, 0.0)).unwrap();
2274 let (g1, g2) = (comp.node(first[0]), comp.node(second[0]));
2275 assert_eq!((g1.name.as_str(), g2.name.as_str()), ("Group1", "Group1_1"));
2276 assert_eq!(g2.pos, [60.0, 20.0]);
2277
2278 let inner = comp.node(g2.macro_output.expect("macro output"));
2279 assert_eq!(inner.name, "Inner1_1");
2280 assert!(inner.internal);
2281 assert_eq!(inner.connected_node("XBlurSize"), Some("Inner1Size_1"));
2282 assert!(comp.splines.contains_key("Inner1Size_1"));
2283 assert_eq!(comp.node(g1.macro_output.unwrap()).name, "Inner1");
2284 assert_eq!(comp.find_node("Group1_1"), Some(second[0]));
2285 assert_eq!(comp.find_node("Inner1_1"), g2.macro_output);
2286 }
2287
2288 #[test]
2289 fn paste_is_one_undo_step_and_redoable() {
2290 let mut comp = sample_comp();
2291 let mut history = CompHistory::new();
2292 let bg = comp.find_node("BG1").unwrap();
2293 let bc = comp.find_node("BC1").unwrap();
2294 let snippet = comp.export_fusion_clipboard(&[bg, bc]);
2295 let (nodes, splines) = (comp.nodes.len(), comp.splines.len());
2296 history.mark_saved(&comp);
2297
2298 let ids = history
2299 .paste_fusion_clipboard(&mut comp, &snippet, (60.0, 40.0))
2300 .unwrap();
2301 assert_eq!(ids.len(), 2);
2302 assert_eq!(history.undo_len(), 1);
2303 assert_eq!(history.undo_label(), Some("Paste"));
2304 assert!(history.is_dirty(&comp));
2305
2306 assert!(history.undo(&mut comp));
2307 assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes, splines));
2308 assert!(comp.find_node("BG1_1").is_none());
2309 assert!(!comp.to_fusion_string().contains("BG1_1"));
2310 assert!(!history.can_undo());
2311 assert!(!history.is_dirty(&comp));
2312
2313 assert!(history.redo(&mut comp));
2314 assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes + 2, splines + 1));
2315 let pasted = comp.find_node("BC1_1").unwrap();
2316 assert_eq!(comp.node(pasted).connected_node("Input"), Some("BG1_1"));
2317 assert!(!history.can_redo());
2318 }
2319
2320 #[test]
2321 fn paste_rejects_garbage_without_touching_comp_or_history() {
2322 let mut comp = sample_comp();
2323 let mut history = CompHistory::new();
2324 let (rev, nodes) = (comp.revision, comp.nodes.len());
2325 for bad in ["", "hello world", "{ Foo = 1 }", "{ Tools = ordered() { } }", "{ Tools = "] {
2326 assert!(history.paste_fusion_clipboard(&mut comp, bad, (0.0, 0.0)).is_err(), "{bad:?}");
2327 }
2328 assert_eq!((comp.revision, comp.nodes.len()), (rev, nodes));
2329 assert!(!history.can_undo());
2330 assert!(!history.in_group());
2331 }
2332
2333 const TWO_GROUPS: &str = r#"Composition {
2334 Tools = ordered() {
2335 BG = Background { },
2336 GA = GroupOperator {
2337 Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, },
2338 Tools = ordered() {
2339 Same = Blur { Inputs = { XBlurSize = Input { SourceOp = "SameSize", Source = "Value", }, }, },
2340 SameSize = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, },
2341 },
2342 },
2343 GB = GroupOperator {
2344 Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, },
2345 Tools = ordered() {
2346 Same = Blur { },
2347 },
2348 },
2349 },
2350}"#;
2351
2352 fn tool_names(tools: &LuaTable) -> Vec<&str> {
2353 tools
2354 .entries
2355 .iter()
2356 .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None })
2357 .collect()
2358 }
2359
2360 #[test]
2361 fn mark_saved_stops_later_edits_coalescing_into_the_saved_step() {
2362 let mut comp = sample_comp();
2363 let mut history = CompHistory::new();
2364 let bg = comp.find_node("BG1").unwrap();
2365
2366 history.push_coalesced(&comp, "Drag", "drag");
2367 comp.set_node_pos(bg, [1.0, 1.0]);
2368 history.mark_saved(&comp);
2369 assert!(!history.is_dirty(&comp));
2370
2371 history.push_coalesced(&comp, "Drag", "drag");
2372 comp.set_node_pos(bg, [2.0, 2.0]);
2373 assert_eq!(history.undo_len(), 2);
2374 assert!(history.is_dirty(&comp));
2375 }
2376
2377 #[test]
2378 fn undo_and_redo_keep_the_live_file_identity() {
2379 let mut comp = sample_comp();
2380 comp.path = Some("/tmp/original.comp".into());
2381 comp.name = "original".to_owned();
2382 let mut history = CompHistory::new();
2383 let bg = comp.find_node("BG1").unwrap();
2384
2385 history.push_snapshot(&comp, "Move");
2386 comp.set_node_pos(bg, [9.0, 9.0]);
2387 comp.path = Some("/tmp/save_as.comp".into());
2388 comp.name = "save_as".to_owned();
2389
2390 assert!(history.undo(&mut comp));
2391 assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as"));
2392 assert!(history.redo(&mut comp));
2393 assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as"));
2394 }
2395
2396 #[test]
2397 fn deleting_a_group_removes_its_private_tools_and_modifiers() {
2398 let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
2399 let g = comp.find_node("Group1").unwrap();
2400 let deleted = comp.delete_nodes(&[g]);
2401 assert_eq!(deleted, ["Group1", "Inner1"]);
2402 assert!(comp.nodes.is_empty());
2403 assert!(comp.splines.is_empty());
2404 assert!(tool_names(comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap()).is_empty());
2405 }
2406
2407 #[test]
2408 fn deleting_a_node_keeps_splines_still_used_by_expression_modifiers() {
2409 let src = r#"Composition {
2410 Tools = ordered() {
2411 N = Transform { Inputs = { Angle = Input { SourceOp = "Shared", Source = "Value", }, Size = Input { SourceOp = "E", Source = "NumberResult", }, }, },
2412 M = Transform { Inputs = { Angle = Input { SourceOp = "Own", Source = "Value", }, Size = Input { SourceOp = "E2", Source = "NumberResult", }, }, },
2413 E = Expression { Inputs = { n1 = Input { SourceOp = "Shared", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, },
2414 E2 = Expression { Inputs = { n1 = Input { SourceOp = "Own", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, },
2415 Shared = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, },
2416 Own = BezierSpline { KeyFrames = { [0] = { 2, Flags = { Linear = true } } }, },
2417 },
2418}"#;
2419 let mut comp = Comp::from_fusion_str(src).unwrap();
2420 comp.delete_nodes(&[comp.find_node("M").unwrap()]);
2421 assert!(!comp.expression_modifiers.contains_key("E2"));
2422 assert!(!comp.splines.contains_key("Own"));
2423 assert!(comp.expression_modifiers.contains_key("E"));
2424 assert!(comp.splines.contains_key("Shared"));
2425
2426 // Deleting the other owner prunes the expression modifier and its spline.
2427 let mut comp = Comp::from_fusion_str(src).unwrap();
2428 comp.delete_nodes(&[comp.find_node("N").unwrap()]);
2429 assert!(!comp.expression_modifiers.contains_key("E"));
2430 assert!(!comp.splines.contains_key("Shared"));
2431
2432 // A spline referenced by a surviving (unpruned) expression modifier outlives its owner.
2433 let with_orphan = src.replace("\t},\n}", "\t\tEO = Expression { Inputs = { n1 = Input { SourceOp = \"Shared\", Source = \"Value\", }, }, },\n\t},\n}");
2434 let mut comp = Comp::from_fusion_str(&with_orphan).unwrap();
2435 comp.delete_nodes(&[comp.find_node("N").unwrap()]);
2436 assert!(comp.expression_modifiers.contains_key("EO"));
2437 assert!(comp.splines.contains_key("Shared"));
2438 }
2439
2440 #[test]
2441 fn export_includes_modifiers_nested_in_a_copied_internal_node_once() {
2442 let comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
2443 let inner = comp.find_node("Inner1").unwrap();
2444 let clip = comp.export_fusion_clipboard(&[inner]);
2445 let parsed = parse_lua(&clip).unwrap();
2446 let tools = parsed.as_table().unwrap().get_table("Tools").unwrap();
2447 assert_eq!(tool_names(tools), ["Inner1", "Inner1Size"]);
2448
2449 let whole = comp.export_fusion_clipboard(&[comp.find_node("Group1").unwrap()]);
2450 assert_eq!(whole.matches("Inner1Size = BezierSpline").count(), 1, "{whole}");
2451 }
2452
2453 #[test]
2454 fn paste_never_links_to_group_private_tools() {
2455 let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
2456 let snippet = r#"{ Tools = ordered() { T = Transform { Inputs = {
2457 Input = Input { SourceOp = "Inner1", Source = "Output", },
2458 Mask = Input { SourceOp = "Group1", Source = "Output", },
2459 Angle = Input { SourceOp = "Inner1Size", Source = "Value", },
2460 }, }, }, }"#;
2461 let ids = comp.paste_fusion_clipboard(snippet, (0.0, 0.0)).unwrap();
2462 let t = comp.node(ids[0]);
2463 assert_eq!(t.connected_node("Input"), None);
2464 assert_eq!(t.connected_node("Angle"), None);
2465 assert_eq!(t.connected_node("Mask"), Some("Group1"));
2466 }
2467
2468 #[test]
2469 fn expression_renames_skip_property_names() {
2470 let renames = HashMap::from([("Size".to_owned(), "Big".to_owned())]);
2471 assert_eq!(
2472 rename_expression_idents("Other.Size + Size.Width * Size", &renames),
2473 "Other.Size + Big.Width * Big"
2474 );
2475 }
2476
2477 #[test]
2478 fn rename_and_paste_rewrite_expression_modifier_formulas() {
2479 let src = r#"Composition {
2480 Tools = ordered() {
2481 BG = Background { },
2482 E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width + Other.BG", }, }, },
2483 },
2484}"#;
2485 let mut comp = Comp::from_fusion_str(src).unwrap();
2486 let bg = comp.find_node("BG").unwrap();
2487 comp.rename_node(bg, "Plate").unwrap();
2488 let formula = |c: &Comp| c.expression_modifiers["E"].inputs["NumberExpression"].value.clone();
2489 assert_eq!(formula(&comp), Some(ParamValue::Text("Plate.Width + Other.BG".to_owned())));
2490 assert!(comp.to_fusion_string().contains("Plate.Width + Other.BG"));
2491
2492 let paste = r#"{ Tools = ordered() { BG = Background { }, E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width", }, }, }, }, }"#;
2493 comp.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap();
2494 assert_eq!(
2495 comp.expression_modifiers["E_1"].inputs["NumberExpression"].value,
2496 Some(ParamValue::Text("BG.Width".to_owned()))
2497 );
2498 let mut again = Comp::from_fusion_str(paste).unwrap();
2499 again.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap();
2500 assert_eq!(
2501 again.expression_modifiers["E_1"].inputs["NumberExpression"].value,
2502 Some(ParamValue::Text("BG_1.Width".to_owned()))
2503 );
2504 }
2505
2506 #[test]
2507 fn renaming_one_groups_private_tool_leaves_same_named_tools_elsewhere() {
2508 let mut comp = Comp::from_fusion_str(TWO_GROUPS).unwrap();
2509 let (ga, gb) = (comp.find_node("GA").unwrap(), comp.find_node("GB").unwrap());
2510 let a_same = comp.nodes.iter().position(|n| n.name == "Same" && n.id.0 < ga.0).unwrap();
2511 assert_eq!(comp.rename_node(NodeId(a_same), "Renamed").unwrap(), "Renamed");
2512
2513 let text = comp.to_fusion_string();
2514 let saved = Comp::from_fusion_str(&text).unwrap();
2515 let group_tools = |name: &str| {
2516 let g = saved.node(saved.find_node(name).unwrap());
2517 (
2518 g.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp").unwrap().to_owned(),
2519 tool_names(find_raw_tool_in(&saved, name)).into_iter().map(str::to_owned).collect::<Vec<_>>(),
2520 )
2521 };
2522 assert_eq!(group_tools("GA"), ("Renamed".to_owned(), vec!["Renamed".to_owned(), "SameSize".to_owned()]));
2523 assert_eq!(group_tools("GB"), ("Same".to_owned(), vec!["Same".to_owned()]));
2524 assert_eq!(comp.node(gb).name, "GB");
2525 }
2526
2527 fn find_raw_tool_in<'a>(comp: &'a Comp, group: &str) -> &'a LuaTable {
2528 let tools = comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap();
2529 find_raw_tool(tools, group).unwrap().get_table("Tools").unwrap()
2530 }
2531
2532 #[test]
2533 fn renaming_a_top_level_tool_ignores_groups_with_a_private_tool_of_that_name() {
2534 let src = TWO_GROUPS.replace("BG = Background { },", "BG = Background { },\n\t\tSame = Blur { },");
2535 let mut comp = Comp::from_fusion_str(&src).unwrap();
2536 let top = comp.find_node("Same").unwrap();
2537 assert!(!comp.node(top).internal);
2538 comp.rename_node(top, "Top").unwrap();
2539 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
2540 let ga = saved.node(saved.find_node("GA").unwrap());
2541 assert_eq!(
2542 ga.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp"),
2543 Some("Same")
2544 );
2545 assert!(saved.find_node("Top").is_some_and(|id| !saved.node(id).internal));
2546 }
2547
2548 #[test]
2549 fn duplicate_nodes_clones_groups_and_curve_modifiers() {
2550 let src = r#"Composition {
2551 Tools = ordered() {
2552 BG = Background { },
2553 HC = HueCurves {
2554 Inputs = {
2555 Input = Input { SourceOp = "BG", Source = "Output", },
2556 RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", },
2557 },
2558 Tools = ordered() {
2559 HC_RSup = LUTBezier { KeyColorSplines = { [0] = { [0] = { 0.5 }, [6] = { 0.5 } } }, },
2560 },
2561 },
2562 },
2563}"#;
2564 let mut comp = Comp::from_fusion_str(src).unwrap();
2565 let hc = comp.find_node("HC").unwrap();
2566 let dup = comp.duplicate_nodes(&[hc], [10.0, 0.0]);
2567 assert_eq!(dup.len(), 1);
2568 let d = comp.node(dup[0]);
2569 assert_eq!(d.name, "HC_1");
2570 assert_eq!(d.connected_node("Input"), Some("BG"));
2571 assert_eq!(d.connected_node("RedSuppress"), Some("HC_RSup_1"));
2572 assert!(comp.splines.contains_key("HC_RSup_1") && comp.splines.contains_key("HC_RSup"));
2573 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
2574 assert!(saved.splines.contains_key("HC_RSup_1"));
2575
2576 let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
2577 let g = comp.find_node("Group1").unwrap();
2578 let dup = comp.duplicate_nodes(&[g], [0.0, 80.0]);
2579 let copy = comp.node(dup[0]);
2580 assert_eq!(copy.name, "Group1_1");
2581 assert_eq!(comp.node(copy.macro_output.unwrap()).name, "Inner1_1");
2582 assert!(comp.splines.contains_key("Inner1Size_1"));
2583 }
2584
2585 #[test]
2586 fn updating_a_keyframe_moves_its_handles_with_it() {
2587 let mut comp = sample_comp();
2588 let bc = comp.find_node("BC1").unwrap();
2589 comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].lh = Some([20.0, 1.5]);
2590 comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].rh = Some([40.0, 2.5]);
2591 comp.set_keyframe(bc, "Gain", 30.0, 3.0).unwrap();
2592 let kf = &comp.splines["BC1Gain"].keyframes[1];
2593 assert_eq!((kf.value, kf.lh, kf.rh), (3.0, Some([20.0, 2.5]), Some([40.0, 3.5])));
2594 }
2595
2596 #[test]
2597 fn deleting_the_last_keyframe_keeps_its_value_as_a_static_input() {
2598 let mut comp = sample_comp();
2599 let bc = comp.find_node("BC1").unwrap();
2600 // Within the shared 1e-4 tolerance.
2601 assert!(comp.delete_keyframe("BC1Gain", 0.00005));
2602 assert!(comp.delete_keyframe("BC1Gain", 30.0));
2603 assert!(!comp.splines.contains_key("BC1Gain"));
2604 assert_eq!(comp.node(bc).connected_node("Gain"), None);
2605 assert_eq!(comp.node(bc).static_number("Gain"), Some(2.0));
2606
2607 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
2608 let r = saved.node(saved.find_node("BC1").unwrap());
2609 assert_eq!(r.static_number("Gain"), Some(2.0));
2610 assert!(!saved.to_fusion_string().contains("BC1Gain"));
2611 }
2612}
crates/model/src/edit/clipboard.rs created+696
...@@ -0,0 +1,696 @@
1use super::{
2 EXPRESSION_FORMULA_INPUTS, collect_source_ops_in_table, sanitize_lua_ident, set_view_info_pos,
3};
4use crate::comp::{Comp, Node, NodeId, ensure_table_mut, find_raw_tool};
5use crate::lua_value::{LuaKey, LuaTable, LuaValue, parse_lua};
6use std::collections::{HashMap, HashSet, VecDeque};
7
8impl Comp {
9 pub fn export_fusion_clipboard(&self, ids: &[NodeId]) -> String {
10 let synced = self.sync_to_raw_ast();
11 let root_tools = synced.get_table("Tools");
12 let node_names: HashSet<&str> = self.nodes.iter().map(|n| n.name.as_str()).collect();
13
14 let mut picked: Vec<&Node> = Vec::new();
15 for &id in ids {
16 if let Some(n) = self.nodes.get(id.0) {
17 if !picked.iter().any(|p| p.id == n.id) {
18 picked.push(n);
19 }
20 }
21 }
22 let mut tools = LuaTable {
23 tag: Some("ordered".to_owned()),
24 entries: Vec::new(),
25 };
26 let mut refs: VecDeque<String> = VecDeque::new();
27 for n in &picked {
28 let raw = root_tools.and_then(|t| find_raw_tool(t, &n.name)).unwrap_or(&n.raw);
29 let mut found = HashSet::new();
30 collect_source_ops_in_table(raw, &mut found);
31 let mut found: Vec<String> = found.into_iter().collect();
32 found.sort();
33 refs.extend(found);
34 tools.set(LuaKey::Str(n.name.clone()), LuaValue::Table(raw.clone()));
35 }
36 while let Some(name) = refs.pop_front() {
37 if tools.get(&name).is_some() || node_names.contains(name.as_str()) {
38 continue;
39 }
40 // Modifiers already nested inside a copied group travel with it.
41 let nested_in_copy = tools
42 .entries
43 .iter()
44 .filter_map(|(_, v)| v.as_table()?.get_table("Tools"))
45 .any(|inner| find_raw_tool(inner, &name).is_some());
46 let Some(modifier) = root_tools.and_then(|t| find_raw_tool(t, &name)).filter(|_| !nested_in_copy)
47 else {
48 continue;
49 };
50 let mut found = HashSet::new();
51 collect_source_ops_in_table(modifier, &mut found);
52 let mut found: Vec<String> = found.into_iter().collect();
53 found.sort();
54 refs.extend(found);
55 tools.set(LuaKey::Str(name), LuaValue::Table(modifier.clone()));
56 }
57
58 let mut doc = LuaTable::default();
59 doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools));
60 if let Some(first) = picked.first() {
61 doc.set(
62 LuaKey::Str("ActiveTool".to_owned()),
63 LuaValue::String(first.name.clone()),
64 );
65 }
66 doc.to_fusion_string()
67 }
68
69 /// Pastes Fusion clipboard Lua (`{ Tools = ordered() { ... } }` or a full `Composition`),
70 /// renaming colliding tools/modifiers (`Blur1` -> `Blur1_1`), rewiring references among the
71 /// pasted tools, dropping references to tools that exist nowhere, and shifting each top-level
72 /// tool's `ViewInfo.Pos` by `offset`. Returns the new top-level flow nodes; on `Err` the comp
73 /// is untouched. Prefer [`CompHistory::paste_fusion_clipboard`] for an undoable paste.
74 pub fn paste_fusion_clipboard(
75 &mut self,
76 lua_snippet: &str,
77 offset: (f32, f32),
78 ) -> Result<Vec<NodeId>, String> {
79 let parsed = parse_lua(lua_snippet).map_err(|e| format!("clipboard is not Fusion Lua: {e}"))?;
80 let mut tools = parsed
81 .as_table()
82 .and_then(|t| t.get_table("Tools"))
83 .filter(|t| !t.entries.is_empty())
84 .cloned()
85 .ok_or_else(|| "clipboard has no Fusion tools".to_owned())?;
86
87 let mut pasted_names = Vec::new();
88 collect_tool_names(&tools, &mut pasted_names);
89 let pasted_set: HashSet<&str> = pasted_names.iter().map(String::as_str).collect();
90
91 drop_unknown_source_ops(&mut tools, &mut |name| {
92 pasted_set.contains(name) || self.is_linkable_external(name)
93 });
94
95 let mut reserved: HashSet<String> = self.nodes.iter().map(|n| n.name.clone()).collect();
96 let mut renames: HashMap<String, String> = HashMap::new();
97 for name in &pasted_names {
98 if renames.contains_key(name) {
99 continue;
100 }
101 let fresh = self.generate_unique_name_excluding(name, &reserved);
102 reserved.insert(fresh.clone());
103 renames.insert(name.clone(), fresh);
104 }
105 rename_tools(&mut tools, &renames);
106
107 let mut doc = LuaTable {
108 tag: Some("Composition".to_owned()),
109 entries: Vec::new(),
110 };
111 doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools));
112 let staged = Comp::from_fusion_str(&doc.to_fusion_string())
113 .map_err(|e| format!("clipboard tools failed to parse: {e}"))?;
114 let Some(staged_tools) = doc.get_table("Tools") else {
115 return Err("clipboard has no Fusion tools".to_owned());
116 };
117
118 let base = self.nodes.len();
119 let shift = |id: NodeId| NodeId(base + id.0);
120 let mut created = Vec::new();
121 let mut top_level: HashMap<String, LuaTable> = HashMap::new();
122 for mut node in staged.nodes {
123 node.id = shift(node.id);
124 node.macro_output = node.macro_output.map(shift);
125 if !node.internal {
126 node.pos = [node.pos[0] + offset.0, node.pos[1] + offset.1];
127 set_view_info_pos(&mut node.raw, node.pos);
128 top_level.insert(node.name.clone(), node.raw.clone());
129 created.push(node.id);
130 }
131 self.nodes.push(node);
132 }
133 for (name, id) in staged.node_by_name {
134 self.node_by_name.entry(name).or_insert(shift(id));
135 }
136 self.splines.extend(staged.splines);
137 self.poly_paths.extend(staged.poly_paths);
138 self.gradient_modifiers.extend(staged.gradient_modifiers);
139 self.text_modifiers.extend(staged.text_modifiers);
140 self.text_splines.extend(staged.text_splines);
141 self.polyline_splines.extend(staged.polyline_splines);
142 self.text_cls.extend(staged.text_cls);
143 self.shakes.extend(staged.shakes);
144 self.expression_modifiers.extend(staged.expression_modifiers);
145
146 if let Some(root) = self.raw_root.as_mut() {
147 let dest = ensure_table_mut(root, "Tools", Some("ordered"));
148 for (key, value) in &staged_tools.entries {
149 let LuaKey::Str(name) = key else { continue };
150 let table = top_level.remove(name).map_or_else(|| value.clone(), LuaValue::Table);
151 dest.set(key.clone(), table);
152 }
153 }
154
155 self.revision += 1;
156 Ok(created)
157 }
158
159 /// Duplicates the selected nodes at `pos + offset` with unique names, as a copy + paste:
160 /// wires between duplicated nodes are preserved, wires to other nodes stay intact, and owned
161 /// modifiers and group contents are cloned. Returns the new top-level nodes.
162 pub fn duplicate_nodes(&mut self, ids: &[NodeId], offset: [f32; 2]) -> Vec<NodeId> {
163 let snippet = self.export_fusion_clipboard(ids);
164 self.paste_fusion_clipboard(&snippet, (offset[0], offset[1])).unwrap_or_default()
165 }
166
167 fn generate_unique_name_excluding(&self, hint: &str, reserved: &HashSet<String>) -> String {
168 let base = sanitize_lua_ident(hint);
169 if !self.name_exists(&base) && !reserved.contains(&base) {
170 return base;
171 }
172 let mut idx = 1usize;
173 loop {
174 let candidate = format!("{base}_{idx}");
175 if !self.name_exists(&candidate) && !reserved.contains(&candidate) {
176 return candidate;
177 }
178 idx += 1;
179 }
180 }
181}
182
183pub(super) fn collect_tool_names(tools: &LuaTable, out: &mut Vec<String>) {
184 for (key, value) in &tools.entries {
185 let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else {
186 continue;
187 };
188 out.push(name.clone());
189 if let Some(inner) = tool.get_table("Tools") {
190 collect_tool_names(inner, out);
191 }
192 }
193}
194
195/// Renames tool keys (recursively) and rewrites every reference to them: `SourceOp` values and
196/// whole-word identifiers inside `Expression` strings.
197pub(super) fn rename_tools(tools: &mut LuaTable, renames: &HashMap<String, String>) {
198 for (key, value) in &mut tools.entries {
199 let LuaKey::Str(name) = key else { continue };
200 if let Some(new) = renames.get(name.as_str()) {
201 *name = new.clone();
202 }
203 if let Some(tool) = value.as_table_mut() {
204 rewrite_references(tool, renames);
205 if let Some(inner) = tool.get_table_mut("Tools") {
206 rename_tools(inner, renames);
207 }
208 }
209 }
210}
211
212pub(super) fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
213 rewrite_formula_values(tbl, renames);
214 for (key, value) in &mut tbl.entries {
215 match (key, value) {
216 (LuaKey::Str(k), LuaValue::String(s)) if k == "SourceOp" => {
217 if let Some(new) = renames.get(s.as_str()) {
218 *s = new.clone();
219 }
220 }
221 (LuaKey::Str(k), LuaValue::String(s)) if k == "Expression" => {
222 *s = rename_expression_idents(s, renames);
223 }
224 (_, LuaValue::Table(sub)) => rewrite_references(sub, renames),
225 _ => {}
226 }
227 }
228}
229
230/// Rewrites the formula strings of an `Expression` modifier table (not recursive).
231pub(super) fn rewrite_formula_values(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
232 if tbl.tag.as_deref() != Some("Expression") {
233 return;
234 }
235 let Some(inputs) = tbl.get_table_mut("Inputs") else { return };
236 for key in EXPRESSION_FORMULA_INPUTS {
237 if let Some(LuaValue::String(formula)) = inputs.get_table_mut(key).and_then(|i| i.get_mut("Value")) {
238 *formula = rename_expression_idents(formula, renames);
239 }
240 }
241}
242
243pub(super) fn rewrite_formulas_deep(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
244 rewrite_formula_values(tbl, renames);
245 for (_, value) in &mut tbl.entries {
246 if let Some(sub) = value.as_table_mut() {
247 rewrite_formulas_deep(sub, renames);
248 }
249 }
250}
251
252/// Renames whole-word identifiers in `expr`, leaving property names (`Other.Size`) alone.
253pub(super) fn rename_expression_idents(expr: &str, renames: &HashMap<String, String>) -> String {
254 let mut out = String::with_capacity(expr.len());
255 let mut word = String::new();
256 let mut prev = None;
257 let flush = |word: &mut String, out: &mut String, prev: Option<char>| {
258 let renamed = renames.get(word.as_str()).filter(|_| prev != Some('.'));
259 out.push_str(renamed.map_or(word.as_str(), String::as_str));
260 word.clear();
261 };
262 for ch in expr.chars() {
263 if ch.is_ascii_alphanumeric() || ch == '_' {
264 word.push(ch);
265 } else {
266 flush(&mut word, &mut out, prev);
267 out.push(ch);
268 prev = Some(ch);
269 }
270 }
271 flush(&mut word, &mut out, prev);
272 out
273}
274
275/// Removes `SourceOp`/`Source` pairs whose target fails `exists`, so pasted tools never point at
276/// missing operators.
277fn drop_unknown_source_ops(tbl: &mut LuaTable, exists: &mut dyn FnMut(&str) -> bool) {
278 let dangling = tbl
279 .get_str("SourceOp")
280 .is_some_and(|name| !exists(name));
281 if dangling {
282 tbl.remove(&LuaKey::Str("SourceOp".to_owned()));
283 tbl.remove(&LuaKey::Str("Source".to_owned()));
284 }
285 for (_, value) in &mut tbl.entries {
286 if let Some(sub) = value.as_table_mut() {
287 drop_unknown_source_ops(sub, exists);
288 }
289 }
290}
291
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296 use crate::comp::ParamValue;
297 use crate::edit::CompHistory;
298 use crate::edit::tests::{GROUP_SNIPPET, sample_comp};
299
300 #[test]
301 fn export_fusion_clipboard_includes_owned_modifiers_and_internal_wires() {
302 let comp = sample_comp();
303 let bg = comp.find_node("BG1").unwrap();
304 let bc = comp.find_node("BC1").unwrap();
305
306 let both = comp.export_fusion_clipboard(&[bg, bc]);
307 assert!(both.contains("Tools = ordered()"), "{both}");
308 assert!(both.contains("ActiveTool = \"BG1\""), "{both}");
309 let parsed = parse_lua(&both).expect("clipboard parses as Lua");
310 let tools = parsed.as_table().unwrap().get_table("Tools").unwrap();
311 let names: Vec<_> = tools
312 .entries
313 .iter()
314 .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None })
315 .collect();
316 assert_eq!(names, ["BG1", "BC1", "BC1Gain"]);
317 assert_eq!(
318 tools
319 .get_table("BC1")
320 .and_then(|t| t.get_table("Inputs"))
321 .and_then(|i| i.get_table("Input"))
322 .and_then(|i| i.get_str("SourceOp")),
323 Some("BG1")
324 );
325
326 // Selecting only BC1 keeps its owned spline and leaves the external BG1 reference.
327 let only_bc = comp.export_fusion_clipboard(&[bc, bc]);
328 assert!(only_bc.contains("BC1Gain = BezierSpline"));
329 assert!(!only_bc.contains("BG1 = Background"));
330 assert!(only_bc.contains("SourceOp = \"BG1\""));
331
332 // Splines created after load (not yet in `raw_root`) are exported too.
333 let mut comp = comp;
334 let sp = comp.set_keyframe(bg, "Width", 0.0, 1.0).unwrap();
335 assert!(comp.export_fusion_clipboard(&[bg]).contains(&format!("{sp} = BezierSpline")));
336 }
337
338 #[test]
339 fn paste_dedups_names_and_remaps_internal_wires_and_splines() {
340 let mut comp = sample_comp();
341 let bg = comp.find_node("BG1").unwrap();
342 let bc = comp.find_node("BC1").unwrap();
343 let snippet = comp.export_fusion_clipboard(&[bg, bc]);
344 let nodes_before = comp.nodes.len();
345
346 let ids = comp.paste_fusion_clipboard(&snippet, (60.0, 40.0)).expect("paste");
347 assert_eq!(ids.len(), 2);
348 assert_eq!(comp.nodes.len(), nodes_before + 2);
349 let (pbg, pbc) = (comp.node(ids[0]), comp.node(ids[1]));
350 assert_eq!((pbg.name.as_str(), pbc.name.as_str()), ("BG1_1", "BC1_1"));
351 assert_eq!(pbg.pos, [160.0, 90.0]);
352 assert_eq!(pbc.pos, [360.0, 90.0]);
353 assert_eq!(pbc.connected_node("Input"), Some("BG1_1"));
354 assert_eq!(pbc.connected_node("Gain"), Some("BC1Gain_1"));
355 assert_eq!(comp.splines["BC1Gain_1"].keyframes.len(), 2);
356 assert_eq!(comp.splines["BC1Gain"].keyframes.len(), 2);
357 assert_eq!(comp.find_node("BC1_1"), Some(ids[1]));
358 assert_eq!(comp.node(bc).connected_node("Input"), Some("BG1"));
359
360 // Pasting again keeps advancing the suffix instead of clobbering earlier pastes.
361 let again = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap();
362 assert_eq!(comp.node(again[0]).name, "BG1_2");
363 assert_eq!(comp.node(again[1]).connected_node("Input"), Some("BG1_2"));
364
365 // Everything survives a save/load roundtrip, including the cloned spline and offset.
366 let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("reload");
367 let r_bc = reloaded.node(reloaded.find_node("BC1_1").unwrap());
368 assert_eq!(r_bc.pos, [360.0, 90.0]);
369 assert_eq!(r_bc.connected_node("Input"), Some("BG1_1"));
370 assert!(reloaded.splines.contains_key("BC1Gain_1"));
371 }
372
373 #[test]
374 fn paste_external_references_are_kept_when_present_and_dropped_when_missing() {
375 let mut comp = sample_comp();
376 let bc = comp.find_node("BC1").unwrap();
377 let snippet = comp.export_fusion_clipboard(&[bc]);
378
379 let ids = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap();
380 assert_eq!(comp.node(ids[0]).connected_node("Input"), Some("BG1"));
381
382 let mut empty = Comp::from_fusion_str("Composition { Tools = ordered() { } }").unwrap();
383 let ids = empty.paste_fusion_clipboard(&snippet, (5.0, 5.0)).unwrap();
384 let pasted = empty.node(ids[0]);
385 assert_eq!(pasted.name, "BC1");
386 assert_eq!(pasted.connected_node("Input"), None);
387 assert_eq!(pasted.connected_node("Gain"), Some("BC1Gain"));
388 assert!(!empty.to_fusion_string().contains("BG1"));
389 }
390
391 #[test]
392 fn paste_accepts_full_composition_and_rewrites_expressions() {
393 let mut comp = sample_comp();
394 let snippet = r#"Composition {
395 Tools = ordered() {
396 BG1 = Background { Inputs = { Width = Input { Value = 64, } }, },
397 T1 = Transform {
398 Inputs = {
399 Size = Input { Expression = "BG1.Width / 2 + BG10.Width", },
400 Input = Input { SourceOp = "BG1", Source = "Output", },
401 },
402 },
403 },
404}"#;
405 let ids = comp.paste_fusion_clipboard(snippet, (1.0, 2.0)).unwrap();
406 let t1 = comp.node(ids[1]);
407 assert_eq!(comp.node(ids[0]).name, "BG1_1");
408 assert_eq!(comp.node(ids[0]).pos, [1.0, 2.0]);
409 assert_eq!(t1.connected_node("Input"), Some("BG1_1"));
410 assert_eq!(
411 t1.inputs["Size"].expression.as_deref(),
412 Some("BG1_1.Width / 2 + BG10.Width")
413 );
414 }
415
416 #[test]
417 fn paste_group_renames_nested_tools_and_remaps_macro_output() {
418 let mut comp = sample_comp();
419 let first = comp.paste_fusion_clipboard(GROUP_SNIPPET, (0.0, 0.0)).unwrap();
420 let second = comp.paste_fusion_clipboard(GROUP_SNIPPET, (50.0, 0.0)).unwrap();
421 let (g1, g2) = (comp.node(first[0]), comp.node(second[0]));
422 assert_eq!((g1.name.as_str(), g2.name.as_str()), ("Group1", "Group1_1"));
423 assert_eq!(g2.pos, [60.0, 20.0]);
424
425 let inner = comp.node(g2.macro_output.expect("macro output"));
426 assert_eq!(inner.name, "Inner1_1");
427 assert!(inner.internal);
428 assert_eq!(inner.connected_node("XBlurSize"), Some("Inner1Size_1"));
429 assert!(comp.splines.contains_key("Inner1Size_1"));
430 assert_eq!(comp.node(g1.macro_output.unwrap()).name, "Inner1");
431 assert_eq!(comp.find_node("Group1_1"), Some(second[0]));
432 assert_eq!(comp.find_node("Inner1_1"), g2.macro_output);
433 }
434
435 #[test]
436 fn paste_is_one_undo_step_and_redoable() {
437 let mut comp = sample_comp();
438 let mut history = CompHistory::new();
439 let bg = comp.find_node("BG1").unwrap();
440 let bc = comp.find_node("BC1").unwrap();
441 let snippet = comp.export_fusion_clipboard(&[bg, bc]);
442 let (nodes, splines) = (comp.nodes.len(), comp.splines.len());
443 history.mark_saved(&comp);
444
445 let ids = history
446 .paste_fusion_clipboard(&mut comp, &snippet, (60.0, 40.0))
447 .unwrap();
448 assert_eq!(ids.len(), 2);
449 assert_eq!(history.undo_len(), 1);
450 assert_eq!(history.undo_label(), Some("Paste"));
451 assert!(history.is_dirty(&comp));
452
453 assert!(history.undo(&mut comp));
454 assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes, splines));
455 assert!(comp.find_node("BG1_1").is_none());
456 assert!(!comp.to_fusion_string().contains("BG1_1"));
457 assert!(!history.can_undo());
458 assert!(!history.is_dirty(&comp));
459
460 assert!(history.redo(&mut comp));
461 assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes + 2, splines + 1));
462 let pasted = comp.find_node("BC1_1").unwrap();
463 assert_eq!(comp.node(pasted).connected_node("Input"), Some("BG1_1"));
464 assert!(!history.can_redo());
465 }
466
467 #[test]
468 fn paste_rejects_garbage_without_touching_comp_or_history() {
469 let mut comp = sample_comp();
470 let mut history = CompHistory::new();
471 let (rev, nodes) = (comp.revision, comp.nodes.len());
472 for bad in ["", "hello world", "{ Foo = 1 }", "{ Tools = ordered() { } }", "{ Tools = "] {
473 assert!(history.paste_fusion_clipboard(&mut comp, bad, (0.0, 0.0)).is_err(), "{bad:?}");
474 }
475 assert_eq!((comp.revision, comp.nodes.len()), (rev, nodes));
476 assert!(!history.can_undo());
477 assert!(!history.in_group());
478 }
479
480 const TWO_GROUPS: &str = r#"Composition {
481 Tools = ordered() {
482 BG = Background { },
483 GA = GroupOperator {
484 Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, },
485 Tools = ordered() {
486 Same = Blur { Inputs = { XBlurSize = Input { SourceOp = "SameSize", Source = "Value", }, }, },
487 SameSize = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, },
488 },
489 },
490 GB = GroupOperator {
491 Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, },
492 Tools = ordered() {
493 Same = Blur { },
494 },
495 },
496 },
497}"#;
498
499 fn tool_names(tools: &LuaTable) -> Vec<&str> {
500 tools
501 .entries
502 .iter()
503 .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None })
504 .collect()
505 }
506
507 #[test]
508
509 fn deleting_a_group_removes_its_private_tools_and_modifiers() {
510 let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
511 let g = comp.find_node("Group1").unwrap();
512 let deleted = comp.delete_nodes(&[g]);
513 assert_eq!(deleted, ["Group1", "Inner1"]);
514 assert!(comp.nodes.is_empty());
515 assert!(comp.splines.is_empty());
516 assert!(tool_names(comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap()).is_empty());
517 }
518
519 #[test]
520 fn deleting_a_node_keeps_splines_still_used_by_expression_modifiers() {
521 let src = r#"Composition {
522 Tools = ordered() {
523 N = Transform { Inputs = { Angle = Input { SourceOp = "Shared", Source = "Value", }, Size = Input { SourceOp = "E", Source = "NumberResult", }, }, },
524 M = Transform { Inputs = { Angle = Input { SourceOp = "Own", Source = "Value", }, Size = Input { SourceOp = "E2", Source = "NumberResult", }, }, },
525 E = Expression { Inputs = { n1 = Input { SourceOp = "Shared", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, },
526 E2 = Expression { Inputs = { n1 = Input { SourceOp = "Own", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, },
527 Shared = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, },
528 Own = BezierSpline { KeyFrames = { [0] = { 2, Flags = { Linear = true } } }, },
529 },
530}"#;
531 let mut comp = Comp::from_fusion_str(src).unwrap();
532 comp.delete_nodes(&[comp.find_node("M").unwrap()]);
533 assert!(!comp.expression_modifiers.contains_key("E2"));
534 assert!(!comp.splines.contains_key("Own"));
535 assert!(comp.expression_modifiers.contains_key("E"));
536 assert!(comp.splines.contains_key("Shared"));
537
538 // Deleting the other owner prunes the expression modifier and its spline.
539 let mut comp = Comp::from_fusion_str(src).unwrap();
540 comp.delete_nodes(&[comp.find_node("N").unwrap()]);
541 assert!(!comp.expression_modifiers.contains_key("E"));
542 assert!(!comp.splines.contains_key("Shared"));
543
544 // A spline referenced by a surviving (unpruned) expression modifier outlives its owner.
545 let with_orphan = src.replace("\t},\n}", "\t\tEO = Expression { Inputs = { n1 = Input { SourceOp = \"Shared\", Source = \"Value\", }, }, },\n\t},\n}");
546 let mut comp = Comp::from_fusion_str(&with_orphan).unwrap();
547 comp.delete_nodes(&[comp.find_node("N").unwrap()]);
548 assert!(comp.expression_modifiers.contains_key("EO"));
549 assert!(comp.splines.contains_key("Shared"));
550 }
551
552 #[test]
553 fn export_includes_modifiers_nested_in_a_copied_internal_node_once() {
554 let comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
555 let inner = comp.find_node("Inner1").unwrap();
556 let clip = comp.export_fusion_clipboard(&[inner]);
557 let parsed = parse_lua(&clip).unwrap();
558 let tools = parsed.as_table().unwrap().get_table("Tools").unwrap();
559 assert_eq!(tool_names(tools), ["Inner1", "Inner1Size"]);
560
561 let whole = comp.export_fusion_clipboard(&[comp.find_node("Group1").unwrap()]);
562 assert_eq!(whole.matches("Inner1Size = BezierSpline").count(), 1, "{whole}");
563 }
564
565 #[test]
566 fn paste_never_links_to_group_private_tools() {
567 let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
568 let snippet = r#"{ Tools = ordered() { T = Transform { Inputs = {
569 Input = Input { SourceOp = "Inner1", Source = "Output", },
570 Mask = Input { SourceOp = "Group1", Source = "Output", },
571 Angle = Input { SourceOp = "Inner1Size", Source = "Value", },
572 }, }, }, }"#;
573 let ids = comp.paste_fusion_clipboard(snippet, (0.0, 0.0)).unwrap();
574 let t = comp.node(ids[0]);
575 assert_eq!(t.connected_node("Input"), None);
576 assert_eq!(t.connected_node("Angle"), None);
577 assert_eq!(t.connected_node("Mask"), Some("Group1"));
578 }
579
580 #[test]
581 fn expression_renames_skip_property_names() {
582 let renames = HashMap::from([("Size".to_owned(), "Big".to_owned())]);
583 assert_eq!(
584 rename_expression_idents("Other.Size + Size.Width * Size", &renames),
585 "Other.Size + Big.Width * Big"
586 );
587 }
588
589 #[test]
590 fn rename_and_paste_rewrite_expression_modifier_formulas() {
591 let src = r#"Composition {
592 Tools = ordered() {
593 BG = Background { },
594 E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width + Other.BG", }, }, },
595 },
596}"#;
597 let mut comp = Comp::from_fusion_str(src).unwrap();
598 let bg = comp.find_node("BG").unwrap();
599 comp.rename_node(bg, "Plate").unwrap();
600 let formula = |c: &Comp| c.expression_modifiers["E"].inputs["NumberExpression"].value.clone();
601 assert_eq!(formula(&comp), Some(ParamValue::Text("Plate.Width + Other.BG".to_owned())));
602 assert!(comp.to_fusion_string().contains("Plate.Width + Other.BG"));
603
604 let paste = r#"{ Tools = ordered() { BG = Background { }, E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width", }, }, }, }, }"#;
605 comp.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap();
606 assert_eq!(
607 comp.expression_modifiers["E_1"].inputs["NumberExpression"].value,
608 Some(ParamValue::Text("BG.Width".to_owned()))
609 );
610 let mut again = Comp::from_fusion_str(paste).unwrap();
611 again.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap();
612 assert_eq!(
613 again.expression_modifiers["E_1"].inputs["NumberExpression"].value,
614 Some(ParamValue::Text("BG_1.Width".to_owned()))
615 );
616 }
617
618 #[test]
619 fn renaming_one_groups_private_tool_leaves_same_named_tools_elsewhere() {
620 let mut comp = Comp::from_fusion_str(TWO_GROUPS).unwrap();
621 let (ga, gb) = (comp.find_node("GA").unwrap(), comp.find_node("GB").unwrap());
622 let a_same = comp.nodes.iter().position(|n| n.name == "Same" && n.id.0 < ga.0).unwrap();
623 assert_eq!(comp.rename_node(NodeId(a_same), "Renamed").unwrap(), "Renamed");
624
625 let text = comp.to_fusion_string();
626 let saved = Comp::from_fusion_str(&text).unwrap();
627 let group_tools = |name: &str| {
628 let g = saved.node(saved.find_node(name).unwrap());
629 (
630 g.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp").unwrap().to_owned(),
631 tool_names(find_raw_tool_in(&saved, name)).into_iter().map(str::to_owned).collect::<Vec<_>>(),
632 )
633 };
634 assert_eq!(group_tools("GA"), ("Renamed".to_owned(), vec!["Renamed".to_owned(), "SameSize".to_owned()]));
635 assert_eq!(group_tools("GB"), ("Same".to_owned(), vec!["Same".to_owned()]));
636 assert_eq!(comp.node(gb).name, "GB");
637 }
638
639 fn find_raw_tool_in<'a>(comp: &'a Comp, group: &str) -> &'a LuaTable {
640 let tools = comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap();
641 find_raw_tool(tools, group).unwrap().get_table("Tools").unwrap()
642 }
643
644 #[test]
645 fn renaming_a_top_level_tool_ignores_groups_with_a_private_tool_of_that_name() {
646 let src = TWO_GROUPS.replace("BG = Background { },", "BG = Background { },\n\t\tSame = Blur { },");
647 let mut comp = Comp::from_fusion_str(&src).unwrap();
648 let top = comp.find_node("Same").unwrap();
649 assert!(!comp.node(top).internal);
650 comp.rename_node(top, "Top").unwrap();
651 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
652 let ga = saved.node(saved.find_node("GA").unwrap());
653 assert_eq!(
654 ga.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp"),
655 Some("Same")
656 );
657 assert!(saved.find_node("Top").is_some_and(|id| !saved.node(id).internal));
658 }
659
660 #[test]
661 fn duplicate_nodes_clones_groups_and_curve_modifiers() {
662 let src = r#"Composition {
663 Tools = ordered() {
664 BG = Background { },
665 HC = HueCurves {
666 Inputs = {
667 Input = Input { SourceOp = "BG", Source = "Output", },
668 RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", },
669 },
670 Tools = ordered() {
671 HC_RSup = LUTBezier { KeyColorSplines = { [0] = { [0] = { 0.5 }, [6] = { 0.5 } } }, },
672 },
673 },
674 },
675}"#;
676 let mut comp = Comp::from_fusion_str(src).unwrap();
677 let hc = comp.find_node("HC").unwrap();
678 let dup = comp.duplicate_nodes(&[hc], [10.0, 0.0]);
679 assert_eq!(dup.len(), 1);
680 let d = comp.node(dup[0]);
681 assert_eq!(d.name, "HC_1");
682 assert_eq!(d.connected_node("Input"), Some("BG"));
683 assert_eq!(d.connected_node("RedSuppress"), Some("HC_RSup_1"));
684 assert!(comp.splines.contains_key("HC_RSup_1") && comp.splines.contains_key("HC_RSup"));
685 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
686 assert!(saved.splines.contains_key("HC_RSup_1"));
687
688 let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
689 let g = comp.find_node("Group1").unwrap();
690 let dup = comp.duplicate_nodes(&[g], [0.0, 80.0]);
691 let copy = comp.node(dup[0]);
692 assert_eq!(copy.name, "Group1_1");
693 assert_eq!(comp.node(copy.macro_output.unwrap()).name, "Inner1_1");
694 assert!(comp.splines.contains_key("Inner1Size_1"));
695 }
696}
crates/model/src/edit/defaults.rs created+176
...@@ -0,0 +1,176 @@
1use crate::comp::{ParamValue, vec2_lua};
2use crate::lua_value::{LuaKey, LuaTable, LuaValue};
3
4pub(super) fn default_view_info_for_kind(kind: &str, pos: [f32; 2]) -> LuaTable {
5 let tag = match kind {
6 "PipeRouter" => "PipeRouterInfo",
7 "Underlay" => "UnderlayInfo",
8 "Note" | "StickyNote" => "StickyNoteInfo",
9 _ => "OperatorInfo",
10 };
11 let mut vi = LuaTable {
12 tag: Some(tag.to_owned()),
13 entries: Vec::new(),
14 };
15 vi.set(
16 LuaKey::Str("Pos".to_owned()),
17 vec2_lua(pos[0] as f64, pos[1] as f64),
18 );
19 match kind {
20 "Underlay" => {
21 vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(172.0, 166.364));
22 }
23 "Note" | "StickyNote" => {
24 let mut flags = LuaTable::default();
25 flags.set(LuaKey::Str("Expanded".to_owned()), LuaValue::Bool(true));
26 vi.set(LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags));
27 vi.set(LuaKey::Str("Size".to_owned()), vec2_lua(196.0, 179.364));
28 }
29 _ => {}
30 }
31 vi
32}
33
34/// Returns sensible Fusion 21.1 default inputs for common tool classes so Fusion Studio opens
35/// newly created nodes cleanly without errors.
36pub(super) fn default_inputs_for_kind(kind: &str, width: u32, height: u32) -> Vec<(String, ParamValue)> {
37 let w = width as f64;
38 let h = height as f64;
39 let num = |k: &str, v: f64| (k.to_owned(), ParamValue::Number(v));
40 let pt = |k: &str, x: f64, y: f64| (k.to_owned(), ParamValue::Point([x, y]));
41 let txt = |k: &str, s: &str| (k.to_owned(), ParamValue::Text(s.to_owned()));
42 let fuid = |k: &str, s: &str| (k.to_owned(), ParamValue::FuId(s.to_owned()));
43
44 match kind {
45 "Background" => vec![
46 num("Width", w),
47 num("Height", h),
48 num("UseFrameFormatSettings", 1.0),
49 num("TopLeftRed", 0.0),
50 num("TopLeftGreen", 0.0),
51 num("TopLeftBlue", 0.0),
52 num("TopLeftAlpha", 1.0),
53 ],
54 "Merge" => vec![
55 num("PerformDepthMerge", 0.0),
56 pt("Center", 0.5, 0.5),
57 num("Size", 1.0),
58 num("Angle", 0.0),
59 num("Blend", 1.0),
60 ],
61 "Transform" => vec![
62 pt("Center", 0.5, 0.5),
63 pt("Pivot", 0.5, 0.5),
64 num("Size", 1.0),
65 num("Angle", 0.0),
66 ],
67 "Blur" => vec![fuid("Filter", "Fast Gaussian"), num("XBlurSize", 1.0)],
68 "Glow" => vec![num("XGlowSize", 10.0), num("Glow", 0.8)],
69 "SoftGlow" => vec![
70 fuid("Filter", "Fast Gaussian"),
71 num("Gain", 2.0),
72 num("XGlowSize", 10.0),
73 ],
74 "BrightnessContrast" => vec![
75 num("Gain", 1.0),
76 num("Lift", 0.0),
77 num("Gamma", 1.0),
78 num("Contrast", 0.0),
79 num("Brightness", 0.0),
80 num("Saturation", 1.0),
81 ],
82 "ColorCorrector" => vec![
83 num("WheelSaturation1", 1.0),
84 num("MasterRGBGain", 1.0),
85 num("MasterRGBGamma", 1.0),
86 ],
87 "ColorGain" => vec![
88 num("GainRed", 1.0),
89 num("GainGreen", 1.0),
90 num("GainBlue", 1.0),
91 num("GainAlpha", 1.0),
92 num("GammaRed", 1.0),
93 num("GammaGreen", 1.0),
94 num("GammaBlue", 1.0),
95 ],
96 "RectangleMask" => vec![
97 num("MaskWidth", w),
98 num("MaskHeight", h),
99 pt("PixelAspect", 1.0, 1.0),
100 pt("Center", 0.5, 0.5),
101 num("Width", 0.5),
102 num("Height", 0.5),
103 num("CornerRadius", 0.0),
104 num("SoftEdge", 0.0),
105 ],
106 "EllipseMask" => vec![
107 num("MaskWidth", w),
108 num("MaskHeight", h),
109 pt("PixelAspect", 1.0, 1.0),
110 pt("Center", 0.5, 0.5),
111 num("Width", 0.5),
112 num("Height", 0.5),
113 num("SoftEdge", 0.0),
114 ],
115 "PolylineMask" => vec![
116 num("MaskWidth", w),
117 num("MaskHeight", h),
118 pt("PixelAspect", 1.0, 1.0),
119 num("SoftEdge", 0.0),
120 ],
121 "BitmapMask" => vec![
122 num("MaskWidth", w),
123 num("MaskHeight", h),
124 pt("PixelAspect", 1.0, 1.0),
125 fuid("Channel", "Alpha"),
126 ],
127 "TextPlus" => vec![
128 num("Width", w),
129 num("Height", h),
130 num("UseFrameFormatSettings", 1.0),
131 txt("StyledText", ""),
132 txt("Font", "Open Sans"),
133 txt("Style", "Bold"),
134 num("Size", 0.08),
135 pt("Center", 0.5, 0.5),
136 ],
137 "Loader" => vec![],
138 "Saver" => vec![num("ProcessWhenBlendIs00", 0.0), num("CreateDir", 1.0)],
139 "Displace" => vec![
140 num("Type", 0.0),
141 num("XRefraction", 0.0),
142 num("YRefraction", 0.0),
143 num("RefractionStrength", 0.0),
144 ],
145 "FastNoise" => vec![
146 num("Width", w),
147 num("Height", h),
148 num("UseFrameFormatSettings", 1.0),
149 num("Detail", 2.0),
150 num("Contrast", 1.0),
151 num("XScale", 2.0),
152 num("Seethe", 0.0),
153 ],
154 "PipeRouter" | "Underlay" => vec![],
155 "Switch" | "Fuse.Switch" => vec![num("Source", 0.0)],
156 "TimeStretcher" => vec![num("SourceTime", 0.0), num("InterpolateBetweenFrames", 0.0)],
157 "TimeSpeed" => vec![num("Speed", 1.0), num("Delay", 0.0)],
158 "Renderer3D" => vec![
159 num("Width", w),
160 num("Height", h),
161 num("UseFrameFormatSettings", 1.0),
162 fuid("RendererType", "RendererOpenGL"),
163 ],
164 "Camera3D" => vec![num("FLength", 24.0), num("PlaneOfFocus", 5.0)],
165 "Merge3D" => vec![num("PassThroughLights", 1.0)],
166 "Transform3D" => vec![num("Transform3DOp.Scale.X", 1.0)],
167 "ImagePlane3D" => vec![
168 num("SurfacePlaneInputs.Width", 1.0),
169 num("SurfacePlaneInputs.Height", 1.0),
170 ],
171 "Shape3D" => vec![fuid("Shape", "SurfacePlaneInputs")],
172 "Note" | "StickyNote" => vec![txt("Comments", "")],
173 _ => vec![],
174 }
175}
176
crates/model/src/edit/history.rs created+417
...@@ -0,0 +1,417 @@
1use crate::comp::{Comp, NodeId};
2use std::collections::VecDeque;
3
4/// Default maximum number of undo steps retained by [`CompHistory`].
5pub const DEFAULT_MAX_HISTORY: usize = 128;
6
7#[derive(Clone, Debug)]
8struct HistoryEntry {
9 label: String,
10 snapshot: Comp,
11 coalesce_key: Option<String>,
12}
13
14/// Snapshot-based undo/redo history stack for [`Comp`] with transaction groups and drag coalescing.
15#[derive(Clone, Debug)]
16pub struct CompHistory {
17 undo_stack: VecDeque<HistoryEntry>,
18 redo_stack: Vec<HistoryEntry>,
19 max_depth: usize,
20 active_group: Option<(String, Comp)>,
21 group_depth: usize,
22 /// Position in `undo_stack` corresponding to the last saved state (`Some(0)` means clean at
23 /// depth 0; `None` means the saved state is no longer reachable via undo/redo).
24 saved_undo_depth: Option<usize>,
25 saved_revision: Option<u64>,
26}
27
28impl Default for CompHistory {
29 fn default() -> Self {
30 Self::new()
31 }
32}
33
34impl CompHistory {
35 pub fn new() -> Self {
36 Self::with_max_depth(DEFAULT_MAX_HISTORY)
37 }
38
39 pub fn with_max_depth(max_depth: usize) -> Self {
40 Self {
41 undo_stack: VecDeque::new(),
42 redo_stack: Vec::new(),
43 max_depth: max_depth.max(1),
44 active_group: None,
45 group_depth: 0,
46 saved_undo_depth: None,
47 saved_revision: None,
48 }
49 }
50
51 pub fn max_depth(&self) -> usize {
52 self.max_depth
53 }
54
55 pub fn can_undo(&self) -> bool {
56 !self.undo_stack.is_empty()
57 }
58
59 pub fn can_redo(&self) -> bool {
60 !self.redo_stack.is_empty()
61 }
62
63 pub fn undo_len(&self) -> usize {
64 self.undo_stack.len()
65 }
66
67 pub fn redo_len(&self) -> usize {
68 self.redo_stack.len()
69 }
70
71 pub fn undo_label(&self) -> Option<&str> {
72 self.undo_stack.back().map(|e| e.label.as_str())
73 }
74
75 pub fn redo_label(&self) -> Option<&str> {
76 self.redo_stack.last().map(|e| e.label.as_str())
77 }
78
79 pub fn in_group(&self) -> bool {
80 self.group_depth > 0
81 }
82
83 /// Clears all undo/redo entries and any active transaction group.
84 pub fn clear(&mut self) {
85 self.undo_stack.clear();
86 self.redo_stack.clear();
87 self.active_group = None;
88 self.group_depth = 0;
89 self.saved_undo_depth = None;
90 self.saved_revision = None;
91 }
92
93 /// Records the current state of `comp` as the clean saved point.
94 pub fn mark_saved(&mut self, comp: &Comp) {
95 // Edits after a save must never coalesce into the saved undo entry.
96 self.break_coalescing();
97 self.saved_undo_depth = Some(self.undo_stack.len());
98 self.saved_revision = Some(comp.revision);
99 }
100
101 pub fn saved_revision(&self) -> Option<u64> {
102 self.saved_revision
103 }
104
105 /// Returns `true` if `comp` has unsaved modifications relative to the last [`Self::mark_saved`].
106 pub fn is_dirty(&self, comp: &Comp) -> bool {
107 match self.saved_undo_depth {
108 Some(depth) if depth == self.undo_stack.len() => {
109 // If an edit was pushed via coalescing or outside history after mark_saved,
110 // check whether we're still at the saved depth without an active modified group.
111 if let Some((_, ref snap)) = self.active_group {
112 comp.revision != snap.revision
113 } else {
114 false
115 }
116 }
117 _ => self.saved_revision != Some(comp.revision),
118 }
119 }
120
121 /// Pushes a snapshot of `comp` BEFORE applying a discrete mutation.
122 /// No-op if currently inside a [`Self::begin_group`] transaction.
123 pub fn push_snapshot(&mut self, comp: &Comp, label: impl Into<String>) {
124 if self.group_depth > 0 {
125 return;
126 }
127 self.push_entry(HistoryEntry {
128 label: label.into(),
129 snapshot: comp.clone(),
130 coalesce_key: None,
131 });
132 }
133
134 /// Pushes a snapshot of `comp` BEFORE applying a continuous mutation (such as dragging a node
135 /// or scrubbing a parameter slider). Consecutive calls with the same `key` coalesce into a
136 /// single undo step preserving the initial pre-drag snapshot.
137 /// No-op if currently inside a [`Self::begin_group`] transaction.
138 pub fn push_coalesced(
139 &mut self,
140 comp: &Comp,
141 label: impl Into<String>,
142 key: impl Into<String>,
143 ) {
144 if self.group_depth > 0 {
145 return;
146 }
147 let key_str = key.into();
148 let label_str = label.into();
149 if self.redo_stack.is_empty() {
150 if let Some(top) = self.undo_stack.back_mut() {
151 if top.coalesce_key.as_deref() == Some(key_str.as_str()) {
152 top.label = label_str;
153 return;
154 }
155 }
156 }
157 self.push_entry(HistoryEntry {
158 label: label_str,
159 snapshot: comp.clone(),
160 coalesce_key: Some(key_str),
161 });
162 }
163
164 /// Breaks coalescing on the top undo entry so subsequent edits with the same key start a new
165 /// undo step (e.g. on pointer release).
166 pub fn break_coalescing(&mut self) {
167 if let Some(top) = self.undo_stack.back_mut() {
168 top.coalesce_key = None;
169 }
170 }
171
172 /// Begins a transaction group. All mutations until the matching [`Self::commit_group`] collapse
173 /// into a single undo step. Supports nesting.
174 pub fn begin_group(&mut self, comp: &Comp, label: impl Into<String>) {
175 if self.group_depth == 0 {
176 self.active_group = Some((label.into(), comp.clone()));
177 }
178 self.group_depth += 1;
179 }
180
181 /// Commits the current transaction group. When the outermost group closes, pushes one undo
182 /// entry if `comp.revision` changed since `begin_group`. Returns `true` if an entry was added.
183 pub fn commit_group(&mut self, comp: &Comp) -> bool {
184 if self.group_depth == 0 {
185 return false;
186 }
187 self.group_depth -= 1;
188 if self.group_depth > 0 {
189 return false;
190 }
191 let Some((label, snapshot)) = self.active_group.take() else {
192 return false;
193 };
194 if comp.revision == snapshot.revision {
195 return false;
196 }
197 self.push_entry(HistoryEntry {
198 label,
199 snapshot,
200 coalesce_key: None,
201 });
202 true
203 }
204
205 /// Cancels the active transaction group and restores `comp` to its pre-group state.
206 pub fn cancel_group(&mut self, comp: &mut Comp) -> bool {
207 if self.group_depth == 0 {
208 return false;
209 }
210 self.group_depth = 0;
211 let Some((_, snapshot)) = self.active_group.take() else {
212 return false;
213 };
214 let prev_rev = comp.revision;
215 restore_snapshot(comp, snapshot);
216 if comp.revision != prev_rev {
217 comp.revision = prev_rev.max(comp.revision) + 1;
218 }
219 true
220 }
221
222 /// Undoable [`Comp::paste_fusion_clipboard`]: the whole paste is one undo step, and a failed
223 /// paste leaves both `comp` and the history untouched.
224 pub fn paste_fusion_clipboard(
225 &mut self,
226 comp: &mut Comp,
227 lua_snippet: &str,
228 offset: (f32, f32),
229 ) -> Result<Vec<NodeId>, String> {
230 self.begin_group(comp, "Paste");
231 let pasted = comp.paste_fusion_clipboard(lua_snippet, offset);
232 self.commit_group(comp);
233 pasted
234 }
235
236 /// Undoes the most recent edit, restoring `comp` to the saved snapshot.
237 /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly.
238 pub fn undo(&mut self, comp: &mut Comp) -> bool {
239 if self.group_depth > 0 {
240 self.group_depth = 1;
241 self.commit_group(comp);
242 }
243 let Some(entry) = self.undo_stack.pop_back() else {
244 return false;
245 };
246 let prev_rev = comp.revision;
247 let redo_entry = HistoryEntry {
248 label: entry.label,
249 snapshot: comp.clone(),
250 coalesce_key: None,
251 };
252 self.redo_stack.push(redo_entry);
253 restore_snapshot(comp, entry.snapshot);
254 comp.revision = prev_rev.max(comp.revision) + 1;
255 true
256 }
257
258 /// Redoes the most recently undone edit.
259 /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly.
260 pub fn redo(&mut self, comp: &mut Comp) -> bool {
261 let Some(entry) = self.redo_stack.pop() else {
262 return false;
263 };
264 let prev_rev = comp.revision;
265 let undo_entry = HistoryEntry {
266 label: entry.label,
267 snapshot: comp.clone(),
268 coalesce_key: None,
269 };
270 self.undo_stack.push_back(undo_entry);
271 restore_snapshot(comp, entry.snapshot);
272 comp.revision = prev_rev.max(comp.revision) + 1;
273 true
274 }
275
276 fn push_entry(&mut self, entry: HistoryEntry) {
277 // Any saved state that lived in the redo branch is now unreachable.
278 if let Some(saved_depth) = self.saved_undo_depth {
279 if saved_depth > self.undo_stack.len() {
280 self.saved_undo_depth = None;
281 }
282 }
283 self.redo_stack.clear();
284 self.undo_stack.push_back(entry);
285 while self.undo_stack.len() > self.max_depth {
286 self.undo_stack.pop_front();
287 self.saved_undo_depth = self.saved_undo_depth.and_then(|d| d.checked_sub(1));
288 }
289 }
290}
291
292/// Replaces `comp` with `snapshot`, keeping the live file identity so a Save As followed by undo
293/// never points Save at the file the snapshot came from.
294fn restore_snapshot(comp: &mut Comp, mut snapshot: Comp) {
295 snapshot.path = comp.path.take();
296 snapshot.name = std::mem::take(&mut comp.name);
297 *comp = snapshot;
298}
299
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304 use crate::comp::ParamValue;
305 use crate::edit::tests::sample_comp;
306 use std::path::Path;
307
308 #[test]
309 fn comp_history_undo_redo_coalescing_groups_and_bounds() {
310 let mut comp = sample_comp();
311 let mut history = CompHistory::with_max_depth(3);
312 history.mark_saved(&comp);
313 assert!(!history.is_dirty(&comp));
314 assert!(!history.can_undo());
315 assert!(!history.can_redo());
316
317 let bg = comp.find_node("BG1").unwrap();
318
319 // 1. Coalesced drag: 120 frames produce ONE undo step
320 for i in 1..=120 {
321 history.push_coalesced(&comp, "Move BG1", format!("drag_node:{}", bg.0));
322 comp.set_node_pos(bg, [100.0 + i as f32, 50.0 + i as f32 * 0.5]);
323 }
324 history.break_coalescing();
325 assert_eq!(history.undo_len(), 1);
326 assert_eq!(history.undo_label(), Some("Move BG1"));
327 assert!(history.is_dirty(&comp));
328 assert_eq!(comp.node(bg).pos, [220.0, 110.0]);
329
330 // Undo restores original pre-drag position and clears dirty flag
331 assert!(history.undo(&mut comp));
332 assert_eq!(comp.node(bg).pos, [100.0, 50.0]);
333 assert!(!history.is_dirty(&comp));
334 assert!(history.can_redo());
335 assert_eq!(history.redo_label(), Some("Move BG1"));
336
337 // Redo restores final dragged position
338 assert!(history.redo(&mut comp));
339 assert_eq!(comp.node(bg).pos, [220.0, 110.0]);
340 assert!(history.is_dirty(&comp));
341
342 // 2. Redo invalidation on new edit after undo
343 assert!(history.undo(&mut comp));
344 assert!(history.can_redo());
345 history.push_snapshot(&comp, "Add Blur");
346 let blur = comp.add_node("Blur", None, [200.0, 100.0]);
347 assert!(!history.can_redo());
348 assert_eq!(history.undo_len(), 1);
349
350 // 3. Transaction group collapses multiple mutations into one undo step
351 history.begin_group(&comp, "Style Blur");
352 comp.set_input_value(blur, "XBlurSize", ParamValue::Number(5.0));
353 history.push_snapshot(&comp, "Ignored inside group");
354 comp.toggle_passthrough(blur);
355 assert!(history.commit_group(&comp));
356 assert_eq!(history.undo_len(), 2);
357 assert_eq!(history.undo_label(), Some("Style Blur"));
358
359 // No-op group doesn't push
360 history.begin_group(&comp, "No-op");
361 assert!(!history.commit_group(&comp));
362 assert_eq!(history.undo_len(), 2);
363
364 // Cancel group restores pre-group state
365 history.begin_group(&comp, "Canceled");
366 comp.set_node_pos(blur, [999.0, 999.0]);
367 assert!(history.cancel_group(&mut comp));
368 assert_eq!(comp.node(blur).pos, [200.0, 100.0]);
369
370 // 4. Bounded history depth (max_depth = 3)
371 history.push_snapshot(&comp, "Edit 3");
372 comp.set_node_pos(blur, [210.0, 100.0]);
373 history.push_snapshot(&comp, "Edit 4");
374 comp.set_node_pos(blur, [220.0, 100.0]);
375 assert_eq!(history.undo_len(), 3);
376
377 history.clear();
378 assert!(!history.can_undo());
379 assert!(!history.can_redo());
380 }
381
382 #[test]
383 fn mark_saved_stops_later_edits_coalescing_into_the_saved_step() {
384 let mut comp = sample_comp();
385 let mut history = CompHistory::new();
386 let bg = comp.find_node("BG1").unwrap();
387
388 history.push_coalesced(&comp, "Drag", "drag");
389 comp.set_node_pos(bg, [1.0, 1.0]);
390 history.mark_saved(&comp);
391 assert!(!history.is_dirty(&comp));
392
393 history.push_coalesced(&comp, "Drag", "drag");
394 comp.set_node_pos(bg, [2.0, 2.0]);
395 assert_eq!(history.undo_len(), 2);
396 assert!(history.is_dirty(&comp));
397 }
398
399 #[test]
400 fn undo_and_redo_keep_the_live_file_identity() {
401 let mut comp = sample_comp();
402 comp.path = Some("/tmp/original.comp".into());
403 comp.name = "original".to_owned();
404 let mut history = CompHistory::new();
405 let bg = comp.find_node("BG1").unwrap();
406
407 history.push_snapshot(&comp, "Move");
408 comp.set_node_pos(bg, [9.0, 9.0]);
409 comp.path = Some("/tmp/save_as.comp".into());
410 comp.name = "save_as".to_owned();
411
412 assert!(history.undo(&mut comp));
413 assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as"));
414 assert!(history.redo(&mut comp));
415 assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as"));
416 }
417}
crates/model/src/edit/keyframes.rs created+185
...@@ -0,0 +1,185 @@
1use super::remove_tools_recursive;
2use crate::comp::{Comp, InputBinding, NodeId, ParamValue, ensure_table_mut, param_value_to_lua};
3use crate::lua_value::{LuaKey, LuaValue};
4use crate::spline::{BezierSpline, Keyframe};
5use std::collections::HashSet;
6
7/// Keyframe times closer than this are the same keyframe (matches the Inspector's `keyframe_state`).
8const KEYFRAME_EPS: f64 = 1e-4;
9
10
11impl Comp {
12 pub fn set_keyframe(
13 &mut self,
14 node: NodeId,
15 input: &str,
16 frame: f64,
17 value: f64,
18 ) -> Result<String, String> {
19 if node.0 >= self.nodes.len() {
20 return Err(format!("invalid node id {}", node.0));
21 }
22 if !frame.is_finite() || !value.is_finite() {
23 return Err("keyframe frame and value must be finite numbers".to_owned());
24 }
25
26 let existing_spline = self.nodes[node.0]
27 .inputs
28 .get(input)
29 .and_then(|b| b.source_op.clone())
30 .filter(|op| self.splines.contains_key(op));
31
32 let spline_name = if let Some(sp_name) = existing_spline {
33 let sp = self.splines.get_mut(&sp_name).expect("spline exists");
34 upsert_keyframe(sp, frame, value);
35 sp_name
36 } else {
37 let hint = format!("{}{}", self.nodes[node.0].name, input);
38 let sp_name = self.generate_unique_name("BezierSpline", Some(&hint));
39 let color = default_spline_color(&sp_name);
40 let spline = BezierSpline {
41 name: sp_name.clone(),
42 color,
43 keyframes: vec![Keyframe::new(frame, value)],
44 };
45 self.splines.insert(sp_name.clone(), spline);
46
47 let n = &mut self.nodes[node.0];
48 let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding {
49 value: None,
50 source_op: None,
51 source_output: None,
52 expression: None,
53 });
54 entry.source_op = Some(sp_name.clone());
55 entry.source_output = Some("Value".to_owned());
56
57 let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None);
58 let port_tbl = ensure_table_mut(in_tbl, input, Some("Input"));
59 port_tbl.set(
60 LuaKey::Str("SourceOp".to_owned()),
61 LuaValue::String(sp_name.clone()),
62 );
63 port_tbl.set(
64 LuaKey::Str("Source".to_owned()),
65 LuaValue::String("Value".to_owned()),
66 );
67
68 sp_name
69 };
70
71 self.revision += 1;
72 Ok(spline_name)
73 }
74
75 /// Removes the keyframe at `frame` from `spline_name`. Returns `true` if a keyframe was deleted.
76 /// Deleting a spline's last keyframe removes the spline and leaves every input it drove with
77 /// that keyframe's value as a static `Value`.
78 pub fn delete_keyframe(&mut self, spline_name: &str, frame: f64) -> bool {
79 let Some(sp) = self.splines.get_mut(spline_name) else {
80 return false;
81 };
82 let Some(pos) = sp
83 .keyframes
84 .iter()
85 .position(|kf| (kf.time - frame).abs() < KEYFRAME_EPS)
86 else {
87 return false;
88 };
89 let removed = sp.keyframes.remove(pos);
90 if sp.keyframes.is_empty() {
91 self.splines.remove(spline_name);
92 let value = ParamValue::Number(removed.value);
93 for node in &mut self.nodes {
94 for (port, binding) in &mut node.inputs {
95 if binding.source_op.as_deref() != Some(spline_name) {
96 continue;
97 }
98 binding.source_op = None;
99 binding.source_output = None;
100 binding.value = Some(value.clone());
101 let port_tbl = ensure_table_mut(ensure_table_mut(&mut node.raw, "Inputs", None), port, Some("Input"));
102 port_tbl.remove(&LuaKey::Str("SourceOp".to_owned()));
103 port_tbl.remove(&LuaKey::Str("Source".to_owned()));
104 port_tbl.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&value));
105 }
106 }
107 if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) {
108 remove_tools_recursive(tools, &HashSet::from([spline_name.to_owned()]));
109 }
110 }
111 self.revision += 1;
112 true
113 }
114}
115
116fn upsert_keyframe(spline: &mut BezierSpline, frame: f64, value: f64) {
117 if let Some(existing) = spline
118 .keyframes
119 .iter_mut()
120 .find(|kf| (kf.time - frame).abs() < KEYFRAME_EPS)
121 {
122 // Handles are absolute coordinates, so they travel with the key.
123 let (dt, dv) = (frame - existing.time, value - existing.value);
124 existing.time = frame;
125 existing.value = value;
126 for handle in [&mut existing.lh, &mut existing.rh].into_iter().flatten() {
127 handle[0] += dt;
128 handle[1] += dv;
129 }
130 } else {
131 spline.keyframes.push(Keyframe::new(frame, value));
132 spline.sort();
133 }
134}
135
136fn default_spline_color(name: &str) -> [u8; 3] {
137 // Deterministic vivid Fusion-like spline palette based on name hash.
138 const PALETTE: &[[u8; 3]] = &[
139 [255, 128, 0],
140 [102, 204, 255],
141 [170, 238, 102],
142 [255, 102, 170],
143 [204, 153, 255],
144 [255, 221, 85],
145 ];
146 let hash = name
147 .bytes()
148 .fold(0usize, |acc, b| acc.wrapping_mul(31).wrapping_add(b as usize));
149 PALETTE[hash % PALETTE.len()]
150}
151
152
153#[cfg(test)]
154mod tests {
155 use super::*;
156 use crate::edit::tests::sample_comp;
157
158 #[test]
159 fn updating_a_keyframe_moves_its_handles_with_it() {
160 let mut comp = sample_comp();
161 let bc = comp.find_node("BC1").unwrap();
162 comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].lh = Some([20.0, 1.5]);
163 comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].rh = Some([40.0, 2.5]);
164 comp.set_keyframe(bc, "Gain", 30.0, 3.0).unwrap();
165 let kf = &comp.splines["BC1Gain"].keyframes[1];
166 assert_eq!((kf.value, kf.lh, kf.rh), (3.0, Some([20.0, 2.5]), Some([40.0, 3.5])));
167 }
168
169 #[test]
170 fn deleting_the_last_keyframe_keeps_its_value_as_a_static_input() {
171 let mut comp = sample_comp();
172 let bc = comp.find_node("BC1").unwrap();
173 // Within the shared 1e-4 tolerance.
174 assert!(comp.delete_keyframe("BC1Gain", 0.00005));
175 assert!(comp.delete_keyframe("BC1Gain", 30.0));
176 assert!(!comp.splines.contains_key("BC1Gain"));
177 assert_eq!(comp.node(bc).connected_node("Gain"), None);
178 assert_eq!(comp.node(bc).static_number("Gain"), Some(2.0));
179
180 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
181 let r = saved.node(saved.find_node("BC1").unwrap());
182 assert_eq!(r.static_number("Gain"), Some(2.0));
183 assert!(!saved.to_fusion_string().contains("BC1Gain"));
184 }
185}
crates/model/src/edit/tests.rs created+359
...@@ -0,0 +1,359 @@
1use super::*;
2use crate::expr::ExprEngine;
3use std::path::Path;
4
5 pub(super) fn sample_comp() -> Comp {
6 let src = r#"Composition {
7 CurrentTime = 10,
8 RenderRange = { 0, 100 },
9 GlobalRange = { 0, 100 },
10 Prefs = {
11 Comp = {
12 FrameFormat = {
13 Width = 1920,
14 Height = 1080,
15 Rate = 24,
16 DepthFull = 3,
17 },
18 },
19 },
20 Tools = ordered() {
21 BG1 = Background {
22 Inputs = {
23 Width = Input { Value = 1920, },
24 Height = Input { Value = 1080, },
25 TopLeftRed = Input { Value = 0.25, },
26 },
27 ViewInfo = OperatorInfo { Pos = { 100, 50 } },
28 },
29 BC1 = BrightnessContrast {
30 Inputs = {
31 Input = Input {
32 SourceOp = "BG1",
33 Source = "Output",
34 },
35 Gain = Input {
36 SourceOp = "BC1Gain",
37 Source = "Value",
38 },
39 },
40 ViewInfo = OperatorInfo { Pos = { 300, 50 } },
41 },
42 BC1Gain = BezierSpline {
43 SplineColor = { Red = 255, Green = 128, Blue = 0 },
44 KeyFrames = {
45 [0] = { 1, Flags = { Linear = true } },
46 [30] = { 2, Flags = { Linear = true } },
47 },
48 },
49 SurfaceTracker1 = SurfaceTracker {
50 Inputs = {
51 Source = Input {
52 SourceOp = "BC1",
53 Source = "Output",
54 },
55 MeshBlob = Input {
56 Value = TrackingMesh {
57 Vertices = { 1, 2, 3 },
58 },
59 },
60 },
61 ViewInfo = OperatorInfo { Pos = { 500, 50 } },
62 },
63 },
64}"#;
65 Comp::from_fusion_str(src).expect("parse sample comp")
66 }
67
68 #[test]
69 fn add_node_naming_and_tool_defaults() {
70 let mut comp = sample_comp();
71 let rev0 = comp.revision;
72
73 let t1 = comp.add_node("Transform", None, [120.0, 200.0]);
74 let t2 = comp.add_node("Transform", None, [240.0, 200.0]);
75 assert_eq!(comp.node(t1).name, "Transform1");
76 assert_eq!(comp.node(t2).name, "Transform2");
77 assert_eq!(comp.node(t1).pos, [120.0, 200.0]);
78 assert!(comp.revision >= rev0 + 2);
79
80 let h0 = comp.add_node("Background", Some("HeroBG"), [0.0, 0.0]);
81 let h1 = comp.add_node("Background", Some("HeroBG"), [50.0, 0.0]);
82 let h2 = comp.add_node("Background", Some("HeroBG"), [100.0, 0.0]);
83 assert_eq!(comp.node(h0).name, "HeroBG");
84 assert_eq!(comp.node(h1).name, "HeroBG_1");
85 assert_eq!(comp.node(h2).name, "HeroBG_2");
86
87 // Cover all common Fusion 21.1 tool categories + generic fallback
88 let kinds = [
89 "Background",
90 "Merge",
91 "Transform",
92 "Blur",
93 "Glow",
94 "SoftGlow",
95 "BrightnessContrast",
96 "ColorCorrector",
97 "ColorGain",
98 "RectangleMask",
99 "EllipseMask",
100 "PolylineMask",
101 "BitmapMask",
102 "TextPlus",
103 "Loader",
104 "Saver",
105 "Displace",
106 "FastNoise",
107 "PipeRouter",
108 "Switch",
109 "TimeStretcher",
110 "TimeSpeed",
111 "Renderer3D",
112 "Camera3D",
113 "Merge3D",
114 "Transform3D",
115 "ImagePlane3D",
116 "Shape3D",
117 "Note",
118 "Underlay",
119 "MyCustomThirdPartyTool",
120 ];
121 for (i, kind) in kinds.iter().enumerate() {
122 let id = comp.add_node(kind, None, [i as f32 * 50.0, 400.0]);
123 assert_eq!(comp.node(id).kind, *kind);
124 assert!(comp.node(id).raw.get_table("ViewInfo").is_some());
125 }
126
127 // Roundtrip all newly created nodes cleanly
128 let s = comp.to_fusion_string();
129 let reloaded = Comp::from_fusion_str(&s).expect("roundtrip added nodes");
130 assert_eq!(reloaded.nodes.len(), comp.nodes.len());
131 assert_eq!(
132 reloaded.node(reloaded.find_node("HeroBG").unwrap()).static_number("Width"),
133 Some(1920.0)
134 );
135 }
136
137 #[test]
138 fn connect_cycle_detection_disconnect_and_splice() {
139 let mut comp = sample_comp();
140 let bg = comp.find_node("BG1").unwrap();
141 let bc = comp.find_node("BC1").unwrap();
142 let st = comp.find_node("SurfaceTracker1").unwrap();
143
144 // Self-loop rejected
145 assert!(comp.connect_output(bg, "Output", bg, "EffectMask").is_err());
146 // Direct cycle BG1 -> BC1 -> BG1 rejected
147 assert!(comp.connect_output(bc, "Output", bg, "EffectMask").is_err());
148 // Transitive cycle BG1 -> BC1 -> SurfaceTracker1 -> BG1 rejected
149 assert!(comp.connect_output(st, "Output", bg, "EffectMask").is_err());
150
151 // Splice a Blur into BG1 -> BC1.Input
152 let blur = comp.add_node("Blur", None, [200.0, 50.0]);
153 comp.splice_node_into_pipe(blur, bg, bc, "Input")
154 .expect("splice blur");
155 assert_eq!(comp.node(blur).connected_node("Input"), Some("BG1"));
156 assert_eq!(comp.node(bc).connected_node("Input"), Some("Blur1"));
157
158 // Disconnect returns true once, then false
159 assert!(comp.disconnect(bc, "Input"));
160 assert!(!comp.disconnect(bc, "Input"));
161 assert_eq!(comp.node(bc).connected_node("Input"), None);
162
163 // Reconnect and verify roundtrip
164 comp.connect_output(blur, "Output", bc, "Input")
165 .expect("reconnect");
166 let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip");
167 assert_eq!(
168 reloaded.node(reloaded.find_node("BC1").unwrap()).connected_node("Input"),
169 Some("Blur1")
170 );
171 }
172
173 #[test]
174 fn params_expressions_passthrough_pos_and_keyframes() {
175 let mut comp = sample_comp();
176 let bc = comp.find_node("BC1").unwrap();
177
178 assert!(comp.set_input_value(bc, "Gamma", ParamValue::Number(1.45)));
179 assert!(comp.set_input_expression(bc, "Brightness", Some("time * 0.01".to_owned())));
180 assert!(comp.toggle_passthrough(bc));
181 comp.set_node_pos(bc, [333.0, 77.0]);
182
183 // Set keyframe on static input -> creates new BezierSpline and wires it
184 let sp_name = comp.set_keyframe(bc, "Contrast", 0.0, 0.2).expect("kf 0");
185 assert_eq!(sp_name, "BC1Contrast");
186 let sp_name2 = comp.set_keyframe(bc, "Contrast", 20.0, 0.8).expect("kf 20");
187 assert_eq!(sp_name2, sp_name);
188 // Update existing keyframe at frame 20
189 comp.set_keyframe(bc, "Contrast", 20.0, 0.9).expect("update kf 20");
190 assert_eq!(comp.splines[&sp_name].keyframes.len(), 2);
191
192 // Evaluate via Comp::eval_number
193 let expr = ExprEngine::new();
194 let val_mid = comp.eval_number(comp.node(bc), "Contrast", 10.0, 0.0, &expr);
195 assert!((val_mid - 0.55).abs() < 1e-5, "got {val_mid}");
196
197 // Delete keyframe
198 assert!(comp.delete_keyframe(&sp_name, 20.0));
199 assert!(!comp.delete_keyframe(&sp_name, 20.0));
200 assert_eq!(comp.splines[&sp_name].keyframes.len(), 1);
201
202 // Roundtrip
203 let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip");
204 let r_bc = reloaded.node(reloaded.find_node("BC1").unwrap());
205 assert!(r_bc.bypassed);
206 assert_eq!(r_bc.pos, [333.0, 77.0]);
207 assert_eq!(r_bc.static_number("Gamma"), Some(1.45));
208 assert_eq!(
209 r_bc.inputs.get("Brightness").and_then(|b| b.expression.as_deref()),
210 Some("time * 0.01")
211 );
212 assert_eq!(r_bc.connected_node("Contrast"), Some("BC1Contrast"));
213 assert_eq!(reloaded.splines["BC1Contrast"].keyframes.len(), 1);
214
215 // Clear expression and un-bypass
216 assert!(comp.set_input_expression(bc, "Brightness", None));
217 assert!(!comp.toggle_passthrough(bc));
218 let reloaded2 = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip 2");
219 let r_bc2 = reloaded2.node(reloaded2.find_node("BC1").unwrap());
220 assert!(!r_bc2.bypassed);
221 assert_eq!(
222 r_bc2.inputs.get("Brightness").and_then(|b| b.expression.as_deref()),
223 None
224 );
225 }
226
227 #[test]
228 fn rename_duplicate_and_delete_nodes_roundtrip() {
229 let mut comp = sample_comp();
230 let bg = comp.find_node("BG1").unwrap();
231 let bc = comp.find_node("BC1").unwrap();
232
233 // Rename validation
234 assert!(comp.rename_node(bg, "").is_err());
235 assert!(comp.rename_node(bg, "123Bad").is_err());
236 assert!(comp.rename_node(bg, "function").is_err());
237 assert!(comp.rename_node(bg, "BC1").is_err());
238
239 // Rename BG1 -> PlateBG and verify BC1.Input SourceOp is rewritten
240 let new_name = comp.rename_node(bg, "PlateBG").expect("rename BG1");
241 assert_eq!(new_name, "PlateBG");
242 assert!(comp.find_node("BG1").is_none());
243 assert_eq!(comp.find_node("PlateBG"), Some(bg));
244 assert_eq!(comp.node(bc).connected_node("Input"), Some("PlateBG"));
245
246 // Duplicate [PlateBG, BC1] together -> internal wire preserved, BC1Gain spline cloned
247 let dups = comp.duplicate_nodes(&[bg, bc], [0.0, 150.0]);
248 assert_eq!(dups.len(), 2);
249 let dup_bg = dups[0];
250 let dup_bc = dups[1];
251 assert_eq!(comp.node(dup_bg).name, "PlateBG_1");
252 assert_eq!(comp.node(dup_bc).name, "BC1_1");
253 assert_eq!(comp.node(dup_bg).pos, [100.0, 200.0]);
254 assert_eq!(comp.node(dup_bc).connected_node("Input"), Some("PlateBG_1"));
255 let dup_gain_spline = comp.node(dup_bc).connected_node("Gain").unwrap().to_owned();
256 assert_ne!(dup_gain_spline, "BC1Gain");
257 assert!(comp.splines.contains_key(&dup_gain_spline));
258
259 // Share BC1Gain with dup_bg (artificial) vs exclusive spline on dup_bc:
260 // Deleting dup_bc should prune `dup_gain_spline` while leaving `BC1Gain` intact.
261 let deleted = comp.delete_nodes(&[dup_bc]);
262 assert_eq!(deleted, vec!["BC1_1".to_owned()]);
263 assert!(!comp.splines.contains_key(&dup_gain_spline));
264 assert!(comp.splines.contains_key("BC1Gain"));
265
266 // Delete BC1 -> SurfaceTracker1.Source unwired, BC1Gain pruned, NodeId indices compact
267 let bc_now = comp.find_node("BC1").unwrap();
268 let del2 = comp.delete_nodes(&[bc_now]);
269 assert_eq!(del2, vec!["BC1".to_owned()]);
270 assert!(!comp.splines.contains_key("BC1Gain"));
271 for (idx, n) in comp.nodes.iter().enumerate() {
272 assert_eq!(n.id, NodeId(idx));
273 assert_eq!(comp.find_node(&n.name), Some(NodeId(idx)));
274 }
275 let st_now = comp.find_node("SurfaceTracker1").unwrap();
276 assert_eq!(comp.node(st_now).connected_node("Source"), None);
277
278 // Full roundtrip preserves unknown SurfaceTracker1 verbatim + all structural mutations
279 let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("roundtrip");
280 assert!(reloaded.find_node("PlateBG").is_some());
281 assert!(reloaded.find_node("PlateBG_1").is_some());
282 assert!(reloaded.find_node("BC1").is_none());
283 assert!(reloaded.find_node("SurfaceTracker1").is_some());
284 assert!(!reloaded.splines.contains_key("BC1Gain"));
285 let r_st = reloaded.node(reloaded.find_node("SurfaceTracker1").unwrap());
286 assert_eq!(r_st.connected_node("Source"), None);
287 assert!(
288 r_st.raw
289 .get_table("Inputs")
290 .and_then(|i| i.get_table("MeshBlob"))
291 .is_some()
292 );
293 }
294
295 #[test]
296 fn roundtrip_mutations_on_real_20_falling_comp() {
297 let path = Path::new("/Volumes/Project/trees/fusion/20_falling.comp");
298 if !path.exists() {
299 return;
300 }
301 let mut comp = Comp::from_fusion_file(path).expect("load 20_falling.comp");
302 let orig_count = comp.nodes.len();
303
304 let blur = comp.add_node("Blur", Some("TestGlowBlur"), [1000.0, -500.0]);
305 let merge19 = comp.find_node("Merge19").expect("Merge19");
306 comp.set_input_value(blur, "XBlurSize", ParamValue::Number(4.5));
307 comp.set_input_expression(blur, "YBlurSize", Some("XBlurSize * 2".to_owned()));
308 comp.toggle_passthrough(blur);
309 let sp = comp
310 .set_keyframe(blur, "Blend", 2200.0, 0.5)
311 .expect("keyframe blend");
312 comp.set_keyframe(blur, "Blend", 2250.0, 1.0)
313 .expect("keyframe blend 2");
314 comp.connect_output(merge19, "Output", blur, "Input")
315 .expect("connect Merge19 -> blur");
316 comp.rename_node(blur, "TestGlowBlurRenamed")
317 .expect("rename blur");
318
319 let serialized = comp.to_fusion_string();
320 let reloaded = Comp::from_fusion_str(&serialized).expect("re-parse mutated 20_falling");
321 assert_eq!(reloaded.nodes.len(), orig_count + 1);
322 let r_blur_id = reloaded
323 .find_node("TestGlowBlurRenamed")
324 .expect("TestGlowBlurRenamed");
325 let r_blur = reloaded.node(r_blur_id);
326 assert!(r_blur.bypassed);
327 assert_eq!(r_blur.connected_node("Input"), Some("Merge19"));
328 assert_eq!(r_blur.static_number("XBlurSize"), Some(4.5));
329 assert_eq!(
330 r_blur.inputs.get("YBlurSize").and_then(|b| b.expression.as_deref()),
331 Some("XBlurSize * 2")
332 );
333 assert_eq!(reloaded.splines[&sp].keyframes.len(), 2);
334 }
335
336 pub(super) const GROUP_SNIPPET: &str = r#"{
337 Tools = ordered() {
338 Group1 = GroupOperator {
339 Inputs = {
340 Input1 = InstanceInput { SourceOp = "Inner1", Source = "Input", },
341 },
342 Outputs = {
343 Output1 = InstanceOutput { SourceOp = "Inner1", Source = "Output", },
344 },
345 ViewInfo = GroupInfo { Pos = { 10, 20 } },
346 Tools = ordered() {
347 Inner1 = Blur {
348 Inputs = {
349 XBlurSize = Input { SourceOp = "Inner1Size", Source = "Value", },
350 },
351 ViewInfo = OperatorInfo { Pos = { 0, 0 } },
352 },
353 Inner1Size = BezierSpline {
354 KeyFrames = { [0] = { 1, Flags = { Linear = true } } },
355 },
356 },
357 },
358 },
359}"#;