| 1 | //! Core composition IR, Fusion `.comp` importer, parameter evaluation, and graph editing. |
| 2 | |
| 3 | mod eval; |
| 4 | mod load; |
| 5 | mod math; |
| 6 | mod save; |
| 7 | #[cfg(test)] |
| 8 | mod tests; |
| 9 | |
| 10 | pub use math::{GridMesh, MeshPoint}; |
| 11 | pub(crate) use math::{find_raw_tool, find_raw_tool_mut}; |
| 12 | pub(crate) use save::{ensure_table_mut, is_group_kind, param_value_to_lua, vec2_lua}; |
| 13 | |
| 14 | use crate::lua_value::{LuaTable, LuaValue}; |
| 15 | use crate::spline::{BezierSpline, Gradient, PolyPath}; |
| 16 | use std::collections::{HashMap, HashSet}; |
| 17 | use std::path::{Path, PathBuf}; |
| 18 | use 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)] |
| 23 | pub enum BitDepth { |
| 24 | #[default] |
| 25 | Int8 = 1, |
| 26 | Int16 = 2, |
| 27 | Float16 = 3, |
| 28 | Float32 = 4, |
| 29 | } |
| 30 | |
| 31 | impl 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)] |
| 48 | pub struct NodeId(pub usize); |
| 49 | |
| 50 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 51 | pub 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 | |
| 59 | impl 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. |
| 78 | pub 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 | | "Paint" |
| 248 | | "PaintMask" |
| 249 | | "PolylineStroke" |
| 250 | | "Multistroke" |
| 251 | | "TextPlus" |
| 252 | | "Fuse.Colorize" |
| 253 | | "Fuse.Outline" |
| 254 | | "Fuse.XfChroma" |
| 255 | | "Fuse.Cryptomatte" |
| 256 | | "Cryptomatte" |
| 257 | | "Fuse.Null" |
| 258 | | "Fuse.SetMetaData" |
| 259 | | "Fuse.Linger" |
| 260 | | "Fuse.OCLRays" |
| 261 | | "Dimension.OpticalFlow" |
| 262 | | "Dimension.CopyAux" |
| 263 | | "OpticalFlow" |
| 264 | | "Custom" |
| 265 | // Modifiers |
| 266 | | "Expression" |
| 267 | // Particle system |
| 268 | | "pRender" |
| 269 | | "pEmitter" |
| 270 | | "pPointForce" |
| 271 | | "pDirectionalForce" |
| 272 | | "pTurbulence" |
| 273 | | "pDrag" |
| 274 | | "pFriction" |
| 275 | | "pKill" |
| 276 | | "pMerge" |
| 277 | | "pBounce" |
| 278 | | "pVortex" |
| 279 | | "pFlock" |
| 280 | | "pSpawn" |
| 281 | | "pChangeStyle" |
| 282 | | "pGradientForce" |
| 283 | | "pAvoid" |
| 284 | | "pCustom" |
| 285 | | "pCustomForce" |
| 286 | | "pFollow" |
| 287 | | "pImageEmitter" |
| 288 | | "pTangentForce" |
| 289 | // 3D tools |
| 290 | | "Renderer3D" |
| 291 | | "Merge3D" |
| 292 | | "Transform3D" |
| 293 | | "Camera3D" |
| 294 | | "ImagePlane3D" |
| 295 | | "Shape3D" |
| 296 | | "Cube3D" |
| 297 | | "SurfaceFBXMesh" |
| 298 | | "Text3D" |
| 299 | | "LightAmbient" |
| 300 | | "LightDirectional" |
| 301 | | "LightPoint" |
| 302 | | "LightSpot" |
| 303 | | "MtlBlinn" |
| 304 | | "MtlCookTorrance" |
| 305 | | "MtlPhong" |
| 306 | | "MtlWard" |
| 307 | | "MtlReflect" |
| 308 | | "MtlChanBool" |
| 309 | | "SphereMap" |
| 310 | | "Texture2DOperator" |
| 311 | | "TextureTransformOperator" |
| 312 | | "BumpMap" |
| 313 | | "ReplaceMaterial3D" |
| 314 | | "Override3D" |
| 315 | | "Duplicate3D" |
| 316 | | "Replicate3D" |
| 317 | | "Bender3D" |
| 318 | | "ReplaceNormals3D" |
| 319 | | "Displace3D" |
| 320 | ) |
| 321 | } |
| 322 | |
| 323 | /// Metadata extracted from a Fusion `Saver` node. |
| 324 | #[derive(Clone, Debug, PartialEq)] |
| 325 | pub struct SaverSpec { |
| 326 | pub node_id: NodeId, |
| 327 | pub name: String, |
| 328 | pub upstream: Option<NodeId>, |
| 329 | pub filename: String, |
| 330 | pub range: [i64; 2], |
| 331 | pub sequence_start: Option<i64>, |
| 332 | } |
| 333 | |
| 334 | impl SaverSpec { |
| 335 | /// Computes the output path for `frame` following Fusion's Saver sequence naming rules: |
| 336 | /// - `foo_0000.png` -> `foo_{frame:04}.png` (preserving digit width) |
| 337 | /// - `0000.png` -> `{frame:04}.png` |
| 338 | /// - `render.png` -> `render{frame:04}.png` (4-digit default when no trailing digits exist) |
| 339 | pub fn frame_path(&self, frame: i64) -> PathBuf { |
| 340 | let effective_frame = if let Some(start) = self.sequence_start { |
| 341 | start.saturating_add(frame.saturating_sub(self.range[0])) |
| 342 | } else { |
| 343 | frame |
| 344 | }; |
| 345 | |
| 346 | let path = Path::new(&self.filename); |
| 347 | let parent = path.parent().unwrap_or_else(|| Path::new("")); |
| 348 | let fname = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); |
| 349 | |
| 350 | let (stem, ext) = match fname.rfind('.') { |
| 351 | Some(dot) => (&fname[..dot], &fname[dot..]), |
| 352 | None => (fname, ""), |
| 353 | }; |
| 354 | |
| 355 | let prefix = stem.trim_end_matches(|c: char| c.is_ascii_digit()); |
| 356 | let digits = &stem[prefix.len()..]; |
| 357 | let width = if digits.is_empty() { 4 } else { digits.len() }; |
| 358 | |
| 359 | let formatted_num = if effective_frame < 0 { |
| 360 | format!("-{:0width$}", effective_frame.unsigned_abs()) |
| 361 | } else { |
| 362 | format!("{effective_frame:0width$}") |
| 363 | }; |
| 364 | |
| 365 | let out_name = format!("{prefix}{formatted_num}{ext}"); |
| 366 | if parent.as_os_str().is_empty() { |
| 367 | PathBuf::from(out_name) |
| 368 | } else { |
| 369 | parent.join(out_name) |
| 370 | } |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | #[derive(Clone, Debug, PartialEq)] |
| 375 | pub enum ParamValue { |
| 376 | Number(f64), |
| 377 | Point([f64; 2]), |
| 378 | Text(String), |
| 379 | FuId(String), |
| 380 | Gradient(Gradient), |
| 381 | Raw(LuaValue), |
| 382 | } |
| 383 | |
| 384 | impl ParamValue { |
| 385 | pub fn as_f64(&self) -> Option<f64> { |
| 386 | match self { |
| 387 | ParamValue::Number(n) => Some(*n), |
| 388 | _ => None, |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | pub fn as_point(&self) -> Option<[f64; 2]> { |
| 393 | match self { |
| 394 | ParamValue::Point(p) => Some(*p), |
| 395 | _ => None, |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | pub fn as_str(&self) -> Option<&str> { |
| 400 | match self { |
| 401 | ParamValue::Text(s) | ParamValue::FuId(s) => Some(s.as_str()), |
| 402 | _ => None, |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | #[derive(Clone, Debug, PartialEq)] |
| 408 | pub struct InputBinding { |
| 409 | pub value: Option<ParamValue>, |
| 410 | pub source_op: Option<String>, |
| 411 | pub source_output: Option<String>, |
| 412 | pub expression: Option<String>, |
| 413 | } |
| 414 | |
| 415 | #[derive(Clone, Debug, PartialEq)] |
| 416 | pub struct ClipSpec { |
| 417 | pub filename: String, |
| 418 | pub alternate_filename: Option<String>, |
| 419 | pub start_frame: i64, |
| 420 | pub length: Option<i64>, |
| 421 | pub trim_in: i64, |
| 422 | pub trim_out: i64, |
| 423 | pub global_start: i64, |
| 424 | pub global_end: i64, |
| 425 | pub extend_first: i64, |
| 426 | pub extend_last: i64, |
| 427 | pub loop_clip: bool, |
| 428 | pub reverse: bool, |
| 429 | } |
| 430 | |
| 431 | #[derive(Clone, Debug, PartialEq)] |
| 432 | pub struct Node { |
| 433 | pub id: NodeId, |
| 434 | pub name: String, |
| 435 | /// Original Fusion operator class name (e.g. `"Merge"`, `"Fuse.Colorize"`, `"TextPlus"`). |
| 436 | pub kind: String, |
| 437 | /// Position in Flow coordinates (Fusion `ViewInfo.Pos`). |
| 438 | pub pos: [f32; 2], |
| 439 | pub bypassed: bool, |
| 440 | /// True for internal tools unpacked from a MacroOperator/GroupOperator (hidden from top-level Flow). |
| 441 | pub internal: bool, |
| 442 | /// For MacroOperator / GroupOperator nodes, the internal tool that produces this macro's output. |
| 443 | pub macro_output: Option<NodeId>, |
| 444 | pub inputs: HashMap<String, InputBinding>, |
| 445 | /// Ordered list of image/mask connection ports (`(input_name, source_node_name, source_port)`). |
| 446 | pub clips: Vec<ClipSpec>, |
| 447 | /// Preserved raw Lua table for lossless roundtrip / debugging. |
| 448 | pub raw: LuaTable, |
| 449 | } |
| 450 | |
| 451 | impl Node { |
| 452 | /// Returns all image/mask connections targeting another flow node. |
| 453 | pub fn image_connections(&self, node_names: &HashSet<String>) -> Vec<(String, String, PortRole)> { |
| 454 | let mut out = Vec::new(); |
| 455 | for (port, binding) in &self.inputs { |
| 456 | if let Some(src) = &binding.source_op { |
| 457 | if node_names.contains(src) { |
| 458 | let role = PortRole::from_input_name(port); |
| 459 | out.push((port.clone(), src.clone(), role)); |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | out.sort_by(|a, b| a.0.cmp(&b.0)); |
| 464 | out |
| 465 | } |
| 466 | |
| 467 | /// Returns static number value if present. |
| 468 | pub fn static_number(&self, name: &str) -> Option<f64> { |
| 469 | self.inputs.get(name)?.value.as_ref()?.as_f64() |
| 470 | } |
| 471 | |
| 472 | pub fn static_str(&self, name: &str) -> Option<&str> { |
| 473 | self.inputs.get(name)?.value.as_ref()?.as_str() |
| 474 | } |
| 475 | |
| 476 | pub fn static_point(&self, name: &str) -> Option<[f64; 2]> { |
| 477 | self.inputs.get(name)?.value.as_ref()?.as_point() |
| 478 | } |
| 479 | |
| 480 | pub fn connected_node(&self, port: &str) -> Option<&str> { |
| 481 | self.inputs.get(port)?.source_op.as_deref() |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | /// Per-character styling entry from Fusion's `StyledTextCLS` (`CharacterLevelStyling`). |
| 486 | /// Common Fusion property IDs: `100` = Font family, `102` = Size, `109` = Font style, |
| 487 | /// `1330` = Character shear X, `1350` = Character X offset, `1351` = Character Y offset. |
| 488 | #[derive(Clone, Debug, PartialEq)] |
| 489 | pub struct ClsEntry { |
| 490 | pub prop_id: u32, |
| 491 | pub start: usize, |
| 492 | pub end: usize, |
| 493 | pub value: f32, |
| 494 | pub text: String, |
| 495 | } |
| 496 | |
| 497 | /// Fusion `Shake` procedural modifier (`Source = "X"` / `"Y"` / `"Value"` / `"Position"`). |
| 498 | #[derive(Clone, Debug, PartialEq)] |
| 499 | pub struct ShakeModifier { |
| 500 | pub inputs: HashMap<String, InputBinding>, |
| 501 | } |
| 502 | |
| 503 | /// Fusion standalone `Expression` modifier (`NumberExpression`, `PointExpressionX`, |
| 504 | /// `PointExpressionY`, `PointExpression`, `n1..n9` / `NumberIn1..9`, `p1..p9` / `PointIn1..9`). |
| 505 | #[derive(Clone, Debug, PartialEq)] |
| 506 | pub struct ExpressionModifier { |
| 507 | pub inputs: HashMap<String, InputBinding>, |
| 508 | } |
| 509 | |
| 510 | #[derive(Clone, Debug)] |
| 511 | pub struct Comp { |
| 512 | pub path: Option<PathBuf>, |
| 513 | pub name: String, |
| 514 | pub width: u32, |
| 515 | pub height: u32, |
| 516 | pub fps: f64, |
| 517 | /// Project default HiQ working bit depth from `Prefs.Comp.FrameFormat.DepthFull`. |
| 518 | pub depth_full: BitDepth, |
| 519 | pub current_time: f64, |
| 520 | pub global_range: [i64; 2], |
| 521 | pub render_range: [i64; 2], |
| 522 | pub audio_filename: Option<String>, |
| 523 | pub audio_offset: f64, |
| 524 | /// Flow operators (excludes BezierSpline / PolyPath / LUTBezier modifiers). |
| 525 | pub nodes: Vec<Node>, |
| 526 | pub node_by_name: HashMap<String, NodeId>, |
| 527 | /// Animation splines keyed by Fusion modifier tool name (e.g. `"Merge6Blend"`). |
| 528 | pub splines: HashMap<String, BezierSpline>, |
| 529 | /// 2D PolyPath animation modifiers keyed by name (e.g. `"Path5"`). |
| 530 | pub poly_paths: HashMap<String, PolyPath>, |
| 531 | /// Animated gradients (stored as a spline-like modifier with keyframes of Gradients or static). |
| 532 | pub gradient_modifiers: HashMap<String, Vec<(f64, Gradient)>>, |
| 533 | /// Text modifiers such as `StyledTextCLS` (`CharacterLevelStyling1`) keyed by name. |
| 534 | pub text_modifiers: HashMap<String, String>, |
| 535 | /// Keyframed `StyledText` splines (`BezierSpline` with `Value = Text { Value = "..." }`). |
| 536 | pub text_splines: HashMap<String, Vec<(f64, String)>>, |
| 537 | /// Keyframed `Polyline` splines (`BezierSpline` with `Value = Polyline { Points = ... }`). |
| 538 | pub polyline_splines: HashMap<String, (BezierSpline, Vec<(f64, Vec<crate::spline::PolyPoint>)>)>, |
| 539 | /// Per-character styling overrides from `StyledTextCLS` keyed by modifier name. |
| 540 | pub text_cls: HashMap<String, Vec<ClsEntry>>, |
| 541 | /// Procedural `Shake` modifiers keyed by modifier name (e.g. `"Shake1"`). |
| 542 | pub shakes: HashMap<String, ShakeModifier>, |
| 543 | /// Standalone `Expression` modifiers keyed by modifier name (e.g. `"Expression1"`). |
| 544 | pub expression_modifiers: HashMap<String, ExpressionModifier>, |
| 545 | /// `(internal node, port)` wires whose out-of-scope `SourceOp` into another macro was cleared |
| 546 | /// on load; the raw AST still carries the original text. |
| 547 | pub(crate) cross_macro_wires: HashSet<(String, String)>, |
| 548 | /// Preserved raw root `Composition { ... }` Lua AST for lossless `.comp` roundtrip. |
| 549 | pub raw_root: Option<LuaTable>, |
| 550 | /// Generation counter incremented whenever any node, wire, or spline mutates. |
| 551 | pub revision: u64, |
| 552 | } |
| 553 | |
| 554 | const MODIFIER_TYPES: &[&str] = &[ |
| 555 | "BezierSpline", |
| 556 | "LUTBezier", |
| 557 | "PolyPath", |
| 558 | "Path", |
| 559 | "XYPath", |
| 560 | "Shake", |
| 561 | "Perturb", |
| 562 | "Expression", |
| 563 | "StyledTextCLS", |
| 564 | "CharacterLevelStyling", |
| 565 | "Follower", |
| 566 | "TrackerModifier", |
| 567 | "PublishNumber", |
| 568 | "PublishPoint", |
| 569 | "Calculation", |
| 570 | "TimeCode", |
| 571 | "Offset", |
| 572 | "Probe", |
| 573 | "FromImage", |
| 574 | "AnimCurves", |
| 575 | "GradientModifier", |
| 576 | ]; |
| 577 | |
| 578 | /// Each loaded comp gets its own revision range so frame-cache keys never collide across reloads. |
| 579 | pub(super) static NEXT_COMP_REVISION: AtomicU64 = AtomicU64::new(1); |
| 580 | pub(super) const REVISION_STRIDE: u64 = 1 << 32; |
| 581 | |
| 582 | /// Max hops through chained expression modifiers / `Node.Param` references before evaluation gives up. |
| 583 | pub(super) const MAX_EXPR_DEPTH: usize = 16; |
| 584 | |
| 585 | pub(crate) fn is_modifier_type(kind: &str) -> bool { |
| 586 | MODIFIER_TYPES.contains(&kind) |
| 587 | || (kind.ends_with("Spline") && kind != "sBSpline") |
| 588 | || kind.ends_with("Modifier") |
| 589 | } |
| 590 | |
| 591 | |
| 592 | impl Comp { |
| 593 | pub fn node(&self, id: NodeId) -> &Node { |
| 594 | &self.nodes[id.0] |
| 595 | } |
| 596 | |
| 597 | pub fn node_mut(&mut self, id: NodeId) -> &mut Node { |
| 598 | self.revision += 1; |
| 599 | &mut self.nodes[id.0] |
| 600 | } |
| 601 | |
| 602 | pub fn find_node(&self, name: &str) -> Option<NodeId> { |
| 603 | self.node_by_name.get(name).copied() |
| 604 | } |
| 605 | |
| 606 | /// Picks the default output node to view (the input of `Saver1`/first `Saver`, or the last `Merge`). |
| 607 | pub fn default_output_node(&self) -> Option<NodeId> { |
| 608 | // Prefer the upstream input of the first Saver (or Saver itself) |
| 609 | for n in &self.nodes { |
| 610 | if n.kind == "Saver" { |
| 611 | if let Some(src) = n.connected_node("Input").and_then(|s| self.find_node(s)) { |
| 612 | return Some(src); |
| 613 | } |
| 614 | return Some(n.id); |
| 615 | } |
| 616 | } |
| 617 | // Fallback: non-internal node with no outgoing connections, preferring the last sink (ColorCorrector/Merge) |
| 618 | let mut has_consumer = HashSet::new(); |
| 619 | let names: HashSet<String> = self.node_by_name.keys().cloned().collect(); |
| 620 | for n in &self.nodes { |
| 621 | for (_, src, _) in n.image_connections(&names) { |
| 622 | has_consumer.insert(src); |
| 623 | } |
| 624 | } |
| 625 | let non_internal_sinks = || { |
| 626 | self.nodes |
| 627 | .iter() |
| 628 | .rev() |
| 629 | .filter(|n| !n.internal && !has_consumer.contains(&n.name)) |
| 630 | }; |
| 631 | non_internal_sinks() |
| 632 | .find(|n| matches!(n.kind.as_str(), "ColorCorrector" | "BrightnessContrast" | "Merge")) |
| 633 | .or_else(|| non_internal_sinks().next()) |
| 634 | .or_else(|| self.nodes.iter().rev().find(|n| !n.internal)) |
| 635 | .or_else(|| self.nodes.last()) |
| 636 | .map(|n| n.id) |
| 637 | } |
| 638 | |
| 639 | /// Returns all `(param_label, spline_name)` animated channels attached to `node_id` |
| 640 | /// (including `PolyPath`'s `Displacement` spline!). |
| 641 | pub fn node_splines(&self, node_id: NodeId) -> Vec<(String, String)> { |
| 642 | let Some(node) = self.nodes.get(node_id.0) else { return Vec::new() }; |
| 643 | let mut out = Vec::new(); |
| 644 | for (param, binding) in &node.inputs { |
| 645 | if let Some(src) = &binding.source_op { |
| 646 | if self.splines.contains_key(src) { |
| 647 | out.push((param.clone(), src.clone())); |
| 648 | } else if let Some(pp) = self.poly_paths.get(src) { |
| 649 | if let Some(disp) = &pp.displacement_op { |
| 650 | if self.splines.contains_key(disp) { |
| 651 | out.push((format!("{param} (Path)"), disp.clone())); |
| 652 | } |
| 653 | } |
| 654 | } |
| 655 | } |
| 656 | } |
| 657 | out.sort_by(|a, b| a.0.cmp(&b.0)); |
| 658 | out |
| 659 | } |
| 660 | |
| 661 | /// Connects `src` node's `"Output"` to `dst` node's `port` input (ignores self-loops and cycles). |
| 662 | pub fn connect(&mut self, src: NodeId, dst: NodeId, port: &str) { |
| 663 | let _ = self.connect_output(src, "Output", dst, port); |
| 664 | } |
| 665 | |
| 666 | /// Inserts `mid` node cleanly onto the wire `src -> dst.dst_port`! |
| 667 | /// Wires `src -> mid.(default_input)` and `mid -> dst.dst_port`. |
| 668 | pub fn insert_on_wire(&mut self, mid: NodeId, src: NodeId, dst: NodeId, dst_port: &str) { |
| 669 | let _ = self.splice_node_into_pipe(mid, src, dst, dst_port); |
| 670 | } |
| 671 | |
| 672 | /// Toggles bypass (`PassThrough`) on a node. |
| 673 | pub fn toggle_bypass(&mut self, id: NodeId) { |
| 674 | let _ = self.toggle_passthrough(id); |
| 675 | } |
| 676 | |
| 677 | /// Extracts metadata for every top-level (non-internal) `Saver` node in this comp. |
| 678 | pub fn savers(&self) -> Vec<SaverSpec> { |
| 679 | let mut out = Vec::new(); |
| 680 | for n in &self.nodes { |
| 681 | if n.internal || n.kind != "Saver" { |
| 682 | continue; |
| 683 | } |
| 684 | let upstream = n.connected_node("Input").and_then(|src| self.find_node(src)); |
| 685 | let filename = n |
| 686 | .clips |
| 687 | .first() |
| 688 | .map(|c| c.filename.clone()) |
| 689 | .or_else(|| { |
| 690 | n.raw |
| 691 | .get_table("Inputs") |
| 692 | .and_then(|i| i.get_table("Clip")) |
| 693 | .and_then(|c| c.get_table("Value")) |
| 694 | .and_then(|v| v.get_str("Filename")) |
| 695 | .map(str::to_owned) |
| 696 | }) |
| 697 | .unwrap_or_default(); |
| 698 | let set_seq = n.static_number("SetSequenceStart").map(|v| v > 0.5); |
| 699 | let sequence_start = if set_seq == Some(true) { |
| 700 | n.static_number("SequenceStartFrame").map(|v| v.round() as i64) |
| 701 | } else { |
| 702 | None |
| 703 | }; |
| 704 | out.push(SaverSpec { |
| 705 | node_id: n.id, |
| 706 | name: n.name.clone(), |
| 707 | upstream, |
| 708 | filename, |
| 709 | range: self.render_range, |
| 710 | sequence_start, |
| 711 | }); |
| 712 | } |
| 713 | out |
| 714 | } |
| 715 | } |
| 716 | |
| 717 | pub fn default_main_input_port(kind: &str) -> &'static str { |
| 718 | match kind { |
| 719 | "Merge" | "Dissolve" | "ChannelBoolean" | "Dimension.PlanarTracker" | "PlanarTracker" => { |
| 720 | "Background" |
| 721 | } |
| 722 | "BitmapMask" => "Image", |
| 723 | "Switch" => "Input0", |
| 724 | "Fuse.Switch" | "Fuse.SwitchElse" => "Input1", |
| 725 | "Merge3D" => "SceneInput1", |
| 726 | "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" |
| 727 | | "Displace3D" | "Duplicate3D" => "SceneInput", |
| 728 | "ImagePlane3D" | "TextureTransformOperator" => "MaterialInput", |
| 729 | "Fuse.Colorize" | "Fuse.Outline" | "Fuse.AlphaWeightedNoise" => "Image", |
| 730 | "Custom" => "Image1", |
| 731 | "MacroOperator" | "GroupOperator" => "MainInput1", |
| 732 | _ => "Input", |
| 733 | } |
| 734 | } |