From 0f4304f00f855af055d98da5759c54607d86d905 Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 14:26:31 -0800 Subject: [PATCH] General CustomTool per-pixel expression to WGSL compiler and Expression modifier (#18) --- crates/engine/src/custom_shader.rs | 1296 ++++++++++++++++++++++++++++ crates/engine/src/eval/color.rs | 217 ++++- crates/engine/src/eval/mod.rs | 5 +- crates/engine/src/lib.rs | 1 + crates/model/src/comp.rs | 799 +++++++++++++++++ scripts/fusion_probes.py | 165 ++++ 6 files changed, 2439 insertions(+), 44 deletions(-) create mode 100644 crates/engine/src/custom_shader.rs diff --git a/crates/engine/src/custom_shader.rs b/crates/engine/src/custom_shader.rs new file mode 100644 index 0000000000000000000000000000000000000000..97b577f5b3e134c98d027c35ea9bd5457d72d215 --- /dev/null +++ b/crates/engine/src/custom_shader.rs @@ -0,0 +1,1296 @@ +//! General Fusion `CustomTool` (`Custom`) per-pixel math DSL parser, WGSL codegen, +//! and cached `wgpu::ComputePipeline` compiler/dispatcher. + +use bytemuck::{Pod, Zeroable}; +use std::collections::HashMap; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +/// Uniform payload uploaded per `CustomTool` compute dispatch (4224 bytes, 16-byte aligned). +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub struct CustomParams { + /// `n1, n2, n3, n4` (`NumberIn1..4`, default 0.0) + pub n0: [f32; 4], + /// `n5, n6, n7, n8` (`NumberIn5..8`, default 0.0) + pub n1: [f32; 4], + /// `p1x, p1y, p2x, p2y` (`PointIn1..2`, default 0.5) + pub p0: [f32; 4], + /// `p3x, p3y, p4x, p4y` (`PointIn3..4`, default 0.5) + pub p1: [f32; 4], + /// `w1, h1, w2, h2` (full-resolution image dimensions in pixels) + pub img_dims1: [f32; 4], + /// `w3, h3, time, blend` + pub img_dims2: [f32; 4], + /// `has_mask, mask_invert, proc_r, proc_g` + pub mask_proc: [f32; 4], + /// `proc_b, proc_a, hdr_float, 0.0` + pub proc_ba: [f32; 4], + /// 256-sample baked 1D LUTs for `(LUTIn1, LUTIn2, LUTIn3, LUTIn4)`. + pub luts: [[f32; 4]; 256], +} + +impl Default for CustomParams { + fn default() -> Self { + let mut luts = [[0.0f32; 4]; 256]; + for (i, slot) in luts.iter_mut().enumerate() { + let v = i as f32 / 255.0; + *slot = [v, v, v, v]; + } + Self { + n0: [0.0; 4], + n1: [0.0; 4], + p0: [0.5; 4], + p1: [0.5; 4], + img_dims1: [1.0, 1.0, 1.0, 1.0], + img_dims2: [1.0, 1.0, 0.0, 1.0], + mask_proc: [0.0, 0.0, 1.0, 1.0], + proc_ba: [1.0, 1.0, 0.0, 0.0], + luts, + } + } +} + +/// Normalized expression bundle for a Fusion `CustomTool` node. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct CustomProgram { + pub setups: [String; 4], + pub intermediates: [String; 8], + pub red: String, + pub green: String, + pub blue: String, + pub alpha: String, +} + +impl Default for CustomProgram { + fn default() -> Self { + Self { + setups: std::array::from_fn(|_| "0".to_owned()), + intermediates: std::array::from_fn(|_| "0".to_owned()), + red: "r1".to_owned(), + green: "g1".to_owned(), + blue: "b1".to_owned(), + alpha: "a1".to_owned(), + } + } +} + +impl CustomProgram { + /// Returns a canonicalized copy with comments stripped, whitespace collapsed, and defaults applied. + pub fn normalized(&self) -> Self { + Self { + setups: std::array::from_fn(|i| normalize_expr(&self.setups[i], "0")), + intermediates: std::array::from_fn(|i| normalize_expr(&self.intermediates[i], "0")), + red: normalize_expr(&self.red, "r1"), + green: normalize_expr(&self.green, "g1"), + blue: normalize_expr(&self.blue, "b1"), + alpha: normalize_expr(&self.alpha, "a1"), + } + } + + pub fn program_hash(&self) -> u64 { + let mut h = DefaultHasher::new(); + self.hash(&mut h); + h.finish() + } +} + +/// Strips `//` and `/* */` comments, trims, and collapses ASCII whitespace so `"0\n"` == `"0"`. +pub fn normalize_expr(raw: &str, default: &str) -> String { + let bytes = raw.as_bytes(); + let mut cleaned = String::with_capacity(raw.len()); + let mut i = 0; + let mut last_ws = true; + while i < bytes.len() { + if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'/') { + i += 2; + while i < bytes.len() && bytes[i] != b'\n' { + i += 1; + } + continue; + } + if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') { + i += 2; + while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') { + i += 1; + } + i = (i + 2).min(bytes.len()); + continue; + } + let ch = raw[i..].chars().next().unwrap(); + let len = ch.len_utf8(); + if ch.is_whitespace() { + if !last_ws { + cleaned.push(' '); + last_ws = true; + } + } else { + cleaned.push(ch); + last_ws = false; + } + i += len; + } + let trimmed = cleaned.trim(); + if trimmed.is_empty() { + default.to_owned() + } else { + trimmed.to_owned() + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Channel { + Red, + Green, + Blue, + Alpha, +} + +impl Channel { + fn swizzle(self) -> &'static str { + match self { + Self::Red => "r", + Self::Green => "g", + Self::Blue => "b", + Self::Alpha => "a", + } + } +} + +// ============================================================================ +// Lexer & Recursive-Descent Parser -> WGSL Expression Compiler +// ============================================================================ + +#[derive(Clone, Debug, PartialEq)] +enum Token { + Num(f64), + Ident(String), + Plus, + Minus, + Star, + Slash, + Percent, + Caret, + LParen, + RParen, + Comma, + Lt, + Le, + Gt, + Ge, + Eq, + Ne, + And, + Or, + Bang, +} + +fn tokenize(src: &str) -> Result, String> { + let b = src.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if c.is_ascii_whitespace() { + i += 1; + continue; + } + if c == b'/' && b.get(i + 1) == Some(&b'/') { + i += 2; + while i < b.len() && b[i] != b'\n' { + i += 1; + } + continue; + } + if c == b'/' && b.get(i + 1) == Some(&b'*') { + i += 2; + while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') { + i += 1; + } + i = (i + 2).min(b.len()); + continue; + } + if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) { + let start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if b.get(i) == Some(&b'.') { + i += 1; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + } + if matches!(b.get(i), Some(b'e' | b'E')) { + let exp_pos = i; + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + let dig_start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if i == dig_start { + i = exp_pos; + } + } + let s = &src[start..i]; + let v: f64 = s.parse().map_err(|_| format!("invalid number literal '{s}'"))?; + out.push(Token::Num(v)); + continue; + } + if c.is_ascii_alphabetic() || c == b'_' { + let start = i; + while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { + i += 1; + } + out.push(Token::Ident(src[start..i].to_owned())); + continue; + } + let next = b.get(i + 1).copied(); + match (c, next) { + (b'<', Some(b'=')) => { out.push(Token::Le); i += 2; } + (b'>', Some(b'=')) => { out.push(Token::Ge); i += 2; } + (b'=', Some(b'=')) => { out.push(Token::Eq); i += 2; } + (b'!', Some(b'=')) | (b'~', Some(b'=')) | (b'<', Some(b'>')) => { out.push(Token::Ne); i += 2; } + (b'&', Some(b'&')) => { out.push(Token::And); i += 2; } + (b'|', Some(b'|')) => { out.push(Token::Or); i += 2; } + (b'+', _) => { out.push(Token::Plus); i += 1; } + (b'-', _) => { out.push(Token::Minus); i += 1; } + (b'*', _) => { out.push(Token::Star); i += 1; } + (b'/', _) => { out.push(Token::Slash); i += 1; } + (b'%', _) => { out.push(Token::Percent); i += 1; } + (b'^', _) => { out.push(Token::Caret); i += 1; } + (b'(', _) => { out.push(Token::LParen); i += 1; } + (b')', _) => { out.push(Token::RParen); i += 1; } + (b',', _) => { out.push(Token::Comma); i += 1; } + (b'<', _) => { out.push(Token::Lt); i += 1; } + (b'>', _) => { out.push(Token::Gt); i += 1; } + (b'=', _) => { out.push(Token::Eq); i += 1; } + (b'&', _) => { out.push(Token::And); i += 1; } + (b'|', _) => { out.push(Token::Or); i += 1; } + (b'!', _) => { out.push(Token::Bang); i += 1; } + _ => return Err(format!("unexpected character '{}'", c as char)), + } + } + Ok(out) +} + +struct ExprCompiler<'a> { + tokens: &'a [Token], + pos: usize, + channel: Channel, + max_setup: usize, + max_inter: usize, +} + +impl<'a> ExprCompiler<'a> { + fn peek(&self) -> Option<&Token> { + self.tokens.get(self.pos) + } + + fn eat(&mut self, expected: &Token) -> bool { + if self.peek() == Some(expected) { + self.pos += 1; + true + } else { + false + } + } + + fn compile(&mut self) -> Result { + if self.tokens.is_empty() { + return Ok("0.0".to_owned()); + } + let expr = self.parse_or()?; + if self.pos != self.tokens.len() { + return Err(format!("unexpected trailing token {:?}", self.tokens[self.pos])); + } + Ok(expr) + } + + fn parse_or(&mut self) -> Result { + let mut lhs = self.parse_and()?; + while self.eat(&Token::Or) { + let rhs = self.parse_and()?; + lhs = format!("select(0.0, 1.0, (({lhs}) != 0.0) || (({rhs}) != 0.0))"); + } + Ok(lhs) + } + + fn parse_and(&mut self) -> Result { + let mut lhs = self.parse_cmp()?; + while self.eat(&Token::And) { + let rhs = self.parse_cmp()?; + lhs = format!("select(0.0, 1.0, (({lhs}) != 0.0) && (({rhs}) != 0.0))"); + } + Ok(lhs) + } + + fn parse_cmp(&mut self) -> Result { + let mut lhs = self.parse_add()?; + loop { + let op = match self.peek() { + Some(Token::Lt) => "<", + Some(Token::Le) => "<=", + Some(Token::Gt) => ">", + Some(Token::Ge) => ">=", + Some(Token::Eq) => "==", + Some(Token::Ne) => "!=", + _ => break, + }; + self.pos += 1; + let rhs = self.parse_add()?; + lhs = format!("select(0.0, 1.0, ({lhs}) {op} ({rhs}))"); + } + Ok(lhs) + } + + fn parse_add(&mut self) -> Result { + let mut lhs = self.parse_mul()?; + loop { + if self.eat(&Token::Plus) { + let rhs = self.parse_mul()?; + lhs = format!("(({lhs}) + ({rhs}))"); + } else if self.eat(&Token::Minus) { + let rhs = self.parse_mul()?; + lhs = format!("(({lhs}) - ({rhs}))"); + } else { + break; + } + } + Ok(lhs) + } + + fn parse_mul(&mut self) -> Result { + let mut lhs = self.parse_pow()?; + loop { + if self.eat(&Token::Star) { + let rhs = self.parse_pow()?; + lhs = format!("(({lhs}) * ({rhs}))"); + } else if self.eat(&Token::Slash) { + let rhs = self.parse_pow()?; + lhs = format!("safe_div(({lhs}), ({rhs}))"); + } else if self.eat(&Token::Percent) { + let rhs = self.parse_pow()?; + lhs = format!("fu_mod(({lhs}), ({rhs}))"); + } else { + break; + } + } + Ok(lhs) + } + + fn parse_pow(&mut self) -> Result { + let base = self.parse_unary()?; + if self.eat(&Token::Caret) { + // Right-associative and allows unary rhs (e.g. `e^-x`, `2^-3`) + let exp = self.parse_pow()?; + Ok(format!("fu_pow(({base}), ({exp}))")) + } else { + Ok(base) + } + } + + fn parse_unary(&mut self) -> Result { + if self.eat(&Token::Minus) { + let inner = self.parse_unary()?; + Ok(format!("(-({inner}))")) + } else if self.eat(&Token::Plus) { + self.parse_unary() + } else if self.eat(&Token::Bang) { + let inner = self.parse_unary()?; + Ok(format!("select(0.0, 1.0, ({inner}) == 0.0)")) + } else { + self.parse_primary() + } + } + + fn parse_primary(&mut self) -> Result { + match self.peek().cloned() { + Some(Token::LParen) => { + self.pos += 1; + let inner = self.parse_or()?; + if !self.eat(&Token::RParen) { + return Err("expected ')'".to_owned()); + } + Ok(format!("({inner})")) + } + Some(Token::Num(v)) => { + self.pos += 1; + Ok(format_wgsl_f32(v)) + } + Some(Token::Ident(name)) => { + self.pos += 1; + if self.eat(&Token::LParen) { + let mut args = Vec::new(); + if self.peek() != Some(&Token::RParen) { + loop { + args.push(self.parse_or()?); + if !self.eat(&Token::Comma) { + break; + } + } + } + if !self.eat(&Token::RParen) { + return Err(format!("expected ')' after call to '{name}'")); + } + self.emit_call(&name, &args) + } else { + self.emit_var(&name) + } + } + other => Err(format!("unexpected token {other:?}")), + } + } + + fn emit_var(&self, name: &str) -> Result { + let ch = self.channel.swizzle(); + let wgsl = match name { + "r1" => "p1.r", + "g1" => "p1.g", + "b1" => "p1.b", + "a1" => "p1.a", + "r2" => "p2.r", + "g2" => "p2.g", + "b2" => "p2.b", + "a2" => "p2.a", + "r3" => "p3.r", + "g3" => "p3.g", + "b3" => "p3.b", + "a3" => "p3.a", + "c1" => return Ok(format!("p1.{ch}")), + "c2" => return Ok(format!("p2.{ch}")), + "c3" => return Ok(format!("p3.{ch}")), + "x" => "fu.x", + "y" => "fu.y", + "w" | "w1" => "u.img_dims1.x", + "h" | "h1" => "u.img_dims1.y", + "w2" => "u.img_dims1.z", + "h2" => "u.img_dims1.w", + "w3" => "u.img_dims2.x", + "h3" => "u.img_dims2.y", + "time" => "u.img_dims2.z", + "pi" => "3.14159265", + "e" => "2.71828183", + "n1" => "u.n0.x", + "n2" => "u.n0.y", + "n3" => "u.n0.z", + "n4" => "u.n0.w", + "n5" => "u.n1.x", + "n6" => "u.n1.y", + "n7" => "u.n1.z", + "n8" => "u.n1.w", + "p1x" => "u.p0.x", + "p1y" => "u.p0.y", + "p2x" => "u.p0.z", + "p2y" => "u.p0.w", + "p3x" => "u.p1.x", + "p3y" => "u.p1.y", + "p4x" => "u.p1.z", + "p4y" => "u.p1.w", + "s1" if self.max_setup >= 1 => "s1", + "s2" if self.max_setup >= 2 => "s2", + "s3" if self.max_setup >= 3 => "s3", + "s4" if self.max_setup >= 4 => "s4", + "s1" | "s2" | "s3" | "s4" => "0.0", + "i1" if self.max_inter >= 1 => "i1", + "i2" if self.max_inter >= 2 => "i2", + "i3" if self.max_inter >= 3 => "i3", + "i4" if self.max_inter >= 4 => "i4", + "i5" if self.max_inter >= 5 => "i5", + "i6" if self.max_inter >= 6 => "i6", + "i7" if self.max_inter >= 7 => "i7", + "i8" if self.max_inter >= 8 => "i8", + "i1" | "i2" | "i3" | "i4" | "i5" | "i6" | "i7" | "i8" => "0.0", + // Aux channels (Z/Position/Normal/UV/Coverage/Obj/Mat) default cleanly to 0.0 + "z1" | "z2" | "z3" + | "cov1" | "cov2" | "cov3" + | "obj1" | "obj2" | "obj3" + | "mat1" | "mat2" | "mat3" + | "px1" | "py1" | "pz1" + | "px2" | "py2" | "pz2" + | "px3" | "py3" | "pz3" + | "nx1" | "ny1" | "nz1" + | "nx2" | "ny2" | "nz2" + | "nx3" | "ny3" | "nz3" + | "u1" | "v1" | "u2" | "v2" | "u3" | "v3" + | "bg1" | "bga1" | "bg2" | "bga2" | "bg3" | "bga3" => "0.0", + other => return Err(format!("unknown variable '{other}'")), + }; + Ok(wgsl.to_owned()) + } + + fn emit_call(&self, name: &str, args: &[String]) -> Result { + let req = |n: usize| -> Result<(), String> { + if args.len() != n { + Err(format!("function '{name}' expects {n} arg(s), got {}", args.len())) + } else { + Ok(()) + } + }; + + // Image samplers: get{r|g|b|a|c}{1|2|3}[b|w|d](sx, sy) + if let Some(rest) = name.strip_prefix("get") { + if let Some(code) = self.try_emit_sampler(rest, args)? { + return Ok(code); + } + } + + match name { + // Fusion CustomTool trig operates in DEGREES! + "sin" => { req(1)?; Ok(format!("sin(({}) * DEG2RAD)", args[0])) } + "cos" => { req(1)?; Ok(format!("cos(({}) * DEG2RAD)", args[0])) } + "tan" => { req(1)?; Ok(format!("tan(({}) * DEG2RAD)", args[0])) } + "asin" => { req(1)?; Ok(format!("(asin(clamp(({}), -1.0, 1.0)) * RAD2DEG)", args[0])) } + "acos" => { req(1)?; Ok(format!("(acos(clamp(({}), -1.0, 1.0)) * RAD2DEG)", args[0])) } + "atan" => { req(1)?; Ok(format!("(atan(({})) * RAD2DEG)", args[0])) } + "atan2" => { req(2)?; Ok(format!("(atan2(({}), ({})) * RAD2DEG)", args[0], args[1])) } + // Radian trig variants + "sinr" => { req(1)?; Ok(format!("sin(({}))", args[0])) } + "cosr" => { req(1)?; Ok(format!("cos(({}))", args[0])) } + "tanr" => { req(1)?; Ok(format!("tan(({}))", args[0])) } + "asinr" => { req(1)?; Ok(format!("asin(clamp(({}), -1.0, 1.0))", args[0])) } + "acosr" => { req(1)?; Ok(format!("acos(clamp(({}), -1.0, 1.0))", args[0])) } + "atanr" => { req(1)?; Ok(format!("atan(({}))", args[0])) } + "atan2r" => { req(2)?; Ok(format!("atan2(({}), ({}))", args[0], args[1])) } + // Hyperbolic + "sinh" => { req(1)?; Ok(format!("sinh(({}))", args[0])) } + "cosh" => { req(1)?; Ok(format!("cosh(({}))", args[0])) } + "tanh" => { req(1)?; Ok(format!("tanh(({}))", args[0])) } + "deg" => { req(1)?; Ok(format!("(({}) * RAD2DEG)", args[0])) } + "rad" => { req(1)?; Ok(format!("(({}) * DEG2RAD)", args[0])) } + // Core math + "abs" => { req(1)?; Ok(format!("abs(({}))", args[0])) } + "sqrt" => { req(1)?; Ok(format!("sqrt(max(({}), 0.0))", args[0])) } + "pow" => { req(2)?; Ok(format!("fu_pow(({}), ({}))", args[0], args[1])) } + "exp" => { req(1)?; Ok(format!("exp(({}))", args[0])) } + "log" | "ln" => { req(1)?; Ok(format!("log(max(({}), 1e-12))", args[0])) } + "log10" => { req(1)?; Ok(format!("(log(max(({}), 1e-12)) * 0.43429448)", args[0])) } + "log2" => { req(1)?; Ok(format!("log2(max(({}), 1e-12))", args[0])) } + "floor" | "int" => { req(1)?; Ok(format!("floor(({}))", args[0])) } + "ceil" => { req(1)?; Ok(format!("ceil(({}))", args[0])) } + "round" => { req(1)?; Ok(format!("round(({}))", args[0])) } + "trunc" => { req(1)?; Ok(format!("trunc(({}))", args[0])) } + "fract" => { req(1)?; Ok(format!("fract(({}))", args[0])) } + "sign" => { req(1)?; Ok(format!("sign(({}))", args[0])) } + "min" => { + if args.len() < 2 { + return Err("function 'min' expects at least 2 args".to_owned()); + } + let mut acc = format!("min(({}), ({}))", args[0], args[1]); + for arg in &args[2..] { + acc = format!("min(({acc}), ({arg}))"); + } + Ok(acc) + } + "max" => { + if args.len() < 2 { + return Err("function 'max' expects at least 2 args".to_owned()); + } + let mut acc = format!("max(({}), ({}))", args[0], args[1]); + for arg in &args[2..] { + acc = format!("max(({acc}), ({arg}))"); + } + Ok(acc) + } + "clamp" => { req(3)?; Ok(format!("clamp(({}), ({}), ({}))", args[0], args[1], args[2])) } + "mod" => { req(2)?; Ok(format!("fu_mod(({}), ({}))", args[0], args[1])) } + "if" | "iif" => { req(3)?; Ok(format!("select(({}), ({}), ({}) != 0.0)", args[2], args[1], args[0])) } + "dist" => { + req(4)?; + Ok(format!("length(vec2(({}) - ({}), ({}) - ({})))", args[2], args[0], args[3], args[1])) + } + "hypot" => { req(2)?; Ok(format!("length(vec2(({}), ({})))", args[0], args[1])) } + "mix" | "lerp" => { req(3)?; Ok(format!("mix(({}), ({}), ({}))", args[0], args[1], args[2])) } + "step" => { req(2)?; Ok(format!("step(({}), ({}))", args[0], args[1])) } + "smoothstep" => { req(3)?; Ok(format!("smoothstep(({}), ({}), ({}))", args[0], args[1], args[2])) } + // LUT samplers (Fusion canonical `getlut1..4` + `lut1..4` alias) + "getlut1" | "lut1" => { req(1)?; Ok(format!("sample_lut(0u, ({}))", args[0])) } + "getlut2" | "lut2" => { req(1)?; Ok(format!("sample_lut(1u, ({}))", args[0])) } + "getlut3" | "lut3" => { req(1)?; Ok(format!("sample_lut(2u, ({}))", args[0])) } + "getlut4" | "lut4" => { req(1)?; Ok(format!("sample_lut(3u, ({}))", args[0])) } + // Random & procedural noise + "rand" => { req(2)?; Ok(format!("mix(({}), ({}), fu_hash(vec3(f32(gid.x), f32(gid.y), u.img_dims2.z)))", args[0], args[1])) } + "rands" => { req(3)?; Ok(format!("mix(({}), ({}), fu_hash(vec3(f32(gid.x), f32(gid.y), ({}))))", args[0], args[1], args[2])) } + "noise" => { req(1)?; Ok(format!("fu_noise1(({}))", args[0])) } + "noise2" => { req(2)?; Ok(format!("fu_noise2(vec2(({}), ({})))", args[0], args[1])) } + "noise3" => { req(3)?; Ok(format!("fu_noise3(vec3(({}), ({}), ({})))", args[0], args[1], args[2])) } + other => Err(format!("unknown function '{other}'")), + } + } + + fn try_emit_sampler(&self, rest: &str, args: &[String]) -> Result, String> { + let bytes = rest.as_bytes(); + if bytes.len() < 2 || bytes.len() > 3 { + return Ok(None); + } + let ch = match bytes[0] { + b'r' => "r", + b'g' => "g", + b'b' => "b", + b'a' => "a", + b'c' => self.channel.swizzle(), + _ => return Ok(None), + }; + let tex = match bytes[1] { + b'1' => "src_1", + b'2' => "src_2", + b'3' => "src_3", + _ => return Ok(None), + }; + let edge_mode = match bytes.get(2) { + None | Some(b'b') => 0, // Black / Canvas + Some(b'w') => 1, // Wrap + Some(b'd') => 2, // Duplicate / Clamp + _ => return Ok(None), + }; + if args.len() != 2 { + return Err(format!("sampler 'get{rest}' expects 2 args, got {}", args.len())); + } + Ok(Some(format!( + "sample_img({tex}, ({}), ({}), {edge_mode}).{ch}", + args[0], args[1] + ))) + } +} + +fn format_wgsl_f32(v: f64) -> String { + let f = v as f32; + if !f.is_finite() { + return "0.0".to_owned(); + } + let s = format!("{f}"); + if s.contains('.') || s.contains('e') || s.contains('E') { + s + } else { + format!("{s}.0") + } +} + +fn compile_single_expr( + src: &str, + channel: Channel, + max_setup: usize, + max_inter: usize, +) -> Result { + let tokens = tokenize(src)?; + let mut compiler = ExprCompiler { + tokens: &tokens, + pos: 0, + channel, + max_setup, + max_inter, + }; + compiler.compile() +} + +/// Compiles a normalized `CustomProgram` into a complete WGSL compute shader string +/// targeting `format` (`Rgba8Unorm`, `Rgba16Float`, or `Rgba32Float`). +pub fn compile_wgsl(program: &CustomProgram, format: wgpu::TextureFormat) -> Result { + let norm = program.normalized(); + let storage_fmt = match format { + wgpu::TextureFormat::Rgba16Float => "rgba16float", + wgpu::TextureFormat::Rgba32Float => "rgba32float", + _ => "rgba8unorm", + }; + + let mut setup_decls = String::new(); + for idx in 0..4 { + let expr = compile_single_expr(&norm.setups[idx], Channel::Red, idx, 0)?; + setup_decls.push_str(&format!(" let s{}: f32 = {expr};\n", idx + 1)); + } + + let mut inter_decls = String::new(); + for idx in 0..8 { + let expr = compile_single_expr(&norm.intermediates[idx], Channel::Red, 4, idx)?; + inter_decls.push_str(&format!(" let i{}: f32 = {expr};\n", idx + 1)); + } + + let red_expr = compile_single_expr(&norm.red, Channel::Red, 4, 8)?; + let green_expr = compile_single_expr(&norm.green, Channel::Green, 4, 8)?; + let blue_expr = compile_single_expr(&norm.blue, Channel::Blue, 4, 8)?; + let alpha_expr = compile_single_expr(&norm.alpha, Channel::Alpha, 4, 8)?; + + Ok(format!( + r#"// Auto-generated Fusion CustomTool compute shader +@group(0) @binding(0) var src_1: texture_2d; +@group(0) @binding(1) var src_2: texture_2d; +@group(0) @binding(2) var src_3: texture_2d; +@group(0) @binding(3) var mask_tex: texture_2d; +@group(0) @binding(4) var samp_lin: sampler; +@group(0) @binding(5) var dst_tex: texture_storage_2d<{storage_fmt}, write>; + +struct CustomParams {{ + n0: vec4, + n1: vec4, + p0: vec4, + p1: vec4, + img_dims1: vec4, + img_dims2: vec4, + mask_proc: vec4, + proc_ba: vec4, + luts: array, 256>, +}}; +@group(0) @binding(6) var u: CustomParams; + +const DEG2RAD: f32 = 0.017453292519943295; +const RAD2DEG: f32 = 57.29577951308232; + +fn safe_div(a: f32, b: f32) -> f32 {{ + return select(a / b, 0.0, abs(b) < 1e-12); +}} + +fn fu_mod(a: f32, b: f32) -> f32 {{ + if (abs(b) < 1e-12) {{ return 0.0; }} + return a - b * floor(a / b); +}} + +fn fu_pow(a: f32, b: f32) -> f32 {{ + if (a > 0.0) {{ + return pow(a, b); + }} + if (a == 0.0) {{ + return select(0.0, 1.0, abs(b) < 1e-12); + }} + let rb = round(b); + if (abs(b - rb) < 1e-5) {{ + let mag = pow(abs(a), rb); + let odd = (i32(rb) & 1) != 0; + return select(mag, -mag, odd); + }} + return 0.0; +}} + +fn fu_hash(p: vec3) -> f32 {{ + var p3 = fract(p * vec3(0.1031, 0.1030, 0.0973)); + p3 = p3 + dot(p3, p3.yzx + 33.33); + return fract((p3.x + p3.y) * p3.z); +}} + +fn fu_noise1(x: f32) -> f32 {{ + let i = floor(x); + let f = fract(x); + let u_f = f * f * (3.0 - 2.0 * f); + return mix(fu_hash(vec3(i, 0.0, 0.0)), fu_hash(vec3(i + 1.0, 0.0, 0.0)), u_f) * 2.0 - 1.0; +}} + +fn fu_noise2(p: vec2) -> f32 {{ + let i = floor(p); + let f = fract(p); + let u_f = f * f * (3.0 - 2.0 * f); + let a = fu_hash(vec3(i, 0.0)); + let b = fu_hash(vec3(i + vec2(1.0, 0.0), 0.0)); + let c = fu_hash(vec3(i + vec2(0.0, 1.0), 0.0)); + let d = fu_hash(vec3(i + vec2(1.0, 1.0), 0.0)); + return mix(mix(a, b, u_f.x), mix(c, d, u_f.x), u_f.y) * 2.0 - 1.0; +}} + +fn fu_noise3(p: vec3) -> f32 {{ + let i = floor(p); + let f = fract(p); + let u_f = f * f * (3.0 - 2.0 * f); + let n000 = fu_hash(i + vec3(0.0, 0.0, 0.0)); + let n100 = fu_hash(i + vec3(1.0, 0.0, 0.0)); + let n010 = fu_hash(i + vec3(0.0, 1.0, 0.0)); + let n110 = fu_hash(i + vec3(1.0, 1.0, 0.0)); + let n001 = fu_hash(i + vec3(0.0, 0.0, 1.0)); + let n101 = fu_hash(i + vec3(1.0, 0.0, 1.0)); + let n011 = fu_hash(i + vec3(0.0, 1.0, 1.0)); + let n111 = fu_hash(i + vec3(1.0, 1.0, 1.0)); + let nx00 = mix(n000, n100, u_f.x); + let nx10 = mix(n010, n110, u_f.x); + let nx01 = mix(n001, n101, u_f.x); + let nx11 = mix(n011, n111, u_f.x); + return mix(mix(nx00, nx10, u_f.y), mix(nx01, nx11, u_f.y), u_f.z) * 2.0 - 1.0; +}} + +fn sample_lut(ch: u32, v: f32) -> f32 {{ + let t = clamp(v, 0.0, 1.0) * 255.0; + let i0 = u32(floor(t)); + let i1 = min(i0 + 1u, 255u); + let frac = t - f32(i0); + return mix(u.luts[i0][ch], u.luts[i1][ch], frac); +}} + +fn read_img_curr(tex: texture_2d, gid: vec2, dims: vec2) -> vec4 {{ + let tdims = textureDimensions(tex); + if (tdims.x == dims.x && tdims.y == dims.y) {{ + return textureLoad(tex, vec2(gid), 0); + }} + if (tdims.x <= 1u && tdims.y <= 1u) {{ + return textureLoad(tex, vec2(0, 0), 0); + }} + let uv = (vec2(gid) + 0.5) / vec2(dims); + return textureSampleLevel(tex, samp_lin, uv, 0.0); +}} + +fn sample_img(tex: texture_2d, fx: f32, fy: f32, mode: i32) -> vec4 {{ + let uv = vec2(fx, 1.0 - fy); + if (mode == 0) {{ + if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {{ + return vec4(0.0); + }} + return textureSampleLevel(tex, samp_lin, uv, 0.0); + }} else if (mode == 1) {{ + return textureSampleLevel(tex, samp_lin, fract(uv), 0.0); + }} else {{ + return textureSampleLevel(tex, samp_lin, clamp(uv, vec2(0.0), vec2(1.0)), 0.0); + }} +}} + +fn read_custom_mask(gid: vec2, dims: vec2, has_mask: f32, invert: f32) -> f32 {{ + if (has_mask < 0.5) {{ + return 1.0; + }} + let uv = (vec2(gid) + 0.5) / vec2(dims); + let m = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a; + return select(m, 1.0 - m, invert > 0.5); +}} + +@compute @workgroup_size(8, 8) +fn custom_tool_op(@builtin(global_invocation_id) gid: vec3) {{ + let dims = textureDimensions(dst_tex); + if (gid.x >= dims.x || gid.y >= dims.y) {{ return; }} + + let fdims = vec2(dims); + let fu = vec2((f32(gid.x) + 0.5) / fdims.x, 1.0 - (f32(gid.y) + 0.5) / fdims.y); + let p1 = read_img_curr(src_1, gid.xy, dims); + let p2 = read_img_curr(src_2, gid.xy, dims); + let p3 = read_img_curr(src_3, gid.xy, dims); + +{setup_decls}{inter_decls} let out_r: f32 = select(p1.r, ({red_expr}), u.mask_proc.z > 0.5); + let out_g: f32 = select(p1.g, ({green_expr}), u.mask_proc.w > 0.5); + let out_b: f32 = select(p1.b, ({blue_expr}), u.proc_ba.x > 0.5); + let out_a: f32 = select(p1.a, ({alpha_expr}), u.proc_ba.y > 0.5); + + let m = clamp(read_custom_mask(gid.xy, dims, u.mask_proc.x, u.mask_proc.y) * u.img_dims2.w, 0.0, 1.0); + let final_col = mix(p1, vec4(out_r, out_g, out_b, out_a), m); + + if (u.proc_ba.z > 0.5) {{ + textureStore(dst_tex, vec2(gid.xy), final_col); + }} else {{ + textureStore(dst_tex, vec2(gid.xy), clamp(final_col, vec4(0.0), vec4(1.0))); + }} +}} +"# + )) +} + +// ============================================================================ +// Pipeline Cache & GPU Dispatch +// ============================================================================ + +struct FormatLayouts { + bgl: wgpu::BindGroupLayout, + pl: wgpu::PipelineLayout, +} + +/// Caches dynamically compiled `CustomTool` compute pipelines keyed by +/// `(dst_texture_format, hash_of_normalized_program)`. +#[derive(Default)] +pub struct CustomShaderCache { + layouts: HashMap, + sampler: Option, + pipelines: HashMap<(wgpu::TextureFormat, u64), Option>, +} + +impl CustomShaderCache { + pub fn new() -> Self { + Self::default() + } + + pub fn cached_pipeline_count(&self) -> usize { + self.pipelines.len() + } + + fn ensure_format_layouts(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) { + self.layouts.entry(format).or_insert_with(|| { + let tex_entry = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("custom-tool-bgl"), + entries: &[ + tex_entry(0), + tex_entry(1), + tex_entry(2), + tex_entry(3), + wgpu::BindGroupLayoutEntry { + binding: 4, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 5, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format, + view_dimension: wgpu::TextureViewDimension::D2, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 6, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("custom-tool-pl"), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }); + FormatLayouts { bgl, pl } + }); + if self.sampler.is_none() { + self.sampler = Some(device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("custom-tool-linear"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + mipmap_filter: wgpu::MipmapFilterMode::Nearest, + ..Default::default() + })); + } + } + + /// Compiles and caches the compute pipeline for `program` at `format`, returning `false` + /// if the program contains unsupported syntax (graceful fallback to passthrough). + pub fn ensure_compiled( + &mut self, + device: &wgpu::Device, + program: &CustomProgram, + format: wgpu::TextureFormat, + ) -> bool { + let norm = program.normalized(); + let key = (format, norm.program_hash()); + if let Some(entry) = self.pipelines.get(&key) { + return entry.is_some(); + } + self.ensure_format_layouts(device, format); + let pipeline = match compile_wgsl(&norm, format) { + Ok(wgsl) => { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("custom-tool-shader"), + source: wgpu::ShaderSource::Wgsl(wgsl.into()), + }); + let pl = &self.layouts[&format].pl; + Some(device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("custom_tool_op"), + layout: Some(pl), + module: &module, + entry_point: Some("custom_tool_op"), + compilation_options: Default::default(), + cache: None, + })) + } + Err(_) => None, + }; + let ok = pipeline.is_some(); + self.pipelines.insert(key, pipeline); + ok + } + + /// Dispatches a compiled `CustomProgram` into `dst_view`. Returns `false` if compilation failed. + #[allow(clippy::too_many_arguments)] + pub fn dispatch( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + program: &CustomProgram, + format: wgpu::TextureFormat, + src_1: &wgpu::TextureView, + src_2: &wgpu::TextureView, + src_3: &wgpu::TextureView, + mask: &wgpu::TextureView, + dst_view: &wgpu::TextureView, + dst_size: [u32; 2], + params: &CustomParams, + ) -> bool { + let norm = program.normalized(); + let key = (format, norm.program_hash()); + if !self.ensure_compiled(device, &norm, format) { + return false; + } + let Some(Some(pipeline)) = self.pipelines.get(&key) else { + return false; + }; + let layout = &self.layouts[&format].bgl; + let sampler = self.sampler.as_ref().expect("sampler initialized"); + + let ubuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("custom-tool-params"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(params)); + + let bg = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("custom-tool-bg"), + layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_1) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_2) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(src_3) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(mask) }, + wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Sampler(sampler) }, + wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(dst_view) }, + wgpu::BindGroupEntry { binding: 6, resource: ubuf.as_entire_binding() }, + ], + }); + + let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("custom-tool-pass"), + timestamp_writes: None, + }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &bg, &[]); + pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Engine, create_texture}; + use model::Comp; + + #[test] + fn parses_operator_precedence_and_edge_cases() { + let mut p = CustomProgram::default(); + p.setups[0] = "1/n1".to_owned(); + p.setups[1] = "s1 - n2*s1".to_owned(); + p.intermediates[0] = "if(n7=0, (r1/n1), (r1*n1))".to_owned(); + p.red = "if(c1>n1, n1+i1*(1-e^-((c1-n1)/i1)), c1)".to_owned(); + p.green = "x%s2")); + assert!(wgsl.contains("sample_img(src_1,")); + assert!(wgsl.contains("sample_img(src_2,")); + assert!(wgsl.contains("sample_img(src_3,")); + assert!(wgsl.contains("sample_lut(0u,")); + assert!(wgsl.contains("sample_lut(3u,")); + } + + #[test] + fn rejects_invalid_syntax_gracefully() { + let mut p = CustomProgram::default(); + p.red = "unknown_func(r1)".to_owned(); + assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_err()); + + p.red = "r1 + + *".to_owned(); + assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_err()); + + p.red = "totally_unknown_var".to_owned(); + assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_err()); + } + + #[test] + fn gpu_executes_wave_formula_and_caches_pipeline() { + let eng = Engine::new_headless().expect("gpu"); + let mut cache = CustomShaderCache::new(); + let mut prog = CustomProgram::default(); + prog.red = "sin(x*w*n1 + n2*n1*w)*0.5+0.5".to_owned(); + prog.green = "sin(y*w*n1 + n2*n1*w)*0.5+0.5".to_owned(); + prog.blue = "0\n".to_owned(); + prog.alpha = "1".to_owned(); + + let mut params = CustomParams::default(); + params.n0 = [0.7413, 10.655, 0.0, 0.0]; + params.img_dims1 = [64.0, 64.0, 64.0, 64.0]; + + let dummy = create_texture(eng.device(), [1, 1], 0); + let dst = create_texture(eng.device(), [64, 64], 1); + let mut enc = eng.device().create_command_encoder(&Default::default()); + let ok = cache.dispatch( + eng.device(), + eng.queue(), + &mut enc, + &prog, + wgpu::TextureFormat::Rgba8Unorm, + &dummy.view, + &dummy.view, + &dummy.view, + &dummy.view, + &dst.view, + [64, 64], + ¶ms, + ); + assert!(ok); + eng.queue().submit(Some(enc.finish())); + assert_eq!(cache.cached_pipeline_count(), 1); + + // Whitespace-equivalent program hits the exact same cached pipeline! + let mut prog2 = prog.clone(); + prog2.blue = " 0 ".to_owned(); + assert!(cache.ensure_compiled(eng.device(), &prog2, wgpu::TextureFormat::Rgba8Unorm)); + assert_eq!(cache.cached_pipeline_count(), 1); + + let rgba = eng.readback_rgba(&dst).expect("readback"); + // Verify pixel (10, 20) against CPU formula + let px = 10usize; + let py = 20usize; + let fu_x = (px as f64 + 0.5) / 64.0; + let fu_y = 1.0 - (py as f64 + 0.5) / 64.0; + let n1 = 0.7413_f64; + let n2 = 10.655_f64; + let w = 64.0_f64; + let exp_r = ((fu_x * w * n1 + n2 * n1 * w).to_radians().sin() * 0.5 + 0.5) * 255.0; + let exp_g = ((fu_y * w * n1 + n2 * n1 * w).to_radians().sin() * 0.5 + 0.5) * 255.0; + let idx = (py * 64 + px) * 4; + assert!((rgba[idx] as f64 - exp_r).abs() <= 1.5, "r got {} expected {exp_r}", rgba[idx]); + assert!((rgba[idx + 1] as f64 - exp_g).abs() <= 1.5, "g got {} expected {exp_g}", rgba[idx + 1]); + assert_eq!(rgba[idx + 2], 0); + assert_eq!(rgba[idx + 3], 255); + } + + #[test] + fn gpu_executes_premul_invert_safe_div_when_alpha_zero() { + let eng = Engine::new_headless().expect("gpu"); + let mut cache = CustomShaderCache::new(); + let mut prog = CustomProgram::default(); + prog.intermediates[0] = "a1".to_owned(); + prog.red = "(1-r1/a1)*i1".to_owned(); + prog.green = "(1-g1/a1)*i1".to_owned(); + prog.blue = "(1-b1/a1)*i1".to_owned(); + prog.alpha = "i1".to_owned(); + + // 2x1 input: pixel 0 is transparent black (a1 == 0), pixel 1 is premul (0.2, 0.4, 0.0, 0.5) + let src = create_texture(eng.device(), [2, 1], 0); + let input_bytes: [u8; 8] = [0, 0, 0, 0, 51, 102, 0, 128]; + eng.queue().write_texture( + src.texture.as_image_copy(), + &input_bytes, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(8), rows_per_image: Some(1) }, + wgpu::Extent3d { width: 2, height: 1, depth_or_array_layers: 1 }, + ); + let dummy = create_texture(eng.device(), [1, 1], 0); + let dst = create_texture(eng.device(), [2, 1], 2); + let params = CustomParams { + img_dims1: [2.0, 1.0, 1.0, 1.0], + ..Default::default() + }; + + let mut enc = eng.device().create_command_encoder(&Default::default()); + assert!(cache.dispatch( + eng.device(), + eng.queue(), + &mut enc, + &prog, + wgpu::TextureFormat::Rgba8Unorm, + &src.view, + &dummy.view, + &dummy.view, + &dummy.view, + &dst.view, + [2, 1], + ¶ms, + )); + eng.queue().submit(Some(enc.finish())); + + let rgba = eng.readback_rgba(&dst).expect("readback"); + // Pixel 0 (a1 == 0): must be clean (0, 0, 0, 0), no NaN! + assert_eq!(&rgba[0..4], &[0, 0, 0, 0]); + // Pixel 1: straight RGB = (51/128, 102/128, 0) = (0.398, 0.797, 0) + // Inverted * a1 = ((1-0.398)*0.502, (1-0.797)*0.502, 1*0.502) * 255 = (77, 26, 128) + assert!((rgba[4] as i32 - 77).abs() <= 2, "r={}", rgba[4]); + assert!((rgba[5] as i32 - 26).abs() <= 2, "g={}", rgba[5]); + assert!((rgba[6] as i32 - 128).abs() <= 2, "b={}", rgba[6]); + assert_eq!(rgba[7], 128); + } + + #[test] + fn end_to_end_comp_custom_tool_with_lut_and_expression_modifier() { + let src = r#"Composition { + Prefs = { Comp = { FrameFormat = { Width = 16, Height = 16, Rate = 24 } } }, + Tools = ordered() { + BG1 = Background { + Inputs = { + Width = Input { Value = 16, }, + Height = Input { Value = 16, }, + TopLeftRed = Input { Value = 0.25, }, + TopLeftGreen = Input { Value = 0.5, }, + TopLeftBlue = Input { Value = 0.75, }, + TopLeftAlpha = Input { Value = 1.0, }, + }, + }, + NumExpr = Expression { + Inputs = { + n1 = Input { Value = 2.0, }, + NumberExpression = Input { Value = "n1 * 0.25", }, + }, + }, + CT1LUT1 = LUTBezier { + KeyColorSplines = { + [0] = { + [0] = { 1.0, Flags = { Linear = true } }, + [1] = { 0.0, Flags = { Linear = true } }, + }, + }, + }, + CT1 = Custom { + Inputs = { + Image1 = Input { SourceOp = "BG1", Source = "Output", }, + NumberIn1 = Input { SourceOp = "NumExpr", Source = "NumberResult", }, + LUTIn1 = Input { SourceOp = "CT1LUT1", Source = "Value", }, + RedExpression = Input { Value = "lut1(r1)", }, + GreenExpression = Input { Value = "g1 * n1", }, + BlueExpression = Input { Value = "if(b1 > 0.5, 1, 0)", }, + AlphaExpression = Input { Value = "a1", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse"); + let mut eng = Engine::new_headless().expect("gpu"); + let ct_id = comp.find_node("CT1").unwrap(); + let (tex, _) = eng.evaluate(&comp, ct_id, 0.0); + let rgba = eng.readback_rgba(&tex).expect("readback"); + // r = lut1(0.25) = 0.75 (~191), g = 0.5 * 0.5 = 0.25 (~64), b = 1.0 (255), a = 1.0 (255) + assert!((rgba[0] as i32 - 191).abs() <= 2, "r={}", rgba[0]); + assert!((rgba[1] as i32 - 64).abs() <= 2, "g={}", rgba[1]); + assert_eq!(rgba[2], 255); + assert_eq!(rgba[3], 255); + } +} diff --git a/crates/engine/src/eval/color.rs b/crates/engine/src/eval/color.rs index f21de8cd51cf465170b928b3f2a480b770b0460d..5ce9291ce60967d6367e49d5c3f5b6bc3ba1ee2f 100644 --- a/crates/engine/src/eval/color.rs +++ b/crates/engine/src/eval/color.rs @@ -247,54 +247,185 @@ impl Engine { visiting: &mut HashSet<(NodeId, i64)>, stats: &mut EvalStats, ) -> CachedTexture { - let size = if let Some(src_id) = node.connected_node("Image1").and_then(|s| comp.find_node(s)) { - self.eval_node(comp, src_id, time, enc, visiting, stats).size - } else { - comp_dims + let img1 = node + .connected_node("Image1") + .and_then(|s| comp.find_node(s)) + .map(|id| { + let t = self.eval_node(comp, id, time, enc, visiting, stats); + self.crop_to_canvas(enc, t) + }); + let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32; + if blend <= 1e-6 { + return img1.unwrap_or_else(|| self.dummy.clone()); + } + let img2 = node + .connected_node("Image2") + .and_then(|s| comp.find_node(s)) + .map(|id| { + let t = self.eval_node(comp, id, time, enc, visiting, stats); + self.crop_to_canvas(enc, t) + }); + let img3 = node + .connected_node("Image3") + .and_then(|s| comp.find_node(s)) + .map(|id| { + let t = self.eval_node(comp, id, time, enc, visiting, stats); + self.crop_to_canvas(enc, t) + }); + + let size = img1.as_ref().map_or(comp_dims, |t| t.size); + let depth = self.node_depth(comp, node, time, img1.as_ref().map(|t| t.depth)); + let eff_depth = self.effective_depth(depth); + let (mask, mask_inv) = + self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats); + + let setup_names = ["Setup1", "Setup2", "Setup3", "Setup4"]; + let inter_names = [ + ("Intermediate1", "Inter1"), + ("Intermediate2", "Inter2"), + ("Intermediate3", "Inter3"), + ("Intermediate4", "Inter4"), + ("Intermediate5", "Inter5"), + ("Intermediate6", "Inter6"), + ("Intermediate7", "Inter7"), + ("Intermediate8", "Inter8"), + ]; + let program = crate::custom_shader::CustomProgram { + setups: std::array::from_fn(|i| comp.eval_text(node, setup_names[i], time, "0", &self.expr)), + intermediates: std::array::from_fn(|i| { + let (primary, alias) = inter_names[i]; + if node.inputs.contains_key(primary) { + comp.eval_text(node, primary, time, "0", &self.expr) + } else if node.inputs.contains_key(alias) { + comp.eval_text(node, alias, time, "0", &self.expr) + } else { + "0".to_owned() + } + }), + red: comp.eval_text(node, "RedExpression", time, "r1", &self.expr), + green: comp.eval_text(node, "GreenExpression", time, "g1", &self.expr), + blue: comp.eval_text(node, "BlueExpression", time, "b1", &self.expr), + alpha: comp.eval_text(node, "AlphaExpression", time, "a1", &self.expr), + } + .normalized(); + + let pscale = self.proxy_scale.max(1); + let w1 = (size[0] * pscale) as f32; + let h1 = (size[1] * pscale) as f32; + let (w2, h2) = img2 + .as_ref() + .map_or((w1, h1), |t| ((t.size[0] * pscale) as f32, (t.size[1] * pscale) as f32)); + let (w3, h3) = img3 + .as_ref() + .map_or((w1, h1), |t| ((t.size[0] * pscale) as f32, (t.size[1] * pscale) as f32)); + + let n = |k: &str| comp.eval_number(node, k, time, 0.0, &self.expr) as f32; + let pt = |k: &str| { + let p = comp.eval_point(node, k, time, [0.5, 0.5], &self.expr); + [p[0] as f32, p[1] as f32] }; - let n1 = comp.eval_number(node, "NumberIn1", time, 1.0, &self.expr) as f32; - let n2 = comp.eval_number(node, "NumberIn2", time, 0.0, &self.expr) as f32; - let red_expr = node.inputs.get("RedExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or(""); - let green_expr = node.inputs.get("GreenExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or(""); - let blue_expr = node.inputs.get("BlueExpression").and_then(|b| b.value.as_ref()).and_then(ParamValue::as_str).unwrap_or(""); - let wave_mode = |expr: &str| -> f32 { - if !expr.contains("sin(") { - 0.0 - } else if expr.contains("y*w") || expr.contains("y * w") { - 2.0 - } else { - 1.0 + let p1 = pt("PointIn1"); + let p2 = pt("PointIn2"); + let p3 = pt("PointIn3"); + let p4 = pt("PointIn4"); + + let lut_names = ["LUTIn1", "LUTIn2", "LUTIn3", "LUTIn4"]; + let lut_splines: [Option<&model::BezierSpline>; 4] = std::array::from_fn(|idx| { + node.connected_node(lut_names[idx]) + .and_then(|s| comp.splines.get(s)) + .filter(|sp| !sp.keyframes.is_empty()) + }); + let mut luts = [[0.0f32; 4]; 256]; + for (i, slot) in luts.iter_mut().enumerate() { + let x = i as f64 / 255.0; + for ch in 0..4 { + slot[ch] = lut_splines[ch].map_or(x as f32, |sp| sp.eval(x) as f32); } + } + let mut lh = DefaultHasher::new(); + bytemuck::cast_slice::<[f32; 4], u8>(&luts).hash(&mut lh); + let lut_hash = lh.finish(); + + let params = crate::custom_shader::CustomParams { + n0: [n("NumberIn1"), n("NumberIn2"), n("NumberIn3"), n("NumberIn4")], + n1: [n("NumberIn5"), n("NumberIn6"), n("NumberIn7"), n("NumberIn8")], + p0: [p1[0], p1[1], p2[0], p2[1]], + p1: [p3[0], p3[1], p4[0], p4[1]], + img_dims1: [w1, h1, w2, h2], + img_dims2: [w3, h3, time as f32, blend], + mask_proc: [ + if mask.is_some() { 1.0 } else { 0.0 }, + if mask_inv { 1.0 } else { 0.0 }, + comp.eval_number(node, "ProcessRed", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "ProcessGreen", time, 1.0, &self.expr) as f32, + ], + proc_ba: [ + comp.eval_number(node, "ProcessBlue", time, 1.0, &self.expr) as f32, + comp.eval_number(node, "ProcessAlpha", time, 1.0, &self.expr) as f32, + if eff_depth.is_float() { 1.0 } else { 0.0 }, + 0.0, + ], + luts, }; - let rm = wave_mode(red_expr); - let gm = wave_mode(green_expr); - let bm = wave_mode(blue_expr); - if rm > 0.5 || gm > 0.5 || bm > 0.5 { - let mut u = UniformParams::default(); - // Fusion CustomTool `w` is Image1's full-res pixel width! - let w_ref = (size[0] * self.proxy_scale.max(1)) as f32; - u.p[0] = [n1, n2, w_ref, 0.0]; - u.p[1] = [rm, gm, bm, 1.0]; - let key = self.make_key(node, "CustomWave", size, &[], 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 = create_texture(&self.device, size, key); - self.dispatch_op(enc, ShaderOp::CustomWave, &self.dummy.view, &self.dummy.view, &self.dummy.view, &dst, &u); + + let prog_hash = program.program_hash(); + let scalar_slice: [[f32; 4]; 8] = [ + params.n0, + params.n1, + params.p0, + params.p1, + params.img_dims1, + params.img_dims2, + params.mask_proc, + params.proc_ba, + ]; + let key = self.make_key( + node, + "CustomTool", + size, + &[ + img1.as_ref().map_or(0, |t| t.content_hash), + img2.as_ref().map_or(0, |t| t.content_hash), + img3.as_ref().map_or(0, |t| t.content_hash), + mask.as_ref().map_or(0, |m| m.content_hash), + prog_hash, + lut_hash, + eff_depth as u64, + ], + bytemuck::cast_slice(&scalar_slice), + ); + 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, eff_depth, key); + let v1 = img1.as_ref().map_or(&self.dummy.view, |t| &t.view); + let v2 = img2.as_ref().map_or(&self.dummy.view, |t| &t.view); + let v3 = img3.as_ref().map_or(&self.dummy.view, |t| &t.view); + let vm = mask.as_ref().map_or(&self.dummy.view, |m| &m.view); + + let ok = self.custom_shaders.dispatch( + &self.device, + &self.queue, + enc, + &program, + dst.format, + v1, + v2, + v3, + vm, + &dst.view, + dst.size, + ¶ms, + ); + if ok { self.cache.insert(key, dst.clone(), node.id, frame_i); - return dst; - } - if red_expr.contains("1-r1") || red_expr.contains("1 - r1") { - return self.eval_invert(comp, node, time, frame_i, enc, visiting, stats); - } - // Fallback: passthrough Image1 - if let Some(src_id) = node.connected_node("Image1").and_then(|s| comp.find_node(s)) { - self.eval_node(comp, src_id, time, enc, visiting, stats) + dst } else { - self.dummy.clone() + img1.unwrap_or_else(|| self.dummy.clone()) } } diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index 42bbf3db09d6ccb063bef7c98e54ec460cfd4239..f96eeb036ab9dbb59dab5cdf000d0e78ed79e75e 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -4,7 +4,7 @@ use crate::cache::{CacheMode, CachedTexture, EvalStats, NodeCache}; use crate::media::{MediaCache, TextPlusParams, rasterize_polyline_mask, rasterize_text_plus}; use bytemuck::{Pod, Zeroable}; -use model::{BitDepth, Comp, ExprEngine, Node, NodeId, ParamValue, default_main_input_port}; +use model::{BitDepth, Comp, ExprEngine, Node, NodeId, default_main_input_port}; use std::cell::{OnceCell, RefCell}; use std::collections::{HashMap, HashSet}; use std::collections::hash_map::DefaultHasher; @@ -118,6 +118,7 @@ enum ShaderOp { OutlineTint, OutlineComposite, TextOutline, + #[allow(dead_code)] CustomWave, Crop, GlowAdd, @@ -386,6 +387,7 @@ pub struct Engine { scene3d: crate::scene3d::Scene3DRenderer, optflow: std::sync::OnceLock, particles: crate::particles::ParticleCache, + custom_shaders: crate::custom_shader::CustomShaderCache, sprite_cache: HashMap<(NodeId, u64, i64), crate::particles::SpriteImage>, dummy: CachedTexture, pub cache: NodeCache, @@ -435,6 +437,7 @@ impl Engine { scene3d, optflow: std::sync::OnceLock::new(), particles: crate::particles::ParticleCache::default(), + custom_shaders: crate::custom_shader::CustomShaderCache::new(), sprite_cache: HashMap::new(), dummy, cache: NodeCache::new(crate::cache::DEFAULT_VRAM_BUDGET_MB), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7ce9331f7fe4cf8d5abd24ef6100c44066ccb71c..1b17f89c1ee4b1f643d5962cfd71b8669c781745 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1,6 +1,7 @@ pub mod audio; pub mod cache; pub mod cryptomatte; +pub mod custom_shader; pub mod eval; pub mod export; pub mod media; diff --git a/crates/model/src/comp.rs b/crates/model/src/comp.rs index 9a735b96ae6c3912fefe195271e233b57a24c829..5b366984d20deacb806a5598320da77400656f74 100644 --- a/crates/model/src/comp.rs +++ b/crates/model/src/comp.rs @@ -351,6 +351,13 @@ pub struct ShakeModifier { pub inputs: HashMap, } +/// Fusion standalone `Expression` modifier (`NumberExpression`, `PointExpressionX`, +/// `PointExpressionY`, `PointExpression`, `n1..n9` / `NumberIn1..9`, `p1..p9` / `PointIn1..9`). +#[derive(Clone, Debug, PartialEq)] +pub struct ExpressionModifier { + pub inputs: HashMap, +} + #[derive(Clone, Debug)] pub struct Comp { pub path: Option, @@ -384,6 +391,8 @@ pub struct Comp { pub text_cls: HashMap>, /// Procedural `Shake` modifiers keyed by modifier name (e.g. `"Shake1"`). pub shakes: HashMap, + /// Standalone `Expression` modifiers keyed by modifier name (e.g. `"Expression1"`). + pub expression_modifiers: HashMap, /// Preserved raw root `Composition { ... }` Lua AST for lossless `.comp` roundtrip. pub raw_root: Option, /// Generation counter incremented whenever any node, wire, or spline mutates. @@ -487,6 +496,7 @@ impl Comp { let mut polyline_splines = HashMap::new(); let mut text_cls = HashMap::new(); let mut shakes = HashMap::new(); + let mut expression_modifiers = HashMap::new(); let mut tracker_aliases: Vec<(String, String)> = Vec::new(); let mut macro_defaults: Vec<(String, String, ParamValue)> = Vec::new(); let mut instanced_from: Vec<(NodeId, String)> = Vec::new(); @@ -505,6 +515,7 @@ impl Comp { &mut polyline_splines, &mut text_cls, &mut shakes, + &mut expression_modifiers, &mut tracker_aliases, &mut macro_defaults, &mut instanced_from, @@ -629,6 +640,7 @@ impl Comp { polyline_splines, text_cls, shakes, + expression_modifiers, raw_root: Some(root.clone()), revision: 1, }) @@ -773,6 +785,19 @@ impl Comp { }; return self.eval_shake_axis(sh, axis, time, expr_engine); } + if let Some(em) = self.expression_modifiers.get(src) { + if let Some(v) = self.eval_expr_mod_number( + em, + binding.source_output.as_deref(), + time, + expr_engine, + 0, + ) { + if v.is_finite() { + return v; + } + } + } } binding .value @@ -813,6 +838,13 @@ impl Comp { let y = self.eval_shake_axis(sh, 1, time, expr_engine); return [x, y]; } + if let Some(em) = self.expression_modifiers.get(src) { + if let Some(pt) = self.eval_expr_mod_point(em, time, expr_engine, 0) { + if pt[0].is_finite() && pt[1].is_finite() { + return pt; + } + } + } } binding .value @@ -897,6 +929,299 @@ impl Comp { min_v + (max_v - min_v) * t01 } + fn eval_expr_mod_input_number( + &self, + em: &ExpressionModifier, + keys: &[&str], + time: f64, + default: f64, + expr_engine: &ExprEngine, + depth: u8, + ) -> f64 { + let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else { + return default; + }; + if let Some(expr) = &b.expression { + if let Some(v) = self.eval_modifier_inline_number(expr, time, expr_engine) { + if v.is_finite() { + return v; + } + } + } + if let Some(src) = &b.source_op { + if let Some(spl) = self.splines.get(src) { + return spl.eval(time); + } + if let Some(sh) = self.shakes.get(src) { + let axis = match b.source_output.as_deref() { + Some("Y") => 1, + _ => 0, + }; + return self.eval_shake_axis(sh, axis, time, expr_engine); + } + if depth < 8 { + if let Some(sub) = self.expression_modifiers.get(src) { + if let Some(v) = self.eval_expr_mod_number( + sub, + b.source_output.as_deref(), + time, + expr_engine, + depth + 1, + ) { + if v.is_finite() { + return v; + } + } + } + } + } + b.value.as_ref().and_then(ParamValue::as_f64).unwrap_or(default) + } + + fn eval_expr_mod_input_point( + &self, + em: &ExpressionModifier, + keys: &[&str], + time: f64, + default: [f64; 2], + expr_engine: &ExprEngine, + depth: u8, + ) -> [f64; 2] { + let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else { + return default; + }; + if let Some(expr) = &b.expression { + let trimmed = expr.trim(); + // Direct `NodeName.ParamName` reference to a Point input on another flow node. + if let Some((node_name, param_name)) = trimmed.split_once('.') { + if !param_name.contains('.') && !param_name.contains(' ') { + if let Some(nid) = self.find_node(node_name.trim()) { + return self.eval_point(self.node(nid), param_name.trim(), time, default, expr_engine); + } + } + } + let (sp, spts, en) = self.collect_global_expr_env(time); + if let Some(pt) = expr_engine.eval_point(trimmed, time, &sp, &spts, &en) { + if pt[0].is_finite() && pt[1].is_finite() { + return pt; + } + } + } + if let Some(src) = &b.source_op { + if let Some(pp) = self.poly_paths.get(src) { + let disp = pp + .displacement_op + .as_deref() + .and_then(|d| self.splines.get(d)) + .map(|sp| sp.eval(time)) + .unwrap_or(pp.displacement_value); + return pp.eval_center(disp); + } + if let Some(sh) = self.shakes.get(src) { + let x = self.eval_shake_axis(sh, 0, time, expr_engine); + let y = self.eval_shake_axis(sh, 1, time, expr_engine); + return [x, y]; + } + if depth < 8 { + if let Some(sub) = self.expression_modifiers.get(src) { + if let Some(pt) = self.eval_expr_mod_point(sub, time, expr_engine, depth + 1) { + if pt[0].is_finite() && pt[1].is_finite() { + return pt; + } + } + } + } + } + b.value.as_ref().and_then(ParamValue::as_point).unwrap_or(default) + } + + fn eval_modifier_inline_number( + &self, + expr: &str, + time: f64, + expr_engine: &ExprEngine, + ) -> Option { + let trimmed = expr.trim(); + if let Some((node_name, param_name)) = trimmed.split_once('.') { + if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') { + if let Some(nid) = self.find_node(node_name.trim()) { + return Some(self.eval_number(self.node(nid), param_name.trim(), time, 0.0, expr_engine)); + } + } + } + let (sp, spts, en) = self.collect_global_expr_env(time); + expr_engine.eval_number(trimmed, time, &sp, &spts, &en) + } + + fn collect_global_expr_env( + &self, + time: f64, + ) -> ( + HashMap, + HashMap, + HashMap>, + ) { + let mut env_nodes = HashMap::new(); + for n in &self.nodes { + let mut m = HashMap::new(); + for (k, b) in &n.inputs { + if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { + m.insert(k.clone(), v); + } else if let Some(src) = &b.source_op { + if let Some(sp) = self.splines.get(src) { + m.insert(k.clone(), sp.eval(time)); + } + } + } + if !m.is_empty() { + env_nodes.insert(n.name.clone(), m); + } + } + (HashMap::new(), HashMap::new(), env_nodes) + } + + fn build_expr_mod_vars( + &self, + em: &ExpressionModifier, + time: f64, + expr_engine: &ExprEngine, + depth: u8, + ) -> (HashMap, HashMap) { + let mut vars = HashMap::with_capacity(32); + let mut pts = HashMap::with_capacity(18); + vars.insert("time".to_owned(), time); + vars.insert("pi".to_owned(), std::f64::consts::PI); + vars.insert("e".to_owned(), std::f64::consts::E); + + for i in 1..=9 { + let short = format!("n{i}"); + let long = format!("NumberIn{i}"); + let v = self.eval_expr_mod_input_number( + em, + &[short.as_str(), long.as_str()], + time, + 0.0, + expr_engine, + depth, + ); + vars.insert(short, v); + vars.insert(long, v); + } + for i in 1..=9 { + let short = format!("p{i}"); + let long = format!("PointIn{i}"); + let pt = self.eval_expr_mod_input_point( + em, + &[short.as_str(), long.as_str()], + time, + [0.5, 0.5], + expr_engine, + depth, + ); + vars.insert(format!("p{i}x"), pt[0]); + vars.insert(format!("p{i}y"), pt[1]); + pts.insert(short, pt); + pts.insert(long, pt); + } + for (k, b) in &em.inputs { + if !vars.contains_key(k) { + if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) { + vars.insert(k.clone(), v); + } + } + } + (vars, pts) + } + + fn eval_expr_mod_formula( + &self, + formula: &str, + time: f64, + vars: &HashMap, + pts: &HashMap, + expr_engine: &ExprEngine, + ) -> Option { + let trimmed = formula.trim(); + if trimmed.is_empty() { + return None; + } + if let Some(v) = eval_fusion_math_expr(trimmed, vars) { + return Some(v); + } + // Fallback to Lua SimpleExpression engine for Lua-specific formulas + let (_, _, en) = self.collect_global_expr_env(time); + expr_engine.eval_number(trimmed, time, vars, pts, &en) + } + + fn eval_expr_mod_number( + &self, + em: &ExpressionModifier, + source_output: Option<&str>, + time: f64, + expr_engine: &ExprEngine, + depth: u8, + ) -> Option { + if depth >= 8 { + return None; + } + let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth); + let key = match source_output { + Some("X") => "PointExpressionX", + Some("Y") => "PointExpressionY", + _ => "NumberExpression", + }; + let formula = em + .inputs + .get(key) + .and_then(|b| b.value.as_ref()) + .and_then(ParamValue::as_str)?; + self.eval_expr_mod_formula(formula, time, &vars, &pts, expr_engine) + } + + fn eval_expr_mod_point( + &self, + em: &ExpressionModifier, + time: f64, + expr_engine: &ExprEngine, + depth: u8, + ) -> Option<[f64; 2]> { + if depth >= 8 { + return None; + } + let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth); + let fx = em + .inputs + .get("PointExpressionX") + .and_then(|b| b.value.as_ref()) + .and_then(ParamValue::as_str); + let fy = em + .inputs + .get("PointExpressionY") + .and_then(|b| b.value.as_ref()) + .and_then(ParamValue::as_str); + if fx.is_some() || fy.is_some() { + let x = fx + .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine)) + .unwrap_or(0.5); + let y = fy + .and_then(|s| self.eval_expr_mod_formula(s, time, &vars, &pts, expr_engine)) + .unwrap_or(0.5); + return Some([x, y]); + } + if let Some(fp) = em + .inputs + .get("PointExpression") + .and_then(|b| b.value.as_ref()) + .and_then(ParamValue::as_str) + { + let (_, _, en) = self.collect_global_expr_env(time); + if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) { + return Some(pt); + } + } + None + } + pub fn eval_text( &self, node: &Node, @@ -1782,6 +2107,7 @@ fn parse_tools_table( polyline_splines: &mut HashMap)>)>, text_cls: &mut HashMap>, shakes: &mut HashMap, + expression_modifiers: &mut HashMap, tracker_aliases: &mut Vec<(String, String)>, macro_defaults: &mut Vec<(String, String, ParamValue)>, instanced_from: &mut Vec<(NodeId, String)>, @@ -1888,6 +2214,40 @@ fn parse_tools_table( shakes.insert(name.clone(), ShakeModifier { inputs }); continue; } + if kind == "Expression" { + let mut inputs = HashMap::new(); + if let Some(in_tbl) = tbl.get_table("Inputs") { + for (ik, iv) in &in_tbl.entries { + let LuaKey::Str(in_name) = ik else { continue }; + let Some(it) = iv.as_table() else { continue }; + inputs.insert(in_name.clone(), parse_input_binding(it)); + } + } + if let Some(uc) = tbl.get_table("UserControls") { + for (uk, uv) in &uc.entries { + let LuaKey::Str(uname) = uk else { continue }; + let Some(ut) = uv.as_table() else { continue }; + let missing = inputs.get(uname).is_none_or(|b| { + b.value.is_none() && b.source_op.is_none() && b.expression.is_none() + }); + if missing { + if let Some(val) = ut.get("INP_Default").map(parse_param_value) { + inputs.insert( + uname.clone(), + InputBinding { + value: Some(val), + source_op: None, + source_output: None, + expression: None, + }, + ); + } + } + } + } + expression_modifiers.insert(name.clone(), ExpressionModifier { inputs }); + continue; + } if is_modifier_type(&kind) { if tbl.get_table("KeyFrames").is_some() { splines.insert(name.clone(), BezierSpline::from_lua(name.clone(), tbl)); @@ -2018,6 +2378,7 @@ fn parse_tools_table( polyline_splines, text_cls, shakes, + expression_modifiers, tracker_aliases, macro_defaults, instanced_from, @@ -2053,6 +2414,7 @@ fn parse_tools_table( polyline_splines, text_cls, shakes, + expression_modifiers, tracker_aliases, macro_defaults, instanced_from, @@ -2089,3 +2451,440 @@ fn parse_tools_table( }); } } + +/// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`. +/// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`. +fn eval_fusion_math_expr(src: &str, vars: &HashMap) -> Option { + struct Parser<'a> { + bytes: &'a [u8], + pos: usize, + vars: &'a HashMap, + } + + impl<'a> Parser<'a> { + fn skip_ws(&mut self) { + while self.pos < self.bytes.len() { + let b = self.bytes[self.pos]; + if b.is_ascii_whitespace() { + self.pos += 1; + } else if b == b'/' && self.bytes.get(self.pos + 1) == Some(&b'/') { + while self.pos < self.bytes.len() && self.bytes[self.pos] != b'\n' { + self.pos += 1; + } + } else { + break; + } + } + } + + fn peek(&mut self) -> Option { + self.skip_ws(); + self.bytes.get(self.pos).copied() + } + + fn eat_str(&mut self, s: &str) -> bool { + self.skip_ws(); + if self.bytes[self.pos..].starts_with(s.as_bytes()) { + self.pos += s.len(); + true + } else { + false + } + } + + fn parse_or(&mut self) -> Option { + let mut v = self.parse_and()?; + loop { + self.skip_ws(); + if self.eat_str("||") || self.eat_str("|") { + let r = self.parse_and()?; + v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 }; + } else { + break; + } + } + Some(v) + } + + fn parse_and(&mut self) -> Option { + let mut v = self.parse_cmp()?; + loop { + self.skip_ws(); + if self.eat_str("&&") || self.eat_str("&") { + let r = self.parse_cmp()?; + v = if v != 0.0 && r != 0.0 { 1.0 } else { 0.0 }; + } else { + break; + } + } + Some(v) + } + + fn parse_cmp(&mut self) -> Option { + let mut v = self.parse_add()?; + loop { + self.skip_ws(); + if self.eat_str("<=") { + let r = self.parse_add()?; + v = if v <= r { 1.0 } else { 0.0 }; + } else if self.eat_str(">=") { + let r = self.parse_add()?; + v = if v >= r { 1.0 } else { 0.0 }; + } else if self.eat_str("==") || self.eat_str("=") { + let r = self.parse_add()?; + v = if (v - r).abs() <= 1e-12 { 1.0 } else { 0.0 }; + } else if self.eat_str("!=") || self.eat_str("~=") || self.eat_str("<>") { + let r = self.parse_add()?; + v = if (v - r).abs() > 1e-12 { 1.0 } else { 0.0 }; + } else if self.eat_str("<") { + let r = self.parse_add()?; + v = if v < r { 1.0 } else { 0.0 }; + } else if self.eat_str(">") { + let r = self.parse_add()?; + v = if v > r { 1.0 } else { 0.0 }; + } else { + break; + } + } + Some(v) + } + + fn parse_add(&mut self) -> Option { + let mut v = self.parse_mul()?; + loop { + match self.peek() { + Some(b'+') => { + self.pos += 1; + v += self.parse_mul()?; + } + Some(b'-') => { + self.pos += 1; + v -= self.parse_mul()?; + } + _ => break, + } + } + Some(v) + } + + fn parse_mul(&mut self) -> Option { + let mut v = self.parse_pow()?; + loop { + match self.peek() { + Some(b'*') => { + self.pos += 1; + v *= self.parse_pow()?; + } + Some(b'/') => { + self.pos += 1; + let r = self.parse_pow()?; + v = if r.abs() < 1e-12 { 0.0 } else { v / r }; + } + Some(b'%') => { + self.pos += 1; + let r = self.parse_pow()?; + v = if r.abs() < 1e-12 { 0.0 } else { v - r * (v / r).floor() }; + } + _ => break, + } + } + Some(v) + } + + fn parse_pow(&mut self) -> Option { + let base = self.parse_unary()?; + if self.peek() == Some(b'^') { + self.pos += 1; + let exp = self.parse_pow()?; + Some(if base > 0.0 { + base.powf(exp) + } else if base == 0.0 { + if exp == 0.0 { 1.0 } else { 0.0 } + } else if (exp - exp.round()).abs() < 1e-6 { + let p = base.abs().powf(exp); + if (exp.round() as i64) & 1 != 0 { -p } else { p } + } else { + 0.0 + }) + } else { + Some(base) + } + } + + fn parse_unary(&mut self) -> Option { + match self.peek() { + Some(b'-') => { + self.pos += 1; + Some(-self.parse_unary()?) + } + Some(b'+') => { + self.pos += 1; + self.parse_unary() + } + Some(b'!') => { + self.pos += 1; + let v = self.parse_unary()?; + Some(if v == 0.0 { 1.0 } else { 0.0 }) + } + _ => self.parse_primary(), + } + } + + fn parse_primary(&mut self) -> Option { + let b = self.peek()?; + if b == b'(' { + self.pos += 1; + let v = self.parse_or()?; + if self.peek() != Some(b')') { + return None; + } + self.pos += 1; + return Some(v); + } + if b.is_ascii_digit() || b == b'.' { + let start = self.pos; + while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { + self.pos += 1; + } + if self.bytes.get(self.pos) == Some(&b'.') { + self.pos += 1; + while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { + self.pos += 1; + } + } + if matches!(self.bytes.get(self.pos), Some(b'e' | b'E')) { + let exp_pos = self.pos; + self.pos += 1; + if matches!(self.bytes.get(self.pos), Some(b'+' | b'-')) { + self.pos += 1; + } + let dig_start = self.pos; + while self.pos < self.bytes.len() && self.bytes[self.pos].is_ascii_digit() { + self.pos += 1; + } + if self.pos == dig_start { + self.pos = exp_pos; + } + } + let s = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?; + return s.parse::().ok(); + } + if b.is_ascii_alphabetic() || b == b'_' { + let start = self.pos; + while self.pos < self.bytes.len() + && (self.bytes[self.pos].is_ascii_alphanumeric() || self.bytes[self.pos] == b'_') + { + self.pos += 1; + } + let ident = std::str::from_utf8(&self.bytes[start..self.pos]).ok()?; + if self.peek() == Some(b'(') { + self.pos += 1; + let mut args = Vec::new(); + if self.peek() != Some(b')') { + loop { + args.push(self.parse_or()?); + if self.peek() == Some(b',') { + self.pos += 1; + } else { + break; + } + } + } + if self.peek() != Some(b')') { + return None; + } + self.pos += 1; + return Self::eval_fn(ident, &args); + } + return self.vars.get(ident).copied(); + } + None + } + + fn eval_fn(name: &str, args: &[f64]) -> Option { + const DEG2RAD: f64 = std::f64::consts::PI / 180.0; + const RAD2DEG: f64 = 180.0 / std::f64::consts::PI; + let a = |i: usize| args.get(i).copied(); + Some(match name { + "sin" => (a(0)? * DEG2RAD).sin(), + "cos" => (a(0)? * DEG2RAD).cos(), + "tan" => (a(0)? * DEG2RAD).tan(), + "asin" => a(0)?.clamp(-1.0, 1.0).asin() * RAD2DEG, + "acos" => a(0)?.clamp(-1.0, 1.0).acos() * RAD2DEG, + "atan" => a(0)?.atan() * RAD2DEG, + "atan2" => a(0)?.atan2(a(1)?) * RAD2DEG, + "sinr" => a(0)?.sin(), + "cosr" => a(0)?.cos(), + "tanr" => a(0)?.tan(), + "asinr" => a(0)?.clamp(-1.0, 1.0).asin(), + "acosr" => a(0)?.clamp(-1.0, 1.0).acos(), + "atanr" => a(0)?.atan(), + "atan2r" => a(0)?.atan2(a(1)?), + "sinh" => a(0)?.sinh(), + "cosh" => a(0)?.cosh(), + "tanh" => a(0)?.tanh(), + "deg" => a(0)? * RAD2DEG, + "rad" => a(0)? * DEG2RAD, + "abs" => a(0)?.abs(), + "sqrt" => a(0)?.max(0.0).sqrt(), + "pow" => a(0)?.powf(a(1)?), + "exp" => a(0)?.exp(), + "log" | "ln" => a(0)?.max(1e-12).ln(), + "log10" => a(0)?.max(1e-12).log10(), + "log2" => a(0)?.max(1e-12).log2(), + "floor" | "int" => a(0)?.floor(), + "ceil" => a(0)?.ceil(), + "round" => a(0)?.round(), + "trunc" => a(0)?.trunc(), + "fract" => a(0)? - a(0)?.floor(), + "sign" => { + let v = a(0)?; + if v > 0.0 { 1.0 } else if v < 0.0 { -1.0 } else { 0.0 } + } + "min" => { + if args.is_empty() { return None; } + args.iter().copied().fold(f64::INFINITY, f64::min) + } + "max" => { + if args.is_empty() { return None; } + args.iter().copied().fold(f64::NEG_INFINITY, f64::max) + } + "clamp" => a(0)?.clamp(a(1)?, a(2)?), + "mod" => { + let (x, y) = (a(0)?, a(1)?); + if y.abs() < 1e-12 { 0.0 } else { x - y * (x / y).floor() } + } + "if" | "iif" => { + if a(0)? != 0.0 { a(1)? } else { a(2)? } + } + "dist" => { + let (x1, y1, x2, y2) = (a(0)?, a(1)?, a(2)?, a(3)?); + ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt() + } + "hypot" => a(0)?.hypot(a(1)?), + "mix" | "lerp" => { + let (x, y, t) = (a(0)?, a(1)?, a(2)?); + x + (y - x) * t + } + "step" => if a(1)? < a(0)? { 0.0 } else { 1.0 }, + "smoothstep" => { + let (e0, e1, x) = (a(0)?, a(1)?, a(2)?); + let denom = e1 - e0; + let t = if denom.abs() < 1e-12 { 0.0 } else { ((x - e0) / denom).clamp(0.0, 1.0) }; + t * t * (3.0 - 2.0 * t) + } + _ => return None, + }) + } + } + + let mut p = Parser { + bytes: src.as_bytes(), + pos: 0, + vars, + }; + let val = p.parse_or()?; + p.skip_ws(); + if p.pos != p.bytes.len() || !val.is_finite() { + return None; + } + Some(val) +} + +#[cfg(test)] +mod expression_modifier_tests { + use super::*; + + #[test] + fn evaluates_standalone_expression_modifier_number_and_chained() { + let src = r#"Composition { + Tools = ordered() { + XF1 = Transform { + Inputs = { + Angle = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", }, + Size = Input { SourceOp = "HourHandExpr", Source = "NumberResult", }, + }, + }, + Clock_MinHandExpr = Expression { + Inputs = { + n1 = Input { Value = 1, }, + n2 = Input { SourceOp = "TimeSpline", Source = "Value", }, + NumberExpression = Input { Value = "if(n1>0.5,floor(-n2)*30,-n2*30)", }, + }, + }, + HourHandExpr = Expression { + Inputs = { + n1 = Input { SourceOp = "Clock_MinHandExpr", Source = "NumberResult", }, + NumberExpression = Input { Value = "n1/12", }, + }, + }, + TimeSpline = BezierSpline { + KeyFrames = { + [0] = { 0.0, Flags = { Linear = true } }, + [10] = { 2.5, Flags = { Linear = true } }, + }, + }, + }, + }"#; + + let comp = Comp::from_fusion_str(src).expect("parse comp"); + assert!(comp.expression_modifiers.contains_key("Clock_MinHandExpr")); + assert!(comp.expression_modifiers.contains_key("HourHandExpr")); + // Expression modifiers are modifiers, not flow nodes + assert!(comp.find_node("Clock_MinHandExpr").is_none()); + + let expr = ExprEngine::new(); + let xf = comp.node(comp.find_node("XF1").unwrap()); + // At t=10: n2 = 2.5, floor(-2.5) = -3.0, -3.0 * 30 = -90.0 + let angle = comp.eval_number(xf, "Angle", 10.0, 0.0, &expr); + assert!((angle - (-90.0)).abs() < 1e-6, "got {angle}"); + // Chained HourHandExpr: n1 / 12 = -90 / 12 = -7.5 + let size = comp.eval_number(xf, "Size", 10.0, 1.0, &expr); + assert!((size - (-7.5)).abs() < 1e-6, "got {size}"); + + // Lossless roundtrip preserves Expression modifiers + let saved = comp.to_fusion_string(); + let reloaded = Comp::from_fusion_str(&saved).expect("reload"); + let r_xf = reloaded.node(reloaded.find_node("XF1").unwrap()); + assert!((reloaded.eval_number(r_xf, "Angle", 10.0, 0.0, &expr) - (-90.0)).abs() < 1e-6); + } + + #[test] + fn evaluates_standalone_expression_modifier_point_and_dist_trig() { + let src = r#"Composition { + Tools = ordered() { + XF1 = Transform { + Inputs = { + Center = Input { SourceOp = "PtExpr", Source = "PointResult", }, + Angle = Input { SourceOp = "TrigExpr", Source = "NumberResult", }, + }, + }, + PtExpr = Expression { + Inputs = { + p1 = Input { Value = { 0.8, 0.2 }, }, + n1 = Input { Value = 10, }, + PointExpressionX = Input { Value = "if(p1x>0.5, 0.5 + time*dist(p1x,p1y,0.5,p1y)/n1, 0.5)", }, + PointExpressionY = Input { Value = "-p1y + p1y*0.5 + 0.5", }, + }, + }, + TrigExpr = Expression { + Inputs = { + NumberIn1 = Input { Value = 90, }, + NumberExpression = Input { Value = "sin(n1) + cos(0) + (1/0)", }, + }, + }, + }, + }"#; + + let comp = Comp::from_fusion_str(src).expect("parse comp"); + let expr = ExprEngine::new(); + let xf = comp.node(comp.find_node("XF1").unwrap()); + // At t=5: dist(0.8,0.2,0.5,0.2) = 0.3, x = 0.5 + 5*0.3/10 = 0.65, y = -0.2 + 0.1 + 0.5 = 0.4 + let pt = comp.eval_point(xf, "Center", 5.0, [0.5, 0.5], &expr); + assert!((pt[0] - 0.65).abs() < 1e-6, "got x={}", pt[0]); + assert!((pt[1] - 0.40).abs() < 1e-6, "got y={}", pt[1]); + // sin(90 deg) + cos(0 deg) + safe_div(1,0) = 1 + 1 + 0 = 2.0 + let ang = comp.eval_number(xf, "Angle", 0.0, 0.0, &expr); + assert!((ang - 2.0).abs() < 1e-6, "got {ang}"); + } +} diff --git a/scripts/fusion_probes.py b/scripts/fusion_probes.py index 72b95d9c294baf0879d11c71f8827e48fefdc1b2..2d3e3f0638a3d3b96aeaa524a8ba3cf2b4a4afc1 100644 --- a/scripts/fusion_probes.py +++ b/scripts/fusion_probes.py @@ -2000,6 +2000,170 @@ def build_probe_archive_3d(): return comp_path, "archive_3d", cases +def build_probe_custom_tool(): + """Shale #18 probe: CustomTool per-pixel DSL (waves, premul invert, samplers, if, LUTIn1, Setup/Inter, mask/blend) + Expression modifier.""" + chart = generate_color_chart() + grid = generate_grid_chart() + cases = [ + (0, "custom_wave_sin_deg"), + (1, "custom_premul_invert_i1"), + (2, "custom_samplers_b_w_d"), + (3, "custom_if_img2_pt_num"), + (4, "custom_lut1_curve"), + (5, "custom_setup_c1_mod_dist"), + (6, "custom_mask_blend_procb0"), + (7, "expression_modifier_num_pt"), + ] + nodes = [ + make_loader("ChartLoader", chart, post_mult=1), + make_loader("GridLoader", grid, post_mult=1), + """\t\tBlackBG = Background { Inputs = { Width = Input { Value = 512, }, Height = Input { Value = 512, }, TopLeftAlpha = Input { Value = 1, }, }, }, +\t\t-- f00: sin/cos wave generator matching 20_falling CustomTool1 +\t\tOp_0 = Custom { +\t\t\tInputs = { +\t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, +\t\t\t\tNumberIn1 = Input { Value = 0.7413, }, +\t\t\t\tNumberIn2 = Input { Value = 10.655, }, +\t\t\t\tRedExpression = Input { Value = "sin(x*w*n1 + n2*n1*w)*0.5+0.5", }, +\t\t\t\tGreenExpression = Input { Value = "sin(y*w*n1 + n2*n1*w)*0.5+0.5", }, +\t\t\t\tBlueExpression = Input { Value = "0\\n", }, +\t\t\t\tAlphaExpression = Input { Value = "1", }, +\t\t\t}, +\t\t}, +\t\t-- f01: Premul/unpremul invert via Intermediate1 matching CustomTool2 +\t\tOp_1 = Custom { +\t\t\tInputs = { +\t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, +\t\t\t\tIntermediate1 = Input { Value = "a1", }, +\t\t\t\tRedExpression = Input { Value = "(1-r1/a1)*i1", }, +\t\t\t\tGreenExpression = Input { Value = "(1-g1/a1)*i1", }, +\t\t\t\tBlueExpression = Input { Value = "(1-b1/a1)*i1", }, +\t\t\t\tAlphaExpression = Input { Value = "i1", }, +\t\t\t}, +\t\t}, +\t\t-- f02: Offset image samplers (b=black, w=wrap, d=duplicate) +\t\tOp_2 = Custom { +\t\t\tInputs = { +\t\t\t\tImage1 = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tRedExpression = Input { Value = "getr1b(x + 0.15, y - 0.1)", }, +\t\t\t\tGreenExpression = Input { Value = "getg1w(x + 0.25, y + 0.25)", }, +\t\t\t\tBlueExpression = Input { Value = "getb1d(x - 0.2, y + 0.2)", }, +\t\t\t\tAlphaExpression = Input { Value = "1", }, +\t\t\t}, +\t\t}, +\t\t-- f03: if(...), Image2, PointIn1, NumberIn1 +\t\tOp_3 = Custom { +\t\t\tInputs = { +\t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, +\t\t\t\tImage2 = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tNumberIn1 = Input { Value = 0.6, }, +\t\t\t\tPointIn1 = Input { Value = { 0.4, 0.6 }, }, +\t\t\t\tRedExpression = Input { Value = "if(x > p1x, r1 * n1, r2)", }, +\t\t\t\tGreenExpression = Input { Value = "if(y > p1y, g1, g2 * n1)", }, +\t\t\t\tBlueExpression = Input { Value = "if(x > p1x && y > p1y, b2, b1)", }, +\t\t\t\tAlphaExpression = Input { Value = "1", }, +\t\t\t}, +\t\t}, +\t\t-- f04: LUTIn1 curved spline +\t\tOp_4LUTIn1 = LUTBezier { +\t\t\tKeyColorSplines = { +\t\t\t\t[0] = { +\t\t\t\t\t[0] = { 0.0, RH = { 0.15, 0.6 }, }, +\t\t\t\t\t[0.5] = { 0.85, LH = { 0.35, 0.85 }, RH = { 0.65, 0.85 }, }, +\t\t\t\t\t[1] = { 0.2, LH = { 0.85, 0.4 }, }, +\t\t\t\t}, +\t\t\t}, +\t\t}, +\t\tOp_4 = Custom { +\t\t\tInputs = { +\t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, +\t\t\t\tLUTIn1 = Input { SourceOp = "Op_4LUTIn1", Source = "Value", }, +\t\t\t\tRedExpression = Input { Value = "getlut1(r1)", }, +\t\t\t\tGreenExpression = Input { Value = "getlut1(g1)", }, +\t\t\t\tBlueExpression = Input { Value = "getlut1(b1)", }, +\t\t\t\tAlphaExpression = Input { Value = "a1", }, +\t\t\t}, +\t\t}, +\t\t-- f05: Setup1/2, Intermediate1, c1, e^-(), %, dist, max(3) +\t\tOp_5 = Custom { +\t\t\tInputs = { +\t\t\t\tImage1 = Input { SourceOp = "ChartLoader", Source = "Output", }, +\t\t\t\tNumberIn1 = Input { Value = 0.4, }, +\t\t\t\tNumberIn2 = Input { Value = 0.2, }, +\t\t\t\tSetup1 = Input { Value = "1 - n1", }, +\t\t\t\tIntermediate1 = Input { Value = "max(0, 1 - dist(x, y, 0.5, 0.5) * 2)", }, +\t\t\t\tRedExpression = Input { Value = "if(c1>n1, n1+s1*(1-e^-((c1-n1)/s1)), c1) * i1", }, +\t\t\t\tGreenExpression = Input { Value = "((x * 4) % 1) * i1", }, +\t\t\t\tBlueExpression = Input { Value = "max(r1, g1, b1) * i1", }, +\t\t\t\tAlphaExpression = Input { Value = "1", }, +\t\t\t}, +\t\t}, +\t\t-- f06: EffectMask + Blend=0.75 + ProcessBlue=0 +\t\tMask6 = EllipseMask { Inputs = { MaskWidth = Input { Value = 512, }, MaskHeight = Input { Value = 512, }, Width = Input { Value = 0.65, }, Height = Input { Value = 0.65, }, }, }, +\t\tOp_6 = Custom { +\t\t\tInputs = { +\t\t\t\tEffectMask = Input { SourceOp = "Mask6", Source = "Mask", }, +\t\t\t\tBlend = Input { Value = 0.75, }, +\t\t\t\tProcessBlue = Input { Value = 0, }, +\t\t\t\tImage1 = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tRedExpression = Input { Value = "1 - r1", }, +\t\t\t\tGreenExpression = Input { Value = "1 - g1", }, +\t\t\t\tBlueExpression = Input { Value = "0", }, +\t\t\t\tAlphaExpression = Input { Value = "a1", }, +\t\t\t}, +\t\t}, +\t\t-- f07: Standalone Expression modifier driving CustomTool NumberIn1 & Transform Center +\t\tExprNum7 = Expression { +\t\t\tInputs = { +\t\t\t\tn1 = Input { Value = 1.0, }, +\t\t\t\tNumberExpression = Input { Value = "if(n1>0.5, sin(90)*0.5 + 0.25, 0.1)", }, +\t\t\t}, +\t\t}, +\t\tExprPt7 = Expression { +\t\t\tInputs = { +\t\t\t\tp1 = Input { Value = { 0.8, 0.2 }, }, +\t\t\t\tPointExpressionX = Input { Value = "0.5 + (p1x - 0.5) * 0.5", }, +\t\t\t\tPointExpressionY = Input { Value = "0.6", }, +\t\t\t}, +\t\t}, +\t\tXf7 = Transform { +\t\t\tInputs = { +\t\t\t\tInput = Input { SourceOp = "GridLoader", Source = "Output", }, +\t\t\t\tCenter = Input { SourceOp = "ExprPt7", Source = "PointResult", }, +\t\t\t\tSize = Input { Value = 0.7, }, +\t\t\t}, +\t\t}, +\t\tOp_7 = Custom { +\t\t\tInputs = { +\t\t\t\tImage1 = Input { SourceOp = "Xf7", Source = "Output", }, +\t\t\t\tNumberIn1 = Input { SourceOp = "ExprNum7", Source = "NumberResult", }, +\t\t\t\tRedExpression = Input { Value = "r1 * n1", }, +\t\t\t\tGreenExpression = Input { Value = "g1 * n1", }, +\t\t\t\tBlueExpression = Input { Value = "b1", }, +\t\t\t\tAlphaExpression = Input { Value = "a1", }, +\t\t\t}, +\t\t},""", + ] + 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"CT_{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, "custom_tool")) + comp_path = local_root() / "comps" / "probe_custom_tool.comp" + comp_path.write_text(make_comp("\n".join(nodes + splines), len(cases) - 1)) + return comp_path, "custom_tool", cases + + def main(): ensure_dirs() which = [a for a in sys.argv[1:] if not a.startswith("--")] or ["merge"] @@ -2019,6 +2183,7 @@ def main(): "moon_3d": build_probe_moon_3d, "ultrakey": build_probe_ultrakey, "archive_3d": build_probe_archive_3d, + "custom_tool": build_probe_custom_tool, "glow": build_probe_glow, "text": build_probe_text, "noise_text": build_probe_noise_text, -- 2.54.1