From e425cbbc6a0f2456b92ab401b458ae1f44826f6f Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 02:57:14 -0800 Subject: [PATCH] engine: native SwitchElse, CheckerPieceGenerator, AlphaWeightedNoise, Crystallize fuses Ports Clover's four custom Fuses with GPU compute shaders (archive_fx.wgsl), CheckerPieceGenerator's ExtraScale output resolved in Comp::eval_number, catalog entries, and GPU/model unit tests. Assisted-by: claude-sonnet-5.5 --- crates/app/src/add_tool.rs | 5 + crates/engine/src/eval/fuses.rs | 432 ++++++++++++++++++++++ crates/engine/src/eval/mod.rs | 12 +- crates/engine/src/eval/registry.rs | 17 +- crates/engine/src/shaders/archive_fx.wgsl | 95 +++++ crates/model/src/comp.rs | 8 +- crates/model/src/comp/eval.rs | 53 +++ 7 files changed, 614 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/eval/fuses.rs diff --git a/crates/app/src/add_tool.rs b/crates/app/src/add_tool.rs index d1be3494212de03c0110a90485d3e83238fded5a..bcbb2389b9a82d32f438502b376b91babdde4963 100644 --- a/crates/app/src/add_tool.rs +++ b/crates/app/src/add_tool.rs @@ -68,11 +68,13 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ 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 }, + ToolEntry { kind: "Fuse.CheckerPieceGenerator", display: "Checker Piece", aliases: "checkerboard checker tile squares", 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: "Fuse.SwitchElse", display: "Switch Else", aliases: "sw select fallback default", 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 @@ -86,6 +88,7 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ 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 }, + ToolEntry { kind: "Fuse.AlphaWeightedNoise", display: "Alpha Weighted Noise", aliases: "awn dither stipple random alpha", 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 }, @@ -117,6 +120,7 @@ pub const TOOL_CATALOG: &[ToolEntry] = &[ 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 }, + ToolEntry { kind: "Fuse.Crystallize", display: "Crystallize", aliases: "facet voronoi cells shards", 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 }, @@ -606,6 +610,7 @@ mod tests { "MtlPhong", "MtlCookTorrance", "LightPoint", "LightSpot", "WandMask", "Fuse.Duplicate", "Fuse.KScope", "Fuse.Wireless", "Fuse.Cryptomatte", "Dimension.OpticalFlow", "Dimension.CopyAux", "pBounce", "Custom", "Switch", + "Fuse.SwitchElse", "Fuse.CheckerPieceGenerator", "Fuse.AlphaWeightedNoise", "Fuse.Crystallize", ] { assert!(seen.contains(kind), "catalog is missing {kind}"); } diff --git a/crates/engine/src/eval/fuses.rs b/crates/engine/src/eval/fuses.rs new file mode 100644 index 0000000000000000000000000000000000000000..8dadd59cdd0cacae56177480c973243fda96bb2b --- /dev/null +++ b/crates/engine/src/eval/fuses.rs @@ -0,0 +1,432 @@ +//! Native ports of Clover's custom Fuses: `SwitchElse`, `CheckerPieceGenerator`, +//! `AlphaWeightedNoise`, and `Crystallize`. + +use super::*; + +impl Engine { + pub(super) fn eval_switch_else( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + enc: &mut wgpu::CommandEncoder, + visiting: &mut HashSet<(NodeId, i64)>, + stats: &mut EvalStats, + ) -> CachedTexture { + let index = |name: &str, default: f64| comp.eval_number(node, name, time, default, &self.expr).round().max(1.0) as usize; + let picked = [index("Switch", 1.0), index("Else", 2.0)].into_iter().find_map(|i| { + node.connected_node(&format!("Input{i}")).and_then(|s| comp.find_node(s)) + }); + match picked { + Some(id) => self.eval_node(comp, id, time, enc, visiting, stats), + None => self.dummy.clone(), + } + } + + pub(super) fn eval_checker_piece( + &mut self, + comp: &Comp, + node: &Node, + time: f64, + frame_i: i64, + enc: &mut wgpu::CommandEncoder, + stats: &mut EvalStats, + ) -> CachedTexture { + let (full_size, _) = comp.checker_piece_metrics(node, time, &self.expr); + let edge = (full_size / self.proxy_scale.max(1)).max(1); + let flip = comp.eval_number(node, "Flip", time, 0.0, &self.expr) > 0.5; + let color = |suffix: &str, default: [f64; 3]| { + [ + comp.eval_number(node, &format!("R{suffix}"), time, default[0], &self.expr) as f32, + comp.eval_number(node, &format!("G{suffix}"), time, default[1], &self.expr) as f32, + comp.eval_number(node, &format!("B{suffix}"), time, default[2], &self.expr) as f32, + comp.eval_number(node, &format!("A{suffix}"), time, 1.0, &self.expr) as f32, + ] + }; + let (a, b) = (color("1", [0.0; 3]), color("2", [1.0; 3])); + + let mut u = UniformParams::default(); + (u.p[0], u.p[1]) = if flip { (b, a) } else { (a, b) }; + let depth = self.node_depth(comp, node, time, None); + let size = [edge, edge]; + let key = self.make_key(node, "CheckerPiece", size, &[depth as u64], bytemuck::cast_slice(&u.p[..2])); + if let Some(hit) = self.cache.get(key, node.id, frame_i) { + stats.cache_hits += 1; + return hit; + } + stats.cache_misses += 1; + stats.nodes_evaluated += 1; + let dst = self.alloc_tex(size, depth, key); + self.dispatch_op(enc, ShaderOp::CheckerPiece, &self.dummy.view, &self.dummy.view, &self.dummy.view, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + pub(super) fn eval_alpha_weighted_noise( + &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("Image") + .or_else(|| 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 mut u = UniformParams::default(); + u.p[0] = [ + comp.eval_number(node, "RandomSeed", time, 0.0, &self.expr).round().max(0.0) as f32, + comp.eval_number(node, "Gain", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "Lift", time, 0.0, &self.expr) as f32, + 0.0, + ]; + let key = self.make_key(node, "AlphaWeightedNoise", src.size, &[src.content_hash], bytemuck::cast_slice(&u.p[..1])); + 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); + self.dispatch_op(enc, ShaderOp::AlphaWeightedNoise, &src.view, &self.dummy.view, &self.dummy.view, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } + + pub(super) fn eval_crystallize( + &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 num = |name: &str, default: f64| comp.eval_number(node, name, time, default, &self.expr); + let size = num("Size", 0.025).max(0.001); + let smooth = num("Smooth", 1.0) >= 0.5; + let width = src.canvas_size[0] as f32; + + let mut u = UniformParams::default(); + u.p[0] = [ + size as f32 * width, + (num("Feathering", 0.0).max(0.0) * 0.2).max(1e-4) as f32, + (num("Seethe", 0.0) + num("SeetheRate", 0.02) * time) as f32, + num("RandomSeed", 0.0) as f32, + ]; + u.p[1] = [ + num("Jitter", 1.0).clamp(0.0, 1.0) as f32, + num("Blades", 2.0).round().clamp(1.0, 3.0) as f32, + src.origin[0] as f32, + src.origin[1] as f32, + ]; + u.p[2] = [src.canvas_size[1] as f32, if smooth { 1.0 } else { 0.0 }, 0.0, 0.0]; + + let key = self.make_key(node, "Crystallize", src.size, &[src.content_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 blurred; + let facet_src = if smooth { + // Box about one facet wide, standing in for the facet's average. + let radius = 0.35 * u.p[0][0]; + let tmp = self.alloc_tex_like(&src, src.depth, 0); + blurred = self.alloc_tex_like(&src, src.depth, 0); + for (dir, from, to) in [([1.0, 0.0], &src, &tmp), ([0.0, 1.0], &tmp, &blurred)] { + let mut ub = UniformParams::default(); + ub.p[0] = [dir[0], dir[1], radius, 1.0]; + ub.p[1] = [1.0, 0.0, 0.0, 1.0]; + self.dispatch_op(enc, ShaderOp::Blur, &from.view, &self.dummy.view, &self.dummy.view, to, &ub); + } + &blurred + } else { + &src + }; + + let dst = self.alloc_tex_like(&src, src.depth, key); + self.dispatch_op(enc, ShaderOp::Crystallize, &facet_src.view, &self.dummy.view, &self.dummy.view, &dst, &u); + self.cache.insert(key, dst.clone(), node.id, frame_i); + dst + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn comp(tools: &str) -> Comp { + let src = format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ {tools} }} }}"); + Comp::from_fusion_str(&src).expect("parse comp") + } + + fn bg(name: &str, w: u32, inputs: &str) -> String { + format!("{name} = Background {{ Inputs = {{ Width = Input {{ Value = {w}, }}, Height = Input {{ Value = {w}, }}, {inputs} }}, }},") + } + + /// Renders `name` and returns `(size, rgba8 rows top-down)`; `None` without a GPU adapter. + fn render(comp: &Comp, name: &str, time: f64) -> Option<([u32; 2], Vec)> { + let mut eng = Engine::new_headless().ok()?; + let (tex, _) = eng.evaluate(comp, comp.find_node(name).unwrap(), time); + Some((tex.size, eng.readback_rgba(&tex).unwrap())) + } + + fn px(img: &(Vec, u32), x: u32, y: u32) -> [u8; 4] { + let i = ((y * img.1 + x) * 4) as usize; + img.0[i..i + 4].try_into().unwrap() + } + + #[test] + fn switch_else_prefers_switch_input_then_else_then_dummy() { + let tools = [ + bg("Red", 16, "TopLeftRed = Input { Value = 1, },"), + bg("Green", 16, "TopLeftGreen = Input { Value = 1, },"), + r#"Both = Fuse.SwitchElse { Inputs = { + Input1 = Input { SourceOp = "Red", Source = "Output", }, + Input2 = Input { SourceOp = "Green", Source = "Output", }, + }, }, + ElseOnly = Fuse.SwitchElse { Inputs = { + Input2 = Input { SourceOp = "Green", Source = "Output", }, + }, }, + Swapped = Fuse.SwitchElse { Inputs = { + Switch = Input { Value = 2, }, + Else = Input { Value = 1, }, + Input1 = Input { SourceOp = "Red", Source = "Output", }, + Input2 = Input { SourceOp = "Green", Source = "Output", }, + }, }, + SwappedElse = Fuse.SwitchElse { Inputs = { + Switch = Input { Value = 2, }, + Else = Input { Value = 1, }, + Input1 = Input { SourceOp = "Red", Source = "Output", }, + }, }, + Dangling = Fuse.SwitchElse { Inputs = { + Input1 = Input { SourceOp = "Missing", Source = "Output", }, + Input2 = Input { SourceOp = "Green", Source = "Output", }, + }, }, + Empty = Fuse.SwitchElse { },"# + .to_string(), + ] + .concat(); + let c = comp(&tools); + let color = |name| render(&c, name, 0.0).map(|(size, p)| (size, [p[0], p[1], p[2]])); + let Some(both) = color("Both") else { return }; + assert_eq!(both, ([16, 16], [255, 0, 0])); + assert_eq!(color("ElseOnly").unwrap(), ([16, 16], [0, 255, 0])); + assert_eq!(color("Swapped").unwrap(), ([16, 16], [0, 255, 0])); + assert_eq!(color("SwappedElse").unwrap(), ([16, 16], [255, 0, 0])); + assert_eq!(color("Dangling").unwrap(), ([16, 16], [0, 255, 0])); + assert_eq!(color("Empty").unwrap().0, [1, 1]); + } + + #[test] + fn checker_piece_is_y_up_nearest_2x2_with_flip_and_colors() { + let c = comp( + r#"Plain = Fuse.CheckerPieceGenerator { Inputs = { + Width = Input { Value = 40, }, + Repeat = Input { Value = 5, }, + }, }, + Flipped = Fuse.CheckerPieceGenerator { Inputs = { + Width = Input { Value = 40, }, + Repeat = Input { Value = 5, }, + Flip = Input { Value = 1, }, + R1 = Input { Value = 1, }, G1 = Input { Value = 0, }, B1 = Input { Value = 0, }, A1 = Input { Value = 1, }, + R2 = Input { Value = 0, }, G2 = Input { Value = 0, }, B2 = Input { Value = 1, }, A2 = Input { Value = 0.5, }, + }, }, + Odd = Fuse.CheckerPieceGenerator { Inputs = { + Width = Input { Value = 100, }, + Repeat = Input { Value = 3, }, + }, }, + Floor = Fuse.CheckerPieceGenerator { Inputs = { + Width = Input { Value = 4, }, + Repeat = Input { Value = 10, }, + }, },"#, + ); + let Some((size, rgba)) = render(&c, "Plain", 0.0) else { return }; + // 40 / 5 = 8 px tiles; A = black bottom-left & top-right, B = white top-left & bottom-right. + assert_eq!(size, [8, 8]); + let img = (rgba, 8); + let [top_left, top_right, bottom_left, bottom_right] = + [(0, 0), (7, 0), (0, 7), (7, 7)].map(|(x, y)| px(&img, x, y)); + assert_eq!([top_left, bottom_right], [[255; 4]; 2]); + assert_eq!([top_right, bottom_left], [[0, 0, 0, 255]; 2]); + // Nearest-neighbor: the quadrant seams sit exactly at the midlines. + assert_eq!([px(&img, 3, 3), px(&img, 4, 3), px(&img, 3, 4), px(&img, 4, 4)], [top_left, top_right, bottom_left, bottom_right]); + + let (_, rgba) = render(&c, "Flipped", 0.0).unwrap(); + let img = (rgba, 8); + // Flip swaps A and B: B (blue, half alpha) now bottom-left & top-right, A (red) top-left & bottom-right. + assert_eq!(px(&img, 0, 0), [255, 0, 0, 255]); + assert_eq!(px(&img, 7, 7), [255, 0, 0, 255]); + assert_eq!(px(&img, 7, 0), [0, 0, 255, 128]); + assert_eq!(px(&img, 0, 7), [0, 0, 255, 128]); + + assert_eq!(render(&c, "Odd", 0.0).unwrap().0, [32, 32]); + assert_eq!(render(&c, "Floor", 0.0).unwrap().0, [2, 2]); + } + + #[test] + fn alpha_weighted_noise_thresholds_alpha_and_unpremultiplies_without_nan() { + let tools = [ + bg("Clear", 64, "TopLeftRed = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 0, },"), + bg("Solid", 64, "TopLeftRed = Input { Value = 0.5, }, TopLeftAlpha = Input { Value = 1, },"), + bg("Half", 64, "TopLeftRed = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 0.5, },"), + r#"ClearNoise = Fuse.AlphaWeightedNoise { Inputs = { + Image = Input { SourceOp = "Clear", Source = "Output", }, + Lift = Input { Value = 1, }, + }, }, + SolidNoise = Fuse.AlphaWeightedNoise { Inputs = { Image = Input { SourceOp = "Solid", Source = "Output", }, }, }, + SolidGone = Fuse.AlphaWeightedNoise { Inputs = { + Image = Input { SourceOp = "Solid", Source = "Output", }, + Gain = Input { Value = 0, }, + }, }, + HalfA = Fuse.AlphaWeightedNoise { Inputs = { Image = Input { SourceOp = "Half", Source = "Output", }, }, }, + HalfAgain = Fuse.AlphaWeightedNoise { Inputs = { Input = Input { SourceOp = "Half", Source = "Output", }, }, }, + HalfB = Fuse.AlphaWeightedNoise { Inputs = { + Image = Input { SourceOp = "Half", Source = "Output", }, + RandomSeed = Input { Value = 7, }, + }, }, + HalfBright = Fuse.AlphaWeightedNoise { Inputs = { + Image = Input { SourceOp = "Half", Source = "Output", }, + Lift = Input { Value = 0.25, }, + }, }, + NoInput = Fuse.AlphaWeightedNoise { },"# + .to_string(), + ] + .concat(); + let c = comp(&tools); + let Some((_, clear)) = render(&c, "ClearNoise", 0.0) else { return }; + assert!(clear.chunks(4).all(|p| p == [0, 0, 0, 255]), "alpha 0 -> 1 has no color to recover, so rgb is 0 rather than NaN"); + assert!(render(&c, "SolidNoise", 0.0).unwrap().1.chunks(4).all(|p| p == [128, 0, 0, 255])); + assert!(render(&c, "SolidGone", 0.0).unwrap().1.chunks(4).all(|p| p == [0, 0, 0, 0])); + + let coverage = |name| { + let (_, px) = render(&c, name, 0.0).unwrap(); + let opaque = px.chunks(4).filter(|p| p[3] == 255).count(); + assert!(px.chunks(4).all(|p| p == [0, 0, 0, 0] || p[3] == 255), "{name}: alpha is binary"); + assert!(px.chunks(4).filter(|p| p[3] == 255).all(|p| p[0] == 128), "{name}: rgb / alpha restored"); + opaque as f32 / 4096.0 + }; + assert!((coverage("HalfA") - 0.5).abs() < 0.05); + assert!((coverage("HalfBright") - 0.75).abs() < 0.05); + let a = render(&c, "HalfA", 0.0).unwrap().1; + assert_eq!(a, render(&c, "HalfA", 1.0).unwrap().1, "deterministic"); + assert_eq!(a, render(&c, "HalfAgain", 0.0).unwrap().1, "`Input` is the fallback main port"); + assert_ne!(a, render(&c, "HalfB", 0.0).unwrap().1, "seed changes the pattern"); + assert_eq!(render(&c, "NoInput", 0.0).unwrap().0, [1, 1]); + } + + fn crystallize_comp(input: &str, crystal: &str) -> Comp { + comp(&format!( + r#"{} Crystal = Fuse.Crystallize {{ Inputs = {{ + Input = Input {{ SourceOp = "Src", Source = "Output", }}, + Size = Input {{ Value = 0.125, }}, + Smooth = Input {{ Value = 0, }}, + Feathering = Input {{ Value = 0, }}, + Jitter = Input {{ Value = 0, }}, + Blades = Input {{ Value = 1, }}, + {crystal} + }}, }},"#, + bg("Src", 64, input) + )) + } + + const H_RAMP: &str = "Type = Input { Value = \"Horizontal\", }, TopRightRed = Input { Value = 1, }, TopRightAlpha = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, },"; + const V_RAMP: &str = "Type = Input { Value = \"Vertical\", }, TopLeftRed = Input { Value = 1, }, TopLeftAlpha = Input { Value = 1, }, BottomLeftAlpha = Input { Value = 1, },"; + + #[test] + fn crystallize_samples_facet_homes_in_fusion_y_up_pixels() { + // 8 px cells, jitter 0: every pixel takes the ramp value at the center of a nearby cell. + for (ramp, horizontal) in [(H_RAMP, true), (V_RAMP, false)] { + let c = crystallize_comp(ramp, ""); + let Some((size, rgba)) = render(&c, "Crystal", 0.0) else { return }; + assert_eq!(size, [64, 64]); + let img = (rgba, 64); + let mut input = std::collections::HashSet::new(); + for y in 12..52 { + for x in 12..52 { + let r = f32::from(px(&img, x, y)[0]) / 255.0; + // Fusion y is up: the vertical ramp is 1 at the top row. + let ramp_at = if horizontal { (x as f32 + 0.5) / 64.0 } else { 1.0 - (y as f32 + 0.5) / 64.0 }; + assert!((r - ramp_at).abs() < 0.2, "({x},{y}) {r} vs {ramp_at}"); + let cell_center = r * 8.0 - 0.5; + assert!((cell_center - cell_center.round()).abs() < 0.05, "({x},{y}) {r} is not a cell center"); + input.insert((r * 255.0).round() as u8); + } + } + assert!(input.len() > 3 && input.len() <= 8, "{} distinct facets", input.len()); + } + } + + #[test] + fn crystallize_seed_seethe_and_blades_change_the_facets() { + let render_with = |extra: &str, time: f64| { + let c = crystallize_comp(H_RAMP, &format!("Jitter = Input {{ Value = 1, }}, SeetheRate = Input {{ Value = 0, }}, {extra}")); + render(&c, "Crystal", time).map(|r| r.1) + }; + let Some(base) = render_with("", 0.0) else { return }; + assert_eq!(base, render_with("", 5.0).unwrap(), "SeetheRate 0 ignores time"); + assert_ne!(base, render_with("RandomSeed = Input { Value = 3, },", 0.0).unwrap()); + assert_ne!(base, render_with("Seethe = Input { Value = 0.3, },", 0.0).unwrap()); + assert_ne!(base, render_with("Blades = Input { Value = 3, },", 0.0).unwrap()); + + let c = crystallize_comp(H_RAMP, "SeetheRate = Input { Value = 0.1, },"); + assert_ne!(render(&c, "Crystal", 0.0).unwrap().1, render(&c, "Crystal", 5.0).unwrap().1, "phase = seethe + rate * time"); + } + + #[test] + fn crystallize_feathering_blends_neighbouring_facets_and_smooth_averages_the_source() { + let c = crystallize_comp(H_RAMP, ""); + let hard = render(&c, "Crystal", 0.0).unwrap().1; + let c = crystallize_comp(H_RAMP, "Feathering = Input { Value = 1, },"); + let feathered = render(&c, "Crystal", 0.0).unwrap().1; + let distinct = |p: &[u8]| p.chunks(4).map(|p| p[0]).collect::>().len(); + assert!(distinct(&feathered) > distinct(&hard) * 2, "feathering mixes facet colors"); + + // Per-pixel alpha noise: facets sampling one texel stay binary-ish, Smooth averages a facet's worth. + let noisy = |smooth| { + comp(&format!( + r#"{} + Noise = Fuse.AlphaWeightedNoise {{ Inputs = {{ Image = Input {{ SourceOp = "Half", Source = "Output", }}, }}, }}, + Crystal = Fuse.Crystallize {{ Inputs = {{ + Input = Input {{ SourceOp = "Noise", Source = "Output", }}, + Size = Input {{ Value = 0.125, }}, + Smooth = Input {{ Value = {smooth}, }}, + }}, }},"#, + bg("Half", 64, "TopLeftAlpha = Input { Value = 0.5, },") + )) + }; + let spread = |smooth| { + let a: Vec = render(&noisy(smooth), "Crystal", 0.0).unwrap().1.chunks(4).map(|p| f32::from(p[3]) / 255.0).collect(); + let mean = a.iter().sum::() / a.len() as f32; + a.iter().map(|v| (v - mean).powi(2)).sum::() / a.len() as f32 + }; + assert!(spread(1) * 3.0 < spread(0), "smooth {} vs raw {}", spread(1), spread(0)); + } + + #[test] + fn crystallize_preserves_flat_images_and_requires_an_input() { + let c = comp(&format!( + r#"{} Crystal = Fuse.Crystallize {{ Inputs = {{ Input = Input {{ SourceOp = "Src", Source = "Output", }}, }}, }}, Bare = Fuse.Crystallize {{ }},"#, + bg("Src", 32, "TopLeftRed = Input { Value = 0.5, }, TopLeftGreen = Input { Value = 0.25, }, TopLeftAlpha = Input { Value = 1, },") + )); + let Some((size, rgba)) = render(&c, "Crystal", 2.0) else { return }; + assert_eq!(size, [32, 32]); + assert!(rgba.chunks(4).all(|p| p == [128, 64, 0, 255]), "default Smooth/Feathering keep a flat field flat"); + assert_eq!(render(&c, "Bare", 0.0).unwrap().0, [1, 1]); + } +} diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index 6f7259f2b0d8c656e6f9e2bae21cca61d424198e..0f501df739bbf66787eca9b8f4f59fb331fd6708 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -15,6 +15,7 @@ mod composite; mod transform; mod color; mod blur_glow; +mod fuses; mod keyers; mod masks; mod paint; @@ -589,6 +590,10 @@ impl Engine { "GridWarp" => self.eval_grid_warp(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), + "Fuse.SwitchElse" => self.eval_switch_else(comp, node, time, enc, visiting, stats), + "Fuse.CheckerPieceGenerator" => self.eval_checker_piece(comp, node, time, frame_i, enc, stats), + "Fuse.AlphaWeightedNoise" => self.eval_alpha_weighted_noise(comp, node, time, frame_i, enc, visiting, stats), + "Fuse.Crystallize" => self.eval_crystallize(comp, node, time, frame_i, enc, visiting, stats), "sRender" => self.eval_s_render(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "sNGon" | "sRectangle" @@ -709,7 +714,8 @@ mod lazy_shader_verify { ShaderOp::UltraKeyer, ShaderOp::Dissolve, ShaderOp::Homography, ShaderOp::ShadowComp, ShaderOp::Plasma, ShaderOp::FilmGrain, ShaderOp::SetDomain, ShaderOp::ChangeDepth, ShaderOp::Vortex, ShaderOp::KScope, ShaderOp::Drip, ShaderOp::Dent, - ShaderOp::PerspectivePos, ShaderOp::DaySky, ShaderOp::GridWarp, + ShaderOp::PerspectivePos, ShaderOp::DaySky, ShaderOp::GridWarp, ShaderOp::CheckerPiece, + ShaderOp::AlphaWeightedNoise, ShaderOp::Crystallize, ]; // Verify starts completely empty (lazy!) assert_eq!(eng.pipelines.borrow().modules.len(), 0); @@ -719,9 +725,9 @@ mod lazy_shader_verify { eng.pipelines_for(BitDepth::Float16).borrow_mut().ensure_pipeline(&eng.device, op); } assert_eq!(eng.pipelines.borrow().modules.len(), 7); - assert_eq!(eng.pipelines.borrow().pipelines.len(), 47); + assert_eq!(eng.pipelines.borrow().pipelines.len(), 50); assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().modules.len(), 7); - assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 47); + assert_eq!(eng.pipelines_for(BitDepth::Float16).borrow().pipelines.len(), 50); } #[test] diff --git a/crates/engine/src/eval/registry.rs b/crates/engine/src/eval/registry.rs index 4f4987fac98a7ce142fee34198eeb692c46b9679..37f98c918d1a54638fb06a181ce61f86da2bdd68 100644 --- a/crates/engine/src/eval/registry.rs +++ b/crates/engine/src/eval/registry.rs @@ -89,6 +89,9 @@ pub(super) enum ShaderOp { PerspectivePos, DaySky, GridWarp, + CheckerPiece, + AlphaWeightedNoise, + Crystallize, } impl ShaderOp { @@ -142,9 +145,14 @@ impl ShaderOp { | Self::UltraKeyer | Self::Plasma => ShaderDomain::KeyersGen, - Self::Drip | Self::Dent | Self::PerspectivePos | Self::DaySky | Self::GridWarp => { - ShaderDomain::ArchiveFx - } + Self::Drip + | Self::Dent + | Self::PerspectivePos + | Self::DaySky + | Self::GridWarp + | Self::CheckerPiece + | Self::AlphaWeightedNoise + | Self::Crystallize => ShaderDomain::ArchiveFx, } } @@ -197,6 +205,9 @@ impl ShaderOp { Self::PerspectivePos => "perspective_pos_op", Self::DaySky => "day_sky_op", Self::GridWarp => "grid_warp_op", + Self::CheckerPiece => "checker_piece_op", + Self::AlphaWeightedNoise => "alpha_weighted_noise_op", + Self::Crystallize => "crystallize_op", } } } diff --git a/crates/engine/src/shaders/archive_fx.wgsl b/crates/engine/src/shaders/archive_fx.wgsl index 1c3516abf9af96e3cf3f4d5ba03e9063052b52a8..e1a2f18e6ac60251e977e2dcc0609dfced307f61 100644 --- a/crates/engine/src/shaders/archive_fx.wgsl +++ b/crates/engine/src/shaders/archive_fx.wgsl @@ -228,3 +228,98 @@ fn grid_warp_op(@builtin(global_invocation_id) gid: vec3) { let m = read_mask(gid.xy, dims, u.p[0].y, u.p[0].z) * u.p[0].x; store_dst(vec2(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0))); } + +// ============================================================================ +// Fuses: CheckerPieceGenerator, AlphaWeightedNoise, Crystallize +// ============================================================================ + +// 6. CheckerPieceGenerator: nearest-neighbor 2x2 board, color A at bottom-left & top-right. +// p[0] = color A (rgba), p[1] = color B (rgba); Flip is pre-applied by swapping A/B. +@compute @workgroup_size(8, 8) +fn checker_piece_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let right = gid.x * 2u >= dims.x; + let bottom = gid.y * 2u >= dims.y; // texture row 0 is the top + store_dst(vec2(gid.xy), select(u.p[1], u.p[0], right != bottom)); +} + +fn pcg_hash(v: u32) -> u32 { + let s = v * 747796405u + 2891336453u; + let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u; + return (w >> 22u) ^ w; +} + +// 7. AlphaWeightedNoise: alpha becomes 0 or 1 with probability `a * gain + lift`. +// p[0] = (seed, gain, lift, 0) +@compute @workgroup_size(8, 8) +fn alpha_weighted_noise_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let src = textureLoad(src_a, vec2(gid.xy), 0); + let rnd = f32(pcg_hash(gid.x + pcg_hash(gid.y + pcg_hash(u32(u.p[0].x)))) >> 8u) / 16777216.0; + let new_a = select(0.0, 1.0, rnd < src.a * u.p[0].y + u.p[0].z); + let rgb = select(vec3(0.0), src.rgb / src.a * new_a, src.a > 1e-6 && new_a > 0.5); + store_dst(vec2(gid.xy), vec4(rgb, new_a)); +} + +fn crystal_hash(c: vec2, n: f32) -> f32 { + let h = sin(c.x * 127.1 + c.y * 311.7 + n * 74.7) * 43758.5453; + return h - floor(h); +} + +// A facet is the union of the Voronoi regions of `blades` seeds spun rigidly about a fixed home. +fn crystal_facet_distance(p: vec2, c: vec2, home: vec2, phase: f32, n: f32, blades: i32) -> f32 { + let a = 6.2831853 * (crystal_hash(c, n + 2.0) + phase) / f32(blades); + let r = 0.12 + 0.13 * crystal_hash(c, n + 3.0); + var d = 1e9; + for (var k = 0; k < blades; k = k + 1) { + let ak = a + 6.2831853 * f32(k) / f32(blades); + let v = home + r * vec2(cos(ak), sin(ak)) - p; + d = min(d, length(v)); + } + return d; +} + +// 8. Crystallize (port of Crystallize.fuse's CrystallizeKernel; Fusion pixel coords are bottom-up). +// p[0] = (size_px, feather, phase, seed) +// p[1] = (jitter, blades, dod_origin_x, dod_origin_y) origin is top-down canvas pixels +// p[2].x = canvas height +@compute @workgroup_size(8, 8) +fn crystallize_op(@builtin(global_invocation_id) gid: vec3) { + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) { return; } + let size = u.p[0].x; + let feather = u.p[0].y; + let phase = u.p[0].z; + let seed = u.p[0].w; + let jitter = u.p[1].x; + let blades = i32(u.p[1].y); + let fdims = vec2(dims); + let origin = vec2(u.p[1].z, u.p[2].x - u.p[1].w - fdims.y); + let px = vec2(f32(gid.x), fdims.y - 1.0 - f32(gid.y)); + let p = (px + origin + 0.5) / size; + let cell = floor(p); + + var homes: array, 25>; + var dist: array; + var dmin = 1e9; + for (var i = 0; i < 25; i = i + 1) { + let c = cell + vec2(f32(i % 5 - 2), f32(i / 5 - 2)); + homes[i] = c + 0.5 + jitter * (vec2(crystal_hash(c, seed), crystal_hash(c, seed + 1.0)) - 0.5); + dist[i] = crystal_facet_distance(p, c, homes[i], phase, seed, blades); + dmin = min(dmin, dist[i]); + } + + var acc = vec4(0.0); + var total = 0.0; + for (var i = 0; i < 25; i = i + 1) { + let w = exp((dmin - dist[i]) / feather); + if (w > 0.001) { + let uv = (homes[i] * size - origin) / fdims; + acc = acc + w * textureSampleLevel(src_a, samp_lin, vec2(uv.x, 1.0 - uv.y), 0.0); + total = total + w; + } + } + store_dst(vec2(gid.xy), acc / total); +} diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index ff1fd141dff3da3fb73248c3a109fc7e59cfa68e..6053d3974265cf4f6a3d2c5cad9e9f79c3cc7db9 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -89,6 +89,7 @@ pub fn is_supported_tool(kind: &str) -> bool { | "TimeSpeed" | "Switch" | "Fuse.Switch" + | "Fuse.SwitchElse" | "Note" | "Underlay" | "StickyNote" @@ -138,6 +139,9 @@ pub fn is_supported_tool(kind: &str) -> bool { | "GridWarp" | "Fuse.Duplicate" | "Fuse.KScope" + | "Fuse.AlphaWeightedNoise" + | "Fuse.CheckerPieceGenerator" + | "Fuse.Crystallize" // 2D vector shape pipeline | "sRender" | "sNGon" @@ -606,12 +610,12 @@ pub fn default_main_input_port(kind: &str) -> &'static str { "Merge" | "Dissolve" | "ChannelBoolean" => "Background", "BitmapMask" => "Image", "Switch" => "Input0", - "Fuse.Switch" => "Input1", + "Fuse.Switch" | "Fuse.SwitchElse" => "Input1", "Merge3D" => "SceneInput1", "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => "SceneInput", "ImagePlane3D" | "TextureTransformOperator" => "MaterialInput", - "Fuse.Colorize" | "Fuse.Outline" => "Image", + "Fuse.Colorize" | "Fuse.Outline" | "Fuse.AlphaWeightedNoise" => "Image", "Custom" => "Image1", "MacroOperator" | "GroupOperator" => "MainInput1", _ => "Input", diff --git a/crates/model/src/comp/eval.rs b/crates/model/src/comp/eval.rs index af163d6c8683560fbe578287b9147e9a82e62a3f..a2064a1524c2fc59b61a0071a384e57c21b7eca8 100644 --- a/crates/model/src/comp/eval.rs +++ b/crates/model/src/comp/eval.rs @@ -142,6 +142,12 @@ impl Comp { if let Some(sp) = self.splines.get(src) { return sp.eval(time); } + if binding.source_output.as_deref() == Some("ExtraScale") { + let checker = self.find_node(src).map(|id| self.node(id)); + if let Some(checker) = checker.filter(|n| n.kind == "Fuse.CheckerPieceGenerator") { + return self.checker_piece_metrics_at(checker, time, expr_engine, depth + 1).1; + } + } if let Some(sh) = self.shakes.get(src) { let axis = match binding.source_output.as_deref() { Some("Y") => 1, @@ -170,6 +176,20 @@ impl Comp { .unwrap_or(default) } + /// `(size, extra_scale)` of a `Fuse.CheckerPieceGenerator`: the even tile edge in pixels and the + /// factor that scales it back to the exact `Width / Repeat` (its `ExtraScale` output). + pub fn checker_piece_metrics(&self, node: &Node, time: f64, expr_engine: &ExprEngine) -> (u32, f64) { + self.checker_piece_metrics_at(node, time, expr_engine, 0) + } + + fn checker_piece_metrics_at(&self, node: &Node, time: f64, expr_engine: &ExprEngine, depth: usize) -> (u32, f64) { + let width = self.eval_number_at(node, "Width", time, f64::from(self.width), expr_engine, depth); + let repeats = self.eval_number_at(node, "Repeat", time, 10.0, expr_engine, depth).max(1.0); + let precise = width / repeats; + let size = ((precise / 2.0).floor() * 2.0).max(2.0); + (size as u32, precise / size) + } + /// Evaluates a 2D point input (`Center`, `Pivot`, etc.) on `node` at `time`. pub fn eval_point( &self, @@ -825,4 +845,37 @@ mod tests { let echo = comp.node(comp.find_node("Echo").unwrap()); assert_eq!(comp.eval_number(echo, "Width", 0.0, -1.0, &engine), 13.0); } + #[test] + fn checker_piece_extra_scale_output_feeds_number_inputs() { + let src = r#"Composition { + Tools = ordered() { + Checker = Fuse.CheckerPieceGenerator { Inputs = { + Width = Input { Value = 100, }, + Repeat = Input { Value = 3, }, + }, }, + Default = Fuse.CheckerPieceGenerator { }, + Tiny = Fuse.CheckerPieceGenerator { Inputs = { + Width = Input { Value = 4, }, + Repeat = Input { Value = 10, }, + }, }, + M = Merge { Inputs = { + Size = Input { SourceOp = "Checker", Source = "ExtraScale", }, + Blend = Input { SourceOp = "Default", Source = "ExtraScale", }, + Angle = Input { SourceOp = "Tiny", Source = "Output", }, + }, }, + } + }"#; + let mut comp = Comp::from_fusion_str(src).unwrap(); + comp.width = 1920; + let engine = ExprEngine::new(); + let m = comp.node(comp.find_node("M").unwrap()); + let node = |n| comp.node(comp.find_node(n).unwrap()); + + assert_eq!(comp.checker_piece_metrics(node("Checker"), 0.0, &engine).0, 32); + assert!((comp.eval_number(m, "Size", 0.0, 1.0, &engine) - 100.0 / 3.0 / 32.0).abs() < 1e-12); + assert_eq!(comp.checker_piece_metrics(node("Default"), 0.0, &engine), (192, 1.0)); + assert_eq!(comp.eval_number(m, "Blend", 0.0, 0.0, &engine), 1.0); + assert_eq!(comp.checker_piece_metrics(node("Tiny"), 0.0, &engine), (2, 0.2)); + assert_eq!(comp.eval_number(m, "Angle", 0.0, 7.0, &engine), 7.0, "non-ExtraScale outputs stay unresolved"); + } } -- 2.54.1