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" => match transform_affine(node, fmt, t).inverse() {
409            // Pack the inverse, and its footprint scale.
410            Some(inv) => {
411                out.extend(inv.0.iter().map(|x| *x as f32));
412                out.push(inv.det().abs().sqrt() as f32);
413            }
414            // At zero scale the layer has no area, so it shows nothing (a
415            // layer that grows from 0 starts unseen): every point maps far
416            // outside it, as a corner pin's points behind its projection do.
417            None => out.extend([0.0, 0.0, 0.0, 0.0, -1e9, -1e9, 1.0]),
418        },
419        "corner_pin" => {
420            let c = p.vecn("corners", &[0.0, 0.0, w, 0.0, w, h, 0.0, h]);
421            let src = p.vecn("source_rect", &[0.0, 0.0, w, h]);
422            let from = [
423                [src[0], src[1]],
424                [src[0] + src[2], src[1]],
425                [src[0] + src[2], src[1] + src[3]],
426                [src[0], src[1] + src[3]],
427            ];
428            let to = [[c[0], c[1]], [c[2], c[3]], [c[4], c[5]], [c[6], c[7]]];
429            let area = |q: &[[f64; 2]; 4]| {
430                let mut a = 0.0;
431                for i in 0..4 {
432                    let (p0, p1) = (q[i], q[(i + 1) % 4]);
433                    a += p0[0] * p1[1] - p1[0] * p0[1];
434                }
435                (a / 2.0).abs()
436            };
437            // Homography dest -> source, so the shader maps output to input.
438            match homography(&to, &from) {
439                Some(hm) => {
440                    out.extend(hm.iter().map(|x| *x as f32));
441                    out.push((area(&from) / area(&to).max(1e-6)).sqrt() as f32);
442                }
443                // Corners on one point or one line: no area, so nothing
444                // shows (a pin that unfolds from a point starts unseen). An
445                // all-zero homography maps every point behind it.
446                None => {
447                    out.extend([0.0; 9]);
448                    out.push(1.0);
449                }
450            }
451        }
452        "wave" => {
453            out.push(p.num("amplitude", 10.0) as f32);
454            out.push(p.num("wavelength", 100.0) as f32);
455            out.push(p.num("phase", 0.0).to_radians() as f32);
456            out.push(p.num("direction", 0.0).to_radians() as f32);
457        }
458        "twirl" => {
459            p.vec(out, "center", &center);
460            out.push(p.num("radius", w.min(h) / 2.0) as f32);
461            out.push(p.num("angle", 90.0).to_radians() as f32);
462        }
463        "tile" => {
464            p.vec(out, "origin", &[0.0, 0.0]);
465            p.vec(out, "size", &[w, h]);
466        }
467        "displace" => p.vec(out, "amount", &[20.0, 20.0]),
468        "blur" => {
469            // Packed per pass by the executor (direction varies).
470            out.extend([p.num("radius", 8.0) as f32, 1.0, 0.0, 0.0]);
471        }
472        // Scene objects are read directly by the 3D pass.
473        "mesh" | "light" | "camera" | "render3d" | "audio" | "particles" | "swarm" | "fluid" | "feedback" => {}
474        "shader" => {
475            let mut u = p.vecn("u", &[0.0; 16]);
476            for (i, slot) in u.iter_mut().enumerate() {
477                const U: [&str; 16] = [
478                    "u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7", "u8", "u9", "u10", "u11", "u12", "u13", "u14",
479                    "u15",
480                ];
481                if let Some(v) = node.params.get(U[i]).and_then(|v| v.eval_vals(t)) {
482                    *slot = v.first().copied().unwrap_or(0.0);
483                }
484            }
485            out.extend(u.iter().map(|x| *x as f32));
486            // The node's local time (components and timing shift it).
487            out.push(t as f32);
488        }
489        "path" | "text" => {
490            p.color(out, "color", [1.0, 1.0, 1.0, 1.0])?;
491            fade(out, p.num("opacity", 1.0));
492            out.push(match text(node, "fill_rule").unwrap_or("nonzero") {
493                "nonzero" => 0.0,
494                "evenodd" => 1.0,
495                o => return Err(bad(id, "fill_rule", format!("unknown fill rule `{o}`"))),
496            });
497        }
498        other => unreachable!("no packer for {other}"),
499    }
500    debug_assert_eq!(out.len() - start, def.params, "param block size for {}", def.func);
501    Ok(())
502}
503
504/// Fades the premultiplied color just packed by `opacity`.
505fn fade(out: &mut [f32], opacity: f64) {
506    let k = opacity.clamp(0.0, 1.0) as f32;
507    let n = out.len();
508    for v in &mut out[n - 4..] {
509        *v *= k;
510    }
511}
512
513/// Forward matrix of a `transform` node:
514/// p' = T(position) * R(rotation) * K(skew) * S(scale) * T(-anchor) * p.
515pub fn transform_affine(node: &Node, fmt: &Format, t: f64) -> Affine {
516    let p = Packer { id: "", node, t };
517    let center = [fmt.width as f64 / 2.0, fmt.height as f64 / 2.0];
518    let pos = p.vecn("position", &center);
519    let anchor = p.vecn("anchor", &center);
520    let scale = p.vecn("scale", &[1.0, 1.0]);
521    let rot = p.num("rotation", 0.0).to_radians();
522    let skew = p.num("skew", 0.0).to_radians();
523    Affine::translate(pos[0], pos[1])
524        .mul(Affine::rotate(rot))
525        .mul(Affine::skew_x(skew))
526        .mul(Affine::scale(scale[0], scale[1]))
527        .mul(Affine::translate(-anchor[0], -anchor[1]))
528}
529
530/// The placement params of a `shape` ([`shape_motion_px`] measures them).
531pub const SHAPE_PLACEMENT: &[&str] = &["center", "size", "scale", "rotation", "radius", "stroke", "softness"];
532
533/// How far (px, an upper bound) a `shape` node's edges move between local
534/// times l0 and l1 through its placement params.
535pub fn shape_motion_px(node: &Node, fmt: &Format, l0: f64, l1: f64) -> f64 {
536    let (w, h) = (fmt.width as f64, fmt.height as f64);
537    let at = |t: f64| {
538        let p = Packer { id: "", node, t };
539        let c = p.vecn("center", &[w / 2.0, h / 2.0]);
540        let s = p.vecn("size", &[w / 4.0, w / 4.0]);
541        let k = p.vecn("scale", &[1.0, 1.0]);
542        let half = [(s[0] * k[0]).abs() / 2.0, (s[1] * k[1]).abs() / 2.0];
543        let extra = [p.num("radius", 0.0), p.num("stroke", 0.0), p.num("softness", 1.0)];
544        (c, half, p.num("rotation", 0.0).to_radians(), extra)
545    };
546    let (c0, e0, r0, x0) = at(l0);
547    let (c1, e1, r1, x1) = at(l1);
548    (c1[0] - c0[0]).hypot(c1[1] - c0[1])
549        + (e1[0] - e0[0]).abs().max((e1[1] - e0[1]).abs())
550        + (r1 - r0).abs() * e0[0].hypot(e0[1]).max(e1[0].hypot(e1[1]))
551        + x0.iter().zip(&x1).map(|(a, b)| (a - b).abs()).sum::<f64>()
552}
553
554/// How far (px, an upper bound) a `wave` node's displacement changes
555/// between local times l0 and l1 through its amplitude and phase.
556pub fn wave_motion_px(node: &Node, l0: f64, l1: f64) -> f64 {
557    let at = |t: f64| {
558        let p = Packer { id: "", node, t };
559        (p.num("amplitude", 10.0), p.num("phase", 0.0).to_radians())
560    };
561    let ((a0, p0), (a1, p1)) = (at(l0), at(l1));
562    (a1 - a0).abs() + a0.abs().max(a1.abs()) * (p1 - p0).abs()
563}
564
565/// Axis-aligned bounds (x0, y0, x1, y1) of where a node can be non-transparent.
566pub type Rect = [f64; 4];
567pub const UNBOUNDED: Rect = [-1e9, -1e9, 1e9, 1e9];
568pub const EMPTY: Rect = [1e9, 1e9, -1e9, -1e9];
569
570fn union(a: Rect, b: Rect) -> Rect {
571    [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]
572}
573
574fn intersect(a: Rect, b: Rect) -> Rect {
575    [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]
576}
577
578/// Ops whose fg input is guarded by its bounds in fused kernels: pixels
579/// outside skip evaluating the fg subtree entirely.
580pub fn guarded(def: &OpDef) -> bool {
581    matches!(def.name, "over" | "blend")
582}
583
584/// Where an image or video frame is drawn ([x, y, w, h] px) and the part
585/// of it that shows ([u0, v0, u1, v1]), by `fit` inside `rect` (a box) or
586/// the frame. A picture keeps its aspect ratio unless `fit` is "fill": in
587/// a box it defaults to "cover" (the box filled, the overflow cropped
588/// evenly), in the frame to "contain". A box of the picture's own shape
589/// draws it exactly there, as before.
590fn placement(p: &Packer, w: f64, h: f64, res: Option<ResourceInfo>) -> Result<([f64; 4], [f64; 4]), OpsError> {
591    let r = res.unwrap_or(ResourceInfo { width: 1, height: 1 });
592    let (iw, ih) = (r.width as f64, r.height as f64);
593    let boxed = p.node.params.contains_key("rect");
594    let b = if boxed {
595        let v = p.vecn("rect", &[0.0, 0.0, iw, ih]);
596        [v[0], v[1], v[2], v[3]]
597    } else {
598        [0.0, 0.0, w, h]
599    };
600    let whole = [0.0, 0.0, 1.0, 1.0];
601    let fit = text(p.node, "fit").unwrap_or(if boxed { "cover" } else { "contain" });
602    // Within 1%: rounding in a box sized for the picture never crops it.
603    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;
604    let centered = |sw: f64, sh: f64| [b[0] + (b[2] - sw) / 2.0, b[1] + (b[3] - sh) / 2.0, sw, sh];
605    Ok(match fit {
606        "fill" => (b, whole),
607        _ if boxed && same_shape && fit != "none" => (b, whole),
608        "none" => (centered(iw, ih), whole),
609        "contain" => {
610            let s = (b[2] / iw).min(b[3] / ih);
611            (centered(iw * s, ih * s), whole)
612        }
613        // Without a box the frame crops the overflow; in a box the window does.
614        "cover" if !boxed => {
615            let s = (b[2] / iw).max(b[3] / ih);
616            (centered(iw * s, ih * s), whole)
617        }
618        "cover" => {
619            let s = (b[2] / iw).max(b[3] / ih);
620            let (u, v) = (b[2] / (iw * s), b[3] / (ih * s));
621            (b, [(1.0 - u) / 2.0, (1.0 - v) / 2.0, (1.0 + u) / 2.0, (1.0 + v) / 2.0])
622        }
623        other => return Err(bad(p.id, "fit", format!("unknown fit `{other}`"))),
624    })
625}
626
627/// Conservative bounds of a node's output in its own coordinate space,
628/// given its inputs' bounds. Anything unknown is unbounded.
629pub fn bounds(def: &OpDef, node: &Node, fmt: &Format, t: f64, inputs: &[Rect], res: Option<ResourceInfo>) -> Rect {
630    let p = Packer { id: "", node, t };
631    let (w, h) = (fmt.width as f64, fmt.height as f64);
632    let input = |i: usize| inputs.get(i).copied().unwrap_or(UNBOUNDED);
633    match def.func {
634        "shape" => {
635            let c = p.vecn("center", &[w / 2.0, h / 2.0]);
636            let sc = p.vecn("scale", &[1.0, 1.0]);
637            let size = p.vecn("size", &[w / 4.0, w / 4.0]);
638            let size = [size[0] * sc[0].abs(), size[1] * sc[1].abs()];
639            // Bounding circle of the (possibly rotated) shape, plus room for
640            // the stroke and antialiasing even under strong minification.
641            let r = (size[0] * size[0] + size[1] * size[1]).sqrt() / 2.0
642                + p.num("stroke", 0.0)
643                + p.num("softness", 1.0).max(1.0) * 8.0;
644            [c[0] - r, c[1] - r, c[0] + r, c[1] + r]
645        }
646        "image" => match (node.params.contains_key("rect"), text(node, "fit"), res) {
647            (true, Some("none"), Some(_)) => match placement(&p, w, h, res) {
648                Ok((r, _)) => [r[0] - 1.0, r[1] - 1.0, r[0] + r[2] + 1.0, r[1] + r[3] + 1.0],
649                Err(_) => UNBOUNDED,
650            },
651            (true, Some("none"), None) => UNBOUNDED,
652            (true, _, _) => {
653                let r = p.vecn("rect", &[0.0, 0.0, w, h]);
654                [r[0] - 1.0, r[1] - 1.0, r[0] + r[2] + 1.0, r[1] + r[3] + 1.0]
655            }
656            _ => UNBOUNDED,
657        },
658        "opacity" | "adjust" | "levels" | "invert" | "tint" | "threshold" => input(0),
659        "crop" => {
660            let r = p.vecn("rect", &[0.0, 0.0, w, h]);
661            intersect(input(0), [r[0] - 1.0, r[1] - 1.0, r[0] + r[2] + 1.0, r[1] + r[3] + 1.0])
662        }
663        "mask" => match text(node, "mode").unwrap_or("alpha") {
664            "alpha" | "luma" => intersect(input(0), input(1)),
665            _ => input(0),
666        },
667        "over" | "blend" | "mix" => union(input(0), input(1)),
668        "transform" => {
669            let b = input(0);
670            let m = transform_affine(node, fmt, t);
671            // At zero scale nothing shows (see `pack`), whatever the input.
672            if m.inverse().is_none() {
673                return EMPTY;
674            }
675            if b[0] <= -1e8 || b[0] > b[2] {
676                return b;
677            }
678            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));
679            let xs = pts.map(|p| p.0);
680            let ys = pts.map(|p| p.1);
681            let f = |v: [f64; 4], min: bool| {
682                v.into_iter().fold(if min { f64::MAX } else { f64::MIN }, |a, b| {
683                    if min { a.min(b) } else { a.max(b) }
684                })
685            };
686            [
687                f(xs, true) - 2.0,
688                f(ys, true) - 2.0,
689                f(xs, false) + 2.0,
690                f(ys, false) + 2.0,
691            ]
692        }
693        _ => UNBOUNDED,
694    }
695}
696
697/// Whether `outer` holds all of `inner` (an empty `inner` is held by
698/// nothing).
699pub fn contains(outer: Rect, inner: Rect) -> bool {
700    inner[0] < inner[2]
701        && inner[1] < inner[3]
702        && outer[0] <= inner[0]
703        && outer[1] <= inner[1]
704        && outer[2] >= inner[2]
705        && outer[3] >= inner[3]
706}
707
708/// Of two rects a layer is opaque in, the one that holds the other, else
709/// the larger.
710fn larger(a: Rect, b: Rect) -> Rect {
711    let area = |r: Rect| (r[2] - r[0]).max(0.0) * (r[3] - r[1]).max(0.0);
712    if contains(a, b) || area(a) >= area(b) { a } else { b }
713}
714
715/// A rect that reaches past `UNBOUNDED`'s edges on every side.
716fn everywhere(r: Rect) -> bool {
717    r[0] <= -1e8 && r[1] <= -1e8 && r[2] >= 1e8 && r[3] >= 1e8
718}
719
720/// Where a node's output is fully opaque, in its own coordinate space,
721/// given its inputs' opaque rects: a conservative rect inside which it
722/// hides whatever lies under it. [`UNBOUNDED`] for a layer opaque
723/// everywhere (an opaque solid or gradient, or a composite over one),
724/// [`EMPTY`] for anything not known to be opaque: type and paths (their
725/// counters show what is under them), pictures and footage (which may
726/// carry alpha), shaders, blurs, warps.
727pub fn opaque(def: &OpDef, node: &Node, fmt: &Format, t: f64, inputs: &[Rect]) -> Rect {
728    let p = Packer { id: "", node, t };
729    let (w, h) = (fmt.width as f64, fmt.height as f64);
730    let input = |i: usize| inputs.get(i).copied().unwrap_or(EMPTY);
731    let one = |v: f64| (v - 1.0).abs() <= 1e-6;
732    // The packed block, as the kernel reads it (colors premultiplied, so
733    // alpha already carries any `opacity`).
734    let packed = || {
735        let mut out = Vec::with_capacity(def.params);
736        pack(def, "", node, fmt, t, None, &mut out).ok().map(|()| out)
737    };
738    let solid = |a: f32| a >= 1.0 - 1e-6;
739    match def.func {
740        "solid" => match packed() {
741            Some(v) if solid(v[3]) => UNBOUNDED,
742            _ => EMPTY,
743        },
744        "checker" | "noise" => match packed() {
745            Some(v) if solid(v[3]) && solid(v[7]) => UNBOUNDED,
746            _ => EMPTY,
747        },
748        "gradient_linear" | "gradient_radial" | "gradient_conic" => match packed() {
749            Some(v) if (0..(v[0] as usize).clamp(1, 8)).all(|k| solid(v[6 + k * 5 + 4])) => UNBOUNDED,
750            _ => EMPTY,
751        },
752        "shape" => packed().map(|v| shape_interior(&v)).unwrap_or(EMPTY),
753        "opacity" if one(p.num("opacity", 1.0)) => input(0),
754        "adjust" | "levels" | "lut" | "invert" | "tint" | "threshold" => input(0),
755        // Alpha passes through when its row is the identity.
756        "color_matrix" => match packed() {
757            Some(v) if v[15..20] == [0.0, 0.0, 0.0, 1.0, 0.0] => input(0),
758            _ => EMPTY,
759        },
760        "crop" => {
761            let r = p.vecn("rect", &[0.0, 0.0, w, h]);
762            // Its soft edge, wide enough for a minified footprint.
763            let s = 2.0 * p.num("softness", 1.0).max(1.0);
764            intersect(input(0), [r[0] + s, r[1] + s, r[0] + r[2] - s, r[1] + r[3] - s])
765        }
766        "mask" if text(node, "mode").unwrap_or("alpha") == "alpha" => intersect(input(0), input(1)),
767        // Alpha adds up as it does for `over`, whatever the blend mode.
768        "over" | "blend" => {
769            let fg = if one(p.num("opacity", 1.0)) { input(0) } else { EMPTY };
770            larger(fg, input(1))
771        }
772        "composite" => match text(node, "operator").unwrap_or("over") {
773            "over" => larger(input(0), input(1)),
774            "in" => intersect(input(0), input(1)),
775            "atop" => input(1),
776            _ => EMPTY,
777        },
778        "mix" => match p.num("t", 0.5) {
779            k if k.abs() <= 1e-6 => input(0),
780            k if one(k) => input(1),
781            k if (0.0..=1.0).contains(&k) => intersect(input(0), input(1)),
782            _ => EMPTY,
783        },
784        "transform" => {
785            let b = input(0);
786            let m = transform_affine(node, fmt, t);
787            // At zero scale nothing shows (see `pack`).
788            if m.inverse().is_none() || b[0] >= b[2] || b[1] >= b[3] {
789                return EMPTY;
790            }
791            if everywhere(b) {
792                return UNBOUNDED;
793            }
794            // Moved, scaled, flipped or turned a quarter: still an upright
795            // rect, its edges resampled over a source pixel.
796            let [a, bb, c, d, ..] = m.0;
797            if !((bb.abs() < 1e-9 && c.abs() < 1e-9) || (a.abs() < 1e-9 && d.abs() < 1e-9)) {
798                return EMPTY;
799            }
800            let (sx, sy) = ((a.abs() + c.abs()).max(1.0), (bb.abs() + d.abs()).max(1.0));
801            let (p0, p1) = (m.apply(b[0], b[1]), m.apply(b[2], b[3]));
802            [
803                p0.0.min(p1.0) + sx,
804                p0.1.min(p1.1) + sy,
805                p0.0.max(p1.0) - sx,
806                p0.1.max(p1.1) - sy,
807            ]
808        }
809        _ => EMPTY,
810    }
811}
812
813/// The upright rect inside a filled, opaque `shape` (from its packed
814/// block: color, center, half size, corner radius, kind, softness,
815/// rotation, stroke), short of its soft edge.
816fn shape_interior(v: &[f32]) -> Rect {
817    use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, PI};
818    let v: Vec<f64> = v.iter().map(|&x| x as f64).collect();
819    if v[3] < 1.0 - 1e-6 || v[12] > 0.0 {
820        return EMPTY;
821    }
822    let (cx, cy, hw, hh) = (v[4], v[5], v[6], v[7]);
823    // An ellipse holds the rect touching it at 45 degrees; a rounded rect
824    // the one touching its corner arcs there.
825    let (ex, ey) = if v[9] > 0.5 {
826        (hw * FRAC_1_SQRT_2, hh * FRAC_1_SQRT_2)
827    } else {
828        let k = v[8].clamp(0.0, hw.min(hh)) * (1.0 - FRAC_1_SQRT_2);
829        (hw - k, hh - k)
830    };
831    let turn = v[11].rem_euclid(PI);
832    let (ex, ey) = if turn < 1e-6 || PI - turn < 1e-6 {
833        (ex, ey)
834    } else if (turn - FRAC_PI_2).abs() < 1e-6 {
835        (ey, ex)
836    } else {
837        // Any other angle: the square inside its inscribed circle.
838        let m = hw.min(hh) * FRAC_1_SQRT_2;
839        (m, m)
840    };
841    let soft = 2.0 * v[10].max(1.0);
842    let (ex, ey) = (ex - soft, ey - soft);
843    if ex <= 0.0 || ey <= 0.0 {
844        return EMPTY;
845    }
846    [cx - ex, cy - ey, cx + ex, cy + ey]
847}
848
849/// Where an active composite hides its bg (its second input) entirely:
850/// inside `fg`, its fg's opaque rect, when it draws the fg whole over the
851/// bg (`over` or a normal `blend` at full opacity, a `composite` over).
852/// Other modes and operators show the bg through, or its shape. EMPTY
853/// when nothing is hidden.
854pub fn hidden_bg(def: &OpDef, node: &Node, t: f64, fg: Rect) -> Rect {
855    let p = Packer { id: "", node, t };
856    let full = (p.num("opacity", 1.0) - 1.0).abs() <= 1e-6;
857    let hides = match def.name {
858        "over" => full,
859        "blend" => full && text(node, "mode").unwrap_or("normal") == "normal",
860        "composite" => text(node, "operator").unwrap_or("over") == "over",
861        _ => false,
862    };
863    if hides { fg } else { EMPTY }
864}
865
866/// Gradient block: stop count, space, 4 geometry floats, 8 stops of
867/// (position, premultiplied rgba).
868pub const GRADIENT_PARAMS: usize = 6 + 8 * 5;
869
870/// Parses gradient stops: `"0:#ff0000, 0.5:#00ff0080, 1:#0000ff"`, or a
871/// flat vector of `[pos, r, g, b, a]` groups (sRGB, straight alpha).
872fn parse_stops(p: &Param, t: f64) -> Option<Vec<(f64, [f64; 4])>> {
873    match p {
874        Param::Text(s) => s
875            .split(',')
876            .map(|part| {
877                let (pos, col) = part.trim().split_once(':')?;
878                Some((pos.trim().parse().ok()?, parse_hex(col.trim())?))
879            })
880            .collect(),
881        p => {
882            let v = p.eval(t)?;
883            (v.len() % 5 == 0 && !v.is_empty())
884                .then(|| v.chunks_exact(5).map(|c| (c[0], [c[1], c[2], c[3], c[4]])).collect())
885        }
886    }
887}
888
889pub const BLEND_MODES: &[&str] = &[
890    "normal",
891    "multiply",
892    "screen",
893    "overlay",
894    "darken",
895    "lighten",
896    "color_dodge",
897    "color_burn",
898    "hard_light",
899    "soft_light",
900    "difference",
901    "exclusion",
902    "hue",
903    "saturation",
904    "color",
905    "luminosity",
906    "add",
907    "subtract",
908    "divide",
909];
910
911fn space(id: &str, node: &Node) -> Result<f32, OpsError> {
912    match text(node, "space").unwrap_or("linear") {
913        "linear" => Ok(0.0),
914        "srgb" => Ok(1.0),
915        other => Err(bad(id, "space", format!("unknown space `{other}` (linear | srgb)"))),
916    }
917}
918
919fn bad(id: &str, param: &str, reason: String) -> OpsError {
920    OpsError::BadParam {
921        node: id.to_string(),
922        param: param.to_string(),
923        reason,
924    }
925}
926
927struct Packer<'a> {
928    id: &'a str,
929    node: &'a Node,
930    t: f64,
931}
932
933impl Packer<'_> {
934    fn vecn(&self, name: &str, default: &[f64]) -> ultrafast_graph::Vals {
935        let mut v = self
936            .node
937            .params
938            .get(name)
939            .and_then(|p| p.eval_vals(self.t))
940            .unwrap_or_else(|| ultrafast_graph::Vals::from_slice(default));
941        // Broadcast a scalar to the expected width; pad or truncate otherwise.
942        if v.len() == 1 && default.len() > 1 {
943            v = ultrafast_graph::Vals::filled(v[0], default.len());
944        }
945        v.resize(default.len(), 0.0);
946        v
947    }
948
949    fn vec(&self, out: &mut Vec<f32>, name: &str, default: &[f64]) {
950        out.extend(self.vecn(name, default).into_iter().map(|x| x as f32));
951    }
952
953    fn num(&self, name: &str, default: f64) -> f64 {
954        self.vecn(name, &[default])[0]
955    }
956
957    /// Packs a gradient: stops (from `stops`, else `a`/`b`), interpolation
958    /// space, and geometry for the kind.
959    fn gradient(
960        &self,
961        out: &mut Vec<f32>,
962        func: &str,
963        a: [f64; 4],
964        b: [f64; 4],
965        center: [f64; 2],
966        h: f64,
967    ) -> Result<(), OpsError> {
968        let mut stops = match self.node.params.get("stops") {
969            Some(p) => parse_stops(p, self.t).ok_or_else(|| {
970                bad(
971                    self.id,
972                    "stops",
973                    "use \"pos:#rrggbb, ...\" or [pos, r, g, b, a, ...]".into(),
974                )
975            })?,
976            None => {
977                let mut ca = Vec::new();
978                let mut cb = Vec::new();
979                self.color_straight(&mut ca, "a", a)?;
980                self.color_straight(&mut cb, "b", b)?;
981                vec![(0.0, [ca[0], ca[1], ca[2], ca[3]]), (1.0, [cb[0], cb[1], cb[2], cb[3]])]
982            }
983        };
984        stops.sort_by(|x, y| x.0.partial_cmp(&y.0).unwrap());
985        stops.truncate(8);
986        let encoded = match text(self.node, "space").unwrap_or("linear") {
987            "linear" => false,
988            "srgb" => true,
989            o => return Err(bad(self.id, "space", format!("unknown space `{o}` (linear | srgb)"))),
990        };
991        out.push(stops.len() as f32);
992        out.push(encoded as u8 as f32);
993        match func {
994            "gradient_linear" => {
995                self.vec(out, "start", &[0.0, 0.0]);
996                self.vec(out, "end", &[0.0, h]);
997            }
998            "gradient_radial" => {
999                self.vec(out, "center", &center);
1000                self.vec(out, "radius", &[center[0].max(center[1])]);
1001                out.push(0.0);
1002            }
1003            _ => {
1004                self.vec(out, "center", &center);
1005                out.push(self.num("angle", 0.0).to_radians() as f32);
1006                out.push(0.0);
1007            }
1008        }
1009        for k in 0..8 {
1010            let (pos, c) = stops.get(k).copied().unwrap_or((1.0, [0.0; 4]));
1011            // Premultiplied, in the interpolation space.
1012            let al = c[3].clamp(0.0, 1.0);
1013            let ch = |x: f64| if encoded { x * al } else { srgb_to_linear(x) * al };
1014            out.extend([pos as f32, ch(c[0]) as f32, ch(c[1]) as f32, ch(c[2]) as f32, al as f32]);
1015        }
1016        Ok(())
1017    }
1018
1019    /// A document color as straight sRGB (no conversion).
1020    fn color_straight(&self, out: &mut Vec<f64>, name: &str, default: [f64; 4]) -> Result<(), OpsError> {
1021        let c = match self.node.params.get(name) {
1022            None => default,
1023            Some(Param::Text(s)) => parse_hex(s).ok_or_else(|| {
1024                bad(
1025                    self.id,
1026                    name,
1027                    format!("`{s}` is not a #rgb, #rrggbb or #rrggbbaa color"),
1028                )
1029            })?,
1030            Some(p) => {
1031                let v = p.eval(self.t).unwrap_or_default();
1032                match v.len() {
1033                    3 => [v[0], v[1], v[2], 1.0],
1034                    4 => [v[0], v[1], v[2], v[3]],
1035                    _ => return Err(bad(self.id, name, "color needs 3 or 4 components".into())),
1036                }
1037            }
1038        };
1039        out.extend(c);
1040        Ok(())
1041    }
1042
1043    /// Document colors are straight-alpha, sRGB-encoded: `[r,g,b(,a)]` in 0..1
1044    /// or `#rrggbb(aa)`. The engine works in linear premultiplied.
1045    fn color(&self, out: &mut Vec<f32>, name: &str, default: [f64; 4]) -> Result<(), OpsError> {
1046        let c = match self.node.params.get(name) {
1047            None => default,
1048            Some(Param::Text(s)) => parse_hex(s).ok_or_else(|| {
1049                bad(
1050                    self.id,
1051                    name,
1052                    format!("`{s}` is not a #rgb, #rrggbb or #rrggbbaa color"),
1053                )
1054            })?,
1055            Some(p) => {
1056                let v = p.eval(self.t).unwrap_or_default();
1057                match v.len() {
1058                    3 => [v[0], v[1], v[2], 1.0],
1059                    4 => [v[0], v[1], v[2], v[3]],
1060                    _ => return Err(bad(self.id, name, "color needs 3 or 4 components".into())),
1061                }
1062            }
1063        };
1064        let a = c[3].clamp(0.0, 1.0);
1065        out.extend([
1066            (srgb_to_linear(c[0]) * a) as f32,
1067            (srgb_to_linear(c[1]) * a) as f32,
1068            (srgb_to_linear(c[2]) * a) as f32,
1069            a as f32,
1070        ]);
1071        Ok(())
1072    }
1073}
1074
1075/// Homography mapping 4 `from` points to 4 `to` points, row-major 3x3.
1076pub fn homography(from: &[[f64; 2]; 4], to: &[[f64; 2]; 4]) -> Option<[f64; 9]> {
1077    // Solve the 8x8 linear system with h33 = 1.
1078    let mut m = [[0.0f64; 9]; 8];
1079    for i in 0..4 {
1080        let (x, y) = (from[i][0], from[i][1]);
1081        let (u, v) = (to[i][0], to[i][1]);
1082        m[2 * i] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
1083        m[2 * i + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
1084    }
1085    for col in 0..8 {
1086        let piv = (col..8).max_by(|&a, &b| m[a][col].abs().partial_cmp(&m[b][col].abs()).unwrap())?;
1087        if m[piv][col].abs() < 1e-12 {
1088            return None;
1089        }
1090        m.swap(col, piv);
1091        for row in 0..8 {
1092            if row != col {
1093                let f = m[row][col] / m[col][col];
1094                for k in col..9 {
1095                    m[row][k] -= f * m[col][k];
1096                }
1097            }
1098        }
1099    }
1100    let mut h = [0.0; 9];
1101    for i in 0..8 {
1102        h[i] = m[i][8] / m[i][i];
1103    }
1104    h[8] = 1.0;
1105    Some(h)
1106}
1107
1108#[cfg(test)]
1109mod tests {
1110    fn placed(params: &str) -> ([f64; 4], [f64; 4]) {
1111        let node: Node =
1112            serde_json::from_str(&format!(r#"{{"op":"image","params":{{"src":"a.jpg"{params}}}}}"#)).unwrap();
1113        let p = Packer {
1114            id: "img",
1115            node: &node,
1116            t: 0.0,
1117        };
1118        // A portrait picture (1280x1551) on a 1080x1920 frame.
1119        placement(
1120            &p,
1121            1080.0,
1122            1920.0,
1123            Some(ResourceInfo {
1124                width: 1280,
1125                height: 1551,
1126            }),
1127        )
1128        .unwrap()
1129    }
1130
1131    #[test]
1132    fn pictures_keep_their_shape_in_a_box_unless_asked_to_fill() {
1133        let whole = [0.0, 0.0, 1.0, 1.0];
1134        // Cover (the default in a box): the box filled, the sides cropped evenly.
1135        let (r, w) = placed(r#","rect":[40,190,1000,1560]"#);
1136        assert_eq!(r, [40.0, 190.0, 1000.0, 1560.0]);
1137        let u = (1000.0 / 1560.0) / (1280.0 / 1551.0);
1138        assert!(
1139            (w[0] - (1.0 - u) / 2.0).abs() < 1e-9
1140                && (w[2] - (1.0 + u) / 2.0).abs() < 1e-9
1141                && w[1] == 0.0
1142                && w[3] == 1.0,
1143            "{w:?}"
1144        );
1145        assert_eq!(placed(r#","rect":[40,190,1000,1560],"fit":"cover""#), (r, w));
1146        // Contain: the whole picture, centred in the box.
1147        let (r, w) = placed(r#","rect":[40,190,1000,1560],"fit":"contain""#);
1148        assert!(
1149            (r[2] - 1000.0).abs() < 1e-9 && (r[3] - 1000.0 * 1551.0 / 1280.0).abs() < 1e-9 && w == whole,
1150            "{r:?}"
1151        );
1152        assert!((r[1] - (190.0 + (1560.0 - r[3]) / 2.0)).abs() < 1e-9);
1153        // Fill stretches only when asked for.
1154        assert_eq!(
1155            placed(r#","rect":[40,190,1000,1560],"fit":"fill""#),
1156            ([40.0, 190.0, 1000.0, 1560.0], whole)
1157        );
1158        // A box of the picture's own shape draws it exactly there, as before.
1159        assert_eq!(placed(r#","rect":[0,0,640,775.5]"#), ([0.0, 0.0, 640.0, 775.5], whole));
1160        // Without a box nothing changes: contain in the frame by default.
1161        let (r, w) = placed("");
1162        assert!(
1163            (r[2] - 1080.0).abs() < 1e-9 && (r[0]).abs() < 1e-9 && w == whole,
1164            "{r:?}"
1165        );
1166    }
1167
1168    #[test]
1169    fn sequence_frames_land_on_boundaries_after_offsets() {
1170        let node: Node =
1171            serde_json::from_str(r#"{"op":"image","params":{"src":"f{frame:03}.png","first_frame":5}}"#).unwrap();
1172        // Local times of frames under a 0.37 s offset; some land a hair
1173        // under their boundary (f / 30 * 30 < f).
1174        let under = (0..300u32)
1175            .filter(|&f| ((f as f64 / 30.0 + 0.37) - 0.37) * 30.0 < f as f64)
1176            .count();
1177        assert!(under > 0);
1178        for f in 0..300u32 {
1179            let lt = (f as f64 / 30.0 + 0.37) - 0.37;
1180            assert_eq!(
1181                sequence_path("f{frame}.png", &node, lt, 30.0),
1182                format!("f{}.png", f + 5),
1183                "frame {f}"
1184            );
1185        }
1186    }
1187
1188    use super::*;
1189
1190    #[test]
1191    fn every_op_packs_its_declared_size() {
1192        let fmt = Format {
1193            width: 64,
1194            height: 32,
1195            fps: 30.0,
1196            duration: 1.0,
1197            motion_blur: None,
1198        };
1199        for def in OPS {
1200            let node = Node {
1201                op: def.name.into(),
1202                ..Default::default()
1203            };
1204            let mut out = Vec::new();
1205            pack(def, "n", &node, &fmt, 0.0, None, &mut out).unwrap();
1206            assert_eq!(out.len(), def.params, "{}", def.func);
1207        }
1208    }
1209
1210    #[test]
1211    fn colors_are_linearized_and_premultiplied() {
1212        let mut node = Node {
1213            op: "solid".into(),
1214            ..Default::default()
1215        };
1216        node.params.insert("color".into(), Param::Text("#ffffff80".into()));
1217        let fmt = Format {
1218            width: 1,
1219            height: 1,
1220            fps: 1.0,
1221            duration: 1.0,
1222            motion_blur: None,
1223        };
1224        let mut out = Vec::new();
1225        pack(resolve("n", &node).unwrap(), "n", &node, &fmt, 0.0, None, &mut out).unwrap();
1226        let a = 128.0 / 255.0;
1227        assert!((out[0] - a as f32).abs() < 1e-6);
1228        assert!((out[3] - a as f32).abs() < 1e-6);
1229    }
1230
1231    #[test]
1232    fn homography_maps_corners() {
1233        let from = [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]];
1234        let to = [[1.0, 2.0], [12.0, 1.0], [11.0, 13.0], [0.0, 9.0]];
1235        let h = homography(&from, &to).unwrap();
1236        for i in 0..4 {
1237            let (x, y) = (from[i][0], from[i][1]);
1238            let w = h[6] * x + h[7] * y + h[8];
1239            let u = (h[0] * x + h[1] * y + h[2]) / w;
1240            let v = (h[3] * x + h[4] * y + h[5]) / w;
1241            assert!((u - to[i][0]).abs() < 1e-9 && (v - to[i][1]).abs() < 1e-9);
1242        }
1243    }
1244
1245    #[test]
1246    fn affine_inverse_roundtrips() {
1247        let m = Affine::translate(5.0, 3.0)
1248            .mul(Affine::rotate(0.7))
1249            .mul(Affine::scale(2.0, 0.5));
1250        let (x, y) = m.apply(3.0, -4.0);
1251        let (bx, by) = m.inverse().unwrap().apply(x, y);
1252        assert!((bx - 3.0).abs() < 1e-9 && (by + 4.0).abs() < 1e-9);
1253    }
1254
1255    /// A layer that grows from zero scale (or a pin that unfolds from a
1256    /// point) shows nothing at that moment instead of failing the render:
1257    /// every point maps far outside it, and it has no bounds.
1258    #[test]
1259    fn zero_scale_shows_nothing() {
1260        let fmt = Format {
1261            width: 64,
1262            height: 32,
1263            fps: 30.0,
1264            duration: 1.0,
1265            motion_blur: None,
1266        };
1267        let grows: Node = serde_json::from_str(
1268            r#"{"op":"transform","params":{"scale":{"keys":[{"t":0,"v":[0,0]},{"t":1,"v":[1,1]}]}}}"#,
1269        )
1270        .unwrap();
1271        let unfolds: Node = serde_json::from_str(
1272            r#"{"op":"corner_pin","params":{"corners":{"keys":[{"t":0,"v":[9,9,9,9,9,9,9,9]},{"t":1,"v":[0,0,64,0,64,32,0,32]}]}}}"#,
1273        )
1274        .unwrap();
1275        let shape = [10.0, 10.0, 20.0, 20.0];
1276        for node in [&grows, &unfolds] {
1277            let def = resolve("n", node).unwrap();
1278            let mut out = Vec::new();
1279            pack(def, "n", node, &fmt, 0.0, None, &mut out).unwrap();
1280            assert_eq!(out.len(), def.params, "{}", def.func);
1281            assert!(out.iter().all(|x| x.is_finite()), "{}: {out:?}", def.func);
1282            // Grown halfway it is drawn as usual.
1283            out.clear();
1284            pack(def, "n", node, &fmt, 0.5, None, &mut out).unwrap();
1285            assert!(out.iter().any(|x| *x != 0.0), "{}: {out:?}", def.func);
1286        }
1287        let mut out = Vec::new();
1288        pack(resolve("n", &grows).unwrap(), "n", &grows, &fmt, 0.0, None, &mut out).unwrap();
1289        let (x, y) = (
1290            out[0] * 20.0 + out[2] * 7.0 + out[4],
1291            out[1] * 20.0 + out[3] * 7.0 + out[5],
1292        );
1293        assert!(x < -1e8 && y < -1e8, "({x}, {y})");
1294        let def = resolve("n", &grows).unwrap();
1295        assert_eq!(bounds(def, &grows, &fmt, 0.0, &[shape], None), EMPTY);
1296        assert_eq!(bounds(def, &grows, &fmt, 0.0, &[UNBOUNDED], None), EMPTY);
1297        let half = bounds(def, &grows, &fmt, 0.5, &[shape], None);
1298        assert!(half[0] < half[2] && half[1] < half[3], "{half:?}");
1299    }
1300
1301    /// What `opaque` knows hides what is under it, and what it leaves
1302    /// alone: translucent colors, outlines, type, pictures, faded or
1303    /// blended layers, turned rects.
1304    #[test]
1305    fn opaque_rects_hide_only_what_is_covered() {
1306        let fmt = Format {
1307            width: 480,
1308            height: 270,
1309            fps: 30.0,
1310            duration: 1.0,
1311            motion_blur: None,
1312        };
1313        let at = |json: &str, inputs: &[Rect]| {
1314            let node: Node = serde_json::from_str(json).unwrap();
1315            opaque(resolve("n", &node).unwrap(), &node, &fmt, 0.0, inputs)
1316        };
1317        assert_eq!(at(r##"{"op":"solid","params":{"color":"#102030"}}"##, &[]), UNBOUNDED);
1318        assert_eq!(at(r##"{"op":"solid","params":{"color":"#10203080"}}"##, &[]), EMPTY);
1319        assert_eq!(
1320            at(r##"{"op":"gradient","params":{"stops":"0:#000000, 1:#ffffff"}}"##, &[]),
1321            UNBOUNDED
1322        );
1323        assert_eq!(
1324            at(
1325                r##"{"op":"gradient","params":{"stops":"0:#000000, 1:#ffffff00"}}"##,
1326                &[]
1327            ),
1328            EMPTY
1329        );
1330        assert_eq!(at(r#"{"op":"text","params":{"text":"Hi"}}"#, &[]), EMPTY);
1331        assert_eq!(at(r#"{"op":"image","params":{"src":"a.png"}}"#, &[]), EMPTY);
1332        // A filled rect, short of its soft edge; an outline hides nothing.
1333        let rect = at(
1334            r##"{"op":"shape","params":{"size":[200,100],"center":[240,135],"color":"#ffffff"}}"##,
1335            &[],
1336        );
1337        assert!(
1338            contains([140.0, 85.0, 340.0, 185.0], rect) && contains(rect, [145.0, 90.0, 335.0, 180.0]),
1339            "{rect:?}"
1340        );
1341        assert_eq!(
1342            at(
1343                r##"{"op":"shape","params":{"size":[200,100],"color":"#ffffff","stroke":4}}"##,
1344                &[]
1345            ),
1346            EMPTY
1347        );
1348        // Turned, it keeps the square inside its inscribed circle.
1349        let turned = at(
1350            r##"{"op":"shape","params":{"size":[200,100],"center":[240,135],"color":"#ffffff","rotation":30}}"##,
1351            &[],
1352        );
1353        assert!(
1354            contains([240.0 - 36.0, 135.0 - 36.0, 240.0 + 36.0, 135.0 + 36.0], turned),
1355            "{turned:?}"
1356        );
1357        // Composites: an opaque bg or a whole fg; faded fgs and other
1358        // modes don't hide the bg.
1359        let over = r#"{"op":"over","inputs":{"fg":"a","bg":"b"}}"#;
1360        assert_eq!(at(over, &[EMPTY, UNBOUNDED]), UNBOUNDED);
1361        assert_eq!(at(over, &[rect, EMPTY]), rect);
1362        let node = |json: &str| -> Node { serde_json::from_str(json).unwrap() };
1363        let hides = |json: &str| {
1364            let n = node(json);
1365            hidden_bg(resolve("n", &n).unwrap(), &n, 0.0, UNBOUNDED)
1366        };
1367        assert_eq!(hides(over), UNBOUNDED);
1368        assert_eq!(
1369            hides(r#"{"op":"over","inputs":{"fg":"a","bg":"b"},"params":{"opacity":0.9}}"#),
1370            EMPTY
1371        );
1372        assert_eq!(hides(r#"{"op":"blend","inputs":{"fg":"a","bg":"b"}}"#), UNBOUNDED);
1373        assert_eq!(
1374            hides(r#"{"op":"blend","inputs":{"fg":"a","bg":"b"},"params":{"mode":"multiply"}}"#),
1375            EMPTY
1376        );
1377        assert_eq!(hides(r#"{"op":"mix","inputs":{"a":"a","b":"b"}}"#), EMPTY);
1378        // A cropped solid, moved: still upright; turned: unknown.
1379        let crop = at(
1380            r#"{"op":"crop","inputs":{"source":"s"},"params":{"rect":[0,0,200,270]}}"#,
1381            &[UNBOUNDED],
1382        );
1383        assert!(
1384            contains([0.0, 0.0, 200.0, 270.0], crop) && contains(crop, [4.0, 4.0, 196.0, 266.0]),
1385            "{crop:?}"
1386        );
1387        let moved = at(
1388            r#"{"op":"transform","inputs":{"source":"c"},"params":{"position":[340,135]}}"#,
1389            &[crop],
1390        );
1391        assert!(
1392            contains([100.0, 0.0, 300.0, 270.0], moved) && contains(moved, [106.0, 6.0, 294.0, 264.0]),
1393            "{moved:?}"
1394        );
1395        let turned = at(
1396            r#"{"op":"transform","inputs":{"source":"c"},"params":{"rotation":10}}"#,
1397            &[crop],
1398        );
1399        assert_eq!(turned, EMPTY);
1400        assert_eq!(
1401            at(
1402                r#"{"op":"transform","inputs":{"source":"c"},"params":{"rotation":10}}"#,
1403                &[UNBOUNDED]
1404            ),
1405            UNBOUNDED
1406        );
1407        assert_eq!(
1408            at(
1409                r#"{"op":"transform","inputs":{"source":"c"},"params":{"scale":0}}"#,
1410                &[UNBOUNDED]
1411            ),
1412            EMPTY
1413        );
1414    }
1415}