Skip to main content

rlx_core/render/scenes/
fragment_field.rs

1//! Fragment-field scene: a fullscreen Shadertoy-style domain-warped field,
2//! colored through the shared palette LUT (ADR-0021). The first "generative-art"-
3//! tier built-in and one of the two preset-driven systems (ADR-0002 layers 1-2).
4//!
5//! Its look is a set of named parameters — `warp`, `hue`, `zoom`, `glow`,
6//! `flash`, plus the shared color knobs `color_span`/`color_center`/`saturation`
7//! (Plan 0020) — that a preset binds to expressions over the audio analysis (Plan
8//! 0003 Phase 5). With no preset the parameter defaults render a gentle idle
9//! field. The scene reads no audio directly; all reactivity flows through the
10//! parameter values.
11//!
12//! Color: the field level indexes a 256-entry gradient LUT (the preset's
13//! `[palette]`, default `spectrum` = the exact prior cosine) instead of a
14//! hardcoded `palette()`. `color_span` sets how much of the gradient the field
15//! spans (replacing the old fixed `field*0.6`), `color_center`/`hue` slide the
16//! window, and `saturation` desaturates toward luma — all bindable.
17
18// Hot-path panic-denial pragma (Plan 0002 Phase 2, extended to scenes by Plan
19// 0003 Phase 0). Runs every displayed frame.
20#![deny(
21    clippy::unwrap_used,
22    clippy::expect_used,
23    clippy::indexing_slicing,
24    clippy::panic,
25    clippy::unreachable
26)]
27
28use crate::render::gpu;
29
30use super::common;
31use super::{Phase, Scene};
32use crate::dsp::AnalysisFrame;
33use crate::render::palette::{self, Palette};
34use crate::render::scenes::{ParamGroup, ParamKind, ParamSpec, default_of};
35
36/// Parameter defaults — a calm idle field when nothing is bound.
37const DEFAULT_WARP: f32 = default_of(PARAMS, "warp");
38const DEFAULT_HUE: f32 = 0.0;
39const DEFAULT_ZOOM: f32 = 1.0;
40const DEFAULT_GLOW: f32 = default_of(PARAMS, "glow");
41const DEFAULT_FLASH: f32 = default_of(PARAMS, "flash");
42// Shared palette color knobs (ADR-0021). `color_span` = 0.6 + `color_center` = 0
43// + `saturation` = 1 reproduce the prior look exactly (the old `field*0.6` sample
44// with no desaturation).
45const DEFAULT_COLOR_SPAN: f32 = default_of(PARAMS, "color_span");
46const DEFAULT_COLOR_CENTER: f32 = default_of(PARAMS, "color_center");
47/// The two rate parameters (ADR-0132), in units of the scene's own default
48/// speed. `1.0` is what this scene has always animated at, so a preset that
49/// binds neither renders exactly as before.
50const DEFAULT_FIELD_SPEED: f32 = default_of(PARAMS, "field_speed");
51const DEFAULT_FOLD_SPEED: f32 = default_of(PARAMS, "fold_speed");
52
53const SHADER: &str = r#"
54struct Params {
55    // x: time (s), y: aspect, z: warp, w: hue
56    a: vec4<f32>,
57    // x: zoom, y: glow, z: flash, w: color_span
58    b: vec4<f32>,
59    // xy: pan (field-space offset, ADR-0018), z: color_center, w: saturation
60    c: vec4<f32>,
61    // x: palette_mix (A/B crossfade), y: occlude (ADR-0085),
62    // z: palette_steps (integral, quantized CPU-side), w: palette_contour (ADR-0078)
63    d: vec4<f32>,
64    // x: fold phase, y: field phase (ADR-0132) — both INTEGRATED on the CPU
65    // (`phase += rate * dt`) rather than derived here from `t * rate`. At a
66    // constant rate a phase equals `rate * t`, so the defaults reproduce the
67    // literals these replaced; what integration buys is that a rate BOUND TO
68    // AUDIO bends the motion instead of teleporting it — at t = 100 s a
69    // `warp_speed`-style multiply would move the phase fifty seconds in one
70    // frame. z: palette_contour_style (integral, rounded CPU-side),
71    // w: palette_contour_ink (ADR-0197)
72    e: vec4<f32>,
73}
74
75@group(0) @binding(0) var<uniform> params: Params;
76// The gradient LUTs sit in their own bind group (group 1), so this pipeline's
77// layout stays distinct from the screen-space kaleidoscope's single 3-entry
78// [uniform, texture, sampler] group — two byte-identical layouts mis-render when
79// they coexist on the DX12 WARP software adapter (the same quirk the shared line
80// renderer and the lazy feedback scenes work around). Two LUTs (A/B) for the
81// `palette_mix` crossfade; one shared sampler.
82@group(1) @binding(0) var lut_a: texture_2d<f32>;
83@group(1) @binding(1) var lut_b: texture_2d<f32>;
84@group(1) @binding(2) var lut_samp: sampler;
85
86// Shared `saturation` (mirrors core/src/render/palette.rs::desaturate verbatim):
87// scale chroma around Rec. 601 luma. 1.0 unchanged, 0.0 grayscale.
88fn apply_saturation(c: vec3<f32>, s: f32) -> vec3<f32> {
89    let luma = dot(c, vec3<f32>(0.299, 0.587, 0.114));
90    return vec3<f32>(luma) + (c - vec3<f32>(luma)) * s;
91}
92
93// Shared `palette_steps` (mirrors core/src/render/palette.rs::band_coord
94// verbatim, ADR-0078): snap the palette coordinate to a band centre before the
95// LUT read. Below 1.5 steps it is the exact identity, not a one-band degenerate.
96fn band_coord(t: f32, steps: f32) -> f32 {
97    if (steps < 1.5) {
98        return t;
99    }
100    return (floor(t * steps) + 0.5) / steps;
101}
102
103// Shared `palette_contour` (ADR-0078 / ADR-0133; the WGSL is the implementation,
104// copied verbatim at each fragment-stage site — palette.rs has no CPU
105// counterpart to be canonical, since `fwidth` exists only here).
106//
107// Darkens within one PIXEL of a band edge, so the line has the same weight where
108// the field is shallow and where it is steep — AND ONLY WHERE THE INK ACTUALLY
109// CHANGES (ADR-0133). It samples the two band centres either side of the nearest
110// edge and returns unchanged when they resolve to the same colour within half a
111// code value, which is below the LUT's own 8-bit quantization. On a smooth
112// palette two distinct centres always differ by at least one code value, so
113// every edge draws exactly as it did at any `palette_steps`; inside a plateau
114// the LUT is literally constant and the samples are bit-equal, so the line
115// vanishes there and survives at the run boundaries. One rule, both behaviours,
116// no new parameter.
117//
118// The two LUTs, the sampler and `palette_mix` are EXPLICIT parameters rather
119// than module-scope globals this happens to find: all six sites name them the
120// same today, so implicit capture would compile — and would silently bind the
121// shared function to whatever a future site called its textures.
122//
123// `textureSampleLevel`, not `textureSample`: the LUT has one mip, and an
124// explicit LOD keeps these reads free of the uniformity requirement that a
125// sample after a conditional return would otherwise carry.
126//
127// **What the line is drawn in is `style`** (ADR-0197): `0` the soft darkening
128// above, `1` a hard darkening over the same footprint, `2` a soft line in the
129// palette's own colour at `ink_t` and `3` a hard one. `style` arrives rounded to
130// a whole number from the CPU (`palette::band_contour_style`), so the equality
131// comparisons below are exact. The `style < 0.5` arm is the expression that
132// shipped before the other three existed, which is what keeps every golden still.
133fn band_contour_ink(
134    col: vec3<f32>,
135    t: f32,
136    steps: f32,
137    amount: f32,
138    style: f32,
139    ink_t: f32,
140    lut_a: texture_2d<f32>,
141    lut_b: texture_2d<f32>,
142    lut_samp: sampler,
143    mix_ab: f32,
144) -> vec3<f32> {
145    let f = t * steps;
146    let w = max(fwidth(f), 1e-5);
147    if (steps < 1.5 || amount <= 0.0) {
148        return col;
149    }
150    let n = round(f);
151    let m = clamp(mix_ab, 0.0, 1.0);
152    let lo = mix(
153        textureSampleLevel(lut_a, lut_samp, vec2<f32>((n - 0.5) / steps, 0.5), 0.0).rgb,
154        textureSampleLevel(lut_b, lut_samp, vec2<f32>((n - 0.5) / steps, 0.5), 0.0).rgb,
155        m
156    );
157    let hi = mix(
158        textureSampleLevel(lut_a, lut_samp, vec2<f32>((n + 0.5) / steps, 0.5), 0.0).rgb,
159        textureSampleLevel(lut_b, lut_samp, vec2<f32>((n + 0.5) / steps, 0.5), 0.0).rgb,
160        m
161    );
162    if (all(abs(hi - lo) < vec3<f32>(0.5 / 255.0))) {
163        return col;
164    }
165    let d = min(fract(f), 1.0 - fract(f));
166    if (style < 0.5) {
167        return col * (1.0 - clamp(amount, 0.0, 1.0) * (1.0 - smoothstep(0.0, w, d)));
168    }
169    let hard = style == 1.0 || style == 3.0;
170    let cover = select(1.0 - smoothstep(0.0, w, d), f32(d < w), hard);
171    let ink_lut = mix(
172        textureSampleLevel(lut_a, lut_samp, vec2<f32>(ink_t, 0.5), 0.0).rgb,
173        textureSampleLevel(lut_b, lut_samp, vec2<f32>(ink_t, 0.5), 0.0).rgb,
174        m
175    );
176    let ink = select(vec3<f32>(0.0), ink_lut, style >= 2.0);
177    return mix(col, ink, clamp(amount, 0.0, 1.0) * cover);
178}
179
180@fragment
181fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
182    let t = params.a.x;
183    let aspect = params.a.y;
184    let warp = params.a.z;
185    let hue = params.a.w;
186    let zoom = params.b.x;
187    let glow = params.b.y;
188    let flash = params.b.z;
189    let color_span = params.b.w;
190    let pan = params.c.xy;
191    let color_center = params.c.z;
192    let saturation = params.c.w;
193    let palette_mix = params.d.x;
194    let palette_steps = params.d.z;
195    let palette_contour = params.d.w;
196    let fold_phase = params.e.x;
197    let field_phase = params.e.y;
198    let palette_contour_style = params.e.z;
199    let palette_contour_ink = params.e.w;
200
201    var uv = in.ndc;
202    uv.x = uv.x * aspect;
203
204    // Iterated sine-fold domain warp, scaled by zoom and folded by warp; `pan`
205    // slides the sampled field window (the shared ViewTransform, ADR-0018). The
206    // vignette below stays screen-anchored (uses unshifted `uv`).
207    var p = uv * zoom + pan;
208    // The fold's two rates keep their designed 0.7 : 0.6 quadrature ratio; what
209    // `fold_speed` scales is the phase they share, so slowing the fold does not
210    // flatten it the way `warp` does (ADR-0132).
211    for (var i = 0; i < 5; i = i + 1) {
212        let fi = f32(i);
213        p = p + warp * vec2<f32>(
214            sin(p.y * 1.5 + fold_phase * 0.7 + fi),
215            cos(p.x * 1.5 - fold_phase * 0.6 + fi)
216        ) / (fi + 1.0);
217    }
218
219    let field = 0.5 + 0.5 * sin(p.x + p.y + field_phase * 0.5);
220    // Field level indexes the gradient LUT: `color_span` sets the spanned range
221    // (was a fixed 0.6), `color_center`/`hue` slide the window. Linear-filtered,
222    // repeat-addressed (a hue rotation wraps like the cosine wheel).
223    let coord = field * color_span + color_center + hue;
224    // Hard bands, then the contour drawn from the SAME coordinate (ADR-0078), so
225    // the dark line follows the field's iso-lines and reads as structure rather
226    // than as an outline of the picture's brightness.
227    let banded = band_coord(coord, palette_steps);
228    // Sample both palettes and crossfade by `palette_mix` (0 = A, 1 = B). When a
229    // preset declares no [palette_b] the two LUTs are identical, so mix is a no-op.
230    let ca = textureSample(lut_a, lut_samp, vec2<f32>(banded, 0.5)).rgb;
231    let cb = textureSample(lut_b, lut_samp, vec2<f32>(banded, 0.5)).rgb;
232    var col = mix(ca, cb, clamp(palette_mix, 0.0, 1.0));
233    col = band_contour_ink(
234        col, coord, palette_steps, palette_contour, palette_contour_style,
235        palette_contour_ink, lut_a, lut_b, lut_samp, palette_mix
236    );
237    col = apply_saturation(col, saturation);
238
239    let r = length(uv);
240    col = col * (glow * (1.0 - 0.25 * r));
241    col = col + vec3<f32>(flash * 0.12);
242
243    // Alpha is `occlude` (`params.d.y`). The field covers every pixel, which is the
244    // coverage it honestly has (ADR-0056), and `occlude` scales how much backdrop
245    // survives underneath it (ADR-0085): the fold resolves `field + bg * (1 -
246    // occlude)`, so at 1 the field replaces the backdrop and at 0 the backdrop adds
247    // through at full strength. The renderer hands a value other than a literal 1.0
248    // only when the scene draws straight onto the destination — with a post stage
249    // routed, or the `over` junction live, the scene renders into a scratch and the
250    // chain's last fold owns the seam instead.
251    return vec4<f32>(col, params.d.y);
252}
253"#;
254
255#[repr(C)]
256#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
257struct Params {
258    a: [f32; 4],
259    b: [f32; 4],
260    c: [f32; 4],
261    d: [f32; 4],
262    e: [f32; 4],
263}
264
265/// Fullscreen domain-warped fragment field, driven by named preset parameters.
266pub struct FragmentFieldScene {
267    /// The pipeline, the uniform buffer, the 256×1 gradient LUT pair (A/B) the
268    /// fragment samples + crossfades for colour (ADR-0021), and the two bind
269    /// groups. The LUT group is **group 1**, separate from the uniform group, so
270    /// this pipeline's layout does not match the kaleidoscope's.
271    gpu: gpu::FullscreenScene,
272    /// Shared scene clock (seconds), set by the renderer each frame.
273    time: f32,
274    /// This frame's elapsed real time, stored by `advance` and consumed by
275    /// `update`, where the phases step against this frame's bound rates
276    /// (ADR-0132).
277    dt: f32,
278    /// The integrated fold and field phases ([`Phase`]). **These are the scene's
279    /// only state**: everything else here is derived from `time` and the
280    /// parameters, so a capture's reproducibility now depends on the scene being
281    /// rebuilt with the preset as well as on the clock resetting
282    /// (`reset_for_capture` does both).
283    ///
284    /// They stay two accumulators rather than one, because each follows its own
285    /// rate: `fold_speed` and `field_speed` are separately bindable.
286    fold_phase: Phase,
287    field_phase: Phase,
288    /// Animation rates, in units of the scene's default speed (ADR-0132).
289    field_speed: f32,
290    fold_speed: f32,
291    warp: f32,
292    /// The shared palette knobs (ADR-0021). This scene has no `brightness`.
293    colour: common::PaletteParams,
294    /// The shared view transform (ADR-0018): `pan_*` offset the sampled field
295    /// window, on top of `zoom`.
296    pan: common::PanParams,
297    zoom: f32,
298    glow: f32,
299    flash: f32,
300    color_span: f32,
301    color_center: f32,
302    /// How much of this field's (total) coverage the backdrop resolves against
303    /// (ADR-0085). Set by the renderer every frame through
304    /// [`Scene::set_occlude`](super::Scene::set_occlude) — **not** a named param,
305    /// so it is not reset by `reset_params`.
306    occlude: f32,
307}
308
309impl FragmentFieldScene {
310    /// Build the scene's pipeline and uniform buffer on `device`.
311    pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> Self {
312        let shader = gpu::fullscreen_shader(
313            device,
314            "fragment-field-shader",
315            gpu::FULLSCREEN_VS_NDC,
316            SHADER,
317        );
318        let parts =
319            gpu::FullscreenParts::new(device, "fragment-field", std::mem::size_of::<Params>());
320        let uniform_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
321            label: Some("fragment-field-uniform-layout"),
322            entries: &[gpu::uniform(0, wgpu::ShaderStages::FRAGMENT)],
323        });
324        // The LUT texture + sampler live in their own group (group 1) — see the
325        // WGSL note: keeping this pipeline's layout distinct from the
326        // kaleidoscope's avoids the DX12 WARP identical-layout mis-render.
327        let lut_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
328            label: Some("fragment-field-lut-layout"),
329            entries: &[
330                gpu::texture(0, true),
331                gpu::texture(1, true),
332                gpu::sampler(2),
333            ],
334        });
335        let uniform_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
336            label: Some("fragment-field-uniform-bg"),
337            layout: &uniform_layout,
338            entries: &[wgpu::BindGroupEntry {
339                binding: 0,
340                resource: parts.uniforms().as_entire_binding(),
341            }],
342        });
343        let lut_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
344            label: Some("fragment-field-lut-bg"),
345            layout: &lut_layout,
346            entries: &parts.luts().bind_entries(0, 1, 2),
347        });
348
349        Self {
350            gpu: parts.finish(
351                device,
352                &shader,
353                &[&uniform_layout, &lut_layout],
354                uniform_bg,
355                Some(lut_bg),
356                surface_format,
357                wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
358                "fragment-field",
359            ),
360            time: 0.0,
361            dt: crate::render::scenes::FALLBACK_DT,
362            fold_phase: Phase::default(),
363            field_phase: Phase::default(),
364            field_speed: DEFAULT_FIELD_SPEED,
365            fold_speed: DEFAULT_FOLD_SPEED,
366            warp: DEFAULT_WARP,
367            colour: common::PaletteParams::new(DEFAULT_HUE, common::DEFAULT_BRIGHTNESS),
368            pan: common::PanParams::default(),
369            zoom: DEFAULT_ZOOM,
370            glow: DEFAULT_GLOW,
371            flash: DEFAULT_FLASH,
372            color_span: DEFAULT_COLOR_SPAN,
373            color_center: DEFAULT_COLOR_CENTER,
374            occlude: crate::render::post::DEFAULT_OCCLUDE,
375        }
376    }
377}
378
379/// The parameter names this scene consumes — the vocabulary a preset binding
380/// is checked against at load, so a typo is warned about instead of silently
381/// doing nothing (ADR-0020). **Keep in sync with `set_param` below**; the
382/// `declared_params_match_set_param` guard in `core/tests/suite/preset.rs` fails if
383/// the two drift.
384pub const PARAMS: &[ParamSpec] = &[
385    ParamSpec {
386        name: "warp",
387        default: 0.4,
388        range: Some([0.0, 1.5]),
389        doc: "Amplitude of the domain fold; 0 flattens the field into plain bands.",
390        kind: ParamKind::Modal,
391        group: ParamGroup::Shape,
392        main: true,
393    },
394    ParamSpec {
395        name: "field_speed",
396        default: 1.0,
397        range: Some([0.0, 4.0]),
398        doc: "How fast the field itself drifts, as a multiple of its base rate.",
399        kind: ParamKind::Modal,
400        group: ParamGroup::Motion,
401        main: true,
402    },
403    ParamSpec {
404        name: "fold_speed",
405        default: 1.0,
406        range: Some([0.0, 4.0]),
407        doc: "How fast the fold turns, independently of the field's own drift.",
408        kind: ParamKind::Modal,
409        group: ParamGroup::Motion,
410        main: false,
411    },
412    crate::render::scenes::common::hue(DEFAULT_HUE),
413    crate::render::scenes::common::zoom(DEFAULT_ZOOM),
414    ParamSpec {
415        name: "glow",
416        default: 0.7,
417        range: Some([0.0, 2.0]),
418        doc: "Overall light the field emits, before the composite sees it.",
419        kind: ParamKind::Modal,
420        group: ParamGroup::Light,
421        main: true,
422    },
423    ParamSpec {
424        name: "flash",
425        default: 0.0,
426        range: Some([0.0, 1.0]),
427        doc: "Lifts the whole field toward white, for a beat-driven blink.",
428        kind: ParamKind::Modal,
429        group: ParamGroup::Light,
430        main: false,
431    },
432    crate::render::scenes::common::PAN_X,
433    crate::render::scenes::common::PAN_Y,
434    ParamSpec {
435        name: "color_span",
436        default: 0.6,
437        range: Some([0.0, 1.0]),
438        doc: "How much of the palette the field's range covers; 0 is one flat colour.",
439        kind: ParamKind::Modal,
440        group: ParamGroup::Colour,
441        main: false,
442    },
443    ParamSpec {
444        name: "color_center",
445        default: 0.0,
446        range: Some([-1.0, 1.0]),
447        doc: "Shifts which part of the field's range lands in the middle of the palette.",
448        kind: ParamKind::Modal,
449        group: ParamGroup::Colour,
450        main: false,
451    },
452    crate::render::scenes::common::SATURATION,
453    crate::render::scenes::common::PALETTE_MIX,
454    crate::render::scenes::common::PALETTE_STEPS,
455    crate::render::scenes::common::PALETTE_CONTOUR,
456    crate::render::scenes::common::PALETTE_CONTOUR_STYLE,
457    crate::render::scenes::common::PALETTE_CONTOUR_INK,
458];
459
460impl Scene for FragmentFieldScene {
461    fn name(&self) -> &'static str {
462        "fragment field"
463    }
464
465    fn set_time(&mut self, time: f32) {
466        self.time = time;
467    }
468
469    fn advance(&mut self, dt: f32) {
470        // Stored, not integrated: `update` steps both phases, so the scene has
471        // one integration site (ADR-0132).
472        self.dt = dt;
473    }
474
475    fn set_occlude(&mut self, occlude: f32) {
476        self.occlude = occlude;
477    }
478
479    fn set_palette(&mut self, palette: &Palette) {
480        // Store the baked LUT; `render` uploads it (deferred so scenes with lazy
481        // GPU resources share this seam). Cheap array copy, off the hot path.
482        self.gpu.set_palette(palette);
483    }
484
485    fn reset_params(&mut self) {
486        // The two rates reset with every other param; the PHASES do not — they
487        // are state, and resetting them each frame would be the multiply this
488        // ADR exists to remove.
489        self.field_speed = DEFAULT_FIELD_SPEED;
490        self.fold_speed = DEFAULT_FOLD_SPEED;
491        self.warp = DEFAULT_WARP;
492        self.colour.reset();
493        self.pan.reset();
494        self.zoom = DEFAULT_ZOOM;
495        self.glow = DEFAULT_GLOW;
496        self.flash = DEFAULT_FLASH;
497        self.color_span = DEFAULT_COLOR_SPAN;
498        self.color_center = DEFAULT_COLOR_CENTER;
499    }
500
501    fn set_param(&mut self, name: &str, value: f32) {
502        // The shared param blocks first, this scene's own names after
503        // (`scenes::common`).
504        if self.colour.set(name, value) || self.pan.set(name, value) {
505            return;
506        }
507        match name {
508            "warp" => self.warp = value,
509            "field_speed" => self.field_speed = value,
510            "fold_speed" => self.fold_speed = value,
511            "zoom" => self.zoom = value,
512            "glow" => self.glow = value,
513            "flash" => self.flash = value,
514            "color_span" => self.color_span = value,
515            "color_center" => self.color_center = value,
516            _ => {}
517        }
518    }
519
520    fn update(&mut self, _frame: &AnalysisFrame) {
521        // Fully parameter-driven; the analysis reaches this scene only through
522        // the preset expressions bound to its parameters. The one thing that
523        // happens here is the phase integration, which runs after `set_param`
524        // so it uses this frame's rates (ADR-0132).
525        self.fold_phase.step(self.fold_speed, self.dt);
526        self.field_phase.step(self.field_speed, self.dt);
527    }
528
529    fn render(
530        &mut self,
531        queue: &wgpu::Queue,
532        encoder: &mut wgpu::CommandEncoder,
533        view: &wgpu::TextureView,
534        aspect: f32,
535    ) {
536        // Upload the active palette LUTs (A + B) if a preset switch changed them
537        // (off the hot path — once per switch, not per frame).
538        self.gpu.flush_palette(queue);
539
540        let params = Params {
541            a: [self.time, aspect.max(0.1), self.warp, self.colour.hue],
542            b: [self.zoom, self.glow, self.flash, self.color_span],
543            c: [
544                self.pan.x,
545                self.pan.y,
546                self.color_center,
547                self.colour.saturation,
548            ],
549            d: [
550                self.colour.mix,
551                self.occlude,
552                palette::band_steps(self.colour.steps),
553                palette::band_contour(self.colour.contour),
554            ],
555            e: [
556                self.fold_phase.get(),
557                self.field_phase.get(),
558                palette::band_contour_style(self.colour.contour_style),
559                self.colour.contour_ink,
560            ],
561        };
562        self.gpu.write_uniform(queue, &params);
563
564        // Load over the engine backdrop (ADR-0018). The present blends
565        // premultiplied-OVER with alpha `occlude`, so the backdrop resolves as
566        // `field + bg * (1 - occlude)`: covered at 1 (exactly a replace), added
567        // to at 0.
568        self.gpu
569            .draw(encoder, "fragment-field-pass", view, wgpu::LoadOp::Load);
570    }
571}
572
573#[cfg(test)]
574mod tests {
575    use super::*;
576
577    /// The property ADR-0132 exists for, and the one a `time * rate` multiply
578    /// fails: a rate change moves the phase by `rate * dt` **whatever the
579    /// elapsed scene time**. Under a multiply the same change at t = 100 s
580    /// would move the picture fifty seconds in one frame — a teleport, on a lane
581    /// whose whole method is binding parameters to audio.
582    #[test]
583    fn a_rate_change_advances_the_phase_by_rate_times_dt_at_any_elapsed_time() {
584        let dt = 1.0 / 60.0;
585        let (mut fold, mut field) = (Phase::default(), Phase::default());
586        // Run a long way out, so a multiply-by-elapsed-time would be obvious.
587        for _ in 0..6_000 {
588            fold.step(1.0, dt);
589            field.step(1.0, dt);
590        }
591        let elapsed = fold.get();
592        assert!(
593            elapsed > 99.0,
594            "the fixture must be far from t = 0: {elapsed}"
595        );
596
597        // Now the preset's binding moves, as an audio-bound rate does.
598        let before = fold.get();
599        fold.step(1.5, dt);
600        let fold_step = fold.get() - before;
601        assert!(
602            (fold_step - 1.5 * dt).abs() < 1e-4,
603            "the fold advanced {fold_step}, not {} — scaling with elapsed time is the defect",
604            1.5 * dt
605        );
606
607        // And each accumulator carries its own rate: the pair is not welded.
608        let field_before = field.get();
609        field.step(0.25, dt);
610        // Tolerance is above the f32 ulp at this magnitude (~7.6e-6 near 100),
611        // which is the accumulation cost ADR-0132 accepts.
612        assert!(
613            (field.get() - field_before - 0.25 * dt).abs() < 1e-4,
614            "the field phase must follow field_speed alone: moved {}",
615            field.get() - field_before
616        );
617    }
618
619    /// At a constant rate the integrated phase equals `rate * t` — which is why
620    /// every shipped preset, all of which leave both parameters at their `1.0`
621    /// default, renders unchanged. Asserted rather than assumed, because it is
622    /// what makes moving no golden a property rather than an observation.
623    #[test]
624    fn a_constant_rate_integrates_to_rate_times_elapsed_time() {
625        let dt = 1.0 / 60.0;
626        for rate in [1.0f32, 0.4, 2.5] {
627            let mut phase = Phase::default();
628            let mut clock = 0.0f32;
629            for _ in 0..600 {
630                phase.step(rate, dt);
631                clock += dt;
632            }
633            assert!(
634                (phase.get() - rate * clock).abs() < 1e-3,
635                "rate {rate}: integrated {} against {}",
636                phase.get(),
637                rate * clock
638            );
639        }
640    }
641
642    /// The default is exactly `1.0` on both, so the phase is bit-identical to
643    /// the clock the three shader literals read — the capture path
644    /// accumulates `time` the same way, one `FALLBACK_DT` per frame.
645    #[test]
646    fn the_default_rates_make_the_phase_the_clock() {
647        assert_eq!(DEFAULT_FIELD_SPEED, 1.0);
648        assert_eq!(DEFAULT_FOLD_SPEED, 1.0);
649
650        let dt = crate::render::scenes::FALLBACK_DT;
651        let (mut fold, mut field) = (Phase::default(), Phase::default());
652        let mut clock = 0.0f32;
653        for _ in 0..240 {
654            fold.step(DEFAULT_FOLD_SPEED, dt);
655            field.step(DEFAULT_FIELD_SPEED, dt);
656            clock += dt;
657        }
658        assert_eq!(
659            fold.get(),
660            clock,
661            "at rate 1.0 the accumulation must be bit-identical to the clock's"
662        );
663        assert_eq!(field.get(), clock);
664    }
665}