Skip to main content

ultrafast_render/
layout.rs

1//! `stack`: lays its inputs out in a column or a row by their measured
2//! bounds, so agents compose blocks of type, artwork and shapes without
3//! computing positions. Each child is wrapped in a translation (absorbed by
4//! vector content, so it stays sharp), and the stack becomes their
5//! composite. Children keep their own animation, relative to the layout.
6
7use crate::geom::{self, Fonts};
8use crate::ops::Affine;
9use std::collections::BTreeMap;
10use std::path::Path;
11use ultrafast_graph::{Document, Node, Param};
12
13pub fn used_by(doc: &Document) -> bool {
14    doc.nodes.values().any(|n| n.op == "stack")
15}
16
17fn num(node: &Node, k: &str, d: f64) -> f64 {
18    node.params
19        .get(k)
20        .and_then(|p| p.eval(0.0))
21        .and_then(|v| v.first().copied())
22        .unwrap_or(d)
23}
24
25fn text<'a>(node: &'a Node, k: &str) -> Option<&'a str> {
26    match node.params.get(k) {
27        Some(Param::Text(s)) => Some(s),
28        _ => None,
29    }
30}
31
32/// Frame bounds [x0, y0, x1, y1] of a child as placed by its own params,
33/// at time `t`.
34fn bounds(
35    id: &str,
36    t: f64,
37    doc: &Document,
38    done: &BTreeMap<String, [f64; 4]>,
39    fonts: &mut Fonts,
40    base: &Path,
41) -> Result<[f64; 4], String> {
42    if let Some(b) = done.get(id) {
43        return Ok(*b);
44    }
45    let node = doc.nodes.get(id).ok_or_else(|| format!("no node `{id}`"))?;
46    let geo = |g: geom::Geometry| {
47        [
48            g.bounds[0] as f64,
49            g.bounds[1] as f64,
50            g.bounds[2] as f64,
51            g.bounds[3] as f64,
52        ]
53    };
54    match node.op.as_str() {
55        "text" => geom::text_node(id, node, &doc.format, t, Affine::IDENTITY, fonts, base)
56            .map(geo)
57            .map_err(|e| e.to_string()),
58        "path" => geom::path(id, node, &doc.format, t, Affine::IDENTITY)
59            .map(geo)
60            .map_err(|e| e.to_string()),
61        "shape" => {
62            let c = node.params.get("center").and_then(|p| p.eval(t)).unwrap_or_default();
63            let s = node.params.get("size").and_then(|p| p.eval(t)).unwrap_or_default();
64            let k = node
65                .params
66                .get("scale")
67                .and_then(|p| p.eval(t))
68                .unwrap_or_else(|| vec![1.0]);
69            let (cx, cy) = (c.first().copied().unwrap_or(0.0), c.get(1).copied().unwrap_or(0.0));
70            let (kx, ky) = (
71                k.first().copied().unwrap_or(1.0).abs(),
72                k.get(1).or(k.first()).copied().unwrap_or(1.0).abs(),
73            );
74            let (w, h) = (
75                s.first().copied().unwrap_or(0.0) * kx,
76                s.get(1).or(s.first()).copied().unwrap_or(0.0) * ky,
77            );
78            Ok([cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0])
79        }
80        "svg" => {
81            let imp = crate::svg::import_node(node, base)?;
82            let p = node.params.get("position").and_then(|p| p.eval(t)).unwrap_or_default();
83            let a = node.params.get("anchor").and_then(|p| p.eval(t)).unwrap_or_default();
84            let x = p.first().copied().unwrap_or(0.0) - a.first().copied().unwrap_or(0.0);
85            let y = p.get(1).copied().unwrap_or(0.0) - a.get(1).copied().unwrap_or(0.0);
86            Ok([x, y, x + imp.size[0], y + imp.size[1]])
87        }
88        // A spacer: `size` [w, h] of empty room.
89        "solid" if node.params.contains_key("size") => {
90            let s = node.params.get("size").and_then(|p| p.eval(0.0)).unwrap_or_default();
91            Ok([
92                0.0,
93                0.0,
94                s.first().copied().unwrap_or(0.0),
95                s.get(1).copied().unwrap_or(0.0),
96            ])
97        }
98        other => Err(format!(
99            "`stack` lays out text, path, shape, svg and stack nodes; `{id}` is a `{other}` (wrap it in a stack with a fixed-size spacer, or place it by hand)"
100        )),
101    }
102}
103
104/// `doc` with every `stack` expanded into translated children and their
105/// composite. Problems are reported per node; a failed stack shows nothing.
106pub fn expand(doc: &Document, fonts: &mut Fonts, base: &Path) -> (Document, Vec<(String, String)>) {
107    let mut d = doc.clone();
108    let mut problems = Vec::new();
109    let mut done: BTreeMap<String, [f64; 4]> = BTreeMap::new();
110    // Per expanded stack, the translations that place its leaves: an outer
111    // stack moves those instead of wrapping (and resampling) the composite.
112    let mut leaves: BTreeMap<String, Vec<String>> = BTreeMap::new();
113    // Inner stacks first, so outer ones can measure them.
114    let order = match doc.reachable_topo_order() {
115        Ok(o) => o,
116        Err(e) => return (d, vec![(String::new(), e.to_string())]),
117    };
118    let mut stacks: Vec<String> = order.into_iter().filter(|id| doc.nodes[id].op == "stack").collect();
119    // Stacks not reachable from the output are still expanded (they may be
120    // previewed); they go last.
121    for (id, n) in &doc.nodes {
122        if n.op == "stack" && !stacks.contains(id) {
123            stacks.push(id.clone());
124        }
125    }
126    for id in stacks {
127        let node = d.nodes[&id].clone();
128        let mut ports: Vec<(&String, &String)> = node.inputs.iter().collect();
129        ports.sort_by_key(|(p, _)| {
130            p.trim_start_matches(|c: char| !c.is_ascii_digit())
131                .parse::<u32>()
132                .unwrap_or(u32::MAX)
133        });
134        let children: Vec<String> = ports.iter().map(|(_, src)| (*src).clone()).collect();
135        let row = text(&node, "direction") == Some("row");
136        let gap = num(&node, "gap", 24.0);
137        let align = text(&node, "align").unwrap_or("start").to_string();
138        let anchor = text(&node, "anchor").unwrap_or("top_left").replace('-', "_");
139        let pos = node
140            .params
141            .get("position")
142            .and_then(|p| p.eval(0.0))
143            .unwrap_or_default();
144        let pos = [pos.first().copied().unwrap_or(0.0), pos.get(1).copied().unwrap_or(0.0)];
145        let mut bs = Vec::new();
146        let mut failed = None;
147        // Children are measured at `at` seconds: when entrances have landed.
148        let at = num(&node, "at", 0.0);
149        for c in &children {
150            match bounds(c, at, &d, &done, fonts, base) {
151                Ok(b) => bs.push(b),
152                Err(e) => {
153                    failed = Some(e);
154                    break;
155                }
156            }
157        }
158        let empty = || Node {
159            op: "solid".into(),
160            params: [("color".to_string(), Param::Text("#00000000".into()))].into(),
161            ..Default::default()
162        };
163        if let Some(e) = failed {
164            problems.push((id.clone(), e));
165            d.nodes.insert(id.clone(), empty());
166            continue;
167        }
168        if children.is_empty() {
169            d.nodes.insert(id.clone(), empty());
170            continue;
171        }
172        let size = |b: &[f64; 4]| (b[2] - b[0], b[3] - b[1]);
173        let main: f64 =
174            bs.iter().map(|b| if row { size(b).0 } else { size(b).1 }).sum::<f64>() + gap * (bs.len() - 1) as f64;
175        let cross = bs
176            .iter()
177            .map(|b| if row { size(b).1 } else { size(b).0 })
178            .fold(0.0, f64::max);
179        let (w, h) = if row { (main, cross) } else { (cross, main) };
180        // Where the block's top-left goes, from its anchor.
181        let fx = if anchor.ends_with("left") {
182            0.0
183        } else if anchor.ends_with("right") {
184            1.0
185        } else {
186            0.5
187        };
188        let fy = if anchor.starts_with("top") {
189            0.0
190        } else if anchor.starts_with("bottom") {
191            1.0
192        } else {
193            0.5
194        };
195        let (bx, by) = (pos[0] - fx * w, pos[1] - fy * h);
196        let along = match align.as_str() {
197            "center" => 0.5,
198            "end" => 1.0,
199            _ => 0.0,
200        };
201        let mut cursor = 0.0;
202        let mut layers = Vec::new();
203        let mut mine = Vec::new();
204        for (k, (c, b)) in children.iter().zip(&bs).enumerate() {
205            let (cw, ch) = size(b);
206            let (tx, ty) = if row {
207                (bx + cursor, by + (h - ch) * along)
208            } else {
209                (bx + (w - cw) * along, by + cursor)
210            };
211            cursor += if row { cw } else { ch } + gap;
212            let (dx, dy) = (tx - b[0], ty - b[1]);
213            if let Some(inner) = leaves.get(c).cloned() {
214                // A stack inside: move its leaves.
215                for l in &inner {
216                    if let Some(Param::Vector(v)) = d.nodes.get_mut(l).and_then(|n| n.params.get_mut("position")) {
217                        v[0] += dx;
218                        v[1] += dy;
219                    }
220                }
221                mine.extend(inner);
222                layers.push(c.clone());
223                continue;
224            }
225            let tid = format!("{id}/{k}");
226            let mut p = BTreeMap::new();
227            p.insert("anchor".to_string(), Param::Vector(vec![0.0, 0.0]));
228            p.insert("position".to_string(), Param::Vector(vec![dx, dy]));
229            d.nodes.insert(
230                tid.clone(),
231                Node {
232                    op: "transform".into(),
233                    params: p,
234                    inputs: [("source".to_string(), c.clone())].into(),
235                    ..Default::default()
236                },
237            );
238            mine.push(tid.clone());
239            layers.push(tid);
240        }
241        let mut acc = layers[0].clone();
242        for (k, l) in layers.iter().enumerate().skip(1) {
243            let oid = if k == layers.len() - 1 {
244                id.clone()
245            } else {
246                format!("{id}/over{k}")
247            };
248            d.nodes.insert(
249                oid.clone(),
250                Node {
251                    op: "over".into(),
252                    inputs: [("fg".to_string(), l.clone()), ("bg".to_string(), acc)].into(),
253                    timing: if k == layers.len() - 1 { node.timing } else { None },
254                    ..Default::default()
255                },
256            );
257            acc = oid;
258        }
259        if layers.len() == 1 {
260            // The stack is its only child, moved.
261            let only = layers[0].clone();
262            let mut t = d.nodes.get(&only).cloned().unwrap();
263            if mine.contains(&only) {
264                d.nodes.remove(&only);
265                mine.retain(|m| *m != only);
266                mine.push(id.clone());
267            } else {
268                // A single inner stack: the outer is just a pass-through.
269                t = Node {
270                    op: "opacity".into(),
271                    params: [("opacity".to_string(), Param::Number(1.0))].into(),
272                    inputs: [("source".to_string(), only)].into(),
273                    ..Default::default()
274                };
275            }
276            t.timing = node.timing;
277            d.nodes.insert(id.clone(), t);
278        }
279        done.insert(id.clone(), [bx, by, bx + w, by + h]);
280        leaves.insert(id.clone(), mine);
281    }
282    (d, problems)
283}