Skip to main content

ultrafast_render/
plan.rs

1//! Graph -> render plan compiler.
2//!
3//! The plan partitions the nodes reachable from the output into **groups**.
4//! Each group becomes one GPU kernel: its root node plus every upstream node
5//! that can be evaluated inline (generators, per-pixel maps, warps) and has no
6//! other consumer. Nodes that must exist as textures (the output, nodes with
7//! several consumers, inputs of multi-tap ops like blur, agent shaders) are
8//! group roots. This is operation fusion: a stack of 30 animated layers over a
9//! background is one dispatch with no intermediate textures.
10//!
11//! Plans are rebuilt only when the document's *structure signature* changes
12//! (ops, wiring, kernel variants, which params are animated). Param edits
13//! reuse the plan and every compiled kernel unchanged.
14
15use crate::RenderError;
16use crate::codegen::{self, Child, SpecNode};
17use crate::ops::{self, Form, OpDef};
18use std::collections::HashMap;
19use std::sync::Arc;
20use ultrafast_graph::{Document, NodeId, Timing};
21
22/// A static subtree at least this heavy is cached as its own texture rather
23/// than re-evaluated inside an animated consumer every frame.
24const HEAVY_STATIC: usize = 4;
25/// Texture bindings available to one kernel (T0..T15).
26pub const MAX_TEXTURES: usize = 16;
27
28#[derive(Debug, Clone)]
29pub struct PlanNode {
30    pub id: NodeId,
31    pub def: &'static OpDef,
32    /// Timing chain (outermost first): local time and visibility windows.
33    pub chain: Vec<Timing>,
34    /// Has a visibility window somewhere in its chain.
35    pub gated: bool,
36    /// Connected input nodes, in port order.
37    pub inputs: Vec<usize>,
38    pub is_static: bool,
39    pub variant: String,
40    /// Agent code's big constant tables, packed after the node's params
41    /// (its `variant` reads them there; see [`crate::tables`]).
42    pub tables: Option<Arc<[f32]>>,
43}
44
45/// Where a kernel texture binding comes from.
46#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub enum TexSource {
48    /// Output of an earlier group.
49    Group(usize),
50    /// An external resource (image file, ...), keyed by its source string.
51    Resource(String),
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum GroupKind {
56    /// One generated kernel.
57    Fused,
58    /// Two-pass separable blur of its single input.
59    Blur,
60    /// GPU coverage rasterization of vector geometry (path, text).
61    Raster,
62    /// 3D pass: meshes, lights and a camera rendered with depth and MSAA.
63    Render3D,
64    /// Particle sprites, drawn into a texture sized to their bounds.
65    Particles,
66    /// A simulation stepped once per frame from its own persistent state.
67    Sim,
68}
69
70/// A raster node plus the transforms stacked directly on it, which are
71/// applied to the geometry before rasterization instead of resampling.
72#[derive(Debug, Clone)]
73pub struct RasterChain {
74    pub node: usize,
75    /// Absorbed `transform` nodes, innermost first.
76    pub transforms: Vec<usize>,
77}
78
79/// A run of layers ([`codegen::RunLayout`]) with plan node indices.
80#[derive(Debug, Clone)]
81pub struct PlanRun {
82    pub stride: usize,
83    pub payload: usize,
84    /// (kind, composite node, layer): a texture binding or a generator node.
85    pub layers: Vec<(usize, usize, codegen::LayerRef)>,
86}
87
88/// One piece of a group's param block ([`codegen::Slot`], with plan node
89/// indices).
90#[derive(Debug, Clone, PartialEq)]
91pub enum ParamSlot {
92    /// A node's block: its op params, its window flag, its guard rect.
93    Node(usize),
94    /// Where run `r` (of [`Group::runs`]) starts and how many of its layers
95    /// show this frame.
96    Run(usize),
97    Value(f32),
98    /// Zeros.
99    Pad(usize),
100    /// Two floats per texture binding.
101    Origins,
102}
103
104#[derive(Debug, Clone)]
105pub struct Group {
106    pub kind: GroupKind,
107    /// Plan node index of the root.
108    pub root: usize,
109    /// Every node evaluated in this group, root last.
110    pub nodes: Vec<usize>,
111    /// Texture bindings T0.., in kernel order.
112    pub textures: Vec<TexSource>,
113    /// What fills the param block after the 4-float frame header, in order.
114    pub params: Vec<ParamSlot>,
115    pub param_len: usize,
116    /// The kernel may read any texture binding: bind all 16.
117    pub pad_textures: bool,
118    /// Runs of layers composited in a loop: their layers, with plan node
119    /// indices.
120    pub runs: Vec<PlanRun>,
121    pub is_static: bool,
122    /// Output texture slot.
123    pub output: usize,
124    /// Kernel identity: hash of the generated code. Equal keys share kernels.
125    pub key: String,
126    /// Generated Slang for the kernel body (entry named by `codegen::ENTRY`).
127    pub body: String,
128    pub raster: Option<RasterChain>,
129}
130
131#[derive(Debug, Clone)]
132pub struct Plan {
133    pub signature: u64,
134    pub nodes: Vec<PlanNode>,
135    pub groups: Vec<Group>,
136    /// For each node, the group it is the root of (usize::MAX if inlined).
137    pub group_of: Vec<usize>,
138    /// For each node, the one group it is part of ([`SHARED`] when several
139    /// groups evaluate it, usize::MAX when none): an O(1) membership test.
140    pub owner: Vec<usize>,
141    pub slot_count: usize,
142    pub output_slot: usize,
143    /// With motion blur: the group holding every moving layer, after which
144    /// only finishing looks follow, and which groups are those looks (run
145    /// once per frame on the blurred image).
146    pub mb_split: Option<usize>,
147    pub post: Vec<bool>,
148    /// Per group: bitset of the plan nodes its root depends on.
149    pub group_up: Vec<Vec<u64>>,
150    /// Per group: the groups its root depends on are exactly those before it.
151    pub prefix: Vec<bool>,
152    /// Per node: a generator only used as an overlay texture.
153    pub overlay: Vec<bool>,
154    /// Nodes present in the document but not reachable from the output.
155    pub eliminated: Vec<NodeId>,
156    /// Per group: its output is only ever read where it lands in the frame
157    /// (per-pixel ops all the way to the output), so content outside the
158    /// frame is never seen and need not be drawn.
159    pub framed: Vec<bool>,
160}
161
162/// Hash of everything that shapes the plan. Cheap enough to compute after
163/// every edit batch.
164/// Timing chains of flattened nodes (see [`ultrafast_graph::Flat`]).
165pub type Chains = HashMap<NodeId, Vec<Timing>>;
166
167fn gated(chains: Option<&Chains>, id: &str) -> bool {
168    chains
169        .and_then(|c| c.get(id))
170        .is_some_and(|c| c.iter().any(Timing::has_window))
171}
172
173pub fn signature(doc: &Document, chains: Option<&Chains>) -> u64 {
174    use std::hash::{Hash, Hasher};
175    let mut h = std::collections::hash_map::DefaultHasher::new();
176    doc.output.hash(&mut h);
177    (doc.format.width, doc.format.height).hash(&mut h);
178    doc.format.motion_blur.is_some_and(|m| m.samples > 1).hash(&mut h);
179    for (id, n) in &doc.nodes {
180        id.hash(&mut h);
181        n.op.hash(&mut h);
182        n.inputs.hash(&mut h);
183        // Kernel variant (gradient kind, shader code, image source) and which
184        // params are animated shape the plan; param values do not.
185        if let Ok(def) = ops::resolve(id, n) {
186            def.func.hash(&mut h);
187            ops::variant_key(def, n).hash(&mut h);
188        }
189        for (k, p) in &n.params {
190            if p.is_animated() {
191                k.hash(&mut h);
192            }
193        }
194        // A reduced-resolution shader is its own group.
195        ops::render_scale(n).is_some().hash(&mut h);
196        gated(chains, id).hash(&mut h);
197    }
198    h.finish()
199}
200
201pub fn compile(doc: &Document, chains: Option<&Chains>) -> Result<Plan, RenderError> {
202    let order = schedule(doc, &doc.reachable_topo_order()?);
203    let index: HashMap<&str, usize> = order.iter().enumerate().map(|(i, id)| (id.as_str(), i)).collect();
204
205    let mut nodes: Vec<PlanNode> = Vec::with_capacity(order.len());
206    for id in &order {
207        let node = &doc.nodes[id];
208        let def = ops::resolve(id, node)?;
209        let ports = ops::connected_ports(def, id, node)?;
210        let inputs: Vec<usize> = ports.iter().map(|p| index[node.inputs[p].as_str()]).collect();
211        let gated = gated(chains, id);
212        let is_static = !node.is_animated()
213            && !ops::time_varying(def, node)
214            && !gated
215            && inputs.iter().all(|&i| nodes[i].is_static);
216        // Video decoders and image sequences are per node (each has its own
217        // playhead: timing, first_frame, fps), so their resource identity
218        // includes the node id.
219        let mut variant = if def.name == "video" || (def.name == "image" && ops::time_varying(def, node)) {
220            format!("{}\u{1f}{id}", ops::variant_key(def, node))
221        } else {
222            ops::variant_key(def, node)
223        };
224        // Agent code's big tables are read from the params, not compiled in.
225        let tables = if matches!(def.form, Form::Custom | Form::Sim) {
226            crate::tables::hoist(&variant).map(|h| {
227                variant = h.code;
228                h.data
229            })
230        } else {
231            None
232        };
233        nodes.push(PlanNode {
234            id: id.clone(),
235            def,
236            chain: chains.and_then(|c| c.get(id)).cloned().unwrap_or_default(),
237            gated,
238            inputs,
239            is_static,
240            variant,
241            tables,
242        });
243    }
244    let n = nodes.len();
245
246    let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); n];
247    for (i, node) in nodes.iter().enumerate() {
248        for &s in &node.inputs {
249            consumers[s].push(i);
250        }
251    }
252    // Rough cost: nodes in the subtree, with agent shaders and fractal
253    // generators counting as heavy on their own (one node, many noise
254    // evaluations per pixel), so a still one is cached rather than fused
255    // into a consumer that changes every frame.
256    let mut weight = vec![1usize; n];
257    for i in 0..n {
258        if matches!(nodes[i].def.name, "shader" | "noise" | "marble") {
259            weight[i] = HEAVY_STATIC;
260        }
261        weight[i] += nodes[i].inputs.iter().map(|&s| weight[s]).sum::<usize>();
262    }
263
264    // Raster nodes absorb the chain of transforms stacked on them. Chain
265    // members other than the head are never materialized or inlined.
266    let mut chain_head = vec![usize::MAX; n];
267    let mut in_chain = vec![false; n];
268    for i in 0..n {
269        if nodes[i].def.form != Form::Raster {
270            continue;
271        }
272        let mut head = i;
273        while consumers[head].len() == 1 && nodes[consumers[head][0]].def.func == "transform" {
274            in_chain[head] = true;
275            head = consumers[head][0];
276        }
277        chain_head[head] = i;
278    }
279
280    // Which nodes must exist as textures.
281    if nodes.last().is_some_and(|o| o.def.form == Form::Object) {
282        let o = nodes.last().unwrap();
283        return Err(RenderError::BadParam {
284            node: o.id.clone(),
285            param: "output".into(),
286            reason: format!(
287                "`{}` is a 3D object, not an image: render it with a `render3d` node",
288                o.def.name
289            ),
290        });
291    }
292    let mut materialize: Vec<bool> = (0..n)
293        .map(|i| {
294            // Scene objects are data, never textures; 3D passes always are.
295            match nodes[i].def.form {
296                Form::Object => return false,
297                Form::Render3D | Form::Particles | Form::Sim => return true,
298                _ => {}
299            }
300            if ops::render_scale(&doc.nodes[&nodes[i].id]).is_some() {
301                return true;
302            }
303            // An agent shader with a timing window is its own pass: fused into
304            // a composite, it would run whenever anything else in that kernel
305            // shows (its window only switches its result off), and a raymarch
306            // or a simulation-sized shader is far costlier than the texture
307            // it takes to keep it apart.
308            if nodes[i].def.name == "shader" && nodes[i].gated {
309                return true;
310            }
311            if chain_head[i] != usize::MAX {
312                return true;
313            }
314            if in_chain[i] {
315                return false;
316            }
317            if i == n - 1 || consumers[i].len() != 1 || nodes[i].def.form == Form::Blur {
318                return true;
319            }
320            let c = &nodes[consumers[i][0]];
321            if matches!(
322                c.def.form,
323                Form::Blur | Form::Custom | Form::Object | Form::Render3D | Form::Particles | Form::Sim
324            ) {
325                return true;
326            }
327            nodes[i].is_static && !c.is_static && weight[i] >= HEAVY_STATIC
328        })
329        .collect();
330
331    // Motion blur: materialize the image every moving layer reaches, so the
332    // finishing looks after it can run once on the blurred result.
333    let split = if doc.format.motion_blur.is_some_and(|m| m.samples > 1) {
334        finishing_split(&nodes).filter(|&x| !in_chain[x] && chain_head[x] == usize::MAX)
335    } else {
336        None
337    };
338    if let Some(x) = split {
339        materialize[x] = true;
340    }
341
342    // Kernels bind at most 16 textures. Walking in dependency order, count
343    // the textures each inlined subtree would bring into its group; when a
344    // node would exceed the budget, materialize its heaviest inlined child
345    // (which then becomes its own group, already within budget).
346    let budget = MAX_TEXTURES - 1;
347    let mut contrib = vec![0usize; n];
348    for i in 0..n {
349        if nodes[i].def.form == Form::Object {
350            continue;
351        }
352        let resource = ops::uses_resource(nodes[i].def) as usize;
353        let child = |c: usize, m: &[bool], contrib: &[usize]| if m[c] { 1 } else { contrib[c] };
354        let mut own: usize = resource
355            + nodes[i]
356                .inputs
357                .iter()
358                .map(|&c| child(c, &materialize, &contrib))
359                .sum::<usize>();
360        while own > budget {
361            let heaviest = nodes[i]
362                .inputs
363                .iter()
364                .copied()
365                .filter(|&c| !materialize[c] && nodes[c].def.form != Form::Object)
366                .max_by_key(|&c| contrib[c]);
367            let Some(c) = heaviest else { break };
368            own = own - contrib[c] + 1;
369            materialize[c] = true;
370        }
371        contrib[i] = own;
372    }
373
374    let mut group_of = vec![usize::MAX; n];
375    let mut groups: Vec<Group> = Vec::new();
376    for root in 0..n {
377        if !materialize[root] {
378            continue;
379        }
380        let g = groups.len();
381        let group = if nodes[root].def.form == Form::Particles {
382            Group {
383                kind: GroupKind::Particles,
384                root,
385                is_static: false,
386                nodes: vec![root],
387                textures: nodes[root]
388                    .inputs
389                    .iter()
390                    .map(|&s| TexSource::Group(group_of[s]))
391                    .collect(),
392                params: Vec::new(),
393                pad_textures: false,
394                runs: Vec::new(),
395                param_len: 4,
396                output: usize::MAX,
397                key: String::new(),
398                body: String::new(),
399                raster: None,
400            }
401        } else if nodes[root].def.form == Form::Sim {
402            // Feedback steps run agent code: one generated kernel.
403            let (key, body) = if nodes[root].def.name == "feedback" {
404                crate::codegen::feedback(&nodes[root].variant, nodes[root].tables.is_some())
405            } else {
406                (String::new(), String::new())
407            };
408            Group {
409                kind: GroupKind::Sim,
410                root,
411                is_static: false,
412                nodes: vec![root],
413                textures: nodes[root]
414                    .inputs
415                    .iter()
416                    .map(|&s| TexSource::Group(group_of[s]))
417                    .collect(),
418                params: Vec::new(),
419                pad_textures: false,
420                runs: Vec::new(),
421                param_len: 4,
422                output: usize::MAX,
423                key,
424                body,
425                raster: None,
426            }
427        } else if nodes[root].def.form == Form::Render3D {
428            // Objects connected to the pass, and the images their materials use.
429            let objects: Vec<usize> = nodes[root]
430                .inputs
431                .iter()
432                .copied()
433                .filter(|&o| nodes[o].def.form == Form::Object)
434                .collect();
435            let mut textures = Vec::new();
436            // Images on the pass itself (an environment map), then the ones
437            // object materials use.
438            let images = nodes[root]
439                .inputs
440                .iter()
441                .filter(|&&s| nodes[s].def.form != Form::Object);
442            for &src in images.chain(objects.iter().flat_map(|&o| nodes[o].inputs.iter())) {
443                let ts = TexSource::Group(group_of[src]);
444                if !textures.contains(&ts) {
445                    textures.push(ts);
446                }
447            }
448            let mut members = objects.clone();
449            members.push(root);
450            Group {
451                kind: GroupKind::Render3D,
452                root,
453                is_static: members.iter().all(|&m| nodes[m].is_static),
454                nodes: members,
455                textures,
456                params: Vec::new(),
457                pad_textures: false,
458                runs: Vec::new(),
459                param_len: 4,
460                output: usize::MAX,
461                key: String::new(),
462                body: String::new(),
463                raster: None,
464            }
465        } else if chain_head[root] != usize::MAX {
466            let r = chain_head[root];
467            let mut transforms = Vec::new();
468            let mut cur = r;
469            while cur != root {
470                cur = consumers[cur][0];
471                transforms.push(cur);
472            }
473            let mut members = vec![r];
474            members.extend(&transforms);
475            Group {
476                kind: GroupKind::Raster,
477                root,
478                is_static: members.iter().all(|&m| nodes[m].is_static),
479                nodes: members,
480                textures: Vec::new(),
481                params: vec![ParamSlot::Node(r)],
482                pad_textures: false,
483                runs: Vec::new(),
484                param_len: 4 + nodes[r].def.params,
485                output: usize::MAX,
486                key: String::new(),
487                body: String::new(),
488                raster: Some(RasterChain { node: r, transforms }),
489            }
490        } else if nodes[root].def.form == Form::Blur {
491            let src = nodes[root].inputs[0];
492            Group {
493                kind: GroupKind::Blur,
494                root,
495                nodes: vec![root],
496                textures: vec![TexSource::Group(group_of[src])],
497                params: vec![ParamSlot::Node(root)],
498                pad_textures: false,
499                runs: Vec::new(),
500                param_len: 4 + nodes[root].def.params,
501                is_static: nodes[root].is_static,
502                output: usize::MAX,
503                key: String::new(),
504                body: String::new(),
505                raster: None,
506            }
507        } else {
508            build_fused(&nodes, &materialize, &group_of, root)?
509        };
510        group_of[root] = g;
511        groups.push(group);
512    }
513
514    // Motion blur: every group the finishing split depends on goes first,
515    // so the groups after it can run once after the samples without reading
516    // slots the sampled groups reuse.
517    if let Some(x) = split {
518        let up = upstream(&nodes, x);
519        let order: Vec<usize> = (0..groups.len())
520            .filter(|&g| up[groups[g].root])
521            .chain((0..groups.len()).filter(|&g| !up[groups[g].root]))
522            .collect();
523        let mut new_index = vec![0usize; groups.len()];
524        for (ni, &og) in order.iter().enumerate() {
525            new_index[og] = ni;
526        }
527        let mut old: Vec<Option<Group>> = std::mem::take(&mut groups).into_iter().map(Some).collect();
528        groups = order.iter().map(|&og| old[og].take().unwrap()).collect();
529        for g in &mut groups {
530            for t in &mut g.textures {
531                if let TexSource::Group(s) = t {
532                    *s = new_index[*s];
533                }
534            }
535        }
536        for v in group_of.iter_mut() {
537            if *v != usize::MAX {
538                *v = new_index[*v];
539            }
540        }
541    }
542    let (slot_count, output_slot) = assign_slots(&mut groups);
543    let (mb_split, post) = match split {
544        Some(x) => {
545            let up = upstream(&nodes, x);
546            (Some(group_of[x]), groups.iter().map(|g| !up[g.root]).collect())
547        }
548        None => (None, vec![false; groups.len()]),
549    };
550    // Per group: the nodes its root depends on, and whether those span
551    // exactly the groups before it (so the groups up to it can be sampled
552    // for motion blur and the rest run once).
553    let words = n.div_ceil(64);
554    let mut up_nodes = vec![vec![0u64; words]; n];
555    for i in 0..n {
556        up_nodes[i][i / 64] |= 1 << (i % 64);
557        for k in 0..nodes[i].inputs.len() {
558            let s = nodes[i].inputs[k];
559            let (a, b) = up_nodes.split_at_mut(i);
560            for (w, v) in b[0].iter_mut().zip(&a[s]) {
561                *w |= *v;
562            }
563        }
564    }
565    let group_up: Vec<Vec<u64>> = groups.iter().map(|g| up_nodes[g.root].clone()).collect();
566    let prefix: Vec<bool> = (0..groups.len())
567        .map(|k| (0..groups.len()).all(|j| (j <= k) == bit(&group_up[k], groups[j].root)))
568        .collect();
569    let overlay = overlays(&nodes);
570    let eliminated = doc
571        .nodes
572        .keys()
573        .filter(|id| !index.contains_key(id.as_str()))
574        .cloned()
575        .collect();
576    let mut owner = vec![usize::MAX; nodes.len()];
577    for (gi, g) in groups.iter().enumerate() {
578        for &m in &g.nodes {
579            owner[m] = if owner[m] == usize::MAX || owner[m] == gi {
580                gi
581            } else {
582                SHARED
583            };
584        }
585    }
586    let framed = framed_groups(&nodes, &groups, &group_of);
587    Ok(Plan {
588        signature: signature(doc, chains),
589        framed,
590        nodes,
591        groups,
592        group_of,
593        owner,
594        slot_count,
595        output_slot,
596        eliminated,
597        mb_split,
598        post,
599        group_up,
600        prefix,
601        overlay,
602    })
603}
604
605/// [`Plan::framed`]: which groups' outputs are read only at their own frame
606/// positions. The output is; a group read by a fused group's per-pixel ops
607/// (inputs evaluated where the output pixel is) inherits that group's
608/// answer; any warp, displacement, blur tap, shader, sprite or 3D material
609/// reading it may look outside the frame.
610fn framed_groups(nodes: &[PlanNode], groups: &[Group], group_of: &[usize]) -> Vec<bool> {
611    let n = groups.len();
612    // Per producer group: (consumer group, read at the consumer's own pixel).
613    let mut reads: Vec<Vec<(usize, bool)>> = vec![Vec::new(); n];
614    for (ci, c) in groups.iter().enumerate() {
615        if c.kind != GroupKind::Fused {
616            for t in &c.textures {
617                if let TexSource::Group(p) = t {
618                    reads[*p].push((ci, false));
619                }
620            }
621            continue;
622        }
623        // Whether each node of the group is evaluated at the output pixel.
624        let mut here: HashMap<usize, bool> = HashMap::new();
625        here.insert(c.root, true);
626        for &m in c.nodes.iter().rev() {
627            let at = *here.get(&m).unwrap_or(&false);
628            let pn = &nodes[m];
629            for (port, &src) in pn.inputs.iter().enumerate() {
630                let passes = at
631                    && match pn.def.form {
632                        Form::Map => true,
633                        // The map is read in place; the source displaced.
634                        Form::Displace => port == 1,
635                        _ => false,
636                    };
637                if c.nodes.contains(&src) {
638                    // Evaluated inline: at this node's pixel only if every
639                    // consumer here passes its own.
640                    let e = here.entry(src).or_insert(true);
641                    *e &= passes;
642                } else if group_of[src] < n {
643                    reads[group_of[src]].push((ci, passes));
644                }
645            }
646        }
647    }
648    let mut framed = vec![false; n];
649    for g in (0..n).rev() {
650        framed[g] = if g + 1 == n {
651            true
652        } else {
653            !reads[g].is_empty() && reads[g].iter().all(|&(c, here)| here && framed[c])
654        };
655    }
656    framed
657}
658
659/// [`Plan::owner`] of a node several groups evaluate.
660pub const SHARED: usize = usize::MAX - 1;
661
662impl Plan {
663    /// Whether group `gi` evaluates node `ni`.
664    pub fn in_group(&self, gi: usize, ni: usize) -> bool {
665        match self.owner[ni] {
666            SHARED => self.groups[gi].nodes.contains(&ni),
667            o => o == gi,
668        }
669    }
670}
671
672/// Whether bit `i` is set in a node set.
673pub fn bit(set: &[u64], i: usize) -> bool {
674    set[i / 64] >> (i % 64) & 1 == 1
675}
676
677/// Generators that only ever lie over the picture as a texture (grain, a
678/// light leak): consumed only as the `fg` of blends.
679fn overlays(nodes: &[PlanNode]) -> Vec<bool> {
680    let n = nodes.len();
681    let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); n];
682    for (i, node) in nodes.iter().enumerate() {
683        for &s in &node.inputs {
684            consumers[s].push(i);
685        }
686    }
687    (0..n)
688        .map(|i| {
689            matches!(nodes[i].def.form, Form::Custom | Form::Gen)
690                && nodes[i].inputs.is_empty()
691                && !consumers[i].is_empty()
692                && consumers[i]
693                    .iter()
694                    .all(|&c| nodes[c].def.name == "blend" && nodes[c].inputs.first() == Some(&i))
695        })
696        .collect()
697}
698
699/// Nodes `x` depends on, itself included.
700fn upstream(nodes: &[PlanNode], x: usize) -> Vec<bool> {
701    let mut up = vec![false; nodes.len()];
702    let mut stack = vec![x];
703    while let Some(i) = stack.pop() {
704        if !std::mem::replace(&mut up[i], true) {
705            stack.extend(nodes[i].inputs.iter().copied());
706        }
707    }
708    up
709}
710
711/// The node whose image already holds every moving layer, when everything
712/// after it is a finishing look: color, blur and glow, shaders, still or
713/// procedural overlays. With motion blur those run once on the blurred
714/// image (as on a camera's exposure). None when there is nothing to gain.
715fn finishing_split(nodes: &[PlanNode]) -> Option<usize> {
716    let n = nodes.len();
717    let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); n];
718    for (i, node) in nodes.iter().enumerate() {
719        for &s in &node.inputs {
720            consumers[s].push(i);
721        }
722    }
723    let finishing = |i: usize| {
724        let d = nodes[i].def;
725        let generator = nodes[i].inputs.is_empty();
726        match d.form {
727            Form::Map | Form::Blur => true,
728            // Filters, and still generators.
729            Form::Custom | Form::Gen if !generator || nodes[i].is_static => true,
730            // A changing generator is moving content, unless it only ever
731            // lies over the picture as a texture (grain, a light leak).
732            Form::Custom | Form::Gen => {
733                !consumers[i].is_empty()
734                    && consumers[i]
735                        .iter()
736                        .all(|&c| nodes[c].def.name == "blend" && nodes[c].inputs.first() == Some(&i))
737            }
738            _ => false,
739        }
740    };
741    // Upstream sets, in topological order (inputs come first).
742    let words = n.div_ceil(64);
743    let mut up = vec![vec![0u64; words]; n];
744    for i in 0..n {
745        up[i][i / 64] |= 1 << (i % 64);
746        for k in 0..nodes[i].inputs.len() {
747            let s = nodes[i].inputs[k];
748            let (a, b) = if s < i { up.split_at_mut(i) } else { continue };
749            for (w, v) in b[0].iter_mut().zip(&a[s]) {
750                *w |= *v;
751            }
752        }
753    }
754    let has = |set: &Vec<u64>, j: usize| set[j / 64] >> (j % 64) & 1 == 1;
755    let scene: Vec<usize> = (0..n).filter(|&i| !finishing(i)).collect();
756    let mut best: Option<(usize, u32)> = None;
757    for x in 0..n.saturating_sub(1) {
758        if !scene.iter().all(|&s| has(&up[x], s)) {
759            continue;
760        }
761        if !(0..n).all(|j| has(&up[x], j) || finishing(j)) {
762            continue;
763        }
764        let size: u32 = up[x].iter().map(|w| w.count_ones()).sum();
765        if best.is_none_or(|(_, b)| size < b) {
766            best = Some((x, size));
767        }
768    }
769    best.map(|(x, _)| x)
770}
771
772fn build_fused(
773    nodes: &[PlanNode],
774    materialize: &[bool],
775    group_of: &[usize],
776    root: usize,
777) -> Result<Group, RenderError> {
778    // Build a codegen spec of the inlined subtree. Materialized inputs and
779    // resources become external texture references.
780    let mut spec: Vec<SpecNode> = Vec::new();
781    let mut externals: Vec<TexSource> = Vec::new();
782    let mut member: Vec<usize> = Vec::new();
783    fn ext(externals: &mut Vec<TexSource>, s: TexSource) -> usize {
784        externals.iter().position(|e| *e == s).unwrap_or_else(|| {
785            externals.push(s);
786            externals.len() - 1
787        })
788    }
789    fn walk(
790        nodes: &[PlanNode],
791        materialize: &[bool],
792        group_of: &[usize],
793        i: usize,
794        spec: &mut Vec<SpecNode>,
795        externals: &mut Vec<TexSource>,
796        member: &mut Vec<usize>,
797    ) -> usize {
798        let n = &nodes[i];
799        let children = n
800            .inputs
801            .iter()
802            .map(|&s| {
803                if materialize[s] {
804                    Child::External(ext(externals, TexSource::Group(group_of[s])))
805                } else {
806                    Child::Node(walk(nodes, materialize, group_of, s, spec, externals, member))
807                }
808            })
809            .collect();
810        let resource = ops::uses_resource(n.def).then(|| ext(externals, TexSource::Resource(n.variant.clone())));
811        let code = (n.def.form == Form::Custom).then(|| n.variant.clone());
812        spec.push(SpecNode {
813            def: n.def,
814            children,
815            resource,
816            code,
817            tables: n.tables.as_ref().map_or(0, |t| t.len()),
818            tag: i,
819            gated: n.gated,
820        });
821        member.push(i);
822        spec.len() - 1
823    }
824    let top = walk(
825        nodes,
826        materialize,
827        group_of,
828        root,
829        &mut spec,
830        &mut externals,
831        &mut member,
832    );
833    let k = codegen::generate(&spec, top);
834    if k.bindings.len() > MAX_TEXTURES {
835        return Err(RenderError::TooManyInputs {
836            node: nodes[root].id.clone(),
837            count: k.bindings.len(),
838        });
839    }
840    Ok(Group {
841        kind: GroupKind::Fused,
842        root,
843        // Inputs' staticness is folded in by assign_slots.
844        is_static: member.iter().all(|&m| nodes[m].is_static),
845        nodes: member,
846        textures: k.bindings.iter().map(|&b| externals[b].clone()).collect(),
847        params: k
848            .layout
849            .iter()
850            .map(|s| match s {
851                codegen::Slot::Node(i) => ParamSlot::Node(spec[*i].tag),
852                codegen::Slot::Run(r) => ParamSlot::Run(*r),
853                codegen::Slot::Value(v) => ParamSlot::Value(*v),
854                codegen::Slot::Pad(n) => ParamSlot::Pad(*n),
855                codegen::Slot::Origins => ParamSlot::Origins,
856            })
857            .collect(),
858        param_len: k.param_len,
859        pad_textures: k.pad_textures,
860        runs: k
861            .runs
862            .iter()
863            .map(|r| PlanRun {
864                stride: r.stride,
865                payload: r.payload,
866                layers: r
867                    .layers
868                    .iter()
869                    .map(|l| {
870                        let layer = match l.layer {
871                            codegen::LayerRef::Gen(g) => codegen::LayerRef::Gen(spec[g].tag),
872                            ref t => t.clone(),
873                        };
874                        (l.kind, spec[l.composite].tag, layer)
875                    })
876                    .collect(),
877            })
878            .collect(),
879        output: usize::MAX,
880        key: k.key,
881        body: k.body,
882        raster: None,
883    })
884}
885
886/// Assigns texture slots by lifetime. Static group outputs are read on frames
887/// where their producer does not run, so they keep dedicated slots. Dynamic
888/// outputs share slots once their last reader has run.
889fn assign_slots(groups: &mut [Group]) -> (usize, usize) {
890    let n = groups.len();
891    // A group is only static if every group it reads is static.
892    for g in 0..n {
893        let inputs_static = groups[g].textures.iter().all(|t| match t {
894            TexSource::Group(s) => groups[*s].is_static,
895            TexSource::Resource(_) => true,
896        });
897        groups[g].is_static &= inputs_static;
898    }
899    let mut last_use: Vec<usize> = (0..n).collect();
900    for g in 0..n {
901        for t in &groups[g].textures {
902            if let TexSource::Group(s) = t {
903                last_use[*s] = last_use[*s].max(g);
904            }
905        }
906    }
907    let mut count = 0;
908    let mut free: Vec<usize> = Vec::new();
909    let mut release_at: Vec<Vec<usize>> = vec![Vec::new(); n];
910    let new_slot = |count: &mut usize| {
911        *count += 1;
912        *count - 1
913    };
914    for g in 0..n {
915        // 3D passes keep their own slot: with motion blur a still scene is
916        // rendered once and read by every sample.
917        let slot = if groups[g].is_static || groups[g].kind == GroupKind::Render3D {
918            new_slot(&mut count)
919        } else {
920            free.pop().unwrap_or_else(|| new_slot(&mut count))
921        };
922        groups[g].output = slot;
923        if !groups[g].is_static && groups[g].kind != GroupKind::Render3D && g != n - 1 {
924            release_at[last_use[g]].push(slot);
925        }
926        let released = std::mem::take(&mut release_at[g]);
927        free.extend(released);
928    }
929    (count, groups.last().map(|g| g.output).unwrap_or(0))
930}
931
932/// Reorders a valid topological order to keep few intermediates alive at once:
933/// at each node, the input with the heaviest subtree is evaluated first, so
934/// light branches are produced just before they are consumed (Sethi-Ullman).
935fn schedule(doc: &Document, topo: &[NodeId]) -> Vec<NodeId> {
936    let mut weight: HashMap<&str, usize> = HashMap::new();
937    for id in topo {
938        let w = 1 + doc.nodes[id].inputs.values().map(|s| weight[s.as_str()]).sum::<usize>();
939        weight.insert(id.as_str(), w);
940    }
941    let mut out = Vec::with_capacity(topo.len());
942    let mut done: HashMap<&str, ()> = HashMap::new();
943    let mut stack: Vec<(&str, bool)> = vec![(doc.output.as_str(), false)];
944    while let Some((id, expanded)) = stack.pop() {
945        if done.contains_key(id) {
946            continue;
947        }
948        if expanded {
949            done.insert(id, ());
950            out.push(id.to_string());
951            continue;
952        }
953        stack.push((id, true));
954        let mut inputs: Vec<&str> = doc.nodes[id].inputs.values().map(String::as_str).collect();
955        // Stack is LIFO: push lightest first so the heaviest is expanded first.
956        inputs.sort_by_key(|s| weight[s]);
957        for s in inputs {
958            if !done.contains_key(s) {
959                stack.push((s, false));
960            }
961        }
962    }
963    out
964}
965
966impl Plan {
967    /// Human/agent readable description of the plan.
968    pub fn describe(&self) -> String {
969        let mut s = format!(
970            "plan: {} nodes in {} kernels, {} texture slots, output slot {}\n",
971            self.nodes.len(),
972            self.groups.len(),
973            self.slot_count,
974            self.output_slot
975        );
976        for (gi, g) in self.groups.iter().enumerate() {
977            let ids: Vec<&str> = g.nodes.iter().map(|&i| self.nodes[i].id.as_str()).collect();
978            let tex: Vec<String> = g
979                .textures
980                .iter()
981                .map(|t| match t {
982                    TexSource::Group(x) => format!("g{x}"),
983                    TexSource::Resource(r) => format!("res:{r}"),
984                })
985                .collect();
986            s += &format!(
987                "  g{gi:<3} {:<6} {} -> slot {}{}  [{}]\n",
988                match g.kind {
989                    GroupKind::Fused => "fused",
990                    GroupKind::Blur => "blur",
991                    GroupKind::Raster => "raster",
992                    GroupKind::Render3D => "3d",
993                    GroupKind::Particles => "particles",
994                    GroupKind::Sim => "sim",
995                },
996                if tex.is_empty() {
997                    String::new()
998                } else {
999                    format!("reads {} ", tex.join(","))
1000                },
1001                g.output,
1002                if g.is_static { " static/cached" } else { "" },
1003                ids.join(" "),
1004            );
1005        }
1006        if let Some(sg) = self.mb_split {
1007            let post: Vec<String> = (0..self.groups.len())
1008                .filter(|&g| self.post[g])
1009                .map(|g| format!("g{g}"))
1010                .collect();
1011            s += &format!(
1012                "  motion blur: samples up to g{sg}; once per frame on the blurred image: {}\n",
1013                post.join(" ")
1014            );
1015        }
1016        if !self.eliminated.is_empty() {
1017            s += &format!("  eliminated (unreachable): {}\n", self.eliminated.join(", "));
1018        }
1019        s
1020    }
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025    use super::*;
1026
1027    fn layered(n: usize, animated: bool) -> Document {
1028        let anim = r#"{"keys":[{"t":0,"v":[0,0]},{"t":1,"v":[9,9]}]}"#;
1029        let center = if animated { anim } else { "[4,4]" };
1030        let mut nodes = format!(r#""s0": {{"op":"shape","params":{{"center":{center}}}}}"#);
1031        for i in 1..n {
1032            nodes += &format!(
1033                r#","s{i}": {{"op":"shape","params":{{"center":{center}}}}}
1034                ,"o{i}": {{"op":"over","inputs":{{"fg":"s{i}","bg":"{}"}}}}"#,
1035                if i == 1 {
1036                    "s0".to_string()
1037                } else {
1038                    format!("o{}", i - 1)
1039                }
1040            );
1041        }
1042        Document::from_json(&format!(
1043            r#"{{"version":1,"format":{{"width":8,"height":8,"fps":30,"duration":1}},"output":"o{}","nodes":{{{nodes}}}}}"#,
1044            n - 1
1045        ))
1046        .unwrap()
1047    }
1048
1049    #[test]
1050    fn layer_stack_fuses_into_one_kernel() {
1051        let plan = compile(&layered(20, true), None).unwrap();
1052        assert_eq!(plan.nodes.len(), 39);
1053        assert_eq!(plan.groups.len(), 1, "{}", plan.describe());
1054        assert_eq!(plan.slot_count, 1);
1055    }
1056
1057    #[test]
1058    fn shared_nodes_materialize_and_blur_is_a_barrier() {
1059        let doc = Document::from_json(
1060            r#"{"version":1,"format":{"width":8,"height":8,"fps":30,"duration":1},"output":"out","nodes":{
1061            "s": {"op":"shape"},
1062            "b": {"op":"blur","inputs":{"source":"s"}},
1063            "m": {"op":"mask","inputs":{"source":"b","matte":"s"}},
1064            "out": {"op":"transform","inputs":{"source":"m"}}}}"#,
1065        )
1066        .unwrap();
1067        let plan = compile(&doc, None).unwrap();
1068        // s (2 consumers), b (blur), then m + out fused.
1069        assert_eq!(plan.groups.len(), 3, "{}", plan.describe());
1070        assert_eq!(plan.groups[1].kind, GroupKind::Blur);
1071        assert_eq!(plan.groups[2].nodes.len(), 2);
1072        for g in &plan.groups {
1073            for t in &g.textures {
1074                if let TexSource::Group(s) = t {
1075                    assert_ne!(plan.groups[*s].output, g.output);
1076                }
1077            }
1078        }
1079    }
1080
1081    #[test]
1082    fn param_values_do_not_change_signature_but_animation_does() {
1083        let mut a = layered(3, false);
1084        let s0 = signature(&a, None);
1085        a.nodes
1086            .get_mut("s1")
1087            .unwrap()
1088            .params
1089            .insert("size".into(), ultrafast_graph::Param::Number(3.0));
1090        assert_eq!(signature(&a, None), s0);
1091        let b = layered(3, true);
1092        assert_ne!(signature(&b, None), s0);
1093    }
1094}