diff --git a/crates/app/src/add_tool.rs b/crates/app/src/add_tool.rs index 375dfdc4a4495a25b1cffc33ea7aec039bed3bd2..34926c7649c4073d3f0800ebaa634e0424493097 100644 --- a/crates/app/src/add_tool.rs +++ b/crates/app/src/add_tool.rs @@ -11,6 +11,7 @@ pub enum ToolCategory { BlurGlow, TransformWarp, Mask, + Shape2D, Particle, Scene3D, Utility, @@ -26,6 +27,7 @@ impl ToolCategory { Self::BlurGlow => "Blur/Glow", Self::TransformWarp => "Transform/Warp", Self::Mask => "Mask", + Self::Shape2D => "Shape", Self::Particle => "Particle", Self::Scene3D => "3D", Self::Utility => "Utility", @@ -41,6 +43,7 @@ impl ToolCategory { 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::Shape2D => [0.52, 0.78, 0.40, 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], @@ -64,12 +67,14 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ 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 }, + ToolEntry { kind: "DaySky", display: "Day Sky", aliases: "sky sun atmosphere preetham hdri", 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 }, + ToolEntry { kind: "Paint", display: "Paint", aliases: "brush stroke clone retouch", 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 }, @@ -84,7 +89,7 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ // 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 }, + ToolEntry { kind: "Fuse.Cryptomatte", display: "Cryptomatte", aliases: "cryptomatte 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 }, @@ -106,11 +111,29 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ 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 }, + ToolEntry { kind: "PerspectivePositioner", display: "Perspective Positioner", aliases: "pp rectify quad corner", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "GridWarp", display: "Grid Warp", aliases: "gw mesh bezier lattice", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "Drip", display: "Drip", aliases: "ripple concentric wave", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "Dent", display: "Dent", aliases: "pinch punch bulge lens", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "Fuse.Duplicate", display: "Duplicate", aliases: "copies repeat array clone", category: ToolCategory::TransformWarp, is_generator: false }, + ToolEntry { kind: "Fuse.KScope", display: "Kaleidoscope", aliases: "kscope mirror slices", 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 }, + ToolEntry { kind: "WandMask", display: "Wand Mask", aliases: "wand magic select flood", category: ToolCategory::Mask, is_generator: false }, + ToolEntry { kind: "PaintMask", display: "Paint Mask", aliases: "brush stroke matte", category: ToolCategory::Mask, is_generator: false }, + // Shape + ToolEntry { kind: "sRender", display: "Shape Render", aliases: "srender rasterize vector shapes", category: ToolCategory::Shape2D, is_generator: false }, + ToolEntry { kind: "sEllipse", display: "Shape Ellipse", aliases: "sellipse vector circle oval", category: ToolCategory::Shape2D, is_generator: true }, + ToolEntry { kind: "sRectangle", display: "Shape Rectangle", aliases: "srect vector box rounded", category: ToolCategory::Shape2D, is_generator: true }, + ToolEntry { kind: "sNGon", display: "Shape NGon", aliases: "sngon vector polygon sides", category: ToolCategory::Shape2D, is_generator: true }, + ToolEntry { kind: "sGrid", display: "Shape Grid", aliases: "sgrid vector cells array", category: ToolCategory::Shape2D, is_generator: true }, + ToolEntry { kind: "sMerge", display: "Shape Merge", aliases: "smerge vector combine", category: ToolCategory::Shape2D, is_generator: false }, + ToolEntry { kind: "sTransform", display: "Shape Transform", aliases: "stransform vector move scale rotate", category: ToolCategory::Shape2D, is_generator: false }, + ToolEntry { kind: "sBoolean", display: "Shape Boolean", aliases: "sbool vector union subtract intersect xor", category: ToolCategory::Shape2D, is_generator: false }, + ToolEntry { kind: "sOutline", display: "Shape Outline", aliases: "soutline vector stroke", category: ToolCategory::Shape2D, 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 }, @@ -121,6 +144,7 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ 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 }, + ToolEntry { kind: "pBounce", display: "pBounce", aliases: "particle collision rebound", 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 }, @@ -130,6 +154,22 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ 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 }, + ToolEntry { kind: "Cube3D", display: "Cube 3D", aliases: "3cu box", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "SurfaceFBXMesh", display: "FBX Mesh", aliases: "3fbx obj import model", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "Text3D", display: "Text 3D", aliases: "3txt extrude title", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "LightPoint", display: "Point Light", aliases: "3pl omni light", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "LightSpot", display: "Spot Light", aliases: "3sl cone light", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "MtlBlinn", display: "Blinn Material", aliases: "blinn specular shader", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "MtlPhong", display: "Phong Material", aliases: "specular shader", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "MtlCookTorrance", display: "Cook-Torrance Material", aliases: "pbr roughness shader", category: ToolCategory::Scene3D, is_generator: true }, + ToolEntry { kind: "Texture2DOperator", display: "Texture 2D", aliases: "3tex image material", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "TextureTransformOperator", display: "Texture Transform", aliases: "uv tile material", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "BumpMap", display: "Bump Map", aliases: "height normal relief", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "ReplaceMaterial3D", display: "Replace Material 3D", aliases: "3rm override shader", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "Override3D", display: "Override 3D", aliases: "3ov visibility lighting", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "Duplicate3D", display: "Duplicate 3D", aliases: "3du instance copies", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "ReplaceNormals3D", display: "Replace Normals 3D", aliases: "3rn flip normals", category: ToolCategory::Scene3D, is_generator: false }, + ToolEntry { kind: "Displace3D", display: "Displace 3D", aliases: "3dp heightmap vertex", category: ToolCategory::Scene3D, is_generator: false }, // 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 }, @@ -140,6 +180,10 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ 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 }, + ToolEntry { kind: "Custom", display: "Custom Tool", aliases: "ct shader expression", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "Fuse.Wireless", display: "Wireless Link", aliases: "wireless jump portal", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "Dimension.OpticalFlow", display: "Optical Flow", aliases: "flow motion vectors retime", category: ToolCategory::Utility, is_generator: false }, + ToolEntry { kind: "Dimension.CopyAux", display: "Copy Aux", aliases: "aux channels passthrough", category: ToolCategory::Utility, is_generator: false }, ]; /// Case-insensitive fuzzy/subsequence scoring for tool search. @@ -549,6 +593,30 @@ mod tests { assert!(res_3d.iter().any(|e| e.kind == "Camera3D")); } + #[test] + fn catalog_kinds_are_unique_and_supported() { + let mut seen = std::collections::HashSet::new(); + for entry in TOOL_CATALOG { + assert!(seen.insert(entry.kind), "duplicate catalog kind {}", entry.kind); + assert!(model::is_supported_tool(entry.kind), "{} is not a supported tool", entry.kind); + } + for kind in [ + "sRender", "sEllipse", "sBoolean", "Paint", "PaintMask", "DaySky", "Drip", "Dent", + "PerspectivePositioner", "GridWarp", "Cube3D", "SurfaceFBXMesh", "MtlBlinn", + "MtlPhong", "MtlCookTorrance", "LightPoint", "LightSpot", "WandMask", + "Fuse.Duplicate", "Fuse.KScope", "Fuse.Wireless", "Fuse.Cryptomatte", + "Dimension.OpticalFlow", "Dimension.CopyAux", "pBounce", "Custom", "Switch", + ] { + assert!(seen.contains(kind), "catalog is missing {kind}"); + } + } + + #[test] + fn cryptomatte_search_yields_exact_fusion_id() { + let res = search_tools("cryptomatte"); + assert_eq!(res[0].kind, "Fuse.Cryptomatte"); + } + #[test] fn non_matching_query_returns_empty() { let res = search_tools("zzzznotatool999"); diff --git a/crates/engine/src/bin/render_check.rs b/crates/engine/src/bin/render_check.rs index 2e6c7b5d95a625cb8a04d52c5645b9a28c825533..b49f041c3907e338e9309a64b6cef86fa1b1bf2d 100644 --- a/crates/engine/src/bin/render_check.rs +++ b/crates/engine/src/bin/render_check.rs @@ -8,7 +8,7 @@ use std::fs::File; use std::path::{Path, PathBuf}; use std::time::Instant; -fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f64, f64), Box> { +fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f64, f64, f64), Box> { let mut ref_img = image::open(ref_path)?.to_rgba8(); if [ref_img.width(), ref_img.height()] != tex_size { ref_img = image::imageops::resize( @@ -21,17 +21,19 @@ fn compute_diff(pixels: &[u8], tex_size: [u32; 2], ref_path: &Path) -> Result<(f let rraw = ref_img.into_raw(); let mut sum_abs = 0u64; let mut sum_sq = 0u64; - let n = (tex_size[0] as u64) * (tex_size[1] as u64) * 3; + let mut alpha_abs = 0u64; + let px = (tex_size[0] as u64) * (tex_size[1] as u64); for (a, b) in pixels.chunks_exact(4).zip(rraw.chunks_exact(4)) { for c in 0..3 { let d = (a[c] as i32 - b[c] as i32).unsigned_abs() as u64; sum_abs += d; sum_sq += d * d; } + alpha_abs += (a[3] as i32 - b[3] as i32).unsigned_abs() as u64; } - let mae = sum_abs as f64 / n as f64; - let rmse = (sum_sq as f64 / n as f64).sqrt(); - Ok((mae, rmse)) + let mae = sum_abs as f64 / (px * 3) as f64; + let rmse = (sum_sq as f64 / (px * 3) as f64).sqrt(); + Ok((mae, rmse, alpha_abs as f64 / px as f64)) } fn write_png(path: &Path, size: [u32; 2], pixels: &[u8]) -> Result<(), Box> { @@ -59,10 +61,10 @@ fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box6} {:>7} {:>7} {:>8} {:>8} {:>7} {}", - "STATUS", "CASE", "FRAME", "MAE%", "RMSE", "WARM_MS", "BUST_MS", "VRAM", "UNSUPPORTED" + "{:<6} {:<20} {:>6} {:>7} {:>7} {:>7} {:>8} {:>8} {:>7} {}", + "STATUS", "CASE", "FRAME", "MAE%", "A_MAE%", "RMSE", "WARM_MS", "BUST_MS", "VRAM", "UNSUPPORTED" ); - eprintln!("{}", "-".repeat(94)); + eprintln!("{}", "-".repeat(102)); for (lineno, raw) in text.lines().enumerate() { let line = raw.trim(); @@ -97,8 +99,9 @@ fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box Result<(), Box6} {:>6.2}% {:>7.2} {:>7.2}ms {:>7.2}ms {:>5.0}MB {:?}", + "{:<6} {:<20} {:>6} {:>6.2}% {:>6.2}% {:>7.2} {:>7.2}ms {:>7.2}ms {:>5.0}MB {:?}", if ok { "PASS" } else { "FAIL" }, case_name, frame as i64, mae_pct, + alpha_mae_pct, rmse, warm.eval_ms, bust.eval_ms, @@ -126,7 +130,7 @@ fn run_suite(manifest_path: &Path, hiq: bool) -> Result<(), Box 0 { std::process::exit(1); @@ -661,9 +665,9 @@ fn main() -> Result<(), Box> { eprintln!("Wrote {} ({}x{})", out_path.display(), tex.size[0], tex.size[1]); } if let Some(rp) = ref_path { - let (mae, rmse) = compute_diff(&pixels, tex.size, &rp)?; + let (mae, rmse, alpha_mae) = compute_diff(&pixels, tex.size, &rp)?; eprintln!( - "Diff vs {} ({}x{}): MAE={mae:.2}/255 ({:.1}%), RMSE={rmse:.2}/255", + "Diff vs {} ({}x{}): MAE={mae:.2}/255 ({:.1}%), A_MAE={alpha_mae:.2}/255, RMSE={rmse:.2}/255", rp.display(), tex.size[0], tex.size[1], diff --git a/scripts/diff_fuzz/matrix.py b/scripts/diff_fuzz/matrix.py index ecdda7733da4bd5b8b15d36ee0e634f34d0f3b8c..364b131ae2b92a2220d28f25ffff9bc600411615 100644 --- a/scripts/diff_fuzz/matrix.py +++ b/scripts/diff_fuzz/matrix.py @@ -1,4 +1,4 @@ -"""Exhaustive edge-case parameter matrix suites (Merge, HDR, masks, color/blur, warps, 3D, misc, paint).""" +"""Exhaustive edge-case parameter matrix suites (Merge, HDR, masks, color/blur, warps, 3D, misc, paint, aspect).""" from typing import Dict, List, Tuple @@ -955,6 +955,62 @@ def build_matrix_paint(assets: Dict[str, str]): return comp_path, "matrix_paint", [(c[0], c[1]) for c in cases] +ASPECT_SIZES = ((320, 180), (180, 320), (321, 181)) + +_ASPECT_SETUP = """\t\tBlackBG = Background { Inputs = { Width = Input { Value = @W@, }, Height = Input { Value = @H@, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\tWhiteFG = Background { Inputs = { Width = Input { Value = @W@, }, Height = Input { Value = @H@, }, TopLeftRed = Input { Value = 0.95, }, TopLeftGreen = Input { Value = 0.75, }, TopLeftBlue = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\tSmallFG = Background { Inputs = { Width = Input { Value = @HW@, }, Height = Input { Value = @HH@, }, TopLeftRed = Input { Value = 0.2, }, TopLeftGreen = Input { Value = 0.8, }, TopLeftBlue = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 1, }, }, },""" + +_ASPECT_CASES = ( + ("BG_Horizontal", 'Background { Inputs = { Width = Input { Value = @W@, }, Height = Input { Value = @H@, }, Type = Input { Value = FuID { "Horizontal" }, }, TopLeftRed = Input { Value = 0.9, }, TopLeftGreen = Input { Value = 0.2, }, TopLeftBlue = Input { Value = 0.1, }, TopLeftAlpha = Input { Value = 1, }, TopRightRed = Input { Value = 0.1, }, TopRightGreen = Input { Value = 0.3, }, TopRightBlue = Input { Value = 0.9, }, TopRightAlpha = Input { Value = 1, }, }, }'), + ("BG_Vertical", 'Background { Inputs = { Width = Input { Value = @W@, }, Height = Input { Value = @H@, }, Type = Input { Value = FuID { "Vertical" }, }, TopLeftRed = Input { Value = 0.9, }, TopLeftGreen = Input { Value = 0.2, }, TopLeftBlue = Input { Value = 0.1, }, TopLeftAlpha = Input { Value = 1, }, BottomLeftRed = Input { Value = 0.1, }, BottomLeftGreen = Input { Value = 0.3, }, BottomLeftBlue = Input { Value = 0.9, }, BottomLeftAlpha = Input { Value = 1, }, }, }'), + ("BG_FourCorner", 'Background { Inputs = { Width = Input { Value = @W@, }, Height = Input { Value = @H@, }, Type = Input { Value = FuID { "Four Corner" }, }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, TopRightGreen = Input { Value = 1, }, TopRightAlpha = Input { Value = 1, }, BottomLeftBlue = Input { Value = 1, }, BottomLeftAlpha = Input { Value = 1, }, BottomRightRed = Input { Value = 1, }, BottomRightGreen = Input { Value = 1, }, BottomRightAlpha = Input { Value = 1, }, }, }'), + ("EllipseMask_Circle", 'Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "@MASK@", Source = "Mask", }, }, }', + 'EllipseMask { Inputs = { MaskWidth = Input { Value = @W@, }, MaskHeight = Input { Value = @H@, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.5, }, SoftEdge = Input { Value = 0.02, }, }, }'), + ("EllipseMask_Rotated", 'Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "@MASK@", Source = "Mask", }, }, }', + 'EllipseMask { Inputs = { MaskWidth = Input { Value = @W@, }, MaskHeight = Input { Value = @H@, }, Center = Input { Value = { 0.4, 0.55 }, }, Width = Input { Value = 0.6, }, Height = Input { Value = 0.3, }, Angle = Input { Value = 30, }, BorderWidth = Input { Value = 0.01, }, }, }'), + ("RectangleMask_Rounded", 'Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "@MASK@", Source = "Mask", }, }, }', + 'RectangleMask { Inputs = { MaskWidth = Input { Value = @W@, }, MaskHeight = Input { Value = @H@, }, Width = Input { Value = 0.6, }, Height = Input { Value = 0.4, }, CornerRadius = Input { Value = 0.1, }, SoftEdge = Input { Value = 0.02, }, }, }'), + ("RectangleMask_Rotated", 'Merge { Inputs = { Background = Input { SourceOp = "BlackBG", Source = "Output", }, Foreground = Input { SourceOp = "WhiteFG", Source = "Output", }, EffectMask = Input { SourceOp = "@MASK@", Source = "Mask", }, }, }', + 'RectangleMask { Inputs = { MaskWidth = Input { Value = @W@, }, MaskHeight = Input { Value = @H@, }, Center = Input { Value = { 0.55, 0.45 }, }, Width = Input { Value = 0.5, }, Height = Input { Value = 0.3, }, Angle = Input { Value = -25, }, }, }'), + ("Transform_Rotation", 'Transform { Inputs = { Input = Input { SourceOp = "Grad", Source = "Output", }, Angle = Input { Value = 30, }, Size = Input { Value = 0.7, }, }, }'), + ("Transform_Rotation_Aspect", 'Transform { Inputs = { Input = Input { SourceOp = "Grad", Source = "Output", }, Center = Input { Value = { 0.6, 0.45 }, }, Pivot = Input { Value = { 0.3, 0.6 }, }, Angle = Input { Value = 28, }, Aspect = Input { Value = 1.5, }, Size = Input { Value = 0.8, }, }, }'), + ("Merge_Center_Size_Angle", 'Merge { Inputs = { Background = Input { SourceOp = "Grad", Source = "Output", }, Foreground = Input { SourceOp = "SmallFG", Source = "Output", }, Center = Input { Value = { 0.65, 0.4 }, }, Size = Input { Value = 0.8, }, Angle = Input { Value = 35, }, }, }'), + ("DVE_Rotation", 'DVE { Inputs = { Input = Input { SourceOp = "Grad", Source = "Output", }, XRotation = Input { Value = 25, }, YRotation = Input { Value = -30, }, ZRotation = Input { Value = 15, }, ZMove = Input { Value = 1.2, }, }, }'), + ("TextPlus_Centered", 'TextPlus { Inputs = { Width = Input { Value = @W@, }, Height = Input { Value = @H@, }, Font = Input { Value = "Liberation Sans", }, Style = Input { Value = "Regular", }, StyledText = Input { Value = "Aspect 321", }, Size = Input { Value = 0.18, }, Center = Input { Value = { 0.5, 0.5 }, }, }, }'), +) + + +def _build_matrix_aspect(w: int, h: int): + """Non-square and odd-dimension canvases: gradients, masks, Transform/Merge/DVE geometry and TextPlus at WxH.""" + sub = {"@W@": str(w), "@H@": str(h), "@HW@": str(w // 2), "@HH@": str(h // 2)} + + def fill(text: str) -> str: + for k, v in sub.items(): + text = text.replace(k, v) + return text + + nodes = [ + fill(_ASPECT_SETUP), + fill(f'\t\tGrad = {_ASPECT_CASES[0][1]},'), + ] + cases: List[Tuple[int, str, str]] = [] + for f, (label, body, *mask) in enumerate(_ASPECT_CASES): + if mask: + nodes.append(fill(f"\t\tMask_{f} = {mask[0]},")) + body = body.replace("@MASK@", f"Mask_{f}") + nodes.append(fill(f"\t\tOp_{f} = {body},")) + cases.append((f, label, f"Op_{f}")) + + prefix = f"matrix_aspect_{w}x{h}" + sw_nodes, sw_splines, out_op = build_switch_chain(cases, "BlackBG", "AS") + nodes.extend(sw_nodes) + nodes.append(make_saver(out_op, prefix)) + comp_path = ensure_dirs() / "comps" / f"{prefix}.comp" + comp_path.write_text(make_comp("\n".join(nodes + sw_splines), len(cases) - 1, w=w, h=h)) + return comp_path, prefix, [(c[0], c[1]) for c in cases] + + MATRIX_BUILDERS = { "matrix_merge_modes": build_matrix_merge_modes, "matrix_hdr_depth": build_matrix_hdr_depth, @@ -964,6 +1020,10 @@ MATRIX_BUILDERS = { "matrix_3d": build_matrix_3d, "matrix_misc": build_matrix_misc, "matrix_paint": build_matrix_paint, + **{ + f"matrix_aspect_{w}x{h}": (lambda assets, w=w, h=h: _build_matrix_aspect(w, h)) + for w, h in ASPECT_SIZES + }, } diff --git a/scripts/diff_fuzz/runner.py b/scripts/diff_fuzz/runner.py index 7613e380c10b0a9ae9c916d7d782418a2f56fc42..bf80d6d383e42bbba3153bd26e74bea4f8a3c688 100644 --- a/scripts/diff_fuzz/runner.py +++ b/scripts/diff_fuzz/runner.py @@ -14,6 +14,7 @@ from .assets import ( ensure_render_check, make_comp, make_saver, + read_png_rgba, build_switch_chain, use_smb, ) @@ -22,6 +23,21 @@ from .fuzzer import FuzzGraph, SplineParam +def alpha_mae_pct(ours_path: Path, gt_path: Path) -> float: + """Mean absolute alpha error as a percentage; GT is nearest-sampled onto our size when they differ.""" + ow, oh, ob = read_png_rgba(ours_path) + gw, gh, gb = read_png_rgba(gt_path) + if (ow, oh) == (gw, gh): + total = sum(abs(a - b) for a, b in zip(ob[3::4], gb[3::4])) + else: + total = sum( + abs(ob[(y * ow + x) * 4 + 3] - gb[(min(gh - 1, int((y + 0.5) * gh / oh)) * gw + min(gw - 1, int((x + 0.5) * gw / ow))) * 4 + 3]) + for y in range(oh) + for x in range(ow) + ) + return total / (ow * oh) / 2.55 + + def run_comp_both( comp_path: Path, prefix: str, @@ -122,6 +138,8 @@ def run_comp_both( gt_p = root / "gt" / f"{prefix}_{f:04d}.png" ours_p = ours_sub / f"{f:04d}.png" m = compute_diff_metrics(ours_p, gt_p) + if "error" not in m: + m["alpha_mae_pct"] = alpha_mae_pct(ours_p, gt_p) m["frame"] = f m["label"] = label results[f] = m @@ -295,11 +313,12 @@ def bisect_failing_graph( def print_table(title: str, rows: List[Dict[str, Any]], threshold_pct: float) -> None: print(f"\n=== {title} ===") - print(f" {'Case':<44s} | {'MAE%':>7s} | {'MAE':>6s} | {'RMSE':>6s} | {'Status'}") - print(f" {'-'*44}-+-{'-'*7}-+-{'-'*6}-+-{'-'*6}-+-{'-'*18}") + print(f" {'Case':<44s} | {'MAE%':>7s} | {'A_MAE%':>7s} | {'MAE':>6s} | {'RMSE':>6s} | {'Status'}") + print(f" {'-'*44}-+-{'-'*7}-+-{'-'*7}-+-{'-'*6}-+-{'-'*6}-+-{'-'*18}") for r in rows: label = str(r.get("label", ""))[:44] mae_pct = r.get("mae_pct", 100.0) + a_pct = r.get("alpha_mae_pct", 0.0) mae = r.get("mae_255", 255.0) rmse = r.get("rmse_255", 255.0) if r.get("error"): @@ -308,7 +327,8 @@ def print_table(title: str, rows: List[Dict[str, Any]], threshold_pct: float) -> status = f"SIZE {r.get('dims_ours')}!={r.get('dims_gt')}" elif mae_pct > threshold_pct: status = "FAIL" + elif a_pct > threshold_pct: + status = "PASS (ALPHA DIFF)" else: status = "PASS" - print(f" {label:<44s} | {mae_pct:6.2f}% | {mae:6.2f} | {rmse:6.2f} | {status}") - + print(f" {label:<44s} | {mae_pct:6.2f}% | {a_pct:6.2f}% | {mae:6.2f} | {rmse:6.2f} | {status}") diff --git a/scripts/gen_compatibility.py b/scripts/gen_compatibility.py index 13a8921b2820ac4ebb33c743cdff9d127b283b46..f0e54fcb1383540daa111121adc1220fcca083d4 100755 --- a/scripts/gen_compatibility.py +++ b/scripts/gen_compatibility.py @@ -17,8 +17,11 @@ from typing import Dict, List, Optional, Sequence, Set, Tuple REPO_ROOT = Path(__file__).resolve().parent.parent EVAL_RS = REPO_ROOT / "crates" / "engine" / "src" / "eval" / "mod.rs" +EVAL_DIR_LABEL = "crates/engine/src/eval/" +SCENE3D_DIR_LABEL = "crates/engine/src/scene3d/" SCENE3D_RS = REPO_ROOT / "crates" / "engine" / "src" / "scene3d" / "collect.rs" COMP_RS = REPO_ROOT / "crates" / "model" / "src" / "comp.rs" +ADD_TOOL_RS = REPO_ROOT / "crates" / "app" / "src" / "add_tool.rs" PROBES_PY = REPO_ROOT / "scripts" / "fusion_probes.py" DEFAULT_OUTPUT = REPO_ROOT / "compatibility.md" @@ -37,6 +40,16 @@ class ToolMeta: aliases: Tuple[str, ...] = () +# Supported tools intentionally absent from the Add Tool launcher: created by other +# tools or by grouping, or a duplicate spelling of a listed tool. +ADD_TOOL_EXCLUDED: Set[str] = { + "PolylineStroke", # created by Paint + "Multistroke", # created by Paint + "MacroOperator", # created by grouping + "GroupOperator", # created by grouping + "Fuse.Switch", # Switch covers it +} + CATEGORIES: Sequence[str] = ( "Generators", "Compositing & Blending", @@ -52,7 +65,7 @@ CATEGORIES: Sequence[str] = ( ) # Structured metadata for every supported Flow tool. -# Any tool discovered in eval.rs / scene3d.rs that is missing here will be +# Any tool discovered in eval/ or scene3d/ that is missing here will be # flagged automatically so compatibility.md never drifts stale. TOOL_METADATA: Sequence[ToolMeta] = ( # Generators @@ -190,7 +203,7 @@ TOOL_METADATA: Sequence[ToolMeta] = ( ToolMeta("MacroOperator", "Time, Routing & Utility", "Suite comps", "0.0%", "Unpacks internal `Tools` subgraph and evaluates exported output seamlessly."), ToolMeta("GroupOperator", "Time, Routing & Utility", "Suite comps", "0.0%", "Unpacks internal `Tools` subgraph and evaluates exported output seamlessly."), ToolMeta("Custom", "Time, Routing & Utility", "Suite comps", "0.1%–0.6%", "Custom Tool shader evaluation (procedural wave/channel expressions + `UserControls` defaults)."), - ToolMeta("Note", "Time, Routing & Utility", "—", "N/A", "Non-rendering Flow sticky note; preserved losslessly on `.comp` roundtrip."), + ToolMeta("Note", "Time, Routing & Utility", "—", "N/A", "Non-rendering Flow sticky note; preserved losslessly on `.comp` roundtrip.", aliases=("StickyNote",)), ToolMeta("Underlay", "Time, Routing & Utility", "—", "N/A", "Non-rendering Flow backdrop/group box; preserved losslessly on `.comp` roundtrip."), ) @@ -231,7 +244,7 @@ UNSUPPORTED_NOTES: Sequence[UnsupportedMeta] = ( def parse_eval_rs(path: Path) -> Set[str]: - """Extract all supported tool class names from eval_node_inner in eval.rs.""" + """Extract all supported tool class names from eval_node_inner in eval/mod.rs.""" text = path.read_text(encoding="utf-8") m = re.search(r"fn eval_node_inner\b.*?(?=\n fn |\n\})", text, re.S) if not m: @@ -250,24 +263,52 @@ def parse_eval_rs(path: Path) -> Set[str]: return tools +def _top_level_match_arms(text: str, header: str) -> Set[str]: + """String literals in the arm patterns of the first `match` whose header regex matches. + + Tracks brace depth instead of source indentation, so arms are found at any nesting. + """ + m = re.search(header, text, re.S) + if not m: + raise RuntimeError(f"Could not locate match header /{header}/") + names: Set[str] = set() + depth = 1 + pattern = "" + for line in text[m.end():].splitlines(): + code = re.sub(r'"(?:[^"\\]|\\.)*"', '""', line) + if depth == 1: + pattern += line + "\n" + if "=>" in line: + names.update(re.findall(r'"([^"]+)"', pattern.split("=>", 1)[0])) + pattern = "" + depth += code.count("{") - code.count("}") + if depth <= 0: + break + if depth > 1: + pattern = "" + return names + + def parse_scene3d_rs(path: Path) -> Set[str]: - """Extract all supported 3D tool class names from collect_scene & resolve_material in scene3d.rs.""" + """Extract supported 3D tool class names from the scene collection and material-resolution matches.""" text = path.read_text(encoding="utf-8") - m = re.search(r"match node\.kind\.as_str\(\)\s*\{(.*?)\n _ => \{\}", text, re.S) + return _top_level_match_arms(text, r"match node\.kind\.as_str\(\)\s*\{") | _top_level_match_arms( + text, r"fn resolve_material_inner\b.*?match n\.kind\.as_str\(\)\s*\{" + ) + + +def parse_is_supported_tool(path: Path) -> Set[str]: + """Return every class name accepted by `is_supported_tool` in comp.rs.""" + text = path.read_text(encoding="utf-8") + m = re.search(r"fn is_supported_tool\b.*?matches!\(\s*kind,(.*?)\n \)", text, re.S) if not m: - raise RuntimeError(f"Could not locate collect_scene match in {path}") - tools: Set[str] = set() - for line in m.group(1).splitlines(): - 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 + raise RuntimeError(f"Could not locate is_supported_tool in {path}") + return set(re.findall(r'"([^"]+)"', re.sub(r"//[^\n]*", "", m.group(1)))) + + +def parse_add_tool_catalog(path: Path) -> Set[str]: + """Return every `kind` listed in TOOL_CATALOG of add_tool.rs.""" + return set(re.findall(r'ToolEntry\s*\{\s*kind:\s*"([^"]+)"', path.read_text(encoding="utf-8"))) def parse_comp_rs_modifiers(path: Path) -> Tuple[List[str], Set[str]]: @@ -296,34 +337,45 @@ def parse_probe_suites(path: Path) -> Set[str]: return set(re.findall(r'"([^"]+)"\s*:', m.group(1))) -TOOLS_START_RE = re.compile(r"(?m)^\tTools\s*=\s*(?:ordered\(\)\s*)?\{") -TOP_TOOL_RE = re.compile( - r'^\t\t(?:\["[^"]+"\]|[A-Za-z_][A-Za-z0-9_]*)\s*=\s*([A-Za-z_][A-Za-z0-9_.]*)\s*\{' +TOOL_RE = re.compile( + r'^(\t+)(?:\["[^"]+"\]|[A-Za-z_][A-Za-z0-9_]*)\s*=\s*([A-Za-z_][A-Za-z0-9_.]*)\s*\{' ) +TOOLS_BLOCK_RE = re.compile(r"^(\t+)Tools\s*=\s*(?:ordered\(\)\s*)?\{") + + +def count_tool_classes(text: str) -> Counter[str]: + """Count tool classes in every `Tools` block, including those nested in Macro/Group operators.""" + counts: Counter[str] = Counter() + block_indents: List[int] = [] # tab depth of each open Tools block + for line in text.splitlines(): + stripped = line.lstrip("\t") + depth = len(line) - len(stripped) + if block_indents and depth <= block_indents[-1] and stripped.startswith("}"): + block_indents.pop() + continue + if block_indents and depth == block_indents[-1] + 1: + tm = TOOL_RE.match(line) + if tm: + counts[tm.group(2)] += 1 + continue + if TOOLS_BLOCK_RE.match(line): + block_indents.append(depth) + return counts def scan_comp_corpus(root: Path) -> Optional[Tuple[int, Counter[str]]]: - """Lightweight top-level tool-class scanner over all *.comp files under root.""" + """Tool-class counts over all *.comp files under root.""" if not root.exists(): return None - counts: Counter[str] = Counter() comp_files = sorted(root.rglob("*.comp")) if not comp_files: return None + counts: Counter[str] = Counter() for path in comp_files: try: - text = path.read_text(encoding="utf-8", errors="replace") + counts += count_tool_classes(path.read_text(encoding="utf-8", errors="replace")) except OSError: continue - m = TOOLS_START_RE.search(text) - if not m: - continue - for line in text[m.end():].splitlines(): - if line.startswith("\t}"): - break - tm = TOP_TOOL_RE.match(line) - if tm: - counts[tm.group(1)] += 1 return len(comp_files), counts @@ -359,6 +411,8 @@ def build_markdown( eval_tools: Set[str], scene3d_tools: Set[str], impl_modifiers: Set[str], + comp_supported: Set[str], + catalog_kinds: Set[str], probe_suites: Set[str], active_corpus: Optional[Tuple[int, Counter[str]]], archive_corpus: Optional[Tuple[int, Counter[str]]], @@ -384,7 +438,7 @@ def build_markdown( meta_all_names.update(m.aliases) non_render_tools = {"Note", "Underlay"} - # Detect drift: tools in eval.rs / scene3d.rs not in TOOL_METADATA + # Detect drift: tools in eval/ or scene3d/ not in TOOL_METADATA uncategorized = sorted(live_engine_tools - meta_all_names) for name in uncategorized: warnings.append(f"Uncategorized tool found in engine source: {name}") @@ -392,7 +446,7 @@ def build_markdown( # Detect stale metadata: tools in TOOL_METADATA no longer in engine source (excluding Note/Underlay) stale = sorted((set(meta_by_name.keys()) - non_render_tools) - live_engine_tools) for name in stale: - warnings.append(f"Stale tool in metadata not found in eval.rs/scene3d.rs: {name}") + warnings.append(f"Stale tool in metadata not found in {EVAL_DIR_LABEL} or {SCENE3D_DIR_LABEL}: {name}") # Detect uncategorized modifiers known_mod_classes: Set[str] = set() @@ -402,6 +456,20 @@ def build_markdown( for name in uncategorized_mods: warnings.append(f"Uncategorized modifier found in comp.rs: {name}") + # is_supported_tool() must accept exactly the metadata classes (plus modifier classes). + for name in sorted(comp_supported - meta_all_names - known_mod_classes): + warnings.append(f"is_supported_tool accepts {name} but TOOL_METADATA has no entry") + for name in sorted(((live_engine_tools | non_render_tools) & set(meta_by_name)) - comp_supported): + warnings.append(f"is_supported_tool rejects {name} although the engine evaluates it") + + # Add Tool launcher must offer every user-creatable supported tool and nothing unsupported. + for name in sorted(set(meta_by_name) - ADD_TOOL_EXCLUDED - catalog_kinds): + warnings.append(f"add_tool.rs TOOL_CATALOG is missing {name}") + for name in sorted(catalog_kinds - comp_supported): + warnings.append(f"add_tool.rs TOOL_CATALOG lists {name} which is not supported") + for name in sorted(catalog_kinds & ADD_TOOL_EXCLUDED): + warnings.append(f"add_tool.rs TOOL_CATALOG lists {name} which ADD_TOOL_EXCLUDED omits") + all_supported_tools = live_engine_tools | non_render_tools all_supported_classes = all_supported_tools | impl_modifiers @@ -409,8 +477,8 @@ def build_markdown( lines.append("# Fusion 21.1 Compatibility Matrix") lines.append("") lines.append( - "Auto-generated from live engine sources (`crates/engine/src/eval.rs`, " - "`crates/engine/src/scene3d.rs`, `crates/model/src/comp.rs`) and real Fusion `.comp` corpora " + f"Auto-generated from live engine sources (`{EVAL_DIR_LABEL}`, " + f"`{SCENE3D_DIR_LABEL}`, `crates/model/src/comp.rs`) and real Fusion `.comp` corpora " "via `python3 scripts/gen_compatibility.py`." ) lines.append("") @@ -427,7 +495,7 @@ def build_markdown( lines.append("| --- | --- |") lines.append( f"| **Supported Flow Tools** | **{len(all_supported_tools)}** " - f"({len(eval_tools)} 2D/Fuse/utility in `eval.rs`, {len(scene3d_tools - eval_tools)} 3D scene nodes in `scene3d.rs`, 2 Flow annotations) |" + f"({len(eval_tools)} 2D/Fuse/utility in `{EVAL_DIR_LABEL}`, {len(scene3d_tools - eval_tools)} 3D scene nodes in `{SCENE3D_DIR_LABEL}`, 2 Flow annotations) |" ) lines.append( f"| **Modifiers & Animation** | **{len(MODIFIER_METADATA)}** systems " @@ -470,7 +538,7 @@ def build_markdown( lines.append("## Uncategorized (New in Engine)") lines.append("") lines.append("> [!WARNING]") - lines.append("> The following tools were found in `eval.rs` / `scene3d.rs` but are not yet listed in `TOOL_METADATA` in `scripts/gen_compatibility.py`.") + lines.append(f"> The following tools were found in `{EVAL_DIR_LABEL}` / `{SCENE3D_DIR_LABEL}` but are not yet listed in `TOOL_METADATA` in `scripts/gen_compatibility.py`.") lines.append("") lines.append(f"| Tool | {usage_col} |") lines.append("| --- | --- |") @@ -551,7 +619,7 @@ def main() -> int: parser.add_argument("-o", "--output", type=Path, default=DEFAULT_OUTPUT, help="Output markdown path.") parser.add_argument("--active-dir", type=Path, default=ACTIVE_CORPUS_DIR, help="Active Fusion .comp directory.") parser.add_argument("--archive-dir", type=Path, default=ARCHIVE_CORPUS_DIR, help="Archive Fusion .comp directory.") - parser.add_argument("--strict", action="store_true", help="Exit non-zero if uncategorized or stale tools are found.") + parser.add_argument("--strict", action="store_true", help="Exit non-zero on any registry drift: engine vs TOOL_METADATA vs is_supported_tool vs add_tool.rs.") args = parser.parse_args() eval_tools = parse_eval_rs(EVAL_RS) @@ -566,6 +634,8 @@ def main() -> int: eval_tools=eval_tools, scene3d_tools=scene3d_tools, impl_modifiers=impl_modifiers, + comp_supported=parse_is_supported_tool(COMP_RS), + catalog_kinds=parse_add_tool_catalog(ADD_TOOL_RS), probe_suites=probe_suites, active_corpus=active_corpus, archive_corpus=archive_corpus,