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/// Gradient block: stop count, space, 4 geometry floats, 8 stops of
698/// (position, premultiplied rgba).
699pub const GRADIENT_PARAMS: usize = 6 + 8 * 5;
700
701/// Parses gradient stops: `"0:#ff0000, 0.5:#00ff0080, 1:#0000ff"`, or a
702/// flat vector of `[pos, r, g, b, a]` groups (sRGB, straight alpha).
703fn parse_stops(p: &Param, t: f64) -> Option<Vec<(f64, [f64; 4])>> {
704    match p {
705        Param::Text(s) => s
706            .split(',')
707            .map(|part| {
708                let (pos, col) = part.trim().split_once(':')?;
709                Some((pos.trim().parse().ok()?, parse_hex(col.trim())?))
710            })
711            .collect(),
712        p => {
713            let v = p.eval(t)?;
714            (v.len() % 5 == 0 && !v.is_empty())
715                .then(|| v.chunks_exact(5).map(|c| (c[0], [c[1], c[2], c[3], c[4]])).collect())
716        }
717    }
718}
719
720pub const BLEND_MODES: &[&str] = &[
721    "normal",
722    "multiply",
723    "screen",
724    "overlay",
725    "darken",
726    "lighten",
727    "color_dodge",
728    "color_burn",
729    "hard_light",
730    "soft_light",
731    "difference",
732    "exclusion",
733    "hue",
734    "saturation",
735    "color",
736    "luminosity",
737    "add",
738    "subtract",
739    "divide",
740];
741
742fn space(id: &str, node: &Node) -> Result<f32, OpsError> {
743    match text(node, "space").unwrap_or("linear") {
744        "linear" => Ok(0.0),
745        "srgb" => Ok(1.0),
746        other => Err(bad(id, "space", format!("unknown space `{other}` (linear | srgb)"))),
747    }
748}
749
750fn bad(id: &str, param: &str, reason: String) -> OpsError {
751    OpsError::BadParam {
752        node: id.to_string(),
753        param: param.to_string(),
754        reason,
755    }
756}
757
758struct Packer<'a> {
759    id: &'a str,
760    node: &'a Node,
761    t: f64,
762}
763
764impl Packer<'_> {
765    fn vecn(&self, name: &str, default: &[f64]) -> ultrafast_graph::Vals {
766        let mut v = self
767            .node
768            .params
769            .get(name)
770            .and_then(|p| p.eval_vals(self.t))
771            .unwrap_or_else(|| ultrafast_graph::Vals::from_slice(default));
772        // Broadcast a scalar to the expected width; pad or truncate otherwise.
773        if v.len() == 1 && default.len() > 1 {
774            v = ultrafast_graph::Vals::filled(v[0], default.len());
775        }
776        v.resize(default.len(), 0.0);
777        v
778    }
779
780    fn vec(&self, out: &mut Vec<f32>, name: &str, default: &[f64]) {
781        out.extend(self.vecn(name, default).into_iter().map(|x| x as f32));
782    }
783
784    fn num(&self, name: &str, default: f64) -> f64 {
785        self.vecn(name, &[default])[0]
786    }
787
788    /// Packs a gradient: stops (from `stops`, else `a`/`b`), interpolation
789    /// space, and geometry for the kind.
790    fn gradient(
791        &self,
792        out: &mut Vec<f32>,
793        func: &str,
794        a: [f64; 4],
795        b: [f64; 4],
796        center: [f64; 2],
797        h: f64,
798    ) -> Result<(), OpsError> {
799        let mut stops = match self.node.params.get("stops") {
800            Some(p) => parse_stops(p, self.t).ok_or_else(|| {
801                bad(
802                    self.id,
803                    "stops",
804                    "use \"pos:#rrggbb, ...\" or [pos, r, g, b, a, ...]".into(),
805                )
806            })?,
807            None => {
808                let mut ca = Vec::new();
809                let mut cb = Vec::new();
810                self.color_straight(&mut ca, "a", a)?;
811                self.color_straight(&mut cb, "b", b)?;
812                vec![(0.0, [ca[0], ca[1], ca[2], ca[3]]), (1.0, [cb[0], cb[1], cb[2], cb[3]])]
813            }
814        };
815        stops.sort_by(|x, y| x.0.partial_cmp(&y.0).unwrap());
816        stops.truncate(8);
817        let encoded = match text(self.node, "space").unwrap_or("linear") {
818            "linear" => false,
819            "srgb" => true,
820            o => return Err(bad(self.id, "space", format!("unknown space `{o}` (linear | srgb)"))),
821        };
822        out.push(stops.len() as f32);
823        out.push(encoded as u8 as f32);
824        match func {
825            "gradient_linear" => {
826                self.vec(out, "start", &[0.0, 0.0]);
827                self.vec(out, "end", &[0.0, h]);
828            }
829            "gradient_radial" => {
830                self.vec(out, "center", &center);
831                self.vec(out, "radius", &[center[0].max(center[1])]);
832                out.push(0.0);
833            }
834            _ => {
835                self.vec(out, "center", &center);
836                out.push(self.num("angle", 0.0).to_radians() as f32);
837                out.push(0.0);
838            }
839        }
840        for k in 0..8 {
841            let (pos, c) = stops.get(k).copied().unwrap_or((1.0, [0.0; 4]));
842            // Premultiplied, in the interpolation space.
843            let al = c[3].clamp(0.0, 1.0);
844            let ch = |x: f64| if encoded { x * al } else { srgb_to_linear(x) * al };
845            out.extend([pos as f32, ch(c[0]) as f32, ch(c[1]) as f32, ch(c[2]) as f32, al as f32]);
846        }
847        Ok(())
848    }
849
850    /// A document color as straight sRGB (no conversion).
851    fn color_straight(&self, out: &mut Vec<f64>, name: &str, default: [f64; 4]) -> Result<(), OpsError> {
852        let c = match self.node.params.get(name) {
853            None => default,
854            Some(Param::Text(s)) => parse_hex(s).ok_or_else(|| {
855                bad(
856                    self.id,
857                    name,
858                    format!("`{s}` is not a #rgb, #rrggbb or #rrggbbaa color"),
859                )
860            })?,
861            Some(p) => {
862                let v = p.eval(self.t).unwrap_or_default();
863                match v.len() {
864                    3 => [v[0], v[1], v[2], 1.0],
865                    4 => [v[0], v[1], v[2], v[3]],
866                    _ => return Err(bad(self.id, name, "color needs 3 or 4 components".into())),
867                }
868            }
869        };
870        out.extend(c);
871        Ok(())
872    }
873
874    /// Document colors are straight-alpha, sRGB-encoded: `[r,g,b(,a)]` in 0..1
875    /// or `#rrggbb(aa)`. The engine works in linear premultiplied.
876    fn color(&self, out: &mut Vec<f32>, name: &str, default: [f64; 4]) -> Result<(), OpsError> {
877        let c = match self.node.params.get(name) {
878            None => default,
879            Some(Param::Text(s)) => parse_hex(s).ok_or_else(|| {
880                bad(
881                    self.id,
882                    name,
883                    format!("`{s}` is not a #rgb, #rrggbb or #rrggbbaa color"),
884                )
885            })?,
886            Some(p) => {
887                let v = p.eval(self.t).unwrap_or_default();
888                match v.len() {
889                    3 => [v[0], v[1], v[2], 1.0],
890                    4 => [v[0], v[1], v[2], v[3]],
891                    _ => return Err(bad(self.id, name, "color needs 3 or 4 components".into())),
892                }
893            }
894        };
895        let a = c[3].clamp(0.0, 1.0);
896        out.extend([
897            (srgb_to_linear(c[0]) * a) as f32,
898            (srgb_to_linear(c[1]) * a) as f32,
899            (srgb_to_linear(c[2]) * a) as f32,
900            a as f32,
901        ]);
902        Ok(())
903    }
904}
905
906/// Homography mapping 4 `from` points to 4 `to` points, row-major 3x3.
907pub fn homography(from: &[[f64; 2]; 4], to: &[[f64; 2]; 4]) -> Option<[f64; 9]> {
908    // Solve the 8x8 linear system with h33 = 1.
909    let mut m = [[0.0f64; 9]; 8];
910    for i in 0..4 {
911        let (x, y) = (from[i][0], from[i][1]);
912        let (u, v) = (to[i][0], to[i][1]);
913        m[2 * i] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
914        m[2 * i + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
915    }
916    for col in 0..8 {
917        let piv = (col..8).max_by(|&a, &b| m[a][col].abs().partial_cmp(&m[b][col].abs()).unwrap())?;
918        if m[piv][col].abs() < 1e-12 {
919            return None;
920        }
921        m.swap(col, piv);
922        for row in 0..8 {
923            if row != col {
924                let f = m[row][col] / m[col][col];
925                for k in col..9 {
926                    m[row][k] -= f * m[col][k];
927                }
928            }
929        }
930    }
931    let mut h = [0.0; 9];
932    for i in 0..8 {
933        h[i] = m[i][8] / m[i][i];
934    }
935    h[8] = 1.0;
936    Some(h)
937}
938
939#[cfg(test)]
940mod tests {
941    fn placed(params: &str) -> ([f64; 4], [f64; 4]) {
942        let node: Node =
943            serde_json::from_str(&format!(r#"{{"op":"image","params":{{"src":"a.jpg"{params}}}}}"#)).unwrap();
944        let p = Packer {
945            id: "img",
946            node: &node,
947            t: 0.0,
948        };
949        // A portrait picture (1280x1551) on a 1080x1920 frame.
950        placement(
951            &p,
952            1080.0,
953            1920.0,
954            Some(ResourceInfo {
955                width: 1280,
956                height: 1551,
957            }),
958        )
959        .unwrap()
960    }
961
962    #[test]
963    fn pictures_keep_their_shape_in_a_box_unless_asked_to_fill() {
964        let whole = [0.0, 0.0, 1.0, 1.0];
965        // Cover (the default in a box): the box filled, the sides cropped evenly.
966        let (r, w) = placed(r#","rect":[40,190,1000,1560]"#);
967        assert_eq!(r, [40.0, 190.0, 1000.0, 1560.0]);
968        let u = (1000.0 / 1560.0) / (1280.0 / 1551.0);
969        assert!(
970            (w[0] - (1.0 - u) / 2.0).abs() < 1e-9
971                && (w[2] - (1.0 + u) / 2.0).abs() < 1e-9
972                && w[1] == 0.0
973                && w[3] == 1.0,
974            "{w:?}"
975        );
976        assert_eq!(placed(r#","rect":[40,190,1000,1560],"fit":"cover""#), (r, w));
977        // Contain: the whole picture, centred in the box.
978        let (r, w) = placed(r#","rect":[40,190,1000,1560],"fit":"contain""#);
979        assert!(
980            (r[2] - 1000.0).abs() < 1e-9 && (r[3] - 1000.0 * 1551.0 / 1280.0).abs() < 1e-9 && w == whole,
981            "{r:?}"
982        );
983        assert!((r[1] - (190.0 + (1560.0 - r[3]) / 2.0)).abs() < 1e-9);
984        // Fill stretches only when asked for.
985        assert_eq!(
986            placed(r#","rect":[40,190,1000,1560],"fit":"fill""#),
987            ([40.0, 190.0, 1000.0, 1560.0], whole)
988        );
989        // A box of the picture's own shape draws it exactly there, as before.
990        assert_eq!(placed(r#","rect":[0,0,640,775.5]"#), ([0.0, 0.0, 640.0, 775.5], whole));
991        // Without a box nothing changes: contain in the frame by default.
992        let (r, w) = placed("");
993        assert!(
994            (r[2] - 1080.0).abs() < 1e-9 && (r[0]).abs() < 1e-9 && w == whole,
995            "{r:?}"
996        );
997    }
998
999    #[test]
1000    fn sequence_frames_land_on_boundaries_after_offsets() {
1001        let node: Node =
1002            serde_json::from_str(r#"{"op":"image","params":{"src":"f{frame:03}.png","first_frame":5}}"#).unwrap();
1003        // Local times of frames under a 0.37 s offset; some land a hair
1004        // under their boundary (f / 30 * 30 < f).
1005        let under = (0..300u32)
1006            .filter(|&f| ((f as f64 / 30.0 + 0.37) - 0.37) * 30.0 < f as f64)
1007            .count();
1008        assert!(under > 0);
1009        for f in 0..300u32 {
1010            let lt = (f as f64 / 30.0 + 0.37) - 0.37;
1011            assert_eq!(
1012                sequence_path("f{frame}.png", &node, lt, 30.0),
1013                format!("f{}.png", f + 5),
1014                "frame {f}"
1015            );
1016        }
1017    }
1018
1019    use super::*;
1020
1021    #[test]
1022    fn every_op_packs_its_declared_size() {
1023        let fmt = Format {
1024            width: 64,
1025            height: 32,
1026            fps: 30.0,
1027            duration: 1.0,
1028            motion_blur: None,
1029        };
1030        for def in OPS {
1031            let node = Node {
1032                op: def.name.into(),
1033                ..Default::default()
1034            };
1035            let mut out = Vec::new();
1036            pack(def, "n", &node, &fmt, 0.0, None, &mut out).unwrap();
1037            assert_eq!(out.len(), def.params, "{}", def.func);
1038        }
1039    }
1040
1041    #[test]
1042    fn colors_are_linearized_and_premultiplied() {
1043        let mut node = Node {
1044            op: "solid".into(),
1045            ..Default::default()
1046        };
1047        node.params.insert("color".into(), Param::Text("#ffffff80".into()));
1048        let fmt = Format {
1049            width: 1,
1050            height: 1,
1051            fps: 1.0,
1052            duration: 1.0,
1053            motion_blur: None,
1054        };
1055        let mut out = Vec::new();
1056        pack(resolve("n", &node).unwrap(), "n", &node, &fmt, 0.0, None, &mut out).unwrap();
1057        let a = 128.0 / 255.0;
1058        assert!((out[0] - a as f32).abs() < 1e-6);
1059        assert!((out[3] - a as f32).abs() < 1e-6);
1060    }
1061
1062    #[test]
1063    fn homography_maps_corners() {
1064        let from = [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0]];
1065        let to = [[1.0, 2.0], [12.0, 1.0], [11.0, 13.0], [0.0, 9.0]];
1066        let h = homography(&from, &to).unwrap();
1067        for i in 0..4 {
1068            let (x, y) = (from[i][0], from[i][1]);
1069            let w = h[6] * x + h[7] * y + h[8];
1070            let u = (h[0] * x + h[1] * y + h[2]) / w;
1071            let v = (h[3] * x + h[4] * y + h[5]) / w;
1072            assert!((u - to[i][0]).abs() < 1e-9 && (v - to[i][1]).abs() < 1e-9);
1073        }
1074    }
1075
1076    #[test]
1077    fn affine_inverse_roundtrips() {
1078        let m = Affine::translate(5.0, 3.0)
1079            .mul(Affine::rotate(0.7))
1080            .mul(Affine::scale(2.0, 0.5));
1081        let (x, y) = m.apply(3.0, -4.0);
1082        let (bx, by) = m.inverse().unwrap().apply(x, y);
1083        assert!((bx - 3.0).abs() < 1e-9 && (by + 4.0).abs() < 1e-9);
1084    }
1085
1086    /// A layer that grows from zero scale (or a pin that unfolds from a
1087    /// point) shows nothing at that moment instead of failing the render:
1088    /// every point maps far outside it, and it has no bounds.
1089    #[test]
1090    fn zero_scale_shows_nothing() {
1091        let fmt = Format {
1092            width: 64,
1093            height: 32,
1094            fps: 30.0,
1095            duration: 1.0,
1096            motion_blur: None,
1097        };
1098        let grows: Node = serde_json::from_str(
1099            r#"{"op":"transform","params":{"scale":{"keys":[{"t":0,"v":[0,0]},{"t":1,"v":[1,1]}]}}}"#,
1100        )
1101        .unwrap();
1102        let unfolds: Node = serde_json::from_str(
1103            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]}]}}}"#,
1104        )
1105        .unwrap();
1106        let shape = [10.0, 10.0, 20.0, 20.0];
1107        for node in [&grows, &unfolds] {
1108            let def = resolve("n", node).unwrap();
1109            let mut out = Vec::new();
1110            pack(def, "n", node, &fmt, 0.0, None, &mut out).unwrap();
1111            assert_eq!(out.len(), def.params, "{}", def.func);
1112            assert!(out.iter().all(|x| x.is_finite()), "{}: {out:?}", def.func);
1113            // Grown halfway it is drawn as usual.
1114            out.clear();
1115            pack(def, "n", node, &fmt, 0.5, None, &mut out).unwrap();
1116            assert!(out.iter().any(|x| *x != 0.0), "{}: {out:?}", def.func);
1117        }
1118        let mut out = Vec::new();
1119        pack(resolve("n", &grows).unwrap(), "n", &grows, &fmt, 0.0, None, &mut out).unwrap();
1120        let (x, y) = (
1121            out[0] * 20.0 + out[2] * 7.0 + out[4],
1122            out[1] * 20.0 + out[3] * 7.0 + out[5],
1123        );
1124        assert!(x < -1e8 && y < -1e8, "({x}, {y})");
1125        let def = resolve("n", &grows).unwrap();
1126        assert_eq!(bounds(def, &grows, &fmt, 0.0, &[shape], None), EMPTY);
1127        assert_eq!(bounds(def, &grows, &fmt, 0.0, &[UNBOUNDED], None), EMPTY);
1128        let half = bounds(def, &grows, &fmt, 0.5, &[shape], None);
1129        assert!(half[0] < half[2] && half[1] < half[3], "{half:?}");
1130    }
1131}