authoravatarclover caruso<git@paperclover.net>2026-11-30 12:46:02-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 14:11:43-08:00
log76fc78f911b8eff80bf8ebe824e6d289ad9e8335
treeaa288ac14822cca3f81da87ca2260ba09a967dd1
parent809227098392cd1e8e4c38a6ae01bb5a0cbdf628
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

RAM/VRAM/proxy caches (#13), 3D & archive tool depth (#11), and Studio Inspector/Add Tool/Flow authoring (#14)


20 files changed, 5782 insertions(+), 278 deletions(-)

compatibility.md+32-17
...@@ -9,10 +9,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en...@@ -9,10 +9,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
99
10| Metric | Value |10| Metric | Value |
11| --- | --- |11| --- | --- |
12| **Supported Flow Tools** | **80** (71 2D/Fuse/utility in `eval.rs`, 7 3D scene nodes in `scene3d.rs`, 2 Flow annotations) |12| **Supported Flow Tools** | **95** (74 2D/Fuse/utility in `eval.rs`, 19 3D scene nodes in `scene3d.rs`, 2 Flow annotations) |
13| **Modifiers & Animation** | **7** systems (8 Fusion modifier classes + Lua expressions) |13| **Modifiers & Animation** | **7** systems (8 Fusion modifier classes + Lua expressions) |
14| **Active Corpus (`trees/fusion`) Coverage** | **99.4%** (1,981 / 1,993 nodes across 16 `.comp` files) |14| **Active Corpus (`trees/fusion`) Coverage** | **99.5%** (1,984 / 1,993 nodes across 16 `.comp` files) |
15| **Archive Corpus (`private/samples`) Coverage** | **96.1%** (52,826 / 54,955 nodes across 324 `.comp` files) |15| **Archive Corpus (`private/samples`) Coverage** | **98.7%** (54,258 / 54,955 nodes across 324 `.comp` files) |
16| **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. |16| **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. |
1717
18## Generators18## Generators
...@@ -83,6 +83,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en...@@ -83,6 +83,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
83| `DVE` | `tier1_b` | 0.1%–0.4% | 4 / 22 | 2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`). |83| `DVE` | `tier1_b` | 0.1%–0.4% | 4 / 22 | 2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`). |
84| `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). |84| `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). |
85| `Vortex` | `vortex_cc` | 0.0%–0.4% | 1 / 1 | Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`). |85| `Vortex` | `vortex_cc` | 0.0%–0.4% | 1 / 1 | Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`). |
86| `Fuse.Duplicate` | `archive_3d` | 0.0%–0.4% | 0 / 46 | Multi-copy iterative 2D transform composite (`Copies`, `Center`, `Size`, `Angle`, `Gain`, `Blend`, `TimeOffset`, `MergeUnder`). |
87| `Fuse.KScope` | Unit tests | 0.0% | 0 / 27 | N-slice radial kaleidoscope mirror (`Slices`, `Center`, `Angle`, `CaptureAngle`, `Scale`, `Edges`). |
86| `Scale` | Suite comps | 0.0%–0.2% | 12 / 98 | Proportional/non-proportional image scaling with resampling filter. |88| `Scale` | Suite comps | 0.0%–0.2% | 12 / 98 | Proportional/non-proportional image scaling with resampling filter. |
87| `BetterResize` | Suite comps | 0.0%–0.2% | 0 / 93 | Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`). |89| `BetterResize` | Suite comps | 0.0%–0.2% | 0 / 93 | Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`). |
88| `Crop` | Suite comps | 0.0%–0.1% | 3 / 168 | Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`). |90| `Crop` | Suite comps | 0.0%–0.1% | 3 / 168 | Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`). |
...@@ -96,6 +98,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en...@@ -96,6 +98,7 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
96| `RectangleMask` | `mask`, `mask_softedge` | 0.0%–0.2% | 53 / 885 | Center, Width, Height, `CornerRadius`, Angle, progressive-pyramid `SoftEdge`, `BorderWidth`, `Solid`, `Filter`, `ClippingMode`, `Invert`, `PaintMode` chaining. |98| `RectangleMask` | `mask`, `mask_softedge` | 0.0%–0.2% | 53 / 885 | Center, Width, Height, `CornerRadius`, Angle, progressive-pyramid `SoftEdge`, `BorderWidth`, `Solid`, `Filter`, `ClippingMode`, `Invert`, `PaintMode` chaining. |
97| `PolylineMask` | `mask_softedge`, Suite comps | 0.1%–0.4% | 16 / 505 | CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, progressive-pyramid `SoftEdge`, `ClippingMode`, `Invert`, `PaintMode`. |99| `PolylineMask` | `mask_softedge`, Suite comps | 0.1%–0.4% | 16 / 505 | CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, progressive-pyramid `SoftEdge`, `ClippingMode`, `Invert`, `PaintMode`. |
98| `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`. |100| `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`. |
101| `WandMask` | `archive_3d` | 0.0%–0.3% | 0 / 150 | Seeded BFS flood-fill wand mask (`Source`, `SelectionPoint`, `SelectionRange`, `ColorSpace`, `SoftEdge`, `Invert`, `Level`, `PaintMode`). |
99102
100## Particles103## Particles
101104
...@@ -120,8 +123,20 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en...@@ -120,8 +123,20 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en
120| `Transform3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 1 / 799 | 3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node. |123| `Transform3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 1 / 799 | 3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node. |
121| `ImagePlane3D` | `cam3d` | 0.1%–0.4% | 4 / 496 | Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture. |124| `ImagePlane3D` | `cam3d` | 0.1%–0.4% | 4 / 496 | Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture. |
122| `Shape3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 4 / 374 | `Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry. |125| `Shape3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 4 / 374 | `Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry. |
126| `Text3D` | `archive_3d` | Visual* | 0 / 410 | 3D CoreText rasterized text plane with optional multi-slice `-Z` extrusion (`ExtrusionDepth`, `StyledText`, `Font`, `Style`, `Size`, color). |
123| `LightAmbient` | Suite comps | 0.1%–0.4% | 3 / 42 | Scene ambient RGB light intensity accumulation in `Renderer3D`. |127| `LightAmbient` | Suite comps | 0.1%–0.4% | 3 / 42 | Scene ambient RGB light intensity accumulation in `Renderer3D`. |
124| `LightDirectional` | Suite comps | 0.1%–0.4% | 3 / 82 | World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`. |128| `LightDirectional` | Suite comps | 0.1%–0.4% | 3 / 82 | World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`. |
129| `LightPoint` | `archive_3d` | 0.1%–0.8% | 0 / 63 | Positional point light with RGB color, `Intensity`, `DecayType` (`None`/`Linear`/`Quadratic`), and `DecayRate`. |
130| `LightSpot` | `archive_3d` | 0.1%–0.8% | 0 / 52 | Directional spotlight with `ConeAngle`, `PenumbraAngle`, `Intensity`, RGB color, and `DecayType`. |
131| `MtlBlinn` | `archive_3d` | 0.1%–0.8% | 0 / 181 | Blinn-Phong 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Diffuse.Color.Material`, `Specular.Color/Intensity/Exponent`). |
132| `MtlCookTorrance` | `archive_3d` | 0.1%–0.8% | 3 / 8 | Cook-Torrance 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Diffuse.Color.Material`, `Specular.Roughness/Color/Intensity`). |
133| `MtlPhong` | `archive_3d` | 0.1%–0.8% | 0 / 0 | Phong 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Specular.Color/Intensity/Exponent`). |
134| `Texture2DOperator` | `archive_3d` | 0.0%–0.4% | 0 / 44 | 2D-image-to-3D-material adapter feeding `MaterialInput` or `Diffuse.Color.Material`. |
135| `ReplaceMaterial3D` | `archive_3d` | 0.0%–0.4% | 0 / 131 | Subtree 3D material override (`SceneInput` + `MaterialInput`). |
136| `Override3D` | `archive_3d` | 0.0%–0.2% | 0 / 124 | Subtree 3D visibility (`Visibility.DoVisible`/`IsVisible`) and lighting (`Lighting.DoAffectedByLights`/`IsAffectedByLights`) override. |
137| `Duplicate3D` | `archive_3d` | 0.1%–0.5% | 0 / 74 | Cumulative 3D scene instancer (`FirstCopy..LastCopy`, `Transform3DOp`, seeded `JitterTranslate`/`JitterRotate`). |
138| `ReplaceNormals3D` | `archive_3d` | 0.0%–0.4% | 0 / 27 | Subtree normal orientation override (`FlipNormals`). |
139| `Displace3D` | `archive_3d` | 0.2%–1.5% | 0 / 95 | Heightmap vertex displacement along mesh normals (`Input`, `Scale`, `Bias`, `Channel`) with smooth normal recomputation. |
125140
126## Time, Routing & Utility141## Time, Routing & Utility
127142
...@@ -165,25 +180,25 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w...@@ -165,25 +180,25 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w
165| `PlanarTracker` | 0 / 0 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. |180| `PlanarTracker` | 0 / 0 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. |
166| `Dimension.CopyAux` | 4 / 0 | — | Preserved lossless on save; passes through main image input. |181| `Dimension.CopyAux` | 4 / 0 | — | Preserved lossless on save; passes through main image input. |
167| `SurfaceFBXMesh` | 0 / 216 | — | Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`. |182| `SurfaceFBXMesh` | 0 / 216 | — | Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`. |
168| `Text3D` | 0 / 410 | — | Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`. |
169| `MtlBlinn` | 0 / 181 | — | Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending). |
170| `MtlCookTorrance` | 3 / 8 | — | Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Cook-Torrance BRDF pending). |
171| `WandMask` | 0 / 150 | — | Preserved lossless on save; flood-fill wand mask not yet implemented. |
172| `ReplaceMaterial3D` | 0 / 131 | — | Preserved lossless on save; 3D material override not yet traversed in `Renderer3D`. |
173| `Override3D` | 0 / 124 | — | Preserved lossless on save; 3D render-flag override not yet traversed in `Renderer3D`. |
174| `Displace3D` | 0 / 95 | — | Preserved lossless on save; vertex displacement not yet implemented in `Renderer3D`. |
175| `Duplicate3D` | 0 / 74 | — | Preserved lossless on save; passes through main input in Flow. |
176| `LightPoint` | 0 / 63 | — | Preserved lossless on save; passes through main input in Flow. |
177| `LightSpot` | 0 / 52 | — | Preserved lossless on save; passes through main input in Flow. |
178| `Fuse.Duplicate` | 0 / 46 | — | Preserved lossless on save; passes through main input in Flow. |
179| `Texture2DOperator` | 0 / 44 | — | Preserved lossless on save; passes through main input in Flow. |
180| `Multistroke` | 0 / 33 | — | Preserved lossless on save; passes through main input in Flow. |183| `Multistroke` | 0 / 33 | — | Preserved lossless on save; passes through main input in Flow. |
181| `Drip` | 0 / 29 | — | Preserved lossless on save; passes through main input in Flow. |184| `Drip` | 0 / 29 | — | Preserved lossless on save; passes through main input in Flow. |
182| `PolylineStroke` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. |185| `PolylineStroke` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. |
183| `Fuse.KScope` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. |
184| `ReplaceNormals3D` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. |
185| `Paint` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. |186| `Paint` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. |
186| `Fuse.HexagonTiles` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. |187| `Fuse.HexagonTiles` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. |
188| `Cube3D` | 0 / 24 | — | Preserved lossless on save; passes through main input in Flow. |
189| `Expression` | 0 / 23 | — | Preserved lossless on save; passes through main input in Flow. |
190| `AudioDisplay` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. |
191| `sRender` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. |
192| `Fuse.AlphaWeightedNoise` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. |
193| `Fuse.Hexagon` | 0 / 17 | — | Preserved lossless on save; passes through main input in Flow. |
194| `DaySky` | 0 / 16 | — | Preserved lossless on save; passes through main input in Flow. |
195| `PaintMask` | 0 / 14 | — | Preserved lossless on save; passes through main input in Flow. |
196| `SurfaceAlembicMesh` | 0 / 13 | — | Preserved lossless on save; passes through main input in Flow. |
197| `TextureTransformOperator` | 0 / 12 | — | Preserved lossless on save; passes through main input in Flow. |
198| `pBounce` | 0 / 10 | — | Preserved lossless on save; passes through main input in Flow. |
199| `BumpMap` | 0 / 10 | — | Preserved lossless on save; passes through main input in Flow. |
200| `sNGon` | 0 / 9 | — | Preserved lossless on save; passes through main input in Flow. |
201| `Dent` | 0 / 7 | — | Preserved lossless on save; passes through main input in Flow. |
187202
188---203---
189204
crates/engine/src/bin/render_check.rs+15-1
...@@ -366,6 +366,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -366,6 +366,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
366 let mut ref_path: Option<PathBuf> = None;366 let mut ref_path: Option<PathBuf> = None;
367 let mut node_name: Option<String> = None;367 let mut node_name: Option<String> = None;
368 let mut proxy_scale: u32 = 1;368 let mut proxy_scale: u32 = 1;
369 let mut use_proxy_clips = false;
370 let mut vram_budget_mb: Option<u64> = None;
369 let mut hiq = true;371 let mut hiq = true;
370 let mut bench = false;372 let mut bench = false;
371 let mut i = 3;373 let mut i = 3;
...@@ -387,6 +389,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -387,6 +389,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
387 proxy_scale = args[i + 1].parse().unwrap_or(1).max(1);389 proxy_scale = args[i + 1].parse().unwrap_or(1).max(1);
388 i += 2;390 i += 2;
389 }391 }
392 "--proxy-clips" => {
393 use_proxy_clips = true;
394 i += 1;
395 }
396 "--vram-mb" if i + 1 < args.len() => {
397 vram_budget_mb = args[i + 1].parse().ok();
398 i += 2;
399 }
390 "--fast" => {400 "--fast" => {
391 hiq = false;401 hiq = false;
392 i += 1;402 i += 1;
...@@ -396,7 +406,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -396,7 +406,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
396 i += 1;406 i += 1;
397 }407 }
398 other => {408 other => {
399 eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --fast, --bench)");409 eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --proxy-clips, --vram-mb, --fast, --bench)");
400 std::process::exit(2);410 std::process::exit(2);
401 }411 }
402 }412 }
...@@ -421,6 +431,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {...@@ -421,6 +431,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
421431
422 let mut engine = Engine::new_headless()?;432 let mut engine = Engine::new_headless()?;
423 engine.proxy_scale = proxy_scale;433 engine.proxy_scale = proxy_scale;
434 engine.use_proxy_clips = use_proxy_clips;
435 if let Some(mb) = vram_budget_mb {
436 engine.set_vram_budget_mb(mb);
437 }
424 engine.hiq = hiq;438 engine.hiq = hiq;
425439
426 let (tex, cold) = engine.evaluate(&comp, target, frame);440 let (tex, cold) = engine.evaluate(&comp, target, frame);
crates/engine/src/cache.rs+21-2
...@@ -111,12 +111,16 @@ struct Entry {...@@ -111,12 +111,16 @@ struct Entry {
111 frames: HashSet<i64>,111 frames: HashSet<i64>,
112}112}
113113
114/// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB).
115pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768;
116
114pub struct NodeCache {117pub struct NodeCache {
115 pub mode: CacheMode,118 pub mode: CacheMode,
116 pub budget_bytes: u64,119 pub budget_bytes: u64,
117 entries: HashMap<u64, Entry>,120 entries: HashMap<u64, Entry>,
118 total_bytes: u64,121 total_bytes: u64,
119 tick: u64,122 tick: u64,
123 evictions: u64,
120 /// Monotonic salt bumped when busting GPU cache globally.124 /// Monotonic salt bumped when busting GPU cache globally.
121 pub gpu_salt: u64,125 pub gpu_salt: u64,
122 /// Per-node salt bumped when surgically busting a subtree.126 /// Per-node salt bumped when surgically busting a subtree.
...@@ -127,15 +131,29 @@ impl NodeCache {...@@ -127,15 +131,29 @@ impl NodeCache {
127 pub fn new(budget_mb: u64) -> Self {131 pub fn new(budget_mb: u64) -> Self {
128 Self {132 Self {
129 mode: CacheMode::Enabled,133 mode: CacheMode::Enabled,
130 budget_bytes: budget_mb * 1024 * 1024,134 budget_bytes: budget_mb.saturating_mul(1024 * 1024),
131 entries: HashMap::new(),135 entries: HashMap::new(),
132 total_bytes: 0,136 total_bytes: 0,
133 tick: 0,137 tick: 0,
138 evictions: 0,
134 gpu_salt: 0,139 gpu_salt: 0,
135 node_salts: HashMap::new(),140 node_salts: HashMap::new(),
136 }141 }
137 }142 }
138143
144 pub fn set_budget_mb(&mut self, budget_mb: u64) {
145 self.budget_bytes = budget_mb.saturating_mul(1024 * 1024);
146 self.evict_over_budget();
147 }
148
149 pub fn budget_mb(&self) -> u64 {
150 self.budget_bytes / (1024 * 1024)
151 }
152
153 pub fn eviction_count(&self) -> u64 {
154 self.evictions
155 }
156
139 pub fn node_salt(&self, id: NodeId) -> u64 {157 pub fn node_salt(&self, id: NodeId) -> u64 {
140 self.node_salts.get(&id).copied().unwrap_or(0)158 self.node_salts.get(&id).copied().unwrap_or(0)
141 }159 }
...@@ -178,13 +196,14 @@ impl NodeCache {...@@ -178,13 +196,14 @@ impl NodeCache {
178 }196 }
179197
180 fn evict_over_budget(&mut self) {198 fn evict_over_budget(&mut self) {
181 while self.total_bytes > self.budget_bytes && self.entries.len() > 2 {199 while self.total_bytes > self.budget_bytes && self.entries.len() > 1 {
182 let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used)200 let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used)
183 else {201 else {
184 break;202 break;
185 };203 };
186 if let Some(removed) = self.entries.remove(&oldest_key) {204 if let Some(removed) = self.entries.remove(&oldest_key) {
187 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);205 self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes);
206 self.evictions += 1;
188 }207 }
189 }208 }
190 }209 }
crates/engine/src/eval/io.rs+179-1
...@@ -21,8 +21,31 @@ impl Engine {...@@ -21,8 +21,31 @@ impl Engine {
21 node.static_str("Clip1.OpenEXRFormat.BlueName"),21 node.static_str("Clip1.OpenEXRFormat.BlueName"),
22 node.static_str("Clip1.OpenEXRFormat.AlphaName"),22 node.static_str("Clip1.OpenEXRFormat.AlphaName"),
23 ];23 ];
24 // When `use_proxy_clips` is enabled, prefer Loader `ProxyFilename` or `Clip.AlternateFilename`
25 // if the resolved proxy file exists on disk, falling back seamlessly to the primary clip.
26 let effective_clip: std::borrow::Cow<'_, model::ClipSpec> = if self.use_proxy_clips {
27 let proxy_candidate = node
28 .static_str("ProxyFilename")
29 .filter(|s| !s.trim().is_empty())
30 .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty()));
31 if let Some(proxy_name) = proxy_candidate {
32 let mut proxy_clip = clip.clone();
33 proxy_clip.filename = proxy_name.to_owned();
34 if crate::media::resolve_clip_path(&proxy_clip, frame_i)
35 .is_some_and(|p| p.exists())
36 {
37 std::borrow::Cow::Owned(proxy_clip)
38 } else {
39 std::borrow::Cow::Borrowed(clip)
40 }
41 } else {
42 std::borrow::Cow::Borrowed(clip)
43 }
44 } else {
45 std::borrow::Cow::Borrowed(clip)
46 };
24 let Some((resolved, local_idx, img, loaded_from_disk)) =47 let Some((resolved, local_idx, img, loaded_from_disk)) =
25 self.media.load_clip(clip, frame_i, post_mult, exr_channels)48 self.media.load_clip(&effective_clip, frame_i, post_mult, exr_channels)
26 else {49 else {
27 return self.dummy.clone();50 return self.dummy.clone();
28 };51 };
...@@ -770,3 +793,158 @@ impl Engine {...@@ -770,3 +793,158 @@ impl Engine {
770 dst793 dst
771 }794 }
772}795}
796
797#[cfg(test)]
798mod tests {
799 use super::*;
800
801 fn write_solid_png(path: &std::path::Path, w: u32, h: u32, rgba: [u8; 4]) {
802 let mut buf = Vec::with_capacity((w * h * 4) as usize);
803 for _ in 0..(w * h) {
804 buf.extend_from_slice(&rgba);
805 }
806 let file = std::fs::File::create(path).expect("create png");
807 let mut enc = png::Encoder::new(file, w, h);
808 enc.set_color(png::ColorType::Rgba);
809 enc.set_depth(png::BitDepth::Eight);
810 enc.write_header()
811 .expect("hdr")
812 .write_image_data(&buf)
813 .expect("data");
814 }
815
816 #[test]
817 fn loader_prefers_proxy_or_alternate_filename_and_respects_proxy_scale() {
818 let dir = std::env::temp_dir().join("fission_proxy_loader_test");
819 let _ = std::fs::create_dir_all(&dir);
820 let main_png = dir.join("main.png");
821 let proxy_png = dir.join("proxy.png");
822 let alt_png = dir.join("alt.png");
823 write_solid_png(&main_png, 32, 16, [255, 0, 0, 255]); // red
824 write_solid_png(&proxy_png, 32, 16, [0, 255, 0, 255]); // green
825 write_solid_png(&alt_png, 32, 16, [0, 0, 255, 255]); // blue
826
827 let comp_src = format!(
828 r#"
829Composition {{
830 CurrentTime = 0,
831 RenderRange = {{ 0, 10 }},
832 GlobalRange = {{ 0, 10 }},
833 Tools = ordered() {{
834 LD1 = Loader {{
835 Clips = {{
836 Clip {{
837 ID = "Clip1",
838 Filename = "{}",
839 AlternateFilename = "{}",
840 FormatID = "PNGFormat",
841 StartFrame = 0,
842 Length = 1,
843 }}
844 }},
845 Inputs = {{
846 ProxyFilename = Input {{ Value = "{}", }},
847 }},
848 }},
849 LD2 = Loader {{
850 Clips = {{
851 Clip {{
852 ID = "Clip1",
853 Filename = "{}",
854 AlternateFilename = "{}",
855 FormatID = "PNGFormat",
856 StartFrame = 0,
857 Length = 1,
858 }}
859 }},
860 }},
861 }},
862}}
863"#,
864 main_png.display(),
865 alt_png.display(),
866 proxy_png.display(),
867 main_png.display(),
868 alt_png.display(),
869 );
870 let comp = Comp::from_fusion_str(&comp_src).expect("parse");
871 let ld1 = comp.find_node("LD1").expect("LD1");
872 let ld2 = comp.find_node("LD2").expect("LD2");
873
874 let mut engine = Engine::new_headless().expect("gpu");
875 // Default: primary red clip at 1:1
876 let (tex, _) = engine.evaluate(&comp, ld1, 0.0);
877 assert_eq!(tex.size, [32, 16]);
878 let px = engine.readback_rgba(&tex).expect("readback");
879 assert!(px[0] > 240 && px[1] < 15 && px[2] < 15, "expected red primary");
880
881 // Proxy clips enabled + 1:2 resolution scale: LD1 picks ProxyFilename (green), LD2 picks AlternateFilename (blue)
882 engine.use_proxy_clips = true;
883 engine.proxy_scale = 2;
884 let (tex1, _) = engine.evaluate(&comp, ld1, 0.0);
885 assert_eq!(tex1.size, [16, 8]);
886 let px1 = engine.readback_rgba(&tex1).expect("readback");
887 assert!(px1[1] > 240 && px1[0] < 15 && px1[2] < 15, "expected green proxy");
888
889 let (tex2, _) = engine.evaluate(&comp, ld2, 0.0);
890 assert_eq!(tex2.size, [16, 8]);
891 let px2 = engine.readback_rgba(&tex2).expect("readback");
892 assert!(px2[2] > 240 && px2[0] < 15 && px2[1] < 15, "expected blue alternate");
893
894 // 1:4 scale
895 engine.proxy_scale = 4;
896 let (tex4, _) = engine.evaluate(&comp, ld1, 0.0);
897 assert_eq!(tex4.size, [8, 4]);
898
899 let _ = std::fs::remove_dir_all(&dir);
900 }
901
902 #[test]
903 fn vram_budget_strictly_caps_node_cache() {
904 let mut engine = Engine::new_headless().expect("gpu");
905 engine.set_vram_budget_mb(8);
906 assert_eq!(engine.vram_budget_mb(), 8);
907
908 let comp_src = r#"
909Composition {
910 CurrentTime = 0,
911 RenderRange = { 0, 20 },
912 GlobalRange = { 0, 20 },
913 Tools = ordered() {
914 BG = Background {
915 Inputs = {
916 Width = Input { Value = 1024, },
917 Height = Input { Value = 1024, },
918 TopLeftRed = Input { Value = 0.5, },
919 TopLeftAlpha = Input { Value = 1.0, },
920 },
921 },
922 BC = BrightnessContrast {
923 Inputs = {
924 Gain = Input { SourceOp = "GainSp", Source = "Value", },
925 Input = Input { SourceOp = "BG", Source = "Output", },
926 },
927 },
928 GainSp = BezierSpline {
929 KeyFrames = {
930 [0] = { 0.5 },
931 [10] = { 2.0 },
932 },
933 },
934 },
935}
936"#;
937 let comp = Comp::from_fusion_str(comp_src).expect("parse");
938 let bc = comp.find_node("BC").expect("BC");
939 // Each 1024x1024 RGBA8 texture is 4 MB; 8 MB budget holds at most 2 textures across 6 animated frames.
940 for f in 0..6 {
941 let (_, stats) = engine.evaluate(&comp, bc, f as f64);
942 assert!(
943 stats.cached_vram_mb <= 8.5,
944 "VRAM exceeded 8 MB cap at frame {f}: {:.1} MB",
945 stats.cached_vram_mb
946 );
947 }
948 assert!(engine.cache.eviction_count() >= 1);
949 }
950}
crates/engine/src/eval/masks.rs+169
...@@ -384,4 +384,173 @@ impl Engine {...@@ -384,4 +384,173 @@ impl Engine {
384 out_tex384 out_tex
385 }385 }
386386
387 pub(super) fn eval_wand_mask(
388 &mut self,
389 comp: &Comp,
390 node: &Node,
391 time: f64,
392 frame_i: i64,
393 comp_dims: [u32; 2],
394 enc: &mut wgpu::CommandEncoder,
395 visiting: &mut HashSet<(NodeId, i64)>,
396 stats: &mut EvalStats,
397 ) -> CachedTexture {
398 let Some(src_id) = node
399 .connected_node("Source")
400 .or_else(|| node.connected_node("Input"))
401 .and_then(|s| comp.find_node(s))
402 else {
403 return create_texture(&self.device, comp_dims, 0);
404 };
405 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
406 let src = self.crop_to_canvas(enc, src);
407 let size = src.size;
408
409 let seed_pt = comp.eval_point(node, "SelectionPoint", time, [0.5, 0.5], &self.expr);
410 let range = comp.eval_number(node, "SelectionRange", time, 0.1, &self.expr).clamp(0.0, 1.0) as f32;
411 let color_space = comp.eval_number(node, "ColorSpace", time, 0.0, &self.expr).round() as i32;
412 let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32;
413 let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) as f32;
414 let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32;
415 let is_box = Self::mask_filter_is_box(node);
416 let clamp_edges = Self::mask_clamp_edges(node);
417 let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats);
418 let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash);
419 let paint_mode = Self::paint_mode_id(node);
420
421 let key = self.make_key(
422 node,
423 "WandMask",
424 size,
425 &[src.content_hash, prev_hash],
426 &[
427 seed_pt[0] as f32,
428 seed_pt[1] as f32,
429 range,
430 color_space as f32,
431 soft,
432 invert,
433 level,
434 if is_box { 1.0 } else { 0.0 },
435 clamp_edges,
436 paint_mode,
437 ],
438 );
439 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
440 stats.cache_hits += 1;
441 return hit;
442 }
443 stats.cache_misses += 1;
444 stats.nodes_evaluated += 1;
445
446 // Flush pending GPU commands so readback sees fresh source pixels.
447 let flush_enc = std::mem::replace(
448 enc,
449 self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
450 label: Some("comp-eval-post-wand"),
451 }),
452 );
453 self.queue.submit(Some(flush_enc.finish()));
454
455 let w = size[0].max(1) as usize;
456 let h = size[1].max(1) as usize;
457 let mut mask_rgba = vec![0u8; w * h * 4];
458 if let Ok(src_rgba) = self.readback_rgba(&src) {
459 if src_rgba.len() >= w * h * 4 {
460 let sx = ((seed_pt[0] as f32).clamp(0.0, 1.0) * (w - 1) as f32).round() as usize;
461 let sy = ((1.0 - (seed_pt[1] as f32).clamp(0.0, 1.0)) * (h - 1) as f32).round() as usize;
462 let soff = (sy * w + sx) * 4;
463 let sr = src_rgba[soff] as f32 / 255.0;
464 let sg = src_rgba[soff + 1] as f32 / 255.0;
465 let sb = src_rgba[soff + 2] as f32 / 255.0;
466 let sl = 0.299 * sr + 0.587 * sg + 0.114 * sb;
467
468 let mut visited = vec![false; w * h];
469 let mut queue = std::collections::VecDeque::with_capacity(1024);
470 let start_idx = sy * w + sx;
471 visited[start_idx] = true;
472 queue.push_back((sx, sy));
473
474 while let Some((x, y)) = queue.pop_front() {
475 let off = (y * w + x) * 4;
476 mask_rgba[off] = 255;
477 mask_rgba[off + 1] = 255;
478 mask_rgba[off + 2] = 255;
479 mask_rgba[off + 3] = 255;
480
481 let nbrs = [
482 (x.wrapping_sub(1), y, x > 0),
483 (x + 1, y, x + 1 < w),
484 (x, y.wrapping_sub(1), y > 0),
485 (x, y + 1, y + 1 < h),
486 ];
487 for (nx, ny, ok) in nbrs {
488 if !ok {
489 continue;
490 }
491 let ni = ny * w + nx;
492 if visited[ni] {
493 continue;
494 }
495 let noff = ni * 4;
496 let r = src_rgba[noff] as f32 / 255.0;
497 let g = src_rgba[noff + 1] as f32 / 255.0;
498 let b = src_rgba[noff + 2] as f32 / 255.0;
499 let dist = if color_space == 1 {
500 // YUV / Luma-weighted distance
501 let l = 0.299 * r + 0.587 * g + 0.114 * b;
502 let du = (b - l) - (sb - sl);
503 let dv = (r - l) - (sr - sl);
504 ((l - sl).abs()).max(du.abs()).max(dv.abs())
505 } else {
506 // Max-channel RGB Chebyshev distance
507 (r - sr).abs().max((g - sg).abs()).max((b - sb).abs())
508 };
509 if dist <= range {
510 visited[ni] = true;
511 queue.push_back((nx, ny));
512 }
513 }
514 }
515 }
516 }
517
518 let soft_px = soft * size[0] as f32;
519 let need_post = soft_px >= 0.5 || invert > 0.5 || (level - 1.0).abs() > 1e-4 || prev_mask.is_some();
520 let raw_tex = create_texture(&self.device, size, if need_post { 0 } else { key });
521 self.queue.write_texture(
522 raw_tex.texture.as_image_copy(),
523 &mask_rgba,
524 wgpu::TexelCopyBufferLayout {
525 offset: 0,
526 bytes_per_row: Some(size[0] * 4),
527 rows_per_image: Some(size[1]),
528 },
529 wgpu::Extent3d {
530 width: size[0],
531 height: size[1],
532 depth_or_array_layers: 1,
533 },
534 );
535
536 let out_tex = if need_post {
537 let blurred = if soft_px >= 0.5 {
538 self.blur_mask_texture(enc, &raw_tex, soft_px, is_box, clamp_edges)
539 } else {
540 raw_tex
541 };
542 let combined = create_texture(&self.device, size, key);
543 let mut uc = UniformParams::default();
544 uc.p[0] = [paint_mode, invert, level, if prev_mask.is_some() { 1.0 } else { 0.0 }];
545 let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
546 self.dispatch_op(enc, ShaderOp::MaskCombine, &blurred.view, &self.dummy.view, mv, &combined, &uc);
547 combined
548 } else {
549 raw_tex
550 };
551
552 self.cache.insert(key, out_tex.clone(), node.id, frame_i);
553 out_tex
554 }
555
387}556}
crates/engine/src/eval/mod.rs+162-5
...@@ -102,6 +102,7 @@ enum ShaderOp {...@@ -102,6 +102,7 @@ enum ShaderOp {
102 SetDomain,102 SetDomain,
103 ChangeDepth,103 ChangeDepth,
104 Vortex,104 Vortex,
105 KScope,
105}106}
106107
107struct Pipelines {108struct Pipelines {
...@@ -149,6 +150,7 @@ struct Pipelines {...@@ -149,6 +150,7 @@ struct Pipelines {
149 set_domain: wgpu::ComputePipeline,150 set_domain: wgpu::ComputePipeline,
150 change_depth: wgpu::ComputePipeline,151 change_depth: wgpu::ComputePipeline,
151 vortex: wgpu::ComputePipeline,152 vortex: wgpu::ComputePipeline,
153 kscope: wgpu::ComputePipeline,
152}154}
153155
154impl Pipelines {156impl Pipelines {
...@@ -290,6 +292,7 @@ impl Pipelines {...@@ -290,6 +292,7 @@ impl Pipelines {
290 set_domain: make("set_domain_op"),292 set_domain: make("set_domain_op"),
291 change_depth: make("change_depth_op"),293 change_depth: make("change_depth_op"),
292 vortex: make("vortex_op"),294 vortex: make("vortex_op"),
295 kscope: make("kscope_op"),
293 }296 }
294 }297 }
295298
...@@ -337,6 +340,7 @@ impl Pipelines {...@@ -337,6 +340,7 @@ impl Pipelines {
337 ShaderOp::SetDomain => &self.set_domain,340 ShaderOp::SetDomain => &self.set_domain,
338 ShaderOp::ChangeDepth => &self.change_depth,341 ShaderOp::ChangeDepth => &self.change_depth,
339 ShaderOp::Vortex => &self.vortex,342 ShaderOp::Vortex => &self.vortex,
343 ShaderOp::KScope => &self.kscope,
340 }344 }
341 }345 }
342}346}
...@@ -359,11 +363,16 @@ pub struct Engine {...@@ -359,11 +363,16 @@ pub struct Engine {
359 pub expr: ExprEngine,363 pub expr: ExprEngine,
360 /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame.364 /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame.
361 frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>,365 frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>,
366 /// Bounded LRU of recent final output textures (up to 8 entries) so tight VRAM caps on
367 /// 150+ node comps still deliver `<0.1ms` warm hits during pan/zoom/exposure/scrubbing.
368 output_cache: std::collections::VecDeque<(u64, CachedTexture, Vec<String>)>,
362 /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default369 /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default
363 /// to matching the dimensions & aspect ratio of the node they mask!).370 /// to matching the dimensions & aspect ratio of the node they mask!).
364 mask_target_size: Option<[u32; 2]>,371 mask_target_size: Option<[u32; 2]>,
365 /// Proxy downscale divisor: 1 = full res, 2 = half res, 4 = quarter res.372 /// Proxy downscale divisor: 1 = full res, 2 = half res, 4 = quarter res.
366 pub proxy_scale: u32,373 pub proxy_scale: u32,
374 /// When `true`, `Loader` nodes prefer `ProxyFilename` or `Clip.AlternateFilename` if present on disk.
375 pub use_proxy_clips: bool,
367 /// High-Quality mode (`true` = exact Fusion bar-for-bar passes & project/ChangeDepth bit depth;376 /// High-Quality mode (`true` = exact Fusion bar-for-bar passes & project/ChangeDepth bit depth;
368 /// `false` = perfmaxxed pyramid blur/glow & fast Rgba8Unorm working textures).377 /// `false` = perfmaxxed pyramid blur/glow & fast Rgba8Unorm working textures).
369 pub hiq: bool,378 pub hiq: bool,
...@@ -398,12 +407,14 @@ impl Engine {...@@ -398,12 +407,14 @@ impl Engine {
398 particles: crate::particles::ParticleCache::default(),407 particles: crate::particles::ParticleCache::default(),
399 sprite_cache: HashMap::new(),408 sprite_cache: HashMap::new(),
400 dummy,409 dummy,
401 cache: NodeCache::new(2048), // 2 GB GPU texture cache cap (prevents thrashing on 100+ node diamond DAGs)410 cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB),
402 media: MediaCache::new(1024),411 media: MediaCache::new(512),
403 expr: ExprEngine::new(),412 expr: ExprEngine::new(),
404 frame_memo: HashMap::new(),413 frame_memo: HashMap::new(),
414 output_cache: std::collections::VecDeque::new(),
405 mask_target_size: None,415 mask_target_size: None,
406 proxy_scale: 1,416 proxy_scale: 1,
417 use_proxy_clips: false,
407 hiq: true,418 hiq: true,
408 }419 }
409 }420 }
...@@ -531,8 +542,85 @@ impl Engine {...@@ -531,8 +542,85 @@ impl Engine {
531 self.cache.mode = mode;542 self.cache.mode = mode;
532 }543 }
533544
545 pub fn set_vram_budget_mb(&mut self, budget_mb: u64) {
546 self.cache.set_budget_mb(budget_mb);
547 if budget_mb < 64 {
548 self.output_cache.clear();
549 }
550 }
551
552 pub fn vram_budget_mb(&self) -> u64 {
553 self.cache.budget_mb()
554 }
555
556 pub fn set_media_budget_mb(&mut self, budget_mb: u64) {
557 self.media.set_budget_mb(budget_mb);
558 }
559
560 /// Uploads a cached `RamFrame` directly into a viewer `wgpu::Texture` with full
561 /// `DisplaySettings` (exposure, gamma, channel isolate, zoom/pan) without evaluating the DAG.
562 pub fn render_ram_frame_into_viewer(
563 &self,
564 frame: &crate::ram_cache::RamFrame,
565 dst_texture: &wgpu::Texture,
566 display: DisplaySettings,
567 ) -> EvalStats {
568 let t0 = Instant::now();
569 let src = create_texture(&self.device, frame.size, 0);
570 self.queue.write_texture(
571 src.texture.as_image_copy(),
572 &frame.rgba,
573 wgpu::TexelCopyBufferLayout {
574 offset: 0,
575 bytes_per_row: Some(frame.size[0] * 4),
576 rows_per_image: Some(frame.size[1]),
577 },
578 wgpu::Extent3d {
579 width: frame.size[0],
580 height: frame.size[1],
581 depth_or_array_layers: 1,
582 },
583 );
584 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
585 label: Some("comp-ram-viewer-blit"),
586 });
587 let dst_size = [dst_texture.width(), dst_texture.height()];
588 let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default());
589 let mut params = UniformParams::default();
590 params.p[0] = [
591 2.0_f32.powf(display.exposure),
592 display.gamma,
593 display.channel as f32,
594 if display.checker_bg { 1.0 } else { 0.0 },
595 ];
596 params.p[1] = display.uv_rect;
597 params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0];
598 self.dispatch_to_view(
599 &mut encoder,
600 &self.pipelines.display_blit,
601 &src.view,
602 &self.dummy.view,
603 &self.dummy.view,
604 &dst_view,
605 dst_size,
606 &params,
607 );
608 self.queue.submit(Some(encoder.finish()));
609
610 EvalStats {
611 eval_ms: t0.elapsed().as_secs_f64() * 1000.0,
612 cache_hits: 1,
613 cached_entries: self.cache.entry_count(),
614 cached_vram_mb: self.cache.total_mb(),
615 media_entries: self.media.entry_count(),
616 media_mb: self.media.total_mb(),
617 ..EvalStats::default()
618 }
619 }
620
534 pub fn bust_all_caches(&mut self) {621 pub fn bust_all_caches(&mut self) {
535 self.cache.bust_all();622 self.cache.bust_all();
623 self.output_cache.clear();
536 self.media.clear();624 self.media.clear();
537 self.particles.clear();625 self.particles.clear();
538 self.sprite_cache.clear();626 self.sprite_cache.clear();
...@@ -540,16 +628,58 @@ impl Engine {...@@ -540,16 +628,58 @@ impl Engine {
540628
541 pub fn bust_gpu_cache(&mut self) {629 pub fn bust_gpu_cache(&mut self) {
542 self.cache.bust_all();630 self.cache.bust_all();
631 self.output_cache.clear();
543 }632 }
544633
545 pub fn bust_frame(&mut self, frame: i64) -> usize {634 pub fn bust_frame(&mut self, frame: i64) -> usize {
635 self.output_cache.clear();
546 self.cache.bust_frame(frame)636 self.cache.bust_frame(frame)
547 }637 }
548638
549 pub fn bust_subtree(&mut self, node: NodeId) -> usize {639 pub fn bust_subtree(&mut self, node: NodeId) -> usize {
640 self.output_cache.clear();
550 self.cache.bust_subtree(node)641 self.cache.bust_subtree(node)
551 }642 }
552643
644 fn output_cache_key(&self, comp: &Comp, target: NodeId, time: f64) -> u64 {
645 let mut h = DefaultHasher::new();
646 self.cache.gpu_salt.hash(&mut h);
647 comp.name.hash(&mut h);
648 comp.path.hash(&mut h);
649 comp.nodes.len().hash(&mut h);
650 comp.revision.hash(&mut h);
651 target.hash(&mut h);
652 time.to_bits().hash(&mut h);
653 self.proxy_scale.hash(&mut h);
654 self.hiq.hash(&mut h);
655 self.use_proxy_clips.hash(&mut h);
656 h.finish()
657 }
658
659 fn output_cache_get(&mut self, key: u64) -> Option<(CachedTexture, Vec<String>)> {
660 if self.cache.mode == CacheMode::Bypass {
661 return None;
662 }
663 let pos = self.output_cache.iter().position(|(k, _, _)| *k == key)?;
664 let entry = self.output_cache.remove(pos)?;
665 let res = (entry.1.clone(), entry.2.clone());
666 self.output_cache.push_back(entry);
667 Some(res)
668 }
669
670 fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec<String>) {
671 if self.cache.mode == CacheMode::Bypass || self.cache.budget_bytes < 64 * 1024 * 1024 {
672 return;
673 }
674 if let Some(pos) = self.output_cache.iter().position(|(k, _, _)| *k == key) {
675 self.output_cache.remove(pos);
676 }
677 self.output_cache.push_back((key, tex, unsupported));
678 while self.output_cache.len() > 8 {
679 self.output_cache.pop_front();
680 }
681 }
682
553 /// Evaluates `target` node at `time` and returns its GPU texture + telemetry.683 /// Evaluates `target` node at `time` and returns its GPU texture + telemetry.
554 pub fn evaluate(684 pub fn evaluate(
555 &mut self,685 &mut self,
...@@ -558,6 +688,20 @@ impl Engine {...@@ -558,6 +688,20 @@ impl Engine {
558 time: f64,688 time: f64,
559 ) -> (CachedTexture, EvalStats) {689 ) -> (CachedTexture, EvalStats) {
560 let t0 = Instant::now();690 let t0 = Instant::now();
691 let out_key = self.output_cache_key(comp, target, time);
692 if let Some((tex, unsupported)) = self.output_cache_get(out_key) {
693 let stats = EvalStats {
694 eval_ms: t0.elapsed().as_secs_f64() * 1000.0,
695 cache_hits: 1,
696 cached_entries: self.cache.entry_count(),
697 cached_vram_mb: self.cache.total_mb(),
698 media_entries: self.media.entry_count(),
699 media_mb: self.media.total_mb(),
700 unsupported_nodes: unsupported,
701 ..EvalStats::default()
702 };
703 return (tex, stats);
704 }
561 let mut stats = EvalStats::default();705 let mut stats = EvalStats::default();
562 let mut visiting = HashSet::new();706 let mut visiting = HashSet::new();
563 self.frame_memo.clear();707 self.frame_memo.clear();
...@@ -582,6 +726,7 @@ impl Engine {...@@ -582,6 +726,7 @@ impl Engine {
582 }726 }
583 self.queue.submit(Some(encoder.finish()));727 self.queue.submit(Some(encoder.finish()));
584728
729 self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone());
585 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;730 stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0;
586 stats.cached_entries = self.cache.entry_count();731 stats.cached_entries = self.cache.entry_count();
587 stats.cached_vram_mb = self.cache.total_mb();732 stats.cached_vram_mb = self.cache.total_mb();
...@@ -600,14 +745,23 @@ impl Engine {...@@ -600,14 +745,23 @@ impl Engine {
600 display: DisplaySettings,745 display: DisplaySettings,
601 ) -> EvalStats {746 ) -> EvalStats {
602 let t0 = Instant::now();747 let t0 = Instant::now();
748 let out_key = self.output_cache_key(comp, target, time);
603 let mut stats = EvalStats::default();749 let mut stats = EvalStats::default();
604 let mut visiting = HashSet::new();
605 self.frame_memo.clear();
606 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {750 let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
607 label: Some("comp-viewer-eval"),751 label: Some("comp-viewer-eval"),
608 });752 });
609753
610 let tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);754 let tex = if let Some((cached, unsupported)) = self.output_cache_get(out_key) {
755 stats.cache_hits = 1;
756 stats.unsupported_nodes = unsupported;
757 cached
758 } else {
759 let mut visiting = HashSet::new();
760 self.frame_memo.clear();
761 let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats);
762 self.output_cache_insert(out_key, t.clone(), stats.unsupported_nodes.clone());
763 t
764 };
611765
612 let dst_size = [dst_texture.width(), dst_texture.height()];766 let dst_size = [dst_texture.width(), dst_texture.height()];
613 let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default());767 let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default());
...@@ -907,10 +1061,13 @@ impl Engine {...@@ -907,10 +1061,13 @@ impl Engine {
907 "FilmGrain" => self.eval_film_grain(comp, node, time, frame_i, enc, visiting, stats),1061 "FilmGrain" => self.eval_film_grain(comp, node, time, frame_i, enc, visiting, stats),
908 "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats),1062 "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats),
909 "Vortex" => self.eval_vortex(comp, node, time, frame_i, enc, visiting, stats),1063 "Vortex" => self.eval_vortex(comp, node, time, frame_i, enc, visiting, stats),
1064 "Fuse.Duplicate" => self.eval_duplicate(comp, node, time, frame_i, enc, visiting, stats),
1065 "Fuse.KScope" => self.eval_kscope(comp, node, time, frame_i, enc, visiting, stats),
910 "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats),1066 "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats),
911 "RectangleMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 1, enc, visiting, stats),1067 "RectangleMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 1, enc, visiting, stats),
912 "PolylineMask" => self.eval_polyline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats),1068 "PolylineMask" => self.eval_polyline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
913 "BitmapMask" => self.eval_bitmap_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats),1069 "BitmapMask" => self.eval_bitmap_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
1070 "WandMask" => self.eval_wand_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats),
914 "TextPlus" => self.eval_text_plus(comp, node, time, frame_i, comp_dims, enc, stats),1071 "TextPlus" => self.eval_text_plus(comp, node, time, frame_i, comp_dims, enc, stats),
915 "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats),1072 "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats),
916 "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats),1073 "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats),
crates/engine/src/eval/text_3d.rs+71-4
...@@ -518,18 +518,61 @@ impl Engine {...@@ -518,18 +518,61 @@ impl Engine {
518 hash_floats.extend_from_slice(&lights.ambient);518 hash_floats.extend_from_slice(&lights.ambient);
519 hash_floats.extend_from_slice(&lights.dir_to_light);519 hash_floats.extend_from_slice(&lights.dir_to_light);
520 hash_floats.extend_from_slice(&lights.dir_color);520 hash_floats.extend_from_slice(&lights.dir_color);
521 for ms in mesh_specs {521 for pl in &lights.points {
522 let tex = ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats));522 hash_floats.extend_from_slice(&pl.pos);
523 hash_floats.extend_from_slice(&pl.color);
524 hash_floats.push(pl.decay_type);
525 hash_floats.push(pl.decay_rate);
526 }
527 for sl in &lights.spots {
528 hash_floats.extend_from_slice(&sl.pos);
529 hash_floats.extend_from_slice(&sl.dir);
530 hash_floats.extend_from_slice(&sl.color);
531 hash_floats.push(sl.cos_inner);
532 hash_floats.push(sl.cos_outer);
533 hash_floats.push(sl.decay_type);
534 }
535
536 // First resolve all 2D textures & Text3D plates & Displace3D heightmaps
537 let mut pending_displace_tex: Vec<Option<(CachedTexture, f32, f32, i32)>> = Vec::with_capacity(mesh_specs.len());
538 for ms in &mesh_specs {
539 let tex = if let Some(t3d) = &ms.text3d {
540 let tnode = comp.node(t3d.node_id);
541 Some(self.eval_text_plus(comp, tnode, time, frame_i, [1024, 512], enc, stats))
542 } else {
543 ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats))
544 };
545 let disp_entry = ms.displace.as_ref().map(|ds| {
546 let dtex = self.eval_node(comp, ds.input_node, time, enc, visiting, stats);
547 (dtex, ds.scale, ds.bias, ds.channel)
548 });
523 upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash));549 upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash));
550 upstream_hashes.push(disp_entry.as_ref().map_or(0, |(t, _, _, _)| t.content_hash));
524 hash_floats.extend_from_slice(&ms.world);551 hash_floats.extend_from_slice(&ms.world);
525 hash_floats.extend_from_slice(&ms.diffuse_col);552 hash_floats.extend_from_slice(&ms.diffuse_col);
553 hash_floats.extend_from_slice(&ms.specular_col);
554 hash_floats.push(ms.specular_intensity);
555 hash_floats.push(ms.specular_exponent);
556 hash_floats.push(if ms.affected_by_lights { 1.0 } else { 0.0 });
557 hash_floats.push(if ms.flip_normals { 1.0 } else { 0.0 });
558 if let Some((_, sc, bi, ch)) = disp_entry {
559 hash_floats.push(sc);
560 hash_floats.push(bi);
561 hash_floats.push(ch as f32);
562 }
526 draw_meshes.push(crate::scene3d::DrawMesh {563 draw_meshes.push(crate::scene3d::DrawMesh {
527 world: ms.world,564 world: ms.world,
528 shape: ms.shape,565 shape: ms.shape.clone(),
529 tex,566 tex,
530 diffuse_col: ms.diffuse_col,567 diffuse_col: ms.diffuse_col,
531 roughness: ms.roughness,568 specular_col: ms.specular_col,
569 specular_intensity: ms.specular_intensity,
570 specular_exponent: ms.specular_exponent,
571 affected_by_lights: ms.affected_by_lights,
572 flip_normals: ms.flip_normals,
573 displace: None,
532 });574 });
575 pending_displace_tex.push(disp_entry);
533 }576 }
534577
535 let key = self.make_key(node, "Renderer3D", size, &upstream_hashes, &hash_floats);578 let key = self.make_key(node, "Renderer3D", size, &upstream_hashes, &hash_floats);
...@@ -540,6 +583,30 @@ impl Engine {...@@ -540,6 +583,30 @@ impl Engine {
540 stats.cache_misses += 1;583 stats.cache_misses += 1;
541 stats.nodes_evaluated += 1;584 stats.nodes_evaluated += 1;
542585
586 // If any Displace3D heightmaps are present, flush pending encoder commands so CPU readback sees fresh pixels.
587 if pending_displace_tex.iter().any(|d| d.is_some()) {
588 let flush_enc = std::mem::replace(
589 enc,
590 self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
591 label: Some("comp-eval-post-disp3d"),
592 }),
593 );
594 self.queue.submit(Some(flush_enc.finish()));
595 for (dm, entry) in draw_meshes.iter_mut().zip(pending_displace_tex.into_iter()) {
596 if let Some((dtex, scale, bias, channel)) = entry {
597 if let Ok(rgba) = self.readback_rgba(&dtex) {
598 dm.displace = Some(crate::scene3d::DisplaceHeightmap {
599 size: dtex.size,
600 rgba,
601 scale,
602 bias,
603 channel,
604 });
605 }
606 }
607 }
608 }
609
543 let dst = create_texture(&self.device, size, key);610 let dst = create_texture(&self.device, size, key);
544 self.scene3d.render_meshes(611 self.scene3d.render_meshes(
545 &self.device,612 &self.device,
crates/engine/src/eval/transform.rs+191
...@@ -423,4 +423,195 @@ impl Engine {...@@ -423,4 +423,195 @@ impl Engine {
423 dst423 dst
424 }424 }
425425
426 pub(super) fn eval_duplicate(
427 &mut self,
428 comp: &Comp,
429 node: &Node,
430 time: f64,
431 frame_i: i64,
432 enc: &mut wgpu::CommandEncoder,
433 visiting: &mut HashSet<(NodeId, i64)>,
434 stats: &mut EvalStats,
435 ) -> CachedTexture {
436 let Some(src_id) = node
437 .connected_node("Background")
438 .or_else(|| node.connected_node("Input"))
439 .and_then(|s| comp.find_node(s))
440 else {
441 return self.dummy.clone();
442 };
443 let base = self.eval_node(comp, src_id, time, enc, visiting, stats);
444 let copies = comp.eval_number(node, "Copies", time, 2.0, &self.expr).round().clamp(1.0, 64.0) as i32;
445 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
446 if copies <= 1 || blend <= 1e-6 {
447 return base;
448 }
449 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
450 // Fusion Fuse.Duplicate uses `Size` (or `XSize` when LockSize=0); default 1.0
451 let size_s = comp.eval_number(node, "XSize", time, comp.eval_number(node, "Size", time, 1.0, &self.expr), &self.expr) as f32;
452 let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;
453 let gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32;
454 let time_off = comp.eval_number(node, "TimeOffset", time, 0.0, &self.expr);
455 let merge_under = comp.eval_number(node, "MergeUnder", time, 0.0, &self.expr) > 0.5;
456 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(base.size), enc, visiting, stats);
457 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
458
459 let params = [
460 copies as f32,
461 center[0] as f32,
462 center[1] as f32,
463 size_s,
464 angle_deg,
465 gain,
466 blend,
467 time_off as f32,
468 if merge_under { 1.0 } else { 0.0 },
469 ];
470 let key = self.make_key(node, "Duplicate", base.size, &[base.content_hash, mask_hash], &params);
471 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
472 stats.cache_hits += 1;
473 return hit;
474 }
475 stats.cache_misses += 1;
476 stats.nodes_evaluated += 1;
477
478 let dx = center[0] as f32 - 0.5;
479 let dy = center[1] as f32 - 0.5;
480 let mut accum = base.clone();
481 for i in 1..copies {
482 let fi = i as f32;
483 let copy_src = if time_off.abs() > 1e-4 {
484 self.eval_node(comp, src_id, time + (i as f64) * time_off, enc, visiting, stats)
485 } else {
486 base.clone()
487 };
488 let cx = 0.5 + dx * fi;
489 let cy = 0.5 + dy * fi;
490 let sc = size_s.powi(i).max(1e-4);
491 let ang = (angle_deg * fi).to_radians();
492 let g_i = gain.powi(i);
493 let is_last = i == copies - 1;
494 let next = self.alloc_tex_like(&base, base.depth, if is_last { key } else { 0 });
495 let mut u = UniformParams::default();
496 u.p[0] = [cx, cy, sc, ang];
497 u.p[1] = [blend, g_i, 0.0, 0.0];
498 u.p[2] = [0.0, 0.0, 0.0, if merge_under { 1.0 } else { 0.0 }];
499 u.p[3] = [
500 if mask.is_some() { 1.0 } else { 0.0 },
501 if mask_inv { 1.0 } else { 0.0 },
502 copy_src.canvas_size[0] as f32,
503 copy_src.canvas_size[1] as f32,
504 ];
505 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
506 self.dispatch_op(enc, ShaderOp::Merge, &accum.view, &copy_src.view, mv, &next, &u);
507 accum = next;
508 }
509
510 self.cache.insert(key, accum.clone(), node.id, frame_i);
511 accum
512 }
513
514 pub(super) fn eval_kscope(
515 &mut self,
516 comp: &Comp,
517 node: &Node,
518 time: f64,
519 frame_i: i64,
520 enc: &mut wgpu::CommandEncoder,
521 visiting: &mut HashSet<(NodeId, i64)>,
522 stats: &mut EvalStats,
523 ) -> CachedTexture {
524 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
525 return self.dummy.clone();
526 };
527 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
528 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
529 if blend <= 1e-6 {
530 return src;
531 }
532 let src = self.crop_to_canvas(enc, src);
533 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
534 let slices = comp.eval_number(node, "Slices", time, 6.0, &self.expr).max(1.0) as f32;
535 let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians();
536 let cap_angle = (comp.eval_number(node, "CaptureAngle", time, 0.0, &self.expr) as f32).to_radians();
537 let scale = comp.eval_number(node, "Scale", time, 1.0, &self.expr).max(1e-4) as f32;
538 let edges = comp.eval_number(node, "Edges", time, 3.0, &self.expr) as f32;
539 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
540 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
541
542 let mut u = UniformParams::default();
543 u.p[0] = [center[0] as f32, center[1] as f32, slices, angle];
544 u.p[1] = [cap_angle, scale, edges, blend];
545 u.p[2] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0];
546
547 let key = self.make_key(node, "KScope", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3]));
548 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
549 stats.cache_hits += 1;
550 return hit;
551 }
552 stats.cache_misses += 1;
553 stats.nodes_evaluated += 1;
554 let dst = self.alloc_tex_like(&src, src.depth, key);
555 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
556 self.dispatch_op(enc, ShaderOp::KScope, &src.view, &self.dummy.view, mv, &dst, &u);
557 self.cache.insert(key, dst.clone(), node.id, frame_i);
558 dst
559 }
560}
561
562#[cfg(test)]
563mod tests {
564 use super::*;
565 use crate::Engine;
566
567 #[test]
568 fn test_fuse_kscope_6_slice_symmetry() {
569 let src = r#"Composition {
570 CurrentTime = 0,
571 RenderRange = { 0, 1 },
572 GlobalRange = { 0, 1 },
573 Tools = ordered() {
574 BG1 = Background {
575 Inputs = {
576 Width = Input { Value = 128, },
577 Height = Input { Value = 128, },
578 Type = Input { Value = FuID { "Horizontal" }, },
579 TopLeftRed = Input { Value = 1.0, },
580 TopLeftGreen = Input { Value = 0.0, },
581 TopLeftBlue = Input { Value = 0.0, },
582 TopRightRed = Input { Value = 0.0, },
583 TopRightGreen = Input { Value = 0.0, },
584 TopRightBlue = Input { Value = 1.0, },
585 },
586 },
587 KS1 = Fuse.KScope {
588 Inputs = {
589 Input = Input { SourceOp = "BG1", Source = "Output", },
590 Slices = Input { Value = 6, },
591 Scale = Input { Value = 1.0, },
592 },
593 },
594 },
595 }"#;
596 let comp = Comp::from_fusion_str(src).expect("parse KScope comp");
597 let Ok(mut eng) = Engine::new_headless() else {
598 return;
599 };
600 let node_id = comp.find_node("KS1").expect("KS1");
601 let (tex, _) = eng.evaluate(&comp, node_id, 0.0);
602 let rgba = eng.readback_rgba(&tex).expect("readback KScope");
603 let [w, h] = tex.size;
604 assert_eq!((w, h), (128, 128));
605 // With Slices=6, sector=60 deg mirrored every 120 deg -> reflection across X axis is exact!
606 let px = |x: usize, y: usize| -> [u8; 4] {
607 let i = (y * 128 + x) * 4;
608 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
609 };
610 let a = px(64 + 28, 64 + 12);
611 let b = px(64 + 28, 63 - 12);
612 for c in 0..3 {
613 let diff = (a[c] as i32 - b[c] as i32).abs();
614 assert!(diff <= 2, "KScope 6-slice mirror symmetry mismatch ch={c}: {a:?} vs {b:?}");
615 }
616 }
426}617}
crates/engine/src/lib.rs+5-1
...@@ -6,9 +6,13 @@ pub mod export;...@@ -6,9 +6,13 @@ pub mod export;
6pub mod media;6pub mod media;
7pub mod optflow;7pub mod optflow;
8pub mod particles;8pub mod particles;
9pub mod ram_cache;
9pub mod scene3d;10pub mod scene3d;
1011
11pub use audio::{AudioPlayer, AudioTrack};12pub use audio::{AudioPlayer, AudioTrack};
12pub use cache::{CacheMode, CachedTexture, EvalStats, NodeCache};13pub use cache::{CacheMode, CachedTexture, DEFAULT_VRAM_BUDGET_MB, EvalStats, NodeCache};
13pub use eval::{DisplaySettings, Engine, create_texture};14pub use eval::{DisplaySettings, Engine, create_texture};
14pub use export::{ExportOptions, ExportProgress, ExportSummary, export_saver_png_sequence, select_saver};15pub use export::{ExportOptions, ExportProgress, ExportSummary, export_saver_png_sequence, select_saver};
16pub use ram_cache::{
17 DEFAULT_RAM_CACHE_MB, PrefetchJob, RamFrame, RamFrameCache, RamFrameKey, RamPrefetcher,
18};
crates/engine/src/media.rs+13
...@@ -460,6 +460,19 @@ impl MediaCache {...@@ -460,6 +460,19 @@ impl MediaCache {
460 self.total_bytes = 0;460 self.total_bytes = 0;
461 }461 }
462462
463 pub fn set_budget_mb(&mut self, budget_mb: u64) {
464 self.budget_bytes = budget_mb.saturating_mul(1024 * 1024);
465 while self.total_bytes > self.budget_bytes && self.images.len() > 1 {
466 let Some((oldest_key, _)) = self.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else {
467 break;
468 };
469 self.lru.remove(&oldest_key);
470 if let Some(removed) = self.images.remove(&oldest_key) {
471 self.total_bytes = self.total_bytes.saturating_sub(removed.byte_size());
472 }
473 }
474 }
475
463 pub fn entry_count(&self) -> usize {476 pub fn entry_count(&self) -> usize {
464 self.images.len()477 self.images.len()
465 }478 }
crates/engine/src/ram_cache.rs created+566
...@@ -0,0 +1,566 @@
1//! Thread-safe LRU RAM frame cache and cancellable background lookahead pre-fetcher.
2//!
3//! Designed for real-time 24fps+ playback and instant scrubbing:
4//! - `RamFrameCache` stores finished premultiplied RGBA8 frames keyed by
5//! `(NodeId, comp.revision, frame, proxy_scale, hiq, use_proxy_clips)` under a hard byte cap.
6//! - `cached_frame_ranges` reports contiguous `[start, end]` cached intervals for timeline display.
7//! - `RamPrefetcher` runs lookahead evaluation on a background thread with an atomic generation
8//! counter so scrubbing or editing cancels stale pre-fetch work immediately.
9
10use crate::eval::Engine;
11use model::{Comp, NodeId};
12use std::collections::HashMap;
13use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
14use std::sync::{Arc, Condvar, Mutex};
15use std::thread::{self, JoinHandle};
16
17/// Default RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames).
18pub const DEFAULT_RAM_CACHE_MB: u64 = 1024;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub struct RamFrameKey {
22 pub target: NodeId,
23 pub revision: u64,
24 pub frame: i64,
25 pub proxy_scale: u32,
26 pub hiq: bool,
27 pub use_proxy_clips: bool,
28}
29
30#[derive(Clone, Debug)]
31pub struct RamFrame {
32 pub size: [u32; 2],
33 /// Premultiplied RGBA8 pixels, top-down (`size[0] * size[1] * 4` bytes).
34 pub rgba: Arc<Vec<u8>>,
35 pub eval_ms: f64,
36}
37
38impl RamFrame {
39 pub fn byte_size(&self) -> u64 {
40 self.rgba.len() as u64
41 }
42}
43
44struct RamEntry {
45 frame: RamFrame,
46 last_used: u64,
47}
48
49struct RamCacheInner {
50 budget_bytes: u64,
51 entries: HashMap<RamFrameKey, RamEntry>,
52 total_bytes: u64,
53 tick: u64,
54 evictions: u64,
55}
56
57impl RamCacheInner {
58 fn evict_over_budget(&mut self) {
59 while self.total_bytes > self.budget_bytes && !self.entries.is_empty() {
60 let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used) else {
61 break;
62 };
63 if let Some(removed) = self.entries.remove(&oldest_key) {
64 self.total_bytes = self.total_bytes.saturating_sub(removed.frame.byte_size());
65 self.evictions += 1;
66 }
67 }
68 }
69}
70
71/// Shareable, thread-safe LRU RAM frame cache.
72#[derive(Clone)]
73pub struct RamFrameCache {
74 inner: Arc<Mutex<RamCacheInner>>,
75}
76
77impl Default for RamFrameCache {
78 fn default() -> Self {
79 Self::new(DEFAULT_RAM_CACHE_MB)
80 }
81}
82
83impl RamFrameCache {
84 pub fn new(budget_mb: u64) -> Self {
85 Self {
86 inner: Arc::new(Mutex::new(RamCacheInner {
87 budget_bytes: budget_mb.saturating_mul(1024 * 1024),
88 entries: HashMap::new(),
89 total_bytes: 0,
90 tick: 0,
91 evictions: 0,
92 })),
93 }
94 }
95
96 pub fn set_budget_mb(&self, budget_mb: u64) {
97 if let Ok(mut guard) = self.inner.lock() {
98 guard.budget_bytes = budget_mb.saturating_mul(1024 * 1024);
99 guard.evict_over_budget();
100 }
101 }
102
103 pub fn budget_mb(&self) -> u64 {
104 self.inner
105 .lock()
106 .map(|g| g.budget_bytes / (1024 * 1024))
107 .unwrap_or(0)
108 }
109
110 pub fn get(&self, key: RamFrameKey) -> Option<RamFrame> {
111 let mut guard = self.inner.lock().ok()?;
112 guard.tick += 1;
113 let tick = guard.tick;
114 let entry = guard.entries.get_mut(&key)?;
115 entry.last_used = tick;
116 Some(entry.frame.clone())
117 }
118
119 pub fn contains(&self, key: RamFrameKey) -> bool {
120 self.inner
121 .lock()
122 .map(|g| g.entries.contains_key(&key))
123 .unwrap_or(false)
124 }
125
126 pub fn insert(&self, key: RamFrameKey, frame: RamFrame) {
127 let Ok(mut guard) = self.inner.lock() else {
128 return;
129 };
130 let bytes = frame.byte_size();
131 if guard.budget_bytes == 0 || bytes > guard.budget_bytes {
132 return;
133 }
134 guard.tick += 1;
135 let tick = guard.tick;
136 if let Some(old) = guard.entries.remove(&key) {
137 guard.total_bytes = guard.total_bytes.saturating_sub(old.frame.byte_size());
138 }
139 guard.total_bytes += bytes;
140 guard.entries.insert(key, RamEntry { frame, last_used: tick });
141 guard.evict_over_budget();
142 }
143
144 pub fn clear(&self) {
145 if let Ok(mut guard) = self.inner.lock() {
146 guard.entries.clear();
147 guard.total_bytes = 0;
148 }
149 }
150
151 /// Evicts cached frames belonging to older composition revisions.
152 pub fn invalidate_other_revisions(&self, keep_revision: u64) -> usize {
153 let Ok(mut guard) = self.inner.lock() else {
154 return 0;
155 };
156 let stale: Vec<RamFrameKey> = guard
157 .entries
158 .keys()
159 .copied()
160 .filter(|k| k.revision != keep_revision)
161 .collect();
162 let count = stale.len();
163 for k in stale {
164 if let Some(removed) = guard.entries.remove(&k) {
165 guard.total_bytes = guard.total_bytes.saturating_sub(removed.frame.byte_size());
166 }
167 }
168 count
169 }
170
171 /// Returns sorted, merged inclusive `[start, end]` frame ranges currently cached
172 /// for the specified target node, revision, and quality settings.
173 pub fn cached_frame_ranges(
174 &self,
175 target: NodeId,
176 revision: u64,
177 proxy_scale: u32,
178 hiq: bool,
179 use_proxy_clips: bool,
180 ) -> Vec<(i64, i64)> {
181 let Ok(guard) = self.inner.lock() else {
182 return Vec::new();
183 };
184 let mut frames: Vec<i64> = guard
185 .entries
186 .keys()
187 .filter(|k| {
188 k.target == target
189 && k.revision == revision
190 && k.proxy_scale == proxy_scale
191 && k.hiq == hiq
192 && k.use_proxy_clips == use_proxy_clips
193 })
194 .map(|k| k.frame)
195 .collect();
196 if frames.is_empty() {
197 return Vec::new();
198 }
199 frames.sort_unstable();
200 frames.dedup();
201 let mut ranges = Vec::new();
202 let mut start = frames[0];
203 let mut prev = frames[0];
204 for &f in &frames[1..] {
205 if f == prev + 1 {
206 prev = f;
207 } else {
208 ranges.push((start, prev));
209 start = f;
210 prev = f;
211 }
212 }
213 ranges.push((start, prev));
214 ranges
215 }
216
217 pub fn entry_count(&self) -> usize {
218 self.inner.lock().map(|g| g.entries.len()).unwrap_or(0)
219 }
220
221 pub fn total_bytes(&self) -> u64 {
222 self.inner.lock().map(|g| g.total_bytes).unwrap_or(0)
223 }
224
225 pub fn total_mb(&self) -> f64 {
226 self.total_bytes() as f64 / (1024.0 * 1024.0)
227 }
228
229 pub fn eviction_count(&self) -> u64 {
230 self.inner.lock().map(|g| g.evictions).unwrap_or(0)
231 }
232}
233
234/// Parameters for a background lookahead pre-fetch window.
235#[derive(Clone)]
236pub struct PrefetchJob {
237 pub comp: Comp,
238 pub target: NodeId,
239 pub center_frame: i64,
240 pub range: [i64; 2],
241 pub lookahead: i64,
242 pub proxy_scale: u32,
243 pub hiq: bool,
244 pub use_proxy_clips: bool,
245}
246
247struct WorkerSlot {
248 job: Option<(u64, PrefetchJob)>,
249 shutdown: bool,
250}
251
252/// Background lookahead frame pre-fetcher backed by a dedicated headless `Engine`.
253///
254/// Calling `request_lookahead` or `cancel` immediately increments an atomic generation
255/// counter so any in-flight lookahead loop aborts before evaluating another frame.
256pub struct RamPrefetcher {
257 cache: RamFrameCache,
258 vram_budget_mb: u64,
259 generation: Arc<AtomicU64>,
260 busy: Arc<AtomicBool>,
261 completed_frames: Arc<AtomicU64>,
262 slot: Arc<(Mutex<WorkerSlot>, Condvar)>,
263 worker: Option<JoinHandle<()>>,
264}
265
266impl RamPrefetcher {
267 pub fn new(cache: RamFrameCache, worker_vram_budget_mb: u64) -> Self {
268 Self {
269 cache,
270 vram_budget_mb: worker_vram_budget_mb.max(128),
271 generation: Arc::new(AtomicU64::new(1)),
272 busy: Arc::new(AtomicBool::new(false)),
273 completed_frames: Arc::new(AtomicU64::new(0)),
274 slot: Arc::new((
275 Mutex::new(WorkerSlot {
276 job: None,
277 shutdown: false,
278 }),
279 Condvar::new(),
280 )),
281 worker: None,
282 }
283 }
284
285 pub fn cache(&self) -> &RamFrameCache {
286 &self.cache
287 }
288
289 pub fn is_busy(&self) -> bool {
290 self.busy.load(Ordering::Acquire)
291 }
292
293 pub fn completed_frames(&self) -> u64 {
294 self.completed_frames.load(Ordering::Acquire)
295 }
296
297 /// Cancels any active lookahead pass immediately.
298 pub fn cancel(&self) {
299 self.generation.fetch_add(1, Ordering::AcqRel);
300 if let Ok(mut guard) = self.slot.0.lock() {
301 guard.job = None;
302 }
303 }
304
305 /// Schedules background lookahead rendering starting at `job.center_frame + 1`
306 /// through `min(job.range[1], job.center_frame + job.lookahead)`, wrapping or
307 /// skipping frames that are already cached. Cancels any superseded request.
308 pub fn request_lookahead(&mut self, job: PrefetchJob) {
309 self.ensure_worker();
310 let job_gen = self.generation.fetch_add(1, Ordering::AcqRel) + 1;
311 if let Ok(mut guard) = self.slot.0.lock() {
312 guard.job = Some((job_gen, job));
313 self.slot.1.notify_one();
314 }
315 }
316
317 fn ensure_worker(&mut self) {
318 if self.worker.is_some() {
319 return;
320 }
321 let cache = self.cache.clone();
322 let vram_mb = self.vram_budget_mb;
323 let generation = self.generation.clone();
324 let busy = self.busy.clone();
325 let completed = self.completed_frames.clone();
326 let slot = self.slot.clone();
327
328 let handle = thread::Builder::new()
329 .name("fission-ram-prefetch".to_owned())
330 .spawn(move || {
331 let mut engine_opt: Option<Engine> = None;
332 let mut last_comp_rev: Option<u64> = None;
333
334 loop {
335 let (job_gen, job) = {
336 let Ok(mut guard) = slot.0.lock() else {
337 break;
338 };
339 while !guard.shutdown && guard.job.is_none() {
340 guard = match slot.1.wait(guard) {
341 Ok(g) => g,
342 Err(_) => return,
343 };
344 }
345 if guard.shutdown {
346 break;
347 }
348 match guard.job.take() {
349 Some(item) => item,
350 None => continue,
351 }
352 };
353
354 if generation.load(Ordering::Acquire) != job_gen {
355 continue;
356 }
357
358 if engine_opt.is_none() {
359 match Engine::new_headless() {
360 Ok(mut eng) => {
361 eng.set_vram_budget_mb(vram_mb);
362 engine_opt = Some(eng);
363 }
364 Err(_) => {
365 // Headless GPU unavailable; stay idle until shutdown.
366 continue;
367 }
368 }
369 }
370
371 let Some(engine) = engine_opt.as_mut() else {
372 continue;
373 };
374
375 if last_comp_rev != Some(job.comp.revision) {
376 engine.bust_gpu_cache();
377 last_comp_rev = Some(job.comp.revision);
378 }
379 engine.proxy_scale = job.proxy_scale.max(1);
380 engine.hiq = job.hiq;
381 engine.use_proxy_clips = job.use_proxy_clips;
382
383 busy.store(true, Ordering::Release);
384 let start = job.range[0].min(job.range[1]);
385 let end = job.range[0].max(job.range[1]);
386 let count = job.lookahead.max(0);
387
388 for offset in 1..=count {
389 if generation.load(Ordering::Acquire) != job_gen {
390 break;
391 }
392 let f = job.center_frame + offset;
393 if f < start || f > end {
394 break;
395 }
396 let key = RamFrameKey {
397 target: job.target,
398 revision: job.comp.revision,
399 frame: f,
400 proxy_scale: engine.proxy_scale,
401 hiq: engine.hiq,
402 use_proxy_clips: engine.use_proxy_clips,
403 };
404 if cache.contains(key) {
405 continue;
406 }
407 let (tex, stats) = engine.evaluate(&job.comp, job.target, f as f64);
408 if generation.load(Ordering::Acquire) != job_gen {
409 break;
410 }
411 if let Ok(rgba) = engine.readback_rgba(&tex) {
412 cache.insert(
413 key,
414 RamFrame {
415 size: tex.size,
416 rgba: Arc::new(rgba),
417 eval_ms: stats.eval_ms,
418 },
419 );
420 completed.fetch_add(1, Ordering::AcqRel);
421 }
422 }
423 busy.store(false, Ordering::Release);
424 }
425 })
426 .ok();
427
428 self.worker = handle;
429 }
430}
431
432impl Drop for RamPrefetcher {
433 fn drop(&mut self) {
434 self.generation.fetch_add(1, Ordering::AcqRel);
435 if let Ok(mut guard) = self.slot.0.lock() {
436 guard.shutdown = true;
437 guard.job = None;
438 self.slot.1.notify_all();
439 }
440 if let Some(handle) = self.worker.take() {
441 let _ = handle.join();
442 }
443 }
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449 use std::time::{Duration, Instant};
450
451 fn dummy_frame(w: u32, h: u32) -> RamFrame {
452 RamFrame {
453 size: [w, h],
454 rgba: Arc::new(vec![128u8; (w * h * 4) as usize]),
455 eval_ms: 1.5,
456 }
457 }
458
459 #[test]
460 fn ram_cache_enforces_budget_lru_and_merges_ranges() {
461 // 4 MB budget -> holds at most 4 frames of 1 MB each (512x512 RGBA8 = 1 MB)
462 let cache = RamFrameCache::new(4);
463 let node = NodeId(0);
464 for f in [10, 11, 12, 14] {
465 cache.insert(
466 RamFrameKey {
467 target: node,
468 revision: 1,
469 frame: f,
470 proxy_scale: 1,
471 hiq: true,
472 use_proxy_clips: false,
473 },
474 dummy_frame(512, 512),
475 );
476 }
477 assert_eq!(cache.entry_count(), 4);
478 assert_eq!(
479 cache.cached_frame_ranges(node, 1, 1, true, false),
480 vec![(10, 12), (14, 14)]
481 );
482
483 // Touch frame 10 so frame 11 becomes LRU, then insert frame 15.
484 assert!(cache
485 .get(RamFrameKey {
486 target: node,
487 revision: 1,
488 frame: 10,
489 proxy_scale: 1,
490 hiq: true,
491 use_proxy_clips: false,
492 })
493 .is_some());
494 cache.insert(
495 RamFrameKey {
496 target: node,
497 revision: 1,
498 frame: 15,
499 proxy_scale: 1,
500 hiq: true,
501 use_proxy_clips: false,
502 },
503 dummy_frame(512, 512),
504 );
505 assert_eq!(cache.entry_count(), 4);
506 assert!(cache.eviction_count() >= 1);
507 assert_eq!(
508 cache.cached_frame_ranges(node, 1, 1, true, false),
509 vec![(10, 10), (12, 12), (14, 15)]
510 );
511
512 // Revision invalidation drops old revisions cleanly
513 let evicted = cache.invalidate_other_revisions(2);
514 assert_eq!(evicted, 4);
515 assert_eq!(cache.entry_count(), 0);
516 }
517
518 #[test]
519 fn ram_prefetcher_renders_lookahead_and_cancels_cleanly() {
520 let comp_src = r#"
521Composition {
522 CurrentTime = 0,
523 RenderRange = { 0, 10 },
524 GlobalRange = { 0, 10 },
525 Tools = ordered() {
526 BG1 = Background {
527 Inputs = {
528 Width = Input { Value = 64, },
529 Height = Input { Value = 64, },
530 TopLeftRed = Input { Value = 0.5, },
531 TopLeftAlpha = Input { Value = 1.0, },
532 },
533 },
534 },
535}
536"#;
537 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
538 let target = comp.find_node("BG1").expect("BG1");
539
540 let cache = RamFrameCache::new(64);
541 let mut prefetcher = RamPrefetcher::new(cache.clone(), 128);
542 prefetcher.request_lookahead(PrefetchJob {
543 comp: comp.clone(),
544 target,
545 center_frame: 0,
546 range: [0, 10],
547 lookahead: 4,
548 proxy_scale: 1,
549 hiq: true,
550 use_proxy_clips: false,
551 });
552
553 let deadline = Instant::now() + Duration::from_secs(10);
554 while Instant::now() < deadline {
555 if cache.cached_frame_ranges(target, comp.revision, 1, true, false) == vec![(1, 4)] {
556 break;
557 }
558 thread::sleep(Duration::from_millis(20));
559 }
560 assert_eq!(
561 cache.cached_frame_ranges(target, comp.revision, 1, true, false),
562 vec![(1, 4)]
563 );
564 prefetcher.cancel();
565 }
566}
crates/engine/src/scene3d.rs+779-74
...@@ -27,10 +27,12 @@ struct MeshUniform {...@@ -27,10 +27,12 @@ struct MeshUniform {
27 model: [f32; 16],27 model: [f32; 16],
28 /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture)28 /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture)
29 dod: [f32; 4],29 dod: [f32; 4],
30 /// `[use_tex, lighting_enabled, roughness, 0]`30 /// `[use_tex, lighting_enabled, specular_intensity, flip_normals]`
31 flags: [f32; 4],31 flags: [f32; 4],
32 /// Diffuse color multiplier `(r, g, b, a)`32 /// Diffuse color multiplier `(r, g, b, a)`
33 diffuse_col: [f32; 4],33 diffuse_col: [f32; 4],
34 /// Specular color `(r, g, b, shininess_exponent)`
35 specular_col: [f32; 4],
34 /// Ambient light `(r, g, b, 0)`36 /// Ambient light `(r, g, b, 0)`
35 ambient: [f32; 4],37 ambient: [f32; 4],
36 /// Directional light direction TO light `(dx, dy, dz, has_dir)`38 /// Directional light direction TO light `(dx, dy, dz, has_dir)`
...@@ -39,6 +41,18 @@ struct MeshUniform {...@@ -39,6 +41,18 @@ struct MeshUniform {
39 dir_color: [f32; 4],41 dir_color: [f32; 4],
40 /// Camera world position `(cx, cy, cz, 0)`42 /// Camera world position `(cx, cy, cz, 0)`
41 cam_pos: [f32; 4],43 cam_pos: [f32; 4],
44 /// `[num_point_lights, num_spot_lights, 0, 0]`
45 light_counts: [f32; 4],
46 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`
47 point_pos: [[f32; 4]; 4],
48 /// Point light colors * intensity `(r, g, b, decay_rate)`
49 point_col: [[f32; 4]; 4],
50 /// Spot light positions `(x, y, z, cos_inner)`
51 spot_pos: [[f32; 4]; 4],
52 /// Spot light forward directions `(dx, dy, dz, cos_outer)`
53 spot_dir: [[f32; 4]; 4],
54 /// Spot light colors * intensity `(r, g, b, decay_type)`
55 spot_col: [[f32; 4]; 4],
42}56}
4357
44const SHADER_3D: &str = r#"58const SHADER_3D: &str = r#"
...@@ -48,10 +62,17 @@ struct MeshUniform {...@@ -48,10 +62,17 @@ struct MeshUniform {
48 dod: vec4<f32>,62 dod: vec4<f32>,
49 flags: vec4<f32>,63 flags: vec4<f32>,
50 diffuse_col: vec4<f32>,64 diffuse_col: vec4<f32>,
65 specular_col: vec4<f32>,
51 ambient: vec4<f32>,66 ambient: vec4<f32>,
52 dir_to_light: vec4<f32>,67 dir_to_light: vec4<f32>,
53 dir_color: vec4<f32>,68 dir_color: vec4<f32>,
54 cam_pos: vec4<f32>,69 cam_pos: vec4<f32>,
70 light_counts: vec4<f32>,
71 point_pos: array<vec4<f32>, 4>,
72 point_col: array<vec4<f32>, 4>,
73 spot_pos: array<vec4<f32>, 4>,
74 spot_dir: array<vec4<f32>, 4>,
75 spot_col: array<vec4<f32>, 4>,
55};76};
5677
57@group(0) @binding(0) var<uniform> u: MeshUniform;78@group(0) @binding(0) var<uniform> u: MeshUniform;
...@@ -80,7 +101,46 @@ fn vs_mesh(v: VsIn) -> VsOut {...@@ -80,7 +101,46 @@ fn vs_mesh(v: VsIn) -> VsOut {
80 out.world_pos = wp.xyz;101 out.world_pos = wp.xyz;
81 let wn = (u.model * vec4<f32>(v.normal, 0.0)).xyz;102 let wn = (u.model * vec4<f32>(v.normal, 0.0)).xyz;
82 let nlen = length(wn);103 let nlen = length(wn);
83 out.world_n = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5);104 var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5);
105 if (u.flags.w > 0.5) {
106 n_norm = -n_norm;
107 }
108 out.world_n = n_norm;
109 return out;
110}
111
112fn light_attenuation(dist: f32, decay_type: f32, decay_rate: f32) -> f32 {
113 let dt = i32(decay_type + 0.5);
114 let rate = max(decay_rate, 0.001);
115 if (dt == 1) {
116 return 1.0 / max(1.0 + dist * rate, 1e-4);
117 } else if (dt == 2) {
118 let d = dist * rate;
119 return 1.0 / max(1.0 + d * d, 1e-4);
120 }
121 return 1.0;
122}
123
124fn eval_light_contrib(
125 n: vec3<f32>,
126 v: vec3<f32>,
127 l: vec3<f32>,
128 light_rgb: vec3<f32>,
129 albedo: vec3<f32>,
130 spec_rgb: vec3<f32>,
131 spec_int: f32,
132 shininess: f32,
133) -> vec3<f32> {
134 let ndotl = max(dot(n, l), 0.0);
135 if (ndotl <= 0.0) {
136 return vec3<f32>(0.0);
137 }
138 var out = albedo * light_rgb * ndotl;
139 if (spec_int > 1e-4) {
140 let h = normalize(l + v);
141 let spec = pow(max(dot(n, h), 0.0), shininess) * spec_int;
142 out = out + light_rgb * spec_rgb * spec;
143 }
84 return out;144 return out;
85}145}
86146
...@@ -107,20 +167,43 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -107,20 +167,43 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
107 // Premultiplied -> unpremultiplied albedo for lighting167 // Premultiplied -> unpremultiplied albedo for lighting
108 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);168 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);
109 let n = normalize(in.world_n);169 let n = normalize(in.world_n);
170 let v = normalize(u.cam_pos.xyz - in.world_pos);
171 let spec_rgb = u.specular_col.rgb;
172 let shininess = max(u.specular_col.w, 1.0);
173 let spec_int = u.flags.z;
174
110 var lit = albedo * u.ambient.rgb;175 var lit = albedo * u.ambient.rgb;
111 if (u.dir_to_light.w > 0.5) {176 if (u.dir_to_light.w > 0.5) {
112 let l = normalize(u.dir_to_light.xyz);177 let l = normalize(u.dir_to_light.xyz);
113 let ndotl = max(dot(n, l), 0.0);178 lit = lit + eval_light_contrib(n, v, l, u.dir_color.rgb, albedo, spec_rgb, spec_int, shininess);
114 lit = lit + albedo * u.dir_color.rgb * ndotl;179 }
115 if (ndotl > 0.0) {180
116 let v = normalize(u.cam_pos.xyz - in.world_pos);181 let n_pt = i32(u.light_counts.x + 0.5);
117 let h = normalize(l + v);182 for (var i: i32 = 0; i < 4; i = i + 1) {
118 let rough = clamp(u.flags.z, 0.05, 1.0);183 if (i >= n_pt) { break; }
119 let shininess = max(2.0 / (rough * rough) - 2.0, 2.0);184 let to_l = u.point_pos[i].xyz - in.world_pos;
120 let spec = pow(max(dot(n, h), 0.0), shininess) * (1.0 - rough * 0.85) * 0.25;185 let dist = max(length(to_l), 1e-4);
121 lit = lit + u.dir_color.rgb * spec;186 let att = light_attenuation(dist, u.point_pos[i].w, u.point_col[i].w);
187 lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);
188 }
189
190 let n_sp = i32(u.light_counts.y + 0.5);
191 for (var i: i32 = 0; i < 4; i = i + 1) {
192 if (i >= n_sp) { break; }
193 let to_l = u.spot_pos[i].xyz - in.world_pos;
194 let dist = max(length(to_l), 1e-4);
195 let l_dir = to_l / dist;
196 // spot_dir.xyz is direction spotlight points; fragment direction from light is -l_dir
197 let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz));
198 let cos_inner = u.spot_pos[i].w;
199 let cos_outer = u.spot_dir[i].w;
200 let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0);
201 if (cone > 0.0) {
202 let att = light_attenuation(dist, u.spot_col[i].w, 1.0) * cone;
203 lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess);
122 }204 }
123 }205 }
206
124 col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a);207 col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a);
125 }208 }
126 return col;209 return col;
...@@ -146,8 +229,31 @@ pub enum ShapeKind {...@@ -146,8 +229,31 @@ pub enum ShapeKind {
146 ImagePlane,229 ImagePlane,
147 Sphere { radius: f32, sub_base: u32, sub_height: u32 },230 Sphere { radius: f32, sub_base: u32, sub_height: u32 },
148 Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 },231 Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 },
149 Plane { width: f32, height: f32 },232 Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 },
150 Cube { width: f32, height: f32, depth: f32 },233 Cube { width: f32, height: f32, depth: f32 },
234 TextPlate { width: f32, height: f32, depth: f32, slices: u32 },
235}
236
237#[derive(Clone, Debug)]
238pub struct Displace3DSpec {
239 pub input_node: NodeId,
240 pub scale: f32,
241 pub bias: f32,
242 pub channel: i32, // 0=R, 1=G, 2=B, 3=A, 4=Luma (default)
243}
244
245#[derive(Clone, Debug)]
246pub struct DisplaceHeightmap {
247 pub size: [u32; 2],
248 pub rgba: Vec<u8>,
249 pub scale: f32,
250 pub bias: f32,
251 pub channel: i32,
252}
253
254#[derive(Clone, Debug)]
255pub struct Text3DSpec {
256 pub node_id: NodeId,
151}257}
152258
153#[derive(Clone)]259#[derive(Clone)]
...@@ -155,16 +261,42 @@ pub struct MeshInstance {...@@ -155,16 +261,42 @@ pub struct MeshInstance {
155 pub world: Mat4,261 pub world: Mat4,
156 pub shape: ShapeKind,262 pub shape: ShapeKind,
157 pub material_node: Option<NodeId>,263 pub material_node: Option<NodeId>,
264 pub text3d: Option<Text3DSpec>,
158 pub diffuse_col: [f32; 4],265 pub diffuse_col: [f32; 4],
159 pub roughness: f32,266 pub specular_col: [f32; 3],
267 pub specular_intensity: f32,
268 pub specular_exponent: f32,
269 pub affected_by_lights: bool,
270 pub flip_normals: bool,
271 pub displace: Option<Displace3DSpec>,
160}272}
161273
162#[derive(Clone, Copy, Debug)]274#[derive(Clone, Copy, Debug)]
275pub struct PointLight {
276 pub pos: [f32; 3],
277 pub color: [f32; 3],
278 pub decay_type: f32,
279 pub decay_rate: f32,
280}
281
282#[derive(Clone, Copy, Debug)]
283pub struct SpotLight {
284 pub pos: [f32; 3],
285 pub dir: [f32; 3],
286 pub color: [f32; 3],
287 pub cos_inner: f32,
288 pub cos_outer: f32,
289 pub decay_type: f32,
290}
291
292#[derive(Clone, Debug)]
163pub struct SceneLights {293pub struct SceneLights {
164 pub ambient: [f32; 3],294 pub ambient: [f32; 3],
165 pub dir_to_light: [f32; 3],295 pub dir_to_light: [f32; 3],
166 pub dir_color: [f32; 3],296 pub dir_color: [f32; 3],
167 pub has_dir: bool,297 pub has_dir: bool,
298 pub points: Vec<PointLight>,
299 pub spots: Vec<SpotLight>,
168}300}
169301
170impl Default for SceneLights {302impl Default for SceneLights {
...@@ -174,6 +306,8 @@ impl Default for SceneLights {...@@ -174,6 +306,8 @@ impl Default for SceneLights {
174 dir_to_light: [0.0, 0.0, 1.0],306 dir_to_light: [0.0, 0.0, 1.0],
175 dir_color: [0.0, 0.0, 0.0],307 dir_color: [0.0, 0.0, 0.0],
176 has_dir: false,308 has_dir: false,
309 points: Vec::new(),
310 spots: Vec::new(),
177 }311 }
178 }312 }
179}313}
...@@ -183,7 +317,12 @@ pub struct DrawMesh {...@@ -183,7 +317,12 @@ pub struct DrawMesh {
183 pub shape: ShapeKind,317 pub shape: ShapeKind,
184 pub tex: Option<CachedTexture>,318 pub tex: Option<CachedTexture>,
185 pub diffuse_col: [f32; 4],319 pub diffuse_col: [f32; 4],
186 pub roughness: f32,320 pub specular_col: [f32; 3],
321 pub specular_intensity: f32,
322 pub specular_exponent: f32,
323 pub affected_by_lights: bool,
324 pub flip_normals: bool,
325 pub displace: Option<DisplaceHeightmap>,
187}326}
188327
189impl Scene3DRenderer {328impl Scene3DRenderer {
...@@ -343,10 +482,13 @@ impl Scene3DRenderer {...@@ -343,10 +482,13 @@ impl Scene3DRenderer {
343 .as_ref()482 .as_ref()
344 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))483 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))
345 .unwrap_or(16.0 / 9.0);484 .unwrap_or(16.0 / 9.0);
346 let (verts, indices) = build_shape_mesh(&m.shape, aspect);485 let (mut verts, indices) = build_shape_mesh(&m.shape, aspect);
347 if indices.is_empty() {486 if indices.is_empty() {
348 continue;487 continue;
349 }488 }
489 if let Some(disp) = &m.displace {
490 apply_heightmap_displace(&mut verts, &indices, disp);
491 }
350 let vbytes = bytemuck::cast_slice(&verts);492 let vbytes = bytemuck::cast_slice(&verts);
351 let ibytes = bytemuck::cast_slice(&indices);493 let ibytes = bytemuck::cast_slice(&indices);
352 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {494 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {
...@@ -374,17 +516,39 @@ impl Scene3DRenderer {...@@ -374,17 +516,39 @@ impl Scene3DRenderer {
374 } else {516 } else {
375 [0.0; 4]517 [0.0; 4]
376 };518 };
519 let mut point_pos = [[0.0_f32; 4]; 4];
520 let mut point_col = [[0.0_f32; 4]; 4];
521 let n_pt = lights.points.len().min(4);
522 for (pi, pl) in lights.points.iter().take(4).enumerate() {
523 point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type];
524 point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], pl.decay_rate];
525 }
526 let mut spot_pos = [[0.0_f32; 4]; 4];
527 let mut spot_dir = [[0.0_f32; 4]; 4];
528 let mut spot_col = [[0.0_f32; 4]; 4];
529 let n_sp = lights.spots.len().min(4);
530 for (si, sl) in lights.spots.iter().take(4).enumerate() {
531 spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner];
532 spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer];
533 spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type];
534 }
377 let uni = MeshUniform {535 let uni = MeshUniform {
378 mvp,536 mvp,
379 model: m.world,537 model: m.world,
380 dod,538 dod,
381 flags: [539 flags: [
382 if m.tex.is_some() { 1.0 } else { 0.0 },540 if m.tex.is_some() { 1.0 } else { 0.0 },
383 if lighting_enabled { 1.0 } else { 0.0 },541 if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 },
384 m.roughness,542 m.specular_intensity,
385 0.0,543 if m.flip_normals { 1.0 } else { 0.0 },
386 ],544 ],
387 diffuse_col: m.diffuse_col,545 diffuse_col: m.diffuse_col,
546 specular_col: [
547 m.specular_col[0],
548 m.specular_col[1],
549 m.specular_col[2],
550 m.specular_exponent,
551 ],
388 ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0],552 ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0],
389 dir_to_light: [553 dir_to_light: [
390 lights.dir_to_light[0],554 lights.dir_to_light[0],
...@@ -394,6 +558,12 @@ impl Scene3DRenderer {...@@ -394,6 +558,12 @@ impl Scene3DRenderer {
394 ],558 ],
395 dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0],559 dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0],
396 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],560 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],
561 light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0],
562 point_pos,
563 point_col,
564 spot_pos,
565 spot_dir,
566 spot_col,
397 };567 };
398 let ubuf = device.create_buffer(&wgpu::BufferDescriptor {568 let ubuf = device.create_buffer(&wgpu::BufferDescriptor {
399 label: Some("scene3d-u"),569 label: Some("scene3d-u"),
...@@ -466,16 +636,53 @@ fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u...@@ -466,16 +636,53 @@ fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u
466 ];636 ];
467 (verts, vec![0, 1, 2, 0, 2, 3])637 (verts, vec![0, 1, 2, 0, 2, 3])
468 }638 }
469 ShapeKind::Plane { width, height } => {639 ShapeKind::Plane { width, height, sub_w, sub_h } => {
640 let sw = sub_w.clamp(1, 64);
641 let sh = sub_h.clamp(1, 64);
470 let hx = width * 0.5;642 let hx = width * 0.5;
471 let hy = height * 0.5;643 let hy = height * 0.5;
472 let verts = vec![644 let mut verts = Vec::with_capacity(((sw + 1) * (sh + 1)) as usize);
473 Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] },645 let mut idx = Vec::with_capacity((sw * sh * 6) as usize);
474 Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] },646 for iy in 0..=sh {
475 Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] },647 let v = iy as f32 / sh as f32;
476 Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] },648 let y = hy - v * height;
477 ];649 for ix in 0..=sw {
478 (verts, vec![0, 1, 2, 0, 2, 3])650 let u = ix as f32 / sw as f32;
651 let x = -hx + u * width;
652 verts.push(Vertex3D { pos: [x, y, 0.0], normal: [0.0, 0.0, 1.0], uv: [u, v] });
653 }
654 }
655 let row = sw + 1;
656 for iy in 0..sh {
657 for ix in 0..sw {
658 let a = iy * row + ix;
659 let b = (iy + 1) * row + ix;
660 let c = (iy + 1) * row + ix + 1;
661 let d = iy * row + ix + 1;
662 idx.extend_from_slice(&[a, b, c, a, c, d]);
663 }
664 }
665 (verts, idx)
666 }
667 ShapeKind::TextPlate { width, height, depth, slices } => {
668 let hx = width * 0.5;
669 let hy = height * 0.5;
670 let n_slices = if depth.abs() > 1e-4 { slices.clamp(2, 16) } else { 1 };
671 let mut verts = Vec::with_capacity((n_slices * 4) as usize);
672 let mut idx = Vec::with_capacity((n_slices * 6) as usize);
673 for s in 0..n_slices {
674 let t = if n_slices == 1 { 0.0 } else { s as f32 / (n_slices - 1) as f32 };
675 // Fusion Text3D extrudes backward along -Z from z=0 to z=-depth
676 let z = -t * depth;
677 let nz = if n_slices > 1 && s == n_slices - 1 { -1.0 } else { 1.0 };
678 let base = verts.len() as u32;
679 verts.push(Vertex3D { pos: [-hx, hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 0.0] });
680 verts.push(Vertex3D { pos: [-hx, -hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 1.0] });
681 verts.push(Vertex3D { pos: [ hx, -hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 1.0] });
682 verts.push(Vertex3D { pos: [ hx, hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 0.0] });
683 idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
684 }
685 (verts, idx)
479 }686 }
480 ShapeKind::Sphere { radius, sub_base, sub_height } => {687 ShapeKind::Sphere { radius, sub_base, sub_height } => {
481 let seg_u = sub_base.clamp(12, 96);688 let seg_u = sub_base.clamp(12, 96);
...@@ -488,7 +695,8 @@ fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u...@@ -488,7 +695,8 @@ fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u
488 let (sp, cp) = phi.sin_cos();695 let (sp, cp) = phi.sin_cos();
489 for iu in 0..=seg_u {696 for iu in 0..=seg_u {
490 let u = iu as f32 / seg_u as f32;697 let u = iu as f32 / seg_u as f32;
491 let theta = u * std::f32::consts::TAU;698 // Fusion Shape3D Sphere places u=0.75 facing +Z (verified via probe_archive_3d f02)
699 let theta = (u - 0.75) * std::f32::consts::TAU;
492 let (st, ct) = theta.sin_cos();700 let (st, ct) = theta.sin_cos();
493 let nx = sp * st;701 let nx = sp * st;
494 let ny = cp;702 let ny = cp;
...@@ -573,8 +781,83 @@ fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u...@@ -573,8 +781,83 @@ fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Vertex3D>, Vec<u
573 }781 }
574}782}
575783
784fn apply_heightmap_displace(verts: &mut [Vertex3D], indices: &[u32], disp: &DisplaceHeightmap) {
785 let w = disp.size[0].max(1) as usize;
786 let h = disp.size[1].max(1) as usize;
787 if disp.rgba.len() < w * h * 4 {
788 return;
789 }
790 for v in verts.iter_mut() {
791 let px = ((v.uv[0].clamp(0.0, 1.0)) * (w - 1) as f32).round() as usize;
792 let py = ((v.uv[1].clamp(0.0, 1.0)) * (h - 1) as f32).round() as usize;
793 let off = (py * w + px) * 4;
794 let r = disp.rgba[off] as f32 / 255.0;
795 let g = disp.rgba[off + 1] as f32 / 255.0;
796 let b = disp.rgba[off + 2] as f32 / 255.0;
797 let a = disp.rgba[off + 3] as f32 / 255.0;
798 let sample = match disp.channel {
799 0 => r,
800 1 => g,
801 2 => b,
802 3 => a,
803 _ => 0.299 * r + 0.587 * g + 0.114 * b,
804 };
805 let d = (sample - 0.5 + disp.bias) * disp.scale;
806 v.pos[0] += v.normal[0] * d;
807 v.pos[1] += v.normal[1] * d;
808 v.pos[2] += v.normal[2] * d;
809 }
810 // Recompute smooth vertex normals from displaced triangles
811 let mut acc = vec![[0.0_f32; 3]; verts.len()];
812 for tri in indices.chunks_exact(3) {
813 let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize);
814 if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() {
815 continue;
816 }
817 let p0 = verts[i0].pos;
818 let p1 = verts[i1].pos;
819 let p2 = verts[i2].pos;
820 let e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]];
821 let e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]];
822 let fn_v = [
823 e1[1] * e2[2] - e1[2] * e2[1],
824 e1[2] * e2[0] - e1[0] * e2[2],
825 e1[0] * e2[1] - e1[1] * e2[0],
826 ];
827 for &i in &[i0, i1, i2] {
828 acc[i][0] += fn_v[0];
829 acc[i][1] += fn_v[1];
830 acc[i][2] += fn_v[2];
831 }
832 }
833 for (v, n) in verts.iter_mut().zip(acc.into_iter()) {
834 let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
835 if len > 1e-6 {
836 v.normal = [n[0] / len, n[1] / len, n[2] / len];
837 }
838 }
839}
840
841#[derive(Clone, Default)]
842struct SceneOverrides {
843 material_override: Option<NodeId>,
844 affected_by_lights: Option<bool>,
845 flip_normals: bool,
846 displace: Option<Displace3DSpec>,
847}
848
849fn splitmix64(mut x: u64) -> f32 {
850 x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
851 x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
852 x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
853 x ^= x >> 31;
854 // Uniform in [-0.5, +0.5]
855 ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5
856}
857
576/// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`,858/// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`,
577/// `ImagePlane3D`, `Shape3D`, `LightAmbient`, `LightDirectional`).859/// `ImagePlane3D`, `Shape3D`, `Text3D`, `LightAmbient`, `LightDirectional`, `LightPoint`,
860/// `LightSpot`, `ReplaceMaterial3D`, `Override3D`, `Duplicate3D`, `ReplaceNormals3D`, `Displace3D`).
578#[allow(clippy::too_many_arguments)]861#[allow(clippy::too_many_arguments)]
579pub fn collect_scene(862pub fn collect_scene(
580 comp: &Comp,863 comp: &Comp,
...@@ -587,6 +870,35 @@ pub fn collect_scene(...@@ -587,6 +870,35 @@ pub fn collect_scene(
587 meshes: &mut Vec<MeshInstance>,870 meshes: &mut Vec<MeshInstance>,
588 lights: &mut SceneLights,871 lights: &mut SceneLights,
589 depth: usize,872 depth: usize,
873) {
874 collect_scene_inner(
875 comp,
876 node_id,
877 time,
878 expr,
879 parent_xform,
880 render_aspect,
881 &SceneOverrides::default(),
882 cameras,
883 meshes,
884 lights,
885 depth,
886 );
887}
888
889#[allow(clippy::too_many_arguments)]
890fn collect_scene_inner(
891 comp: &Comp,
892 node_id: NodeId,
893 time: f64,
894 expr: &ExprEngine,
895 parent_xform: Mat4,
896 render_aspect: f32,
897 ovr: &SceneOverrides,
898 cameras: &mut Vec<CameraInstance>,
899 meshes: &mut Vec<MeshInstance>,
900 lights: &mut SceneLights,
901 depth: usize,
590) {902) {
591 if depth > 32 {903 if depth > 32 {
592 return;904 return;
...@@ -608,10 +920,101 @@ pub fn collect_scene(...@@ -608,10 +920,101 @@ pub fn collect_scene(
608 input_names.sort();920 input_names.sort();
609 for in_name in input_names {921 for in_name in input_names {
610 if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) {922 if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) {
611 collect_scene(comp, src_id, time, expr, world, render_aspect, cameras, meshes, lights, depth + 1);923 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);
612 }924 }
613 }925 }
614 }926 }
927 "ReplaceMaterial3D" => {
928 let mut next_ovr = ovr.clone();
929 if let Some(mid) = node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)) {
930 next_ovr.material_override = Some(mid);
931 }
932 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
933 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1);
934 }
935 }
936 "Override3D" => {
937 let do_vis = comp.eval_number(node, "Visibility.DoVisible", time, 0.0, expr) > 0.5;
938 let is_vis = comp.eval_number(node, "Visibility.IsVisible", time, 1.0, expr) > 0.5;
939 if do_vis && !is_vis {
940 return;
941 }
942 let mut next_ovr = ovr.clone();
943 let do_lit = comp.eval_number(node, "Lighting.DoAffectedByLights", time, 0.0, expr) > 0.5;
944 if do_lit {
945 let is_lit = comp.eval_number(node, "Lighting.IsAffectedByLights", time, 1.0, expr) > 0.5;
946 next_ovr.affected_by_lights = Some(is_lit);
947 }
948 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
949 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1);
950 }
951 }
952 "ReplaceNormals3D" => {
953 let mut next_ovr = ovr.clone();
954 if comp.eval_number(node, "FlipNormals", time, 0.0, expr) > 0.5 {
955 next_ovr.flip_normals = !next_ovr.flip_normals;
956 }
957 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
958 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1);
959 }
960 }
961 "Displace3D" => {
962 let mut next_ovr = ovr.clone();
963 if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {
964 let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32;
965 let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32;
966 let channel = comp.eval_number(node, "Channel", time, 4.0, expr).round() as i32;
967 next_ovr.displace = Some(Displace3DSpec {
968 input_node: in_id,
969 scale,
970 bias,
971 channel,
972 });
973 }
974 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
975 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1);
976 }
977 }
978 "Duplicate3D" => {
979 let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {
980 return;
981 };
982 let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32;
983 let last = comp.eval_number(node, "LastCopy", time, 1.0, expr).round() as i32;
984 let count = (last - first + 1).clamp(0, 256);
985 // Fusion Duplicate3D uses bare `Translate.X/Y/Z`, `Rotate.X/Y/Z`, `Scale.X/Y/Z` (with fallback to `Transform3DOp.*`)
986 let step = eval_duplicate3d_step(comp, node, time, expr);
987 let seed = comp.eval_number(node, "RandomSeed", time, 26024.0, expr).round() as u64;
988 let jtx = comp.eval_number(node, "JitterTranslate.X", time, 0.0, expr) as f32;
989 let jty = comp.eval_number(node, "JitterTranslate.Y", time, 0.0, expr) as f32;
990 let jtz = comp.eval_number(node, "JitterTranslate.Z", time, 0.0, expr) as f32;
991 let jrx = comp.eval_number(node, "JitterRotate.X", time, 0.0, expr) as f32;
992 let jry = comp.eval_number(node, "JitterRotate.Y", time, 0.0, expr) as f32;
993 let jrz = comp.eval_number(node, "JitterRotate.Z", time, 0.0, expr) as f32;
994 let has_jitter = (jtx.abs() + jty.abs() + jtz.abs() + jrx.abs() + jry.abs() + jrz.abs()) > 1e-5;
995
996 let mut acc = mat4_identity();
997 for _ in 0..first.max(0) {
998 acc = mat4_mul(acc, step);
999 }
1000 for i in 0..count {
1001 let copy_idx = (first + i) as u64;
1002 let mut m = mat4_mul(parent_xform, acc);
1003 if has_jitter {
1004 let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407));
1005 let tx = splitmix64(s ^ 1) * jtx;
1006 let ty = splitmix64(s ^ 2) * jty;
1007 let tz = splitmix64(s ^ 3) * jtz;
1008 let rx = (splitmix64(s ^ 4) * jrx).to_radians();
1009 let ry = (splitmix64(s ^ 5) * jry).to_radians();
1010 let rz = (splitmix64(s ^ 6) * jrz).to_radians();
1011 let jm = mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))));
1012 m = mat4_mul(m, jm);
1013 }
1014 collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, depth + 1);
1015 acc = mat4_mul(acc, step);
1016 }
1017 }
615 "Camera3D" => {1018 "Camera3D" => {
616 let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32;1019 let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32;
617 let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32;1020 let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32;
...@@ -667,22 +1070,69 @@ pub fn collect_scene(...@@ -667,22 +1070,69 @@ pub fn collect_scene(
667 lights.dir_color = [r * inten, g * inten, b * inten];1070 lights.dir_color = [r * inten, g * inten, b * inten];
668 lights.has_dir = true;1071 lights.has_dir = true;
669 }1072 }
1073 "LightPoint" => {
1074 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
1075 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
1076 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
1077 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
1078 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
1079 let decay_rate = comp.eval_number(node, "DecayRate", time, 1.0, expr) as f32;
1080 lights.points.push(PointLight {
1081 pos: [world[12], world[13], world[14]],
1082 color: [r * inten, g * inten, b * inten],
1083 decay_type,
1084 decay_rate,
1085 });
1086 }
1087 "LightSpot" => {
1088 let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32;
1089 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
1090 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
1091 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
1092 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;
1093 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;
1094 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
1095 // SpotLight shines along -Z in local space
1096 let dx = -world[8];
1097 let dy = -world[9];
1098 let dz = -world[10];
1099 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
1100 let half_cone = (cone_deg * 0.5).max(0.5);
1101 let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5);
1102 let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg);
1103 lights.spots.push(SpotLight {
1104 pos: [world[12], world[13], world[14]],
1105 dir: [dx / len, dy / len, dz / len],
1106 color: [r * inten, g * inten, b * inten],
1107 cos_inner: inner_deg.to_radians().cos(),
1108 cos_outer: outer_deg.to_radians().cos(),
1109 decay_type,
1110 });
1111 }
670 "ImagePlane3D" => {1112 "ImagePlane3D" => {
671 let mat_node = node1113 let mat_node = ovr.material_override.or_else(|| {
672 .connected_node("MaterialInput")1114 node.connected_node("MaterialInput")
673 .or_else(|| node.connected_node("SceneInput"))1115 .or_else(|| node.connected_node("SceneInput"))
674 .and_then(|s| comp.find_node(s));1116 .and_then(|s| comp.find_node(s))
675 let (tex_node, diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr);1117 });
1118 let mat = resolve_material(comp, mat_node, time, expr);
676 meshes.push(MeshInstance {1119 meshes.push(MeshInstance {
677 world,1120 world,
678 shape: ShapeKind::ImagePlane,1121 shape: ShapeKind::ImagePlane,
679 material_node: tex_node,1122 material_node: mat.tex_node,
680 diffuse_col,1123 text3d: None,
681 roughness,1124 diffuse_col: mat.diffuse_col,
1125 specular_col: mat.specular_col,
1126 specular_intensity: mat.specular_intensity,
1127 specular_exponent: mat.specular_exponent,
1128 affected_by_lights: ovr.affected_by_lights.unwrap_or(true),
1129 flip_normals: ovr.flip_normals,
1130 displace: ovr.displace.clone(),
682 });1131 });
683 }1132 }
684 "Shape3D" => {1133 "Shape3D" => {
685 let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs");1134 let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs");
1135 let disp_sub = if ovr.displace.is_some() { 32 } else { 1 };
686 let shape = match shape_name {1136 let shape = match shape_name {
687 "SurfaceSphereInputs" => ShapeKind::Sphere {1137 "SurfaceSphereInputs" => ShapeKind::Sphere {
688 // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00)1138 // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00)
...@@ -701,22 +1151,32 @@ pub fn collect_scene(...@@ -701,22 +1151,32 @@ pub fn collect_scene(
701 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32,1151 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32,
702 }1152 }
703 }1153 }
704 "SurfaceCubeInputs" => ShapeKind::Cube {1154 "SurfaceCubeInputs" => {
705 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32,1155 let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr);
706 height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, 1.0, expr) as f32,1156 ShapeKind::Cube {
707 depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, 1.0, expr) as f32,1157 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32,
708 },1158 height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32,
709 _ => ShapeKind::Plane {1159 depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32,
710 width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32,1160 }
711 height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32,1161 }
712 },1162 _ => {
1163 let sw = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32;
1164 let sh = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionHeight", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32;
1165 ShapeKind::Plane {
1166 width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32,
1167 height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32,
1168 sub_w: sw,
1169 sub_h: sh,
1170 }
1171 }
713 };1172 };
714 let mat_node = node1173 let mat_node = ovr.material_override.or_else(|| {
715 .connected_node("MaterialInput")1174 node.connected_node("MaterialInput")
716 .and_then(|s| comp.find_node(s));1175 .and_then(|s| comp.find_node(s))
717 let (tex_node, mut diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr);1176 });
1177 let mut mat = resolve_material(comp, mat_node, time, expr);
718 if mat_node.is_none() {1178 if mat_node.is_none() {
719 diffuse_col = [1179 mat.diffuse_col = [
720 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32,1180 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32,
721 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32,1181 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32,
722 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32,1182 comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32,
...@@ -726,50 +1186,149 @@ pub fn collect_scene(...@@ -726,50 +1186,149 @@ pub fn collect_scene(
726 meshes.push(MeshInstance {1186 meshes.push(MeshInstance {
727 world,1187 world,
728 shape,1188 shape,
729 material_node: tex_node,1189 material_node: mat.tex_node,
730 diffuse_col,1190 text3d: None,
731 roughness,1191 diffuse_col: mat.diffuse_col,
1192 specular_col: mat.specular_col,
1193 specular_intensity: mat.specular_intensity,
1194 specular_exponent: mat.specular_exponent,
1195 affected_by_lights: ovr.affected_by_lights.unwrap_or(true),
1196 flip_normals: ovr.flip_normals,
1197 displace: ovr.displace.clone(),
1198 });
1199 }
1200 "Text3D" => {
1201 let ext_depth = comp.eval_number(node, "Extrusion.ExtrusionDepth", time, 0.0, expr) as f32;
1202 let mat_node = ovr.material_override.or_else(|| {
1203 node.connected_node("MaterialInput")
1204 .and_then(|s| comp.find_node(s))
1205 });
1206 let mut mat = resolve_material(comp, mat_node, time, expr);
1207 if mat_node.is_none() {
1208 mat.diffuse_col = [1.0, 1.0, 1.0, 1.0];
1209 }
1210 // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate)
1211 meshes.push(MeshInstance {
1212 world,
1213 shape: ShapeKind::TextPlate {
1214 width: 4.0,
1215 height: 2.0,
1216 depth: ext_depth,
1217 slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 },
1218 },
1219 material_node: mat.tex_node,
1220 text3d: Some(Text3DSpec { node_id }),
1221 diffuse_col: mat.diffuse_col,
1222 specular_col: mat.specular_col,
1223 specular_intensity: mat.specular_intensity,
1224 specular_exponent: mat.specular_exponent,
1225 affected_by_lights: ovr.affected_by_lights.unwrap_or(true),
1226 flip_normals: ovr.flip_normals,
1227 displace: ovr.displace.clone(),
732 });1228 });
733 }1229 }
734 "MacroOperator" | "GroupOperator" => {1230 "MacroOperator" | "GroupOperator" => {
735 if let Some(out_id) = node.macro_output {1231 if let Some(out_id) = node.macro_output {
736 collect_scene(comp, out_id, time, expr, world, render_aspect, cameras, meshes, lights, depth + 1);1232 collect_scene_inner(comp, out_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1);
737 }1233 }
738 }1234 }
739 _ => {}1235 _ => {}
740 }1236 }
741}1237}
7421238
743/// Resolves a 3D material input (either a 2D image node directly or a Fusion 3D material like1239struct ResolvedMaterial {
744/// `MtlCookTorrance` / `MtlBlinn` / `MtlPhong`) to `(diffuse_2d_node, diffuse_rgba, roughness)`.1240 tex_node: Option<NodeId>,
1241 diffuse_col: [f32; 4],
1242 specular_col: [f32; 3],
1243 specular_intensity: f32,
1244 specular_exponent: f32,
1245}
1246
1247/// Resolves a 3D material input (either a 2D image node, `Texture2DOperator`, or a Fusion 3D
1248/// material like `MtlBlinn` / `MtlCookTorrance` / `MtlPhong`).
745fn resolve_material(1249fn resolve_material(
746 comp: &Comp,1250 comp: &Comp,
747 mat_node: Option<NodeId>,1251 mat_node: Option<NodeId>,
748 time: f64,1252 time: f64,
749 expr: &ExprEngine,1253 expr: &ExprEngine,
750) -> (Option<NodeId>, [f32; 4], f32) {1254) -> ResolvedMaterial {
1255 let default_mat = ResolvedMaterial {
1256 tex_node: None,
1257 diffuse_col: [1.0, 1.0, 1.0, 1.0],
1258 specular_col: [1.0, 1.0, 1.0],
1259 specular_intensity: 0.15,
1260 specular_exponent: 25.0,
1261 };
751 let Some(mid) = mat_node else {1262 let Some(mid) = mat_node else {
752 return (None, [1.0, 1.0, 1.0, 1.0], 0.5);1263 return default_mat;
753 };1264 };
754 let n = comp.node(mid);1265 let n = comp.node(mid);
755 if n.kind.starts_with("Mtl") {1266 match n.kind.as_str() {
756 let diff_tex = n1267 "Texture2DOperator" => {
757 .connected_node("Diffuse.Color.Material")1268 let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s));
758 .or_else(|| n.connected_node("MaterialInput"))1269 ResolvedMaterial {
759 .and_then(|s| comp.find_node(s));1270 tex_node: tex_src,
760 let col = [1271 ..default_mat
761 comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32,1272 }
762 comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32,1273 }
763 comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32,1274 "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" => {
764 comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32,1275 let mut diff_tex = n
765 ];1276 .connected_node("Diffuse.Color.Material")
766 let rough = comp.eval_number(n, "Specular.Roughness", time, 0.5, expr) as f32;1277 .or_else(|| n.connected_node("MaterialInput"))
767 (diff_tex, col, rough)1278 .and_then(|s| comp.find_node(s));
768 } else {1279 // Unwrap Texture2DOperator if feeding Diffuse.Color.Material
769 (Some(mid), [1.0, 1.0, 1.0, 1.0], 0.5)1280 if let Some(tid) = diff_tex {
1281 if comp.node(tid).kind == "Texture2DOperator" {
1282 diff_tex = comp.node(tid).connected_node("Input").and_then(|s| comp.find_node(s));
1283 }
1284 }
1285 let col = [
1286 comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32,
1287 comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32,
1288 comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32,
1289 comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32,
1290 ];
1291 let spec_col = [
1292 comp.eval_number(n, "Specular.Color.Red", time, 1.0, expr) as f32,
1293 comp.eval_number(n, "Specular.Color.Green", time, 1.0, expr) as f32,
1294 comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32,
1295 ];
1296 let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32;
1297 let (spec_exp, spec_gain) = if n.kind == "MtlCookTorrance" {
1298 let rough = comp.eval_number(n, "Specular.Roughness", time, 0.4, expr).clamp(0.05, 1.0) as f32;
1299 ((2.0 / (rough * rough) - 2.0).max(2.0), 0.15)
1300 } else {
1301 (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0)
1302 };
1303 ResolvedMaterial {
1304 tex_node: diff_tex,
1305 diffuse_col: col,
1306 specular_col: spec_col,
1307 specular_intensity: spec_int.clamp(0.0, 4.0) * spec_gain,
1308 specular_exponent: spec_exp,
1309 }
1310 }
1311 _ => ResolvedMaterial {
1312 tex_node: Some(mid),
1313 ..default_mat
1314 },
770 }1315 }
771}1316}
7721317
1318fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 {
1319 let tx = comp.eval_number(node, "Translate.X", time, comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr), expr) as f32;
1320 let ty = comp.eval_number(node, "Translate.Y", time, comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr), expr) as f32;
1321 let tz = comp.eval_number(node, "Translate.Z", time, comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr), expr) as f32;
1322 let rx = (comp.eval_number(node, "Rotate.X", time, comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr), expr) as f32).to_radians();
1323 let ry = (comp.eval_number(node, "Rotate.Y", time, comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr), expr) as f32).to_radians();
1324 let rz = (comp.eval_number(node, "Rotate.Z", time, comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr), expr) as f32).to_radians();
1325 let sx = comp.eval_number(node, "Scale.X", time, comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr), expr) as f32;
1326 let sy = comp.eval_number(node, "Scale.Y", time, comp.eval_number(node, "Transform3DOp.Scale.Y", time, sx as f64, expr), expr) as f32;
1327 let sz = comp.eval_number(node, "Scale.Z", time, comp.eval_number(node, "Transform3DOp.Scale.Z", time, sx as f64, expr), expr) as f32;
1328 let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx)));
1329 mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz)))
1330}
1331
773pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 {1332pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 {
774 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32;1333 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32;
775 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;1334 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;
...@@ -911,3 +1470,149 @@ pub fn mat4_perspective_wgpu(vfov_rad: f32, aspect: f32, near: f32, far: f32) ->...@@ -911,3 +1470,149 @@ pub fn mat4_perspective_wgpu(vfov_rad: f32, aspect: f32, near: f32, far: f32) ->
911 0.0, 0.0, far * near * nf, 0.0,1470 0.0, 0.0, far * near * nf, 0.0,
912 ]1471 ]
913}1472}
1473
1474#[cfg(test)]
1475mod tests {
1476 use super::*;
1477
1478 #[test]
1479 fn test_collect_scene_archive_3d_nodes() {
1480 let src = r#"Composition {
1481 CurrentTime = 0,
1482 RenderRange = { 0, 10 },
1483 GlobalRange = { 0, 10 },
1484 Tools = ordered() {
1485 BG1 = Background {
1486 Inputs = {
1487 Width = Input { Value = 64, },
1488 Height = Input { Value = 64, },
1489 },
1490 },
1491 Tex2D = Texture2DOperator {
1492 Inputs = {
1493 Input = Input { SourceOp = "BG1", Source = "Output", },
1494 },
1495 },
1496 Blinn1 = MtlBlinn {
1497 Inputs = {
1498 ["Diffuse.Color.Red"] = Input { Value = 0.8, },
1499 ["Diffuse.Color.Material"] = Input { SourceOp = "Tex2D", Source = "MaterialOutput", },
1500 ["Specular.Intensity"] = Input { Value = 0.75, },
1501 ["Specular.Exponent"] = Input { Value = 40.0, },
1502 },
1503 },
1504 Cook1 = MtlCookTorrance {
1505 Inputs = {
1506 ["Diffuse.Color.Green"] = Input { Value = 0.6, },
1507 ["Specular.Roughness"] = Input { Value = 0.25, },
1508 },
1509 },
1510 Shape1 = Shape3D {
1511 Inputs = {
1512 Shape = Input { Value = FuID { "SurfaceSphereInputs" }, },
1513 MaterialInput = Input { SourceOp = "Blinn1", Source = "MaterialOutput", },
1514 },
1515 },
1516 RepMat = ReplaceMaterial3D {
1517 Inputs = {
1518 SceneInput = Input { SourceOp = "Shape1", Source = "Output", },
1519 MaterialInput = Input { SourceOp = "Cook1", Source = "MaterialOutput", },
1520 },
1521 },
1522 RepNorm = ReplaceNormals3D {
1523 Inputs = {
1524 SceneInput = Input { SourceOp = "RepMat", Source = "Output", },
1525 FlipNormals = Input { Value = 1, },
1526 },
1527 },
1528 Disp1 = Displace3D {
1529 Inputs = {
1530 SceneInput = Input { SourceOp = "RepNorm", Source = "Output", },
1531 Input = Input { SourceOp = "BG1", Source = "Output", },
1532 Scale = Input { Value = 0.2, },
1533 },
1534 },
1535 Dup1 = Duplicate3D {
1536 Inputs = {
1537 SceneInput = Input { SourceOp = "Disp1", Source = "Output", },
1538 FirstCopy = Input { Value = 0, },
1539 LastCopy = Input { Value = 2, },
1540 ["Translate.X"] = Input { Value = 1.5, },
1541 },
1542 },
1543 OvrHide = Override3D {
1544 Inputs = {
1545 SceneInput = Input { SourceOp = "Shape1", Source = "Output", },
1546 ["Visibility.DoVisible"] = Input { Value = 1, },
1547 ["Visibility.IsVisible"] = Input { Value = 0, },
1548 },
1549 },
1550 Txt1 = Text3D {
1551 Inputs = {
1552 StyledText = Input { Value = "HI", },
1553 ["Extrusion.ExtrusionDepth"] = Input { Value = 0.15, },
1554 },
1555 },
1556 Pt1 = LightPoint {
1557 Inputs = {
1558 Intensity = Input { Value = 2.0, },
1559 DecayType = Input { Value = 1, },
1560 ["Transform3DOp.Translate.X"] = Input { Value = 3.0, },
1561 },
1562 },
1563 Sp1 = LightSpot {
1564 Inputs = {
1565 Intensity = Input { Value = 1.5, },
1566 ConeAngle = Input { Value = 45.0, },
1567 PenumbraAngle = Input { Value = 10.0, },
1568 },
1569 },
1570 Cam1 = Camera3D {
1571 Inputs = {
1572 ["Transform3DOp.Translate.Z"] = Input { Value = 5.0, },
1573 },
1574 },
1575 Merge1 = Merge3D {
1576 Inputs = {
1577 SceneInput1 = Input { SourceOp = "Dup1", Source = "Output", },
1578 SceneInput2 = Input { SourceOp = "OvrHide", Source = "Output", },
1579 SceneInput3 = Input { SourceOp = "Txt1", Source = "Output", },
1580 SceneInput4 = Input { SourceOp = "Pt1", Source = "Output", },
1581 SceneInput5 = Input { SourceOp = "Sp1", Source = "Output", },
1582 SceneInput6 = Input { SourceOp = "Cam1", Source = "Output", },
1583 },
1584 },
1585 },
1586 }"#;
1587 let comp = Comp::from_fusion_str(src).expect("parse 3D test comp");
1588 let expr = ExprEngine::new();
1589 let merge_id = comp.find_node("Merge1").expect("Merge1");
1590 let mut cams = Vec::new();
1591 let mut meshes = Vec::new();
1592 let mut lights = SceneLights::default();
1593 collect_scene(
1594 &comp,
1595 merge_id,
1596 0.0,
1597 &expr,
1598 mat4_identity(),
1599 16.0 / 9.0,
1600 &mut cams,
1601 &mut meshes,
1602 &mut lights,
1603 0,
1604 );
1605 assert_eq!(cams.len(), 1);
1606 // 3 copies from Duplicate3D (0..=2) + 1 Text3D (OvrHide suppresses its Shape1)
1607 assert_eq!(meshes.len(), 4);
1608 assert!(meshes[0].flip_normals);
1609 assert!(meshes[0].displace.is_some());
1610 assert!((meshes[0].diffuse_col[1] - 0.6).abs() < 1e-4, "ReplaceMaterial3D should apply Cook1");
1611 assert!((meshes[2].world[12] - 3.0).abs() < 1e-4, "Duplicate3D copy 2 translated X=3.0");
1612 assert!(meshes[3].text3d.is_some());
1613 assert_eq!(lights.points.len(), 1);
1614 assert!((lights.points[0].pos[0] - 3.0).abs() < 1e-4);
1615 assert_eq!(lights.spots.len(), 1);
1616 assert!(lights.spots[0].cos_inner > lights.spots[0].cos_outer);
1617 }
1618}
crates/engine/src/shaders.wgsl+38
...@@ -2441,3 +2441,41 @@ fn vortex_op(@builtin(global_invocation_id) gid: vec3<u32>) {...@@ -2441,3 +2441,41 @@ fn vortex_op(@builtin(global_invocation_id) gid: vec3<u32>) {
2441 let m = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w) * blend;2441 let m = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w) * blend;
2442 store_dst(vec2<i32>(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0)));2442 store_dst(vec2<i32>(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0)));
2443}2443}
2444
2445
2446// ============================================================================
2447// 35. Fuse.KScope (N-slice radial kaleidoscope mirror)
2448// p[0] = (center.x, center.y, slices, angle_rad)
2449// p[1] = (capture_angle_rad, scale, edges, blend)
2450// p[2] = (has_mask, mask_invert, 0, 0)
2451// ============================================================================
2452@compute @workgroup_size(8, 8)
2453fn kscope_op(@builtin(global_invocation_id) gid: vec3<u32>) {
2454 let dims = textureDimensions(dst_tex);
2455 if (gid.x >= dims.x || gid.y >= dims.y) { return; }
2456 let aspect = f32(dims.x) / max(f32(dims.y), 1.0);
2457 let fu = pix_to_fu(gid.xy, dims);
2458 let center = u.p[0].xy;
2459 let slices = max(u.p[0].z, 1.0);
2460 let angle = u.p[0].w;
2461 let cap_angle = u.p[1].x;
2462 let scale = max(u.p[1].y, 1e-4);
2463 let edges = i32(u.p[1].z + 0.5);
2464 let blend = u.p[1].w;
2465
2466 let orig = textureLoad(src_a, vec2<i32>(gid.xy), 0);
2467 let rel = (fu - center) * vec2<f32>(aspect, 1.0);
2468 let r = length(rel) / scale;
2469 let sector = 6.28318530718 / slices;
2470 var th = atan2(rel.y, rel.x) - angle;
2471 th = th - floor(th / (2.0 * sector)) * (2.0 * sector);
2472 if (th > sector) {
2473 th = 2.0 * sector - th;
2474 }
2475 th = th + cap_angle;
2476 let src_fu = center + vec2<f32>(cos(th) * r / aspect, sin(th) * r);
2477 let kcol = sample_edges(src_a, src_fu, edges);
2478
2479 let m = read_mask(gid.xy, dims, u.p[2].x, u.p[2].y) * blend;
2480 store_dst(vec2<i32>(gid.xy), mix(orig, kcol, clamp(m, 0.0, 1.0)));
2481}
crates/flow/src/lib.rs+453-71
...@@ -6,7 +6,7 @@...@@ -6,7 +6,7 @@
6//! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert.6//! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert.
77
8use draw::{Glyphs, PathStyle, Primitive};8use draw::{Glyphs, PathStyle, Primitive};
9use model::{Comp, NodeId, PortRole, default_main_input_port, is_supported_tool};9use model::{Comp, CompHistory, NodeId, PortRole, default_main_input_port, is_supported_tool};
10use std::collections::{HashMap, HashSet};10use std::collections::{HashMap, HashSet};
11use std::sync::Arc;11use std::sync::Arc;
12use winit::event::{ElementState, MouseButton};12use winit::event::{ElementState, MouseButton};
...@@ -71,6 +71,10 @@ struct ModalTransform {...@@ -71,6 +71,10 @@ struct ModalTransform {
71struct WireDrag {71struct WireDrag {
72 src: NodeId,72 src: NodeId,
73 cursor_local: [f32; 2],73 cursor_local: [f32; 2],
74 /// If hovering a target input port, `(dst, port, creates_cycle)`.
75 target: Option<(NodeId, &'static str, bool)>,
76 /// True when dragging an existing connected input off to disconnect/rewire.
77 detached_from: Option<(NodeId, String)>,
74}78}
7579
76#[derive(Clone, Debug)]80#[derive(Clone, Debug)]
...@@ -86,7 +90,14 @@ pub enum FlowAction {...@@ -86,7 +90,14 @@ pub enum FlowAction {
86 ViewNode(usize, NodeId),90 ViewNode(usize, NodeId),
87 /// `` ` `` key: clear both Viewer 1 and Viewer 2.91 /// `` ` `` key: clear both Viewer 1 and Viewer 2.
88 ClearViewers,92 ClearViewers,
89 GraphMutated,93 /// Graph topology or node state mutated (optional affected node for subtree bust).
94 GraphMutated(Option<NodeId>),
95 /// `Shift+Space`: open Add Tool launcher.
96 OpenAddTool,
97 /// `F2`: begin inline rename on the primary selected node.
98 RequestRename(NodeId),
99 /// Transient feedback message (e.g., cycle rejected).
100 StatusNotice(String),
90}101}
91102
92#[derive(Clone, Debug)]103#[derive(Clone, Debug)]
...@@ -185,6 +196,57 @@ impl FlowView {...@@ -185,6 +196,57 @@ impl FlowView {
185 self.palette.bg196 self.palette.bg
186 }197 }
187198
199 /// Resets transient interaction state and re-fits when a new composition is loaded.
200 pub fn reset_for_comp(&mut self, comp: &Comp) {
201 self.selected.clear();
202 self.primary = None;
203 self.hovered_node = None;
204 self.hovered_wire = None;
205 self.modal = None;
206 self.wire_drag = None;
207 self.box_select = None;
208 self.panning = None;
209 self.lmb_drag_node = None;
210 self.label_cache.clear();
211 self.fitted_once = false;
212 self.fit_comp(comp);
213 }
214
215 /// Removes any stale `NodeId`s from selection/viewed_nodes after undo/redo or deletion.
216 pub fn sanitize_ids(&mut self, comp: &Comp) {
217 let len = comp.nodes.len();
218 self.selected.retain(|id| id.0 < len && !comp.nodes[id.0].internal);
219 if self.primary.is_some_and(|id| id.0 >= len || comp.nodes[id.0].internal) {
220 self.primary = self.selected.iter().copied().next();
221 }
222 for slot in &mut self.viewed_nodes {
223 if slot.is_some_and(|id| id.0 >= len) {
224 *slot = None;
225 }
226 }
227 if self.hovered_node.is_some_and(|id| id.0 >= len) {
228 self.hovered_node = None;
229 }
230 self.hovered_wire = None;
231 self.modal = None;
232 self.wire_drag = None;
233 self.lmb_drag_node = None;
234 }
235
236 /// Computes a clean world-space spawn position for a newly added node.
237 pub fn spawn_position(&self, comp: &Comp, is_generator: bool) -> [f32; 2] {
238 if let Some(sel_id) = self.primary.filter(|id| id.0 < comp.nodes.len()) {
239 let p = comp.node(sel_id).pos;
240 if is_generator {
241 [p[0], p[1] - 55.0]
242 } else {
243 [p[0] + 110.0, p[1]]
244 }
245 } else {
246 self.pan
247 }
248 }
249
188 pub fn fit_all(&mut self, comp: &Comp) {250 pub fn fit_all(&mut self, comp: &Comp) {
189 let ids: Vec<NodeId> = if !self.selected.is_empty() {251 let ids: Vec<NodeId> = if !self.selected.is_empty() {
190 self.selected.iter().copied().collect()252 self.selected.iter().copied().collect()
...@@ -326,18 +388,24 @@ impl FlowView {...@@ -326,18 +388,24 @@ impl FlowView {
326388
327 fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> {389 fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> {
328 for n in comp.nodes.iter().rev() {390 for n in comp.nodes.iter().rev() {
391 if n.internal { continue; }
329 let r = self.node_rect_local(n.pos);392 let r = self.node_rect_local(n.pos);
330 if local[0] >= r[0] - 8.0 && local[0] <= r[2] + 8.0 && local[1] >= r[1] - 8.0 && local[1] <= r[3] + 8.0 {393 if local[0] >= r[0] - 10.0 && local[0] <= r[2] + 10.0 && local[1] >= r[1] - 10.0 && local[1] <= r[3] + 10.0 {
331 // Pick Background/Foreground/Mask cleanly based on approach edge for Merge!394 // Pick Background/Foreground/Mask cleanly based on approach edge for Merge/Displace!
332 if n.kind == "Merge" || n.kind == "Displace" {395 if n.kind == "Merge" || n.kind == "Displace" || n.kind == "Dissolve" {
333 let cy = (r[1] + r[3]) * 0.5;
334 if local[1] < r[1] + 2.0 {396 if local[1] < r[1] + 2.0 {
335 return Some((n.id, "Foreground"));397 return Some((n.id, "Foreground"));
336 }398 }
337 if local[1] > r[3] - 2.0 {399 if local[1] > r[3] - 2.0 {
338 return Some((n.id, "EffectMask"));400 return Some((n.id, "EffectMask"));
339 }401 }
340 let _ = cy;402 return Some((n.id, "Background"));
403 }
404 if n.kind == "Merge3D" || n.kind == "Renderer3D" {
405 return Some((n.id, "SceneInput1"));
406 }
407 if local[1] > r[3] - 1.5 && n.kind != "PipeRouter" {
408 return Some((n.id, "EffectMask"));
341 }409 }
342 return Some((n.id, default_main_input_port(&n.kind)));410 return Some((n.id, default_main_input_port(&n.kind)));
343 }411 }
...@@ -345,6 +413,28 @@ impl FlowView {...@@ -345,6 +413,28 @@ impl FlowView {
345 None413 None
346 }414 }
347415
416 /// Hit-tests already-connected input port triangles so the user can drag an input off to disconnect/rewire.
417 fn hit_connected_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, String, NodeId)> {
418 let hit_r2 = 10.5_f32 * 10.5_f32;
419 for dst in comp.nodes.iter().rev() {
420 if dst.internal { continue; }
421 for (port, binding) in &dst.inputs {
422 let Some(src_name) = &binding.source_op else { continue };
423 let Some(src_id) = comp.find_node(src_name) else { continue };
424 let role = PortRole::from_input_name(port);
425 let (_a, _ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role);
426 let bn = be.normal();
427 let center = [b[0] + bn[0] * 4.0, b[1] + bn[1] * 4.0];
428 let dx = local[0] - center[0];
429 let dy = local[1] - center[1];
430 if dx * dx + dy * dy <= hit_r2 {
431 return Some((dst.id, port.clone(), src_id));
432 }
433 }
434 }
435 None
436 }
437
348 fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option<NodeId>) -> Option<WireRef> {438 fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option<NodeId>) -> Option<WireRef> {
349 let mut best: Option<(f32, WireRef)> = None;439 let mut best: Option<(f32, WireRef)> = None;
350 for dst in &comp.nodes {440 for dst in &comp.nodes {
...@@ -375,7 +465,7 @@ impl FlowView {...@@ -375,7 +465,7 @@ impl FlowView {
375 best.map(|(_, w)| w)465 best.map(|(_, w)| w)
376 }466 }
377467
378 fn begin_modal(&mut self, comp: &Comp, mode: TransformMode) {468 fn begin_modal(&mut self, comp: &Comp, history: &mut CompHistory, mode: TransformMode) {
379 if self.selected.is_empty() {469 if self.selected.is_empty() {
380 return;470 return;
381 }471 }
...@@ -383,11 +473,21 @@ impl FlowView {...@@ -383,11 +473,21 @@ impl FlowView {
383 let mut cy = 0.0_f32;473 let mut cy = 0.0_f32;
384 let mut saved = Vec::with_capacity(self.selected.len());474 let mut saved = Vec::with_capacity(self.selected.len());
385 for &id in &self.selected {475 for &id in &self.selected {
476 if id.0 >= comp.nodes.len() { continue; }
386 let p = comp.node(id).pos;477 let p = comp.node(id).pos;
387 cx += p[0];478 cx += p[0];
388 cy += p[1];479 cy += p[1];
389 saved.push((id, p));480 saved.push((id, p));
390 }481 }
482 if saved.is_empty() {
483 return;
484 }
485 let label = match mode {
486 TransformMode::Grab => "Move Nodes",
487 TransformMode::Rotate => "Rotate Nodes",
488 TransformMode::Scale => "Scale Nodes",
489 };
490 history.begin_group(comp, label);
391 let n = saved.len() as f32;491 let n = saved.len() as f32;
392 self.modal = Some(ModalTransform {492 self.modal = Some(ModalTransform {
393 mode,493 mode,
...@@ -398,7 +498,7 @@ impl FlowView {...@@ -398,7 +498,7 @@ impl FlowView {
398 });498 });
399 }499 }
400500
401 fn apply_modal(&mut self, comp: &mut Comp) {501 fn apply_modal(&mut self, comp: &mut Comp, shift_held: bool) {
402 let Some(m) = &self.modal else { return };502 let Some(m) = &self.modal else { return };
403 let cur = self.local_to_world(self.pointer_local);503 let cur = self.local_to_world(self.pointer_local);
404 let dx = cur[0] - m.start_pointer_world[0];504 let dx = cur[0] - m.start_pointer_world[0];
...@@ -413,7 +513,7 @@ impl FlowView {...@@ -413,7 +513,7 @@ impl FlowView {
413 AxisLock::Y => (0.0, dy),513 AxisLock::Y => (0.0, dy),
414 };514 };
415 for &(id, orig) in &m.saved_positions {515 for &(id, orig) in &m.saved_positions {
416 comp.node_mut(id).pos = [orig[0] + mx, orig[1] + my];516 comp.set_node_pos(id, [orig[0] + mx, orig[1] + my]);
417 }517 }
418 }518 }
419 TransformMode::Rotate => {519 TransformMode::Rotate => {
...@@ -424,7 +524,7 @@ impl FlowView {...@@ -424,7 +524,7 @@ impl FlowView {
424 for &(id, orig) in &m.saved_positions {524 for &(id, orig) in &m.saved_positions {
425 let rx = orig[0] - piv[0];525 let rx = orig[0] - piv[0];
426 let ry = orig[1] - piv[1];526 let ry = orig[1] - piv[1];
427 comp.node_mut(id).pos = [piv[0] + rx * c - ry * s, piv[1] + rx * s + ry * c];527 comp.set_node_pos(id, [piv[0] + rx * c - ry * s, piv[1] + rx * s + ry * c]);
428 }528 }
429 }529 }
430 TransformMode::Scale => {530 TransformMode::Scale => {
...@@ -437,47 +537,74 @@ impl FlowView {...@@ -437,47 +537,74 @@ impl FlowView {
437 AxisLock::Y => (1.0, factor),537 AxisLock::Y => (1.0, factor),
438 };538 };
439 for &(id, orig) in &m.saved_positions {539 for &(id, orig) in &m.saved_positions {
440 comp.node_mut(id).pos = [540 comp.set_node_pos(id, [
441 piv[0] + (orig[0] - piv[0]) * sx,541 piv[0] + (orig[0] - piv[0]) * sx,
442 piv[1] + (orig[1] - piv[1]) * sy,542 piv[1] + (orig[1] - piv[1]) * sy,
443 ];543 ]);
444 }544 }
445 }545 }
446 }546 }
447 if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 {547 // Shift-dragging a single node over an existing pipe highlights it for splicing on release.
548 if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 && shift_held {
448 let id = m.saved_positions[0].0;549 let id = m.saved_positions[0].0;
449 let c_local = self.world_to_local(comp.node(id).pos);550 let c_local = self.world_to_local(comp.node(id).pos);
450 self.hovered_wire = self.hit_wire(comp, c_local, Some(id));551 self.hovered_wire = self.hit_wire(comp, c_local, Some(id)).filter(|w| {
552 !comp.would_create_cycle(w.src, id) && !comp.would_create_cycle(id, w.dst)
553 });
451 } else {554 } else {
452 self.hovered_wire = None;555 self.hovered_wire = None;
453 }556 }
454 }557 }
455558
456 fn cancel_modal(&mut self, comp: &mut Comp) {559 fn cancel_modal(&mut self, comp: &mut Comp, history: &mut CompHistory) {
457 if let Some(m) = self.modal.take() {560 if self.modal.take().is_some() {
458 for (id, orig) in m.saved_positions {561 history.cancel_group(comp);
459 comp.node_mut(id).pos = orig;
460 }
461 }562 }
462 self.hovered_wire = None;563 self.hovered_wire = None;
463 }564 }
464565
465 fn confirm_modal(&mut self, comp: &mut Comp) -> bool {566 fn confirm_modal(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<FlowAction>) {
466 let mut mutated = false;
467 if let Some(m) = self.modal.take() {567 if let Some(m) = self.modal.take() {
468 if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 {568 if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 {
469 let id = m.saved_positions[0].0;569 let id = m.saved_positions[0].0;
470 if let Some(w) = self.hovered_wire.take() {570 if let Some(w) = self.hovered_wire.take() {
471 comp.insert_on_wire(id, w.src, w.dst, &w.port);571 match comp.splice_node_into_pipe(id, w.src, w.dst, &w.port) {
472 mutated = true;572 Ok(()) => {
573 actions.push(FlowAction::GraphMutated(Some(w.dst)));
574 actions.push(FlowAction::StatusNotice(format!(
575 "Spliced {} into pipe",
576 comp.node(id).name
577 )));
578 }
579 Err(e) => {
580 actions.push(FlowAction::StatusNotice(e));
581 }
582 }
473 }583 }
474 }584 }
585 history.commit_group(comp);
475 }586 }
476 self.hovered_wire = None;587 self.hovered_wire = None;
477 mutated
478 }588 }
479589
480 fn handle_key(&mut self, comp: &mut Comp, physical: Option<PhysicalKey>, key: &Key, kmod: ModifiersState, actions: &mut Vec<FlowAction>) {590 fn handle_key(
591 &mut self,
592 comp: &mut Comp,
593 history: &mut CompHistory,
594 physical: Option<PhysicalKey>,
595 key: &Key,
596 kmod: ModifiersState,
597 actions: &mut Vec<FlowAction>,
598 ) {
599 // Shift+Space: open Add Tool launcher
600 if kmod.shift_key()
601 && !kmod.super_key()
602 && !kmod.control_key()
603 && matches!(key, Key::Named(NamedKey::Space))
604 {
605 actions.push(FlowAction::OpenAddTool);
606 return;
607 }
481 // Numpad '.' (Blender Frame Selected) or Cmd+F or plain F608 // Numpad '.' (Blender Frame Selected) or Cmd+F or plain F
482 if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) {609 if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) {
483 self.fit_all(comp);610 self.fit_all(comp);
...@@ -488,16 +615,41 @@ impl FlowView {...@@ -488,16 +615,41 @@ impl FlowView {
488 actions.push(FlowAction::ClearViewers);615 actions.push(FlowAction::ClearViewers);
489 return;616 return;
490 }617 }
618 let cmd = kmod.super_key() || kmod.control_key();
491 match key {619 match key {
492 Key::Named(NamedKey::Escape) => {620 Key::Named(NamedKey::Escape) => {
493 if self.modal.is_some() {621 if self.modal.is_some() {
494 self.cancel_modal(comp);622 self.cancel_modal(comp, history);
495 }623 }
496 self.wire_drag = None;624 self.wire_drag = None;
497 }625 }
498 Key::Named(NamedKey::Enter) => {626 Key::Named(NamedKey::Enter) => {
499 if self.modal.is_some() && self.confirm_modal(comp) {627 if self.modal.is_some() {
500 actions.push(FlowAction::GraphMutated);628 self.confirm_modal(comp, history, actions);
629 }
630 }
631 Key::Named(NamedKey::Delete) | Key::Named(NamedKey::Backspace) => {
632 if !self.selected.is_empty() {
633 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
634 history.push_snapshot(comp, "Delete Nodes");
635 let deleted = comp.delete_nodes(&ids);
636 if !deleted.is_empty() {
637 self.sanitize_ids(comp);
638 self.selected.clear();
639 self.primary = None;
640 actions.push(FlowAction::SelectionChanged(None));
641 actions.push(FlowAction::GraphMutated(None));
642 actions.push(FlowAction::StatusNotice(format!(
643 "Deleted {} node{}",
644 deleted.len(),
645 if deleted.len() == 1 { "" } else { "s" }
646 )));
647 }
648 }
649 }
650 Key::Named(NamedKey::F2) => {
651 if let Some(id) = self.primary {
652 actions.push(FlowAction::RequestRename(id));
501 }653 }
502 }654 }
503 Key::Character(c) => match c.to_ascii_lowercase().as_str() {655 Key::Character(c) => match c.to_ascii_lowercase().as_str() {
...@@ -505,59 +657,82 @@ impl FlowView {...@@ -505,59 +657,82 @@ impl FlowView {
505 self.viewed_nodes = [None, None];657 self.viewed_nodes = [None, None];
506 actions.push(FlowAction::ClearViewers);658 actions.push(FlowAction::ClearViewers);
507 }659 }
660 "d" if cmd && !kmod.shift_key() => {
661 if !self.selected.is_empty() {
662 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
663 history.push_snapshot(comp, "Duplicate Nodes");
664 let created = comp.duplicate_nodes(&ids, [44.0, 28.0]);
665 if !created.is_empty() {
666 self.selected.clear();
667 for &nid in &created {
668 self.selected.insert(nid);
669 }
670 self.primary = created.first().copied();
671 actions.push(FlowAction::SelectionChanged(self.primary));
672 actions.push(FlowAction::GraphMutated(self.primary));
673 actions.push(FlowAction::StatusNotice(format!(
674 "Duplicated {} node{}",
675 created.len(),
676 if created.len() == 1 { "" } else { "s" }
677 )));
678 }
679 }
680 }
508 "f" if kmod.super_key() => self.fit_all(comp),681 "f" if kmod.super_key() => self.fit_all(comp),
509 "f" if !kmod.super_key() => self.fit_all(comp),682 "f" if !kmod.super_key() => self.fit_all(comp),
510 "." if !kmod.super_key() => self.fit_all(comp),683 "." if !kmod.super_key() => self.fit_all(comp),
511 "g" if !kmod.super_key() && self.modal.is_none() => {684 "g" if !cmd && self.modal.is_none() => {
512 self.begin_modal(comp, TransformMode::Grab);685 self.begin_modal(comp, history, TransformMode::Grab);
513 }686 }
514 "r" if !kmod.super_key() && self.modal.is_none() => {687 "r" if !cmd && self.modal.is_none() => {
515 self.begin_modal(comp, TransformMode::Rotate);688 self.begin_modal(comp, history, TransformMode::Rotate);
516 }689 }
517 "s" if !kmod.super_key() && self.modal.is_none() => {690 "s" if !cmd && self.modal.is_none() => {
518 self.begin_modal(comp, TransformMode::Scale);691 self.begin_modal(comp, history, TransformMode::Scale);
519 }692 }
520 "x" if self.modal.is_some() => {693 "x" if self.modal.is_some() => {
521 if let Some(m) = &mut self.modal {694 if let Some(m) = &mut self.modal {
522 m.axis = if m.axis == AxisLock::X { AxisLock::None } else { AxisLock::X };695 m.axis = if m.axis == AxisLock::X { AxisLock::None } else { AxisLock::X };
523 }696 }
524 self.apply_modal(comp);697 self.apply_modal(comp, kmod.shift_key());
525 }698 }
526 "y" if self.modal.is_some() => {699 "y" if self.modal.is_some() => {
527 if let Some(m) = &mut self.modal {700 if let Some(m) = &mut self.modal {
528 m.axis = if m.axis == AxisLock::Y { AxisLock::None } else { AxisLock::Y };701 m.axis = if m.axis == AxisLock::Y { AxisLock::None } else { AxisLock::Y };
529 }702 }
530 self.apply_modal(comp);703 self.apply_modal(comp, kmod.shift_key());
531 }704 }
532 "a" if !kmod.super_key() => {705 "a" if !kmod.super_key() => {
533 if self.selected.len() == comp.nodes.len() {706 let visible: Vec<NodeId> = comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect();
707 if self.selected.len() == visible.len() {
534 self.selected.clear();708 self.selected.clear();
535 self.primary = None;709 self.primary = None;
536 } else {710 } else {
537 self.selected = comp.nodes.iter().map(|n| n.id).collect();711 self.selected = visible.iter().copied().collect();
538 self.primary = comp.nodes.first().map(|n| n.id);712 self.primary = visible.first().copied();
539 }713 }
540 actions.push(FlowAction::SelectionChanged(self.primary));714 actions.push(FlowAction::SelectionChanged(self.primary));
541 }715 }
542 "1" if !kmod.super_key() => {716 "1" if !cmd => {
543 if let Some(id) = self.primary {717 if let Some(id) = self.primary {
544 self.viewed_nodes[0] = Some(id);718 self.viewed_nodes[0] = Some(id);
545 actions.push(FlowAction::ViewNode(0, id));719 actions.push(FlowAction::ViewNode(0, id));
546 }720 }
547 }721 }
548 "2" if !kmod.super_key() => {722 "2" if !cmd => {
549 if let Some(id) = self.primary {723 if let Some(id) = self.primary {
550 self.viewed_nodes[1] = Some(id);724 self.viewed_nodes[1] = Some(id);
551 actions.push(FlowAction::ViewNode(1, id));725 actions.push(FlowAction::ViewNode(1, id));
552 }726 }
553 }727 }
554 "p" => {728 "p" if !kmod.super_key() => {
555 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
556 for id in ids {
557 comp.toggle_bypass(id);
558 }
559 if !self.selected.is_empty() {729 if !self.selected.is_empty() {
560 actions.push(FlowAction::GraphMutated);730 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
731 history.push_snapshot(comp, "Toggle Passthrough");
732 for id in ids {
733 comp.toggle_passthrough(id);
734 }
735 actions.push(FlowAction::GraphMutated(self.primary));
561 }736 }
562 }737 }
563 _ => {}738 _ => {}
...@@ -569,6 +744,7 @@ impl FlowView {...@@ -569,6 +744,7 @@ impl FlowView {
569 pub fn input(744 pub fn input(
570 &mut self,745 &mut self,
571 comp: &mut Comp,746 comp: &mut Comp,
747 history: &mut CompHistory,
572 event: ui::Event,748 event: ui::Event,
573 rect: [f32; 4],749 rect: [f32; 4],
574 pointer_window: [f32; 2],750 pointer_window: [f32; 2],
...@@ -586,9 +762,17 @@ impl FlowView {...@@ -586,9 +762,17 @@ impl FlowView {
586 start_pan[1] - (self.pointer_local[1] - start_p[1]) / self.zoom,762 start_pan[1] - (self.pointer_local[1] - start_p[1]) / self.zoom,
587 ];763 ];
588 } else if self.modal.is_some() {764 } else if self.modal.is_some() {
589 self.apply_modal(comp);765 self.apply_modal(comp, modifiers.shift_key());
590 } else if let Some(wd) = &mut self.wire_drag {766 } else if let Some(wd) = &mut self.wire_drag {
591 wd.cursor_local = self.pointer_local;767 wd.cursor_local = self.pointer_local;
768 let src = wd.src;
769 let target = self.hit_input_port(comp, self.pointer_local).map(|(dst, port)| {
770 let cycle = comp.would_create_cycle(src, dst);
771 (dst, port, cycle)
772 });
773 if let Some(wd_mut) = &mut self.wire_drag {
774 wd_mut.target = target;
775 }
592 } else if let Some(bs) = &mut self.box_select {776 } else if let Some(bs) = &mut self.box_select {
593 bs.cur_local = self.pointer_local;777 bs.cur_local = self.pointer_local;
594 } else if let Some((nid, start_l, ref mut moved)) = self.lmb_drag_node {778 } else if let Some((nid, start_l, ref mut moved)) = self.lmb_drag_node {
...@@ -602,7 +786,7 @@ impl FlowView {...@@ -602,7 +786,7 @@ impl FlowView {
602 self.primary = Some(nid);786 self.primary = Some(nid);
603 actions.push(FlowAction::SelectionChanged(self.primary));787 actions.push(FlowAction::SelectionChanged(self.primary));
604 }788 }
605 self.begin_modal(comp, TransformMode::Grab);789 self.begin_modal(comp, history, TransformMode::Grab);
606 }790 }
607 } else {791 } else {
608 self.hovered_node = self.hit_node(comp, self.pointer_local);792 self.hovered_node = self.hit_node(comp, self.pointer_local);
...@@ -622,23 +806,53 @@ impl FlowView {...@@ -622,23 +806,53 @@ impl FlowView {
622 }806 }
623 } else if button == MouseButton::Right {807 } else if button == MouseButton::Right {
624 if pressed && self.modal.is_some() {808 if pressed && self.modal.is_some() {
625 self.cancel_modal(comp);809 self.cancel_modal(comp, history);
626 } else if pressed && self.wire_drag.is_some() {810 } else if pressed && self.wire_drag.is_some() {
627 self.wire_drag = None;811 self.wire_drag = None;
812 } else if pressed {
813 // Right-click a hovered wire or connected input port to disconnect it!
814 if let Some(w) = self.hit_wire(comp, self.pointer_local, None) {
815 history.push_snapshot(comp, "Disconnect");
816 if comp.disconnect(w.dst, &w.port) {
817 self.hovered_wire = None;
818 actions.push(FlowAction::GraphMutated(Some(w.dst)));
819 actions.push(FlowAction::StatusNotice(format!(
820 "Disconnected {}.{}",
821 comp.node(w.dst).name,
822 w.port
823 )));
824 }
825 }
628 }826 }
629 } else if button == MouseButton::Left {827 } else if button == MouseButton::Left {
630 if pressed {828 if pressed {
631 if self.modal.is_some() {829 if self.modal.is_some() {
632 if self.confirm_modal(comp) {830 self.confirm_modal(comp, history, &mut actions);
633 actions.push(FlowAction::GraphMutated);
634 }
635 } else if let Some(src) = self.hit_output_port(comp, self.pointer_local) {831 } else if let Some(src) = self.hit_output_port(comp, self.pointer_local) {
636 self.wire_drag = Some(WireDrag { src, cursor_local: self.pointer_local });832 self.wire_drag = Some(WireDrag {
833 src,
834 cursor_local: self.pointer_local,
835 target: None,
836 detached_from: None,
837 });
838 } else if let Some((dst, port, src)) = self.hit_connected_input_port(comp, self.pointer_local) {
839 // Dragging an existing input port detaches it so user can drop to disconnect or rewire!
840 history.push_snapshot(comp, "Disconnect");
841 comp.disconnect(dst, &port);
842 actions.push(FlowAction::GraphMutated(Some(dst)));
843 self.wire_drag = Some(WireDrag {
844 src,
845 cursor_local: self.pointer_local,
846 target: None,
847 detached_from: Some((dst, port)),
848 });
637 } else if let Some(nid) = self.hit_node(comp, self.pointer_local) {849 } else if let Some(nid) = self.hit_node(comp, self.pointer_local) {
638 if modifiers.shift_key() {850 if modifiers.shift_key() {
639 if !self.selected.remove(&nid) {851 if !self.selected.remove(&nid) {
640 self.selected.insert(nid);852 self.selected.insert(nid);
641 self.primary = Some(nid);853 self.primary = Some(nid);
854 } else if self.primary == Some(nid) {
855 self.primary = self.selected.iter().copied().next();
642 }856 }
643 } else if !self.selected.contains(&nid) {857 } else if !self.selected.contains(&nid) {
644 self.selected.clear();858 self.selected.clear();
...@@ -663,15 +877,34 @@ impl FlowView {...@@ -663,15 +877,34 @@ impl FlowView {
663 } else {877 } else {
664 if let Some((_nid, _start, moved)) = self.lmb_drag_node.take() {878 if let Some((_nid, _start, moved)) = self.lmb_drag_node.take() {
665 if moved && self.modal.is_some() {879 if moved && self.modal.is_some() {
666 if self.confirm_modal(comp) {880 self.confirm_modal(comp, history, &mut actions);
667 actions.push(FlowAction::GraphMutated);
668 }
669 }881 }
670 }882 }
671 if let Some(wd) = self.wire_drag.take() {883 if let Some(wd) = self.wire_drag.take() {
672 if let Some((dst, port)) = self.hit_input_port(comp, self.pointer_local) {884 if let Some((dst, port)) = self.hit_input_port(comp, self.pointer_local) {
673 comp.connect(wd.src, dst, port);885 if comp.would_create_cycle(wd.src, dst) {
674 actions.push(FlowAction::GraphMutated);886 actions.push(FlowAction::StatusNotice(
887 "Cycle rejected: cannot connect downstream to upstream".to_owned(),
888 ));
889 } else {
890 if wd.detached_from.is_none() {
891 history.push_snapshot(comp, "Connect");
892 }
893 match comp.connect_output(wd.src, "Output", dst, port) {
894 Ok(()) => {
895 actions.push(FlowAction::GraphMutated(Some(dst)));
896 }
897 Err(e) => {
898 actions.push(FlowAction::StatusNotice(e));
899 }
900 }
901 }
902 } else if let Some((dst, port)) = wd.detached_from {
903 actions.push(FlowAction::StatusNotice(format!(
904 "Disconnected {}.{}",
905 comp.node(dst).name,
906 port
907 )));
675 }908 }
676 }909 }
677 if let Some(bs) = self.box_select.take() {910 if let Some(bs) = self.box_select.take() {
...@@ -681,6 +914,7 @@ impl FlowView {...@@ -681,6 +914,7 @@ impl FlowView {
681 let y1 = bs.start_local[1].max(bs.cur_local[1]);914 let y1 = bs.start_local[1].max(bs.cur_local[1]);
682 if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 {915 if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 {
683 for n in &comp.nodes {916 for n in &comp.nodes {
917 if n.internal { continue; }
684 let c = self.world_to_local(n.pos);918 let c = self.world_to_local(n.pos);
685 if c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 {919 if c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 {
686 self.selected.insert(n.id);920 self.selected.insert(n.id);
...@@ -708,10 +942,10 @@ impl FlowView {...@@ -708,10 +942,10 @@ impl FlowView {
708 self.zoom_at(factor, self.pointer_local);942 self.zoom_at(factor, self.pointer_local);
709 }943 }
710 ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => {944 ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => {
711 self.handle_key(comp, Some(physical), &key, kmod, &mut actions);945 self.handle_key(comp, history, Some(physical), &key, kmod, &mut actions);
712 }946 }
713 ui::Event::Key { key, modifiers: kmod, .. } => {947 ui::Event::Key { key, modifiers: kmod, .. } => {
714 self.handle_key(comp, None, &key, kmod, &mut actions);948 self.handle_key(comp, history, None, &key, kmod, &mut actions);
715 }949 }
716 _ => {}950 _ => {}
717 }951 }
...@@ -767,9 +1001,12 @@ impl FlowView {...@@ -767,9 +1001,12 @@ impl FlowView {
767 self.badge_cache1001 self.badge_cache
768 .entry("preserved".to_owned())1002 .entry("preserved".to_owned())
769 .or_insert_with(|| make_layout("preserved", &tiny_font));1003 .or_insert_with(|| make_layout("preserved", &tiny_font));
1004 self.badge_cache
1005 .entry("cycle!".to_owned())
1006 .or_insert_with(|| make_layout("cycle!", &tiny_font));
770 for key in [1007 for key in [
771 "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+S: Save Cmd+Shift+R: Export Cmd+F: Fit",1008 "Shift+Space: Add Tool G/R/S: Transform Shift+Drag: Splice Del: Delete Cmd+D: Dup F2: Rename Ctrl+P: Bypass 1/2: Viewer",
772 "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",1009 "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]",
773 "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",1010 "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
774 "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",1011 "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",
775 ] {1012 ] {
...@@ -917,12 +1154,61 @@ impl FlowView {...@@ -917,12 +1154,61 @@ impl FlowView {
917 }1154 }
918 }1155 }
9191156
920 // Active wire drag preview1157 // Active wire drag preview (smooth cubic bezier + cycle rejection feedback)
921 if let Some(wd) = &self.wire_drag {1158 if let Some(wd) = &self.wire_drag {
922 let sr = self.node_rect_local(comp.node(wd.src).pos);1159 if wd.src.0 < comp.nodes.len() {
923 let edge = self.node_output_edge(comp, wd.src);1160 let sr = self.node_rect_local(comp.node(wd.src).pos);
924 let a = edge.point_on_rect(sr, 0.5);1161 let edge = self.node_output_edge(comp, wd.src);
925 out.push(Primitive::Segment { from: a, to: wd.cursor_local, width: 2.0, color: [0.98, 0.84, 0.30, 1.0] });1162 let a = edge.point_on_rect(sr, 0.5);
1163 let (end, is_cycle, target_role) = match wd.target {
1164 Some((dst, port, cycle)) if dst.0 < comp.nodes.len() => {
1165 let role = PortRole::from_input_name(port);
1166 let (_, _, b, _) = self.wire_endpoints(comp, wd.src, dst, role);
1167 (b, cycle, Some(role))
1168 }
1169 _ => (wd.cursor_local, false, None),
1170 };
1171 let wire_col = if is_cycle {
1172 [0.96, 0.30, 0.34, 1.0]
1173 } else if let Some(role) = target_role {
1174 port_color(role)
1175 } else {
1176 [0.98, 0.84, 0.30, 1.0]
1177 };
1178 let pts = sample_preview_bezier(a, edge.normal(), end, 16);
1179 for seg in pts.windows(2) {
1180 out.push(Primitive::Segment {
1181 from: seg[0],
1182 to: seg[1],
1183 width: if is_cycle { 2.4 } else { 2.0 },
1184 color: wire_col,
1185 });
1186 }
1187 if is_cycle {
1188 if let Some(badge) = self.badge_cache.get("cycle!") {
1189 let bx = end[0] + 8.0;
1190 let by = end[1] - 14.0;
1191 out.push(Primitive::RoundedRect {
1192 rect: [bx, by, bx + 36.0, by + 13.0],
1193 radius: 3.0,
1194 stroke: None,
1195 color: [0.30, 0.06, 0.08, 0.94],
1196 });
1197 out.push(Primitive::RoundedRect {
1198 rect: [bx, by, bx + 36.0, by + 13.0],
1199 radius: 3.0,
1200 stroke: Some(1.0),
1201 color: [0.96, 0.30, 0.34, 0.95],
1202 });
1203 out.push(Primitive::Text {
1204 text: badge as &dyn Glyphs,
1205 origin: [bx + 5.0, by + 2.0],
1206 clip: Some([bx, by, bx + 36.0, by + 13.0]),
1207 ink: [1.0, 0.65, 0.65, 1.0],
1208 });
1209 }
1210 }
1211 }
926 }1212 }
9271213
928 // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!)1214 // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!)
...@@ -1105,10 +1391,10 @@ impl FlowView {...@@ -1105,10 +1391,10 @@ impl FlowView {
11051391
1106 // 6. Status HUD strip1392 // 6. Status HUD strip
1107 let hud_key = match self.modal.as_ref().map(|m| m.mode) {1393 let hud_key = match self.modal.as_ref().map(|m| m.mode) {
1108 Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",1394 Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]",
1109 Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",1395 Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
1110 Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",1396 Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",
1111 None => "G: Grab R: Rotate S: Scale X/Y: Axis 1/2: Viewer `: Clear P: Bypass Cmd+S: Save Cmd+Shift+R: Export Cmd+F: Fit",1397 None => "Shift+Space: Add Tool G/R/S: Transform Shift+Drag: Splice Del: Delete Cmd+D: Dup F2: Rename Ctrl+P: Bypass 1/2: Viewer",
1112 };1398 };
1113 if let Some(l) = self.badge_cache.get(hud_key) {1399 if let Some(l) = self.badge_cache.get(hud_key) {
1114 let pill_h = 20.0;1400 let pill_h = 20.0;
...@@ -1224,3 +1510,99 @@ fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {...@@ -1224,3 +1510,99 @@ fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {
1224 let q = [a[0] + ab[0] * t, a[1] + ab[1] * t];1510 let q = [a[0] + ab[0] * t, a[1] + ab[1] * t];
1225 ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt()1511 ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt()
1226}1512}
1513
1514/// Samples a smooth cubic Bezier preview wire leaving `a` along `out_normal` and arriving at `b`.
1515pub fn sample_preview_bezier(a: [f32; 2], out_normal: [f32; 2], b: [f32; 2], steps: usize) -> Vec<[f32; 2]> {
1516 let steps = steps.max(2);
1517 let dist = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt();
1518 let handle = (dist * 0.42).clamp(24.0, 140.0);
1519 let c1 = [a[0] + out_normal[0] * handle, a[1] + out_normal[1] * handle];
1520 let c2 = [b[0] - out_normal[0] * handle * 0.65, b[1] - out_normal[1] * handle * 0.65];
1521 let mut pts = Vec::with_capacity(steps + 1);
1522 for i in 0..=steps {
1523 let t = i as f32 / steps as f32;
1524 let u = 1.0 - t;
1525 let u2 = u * u;
1526 let t2 = t * t;
1527 let x = u2 * u * a[0] + 3.0 * u2 * t * c1[0] + 3.0 * u * t2 * c2[0] + t2 * t * b[0];
1528 let y = u2 * u * a[1] + 3.0 * u2 * t * c1[1] + 3.0 * u * t2 * c2[1] + t2 * t * b[1];
1529 pts.push([x, y]);
1530 }
1531 pts
1532}
1533
1534#[cfg(test)]
1535mod tests {
1536 use super::*;
1537
1538 fn test_comp() -> Comp {
1539 let src = r#"Composition {
1540 Tools = ordered() {
1541 BG1 = Background {
1542 ViewInfo = OperatorInfo { Pos = { 0, 0 } },
1543 },
1544 Merge1 = Merge {
1545 Inputs = {
1546 Background = Input { SourceOp = "BG1", Source = "Output" },
1547 },
1548 ViewInfo = OperatorInfo { Pos = { 160, 0 } },
1549 },
1550 },
1551 }"#;
1552 Comp::from_fusion_str(src).expect("parse comp")
1553 }
1554
1555 #[test]
1556 fn bezier_preview_endpoints_match() {
1557 let pts = sample_preview_bezier([10.0, 20.0], [1.0, 0.0], [210.0, 80.0], 16);
1558 assert_eq!(pts.len(), 17);
1559 assert!((pts[0][0] - 10.0).abs() < 1e-4);
1560 assert!((pts[0][1] - 20.0).abs() < 1e-4);
1561 assert!((pts[16][0] - 210.0).abs() < 1e-4);
1562 assert!((pts[16][1] - 80.0).abs() < 1e-4);
1563 }
1564
1565 #[test]
1566 fn dist_to_seg_basic() {
1567 assert!((dist_to_seg([5.0, 3.0], [0.0, 0.0], [10.0, 0.0]) - 3.0).abs() < 1e-5);
1568 assert!((dist_to_seg([12.0, 0.0], [0.0, 0.0], [10.0, 0.0]) - 2.0).abs() < 1e-5);
1569 }
1570
1571 #[test]
1572 fn flow_hit_node_and_input_ports() {
1573 let theme = ui::Theme::new(&theme::KNIFE, true);
1574 let mut flow = FlowView::new(&theme);
1575 flow.size = [800.0, 600.0];
1576 flow.pan = [80.0, 0.0];
1577 flow.zoom = 1.0;
1578
1579 let comp = test_comp();
1580 let bg = comp.find_node("BG1").unwrap();
1581 let merge = comp.find_node("Merge1").unwrap();
1582
1583 let bg_local = flow.world_to_local(comp.node(bg).pos);
1584 assert_eq!(flow.hit_node(&comp, bg_local), Some(bg));
1585
1586 let merge_local = flow.world_to_local(comp.node(merge).pos);
1587 assert_eq!(flow.hit_node(&comp, merge_local), Some(merge));
1588
1589 // Top of Merge hits Foreground; bottom hits EffectMask; middle hits Background
1590 let mr = flow.node_rect_local(comp.node(merge).pos);
1591 assert_eq!(flow.hit_input_port(&comp, [merge_local[0], mr[1] - 2.0]), Some((merge, "Foreground")));
1592 assert_eq!(flow.hit_input_port(&comp, [merge_local[0], mr[3] + 2.0]), Some((merge, "EffectMask")));
1593 assert_eq!(flow.hit_input_port(&comp, merge_local), Some((merge, "Background")));
1594 }
1595
1596 #[test]
1597 fn flow_spawn_position_generator_vs_effect() {
1598 let theme = ui::Theme::new(&theme::KNIFE, true);
1599 let mut flow = FlowView::new(&theme);
1600 let comp = test_comp();
1601 let bg = comp.find_node("BG1").unwrap();
1602 flow.primary = Some(bg);
1603 let p_eff = flow.spawn_position(&comp, false);
1604 let p_gen = flow.spawn_position(&comp, true);
1605 assert!(p_eff[0] > comp.node(bg).pos[0]);
1606 assert!(p_gen[1] < comp.node(bg).pos[1]);
1607 }
1608}
crates/model/src/comp.rs+15
...@@ -120,10 +120,13 @@ pub fn is_supported_tool(kind: &str) -> bool {...@@ -120,10 +120,13 @@ pub fn is_supported_tool(kind: &str) -> bool {
120 | "FilmGrain"120 | "FilmGrain"
121 | "Displace"121 | "Displace"
122 | "Vortex"122 | "Vortex"
123 | "Fuse.Duplicate"
124 | "Fuse.KScope"
123 | "EllipseMask"125 | "EllipseMask"
124 | "RectangleMask"126 | "RectangleMask"
125 | "PolylineMask"127 | "PolylineMask"
126 | "BitmapMask"128 | "BitmapMask"
129 | "WandMask"
127 | "TextPlus"130 | "TextPlus"
128 | "Fuse.Colorize"131 | "Fuse.Colorize"
129 | "Fuse.Outline"132 | "Fuse.Outline"
...@@ -150,8 +153,20 @@ pub fn is_supported_tool(kind: &str) -> bool {...@@ -150,8 +153,20 @@ pub fn is_supported_tool(kind: &str) -> bool {
150 | "Camera3D"153 | "Camera3D"
151 | "ImagePlane3D"154 | "ImagePlane3D"
152 | "Shape3D"155 | "Shape3D"
156 | "Text3D"
153 | "LightAmbient"157 | "LightAmbient"
154 | "LightDirectional"158 | "LightDirectional"
159 | "LightPoint"
160 | "LightSpot"
161 | "MtlBlinn"
162 | "MtlCookTorrance"
163 | "MtlPhong"
164 | "Texture2DOperator"
165 | "ReplaceMaterial3D"
166 | "Override3D"
167 | "Duplicate3D"
168 | "ReplaceNormals3D"
169 | "Displace3D"
155 )170 )
156}171}
157172
crates/studio/src/add_tool.rs created+557
...@@ -0,0 +1,557 @@
1//! `Shift+Space` Add Tool fuzzy-search launcher modal overlay.
2
3use winit::keyboard::{Key, NamedKey};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub enum ToolCategory {
7 Generator,
8 Composite,
9 Color,
10 Keyer,
11 BlurGlow,
12 TransformWarp,
13 Mask,
14 Particle,
15 Scene3D,
16 Utility,
17}
18
19impl ToolCategory {
20 pub fn label(self) -> &'static str {
21 match self {
22 Self::Generator => "Generator",
23 Self::Composite => "Composite",
24 Self::Color => "Color",
25 Self::Keyer => "Keyer",
26 Self::BlurGlow => "Blur/Glow",
27 Self::TransformWarp => "Transform/Warp",
28 Self::Mask => "Mask",
29 Self::Particle => "Particle",
30 Self::Scene3D => "3D",
31 Self::Utility => "Utility",
32 }
33 }
34
35 pub fn color(self) -> [f32; 4] {
36 match self {
37 Self::Generator => [0.36, 0.82, 0.48, 1.0],
38 Self::Composite => [0.68, 0.72, 0.82, 1.0],
39 Self::Color => [0.94, 0.62, 0.24, 1.0],
40 Self::Keyer => [0.30, 0.84, 0.64, 1.0],
41 Self::BlurGlow => [0.94, 0.50, 0.28, 1.0],
42 Self::TransformWarp => [0.88, 0.72, 0.28, 1.0],
43 Self::Mask => [0.34, 0.66, 0.98, 1.0],
44 Self::Particle => [0.88, 0.46, 0.78, 1.0],
45 Self::Scene3D => [0.30, 0.86, 0.92, 1.0],
46 Self::Utility => [0.56, 0.62, 0.72, 1.0],
47 }
48 }
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub struct ToolEntry {
53 pub kind: &'static str,
54 pub display: &'static str,
55 pub aliases: &'static str,
56 pub category: ToolCategory,
57 pub is_generator: bool,
58}
59
60pub const TOOL_CATALOG: &[ToolEntry] = &[
61 // Generator
62 ToolEntry { kind: "Background", display: "Background", aliases: "bg solid color", category: ToolCategory::Generator, is_generator: true },
63 ToolEntry { kind: "FastNoise", display: "FastNoise", aliases: "fn noise fractal perlin", category: ToolCategory::Generator, is_generator: true },
64 ToolEntry { kind: "Plasma", display: "Plasma", aliases: "gradient organic", category: ToolCategory::Generator, is_generator: true },
65 ToolEntry { kind: "TextPlus", display: "Text+", aliases: "textplus title font", category: ToolCategory::Generator, is_generator: true },
66 ToolEntry { kind: "Loader", display: "Loader", aliases: "ld read media footage image", category: ToolCategory::Generator, is_generator: true },
67 // Composite
68 ToolEntry { kind: "Merge", display: "Merge", aliases: "mrg over blend comp", category: ToolCategory::Composite, is_generator: false },
69 ToolEntry { kind: "Dissolve", display: "Dissolve", aliases: "dx mix crossfade", category: ToolCategory::Composite, is_generator: false },
70 ToolEntry { kind: "ChannelBoolean", display: "Channel Booleans", aliases: "cb channel matte", category: ToolCategory::Composite, is_generator: false },
71 ToolEntry { kind: "Switch", display: "Switch", aliases: "sw select", category: ToolCategory::Composite, is_generator: false },
72 ToolEntry { kind: "Shadow", display: "Shadow", aliases: "drop shadow", category: ToolCategory::Composite, is_generator: false },
73 // Color
74 ToolEntry { kind: "BrightnessContrast", display: "Brightness / Contrast", aliases: "bc gain lift gamma", category: ToolCategory::Color, is_generator: false },
75 ToolEntry { kind: "ColorCorrector", display: "Color Corrector", aliases: "cc grade wheel saturation", category: ToolCategory::Color, is_generator: false },
76 ToolEntry { kind: "ColorGain", display: "Color Gain", aliases: "cg rgb gain", category: ToolCategory::Color, is_generator: false },
77 ToolEntry { kind: "ColorCurves", display: "Color Curves", aliases: "curves lut", category: ToolCategory::Color, is_generator: false },
78 ToolEntry { kind: "HueCurves", display: "Hue Curves", aliases: "hue sat", category: ToolCategory::Color, is_generator: false },
79 ToolEntry { kind: "GamutConvert", display: "Gamut", aliases: "colorspace srgb linear", category: ToolCategory::Color, is_generator: false },
80 ToolEntry { kind: "InvertColor", display: "Invert Color", aliases: "negate invert", category: ToolCategory::Color, is_generator: false },
81 ToolEntry { kind: "FilmGrain", display: "Film Grain", aliases: "grain noise", category: ToolCategory::Color, is_generator: false },
82 ToolEntry { kind: "Fuse.Colorize", display: "Colorize", aliases: "tint duotone", category: ToolCategory::Color, is_generator: false },
83 ToolEntry { kind: "Fuse.Outline", display: "Outline", aliases: "stroke edge", category: ToolCategory::Color, is_generator: false },
84 // Keyer
85 ToolEntry { kind: "UltraKeyer", display: "Ultra Keyer", aliases: "uk chroma green blue screen", category: ToolCategory::Keyer, is_generator: false },
86 ToolEntry { kind: "LumaKeyer", display: "Luma Keyer", aliases: "lk luminance key", category: ToolCategory::Keyer, is_generator: false },
87 ToolEntry { kind: "Cryptomatte", display: "Cryptomatte", aliases: "crypto id matte", category: ToolCategory::Keyer, is_generator: false },
88 // Blur / Glow
89 ToolEntry { kind: "Blur", display: "Blur", aliases: "bl gaussian defocus", category: ToolCategory::BlurGlow, is_generator: false },
90 ToolEntry { kind: "DirectionalBlur", display: "Directional Blur", aliases: "db radial zoom motion blur", category: ToolCategory::BlurGlow, is_generator: false },
91 ToolEntry { kind: "VariBlur", display: "VariBlur", aliases: "vb depth blur", category: ToolCategory::BlurGlow, is_generator: false },
92 ToolEntry { kind: "Glow", display: "Glow", aliases: "gl bloom", category: ToolCategory::BlurGlow, is_generator: false },
93 ToolEntry { kind: "SoftGlow", display: "Soft Glow", aliases: "sg bloom halo", category: ToolCategory::BlurGlow, is_generator: false },
94 ToolEntry { kind: "Fuse.XGlow", display: "XGlow", aliases: "exponential glow", category: ToolCategory::BlurGlow, is_generator: false },
95 ToolEntry { kind: "Sharpen", display: "Sharpen", aliases: "unsharp crisp", category: ToolCategory::BlurGlow, is_generator: false },
96 ToolEntry { kind: "Filter", display: "Filter", aliases: "sobel emboss laplacian", category: ToolCategory::BlurGlow, is_generator: false },
97 ToolEntry { kind: "ErodeDilate", display: "Erode / Dilate", aliases: "ed shrink grow matte", category: ToolCategory::BlurGlow, is_generator: false },
98 // Transform / Warp
99 ToolEntry { kind: "Transform", display: "Transform", aliases: "xf move scale rotate", category: ToolCategory::TransformWarp, is_generator: false },
100 ToolEntry { kind: "CameraShake", display: "Camera Shake", aliases: "shake jitter", category: ToolCategory::TransformWarp, is_generator: false },
101 ToolEntry { kind: "CornerPositioner", display: "Corner Positioner", aliases: "cp pin perspective", category: ToolCategory::TransformWarp, is_generator: false },
102 ToolEntry { kind: "DVE", display: "DVE", aliases: "3d card tilt", category: ToolCategory::TransformWarp, is_generator: false },
103 ToolEntry { kind: "Scale", display: "Scale", aliases: "resize", category: ToolCategory::TransformWarp, is_generator: false },
104 ToolEntry { kind: "BetterResize", display: "Resize", aliases: "rs scale format", category: ToolCategory::TransformWarp, is_generator: false },
105 ToolEntry { kind: "Crop", display: "Crop", aliases: "trim canvas", category: ToolCategory::TransformWarp, is_generator: false },
106 ToolEntry { kind: "Displace", display: "Displace", aliases: "dsp refract warp bump", category: ToolCategory::TransformWarp, is_generator: false },
107 ToolEntry { kind: "Vortex", display: "Vortex", aliases: "swirl twist", category: ToolCategory::TransformWarp, is_generator: false },
108 ToolEntry { kind: "Fuse.XfChroma", display: "XfChroma", aliases: "chromatic aberration rgb split", category: ToolCategory::TransformWarp, is_generator: false },
109 // Mask
110 ToolEntry { kind: "EllipseMask", display: "Ellipse Mask", aliases: "el circle oval", category: ToolCategory::Mask, is_generator: true },
111 ToolEntry { kind: "RectangleMask", display: "Rectangle Mask", aliases: "rect box square", category: ToolCategory::Mask, is_generator: true },
112 ToolEntry { kind: "PolylineMask", display: "Polygon Mask", aliases: "poly roto spline", category: ToolCategory::Mask, is_generator: true },
113 ToolEntry { kind: "BitmapMask", display: "Bitmap Mask", aliases: "bmp alpha luma", category: ToolCategory::Mask, is_generator: false },
114 // Particle
115 ToolEntry { kind: "pEmitter", display: "pEmitter", aliases: "pe particle emit", category: ToolCategory::Particle, is_generator: true },
116 ToolEntry { kind: "pRender", display: "pRender", aliases: "pr particle render", category: ToolCategory::Particle, is_generator: false },
117 ToolEntry { kind: "pTurbulence", display: "pTurbulence", aliases: "pt particle wind", category: ToolCategory::Particle, is_generator: false },
118 ToolEntry { kind: "pDirectionalForce", display: "pDirectionalForce", aliases: "pf gravity force", category: ToolCategory::Particle, is_generator: false },
119 ToolEntry { kind: "pPointForce", display: "pPointForce", aliases: "particle attract", category: ToolCategory::Particle, is_generator: false },
120 ToolEntry { kind: "pDrag", display: "pDrag", aliases: "particle damping", category: ToolCategory::Particle, is_generator: false },
121 ToolEntry { kind: "pFriction", display: "pFriction", aliases: "particle friction", category: ToolCategory::Particle, is_generator: false },
122 ToolEntry { kind: "pKill", display: "pKill", aliases: "particle kill", category: ToolCategory::Particle, is_generator: false },
123 ToolEntry { kind: "pMerge", display: "pMerge", aliases: "particle merge", category: ToolCategory::Particle, is_generator: false },
124 // 3D
125 ToolEntry { kind: "Renderer3D", display: "Renderer 3D", aliases: "3rn render 3d", category: ToolCategory::Scene3D, is_generator: false },
126 ToolEntry { kind: "Merge3D", display: "Merge 3D", aliases: "3mg scene 3d", category: ToolCategory::Scene3D, is_generator: false },
127 ToolEntry { kind: "Camera3D", display: "Camera 3D", aliases: "3cm cam", category: ToolCategory::Scene3D, is_generator: true },
128 ToolEntry { kind: "Shape3D", display: "Shape 3D", aliases: "3sh sphere plane cube", category: ToolCategory::Scene3D, is_generator: true },
129 ToolEntry { kind: "ImagePlane3D", display: "Image Plane 3D", aliases: "3im card plane", category: ToolCategory::Scene3D, is_generator: false },
130 ToolEntry { kind: "Transform3D", display: "Transform 3D", aliases: "3xf move 3d", category: ToolCategory::Scene3D, is_generator: false },
131 ToolEntry { kind: "LightAmbient", display: "Ambient Light", aliases: "3la light", category: ToolCategory::Scene3D, is_generator: true },
132 ToolEntry { kind: "LightDirectional", display: "Directional Light", aliases: "3dl sun light", category: ToolCategory::Scene3D, is_generator: true },
133 // Utility
134 ToolEntry { kind: "Saver", display: "Saver", aliases: "sv write export png", category: ToolCategory::Utility, is_generator: false },
135 ToolEntry { kind: "PipeRouter", display: "Pipe Router", aliases: "dot router wire", category: ToolCategory::Utility, is_generator: false },
136 ToolEntry { kind: "TimeStretcher", display: "Time Stretcher", aliases: "ts retime freeze", category: ToolCategory::Utility, is_generator: false },
137 ToolEntry { kind: "TimeSpeed", display: "Time Speed", aliases: "tsp speed delay", category: ToolCategory::Utility, is_generator: false },
138 ToolEntry { kind: "ChangeDepth", display: "Change Depth", aliases: "cd bit depth float", category: ToolCategory::Utility, is_generator: false },
139 ToolEntry { kind: "SetDomain", display: "Set Domain", aliases: "dod roi", category: ToolCategory::Utility, is_generator: false },
140 ToolEntry { kind: "Tracker", display: "Tracker", aliases: "tr matchmove", category: ToolCategory::Utility, is_generator: false },
141 ToolEntry { kind: "Note", display: "Sticky Note", aliases: "comment note", category: ToolCategory::Utility, is_generator: true },
142 ToolEntry { kind: "Underlay", display: "Underlay", aliases: "backdrop group", category: ToolCategory::Utility, is_generator: true },
143];
144
145/// Case-insensitive fuzzy/subsequence scoring for tool search.
146/// Higher score is better; returns `None` if `query` does not match `candidate`.
147pub fn fuzzy_score(query: &str, entry: &ToolEntry) -> Option<i32> {
148 let q = query.trim().to_ascii_lowercase();
149 if q.is_empty() {
150 return Some(0);
151 }
152 let kind_l = entry.kind.to_ascii_lowercase();
153 let disp_l = entry.display.to_ascii_lowercase();
154 let alias_l = entry.aliases.to_ascii_lowercase();
155 let cat_l = entry.category.label().to_ascii_lowercase();
156
157 let mut best: Option<i32> = None;
158 for (field, bonus) in [(&kind_l, 40), (&disp_l, 35), (&alias_l, 15), (&cat_l, 0)] {
159 if let Some(s) = score_field(&q, field) {
160 let total = s + bonus;
161 best = Some(best.map_or(total, |prev| prev.max(total)));
162 }
163 }
164 best
165}
166
167fn score_field(query: &str, target: &str) -> Option<i32> {
168 if target == query {
169 return Some(1000);
170 }
171 if target.starts_with(query) {
172 return Some(850 - (target.len() as i32 - query.len() as i32));
173 }
174 if let Some(idx) = target.find(query) {
175 let boundary_bonus = if idx == 0 || matches!(target.as_bytes()[idx - 1], b' ' | b'.' | b'/' | b'_') {
176 120
177 } else {
178 0
179 };
180 return Some(620 + boundary_bonus - idx as i32 * 4);
181 }
182
183 // Subsequence match with consecutive-run & word-boundary bonuses
184 let q_bytes = query.as_bytes();
185 let t_bytes = target.as_bytes();
186 let mut qi = 0usize;
187 let mut score = 200i32;
188 let mut prev_match: Option<usize> = None;
189
190 for (ti, &tb) in t_bytes.iter().enumerate() {
191 if qi < q_bytes.len() && tb == q_bytes[qi] {
192 if prev_match.is_some_and(|p| p + 1 == ti) {
193 score += 28;
194 } else if let Some(p) = prev_match {
195 score -= ((ti - p) as i32).min(20);
196 }
197 if ti == 0 || matches!(t_bytes[ti - 1], b' ' | b'.' | b'/' | b'_') {
198 score += 22;
199 }
200 prev_match = Some(ti);
201 qi += 1;
202 }
203 }
204
205 if qi == q_bytes.len() {
206 Some(score - (t_bytes.len() as i32))
207 } else {
208 None
209 }
210}
211
212/// Returns matching tool entries ranked from best to worst.
213pub fn search_tools(query: &str) -> Vec<&'static ToolEntry> {
214 let mut scored: Vec<(i32, usize, &'static ToolEntry)> = TOOL_CATALOG
215 .iter()
216 .enumerate()
217 .filter_map(|(idx, entry)| fuzzy_score(query, entry).map(|s| (s, idx, entry)))
218 .collect();
219 scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
220 scored.into_iter().map(|(_, _, e)| e).collect()
221}
222
223pub struct AddToolLauncher {
224 pub open: bool,
225 pub query: String,
226 pub selected_idx: usize,
227 needs_focus: bool,
228}
229
230impl Default for AddToolLauncher {
231 fn default() -> Self {
232 Self::new()
233 }
234}
235
236impl AddToolLauncher {
237 pub fn new() -> Self {
238 Self {
239 open: false,
240 query: String::new(),
241 selected_idx: 0,
242 needs_focus: false,
243 }
244 }
245
246 pub fn open(&mut self) {
247 self.open = true;
248 self.query.clear();
249 self.selected_idx = 0;
250 self.needs_focus = true;
251 }
252
253 pub fn close(&mut self) {
254 self.open = false;
255 self.needs_focus = false;
256 }
257
258 /// Builds the floating modal overlay when open. Returns `Some(ToolEntry)` if a tool was chosen.
259 pub fn build_ui(&mut self, ui: &mut ui::Ui, window_size: [f32; 2]) -> Option<ToolEntry> {
260 if !self.open {
261 return None;
262 }
263
264 let theme = ui.theme.clone();
265 let results = search_tools(&self.query);
266 if self.selected_idx >= results.len() {
267 self.selected_idx = 0;
268 }
269
270 let modal_id = ui::Id::ROOT.child("add-tool-modal");
271 let input_id = modal_id.child("query");
272
273 // Handle Up / Down / Enter / Escape from the search field before rendering rows
274 let mut picked: Option<ToolEntry> = None;
275 let mut should_close = false;
276
277 let scrim_id = ui::Id::ROOT.child("add-tool-scrim");
278 let scrim_sig = ui.signal(scrim_id);
279 if scrim_sig.clicked {
280 should_close = true;
281 }
282
283 // Full-window barrier scrim so clicks behind modal don't leak
284 ui.open_as(
285 scrim_id,
286 ui::Spec {
287 flags: ui::Flags::FLOAT | ui::Flags::BARRIER | ui::Flags::CLICKABLE,
288 position: [0.0, 0.0],
289 size: [ui::px(window_size[0]), ui::px(window_size[1])],
290 fill: Some([0.0, 0.0, 0.0, 0.42]),
291 ..ui::Spec::default()
292 },
293 );
294 ui.close();
295
296 let modal_w = 460.0_f32.min((window_size[0] - 40.0).max(260.0));
297 let modal_h = 380.0_f32.min((window_size[1] - 80.0).max(220.0));
298 let modal_x = ((window_size[0] - modal_w) * 0.5).max(16.0);
299 let modal_y = (window_size[1] * 0.14).max(24.0);
300
301 ui.open_as(
302 modal_id,
303 ui::Spec {
304 flags: ui::Flags::FLOAT | ui::Flags::BARRIER | ui::Flags::CLICKABLE | ui::Flags::CLIP,
305 position: [modal_x, modal_y],
306 size: [ui::px(modal_w), ui::px(modal_h)],
307 axis: ui::Axis::Y,
308 fill: Some(theme.popup),
309 border: Some(theme.accent),
310 shadow: Some([0.0, 0.0, 0.0, 0.45]),
311 radius: 10.0,
312 pad: [10.0, 10.0],
313 gap: 8.0,
314 ..ui::Spec::default()
315 },
316 );
317
318 // Header
319 ui.open(
320 "hdr",
321 ui::Spec {
322 size: [ui::fill(), ui::px(20.0)],
323 axis: ui::Axis::X,
324 gap: 6.0,
325 ..ui::Spec::default()
326 },
327 );
328 ui.leaf(
329 "title",
330 ui::Spec {
331 size: [ui::fill(), ui::fill()],
332 text: Some("Add Tool"),
333 font_size: Some(12.5),
334 medium: true,
335 color: Some(theme.text),
336 ..ui::Spec::default()
337 },
338 );
339 ui.leaf(
340 "hint",
341 ui::Spec {
342 size: [ui::fit(), ui::fill()],
343 text: Some("↑↓ select · Enter add · Esc close"),
344 font_size: Some(10.0),
345 color: Some(theme.text_dim),
346 ..ui::Spec::default()
347 },
348 );
349 ui.close();
350
351 // Search input
352 let prev_query = self.query.clone();
353 let input_sig = ui::text_field(
354 ui,
355 input_id,
356 &mut self.query,
357 "Type tool name (e.g. Merge, Blur, BC, xf, Text+)…",
358 ui::Spec {
359 size: [ui::fill(), ui::px(30.0)],
360 font_size: Some(13.0),
361 fill: Some(theme.base),
362 border: Some(theme.accent),
363 radius: 6.0,
364 pad: [10.0, 4.0],
365 ..ui::Spec::default()
366 },
367 );
368 if self.needs_focus {
369 ui.set_focus(Some(input_id));
370 self.needs_focus = false;
371 }
372 if self.query != prev_query {
373 self.selected_idx = 0;
374 }
375
376 for ev in &input_sig.events {
377 if let ui::Event::Key { key, .. } = ev {
378 match key {
379 Key::Named(NamedKey::Escape) => should_close = true,
380 Key::Named(NamedKey::ArrowDown) => {
381 if !results.is_empty() {
382 self.selected_idx = (self.selected_idx + 1) % results.len();
383 }
384 }
385 Key::Named(NamedKey::ArrowUp) => {
386 if !results.is_empty() {
387 self.selected_idx = (self.selected_idx + results.len() - 1) % results.len();
388 }
389 }
390 Key::Named(NamedKey::Enter) => {
391 if let Some(&entry) = results.get(self.selected_idx) {
392 picked = Some(*entry);
393 should_close = true;
394 }
395 }
396 _ => {}
397 }
398 }
399 }
400
401 // Scrollable results list
402 ui.open(
403 "results",
404 ui::Spec {
405 flags: ui::Flags::SCROLL | ui::Flags::CLIP,
406 size: [ui::fill(), ui::fill()],
407 axis: ui::Axis::Y,
408 gap: 2.0,
409 ..ui::Spec::default()
410 },
411 );
412 if results.is_empty() {
413 ui.leaf(
414 "no-match",
415 ui::Spec {
416 size: [ui::fill(), ui::px(28.0)],
417 text: Some("No matching tools"),
418 font_size: Some(11.5),
419 color: Some(theme.text_dim),
420 center: true,
421 ..ui::Spec::default()
422 },
423 );
424 } else {
425 for (idx, entry) in results.iter().enumerate() {
426 let is_sel = idx == self.selected_idx;
427 let cat_col = entry.category.color();
428 let row_id = ui.open(
429 ("row", entry.kind),
430 ui::Spec {
431 cursor: Some(winit::window::CursorIcon::Pointer),
432 flags: ui::Flags::CLICKABLE,
433 size: [ui::fill(), ui::px(26.0)],
434 axis: ui::Axis::X,
435 pad: [8.0, 2.0],
436 gap: 8.0,
437 fill: if is_sel {
438 Some([theme.accent[0], theme.accent[1], theme.accent[2], 0.22])
439 } else {
440 None
441 },
442 hover_fill: Some([theme.accent[0], theme.accent[1], theme.accent[2], 0.14]),
443 radius: 5.0,
444 ..ui::Spec::default()
445 },
446 );
447 let row_sig = ui.signal(row_id);
448 if row_sig.clicked {
449 picked = Some(**entry);
450 should_close = true;
451 }
452
453 // Category color pip
454 ui.leaf(
455 "pip",
456 ui::Spec {
457 size: [ui::px(6.0), ui::px(14.0)],
458 fill: Some(cat_col),
459 radius: 2.0,
460 ..ui::Spec::default()
461 },
462 );
463 ui.leaf(
464 "name",
465 ui::Spec {
466 size: [ui::fill(), ui::fill()],
467 text: Some(entry.display),
468 font_size: Some(12.0),
469 medium: is_sel,
470 color: Some(theme.text),
471 ..ui::Spec::default()
472 },
473 );
474 ui.leaf(
475 "kind",
476 ui::Spec {
477 size: [ui::fit(), ui::fill()],
478 text: Some(entry.kind),
479 font_size: Some(10.0),
480 color: Some(theme.text_dim),
481 ..ui::Spec::default()
482 },
483 );
484 ui.leaf(
485 "cat",
486 ui::Spec {
487 size: [ui::fit(), ui::px(18.0)],
488 text: Some(entry.category.label()),
489 font_size: Some(9.5),
490 color: Some(cat_col),
491 fill: Some([cat_col[0], cat_col[1], cat_col[2], 0.14]),
492 radius: 3.0,
493 pad: [5.0, 0.0],
494 center: true,
495 ..ui::Spec::default()
496 },
497 );
498 ui.close();
499 }
500 }
501 ui.close(); // results
502 ui.close(); // modal_id
503
504 if should_close {
505 self.close();
506 ui.set_focus(None);
507 }
508 picked
509 }
510}
511
512#[cfg(test)]
513mod tests {
514 use super::*;
515
516 #[test]
517 fn empty_query_returns_all_tools() {
518 let all = search_tools("");
519 assert_eq!(all.len(), TOOL_CATALOG.len());
520 assert!(all.len() >= 50);
521 }
522
523 #[test]
524 fn exact_and_prefix_rank_above_subsequence() {
525 let res = search_tools("blur");
526 assert!(!res.is_empty());
527 assert_eq!(res[0].kind, "Blur");
528
529 let res_mrg = search_tools("merge");
530 assert_eq!(res_mrg[0].kind, "Merge");
531 }
532
533 #[test]
534 fn alias_and_subsequence_matching_works() {
535 // Alias "bc" -> BrightnessContrast
536 let res_bc = search_tools("bc");
537 assert!(res_bc.iter().take(3).any(|e| e.kind == "BrightnessContrast"));
538
539 // Alias "xf" -> Transform
540 let res_xf = search_tools("xf");
541 assert!(res_xf.iter().take(3).any(|e| e.kind == "Transform"));
542
543 // Subsequence "tplus" -> TextPlus
544 let res_tp = search_tools("tplus");
545 assert!(res_tp.iter().any(|e| e.kind == "TextPlus"));
546
547 // Case-insensitive category match
548 let res_3d = search_tools("camera");
549 assert!(res_3d.iter().any(|e| e.kind == "Camera3D"));
550 }
551
552 #[test]
553 fn non_matching_query_returns_empty() {
554 let res = search_tools("zzzznotatool999");
555 assert!(res.is_empty());
556 }
557}
crates/studio/src/inspector.rs created+1802
...@@ -0,0 +1,1802 @@
1//! Inspector dock pane — Fusion 21.1 parameter editor with scrub sliders, Vec2, RGBA color groups,
2//! booleans, FuID enum cyclers, text fields, expression badges, and keyframe diamonds (`â—†`).
3
4use engine::EvalStats;
5use model::{Comp, CompHistory, ExprEngine, NodeId, ParamValue, is_supported_tool};
6use std::collections::{HashMap, HashSet};
7use std::time::{Duration, Instant};
8
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub enum ParamKind {
11 Float { min: f64, max: f64, default: f64, step: f64 },
12 Vec2 { min: f64, max: f64, default: [f64; 2] },
13 Bool { default: bool },
14 Enum { options: &'static [&'static str], default: &'static str },
15 Color {
16 r: &'static str,
17 g: &'static str,
18 b: &'static str,
19 a: Option<&'static str>,
20 default: [f64; 4],
21 },
22 Text { default: &'static str },
23}
24
25#[derive(Clone, Copy, Debug)]
26pub struct ParamSpec {
27 pub name: &'static str,
28 pub label: &'static str,
29 pub kind: ParamKind,
30}
31
32#[derive(Clone, Debug)]
33pub enum InspectorAction {
34 /// A parameter or node property changed; bust subtree & re-render viewers.
35 ParamEdited(NodeId),
36 /// A keyframe was added or deleted; refresh spline editor + bust subtree.
37 KeyframeEdited(NodeId),
38 /// Node was renamed.
39 NodeRenamed(NodeId),
40 /// Status notice to show in window title.
41 StatusNotice(String),
42}
43
44#[derive(Clone, Debug)]
45struct DragState {
46 node_id: NodeId,
47 key: String,
48 start_x: f32,
49 start_val: f64,
50 min: f64,
51 max: f64,
52 width: f32,
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum KeyframeState {
57 Static,
58 AnimatedOtherFrame,
59 KeyframeAtCurrent,
60}
61
62pub struct InspectorState {
63 pub bg: [f32; 4],
64 pub panel_bg: [f32; 4],
65 pub rule: [f32; 4],
66 pub text: [f32; 4],
67 pub text_dim: [f32; 4],
68 pub accent: [f32; 4],
69 expr: ExprEngine,
70 /// Node name edit buffer synced with the currently selected node.
71 name_node: Option<NodeId>,
72 name_buf: String,
73 /// Text parameter edit buffers keyed by `(node_id, param_name)`.
74 text_bufs: HashMap<(usize, String), String>,
75 /// Active scrub slider drag.
76 drag: Option<DragState>,
77 /// Last click timestamp per slider key for double-click reset.
78 last_click: HashMap<String, Instant>,
79}
80
81impl InspectorState {
82 pub fn new(theme: &ui::Theme) -> Self {
83 let b = theme.base;
84 let lift = |c: [f32; 4], d: f32| {
85 [
86 (c[0] + d).clamp(0.0, 1.0),
87 (c[1] + d).clamp(0.0, 1.0),
88 (c[2] + d).clamp(0.0, 1.0),
89 1.0,
90 ]
91 };
92 Self {
93 bg: b,
94 panel_bg: lift(b, 0.020),
95 rule: theme.rule,
96 text: theme.text,
97 text_dim: theme.text_dim,
98 accent: theme.accent,
99 expr: ExprEngine::new(),
100 name_node: None,
101 name_buf: String::new(),
102 text_bufs: HashMap::new(),
103 drag: None,
104 last_click: HashMap::new(),
105 }
106 }
107
108 pub fn background(&self) -> [f32; 4] {
109 self.bg
110 }
111
112 pub fn reset(&mut self) {
113 self.name_node = None;
114 self.name_buf.clear();
115 self.text_bufs.clear();
116 self.drag = None;
117 }
118
119 pub fn build_ui(
120 &mut self,
121 ui: &mut ui::Ui,
122 pane_id: ui::Id,
123 comp: &mut Comp,
124 history: &mut CompHistory,
125 selected: Option<NodeId>,
126 current_frame: f64,
127 stats: &EvalStats,
128 ) -> Vec<InspectorAction> {
129 let mut actions = Vec::new();
130 let bg = self.bg;
131 let panel_bg = self.panel_bg;
132 let rule = self.rule;
133 let text_col = self.text;
134 let text_dim = self.text_dim;
135 let accent = self.accent;
136
137 ui.open_as(
138 pane_id,
139 ui::Spec {
140 size: [ui::fill(), ui::fill()],
141 axis: ui::Axis::Y,
142 fill: Some(bg),
143 ..ui::Spec::default()
144 },
145 );
146
147 let Some(node_id) = selected.filter(|id| id.0 < comp.nodes.len()) else {
148 // Empty state
149 ui.open(
150 "insp-empty",
151 ui::Spec {
152 size: [ui::fill(), ui::fill()],
153 axis: ui::Axis::Y,
154 pad: [14.0, 18.0],
155 gap: 8.0,
156 ..ui::Spec::default()
157 },
158 );
159 ui.leaf(
160 "empty-title",
161 ui::Spec {
162 size: [ui::fill(), ui::px(20.0)],
163 text: Some("No Node Selected"),
164 font_size: Some(12.5),
165 medium: true,
166 color: Some(text_col),
167 ..ui::Spec::default()
168 },
169 );
170 ui.leaf(
171 "empty-hint",
172 ui::Spec {
173 size: [ui::fill(), ui::fit()],
174 text: Some("Select a node in the Flow graph to inspect and keyframe its parameters, or press Shift+Space to add a tool."),
175 font_size: Some(11.0),
176 overflow: ui::Overflow::Wrap,
177 color: Some(text_dim),
178 ..ui::Spec::default()
179 },
180 );
181 self.render_stats_footer(ui, stats, panel_bg, rule, text_dim);
182 ui.close();
183 ui.close();
184 return actions;
185 };
186
187 // Sync editable name buffer when selection changes or node was renamed externally (e.g. undo)
188 let current_name = comp.node(node_id).name.clone();
189 let name_field_id = pane_id.child(("node-name", node_id.0));
190 if self.name_node != Some(node_id)
191 || (ui.focused() != Some(name_field_id) && self.name_buf != current_name)
192 {
193 self.name_node = Some(node_id);
194 self.name_buf = current_name.clone();
195 }
196
197 // 1. Header: Node name + Class badge + Bypass toggle
198 ui.open(
199 "insp-header",
200 ui::Spec {
201 size: [ui::fill(), ui::children()],
202 axis: ui::Axis::Y,
203 pad: [10.0, 8.0],
204 gap: 6.0,
205 fill: Some(panel_bg),
206 border: Some(rule),
207 ..ui::Spec::default()
208 },
209 );
210
211 // Row 1: Editable name + Bypass button
212 ui.open(
213 "insp-name-row",
214 ui::Spec {
215 size: [ui::fill(), ui::px(26.0)],
216 axis: ui::Axis::X,
217 gap: 6.0,
218 ..ui::Spec::default()
219 },
220 );
221 let name_sig = ui::text_field(
222 ui,
223 name_field_id,
224 &mut self.name_buf,
225 "Node name",
226 ui::Spec {
227 size: [ui::fill(), ui::px(24.0)],
228 font_size: Some(12.0),
229 medium: true,
230 fill: Some(bg),
231 border: Some(rule),
232 hover_border: Some(accent),
233 radius: 4.0,
234 pad: [6.0, 2.0],
235 ..ui::Spec::default()
236 },
237 );
238 let enter_pressed = name_sig.events.iter().any(|ev| {
239 matches!(
240 ev,
241 ui::Event::Key { key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Enter), .. }
242 )
243 });
244 if enter_pressed && self.name_buf.trim() != current_name {
245 let desired = self.name_buf.trim().to_owned();
246 history.push_snapshot(comp, "Rename Node");
247 match comp.rename_node(node_id, &desired) {
248 Ok(applied) => {
249 self.name_buf = applied;
250 actions.push(InspectorAction::NodeRenamed(node_id));
251 }
252 Err(e) => {
253 self.name_buf = current_name.clone();
254 actions.push(InspectorAction::StatusNotice(e));
255 }
256 }
257 ui.set_focus(None);
258 }
259
260 let bypassed = comp.node(node_id).bypassed;
261 let pass_lbl = if bypassed { "Bypassed" } else { "Active" };
262 let pass_fill = if bypassed {
263 [0.85, 0.28, 0.28, 0.28]
264 } else {
265 [0.24, 0.78, 0.48, 0.18]
266 };
267 let pass_border = if bypassed {
268 [0.92, 0.36, 0.36, 0.75]
269 } else {
270 [0.28, 0.82, 0.52, 0.55]
271 };
272 let pass_sig = ui.leaf(
273 ("insp-pass", node_id.0),
274 ui::Spec {
275 cursor: Some(winit::window::CursorIcon::Pointer),
276 flags: ui::Flags::CLICKABLE,
277 size: [ui::fit(), ui::px(24.0)],
278 text: Some(pass_lbl),
279 font_size: Some(10.5),
280 medium: true,
281 color: Some(text_col),
282 fill: Some(pass_fill),
283 border: Some(pass_border),
284 radius: 4.0,
285 pad: [8.0, 0.0],
286 center: true,
287 ..ui::Spec::default()
288 },
289 );
290 if pass_sig.clicked {
291 history.push_snapshot(comp, "Toggle Passthrough");
292 comp.toggle_passthrough(node_id);
293 actions.push(InspectorAction::ParamEdited(node_id));
294 }
295 ui.close(); // insp-name-row
296
297 // Row 2: Tool class badge + supported/preserved indicator + frame badge
298 let node_kind = comp.node(node_id).kind.clone();
299 let supported = is_supported_tool(&node_kind);
300 let frame_str = format!("f{:.0}", current_frame);
301 ui.open(
302 "insp-meta-row",
303 ui::Spec {
304 size: [ui::fill(), ui::px(18.0)],
305 axis: ui::Axis::X,
306 gap: 6.0,
307 ..ui::Spec::default()
308 },
309 );
310 ui.leaf(
311 "insp-kind-badge",
312 ui::Spec {
313 size: [ui::fit(), ui::px(18.0)],
314 text: Some(&node_kind),
315 font_size: Some(10.0),
316 medium: true,
317 color: Some(accent),
318 fill: Some([accent[0], accent[1], accent[2], 0.14]),
319 border: Some([accent[0], accent[1], accent[2], 0.40]),
320 radius: 3.0,
321 pad: [6.0, 0.0],
322 center: true,
323 ..ui::Spec::default()
324 },
325 );
326 if !supported {
327 ui.leaf(
328 "insp-preserved-badge",
329 ui::Spec {
330 size: [ui::fit(), ui::px(18.0)],
331 text: Some("preserved"),
332 font_size: Some(9.5),
333 medium: true,
334 color: Some([0.98, 0.78, 0.40, 1.0]),
335 fill: Some([0.24, 0.16, 0.06, 0.85]),
336 border: Some([0.92, 0.64, 0.24, 0.60]),
337 radius: 3.0,
338 pad: [5.0, 0.0],
339 center: true,
340 ..ui::Spec::default()
341 },
342 );
343 }
344 ui.leaf(
345 "insp-spacer",
346 ui::Spec {
347 size: [ui::fill(), ui::px(18.0)],
348 ..ui::Spec::default()
349 },
350 );
351 ui.leaf(
352 "insp-frame",
353 ui::Spec {
354 size: [ui::fit(), ui::px(18.0)],
355 text: Some(&frame_str),
356 font_size: Some(10.0),
357 color: Some(text_dim),
358 center: true,
359 ..ui::Spec::default()
360 },
361 );
362 ui.close(); // insp-meta-row
363 ui.close(); // insp-header
364
365 // 2. Scrollable Parameter List
366 ui.open(
367 "insp-scroll",
368 ui::Spec {
369 flags: ui::Flags::SCROLL | ui::Flags::CLIP,
370 size: [ui::fill(), ui::fill()],
371 axis: ui::Axis::Y,
372 pad: [10.0, 8.0],
373 gap: 6.0,
374 ..ui::Spec::default()
375 },
376 );
377
378 let schema = schema_for_kind(&node_kind);
379 let mut covered: HashSet<&str> = HashSet::new();
380
381 for spec in schema {
382 covered.insert(spec.name);
383 if let ParamKind::Color { r, g, b, a, .. } = spec.kind {
384 covered.insert(r);
385 covered.insert(g);
386 covered.insert(b);
387 if let Some(alpha_k) = a {
388 covered.insert(alpha_k);
389 }
390 }
391 self.render_param_spec(ui, pane_id, comp, history, node_id, spec, current_frame, &mut actions);
392 }
393
394 // Fallback: list all remaining present non-image inputs on the node!
395 let mut extra_keys: Vec<String> = comp
396 .node(node_id)
397 .inputs
398 .iter()
399 .filter_map(|(k, b)| {
400 if covered.contains(k.as_str()) {
401 return None;
402 }
403 // Skip image/node connections unless they also have a value or spline
404 let is_node_conn = b
405 .source_op
406 .as_deref()
407 .is_some_and(|op| comp.node_by_name.contains_key(op));
408 if is_node_conn && b.value.is_none() {
409 return None;
410 }
411 if b.value.is_none() && b.expression.is_none() && b.source_op.is_none() {
412 return None;
413 }
414 Some(k.clone())
415 })
416 .collect();
417 extra_keys.sort();
418
419 if !extra_keys.is_empty() {
420 ui.leaf(
421 "insp-extra-hdr",
422 ui::Spec {
423 size: [ui::fill(), ui::px(18.0)],
424 text: Some("OTHER INPUTS"),
425 font_size: Some(9.5),
426 medium: true,
427 color: Some(text_dim),
428 ..ui::Spec::default()
429 },
430 );
431 for key in extra_keys {
432 self.render_fallback_input(ui, pane_id, comp, history, node_id, &key, current_frame, &mut actions);
433 }
434 }
435
436 // Loader clip info if Loader node
437 if node_kind == "Loader" {
438 let clip_summary = comp
439 .node(node_id)
440 .clips
441 .first()
442 .map(|c| c.filename.clone())
443 .unwrap_or_else(|| "(no clip)".to_owned());
444 ui.open(
445 "insp-loader-clip",
446 ui::Spec {
447 size: [ui::fill(), ui::children()],
448 axis: ui::Axis::Y,
449 gap: 3.0,
450 pad: [6.0, 5.0],
451 fill: Some(panel_bg),
452 border: Some(rule),
453 radius: 4.0,
454 ..ui::Spec::default()
455 },
456 );
457 ui.leaf(
458 "clip-lbl",
459 ui::Spec {
460 size: [ui::fill(), ui::px(14.0)],
461 text: Some("Clip Filename"),
462 font_size: Some(10.0),
463 color: Some(text_dim),
464 ..ui::Spec::default()
465 },
466 );
467 ui.leaf(
468 "clip-path",
469 ui::Spec {
470 size: [ui::fill(), ui::fit()],
471 text: Some(&clip_summary),
472 font_size: Some(10.5),
473 overflow: ui::Overflow::Wrap,
474 color: Some(text_col),
475 ..ui::Spec::default()
476 },
477 );
478 ui.close();
479 }
480
481 ui.close(); // insp-scroll
482
483 // 3. Footer: EvalStats summary
484 self.render_stats_footer(ui, stats, panel_bg, rule, text_dim);
485
486 ui.close(); // pane_id
487 actions
488 }
489
490 fn render_stats_footer(
491 &self,
492 ui: &mut ui::Ui,
493 stats: &EvalStats,
494 panel_bg: [f32; 4],
495 rule: [f32; 4],
496 text_dim: [f32; 4],
497 ) {
498 let line = format!(
499 "Eval {:.1}ms · {} nodes · cache {}/{} · {:.0}MB",
500 stats.eval_ms,
501 stats.nodes_evaluated,
502 stats.cache_hits,
503 stats.cache_hits + stats.cache_misses,
504 stats.cached_vram_mb,
505 );
506 ui.open(
507 "insp-footer",
508 ui::Spec {
509 size: [ui::fill(), ui::px(24.0)],
510 axis: ui::Axis::X,
511 pad: [10.0, 4.0],
512 fill: Some(panel_bg),
513 border: Some(rule),
514 ..ui::Spec::default()
515 },
516 );
517 ui.leaf(
518 "insp-stats-txt",
519 ui::Spec {
520 size: [ui::fill(), ui::fill()],
521 text: Some(&line),
522 font_size: Some(10.0),
523 color: Some(text_dim),
524 ..ui::Spec::default()
525 },
526 );
527 ui.close();
528 }
529
530 #[allow(clippy::too_many_arguments)]
531 fn render_param_spec(
532 &mut self,
533 ui: &mut ui::Ui,
534 pane_id: ui::Id,
535 comp: &mut Comp,
536 history: &mut CompHistory,
537 node_id: NodeId,
538 spec: &ParamSpec,
539 current_frame: f64,
540 actions: &mut Vec<InspectorAction>,
541 ) {
542 match spec.kind {
543 ParamKind::Float { min, max, default, step: _ } => {
544 self.render_float_row(
545 ui,
546 pane_id,
547 comp,
548 history,
549 node_id,
550 spec.name,
551 spec.label,
552 min,
553 max,
554 default,
555 current_frame,
556 actions,
557 );
558 }
559 ParamKind::Vec2 { min, max, default } => {
560 self.render_vec2_row(
561 ui,
562 pane_id,
563 comp,
564 history,
565 node_id,
566 spec.name,
567 spec.label,
568 min,
569 max,
570 default,
571 current_frame,
572 actions,
573 );
574 }
575 ParamKind::Bool { default } => {
576 self.render_bool_row(ui, comp, history, node_id, spec.name, spec.label, default, actions);
577 }
578 ParamKind::Enum { options, default } => {
579 self.render_enum_row(ui, comp, history, node_id, spec.name, spec.label, options, default, actions);
580 }
581 ParamKind::Color { r, g, b, a, default } => {
582 self.render_color_group(
583 ui,
584 pane_id,
585 comp,
586 history,
587 node_id,
588 spec.label,
589 r,
590 g,
591 b,
592 a,
593 default,
594 current_frame,
595 actions,
596 );
597 }
598 ParamKind::Text { default } => {
599 self.render_text_row(ui, pane_id, comp, history, node_id, spec.name, spec.label, default, actions);
600 }
601 }
602 }
603
604 #[allow(clippy::too_many_arguments)]
605 fn render_fallback_input(
606 &mut self,
607 ui: &mut ui::Ui,
608 pane_id: ui::Id,
609 comp: &mut Comp,
610 history: &mut CompHistory,
611 node_id: NodeId,
612 key: &str,
613 current_frame: f64,
614 actions: &mut Vec<InspectorAction>,
615 ) {
616 let val = comp.node(node_id).inputs.get(key).and_then(|b| b.value.clone());
617 match val {
618 Some(ParamValue::Point(pt)) => {
619 self.render_vec2_row(ui, pane_id, comp, history, node_id, key, key, -1.0, 2.0, pt, current_frame, actions);
620 }
621 Some(ParamValue::Text(_)) => {
622 self.render_text_row(ui, pane_id, comp, history, node_id, key, key, "", actions);
623 }
624 Some(ParamValue::FuId(cur)) => {
625 let text_dim = self.text_dim;
626 let text_col = self.text;
627 let panel_bg = self.panel_bg;
628 let rule = self.rule;
629 ui.open(
630 ("fb-fuid", node_id.0, key),
631 ui::Spec {
632 size: [ui::fill(), ui::px(22.0)],
633 axis: ui::Axis::X,
634 gap: 6.0,
635 ..ui::Spec::default()
636 },
637 );
638 ui.leaf(
639 "lbl",
640 ui::Spec {
641 size: [ui::px(92.0), ui::fill()],
642 text: Some(key),
643 font_size: Some(10.5),
644 overflow: ui::Overflow::Ellipsis,
645 color: Some(text_dim),
646 ..ui::Spec::default()
647 },
648 );
649 ui.leaf(
650 "val",
651 ui::Spec {
652 size: [ui::fill(), ui::fill()],
653 text: Some(&cur),
654 font_size: Some(10.5),
655 color: Some(text_col),
656 fill: Some(panel_bg),
657 border: Some(rule),
658 radius: 4.0,
659 pad: [6.0, 0.0],
660 ..ui::Spec::default()
661 },
662 );
663 ui.close();
664 }
665 Some(ParamValue::Number(v)) => {
666 let (min, max) = infer_float_range(key, v);
667 self.render_float_row(ui, pane_id, comp, history, node_id, key, key, min, max, v, current_frame, actions);
668 }
669 None => {
670 // Animated spline or expression-only scalar input
671 let cur = comp.eval_number(comp.node(node_id), key, current_frame, 0.0, &self.expr);
672 let (min, max) = infer_float_range(key, cur);
673 self.render_float_row(ui, pane_id, comp, history, node_id, key, key, min, max, 0.0, current_frame, actions);
674 }
675 _ => {}
676 }
677 }
678
679 #[allow(clippy::too_many_arguments)]
680 fn render_float_row(
681 &mut self,
682 ui: &mut ui::Ui,
683 pane_id: ui::Id,
684 comp: &mut Comp,
685 history: &mut CompHistory,
686 node_id: NodeId,
687 input_name: &str,
688 label: &str,
689 min: f64,
690 max: f64,
691 default: f64,
692 current_frame: f64,
693 actions: &mut Vec<InspectorAction>,
694 ) {
695 let cur_val = comp.eval_number(comp.node(node_id), input_name, current_frame, default, &self.expr);
696 let has_expr = comp
697 .node(node_id)
698 .inputs
699 .get(input_name)
700 .and_then(|b| b.expression.as_ref())
701 .is_some();
702 let kf_state = keyframe_state(comp, node_id, input_name, current_frame);
703
704 ui.open(
705 ("row-f", node_id.0, input_name),
706 ui::Spec {
707 size: [ui::fill(), ui::px(22.0)],
708 axis: ui::Axis::X,
709 gap: 4.0,
710 ..ui::Spec::default()
711 },
712 );
713
714 // Label
715 ui.leaf(
716 "lbl",
717 ui::Spec {
718 size: [ui::px(86.0), ui::fill()],
719 text: Some(label),
720 font_size: Some(10.5),
721 overflow: ui::Overflow::Ellipsis,
722 color: Some(self.text_dim),
723 ..ui::Spec::default()
724 },
725 );
726
727 // Expression `=` badge if present
728 if has_expr {
729 ui.leaf(
730 "expr-badge",
731 ui::Spec {
732 size: [ui::px(16.0), ui::px(18.0)],
733 text: Some("="),
734 font_size: Some(10.5),
735 bold: true,
736 color: Some([0.36, 0.88, 0.92, 1.0]),
737 fill: Some([0.10, 0.24, 0.28, 0.85]),
738 border: Some([0.32, 0.78, 0.86, 0.65]),
739 radius: 3.0,
740 center: true,
741 ..ui::Spec::default()
742 },
743 );
744 }
745
746 // Scrub slider
747 let slider_id = pane_id.child(("sld", node_id.0, input_name));
748 let drag_key = format!("{}:{input_name}", node_id.0);
749 if let Some(new_val) = self.scrub_slider(
750 ui,
751 slider_id,
752 &drag_key,
753 node_id,
754 cur_val,
755 min,
756 max,
757 default,
758 history,
759 comp,
760 input_name,
761 ) {
762 if kf_state != KeyframeState::Static {
763 let _ = comp.set_keyframe(node_id, input_name, current_frame, new_val);
764 actions.push(InspectorAction::KeyframeEdited(node_id));
765 } else {
766 comp.set_input_value(node_id, input_name, ParamValue::Number(new_val));
767 actions.push(InspectorAction::ParamEdited(node_id));
768 }
769 }
770
771 // Reset button (small dot/arrow when non-default)
772 let is_default = (cur_val - default).abs() < 1e-4;
773 if !is_default {
774 let rst = ui.leaf(
775 ("rst", node_id.0, input_name),
776 ui::Spec {
777 cursor: Some(winit::window::CursorIcon::Pointer),
778 flags: ui::Flags::CLICKABLE,
779 size: [ui::px(18.0), ui::px(20.0)],
780 text: Some("↺"),
781 font_size: Some(10.5),
782 color: Some(self.text_dim),
783 hover_fill: Some(self.panel_bg),
784 radius: 3.0,
785 center: true,
786 ..ui::Spec::default()
787 },
788 );
789 if rst.clicked {
790 history.push_snapshot(comp, format!("Reset {label}"));
791 if kf_state != KeyframeState::Static {
792 let _ = comp.set_keyframe(node_id, input_name, current_frame, default);
793 actions.push(InspectorAction::KeyframeEdited(node_id));
794 } else {
795 comp.set_input_value(node_id, input_name, ParamValue::Number(default));
796 actions.push(InspectorAction::ParamEdited(node_id));
797 }
798 }
799 }
800
801 // Keyframe diamond button (`â—†`)
802 if self.keyframe_button(ui, ("kf", node_id.0, input_name), kf_state) {
803 self.toggle_keyframe(comp, history, node_id, input_name, current_frame, cur_val, kf_state, actions);
804 }
805
806 ui.close();
807 }
808
809 #[allow(clippy::too_many_arguments)]
810 fn render_vec2_row(
811 &mut self,
812 ui: &mut ui::Ui,
813 pane_id: ui::Id,
814 comp: &mut Comp,
815 history: &mut CompHistory,
816 node_id: NodeId,
817 input_name: &str,
818 label: &str,
819 min: f64,
820 max: f64,
821 default: [f64; 2],
822 current_frame: f64,
823 actions: &mut Vec<InspectorAction>,
824 ) {
825 let cur = comp.eval_point(comp.node(node_id), input_name, current_frame, default, &self.expr);
826 let has_expr = comp
827 .node(node_id)
828 .inputs
829 .get(input_name)
830 .and_then(|b| b.expression.as_ref())
831 .is_some();
832
833 ui.open(
834 ("row-v2", node_id.0, input_name),
835 ui::Spec {
836 size: [ui::fill(), ui::px(22.0)],
837 axis: ui::Axis::X,
838 gap: 4.0,
839 ..ui::Spec::default()
840 },
841 );
842 ui.leaf(
843 "lbl",
844 ui::Spec {
845 size: [ui::px(86.0), ui::fill()],
846 text: Some(label),
847 font_size: Some(10.5),
848 overflow: ui::Overflow::Ellipsis,
849 color: Some(self.text_dim),
850 ..ui::Spec::default()
851 },
852 );
853 if has_expr {
854 ui.leaf(
855 "expr-badge",
856 ui::Spec {
857 size: [ui::px(16.0), ui::px(18.0)],
858 text: Some("="),
859 font_size: Some(10.5),
860 bold: true,
861 color: Some([0.36, 0.88, 0.92, 1.0]),
862 fill: Some([0.10, 0.24, 0.28, 0.85]),
863 border: Some([0.32, 0.78, 0.86, 0.65]),
864 radius: 3.0,
865 center: true,
866 ..ui::Spec::default()
867 },
868 );
869 }
870
871 let x_id = pane_id.child(("v2x", node_id.0, input_name));
872 let x_key = format!("{}:{input_name}:x", node_id.0);
873 if let Some(nx) = self.scrub_slider(
874 ui,
875 x_id,
876 &x_key,
877 node_id,
878 cur[0],
879 min,
880 max,
881 default[0],
882 history,
883 comp,
884 input_name,
885 ) {
886 comp.set_input_value(node_id, input_name, ParamValue::Point([nx, cur[1]]));
887 actions.push(InspectorAction::ParamEdited(node_id));
888 }
889
890 let y_id = pane_id.child(("v2y", node_id.0, input_name));
891 let y_key = format!("{}:{input_name}:y", node_id.0);
892 if let Some(ny) = self.scrub_slider(
893 ui,
894 y_id,
895 &y_key,
896 node_id,
897 cur[1],
898 min,
899 max,
900 default[1],
901 history,
902 comp,
903 input_name,
904 ) {
905 comp.set_input_value(node_id, input_name, ParamValue::Point([cur[0], ny]));
906 actions.push(InspectorAction::ParamEdited(node_id));
907 }
908
909 ui.close();
910 }
911
912 #[allow(clippy::too_many_arguments)]
913 fn render_bool_row(
914 &mut self,
915 ui: &mut ui::Ui,
916 comp: &mut Comp,
917 history: &mut CompHistory,
918 node_id: NodeId,
919 input_name: &str,
920 label: &str,
921 default: bool,
922 actions: &mut Vec<InspectorAction>,
923 ) {
924 let checked = comp
925 .node(node_id)
926 .static_number(input_name)
927 .map(|v| v >= 0.5)
928 .unwrap_or(default);
929
930 ui.open(
931 ("row-b", node_id.0, input_name),
932 ui::Spec {
933 size: [ui::fill(), ui::px(22.0)],
934 axis: ui::Axis::X,
935 gap: 6.0,
936 ..ui::Spec::default()
937 },
938 );
939 ui.leaf(
940 "lbl",
941 ui::Spec {
942 size: [ui::px(86.0), ui::fill()],
943 text: Some(label),
944 font_size: Some(10.5),
945 overflow: ui::Overflow::Ellipsis,
946 color: Some(self.text_dim),
947 ..ui::Spec::default()
948 },
949 );
950 let fill = if checked {
951 [self.accent[0], self.accent[1], self.accent[2], 0.28]
952 } else {
953 self.panel_bg
954 };
955 let border = if checked { self.accent } else { self.rule };
956 let sig = ui.leaf(
957 ("chk", node_id.0, input_name),
958 ui::Spec {
959 cursor: Some(winit::window::CursorIcon::Pointer),
960 flags: ui::Flags::CLICKABLE,
961 size: [ui::px(54.0), ui::px(20.0)],
962 text: Some(if checked { "✓ On" } else { "Off" }),
963 font_size: Some(10.5),
964 medium: checked,
965 color: Some(if checked { self.text } else { self.text_dim }),
966 fill: Some(fill),
967 border: Some(border),
968 radius: 4.0,
969 center: true,
970 ..ui::Spec::default()
971 },
972 );
973 if sig.clicked {
974 history.push_snapshot(comp, format!("Toggle {label}"));
975 let next = if checked { 0.0 } else { 1.0 };
976 comp.set_input_value(node_id, input_name, ParamValue::Number(next));
977 actions.push(InspectorAction::ParamEdited(node_id));
978 }
979 ui.close();
980 }
981
982 #[allow(clippy::too_many_arguments)]
983 fn render_enum_row(
984 &mut self,
985 ui: &mut ui::Ui,
986 comp: &mut Comp,
987 history: &mut CompHistory,
988 node_id: NodeId,
989 input_name: &str,
990 label: &str,
991 options: &'static [&'static str],
992 default: &'static str,
993 actions: &mut Vec<InspectorAction>,
994 ) {
995 let cur = comp
996 .node(node_id)
997 .static_str(input_name)
998 .unwrap_or(default)
999 .to_owned();
1000
1001 ui.open(
1002 ("row-e", node_id.0, input_name),
1003 ui::Spec {
1004 size: [ui::fill(), ui::px(22.0)],
1005 axis: ui::Axis::X,
1006 gap: 6.0,
1007 ..ui::Spec::default()
1008 },
1009 );
1010 ui.leaf(
1011 "lbl",
1012 ui::Spec {
1013 size: [ui::px(86.0), ui::fill()],
1014 text: Some(label),
1015 font_size: Some(10.5),
1016 overflow: ui::Overflow::Ellipsis,
1017 color: Some(self.text_dim),
1018 ..ui::Spec::default()
1019 },
1020 );
1021 let btn_lbl = format!("{cur} ▾");
1022 let sig = ui.leaf(
1023 ("enum", node_id.0, input_name),
1024 ui::Spec {
1025 cursor: Some(winit::window::CursorIcon::Pointer),
1026 flags: ui::Flags::CLICKABLE,
1027 size: [ui::fill(), ui::px(20.0)],
1028 text: Some(&btn_lbl),
1029 font_size: Some(10.5),
1030 color: Some(self.text),
1031 fill: Some(self.panel_bg),
1032 border: Some(self.rule),
1033 hover_border: Some(self.accent),
1034 radius: 4.0,
1035 pad: [6.0, 0.0],
1036 ..ui::Spec::default()
1037 },
1038 );
1039 if sig.clicked && !options.is_empty() {
1040 let idx = options.iter().position(|&o| o == cur).unwrap_or(0);
1041 let next_idx = if ui.modifiers().shift_key() {
1042 (idx + options.len() - 1) % options.len()
1043 } else {
1044 (idx + 1) % options.len()
1045 };
1046 history.push_snapshot(comp, format!("Set {label}"));
1047 comp.set_input_value(node_id, input_name, ParamValue::FuId(options[next_idx].to_owned()));
1048 actions.push(InspectorAction::ParamEdited(node_id));
1049 }
1050 ui.close();
1051 }
1052
1053 #[allow(clippy::too_many_arguments)]
1054 fn render_color_group(
1055 &mut self,
1056 ui: &mut ui::Ui,
1057 pane_id: ui::Id,
1058 comp: &mut Comp,
1059 history: &mut CompHistory,
1060 node_id: NodeId,
1061 label: &str,
1062 r_key: &'static str,
1063 g_key: &'static str,
1064 b_key: &'static str,
1065 a_key: Option<&'static str>,
1066 default: [f64; 4],
1067 current_frame: f64,
1068 actions: &mut Vec<InspectorAction>,
1069 ) {
1070 let rv = comp.eval_number(comp.node(node_id), r_key, current_frame, default[0], &self.expr);
1071 let gv = comp.eval_number(comp.node(node_id), g_key, current_frame, default[1], &self.expr);
1072 let bv = comp.eval_number(comp.node(node_id), b_key, current_frame, default[2], &self.expr);
1073 let _av = a_key
1074 .map(|ak| comp.eval_number(comp.node(node_id), ak, current_frame, default[3], &self.expr))
1075 .unwrap_or(default[3]);
1076 let swatch = [
1077 rv.clamp(0.0, 1.0) as f32,
1078 gv.clamp(0.0, 1.0) as f32,
1079 bv.clamp(0.0, 1.0) as f32,
1080 1.0,
1081 ];
1082
1083 ui.open(
1084 ("grp-col", node_id.0, label),
1085 ui::Spec {
1086 size: [ui::fill(), ui::children()],
1087 axis: ui::Axis::Y,
1088 gap: 4.0,
1089 pad: [6.0, 5.0],
1090 fill: Some(self.panel_bg),
1091 border: Some(self.rule),
1092 radius: 4.0,
1093 ..ui::Spec::default()
1094 },
1095 );
1096 // Swatch header
1097 ui.open(
1098 "col-hdr",
1099 ui::Spec {
1100 size: [ui::fill(), ui::px(18.0)],
1101 axis: ui::Axis::X,
1102 gap: 6.0,
1103 ..ui::Spec::default()
1104 },
1105 );
1106 ui.leaf(
1107 "col-lbl",
1108 ui::Spec {
1109 size: [ui::px(80.0), ui::fill()],
1110 text: Some(label),
1111 font_size: Some(10.5),
1112 medium: true,
1113 color: Some(self.text),
1114 ..ui::Spec::default()
1115 },
1116 );
1117 ui.leaf(
1118 "col-swatch",
1119 ui::Spec {
1120 size: [ui::fill(), ui::px(16.0)],
1121 fill: Some(swatch),
1122 border: Some(self.rule),
1123 radius: 3.0,
1124 ..ui::Spec::default()
1125 },
1126 );
1127 ui.close();
1128
1129 self.render_float_row(ui, pane_id, comp, history, node_id, r_key, "Red", 0.0, 1.0, default[0], current_frame, actions);
1130 self.render_float_row(ui, pane_id, comp, history, node_id, g_key, "Green", 0.0, 1.0, default[1], current_frame, actions);
1131 self.render_float_row(ui, pane_id, comp, history, node_id, b_key, "Blue", 0.0, 1.0, default[2], current_frame, actions);
1132 if let Some(ak) = a_key {
1133 self.render_float_row(ui, pane_id, comp, history, node_id, ak, "Alpha", 0.0, 1.0, default[3], current_frame, actions);
1134 }
1135 ui.close();
1136 }
1137
1138 #[allow(clippy::too_many_arguments)]
1139 fn render_text_row(
1140 &mut self,
1141 ui: &mut ui::Ui,
1142 pane_id: ui::Id,
1143 comp: &mut Comp,
1144 history: &mut CompHistory,
1145 node_id: NodeId,
1146 input_name: &str,
1147 label: &str,
1148 default: &str,
1149 actions: &mut Vec<InspectorAction>,
1150 ) {
1151 let field_id = pane_id.child(("txt", node_id.0, input_name));
1152 let key = (node_id.0, input_name.to_owned());
1153 let model_val = comp
1154 .node(node_id)
1155 .static_str(input_name)
1156 .unwrap_or(default)
1157 .to_owned();
1158 let buf = self.text_bufs.entry(key).or_insert_with(|| model_val.clone());
1159 if ui.focused() != Some(field_id) && *buf != model_val {
1160 *buf = model_val.clone();
1161 }
1162 let prev = buf.clone();
1163
1164 ui.open(
1165 ("row-t", node_id.0, input_name),
1166 ui::Spec {
1167 size: [ui::fill(), ui::px(24.0)],
1168 axis: ui::Axis::X,
1169 gap: 6.0,
1170 ..ui::Spec::default()
1171 },
1172 );
1173 ui.leaf(
1174 "lbl",
1175 ui::Spec {
1176 size: [ui::px(86.0), ui::fill()],
1177 text: Some(label),
1178 font_size: Some(10.5),
1179 overflow: ui::Overflow::Ellipsis,
1180 color: Some(self.text_dim),
1181 ..ui::Spec::default()
1182 },
1183 );
1184 ui::text_field(
1185 ui,
1186 field_id,
1187 buf,
1188 label,
1189 ui::Spec {
1190 size: [ui::fill(), ui::px(22.0)],
1191 font_size: Some(11.0),
1192 fill: Some(self.panel_bg),
1193 border: Some(self.rule),
1194 hover_border: Some(self.accent),
1195 radius: 4.0,
1196 pad: [6.0, 2.0],
1197 ..ui::Spec::default()
1198 },
1199 );
1200 if *buf != prev {
1201 history.push_coalesced(
1202 comp,
1203 format!("Edit {label}"),
1204 format!("text:{}:{input_name}", node_id.0),
1205 );
1206 comp.set_input_value(node_id, input_name, ParamValue::Text(buf.clone()));
1207 actions.push(InspectorAction::ParamEdited(node_id));
1208 }
1209 ui.close();
1210 }
1211
1212 #[allow(clippy::too_many_arguments)]
1213 fn scrub_slider(
1214 &mut self,
1215 ui: &mut ui::Ui,
1216 slider_id: ui::Id,
1217 drag_key: &str,
1218 node_id: NodeId,
1219 value: f64,
1220 min: f64,
1221 max: f64,
1222 default: f64,
1223 history: &mut CompHistory,
1224 comp: &Comp,
1225 input_name: &str,
1226 ) -> Option<f64> {
1227 let sig = ui.signal(slider_id);
1228 let rect = ui.laid_out(slider_id);
1229 let width = rect.map(|r| (r[2] - r[0]).max(40.0)).unwrap_or(110.0);
1230 let mut updated: Option<f64> = None;
1231
1232 if let Some(press) = sig.press {
1233 let now = Instant::now();
1234 let is_double = self
1235 .last_click
1236 .get(drag_key)
1237 .is_some_and(|prev| now.duration_since(*prev) < Duration::from_millis(320));
1238 self.last_click.insert(drag_key.to_owned(), now);
1239 if is_double {
1240 history.push_snapshot(comp, format!("Reset {input_name}"));
1241 self.drag = None;
1242 updated = Some(default);
1243 } else {
1244 self.drag = Some(DragState {
1245 node_id,
1246 key: drag_key.to_owned(),
1247 start_x: press[0],
1248 start_val: value,
1249 min,
1250 max,
1251 width,
1252 });
1253 }
1254 } else if sig.dragging {
1255 if let (Some(d), Some(ptr)) = (&self.drag, ui.pointer()) {
1256 if d.key == drag_key && d.node_id == node_id {
1257 let fine = if ui.modifiers().shift_key() { 0.15 } else { 1.0 };
1258 let next = compute_scrub_value(d.start_val, ptr[0] - d.start_x, d.width, d.min, d.max, fine);
1259 if (next - value).abs() > 1e-6 {
1260 history.push_coalesced(
1261 comp,
1262 format!("Adjust {input_name}"),
1263 format!("scrub:{drag_key}"),
1264 );
1265 updated = Some(next);
1266 }
1267 }
1268 }
1269 } else if self.drag.as_ref().is_some_and(|d| d.key == drag_key) {
1270 self.drag = None;
1271 history.break_coalescing();
1272 }
1273
1274 let display_val = updated.unwrap_or(value);
1275 let frac = normalize_slider_fraction(display_val, min, max);
1276 let val_text = format_param_number(display_val);
1277 let fill_w = (width * frac).clamp(0.0, width);
1278 let active_drag = self.drag.as_ref().is_some_and(|d| d.key == drag_key);
1279
1280 ui.open_as(
1281 slider_id,
1282 ui::Spec {
1283 cursor: Some(winit::window::CursorIcon::EwResize),
1284 flags: ui::Flags::CLICKABLE | ui::Flags::CLIP,
1285 size: [ui::fill(), ui::px(20.0)],
1286 fill: Some(self.panel_bg),
1287 border: Some(if active_drag || sig.hovered { self.accent } else { self.rule }),
1288 radius: 4.0,
1289 ..ui::Spec::default()
1290 },
1291 );
1292 if fill_w > 0.5 {
1293 ui.leaf(
1294 "fill",
1295 ui::Spec {
1296 flags: ui::Flags::FLOAT | ui::Flags::INERT,
1297 position: [0.0, 0.0],
1298 size: [ui::px(fill_w), ui::px(20.0)],
1299 fill: Some([self.accent[0], self.accent[1], self.accent[2], if active_drag { 0.34 } else { 0.22 }]),
1300 radius: 3.0,
1301 ..ui::Spec::default()
1302 },
1303 );
1304 }
1305 ui.leaf(
1306 "txt",
1307 ui::Spec {
1308 flags: ui::Flags::INERT,
1309 size: [ui::fill(), ui::fill()],
1310 text: Some(&val_text),
1311 font_size: Some(10.5),
1312 color: Some(self.text),
1313 center: true,
1314 ..ui::Spec::default()
1315 },
1316 );
1317 ui.close();
1318
1319 updated
1320 }
1321
1322 fn keyframe_button(&self, ui: &mut ui::Ui, part: impl std::hash::Hash, state: KeyframeState) -> bool {
1323 let (ink, fill, border) = match state {
1324 KeyframeState::KeyframeAtCurrent => (
1325 [1.0, 0.80, 0.22, 1.0],
1326 Some([0.98, 0.72, 0.18, 0.24]),
1327 Some([0.98, 0.76, 0.20, 0.85]),
1328 ),
1329 KeyframeState::AnimatedOtherFrame => (
1330 [0.92, 0.64, 0.24, 0.90],
1331 Some([0.92, 0.64, 0.24, 0.12]),
1332 Some([0.92, 0.64, 0.24, 0.45]),
1333 ),
1334 KeyframeState::Static => (self.text_dim, None, None),
1335 };
1336 let sig = ui.leaf(
1337 part,
1338 ui::Spec {
1339 cursor: Some(winit::window::CursorIcon::Pointer),
1340 flags: ui::Flags::CLICKABLE,
1341 size: [ui::px(20.0), ui::px(20.0)],
1342 text: Some("â—†"),
1343 font_size: Some(10.5),
1344 color: Some(ink),
1345 fill,
1346 border,
1347 hover_fill: Some([0.98, 0.76, 0.22, 0.18]),
1348 radius: 4.0,
1349 center: true,
1350 ..ui::Spec::default()
1351 },
1352 );
1353 sig.clicked
1354 }
1355
1356 #[allow(clippy::too_many_arguments)]
1357 fn toggle_keyframe(
1358 &self,
1359 comp: &mut Comp,
1360 history: &mut CompHistory,
1361 node_id: NodeId,
1362 input_name: &str,
1363 current_frame: f64,
1364 cur_val: f64,
1365 state: KeyframeState,
1366 actions: &mut Vec<InspectorAction>,
1367 ) {
1368 match state {
1369 KeyframeState::KeyframeAtCurrent => {
1370 if let Some(sp_name) = comp
1371 .node(node_id)
1372 .inputs
1373 .get(input_name)
1374 .and_then(|b| b.source_op.clone())
1375 {
1376 history.push_snapshot(comp, format!("Delete Keyframe {input_name}"));
1377 if comp.delete_keyframe(&sp_name, current_frame) {
1378 actions.push(InspectorAction::KeyframeEdited(node_id));
1379 actions.push(InspectorAction::StatusNotice(format!(
1380 "Deleted keyframe on {input_name} @ f{current_frame:.0}"
1381 )));
1382 }
1383 }
1384 }
1385 KeyframeState::Static | KeyframeState::AnimatedOtherFrame => {
1386 history.push_snapshot(comp, format!("Set Keyframe {input_name}"));
1387 match comp.set_keyframe(node_id, input_name, current_frame, cur_val) {
1388 Ok(_) => {
1389 actions.push(InspectorAction::KeyframeEdited(node_id));
1390 actions.push(InspectorAction::StatusNotice(format!(
1391 "Keyframed {input_name} = {:.3} @ f{current_frame:.0}",
1392 cur_val
1393 )));
1394 }
1395 Err(e) => actions.push(InspectorAction::StatusNotice(e)),
1396 }
1397 }
1398 }
1399 }
1400}
1401
1402/// Computes whether an input is static, animated on another frame, or has a keyframe at `frame`.
1403pub fn keyframe_state(comp: &Comp, node_id: NodeId, input_name: &str, frame: f64) -> KeyframeState {
1404 let Some(sp_name) = comp
1405 .node(node_id)
1406 .inputs
1407 .get(input_name)
1408 .and_then(|b| b.source_op.as_deref())
1409 else {
1410 return KeyframeState::Static;
1411 };
1412 let Some(spline) = comp.splines.get(sp_name) else {
1413 return KeyframeState::Static;
1414 };
1415 if spline.keyframes.iter().any(|kf| (kf.time - frame).abs() < 1e-4) {
1416 KeyframeState::KeyframeAtCurrent
1417 } else if !spline.keyframes.is_empty() {
1418 KeyframeState::AnimatedOtherFrame
1419 } else {
1420 KeyframeState::Static
1421 }
1422}
1423
1424pub fn normalize_slider_fraction(value: f64, min: f64, max: f64) -> f32 {
1425 let span = (max - min).abs().max(1e-6);
1426 ((value - min) / span).clamp(0.0, 1.0) as f32
1427}
1428
1429pub fn compute_scrub_value(start_val: f64, dx: f32, width: f32, min: f64, max: f64, fine_scale: f64) -> f64 {
1430 let span = (max - min).max(1e-4);
1431 let delta = (f64::from(dx) / f64::from(width.max(40.0))) * span * fine_scale;
1432 (start_val + delta).clamp(min, max)
1433}
1434
1435pub fn format_param_number(v: f64) -> String {
1436 if v.abs() >= 100.0 {
1437 format!("{v:.1}")
1438 } else if v.abs() >= 10.0 {
1439 format!("{v:.2}")
1440 } else {
1441 format!("{v:.3}")
1442 }
1443}
1444
1445pub fn infer_float_range(name: &str, val: f64) -> (f64, f64) {
1446 let lower = name.to_ascii_lowercase();
1447 if lower.contains("angle") || lower.contains("rotate") {
1448 (-360.0, 360.0)
1449 } else if lower.contains("width") || lower.contains("height") {
1450 if val > 2.0 {
1451 (1.0, (val * 2.0).max(4096.0))
1452 } else {
1453 (0.0, 2.0)
1454 }
1455 } else if lower.contains("blend") || lower.contains("alpha") || lower.contains("opacity") {
1456 (0.0, 1.0)
1457 } else if lower.contains("size") || lower.contains("blur") || lower.contains("glow") {
1458 (0.0, (val.abs() * 2.0).max(50.0))
1459 } else if val < 0.0 || val > 1.0 {
1460 let hi = (val.abs() * 2.0).max(10.0);
1461 (-hi, hi)
1462 } else {
1463 (0.0, 1.0)
1464 }
1465}
1466
1467const APPLY_MODES: &[&str] = &[
1468 "Normal",
1469 "Screen",
1470 "Multiply",
1471 "Overlay",
1472 "Soft Light",
1473 "Hard Light",
1474 "Color Dodge",
1475 "Color Burn",
1476 "Darken",
1477 "Lighten",
1478 "Difference",
1479 "Exclusion",
1480 "Hue",
1481 "Saturation",
1482 "Color",
1483 "Luminosity",
1484];
1485
1486const BLUR_FILTERS: &[&str] = &["Fast Gaussian", "Gaussian", "Box", "Bartlett", "Multi-box"];
1487const CLIPPING_MODES: &[&str] = &["Frame", "Domain", "None"];
1488const EDGES_MODES: &[&str] = &["Canvas", "Wrap", "Duplicate", "Mirror"];
1489const SHAPE3D_TYPES: &[&str] = &[
1490 "SurfacePlaneInputs",
1491 "SurfaceSphereInputs",
1492 "SurfaceCubeInputs",
1493 "SurfaceCylinderInputs",
1494 "SurfaceConeInputs",
1495 "SurfaceTorusInputs",
1496];
1497
1498const fn flt(name: &'static str, label: &'static str, min: f64, max: f64, default: f64) -> ParamSpec {
1499 ParamSpec {
1500 name,
1501 label,
1502 kind: ParamKind::Float { min, max, default, step: 0.01 },
1503 }
1504}
1505
1506const fn v2(name: &'static str, label: &'static str, min: f64, max: f64, default: [f64; 2]) -> ParamSpec {
1507 ParamSpec {
1508 name,
1509 label,
1510 kind: ParamKind::Vec2 { min, max, default },
1511 }
1512}
1513
1514const fn boolean(name: &'static str, label: &'static str, default: bool) -> ParamSpec {
1515 ParamSpec {
1516 name,
1517 label,
1518 kind: ParamKind::Bool { default },
1519 }
1520}
1521
1522const fn fuid(
1523 name: &'static str,
1524 label: &'static str,
1525 options: &'static [&'static str],
1526 default: &'static str,
1527) -> ParamSpec {
1528 ParamSpec {
1529 name,
1530 label,
1531 kind: ParamKind::Enum { options, default },
1532 }
1533}
1534
1535/// Curated Fusion 21.1 parameter schemas for major compositor tools.
1536pub fn schema_for_kind(kind: &str) -> &'static [ParamSpec] {
1537 match kind {
1538 "Merge" => const { &[
1539 fuid("ApplyMode", "Apply Mode", APPLY_MODES, "Normal"),
1540 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1541 flt("SubMerge", "Subtractive", 0.0, 1.0, 0.0),
1542 v2("Center", "Center", -1.0, 2.0, [0.5, 0.5]),
1543 flt("Size", "Size", 0.0, 5.0, 1.0),
1544 flt("Angle", "Angle", -360.0, 360.0, 0.0),
1545 boolean("FlipHoriz", "Flip Horiz", false),
1546 boolean("FlipVert", "Flip Vert", false),
1547 fuid("Edges", "Edges", EDGES_MODES, "Canvas"),
1548 boolean("PerformDepthMerge", "Depth Merge", false),
1549 ] },
1550 "Transform" => const { &[
1551 v2("Center", "Center", -1.0, 2.0, [0.5, 0.5]),
1552 v2("Pivot", "Pivot", -1.0, 2.0, [0.5, 0.5]),
1553 flt("Size", "Size", 0.0, 5.0, 1.0),
1554 flt("Aspect", "Aspect", 0.1, 4.0, 1.0),
1555 flt("Angle", "Angle", -360.0, 360.0, 0.0),
1556 boolean("FlipHoriz", "Flip Horiz", false),
1557 boolean("FlipVert", "Flip Vert", false),
1558 fuid("Edges", "Edges", EDGES_MODES, "Canvas"),
1559 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1560 ] },
1561 "Blur" => const { &[
1562 fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"),
1563 boolean("LockXY", "Lock X/Y", true),
1564 flt("XBlurSize", "Blur Size", 0.0, 100.0, 1.0),
1565 flt("YBlurSize", "Y Blur Size", 0.0, 100.0, 1.0),
1566 fuid("ClippingMode", "Clipping", CLIPPING_MODES, "Frame"),
1567 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1568 ] },
1569 "Glow" => const { &[
1570 flt("XGlowSize", "Glow Size", 0.0, 100.0, 10.0),
1571 flt("Glow", "Glow", 0.0, 2.0, 0.8),
1572 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1573 fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"),
1574 ] },
1575 "SoftGlow" => const { &[
1576 fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"),
1577 flt("Threshold", "Threshold", 0.0, 1.0, 0.0),
1578 flt("Gain", "Gain", 0.0, 5.0, 2.0),
1579 flt("XGlowSize", "Glow Size", 0.0, 100.0, 10.0),
1580 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1581 ] },
1582 "BrightnessContrast" => const { &[
1583 flt("Gain", "Gain", 0.0, 5.0, 1.0),
1584 flt("Lift", "Lift", -1.0, 1.0, 0.0),
1585 flt("Gamma", "Gamma", 0.05, 5.0, 1.0),
1586 flt("Contrast", "Contrast", -1.0, 1.0, 0.0),
1587 flt("Brightness", "Brightness", -1.0, 1.0, 0.0),
1588 flt("Saturation", "Saturation", 0.0, 4.0, 1.0),
1589 boolean("PreDividePostMultiply", "Pre-Div/Post", false),
1590 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1591 ] },
1592 "ColorCorrector" => const { &[
1593 flt("WheelSaturation1", "Saturation", 0.0, 4.0, 1.0),
1594 flt("WheelHue1", "Hue", -1.0, 1.0, 0.0),
1595 flt("MasterRGBGain", "Gain", 0.0, 5.0, 1.0),
1596 flt("MasterRGBGamma", "Gamma", 0.05, 5.0, 1.0),
1597 flt("MasterRGBLift", "Lift", -1.0, 1.0, 0.0),
1598 flt("MasterRGBContrast", "Contrast", 0.0, 3.0, 1.0),
1599 flt("MasterRGBBrightness", "Brightness", -1.0, 1.0, 0.0),
1600 boolean("PreDividePostMultiply", "Pre-Div/Post", false),
1601 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1602 ] },
1603 "Background" => const { &[
1604 ParamSpec {
1605 name: "TopLeftColor",
1606 label: "Color",
1607 kind: ParamKind::Color {
1608 r: "TopLeftRed",
1609 g: "TopLeftGreen",
1610 b: "TopLeftBlue",
1611 a: Some("TopLeftAlpha"),
1612 default: [0.0, 0.0, 0.0, 1.0],
1613 },
1614 },
1615 flt("Width", "Width", 1.0, 7680.0, 1920.0),
1616 flt("Height", "Height", 1.0, 4320.0, 1080.0),
1617 ] },
1618 "TextPlus" => const { &[
1619 ParamSpec {
1620 name: "StyledText",
1621 label: "Styled Text",
1622 kind: ParamKind::Text { default: "" },
1623 },
1624 ParamSpec {
1625 name: "Font",
1626 label: "Font",
1627 kind: ParamKind::Text { default: "Open Sans" },
1628 },
1629 flt("Size", "Size", 0.005, 1.0, 0.08),
1630 flt("Tracking", "Tracking", 0.0, 4.0, 1.0),
1631 v2("Center", "Center", -1.0, 2.0, [0.5, 0.5]),
1632 ParamSpec {
1633 name: "TextColor",
1634 label: "Text Color",
1635 kind: ParamKind::Color {
1636 r: "Red1",
1637 g: "Green1",
1638 b: "Blue1",
1639 a: Some("Alpha1"),
1640 default: [1.0, 1.0, 1.0, 1.0],
1641 },
1642 },
1643 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1644 ] },
1645 "EllipseMask" => const { &[
1646 flt("Level", "Level", 0.0, 1.0, 1.0),
1647 flt("SoftEdge", "Soft Edge", 0.0, 0.5, 0.0),
1648 flt("BorderWidth", "Border", -0.2, 0.2, 0.0),
1649 boolean("Solid", "Solid", true),
1650 boolean("Invert", "Invert", false),
1651 v2("Center", "Center", -0.5, 1.5, [0.5, 0.5]),
1652 flt("Width", "Width", 0.0, 2.0, 0.5),
1653 flt("Height", "Height", 0.0, 2.0, 0.5),
1654 flt("Angle", "Angle", -360.0, 360.0, 0.0),
1655 ] },
1656 "RectangleMask" => const { &[
1657 flt("Level", "Level", 0.0, 1.0, 1.0),
1658 flt("SoftEdge", "Soft Edge", 0.0, 0.5, 0.0),
1659 flt("CornerRadius", "Corner", 0.0, 1.0, 0.0),
1660 boolean("Solid", "Solid", true),
1661 boolean("Invert", "Invert", false),
1662 v2("Center", "Center", -0.5, 1.5, [0.5, 0.5]),
1663 flt("Width", "Width", 0.0, 2.0, 0.5),
1664 flt("Height", "Height", 0.0, 2.0, 0.5),
1665 flt("Angle", "Angle", -360.0, 360.0, 0.0),
1666 ] },
1667 "Displace" => const { &[
1668 flt("XRefraction", "X Refract", -1.0, 1.0, 0.0),
1669 flt("YRefraction", "Y Refract", -1.0, 1.0, 0.0),
1670 flt("RefractionStrength", "Strength", -2.0, 2.0, 0.0),
1671 flt("LightAngle", "Light Angle", -360.0, 360.0, 0.0),
1672 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1673 ] },
1674 "Vortex" => const { &[
1675 v2("Center", "Center", -0.5, 1.5, [0.5, 0.5]),
1676 flt("Size", "Size", 0.0, 2.0, 0.5),
1677 flt("Angle", "Angle", -720.0, 720.0, 90.0),
1678 flt("Power", "Power", 0.1, 5.0, 1.0),
1679 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1680 ] },
1681 "FastNoise" => const { &[
1682 flt("Detail", "Detail", 0.0, 10.0, 2.0),
1683 flt("Contrast", "Contrast", 0.0, 5.0, 1.0),
1684 flt("Brightness", "Brightness", -1.0, 1.0, 0.0),
1685 flt("XScale", "Scale", 0.01, 50.0, 2.0),
1686 flt("Seethe", "Seethe", 0.0, 100.0, 0.0),
1687 flt("SeetheRate", "Seethe Rate", 0.0, 2.0, 0.0),
1688 v2("Center", "Center", -2.0, 3.0, [0.5, 0.5]),
1689 ] },
1690 "UltraKeyer" => const { &[
1691 ParamSpec {
1692 name: "KeyColor",
1693 label: "Key Color",
1694 kind: ParamKind::Color {
1695 r: "BackgroundRed",
1696 g: "BackgroundGreen",
1697 b: "BackgroundBlue",
1698 a: None,
1699 default: [0.0, 1.0, 0.0, 1.0],
1700 },
1701 },
1702 flt("MatteThresholdLow", "Matte Low", 0.0, 1.0, 0.0),
1703 flt("MatteThresholdHigh", "Matte High", 0.0, 1.0, 1.0),
1704 flt("SpillSuppression", "Spill", 0.0, 1.0, 0.0),
1705 boolean("PostMultiplyImage", "Post-Multiply", true),
1706 flt("Blend", "Blend", 0.0, 1.0, 1.0),
1707 ] },
1708 "Loader" => const { &[
1709 flt("GlobalIn", "Global In", 0.0, 10000.0, 0.0),
1710 flt("GlobalOut", "Global Out", 0.0, 10000.0, 100.0),
1711 boolean("Loop", "Loop", false),
1712 boolean("Reverse", "Reverse", false),
1713 ] },
1714 "Camera3D" => const { &[
1715 flt("FLength", "Focal Len", 5.0, 200.0, 24.0),
1716 flt("PlaneOfFocus", "Focus Dist", 0.1, 100.0, 5.0),
1717 flt("Transform3DOp.Translate.X", "Trans X", -50.0, 50.0, 0.0),
1718 flt("Transform3DOp.Translate.Y", "Trans Y", -50.0, 50.0, 0.0),
1719 flt("Transform3DOp.Translate.Z", "Trans Z", -50.0, 50.0, 5.0),
1720 flt("Transform3DOp.Rotate.X", "Rot X", -180.0, 180.0, 0.0),
1721 flt("Transform3DOp.Rotate.Y", "Rot Y", -180.0, 180.0, 0.0),
1722 flt("Transform3DOp.Rotate.Z", "Rot Z", -180.0, 180.0, 0.0),
1723 ] },
1724 "Shape3D" => const { &[
1725 fuid("Shape", "Shape", SHAPE3D_TYPES, "SurfacePlaneInputs"),
1726 flt("SurfacePlaneInputs.Width", "Width", 0.01, 20.0, 1.0),
1727 flt("SurfacePlaneInputs.Height", "Height", 0.01, 20.0, 1.0),
1728 flt("Transform3DOp.Translate.X", "Trans X", -50.0, 50.0, 0.0),
1729 flt("Transform3DOp.Translate.Y", "Trans Y", -50.0, 50.0, 0.0),
1730 flt("Transform3DOp.Translate.Z", "Trans Z", -50.0, 50.0, 0.0),
1731 flt("Transform3DOp.Scale.X", "Scale", 0.01, 20.0, 1.0),
1732 ] },
1733 _ => &[],
1734 }
1735}
1736
1737#[cfg(test)]
1738mod tests {
1739 use super::*;
1740
1741 #[test]
1742 fn curated_schemas_cover_all_major_tools() {
1743 let major = [
1744 "Merge",
1745 "Transform",
1746 "Blur",
1747 "Glow",
1748 "SoftGlow",
1749 "BrightnessContrast",
1750 "ColorCorrector",
1751 "Background",
1752 "TextPlus",
1753 "EllipseMask",
1754 "RectangleMask",
1755 "Displace",
1756 "Vortex",
1757 "FastNoise",
1758 "UltraKeyer",
1759 "Loader",
1760 "Camera3D",
1761 "Shape3D",
1762 ];
1763 for tool in major {
1764 let s = schema_for_kind(tool);
1765 assert!(!s.is_empty(), "expected non-empty curated schema for {tool}");
1766 }
1767 assert!(schema_for_kind("UnknownCustomTool").is_empty());
1768 }
1769
1770 #[test]
1771 fn slider_math_and_clamping() {
1772 assert!((normalize_slider_fraction(0.5, 0.0, 1.0) - 0.5).abs() < 1e-6);
1773 assert!((normalize_slider_fraction(-5.0, 0.0, 1.0) - 0.0).abs() < 1e-6);
1774 assert!((normalize_slider_fraction(10.0, 0.0, 1.0) - 1.0).abs() < 1e-6);
1775
1776 let v = compute_scrub_value(0.5, 50.0, 100.0, 0.0, 1.0, 1.0);
1777 assert!((v - 1.0).abs() < 1e-6);
1778 let v_fine = compute_scrub_value(0.5, 50.0, 100.0, 0.0, 1.0, 0.1);
1779 assert!((v_fine - 0.55).abs() < 1e-6);
1780 }
1781
1782 #[test]
1783 fn keyframe_state_transitions() {
1784 let src = r#"Composition {
1785 Tools = ordered() {
1786 BC1 = BrightnessContrast {
1787 Inputs = { Gain = Input { Value = 1.0 } },
1788 },
1789 },
1790 }"#;
1791 let mut comp = Comp::from_fusion_str(src).unwrap();
1792 let bc = comp.find_node("BC1").unwrap();
1793 assert_eq!(keyframe_state(&comp, bc, "Gain", 10.0), KeyframeState::Static);
1794
1795 let sp = comp.set_keyframe(bc, "Gain", 10.0, 1.5).unwrap();
1796 assert_eq!(keyframe_state(&comp, bc, "Gain", 10.0), KeyframeState::KeyframeAtCurrent);
1797 assert_eq!(keyframe_state(&comp, bc, "Gain", 20.0), KeyframeState::AnimatedOtherFrame);
1798
1799 assert!(comp.delete_keyframe(&sp, 10.0));
1800 assert_eq!(keyframe_state(&comp, bc, "Gain", 10.0), KeyframeState::Static);
1801 }
1802}
crates/studio/src/main.rs+606-94
...@@ -1,15 +1,21 @@...@@ -1,15 +1,21 @@
1//! Compositor Studio — docked zero-copy `wgpu` Multi-Viewer (`1`/`2`) + Flow + Blender-style Spline Editor1//! Compositor Studio — docked zero-copy `wgpu` Multi-Viewer (`1`/`2`) + Flow + Blender-style Spline Editor
2//! built on Knife's `draw`, `ui`, `dock`, and `theme::KNIFE` (soft toned quiet iris).2//! built on Knife's `draw`, `ui`, `dock`, and `theme::KNIFE` (soft toned quiet iris).
33
4mod add_tool;
5mod inspector;
6
7use add_tool::{AddToolLauncher, ToolEntry};
4use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab};8use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab};
5use engine::{AudioPlayer, AudioTrack, CacheMode, Engine, ExportOptions, export_saver_png_sequence};9use engine::{AudioPlayer, AudioTrack, CacheMode, Engine, ExportOptions, export_saver_png_sequence};
6use flow::{FlowAction, FlowView};10use flow::{FlowAction, FlowView};
7use model::Comp;11use inspector::{InspectorAction, InspectorState};
12use model::{Comp, CompHistory, NodeId, default_main_input_port};
8use spline::{SplineAction, SplineView};13use spline::{SplineAction, SplineView};
9use std::collections::HashMap;14use std::collections::HashMap;
10use std::error::Error;15use std::error::Error;
11use std::fs::File;16use std::fs::File;
12use std::path::{Path, PathBuf};17use std::path::{Path, PathBuf};
18use std::process::Command as ProcessCommand;
13use std::sync::{Arc, mpsc};19use std::sync::{Arc, mpsc};
14use std::time::{Duration, Instant};20use std::time::{Duration, Instant};
15use ui::host::{Accessibility, Clipboard, Surface};21use ui::host::{Accessibility, Clipboard, Surface};
...@@ -22,12 +28,14 @@ use winit::keyboard::{Key, KeyCode, NamedKey, PhysicalKey};...@@ -22,12 +28,14 @@ use winit::keyboard::{Key, KeyCode, NamedKey, PhysicalKey};
22use winit::window::{CursorIcon, Window, WindowId};28use winit::window::{CursorIcon, Window, WindowId};
2329
24const DEFAULT_COMP: &str = "/Volumes/Project/trees/fusion/20_falling.comp";30const DEFAULT_COMP: &str = "/Volumes/Project/trees/fusion/20_falling.comp";
25const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline"];31const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline", "Inspector"];
2632
27fn viewer_pane_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("pane-viewer", slot)) }33fn viewer_pane_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("pane-viewer", slot)) }
28fn viewer_canvas_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("canvas-viewer", slot)) }34fn viewer_canvas_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("canvas-viewer", slot)) }
35fn flow_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-flow") }
29fn flow_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-flow") }36fn flow_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-flow") }
30fn spline_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-spline") }37fn spline_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-spline") }
38fn inspector_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-inspector") }
3139
32struct Cli {40struct Cli {
33 comp_path: PathBuf,41 comp_path: PathBuf,
...@@ -35,6 +43,7 @@ struct Cli {...@@ -35,6 +43,7 @@ struct Cli {
35 frame: Option<f64>,43 frame: Option<f64>,
36 select_node: Option<String>,44 select_node: Option<String>,
37 dual_viewer: bool,45 dual_viewer: bool,
46 open_add_tool: bool,
38}47}
3948
40fn parse_cli() -> Cli {49fn parse_cli() -> Cli {
...@@ -44,6 +53,7 @@ fn parse_cli() -> Cli {...@@ -44,6 +53,7 @@ fn parse_cli() -> Cli {
44 let mut frame = None;53 let mut frame = None;
45 let mut select_node = None;54 let mut select_node = None;
46 let mut dual_viewer = false;55 let mut dual_viewer = false;
56 let mut open_add_tool = false;
47 let mut i = 1;57 let mut i = 1;
48 while i < args.len() {58 while i < args.len() {
49 match args[i].as_str() {59 match args[i].as_str() {
...@@ -63,6 +73,10 @@ fn parse_cli() -> Cli {...@@ -63,6 +73,10 @@ fn parse_cli() -> Cli {
63 dual_viewer = true;73 dual_viewer = true;
64 i += 1;74 i += 1;
65 }75 }
76 "--open-add-tool" => {
77 open_add_tool = true;
78 i += 1;
79 }
66 other if !other.starts_with("--") => {80 other if !other.starts_with("--") => {
67 comp_path = PathBuf::from(other);81 comp_path = PathBuf::from(other);
68 i += 1;82 i += 1;
...@@ -70,7 +84,7 @@ fn parse_cli() -> Cli {...@@ -70,7 +84,7 @@ fn parse_cli() -> Cli {
70 _ => i += 1,84 _ => i += 1,
71 }85 }
72 }86 }
73 Cli { comp_path, snapshot, frame, select_node, dual_viewer }87 Cli { comp_path, snapshot, frame, select_node, dual_viewer, open_add_tool }
74}88}
7589
76fn main() {90fn main() {
...@@ -93,14 +107,20 @@ struct Studio {...@@ -93,14 +107,20 @@ struct Studio {
93 renderer: draw::Renderer,107 renderer: draw::Renderer,
94 engine: Engine,108 engine: Engine,
95 comp: Comp,109 comp: Comp,
96 saved_revision: u64,110 history: CompHistory,
97 playback: PlaybackClock,111 playback: PlaybackClock,
112 enable_audio: bool,
98 audio_player: Option<AudioPlayer>,113 audio_player: Option<AudioPlayer>,
99 audio_rx: Option<mpsc::Receiver<Result<AudioTrack, String>>>,114 audio_rx: Option<mpsc::Receiver<Result<AudioTrack, String>>>,
100 status_notice: Option<(String, Instant)>,115 status_notice: Option<(String, Instant)>,
101 viewers: [ViewerState; 2],116 viewers: [ViewerState; 2],
102 flow: FlowView,117 flow: FlowView,
103 spline: SplineView,118 spline: SplineView,
119 inspector: InspectorState,
120 add_tool: AddToolLauncher,
121 renaming_node: Option<NodeId>,
122 rename_buf: String,
123 rename_needs_focus: bool,
104 size: [f32; 2],124 size: [f32; 2],
105 scale: f32,125 scale: f32,
106 clock: Instant,126 clock: Instant,
...@@ -125,6 +145,7 @@ impl Studio {...@@ -125,6 +145,7 @@ impl Studio {
125 let g_flow = GroupId(2);145 let g_flow = GroupId(2);
126 let g_spline = GroupId(3);146 let g_spline = GroupId(3);
127 let g_v2 = GroupId(4);147 let g_v2 = GroupId(4);
148 let g_inspector = GroupId(5);
128149
129 let top_node = if dual_viewer {150 let top_node = if dual_viewer {
130 DockNode::Split {151 DockNode::Split {
...@@ -148,37 +169,51 @@ impl Studio {...@@ -148,37 +169,51 @@ impl Studio {
148 DockNode::Group { id: g_v1, tabs: vec!["Viewer 1".to_owned()], preview: None, rest: Default::default() }169 DockNode::Group { id: g_v1, tabs: vec!["Viewer 1".to_owned()], preview: None, rest: Default::default() }
149 };170 };
150171
172 let left_workspace = DockNode::Split {
173 id: SplitId(1),
174 axis: DockAxis::Y,
175 parts: vec![
176 DockPart { share: 0.54, node: top_node, rest: Default::default() },
177 DockPart {
178 share: 0.46,
179 node: DockNode::Split {
180 id: SplitId(2),
181 axis: DockAxis::X,
182 parts: vec![
183 DockPart {
184 share: 0.52,
185 node: DockNode::Group { id: g_flow, tabs: vec!["Flow".to_owned()], preview: None, rest: Default::default() },
186 rest: Default::default(),
187 },
188 DockPart {
189 share: 0.48,
190 node: DockNode::Group { id: g_spline, tabs: vec!["Spline".to_owned()], preview: None, rest: Default::default() },
191 rest: Default::default(),
192 },
193 ],
194 rest: Default::default(),
195 },
196 rest: Default::default(),
197 },
198 ],
199 rest: Default::default(),
200 };
201
151 let layout = dock::Layout {202 let layout = dock::Layout {
152 root: DockNode::Split {203 root: DockNode::Split {
153 id: SplitId(1),204 id: SplitId(4),
154 axis: DockAxis::Y,205 axis: DockAxis::X,
155 parts: vec![206 parts: vec![
156 DockPart { share: 0.54, node: top_node, rest: Default::default() },207 DockPart { share: 0.76, node: left_workspace, rest: Default::default() },
157 DockPart {208 DockPart {
158 share: 0.46,209 share: 0.24,
159 node: DockNode::Split {210 node: DockNode::Group { id: g_inspector, tabs: vec!["Inspector".to_owned()], preview: None, rest: Default::default() },
160 id: SplitId(2),
161 axis: DockAxis::X,
162 parts: vec![
163 DockPart {
164 share: 0.52,
165 node: DockNode::Group { id: g_flow, tabs: vec!["Flow".to_owned()], preview: None, rest: Default::default() },
166 rest: Default::default(),
167 },
168 DockPart {
169 share: 0.48,
170 node: DockNode::Group { id: g_spline, tabs: vec!["Spline".to_owned()], preview: None, rest: Default::default() },
171 rest: Default::default(),
172 },
173 ],
174 rest: Default::default(),
175 },
176 rest: Default::default(),211 rest: Default::default(),
177 },212 },
178 ],213 ],
179 rest: Default::default(),214 rest: Default::default(),
180 },215 },
181 issued: 5,216 issued: 6,
182 rest: Default::default(),217 rest: Default::default(),
183 };218 };
184 let mut seen = dock::Seen::default();219 let mut seen = dock::Seen::default();
...@@ -188,6 +223,7 @@ impl Studio {...@@ -188,6 +223,7 @@ impl Studio {
188 }223 }
189 seen.active.insert(g_flow, "Flow".to_owned());224 seen.active.insert(g_flow, "Flow".to_owned());
190 seen.active.insert(g_spline, "Spline".to_owned());225 seen.active.insert(g_spline, "Spline".to_owned());
226 seen.active.insert(g_inspector, "Inspector".to_owned());
191 seen.focused = Some(g_flow);227 seen.focused = Some(g_flow);
192 let dock = Dock::new();228 let dock = Dock::new();
193229
...@@ -217,6 +253,9 @@ impl Studio {...@@ -217,6 +253,9 @@ impl Studio {
217 let mut spline = SplineView::new(&ui_theme);253 let mut spline = SplineView::new(&ui_theme);
218 spline.set_target_node(&comp, default_sel);254 spline.set_target_node(&comp, default_sel);
219255
256 let inspector = InspectorState::new(&ui_theme);
257 let add_tool = AddToolLauncher::new();
258
220 let (audio_player, audio_rx) = if enable_audio {259 let (audio_player, audio_rx) = if enable_audio {
221 let player = match AudioPlayer::new() {260 let player = match AudioPlayer::new() {
222 Ok(p) => Some(p),261 Ok(p) => Some(p),
...@@ -225,23 +264,14 @@ impl Studio {...@@ -225,23 +264,14 @@ impl Studio {
225 None264 None
226 }265 }
227 };266 };
228 let rx = comp.audio_filename.as_ref().and_then(|af| {267 let rx = spawn_audio_loader(&comp);
229 let p = PathBuf::from(af);
230 if !p.exists() {
231 return None;
232 }
233 let (tx, rx) = mpsc::channel();
234 std::thread::spawn(move || {
235 let _ = tx.send(AudioTrack::load(&p));
236 });
237 Some(rx)
238 });
239 (player, rx)268 (player, rx)
240 } else {269 } else {
241 (None, None)270 (None, None)
242 };271 };
243272
244 let saved_revision = comp.revision;273 let mut history = CompHistory::new();
274 history.mark_saved(&comp);
245275
246 Self {276 Self {
247 ui,277 ui,
...@@ -251,14 +281,20 @@ impl Studio {...@@ -251,14 +281,20 @@ impl Studio {
251 renderer,281 renderer,
252 engine,282 engine,
253 comp,283 comp,
254 saved_revision,284 history,
255 playback,285 playback,
286 enable_audio,
256 audio_player,287 audio_player,
257 audio_rx,288 audio_rx,
258 status_notice: None,289 status_notice: None,
259 viewers: [v1, v2],290 viewers: [v1, v2],
260 flow,291 flow,
261 spline,292 spline,
293 inspector,
294 add_tool,
295 renaming_node: None,
296 rename_buf: String::new(),
297 rename_needs_focus: false,
262 size: [1440.0, 900.0],298 size: [1440.0, 900.0],
263 scale: 2.0,299 scale: 2.0,
264 clock: Instant::now(),300 clock: Instant::now(),
...@@ -316,36 +352,199 @@ impl Studio {...@@ -316,36 +352,199 @@ impl Studio {
316 }352 }
317 }353 }
318354
355 fn set_notice(&mut self, msg: impl Into<String>) {
356 self.status_notice = Some((msg.into(), Instant::now()));
357 }
358
359 fn invalidate_node(&mut self, node: Option<NodeId>) {
360 if let Some(id) = node {
361 self.engine.bust_subtree(id);
362 } else {
363 self.engine.bust_all_caches();
364 }
365 for v in &mut self.viewers {
366 v.cached_frames.clear();
367 v.dirty = true;
368 }
369 }
370
371 fn undo(&mut self) {
372 let label = self.history.undo_label().unwrap_or("Edit").to_owned();
373 if self.history.undo(&mut self.comp) {
374 self.flow.sanitize_ids(&self.comp);
375 for slot in [0usize, 1] {
376 if self.viewers[slot].viewed_node.is_some_and(|id| id.0 >= self.comp.nodes.len()) {
377 self.viewers[slot].viewed_node = self.comp.default_output_node();
378 }
379 }
380 self.flow.viewed_nodes = [self.viewers[0].viewed_node, self.viewers[1].viewed_node];
381 self.spline.set_target_node(&self.comp, self.flow.primary);
382 self.renaming_node = None;
383 self.invalidate_node(None);
384 self.set_notice(format!("Undo: {label}"));
385 } else {
386 self.set_notice("Nothing to undo");
387 }
388 }
389
390 fn redo(&mut self) {
391 let label = self.history.redo_label().unwrap_or("Edit").to_owned();
392 if self.history.redo(&mut self.comp) {
393 self.flow.sanitize_ids(&self.comp);
394 for slot in [0usize, 1] {
395 if self.viewers[slot].viewed_node.is_some_and(|id| id.0 >= self.comp.nodes.len()) {
396 self.viewers[slot].viewed_node = self.comp.default_output_node();
397 }
398 }
399 self.flow.viewed_nodes = [self.viewers[0].viewed_node, self.viewers[1].viewed_node];
400 self.spline.set_target_node(&self.comp, self.flow.primary);
401 self.renaming_node = None;
402 self.invalidate_node(None);
403 self.set_notice(format!("Redo: {label}"));
404 } else {
405 self.set_notice("Nothing to redo");
406 }
407 }
408
319 fn save_comp(&mut self) -> Result<String, String> {409 fn save_comp(&mut self) -> Result<String, String> {
320 let Some(path) = self.comp.path.clone() else {410 let Some(path) = self.comp.path.clone() else {
321 return Err("comp has no file path to save".to_owned());411 return self.save_comp_as();
322 };412 };
413 self.save_to_path(&path)
414 }
415
416 fn save_to_path(&mut self, path: &Path) -> Result<String, String> {
323 self.comp.current_time = self.playback.current_frame;417 self.comp.current_time = self.playback.current_frame;
324 match self.comp.save_to_file(&path) {418 match self.comp.save_to_file(path) {
325 Ok(backup) => {419 Ok(backup) => {
326 self.saved_revision = self.comp.revision;420 self.comp.path = Some(path.to_path_buf());
421 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
422 self.comp.name = stem.to_owned();
423 }
424 self.history.mark_saved(&self.comp);
327 let msg = match backup {425 let msg = match backup {
328 Some(bak) => {426 Some(bak) => {
329 eprintln!("Saved {} (backup -> {})", path.display(), bak.display());427 eprintln!("Saved {} (backup -> {})", path.display(), bak.display());
330 format!("Saved (backup in temp)")428 "Saved (backup in temp)".to_owned()
331 }429 }
332 None => {430 None => {
333 eprintln!("Saved {}", path.display());431 eprintln!("Saved {}", path.display());
334 "Saved".to_owned()432 format!("Saved {}", self.comp.name)
335 }433 }
336 };434 };
337 self.status_notice = Some((msg.clone(), Instant::now()));435 self.set_notice(msg.clone());
338 Ok(msg)436 Ok(msg)
339 }437 }
340 Err(e) => {438 Err(e) => {
341 let err = format!("Save failed: {e}");439 let err = format!("Save failed: {e}");
342 eprintln!("{err}");440 eprintln!("{err}");
343 self.status_notice = Some((err.clone(), Instant::now()));441 self.set_notice(err.clone());
344 Err(err)442 Err(err)
345 }443 }
346 }444 }
347 }445 }
348446
447 fn save_comp_as(&mut self) -> Result<String, String> {
448 let default_name = format!("{}.comp", self.comp.name);
449 let Some(mut path) = native_save_comp_dialog(&default_name) else {
450 return Err("Save As cancelled".to_owned());
451 };
452 if path.extension().is_none() {
453 path.set_extension("comp");
454 }
455 self.save_to_path(&path)
456 }
457
458 fn open_comp_dialog(&mut self) {
459 let Some(path) = native_open_comp_dialog() else {
460 return;
461 };
462 match Comp::from_fusion_file(&path) {
463 Ok(new_comp) => {
464 self.reload_comp(new_comp);
465 self.set_notice(format!("Opened {}", self.comp.name));
466 }
467 Err(e) => {
468 let msg = format!("Open failed: {e}");
469 eprintln!("{msg}");
470 self.set_notice(msg);
471 }
472 }
473 }
474
475 fn reload_comp(&mut self, new_comp: Comp) {
476 if self.playback.playing {
477 self.playback.toggle_play(Instant::now());
478 self.sync_audio(true, false);
479 }
480 self.comp = new_comp;
481 self.history.clear();
482 self.history.mark_saved(&self.comp);
483 self.engine.bust_all_caches();
484 self.playback.init_from_comp(&self.comp);
485
486 let out_node = self.comp.default_output_node();
487 for (slot, v) in self.viewers.iter_mut().enumerate() {
488 v.viewed_node = out_node;
489 v.cached_frames.clear();
490 v.dirty = true;
491 if slot == 0 {
492 v.fit();
493 }
494 }
495 self.flow.reset_for_comp(&self.comp);
496 self.flow.viewed_nodes = [self.viewers[0].viewed_node, None];
497 let default_sel = self
498 .comp
499 .nodes
500 .iter()
501 .find(|n| !self.comp.node_splines(n.id).is_empty())
502 .map(|n| n.id)
503 .or(out_node);
504 if let Some(id) = default_sel {
505 self.flow.selected.insert(id);
506 self.flow.primary = Some(id);
507 }
508 self.spline.set_target_node(&self.comp, default_sel);
509 self.inspector.reset();
510 self.renaming_node = None;
511
512 if self.enable_audio {
513 if let Some(player) = &mut self.audio_player {
514 player.set_track(None);
515 }
516 self.audio_rx = spawn_audio_loader(&self.comp);
517 }
518 }
519
520 fn add_tool_from_entry(&mut self, entry: ToolEntry) {
521 let prev_sel = self.flow.primary.filter(|id| id.0 < self.comp.nodes.len());
522 let pos = self.flow.spawn_position(&self.comp, entry.is_generator);
523 self.history.push_snapshot(&self.comp, format!("Add {}", entry.display));
524 let new_id = self.comp.add_node(entry.kind, None, pos);
525 if !entry.is_generator {
526 if let Some(src_id) = prev_sel {
527 let port = default_main_input_port(entry.kind);
528 let _ = self.comp.connect_output(src_id, "Output", new_id, port);
529 }
530 }
531 self.flow.selected.clear();
532 self.flow.selected.insert(new_id);
533 self.flow.primary = Some(new_id);
534 self.spline.set_target_node(&self.comp, Some(new_id));
535 self.invalidate_node(Some(new_id));
536 self.set_notice(format!("Added {}", self.comp.node(new_id).name));
537 }
538
539 fn begin_inline_rename(&mut self, id: NodeId) {
540 if id.0 >= self.comp.nodes.len() {
541 return;
542 }
543 self.renaming_node = Some(id);
544 self.rename_buf = self.comp.node(id).name.clone();
545 self.rename_needs_focus = true;
546 }
547
349 fn export_saver_pngs(&mut self) -> Result<String, String> {548 fn export_saver_pngs(&mut self) -> Result<String, String> {
350 if self.playback.playing {549 if self.playback.playing {
351 self.playback.toggle_play(Instant::now());550 self.playback.toggle_play(Instant::now());
...@@ -393,7 +592,7 @@ impl Studio {...@@ -393,7 +592,7 @@ impl Studio {
393 }592 }
394593
395 fn window_title(&self) -> String {594 fn window_title(&self) -> String {
396 let dirty = if self.comp.revision != self.saved_revision { " •" } else { "" };595 let dirty = if self.history.is_dirty(&self.comp) { "*" } else { "" };
397 if let Some((msg, at)) = &self.status_notice {596 if let Some((msg, at)) = &self.status_notice {
398 if at.elapsed() < Duration::from_secs(5) {597 if at.elapsed() < Duration::from_secs(5) {
399 return format!("Fission — {}{dirty} — {msg}", self.comp.name);598 return format!("Fission — {}{dirty} — {msg}", self.comp.name);
...@@ -454,17 +653,29 @@ impl Studio {...@@ -454,17 +653,29 @@ impl Studio {
454 .map(|&name| ui::popup::Item { text: name, ..Default::default() })653 .map(|&name| ui::popup::Item { text: name, ..Default::default() })
455 .collect();654 .collect();
456655
457 let comp_unsaved = self.comp.revision != self.saved_revision;656 let comp_unsaved = self.history.is_dirty(&self.comp);
657 let cur_frame = self.playback.current_frame;
658 let eval_stats = self.viewers[0].last_stats.clone();
659 let can_undo = self.history.can_undo();
660 let can_redo = self.history.can_redo();
661 let primary_sel = self.flow.primary;
458 let Studio {662 let Studio {
459 ui,663 ui,
460 dock,664 dock,
461 layout,665 layout,
462 seen,666 seen,
463 engine,667 engine,
668 comp,
669 history,
464 playback,670 playback,
465 viewers,671 viewers,
466 flow,672 flow,
467 spline,673 spline,
674 inspector,
675 add_tool,
676 renaming_node,
677 rename_buf,
678 rename_needs_focus,
468 size,679 size,
469 ..680 ..
470 } = self;681 } = self;
...@@ -473,7 +684,17 @@ impl Studio {...@@ -473,7 +684,17 @@ impl Studio {
473 let v2_bg = viewers[1].background();684 let v2_bg = viewers[1].background();
474 let flow_bg = flow.background();685 let flow_bg = flow.background();
475 let spline_bg = spline.background();686 let spline_bg = spline.background();
687 let inspector_bg = inspector.background();
476 let mut viewer_actions: Vec<(usize, ViewerAction)> = Vec::new();688 let mut viewer_actions: Vec<(usize, ViewerAction)> = Vec::new();
689 let mut inspector_actions: Vec<InspectorAction> = Vec::new();
690 let mut req_open_add_tool = false;
691 let mut req_undo = false;
692 let mut req_redo = false;
693 let mut req_open = false;
694 let mut req_save = false;
695 let mut req_save_as = false;
696 let mut commit_rename: Option<(NodeId, String)> = None;
697 let mut cancel_rename = false;
477698
478 let mut d = dock.at(layout, seen, &String::clone);699 let mut d = dock.at(layout, seen, &String::clone);
479 let events = d.build(700 let events = d.build(
...@@ -488,6 +709,7 @@ impl Studio {...@@ -488,6 +709,7 @@ impl Studio {
488 "Viewer 2" => v2_bg,709 "Viewer 2" => v2_bg,
489 "Flow" => flow_bg,710 "Flow" => flow_bg,
490 "Spline" => spline_bg,711 "Spline" => spline_bg,
712 "Inspector" => inspector_bg,
491 _ => flow_bg,713 _ => flow_bg,
492 };714 };
493 Tab {715 Tab {
...@@ -513,6 +735,83 @@ impl Studio {...@@ -513,6 +735,83 @@ impl Studio {
513 Some(viewer_canvas_id(1))735 Some(viewer_canvas_id(1))
514 }736 }
515 "Flow" => {737 "Flow" => {
738 ui.open_as(
739 flow_pane_id(),
740 ui::Spec {
741 size: [ui::fill(), ui::fill()],
742 axis: ui::Axis::Y,
743 fill: Some(flow_bg),
744 ..ui::Spec::default()
745 },
746 );
747 // Compact Flow toolbar with `+ Add`, Undo/Redo, Open/Save/Save As, and inline F2 rename
748 let bar_bg = ui.theme.strip;
749 ui.open(
750 "flow-toolbar",
751 ui::Spec {
752 size: [ui::fill(), ui::px(28.0)],
753 axis: ui::Axis::X,
754 pad: [6.0, 3.0],
755 gap: 4.0,
756 fill: Some(bar_bg),
757 ..ui::Spec::default()
758 },
759 );
760 if studio_btn(ui, "flow-add-btn", "+ Add", false).clicked {
761 req_open_add_tool = true;
762 }
763 if studio_btn(ui, "flow-undo-btn", "Undo", can_undo).clicked && can_undo {
764 req_undo = true;
765 }
766 if studio_btn(ui, "flow-redo-btn", "Redo", can_redo).clicked && can_redo {
767 req_redo = true;
768 }
769 if studio_btn(ui, "flow-open-btn", "Open", false).clicked {
770 req_open = true;
771 }
772 if studio_btn(ui, "flow-save-btn", if comp_unsaved { "Save*" } else { "Save" }, comp_unsaved).clicked {
773 req_save = true;
774 }
775 if studio_btn(ui, "flow-saveas-btn", "Save As", false).clicked {
776 req_save_as = true;
777 }
778 if let Some(rn_id) = *renaming_node {
779 let rn_field_id = flow_pane_id().child(("rename-field", rn_id.0));
780 let rn_sig = ui::text_field(
781 ui,
782 rn_field_id,
783 rename_buf,
784 "Rename node…",
785 ui::Spec {
786 size: [ui::px(160.0), ui::px(22.0)],
787 font_size: Some(11.5),
788 fill: Some(ui.theme.base),
789 border: Some(ui.theme.accent),
790 radius: 4.0,
791 pad: [6.0, 1.0],
792 ..ui::Spec::default()
793 },
794 );
795 if *rename_needs_focus {
796 ui.set_focus(Some(rn_field_id));
797 *rename_needs_focus = false;
798 }
799 for ev in &rn_sig.events {
800 if let ui::Event::Key { key, .. } = ev {
801 match key {
802 Key::Named(NamedKey::Enter) => {
803 commit_rename = Some((rn_id, rename_buf.trim().to_owned()));
804 }
805 Key::Named(NamedKey::Escape) => {
806 cancel_rename = true;
807 }
808 _ => {}
809 }
810 }
811 }
812 }
813 ui.close(); // flow-toolbar
814
516 let id = ui.open_as(815 let id = ui.open_as(
517 flow_canvas_id(),816 flow_canvas_id(),
518 ui::Spec {817 ui::Spec {
...@@ -522,6 +821,7 @@ impl Studio {...@@ -522,6 +821,7 @@ impl Studio {
522 },821 },
523 );822 );
524 ui.close();823 ui.close();
824 ui.close(); // flow_pane_id
525 Some(id)825 Some(id)
526 }826 }
527 "Spline" => {827 "Spline" => {
...@@ -536,12 +836,86 @@ impl Studio {...@@ -536,12 +836,86 @@ impl Studio {
536 ui.close();836 ui.close();
537 Some(id)837 Some(id)
538 }838 }
839 "Inspector" => {
840 let acts = inspector.build_ui(
841 ui,
842 inspector_pane_id(),
843 comp,
844 history,
845 primary_sel,
846 cur_frame,
847 &eval_stats,
848 );
849 inspector_actions.extend(acts);
850 Some(inspector_pane_id())
851 }
539 _ => None,852 _ => None,
540 }853 }
541 },854 },
542 );855 );
856
857 let picked_tool = add_tool.build_ui(ui, *size);
543 self.ui.end();858 self.ui.end();
544859
860 if req_open_add_tool {
861 self.add_tool.open();
862 }
863 if req_undo {
864 self.undo();
865 }
866 if req_redo {
867 self.redo();
868 }
869 if req_open {
870 self.open_comp_dialog();
871 }
872 if req_save {
873 let _ = self.save_comp();
874 }
875 if req_save_as {
876 let _ = self.save_comp_as();
877 }
878 if let Some((rn_id, new_name)) = commit_rename {
879 self.renaming_node = None;
880 self.ui.set_focus(Some(flow_canvas_id()));
881 if !new_name.is_empty() && rn_id.0 < self.comp.nodes.len() && new_name != self.comp.node(rn_id).name {
882 self.history.push_snapshot(&self.comp, "Rename Node");
883 match self.comp.rename_node(rn_id, &new_name) {
884 Ok(applied) => {
885 self.spline.set_target_node(&self.comp, self.flow.primary);
886 self.invalidate_node(Some(rn_id));
887 self.set_notice(format!("Renamed to {applied}"));
888 }
889 Err(e) => self.set_notice(e),
890 }
891 }
892 } else if cancel_rename {
893 self.renaming_node = None;
894 self.ui.set_focus(Some(flow_canvas_id()));
895 }
896 if let Some(entry) = picked_tool {
897 self.add_tool_from_entry(entry);
898 }
899
900 for a in inspector_actions {
901 match a {
902 InspectorAction::ParamEdited(id) => {
903 self.invalidate_node(Some(id));
904 }
905 InspectorAction::KeyframeEdited(id) => {
906 self.spline.set_target_node(&self.comp, self.flow.primary);
907 self.invalidate_node(Some(id));
908 }
909 InspectorAction::NodeRenamed(id) => {
910 self.spline.set_target_node(&self.comp, self.flow.primary);
911 self.invalidate_node(Some(id));
912 }
913 InspectorAction::StatusNotice(msg) => {
914 self.set_notice(msg);
915 }
916 }
917 }
918
545 for ev in events {919 for ev in events {
546 match ev {920 match ev {
547 Event::Close(name) => {921 Event::Close(name) => {
...@@ -583,7 +957,7 @@ impl Studio {...@@ -583,7 +957,7 @@ impl Studio {
583 let mods = self.ui.modifiers();957 let mods = self.ui.modifiers();
584 let mut acts = Vec::new();958 let mut acts = Vec::new();
585 for ev in sig.events {959 for ev in sig.events {
586 acts.extend(self.flow.input(&mut self.comp, ev, rect, ptr, mods));960 acts.extend(self.flow.input(&mut self.comp, &mut self.history, ev, rect, ptr, mods));
587 }961 }
588 for a in acts {962 for a in acts {
589 match a {963 match a {
...@@ -601,10 +975,17 @@ impl Studio {...@@ -601,10 +975,17 @@ impl Studio {
601 FlowAction::ClearViewers => {975 FlowAction::ClearViewers => {
602 self.clear_viewers();976 self.clear_viewers();
603 }977 }
604 FlowAction::GraphMutated => {978 FlowAction::GraphMutated(node) => {
605 for v in &mut self.viewers {979 self.invalidate_node(node);
606 v.dirty = true;980 }
607 }981 FlowAction::OpenAddTool => {
982 self.add_tool.open();
983 }
984 FlowAction::RequestRename(id) => {
985 self.begin_inline_rename(id);
986 }
987 FlowAction::StatusNotice(msg) => {
988 self.set_notice(msg);
608 }989 }
609 }990 }
610 }991 }
...@@ -804,6 +1185,9 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box<dyn Error>> {...@@ -804,6 +1185,9 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box<dyn Error>> {
804 let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm);1185 let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm);
8051186
806 let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer, false);1187 let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer, false);
1188 if cli.open_add_tool {
1189 studio.add_tool.open();
1190 }
807 studio.size = [1440.0, 900.0];1191 studio.size = [1440.0, 900.0];
808 studio.scale = 2.0;1192 studio.scale = 2.0;
8091193
...@@ -878,6 +1262,7 @@ fn run_window(cli: &Cli) -> Result<(), Box<dyn Error>> {...@@ -878,6 +1262,7 @@ fn run_window(cli: &Cli) -> Result<(), Box<dyn Error>> {
878 frame: cli.frame,1262 frame: cli.frame,
879 select_node: cli.select_node.clone(),1263 select_node: cli.select_node.clone(),
880 dual_viewer: cli.dual_viewer,1264 dual_viewer: cli.dual_viewer,
1265 open_add_tool: cli.open_add_tool,
881 },1266 },
882 host: None,1267 host: None,
883 error: None,1268 error: None,
...@@ -939,53 +1324,108 @@ impl WindowHost {...@@ -939,53 +1324,108 @@ impl WindowHost {
939 }1324 }
9401325
941 fn input(&mut self, event: ui::Event) {1326 fn input(&mut self, event: ui::Event) {
942 // Global Cmd+S saves lossless .comp (with temp-folder .bak); Cmd+Shift+R exports Saver PNG sequence!1327 let typing = self.studio.ui.typing();
943 let (is_cmd_s, is_cmd_shift_r) = match &event {1328 // Global file & history shortcuts: Cmd+S, Cmd+Shift+S, Cmd+O, Cmd+Z, Cmd+Shift+Z / Cmd+Y, Cmd+Shift+R
944 ui::Event::KeyInput { physical, modifiers, state: ElementState::Pressed, repeat: false, .. } => (1329 let key_cmd = match &event {
945 modifiers.super_key() && !modifiers.shift_key() && *physical == PhysicalKey::Code(KeyCode::KeyS),1330 ui::Event::KeyInput { physical, modifiers, state: ElementState::Pressed, repeat: false, .. } => {
946 modifiers.super_key() && modifiers.shift_key() && *physical == PhysicalKey::Code(KeyCode::KeyR),1331 let cmd = modifiers.super_key() || modifiers.control_key();
947 ),1332 let shift = modifiers.shift_key();
948 ui::Event::Key { key: Key::Character(c), modifiers, .. } => (1333 if cmd && !shift && *physical == PhysicalKey::Code(KeyCode::KeyS) {
949 modifiers.super_key() && !modifiers.shift_key() && c.eq_ignore_ascii_case("s"),1334 Some("save")
950 modifiers.super_key() && modifiers.shift_key() && c.eq_ignore_ascii_case("r"),1335 } else if cmd && shift && *physical == PhysicalKey::Code(KeyCode::KeyS) {
951 ),1336 Some("save_as")
952 _ => (false, false),1337 } else if cmd && !shift && *physical == PhysicalKey::Code(KeyCode::KeyO) {
1338 Some("open")
1339 } else if cmd && !shift && !typing && *physical == PhysicalKey::Code(KeyCode::KeyZ) {
1340 Some("undo")
1341 } else if cmd && shift && !typing && *physical == PhysicalKey::Code(KeyCode::KeyZ) {
1342 Some("redo")
1343 } else if cmd && !shift && !typing && *physical == PhysicalKey::Code(KeyCode::KeyY) {
1344 Some("redo")
1345 } else if cmd && shift && *physical == PhysicalKey::Code(KeyCode::KeyR) {
1346 Some("export")
1347 } else {
1348 None
1349 }
1350 }
1351 ui::Event::Key { key: Key::Character(c), modifiers, .. } => {
1352 let cmd = modifiers.super_key() || modifiers.control_key();
1353 let shift = modifiers.shift_key();
1354 if cmd && !shift && c.eq_ignore_ascii_case("s") {
1355 Some("save")
1356 } else if cmd && shift && c.eq_ignore_ascii_case("s") {
1357 Some("save_as")
1358 } else if cmd && !shift && c.eq_ignore_ascii_case("o") {
1359 Some("open")
1360 } else if cmd && !shift && !typing && c.eq_ignore_ascii_case("z") {
1361 Some("undo")
1362 } else if cmd && shift && !typing && c.eq_ignore_ascii_case("z") {
1363 Some("redo")
1364 } else if cmd && !shift && !typing && c.eq_ignore_ascii_case("y") {
1365 Some("redo")
1366 } else if cmd && shift && c.eq_ignore_ascii_case("r") {
1367 Some("export")
1368 } else {
1369 None
1370 }
1371 }
1372 _ => None,
953 };1373 };
954 if is_cmd_s {1374 if let Some(action) = key_cmd {
955 let _ = self.studio.save_comp();1375 match action {
956 self.window.set_title(&self.studio.window_title());1376 "save" => { let _ = self.studio.save_comp(); }
957 self.window.request_redraw();1377 "save_as" => { let _ = self.studio.save_comp_as(); }
958 return;1378 "open" => self.studio.open_comp_dialog(),
959 }1379 "undo" => self.studio.undo(),
960 if is_cmd_shift_r {1380 "redo" => self.studio.redo(),
961 let _ = self.studio.export_saver_pngs();1381 "export" => { let _ = self.studio.export_saver_pngs(); }
1382 _ => {}
1383 }
962 self.window.set_title(&self.studio.window_title());1384 self.window.set_title(&self.studio.window_title());
963 self.window.request_redraw();1385 self.window.request_redraw();
964 return;1386 return;
965 }1387 }
966 // Global Space toggles playback (synced with audio) and `` ` `` clears both viewers from any focused pane!1388
967 let is_space = matches!(1389 // Shift+Space opens Add Tool launcher (when not typing in a text field)
968 &event,1390 if !typing {
969 ui::Event::KeyInput { key: Key::Named(NamedKey::Space), state: ElementState::Pressed, repeat: false, .. }1391 let is_shift_space = match &event {
970 | ui::Event::Key { key: Key::Named(NamedKey::Space), .. }1392 ui::Event::KeyInput { key: Key::Named(NamedKey::Space), modifiers, state: ElementState::Pressed, repeat: false, .. }
971 );1393 | ui::Event::Key { key: Key::Named(NamedKey::Space), modifiers, .. } => {
972 if is_space {1394 modifiers.shift_key() && !modifiers.super_key() && !modifiers.control_key()
973 self.studio.playback.toggle_play(Instant::now());1395 }
974 self.studio.sync_audio(true, false);1396 _ => false,
975 self.window.request_redraw();1397 };
976 return;1398 if is_shift_space {
977 }1399 self.studio.add_tool.open();
978 let is_backquote = match &event {1400 self.window.request_redraw();
979 ui::Event::KeyInput { physical: PhysicalKey::Code(KeyCode::Backquote), state: ElementState::Pressed, repeat: false, .. } => true,1401 return;
980 ui::Event::Key { key: Key::Character(c), .. } if c.as_str() == "`" || c.as_str() == "~" => true,1402 }
981 _ => false,1403 // Global Space toggles playback (synced with audio) and `` ` `` clears both viewers from any focused pane!
982 };1404 let is_space = match &event {
983 if is_backquote {1405 ui::Event::KeyInput { key: Key::Named(NamedKey::Space), modifiers, state: ElementState::Pressed, repeat: false, .. }
984 self.studio.clear_viewers();1406 | ui::Event::Key { key: Key::Named(NamedKey::Space), modifiers, .. } => {
985 self.window.request_redraw();1407 !modifiers.shift_key() && !modifiers.super_key() && !modifiers.control_key()
986 return;1408 }
1409 _ => false,
1410 };
1411 if is_space && !self.studio.add_tool.open {
1412 self.studio.playback.toggle_play(Instant::now());
1413 self.studio.sync_audio(true, false);
1414 self.window.request_redraw();
1415 return;
1416 }
1417 let is_backquote = match &event {
1418 ui::Event::KeyInput { physical: PhysicalKey::Code(KeyCode::Backquote), state: ElementState::Pressed, repeat: false, .. } => true,
1419 ui::Event::Key { key: Key::Character(c), .. } if c.as_str() == "`" || c.as_str() == "~" => true,
1420 _ => false,
1421 };
1422 if is_backquote && !self.studio.add_tool.open {
1423 self.studio.clear_viewers();
1424 self.window.request_redraw();
1425 return;
1426 }
987 }1427 }
988 if !self.studio.ui.popups_open() && let ui::Event::Key { key, modifiers, .. } = &event {1428 if !self.studio.ui.popups_open() && !self.studio.add_tool.open && let ui::Event::Key { key, modifiers, .. } = &event {
989 let cmd = match key {1429 let cmd = match key {
990 Key::Named(NamedKey::Tab) if modifiers.control_key() => {1430 Key::Named(NamedKey::Tab) if modifiers.control_key() => {
991 Some(if modifiers.shift_key() { Command::Previous } else { Command::Next })1431 Some(if modifiers.shift_key() { Command::Previous } else { Command::Next })
...@@ -1093,3 +1533,75 @@ impl ApplicationHandler<UserEvent> for App {...@@ -1093,3 +1533,75 @@ impl ApplicationHandler<UserEvent> for App {
1093 event_loop.set_control_flow(ControlFlow::Wait);1533 event_loop.set_control_flow(ControlFlow::Wait);
1094 }1534 }
1095}1535}
1536
1537fn spawn_audio_loader(comp: &Comp) -> Option<mpsc::Receiver<Result<AudioTrack, String>>> {
1538 comp.audio_filename.as_ref().and_then(|af| {
1539 let p = PathBuf::from(af);
1540 if !p.exists() {
1541 return None;
1542 }
1543 let (tx, rx) = mpsc::channel();
1544 std::thread::spawn(move || {
1545 let _ = tx.send(AudioTrack::load(&p));
1546 });
1547 Some(rx)
1548 })
1549}
1550
1551fn studio_btn(ui: &mut ui::Ui, part: impl std::hash::Hash, label: &str, active: bool) -> ui::Signal {
1552 let t = &ui.theme;
1553 let fill = if active {
1554 [t.accent[0], t.accent[1], t.accent[2], 0.24]
1555 } else {
1556 [t.base[0], t.base[1], t.base[2], 0.65]
1557 };
1558 let border = if active {
1559 [t.accent[0], t.accent[1], t.accent[2], 0.65]
1560 } else {
1561 t.rule
1562 };
1563 let ink = if active { t.text } else { t.text_dim };
1564 ui.leaf(
1565 part,
1566 ui::Spec {
1567 cursor: Some(CursorIcon::Pointer),
1568 flags: ui::Flags::CLICKABLE,
1569 size: [ui::fit(), ui::px(22.0)],
1570 text: Some(label),
1571 font_size: Some(11.0),
1572 medium: true,
1573 color: Some(ink),
1574 fill: Some(fill),
1575 border: Some(border),
1576 hover_fill: Some(t.ghost_soft),
1577 hover_border: Some(t.accent),
1578 radius: 5.0,
1579 pad: [7.0, 0.0],
1580 center: true,
1581 ..ui::Spec::default()
1582 },
1583 )
1584}
1585
1586fn native_open_comp_dialog() -> Option<PathBuf> {
1587 let script = r#"POSIX path of (choose file with prompt "Open Fusion Composition" of type {"comp"})"#;
1588 let out = ProcessCommand::new("osascript").args(["-e", script]).output().ok()?;
1589 if !out.status.success() {
1590 return None;
1591 }
1592 let s = String::from_utf8_lossy(&out.stdout).trim().to_owned();
1593 if s.is_empty() { None } else { Some(PathBuf::from(s)) }
1594}
1595
1596fn native_save_comp_dialog(default_name: &str) -> Option<PathBuf> {
1597 let safe = default_name.replace('"', "");
1598 let script = format!(
1599 r#"POSIX path of (choose file name with prompt "Save Fusion Composition As" default name "{safe}")"#
1600 );
1601 let out = ProcessCommand::new("osascript").args(["-e", &script]).output().ok()?;
1602 if !out.status.success() {
1603 return None;
1604 }
1605 let s = String::from_utf8_lossy(&out.stdout).trim().to_owned();
1606 if s.is_empty() { None } else { Some(PathBuf::from(s)) }
1607}
scripts/fusion_probes.py+86
...@@ -1915,6 +1915,91 @@ def build_probe_ultrakey():...@@ -1915,6 +1915,91 @@ def build_probe_ultrakey():
1915 return comp_path, "ultrakey", cases1915 return comp_path, "ultrakey", cases
19161916
19171917
1918def build_probe_archive_3d():
1919 """Shale #11 probe: 3D lights/materials/modifiers/Text3D + WandMask + Fuse.Duplicate + Fuse.KScope."""
1920 grid = generate_grid_chart()
1921 cases = [
1922 (0, "light_point_mtl_blinn"),
1923 (1, "light_spot_mtl_cook"),
1924 (2, "replace_mtl_tex2d"),
1925 (3, "override3d_hide_cube"),
1926 (4, "duplicate3d_5x"),
1927 (5, "displace3d_plane"),
1928 (6, "text3d_hello"),
1929 (7, "wand_mask_red_quad"),
1930 (8, "fuse_duplicate_4x"),
1931 ]
1932 nodes = [
1933 make_loader("GridLoader", grid, post_mult=1),
1934 """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, },
1935\t\tGradBG = Background { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, Type = Input { Value = FuID { "Horizontal" }, }, TopLeftRed = Input { Value = 0, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopRightRed = Input { Value = 1, }, TopRightGreen = Input { Value = 1, }, TopRightBlue = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, }, },
1936\t\tCamBase = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 5.0, }, AoV = Input { Value = 35.0, }, FilmGate = Input { Value = FuID { "User" }, }, ApertureW = Input { Value = 1.0, }, ApertureH = Input { Value = 1.0, }, }, },
1937\t\t-- f00: LightPoint + MtlBlinn on Sphere
1938\t\tBlinn0 = MtlBlinn { Inputs = { ["Diffuse.Color.Red"] = Input { Value = 0.2, }, ["Diffuse.Color.Green"] = Input { Value = 0.6, }, ["Diffuse.Color.Blue"] = Input { Value = 0.9, }, ["Specular.Intensity"] = Input { Value = 0.8, }, ["Specular.Exponent"] = Input { Value = 32.0, }, }, },
1939\t\tSph0 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, MaterialInput = Input { SourceOp = "Blinn0", Source = "MaterialOutput", }, }, },
1940\t\tPt0 = LightPoint { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = 2.0, }, ["Transform3DOp.Translate.Y"] = Input { Value = 1.5, }, ["Transform3DOp.Translate.Z"] = Input { Value = 3.0, }, Intensity = Input { Value = 1.2, }, }, },
1941\t\tAmb0 = LightAmbient { Inputs = { Intensity = Input { Value = 0.15, }, }, },
1942\t\tM3D_0 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Sph0", Source = "Output", }, SceneInput2 = Input { SourceOp = "Pt0", Source = "Output", }, SceneInput3 = Input { SourceOp = "Amb0", Source = "Output", }, SceneInput4 = Input { SourceOp = "CamBase", Source = "Output", }, }, },
1943\t\tOp_0 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, ["RendererSoftware.LightingEnabled"] = Input { Value = 1, }, SceneInput = Input { SourceOp = "M3D_0", Source = "Output", }, }, },
1944\t\t-- f01: LightSpot + MtlCookTorrance on Plane
1945\t\tCook1 = MtlCookTorrance { Inputs = { ["Diffuse.Color.Red"] = Input { Value = 0.9, }, ["Diffuse.Color.Green"] = Input { Value = 0.8, }, ["Diffuse.Color.Blue"] = Input { Value = 0.7, }, ["Specular.Roughness"] = Input { Value = 0.35, }, }, },
1946\t\tPl1 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfacePlaneInputs" }, }, ["SurfacePlaneInputs.Width"] = Input { Value = 3.0, }, ["SurfacePlaneInputs.Height"] = Input { Value = 3.0, }, MaterialInput = Input { SourceOp = "Cook1", Source = "MaterialOutput", }, }, },
1947\t\tSpot1 = LightSpot { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 3.5, }, ConeAngle = Input { Value = 30.0, }, PenumbraAngle = Input { Value = 10.0, }, Intensity = Input { Value = 1.2, }, }, },
1948\t\tM3D_1 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Pl1", Source = "Output", }, SceneInput2 = Input { SourceOp = "Spot1", Source = "Output", }, SceneInput3 = Input { SourceOp = "CamBase", Source = "Output", }, }, },
1949\t\tOp_1 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, ["RendererSoftware.LightingEnabled"] = Input { Value = 1, }, SceneInput = Input { SourceOp = "M3D_1", Source = "Output", }, }, },
1950\t\t-- f02: ReplaceMaterial3D + Texture2DOperator
1951\t\tTex2 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "GridLoader", Source = "Output", }, }, },
1952\t\tSph2 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, }, },
1953\t\tRep2 = ReplaceMaterial3D { Inputs = { SceneInput = Input { SourceOp = "Sph2", Source = "Output", }, MaterialInput = Input { SourceOp = "Tex2", Source = "MaterialOutput", }, }, },
1954\t\tM3D_2 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Rep2", Source = "Output", }, SceneInput2 = Input { SourceOp = "CamBase", Source = "Output", }, }, },
1955\t\tOp_2 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_2", Source = "Output", }, }, },
1956\t\t-- f03: Override3D hiding left cube while right cube remains visible
1957\t\tCubeL = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, ["Transform3DOp.Translate.X"] = Input { Value = -0.8, }, ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 1.0, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.2, }, ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.2, }, }, },
1958\t\tOvr3 = Override3D { Inputs = { SceneInput = Input { SourceOp = "CubeL", Source = "Output", }, ["Visibility.DoVisible"] = Input { Value = 1, }, ["Visibility.IsVisible"] = Input { Value = 0, }, }, },
1959\t\tCubeR = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, ["Transform3DOp.Translate.X"] = Input { Value = 0.8, }, ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.2, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.8, }, ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.3, }, }, },
1960\t\tM3D_3 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Ovr3", Source = "Output", }, SceneInput2 = Input { SourceOp = "CubeR", Source = "Output", }, SceneInput3 = Input { SourceOp = "CamBase", Source = "Output", }, }, },
1961\t\tOp_3 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_3", Source = "Output", }, }, },
1962\t\t-- f04: Duplicate3D 5 copies along X
1963\t\tBox4 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceCubeInputs" }, }, ["SurfaceCubeInputs.Size"] = Input { Value = 0.35, }, ["Transform3DOp.Translate.X"] = Input { Value = -1.2, }, ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.9, }, ["MtlStdInputs.Diffuse.Color.Green"] = Input { Value = 0.5, }, ["MtlStdInputs.Diffuse.Color.Blue"] = Input { Value = 0.1, }, }, },
1964\t\tDup4 = Duplicate3D { Inputs = { SceneInput = Input { SourceOp = "Box4", Source = "Output", }, FirstCopy = Input { Value = 0, }, LastCopy = Input { Value = 4, }, ["Translate.X"] = Input { Value = 0.6, }, ["Rotate.Z"] = Input { Value = 15.0, }, }, },
1965\t\tM3D_4 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Dup4", Source = "Output", }, SceneInput2 = Input { SourceOp = "CamBase", Source = "Output", }, }, },
1966\t\tOp_4 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_4", Source = "Output", }, }, },
1967\t\t-- f05: Displace3D on subdivided plane
1968\t\tPl5 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfacePlaneInputs" }, }, ["SurfacePlaneInputs.Width"] = Input { Value = 2.0, }, ["SurfacePlaneInputs.Height"] = Input { Value = 2.0, }, ["Transform3DOp.Rotate.Y"] = Input { Value = -35.0, }, MaterialInput = Input { SourceOp = "GridLoader", Source = "Output", }, }, },
1969\t\tDisp5 = Displace3D { Inputs = { SceneInput = Input { SourceOp = "Pl5", Source = "Output", }, Input = Input { SourceOp = "GradBG", Source = "Output", }, Scale = Input { Value = 0.5, }, }, },
1970\t\tM3D_5 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Disp5", Source = "Output", }, SceneInput2 = Input { SourceOp = "CamBase", Source = "Output", }, }, },
1971\t\tOp_5 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_5", Source = "Output", }, }, },
1972\t\t-- f06: Text3D
1973\t\tT3D_6 = Text3D { Inputs = { StyledText = Input { Value = "HELLO", }, Font = Input { Value = "Open Sans", }, Style = Input { Value = "Bold", }, Size = Input { Value = 0.35, }, Red1 = Input { Value = 1.0, }, Green1 = Input { Value = 0.85, }, Blue1 = Input { Value = 0.2, }, }, },
1974\t\tM3D_6 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "T3D_6", Source = "Output", }, SceneInput2 = Input { SourceOp = "CamBase", Source = "Output", }, }, },
1975\t\tOp_6 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_6", Source = "Output", }, }, },
1976\t\t-- f07: WandMask selecting top-left red cell of GridLoader
1977\t\tWand7 = WandMask { Inputs = { Source = Input { SourceOp = "GridLoader", Source = "Output", }, SelectionPoint = Input { Value = { 0.08, 0.92 }, }, SelectionRange = Input { Value = 0.15, }, }, },
1978\t\tOp_7 = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 1, }, TopLeftBlue = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, EffectMask = Input { SourceOp = "Wand7", Source = "Mask", }, }, },
1979\t\t-- f08: Fuse.Duplicate 4 copies rotated 30 deg & scaled 0.85
1980\t\tSmall8 = Transform { Inputs = { Input = Input { SourceOp = "GridLoader", Source = "Output", }, Size = Input { Value = 0.45, }, }, },
1981\t\tOp_8 = Fuse.Duplicate { Inputs = { Background = Input { SourceOp = "Small8", Source = "Output", }, Copies = Input { Value = 4, }, Angle = Input { Value = 30.0, }, XSize = Input { Value = 0.85, }, }, },""",
1982 ]
1983 splines = []
1984 prev = "BlackBG"
1985 for f, _label in cases:
1986 bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases}
1987 sname = f"A3D_{f}_Blend"
1988 splines.append(step_spline(sname, bl))
1989 nodes.append(f"""\t\tSw_{f} = Merge {{
1990\t\t\tInputs = {{
1991\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }},
1992\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }},
1993\t\t\t\tForeground = Input {{ SourceOp = "Op_{f}", Source = "Output", }},
1994\t\t\t}},
1995\t\t}},""")
1996 prev = f"Sw_{f}"
1997 nodes.append(make_saver(prev, "archive_3d"))
1998 comp_path = local_root() / "comps" / "probe_archive_3d.comp"
1999 comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1))
2000 return comp_path, "archive_3d", cases
2001
2002
1918def main():2003def main():
1919 ensure_dirs()2004 ensure_dirs()
1920 which = [a for a in sys.argv[1:] if not a.startswith("--")] or ["merge"]2005 which = [a for a in sys.argv[1:] if not a.startswith("--")] or ["merge"]
...@@ -1933,6 +2018,7 @@ def main():...@@ -1933,6 +2018,7 @@ def main():
1933 "vortex_cc": build_probe_vortex_cc,2018 "vortex_cc": build_probe_vortex_cc,
1934 "moon_3d": build_probe_moon_3d,2019 "moon_3d": build_probe_moon_3d,
1935 "ultrakey": build_probe_ultrakey,2020 "ultrakey": build_probe_ultrakey,
2021 "archive_3d": build_probe_archive_3d,
1936 "glow": build_probe_glow,2022 "glow": build_probe_glow,
1937 "text": build_probe_text,2023 "text": build_probe_text,
1938 "noise_text": build_probe_noise_text,2024 "noise_text": build_probe_noise_text,
scripts/gen_compatibility.py+22-8
...@@ -104,6 +104,8 @@ TOOL_METADATA: Sequence[ToolMeta] = (...@@ -104,6 +104,8 @@ TOOL_METADATA: Sequence[ToolMeta] = (
104 ToolMeta("DVE", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`)."),104 ToolMeta("DVE", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`)."),
105 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)."),105 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)."),
106 ToolMeta("Vortex", "Transform, Warp & Framing", "`vortex_cc`", "0.0%–0.4%", "Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`)."),106 ToolMeta("Vortex", "Transform, Warp & Framing", "`vortex_cc`", "0.0%–0.4%", "Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`)."),
107 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`)."),
108 ToolMeta("Fuse.KScope", "Transform, Warp & Framing", "Unit tests", "0.0%", "N-slice radial kaleidoscope mirror (`Slices`, `Center`, `Angle`, `CaptureAngle`, `Scale`, `Edges`)."),
107 ToolMeta("Scale", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Proportional/non-proportional image scaling with resampling filter."),109 ToolMeta("Scale", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Proportional/non-proportional image scaling with resampling filter."),
108 ToolMeta("BetterResize", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`)."),110 ToolMeta("BetterResize", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`)."),
109 ToolMeta("Crop", "Transform, Warp & Framing", "Suite comps", "0.0%–0.1%", "Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`)."),111 ToolMeta("Crop", "Transform, Warp & Framing", "Suite comps", "0.0%–0.1%", "Region crop & canvas repositioning (`XOffset`, `YOffset`, `XSize`, `YSize`, `KeepCentered`)."),
...@@ -114,6 +116,7 @@ TOOL_METADATA: Sequence[ToolMeta] = (...@@ -114,6 +116,7 @@ TOOL_METADATA: Sequence[ToolMeta] = (
114 ToolMeta("RectangleMask", "Masks", "`mask`, `mask_softedge`", "0.0%–0.2%", "Center, Width, Height, `CornerRadius`, Angle, progressive-pyramid `SoftEdge`, `BorderWidth`, `Solid`, `Filter`, `ClippingMode`, `Invert`, `PaintMode` chaining."),116 ToolMeta("RectangleMask", "Masks", "`mask`, `mask_softedge`", "0.0%–0.2%", "Center, Width, Height, `CornerRadius`, Angle, progressive-pyramid `SoftEdge`, `BorderWidth`, `Solid`, `Filter`, `ClippingMode`, `Invert`, `PaintMode` chaining."),
115 ToolMeta("PolylineMask", "Masks", "`mask_softedge`, Suite comps", "0.1%–0.4%", "CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, progressive-pyramid `SoftEdge`, `ClippingMode`, `Invert`, `PaintMode`."),117 ToolMeta("PolylineMask", "Masks", "`mask_softedge`, Suite comps", "0.1%–0.4%", "CPU `zeno` Bezier/linear polygon rasterizer with animated keyframed `Polyline` splines, progressive-pyramid `SoftEdge`, `ClippingMode`, `Invert`, `PaintMode`."),
116 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`."),118 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`."),
119 ToolMeta("WandMask", "Masks", "`archive_3d`", "0.0%–0.3%", "Seeded BFS flood-fill wand mask (`Source`, `SelectionPoint`, `SelectionRange`, `ColorSpace`, `SoftEdge`, `Invert`, `Level`, `PaintMode`)."),
117120
118 # Particles121 # Particles
119 ToolMeta("pRender", "Particles", "Unit tests", "Visual*", "2D deterministic particle rasterizer (`ParticleStyleBitmap` rotated bilinear sprites, `ParticleStylePoint`/`Blob`, cached frame stepping). *Stochastic seed."),122 ToolMeta("pRender", "Particles", "Unit tests", "Visual*", "2D deterministic particle rasterizer (`ParticleStyleBitmap` rotated bilinear sprites, `ParticleStylePoint`/`Blob`, cached frame stepping). *Stochastic seed."),
...@@ -132,8 +135,20 @@ TOOL_METADATA: Sequence[ToolMeta] = (...@@ -132,8 +135,20 @@ TOOL_METADATA: Sequence[ToolMeta] = (
132 ToolMeta("Transform3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node."),135 ToolMeta("Transform3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node."),
133 ToolMeta("ImagePlane3D", "3D Pipeline", "`cam3d`", "0.1%–0.4%", "Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture."),136 ToolMeta("ImagePlane3D", "3D Pipeline", "`cam3d`", "0.1%–0.4%", "Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture."),
134 ToolMeta("Shape3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "`Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry."),137 ToolMeta("Shape3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "`Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry."),
138 ToolMeta("Text3D", "3D Pipeline", "`archive_3d`", "Visual*", "3D CoreText rasterized text plane with optional multi-slice `-Z` extrusion (`ExtrusionDepth`, `StyledText`, `Font`, `Style`, `Size`, color)."),
135 ToolMeta("LightAmbient", "3D Pipeline", "Suite comps", "0.1%–0.4%", "Scene ambient RGB light intensity accumulation in `Renderer3D`."),139 ToolMeta("LightAmbient", "3D Pipeline", "Suite comps", "0.1%–0.4%", "Scene ambient RGB light intensity accumulation in `Renderer3D`."),
136 ToolMeta("LightDirectional", "3D Pipeline", "Suite comps", "0.1%–0.4%", "World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`."),140 ToolMeta("LightDirectional", "3D Pipeline", "Suite comps", "0.1%–0.4%", "World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`."),
141 ToolMeta("LightPoint", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Positional point light with RGB color, `Intensity`, `DecayType` (`None`/`Linear`/`Quadratic`), and `DecayRate`."),
142 ToolMeta("LightSpot", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Directional spotlight with `ConeAngle`, `PenumbraAngle`, `Intensity`, RGB color, and `DecayType`."),
143 ToolMeta("MtlBlinn", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Blinn-Phong 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Diffuse.Color.Material`, `Specular.Color/Intensity/Exponent`)."),
144 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`)."),
145 ToolMeta("MtlPhong", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Phong 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Specular.Color/Intensity/Exponent`)."),
146 ToolMeta("Texture2DOperator", "3D Pipeline", "`archive_3d`", "0.0%–0.4%", "2D-image-to-3D-material adapter feeding `MaterialInput` or `Diffuse.Color.Material`."),
147 ToolMeta("ReplaceMaterial3D", "3D Pipeline", "`archive_3d`", "0.0%–0.4%", "Subtree 3D material override (`SceneInput` + `MaterialInput`)."),
148 ToolMeta("Override3D", "3D Pipeline", "`archive_3d`", "0.0%–0.2%", "Subtree 3D visibility (`Visibility.DoVisible`/`IsVisible`) and lighting (`Lighting.DoAffectedByLights`/`IsAffectedByLights`) override."),
149 ToolMeta("Duplicate3D", "3D Pipeline", "`archive_3d`", "0.1%–0.5%", "Cumulative 3D scene instancer (`FirstCopy..LastCopy`, `Transform3DOp`, seeded `JitterTranslate`/`JitterRotate`)."),
150 ToolMeta("ReplaceNormals3D", "3D Pipeline", "`archive_3d`", "0.0%–0.4%", "Subtree normal orientation override (`FlipNormals`)."),
151 ToolMeta("Displace3D", "3D Pipeline", "`archive_3d`", "0.2%–1.5%", "Heightmap vertex displacement along mesh normals (`Input`, `Scale`, `Bias`, `Channel`) with smooth normal recomputation."),
137152
138 # Time, Routing & Utility153 # Time, Routing & Utility
139 ToolMeta("Saver", "Time, Routing & Utility", "All suites", "0.0%", "Output sink / passthrough in interactive Flow; Saver-driven pipelined PNG sequence export (`render-check --export` and `Cmd+Shift+R`)."),154 ToolMeta("Saver", "Time, Routing & Utility", "All suites", "0.0%", "Output sink / passthrough in interactive Flow; Saver-driven pipelined PNG sequence export (`render-check --export` and `Cmd+Shift+R`)."),
...@@ -186,13 +201,6 @@ UNSUPPORTED_NOTES: Sequence[UnsupportedMeta] = (...@@ -186,13 +201,6 @@ UNSUPPORTED_NOTES: Sequence[UnsupportedMeta] = (
186 UnsupportedMeta("PlanarTracker", "Preserved lossless on save; passes through main image input in Flow.", 7),201 UnsupportedMeta("PlanarTracker", "Preserved lossless on save; passes through main image input in Flow.", 7),
187 UnsupportedMeta("Dimension.CopyAux", "Preserved lossless on save; passes through main image input.", None),202 UnsupportedMeta("Dimension.CopyAux", "Preserved lossless on save; passes through main image input.", None),
188 UnsupportedMeta("SurfaceFBXMesh", "Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`.", None),203 UnsupportedMeta("SurfaceFBXMesh", "Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`.", None),
189 UnsupportedMeta("Text3D", "Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`.", None),
190 UnsupportedMeta("MtlBlinn", "Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending).", None),
191 UnsupportedMeta("MtlCookTorrance", "Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Cook-Torrance BRDF pending).", None),
192 UnsupportedMeta("WandMask", "Preserved lossless on save; flood-fill wand mask not yet implemented.", None),
193 UnsupportedMeta("ReplaceMaterial3D", "Preserved lossless on save; 3D material override not yet traversed in `Renderer3D`.", None),
194 UnsupportedMeta("Override3D", "Preserved lossless on save; 3D render-flag override not yet traversed in `Renderer3D`.", None),
195 UnsupportedMeta("Displace3D", "Preserved lossless on save; vertex displacement not yet implemented in `Renderer3D`.", None),
196)204)
197205
198206
...@@ -217,7 +225,7 @@ def parse_eval_rs(path: Path) -> Set[str]:...@@ -217,7 +225,7 @@ def parse_eval_rs(path: Path) -> Set[str]:
217225
218226
219def parse_scene3d_rs(path: Path) -> Set[str]:227def parse_scene3d_rs(path: Path) -> Set[str]:
220 """Extract all supported 3D tool class names from collect_scene in scene3d.rs."""228 """Extract all supported 3D tool class names from collect_scene & resolve_material in scene3d.rs."""
221 text = path.read_text(encoding="utf-8")229 text = path.read_text(encoding="utf-8")
222 m = re.search(r"match node\.kind\.as_str\(\)\s*\{(.*?)\n _ => \{\}", text, re.S)230 m = re.search(r"match node\.kind\.as_str\(\)\s*\{(.*?)\n _ => \{\}", text, re.S)
223 if not m:231 if not m:
...@@ -227,6 +235,12 @@ def parse_scene3d_rs(path: Path) -> Set[str]:...@@ -227,6 +235,12 @@ def parse_scene3d_rs(path: Path) -> Set[str]:
227 if line.startswith(' "') and "=>" in line:235 if line.startswith(' "') and "=>" in line:
228 lhs = line.split("=>", 1)[0]236 lhs = line.split("=>", 1)[0]
229 tools.update(re.findall(r'"([^"]+)"', lhs))237 tools.update(re.findall(r'"([^"]+)"', lhs))
238 mm = re.search(r"match n\.kind\.as_str\(\)\s*\{(.*?)\n _ =>", text, re.S)
239 if mm:
240 for line in mm.group(1).splitlines():
241 if line.startswith(' "') and "=>" in line:
242 lhs = line.split("=>", 1)[0]
243 tools.update(re.findall(r'"([^"]+)"', lhs))
230 return tools244 return tools
231245
232246