Skip to main content

ultrafast_render/
codegen.rs

1//! Slang code generation for fused kernels.
2//!
3//! A kernel is generated from a small expression tree (`SpecNode`s). Each
4//! node calls its op function from `shaders/lib.slang`; warps change the
5//! context their input is evaluated in, so a shape under a transform is
6//! evaluated analytically at the transformed position instead of being
7//! rasterized and resampled.
8//!
9//! Param offsets are baked into the code and depend only on structure, so a
10//! param edit never changes the code and never triggers a compile.
11
12use crate::ops::{Form, OpDef};
13
14/// Name every generated kernel entry point is emitted with. The compiler
15/// renames it to a unique symbol per kernel key.
16pub const ENTRY: &str = "ENTRY_POINT";
17/// Placeholder for a per-kernel prefix on module-level names, so several
18/// kernels can share one compile unit.
19const NSID: &str = "NSID";
20
21/// Op library prepended to every generated module.
22pub const LIBRARY: &str = include_str!("../shaders/lib.slang");
23
24#[derive(Debug, Clone)]
25pub enum Child {
26    /// Another node of the same spec, evaluated inline.
27    Node(usize),
28    /// External texture, identified by the caller's external index.
29    External(usize),
30}
31
32#[derive(Debug, Clone)]
33pub struct SpecNode {
34    pub def: &'static OpDef,
35    /// One per connected port, in port order.
36    pub children: Vec<Child>,
37    /// External index of the resource texture (GenResource ops).
38    pub resource: Option<usize>,
39    /// Agent-written shader code (Custom ops).
40    pub code: Option<String>,
41    /// Floats of the code's constant tables, after the rest of its param
42    /// block (see [`crate::tables`]).
43    pub tables: usize,
44    /// Caller's identifier for this node, carried through.
45    pub tag: usize,
46    /// Has a visibility window: one extra param float (after the op block)
47    /// says whether it is active this frame; inactive nodes are skipped.
48    pub gated: bool,
49}
50
51#[derive(Debug, Clone)]
52pub struct Generated {
53    /// Module-level declarations plus the entry point, without the library.
54    pub body: String,
55    /// External indices bound to T0, T1, ... in order.
56    pub bindings: Vec<usize>,
57    /// What fills P[4..], in order.
58    pub layout: Vec<Slot>,
59    /// The runs of layers `Slot::Run` refers to.
60    pub runs: Vec<RunLayout>,
61    /// Total param floats: 4-float header, node blocks, one 2-float origin
62    /// per texture binding, then the blocks of repeated layers.
63    pub param_len: usize,
64    /// The kernel may read any of T0..T15 (a run of texture layers picks
65    /// its texture per layer): every binding needs a texture.
66    pub pad_textures: bool,
67    /// Content hash of `body`.
68    pub key: String,
69}
70
71/// What fills a kernel's params after the 4-float header, in order.
72#[derive(Debug, Clone, PartialEq)]
73pub enum Slot {
74    /// A spec node's param block: its op params, its window flag when it
75    /// has one, a 4-float guard rect when it is guarded.
76    Node(usize),
77    /// Where run `r`'s layers start and how many there are this frame (two
78    /// floats the packer writes; the layers' blocks follow everything else).
79    Run(usize),
80    /// A literal float.
81    Value(f32),
82    /// Zeros (padding a repeated layer to its stride).
83    Pad(usize),
84    /// Two floats per texture binding: where each placed texture sits.
85    Origins,
86}
87
88/// Chains at least this long of one composite over one kind of layer are
89/// emitted as a loop.
90const MIN_RUN: usize = 4;
91
92/// A run of layers composited one over the other, emitted as a loop over
93/// param blocks, so the kernel is the same however many layers there are.
94struct Run {
95    /// Composite nodes in loop order: the bottom one first.
96    links: Vec<usize>,
97    /// What the bottom composite lays its layer over.
98    base: Child,
99}
100
101/// A run of layers as the packer writes it each frame: the blocks of the
102/// layers showing then (`[kind][composite params][guard rect][layer]`,
103/// `stride` floats each), after everything else in the params.
104#[derive(Debug, Clone)]
105pub struct RunLayout {
106    pub stride: usize,
107    /// Floats in the layer part of a block (a generator's params, or a
108    /// texture's binding), padded to this.
109    pub payload: usize,
110    pub layers: Vec<RunLayer>,
111}
112
113#[derive(Debug, Clone)]
114pub struct RunLayer {
115    /// 0: a texture; 1..: a generator kind.
116    pub kind: usize,
117    /// The composite (spec index).
118    pub composite: usize,
119    pub layer: LayerRef,
120}
121
122#[derive(Debug, Clone, PartialEq)]
123pub enum LayerRef {
124    /// Texture binding.
125    Texture(usize),
126    /// Generator (spec index).
127    Gen(usize),
128}
129
130struct Emitter<'a> {
131    spec: &'a [SpecNode],
132    decls: String,
133    code: String,
134    vars: usize,
135    bindings: Vec<usize>,
136    layout: Vec<Slot>,
137    /// Runs, their texture layers holding external indices until the end,
138    /// when they bind after every other texture.
139    runs: Vec<RunLayout>,
140    offsets: Vec<Option<usize>>,
141    next_offset: usize,
142    /// Values already computed in the current scope, by (node, context,
143    /// identity): a subtree reached twice (a gated layer's passthrough, a
144    /// guarded composite's background) is emitted once.
145    memo: std::collections::HashMap<(usize, String, bool), String>,
146    /// Custom shader nodes whose namespace is already declared.
147    declared: std::collections::HashSet<usize>,
148}
149
150impl Emitter<'_> {
151    fn var(&mut self) -> String {
152        self.vars += 1;
153        format!("v{}", self.vars)
154    }
155
156    fn texture(&mut self, ext: usize) -> String {
157        let i = self.bindings.iter().position(|&b| b == ext).unwrap_or_else(|| {
158            self.bindings.push(ext);
159            self.bindings.len() - 1
160        });
161        format!("T{i}")
162    }
163
164    /// Placeholder for the param offset of a texture's origin; resolved once
165    /// all node params are laid out (origins follow them).
166    fn origin(&self, texture: &str) -> String {
167        format!("ORIGIN_{texture}_")
168    }
169
170    fn offset(&mut self, n: usize) -> usize {
171        if let Some(o) = self.offsets[n] {
172            return o;
173        }
174        let o = self.next_offset;
175        self.offsets[n] = Some(o);
176        self.layout.push(Slot::Node(n));
177        self.next_offset += self.block(n) + self.spec[n].tables;
178        o
179    }
180
181    /// Floats of node `n`'s param block before its tables: op params, window
182    /// flag, guard rect.
183    fn block(&self, n: usize) -> usize {
184        self.spec[n].def.params
185            + self.spec[n].gated as usize
186            + if crate::ops::guarded(self.spec[n].def) { 4 } else { 0 }
187    }
188
189    fn child(&mut self, c: &Child, ctx: &str, identity: bool) -> String {
190        match c {
191            Child::Node(n) => self.node(*n, ctx, identity),
192            Child::External(e) => {
193                let t = self.texture(*e);
194                let v = self.var();
195                let o = self.origin(&t);
196                if identity {
197                    self.code += &format!("    float4 {v} = load_t({t}, gid.xy, {o});\n");
198                } else {
199                    self.code += &format!("    float4 {v} = sample_t({t}, {ctx}.pos, {o});\n");
200                }
201                v
202            }
203        }
204    }
205
206    /// Emits node `n` evaluated in context `ctx`; returns its value variable.
207    /// `identity` means ctx is the unwarped pixel center, so textures can be
208    /// loaded without resampling. Gated nodes (and everything inlined under
209    /// them) only run while active.
210    fn node(&mut self, n: usize, ctx: &str, identity: bool) -> String {
211        let key = (n, ctx.to_string(), identity);
212        if let Some(v) = self.memo.get(&key) {
213            return v.clone();
214        }
215        if let Some(run) = self.run_at(n) {
216            let v = self.emit_run(run, ctx, identity);
217            self.memo.insert(key, v.clone());
218            return v;
219        }
220        let v = if !self.spec[n].gated {
221            self.node_inner(n, ctx, identity)
222        } else {
223            // Inactive: pass the destination/source input through unchanged.
224            // It is computed before the branch (in scope for both sides), so
225            // the active side reuses it instead of emitting it again.
226            let pass = crate::ops::passthrough(self.spec[n].def, self.spec[n].children.len());
227            let pv = pass.map(|i| {
228                let child = self.spec[n].children[i].clone();
229                self.child(&child, ctx, identity)
230            });
231            let active = self.offset(n) + self.spec[n].def.params;
232            let v = self.var();
233            self.code += &format!(
234                "    float4 {v} = {};\n    if (P[{active}] > 0.5) {{\n",
235                pv.as_deref().unwrap_or("float4(0.0)")
236            );
237            let saved = self.memo.clone();
238            let inner = self.node_inner(n, ctx, identity);
239            self.memo = saved;
240            self.code += &format!("    {v} = {inner};\n    }}\n");
241            v
242        };
243        self.memo.insert(key, v.clone());
244        v
245    }
246
247    /// The run of layers whose top composite is `n`: guarded composites of
248    /// one op with windows, chained through their backgrounds, each laying
249    /// either a texture or a plain generator over the one below. Windowed
250    /// layers (captions, beats) are what differs between chapters and what
251    /// is mostly off at any moment, so looping over the ones showing costs
252    /// less than unrolling them all; layers that are always on stay
253    /// unrolled, where constant offsets are cheapest.
254    fn run_at(&self, n: usize) -> Option<Run> {
255        let top = &self.spec[n];
256        if top.def.form != Form::Map || !crate::ops::guarded(top.def) {
257            return None;
258        }
259        let layer_ok = |c: &Child| match c {
260            Child::External(_) => true,
261            Child::Node(g) => {
262                let g = &self.spec[*g];
263                g.def.form == Form::Gen && g.children.is_empty() && g.resource.is_none() && g.code.is_none()
264            }
265        };
266        let mut links = Vec::new();
267        let mut cur = n;
268        let base = loop {
269            let s = &self.spec[cur];
270            if s.def.name != top.def.name || !s.gated || s.children.len() != 2 || !layer_ok(&s.children[0]) {
271                break Child::Node(cur);
272            }
273            links.push(cur);
274            match &s.children[1] {
275                Child::Node(b) => cur = *b,
276                c @ Child::External(_) => break c.clone(),
277            }
278        };
279        if links.len() < MIN_RUN {
280            return None;
281        }
282        links.reverse();
283        Some(Run { links, base })
284    }
285
286    /// A run as a loop over the blocks of the layers showing this frame,
287    /// which the packer writes after everything else in the params:
288    /// `[kind][composite params][guard rect][layer]`, kind 0 a texture (its
289    /// binding in the layer part), kind 1.. a generator (its params there).
290    /// Layers out of their windows or empty are left out, so the loop runs
291    /// only over what shows.
292    fn emit_run(&mut self, run: Run, ctx: &str, identity: bool) -> String {
293        let bgv = self.child(&run.base, ctx, identity);
294        let cdef = self.spec[run.links[0]].def;
295        // Generator kinds in a fixed order, so runs of the same kinds share
296        // a kernel whatever their length or order.
297        let mut kinds: Vec<&'static OpDef> = Vec::new();
298        let mut textures = false;
299        for &l in &run.links {
300            match &self.spec[l].children[0] {
301                Child::External(_) => textures = true,
302                Child::Node(g) => {
303                    // By function: one op can have several (gradient kinds).
304                    let d = self.spec[*g].def;
305                    if !kinds.iter().any(|k| k.func == d.func) {
306                        kinds.push(d);
307                    }
308                }
309            }
310        }
311        kinds.sort_by_key(|d| d.func);
312        // A texture's layer part: its binding, width and height.
313        let payload = kinds
314            .iter()
315            .map(|d| d.params)
316            .chain(textures.then_some(3))
317            .max()
318            .unwrap_or(1)
319            .max(1);
320        let stride = 1 + cdef.params + 4 + payload;
321        let layers = run
322            .links
323            .iter()
324            .map(|&l| match &self.spec[l].children[0] {
325                Child::External(e) => RunLayer {
326                    kind: 0,
327                    composite: l,
328                    layer: LayerRef::Texture(*e),
329                },
330                Child::Node(g) => RunLayer {
331                    kind: 1 + kinds
332                        .iter()
333                        .position(|d| d.func == self.spec[*g].def.func)
334                        .expect("kind collected above"),
335                    composite: l,
336                    layer: LayerRef::Gen(*g),
337                },
338            })
339            .collect();
340        // In the main block: where the layers start and how many show.
341        let slot = self.next_offset;
342        self.next_offset += 2;
343        self.layout.push(Slot::Run(self.runs.len()));
344        self.runs.push(RunLayout {
345            stride,
346            payload,
347            layers,
348        });
349        let v = self.var();
350        let id = self.vars;
351        let (i, o, q, k, f) = (
352            format!("i{id}"),
353            format!("o{id}"),
354            format!("q{id}"),
355            format!("k{id}"),
356            format!("f{id}"),
357        );
358        let mut code = format!(
359            "    float4 {v} = {bgv};\n    for (uint {i} = 0; {i} < uint(P[{count}]); {i}++) {{\n        \
360             uint {o} = uint(P[{slot}]) + {i} * {stride};\n        \
361             if (!in_rect({ctx}.pos, pf4({o} + {guard}))) continue;\n        \
362             uint {k} = uint(P[{o}]);\n        uint {q} = {o} + {layer};\n        float4 {f} = float4(0.0);\n",
363            count = slot + 1,
364            guard = 1 + cdef.params,
365            layer = 1 + cdef.params + 4
366        );
367        // One reader per kind; with a single kind, no dispatch at all.
368        let mut reads: Vec<(usize, String)> = Vec::new();
369        if textures {
370            // A layer's texture: texel size ORIGINS[3b + 2] frame px, size
371            // P[q+1..q+3] texels. Loaded texel for texel when its texels are
372            // the output's, else sampled at the frame position.
373            let sample = self.texture_picker(false);
374            let sampled = format!(
375                "{f} = {sample}(b, ({ctx}.pos - pf2(ORIGINS_BASE_ + 3 * b)) / (pf2({q} + 1) * P[ORIGINS_BASE_ + 3 * b + 2]));"
376            );
377            reads.push((
378                0,
379                if identity {
380                    let load = self.texture_picker(true);
381                    format!(
382                        "uint b = uint(P[{q}]); if (P[ORIGINS_BASE_ + 3 * b + 2] == P[1]) {{ \
383                         int2 p = int2(gid.xy) - int2(round(pf2(ORIGINS_BASE_ + 3 * b) / P[1])); \
384                         if (p.x >= 0 && p.y >= 0 && p.x < int(P[{q} + 1]) && p.y < int(P[{q} + 2])) {f} = {load}(b, p); }} \
385                         else {{ {sampled} }}"
386                    )
387                } else {
388                    format!("uint b = uint(P[{q}]); {sampled}")
389                },
390            ));
391        }
392        for (x, d) in kinds.iter().enumerate() {
393            reads.push((x + 1, format!("{f} = g_{}({ctx}, {q});", d.func)));
394        }
395        if reads.len() == 1 {
396            code += &format!("        {}\n", reads[0].1);
397        } else {
398            for (x, (kind, read)) in reads.iter().enumerate() {
399                let branch = if x == 0 { "if" } else { "else if" };
400                code += &format!("        {branch} ({k} == {kind}) {{ {read} }}\n");
401            }
402        }
403        code += &format!("        {v} = f_{}({ctx}, {f}, {v}, {o} + 1);\n    }}\n", cdef.func);
404        self.code += &code;
405        v
406    }
407
408    /// A function reading texture binding `b` (any of T0..T15), declared
409    /// once per kernel: a texel load at a texture position, or a sample at
410    /// texture coordinates (the caller places and bounds the texture).
411    fn texture_picker(&mut self, identity: bool) -> String {
412        let name = format!("{NSID}_layer_{}", if identity { "load" } else { "sample" });
413        if !self.decls.contains(&format!("float4 {name}(")) {
414            let mut cases = String::new();
415            for t in 0..16 {
416                let read = if identity {
417                    format!("T{t}.Load(int3(p, 0))")
418                } else {
419                    format!("T{t}.SampleLevel(S, uv, 0)")
420                };
421                cases += &format!("    case {t}: return {read};\n");
422            }
423            let arg = if identity { "int2 p" } else { "float2 uv" };
424            self.decls += &format!(
425                "float4 {name}(uint b, {arg}) {{\n    switch (b) {{\n{cases}    default: return float4(0.0);\n    }}\n}}\n"
426            );
427        }
428        name
429    }
430
431    fn node_inner(&mut self, n: usize, ctx: &str, identity: bool) -> String {
432        let s = &self.spec[n];
433        let def = s.def;
434        match def.form {
435            Form::Gen => {
436                let o = self.offset(n);
437                let v = self.var();
438                self.code += &format!("    float4 {v} = g_{}({ctx}, {o});\n", def.func);
439                v
440            }
441            Form::GenResource => {
442                let o = self.offset(n);
443                let t = self.texture(s.resource.expect("resource op without resource"));
444                let v = self.var();
445                self.code += &format!("    float4 {v} = g_{}({ctx}, {o}, {t});\n", def.func);
446                v
447            }
448            Form::Map if crate::ops::guarded(def) => {
449                // fg is only evaluated inside its bounds; elsewhere the
450                // result is bg untouched (for over and normal blends with
451                // transparent fg).
452                let (fg, bg) = (s.children[0].clone(), s.children[1].clone());
453                let bgv = self.child(&bg, ctx, identity);
454                let o = self.offset(n);
455                let guard = o + def.params + s.gated as usize;
456                let v = self.var();
457                self.code += &format!("    float4 {v} = {bgv};\n    if (in_rect({ctx}.pos, pf4({guard}))) {{\n");
458                let saved = self.memo.clone();
459                let fgv = self.child(&fg, ctx, identity);
460                self.memo = saved;
461                self.code += &format!("    {v} = f_{}({ctx}, {fgv}, {bgv}, {o});\n    }}\n", def.func);
462                v
463            }
464            Form::Map => {
465                let children = s.children.clone();
466                let args: Vec<String> = children.iter().map(|c| self.child(c, ctx, identity)).collect();
467                let o = self.offset(n);
468                // Ops with a resource (LUTs) get its texture last.
469                let res = match s.resource {
470                    Some(r) => format!(", {}", self.texture(r)),
471                    None => String::new(),
472                };
473                let v = self.var();
474                self.code += &format!(
475                    "    float4 {v} = f_{}({ctx}, {}, {o}{res});\n",
476                    def.func,
477                    args.join(", ")
478                );
479                v
480            }
481            Form::Warp => {
482                let o = self.offset(n);
483                let c = format!("c{}", self.vars + 1);
484                self.vars += 1;
485                self.code += &format!("    Ctx {c} = w_{}({ctx}, {o});\n", def.func);
486                let child = s.children[0].clone();
487                self.child(&child, &c, false)
488            }
489            Form::Displace => {
490                let (source, map) = (s.children[0].clone(), s.children[1].clone());
491                let m = self.child(&map, ctx, identity);
492                let o = self.offset(n);
493                let c = format!("c{}", self.vars + 1);
494                self.vars += 1;
495                self.code += &format!("    Ctx {c} = w_displace({ctx}, {m}, {o});\n");
496                self.child(&source, &c, false)
497            }
498            Form::Custom => {
499                let o = self.offset(n);
500                let ns = format!("{NSID}_cs{n}");
501                let mut cases = String::new();
502                for (port, c) in s.children.clone().iter().enumerate() {
503                    let Child::External(e) = c else {
504                        unreachable!("custom shader inputs are always materialized")
505                    };
506                    let t = self.texture(*e);
507                    let o = self.origin(&t);
508                    cases += &format!("        case {port}: return sample_t({t}, pos, {o});\n");
509                }
510                let code = s.code.clone().unwrap_or_default();
511                let tables = if s.tables > 0 {
512                    crate::tables::declare_base(o + self.block(n))
513                } else {
514                    String::new()
515                };
516                if self.declared.insert(n) {
517                    self.decls += &format!(
518                        "namespace {ns} {{\n\
519                     static const uint PO = {o};\n\
520                     {tables}\
521                     float param(int i) {{ return P[PO + uint(i)]; }}\n\
522                     float time() {{ return P[PO + 16]; }}\n\
523                     float2 size() {{ return resolution(); }}\n\
524                     float4 input(int i, float2 pos) {{\n    switch (i) {{\n{cases}        default: return float4(0.0);\n    }}\n}}\n\
525                     float4 from_srgb(float4 c) {{ return float4(srgb_to_linear(saturate(c.rgb)) * c.a, c.a); }}\n\
526                     #line 1 \"shader\"\n\
527                     {code}\n\
528                     }}\n"
529                    );
530                }
531                let v = self.var();
532                self.code += &format!("    float4 {v} = {ns}::shade({ctx}.pos, {ctx}.px);\n");
533                v
534            }
535            Form::Blur | Form::Raster | Form::Object | Form::Render3D | Form::Particles | Form::Sim => {
536                unreachable!("barriers and scene objects are never inlined")
537            }
538        }
539    }
540}
541
542/// Generates the kernel for `spec`, rooted at node `root`.
543pub fn generate(spec: &[SpecNode], root: usize) -> Generated {
544    let mut e = Emitter {
545        spec,
546        decls: String::new(),
547        code: String::new(),
548        vars: 0,
549        bindings: Vec::new(),
550        layout: Vec::new(),
551        runs: Vec::new(),
552        offsets: vec![None; spec.len()],
553        next_offset: 4,
554        memo: std::collections::HashMap::new(),
555        declared: std::collections::HashSet::new(),
556    };
557    let v = e.node(root, "c0", true);
558    // Runs' textures bind after every other texture, so the others keep
559    // their bindings however long the runs are.
560    let mut pad_textures = false;
561    let mut runs = std::mem::take(&mut e.runs);
562    for run in &mut runs {
563        for layer in &mut run.layers {
564            if let LayerRef::Texture(ext) = layer.layer {
565                pad_textures = true;
566                let b = e.bindings.iter().position(|&x| x == ext).unwrap_or_else(|| {
567                    e.bindings.push(ext);
568                    e.bindings.len() - 1
569                });
570                layer.layer = LayerRef::Texture(b);
571            }
572        }
573    }
574    // Texture origins and texel sizes (3 floats each) follow the node params.
575    let origins = e.next_offset;
576    for k in 0..e.bindings.len() {
577        let off = origins + 3 * k;
578        let ph = format!("ORIGIN_T{k}_");
579        e.code = e.code.replace(&ph, &off.to_string());
580        e.decls = e.decls.replace(&ph, &off.to_string());
581    }
582    e.code = e.code.replace("ORIGINS_BASE_", &origins.to_string());
583    e.layout.push(Slot::Origins);
584    // Then, at most, every layer of every run.
585    let param_len = origins + 3 * e.bindings.len() + runs.iter().map(|r| r.stride * r.layers.len()).sum::<usize>();
586    let body = format!(
587        "{}\n[shader(\"compute\")]\n[numthreads(16, 16, 1)]\nvoid {ENTRY}(uint3 gid: SV_DispatchThreadID) {{\n    \
588         if (outside_frame(gid.xy)) return;\n    Ctx c0 = root_ctx(gid.xy);\n{}    OUT.Store(gid.xy, {v});\n}}\n",
589        e.decls, e.code
590    );
591    let key = blake3::hash(body.as_bytes()).to_hex()[..24].to_string();
592    Generated {
593        body,
594        bindings: e.bindings,
595        layout: e.layout,
596        runs,
597        param_len,
598        pad_textures,
599        key,
600    }
601}
602
603/// Generates the standalone single-op kernel for `def` (tier 0): all inputs
604/// are textures. Returns None for ops without one (blur, custom shaders).
605pub fn single_op(def: &'static OpDef) -> Option<Generated> {
606    if matches!(
607        def.form,
608        Form::Blur | Form::Custom | Form::Raster | Form::Object | Form::Render3D | Form::Particles | Form::Sim
609    ) {
610        return None;
611    }
612    let spec = [SpecNode {
613        def,
614        children: (0..def.ports.len()).map(Child::External).collect(),
615        resource: crate::ops::uses_resource(def).then_some(def.ports.len()),
616        code: None,
617        tables: 0,
618        tag: 0,
619        gated: false,
620    }];
621    Some(generate(&spec, 0))
622}
623
624/// Renames the generated entry point to a unique symbol.
625pub fn entry_name(key: &str) -> String {
626    format!("k_{key}")
627}
628
629/// Assembles a compile unit: the op library plus each kernel body with its
630/// entry point and module-level names made unique.
631pub fn module(kernels: &[(&str, &str)]) -> String {
632    let mut s = String::with_capacity(LIBRARY.len() + kernels.iter().map(|k| k.1.len() + 64).sum::<usize>());
633    s += LIBRARY;
634    // Groups with the same structure share one kernel: emit each key once.
635    let mut seen = std::collections::HashSet::new();
636    for (key, body) in kernels {
637        if !seen.insert(*key) {
638            continue;
639        }
640        let name = entry_name(key);
641        s += "\n";
642        s += &body.replace(ENTRY, &name).replace(NSID, &format!("k{key}"));
643    }
644    s
645}
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650    use crate::ops::OPS;
651
652    fn def(func: &str) -> &'static OpDef {
653        OPS.iter().find(|d| d.func == func).unwrap()
654    }
655
656    #[test]
657    fn warp_over_generator_is_analytic() {
658        let spec = vec![
659            SpecNode {
660                def: def("shape"),
661                children: vec![],
662                resource: None,
663                code: None,
664                tables: 0,
665                tag: 0,
666                gated: false,
667            },
668            SpecNode {
669                def: def("transform"),
670                children: vec![Child::Node(0)],
671                resource: None,
672                code: None,
673                tables: 0,
674                tag: 1,
675                gated: false,
676            },
677            SpecNode {
678                def: def("over"),
679                children: vec![Child::Node(1), Child::External(7)],
680                resource: None,
681                code: None,
682                tables: 0,
683                tag: 2,
684                gated: false,
685            },
686        ];
687        let g = generate(&spec, 2);
688        assert!(g.body.contains("w_transform(c0, 10)"), "{}", g.body);
689        // The fg subtree only runs inside its bounds.
690        assert!(g.body.contains("if (in_rect(c0.pos, pf4(6)))"), "{}", g.body);
691        assert!(g.body.contains("g_shape(c"), "{}", g.body);
692        // Origin of T0 follows the 26 node param floats (over carries a 4-float guard).
693        assert!(g.body.contains("load_t(T0, gid.xy, 30)"), "{}", g.body);
694        assert_eq!(g.bindings, vec![7]);
695        // transform(7) + shape(13) + over(2) after the header, plus one
696        // origin and texel size.
697        assert_eq!(g.param_len, 4 + 7 + 13 + 2 + 4 + 3);
698    }
699
700    fn chain(n: usize, texture_every: usize) -> Vec<SpecNode> {
701        // Layers over External(0): shapes, with a texture every few layers.
702        let mut spec = Vec::new();
703        let mut below = Child::External(0);
704        for i in 0..n {
705            let layer = if texture_every > 0 && i % texture_every == 1 {
706                Child::External(10 + i)
707            } else {
708                spec.push(SpecNode {
709                    def: def("shape"),
710                    children: vec![],
711                    resource: None,
712                    code: None,
713                    tables: 0,
714                    tag: spec.len(),
715                    gated: false,
716                });
717                Child::Node(spec.len() - 1)
718            };
719            spec.push(SpecNode {
720                def: def("over"),
721                children: vec![layer, below],
722                resource: None,
723                code: None,
724                tables: 0,
725                tag: spec.len(),
726                gated: true,
727            });
728            below = Child::Node(spec.len() - 1);
729        }
730        spec
731    }
732
733    #[test]
734    fn repeated_layers_loop_and_share_a_kernel_at_any_count() {
735        let a = chain(6, 0);
736        let b = chain(9, 0);
737        let (ga, gb) = (generate(&a, a.len() - 1), generate(&b, b.len() - 1));
738        assert!(ga.body.contains("for (uint"), "{}", ga.body);
739        assert_eq!(ga.key, gb.key);
740        assert_ne!(ga.param_len, gb.param_len);
741        assert!(!ga.pad_textures);
742        // Textures among the layers loop too, bound after the base.
743        let c = chain(8, 3);
744        let d = chain(11, 3);
745        let (gc, gd) = (generate(&c, c.len() - 1), generate(&d, d.len() - 1));
746        assert_eq!(gc.key, gd.key);
747        assert!(gc.pad_textures);
748        assert_eq!(gc.bindings[0], 0);
749        // Short chains stay unrolled.
750        let e = chain(3, 0);
751        assert!(!generate(&e, e.len() - 1).body.contains("for (uint"));
752    }
753
754    #[test]
755    fn same_structure_same_key() {
756        let a = single_op(def("over")).unwrap();
757        let b = single_op(def("over")).unwrap();
758        assert_eq!(a.key, b.key);
759        assert_ne!(a.key, single_op(def("mask")).unwrap().key);
760    }
761}
762
763/// Param layout of a `feedback` step kernel (after the 4-float header,
764/// whose [1] is the state texel size in frame px).
765pub mod feedback_params {
766    /// u0..u15.
767    pub const U: usize = 4;
768    pub const TIME: usize = 20;
769    pub const DT: usize = 21;
770    /// Steps taken since the simulation started (0 on the first).
771    pub const STEP: usize = 22;
772    /// Origins of in0..in3 (2 floats each).
773    pub const ORIGINS: usize = 24;
774    /// Texel sizes of in0..in3 (frame px).
775    pub const SCALES: usize = 32;
776    pub const LEN: usize = 36;
777}
778
779/// Kernel for one step of a `feedback` node: `update(pos, px)` from the
780/// agent's code, with the previous state (T0) and up to four placed inputs
781/// (T1..T4), and the code's constant tables after the params when it has
782/// them. Returns (key, body).
783pub fn feedback(code: &str, tables: bool) -> (String, String) {
784    use feedback_params::*;
785    let mut cases = String::new();
786    for i in 0..4 {
787        cases += &format!(
788            "        case {i}: return sample_region(T{}, pos, pf2({}), P[{}]);\n",
789            i + 1,
790            ORIGINS + 2 * i,
791            SCALES + i
792        );
793    }
794    let tables = if tables {
795        crate::tables::declare_base(LEN)
796    } else {
797        String::new()
798    };
799    let body = format!(
800        "namespace {NSID}_fb {{\n\
801         {tables}\
802         float param(int i) {{ return P[{U} + uint(i)]; }}\n\
803         float time() {{ return P[{TIME}]; }}\n\
804         float dt() {{ return P[{DT}]; }}\n\
805         int step_index() {{ return int(P[{STEP}] + 0.5); }}\n\
806         float2 size() {{ return resolution(); }}\n\
807         float4 prev(float2 pos) {{ return sample_region(T0, pos, float2(0.0), P[1]); }}\n\
808         float4 prev_sharp(float2 pos) {{ return sample_sharp(T0, pos / P[1]); }}\n\
809         float4 input(int i, float2 pos) {{\n    switch (i) {{\n{cases}        default: return float4(0.0);\n    }}\n}}\n\
810         float4 from_srgb(float4 c) {{ return float4(srgb_to_linear(saturate(c.rgb)) * c.a, c.a); }}\n\
811         #line 1 \"shader\"\n\
812         {code}\n\
813         }}\n\
814         [shader(\"compute\")]\n[numthreads(16, 16, 1)]\nvoid {ENTRY}(uint3 gid: SV_DispatchThreadID) {{\n    \
815         if (outside_grid(gid.xy)) return;\n    Ctx c0 = root_ctx(gid.xy);\n    \
816         OUT.Store(gid.xy, {NSID}_fb::update(c0.pos, c0.px));\n}}\n"
817    );
818    let key = blake3::hash(body.as_bytes()).to_hex()[..24].to_string();
819    (key, body)
820}