From afe537215348ea618a2d7a817264ba6e771728a0 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 14:44:17 -0800 Subject: [PATCH] Add Drip, Dent, sRender/sNGon shape pipeline, instanced SourceOp inheritance, and >99.3% archive coverage (#20, #17) --- compatibility.md | 47 +- crates/engine/src/eval/mod.rs | 33 +- crates/engine/src/eval/shapes_warp.rs | 1057 +++++++++++++++++++++ crates/engine/src/shaders/archive_fx.wgsl | 116 +++ crates/model/src/comp.rs | 218 ++++- scripts/gen_compatibility.py | 20 +- 6 files changed, 1462 insertions(+), 29 deletions(-) create mode 100644 crates/engine/src/eval/shapes_warp.rs create mode 100644 crates/engine/src/shaders/archive_fx.wgsl diff --git a/compatibility.md b/compatibility.md index f143b2a37d531510acc8bbd8310ba040ac5a9794..6d4846db71904a92072615f73ca4175c86355c41 100644 --- a/compatibility.md +++ b/compatibility.md @@ -9,10 +9,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | Metric | Value | | --- | --- | -| **Supported Flow Tools** | **95** (74 2D/Fuse/utility in `eval.rs`, 19 3D scene nodes in `scene3d.rs`, 2 Flow annotations) | -| **Modifiers & Animation** | **7** systems (8 Fusion modifier classes + Lua expressions) | +| **Supported Flow Tools** | **110** (85 2D/Fuse/utility in `eval.rs`, 23 3D scene nodes in `scene3d.rs`, 2 Flow annotations) | +| **Modifiers & Animation** | **8** systems (9 Fusion modifier classes + Lua expressions) | | **Active Corpus (`trees/fusion`) Coverage** | **99.5%** (1,984 / 1,993 nodes across 16 `.comp` files) | -| **Archive Corpus (`private/samples`) Coverage** | **98.7%** (54,258 / 54,955 nodes across 324 `.comp` files) | +| **Archive Corpus (`private/samples`) Coverage** | **99.4%** (54,635 / 54,955 nodes across 324 `.comp` files) | | **HiQ vs Fast Mode** | **`HiQ`**: honors `DepthFull` / generator `Depth` / `ChangeDepth` (`Rgba8Unorm`, clamped `Rgba16Float`, unclamped HDR `Rgba16Float`/`Rgba32Float`), full-res blurs & `XGlow`. **`Fast`**: collapses working targets to `Rgba8Unorm`, downsamples blurs, caps `XGlow` octaves for interactive scrubbing. | ## Generators @@ -83,6 +83,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | `DVE` | `tier1_b` | 0.1%–0.4% | 4 / 22 | 2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`). | | `Displace` | `displace`, `displace_wave` | 0.0%–0.1% | 11 / 109 | `XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting). | | `Vortex` | `vortex_cc` | 0.0%–0.4% | 1 / 1 | Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`). | +| `Drip` | Unit tests | 0.0% | 0 / 29 | Concentric ripple warp (`Center`, `Strength`, `Amplitude`, `Frequency`, `Aspect`, `Phase`, `Dampening`, `Shape`, `Blend`, `EffectMask`). | +| `Dent` | Unit tests | 0.0% | 0 / 7 | Radial distortion warp (`Center`, `Strength`, `Size`, `Type`: `Dent`/`Sine`/`Pinch`/`Punch`, `Blend`, `EffectMask`). | | `Fuse.Duplicate` | `archive_3d` | 0.0%–0.4% | 0 / 46 | Multi-copy iterative 2D transform composite (`Copies`, `Center`, `Size`, `Angle`, `Gain`, `Blend`, `TimeOffset`, `MergeUnder`). | | `Fuse.KScope` | Unit tests | 0.0% | 0 / 27 | N-slice radial kaleidoscope mirror (`Slices`, `Center`, `Angle`, `CaptureAngle`, `Scale`, `Edges`). | | `Scale` | Suite comps | 0.0%–0.2% | 12 / 98 | Proportional/non-proportional image scaling with resampling filter. | @@ -100,6 +102,19 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | `BitmapMask` | `mask_softedge` | 0.0%–0.2% | 3 / 121 | GPU image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`/`Saturation`/`Lightness`/`Hue`), `Low`/`High` clip, centered 1:1 alignment, `SoftEdge`, `Invert`, `Level`, `PaintMode`. | | `WandMask` | `archive_3d` | 0.0%–0.3% | 0 / 150 | Seeded BFS flood-fill wand mask (`Source`, `SelectionPoint`, `SelectionRange`, `ColorSpace`, `SoftEdge`, `Invert`, `Level`, `PaintMode`). | +## 2D Vector Shapes + +| Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | +| --- | --- | --- | --- | --- | +| `sRender` | Unit tests | 0.0% | 0 / 21 | Antialiased `zeno` 2D vector shape tree rasterizer (`Width`, `Height`, `Blend`, `EffectMask`, cached RGBA upload & `HiQ` depth promotion). | +| `sNGon` | Unit tests | 0.0% | 0 / 9 | Regular N-sided polygon vector shape (`Sides`, `Width`, `Height`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, `JoinStyle`, RGBA color). | +| `sRectangle` | Unit tests | 0.0% | 0 / 6 | Vector rectangle & rounded rectangle (`Width`, `Height`, `CornerRadius`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, RGBA color). | +| `sEllipse` | Unit tests | 0.0% | 0 / 3 | Cubic Bezier vector ellipse (`Width`, `Height`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, RGBA color). | +| `sMerge` | Unit tests | 0.0% | 0 / 3 | Composites multiple upstream vector shape inputs (`Input1`..`InputN`) in painter's order. | +| `sTransform` | Unit tests | 0.0% | 0 / 4 | 2D affine shape transform (`XOffset`/`YOffset`, `XSize`/`YSize`, `Scale`, `ZRotation`, `XPivot`/`YPivot`). | +| `sBoolean` | Unit tests | 0.0% | 0 / 0 | Shape boolean combiner (`Union`, `Intersect`, `Subtract`, `Xor`) over `Input1` and `Input2`. | +| `sOutline` | Unit tests | 0.0% | 0 / 0 | Converts upstream vector shapes into stroked outlines (`Thickness`/`BorderWidth`, `JoinStyle`, `CapStyle`). | + ## Particles | Tool | Probe Suite | Verified MAE | Usage (Active / Archive) | Notes & Fallbacks | @@ -112,6 +127,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | `pDrag` | Unit tests | Visual* | 0 / 2 | Velocity damping / aerodynamic drag force. | | `pKill` | Unit tests | Visual* | 0 / 1 | Region-based particle termination (`Inside`/`Outside`/`Entering`/`Leaving`). | | `pMerge` | Unit tests | Visual* | 0 / 0 | Combines multiple upstream particle emitter streams. | +| `pBounce` | Unit tests | Visual* | 0 / 10 | Region-based particle collision & elastic rebound (`Elasticity`, `Friction`, region planes/spheres/cubes). | ## 3D Pipeline @@ -123,6 +139,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | `Transform3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 1 / 799 | 3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node. | | `ImagePlane3D` | `cam3d` | 0.1%–0.4% | 4 / 496 | Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture. | | `Shape3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 4 / 374 | `Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry. | +| `Cube3D` | Unit tests | 0.1%–0.4% | 0 / 24 | Dedicated 3D cube geometry with per-face / standard material binding (`SurfaceCubeInputs.*`, `MaterialInput`). | +| `SurfaceFBXMesh` | Unit tests | Visual* | 0 / 216 | Binary/ASCII `.fbx` and `.obj` mesh loader (`ImportFile`, `ObjName`, `ScaleFileUnitsBy`, normals, UVs, material binding). | | `Text3D` | `archive_3d` | Visual* | 0 / 410 | 3D CoreText rasterized text plane with optional multi-slice `-Z` extrusion (`ExtrusionDepth`, `StyledText`, `Font`, `Style`, `Size`, color). | | `LightAmbient` | Suite comps | 0.1%–0.4% | 3 / 42 | Scene ambient RGB light intensity accumulation in `Renderer3D`. | | `LightDirectional` | Suite comps | 0.1%–0.4% | 3 / 82 | World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`. | @@ -132,6 +150,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | `MtlCookTorrance` | `archive_3d` | 0.1%–0.8% | 3 / 8 | Cook-Torrance 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Diffuse.Color.Material`, `Specular.Roughness/Color/Intensity`). | | `MtlPhong` | `archive_3d` | 0.1%–0.8% | 0 / 0 | Phong 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Specular.Color/Intensity/Exponent`). | | `Texture2DOperator` | `archive_3d` | 0.0%–0.4% | 0 / 44 | 2D-image-to-3D-material adapter feeding `MaterialInput` or `Diffuse.Color.Material`. | +| `TextureTransformOperator` | Unit tests | 0.0%–0.4% | 0 / 12 | 3D material UV translation, scale, rotation, and wrap-mode (`Wrap`/`Mirror`/`Clamp`) transform operator. | +| `BumpMap` | Unit tests | 0.1%–0.5% | 0 / 10 | 3D heightmap and tangent-space normal-map bump perturbation (`HeightScale`, `SourceImageType`) feeding `Bumpmap.Material`. | | `ReplaceMaterial3D` | `archive_3d` | 0.0%–0.4% | 0 / 131 | Subtree 3D material override (`SceneInput` + `MaterialInput`). | | `Override3D` | `archive_3d` | 0.0%–0.2% | 0 / 124 | Subtree 3D visibility (`Visibility.DoVisible`/`IsVisible`) and lighting (`Lighting.DoAffectedByLights`/`IsAffectedByLights`) override. | | `Duplicate3D` | `archive_3d` | 0.1%–0.5% | 0 / 74 | Cumulative 3D scene instancer (`FirstCopy..LastCopy`, `Transform3DOp`, seeded `JitterTranslate`/`JitterRotate`). | @@ -165,6 +185,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | `LUTBezier` | `tier1_a` | 18 / 945 | Curve lookup splines used standalone and nested inside `ColorCurves` / `HueCurves`. | | `PolyPath` / `Path` | Suite comps | 119 / 2389 | 2D motion-path polyline evaluation with animated `Displacement` spline. | | `Shake` | `tier1_c` | 0 / 165 | Procedural multi-octave noise modifier (`Source = X / Y / Value / Position`) with spline & expression inputs. | +| `Expression` | Unit tests | 0 / 23 | Standalone Fusion `Expression` modifier (`NumberExpression`, `PointExpressionX`/`Y`, `n1..n9`/`p1..p9` inputs, math DSL + Lua fallback). | | `StyledTextCLS` | Suite comps | 3 / 60 | Per-character `TextPlus` styling overrides (font, size, color, kerning, opacity). | | `TrackerModifier` | Suite comps | 3 / 0 | Resolves baked tracker path aliases (`Track1TrackerPath`, etc.) into 2D `PolyPath` coordinates. | | Lua Expressions | Suite comps | — | Inline `Expression = "..."` evaluation (`time`, `comp.RenderStart`/`End`, node input references, math/trig/clamp/ternary). | @@ -179,26 +200,26 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w | `MagicMask` | 3 / 1 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | | `PlanarTracker` | 0 / 0 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | | `Dimension.CopyAux` | 4 / 0 | — | Preserved lossless on save; passes through main image input. | -| `SurfaceFBXMesh` | 0 / 216 | — | Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`. | | `Multistroke` | 0 / 33 | — | Preserved lossless on save; passes through main input in Flow. | -| `Drip` | 0 / 29 | — | Preserved lossless on save; passes through main input in Flow. | | `PolylineStroke` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. | | `Paint` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. | | `Fuse.HexagonTiles` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. | -| `Cube3D` | 0 / 24 | — | Preserved lossless on save; passes through main input in Flow. | -| `Expression` | 0 / 23 | — | Preserved lossless on save; passes through main input in Flow. | | `AudioDisplay` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. | -| `sRender` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. | | `Fuse.AlphaWeightedNoise` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. | | `Fuse.Hexagon` | 0 / 17 | — | Preserved lossless on save; passes through main input in Flow. | | `DaySky` | 0 / 16 | — | Preserved lossless on save; passes through main input in Flow. | | `PaintMask` | 0 / 14 | — | Preserved lossless on save; passes through main input in Flow. | | `SurfaceAlembicMesh` | 0 / 13 | — | Preserved lossless on save; passes through main input in Flow. | -| `TextureTransformOperator` | 0 / 12 | — | Preserved lossless on save; passes through main input in Flow. | -| `pBounce` | 0 / 10 | — | Preserved lossless on save; passes through main input in Flow. | -| `BumpMap` | 0 / 10 | — | Preserved lossless on save; passes through main input in Flow. | -| `sNGon` | 0 / 9 | — | Preserved lossless on save; passes through main input in Flow. | -| `Dent` | 0 / 7 | — | Preserved lossless on save; passes through main input in Flow. | +| `PseudoColor` | 0 / 6 | — | Preserved lossless on save; passes through main input in Flow. | +| `Fuse.CheckerPieceGenerator` | 0 / 6 | — | Preserved lossless on save; passes through main input in Flow. | +| `GridWarp` | 0 / 5 | — | Preserved lossless on save; passes through main input in Flow. | +| `Fog` | 0 / 5 | — | Preserved lossless on save; passes through main input in Flow. | +| `Highlight` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. | +| `Fuse.Lightning` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. | +| `PerspectivePositioner` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. | +| `sGrid` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. | +| `DepthBlur` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. | +| `Replicate3D` | 0 / 4 | — | Preserved lossless on save; passes through main input in Flow. | --- diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index f96eeb036ab9dbb59dab5cdf000d0e78ed79e75e..ceaf72b0b38a3b3ea4e2156c290d413ba5d9f313 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -18,6 +18,7 @@ mod color; mod blur_glow; mod keyers; mod masks; +mod shapes_warp; mod text_3d; @@ -67,6 +68,7 @@ enum ShaderDomain { Transform, Masks, KeyersGen, + ArchiveFx, } impl ShaderDomain { @@ -78,6 +80,7 @@ impl ShaderDomain { Self::Transform => include_str!("../shaders/transform.wgsl"), Self::Masks => include_str!("../shaders/masks.wgsl"), Self::KeyersGen => include_str!("../shaders/keyers_gen.wgsl"), + Self::ArchiveFx => include_str!("../shaders/archive_fx.wgsl"), } } @@ -89,6 +92,7 @@ impl ShaderDomain { Self::Transform => "compositor-shaders-transform", Self::Masks => "compositor-shaders-masks", Self::KeyersGen => "compositor-shaders-keyers-gen", + Self::ArchiveFx => "compositor-shaders-archive-fx", } } } @@ -139,6 +143,8 @@ enum ShaderOp { ChangeDepth, Vortex, KScope, + Drip, + Dent, } impl ShaderOp { @@ -192,6 +198,8 @@ impl ShaderOp { | Self::CustomWave | Self::UltraKeyer | Self::Plasma => ShaderDomain::KeyersGen, + + Self::Drip | Self::Dent => ShaderDomain::ArchiveFx, } } @@ -240,6 +248,8 @@ impl ShaderOp { Self::ChangeDepth => "change_depth_op", Self::Vortex => "vortex_op", Self::KScope => "kscope_op", + Self::Drip => "drip_op", + Self::Dent => "dent_op", } } } @@ -1094,8 +1104,18 @@ impl Engine { "FilmGrain" => self.eval_film_grain(comp, node, time, frame_i, enc, visiting, stats), "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats), "Vortex" => self.eval_vortex(comp, node, time, frame_i, enc, visiting, stats), + "Drip" => self.eval_drip(comp, node, time, frame_i, enc, visiting, stats), + "Dent" => self.eval_dent(comp, node, time, frame_i, enc, visiting, stats), "Fuse.Duplicate" => self.eval_duplicate(comp, node, time, frame_i, enc, visiting, stats), "Fuse.KScope" => self.eval_kscope(comp, node, time, frame_i, enc, visiting, stats), + "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), + "sNGon" + | "sRectangle" + | "sEllipse" + | "sMerge" + | "sTransform" + | "sBoolean" + | "sOutline" => self.dummy.clone(), "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats), "RectangleMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 1, enc, visiting, stats), "PolylineMask" => self.eval_polyline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), @@ -1114,7 +1134,8 @@ impl Engine { | "pDrag" | "pFriction" | "pKill" - | "pMerge" => self.dummy.clone(), + | "pMerge" + | "pBounce" => self.dummy.clone(), "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "Renderer3D" => self.eval_renderer3d(comp, node, time, frame_i, comp_dims, enc, visiting, stats), other => { @@ -1350,7 +1371,7 @@ mod lazy_shader_verify { ShaderOp::Invert, ShaderOp::ChannelBoolean, ShaderOp::Filter, ShaderOp::HueCurves, ShaderOp::UltraKeyer, ShaderOp::Dissolve, ShaderOp::Homography, ShaderOp::ShadowComp, ShaderOp::Plasma, ShaderOp::FilmGrain, ShaderOp::SetDomain, ShaderOp::ChangeDepth, - ShaderOp::Vortex, ShaderOp::KScope, + ShaderOp::Vortex, ShaderOp::KScope, ShaderOp::Drip, ShaderOp::Dent, ]; // Verify starts completely empty (lazy!) assert_eq!(eng.pipelines.borrow().modules.len(), 0); @@ -1359,9 +1380,9 @@ mod lazy_shader_verify { eng.pipelines.borrow_mut().ensure_pipeline(&eng.device, op); eng.pipelines_for(BitDepth::Float16).borrow_mut().ensure_pipeline(&eng.device, op); } - assert_eq!(eng.pipelines.borrow().modules.len(), 6); - assert_eq!(eng.pipelines.borrow().pipelines.len(), 43); - assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().modules.len(), 6); - assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 43); + assert_eq!(eng.pipelines.borrow().modules.len(), 7); + assert_eq!(eng.pipelines.borrow().pipelines.len(), 45); + assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().modules.len(), 7); + assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 45); } } diff --git a/crates/engine/src/eval/shapes_warp.rs b/crates/engine/src/eval/shapes_warp.rs new file mode 100644 index 0000000000000000000000000000000000000000..0a2b8fd5c9ffaa097f89cd7dd61e427092c77393 --- /dev/null +++ b/crates/engine/src/eval/shapes_warp.rs @@ -0,0 +1,1057 @@ +//! GPU Archive FX Warps (`Drip`, `Dent`) and 2D Vector Shape Pipeline +//! (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sMerge`, `sTransform`, `sBoolean`, `sOutline`). + +use super::*; + +#[derive(Clone, Copy, Debug)] +struct Affine2D { + // [a, b, c, d, tx, ty] => x' = a*x + b*y + tx, y' = c*x + d*y + ty + m: [f32; 6], +} + +impl Affine2D { + fn identity() -> Self { + Self { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] } + } + + fn translate(tx: f32, ty: f32) -> Self { + Self { m: [1.0, 0.0, 0.0, 1.0, tx, ty] } + } + + fn scale(sx: f32, sy: f32) -> Self { + Self { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] } + } + + fn rotate_deg(deg: f32) -> Self { + let r = deg.to_radians(); + let (s, c) = r.sin_cos(); + Self { m: [c, -s, s, c, 0.0, 0.0] } + } + + fn mul(self, rhs: Self) -> Self { + let [a1, b1, c1, d1, tx1, ty1] = self.m; + let [a2, b2, c2, d2, tx2, ty2] = rhs.m; + Self { + m: [ + a1 * a2 + b1 * c2, + a1 * b2 + b1 * d2, + c1 * a2 + d1 * c2, + c1 * b2 + d1 * d2, + a1 * tx2 + b1 * ty2 + tx1, + c1 * tx2 + d1 * ty2 + ty1, + ], + } + } + + fn apply(self, p: [f32; 2]) -> [f32; 2] { + [ + self.m[0] * p[0] + self.m[1] * p[1] + self.m[4], + self.m[2] * p[0] + self.m[3] * p[1] + self.m[5], + ] + } + + fn avg_scale(self) -> f32 { + let sx = self.m[0].hypot(self.m[2]); + let sy = self.m[1].hypot(self.m[3]); + ((sx + sy) * 0.5).max(1e-4) + } + + fn hash_into(self, h: &mut DefaultHasher) { + for v in self.m { + v.to_bits().hash(h); + } + } +} + +#[derive(Clone, Copy, Debug)] +enum ShapePrimKind { + NGon { sides: u32, width: f32, height: f32 }, + Rectangle { width: f32, height: f32, corner_radius: f32 }, + Ellipse { width: f32, height: f32 }, +} + +#[derive(Clone, Copy, Debug)] +enum ShapeBoolOp { + Union, + Intersect, + Subtract, + Xor, +} + +#[derive(Clone, Debug)] +enum ShapeTree { + Primitive { + kind: ShapePrimKind, + xform: Affine2D, + color: [f32; 4], + solid: bool, + border_width: f32, + join_style: u8, + cap_style: u8, + }, + Group(Vec), + Boolean { + op: ShapeBoolOp, + a: Box, + b: Box, + }, +} + +impl ShapeTree { + fn hash_into(&self, h: &mut DefaultHasher) { + match self { + ShapeTree::Primitive { + kind, + xform, + color, + solid, + border_width, + join_style, + cap_style, + } => { + 0u8.hash(h); + match *kind { + ShapePrimKind::NGon { sides, width, height } => { + 1u8.hash(h); + sides.hash(h); + width.to_bits().hash(h); + height.to_bits().hash(h); + } + ShapePrimKind::Rectangle { width, height, corner_radius } => { + 2u8.hash(h); + width.to_bits().hash(h); + height.to_bits().hash(h); + corner_radius.to_bits().hash(h); + } + ShapePrimKind::Ellipse { width, height } => { + 3u8.hash(h); + width.to_bits().hash(h); + height.to_bits().hash(h); + } + } + xform.hash_into(h); + for c in color { + c.to_bits().hash(h); + } + solid.hash(h); + border_width.to_bits().hash(h); + join_style.hash(h); + cap_style.hash(h); + } + ShapeTree::Group(children) => { + 1u8.hash(h); + children.len().hash(h); + for ch in children { + ch.hash_into(h); + } + } + ShapeTree::Boolean { op, a, b } => { + 2u8.hash(h); + (*op as u8).hash(h); + a.hash_into(h); + b.hash_into(h); + } + } + } +} + +fn eval_first_num( + comp: &Comp, + node: &Node, + keys: &[&str], + time: f64, + default: f64, + expr: &ExprEngine, +) -> f64 { + for &k in keys { + if node.inputs.contains_key(k) { + return comp.eval_number(node, k, time, default, expr); + } + } + default +} + +fn parse_bool_op(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> ShapeBoolOp { + if let Some(s) = node.static_str("Operation") { + let low = s.to_ascii_lowercase(); + if low.contains("inter") { + return ShapeBoolOp::Intersect; + } + if low.contains("sub") || low.contains("diff") { + return ShapeBoolOp::Subtract; + } + if low.contains("xor") { + return ShapeBoolOp::Xor; + } + return ShapeBoolOp::Union; + } + match comp.eval_number(node, "Operation", time, 0.0, expr).round() as i32 { + 1 => ShapeBoolOp::Intersect, + 2 => ShapeBoolOp::Subtract, + 3 => ShapeBoolOp::Xor, + _ => ShapeBoolOp::Union, + } +} + +#[allow(clippy::too_many_arguments)] +fn collect_shape_tree( + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &ExprEngine, + parent_xform: Affine2D, + outline_override: Option<(f32, u8, u8)>, + depth: usize, +) -> Option { + if depth > 32 { + return None; + } + let node = comp.node(node_id); + if node.bypassed { + return node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s)) + .and_then(|id| { + collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) + }); + } + + match node.kind.as_str() { + "sNGon" | "sRectangle" | "sEllipse" => { + let tx = eval_first_num(comp, node, &["Translate.X", "XOffset"], time, 0.0, expr) as f32; + let ty = eval_first_num(comp, node, &["Translate.Y", "YOffset"], time, 0.0, expr) as f32; + let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32; + let local = Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)); + let xform = parent_xform.mul(local); + + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; + + let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5; + let mut border_width = comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32; + let mut join_style = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8; + let mut cap_style = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; + + if let Some((ov_w, ov_j, ov_c)) = outline_override { + solid = false; + border_width = ov_w; + join_style = ov_j; + cap_style = ov_c; + } + + let kind = match node.kind.as_str() { + "sNGon" => { + let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32; + let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; + let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; + ShapePrimKind::NGon { sides, width, height } + } + "sRectangle" => { + let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; + let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; + let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; + ShapePrimKind::Rectangle { width, height, corner_radius } + } + _ => { + let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; + let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; + ShapePrimKind::Ellipse { width, height } + } + }; + + Some(ShapeTree::Primitive { + kind, + xform, + color: [r, g, b, a], + solid, + border_width, + join_style, + cap_style, + }) + } + "sTransform" => { + let src_id = node.connected_node("Input").and_then(|s| comp.find_node(s))?; + let ox = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32; + let oy = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32; + let px = eval_first_num(comp, node, &["XPivot", "Pivot.X"], time, 0.0, expr) as f32; + let py = eval_first_num(comp, node, &["YPivot", "Pivot.Y"], time, 0.0, expr) as f32; + let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr); + let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; + let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; + let rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; + + let local = Affine2D::translate(ox + px, oy + py) + .mul(Affine2D::rotate_deg(rot)) + .mul(Affine2D::scale(sx, sy)) + .mul(Affine2D::translate(-px, -py)); + let combined = parent_xform.mul(local); + collect_shape_tree(comp, src_id, time, expr, combined, outline_override, depth + 1) + } + "sMerge" => { + let mut ports: Vec<(u32, &str)> = node + .inputs + .keys() + .filter_map(|k| { + let rest = k.strip_prefix("Input")?; + let idx: u32 = if rest.is_empty() { 0 } else { rest.parse().ok()? }; + Some((idx, k.as_str())) + }) + .collect(); + ports.sort_by_key(|&(idx, _)| idx); + let mut children = Vec::new(); + for (_, port) in ports { + if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { + if let Some(tree) = collect_shape_tree( + comp, + src_id, + time, + expr, + parent_xform, + outline_override, + depth + 1, + ) { + children.push(tree); + } + } + } + if children.is_empty() { + None + } else { + Some(ShapeTree::Group(children)) + } + } + "sOutline" => { + let src_id = node.connected_node("Input").and_then(|s| comp.find_node(s))?; + let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr).abs() as f32; + let join = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8; + let cap = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; + collect_shape_tree(comp, src_id, time, expr, parent_xform, Some((thickness, join, cap)), depth + 1) + } + "sBoolean" => { + let op = parse_bool_op(comp, node, time, expr); + let a = node + .connected_node("Input1") + .or_else(|| node.connected_node("Input")) + .and_then(|s| comp.find_node(s)) + .and_then(|id| { + collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) + }); + let b = node + .connected_node("Input2") + .and_then(|s| comp.find_node(s)) + .and_then(|id| { + collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) + }); + match (a, b) { + (Some(ta), Some(tb)) => Some(ShapeTree::Boolean { + op, + a: Box::new(ta), + b: Box::new(tb), + }), + (Some(ta), None) => match op { + ShapeBoolOp::Intersect => None, + _ => Some(ta), + }, + (None, Some(tb)) => match op { + ShapeBoolOp::Union | ShapeBoolOp::Xor => Some(tb), + _ => None, + }, + (None, None) => None, + } + } + "PipeRouter" | "Fuse.Wireless" => { + let src_id = node.connected_node("Input").and_then(|s| comp.find_node(s))?; + collect_shape_tree(comp, src_id, time, expr, parent_xform, outline_override, depth + 1) + } + "MacroOperator" | "GroupOperator" => { + let out_id = node.macro_output?; + collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1) + } + _ => None, + } +} + +fn build_primitive_commands(kind: ShapePrimKind, xform: Affine2D, dims: [u32; 2]) -> Vec { + let wf = dims[0] as f32; + let hf = dims[1] as f32; + let to_px = |local: [f32; 2]| -> zeno::Vector { + let wpt = xform.apply(local); + let px = (wpt[0] + 0.5) * wf; + let py = 0.5 * hf - wpt[1] * wf; + zeno::Vector::new(px, py) + }; + + const KAPPA: f32 = 0.55228475; + let mut cmds = Vec::new(); + match kind { + ShapePrimKind::NGon { sides, width, height } => { + let n = sides.max(3); + let rx = width * 0.5; + let ry = height * 0.5; + if rx <= 1e-6 || ry <= 1e-6 { + return cmds; + } + for k in 0..n { + let theta = std::f32::consts::FRAC_PI_2 + + (k as f32) * std::f32::consts::TAU / (n as f32); + let v = to_px([rx * theta.cos(), ry * theta.sin()]); + if k == 0 { + cmds.push(zeno::Command::MoveTo(v)); + } else { + cmds.push(zeno::Command::LineTo(v)); + } + } + cmds.push(zeno::Command::Close); + } + ShapePrimKind::Rectangle { width, height, corner_radius } => { + let hx = width * 0.5; + let hy = height * 0.5; + if hx <= 1e-6 || hy <= 1e-6 { + return cmds; + } + let r = corner_radius.min(hx.min(hy)); + if r <= 1e-5 { + cmds.push(zeno::Command::MoveTo(to_px([-hx, -hy]))); + cmds.push(zeno::Command::LineTo(to_px([hx, -hy]))); + cmds.push(zeno::Command::LineTo(to_px([hx, hy]))); + cmds.push(zeno::Command::LineTo(to_px([-hx, hy]))); + cmds.push(zeno::Command::Close); + } else { + let k = r * KAPPA; + cmds.push(zeno::Command::MoveTo(to_px([-hx + r, -hy]))); + cmds.push(zeno::Command::LineTo(to_px([hx - r, -hy]))); + cmds.push(zeno::Command::CurveTo( + to_px([hx - r + k, -hy]), + to_px([hx, -hy + r - k]), + to_px([hx, -hy + r]), + )); + cmds.push(zeno::Command::LineTo(to_px([hx, hy - r]))); + cmds.push(zeno::Command::CurveTo( + to_px([hx, hy - r + k]), + to_px([hx - r + k, hy]), + to_px([hx - r, hy]), + )); + cmds.push(zeno::Command::LineTo(to_px([-hx + r, hy]))); + cmds.push(zeno::Command::CurveTo( + to_px([-hx + r - k, hy]), + to_px([-hx, hy - r + k]), + to_px([-hx, hy - r]), + )); + cmds.push(zeno::Command::LineTo(to_px([-hx, -hy + r]))); + cmds.push(zeno::Command::CurveTo( + to_px([-hx, -hy + r - k]), + to_px([-hx + r - k, -hy]), + to_px([-hx + r, -hy]), + )); + cmds.push(zeno::Command::Close); + } + } + ShapePrimKind::Ellipse { width, height } => { + let rx = width * 0.5; + let ry = height * 0.5; + if rx <= 1e-6 || ry <= 1e-6 { + return cmds; + } + let kx = rx * KAPPA; + let ky = ry * KAPPA; + cmds.push(zeno::Command::MoveTo(to_px([rx, 0.0]))); + cmds.push(zeno::Command::CurveTo( + to_px([rx, ky]), + to_px([kx, ry]), + to_px([0.0, ry]), + )); + cmds.push(zeno::Command::CurveTo( + to_px([-kx, ry]), + to_px([-rx, ky]), + to_px([-rx, 0.0]), + )); + cmds.push(zeno::Command::CurveTo( + to_px([-rx, -ky]), + to_px([-kx, -ry]), + to_px([0.0, -ry]), + )); + cmds.push(zeno::Command::CurveTo( + to_px([kx, -ry]), + to_px([rx, -ky]), + to_px([rx, 0.0]), + )); + cmds.push(zeno::Command::Close); + } + } + cmds +} + +fn composite_over(dst: &mut [f32], src: &[f32]) { + for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) { + let sa = s[3].clamp(0.0, 1.0); + if sa <= 1e-6 { + continue; + } + let inv = 1.0 - sa; + d[0] = s[0] + d[0] * inv; + d[1] = s[1] + d[1] * inv; + d[2] = s[2] + d[2] * inv; + d[3] = sa + d[3] * inv; + } +} + +fn rasterize_shape_tree_f32( + tree: &ShapeTree, + dims: [u32; 2], + dst: &mut [f32], + cov_buf: &mut [u8], + scratch: &mut zeno::Scratch, +) { + let [w, h] = dims; + match tree { + ShapeTree::Primitive { + kind, + xform, + color, + solid, + border_width, + join_style, + cap_style, + } => { + let cmds = build_primitive_commands(*kind, *xform, dims); + if cmds.is_empty() { + return; + } + cov_buf.fill(0); + let style = if *solid { + zeno::Style::Fill(zeno::Fill::NonZero) + } else { + let stroke_px = (*border_width * xform.avg_scale() * (w as f32)).max(0.5); + let join = match *join_style { + 0 => zeno::Join::Bevel, + 1 => zeno::Join::Round, + _ => zeno::Join::Miter, + }; + let cap = match *cap_style { + 1 => zeno::Cap::Round, + 2 => zeno::Cap::Square, + _ => zeno::Cap::Butt, + }; + let mut st = zeno::Stroke::new(stroke_px); + st.join(join).cap(cap); + zeno::Style::Stroke(st) + }; + let _ = zeno::Mask::with_scratch(&cmds, scratch) + .style(style) + .size(w, h) + .origin(zeno::Origin::TopLeft) + .render_into(cov_buf, None); + + let ca = color[3].clamp(0.0, 1.0); + if ca <= 1e-6 { + return; + } + for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) { + if cov == 0 { + continue; + } + let sa = (cov as f32 / 255.0) * ca; + let inv = 1.0 - sa; + px[0] = color[0] * sa + px[0] * inv; + px[1] = color[1] * sa + px[1] * inv; + px[2] = color[2] * sa + px[2] * inv; + px[3] = sa + px[3] * inv; + } + } + ShapeTree::Group(children) => { + for ch in children { + rasterize_shape_tree_f32(ch, dims, dst, cov_buf, scratch); + } + } + ShapeTree::Boolean { op, a, b } => { + let len = dst.len(); + let mut buf_a = vec![0.0f32; len]; + let mut buf_b = vec![0.0f32; len]; + rasterize_shape_tree_f32(a, dims, &mut buf_a, cov_buf, scratch); + rasterize_shape_tree_f32(b, dims, &mut buf_b, cov_buf, scratch); + let mut comb = vec![0.0f32; len]; + for ((ca_p, cb_p), out_p) in buf_a + .chunks_exact(4) + .zip(buf_b.chunks_exact(4)) + .zip(comb.chunks_exact_mut(4)) + { + let aa = ca_p[3].clamp(0.0, 1.0); + let ba = cb_p[3].clamp(0.0, 1.0); + let unpre_a = if aa > 1e-5 { + [ca_p[0] / aa, ca_p[1] / aa, ca_p[2] / aa] + } else { + [0.0; 3] + }; + let unpre_b = if ba > 1e-5 { + [cb_p[0] / ba, cb_p[1] / ba, cb_p[2] / ba] + } else { + [0.0; 3] + }; + match op { + ShapeBoolOp::Union => { + let inv_b = 1.0 - ba; + out_p[0] = cb_p[0] + ca_p[0] * inv_b; + out_p[1] = cb_p[1] + ca_p[1] * inv_b; + out_p[2] = cb_p[2] + ca_p[2] * inv_b; + out_p[3] = (ba + aa * inv_b).clamp(0.0, 1.0); + } + ShapeBoolOp::Intersect => { + let oa = aa * ba; + out_p[0] = unpre_a[0] * oa; + out_p[1] = unpre_a[1] * oa; + out_p[2] = unpre_a[2] * oa; + out_p[3] = oa; + } + ShapeBoolOp::Subtract => { + let oa = aa * (1.0 - ba); + out_p[0] = unpre_a[0] * oa; + out_p[1] = unpre_a[1] * oa; + out_p[2] = unpre_a[2] * oa; + out_p[3] = oa; + } + ShapeBoolOp::Xor => { + let wa = aa * (1.0 - ba); + let wb = ba * (1.0 - aa); + let oa = (wa + wb).clamp(0.0, 1.0); + out_p[0] = unpre_a[0] * wa + unpre_b[0] * wb; + out_p[1] = unpre_a[1] * wa + unpre_b[1] * wb; + out_p[2] = unpre_a[2] * wa + unpre_b[2] * wb; + out_p[3] = oa; + } + } + } + composite_over(dst, &comb); + } + } +} + +fn rasterize_shape_tree_rgba8(tree: Option<&ShapeTree>, dims: [u32; 2], blend: f32) -> Vec { + let px_count = (dims[0] as usize) * (dims[1] as usize); + let mut out = vec![0u8; px_count * 4]; + let Some(tree) = tree else { + return out; + }; + let b = blend.clamp(0.0, 1.0); + if b <= 1e-6 { + return out; + } + let mut accum = vec![0.0f32; px_count * 4]; + let mut cov_buf = vec![0u8; px_count]; + let mut scratch = zeno::Scratch::new(); + rasterize_shape_tree_f32(tree, dims, &mut accum, &mut cov_buf, &mut scratch); + for (dst_px, src_px) in out.chunks_exact_mut(4).zip(accum.chunks_exact(4)) { + dst_px[0] = (src_px[0] * b * 255.0).round().clamp(0.0, 255.0) as u8; + dst_px[1] = (src_px[1] * b * 255.0).round().clamp(0.0, 255.0) as u8; + dst_px[2] = (src_px[2] * b * 255.0).round().clamp(0.0, 255.0) as u8; + dst_px[3] = (src_px[3] * b * 255.0).round().clamp(0.0, 255.0) as u8; + } + out +} + +impl Engine { + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_drip( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let strength = comp.eval_number(node, "Strength", time, 1.0, &self.expr) as f32; + let amp = comp.eval_number(node, "Amplitude", time, 0.1, &self.expr) as f32; + if blend <= 1e-6 || (strength * amp).abs() <= 1e-7 { + return src; + } + let src = self.crop_to_canvas(enc, src); + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let freq = comp.eval_number(node, "Frequency", time, 10.0, &self.expr) as f32; + let aspect = comp.eval_number(node, "Aspect", time, 1.0, &self.expr).max(1e-4) as f32; + let phase = comp.eval_number(node, "Phase", time, 0.0, &self.expr) as f32; + let dampening = comp.eval_number(node, "Dampening", time, 0.0, &self.expr).max(0.0) as f32; + let shape = comp.eval_number(node, "Shape", time, 0.0, &self.expr).round() as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, strength, amp]; + u.p[1] = [freq, aspect, phase, dampening]; + u.p[2] = [shape, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + + let key = self.make_key( + node, + "Drip", + src.size, + &[src.content_hash, mask_hash], + bytemuck::cast_slice(&u.p[..3]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Drip, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_dent( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + let strength = comp.eval_number(node, "Strength", time, 0.5, &self.expr) as f32; + if blend <= 1e-6 || strength.abs() <= 1e-6 { + return src; + } + let src = self.crop_to_canvas(enc, src); + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32; + let dent_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, strength]; + u.p[1] = [dent_type, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }]; + + let key = self.make_key( + node, + "Dent", + src.size, + &[src.content_hash, mask_hash], + bytemuck::cast_slice(&u.p[..2]), + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Dent, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn eval_s_render( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32; + let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32; + let dims = if w > 1 && h > 1 { self.scaled_dims(w, h) } else { comp_dims }; + let dst_depth = self.node_depth(comp, node, time, None); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + + let shape_tree = node + .connected_node("Input") + .and_then(|s| comp.find_node(s)) + .and_then(|src_id| { + collect_shape_tree(comp, src_id, time, &self.expr, Affine2D::identity(), None, 0) + }); + + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut h_key = DefaultHasher::new(); + self.cache.gpu_salt.hash(&mut h_key); + self.hiq.hash(&mut h_key); + self.cache.node_salt(node.id).hash(&mut h_key); + "sRender".hash(&mut h_key); + dims.hash(&mut h_key); + dst_depth.hash(&mut h_key); + blend.to_bits().hash(&mut h_key); + mask_hash.hash(&mut h_key); + mask_inv.hash(&mut h_key); + if let Some(ref tree) = shape_tree { + 1u8.hash(&mut h_key); + tree.hash_into(&mut h_key); + } else { + 0u8.hash(&mut h_key); + } + let key = h_key.finish(); + + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let rgba = rasterize_shape_tree_rgba8(shape_tree.as_ref(), dims, blend); + let needs_post = dst_depth != BitDepth::Int8 || mask.is_some(); + let base_tex = create_texture(&self.device, dims, if needs_post { 0 } else { key }); + self.queue.write_texture( + base_tex.texture.as_image_copy(), + &rgba, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(dims[0] * 4), + rows_per_image: Some(dims[1]), + }, + wgpu::Extent3d { + width: dims[0], + height: dims[1], + depth_or_array_layers: 1, + }, + ); + + let mut out = if dst_depth != BitDepth::Int8 { + let promoted = self.alloc_tex(dims, dst_depth, if mask.is_some() { 0 } else { key }); + let u = UniformParams::default(); + self.dispatch_op( + enc, + ShaderOp::ChangeDepth, + &base_tex.view, + &self.dummy.view, + &self.dummy.view, + &promoted, + &u, + ); + promoted + } else { + base_tex + }; + + if let Some(ref mtex) = mask { + let masked = self.alloc_tex(dims, out.depth, key); + let mut u = UniformParams::default(); + u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0]; + self.dispatch_op( + enc, + ShaderOp::MaskApply, + &out.view, + &self.dummy.view, + &mtex.view, + &masked, + &u, + ); + out = masked; + } + + self.cache.insert(key, out.clone(), node.id, frame_i); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Engine; + + #[test] + fn test_drip_concentric_ripple_displacement() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 0.0, }, + TopRightGreen = Input { Value = 0.0, }, + TopRightBlue = Input { Value = 1.0, }, + }, + }, + Drip1 = Drip { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + Center = Input { Value = { 0.5, 0.5 }, }, + Strength = Input { Value = 1.0, }, + Amplitude = Input { Value = 0.12, }, + Frequency = Input { Value = 4.0, }, + Phase = Input { Value = 0.0, }, + Shape = Input { Value = 0, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse Drip comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let bg_id = comp.find_node("BG1").unwrap(); + let drip_id = comp.find_node("Drip1").unwrap(); + let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0); + let (drip_tex, stats) = eng.evaluate(&comp, drip_id, 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg"); + let drip_px = eng.readback_rgba(&drip_tex).expect("readback drip"); + + let diff_sum: u64 = bg_px + .iter() + .zip(drip_px.iter()) + .map(|(&a, &b)| a.abs_diff(b) as u64) + .sum(); + assert!(diff_sum > 10_000, "Drip should visibly displace pixels, got diff_sum={diff_sum}"); + } + + #[test] + fn test_dent_radial_distortion() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 0.0, }, + TopRightGreen = Input { Value = 1.0, }, + TopRightBlue = Input { Value = 0.0, }, + }, + }, + Dent1 = Dent { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + Center = Input { Value = { 0.5, 0.5 }, }, + Size = Input { Value = 0.6, }, + Strength = Input { Value = 0.8, }, + Type = Input { Value = 0, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse Dent comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let bg_id = comp.find_node("BG1").unwrap(); + let dent_id = comp.find_node("Dent1").unwrap(); + let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0); + let (dent_tex, stats) = eng.evaluate(&comp, dent_id, 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg"); + let dent_px = eng.readback_rgba(&dent_tex).expect("readback dent"); + + // Corners outside radius=0.3 must remain unchanged; interior must be distorted! + assert_eq!(&bg_px[0..4], &dent_px[0..4], "corner pixel outside dent radius should match"); + let mut interior_diff = 0u64; + for y in 44..84 { + for x in 44..84 { + let idx = (y * 128 + x) * 4; + interior_diff += bg_px[idx].abs_diff(dent_px[idx]) as u64; + interior_diff += bg_px[idx + 1].abs_diff(dent_px[idx + 1]) as u64; + } + } + assert!(interior_diff > 2_000, "Dent interior should visibly distort, got {interior_diff}"); + } + + #[test] + fn test_s_render_ngon_transform_merge_and_boolean() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + NGon1 = sNGon { + Inputs = { + Sides = Input { Value = 6, }, + Width = Input { Value = 0.4, }, + Red = Input { Value = 1.0, }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 0.0, }, + }, + }, + XF1 = sTransform { + Inputs = { + XOffset = Input { Value = -0.2, }, + YOffset = Input { Value = 0.0, }, + XSize = Input { Value = 1.0, }, + YSize = Input { Value = 1.0, }, + ZRotation = Input { Value = 15.0, }, + Input = Input { SourceOp = "NGon1", Source = "Output", }, + }, + }, + Rect1 = sRectangle { + Inputs = { + Width = Input { Value = 0.3, }, + Height = Input { Value = 0.3, }, + CornerRadius = Input { Value = 0.05, }, + Translate = Input { Value = { 0.0, 0.0 }, }, + ["Translate.X"] = Input { Value = 0.2, }, + Red = Input { Value = 0.0, }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 1.0, }, + }, + }, + Merge1 = sMerge { + Inputs = { + Input1 = Input { SourceOp = "XF1", Source = "Output", }, + Input2 = Input { SourceOp = "Rect1", Source = "Output", }, + }, + }, + Render1 = sRender { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Input = Input { SourceOp = "Merge1", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse sRender comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let render_id = comp.find_node("Render1").unwrap(); + let (tex, stats) = eng.evaluate(&comp, render_id, 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + assert_eq!(tex.size, [128, 128]); + let px = eng.readback_rgba(&tex).expect("readback sRender"); + + // Left shape center (-0.2 -> x ~ 38, y ~ 64) should be solid red + let left = (64 * 128 + 38) * 4; + assert!(px[left] > 240 && px[left + 2] < 10 && px[left + 3] > 240, "left={:?}", &px[left..left + 4]); + // Right shape center (+0.2 -> x ~ 90, y ~ 64) should be solid blue + let right = (64 * 128 + 90) * 4; + assert!(px[right + 2] > 240 && px[right] < 10 && px[right + 3] > 240, "right={:?}", &px[right..right + 4]); + // Top-left corner (0, 0) should be transparent + assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner should be transparent"); + } +} diff --git a/crates/engine/src/shaders/archive_fx.wgsl b/crates/engine/src/shaders/archive_fx.wgsl new file mode 100644 index 0000000000000000000000000000000000000000..f91f82d1deeb48caec27793a3ed2e9cc71912c52 --- /dev/null +++ b/crates/engine/src/shaders/archive_fx.wgsl @@ -0,0 +1,116 @@ +// ============================================================================ +// Archive FX Warps: Drip (concentric ripple) & Dent (radial dent/bulge/pinch/punch) +// ============================================================================ + +// 1. Drip (concentric ripple warp) +// p[0] = (center.x, center.y, strength, amplitude) +// p[1] = (frequency, aspect, phase, dampening) +// p[2] = (shape: 0=Circle, 1=Square, 2=Horizontal, 3=Vertical, blend, has_mask, mask_invert) +@compute @workgroup_size(8, 8) +fn drip_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let canvas_aspect = f32(dims.x) / max(f32(dims.y), 1.0); + let fu = pix_to_fu(gid.xy, dims); + let orig = textureLoad(src_a, vec2(gid.xy), 0); + + let center = u.p[0].xy; + let strength = u.p[0].z; + let amp = u.p[0].w; + let freq = u.p[1].x; + let drip_aspect = max(u.p[1].y, 1e-4); + let phase = u.p[1].z; + let dampening = max(u.p[1].w, 0.0); + let shape = i32(u.p[2].x + 0.5); + let blend = u.p[2].y; + + let rel = vec2(fu.x - center.x, (fu.y - center.y) / (canvas_aspect * drip_aspect)); + var dist: f32 = 0.0; + var dir: vec2 = vec2(0.0); + + if (shape == 1) { + // Square ripples + dist = max(abs(rel.x), abs(rel.y)); + let rl = length(rel); + dir = select(vec2(0.0), rel / rl, rl > 1e-5); + } else if (shape == 2) { + // Horizontal wave bands + dist = abs(rel.y); + dir = vec2(0.0, select(-1.0, 1.0, rel.y >= 0.0)); + } else if (shape == 3) { + // Vertical wave bands + dist = abs(rel.x); + dir = vec2(select(-1.0, 1.0, rel.x >= 0.0), 0.0); + } else if (shape == 4) { + // Diamond / cross ripples + dist = abs(rel.x) + abs(rel.y); + let rl = length(rel); + dir = select(vec2(0.0), rel / rl, rl > 1e-5); + } else { + // Circle ripples (shape == 0 and default) + dist = length(rel); + dir = select(vec2(0.0), rel / dist, dist > 1e-5); + } + + let falloff = exp(-dist * dampening * 2.0); + let disp = sin(dist * freq * 6.28318530718 + phase) * amp * strength * falloff; + let src_fu = fu - dir * disp * vec2(1.0, canvas_aspect); + let warped = sample_edges(src_a, src_fu, 2); + + let m = read_mask(gid.xy, dims, u.p[2].z, u.p[2].w) * blend; + store_dst(vec2(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0))); +} + +// 2. Dent (radial dent / sine / pinch / punch warp) +// p[0] = (center.x, center.y, radius_norm, strength) +// p[1] = (type: 0=Dent, 1=Sine, 2=Pinch, 3=Punch, blend, has_mask, mask_invert) +@compute @workgroup_size(8, 8) +fn dent_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let aspect = f32(dims.x) / max(f32(dims.y), 1.0); + let fu = pix_to_fu(gid.xy, dims); + let orig = textureLoad(src_a, vec2(gid.xy), 0); + + let center = u.p[0].xy; + let radius = max(u.p[0].z, 1e-5); + let strength = u.p[0].w; + let dent_type = i32(u.p[1].x + 0.5); + let blend = u.p[1].y; + + let rel_w = (fu - center) * vec2(1.0, 1.0 / aspect); + let r = length(rel_w); + + var warped = orig; + if (r < radius && r > 1e-6 && abs(strength) > 1e-6) { + let t = clamp(r / radius, 0.0, 1.0); + var new_r = r; + if (dent_type == 0) { + // Dent: smooth quadratic bulge/indent + let w = (1.0 - t) * (1.0 - t); + new_r = r * max(0.0, 1.0 - strength * w); + } else if (dent_type == 1) { + // Sine: sinusoidal radial displacement + let w = sin(t * 3.14159265359); + new_r = r * max(0.0, 1.0 - strength * w); + } else if (dent_type == 2) { + // Pinch: power-law radial pinch/expand + let p = select(1.0 / max(1.0 - strength, 0.05), 1.0 + strength, strength >= 0.0); + new_r = radius * pow(t, p); + } else if (dent_type == 3) { + // Punch: spherical dome punch + let w = sqrt(max(0.0, 1.0 - t * t)); + new_r = r * max(0.0, 1.0 - strength * w); + } else { + // Extended Fusion Dent modes (4..5): smooth quartic falloff + let w = (1.0 - t * t) * (1.0 - t * t); + new_r = r * max(0.0, 1.0 - strength * w); + } + let scale = new_r / r; + let src_fu = center + rel_w * scale * vec2(1.0, aspect); + warped = sample_edges(src_a, src_fu, 2); + } + + let m = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w) * blend; + store_dst(vec2(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0))); +} diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index 5b366984d20deacb806a5598320da77400656f74..d093107a3cc5ed65ca1aa5e37b04f95ae45c2986 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -120,8 +120,19 @@ pub fn is_supported_tool(kind: &str) -> bool { | "FilmGrain" | "Displace" | "Vortex" + | "Drip" + | "Dent" | "Fuse.Duplicate" | "Fuse.KScope" + // 2D vector shape pipeline + | "sRender" + | "sNGon" + | "sRectangle" + | "sEllipse" + | "sMerge" + | "sTransform" + | "sBoolean" + | "sOutline" | "EllipseMask" | "RectangleMask" | "PolylineMask" @@ -136,6 +147,8 @@ pub fn is_supported_tool(kind: &str) -> bool { | "Dimension.OpticalFlow" | "OpticalFlow" | "Custom" + // Modifiers + | "Expression" // Particle system | "pRender" | "pEmitter" @@ -146,6 +159,7 @@ pub fn is_supported_tool(kind: &str) -> bool { | "pFriction" | "pKill" | "pMerge" + | "pBounce" // 3D tools | "Renderer3D" | "Merge3D" @@ -153,6 +167,8 @@ pub fn is_supported_tool(kind: &str) -> bool { | "Camera3D" | "ImagePlane3D" | "Shape3D" + | "Cube3D" + | "SurfaceFBXMesh" | "Text3D" | "LightAmbient" | "LightDirectional" @@ -162,6 +178,8 @@ pub fn is_supported_tool(kind: &str) -> bool { | "MtlCookTorrance" | "MtlPhong" | "Texture2DOperator" + | "TextureTransformOperator" + | "BumpMap" | "ReplaceMaterial3D" | "Override3D" | "Duplicate3D" @@ -585,20 +603,54 @@ impl Comp { } } - // Resolve Fusion instanced tools (e.g. `Instance_ColorGain1 = ColorGain { SourceOp = "ColorGain1" }`) - for (nid, master_name) in instanced_from { - if let Some(&mid) = node_by_name.get(&master_name) { - if mid != nid { - let master_inputs = nodes[mid.0].inputs.clone(); + // Resolve Fusion tool-level `SourceOp` instanced node inheritance + // (e.g. `Instance_ColorCorrector1_6 = ColorCorrector { SourceOp = "ColorCorrector1_6" }`), + // walking chains up to depth 8 (cycle-safe) while NEVER copying image/mask/scene wires. + if !instanced_from.is_empty() { + let parent_of: HashMap = instanced_from + .iter() + .filter_map(|(nid, master_name)| { + node_by_name + .get(master_name) + .copied() + .filter(|&mid| mid != *nid) + .map(|mid| (*nid, mid)) + }) + .collect(); + let orig_inputs: Vec> = + nodes.iter().map(|n| n.inputs.clone()).collect(); + + for &(nid, _) in &instanced_from { + let mut visited = HashSet::new(); + visited.insert(nid); + let mut cur = nid; + for _depth in 0..8 { + let Some(&pid) = parent_of.get(&cur) else { + break; + }; + if !visited.insert(pid) { + break; + } let inst_inputs = &mut nodes[nid.0].inputs; - for (k, mb) in master_inputs { - let empty = inst_inputs.get(&k).is_none_or(|b| { + for (inp_name, parent_binding) in &orig_inputs[pid.0] { + if is_non_inheritable_instance_port(inp_name, parent_binding, &node_by_name) + { + continue; + } + if parent_binding.value.is_none() + && parent_binding.source_op.is_none() + && parent_binding.expression.is_none() + { + continue; + } + let child_empty = inst_inputs.get(inp_name).is_none_or(|b| { b.value.is_none() && b.source_op.is_none() && b.expression.is_none() }); - if empty { - inst_inputs.insert(k, mb); + if child_empty { + inst_inputs.insert(inp_name.clone(), parent_binding.clone()); } } + cur = pid; } } } @@ -1807,6 +1859,14 @@ fn sync_node_inputs( if orig == *binding { continue; } + // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools. + if orig.value.is_none() + && orig.source_op.is_none() + && orig.expression.is_none() + && master_inputs.is_some_and(|m| m.get(port) == Some(binding)) + { + continue; + } let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None); if let Some(it) = in_tbl.get_table_mut(port) { if orig.source_op != binding.source_op { @@ -1968,6 +2028,45 @@ fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTabl } } +fn is_non_inheritable_instance_port( + name: &str, + binding: &InputBinding, + node_by_name: &HashMap, +) -> bool { + if matches!( + name, + "Input" + | "Background" + | "Foreground" + | "EffectMask" + | "MaterialInput" + | "GarbageMatte" + | "SolidMatte" + | "Mask" + | "TrackingMask" + | "RegionMask" + | "MatchReference" + | "MatchMask" + | "Image" + | "Image1" + | "Image2" + | "BlurImage" + | "DisplaceImage" + ) || name.starts_with("SceneInput") + || name.starts_with("MainInput") + { + return true; + } + // Never inherit flow-graph image/scene/material connections targeting another flow node; + // modifiers (`BezierSpline`, `PolyPath`, `Shake`, `Expression`, etc.) are not in `node_by_name`. + binding.value.is_none() + && binding.expression.is_none() + && binding + .source_op + .as_deref() + .is_some_and(|op| node_by_name.contains_key(op)) +} + pub fn default_main_input_port(kind: &str) -> &'static str { match kind { "Merge" => "Background", @@ -2887,4 +2986,105 @@ mod expression_modifier_tests { let ang = comp.eval_number(xf, "Angle", 0.0, 0.0, &expr); assert!((ang - 2.0).abs() < 1e-6, "got {ang}"); } + + #[test] + fn resolves_instanced_source_op_inheritance_chains_and_keeps_image_wires_isolated() { + let src = r#"Composition { + Tools = ordered() { + Loader1 = Loader {}, + Transform2 = Transform { + Inputs = { + Input = Input { SourceOp = "Loader1", Source = "Output", }, + }, + }, + Ellipse1 = EllipseMask {}, + ColorCorrector1_6Blend = BezierSpline { + KeyFrames = { + [0] = { 0.25, Flags = { Linear = true } }, + [10] = { 0.75, Flags = { Linear = true } }, + }, + }, + ColorCorrector1_6 = ColorCorrector { + Inputs = { + Blend = Input { SourceOp = "ColorCorrector1_6Blend", Source = "Value", }, + WheelTintAngle1 = Input { Value = -0.434283, }, + WheelHue1 = Input { Value = 0.2, }, + PreDividePostMultiply = Input { Value = 1, }, + Input = Input { SourceOp = "Loader1", Source = "Output", }, + EffectMask = Input { SourceOp = "Ellipse1", Source = "Mask", }, + }, + }, + Instance_ColorCorrector1_6 = ColorCorrector { + SourceOp = "ColorCorrector1_6", + Inputs = { + Input = Input { SourceOp = "Transform2", Source = "Output", }, + EffectMask = Input {}, + WheelTintAngle1 = Input {}, + WheelHue1 = Input { Value = 0.9, }, + }, + }, + Instance_Chained = ColorCorrector { + SourceOp = "Instance_ColorCorrector1_6", + Inputs = { + Input = Input { SourceOp = "Loader1", Source = "Output", }, + }, + }, + CycleA = Blur { + SourceOp = "CycleB", + Inputs = { + XBlurSize = Input { Value = 3.0, }, + }, + }, + CycleB = Blur { + SourceOp = "CycleA", + Inputs = { + YBlurSize = Input { Value = 7.0, }, + }, + }, + }, + }"#; + + let comp = Comp::from_fusion_str(src).expect("parse instanced comp"); + let expr = ExprEngine::new(); + + let inst = comp.node(comp.find_node("Instance_ColorCorrector1_6").unwrap()); + // Inherits WheelTintAngle1 (even through empty `Input {}` stub) and Blend spline from master! + let tint = comp.eval_number(inst, "WheelTintAngle1", 0.0, 0.0, &expr); + assert!((tint - (-0.434283)).abs() < 1e-6, "got {tint}"); + let blend_t5 = comp.eval_number(inst, "Blend", 5.0, 1.0, &expr); + assert!((blend_t5 - 0.5).abs() < 1e-6, "got {blend_t5}"); + let pdpm = comp.eval_number(inst, "PreDividePostMultiply", 0.0, 0.0, &expr); + assert!((pdpm - 1.0).abs() < 1e-6, "got {pdpm}"); + // Keeps its own explicit override (`WheelHue1 = 0.9`) and its own `Input` wire (`Transform2`)! + let hue = comp.eval_number(inst, "WheelHue1", 0.0, 0.0, &expr); + assert!((hue - 0.9).abs() < 1e-6, "got {hue}"); + assert_eq!(inst.connected_node("Input"), Some("Transform2")); + // NEVER inherits parent's `EffectMask` image/mask wire! + assert_eq!(inst.connected_node("EffectMask"), None); + + // Chained inheritance (`Instance_Chained -> Instance_ColorCorrector1_6 -> ColorCorrector1_6`): + // nearest ancestor wins (`WheelHue1 = 0.9`), grandparent fills remaining params (`WheelTintAngle1`, `Blend`). + let chained = comp.node(comp.find_node("Instance_Chained").unwrap()); + assert!((comp.eval_number(chained, "WheelHue1", 0.0, 0.0, &expr) - 0.9).abs() < 1e-6); + assert!((comp.eval_number(chained, "WheelTintAngle1", 0.0, 0.0, &expr) - (-0.434283)).abs() < 1e-6); + assert!((comp.eval_number(chained, "Blend", 10.0, 0.0, &expr) - 0.75).abs() < 1e-6); + assert_eq!(chained.connected_node("Input"), Some("Loader1")); + assert_eq!(chained.connected_node("EffectMask"), None); + + // Cycle safety (`CycleA <-> CycleB` terminates cleanly and cross-inherits missing params) + let cyc_a = comp.node(comp.find_node("CycleA").unwrap()); + let cyc_b = comp.node(comp.find_node("CycleB").unwrap()); + assert!((comp.eval_number(cyc_a, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6); + assert!((comp.eval_number(cyc_a, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6); + assert!((comp.eval_number(cyc_b, "XBlurSize", 0.0, 0.0, &expr) - 3.0).abs() < 1e-6); + assert!((comp.eval_number(cyc_b, "YBlurSize", 0.0, 0.0, &expr) - 7.0).abs() < 1e-6); + + // Roundtrip preserves SourceOp inheritance without duplicating master params + let saved = comp.to_fusion_string(); + let reloaded = Comp::from_fusion_str(&saved).expect("reload"); + let r_inst = reloaded.node(reloaded.find_node("Instance_ColorCorrector1_6").unwrap()); + assert!((reloaded.eval_number(r_inst, "WheelTintAngle1", 0.0, 0.0, &expr) - (-0.434283)).abs() < 1e-6); + assert!((reloaded.eval_number(r_inst, "Blend", 5.0, 1.0, &expr) - 0.5).abs() < 1e-6); + assert_eq!(r_inst.connected_node("EffectMask"), None); + } } diff --git a/scripts/gen_compatibility.py b/scripts/gen_compatibility.py index 55bff7a58366be03bbe300274237f7b0bff4b484..0df90307109680b19542b51bf954b98adae22c5b 100755 --- a/scripts/gen_compatibility.py +++ b/scripts/gen_compatibility.py @@ -45,6 +45,7 @@ CATEGORIES: Sequence[str] = ( "Blur, Sharpen & Glow", "Transform, Warp & Framing", "Masks", + "2D Vector Shapes", "Particles", "3D Pipeline", "Time, Routing & Utility", @@ -104,6 +105,8 @@ TOOL_METADATA: Sequence[ToolMeta] = ( ToolMeta("DVE", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`)."), ToolMeta("Displace", "Transform, Warp & Framing", "`displace`, `displace_wave`", "0.0%–0.1%", "`XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting)."), ToolMeta("Vortex", "Transform, Warp & Framing", "`vortex_cc`", "0.0%–0.4%", "Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`)."), + ToolMeta("Drip", "Transform, Warp & Framing", "Unit tests", "0.0%", "Concentric ripple warp (`Center`, `Strength`, `Amplitude`, `Frequency`, `Aspect`, `Phase`, `Dampening`, `Shape`, `Blend`, `EffectMask`)."), + ToolMeta("Dent", "Transform, Warp & Framing", "Unit tests", "0.0%", "Radial distortion warp (`Center`, `Strength`, `Size`, `Type`: `Dent`/`Sine`/`Pinch`/`Punch`, `Blend`, `EffectMask`)."), ToolMeta("Fuse.Duplicate", "Transform, Warp & Framing", "`archive_3d`", "0.0%–0.4%", "Multi-copy iterative 2D transform composite (`Copies`, `Center`, `Size`, `Angle`, `Gain`, `Blend`, `TimeOffset`, `MergeUnder`)."), ToolMeta("Fuse.KScope", "Transform, Warp & Framing", "Unit tests", "0.0%", "N-slice radial kaleidoscope mirror (`Slices`, `Center`, `Angle`, `CaptureAngle`, `Scale`, `Edges`)."), ToolMeta("Scale", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Proportional/non-proportional image scaling with resampling filter."), @@ -118,6 +121,16 @@ TOOL_METADATA: Sequence[ToolMeta] = ( ToolMeta("BitmapMask", "Masks", "`mask_softedge`", "0.0%–0.2%", "GPU image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`/`Saturation`/`Lightness`/`Hue`), `Low`/`High` clip, centered 1:1 alignment, `SoftEdge`, `Invert`, `Level`, `PaintMode`."), ToolMeta("WandMask", "Masks", "`archive_3d`", "0.0%–0.3%", "Seeded BFS flood-fill wand mask (`Source`, `SelectionPoint`, `SelectionRange`, `ColorSpace`, `SoftEdge`, `Invert`, `Level`, `PaintMode`)."), + # 2D Vector Shapes + ToolMeta("sRender", "2D Vector Shapes", "Unit tests", "0.0%", "Antialiased `zeno` 2D vector shape tree rasterizer (`Width`, `Height`, `Blend`, `EffectMask`, cached RGBA upload & `HiQ` depth promotion)."), + ToolMeta("sNGon", "2D Vector Shapes", "Unit tests", "0.0%", "Regular N-sided polygon vector shape (`Sides`, `Width`, `Height`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, `JoinStyle`, RGBA color)."), + ToolMeta("sRectangle", "2D Vector Shapes", "Unit tests", "0.0%", "Vector rectangle & rounded rectangle (`Width`, `Height`, `CornerRadius`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, RGBA color)."), + ToolMeta("sEllipse", "2D Vector Shapes", "Unit tests", "0.0%", "Cubic Bezier vector ellipse (`Width`, `Height`, `Translate.X/Y`, `Angle`, `Solid`, `BorderWidth`, RGBA color)."), + ToolMeta("sMerge", "2D Vector Shapes", "Unit tests", "0.0%", "Composites multiple upstream vector shape inputs (`Input1`..`InputN`) in painter's order."), + ToolMeta("sTransform", "2D Vector Shapes", "Unit tests", "0.0%", "2D affine shape transform (`XOffset`/`YOffset`, `XSize`/`YSize`, `Scale`, `ZRotation`, `XPivot`/`YPivot`)."), + ToolMeta("sBoolean", "2D Vector Shapes", "Unit tests", "0.0%", "Shape boolean combiner (`Union`, `Intersect`, `Subtract`, `Xor`) over `Input1` and `Input2`."), + ToolMeta("sOutline", "2D Vector Shapes", "Unit tests", "0.0%", "Converts upstream vector shapes into stroked outlines (`Thickness`/`BorderWidth`, `JoinStyle`, `CapStyle`)."), + # Particles ToolMeta("pRender", "Particles", "Unit tests", "Visual*", "2D deterministic particle rasterizer (`ParticleStyleBitmap` rotated bilinear sprites, `ParticleStylePoint`/`Blob`, cached frame stepping). *Stochastic seed."), ToolMeta("pEmitter", "Particles", "Unit tests", "Visual*", "Seeded particle emitter (`RectRgn`/`SphereRgn`/`CubeRgn`/`LineRgn`/`Point`, `Number`, `Lifespan`, `Velocity`, `RotationZ`, `SpinZ`, `ColorVariance`, `SizeOverLife`, `FadeIn`/`FadeOut`)."), @@ -127,6 +140,7 @@ TOOL_METADATA: Sequence[ToolMeta] = ( ToolMeta("pDrag", "Particles", "Unit tests", "Visual*", "Velocity damping / aerodynamic drag force.", aliases=("pFriction",)), ToolMeta("pKill", "Particles", "Unit tests", "Visual*", "Region-based particle termination (`Inside`/`Outside`/`Entering`/`Leaving`)."), ToolMeta("pMerge", "Particles", "Unit tests", "Visual*", "Combines multiple upstream particle emitter streams."), + ToolMeta("pBounce", "Particles", "Unit tests", "Visual*", "Region-based particle collision & elastic rebound (`Elasticity`, `Friction`, region planes/spheres/cubes)."), # 3D Pipeline ToolMeta("Renderer3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "GPU wgpu 3D rasterizer with depth buffer, perspective camera selection, lighting, and 2D texture sampling."), @@ -135,6 +149,8 @@ TOOL_METADATA: Sequence[ToolMeta] = ( ToolMeta("Transform3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node."), ToolMeta("ImagePlane3D", "3D Pipeline", "`cam3d`", "0.1%–0.4%", "Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture."), ToolMeta("Shape3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "`Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry."), + ToolMeta("Cube3D", "3D Pipeline", "Unit tests", "0.1%–0.4%", "Dedicated 3D cube geometry with per-face / standard material binding (`SurfaceCubeInputs.*`, `MaterialInput`)."), + ToolMeta("SurfaceFBXMesh", "3D Pipeline", "Unit tests", "Visual*", "Binary/ASCII `.fbx` and `.obj` mesh loader (`ImportFile`, `ObjName`, `ScaleFileUnitsBy`, normals, UVs, material binding)."), ToolMeta("Text3D", "3D Pipeline", "`archive_3d`", "Visual*", "3D CoreText rasterized text plane with optional multi-slice `-Z` extrusion (`ExtrusionDepth`, `StyledText`, `Font`, `Style`, `Size`, color)."), ToolMeta("LightAmbient", "3D Pipeline", "Suite comps", "0.1%–0.4%", "Scene ambient RGB light intensity accumulation in `Renderer3D`."), ToolMeta("LightDirectional", "3D Pipeline", "Suite comps", "0.1%–0.4%", "World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`."), @@ -144,6 +160,8 @@ TOOL_METADATA: Sequence[ToolMeta] = ( ToolMeta("MtlCookTorrance", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Cook-Torrance 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Diffuse.Color.Material`, `Specular.Roughness/Color/Intensity`)."), ToolMeta("MtlPhong", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Phong 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Specular.Color/Intensity/Exponent`)."), ToolMeta("Texture2DOperator", "3D Pipeline", "`archive_3d`", "0.0%–0.4%", "2D-image-to-3D-material adapter feeding `MaterialInput` or `Diffuse.Color.Material`."), + ToolMeta("TextureTransformOperator", "3D Pipeline", "Unit tests", "0.0%–0.4%", "3D material UV translation, scale, rotation, and wrap-mode (`Wrap`/`Mirror`/`Clamp`) transform operator."), + ToolMeta("BumpMap", "3D Pipeline", "Unit tests", "0.1%–0.5%", "3D heightmap and tangent-space normal-map bump perturbation (`HeightScale`, `SourceImageType`) feeding `Bumpmap.Material`."), ToolMeta("ReplaceMaterial3D", "3D Pipeline", "`archive_3d`", "0.0%–0.4%", "Subtree 3D material override (`SceneInput` + `MaterialInput`)."), ToolMeta("Override3D", "3D Pipeline", "`archive_3d`", "0.0%–0.2%", "Subtree 3D visibility (`Visibility.DoVisible`/`IsVisible`) and lighting (`Lighting.DoAffectedByLights`/`IsAffectedByLights`) override."), ToolMeta("Duplicate3D", "3D Pipeline", "`archive_3d`", "0.1%–0.5%", "Cumulative 3D scene instancer (`FirstCopy..LastCopy`, `Transform3DOp`, seeded `JitterTranslate`/`JitterRotate`)."), @@ -181,6 +199,7 @@ MODIFIER_METADATA: Sequence[ModifierMeta] = ( ModifierMeta("`LUTBezier`", ("LUTBezier",), "`tier1_a`", "Curve lookup splines used standalone and nested inside `ColorCurves` / `HueCurves`."), ModifierMeta("`PolyPath` / `Path`", ("PolyPath", "Path"), "Suite comps", "2D motion-path polyline evaluation with animated `Displacement` spline."), ModifierMeta("`Shake`", ("Shake",), "`tier1_c`", "Procedural multi-octave noise modifier (`Source = X / Y / Value / Position`) with spline & expression inputs."), + ModifierMeta("`Expression`", ("Expression",), "Unit tests", "Standalone Fusion `Expression` modifier (`NumberExpression`, `PointExpressionX`/`Y`, `n1..n9`/`p1..p9` inputs, math DSL + Lua fallback)."), ModifierMeta("`StyledTextCLS`", ("StyledTextCLS", "CharacterLevelStyling"), "Suite comps", "Per-character `TextPlus` styling overrides (font, size, color, kerning, opacity)."), ModifierMeta("`TrackerModifier`", ("TrackerModifier",), "Suite comps", "Resolves baked tracker path aliases (`Track1TrackerPath`, etc.) into 2D `PolyPath` coordinates."), ModifierMeta("Lua Expressions", (), "Suite comps", "Inline `Expression = \"...\"` evaluation (`time`, `comp.RenderStart`/`End`, node input references, math/trig/clamp/ternary)."), @@ -200,7 +219,6 @@ UNSUPPORTED_NOTES: Sequence[UnsupportedMeta] = ( UnsupportedMeta("MagicMask", "Preserved lossless on save; passes through main image input in Flow.", 7), UnsupportedMeta("PlanarTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), UnsupportedMeta("Dimension.CopyAux", "Preserved lossless on save; passes through main image input.", None), - UnsupportedMeta("SurfaceFBXMesh", "Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`.", None), ) -- 2.54.1