1//! General Fusion `CustomTool` (`Custom`) per-pixel math DSL parser, WGSL codegen,
2//! and cached `wgpu::ComputePipeline` compiler/dispatcher.
3
4use bytemuck::{Pod, Zeroable};
5use std::collections::HashMap;
6use std::collections::hash_map::DefaultHasher;
7use std::hash::{Hash, Hasher};
8use std::num::NonZeroU64;
9
10/// Uniform payload uploaded per `CustomTool` compute dispatch (4224 bytes, 16-byte aligned).
11#[repr(C)]
12#[derive(Clone, Copy, Pod, Zeroable)]
13pub struct CustomParams {
14 /// `n1, n2, n3, n4` (`NumberIn1..4`, default 0.0)
15 pub n0: [f32; 4],
16 /// `n5, n6, n7, n8` (`NumberIn5..8`, default 0.0)
17 pub n1: [f32; 4],
18 /// `p1x, p1y, p2x, p2y` (`PointIn1..2`, default 0.5)
19 pub p0: [f32; 4],
20 /// `p3x, p3y, p4x, p4y` (`PointIn3..4`, default 0.5)
21 pub p1: [f32; 4],
22 /// `w1, h1, w2, h2` (full-resolution image dimensions in pixels)
23 pub img_dims1: [f32; 4],
24 /// `w3, h3, time, blend`
25 pub img_dims2: [f32; 4],
26 /// `has_mask, mask_invert, proc_r, proc_g`
27 pub mask_proc: [f32; 4],
28 /// `proc_b, proc_a, hdr_float, 0.0`
29 pub proc_ba: [f32; 4],
30 /// 256-sample baked 1D LUTs for `(LUTIn1, LUTIn2, LUTIn3, LUTIn4)`.
31 pub luts: [[f32; 4]; 256],
32}
33
34impl Default for CustomParams {
35 fn default() -> Self {
36 let mut luts = [[0.0f32; 4]; 256];
37 for (i, slot) in luts.iter_mut().enumerate() {
38 let v = i as f32 / 255.0;
39 *slot = [v, v, v, v];
40 }
41 Self {
42 n0: [0.0; 4],
43 n1: [0.0; 4],
44 p0: [0.5; 4],
45 p1: [0.5; 4],
46 img_dims1: [1.0, 1.0, 1.0, 1.0],
47 img_dims2: [1.0, 1.0, 0.0, 1.0],
48 mask_proc: [0.0, 0.0, 1.0, 1.0],
49 proc_ba: [1.0, 1.0, 0.0, 0.0],
50 luts,
51 }
52 }
53}
54
55/// Normalized expression bundle for a Fusion `CustomTool` node.
56#[derive(Clone, Debug, PartialEq, Eq, Hash)]
57pub struct CustomProgram {
58 pub setups: [String; 4],
59 pub intermediates: [String; 8],
60 pub red: String,
61 pub green: String,
62 pub blue: String,
63 pub alpha: String,
64}
65
66impl Default for CustomProgram {
67 fn default() -> Self {
68 Self {
69 setups: std::array::from_fn(|_| "0".to_owned()),
70 intermediates: std::array::from_fn(|_| "0".to_owned()),
71 red: "r1".to_owned(),
72 green: "g1".to_owned(),
73 blue: "b1".to_owned(),
74 alpha: "a1".to_owned(),
75 }
76 }
77}
78
79impl CustomProgram {
80 /// Returns a canonicalized copy with comments stripped, whitespace collapsed, and defaults applied.
81 pub fn normalized(&self) -> Self {
82 Self {
83 setups: std::array::from_fn(|i| normalize_expr(&self.setups[i], "0")),
84 intermediates: std::array::from_fn(|i| normalize_expr(&self.intermediates[i], "0")),
85 red: normalize_expr(&self.red, "r1"),
86 green: normalize_expr(&self.green, "g1"),
87 blue: normalize_expr(&self.blue, "b1"),
88 alpha: normalize_expr(&self.alpha, "a1"),
89 }
90 }
91
92 pub fn program_hash(&self) -> u64 {
93 let mut h = DefaultHasher::new();
94 self.hash(&mut h);
95 h.finish()
96 }
97}
98
99/// Strips `//` and `/* */` comments, trims, and collapses ASCII whitespace so `"0\n"` == `"0"`.
100pub fn normalize_expr(raw: &str, default: &str) -> String {
101 let bytes = raw.as_bytes();
102 let mut cleaned = String::with_capacity(raw.len());
103 let mut i = 0;
104 let mut last_ws = true;
105 while i < bytes.len() {
106 if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'/') {
107 i += 2;
108 while i < bytes.len() && bytes[i] != b'\n' {
109 i += 1;
110 }
111 continue;
112 }
113 if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
114 i += 2;
115 while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
116 i += 1;
117 }
118 i = (i + 2).min(bytes.len());
119 continue;
120 }
121 let ch = raw[i..].chars().next().unwrap();
122 let len = ch.len_utf8();
123 if ch.is_whitespace() {
124 if !last_ws {
125 cleaned.push(' ');
126 last_ws = true;
127 }
128 } else {
129 cleaned.push(ch);
130 last_ws = false;
131 }
132 i += len;
133 }
134 let trimmed = cleaned.trim();
135 if trimmed.is_empty() {
136 default.to_owned()
137 } else {
138 trimmed.to_owned()
139 }
140}
141
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143enum Channel {
144 Red,
145 Green,
146 Blue,
147 Alpha,
148}
149
150impl Channel {
151 fn swizzle(self) -> &'static str {
152 match self {
153 Self::Red => "r",
154 Self::Green => "g",
155 Self::Blue => "b",
156 Self::Alpha => "a",
157 }
158 }
159}
160
161// ============================================================================
162// Lexer & Recursive-Descent Parser -> WGSL Expression Compiler
163// ============================================================================
164
165#[derive(Clone, Debug, PartialEq)]
166enum Token {
167 Num(f64),
168 Ident(String),
169 Plus,
170 Minus,
171 Star,
172 Slash,
173 Percent,
174 Caret,
175 LParen,
176 RParen,
177 Comma,
178 Lt,
179 Le,
180 Gt,
181 Ge,
182 Eq,
183 Ne,
184 And,
185 Or,
186 Bang,
187}
188
189fn tokenize(src: &str) -> Result<Vec<Token>, String> {
190 let b = src.as_bytes();
191 let mut out = Vec::new();
192 let mut i = 0;
193 while i < b.len() {
194 let c = b[i];
195 if c.is_ascii_whitespace() {
196 i += 1;
197 continue;
198 }
199 if c == b'/' && b.get(i + 1) == Some(&b'/') {
200 i += 2;
201 while i < b.len() && b[i] != b'\n' {
202 i += 1;
203 }
204 continue;
205 }
206 if c == b'/' && b.get(i + 1) == Some(&b'*') {
207 i += 2;
208 while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') {
209 i += 1;
210 }
211 i = (i + 2).min(b.len());
212 continue;
213 }
214 if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) {
215 let start = i;
216 while i < b.len() && b[i].is_ascii_digit() {
217 i += 1;
218 }
219 if b.get(i) == Some(&b'.') {
220 i += 1;
221 while i < b.len() && b[i].is_ascii_digit() {
222 i += 1;
223 }
224 }
225 if matches!(b.get(i), Some(b'e' | b'E')) {
226 let exp_pos = i;
227 i += 1;
228 if matches!(b.get(i), Some(b'+' | b'-')) {
229 i += 1;
230 }
231 let dig_start = i;
232 while i < b.len() && b[i].is_ascii_digit() {
233 i += 1;
234 }
235 if i == dig_start {
236 i = exp_pos;
237 }
238 }
239 let s = &src[start..i];
240 let v: f64 = s.parse().map_err(|_| format!("invalid number literal '{s}'"))?;
241 out.push(Token::Num(v));
242 continue;
243 }
244 if c.is_ascii_alphabetic() || c == b'_' {
245 let start = i;
246 while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
247 i += 1;
248 }
249 out.push(Token::Ident(src[start..i].to_owned()));
250 continue;
251 }
252 let next = b.get(i + 1).copied();
253 match (c, next) {
254 (b'<', Some(b'=')) => { out.push(Token::Le); i += 2; }
255 (b'>', Some(b'=')) => { out.push(Token::Ge); i += 2; }
256 (b'=', Some(b'=')) => { out.push(Token::Eq); i += 2; }
257 (b'!', Some(b'=')) | (b'~', Some(b'=')) | (b'<', Some(b'>')) => { out.push(Token::Ne); i += 2; }
258 (b'&', Some(b'&')) => { out.push(Token::And); i += 2; }
259 (b'|', Some(b'|')) => { out.push(Token::Or); i += 2; }
260 (b'+', _) => { out.push(Token::Plus); i += 1; }
261 (b'-', _) => { out.push(Token::Minus); i += 1; }
262 (b'*', _) => { out.push(Token::Star); i += 1; }
263 (b'/', _) => { out.push(Token::Slash); i += 1; }
264 (b'%', _) => { out.push(Token::Percent); i += 1; }
265 (b'^', _) => { out.push(Token::Caret); i += 1; }
266 (b'(', _) => { out.push(Token::LParen); i += 1; }
267 (b')', _) => { out.push(Token::RParen); i += 1; }
268 (b',', _) => { out.push(Token::Comma); i += 1; }
269 (b'<', _) => { out.push(Token::Lt); i += 1; }
270 (b'>', _) => { out.push(Token::Gt); i += 1; }
271 (b'=', _) => { out.push(Token::Eq); i += 1; }
272 (b'&', _) => { out.push(Token::And); i += 1; }
273 (b'|', _) => { out.push(Token::Or); i += 1; }
274 (b'!', _) => { out.push(Token::Bang); i += 1; }
275 _ => return Err(format!("unexpected character '{}'", c as char)),
276 }
277 }
278 Ok(out)
279}
280
281const MAX_PARSE_DEPTH: usize = 64;
282
283struct ExprCompiler<'a> {
284 tokens: &'a [Token],
285 pos: usize,
286 channel: Channel,
287 max_setup: usize,
288 max_inter: usize,
289 depth: usize,
290}
291
292impl<'a> ExprCompiler<'a> {
293 fn peek(&self) -> Option<&Token> {
294 self.tokens.get(self.pos)
295 }
296
297 fn eat(&mut self, expected: &Token) -> bool {
298 if self.peek() == Some(expected) {
299 self.pos += 1;
300 true
301 } else {
302 false
303 }
304 }
305
306 fn with_depth(
307 &mut self,
308 f: impl FnOnce(&mut Self) -> Result<String, String>,
309 ) -> Result<String, String> {
310 if self.depth >= MAX_PARSE_DEPTH {
311 return Err(format!("expression exceeds maximum nesting depth ({MAX_PARSE_DEPTH})"));
312 }
313 self.depth += 1;
314 let res = f(self);
315 self.depth -= 1;
316 res
317 }
318
319 fn compile(&mut self) -> Result<String, String> {
320 if self.tokens.is_empty() {
321 return Ok("0.0".to_owned());
322 }
323 let expr = self.parse_or()?;
324 if self.pos != self.tokens.len() {
325 return Err(format!("unexpected trailing token {:?}", self.tokens[self.pos]));
326 }
327 Ok(expr)
328 }
329
330 fn parse_or(&mut self) -> Result<String, String> {
331 let mut lhs = self.parse_and()?;
332 while self.eat(&Token::Or) {
333 let rhs = self.parse_and()?;
334 lhs = format!("select(0.0, 1.0, (({lhs}) != 0.0) || (({rhs}) != 0.0))");
335 }
336 Ok(lhs)
337 }
338
339 fn parse_and(&mut self) -> Result<String, String> {
340 let mut lhs = self.parse_cmp()?;
341 while self.eat(&Token::And) {
342 let rhs = self.parse_cmp()?;
343 lhs = format!("select(0.0, 1.0, (({lhs}) != 0.0) && (({rhs}) != 0.0))");
344 }
345 Ok(lhs)
346 }
347
348 fn parse_cmp(&mut self) -> Result<String, String> {
349 let mut lhs = self.parse_add()?;
350 loop {
351 let op = match self.peek() {
352 Some(Token::Lt) => "<",
353 Some(Token::Le) => "<=",
354 Some(Token::Gt) => ">",
355 Some(Token::Ge) => ">=",
356 Some(Token::Eq) => "==",
357 Some(Token::Ne) => "!=",
358 _ => break,
359 };
360 self.pos += 1;
361 let rhs = self.parse_add()?;
362 lhs = format!("select(0.0, 1.0, ({lhs}) {op} ({rhs}))");
363 }
364 Ok(lhs)
365 }
366
367 fn parse_add(&mut self) -> Result<String, String> {
368 let mut lhs = self.parse_mul()?;
369 loop {
370 if self.eat(&Token::Plus) {
371 let rhs = self.parse_mul()?;
372 lhs = format!("(({lhs}) + ({rhs}))");
373 } else if self.eat(&Token::Minus) {
374 let rhs = self.parse_mul()?;
375 lhs = format!("(({lhs}) - ({rhs}))");
376 } else {
377 break;
378 }
379 }
380 Ok(lhs)
381 }
382
383 fn parse_mul(&mut self) -> Result<String, String> {
384 let mut lhs = self.parse_pow()?;
385 loop {
386 if self.eat(&Token::Star) {
387 let rhs = self.parse_pow()?;
388 lhs = format!("(({lhs}) * ({rhs}))");
389 } else if self.eat(&Token::Slash) {
390 let rhs = self.parse_pow()?;
391 lhs = format!("safe_div(({lhs}), ({rhs}))");
392 } else if self.eat(&Token::Percent) {
393 let rhs = self.parse_pow()?;
394 lhs = format!("fu_mod(({lhs}), ({rhs}))");
395 } else {
396 break;
397 }
398 }
399 Ok(lhs)
400 }
401
402 fn parse_pow(&mut self) -> Result<String, String> {
403 let base = self.parse_unary()?;
404 if self.eat(&Token::Caret) {
405 // Right-associative and allows unary rhs (e.g. `e^-x`, `2^-3`)
406 let exp = self.with_depth(Self::parse_pow)?;
407 Ok(format!("fu_pow(({base}), ({exp}))"))
408 } else {
409 Ok(base)
410 }
411 }
412
413 fn parse_unary(&mut self) -> Result<String, String> {
414 if self.eat(&Token::Minus) {
415 let inner = self.with_depth(Self::parse_unary)?;
416 Ok(format!("(-({inner}))"))
417 } else if self.eat(&Token::Plus) {
418 self.with_depth(Self::parse_unary)
419 } else if self.eat(&Token::Bang) {
420 let inner = self.with_depth(Self::parse_unary)?;
421 Ok(format!("select(0.0, 1.0, ({inner}) == 0.0)"))
422 } else {
423 self.parse_primary()
424 }
425 }
426
427 fn parse_primary(&mut self) -> Result<String, String> {
428 match self.peek().cloned() {
429 Some(Token::LParen) => {
430 self.pos += 1;
431 let inner = self.with_depth(Self::parse_or)?;
432 if !self.eat(&Token::RParen) {
433 return Err("expected ')'".to_owned());
434 }
435 Ok(format!("({inner})"))
436 }
437 Some(Token::Num(v)) => {
438 self.pos += 1;
439 Ok(format_wgsl_f32(v))
440 }
441 Some(Token::Ident(name)) => {
442 self.pos += 1;
443 if self.eat(&Token::LParen) {
444 let mut args = Vec::new();
445 if self.peek() != Some(&Token::RParen) {
446 loop {
447 args.push(self.with_depth(Self::parse_or)?);
448 if !self.eat(&Token::Comma) {
449 break;
450 }
451 }
452 }
453 if !self.eat(&Token::RParen) {
454 return Err(format!("expected ')' after call to '{name}'"));
455 }
456 self.emit_call(&name, &args)
457 } else {
458 self.emit_var(&name)
459 }
460 }
461 other => Err(format!("unexpected token {other:?}")),
462 }
463 }
464
465 fn emit_var(&self, name: &str) -> Result<String, String> {
466 let ch = self.channel.swizzle();
467 let wgsl = match name {
468 "r1" => "p1.r",
469 "g1" => "p1.g",
470 "b1" => "p1.b",
471 "a1" => "p1.a",
472 "r2" => "p2.r",
473 "g2" => "p2.g",
474 "b2" => "p2.b",
475 "a2" => "p2.a",
476 "r3" => "p3.r",
477 "g3" => "p3.g",
478 "b3" => "p3.b",
479 "a3" => "p3.a",
480 "c1" => return Ok(format!("p1.{ch}")),
481 "c2" => return Ok(format!("p2.{ch}")),
482 "c3" => return Ok(format!("p3.{ch}")),
483 "x" => "fu.x",
484 "y" => "fu.y",
485 "w" | "w1" => "u.img_dims1.x",
486 "h" | "h1" => "u.img_dims1.y",
487 "w2" => "u.img_dims1.z",
488 "h2" => "u.img_dims1.w",
489 "w3" => "u.img_dims2.x",
490 "h3" => "u.img_dims2.y",
491 "time" => "u.img_dims2.z",
492 "pi" => "3.14159265",
493 "e" => "2.71828183",
494 "n1" => "u.n0.x",
495 "n2" => "u.n0.y",
496 "n3" => "u.n0.z",
497 "n4" => "u.n0.w",
498 "n5" => "u.n1.x",
499 "n6" => "u.n1.y",
500 "n7" => "u.n1.z",
501 "n8" => "u.n1.w",
502 "p1x" => "u.p0.x",
503 "p1y" => "u.p0.y",
504 "p2x" => "u.p0.z",
505 "p2y" => "u.p0.w",
506 "p3x" => "u.p1.x",
507 "p3y" => "u.p1.y",
508 "p4x" => "u.p1.z",
509 "p4y" => "u.p1.w",
510 "s1" if self.max_setup >= 1 => "s1",
511 "s2" if self.max_setup >= 2 => "s2",
512 "s3" if self.max_setup >= 3 => "s3",
513 "s4" if self.max_setup >= 4 => "s4",
514 "s1" | "s2" | "s3" | "s4" => "0.0",
515 "i1" if self.max_inter >= 1 => "i1",
516 "i2" if self.max_inter >= 2 => "i2",
517 "i3" if self.max_inter >= 3 => "i3",
518 "i4" if self.max_inter >= 4 => "i4",
519 "i5" if self.max_inter >= 5 => "i5",
520 "i6" if self.max_inter >= 6 => "i6",
521 "i7" if self.max_inter >= 7 => "i7",
522 "i8" if self.max_inter >= 8 => "i8",
523 "i1" | "i2" | "i3" | "i4" | "i5" | "i6" | "i7" | "i8" => "0.0",
524 // Aux channels (Z/Position/Normal/UV/Coverage/Obj/Mat) default cleanly to 0.0
525 "z1" | "z2" | "z3"
526 | "cov1" | "cov2" | "cov3"
527 | "obj1" | "obj2" | "obj3"
528 | "mat1" | "mat2" | "mat3"
529 | "px1" | "py1" | "pz1"
530 | "px2" | "py2" | "pz2"
531 | "px3" | "py3" | "pz3"
532 | "nx1" | "ny1" | "nz1"
533 | "nx2" | "ny2" | "nz2"
534 | "nx3" | "ny3" | "nz3"
535 | "u1" | "v1" | "u2" | "v2" | "u3" | "v3"
536 | "bg1" | "bga1" | "bg2" | "bga2" | "bg3" | "bga3" => "0.0",
537 other => return Err(format!("unknown variable '{other}'")),
538 };
539 Ok(wgsl.to_owned())
540 }
541
542 fn emit_call(&self, name: &str, args: &[String]) -> Result<String, String> {
543 let req = |n: usize| -> Result<(), String> {
544 if args.len() != n {
545 Err(format!("function '{name}' expects {n} arg(s), got {}", args.len()))
546 } else {
547 Ok(())
548 }
549 };
550
551 // Image samplers: get{r|g|b|a|c}{1|2|3}[b|w|d](sx, sy)
552 if let Some(rest) = name.strip_prefix("get") {
553 if let Some(code) = self.try_emit_sampler(rest, args)? {
554 return Ok(code);
555 }
556 }
557
558 match name {
559 // Fusion CustomTool trig operates in DEGREES!
560 "sin" => { req(1)?; Ok(format!("sin(({}) * DEG2RAD)", args[0])) }
561 "cos" => { req(1)?; Ok(format!("cos(({}) * DEG2RAD)", args[0])) }
562 "tan" => { req(1)?; Ok(format!("tan(({}) * DEG2RAD)", args[0])) }
563 "asin" => { req(1)?; Ok(format!("(asin(clamp(({}), -1.0, 1.0)) * RAD2DEG)", args[0])) }
564 "acos" => { req(1)?; Ok(format!("(acos(clamp(({}), -1.0, 1.0)) * RAD2DEG)", args[0])) }
565 "atan" => { req(1)?; Ok(format!("(atan(({})) * RAD2DEG)", args[0])) }
566 "atan2" => { req(2)?; Ok(format!("(atan2(({}), ({})) * RAD2DEG)", args[0], args[1])) }
567 // Radian trig variants
568 "sinr" => { req(1)?; Ok(format!("sin(({}))", args[0])) }
569 "cosr" => { req(1)?; Ok(format!("cos(({}))", args[0])) }
570 "tanr" => { req(1)?; Ok(format!("tan(({}))", args[0])) }
571 "asinr" => { req(1)?; Ok(format!("asin(clamp(({}), -1.0, 1.0))", args[0])) }
572 "acosr" => { req(1)?; Ok(format!("acos(clamp(({}), -1.0, 1.0))", args[0])) }
573 "atanr" => { req(1)?; Ok(format!("atan(({}))", args[0])) }
574 "atan2r" => { req(2)?; Ok(format!("atan2(({}), ({}))", args[0], args[1])) }
575 // Hyperbolic
576 "sinh" => { req(1)?; Ok(format!("sinh(({}))", args[0])) }
577 "cosh" => { req(1)?; Ok(format!("cosh(({}))", args[0])) }
578 "tanh" => { req(1)?; Ok(format!("tanh(({}))", args[0])) }
579 "deg" => { req(1)?; Ok(format!("(({}) * RAD2DEG)", args[0])) }
580 "rad" => { req(1)?; Ok(format!("(({}) * DEG2RAD)", args[0])) }
581 // Core math
582 "abs" => { req(1)?; Ok(format!("abs(({}))", args[0])) }
583 "sqrt" => { req(1)?; Ok(format!("sqrt(max(({}), 0.0))", args[0])) }
584 "pow" => { req(2)?; Ok(format!("fu_pow(({}), ({}))", args[0], args[1])) }
585 "exp" => { req(1)?; Ok(format!("exp(({}))", args[0])) }
586 "log" | "ln" => { req(1)?; Ok(format!("log(max(({}), 1e-12))", args[0])) }
587 "log10" => { req(1)?; Ok(format!("(log(max(({}), 1e-12)) * 0.43429448)", args[0])) }
588 "log2" => { req(1)?; Ok(format!("log2(max(({}), 1e-12))", args[0])) }
589 "floor" | "int" => { req(1)?; Ok(format!("floor(({}))", args[0])) }
590 "ceil" => { req(1)?; Ok(format!("ceil(({}))", args[0])) }
591 "round" => { req(1)?; Ok(format!("round(({}))", args[0])) }
592 "trunc" => { req(1)?; Ok(format!("trunc(({}))", args[0])) }
593 "fract" => { req(1)?; Ok(format!("fract(({}))", args[0])) }
594 "sign" => { req(1)?; Ok(format!("sign(({}))", args[0])) }
595 "min" => {
596 if args.len() < 2 {
597 return Err("function 'min' expects at least 2 args".to_owned());
598 }
599 let mut acc = format!("min(({}), ({}))", args[0], args[1]);
600 for arg in &args[2..] {
601 acc = format!("min(({acc}), ({arg}))");
602 }
603 Ok(acc)
604 }
605 "max" => {
606 if args.len() < 2 {
607 return Err("function 'max' expects at least 2 args".to_owned());
608 }
609 let mut acc = format!("max(({}), ({}))", args[0], args[1]);
610 for arg in &args[2..] {
611 acc = format!("max(({acc}), ({arg}))");
612 }
613 Ok(acc)
614 }
615 "clamp" => { req(3)?; Ok(format!("clamp(({}), ({}), ({}))", args[0], args[1], args[2])) }
616 "mod" => { req(2)?; Ok(format!("fu_mod(({}), ({}))", args[0], args[1])) }
617 "if" | "iif" => { req(3)?; Ok(format!("select(({}), ({}), ({}) != 0.0)", args[2], args[1], args[0])) }
618 "dist" => {
619 req(4)?;
620 Ok(format!("length(vec2<f32>(({}) - ({}), ({}) - ({})))", args[2], args[0], args[3], args[1]))
621 }
622 "hypot" => { req(2)?; Ok(format!("length(vec2<f32>(({}), ({})))", args[0], args[1])) }
623 "mix" | "lerp" => { req(3)?; Ok(format!("mix(({}), ({}), ({}))", args[0], args[1], args[2])) }
624 "step" => { req(2)?; Ok(format!("step(({}), ({}))", args[0], args[1])) }
625 "smoothstep" => { req(3)?; Ok(format!("smoothstep(({}), ({}), ({}))", args[0], args[1], args[2])) }
626 // LUT samplers (Fusion canonical `getlut1..4` + `lut1..4` alias)
627 "getlut1" | "lut1" => { req(1)?; Ok(format!("sample_lut(0u, ({}))", args[0])) }
628 "getlut2" | "lut2" => { req(1)?; Ok(format!("sample_lut(1u, ({}))", args[0])) }
629 "getlut3" | "lut3" => { req(1)?; Ok(format!("sample_lut(2u, ({}))", args[0])) }
630 "getlut4" | "lut4" => { req(1)?; Ok(format!("sample_lut(3u, ({}))", args[0])) }
631 // Random & procedural noise
632 "rand" => { req(2)?; Ok(format!("mix(({}), ({}), fu_hash(vec3<f32>(f32(gid.x), f32(gid.y), u.img_dims2.z)))", args[0], args[1])) }
633 "rands" => { req(3)?; Ok(format!("mix(({}), ({}), fu_hash(vec3<f32>(f32(gid.x), f32(gid.y), ({}))))", args[0], args[1], args[2])) }
634 "noise" => { req(1)?; Ok(format!("fu_noise1(({}))", args[0])) }
635 "noise2" => { req(2)?; Ok(format!("fu_noise2(vec2<f32>(({}), ({})))", args[0], args[1])) }
636 "noise3" => { req(3)?; Ok(format!("fu_noise3(vec3<f32>(({}), ({}), ({})))", args[0], args[1], args[2])) }
637 other => Err(format!("unknown function '{other}'")),
638 }
639 }
640
641 fn try_emit_sampler(&self, rest: &str, args: &[String]) -> Result<Option<String>, String> {
642 let bytes = rest.as_bytes();
643 if bytes.len() < 2 || bytes.len() > 3 {
644 return Ok(None);
645 }
646 let ch = match bytes[0] {
647 b'r' => "r",
648 b'g' => "g",
649 b'b' => "b",
650 b'a' => "a",
651 b'c' => self.channel.swizzle(),
652 _ => return Ok(None),
653 };
654 let tex = match bytes[1] {
655 b'1' => "src_1",
656 b'2' => "src_2",
657 b'3' => "src_3",
658 _ => return Ok(None),
659 };
660 let edge_mode = match bytes.get(2) {
661 None | Some(b'b') => 0, // Black / Canvas
662 Some(b'w') => 1, // Wrap
663 Some(b'd') => 2, // Duplicate / Clamp
664 _ => return Ok(None),
665 };
666 if args.len() != 2 {
667 return Err(format!("sampler 'get{rest}' expects 2 args, got {}", args.len()));
668 }
669 Ok(Some(format!(
670 "sample_img({tex}, ({}), ({}), {edge_mode}).{ch}",
671 args[0], args[1]
672 )))
673 }
674}
675
676fn format_wgsl_f32(v: f64) -> String {
677 let f = v as f32;
678 if !f.is_finite() {
679 return "0.0".to_owned();
680 }
681 let s = format!("{f}");
682 if s.contains('.') || s.contains('e') || s.contains('E') {
683 s
684 } else {
685 format!("{s}.0")
686 }
687}
688
689fn compile_single_expr(
690 src: &str,
691 channel: Channel,
692 max_setup: usize,
693 max_inter: usize,
694) -> Result<String, String> {
695 let tokens = tokenize(src)?;
696 let mut compiler = ExprCompiler {
697 tokens: &tokens,
698 pos: 0,
699 channel,
700 max_setup,
701 max_inter,
702 depth: 0,
703 };
704 compiler.compile()
705}
706
707/// Compiles a normalized `CustomProgram` into a complete WGSL compute shader string
708/// targeting `format` (`Rgba8Unorm`, `Rgba16Float`, or `Rgba32Float`).
709pub fn compile_wgsl(program: &CustomProgram, format: wgpu::TextureFormat) -> Result<String, String> {
710 let norm = program.normalized();
711 let storage_fmt = match format {
712 wgpu::TextureFormat::Rgba16Float => "rgba16float",
713 wgpu::TextureFormat::Rgba32Float => "rgba32float",
714 _ => "rgba8unorm",
715 };
716
717 let mut setup_decls = String::new();
718 for idx in 0..4 {
719 let expr = compile_single_expr(&norm.setups[idx], Channel::Red, idx, 0)?;
720 setup_decls.push_str(&format!(" let s{}: f32 = {expr};\n", idx + 1));
721 }
722
723 let mut inter_decls = String::new();
724 for idx in 0..8 {
725 let expr = compile_single_expr(&norm.intermediates[idx], Channel::Red, 4, idx)?;
726 inter_decls.push_str(&format!(" let i{}: f32 = {expr};\n", idx + 1));
727 }
728
729 let red_expr = compile_single_expr(&norm.red, Channel::Red, 4, 8)?;
730 let green_expr = compile_single_expr(&norm.green, Channel::Green, 4, 8)?;
731 let blue_expr = compile_single_expr(&norm.blue, Channel::Blue, 4, 8)?;
732 let alpha_expr = compile_single_expr(&norm.alpha, Channel::Alpha, 4, 8)?;
733
734 Ok(format!(
735 r#"// Auto-generated Fusion CustomTool compute shader
736@group(0) @binding(0) var src_1: texture_2d<f32>;
737@group(0) @binding(1) var src_2: texture_2d<f32>;
738@group(0) @binding(2) var src_3: texture_2d<f32>;
739@group(0) @binding(3) var mask_tex: texture_2d<f32>;
740@group(0) @binding(4) var samp_lin: sampler;
741@group(0) @binding(5) var dst_tex: texture_storage_2d<{storage_fmt}, write>;
742
743struct CustomParams {{
744 n0: vec4<f32>,
745 n1: vec4<f32>,
746 p0: vec4<f32>,
747 p1: vec4<f32>,
748 img_dims1: vec4<f32>,
749 img_dims2: vec4<f32>,
750 mask_proc: vec4<f32>,
751 proc_ba: vec4<f32>,
752 luts: array<vec4<f32>, 256>,
753}};
754@group(0) @binding(6) var<uniform> u: CustomParams;
755
756const DEG2RAD: f32 = 0.017453292519943295;
757const RAD2DEG: f32 = 57.29577951308232;
758
759fn safe_div(a: f32, b: f32) -> f32 {{
760 return select(a / b, 0.0, abs(b) < 1e-12);
761}}
762
763fn fu_mod(a: f32, b: f32) -> f32 {{
764 if (abs(b) < 1e-12) {{ return 0.0; }}
765 return a - b * floor(a / b);
766}}
767
768fn fu_pow(a: f32, b: f32) -> f32 {{
769 if (a > 0.0) {{
770 return pow(a, b);
771 }}
772 if (a == 0.0) {{
773 return select(0.0, 1.0, abs(b) < 1e-12);
774 }}
775 let rb = round(b);
776 if (abs(b - rb) < 1e-5) {{
777 let mag = pow(abs(a), rb);
778 let odd = (i32(rb) & 1) != 0;
779 return select(mag, -mag, odd);
780 }}
781 return 0.0;
782}}
783
784fn fu_hash(p: vec3<f32>) -> f32 {{
785 var p3 = fract(p * vec3<f32>(0.1031, 0.1030, 0.0973));
786 p3 = p3 + dot(p3, p3.yzx + 33.33);
787 return fract((p3.x + p3.y) * p3.z);
788}}
789
790fn fu_noise1(x: f32) -> f32 {{
791 let i = floor(x);
792 let f = fract(x);
793 let u_f = f * f * (3.0 - 2.0 * f);
794 return mix(fu_hash(vec3<f32>(i, 0.0, 0.0)), fu_hash(vec3<f32>(i + 1.0, 0.0, 0.0)), u_f) * 2.0 - 1.0;
795}}
796
797fn fu_noise2(p: vec2<f32>) -> f32 {{
798 let i = floor(p);
799 let f = fract(p);
800 let u_f = f * f * (3.0 - 2.0 * f);
801 let a = fu_hash(vec3<f32>(i, 0.0));
802 let b = fu_hash(vec3<f32>(i + vec2<f32>(1.0, 0.0), 0.0));
803 let c = fu_hash(vec3<f32>(i + vec2<f32>(0.0, 1.0), 0.0));
804 let d = fu_hash(vec3<f32>(i + vec2<f32>(1.0, 1.0), 0.0));
805 return mix(mix(a, b, u_f.x), mix(c, d, u_f.x), u_f.y) * 2.0 - 1.0;
806}}
807
808fn fu_noise3(p: vec3<f32>) -> f32 {{
809 let i = floor(p);
810 let f = fract(p);
811 let u_f = f * f * (3.0 - 2.0 * f);
812 let n000 = fu_hash(i + vec3<f32>(0.0, 0.0, 0.0));
813 let n100 = fu_hash(i + vec3<f32>(1.0, 0.0, 0.0));
814 let n010 = fu_hash(i + vec3<f32>(0.0, 1.0, 0.0));
815 let n110 = fu_hash(i + vec3<f32>(1.0, 1.0, 0.0));
816 let n001 = fu_hash(i + vec3<f32>(0.0, 0.0, 1.0));
817 let n101 = fu_hash(i + vec3<f32>(1.0, 0.0, 1.0));
818 let n011 = fu_hash(i + vec3<f32>(0.0, 1.0, 1.0));
819 let n111 = fu_hash(i + vec3<f32>(1.0, 1.0, 1.0));
820 let nx00 = mix(n000, n100, u_f.x);
821 let nx10 = mix(n010, n110, u_f.x);
822 let nx01 = mix(n001, n101, u_f.x);
823 let nx11 = mix(n011, n111, u_f.x);
824 return mix(mix(nx00, nx10, u_f.y), mix(nx01, nx11, u_f.y), u_f.z) * 2.0 - 1.0;
825}}
826
827fn sample_lut(ch: u32, v: f32) -> f32 {{
828 let t = clamp(v, 0.0, 1.0) * 255.0;
829 let i0 = u32(floor(t));
830 let i1 = min(i0 + 1u, 255u);
831 let frac = t - f32(i0);
832 return mix(u.luts[i0][ch], u.luts[i1][ch], frac);
833}}
834
835fn read_img_curr(tex: texture_2d<f32>, gid: vec2<u32>, dims: vec2<u32>) -> vec4<f32> {{
836 let tdims = textureDimensions(tex);
837 if (tdims.x == dims.x && tdims.y == dims.y) {{
838 return textureLoad(tex, vec2<i32>(gid), 0);
839 }}
840 if (tdims.x <= 1u && tdims.y <= 1u) {{
841 return textureLoad(tex, vec2<i32>(0, 0), 0);
842 }}
843 let uv = (vec2<f32>(gid) + 0.5) / vec2<f32>(dims);
844 return textureSampleLevel(tex, samp_lin, uv, 0.0);
845}}
846
847fn sample_img(tex: texture_2d<f32>, fx: f32, fy: f32, mode: i32) -> vec4<f32> {{
848 let uv = vec2<f32>(fx, 1.0 - fy);
849 if (mode == 0) {{
850 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {{
851 return vec4<f32>(0.0);
852 }}
853 return textureSampleLevel(tex, samp_lin, uv, 0.0);
854 }} else if (mode == 1) {{
855 return textureSampleLevel(tex, samp_lin, fract(uv), 0.0);
856 }} else {{
857 return textureSampleLevel(tex, samp_lin, clamp(uv, vec2<f32>(0.0), vec2<f32>(1.0)), 0.0);
858 }}
859}}
860
861fn read_custom_mask(gid: vec2<u32>, dims: vec2<u32>, has_mask: f32, invert: f32) -> f32 {{
862 if (has_mask < 0.5) {{
863 return 1.0;
864 }}
865 let uv = (vec2<f32>(gid) + 0.5) / vec2<f32>(dims);
866 let m = textureSampleLevel(mask_tex, samp_lin, uv, 0.0).a;
867 return select(m, 1.0 - m, invert > 0.5);
868}}
869
870@compute @workgroup_size(8, 8)
871fn custom_tool_op(@builtin(global_invocation_id) gid: vec3<u32>) {{
872 let dims = textureDimensions(dst_tex);
873 if (gid.x >= dims.x || gid.y >= dims.y) {{ return; }}
874
875 let fdims = vec2<f32>(dims);
876 let fu = vec2<f32>((f32(gid.x) + 0.5) / fdims.x, 1.0 - (f32(gid.y) + 0.5) / fdims.y);
877 let p1 = read_img_curr(src_1, gid.xy, dims);
878 let p2 = read_img_curr(src_2, gid.xy, dims);
879 let p3 = read_img_curr(src_3, gid.xy, dims);
880
881{setup_decls}{inter_decls} let out_r: f32 = select(p1.r, ({red_expr}), u.mask_proc.z > 0.5);
882 let out_g: f32 = select(p1.g, ({green_expr}), u.mask_proc.w > 0.5);
883 let out_b: f32 = select(p1.b, ({blue_expr}), u.proc_ba.x > 0.5);
884 let out_a: f32 = select(p1.a, ({alpha_expr}), u.proc_ba.y > 0.5);
885
886 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);
887 let final_col = mix(p1, vec4<f32>(out_r, out_g, out_b, out_a), m);
888
889 if (u.proc_ba.z > 0.5) {{
890 textureStore(dst_tex, vec2<i32>(gid.xy), final_col);
891 }} else {{
892 textureStore(dst_tex, vec2<i32>(gid.xy), clamp(final_col, vec4<f32>(0.0), vec4<f32>(1.0)));
893 }}
894}}
895"#
896 ))
897}
898
899// ============================================================================
900// Pipeline Cache & GPU Dispatch
901// ============================================================================
902
903const CUSTOM_UNIFORM_SLOTS_PER_CHUNK: u32 = 256;
904const CUSTOM_BIND_GROUP_CACHE_CAPACITY: usize = 128;
905const MAX_CUSTOM_PIPELINES: usize = 128;
906
907struct FormatLayouts {
908 bgl: wgpu::BindGroupLayout,
909 pl: wgpu::PipelineLayout,
910}
911
912struct CustomPipelineEntry {
913 pipeline: Option<wgpu::ComputePipeline>,
914 last_used: u64,
915}
916
917struct CustomBindGroupKey {
918 format: wgpu::TextureFormat,
919 src_1: wgpu::TextureView,
920 src_2: wgpu::TextureView,
921 src_3: wgpu::TextureView,
922 mask: wgpu::TextureView,
923 dst_view: wgpu::TextureView,
924 chunk_idx: usize,
925}
926
927impl CustomBindGroupKey {
928 #[allow(clippy::too_many_arguments)]
929 fn matches(
930 &self,
931 format: wgpu::TextureFormat,
932 src_1: &wgpu::TextureView,
933 src_2: &wgpu::TextureView,
934 src_3: &wgpu::TextureView,
935 mask: &wgpu::TextureView,
936 dst_view: &wgpu::TextureView,
937 chunk_idx: usize,
938 ) -> bool {
939 self.format == format
940 && &self.src_1 == src_1
941 && &self.src_2 == src_2
942 && &self.src_3 == src_3
943 && &self.mask == mask
944 && &self.dst_view == dst_view
945 && self.chunk_idx == chunk_idx
946 }
947}
948
949struct CustomBindGroupEntry {
950 key: CustomBindGroupKey,
951 bg: wgpu::BindGroup,
952 last_used: u64,
953}
954
955fn hash_custom_bind_group_key(
956 format: wgpu::TextureFormat,
957 src_1: &wgpu::TextureView,
958 src_2: &wgpu::TextureView,
959 src_3: &wgpu::TextureView,
960 mask: &wgpu::TextureView,
961 dst_view: &wgpu::TextureView,
962 chunk_idx: usize,
963) -> u64 {
964 let mut h = DefaultHasher::new();
965 format.hash(&mut h);
966 src_1.hash(&mut h);
967 src_2.hash(&mut h);
968 src_3.hash(&mut h);
969 mask.hash(&mut h);
970 dst_view.hash(&mut h);
971 chunk_idx.hash(&mut h);
972 h.finish()
973}
974
975/// Caches dynamically compiled `CustomTool` compute pipelines keyed by
976/// `(dst_texture_format, normalized_program)` with an LRU cap, plus a lazily growing
977/// chunked dynamic-offset uniform ring buffer and LRU-cached `BindGroup`s so repeated
978/// dispatches avoid per-frame GPU buffer/bind-group allocations.
979#[derive(Default)]
980pub struct CustomShaderCache {
981 layouts: HashMap<wgpu::TextureFormat, FormatLayouts>,
982 sampler: Option<wgpu::Sampler>,
983 pipelines: HashMap<(wgpu::TextureFormat, CustomProgram), CustomPipelineEntry>,
984 pipeline_tick: u64,
985 uniform_chunks: Vec<wgpu::Buffer>,
986 uniform_stride: u32,
987 uniform_cursor: u32,
988 bg_cache: HashMap<u64, Vec<CustomBindGroupEntry>>,
989 bg_count: usize,
990 bg_tick: u64,
991 bg_hits: u64,
992 bg_misses: u64,
993}
994
995impl CustomShaderCache {
996 pub fn new() -> Self {
997 Self::default()
998 }
999
1000 pub fn cached_pipeline_count(&self) -> usize {
1001 self.pipelines.len()
1002 }
1003
1004 pub fn cached_bind_group_count(&self) -> usize {
1005 self.bg_count
1006 }
1007
1008 pub fn bind_group_hits(&self) -> u64 {
1009 self.bg_hits
1010 }
1011
1012 pub fn bind_group_misses(&self) -> u64 {
1013 self.bg_misses
1014 }
1015
1016 pub fn clear_bind_group_cache(&mut self) {
1017 self.bg_cache.clear();
1018 self.bg_count = 0;
1019 }
1020
1021 pub fn reset_uniform_cursor(&mut self) {
1022 self.uniform_cursor = 0;
1023 }
1024
1025 /// Trims the dynamic uniform ring to at most `keep` chunks and resets the cursor.
1026 /// Clears `bg_cache` whenever chunks are dropped so cached bind groups never reference freed buffers.
1027 pub fn trim_uniform_chunks(&mut self, keep: usize) {
1028 self.uniform_cursor = 0;
1029 if self.uniform_chunks.len() > keep {
1030 self.uniform_chunks.truncate(keep);
1031 self.clear_bind_group_cache();
1032 }
1033 }
1034
1035 fn ensure_format_layouts(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) {
1036 self.layouts.entry(format).or_insert_with(|| {
1037 let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
1038 binding,
1039 visibility: wgpu::ShaderStages::COMPUTE,
1040 ty: wgpu::BindingType::Texture {
1041 sample_type: wgpu::TextureSampleType::Float { filterable: true },
1042 view_dimension: wgpu::TextureViewDimension::D2,
1043 multisampled: false,
1044 },
1045 count: None,
1046 };
1047 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
1048 label: Some("custom-tool-bgl"),
1049 entries: &[
1050 tex_entry(0),
1051 tex_entry(1),
1052 tex_entry(2),
1053 tex_entry(3),
1054 wgpu::BindGroupLayoutEntry {
1055 binding: 4,
1056 visibility: wgpu::ShaderStages::COMPUTE,
1057 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
1058 count: None,
1059 },
1060 wgpu::BindGroupLayoutEntry {
1061 binding: 5,
1062 visibility: wgpu::ShaderStages::COMPUTE,
1063 ty: wgpu::BindingType::StorageTexture {
1064 access: wgpu::StorageTextureAccess::WriteOnly,
1065 format,
1066 view_dimension: wgpu::TextureViewDimension::D2,
1067 },
1068 count: None,
1069 },
1070 wgpu::BindGroupLayoutEntry {
1071 binding: 6,
1072 visibility: wgpu::ShaderStages::COMPUTE,
1073 ty: wgpu::BindingType::Buffer {
1074 ty: wgpu::BufferBindingType::Uniform,
1075 has_dynamic_offset: true,
1076 min_binding_size: NonZeroU64::new(std::mem::size_of::<CustomParams>() as u64),
1077 },
1078 count: None,
1079 },
1080 ],
1081 });
1082 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1083 label: Some("custom-tool-pl"),
1084 bind_group_layouts: &[Some(&bgl)],
1085 immediate_size: 0,
1086 });
1087 FormatLayouts { bgl, pl }
1088 });
1089 if self.sampler.is_none() {
1090 self.sampler = Some(device.create_sampler(&wgpu::SamplerDescriptor {
1091 label: Some("custom-tool-linear"),
1092 address_mode_u: wgpu::AddressMode::ClampToEdge,
1093 address_mode_v: wgpu::AddressMode::ClampToEdge,
1094 mag_filter: wgpu::FilterMode::Linear,
1095 min_filter: wgpu::FilterMode::Linear,
1096 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
1097 ..Default::default()
1098 }));
1099 }
1100 }
1101
1102 fn ensure_uniform_stride(&mut self, device: &wgpu::Device) {
1103 if self.uniform_stride != 0 {
1104 return;
1105 }
1106 let uniform_size = std::mem::size_of::<CustomParams>() as u32;
1107 let min_align = device.limits().min_uniform_buffer_offset_alignment.max(1);
1108 self.uniform_stride = uniform_size.div_ceil(min_align) * min_align;
1109 }
1110
1111 fn alloc_uniform_slot(
1112 &mut self,
1113 device: &wgpu::Device,
1114 queue: &wgpu::Queue,
1115 params: &CustomParams,
1116 ) -> (usize, u32) {
1117 self.ensure_uniform_stride(device);
1118 let slot_global = self.uniform_cursor;
1119 let chunk_idx = (slot_global / CUSTOM_UNIFORM_SLOTS_PER_CHUNK) as usize;
1120 let slot_in_chunk = slot_global % CUSTOM_UNIFORM_SLOTS_PER_CHUNK;
1121 while chunk_idx >= self.uniform_chunks.len() {
1122 let size = u64::from(CUSTOM_UNIFORM_SLOTS_PER_CHUNK) * u64::from(self.uniform_stride);
1123 let buf = device.create_buffer(&wgpu::BufferDescriptor {
1124 label: Some("custom-tool-params-ring"),
1125 size,
1126 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1127 mapped_at_creation: false,
1128 });
1129 self.uniform_chunks.push(buf);
1130 }
1131 let offset = slot_in_chunk * self.uniform_stride;
1132 queue.write_buffer(
1133 &self.uniform_chunks[chunk_idx],
1134 u64::from(offset),
1135 bytemuck::bytes_of(params),
1136 );
1137 self.uniform_cursor = slot_global + 1;
1138 (chunk_idx, offset)
1139 }
1140
1141 #[allow(clippy::too_many_arguments)]
1142 fn ensure_bind_group(
1143 &mut self,
1144 device: &wgpu::Device,
1145 format: wgpu::TextureFormat,
1146 src_1: &wgpu::TextureView,
1147 src_2: &wgpu::TextureView,
1148 src_3: &wgpu::TextureView,
1149 mask: &wgpu::TextureView,
1150 dst_view: &wgpu::TextureView,
1151 chunk_idx: usize,
1152 ) -> (u64, usize) {
1153 let hash = hash_custom_bind_group_key(format, src_1, src_2, src_3, mask, dst_view, chunk_idx);
1154 self.bg_tick = self.bg_tick.wrapping_add(1);
1155 let tick = self.bg_tick;
1156
1157 if let Some(bucket) = self.bg_cache.get_mut(&hash)
1158 && let Some((idx, entry)) = bucket
1159 .iter_mut()
1160 .enumerate()
1161 .find(|(_, e)| e.key.matches(format, src_1, src_2, src_3, mask, dst_view, chunk_idx))
1162 {
1163 entry.last_used = tick;
1164 self.bg_hits += 1;
1165 return (hash, idx);
1166 }
1167
1168 self.bg_misses += 1;
1169 if self.bg_count >= CUSTOM_BIND_GROUP_CACHE_CAPACITY {
1170 let mut oldest_hash = None;
1171 let mut oldest_idx = 0usize;
1172 let mut oldest_tick = u64::MAX;
1173 for (&h, bucket) in &self.bg_cache {
1174 for (idx, entry) in bucket.iter().enumerate() {
1175 if entry.last_used < oldest_tick {
1176 oldest_tick = entry.last_used;
1177 oldest_hash = Some(h);
1178 oldest_idx = idx;
1179 }
1180 }
1181 }
1182 if let Some(h) = oldest_hash {
1183 let empty = if let Some(bucket) = self.bg_cache.get_mut(&h) {
1184 bucket.swap_remove(oldest_idx);
1185 self.bg_count -= 1;
1186 bucket.is_empty()
1187 } else {
1188 false
1189 };
1190 if empty {
1191 self.bg_cache.remove(&h);
1192 }
1193 }
1194 }
1195
1196 let layout = &self.layouts[&format].bgl;
1197 let sampler = self.sampler.as_ref().expect("sampler initialized");
1198 let ubuf = &self.uniform_chunks[chunk_idx];
1199 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
1200 label: Some("custom-tool-bg"),
1201 layout,
1202 entries: &[
1203 wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src_1) },
1204 wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(src_2) },
1205 wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(src_3) },
1206 wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(mask) },
1207 wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::Sampler(sampler) },
1208 wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(dst_view) },
1209 wgpu::BindGroupEntry {
1210 binding: 6,
1211 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1212 buffer: ubuf,
1213 offset: 0,
1214 size: NonZeroU64::new(std::mem::size_of::<CustomParams>() as u64),
1215 }),
1216 },
1217 ],
1218 });
1219
1220 let bucket = self.bg_cache.entry(hash).or_default();
1221 let idx = bucket.len();
1222 bucket.push(CustomBindGroupEntry {
1223 key: CustomBindGroupKey {
1224 format,
1225 src_1: src_1.clone(),
1226 src_2: src_2.clone(),
1227 src_3: src_3.clone(),
1228 mask: mask.clone(),
1229 dst_view: dst_view.clone(),
1230 chunk_idx,
1231 },
1232 bg,
1233 last_used: tick,
1234 });
1235 self.bg_count += 1;
1236 (hash, idx)
1237 }
1238
1239 fn compile_wgsl_pipeline(
1240 &mut self,
1241 device: &wgpu::Device,
1242 format: wgpu::TextureFormat,
1243 wgsl: &str,
1244 ) -> Option<wgpu::ComputePipeline> {
1245 self.ensure_format_layouts(device, format);
1246 let pl = &self.layouts[&format].pl;
1247 #[cfg(not(target_arch = "wasm32"))]
1248 let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
1249 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1250 label: Some("custom-tool-shader"),
1251 source: wgpu::ShaderSource::Wgsl(wgsl.into()),
1252 });
1253 let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
1254 label: Some("custom_tool_op"),
1255 layout: Some(pl),
1256 module: &module,
1257 entry_point: Some("custom_tool_op"),
1258 compilation_options: Default::default(),
1259 cache: None,
1260 });
1261 #[cfg(not(target_arch = "wasm32"))]
1262 if pollster::block_on(scope.pop()).is_some() {
1263 return None;
1264 }
1265 Some(pipeline)
1266 }
1267
1268 fn ensure_compiled_key(
1269 &mut self,
1270 device: &wgpu::Device,
1271 key: &(wgpu::TextureFormat, CustomProgram),
1272 ) -> bool {
1273 self.pipeline_tick = self.pipeline_tick.wrapping_add(1);
1274 let tick = self.pipeline_tick;
1275 if let Some(entry) = self.pipelines.get_mut(key) {
1276 entry.last_used = tick;
1277 return entry.pipeline.is_some();
1278 }
1279 let pipeline = match compile_wgsl(&key.1, key.0) {
1280 Ok(wgsl) => self.compile_wgsl_pipeline(device, key.0, &wgsl),
1281 Err(_) => None,
1282 };
1283 let ok = pipeline.is_some();
1284 if self.pipelines.len() >= MAX_CUSTOM_PIPELINES
1285 && let Some(oldest_key) = self
1286 .pipelines
1287 .iter()
1288 .min_by_key(|(_, entry)| entry.last_used)
1289 .map(|(k, _)| k.clone())
1290 {
1291 self.pipelines.remove(&oldest_key);
1292 }
1293 self.pipelines.insert(
1294 key.clone(),
1295 CustomPipelineEntry {
1296 pipeline,
1297 last_used: tick,
1298 },
1299 );
1300 ok
1301 }
1302
1303 /// Compiles and caches the compute pipeline for `program` at `format`, returning `false`
1304 /// if the program contains unsupported syntax (graceful fallback to passthrough).
1305 pub fn ensure_compiled(
1306 &mut self,
1307 device: &wgpu::Device,
1308 program: &CustomProgram,
1309 format: wgpu::TextureFormat,
1310 ) -> bool {
1311 let key = (format, program.normalized());
1312 self.ensure_compiled_key(device, &key)
1313 }
1314
1315 /// Dispatches a compiled `CustomProgram` into `dst_view`. Returns `false` if compilation failed.
1316 #[allow(clippy::too_many_arguments)]
1317 pub fn dispatch(
1318 &mut self,
1319 device: &wgpu::Device,
1320 queue: &wgpu::Queue,
1321 enc: &mut wgpu::CommandEncoder,
1322 program: &CustomProgram,
1323 format: wgpu::TextureFormat,
1324 src_1: &wgpu::TextureView,
1325 src_2: &wgpu::TextureView,
1326 src_3: &wgpu::TextureView,
1327 mask: &wgpu::TextureView,
1328 dst_view: &wgpu::TextureView,
1329 dst_size: [u32; 2],
1330 params: &CustomParams,
1331 ) -> bool {
1332 let key = (format, program.normalized());
1333 if !self.ensure_compiled_key(device, &key) {
1334 return false;
1335 }
1336
1337 let (chunk_idx, offset) = self.alloc_uniform_slot(device, queue, params);
1338 let (bg_hash, bg_idx) = self.ensure_bind_group(
1339 device,
1340 format,
1341 src_1,
1342 src_2,
1343 src_3,
1344 mask,
1345 dst_view,
1346 chunk_idx,
1347 );
1348 let Some(Some(pipeline)) = self.pipelines.get(&key).map(|e| &e.pipeline) else {
1349 return false;
1350 };
1351 let bg = &self.bg_cache[&bg_hash][bg_idx].bg;
1352
1353 let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
1354 label: Some("custom-tool-pass"),
1355 timestamp_writes: None,
1356 });
1357 pass.set_pipeline(pipeline);
1358 pass.set_bind_group(0, bg, &[offset]);
1359 pass.dispatch_workgroups(dst_size[0].div_ceil(8), dst_size[1].div_ceil(8), 1);
1360 true
1361 }
1362}
1363
1364#[cfg(test)]
1365mod tests {
1366 use super::*;
1367 use crate::{Engine, create_texture};
1368 use model::Comp;
1369
1370 #[test]
1371 fn parses_operator_precedence_and_edge_cases() {
1372 let mut p = CustomProgram::default();
1373 p.setups[0] = "1/n1".to_owned();
1374 p.setups[1] = "s1 - n2*s1".to_owned();
1375 p.intermediates[0] = "if(n7=0, (r1/n1), (r1*n1))".to_owned();
1376 p.red = "if(c1>n1, n1+i1*(1-e^-((c1-n1)/i1)), c1)".to_owned();
1377 p.green = "x%s2<n2||y%s2<n2".to_owned();
1378 p.blue = "0\n // trailing comment".to_owned();
1379 p.alpha = "max(r1, g1, b1) * (1 - dist((x-.5)*2, (y-.5)*2, 0, 0))".to_owned();
1380
1381 let wgsl = compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).expect("compile");
1382 assert!(wgsl.contains("safe_div"));
1383 assert!(wgsl.contains("fu_pow((2.71828183),"));
1384 assert!(wgsl.contains("fu_mod"));
1385 assert!(wgsl.contains("select("));
1386 assert!(wgsl.contains("min(") || wgsl.contains("max("));
1387 assert!(wgsl.contains("p1.r"));
1388 }
1389
1390 #[test]
1391 fn compiles_samplers_and_luts() {
1392 let mut p = CustomProgram::default();
1393 p.red = "getlut1(getr1b(x + 0.1, y))".to_owned();
1394 p.green = "lut2(getg2w(x, y - 0.25))".to_owned();
1395 p.blue = "getlut3(getb3d(x, y))".to_owned();
1396 p.alpha = "lut4(geta1(x, y))".to_owned();
1397
1398 let wgsl = compile_wgsl(&p, wgpu::TextureFormat::Rgba16Float).expect("compile");
1399 assert!(wgsl.contains("texture_storage_2d<rgba16float, write>"));
1400 assert!(wgsl.contains("sample_img(src_1,"));
1401 assert!(wgsl.contains("sample_img(src_2,"));
1402 assert!(wgsl.contains("sample_img(src_3,"));
1403 assert!(wgsl.contains("sample_lut(0u,"));
1404 assert!(wgsl.contains("sample_lut(3u,"));
1405 }
1406
1407 #[test]
1408 fn rejects_invalid_syntax_gracefully() {
1409 let mut p = CustomProgram::default();
1410 p.red = "unknown_func(r1)".to_owned();
1411 assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_err());
1412
1413 p.red = "r1 + + *".to_owned();
1414 assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_err());
1415
1416 p.red = "totally_unknown_var".to_owned();
1417 assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_err());
1418 }
1419
1420 #[test]
1421 fn gpu_executes_wave_formula_and_caches_pipeline() {
1422 let eng = Engine::new_headless().expect("gpu");
1423 let mut cache = CustomShaderCache::new();
1424 let mut prog = CustomProgram::default();
1425 prog.red = "sin(x*w*n1 + n2*n1*w)*0.5+0.5".to_owned();
1426 prog.green = "sin(y*w*n1 + n2*n1*w)*0.5+0.5".to_owned();
1427 prog.blue = "0\n".to_owned();
1428 prog.alpha = "1".to_owned();
1429
1430 let mut params = CustomParams::default();
1431 params.n0 = [0.7413, 10.655, 0.0, 0.0];
1432 params.img_dims1 = [64.0, 64.0, 64.0, 64.0];
1433
1434 let dummy = create_texture(eng.device(), [1, 1], 0);
1435 let dst = create_texture(eng.device(), [64, 64], 1);
1436 let mut enc = eng.device().create_command_encoder(&Default::default());
1437 let ok = cache.dispatch(
1438 eng.device(),
1439 eng.queue(),
1440 &mut enc,
1441 &prog,
1442 wgpu::TextureFormat::Rgba8Unorm,
1443 &dummy.view,
1444 &dummy.view,
1445 &dummy.view,
1446 &dummy.view,
1447 &dst.view,
1448 [64, 64],
1449 &params,
1450 );
1451 assert!(ok);
1452 eng.queue().submit(Some(enc.finish()));
1453 assert_eq!(cache.cached_pipeline_count(), 1);
1454
1455 // Whitespace-equivalent program hits the exact same cached pipeline!
1456 let mut prog2 = prog.clone();
1457 prog2.blue = " 0 ".to_owned();
1458 assert!(cache.ensure_compiled(eng.device(), &prog2, wgpu::TextureFormat::Rgba8Unorm));
1459 assert_eq!(cache.cached_pipeline_count(), 1);
1460
1461 let rgba = eng.readback_rgba(&dst).expect("readback");
1462 // Verify pixel (10, 20) against CPU formula
1463 let px = 10usize;
1464 let py = 20usize;
1465 let fu_x = (px as f64 + 0.5) / 64.0;
1466 let fu_y = 1.0 - (py as f64 + 0.5) / 64.0;
1467 let n1 = 0.7413_f64;
1468 let n2 = 10.655_f64;
1469 let w = 64.0_f64;
1470 let exp_r = ((fu_x * w * n1 + n2 * n1 * w).to_radians().sin() * 0.5 + 0.5) * 255.0;
1471 let exp_g = ((fu_y * w * n1 + n2 * n1 * w).to_radians().sin() * 0.5 + 0.5) * 255.0;
1472 let idx = (py * 64 + px) * 4;
1473 assert!((rgba[idx] as f64 - exp_r).abs() <= 1.5, "r got {} expected {exp_r}", rgba[idx]);
1474 assert!((rgba[idx + 1] as f64 - exp_g).abs() <= 1.5, "g got {} expected {exp_g}", rgba[idx + 1]);
1475 assert_eq!(rgba[idx + 2], 0);
1476 assert_eq!(rgba[idx + 3], 255);
1477 }
1478
1479 #[test]
1480 fn gpu_executes_premul_invert_safe_div_when_alpha_zero() {
1481 let eng = Engine::new_headless().expect("gpu");
1482 let mut cache = CustomShaderCache::new();
1483 let mut prog = CustomProgram::default();
1484 prog.intermediates[0] = "a1".to_owned();
1485 prog.red = "(1-r1/a1)*i1".to_owned();
1486 prog.green = "(1-g1/a1)*i1".to_owned();
1487 prog.blue = "(1-b1/a1)*i1".to_owned();
1488 prog.alpha = "i1".to_owned();
1489
1490 // 2x1 input: pixel 0 is transparent black (a1 == 0), pixel 1 is premul (0.2, 0.4, 0.0, 0.5)
1491 let src = create_texture(eng.device(), [2, 1], 0);
1492 let input_bytes: [u8; 8] = [0, 0, 0, 0, 51, 102, 0, 128];
1493 eng.queue().write_texture(
1494 src.texture.as_image_copy(),
1495 &input_bytes,
1496 wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(8), rows_per_image: Some(1) },
1497 wgpu::Extent3d { width: 2, height: 1, depth_or_array_layers: 1 },
1498 );
1499 let dummy = create_texture(eng.device(), [1, 1], 0);
1500 let dst = create_texture(eng.device(), [2, 1], 2);
1501 let params = CustomParams {
1502 img_dims1: [2.0, 1.0, 1.0, 1.0],
1503 ..Default::default()
1504 };
1505
1506 let mut enc = eng.device().create_command_encoder(&Default::default());
1507 assert!(cache.dispatch(
1508 eng.device(),
1509 eng.queue(),
1510 &mut enc,
1511 &prog,
1512 wgpu::TextureFormat::Rgba8Unorm,
1513 &src.view,
1514 &dummy.view,
1515 &dummy.view,
1516 &dummy.view,
1517 &dst.view,
1518 [2, 1],
1519 &params,
1520 ));
1521 eng.queue().submit(Some(enc.finish()));
1522
1523 let rgba = eng.readback_rgba(&dst).expect("readback");
1524 // Pixel 0 (a1 == 0): must be clean (0, 0, 0, 0), no NaN!
1525 assert_eq!(&rgba[0..4], &[0, 0, 0, 0]);
1526 // Pixel 1: straight RGB = (51/128, 102/128, 0) = (0.398, 0.797, 0)
1527 // Inverted * a1 = ((1-0.398)*0.502, (1-0.797)*0.502, 1*0.502) * 255 = (77, 26, 128)
1528 assert!((rgba[4] as i32 - 77).abs() <= 2, "r={}", rgba[4]);
1529 assert!((rgba[5] as i32 - 26).abs() <= 2, "g={}", rgba[5]);
1530 assert!((rgba[6] as i32 - 128).abs() <= 2, "b={}", rgba[6]);
1531 assert_eq!(rgba[7], 128);
1532 }
1533
1534 #[test]
1535 fn end_to_end_comp_custom_tool_with_lut_and_expression_modifier() {
1536 let src = r#"Composition {
1537 Prefs = { Comp = { FrameFormat = { Width = 16, Height = 16, Rate = 24 } } },
1538 Tools = ordered() {
1539 BG1 = Background {
1540 Inputs = {
1541 Width = Input { Value = 16, },
1542 Height = Input { Value = 16, },
1543 TopLeftRed = Input { Value = 0.25, },
1544 TopLeftGreen = Input { Value = 0.5, },
1545 TopLeftBlue = Input { Value = 0.75, },
1546 TopLeftAlpha = Input { Value = 1.0, },
1547 },
1548 },
1549 NumExpr = Expression {
1550 Inputs = {
1551 n1 = Input { Value = 2.0, },
1552 NumberExpression = Input { Value = "n1 * 0.25", },
1553 },
1554 },
1555 CT1LUT1 = LUTBezier {
1556 KeyColorSplines = {
1557 [0] = {
1558 [0] = { 1.0, Flags = { Linear = true } },
1559 [1] = { 0.0, Flags = { Linear = true } },
1560 },
1561 },
1562 },
1563 CT1 = Custom {
1564 Inputs = {
1565 Image1 = Input { SourceOp = "BG1", Source = "Output", },
1566 NumberIn1 = Input { SourceOp = "NumExpr", Source = "NumberResult", },
1567 LUTIn1 = Input { SourceOp = "CT1LUT1", Source = "Value", },
1568 RedExpression = Input { Value = "lut1(r1)", },
1569 GreenExpression = Input { Value = "g1 * n1", },
1570 BlueExpression = Input { Value = "if(b1 > 0.5, 1, 0)", },
1571 AlphaExpression = Input { Value = "a1", },
1572 },
1573 },
1574 },
1575 }"#;
1576 let comp = Comp::from_fusion_str(src).expect("parse");
1577 let mut eng = Engine::new_headless().expect("gpu");
1578 let ct_id = comp.find_node("CT1").unwrap();
1579 let (tex, _) = eng.evaluate(&comp, ct_id, 0.0);
1580 let rgba = eng.readback_rgba(&tex).expect("readback");
1581 // r = lut1(0.25) = 0.75 (~191), g = 0.5 * 0.5 = 0.25 (~64), b = 1.0 (255), a = 1.0 (255)
1582 assert!((rgba[0] as i32 - 191).abs() <= 2, "r={}", rgba[0]);
1583 assert!((rgba[1] as i32 - 64).abs() <= 2, "g={}", rgba[1]);
1584 assert_eq!(rgba[2], 255);
1585 assert_eq!(rgba[3], 255);
1586 }
1587
1588 #[test]
1589 fn rejects_deeply_nested_expressions_without_stack_overflow() {
1590 let mut p = CustomProgram::default();
1591 let depth = MAX_PARSE_DEPTH + 16;
1592 p.red = format!("{}r1{}", "(".repeat(depth), ")".repeat(depth));
1593 let err = compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).expect_err("must reject deep parens");
1594 assert!(err.contains("nesting depth"), "unexpected err: {err}");
1595
1596 p.red = format!("{}r1", "-".repeat(depth));
1597 let err_unary = compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).expect_err("must reject deep unary");
1598 assert!(err_unary.contains("nesting depth"), "unexpected err: {err_unary}");
1599
1600 p.red = format!("{}1", "2^".repeat(depth));
1601 let err_pow = compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).expect_err("must reject deep pow");
1602 assert!(err_pow.contains("nesting depth"), "unexpected err: {err_pow}");
1603
1604 // Within limit should still compile cleanly.
1605 let ok_depth = 16;
1606 p.red = format!("{}r1{}", "(".repeat(ok_depth), ")".repeat(ok_depth));
1607 assert!(compile_wgsl(&p, wgpu::TextureFormat::Rgba8Unorm).is_ok());
1608 }
1609
1610 #[test]
1611 fn validation_error_scope_catches_invalid_wgsl_without_panicking() {
1612 let eng = Engine::new_headless().expect("gpu");
1613 let mut cache = CustomShaderCache::new();
1614 let res = cache.compile_wgsl_pipeline(
1615 eng.device(),
1616 wgpu::TextureFormat::Rgba8Unorm,
1617 "this is not valid wgsl @@@",
1618 );
1619 assert!(res.is_none(), "invalid WGSL must return None cleanly");
1620
1621 // Caching failure in pipelines map returns false on subsequent queries too.
1622 let mut bad_prog = CustomProgram::default();
1623 bad_prog.red = "unknown_ident_xyz".to_owned();
1624 assert!(!cache.ensure_compiled(eng.device(), &bad_prog, wgpu::TextureFormat::Rgba8Unorm));
1625 assert!(!cache.ensure_compiled(eng.device(), &bad_prog, wgpu::TextureFormat::Rgba8Unorm));
1626 }
1627
1628 #[test]
1629 fn custom_shader_cache_reuses_uniform_buffer_and_bind_groups() {
1630 let eng = Engine::new_headless().expect("gpu");
1631 let mut cache = CustomShaderCache::new();
1632 let prog = CustomProgram {
1633 red: "n1".to_owned(),
1634 green: "0".to_owned(),
1635 blue: "0".to_owned(),
1636 alpha: "1".to_owned(),
1637 ..Default::default()
1638 };
1639 let dummy = create_texture(eng.device(), [1, 1], 0);
1640 let dst = create_texture(eng.device(), [8, 8], 1);
1641
1642 for i in 0..10u32 {
1643 let v = (i as f32 + 1.0) / 10.0;
1644 let params = CustomParams {
1645 n0: [v, 0.0, 0.0, 0.0],
1646 img_dims1: [8.0, 8.0, 8.0, 8.0],
1647 ..Default::default()
1648 };
1649 let mut enc = eng.device().create_command_encoder(&Default::default());
1650 assert!(cache.dispatch(
1651 eng.device(),
1652 eng.queue(),
1653 &mut enc,
1654 &prog,
1655 wgpu::TextureFormat::Rgba8Unorm,
1656 &dummy.view,
1657 &dummy.view,
1658 &dummy.view,
1659 &dummy.view,
1660 &dst.view,
1661 [8, 8],
1662 &params,
1663 ));
1664 eng.queue().submit(Some(enc.finish()));
1665 let rgba = eng.readback_rgba(&dst).expect("readback");
1666 let expected = (v * 255.0).round() as i32;
1667 assert!((rgba[0] as i32 - expected).abs() <= 1, "iter {i}: got {} expected {expected}", rgba[0]);
1668 }
1669
1670 assert_eq!(cache.cached_pipeline_count(), 1);
1671 assert_eq!(cache.cached_bind_group_count(), 1);
1672 assert_eq!(cache.bind_group_misses(), 1);
1673 assert_eq!(cache.bind_group_hits(), 9);
1674 }
1675
1676 #[test]
1677 fn custom_shader_cache_isolates_multiple_dispatches_in_single_encoder() {
1678 let eng = Engine::new_headless().expect("gpu");
1679 let mut cache = CustomShaderCache::new();
1680 let prog = CustomProgram {
1681 red: "n1".to_owned(),
1682 green: "n2".to_owned(),
1683 blue: "0".to_owned(),
1684 alpha: "1".to_owned(),
1685 ..Default::default()
1686 };
1687 let dummy = create_texture(eng.device(), [1, 1], 0);
1688 let dst_a = create_texture(eng.device(), [8, 8], 1);
1689 let dst_b = create_texture(eng.device(), [8, 8], 2);
1690
1691 let params_a = CustomParams {
1692 n0: [0.2, 0.4, 0.0, 0.0],
1693 img_dims1: [8.0, 8.0, 8.0, 8.0],
1694 ..Default::default()
1695 };
1696 let params_b = CustomParams {
1697 n0: [0.8, 0.6, 0.0, 0.0],
1698 img_dims1: [8.0, 8.0, 8.0, 8.0],
1699 ..Default::default()
1700 };
1701
1702 let mut enc = eng.device().create_command_encoder(&Default::default());
1703 assert!(cache.dispatch(
1704 eng.device(),
1705 eng.queue(),
1706 &mut enc,
1707 &prog,
1708 wgpu::TextureFormat::Rgba8Unorm,
1709 &dummy.view,
1710 &dummy.view,
1711 &dummy.view,
1712 &dummy.view,
1713 &dst_a.view,
1714 [8, 8],
1715 &params_a,
1716 ));
1717 assert!(cache.dispatch(
1718 eng.device(),
1719 eng.queue(),
1720 &mut enc,
1721 &prog,
1722 wgpu::TextureFormat::Rgba8Unorm,
1723 &dummy.view,
1724 &dummy.view,
1725 &dummy.view,
1726 &dummy.view,
1727 &dst_b.view,
1728 [8, 8],
1729 &params_b,
1730 ));
1731 eng.queue().submit(Some(enc.finish()));
1732
1733 let rgba_a = eng.readback_rgba(&dst_a).expect("readback a");
1734 let rgba_b = eng.readback_rgba(&dst_b).expect("readback b");
1735 assert!((rgba_a[0] as i32 - 51).abs() <= 1, "a.r={}", rgba_a[0]);
1736 assert!((rgba_a[1] as i32 - 102).abs() <= 1, "a.g={}", rgba_a[1]);
1737 assert!((rgba_b[0] as i32 - 204).abs() <= 1, "b.r={}", rgba_b[0]);
1738 assert!((rgba_b[1] as i32 - 153).abs() <= 1, "b.g={}", rgba_b[1]);
1739 }
1740
1741 #[test]
1742 fn custom_shader_cache_evicts_lru_bind_groups_at_capacity() {
1743 let eng = Engine::new_headless().expect("gpu");
1744 let mut cache = CustomShaderCache::new();
1745 let prog = CustomProgram::default();
1746 let dummy = create_texture(eng.device(), [1, 1], 0);
1747 let params = CustomParams {
1748 img_dims1: [4.0, 4.0, 4.0, 4.0],
1749 ..Default::default()
1750 };
1751
1752 let mut enc = eng.device().create_command_encoder(&Default::default());
1753 for i in 0..(CUSTOM_BIND_GROUP_CACHE_CAPACITY + 8) {
1754 let dst = create_texture(eng.device(), [4, 4], i as u64 + 1);
1755 assert!(cache.dispatch(
1756 eng.device(),
1757 eng.queue(),
1758 &mut enc,
1759 &prog,
1760 wgpu::TextureFormat::Rgba8Unorm,
1761 &dummy.view,
1762 &dummy.view,
1763 &dummy.view,
1764 &dummy.view,
1765 &dst.view,
1766 [4, 4],
1767 &params,
1768 ));
1769 }
1770 eng.queue().submit(Some(enc.finish()));
1771 assert_eq!(cache.cached_bind_group_count(), CUSTOM_BIND_GROUP_CACHE_CAPACITY);
1772 }
1773
1774 #[test]
1775 fn custom_shader_cache_grows_uniform_chunks_past_256_without_wrapping() {
1776 let eng = Engine::new_headless().expect("gpu");
1777 let mut cache = CustomShaderCache::new();
1778 let prog = CustomProgram {
1779 red: "n1".to_owned(),
1780 green: "n2".to_owned(),
1781 blue: "0".to_owned(),
1782 alpha: "1".to_owned(),
1783 ..Default::default()
1784 };
1785 let dummy = create_texture(eng.device(), [1, 1], 0);
1786 let dst_first = create_texture(eng.device(), [4, 4], 1);
1787 let dst_mid = create_texture(eng.device(), [4, 4], 2);
1788 let dst_last = create_texture(eng.device(), [4, 4], 3);
1789
1790 let mut enc = eng.device().create_command_encoder(&Default::default());
1791 let first_params = CustomParams {
1792 n0: [0.2, 0.8, 0.0, 0.0],
1793 img_dims1: [4.0, 4.0, 4.0, 4.0],
1794 ..Default::default()
1795 };
1796 assert!(cache.dispatch(
1797 eng.device(),
1798 eng.queue(),
1799 &mut enc,
1800 &prog,
1801 wgpu::TextureFormat::Rgba8Unorm,
1802 &dummy.view,
1803 &dummy.view,
1804 &dummy.view,
1805 &dummy.view,
1806 &dst_first.view,
1807 [4, 4],
1808 &first_params,
1809 ));
1810
1811 // 260 intermediate dispatches push past slot 256 (into chunk 1) in a single unsubmitted encoder.
1812 let fill_params = CustomParams {
1813 n0: [0.9, 0.1, 0.0, 0.0],
1814 img_dims1: [4.0, 4.0, 4.0, 4.0],
1815 ..Default::default()
1816 };
1817 for _ in 0..260 {
1818 assert!(cache.dispatch(
1819 eng.device(),
1820 eng.queue(),
1821 &mut enc,
1822 &prog,
1823 wgpu::TextureFormat::Rgba8Unorm,
1824 &dummy.view,
1825 &dummy.view,
1826 &dummy.view,
1827 &dummy.view,
1828 &dst_mid.view,
1829 [4, 4],
1830 &fill_params,
1831 ));
1832 }
1833
1834 let last_params = CustomParams {
1835 n0: [0.6, 0.4, 0.0, 0.0],
1836 img_dims1: [4.0, 4.0, 4.0, 4.0],
1837 ..Default::default()
1838 };
1839 assert!(cache.dispatch(
1840 eng.device(),
1841 eng.queue(),
1842 &mut enc,
1843 &prog,
1844 wgpu::TextureFormat::Rgba8Unorm,
1845 &dummy.view,
1846 &dummy.view,
1847 &dummy.view,
1848 &dummy.view,
1849 &dst_last.view,
1850 [4, 4],
1851 &last_params,
1852 ));
1853
1854 assert_eq!(cache.uniform_chunks.len(), 2);
1855 assert_eq!(cache.uniform_cursor, 262);
1856 assert!(cache.cached_bind_group_count() >= 2);
1857 eng.queue().submit(Some(enc.finish()));
1858
1859 let rgba_first = eng.readback_rgba(&dst_first).expect("readback first");
1860 let rgba_last = eng.readback_rgba(&dst_last).expect("readback last");
1861 assert!(
1862 (rgba_first[0] as i32 - 51).abs() <= 1 && (rgba_first[1] as i32 - 204).abs() <= 1,
1863 "slot 0 must not be overwritten by chunk 1 writes: got {:?}",
1864 &rgba_first[..4]
1865 );
1866 assert!(
1867 (rgba_last[0] as i32 - 153).abs() <= 1 && (rgba_last[1] as i32 - 102).abs() <= 1,
1868 "chunk 1 write must produce exact params: got {:?}",
1869 &rgba_last[..4]
1870 );
1871
1872 // Trimming chunks resets cursor and invalidates bind groups referencing trimmed buffers.
1873 cache.trim_uniform_chunks(1);
1874 assert_eq!(cache.uniform_chunks.len(), 1);
1875 assert_eq!(cache.uniform_cursor, 0);
1876 assert_eq!(cache.cached_bind_group_count(), 0);
1877 }
1878
1879 #[test]
1880 fn custom_shader_cache_evicts_lru_pipelines_past_capacity() {
1881 let eng = Engine::new_headless().expect("gpu");
1882 let mut cache = CustomShaderCache::new();
1883 let fmt = wgpu::TextureFormat::Rgba8Unorm;
1884 let make_prog = |i: usize| CustomProgram {
1885 red: format!("{i}.0 / 255.0"),
1886 green: "0".to_owned(),
1887 blue: "0".to_owned(),
1888 alpha: "1".to_owned(),
1889 ..Default::default()
1890 };
1891
1892 for i in 0..MAX_CUSTOM_PIPELINES {
1893 let p = make_prog(i);
1894 assert!(cache.ensure_compiled(eng.device(), &p, fmt));
1895 }
1896 assert_eq!(cache.cached_pipeline_count(), MAX_CUSTOM_PIPELINES);
1897
1898 // Touch entry 0 so entry 1 becomes the least recently used pipeline.
1899 let p0 = make_prog(0);
1900 let p1 = make_prog(1);
1901 assert!(cache.ensure_compiled(eng.device(), &p0, fmt));
1902
1903 let p_new = make_prog(MAX_CUSTOM_PIPELINES);
1904 assert!(cache.ensure_compiled(eng.device(), &p_new, fmt));
1905 assert_eq!(cache.cached_pipeline_count(), MAX_CUSTOM_PIPELINES);
1906 assert!(cache.pipelines.contains_key(&(fmt, p0.normalized())));
1907 assert!(!cache.pipelines.contains_key(&(fmt, p1.normalized())));
1908 assert!(cache.pipelines.contains_key(&(fmt, p_new.normalized())));
1909 }
1910}