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