Skip to main content

ultrafast_ops/
ops.rs

1//! Op registry: how each document op maps onto the Slang op library, which
2//! image ports it has, and how its params pack into the fixed-size float
3//! block the shader reads.
4//!
5//! Packing runs every frame for animated groups, so it is plain arithmetic
6//! into a reused buffer.
7
8use crate::OpsError;
9use ultrafast_graph::{Format, Node, Param};
10
11pub use ultrafast_geom::{Affine, parse_hex, srgb_to_linear, text};
12
13/// How an op participates in code generation.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Form {
16    /// `g_<fn>(ctx, o)`: produces a color from a position.
17    Gen,
18    /// `g_<fn>(ctx, o, T)`: like `Gen`, sampling an external resource texture.
19    GenResource,
20    /// `f_<fn>(ctx, inputs..., o)`: combines inputs evaluated at the same ctx.
21    Map,
22    /// `w_<fn>(ctx, o)`: remaps the context its single input is evaluated in.
23    Warp,
24    /// Evaluates `map` at ctx, then `source` at a displaced ctx.
25    Displace,
26    /// Multi-tap op that must read materialized textures (blur).
27    Blur,
28    /// Agent-written Slang. Inputs are materialized and sampled freely.
29    Custom,
30    /// Vector geometry rasterized by the GPU coverage rasterizer (paths,
31    /// text). Absorbs downstream transforms so geometry stays sharp.
32    Raster,
33    /// Scene data (meshes, lights, cameras): not an image. Consumed by
34    /// `render3d`.
35    Object,
36    /// Renders connected 3D objects into an image.
37    Render3D,
38    /// Deterministic particle system drawn as sprites.
39    Particles,
40    /// Stateful simulation stepped once per frame (fluid, feedback):
41    /// materialized, with its own persistent state textures.
42    Sim,
43}
44
45#[derive(Debug)]
46pub struct OpDef {
47    /// Document op name.
48    pub name: &'static str,
49    /// Slang function suffix (`g_`/`f_`/`w_` + this).
50    pub func: &'static str,
51    pub form: Form,
52    /// Image input ports, in evaluation order.
53    pub ports: &'static [&'static str],
54    /// Packed param floats.
55    pub params: usize,
56}
57
58macro_rules! op {
59    ($name:literal, $func:literal, $form:ident, [$($p:literal),*], $n:expr) => {
60        OpDef { name: $name, func: $func, form: Form::$form, ports: &[$($p),*], params: $n }
61    };
62}
63
64pub static OPS: &[OpDef] = &[
65    op!("solid", "solid", Gen, [], 4),
66    op!("gradient", "gradient_linear", Gen, [], GRADIENT_PARAMS),
67    op!("gradient", "gradient_radial", Gen, [], GRADIENT_PARAMS),
68    op!("gradient", "gradient_conic", Gen, [], GRADIENT_PARAMS),
69    op!("shape", "shape", Gen, [], 13),
70    op!("checker", "checker", Gen, [], 9),
71    op!("noise", "noise", Gen, [], 14),
72    op!("image", "image", GenResource, [], 10),
73    op!("video", "image", GenResource, [], 10),
74    op!("opacity", "opacity", Map, ["source"], 1),
75    op!("over", "over", Map, ["fg", "bg"], 2),
76    op!("blend", "blend", Map, ["fg", "bg"], 3),
77    op!("composite", "composite", Map, ["fg", "bg"], 1),
78    op!("mask", "mask", Map, ["source", "matte"], 1),
79    op!("mix", "mix", Map, ["a", "b"], 1),
80    op!("adjust", "adjust", Map, ["source"], 6),
81    op!("levels", "levels", Map, ["source"], 5),
82    op!("color_matrix", "color_matrix", Map, ["source"], 20),
83    op!("lut", "lut", Map, ["source"], 3),
84    op!("invert", "invert", Map, ["source"], 1),
85    op!("tint", "tint", Map, ["source"], 8),
86    op!("threshold", "threshold", Map, ["source"], 2),
87    op!("crop", "crop", Map, ["source"], 5),
88    op!("transform", "transform", Warp, ["source"], 7),
89    op!("corner_pin", "corner_pin", Warp, ["source"], 10),
90    op!("wave", "wave", Warp, ["source"], 4),
91    op!("twirl", "twirl", Warp, ["source"], 4),
92    op!("tile", "tile", Warp, ["source"], 4),
93    op!("displace", "displace", Displace, ["source", "map"], 2),
94    op!("blur", "blur", Blur, ["source"], 4),
95    op!("shader", "shader", Custom, ["in0", "in1", "in2", "in3"], 17),
96    op!("path", "path", Raster, [], 5),
97    op!("text", "text", Raster, [], 5),
98    op!("mesh", "mesh", Object, ["texture"], 0),
99    op!("light", "light", Object, [], 0),
100    op!("camera", "camera", Object, [], 0),
101    // Sound: mixed into exports, not part of the image graph.
102    op!("audio", "audio", Object, [], 0),
103    op!("render3d", "render3d", Render3D, ["*"], 0),
104    op!("particles", "particles", Particles, ["sprite"], 0),
105    op!("swarm", "particles", Particles, [], 0),
106    op!("fluid", "fluid", Sim, ["dye", "stir"], 0),
107    op!("feedback", "feedback", Sim, ["in0", "in1", "in2", "in3"], 0),
108];
109
110/// Ops whose kernel variant depends on a param.
111pub fn resolve(id: &str, node: &Node) -> Result<&'static OpDef, OpsError> {
112    // Only gradients pick among several kernels by param; every other op
113    // name maps to exactly one definition.
114    let func = match node.op.as_str() {
115        "gradient" => Some(match text(node, "kind").unwrap_or("linear") {
116            "linear" => "gradient_linear",
117            "radial" => "gradient_radial",
118            "conic" => "gradient_conic",
119            other => {
120                return Err(bad(id, "kind", format!("unknown gradient kind `{other}`")));
121            }
122        }),
123        _ => None,
124    };
125    OPS.iter()
126        .find(|d| d.name == node.op && func.is_none_or(|f| d.func == f))
127        .ok_or_else(|| OpsError::UnknownOp {
128            node: id.to_string(),
129            op: node.op.clone(),
130        })
131}
132
133/// Ports actually connected for this node. Custom shaders take any subset
134/// of their ports; every other op requires all of them.
135pub fn connected_ports(def: &OpDef, id: &str, node: &Node) -> Result<Vec<String>, OpsError> {
136    // `*`: any input names (render3d takes any number of objects).
137    if def.ports == ["*"] {
138        return Ok(node.inputs.keys().cloned().collect());
139    }
140    let mut out = Vec::new();
141    for p in def.ports {
142        if node.inputs.contains_key(*p) {
143            out.push(p.to_string());
144        } else if !matches!(def.form, Form::Custom | Form::Object | Form::Particles | Form::Sim) {
145            return Err(OpsError::MissingPort {
146                node: id.to_string(),
147                port: p.to_string(),
148            });
149        }
150    }
151    Ok(out)
152}
153
154/// Ops that sample an external resource texture (bound after their inputs).
155pub fn uses_resource(def: &OpDef) -> bool {
156    def.form == Form::GenResource || def.name == "lut"
157}
158
159/// Extra identity that changes the generated code (beyond op and wiring).
160pub fn variant_key(def: &OpDef, node: &Node) -> String {
161    match def.form {
162        Form::Custom | Form::Sim => text(node, "code").unwrap_or("").to_string(),
163        // Resource identity: kind and source. Video decoders are per node
164        // (each node has its own playhead).
165        Form::GenResource => format!("{}:{}", node.op, text(node, "src").unwrap_or("")),
166        _ if uses_resource(def) => format!("{}:{}", node.op, text(node, "src").unwrap_or("")),
167        _ => String::new(),
168    }
169}
170
171/// The input an inactive node (outside its timing window) passes through:
172/// the destination of a composite, the source of an effect. Generators have
173/// none and go transparent. This gives layer semantics: a layer outside its
174/// window leaves what is under it untouched. `connected` is the number of
175/// connected inputs (custom shaders may leave ports open).
176pub fn passthrough(def: &OpDef, connected: usize) -> Option<usize> {
177    // Simulations show nothing outside their window (their state holds);
178    // particles neither (their input is a sprite, not a layer to show).
179    if matches!(def.form, Form::Sim | Form::Particles) {
180        return None;
181    }
182    let i = match def.name {
183        "over" | "blend" | "composite" => 1,
184        _ => 0,
185    };
186    (i < connected).then_some(i)
187}
188
189/// A shader node's `resolution` below 1: it renders at that fraction of
190/// the frame size and is upscaled (for soft, expensive procedural looks).
191pub fn render_scale(node: &Node) -> Option<f64> {
192    if node.op != "shader" {
193        return None;
194    }
195    let r = node.params.get("resolution")?.eval(0.0)?.first().copied()?;
196    (r < 0.999).then_some(r.clamp(0.1, 1.0))
197}
198
199/// A shader that asks to be sampled under motion blur (`motion_blur:
200/// true`: it moves things), instead of holding at the frame's time.
201pub fn samples_motion(node: &Node) -> bool {
202    matches!(node.params.get("motion_blur"), Some(Param::Bool(true)))
203}
204
205/// Ops whose output changes with time even when no param is animated.
206pub fn time_varying(def: &OpDef, node: &Node) -> bool {
207    def.name == "video"
208        || def.name == "particles"
209        || def.name == "swarm"
210        || def.form == Form::Sim
211        // A shader that reads the clock animates by itself.
212        || (def.name == "shader" && text(node, "code").is_some_and(|c| c.contains("time(")))
213        || (def.name == "image" && text(node, "src").is_some_and(|s| s.contains("{frame")))
214}
215
216/// Resolves an image-sequence path: `{frame}` or `{frame:05}` becomes the
217/// frame number at local time `t` (`fps` param, default the document's).
218pub fn sequence_path(src: &str, node: &Node, t: f64, doc_fps: f64) -> String {
219    let Some(start) = src.find("{frame") else {
220        return src.to_string();
221    };
222    let Some(end) = src[start..].find('}').map(|e| start + e) else {
223        return src.to_string();
224    };
225    let fps = Packer { id: "", node, t }.num("fps", doc_fps);
226    let first = Packer { id: "", node, t }.num("first_frame", 0.0);
227    // Local times land a hair under a frame boundary after offsets
228    // ((t - offset) * fps = 9.999999...): count those as the boundary.
229    let frame = ((t * fps + 1e-6).floor() + first).max(0.0) as u64;
230    let spec = &src[start + 6..end];
231    let width: usize = spec
232        .strip_prefix(':')
233        .and_then(|w| w.trim_start_matches('0').parse().ok())
234        .unwrap_or(0);
235    format!("{}{:0width$}{}", &src[..start], frame, &src[end + 1..], width = width)
236}
237
238/// Source time of a `video` node at composition time `t`: the `time` param
239/// if set (animate it for time remapping), else `start + t * speed`.
240/// `loop` wraps at the source duration; otherwise the last frame holds.
241pub fn video_time(node: &Node, t: f64, duration: f64) -> f64 {
242    let p = Packer { id: "", node, t };
243    let raw = if node.params.contains_key("time") {
244        p.num("time", 0.0)
245    } else {
246        p.num("start", 0.0) + t * p.num("speed", 1.0)
247    };
248    let looping = matches!(node.params.get("loop"), Some(Param::Bool(true)));
249    if looping && duration > 0.0 {
250        raw.rem_euclid(duration)
251    } else {
252        raw.clamp(0.0, duration.max(0.0))
253    }
254}
255
256/// Size of a resource the op samples, needed to pack placement params.
257#[derive(Debug, Clone, Copy)]
258pub struct ResourceInfo {
259    pub width: u32,
260    pub height: u32,
261}
262
263pub fn pack(
264    def: &OpDef,
265    id: &str,
266    node: &Node,
267    fmt: &Format,
268    t: f64,
269    res: Option<ResourceInfo>,
270    out: &mut Vec<f32>,
271) -> Result<(), OpsError> {
272    let start = out.len();
273    let (w, h) = (fmt.width as f64, fmt.height as f64);
274    let center = [w / 2.0, h / 2.0];
275    let p = Packer { id, node, t };
276    match def.func {
277        "solid" => p.color(out, "color", [0.0, 0.0, 0.0, 1.0])?,
278        "gradient_linear" | "gradient_radial" | "gradient_conic" => {
279            let (a, b) = if def.func == "gradient_radial" {
280                ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])
281            } else {
282                ([0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0])
283            };
284            p.gradient(out, def.func, a, b, center, h)?;
285        }
286        "shape" => {
287            p.color(out, "color", [1.0, 1.0, 1.0, 1.0])?;
288            fade(out, p.num("opacity", 1.0));
289            p.vec(out, "center", &center);
290            // `scale` about the center scales the size, corners and stroke.
291            let sc = p.vecn("scale", &[1.0, 1.0]);
292            let k = (sc[0].abs() + sc[1].abs()) / 2.0;
293            let size = p.vecn("size", &[w / 4.0, w / 4.0]);
294            out.extend([
295                (size[0] * sc[0].abs() / 2.0) as f32,
296                (size[1] * sc[1].abs() / 2.0) as f32,
297            ]);
298            out.push((p.num("radius", 0.0) * k) as f32);
299            let ellipse = match text(node, "kind").unwrap_or("rect") {
300                "rect" => false,
301                "ellipse" | "circle" => true,
302                other => return Err(bad(id, "kind", format!("unknown shape kind `{other}`"))),
303            };
304            out.push(ellipse as u8 as f32);
305            p.vec(out, "softness", &[1.0]);
306            out.push(p.num("rotation", 0.0).to_radians() as f32);
307            out.push((p.num("stroke", 0.0) * k) as f32);
308        }
309        "checker" => {
310            p.color(out, "a", [0.2, 0.2, 0.2, 1.0])?;
311            p.color(out, "b", [0.4, 0.4, 0.4, 1.0])?;
312            p.vec(out, "size", &[32.0]);
313        }
314        "noise" => {
315            p.color(out, "a", [0.0, 0.0, 0.0, 1.0])?;
316            p.color(out, "b", [1.0, 1.0, 1.0, 1.0])?;
317            p.vec(out, "scale", &[200.0, 200.0]);
318            p.vec(out, "offset", &[0.0, 0.0]);
319            p.vec(out, "evolution", &[0.0]);
320            p.vec(out, "octaves", &[4.0]);
321        }
322        "image" => {
323            let (rect, window) = placement(&p, w, h, res)?;
324            out.extend(rect.iter().map(|x| *x as f32));
325            out.push(p.num("opacity", 1.0) as f32);
326            out.push(space(id, node)?);
327            out.extend(window.iter().map(|x| *x as f32));
328        }
329        "opacity" => out.push(p.num("opacity", 1.0) as f32),
330        "over" => {
331            out.push(p.num("opacity", 1.0) as f32);
332            out.push(space(id, node)?);
333        }
334        "blend" => {
335            let mode = text(node, "mode").unwrap_or("normal");
336            let m = BLEND_MODES
337                .iter()
338                .position(|n| *n == mode)
339                .ok_or_else(|| bad(id, "mode", format!("unknown blend mode `{mode}`")))?;
340            out.push(m as f32);
341            out.push(p.num("opacity", 1.0) as f32);
342            out.push(space(id, node)?);
343        }
344        "composite" => {
345            let op = text(node, "operator").unwrap_or("over");
346            let i = ["in", "out", "atop", "xor", "plus", "over"]
347                .iter()
348                .position(|n| *n == op)
349                .ok_or_else(|| bad(id, "operator", format!("unknown operator `{op}`")))?;
350            out.push(i as f32);
351        }
352        "mask" => out.push(match text(node, "mode").unwrap_or("alpha") {
353            "alpha" => 0.0,
354            "alpha_inverted" | "inverted" => 1.0,
355            "luma" => 2.0,
356            "luma_inverted" => 3.0,
357            other => return Err(bad(id, "mode", format!("unknown mask mode `{other}`"))),
358        }),
359        "mix" => out.push(p.num("t", 0.5) as f32),
360        "adjust" => {
361            out.push(p.num("exposure", 0.0) as f32);
362            out.push(p.num("contrast", 1.0) as f32);
363            out.push(p.num("saturation", 1.0) as f32);
364            out.push(p.num("hue", 0.0).to_radians() as f32);
365            out.push(p.num("brightness", 0.0) as f32);
366            out.push(p.num("gamma", 1.0) as f32);
367        }
368        "levels" => {
369            for (name, d) in [
370                ("in_black", 0.0),
371                ("in_white", 1.0),
372                ("gamma", 1.0),
373                ("out_black", 0.0),
374                ("out_white", 1.0),
375            ] {
376                out.push(p.num(name, d) as f32);
377            }
378        }
379        "color_matrix" => {
380            let mut ident = vec![0.0; 20];
381            for i in 0..4 {
382                ident[i * 5 + i] = 1.0;
383            }
384            p.vec(out, "matrix", &ident);
385        }
386        "invert" => out.push(p.num("amount", 1.0) as f32),
387        "lut" => {
388            out.push(p.num("amount", 1.0) as f32);
389            out.push(res.map(|r| r.height as f32).unwrap_or(0.0));
390            out.push(match text(node, "space").unwrap_or("srgb") {
391                "srgb" => 0.0,
392                "linear" => 1.0,
393                o => return Err(bad(id, "space", format!("unknown space `{o}` (srgb | linear)"))),
394            });
395        }
396        "tint" => {
397            p.color(out, "dark", [0.0, 0.0, 0.0, 1.0])?;
398            p.color(out, "light", [1.0, 1.0, 1.0, 1.0])?;
399        }
400        "threshold" => {
401            out.push(p.num("level", 0.5) as f32);
402            out.push(p.num("softness", 0.01) as f32);
403        }
404        "crop" => {
405            p.vec(out, "rect", &[0.0, 0.0, w, h]);
406            p.vec(out, "softness", &[1.0]);
407        }
408        "transform" => {
409            let pos = p.vecn("position", &center);
410            let anchor = p.vecn("anchor", &center);
411            let scale = p.vecn("scale", &[1.0, 1.0]);
412            let rot = p.num("rotation", 0.0).to_radians();
413            let skew = p.num("skew", 0.0).to_radians();
414            // Forward: p' = T(pos) * R * K(skew) * S * T(-anchor) * p. Pack the inverse.
415            let m = Affine::translate(pos[0], pos[1])
416                .mul(Affine::rotate(rot))
417                .mul(Affine::skew_x(skew))
418                .mul(Affine::scale(scale[0], scale[1]))
419                .mul(Affine::translate(-anchor[0], -anchor[1]));
420            let inv = m
421                .inverse()
422                .ok_or_else(|| bad(id, "scale", "transform is not invertible (zero scale)".into()))?;
423            out.extend(inv.0.iter().map(|x| *x as f32));
424            out.push(inv.det().abs().sqrt() as f32);
425        }
426        "corner_pin" => {
427            let c = p.vecn("corners", &[0.0, 0.0, w, 0.0, w, h, 0.0, h]);
428            let src = p.vecn("source_rect", &[0.0, 0.0, w, h]);
429            let from = [
430                [src[0], src[1]],
431                [src[0] + src[2], src[1]],
432                [src[0] + src[2], src[1] + src[3]],
433                [src[0], src[1] + src[3]],
434            ];
435            let to = [[c[0], c[1]], [c[2], c[3]], [c[4], c[5]], [c[6], c[7]]];
436            // Homography dest -> source, so the shader maps output to input.
437            let hm = homography(&to, &from).ok_or_else(|| bad(id, "corners", "corners are degenerate".into()))?;
438            out.extend(hm.iter().map(|x| *x as f32));
439            let area = |q: &[[f64; 2]; 4]| {
440                let mut a = 0.0;
441                for i in 0..4 {
442                    let (p0, p1) = (q[i], q[(i + 1) % 4]);
443                    a += p0[0] * p1[1] - p1[0] * p0[1];
444                }
445                (a / 2.0).abs()
446            };
447            out.push((area(&from) / area(&to).max(1e-6)).sqrt() as f32);
448        }
449        "wave" => {
450            out.push(p.num("amplitude", 10.0) as f32);
451            out.push(p.num("wavelength", 100.0) as f32);
452            out.push(p.num("phase", 0.0).to_radians() as f32);
453            out.push(p.num("direction", 0.0).to_radians() as f32);
454        }
455        "twirl" => {
456            p.vec(out, "center", &center);
457            out.push(p.num("radius", w.min(h) / 2.0) as f32);
458            out.push(p.num("angle", 90.0).to_radians() as f32);
459        }
460        "tile" => {
461            p.vec(out, "origin", &[0.0, 0.0]);
462            p.vec(out, "size", &[w, h]);
463        }
464        "displace" => p.vec(out, "amount", &[20.0, 20.0]),
465        "blur" => {
466            // Packed per pass by the executor (direction varies).
467            out.extend([p.num("radius", 8.0) as f32, 1.0, 0.0, 0.0]);
468        }
469        // Scene objects are read directly by the 3D pass.
470        "mesh" | "light" | "camera" | "render3d" | "audio" | "particles" | "swarm" | "fluid" | "feedback" => {}
471        "shader" => {
472            let mut u = p.vecn("u", &[0.0; 16]);
473            for (i, slot) in u.iter_mut().enumerate() {
474                const U: [&str; 16] = [
475                    "u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7", "u8", "u9", "u10", "u11", "u12", "u13", "u14",
476                    "u15",
477                ];
478                if let Some(v) = node.params.get(U[i]).and_then(|v| v.eval_vals(t)) {
479                    *slot = v.first().copied().unwrap_or(0.0);
480                }
481            }
482            out.extend(u.iter().map(|x| *x as f32));
483            // The node's local time (components and timing shift it).
484            out.push(t as f32);
485        }
486        "path" | "text" => {
487            p.color(out, "color", [1.0, 1.0, 1.0, 1.0])?;
488            fade(out, p.num("opacity", 1.0));
489            out.push(match text(node, "fill_rule").unwrap_or("nonzero") {
490                "nonzero" => 0.0,
491                "evenodd" => 1.0,
492                o => return Err(bad(id, "fill_rule", format!("unknown fill rule `{o}`"))),
493            });
494        }
495        other => unreachable!("no packer for {other}"),
496    }
497    debug_assert_eq!(out.len() - start, def.params, "param block size for {}", def.func);
498    Ok(())
499}
500
501/// Fades the premultiplied color just packed by `opacity`.
502fn fade(out: &mut [f32], opacity: f64) {
503    let k = opacity.clamp(0.0, 1.0) as f32;
504    let n = out.len();
505    for v in &mut out[n - 4..] {
506        *v *= k;
507    }
508}
509
510/// Forward matrix of a `transform` node:
511/// p' = T(position) * R(rotation) * K(skew) * S(scale) * T(-anchor) * p.
512pub fn transform_affine(node: &Node, fmt: &Format, t: f64) -> Affine {
513    let p = Packer { id: "", node, t };
514    let center = [fmt.width as f64 / 2.0, fmt.height as f64 / 2.0];
515    let pos = p.vecn("position", &center);
516    let anchor = p.vecn("anchor", &center);
517    let scale = p.vecn("scale", &[1.0, 1.0]);
518    let rot = p.num("rotation", 0.0).to_radians();
519    let skew = p.num("skew", 0.0).to_radians();
520    Affine::translate(pos[0], pos[1])
521        .mul(Affine::rotate(rot))
522        .mul(Affine::skew_x(skew))
523        .mul(Affine::scale(scale[0], scale[1]))
524        .mul(Affine::translate(-anchor[0], -anchor[1]))
525}
526
527/// The placement params of a `shape` ([`shape_motion_px`] measures them).
528pub const SHAPE_PLACEMENT: &[&str] = &["center", "size", "scale", "rotation", "radius", "stroke", "softness"];
529
530/// How far (px, an upper bound) a `shape` node's edges move between local
531/// times l0 and l1 through its placement params.
532pub fn shape_motion_px(node: &Node, fmt: &Format, l0: f64, l1: f64) -> f64 {
533    let (w, h) = (fmt.width as f64, fmt.height as f64);
534    let at = |t: f64| {
535        let p = Packer { id: "", node, t };
536        let c = p.vecn("center", &[w / 2.0, h / 2.0]);
537        let s = p.vecn("size", &[w / 4.0, w / 4.0]);
538        let k = p.vecn("scale", &[1.0, 1.0]);
539        let half = [(s[0] * k[0]).abs() / 2.0, (s[1] * k[1]).abs() / 2.0];
540        let extra = [p.num("radius", 0.0), p.num("stroke", 0.0), p.num("softness", 1.0)];
541        (c, half, p.num("rotation", 0.0).to_radians(), extra)
542    };
543    let (c0, e0, r0, x0) = at(l0);
544    let (c1, e1, r1, x1) = at(l1);
545    (c1[0] - c0[0]).hypot(c1[1] - c0[1])
546        + (e1[0] - e0[0]).abs().max((e1[1] - e0[1]).abs())
547        + (r1 - r0).abs() * e0[0].hypot(e0[1]).max(e1[0].hypot(e1[1]))
548        + x0.iter().zip(&x1).map(|(a, b)| (a - b).abs()).sum::<f64>()
549}
550
551/// How far (px, an upper bound) a `wave` node's displacement changes
552/// between local times l0 and l1 through its amplitude and phase.
553pub fn wave_motion_px(node: &Node, l0: f64, l1: f64) -> f64 {
554    let at = |t: f64| {
555        let p = Packer { id: "", node, t };
556        (p.num("amplitude", 10.0), p.num("phase", 0.0).to_radians())
557    };
558    let ((a0, p0), (a1, p1)) = (at(l0), at(l1));
559    (a1 - a0).abs() + a0.abs().max(a1.abs()) * (p1 - p0).abs()
560}
561
562/// Axis-aligned bounds (x0, y0, x1, y1) of where a node can be non-transparent.
563pub type Rect = [f64; 4];
564pub const UNBOUNDED: Rect = [-1e9, -1e9, 1e9, 1e9];
565pub const EMPTY: Rect = [1e9, 1e9, -1e9, -1e9];
566
567fn union(a: Rect, b: Rect) -> Rect {
568    [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]
569}
570
571fn intersect(a: Rect, b: Rect) -> Rect {
572    [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]
573}
574
575/// Ops whose fg input is guarded by its bounds in fused kernels: pixels
576/// outside skip evaluating the fg subtree entirely.
577pub fn guarded(def: &OpDef) -> bool {
578    matches!(def.name, "over" | "blend")
579}
580
581/// Where an image or video frame is drawn ([x, y, w, h] px) and the part
582/// of it that shows ([u0, v0, u1, v1]), by `fit` inside `rect` (a box) or
583/// the frame. A picture keeps its aspect ratio unless `fit` is "fill": in
584/// a box it defaults to "cover" (the box filled, the overflow cropped
585/// evenly), in the frame to "contain". A box of the picture's own shape
586/// draws it exactly there, as before.
587fn placement(p: &Packer, w: f64, h: f64, res: Option<ResourceInfo>) -> Result<([f64; 4], [f64; 4]), OpsError> {
588    let r = res.unwrap_or(ResourceInfo { width: 1, height: 1 });
589    let (iw, ih) = (r.width as f64, r.height as f64);
590    let boxed = p.node.params.contains_key("rect");
591    let b = if boxed {
592        let v = p.vecn("rect", &[0.0, 0.0, iw, ih]);
593        [v[0], v[1], v[2], v[3]]
594    } else {
595        [0.0, 0.0, w, h]
596    };
597    let whole = [0.0, 0.0, 1.0, 1.0];
598    let fit = text(p.node, "fit").unwrap_or(if boxed { "cover" } else { "contain" });
599    // Within 1%: rounding in a box sized for the picture never crops it.
600    let same_shape = res.is_some() && b[2] > 0.0 && b[3] > 0.0 && ((b[2] / b[3]) / (iw / ih) - 1.0).abs() < 1e-2;
601    let centered = |sw: f64, sh: f64| [b[0] + (b[2] - sw) / 2.0, b[1] + (b[3] - sh) / 2.0, sw, sh];
602    Ok(match fit {
603        "fill" => (b, whole),
604        _ if boxed && same_shape && fit != "none" => (b, whole),
605        "none" => (centered(iw, ih), whole),
606        "contain" => {
607            let s = (b[2] / iw).min(b[3] / ih);
608            (centered(iw * s, ih * s), whole)
609        }
610        // Without a box the frame crops the overflow; in a box the window does.
611        "cover" if !boxed => {
612            let s = (b[2] / iw).max(b[3] / ih);
613            (centered(iw * s, ih * s), whole)
614        }
615        "cover" => {
616            let s = (b[2] / iw).max(b[3] / ih);
617            let (u, v) = (b[2] / (iw * s), b[3] / (ih * s));
618            (b, [(1.0 - u) / 2.0, (1.0 - v) / 2.0, (1.0 + u) / 2.0, (1.0 + v) / 2.0])
619        }
620        other => return Err(bad(p.id, "fit", format!("unknown fit `{other}`"))),
621    })
622}
623
624/// Conservative bounds of a node's output in its own coordinate space,
625/// given its inputs' bounds. Anything unknown is unbounded.
626pub fn bounds(def: &OpDef, node: &Node, fmt: &Format, t: f64, inputs: &[Rect], res: Option<ResourceInfo>) -> Rect {
627    let p = Packer { id: "", node, t };
628    let (w, h) = (fmt.width as f64, fmt.height as f64);
629    let input = |i: usize| inputs.get(i).copied().unwrap_or(UNBOUNDED);
630    match def.func {
631        "shape" => {
632            let c = p.vecn("center", &[w / 2.0, h / 2.0]);
633            let sc = p.vecn("scale", &[1.0, 1.0]);
634            let size = p.vecn("size", &[w / 4.0, w / 4.0]);
635            let size = [size[0] * sc[0].abs(), size[1] * sc[1].abs()];
636            // Bounding circle of the (possibly rotated) shape, plus room for
637            // the stroke and antialiasing even under strong minification.
638            let r = (size[0] * size[0] + size[1] * size[1]).sqrt() / 2.0
639                + p.num("stroke", 0.0)
640                + p.num("softness", 1.0).max(1.0) * 8.0;
641            [c[0] - r, c[1] - r, c[0] + r, c[1] + r]
642        }
643        "image" => match (node.params.contains_key("rect"), text(node, "fit"), res) {
644            (true, Some("none"), Some(_)) => match placement(&p, w, h, res) {
645                Ok((r, _)) => [r[0] - 1.0, r[1] - 1.0, r[0] + r[2] + 1.0, r[1] + r[3] + 1.0],
646                Err(_) => UNBOUNDED,
647            },
648            (true, Some("none"), None) => UNBOUNDED,
649            (true, _, _) => {
650                let r = p.vecn("rect", &[0.0, 0.0, w, h]);
651                [r[0] - 1.0, r[1] - 1.0, r[0] + r[2] + 1.0, r[1] + r[3] + 1.0]
652            }
653            _ => UNBOUNDED,
654        },
655        "opacity" | "adjust" | "levels" | "invert" | "tint" | "threshold" => input(0),
656        "crop" => {
657            let r = p.vecn("rect", &[0.0, 0.0, w, h]);
658            intersect(input(0), [r[0] - 1.0, r[1] - 1.0, r[0] + r[2] + 1.0, r[1] + r[3] + 1.0])
659        }
660        "mask" => match text(node, "mode").unwrap_or("alpha") {
661            "alpha" | "luma" => intersect(input(0), input(1)),
662            _ => input(0),
663        },
664        "over" | "blend" | "mix" => union(input(0), input(1)),
665        "transform" => {
666            let b = input(0);
667            if b[0] <= -1e8 || b[0] > b[2] {
668                return b;
669            }
670            let m = transform_affine(node, fmt, t);
671            let pts = [(b[0], b[1]), (b[2], b[1]), (b[0], b[3]), (b[2], b[3])].map(|(x, y)| m.apply(x, y));
672            let xs = pts.map(|p| p.0);
673            let ys = pts.map(|p| p.1);
674            let f = |v: [f64; 4], min: bool| {
675                v.into_iter().fold(if min { f64::MAX } else { f64::MIN }, |a, b| {
676                    if min { a.min(b) } else { a.max(b) }
677                })
678            };
679            [
680                f(xs, true) - 2.0,
681                f(ys, true) - 2.0,
682                f(xs, false) + 2.0,
683                f(ys, false) + 2.0,
684            ]
685        }
686        _ => UNBOUNDED,
687    }
688}
689
690/// Gradient block: stop count, space, 4 geometry floats, 8 stops of
691/// (position, premultiplied rgba).
692pub const GRADIENT_PARAMS: usize = 6 + 8 * 5;
693
694/// Parses gradient stops: `"0:#ff0000, 0.5:#00ff0080, 1:#0000ff"`, or a
695/// flat vector of `[pos, r, g, b, a]` groups (sRGB, straight alpha).
696fn parse_stops(p: &Param, t: f64) -> Option<Vec<(f64, [f64; 4])>> {
697    match p {
698        Param::Text(s) => s
699            .split(',')
700            .map(|part| {
701                let (pos, col) = part.trim().split_once(':')?;
702                Some((pos.trim().parse().ok()?, parse_hex(col.trim())?))
703            })
704            .collect(),
705        p => {
706            let v = p.eval(t)?;
707            (v.len() % 5 == 0 && !v.is_empty())
708                .then(|| v.chunks_exact(5).map(|c| (c[0], [c[1], c[2], c[3], c[4]])).collect())
709        }
710    }
711}
712
713pub const BLEND_MODES: &[&str] = &[
714    "normal",
715    "multiply",
716    "screen",
717    "overlay",
718    "darken",
719    "lighten",
720    "color_dodge",
721    "color_burn",
722    "hard_light",
723    "soft_light",
724    "difference",
725    "exclusion",
726    "hue",
727    "saturation",
728    "color",
729    "luminosity",
730    "add",
731    "subtract",
732    "divide",
733];
734
735fn space(id: &str, node: &Node) -> Result<f32, OpsError> {
736    match text(node, "space").unwrap_or("linear") {
737        "linear" => Ok(0.0),
738        "srgb" => Ok(1.0),
739        other => Err(bad(id, "space", format!("unknown space `{other}` (linear | srgb)"))),
740    }
741}
742
743fn bad(id: &str, param: &str, reason: String) -> OpsError {
744    OpsError::BadParam {
745        node: id.to_string(),
746        param: param.to_string(),
747        reason,
748    }
749}
750
751struct Packer<'a> {
752    id: &'a str,
753    node: &'a Node,
754    t: f64,
755}
756
757impl Packer<'_> {
758    fn vecn(&self, name: &str, default: &[f64]) -> ultrafast_graph::Vals {
759        let mut v = self
760            .node
761            .params
762            .get(name)
763            .and_then(|p| p.eval_vals(self.t))
764            .unwrap_or_else(|| ultrafast_graph::Vals::from_slice(default));
765        // Broadcast a scalar to the expected width; pad or truncate otherwise.
766        if v.len() == 1 && default.len() > 1 {
767            v = ultrafast_graph::Vals::filled(v[0], default.len());
768        }
769        v.resize(default.len(), 0.0);
770        v
771    }
772
773    fn vec(&self, out: &mut Vec<f32>, name: &str, default: &[f64]) {
774        out.extend(self.vecn(name, default).into_iter().map(|x| x as f32));
775    }
776
777    fn num(&self, name: &str, default: f64) -> f64 {
778        self.vecn(name, &[default])[0]
779    }
780
781    /// Packs a gradient: stops (from `stops`, else `a`/`b`), interpolation
782    /// space, and geometry for the kind.
783    fn gradient(
784        &self,
785        out: &mut Vec<f32>,
786        func: &str,
787        a: [f64; 4],
788        b: [f64; 4],
789        center: [f64; 2],
790        h: f64,
791    ) -> Result<(), OpsError> {
792        let mut stops = match self.node.params.get("stops") {
793            Some(p) => parse_stops(p, self.t).ok_or_else(|| {
794                bad(
795                    self.id,
796                    "stops",
797                    "use \"pos:#rrggbb, ...\" or [pos, r, g, b, a, ...]".into(),
798                )
799            })?,
800            None => {
801                let mut ca = Vec::new();
802                let mut cb = Vec::new();
803                self.color_straight(&mut ca, "a", a)?;
804                self.color_straight(&mut cb, "b", b)?;
805                vec![(0.0, [ca[0], ca[1], ca[2], ca[3]]), (1.0, [cb[0], cb[1], cb[2], cb[3]])]
806            }
807        };
808        stops.sort_by(|x, y| x.0.partial_cmp(&y.0).unwrap());
809        stops.truncate(8);
810        let encoded = match text(self.node, "space").unwrap_or("linear") {
811            "linear" => false,
812            "srgb" => true,
813            o => return Err(bad(self.id, "space", format!("unknown space `{o}` (linear | srgb)"))),
814        };
815        out.push(stops.len() as f32);
816        out.push(encoded as u8 as f32);
817        match func {
818            "gradient_linear" => {
819                self.vec(out, "start", &[0.0, 0.0]);
820                self.vec(out, "end", &[0.0, h]);
821            }
822            "gradient_radial" => {
823                self.vec(out, "center", &center);
824                self.vec(out, "radius", &[center[0].max(center[1])]);
825                out.push(0.0);
826            }
827            _ => {
828                self.vec(out, "center", &center);
829                out.push(self.num("angle", 0.0).to_radians() as f32);
830                out.push(0.0);
831            }
832        }
833        for k in 0..8 {
834            let (pos, c) = stops.get(k).copied().unwrap_or((1.0, [0.0; 4]));
835            // Premultiplied, in the interpolation space.
836            let al = c[3].clamp(0.0, 1.0);
837            let ch = |x: f64| if encoded { x * al } else { srgb_to_linear(x) * al };
838            out.extend([pos as f32, ch(c[0]) as f32, ch(c[1]) as f32, ch(c[2]) as f32, al as f32]);
839        }
840        Ok(())
841    }
842
843    /// A document color as straight sRGB (no conversion).
844    fn color_straight(&self, out: &mut Vec<f64>, name: &str, default: [f64; 4]) -> Result<(), OpsError> {
845        let c = match self.node.params.get(name) {
846            None => default,
847            Some(Param::Text(s)) => parse_hex(s).ok_or_else(|| {
848                bad(
849                    self.id,
850                    name,
851                    format!("`{s}` is not a #rgb, #rrggbb or #rrggbbaa color"),
852                )
853            })?,
854            Some(p) => {
855                let v = p.eval(self.t).unwrap_or_default();
856                match v.len() {
857                    3 => [v[0], v[1], v[2], 1.0],
858                    4 => [v[0], v[1], v[2], v[3]],
859                    _ => return Err(bad(self.id, name, "color needs 3 or 4 components".into())),
860                }
861            }
862        };
863        out.extend(c);
864        Ok(())
865    }
866
867    /// Document colors are straight-alpha, sRGB-encoded: `[r,g,b(,a)]` in 0..1
868    /// or `#rrggbb(aa)`. The engine works in linear premultiplied.
869    fn color(&self, out: &mut Vec<f32>, name: &str, default: [f64; 4]) -> Result<(), OpsError> {
870        let c = match self.node.params.get(name) {
871            None => default,
872            Some(Param::Text(s)) => parse_hex(s).ok_or_else(|| {
873                bad(
874                    self.id,
875                    name,
876                    format!("`{s}` is not a #rgb, #rrggbb or #rrggbbaa color"),
877                )
878            })?,
879            Some(p) => {
880                let v = p.eval(self.t).unwrap_or_default();
881                match v.len() {
882                    3 => [v[0], v[1], v[2], 1.0],
883                    4 => [v[0], v[1], v[2], v[3]],
884                    _ => return Err(bad(self.id, name, "color needs 3 or 4 components".into())),
885                }
886            }
887        };
888        let a = c[3].clamp(0.0, 1.0);
889        out.extend([
890            (srgb_to_linear(c[0]) * a) as f32,
891            (srgb_to_linear(c[1]) * a) as f32,
892            (srgb_to_linear(c[2]) * a) as f32,
893            a as f32,
894        ]);
895        Ok(())
896    }
897}
898
899/// Homography mapping 4 `from` points to 4 `to` points, row-major 3x3.
900pub fn homography(from: &[[f64; 2]; 4], to: &[[f64; 2]; 4]) -> Option<[f64; 9]> {
901    // Solve the 8x8 linear system with h33 = 1.
902    let mut m = [[0.0f64; 9]; 8];
903    for i in 0..4 {
904        let (x, y) = (from[i][0], from[i][1]);
905        let (u, v) = (to[i][0], to[i][1]);
906        m[2 * i] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
907        m[2 * i + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
908    }
909    for col in 0..8 {
910        let piv = (col..8).max_by(|&a, &b| m[a][col].abs().partial_cmp(&m[b][col].abs()).unwrap())?;
911        if m[piv][col].abs() < 1e-12 {
912            return None;
913        }
914        m.swap(col, piv);
915        for row in 0..8 {
916            if row != col {
917                let f = m[row][col] / m[col][col];
918                for k in col..9 {
919                    m[row][k] -= f * m[col][k];
920                }
921            }
922        }
923    }
924    let mut h = [0.0; 9];
925    for i in 0..8 {
926        h[i] = m[i][8] / m[i][i];
927    }
928    h[8] = 1.0;
929    Some(h)
930}
931
932#[cfg(test)]
933mod tests {
934    fn placed(params: &str) -> ([f64; 4], [f64; 4]) {
935        let node: Node =
936            serde_json::from_str(&format!(r#"{{"op":"image","params":{{"src":"a.jpg"{params}}}}}"#)).unwrap();
937        let p = Packer {
938            id: "img",
939            node: &node,
940            t: 0.0,
941        };
942        // A portrait picture (1280x1551) on a 1080x1920 frame.
943        placement(
944            &p,
945            1080.0,
946            1920.0,
947            Some(ResourceInfo {
948                width: 1280,
949                height: 1551,
950            }),
951        )
952        .unwrap()
953    }
954
955    #[test]
956    fn pictures_keep_their_shape_in_a_box_unless_asked_to_fill() {
957        let whole = [0.0, 0.0, 1.0, 1.0];
958        // Cover (the default in a box): the box filled, the sides cropped evenly.
959        let (r, w) = placed(r#","rect":[40,190,1000,1560]"#);
960        assert_eq!(r, [40.0, 190.0, 1000.0, 1560.0]);
961        let u = (1000.0 / 1560.0) / (1280.0 / 1551.0);
962        assert!(
963            (w[0] - (1.0 - u) / 2.0).abs() < 1e-9
964                && (w[2] - (1.0 + u) / 2.0).abs() < 1e-9
965                && w[1] == 0.0
966                && w[3] == 1.0,
967            "{w:?}"
968        );
969        assert_eq!(placed(r#","rect":[40,190,1000,1560],"fit":"cover""#), (r, w));
970        // Contain: the whole picture, centred in the box.
971        let (r, w) = placed(r#","rect":[40,190,1000,1560],"fit":"contain""#);
972        assert!(
973            (r[2] - 1000.0).abs() < 1e-9 && (r[3] - 1000.0 * 1551.0 / 1280.0).abs() < 1e-9 && w == whole,
974            "{r:?}"
975        );
976        assert!((r[1] - (190.0 + (1560.0 - r[3]) / 2.0)).abs() < 1e-9);
977        // Fill stretches only when asked for.
978        assert_eq!(
979            placed(r#","rect":[40,190,1000,1560],"fit":"fill""#),
980            ([40.0, 190.0, 1000.0, 1560.0], whole)
981        );
982        // A box of the picture's own shape draws it exactly there, as before.
983        assert_eq!(placed(r#","rect":[0,0,640,775.5]"#), ([0.0, 0.0, 640.0, 775.5], whole));
984        // Without a box nothing changes: contain in the frame by default.
985        let (r, w) = placed("");
986        assert!(
987            (r[2] - 1080.0).abs() < 1e-9 && (r[0]).abs() < 1e-9 && w == whole,
988            "{r:?}"
989        );
990    }
991
992    #[test]
993    fn sequence_frames_land_on_boundaries_after_offsets() {
994        let node: Node =
995            serde_json::from_str(r#"{"op":"image","params":{"src":"f{frame:03}.png","first_frame":5}}"#).unwrap();
996        // Local times of frames under a 0.37 s offset; some land a hair
997        // under their boundary (f / 30 * 30 < f).
998        let under = (0..300u32)
999            .filter(|&f| ((f as f64 / 30.0 + 0.37) - 0.37) * 30.0 < f as f64)
1000            .count();
1001        assert!(under > 0);
1002        for f in 0..300u32 {
1003            let lt = (f as f64 / 30.0 + 0.37) - 0.37;
1004            assert_eq!(
1005                sequence_path("f{frame}.png", &node, lt, 30.0),
1006                format!("f{}.png", f + 5),
1007                "frame {f}"
1008            );
1009        }
1010    }
1011
1012    use super::*;
1013
1014    #[test]
1015    fn every_op_packs_its_declared_size() {
1016        let fmt = Format {
1017            width: 64,
1018            height: 32,
1019            fps: 30.0,
1020            duration: 1.0,
1021            motion_blur: None,
1022        };
1023        for def in OPS {
1024            let node = Node {
1025                op: def.name.into(),
1026                ..Default::default()
1027            };
1028            let mut out = Vec::new();
1029            pack(def, "n", &node, &fmt, 0.0, None, &mut out).unwrap();
1030            assert_eq!(out.len(), def.params, "{}", def.func);
1031        }
1032    }
1033
1034    #[test]
1035    fn colors_are_linearized_and_premultiplied() {
1036        let mut node = Node {
1037            op: "solid".into(),
1038            ..Default::default()
1039        };
1040        node.params.insert("color".into(), Param::Text("#ffffff80".into()));
1041        let fmt = Format {
1042            width: 1,
1043            height: 1,
1044            fps: 1.0,
1045            duration: 1.0,
1046            motion_blur: None,
1047        };
1048        let mut out = Vec::new();
1049        pack(resolve("n", &node).unwrap(), "n", &node, &fmt, 0.0, None, &mut out).unwrap();
1050        let a = 128.0 / 255.0;
1051        assert!((out[0] - a as f32).abs() < 1e-6);
1052        assert!((out[3] - a as f32).abs() < 1e-6);
1053    }
1054
1055    #[test]
1056    fn homography_maps_corners() {
1057        let from = [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]];
1058        let to = [[1.0, 2.0], [12.0, 1.0], [11.0, 13.0], [0.0, 9.0]];
1059        let h = homography(&from, &to).unwrap();
1060        for i in 0..4 {
1061            let (x, y) = (from[i][0], from[i][1]);
1062            let w = h[6] * x + h[7] * y + h[8];
1063            let u = (h[0] * x + h[1] * y + h[2]) / w;
1064            let v = (h[3] * x + h[4] * y + h[5]) / w;
1065            assert!((u - to[i][0]).abs() < 1e-9 && (v - to[i][1]).abs() < 1e-9);
1066        }
1067    }
1068
1069    #[test]
1070    fn affine_inverse_roundtrips() {
1071        let m = Affine::translate(5.0, 3.0)
1072            .mul(Affine::rotate(0.7))
1073            .mul(Affine::scale(2.0, 0.5));
1074        let (x, y) = m.apply(3.0, -4.0);
1075        let (bx, by) = m.inverse().unwrap().apply(x, y);
1076        assert!((bx - 3.0).abs() < 1e-9 && (by + 4.0).abs() < 1e-9);
1077    }
1078}