1//! Core composition IR, Fusion `.comp` importer, parameter evaluation, and graph editing.
2
3mod eval;
4mod load;
5mod math;
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};
17use std::path::{Path, PathBuf};
18use std::sync::atomic::AtomicU64;
19
20/// Fusion working color bit depth (`DepthFull` / `ChangeDepth.Depth` / generator `Depth`).
21/// Fusion enum: `0 = Default`, `1 = int8`, `2 = int16`, `3 = float16`, `4 = float32`.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
23pub enum BitDepth {
24 #[default]
25 Int8 = 1,
26 Int16 = 2,
27 Float16 = 3,
28 Float32 = 4,
29}
30
31impl BitDepth {
32 pub fn from_fusion_depth(v: i32) -> Option<Self> {
33 match v {
34 1 => Some(Self::Int8),
35 2 => Some(Self::Int16),
36 3 => Some(Self::Float16),
37 4 => Some(Self::Float32),
38 _ => None,
39 }
40 }
41
42 pub fn is_float(self) -> bool {
43 matches!(self, Self::Float16 | Self::Float32)
44 }
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub struct NodeId(pub usize);
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
51pub enum PortRole {
52 Background, // Gold / yellow (Fusion main input)
53 Foreground, // Green
54 Mask, // Blue (EffectMask)
55 Aux, // Purple / grey
56 Scene3D, // Cyan
57}
58
59impl PortRole {
60 pub fn from_input_name(name: &str) -> Self {
61 if name.starts_with("SceneInput") {
62 return Self::Scene3D;
63 }
64 match name {
65 "EffectMask" | "GarbageMatte" | "SolidMatte" | "Mask" | "TrackingMask" | "RegionMask" => {
66 Self::Mask
67 }
68 "Foreground" | "Image2" | "Overlay" | "ReplaceImage" => Self::Foreground,
69 "Background" | "Input" | "Image" | "Image1" | "Source" | "MainInput1" => {
70 Self::Background
71 }
72 _ => Self::Aux,
73 }
74 }
75}
76
77/// Canonical registry of Fusion tool classes evaluated natively by the engine.
78pub fn is_supported_tool(kind: &str) -> bool {
79 matches!(
80 kind,
81 // Routing / Utility
82 "Saver"
83 | "PipeRouter"
84 | "Fuse.Wireless"
85 | "Tracker"
86 | "SurfaceTracker"
87 | "Dimension.PlanarTracker"
88 | "PlanarTracker"
89 | "Dimension.PlanarTransform"
90 | "PlanarTransform"
91 | "MacroOperator"
92 | "GroupOperator"
93 | "TimeStretcher"
94 | "TimeSpeed"
95 | "Trails"
96 | "Switch"
97 | "Fuse.Switch"
98 | "Fuse.SwitchElse"
99 | "Note"
100 | "Underlay"
101 | "StickyNote"
102 // 2D tools
103 | "Loader"
104 | "Background"
105 | "Merge"
106 | "MultiMerge"
107 | "Fuse.MultiMerge"
108 | "Dissolve"
109 | "Fuse.Wipe"
110 | "Transform"
111 | "CameraShake"
112 | "CornerPositioner"
113 | "PerspectivePositioner"
114 | "DVE"
115 | "Shadow"
116 | "Scale"
117 | "BetterResize"
118 | "Crop"
119 | "Letterbox"
120 | "SetDomain"
121 | "ChangeDepth"
122 | "BrightnessContrast"
123 | "ColorCorrector"
124 | "ColorGain"
125 | "ColorCurves"
126 | "HueCurves"
127 | "GamutConvert"
128 | "AcesTransform"
129 | "ColorSpace"
130 | "ColorMatrix"
131 | "WhiteBalance"
132 | "AutoGain"
133 | "ColorBalance"
134 | "SoftClip"
135 | "InvertColor"
136 | "AlphaMultiply"
137 | "AlphaDivide"
138 | "PseudoColor"
139 | "ChannelBoolean"
140 | "LumaKeyer"
141 | "UltraKeyer"
142 | "DeltaKeyer"
143 | "DifferenceKeyer"
144 | "ChromaKeyer"
145 | "CleanPLate"
146 | "CleanPlate"
147 | "MatteControl"
148 | "Blur"
149 | "Defocus"
150 | "DepthBlur"
151 | "Fog"
152 | "Highlight"
153 | "HotSpot"
154 | "RankFilter"
155 | "Sharpen"
156 | "UnsharpMask"
157 | "Filter"
158 | "RemoveNoise"
159 | "VectorDenoise"
160 | "VariBlur"
161 | "DirectionalBlur"
162 | "VectorMotionBlur"
163 | "Glow"
164 | "SoftGlow"
165 | "Fuse.XGlow"
166 | "ErodeDilate"
167 | "FastNoise"
168 | "Plasma"
169 | "DaySky"
170 | "Mandel"
171 | "FilmGrain"
172 | "Grain"
173 | "Displace"
174 | "Vortex"
175 | "Drip"
176 | "Dent"
177 | "GridWarp"
178 | "CoordSpace"
179 | "LensDistort"
180 | "Fuse.Duplicate"
181 | "Fuse.KScope"
182 | "Fuse.AlphaWeightedNoise"
183 | "Fuse.CheckerPieceGenerator"
184 | "Fuse.Crystallize"
185 | "Fuse.HexagonTiles"
186 | "Fuse.Hexagon"
187 | "Fuse.Lightning"
188 | "Fuse.VORONOI_DIAGRAM"
189 // 2D vector shape pipeline
190 | "sRender"
191 | "sNGon"
192 | "sStar"
193 | "sRectangle"
194 | "sEllipse"
195 | "sPolygon"
196 | "sGrid"
197 | "sMerge"
198 | "sTransform"
199 | "sDuplicate"
200 | "sJitter"
201 | "sExpand"
202 | "sOffset"
203 | "sBoolean"
204 | "sOutline"
205 | "sBSpline"
206 | "sChangeStyle"
207 | "sText"
208 | "EllipseMask"
209 | "RectangleMask"
210 | "TriangleMask"
211 | "PolylineMask"
212 | "BSplineMask"
213 | "MultiPoly"
214 | "RangesMask"
215 | "TeapotMask"
216 | "BitmapMask"
217 | "WandMask"
218 | "MagicMask"
219 | "AutoMatte"
220 // Warp / Filter / Film / Effect / ColorFX / LUT / Resolve IO
221 | "Distort"
222 | "CreateBumpMap"
223 | "CreateReliefMap"
224 | "CustomFilter"
225 | "CineonLog"
226 | "LightTrim"
227 | "TV"
228 | "AutoDomain"
229 | "Fuse.FrameAverage"
230 | "CustomColorMatrix"
231 | "SetCanvasColor"
232 | "ChromaticAdaptation"
233 | "ColorSpaceTransform"
234 | "GamutLimiter"
235 | "GamutMapping"
236 | "FilmLookCreator"
237 | "OCIOCDLTransform"
238 | "FileLUT"
239 | "Fuse.LUTCubeCreator"
240 | "Fuse.LUTCubeApply"
241 | "Fuse.LUTCubeAnalyzer"
242 | "LUTCubeCreator"
243 | "LUTCubeApply"
244 | "LUTCubeAnalyzer"
245 | "MediaIn"
246 | "MediaOut"
247 // Position, Deep Pixel & Optical Flow
248 | "VolumeFog"
249 | "VolumeMask"
250 | "ZtoWorldPos"
251 | "SSAO"
252 | "Shader"
253 | "Texture"
254 | "Dimension.RepairFrame"
255 | "RepairFrame"
256 | "Dimension.SmoothMotion"
257 | "SmoothMotion"
258 | "Dimension.Tween"
259 | "Tween"
260 | "PropagateDepth"
261 | "Dimension.PropagateDepth"
262 | "VectorTransform"
263 | "VectorWarp"
264 // OCIO, Layer, Metadata, MultiText & Utility
265 | "OCIOColorSpace"
266 | "OCIODisplay"
267 | "OCIOFileTransform"
268 | "LayerMuxer"
269 | "LayerRegex"
270 | "LayerRemover"
271 | "Swizzler"
272 | "Fuse.FLS_CopyMetadata"
273 | "Fuse.SetMetaDataTC"
274 | "MultiText"
275 | "Fields"
276 | "KeyStretcher"
277 | "ChromaticAberrationRemoval"
278 | "Dummy"
279 | "Paint"
280 | "PaintMask"
281 | "PolylineStroke"
282 | "Multistroke"
283 | "TextPlus"
284 | "Fuse.Colorize"
285 | "Fuse.Outline"
286 | "Fuse.XfChroma"
287 | "Fuse.Cryptomatte"
288 | "Cryptomatte"
289 | "Fuse.Null"
290 | "Fuse.SetMetaData"
291 | "Fuse.Linger"
292 | "Fuse.OCLRays"
293 | "Dimension.OpticalFlow"
294 | "Dimension.CopyAux"
295 | "OpticalFlow"
296 | "Custom"
297 // Modifiers
298 | "Expression"
299 // Particle system
300 | "pRender"
301 | "pEmitter"
302 | "pPointForce"
303 | "pDirectionalForce"
304 | "pTurbulence"
305 | "pDrag"
306 | "pFriction"
307 | "pKill"
308 | "pMerge"
309 | "pBounce"
310 | "pVortex"
311 | "pFlock"
312 | "pSpawn"
313 | "pChangeStyle"
314 | "pGradientForce"
315 | "pAvoid"
316 | "pCustom"
317 | "pCustomForce"
318 | "pFollow"
319 | "pImageEmitter"
320 | "pTangentForce"
321 // 3D tools
322 | "Renderer3D"
323 | "Merge3D"
324 | "Transform3D"
325 | "Camera3D"
326 | "ImagePlane3D"
327 | "Shape3D"
328 | "Cube3D"
329 | "SurfaceFBXMesh"
330 | "Text3D"
331 | "LightAmbient"
332 | "LightDirectional"
333 | "LightPoint"
334 | "LightSpot"
335 | "MtlBlinn"
336 | "MtlCookTorrance"
337 | "MtlPhong"
338 | "MtlWard"
339 | "MtlReflect"
340 | "MtlChanBool"
341 | "SphereMap"
342 | "Texture2DOperator"
343 | "TextureTransformOperator"
344 | "BumpMap"
345 | "ReplaceMaterial3D"
346 | "Override3D"
347 | "Duplicate3D"
348 | "Replicate3D"
349 | "Bender3D"
350 | "ReplaceNormals3D"
351 | "Displace3D"
352 | "LightDome"
353 | "MtlMerge3D"
354 | "MtlPBRUber"
355 | "MtlStereoMix3D"
356 | "CubeMap"
357 | "FalloffOperator"
358 | "FastNoiseTexture3D"
359 | "TexCatcher"
360 | "TexGradient"
361 | "Fog3D"
362 | "Locator3D"
363 | "Ribbon3D"
364 | "Triangulate3D"
365 | "Weld3D"
366 | "UVMap"
367 )
368}
369
370/// Metadata extracted from a Fusion `Saver` node.
371#[derive(Clone, Debug, PartialEq)]
372pub struct SaverSpec {
373 pub node_id: NodeId,
374 pub name: String,
375 pub upstream: Option<NodeId>,
376 pub filename: String,
377 pub range: [i64; 2],
378 pub sequence_start: Option<i64>,
379}
380
381impl SaverSpec {
382 /// Computes the output path for `frame` following Fusion's Saver sequence naming rules:
383 /// - `foo_0000.png` -> `foo_{frame:04}.png` (preserving digit width)
384 /// - `0000.png` -> `{frame:04}.png`
385 /// - `render.png` -> `render{frame:04}.png` (4-digit default when no trailing digits exist)
386 pub fn frame_path(&self, frame: i64) -> PathBuf {
387 let effective_frame = if let Some(start) = self.sequence_start {
388 start.saturating_add(frame.saturating_sub(self.range[0]))
389 } else {
390 frame
391 };
392
393 let path = Path::new(&self.filename);
394 let parent = path.parent().unwrap_or_else(|| Path::new(""));
395 let fname = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
396
397 let (stem, ext) = match fname.rfind('.') {
398 Some(dot) => (&fname[..dot], &fname[dot..]),
399 None => (fname, ""),
400 };
401
402 let prefix = stem.trim_end_matches(|c: char| c.is_ascii_digit());
403 let digits = &stem[prefix.len()..];
404 let width = if digits.is_empty() { 4 } else { digits.len() };
405
406 let formatted_num = if effective_frame < 0 {
407 format!("-{:0width$}", effective_frame.unsigned_abs())
408 } else {
409 format!("{effective_frame:0width$}")
410 };
411
412 let out_name = format!("{prefix}{formatted_num}{ext}");
413 if parent.as_os_str().is_empty() {
414 PathBuf::from(out_name)
415 } else {
416 parent.join(out_name)
417 }
418 }
419}
420
421#[derive(Clone, Debug, PartialEq)]
422pub enum ParamValue {
423 Number(f64),
424 Point([f64; 2]),
425 Text(String),
426 FuId(String),
427 Gradient(Gradient),
428 Raw(LuaValue),
429}
430
431impl ParamValue {
432 pub fn as_f64(&self) -> Option<f64> {
433 match self {
434 ParamValue::Number(n) => Some(*n),
435 _ => None,
436 }
437 }
438
439 pub fn as_point(&self) -> Option<[f64; 2]> {
440 match self {
441 ParamValue::Point(p) => Some(*p),
442 _ => None,
443 }
444 }
445
446 pub fn as_str(&self) -> Option<&str> {
447 match self {
448 ParamValue::Text(s) | ParamValue::FuId(s) => Some(s.as_str()),
449 _ => None,
450 }
451 }
452}
453
454#[derive(Clone, Debug, PartialEq)]
455pub struct InputBinding {
456 pub value: Option<ParamValue>,
457 pub source_op: Option<String>,
458 pub source_output: Option<String>,
459 pub expression: Option<String>,
460}
461
462#[derive(Clone, Debug, PartialEq)]
463pub struct ClipSpec {
464 pub filename: String,
465 pub alternate_filename: Option<String>,
466 pub start_frame: i64,
467 pub length: Option<i64>,
468 pub trim_in: i64,
469 pub trim_out: i64,
470 pub global_start: i64,
471 pub global_end: i64,
472 pub extend_first: i64,
473 pub extend_last: i64,
474 pub loop_clip: bool,
475 pub reverse: bool,
476}
477
478#[derive(Clone, Debug, PartialEq)]
479pub struct Node {
480 pub id: NodeId,
481 pub name: String,
482 /// Original Fusion operator class name (e.g. `"Merge"`, `"Fuse.Colorize"`, `"TextPlus"`).
483 pub kind: String,
484 /// Position in Flow coordinates (Fusion `ViewInfo.Pos`).
485 pub pos: [f32; 2],
486 pub bypassed: bool,
487 /// True for internal tools unpacked from a MacroOperator/GroupOperator (hidden from top-level Flow).
488 pub internal: bool,
489 /// For MacroOperator / GroupOperator nodes, the internal tool that produces this macro's output.
490 pub macro_output: Option<NodeId>,
491 pub inputs: HashMap<String, InputBinding>,
492 /// Ordered list of image/mask connection ports (`(input_name, source_node_name, source_port)`).
493 pub clips: Vec<ClipSpec>,
494 /// Preserved raw Lua table for lossless roundtrip / debugging.
495 pub raw: LuaTable,
496}
497
498impl Node {
499 /// Returns all image/mask connections targeting another flow node.
500 pub fn image_connections(&self, node_names: &HashSet<String>) -> Vec<(String, String, PortRole)> {
501 let mut out = Vec::new();
502 for (port, binding) in &self.inputs {
503 if let Some(src) = &binding.source_op {
504 if node_names.contains(src) {
505 let role = PortRole::from_input_name(port);
506 out.push((port.clone(), src.clone(), role));
507 }
508 }
509 }
510 out.sort_by(|a, b| a.0.cmp(&b.0));
511 out
512 }
513
514 /// Returns static number value if present.
515 pub fn static_number(&self, name: &str) -> Option<f64> {
516 self.inputs.get(name)?.value.as_ref()?.as_f64()
517 }
518
519 pub fn static_str(&self, name: &str) -> Option<&str> {
520 self.inputs.get(name)?.value.as_ref()?.as_str()
521 }
522
523 pub fn static_point(&self, name: &str) -> Option<[f64; 2]> {
524 self.inputs.get(name)?.value.as_ref()?.as_point()
525 }
526
527 pub fn connected_node(&self, port: &str) -> Option<&str> {
528 self.inputs.get(port)?.source_op.as_deref()
529 }
530}
531
532/// Per-character styling entry from Fusion's `StyledTextCLS` (`CharacterLevelStyling`).
533/// Common Fusion property IDs: `100` = Font family, `102` = Size, `109` = Font style,
534/// `1330` = Character shear X, `1350` = Character X offset, `1351` = Character Y offset.
535#[derive(Clone, Debug, PartialEq)]
536pub struct ClsEntry {
537 pub prop_id: u32,
538 pub start: usize,
539 pub end: usize,
540 pub value: f32,
541 pub text: String,
542}
543
544/// Fusion `Shake` procedural modifier (`Source = "X"` / `"Y"` / `"Value"` / `"Position"`).
545#[derive(Clone, Debug, PartialEq)]
546pub struct ShakeModifier {
547 pub inputs: HashMap<String, InputBinding>,
548}
549
550/// Fusion standalone `Expression` modifier (`NumberExpression`, `PointExpressionX`,
551/// `PointExpressionY`, `PointExpression`, `n1..n9` / `NumberIn1..9`, `p1..p9` / `PointIn1..9`).
552#[derive(Clone, Debug, PartialEq)]
553pub struct ExpressionModifier {
554 pub inputs: HashMap<String, InputBinding>,
555}
556
557#[derive(Clone, Debug)]
558pub struct Comp {
559 pub path: Option<PathBuf>,
560 pub name: String,
561 pub width: u32,
562 pub height: u32,
563 pub fps: f64,
564 /// Project default HiQ working bit depth from `Prefs.Comp.FrameFormat.DepthFull`.
565 pub depth_full: BitDepth,
566 pub current_time: f64,
567 pub global_range: [i64; 2],
568 pub render_range: [i64; 2],
569 pub audio_filename: Option<String>,
570 pub audio_offset: f64,
571 /// Flow operators (excludes BezierSpline / PolyPath / LUTBezier modifiers).
572 pub nodes: Vec<Node>,
573 pub node_by_name: HashMap<String, NodeId>,
574 /// Animation splines keyed by Fusion modifier tool name (e.g. `"Merge6Blend"`).
575 pub splines: HashMap<String, BezierSpline>,
576 /// 2D PolyPath animation modifiers keyed by name (e.g. `"Path5"`).
577 pub poly_paths: HashMap<String, PolyPath>,
578 /// Animated gradients (stored as a spline-like modifier with keyframes of Gradients or static).
579 pub gradient_modifiers: HashMap<String, Vec<(f64, Gradient)>>,
580 /// Text modifiers such as `StyledTextCLS` (`CharacterLevelStyling1`) keyed by name.
581 pub text_modifiers: HashMap<String, String>,
582 /// Keyframed `StyledText` splines (`BezierSpline` with `Value = Text { Value = "..." }`).
583 pub text_splines: HashMap<String, Vec<(f64, String)>>,
584 /// Keyframed `Polyline` splines (`BezierSpline` with `Value = Polyline { Points = ... }`).
585 pub polyline_splines: HashMap<String, (BezierSpline, Vec<(f64, Vec<crate::spline::PolyPoint>)>)>,
586 /// Per-character styling overrides from `StyledTextCLS` keyed by modifier name.
587 pub text_cls: HashMap<String, Vec<ClsEntry>>,
588 /// Procedural `Shake` modifiers keyed by modifier name (e.g. `"Shake1"`).
589 pub shakes: HashMap<String, ShakeModifier>,
590 /// Standalone `Expression` modifiers keyed by modifier name (e.g. `"Expression1"`).
591 pub expression_modifiers: HashMap<String, ExpressionModifier>,
592 /// `(internal node, port)` wires whose out-of-scope `SourceOp` into another macro was cleared
593 /// on load; the raw AST still carries the original text.
594 pub(crate) cross_macro_wires: HashSet<(String, String)>,
595 /// Preserved raw root `Composition { ... }` Lua AST for lossless `.comp` roundtrip.
596 pub raw_root: Option<LuaTable>,
597 /// Generation counter incremented whenever any node, wire, or spline mutates.
598 pub revision: u64,
599}
600
601const MODIFIER_TYPES: &[&str] = &[
602 "BezierSpline",
603 "LUTBezier",
604 "PolyPath",
605 "Path",
606 "XYPath",
607 "Shake",
608 "Perturb",
609 "Expression",
610 "StyledTextCLS",
611 "CharacterLevelStyling",
612 "Follower",
613 "TrackerModifier",
614 "PublishNumber",
615 "PublishPoint",
616 "Calculation",
617 "TimeCode",
618 "Offset",
619 "Probe",
620 "FromImage",
621 "AnimCurves",
622 "GradientModifier",
623];
624
625/// Each loaded comp gets its own revision range so frame-cache keys never collide across reloads.
626pub(super) static NEXT_COMP_REVISION: AtomicU64 = AtomicU64::new(1);
627pub(super) const REVISION_STRIDE: u64 = 1 << 32;
628
629/// Max hops through chained expression modifiers / `Node.Param` references before evaluation gives up.
630pub(super) const MAX_EXPR_DEPTH: usize = 16;
631
632pub(crate) fn is_modifier_type(kind: &str) -> bool {
633 MODIFIER_TYPES.contains(&kind)
634 || (kind.ends_with("Spline") && kind != "sBSpline")
635 || kind.ends_with("Modifier")
636}
637
638
639impl Comp {
640 pub fn node(&self, id: NodeId) -> &Node {
641 &self.nodes[id.0]
642 }
643
644 pub fn node_mut(&mut self, id: NodeId) -> &mut Node {
645 self.revision += 1;
646 &mut self.nodes[id.0]
647 }
648
649 pub fn find_node(&self, name: &str) -> Option<NodeId> {
650 self.node_by_name.get(name).copied()
651 }
652
653 /// Picks the default output node to view (the input of `Saver1`/first `Saver`, or the last `Merge`).
654 pub fn default_output_node(&self) -> Option<NodeId> {
655 // Prefer the upstream input of the first Saver (or Saver itself)
656 for n in &self.nodes {
657 if n.kind == "Saver" {
658 if let Some(src) = n.connected_node("Input").and_then(|s| self.find_node(s)) {
659 return Some(src);
660 }
661 return Some(n.id);
662 }
663 }
664 // Fallback: non-internal node with no outgoing connections, preferring the last sink (ColorCorrector/Merge)
665 let mut has_consumer = HashSet::new();
666 let names: HashSet<String> = self.node_by_name.keys().cloned().collect();
667 for n in &self.nodes {
668 for (_, src, _) in n.image_connections(&names) {
669 has_consumer.insert(src);
670 }
671 }
672 let non_internal_sinks = || {
673 self.nodes
674 .iter()
675 .rev()
676 .filter(|n| !n.internal && !has_consumer.contains(&n.name))
677 };
678 non_internal_sinks()
679 .find(|n| matches!(n.kind.as_str(), "ColorCorrector" | "BrightnessContrast" | "Merge"))
680 .or_else(|| non_internal_sinks().next())
681 .or_else(|| self.nodes.iter().rev().find(|n| !n.internal))
682 .or_else(|| self.nodes.last())
683 .map(|n| n.id)
684 }
685
686 /// Returns all `(param_label, spline_name)` animated channels attached to `node_id`
687 /// (including `PolyPath`'s `Displacement` spline!).
688 pub fn node_splines(&self, node_id: NodeId) -> Vec<(String, String)> {
689 let Some(node) = self.nodes.get(node_id.0) else { return Vec::new() };
690 let mut out = Vec::new();
691 for (param, binding) in &node.inputs {
692 if let Some(src) = &binding.source_op {
693 if self.splines.contains_key(src) {
694 out.push((param.clone(), src.clone()));
695 } else if let Some(pp) = self.poly_paths.get(src) {
696 if let Some(disp) = &pp.displacement_op {
697 if self.splines.contains_key(disp) {
698 out.push((format!("{param} (Path)"), disp.clone()));
699 }
700 }
701 }
702 }
703 }
704 out.sort_by(|a, b| a.0.cmp(&b.0));
705 out
706 }
707
708 /// Connects `src` node's `"Output"` to `dst` node's `port` input (ignores self-loops and cycles).
709 pub fn connect(&mut self, src: NodeId, dst: NodeId, port: &str) {
710 let _ = self.connect_output(src, "Output", dst, port);
711 }
712
713 /// Inserts `mid` node cleanly onto the wire `src -> dst.dst_port`!
714 /// Wires `src -> mid.(default_input)` and `mid -> dst.dst_port`.
715 pub fn insert_on_wire(&mut self, mid: NodeId, src: NodeId, dst: NodeId, dst_port: &str) {
716 let _ = self.splice_node_into_pipe(mid, src, dst, dst_port);
717 }
718
719 /// Toggles bypass (`PassThrough`) on a node.
720 pub fn toggle_bypass(&mut self, id: NodeId) {
721 let _ = self.toggle_passthrough(id);
722 }
723
724 /// Extracts metadata for every top-level (non-internal) `Saver` node in this comp.
725 pub fn savers(&self) -> Vec<SaverSpec> {
726 let mut out = Vec::new();
727 for n in &self.nodes {
728 if n.internal || n.kind != "Saver" {
729 continue;
730 }
731 let upstream = n.connected_node("Input").and_then(|src| self.find_node(src));
732 let filename = n
733 .clips
734 .first()
735 .map(|c| c.filename.clone())
736 .or_else(|| {
737 n.raw
738 .get_table("Inputs")
739 .and_then(|i| i.get_table("Clip"))
740 .and_then(|c| c.get_table("Value"))
741 .and_then(|v| v.get_str("Filename"))
742 .map(str::to_owned)
743 })
744 .unwrap_or_default();
745 let set_seq = n.static_number("SetSequenceStart").map(|v| v > 0.5);
746 let sequence_start = if set_seq == Some(true) {
747 n.static_number("SequenceStartFrame").map(|v| v.round() as i64)
748 } else {
749 None
750 };
751 out.push(SaverSpec {
752 node_id: n.id,
753 name: n.name.clone(),
754 upstream,
755 filename,
756 range: self.render_range,
757 sequence_start,
758 });
759 }
760 out
761 }
762}
763
764pub fn default_main_input_port(kind: &str) -> &'static str {
765 match kind {
766 "Merge" | "Dissolve" | "ChannelBoolean" | "Dimension.PlanarTracker" | "PlanarTracker" => {
767 "Background"
768 }
769 "BitmapMask" => "Image",
770 "Switch" => "Input0",
771 "Fuse.Switch" | "Fuse.SwitchElse" => "Input1",
772 "Merge3D" => "SceneInput1",
773 "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D"
774 | "Displace3D" | "Duplicate3D" => "SceneInput",
775 "ImagePlane3D" | "TextureTransformOperator" => "MaterialInput",
776 "Fuse.Colorize" | "Fuse.Outline" | "Fuse.AlphaWeightedNoise" => "Image",
777 "Custom" => "Image1",
778 "MacroOperator" | "GroupOperator" => "MainInput1",
779 _ => "Input",
780 }
781}