From 76fc78f911b8eff80bf8ebe824e6d289ad9e8335 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 12:46:02 -0800 Subject: [PATCH] RAM/VRAM/proxy caches (#13), 3D & archive tool depth (#11), and Studio Inspector/Add Tool/Flow authoring (#14) --- compatibility.md | 49 +- crates/engine/src/bin/render_check.rs | 16 +- crates/engine/src/cache.rs | 23 +- crates/engine/src/eval/io.rs | 180 ++- crates/engine/src/eval/masks.rs | 169 +++ crates/engine/src/eval/mod.rs | 167 ++- crates/engine/src/eval/text_3d.rs | 75 +- crates/engine/src/eval/transform.rs | 191 +++ crates/engine/src/lib.rs | 6 +- crates/engine/src/media.rs | 13 + crates/engine/src/ram_cache.rs | 566 ++++++++ crates/engine/src/scene3d.rs | 853 +++++++++++- crates/engine/src/shaders.wgsl | 38 + crates/flow/src/lib.rs | 524 ++++++- crates/model/src/comp.rs | 15 + crates/studio/src/add_tool.rs | 557 ++++++++ crates/studio/src/inspector.rs | 1802 +++++++++++++++++++++++++ crates/studio/src/main.rs | 700 ++++++++-- scripts/fusion_probes.py | 86 ++ scripts/gen_compatibility.py | 30 +- 20 files changed, 5782 insertions(+), 278 deletions(-) create mode 100644 crates/engine/src/ram_cache.rs create mode 100644 crates/studio/src/add_tool.rs create mode 100644 crates/studio/src/inspector.rs diff --git a/compatibility.md b/compatibility.md index 076176870c00ba671a7d2e408f81a6a708c650d5..f143b2a37d531510acc8bbd8310ba040ac5a9794 100644 --- a/compatibility.md +++ b/compatibility.md @@ -9,10 +9,10 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | Metric | Value | | --- | --- | -| **Supported Flow Tools** | **80** (71 2D/Fuse/utility in `eval.rs`, 7 3D scene nodes in `scene3d.rs`, 2 Flow annotations) | +| **Supported Flow Tools** | **95** (74 2D/Fuse/utility in `eval.rs`, 19 3D scene nodes in `scene3d.rs`, 2 Flow annotations) | | **Modifiers & Animation** | **7** systems (8 Fusion modifier classes + Lua expressions) | -| **Active Corpus (`trees/fusion`) Coverage** | **99.4%** (1,981 / 1,993 nodes across 16 `.comp` files) | -| **Archive Corpus (`private/samples`) Coverage** | **96.1%** (52,826 / 54,955 nodes across 324 `.comp` files) | +| **Active Corpus (`trees/fusion`) Coverage** | **99.5%** (1,984 / 1,993 nodes across 16 `.comp` files) | +| **Archive Corpus (`private/samples`) Coverage** | **98.7%** (54,258 / 54,955 nodes across 324 `.comp` files) | | **HiQ vs Fast Mode** | **`HiQ`**: honors `DepthFull` / generator `Depth` / `ChangeDepth` (`Rgba8Unorm`, clamped `Rgba16Float`, unclamped HDR `Rgba16Float`/`Rgba32Float`), full-res blurs & `XGlow`. **`Fast`**: collapses working targets to `Rgba8Unorm`, downsamples blurs, caps `XGlow` octaves for interactive scrubbing. | ## Generators @@ -83,6 +83,8 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | `DVE` | `tier1_b` | 0.1%–0.4% | 4 / 22 | 2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`). | | `Displace` | `displace`, `displace_wave` | 0.0%–0.1% | 11 / 109 | `XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting). | | `Vortex` | `vortex_cc` | 0.0%–0.4% | 1 / 1 | Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`). | +| `Fuse.Duplicate` | `archive_3d` | 0.0%–0.4% | 0 / 46 | Multi-copy iterative 2D transform composite (`Copies`, `Center`, `Size`, `Angle`, `Gain`, `Blend`, `TimeOffset`, `MergeUnder`). | +| `Fuse.KScope` | Unit tests | 0.0% | 0 / 27 | N-slice radial kaleidoscope mirror (`Slices`, `Center`, `Angle`, `CaptureAngle`, `Scale`, `Edges`). | | `Scale` | Suite comps | 0.0%–0.2% | 12 / 98 | Proportional/non-proportional image scaling with resampling filter. | | `BetterResize` | Suite comps | 0.0%–0.2% | 0 / 93 | Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`). | | `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 | `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. | | `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`. | | `BitmapMask` | `mask_softedge` | 0.0%–0.2% | 3 / 121 | GPU image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`/`Saturation`/`Lightness`/`Hue`), `Low`/`High` clip, centered 1:1 alignment, `SoftEdge`, `Invert`, `Level`, `PaintMode`. | +| `WandMask` | `archive_3d` | 0.0%–0.3% | 0 / 150 | Seeded BFS flood-fill wand mask (`Source`, `SelectionPoint`, `SelectionRange`, `ColorSpace`, `SoftEdge`, `Invert`, `Level`, `PaintMode`). | ## Particles @@ -120,8 +123,20 @@ Auto-generated from live engine sources (`crates/engine/src/eval.rs`, `crates/en | `Transform3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 1 / 799 | 3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node. | | `ImagePlane3D` | `cam3d` | 0.1%–0.4% | 4 / 496 | Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture. | | `Shape3D` | `cam3d`, `cam3d_fov` | 0.1%–0.4% | 4 / 374 | `Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry. | +| `Text3D` | `archive_3d` | Visual* | 0 / 410 | 3D CoreText rasterized text plane with optional multi-slice `-Z` extrusion (`ExtrusionDepth`, `StyledText`, `Font`, `Style`, `Size`, color). | | `LightAmbient` | Suite comps | 0.1%–0.4% | 3 / 42 | Scene ambient RGB light intensity accumulation in `Renderer3D`. | | `LightDirectional` | Suite comps | 0.1%–0.4% | 3 / 82 | World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`. | +| `LightPoint` | `archive_3d` | 0.1%–0.8% | 0 / 63 | Positional point light with RGB color, `Intensity`, `DecayType` (`None`/`Linear`/`Quadratic`), and `DecayRate`. | +| `LightSpot` | `archive_3d` | 0.1%–0.8% | 0 / 52 | Directional spotlight with `ConeAngle`, `PenumbraAngle`, `Intensity`, RGB color, and `DecayType`. | +| `MtlBlinn` | `archive_3d` | 0.1%–0.8% | 0 / 181 | Blinn-Phong 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Diffuse.Color.Material`, `Specular.Color/Intensity/Exponent`). | +| `MtlCookTorrance` | `archive_3d` | 0.1%–0.8% | 3 / 8 | Cook-Torrance 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Diffuse.Color.Material`, `Specular.Roughness/Color/Intensity`). | +| `MtlPhong` | `archive_3d` | 0.1%–0.8% | 0 / 0 | Phong 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Specular.Color/Intensity/Exponent`). | +| `Texture2DOperator` | `archive_3d` | 0.0%–0.4% | 0 / 44 | 2D-image-to-3D-material adapter feeding `MaterialInput` or `Diffuse.Color.Material`. | +| `ReplaceMaterial3D` | `archive_3d` | 0.0%–0.4% | 0 / 131 | Subtree 3D material override (`SceneInput` + `MaterialInput`). | +| `Override3D` | `archive_3d` | 0.0%–0.2% | 0 / 124 | Subtree 3D visibility (`Visibility.DoVisible`/`IsVisible`) and lighting (`Lighting.DoAffectedByLights`/`IsAffectedByLights`) override. | +| `Duplicate3D` | `archive_3d` | 0.1%–0.5% | 0 / 74 | Cumulative 3D scene instancer (`FirstCopy..LastCopy`, `Transform3DOp`, seeded `JitterTranslate`/`JitterRotate`). | +| `ReplaceNormals3D` | `archive_3d` | 0.0%–0.4% | 0 / 27 | Subtree normal orientation override (`FlipNormals`). | +| `Displace3D` | `archive_3d` | 0.2%–1.5% | 0 / 95 | Heightmap vertex displacement along mesh normals (`Input`, `Scale`, `Bias`, `Channel`) with smooth normal recomputation. | ## Time, Routing & Utility @@ -165,25 +180,25 @@ Unlike Blackmagic Fusion — which unlinks missing OFX or Resolve-only plugins w | `PlanarTracker` | 0 / 0 | [#7](https://shale.paperclover.net/fission/issues/7) | Preserved lossless on save; passes through main image input in Flow. | | `Dimension.CopyAux` | 4 / 0 | — | Preserved lossless on save; passes through main image input. | | `SurfaceFBXMesh` | 0 / 216 | — | Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`. | -| `Text3D` | 0 / 410 | — | Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`. | -| `MtlBlinn` | 0 / 181 | — | Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending). | -| `MtlCookTorrance` | 3 / 8 | — | Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Cook-Torrance BRDF pending). | -| `WandMask` | 0 / 150 | — | Preserved lossless on save; flood-fill wand mask not yet implemented. | -| `ReplaceMaterial3D` | 0 / 131 | — | Preserved lossless on save; 3D material override not yet traversed in `Renderer3D`. | -| `Override3D` | 0 / 124 | — | Preserved lossless on save; 3D render-flag override not yet traversed in `Renderer3D`. | -| `Displace3D` | 0 / 95 | — | Preserved lossless on save; vertex displacement not yet implemented in `Renderer3D`. | -| `Duplicate3D` | 0 / 74 | — | Preserved lossless on save; passes through main input in Flow. | -| `LightPoint` | 0 / 63 | — | Preserved lossless on save; passes through main input in Flow. | -| `LightSpot` | 0 / 52 | — | Preserved lossless on save; passes through main input in Flow. | -| `Fuse.Duplicate` | 0 / 46 | — | Preserved lossless on save; passes through main input in Flow. | -| `Texture2DOperator` | 0 / 44 | — | Preserved lossless on save; passes through main input in Flow. | | `Multistroke` | 0 / 33 | — | Preserved lossless on save; passes through main input in Flow. | | `Drip` | 0 / 29 | — | Preserved lossless on save; passes through main input in Flow. | | `PolylineStroke` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. | -| `Fuse.KScope` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. | -| `ReplaceNormals3D` | 0 / 27 | — | Preserved lossless on save; passes through main input in Flow. | | `Paint` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. | | `Fuse.HexagonTiles` | 0 / 25 | — | Preserved lossless on save; passes through main input in Flow. | +| `Cube3D` | 0 / 24 | — | Preserved lossless on save; passes through main input in Flow. | +| `Expression` | 0 / 23 | — | Preserved lossless on save; passes through main input in Flow. | +| `AudioDisplay` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. | +| `sRender` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. | +| `Fuse.AlphaWeightedNoise` | 0 / 21 | — | Preserved lossless on save; passes through main input in Flow. | +| `Fuse.Hexagon` | 0 / 17 | — | Preserved lossless on save; passes through main input in Flow. | +| `DaySky` | 0 / 16 | — | Preserved lossless on save; passes through main input in Flow. | +| `PaintMask` | 0 / 14 | — | Preserved lossless on save; passes through main input in Flow. | +| `SurfaceAlembicMesh` | 0 / 13 | — | Preserved lossless on save; passes through main input in Flow. | +| `TextureTransformOperator` | 0 / 12 | — | Preserved lossless on save; passes through main input in Flow. | +| `pBounce` | 0 / 10 | — | Preserved lossless on save; passes through main input in Flow. | +| `BumpMap` | 0 / 10 | — | Preserved lossless on save; passes through main input in Flow. | +| `sNGon` | 0 / 9 | — | Preserved lossless on save; passes through main input in Flow. | +| `Dent` | 0 / 7 | — | Preserved lossless on save; passes through main input in Flow. | --- diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index f1dddf3a508ae22d1cc7fa64f6f72e2c6768fae0..410db419be7cb2f985781da2395a1bd9527faaec 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -366,6 +366,8 @@ fn main() -> Result<(), Box> { let mut ref_path: Option = None; let mut node_name: Option = None; let mut proxy_scale: u32 = 1; + let mut use_proxy_clips = false; + let mut vram_budget_mb: Option = None; let mut hiq = true; let mut bench = false; let mut i = 3; @@ -387,6 +389,14 @@ fn main() -> Result<(), Box> { proxy_scale = args[i + 1].parse().unwrap_or(1).max(1); i += 2; } + "--proxy-clips" => { + use_proxy_clips = true; + i += 1; + } + "--vram-mb" if i + 1 < args.len() => { + vram_budget_mb = args[i + 1].parse().ok(); + i += 2; + } "--fast" => { hiq = false; i += 1; @@ -396,7 +406,7 @@ fn main() -> Result<(), Box> { i += 1; } other => { - eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --fast, --bench)"); + eprintln!("unexpected argument '{other}' (use --out, --ref, --node, --proxy, --proxy-clips, --vram-mb, --fast, --bench)"); std::process::exit(2); } } @@ -421,6 +431,10 @@ fn main() -> Result<(), Box> { let mut engine = Engine::new_headless()?; engine.proxy_scale = proxy_scale; + engine.use_proxy_clips = use_proxy_clips; + if let Some(mb) = vram_budget_mb { + engine.set_vram_budget_mb(mb); + } engine.hiq = hiq; let (tex, cold) = engine.evaluate(&comp, target, frame); diff --git a/crates/engine/src/cache.rs b/crates/engine/src/cache.rs index c0280c18927944910a3fc3f0d0d0b8c7f3220729..42fb830ffa304fd5f23371474aef4a9dfaab348b 100644 --- a/crates/engine/src/cache.rs +++ b/crates/engine/src/cache.rs @@ -111,12 +111,16 @@ struct Entry { frames: HashSet, } +/// Default GPU texture cache VRAM budget (768 MiB keeps heavy 150+ node comps well below 1 GiB). +pub const DEFAULT_VRAM_BUDGET_MB: u64 = 768; + pub struct NodeCache { pub mode: CacheMode, pub budget_bytes: u64, entries: HashMap, total_bytes: u64, tick: u64, + evictions: u64, /// Monotonic salt bumped when busting GPU cache globally. pub gpu_salt: u64, /// Per-node salt bumped when surgically busting a subtree. @@ -127,15 +131,29 @@ impl NodeCache { pub fn new(budget_mb: u64) -> Self { Self { mode: CacheMode::Enabled, - budget_bytes: budget_mb * 1024 * 1024, + budget_bytes: budget_mb.saturating_mul(1024 * 1024), entries: HashMap::new(), total_bytes: 0, tick: 0, + evictions: 0, gpu_salt: 0, node_salts: HashMap::new(), } } + pub fn set_budget_mb(&mut self, budget_mb: u64) { + self.budget_bytes = budget_mb.saturating_mul(1024 * 1024); + self.evict_over_budget(); + } + + pub fn budget_mb(&self) -> u64 { + self.budget_bytes / (1024 * 1024) + } + + pub fn eviction_count(&self) -> u64 { + self.evictions + } + pub fn node_salt(&self, id: NodeId) -> u64 { self.node_salts.get(&id).copied().unwrap_or(0) } @@ -178,13 +196,14 @@ impl NodeCache { } fn evict_over_budget(&mut self) { - while self.total_bytes > self.budget_bytes && self.entries.len() > 2 { + while self.total_bytes > self.budget_bytes && self.entries.len() > 1 { let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used) else { break; }; if let Some(removed) = self.entries.remove(&oldest_key) { self.total_bytes = self.total_bytes.saturating_sub(removed.tex.bytes); + self.evictions += 1; } } } diff --git a/crates/engine/src/eval/io.rs b/crates/engine/src/eval/io.rs index 5316d4f8ac653d1eea4392f0cfe1d8996c3f20d9..c260e86744cad573b553e4fbaa76913b54c2e62c 100644 --- a/crates/engine/src/eval/io.rs +++ b/crates/engine/src/eval/io.rs @@ -21,8 +21,31 @@ impl Engine { node.static_str("Clip1.OpenEXRFormat.BlueName"), node.static_str("Clip1.OpenEXRFormat.AlphaName"), ]; + // When `use_proxy_clips` is enabled, prefer Loader `ProxyFilename` or `Clip.AlternateFilename` + // if the resolved proxy file exists on disk, falling back seamlessly to the primary clip. + let effective_clip: std::borrow::Cow<'_, model::ClipSpec> = if self.use_proxy_clips { + let proxy_candidate = node + .static_str("ProxyFilename") + .filter(|s| !s.trim().is_empty()) + .or_else(|| clip.alternate_filename.as_deref().filter(|s| !s.trim().is_empty())); + if let Some(proxy_name) = proxy_candidate { + let mut proxy_clip = clip.clone(); + proxy_clip.filename = proxy_name.to_owned(); + if crate::media::resolve_clip_path(&proxy_clip, frame_i) + .is_some_and(|p| p.exists()) + { + std::borrow::Cow::Owned(proxy_clip) + } else { + std::borrow::Cow::Borrowed(clip) + } + } else { + std::borrow::Cow::Borrowed(clip) + } + } else { + std::borrow::Cow::Borrowed(clip) + }; let Some((resolved, local_idx, img, loaded_from_disk)) = - self.media.load_clip(clip, frame_i, post_mult, exr_channels) + self.media.load_clip(&effective_clip, frame_i, post_mult, exr_channels) else { return self.dummy.clone(); }; @@ -770,3 +793,158 @@ impl Engine { dst } } + +#[cfg(test)] +mod tests { + use super::*; + + fn write_solid_png(path: &std::path::Path, w: u32, h: u32, rgba: [u8; 4]) { + let mut buf = Vec::with_capacity((w * h * 4) as usize); + for _ in 0..(w * h) { + buf.extend_from_slice(&rgba); + } + let file = std::fs::File::create(path).expect("create png"); + let mut enc = png::Encoder::new(file, w, h); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.write_header() + .expect("hdr") + .write_image_data(&buf) + .expect("data"); + } + + #[test] + fn loader_prefers_proxy_or_alternate_filename_and_respects_proxy_scale() { + let dir = std::env::temp_dir().join("fission_proxy_loader_test"); + let _ = std::fs::create_dir_all(&dir); + let main_png = dir.join("main.png"); + let proxy_png = dir.join("proxy.png"); + let alt_png = dir.join("alt.png"); + write_solid_png(&main_png, 32, 16, [255, 0, 0, 255]); // red + write_solid_png(&proxy_png, 32, 16, [0, 255, 0, 255]); // green + write_solid_png(&alt_png, 32, 16, [0, 0, 255, 255]); // blue + + let comp_src = format!( + r#" +Composition {{ + CurrentTime = 0, + RenderRange = {{ 0, 10 }}, + GlobalRange = {{ 0, 10 }}, + Tools = ordered() {{ + LD1 = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + AlternateFilename = "{}", + FormatID = "PNGFormat", + StartFrame = 0, + Length = 1, + }} + }}, + Inputs = {{ + ProxyFilename = Input {{ Value = "{}", }}, + }}, + }}, + LD2 = Loader {{ + Clips = {{ + Clip {{ + ID = "Clip1", + Filename = "{}", + AlternateFilename = "{}", + FormatID = "PNGFormat", + StartFrame = 0, + Length = 1, + }} + }}, + }}, + }}, +}} +"#, + main_png.display(), + alt_png.display(), + proxy_png.display(), + main_png.display(), + alt_png.display(), + ); + let comp = Comp::from_fusion_str(&comp_src).expect("parse"); + let ld1 = comp.find_node("LD1").expect("LD1"); + let ld2 = comp.find_node("LD2").expect("LD2"); + + let mut engine = Engine::new_headless().expect("gpu"); + // Default: primary red clip at 1:1 + let (tex, _) = engine.evaluate(&comp, ld1, 0.0); + assert_eq!(tex.size, [32, 16]); + let px = engine.readback_rgba(&tex).expect("readback"); + assert!(px[0] > 240 && px[1] < 15 && px[2] < 15, "expected red primary"); + + // Proxy clips enabled + 1:2 resolution scale: LD1 picks ProxyFilename (green), LD2 picks AlternateFilename (blue) + engine.use_proxy_clips = true; + engine.proxy_scale = 2; + let (tex1, _) = engine.evaluate(&comp, ld1, 0.0); + assert_eq!(tex1.size, [16, 8]); + let px1 = engine.readback_rgba(&tex1).expect("readback"); + assert!(px1[1] > 240 && px1[0] < 15 && px1[2] < 15, "expected green proxy"); + + let (tex2, _) = engine.evaluate(&comp, ld2, 0.0); + assert_eq!(tex2.size, [16, 8]); + let px2 = engine.readback_rgba(&tex2).expect("readback"); + assert!(px2[2] > 240 && px2[0] < 15 && px2[1] < 15, "expected blue alternate"); + + // 1:4 scale + engine.proxy_scale = 4; + let (tex4, _) = engine.evaluate(&comp, ld1, 0.0); + assert_eq!(tex4.size, [8, 4]); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn vram_budget_strictly_caps_node_cache() { + let mut engine = Engine::new_headless().expect("gpu"); + engine.set_vram_budget_mb(8); + assert_eq!(engine.vram_budget_mb(), 8); + + let comp_src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 20 }, + GlobalRange = { 0, 20 }, + Tools = ordered() { + BG = Background { + Inputs = { + Width = Input { Value = 1024, }, + Height = Input { Value = 1024, }, + TopLeftRed = Input { Value = 0.5, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + BC = BrightnessContrast { + Inputs = { + Gain = Input { SourceOp = "GainSp", Source = "Value", }, + Input = Input { SourceOp = "BG", Source = "Output", }, + }, + }, + GainSp = BezierSpline { + KeyFrames = { + [0] = { 0.5 }, + [10] = { 2.0 }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse"); + let bc = comp.find_node("BC").expect("BC"); + // Each 1024x1024 RGBA8 texture is 4 MB; 8 MB budget holds at most 2 textures across 6 animated frames. + for f in 0..6 { + let (_, stats) = engine.evaluate(&comp, bc, f as f64); + assert!( + stats.cached_vram_mb <= 8.5, + "VRAM exceeded 8 MB cap at frame {f}: {:.1} MB", + stats.cached_vram_mb + ); + } + assert!(engine.cache.eviction_count() >= 1); + } +} diff --git a/crates/engine/src/eval/masks.rs b/crates/engine/src/eval/masks.rs index d0337cc70684824b850e913ca84e04167983efa3..23d1a24a3adada77fc616e566d7591bc26a9dc9c 100644 --- a/crates/engine/src/eval/masks.rs +++ b/crates/engine/src/eval/masks.rs @@ -384,4 +384,173 @@ impl Engine { out_tex } + pub(super) fn eval_wand_mask( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + comp_dims: [u32; 2], + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node + .connected_node("Source") + .or_else(|| node.connected_node("Input")) + .and_then(|s| comp.find_node(s)) + else { + return create_texture(&self.device, comp_dims, 0); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let src = self.crop_to_canvas(enc, src); + let size = src.size; + + let seed_pt = comp.eval_point(node, "SelectionPoint", time, [0.5, 0.5], &self.expr); + let range = comp.eval_number(node, "SelectionRange", time, 0.1, &self.expr).clamp(0.0, 1.0) as f32; + let color_space = comp.eval_number(node, "ColorSpace", time, 0.0, &self.expr).round() as i32; + let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32; + let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) as f32; + let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32; + let is_box = Self::mask_filter_is_box(node); + let clamp_edges = Self::mask_clamp_edges(node); + let (prev_mask, _) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); + let prev_hash = prev_mask.as_ref().map_or(0, |m| m.content_hash); + let paint_mode = Self::paint_mode_id(node); + + let key = self.make_key( + node, + "WandMask", + size, + &[src.content_hash, prev_hash], + &[ + seed_pt[0] as f32, + seed_pt[1] as f32, + range, + color_space as f32, + soft, + invert, + level, + if is_box { 1.0 } else { 0.0 }, + clamp_edges, + paint_mode, + ], + ); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + // Flush pending GPU commands so readback sees fresh source pixels. + let flush_enc = std::mem::replace( + enc, + self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("comp-eval-post-wand"), + }), + ); + self.queue.submit(Some(flush_enc.finish())); + + let w = size[0].max(1) as usize; + let h = size[1].max(1) as usize; + let mut mask_rgba = vec![0u8; w * h * 4]; + if let Ok(src_rgba) = self.readback_rgba(&src) { + if src_rgba.len() >= w * h * 4 { + let sx = ((seed_pt[0] as f32).clamp(0.0, 1.0) * (w - 1) as f32).round() as usize; + let sy = ((1.0 - (seed_pt[1] as f32).clamp(0.0, 1.0)) * (h - 1) as f32).round() as usize; + let soff = (sy * w + sx) * 4; + let sr = src_rgba[soff] as f32 / 255.0; + let sg = src_rgba[soff + 1] as f32 / 255.0; + let sb = src_rgba[soff + 2] as f32 / 255.0; + let sl = 0.299 * sr + 0.587 * sg + 0.114 * sb; + + let mut visited = vec![false; w * h]; + let mut queue = std::collections::VecDeque::with_capacity(1024); + let start_idx = sy * w + sx; + visited[start_idx] = true; + queue.push_back((sx, sy)); + + while let Some((x, y)) = queue.pop_front() { + let off = (y * w + x) * 4; + mask_rgba[off] = 255; + mask_rgba[off + 1] = 255; + mask_rgba[off + 2] = 255; + mask_rgba[off + 3] = 255; + + let nbrs = [ + (x.wrapping_sub(1), y, x > 0), + (x + 1, y, x + 1 < w), + (x, y.wrapping_sub(1), y > 0), + (x, y + 1, y + 1 < h), + ]; + for (nx, ny, ok) in nbrs { + if !ok { + continue; + } + let ni = ny * w + nx; + if visited[ni] { + continue; + } + let noff = ni * 4; + let r = src_rgba[noff] as f32 / 255.0; + let g = src_rgba[noff + 1] as f32 / 255.0; + let b = src_rgba[noff + 2] as f32 / 255.0; + let dist = if color_space == 1 { + // YUV / Luma-weighted distance + let l = 0.299 * r + 0.587 * g + 0.114 * b; + let du = (b - l) - (sb - sl); + let dv = (r - l) - (sr - sl); + ((l - sl).abs()).max(du.abs()).max(dv.abs()) + } else { + // Max-channel RGB Chebyshev distance + (r - sr).abs().max((g - sg).abs()).max((b - sb).abs()) + }; + if dist <= range { + visited[ni] = true; + queue.push_back((nx, ny)); + } + } + } + } + } + + let soft_px = soft * size[0] as f32; + let need_post = soft_px >= 0.5 || invert > 0.5 || (level - 1.0).abs() > 1e-4 || prev_mask.is_some(); + let raw_tex = create_texture(&self.device, size, if need_post { 0 } else { key }); + self.queue.write_texture( + raw_tex.texture.as_image_copy(), + &mask_rgba, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(size[0] * 4), + rows_per_image: Some(size[1]), + }, + wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + ); + + let out_tex = if need_post { + let blurred = if soft_px >= 0.5 { + self.blur_mask_texture(enc, &raw_tex, soft_px, is_box, clamp_edges) + } else { + raw_tex + }; + let combined = create_texture(&self.device, size, key); + let mut uc = UniformParams::default(); + uc.p[0] = [paint_mode, invert, level, if prev_mask.is_some() { 1.0 } else { 0.0 }]; + let mv = prev_mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::MaskCombine, &blurred.view, &self.dummy.view, mv, &combined, &uc); + combined + } else { + raw_tex + }; + + self.cache.insert(key, out_tex.clone(), node.id, frame_i); + out_tex + } + } diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index 847c5301ec5d75697a7f449e37a5e11d2fcbfd00..3855e58f356dbfb834a6f7e58f64d6e78608bcbe 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -102,6 +102,7 @@ enum ShaderOp { SetDomain, ChangeDepth, Vortex, + KScope, } struct Pipelines { @@ -149,6 +150,7 @@ struct Pipelines { set_domain: wgpu::ComputePipeline, change_depth: wgpu::ComputePipeline, vortex: wgpu::ComputePipeline, + kscope: wgpu::ComputePipeline, } impl Pipelines { @@ -290,6 +292,7 @@ impl Pipelines { set_domain: make("set_domain_op"), change_depth: make("change_depth_op"), vortex: make("vortex_op"), + kscope: make("kscope_op"), } } @@ -337,6 +340,7 @@ impl Pipelines { ShaderOp::SetDomain => &self.set_domain, ShaderOp::ChangeDepth => &self.change_depth, ShaderOp::Vortex => &self.vortex, + ShaderOp::KScope => &self.kscope, } } } @@ -359,11 +363,16 @@ pub struct Engine { pub expr: ExprEngine, /// Per-evaluation DAG memo so diamond graphs never re-evaluate a node twice within one frame. frame_memo: HashMap<(NodeId, i64, Option<[u32; 2]>), CachedTexture>, + /// Bounded LRU of recent final output textures (up to 8 entries) so tight VRAM caps on + /// 150+ node comps still deliver `<0.1ms` warm hits during pan/zoom/exposure/scrubbing. + output_cache: std::collections::VecDeque<(u64, CachedTexture, Vec)>, /// Inherited target image dimensions when evaluating an `EffectMask` chain (Fusion masks default /// to matching the dimensions & aspect ratio of the node they mask!). mask_target_size: Option<[u32; 2]>, /// Proxy downscale divisor: 1 = full res, 2 = half res, 4 = quarter res. pub proxy_scale: u32, + /// When `true`, `Loader` nodes prefer `ProxyFilename` or `Clip.AlternateFilename` if present on disk. + pub use_proxy_clips: bool, /// High-Quality mode (`true` = exact Fusion bar-for-bar passes & project/ChangeDepth bit depth; /// `false` = perfmaxxed pyramid blur/glow & fast Rgba8Unorm working textures). pub hiq: bool, @@ -398,12 +407,14 @@ impl Engine { particles: crate::particles::ParticleCache::default(), sprite_cache: HashMap::new(), dummy, - cache: NodeCache::new(2048), // 2 GB GPU texture cache cap (prevents thrashing on 100+ node diamond DAGs) - media: MediaCache::new(1024), + cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB), + media: MediaCache::new(512), expr: ExprEngine::new(), frame_memo: HashMap::new(), + output_cache: std::collections::VecDeque::new(), mask_target_size: None, proxy_scale: 1, + use_proxy_clips: false, hiq: true, } } @@ -531,8 +542,85 @@ impl Engine { self.cache.mode = mode; } + pub fn set_vram_budget_mb(&mut self, budget_mb: u64) { + self.cache.set_budget_mb(budget_mb); + if budget_mb < 64 { + self.output_cache.clear(); + } + } + + pub fn vram_budget_mb(&self) -> u64 { + self.cache.budget_mb() + } + + pub fn set_media_budget_mb(&mut self, budget_mb: u64) { + self.media.set_budget_mb(budget_mb); + } + + /// Uploads a cached `RamFrame` directly into a viewer `wgpu::Texture` with full + /// `DisplaySettings` (exposure, gamma, channel isolate, zoom/pan) without evaluating the DAG. + pub fn render_ram_frame_into_viewer( + &self, + frame: &crate::ram_cache::RamFrame, + dst_texture: &wgpu::Texture, + display: DisplaySettings, + ) -> EvalStats { + let t0 = Instant::now(); + let src = create_texture(&self.device, frame.size, 0); + self.queue.write_texture( + src.texture.as_image_copy(), + &frame.rgba, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(frame.size[0] * 4), + rows_per_image: Some(frame.size[1]), + }, + wgpu::Extent3d { + width: frame.size[0], + height: frame.size[1], + depth_or_array_layers: 1, + }, + ); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("comp-ram-viewer-blit"), + }); + let dst_size = [dst_texture.width(), dst_texture.height()]; + let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default()); + let mut params = UniformParams::default(); + params.p[0] = [ + 2.0_f32.powf(display.exposure), + display.gamma, + display.channel as f32, + if display.checker_bg { 1.0 } else { 0.0 }, + ]; + params.p[1] = display.uv_rect; + params.p[2] = [if display.smooth_resize { 0.0 } else { 1.0 }, 0.0, 0.0, 0.0]; + self.dispatch_to_view( + &mut encoder, + &self.pipelines.display_blit, + &src.view, + &self.dummy.view, + &self.dummy.view, + &dst_view, + dst_size, + ¶ms, + ); + self.queue.submit(Some(encoder.finish())); + + EvalStats { + eval_ms: t0.elapsed().as_secs_f64() * 1000.0, + cache_hits: 1, + cached_entries: self.cache.entry_count(), + cached_vram_mb: self.cache.total_mb(), + media_entries: self.media.entry_count(), + media_mb: self.media.total_mb(), + ..EvalStats::default() + } + } + pub fn bust_all_caches(&mut self) { self.cache.bust_all(); + self.output_cache.clear(); self.media.clear(); self.particles.clear(); self.sprite_cache.clear(); @@ -540,16 +628,58 @@ impl Engine { pub fn bust_gpu_cache(&mut self) { self.cache.bust_all(); + self.output_cache.clear(); } pub fn bust_frame(&mut self, frame: i64) -> usize { + self.output_cache.clear(); self.cache.bust_frame(frame) } pub fn bust_subtree(&mut self, node: NodeId) -> usize { + self.output_cache.clear(); self.cache.bust_subtree(node) } + fn output_cache_key(&self, comp: &Comp, target: NodeId, time: f64) -> u64 { + let mut h = DefaultHasher::new(); + self.cache.gpu_salt.hash(&mut h); + comp.name.hash(&mut h); + comp.path.hash(&mut h); + comp.nodes.len().hash(&mut h); + comp.revision.hash(&mut h); + target.hash(&mut h); + time.to_bits().hash(&mut h); + self.proxy_scale.hash(&mut h); + self.hiq.hash(&mut h); + self.use_proxy_clips.hash(&mut h); + h.finish() + } + + fn output_cache_get(&mut self, key: u64) -> Option<(CachedTexture, Vec)> { + if self.cache.mode == CacheMode::Bypass { + return None; + } + let pos = self.output_cache.iter().position(|(k, _, _)| *k == key)?; + let entry = self.output_cache.remove(pos)?; + let res = (entry.1.clone(), entry.2.clone()); + self.output_cache.push_back(entry); + Some(res) + } + + fn output_cache_insert(&mut self, key: u64, tex: CachedTexture, unsupported: Vec) { + if self.cache.mode == CacheMode::Bypass || self.cache.budget_bytes < 64 * 1024 * 1024 { + return; + } + if let Some(pos) = self.output_cache.iter().position(|(k, _, _)| *k == key) { + self.output_cache.remove(pos); + } + self.output_cache.push_back((key, tex, unsupported)); + while self.output_cache.len() > 8 { + self.output_cache.pop_front(); + } + } + /// Evaluates `target` node at `time` and returns its GPU texture + telemetry. pub fn evaluate( &mut self, @@ -558,6 +688,20 @@ impl Engine { time: f64, ) -> (CachedTexture, EvalStats) { let t0 = Instant::now(); + let out_key = self.output_cache_key(comp, target, time); + if let Some((tex, unsupported)) = self.output_cache_get(out_key) { + let stats = EvalStats { + eval_ms: t0.elapsed().as_secs_f64() * 1000.0, + cache_hits: 1, + cached_entries: self.cache.entry_count(), + cached_vram_mb: self.cache.total_mb(), + media_entries: self.media.entry_count(), + media_mb: self.media.total_mb(), + unsupported_nodes: unsupported, + ..EvalStats::default() + }; + return (tex, stats); + } let mut stats = EvalStats::default(); let mut visiting = HashSet::new(); self.frame_memo.clear(); @@ -582,6 +726,7 @@ impl Engine { } self.queue.submit(Some(encoder.finish())); + self.output_cache_insert(out_key, tex.clone(), stats.unsupported_nodes.clone()); stats.eval_ms = t0.elapsed().as_secs_f64() * 1000.0; stats.cached_entries = self.cache.entry_count(); stats.cached_vram_mb = self.cache.total_mb(); @@ -600,14 +745,23 @@ impl Engine { display: DisplaySettings, ) -> EvalStats { let t0 = Instant::now(); + let out_key = self.output_cache_key(comp, target, time); let mut stats = EvalStats::default(); - let mut visiting = HashSet::new(); - self.frame_memo.clear(); let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("comp-viewer-eval"), }); - let tex = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); + let tex = if let Some((cached, unsupported)) = self.output_cache_get(out_key) { + stats.cache_hits = 1; + stats.unsupported_nodes = unsupported; + cached + } else { + let mut visiting = HashSet::new(); + self.frame_memo.clear(); + let t = self.eval_node(comp, target, time, &mut encoder, &mut visiting, &mut stats); + self.output_cache_insert(out_key, t.clone(), stats.unsupported_nodes.clone()); + t + }; let dst_size = [dst_texture.width(), dst_texture.height()]; let dst_view = dst_texture.create_view(&wgpu::TextureViewDescriptor::default()); @@ -907,10 +1061,13 @@ impl Engine { "FilmGrain" => self.eval_film_grain(comp, node, time, frame_i, enc, visiting, stats), "Displace" => self.eval_displace(comp, node, time, frame_i, enc, visiting, stats), "Vortex" => self.eval_vortex(comp, node, time, frame_i, enc, visiting, stats), + "Fuse.Duplicate" => self.eval_duplicate(comp, node, time, frame_i, enc, visiting, stats), + "Fuse.KScope" => self.eval_kscope(comp, node, time, frame_i, enc, visiting, stats), "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats), "RectangleMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 1, enc, visiting, stats), "PolylineMask" => self.eval_polyline_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "BitmapMask" => self.eval_bitmap_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), + "WandMask" => self.eval_wand_mask(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "TextPlus" => self.eval_text_plus(comp, node, time, frame_i, comp_dims, enc, stats), "Fuse.Colorize" => self.eval_colorize(comp, node, time, frame_i, enc, visiting, stats), "Fuse.Outline" => self.eval_outline(comp, node, time, frame_i, enc, visiting, stats), diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index 3b8018bd3baf1d655be31b1c82f11311e0790462..afe59d79e86c4498a5f03f5cf382efba4bcd8c75 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -518,18 +518,61 @@ impl Engine { hash_floats.extend_from_slice(&lights.ambient); hash_floats.extend_from_slice(&lights.dir_to_light); hash_floats.extend_from_slice(&lights.dir_color); - for ms in mesh_specs { - let tex = ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)); + for pl in &lights.points { + hash_floats.extend_from_slice(&pl.pos); + hash_floats.extend_from_slice(&pl.color); + hash_floats.push(pl.decay_type); + hash_floats.push(pl.decay_rate); + } + for sl in &lights.spots { + hash_floats.extend_from_slice(&sl.pos); + hash_floats.extend_from_slice(&sl.dir); + hash_floats.extend_from_slice(&sl.color); + hash_floats.push(sl.cos_inner); + hash_floats.push(sl.cos_outer); + hash_floats.push(sl.decay_type); + } + + // First resolve all 2D textures & Text3D plates & Displace3D heightmaps + let mut pending_displace_tex: Vec> = Vec::with_capacity(mesh_specs.len()); + for ms in &mesh_specs { + let tex = if let Some(t3d) = &ms.text3d { + let tnode = comp.node(t3d.node_id); + Some(self.eval_text_plus(comp, tnode, time, frame_i, [1024, 512], enc, stats)) + } else { + ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats)) + }; + let disp_entry = ms.displace.as_ref().map(|ds| { + let dtex = self.eval_node(comp, ds.input_node, time, enc, visiting, stats); + (dtex, ds.scale, ds.bias, ds.channel) + }); upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash)); + upstream_hashes.push(disp_entry.as_ref().map_or(0, |(t, _, _, _)| t.content_hash)); hash_floats.extend_from_slice(&ms.world); hash_floats.extend_from_slice(&ms.diffuse_col); + hash_floats.extend_from_slice(&ms.specular_col); + hash_floats.push(ms.specular_intensity); + hash_floats.push(ms.specular_exponent); + hash_floats.push(if ms.affected_by_lights { 1.0 } else { 0.0 }); + hash_floats.push(if ms.flip_normals { 1.0 } else { 0.0 }); + if let Some((_, sc, bi, ch)) = disp_entry { + hash_floats.push(sc); + hash_floats.push(bi); + hash_floats.push(ch as f32); + } draw_meshes.push(crate::scene3d::DrawMesh { world: ms.world, - shape: ms.shape, + shape: ms.shape.clone(), tex, diffuse_col: ms.diffuse_col, - roughness: ms.roughness, + specular_col: ms.specular_col, + specular_intensity: ms.specular_intensity, + specular_exponent: ms.specular_exponent, + affected_by_lights: ms.affected_by_lights, + flip_normals: ms.flip_normals, + displace: None, }); + pending_displace_tex.push(disp_entry); } let key = self.make_key(node, "Renderer3D", size, &upstream_hashes, &hash_floats); @@ -540,6 +583,30 @@ impl Engine { stats.cache_misses += 1; stats.nodes_evaluated += 1; + // If any Displace3D heightmaps are present, flush pending encoder commands so CPU readback sees fresh pixels. + if pending_displace_tex.iter().any(|d| d.is_some()) { + let flush_enc = std::mem::replace( + enc, + self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("comp-eval-post-disp3d"), + }), + ); + self.queue.submit(Some(flush_enc.finish())); + for (dm, entry) in draw_meshes.iter_mut().zip(pending_displace_tex.into_iter()) { + if let Some((dtex, scale, bias, channel)) = entry { + if let Ok(rgba) = self.readback_rgba(&dtex) { + dm.displace = Some(crate::scene3d::DisplaceHeightmap { + size: dtex.size, + rgba, + scale, + bias, + channel, + }); + } + } + } + } + let dst = create_texture(&self.device, size, key); self.scene3d.render_meshes( &self.device, diff --git a/crates/engine/src/eval/transform.rs b/crates/engine/src/eval/transform.rs index 4f4cf041d00b0d0e3d9dcd14ed8fbe5a77a5c1a2..0911793d19efef9dfb920a422dbb3888c53cd7b6 100644 --- a/crates/engine/src/eval/transform.rs +++ b/crates/engine/src/eval/transform.rs @@ -423,4 +423,195 @@ impl Engine { dst } + pub(super) fn eval_duplicate( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node + .connected_node("Background") + .or_else(|| node.connected_node("Input")) + .and_then(|s| comp.find_node(s)) + else { + return self.dummy.clone(); + }; + let base = self.eval_node(comp, src_id, time, enc, visiting, stats); + let copies = comp.eval_number(node, "Copies", time, 2.0, &self.expr).round().clamp(1.0, 64.0) as i32; + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if copies <= 1 || blend <= 1e-6 { + return base; + } + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + // Fusion Fuse.Duplicate uses `Size` (or `XSize` when LockSize=0); default 1.0 + let size_s = comp.eval_number(node, "XSize", time, comp.eval_number(node, "Size", time, 1.0, &self.expr), &self.expr) as f32; + let angle_deg = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32; + let gain = comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32; + let time_off = comp.eval_number(node, "TimeOffset", time, 0.0, &self.expr); + let merge_under = comp.eval_number(node, "MergeUnder", time, 0.0, &self.expr) > 0.5; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(base.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let params = [ + copies as f32, + center[0] as f32, + center[1] as f32, + size_s, + angle_deg, + gain, + blend, + time_off as f32, + if merge_under { 1.0 } else { 0.0 }, + ]; + let key = self.make_key(node, "Duplicate", base.size, &[base.content_hash, mask_hash], ¶ms); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + + let dx = center[0] as f32 - 0.5; + let dy = center[1] as f32 - 0.5; + let mut accum = base.clone(); + for i in 1..copies { + let fi = i as f32; + let copy_src = if time_off.abs() > 1e-4 { + self.eval_node(comp, src_id, time + (i as f64) * time_off, enc, visiting, stats) + } else { + base.clone() + }; + let cx = 0.5 + dx * fi; + let cy = 0.5 + dy * fi; + let sc = size_s.powi(i).max(1e-4); + let ang = (angle_deg * fi).to_radians(); + let g_i = gain.powi(i); + let is_last = i == copies - 1; + let next = self.alloc_tex_like(&base, base.depth, if is_last { key } else { 0 }); + let mut u = UniformParams::default(); + u.p[0] = [cx, cy, sc, ang]; + u.p[1] = [blend, g_i, 0.0, 0.0]; + u.p[2] = [0.0, 0.0, 0.0, if merge_under { 1.0 } else { 0.0 }]; + u.p[3] = [ + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + copy_src.canvas_size[0] as f32, + copy_src.canvas_size[1] as f32, + ]; + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::Merge, &accum.view, ©_src.view, mv, &next, &u); + accum = next; + } + + self.cache.insert(key, accum.clone(), node.id, frame_i); + accum + } + + pub(super) fn eval_kscope( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else { + return self.dummy.clone(); + }; + let src = self.eval_node(comp, src_id, time, enc, visiting, stats); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return src; + } + let src = self.crop_to_canvas(enc, src); + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let slices = comp.eval_number(node, "Slices", time, 6.0, &self.expr).max(1.0) as f32; + let angle = (comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32).to_radians(); + let cap_angle = (comp.eval_number(node, "CaptureAngle", time, 0.0, &self.expr) as f32).to_radians(); + let scale = comp.eval_number(node, "Scale", time, 1.0, &self.expr).max(1e-4) as f32; + let edges = comp.eval_number(node, "Edges", time, 3.0, &self.expr) as f32; + let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats); + let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); + + let mut u = UniformParams::default(); + u.p[0] = [center[0] as f32, center[1] as f32, slices, angle]; + u.p[1] = [cap_angle, scale, edges, blend]; + u.p[2] = [if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0]; + + let key = self.make_key(node, "KScope", src.size, &[src.content_hash, mask_hash], bytemuck::cast_slice(&u.p[..3])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = self.alloc_tex_like(&src, src.depth, key); + let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + self.dispatch_op(enc, ShaderOp::KScope, &src.view, &self.dummy.view, mv, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Engine; + + #[test] + fn test_fuse_kscope_6_slice_symmetry() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 1.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 0.0, }, + TopRightGreen = Input { Value = 0.0, }, + TopRightBlue = Input { Value = 1.0, }, + }, + }, + KS1 = Fuse.KScope { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + Slices = Input { Value = 6, }, + Scale = Input { Value = 1.0, }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse KScope comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let node_id = comp.find_node("KS1").expect("KS1"); + let (tex, _) = eng.evaluate(&comp, node_id, 0.0); + let rgba = eng.readback_rgba(&tex).expect("readback KScope"); + let [w, h] = tex.size; + assert_eq!((w, h), (128, 128)); + // With Slices=6, sector=60 deg mirrored every 120 deg -> reflection across X axis is exact! + let px = |x: usize, y: usize| -> [u8; 4] { + let i = (y * 128 + x) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + let a = px(64 + 28, 64 + 12); + let b = px(64 + 28, 63 - 12); + for c in 0..3 { + let diff = (a[c] as i32 - b[c] as i32).abs(); + assert!(diff <= 2, "KScope 6-slice mirror symmetry mismatch ch={c}: {a:?} vs {b:?}"); + } + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b28f2d705776fa9298e66ed26d8e4bbf42322040..7ce9331f7fe4cf8d5abd24ef6100c44066ccb71c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -6,9 +6,13 @@ pub mod export; pub mod media; pub mod optflow; pub mod particles; +pub mod ram_cache; pub mod scene3d; pub use audio::{AudioPlayer, AudioTrack}; -pub use cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; +pub use cache::{CacheMode, CachedTexture, DEFAULT_VRAM_BUDGET_MB, EvalStats, NodeCache}; pub use eval::{DisplaySettings, Engine, create_texture}; pub use export::{ExportOptions, ExportProgress, ExportSummary, export_saver_png_sequence, select_saver}; +pub use ram_cache::{ + DEFAULT_RAM_CACHE_MB, PrefetchJob, RamFrame, RamFrameCache, RamFrameKey, RamPrefetcher, +}; diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index a420462195d0a1d88a51fece5588efe4f4ddd56d..8c1ae0ca76a1fb44a404d235c560ec94a6f301b7 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -460,6 +460,19 @@ impl MediaCache { self.total_bytes = 0; } + pub fn set_budget_mb(&mut self, budget_mb: u64) { + self.budget_bytes = budget_mb.saturating_mul(1024 * 1024); + while self.total_bytes > self.budget_bytes && self.images.len() > 1 { + let Some((oldest_key, _)) = self.lru.iter().min_by_key(|(_, t)| **t).map(|(k, t)| (k.clone(), *t)) else { + break; + }; + self.lru.remove(&oldest_key); + if let Some(removed) = self.images.remove(&oldest_key) { + self.total_bytes = self.total_bytes.saturating_sub(removed.byte_size()); + } + } + } + pub fn entry_count(&self) -> usize { self.images.len() } diff --git a/crates/engine/src/ram_cache.rs b/crates/engine/src/ram_cache.rs new file mode 100644 index 0000000000000000000000000000000000000000..1231a3789a644629063371d48a054a1eded7b852 --- /dev/null +++ b/crates/engine/src/ram_cache.rs @@ -0,0 +1,566 @@ +//! Thread-safe LRU RAM frame cache and cancellable background lookahead pre-fetcher. +//! +//! Designed for real-time 24fps+ playback and instant scrubbing: +//! - `RamFrameCache` stores finished premultiplied RGBA8 frames keyed by +//! `(NodeId, comp.revision, frame, proxy_scale, hiq, use_proxy_clips)` under a hard byte cap. +//! - `cached_frame_ranges` reports contiguous `[start, end]` cached intervals for timeline display. +//! - `RamPrefetcher` runs lookahead evaluation on a background thread with an atomic generation +//! counter so scrubbing or editing cancels stale pre-fetch work immediately. + +use crate::eval::Engine; +use model::{Comp, NodeId}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread::{self, JoinHandle}; + +/// Default RAM frame cache ceiling (1 GiB ≈ 130 full-res 1080p frames or ~520 half-res frames). +pub const DEFAULT_RAM_CACHE_MB: u64 = 1024; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct RamFrameKey { + pub target: NodeId, + pub revision: u64, + pub frame: i64, + pub proxy_scale: u32, + pub hiq: bool, + pub use_proxy_clips: bool, +} + +#[derive(Clone, Debug)] +pub struct RamFrame { + pub size: [u32; 2], + /// Premultiplied RGBA8 pixels, top-down (`size[0] * size[1] * 4` bytes). + pub rgba: Arc>, + pub eval_ms: f64, +} + +impl RamFrame { + pub fn byte_size(&self) -> u64 { + self.rgba.len() as u64 + } +} + +struct RamEntry { + frame: RamFrame, + last_used: u64, +} + +struct RamCacheInner { + budget_bytes: u64, + entries: HashMap, + total_bytes: u64, + tick: u64, + evictions: u64, +} + +impl RamCacheInner { + fn evict_over_budget(&mut self) { + while self.total_bytes > self.budget_bytes && !self.entries.is_empty() { + let Some((&oldest_key, _)) = self.entries.iter().min_by_key(|(_, e)| e.last_used) else { + break; + }; + if let Some(removed) = self.entries.remove(&oldest_key) { + self.total_bytes = self.total_bytes.saturating_sub(removed.frame.byte_size()); + self.evictions += 1; + } + } + } +} + +/// Shareable, thread-safe LRU RAM frame cache. +#[derive(Clone)] +pub struct RamFrameCache { + inner: Arc>, +} + +impl Default for RamFrameCache { + fn default() -> Self { + Self::new(DEFAULT_RAM_CACHE_MB) + } +} + +impl RamFrameCache { + pub fn new(budget_mb: u64) -> Self { + Self { + inner: Arc::new(Mutex::new(RamCacheInner { + budget_bytes: budget_mb.saturating_mul(1024 * 1024), + entries: HashMap::new(), + total_bytes: 0, + tick: 0, + evictions: 0, + })), + } + } + + pub fn set_budget_mb(&self, budget_mb: u64) { + if let Ok(mut guard) = self.inner.lock() { + guard.budget_bytes = budget_mb.saturating_mul(1024 * 1024); + guard.evict_over_budget(); + } + } + + pub fn budget_mb(&self) -> u64 { + self.inner + .lock() + .map(|g| g.budget_bytes / (1024 * 1024)) + .unwrap_or(0) + } + + pub fn get(&self, key: RamFrameKey) -> Option { + let mut guard = self.inner.lock().ok()?; + guard.tick += 1; + let tick = guard.tick; + let entry = guard.entries.get_mut(&key)?; + entry.last_used = tick; + Some(entry.frame.clone()) + } + + pub fn contains(&self, key: RamFrameKey) -> bool { + self.inner + .lock() + .map(|g| g.entries.contains_key(&key)) + .unwrap_or(false) + } + + pub fn insert(&self, key: RamFrameKey, frame: RamFrame) { + let Ok(mut guard) = self.inner.lock() else { + return; + }; + let bytes = frame.byte_size(); + if guard.budget_bytes == 0 || bytes > guard.budget_bytes { + return; + } + guard.tick += 1; + let tick = guard.tick; + if let Some(old) = guard.entries.remove(&key) { + guard.total_bytes = guard.total_bytes.saturating_sub(old.frame.byte_size()); + } + guard.total_bytes += bytes; + guard.entries.insert(key, RamEntry { frame, last_used: tick }); + guard.evict_over_budget(); + } + + pub fn clear(&self) { + if let Ok(mut guard) = self.inner.lock() { + guard.entries.clear(); + guard.total_bytes = 0; + } + } + + /// Evicts cached frames belonging to older composition revisions. + pub fn invalidate_other_revisions(&self, keep_revision: u64) -> usize { + let Ok(mut guard) = self.inner.lock() else { + return 0; + }; + let stale: Vec = guard + .entries + .keys() + .copied() + .filter(|k| k.revision != keep_revision) + .collect(); + let count = stale.len(); + for k in stale { + if let Some(removed) = guard.entries.remove(&k) { + guard.total_bytes = guard.total_bytes.saturating_sub(removed.frame.byte_size()); + } + } + count + } + + /// Returns sorted, merged inclusive `[start, end]` frame ranges currently cached + /// for the specified target node, revision, and quality settings. + pub fn cached_frame_ranges( + &self, + target: NodeId, + revision: u64, + proxy_scale: u32, + hiq: bool, + use_proxy_clips: bool, + ) -> Vec<(i64, i64)> { + let Ok(guard) = self.inner.lock() else { + return Vec::new(); + }; + let mut frames: Vec = guard + .entries + .keys() + .filter(|k| { + k.target == target + && k.revision == revision + && k.proxy_scale == proxy_scale + && k.hiq == hiq + && k.use_proxy_clips == use_proxy_clips + }) + .map(|k| k.frame) + .collect(); + if frames.is_empty() { + return Vec::new(); + } + frames.sort_unstable(); + frames.dedup(); + let mut ranges = Vec::new(); + let mut start = frames[0]; + let mut prev = frames[0]; + for &f in &frames[1..] { + if f == prev + 1 { + prev = f; + } else { + ranges.push((start, prev)); + start = f; + prev = f; + } + } + ranges.push((start, prev)); + ranges + } + + pub fn entry_count(&self) -> usize { + self.inner.lock().map(|g| g.entries.len()).unwrap_or(0) + } + + pub fn total_bytes(&self) -> u64 { + self.inner.lock().map(|g| g.total_bytes).unwrap_or(0) + } + + pub fn total_mb(&self) -> f64 { + self.total_bytes() as f64 / (1024.0 * 1024.0) + } + + pub fn eviction_count(&self) -> u64 { + self.inner.lock().map(|g| g.evictions).unwrap_or(0) + } +} + +/// Parameters for a background lookahead pre-fetch window. +#[derive(Clone)] +pub struct PrefetchJob { + pub comp: Comp, + pub target: NodeId, + pub center_frame: i64, + pub range: [i64; 2], + pub lookahead: i64, + pub proxy_scale: u32, + pub hiq: bool, + pub use_proxy_clips: bool, +} + +struct WorkerSlot { + job: Option<(u64, PrefetchJob)>, + shutdown: bool, +} + +/// Background lookahead frame pre-fetcher backed by a dedicated headless `Engine`. +/// +/// Calling `request_lookahead` or `cancel` immediately increments an atomic generation +/// counter so any in-flight lookahead loop aborts before evaluating another frame. +pub struct RamPrefetcher { + cache: RamFrameCache, + vram_budget_mb: u64, + generation: Arc, + busy: Arc, + completed_frames: Arc, + slot: Arc<(Mutex, Condvar)>, + worker: Option>, +} + +impl RamPrefetcher { + pub fn new(cache: RamFrameCache, worker_vram_budget_mb: u64) -> Self { + Self { + cache, + vram_budget_mb: worker_vram_budget_mb.max(128), + generation: Arc::new(AtomicU64::new(1)), + busy: Arc::new(AtomicBool::new(false)), + completed_frames: Arc::new(AtomicU64::new(0)), + slot: Arc::new(( + Mutex::new(WorkerSlot { + job: None, + shutdown: false, + }), + Condvar::new(), + )), + worker: None, + } + } + + pub fn cache(&self) -> &RamFrameCache { + &self.cache + } + + pub fn is_busy(&self) -> bool { + self.busy.load(Ordering::Acquire) + } + + pub fn completed_frames(&self) -> u64 { + self.completed_frames.load(Ordering::Acquire) + } + + /// Cancels any active lookahead pass immediately. + pub fn cancel(&self) { + self.generation.fetch_add(1, Ordering::AcqRel); + if let Ok(mut guard) = self.slot.0.lock() { + guard.job = None; + } + } + + /// Schedules background lookahead rendering starting at `job.center_frame + 1` + /// through `min(job.range[1], job.center_frame + job.lookahead)`, wrapping or + /// skipping frames that are already cached. Cancels any superseded request. + pub fn request_lookahead(&mut self, job: PrefetchJob) { + self.ensure_worker(); + let job_gen = self.generation.fetch_add(1, Ordering::AcqRel) + 1; + if let Ok(mut guard) = self.slot.0.lock() { + guard.job = Some((job_gen, job)); + self.slot.1.notify_one(); + } + } + + fn ensure_worker(&mut self) { + if self.worker.is_some() { + return; + } + let cache = self.cache.clone(); + let vram_mb = self.vram_budget_mb; + let generation = self.generation.clone(); + let busy = self.busy.clone(); + let completed = self.completed_frames.clone(); + let slot = self.slot.clone(); + + let handle = thread::Builder::new() + .name("fission-ram-prefetch".to_owned()) + .spawn(move || { + let mut engine_opt: Option = None; + let mut last_comp_rev: Option = None; + + loop { + let (job_gen, job) = { + let Ok(mut guard) = slot.0.lock() else { + break; + }; + while !guard.shutdown && guard.job.is_none() { + guard = match slot.1.wait(guard) { + Ok(g) => g, + Err(_) => return, + }; + } + if guard.shutdown { + break; + } + match guard.job.take() { + Some(item) => item, + None => continue, + } + }; + + if generation.load(Ordering::Acquire) != job_gen { + continue; + } + + if engine_opt.is_none() { + match Engine::new_headless() { + Ok(mut eng) => { + eng.set_vram_budget_mb(vram_mb); + engine_opt = Some(eng); + } + Err(_) => { + // Headless GPU unavailable; stay idle until shutdown. + continue; + } + } + } + + let Some(engine) = engine_opt.as_mut() else { + continue; + }; + + if last_comp_rev != Some(job.comp.revision) { + engine.bust_gpu_cache(); + last_comp_rev = Some(job.comp.revision); + } + engine.proxy_scale = job.proxy_scale.max(1); + engine.hiq = job.hiq; + engine.use_proxy_clips = job.use_proxy_clips; + + busy.store(true, Ordering::Release); + let start = job.range[0].min(job.range[1]); + let end = job.range[0].max(job.range[1]); + let count = job.lookahead.max(0); + + for offset in 1..=count { + if generation.load(Ordering::Acquire) != job_gen { + break; + } + let f = job.center_frame + offset; + if f < start || f > end { + break; + } + let key = RamFrameKey { + target: job.target, + revision: job.comp.revision, + frame: f, + proxy_scale: engine.proxy_scale, + hiq: engine.hiq, + use_proxy_clips: engine.use_proxy_clips, + }; + if cache.contains(key) { + continue; + } + let (tex, stats) = engine.evaluate(&job.comp, job.target, f as f64); + if generation.load(Ordering::Acquire) != job_gen { + break; + } + if let Ok(rgba) = engine.readback_rgba(&tex) { + cache.insert( + key, + RamFrame { + size: tex.size, + rgba: Arc::new(rgba), + eval_ms: stats.eval_ms, + }, + ); + completed.fetch_add(1, Ordering::AcqRel); + } + } + busy.store(false, Ordering::Release); + } + }) + .ok(); + + self.worker = handle; + } +} + +impl Drop for RamPrefetcher { + fn drop(&mut self) { + self.generation.fetch_add(1, Ordering::AcqRel); + if let Ok(mut guard) = self.slot.0.lock() { + guard.shutdown = true; + guard.job = None; + self.slot.1.notify_all(); + } + if let Some(handle) = self.worker.take() { + let _ = handle.join(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + fn dummy_frame(w: u32, h: u32) -> RamFrame { + RamFrame { + size: [w, h], + rgba: Arc::new(vec![128u8; (w * h * 4) as usize]), + eval_ms: 1.5, + } + } + + #[test] + fn ram_cache_enforces_budget_lru_and_merges_ranges() { + // 4 MB budget -> holds at most 4 frames of 1 MB each (512x512 RGBA8 = 1 MB) + let cache = RamFrameCache::new(4); + let node = NodeId(0); + for f in [10, 11, 12, 14] { + cache.insert( + RamFrameKey { + target: node, + revision: 1, + frame: f, + proxy_scale: 1, + hiq: true, + use_proxy_clips: false, + }, + dummy_frame(512, 512), + ); + } + assert_eq!(cache.entry_count(), 4); + assert_eq!( + cache.cached_frame_ranges(node, 1, 1, true, false), + vec![(10, 12), (14, 14)] + ); + + // Touch frame 10 so frame 11 becomes LRU, then insert frame 15. + assert!(cache + .get(RamFrameKey { + target: node, + revision: 1, + frame: 10, + proxy_scale: 1, + hiq: true, + use_proxy_clips: false, + }) + .is_some()); + cache.insert( + RamFrameKey { + target: node, + revision: 1, + frame: 15, + proxy_scale: 1, + hiq: true, + use_proxy_clips: false, + }, + dummy_frame(512, 512), + ); + assert_eq!(cache.entry_count(), 4); + assert!(cache.eviction_count() >= 1); + assert_eq!( + cache.cached_frame_ranges(node, 1, 1, true, false), + vec![(10, 10), (12, 12), (14, 15)] + ); + + // Revision invalidation drops old revisions cleanly + let evicted = cache.invalidate_other_revisions(2); + assert_eq!(evicted, 4); + assert_eq!(cache.entry_count(), 0); + } + + #[test] + fn ram_prefetcher_renders_lookahead_and_cancels_cleanly() { + let comp_src = r#" +Composition { + CurrentTime = 0, + RenderRange = { 0, 10 }, + GlobalRange = { 0, 10 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + TopLeftRed = Input { Value = 0.5, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + }, +} +"#; + let comp = Comp::from_fusion_str(comp_src).expect("parse comp"); + let target = comp.find_node("BG1").expect("BG1"); + + let cache = RamFrameCache::new(64); + let mut prefetcher = RamPrefetcher::new(cache.clone(), 128); + prefetcher.request_lookahead(PrefetchJob { + comp: comp.clone(), + target, + center_frame: 0, + range: [0, 10], + lookahead: 4, + proxy_scale: 1, + hiq: true, + use_proxy_clips: false, + }); + + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + if cache.cached_frame_ranges(target, comp.revision, 1, true, false) == vec![(1, 4)] { + break; + } + thread::sleep(Duration::from_millis(20)); + } + assert_eq!( + cache.cached_frame_ranges(target, comp.revision, 1, true, false), + vec![(1, 4)] + ); + prefetcher.cancel(); + } +} diff --git a/crates/engine/src/scene3d.rs b/crates/engine/src/scene3d.rs index d3a7101a011001f937aa0deb188f1eef5f2ec26f..5a5b822e82f866338270a625683e456419a20f9e 100644 --- a/crates/engine/src/scene3d.rs +++ b/crates/engine/src/scene3d.rs @@ -27,10 +27,12 @@ struct MeshUniform { model: [f32; 16], /// DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture) dod: [f32; 4], - /// `[use_tex, lighting_enabled, roughness, 0]` + /// `[use_tex, lighting_enabled, specular_intensity, flip_normals]` flags: [f32; 4], /// Diffuse color multiplier `(r, g, b, a)` diffuse_col: [f32; 4], + /// Specular color `(r, g, b, shininess_exponent)` + specular_col: [f32; 4], /// Ambient light `(r, g, b, 0)` ambient: [f32; 4], /// Directional light direction TO light `(dx, dy, dz, has_dir)` @@ -39,6 +41,18 @@ struct MeshUniform { dir_color: [f32; 4], /// Camera world position `(cx, cy, cz, 0)` cam_pos: [f32; 4], + /// `[num_point_lights, num_spot_lights, 0, 0]` + light_counts: [f32; 4], + /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` + point_pos: [[f32; 4]; 4], + /// Point light colors * intensity `(r, g, b, decay_rate)` + point_col: [[f32; 4]; 4], + /// Spot light positions `(x, y, z, cos_inner)` + spot_pos: [[f32; 4]; 4], + /// Spot light forward directions `(dx, dy, dz, cos_outer)` + spot_dir: [[f32; 4]; 4], + /// Spot light colors * intensity `(r, g, b, decay_type)` + spot_col: [[f32; 4]; 4], } const SHADER_3D: &str = r#" @@ -48,10 +62,17 @@ struct MeshUniform { dod: vec4, flags: vec4, diffuse_col: vec4, + specular_col: vec4, ambient: vec4, dir_to_light: vec4, dir_color: vec4, cam_pos: vec4, + light_counts: vec4, + point_pos: array, 4>, + point_col: array, 4>, + spot_pos: array, 4>, + spot_dir: array, 4>, + spot_col: array, 4>, }; @group(0) @binding(0) var u: MeshUniform; @@ -80,7 +101,46 @@ fn vs_mesh(v: VsIn) -> VsOut { out.world_pos = wp.xyz; let wn = (u.model * vec4(v.normal, 0.0)).xyz; let nlen = length(wn); - out.world_n = select(vec3(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); + var n_norm = select(vec3(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); + if (u.flags.w > 0.5) { + n_norm = -n_norm; + } + out.world_n = n_norm; + return out; +} + +fn light_attenuation(dist: f32, decay_type: f32, decay_rate: f32) -> f32 { + let dt = i32(decay_type + 0.5); + let rate = max(decay_rate, 0.001); + if (dt == 1) { + return 1.0 / max(1.0 + dist * rate, 1e-4); + } else if (dt == 2) { + let d = dist * rate; + return 1.0 / max(1.0 + d * d, 1e-4); + } + return 1.0; +} + +fn eval_light_contrib( + n: vec3, + v: vec3, + l: vec3, + light_rgb: vec3, + albedo: vec3, + spec_rgb: vec3, + spec_int: f32, + shininess: f32, +) -> vec3 { + let ndotl = max(dot(n, l), 0.0); + if (ndotl <= 0.0) { + return vec3(0.0); + } + var out = albedo * light_rgb * ndotl; + if (spec_int > 1e-4) { + let h = normalize(l + v); + let spec = pow(max(dot(n, h), 0.0), shininess) * spec_int; + out = out + light_rgb * spec_rgb * spec; + } return out; } @@ -107,20 +167,43 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { // Premultiplied -> unpremultiplied albedo for lighting let albedo = select(vec3(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5); let n = normalize(in.world_n); + let v = normalize(u.cam_pos.xyz - in.world_pos); + let spec_rgb = u.specular_col.rgb; + let shininess = max(u.specular_col.w, 1.0); + let spec_int = u.flags.z; + var lit = albedo * u.ambient.rgb; if (u.dir_to_light.w > 0.5) { let l = normalize(u.dir_to_light.xyz); - let ndotl = max(dot(n, l), 0.0); - lit = lit + albedo * u.dir_color.rgb * ndotl; - if (ndotl > 0.0) { - let v = normalize(u.cam_pos.xyz - in.world_pos); - let h = normalize(l + v); - let rough = clamp(u.flags.z, 0.05, 1.0); - let shininess = max(2.0 / (rough * rough) - 2.0, 2.0); - let spec = pow(max(dot(n, h), 0.0), shininess) * (1.0 - rough * 0.85) * 0.25; - lit = lit + u.dir_color.rgb * spec; + lit = lit + eval_light_contrib(n, v, l, u.dir_color.rgb, albedo, spec_rgb, spec_int, shininess); + } + + let n_pt = i32(u.light_counts.x + 0.5); + for (var i: i32 = 0; i < 4; i = i + 1) { + if (i >= n_pt) { break; } + let to_l = u.point_pos[i].xyz - in.world_pos; + let dist = max(length(to_l), 1e-4); + let att = light_attenuation(dist, u.point_pos[i].w, u.point_col[i].w); + lit = lit + eval_light_contrib(n, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); + } + + let n_sp = i32(u.light_counts.y + 0.5); + for (var i: i32 = 0; i < 4; i = i + 1) { + if (i >= n_sp) { break; } + let to_l = u.spot_pos[i].xyz - in.world_pos; + let dist = max(length(to_l), 1e-4); + let l_dir = to_l / dist; + // spot_dir.xyz is direction spotlight points; fragment direction from light is -l_dir + let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz)); + let cos_inner = u.spot_pos[i].w; + let cos_outer = u.spot_dir[i].w; + let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); + if (cone > 0.0) { + let att = light_attenuation(dist, u.spot_col[i].w, 1.0) * cone; + lit = lit + eval_light_contrib(n, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess); } } + col = vec4(clamp(lit, vec3(0.0), vec3(1.0)) * col.a, col.a); } return col; @@ -146,8 +229,31 @@ pub enum ShapeKind { ImagePlane, Sphere { radius: f32, sub_base: u32, sub_height: u32 }, Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 }, - Plane { width: f32, height: f32 }, + Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, Cube { width: f32, height: f32, depth: f32 }, + TextPlate { width: f32, height: f32, depth: f32, slices: u32 }, +} + +#[derive(Clone, Debug)] +pub struct Displace3DSpec { + pub input_node: NodeId, + pub scale: f32, + pub bias: f32, + pub channel: i32, // 0=R, 1=G, 2=B, 3=A, 4=Luma (default) +} + +#[derive(Clone, Debug)] +pub struct DisplaceHeightmap { + pub size: [u32; 2], + pub rgba: Vec, + pub scale: f32, + pub bias: f32, + pub channel: i32, +} + +#[derive(Clone, Debug)] +pub struct Text3DSpec { + pub node_id: NodeId, } #[derive(Clone)] @@ -155,16 +261,42 @@ pub struct MeshInstance { pub world: Mat4, pub shape: ShapeKind, pub material_node: Option, + pub text3d: Option, pub diffuse_col: [f32; 4], - pub roughness: f32, + pub specular_col: [f32; 3], + pub specular_intensity: f32, + pub specular_exponent: f32, + pub affected_by_lights: bool, + pub flip_normals: bool, + pub displace: Option, } #[derive(Clone, Copy, Debug)] +pub struct PointLight { + pub pos: [f32; 3], + pub color: [f32; 3], + pub decay_type: f32, + pub decay_rate: f32, +} + +#[derive(Clone, Copy, Debug)] +pub struct SpotLight { + pub pos: [f32; 3], + pub dir: [f32; 3], + pub color: [f32; 3], + pub cos_inner: f32, + pub cos_outer: f32, + pub decay_type: f32, +} + +#[derive(Clone, Debug)] pub struct SceneLights { pub ambient: [f32; 3], pub dir_to_light: [f32; 3], pub dir_color: [f32; 3], pub has_dir: bool, + pub points: Vec, + pub spots: Vec, } impl Default for SceneLights { @@ -174,6 +306,8 @@ impl Default for SceneLights { dir_to_light: [0.0, 0.0, 1.0], dir_color: [0.0, 0.0, 0.0], has_dir: false, + points: Vec::new(), + spots: Vec::new(), } } } @@ -183,7 +317,12 @@ pub struct DrawMesh { pub shape: ShapeKind, pub tex: Option, pub diffuse_col: [f32; 4], - pub roughness: f32, + pub specular_col: [f32; 3], + pub specular_intensity: f32, + pub specular_exponent: f32, + pub affected_by_lights: bool, + pub flip_normals: bool, + pub displace: Option, } impl Scene3DRenderer { @@ -343,10 +482,13 @@ impl Scene3DRenderer { .as_ref() .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) .unwrap_or(16.0 / 9.0); - let (verts, indices) = build_shape_mesh(&m.shape, aspect); + let (mut verts, indices) = build_shape_mesh(&m.shape, aspect); if indices.is_empty() { continue; } + if let Some(disp) = &m.displace { + apply_heightmap_displace(&mut verts, &indices, disp); + } let vbytes = bytemuck::cast_slice(&verts); let ibytes = bytemuck::cast_slice(&indices); let vbuf = device.create_buffer(&wgpu::BufferDescriptor { @@ -374,17 +516,39 @@ impl Scene3DRenderer { } else { [0.0; 4] }; + let mut point_pos = [[0.0_f32; 4]; 4]; + let mut point_col = [[0.0_f32; 4]; 4]; + let n_pt = lights.points.len().min(4); + for (pi, pl) in lights.points.iter().take(4).enumerate() { + point_pos[pi] = [pl.pos[0], pl.pos[1], pl.pos[2], pl.decay_type]; + point_col[pi] = [pl.color[0], pl.color[1], pl.color[2], pl.decay_rate]; + } + let mut spot_pos = [[0.0_f32; 4]; 4]; + let mut spot_dir = [[0.0_f32; 4]; 4]; + let mut spot_col = [[0.0_f32; 4]; 4]; + let n_sp = lights.spots.len().min(4); + for (si, sl) in lights.spots.iter().take(4).enumerate() { + spot_pos[si] = [sl.pos[0], sl.pos[1], sl.pos[2], sl.cos_inner]; + spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer]; + spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type]; + } let uni = MeshUniform { mvp, model: m.world, dod, flags: [ if m.tex.is_some() { 1.0 } else { 0.0 }, - if lighting_enabled { 1.0 } else { 0.0 }, - m.roughness, - 0.0, + if lighting_enabled && m.affected_by_lights { 1.0 } else { 0.0 }, + m.specular_intensity, + if m.flip_normals { 1.0 } else { 0.0 }, ], diffuse_col: m.diffuse_col, + specular_col: [ + m.specular_col[0], + m.specular_col[1], + m.specular_col[2], + m.specular_exponent, + ], ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0], dir_to_light: [ lights.dir_to_light[0], @@ -394,6 +558,12 @@ impl Scene3DRenderer { ], dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0], cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], + light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0], + point_pos, + point_col, + spot_pos, + spot_dir, + spot_col, }; let ubuf = device.create_buffer(&wgpu::BufferDescriptor { label: Some("scene3d-u"), @@ -466,16 +636,53 @@ fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec, Vec { + ShapeKind::Plane { width, height, sub_w, sub_h } => { + let sw = sub_w.clamp(1, 64); + let sh = sub_h.clamp(1, 64); let hx = width * 0.5; let hy = height * 0.5; - let verts = vec![ - Vertex3D { pos: [-hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 0.0] }, - Vertex3D { pos: [-hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [0.0, 1.0] }, - Vertex3D { pos: [ hx, -hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 1.0] }, - Vertex3D { pos: [ hx, hy, 0.0], normal: [0.0, 0.0, 1.0], uv: [1.0, 0.0] }, - ]; - (verts, vec![0, 1, 2, 0, 2, 3]) + let mut verts = Vec::with_capacity(((sw + 1) * (sh + 1)) as usize); + let mut idx = Vec::with_capacity((sw * sh * 6) as usize); + for iy in 0..=sh { + let v = iy as f32 / sh as f32; + let y = hy - v * height; + for ix in 0..=sw { + let u = ix as f32 / sw as f32; + let x = -hx + u * width; + verts.push(Vertex3D { pos: [x, y, 0.0], normal: [0.0, 0.0, 1.0], uv: [u, v] }); + } + } + let row = sw + 1; + for iy in 0..sh { + for ix in 0..sw { + let a = iy * row + ix; + let b = (iy + 1) * row + ix; + let c = (iy + 1) * row + ix + 1; + let d = iy * row + ix + 1; + idx.extend_from_slice(&[a, b, c, a, c, d]); + } + } + (verts, idx) + } + ShapeKind::TextPlate { width, height, depth, slices } => { + let hx = width * 0.5; + let hy = height * 0.5; + let n_slices = if depth.abs() > 1e-4 { slices.clamp(2, 16) } else { 1 }; + let mut verts = Vec::with_capacity((n_slices * 4) as usize); + let mut idx = Vec::with_capacity((n_slices * 6) as usize); + for s in 0..n_slices { + let t = if n_slices == 1 { 0.0 } else { s as f32 / (n_slices - 1) as f32 }; + // Fusion Text3D extrudes backward along -Z from z=0 to z=-depth + let z = -t * depth; + let nz = if n_slices > 1 && s == n_slices - 1 { -1.0 } else { 1.0 }; + let base = verts.len() as u32; + verts.push(Vertex3D { pos: [-hx, hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 0.0] }); + verts.push(Vertex3D { pos: [-hx, -hy, z], normal: [0.0, 0.0, nz], uv: [0.0, 1.0] }); + verts.push(Vertex3D { pos: [ hx, -hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 1.0] }); + verts.push(Vertex3D { pos: [ hx, hy, z], normal: [0.0, 0.0, nz], uv: [1.0, 0.0] }); + idx.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]); + } + (verts, idx) } ShapeKind::Sphere { radius, sub_base, sub_height } => { let seg_u = sub_base.clamp(12, 96); @@ -488,7 +695,8 @@ fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec, Vec (Vec, Vec r, + 1 => g, + 2 => b, + 3 => a, + _ => 0.299 * r + 0.587 * g + 0.114 * b, + }; + let d = (sample - 0.5 + disp.bias) * disp.scale; + v.pos[0] += v.normal[0] * d; + v.pos[1] += v.normal[1] * d; + v.pos[2] += v.normal[2] * d; + } + // Recompute smooth vertex normals from displaced triangles + let mut acc = vec![[0.0_f32; 3]; verts.len()]; + for tri in indices.chunks_exact(3) { + let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize); + if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() { + continue; + } + let p0 = verts[i0].pos; + let p1 = verts[i1].pos; + let p2 = verts[i2].pos; + let e1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]]; + let e2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]]; + let fn_v = [ + e1[1] * e2[2] - e1[2] * e2[1], + e1[2] * e2[0] - e1[0] * e2[2], + e1[0] * e2[1] - e1[1] * e2[0], + ]; + for &i in &[i0, i1, i2] { + acc[i][0] += fn_v[0]; + acc[i][1] += fn_v[1]; + acc[i][2] += fn_v[2]; + } + } + for (v, n) in verts.iter_mut().zip(acc.into_iter()) { + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + if len > 1e-6 { + v.normal = [n[0] / len, n[1] / len, n[2] / len]; + } + } +} + +#[derive(Clone, Default)] +struct SceneOverrides { + material_override: Option, + affected_by_lights: Option, + flip_normals: bool, + displace: Option, +} + +fn splitmix64(mut x: u64) -> f32 { + x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); + x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + x ^= x >> 31; + // Uniform in [-0.5, +0.5] + ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5 +} + /// Recursively traverses a Fusion 3D scene graph (`Merge3D`, `Transform3D`, `Camera3D`, -/// `ImagePlane3D`, `Shape3D`, `LightAmbient`, `LightDirectional`). +/// `ImagePlane3D`, `Shape3D`, `Text3D`, `LightAmbient`, `LightDirectional`, `LightPoint`, +/// `LightSpot`, `ReplaceMaterial3D`, `Override3D`, `Duplicate3D`, `ReplaceNormals3D`, `Displace3D`). #[allow(clippy::too_many_arguments)] pub fn collect_scene( comp: &Comp, @@ -587,6 +870,35 @@ pub fn collect_scene( meshes: &mut Vec, lights: &mut SceneLights, depth: usize, +) { + collect_scene_inner( + comp, + node_id, + time, + expr, + parent_xform, + render_aspect, + &SceneOverrides::default(), + cameras, + meshes, + lights, + depth, + ); +} + +#[allow(clippy::too_many_arguments)] +fn collect_scene_inner( + comp: &Comp, + node_id: NodeId, + time: f64, + expr: &ExprEngine, + parent_xform: Mat4, + render_aspect: f32, + ovr: &SceneOverrides, + cameras: &mut Vec, + meshes: &mut Vec, + lights: &mut SceneLights, + depth: usize, ) { if depth > 32 { return; @@ -608,10 +920,101 @@ pub fn collect_scene( input_names.sort(); for in_name in input_names { if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) { - collect_scene(comp, src_id, time, expr, world, render_aspect, cameras, meshes, lights, depth + 1); + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); } } } + "ReplaceMaterial3D" => { + let mut next_ovr = ovr.clone(); + if let Some(mid) = node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)) { + next_ovr.material_override = Some(mid); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); + } + } + "Override3D" => { + let do_vis = comp.eval_number(node, "Visibility.DoVisible", time, 0.0, expr) > 0.5; + let is_vis = comp.eval_number(node, "Visibility.IsVisible", time, 1.0, expr) > 0.5; + if do_vis && !is_vis { + return; + } + let mut next_ovr = ovr.clone(); + let do_lit = comp.eval_number(node, "Lighting.DoAffectedByLights", time, 0.0, expr) > 0.5; + if do_lit { + let is_lit = comp.eval_number(node, "Lighting.IsAffectedByLights", time, 1.0, expr) > 0.5; + next_ovr.affected_by_lights = Some(is_lit); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); + } + } + "ReplaceNormals3D" => { + let mut next_ovr = ovr.clone(); + if comp.eval_number(node, "FlipNormals", time, 0.0, expr) > 0.5 { + next_ovr.flip_normals = !next_ovr.flip_normals; + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); + } + } + "Displace3D" => { + let mut next_ovr = ovr.clone(); + if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { + let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32; + let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32; + let channel = comp.eval_number(node, "Channel", time, 4.0, expr).round() as i32; + next_ovr.displace = Some(Displace3DSpec { + input_node: in_id, + scale, + bias, + channel, + }); + } + if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { + collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, depth + 1); + } + } + "Duplicate3D" => { + let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { + return; + }; + let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32; + let last = comp.eval_number(node, "LastCopy", time, 1.0, expr).round() as i32; + let count = (last - first + 1).clamp(0, 256); + // Fusion Duplicate3D uses bare `Translate.X/Y/Z`, `Rotate.X/Y/Z`, `Scale.X/Y/Z` (with fallback to `Transform3DOp.*`) + let step = eval_duplicate3d_step(comp, node, time, expr); + let seed = comp.eval_number(node, "RandomSeed", time, 26024.0, expr).round() as u64; + let jtx = comp.eval_number(node, "JitterTranslate.X", time, 0.0, expr) as f32; + let jty = comp.eval_number(node, "JitterTranslate.Y", time, 0.0, expr) as f32; + let jtz = comp.eval_number(node, "JitterTranslate.Z", time, 0.0, expr) as f32; + let jrx = comp.eval_number(node, "JitterRotate.X", time, 0.0, expr) as f32; + let jry = comp.eval_number(node, "JitterRotate.Y", time, 0.0, expr) as f32; + let jrz = comp.eval_number(node, "JitterRotate.Z", time, 0.0, expr) as f32; + let has_jitter = (jtx.abs() + jty.abs() + jtz.abs() + jrx.abs() + jry.abs() + jrz.abs()) > 1e-5; + + let mut acc = mat4_identity(); + for _ in 0..first.max(0) { + acc = mat4_mul(acc, step); + } + for i in 0..count { + let copy_idx = (first + i) as u64; + let mut m = mat4_mul(parent_xform, acc); + if has_jitter { + let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407)); + let tx = splitmix64(s ^ 1) * jtx; + let ty = splitmix64(s ^ 2) * jty; + let tz = splitmix64(s ^ 3) * jtz; + let rx = (splitmix64(s ^ 4) * jrx).to_radians(); + let ry = (splitmix64(s ^ 5) * jry).to_radians(); + let rz = (splitmix64(s ^ 6) * jrz).to_radians(); + 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)))); + m = mat4_mul(m, jm); + } + collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, depth + 1); + acc = mat4_mul(acc, step); + } + } "Camera3D" => { let ap_w = comp.eval_number(node, "ApertureW", time, 1.4173236, expr) as f32; let ap_h = comp.eval_number(node, "ApertureH", time, 0.9448824, expr) as f32; @@ -667,22 +1070,69 @@ pub fn collect_scene( lights.dir_color = [r * inten, g * inten, b * inten]; lights.has_dir = true; } + "LightPoint" => { + let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; + let decay_rate = comp.eval_number(node, "DecayRate", time, 1.0, expr) as f32; + lights.points.push(PointLight { + pos: [world[12], world[13], world[14]], + color: [r * inten, g * inten, b * inten], + decay_type, + decay_rate, + }); + } + "LightSpot" => { + let inten = comp.eval_number(node, "Intensity", time, 1.0, expr) as f32; + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; + let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; + let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; + // SpotLight shines along -Z in local space + let dx = -world[8]; + let dy = -world[9]; + let dz = -world[10]; + let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); + let half_cone = (cone_deg * 0.5).max(0.5); + let outer_deg = (half_cone + penumbra_deg.max(0.0)).min(89.5); + let inner_deg = (half_cone + penumbra_deg.min(0.0)).max(0.1).min(outer_deg); + lights.spots.push(SpotLight { + pos: [world[12], world[13], world[14]], + dir: [dx / len, dy / len, dz / len], + color: [r * inten, g * inten, b * inten], + cos_inner: inner_deg.to_radians().cos(), + cos_outer: outer_deg.to_radians().cos(), + decay_type, + }); + } "ImagePlane3D" => { - let mat_node = node - .connected_node("MaterialInput") - .or_else(|| node.connected_node("SceneInput")) - .and_then(|s| comp.find_node(s)); - let (tex_node, diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr); + let mat_node = ovr.material_override.or_else(|| { + node.connected_node("MaterialInput") + .or_else(|| node.connected_node("SceneInput")) + .and_then(|s| comp.find_node(s)) + }); + let mat = resolve_material(comp, mat_node, time, expr); meshes.push(MeshInstance { world, shape: ShapeKind::ImagePlane, - material_node: tex_node, - diffuse_col, - roughness, + material_node: mat.tex_node, + text3d: None, + diffuse_col: mat.diffuse_col, + specular_col: mat.specular_col, + specular_intensity: mat.specular_intensity, + specular_exponent: mat.specular_exponent, + affected_by_lights: ovr.affected_by_lights.unwrap_or(true), + flip_normals: ovr.flip_normals, + displace: ovr.displace.clone(), }); } "Shape3D" => { let shape_name = node.static_str("Shape").unwrap_or("SurfacePlaneInputs"); + let disp_sub = if ovr.displace.is_some() { 32 } else { 1 }; let shape = match shape_name { "SurfaceSphereInputs" => ShapeKind::Sphere { // Fusion 21.1 Shape3D Sphere default Radius is 1.0 (verified via probe_moon_3d f00) @@ -701,22 +1151,32 @@ pub fn collect_scene( sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 48.0, expr).round() as u32, } } - "SurfaceCubeInputs" => ShapeKind::Cube { - width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32, - height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, 1.0, expr) as f32, - depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, 1.0, expr) as f32, - }, - _ => ShapeKind::Plane { - width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32, - height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32, - }, + "SurfaceCubeInputs" => { + let sz = comp.eval_number(node, "SurfaceCubeInputs.Size", time, 1.0, expr); + ShapeKind::Cube { + width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, sz, expr) as f32, + height: comp.eval_number(node, "SurfaceCubeInputs.Height", time, sz, expr) as f32, + depth: comp.eval_number(node, "SurfaceCubeInputs.Depth", time, sz, expr) as f32, + } + } + _ => { + let sw = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionWidth", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; + let sh = comp.eval_number(node, "SurfacePlaneInputs.SubdivisionHeight", time, disp_sub as f64, expr).round().max(disp_sub as f64) as u32; + ShapeKind::Plane { + width: comp.eval_number(node, "SurfacePlaneInputs.Width", time, 1.0, expr) as f32, + height: comp.eval_number(node, "SurfacePlaneInputs.Height", time, 1.0, expr) as f32, + sub_w: sw, + sub_h: sh, + } + } }; - let mat_node = node - .connected_node("MaterialInput") - .and_then(|s| comp.find_node(s)); - let (tex_node, mut diffuse_col, roughness) = resolve_material(comp, mat_node, time, expr); + let mat_node = ovr.material_override.or_else(|| { + node.connected_node("MaterialInput") + .and_then(|s| comp.find_node(s)) + }); + let mut mat = resolve_material(comp, mat_node, time, expr); if mat_node.is_none() { - diffuse_col = [ + mat.diffuse_col = [ comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Red", time, 1.0, expr) as f32, comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Green", time, 1.0, expr) as f32, comp.eval_number(node, "MtlStdInputs.Diffuse.Color.Blue", time, 1.0, expr) as f32, @@ -726,50 +1186,149 @@ pub fn collect_scene( meshes.push(MeshInstance { world, shape, - material_node: tex_node, - diffuse_col, - roughness, + material_node: mat.tex_node, + text3d: None, + diffuse_col: mat.diffuse_col, + specular_col: mat.specular_col, + specular_intensity: mat.specular_intensity, + specular_exponent: mat.specular_exponent, + affected_by_lights: ovr.affected_by_lights.unwrap_or(true), + flip_normals: ovr.flip_normals, + displace: ovr.displace.clone(), + }); + } + "Text3D" => { + let ext_depth = comp.eval_number(node, "Extrusion.ExtrusionDepth", time, 0.0, expr) as f32; + let mat_node = ovr.material_override.or_else(|| { + node.connected_node("MaterialInput") + .and_then(|s| comp.find_node(s)) + }); + let mut mat = resolve_material(comp, mat_node, time, expr); + if mat_node.is_none() { + mat.diffuse_col = [1.0, 1.0, 1.0, 1.0]; + } + // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate) + meshes.push(MeshInstance { + world, + shape: ShapeKind::TextPlate { + width: 4.0, + height: 2.0, + depth: ext_depth, + slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 }, + }, + material_node: mat.tex_node, + text3d: Some(Text3DSpec { node_id }), + diffuse_col: mat.diffuse_col, + specular_col: mat.specular_col, + specular_intensity: mat.specular_intensity, + specular_exponent: mat.specular_exponent, + affected_by_lights: ovr.affected_by_lights.unwrap_or(true), + flip_normals: ovr.flip_normals, + displace: ovr.displace.clone(), }); } "MacroOperator" | "GroupOperator" => { if let Some(out_id) = node.macro_output { - collect_scene(comp, out_id, time, expr, world, render_aspect, cameras, meshes, lights, depth + 1); + collect_scene_inner(comp, out_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, depth + 1); } } _ => {} } } -/// Resolves a 3D material input (either a 2D image node directly or a Fusion 3D material like -/// `MtlCookTorrance` / `MtlBlinn` / `MtlPhong`) to `(diffuse_2d_node, diffuse_rgba, roughness)`. +struct ResolvedMaterial { + tex_node: Option, + diffuse_col: [f32; 4], + specular_col: [f32; 3], + specular_intensity: f32, + specular_exponent: f32, +} + +/// Resolves a 3D material input (either a 2D image node, `Texture2DOperator`, or a Fusion 3D +/// material like `MtlBlinn` / `MtlCookTorrance` / `MtlPhong`). fn resolve_material( comp: &Comp, mat_node: Option, time: f64, expr: &ExprEngine, -) -> (Option, [f32; 4], f32) { +) -> ResolvedMaterial { + let default_mat = ResolvedMaterial { + tex_node: None, + diffuse_col: [1.0, 1.0, 1.0, 1.0], + specular_col: [1.0, 1.0, 1.0], + specular_intensity: 0.15, + specular_exponent: 25.0, + }; let Some(mid) = mat_node else { - return (None, [1.0, 1.0, 1.0, 1.0], 0.5); + return default_mat; }; let n = comp.node(mid); - if n.kind.starts_with("Mtl") { - let diff_tex = n - .connected_node("Diffuse.Color.Material") - .or_else(|| n.connected_node("MaterialInput")) - .and_then(|s| comp.find_node(s)); - let col = [ - comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32, - comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32, - comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32, - comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32, - ]; - let rough = comp.eval_number(n, "Specular.Roughness", time, 0.5, expr) as f32; - (diff_tex, col, rough) - } else { - (Some(mid), [1.0, 1.0, 1.0, 1.0], 0.5) + match n.kind.as_str() { + "Texture2DOperator" => { + let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s)); + ResolvedMaterial { + tex_node: tex_src, + ..default_mat + } + } + "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" => { + let mut diff_tex = n + .connected_node("Diffuse.Color.Material") + .or_else(|| n.connected_node("MaterialInput")) + .and_then(|s| comp.find_node(s)); + // Unwrap Texture2DOperator if feeding Diffuse.Color.Material + if let Some(tid) = diff_tex { + if comp.node(tid).kind == "Texture2DOperator" { + diff_tex = comp.node(tid).connected_node("Input").and_then(|s| comp.find_node(s)); + } + } + let col = [ + comp.eval_number(n, "Diffuse.Color.Red", time, 1.0, expr) as f32, + comp.eval_number(n, "Diffuse.Color.Green", time, 1.0, expr) as f32, + comp.eval_number(n, "Diffuse.Color.Blue", time, 1.0, expr) as f32, + comp.eval_number(n, "Diffuse.Opacity", time, 1.0, expr) as f32, + ]; + let spec_col = [ + comp.eval_number(n, "Specular.Color.Red", time, 1.0, expr) as f32, + comp.eval_number(n, "Specular.Color.Green", time, 1.0, expr) as f32, + comp.eval_number(n, "Specular.Color.Blue", time, 1.0, expr) as f32, + ]; + let spec_int = comp.eval_number(n, "Specular.Intensity", time, 1.0, expr) as f32; + let (spec_exp, spec_gain) = if n.kind == "MtlCookTorrance" { + let rough = comp.eval_number(n, "Specular.Roughness", time, 0.4, expr).clamp(0.05, 1.0) as f32; + ((2.0 / (rough * rough) - 2.0).max(2.0), 0.15) + } else { + (comp.eval_number(n, "Specular.Exponent", time, 25.0, expr).max(1.0) as f32, 1.0) + }; + ResolvedMaterial { + tex_node: diff_tex, + diffuse_col: col, + specular_col: spec_col, + specular_intensity: spec_int.clamp(0.0, 4.0) * spec_gain, + specular_exponent: spec_exp, + } + } + _ => ResolvedMaterial { + tex_node: Some(mid), + ..default_mat + }, } } +fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { + let tx = comp.eval_number(node, "Translate.X", time, comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr), expr) as f32; + let ty = comp.eval_number(node, "Translate.Y", time, comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr), expr) as f32; + let tz = comp.eval_number(node, "Translate.Z", time, comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr), expr) as f32; + 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(); + 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(); + 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(); + let sx = comp.eval_number(node, "Scale.X", time, comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr), expr) as f32; + let sy = comp.eval_number(node, "Scale.Y", time, comp.eval_number(node, "Transform3DOp.Scale.Y", time, sx as f64, expr), expr) as f32; + let sz = comp.eval_number(node, "Scale.Z", time, comp.eval_number(node, "Transform3DOp.Scale.Z", time, sx as f64, expr), expr) as f32; + let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))); + mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz))) +} + pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32; 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) -> 0.0, 0.0, far * near * nf, 0.0, ] } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_collect_scene_archive_3d_nodes() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 10 }, + GlobalRange = { 0, 10 }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + }, + }, + Tex2D = Texture2DOperator { + Inputs = { + Input = Input { SourceOp = "BG1", Source = "Output", }, + }, + }, + Blinn1 = MtlBlinn { + Inputs = { + ["Diffuse.Color.Red"] = Input { Value = 0.8, }, + ["Diffuse.Color.Material"] = Input { SourceOp = "Tex2D", Source = "MaterialOutput", }, + ["Specular.Intensity"] = Input { Value = 0.75, }, + ["Specular.Exponent"] = Input { Value = 40.0, }, + }, + }, + Cook1 = MtlCookTorrance { + Inputs = { + ["Diffuse.Color.Green"] = Input { Value = 0.6, }, + ["Specular.Roughness"] = Input { Value = 0.25, }, + }, + }, + Shape1 = Shape3D { + Inputs = { + Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, + MaterialInput = Input { SourceOp = "Blinn1", Source = "MaterialOutput", }, + }, + }, + RepMat = ReplaceMaterial3D { + Inputs = { + SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, + MaterialInput = Input { SourceOp = "Cook1", Source = "MaterialOutput", }, + }, + }, + RepNorm = ReplaceNormals3D { + Inputs = { + SceneInput = Input { SourceOp = "RepMat", Source = "Output", }, + FlipNormals = Input { Value = 1, }, + }, + }, + Disp1 = Displace3D { + Inputs = { + SceneInput = Input { SourceOp = "RepNorm", Source = "Output", }, + Input = Input { SourceOp = "BG1", Source = "Output", }, + Scale = Input { Value = 0.2, }, + }, + }, + Dup1 = Duplicate3D { + Inputs = { + SceneInput = Input { SourceOp = "Disp1", Source = "Output", }, + FirstCopy = Input { Value = 0, }, + LastCopy = Input { Value = 2, }, + ["Translate.X"] = Input { Value = 1.5, }, + }, + }, + OvrHide = Override3D { + Inputs = { + SceneInput = Input { SourceOp = "Shape1", Source = "Output", }, + ["Visibility.DoVisible"] = Input { Value = 1, }, + ["Visibility.IsVisible"] = Input { Value = 0, }, + }, + }, + Txt1 = Text3D { + Inputs = { + StyledText = Input { Value = "HI", }, + ["Extrusion.ExtrusionDepth"] = Input { Value = 0.15, }, + }, + }, + Pt1 = LightPoint { + Inputs = { + Intensity = Input { Value = 2.0, }, + DecayType = Input { Value = 1, }, + ["Transform3DOp.Translate.X"] = Input { Value = 3.0, }, + }, + }, + Sp1 = LightSpot { + Inputs = { + Intensity = Input { Value = 1.5, }, + ConeAngle = Input { Value = 45.0, }, + PenumbraAngle = Input { Value = 10.0, }, + }, + }, + Cam1 = Camera3D { + Inputs = { + ["Transform3DOp.Translate.Z"] = Input { Value = 5.0, }, + }, + }, + Merge1 = Merge3D { + Inputs = { + SceneInput1 = Input { SourceOp = "Dup1", Source = "Output", }, + SceneInput2 = Input { SourceOp = "OvrHide", Source = "Output", }, + SceneInput3 = Input { SourceOp = "Txt1", Source = "Output", }, + SceneInput4 = Input { SourceOp = "Pt1", Source = "Output", }, + SceneInput5 = Input { SourceOp = "Sp1", Source = "Output", }, + SceneInput6 = Input { SourceOp = "Cam1", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse 3D test comp"); + let expr = ExprEngine::new(); + let merge_id = comp.find_node("Merge1").expect("Merge1"); + let mut cams = Vec::new(); + let mut meshes = Vec::new(); + let mut lights = SceneLights::default(); + collect_scene( + &comp, + merge_id, + 0.0, + &expr, + mat4_identity(), + 16.0 / 9.0, + &mut cams, + &mut meshes, + &mut lights, + 0, + ); + assert_eq!(cams.len(), 1); + // 3 copies from Duplicate3D (0..=2) + 1 Text3D (OvrHide suppresses its Shape1) + assert_eq!(meshes.len(), 4); + assert!(meshes[0].flip_normals); + assert!(meshes[0].displace.is_some()); + assert!((meshes[0].diffuse_col[1] - 0.6).abs() < 1e-4, "ReplaceMaterial3D should apply Cook1"); + assert!((meshes[2].world[12] - 3.0).abs() < 1e-4, "Duplicate3D copy 2 translated X=3.0"); + assert!(meshes[3].text3d.is_some()); + assert_eq!(lights.points.len(), 1); + assert!((lights.points[0].pos[0] - 3.0).abs() < 1e-4); + assert_eq!(lights.spots.len(), 1); + assert!(lights.spots[0].cos_inner > lights.spots[0].cos_outer); + } +} diff --git a/crates/engine/src/shaders.wgsl b/crates/engine/src/shaders.wgsl index 4326971277fcbb8922c3c26cc0e80e3241b50102..78cc1de00b14cbeb0c47f0a0d8296cf32ac1960b 100644 --- a/crates/engine/src/shaders.wgsl +++ b/crates/engine/src/shaders.wgsl @@ -2441,3 +2441,41 @@ fn vortex_op(@builtin(global_invocation_id) gid: vec3) { let m = read_mask(gid.xy, dims, u.p[1].z, u.p[1].w) * blend; store_dst(vec2(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0))); } + + +// ============================================================================ +// 35. Fuse.KScope (N-slice radial kaleidoscope mirror) +// p[0] = (center.x, center.y, slices, angle_rad) +// p[1] = (capture_angle_rad, scale, edges, blend) +// p[2] = (has_mask, mask_invert, 0, 0) +// ============================================================================ +@compute @workgroup_size(8, 8) +fn kscope_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let aspect = f32(dims.x) / max(f32(dims.y), 1.0); + let fu = pix_to_fu(gid.xy, dims); + let center = u.p[0].xy; + let slices = max(u.p[0].z, 1.0); + let angle = u.p[0].w; + let cap_angle = u.p[1].x; + let scale = max(u.p[1].y, 1e-4); + let edges = i32(u.p[1].z + 0.5); + let blend = u.p[1].w; + + let orig = textureLoad(src_a, vec2(gid.xy), 0); + let rel = (fu - center) * vec2(aspect, 1.0); + let r = length(rel) / scale; + let sector = 6.28318530718 / slices; + var th = atan2(rel.y, rel.x) - angle; + th = th - floor(th / (2.0 * sector)) * (2.0 * sector); + if (th > sector) { + th = 2.0 * sector - th; + } + th = th + cap_angle; + let src_fu = center + vec2(cos(th) * r / aspect, sin(th) * r); + let kcol = sample_edges(src_a, src_fu, edges); + + let m = read_mask(gid.xy, dims, u.p[2].x, u.p[2].y) * blend; + store_dst(vec2(gid.xy), mix(orig, kcol, clamp(m, 0.0, 1.0))); +} diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 8efa662707cd3329e92d0181f6acda9ee63143cc..9b51f1d4fd586e771fdb1b27e6874b3284ad8147 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -6,7 +6,7 @@ //! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert. use draw::{Glyphs, PathStyle, Primitive}; -use model::{Comp, NodeId, PortRole, default_main_input_port, is_supported_tool}; +use model::{Comp, CompHistory, NodeId, PortRole, default_main_input_port, is_supported_tool}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use winit::event::{ElementState, MouseButton}; @@ -71,6 +71,10 @@ struct ModalTransform { struct WireDrag { src: NodeId, cursor_local: [f32; 2], + /// If hovering a target input port, `(dst, port, creates_cycle)`. + target: Option<(NodeId, &'static str, bool)>, + /// True when dragging an existing connected input off to disconnect/rewire. + detached_from: Option<(NodeId, String)>, } #[derive(Clone, Debug)] @@ -86,7 +90,14 @@ pub enum FlowAction { ViewNode(usize, NodeId), /// `` ` `` key: clear both Viewer 1 and Viewer 2. ClearViewers, - GraphMutated, + /// Graph topology or node state mutated (optional affected node for subtree bust). + GraphMutated(Option), + /// `Shift+Space`: open Add Tool launcher. + OpenAddTool, + /// `F2`: begin inline rename on the primary selected node. + RequestRename(NodeId), + /// Transient feedback message (e.g., cycle rejected). + StatusNotice(String), } #[derive(Clone, Debug)] @@ -185,6 +196,57 @@ impl FlowView { self.palette.bg } + /// Resets transient interaction state and re-fits when a new composition is loaded. + pub fn reset_for_comp(&mut self, comp: &Comp) { + self.selected.clear(); + self.primary = None; + self.hovered_node = None; + self.hovered_wire = None; + self.modal = None; + self.wire_drag = None; + self.box_select = None; + self.panning = None; + self.lmb_drag_node = None; + self.label_cache.clear(); + self.fitted_once = false; + self.fit_comp(comp); + } + + /// Removes any stale `NodeId`s from selection/viewed_nodes after undo/redo or deletion. + pub fn sanitize_ids(&mut self, comp: &Comp) { + let len = comp.nodes.len(); + self.selected.retain(|id| id.0 < len && !comp.nodes[id.0].internal); + if self.primary.is_some_and(|id| id.0 >= len || comp.nodes[id.0].internal) { + self.primary = self.selected.iter().copied().next(); + } + for slot in &mut self.viewed_nodes { + if slot.is_some_and(|id| id.0 >= len) { + *slot = None; + } + } + if self.hovered_node.is_some_and(|id| id.0 >= len) { + self.hovered_node = None; + } + self.hovered_wire = None; + self.modal = None; + self.wire_drag = None; + self.lmb_drag_node = None; + } + + /// Computes a clean world-space spawn position for a newly added node. + pub fn spawn_position(&self, comp: &Comp, is_generator: bool) -> [f32; 2] { + if let Some(sel_id) = self.primary.filter(|id| id.0 < comp.nodes.len()) { + let p = comp.node(sel_id).pos; + if is_generator { + [p[0], p[1] - 55.0] + } else { + [p[0] + 110.0, p[1]] + } + } else { + self.pan + } + } + pub fn fit_all(&mut self, comp: &Comp) { let ids: Vec = if !self.selected.is_empty() { self.selected.iter().copied().collect() @@ -326,18 +388,24 @@ impl FlowView { fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> { for n in comp.nodes.iter().rev() { + if n.internal { continue; } let r = self.node_rect_local(n.pos); - 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 { - // Pick Background/Foreground/Mask cleanly based on approach edge for Merge! - if n.kind == "Merge" || n.kind == "Displace" { - let cy = (r[1] + r[3]) * 0.5; + 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 { + // Pick Background/Foreground/Mask cleanly based on approach edge for Merge/Displace! + if n.kind == "Merge" || n.kind == "Displace" || n.kind == "Dissolve" { if local[1] < r[1] + 2.0 { return Some((n.id, "Foreground")); } if local[1] > r[3] - 2.0 { return Some((n.id, "EffectMask")); } - let _ = cy; + return Some((n.id, "Background")); + } + if n.kind == "Merge3D" || n.kind == "Renderer3D" { + return Some((n.id, "SceneInput1")); + } + if local[1] > r[3] - 1.5 && n.kind != "PipeRouter" { + return Some((n.id, "EffectMask")); } return Some((n.id, default_main_input_port(&n.kind))); } @@ -345,6 +413,28 @@ impl FlowView { None } + /// Hit-tests already-connected input port triangles so the user can drag an input off to disconnect/rewire. + fn hit_connected_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, String, NodeId)> { + let hit_r2 = 10.5_f32 * 10.5_f32; + for dst in comp.nodes.iter().rev() { + if dst.internal { continue; } + for (port, binding) in &dst.inputs { + let Some(src_name) = &binding.source_op else { continue }; + let Some(src_id) = comp.find_node(src_name) else { continue }; + let role = PortRole::from_input_name(port); + let (_a, _ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role); + let bn = be.normal(); + let center = [b[0] + bn[0] * 4.0, b[1] + bn[1] * 4.0]; + let dx = local[0] - center[0]; + let dy = local[1] - center[1]; + if dx * dx + dy * dy <= hit_r2 { + return Some((dst.id, port.clone(), src_id)); + } + } + } + None + } + fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option) -> Option { let mut best: Option<(f32, WireRef)> = None; for dst in &comp.nodes { @@ -375,7 +465,7 @@ impl FlowView { best.map(|(_, w)| w) } - fn begin_modal(&mut self, comp: &Comp, mode: TransformMode) { + fn begin_modal(&mut self, comp: &Comp, history: &mut CompHistory, mode: TransformMode) { if self.selected.is_empty() { return; } @@ -383,11 +473,21 @@ impl FlowView { let mut cy = 0.0_f32; let mut saved = Vec::with_capacity(self.selected.len()); for &id in &self.selected { + if id.0 >= comp.nodes.len() { continue; } let p = comp.node(id).pos; cx += p[0]; cy += p[1]; saved.push((id, p)); } + if saved.is_empty() { + return; + } + let label = match mode { + TransformMode::Grab => "Move Nodes", + TransformMode::Rotate => "Rotate Nodes", + TransformMode::Scale => "Scale Nodes", + }; + history.begin_group(comp, label); let n = saved.len() as f32; self.modal = Some(ModalTransform { mode, @@ -398,7 +498,7 @@ impl FlowView { }); } - fn apply_modal(&mut self, comp: &mut Comp) { + fn apply_modal(&mut self, comp: &mut Comp, shift_held: bool) { let Some(m) = &self.modal else { return }; let cur = self.local_to_world(self.pointer_local); let dx = cur[0] - m.start_pointer_world[0]; @@ -413,7 +513,7 @@ impl FlowView { AxisLock::Y => (0.0, dy), }; for &(id, orig) in &m.saved_positions { - comp.node_mut(id).pos = [orig[0] + mx, orig[1] + my]; + comp.set_node_pos(id, [orig[0] + mx, orig[1] + my]); } } TransformMode::Rotate => { @@ -424,7 +524,7 @@ impl FlowView { for &(id, orig) in &m.saved_positions { let rx = orig[0] - piv[0]; let ry = orig[1] - piv[1]; - comp.node_mut(id).pos = [piv[0] + rx * c - ry * s, piv[1] + rx * s + ry * c]; + comp.set_node_pos(id, [piv[0] + rx * c - ry * s, piv[1] + rx * s + ry * c]); } } TransformMode::Scale => { @@ -437,47 +537,74 @@ impl FlowView { AxisLock::Y => (1.0, factor), }; for &(id, orig) in &m.saved_positions { - comp.node_mut(id).pos = [ + comp.set_node_pos(id, [ piv[0] + (orig[0] - piv[0]) * sx, piv[1] + (orig[1] - piv[1]) * sy, - ]; + ]); } } } - if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 { + // Shift-dragging a single node over an existing pipe highlights it for splicing on release. + if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 && shift_held { let id = m.saved_positions[0].0; let c_local = self.world_to_local(comp.node(id).pos); - self.hovered_wire = self.hit_wire(comp, c_local, Some(id)); + self.hovered_wire = self.hit_wire(comp, c_local, Some(id)).filter(|w| { + !comp.would_create_cycle(w.src, id) && !comp.would_create_cycle(id, w.dst) + }); } else { self.hovered_wire = None; } } - fn cancel_modal(&mut self, comp: &mut Comp) { - if let Some(m) = self.modal.take() { - for (id, orig) in m.saved_positions { - comp.node_mut(id).pos = orig; - } + fn cancel_modal(&mut self, comp: &mut Comp, history: &mut CompHistory) { + if self.modal.take().is_some() { + history.cancel_group(comp); } self.hovered_wire = None; } - fn confirm_modal(&mut self, comp: &mut Comp) -> bool { - let mut mutated = false; + fn confirm_modal(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec) { if let Some(m) = self.modal.take() { if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 { let id = m.saved_positions[0].0; if let Some(w) = self.hovered_wire.take() { - comp.insert_on_wire(id, w.src, w.dst, &w.port); - mutated = true; + match comp.splice_node_into_pipe(id, w.src, w.dst, &w.port) { + Ok(()) => { + actions.push(FlowAction::GraphMutated(Some(w.dst))); + actions.push(FlowAction::StatusNotice(format!( + "Spliced {} into pipe", + comp.node(id).name + ))); + } + Err(e) => { + actions.push(FlowAction::StatusNotice(e)); + } + } } } + history.commit_group(comp); } self.hovered_wire = None; - mutated } - fn handle_key(&mut self, comp: &mut Comp, physical: Option, key: &Key, kmod: ModifiersState, actions: &mut Vec) { + fn handle_key( + &mut self, + comp: &mut Comp, + history: &mut CompHistory, + physical: Option, + key: &Key, + kmod: ModifiersState, + actions: &mut Vec, + ) { + // Shift+Space: open Add Tool launcher + if kmod.shift_key() + && !kmod.super_key() + && !kmod.control_key() + && matches!(key, Key::Named(NamedKey::Space)) + { + actions.push(FlowAction::OpenAddTool); + return; + } // Numpad '.' (Blender Frame Selected) or Cmd+F or plain F if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) { self.fit_all(comp); @@ -488,16 +615,41 @@ impl FlowView { actions.push(FlowAction::ClearViewers); return; } + let cmd = kmod.super_key() || kmod.control_key(); match key { Key::Named(NamedKey::Escape) => { if self.modal.is_some() { - self.cancel_modal(comp); + self.cancel_modal(comp, history); } self.wire_drag = None; } Key::Named(NamedKey::Enter) => { - if self.modal.is_some() && self.confirm_modal(comp) { - actions.push(FlowAction::GraphMutated); + if self.modal.is_some() { + self.confirm_modal(comp, history, actions); + } + } + Key::Named(NamedKey::Delete) | Key::Named(NamedKey::Backspace) => { + if !self.selected.is_empty() { + let ids: Vec = self.selected.iter().copied().collect(); + history.push_snapshot(comp, "Delete Nodes"); + let deleted = comp.delete_nodes(&ids); + if !deleted.is_empty() { + self.sanitize_ids(comp); + self.selected.clear(); + self.primary = None; + actions.push(FlowAction::SelectionChanged(None)); + actions.push(FlowAction::GraphMutated(None)); + actions.push(FlowAction::StatusNotice(format!( + "Deleted {} node{}", + deleted.len(), + if deleted.len() == 1 { "" } else { "s" } + ))); + } + } + } + Key::Named(NamedKey::F2) => { + if let Some(id) = self.primary { + actions.push(FlowAction::RequestRename(id)); } } Key::Character(c) => match c.to_ascii_lowercase().as_str() { @@ -505,59 +657,82 @@ impl FlowView { self.viewed_nodes = [None, None]; actions.push(FlowAction::ClearViewers); } + "d" if cmd && !kmod.shift_key() => { + if !self.selected.is_empty() { + let ids: Vec = self.selected.iter().copied().collect(); + history.push_snapshot(comp, "Duplicate Nodes"); + let created = comp.duplicate_nodes(&ids, [44.0, 28.0]); + if !created.is_empty() { + self.selected.clear(); + for &nid in &created { + self.selected.insert(nid); + } + self.primary = created.first().copied(); + actions.push(FlowAction::SelectionChanged(self.primary)); + actions.push(FlowAction::GraphMutated(self.primary)); + actions.push(FlowAction::StatusNotice(format!( + "Duplicated {} node{}", + created.len(), + if created.len() == 1 { "" } else { "s" } + ))); + } + } + } "f" if kmod.super_key() => self.fit_all(comp), "f" if !kmod.super_key() => self.fit_all(comp), "." if !kmod.super_key() => self.fit_all(comp), - "g" if !kmod.super_key() && self.modal.is_none() => { - self.begin_modal(comp, TransformMode::Grab); + "g" if !cmd && self.modal.is_none() => { + self.begin_modal(comp, history, TransformMode::Grab); } - "r" if !kmod.super_key() && self.modal.is_none() => { - self.begin_modal(comp, TransformMode::Rotate); + "r" if !cmd && self.modal.is_none() => { + self.begin_modal(comp, history, TransformMode::Rotate); } - "s" if !kmod.super_key() && self.modal.is_none() => { - self.begin_modal(comp, TransformMode::Scale); + "s" if !cmd && self.modal.is_none() => { + self.begin_modal(comp, history, TransformMode::Scale); } "x" if self.modal.is_some() => { if let Some(m) = &mut self.modal { m.axis = if m.axis == AxisLock::X { AxisLock::None } else { AxisLock::X }; } - self.apply_modal(comp); + self.apply_modal(comp, kmod.shift_key()); } "y" if self.modal.is_some() => { if let Some(m) = &mut self.modal { m.axis = if m.axis == AxisLock::Y { AxisLock::None } else { AxisLock::Y }; } - self.apply_modal(comp); + self.apply_modal(comp, kmod.shift_key()); } "a" if !kmod.super_key() => { - if self.selected.len() == comp.nodes.len() { + let visible: Vec = comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect(); + if self.selected.len() == visible.len() { self.selected.clear(); self.primary = None; } else { - self.selected = comp.nodes.iter().map(|n| n.id).collect(); - self.primary = comp.nodes.first().map(|n| n.id); + self.selected = visible.iter().copied().collect(); + self.primary = visible.first().copied(); } actions.push(FlowAction::SelectionChanged(self.primary)); } - "1" if !kmod.super_key() => { + "1" if !cmd => { if let Some(id) = self.primary { self.viewed_nodes[0] = Some(id); actions.push(FlowAction::ViewNode(0, id)); } } - "2" if !kmod.super_key() => { + "2" if !cmd => { if let Some(id) = self.primary { self.viewed_nodes[1] = Some(id); actions.push(FlowAction::ViewNode(1, id)); } } - "p" => { - let ids: Vec = self.selected.iter().copied().collect(); - for id in ids { - comp.toggle_bypass(id); - } + "p" if !kmod.super_key() => { if !self.selected.is_empty() { - actions.push(FlowAction::GraphMutated); + let ids: Vec = self.selected.iter().copied().collect(); + history.push_snapshot(comp, "Toggle Passthrough"); + for id in ids { + comp.toggle_passthrough(id); + } + actions.push(FlowAction::GraphMutated(self.primary)); } } _ => {} @@ -569,6 +744,7 @@ impl FlowView { pub fn input( &mut self, comp: &mut Comp, + history: &mut CompHistory, event: ui::Event, rect: [f32; 4], pointer_window: [f32; 2], @@ -586,9 +762,17 @@ impl FlowView { start_pan[1] - (self.pointer_local[1] - start_p[1]) / self.zoom, ]; } else if self.modal.is_some() { - self.apply_modal(comp); + self.apply_modal(comp, modifiers.shift_key()); } else if let Some(wd) = &mut self.wire_drag { wd.cursor_local = self.pointer_local; + let src = wd.src; + let target = self.hit_input_port(comp, self.pointer_local).map(|(dst, port)| { + let cycle = comp.would_create_cycle(src, dst); + (dst, port, cycle) + }); + if let Some(wd_mut) = &mut self.wire_drag { + wd_mut.target = target; + } } else if let Some(bs) = &mut self.box_select { bs.cur_local = self.pointer_local; } else if let Some((nid, start_l, ref mut moved)) = self.lmb_drag_node { @@ -602,7 +786,7 @@ impl FlowView { self.primary = Some(nid); actions.push(FlowAction::SelectionChanged(self.primary)); } - self.begin_modal(comp, TransformMode::Grab); + self.begin_modal(comp, history, TransformMode::Grab); } } else { self.hovered_node = self.hit_node(comp, self.pointer_local); @@ -622,23 +806,53 @@ impl FlowView { } } else if button == MouseButton::Right { if pressed && self.modal.is_some() { - self.cancel_modal(comp); + self.cancel_modal(comp, history); } else if pressed && self.wire_drag.is_some() { self.wire_drag = None; + } else if pressed { + // Right-click a hovered wire or connected input port to disconnect it! + if let Some(w) = self.hit_wire(comp, self.pointer_local, None) { + history.push_snapshot(comp, "Disconnect"); + if comp.disconnect(w.dst, &w.port) { + self.hovered_wire = None; + actions.push(FlowAction::GraphMutated(Some(w.dst))); + actions.push(FlowAction::StatusNotice(format!( + "Disconnected {}.{}", + comp.node(w.dst).name, + w.port + ))); + } + } } } else if button == MouseButton::Left { if pressed { if self.modal.is_some() { - if self.confirm_modal(comp) { - actions.push(FlowAction::GraphMutated); - } + self.confirm_modal(comp, history, &mut actions); } else if let Some(src) = self.hit_output_port(comp, self.pointer_local) { - self.wire_drag = Some(WireDrag { src, cursor_local: self.pointer_local }); + self.wire_drag = Some(WireDrag { + src, + cursor_local: self.pointer_local, + target: None, + detached_from: None, + }); + } else if let Some((dst, port, src)) = self.hit_connected_input_port(comp, self.pointer_local) { + // Dragging an existing input port detaches it so user can drop to disconnect or rewire! + history.push_snapshot(comp, "Disconnect"); + comp.disconnect(dst, &port); + actions.push(FlowAction::GraphMutated(Some(dst))); + self.wire_drag = Some(WireDrag { + src, + cursor_local: self.pointer_local, + target: None, + detached_from: Some((dst, port)), + }); } else if let Some(nid) = self.hit_node(comp, self.pointer_local) { if modifiers.shift_key() { if !self.selected.remove(&nid) { self.selected.insert(nid); self.primary = Some(nid); + } else if self.primary == Some(nid) { + self.primary = self.selected.iter().copied().next(); } } else if !self.selected.contains(&nid) { self.selected.clear(); @@ -663,15 +877,34 @@ impl FlowView { } else { if let Some((_nid, _start, moved)) = self.lmb_drag_node.take() { if moved && self.modal.is_some() { - if self.confirm_modal(comp) { - actions.push(FlowAction::GraphMutated); - } + self.confirm_modal(comp, history, &mut actions); } } if let Some(wd) = self.wire_drag.take() { if let Some((dst, port)) = self.hit_input_port(comp, self.pointer_local) { - comp.connect(wd.src, dst, port); - actions.push(FlowAction::GraphMutated); + if comp.would_create_cycle(wd.src, dst) { + actions.push(FlowAction::StatusNotice( + "Cycle rejected: cannot connect downstream to upstream".to_owned(), + )); + } else { + if wd.detached_from.is_none() { + history.push_snapshot(comp, "Connect"); + } + match comp.connect_output(wd.src, "Output", dst, port) { + Ok(()) => { + actions.push(FlowAction::GraphMutated(Some(dst))); + } + Err(e) => { + actions.push(FlowAction::StatusNotice(e)); + } + } + } + } else if let Some((dst, port)) = wd.detached_from { + actions.push(FlowAction::StatusNotice(format!( + "Disconnected {}.{}", + comp.node(dst).name, + port + ))); } } if let Some(bs) = self.box_select.take() { @@ -681,6 +914,7 @@ impl FlowView { let y1 = bs.start_local[1].max(bs.cur_local[1]); if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 { for n in &comp.nodes { + if n.internal { continue; } let c = self.world_to_local(n.pos); if c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 { self.selected.insert(n.id); @@ -708,10 +942,10 @@ impl FlowView { self.zoom_at(factor, self.pointer_local); } ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => { - self.handle_key(comp, Some(physical), &key, kmod, &mut actions); + self.handle_key(comp, history, Some(physical), &key, kmod, &mut actions); } ui::Event::Key { key, modifiers: kmod, .. } => { - self.handle_key(comp, None, &key, kmod, &mut actions); + self.handle_key(comp, history, None, &key, kmod, &mut actions); } _ => {} } @@ -767,9 +1001,12 @@ impl FlowView { self.badge_cache .entry("preserved".to_owned()) .or_insert_with(|| make_layout("preserved", &tiny_font)); + self.badge_cache + .entry("cycle!".to_owned()) + .or_insert_with(|| make_layout("cycle!", &tiny_font)); for key in [ - "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", - "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", + "Shift+Space: Add Tool G/R/S: Transform Shift+Drag: Splice Del: Delete Cmd+D: Dup F2: Rename Ctrl+P: Bypass 1/2: Viewer", + "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]", "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", ] { @@ -917,12 +1154,61 @@ impl FlowView { } } - // Active wire drag preview + // Active wire drag preview (smooth cubic bezier + cycle rejection feedback) if let Some(wd) = &self.wire_drag { - let sr = self.node_rect_local(comp.node(wd.src).pos); - let edge = self.node_output_edge(comp, wd.src); - let a = edge.point_on_rect(sr, 0.5); - out.push(Primitive::Segment { from: a, to: wd.cursor_local, width: 2.0, color: [0.98, 0.84, 0.30, 1.0] }); + if wd.src.0 < comp.nodes.len() { + let sr = self.node_rect_local(comp.node(wd.src).pos); + let edge = self.node_output_edge(comp, wd.src); + let a = edge.point_on_rect(sr, 0.5); + let (end, is_cycle, target_role) = match wd.target { + Some((dst, port, cycle)) if dst.0 < comp.nodes.len() => { + let role = PortRole::from_input_name(port); + let (_, _, b, _) = self.wire_endpoints(comp, wd.src, dst, role); + (b, cycle, Some(role)) + } + _ => (wd.cursor_local, false, None), + }; + let wire_col = if is_cycle { + [0.96, 0.30, 0.34, 1.0] + } else if let Some(role) = target_role { + port_color(role) + } else { + [0.98, 0.84, 0.30, 1.0] + }; + let pts = sample_preview_bezier(a, edge.normal(), end, 16); + for seg in pts.windows(2) { + out.push(Primitive::Segment { + from: seg[0], + to: seg[1], + width: if is_cycle { 2.4 } else { 2.0 }, + color: wire_col, + }); + } + if is_cycle { + if let Some(badge) = self.badge_cache.get("cycle!") { + let bx = end[0] + 8.0; + let by = end[1] - 14.0; + out.push(Primitive::RoundedRect { + rect: [bx, by, bx + 36.0, by + 13.0], + radius: 3.0, + stroke: None, + color: [0.30, 0.06, 0.08, 0.94], + }); + out.push(Primitive::RoundedRect { + rect: [bx, by, bx + 36.0, by + 13.0], + radius: 3.0, + stroke: Some(1.0), + color: [0.96, 0.30, 0.34, 0.95], + }); + out.push(Primitive::Text { + text: badge as &dyn Glyphs, + origin: [bx + 5.0, by + 2.0], + clip: Some([bx, by, bx + 36.0, by + 13.0]), + ink: [1.0, 0.65, 0.65, 1.0], + }); + } + } + } } // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!) @@ -1105,10 +1391,10 @@ impl FlowView { // 6. Status HUD strip let hud_key = match self.modal.as_ref().map(|m| m.mode) { - Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", + Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]", Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", - 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", + 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", }; if let Some(l) = self.badge_cache.get(hud_key) { let pill_h = 20.0; @@ -1224,3 +1510,99 @@ fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 { let q = [a[0] + ab[0] * t, a[1] + ab[1] * t]; ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt() } + +/// Samples a smooth cubic Bezier preview wire leaving `a` along `out_normal` and arriving at `b`. +pub fn sample_preview_bezier(a: [f32; 2], out_normal: [f32; 2], b: [f32; 2], steps: usize) -> Vec<[f32; 2]> { + let steps = steps.max(2); + let dist = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt(); + let handle = (dist * 0.42).clamp(24.0, 140.0); + let c1 = [a[0] + out_normal[0] * handle, a[1] + out_normal[1] * handle]; + let c2 = [b[0] - out_normal[0] * handle * 0.65, b[1] - out_normal[1] * handle * 0.65]; + let mut pts = Vec::with_capacity(steps + 1); + for i in 0..=steps { + let t = i as f32 / steps as f32; + let u = 1.0 - t; + let u2 = u * u; + let t2 = t * t; + let x = u2 * u * a[0] + 3.0 * u2 * t * c1[0] + 3.0 * u * t2 * c2[0] + t2 * t * b[0]; + let y = u2 * u * a[1] + 3.0 * u2 * t * c1[1] + 3.0 * u * t2 * c2[1] + t2 * t * b[1]; + pts.push([x, y]); + } + pts +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_comp() -> Comp { + let src = r#"Composition { + Tools = ordered() { + BG1 = Background { + ViewInfo = OperatorInfo { Pos = { 0, 0 } }, + }, + Merge1 = Merge { + Inputs = { + Background = Input { SourceOp = "BG1", Source = "Output" }, + }, + ViewInfo = OperatorInfo { Pos = { 160, 0 } }, + }, + }, + }"#; + Comp::from_fusion_str(src).expect("parse comp") + } + + #[test] + fn bezier_preview_endpoints_match() { + let pts = sample_preview_bezier([10.0, 20.0], [1.0, 0.0], [210.0, 80.0], 16); + assert_eq!(pts.len(), 17); + assert!((pts[0][0] - 10.0).abs() < 1e-4); + assert!((pts[0][1] - 20.0).abs() < 1e-4); + assert!((pts[16][0] - 210.0).abs() < 1e-4); + assert!((pts[16][1] - 80.0).abs() < 1e-4); + } + + #[test] + fn dist_to_seg_basic() { + assert!((dist_to_seg([5.0, 3.0], [0.0, 0.0], [10.0, 0.0]) - 3.0).abs() < 1e-5); + assert!((dist_to_seg([12.0, 0.0], [0.0, 0.0], [10.0, 0.0]) - 2.0).abs() < 1e-5); + } + + #[test] + fn flow_hit_node_and_input_ports() { + let theme = ui::Theme::new(&theme::KNIFE, true); + let mut flow = FlowView::new(&theme); + flow.size = [800.0, 600.0]; + flow.pan = [80.0, 0.0]; + flow.zoom = 1.0; + + let comp = test_comp(); + let bg = comp.find_node("BG1").unwrap(); + let merge = comp.find_node("Merge1").unwrap(); + + let bg_local = flow.world_to_local(comp.node(bg).pos); + assert_eq!(flow.hit_node(&comp, bg_local), Some(bg)); + + let merge_local = flow.world_to_local(comp.node(merge).pos); + assert_eq!(flow.hit_node(&comp, merge_local), Some(merge)); + + // Top of Merge hits Foreground; bottom hits EffectMask; middle hits Background + let mr = flow.node_rect_local(comp.node(merge).pos); + assert_eq!(flow.hit_input_port(&comp, [merge_local[0], mr[1] - 2.0]), Some((merge, "Foreground"))); + assert_eq!(flow.hit_input_port(&comp, [merge_local[0], mr[3] + 2.0]), Some((merge, "EffectMask"))); + assert_eq!(flow.hit_input_port(&comp, merge_local), Some((merge, "Background"))); + } + + #[test] + fn flow_spawn_position_generator_vs_effect() { + let theme = ui::Theme::new(&theme::KNIFE, true); + let mut flow = FlowView::new(&theme); + let comp = test_comp(); + let bg = comp.find_node("BG1").unwrap(); + flow.primary = Some(bg); + let p_eff = flow.spawn_position(&comp, false); + let p_gen = flow.spawn_position(&comp, true); + assert!(p_eff[0] > comp.node(bg).pos[0]); + assert!(p_gen[1] < comp.node(bg).pos[1]); + } +} diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index a017f421889ff556382da1ee7e3832ab28da319b..9a735b96ae6c3912fefe195271e233b57a24c829 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -120,10 +120,13 @@ pub fn is_supported_tool(kind: &str) -> bool { | "FilmGrain" | "Displace" | "Vortex" + | "Fuse.Duplicate" + | "Fuse.KScope" | "EllipseMask" | "RectangleMask" | "PolylineMask" | "BitmapMask" + | "WandMask" | "TextPlus" | "Fuse.Colorize" | "Fuse.Outline" @@ -150,8 +153,20 @@ pub fn is_supported_tool(kind: &str) -> bool { | "Camera3D" | "ImagePlane3D" | "Shape3D" + | "Text3D" | "LightAmbient" | "LightDirectional" + | "LightPoint" + | "LightSpot" + | "MtlBlinn" + | "MtlCookTorrance" + | "MtlPhong" + | "Texture2DOperator" + | "ReplaceMaterial3D" + | "Override3D" + | "Duplicate3D" + | "ReplaceNormals3D" + | "Displace3D" ) } diff --git a/crates/studio/src/add_tool.rs b/crates/studio/src/add_tool.rs new file mode 100644 index 0000000000000000000000000000000000000000..375dfdc4a4495a25b1cffc33ea7aec039bed3bd2 --- /dev/null +++ b/crates/studio/src/add_tool.rs @@ -0,0 +1,557 @@ +//! `Shift+Space` Add Tool fuzzy-search launcher modal overlay. + +use winit::keyboard::{Key, NamedKey}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToolCategory { + Generator, + Composite, + Color, + Keyer, + BlurGlow, + TransformWarp, + Mask, + Particle, + Scene3D, + Utility, +} + +impl ToolCategory { + pub fn label(self) -> &'static str { + match self { + Self::Generator => "Generator", + Self::Composite => "Composite", + Self::Color => "Color", + Self::Keyer => "Keyer", + Self::BlurGlow => "Blur/Glow", + Self::TransformWarp => "Transform/Warp", + Self::Mask => "Mask", + Self::Particle => "Particle", + Self::Scene3D => "3D", + Self::Utility => "Utility", + } + } + + pub fn color(self) -> [f32; 4] { + match self { + Self::Generator => [0.36, 0.82, 0.48, 1.0], + Self::Composite => [0.68, 0.72, 0.82, 1.0], + Self::Color => [0.94, 0.62, 0.24, 1.0], + Self::Keyer => [0.30, 0.84, 0.64, 1.0], + Self::BlurGlow => [0.94, 0.50, 0.28, 1.0], + Self::TransformWarp => [0.88, 0.72, 0.28, 1.0], + Self::Mask => [0.34, 0.66, 0.98, 1.0], + Self::Particle => [0.88, 0.46, 0.78, 1.0], + Self::Scene3D => [0.30, 0.86, 0.92, 1.0], + Self::Utility => [0.56, 0.62, 0.72, 1.0], + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ToolEntry { + pub kind: &'static str, + pub display: &'static str, + pub aliases: &'static str, + pub category: ToolCategory, + pub is_generator: bool, +} + +pub const TOOL_CATALOG: &[ToolEntry] = &[ + // Generator + ToolEntry { kind: "Background", display: "Background", aliases: "bg solid color", category: ToolCategory::Generator, is_generator: true }, + ToolEntry { kind: "FastNoise", display: "FastNoise", aliases: "fn noise fractal perlin", category: ToolCategory::Generator, is_generator: true }, + ToolEntry { kind: "Plasma", display: "Plasma", aliases: "gradient organic", category: ToolCategory::Generator, is_generator: true }, + ToolEntry { kind: "TextPlus", display: "Text+", aliases: "textplus title font", category: ToolCategory::Generator, is_generator: true }, + ToolEntry { kind: "Loader", display: "Loader", aliases: "ld read media footage image", category: ToolCategory::Generator, is_generator: true }, + // Composite + ToolEntry { kind: "Merge", display: "Merge", aliases: "mrg over blend comp", category: ToolCategory::Composite, is_generator: false }, + ToolEntry { kind: "Dissolve", display: "Dissolve", aliases: "dx mix crossfade", category: ToolCategory::Composite, is_generator: false }, + ToolEntry { kind: "ChannelBoolean", display: "Channel Booleans", aliases: "cb channel matte", category: ToolCategory::Composite, is_generator: false }, + ToolEntry { kind: "Switch", display: "Switch", aliases: "sw select", category: ToolCategory::Composite, is_generator: false }, + ToolEntry { kind: "Shadow", display: "Shadow", aliases: "drop shadow", category: ToolCategory::Composite, is_generator: false }, + // Color + ToolEntry { kind: "BrightnessContrast", display: "Brightness / Contrast", aliases: "bc gain lift gamma", category: ToolCategory::Color, is_generator: false }, + ToolEntry { kind: "ColorCorrector", display: "Color Corrector", aliases: "cc grade wheel saturation", category: ToolCategory::Color, is_generator: false }, + ToolEntry { kind: "ColorGain", display: "Color Gain", aliases: "cg rgb gain", category: ToolCategory::Color, is_generator: false }, + ToolEntry { kind: "ColorCurves", display: "Color Curves", aliases: "curves lut", category: ToolCategory::Color, is_generator: false }, + ToolEntry { kind: "HueCurves", display: "Hue Curves", aliases: "hue sat", category: ToolCategory::Color, is_generator: false }, + ToolEntry { kind: "GamutConvert", display: "Gamut", aliases: "colorspace srgb linear", category: ToolCategory::Color, is_generator: false }, + ToolEntry { kind: "InvertColor", display: "Invert Color", aliases: "negate invert", category: ToolCategory::Color, is_generator: false }, + ToolEntry { kind: "FilmGrain", display: "Film Grain", aliases: "grain noise", category: ToolCategory::Color, is_generator: false }, + ToolEntry { kind: "Fuse.Colorize", display: "Colorize", aliases: "tint duotone", category: ToolCategory::Color, is_generator: false }, + ToolEntry { kind: "Fuse.Outline", display: "Outline", aliases: "stroke edge", category: ToolCategory::Color, is_generator: false }, + // Keyer + ToolEntry { kind: "UltraKeyer", display: "Ultra Keyer", aliases: "uk chroma green blue screen", category: ToolCategory::Keyer, is_generator: false }, + ToolEntry { kind: "LumaKeyer", display: "Luma Keyer", aliases: "lk luminance key", category: ToolCategory::Keyer, is_generator: false }, + ToolEntry { kind: "Cryptomatte", display: "Cryptomatte", aliases: "crypto id matte", category: ToolCategory::Keyer, is_generator: false }, + // Blur / Glow + ToolEntry { kind: "Blur", display: "Blur", aliases: "bl gaussian defocus", category: ToolCategory::BlurGlow, is_generator: false }, + ToolEntry { kind: "DirectionalBlur", display: "Directional Blur", aliases: "db radial zoom motion blur", category: ToolCategory::BlurGlow, is_generator: false }, + ToolEntry { kind: "VariBlur", display: "VariBlur", aliases: "vb depth blur", category: ToolCategory::BlurGlow, is_generator: false }, + ToolEntry { kind: "Glow", display: "Glow", aliases: "gl bloom", category: ToolCategory::BlurGlow, is_generator: false }, + ToolEntry { kind: "SoftGlow", display: "Soft Glow", aliases: "sg bloom halo", category: ToolCategory::BlurGlow, is_generator: false }, + ToolEntry { kind: "Fuse.XGlow", display: "XGlow", aliases: "exponential glow", category: ToolCategory::BlurGlow, is_generator: false }, + ToolEntry { kind: "Sharpen", display: "Sharpen", aliases: "unsharp crisp", category: ToolCategory::BlurGlow, is_generator: false }, + ToolEntry { kind: "Filter", display: "Filter", aliases: "sobel emboss laplacian", category: ToolCategory::BlurGlow, is_generator: false }, + ToolEntry { kind: "ErodeDilate", display: "Erode / Dilate", aliases: "ed shrink grow matte", category: ToolCategory::BlurGlow, is_generator: false }, + // Transform / Warp + ToolEntry { kind: "Transform", display: "Transform", aliases: "xf move scale rotate", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "CameraShake", display: "Camera Shake", aliases: "shake jitter", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "CornerPositioner", display: "Corner Positioner", aliases: "cp pin perspective", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "DVE", display: "DVE", aliases: "3d card tilt", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "Scale", display: "Scale", aliases: "resize", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "BetterResize", display: "Resize", aliases: "rs scale format", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "Crop", display: "Crop", aliases: "trim canvas", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "Displace", display: "Displace", aliases: "dsp refract warp bump", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "Vortex", display: "Vortex", aliases: "swirl twist", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "Fuse.XfChroma", display: "XfChroma", aliases: "chromatic aberration rgb split", category: ToolCategory::TransformWarp, is_generator: false }, + // Mask + ToolEntry { kind: "EllipseMask", display: "Ellipse Mask", aliases: "el circle oval", category: ToolCategory::Mask, is_generator: true }, + ToolEntry { kind: "RectangleMask", display: "Rectangle Mask", aliases: "rect box square", category: ToolCategory::Mask, is_generator: true }, + ToolEntry { kind: "PolylineMask", display: "Polygon Mask", aliases: "poly roto spline", category: ToolCategory::Mask, is_generator: true }, + ToolEntry { kind: "BitmapMask", display: "Bitmap Mask", aliases: "bmp alpha luma", category: ToolCategory::Mask, is_generator: false }, + // Particle + ToolEntry { kind: "pEmitter", display: "pEmitter", aliases: "pe particle emit", category: ToolCategory::Particle, is_generator: true }, + ToolEntry { kind: "pRender", display: "pRender", aliases: "pr particle render", category: ToolCategory::Particle, is_generator: false }, + ToolEntry { kind: "pTurbulence", display: "pTurbulence", aliases: "pt particle wind", category: ToolCategory::Particle, is_generator: false }, + ToolEntry { kind: "pDirectionalForce", display: "pDirectionalForce", aliases: "pf gravity force", category: ToolCategory::Particle, is_generator: false }, + ToolEntry { kind: "pPointForce", display: "pPointForce", aliases: "particle attract", category: ToolCategory::Particle, is_generator: false }, + ToolEntry { kind: "pDrag", display: "pDrag", aliases: "particle damping", category: ToolCategory::Particle, is_generator: false }, + ToolEntry { kind: "pFriction", display: "pFriction", aliases: "particle friction", category: ToolCategory::Particle, is_generator: false }, + ToolEntry { kind: "pKill", display: "pKill", aliases: "particle kill", category: ToolCategory::Particle, is_generator: false }, + ToolEntry { kind: "pMerge", display: "pMerge", aliases: "particle merge", category: ToolCategory::Particle, is_generator: false }, + // 3D + ToolEntry { kind: "Renderer3D", display: "Renderer 3D", aliases: "3rn render 3d", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "Merge3D", display: "Merge 3D", aliases: "3mg scene 3d", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "Camera3D", display: "Camera 3D", aliases: "3cm cam", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "Shape3D", display: "Shape 3D", aliases: "3sh sphere plane cube", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "ImagePlane3D", display: "Image Plane 3D", aliases: "3im card plane", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "Transform3D", display: "Transform 3D", aliases: "3xf move 3d", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "LightAmbient", display: "Ambient Light", aliases: "3la light", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "LightDirectional", display: "Directional Light", aliases: "3dl sun light", category: ToolCategory::Scene3D, is_generator: true }, + // Utility + ToolEntry { kind: "Saver", display: "Saver", aliases: "sv write export png", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "PipeRouter", display: "Pipe Router", aliases: "dot router wire", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "TimeStretcher", display: "Time Stretcher", aliases: "ts retime freeze", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "TimeSpeed", display: "Time Speed", aliases: "tsp speed delay", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "ChangeDepth", display: "Change Depth", aliases: "cd bit depth float", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "SetDomain", display: "Set Domain", aliases: "dod roi", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "Tracker", display: "Tracker", aliases: "tr matchmove", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "Note", display: "Sticky Note", aliases: "comment note", category: ToolCategory::Utility, is_generator: true }, + ToolEntry { kind: "Underlay", display: "Underlay", aliases: "backdrop group", category: ToolCategory::Utility, is_generator: true }, +]; + +/// Case-insensitive fuzzy/subsequence scoring for tool search. +/// Higher score is better; returns `None` if `query` does not match `candidate`. +pub fn fuzzy_score(query: &str, entry: &ToolEntry) -> Option { + let q = query.trim().to_ascii_lowercase(); + if q.is_empty() { + return Some(0); + } + let kind_l = entry.kind.to_ascii_lowercase(); + let disp_l = entry.display.to_ascii_lowercase(); + let alias_l = entry.aliases.to_ascii_lowercase(); + let cat_l = entry.category.label().to_ascii_lowercase(); + + let mut best: Option = None; + for (field, bonus) in [(&kind_l, 40), (&disp_l, 35), (&alias_l, 15), (&cat_l, 0)] { + if let Some(s) = score_field(&q, field) { + let total = s + bonus; + best = Some(best.map_or(total, |prev| prev.max(total))); + } + } + best +} + +fn score_field(query: &str, target: &str) -> Option { + if target == query { + return Some(1000); + } + if target.starts_with(query) { + return Some(850 - (target.len() as i32 - query.len() as i32)); + } + if let Some(idx) = target.find(query) { + let boundary_bonus = if idx == 0 || matches!(target.as_bytes()[idx - 1], b' ' | b'.' | b'/' | b'_') { + 120 + } else { + 0 + }; + return Some(620 + boundary_bonus - idx as i32 * 4); + } + + // Subsequence match with consecutive-run & word-boundary bonuses + let q_bytes = query.as_bytes(); + let t_bytes = target.as_bytes(); + let mut qi = 0usize; + let mut score = 200i32; + let mut prev_match: Option = None; + + for (ti, &tb) in t_bytes.iter().enumerate() { + if qi < q_bytes.len() && tb == q_bytes[qi] { + if prev_match.is_some_and(|p| p + 1 == ti) { + score += 28; + } else if let Some(p) = prev_match { + score -= ((ti - p) as i32).min(20); + } + if ti == 0 || matches!(t_bytes[ti - 1], b' ' | b'.' | b'/' | b'_') { + score += 22; + } + prev_match = Some(ti); + qi += 1; + } + } + + if qi == q_bytes.len() { + Some(score - (t_bytes.len() as i32)) + } else { + None + } +} + +/// Returns matching tool entries ranked from best to worst. +pub fn search_tools(query: &str) -> Vec<&'static ToolEntry> { + let mut scored: Vec<(i32, usize, &'static ToolEntry)> = TOOL_CATALOG + .iter() + .enumerate() + .filter_map(|(idx, entry)| fuzzy_score(query, entry).map(|s| (s, idx, entry))) + .collect(); + scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1))); + scored.into_iter().map(|(_, _, e)| e).collect() +} + +pub struct AddToolLauncher { + pub open: bool, + pub query: String, + pub selected_idx: usize, + needs_focus: bool, +} + +impl Default for AddToolLauncher { + fn default() -> Self { + Self::new() + } +} + +impl AddToolLauncher { + pub fn new() -> Self { + Self { + open: false, + query: String::new(), + selected_idx: 0, + needs_focus: false, + } + } + + pub fn open(&mut self) { + self.open = true; + self.query.clear(); + self.selected_idx = 0; + self.needs_focus = true; + } + + pub fn close(&mut self) { + self.open = false; + self.needs_focus = false; + } + + /// Builds the floating modal overlay when open. Returns `Some(ToolEntry)` if a tool was chosen. + pub fn build_ui(&mut self, ui: &mut ui::Ui, window_size: [f32; 2]) -> Option { + if !self.open { + return None; + } + + let theme = ui.theme.clone(); + let results = search_tools(&self.query); + if self.selected_idx >= results.len() { + self.selected_idx = 0; + } + + let modal_id = ui::Id::ROOT.child("add-tool-modal"); + let input_id = modal_id.child("query"); + + // Handle Up / Down / Enter / Escape from the search field before rendering rows + let mut picked: Option = None; + let mut should_close = false; + + let scrim_id = ui::Id::ROOT.child("add-tool-scrim"); + let scrim_sig = ui.signal(scrim_id); + if scrim_sig.clicked { + should_close = true; + } + + // Full-window barrier scrim so clicks behind modal don't leak + ui.open_as( + scrim_id, + ui::Spec { + flags: ui::Flags::FLOAT | ui::Flags::BARRIER | ui::Flags::CLICKABLE, + position: [0.0, 0.0], + size: [ui::px(window_size[0]), ui::px(window_size[1])], + fill: Some([0.0, 0.0, 0.0, 0.42]), + ..ui::Spec::default() + }, + ); + ui.close(); + + let modal_w = 460.0_f32.min((window_size[0] - 40.0).max(260.0)); + let modal_h = 380.0_f32.min((window_size[1] - 80.0).max(220.0)); + let modal_x = ((window_size[0] - modal_w) * 0.5).max(16.0); + let modal_y = (window_size[1] * 0.14).max(24.0); + + ui.open_as( + modal_id, + ui::Spec { + flags: ui::Flags::FLOAT | ui::Flags::BARRIER | ui::Flags::CLICKABLE | ui::Flags::CLIP, + position: [modal_x, modal_y], + size: [ui::px(modal_w), ui::px(modal_h)], + axis: ui::Axis::Y, + fill: Some(theme.popup), + border: Some(theme.accent), + shadow: Some([0.0, 0.0, 0.0, 0.45]), + radius: 10.0, + pad: [10.0, 10.0], + gap: 8.0, + ..ui::Spec::default() + }, + ); + + // Header + ui.open( + "hdr", + ui::Spec { + size: [ui::fill(), ui::px(20.0)], + axis: ui::Axis::X, + gap: 6.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "title", + ui::Spec { + size: [ui::fill(), ui::fill()], + text: Some("Add Tool"), + font_size: Some(12.5), + medium: true, + color: Some(theme.text), + ..ui::Spec::default() + }, + ); + ui.leaf( + "hint", + ui::Spec { + size: [ui::fit(), ui::fill()], + text: Some("↑↓ select · Enter add · Esc close"), + font_size: Some(10.0), + color: Some(theme.text_dim), + ..ui::Spec::default() + }, + ); + ui.close(); + + // Search input + let prev_query = self.query.clone(); + let input_sig = ui::text_field( + ui, + input_id, + &mut self.query, + "Type tool name (e.g. Merge, Blur, BC, xf, Text+)…", + ui::Spec { + size: [ui::fill(), ui::px(30.0)], + font_size: Some(13.0), + fill: Some(theme.base), + border: Some(theme.accent), + radius: 6.0, + pad: [10.0, 4.0], + ..ui::Spec::default() + }, + ); + if self.needs_focus { + ui.set_focus(Some(input_id)); + self.needs_focus = false; + } + if self.query != prev_query { + self.selected_idx = 0; + } + + for ev in &input_sig.events { + if let ui::Event::Key { key, .. } = ev { + match key { + Key::Named(NamedKey::Escape) => should_close = true, + Key::Named(NamedKey::ArrowDown) => { + if !results.is_empty() { + self.selected_idx = (self.selected_idx + 1) % results.len(); + } + } + Key::Named(NamedKey::ArrowUp) => { + if !results.is_empty() { + self.selected_idx = (self.selected_idx + results.len() - 1) % results.len(); + } + } + Key::Named(NamedKey::Enter) => { + if let Some(&entry) = results.get(self.selected_idx) { + picked = Some(*entry); + should_close = true; + } + } + _ => {} + } + } + } + + // Scrollable results list + ui.open( + "results", + ui::Spec { + flags: ui::Flags::SCROLL | ui::Flags::CLIP, + size: [ui::fill(), ui::fill()], + axis: ui::Axis::Y, + gap: 2.0, + ..ui::Spec::default() + }, + ); + if results.is_empty() { + ui.leaf( + "no-match", + ui::Spec { + size: [ui::fill(), ui::px(28.0)], + text: Some("No matching tools"), + font_size: Some(11.5), + color: Some(theme.text_dim), + center: true, + ..ui::Spec::default() + }, + ); + } else { + for (idx, entry) in results.iter().enumerate() { + let is_sel = idx == self.selected_idx; + let cat_col = entry.category.color(); + let row_id = ui.open( + ("row", entry.kind), + ui::Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::fill(), ui::px(26.0)], + axis: ui::Axis::X, + pad: [8.0, 2.0], + gap: 8.0, + fill: if is_sel { + Some([theme.accent[0], theme.accent[1], theme.accent[2], 0.22]) + } else { + None + }, + hover_fill: Some([theme.accent[0], theme.accent[1], theme.accent[2], 0.14]), + radius: 5.0, + ..ui::Spec::default() + }, + ); + let row_sig = ui.signal(row_id); + if row_sig.clicked { + picked = Some(**entry); + should_close = true; + } + + // Category color pip + ui.leaf( + "pip", + ui::Spec { + size: [ui::px(6.0), ui::px(14.0)], + fill: Some(cat_col), + radius: 2.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "name", + ui::Spec { + size: [ui::fill(), ui::fill()], + text: Some(entry.display), + font_size: Some(12.0), + medium: is_sel, + color: Some(theme.text), + ..ui::Spec::default() + }, + ); + ui.leaf( + "kind", + ui::Spec { + size: [ui::fit(), ui::fill()], + text: Some(entry.kind), + font_size: Some(10.0), + color: Some(theme.text_dim), + ..ui::Spec::default() + }, + ); + ui.leaf( + "cat", + ui::Spec { + size: [ui::fit(), ui::px(18.0)], + text: Some(entry.category.label()), + font_size: Some(9.5), + color: Some(cat_col), + fill: Some([cat_col[0], cat_col[1], cat_col[2], 0.14]), + radius: 3.0, + pad: [5.0, 0.0], + center: true, + ..ui::Spec::default() + }, + ); + ui.close(); + } + } + ui.close(); // results + ui.close(); // modal_id + + if should_close { + self.close(); + ui.set_focus(None); + } + picked + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_query_returns_all_tools() { + let all = search_tools(""); + assert_eq!(all.len(), TOOL_CATALOG.len()); + assert!(all.len() >= 50); + } + + #[test] + fn exact_and_prefix_rank_above_subsequence() { + let res = search_tools("blur"); + assert!(!res.is_empty()); + assert_eq!(res[0].kind, "Blur"); + + let res_mrg = search_tools("merge"); + assert_eq!(res_mrg[0].kind, "Merge"); + } + + #[test] + fn alias_and_subsequence_matching_works() { + // Alias "bc" -> BrightnessContrast + let res_bc = search_tools("bc"); + assert!(res_bc.iter().take(3).any(|e| e.kind == "BrightnessContrast")); + + // Alias "xf" -> Transform + let res_xf = search_tools("xf"); + assert!(res_xf.iter().take(3).any(|e| e.kind == "Transform")); + + // Subsequence "tplus" -> TextPlus + let res_tp = search_tools("tplus"); + assert!(res_tp.iter().any(|e| e.kind == "TextPlus")); + + // Case-insensitive category match + let res_3d = search_tools("camera"); + assert!(res_3d.iter().any(|e| e.kind == "Camera3D")); + } + + #[test] + fn non_matching_query_returns_empty() { + let res = search_tools("zzzznotatool999"); + assert!(res.is_empty()); + } +} diff --git a/crates/studio/src/inspector.rs b/crates/studio/src/inspector.rs new file mode 100644 index 0000000000000000000000000000000000000000..b7762169df7751d0013e13e9c70704b5c79c157a --- /dev/null +++ b/crates/studio/src/inspector.rs @@ -0,0 +1,1802 @@ +//! Inspector dock pane — Fusion 21.1 parameter editor with scrub sliders, Vec2, RGBA color groups, +//! booleans, FuID enum cyclers, text fields, expression badges, and keyframe diamonds (`◆`). + +use engine::EvalStats; +use model::{Comp, CompHistory, ExprEngine, NodeId, ParamValue, is_supported_tool}; +use std::collections::{HashMap, HashSet}; +use std::time::{Duration, Instant}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ParamKind { + Float { min: f64, max: f64, default: f64, step: f64 }, + Vec2 { min: f64, max: f64, default: [f64; 2] }, + Bool { default: bool }, + Enum { options: &'static [&'static str], default: &'static str }, + Color { + r: &'static str, + g: &'static str, + b: &'static str, + a: Option<&'static str>, + default: [f64; 4], + }, + Text { default: &'static str }, +} + +#[derive(Clone, Copy, Debug)] +pub struct ParamSpec { + pub name: &'static str, + pub label: &'static str, + pub kind: ParamKind, +} + +#[derive(Clone, Debug)] +pub enum InspectorAction { + /// A parameter or node property changed; bust subtree & re-render viewers. + ParamEdited(NodeId), + /// A keyframe was added or deleted; refresh spline editor + bust subtree. + KeyframeEdited(NodeId), + /// Node was renamed. + NodeRenamed(NodeId), + /// Status notice to show in window title. + StatusNotice(String), +} + +#[derive(Clone, Debug)] +struct DragState { + node_id: NodeId, + key: String, + start_x: f32, + start_val: f64, + min: f64, + max: f64, + width: f32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeyframeState { + Static, + AnimatedOtherFrame, + KeyframeAtCurrent, +} + +pub struct InspectorState { + pub bg: [f32; 4], + pub panel_bg: [f32; 4], + pub rule: [f32; 4], + pub text: [f32; 4], + pub text_dim: [f32; 4], + pub accent: [f32; 4], + expr: ExprEngine, + /// Node name edit buffer synced with the currently selected node. + name_node: Option, + name_buf: String, + /// Text parameter edit buffers keyed by `(node_id, param_name)`. + text_bufs: HashMap<(usize, String), String>, + /// Active scrub slider drag. + drag: Option, + /// Last click timestamp per slider key for double-click reset. + last_click: HashMap, +} + +impl InspectorState { + pub fn new(theme: &ui::Theme) -> Self { + let b = theme.base; + let lift = |c: [f32; 4], d: f32| { + [ + (c[0] + d).clamp(0.0, 1.0), + (c[1] + d).clamp(0.0, 1.0), + (c[2] + d).clamp(0.0, 1.0), + 1.0, + ] + }; + Self { + bg: b, + panel_bg: lift(b, 0.020), + rule: theme.rule, + text: theme.text, + text_dim: theme.text_dim, + accent: theme.accent, + expr: ExprEngine::new(), + name_node: None, + name_buf: String::new(), + text_bufs: HashMap::new(), + drag: None, + last_click: HashMap::new(), + } + } + + pub fn background(&self) -> [f32; 4] { + self.bg + } + + pub fn reset(&mut self) { + self.name_node = None; + self.name_buf.clear(); + self.text_bufs.clear(); + self.drag = None; + } + + pub fn build_ui( + &mut self, + ui: &mut ui::Ui, + pane_id: ui::Id, + comp: &mut Comp, + history: &mut CompHistory, + selected: Option, + current_frame: f64, + stats: &EvalStats, + ) -> Vec { + let mut actions = Vec::new(); + let bg = self.bg; + let panel_bg = self.panel_bg; + let rule = self.rule; + let text_col = self.text; + let text_dim = self.text_dim; + let accent = self.accent; + + ui.open_as( + pane_id, + ui::Spec { + size: [ui::fill(), ui::fill()], + axis: ui::Axis::Y, + fill: Some(bg), + ..ui::Spec::default() + }, + ); + + let Some(node_id) = selected.filter(|id| id.0 < comp.nodes.len()) else { + // Empty state + ui.open( + "insp-empty", + ui::Spec { + size: [ui::fill(), ui::fill()], + axis: ui::Axis::Y, + pad: [14.0, 18.0], + gap: 8.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "empty-title", + ui::Spec { + size: [ui::fill(), ui::px(20.0)], + text: Some("No Node Selected"), + font_size: Some(12.5), + medium: true, + color: Some(text_col), + ..ui::Spec::default() + }, + ); + ui.leaf( + "empty-hint", + ui::Spec { + size: [ui::fill(), ui::fit()], + text: Some("Select a node in the Flow graph to inspect and keyframe its parameters, or press Shift+Space to add a tool."), + font_size: Some(11.0), + overflow: ui::Overflow::Wrap, + color: Some(text_dim), + ..ui::Spec::default() + }, + ); + self.render_stats_footer(ui, stats, panel_bg, rule, text_dim); + ui.close(); + ui.close(); + return actions; + }; + + // Sync editable name buffer when selection changes or node was renamed externally (e.g. undo) + let current_name = comp.node(node_id).name.clone(); + let name_field_id = pane_id.child(("node-name", node_id.0)); + if self.name_node != Some(node_id) + || (ui.focused() != Some(name_field_id) && self.name_buf != current_name) + { + self.name_node = Some(node_id); + self.name_buf = current_name.clone(); + } + + // 1. Header: Node name + Class badge + Bypass toggle + ui.open( + "insp-header", + ui::Spec { + size: [ui::fill(), ui::children()], + axis: ui::Axis::Y, + pad: [10.0, 8.0], + gap: 6.0, + fill: Some(panel_bg), + border: Some(rule), + ..ui::Spec::default() + }, + ); + + // Row 1: Editable name + Bypass button + ui.open( + "insp-name-row", + ui::Spec { + size: [ui::fill(), ui::px(26.0)], + axis: ui::Axis::X, + gap: 6.0, + ..ui::Spec::default() + }, + ); + let name_sig = ui::text_field( + ui, + name_field_id, + &mut self.name_buf, + "Node name", + ui::Spec { + size: [ui::fill(), ui::px(24.0)], + font_size: Some(12.0), + medium: true, + fill: Some(bg), + border: Some(rule), + hover_border: Some(accent), + radius: 4.0, + pad: [6.0, 2.0], + ..ui::Spec::default() + }, + ); + let enter_pressed = name_sig.events.iter().any(|ev| { + matches!( + ev, + ui::Event::Key { key: winit::keyboard::Key::Named(winit::keyboard::NamedKey::Enter), .. } + ) + }); + if enter_pressed && self.name_buf.trim() != current_name { + let desired = self.name_buf.trim().to_owned(); + history.push_snapshot(comp, "Rename Node"); + match comp.rename_node(node_id, &desired) { + Ok(applied) => { + self.name_buf = applied; + actions.push(InspectorAction::NodeRenamed(node_id)); + } + Err(e) => { + self.name_buf = current_name.clone(); + actions.push(InspectorAction::StatusNotice(e)); + } + } + ui.set_focus(None); + } + + let bypassed = comp.node(node_id).bypassed; + let pass_lbl = if bypassed { "Bypassed" } else { "Active" }; + let pass_fill = if bypassed { + [0.85, 0.28, 0.28, 0.28] + } else { + [0.24, 0.78, 0.48, 0.18] + }; + let pass_border = if bypassed { + [0.92, 0.36, 0.36, 0.75] + } else { + [0.28, 0.82, 0.52, 0.55] + }; + let pass_sig = ui.leaf( + ("insp-pass", node_id.0), + ui::Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::fit(), ui::px(24.0)], + text: Some(pass_lbl), + font_size: Some(10.5), + medium: true, + color: Some(text_col), + fill: Some(pass_fill), + border: Some(pass_border), + radius: 4.0, + pad: [8.0, 0.0], + center: true, + ..ui::Spec::default() + }, + ); + if pass_sig.clicked { + history.push_snapshot(comp, "Toggle Passthrough"); + comp.toggle_passthrough(node_id); + actions.push(InspectorAction::ParamEdited(node_id)); + } + ui.close(); // insp-name-row + + // Row 2: Tool class badge + supported/preserved indicator + frame badge + let node_kind = comp.node(node_id).kind.clone(); + let supported = is_supported_tool(&node_kind); + let frame_str = format!("f{:.0}", current_frame); + ui.open( + "insp-meta-row", + ui::Spec { + size: [ui::fill(), ui::px(18.0)], + axis: ui::Axis::X, + gap: 6.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "insp-kind-badge", + ui::Spec { + size: [ui::fit(), ui::px(18.0)], + text: Some(&node_kind), + font_size: Some(10.0), + medium: true, + color: Some(accent), + fill: Some([accent[0], accent[1], accent[2], 0.14]), + border: Some([accent[0], accent[1], accent[2], 0.40]), + radius: 3.0, + pad: [6.0, 0.0], + center: true, + ..ui::Spec::default() + }, + ); + if !supported { + ui.leaf( + "insp-preserved-badge", + ui::Spec { + size: [ui::fit(), ui::px(18.0)], + text: Some("preserved"), + font_size: Some(9.5), + medium: true, + color: Some([0.98, 0.78, 0.40, 1.0]), + fill: Some([0.24, 0.16, 0.06, 0.85]), + border: Some([0.92, 0.64, 0.24, 0.60]), + radius: 3.0, + pad: [5.0, 0.0], + center: true, + ..ui::Spec::default() + }, + ); + } + ui.leaf( + "insp-spacer", + ui::Spec { + size: [ui::fill(), ui::px(18.0)], + ..ui::Spec::default() + }, + ); + ui.leaf( + "insp-frame", + ui::Spec { + size: [ui::fit(), ui::px(18.0)], + text: Some(&frame_str), + font_size: Some(10.0), + color: Some(text_dim), + center: true, + ..ui::Spec::default() + }, + ); + ui.close(); // insp-meta-row + ui.close(); // insp-header + + // 2. Scrollable Parameter List + ui.open( + "insp-scroll", + ui::Spec { + flags: ui::Flags::SCROLL | ui::Flags::CLIP, + size: [ui::fill(), ui::fill()], + axis: ui::Axis::Y, + pad: [10.0, 8.0], + gap: 6.0, + ..ui::Spec::default() + }, + ); + + let schema = schema_for_kind(&node_kind); + let mut covered: HashSet<&str> = HashSet::new(); + + for spec in schema { + covered.insert(spec.name); + if let ParamKind::Color { r, g, b, a, .. } = spec.kind { + covered.insert(r); + covered.insert(g); + covered.insert(b); + if let Some(alpha_k) = a { + covered.insert(alpha_k); + } + } + self.render_param_spec(ui, pane_id, comp, history, node_id, spec, current_frame, &mut actions); + } + + // Fallback: list all remaining present non-image inputs on the node! + let mut extra_keys: Vec = comp + .node(node_id) + .inputs + .iter() + .filter_map(|(k, b)| { + if covered.contains(k.as_str()) { + return None; + } + // Skip image/node connections unless they also have a value or spline + let is_node_conn = b + .source_op + .as_deref() + .is_some_and(|op| comp.node_by_name.contains_key(op)); + if is_node_conn && b.value.is_none() { + return None; + } + if b.value.is_none() && b.expression.is_none() && b.source_op.is_none() { + return None; + } + Some(k.clone()) + }) + .collect(); + extra_keys.sort(); + + if !extra_keys.is_empty() { + ui.leaf( + "insp-extra-hdr", + ui::Spec { + size: [ui::fill(), ui::px(18.0)], + text: Some("OTHER INPUTS"), + font_size: Some(9.5), + medium: true, + color: Some(text_dim), + ..ui::Spec::default() + }, + ); + for key in extra_keys { + self.render_fallback_input(ui, pane_id, comp, history, node_id, &key, current_frame, &mut actions); + } + } + + // Loader clip info if Loader node + if node_kind == "Loader" { + let clip_summary = comp + .node(node_id) + .clips + .first() + .map(|c| c.filename.clone()) + .unwrap_or_else(|| "(no clip)".to_owned()); + ui.open( + "insp-loader-clip", + ui::Spec { + size: [ui::fill(), ui::children()], + axis: ui::Axis::Y, + gap: 3.0, + pad: [6.0, 5.0], + fill: Some(panel_bg), + border: Some(rule), + radius: 4.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "clip-lbl", + ui::Spec { + size: [ui::fill(), ui::px(14.0)], + text: Some("Clip Filename"), + font_size: Some(10.0), + color: Some(text_dim), + ..ui::Spec::default() + }, + ); + ui.leaf( + "clip-path", + ui::Spec { + size: [ui::fill(), ui::fit()], + text: Some(&clip_summary), + font_size: Some(10.5), + overflow: ui::Overflow::Wrap, + color: Some(text_col), + ..ui::Spec::default() + }, + ); + ui.close(); + } + + ui.close(); // insp-scroll + + // 3. Footer: EvalStats summary + self.render_stats_footer(ui, stats, panel_bg, rule, text_dim); + + ui.close(); // pane_id + actions + } + + fn render_stats_footer( + &self, + ui: &mut ui::Ui, + stats: &EvalStats, + panel_bg: [f32; 4], + rule: [f32; 4], + text_dim: [f32; 4], + ) { + let line = format!( + "Eval {:.1}ms · {} nodes · cache {}/{} · {:.0}MB", + stats.eval_ms, + stats.nodes_evaluated, + stats.cache_hits, + stats.cache_hits + stats.cache_misses, + stats.cached_vram_mb, + ); + ui.open( + "insp-footer", + ui::Spec { + size: [ui::fill(), ui::px(24.0)], + axis: ui::Axis::X, + pad: [10.0, 4.0], + fill: Some(panel_bg), + border: Some(rule), + ..ui::Spec::default() + }, + ); + ui.leaf( + "insp-stats-txt", + ui::Spec { + size: [ui::fill(), ui::fill()], + text: Some(&line), + font_size: Some(10.0), + color: Some(text_dim), + ..ui::Spec::default() + }, + ); + ui.close(); + } + + #[allow(clippy::too_many_arguments)] + fn render_param_spec( + &mut self, + ui: &mut ui::Ui, + pane_id: ui::Id, + comp: &mut Comp, + history: &mut CompHistory, + node_id: NodeId, + spec: &ParamSpec, + current_frame: f64, + actions: &mut Vec, + ) { + match spec.kind { + ParamKind::Float { min, max, default, step: _ } => { + self.render_float_row( + ui, + pane_id, + comp, + history, + node_id, + spec.name, + spec.label, + min, + max, + default, + current_frame, + actions, + ); + } + ParamKind::Vec2 { min, max, default } => { + self.render_vec2_row( + ui, + pane_id, + comp, + history, + node_id, + spec.name, + spec.label, + min, + max, + default, + current_frame, + actions, + ); + } + ParamKind::Bool { default } => { + self.render_bool_row(ui, comp, history, node_id, spec.name, spec.label, default, actions); + } + ParamKind::Enum { options, default } => { + self.render_enum_row(ui, comp, history, node_id, spec.name, spec.label, options, default, actions); + } + ParamKind::Color { r, g, b, a, default } => { + self.render_color_group( + ui, + pane_id, + comp, + history, + node_id, + spec.label, + r, + g, + b, + a, + default, + current_frame, + actions, + ); + } + ParamKind::Text { default } => { + self.render_text_row(ui, pane_id, comp, history, node_id, spec.name, spec.label, default, actions); + } + } + } + + #[allow(clippy::too_many_arguments)] + fn render_fallback_input( + &mut self, + ui: &mut ui::Ui, + pane_id: ui::Id, + comp: &mut Comp, + history: &mut CompHistory, + node_id: NodeId, + key: &str, + current_frame: f64, + actions: &mut Vec, + ) { + let val = comp.node(node_id).inputs.get(key).and_then(|b| b.value.clone()); + match val { + Some(ParamValue::Point(pt)) => { + self.render_vec2_row(ui, pane_id, comp, history, node_id, key, key, -1.0, 2.0, pt, current_frame, actions); + } + Some(ParamValue::Text(_)) => { + self.render_text_row(ui, pane_id, comp, history, node_id, key, key, "", actions); + } + Some(ParamValue::FuId(cur)) => { + let text_dim = self.text_dim; + let text_col = self.text; + let panel_bg = self.panel_bg; + let rule = self.rule; + ui.open( + ("fb-fuid", node_id.0, key), + ui::Spec { + size: [ui::fill(), ui::px(22.0)], + axis: ui::Axis::X, + gap: 6.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "lbl", + ui::Spec { + size: [ui::px(92.0), ui::fill()], + text: Some(key), + font_size: Some(10.5), + overflow: ui::Overflow::Ellipsis, + color: Some(text_dim), + ..ui::Spec::default() + }, + ); + ui.leaf( + "val", + ui::Spec { + size: [ui::fill(), ui::fill()], + text: Some(&cur), + font_size: Some(10.5), + color: Some(text_col), + fill: Some(panel_bg), + border: Some(rule), + radius: 4.0, + pad: [6.0, 0.0], + ..ui::Spec::default() + }, + ); + ui.close(); + } + Some(ParamValue::Number(v)) => { + let (min, max) = infer_float_range(key, v); + self.render_float_row(ui, pane_id, comp, history, node_id, key, key, min, max, v, current_frame, actions); + } + None => { + // Animated spline or expression-only scalar input + let cur = comp.eval_number(comp.node(node_id), key, current_frame, 0.0, &self.expr); + let (min, max) = infer_float_range(key, cur); + self.render_float_row(ui, pane_id, comp, history, node_id, key, key, min, max, 0.0, current_frame, actions); + } + _ => {} + } + } + + #[allow(clippy::too_many_arguments)] + fn render_float_row( + &mut self, + ui: &mut ui::Ui, + pane_id: ui::Id, + comp: &mut Comp, + history: &mut CompHistory, + node_id: NodeId, + input_name: &str, + label: &str, + min: f64, + max: f64, + default: f64, + current_frame: f64, + actions: &mut Vec, + ) { + let cur_val = comp.eval_number(comp.node(node_id), input_name, current_frame, default, &self.expr); + let has_expr = comp + .node(node_id) + .inputs + .get(input_name) + .and_then(|b| b.expression.as_ref()) + .is_some(); + let kf_state = keyframe_state(comp, node_id, input_name, current_frame); + + ui.open( + ("row-f", node_id.0, input_name), + ui::Spec { + size: [ui::fill(), ui::px(22.0)], + axis: ui::Axis::X, + gap: 4.0, + ..ui::Spec::default() + }, + ); + + // Label + ui.leaf( + "lbl", + ui::Spec { + size: [ui::px(86.0), ui::fill()], + text: Some(label), + font_size: Some(10.5), + overflow: ui::Overflow::Ellipsis, + color: Some(self.text_dim), + ..ui::Spec::default() + }, + ); + + // Expression `=` badge if present + if has_expr { + ui.leaf( + "expr-badge", + ui::Spec { + size: [ui::px(16.0), ui::px(18.0)], + text: Some("="), + font_size: Some(10.5), + bold: true, + color: Some([0.36, 0.88, 0.92, 1.0]), + fill: Some([0.10, 0.24, 0.28, 0.85]), + border: Some([0.32, 0.78, 0.86, 0.65]), + radius: 3.0, + center: true, + ..ui::Spec::default() + }, + ); + } + + // Scrub slider + let slider_id = pane_id.child(("sld", node_id.0, input_name)); + let drag_key = format!("{}:{input_name}", node_id.0); + if let Some(new_val) = self.scrub_slider( + ui, + slider_id, + &drag_key, + node_id, + cur_val, + min, + max, + default, + history, + comp, + input_name, + ) { + if kf_state != KeyframeState::Static { + let _ = comp.set_keyframe(node_id, input_name, current_frame, new_val); + actions.push(InspectorAction::KeyframeEdited(node_id)); + } else { + comp.set_input_value(node_id, input_name, ParamValue::Number(new_val)); + actions.push(InspectorAction::ParamEdited(node_id)); + } + } + + // Reset button (small dot/arrow when non-default) + let is_default = (cur_val - default).abs() < 1e-4; + if !is_default { + let rst = ui.leaf( + ("rst", node_id.0, input_name), + ui::Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::px(18.0), ui::px(20.0)], + text: Some("↺"), + font_size: Some(10.5), + color: Some(self.text_dim), + hover_fill: Some(self.panel_bg), + radius: 3.0, + center: true, + ..ui::Spec::default() + }, + ); + if rst.clicked { + history.push_snapshot(comp, format!("Reset {label}")); + if kf_state != KeyframeState::Static { + let _ = comp.set_keyframe(node_id, input_name, current_frame, default); + actions.push(InspectorAction::KeyframeEdited(node_id)); + } else { + comp.set_input_value(node_id, input_name, ParamValue::Number(default)); + actions.push(InspectorAction::ParamEdited(node_id)); + } + } + } + + // Keyframe diamond button (`◆`) + if self.keyframe_button(ui, ("kf", node_id.0, input_name), kf_state) { + self.toggle_keyframe(comp, history, node_id, input_name, current_frame, cur_val, kf_state, actions); + } + + ui.close(); + } + + #[allow(clippy::too_many_arguments)] + fn render_vec2_row( + &mut self, + ui: &mut ui::Ui, + pane_id: ui::Id, + comp: &mut Comp, + history: &mut CompHistory, + node_id: NodeId, + input_name: &str, + label: &str, + min: f64, + max: f64, + default: [f64; 2], + current_frame: f64, + actions: &mut Vec, + ) { + let cur = comp.eval_point(comp.node(node_id), input_name, current_frame, default, &self.expr); + let has_expr = comp + .node(node_id) + .inputs + .get(input_name) + .and_then(|b| b.expression.as_ref()) + .is_some(); + + ui.open( + ("row-v2", node_id.0, input_name), + ui::Spec { + size: [ui::fill(), ui::px(22.0)], + axis: ui::Axis::X, + gap: 4.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "lbl", + ui::Spec { + size: [ui::px(86.0), ui::fill()], + text: Some(label), + font_size: Some(10.5), + overflow: ui::Overflow::Ellipsis, + color: Some(self.text_dim), + ..ui::Spec::default() + }, + ); + if has_expr { + ui.leaf( + "expr-badge", + ui::Spec { + size: [ui::px(16.0), ui::px(18.0)], + text: Some("="), + font_size: Some(10.5), + bold: true, + color: Some([0.36, 0.88, 0.92, 1.0]), + fill: Some([0.10, 0.24, 0.28, 0.85]), + border: Some([0.32, 0.78, 0.86, 0.65]), + radius: 3.0, + center: true, + ..ui::Spec::default() + }, + ); + } + + let x_id = pane_id.child(("v2x", node_id.0, input_name)); + let x_key = format!("{}:{input_name}:x", node_id.0); + if let Some(nx) = self.scrub_slider( + ui, + x_id, + &x_key, + node_id, + cur[0], + min, + max, + default[0], + history, + comp, + input_name, + ) { + comp.set_input_value(node_id, input_name, ParamValue::Point([nx, cur[1]])); + actions.push(InspectorAction::ParamEdited(node_id)); + } + + let y_id = pane_id.child(("v2y", node_id.0, input_name)); + let y_key = format!("{}:{input_name}:y", node_id.0); + if let Some(ny) = self.scrub_slider( + ui, + y_id, + &y_key, + node_id, + cur[1], + min, + max, + default[1], + history, + comp, + input_name, + ) { + comp.set_input_value(node_id, input_name, ParamValue::Point([cur[0], ny])); + actions.push(InspectorAction::ParamEdited(node_id)); + } + + ui.close(); + } + + #[allow(clippy::too_many_arguments)] + fn render_bool_row( + &mut self, + ui: &mut ui::Ui, + comp: &mut Comp, + history: &mut CompHistory, + node_id: NodeId, + input_name: &str, + label: &str, + default: bool, + actions: &mut Vec, + ) { + let checked = comp + .node(node_id) + .static_number(input_name) + .map(|v| v >= 0.5) + .unwrap_or(default); + + ui.open( + ("row-b", node_id.0, input_name), + ui::Spec { + size: [ui::fill(), ui::px(22.0)], + axis: ui::Axis::X, + gap: 6.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "lbl", + ui::Spec { + size: [ui::px(86.0), ui::fill()], + text: Some(label), + font_size: Some(10.5), + overflow: ui::Overflow::Ellipsis, + color: Some(self.text_dim), + ..ui::Spec::default() + }, + ); + let fill = if checked { + [self.accent[0], self.accent[1], self.accent[2], 0.28] + } else { + self.panel_bg + }; + let border = if checked { self.accent } else { self.rule }; + let sig = ui.leaf( + ("chk", node_id.0, input_name), + ui::Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::px(54.0), ui::px(20.0)], + text: Some(if checked { "✓ On" } else { "Off" }), + font_size: Some(10.5), + medium: checked, + color: Some(if checked { self.text } else { self.text_dim }), + fill: Some(fill), + border: Some(border), + radius: 4.0, + center: true, + ..ui::Spec::default() + }, + ); + if sig.clicked { + history.push_snapshot(comp, format!("Toggle {label}")); + let next = if checked { 0.0 } else { 1.0 }; + comp.set_input_value(node_id, input_name, ParamValue::Number(next)); + actions.push(InspectorAction::ParamEdited(node_id)); + } + ui.close(); + } + + #[allow(clippy::too_many_arguments)] + fn render_enum_row( + &mut self, + ui: &mut ui::Ui, + comp: &mut Comp, + history: &mut CompHistory, + node_id: NodeId, + input_name: &str, + label: &str, + options: &'static [&'static str], + default: &'static str, + actions: &mut Vec, + ) { + let cur = comp + .node(node_id) + .static_str(input_name) + .unwrap_or(default) + .to_owned(); + + ui.open( + ("row-e", node_id.0, input_name), + ui::Spec { + size: [ui::fill(), ui::px(22.0)], + axis: ui::Axis::X, + gap: 6.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "lbl", + ui::Spec { + size: [ui::px(86.0), ui::fill()], + text: Some(label), + font_size: Some(10.5), + overflow: ui::Overflow::Ellipsis, + color: Some(self.text_dim), + ..ui::Spec::default() + }, + ); + let btn_lbl = format!("{cur} ▾"); + let sig = ui.leaf( + ("enum", node_id.0, input_name), + ui::Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::fill(), ui::px(20.0)], + text: Some(&btn_lbl), + font_size: Some(10.5), + color: Some(self.text), + fill: Some(self.panel_bg), + border: Some(self.rule), + hover_border: Some(self.accent), + radius: 4.0, + pad: [6.0, 0.0], + ..ui::Spec::default() + }, + ); + if sig.clicked && !options.is_empty() { + let idx = options.iter().position(|&o| o == cur).unwrap_or(0); + let next_idx = if ui.modifiers().shift_key() { + (idx + options.len() - 1) % options.len() + } else { + (idx + 1) % options.len() + }; + history.push_snapshot(comp, format!("Set {label}")); + comp.set_input_value(node_id, input_name, ParamValue::FuId(options[next_idx].to_owned())); + actions.push(InspectorAction::ParamEdited(node_id)); + } + ui.close(); + } + + #[allow(clippy::too_many_arguments)] + fn render_color_group( + &mut self, + ui: &mut ui::Ui, + pane_id: ui::Id, + comp: &mut Comp, + history: &mut CompHistory, + node_id: NodeId, + label: &str, + r_key: &'static str, + g_key: &'static str, + b_key: &'static str, + a_key: Option<&'static str>, + default: [f64; 4], + current_frame: f64, + actions: &mut Vec, + ) { + let rv = comp.eval_number(comp.node(node_id), r_key, current_frame, default[0], &self.expr); + let gv = comp.eval_number(comp.node(node_id), g_key, current_frame, default[1], &self.expr); + let bv = comp.eval_number(comp.node(node_id), b_key, current_frame, default[2], &self.expr); + let _av = a_key + .map(|ak| comp.eval_number(comp.node(node_id), ak, current_frame, default[3], &self.expr)) + .unwrap_or(default[3]); + let swatch = [ + rv.clamp(0.0, 1.0) as f32, + gv.clamp(0.0, 1.0) as f32, + bv.clamp(0.0, 1.0) as f32, + 1.0, + ]; + + ui.open( + ("grp-col", node_id.0, label), + ui::Spec { + size: [ui::fill(), ui::children()], + axis: ui::Axis::Y, + gap: 4.0, + pad: [6.0, 5.0], + fill: Some(self.panel_bg), + border: Some(self.rule), + radius: 4.0, + ..ui::Spec::default() + }, + ); + // Swatch header + ui.open( + "col-hdr", + ui::Spec { + size: [ui::fill(), ui::px(18.0)], + axis: ui::Axis::X, + gap: 6.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "col-lbl", + ui::Spec { + size: [ui::px(80.0), ui::fill()], + text: Some(label), + font_size: Some(10.5), + medium: true, + color: Some(self.text), + ..ui::Spec::default() + }, + ); + ui.leaf( + "col-swatch", + ui::Spec { + size: [ui::fill(), ui::px(16.0)], + fill: Some(swatch), + border: Some(self.rule), + radius: 3.0, + ..ui::Spec::default() + }, + ); + ui.close(); + + self.render_float_row(ui, pane_id, comp, history, node_id, r_key, "Red", 0.0, 1.0, default[0], current_frame, actions); + self.render_float_row(ui, pane_id, comp, history, node_id, g_key, "Green", 0.0, 1.0, default[1], current_frame, actions); + self.render_float_row(ui, pane_id, comp, history, node_id, b_key, "Blue", 0.0, 1.0, default[2], current_frame, actions); + if let Some(ak) = a_key { + self.render_float_row(ui, pane_id, comp, history, node_id, ak, "Alpha", 0.0, 1.0, default[3], current_frame, actions); + } + ui.close(); + } + + #[allow(clippy::too_many_arguments)] + fn render_text_row( + &mut self, + ui: &mut ui::Ui, + pane_id: ui::Id, + comp: &mut Comp, + history: &mut CompHistory, + node_id: NodeId, + input_name: &str, + label: &str, + default: &str, + actions: &mut Vec, + ) { + let field_id = pane_id.child(("txt", node_id.0, input_name)); + let key = (node_id.0, input_name.to_owned()); + let model_val = comp + .node(node_id) + .static_str(input_name) + .unwrap_or(default) + .to_owned(); + let buf = self.text_bufs.entry(key).or_insert_with(|| model_val.clone()); + if ui.focused() != Some(field_id) && *buf != model_val { + *buf = model_val.clone(); + } + let prev = buf.clone(); + + ui.open( + ("row-t", node_id.0, input_name), + ui::Spec { + size: [ui::fill(), ui::px(24.0)], + axis: ui::Axis::X, + gap: 6.0, + ..ui::Spec::default() + }, + ); + ui.leaf( + "lbl", + ui::Spec { + size: [ui::px(86.0), ui::fill()], + text: Some(label), + font_size: Some(10.5), + overflow: ui::Overflow::Ellipsis, + color: Some(self.text_dim), + ..ui::Spec::default() + }, + ); + ui::text_field( + ui, + field_id, + buf, + label, + ui::Spec { + size: [ui::fill(), ui::px(22.0)], + font_size: Some(11.0), + fill: Some(self.panel_bg), + border: Some(self.rule), + hover_border: Some(self.accent), + radius: 4.0, + pad: [6.0, 2.0], + ..ui::Spec::default() + }, + ); + if *buf != prev { + history.push_coalesced( + comp, + format!("Edit {label}"), + format!("text:{}:{input_name}", node_id.0), + ); + comp.set_input_value(node_id, input_name, ParamValue::Text(buf.clone())); + actions.push(InspectorAction::ParamEdited(node_id)); + } + ui.close(); + } + + #[allow(clippy::too_many_arguments)] + fn scrub_slider( + &mut self, + ui: &mut ui::Ui, + slider_id: ui::Id, + drag_key: &str, + node_id: NodeId, + value: f64, + min: f64, + max: f64, + default: f64, + history: &mut CompHistory, + comp: &Comp, + input_name: &str, + ) -> Option { + let sig = ui.signal(slider_id); + let rect = ui.laid_out(slider_id); + let width = rect.map(|r| (r[2] - r[0]).max(40.0)).unwrap_or(110.0); + let mut updated: Option = None; + + if let Some(press) = sig.press { + let now = Instant::now(); + let is_double = self + .last_click + .get(drag_key) + .is_some_and(|prev| now.duration_since(*prev) < Duration::from_millis(320)); + self.last_click.insert(drag_key.to_owned(), now); + if is_double { + history.push_snapshot(comp, format!("Reset {input_name}")); + self.drag = None; + updated = Some(default); + } else { + self.drag = Some(DragState { + node_id, + key: drag_key.to_owned(), + start_x: press[0], + start_val: value, + min, + max, + width, + }); + } + } else if sig.dragging { + if let (Some(d), Some(ptr)) = (&self.drag, ui.pointer()) { + if d.key == drag_key && d.node_id == node_id { + let fine = if ui.modifiers().shift_key() { 0.15 } else { 1.0 }; + let next = compute_scrub_value(d.start_val, ptr[0] - d.start_x, d.width, d.min, d.max, fine); + if (next - value).abs() > 1e-6 { + history.push_coalesced( + comp, + format!("Adjust {input_name}"), + format!("scrub:{drag_key}"), + ); + updated = Some(next); + } + } + } + } else if self.drag.as_ref().is_some_and(|d| d.key == drag_key) { + self.drag = None; + history.break_coalescing(); + } + + let display_val = updated.unwrap_or(value); + let frac = normalize_slider_fraction(display_val, min, max); + let val_text = format_param_number(display_val); + let fill_w = (width * frac).clamp(0.0, width); + let active_drag = self.drag.as_ref().is_some_and(|d| d.key == drag_key); + + ui.open_as( + slider_id, + ui::Spec { + cursor: Some(winit::window::CursorIcon::EwResize), + flags: ui::Flags::CLICKABLE | ui::Flags::CLIP, + size: [ui::fill(), ui::px(20.0)], + fill: Some(self.panel_bg), + border: Some(if active_drag || sig.hovered { self.accent } else { self.rule }), + radius: 4.0, + ..ui::Spec::default() + }, + ); + if fill_w > 0.5 { + ui.leaf( + "fill", + ui::Spec { + flags: ui::Flags::FLOAT | ui::Flags::INERT, + position: [0.0, 0.0], + size: [ui::px(fill_w), ui::px(20.0)], + fill: Some([self.accent[0], self.accent[1], self.accent[2], if active_drag { 0.34 } else { 0.22 }]), + radius: 3.0, + ..ui::Spec::default() + }, + ); + } + ui.leaf( + "txt", + ui::Spec { + flags: ui::Flags::INERT, + size: [ui::fill(), ui::fill()], + text: Some(&val_text), + font_size: Some(10.5), + color: Some(self.text), + center: true, + ..ui::Spec::default() + }, + ); + ui.close(); + + updated + } + + fn keyframe_button(&self, ui: &mut ui::Ui, part: impl std::hash::Hash, state: KeyframeState) -> bool { + let (ink, fill, border) = match state { + KeyframeState::KeyframeAtCurrent => ( + [1.0, 0.80, 0.22, 1.0], + Some([0.98, 0.72, 0.18, 0.24]), + Some([0.98, 0.76, 0.20, 0.85]), + ), + KeyframeState::AnimatedOtherFrame => ( + [0.92, 0.64, 0.24, 0.90], + Some([0.92, 0.64, 0.24, 0.12]), + Some([0.92, 0.64, 0.24, 0.45]), + ), + KeyframeState::Static => (self.text_dim, None, None), + }; + let sig = ui.leaf( + part, + ui::Spec { + cursor: Some(winit::window::CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::px(20.0), ui::px(20.0)], + text: Some("◆"), + font_size: Some(10.5), + color: Some(ink), + fill, + border, + hover_fill: Some([0.98, 0.76, 0.22, 0.18]), + radius: 4.0, + center: true, + ..ui::Spec::default() + }, + ); + sig.clicked + } + + #[allow(clippy::too_many_arguments)] + fn toggle_keyframe( + &self, + comp: &mut Comp, + history: &mut CompHistory, + node_id: NodeId, + input_name: &str, + current_frame: f64, + cur_val: f64, + state: KeyframeState, + actions: &mut Vec, + ) { + match state { + KeyframeState::KeyframeAtCurrent => { + if let Some(sp_name) = comp + .node(node_id) + .inputs + .get(input_name) + .and_then(|b| b.source_op.clone()) + { + history.push_snapshot(comp, format!("Delete Keyframe {input_name}")); + if comp.delete_keyframe(&sp_name, current_frame) { + actions.push(InspectorAction::KeyframeEdited(node_id)); + actions.push(InspectorAction::StatusNotice(format!( + "Deleted keyframe on {input_name} @ f{current_frame:.0}" + ))); + } + } + } + KeyframeState::Static | KeyframeState::AnimatedOtherFrame => { + history.push_snapshot(comp, format!("Set Keyframe {input_name}")); + match comp.set_keyframe(node_id, input_name, current_frame, cur_val) { + Ok(_) => { + actions.push(InspectorAction::KeyframeEdited(node_id)); + actions.push(InspectorAction::StatusNotice(format!( + "Keyframed {input_name} = {:.3} @ f{current_frame:.0}", + cur_val + ))); + } + Err(e) => actions.push(InspectorAction::StatusNotice(e)), + } + } + } + } +} + +/// Computes whether an input is static, animated on another frame, or has a keyframe at `frame`. +pub fn keyframe_state(comp: &Comp, node_id: NodeId, input_name: &str, frame: f64) -> KeyframeState { + let Some(sp_name) = comp + .node(node_id) + .inputs + .get(input_name) + .and_then(|b| b.source_op.as_deref()) + else { + return KeyframeState::Static; + }; + let Some(spline) = comp.splines.get(sp_name) else { + return KeyframeState::Static; + }; + if spline.keyframes.iter().any(|kf| (kf.time - frame).abs() < 1e-4) { + KeyframeState::KeyframeAtCurrent + } else if !spline.keyframes.is_empty() { + KeyframeState::AnimatedOtherFrame + } else { + KeyframeState::Static + } +} + +pub fn normalize_slider_fraction(value: f64, min: f64, max: f64) -> f32 { + let span = (max - min).abs().max(1e-6); + ((value - min) / span).clamp(0.0, 1.0) as f32 +} + +pub fn compute_scrub_value(start_val: f64, dx: f32, width: f32, min: f64, max: f64, fine_scale: f64) -> f64 { + let span = (max - min).max(1e-4); + let delta = (f64::from(dx) / f64::from(width.max(40.0))) * span * fine_scale; + (start_val + delta).clamp(min, max) +} + +pub fn format_param_number(v: f64) -> String { + if v.abs() >= 100.0 { + format!("{v:.1}") + } else if v.abs() >= 10.0 { + format!("{v:.2}") + } else { + format!("{v:.3}") + } +} + +pub fn infer_float_range(name: &str, val: f64) -> (f64, f64) { + let lower = name.to_ascii_lowercase(); + if lower.contains("angle") || lower.contains("rotate") { + (-360.0, 360.0) + } else if lower.contains("width") || lower.contains("height") { + if val > 2.0 { + (1.0, (val * 2.0).max(4096.0)) + } else { + (0.0, 2.0) + } + } else if lower.contains("blend") || lower.contains("alpha") || lower.contains("opacity") { + (0.0, 1.0) + } else if lower.contains("size") || lower.contains("blur") || lower.contains("glow") { + (0.0, (val.abs() * 2.0).max(50.0)) + } else if val < 0.0 || val > 1.0 { + let hi = (val.abs() * 2.0).max(10.0); + (-hi, hi) + } else { + (0.0, 1.0) + } +} + +const APPLY_MODES: &[&str] = &[ + "Normal", + "Screen", + "Multiply", + "Overlay", + "Soft Light", + "Hard Light", + "Color Dodge", + "Color Burn", + "Darken", + "Lighten", + "Difference", + "Exclusion", + "Hue", + "Saturation", + "Color", + "Luminosity", +]; + +const BLUR_FILTERS: &[&str] = &["Fast Gaussian", "Gaussian", "Box", "Bartlett", "Multi-box"]; +const CLIPPING_MODES: &[&str] = &["Frame", "Domain", "None"]; +const EDGES_MODES: &[&str] = &["Canvas", "Wrap", "Duplicate", "Mirror"]; +const SHAPE3D_TYPES: &[&str] = &[ + "SurfacePlaneInputs", + "SurfaceSphereInputs", + "SurfaceCubeInputs", + "SurfaceCylinderInputs", + "SurfaceConeInputs", + "SurfaceTorusInputs", +]; + +const fn flt(name: &'static str, label: &'static str, min: f64, max: f64, default: f64) -> ParamSpec { + ParamSpec { + name, + label, + kind: ParamKind::Float { min, max, default, step: 0.01 }, + } +} + +const fn v2(name: &'static str, label: &'static str, min: f64, max: f64, default: [f64; 2]) -> ParamSpec { + ParamSpec { + name, + label, + kind: ParamKind::Vec2 { min, max, default }, + } +} + +const fn boolean(name: &'static str, label: &'static str, default: bool) -> ParamSpec { + ParamSpec { + name, + label, + kind: ParamKind::Bool { default }, + } +} + +const fn fuid( + name: &'static str, + label: &'static str, + options: &'static [&'static str], + default: &'static str, +) -> ParamSpec { + ParamSpec { + name, + label, + kind: ParamKind::Enum { options, default }, + } +} + +/// Curated Fusion 21.1 parameter schemas for major compositor tools. +pub fn schema_for_kind(kind: &str) -> &'static [ParamSpec] { + match kind { + "Merge" => const { &[ + fuid("ApplyMode", "Apply Mode", APPLY_MODES, "Normal"), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + flt("SubMerge", "Subtractive", 0.0, 1.0, 0.0), + v2("Center", "Center", -1.0, 2.0, [0.5, 0.5]), + flt("Size", "Size", 0.0, 5.0, 1.0), + flt("Angle", "Angle", -360.0, 360.0, 0.0), + boolean("FlipHoriz", "Flip Horiz", false), + boolean("FlipVert", "Flip Vert", false), + fuid("Edges", "Edges", EDGES_MODES, "Canvas"), + boolean("PerformDepthMerge", "Depth Merge", false), + ] }, + "Transform" => const { &[ + v2("Center", "Center", -1.0, 2.0, [0.5, 0.5]), + v2("Pivot", "Pivot", -1.0, 2.0, [0.5, 0.5]), + flt("Size", "Size", 0.0, 5.0, 1.0), + flt("Aspect", "Aspect", 0.1, 4.0, 1.0), + flt("Angle", "Angle", -360.0, 360.0, 0.0), + boolean("FlipHoriz", "Flip Horiz", false), + boolean("FlipVert", "Flip Vert", false), + fuid("Edges", "Edges", EDGES_MODES, "Canvas"), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + ] }, + "Blur" => const { &[ + fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"), + boolean("LockXY", "Lock X/Y", true), + flt("XBlurSize", "Blur Size", 0.0, 100.0, 1.0), + flt("YBlurSize", "Y Blur Size", 0.0, 100.0, 1.0), + fuid("ClippingMode", "Clipping", CLIPPING_MODES, "Frame"), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + ] }, + "Glow" => const { &[ + flt("XGlowSize", "Glow Size", 0.0, 100.0, 10.0), + flt("Glow", "Glow", 0.0, 2.0, 0.8), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"), + ] }, + "SoftGlow" => const { &[ + fuid("Filter", "Filter", BLUR_FILTERS, "Fast Gaussian"), + flt("Threshold", "Threshold", 0.0, 1.0, 0.0), + flt("Gain", "Gain", 0.0, 5.0, 2.0), + flt("XGlowSize", "Glow Size", 0.0, 100.0, 10.0), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + ] }, + "BrightnessContrast" => const { &[ + flt("Gain", "Gain", 0.0, 5.0, 1.0), + flt("Lift", "Lift", -1.0, 1.0, 0.0), + flt("Gamma", "Gamma", 0.05, 5.0, 1.0), + flt("Contrast", "Contrast", -1.0, 1.0, 0.0), + flt("Brightness", "Brightness", -1.0, 1.0, 0.0), + flt("Saturation", "Saturation", 0.0, 4.0, 1.0), + boolean("PreDividePostMultiply", "Pre-Div/Post", false), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + ] }, + "ColorCorrector" => const { &[ + flt("WheelSaturation1", "Saturation", 0.0, 4.0, 1.0), + flt("WheelHue1", "Hue", -1.0, 1.0, 0.0), + flt("MasterRGBGain", "Gain", 0.0, 5.0, 1.0), + flt("MasterRGBGamma", "Gamma", 0.05, 5.0, 1.0), + flt("MasterRGBLift", "Lift", -1.0, 1.0, 0.0), + flt("MasterRGBContrast", "Contrast", 0.0, 3.0, 1.0), + flt("MasterRGBBrightness", "Brightness", -1.0, 1.0, 0.0), + boolean("PreDividePostMultiply", "Pre-Div/Post", false), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + ] }, + "Background" => const { &[ + ParamSpec { + name: "TopLeftColor", + label: "Color", + kind: ParamKind::Color { + r: "TopLeftRed", + g: "TopLeftGreen", + b: "TopLeftBlue", + a: Some("TopLeftAlpha"), + default: [0.0, 0.0, 0.0, 1.0], + }, + }, + flt("Width", "Width", 1.0, 7680.0, 1920.0), + flt("Height", "Height", 1.0, 4320.0, 1080.0), + ] }, + "TextPlus" => const { &[ + ParamSpec { + name: "StyledText", + label: "Styled Text", + kind: ParamKind::Text { default: "" }, + }, + ParamSpec { + name: "Font", + label: "Font", + kind: ParamKind::Text { default: "Open Sans" }, + }, + flt("Size", "Size", 0.005, 1.0, 0.08), + flt("Tracking", "Tracking", 0.0, 4.0, 1.0), + v2("Center", "Center", -1.0, 2.0, [0.5, 0.5]), + ParamSpec { + name: "TextColor", + label: "Text Color", + kind: ParamKind::Color { + r: "Red1", + g: "Green1", + b: "Blue1", + a: Some("Alpha1"), + default: [1.0, 1.0, 1.0, 1.0], + }, + }, + flt("Blend", "Blend", 0.0, 1.0, 1.0), + ] }, + "EllipseMask" => const { &[ + flt("Level", "Level", 0.0, 1.0, 1.0), + flt("SoftEdge", "Soft Edge", 0.0, 0.5, 0.0), + flt("BorderWidth", "Border", -0.2, 0.2, 0.0), + boolean("Solid", "Solid", true), + boolean("Invert", "Invert", false), + v2("Center", "Center", -0.5, 1.5, [0.5, 0.5]), + flt("Width", "Width", 0.0, 2.0, 0.5), + flt("Height", "Height", 0.0, 2.0, 0.5), + flt("Angle", "Angle", -360.0, 360.0, 0.0), + ] }, + "RectangleMask" => const { &[ + flt("Level", "Level", 0.0, 1.0, 1.0), + flt("SoftEdge", "Soft Edge", 0.0, 0.5, 0.0), + flt("CornerRadius", "Corner", 0.0, 1.0, 0.0), + boolean("Solid", "Solid", true), + boolean("Invert", "Invert", false), + v2("Center", "Center", -0.5, 1.5, [0.5, 0.5]), + flt("Width", "Width", 0.0, 2.0, 0.5), + flt("Height", "Height", 0.0, 2.0, 0.5), + flt("Angle", "Angle", -360.0, 360.0, 0.0), + ] }, + "Displace" => const { &[ + flt("XRefraction", "X Refract", -1.0, 1.0, 0.0), + flt("YRefraction", "Y Refract", -1.0, 1.0, 0.0), + flt("RefractionStrength", "Strength", -2.0, 2.0, 0.0), + flt("LightAngle", "Light Angle", -360.0, 360.0, 0.0), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + ] }, + "Vortex" => const { &[ + v2("Center", "Center", -0.5, 1.5, [0.5, 0.5]), + flt("Size", "Size", 0.0, 2.0, 0.5), + flt("Angle", "Angle", -720.0, 720.0, 90.0), + flt("Power", "Power", 0.1, 5.0, 1.0), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + ] }, + "FastNoise" => const { &[ + flt("Detail", "Detail", 0.0, 10.0, 2.0), + flt("Contrast", "Contrast", 0.0, 5.0, 1.0), + flt("Brightness", "Brightness", -1.0, 1.0, 0.0), + flt("XScale", "Scale", 0.01, 50.0, 2.0), + flt("Seethe", "Seethe", 0.0, 100.0, 0.0), + flt("SeetheRate", "Seethe Rate", 0.0, 2.0, 0.0), + v2("Center", "Center", -2.0, 3.0, [0.5, 0.5]), + ] }, + "UltraKeyer" => const { &[ + ParamSpec { + name: "KeyColor", + label: "Key Color", + kind: ParamKind::Color { + r: "BackgroundRed", + g: "BackgroundGreen", + b: "BackgroundBlue", + a: None, + default: [0.0, 1.0, 0.0, 1.0], + }, + }, + flt("MatteThresholdLow", "Matte Low", 0.0, 1.0, 0.0), + flt("MatteThresholdHigh", "Matte High", 0.0, 1.0, 1.0), + flt("SpillSuppression", "Spill", 0.0, 1.0, 0.0), + boolean("PostMultiplyImage", "Post-Multiply", true), + flt("Blend", "Blend", 0.0, 1.0, 1.0), + ] }, + "Loader" => const { &[ + flt("GlobalIn", "Global In", 0.0, 10000.0, 0.0), + flt("GlobalOut", "Global Out", 0.0, 10000.0, 100.0), + boolean("Loop", "Loop", false), + boolean("Reverse", "Reverse", false), + ] }, + "Camera3D" => const { &[ + flt("FLength", "Focal Len", 5.0, 200.0, 24.0), + flt("PlaneOfFocus", "Focus Dist", 0.1, 100.0, 5.0), + flt("Transform3DOp.Translate.X", "Trans X", -50.0, 50.0, 0.0), + flt("Transform3DOp.Translate.Y", "Trans Y", -50.0, 50.0, 0.0), + flt("Transform3DOp.Translate.Z", "Trans Z", -50.0, 50.0, 5.0), + flt("Transform3DOp.Rotate.X", "Rot X", -180.0, 180.0, 0.0), + flt("Transform3DOp.Rotate.Y", "Rot Y", -180.0, 180.0, 0.0), + flt("Transform3DOp.Rotate.Z", "Rot Z", -180.0, 180.0, 0.0), + ] }, + "Shape3D" => const { &[ + fuid("Shape", "Shape", SHAPE3D_TYPES, "SurfacePlaneInputs"), + flt("SurfacePlaneInputs.Width", "Width", 0.01, 20.0, 1.0), + flt("SurfacePlaneInputs.Height", "Height", 0.01, 20.0, 1.0), + flt("Transform3DOp.Translate.X", "Trans X", -50.0, 50.0, 0.0), + flt("Transform3DOp.Translate.Y", "Trans Y", -50.0, 50.0, 0.0), + flt("Transform3DOp.Translate.Z", "Trans Z", -50.0, 50.0, 0.0), + flt("Transform3DOp.Scale.X", "Scale", 0.01, 20.0, 1.0), + ] }, + _ => &[], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn curated_schemas_cover_all_major_tools() { + let major = [ + "Merge", + "Transform", + "Blur", + "Glow", + "SoftGlow", + "BrightnessContrast", + "ColorCorrector", + "Background", + "TextPlus", + "EllipseMask", + "RectangleMask", + "Displace", + "Vortex", + "FastNoise", + "UltraKeyer", + "Loader", + "Camera3D", + "Shape3D", + ]; + for tool in major { + let s = schema_for_kind(tool); + assert!(!s.is_empty(), "expected non-empty curated schema for {tool}"); + } + assert!(schema_for_kind("UnknownCustomTool").is_empty()); + } + + #[test] + fn slider_math_and_clamping() { + assert!((normalize_slider_fraction(0.5, 0.0, 1.0) - 0.5).abs() < 1e-6); + assert!((normalize_slider_fraction(-5.0, 0.0, 1.0) - 0.0).abs() < 1e-6); + assert!((normalize_slider_fraction(10.0, 0.0, 1.0) - 1.0).abs() < 1e-6); + + let v = compute_scrub_value(0.5, 50.0, 100.0, 0.0, 1.0, 1.0); + assert!((v - 1.0).abs() < 1e-6); + let v_fine = compute_scrub_value(0.5, 50.0, 100.0, 0.0, 1.0, 0.1); + assert!((v_fine - 0.55).abs() < 1e-6); + } + + #[test] + fn keyframe_state_transitions() { + let src = r#"Composition { + Tools = ordered() { + BC1 = BrightnessContrast { + Inputs = { Gain = Input { Value = 1.0 } }, + }, + }, + }"#; + let mut comp = Comp::from_fusion_str(src).unwrap(); + let bc = comp.find_node("BC1").unwrap(); + assert_eq!(keyframe_state(&comp, bc, "Gain", 10.0), KeyframeState::Static); + + let sp = comp.set_keyframe(bc, "Gain", 10.0, 1.5).unwrap(); + assert_eq!(keyframe_state(&comp, bc, "Gain", 10.0), KeyframeState::KeyframeAtCurrent); + assert_eq!(keyframe_state(&comp, bc, "Gain", 20.0), KeyframeState::AnimatedOtherFrame); + + assert!(comp.delete_keyframe(&sp, 10.0)); + assert_eq!(keyframe_state(&comp, bc, "Gain", 10.0), KeyframeState::Static); + } +} diff --git a/crates/studio/src/main.rs b/crates/studio/src/main.rs index 5010b03ccca5e6123dcd183665f81384f901f2f9..45d7dcf4e511c9e238ee0aaf53b349fccac37efd 100644 --- a/crates/studio/src/main.rs +++ b/crates/studio/src/main.rs @@ -1,15 +1,21 @@ //! Compositor Studio — docked zero-copy `wgpu` Multi-Viewer (`1`/`2`) + Flow + Blender-style Spline Editor //! built on Knife's `draw`, `ui`, `dock`, and `theme::KNIFE` (soft toned quiet iris). +mod add_tool; +mod inspector; + +use add_tool::{AddToolLauncher, ToolEntry}; use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab}; use engine::{AudioPlayer, AudioTrack, CacheMode, Engine, ExportOptions, export_saver_png_sequence}; use flow::{FlowAction, FlowView}; -use model::Comp; +use inspector::{InspectorAction, InspectorState}; +use model::{Comp, CompHistory, NodeId, default_main_input_port}; use spline::{SplineAction, SplineView}; use std::collections::HashMap; use std::error::Error; use std::fs::File; use std::path::{Path, PathBuf}; +use std::process::Command as ProcessCommand; use std::sync::{Arc, mpsc}; use std::time::{Duration, Instant}; use ui::host::{Accessibility, Clipboard, Surface}; @@ -22,12 +28,14 @@ use winit::keyboard::{Key, KeyCode, NamedKey, PhysicalKey}; use winit::window::{CursorIcon, Window, WindowId}; const DEFAULT_COMP: &str = "/Volumes/Project/trees/fusion/20_falling.comp"; -const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline"]; +const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline", "Inspector"]; fn viewer_pane_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("pane-viewer", slot)) } fn viewer_canvas_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("canvas-viewer", slot)) } +fn flow_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-flow") } fn flow_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-flow") } fn spline_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-spline") } +fn inspector_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-inspector") } struct Cli { comp_path: PathBuf, @@ -35,6 +43,7 @@ struct Cli { frame: Option, select_node: Option, dual_viewer: bool, + open_add_tool: bool, } fn parse_cli() -> Cli { @@ -44,6 +53,7 @@ fn parse_cli() -> Cli { let mut frame = None; let mut select_node = None; let mut dual_viewer = false; + let mut open_add_tool = false; let mut i = 1; while i < args.len() { match args[i].as_str() { @@ -63,6 +73,10 @@ fn parse_cli() -> Cli { dual_viewer = true; i += 1; } + "--open-add-tool" => { + open_add_tool = true; + i += 1; + } other if !other.starts_with("--") => { comp_path = PathBuf::from(other); i += 1; @@ -70,7 +84,7 @@ fn parse_cli() -> Cli { _ => i += 1, } } - Cli { comp_path, snapshot, frame, select_node, dual_viewer } + Cli { comp_path, snapshot, frame, select_node, dual_viewer, open_add_tool } } fn main() { @@ -93,14 +107,20 @@ struct Studio { renderer: draw::Renderer, engine: Engine, comp: Comp, - saved_revision: u64, + history: CompHistory, playback: PlaybackClock, + enable_audio: bool, audio_player: Option, audio_rx: Option>>, status_notice: Option<(String, Instant)>, viewers: [ViewerState; 2], flow: FlowView, spline: SplineView, + inspector: InspectorState, + add_tool: AddToolLauncher, + renaming_node: Option, + rename_buf: String, + rename_needs_focus: bool, size: [f32; 2], scale: f32, clock: Instant, @@ -125,6 +145,7 @@ impl Studio { let g_flow = GroupId(2); let g_spline = GroupId(3); let g_v2 = GroupId(4); + let g_inspector = GroupId(5); let top_node = if dual_viewer { DockNode::Split { @@ -148,37 +169,51 @@ impl Studio { DockNode::Group { id: g_v1, tabs: vec!["Viewer 1".to_owned()], preview: None, rest: Default::default() } }; + let left_workspace = DockNode::Split { + id: SplitId(1), + axis: DockAxis::Y, + parts: vec![ + DockPart { share: 0.54, node: top_node, rest: Default::default() }, + DockPart { + share: 0.46, + node: DockNode::Split { + id: SplitId(2), + axis: DockAxis::X, + parts: vec![ + DockPart { + share: 0.52, + node: DockNode::Group { id: g_flow, tabs: vec!["Flow".to_owned()], preview: None, rest: Default::default() }, + rest: Default::default(), + }, + DockPart { + share: 0.48, + node: DockNode::Group { id: g_spline, tabs: vec!["Spline".to_owned()], preview: None, rest: Default::default() }, + rest: Default::default(), + }, + ], + rest: Default::default(), + }, + rest: Default::default(), + }, + ], + rest: Default::default(), + }; + let layout = dock::Layout { root: DockNode::Split { - id: SplitId(1), - axis: DockAxis::Y, + id: SplitId(4), + axis: DockAxis::X, parts: vec![ - DockPart { share: 0.54, node: top_node, rest: Default::default() }, + DockPart { share: 0.76, node: left_workspace, rest: Default::default() }, DockPart { - share: 0.46, - node: DockNode::Split { - id: SplitId(2), - axis: DockAxis::X, - parts: vec![ - DockPart { - share: 0.52, - node: DockNode::Group { id: g_flow, tabs: vec!["Flow".to_owned()], preview: None, rest: Default::default() }, - rest: Default::default(), - }, - DockPart { - share: 0.48, - node: DockNode::Group { id: g_spline, tabs: vec!["Spline".to_owned()], preview: None, rest: Default::default() }, - rest: Default::default(), - }, - ], - rest: Default::default(), - }, + share: 0.24, + node: DockNode::Group { id: g_inspector, tabs: vec!["Inspector".to_owned()], preview: None, rest: Default::default() }, rest: Default::default(), }, ], rest: Default::default(), }, - issued: 5, + issued: 6, rest: Default::default(), }; let mut seen = dock::Seen::default(); @@ -188,6 +223,7 @@ impl Studio { } seen.active.insert(g_flow, "Flow".to_owned()); seen.active.insert(g_spline, "Spline".to_owned()); + seen.active.insert(g_inspector, "Inspector".to_owned()); seen.focused = Some(g_flow); let dock = Dock::new(); @@ -217,6 +253,9 @@ impl Studio { let mut spline = SplineView::new(&ui_theme); spline.set_target_node(&comp, default_sel); + let inspector = InspectorState::new(&ui_theme); + let add_tool = AddToolLauncher::new(); + let (audio_player, audio_rx) = if enable_audio { let player = match AudioPlayer::new() { Ok(p) => Some(p), @@ -225,23 +264,14 @@ impl Studio { None } }; - let rx = comp.audio_filename.as_ref().and_then(|af| { - let p = PathBuf::from(af); - if !p.exists() { - return None; - } - let (tx, rx) = mpsc::channel(); - std::thread::spawn(move || { - let _ = tx.send(AudioTrack::load(&p)); - }); - Some(rx) - }); + let rx = spawn_audio_loader(&comp); (player, rx) } else { (None, None) }; - let saved_revision = comp.revision; + let mut history = CompHistory::new(); + history.mark_saved(&comp); Self { ui, @@ -251,14 +281,20 @@ impl Studio { renderer, engine, comp, - saved_revision, + history, playback, + enable_audio, audio_player, audio_rx, status_notice: None, viewers: [v1, v2], flow, spline, + inspector, + add_tool, + renaming_node: None, + rename_buf: String::new(), + rename_needs_focus: false, size: [1440.0, 900.0], scale: 2.0, clock: Instant::now(), @@ -316,36 +352,199 @@ impl Studio { } } + fn set_notice(&mut self, msg: impl Into) { + self.status_notice = Some((msg.into(), Instant::now())); + } + + fn invalidate_node(&mut self, node: Option) { + if let Some(id) = node { + self.engine.bust_subtree(id); + } else { + self.engine.bust_all_caches(); + } + for v in &mut self.viewers { + v.cached_frames.clear(); + v.dirty = true; + } + } + + fn undo(&mut self) { + let label = self.history.undo_label().unwrap_or("Edit").to_owned(); + if self.history.undo(&mut self.comp) { + self.flow.sanitize_ids(&self.comp); + for slot in [0usize, 1] { + if self.viewers[slot].viewed_node.is_some_and(|id| id.0 >= self.comp.nodes.len()) { + self.viewers[slot].viewed_node = self.comp.default_output_node(); + } + } + self.flow.viewed_nodes = [self.viewers[0].viewed_node, self.viewers[1].viewed_node]; + self.spline.set_target_node(&self.comp, self.flow.primary); + self.renaming_node = None; + self.invalidate_node(None); + self.set_notice(format!("Undo: {label}")); + } else { + self.set_notice("Nothing to undo"); + } + } + + fn redo(&mut self) { + let label = self.history.redo_label().unwrap_or("Edit").to_owned(); + if self.history.redo(&mut self.comp) { + self.flow.sanitize_ids(&self.comp); + for slot in [0usize, 1] { + if self.viewers[slot].viewed_node.is_some_and(|id| id.0 >= self.comp.nodes.len()) { + self.viewers[slot].viewed_node = self.comp.default_output_node(); + } + } + self.flow.viewed_nodes = [self.viewers[0].viewed_node, self.viewers[1].viewed_node]; + self.spline.set_target_node(&self.comp, self.flow.primary); + self.renaming_node = None; + self.invalidate_node(None); + self.set_notice(format!("Redo: {label}")); + } else { + self.set_notice("Nothing to redo"); + } + } + fn save_comp(&mut self) -> Result { let Some(path) = self.comp.path.clone() else { - return Err("comp has no file path to save".to_owned()); + return self.save_comp_as(); }; + self.save_to_path(&path) + } + + fn save_to_path(&mut self, path: &Path) -> Result { self.comp.current_time = self.playback.current_frame; - match self.comp.save_to_file(&path) { + match self.comp.save_to_file(path) { Ok(backup) => { - self.saved_revision = self.comp.revision; + self.comp.path = Some(path.to_path_buf()); + if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) { + self.comp.name = stem.to_owned(); + } + self.history.mark_saved(&self.comp); let msg = match backup { Some(bak) => { eprintln!("Saved {} (backup -> {})", path.display(), bak.display()); - format!("Saved (backup in temp)") + "Saved (backup in temp)".to_owned() } None => { eprintln!("Saved {}", path.display()); - "Saved".to_owned() + format!("Saved {}", self.comp.name) } }; - self.status_notice = Some((msg.clone(), Instant::now())); + self.set_notice(msg.clone()); Ok(msg) } Err(e) => { let err = format!("Save failed: {e}"); eprintln!("{err}"); - self.status_notice = Some((err.clone(), Instant::now())); + self.set_notice(err.clone()); Err(err) } } } + fn save_comp_as(&mut self) -> Result { + let default_name = format!("{}.comp", self.comp.name); + let Some(mut path) = native_save_comp_dialog(&default_name) else { + return Err("Save As cancelled".to_owned()); + }; + if path.extension().is_none() { + path.set_extension("comp"); + } + self.save_to_path(&path) + } + + fn open_comp_dialog(&mut self) { + let Some(path) = native_open_comp_dialog() else { + return; + }; + match Comp::from_fusion_file(&path) { + Ok(new_comp) => { + self.reload_comp(new_comp); + self.set_notice(format!("Opened {}", self.comp.name)); + } + Err(e) => { + let msg = format!("Open failed: {e}"); + eprintln!("{msg}"); + self.set_notice(msg); + } + } + } + + fn reload_comp(&mut self, new_comp: Comp) { + if self.playback.playing { + self.playback.toggle_play(Instant::now()); + self.sync_audio(true, false); + } + self.comp = new_comp; + self.history.clear(); + self.history.mark_saved(&self.comp); + self.engine.bust_all_caches(); + self.playback.init_from_comp(&self.comp); + + let out_node = self.comp.default_output_node(); + for (slot, v) in self.viewers.iter_mut().enumerate() { + v.viewed_node = out_node; + v.cached_frames.clear(); + v.dirty = true; + if slot == 0 { + v.fit(); + } + } + self.flow.reset_for_comp(&self.comp); + self.flow.viewed_nodes = [self.viewers[0].viewed_node, None]; + let default_sel = self + .comp + .nodes + .iter() + .find(|n| !self.comp.node_splines(n.id).is_empty()) + .map(|n| n.id) + .or(out_node); + if let Some(id) = default_sel { + self.flow.selected.insert(id); + self.flow.primary = Some(id); + } + self.spline.set_target_node(&self.comp, default_sel); + self.inspector.reset(); + self.renaming_node = None; + + if self.enable_audio { + if let Some(player) = &mut self.audio_player { + player.set_track(None); + } + self.audio_rx = spawn_audio_loader(&self.comp); + } + } + + fn add_tool_from_entry(&mut self, entry: ToolEntry) { + let prev_sel = self.flow.primary.filter(|id| id.0 < self.comp.nodes.len()); + let pos = self.flow.spawn_position(&self.comp, entry.is_generator); + self.history.push_snapshot(&self.comp, format!("Add {}", entry.display)); + let new_id = self.comp.add_node(entry.kind, None, pos); + if !entry.is_generator { + if let Some(src_id) = prev_sel { + let port = default_main_input_port(entry.kind); + let _ = self.comp.connect_output(src_id, "Output", new_id, port); + } + } + self.flow.selected.clear(); + self.flow.selected.insert(new_id); + self.flow.primary = Some(new_id); + self.spline.set_target_node(&self.comp, Some(new_id)); + self.invalidate_node(Some(new_id)); + self.set_notice(format!("Added {}", self.comp.node(new_id).name)); + } + + fn begin_inline_rename(&mut self, id: NodeId) { + if id.0 >= self.comp.nodes.len() { + return; + } + self.renaming_node = Some(id); + self.rename_buf = self.comp.node(id).name.clone(); + self.rename_needs_focus = true; + } + fn export_saver_pngs(&mut self) -> Result { if self.playback.playing { self.playback.toggle_play(Instant::now()); @@ -393,7 +592,7 @@ impl Studio { } fn window_title(&self) -> String { - let dirty = if self.comp.revision != self.saved_revision { " •" } else { "" }; + let dirty = if self.history.is_dirty(&self.comp) { "*" } else { "" }; if let Some((msg, at)) = &self.status_notice { if at.elapsed() < Duration::from_secs(5) { return format!("Fission — {}{dirty} — {msg}", self.comp.name); @@ -454,17 +653,29 @@ impl Studio { .map(|&name| ui::popup::Item { text: name, ..Default::default() }) .collect(); - let comp_unsaved = self.comp.revision != self.saved_revision; + let comp_unsaved = self.history.is_dirty(&self.comp); + let cur_frame = self.playback.current_frame; + let eval_stats = self.viewers[0].last_stats.clone(); + let can_undo = self.history.can_undo(); + let can_redo = self.history.can_redo(); + let primary_sel = self.flow.primary; let Studio { ui, dock, layout, seen, engine, + comp, + history, playback, viewers, flow, spline, + inspector, + add_tool, + renaming_node, + rename_buf, + rename_needs_focus, size, .. } = self; @@ -473,7 +684,17 @@ impl Studio { let v2_bg = viewers[1].background(); let flow_bg = flow.background(); let spline_bg = spline.background(); + let inspector_bg = inspector.background(); let mut viewer_actions: Vec<(usize, ViewerAction)> = Vec::new(); + let mut inspector_actions: Vec = Vec::new(); + let mut req_open_add_tool = false; + let mut req_undo = false; + let mut req_redo = false; + let mut req_open = false; + let mut req_save = false; + let mut req_save_as = false; + let mut commit_rename: Option<(NodeId, String)> = None; + let mut cancel_rename = false; let mut d = dock.at(layout, seen, &String::clone); let events = d.build( @@ -488,6 +709,7 @@ impl Studio { "Viewer 2" => v2_bg, "Flow" => flow_bg, "Spline" => spline_bg, + "Inspector" => inspector_bg, _ => flow_bg, }; Tab { @@ -513,6 +735,83 @@ impl Studio { Some(viewer_canvas_id(1)) } "Flow" => { + ui.open_as( + flow_pane_id(), + ui::Spec { + size: [ui::fill(), ui::fill()], + axis: ui::Axis::Y, + fill: Some(flow_bg), + ..ui::Spec::default() + }, + ); + // Compact Flow toolbar with `+ Add`, Undo/Redo, Open/Save/Save As, and inline F2 rename + let bar_bg = ui.theme.strip; + ui.open( + "flow-toolbar", + ui::Spec { + size: [ui::fill(), ui::px(28.0)], + axis: ui::Axis::X, + pad: [6.0, 3.0], + gap: 4.0, + fill: Some(bar_bg), + ..ui::Spec::default() + }, + ); + if studio_btn(ui, "flow-add-btn", "+ Add", false).clicked { + req_open_add_tool = true; + } + if studio_btn(ui, "flow-undo-btn", "Undo", can_undo).clicked && can_undo { + req_undo = true; + } + if studio_btn(ui, "flow-redo-btn", "Redo", can_redo).clicked && can_redo { + req_redo = true; + } + if studio_btn(ui, "flow-open-btn", "Open", false).clicked { + req_open = true; + } + if studio_btn(ui, "flow-save-btn", if comp_unsaved { "Save*" } else { "Save" }, comp_unsaved).clicked { + req_save = true; + } + if studio_btn(ui, "flow-saveas-btn", "Save As", false).clicked { + req_save_as = true; + } + if let Some(rn_id) = *renaming_node { + let rn_field_id = flow_pane_id().child(("rename-field", rn_id.0)); + let rn_sig = ui::text_field( + ui, + rn_field_id, + rename_buf, + "Rename node…", + ui::Spec { + size: [ui::px(160.0), ui::px(22.0)], + font_size: Some(11.5), + fill: Some(ui.theme.base), + border: Some(ui.theme.accent), + radius: 4.0, + pad: [6.0, 1.0], + ..ui::Spec::default() + }, + ); + if *rename_needs_focus { + ui.set_focus(Some(rn_field_id)); + *rename_needs_focus = false; + } + for ev in &rn_sig.events { + if let ui::Event::Key { key, .. } = ev { + match key { + Key::Named(NamedKey::Enter) => { + commit_rename = Some((rn_id, rename_buf.trim().to_owned())); + } + Key::Named(NamedKey::Escape) => { + cancel_rename = true; + } + _ => {} + } + } + } + } + ui.close(); // flow-toolbar + let id = ui.open_as( flow_canvas_id(), ui::Spec { @@ -522,6 +821,7 @@ impl Studio { }, ); ui.close(); + ui.close(); // flow_pane_id Some(id) } "Spline" => { @@ -536,12 +836,86 @@ impl Studio { ui.close(); Some(id) } + "Inspector" => { + let acts = inspector.build_ui( + ui, + inspector_pane_id(), + comp, + history, + primary_sel, + cur_frame, + &eval_stats, + ); + inspector_actions.extend(acts); + Some(inspector_pane_id()) + } _ => None, } }, ); + + let picked_tool = add_tool.build_ui(ui, *size); self.ui.end(); + if req_open_add_tool { + self.add_tool.open(); + } + if req_undo { + self.undo(); + } + if req_redo { + self.redo(); + } + if req_open { + self.open_comp_dialog(); + } + if req_save { + let _ = self.save_comp(); + } + if req_save_as { + let _ = self.save_comp_as(); + } + if let Some((rn_id, new_name)) = commit_rename { + self.renaming_node = None; + self.ui.set_focus(Some(flow_canvas_id())); + if !new_name.is_empty() && rn_id.0 < self.comp.nodes.len() && new_name != self.comp.node(rn_id).name { + self.history.push_snapshot(&self.comp, "Rename Node"); + match self.comp.rename_node(rn_id, &new_name) { + Ok(applied) => { + self.spline.set_target_node(&self.comp, self.flow.primary); + self.invalidate_node(Some(rn_id)); + self.set_notice(format!("Renamed to {applied}")); + } + Err(e) => self.set_notice(e), + } + } + } else if cancel_rename { + self.renaming_node = None; + self.ui.set_focus(Some(flow_canvas_id())); + } + if let Some(entry) = picked_tool { + self.add_tool_from_entry(entry); + } + + for a in inspector_actions { + match a { + InspectorAction::ParamEdited(id) => { + self.invalidate_node(Some(id)); + } + InspectorAction::KeyframeEdited(id) => { + self.spline.set_target_node(&self.comp, self.flow.primary); + self.invalidate_node(Some(id)); + } + InspectorAction::NodeRenamed(id) => { + self.spline.set_target_node(&self.comp, self.flow.primary); + self.invalidate_node(Some(id)); + } + InspectorAction::StatusNotice(msg) => { + self.set_notice(msg); + } + } + } + for ev in events { match ev { Event::Close(name) => { @@ -583,7 +957,7 @@ impl Studio { let mods = self.ui.modifiers(); let mut acts = Vec::new(); for ev in sig.events { - acts.extend(self.flow.input(&mut self.comp, ev, rect, ptr, mods)); + acts.extend(self.flow.input(&mut self.comp, &mut self.history, ev, rect, ptr, mods)); } for a in acts { match a { @@ -601,10 +975,17 @@ impl Studio { FlowAction::ClearViewers => { self.clear_viewers(); } - FlowAction::GraphMutated => { - for v in &mut self.viewers { - v.dirty = true; - } + FlowAction::GraphMutated(node) => { + self.invalidate_node(node); + } + FlowAction::OpenAddTool => { + self.add_tool.open(); + } + FlowAction::RequestRename(id) => { + self.begin_inline_rename(id); + } + FlowAction::StatusNotice(msg) => { + self.set_notice(msg); } } } @@ -804,6 +1185,9 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box> { let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm); let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer, false); + if cli.open_add_tool { + studio.add_tool.open(); + } studio.size = [1440.0, 900.0]; studio.scale = 2.0; @@ -878,6 +1262,7 @@ fn run_window(cli: &Cli) -> Result<(), Box> { frame: cli.frame, select_node: cli.select_node.clone(), dual_viewer: cli.dual_viewer, + open_add_tool: cli.open_add_tool, }, host: None, error: None, @@ -939,53 +1324,108 @@ impl WindowHost { } fn input(&mut self, event: ui::Event) { - // Global Cmd+S saves lossless .comp (with temp-folder .bak); Cmd+Shift+R exports Saver PNG sequence! - let (is_cmd_s, is_cmd_shift_r) = match &event { - ui::Event::KeyInput { physical, modifiers, state: ElementState::Pressed, repeat: false, .. } => ( - modifiers.super_key() && !modifiers.shift_key() && *physical == PhysicalKey::Code(KeyCode::KeyS), - modifiers.super_key() && modifiers.shift_key() && *physical == PhysicalKey::Code(KeyCode::KeyR), - ), - ui::Event::Key { key: Key::Character(c), modifiers, .. } => ( - modifiers.super_key() && !modifiers.shift_key() && c.eq_ignore_ascii_case("s"), - modifiers.super_key() && modifiers.shift_key() && c.eq_ignore_ascii_case("r"), - ), - _ => (false, false), + let typing = self.studio.ui.typing(); + // Global file & history shortcuts: Cmd+S, Cmd+Shift+S, Cmd+O, Cmd+Z, Cmd+Shift+Z / Cmd+Y, Cmd+Shift+R + let key_cmd = match &event { + ui::Event::KeyInput { physical, modifiers, state: ElementState::Pressed, repeat: false, .. } => { + let cmd = modifiers.super_key() || modifiers.control_key(); + let shift = modifiers.shift_key(); + if cmd && !shift && *physical == PhysicalKey::Code(KeyCode::KeyS) { + Some("save") + } else if cmd && shift && *physical == PhysicalKey::Code(KeyCode::KeyS) { + Some("save_as") + } else if cmd && !shift && *physical == PhysicalKey::Code(KeyCode::KeyO) { + Some("open") + } else if cmd && !shift && !typing && *physical == PhysicalKey::Code(KeyCode::KeyZ) { + Some("undo") + } else if cmd && shift && !typing && *physical == PhysicalKey::Code(KeyCode::KeyZ) { + Some("redo") + } else if cmd && !shift && !typing && *physical == PhysicalKey::Code(KeyCode::KeyY) { + Some("redo") + } else if cmd && shift && *physical == PhysicalKey::Code(KeyCode::KeyR) { + Some("export") + } else { + None + } + } + ui::Event::Key { key: Key::Character(c), modifiers, .. } => { + let cmd = modifiers.super_key() || modifiers.control_key(); + let shift = modifiers.shift_key(); + if cmd && !shift && c.eq_ignore_ascii_case("s") { + Some("save") + } else if cmd && shift && c.eq_ignore_ascii_case("s") { + Some("save_as") + } else if cmd && !shift && c.eq_ignore_ascii_case("o") { + Some("open") + } else if cmd && !shift && !typing && c.eq_ignore_ascii_case("z") { + Some("undo") + } else if cmd && shift && !typing && c.eq_ignore_ascii_case("z") { + Some("redo") + } else if cmd && !shift && !typing && c.eq_ignore_ascii_case("y") { + Some("redo") + } else if cmd && shift && c.eq_ignore_ascii_case("r") { + Some("export") + } else { + None + } + } + _ => None, }; - if is_cmd_s { - let _ = self.studio.save_comp(); + if let Some(action) = key_cmd { + match action { + "save" => { let _ = self.studio.save_comp(); } + "save_as" => { let _ = self.studio.save_comp_as(); } + "open" => self.studio.open_comp_dialog(), + "undo" => self.studio.undo(), + "redo" => self.studio.redo(), + "export" => { let _ = self.studio.export_saver_pngs(); } + _ => {} + } self.window.set_title(&self.studio.window_title()); self.window.request_redraw(); return; } - if is_cmd_shift_r { - let _ = self.studio.export_saver_pngs(); - self.window.set_title(&self.studio.window_title()); - self.window.request_redraw(); - return; - } - // Global Space toggles playback (synced with audio) and `` ` `` clears both viewers from any focused pane! - let is_space = matches!( - &event, - ui::Event::KeyInput { key: Key::Named(NamedKey::Space), state: ElementState::Pressed, repeat: false, .. } - | ui::Event::Key { key: Key::Named(NamedKey::Space), .. } - ); - if is_space { - self.studio.playback.toggle_play(Instant::now()); - self.studio.sync_audio(true, false); - self.window.request_redraw(); - return; - } - let is_backquote = match &event { - ui::Event::KeyInput { physical: PhysicalKey::Code(KeyCode::Backquote), state: ElementState::Pressed, repeat: false, .. } => true, - ui::Event::Key { key: Key::Character(c), .. } if c.as_str() == "`" || c.as_str() == "~" => true, - _ => false, - }; - if is_backquote { - self.studio.clear_viewers(); - self.window.request_redraw(); - return; + + // Shift+Space opens Add Tool launcher (when not typing in a text field) + if !typing { + let is_shift_space = match &event { + ui::Event::KeyInput { key: Key::Named(NamedKey::Space), modifiers, state: ElementState::Pressed, repeat: false, .. } + | ui::Event::Key { key: Key::Named(NamedKey::Space), modifiers, .. } => { + modifiers.shift_key() && !modifiers.super_key() && !modifiers.control_key() + } + _ => false, + }; + if is_shift_space { + self.studio.add_tool.open(); + self.window.request_redraw(); + return; + } + // Global Space toggles playback (synced with audio) and `` ` `` clears both viewers from any focused pane! + let is_space = match &event { + ui::Event::KeyInput { key: Key::Named(NamedKey::Space), modifiers, state: ElementState::Pressed, repeat: false, .. } + | ui::Event::Key { key: Key::Named(NamedKey::Space), modifiers, .. } => { + !modifiers.shift_key() && !modifiers.super_key() && !modifiers.control_key() + } + _ => false, + }; + if is_space && !self.studio.add_tool.open { + self.studio.playback.toggle_play(Instant::now()); + self.studio.sync_audio(true, false); + self.window.request_redraw(); + return; + } + let is_backquote = match &event { + ui::Event::KeyInput { physical: PhysicalKey::Code(KeyCode::Backquote), state: ElementState::Pressed, repeat: false, .. } => true, + ui::Event::Key { key: Key::Character(c), .. } if c.as_str() == "`" || c.as_str() == "~" => true, + _ => false, + }; + if is_backquote && !self.studio.add_tool.open { + self.studio.clear_viewers(); + self.window.request_redraw(); + return; + } } - if !self.studio.ui.popups_open() && let ui::Event::Key { key, modifiers, .. } = &event { + if !self.studio.ui.popups_open() && !self.studio.add_tool.open && let ui::Event::Key { key, modifiers, .. } = &event { let cmd = match key { Key::Named(NamedKey::Tab) if modifiers.control_key() => { Some(if modifiers.shift_key() { Command::Previous } else { Command::Next }) @@ -1093,3 +1533,75 @@ impl ApplicationHandler for App { event_loop.set_control_flow(ControlFlow::Wait); } } + +fn spawn_audio_loader(comp: &Comp) -> Option>> { + comp.audio_filename.as_ref().and_then(|af| { + let p = PathBuf::from(af); + if !p.exists() { + return None; + } + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(AudioTrack::load(&p)); + }); + Some(rx) + }) +} + +fn studio_btn(ui: &mut ui::Ui, part: impl std::hash::Hash, label: &str, active: bool) -> ui::Signal { + let t = &ui.theme; + let fill = if active { + [t.accent[0], t.accent[1], t.accent[2], 0.24] + } else { + [t.base[0], t.base[1], t.base[2], 0.65] + }; + let border = if active { + [t.accent[0], t.accent[1], t.accent[2], 0.65] + } else { + t.rule + }; + let ink = if active { t.text } else { t.text_dim }; + ui.leaf( + part, + ui::Spec { + cursor: Some(CursorIcon::Pointer), + flags: ui::Flags::CLICKABLE, + size: [ui::fit(), ui::px(22.0)], + text: Some(label), + font_size: Some(11.0), + medium: true, + color: Some(ink), + fill: Some(fill), + border: Some(border), + hover_fill: Some(t.ghost_soft), + hover_border: Some(t.accent), + radius: 5.0, + pad: [7.0, 0.0], + center: true, + ..ui::Spec::default() + }, + ) +} + +fn native_open_comp_dialog() -> Option { + let script = r#"POSIX path of (choose file with prompt "Open Fusion Composition" of type {"comp"})"#; + let out = ProcessCommand::new("osascript").args(["-e", script]).output().ok()?; + if !out.status.success() { + return None; + } + let s = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + if s.is_empty() { None } else { Some(PathBuf::from(s)) } +} + +fn native_save_comp_dialog(default_name: &str) -> Option { + let safe = default_name.replace('"', ""); + let script = format!( + r#"POSIX path of (choose file name with prompt "Save Fusion Composition As" default name "{safe}")"# + ); + let out = ProcessCommand::new("osascript").args(["-e", &script]).output().ok()?; + if !out.status.success() { + return None; + } + let s = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + if s.is_empty() { None } else { Some(PathBuf::from(s)) } +} diff --git a/scripts/fusion_probes.py b/scripts/fusion_probes.py index 4a8e68b987ed6b344e794124150b6a40b821d729..72b95d9c294baf0879d11c71f8827e48fefdc1b2 100644 --- a/scripts/fusion_probes.py +++ b/scripts/fusion_probes.py @@ -1915,6 +1915,91 @@ def build_probe_ultrakey(): return comp_path, "ultrakey", cases +def build_probe_archive_3d(): + """Shale #11 probe: 3D lights/materials/modifiers/Text3D + WandMask + Fuse.Duplicate + Fuse.KScope.""" + grid = generate_grid_chart() + cases = [ + (0, "light_point_mtl_blinn"), + (1, "light_spot_mtl_cook"), + (2, "replace_mtl_tex2d"), + (3, "override3d_hide_cube"), + (4, "duplicate3d_5x"), + (5, "displace3d_plane"), + (6, "text3d_hello"), + (7, "wand_mask_red_quad"), + (8, "fuse_duplicate_4x"), + ] + nodes = [ + make_loader("GridLoader", grid, post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\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, }, }, }, +\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, }, }, }, +\t\t-- f00: LightPoint + MtlBlinn on Sphere +\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, }, }, }, +\t\tSph0 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, MaterialInput = Input { SourceOp = "Blinn0", Source = "MaterialOutput", }, }, }, +\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, }, }, }, +\t\tAmb0 = LightAmbient { Inputs = { Intensity = Input { Value = 0.15, }, }, }, +\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", }, }, }, +\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", }, }, }, +\t\t-- f01: LightSpot + MtlCookTorrance on Plane +\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, }, }, }, +\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", }, }, }, +\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, }, }, }, +\t\tM3D_1 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Pl1", Source = "Output", }, SceneInput2 = Input { SourceOp = "Spot1", Source = "Output", }, SceneInput3 = Input { SourceOp = "CamBase", Source = "Output", }, }, }, +\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", }, }, }, +\t\t-- f02: ReplaceMaterial3D + Texture2DOperator +\t\tTex2 = Texture2DOperator { Inputs = { Input = Input { SourceOp = "GridLoader", Source = "Output", }, }, }, +\t\tSph2 = Shape3D { Inputs = { Shape = Input { Value = FuID { "SurfaceSphereInputs" }, }, }, }, +\t\tRep2 = ReplaceMaterial3D { Inputs = { SceneInput = Input { SourceOp = "Sph2", Source = "Output", }, MaterialInput = Input { SourceOp = "Tex2", Source = "MaterialOutput", }, }, }, +\t\tM3D_2 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Rep2", Source = "Output", }, SceneInput2 = Input { SourceOp = "CamBase", Source = "Output", }, }, }, +\t\tOp_2 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_2", Source = "Output", }, }, }, +\t\t-- f03: Override3D hiding left cube while right cube remains visible +\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, }, }, }, +\t\tOvr3 = Override3D { Inputs = { SceneInput = Input { SourceOp = "CubeL", Source = "Output", }, ["Visibility.DoVisible"] = Input { Value = 1, }, ["Visibility.IsVisible"] = Input { Value = 0, }, }, }, +\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, }, }, }, +\t\tM3D_3 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Ovr3", Source = "Output", }, SceneInput2 = Input { SourceOp = "CubeR", Source = "Output", }, SceneInput3 = Input { SourceOp = "CamBase", Source = "Output", }, }, }, +\t\tOp_3 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_3", Source = "Output", }, }, }, +\t\t-- f04: Duplicate3D 5 copies along X +\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, }, }, }, +\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, }, }, }, +\t\tM3D_4 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Dup4", Source = "Output", }, SceneInput2 = Input { SourceOp = "CamBase", Source = "Output", }, }, }, +\t\tOp_4 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_4", Source = "Output", }, }, }, +\t\t-- f05: Displace3D on subdivided plane +\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", }, }, }, +\t\tDisp5 = Displace3D { Inputs = { SceneInput = Input { SourceOp = "Pl5", Source = "Output", }, Input = Input { SourceOp = "GradBG", Source = "Output", }, Scale = Input { Value = 0.5, }, }, }, +\t\tM3D_5 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Disp5", Source = "Output", }, SceneInput2 = Input { SourceOp = "CamBase", Source = "Output", }, }, }, +\t\tOp_5 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_5", Source = "Output", }, }, }, +\t\t-- f06: Text3D +\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, }, }, }, +\t\tM3D_6 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "T3D_6", Source = "Output", }, SceneInput2 = Input { SourceOp = "CamBase", Source = "Output", }, }, }, +\t\tOp_6 = Renderer3D { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, SceneInput = Input { SourceOp = "M3D_6", Source = "Output", }, }, }, +\t\t-- f07: WandMask selecting top-left red cell of GridLoader +\t\tWand7 = WandMask { Inputs = { Source = Input { SourceOp = "GridLoader", Source = "Output", }, SelectionPoint = Input { Value = { 0.08, 0.92 }, }, SelectionRange = Input { Value = 0.15, }, }, }, +\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", }, }, }, +\t\t-- f08: Fuse.Duplicate 4 copies rotated 30 deg & scaled 0.85 +\t\tSmall8 = Transform { Inputs = { Input = Input { SourceOp = "GridLoader", Source = "Output", }, Size = Input { Value = 0.45, }, }, }, +\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, }, }, },""", + ] + splines = [] + prev = "BlackBG" + for f, _label in cases: + bl = {c[0]: (1.0 if c[0] == f else 0.0) for c in cases} + sname = f"A3D_{f}_Blend" + splines.append(step_spline(sname, bl)) + nodes.append(f"""\t\tSw_{f} = Merge {{ +\t\t\tInputs = {{ +\t\t\t\tBlend = Input {{ SourceOp = "{sname}", Source = "Value", }}, +\t\t\t\tBackground = Input {{ SourceOp = "{prev}", Source = "Output", }}, +\t\t\t\tForeground = Input {{ SourceOp = "Op_{f}", Source = "Output", }}, +\t\t\t}}, +\t\t}},""") + prev = f"Sw_{f}" + nodes.append(make_saver(prev, "archive_3d")) + comp_path = local_root() / "comps" / "probe_archive_3d.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "archive_3d", cases + + def main(): ensure_dirs() which = [a for a in sys.argv[1:] if not a.startswith("--")] or ["merge"] @@ -1933,6 +2018,7 @@ def main(): "vortex_cc": build_probe_vortex_cc, "moon_3d": build_probe_moon_3d, "ultrakey": build_probe_ultrakey, + "archive_3d": build_probe_archive_3d, "glow": build_probe_glow, "text": build_probe_text, "noise_text": build_probe_noise_text, diff --git a/scripts/gen_compatibility.py b/scripts/gen_compatibility.py index 6c9084db92034a14a6d4138d79a28f63b2c1c551..87b76b6ea0208a94b33da43f88c26b3d7c2b9a5e 100755 --- a/scripts/gen_compatibility.py +++ b/scripts/gen_compatibility.py @@ -104,6 +104,8 @@ TOOL_METADATA: Sequence[ToolMeta] = ( ToolMeta("DVE", "Transform, Warp & Framing", "`tier1_b`", "0.1%–0.4%", "2.5D ZYX Euler rotation + perspective homography (`Center`, `ZMove`, `Pivot`, `AlphaMode`)."), ToolMeta("Displace", "Transform, Warp & Framing", "`displace`, `displace_wave`", "0.0%–0.1%", "`XY` refraction (channels, offsets, refraction strength) and `Radial`/`Bump` (`LightPower`, `LightAngle`, `LightChannel` additive directional slope lighting)."), ToolMeta("Vortex", "Transform, Warp & Framing", "`vortex_cc`", "0.0%–0.4%", "Isotropic radial swirl warp (`Center`, `Size`, `Angle`, `Power`, `Blend`, `EffectMask`)."), + ToolMeta("Fuse.Duplicate", "Transform, Warp & Framing", "`archive_3d`", "0.0%–0.4%", "Multi-copy iterative 2D transform composite (`Copies`, `Center`, `Size`, `Angle`, `Gain`, `Blend`, `TimeOffset`, `MergeUnder`)."), + ToolMeta("Fuse.KScope", "Transform, Warp & Framing", "Unit tests", "0.0%", "N-slice radial kaleidoscope mirror (`Slices`, `Center`, `Angle`, `CaptureAngle`, `Scale`, `Edges`)."), ToolMeta("Scale", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Proportional/non-proportional image scaling with resampling filter."), ToolMeta("BetterResize", "Transform, Warp & Framing", "Suite comps", "0.0%–0.2%", "Target pixel-dimension resize (`Width`, `Height`, `KeepAspect`)."), 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] = ( 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."), 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`."), ToolMeta("BitmapMask", "Masks", "`mask_softedge`", "0.0%–0.2%", "GPU image-to-mask extraction (`Alpha`/`Luminance`/`Red`/`Green`/`Blue`/`Saturation`/`Lightness`/`Hue`), `Low`/`High` clip, centered 1:1 alignment, `SoftEdge`, `Invert`, `Level`, `PaintMode`."), + ToolMeta("WandMask", "Masks", "`archive_3d`", "0.0%–0.3%", "Seeded BFS flood-fill wand mask (`Source`, `SelectionPoint`, `SelectionRange`, `ColorSpace`, `SoftEdge`, `Invert`, `Level`, `PaintMode`)."), # Particles 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] = ( ToolMeta("Transform3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "3D translate, rotate (all 6 `RotOrder`s), and scale (`ScaleLock`) transform node."), ToolMeta("ImagePlane3D", "3D Pipeline", "`cam3d`", "0.1%–0.4%", "Textured 3D quad driven by 2D image input or `Mtl*` diffuse texture."), ToolMeta("Shape3D", "3D Pipeline", "`cam3d`, `cam3d_fov`", "0.1%–0.4%", "`Plane`, `Sphere`, `Cylinder` (`StartSweep`/`EndSweep`, subdivisions), and `Cube` procedural geometry."), + ToolMeta("Text3D", "3D Pipeline", "`archive_3d`", "Visual*", "3D CoreText rasterized text plane with optional multi-slice `-Z` extrusion (`ExtrusionDepth`, `StyledText`, `Font`, `Style`, `Size`, color)."), ToolMeta("LightAmbient", "3D Pipeline", "Suite comps", "0.1%–0.4%", "Scene ambient RGB light intensity accumulation in `Renderer3D`."), ToolMeta("LightDirectional", "3D Pipeline", "Suite comps", "0.1%–0.4%", "World-oriented directional light (`-Z` emission axis) with RGB intensity in `Renderer3D`."), + ToolMeta("LightPoint", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Positional point light with RGB color, `Intensity`, `DecayType` (`None`/`Linear`/`Quadratic`), and `DecayRate`."), + ToolMeta("LightSpot", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Directional spotlight with `ConeAngle`, `PenumbraAngle`, `Intensity`, RGB color, and `DecayType`."), + 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`)."), + ToolMeta("MtlCookTorrance", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Cook-Torrance 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Diffuse.Color.Material`, `Specular.Roughness/Color/Intensity`)."), + ToolMeta("MtlPhong", "3D Pipeline", "`archive_3d`", "0.1%–0.8%", "Phong 3D material (`Diffuse.Color`, `Diffuse.Opacity`, `Specular.Color/Intensity/Exponent`)."), + ToolMeta("Texture2DOperator", "3D Pipeline", "`archive_3d`", "0.0%–0.4%", "2D-image-to-3D-material adapter feeding `MaterialInput` or `Diffuse.Color.Material`."), + ToolMeta("ReplaceMaterial3D", "3D Pipeline", "`archive_3d`", "0.0%–0.4%", "Subtree 3D material override (`SceneInput` + `MaterialInput`)."), + ToolMeta("Override3D", "3D Pipeline", "`archive_3d`", "0.0%–0.2%", "Subtree 3D visibility (`Visibility.DoVisible`/`IsVisible`) and lighting (`Lighting.DoAffectedByLights`/`IsAffectedByLights`) override."), + ToolMeta("Duplicate3D", "3D Pipeline", "`archive_3d`", "0.1%–0.5%", "Cumulative 3D scene instancer (`FirstCopy..LastCopy`, `Transform3DOp`, seeded `JitterTranslate`/`JitterRotate`)."), + ToolMeta("ReplaceNormals3D", "3D Pipeline", "`archive_3d`", "0.0%–0.4%", "Subtree normal orientation override (`FlipNormals`)."), + ToolMeta("Displace3D", "3D Pipeline", "`archive_3d`", "0.2%–1.5%", "Heightmap vertex displacement along mesh normals (`Input`, `Scale`, `Bias`, `Channel`) with smooth normal recomputation."), # Time, Routing & Utility 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] = ( UnsupportedMeta("PlanarTracker", "Preserved lossless on save; passes through main image input in Flow.", 7), UnsupportedMeta("Dimension.CopyAux", "Preserved lossless on save; passes through main image input.", None), UnsupportedMeta("SurfaceFBXMesh", "Preserved lossless on save; FBX mesh geometry not yet imported in `Renderer3D`.", None), - UnsupportedMeta("Text3D", "Preserved lossless on save; extruded 3D text mesh not yet implemented in `Renderer3D`.", None), - UnsupportedMeta("MtlBlinn", "Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Blinn specular/bump pending).", None), - UnsupportedMeta("MtlCookTorrance", "Preserved lossless on save; basic diffuse color & texture resolved in `Renderer3D` (full Cook-Torrance BRDF pending).", None), - UnsupportedMeta("WandMask", "Preserved lossless on save; flood-fill wand mask not yet implemented.", None), - UnsupportedMeta("ReplaceMaterial3D", "Preserved lossless on save; 3D material override not yet traversed in `Renderer3D`.", None), - UnsupportedMeta("Override3D", "Preserved lossless on save; 3D render-flag override not yet traversed in `Renderer3D`.", None), - UnsupportedMeta("Displace3D", "Preserved lossless on save; vertex displacement not yet implemented in `Renderer3D`.", None), ) @@ -217,7 +225,7 @@ def parse_eval_rs(path: Path) -> Set[str]: def parse_scene3d_rs(path: Path) -> Set[str]: - """Extract all supported 3D tool class names from collect_scene in scene3d.rs.""" + """Extract all supported 3D tool class names from collect_scene & resolve_material in scene3d.rs.""" text = path.read_text(encoding="utf-8") m = re.search(r"match node\.kind\.as_str\(\)\s*\{(.*?)\n _ => \{\}", text, re.S) if not m: @@ -227,6 +235,12 @@ def parse_scene3d_rs(path: Path) -> Set[str]: if line.startswith(' "') and "=>" in line: lhs = line.split("=>", 1)[0] tools.update(re.findall(r'"([^"]+)"', lhs)) + mm = re.search(r"match n\.kind\.as_str\(\)\s*\{(.*?)\n _ =>", text, re.S) + if mm: + for line in mm.group(1).splitlines(): + if line.startswith(' "') and "=>" in line: + lhs = line.split("=>", 1)[0] + tools.update(re.findall(r'"([^"]+)"', lhs)) return tools -- 2.54.1