authoravatarclover caruso<git@paperclover.net>2026-11-30 20:00:17-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 20:12:25-08:00
log79c98cb78b7de4f5a3b178ce9c0cdf90a594d95d
treeb43f9e34b253365a664b687540f1d1b23c9f074c
parent2810ca0adc68286adada4ae16bea07aa16dd2e4f
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Split shapes_warp.rs into shapes.rs and warps.rs and refine Drip edge handling


5 files changed, 2010 insertions(+), 1949 deletions(-)

crates/engine/src/eval/mod.rs+2-1
......@@ -19,7 +19,8 @@ mod blur_glow;
1919mod keyers;
2020mod masks;
2121mod paint;
22mod shapes_warp;
22mod shapes;
23mod warps;
2324mod text_3d;
2425
2526
crates/engine/src/eval/shapes.rs created+1009
......@@ -0,0 +1,1009 @@
1//! 2D Vector Shape Pipeline (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sGrid`,
2//! `sMerge`, `sTransform`, `sBoolean`, `sOutline`).
3
4use super::*;
5
6#[derive(Clone, Copy, Debug)]
7struct Affine2D {
8 // [a, b, c, d, tx, ty] => x' = a*x + b*y + tx, y' = c*x + d*y + ty
9 m: [f32; 6],
10}
11
12impl Affine2D {
13 fn identity() -> Self {
14 Self { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] }
15 }
16
17 fn translate(tx: f32, ty: f32) -> Self {
18 Self { m: [1.0, 0.0, 0.0, 1.0, tx, ty] }
19 }
20
21 fn scale(sx: f32, sy: f32) -> Self {
22 Self { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }
23 }
24
25 fn rotate_deg(deg: f32) -> Self {
26 let r = deg.to_radians();
27 let (s, c) = r.sin_cos();
28 Self { m: [c, -s, s, c, 0.0, 0.0] }
29 }
30
31 fn mul(self, rhs: Self) -> Self {
32 let [a1, b1, c1, d1, tx1, ty1] = self.m;
33 let [a2, b2, c2, d2, tx2, ty2] = rhs.m;
34 Self {
35 m: [
36 a1 * a2 + b1 * c2,
37 a1 * b2 + b1 * d2,
38 c1 * a2 + d1 * c2,
39 c1 * b2 + d1 * d2,
40 a1 * tx2 + b1 * ty2 + tx1,
41 c1 * tx2 + d1 * ty2 + ty1,
42 ],
43 }
44 }
45
46 fn apply(self, p: [f32; 2]) -> [f32; 2] {
47 [
48 self.m[0] * p[0] + self.m[1] * p[1] + self.m[4],
49 self.m[2] * p[0] + self.m[3] * p[1] + self.m[5],
50 ]
51 }
52
53 fn avg_scale(self) -> f32 {
54 let sx = self.m[0].hypot(self.m[2]);
55 let sy = self.m[1].hypot(self.m[3]);
56 ((sx + sy) * 0.5).max(1e-4)
57 }
58
59 fn hash_into(self, h: &mut DefaultHasher) {
60 for v in self.m {
61 v.to_bits().hash(h);
62 }
63 }
64}
65
66#[derive(Clone, Copy, Debug)]
67enum ShapePrimKind {
68 NGon { sides: u32, width: f32, height: f32 },
69 Rectangle { width: f32, height: f32, corner_radius: f32 },
70 Ellipse { width: f32, height: f32 },
71}
72
73#[derive(Clone, Copy, Debug)]
74enum ShapeBoolOp {
75 Union,
76 Intersect,
77 Subtract,
78 Xor,
79}
80
81#[derive(Clone, Debug)]
82enum ShapeTree {
83 Primitive {
84 kind: ShapePrimKind,
85 xform: Affine2D,
86 color: [f32; 4],
87 solid: bool,
88 border_width: f32,
89 join_style: u8,
90 cap_style: u8,
91 },
92 Group(Vec<ShapeTree>),
93 Boolean {
94 op: ShapeBoolOp,
95 color: [f32; 4],
96 a: Box<ShapeTree>,
97 b: Box<ShapeTree>,
98 },
99}
100
101impl ShapeTree {
102 fn hash_into(&self, h: &mut DefaultHasher) {
103 match self {
104 ShapeTree::Primitive {
105 kind,
106 xform,
107 color,
108 solid,
109 border_width,
110 join_style,
111 cap_style,
112 } => {
113 0u8.hash(h);
114 match *kind {
115 ShapePrimKind::NGon { sides, width, height } => {
116 1u8.hash(h);
117 sides.hash(h);
118 width.to_bits().hash(h);
119 height.to_bits().hash(h);
120 }
121 ShapePrimKind::Rectangle { width, height, corner_radius } => {
122 2u8.hash(h);
123 width.to_bits().hash(h);
124 height.to_bits().hash(h);
125 corner_radius.to_bits().hash(h);
126 }
127 ShapePrimKind::Ellipse { width, height } => {
128 3u8.hash(h);
129 width.to_bits().hash(h);
130 height.to_bits().hash(h);
131 }
132 }
133 xform.hash_into(h);
134 for c in color {
135 c.to_bits().hash(h);
136 }
137 solid.hash(h);
138 border_width.to_bits().hash(h);
139 join_style.hash(h);
140 cap_style.hash(h);
141 }
142 ShapeTree::Group(children) => {
143 1u8.hash(h);
144 children.len().hash(h);
145 for ch in children {
146 ch.hash_into(h);
147 }
148 }
149 ShapeTree::Boolean { op, color, a, b } => {
150 2u8.hash(h);
151 (*op as u8).hash(h);
152 for c in color {
153 c.to_bits().hash(h);
154 }
155 a.hash_into(h);
156 b.hash_into(h);
157 }
158 }
159 }
160}
161
162fn eval_first_num(
163 comp: &Comp,
164 node: &Node,
165 keys: &[&str],
166 time: f64,
167 default: f64,
168 expr: &ExprEngine,
169) -> f64 {
170 for &k in keys {
171 if node.inputs.contains_key(k) {
172 return comp.eval_number(node, k, time, default, expr);
173 }
174 }
175 default
176}
177
178/// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty.
179fn parse_bool_op(node: &Node) -> Option<ShapeBoolOp> {
180 if !node.inputs.contains_key("Operation") {
181 return Some(ShapeBoolOp::Intersect);
182 }
183 match node.static_str("Operation")? {
184 "Union" => Some(ShapeBoolOp::Union),
185 "Intersection" => Some(ShapeBoolOp::Intersect),
186 "Subtract" => Some(ShapeBoolOp::Subtract),
187 "Xor" => Some(ShapeBoolOp::Xor),
188 _ => None,
189 }
190}
191
192#[allow(clippy::too_many_arguments)]
193fn collect_shape_tree(
194 comp: &Comp,
195 node_id: NodeId,
196 time: f64,
197 expr: &ExprEngine,
198 parent_xform: Affine2D,
199 outline_override: Option<(f32, u8, u8)>,
200 depth: usize,
201) -> Option<ShapeTree> {
202 if depth > 32 {
203 return None;
204 }
205 let node = comp.node(node_id);
206 if node.bypassed {
207 return node
208 .connected_node("Input")
209 .or_else(|| node.connected_node("Input1"))
210 .and_then(|s| comp.find_node(s))
211 .and_then(|id| {
212 collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1)
213 });
214 }
215
216 match node.kind.as_str() {
217 "sNGon" | "sRectangle" | "sEllipse" => {
218 let tx = eval_first_num(comp, node, &["Translate.X", "XOffset"], time, 0.0, expr) as f32;
219 let ty = eval_first_num(comp, node, &["Translate.Y", "YOffset"], time, 0.0, expr) as f32;
220 let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32;
221 let local = Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle));
222 let xform = parent_xform.mul(local);
223
224 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
225 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
226 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
227 let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32;
228
229 let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5;
230 let mut border_width = comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32;
231 let mut join_style = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8;
232 let mut cap_style = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8;
233
234 if let Some((ov_w, ov_j, ov_c)) = outline_override {
235 solid = false;
236 border_width = ov_w;
237 join_style = ov_j;
238 cap_style = ov_c;
239 }
240
241 let kind = match node.kind.as_str() {
242 "sNGon" => {
243 let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32;
244 let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32;
245 let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32;
246 ShapePrimKind::NGon { sides, width, height }
247 }
248 "sRectangle" => {
249 let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32;
250 let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32;
251 let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32;
252 ShapePrimKind::Rectangle { width, height, corner_radius }
253 }
254 _ => {
255 let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32;
256 let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32;
257 ShapePrimKind::Ellipse { width, height }
258 }
259 };
260
261 Some(ShapeTree::Primitive {
262 kind,
263 xform,
264 color: [r, g, b, a],
265 solid,
266 border_width,
267 join_style,
268 cap_style,
269 })
270 }
271 "sTransform" => {
272 let src_id = node
273 .connected_node("Input")
274 .or_else(|| node.connected_node("Input1"))
275 .and_then(|s| comp.find_node(s))?;
276 let ox = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32;
277 let oy = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32;
278 let px = eval_first_num(comp, node, &["XPivot", "Pivot.X"], time, 0.0, expr) as f32;
279 let py = eval_first_num(comp, node, &["YPivot", "Pivot.Y"], time, 0.0, expr) as f32;
280 let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr);
281 let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32;
282 let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32;
283 let rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32;
284
285 let local = Affine2D::translate(ox + px, oy + py)
286 .mul(Affine2D::rotate_deg(rot))
287 .mul(Affine2D::scale(sx, sy))
288 .mul(Affine2D::translate(-px, -py));
289 let combined = parent_xform.mul(local);
290 collect_shape_tree(comp, src_id, time, expr, combined, outline_override, depth + 1)
291 }
292 "sMerge" => {
293 let mut ports: Vec<(u32, &str)> = node
294 .inputs
295 .keys()
296 .filter_map(|k| {
297 let rest = k.strip_prefix("Input")?;
298 let idx: u32 = if rest.is_empty() { 0 } else { rest.parse().ok()? };
299 Some((idx, k.as_str()))
300 })
301 .collect();
302 ports.sort_by_key(|&(idx, _)| idx);
303 let mut children = Vec::new();
304 for (_, port) in ports {
305 if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) {
306 if let Some(tree) = collect_shape_tree(
307 comp,
308 src_id,
309 time,
310 expr,
311 parent_xform,
312 outline_override,
313 depth + 1,
314 ) {
315 children.push(tree);
316 }
317 }
318 }
319 if children.is_empty() {
320 None
321 } else {
322 Some(ShapeTree::Group(children))
323 }
324 }
325 "sGrid" => {
326 let src_id = node
327 .connected_node("Input")
328 .or_else(|| node.connected_node("Input1"))
329 .and_then(|s| comp.find_node(s))?;
330 let cells_x = comp.eval_number(node, "CellsX", time, 3.0, expr).round().clamp(1.0, 256.0) as usize;
331 let cells_y = comp.eval_number(node, "CellsY", time, 3.0, expr).round().clamp(1.0, 256.0) as usize;
332 let x_off = comp.eval_number(node, "XOffset", time, 0.2, expr) as f32;
333 let y_off = comp.eval_number(node, "YOffset", time, 0.2, expr) as f32;
334 let mut children = Vec::with_capacity(cells_x.saturating_mul(cells_y));
335 for iy in 0..cells_y {
336 let ty = (iy as f32 - (cells_y as f32 - 1.0) * 0.5) * y_off;
337 for ix in 0..cells_x {
338 let tx = (ix as f32 - (cells_x as f32 - 1.0) * 0.5) * x_off;
339 let cell_xf = parent_xform.mul(Affine2D::translate(tx, ty));
340 if let Some(tree) = collect_shape_tree(
341 comp,
342 src_id,
343 time,
344 expr,
345 cell_xf,
346 outline_override,
347 depth + 1,
348 ) {
349 children.push(tree);
350 }
351 }
352 }
353 if children.is_empty() {
354 None
355 } else {
356 Some(ShapeTree::Group(children))
357 }
358 }
359 "sOutline" => {
360 let src_id = node
361 .connected_node("Input")
362 .or_else(|| node.connected_node("Input1"))
363 .and_then(|s| comp.find_node(s))?;
364 let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr).abs() as f32;
365 let join = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8;
366 let cap = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8;
367 collect_shape_tree(comp, src_id, time, expr, parent_xform, Some((thickness, join, cap)), depth + 1)
368 }
369 "sBoolean" => {
370 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
371 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
372 let b_col = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
373 let a_col = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32;
374 let color = [r, g, b_col, a_col];
375 let child = |port: &str| {
376 node.connected_node(port)
377 .and_then(|s| comp.find_node(s))
378 .and_then(|id| {
379 collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1)
380 })
381 };
382 let a = child("Input1").or_else(|| child("Input"))?;
383 // Input2 absent passes Input1 through (recolored) whatever the operation; Input1 absent renders empty.
384 let (op, b) = match (parse_bool_op(node), child("Input2")) {
385 (_, None) => (ShapeBoolOp::Union, ShapeTree::Group(Vec::new())),
386 (Some(op), Some(b)) => (op, b),
387 (None, Some(_)) => return None,
388 };
389 Some(ShapeTree::Boolean {
390 op,
391 color,
392 a: Box::new(a),
393 b: Box::new(b),
394 })
395 }
396 "PipeRouter" | "Fuse.Wireless" => {
397 let src_id = node
398 .connected_node("Input")
399 .or_else(|| node.connected_node("Input1"))
400 .and_then(|s| comp.find_node(s))?;
401 collect_shape_tree(comp, src_id, time, expr, parent_xform, outline_override, depth + 1)
402 }
403 "MacroOperator" | "GroupOperator" => {
404 let out_id = node.macro_output?;
405 collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1)
406 }
407 _ => None,
408 }
409}
410
411fn build_primitive_commands(kind: ShapePrimKind, xform: Affine2D, dims: [u32; 2]) -> Vec<zeno::Command> {
412 let wf = dims[0] as f32;
413 let hf = dims[1] as f32;
414 let to_px = |local: [f32; 2]| -> zeno::Vector {
415 let wpt = xform.apply(local);
416 let px = (wpt[0] + 0.5) * wf;
417 let py = 0.5 * hf - wpt[1] * wf;
418 zeno::Vector::new(px, py)
419 };
420
421 const KAPPA: f32 = 0.55228475;
422 let mut cmds = Vec::new();
423 match kind {
424 ShapePrimKind::NGon { sides, width, height } => {
425 let n = sides.max(3);
426 let rx = width * 0.5;
427 let ry = height * 0.5;
428 if rx <= 1e-6 || ry <= 1e-6 {
429 return cmds;
430 }
431 for k in 0..n {
432 let theta = (k as f32) * std::f32::consts::TAU / (n as f32);
433 let v = to_px([rx * theta.cos(), ry * theta.sin()]);
434 if k == 0 {
435 cmds.push(zeno::Command::MoveTo(v));
436 } else {
437 cmds.push(zeno::Command::LineTo(v));
438 }
439 }
440 cmds.push(zeno::Command::Close);
441 }
442 ShapePrimKind::Rectangle { width, height, corner_radius } => {
443 let hx = width * 0.5;
444 let hy = height * 0.5;
445 if hx <= 1e-6 || hy <= 1e-6 {
446 return cmds;
447 }
448 let r = corner_radius.min(hx.min(hy));
449 if r <= 1e-5 {
450 cmds.push(zeno::Command::MoveTo(to_px([-hx, -hy])));
451 cmds.push(zeno::Command::LineTo(to_px([hx, -hy])));
452 cmds.push(zeno::Command::LineTo(to_px([hx, hy])));
453 cmds.push(zeno::Command::LineTo(to_px([-hx, hy])));
454 cmds.push(zeno::Command::Close);
455 } else {
456 let k = r * KAPPA;
457 cmds.push(zeno::Command::MoveTo(to_px([-hx + r, -hy])));
458 cmds.push(zeno::Command::LineTo(to_px([hx - r, -hy])));
459 cmds.push(zeno::Command::CurveTo(
460 to_px([hx - r + k, -hy]),
461 to_px([hx, -hy + r - k]),
462 to_px([hx, -hy + r]),
463 ));
464 cmds.push(zeno::Command::LineTo(to_px([hx, hy - r])));
465 cmds.push(zeno::Command::CurveTo(
466 to_px([hx, hy - r + k]),
467 to_px([hx - r + k, hy]),
468 to_px([hx - r, hy]),
469 ));
470 cmds.push(zeno::Command::LineTo(to_px([-hx + r, hy])));
471 cmds.push(zeno::Command::CurveTo(
472 to_px([-hx + r - k, hy]),
473 to_px([-hx, hy - r + k]),
474 to_px([-hx, hy - r]),
475 ));
476 cmds.push(zeno::Command::LineTo(to_px([-hx, -hy + r])));
477 cmds.push(zeno::Command::CurveTo(
478 to_px([-hx, -hy + r - k]),
479 to_px([-hx + r - k, -hy]),
480 to_px([-hx + r, -hy]),
481 ));
482 cmds.push(zeno::Command::Close);
483 }
484 }
485 ShapePrimKind::Ellipse { width, height } => {
486 let rx = width * 0.5;
487 let ry = height * 0.5;
488 if rx <= 1e-6 || ry <= 1e-6 {
489 return cmds;
490 }
491 let kx = rx * KAPPA;
492 let ky = ry * KAPPA;
493 cmds.push(zeno::Command::MoveTo(to_px([rx, 0.0])));
494 cmds.push(zeno::Command::CurveTo(
495 to_px([rx, ky]),
496 to_px([kx, ry]),
497 to_px([0.0, ry]),
498 ));
499 cmds.push(zeno::Command::CurveTo(
500 to_px([-kx, ry]),
501 to_px([-rx, ky]),
502 to_px([-rx, 0.0]),
503 ));
504 cmds.push(zeno::Command::CurveTo(
505 to_px([-rx, -ky]),
506 to_px([-kx, -ry]),
507 to_px([0.0, -ry]),
508 ));
509 cmds.push(zeno::Command::CurveTo(
510 to_px([kx, -ry]),
511 to_px([rx, -ky]),
512 to_px([rx, 0.0]),
513 ));
514 cmds.push(zeno::Command::Close);
515 }
516 }
517 cmds
518}
519
520fn composite_over(dst: &mut [f32], src: &[f32]) {
521 for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) {
522 let sa = s[3].clamp(0.0, 1.0);
523 if sa <= 1e-6 {
524 continue;
525 }
526 let inv = 1.0 - sa;
527 d[0] = s[0] + d[0] * inv;
528 d[1] = s[1] + d[1] * inv;
529 d[2] = s[2] + d[2] * inv;
530 d[3] = sa + d[3] * inv;
531 }
532}
533
534fn rasterize_shape_tree_f32(
535 tree: &ShapeTree,
536 dims: [u32; 2],
537 dst: &mut [f32],
538 cov_buf: &mut [u8],
539 scratch: &mut zeno::Scratch,
540) {
541 let [w, h] = dims;
542 match tree {
543 ShapeTree::Primitive {
544 kind,
545 xform,
546 color,
547 solid,
548 border_width,
549 join_style,
550 cap_style,
551 } => {
552 let cmds = build_primitive_commands(*kind, *xform, dims);
553 if cmds.is_empty() {
554 return;
555 }
556 cov_buf.fill(0);
557 let style = if *solid {
558 zeno::Style::Fill(zeno::Fill::NonZero)
559 } else {
560 let stroke_px = (*border_width * xform.avg_scale() * (w as f32)).max(0.5);
561 let join = match *join_style {
562 0 => zeno::Join::Bevel,
563 1 => zeno::Join::Round,
564 _ => zeno::Join::Miter,
565 };
566 let cap = match *cap_style {
567 1 => zeno::Cap::Round,
568 2 => zeno::Cap::Square,
569 _ => zeno::Cap::Butt,
570 };
571 let mut st = zeno::Stroke::new(stroke_px);
572 st.join(join).cap(cap);
573 zeno::Style::Stroke(st)
574 };
575 let _ = zeno::Mask::with_scratch(&cmds, scratch)
576 .style(style)
577 .size(w, h)
578 .origin(zeno::Origin::TopLeft)
579 .render_into(cov_buf, None);
580
581 let ca = color[3].clamp(0.0, 1.0);
582 if ca <= 1e-6 {
583 return;
584 }
585 for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) {
586 if cov == 0 {
587 continue;
588 }
589 let sa = (cov as f32 / 255.0) * ca;
590 let inv = 1.0 - sa;
591 px[0] = color[0] * sa + px[0] * inv;
592 px[1] = color[1] * sa + px[1] * inv;
593 px[2] = color[2] * sa + px[2] * inv;
594 px[3] = sa + px[3] * inv;
595 }
596 }
597 ShapeTree::Group(children) => {
598 for ch in children {
599 rasterize_shape_tree_f32(ch, dims, dst, cov_buf, scratch);
600 }
601 }
602 ShapeTree::Boolean { op, color, a, b } => {
603 let len = dst.len();
604 let mut buf_a = vec![0.0f32; len];
605 let mut buf_b = vec![0.0f32; len];
606 rasterize_shape_tree_f32(a, dims, &mut buf_a, cov_buf, scratch);
607 rasterize_shape_tree_f32(b, dims, &mut buf_b, cov_buf, scratch);
608 let mut comb = vec![0.0f32; len];
609 let ca = color[3].clamp(0.0, 1.0);
610 for ((ca_p, cb_p), out_p) in buf_a
611 .chunks_exact(4)
612 .zip(buf_b.chunks_exact(4))
613 .zip(comb.chunks_exact_mut(4))
614 {
615 let aa = ca_p[3].clamp(0.0, 1.0);
616 let ba = cb_p[3].clamp(0.0, 1.0);
617 let oa = match op {
618 ShapeBoolOp::Union => (aa + ba - aa * ba).clamp(0.0, 1.0),
619 ShapeBoolOp::Intersect => (aa * ba).clamp(0.0, 1.0),
620 ShapeBoolOp::Subtract => (aa * (1.0 - ba)).clamp(0.0, 1.0),
621 ShapeBoolOp::Xor => (aa * (1.0 - ba) + ba * (1.0 - aa)).clamp(0.0, 1.0),
622 };
623 let sa = oa * ca;
624 out_p[0] = color[0] * sa;
625 out_p[1] = color[1] * sa;
626 out_p[2] = color[2] * sa;
627 out_p[3] = sa;
628 }
629 composite_over(dst, &comb);
630 }
631 }
632}
633
634fn rasterize_shape_tree_rgba8(tree: Option<&ShapeTree>, dims: [u32; 2], blend: f32) -> Vec<u8> {
635 let px_count = (dims[0] as usize) * (dims[1] as usize);
636 let mut out = vec![0u8; px_count * 4];
637 let Some(tree) = tree else {
638 return out;
639 };
640 let b = blend.clamp(0.0, 1.0);
641 if b <= 1e-6 {
642 return out;
643 }
644 let mut accum = vec![0.0f32; px_count * 4];
645 let mut cov_buf = vec![0u8; px_count];
646 let mut scratch = zeno::Scratch::new();
647 rasterize_shape_tree_f32(tree, dims, &mut accum, &mut cov_buf, &mut scratch);
648 for (dst_px, src_px) in out.chunks_exact_mut(4).zip(accum.chunks_exact(4)) {
649 dst_px[0] = (src_px[0] * b * 255.0).round().clamp(0.0, 255.0) as u8;
650 dst_px[1] = (src_px[1] * b * 255.0).round().clamp(0.0, 255.0) as u8;
651 dst_px[2] = (src_px[2] * b * 255.0).round().clamp(0.0, 255.0) as u8;
652 dst_px[3] = (src_px[3] * b * 255.0).round().clamp(0.0, 255.0) as u8;
653 }
654 out
655}
656
657impl Engine {
658 #[allow(clippy::too_many_arguments)]
659 pub(super) fn eval_s_render(
660 &mut self,
661 comp: &Comp,
662 node: &Node,
663 time: f64,
664 frame_i: i64,
665 comp_dims: [u32; 2],
666 enc: &mut wgpu::CommandEncoder,
667 visiting: &mut HashSet<(NodeId, i64)>,
668 stats: &mut EvalStats,
669 ) -> CachedTexture {
670 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32;
671 let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32;
672 let dims = if w > 1 && h > 1 { self.scaled_dims(w, h) } else { comp_dims };
673 let dst_depth = self.node_depth(comp, node, time, None);
674 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
675
676 let shape_tree = node
677 .connected_node("Input")
678 .and_then(|s| comp.find_node(s))
679 .and_then(|src_id| {
680 collect_shape_tree(comp, src_id, time, &self.expr, Affine2D::identity(), None, 0)
681 });
682
683 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats);
684 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
685
686 let mut h_key = DefaultHasher::new();
687 self.cache.gpu_salt.hash(&mut h_key);
688 self.hiq.hash(&mut h_key);
689 self.cache.node_salt(node.id).hash(&mut h_key);
690 "sRender".hash(&mut h_key);
691 dims.hash(&mut h_key);
692 dst_depth.hash(&mut h_key);
693 blend.to_bits().hash(&mut h_key);
694 mask_hash.hash(&mut h_key);
695 mask_inv.hash(&mut h_key);
696 if let Some(ref tree) = shape_tree {
697 1u8.hash(&mut h_key);
698 tree.hash_into(&mut h_key);
699 } else {
700 0u8.hash(&mut h_key);
701 }
702 let key = h_key.finish();
703
704 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
705 stats.cache_hits += 1;
706 return hit;
707 }
708 stats.cache_misses += 1;
709 stats.nodes_evaluated += 1;
710
711 let rgba = rasterize_shape_tree_rgba8(shape_tree.as_ref(), dims, blend);
712 let needs_post = dst_depth != BitDepth::Int8 || mask.is_some();
713 let base_tex = create_texture(&self.device, dims, if needs_post { 0 } else { key });
714 self.queue.write_texture(
715 base_tex.texture.as_image_copy(),
716 &rgba,
717 wgpu::TexelCopyBufferLayout {
718 offset: 0,
719 bytes_per_row: Some(dims[0] * 4),
720 rows_per_image: Some(dims[1]),
721 },
722 wgpu::Extent3d {
723 width: dims[0],
724 height: dims[1],
725 depth_or_array_layers: 1,
726 },
727 );
728
729 let mut out = if dst_depth != BitDepth::Int8 {
730 let promoted = self.alloc_tex(dims, dst_depth, if mask.is_some() { 0 } else { key });
731 let u = UniformParams::default();
732 self.dispatch_op(
733 enc,
734 ShaderOp::ChangeDepth,
735 &base_tex.view,
736 &self.dummy.view,
737 &self.dummy.view,
738 &promoted,
739 &u,
740 );
741 promoted
742 } else {
743 base_tex
744 };
745
746 if let Some(ref mtex) = mask {
747 let masked = self.alloc_tex(dims, out.depth, key);
748 let mut u = UniformParams::default();
749 u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
750 self.dispatch_op(
751 enc,
752 ShaderOp::MaskApply,
753 &out.view,
754 &self.dummy.view,
755 &mtex.view,
756 &masked,
757 &u,
758 );
759 out = masked;
760 }
761
762 self.cache.insert(key, out.clone(), node.id, frame_i);
763 out
764 }
765}
766
767#[cfg(test)]
768mod tests {
769 use super::*;
770 use crate::Engine;
771
772 #[test]
773 fn test_s_render_ngon_transform_merge_and_boolean() {
774 let src = r#"Composition {
775 CurrentTime = 0,
776 RenderRange = { 0, 1 },
777 GlobalRange = { 0, 1 },
778 Tools = ordered() {
779 NGon1 = sNGon {
780 Inputs = {
781 Sides = Input { Value = 6, },
782 Width = Input { Value = 0.4, },
783 Red = Input { Value = 1.0, },
784 Green = Input { Value = 0.0, },
785 Blue = Input { Value = 0.0, },
786 },
787 },
788 XF1 = sTransform {
789 Inputs = {
790 XOffset = Input { Value = -0.2, },
791 YOffset = Input { Value = 0.0, },
792 XSize = Input { Value = 1.0, },
793 YSize = Input { Value = 1.0, },
794 ZRotation = Input { Value = 15.0, },
795 Input = Input { SourceOp = "NGon1", Source = "Output", },
796 },
797 },
798 Rect1 = sRectangle {
799 Inputs = {
800 Width = Input { Value = 0.3, },
801 Height = Input { Value = 0.3, },
802 CornerRadius = Input { Value = 0.05, },
803 Translate = Input { Value = { 0.0, 0.0 }, },
804 ["Translate.X"] = Input { Value = 0.2, },
805 Red = Input { Value = 0.0, },
806 Green = Input { Value = 0.0, },
807 Blue = Input { Value = 1.0, },
808 },
809 },
810 Merge1 = sMerge {
811 Inputs = {
812 Input1 = Input { SourceOp = "XF1", Source = "Output", },
813 Input2 = Input { SourceOp = "Rect1", Source = "Output", },
814 },
815 },
816 Render1 = sRender {
817 Inputs = {
818 Width = Input { Value = 128, },
819 Height = Input { Value = 128, },
820 Input = Input { SourceOp = "Merge1", Source = "Output", },
821 },
822 },
823 },
824 }"#;
825 let comp = Comp::from_fusion_str(src).expect("parse sRender comp");
826 let Ok(mut eng) = Engine::new_headless() else {
827 return;
828 };
829 let render_id = comp.find_node("Render1").unwrap();
830 let (tex, stats) = eng.evaluate(&comp, render_id, 0.0);
831 assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes);
832 assert_eq!(tex.size, [128, 128]);
833 let px = eng.readback_rgba(&tex).expect("readback sRender");
834
835 // Left shape center (-0.2 -> x ~ 38, y ~ 64) should be solid red
836 let left = (64 * 128 + 38) * 4;
837 assert!(px[left] > 240 && px[left + 2] < 10 && px[left + 3] > 240, "left={:?}", &px[left..left + 4]);
838 // Right shape center (+0.2 -> x ~ 90, y ~ 64) should be solid blue
839 let right = (64 * 128 + 90) * 4;
840 assert!(px[right + 2] > 240 && px[right] < 10 && px[right + 3] > 240, "right={:?}", &px[right..right + 4]);
841 // Top-left corner (0, 0) should be transparent
842 assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner should be transparent");
843 }
844
845
846 #[test]
847 fn test_s_boolean_uses_own_color_and_subtract_xor() {
848 let src = r#"Composition {
849 CurrentTime = 0,
850 RenderRange = { 0, 1 },
851 GlobalRange = { 0, 1 },
852 Tools = ordered() {
853 NGon1 = sNGon {
854 Inputs = {
855 Sides = Input { Value = 5, },
856 Width = Input { Value = 0.5, },
857 Height = Input { Value = 0.5, },
858 Red = Input { Value = 1.0, },
859 Green = Input { Value = 0.0, },
860 Blue = Input { Value = 0.0, },
861 },
862 },
863 Rect1 = sRectangle {
864 Inputs = {
865 Width = Input { Value = 0.35, },
866 Height = Input { Value = 0.35, },
867 ["Translate.X"] = Input { Value = 0.18, },
868 Red = Input { Value = 0.0, },
869 Green = Input { Value = 1.0, },
870 Blue = Input { Value = 0.0, },
871 },
872 },
873 BoolSub = sBoolean {
874 Inputs = {
875 Operation = Input { Value = FuID { "Subtract" }, },
876 Input1 = Input { SourceOp = "Rect1", Source = "Output", },
877 Input2 = Input { SourceOp = "NGon1", Source = "Output", },
878 },
879 },
880 BoolXor = sBoolean {
881 Inputs = {
882 Operation = Input { Value = FuID { "Xor" }, },
883 Input1 = Input { SourceOp = "NGon1", Source = "Output", },
884 Input2 = Input { SourceOp = "Rect1", Source = "Output", },
885 },
886 },
887 RSub = sRender {
888 Inputs = {
889 Width = Input { Value = 128, },
890 Height = Input { Value = 128, },
891 Input = Input { SourceOp = "BoolSub", Source = "Output", },
892 },
893 },
894 RXor = sRender {
895 Inputs = {
896 Width = Input { Value = 128, },
897 Height = Input { Value = 128, },
898 Input = Input { SourceOp = "BoolXor", Source = "Output", },
899 },
900 },
901 },
902 }"#;
903 let comp = Comp::from_fusion_str(src).unwrap();
904 let Ok(mut eng) = Engine::new_headless() else {
905 return;
906 };
907 let (tex_sub, _) = eng.evaluate(&comp, comp.find_node("RSub").unwrap(), 0.0);
908 let (tex_xor, _) = eng.evaluate(&comp, comp.find_node("RXor").unwrap(), 0.0);
909 let px_sub = eng.readback_rgba(&tex_sub).unwrap();
910 let px_xor = eng.readback_rgba(&tex_xor).unwrap();
911
912 // Far right of Rect (x=0.30 -> px=102, y=64): outside NGon (max x=0.25), inside Rect -> white!
913 let rect_only = (64 * 128 + 102) * 4;
914 assert_eq!(&px_sub[rect_only..rect_only + 4], &[255, 255, 255, 255]);
915 assert_eq!(&px_xor[rect_only..rect_only + 4], &[255, 255, 255, 255]);
916
917 // Overlap region (x=0.10 -> px=77, y=64): subtracted/xored out -> transparent!
918 let overlap = (64 * 128 + 77) * 4;
919 assert_eq!(&px_sub[overlap..overlap + 4], &[0, 0, 0, 0]);
920 assert_eq!(&px_xor[overlap..overlap + 4], &[0, 0, 0, 0]);
921
922 // Center (0,0 -> px=64, y=64): inside NGon, outside Rect (starts at 0.005) -> white in Xor!
923 let ngon_only = (64 * 128 + 54) * 4;
924 assert_eq!(&px_xor[ngon_only..ngon_only + 4], &[255, 255, 255, 255]);
925 }
926
927 #[test]
928 fn test_s_boolean_operation_names_and_missing_inputs() {
929 let boolean = |name: &str, op: &str, inputs: &str| {
930 format!(
931 r#"{name} = sBoolean {{ Inputs = {{ {op} {inputs} }}, }},
932 R{name} = sRender {{ Inputs = {{ Width = Input {{ Value = 128, }}, Height = Input {{ Value = 128, }},
933 Input = Input {{ SourceOp = "{name}", Source = "Output", }}, }}, }},"#
934 )
935 };
936 let both = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", }, Input2 = Input { SourceOp = "Ell", Source = "Output", },"#;
937 let first = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", },"#;
938 let second = r#"Input2 = Input { SourceOp = "Ell", Source = "Output", },"#;
939 let fu = |v: &str| format!(r#"Operation = Input {{ Value = FuID {{ "{v}" }}, }},"#);
940 let src = format!(
941 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
942 Rect = sRectangle {{ Inputs = {{ Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.2, }},
943 Red = Input {{ Value = 1, }}, Green = Input {{ Value = 0, }}, Blue = Input {{ Value = 0, }}, }}, }},
944 Ell = sEllipse {{ Inputs = {{ Width = Input {{ Value = 0.3, }}, Height = Input {{ Value = 0.3, }}, }}, }},
945 {} {} {} {} {} {}
946 }} }}"#,
947 boolean("Inter", &fu("Intersection"), both),
948 boolean("Default", "", both),
949 boolean("Unknown", &fu("Intersect"), both),
950 boolean("SubFirst", &fu("Subtract"), first),
951 boolean("SubSecond", &fu("Subtract"), second),
952 boolean("UnionBoth", &fu("Union"), both),
953 );
954 let comp = Comp::from_fusion_str(&src).unwrap();
955 let Ok(mut eng) = Engine::new_headless() else {
956 return;
957 };
958 let mut px = |name: &str, x: usize| {
959 let (tex, _) = eng.evaluate(&comp, comp.find_node(&format!("R{name}")).unwrap(), 0.0);
960 let rgba = eng.readback_rgba(&tex).unwrap();
961 let i = (64 * 128 + x) * 4;
962 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
963 };
964 let white = [255; 4];
965 let empty = [0; 4];
966 // x=64 is inside both shapes, x=90 is inside only the rectangle.
967 assert_eq!(px("Inter", 64), white);
968 assert_eq!(px("Inter", 90), empty);
969 assert_eq!(px("Default", 64), white, "Operation defaults to Intersection");
970 assert_eq!(px("Unknown", 64), empty, "unrecognized operation names render nothing");
971 assert_eq!(px("SubFirst", 90), white, "a missing Input2 passes Input1 through in the boolean's own color");
972 assert_eq!(px("SubSecond", 64), empty, "a missing Input1 renders nothing");
973 assert_eq!(px("UnionBoth", 90), white);
974 }
975
976 #[test]
977 fn test_s_grid() {
978 let src = r#"{
979 Tools = ordered() {
980 El1 = sEllipse {
981 Inputs = { Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, },
982 },
983 Gr1 = sGrid {
984 Inputs = {
985 Input = Input { SourceOp = "El1", Source = "Output", },
986 CellsX = Input { Value = 3, },
987 CellsY = Input { Value = 3, },
988 XOffset = Input { Value = 0.25, },
989 YOffset = Input { Value = 0.25, },
990 },
991 },
992 SR1 = sRender {
993 Inputs = {
994 Width = Input { Value = 64, },
995 Height = Input { Value = 64, },
996 Input = Input { SourceOp = "Gr1", Source = "Output", },
997 },
998 },
999 },
1000 }"#;
1001 let comp = Comp::from_fusion_str(src).unwrap();
1002 let Ok(mut eng) = Engine::new_headless() else { return; };
1003 let (t_sr, _) = eng.evaluate(&comp, comp.find_node("SR1").unwrap(), 0.0);
1004 let px_sr = eng.readback_rgba(&t_sr).unwrap();
1005 assert_eq!(&px_sr[(32 * 64 + 32) * 4..(32 * 64 + 32) * 4 + 4], &[255, 255, 255, 255]);
1006 assert_eq!(&px_sr[(32 * 64 + 48) * 4..(32 * 64 + 48) * 4 + 4], &[255, 255, 255, 255]);
1007 assert_eq!(&px_sr[0..4], &[0, 0, 0, 0]);
1008 }
1009}
crates/engine/src/eval/shapes_warp.rs deleted-1947
......@@ -1,1947 +0,0 @@
1//! GPU Archive FX Warps (`Drip`, `Dent`) and 2D Vector Shape Pipeline
2//! (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sMerge`, `sTransform`, `sBoolean`, `sOutline`).
3
4use super::*;
5
6#[derive(Clone, Copy, Debug)]
7struct Affine2D {
8 // [a, b, c, d, tx, ty] => x' = a*x + b*y + tx, y' = c*x + d*y + ty
9 m: [f32; 6],
10}
11
12impl Affine2D {
13 fn identity() -> Self {
14 Self { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] }
15 }
16
17 fn translate(tx: f32, ty: f32) -> Self {
18 Self { m: [1.0, 0.0, 0.0, 1.0, tx, ty] }
19 }
20
21 fn scale(sx: f32, sy: f32) -> Self {
22 Self { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }
23 }
24
25 fn rotate_deg(deg: f32) -> Self {
26 let r = deg.to_radians();
27 let (s, c) = r.sin_cos();
28 Self { m: [c, -s, s, c, 0.0, 0.0] }
29 }
30
31 fn mul(self, rhs: Self) -> Self {
32 let [a1, b1, c1, d1, tx1, ty1] = self.m;
33 let [a2, b2, c2, d2, tx2, ty2] = rhs.m;
34 Self {
35 m: [
36 a1 * a2 + b1 * c2,
37 a1 * b2 + b1 * d2,
38 c1 * a2 + d1 * c2,
39 c1 * b2 + d1 * d2,
40 a1 * tx2 + b1 * ty2 + tx1,
41 c1 * tx2 + d1 * ty2 + ty1,
42 ],
43 }
44 }
45
46 fn apply(self, p: [f32; 2]) -> [f32; 2] {
47 [
48 self.m[0] * p[0] + self.m[1] * p[1] + self.m[4],
49 self.m[2] * p[0] + self.m[3] * p[1] + self.m[5],
50 ]
51 }
52
53 fn avg_scale(self) -> f32 {
54 let sx = self.m[0].hypot(self.m[2]);
55 let sy = self.m[1].hypot(self.m[3]);
56 ((sx + sy) * 0.5).max(1e-4)
57 }
58
59 fn hash_into(self, h: &mut DefaultHasher) {
60 for v in self.m {
61 v.to_bits().hash(h);
62 }
63 }
64}
65
66#[derive(Clone, Copy, Debug)]
67enum ShapePrimKind {
68 NGon { sides: u32, width: f32, height: f32 },
69 Rectangle { width: f32, height: f32, corner_radius: f32 },
70 Ellipse { width: f32, height: f32 },
71}
72
73#[derive(Clone, Copy, Debug)]
74enum ShapeBoolOp {
75 Union,
76 Intersect,
77 Subtract,
78 Xor,
79}
80
81#[derive(Clone, Debug)]
82enum ShapeTree {
83 Primitive {
84 kind: ShapePrimKind,
85 xform: Affine2D,
86 color: [f32; 4],
87 solid: bool,
88 border_width: f32,
89 join_style: u8,
90 cap_style: u8,
91 },
92 Group(Vec<ShapeTree>),
93 Boolean {
94 op: ShapeBoolOp,
95 color: [f32; 4],
96 a: Box<ShapeTree>,
97 b: Box<ShapeTree>,
98 },
99}
100
101impl ShapeTree {
102 fn hash_into(&self, h: &mut DefaultHasher) {
103 match self {
104 ShapeTree::Primitive {
105 kind,
106 xform,
107 color,
108 solid,
109 border_width,
110 join_style,
111 cap_style,
112 } => {
113 0u8.hash(h);
114 match *kind {
115 ShapePrimKind::NGon { sides, width, height } => {
116 1u8.hash(h);
117 sides.hash(h);
118 width.to_bits().hash(h);
119 height.to_bits().hash(h);
120 }
121 ShapePrimKind::Rectangle { width, height, corner_radius } => {
122 2u8.hash(h);
123 width.to_bits().hash(h);
124 height.to_bits().hash(h);
125 corner_radius.to_bits().hash(h);
126 }
127 ShapePrimKind::Ellipse { width, height } => {
128 3u8.hash(h);
129 width.to_bits().hash(h);
130 height.to_bits().hash(h);
131 }
132 }
133 xform.hash_into(h);
134 for c in color {
135 c.to_bits().hash(h);
136 }
137 solid.hash(h);
138 border_width.to_bits().hash(h);
139 join_style.hash(h);
140 cap_style.hash(h);
141 }
142 ShapeTree::Group(children) => {
143 1u8.hash(h);
144 children.len().hash(h);
145 for ch in children {
146 ch.hash_into(h);
147 }
148 }
149 ShapeTree::Boolean { op, color, a, b } => {
150 2u8.hash(h);
151 (*op as u8).hash(h);
152 for c in color {
153 c.to_bits().hash(h);
154 }
155 a.hash_into(h);
156 b.hash_into(h);
157 }
158 }
159 }
160}
161
162fn eval_first_num(
163 comp: &Comp,
164 node: &Node,
165 keys: &[&str],
166 time: f64,
167 default: f64,
168 expr: &ExprEngine,
169) -> f64 {
170 for &k in keys {
171 if node.inputs.contains_key(k) {
172 return comp.eval_number(node, k, time, default, expr);
173 }
174 }
175 default
176}
177
178/// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty.
179fn parse_bool_op(node: &Node) -> Option<ShapeBoolOp> {
180 if !node.inputs.contains_key("Operation") {
181 return Some(ShapeBoolOp::Intersect);
182 }
183 match node.static_str("Operation")? {
184 "Union" => Some(ShapeBoolOp::Union),
185 "Intersection" => Some(ShapeBoolOp::Intersect),
186 "Subtract" => Some(ShapeBoolOp::Subtract),
187 "Xor" => Some(ShapeBoolOp::Xor),
188 _ => None,
189 }
190}
191
192#[allow(clippy::too_many_arguments)]
193fn collect_shape_tree(
194 comp: &Comp,
195 node_id: NodeId,
196 time: f64,
197 expr: &ExprEngine,
198 parent_xform: Affine2D,
199 outline_override: Option<(f32, u8, u8)>,
200 depth: usize,
201) -> Option<ShapeTree> {
202 if depth > 32 {
203 return None;
204 }
205 let node = comp.node(node_id);
206 if node.bypassed {
207 return node
208 .connected_node("Input")
209 .or_else(|| node.connected_node("Input1"))
210 .and_then(|s| comp.find_node(s))
211 .and_then(|id| {
212 collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1)
213 });
214 }
215
216 match node.kind.as_str() {
217 "sNGon" | "sRectangle" | "sEllipse" => {
218 let tx = eval_first_num(comp, node, &["Translate.X", "XOffset"], time, 0.0, expr) as f32;
219 let ty = eval_first_num(comp, node, &["Translate.Y", "YOffset"], time, 0.0, expr) as f32;
220 let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32;
221 let local = Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle));
222 let xform = parent_xform.mul(local);
223
224 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
225 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
226 let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
227 let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32;
228
229 let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5;
230 let mut border_width = comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32;
231 let mut join_style = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8;
232 let mut cap_style = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8;
233
234 if let Some((ov_w, ov_j, ov_c)) = outline_override {
235 solid = false;
236 border_width = ov_w;
237 join_style = ov_j;
238 cap_style = ov_c;
239 }
240
241 let kind = match node.kind.as_str() {
242 "sNGon" => {
243 let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32;
244 let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32;
245 let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32;
246 ShapePrimKind::NGon { sides, width, height }
247 }
248 "sRectangle" => {
249 let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32;
250 let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32;
251 let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32;
252 ShapePrimKind::Rectangle { width, height, corner_radius }
253 }
254 _ => {
255 let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32;
256 let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32;
257 ShapePrimKind::Ellipse { width, height }
258 }
259 };
260
261 Some(ShapeTree::Primitive {
262 kind,
263 xform,
264 color: [r, g, b, a],
265 solid,
266 border_width,
267 join_style,
268 cap_style,
269 })
270 }
271 "sTransform" => {
272 let src_id = node
273 .connected_node("Input")
274 .or_else(|| node.connected_node("Input1"))
275 .and_then(|s| comp.find_node(s))?;
276 let ox = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32;
277 let oy = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32;
278 let px = eval_first_num(comp, node, &["XPivot", "Pivot.X"], time, 0.0, expr) as f32;
279 let py = eval_first_num(comp, node, &["YPivot", "Pivot.Y"], time, 0.0, expr) as f32;
280 let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr);
281 let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32;
282 let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32;
283 let rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32;
284
285 let local = Affine2D::translate(ox + px, oy + py)
286 .mul(Affine2D::rotate_deg(rot))
287 .mul(Affine2D::scale(sx, sy))
288 .mul(Affine2D::translate(-px, -py));
289 let combined = parent_xform.mul(local);
290 collect_shape_tree(comp, src_id, time, expr, combined, outline_override, depth + 1)
291 }
292 "sMerge" => {
293 let mut ports: Vec<(u32, &str)> = node
294 .inputs
295 .keys()
296 .filter_map(|k| {
297 let rest = k.strip_prefix("Input")?;
298 let idx: u32 = if rest.is_empty() { 0 } else { rest.parse().ok()? };
299 Some((idx, k.as_str()))
300 })
301 .collect();
302 ports.sort_by_key(|&(idx, _)| idx);
303 let mut children = Vec::new();
304 for (_, port) in ports {
305 if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) {
306 if let Some(tree) = collect_shape_tree(
307 comp,
308 src_id,
309 time,
310 expr,
311 parent_xform,
312 outline_override,
313 depth + 1,
314 ) {
315 children.push(tree);
316 }
317 }
318 }
319 if children.is_empty() {
320 None
321 } else {
322 Some(ShapeTree::Group(children))
323 }
324 }
325 "sGrid" => {
326 let src_id = node
327 .connected_node("Input")
328 .or_else(|| node.connected_node("Input1"))
329 .and_then(|s| comp.find_node(s))?;
330 let cells_x = comp.eval_number(node, "CellsX", time, 3.0, expr).round().clamp(1.0, 256.0) as usize;
331 let cells_y = comp.eval_number(node, "CellsY", time, 3.0, expr).round().clamp(1.0, 256.0) as usize;
332 let x_off = comp.eval_number(node, "XOffset", time, 0.2, expr) as f32;
333 let y_off = comp.eval_number(node, "YOffset", time, 0.2, expr) as f32;
334 let mut children = Vec::with_capacity(cells_x.saturating_mul(cells_y));
335 for iy in 0..cells_y {
336 let ty = (iy as f32 - (cells_y as f32 - 1.0) * 0.5) * y_off;
337 for ix in 0..cells_x {
338 let tx = (ix as f32 - (cells_x as f32 - 1.0) * 0.5) * x_off;
339 let cell_xf = parent_xform.mul(Affine2D::translate(tx, ty));
340 if let Some(tree) = collect_shape_tree(
341 comp,
342 src_id,
343 time,
344 expr,
345 cell_xf,
346 outline_override,
347 depth + 1,
348 ) {
349 children.push(tree);
350 }
351 }
352 }
353 if children.is_empty() {
354 None
355 } else {
356 Some(ShapeTree::Group(children))
357 }
358 }
359 "sOutline" => {
360 let src_id = node
361 .connected_node("Input")
362 .or_else(|| node.connected_node("Input1"))
363 .and_then(|s| comp.find_node(s))?;
364 let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr).abs() as f32;
365 let join = comp.eval_number(node, "JoinStyle", time, 2.0, expr).round().clamp(0.0, 2.0) as u8;
366 let cap = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8;
367 collect_shape_tree(comp, src_id, time, expr, parent_xform, Some((thickness, join, cap)), depth + 1)
368 }
369 "sBoolean" => {
370 let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32;
371 let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32;
372 let b_col = comp.eval_number(node, "Blue", time, 1.0, expr) as f32;
373 let a_col = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32;
374 let color = [r, g, b_col, a_col];
375 let child = |port: &str| {
376 node.connected_node(port)
377 .and_then(|s| comp.find_node(s))
378 .and_then(|id| {
379 collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1)
380 })
381 };
382 let a = child("Input1").or_else(|| child("Input"))?;
383 // Input2 absent passes Input1 through (recolored) whatever the operation; Input1 absent renders empty.
384 let (op, b) = match (parse_bool_op(node), child("Input2")) {
385 (_, None) => (ShapeBoolOp::Union, ShapeTree::Group(Vec::new())),
386 (Some(op), Some(b)) => (op, b),
387 (None, Some(_)) => return None,
388 };
389 Some(ShapeTree::Boolean {
390 op,
391 color,
392 a: Box::new(a),
393 b: Box::new(b),
394 })
395 }
396 "PipeRouter" | "Fuse.Wireless" => {
397 let src_id = node
398 .connected_node("Input")
399 .or_else(|| node.connected_node("Input1"))
400 .and_then(|s| comp.find_node(s))?;
401 collect_shape_tree(comp, src_id, time, expr, parent_xform, outline_override, depth + 1)
402 }
403 "MacroOperator" | "GroupOperator" => {
404 let out_id = node.macro_output?;
405 collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1)
406 }
407 _ => None,
408 }
409}
410
411fn build_primitive_commands(kind: ShapePrimKind, xform: Affine2D, dims: [u32; 2]) -> Vec<zeno::Command> {
412 let wf = dims[0] as f32;
413 let hf = dims[1] as f32;
414 let to_px = |local: [f32; 2]| -> zeno::Vector {
415 let wpt = xform.apply(local);
416 let px = (wpt[0] + 0.5) * wf;
417 let py = 0.5 * hf - wpt[1] * wf;
418 zeno::Vector::new(px, py)
419 };
420
421 const KAPPA: f32 = 0.55228475;
422 let mut cmds = Vec::new();
423 match kind {
424 ShapePrimKind::NGon { sides, width, height } => {
425 let n = sides.max(3);
426 let rx = width * 0.5;
427 let ry = height * 0.5;
428 if rx <= 1e-6 || ry <= 1e-6 {
429 return cmds;
430 }
431 for k in 0..n {
432 let theta = (k as f32) * std::f32::consts::TAU / (n as f32);
433 let v = to_px([rx * theta.cos(), ry * theta.sin()]);
434 if k == 0 {
435 cmds.push(zeno::Command::MoveTo(v));
436 } else {
437 cmds.push(zeno::Command::LineTo(v));
438 }
439 }
440 cmds.push(zeno::Command::Close);
441 }
442 ShapePrimKind::Rectangle { width, height, corner_radius } => {
443 let hx = width * 0.5;
444 let hy = height * 0.5;
445 if hx <= 1e-6 || hy <= 1e-6 {
446 return cmds;
447 }
448 let r = corner_radius.min(hx.min(hy));
449 if r <= 1e-5 {
450 cmds.push(zeno::Command::MoveTo(to_px([-hx, -hy])));
451 cmds.push(zeno::Command::LineTo(to_px([hx, -hy])));
452 cmds.push(zeno::Command::LineTo(to_px([hx, hy])));
453 cmds.push(zeno::Command::LineTo(to_px([-hx, hy])));
454 cmds.push(zeno::Command::Close);
455 } else {
456 let k = r * KAPPA;
457 cmds.push(zeno::Command::MoveTo(to_px([-hx + r, -hy])));
458 cmds.push(zeno::Command::LineTo(to_px([hx - r, -hy])));
459 cmds.push(zeno::Command::CurveTo(
460 to_px([hx - r + k, -hy]),
461 to_px([hx, -hy + r - k]),
462 to_px([hx, -hy + r]),
463 ));
464 cmds.push(zeno::Command::LineTo(to_px([hx, hy - r])));
465 cmds.push(zeno::Command::CurveTo(
466 to_px([hx, hy - r + k]),
467 to_px([hx - r + k, hy]),
468 to_px([hx - r, hy]),
469 ));
470 cmds.push(zeno::Command::LineTo(to_px([-hx + r, hy])));
471 cmds.push(zeno::Command::CurveTo(
472 to_px([-hx + r - k, hy]),
473 to_px([-hx, hy - r + k]),
474 to_px([-hx, hy - r]),
475 ));
476 cmds.push(zeno::Command::LineTo(to_px([-hx, -hy + r])));
477 cmds.push(zeno::Command::CurveTo(
478 to_px([-hx, -hy + r - k]),
479 to_px([-hx + r - k, -hy]),
480 to_px([-hx + r, -hy]),
481 ));
482 cmds.push(zeno::Command::Close);
483 }
484 }
485 ShapePrimKind::Ellipse { width, height } => {
486 let rx = width * 0.5;
487 let ry = height * 0.5;
488 if rx <= 1e-6 || ry <= 1e-6 {
489 return cmds;
490 }
491 let kx = rx * KAPPA;
492 let ky = ry * KAPPA;
493 cmds.push(zeno::Command::MoveTo(to_px([rx, 0.0])));
494 cmds.push(zeno::Command::CurveTo(
495 to_px([rx, ky]),
496 to_px([kx, ry]),
497 to_px([0.0, ry]),
498 ));
499 cmds.push(zeno::Command::CurveTo(
500 to_px([-kx, ry]),
501 to_px([-rx, ky]),
502 to_px([-rx, 0.0]),
503 ));
504 cmds.push(zeno::Command::CurveTo(
505 to_px([-rx, -ky]),
506 to_px([-kx, -ry]),
507 to_px([0.0, -ry]),
508 ));
509 cmds.push(zeno::Command::CurveTo(
510 to_px([kx, -ry]),
511 to_px([rx, -ky]),
512 to_px([rx, 0.0]),
513 ));
514 cmds.push(zeno::Command::Close);
515 }
516 }
517 cmds
518}
519
520fn composite_over(dst: &mut [f32], src: &[f32]) {
521 for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) {
522 let sa = s[3].clamp(0.0, 1.0);
523 if sa <= 1e-6 {
524 continue;
525 }
526 let inv = 1.0 - sa;
527 d[0] = s[0] + d[0] * inv;
528 d[1] = s[1] + d[1] * inv;
529 d[2] = s[2] + d[2] * inv;
530 d[3] = sa + d[3] * inv;
531 }
532}
533
534fn rasterize_shape_tree_f32(
535 tree: &ShapeTree,
536 dims: [u32; 2],
537 dst: &mut [f32],
538 cov_buf: &mut [u8],
539 scratch: &mut zeno::Scratch,
540) {
541 let [w, h] = dims;
542 match tree {
543 ShapeTree::Primitive {
544 kind,
545 xform,
546 color,
547 solid,
548 border_width,
549 join_style,
550 cap_style,
551 } => {
552 let cmds = build_primitive_commands(*kind, *xform, dims);
553 if cmds.is_empty() {
554 return;
555 }
556 cov_buf.fill(0);
557 let style = if *solid {
558 zeno::Style::Fill(zeno::Fill::NonZero)
559 } else {
560 let stroke_px = (*border_width * xform.avg_scale() * (w as f32)).max(0.5);
561 let join = match *join_style {
562 0 => zeno::Join::Bevel,
563 1 => zeno::Join::Round,
564 _ => zeno::Join::Miter,
565 };
566 let cap = match *cap_style {
567 1 => zeno::Cap::Round,
568 2 => zeno::Cap::Square,
569 _ => zeno::Cap::Butt,
570 };
571 let mut st = zeno::Stroke::new(stroke_px);
572 st.join(join).cap(cap);
573 zeno::Style::Stroke(st)
574 };
575 let _ = zeno::Mask::with_scratch(&cmds, scratch)
576 .style(style)
577 .size(w, h)
578 .origin(zeno::Origin::TopLeft)
579 .render_into(cov_buf, None);
580
581 let ca = color[3].clamp(0.0, 1.0);
582 if ca <= 1e-6 {
583 return;
584 }
585 for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) {
586 if cov == 0 {
587 continue;
588 }
589 let sa = (cov as f32 / 255.0) * ca;
590 let inv = 1.0 - sa;
591 px[0] = color[0] * sa + px[0] * inv;
592 px[1] = color[1] * sa + px[1] * inv;
593 px[2] = color[2] * sa + px[2] * inv;
594 px[3] = sa + px[3] * inv;
595 }
596 }
597 ShapeTree::Group(children) => {
598 for ch in children {
599 rasterize_shape_tree_f32(ch, dims, dst, cov_buf, scratch);
600 }
601 }
602 ShapeTree::Boolean { op, color, a, b } => {
603 let len = dst.len();
604 let mut buf_a = vec![0.0f32; len];
605 let mut buf_b = vec![0.0f32; len];
606 rasterize_shape_tree_f32(a, dims, &mut buf_a, cov_buf, scratch);
607 rasterize_shape_tree_f32(b, dims, &mut buf_b, cov_buf, scratch);
608 let mut comb = vec![0.0f32; len];
609 let ca = color[3].clamp(0.0, 1.0);
610 for ((ca_p, cb_p), out_p) in buf_a
611 .chunks_exact(4)
612 .zip(buf_b.chunks_exact(4))
613 .zip(comb.chunks_exact_mut(4))
614 {
615 let aa = ca_p[3].clamp(0.0, 1.0);
616 let ba = cb_p[3].clamp(0.0, 1.0);
617 let oa = match op {
618 ShapeBoolOp::Union => (aa + ba - aa * ba).clamp(0.0, 1.0),
619 ShapeBoolOp::Intersect => (aa * ba).clamp(0.0, 1.0),
620 ShapeBoolOp::Subtract => (aa * (1.0 - ba)).clamp(0.0, 1.0),
621 ShapeBoolOp::Xor => (aa * (1.0 - ba) + ba * (1.0 - aa)).clamp(0.0, 1.0),
622 };
623 let sa = oa * ca;
624 out_p[0] = color[0] * sa;
625 out_p[1] = color[1] * sa;
626 out_p[2] = color[2] * sa;
627 out_p[3] = sa;
628 }
629 composite_over(dst, &comb);
630 }
631 }
632}
633
634fn rasterize_shape_tree_rgba8(tree: Option<&ShapeTree>, dims: [u32; 2], blend: f32) -> Vec<u8> {
635 let px_count = (dims[0] as usize) * (dims[1] as usize);
636 let mut out = vec![0u8; px_count * 4];
637 let Some(tree) = tree else {
638 return out;
639 };
640 let b = blend.clamp(0.0, 1.0);
641 if b <= 1e-6 {
642 return out;
643 }
644 let mut accum = vec![0.0f32; px_count * 4];
645 let mut cov_buf = vec![0u8; px_count];
646 let mut scratch = zeno::Scratch::new();
647 rasterize_shape_tree_f32(tree, dims, &mut accum, &mut cov_buf, &mut scratch);
648 for (dst_px, src_px) in out.chunks_exact_mut(4).zip(accum.chunks_exact(4)) {
649 dst_px[0] = (src_px[0] * b * 255.0).round().clamp(0.0, 255.0) as u8;
650 dst_px[1] = (src_px[1] * b * 255.0).round().clamp(0.0, 255.0) as u8;
651 dst_px[2] = (src_px[2] * b * 255.0).round().clamp(0.0, 255.0) as u8;
652 dst_px[3] = (src_px[3] * b * 255.0).round().clamp(0.0, 255.0) as u8;
653 }
654 out
655}
656
657impl Engine {
658 #[allow(clippy::too_many_arguments)]
659 pub(super) fn eval_drip(
660 &mut self,
661 comp: &Comp,
662 node: &Node,
663 time: f64,
664 frame_i: i64,
665 enc: &mut wgpu::CommandEncoder,
666 visiting: &mut HashSet<(NodeId, i64)>,
667 stats: &mut EvalStats,
668 ) -> CachedTexture {
669 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
670 return self.dummy.clone();
671 };
672 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
673 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
674 let amp = comp.eval_number(node, "Amplitude", time, 0.1, &self.expr) as f32;
675 if blend <= 1e-6 || amp.abs() <= 1e-7 {
676 return src;
677 }
678 let src = self.crop_to_canvas(enc, src);
679 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
680 let freq = comp.eval_number(node, "Frequency", time, 10.0, &self.expr) as f32;
681 let aspect = comp.eval_number(node, "Aspect", time, 1.0, &self.expr).max(1e-4) as f32;
682 let phase = comp.eval_number(node, "Phase", time, 0.0, &self.expr) as f32;
683 let dampening = comp.eval_number(node, "Dampening", time, 0.0, &self.expr).max(0.0) as f32;
684 let shape = comp.eval_number(node, "Shape", time, 0.0, &self.expr).round() as f32;
685 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
686 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
687
688 let mut u = UniformParams::default();
689 u.p[0] = [center[0] as f32, center[1] as f32, 0.0, amp];
690 u.p[1] = [freq, aspect, phase, dampening];
691 u.p[2] = [shape, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
692
693 let key = self.make_key(
694 node,
695 "Drip",
696 src.size,
697 &[src.content_hash, mask_hash],
698 bytemuck::cast_slice(&u.p[..3]),
699 );
700 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
701 stats.cache_hits += 1;
702 return hit;
703 }
704 stats.cache_misses += 1;
705 stats.nodes_evaluated += 1;
706 let dst = self.alloc_tex_like(&src, src.depth, key);
707 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
708 self.dispatch_op(enc, ShaderOp::Drip, &src.view, &self.dummy.view, mv, &dst, &u);
709 self.cache.insert(key, dst.clone(), node.id, frame_i);
710 dst
711 }
712
713 #[allow(clippy::too_many_arguments)]
714 pub(super) fn eval_dent(
715 &mut self,
716 comp: &Comp,
717 node: &Node,
718 time: f64,
719 frame_i: i64,
720 enc: &mut wgpu::CommandEncoder,
721 visiting: &mut HashSet<(NodeId, i64)>,
722 stats: &mut EvalStats,
723 ) -> CachedTexture {
724 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
725 return self.dummy.clone();
726 };
727 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
728 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
729 let strength = comp.eval_number(node, "Strength", time, 0.5, &self.expr) as f32;
730 if blend <= 1e-6 || strength.abs() <= 1e-6 {
731 return src;
732 }
733 let src = self.crop_to_canvas(enc, src);
734 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
735 let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32;
736 let dent_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as f32;
737 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
738 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
739
740 let mut u = UniformParams::default();
741 u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, strength];
742 u.p[1] = [dent_type, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
743
744 let key = self.make_key(
745 node,
746 "Dent",
747 src.size,
748 &[src.content_hash, mask_hash],
749 bytemuck::cast_slice(&u.p[..2]),
750 );
751 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
752 stats.cache_hits += 1;
753 return hit;
754 }
755 stats.cache_misses += 1;
756 stats.nodes_evaluated += 1;
757 let dst = self.alloc_tex_like(&src, src.depth, key);
758 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
759 self.dispatch_op(enc, ShaderOp::Dent, &src.view, &self.dummy.view, mv, &dst, &u);
760 self.cache.insert(key, dst.clone(), node.id, frame_i);
761 dst
762 }
763
764 #[allow(clippy::too_many_arguments)]
765 pub(super) fn eval_s_render(
766 &mut self,
767 comp: &Comp,
768 node: &Node,
769 time: f64,
770 frame_i: i64,
771 comp_dims: [u32; 2],
772 enc: &mut wgpu::CommandEncoder,
773 visiting: &mut HashSet<(NodeId, i64)>,
774 stats: &mut EvalStats,
775 ) -> CachedTexture {
776 let w = comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32;
777 let h = comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32;
778 let dims = if w > 1 && h > 1 { self.scaled_dims(w, h) } else { comp_dims };
779 let dst_depth = self.node_depth(comp, node, time, None);
780 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
781
782 let shape_tree = node
783 .connected_node("Input")
784 .and_then(|s| comp.find_node(s))
785 .and_then(|src_id| {
786 collect_shape_tree(comp, src_id, time, &self.expr, Affine2D::identity(), None, 0)
787 });
788
789 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats);
790 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
791
792 let mut h_key = DefaultHasher::new();
793 self.cache.gpu_salt.hash(&mut h_key);
794 self.hiq.hash(&mut h_key);
795 self.cache.node_salt(node.id).hash(&mut h_key);
796 "sRender".hash(&mut h_key);
797 dims.hash(&mut h_key);
798 dst_depth.hash(&mut h_key);
799 blend.to_bits().hash(&mut h_key);
800 mask_hash.hash(&mut h_key);
801 mask_inv.hash(&mut h_key);
802 if let Some(ref tree) = shape_tree {
803 1u8.hash(&mut h_key);
804 tree.hash_into(&mut h_key);
805 } else {
806 0u8.hash(&mut h_key);
807 }
808 let key = h_key.finish();
809
810 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
811 stats.cache_hits += 1;
812 return hit;
813 }
814 stats.cache_misses += 1;
815 stats.nodes_evaluated += 1;
816
817 let rgba = rasterize_shape_tree_rgba8(shape_tree.as_ref(), dims, blend);
818 let needs_post = dst_depth != BitDepth::Int8 || mask.is_some();
819 let base_tex = create_texture(&self.device, dims, if needs_post { 0 } else { key });
820 self.queue.write_texture(
821 base_tex.texture.as_image_copy(),
822 &rgba,
823 wgpu::TexelCopyBufferLayout {
824 offset: 0,
825 bytes_per_row: Some(dims[0] * 4),
826 rows_per_image: Some(dims[1]),
827 },
828 wgpu::Extent3d {
829 width: dims[0],
830 height: dims[1],
831 depth_or_array_layers: 1,
832 },
833 );
834
835 let mut out = if dst_depth != BitDepth::Int8 {
836 let promoted = self.alloc_tex(dims, dst_depth, if mask.is_some() { 0 } else { key });
837 let u = UniformParams::default();
838 self.dispatch_op(
839 enc,
840 ShaderOp::ChangeDepth,
841 &base_tex.view,
842 &self.dummy.view,
843 &self.dummy.view,
844 &promoted,
845 &u,
846 );
847 promoted
848 } else {
849 base_tex
850 };
851
852 if let Some(ref mtex) = mask {
853 let masked = self.alloc_tex(dims, out.depth, key);
854 let mut u = UniformParams::default();
855 u.p[0] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
856 self.dispatch_op(
857 enc,
858 ShaderOp::MaskApply,
859 &out.view,
860 &self.dummy.view,
861 &mtex.view,
862 &masked,
863 &u,
864 );
865 out = masked;
866 }
867
868 self.cache.insert(key, out.clone(), node.id, frame_i);
869 out
870 }
871
872 #[allow(clippy::too_many_arguments)]
873 pub(super) fn eval_perspective_positioner(
874 &mut self,
875 comp: &Comp,
876 node: &Node,
877 time: f64,
878 frame_i: i64,
879 enc: &mut wgpu::CommandEncoder,
880 visiting: &mut HashSet<(NodeId, i64)>,
881 stats: &mut EvalStats,
882 ) -> CachedTexture {
883 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
884 return self.dummy.clone();
885 };
886 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
887 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
888 if blend <= 1e-6 {
889 return src;
890 }
891 let src = self.crop_to_canvas(enc, src);
892 let bl = comp.eval_point(node, "BottomLeft", time, [0.0, 0.0], &self.expr);
893 let br = comp.eval_point(node, "BottomRight", time, [1.0, 0.0], &self.expr);
894 let tr = comp.eval_point(node, "TopRight", time, [1.0, 1.0], &self.expr);
895 let tl = comp.eval_point(node, "TopLeft", time, [0.0, 1.0], &self.expr);
896 let mapping_type = comp.eval_number(node, "MappingType", time, 0.0, &self.expr).round() as i32;
897 let h_fwd = quad_forward_homography(bl, br, tr, tl);
898 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
899 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
900
901 let mut u = UniformParams::default();
902 u.p[0] = [bl[0] as f32, bl[1] as f32, br[0] as f32, br[1] as f32];
903 u.p[1] = [tr[0] as f32, tr[1] as f32, tl[0] as f32, tl[1] as f32];
904 u.p[2] = [h_fwd[0], h_fwd[1], h_fwd[2], h_fwd[3]];
905 u.p[3] = [h_fwd[4], h_fwd[5], h_fwd[6], h_fwd[7]];
906 u.p[4] = [
907 h_fwd[8],
908 if mapping_type == 1 { 1.0 } else { 0.0 },
909 blend,
910 if mask.is_some() { 1.0 } else { 0.0 },
911 ];
912 u.p[5] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
913
914 let key = self.make_key(
915 node,
916 "PerspectivePositioner",
917 src.size,
918 &[src.content_hash, mask_hash],
919 bytemuck::cast_slice(&u.p[..6]),
920 );
921 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
922 stats.cache_hits += 1;
923 return hit;
924 }
925 stats.cache_misses += 1;
926 stats.nodes_evaluated += 1;
927 let dst = self.alloc_tex_like(&src, src.depth, key);
928 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
929 self.dispatch_op(enc, ShaderOp::PerspectivePos, &src.view, &self.dummy.view, mv, &dst, &u);
930 self.cache.insert(key, dst.clone(), node.id, frame_i);
931 dst
932 }
933
934 #[allow(clippy::too_many_arguments)]
935 pub(super) fn eval_day_sky(
936 &mut self,
937 comp: &Comp,
938 node: &Node,
939 time: f64,
940 frame_i: i64,
941 comp_dims: [u32; 2],
942 enc: &mut wgpu::CommandEncoder,
943 visiting: &mut HashSet<(NodeId, i64)>,
944 stats: &mut EvalStats,
945 ) -> CachedTexture {
946 let use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5;
947 let w = if use_ff {
948 comp.width
949 } else {
950 comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32
951 };
952 let h = if use_ff {
953 comp.height
954 } else {
955 comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32
956 };
957 let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) };
958 let dst_depth = self.node_depth(comp, node, time, None);
959 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
960
961 let lat_deg = comp.eval_number(node, "Latitude", time, 43.65, &self.expr);
962 let lon_deg = comp.eval_number(node, "Longitude", time, -79.38, &self.expr);
963 let month = parse_month_index(node, comp, time, &self.expr);
964 let day = node
965 .static_str("Day")
966 .and_then(|s| s.parse::<f64>().ok())
967 .unwrap_or_else(|| comp.eval_number(node, "Day", time, 1.0, &self.expr));
968 let hour = comp.eval_number(node, "Time", time, 12.0, &self.expr);
969 let turbidity_in = comp.eval_number(node, "Turbidity", time, 0.0, &self.expr).max(0.0);
970 let exposure = comp.eval_number(node, "Exposure", time, 0.72, &self.expr).max(0.0);
971 let hb = comp.eval_number(node, "Horizon.Brightness", time, 1.0, &self.expr).max(0.0);
972 let hl = comp.eval_number(node, "Horizon.Luminance", time, 1.0, &self.expr).max(0.0);
973 let ci = comp.eval_number(node, "Circumsolar.Intensity", time, 1.0, &self.expr).max(0.0);
974 let cw = comp.eval_number(node, "Circumsolar.Width", time, 1.0, &self.expr).max(0.0);
975 let bs = comp.eval_number(node, "BackscatteredLight", time, 1.0, &self.expr).max(0.0);
976
977 let (sun_dir, ts) = solar_direction(lat_deg, lon_deg, month, day, hour);
978 // Calibrated to Fusion 21.1 DaySky: Turbidity in [0,1] maps to T = 1.9 + 4.0 * turb
979 let t_preetham = 1.9 + turbidity_in * 4.0;
980 let (xz, yz, _yz_lum) = preetham_zenith_xyy(t_preetham, ts);
981 let c_y0 = [
982 0.1787 * t_preetham - 1.4630,
983 (-0.3554 * t_preetham + 0.4275) * 1.20,
984 -0.0227 * t_preetham + 5.3251,
985 0.1206 * t_preetham - 2.5771,
986 -0.0670 * t_preetham + 0.3703,
987 ];
988 let c_x0 = [
989 -0.0193 * t_preetham - 0.2592,
990 -0.0665 * t_preetham + 0.0008,
991 -0.0004 * t_preetham + 0.2125,
992 -0.0641 * t_preetham - 0.8989,
993 -0.0033 * t_preetham + 0.0452,
994 ];
995 let c_y_c0 = [
996 -0.0167 * t_preetham - 0.2608,
997 -0.0950 * t_preetham + 0.0092,
998 -0.0079 * t_preetham + 0.2102,
999 -0.0441 * t_preetham - 1.6537,
1000 -0.0109 * t_preetham + 0.0529,
1001 ];
1002
1003 let scale_perez = |base: [f64; 5]| -> [f64; 5] {
1004 let a = if hb <= 1e-4 || hl <= 1e-4 { 0.0 } else { base[0] * hb };
1005 let b = base[1] / hl.max(1e-3);
1006 let c = if cw <= 1e-4 { 0.0 } else { base[2] * ci };
1007 let d = base[3] * cw;
1008 let e = base[4] * bs;
1009 [a, b, c, d, e]
1010 };
1011 let c_y = scale_perez(c_y0);
1012 let c_x = scale_perez(c_x0);
1013 let c_yc = scale_perez(c_y_c0);
1014
1015 // Log-average Perez luminance normalization: geom_mean(Y_hdr) == Exposure
1016 const N_TH: usize = 32;
1017 const N_PH: usize = 32;
1018 let mut sum_log = 0.0_f64;
1019 for iy in 0..N_TH {
1020 let th = (iy as f64 + 0.5) / N_TH as f64 * std::f64::consts::FRAC_PI_2;
1021 let (st, ct) = th.sin_cos();
1022 for ix in 0..N_PH {
1023 let ph = (ix as f64 + 0.5) / N_PH as f64 * std::f64::consts::TAU;
1024 let (sp, cp) = ph.sin_cos();
1025 let cos_g = (st * cp * sun_dir[0] + st * sp * sun_dir[1] + ct * sun_dir[2]).clamp(-1.0, 1.0);
1026 let fy = eval_perez(th, cos_g.acos(), c_y).max(1e-5);
1027 sum_log += fy.ln();
1028 }
1029 }
1030 let geomean_fy = (sum_log / (N_TH * N_PH) as f64).exp().max(1e-5);
1031 let lum_gain = (exposure / geomean_fy) as f32;
1032 let f_y0 = 1.0_f64;
1033 let f_x0 = eval_perez(0.0, ts, c_x);
1034 let f_yc0 = eval_perez(0.0, ts, c_yc);
1035 let yz_scaled = lum_gain;
1036
1037 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats);
1038 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1039
1040 let mut u = UniformParams::default();
1041 u.p[0] = [sun_dir[0] as f32, sun_dir[1] as f32, sun_dir[2] as f32, yz_scaled];
1042 u.p[1] = [xz as f32, yz as f32, f_y0 as f32, f_x0 as f32];
1043 u.p[2] = [f_yc0 as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
1044 u.p[3] = [c_y[0] as f32, c_y[1] as f32, c_y[2] as f32, c_y[3] as f32];
1045 u.p[4] = [c_y[4] as f32, c_x[0] as f32, c_x[1] as f32, c_x[2] as f32];
1046 u.p[5] = [c_x[3] as f32, c_x[4] as f32, c_yc[0] as f32, c_yc[1] as f32];
1047 u.p[6] = [c_yc[2] as f32, c_yc[3] as f32, c_yc[4] as f32, 0.0];
1048
1049 let key = self.make_key(
1050 node,
1051 "DaySky",
1052 size,
1053 &[mask_hash, dst_depth as u64],
1054 bytemuck::cast_slice(&u.p[..7]),
1055 );
1056 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1057 stats.cache_hits += 1;
1058 return hit;
1059 }
1060 stats.cache_misses += 1;
1061 stats.nodes_evaluated += 1;
1062 let dst = self.alloc_tex(size, dst_depth, key);
1063 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1064 self.dispatch_op(enc, ShaderOp::DaySky, &self.dummy.view, &self.dummy.view, mv, &dst, &u);
1065 self.cache.insert(key, dst.clone(), node.id, frame_i);
1066 dst
1067 }
1068
1069 #[allow(clippy::too_many_arguments)]
1070 pub(super) fn eval_grid_warp(
1071 &mut self,
1072 comp: &Comp,
1073 node: &Node,
1074 time: f64,
1075 frame_i: i64,
1076 enc: &mut wgpu::CommandEncoder,
1077 visiting: &mut HashSet<(NodeId, i64)>,
1078 stats: &mut EvalStats,
1079 ) -> CachedTexture {
1080 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
1081 return self.dummy.clone();
1082 };
1083 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
1084 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
1085 if blend <= 1e-6 {
1086 return src;
1087 }
1088 let src_mesh = comp.eval_grid_mesh(node, "SrcGridChange", time);
1089 let dst_mesh = comp.eval_grid_mesh(node, "DstGridChange", time);
1090 let (Some(src_mesh), Some(dst_mesh)) = (src_mesh, dst_mesh) else {
1091 return src;
1092 };
1093 if src_mesh == dst_mesh {
1094 return src;
1095 }
1096 let src = self.crop_to_canvas(enc, src);
1097 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
1098 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
1099
1100 let mut u = UniformParams::default();
1101 u.p[0] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0];
1102
1103 let mut mesh_params: Vec<f32> = Vec::with_capacity(4 + (src_mesh.points.len() + dst_mesh.points.len()) * 10);
1104 mesh_params.extend_from_slice(&[blend, src_mesh.cols as f32, src_mesh.rows as f32, dst_mesh.cols as f32]);
1105 for m in [&src_mesh, &dst_mesh] {
1106 for p in &m.points {
1107 mesh_params.extend_from_slice(&[
1108 p.x as f32,
1109 p.y as f32,
1110 p.l_cx.unwrap_or(f32::NAN as f64) as f32,
1111 p.l_cy.unwrap_or(0.0) as f32,
1112 p.r_cx.unwrap_or(f32::NAN as f64) as f32,
1113 p.r_cy.unwrap_or(0.0) as f32,
1114 p.t_cx.unwrap_or(0.0) as f32,
1115 p.t_cy.unwrap_or(f32::NAN as f64) as f32,
1116 p.b_cx.unwrap_or(0.0) as f32,
1117 p.b_cy.unwrap_or(f32::NAN as f64) as f32,
1118 ]);
1119 }
1120 }
1121
1122 let key = self.make_key(node, "GridWarp", src.size, &[src.content_hash, mask_hash], &mesh_params);
1123 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
1124 stats.cache_hits += 1;
1125 return hit;
1126 }
1127 stats.cache_misses += 1;
1128 stats.nodes_evaluated += 1;
1129
1130 let uv_f16 = rasterize_grid_warp_uv_f16(&src_mesh, &dst_mesh, src.size);
1131 let uv_tex = create_texture_dod_fmt(
1132 &self.device,
1133 src.size,
1134 [0, 0],
1135 src.size,
1136 BitDepth::Float16,
1137 wgpu::TextureFormat::Rgba16Float,
1138 0,
1139 );
1140 self.queue.write_texture(
1141 uv_tex.texture.as_image_copy(),
1142 bytemuck::cast_slice(&uv_f16),
1143 wgpu::TexelCopyBufferLayout {
1144 offset: 0,
1145 bytes_per_row: Some(src.size[0] * 8),
1146 rows_per_image: Some(src.size[1]),
1147 },
1148 wgpu::Extent3d {
1149 width: src.size[0],
1150 height: src.size[1],
1151 depth_or_array_layers: 1,
1152 },
1153 );
1154
1155 let dst = self.alloc_tex_like(&src, src.depth, key);
1156 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
1157 self.dispatch_op(enc, ShaderOp::GridWarp, &src.view, &uv_tex.view, mv, &dst, &u);
1158 self.cache.insert(key, dst.clone(), node.id, frame_i);
1159 dst
1160 }
1161}
1162
1163fn quad_forward_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> [f32; 9] {
1164 let dx1 = br[0] - tr[0];
1165 let dy1 = br[1] - tr[1];
1166 let dx2 = tl[0] - tr[0];
1167 let dy2 = tl[1] - tr[1];
1168 let sx = bl[0] - br[0] + tr[0] - tl[0];
1169 let sy = bl[1] - br[1] + tr[1] - tl[1];
1170 let denom = dx1 * dy2 - dx2 * dy1;
1171 if denom.abs() < 1e-10 {
1172 return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
1173 }
1174 let g = (sx * dy2 - sy * dx2) / denom;
1175 let h = (dx1 * sy - dy1 * sx) / denom;
1176 let a = br[0] - bl[0] + g * br[0];
1177 let b = tl[0] - bl[0] + h * tl[0];
1178 let c = bl[0];
1179 let d = br[1] - bl[1] + g * br[1];
1180 let e = tl[1] - bl[1] + h * tl[1];
1181 let f = bl[1];
1182 [a as f32, b as f32, c as f32, d as f32, e as f32, f as f32, g as f32, h as f32, 1.0]
1183}
1184
1185fn parse_month_index(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> usize {
1186 if let Some(m) = node.static_str("Month") {
1187 let low = m.to_ascii_lowercase();
1188 let names = [
1189 "january", "february", "march", "april", "may", "june",
1190 "july", "august", "september", "october", "november", "december",
1191 ];
1192 if let Some(idx) = names.iter().position(|&n| low.starts_with(&n[..3])) {
1193 return idx + 1;
1194 }
1195 if let Ok(v) = m.parse::<usize>() {
1196 return v.clamp(1, 12);
1197 }
1198 }
1199 (comp.eval_number(node, "Month", time, 0.0, expr).round() as usize + 1).clamp(1, 12)
1200}
1201
1202fn solar_direction(lat_deg: f64, lon_deg: f64, month: usize, day: f64, hour: f64) -> ([f64; 3], f64) {
1203 const CUM_DAYS: [i32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
1204 let doy = CUM_DAYS[month.saturating_sub(1).min(11)] as f64 + day;
1205 let b = 2.0 * std::f64::consts::PI * (doy - 81.0) / 365.0;
1206 let eot_min = 9.87 * (2.0 * b).sin() - 7.53 * b.cos() - 1.5 * b.sin();
1207 let decl = 23.44_f64.to_radians() * ((2.0 * std::f64::consts::PI / 365.0) * (doy - 81.0)).sin();
1208 let std_meridian = (lon_deg / 15.0).round() * 15.0;
1209 let solar_hour = hour + (lon_deg - std_meridian) / 15.0 + eot_min / 60.0;
1210 let hour_angle = ((solar_hour - 12.0) * 15.0).to_radians();
1211 let lat = lat_deg.to_radians();
1212 let sin_alt = (lat.sin() * decl.sin() + lat.cos() * decl.cos() * hour_angle.cos()).clamp(-1.0, 1.0);
1213 let ts = (std::f64::consts::FRAC_PI_2 - sin_alt.asin()).max(0.0);
1214 // Azimuth measured from South (0=South, pi/2=East morning, pi=North, 3*pi/2=West afternoon)
1215 let cos_az_south = (-(decl.sin() * lat.cos() - decl.cos() * lat.sin() * hour_angle.cos())
1216 / ts.sin().max(1e-5))
1217 .clamp(-1.0, 1.0);
1218 let mut phi_s = cos_az_south.acos();
1219 if hour_angle > 0.0 {
1220 phi_s = 2.0 * std::f64::consts::PI - phi_s;
1221 }
1222 let dir = [ts.sin() * phi_s.cos(), ts.sin() * phi_s.sin(), ts.cos()];
1223 (dir, ts)
1224}
1225
1226fn preetham_zenith_xyy(t: f64, ts: f64) -> (f64, f64, f64) {
1227 let t2 = t * t;
1228 let ts2 = ts * ts;
1229 let ts3 = ts2 * ts;
1230 let chi = (4.0 / 9.0 - t / 120.0) * (std::f64::consts::PI - 2.0 * ts);
1231 let yz_lum = ((4.0453 * t - 4.9710) * chi.tan() - 0.2155 * t + 2.4192).max(0.05);
1232 let xz = (0.00166 * ts3 - 0.00375 * ts2 + 0.00209 * ts) * t2
1233 + (-0.02903 * ts3 + 0.06377 * ts2 - 0.03202 * ts + 0.00394) * t
1234 + (0.11693 * ts3 - 0.21196 * ts2 + 0.06052 * ts + 0.25886);
1235 let yz = (0.00275 * ts3 - 0.00610 * ts2 + 0.00317 * ts) * t2
1236 + (-0.04214 * ts3 + 0.08970 * ts2 - 0.04153 * ts + 0.00516) * t
1237 + (0.15346 * ts3 - 0.26756 * ts2 + 0.06670 * ts + 0.26688);
1238 (xz, yz, yz_lum)
1239}
1240
1241fn eval_perez(theta: f64, gamma: f64, c: [f64; 5]) -> f64 {
1242 let ct = theta.cos().max(0.02);
1243 let cg = gamma.cos();
1244 (1.0 + c[0] * (c[1] / ct).exp()) * (1.0 + c[2] * (c[3] * gamma).exp() + c[4] * cg * cg)
1245}
1246
1247#[derive(Clone, Copy)]
1248struct CoonsPt {
1249 p: [f32; 2],
1250 l: [f32; 2],
1251 r: [f32; 2],
1252 t: [f32; 2],
1253 b: [f32; 2],
1254}
1255
1256fn mesh_coons_cells(mesh: &model::comp::GridMesh) -> Vec<[CoonsPt; 4]> {
1257 let cols = mesh.cols;
1258 let rows = mesh.rows;
1259 let dc = (mesh.delta_c as f32) / 3.0;
1260 let dr = (mesh.delta_r as f32) / 3.0;
1261 let pts: Vec<CoonsPt> = mesh
1262 .points
1263 .iter()
1264 .map(|mp| {
1265 let p = [mp.x as f32, mp.y as f32];
1266 let l = [p[0] + mp.l_cx.map_or(-dc, |v| v as f32), p[1] + mp.l_cy.unwrap_or(0.0) as f32];
1267 let r = [p[0] + mp.r_cx.map_or(dc, |v| v as f32), p[1] + mp.r_cy.unwrap_or(0.0) as f32];
1268 let t = [p[0] + mp.t_cx.unwrap_or(0.0) as f32, p[1] + mp.t_cy.map_or(-dr, |v| v as f32)];
1269 let b = [p[0] + mp.b_cx.unwrap_or(0.0) as f32, p[1] + mp.b_cy.map_or(dr, |v| v as f32)];
1270 CoonsPt { p, l, r, t, b }
1271 })
1272 .collect();
1273 let mut cells = Vec::with_capacity((cols - 1) * (rows - 1));
1274 for r in 0..(rows - 1) {
1275 for c in 0..(cols - 1) {
1276 cells.push([
1277 pts[r * cols + c],
1278 pts[r * cols + c + 1],
1279 pts[(r + 1) * cols + c],
1280 pts[(r + 1) * cols + c + 1],
1281 ]);
1282 }
1283 }
1284 cells
1285}
1286
1287fn bez3_2d(p0: [f32; 2], p1: [f32; 2], p2: [f32; 2], p3: [f32; 2], t: f32) -> [f32; 2] {
1288 let u = 1.0 - t;
1289 let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
1290 [
1291 w0 * p0[0] + w1 * p1[0] + w2 * p2[0] + w3 * p3[0],
1292 w0 * p0[1] + w1 * p1[1] + w2 * p2[1] + w3 * p3[1],
1293 ]
1294}
1295
1296fn eval_coons_cell(cell: &[CoonsPt; 4], u: f32, v: f32) -> [f32; 2] {
1297 let [p00, p10, p01, p11] = *cell;
1298 let bot = bez3_2d(p00.p, p00.r, p10.l, p10.p, u);
1299 let top = bez3_2d(p01.p, p01.r, p11.l, p11.p, u);
1300 let lft = bez3_2d(p00.p, p00.b, p01.t, p01.p, v);
1301 let rgt = bez3_2d(p10.p, p10.b, p11.t, p11.p, v);
1302 let bi0 = (1.0 - u) * (1.0 - v) * p00.p[0] + u * (1.0 - v) * p10.p[0] + (1.0 - u) * v * p01.p[0] + u * v * p11.p[0];
1303 let bi1 = (1.0 - u) * (1.0 - v) * p00.p[1] + u * (1.0 - v) * p10.p[1] + (1.0 - u) * v * p01.p[1] + u * v * p11.p[1];
1304 [
1305 (1.0 - v) * bot[0] + v * top[0] + (1.0 - u) * lft[0] + u * rgt[0] - bi0,
1306 (1.0 - v) * bot[1] + v * top[1] + (1.0 - u) * lft[1] + u * rgt[1] - bi1,
1307 ]
1308}
1309
1310fn rasterize_grid_warp_uv_f16(
1311 src_mesh: &model::comp::GridMesh,
1312 dst_mesh: &model::comp::GridMesh,
1313 dims: [u32; 2],
1314) -> Vec<u16> {
1315 let [w, h] = dims;
1316 let (wf, hf) = (w as f32, h as f32);
1317 let mut uv_buf = vec![0u16; (w as usize) * (h as usize) * 4];
1318 let src_cells = mesh_coons_cells(src_mesh);
1319 let dst_cells = mesh_coons_cells(dst_mesh);
1320 let sub = 24usize;
1321 let one_f16 = crate::media::f32_to_f16_bits(1.0);
1322
1323 for (sc, dc) in src_cells.iter().zip(dst_cells.iter()) {
1324 for j in 0..sub {
1325 let (v0, v1) = (j as f32 / sub as f32, (j + 1) as f32 / sub as f32);
1326 for i in 0..sub {
1327 let (u0, u1) = (i as f32 / sub as f32, (i + 1) as f32 / sub as f32);
1328 let da = eval_coons_cell(dc, u0, v0);
1329 let db = eval_coons_cell(dc, u1, v0);
1330 let dc2 = eval_coons_cell(dc, u1, v1);
1331 let dd = eval_coons_cell(dc, u0, v1);
1332 let sa = eval_coons_cell(sc, u0, v0);
1333 let sb = eval_coons_cell(sc, u1, v0);
1334 let sc2 = eval_coons_cell(sc, u1, v1);
1335 let sd = eval_coons_cell(sc, u0, v1);
1336
1337 for ([pa, pb, pc], [qa, qb, qc]) in [([da, db, dc2], [sa, sb, sc2]), ([da, dc2, dd], [sa, sc2, sd])] {
1338 let (ax, ay) = ((pa[0] + 0.5) * wf, (0.5 - pa[1]) * hf);
1339 let (bx, by) = ((pb[0] + 0.5) * wf, (0.5 - pb[1]) * hf);
1340 let (cx, cy) = ((pc[0] + 0.5) * wf, (0.5 - pc[1]) * hf);
1341 let area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
1342 if area.abs() < 1e-6 {
1343 continue;
1344 }
1345 let inv_area = 1.0 / area;
1346 let x0 = ax.min(bx).min(cx).floor().max(0.0) as u32;
1347 let x1 = (ax.max(bx).max(cx).ceil() as u32).min(w.saturating_sub(1));
1348 let y0 = ay.min(by).min(cy).floor().max(0.0) as u32;
1349 let y1 = (ay.max(by).max(cy).ceil() as u32).min(h.saturating_sub(1));
1350 for py in y0..=y1 {
1351 let qy = py as f32 + 0.5;
1352 for px in x0..=x1 {
1353 let qx = px as f32 + 0.5;
1354 let w0 = ((bx - qx) * (cy - qy) - (by - qy) * (cx - qx)) * inv_area;
1355 let w1 = ((cx - qx) * (ay - qy) - (cy - qy) * (ax - qx)) * inv_area;
1356 let w2 = 1.0 - w0 - w1;
1357 if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 {
1358 let su = w0 * qa[0] + w1 * qb[0] + w2 * qc[0] + 0.5;
1359 let sv = w0 * qa[1] + w1 * qb[1] + w2 * qc[1] + 0.5;
1360 let idx = (py as usize * w as usize + px as usize) * 4;
1361 uv_buf[idx] = crate::media::f32_to_f16_bits(su);
1362 uv_buf[idx + 1] = crate::media::f32_to_f16_bits(sv);
1363 uv_buf[idx + 2] = one_f16;
1364 }
1365 }
1366 }
1367 }
1368 }
1369 }
1370 }
1371 uv_buf
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376 use super::*;
1377 use crate::Engine;
1378
1379 #[test]
1380 fn test_drip_concentric_ripple_displacement() {
1381 let src = r#"Composition {
1382 CurrentTime = 0,
1383 RenderRange = { 0, 1 },
1384 GlobalRange = { 0, 1 },
1385 Tools = ordered() {
1386 BG1 = Background {
1387 Inputs = {
1388 Width = Input { Value = 128, },
1389 Height = Input { Value = 128, },
1390 Type = Input { Value = FuID { "Horizontal" }, },
1391 TopLeftRed = Input { Value = 1.0, },
1392 TopLeftGreen = Input { Value = 0.0, },
1393 TopLeftBlue = Input { Value = 0.0, },
1394 TopRightRed = Input { Value = 0.0, },
1395 TopRightGreen = Input { Value = 0.0, },
1396 TopRightBlue = Input { Value = 1.0, },
1397 },
1398 },
1399 Drip1 = Drip {
1400 Inputs = {
1401 Input = Input { SourceOp = "BG1", Source = "Output", },
1402 Center = Input { Value = { 0.5, 0.5 }, },
1403 Strength = Input { Value = 1.0, },
1404 Amplitude = Input { Value = 0.12, },
1405 Frequency = Input { Value = 4.0, },
1406 Phase = Input { Value = 0.0, },
1407 Shape = Input { Value = 0, },
1408 },
1409 },
1410 },
1411 }"#;
1412 let comp = Comp::from_fusion_str(src).expect("parse Drip comp");
1413 let Ok(mut eng) = Engine::new_headless() else {
1414 return;
1415 };
1416 let bg_id = comp.find_node("BG1").unwrap();
1417 let drip_id = comp.find_node("Drip1").unwrap();
1418 let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0);
1419 let (drip_tex, stats) = eng.evaluate(&comp, drip_id, 0.0);
1420 assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes);
1421 let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg");
1422 let drip_px = eng.readback_rgba(&drip_tex).expect("readback drip");
1423
1424 let diff_sum: u64 = bg_px
1425 .iter()
1426 .zip(drip_px.iter())
1427 .map(|(&a, &b)| a.abs_diff(b) as u64)
1428 .sum();
1429 assert!(diff_sum > 10_000, "Drip should visibly displace pixels, got diff_sum={diff_sum}");
1430 }
1431
1432 #[test]
1433 fn test_dent_radial_distortion() {
1434 let src = r#"Composition {
1435 CurrentTime = 0,
1436 RenderRange = { 0, 1 },
1437 GlobalRange = { 0, 1 },
1438 Tools = ordered() {
1439 BG1 = Background {
1440 Inputs = {
1441 Width = Input { Value = 128, },
1442 Height = Input { Value = 128, },
1443 Type = Input { Value = FuID { "Horizontal" }, },
1444 TopLeftRed = Input { Value = 1.0, },
1445 TopLeftGreen = Input { Value = 0.0, },
1446 TopLeftBlue = Input { Value = 0.0, },
1447 TopRightRed = Input { Value = 0.0, },
1448 TopRightGreen = Input { Value = 1.0, },
1449 TopRightBlue = Input { Value = 0.0, },
1450 },
1451 },
1452 Dent1 = Dent {
1453 Inputs = {
1454 Input = Input { SourceOp = "BG1", Source = "Output", },
1455 Center = Input { Value = { 0.5, 0.5 }, },
1456 Size = Input { Value = 0.6, },
1457 Strength = Input { Value = 0.8, },
1458 Type = Input { Value = 0, },
1459 },
1460 },
1461 },
1462 }"#;
1463 let comp = Comp::from_fusion_str(src).expect("parse Dent comp");
1464 let Ok(mut eng) = Engine::new_headless() else {
1465 return;
1466 };
1467 let bg_id = comp.find_node("BG1").unwrap();
1468 let dent_id = comp.find_node("Dent1").unwrap();
1469 let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0);
1470 let (dent_tex, stats) = eng.evaluate(&comp, dent_id, 0.0);
1471 assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes);
1472 let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg");
1473 let dent_px = eng.readback_rgba(&dent_tex).expect("readback dent");
1474
1475 // Corners outside radius=0.3 must remain unchanged; interior must be distorted!
1476 assert_eq!(&bg_px[0..4], &dent_px[0..4], "corner pixel outside dent radius should match");
1477 let mut interior_diff = 0u64;
1478 for y in 44..84 {
1479 for x in 44..84 {
1480 let idx = (y * 128 + x) * 4;
1481 interior_diff += bg_px[idx].abs_diff(dent_px[idx]) as u64;
1482 interior_diff += bg_px[idx + 1].abs_diff(dent_px[idx + 1]) as u64;
1483 }
1484 }
1485 assert!(interior_diff > 2_000, "Dent interior should visibly distort, got {interior_diff}");
1486 }
1487
1488 #[test]
1489 fn test_s_render_ngon_transform_merge_and_boolean() {
1490 let src = r#"Composition {
1491 CurrentTime = 0,
1492 RenderRange = { 0, 1 },
1493 GlobalRange = { 0, 1 },
1494 Tools = ordered() {
1495 NGon1 = sNGon {
1496 Inputs = {
1497 Sides = Input { Value = 6, },
1498 Width = Input { Value = 0.4, },
1499 Red = Input { Value = 1.0, },
1500 Green = Input { Value = 0.0, },
1501 Blue = Input { Value = 0.0, },
1502 },
1503 },
1504 XF1 = sTransform {
1505 Inputs = {
1506 XOffset = Input { Value = -0.2, },
1507 YOffset = Input { Value = 0.0, },
1508 XSize = Input { Value = 1.0, },
1509 YSize = Input { Value = 1.0, },
1510 ZRotation = Input { Value = 15.0, },
1511 Input = Input { SourceOp = "NGon1", Source = "Output", },
1512 },
1513 },
1514 Rect1 = sRectangle {
1515 Inputs = {
1516 Width = Input { Value = 0.3, },
1517 Height = Input { Value = 0.3, },
1518 CornerRadius = Input { Value = 0.05, },
1519 Translate = Input { Value = { 0.0, 0.0 }, },
1520 ["Translate.X"] = Input { Value = 0.2, },
1521 Red = Input { Value = 0.0, },
1522 Green = Input { Value = 0.0, },
1523 Blue = Input { Value = 1.0, },
1524 },
1525 },
1526 Merge1 = sMerge {
1527 Inputs = {
1528 Input1 = Input { SourceOp = "XF1", Source = "Output", },
1529 Input2 = Input { SourceOp = "Rect1", Source = "Output", },
1530 },
1531 },
1532 Render1 = sRender {
1533 Inputs = {
1534 Width = Input { Value = 128, },
1535 Height = Input { Value = 128, },
1536 Input = Input { SourceOp = "Merge1", Source = "Output", },
1537 },
1538 },
1539 },
1540 }"#;
1541 let comp = Comp::from_fusion_str(src).expect("parse sRender comp");
1542 let Ok(mut eng) = Engine::new_headless() else {
1543 return;
1544 };
1545 let render_id = comp.find_node("Render1").unwrap();
1546 let (tex, stats) = eng.evaluate(&comp, render_id, 0.0);
1547 assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes);
1548 assert_eq!(tex.size, [128, 128]);
1549 let px = eng.readback_rgba(&tex).expect("readback sRender");
1550
1551 // Left shape center (-0.2 -> x ~ 38, y ~ 64) should be solid red
1552 let left = (64 * 128 + 38) * 4;
1553 assert!(px[left] > 240 && px[left + 2] < 10 && px[left + 3] > 240, "left={:?}", &px[left..left + 4]);
1554 // Right shape center (+0.2 -> x ~ 90, y ~ 64) should be solid blue
1555 let right = (64 * 128 + 90) * 4;
1556 assert!(px[right + 2] > 240 && px[right] < 10 && px[right + 3] > 240, "right={:?}", &px[right..right + 4]);
1557 // Top-left corner (0, 0) should be transparent
1558 assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner should be transparent");
1559 }
1560
1561 #[test]
1562 fn test_drip_shapes_and_strength_independence() {
1563 let make_comp = |strength: f64, shape: i32| {
1564 format!(
1565 r#"Composition {{
1566 CurrentTime = 0,
1567 RenderRange = {{ 0, 1 }},
1568 GlobalRange = {{ 0, 1 }},
1569 Tools = ordered() {{
1570 BG1 = Background {{
1571 Inputs = {{
1572 Width = Input {{ Value = 128, }},
1573 Height = Input {{ Value = 128, }},
1574 Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
1575 TopLeftRed = Input {{ Value = 1.0, }},
1576 TopRightBlue = Input {{ Value = 1.0, }},
1577 }},
1578 }},
1579 Drip1 = Drip {{
1580 Inputs = {{
1581 Input = Input {{ SourceOp = "BG1", Source = "Output", }},
1582 Center = Input {{ Value = {{ 0.4, 0.6 }}, }},
1583 Strength = Input {{ Value = {strength}, }},
1584 Amplitude = Input {{ Value = 0.08, }},
1585 Frequency = Input {{ Value = 4.0, }},
1586 Phase = Input {{ Value = 0.75, }},
1587 Shape = Input {{ Value = {shape}, }},
1588 }},
1589 }},
1590 }},
1591 }}"#
1592 )
1593 };
1594 let Ok(mut eng) = Engine::new_headless() else {
1595 return;
1596 };
1597 let comp_a = Comp::from_fusion_str(&make_comp(0.25, 1)).unwrap();
1598 let comp_b = Comp::from_fusion_str(&make_comp(1.0, 1)).unwrap();
1599 let (tex_a, _) = eng.evaluate(&comp_a, comp_a.find_node("Drip1").unwrap(), 0.0);
1600 let (tex_b, _) = eng.evaluate(&comp_b, comp_b.find_node("Drip1").unwrap(), 0.0);
1601 let px_a = eng.readback_rgba(&tex_a).unwrap();
1602 let px_b = eng.readback_rgba(&tex_b).unwrap();
1603 assert_eq!(px_a, px_b, "Fusion Drip ignores Strength and uses Amplitude directly");
1604
1605 // Center pixel (0.4*128=51, (1-0.6)*128=51) must remain smooth (raw_rel=0 -> disp=0)
1606 let (bg_tex, _) = eng.evaluate(&comp_a, comp_a.find_node("BG1").unwrap(), 0.0);
1607 let bg_px = eng.readback_rgba(&bg_tex).unwrap();
1608 let diff_sum: u64 = bg_px.iter().zip(px_a.iter()).map(|(&a, &b)| a.abs_diff(b) as u64).sum();
1609 assert!(diff_sum > 5_000, "Square Drip should displace pixels, got {diff_sum}");
1610 }
1611
1612 #[test]
1613 fn test_dent_type0_signed_inversion() {
1614 let src = r#"Composition {
1615 CurrentTime = 0,
1616 RenderRange = { 0, 1 },
1617 GlobalRange = { 0, 1 },
1618 Tools = ordered() {
1619 BG1 = Background {
1620 Inputs = {
1621 Width = Input { Value = 128, },
1622 Height = Input { Value = 128, },
1623 Type = Input { Value = FuID { "Horizontal" }, },
1624 TopLeftRed = Input { Value = 1.0, },
1625 TopLeftGreen = Input { Value = 0.0, },
1626 TopLeftBlue = Input { Value = 0.0, },
1627 TopRightRed = Input { Value = 0.0, },
1628 TopRightGreen = Input { Value = 1.0, },
1629 TopRightBlue = Input { Value = 0.0, },
1630 },
1631 },
1632 Dent1 = Dent {
1633 Inputs = {
1634 Input = Input { SourceOp = "BG1", Source = "Output", },
1635 Center = Input { Value = { 0.5, 0.5 }, },
1636 Size = Input { Value = 0.65, },
1637 Strength = Input { Value = 0.75, },
1638 Type = Input { Value = 0, },
1639 },
1640 },
1641 },
1642 }"#;
1643 let comp = Comp::from_fusion_str(src).unwrap();
1644 let Ok(mut eng) = Engine::new_headless() else {
1645 return;
1646 };
1647 let (tex, _) = eng.evaluate(&comp, comp.find_node("Dent1").unwrap(), 0.0);
1648 let px = eng.readback_rgba(&tex).unwrap();
1649 // Just right of center (x=72, r~0.066): new_r = r - 0.75*(0.325 - r) < 0,
1650 // so it samples the LEFT (red-dominant) side!
1651 let right_near = (64 * 128 + 72) * 4;
1652 assert!(
1653 px[right_near] > px[right_near + 1] + 40,
1654 "Dent Type=0 should invert radially near center: {:?}",
1655 &px[right_near..right_near + 4]
1656 );
1657 }
1658
1659 #[test]
1660 fn test_s_boolean_uses_own_color_and_subtract_xor() {
1661 let src = r#"Composition {
1662 CurrentTime = 0,
1663 RenderRange = { 0, 1 },
1664 GlobalRange = { 0, 1 },
1665 Tools = ordered() {
1666 NGon1 = sNGon {
1667 Inputs = {
1668 Sides = Input { Value = 5, },
1669 Width = Input { Value = 0.5, },
1670 Height = Input { Value = 0.5, },
1671 Red = Input { Value = 1.0, },
1672 Green = Input { Value = 0.0, },
1673 Blue = Input { Value = 0.0, },
1674 },
1675 },
1676 Rect1 = sRectangle {
1677 Inputs = {
1678 Width = Input { Value = 0.35, },
1679 Height = Input { Value = 0.35, },
1680 ["Translate.X"] = Input { Value = 0.18, },
1681 Red = Input { Value = 0.0, },
1682 Green = Input { Value = 1.0, },
1683 Blue = Input { Value = 0.0, },
1684 },
1685 },
1686 BoolSub = sBoolean {
1687 Inputs = {
1688 Operation = Input { Value = FuID { "Subtract" }, },
1689 Input1 = Input { SourceOp = "Rect1", Source = "Output", },
1690 Input2 = Input { SourceOp = "NGon1", Source = "Output", },
1691 },
1692 },
1693 BoolXor = sBoolean {
1694 Inputs = {
1695 Operation = Input { Value = FuID { "Xor" }, },
1696 Input1 = Input { SourceOp = "NGon1", Source = "Output", },
1697 Input2 = Input { SourceOp = "Rect1", Source = "Output", },
1698 },
1699 },
1700 RSub = sRender {
1701 Inputs = {
1702 Width = Input { Value = 128, },
1703 Height = Input { Value = 128, },
1704 Input = Input { SourceOp = "BoolSub", Source = "Output", },
1705 },
1706 },
1707 RXor = sRender {
1708 Inputs = {
1709 Width = Input { Value = 128, },
1710 Height = Input { Value = 128, },
1711 Input = Input { SourceOp = "BoolXor", Source = "Output", },
1712 },
1713 },
1714 },
1715 }"#;
1716 let comp = Comp::from_fusion_str(src).unwrap();
1717 let Ok(mut eng) = Engine::new_headless() else {
1718 return;
1719 };
1720 let (tex_sub, _) = eng.evaluate(&comp, comp.find_node("RSub").unwrap(), 0.0);
1721 let (tex_xor, _) = eng.evaluate(&comp, comp.find_node("RXor").unwrap(), 0.0);
1722 let px_sub = eng.readback_rgba(&tex_sub).unwrap();
1723 let px_xor = eng.readback_rgba(&tex_xor).unwrap();
1724
1725 // Far right of Rect (x=0.30 -> px=102, y=64): outside NGon (max x=0.25), inside Rect -> white!
1726 let rect_only = (64 * 128 + 102) * 4;
1727 assert_eq!(&px_sub[rect_only..rect_only + 4], &[255, 255, 255, 255]);
1728 assert_eq!(&px_xor[rect_only..rect_only + 4], &[255, 255, 255, 255]);
1729
1730 // Overlap region (x=0.10 -> px=77, y=64): subtracted/xored out -> transparent!
1731 let overlap = (64 * 128 + 77) * 4;
1732 assert_eq!(&px_sub[overlap..overlap + 4], &[0, 0, 0, 0]);
1733 assert_eq!(&px_xor[overlap..overlap + 4], &[0, 0, 0, 0]);
1734
1735 // Center (0,0 -> px=64, y=64): inside NGon, outside Rect (starts at 0.005) -> white in Xor!
1736 let ngon_only = (64 * 128 + 54) * 4;
1737 assert_eq!(&px_xor[ngon_only..ngon_only + 4], &[255, 255, 255, 255]);
1738 }
1739
1740 #[test]
1741 fn test_dent_sine_falls_off_linearly_from_strength_at_center() {
1742 let src = r#"Composition {
1743 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
1744 Tools = ordered() {
1745 BG1 = Background { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, },
1746 Type = Input { Value = FuID { "Horizontal" }, },
1747 TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, },
1748 TopRightRed = Input { Value = 0, }, TopRightGreen = Input { Value = 1, }, TopRightBlue = Input { Value = 0, }, TopRightAlpha = Input { Value = 1, }, }, },
1749 Dent1 = Dent { Inputs = { Input = Input { SourceOp = "BG1", Source = "Output", },
1750 Center = Input { Value = { 0.5, 0.5 }, }, Size = Input { Value = 0.5, },
1751 Strength = Input { Value = 0.5, }, Type = Input { Value = 1, }, }, },
1752 },
1753 }"#;
1754 let comp = Comp::from_fusion_str(src).unwrap();
1755 let Ok(mut eng) = Engine::new_headless() else {
1756 return;
1757 };
1758 let (tex, _) = eng.evaluate(&comp, comp.find_node("Dent1").unwrap(), 0.0);
1759 let px = eng.readback_rgba(&tex).unwrap();
1760 // x=72 (r=0.066 of the 0.25 radius): new_r = r - 0.5 * (1 - r / R) = -0.30 -> source at x=0.20,
1761 // so the gradient reads ~80% red / ~20% green.
1762 let i = (64 * 128 + 72) * 4;
1763 assert!(px[i].abs_diff(204) < 8 && px[i + 1].abs_diff(51) < 8, "got {:?}", &px[i..i + 4]);
1764 }
1765
1766 #[test]
1767 fn test_s_boolean_operation_names_and_missing_inputs() {
1768 let boolean = |name: &str, op: &str, inputs: &str| {
1769 format!(
1770 r#"{name} = sBoolean {{ Inputs = {{ {op} {inputs} }}, }},
1771 R{name} = sRender {{ Inputs = {{ Width = Input {{ Value = 128, }}, Height = Input {{ Value = 128, }},
1772 Input = Input {{ SourceOp = "{name}", Source = "Output", }}, }}, }},"#
1773 )
1774 };
1775 let both = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", }, Input2 = Input { SourceOp = "Ell", Source = "Output", },"#;
1776 let first = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", },"#;
1777 let second = r#"Input2 = Input { SourceOp = "Ell", Source = "Output", },"#;
1778 let fu = |v: &str| format!(r#"Operation = Input {{ Value = FuID {{ "{v}" }}, }},"#);
1779 let src = format!(
1780 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{
1781 Rect = sRectangle {{ Inputs = {{ Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.2, }},
1782 Red = Input {{ Value = 1, }}, Green = Input {{ Value = 0, }}, Blue = Input {{ Value = 0, }}, }}, }},
1783 Ell = sEllipse {{ Inputs = {{ Width = Input {{ Value = 0.3, }}, Height = Input {{ Value = 0.3, }}, }}, }},
1784 {} {} {} {} {} {}
1785 }} }}"#,
1786 boolean("Inter", &fu("Intersection"), both),
1787 boolean("Default", "", both),
1788 boolean("Unknown", &fu("Intersect"), both),
1789 boolean("SubFirst", &fu("Subtract"), first),
1790 boolean("SubSecond", &fu("Subtract"), second),
1791 boolean("UnionBoth", &fu("Union"), both),
1792 );
1793 let comp = Comp::from_fusion_str(&src).unwrap();
1794 let Ok(mut eng) = Engine::new_headless() else {
1795 return;
1796 };
1797 let mut px = |name: &str, x: usize| {
1798 let (tex, _) = eng.evaluate(&comp, comp.find_node(&format!("R{name}")).unwrap(), 0.0);
1799 let rgba = eng.readback_rgba(&tex).unwrap();
1800 let i = (64 * 128 + x) * 4;
1801 [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
1802 };
1803 let white = [255; 4];
1804 let empty = [0; 4];
1805 // x=64 is inside both shapes, x=90 is inside only the rectangle.
1806 assert_eq!(px("Inter", 64), white);
1807 assert_eq!(px("Inter", 90), empty);
1808 assert_eq!(px("Default", 64), white, "Operation defaults to Intersection");
1809 assert_eq!(px("Unknown", 64), empty, "unrecognized operation names render nothing");
1810 assert_eq!(px("SubFirst", 90), white, "a missing Input2 passes Input1 through in the boolean's own color");
1811 assert_eq!(px("SubSecond", 64), empty, "a missing Input1 renders nothing");
1812 assert_eq!(px("UnionBoth", 90), white);
1813 }
1814
1815 #[test]
1816 fn test_perspective_positioner_and_s_grid() {
1817 let src = r#"{
1818 Tools = ordered() {
1819 Bg1 = Background {
1820 Inputs = {
1821 Width = Input { Value = 64, },
1822 Height = Input { Value = 64, },
1823 Type = Input { Value = FuID { "Horizontal" }, },
1824 TopLeftRed = Input { Value = 1, },
1825 TopRightRed = Input { Value = 0, },
1826 TopRightBlue = Input { Value = 1, },
1827 },
1828 },
1829 PP_Lin = PerspectivePositioner {
1830 Inputs = {
1831 TopLeft = Input { Value = { 0.25, 0.75 }, },
1832 TopRight = Input { Value = { 0.75, 0.75 }, },
1833 BottomLeft = Input { Value = { 0.25, 0.25 }, },
1834 BottomRight = Input { Value = { 0.75, 0.25 }, },
1835 Input = Input { SourceOp = "Bg1", Source = "Output", },
1836 },
1837 },
1838 El1 = sEllipse {
1839 Inputs = { Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, },
1840 },
1841 Gr1 = sGrid {
1842 Inputs = {
1843 Input = Input { SourceOp = "El1", Source = "Output", },
1844 CellsX = Input { Value = 3, },
1845 CellsY = Input { Value = 3, },
1846 XOffset = Input { Value = 0.25, },
1847 YOffset = Input { Value = 0.25, },
1848 },
1849 },
1850 SR1 = sRender {
1851 Inputs = {
1852 Width = Input { Value = 64, },
1853 Height = Input { Value = 64, },
1854 Input = Input { SourceOp = "Gr1", Source = "Output", },
1855 },
1856 },
1857 },
1858 }"#;
1859 let comp = Comp::from_fusion_str(src).unwrap();
1860 let Ok(mut eng) = Engine::new_headless() else { return; };
1861 let (t_pp, _) = eng.evaluate(&comp, comp.find_node("PP_Lin").unwrap(), 0.0);
1862 let px_pp = eng.readback_rgba(&t_pp).unwrap();
1863 // Top-left output pixel samples around (0.25, 0.75) in Bg1 -> ~75% red, ~25% blue!
1864 let p0 = &px_pp[0..4];
1865 assert!(p0[0] > 165 && p0[2] > 40 && p0[2] < 90, "got {p0:?}");
1866
1867 let (t_sr, _) = eng.evaluate(&comp, comp.find_node("SR1").unwrap(), 0.0);
1868 let px_sr = eng.readback_rgba(&t_sr).unwrap();
1869 // Center cell (32, 32) and offset (+0.25*64 = 48, 32) should be lit white
1870 assert_eq!(&px_sr[(32 * 64 + 32) * 4..(32 * 64 + 32) * 4 + 4], &[255, 255, 255, 255]);
1871 assert_eq!(&px_sr[(32 * 64 + 48) * 4..(32 * 64 + 48) * 4 + 4], &[255, 255, 255, 255]);
1872 assert_eq!(&px_sr[0..4], &[0, 0, 0, 0]);
1873 }
1874
1875 #[test]
1876 fn test_day_sky_and_grid_warp() {
1877 let src = r#"{
1878 Tools = ordered() {
1879 DS1 = DaySky {
1880 Inputs = {
1881 Width = Input { Value = 64, },
1882 Height = Input { Value = 64, },
1883 Latitude = Input { Value = 37.0, },
1884 Longitude = Input { Value = 0.0, },
1885 Time = Input { Value = 12.0, },
1886 Exposure = Input { Value = 1.0, },
1887 },
1888 },
1889 BgW = Background {
1890 Inputs = {
1891 Width = Input { Value = 64, },
1892 Height = Input { Value = 64, },
1893 Type = Input { Value = FuID { "Horizontal" }, },
1894 TopLeftRed = Input { Value = 1, },
1895 TopRightGreen = Input { Value = 1, },
1896 },
1897 },
1898 GW1 = GridWarp {
1899 Inputs = {
1900 SrcGridChange = Input {
1901 Value = Mesh {
1902 Columns = 2, Rows = 2,
1903 DeltaC = 1, DeltaR = 1,
1904 Center = { 0, 0 },
1905 Corners = { -0.5, -0.5, 0.5, 0.5 },
1906 Points = {
1907 { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 },
1908 { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 },
1909 },
1910 },
1911 },
1912 DstGridChange = Input {
1913 Value = Mesh {
1914 Columns = 2, Rows = 2,
1915 DeltaC = 1, DeltaR = 1,
1916 Center = { 0, 0 },
1917 Corners = { -0.5, -0.5, 0.5, 0.5 },
1918 Points = {
1919 { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 },
1920 { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 },
1921 },
1922 },
1923 },
1924 Input = Input { SourceOp = "BgW", Source = "Output", },
1925 },
1926 },
1927 },
1928 }"#;
1929 let comp = Comp::from_fusion_str(src).unwrap();
1930 let Ok(mut eng) = Engine::new_headless() else { return; };
1931 let (t_ds, _) = eng.evaluate(&comp, comp.find_node("DS1").unwrap(), 0.0);
1932 let px_ds = eng.readback_rgba(&t_ds).unwrap();
1933 // Zenith row (y=0) is sky blue (B > R), horizon (y=63) is brighter haze
1934 let zen = &px_ds[(0 * 64 + 32) * 4..(0 * 64 + 32) * 4 + 4];
1935 let hor = &px_ds[(62 * 64 + 32) * 4..(62 * 64 + 32) * 4 + 4];
1936 assert!(zen[2] > zen[0] && zen[3] == 255, "zen={zen:?}");
1937 assert!(hor[0] > zen[0], "hor={hor:?} zen={zen:?}");
1938
1939 let (t_bg, _) = eng.evaluate(&comp, comp.find_node("BgW").unwrap(), 0.0);
1940 let (t_gw, _) = eng.evaluate(&comp, comp.find_node("GW1").unwrap(), 0.0);
1941 let px_bg = eng.readback_rgba(&t_bg).unwrap();
1942 let px_gw = eng.readback_rgba(&t_gw).unwrap();
1943 let mae: f64 = px_bg.iter().zip(&px_gw).map(|(a, b)| (*a as f64 - *b as f64).abs()).sum::<f64>()
1944 / px_bg.len() as f64;
1945 assert!(mae < 1.5, "identity GridWarp should match source, mae={mae}");
1946 }
1947}
crates/engine/src/eval/warps.rs created+998
......@@ -0,0 +1,998 @@
1//! 2D Warp & Sky Generators (`Drip`, `Dent`, `PerspectivePositioner`, `DaySky`, `GridWarp`).
2
3use super::*;
4
5impl Engine {
6 #[allow(clippy::too_many_arguments)]
7 pub(super) fn eval_drip(
8 &mut self,
9 comp: &Comp,
10 node: &Node,
11 time: f64,
12 frame_i: i64,
13 enc: &mut wgpu::CommandEncoder,
14 visiting: &mut HashSet<(NodeId, i64)>,
15 stats: &mut EvalStats,
16 ) -> CachedTexture {
17 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
18 return self.dummy.clone();
19 };
20 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
21 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
22 let amp = comp.eval_number(node, "Amplitude", time, 0.1, &self.expr) as f32;
23 if blend <= 1e-6 || amp.abs() <= 1e-7 {
24 return src;
25 }
26 let src = self.crop_to_canvas(enc, src);
27 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
28 let freq = comp.eval_number(node, "Frequency", time, 10.0, &self.expr) as f32;
29 let aspect = comp.eval_number(node, "Aspect", time, 1.0, &self.expr).max(1e-4) as f32;
30 let phase = comp.eval_number(node, "Phase", time, 0.0, &self.expr) as f32;
31 let dampening = comp.eval_number(node, "Dampening", time, 0.0, &self.expr).max(0.0) as f32;
32 let shape = comp.eval_number(node, "Shape", time, 0.0, &self.expr).round() as f32;
33 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
34 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
35
36 let mut u = UniformParams::default();
37 u.p[0] = [center[0] as f32, center[1] as f32, 0.0, amp];
38 u.p[1] = [freq, aspect, phase, dampening];
39 u.p[2] = [shape, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
40
41 let key = self.make_key(
42 node,
43 "Drip",
44 src.size,
45 &[src.content_hash, mask_hash],
46 bytemuck::cast_slice(&u.p[..3]),
47 );
48 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
49 stats.cache_hits += 1;
50 return hit;
51 }
52 stats.cache_misses += 1;
53 stats.nodes_evaluated += 1;
54 let dst = self.alloc_tex_like(&src, src.depth, key);
55 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
56 self.dispatch_op(enc, ShaderOp::Drip, &src.view, &self.dummy.view, mv, &dst, &u);
57 self.cache.insert(key, dst.clone(), node.id, frame_i);
58 dst
59 }
60
61 #[allow(clippy::too_many_arguments)]
62 pub(super) fn eval_dent(
63 &mut self,
64 comp: &Comp,
65 node: &Node,
66 time: f64,
67 frame_i: i64,
68 enc: &mut wgpu::CommandEncoder,
69 visiting: &mut HashSet<(NodeId, i64)>,
70 stats: &mut EvalStats,
71 ) -> CachedTexture {
72 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
73 return self.dummy.clone();
74 };
75 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
76 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
77 let strength = comp.eval_number(node, "Strength", time, 0.5, &self.expr) as f32;
78 if blend <= 1e-6 || strength.abs() <= 1e-6 {
79 return src;
80 }
81 let src = self.crop_to_canvas(enc, src);
82 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
83 let size = comp.eval_number(node, "Size", time, 0.5, &self.expr).max(1e-4) as f32;
84 let dent_type = comp.eval_number(node, "Type", time, 0.0, &self.expr).round() as f32;
85 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
86 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
87
88 let mut u = UniformParams::default();
89 u.p[0] = [center[0] as f32, center[1] as f32, size * 0.5, strength];
90 u.p[1] = [dent_type, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
91
92 let key = self.make_key(
93 node,
94 "Dent",
95 src.size,
96 &[src.content_hash, mask_hash],
97 bytemuck::cast_slice(&u.p[..2]),
98 );
99 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
100 stats.cache_hits += 1;
101 return hit;
102 }
103 stats.cache_misses += 1;
104 stats.nodes_evaluated += 1;
105 let dst = self.alloc_tex_like(&src, src.depth, key);
106 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
107 self.dispatch_op(enc, ShaderOp::Dent, &src.view, &self.dummy.view, mv, &dst, &u);
108 self.cache.insert(key, dst.clone(), node.id, frame_i);
109 dst
110 }
111
112 #[allow(clippy::too_many_arguments)]
113 pub(super) fn eval_perspective_positioner(
114 &mut self,
115 comp: &Comp,
116 node: &Node,
117 time: f64,
118 frame_i: i64,
119 enc: &mut wgpu::CommandEncoder,
120 visiting: &mut HashSet<(NodeId, i64)>,
121 stats: &mut EvalStats,
122 ) -> CachedTexture {
123 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
124 return self.dummy.clone();
125 };
126 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
127 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
128 if blend <= 1e-6 {
129 return src;
130 }
131 let src = self.crop_to_canvas(enc, src);
132 let bl = comp.eval_point(node, "BottomLeft", time, [0.0, 0.0], &self.expr);
133 let br = comp.eval_point(node, "BottomRight", time, [1.0, 0.0], &self.expr);
134 let tr = comp.eval_point(node, "TopRight", time, [1.0, 1.0], &self.expr);
135 let tl = comp.eval_point(node, "TopLeft", time, [0.0, 1.0], &self.expr);
136 let mapping_type = comp.eval_number(node, "MappingType", time, 0.0, &self.expr).round() as i32;
137 let h_fwd = quad_forward_homography(bl, br, tr, tl);
138 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
139 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
140
141 let mut u = UniformParams::default();
142 u.p[0] = [bl[0] as f32, bl[1] as f32, br[0] as f32, br[1] as f32];
143 u.p[1] = [tr[0] as f32, tr[1] as f32, tl[0] as f32, tl[1] as f32];
144 u.p[2] = [h_fwd[0], h_fwd[1], h_fwd[2], h_fwd[3]];
145 u.p[3] = [h_fwd[4], h_fwd[5], h_fwd[6], h_fwd[7]];
146 u.p[4] = [
147 h_fwd[8],
148 if mapping_type == 1 { 1.0 } else { 0.0 },
149 blend,
150 if mask.is_some() { 1.0 } else { 0.0 },
151 ];
152 u.p[5] = [if mask_inv { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0];
153
154 let key = self.make_key(
155 node,
156 "PerspectivePositioner",
157 src.size,
158 &[src.content_hash, mask_hash],
159 bytemuck::cast_slice(&u.p[..6]),
160 );
161 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
162 stats.cache_hits += 1;
163 return hit;
164 }
165 stats.cache_misses += 1;
166 stats.nodes_evaluated += 1;
167 let dst = self.alloc_tex_like(&src, src.depth, key);
168 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
169 self.dispatch_op(enc, ShaderOp::PerspectivePos, &src.view, &self.dummy.view, mv, &dst, &u);
170 self.cache.insert(key, dst.clone(), node.id, frame_i);
171 dst
172 }
173
174 #[allow(clippy::too_many_arguments)]
175 pub(super) fn eval_day_sky(
176 &mut self,
177 comp: &Comp,
178 node: &Node,
179 time: f64,
180 frame_i: i64,
181 comp_dims: [u32; 2],
182 enc: &mut wgpu::CommandEncoder,
183 visiting: &mut HashSet<(NodeId, i64)>,
184 stats: &mut EvalStats,
185 ) -> CachedTexture {
186 let use_ff = comp.eval_number(node, "UseFrameFormatSettings", time, 0.0, &self.expr) > 0.5;
187 let w = if use_ff {
188 comp.width
189 } else {
190 comp.eval_number(node, "Width", time, comp.width as f64, &self.expr).round().max(1.0) as u32
191 };
192 let h = if use_ff {
193 comp.height
194 } else {
195 comp.eval_number(node, "Height", time, comp.height as f64, &self.expr).round().max(1.0) as u32
196 };
197 let size = if w == comp.width && h == comp.height { comp_dims } else { self.scaled_dims(w, h) };
198 let dst_depth = self.node_depth(comp, node, time, None);
199 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
200
201 let lat_deg = comp.eval_number(node, "Latitude", time, 43.65, &self.expr);
202 let lon_deg = comp.eval_number(node, "Longitude", time, -79.38, &self.expr);
203 let month = parse_month_index(node, comp, time, &self.expr);
204 let day = node
205 .static_str("Day")
206 .and_then(|s| s.parse::<f64>().ok())
207 .unwrap_or_else(|| comp.eval_number(node, "Day", time, 1.0, &self.expr));
208 let hour = comp.eval_number(node, "Time", time, 12.0, &self.expr);
209 let turbidity_in = comp.eval_number(node, "Turbidity", time, 0.0, &self.expr).max(0.0);
210 let exposure = comp.eval_number(node, "Exposure", time, 0.72, &self.expr).max(0.0);
211 let hb = comp.eval_number(node, "Horizon.Brightness", time, 1.0, &self.expr).max(0.0);
212 let hl = comp.eval_number(node, "Horizon.Luminance", time, 1.0, &self.expr).max(0.0);
213 let ci = comp.eval_number(node, "Circumsolar.Intensity", time, 1.0, &self.expr).max(0.0);
214 let cw = comp.eval_number(node, "Circumsolar.Width", time, 1.0, &self.expr).max(0.0);
215 let bs = comp.eval_number(node, "BackscatteredLight", time, 1.0, &self.expr).max(0.0);
216
217 let (sun_dir, ts) = solar_direction(lat_deg, lon_deg, month, day, hour);
218 // Calibrated to Fusion 21.1 DaySky: Turbidity in [0,1] maps to T = 1.9 + 4.0 * turb
219 let t_preetham = 1.9 + turbidity_in * 4.0;
220 let (xz, yz, _yz_lum) = preetham_zenith_xyy(t_preetham, ts);
221 let c_y0 = [
222 0.1787 * t_preetham - 1.4630,
223 (-0.3554 * t_preetham + 0.4275) * 1.20,
224 -0.0227 * t_preetham + 5.3251,
225 0.1206 * t_preetham - 2.5771,
226 -0.0670 * t_preetham + 0.3703,
227 ];
228 let c_x0 = [
229 -0.0193 * t_preetham - 0.2592,
230 -0.0665 * t_preetham + 0.0008,
231 -0.0004 * t_preetham + 0.2125,
232 -0.0641 * t_preetham - 0.8989,
233 -0.0033 * t_preetham + 0.0452,
234 ];
235 let c_y_c0 = [
236 -0.0167 * t_preetham - 0.2608,
237 -0.0950 * t_preetham + 0.0092,
238 -0.0079 * t_preetham + 0.2102,
239 -0.0441 * t_preetham - 1.6537,
240 -0.0109 * t_preetham + 0.0529,
241 ];
242
243 let scale_perez = |base: [f64; 5]| -> [f64; 5] {
244 let a = if hb <= 1e-4 || hl <= 1e-4 { 0.0 } else { base[0] * hb };
245 let b = base[1] / hl.max(1e-3);
246 let c = if cw <= 1e-4 { 0.0 } else { base[2] * ci };
247 let d = base[3] * cw;
248 let e = base[4] * bs;
249 [a, b, c, d, e]
250 };
251 let c_y = scale_perez(c_y0);
252 let c_x = scale_perez(c_x0);
253 let c_yc = scale_perez(c_y_c0);
254
255 // Log-average Perez luminance normalization: geom_mean(Y_hdr) == Exposure
256 const N_TH: usize = 32;
257 const N_PH: usize = 32;
258 let mut sum_log = 0.0_f64;
259 for iy in 0..N_TH {
260 let th = (iy as f64 + 0.5) / N_TH as f64 * std::f64::consts::FRAC_PI_2;
261 let (st, ct) = th.sin_cos();
262 for ix in 0..N_PH {
263 let ph = (ix as f64 + 0.5) / N_PH as f64 * std::f64::consts::TAU;
264 let (sp, cp) = ph.sin_cos();
265 let cos_g = (st * cp * sun_dir[0] + st * sp * sun_dir[1] + ct * sun_dir[2]).clamp(-1.0, 1.0);
266 let fy = eval_perez(th, cos_g.acos(), c_y).max(1e-5);
267 sum_log += fy.ln();
268 }
269 }
270 let geomean_fy = (sum_log / (N_TH * N_PH) as f64).exp().max(1e-5);
271 let lum_gain = (exposure / geomean_fy) as f32;
272 let f_y0 = 1.0_f64;
273 let f_x0 = eval_perez(0.0, ts, c_x);
274 let f_yc0 = eval_perez(0.0, ts, c_yc);
275 let yz_scaled = lum_gain;
276
277 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(size), enc, visiting, stats);
278 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
279
280 let mut u = UniformParams::default();
281 u.p[0] = [sun_dir[0] as f32, sun_dir[1] as f32, sun_dir[2] as f32, yz_scaled];
282 u.p[1] = [xz as f32, yz as f32, f_y0 as f32, f_x0 as f32];
283 u.p[2] = [f_yc0 as f32, blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }];
284 u.p[3] = [c_y[0] as f32, c_y[1] as f32, c_y[2] as f32, c_y[3] as f32];
285 u.p[4] = [c_y[4] as f32, c_x[0] as f32, c_x[1] as f32, c_x[2] as f32];
286 u.p[5] = [c_x[3] as f32, c_x[4] as f32, c_yc[0] as f32, c_yc[1] as f32];
287 u.p[6] = [c_yc[2] as f32, c_yc[3] as f32, c_yc[4] as f32, 0.0];
288
289 let key = self.make_key(
290 node,
291 "DaySky",
292 size,
293 &[mask_hash, dst_depth as u64],
294 bytemuck::cast_slice(&u.p[..7]),
295 );
296 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
297 stats.cache_hits += 1;
298 return hit;
299 }
300 stats.cache_misses += 1;
301 stats.nodes_evaluated += 1;
302 let dst = self.alloc_tex(size, dst_depth, key);
303 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
304 self.dispatch_op(enc, ShaderOp::DaySky, &self.dummy.view, &self.dummy.view, mv, &dst, &u);
305 self.cache.insert(key, dst.clone(), node.id, frame_i);
306 dst
307 }
308
309 #[allow(clippy::too_many_arguments)]
310 pub(super) fn eval_grid_warp(
311 &mut self,
312 comp: &Comp,
313 node: &Node,
314 time: f64,
315 frame_i: i64,
316 enc: &mut wgpu::CommandEncoder,
317 visiting: &mut HashSet<(NodeId, i64)>,
318 stats: &mut EvalStats,
319 ) -> CachedTexture {
320 let Some(src_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) else {
321 return self.dummy.clone();
322 };
323 let src = self.eval_node(comp, src_id, time, enc, visiting, stats);
324 let blend = comp.eval_number(node, "Blend", time, 1.0, &self.expr) as f32;
325 if blend <= 1e-6 {
326 return src;
327 }
328 let src_mesh = comp.eval_grid_mesh(node, "SrcGridChange", time);
329 let dst_mesh = comp.eval_grid_mesh(node, "DstGridChange", time);
330 let (Some(src_mesh), Some(dst_mesh)) = (src_mesh, dst_mesh) else {
331 return src;
332 };
333 if src_mesh == dst_mesh {
334 return src;
335 }
336 let src = self.crop_to_canvas(enc, src);
337 let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(src.size), enc, visiting, stats);
338 let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash);
339
340 let mut u = UniformParams::default();
341 u.p[0] = [blend, if mask.is_some() { 1.0 } else { 0.0 }, if mask_inv { 1.0 } else { 0.0 }, 0.0];
342
343 let mut mesh_params: Vec<f32> = Vec::with_capacity(4 + (src_mesh.points.len() + dst_mesh.points.len()) * 10);
344 mesh_params.extend_from_slice(&[blend, src_mesh.cols as f32, src_mesh.rows as f32, dst_mesh.cols as f32]);
345 for m in [&src_mesh, &dst_mesh] {
346 for p in &m.points {
347 mesh_params.extend_from_slice(&[
348 p.x as f32,
349 p.y as f32,
350 p.l_cx.unwrap_or(f32::NAN as f64) as f32,
351 p.l_cy.unwrap_or(0.0) as f32,
352 p.r_cx.unwrap_or(f32::NAN as f64) as f32,
353 p.r_cy.unwrap_or(0.0) as f32,
354 p.t_cx.unwrap_or(0.0) as f32,
355 p.t_cy.unwrap_or(f32::NAN as f64) as f32,
356 p.b_cx.unwrap_or(0.0) as f32,
357 p.b_cy.unwrap_or(f32::NAN as f64) as f32,
358 ]);
359 }
360 }
361
362 let key = self.make_key(node, "GridWarp", src.size, &[src.content_hash, mask_hash], &mesh_params);
363 if let Some(hit) = self.cache.get(key, node.id, frame_i) {
364 stats.cache_hits += 1;
365 return hit;
366 }
367 stats.cache_misses += 1;
368 stats.nodes_evaluated += 1;
369
370 let uv_f16 = rasterize_grid_warp_uv_f16(&src_mesh, &dst_mesh, src.size);
371 let uv_tex = create_texture_dod_fmt(
372 &self.device,
373 src.size,
374 [0, 0],
375 src.size,
376 BitDepth::Float16,
377 wgpu::TextureFormat::Rgba16Float,
378 0,
379 );
380 self.queue.write_texture(
381 uv_tex.texture.as_image_copy(),
382 bytemuck::cast_slice(&uv_f16),
383 wgpu::TexelCopyBufferLayout {
384 offset: 0,
385 bytes_per_row: Some(src.size[0] * 8),
386 rows_per_image: Some(src.size[1]),
387 },
388 wgpu::Extent3d {
389 width: src.size[0],
390 height: src.size[1],
391 depth_or_array_layers: 1,
392 },
393 );
394
395 let dst = self.alloc_tex_like(&src, src.depth, key);
396 let mv = mask.as_ref().map_or(&self.dummy.view, |m| &m.view);
397 self.dispatch_op(enc, ShaderOp::GridWarp, &src.view, &uv_tex.view, mv, &dst, &u);
398 self.cache.insert(key, dst.clone(), node.id, frame_i);
399 dst
400 }
401}
402
403fn quad_forward_homography(bl: [f64; 2], br: [f64; 2], tr: [f64; 2], tl: [f64; 2]) -> [f32; 9] {
404 let dx1 = br[0] - tr[0];
405 let dy1 = br[1] - tr[1];
406 let dx2 = tl[0] - tr[0];
407 let dy2 = tl[1] - tr[1];
408 let sx = bl[0] - br[0] + tr[0] - tl[0];
409 let sy = bl[1] - br[1] + tr[1] - tl[1];
410 let denom = dx1 * dy2 - dx2 * dy1;
411 if denom.abs() < 1e-10 {
412 return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
413 }
414 let g = (sx * dy2 - sy * dx2) / denom;
415 let h = (dx1 * sy - dy1 * sx) / denom;
416 let a = br[0] - bl[0] + g * br[0];
417 let b = tl[0] - bl[0] + h * tl[0];
418 let c = bl[0];
419 let d = br[1] - bl[1] + g * br[1];
420 let e = tl[1] - bl[1] + h * tl[1];
421 let f = bl[1];
422 [a as f32, b as f32, c as f32, d as f32, e as f32, f as f32, g as f32, h as f32, 1.0]
423}
424
425fn parse_month_index(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> usize {
426 if let Some(m) = node.static_str("Month") {
427 let low = m.to_ascii_lowercase();
428 let names = [
429 "january", "february", "march", "april", "may", "june",
430 "july", "august", "september", "october", "november", "december",
431 ];
432 if let Some(idx) = names.iter().position(|&n| low.starts_with(&n[..3])) {
433 return idx + 1;
434 }
435 if let Ok(v) = m.parse::<usize>() {
436 return v.clamp(1, 12);
437 }
438 }
439 (comp.eval_number(node, "Month", time, 0.0, expr).round() as usize + 1).clamp(1, 12)
440}
441
442fn solar_direction(lat_deg: f64, lon_deg: f64, month: usize, day: f64, hour: f64) -> ([f64; 3], f64) {
443 const CUM_DAYS: [i32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
444 let doy = CUM_DAYS[month.saturating_sub(1).min(11)] as f64 + day;
445 let b = 2.0 * std::f64::consts::PI * (doy - 81.0) / 365.0;
446 let eot_min = 9.87 * (2.0 * b).sin() - 7.53 * b.cos() - 1.5 * b.sin();
447 let decl = 23.44_f64.to_radians() * ((2.0 * std::f64::consts::PI / 365.0) * (doy - 81.0)).sin();
448 let std_meridian = (lon_deg / 15.0).round() * 15.0;
449 let solar_hour = hour + (lon_deg - std_meridian) / 15.0 + eot_min / 60.0;
450 let hour_angle = ((solar_hour - 12.0) * 15.0).to_radians();
451 let lat = lat_deg.to_radians();
452 let sin_alt = (lat.sin() * decl.sin() + lat.cos() * decl.cos() * hour_angle.cos()).clamp(-1.0, 1.0);
453 let ts = (std::f64::consts::FRAC_PI_2 - sin_alt.asin()).max(0.0);
454 // Azimuth measured from South (0=South, pi/2=East morning, pi=North, 3*pi/2=West afternoon)
455 let cos_az_south = (-(decl.sin() * lat.cos() - decl.cos() * lat.sin() * hour_angle.cos())
456 / ts.sin().max(1e-5))
457 .clamp(-1.0, 1.0);
458 let mut phi_s = cos_az_south.acos();
459 if hour_angle > 0.0 {
460 phi_s = 2.0 * std::f64::consts::PI - phi_s;
461 }
462 let dir = [ts.sin() * phi_s.cos(), ts.sin() * phi_s.sin(), ts.cos()];
463 (dir, ts)
464}
465
466fn preetham_zenith_xyy(t: f64, ts: f64) -> (f64, f64, f64) {
467 let t2 = t * t;
468 let ts2 = ts * ts;
469 let ts3 = ts2 * ts;
470 let chi = (4.0 / 9.0 - t / 120.0) * (std::f64::consts::PI - 2.0 * ts);
471 let yz_lum = ((4.0453 * t - 4.9710) * chi.tan() - 0.2155 * t + 2.4192).max(0.05);
472 let xz = (0.00166 * ts3 - 0.00375 * ts2 + 0.00209 * ts) * t2
473 + (-0.02903 * ts3 + 0.06377 * ts2 - 0.03202 * ts + 0.00394) * t
474 + (0.11693 * ts3 - 0.21196 * ts2 + 0.06052 * ts + 0.25886);
475 let yz = (0.00275 * ts3 - 0.00610 * ts2 + 0.00317 * ts) * t2
476 + (-0.04214 * ts3 + 0.08970 * ts2 - 0.04153 * ts + 0.00516) * t
477 + (0.15346 * ts3 - 0.26756 * ts2 + 0.06670 * ts + 0.26688);
478 (xz, yz, yz_lum)
479}
480
481fn eval_perez(theta: f64, gamma: f64, c: [f64; 5]) -> f64 {
482 let ct = theta.cos().max(0.02);
483 let cg = gamma.cos();
484 (1.0 + c[0] * (c[1] / ct).exp()) * (1.0 + c[2] * (c[3] * gamma).exp() + c[4] * cg * cg)
485}
486
487#[derive(Clone, Copy)]
488struct CoonsPt {
489 p: [f32; 2],
490 l: [f32; 2],
491 r: [f32; 2],
492 t: [f32; 2],
493 b: [f32; 2],
494}
495
496fn mesh_coons_cells(mesh: &model::comp::GridMesh) -> Vec<[CoonsPt; 4]> {
497 let cols = mesh.cols;
498 let rows = mesh.rows;
499 let dc = (mesh.delta_c as f32) / 3.0;
500 let dr = (mesh.delta_r as f32) / 3.0;
501 let pts: Vec<CoonsPt> = mesh
502 .points
503 .iter()
504 .map(|mp| {
505 let p = [mp.x as f32, mp.y as f32];
506 let l = [p[0] + mp.l_cx.map_or(-dc, |v| v as f32), p[1] + mp.l_cy.unwrap_or(0.0) as f32];
507 let r = [p[0] + mp.r_cx.map_or(dc, |v| v as f32), p[1] + mp.r_cy.unwrap_or(0.0) as f32];
508 let t = [p[0] + mp.t_cx.unwrap_or(0.0) as f32, p[1] + mp.t_cy.map_or(-dr, |v| v as f32)];
509 let b = [p[0] + mp.b_cx.unwrap_or(0.0) as f32, p[1] + mp.b_cy.map_or(dr, |v| v as f32)];
510 CoonsPt { p, l, r, t, b }
511 })
512 .collect();
513 let mut cells = Vec::with_capacity((cols - 1) * (rows - 1));
514 for r in 0..(rows - 1) {
515 for c in 0..(cols - 1) {
516 cells.push([
517 pts[r * cols + c],
518 pts[r * cols + c + 1],
519 pts[(r + 1) * cols + c],
520 pts[(r + 1) * cols + c + 1],
521 ]);
522 }
523 }
524 cells
525}
526
527fn bez3_2d(p0: [f32; 2], p1: [f32; 2], p2: [f32; 2], p3: [f32; 2], t: f32) -> [f32; 2] {
528 let u = 1.0 - t;
529 let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
530 [
531 w0 * p0[0] + w1 * p1[0] + w2 * p2[0] + w3 * p3[0],
532 w0 * p0[1] + w1 * p1[1] + w2 * p2[1] + w3 * p3[1],
533 ]
534}
535
536fn eval_coons_cell(cell: &[CoonsPt; 4], u: f32, v: f32) -> [f32; 2] {
537 let [p00, p10, p01, p11] = *cell;
538 let bot = bez3_2d(p00.p, p00.r, p10.l, p10.p, u);
539 let top = bez3_2d(p01.p, p01.r, p11.l, p11.p, u);
540 let lft = bez3_2d(p00.p, p00.b, p01.t, p01.p, v);
541 let rgt = bez3_2d(p10.p, p10.b, p11.t, p11.p, v);
542 let bi0 = (1.0 - u) * (1.0 - v) * p00.p[0] + u * (1.0 - v) * p10.p[0] + (1.0 - u) * v * p01.p[0] + u * v * p11.p[0];
543 let bi1 = (1.0 - u) * (1.0 - v) * p00.p[1] + u * (1.0 - v) * p10.p[1] + (1.0 - u) * v * p01.p[1] + u * v * p11.p[1];
544 [
545 (1.0 - v) * bot[0] + v * top[0] + (1.0 - u) * lft[0] + u * rgt[0] - bi0,
546 (1.0 - v) * bot[1] + v * top[1] + (1.0 - u) * lft[1] + u * rgt[1] - bi1,
547 ]
548}
549
550fn rasterize_grid_warp_uv_f16(
551 src_mesh: &model::comp::GridMesh,
552 dst_mesh: &model::comp::GridMesh,
553 dims: [u32; 2],
554) -> Vec<u16> {
555 let [w, h] = dims;
556 let (wf, hf) = (w as f32, h as f32);
557 let mut uv_buf = vec![0u16; (w as usize) * (h as usize) * 4];
558 let src_cells = mesh_coons_cells(src_mesh);
559 let dst_cells = mesh_coons_cells(dst_mesh);
560 let sub = 24usize;
561 let one_f16 = crate::media::f32_to_f16_bits(1.0);
562
563 for (sc, dc) in src_cells.iter().zip(dst_cells.iter()) {
564 for j in 0..sub {
565 let (v0, v1) = (j as f32 / sub as f32, (j + 1) as f32 / sub as f32);
566 for i in 0..sub {
567 let (u0, u1) = (i as f32 / sub as f32, (i + 1) as f32 / sub as f32);
568 let da = eval_coons_cell(dc, u0, v0);
569 let db = eval_coons_cell(dc, u1, v0);
570 let dc2 = eval_coons_cell(dc, u1, v1);
571 let dd = eval_coons_cell(dc, u0, v1);
572 let sa = eval_coons_cell(sc, u0, v0);
573 let sb = eval_coons_cell(sc, u1, v0);
574 let sc2 = eval_coons_cell(sc, u1, v1);
575 let sd = eval_coons_cell(sc, u0, v1);
576
577 for ([pa, pb, pc], [qa, qb, qc]) in [([da, db, dc2], [sa, sb, sc2]), ([da, dc2, dd], [sa, sc2, sd])] {
578 let (ax, ay) = ((pa[0] + 0.5) * wf, (0.5 - pa[1]) * hf);
579 let (bx, by) = ((pb[0] + 0.5) * wf, (0.5 - pb[1]) * hf);
580 let (cx, cy) = ((pc[0] + 0.5) * wf, (0.5 - pc[1]) * hf);
581 let area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
582 if area.abs() < 1e-6 {
583 continue;
584 }
585 let inv_area = 1.0 / area;
586 let x0 = ax.min(bx).min(cx).floor().max(0.0) as u32;
587 let x1 = (ax.max(bx).max(cx).ceil() as u32).min(w.saturating_sub(1));
588 let y0 = ay.min(by).min(cy).floor().max(0.0) as u32;
589 let y1 = (ay.max(by).max(cy).ceil() as u32).min(h.saturating_sub(1));
590 for py in y0..=y1 {
591 let qy = py as f32 + 0.5;
592 for px in x0..=x1 {
593 let qx = px as f32 + 0.5;
594 let w0 = ((bx - qx) * (cy - qy) - (by - qy) * (cx - qx)) * inv_area;
595 let w1 = ((cx - qx) * (ay - qy) - (cy - qy) * (ax - qx)) * inv_area;
596 let w2 = 1.0 - w0 - w1;
597 if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 {
598 let su = w0 * qa[0] + w1 * qb[0] + w2 * qc[0] + 0.5;
599 let sv = w0 * qa[1] + w1 * qb[1] + w2 * qc[1] + 0.5;
600 let idx = (py as usize * w as usize + px as usize) * 4;
601 uv_buf[idx] = crate::media::f32_to_f16_bits(su);
602 uv_buf[idx + 1] = crate::media::f32_to_f16_bits(sv);
603 uv_buf[idx + 2] = one_f16;
604 }
605 }
606 }
607 }
608 }
609 }
610 }
611 uv_buf
612}
613
614#[cfg(test)]
615mod tests {
616 use super::*;
617 use crate::Engine;
618
619 #[test]
620 fn test_drip_concentric_ripple_displacement() {
621 let src = r#"Composition {
622 CurrentTime = 0,
623 RenderRange = { 0, 1 },
624 GlobalRange = { 0, 1 },
625 Tools = ordered() {
626 BG1 = Background {
627 Inputs = {
628 Width = Input { Value = 128, },
629 Height = Input { Value = 128, },
630 Type = Input { Value = FuID { "Horizontal" }, },
631 TopLeftRed = Input { Value = 1.0, },
632 TopLeftGreen = Input { Value = 0.0, },
633 TopLeftBlue = Input { Value = 0.0, },
634 TopRightRed = Input { Value = 0.0, },
635 TopRightGreen = Input { Value = 0.0, },
636 TopRightBlue = Input { Value = 1.0, },
637 },
638 },
639 Drip1 = Drip {
640 Inputs = {
641 Input = Input { SourceOp = "BG1", Source = "Output", },
642 Center = Input { Value = { 0.5, 0.5 }, },
643 Strength = Input { Value = 1.0, },
644 Amplitude = Input { Value = 0.12, },
645 Frequency = Input { Value = 4.0, },
646 Phase = Input { Value = 0.0, },
647 Shape = Input { Value = 0, },
648 },
649 },
650 },
651 }"#;
652 let comp = Comp::from_fusion_str(src).expect("parse Drip comp");
653 let Ok(mut eng) = Engine::new_headless() else {
654 return;
655 };
656 let bg_id = comp.find_node("BG1").unwrap();
657 let drip_id = comp.find_node("Drip1").unwrap();
658 let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0);
659 let (drip_tex, stats) = eng.evaluate(&comp, drip_id, 0.0);
660 assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes);
661 let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg");
662 let drip_px = eng.readback_rgba(&drip_tex).expect("readback drip");
663
664 let diff_sum: u64 = bg_px
665 .iter()
666 .zip(drip_px.iter())
667 .map(|(&a, &b)| a.abs_diff(b) as u64)
668 .sum();
669 assert!(diff_sum > 10_000, "Drip should visibly displace pixels, got diff_sum={diff_sum}");
670 }
671
672 #[test]
673 fn test_dent_radial_distortion() {
674 let src = r#"Composition {
675 CurrentTime = 0,
676 RenderRange = { 0, 1 },
677 GlobalRange = { 0, 1 },
678 Tools = ordered() {
679 BG1 = Background {
680 Inputs = {
681 Width = Input { Value = 128, },
682 Height = Input { Value = 128, },
683 Type = Input { Value = FuID { "Horizontal" }, },
684 TopLeftRed = Input { Value = 1.0, },
685 TopLeftGreen = Input { Value = 0.0, },
686 TopLeftBlue = Input { Value = 0.0, },
687 TopRightRed = Input { Value = 0.0, },
688 TopRightGreen = Input { Value = 1.0, },
689 TopRightBlue = Input { Value = 0.0, },
690 },
691 },
692 Dent1 = Dent {
693 Inputs = {
694 Input = Input { SourceOp = "BG1", Source = "Output", },
695 Center = Input { Value = { 0.5, 0.5 }, },
696 Size = Input { Value = 0.6, },
697 Strength = Input { Value = 0.8, },
698 Type = Input { Value = 0, },
699 },
700 },
701 },
702 }"#;
703 let comp = Comp::from_fusion_str(src).expect("parse Dent comp");
704 let Ok(mut eng) = Engine::new_headless() else {
705 return;
706 };
707 let bg_id = comp.find_node("BG1").unwrap();
708 let dent_id = comp.find_node("Dent1").unwrap();
709 let (bg_tex, _) = eng.evaluate(&comp, bg_id, 0.0);
710 let (dent_tex, stats) = eng.evaluate(&comp, dent_id, 0.0);
711 assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes);
712 let bg_px = eng.readback_rgba(&bg_tex).expect("readback bg");
713 let dent_px = eng.readback_rgba(&dent_tex).expect("readback dent");
714
715 // Corners outside radius=0.3 must remain unchanged; interior must be distorted!
716 assert_eq!(&bg_px[0..4], &dent_px[0..4], "corner pixel outside dent radius should match");
717 let mut interior_diff = 0u64;
718 for y in 44..84 {
719 for x in 44..84 {
720 let idx = (y * 128 + x) * 4;
721 interior_diff += bg_px[idx].abs_diff(dent_px[idx]) as u64;
722 interior_diff += bg_px[idx + 1].abs_diff(dent_px[idx + 1]) as u64;
723 }
724 }
725 assert!(interior_diff > 2_000, "Dent interior should visibly distort, got {interior_diff}");
726 }
727
728 #[test]
729 fn test_drip_shapes_and_strength_independence() {
730 let make_comp = |strength: f64, shape: i32| {
731 format!(
732 r#"Composition {{
733 CurrentTime = 0,
734 RenderRange = {{ 0, 1 }},
735 GlobalRange = {{ 0, 1 }},
736 Tools = ordered() {{
737 BG1 = Background {{
738 Inputs = {{
739 Width = Input {{ Value = 128, }},
740 Height = Input {{ Value = 128, }},
741 Type = Input {{ Value = FuID {{ "Horizontal" }}, }},
742 TopLeftRed = Input {{ Value = 1.0, }},
743 TopRightBlue = Input {{ Value = 1.0, }},
744 }},
745 }},
746 Drip1 = Drip {{
747 Inputs = {{
748 Input = Input {{ SourceOp = "BG1", Source = "Output", }},
749 Center = Input {{ Value = {{ 0.4, 0.6 }}, }},
750 Strength = Input {{ Value = {strength}, }},
751 Amplitude = Input {{ Value = 0.08, }},
752 Frequency = Input {{ Value = 4.0, }},
753 Phase = Input {{ Value = 0.75, }},
754 Shape = Input {{ Value = {shape}, }},
755 }},
756 }},
757 }},
758 }}"#
759 )
760 };
761 let Ok(mut eng) = Engine::new_headless() else {
762 return;
763 };
764 let comp_a = Comp::from_fusion_str(&make_comp(0.25, 1)).unwrap();
765 let comp_b = Comp::from_fusion_str(&make_comp(1.0, 1)).unwrap();
766 let (tex_a, _) = eng.evaluate(&comp_a, comp_a.find_node("Drip1").unwrap(), 0.0);
767 let (tex_b, _) = eng.evaluate(&comp_b, comp_b.find_node("Drip1").unwrap(), 0.0);
768 let px_a = eng.readback_rgba(&tex_a).unwrap();
769 let px_b = eng.readback_rgba(&tex_b).unwrap();
770 assert_eq!(px_a, px_b, "Fusion Drip ignores Strength and uses Amplitude directly");
771
772 // Center pixel (0.4*128=51, (1-0.6)*128=51) must remain smooth (raw_rel=0 -> disp=0)
773 let (bg_tex, _) = eng.evaluate(&comp_a, comp_a.find_node("BG1").unwrap(), 0.0);
774 let bg_px = eng.readback_rgba(&bg_tex).unwrap();
775 let diff_sum: u64 = bg_px.iter().zip(px_a.iter()).map(|(&a, &b)| a.abs_diff(b) as u64).sum();
776 assert!(diff_sum > 5_000, "Square Drip should displace pixels, got {diff_sum}");
777 }
778
779 #[test]
780 fn test_dent_type0_signed_inversion() {
781 let src = r#"Composition {
782 CurrentTime = 0,
783 RenderRange = { 0, 1 },
784 GlobalRange = { 0, 1 },
785 Tools = ordered() {
786 BG1 = Background {
787 Inputs = {
788 Width = Input { Value = 128, },
789 Height = Input { Value = 128, },
790 Type = Input { Value = FuID { "Horizontal" }, },
791 TopLeftRed = Input { Value = 1.0, },
792 TopLeftGreen = Input { Value = 0.0, },
793 TopLeftBlue = Input { Value = 0.0, },
794 TopRightRed = Input { Value = 0.0, },
795 TopRightGreen = Input { Value = 1.0, },
796 TopRightBlue = Input { Value = 0.0, },
797 },
798 },
799 Dent1 = Dent {
800 Inputs = {
801 Input = Input { SourceOp = "BG1", Source = "Output", },
802 Center = Input { Value = { 0.5, 0.5 }, },
803 Size = Input { Value = 0.65, },
804 Strength = Input { Value = 0.75, },
805 Type = Input { Value = 0, },
806 },
807 },
808 },
809 }"#;
810 let comp = Comp::from_fusion_str(src).unwrap();
811 let Ok(mut eng) = Engine::new_headless() else {
812 return;
813 };
814 let (tex, _) = eng.evaluate(&comp, comp.find_node("Dent1").unwrap(), 0.0);
815 let px = eng.readback_rgba(&tex).unwrap();
816 // Just right of center (x=72, r~0.066): new_r = r - 0.75*(0.325 - r) < 0,
817 // so it samples the LEFT (red-dominant) side!
818 let right_near = (64 * 128 + 72) * 4;
819 assert!(
820 px[right_near] > px[right_near + 1] + 40,
821 "Dent Type=0 should invert radially near center: {:?}",
822 &px[right_near..right_near + 4]
823 );
824 }
825
826 #[test]
827 fn test_dent_sine_falls_off_linearly_from_strength_at_center() {
828 let src = r#"Composition {
829 CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 },
830 Tools = ordered() {
831 BG1 = Background { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, },
832 Type = Input { Value = FuID { "Horizontal" }, },
833 TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, },
834 TopRightRed = Input { Value = 0, }, TopRightGreen = Input { Value = 1, }, TopRightBlue = Input { Value = 0, }, TopRightAlpha = Input { Value = 1, }, }, },
835 Dent1 = Dent { Inputs = { Input = Input { SourceOp = "BG1", Source = "Output", },
836 Center = Input { Value = { 0.5, 0.5 }, }, Size = Input { Value = 0.5, },
837 Strength = Input { Value = 0.5, }, Type = Input { Value = 1, }, }, },
838 },
839 }"#;
840 let comp = Comp::from_fusion_str(src).unwrap();
841 let Ok(mut eng) = Engine::new_headless() else {
842 return;
843 };
844 let (tex, _) = eng.evaluate(&comp, comp.find_node("Dent1").unwrap(), 0.0);
845 let px = eng.readback_rgba(&tex).unwrap();
846 // x=72 (r=0.066 of the 0.25 radius): new_r = r - 0.5 * (1 - r / R) = -0.30 -> source at x=0.20,
847 // so the gradient reads ~80% red / ~20% green.
848 let i = (64 * 128 + 72) * 4;
849 assert!(px[i].abs_diff(204) < 8 && px[i + 1].abs_diff(51) < 8, "got {:?}", &px[i..i + 4]);
850 }
851
852 #[test]
853 fn test_drip_out_of_bounds_edges_transparent() {
854 let src = r#"Composition {
855 CurrentTime = 0,
856 RenderRange = { 0, 0 },
857 GlobalRange = { 0, 0 },
858 Tools = ordered() {
859 BG1 = Background {
860 Inputs = {
861 Width = Input { Value = 128, },
862 Height = Input { Value = 128, },
863 TopLeftRed = Input { Value = 1.0, },
864 TopLeftGreen = Input { Value = 1.0, },
865 TopLeftBlue = Input { Value = 1.0, },
866 TopLeftAlpha = Input { Value = 1.0, },
867 },
868 },
869 Drip1 = Drip {
870 Inputs = {
871 Input = Input { SourceOp = "BG1", Source = "Output", },
872 Center = Input { Value = { 0.5, 0.5 }, },
873 Amplitude = Input { Value = 0.5, },
874 Frequency = Input { Value = 1.0, },
875 Phase = Input { Value = 0.25, },
876 Dampening = Input { Value = 0.0, },
877 Shape = Input { Value = 1, },
878 },
879 },
880 },
881 }"#;
882 let comp = Comp::from_fusion_str(src).unwrap();
883 let Ok(mut eng) = Engine::new_headless() else { return; };
884 let (tex, _) = eng.evaluate(&comp, comp.find_node("Drip1").unwrap(), 0.0);
885 let px = eng.readback_rgba(&tex).unwrap();
886 // Corner samples outside [0, 1] -> transparent black (Canvas edges=0).
887 assert_eq!(&px[0..4], &[0, 0, 0, 0], "out-of-bounds Drip UV must be transparent");
888 // Center stays white (raw_rel=0 -> disp=0).
889 let c = (64 * 128 + 64) * 4;
890 assert_eq!(&px[c..c + 4], &[255, 255, 255, 255]);
891 }
892
893 #[test]
894 fn test_perspective_positioner() {
895 let src = r#"{
896 Tools = ordered() {
897 Bg1 = Background {
898 Inputs = {
899 Width = Input { Value = 64, },
900 Height = Input { Value = 64, },
901 Type = Input { Value = FuID { "Horizontal" }, },
902 TopLeftRed = Input { Value = 1, },
903 TopRightRed = Input { Value = 0, },
904 TopRightBlue = Input { Value = 1, },
905 },
906 },
907 PP_Lin = PerspectivePositioner {
908 Inputs = {
909 TopLeft = Input { Value = { 0.25, 0.75 }, },
910 TopRight = Input { Value = { 0.75, 0.75 }, },
911 BottomLeft = Input { Value = { 0.25, 0.25 }, },
912 BottomRight = Input { Value = { 0.75, 0.25 }, },
913 Input = Input { SourceOp = "Bg1", Source = "Output", },
914 },
915 },
916 },
917 }"#;
918 let comp = Comp::from_fusion_str(src).unwrap();
919 let Ok(mut eng) = Engine::new_headless() else { return; };
920 let (t_pp, _) = eng.evaluate(&comp, comp.find_node("PP_Lin").unwrap(), 0.0);
921 let px_pp = eng.readback_rgba(&t_pp).unwrap();
922 let p0 = &px_pp[0..4];
923 assert!(p0[0] > 165 && p0[2] > 40 && p0[2] < 90, "got {p0:?}");
924 }
925
926 #[test]
927 fn test_day_sky_and_grid_warp() {
928 let src = r#"{
929 Tools = ordered() {
930 DS1 = DaySky {
931 Inputs = {
932 Width = Input { Value = 64, },
933 Height = Input { Value = 64, },
934 Latitude = Input { Value = 37.0, },
935 Longitude = Input { Value = 0.0, },
936 Time = Input { Value = 12.0, },
937 Exposure = Input { Value = 1.0, },
938 },
939 },
940 BgW = Background {
941 Inputs = {
942 Width = Input { Value = 64, },
943 Height = Input { Value = 64, },
944 Type = Input { Value = FuID { "Horizontal" }, },
945 TopLeftRed = Input { Value = 1, },
946 TopRightGreen = Input { Value = 1, },
947 },
948 },
949 GW1 = GridWarp {
950 Inputs = {
951 SrcGridChange = Input {
952 Value = Mesh {
953 Columns = 2, Rows = 2,
954 DeltaC = 1, DeltaR = 1,
955 Center = { 0, 0 },
956 Corners = { -0.5, -0.5, 0.5, 0.5 },
957 Points = {
958 { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 },
959 { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 },
960 },
961 },
962 },
963 DstGridChange = Input {
964 Value = Mesh {
965 Columns = 2, Rows = 2,
966 DeltaC = 1, DeltaR = 1,
967 Center = { 0, 0 },
968 Corners = { -0.5, -0.5, 0.5, 0.5 },
969 Points = {
970 { X = -0.5, Y = -0.5 }, { X = 0.5, Y = -0.5 },
971 { X = -0.5, Y = 0.5 }, { X = 0.5, Y = 0.5 },
972 },
973 },
974 },
975 Input = Input { SourceOp = "BgW", Source = "Output", },
976 },
977 },
978 },
979 }"#;
980 let comp = Comp::from_fusion_str(src).unwrap();
981 let Ok(mut eng) = Engine::new_headless() else { return; };
982 let (t_ds, _) = eng.evaluate(&comp, comp.find_node("DS1").unwrap(), 0.0);
983 let px_ds = eng.readback_rgba(&t_ds).unwrap();
984 // Zenith row (y=0) is sky blue (B > R), horizon (y=63) is brighter haze
985 let zen = &px_ds[(0 * 64 + 32) * 4..(0 * 64 + 32) * 4 + 4];
986 let hor = &px_ds[(62 * 64 + 32) * 4..(62 * 64 + 32) * 4 + 4];
987 assert!(zen[2] > zen[0] && zen[3] == 255, "zen={zen:?}");
988 assert!(hor[0] > zen[0], "hor={hor:?} zen={zen:?}");
989
990 let (t_bg, _) = eng.evaluate(&comp, comp.find_node("BgW").unwrap(), 0.0);
991 let (t_gw, _) = eng.evaluate(&comp, comp.find_node("GW1").unwrap(), 0.0);
992 let px_bg = eng.readback_rgba(&t_bg).unwrap();
993 let px_gw = eng.readback_rgba(&t_gw).unwrap();
994 let mae: f64 = px_bg.iter().zip(&px_gw).map(|(a, b)| (*a as f64 - *b as f64).abs()).sum::<f64>()
995 / px_bg.len() as f64;
996 assert!(mae < 1.5, "identity GridWarp should match source, mae={mae}");
997 }
998}
crates/engine/src/shaders/archive_fx.wgsl+1-1
......@@ -52,7 +52,7 @@ fn drip_op(@builtin(global_invocation_id) gid: vec3<u32>) {
5252 let disp = sin((dist * freq - phase) * 6.28318530718) * amp * falloff;
5353 src_fu = fu + raw_rel * disp;
5454 }
55 let warped = sample_edges(src_a, src_fu, 2);
55 let warped = sample_edges(src_a, src_fu, 0);
5656
5757 let m = read_mask(gid.xy, dims, u.p[2].z, u.p[2].w) * blend;
5858 store_dst(vec2<i32>(gid.xy), mix(orig, warped, clamp(m, 0.0, 1.0)));