Skip to main content

ultrafast_render/
lib.rs

1//! ultrafast renderer: compiles documents into fused GPU plans and executes them.
2//!
3//! Per frame the renderer: (1) checks the document's structure signature and
4//! recompiles the plan only if it changed, (2) packs params for every group
5//! into the frame's param arena, (3) skips static groups whose inputs and
6//! params are unchanged, (4) dispatches one kernel per group, falling back to
7//! tier-0 kernels for groups whose fused kernel is still compiling.
8//!
9//! Every texture a kernel reads is *placed*: a texture plus the frame
10//! position of its top-left texel. Frame-sized intermediates sit at the
11//! origin; rasterized paths and text get textures sized to their bounds, so
12//! their cost scales with what they cover, not with the frame.
13
14// Engine code: wide kernel and pass signatures and indexed loops over
15// parallel arrays are the clearest form here.
16#![allow(
17    clippy::too_many_arguments,
18    clippy::type_complexity,
19    clippy::needless_range_loop,
20    clippy::should_implement_trait
21)]
22
23pub mod autofaces;
24pub mod blocks;
25pub mod captions;
26mod charts;
27pub mod code;
28pub mod codegen;
29mod glyph_atlas;
30pub mod images;
31pub mod kernels;
32pub mod layout;
33pub mod lottie;
34pub mod particles;
35pub mod plan;
36pub mod pushdown;
37pub mod raymarch;
38pub mod review;
39pub mod scene3d;
40mod sim;
41mod specialize;
42pub mod svg;
43pub mod swarm;
44pub mod tables;
45pub mod transitions;
46
47// Text, vector geometry, the face camera and the op vocabulary live in CPU
48// crates (tools use them without a GPU), re-exported at
49// their old paths.
50pub use ultrafast_framing::follow;
51pub use ultrafast_geom::{fontfetch, geom, lru, markup};
52pub use ultrafast_ops::{builtins, ops, schema};
53
54use images::ImageCache;
55use kernels::{KernelState, Kernels};
56use ops::ResourceInfo;
57use plan::{GroupKind, Plan, TexSource};
58use std::collections::{BTreeMap, HashMap};
59use std::path::{Path, PathBuf};
60use std::sync::Arc;
61use std::time::Instant;
62use ultrafast_gpu::{
63    Bindings, Buffer, BufferBinding, CommandList, Device, GpuError, PixelFormat, Submitted, Texture, TextureDesc,
64};
65use ultrafast_graph::{Document, DocumentError, NodeId};
66
67#[derive(Debug, thiserror::Error)]
68pub enum RenderError {
69    #[error(transparent)]
70    Gpu(#[from] GpuError),
71    #[error(transparent)]
72    Document(#[from] DocumentError),
73    #[error("node `{node}` has unknown op `{op}`")]
74    UnknownOp { node: NodeId, op: String },
75    #[error("node `{node}` is missing required input `{port}`")]
76    MissingPort { node: NodeId, port: String },
77    #[error("node `{node}` param `{param}`: {reason}")]
78    BadParam {
79        node: NodeId,
80        param: String,
81        reason: String,
82    },
83    #[error("node `{node}` needs {count} texture inputs in one kernel (max 16)")]
84    TooManyInputs { node: NodeId, count: usize },
85    #[error("kernel setup failed: {0}")]
86    Setup(String),
87}
88
89/// Geometry errors are the render errors of the same name.
90impl From<ultrafast_geom::GeomError> for RenderError {
91    fn from(e: ultrafast_geom::GeomError) -> Self {
92        match e {
93            ultrafast_geom::GeomError::BadParam { node, param, reason } => {
94                RenderError::BadParam { node, param, reason }
95            }
96        }
97    }
98}
99
100/// Op errors are the render errors of the same name.
101impl From<ultrafast_ops::OpsError> for RenderError {
102    fn from(e: ultrafast_ops::OpsError) -> Self {
103        match e {
104            ultrafast_ops::OpsError::UnknownOp { node, op } => RenderError::UnknownOp { node, op },
105            ultrafast_ops::OpsError::MissingPort { node, port } => RenderError::MissingPort { node, port },
106            ultrafast_ops::OpsError::BadParam { node, param, reason } => RenderError::BadParam { node, param, reason },
107        }
108    }
109}
110
111/// How [`Renderer::render_readback`] hands a frame back.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum Readback {
114    /// sRGB RGBA8.
115    Srgb8,
116    /// sRGB-encoded RGBA half floats, for 10-bit codecs.
117    SrgbHalf,
118    /// Linear RGBA half floats (EXR); straight alpha, as encoders that
119    /// premultiply take it.
120    LinearHalf,
121}
122
123/// How the renderer treats kernels that are still compiling.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum Mode {
126    /// Never stall: use tier-0 fallbacks and placeholders while compiling or
127    /// loading. For live preview.
128    Live,
129    /// Wait for every fused kernel and resource. Deterministic; for export.
130    Exact,
131}
132
133/// What one frame cost and how it was produced.
134#[derive(Debug, Clone, Copy, Default)]
135pub struct FrameReport {
136    pub replanned: bool,
137    pub kernels_run: usize,
138    pub groups_cached: usize,
139    /// Groups skipped because nothing they feed is visible at this time.
140    pub groups_skipped: usize,
141    /// Groups rendered with tier-0 kernels because their fused kernel was
142    /// still compiling.
143    pub groups_fallback: usize,
144    /// Simulation steps taken, and frames rendered only to bring
145    /// simulations up to this one (after a seek).
146    pub sim_steps: usize,
147    pub sim_catchup_frames: usize,
148    /// Motion blur: samples taken this frame (1 when nothing moved), the
149    /// group up to which they were taken, and how many groups up to it read
150    /// nothing moving and ran once instead.
151    pub mb_samples: u32,
152    pub mb_split: usize,
153    pub mb_once: usize,
154    /// Images still decoding and videos whose frame for this time was not
155    /// decoded yet (live mode draws what it has): a later frame at the same
156    /// time will differ, so a paused player draws again.
157    pub media_pending: usize,
158    pub cpu_encode_ms: f64,
159    pub plan_ms: f64,
160}
161
162/// A problem tied to a node that does not stop rendering (bad shader code,
163/// missing image). Agents read these to fix their documents.
164#[derive(Debug, Clone, PartialEq)]
165pub struct Diagnostic {
166    pub node: NodeId,
167    pub message: String,
168}
169
170impl Diagnostic {
171    /// "warning" for parts of an imported file ultrafast leaves out and for
172    /// text that renders but not all of it shows, "error" for problems that
173    /// stop a node from rendering.
174    pub fn severity(&self) -> &'static str {
175        if ["lottie: ", "svg: ", "text: "]
176            .iter()
177            .any(|p| self.message.starts_with(p))
178        {
179            "warning"
180        } else {
181            "error"
182        }
183    }
184}
185
186/// Why a text's keyed `reveal` never shows all of it, if it doesn't: its
187/// keys stop below the glyphs it has (a typewriter keyed for a shorter
188/// text, then edited or filled from a CSV row with a longer one).
189fn reveal_falls_short(node: &ultrafast_graph::Node, units: usize) -> Option<String> {
190    let Some(ultrafast_graph::Param::Animated { keys, .. }) = node.params.get("reveal") else {
191        return None;
192    };
193    let most = keys
194        .iter()
195        .filter_map(|k| k.v.first().copied())
196        .fold(f64::NEG_INFINITY, f64::max);
197    let softness = match node.params.get("reveal_softness") {
198        Some(ultrafast_graph::Param::Number(s)) => s.max(1e-3),
199        _ => 1.0,
200    };
201    // Glyph i shows fully once the reveal reaches i + softness.
202    let needed = units as f64 - 1.0 + softness;
203    if units == 0 || !most.is_finite() || most >= needed - 1e-6 {
204        return None;
205    }
206    let shown = ((most - softness + 1.0).max(0.0).floor() as usize).min(units);
207    let fmt = |v: f64| format!("{}", (v * 100.0).round() / 100.0);
208    Some(format!(
209        "text: its `reveal` keys stop at {}, so the last {} of its {units} glyphs never show in full: key it up to {}",
210        fmt(most),
211        units - shown,
212        fmt(needed)
213    ))
214}
215
216/// The final image of a frame, handed to [`Renderer::submit_frame_with`]
217/// callbacks so they can consume it in the same command buffer.
218pub struct FrameOutput<'a> {
219    pub list: &'a mut CommandList,
220    pub kernels: &'a Kernels,
221    pub texture: &'a Texture,
222    /// Frame position of the texture's top-left texel.
223    pub origin: [f32; 2],
224    /// Frame header (time, frame, width, height) for kernel params.
225    pub header: [f32; 4],
226}
227
228/// How a frame maps onto the textures it renders into: `px` frame pixels
229/// per device texel (1 at the document's own size, 0.5 for twice its
230/// size) and the device size. Everything in a document stays in frame
231/// pixels; only texture sizes and texel steps follow the view.
232#[derive(Debug, Clone, Copy, PartialEq)]
233pub(crate) struct View {
234    pub px: f32,
235    pub w: u32,
236    pub h: u32,
237}
238
239impl View {
240    /// The document at its own size.
241    pub fn native(doc: &Document) -> View {
242        View {
243            px: 1.0,
244            w: doc.format.width,
245            h: doc.format.height,
246        }
247    }
248
249    /// The document drawn at `w` x `h`: one texel step for both axes, the
250    /// finer of the two, so every texel is inside the frame.
251    pub fn sized(doc: &Document, size: Option<(u32, u32)>) -> View {
252        let (fw, fh) = (doc.format.width.max(1), doc.format.height.max(1));
253        match size {
254            Some((w, h)) if (w, h) != (fw, fh) && w > 0 && h > 0 => View {
255                px: 1.0 / (w as f32 / fw as f32).max(h as f32 / fh as f32),
256                w,
257                h,
258            },
259            _ => View::native(doc),
260        }
261    }
262}
263
264/// A texture positioned in the frame.
265#[derive(Clone)]
266struct Placed {
267    tex: Texture,
268    origin: [f32; 2],
269    /// Frame px per texel: 1, or more for a blur kept at the reduced
270    /// resolution it was computed at (the kernels reading it sample it).
271    scale: f32,
272}
273
274struct TexturePool {
275    free: HashMap<TextureDesc, Vec<Texture>>,
276    max_free_per_desc: usize,
277    /// Bytes held in free lists, and the most they may hold: raster
278    /// textures come in many sizes, so a per-size count alone is unbounded.
279    free_bytes: u64,
280    max_free_bytes: u64,
281    /// When each size was last leased or given back: a full pool lets go
282    /// of the sizes nothing has asked for longest (type that grew past a
283    /// size, last week's shot) to keep the ones every frame uses.
284    clock: u64,
285    last_used: HashMap<TextureDesc, u64>,
286}
287
288fn tex_bytes(d: TextureDesc) -> u64 {
289    d.width as u64 * d.height as u64 * d.format.bytes_per_pixel() as u64
290}
291
292impl TexturePool {
293    fn lease(&mut self, device: &Device, desc: TextureDesc) -> Texture {
294        self.clock += 1;
295        self.last_used.insert(desc, self.clock);
296        match self.free.get_mut(&desc).and_then(Vec::pop) {
297            Some(t) => {
298                self.free_bytes -= tex_bytes(desc);
299                t
300            }
301            None => device.create_texture(desc),
302        }
303    }
304
305    fn give_back(&mut self, tex: Texture) {
306        let desc = tex.desc();
307        let bytes = tex_bytes(desc);
308        if bytes > self.max_free_bytes || self.free.get(&desc).is_some_and(|l| l.len() >= self.max_free_per_desc) {
309            return;
310        }
311        self.clock += 1;
312        self.last_used.insert(desc, self.clock);
313        // Make room by dropping the sizes asked for least recently.
314        while self.free_bytes + bytes > self.max_free_bytes {
315            let Some(old) = self
316                .free
317                .iter()
318                .filter(|(d, l)| !l.is_empty() && **d != desc)
319                .min_by_key(|(d, _)| self.last_used.get(*d).copied().unwrap_or(0))
320                .map(|(d, _)| *d)
321            else {
322                return;
323            };
324            let list = self.free.get_mut(&old).unwrap();
325            while self.free_bytes + bytes > self.max_free_bytes && list.pop().is_some() {
326                self.free_bytes -= tex_bytes(old);
327            }
328            if list.is_empty() {
329                self.free.remove(&old);
330                self.last_used.remove(&old);
331            }
332        }
333        self.free.entry(desc).or_default().push(tex);
334        self.free_bytes += bytes;
335    }
336}
337
338type StaticKey = (Vec<f32>, Vec<usize>);
339
340#[derive(Default)]
341struct Profiler {
342    pending: Vec<(String, Submitted)>,
343    totals: HashMap<String, (f64, u32)>,
344}
345
346/// An element under a point of the frame ([`Renderer::pick`]).
347#[derive(Debug, Clone, serde::Serialize)]
348pub struct Picked {
349    /// The document node it belongs to (edit this one).
350    pub node: String,
351    pub op: String,
352    /// The node that drew it (inside a component or block: `node/...`).
353    pub part: String,
354    /// Frame px [x0, y0, x1, y1].
355    pub bounds: [f32; 4],
356}
357
358/// An element on screen ([`Renderer::visible`]).
359#[derive(Debug, Clone, serde::Serialize)]
360pub struct Visible {
361    #[serde(flatten)]
362    pub element: Picked,
363    /// What it reads, for text.
364    #[serde(skip_serializing_if = "Option::is_none")]
365    pub text: Option<String>,
366}
367
368/// Where a document's GPU time goes ([`Renderer::profile_frames`]).
369#[derive(Debug, Clone, serde::Serialize)]
370pub struct ProfileReport {
371    pub frames: u64,
372    pub from: f64,
373    pub gpu_ms_per_frame: f64,
374    /// Most expensive first.
375    pub groups: Vec<GroupShare>,
376    /// Work outside groups: motion-blur averaging, output conversion.
377    pub rest_ms_per_frame: f64,
378}
379
380#[derive(Debug, Clone, serde::Serialize)]
381pub struct GroupShare {
382    /// The group's kind and the nodes it renders.
383    pub group: String,
384    pub ms_per_frame: f64,
385    pub share: f64,
386    /// Motion-blur samples run groups several times a frame.
387    pub runs_per_frame: f64,
388}
389
390/// What one render group cost on the GPU while profiling.
391#[derive(Debug, Clone, serde::Serialize)]
392pub struct GroupCost {
393    /// The group's kind and the nodes it renders.
394    pub group: String,
395    /// Total GPU milliseconds.
396    pub ms: f64,
397    /// Times it ran (motion blur samples run groups several times a frame).
398    pub runs: u32,
399}
400
401struct Active {
402    plan: Plan,
403    /// Frame-sized group outputs. A slot gets a texture the first time a
404    /// live group needs it and gives it back when unused slots outgrow the
405    /// memory budget (long films plan thousands of slots; a frame touches
406    /// a few). Non-resident slots hold the placeholder.
407    slots: Vec<Texture>,
408    resident: Vec<bool>,
409    /// Frame each slot was last needed in.
410    slot_used: Vec<u64>,
411    /// Groups writing each slot (their caches die with its texture).
412    slot_groups: Vec<Vec<usize>>,
413    slot_desc: TextureDesc,
414    /// The view the slots are sized for.
415    view: View,
416    /// Frame each group was last live in (cold raster textures are given
417    /// back under the same budget).
418    group_used: Vec<u64>,
419    /// For static groups: params and input identities of the last run.
420    cache: Vec<Option<StaticKey>>,
421    /// Bounds-sized output textures of raster groups.
422    raster: Vec<Option<Placed>>,
423    /// What each raster group last drew (geometry and paint), so geometry
424    /// that holds still is not drawn again.
425    drawn: Vec<u64>,
426    /// Fused groups that only pass an earlier group's output through at
427    /// the current time (inactive layers, empty foregrounds) show it
428    /// directly instead of copying it.
429    alias: Vec<Option<usize>>,
430    /// Groups whose `raster` entry is another group's texture shown as it is
431    /// (an inactive blur passing its source through): not theirs to reuse
432    /// or return to the pool.
433    borrowed: Vec<bool>,
434    /// Where each group's output can be non-transparent (frame px), as the
435    /// last pass that ran it found.
436    bounds: Vec<ops::Rect>,
437    /// Per blur group: the fused groups reading it, when every reader can
438    /// sample it at the reduced resolution it is computed at (fused groups
439    /// outside their loops, and blurs); None when it must be full size.
440    low_readers: Vec<Option<Vec<usize>>>,
441}
442
443/// A motion-blurred frame's schedule, for the passes that run it.
444struct MbFrame {
445    /// Per group: read by a group of a later phase, so what it makes must
446    /// last until then (no showing a slot another group may write first).
447    crosses: Vec<bool>,
448    /// The shutter's span (seconds): particles drawn once blur themselves
449    /// along their paths over it.
450    span: f64,
451}
452
453/// One sampled group's average across a frame's samples.
454struct MbAccum {
455    /// Running sum (newest, spare) of frame-sized outputs.
456    sum: Option<(Texture, Texture)>,
457    /// Copies of bounds-sized outputs, summed over their union at the end.
458    stash: Vec<Placed>,
459    /// Union of the samples' content bounds.
460    bounds: ops::Rect,
461}
462
463impl Default for MbAccum {
464    fn default() -> Self {
465        MbAccum {
466            sum: None,
467            stash: Vec::new(),
468            bounds: ops::EMPTY,
469        }
470    }
471}
472
473/// Which groups a pass over the plan runs, and what it returns.
474#[derive(Default, Clone, Copy)]
475struct Pass<'a> {
476    /// Only these groups (default: every group that reaches the output now).
477    only: Option<&'a [bool]>,
478    /// The group whose output the pass returns (default: the last).
479    target: Option<usize>,
480    /// Groups whose outputs were replaced outside the pass.
481    changed: &'a [usize],
482    /// Keep the bounds earlier passes this frame found for the groups this
483    /// one does not run (motion blur's samples read what its once-a-frame
484    /// pass made).
485    keep_bounds: bool,
486}
487
488pub struct Renderer {
489    device: Device,
490    kernels: Kernels,
491    active: Option<Active>,
492    seen_revision: Option<(u64, u64)>,
493    pool: TexturePool,
494    images: ImageCache,
495    placeholder: Texture,
496    export: Option<Texture>,
497    mode: Mode,
498    diagnostics: Vec<Diagnostic>,
499    scratch: Vec<f32>,
500    ran: Vec<bool>,
501    /// Per-group GPU timing: each group submitted on its own (see
502    /// [`Renderer::set_profiling`]).
503    profile: Option<Profiler>,
504    /// ULTRAFAST_NO_SKIP: draw every live group every time (a reference for
505    /// checking that skipped work was really redundant).
506    no_skip: bool,
507    /// ULTRAFAST_NO_FRAMED: rasterize off-frame content even when nothing reads
508    /// it (a reference for checking [`plan::Plan::framed`]).
509    no_framed: bool,
510    /// Exact renders wait for a group's fused kernel (default); without,
511    /// groups whose ops all have tier-0 kernels render op by op while it
512    /// compiles (a new look starts at once; see `set_wait_for_fused`).
513    wait_fused: bool,
514    fonts: geom::Fonts,
515    base_dir: PathBuf,
516    /// Built geometry per node: full key, content key (shape without
517    /// placement), the transform it was built under, the geometry.
518    geometry: HashMap<NodeId, (u64, u64, ops::Affine, Arc<geom::Geometry>)>,
519    /// The geometry each node last had built from scratch (key, content
520    /// key, placement), which turns and scales map instead of rebuilding.
521    built: HashMap<NodeId, (u64, u64, ops::Affine, Arc<geom::Geometry>)>,
522    bounds: HashMap<NodeId, [f32; 4]>,
523    acc: Option<Buffer>,
524    videos: HashMap<NodeId, VideoState>,
525    flat: Option<((u64, u64), Arc<ultrafast_graph::Flat>)>,
526    /// Loudness envelopes of soundtracks driving params (120 per second,
527    /// normalized), by file, band and release.
528    envelopes: HashMap<String, Option<Arc<Vec<f32>>>>,
529    /// Where swarm particles settle, by the shape they form.
530    swarm_homes: HashMap<u64, Arc<Vec<[f32; 2]>>>,
531    three: Option<Three>,
532    /// Ping-pong accumulation targets for motion blur.
533    accum: Option<(Texture, Texture)>,
534    /// Color glyph (emoji) bitmaps, created on first use.
535    glyph_atlas: Option<glyph_atlas::GlyphAtlas>,
536    diff_buf: Option<Buffer>,
537    /// Particle pipelines (over, add), the sequential index buffer, and a
538    /// white 1x1 fallback sprite.
539    sprites: Option<(
540        ultrafast_gpu::DrawPipeline,
541        ultrafast_gpu::DrawPipeline,
542        Buffer,
543        Texture,
544    )>,
545    /// Decoded video frames referenced by in-flight GPU work, by frame number.
546    retained: std::collections::VecDeque<(u64, Arc<ultrafast_media::VideoFrame>)>,
547    /// Seconds spent waiting for decoded video frames, and for images an
548    /// exact render needs (decode and upload).
549    media_wait: f64,
550    /// Media not ready for the frame being encoded (see FrameReport::media_pending).
551    media_pending: usize,
552    image_wait: f64,
553    frame_no: u64,
554    /// Simulation state by node.
555    sims: HashMap<NodeId, sim::SimState>,
556    /// Built blocks by their params and frame size.
557    blocks: HashMap<String, Arc<ultrafast_graph::Component>>,
558    /// Built caption tracks by their params and transcript file time.
559    captions: HashMap<String, Arc<ultrafast_graph::Component>>,
560    /// Built face-follow cameras by their params, face file time and format.
561    follows: HashMap<String, Arc<ultrafast_graph::Component>>,
562    /// Imported SVG files by (src, size), with the file time they were read at.
563    svgs: HashMap<String, (Option<std::time::SystemTime>, Arc<svg::Imported>)>,
564    lotties: HashMap<String, (Option<std::time::SystemTime>, Arc<lottie::Imported>)>,
565    /// The frame being rendered (motion-blur samples share it).
566    frame_t: f64,
567    /// While rendering motion-blur samples: (sample, samples, frame time,
568    /// shutter seconds).
569    mb_sample: Option<(u32, u32, f64, f64)>,
570    /// Sample everything every frame (reference renders; ULTRAFAST_MB_FULL=1).
571    mb_full: bool,
572    /// The motion-blurred frame being encoded, its sampled groups' averages,
573    /// and textures it used that go back to the pool next frame.
574    mb_frame: Option<MbFrame>,
575    mb_acc: Vec<Option<MbAccum>>,
576    mb_release: Vec<Texture>,
577    /// Motion blur turned off (a player while it plays: one sample a frame).
578    mb_off: bool,
579    /// Bytes of resident slot textures before unused ones are given back.
580    slot_budget: u64,
581    /// Frames are rendered once each, in order (an export): no seeking
582    /// back, so simulations keep no checkpoints.
583    pub(crate) sequential: bool,
584    /// The output size asked for (None: each document's own).
585    out_size: Option<(u32, u32)>,
586    /// This frame's view.
587    pub(crate) view: View,
588}
589
590/// GPU state of the 3D pass, created on first use.
591struct Three {
592    pipeline: ultrafast_gpu::DrawPipeline,
593    shadow_pipeline: ultrafast_gpu::DrawPipeline,
594    /// Light-space depth (R32F) and its depth attachment.
595    shadow_map: Texture,
596    shadow_depth: Texture,
597    /// Multisampled color and depth attachments, at frame size.
598    attachments: Option<(Texture, Texture)>,
599    /// Depth of field: camera-distance pass, its target (R32F) and depth
600    /// attachment, and the sharp image it blurs (all at frame size).
601    dist_pipeline: ultrafast_gpu::DrawPipeline,
602    dof: Option<(Texture, Texture, Texture)>,
603    white: Texture,
604    /// Vertex buffer, index buffer, index count, local bounds (min, max).
605    meshes: HashMap<String, (Buffer, Buffer, u32, [[f32; 3]; 2])>,
606}
607
608#[derive(Default)]
609struct VideoState {
610    path: String,
611    /// The file as it was when it was opened.
612    stamp: Option<images::FileStamp>,
613    source: Option<ultrafast_media::VideoSource>,
614    error: Option<String>,
615    prepared: Option<Texture>,
616    prepared_pts: Option<f64>,
617}
618
619/// Raster output textures are allocated in steps of this many pixels so
620/// small changes in bounds reuse the same texture.
621const RASTER_BUCKET: u32 = 64;
622/// Largest raster region side, in pixels.
623const MAX_RASTER: i64 = 8192;
624/// Frames of an image sequence decoded ahead of the playhead.
625const SEQUENCE_AHEAD: usize = 12;
626
627/// Where a document's media reference points: URLs (`https://...`, decoded
628/// by ffmpeg straight from the network) and absolute paths as they are,
629/// relative paths under `base`.
630pub fn media_path(base: &Path, src: &str) -> PathBuf {
631    if src.contains("://") || Path::new(src).is_absolute() {
632        PathBuf::from(src)
633    } else {
634        base.join(src)
635    }
636}
637
638impl Renderer {
639    pub fn new(device: Device) -> Result<Self, RenderError> {
640        let kernels = Kernels::new(device.clone()).map_err(RenderError::Setup)?;
641        Self::with_kernels(device, kernels)
642    }
643
644    /// A renderer whose ops' tier-0 kernels compile only when a frame first
645    /// needs one ([`Kernels::on_demand`]), for a command that renders and
646    /// exits (an export, a frame, a check): its exact renders wait for
647    /// their fused kernels anyway. On the first run after an install or an
648    /// upgrade it starts about 0.9 s sooner. [`Renderer::new`] builds them
649    /// all first, so a live session never waits on the compiler.
650    pub fn new_on_demand(device: Device) -> Result<Self, RenderError> {
651        let kernels = Kernels::on_demand(device.clone()).map_err(RenderError::Setup)?;
652        Self::with_kernels(device, kernels)
653    }
654
655    fn with_kernels(device: Device, kernels: Kernels) -> Result<Self, RenderError> {
656        let placeholder = device.create_texture(TextureDesc {
657            width: 1,
658            height: 1,
659            format: PixelFormat::Rgba16Float,
660            cpu_readable: false,
661        });
662        let r = Self {
663            device,
664            kernels,
665            active: None,
666            seen_revision: None,
667            pool: TexturePool {
668                free: HashMap::new(),
669                max_free_per_desc: 128,
670                free_bytes: 0,
671                max_free_bytes: 1 << 30,
672                clock: 0,
673                last_used: HashMap::new(),
674            },
675            images: ImageCache::new(),
676            placeholder,
677            export: None,
678            mode: Mode::Exact,
679            diagnostics: Vec::new(),
680            scratch: Vec::with_capacity(256),
681            ran: Vec::new(),
682            profile: None,
683            no_skip: std::env::var_os("ULTRAFAST_NO_SKIP").is_some(),
684            no_framed: std::env::var_os("ULTRAFAST_NO_FRAMED").is_some(),
685            wait_fused: true,
686            fonts: geom::Fonts::new(),
687            base_dir: PathBuf::from("."),
688            geometry: HashMap::new(),
689            built: HashMap::new(),
690            bounds: HashMap::new(),
691            acc: None,
692            videos: HashMap::new(),
693            flat: None,
694            envelopes: HashMap::new(),
695            swarm_homes: HashMap::new(),
696            three: None,
697            accum: None,
698            glyph_atlas: None,
699            diff_buf: None,
700            sprites: None,
701            retained: std::collections::VecDeque::new(),
702            media_wait: 0.0,
703            media_pending: 0,
704            image_wait: 0.0,
705            frame_no: 0,
706            sims: HashMap::new(),
707            svgs: HashMap::new(),
708            lotties: HashMap::new(),
709            captions: HashMap::new(),
710            follows: HashMap::new(),
711            blocks: HashMap::new(),
712            frame_t: 0.0,
713            mb_sample: None,
714            mb_full: std::env::var("ULTRAFAST_MB_FULL").is_ok(),
715            mb_frame: None,
716            mb_acc: Vec::new(),
717            mb_release: Vec::new(),
718            mb_off: false,
719            slot_budget: 0,
720            sequential: false,
721            out_size: None,
722            view: View { px: 1.0, w: 1, h: 1 },
723        };
724        // Slots may take a third of GPU memory, shared by ULTRAFAST_WORKERS
725        // processes (ULTRAFAST_SLOT_BUDGET_MB overrides).
726        let mut r = r;
727        r.slot_budget = std::env::var("ULTRAFAST_SLOT_BUDGET_MB")
728            .ok()
729            .and_then(|v| v.parse::<u64>().ok())
730            .map(|mb| mb << 20)
731            .unwrap_or_else(|| {
732                // Processes sharing the GPU (parallel export) split it.
733                let workers = std::env::var("ULTRAFAST_WORKERS")
734                    .ok()
735                    .and_then(|v| v.parse::<u64>().ok())
736                    .unwrap_or(1)
737                    .max(1);
738                r.device.memory_bytes() / 3 / workers
739            });
740        // New textures are uninitialized; clear the placeholder once.
741        let mut list = r.device.begin();
742        list.dispatch(
743            &r.kernels.utility("k_clear"),
744            &r.placeholder,
745            &[],
746            &[0.0, 0.0, 1.0, 1.0],
747        );
748        list.submit().wait()?;
749        let device = r.device.clone();
750        r.images.set_device(&device);
751        Ok(r)
752    }
753
754    /// Bytes resident group slots and kept raster textures may use before
755    /// cold ones are given back.
756    pub fn set_slot_budget(&mut self, bytes: u64) {
757        self.slot_budget = bytes;
758        self.pool.max_free_bytes = (bytes / 8).min(1 << 30);
759    }
760
761    /// Declares that frames will be rendered once each, in order (an
762    /// export), so state kept only for seeking back can be skipped.
763    pub fn set_sequential(&mut self, on: bool) {
764        self.sequential = on;
765    }
766
767    /// Lets go of everything held for the current document (plan, group
768    /// and raster textures, decoders, images, simulations, built parts)
769    /// and keeps what any document reuses: compiled kernels, pipelines and
770    /// fonts. A warm renderer serving one document after another calls this
771    /// between them, so GPU memory returns to its baseline instead of
772    /// collecting every earlier document's resources. Call with no frames
773    /// in flight.
774    /// Pins font files to their family, weight and style for what renders
775    /// next, until [`Renderer::unpin_fonts`] (see
776    /// [`geom::Fonts::pin`]): a document laid out elsewhere with those
777    /// files sets its text with them here.
778    pub fn pin_fonts(&mut self, pins: &[geom::FontPin]) -> Result<(), String> {
779        self.release_document();
780        self.fonts.pin(pins)
781    }
782
783    /// How what renders next sets the writing systems its fonts do not
784    /// cover, until [`Renderer::unpin_fonts`] (see
785    /// [`geom::Fonts::set_script_fonts`]).
786    pub fn set_script_fonts(&mut self, rows: Vec<geom::ScriptFont>) {
787        self.release_document();
788        self.fonts.set_script_fonts(rows);
789    }
790
791    /// Drops the pins of [`Renderer::pin_fonts`].
792    pub fn unpin_fonts(&mut self) {
793        self.release_document();
794        self.fonts.unpin();
795    }
796
797    /// Drops the decoded images and video decoders whose files changed on
798    /// disk since they were read (a look re-rendered into the same file, a
799    /// sheet rebuilt), and the cached results made from them, so the next
800    /// frame shows the files as they are now. Returns how many it dropped;
801    /// costs a stat per image and video held. A player calls it when a
802    /// document is (re)loaded and every so often while it is open.
803    pub fn refresh_changed_media(&mut self) -> usize {
804        let mut n = self.images.drop_changed();
805        let base = self.base_dir.clone();
806        self.videos.retain(|_, v| {
807            if v.path.is_empty() || v.path.contains("://") {
808                return true;
809            }
810            let same = images::file_stamp(&media_path(&base, &v.path)) == v.stamp;
811            n += (!same) as usize;
812            same
813        });
814        if n > 0
815            && let Some(a) = self.active.as_mut()
816        {
817            for c in a.cache.iter_mut() {
818                *c = None;
819            }
820        }
821        n
822    }
823
824    pub fn release_document(&mut self) {
825        self.active = None;
826        self.seen_revision = None;
827        self.pool.free.clear();
828        self.pool.last_used.clear();
829        self.pool.free_bytes = 0;
830        let base = self.base_dir.clone();
831        self.images = ImageCache::new();
832        self.images.set_base_dir(&base);
833        self.images.set_device(&self.device);
834        self.export = None;
835        self.geometry.clear();
836        self.built.clear();
837        self.bounds.clear();
838        self.acc = None;
839        self.videos.clear();
840        self.flat = None;
841        self.envelopes.clear();
842        self.swarm_homes.clear();
843        if let Some(three) = self.three.as_mut() {
844            three.attachments = None;
845            three.dof = None;
846            three.meshes.clear();
847        }
848        self.accum = None;
849        self.glyph_atlas = None;
850        self.diff_buf = None;
851        self.retained.clear();
852        self.sims.clear();
853        self.blocks.clear();
854        self.captions.clear();
855        self.follows.clear();
856        self.svgs.clear();
857        self.lotties.clear();
858        self.diagnostics.clear();
859    }
860
861    /// Seconds this renderer has spent waiting for decoded media and
862    /// uploading decoded images (part of the CPU time of the frames).
863    pub fn media_wait(&self) -> f64 {
864        self.media_wait + self.image_wait
865    }
866
867    /// The part of [`media_wait`](Self::media_wait) spent on images.
868    pub fn image_wait(&self) -> f64 {
869        self.image_wait
870    }
871
872    pub fn device(&self) -> &Device {
873        &self.device
874    }
875
876    /// Profiling: every group is submitted to the GPU on its own and timed,
877    /// which is slower but says what each part of a film costs. Read the
878    /// totals with [`Renderer::profile`].
879    pub fn set_profiling(&mut self, on: bool) {
880        self.profile = on.then(Profiler::default);
881    }
882
883    /// GPU time per group so far (waits for groups still running), most
884    /// expensive first.
885    pub fn profile(&mut self) -> Result<Vec<GroupCost>, RenderError> {
886        let Some(p) = &mut self.profile else {
887            return Ok(Vec::new());
888        };
889        for (label, sub) in p.pending.drain(..) {
890            let ms = sub.wait()?.gpu_ms;
891            let e = p.totals.entry(label).or_insert((0.0, 0));
892            e.0 += ms;
893            e.1 += 1;
894        }
895        let mut out: Vec<GroupCost> = p
896            .totals
897            .iter()
898            .map(|(k, &(ms, runs))| GroupCost {
899                group: k.clone(),
900                ms,
901                runs,
902            })
903            .collect();
904        out.sort_by(|a, b| b.ms.total_cmp(&a.ms));
905        Ok(out)
906    }
907
908    /// Whether to skip work that cannot change the frame (redrawing still
909    /// geometry, copying layers that only pass through). On by default;
910    /// off (or ULTRAFAST_NO_SKIP) renders a reference to check it against.
911    pub fn set_skip_redundant(&mut self, on: bool) {
912        self.no_skip = !on;
913    }
914
915    /// Renders `frames` frames from `from` seconds with every group timed
916    /// on its own: where the GPU time of `doc` goes, per frame.
917    pub fn profile_frames(&mut self, doc: &Document, frames: u64, from: f64) -> Result<ProfileReport, RenderError> {
918        // Compile the plan's kernels first so they are not timed.
919        self.submit_frame(doc, from, false)?.0.wait()?;
920        self.set_profiling(true);
921        let first = (from * doc.format.fps).round() as u64;
922        let n = doc.format.frame_count().max(1);
923        let frames = frames.max(1);
924        let mut rest = 0.0;
925        let result = (|| {
926            for i in 0..frames {
927                let (sub, _) = self.submit_frame(doc, doc.format.time_of((first + i) % n), false)?;
928                rest += sub.wait()?.gpu_ms;
929                if i % 16 == 15 {
930                    self.profile()?;
931                }
932            }
933            self.profile()
934        })();
935        self.set_profiling(false);
936        let costs = result?;
937        let f = frames as f64;
938        let total = costs.iter().map(|c| c.ms).sum::<f64>() + rest;
939        Ok(ProfileReport {
940            frames,
941            from,
942            gpu_ms_per_frame: total / f,
943            groups: costs
944                .into_iter()
945                .map(|c| GroupShare {
946                    share: c.ms / total.max(1e-9),
947                    ms_per_frame: c.ms / f,
948                    runs_per_frame: c.runs as f64 / f,
949                    group: c.group,
950                })
951                .collect(),
952            rest_ms_per_frame: rest / f,
953        })
954    }
955
956    /// Motion blur samples every group on every frame instead of only what
957    /// moves (reference renders).
958    pub fn set_full_motion_blur(&mut self, full: bool) {
959        self.mb_full = full;
960    }
961
962    /// Turns the document's motion blur on or off for the frames that
963    /// follow. A player turns it off while it plays (one render a frame
964    /// keeps playback smooth) and back on when it stops, so a still frame
965    /// shows exactly what the export will.
966    pub fn set_motion_blur(&mut self, on: bool) {
967        self.mb_off = !on;
968    }
969
970    pub fn set_mode(&mut self, mode: Mode) {
971        self.mode = mode;
972    }
973
974    /// Whether exact renders wait for fused kernels still compiling. Off,
975    /// such a group renders op by op with the tier-0 kernels (built at
976    /// startup) until its fused kernel is ready: the same image to within
977    /// half-float rounding of the intermediates, with no compile stall when
978    /// a document's structure is new (a new look on a render service).
979    /// Groups with an op that has no tier-0 kernel (custom shaders) still
980    /// wait.
981    pub fn set_wait_for_fused(&mut self, on: bool) {
982        self.wait_fused = on;
983    }
984
985    pub fn waits_for_fused(&self) -> bool {
986        self.wait_fused
987    }
988
989    pub fn mode(&self) -> Mode {
990        self.mode
991    }
992
993    /// Directory relative resource paths resolve against.
994    pub fn set_base_dir(&mut self, dir: &Path) {
995        self.base_dir = dir.to_path_buf();
996        self.images.set_base_dir(dir);
997    }
998
999    pub fn base_dir(&self) -> &Path {
1000        &self.base_dir
1001    }
1002
1003    pub fn plan(&self) -> Option<&Plan> {
1004        self.active.as_ref().map(|a| &a.plan)
1005    }
1006
1007    pub fn kernels(&self) -> &Kernels {
1008        &self.kernels
1009    }
1010
1011    pub fn diagnostics(&self) -> &[Diagnostic] {
1012        &self.diagnostics
1013    }
1014
1015    pub fn clear_diagnostics(&mut self) {
1016        self.diagnostics.clear();
1017    }
1018
1019    fn diagnose(&mut self, node: &str, message: String) {
1020        let d = Diagnostic {
1021            node: node.to_string(),
1022            message,
1023        };
1024        if !self.diagnostics.contains(&d) {
1025            self.diagnostics.push(d);
1026        }
1027    }
1028
1029    /// Bounds (min x, min y, max x, max y) in output pixels of a path or text
1030    /// node, as of the last frame it was rasterized.
1031    /// Outlines of a text node as SVG path data (pixels, placed), for
1032    /// morphing letters or reusing type as vector shapes.
1033    pub fn text_outline(&mut self, node: &ultrafast_graph::Node) -> Result<String, RenderError> {
1034        let fmt = ultrafast_graph::Format {
1035            width: 1,
1036            height: 1,
1037            fps: 1.0,
1038            duration: 1.0,
1039            motion_blur: None,
1040        };
1041        let mut all = kurbo::BezPath::new();
1042        for (p, _, _) in geom::text_paths(
1043            "text",
1044            node,
1045            &fmt,
1046            0.0,
1047            ops::Affine::IDENTITY,
1048            &mut self.fonts,
1049            &self.base_dir,
1050        )?
1051        .0
1052        {
1053            all.extend(p);
1054        }
1055        Ok(all.to_svg())
1056    }
1057
1058    /// Glyph-by-glyph metrics of a single-line text node (see
1059    /// [`geom::measure`]), with this renderer's fonts and base directory.
1060    pub fn measure_text(&mut self, node: &ultrafast_graph::Node) -> Result<geom::LineMetrics, RenderError> {
1061        Ok(geom::measure("text", node, 0.0, &mut self.fonts, &self.base_dir)?)
1062    }
1063
1064    pub fn node_bounds(&self, id: &str) -> Option<[f32; 4]> {
1065        self.bounds.get(id).copied()
1066    }
1067
1068    /// What is under frame point (x, y) at `t`, as last rendered: the
1069    /// smallest visible element there (text, path, shape, image, video),
1070    /// named by the document node it belongs to (a component instance or
1071    /// block for its parts) and by the part itself, with its frame bounds.
1072    pub fn pick(&self, doc: &Document, t: f64, x: f32, y: f32) -> Option<Picked> {
1073        let (px, py) = (x as f64, y as f64);
1074        self.elements(doc, t)
1075            .into_iter()
1076            .filter(|(p, _)| {
1077                let b = p.bounds;
1078                px >= b[0] as f64 && px <= b[2] as f64 && py >= b[1] as f64 && py <= b[3] as f64
1079            })
1080            .min_by(|a, b| {
1081                let area = |p: &Picked| (p.bounds[2] - p.bounds[0]) as f64 * (p.bounds[3] - p.bounds[1]) as f64;
1082                area(&a.0).total_cmp(&area(&b.0))
1083            })
1084            .map(|(p, _)| p)
1085    }
1086
1087    /// Every visible element at `t`, as last rendered (render `t` first):
1088    /// texts, paths, shapes, images and videos that are active and inside
1089    /// the frame, with their document node, bounds, and the words of text.
1090    pub fn visible(&self, doc: &Document, t: f64) -> Vec<Visible> {
1091        let (fw, fh) = (doc.format.width as f32, doc.format.height as f32);
1092        self.elements(doc, t)
1093            .into_iter()
1094            .filter(|(p, _)| p.bounds[2] > 0.0 && p.bounds[3] > 0.0 && p.bounds[0] < fw && p.bounds[1] < fh)
1095            .map(|(p, text)| Visible { element: p, text })
1096            .collect()
1097    }
1098
1099    fn elements(&self, doc: &Document, t: f64) -> Vec<(Picked, Option<String>)> {
1100        let Some(active) = self.active.as_ref() else {
1101            return Vec::new();
1102        };
1103        let plan = &active.plan;
1104        let (fw, fh) = (doc.format.width as f64, doc.format.height as f64);
1105        let flat = self.flat.as_ref().map(|(_, f)| f.clone());
1106        let node_of = |id: &str| {
1107            flat.as_ref()
1108                .and_then(|f| f.doc.nodes.get(id).cloned())
1109                .or_else(|| doc.nodes.get(id).cloned())
1110        };
1111        // What reaches the output at `t`: an inactive composite passes its
1112        // background through (a transition before its change shows only
1113        // the outgoing shot), an inactive effect its source, and nothing
1114        // shows through a zero opacity.
1115        let n = plan.nodes.len();
1116        let mut reaches = vec![false; n];
1117        let output = flat
1118            .as_ref()
1119            .map(|f| f.doc.output.clone())
1120            .unwrap_or_else(|| doc.output.clone());
1121        let mut stack: Vec<usize> = plan
1122            .nodes
1123            .iter()
1124            .position(|pn| pn.id == output)
1125            .or(n.checked_sub(1))
1126            .into_iter()
1127            .collect();
1128        while let Some(i) = stack.pop() {
1129            if reaches[i] {
1130                continue;
1131            }
1132            reaches[i] = true;
1133            let pn = &plan.nodes[i];
1134            let (lt, on) = local_time(pn, t);
1135            let num = |k: &str, d: f64| {
1136                node_of(&pn.id)
1137                    .and_then(|nd| nd.params.get(k).and_then(|p| p.eval(lt)))
1138                    .and_then(|v| v.first().copied())
1139                    .unwrap_or(d)
1140            };
1141            let ports = pn.def.ports;
1142            let port = |name: &str| {
1143                (pn.inputs.len() == ports.len())
1144                    .then(|| ports.iter().position(|p| *p == name).map(|k| pn.inputs[k]))
1145                    .flatten()
1146            };
1147            let next: Vec<usize> = match (on, pn.def.name) {
1148                (false, _) => port("bg").or(port("source")).into_iter().collect(),
1149                (true, "over" | "blend") if num("opacity", 1.0) <= 1e-3 => port("bg").into_iter().collect(),
1150                (true, "opacity") if num("opacity", 1.0) <= 1e-3 => Vec::new(),
1151                (true, "mix") if num("t", 0.5) <= 1e-3 => port("a").into_iter().collect(),
1152                (true, "mix") if num("t", 0.5) >= 1.0 - 1e-3 => port("b").into_iter().collect(),
1153                _ => pn.inputs.clone(),
1154            };
1155            stack.extend(next);
1156        }
1157        // Each element is then walked up to the output: under an opaque
1158        // layer (a card cut in over it), cropped away or faded out on every
1159        // path there, it is not on screen. Text and paths start where their
1160        // raster chain ends, which is where their bounds are.
1161        let fdoc: &Document = match flat.as_ref() {
1162            Some(f) if needs_flat(doc) => &f.doc,
1163            _ => doc,
1164        };
1165        let consumers = review::consumers(plan);
1166        let opaque = opaque_rects(plan, fdoc, t);
1167        let mut root_of: Vec<usize> = (0..n).collect();
1168        for g in &plan.groups {
1169            if let Some(rc) = &g.raster {
1170                root_of[rc.node] = g.root;
1171            }
1172        }
1173        let mut out = Vec::new();
1174        for (i, pn) in plan.nodes.iter().enumerate() {
1175            let (lt, on) = local_time(pn, t);
1176            if !on || !reaches[i] {
1177                continue;
1178            }
1179            // Faded out entirely.
1180            if node_of(&pn.id)
1181                .and_then(|nd| nd.params.get("opacity").and_then(|p| p.eval(lt)))
1182                .and_then(|v| v.first().copied())
1183                .is_some_and(|o| o <= 1e-3)
1184            {
1185                continue;
1186            }
1187            let b = match self.bounds.get(&pn.id) {
1188                Some(b) if b[0] < b[2] => [b[0] as f64, b[1] as f64, b[2] as f64, b[3] as f64],
1189                Some(_) => continue,
1190                None if pn.inputs.is_empty() && matches!(pn.def.name, "shape" | "image" | "video") => {
1191                    let Some(node) = node_of(&pn.id) else { continue };
1192                    let r = ops::bounds(pn.def, &node, &doc.format, lt, &[], None);
1193                    // Whole-frame backgrounds are not things to point at.
1194                    if r[0] <= 0.0 && r[1] <= 0.0 && r[2] >= fw && r[3] >= fh {
1195                        continue;
1196                    }
1197                    r
1198                }
1199                None => continue,
1200            };
1201            if !review::reaches_screen(plan, fdoc, &consumers, &opaque, root_of[i], b, 1.0, 1e-3, t) {
1202                continue;
1203            }
1204            let node = pn.id.split('/').next().unwrap_or(&pn.id).to_string();
1205            let text = (pn.def.name == "text")
1206                .then(|| node_of(&pn.id).map(|n| geom::display_text(&n, lt)))
1207                .flatten();
1208            let r = |v: f64| ((v * 10.0).round() / 10.0) as f32;
1209            out.push((
1210                Picked {
1211                    op: doc.nodes.get(&node).map(|n| n.op.clone()).unwrap_or_default(),
1212                    node,
1213                    part: pn.id.clone(),
1214                    bounds: [r(b[0]), r(b[1]), r(b[2]), r(b[3])],
1215                },
1216                text,
1217            ));
1218        }
1219        out
1220    }
1221
1222    /// Frame bounds of a node's vector content: its own, or the union over
1223    /// the nodes of a component instance (`id/...`), as last rendered.
1224    pub fn content_bounds(&self, id: &str) -> Option<[f32; 4]> {
1225        let prefix = format!("{id}/");
1226        self.bounds
1227            .iter()
1228            .filter(|(k, b)| (k.as_str() == id || k.starts_with(&prefix)) && b[0] < b[2])
1229            .map(|(_, b)| *b)
1230            .reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])
1231    }
1232
1233    /// Replans if the document's structure changed. Returns whether it did.
1234    /// Document with components expanded, cached per revision.
1235    fn flattened(&mut self, doc: &Document) -> Result<Arc<ultrafast_graph::Flat>, RenderError> {
1236        let key = (doc.instance, doc.revision);
1237        if let Some((k, f)) = &self.flat
1238            && *k == key
1239        {
1240            return Ok(f.clone());
1241        }
1242        // Components whose nodes expand from their params get a copy per
1243        // instance with the instance's values in, so those nodes expand
1244        // wherever they are.
1245        let specialized;
1246        let doc = match specialize::per_instance(
1247            doc,
1248            &["block", "code", "stack", "captions", "clip_camera", "svg", "lottie"],
1249        ) {
1250            Some(d) => {
1251                specialized = d;
1252                &specialized
1253            }
1254            None => doc,
1255        };
1256        let with_blocks;
1257        let doc = if uses_op(doc, &["block", "code"]) {
1258            let mut d = doc.clone();
1259            self.in_scopes(&mut d, Self::expand_blocks);
1260            if self.blocks.len() > 64 {
1261                self.blocks.clear();
1262            }
1263            with_blocks = d;
1264            &with_blocks
1265        } else {
1266            doc
1267        };
1268        let laid_out;
1269        let doc = if uses_op(doc, &["stack"]) {
1270            let base = self.base_dir.clone();
1271            let (mut d, mut problems) = if layout::used_by(doc) {
1272                layout::expand(doc, &mut self.fonts, &base)
1273            } else {
1274                (doc.clone(), Vec::new())
1275            };
1276            // Stacks inside components lay out in the component's own graph;
1277            // its input ports stand in as empty layers while they do.
1278            let inner: Vec<String> = d
1279                .components
1280                .iter()
1281                .filter(|(_, c)| c.nodes.values().any(|n| n.op == "stack"))
1282                .map(|(k, _)| k.clone())
1283                .collect();
1284            for name in inner {
1285                let c = &d.components[&name];
1286                let mut nodes = c.nodes.clone();
1287                let ports: Vec<String> = c.inputs.iter().map(|p| format!("${p}")).collect();
1288                for port in &ports {
1289                    nodes.insert(
1290                        port.clone(),
1291                        ultrafast_graph::Node {
1292                            op: "solid".into(),
1293                            params: [("color".to_string(), ultrafast_graph::Param::Text("#00000000".into()))].into(),
1294                            ..Default::default()
1295                        },
1296                    );
1297                }
1298                let scoped = Document {
1299                    version: d.version,
1300                    format: d.format,
1301                    output: c.output.clone(),
1302                    nodes,
1303                    components: Default::default(),
1304                    revision: 0,
1305                    structure_revision: 0,
1306                    instance: 0,
1307                };
1308                let (mut out, p) = layout::expand(&scoped, &mut self.fonts, &base);
1309                problems.extend(p.into_iter().map(|(n, m)| (format!("{name}/{n}"), m)));
1310                for port in &ports {
1311                    out.nodes.remove(port);
1312                }
1313                if let Some(c) = d.components.get_mut(&name) {
1314                    c.nodes = out.nodes;
1315                }
1316            }
1317            for (n, m) in problems {
1318                self.diagnose(&n, m);
1319            }
1320            laid_out = d;
1321            &laid_out
1322        } else {
1323            doc
1324        };
1325        let with_raymarch;
1326        let doc = if let Some((d, problems)) = expand_everywhere(doc, raymarch::used_by, raymarch::expand) {
1327            for (n, m) in problems {
1328                self.diagnose(&n, m);
1329            }
1330            with_raymarch = d;
1331            &with_raymarch
1332        } else {
1333            doc
1334        };
1335        let with_transitions;
1336        let doc = if let Some((d, problems)) = expand_everywhere(doc, transitions::used_by, transitions::expand) {
1337            for (n, m) in problems {
1338                self.diagnose(&n, m);
1339            }
1340            with_transitions = d;
1341            &with_transitions
1342        } else {
1343            doc
1344        };
1345        let with_captions;
1346        let doc = if uses_op(doc, &["captions"]) {
1347            let mut d = doc.clone();
1348            self.in_scopes(&mut d, Self::expand_captions);
1349            if self.captions.len() > 32 {
1350                self.captions.clear();
1351            }
1352            with_captions = d;
1353            &with_captions
1354        } else {
1355            doc
1356        };
1357        let with_follow;
1358        let doc = if uses_op(doc, &["clip_camera"]) {
1359            let mut d = doc.clone();
1360            self.in_scopes(&mut d, Self::expand_follow);
1361            if self.follows.len() > 32 {
1362                self.follows.clear();
1363            }
1364            with_follow = d;
1365            &with_follow
1366        } else {
1367            doc
1368        };
1369        let expanded;
1370        let doc = if svg::used_by(doc) {
1371            let base = self.base_dir.clone();
1372            let mut problems = Vec::new();
1373            let svgs = &mut self.svgs;
1374            expanded = svg::expand(
1375                doc,
1376                |_, node| {
1377                    let key = format!("{:?}", (node.params.get("src"), node.params.get("size")));
1378                    let src = match node.params.get("src") {
1379                        Some(ultrafast_graph::Param::Text(s)) => base.join(s),
1380                        _ => PathBuf::new(),
1381                    };
1382                    let mtime = std::fs::metadata(&src).and_then(|m| m.modified()).ok();
1383                    if let Some((m, imp)) = svgs.get(&key)
1384                        && *m == mtime
1385                    {
1386                        return Ok(imp.clone());
1387                    }
1388                    let imp = Arc::new(svg::import_node(node, &base)?);
1389                    svgs.insert(key, (mtime, imp.clone()));
1390                    Ok(imp)
1391                },
1392                |node, msg| problems.push((node.to_string(), msg)),
1393            );
1394            for (n, m) in problems {
1395                self.diagnose(&n, m);
1396            }
1397            &expanded
1398        } else {
1399            doc
1400        };
1401        let with_lottie;
1402        let doc = if lottie::used_by(doc) {
1403            let base = self.base_dir.clone();
1404            let mut problems = Vec::new();
1405            let cache = &mut self.lotties;
1406            let fonts = &mut self.fonts;
1407            with_lottie = lottie::expand(
1408                doc,
1409                |_, node| {
1410                    let key = format!("{:?}", (node.params.get("src"), node.params.get("size")));
1411                    let src = match node.params.get("src") {
1412                        Some(ultrafast_graph::Param::Text(s)) => base.join(s),
1413                        _ => PathBuf::new(),
1414                    };
1415                    let mtime = std::fs::metadata(&src).and_then(|m| m.modified()).ok();
1416                    if let Some((m, imp)) = cache.get(&key)
1417                        && *m == mtime
1418                    {
1419                        return Ok(imp.clone());
1420                    }
1421                    let imp = Arc::new(lottie::import_node(node, &base, fonts)?);
1422                    cache.insert(key, (mtime, imp.clone()));
1423                    Ok(imp)
1424                },
1425                |node, msg| problems.push((node.to_string(), msg)),
1426            );
1427            for (n, m) in problems {
1428                self.diagnose(&n, m);
1429            }
1430            &with_lottie
1431        } else {
1432            doc
1433        };
1434        let mut f = if builtins::used_by(doc) {
1435            builtins::with_builtins(doc).flatten()?
1436        } else {
1437            doc.flatten()?
1438        };
1439        self.bake_audio_drivers(&mut f.doc);
1440        if pushdown::wanted(&f.doc) {
1441            pushdown::distribute(&mut f);
1442        }
1443        let f = Arc::new(f);
1444        self.flat = Some((key, f.clone()));
1445        Ok(f)
1446    }
1447
1448    /// Runs an expansion pass on the document's own nodes and on each
1449    /// component's (`scope` names where, for the components a pass makes),
1450    /// adding what it makes to the document's components.
1451    fn in_scopes(
1452        &mut self,
1453        d: &mut Document,
1454        mut pass: impl FnMut(
1455            &mut Self,
1456            &mut BTreeMap<String, ultrafast_graph::Node>,
1457            &mut BTreeMap<String, ultrafast_graph::Component>,
1458            &ultrafast_graph::Format,
1459            &str,
1460        ),
1461    ) {
1462        let fmt = d.format;
1463        let mut made = BTreeMap::new();
1464        pass(self, &mut d.nodes, &mut made, &fmt, "");
1465        let names: Vec<String> = d.components.keys().cloned().collect();
1466        for name in names {
1467            let Some(c) = d.components.get_mut(&name) else { continue };
1468            let mut nodes = std::mem::take(&mut c.nodes);
1469            pass(self, &mut nodes, &mut made, &fmt, &format!("{name}/"));
1470            if let Some(c) = d.components.get_mut(&name) {
1471                c.nodes = nodes;
1472            }
1473        }
1474        d.components.extend(made);
1475    }
1476
1477    /// `block` and `code` nodes become components of their own.
1478    fn expand_blocks(
1479        &mut self,
1480        nodes: &mut BTreeMap<String, ultrafast_graph::Node>,
1481        made: &mut BTreeMap<String, ultrafast_graph::Component>,
1482        fmt: &ultrafast_graph::Format,
1483        scope: &str,
1484    ) {
1485        let base = self.base_dir.clone();
1486        let ids: Vec<String> = nodes
1487            .iter()
1488            .filter(|(_, n)| n.op == "block" || n.op == "code")
1489            .map(|(k, _)| k.clone())
1490            .collect();
1491        for id in ids {
1492            let node = nodes[&id].clone();
1493            let key = format!("{}|{:?}|{:?}", node.op, node.params, (fmt.width, fmt.height));
1494            let built = match self.blocks.get(&key) {
1495                Some(c) => Ok(c.clone()),
1496                None if node.op == "code" => code::build(&node, fmt, &mut self.fonts, &base).map(Arc::new),
1497                None => blocks::build(&node, fmt, &mut self.fonts, &base).map(Arc::new),
1498            };
1499            let n = nodes.get_mut(&id).unwrap();
1500            match built {
1501                Ok(c) => {
1502                    self.blocks.insert(key, c.clone());
1503                    // A block costs nothing once it has exited: it
1504                    // gets a window over its own lifetime.
1505                    if n.op == "block"
1506                        && let Some(life) = blocks::lifetime(n)
1507                    {
1508                        let tm = n.timing.get_or_insert_with(Default::default);
1509                        if !tm.has_window() && tm.loop_duration.is_none() && tm.speed > 0.0 {
1510                            tm.in_point = Some(tm.offset);
1511                            tm.out_point = Some(tm.offset + life / tm.speed);
1512                        }
1513                    }
1514                    let name = format!("{}:{scope}{id}", n.op);
1515                    made.insert(name.clone(), (*c).clone());
1516                    n.op = name;
1517                    n.params.retain(|k, _| blocks::PARAMS.contains(&k.as_str()));
1518                }
1519                Err(e) => {
1520                    self.diagnose(&format!("{scope}{id}"), e);
1521                    n.op = "solid".into();
1522                    n.params = [("color".to_string(), ultrafast_graph::Param::Text("#00000000".into()))].into();
1523                }
1524            }
1525        }
1526    }
1527
1528    /// `captions` nodes become components of word nodes.
1529    fn expand_captions(
1530        &mut self,
1531        nodes: &mut BTreeMap<String, ultrafast_graph::Node>,
1532        made: &mut BTreeMap<String, ultrafast_graph::Component>,
1533        fmt: &ultrafast_graph::Format,
1534        scope: &str,
1535    ) {
1536        let base = self.base_dir.clone();
1537        let ids: Vec<String> = nodes
1538            .iter()
1539            .filter(|(_, n)| n.op == "captions")
1540            .map(|(k, _)| k.clone())
1541            .collect();
1542        for id in ids {
1543            let node = nodes[&id].clone();
1544            let src_time = match node.params.get("src") {
1545                Some(ultrafast_graph::Param::Text(s)) => {
1546                    std::fs::metadata(base.join(s)).and_then(|m| m.modified()).ok()
1547                }
1548                _ => None,
1549            };
1550            let key = format!("{:?}|{:?}|{:?}", node.params, src_time, (fmt.width, fmt.height));
1551            let built = match self.captions.get(&key) {
1552                Some(c) => Ok(c.clone()),
1553                None => captions::words_of(&node, &base)
1554                    .and_then(|w| captions::build(&w, &node, fmt, &mut self.fonts, &base))
1555                    .map(Arc::new),
1556            };
1557            let n = nodes.get_mut(&id).unwrap();
1558            match built {
1559                Ok(c) => {
1560                    self.captions.insert(key, c.clone());
1561                    let name = format!("captions:{scope}{id}");
1562                    made.insert(name.clone(), (*c).clone());
1563                    n.op = name;
1564                    n.params.retain(|k, _| captions::PARAMS.contains(&k.as_str()));
1565                }
1566                Err(e) => {
1567                    self.diagnose(&format!("{scope}{id}"), e);
1568                    n.op = "solid".into();
1569                    n.params = [("color".to_string(), ultrafast_graph::Param::Text("#00000000".into()))].into();
1570                }
1571            }
1572        }
1573    }
1574
1575    /// A `clip_camera` node with `faces`: as given, or tracked from its
1576    /// footage (see [`autofaces`]) when it has none.
1577    fn with_faces(
1578        &mut self,
1579        node: &ultrafast_graph::Node,
1580        fmt: &ultrafast_graph::Format,
1581        base: &Path,
1582    ) -> Result<ultrafast_graph::Node, String> {
1583        use ultrafast_graph::Param;
1584        if node.params.contains_key("faces") {
1585            return Ok(node.clone());
1586        }
1587        let Some(Param::Text(src)) = node.params.get("src") else {
1588            return Err("`clip_camera` needs `src` (the source video)".into());
1589        };
1590        let num = |k: &str| {
1591            node.params
1592                .get(k)
1593                .and_then(|p| p.eval(0.0))
1594                .and_then(|v| v.first().copied())
1595        };
1596        let start = num("start").unwrap_or(0.0);
1597        let duration = num("duration").unwrap_or(fmt.duration);
1598        let path = if Path::new(src).is_absolute() {
1599            PathBuf::from(src)
1600        } else {
1601            base.join(src)
1602        };
1603        let faces = autofaces::track(&self.device, &path, start, start + duration)?;
1604        let mut node = node.clone();
1605        node.params.insert("faces".into(), Param::Text(faces.to_string()));
1606        Ok(node)
1607    }
1608
1609    /// `clip_camera` nodes become components of keyed video nodes.
1610    fn expand_follow(
1611        &mut self,
1612        nodes: &mut BTreeMap<String, ultrafast_graph::Node>,
1613        made: &mut BTreeMap<String, ultrafast_graph::Component>,
1614        fmt: &ultrafast_graph::Format,
1615        scope: &str,
1616    ) {
1617        let base = self.base_dir.clone();
1618        let ids: Vec<String> = nodes
1619            .iter()
1620            .filter(|(_, n)| n.op == "clip_camera")
1621            .map(|(k, _)| k.clone())
1622            .collect();
1623        for id in ids {
1624            let node = nodes[&id].clone();
1625            let key = format!(
1626                "{:?}|{:?}|{:?}",
1627                node.params,
1628                follow::inputs_time(&node, &base),
1629                (fmt.width, fmt.height, fmt.fps.to_bits(), fmt.duration.to_bits())
1630            );
1631            let built = match self.follows.get(&key) {
1632                Some(c) => Ok(c.clone()),
1633                None => self
1634                    .with_faces(&node, fmt, &base)
1635                    .and_then(|node| follow::build(&node, fmt, &base).map(Arc::new)),
1636            };
1637            let n = nodes.get_mut(&id).unwrap();
1638            match built {
1639                Ok(c) => {
1640                    self.follows.insert(key, c.clone());
1641                    let name = format!("clip_camera:{scope}{id}");
1642                    made.insert(name.clone(), (*c).clone());
1643                    n.op = name;
1644                    n.params.retain(|k, _| follow::PARAMS.contains(&k.as_str()));
1645                }
1646                Err(e) => {
1647                    self.diagnose(&format!("{scope}{id}"), e);
1648                    n.op = "solid".into();
1649                    n.params = [("color".to_string(), ultrafast_graph::Param::Text("#00000000".into()))].into();
1650                }
1651            }
1652        }
1653    }
1654
1655    /// Fetches the font families `doc` names that this machine lacks,
1656    /// several at once, before its first render would fetch them one by one.
1657    pub fn prefetch_fonts(&mut self, doc: &Document) {
1658        let mut names: Vec<String> = Vec::new();
1659        let mut scan = |nodes: &BTreeMap<String, ultrafast_graph::Node>| {
1660            for n in nodes.values() {
1661                for k in ["font", "em_font"] {
1662                    if let Some(ultrafast_graph::Param::Text(f)) = n.params.get(k) {
1663                        for name in f.split(',').map(|x| x.trim().trim_matches(|c| c == '"' || c == '\'')) {
1664                            if !name.is_empty() && !names.iter().any(|x| x == name) {
1665                                names.push(name.to_string());
1666                            }
1667                        }
1668                    }
1669                }
1670            }
1671        };
1672        scan(&doc.nodes);
1673        for c in doc.components.values() {
1674            scan(&c.nodes);
1675        }
1676        let missing: Vec<String> = names.into_iter().filter(|n| self.fonts.lacks(n)).collect();
1677        if !missing.is_empty() {
1678            fontfetch::prefetch(&missing);
1679        }
1680    }
1681
1682    /// Replaces audio-driven params with keyframes (60 per second) that
1683    /// follow the soundtrack's loudness in the chosen band.
1684    fn bake_audio_drivers(&mut self, doc: &mut Document) {
1685        let duration = doc.format.duration;
1686        let mut baked: Vec<(String, String, ultrafast_graph::Param)> = Vec::new();
1687        for (id, node) in &doc.nodes {
1688            for (name, p) in &node.params {
1689                let ultrafast_graph::Param::Audio { audio } = p else {
1690                    continue;
1691                };
1692                let Some(env) = self.envelope(audio) else { continue };
1693                let (lo, hi) = (
1694                    audio.range.first().copied().unwrap_or(0.0),
1695                    audio.range.get(1).copied().unwrap_or(1.0),
1696                );
1697                let n = (duration * 60.0).ceil() as usize + 1;
1698                let keys: Vec<ultrafast_graph::Key> = (0..n)
1699                    .map(|i| {
1700                        let t = i as f64 / 60.0;
1701                        let k = ((t + audio.start) * 120.0).round().max(0.0) as usize;
1702                        let v = env.get(k).copied().unwrap_or(0.0) as f64;
1703                        ultrafast_graph::Key {
1704                            t,
1705                            v: vec![lo + (hi - lo) * v],
1706                            ease: ultrafast_graph::Ease::Linear,
1707                        }
1708                    })
1709                    .collect();
1710                baked.push((
1711                    id.clone(),
1712                    name.clone(),
1713                    ultrafast_graph::Param::Animated { keys, repeat: None },
1714                ));
1715            }
1716        }
1717        for (id, name, p) in baked {
1718            doc.nodes.get_mut(&id).unwrap().params.insert(name, p);
1719        }
1720    }
1721
1722    fn envelope(&mut self, a: &ultrafast_graph::driver::AudioDriver) -> Option<Arc<Vec<f32>>> {
1723        let key = format!("{}|{}|{}", a.src, a.band, a.smooth);
1724        if let Some(e) = self.envelopes.get(&key) {
1725            return e.clone();
1726        }
1727        let path = media_path(&self.base_dir, &a.src);
1728        let env = match ultrafast_media::audio::decode(&path) {
1729            Ok(Some(pcm)) => Some(Arc::new(audio_envelope(&pcm, &a.band, a.smooth))),
1730            Ok(None) => {
1731                self.diagnose("audio", format!("{} has no audio track", path.display()));
1732                None
1733            }
1734            Err(e) => {
1735                self.diagnose("audio", format!("{}: {e}", path.display()));
1736                None
1737            }
1738        };
1739        self.envelopes.insert(key, env.clone());
1740        env
1741    }
1742
1743    fn ensure_plan(&mut self, doc: &Document, chains: Option<&plan::Chains>) -> Result<bool, RenderError> {
1744        self.view = View::sized(doc, self.out_size);
1745        let view = self.view;
1746        let same_view = self.active.as_ref().is_some_and(|a| a.view == view);
1747        if !same_view {
1748            // Geometry built for another density is not mapped to this one
1749            // (outlines are flattened and glyphs drawn for their size): a
1750            // size renders the same however the renderer got to it.
1751            self.geometry.clear();
1752            self.built.clear();
1753        }
1754        if same_view && self.seen_revision == Some((doc.instance, doc.revision)) {
1755            return Ok(false);
1756        }
1757        self.seen_revision = Some((doc.instance, doc.revision));
1758        let sig = plan::signature(doc, chains);
1759        if same_view && self.active.as_ref().is_some_and(|a| a.plan.signature == sig) {
1760            return Ok(false);
1761        }
1762        let plan = plan::compile(doc, chains)?;
1763        // Per-node caches of nodes that no longer exist are dropped.
1764        self.geometry.retain(|id, _| doc.nodes.contains_key(id));
1765        self.built.retain(|id, _| doc.nodes.contains_key(id));
1766        self.bounds.retain(|id, _| doc.nodes.contains_key(id));
1767        if let Some(three) = self.three.as_mut()
1768            && three.meshes.len() > 64
1769        {
1770            three.meshes.clear();
1771        }
1772        // Video decoders of nodes that no longer exist are dropped.
1773        self.videos
1774            .retain(|id, _| doc.nodes.get(id).is_some_and(|n| n.op == "video"));
1775        // Queue every fused kernel this plan needs; known ones are no-ops.
1776        let jobs: Vec<(String, String)> = plan
1777            .groups
1778            .iter()
1779            .filter(|g| g.kind == GroupKind::Fused || (g.kind == GroupKind::Sim && !g.key.is_empty()))
1780            .map(|g| (g.key.clone(), g.body.clone()))
1781            .collect();
1782        self.kernels.request(jobs);
1783        for g in &plan.groups {
1784            for t in &g.textures {
1785                if let TexSource::Resource(src) = t
1786                    && let Some(path) = src.strip_prefix("image:").or_else(|| src.strip_prefix("lut:"))
1787                {
1788                    // Sequences are requested per frame.
1789                    if !path.contains("{frame") {
1790                        self.images.request(path);
1791                    }
1792                }
1793            }
1794        }
1795        if let Some(old) = self.active.take() {
1796            for (t, r) in old.slots.into_iter().zip(old.resident) {
1797                if r {
1798                    self.pool.give_back(t);
1799                }
1800            }
1801            for (p, b) in old.raster.into_iter().zip(old.borrowed) {
1802                if let (Some(p), false) = (p, b) {
1803                    self.pool.give_back(p.tex);
1804                }
1805            }
1806        }
1807        let desc = TextureDesc {
1808            width: view.w,
1809            height: view.h,
1810            format: PixelFormat::Rgba16Float,
1811            cpu_readable: false,
1812        };
1813        let mut slot_groups = vec![Vec::new(); plan.slot_count];
1814        for (gi, g) in plan.groups.iter().enumerate() {
1815            if let Some(s) = slot_groups.get_mut(g.output) {
1816                s.push(gi);
1817            }
1818        }
1819        let n = plan.groups.len();
1820        let low = low_readers(&plan);
1821        self.active = Some(Active {
1822            slots: vec![self.placeholder.clone(); plan.slot_count],
1823            resident: vec![false; plan.slot_count],
1824            slot_used: vec![0; plan.slot_count],
1825            slot_groups,
1826            slot_desc: desc,
1827            view,
1828            group_used: vec![0; n],
1829            plan,
1830            cache: vec![None; n],
1831            raster: vec![None; n],
1832            drawn: vec![0; n],
1833            alias: vec![None; n],
1834            borrowed: vec![false; n],
1835            bounds: vec![ops::UNBOUNDED; n],
1836            low_readers: low,
1837        });
1838        Ok(true)
1839    }
1840
1841    /// Renders the frames that follow at `size` (device pixels) instead of
1842    /// each document's own size; None goes back to that. The document stays
1843    /// in its own frame pixels: a 1920x1080 document at 3840x2160 is drawn
1844    /// with twice the texels (text, paths, blurs, particles, 3D re-rendered
1845    /// at the finer grid), not scaled up. A size of another shape keeps the
1846    /// finer of the two scales and crops the last texel row or column.
1847    pub fn set_output_size(&mut self, size: Option<(u32, u32)>) {
1848        self.out_size = size;
1849    }
1850
1851    /// The output size asked for (None: each document's own).
1852    pub fn output_size(&self) -> Option<(u32, u32)> {
1853        self.out_size
1854    }
1855
1856    /// The size frames of `doc` render at, in device pixels.
1857    pub fn frame_size(&self, doc: &Document) -> (u32, u32) {
1858        let v = View::sized(doc, self.out_size);
1859        (v.w, v.h)
1860    }
1861
1862    fn export_texture(&mut self, w: u32, h: u32, format: PixelFormat) -> Texture {
1863        let desc = TextureDesc {
1864            width: w,
1865            height: h,
1866            format,
1867            cpu_readable: true,
1868        };
1869        match &self.export {
1870            Some(t) if t.desc() == desc => t.clone(),
1871            _ => {
1872                let t = self.device.create_texture(desc);
1873                self.export = Some(t.clone());
1874                t
1875            }
1876        }
1877    }
1878
1879    /// Encodes and submits frame `t` (seconds). With `export`, the final image
1880    /// is also encoded to sRGB RGBA8 in a CPU-readable texture for
1881    /// [`Renderer::read_export`]. Does not wait for the GPU.
1882    pub fn submit_frame(
1883        &mut self,
1884        doc: &Document,
1885        t: f64,
1886        export: bool,
1887    ) -> Result<(Submitted, FrameReport), RenderError> {
1888        if !export {
1889            return self.submit_frame_with(doc, t, |_| {});
1890        }
1891        let (w, h) = self.frame_size(doc);
1892        let ex = self.export_texture(w, h, PixelFormat::Rgba8Unorm);
1893        self.submit_frame_with(doc, t, |o| {
1894            let mut p = o.header.to_vec();
1895            p.extend(o.origin);
1896            p.push(0.0);
1897            o.list
1898                .dispatch(&o.kernels.utility("k_encode_srgb8"), &ex, &[o.texture], &p);
1899        })
1900    }
1901
1902    /// Encodes frame `t`, then lets `finish` add work that consumes the
1903    /// final image (export, display, video encode) before submitting.
1904    pub fn submit_frame_with(
1905        &mut self,
1906        doc: &Document,
1907        t: f64,
1908        finish: impl FnOnce(FrameOutput),
1909    ) -> Result<(Submitted, FrameReport), RenderError> {
1910        let start = Instant::now();
1911        let flat = if needs_flat(doc) {
1912            Some(self.flattened(doc)?)
1913        } else {
1914            None
1915        };
1916        let doc: &Document = flat.as_ref().map(|f| &f.doc).unwrap_or(doc);
1917        let chains = flat.as_ref().map(|f| &f.chains);
1918        let replanned = self.ensure_plan(doc, chains)?;
1919        let plan_ms = start.elapsed().as_secs_f64() * 1000.0;
1920        let mut report = FrameReport {
1921            replanned,
1922            plan_ms,
1923            ..Default::default()
1924        };
1925        self.media_pending = 0;
1926        // Under memory pressure (zooming layers replace big textures every
1927        // frame), finish the frames in flight and let go of what they and
1928        // the pool hold before starting another.
1929        if self.device.memory_in_use() > self.device.memory_bytes() / 10 * 7 {
1930            self.pool.free.clear();
1931            self.pool.last_used.clear();
1932            self.pool.free_bytes = 0;
1933            self.device.reclaim();
1934        }
1935        let mut list = self.device.begin();
1936        for tex in std::mem::take(&mut self.mb_release) {
1937            self.pool.give_back(tex);
1938        }
1939        // Frames older than the in-flight window are no longer read by the GPU.
1940        self.frame_no += 1;
1941        while self.retained.front().is_some_and(|(n, _)| *n + 4 < self.frame_no) {
1942            self.retained.pop_front();
1943        }
1944        self.prepare_images(&mut list);
1945
1946        let mut active = self.active.take().expect("plan");
1947        self.trim_slots(&mut active);
1948        self.frame_t = t;
1949        let result = self
1950            .sim_catch_up(&mut active, doc, t, &mut list, &mut report)
1951            .and_then(
1952                |_| match doc.format.motion_blur.filter(|m| m.samples > 1 && !self.mb_off) {
1953                    None => self.encode_groups(&mut active, doc, t, &mut list, &mut report),
1954                    Some(mb) => self.encode_motion_blur(&mut active, doc, t, mb, &mut list, &mut report),
1955                },
1956            );
1957        self.active = Some(active);
1958        let output = result?;
1959        // Consumers get the frame in device texels: the texture at the
1960        // view's density, its origin and the header's size in texels.
1961        let output = self.on_device_grid(output, doc, t, &mut list);
1962        let v = self.view;
1963        finish(FrameOutput {
1964            list: &mut list,
1965            kernels: &self.kernels,
1966            texture: &output.tex,
1967            origin: [output.origin[0] / v.px, output.origin[1] / v.px],
1968            header: [t as f32, 1.0, v.w as f32, v.h as f32],
1969        });
1970        report.cpu_encode_ms = start.elapsed().as_secs_f64() * 1000.0;
1971        report.media_pending = self.media_pending;
1972        self.images.end_frame();
1973        Ok((list.submit(), report))
1974    }
1975
1976    /// `p` at the view's density: as it is when it already is, else
1977    /// resampled into a frame-sized texture (given back next frame).
1978    fn on_device_grid(&mut self, p: Placed, doc: &Document, t: f64, list: &mut CommandList) -> Placed {
1979        let v = self.view;
1980        let aligned = |o: f32| (o / v.px - (o / v.px).round()).abs() < 1e-3;
1981        if p.scale == v.px && aligned(p.origin[0]) && aligned(p.origin[1]) {
1982            return p;
1983        }
1984        let desc = TextureDesc {
1985            width: v.w,
1986            height: v.h,
1987            format: PixelFormat::Rgba16Float,
1988            cpu_readable: false,
1989        };
1990        let tex = self.pool.lease(&self.device, desc);
1991        let taps = (v.px / p.scale).ceil().max(1.0);
1992        let mut prm = header(doc, t, v).to_vec();
1993        prm.extend([v.px, 0.0, 0.0, p.origin[0], p.origin[1], p.scale, taps]);
1994        list.dispatch(&self.kernels.utility("k_resample"), &tex, &[&p.tex], &prm);
1995        self.mb_release.push(tex.clone());
1996        Placed {
1997            tex,
1998            origin: [0.0, 0.0],
1999            scale: v.px,
2000        }
2001    }
2002
2003    /// Keeps frame-to-frame GPU memory under the budget: while resident
2004    /// slots and kept raster textures exceed it, the ones no frame needed
2005    /// lately are given back, oldest first. Their groups' caches are dropped,
2006    /// so they render again when next needed.
2007    fn trim_slots(&mut self, active: &mut Active) {
2008        let slot_bytes = tex_bytes(active.slot_desc);
2009        // (last used, slot or group, bytes)
2010        let mut held = 0u64;
2011        let mut cold: Vec<(u64, Result<usize, usize>, u64)> = Vec::new();
2012        for s in 0..active.slots.len() {
2013            if active.resident[s] {
2014                held += slot_bytes;
2015                if active.slot_used[s] + 1 < self.frame_no {
2016                    cold.push((active.slot_used[s], Ok(s), slot_bytes));
2017                }
2018            }
2019        }
2020        for g in 0..active.raster.len() {
2021            if let (Some(p), false) = (&active.raster[g], active.borrowed[g]) {
2022                let b = tex_bytes(p.tex.desc());
2023                held += b;
2024                if active.group_used[g] + 1 < self.frame_no {
2025                    cold.push((active.group_used[g], Err(g), b));
2026                }
2027            }
2028        }
2029        if std::env::var_os("ULTRAFAST_DEBUG_MEM").is_some()
2030            && self.frame_no
2031                % std::env::var("ULTRAFAST_DEBUG_MEM")
2032                    .ok()
2033                    .and_then(|v| v.parse().ok())
2034                    .filter(|&n: &u64| n > 1)
2035                    .unwrap_or(30)
2036                == 0
2037        {
2038            eprintln!(
2039                "mem: frame {}: slots+rasters {} MiB (budget {} MiB, {} cold), pool {} MiB, acc {} MiB, sims {}, images {} MiB, allocated {}/{} MiB, device {} MiB, rss {} MiB",
2040                self.frame_no,
2041                held >> 20,
2042                self.slot_budget >> 20,
2043                cold.len(),
2044                self.pool.free_bytes >> 20,
2045                self.acc.as_ref().map_or(0, |b| b.len()) >> 20,
2046                self.sims.len(),
2047                self.images.bytes() >> 20,
2048                self.device.memory_allocated().0 >> 20,
2049                self.device.memory_allocated().1 >> 20,
2050                self.device.memory_in_use() >> 20,
2051                std::fs::read_to_string("/proc/self/statm")
2052                    .ok()
2053                    .and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
2054                    .map_or(0, |pages| pages * 4096 >> 20)
2055            );
2056            if self.frame_no % 10 == 0 {
2057                eprintln!("mem:   {}", self.device.memory_breakdown(8));
2058            }
2059        }
2060        if held <= self.slot_budget {
2061            return;
2062        }
2063        cold.sort_by_key(|c| c.0);
2064        for (_, which, bytes) in cold {
2065            if held <= self.slot_budget {
2066                break;
2067            }
2068            held -= bytes;
2069            // Dropped, not pooled: the point is to free the memory.
2070            match which {
2071                Ok(s) => {
2072                    drop(std::mem::replace(&mut active.slots[s], self.placeholder.clone()));
2073                    active.resident[s] = false;
2074                    for &g in &active.slot_groups[s] {
2075                        active.cache[g] = None;
2076                    }
2077                }
2078                Err(g) => {
2079                    drop(active.raster[g].take());
2080                    active.drawn[g] = 0;
2081                }
2082            }
2083        }
2084    }
2085
2086    /// Uploads newly decoded images and converts them to the working space.
2087    fn prepare_images(&mut self, list: &mut CommandList) {
2088        let block = self.mode == Mode::Exact;
2089        let t0 = Instant::now();
2090        let fresh = self.images.poll(&self.device, block);
2091        self.image_wait += t0.elapsed().as_secs_f64();
2092        if fresh.is_empty() {
2093            return;
2094        }
2095        let prep = self.kernels.utility("k_prep_srgb8");
2096        for (src, raw) in fresh {
2097            let d = raw.desc();
2098            let tex = self.device.create_texture(TextureDesc {
2099                width: d.width,
2100                height: d.height,
2101                format: PixelFormat::Rgba16Float,
2102                cpu_readable: false,
2103            });
2104            list.dispatch(&prep, &tex, &[&raw], &[0.0, 0.0, d.width as f32, d.height as f32, 0.0]);
2105            self.images.mark_ready(&src, tex);
2106        }
2107    }
2108
2109    fn resource(
2110        &mut self,
2111        key: &str,
2112        node: &str,
2113        doc: &Document,
2114        t: f64,
2115        list: &mut CommandList,
2116    ) -> (Texture, Option<ResourceInfo>) {
2117        if let Some(rest) = key.strip_prefix("video:") {
2118            let path = rest.split('\u{1f}').next().unwrap_or(rest);
2119            return self.video_frame(path, node, doc, t, list);
2120        }
2121        let raw = key
2122            .strip_prefix("image:")
2123            .or_else(|| key.strip_prefix("lut:"))
2124            .unwrap_or(key);
2125        // A sequence's key carries its node id after a unit separator.
2126        let raw = raw.split('\u{1f}').next().unwrap_or(raw);
2127        // Image sequences resolve to this frame's file.
2128        let resolved;
2129        let src = if raw.contains("{frame") && !node.is_empty() {
2130            resolved = ops::sequence_path(raw, &doc.nodes[node], t, doc.format.fps);
2131            self.images.request(&resolved);
2132            // The next frames decode on other threads while this one renders.
2133            for i in 1..=SEQUENCE_AHEAD {
2134                let next = ops::sequence_path(raw, &doc.nodes[node], t + i as f64 / doc.format.fps, doc.format.fps);
2135                if next != resolved {
2136                    self.images.prefetch(&next);
2137                }
2138            }
2139            if self.mode == Mode::Exact {
2140                self.prepare_images(list);
2141            }
2142            resolved.as_str()
2143        } else {
2144            // Still images are requested when the plan is built, but the LRU
2145            // may drop one before its first use (a cutout sequence filling
2146            // the cache while the image waits for its window): ask again,
2147            // or it stays a placeholder for the rest of an export.
2148            if !self.images.is_known(raw) {
2149                self.images.request(raw);
2150                if self.mode == Mode::Exact {
2151                    self.prepare_images(list);
2152                }
2153            }
2154            raw
2155        };
2156        match self.images.get(src) {
2157            Some(images::ImageState::Ready(t)) => {
2158                let d = t.desc();
2159                (
2160                    t.clone(),
2161                    Some(ResourceInfo {
2162                        width: d.width,
2163                        height: d.height,
2164                    }),
2165                )
2166            }
2167            Some(images::ImageState::Failed(e)) => {
2168                let e = e.clone();
2169                self.diagnose(node, e);
2170                (self.placeholder.clone(), None)
2171            }
2172            _ => {
2173                self.media_pending += 1;
2174                (self.placeholder.clone(), None)
2175            }
2176        }
2177    }
2178
2179    /// The current frame of a `video` node, converted to the working space.
2180    /// Decoded frames arrive zero-copy from the hardware decoder (or as the
2181    /// decoder's bytes in GPU-visible memory); one pass per new source
2182    /// frame converts, turns upright and linearizes them into a node-owned
2183    /// texture.
2184    fn video_frame(
2185        &mut self,
2186        path: &str,
2187        node: &str,
2188        doc: &Document,
2189        t: f64,
2190        list: &mut CommandList,
2191    ) -> (Texture, Option<ResourceInfo>) {
2192        let state = self.videos.entry(node.to_string()).or_default();
2193        if state.path != path {
2194            let full = media_path(&self.base_dir, path);
2195            *state = VideoState {
2196                path: path.to_string(),
2197                stamp: images::file_stamp(&full),
2198                ..Default::default()
2199            };
2200            match ultrafast_media::VideoSource::open(&self.device, &full) {
2201                Ok(s) => state.source = Some(s),
2202                Err(e) => state.error = Some(e.to_string()),
2203            }
2204        }
2205        if let Some(e) = state.error.clone() {
2206            self.diagnose(node, e);
2207            return (self.placeholder.clone(), None);
2208        }
2209        let source = state.source.as_ref().unwrap();
2210        let info = ResourceInfo {
2211            width: source.info.width,
2212            height: source.info.height,
2213        };
2214        let tau = ops::video_time(&doc.nodes[node], t, source.info.duration);
2215        let waited = source.waited();
2216        let frame = source.frame_at(tau, self.mode == Mode::Exact);
2217        self.media_wait += source.waited() - waited;
2218        let frame = match frame {
2219            Ok(f) => f,
2220            Err(e) => {
2221                state.error = Some(e.to_string());
2222                self.diagnose(node, e.to_string());
2223                return (self.placeholder.clone(), None);
2224            }
2225        };
2226        let Some(frame) = frame else {
2227            self.media_pending += 1;
2228            return match &state.prepared {
2229                Some(p) => (p.clone(), Some(info)),
2230                None => (self.placeholder.clone(), Some(info)),
2231            };
2232        };
2233        if state.prepared.is_none() || state.prepared_pts != Some(frame.pts) {
2234            let tex = state
2235                .prepared
2236                .get_or_insert_with(|| {
2237                    self.device.create_texture(TextureDesc {
2238                        width: info.width,
2239                        height: info.height,
2240                        format: PixelFormat::Rgba16Float,
2241                        cpu_readable: false,
2242                    })
2243                })
2244                .clone();
2245            let mut p = vec![0.0, 0.0, info.width as f32, info.height as f32];
2246            p.extend(source.format.params(source.info.rotation));
2247            let kernel = self.kernels.utility("k_prep_video");
2248            #[cfg(all(target_os = "macos", not(feature = "vulkan")))]
2249            let (input, data) = (frame.texture(), BufferBinding::Data(&[0u8; 16]));
2250            #[cfg(not(all(target_os = "macos", not(feature = "vulkan"))))]
2251            let (input, data) = (&self.placeholder, BufferBinding::Buffer(frame.buffer()));
2252            list.dispatch_ex(
2253                &kernel,
2254                &tex,
2255                &[input],
2256                &p,
2257                Bindings {
2258                    buffers: &[data],
2259                    ..Default::default()
2260                },
2261            );
2262            state.prepared_pts = Some(frame.pts);
2263            // The decoded frame must outlive the GPU work reading it.
2264            self.retained.push_back((self.frame_no, frame));
2265        }
2266        (state.prepared.clone().unwrap(), Some(info))
2267    }
2268
2269    /// Renders `mb.samples` sub-frames across the shutter (more where
2270    /// things move fast, up to `mb.max_samples`) and averages them layer by
2271    /// layer, as a compositor blurs each moving layer. Every
2272    /// group runs in one phase: groups that read nothing moving run once, at
2273    /// the frame's time, first (phase 0); groups holding a moving layer run
2274    /// per sample, in waves (odd phases), chained to the sampled groups of
2275    /// their wave they read; a sampled group read by a later phase is
2276    /// averaged across the samples, and the groups that read it run once,
2277    /// after its wave (even phases), on that average. A frame where nothing
2278    /// moves renders once.
2279    fn encode_motion_blur(
2280        &mut self,
2281        active: &mut Active,
2282        doc: &Document,
2283        t: f64,
2284        mb: ultrafast_graph::MotionBlur,
2285        list: &mut CommandList,
2286        report: &mut FrameReport,
2287    ) -> Result<Placed, RenderError> {
2288        let span = mb.shutter / doc.format.fps;
2289        let moving = if self.mb_full {
2290            vec![true; active.plan.nodes.len()]
2291        } else {
2292            self.moving_nodes(&active.plan, doc, t - span / 2.0, t + span / 2.0)
2293        };
2294        let n = match mb.max_samples {
2295            Some(max) if max > mb.samples => {
2296                // Motion measured in device texels: a larger view takes more
2297                // samples for the same move, so it blurs as smoothly.
2298                mb.samples_for(
2299                    self.motion_extent_px(&active.plan, doc, &moving, t - span / 2.0, t + span / 2.0)
2300                        / self.view.px as f64,
2301                )
2302            }
2303            _ => mb.samples,
2304        };
2305        let plan = &active.plan;
2306        let ng = plan.groups.len();
2307        // What reaches the output at any time in the shutter (a cut inside
2308        // it shows the shot before it in the first samples).
2309        let mut live = live_groups(plan, t);
2310        for s in 0..n {
2311            let ts = t - span / 2.0 + span * (s as f64 + 0.5) / n as f64;
2312            for (l, m) in live.iter_mut().zip(live_groups(plan, ts)) {
2313                *l |= m;
2314            }
2315        }
2316        let here: Vec<bool> = plan.groups.iter().map(|g| g.nodes.iter().any(|&m| moving[m])).collect();
2317        // Phases in plan order (inputs come first). A group that reads
2318        // nothing moving: 0. One holding a moving node: odd, the wave of the
2319        // sampled groups it reads, or the next one after anything else it
2320        // reads (whose sampled inputs it then reads as averages). Any other
2321        // group reading something moving: even, after what it reads.
2322        let mut phase = vec![0u32; ng];
2323        let mut affected = vec![false; ng];
2324        for g in 0..ng {
2325            let mut p = 0u32;
2326            for ts in &plan.groups[g].textures {
2327                let TexSource::Group(i) = *ts else { continue };
2328                if !affected[i] {
2329                    continue;
2330                }
2331                let sampled_i = phase[i] % 2 == 1;
2332                p = p.max(match (here[g], sampled_i) {
2333                    (true, true) | (false, false) => phase[i],
2334                    _ => phase[i] + 1,
2335                });
2336            }
2337            affected[g] = here[g] || p > 0;
2338            phase[g] = match (affected[g], here[g]) {
2339                (false, _) => 0,
2340                (true, true) => p.max(1) | 1,
2341                (true, false) => p.max(2),
2342            };
2343        }
2344        let sampled: Vec<bool> = phase.iter().map(|p| p % 2 == 1).collect();
2345        if !(0..ng).any(|g| sampled[g] && live[g]) {
2346            report.mb_samples = 1;
2347            return self.encode_groups(active, doc, t, list, report);
2348        }
2349        let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); ng];
2350        for (c, gr) in plan.groups.iter().enumerate() {
2351            for ts in &gr.textures {
2352                if let TexSource::Group(s) = *ts {
2353                    consumers[s].push(c);
2354                }
2355            }
2356        }
2357        // Read by a later phase: what it makes must last until then.
2358        let crosses: Vec<bool> = (0..ng)
2359            .map(|g| consumers[g].iter().any(|&c| phase[c] > phase[g]))
2360            .collect();
2361        // A group that runs once and crosses, with a slot that another
2362        // group writes while it is still needed, renders into a texture of
2363        // its own this frame.
2364        let writes_slot = |k: usize| {
2365            matches!(
2366                plan.groups[k].kind,
2367                GroupKind::Fused | GroupKind::Render3D | GroupKind::Sim
2368            )
2369        };
2370        let pinned: Vec<usize> = (0..ng)
2371            .filter(|&g| {
2372                let gr = &plan.groups[g];
2373                !sampled[g]
2374                    && crosses[g]
2375                    && live[g]
2376                    && gr.kind == GroupKind::Fused
2377                    && !gr.is_static
2378                    && (0..ng).any(|k| {
2379                        k != g
2380                            && writes_slot(k)
2381                            && plan.groups[k].output == gr.output
2382                            && (phase[k] > phase[g] || (phase[k] == phase[g] && k > g))
2383                    })
2384            })
2385            .collect();
2386        report.mb_samples = n;
2387        report.mb_split = (0..ng).rev().find(|&g| sampled[g] && live[g]).unwrap_or(0);
2388        report.mb_once = (0..ng).filter(|&g| !sampled[g] && live[g]).count();
2389        if std::env::var_os("ULTRAFAST_DEBUG_MB").is_some() {
2390            let names: Vec<&str> = moving
2391                .iter()
2392                .enumerate()
2393                .filter(|(_, m)| **m)
2394                .map(|(i, _)| plan.nodes[i].id.as_str())
2395                .collect();
2396            let per: Vec<String> = (0..ng)
2397                .filter(|&g| sampled[g] && live[g])
2398                .map(|g| format!("g{g}@{}", phase[g]))
2399                .collect();
2400            eprintln!(
2401                "t={t:.3} {} once ({} pinned), sampled {}; moving: {}",
2402                report.mb_once,
2403                pinned.len(),
2404                per.join(" "),
2405                names.join(" ")
2406            );
2407        }
2408        for &g in &pinned {
2409            let tex = self.pool.lease(&self.device, active.slot_desc);
2410            active.raster[g] = Some(Placed {
2411                tex,
2412                origin: [0.0, 0.0],
2413                scale: active.view.px,
2414            });
2415        }
2416        self.mb_frame = Some(MbFrame { crosses, span });
2417        let mut installed = Vec::new();
2418        let out = self.motion_blur_phases(active, doc, t, n, span, &phase, &live, &mut installed, list, report);
2419        self.mb_frame = None;
2420        self.mb_sample = None;
2421        self.mb_acc.clear();
2422        // Pinned textures and averages are this frame's only; they go back
2423        // to the pool once the next frame is under way.
2424        for g in pinned.into_iter().chain(installed) {
2425            if let Some(p) = active.raster[g].take() {
2426                self.mb_release.push(p.tex);
2427            }
2428        }
2429        out
2430    }
2431
2432    /// The phases of a motion-blurred frame, in order. Returns the output.
2433    #[allow(clippy::too_many_arguments)]
2434    fn motion_blur_phases(
2435        &mut self,
2436        active: &mut Active,
2437        doc: &Document,
2438        t: f64,
2439        n: u32,
2440        span: f64,
2441        phase: &[u32],
2442        live: &[bool],
2443        installed: &mut Vec<usize>,
2444        list: &mut CommandList,
2445        report: &mut FrameReport,
2446    ) -> Result<Placed, RenderError> {
2447        let ng = active.plan.groups.len();
2448        let crosses = self.mb_frame.as_ref().map(|f| f.crosses.clone()).unwrap_or_default();
2449        let last = phase.iter().copied().max().unwrap_or(0);
2450        for p in 0..=last {
2451            if p % 2 == 0 {
2452                let only: Vec<bool> = (0..ng).map(|g| phase[g] == p && live[g]).collect();
2453                if only.iter().any(|&o| o) {
2454                    let pass = Pass {
2455                        only: Some(&only),
2456                        keep_bounds: p > 0,
2457                        ..Default::default()
2458                    };
2459                    self.encode_groups_masked(active, doc, t, list, report, pass)?;
2460                }
2461                continue;
2462            }
2463            // A wave: its groups per sample; those a later phase reads (and
2464            // the output) are averaged.
2465            self.mb_acc.clear();
2466            self.mb_acc.resize_with(ng, || None);
2467            for g in 0..ng {
2468                if phase[g] == p && (crosses[g] || g == ng - 1) {
2469                    self.mb_acc[g] = Some(MbAccum::default());
2470                }
2471            }
2472            // Every sample renders the wave's groups, including those not
2473            // reaching the output at that instant (a cut in the shutter): an
2474            // average is of the layer itself, and what reads it shows or
2475            // hides it in its own samples.
2476            let only: Vec<bool> = (0..ng).map(|g| phase[g] == p && live[g]).collect();
2477            for s in 0..n {
2478                let ts = t - span / 2.0 + span * (s as f64 + 0.5) / n as f64;
2479                self.mb_sample = Some((s, n, t, span));
2480                let pass = Pass {
2481                    only: Some(&only),
2482                    keep_bounds: true,
2483                    ..Default::default()
2484                };
2485                let r = self.encode_groups_masked(active, doc, ts, list, report, pass);
2486                self.mb_sample = None;
2487                r?;
2488            }
2489            for g in 0..ng {
2490                if let Some(acc) = self.mb_acc[g].take() {
2491                    self.mb_install(active, g, acc, n, t, list, installed);
2492                }
2493            }
2494        }
2495        Ok(placed_output(active, ng - 1))
2496    }
2497
2498    /// Adds the output of sampled group `gi` (as its readers see it now) to
2499    /// its average: a running sum when frame-sized, else a copy of each
2500    /// sample, summed over their union once the wave is done.
2501    fn mb_collect(&mut self, gi: usize, out: Placed, bounds: ops::Rect, doc: &Document, list: &mut CommandList) {
2502        let Some((_, n, t, _)) = self.mb_sample else {
2503            return;
2504        };
2505        let Some(mut acc) = self.mb_acc.get_mut(gi).and_then(Option::take) else {
2506            return;
2507        };
2508        acc.bounds = [
2509            acc.bounds[0].min(bounds[0]),
2510            acc.bounds[1].min(bounds[1]),
2511            acc.bounds[2].max(bounds[2]),
2512            acc.bounds[3].max(bounds[3]),
2513        ];
2514        let frame = TextureDesc {
2515            width: self.view.w,
2516            height: self.view.h,
2517            format: PixelFormat::Rgba16Float,
2518            cpu_readable: false,
2519        };
2520        // Large outputs (a frame-sized slot, particles all over) go into a
2521        // frame-sized running sum; small ones (a word) are copied and summed
2522        // over their union at the end.
2523        let d = out.tex.desc();
2524        let large = d.width as u64 * d.height as u64 * 4 >= frame.width as u64 * frame.height as u64;
2525        if acc.sum.is_some() || (large && acc.stash.is_empty()) {
2526            let first = acc.sum.is_none();
2527            let (sum, spare) = acc.sum.take().unwrap_or_else(|| {
2528                (
2529                    self.pool.lease(&self.device, frame),
2530                    self.pool.lease(&self.device, frame),
2531                )
2532            });
2533            let mut p = header(doc, t, self.view).to_vec();
2534            p.extend([out.origin[0], out.origin[1], 1.0 / n as f32, first as u8 as f32]);
2535            list.dispatch(&self.kernels.utility("k_accumulate"), &spare, &[&out.tex, &sum], &p);
2536            acc.sum = Some((spare, sum));
2537        } else {
2538            let tex = self.pool.lease(&self.device, d);
2539            let p = [t as f32, 1.0, d.width as f32, d.height as f32];
2540            list.dispatch(&self.kernels.utility("k_copy"), &tex, &[&out.tex], &p);
2541            acc.stash.push(Placed {
2542                tex,
2543                origin: out.origin,
2544                scale: out.scale,
2545            });
2546        }
2547        self.mb_acc[gi] = Some(acc);
2548    }
2549
2550    /// Makes a wave's average of group `g` its output for the rest of the
2551    /// frame only (`installed`: next frame draws the group afresh, in a
2552    /// texture of its own size).
2553    #[allow(clippy::too_many_arguments)]
2554    fn mb_install(
2555        &mut self,
2556        active: &mut Active,
2557        g: usize,
2558        acc: MbAccum,
2559        n: u32,
2560        t: f64,
2561        list: &mut CommandList,
2562        installed: &mut Vec<usize>,
2563    ) {
2564        // What the averages were summed from goes straight back to the pool
2565        // (later work in this frame writes it only after these reads).
2566        let placed = if let Some((sum, spare)) = acc.sum {
2567            self.pool.give_back(spare);
2568            for s in acc.stash {
2569                self.pool.give_back(s.tex);
2570            }
2571            Placed {
2572                tex: sum,
2573                origin: [0.0, 0.0],
2574                scale: self.view.px,
2575            }
2576        } else if !acc.stash.is_empty() {
2577            let mut u = ops::EMPTY;
2578            for s in &acc.stash {
2579                let e = extent(s);
2580                u = [u[0].min(e[0]), u[1].min(e[1]), u[2].max(e[2]), u[3].max(e[3])];
2581            }
2582            // The union on the device grid (texels of the view's size).
2583            let px = self.view.px as f64;
2584            let (x0, y0) = ((u[0] / px).floor(), (u[1] / px).floor());
2585            let bucket = |v: f64| ((v.max(1.0) as u32).div_ceil(RASTER_BUCKET) * RASTER_BUCKET).max(RASTER_BUCKET);
2586            let desc = TextureDesc {
2587                width: bucket((u[2] / px).ceil() - x0),
2588                height: bucket((u[3] / px).ceil() - y0),
2589                format: PixelFormat::Rgba16Float,
2590                cpu_readable: false,
2591            };
2592            let (mut a, mut b) = (self.pool.lease(&self.device, desc), self.pool.lease(&self.device, desc));
2593            let k = self.kernels.utility("k_accumulate");
2594            for (i, s) in acc.stash.iter().enumerate() {
2595                let p = [
2596                    t as f32,
2597                    1.0,
2598                    desc.width as f32,
2599                    desc.height as f32,
2600                    s.origin[0] / px as f32 - x0 as f32,
2601                    s.origin[1] / px as f32 - y0 as f32,
2602                    1.0 / n as f32,
2603                    (i == 0) as u8 as f32,
2604                ];
2605                list.dispatch(&k, &b, &[&s.tex, &a], &p);
2606                std::mem::swap(&mut a, &mut b);
2607            }
2608            self.pool.give_back(b);
2609            for s in acc.stash {
2610                self.pool.give_back(s.tex);
2611            }
2612            Placed {
2613                tex: a,
2614                origin: [(x0 * px) as f32, (y0 * px) as f32],
2615                scale: px as f32,
2616            }
2617        } else {
2618            // Not shown during the samples: nothing to average.
2619            return;
2620        };
2621        let borrowed = std::mem::replace(&mut active.borrowed[g], false);
2622        if let Some(old) = active.raster[g].replace(placed)
2623            && !borrowed
2624        {
2625            self.mb_release.push(old.tex);
2626        }
2627        active.drawn[g] = 0;
2628        installed.push(g);
2629        active.alias[g] = None;
2630        active.bounds[g] = acc.bounds;
2631    }
2632
2633    /// How far (px) the fastest moving layer travels over the shutter
2634    /// [t0, t1], which sets how many samples an adaptive motion blur takes.
2635    /// A vector layer is measured on its bounds as last drawn under its own
2636    /// placement and the transforms it absorbs; any other moving transform
2637    /// on the corners of what it moves (its source's bounds); both mapped
2638    /// into the frame by the transforms after them, and only while on
2639    /// screen. A transform over unbounded content is measured on the
2640    /// frame's corners, shapes and waves by their own measures. What it
2641    /// cannot measure (shaders, glyph animation) adds nothing: those take
2642    /// the format's `samples`.
2643    fn motion_extent_px(&self, plan: &Plan, doc: &Document, moving: &[bool], t0: f64, t1: f64) -> f64 {
2644        let (w, h) = (doc.format.width as f64, doc.format.height as f64);
2645        let tm = (t0 + t1) / 2.0;
2646        let n = plan.nodes.len();
2647        let affine_of = |i: usize, t: f64| {
2648            let pn = &plan.nodes[i];
2649            ops::transform_affine(&doc.nodes[&pn.id], &doc.format, local_time(pn, t).0)
2650        };
2651        // Where each node's output lands in the frame: the transforms after
2652        // it (along its last consumer), at the frame's time.
2653        let mut down: Vec<Option<ops::Affine>> = vec![None; n];
2654        if n > 0 {
2655            down[n - 1] = Some(ops::Affine::IDENTITY);
2656        }
2657        for i in (0..n).rev() {
2658            let Some(d) = down[i] else { continue };
2659            let pn = &plan.nodes[i];
2660            let d = if pn.def.name == "transform" && local_time(pn, tm).1 {
2661                d.mul(affine_of(i, tm))
2662            } else {
2663                d
2664            };
2665            for &c in &pn.inputs {
2666                down[c].get_or_insert(d);
2667            }
2668        }
2669        let down = |i: usize| down[i].unwrap_or(ops::Affine::IDENTITY);
2670        let corners = |b: ops::Rect| [(b[0], b[1]), (b[2], b[1]), (b[0], b[3]), (b[2], b[3])];
2671        let bbox = |pts: [(f64, f64); 4]| {
2672            pts.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |r, &(x, y)| {
2673                [r[0].min(x), r[1].min(y), r[2].max(x), r[3].max(y)]
2674            })
2675        };
2676        // The part of `b` (in the space `f` maps into the frame) that the
2677        // frame shows, if any.
2678        let visible = |b: ops::Rect, f: ops::Affine| -> Option<ops::Rect> {
2679            let back = f.inverse()?;
2680            let fr = bbox(corners([0.0, 0.0, w, h]).map(|(x, y)| back.apply(x, y)));
2681            let r = [b[0].max(fr[0]), b[1].max(fr[1]), b[2].min(fr[2]), b[3].min(fr[3])];
2682            (r[0] < r[2] && r[1] < r[3] && {
2683                let s = bbox(corners(r).map(|(x, y)| f.apply(x, y)));
2684                s[2] > 0.0 && s[3] > 0.0 && s[0] < w && s[1] < h
2685            })
2686            .then_some(r)
2687        };
2688        let mut chained = vec![false; n];
2689        let mut most = 0.0f64;
2690        for g in &plan.groups {
2691            let Some(rc) = g.raster.as_ref() else { continue };
2692            for &ti in &rc.transforms {
2693                chained[ti] = true;
2694            }
2695            if !moving[rc.node] && !rc.transforms.iter().any(|&ti| moving[ti]) {
2696                continue;
2697            }
2698            let rn = &plan.nodes[rc.node];
2699            let Some(b) = self.bounds.get(&rn.id) else { continue };
2700            let b = [b[0] as f64, b[1] as f64, b[2] as f64, b[3] as f64];
2701            // Its bounds are in its chain's output space: the frame, unless
2702            // transforms follow it.
2703            let d = down(*rc.transforms.last().unwrap_or(&rc.node));
2704            let Some(b) = visible(b, d) else { continue };
2705            let node = &doc.nodes[&rn.id];
2706            let full = |t: f64| {
2707                let outer = rc
2708                    .transforms
2709                    .iter()
2710                    .fold(ops::Affine::IDENTITY, |acc, &ti| affine_of(ti, t).mul(acc));
2711                outer.mul(geom::placement_affine(node, local_time(rn, t).0))
2712            };
2713            let (f0, fm, f1) = (full(t0), full(tm), full(t1));
2714            // (A layer at zero scale is nowhere: its growth shows in the
2715            // other pairs.)
2716            for (a, z) in [(f0, f1), (f0, fm), (fm, f1)] {
2717                let Some(back) = a.inverse() else { continue };
2718                let m = z.mul(back);
2719                for (x, y) in corners(b) {
2720                    let (u, v) = m.apply(x, y);
2721                    let ((x, y), (u, v)) = (d.apply(x, y), d.apply(u, v));
2722                    most = most.max((u - x).hypot(v - y));
2723                }
2724            }
2725        }
2726        // Bounds of each node's output in its own space, at the frame's time.
2727        let mut local = vec![ops::EMPTY; n];
2728        for (i, pn) in plan.nodes.iter().enumerate() {
2729            let ins: Vec<ops::Rect> = pn.inputs.iter().map(|&c| local[c]).collect();
2730            let (lt, on) = local_time(pn, tm);
2731            local[i] = if on {
2732                ops::bounds(pn.def, &doc.nodes[&pn.id], &doc.format, lt, &ins, None)
2733            } else {
2734                ops::passthrough(pn.def, ins.len())
2735                    .map(|k| ins[k])
2736                    .unwrap_or(ops::EMPTY)
2737            };
2738        }
2739        for (i, pn) in plan.nodes.iter().enumerate() {
2740            if !moving[i] || chained[i] || !matches!(pn.def.name, "transform" | "shape" | "wave") {
2741                continue;
2742            }
2743            let (l0, lm, l1) = (local_time(pn, t0).0, local_time(pn, tm).0, local_time(pn, t1).0);
2744            let node = &doc.nodes[&pn.id];
2745            let b = pn.inputs.first().map(|&s| local[s]).unwrap_or(ops::UNBOUNDED);
2746            if pn.def.name == "transform" && b[0] > -1e8 && b[2] < 1e8 {
2747                if b[0] > b[2] || b[1] > b[3] {
2748                    continue;
2749                }
2750                // What it moves, where the frame shows it, at each time.
2751                let d = down(i);
2752                let at = |t: f64| d.mul(affine_of(i, t));
2753                let (f0, fm, f1) = (at(t0), at(tm), at(t1));
2754                let Some(b) = visible(b, fm) else { continue };
2755                for (a, z) in [(f0, f1), (f0, fm), (fm, f1)] {
2756                    for (x, y) in corners(b) {
2757                        let ((x0, y0), (x1, y1)) = (a.apply(x, y), z.apply(x, y));
2758                        most = most.max((x1 - x0).hypot(y1 - y0));
2759                    }
2760                }
2761                continue;
2762            }
2763            let f = |a: f64, b: f64| match pn.def.name {
2764                "transform" => transform_motion_px(node, &doc.format, a, b),
2765                "shape" => ops::shape_motion_px(node, &doc.format, a, b),
2766                _ => ops::wave_motion_px(node, a, b),
2767            };
2768            most = most.max(f(l0, l1).max(f(l0, lm)).max(f(lm, l1)));
2769        }
2770        most
2771    }
2772
2773    /// Plan nodes whose image moves during [t0, t1], which motion blur
2774    /// samples: params animating to different values, appearing or
2775    /// vanishing, particles and simulations. Time-driven content holds at
2776    /// the frame's time instead (footage and image-sequence frames, shader
2777    /// clocks: a camera already blurred its footage, and flicker or noise
2778    /// would average away), and so do changes that move nothing on screen
2779    /// (colors, opacities, grades; a transform moving content less than
2780    /// half a pixel; a 3D scene moving less than 0.75 px). Overlay textures
2781    /// (grain) count as still.
2782    fn moving_nodes(&self, plan: &Plan, doc: &Document, t0: f64, t1: f64) -> Vec<bool> {
2783        let mut moving = vec![false; plan.nodes.len()];
2784        for (i, pn) in plan.nodes.iter().enumerate() {
2785            if pn.is_static || plan.overlay[i] {
2786                continue;
2787            }
2788            // Simulations step on the first sample (as seeks replay them),
2789            // so they stay with the sampled groups.
2790            if pn.def.form == ops::Form::Sim {
2791                moving[i] = true;
2792                continue;
2793            }
2794            let (l0, on0) = local_time(pn, t0);
2795            let (l1, on1) = local_time(pn, t1);
2796            if on0 != on1 {
2797                moving[i] = true;
2798                continue;
2799            }
2800            if !on0 {
2801                continue;
2802            }
2803            // A particle system blurs itself along its particles' paths
2804            // (drawn once); a swarm is sampled.
2805            if pn.def.name == "swarm" {
2806                moving[i] = true;
2807                continue;
2808            }
2809            if pn.def.name == "particles" {
2810                continue;
2811            }
2812            let node = &doc.nodes[&pn.id];
2813            // Also the middle of the shutter: what turns back within it (a
2814            // key at the frame's time) ends where it began.
2815            let lm = local_time(pn, (t0 + t1) / 2.0).0;
2816            let varies = |p: &ultrafast_graph::Param| {
2817                p.is_animated() && {
2818                    let v0 = p.eval(l0);
2819                    v0 != p.eval(l1) || v0 != p.eval(lm)
2820                }
2821            };
2822            // A shader is an effect: held at the frame's time (its clock and
2823            // its u values: flicker, pulses, glitches stay crisp) unless it
2824            // asks to be sampled.
2825            if pn.def.name == "shader" {
2826                moving[i] =
2827                    ops::samples_motion(node) && (ops::time_varying(pn.def, node) || node.params.values().any(varies));
2828                continue;
2829            }
2830            // A counter's number or decoding text changes glyphs, not position.
2831            let changed: Vec<&str> = node
2832                .params
2833                .iter()
2834                .filter(|(k, p)| {
2835                    *k != "number" && *k != "scramble" && !schema::moves_nothing(pn.def.name, k) && varies(p)
2836                })
2837                .map(|(k, _)| k.as_str())
2838                .collect();
2839            // Moving less than 1.5 px over the shutter blurs nothing anyone
2840            // can see (a 3D scene renders once per 1.5 px too).
2841            // The most it moves between the shutter's ends and its middle.
2842            let most = |f: &dyn Fn(f64, f64) -> f64| f(l0, l1).max(f(l0, lm)).max(f(lm, l1));
2843            moving[i] = match pn.def.name {
2844                _ if changed.is_empty() => false,
2845                "transform" => most(&|a, b| transform_motion_px(node, &doc.format, a, b)) >= 1.5,
2846                "shape" if changed.iter().all(|k| ops::SHAPE_PLACEMENT.contains(k)) => {
2847                    most(&|a, b| ops::shape_motion_px(node, &doc.format, a, b)) >= 1.5
2848                }
2849                "wave" if changed.iter().all(|k| matches!(*k, "amplitude" | "phase")) => {
2850                    most(&|a, b| ops::wave_motion_px(node, a, b)) >= 1.5
2851                }
2852                _ => true,
2853            };
2854        }
2855        for g in &plan.groups {
2856            if g.kind == GroupKind::Render3D
2857                && g.nodes.iter().any(|&m| moving[m])
2858                && self.scene_motion_px(plan, g, doc, t0, t1) < 0.75
2859            {
2860                for &m in &g.nodes {
2861                    moving[m] = false;
2862                }
2863            }
2864        }
2865        // A simulation steps on the first sample, reading what it reads at
2866        // that instant (as a seek's catch-up does): that moves with it.
2867        for (gi, g) in plan.groups.iter().enumerate() {
2868            if g.kind == GroupKind::Sim {
2869                for (i, pn) in plan.nodes.iter().enumerate() {
2870                    if !pn.is_static && plan::bit(&plan.group_up[gi], i) {
2871                        moving[i] = true;
2872                    }
2873                }
2874            }
2875        }
2876        moving
2877    }
2878
2879    /// Encodes every group; returns the placed output of the last one.
2880    fn encode_groups(
2881        &mut self,
2882        active: &mut Active,
2883        doc: &Document,
2884        t: f64,
2885        list: &mut CommandList,
2886        report: &mut FrameReport,
2887    ) -> Result<Placed, RenderError> {
2888        self.encode_groups_masked(active, doc, t, list, report, Pass::default())
2889    }
2890
2891    /// Like [`Renderer::encode_groups`], running the groups `pass` picks
2892    /// and returning its target's output.
2893    fn encode_groups_masked(
2894        &mut self,
2895        active: &mut Active,
2896        doc: &Document,
2897        t: f64,
2898        list: &mut CommandList,
2899        report: &mut FrameReport,
2900        pass: Pass,
2901    ) -> Result<Placed, RenderError> {
2902        let Pass {
2903            only,
2904            target,
2905            changed,
2906            keep_bounds,
2907        } = pass;
2908        let Active {
2909            plan,
2910            slots,
2911            resident,
2912            slot_used,
2913            slot_groups,
2914            slot_desc,
2915            view: _,
2916            group_used,
2917            cache,
2918            raster,
2919            drawn,
2920            alias,
2921            borrowed,
2922            bounds,
2923            low_readers,
2924        } = active;
2925        self.ran.clear();
2926        self.ran.resize(plan.groups.len(), false);
2927        for &g in changed {
2928            self.ran[g] = true;
2929            alias[g] = None;
2930        }
2931        // Work that cannot reach the output at this time (layers outside their
2932        // windows, and everything only they use) is skipped.
2933        let live = match only {
2934            Some(m) => m.to_vec(),
2935            None => live_groups(plan, t),
2936        };
2937        // Live groups' slots get textures before anything reads them.
2938        for (gi, g) in plan.groups.iter().enumerate() {
2939            if !live[gi] {
2940                continue;
2941            }
2942            group_used[gi] = self.frame_no;
2943            let s = g.output;
2944            if s >= slots.len() {
2945                continue;
2946            }
2947            slot_used[s] = self.frame_no;
2948            if !resident[s] {
2949                slots[s] = self.pool.lease(&self.device, *slot_desc);
2950                resident[s] = true;
2951                for &w in &slot_groups[s] {
2952                    cache[w] = None;
2953                }
2954            }
2955        }
2956        let px = self.view.px;
2957        let placed_of = |raster: &Vec<Option<Placed>>, alias: &Vec<Option<usize>>, mut gi: usize| -> Placed {
2958            while let Some(src) = alias[gi] {
2959                gi = src;
2960            }
2961            match &raster[gi] {
2962                Some(p) => p.clone(),
2963                None => Placed {
2964                    tex: slots[plan.groups[gi].output].clone(),
2965                    origin: [0.0, 0.0],
2966                    scale: px,
2967                },
2968            }
2969        };
2970        let last = target.unwrap_or(plan.groups.len() - 1);
2971
2972        let frame_rect = [0.0, 0.0, doc.format.width as f64, doc.format.height as f64];
2973        // Where each group's output can be non-transparent (frame px).
2974        if !keep_bounds || bounds.len() != plan.groups.len() {
2975            bounds.clear();
2976            bounds.resize(plan.groups.len(), ops::UNBOUNDED);
2977        }
2978        let content = bounds;
2979        let collect = self.mb_sample.is_some() && !self.mb_acc.is_empty();
2980        for (gi, g) in plan.groups.iter().enumerate() {
2981            // Motion blur: the group before, as its readers see it, joins
2982            // its average (before anything later can write its slot).
2983            if collect && gi > 0 && live[gi - 1] && self.mb_acc[gi - 1].is_some() {
2984                let out = placed_of(raster, alias, gi - 1);
2985                self.mb_collect(gi - 1, out, content[gi - 1], doc, list);
2986            }
2987            if !live[gi] {
2988                report.groups_skipped += 1;
2989                continue;
2990            }
2991            content[gi] = ops::UNBOUNDED;
2992            // Resolve input textures (placed) and resource sizes.
2993            let mut inputs: Vec<Placed> = Vec::with_capacity(g.textures.len());
2994            let mut res_info: HashMap<&str, ResourceInfo> = HashMap::new();
2995            for ts in &g.textures {
2996                match ts {
2997                    TexSource::Group(s) => inputs.push(placed_of(raster, alias, *s)),
2998                    TexSource::Resource(src) => {
2999                        let user = g.nodes.iter().map(|&n| &plan.nodes[n]).find(|n| n.variant == *src);
3000                        // Under motion blur, footage and image sequences hold
3001                        // the frame's own picture across the shutter.
3002                        let timed = src.starts_with("video:") || src.contains("{frame");
3003                        let at = match self.mb_sample {
3004                            Some((_, _, tc, _)) if timed => tc,
3005                            _ => t,
3006                        };
3007                        let (user_id, user_t, user_on) = match user {
3008                            Some(n) => (n.id.clone(), local_time(n, at).0, local_time(n, t).1),
3009                            None => (String::new(), at, true),
3010                        };
3011                        // A media node outside its window in a fused group
3012                        // that is live for its other layers: nothing samples
3013                        // it, so do not decode (or seek) it.
3014                        if !user_on && (src.starts_with("video:") || src.contains("{frame")) {
3015                            inputs.push(Placed {
3016                                tex: self.placeholder.clone(),
3017                                origin: [0.0, 0.0],
3018                                scale: 1.0,
3019                            });
3020                            continue;
3021                        }
3022                        let (tex, info) = self.resource(src, &user_id, doc, user_t, list);
3023                        if let Some(i) = info {
3024                            res_info.insert(src.as_str(), i);
3025                        }
3026                        inputs.push(Placed {
3027                            tex,
3028                            origin: [0.0, 0.0],
3029                            scale: 1.0,
3030                        });
3031                    }
3032                }
3033            }
3034
3035            // Pack params: header, then the group's layout (node blocks,
3036            // literal values, padding, texture origins), then the blocks of
3037            // the run layers showing now.
3038            self.scratch.clear();
3039            self.scratch.extend(header(doc, t, self.view));
3040            let mut run_headers: Vec<(usize, usize)> = Vec::new();
3041            for slot in &g.params {
3042                match slot {
3043                    plan::ParamSlot::Node(ni) => {
3044                        let pn = &plan.nodes[*ni];
3045                        let info = if ops::uses_resource(pn.def) {
3046                            res_info.get(pn.variant.as_str()).copied()
3047                        } else {
3048                            None
3049                        };
3050                        let (lt, on) = local_time(pn, t);
3051                        // A static group is time-invariant: pack it at one
3052                        // fixed time so its params compare equal from frame
3053                        // to frame (a shader that never reads time() still
3054                        // receives it).
3055                        let lt = if g.is_static { 0.0 } else { lt };
3056                        ops::pack(
3057                            pn.def,
3058                            &pn.id,
3059                            &doc.nodes[&pn.id],
3060                            &doc.format,
3061                            lt,
3062                            info,
3063                            &mut self.scratch,
3064                        )?;
3065                        self.hold_shader_clock(pn, &doc.nodes[&pn.id], g.is_static);
3066                        if pn.gated {
3067                            self.scratch.push(on as u8 as f32);
3068                        }
3069                        if ops::guarded(pn.def) {
3070                            let b = subtree_bounds(plan, g, pn.inputs[0], doc, t, &inputs, &res_info, &content);
3071                            self.scratch.extend(b.map(|v| v as f32));
3072                        }
3073                        if let Some(tables) = &pn.tables {
3074                            self.scratch.extend_from_slice(tables);
3075                        }
3076                    }
3077                    plan::ParamSlot::Run(r) => {
3078                        run_headers.push((*r, self.scratch.len()));
3079                        self.scratch.extend([0.0, 0.0]);
3080                    }
3081                    plan::ParamSlot::Value(v) => self.scratch.push(*v),
3082                    plan::ParamSlot::Pad(n) => self.scratch.extend(std::iter::repeat_n(0.0, *n)),
3083                    plan::ParamSlot::Origins => {
3084                        for p in &inputs {
3085                            self.scratch.extend(p.origin);
3086                            self.scratch.push(p.scale);
3087                        }
3088                    }
3089                }
3090            }
3091            for (r, at) in run_headers {
3092                let run = &g.runs[r];
3093                let start = self.scratch.len();
3094                let mut shown = 0;
3095                for (kind, ci, layer) in &run.layers {
3096                    let pn = &plan.nodes[*ci];
3097                    let (lt, on) = local_time(pn, t);
3098                    // Out of its window, or nothing to lay: the background
3099                    // shows through, as it would without the layer.
3100                    if !on {
3101                        continue;
3102                    }
3103                    let b = subtree_bounds(plan, g, pn.inputs[0], doc, t, &inputs, &res_info, &content);
3104                    if b[0] >= b[2] || b[1] >= b[3] {
3105                        continue;
3106                    }
3107                    let lt = if g.is_static { 0.0 } else { lt };
3108                    let block = self.scratch.len();
3109                    self.scratch.push(*kind as f32);
3110                    ops::pack(
3111                        pn.def,
3112                        &pn.id,
3113                        &doc.nodes[&pn.id],
3114                        &doc.format,
3115                        lt,
3116                        None,
3117                        &mut self.scratch,
3118                    )?;
3119                    self.hold_shader_clock(pn, &doc.nodes[&pn.id], g.is_static);
3120                    self.scratch.extend(b.map(|v| v as f32));
3121                    match layer {
3122                        codegen::LayerRef::Texture(binding) => {
3123                            let d = inputs[*binding].tex.desc();
3124                            self.scratch.extend([*binding as f32, d.width as f32, d.height as f32]);
3125                        }
3126                        codegen::LayerRef::Gen(gi) => {
3127                            let gn = &plan.nodes[*gi];
3128                            let (glt, _) = local_time(gn, t);
3129                            let glt = if g.is_static { 0.0 } else { glt };
3130                            ops::pack(
3131                                gn.def,
3132                                &gn.id,
3133                                &doc.nodes[&gn.id],
3134                                &doc.format,
3135                                glt,
3136                                None,
3137                                &mut self.scratch,
3138                            )?;
3139                            self.hold_shader_clock(gn, &doc.nodes[&gn.id], g.is_static);
3140                        }
3141                    }
3142                    self.scratch.resize(block + run.stride, 0.0);
3143                    shown += 1;
3144                }
3145                self.scratch[at] = start as f32;
3146                self.scratch[at + 1] = shown as f32;
3147            }
3148            match g.kind {
3149                GroupKind::Fused => {
3150                    content[gi] = intersect(
3151                        subtree_bounds(plan, g, g.root, doc, t, &inputs, &res_info, &content),
3152                        frame_rect,
3153                    )
3154                }
3155                GroupKind::Render3D | GroupKind::Sim => content[gi] = frame_rect,
3156                _ => {}
3157            }
3158
3159            // A fused group that at this time only passes an input through
3160            // (its layers are out of their windows, or what it composites
3161            // over is empty here) shows that input as it is.
3162            alias[gi] = None;
3163            if g.kind == GroupKind::Fused && gi != last && !self.no_skip {
3164                let crossing = self.mb_frame.as_ref().is_some_and(|f| f.crosses[gi]);
3165                alias[gi] = passthrough_group(plan, g, g.root, doc, t, &inputs, &res_info, &content).filter(|&src| {
3166                    // Only while nothing reuses the source's slot before the
3167                    // last group that reads this one (with motion blur, a
3168                    // later phase reads it: only a texture of its own).
3169                    let mut f = src;
3170                    while let Some(n) = alias[f] {
3171                        f = n;
3172                    }
3173                    if let Some(p) = &raster[f] {
3174                        // A blur kept at reduced resolution is only for its own
3175                        // readers' kernels.
3176                        return p.scale == px;
3177                    }
3178                    if crossing {
3179                        return false;
3180                    }
3181                    let slot = plan.groups[f].output;
3182                    let last_use = (gi + 1..plan.groups.len())
3183                        .filter(|&k| plan.groups[k].textures.contains(&TexSource::Group(gi)))
3184                        .max()
3185                        .unwrap_or(gi);
3186                    !(gi + 1..=last_use).any(|k| plan.groups[k].output == slot)
3187                });
3188                if let Some(src) = alias[gi] {
3189                    if std::env::var_os("ULTRAFAST_DEBUG_ALIAS").is_some() {
3190                        eprintln!("t={t:.3} g{gi} -> g{src} (last g{last})");
3191                    }
3192                    content[gi] = content[src];
3193                    self.ran[gi] = self.ran[src];
3194                    cache[gi] = None;
3195                    report.groups_cached += 1;
3196                    continue;
3197                }
3198            }
3199
3200            // Raster geometry identity: node params, absorbed transforms, time.
3201            // A raster chain shows while its raster node is active; a timed
3202            // transform outside its window passes it through unmoved.
3203            let raster_geo = g.raster.as_ref().map(|rc| {
3204                // Built on the device grid: the view's density times the
3205                // transforms the raster absorbed (curves flattened and glyphs
3206                // drawn for that size).
3207                let d = 1.0 / px as f64;
3208                let outer = ops::Affine::scale(d, d).mul(absorbed(plan, doc, &rc.transforms, t));
3209                let rn = &plan.nodes[rc.node];
3210                let (lt, on) = local_time(rn, t);
3211                let key = if on {
3212                    geom::geometry_key(&doc.nodes[&rn.id], lt, &outer)
3213                } else {
3214                    0
3215                };
3216                (rc.node, outer, key, lt, on)
3217            });
3218
3219            // Static groups rerun only when params, inputs or upstream changed.
3220            // The time/frame header is excluded: static means time-invariant.
3221            // (Only static groups own their output slot across frames, so
3222            // only they can be reused this way.)
3223            if g.is_static {
3224                let mut ids: Vec<usize> = inputs.iter().map(|p| p.tex.id()).collect();
3225                if let Some((_, _, key, _, _)) = raster_geo {
3226                    ids.push(key as usize);
3227                }
3228                if g.kind == GroupKind::Render3D {
3229                    ids.push(scene_key(plan, g, doc, t) as usize);
3230                }
3231                let upstream_ran = g
3232                    .textures
3233                    .iter()
3234                    .any(|ts| matches!(ts, TexSource::Group(s) if self.ran[*s]));
3235                if std::env::var_os("ULTRAFAST_DEBUG_CACHE").is_some() {
3236                    let why = match &cache[gi] {
3237                        _ if upstream_ran => {
3238                            let ups: Vec<usize> = g
3239                                .textures
3240                                .iter()
3241                                .filter_map(|ts| match ts {
3242                                    TexSource::Group(s) if self.ran[*s] => Some(*s),
3243                                    _ => None,
3244                                })
3245                                .collect();
3246                            format!("upstream ran: {ups:?}")
3247                        }
3248                        None => "first run".to_string(),
3249                        Some((p, _)) if p[..] != self.scratch[2..] => {
3250                            let k = p.iter().zip(&self.scratch[2..]).position(|(a, b)| a != b);
3251                            format!("params differ at {k:?} (len {} vs {})", p.len(), self.scratch.len() - 2)
3252                        }
3253                        Some((_, i)) if *i != ids => format!("inputs differ: {i:?} vs {ids:?}"),
3254                        _ => String::new(),
3255                    };
3256                    if !why.is_empty() {
3257                        eprintln!("t={t:.3} g{gi} reruns: {why}");
3258                    }
3259                }
3260                if !upstream_ran
3261                    && let Some((p, i)) = &cache[gi]
3262                    && p[..] == self.scratch[2..]
3263                    && *i == ids
3264                {
3265                    report.groups_cached += 1;
3266                    if matches!(g.kind, GroupKind::Raster | GroupKind::Blur) {
3267                        content[gi] = extent(&placed_of(raster, alias, gi));
3268                    }
3269                    continue;
3270                }
3271                cache[gi] = Some((self.scratch[2..].to_vec(), ids));
3272            }
3273
3274            let mut in_tex: Vec<&Texture> = inputs.iter().map(|p| &p.tex).collect();
3275            if g.pad_textures {
3276                in_tex.resize(plan::MAX_TEXTURES, &self.placeholder);
3277            }
3278            match g.kind {
3279                GroupKind::Raster => {
3280                    let (rn, outer, key, lt, on) = raster_geo.expect("raster group");
3281                    let framed = plan.framed[gi] && !self.no_framed;
3282                    // The same geometry in the same paint as last time: its
3283                    // texture still holds it (text that has settled, shapes
3284                    // between keys, motion-blur samples of still layers).
3285                    let paint = {
3286                        use std::hash::{Hash, Hasher};
3287                        let mut h = std::collections::hash_map::DefaultHasher::new();
3288                        (key, on, framed).hash(&mut h);
3289                        for v in &self.scratch[4..9] {
3290                            v.to_bits().hash(&mut h);
3291                        }
3292                        h.finish() | 1
3293                    };
3294                    if drawn[gi] == paint
3295                        && !self.no_skip
3296                        && let Some(p) = &raster[gi]
3297                    {
3298                        content[gi] = extent(p);
3299                        report.groups_cached += 1;
3300                        continue;
3301                    }
3302                    drawn[gi] = paint;
3303                    let geo = if on {
3304                        self.geometry(&plan.nodes[rn].id, doc, lt, outer, key)?
3305                    } else {
3306                        Arc::new(geom::Geometry::default())
3307                    };
3308                    let prev = raster[gi].take();
3309                    // Color glyphs keep their own colors and fade with the
3310                    // node's opacity only.
3311                    let opacity = doc.nodes[&plan.nodes[rn].id]
3312                        .params
3313                        .get("opacity")
3314                        .and_then(|p| p.eval(lt))
3315                        .and_then(|v| v.first().copied())
3316                        .unwrap_or(1.0)
3317                        .clamp(0.0, 1.0) as f32;
3318                    let placed = self.encode_raster(&geo, prev, opacity, framed, doc, t, list);
3319                    content[gi] = extent(&placed);
3320                    raster[gi] = Some(placed);
3321                    report.kernels_run += 2;
3322                }
3323                GroupKind::Particles => {
3324                    let prev = raster[gi].take();
3325                    let sprite = inputs.first().cloned();
3326                    let placed = self.encode_particles(plan, g, sprite, prev, doc, t, list)?;
3327                    content[gi] = extent(&placed);
3328                    raster[gi] = Some(placed);
3329                    report.kernels_run += 1;
3330                }
3331                GroupKind::Render3D => {
3332                    let out = slots[g.output].clone();
3333                    // Motion blur: a 3D scene is rendered only as often as
3334                    // it moves (about every 1.5 px on screen during the
3335                    // shutter); samples in between reuse the last render.
3336                    let plan_mb = self.mb_sample.filter(|_| !self.mb_full).map(|(s, n, tc, span)| {
3337                        let m = self.scene_motion_px(plan, g, doc, tc - span / 2.0, tc + span / 2.0) / px;
3338                        if s == 0 && std::env::var("ULTRAFAST_DEBUG_MB").is_ok() {
3339                            eprintln!("t={tc:.2} group {gi}: 3D moves {m:.2} px over the shutter");
3340                        }
3341                        let k = if m.is_finite() {
3342                            ((m / 1.5).ceil() as u32).clamp(1, n)
3343                        } else {
3344                            n
3345                        };
3346                        let bucket = |s: u32| s * k / n;
3347                        let first = s == 0 || bucket(s) != bucket(s - 1);
3348                        let at = tc - span / 2.0 + span * (bucket(s) as f64 + 0.5) / k as f64;
3349                        (first, at)
3350                    });
3351                    match plan_mb {
3352                        Some((false, _)) => report.groups_cached += 1,
3353                        Some((true, at)) => {
3354                            self.encode_render3d(plan, g, &inputs, &out, doc, at, list)?;
3355                            report.kernels_run += 1;
3356                        }
3357                        None => {
3358                            self.encode_render3d(plan, g, &inputs, &out, doc, t, list)?;
3359                            report.kernels_run += 1;
3360                        }
3361                    }
3362                }
3363                GroupKind::Sim => {
3364                    let out = slots[g.output].clone();
3365                    self.encode_sim(plan, gi, &inputs, &out, doc, t, list, report)?;
3366                    report.kernels_run += 1;
3367                }
3368                GroupKind::Blur => {
3369                    // Blur only the region the source covers (plus the blur's
3370                    // reach), at reduced resolution for large radii.
3371                    let src = inputs[0].clone();
3372                    let src_bounds = match g.textures[0] {
3373                        TexSource::Group(s) => intersect(extent(&src), content[s]),
3374                        _ => extent(&src),
3375                    };
3376                    // A texture this group borrowed is not its own to reuse.
3377                    let prev = raster[gi]
3378                        .take()
3379                        .filter(|_| !std::mem::replace(&mut borrowed[gi], false));
3380                    if local_time(&plan.nodes[g.root], t).1 {
3381                        // Kept at its reduced resolution when every reader can
3382                        // sample it there and has its kernel (not while motion
3383                        // blur averages it, nor for a fallback reader).
3384                        let keep_low = self.mb_sample.is_none()
3385                            && low_readers[gi].as_ref().is_some_and(|rs| {
3386                                rs.iter().all(|&c| {
3387                                    matches!(self.kernels.get(&plan.groups[c].key), Some(KernelState::Ready(_)))
3388                                })
3389                            });
3390                        let (placed, b) =
3391                            self.encode_blur(&src, src_bounds, self.scratch[4], prev, keep_low, doc, t, list);
3392                        raster[gi] = Some(placed);
3393                        content[gi] = b;
3394                        report.kernels_run += 2;
3395                    } else {
3396                        // Inactive: the source passes through untouched. Shown
3397                        // as it is when nothing writes its slot before the last
3398                        // reader of this group; otherwise copied, since a
3399                        // later group would reuse that slot first.
3400                        let slot = slots.iter().position(|s| s.id() == src.tex.id());
3401                        let last_use = (gi + 1..plan.groups.len())
3402                            .filter(|&k| plan.groups[k].textures.contains(&TexSource::Group(gi)))
3403                            .max()
3404                            .unwrap_or(gi);
3405                        let crossing = self.mb_frame.as_ref().is_some_and(|f| f.crosses[gi]);
3406                        let clobbered =
3407                            slot.is_some_and(|sl| crossing || (gi + 1..=last_use).any(|k| plan.groups[k].output == sl));
3408                        if clobbered {
3409                            let desc = src.tex.desc();
3410                            let tex = match prev {
3411                                Some(p) if p.tex.desc() == desc => p.tex,
3412                                other => {
3413                                    if let Some(p) = other {
3414                                        self.pool.give_back(p.tex);
3415                                    }
3416                                    self.pool.lease(&self.device, desc)
3417                                }
3418                            };
3419                            list.dispatch(
3420                                &self.kernels.utility("k_copy"),
3421                                &tex,
3422                                &[&src.tex],
3423                                &header(doc, t, self.view),
3424                            );
3425                            raster[gi] = Some(Placed {
3426                                tex,
3427                                origin: src.origin,
3428                                scale: src.scale,
3429                            });
3430                        } else {
3431                            if let Some(p) = prev {
3432                                self.pool.give_back(p.tex);
3433                            }
3434                            raster[gi] = Some(src);
3435                            borrowed[gi] = true;
3436                        }
3437                        content[gi] = src_bounds;
3438                    }
3439                }
3440                GroupKind::Fused => {
3441                    // A fused group pinned for this frame (motion blur) renders
3442                    // into its own texture instead of its shared slot.
3443                    let out = &match &raster[gi] {
3444                        Some(p) => p.tex.clone(),
3445                        None => slots[g.output].clone(),
3446                    };
3447                    let op_by_op = || {
3448                        g.nodes
3449                            .iter()
3450                            .all(|&n| self.kernels.tier0(plan.nodes[n].def.func).is_some())
3451                    };
3452                    let state = match self.mode {
3453                        Mode::Exact if self.wait_fused || !op_by_op() => self.kernels.wait(&g.key),
3454                        _ => self.kernels.get(&g.key).unwrap_or(KernelState::Pending),
3455                    };
3456                    let scale = ops::render_scale(&doc.nodes[&plan.nodes[g.root].id]);
3457                    match state {
3458                        KernelState::Ready(k) if scale.is_some() => {
3459                            // Reduced resolution: render coarse texels, then
3460                            // upscale into the slot.
3461                            let r = scale.unwrap() as f32;
3462                            let v = self.view;
3463                            let low = TextureDesc {
3464                                width: ((v.w as f32 * r).ceil() as u32).max(1),
3465                                height: ((v.h as f32 * r).ceil() as u32).max(1),
3466                                format: PixelFormat::Rgba16Float,
3467                                cpu_readable: false,
3468                            };
3469                            let tmp = self.pool.lease(&self.device, low);
3470                            self.scratch[1] = v.px / r;
3471                            list.dispatch(&k, &tmp, &in_tex, &self.scratch);
3472                            self.scratch[1] = v.px;
3473                            let mut p = header(doc, t, v).to_vec();
3474                            p.extend([v.px, 0.0, 0.0, 0.0, 0.0, v.px / r, 1.0]);
3475                            list.dispatch(&self.kernels.utility("k_resample"), out, &[&tmp], &p);
3476                            self.pool.give_back(tmp);
3477                            report.kernels_run += 2;
3478                        }
3479                        KernelState::Ready(k) => {
3480                            list.dispatch(&k, out, &in_tex, &self.scratch);
3481                            report.kernels_run += 1;
3482                        }
3483                        KernelState::Pending => {
3484                            self.encode_fallback(plan, gi, &inputs, out, doc, t, list, &res_info)?;
3485                            report.groups_fallback += 1;
3486                            // A fallback result is not final: never cache it.
3487                            cache[gi] = None;
3488                        }
3489                        KernelState::Failed(e) => {
3490                            self.diagnose(&plan.nodes[g.root].id.clone(), e);
3491                            list.dispatch(&self.kernels.utility("k_clear"), out, &[], &header(doc, t, self.view));
3492                        }
3493                    }
3494                }
3495            }
3496            self.ran[gi] = true;
3497            if self.profile.is_some() {
3498                let ids: Vec<&str> = g.nodes.iter().map(|&n| plan.nodes[n].id.as_str()).collect();
3499                let names = if ids.len() > 4 {
3500                    format!("{} +{}", ids[..3].join(" "), ids.len() - 3)
3501                } else {
3502                    ids.join(" ")
3503                };
3504                let label = format!("g{gi} {:?} [{names}]", g.kind);
3505                let sub = std::mem::replace(list, self.device.begin()).submit();
3506                // Timed now: a backend may reuse the submission's slot (and
3507                // its timestamps) before a later read.
3508                let ms = sub.wait()?.gpu_ms;
3509                if let Some(p) = &mut self.profile {
3510                    let e = p.totals.entry(label).or_insert((0.0, 0));
3511                    e.0 += ms;
3512                    e.1 += 1;
3513                }
3514            }
3515        }
3516        let gl = plan.groups.len();
3517        if collect && gl > 0 && live[gl - 1] && self.mb_acc[gl - 1].is_some() {
3518            let out = placed_of(raster, alias, gl - 1);
3519            self.mb_collect(gl - 1, out, content[gl - 1], doc, list);
3520        }
3521        Ok(placed_of(raster, alias, last))
3522    }
3523
3524    /// Under motion blur a shader's clock reads the frame's time, not the
3525    /// sample's (its last packed value, right after `ops::pack`), unless the
3526    /// shader asks to be sampled.
3527    fn hold_shader_clock(&mut self, pn: &plan::PlanNode, node: &ultrafast_graph::Node, is_static: bool) {
3528        if pn.def.name == "shader"
3529            && !ops::samples_motion(node)
3530            && let Some((_, _, tc, _)) = self.mb_sample
3531            && let Some(v) = self.scratch.last_mut()
3532        {
3533            *v = if is_static { 0.0 } else { local_time(pn, tc).0 as f32 };
3534        }
3535    }
3536
3537    /// Largest on-screen movement (frame px) of any mesh's bounds between
3538    /// t0 and t1; infinite when it cannot tell (meshes not built yet,
3539    /// visibility changing, corners behind the camera).
3540    fn scene_motion_px(&self, plan: &Plan, g: &plan::Group, doc: &Document, t0: f64, t1: f64) -> f32 {
3541        use scene3d::{Mat4, Params};
3542        let Some(three) = self.three.as_ref() else {
3543            return f32::INFINITY;
3544        };
3545        let (fw, fh) = (doc.format.width as f32, doc.format.height as f32);
3546        let project = |t: f64| -> Option<Vec<[f32; 2]>> {
3547            let (mut eye, mut target, mut up) = ([0.0f32, 0.0, 5.0], [0.0f32, 0.0, 0.0], [0.0f32, 1.0, 0.0]);
3548            let (mut fov, mut near, mut far) = (45.0f32, 0.1f32, 1000.0f32);
3549            for &o in &g.nodes[..g.nodes.len() - 1] {
3550                let pn = &plan.nodes[o];
3551                let (lt, on) = local_time(pn, t);
3552                if pn.def.name != "camera" || !on {
3553                    continue;
3554                }
3555                let node = &doc.nodes[&pn.id];
3556                let p = Params { node, t: lt };
3557                target = p.vec("target", target);
3558                up = p.vec("up", up);
3559                fov = p.num("fov", fov);
3560                near = p.num("near", near);
3561                far = p.num("far", far);
3562                eye = if pn_has(node, "orbit") {
3563                    let [az, el, dist] = p.vec("orbit", [0.0, 0.0, 5.0]);
3564                    let (az, el) = (az.to_radians(), el.to_radians());
3565                    [
3566                        target[0] + dist * el.cos() * az.sin(),
3567                        target[1] + dist * el.sin(),
3568                        target[2] + dist * el.cos() * az.cos(),
3569                    ]
3570                } else {
3571                    p.vec("position", eye)
3572                };
3573            }
3574            let vp = Mat4::perspective(fov, fw / fh.max(1.0), near, far).mul(&Mat4::look_at(eye, target, up));
3575            let mut pts = Vec::new();
3576            for &o in &g.nodes[..g.nodes.len() - 1] {
3577                let pn = &plan.nodes[o];
3578                if pn.def.name != "mesh" {
3579                    continue;
3580                }
3581                let (lt, on) = local_time(pn, t);
3582                if !on {
3583                    // Appearing or vanishing within the shutter is motion.
3584                    pts.push([-1e6, -1e6]);
3585                    continue;
3586                }
3587                let node = &doc.nodes[&pn.id];
3588                let [lo, hi] = three.meshes.get(&scene3d::mesh_key(node))?.3;
3589                let m = Params { node, t: lt }.model().0;
3590                let v = &vp.0;
3591                for corner in 0..8 {
3592                    let c = [
3593                        if corner & 1 == 0 { lo[0] } else { hi[0] },
3594                        if corner & 2 == 0 { lo[1] } else { hi[1] },
3595                        if corner & 4 == 0 { lo[2] } else { hi[2] },
3596                    ];
3597                    let w = [
3598                        m[0] * c[0] + m[1] * c[1] + m[2] * c[2] + m[3],
3599                        m[4] * c[0] + m[5] * c[1] + m[6] * c[2] + m[7],
3600                        m[8] * c[0] + m[9] * c[1] + m[10] * c[2] + m[11],
3601                        1.0,
3602                    ];
3603                    let clip: Vec<f32> = (0..4).map(|r| (0..4).map(|k| v[r * 4 + k] * w[k]).sum()).collect();
3604                    // Corners behind the camera (a ground plane) say nothing.
3605                    if clip[3] <= 1e-3 {
3606                        pts.push([f32::NAN, f32::NAN]);
3607                        continue;
3608                    }
3609                    pts.push([
3610                        (clip[0] / clip[3] * 0.5 + 0.5) * fw,
3611                        (0.5 - clip[1] / clip[3] * 0.5) * fh,
3612                    ]);
3613                }
3614            }
3615            Some(pts)
3616        };
3617        match (project(t0), project(t1)) {
3618            (Some(a), Some(b)) if a.len() == b.len() => a
3619                .iter()
3620                .zip(&b)
3621                .map(|(p, q)| {
3622                    let d = ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt();
3623                    if d.is_nan() { 0.0 } else { d }
3624                })
3625                .fold(0.0, f32::max),
3626            _ => f32::INFINITY,
3627        }
3628    }
3629
3630    /// Renders a `render3d` group: every connected mesh, lit by the connected
3631    /// lights (the first directional light casts a shadow map), seen through
3632    /// the connected camera, with depth and 4x MSAA.
3633    #[allow(clippy::too_many_arguments)]
3634    fn encode_render3d(
3635        &mut self,
3636        plan: &Plan,
3637        g: &plan::Group,
3638        inputs: &[Placed],
3639        out: &Texture,
3640        doc: &Document,
3641        t: f64,
3642        list: &mut CommandList,
3643    ) -> Result<(), RenderError> {
3644        use scene3d::{Mat4, Params};
3645        const SAMPLES: u32 = 4;
3646        const SHADOW: u32 = 2048;
3647        let (fw, fh) = (doc.format.width, doc.format.height);
3648        // The scene draws on the device grid (the view's size); the shaders
3649        // place textures and find screen positions in its texels, and every
3650        // input texture is at the view's density.
3651        let v = self.view;
3652        let (dw, dh) = (v.w, v.h);
3653        let dev = |o: [f32; 2]| [o[0] / v.px, o[1] / v.px];
3654        if self.three.is_none() {
3655            let target = if self.device.backend() == "metal" {
3656                ultrafast_shaderc::Target::Metal
3657            } else {
3658                ultrafast_shaderc::Target::Spirv
3659            };
3660            use ultrafast_shaderc::Stage;
3661            let code = ultrafast_shaderc::Compiler::new()
3662                .compile_stages(
3663                    include_str!("../shaders/lib3d.slang"),
3664                    &[
3665                        ("vs_mesh", Stage::Vertex),
3666                        ("fs_mesh", Stage::Fragment),
3667                        ("vs_shadow", Stage::Vertex),
3668                        ("fs_shadow", Stage::Fragment),
3669                        ("fs_dist", Stage::Fragment),
3670                    ],
3671                    target,
3672                )
3673                .map_err(|e| RenderError::Setup(e.to_string()))?;
3674            let lib = self.device.library(&code.code)?;
3675            let pipeline = self.device.draw_pipeline(
3676                &lib,
3677                "vs_mesh",
3678                "fs_mesh",
3679                SAMPLES,
3680                true,
3681                ultrafast_gpu::Blend::Opaque,
3682                PixelFormat::Rgba16Float,
3683            )?;
3684            let shadow_pipeline = self.device.draw_pipeline(
3685                &lib,
3686                "vs_shadow",
3687                "fs_shadow",
3688                1,
3689                true,
3690                ultrafast_gpu::Blend::Opaque,
3691                PixelFormat::R32Float,
3692            )?;
3693            let dist_pipeline = self.device.draw_pipeline(
3694                &lib,
3695                "vs_shadow",
3696                "fs_dist",
3697                1,
3698                true,
3699                ultrafast_gpu::Blend::Opaque,
3700                PixelFormat::R32Float,
3701            )?;
3702            // 1x1 white RGBA16F (half 1.0 = 0x3c00).
3703            let one = 0x3c00u16.to_le_bytes();
3704            let white = self.device.upload_texture(
3705                TextureDesc {
3706                    width: 1,
3707                    height: 1,
3708                    format: PixelFormat::Rgba16Float,
3709                    cpu_readable: false,
3710                },
3711                &[one[0], one[1], one[0], one[1], one[0], one[1], one[0], one[1]],
3712            );
3713            let shadow_map = self.device.create_texture(TextureDesc {
3714                width: SHADOW,
3715                height: SHADOW,
3716                format: PixelFormat::R32Float,
3717                cpu_readable: false,
3718            });
3719            let shadow_depth = self
3720                .device
3721                .create_attachment(SHADOW, SHADOW, PixelFormat::Depth32Float, 1);
3722            self.three = Some(Three {
3723                pipeline,
3724                shadow_pipeline,
3725                shadow_map,
3726                shadow_depth,
3727                attachments: None,
3728                dist_pipeline,
3729                dof: None,
3730                white,
3731                meshes: HashMap::new(),
3732            });
3733        }
3734
3735        let root = &plan.nodes[g.root];
3736        let (root_t, active) = local_time(root, t);
3737        let rp = Params {
3738            node: &doc.nodes[&root.id],
3739            t: root_t,
3740        };
3741        let clear = rp.color("background", [0.0, 0.0, 0.0, 0.0]);
3742        // Outside its time window the scene draws nothing, background included.
3743        let clear = if active {
3744            [clear[0] * clear[3], clear[1] * clear[3], clear[2] * clear[3], clear[3]]
3745        } else {
3746            [0.0; 4]
3747        };
3748        let sky = rp.color("sky", [0.9, 0.95, 1.0, 1.0]);
3749        let ground = rp.color("ground", [0.35, 0.3, 0.28, 1.0]);
3750        let ambient = rp.num("ambient", 0.35);
3751        let shadows_on = !matches!(
3752            doc.nodes[&root.id].params.get("shadows"),
3753            Some(ultrafast_graph::Param::Bool(false))
3754        );
3755        let shadow_strength = rp.num("shadow_strength", 0.85);
3756        // Fog toward `fog_color` (the background by default) between
3757        // `fog` [start, end] world units from the camera.
3758        let fog = match doc.nodes[&root.id].params.get("fog").and_then(|p| p.eval(root_t)) {
3759            Some(v) if v.len() >= 2 => Some((v[0] as f32, (v[1] as f32).max(v[0] as f32 + 1e-3))),
3760            _ => None,
3761        };
3762        let fog_color = {
3763            let c = rp.color("fog_color", rp.color("background", [0.0, 0.0, 0.0, 1.0]));
3764            [c[0], c[1], c[2]]
3765        };
3766        let env_intensity = rp.num("environment_intensity", 1.0);
3767        let env_rotation = rp.num("environment_rotation", 0.0);
3768        // An image on the `environment` port lights and reflects in the scene.
3769        let env: Option<usize> = doc.nodes[&root.id].inputs.get("environment").and_then(|src| {
3770            let si = root.inputs.iter().copied().find(|&i| plan.nodes[i].id == *src)?;
3771            g.textures
3772                .iter()
3773                .position(|ts| *ts == TexSource::Group(plan.group_of[si]))
3774        });
3775        let env_origin = dev(env.map(|i| inputs[i].origin).unwrap_or([0.0, 0.0]));
3776        // A blurred copy of the environment, for rough surfaces and diffuse
3777        // light (a sparse disk over the sharp image would band).
3778        let env_soft: Option<Placed> = match env {
3779            Some(i) if active => {
3780                let frame_rect = [0.0, 0.0, fw as f64, fh as f64];
3781                let sigma = (fw.max(fh) as f32) * 0.025;
3782                Some(
3783                    self.encode_blur(&inputs[i], frame_rect, sigma, None, false, doc, t, list)
3784                        .0,
3785                )
3786            }
3787            _ => None,
3788        };
3789        let env_soft_origin = dev(env_soft.as_ref().map(|p| p.origin).unwrap_or([0.0, 0.0]));
3790        // Constant depth bias, in shadow-map texels of depth.
3791        let shadow_bias = rp.num("shadow_bias", 1.0);
3792
3793        // Camera and lights.
3794        let aspect = fw as f32 / fh.max(1) as f32;
3795        let mut eye = [0.0f32, 0.0, 5.0];
3796        let mut target = [0.0f32, 0.0, 0.0];
3797        let mut up = [0.0f32, 1.0, 0.0];
3798        let (mut fov, mut near, mut far) = (45.0f32, 0.1f32, 1000.0f32);
3799        let mut lights: Vec<[f32; 8]> = Vec::new();
3800        let mut meshes: Vec<usize> = Vec::new();
3801        for &o in &g.nodes[..g.nodes.len() - 1] {
3802            let pn = &plan.nodes[o];
3803            let (lt, on) = local_time(pn, t);
3804            if !on || !active {
3805                continue;
3806            }
3807            let p = Params {
3808                node: &doc.nodes[&pn.id],
3809                t: lt,
3810            };
3811            match pn.def.name {
3812                "camera" => {
3813                    target = p.vec("target", target);
3814                    up = p.vec("up", up);
3815                    fov = p.num("fov", fov);
3816                    near = p.num("near", near);
3817                    far = p.num("far", far);
3818                    eye = if pn_has(&doc.nodes[&pn.id], "orbit") {
3819                        // Orbit: azimuth, elevation (degrees), distance around target.
3820                        let [az, el, dist] = p.vec("orbit", [0.0, 0.0, 5.0]);
3821                        let (az, el) = (az.to_radians(), el.to_radians());
3822                        [
3823                            target[0] + dist * el.cos() * az.sin(),
3824                            target[1] + dist * el.sin(),
3825                            target[2] + dist * el.cos() * az.cos(),
3826                        ]
3827                    } else {
3828                        p.vec("position", eye)
3829                    };
3830                }
3831                "light" => {
3832                    let c = p.color("color", [1.0, 1.0, 1.0, 1.0]);
3833                    let point = p.text("kind") == Some("point");
3834                    let v = if point {
3835                        p.vec("position", [0.0, 2.0, 2.0])
3836                    } else {
3837                        p.vec("direction", [0.4, 0.8, 0.6])
3838                    };
3839                    lights.push([
3840                        point as u8 as f32,
3841                        v[0],
3842                        v[1],
3843                        v[2],
3844                        c[0],
3845                        c[1],
3846                        c[2],
3847                        p.num("intensity", 3.0),
3848                    ]);
3849                }
3850                "mesh" => meshes.push(o),
3851                _ => {}
3852            }
3853        }
3854        if lights.is_empty() {
3855            // A default key and rim light so an unlit scene is still readable.
3856            lights.push([0.0, 0.5, 0.8, 0.6, 1.0, 0.98, 0.95, 3.0]);
3857            lights.push([0.0, -0.6, 0.3, -0.7, 0.6, 0.7, 1.0, 1.2]);
3858        }
3859        // The first directional light casts the shadow: put it first.
3860        if let Some(i) = lights.iter().position(|l| l[0] < 0.5) {
3861            lights.swap(0, i);
3862        }
3863        lights.truncate(16);
3864        let view = Mat4::look_at(eye, target, up);
3865        let view_proj = Mat4::perspective(fov, aspect, near, far).mul(&view);
3866
3867        // Meshes: geometry from the cache, uploaded once.
3868        let three = self.three.as_mut().unwrap();
3869        if three
3870            .attachments
3871            .as_ref()
3872            .is_none_or(|(c, _)| c.desc().width != dw || c.desc().height != dh)
3873        {
3874            three.attachments = Some((
3875                self.device.create_attachment(dw, dh, PixelFormat::Rgba16Float, SAMPLES),
3876                self.device
3877                    .create_attachment(dw, dh, PixelFormat::Depth32Float, SAMPLES),
3878            ));
3879        }
3880        struct MeshDraw {
3881            key: String,
3882            model: Mat4,
3883            params: Vec<f32>,
3884            texture: Option<usize>,
3885            /// Glass: transmission, index of refraction, thickness,
3886            /// dispersion.
3887            glass: Option<[f32; 4]>,
3888        }
3889        let mut draws_params: Vec<MeshDraw> = Vec::new();
3890        let mut scene_min = [f32::MAX; 3];
3891        let mut scene_max = [f32::MIN; 3];
3892        for &o in &meshes {
3893            let pn = &plan.nodes[o];
3894            let node = &doc.nodes[&pn.id];
3895            let key = scene3d::mesh_key(node);
3896            if !three.meshes.contains_key(&key) {
3897                let m = scene3d::build_mesh(&pn.id, node, &self.base_dir, &mut self.fonts)?;
3898                let vb = self
3899                    .device
3900                    .create_buffer(m.vertices.len() * 4, Some(f32_bytes(&m.vertices)));
3901                let ib = self
3902                    .device
3903                    .create_buffer(m.indices.len() * 4, Some(u32_bytes(&m.indices)));
3904                let mut lo = [f32::MAX; 3];
3905                let mut hi = [f32::MIN; 3];
3906                for v in m.vertices.chunks_exact(8) {
3907                    for k in 0..3 {
3908                        lo[k] = lo[k].min(v[k]);
3909                        hi[k] = hi[k].max(v[k]);
3910                    }
3911                }
3912                three
3913                    .meshes
3914                    .insert(key.clone(), (vb, ib, m.indices.len() as u32, [lo, hi]));
3915            }
3916            let p = Params {
3917                node,
3918                t: local_time(pn, t).0,
3919            };
3920            let model = p.model();
3921            // World bounds for fitting the shadow camera.
3922            let [lo, hi] = three.meshes[&key].3;
3923            for corner in 0..8 {
3924                let c = [
3925                    if corner & 1 == 0 { lo[0] } else { hi[0] },
3926                    if corner & 2 == 0 { lo[1] } else { hi[1] },
3927                    if corner & 4 == 0 { lo[2] } else { hi[2] },
3928                ];
3929                let m = &model.0;
3930                let w = [
3931                    m[0] * c[0] + m[1] * c[1] + m[2] * c[2] + m[3],
3932                    m[4] * c[0] + m[5] * c[1] + m[6] * c[2] + m[7],
3933                    m[8] * c[0] + m[9] * c[1] + m[10] * c[2] + m[11],
3934                ];
3935                for k in 0..3 {
3936                    scene_min[k] = scene_min[k].min(w[k]);
3937                    scene_max[k] = scene_max[k].max(w[k]);
3938                }
3939            }
3940            let normal = model.inverse_affine().transpose();
3941            let base = p.color("color", [0.8, 0.8, 0.8, 1.0]);
3942            let emissive = p.color("emissive", [0.0, 0.0, 0.0, 1.0]);
3943            let texture = pn.inputs.first().and_then(|&src| {
3944                g.textures
3945                    .iter()
3946                    .position(|ts| *ts == TexSource::Group(plan.group_of[src]))
3947            });
3948            let origin = dev(texture.map(|i| inputs[i].origin).unwrap_or([0.0, 0.0]));
3949            let mut prm = header(doc, t, self.view).to_vec();
3950            prm.extend(model.0);
3951            prm.extend(view_proj.0);
3952            prm.extend(normal.0);
3953            prm.extend(base);
3954            prm.extend([
3955                p.num("metallic", 0.0),
3956                p.num("roughness", 0.5),
3957                texture.is_some() as u8 as f32,
3958                p.num("opacity", 1.0),
3959            ]);
3960            prm.extend([emissive[0], emissive[1], emissive[2], 0.0]);
3961            prm.extend([eye[0], eye[1], eye[2], lights.len() as f32]);
3962            prm.extend([sky[0], sky[1], sky[2], ambient, ground[0], ground[1], ground[2], 0.0]);
3963            prm.extend([origin[0], origin[1], fw as f32 / v.px, fh as f32 / v.px]);
3964            let transmission = p.num("transmission", 0.0);
3965            let glass = (transmission > 0.0).then(|| {
3966                [
3967                    transmission.min(1.0),
3968                    p.num("ior", 1.45).max(1.0),
3969                    p.num("thickness", 0.5),
3970                    p.num("dispersion", 0.0),
3971                ]
3972            });
3973            draws_params.push(MeshDraw {
3974                key,
3975                model,
3976                params: prm,
3977                texture,
3978                glass,
3979            });
3980        }
3981
3982        // Shadow camera: orthographic along the shadow light, fitted to the
3983        // scene's bounding sphere.
3984        let shadow_light = lights
3985            .first()
3986            .filter(|l| l[0] < 0.5 && shadows_on && !draws_params.is_empty())
3987            .copied();
3988        let light_vp = shadow_light.map(|l| {
3989            let c = [
3990                (scene_min[0] + scene_max[0]) / 2.0,
3991                (scene_min[1] + scene_max[1]) / 2.0,
3992                (scene_min[2] + scene_max[2]) / 2.0,
3993            ];
3994            let r = ((0..3).map(|k| (scene_max[k] - scene_min[k]).powi(2)).sum::<f32>()).sqrt() / 2.0 + 1e-3;
3995            let len = (l[1] * l[1] + l[2] * l[2] + l[3] * l[3]).sqrt().max(1e-6);
3996            let d = [l[1] / len, l[2] / len, l[3] / len];
3997            let eye = [c[0] + d[0] * r * 2.0, c[1] + d[1] * r * 2.0, c[2] + d[2] * r * 2.0];
3998            let up = if d[1].abs() > 0.95 {
3999                [0.0, 0.0, 1.0]
4000            } else {
4001                [0.0, 1.0, 0.0]
4002            };
4003            let view = Mat4::look_at(eye, c, up);
4004            let (n, f) = (r * 0.5, r * 3.5);
4005            let ortho = Mat4([
4006                1.0 / r,
4007                0.0,
4008                0.0,
4009                0.0,
4010                0.0,
4011                1.0 / r,
4012                0.0,
4013                0.0,
4014                0.0,
4015                0.0,
4016                -1.0 / (f - n),
4017                -n / (f - n),
4018                0.0,
4019                0.0,
4020                0.0,
4021                1.0,
4022            ]);
4023            (ortho.mul(&view), 2.0 * r)
4024        });
4025        for d in &mut draws_params {
4026            match light_vp {
4027                Some((lvp, extent)) => {
4028                    d.params.extend(lvp.0);
4029                    // Biases scale with how much world one shadow texel covers.
4030                    let texel_world = extent / SHADOW as f32;
4031                    d.params
4032                        .extend([1.0, shadow_bias / SHADOW as f32, 1.0 / SHADOW as f32, shadow_strength]);
4033                    d.params.push(texel_world * 1.5);
4034                }
4035                None => {
4036                    d.params.extend(Mat4::IDENTITY.0);
4037                    d.params.extend([0.0; 5]);
4038                }
4039            }
4040            // [101..106] environment, [106..112] fog.
4041            d.params.extend([
4042                env.is_some() as u8 as f32,
4043                env_intensity,
4044                env_rotation,
4045                env_origin[0],
4046                env_origin[1],
4047                fog.is_some() as u8 as f32,
4048                fog.map(|f| f.0).unwrap_or(0.0),
4049                fog.map(|f| f.1).unwrap_or(1.0),
4050                fog_color[0],
4051                fog_color[1],
4052                fog_color[2],
4053            ]);
4054            // [112..114] blurred environment origin, [114..118] glass,
4055            // [118..120] unused.
4056            let g = d.glass.unwrap_or([0.0; 4]);
4057            d.params
4058                .extend([env_soft_origin[0], env_soft_origin[1], g[0], g[1], g[2], g[3], 0.0, 0.0]);
4059            for l in &lights {
4060                d.params.extend(l);
4061            }
4062        }
4063
4064        if active && let Some((lvp, _)) = light_vp {
4065            let shadow_params: Vec<Vec<f32>> = draws_params
4066                .iter()
4067                .map(|d| {
4068                    let mut p = header(doc, t, self.view).to_vec();
4069                    p.extend(d.model.0);
4070                    p.extend(lvp.0);
4071                    p
4072                })
4073                .collect();
4074            let shadow_draws: Vec<ultrafast_gpu::Draw> = draws_params
4075                .iter()
4076                .zip(&shadow_params)
4077                .map(|(d, p)| {
4078                    let (vb, ib, n, _) = &three.meshes[&d.key];
4079                    ultrafast_gpu::Draw {
4080                        pipeline: &three.shadow_pipeline,
4081                        params: p,
4082                        vertices: ultrafast_gpu::BufferBinding::Buffer(vb),
4083                        indices: ib,
4084                        index_count: *n,
4085                        texture: &three.white,
4086                        texture2: &three.white,
4087                        texture3: &three.white,
4088                        texture4: &three.white,
4089                    }
4090                })
4091                .collect();
4092            list.draw_pass(
4093                ultrafast_gpu::DrawTarget {
4094                    resolve: &three.shadow_map,
4095                    color: None,
4096                    depth: Some(&three.shadow_depth),
4097                    clear: [1.0, 1.0, 1.0, 1.0],
4098                },
4099                &shadow_draws,
4100            );
4101        }
4102        // Depth of field: a camera-distance pass, the sharp image, a gather.
4103        let aperture = rp.num("aperture", 0.0);
4104        let focus = if pn_has(&doc.nodes[&root.id], "focus") {
4105            rp.num("focus", 5.0)
4106        } else {
4107            ((eye[0] - target[0]).powi(2) + (eye[1] - target[1]).powi(2) + (eye[2] - target[2]).powi(2)).sqrt()
4108        };
4109        let dof_on = active && aperture > 0.25 && !draws_params.is_empty();
4110        if dof_on {
4111            if three
4112                .dof
4113                .as_ref()
4114                .is_none_or(|(d, _, _)| d.desc().width != dw || d.desc().height != dh)
4115            {
4116                let tex = |format| TextureDesc {
4117                    width: dw,
4118                    height: dh,
4119                    format,
4120                    cpu_readable: false,
4121                };
4122                three.dof = Some((
4123                    self.device.create_texture(tex(PixelFormat::R32Float)),
4124                    self.device.create_attachment(dw, dh, PixelFormat::Depth32Float, 1),
4125                    self.device.create_texture(tex(PixelFormat::Rgba16Float)),
4126                ));
4127            }
4128            let dist_params: Vec<Vec<f32>> = draws_params
4129                .iter()
4130                .map(|d| {
4131                    let mut p = header(doc, t, self.view).to_vec();
4132                    p.extend(d.model.0);
4133                    p.extend(view_proj.0);
4134                    p.extend(eye);
4135                    p
4136                })
4137                .collect();
4138            let (dist, dist_depth, _) = three.dof.as_ref().unwrap();
4139            let dist_draws: Vec<ultrafast_gpu::Draw> = draws_params
4140                .iter()
4141                .zip(&dist_params)
4142                .map(|(d, p)| {
4143                    let (vb, ib, n, _) = &three.meshes[&d.key];
4144                    ultrafast_gpu::Draw {
4145                        pipeline: &three.dist_pipeline,
4146                        params: p,
4147                        vertices: ultrafast_gpu::BufferBinding::Buffer(vb),
4148                        indices: ib,
4149                        index_count: *n,
4150                        texture: &three.white,
4151                        texture2: &three.white,
4152                        texture3: &three.white,
4153                        texture4: &three.white,
4154                    }
4155                })
4156                .collect();
4157            list.draw_pass(
4158                ultrafast_gpu::DrawTarget {
4159                    resolve: dist,
4160                    color: None,
4161                    depth: Some(dist_depth),
4162                    clear: [1.0e6, 0.0, 0.0, 1.0],
4163                },
4164                &dist_draws,
4165            );
4166        }
4167        let (color, depth) = three.attachments.as_ref().unwrap();
4168        // Glass draws after everything else, refracting the finished opaque
4169        // scene (which it samples instead of an albedo texture).
4170        let draws: Vec<ultrafast_gpu::Draw> = if active {
4171            draws_params
4172                .iter()
4173                .filter(|d| d.glass.is_none())
4174                .map(|d| {
4175                    let (vb, ib, n, _) = &three.meshes[&d.key];
4176                    ultrafast_gpu::Draw {
4177                        pipeline: &three.pipeline,
4178                        params: &d.params,
4179                        vertices: ultrafast_gpu::BufferBinding::Buffer(vb),
4180                        indices: ib,
4181                        index_count: *n,
4182                        texture: d.texture.map(|i| &inputs[i].tex).unwrap_or(&three.white),
4183                        texture2: &three.shadow_map,
4184                        texture3: env.map(|i| &inputs[i].tex).unwrap_or(&three.white),
4185                        texture4: env_soft.as_ref().map(|p| &p.tex).unwrap_or(&three.white),
4186                    }
4187                })
4188                .collect()
4189        } else {
4190            Vec::new()
4191        };
4192        let target_tex = if dof_on { &three.dof.as_ref().unwrap().2 } else { out };
4193        list.draw_pass(
4194            ultrafast_gpu::DrawTarget {
4195                resolve: target_tex,
4196                color: Some(color),
4197                depth: Some(depth),
4198                clear,
4199            },
4200            &draws,
4201        );
4202        if dof_on {
4203            let (dist, _, sharp) = three.dof.as_ref().unwrap();
4204            // Gather at half resolution, then mix back by each pixel's blur.
4205            // Both passes work in device texels: the header's frame is the
4206            // device's, and the aperture (the largest blur, frame px) is
4207            // measured in its texels.
4208            let half = TextureDesc {
4209                width: dw.div_ceil(2),
4210                height: dh.div_ceil(2),
4211                format: PixelFormat::Rgba16Float,
4212                cpu_readable: false,
4213            };
4214            let soft = self.pool.lease(&self.device, half);
4215            let (tf, dwf, dhf) = (t as f32, dw as f32, dh as f32);
4216            let ap = aperture / v.px;
4217            let p = [tf, 2.0, dwf, dhf, focus, ap, (aperture * 2.5).clamp(24.0, 64.0)];
4218            list.dispatch(&self.kernels.utility("k_dof"), &soft, &[sharp, dist], &p);
4219            let p = [tf, 1.0, dwf, dhf, focus, ap, 0.0, 2.0];
4220            list.dispatch(&self.kernels.utility("k_dof_mix"), out, &[sharp, &soft, dist], &p);
4221            self.pool.give_back(soft);
4222        }
4223        if active && draws_params.iter().any(|d| d.glass.is_some()) {
4224            let frame = TextureDesc {
4225                width: dw,
4226                height: dh,
4227                format: PixelFormat::Rgba16Float,
4228                cpu_readable: false,
4229            };
4230            let scene = self.pool.lease(&self.device, frame);
4231            list.dispatch(
4232                &self.kernels.utility("k_copy"),
4233                &scene,
4234                &[out],
4235                &header(doc, t, self.view),
4236            );
4237            let glass_tex = self.pool.lease(&self.device, frame);
4238            let three = self.three.as_ref().unwrap();
4239            let (color, depth) = three.attachments.as_ref().unwrap();
4240            let glass: Vec<ultrafast_gpu::Draw> = draws_params
4241                .iter()
4242                .filter(|d| d.glass.is_some())
4243                .map(|d| {
4244                    let (vb, ib, n, _) = &three.meshes[&d.key];
4245                    ultrafast_gpu::Draw {
4246                        pipeline: &three.pipeline,
4247                        params: &d.params,
4248                        vertices: ultrafast_gpu::BufferBinding::Buffer(vb),
4249                        indices: ib,
4250                        index_count: *n,
4251                        texture: &scene,
4252                        texture2: &three.shadow_map,
4253                        texture3: env.map(|i| &inputs[i].tex).unwrap_or(&three.white),
4254                        texture4: env_soft.as_ref().map(|p| &p.tex).unwrap_or(&three.white),
4255                    }
4256                })
4257                .collect();
4258            list.draw_pass(
4259                ultrafast_gpu::DrawTarget {
4260                    resolve: &glass_tex,
4261                    color: Some(color),
4262                    depth: Some(depth),
4263                    clear: [0.0; 4],
4264                },
4265                &glass,
4266            );
4267            let mut p = header(doc, t, self.view).to_vec();
4268            p.extend([0.0, 0.0, 0.0, 0.0]);
4269            list.dispatch(&self.kernels.utility("k_over_frames"), out, &[&glass_tex, &scene], &p);
4270            self.pool.give_back(scene);
4271            self.pool.give_back(glass_tex);
4272        }
4273        if let Some(p) = env_soft {
4274            self.pool.give_back(p.tex);
4275        }
4276        Ok(())
4277    }
4278
4279    /// Gaussian blur of `src` over the region its content covers plus the
4280    /// blur's reach. Large radii run at 1/2..1/8 resolution (the result is
4281    /// band-limited anyway) and are upsampled into the output, or with
4282    /// `keep_low` returned at that resolution (its readers sample it).
4283    /// Returns the placed result and its content bounds.
4284    #[allow(clippy::too_many_arguments)]
4285    fn encode_blur(
4286        &mut self,
4287        src: &Placed,
4288        src_bounds: ops::Rect,
4289        sigma: f32,
4290        prev: Option<Placed>,
4291        keep_low: bool,
4292        doc: &Document,
4293        t: f64,
4294        list: &mut CommandList,
4295    ) -> (Placed, ops::Rect) {
4296        let (fw, fh) = (doc.format.width as f64, doc.format.height as f64);
4297        let pad = (3.0 * sigma as f64).ceil() + 2.0;
4298        let r = intersect(
4299            [
4300                src_bounds[0] - pad,
4301                src_bounds[1] - pad,
4302                src_bounds[2] + pad,
4303                src_bounds[3] + pad,
4304            ],
4305            [-pad, -pad, fw + pad, fh + pad],
4306        );
4307        // The region on the device grid: texels of the view's size (px
4308        // frame px each), so a blur at a larger size keeps its detail.
4309        let px = self.view.px;
4310        let pxd = px as f64;
4311        let (x0, y0) = ((r[0] / pxd).floor(), (r[1] / pxd).floor());
4312        let (x1, y1) = ((r[2] / pxd).ceil().max(x0 + 1.0), (r[3] / pxd).ceil().max(y0 + 1.0));
4313        let (rw, rh) = ((x1 - x0) as u32, (y1 - y0) as u32);
4314        let bucket = |v: u32| (v.div_ceil(RASTER_BUCKET) * RASTER_BUCKET).max(RASTER_BUCKET);
4315        let desc = |w: u32, h: u32| TextureDesc {
4316            width: w,
4317            height: h,
4318            format: PixelFormat::Rgba16Float,
4319            cpu_readable: false,
4320        };
4321        // Downscale so each pass needs about 3 sigma of taps at >= 3 texels.
4322        let mut f = 1.0f32;
4323        while f < 8.0 && sigma / px / (f * 2.0) >= 3.0 {
4324            f *= 2.0;
4325        }
4326        let out_desc = if f > 1.0 && keep_low {
4327            desc(bucket(rw.div_ceil(f as u32)), bucket(rh.div_ceil(f as u32)))
4328        } else {
4329            desc(bucket(rw), bucket(rh))
4330        };
4331        let out = match prev {
4332            Some(p) if p.tex.desc() == out_desc => p.tex,
4333            Some(p) => {
4334                self.pool.give_back(p.tex);
4335                self.pool.lease(&self.device, out_desc)
4336            }
4337            None => self.pool.lease(&self.device, out_desc),
4338        };
4339        let blur = self.kernels.utility("k_blur_region");
4340        let resample = self.kernels.utility("k_resample");
4341        let hdr = header(doc, t, self.view);
4342        let (ox, oy) = ((x0 * pxd) as f32, (y0 * pxd) as f32);
4343        let p = |v: &[f32]| {
4344            let mut x = hdr.to_vec();
4345            x.extend_from_slice(v);
4346            x
4347        };
4348        let si = src.scale;
4349        // Texel sizes in frame px: the view's, and f of them downscaled.
4350        let (t1, tf) = (px, f * px);
4351        let scale = if f == 1.0 {
4352            let tmp = self.pool.lease(&self.device, out_desc);
4353            list.dispatch(
4354                &blur,
4355                &tmp,
4356                &[&src.tex],
4357                &p(&[sigma, 1.0, 0.0, t1, ox, oy, src.origin[0], src.origin[1], si]),
4358            );
4359            list.dispatch(&blur, &out, &[&tmp], &p(&[sigma, 0.0, 1.0, t1, ox, oy, ox, oy, t1]));
4360            self.pool.give_back(tmp);
4361            t1
4362        } else if keep_low {
4363            let b = self.pool.lease(&self.device, out_desc);
4364            list.dispatch(
4365                &resample,
4366                &out,
4367                &[&src.tex],
4368                &p(&[tf, ox, oy, src.origin[0], src.origin[1], si, 2.0]),
4369            );
4370            list.dispatch(&blur, &b, &[&out], &p(&[sigma, 1.0, 0.0, tf, ox, oy, ox, oy, tf]));
4371            list.dispatch(&blur, &out, &[&b], &p(&[sigma, 0.0, 1.0, tf, ox, oy, ox, oy, tf]));
4372            self.pool.give_back(b);
4373            tf
4374        } else {
4375            let low = desc(bucket(rw.div_ceil(f as u32)), bucket(rh.div_ceil(f as u32)));
4376            let a = self.pool.lease(&self.device, low);
4377            let b = self.pool.lease(&self.device, low);
4378            list.dispatch(
4379                &resample,
4380                &a,
4381                &[&src.tex],
4382                &p(&[tf, ox, oy, src.origin[0], src.origin[1], si, 2.0]),
4383            );
4384            list.dispatch(&blur, &b, &[&a], &p(&[sigma, 1.0, 0.0, tf, ox, oy, ox, oy, tf]));
4385            list.dispatch(&blur, &a, &[&b], &p(&[sigma, 0.0, 1.0, tf, ox, oy, ox, oy, tf]));
4386            list.dispatch(&resample, &out, &[&a], &p(&[t1, ox, oy, ox, oy, tf, 1.0]));
4387            self.pool.give_back(a);
4388            self.pool.give_back(b);
4389            t1
4390        };
4391        (
4392            Placed {
4393                tex: out,
4394                origin: [ox, oy],
4395                scale,
4396            },
4397            [x0 * pxd, y0 * pxd, x1 * pxd, y1 * pxd],
4398        )
4399    }
4400
4401    /// Draws a particle system into a texture sized to its bounds.
4402    #[allow(clippy::too_many_arguments)]
4403    fn encode_particles(
4404        &mut self,
4405        plan: &Plan,
4406        g: &plan::Group,
4407        sprite: Option<Placed>,
4408        prev: Option<Placed>,
4409        doc: &Document,
4410        t: f64,
4411        list: &mut CommandList,
4412    ) -> Result<Placed, RenderError> {
4413        let pn = &plan.nodes[g.root];
4414        let (lt, on) = local_time(pn, t);
4415        let node = &doc.nodes[&pn.id];
4416        let sys = if on && node.op == "swarm" {
4417            swarm::evaluate(&pn.id, node, lt, &mut self.fonts, &self.base_dir, &mut self.swarm_homes)?
4418        } else if on {
4419            particles::evaluate(&pn.id, node, lt)?
4420        } else {
4421            particles::Particles {
4422                data: Vec::new(),
4423                count: 0,
4424                bounds: [0.0; 4],
4425            }
4426        };
4427        if self.sprites.is_none() {
4428            let target = if self.device.backend() == "metal" {
4429                ultrafast_shaderc::Target::Metal
4430            } else {
4431                ultrafast_shaderc::Target::Spirv
4432            };
4433            let code = ultrafast_shaderc::Compiler::new()
4434                .compile_stages(
4435                    include_str!("../shaders/particles.slang"),
4436                    &[
4437                        ("vs_particle", ultrafast_shaderc::Stage::Vertex),
4438                        ("fs_particle", ultrafast_shaderc::Stage::Fragment),
4439                    ],
4440                    target,
4441                )
4442                .map_err(|e| RenderError::Setup(e.to_string()))?;
4443            let lib = self.device.library(&code.code)?;
4444            let over = self.device.draw_pipeline(
4445                &lib,
4446                "vs_particle",
4447                "fs_particle",
4448                1,
4449                false,
4450                ultrafast_gpu::Blend::Over,
4451                PixelFormat::Rgba16Float,
4452            )?;
4453            let add = self.device.draw_pipeline(
4454                &lib,
4455                "vs_particle",
4456                "fs_particle",
4457                1,
4458                false,
4459                ultrafast_gpu::Blend::Add,
4460                PixelFormat::Rgba16Float,
4461            )?;
4462            let one = 0x3c00u16.to_le_bytes();
4463            let white = self.device.upload_texture(
4464                TextureDesc {
4465                    width: 1,
4466                    height: 1,
4467                    format: PixelFormat::Rgba16Float,
4468                    cpu_readable: false,
4469                },
4470                &[one[0], one[1], one[0], one[1], one[0], one[1], one[0], one[1]],
4471            );
4472            self.sprites = Some((over, add, self.device.create_buffer(16, None), white));
4473        }
4474        // Under motion blur, drawn once, each particle blurs itself along its
4475        // path over the shutter (within the sampled waves the samples do).
4476        let span = match (&self.mb_frame, self.mb_sample) {
4477            (Some(f), None) if !self.mb_full => f.span,
4478            _ => 0.0,
4479        };
4480        let reach = if span > 0.0 {
4481            sys.data
4482                .chunks_exact(12)
4483                .map(|d| (d[8] as f64).hypot(d[9] as f64))
4484                .fold(0.0, f64::max)
4485                * span
4486                / 2.0
4487                + 1.0
4488        } else {
4489            0.0
4490        };
4491        // Region: the particles' bounds, clipped to a window around the
4492        // frame, in device texels (px frame px each).
4493        let px = self.view.px as f64;
4494        let (fw, fh) = (self.view.w as f64, self.view.h as f64);
4495        let b = [
4496            (sys.bounds[0] - reach) / px,
4497            (sys.bounds[1] - reach) / px,
4498            (sys.bounds[2] + reach) / px,
4499            (sys.bounds[3] + reach) / px,
4500        ];
4501        let r = if sys.count == 0 {
4502            [0.0, 0.0, 1.0, 1.0]
4503        } else {
4504            intersect(
4505                [b[0].floor(), b[1].floor(), b[2].ceil(), b[3].ceil()],
4506                [-fw, -fh, 2.0 * fw, 2.0 * fh],
4507            )
4508        };
4509        let (rw, rh) = (((r[2] - r[0]).max(1.0)) as u32, ((r[3] - r[1]).max(1.0)) as u32);
4510        let bucket = |v: u32| (v.div_ceil(RASTER_BUCKET) * RASTER_BUCKET).max(RASTER_BUCKET);
4511        let desc = TextureDesc {
4512            width: bucket(rw).min(8192),
4513            height: bucket(rh).min(8192),
4514            format: PixelFormat::Rgba16Float,
4515            cpu_readable: false,
4516        };
4517        let out = match prev {
4518            Some(p) if p.tex.desc() == desc => p.tex,
4519            Some(p) => {
4520                self.pool.give_back(p.tex);
4521                self.pool.lease(&self.device, desc)
4522            }
4523            None => self.pool.lease(&self.device, desc),
4524        };
4525        // Sequential indices 0..6n, grown as needed.
4526        let need = sys.count * 6 * 4;
4527        let (over, add, mut idx, white) = self.sprites.clone().unwrap();
4528        if idx.len() < need {
4529            let n = (sys.count * 6).next_power_of_two();
4530            let seq: Vec<u32> = (0..n as u32).collect();
4531            idx = self.device.create_buffer(n * 4, Some(u32_bytes(&seq)));
4532            self.sprites.as_mut().unwrap().2 = idx.clone();
4533        }
4534        let additive = ops::text(node, "blend") == Some("add");
4535        // Region origin and size in frame px: particles are placed there.
4536        let mut p = header(doc, t, self.view).to_vec();
4537        p.extend([
4538            (r[0] * px) as f32,
4539            (r[1] * px) as f32,
4540            (desc.width as f64 * px) as f32,
4541            (desc.height as f64 * px) as f32,
4542            span as f32,
4543        ]);
4544        let sprite_tex = sprite.as_ref().map(|s| &s.tex).unwrap_or(&white);
4545        let draws = if sys.count > 0 {
4546            vec![ultrafast_gpu::Draw {
4547                pipeline: if additive { &add } else { &over },
4548                params: &p,
4549                vertices: ultrafast_gpu::BufferBinding::Data(f32_bytes(&sys.data)),
4550                indices: &idx,
4551                index_count: (sys.count * 6) as u32,
4552                texture: sprite_tex,
4553                texture2: &white,
4554                texture3: &white,
4555                texture4: &white,
4556            }]
4557        } else {
4558            Vec::new()
4559        };
4560        list.draw_pass(
4561            ultrafast_gpu::DrawTarget {
4562                resolve: &out,
4563                color: None,
4564                depth: None,
4565                clear: [0.0; 4],
4566            },
4567            &draws,
4568        );
4569        Ok(Placed {
4570            tex: out,
4571            origin: [(r[0] * px) as f32, (r[1] * px) as f32],
4572            scale: px as f32,
4573        })
4574    }
4575
4576    /// Copies a placed texture into a frame-sized one (tier-0 `opacity` at 1).
4577    fn copy_placed(
4578        &self,
4579        src: &Placed,
4580        dst: &Texture,
4581        doc: &Document,
4582        t: f64,
4583        list: &mut CommandList,
4584    ) -> Result<(), RenderError> {
4585        let k = self.kernels.tier0_kernel("opacity").map_err(RenderError::Setup)?;
4586        let mut p = header(doc, t, self.view).to_vec();
4587        p.extend([1.0, src.origin[0], src.origin[1], src.scale]);
4588        list.dispatch(&k, dst, &[&src.tex], &p);
4589        Ok(())
4590    }
4591
4592    /// Flattened geometry for a raster node, rebuilt only when its key changes.
4593    fn geometry(
4594        &mut self,
4595        id: &str,
4596        doc: &Document,
4597        t: f64,
4598        outer: ops::Affine,
4599        key: u64,
4600    ) -> Result<Arc<geom::Geometry>, RenderError> {
4601        if let Some((k, _, _, g)) = self.geometry.get(id)
4602            && *k == key
4603        {
4604            return Ok(g.clone());
4605        }
4606        let node = &doc.nodes[id];
4607        let content = geom::content_key(node, t);
4608        let full = outer.mul(geom::placement_affine(node, t));
4609        // Moved, turned or shrunk but otherwise unchanged (the common
4610        // animated case): map the geometry as last built instead of building
4611        // it again (curves flattened for its size stay as fine; grown, it is
4612        // built again).
4613        if let Some((_, c, built_at, built)) = self.built.get(id)
4614            && *c == content
4615            && let Some(back) = built_at.inverse()
4616        {
4617            let m = full.mul(back);
4618            let same_linear = (0..4).all(|i| (built_at.0[i] - full.0[i]).abs() < 1e-9);
4619            // Largest stretch of the 2x2 part: its biggest singular value.
4620            let [a, b, cc, d, ..] = m.0;
4621            let (p, q) = ((a * a + b * b + cc * cc + d * d) / 2.0, (a * d - b * cc).abs());
4622            let stretch = (p + (p * p - q * q).max(0.0).sqrt()).sqrt();
4623            if same_linear || stretch <= 1.0005 {
4624                let g = Arc::new(if same_linear {
4625                    built.translated(full.0[4] - built_at.0[4], full.0[5] - built_at.0[5])
4626                } else {
4627                    built.transformed(m.0)
4628                });
4629                self.bounds.insert(id.to_string(), self.frame_bounds(g.bounds));
4630                self.geometry.insert(id.to_string(), (key, content, full, g.clone()));
4631                return Ok(g);
4632            }
4633        }
4634        let g = Arc::new(match node.op.as_str() {
4635            "text" => geom::text_node(id, node, &doc.format, t, outer, &mut self.fonts, &self.base_dir)?,
4636            _ => geom::path(id, node, &doc.format, t, outer)?,
4637        });
4638        if let Some(m) = reveal_falls_short(node, g.units) {
4639            self.diagnose(id, m);
4640        }
4641        self.bounds.insert(id.to_string(), self.frame_bounds(g.bounds));
4642        self.geometry.insert(id.to_string(), (key, content, full, g.clone()));
4643        self.built.insert(id.to_string(), (key, content, full, g.clone()));
4644        Ok(g)
4645    }
4646
4647    /// Bounds of geometry built on the device grid, in frame px (what
4648    /// picking, inspection and motion extents read).
4649    fn frame_bounds(&self, b: [f32; 4]) -> [f32; 4] {
4650        let px = self.view.px;
4651        [b[0] * px, b[1] * px, b[2] * px, b[3] * px]
4652    }
4653
4654    /// The color glyphs of `geo` for `k_raster_resolve`: their bitmaps put
4655    /// in the atlas (recorded on `list` before the resolve reads them), and
4656    /// twelve floats each (see `glyph_images` in lib.slang).
4657    fn glyph_records(&mut self, geo: &geom::Geometry, list: &mut CommandList) -> Vec<f32> {
4658        if geo.images.is_empty() {
4659            return Vec::new();
4660        }
4661        let put = self.kernels.utility("k_atlas_put");
4662        let atlas = self
4663            .glyph_atlas
4664            .get_or_insert_with(|| glyph_atlas::GlyphAtlas::new(&self.device));
4665        let mut place_all = |atlas: &mut glyph_atlas::GlyphAtlas| -> Vec<Option<[u32; 4]>> {
4666            geo.images
4667                .iter()
4668                .map(|im| atlas.place(&self.device, list, &put, &im.bitmap))
4669                .collect()
4670        };
4671        let generation = atlas.generation;
4672        let mut rects = place_all(atlas);
4673        // The atlas started over partway: place them all again.
4674        if atlas.generation != generation {
4675            rects = place_all(atlas);
4676        }
4677        let mut out = Vec::with_capacity(geo.images.len() * 12);
4678        for (im, rect) in geo.images.iter().zip(rects) {
4679            let Some(r) = rect else { continue };
4680            let m = im.xf;
4681            let det = m[0] * m[3] - m[1] * m[2];
4682            if det.abs() < 1e-12 {
4683                continue;
4684            }
4685            // Inverse of (u, v) -> (a u + c v + e, b u + d v + f).
4686            let (ia, ib, ic, id) = (m[3] / det, -m[1] / det, -m[2] / det, m[0] / det);
4687            let (ie, if_) = (-(ia * m[4] + ic * m[5]), -(ib * m[4] + id * m[5]));
4688            out.extend([
4689                ia as f32,
4690                ic as f32,
4691                ie as f32,
4692                im.weight,
4693                ib as f32,
4694                id as f32,
4695                if_ as f32,
4696                0.0,
4697                r[0] as f32,
4698                r[1] as f32,
4699                r[2] as f32,
4700                r[3] as f32,
4701            ]);
4702        }
4703        out
4704    }
4705
4706    /// Rasterizes geometry into a texture covering its bounds: clear the
4707    /// accumulator rows it touches, deposit segment areas, prefix-sum rows
4708    /// into coverage times color. Reuses `prev` when its size still fits.
4709    #[allow(clippy::too_many_arguments)]
4710    fn encode_raster(
4711        &mut self,
4712        geo: &geom::Geometry,
4713        prev: Option<Placed>,
4714        image_opacity: f32,
4715        framed: bool,
4716        doc: &Document,
4717        t: f64,
4718        list: &mut CommandList,
4719    ) -> Placed {
4720        // The region covers the geometry's bounds, even off-frame: content
4721        // placed outside the frame may be moved in by later warps, blurs or
4722        // shaders. It is limited to a window around the frame, to the frame
4723        // itself when nothing downstream looks outside it (layers zoomed far
4724        // past the frame then cost a frame, not nine), and to the texture
4725        // size limit.
4726        // In device texels: the geometry was built on the view's grid.
4727        let (fw, fh) = (self.view.w as i64, self.view.h as i64);
4728        let (wx0, wy0, wx1, wy1) = if framed {
4729            (0, 0, fw, fh)
4730        } else {
4731            (-fw, -fh, 2 * fw, 2 * fh)
4732        };
4733        let b = geo.bounds;
4734        let (mut x0, mut y0, mut x1, mut y1) = if geo.is_empty() || b[0] > b[2] {
4735            (0, 0, 1, 1)
4736        } else {
4737            (
4738                (b[0].floor() as i64 - 1).max(wx0),
4739                (b[1].floor() as i64 - 1).max(wy0),
4740                (b[2].ceil() as i64 + 2).min(wx1),
4741                (b[3].ceil() as i64 + 2).min(wy1),
4742            )
4743        };
4744        x1 = x1.min(x0 + MAX_RASTER);
4745        y1 = y1.min(y0 + MAX_RASTER);
4746        if x1 <= x0 || y1 <= y0 {
4747            (x0, y0, x1, y1) = (0, 0, 1, 1);
4748        }
4749        let (rw, rh) = ((x1 - x0) as usize, (y1 - y0) as usize);
4750        let bucket = |v: usize| ((v as u32).div_ceil(RASTER_BUCKET) * RASTER_BUCKET).max(RASTER_BUCKET);
4751        let desc = TextureDesc {
4752            width: bucket(rw),
4753            height: bucket(rh),
4754            format: PixelFormat::Rgba16Float,
4755            cpu_readable: false,
4756        };
4757        // The last texture is kept while the geometry fits and fills at
4758        // least four fifths of it (the resolve clears the rest, so slack
4759        // costs GPU time). Geometry that grows (zooming type) gets an eighth
4760        // more room, so it does not need a new texture on every frame and
4761        // motion-blur sample; each replaced one stays alive until the frames
4762        // using it finish.
4763        let area = |d: TextureDesc| d.width as u64 * d.height as u64;
4764        let tex = match prev {
4765            Some(p)
4766                if p.tex.desc().width >= desc.width
4767                    && p.tex.desc().height >= desc.height
4768                    && area(p.tex.desc()) * 4 <= 5 * area(desc) =>
4769            {
4770                p.tex
4771            }
4772            Some(p) => {
4773                let grew = p.tex.desc().width < desc.width || p.tex.desc().height < desc.height;
4774                self.pool.give_back(p.tex);
4775                let room = |v: usize, b: u32| {
4776                    if grew {
4777                        bucket(v + v / 8).min(MAX_RASTER as u32 + RASTER_BUCKET)
4778                    } else {
4779                        b
4780                    }
4781                };
4782                let grown = TextureDesc {
4783                    width: room(rw, desc.width),
4784                    height: room(rh, desc.height),
4785                    ..desc
4786                };
4787                self.pool.lease(&self.device, grown)
4788            }
4789            None => self.pool.lease(&self.device, desc),
4790        };
4791
4792        // One accumulator plane per color group (grown with room to spare:
4793        // a replaced buffer also lives until in-flight frames finish).
4794        let groups = geo.groups.len().max(1);
4795        let bytes = (rw + 2) * rh * 4 * groups;
4796        if self.acc.as_ref().is_none_or(|b| b.len() < bytes) {
4797            self.acc = Some(self.device.create_private_buffer(bytes + bytes / 2));
4798        }
4799        let acc = self.acc.clone().unwrap();
4800        list.clear_buffer_range(&acc, 0, bytes);
4801
4802        let hdr = header(doc, t, self.view);
4803        let n = geo.count();
4804        if n > 0 {
4805            let seg_bytes =
4806                unsafe { std::slice::from_raw_parts(geo.segments.as_ptr().cast::<u8>(), geo.segments.len() * 4) };
4807            let mut p = hdr.to_vec();
4808            p.extend([n as f32, rw as f32, rh as f32, x0 as f32, y0 as f32]);
4809            list.dispatch_ex(
4810                &self.kernels.utility("k_raster_lines"),
4811                &tex,
4812                &[],
4813                &p,
4814                Bindings {
4815                    buffers: &[BufferBinding::Buffer(&acc), BufferBinding::Data(seg_bytes)],
4816                    grid: Some((n as u32, 1)),
4817                    threadgroup: Some((64, 1)),
4818                },
4819            );
4820        }
4821        // Packed after the header: [4..8] color, [8] fill rule.
4822        let mut p = hdr.to_vec();
4823        p.push(self.scratch[8]);
4824        p.extend_from_slice(&self.scratch[4..8]);
4825        p.extend([rw as f32, rh as f32, groups as f32]);
4826        // Group colors: the node's own, or a group's color faded with it.
4827        let node_alpha = self.scratch[7];
4828        if geo.groups.is_empty() {
4829            p.extend_from_slice(&self.scratch[4..8]);
4830        }
4831        for g in &geo.groups {
4832            match g {
4833                None => p.extend_from_slice(&self.scratch[4..8]),
4834                Some(c) => {
4835                    let a = c[3] * node_alpha;
4836                    p.extend([c[0] * a, c[1] * a, c[2] * a, a]);
4837                }
4838            }
4839        }
4840        // Color glyphs: their bitmaps in the atlas, and per glyph the map
4841        // from frame px to its unit square.
4842        let records = self.glyph_records(geo, list);
4843        p.extend([(records.len() / 12) as f32, x0 as f32, y0 as f32, image_opacity]);
4844        let atlas = match (&self.glyph_atlas, records.is_empty()) {
4845            (Some(a), false) => a.tex.clone(),
4846            _ => self.placeholder.clone(),
4847        };
4848        let record_bytes: &[u8] = if records.is_empty() {
4849            &[0u8; 48]
4850        } else {
4851            unsafe { std::slice::from_raw_parts(records.as_ptr().cast::<u8>(), records.len() * 4) }
4852        };
4853        list.dispatch_ex(
4854            &self.kernels.utility("k_raster_resolve"),
4855            &tex,
4856            &[&atlas],
4857            &p,
4858            Bindings {
4859                buffers: &[BufferBinding::Buffer(&acc), BufferBinding::Data(record_bytes)],
4860                grid: Some((256, tex.desc().height)),
4861                threadgroup: Some((256, 1)),
4862            },
4863        );
4864        Placed {
4865            tex,
4866            origin: [x0 as f32 * self.view.px, y0 as f32 * self.view.px],
4867            scale: self.view.px,
4868        }
4869    }
4870
4871    /// Runs a fused group as a chain of tier-0 kernels (one per node, through
4872    /// pooled temporaries) while its fused kernel compiles.
4873    #[allow(clippy::too_many_arguments)]
4874    fn encode_fallback(
4875        &mut self,
4876        plan: &Plan,
4877        gi: usize,
4878        inputs: &[Placed],
4879        out: &Texture,
4880        doc: &Document,
4881        t: f64,
4882        list: &mut CommandList,
4883        res_info: &HashMap<&str, ResourceInfo>,
4884    ) -> Result<(), RenderError> {
4885        let g = &plan.groups[gi];
4886        let desc = out.desc();
4887        let mut value: HashMap<usize, Placed> = HashMap::new();
4888        let mut leased = Vec::new();
4889        let external =
4890            |ts: TexSource| -> Option<Placed> { g.textures.iter().position(|x| *x == ts).map(|p| inputs[p].clone()) };
4891        for &ni in &g.nodes {
4892            let pn = &plan.nodes[ni];
4893            let target = if ni == g.root {
4894                out.clone()
4895            } else {
4896                let tex = self.pool.lease(&self.device, desc);
4897                leased.push(tex.clone());
4898                tex
4899            };
4900            // Inputs: inlined nodes come from temporaries, materialized ones
4901            // are this group's external textures.
4902            let port_tex: Vec<Placed> = pn
4903                .inputs
4904                .iter()
4905                .map(|&src| {
4906                    value.get(&src).cloned().unwrap_or_else(|| {
4907                        external(TexSource::Group(plan.group_of[src])).unwrap_or(Placed {
4908                            tex: self.placeholder.clone(),
4909                            origin: [0.0, 0.0],
4910                            scale: 1.0,
4911                        })
4912                    })
4913                })
4914                .collect();
4915            let mut p = header(doc, t, self.view).to_vec();
4916            let info = if ops::uses_resource(pn.def) {
4917                res_info.get(pn.variant.as_str()).copied()
4918            } else {
4919                None
4920            };
4921            let (lt, on) = local_time(pn, t);
4922            ops::pack(pn.def, &pn.id, &doc.nodes[&pn.id], &doc.format, lt, info, &mut p)?;
4923            if ops::guarded(pn.def) {
4924                p.extend(ops::UNBOUNDED.map(|v| v as f32));
4925            }
4926            // Inactive nodes pass their destination/source through, or go
4927            // transparent if they have none.
4928            if !on {
4929                match ops::passthrough(pn.def, port_tex.len()) {
4930                    Some(i) => self.copy_placed(&port_tex[i], &target, doc, t, list)?,
4931                    None => list.dispatch(&self.kernels.utility("k_clear"), &target, &[], &p),
4932                }
4933                value.insert(
4934                    ni,
4935                    Placed {
4936                        tex: target,
4937                        origin: [0.0, 0.0],
4938                        scale: self.view.px,
4939                    },
4940                );
4941                continue;
4942            }
4943            match self.kernels.tier0(pn.def.func).cloned() {
4944                Some(t0) => {
4945                    let k = self.kernels.tier0_kernel(pn.def.func).map_err(RenderError::Setup)?;
4946                    let bound: Vec<Placed> = t0
4947                        .bindings
4948                        .iter()
4949                        .map(|&b| {
4950                            if b == usize::MAX {
4951                                external(TexSource::Resource(pn.variant.clone())).unwrap_or(Placed {
4952                                    tex: self.placeholder.clone(),
4953                                    origin: [0.0, 0.0],
4954                                    scale: 1.0,
4955                                })
4956                            } else {
4957                                port_tex[b].clone()
4958                            }
4959                        })
4960                        .collect();
4961                    for b in &bound {
4962                        p.extend(b.origin);
4963                        p.push(b.scale);
4964                    }
4965                    let refs: Vec<&Texture> = bound.iter().map(|b| &b.tex).collect();
4966                    list.dispatch(&k, &target, &refs, &p);
4967                }
4968                None => list.dispatch(&self.kernels.utility("k_clear"), &target, &[], &p),
4969            }
4970            value.insert(
4971                ni,
4972                Placed {
4973                    tex: target,
4974                    origin: [0.0, 0.0],
4975                    scale: self.view.px,
4976                },
4977            );
4978        }
4979        // Temporaries go back to the pool now: later frames reuse them in
4980        // queue order, after this frame's reads.
4981        for tex in leased {
4982            self.pool.give_back(tex);
4983        }
4984        Ok(())
4985    }
4986
4987    /// Mean squared error (8-bit sRGB units, over black) between frame `t`
4988    /// and `reference` (an RGBA8 sRGB texture of the frame's size), reduced
4989    /// on the GPU: only one partial sum per 16x16 tile is read back.
4990    pub fn frame_mse(&mut self, doc: &Document, t: f64, reference: &Texture) -> Result<f64, RenderError> {
4991        let (w, h) = self.frame_size(doc);
4992        let groups = (w.div_ceil(16) * h.div_ceil(16)) as usize;
4993        if self.diff_buf.as_ref().is_none_or(|b| b.len() < groups * 4) {
4994            self.diff_buf = Some(self.device.create_buffer(groups * 4, None));
4995        }
4996        let buf = self.diff_buf.clone().unwrap();
4997        let (sub, _) = self.submit_frame_with(doc, t, |o| {
4998            let mut p = o.header.to_vec();
4999            p.extend(o.origin);
5000            o.list.dispatch_ex(
5001                &o.kernels.utility("k_diff"),
5002                o.texture,
5003                &[o.texture, reference],
5004                &p,
5005                Bindings {
5006                    buffers: &[BufferBinding::Buffer(&buf)],
5007                    grid: Some((w, h)),
5008                    threadgroup: Some((16, 16)),
5009                },
5010            );
5011        })?;
5012        sub.wait()?;
5013        let sum: u64 = self
5014            .device
5015            .read_buffer(&buf, groups * 4)
5016            .chunks_exact(4)
5017            .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) as u64)
5018            .sum();
5019        Ok(sum as f64 / (w as f64 * h as f64 * 3.0))
5020    }
5021
5022    /// Renders frame `t`, waits, and returns tightly packed sRGB RGBA8 pixels.
5023    pub fn render_rgba8(&mut self, doc: &Document, t: f64) -> Result<(Vec<u8>, FrameReport), RenderError> {
5024        let (sub, report) = self.submit_frame(doc, t, true)?;
5025        sub.wait()?;
5026        let mut px = self.read_export();
5027        clear_transparent(&mut px);
5028        Ok((px, report))
5029    }
5030
5031    /// Renders frame `t`, waits, and returns it tightly packed as `kind`.
5032    /// `opaque` flattens it over black, as a video without alpha shows it;
5033    /// otherwise alpha is straight.
5034    pub fn render_readback(
5035        &mut self,
5036        doc: &Document,
5037        t: f64,
5038        kind: Readback,
5039        opaque: bool,
5040    ) -> Result<(Vec<u8>, FrameReport), RenderError> {
5041        let format = match kind {
5042            Readback::Srgb8 => PixelFormat::Rgba8Unorm,
5043            Readback::SrgbHalf | Readback::LinearHalf => PixelFormat::Rgba16Float,
5044        };
5045        let mode = match (kind, opaque) {
5046            (Readback::LinearHalf, true) => 3.0,
5047            (Readback::LinearHalf, false) => 2.0,
5048            (_, true) => 1.0,
5049            (_, false) => 0.0,
5050        };
5051        let (w, h) = self.frame_size(doc);
5052        let ex = self.export_texture(w, h, format);
5053        let (sub, report) = self.submit_frame_with(doc, t, |o| {
5054            let mut p = o.header.to_vec();
5055            p.extend(o.origin);
5056            p.push(mode);
5057            o.list
5058                .dispatch(&o.kernels.utility("k_encode_srgb8"), &ex, &[o.texture], &p);
5059        })?;
5060        sub.wait()?;
5061        let mut px = self.read_export();
5062        if kind == Readback::Srgb8 && !opaque {
5063            clear_transparent(&mut px);
5064        }
5065        Ok((px, report))
5066    }
5067
5068    /// Renders frame `t` the way the player shows it: letterboxed into a
5069    /// `width` x `height` view with the timeline drawn over it (`hud`: on,
5070    /// playhead 0..1, loop in, loop out, emphasis, playing). RGBA8, sRGB.
5071    pub fn render_presented(
5072        &mut self,
5073        doc: &Document,
5074        t: f64,
5075        width: u32,
5076        height: u32,
5077        hud: [f32; 6],
5078        marks: &[([f32; 4], f32)],
5079    ) -> Result<Vec<u8>, RenderError> {
5080        let view = self.device.create_texture(TextureDesc {
5081            width,
5082            height,
5083            format: PixelFormat::Rgba8Unorm,
5084            cpu_readable: true,
5085        });
5086        let (fw, fh) = self.frame_size(doc);
5087        let (fw, fh) = (fw as f32, fh as f32);
5088        let (dw, dh) = (width as f32, height as f32);
5089        let s = (dw / fw).min(dh / fh);
5090        let rect = [(dw - fw * s) / 2.0, (dh - fh * s) / 2.0, fw * s, fh * s];
5091        let (sub, _) = self.submit_frame_with(doc, t, |o| {
5092            let mut p = o.header.to_vec();
5093            p.extend(o.origin);
5094            p.extend(rect);
5095            p.extend([dw, dh, 0.07, 0.07, 0.08]);
5096            p.extend(hud);
5097            // Edit outlines: frame-space bounds mapped into the view.
5098            p.push(marks.len().min(4) as f32);
5099            for k in 0..4 {
5100                match marks.get(k) {
5101                    Some((b, a)) => p.extend([
5102                        rect[0] + b[0] * s - 6.0,
5103                        rect[1] + b[1] * s - 6.0,
5104                        rect[0] + b[2] * s + 6.0,
5105                        rect[1] + b[3] * s + 6.0,
5106                        *a,
5107                    ]),
5108                    None => p.extend([0.0; 5]),
5109                }
5110            }
5111            o.list.dispatch_ex(
5112                &o.kernels.utility("k_present"),
5113                &view,
5114                &[o.texture],
5115                &p,
5116                ultrafast_gpu::Bindings {
5117                    grid: Some((width, height)),
5118                    ..Default::default()
5119                },
5120            );
5121        })?;
5122        sub.wait()?;
5123        Ok(self.device.readback(&view))
5124    }
5125
5126    /// Reads the last exported frame. Counted as a readback.
5127    pub fn read_export(&self) -> Vec<u8> {
5128        self.device
5129            .readback(self.export.as_ref().expect("no frame exported yet"))
5130    }
5131}
5132
5133/// Straight-alpha RGBA8 whose alpha rounded to 0 carries no color: the
5134/// encoder divides color by coverage, and coverage a hair above zero (the
5135/// tails exact-coverage rasterization leaves along a row) would otherwise
5136/// paint full color into transparent pixels, invisible when composited but
5137/// seen as streaks by anything that reads the color channels alone.
5138fn clear_transparent(px: &mut [u8]) {
5139    for p in px.chunks_exact_mut(4) {
5140        if p[3] == 0 {
5141            p[..3].fill(0);
5142        }
5143    }
5144}
5145
5146type Expansion = (Document, Vec<(String, String)>);
5147
5148/// Runs a node expansion on the document and inside every component (a
5149/// film pulled in as a component keeps its raymarch scenes and
5150/// transitions). None when nothing uses it.
5151/// Whether a node of the document or of one of its components is one of
5152/// `ops`.
5153fn uses_op(doc: &Document, ops: &[&str]) -> bool {
5154    let any = |nodes: &BTreeMap<String, ultrafast_graph::Node>| nodes.values().any(|n| ops.contains(&n.op.as_str()));
5155    any(&doc.nodes) || doc.components.values().any(|c| any(&c.nodes))
5156}
5157
5158fn expand_everywhere(
5159    doc: &Document,
5160    used_by: fn(&Document) -> bool,
5161    expand: fn(&Document) -> Expansion,
5162) -> Option<Expansion> {
5163    let as_doc = |c: &ultrafast_graph::Component| Document {
5164        version: doc.version,
5165        format: doc.format,
5166        output: c.output.clone(),
5167        nodes: c.nodes.clone(),
5168        components: Default::default(),
5169        revision: 0,
5170        structure_revision: 0,
5171        instance: 0,
5172    };
5173    let inner: Vec<&String> = doc
5174        .components
5175        .iter()
5176        .filter(|(_, c)| used_by(&as_doc(c)))
5177        .map(|(name, _)| name)
5178        .collect();
5179    if !used_by(doc) && inner.is_empty() {
5180        return None;
5181    }
5182    let (mut out, mut problems) = if used_by(doc) {
5183        expand(doc)
5184    } else {
5185        (doc.clone(), Vec::new())
5186    };
5187    for name in inner {
5188        let (d, p) = expand(&as_doc(&doc.components[name]));
5189        if let Some(c) = out.components.get_mut(name) {
5190            c.nodes = d.nodes;
5191        }
5192        problems.extend(p.into_iter().map(|(n, m)| (format!("{name}/{n}"), m)));
5193    }
5194    Some((out, problems))
5195}
5196
5197/// Whether rendering `doc` goes through [`Renderer::flattened`].
5198fn needs_flat(doc: &Document) -> bool {
5199    doc.needs_flatten()
5200        || builtins::used_by(doc)
5201        || svg::used_by(doc)
5202        || lottie::used_by(doc)
5203        || captions::used_by(doc)
5204        || follow::used_by(doc)
5205        || layout::used_by(doc)
5206        || blocks::used_by(doc)
5207        || code::used_by(doc)
5208        || raymarch::used_by(doc)
5209        || transitions::used_by(doc)
5210        || pushdown::wanted(doc)
5211        || !doc.components.is_empty()
5212}
5213
5214/// Kernel header: time, output texel size in frame pixels (the view's: 1
5215/// at the document's own size, 0.5 at twice it), frame width and height
5216/// (always the document's).
5217fn header(doc: &Document, t: f64, view: View) -> [f32; 4] {
5218    [t as f32, view.px, doc.format.width as f32, doc.format.height as f32]
5219}
5220
5221/// Loudness of `pcm` in a band, 120 values per second, with an instant
5222/// attack and a `release` (seconds), normalized so the loudest moment is 1.
5223fn audio_envelope(pcm: &ultrafast_media::audio::Pcm, band: &str, release: f64) -> Vec<f32> {
5224    let rate = ultrafast_media::audio::RATE as f32;
5225    let one_pole = |cut: f32| 1.0 - (-2.0 * std::f32::consts::PI * cut / rate).exp();
5226    let (lo_a, hi_a) = match band {
5227        "low" => (one_pole(160.0), 0.0),
5228        "mid" => (one_pole(2400.0), one_pole(250.0)),
5229        "high" => (1.0, one_pole(4500.0)),
5230        _ => (1.0, 0.0),
5231    };
5232    let win = (rate / 120.0) as usize;
5233    let mut out = Vec::with_capacity(pcm.frames() / win + 1);
5234    let (mut lp, mut hp_lp, mut acc, mut n) = (0.0f32, 0.0f32, 0.0f32, 0usize);
5235    for f in pcm.samples.chunks_exact(ultrafast_media::audio::CHANNELS) {
5236        let x = (f[0] + f[1]) * 0.5;
5237        lp += lo_a * (x - lp);
5238        hp_lp += hi_a * (lp - hp_lp);
5239        let y = lp - hp_lp;
5240        acc += y * y;
5241        n += 1;
5242        if n == win {
5243            out.push((acc / n as f32).sqrt());
5244            acc = 0.0;
5245            n = 0;
5246        }
5247    }
5248    // Peak follower: rises at once, falls over `release`.
5249    let fall = (-1.0 / (120.0 * release.max(1e-3) as f32)).exp();
5250    let mut e = 0.0f32;
5251    for v in out.iter_mut() {
5252        e = v.max(e * fall);
5253        *v = e;
5254    }
5255    let peak = out.iter().copied().fold(1e-9f32, f32::max);
5256    for v in out.iter_mut() {
5257        *v /= peak;
5258    }
5259    out
5260}
5261
5262/// Which groups can affect the output at time `t`: walk back from the
5263/// output; an inactive gated node keeps only its passthrough input alive.
5264fn live_groups(plan: &Plan, t: f64) -> Vec<bool> {
5265    let roots: Vec<usize> = plan.nodes.len().checked_sub(1).into_iter().collect();
5266    live_from(plan, t, &roots)
5267}
5268
5269/// Groups needed to evaluate `roots` (node indices) at time `t`.
5270fn live_from(plan: &Plan, t: f64, roots: &[usize]) -> Vec<bool> {
5271    let n = plan.nodes.len();
5272    let mut live = vec![false; n];
5273    let mut stack: Vec<usize> = roots.to_vec();
5274    while let Some(i) = stack.pop() {
5275        if live[i] {
5276            continue;
5277        }
5278        live[i] = true;
5279        let pn = &plan.nodes[i];
5280        if pn.gated && !local_time(pn, t).1 {
5281            if let Some(k) = ops::passthrough(pn.def, pn.inputs.len()) {
5282                stack.push(pn.inputs[k]);
5283            }
5284            continue;
5285        }
5286        stack.extend(pn.inputs.iter().copied());
5287    }
5288    plan.groups.iter().map(|g| g.nodes.iter().any(|&m| live[m])).collect()
5289}
5290
5291/// Local time of a node at composition time `t`, and whether it is active
5292/// (inside every visibility window of its timing chain).
5293/// Per blur group, the fused groups reading it when every reader samples
5294/// its inputs where it needs them (fused groups outside their loops, which
5295/// read layer textures texel for texel, and other blurs): such a blur can
5296/// stay at the reduced resolution it is computed at. Never the output.
5297fn low_readers(plan: &Plan) -> Vec<Option<Vec<usize>>> {
5298    let ng = plan.groups.len();
5299    (0..ng)
5300        .map(|g| {
5301            if plan.groups[g].kind != GroupKind::Blur || g + 1 == ng {
5302                return None;
5303            }
5304            let mut fused = Vec::new();
5305            for (c, gr) in plan.groups.iter().enumerate() {
5306                let bindings: Vec<usize> = (0..gr.textures.len())
5307                    .filter(|&b| gr.textures[b] == TexSource::Group(g))
5308                    .collect();
5309                if bindings.is_empty() {
5310                    continue;
5311                }
5312                match gr.kind {
5313                    GroupKind::Blur => {}
5314                    GroupKind::Fused
5315                        if !gr.runs.iter().any(|r| {
5316                            r.layers
5317                                .iter()
5318                                .any(|(_, _, l)| matches!(l, codegen::LayerRef::Texture(b) if bindings.contains(b)))
5319                        }) =>
5320                    {
5321                        fused.push(c)
5322                    }
5323                    _ => return None,
5324                }
5325            }
5326            Some(fused)
5327        })
5328        .collect()
5329}
5330
5331/// A group's output as its readers see it (through passthroughs).
5332fn placed_output(active: &Active, mut gi: usize) -> Placed {
5333    while let Some(src) = active.alias[gi] {
5334        gi = src;
5335    }
5336    match &active.raster[gi] {
5337        Some(p) => p.clone(),
5338        None => Placed {
5339            tex: active.slots[active.plan.groups[gi].output].clone(),
5340            origin: [0.0, 0.0],
5341            scale: active.view.px,
5342        },
5343    }
5344}
5345
5346/// How far (frame px) a `transform` node moves what it shows between local
5347/// times l0 and l1: the largest shift of any point of the frame.
5348fn transform_motion_px(node: &ultrafast_graph::Node, fmt: &ultrafast_graph::Format, l0: f64, l1: f64) -> f64 {
5349    let a0 = ops::transform_affine(node, fmt, l0);
5350    let a1 = ops::transform_affine(node, fmt, l1);
5351    let Some(back) = a0.inverse() else {
5352        return f64::INFINITY;
5353    };
5354    let m = a1.mul(back);
5355    let (w, h) = (fmt.width as f64, fmt.height as f64);
5356    [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)]
5357        .iter()
5358        .map(|&(x, y)| {
5359            let (u, v) = m.apply(x, y);
5360            (u - x).hypot(v - y)
5361        })
5362        .fold(0.0, f64::max)
5363}
5364
5365/// The absorbed transforms of a raster chain as one affine at time `t`. A
5366/// timed transform outside its window passes its source through, so it adds
5367/// nothing.
5368pub(crate) fn absorbed(plan: &Plan, doc: &Document, transforms: &[usize], t: f64) -> ops::Affine {
5369    transforms.iter().fold(ops::Affine::IDENTITY, |acc, &ti| {
5370        let tn = &plan.nodes[ti];
5371        match local_time(tn, t) {
5372            (lt, true) => ops::transform_affine(&doc.nodes[&tn.id], &doc.format, lt).mul(acc),
5373            (_, false) => acc,
5374        }
5375    })
5376}
5377
5378/// Per plan node, where its output is fully opaque at `t` ([`ops::opaque`],
5379/// in its own space): an inactive node shows its passthrough input, or
5380/// nothing.
5381pub(crate) fn opaque_rects(plan: &Plan, doc: &Document, t: f64) -> Vec<ops::Rect> {
5382    let mut out = vec![ops::EMPTY; plan.nodes.len()];
5383    for (i, pn) in plan.nodes.iter().enumerate() {
5384        let ins: Vec<ops::Rect> = pn.inputs.iter().map(|&c| out[c]).collect();
5385        out[i] = match (local_time(pn, t), doc.nodes.get(&pn.id)) {
5386            ((lt, true), Some(node)) => ops::opaque(pn.def, node, &doc.format, lt, &ins),
5387            ((_, true), None) => ops::EMPTY,
5388            ((_, false), _) => ops::passthrough(pn.def, ins.len())
5389                .map(|k| ins[k])
5390                .unwrap_or(ops::EMPTY),
5391        };
5392    }
5393    out
5394}
5395
5396fn local_time(n: &plan::PlanNode, t: f64) -> (f64, bool) {
5397    match ultrafast_graph::resolve_chain(&n.chain, t) {
5398        Some(lt) => (lt, true),
5399        None => (t, false),
5400    }
5401}
5402
5403fn pn_has(node: &ultrafast_graph::Node, param: &str) -> bool {
5404    node.params.contains_key(param)
5405}
5406
5407fn f32_bytes(v: &[f32]) -> &[u8] {
5408    unsafe { std::slice::from_raw_parts(v.as_ptr().cast::<u8>(), std::mem::size_of_val(v)) }
5409}
5410
5411fn u32_bytes(v: &[u32]) -> &[u8] {
5412    unsafe { std::slice::from_raw_parts(v.as_ptr().cast::<u8>(), std::mem::size_of_val(v)) }
5413}
5414
5415/// Hash of every parameter a 3D pass depends on, for static caching.
5416fn scene_key(plan: &Plan, g: &plan::Group, doc: &Document, t: f64) -> u64 {
5417    use std::hash::{Hash, Hasher};
5418    let mut h = std::collections::hash_map::DefaultHasher::new();
5419    for &m in &g.nodes {
5420        let pn = &plan.nodes[m];
5421        let (lt, on) = local_time(pn, t);
5422        on.hash(&mut h);
5423        geom::geometry_key(&doc.nodes[&pn.id], lt, &ops::Affine::IDENTITY).hash(&mut h);
5424    }
5425    h.finish()
5426}
5427
5428/// Bounds of node `ni`'s output as seen inside group `g` (for guards).
5429/// Nodes outside the group are textures: their bounds are the placed
5430/// texture's extent.
5431fn subtree_bounds(
5432    plan: &Plan,
5433    g: &plan::Group,
5434    ni: usize,
5435    doc: &Document,
5436    t: f64,
5437    inputs: &[Placed],
5438    res_info: &HashMap<&str, ResourceInfo>,
5439    content: &[ops::Rect],
5440) -> ops::Rect {
5441    if !plan.in_group(plan.group_of[g.root], ni) {
5442        let gs = plan.group_of[ni];
5443        return match g.textures.iter().position(|ts| *ts == TexSource::Group(gs)) {
5444            Some(i) => intersect(extent(&inputs[i]), content[gs]),
5445            None => ops::UNBOUNDED,
5446        };
5447    }
5448    let pn = &plan.nodes[ni];
5449    let (lt, on) = local_time(pn, t);
5450    let mut buf = [ops::EMPTY; 8];
5451    let heap: Vec<ops::Rect>;
5452    let ins: &[ops::Rect] = if pn.inputs.len() <= buf.len() {
5453        for (k, &c) in pn.inputs.iter().enumerate() {
5454            buf[k] = subtree_bounds(plan, g, c, doc, t, inputs, res_info, content);
5455        }
5456        &buf[..pn.inputs.len()]
5457    } else {
5458        heap = pn
5459            .inputs
5460            .iter()
5461            .map(|&c| subtree_bounds(plan, g, c, doc, t, inputs, res_info, content))
5462            .collect();
5463        &heap
5464    };
5465    if !on {
5466        return ops::passthrough(pn.def, ins.len())
5467            .map(|i| ins[i])
5468            .unwrap_or(ops::EMPTY);
5469    }
5470    let info = if ops::uses_resource(pn.def) {
5471        res_info.get(pn.variant.as_str()).copied()
5472    } else {
5473        None
5474    };
5475    ops::bounds(pn.def, &doc.nodes[&pn.id], &doc.format, lt, ins, info)
5476}
5477
5478/// The earlier group whose output equals fused group `g`'s at `t`, when
5479/// all `g` would do is pass it through: inactive layers and effects pass
5480/// their source, a composite over an empty foreground its background.
5481#[allow(clippy::too_many_arguments)]
5482fn passthrough_group(
5483    plan: &Plan,
5484    g: &plan::Group,
5485    ni: usize,
5486    doc: &Document,
5487    t: f64,
5488    inputs: &[Placed],
5489    res_info: &HashMap<&str, ResourceInfo>,
5490    content: &[ops::Rect],
5491) -> Option<usize> {
5492    if !plan.in_group(plan.group_of[g.root], ni) {
5493        let gs = plan.group_of[ni];
5494        return g.textures.contains(&TexSource::Group(gs)).then_some(gs);
5495    }
5496    let pn = &plan.nodes[ni];
5497    if !local_time(pn, t).1 {
5498        let i = ops::passthrough(pn.def, pn.inputs.len())?;
5499        return passthrough_group(plan, g, pn.inputs[i], doc, t, inputs, res_info, content);
5500    }
5501    if pn.def.name == "over" && pn.inputs.len() == 2 {
5502        let fg = subtree_bounds(plan, g, pn.inputs[0], doc, t, inputs, res_info, content);
5503        if fg[0] >= fg[2] || fg[1] >= fg[3] {
5504            return passthrough_group(plan, g, pn.inputs[1], doc, t, inputs, res_info, content);
5505        }
5506    }
5507    None
5508}
5509
5510/// Frame extent of a placed texture.
5511fn extent(p: &Placed) -> ops::Rect {
5512    let d = p.tex.desc();
5513    let (x, y, s) = (p.origin[0] as f64, p.origin[1] as f64, p.scale as f64);
5514    [x, y, x + d.width as f64 * s, y + d.height as f64 * s]
5515}
5516
5517fn intersect(a: ops::Rect, b: ops::Rect) -> ops::Rect {
5518    [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]
5519}
5520
5521#[cfg(test)]
5522mod tests {
5523    use super::*;
5524
5525    #[test]
5526    fn a_reveal_keyed_short_of_its_text_is_flagged() {
5527        let text = |reveal: &str| -> ultrafast_graph::Node {
5528            serde_json::from_str(&format!(r#"{{"op":"text","params":{{"text":"x","reveal":{reveal}}}}}"#)).unwrap()
5529        };
5530        // The title template's subtitle: 24 glyphs typed in.
5531        let typed = text(r#"{"keys":[{"t":1,"v":0},{"t":2,"v":24}]}"#);
5532        assert_eq!(reveal_falls_short(&typed, 24), None);
5533        assert_eq!(reveal_falls_short(&typed, 20), None);
5534        let m = reveal_falls_short(&typed, 31).unwrap();
5535        assert!(
5536            m.starts_with("text: ") && m.contains("the last 7 of its 31 glyphs never show") && m.ends_with("up to 31"),
5537            "{m}"
5538        );
5539        // A soft reveal needs its softness past the last glyph: type.json's
5540        // 33 glyphs at softness 4 stopped at 34, leaving "PU" faded and low.
5541        let soft = text(r#"{"keys":[{"t":0,"v":0},{"t":2,"v":34}]},"reveal_softness":4"#);
5542        let m = reveal_falls_short(&soft, 33).unwrap();
5543        assert!(
5544            m.contains("the last 2 of its 33 glyphs") && m.ends_with("up to 36"),
5545            "{m}"
5546        );
5547        assert_eq!(
5548            Diagnostic {
5549                node: "sub".into(),
5550                message: m
5551            }
5552            .severity(),
5553            "warning"
5554        );
5555        // A fixed reveal shows part of the text on purpose.
5556        assert_eq!(reveal_falls_short(&text("5"), 31), None);
5557    }
5558}