Files
nvrl ec6cbce579 Add the Elastic Matter and Sigil Tunnel modes
Elastic Matter (`--mode elastic`): twisted thin-film membranes, an
inflating cutaway bubble and 24 spring-driven droplets that strikes tear
loose and springs pull back. Gaps slow physical time, drops expand the
scene. Direct audio response, no modulation graph.

Sigil Tunnel (`--mode sigil-tunnel`): a flight down a corridor of rings,
each the live sigil figure (spine, ribs, debris, spokes) spun and
flattened on the CPU, repeated along a bending axis with a per-ring
twist and shaded with sigil's closest-approach glow, colours and
feedback. Closest approach to each capsule is solved analytically
(14 rings x 48 segments per pixel, no raymarch). Near rings fade out
before they turn into end-on bands, the vanishing point stays dark so a
sigil drawn over it reads, and the trail is short. Shares sigil's
generator, backbone picker and modulation graph; the UBO gains one
flight row.

Both modes are in the live cycle, the launcher's Shape section, the
preview, timeline scenes and offline render.
2026-11-11 23:48:53 +01:00

1655 lines
61 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Audio→parameter modulation graph (Phase 3) — the **data** that used to be
//! scattered hardcoded formulas in each visualiser's `update`/`render`.
//!
//! ## The two-layer mental model
//!
//! Every modulated parameter has two parts and the split is deliberate:
//!
//! - **BASE** (the *director*) — the section/archetype engine chooses a
//! parameter's resting value, including the multiplicative tension shaping.
//! This stays **engine-side**: it is the hand-tuned musical intelligence and a
//! stability/guardrail anchor, not user data.
//! - **MODULATION** (the *performer*) — how live audio features push the
//! parameter *around* that base, in the moment. This is the user-editable
//! [`Graph`]: a flat list of [`Route`]s, each one a clean
//! `amount · curve(source)` term. The engine sums the routes per target,
//! then applies its own base / spring-smoothing / clamp / drive / effect-gate.
//!
//! So a **default** graph reproduces the stock behaviour byte-for-byte (each
//! default route is one additive audio term lifted out of the old formula),
//! while the user is free to dial any route to zero, invert it, add new
//! source→param links, or re-route a trigger. Clamps and bases stay
//! engine-side, so no graph can request a GPU-unsafe value.
//!
//! ## Determinism
//!
//! [`Graph::modulation`]/[`Graph::fires`] are **pure** functions of a per-frame
//! [`Sources`] snapshot. The snapshot's only stateful inputs (derived envelopes,
//! LFO phase) are advanced in the visualiser's `update` like every other
//! integrator, so `--render` stays bit-reproducible. This module holds no `Rng`
//! and no clock.
//!
//! The model is intentionally **UI-agnostic**: a route is just
//! `(source, target, amount, curve, threshold)`. The sigil-gui matrix editor
//! and the live in-window overlay are two skins over the same records.
//!
//! ## Control nodes
//!
//! A graph may also carry [`Node`]s (see [`crate::nodes`]): CHOP-style
//! operators (lag, envelope, LFO, math, …) chained between the sources and the
//! routes. A route with `node: Some(id)` reads that node instead of its
//! `source`. Nodes are stateful, so evaluation goes through the
//! [`Modulator`] runtime, which the visualiser steps once per frame.
use serde::{Deserialize, Serialize};
pub use crate::image::{Blend, ImageGraph, Img, Top, TopOp, TOP_PARAMS};
pub use crate::nodes::{Input, MathOp, Modulator, Node, Op, Wave};
/// A modulation input. All are normalised to roughly `0..1` (a few are signed
/// or unbounded — noted) so a route `amount` reads as "fraction of full-scale".
/// Engine-derived envelopes (`Kick`/`HiEnv`/`Jolt`/`Shock`) and the generators
/// (`Lfo*`/`Const`) are filled by the visualiser into the [`Sources`] snapshot.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum Source {
// ── raw Bands features ────────────────────────────────────────────────
Low,
Mid,
High,
LowOn,
MidOn,
HighOn,
Flux,
Csd,
Centroid,
Loud,
Beat,
BeatPhase,
Width,
Flatness,
/// Strength of the single loudest chroma pitch-class (0..1).
ChromaDom,
// ── bass music (dubstep / riddim; `audio_visualizer::bass`) ───────────
/// 30–90 Hz level against its recent range.
Sub,
/// The bass line's own envelope: rises and falls with every "womb".
Bass,
/// How open the wobble's filter is (dark "oo" 0 … bright "wah" 1).
Growl,
/// How much the mids move (wobble bass, growls).
Wobble,
/// Wobble rate, 8 Hz = 1.
WobbleRate,
/// High while the low end sits well above its recent average.
Drop,
/// High in the stop before a drop and the gaps a riddim leaves.
Gap,
/// Position in the 4-beat bar (0..1 sawtooth).
Bar,
/// Pulse as each bar turns over.
Downbeat,
// ── harmonic / percussive split ───────────────────────────────────────
/// Sustained, pitched energy: pads, chords, vocals, held bass.
Harm,
/// Transient energy: the drums.
Perc,
// ── engine-derived envelopes (per-mode; 0 where a mode lacks one) ──────
Kick,
HiEnv,
Jolt,
Shock,
// ── structure model ───────────────────────────────────────────────────
Tension,
Release,
Novelty,
// ── generators ────────────────────────────────────────────────────────
LfoSlow,
LfoFast,
Const,
// ── external controllers (live only; 0 in renders) ──────────────────────
/// Knob / fader 1..8 from a MIDI controller (`--midi`) or OSC (`--osc`),
/// 0..1.
Ctl1,
Ctl2,
Ctl3,
Ctl4,
Ctl5,
Ctl6,
Ctl7,
Ctl8,
/// A pad / key hit (MIDI note, OSC `/sigil/pad`): its velocity, decaying
/// over ~0.25 s. Route it to a trigger to fire on a hit.
Pad,
}
/// How many knob sources there are ([`Source::Ctl1`]..).
pub const N_CTL: usize = 8;
impl Source {
/// All sources in index order — also the snapshot slot order.
pub const ALL: [Source; 45] = [
Source::Low,
Source::Mid,
Source::High,
Source::LowOn,
Source::MidOn,
Source::HighOn,
Source::Flux,
Source::Csd,
Source::Centroid,
Source::Loud,
Source::Beat,
Source::BeatPhase,
Source::Width,
Source::Flatness,
Source::ChromaDom,
Source::Sub,
Source::Bass,
Source::Growl,
Source::Wobble,
Source::WobbleRate,
Source::Drop,
Source::Gap,
Source::Bar,
Source::Downbeat,
Source::Harm,
Source::Perc,
Source::Kick,
Source::HiEnv,
Source::Jolt,
Source::Shock,
Source::Tension,
Source::Release,
Source::Novelty,
Source::LfoSlow,
Source::LfoFast,
Source::Const,
Source::Ctl1,
Source::Ctl2,
Source::Ctl3,
Source::Ctl4,
Source::Ctl5,
Source::Ctl6,
Source::Ctl7,
Source::Ctl8,
Source::Pad,
];
pub const COUNT: usize = Self::ALL.len();
#[inline]
pub fn idx(self) -> usize {
self as usize
}
/// Short label for the launcher / live overlay / docs.
pub fn name(self) -> &'static str {
match self {
Source::Low => "low",
Source::Mid => "mid",
Source::High => "high",
Source::LowOn => "low_on",
Source::MidOn => "mid_on",
Source::HighOn => "high_on",
Source::Flux => "flux",
Source::Csd => "csd",
Source::Centroid => "centroid",
Source::Loud => "loud",
Source::Beat => "beat",
Source::BeatPhase => "beat_phase",
Source::Width => "width",
Source::Flatness => "flatness",
Source::ChromaDom => "chroma_dom",
Source::Sub => "sub",
Source::Bass => "bass",
Source::Growl => "growl",
Source::Wobble => "wobble",
Source::WobbleRate => "wobble_rate",
Source::Drop => "drop",
Source::Gap => "gap",
Source::Bar => "bar",
Source::Downbeat => "downbeat",
Source::Harm => "harmonic",
Source::Perc => "percussive",
Source::Kick => "kick",
Source::HiEnv => "hi_env",
Source::Jolt => "jolt",
Source::Shock => "shock",
Source::Tension => "tension",
Source::Release => "release",
Source::Novelty => "novelty",
Source::LfoSlow => "lfo_slow",
Source::LfoFast => "lfo_fast",
Source::Const => "const",
Source::Ctl1 => "ctl1",
Source::Ctl2 => "ctl2",
Source::Ctl3 => "ctl3",
Source::Ctl4 => "ctl4",
Source::Ctl5 => "ctl5",
Source::Ctl6 => "ctl6",
Source::Ctl7 => "ctl7",
Source::Ctl8 => "ctl8",
Source::Pad => "pad",
}
}
/// One-line description for the matrix tooltip.
pub fn help(self) -> &'static str {
match self {
Source::Low => "sub/bass band energy",
Source::Mid => "mid band energy",
Source::High => "high band energy",
Source::LowOn => "bass onset (spectral flux, low)",
Source::MidOn => "mid onset",
Source::HighOn => "high onset (hats/snares)",
Source::Flux => "broadband spectral flux (overall onset)",
Source::Csd => "spectral-centroid spread",
Source::Centroid => "spectral centroid (brightness)",
Source::Loud => "perceptual loudness",
Source::Beat => "beat-tracker confidence pulse",
Source::BeatPhase => "phase within the beat (0..1)",
Source::Width => "stereo width",
Source::Flatness => "spectral flatness (tonal↔noisy)",
Source::ChromaDom => "strength of the loudest pitch class",
Source::Sub => "sub-bass level, 30–90 Hz, against its recent range",
Source::Bass => "bass-line envelope: follows every womb of a wobble",
Source::Growl => "wobble filter: dark \"oo\" low, bright \"wah\" high",
Source::Wobble => "how fast the mids move (wobbles, growls)",
Source::WobbleRate => "wobble rate (8 Hz = 1)",
Source::Drop => "the drop: low end well above its recent average",
Source::Gap => "the stop before a drop; riddim gaps",
Source::Bar => "position in the 4-beat bar (0..1)",
Source::Downbeat => "pulse on the first beat of each bar",
Source::Harm => "sustained, pitched sound: pads, chords, vocals (no drums)",
Source::Perc => "the drums only: transients without the pads and chords",
Source::Kick => "bass envelope (fast attack/slow decay)",
Source::HiEnv => "hi-band envelope (sparkle)",
Source::Jolt => "decaying snare/hat rotational kick (sigil)",
Source::Shock => "decaying broadband radial pulse (sigil)",
Source::Tension => "build-up tension ramp (0..1)",
Source::Release => "drop release spike",
Source::Novelty => "harmonic novelty (section change)",
Source::LfoSlow => "slow free-running LFO (0.11 Hz-ish)",
Source::LfoFast => "faster free-running LFO",
Source::Const => "constant 1.0 (a fixed bias)",
Source::Ctl1
| Source::Ctl2
| Source::Ctl3
| Source::Ctl4
| Source::Ctl5
| Source::Ctl6
| Source::Ctl7
| Source::Ctl8 => {
"a knob or fader on your MIDI controller / OSC app (live window only)"
}
Source::Pad => "a pad or key hit on your controller, decaying (live window only)",
}
}
/// Knob `i` (0-based, < [`N_CTL`]).
pub fn ctl(i: usize) -> Source {
Source::ALL[Source::Ctl1.idx() + i.min(N_CTL - 1)]
}
}
/// Response shaping applied to a source value before it is scaled by `amount`.
/// Input is taken as `0..1` (clamped); `Linear` is the identity used by every
/// default route, so the built-in graph is a plain weighted sum.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
pub enum Curve {
#[default]
Linear,
/// Eased-in (x²) — quiet stays quiet, peaks pop.
Exp,
/// Eased-out (√x) — lifts low values, compresses peaks.
Log,
/// S-curve (smoothstep) — soft knees both ends.
Smoothstep,
}
impl Curve {
pub const ALL: [Curve; 4] = [Curve::Linear, Curve::Exp, Curve::Log, Curve::Smoothstep];
/// Label for the curve picker.
pub fn label(self) -> &'static str {
match self {
Curve::Linear => "linear",
Curve::Exp => "exp (x²)",
Curve::Log => "log (√x)",
Curve::Smoothstep => "smoothstep",
}
}
#[inline]
pub fn apply(self, x: f32) -> f32 {
let x = x.clamp(0.0, 1.0);
match self {
Curve::Linear => x,
Curve::Exp => x * x,
Curve::Log => x.sqrt(),
Curve::Smoothstep => x * x * (3.0 - 2.0 * x),
}
}
}
/// One modulation link: `source` shaped by `curve`, scaled by `amount`, added
/// onto `target`'s running sum. For a **trigger** target the sum is ignored and
/// the route instead *fires* when `curve(source) > threshold` (see
/// [`Graph::fires`]); `amount` is unused there, `threshold` unused for a
/// continuous target.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct Route {
pub source: Source,
/// Mode-namespaced target id (see [`sigil`]/[`tunnel`] id modules). Routes
/// for the wrong mode are harmless: an id no continuous param reads just
/// sums into an unused slot.
pub target: u16,
pub amount: f32,
#[serde(default)]
pub curve: Curve,
/// Fire threshold for trigger targets only (continuous targets ignore it).
#[serde(default)]
pub threshold: f32,
/// Read this node's output instead of `source` (see [`crate::nodes`]).
/// Matrix cells only show and edit routes where this is `None`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node: Option<u32>,
}
impl Route {
/// Continuous (additive) route.
pub const fn cont(source: Source, target: u16, amount: f32) -> Self {
Route {
source,
target,
amount,
curve: Curve::Linear,
threshold: 0.0,
node: None,
}
}
/// Trigger route: fires when `source` exceeds `threshold`.
pub const fn trig(source: Source, target: u16, threshold: f32) -> Self {
Route {
source,
target,
amount: 1.0,
curve: Curve::Linear,
threshold,
node: None,
}
}
}
/// Upper bound on distinct target slots per mode. The per-frame modulation
/// result is a fixed array of this size.
pub const MAX_TARGETS: usize = 32;
/// The editable modulation graph: a flat route list (the matrix) plus optional
/// control [`Node`]s. The visualiser owns the bases/springs/clamps; this owns
/// only the audio coupling. Evaluate it through a [`Modulator`].
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Graph {
pub routes: Vec<Route>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub nodes: Vec<Node>,
/// Image operators run over the rendered frame; empty = passthrough.
#[serde(default, skip_serializing_if = "ImageGraph::is_empty")]
pub image: ImageGraph,
}
impl Graph {
// ── matrix-editor accessors (live overlay / GUI) ──────────────────────────
/// Amount of the (first) route `source→target`, or 0 if none.
pub fn amount(&self, source: Source, target: u16) -> f32 {
self.routes
.iter()
.find(|r| r.node.is_none() && r.source == source && r.target == target)
.map(|r| r.amount)
.unwrap_or(0.0)
}
/// Upsert a continuous route; `amount ≈ 0` removes it (no dead routes).
pub fn set_amount(&mut self, source: Source, target: u16, amount: f32) {
if amount.abs() < 1e-4 {
self.routes
.retain(|r| !(r.node.is_none() && r.source == source && r.target == target));
return;
}
if let Some(r) = self
.routes
.iter_mut()
.find(|r| r.node.is_none() && r.source == source && r.target == target)
{
r.amount = amount;
} else {
self.routes.push(Route::cont(source, target, amount));
}
}
/// Threshold of the trigger route `source→target`, or `None` if absent.
pub fn trigger(&self, source: Source, target: u16) -> Option<f32> {
self.routes
.iter()
.find(|r| r.node.is_none() && r.source == source && r.target == target)
.map(|r| r.threshold)
}
/// Upsert a trigger route; `threshold <= 0` removes it (a 0-threshold
/// trigger would fire every frame — never wanted, so it means "off").
pub fn set_trigger(&mut self, source: Source, target: u16, threshold: f32) {
if threshold <= 0.0 {
self.routes
.retain(|r| !(r.node.is_none() && r.source == source && r.target == target));
return;
}
if let Some(r) = self
.routes
.iter_mut()
.find(|r| r.node.is_none() && r.source == source && r.target == target)
{
r.threshold = threshold;
r.amount = 1.0;
} else {
self.routes.push(Route::trig(source, target, threshold));
}
}
/// Response curve of the route `source→target` (Linear if absent).
pub fn curve(&self, source: Source, target: u16) -> Curve {
self.routes
.iter()
.find(|r| r.node.is_none() && r.source == source && r.target == target)
.map(|r| r.curve)
.unwrap_or_default()
}
/// Set the response curve of an existing route (no-op if absent).
pub fn set_curve(&mut self, source: Source, target: u16, curve: Curve) {
if let Some(r) = self
.routes
.iter_mut()
.find(|r| r.node.is_none() && r.source == source && r.target == target)
{
r.curve = curve;
}
}
}
/// Per-frame snapshot of every [`Source`] value, indexed by [`Source::idx`].
/// The engine fills the analysis-derived slots (it owns `Bands`/`Structure`)
/// then sets the per-mode envelope/generator slots it owns. This crate only
/// stores + reads the values; see `audio_visualizer::viz::modulation` for the
/// engine-side fill.
#[derive(Clone, Copy)]
pub struct Sources {
vals: [f32; Source::COUNT],
}
impl Default for Sources {
fn default() -> Self {
Sources {
vals: [0.0; Source::COUNT],
}
}
}
impl Sources {
pub fn new() -> Self {
Self::default()
}
#[inline]
pub fn get(&self, s: Source) -> f32 {
self.vals[s.idx()]
}
#[inline]
pub fn set(&mut self, s: Source, v: f32) {
self.vals[s.idx()] = v;
}
}
/// A matrix column: one modulation target (geometry/effect param or trigger).
/// Drives the matrix editor's column headers + tooltips (launcher and the live
/// in-window overlay).
pub struct TargetMeta {
pub id: u16,
/// Short column header.
pub name: &'static str,
/// Tooltip / what the param does.
pub help: &'static str,
/// Trigger column (threshold cells) vs. continuous (bipolar amount cells).
pub trigger: bool,
}
/// Sigil mode target ids. Continuous targets feed an engine base + spring/clamp
/// (or a per-frame effect intensity); the last three are trigger targets.
/// **Coupled to [`Graph::default_sigil`].**
pub mod sigil {
use super::TargetMeta;
/// Matrix columns in id order. Coupled to the ids below + `default_sigil`.
pub const TARGETS: [TargetMeta; COUNT] = [
TargetMeta {
id: SCALE,
name: "scale",
help: "backbone world scale (breathe)",
trigger: false,
},
TargetMeta {
id: TUBE,
name: "tube",
help: "capsule radius",
trigger: false,
},
TargetMeta {
id: DIST,
name: "dist",
help: "camera distance (− = pull in)",
trigger: false,
},
TargetMeta {
id: GLOW,
name: "glow",
help: "filament brightness",
trigger: false,
},
TargetMeta {
id: DOLLY,
name: "dolly",
help: "beat/kick camera dolly-punch",
trigger: false,
},
TargetMeta {
id: FOCAL,
name: "focal",
help: "lens focal length (FOV)",
trigger: false,
},
TargetMeta {
id: WARP,
name: "warp",
help: "spine spectral displacement",
trigger: false,
},
TargetMeta {
id: GLITCH,
name: "glitch",
help: "horizontal slice tear",
trigger: false,
},
TargetMeta {
id: SCANLINE,
name: "scan",
help: "CRT scanline depth",
trigger: false,
},
TargetMeta {
id: GRAIN,
name: "grain",
help: "film-grain amplitude",
trigger: false,
},
TargetMeta {
id: SWIRL_ZOOM,
name: "swirlZ",
help: "feedback zoom",
trigger: false,
},
TargetMeta {
id: SWIRL_ROT,
name: "swirlR",
help: "feedback rotate",
trigger: false,
},
TargetMeta {
id: FREEZE,
name: "FRZ",
help: "trigger: feedback hold (snare)",
trigger: true,
},
TargetMeta {
id: STROBE,
name: "STRB",
help: "trigger: beat strobe pop",
trigger: true,
},
TargetMeta {
id: MORPH,
name: "MRPH",
help: "trigger: backbone restructure",
trigger: true,
},
];
// continuous — geometry / camera (sprung)
pub const SCALE: u16 = 0;
pub const TUBE: u16 = 1;
pub const DIST: u16 = 2;
pub const GLOW: u16 = 3;
pub const DOLLY: u16 = 4;
pub const FOCAL: u16 = 5;
/// spine spectral-displacement amount (read in `build_spine`, not sprung)
pub const WARP: u16 = 6;
// continuous — screen-space effect intensities (per-frame, gated by --fx)
pub const GLITCH: u16 = 7;
pub const SCANLINE: u16 = 8;
pub const GRAIN: u16 = 9;
pub const SWIRL_ZOOM: u16 = 10;
pub const SWIRL_ROT: u16 = 11;
// triggers
pub const FREEZE: u16 = 12;
pub const STROBE: u16 = 13;
pub const MORPH: u16 = 14;
pub const COUNT: usize = 15;
}
impl Graph {
/// The built-in sigil graph — encodes exactly the additive audio terms that
/// used to be inline in `Sigil::update`/`render`, so an absent `--routes`
/// reproduces the stock output. Bases / multiplicative tension shaping /
/// clamps / spring stiffness / drive all stay engine-side.
pub fn default_sigil() -> Self {
use sigil::*;
use Source::*;
Graph {
nodes: Vec::new(),
image: ImageGraph::default(),
routes: vec![
// scale ← 0.30·low + 0.25·low_on + 0.85·release
Route::cont(Low, SCALE, 0.30),
Route::cont(LowOn, SCALE, 0.25),
Route::cont(Release, SCALE, 0.85),
// tube ← 0.05·mid + 0.02·mid_on
Route::cont(Mid, TUBE, 0.05),
Route::cont(MidOn, TUBE, 0.02),
// dist ← −0.85·low
Route::cont(Low, DIST, -0.85),
// glow ← 0.45·loud + 0.40·flux + 0.35·tension
Route::cont(Loud, GLOW, 0.45),
Route::cont(Flux, GLOW, 0.40),
Route::cont(Tension, GLOW, 0.35),
// dolly ← 0.55·low_on + 0.45·beat
Route::cont(LowOn, DOLLY, 0.55),
Route::cont(Beat, DOLLY, 0.45),
// focal ← 0.55·tension − 0.15·loud
Route::cont(Tension, FOCAL, 0.55),
Route::cont(Loud, FOCAL, -0.15),
// warp ← 0.10·tension
Route::cont(Tension, WARP, 0.10),
// glitch ← 0.06·high + 0.12·flux + 0.50·novelty
Route::cont(High, GLITCH, 0.06),
Route::cont(Flux, GLITCH, 0.12),
Route::cont(Novelty, GLITCH, 0.50),
// scanline ← 0.07·loud + 0.05·tension
Route::cont(Loud, SCANLINE, 0.07),
Route::cont(Tension, SCANLINE, 0.05),
// grain ← 0.020·flux + 0.010·release
Route::cont(Flux, GRAIN, 0.020),
Route::cont(Release, GRAIN, 0.010),
// swirl_zoom ← 0.018·loud + 0.020·shock
Route::cont(Loud, SWIRL_ZOOM, 0.018),
Route::cont(Shock, SWIRL_ZOOM, 0.020),
// swirl_rot ← 0.006·mid + 0.020·tension
Route::cont(Mid, SWIRL_ROT, 0.006),
Route::cont(Tension, SWIRL_ROT, 0.020),
// freeze fires on a flux burst > 0.62 (engine adds tn>0.25 + cooldown)
Route::trig(Flux, FREEZE, 0.62),
// strobe fires on a beat hit or a hat (engine adds re-arm + ceiling)
Route::trig(Beat, STROBE, 0.72),
Route::trig(HighOn, STROBE, 0.62),
// morph fires on strong harmonic novelty (OR'd with arch-change engine-side)
Route::trig(Novelty, MORPH, 0.75),
],
}
}
}
/// Tunnel mode target ids (the light tunnel). Same shape as [`sigil`]:
/// continuous targets feed an engine base + spring/clamp (or a per-frame effect
/// intensity); FREEZE/STROBE/MORPH/WAVE are triggers. **Coupled to
/// [`Graph::default_tunnel`].** Ids 0..=18 kept their slots when the mode was
/// rebuilt (the lattice became a light tunnel), so saved graphs still load;
/// their meaning follows the new names.
pub mod tunnel {
use super::TargetMeta;
// continuous — tunnel form (sprung)
/// tunnel radius additive (engine base 1.0, clamp 0.6..1.4)
pub const RADIUS: u16 = 0;
/// ring line width additive (engine base 1.0 = 0.012 units, clamp 0.4..3)
pub const WIDTH: u16 = 1;
/// profile wobble (engine base per shape, clamp 0..0.25)
pub const WOBBLE: u16 = 2;
/// twist of the profile down the tunnel, rad per unit depth
pub const TWIST: u16 = 3;
/// ring brightness (engine base per section)
pub const GLOW: u16 = 4;
/// dust motes between the rings
pub const DUST: u16 = 5;
/// flight speed, extra rings per beat (engine base per section)
pub const SPEED: u16 = 6;
// continuous — screen-space effect intensities (per-frame, gated by --fx)
pub const SCANLINE: u16 = 7;
pub const GRAIN: u16 = 8;
pub const GLITCH: u16 = 9;
pub const SWIRL_ROT: u16 = 10;
pub const SWIRL_ZOOM: u16 = 11;
// triggers
pub const FREEZE: u16 = 12;
pub const STROBE: u16 = 13;
/// change the tunnel's profile
pub const MORPH: u16 = 14;
// continuous — camera + lights
/// camera punch: narrows the lens on a hit
pub const PUNCH: u16 = 15;
/// lens focal length / FOV (engine base 1.25, clamp 0.9..2.2)
pub const FOCAL: u16 = 16;
/// light rails along the corners and the packets running down them
pub const RAILS: u16 = 17;
/// light at the end of the tunnel
pub const CORE: u16 = 18;
/// trigger: a bright wave races away down the tunnel
pub const WAVE: u16 = 19;
pub const COUNT: usize = 20;
/// Matrix columns in id order. Coupled to the ids above + `default_tunnel`.
pub const TARGETS: [TargetMeta; COUNT] = [
TargetMeta {
id: RADIUS,
name: "radius",
help: "tunnel radius (− = squeeze)",
trigger: false,
},
TargetMeta {
id: WIDTH,
name: "width",
help: "ring line width",
trigger: false,
},
TargetMeta {
id: WOBBLE,
name: "wobble",
help: "rings bend out of shape",
trigger: false,
},
TargetMeta {
id: TWIST,
name: "twist",
help: "profile twists down the tunnel",
trigger: false,
},
TargetMeta {
id: GLOW,
name: "glow",
help: "ring brightness",
trigger: false,
},
TargetMeta {
id: DUST,
name: "dust",
help: "dust motes flying past",
trigger: false,
},
TargetMeta {
id: SPEED,
name: "speed",
help: "flight speed (rings per beat)",
trigger: false,
},
TargetMeta {
id: SCANLINE,
name: "scan",
help: "CRT scanline depth",
trigger: false,
},
TargetMeta {
id: GRAIN,
name: "grain",
help: "film-grain amplitude",
trigger: false,
},
TargetMeta {
id: GLITCH,
name: "glitch",
help: "horizontal slice tear",
trigger: false,
},
TargetMeta {
id: SWIRL_ROT,
name: "swirlR",
help: "feedback rotate",
trigger: false,
},
TargetMeta {
id: SWIRL_ZOOM,
name: "swirlZ",
help: "feedback zoom (warp streaks)",
trigger: false,
},
TargetMeta {
id: FREEZE,
name: "FRZ",
help: "trigger: feedback hold (snare)",
trigger: true,
},
TargetMeta {
id: STROBE,
name: "STRB",
help: "trigger: beat strobe pop",
trigger: true,
},
TargetMeta {
id: MORPH,
name: "MRPH",
help: "trigger: change the tunnel's shape",
trigger: true,
},
TargetMeta {
id: PUNCH,
name: "punch",
help: "camera punch (lens narrows)",
trigger: false,
},
TargetMeta {
id: FOCAL,
name: "focal",
help: "lens focal length (FOV)",
trigger: false,
},
TargetMeta {
id: RAILS,
name: "rails",
help: "corner light rails",
trigger: false,
},
TargetMeta {
id: CORE,
name: "core",
help: "light at the end of the tunnel",
trigger: false,
},
TargetMeta {
id: WAVE,
name: "WAVE",
help: "trigger: light wave down the tunnel",
trigger: true,
},
];
}
impl Graph {
/// The built-in tunnel graph. Bases (per section), clamps, spring
/// stiffness and drive stay engine-side. `Kick` = the bass envelope
/// (`low_env`), `HiEnv` = the hi-band envelope — the visualiser fills both.
pub fn default_tunnel() -> Self {
use tunnel::*;
use Source::*;
Graph {
nodes: Vec::new(),
image: ImageGraph::default(),
routes: vec![
Route::cont(Kick, RADIUS, -0.06),
Route::cont(Loud, WIDTH, 0.5),
Route::cont(Tension, WIDTH, 0.4),
Route::cont(Mid, WOBBLE, 0.03),
Route::cont(Release, WOBBLE, 0.04),
Route::cont(Tension, TWIST, 0.04),
Route::cont(Loud, GLOW, 0.45),
Route::cont(Tension, GLOW, 0.25),
Route::cont(HiEnv, DUST, 0.9),
Route::cont(Tension, SPEED, 0.5),
Route::cont(Loud, SCANLINE, 0.03),
Route::cont(Flux, GRAIN, 0.015),
Route::cont(Flux, GLITCH, 0.04),
Route::cont(Novelty, GLITCH, 0.15),
Route::cont(Mid, SWIRL_ROT, 0.006),
Route::cont(Loud, SWIRL_ZOOM, 0.025),
Route::cont(Tension, SWIRL_ZOOM, 0.015),
Route::trig(Flux, FREEZE, 0.62),
Route::trig(LowOn, STROBE, 0.72),
Route::trig(Novelty, MORPH, 0.78),
Route::cont(Kick, PUNCH, 0.6),
Route::cont(Tension, FOCAL, 0.3),
Route::cont(HiEnv, RAILS, 0.8),
Route::cont(Loud, RAILS, 0.3),
Route::cont(Low, CORE, 0.6),
Route::cont(Tension, CORE, 0.3),
Route::trig(LowOn, WAVE, 0.5),
],
}
}
}
/// Ophanim mode target ids (the angel-of-rings visualiser). Laid out so the
/// screen-space effect ids sit at **7..=11** like the other modes (the
/// Psychedelic preset boosts that range) and the triggers at 12..=14.
/// **Coupled to [`Graph::default_ophanim`].**
pub mod ophanim {
use super::TargetMeta;
// continuous — form / camera (sprung engine-side)
/// whole-figure scale additive (engine base 1.0, clamp 0.7..1.4)
pub const SCALE: u16 = 0;
/// outer ring spin rate additive (rad/s; engine base ≈0.15)
pub const SPIN_OUT: u16 = 1;
/// middle ring spin rate additive (rad/s)
pub const SPIN_MID: u16 = 2;
/// inner ring spin rate additive (rad/s)
pub const SPIN_IN: u16 = 3;
/// beat/kick camera dolly-punch (engine base 0)
pub const DOLLY: u16 = 4;
/// lens focal length (engine base 1.6, clamp 1.3..2.3)
pub const FOCAL: u16 = 5;
/// gimbal tilt — how far the rings swing off their rest planes
pub const TILT: u16 = 6;
// continuous — screen-space effect intensities (per-frame, gated by --fx)
pub const GLITCH: u16 = 7;
pub const SCANLINE: u16 = 8;
pub const GRAIN: u16 = 9;
pub const SWIRL_ZOOM: u16 = 10;
pub const SWIRL_ROT: u16 = 11;
// triggers
pub const FREEZE: u16 = 12;
pub const STROBE: u16 = 13;
/// every eye blinks shut and snaps back open
pub const BLINK: u16 = 14;
// continuous — the angel's parts
/// how far the eyes open (on top of their per-ring onset envelopes)
pub const EYE: u16 = 15;
/// seraph-core size + brightness pulse
pub const CORE: u16 = 16;
/// wing flap angle
pub const WING: u16 = 17;
/// light-shaft strength
pub const RAYS: u16 = 18;
/// ring/eye glow
pub const GLOW: u16 = 19;
pub const COUNT: usize = 20;
const _: () = assert!(COUNT <= super::MAX_TARGETS);
const fn t(id: u16, name: &'static str, help: &'static str, trigger: bool) -> TargetMeta {
TargetMeta {
id,
name,
help,
trigger,
}
}
/// Matrix columns in id order. Coupled to the ids above + `default_ophanim`.
pub const TARGETS: [TargetMeta; COUNT] = [
t(SCALE, "scale", "whole-figure scale (breathe)", false),
t(SPIN_OUT, "spin out", "outer ring spin rate", false),
t(SPIN_MID, "spin mid", "middle ring spin rate", false),
t(SPIN_IN, "spin in", "inner ring spin rate", false),
t(DOLLY, "dolly", "beat/kick camera dolly-punch", false),
t(FOCAL, "focal", "lens focal length (FOV)", false),
t(TILT, "tilt", "gimbal tilt of the rings", false),
t(GLITCH, "glitch", "slice-tear glitch amount", false),
t(SCANLINE, "scanline", "CRT scanline depth", false),
t(GRAIN, "grain", "film grain amount", false),
t(SWIRL_ZOOM, "swirl zoom", "feedback zoom", false),
t(SWIRL_ROT, "swirl rot", "feedback rotation", false),
t(FREEZE, "freeze", "freeze-frame stutter", true),
t(STROBE, "strobe", "beat strobe flash", true),
t(BLINK, "blink", "all eyes blink at once", true),
t(EYE, "eyes", "how wide the eyes open", false),
t(CORE, "core", "seraph core pulse", false),
t(WING, "wings", "wing flap", false),
t(RAYS, "rays", "light-shaft strength", false),
t(GLOW, "glow", "ring + eye brightness", false),
];
}
/// Target ids for the `ferro` mode (a ferrofluid drop that the bass is the
/// magnetic field of). Effects sit at 7..=11 like every other mode.
pub mod ferro {
use super::TargetMeta;
// continuous — the drop (sprung engine-side)
/// whole-drop size additive (engine base 1.0, clamp 0.8..1.25)
pub const SCALE: u16 = 0;
/// size of the liquid movement (lobes, sway, ripples), additive on the style's gain
pub const GAIN: u16 = 1;
/// noise spikes and thorns, additive on the style's spike
pub const SPIKE: u16 = 2;
/// the magnetic field: raises the whole ferrofluid spike lattice
pub const FIELD: u16 = 3;
/// camera dolly-punch (engine base 0)
pub const DOLLY: u16 = 4;
/// lens focal length (engine base 1.9, clamp 1.5..2.6)
pub const FOCAL: u16 = 5;
/// twist of the liquid about the vertical axis
pub const TWIST: u16 = 6;
// continuous — screen-space effect intensities (per-frame, gated by --fx)
pub const GLITCH: u16 = 7;
pub const SCANLINE: u16 = 8;
pub const GRAIN: u16 = 9;
pub const SWIRL_ZOOM: u16 = 10;
pub const SWIRL_ROT: u16 = 11;
// triggers
pub const FREEZE: u16 = 12;
pub const STROBE: u16 = 13;
/// every spike shoots out at once (the drop landing)
pub const BURST: u16 = 14;
// continuous — surface + light
/// fine crinkles on the surface
pub const RIPPLE: u16 = 15;
/// rim + halo brightness
pub const GLOW: u16 = 16;
/// the light the drop throws behind it
pub const CAUSTICS: u16 = 17;
/// hue shift of the sheen (radians)
pub const HUE: u16 = 18;
pub const COUNT: usize = 19;
const _: () = assert!(COUNT <= super::MAX_TARGETS);
const fn t(id: u16, name: &'static str, help: &'static str, trigger: bool) -> TargetMeta {
TargetMeta {
id,
name,
help,
trigger,
}
}
/// Matrix columns in id order. Coupled to the ids above + `default_ferro`.
pub const TARGETS: [TargetMeta; COUNT] = [
t(SCALE, "scale", "whole-drop size (throb)", false),
t(GAIN, "gain", "size of the liquid movement", false),
t(SPIKE, "spike", "noise spikes and thorns", false),
t(
FIELD,
"field",
"magnetic field: raises the spike lattice",
false,
),
t(DOLLY, "dolly", "camera dolly-punch", false),
t(FOCAL, "focal", "lens focal length (FOV)", false),
t(TWIST, "twist", "twist of the liquid", false),
t(GLITCH, "glitch", "slice-tear glitch amount", false),
t(SCANLINE, "scanline", "CRT scanline depth", false),
t(GRAIN, "grain", "film grain amount", false),
t(SWIRL_ZOOM, "swirl zoom", "feedback zoom", false),
t(SWIRL_ROT, "swirl rot", "feedback rotation", false),
t(FREEZE, "freeze", "freeze-frame stutter", true),
t(STROBE, "strobe", "strobe flash", true),
t(BURST, "burst", "every spike shoots out at once", true),
t(RIPPLE, "ripple", "fine crinkles on the surface", false),
t(GLOW, "glow", "rim + halo brightness", false),
t(CAUSTICS, "caustics", "light thrown behind the drop", false),
t(HUE, "hue", "hue shift of the sheen", false),
];
}
impl Graph {
/// The built-in ophanim graph: rings spin per band (low → outer, mid →
/// middle, high → inner), the kick drives the core, wings and dolly, the
/// highs open the light shafts. Bases, springs, clamps and the per-ring
/// eye onset envelopes stay engine-side.
pub fn default_ophanim() -> Self {
use ophanim::*;
use Source::*;
Graph {
nodes: Vec::new(),
image: ImageGraph::default(),
routes: vec![
Route::cont(Kick, SCALE, 0.03),
Route::cont(Low, SPIN_OUT, 0.45),
Route::cont(Mid, SPIN_MID, 0.55),
Route::cont(High, SPIN_IN, 0.75),
Route::cont(Kick, DOLLY, 0.25),
Route::cont(Tension, FOCAL, 0.2),
Route::cont(Tension, TILT, 0.35),
Route::cont(Release, TILT, 0.20),
Route::cont(Flux, GLITCH, 0.10),
Route::cont(Novelty, GLITCH, 0.30),
Route::cont(Loud, SCANLINE, 0.04),
Route::cont(Flux, GRAIN, 0.015),
Route::cont(Loud, SWIRL_ZOOM, 0.012),
Route::cont(Mid, SWIRL_ROT, 0.012),
Route::trig(Flux, FREEZE, 0.70),
Route::trig(Beat, STROBE, 0.80),
Route::trig(Novelty, BLINK, 0.75),
Route::cont(Loud, EYE, 0.5),
Route::cont(Tension, EYE, 0.4),
Route::cont(Kick, CORE, 0.8),
Route::cont(Loud, CORE, 0.3),
Route::cont(Kick, WING, 0.6),
Route::cont(Tension, WING, 0.4),
Route::cont(High, RAYS, 0.6),
Route::cont(Release, RAYS, 0.4),
Route::cont(Loud, GLOW, 0.4),
Route::cont(Tension, GLOW, 0.3),
],
}
}
/// The built-in ferro graph. The physics of the drop (kick crowns, snare
/// jolts, the gap melt, the jump springs) is engine-side and reads the bass
/// features directly; these routes are the parts worth re-patching: the
/// bass line's envelope is the magnetic field and the throb, the growl opens
/// the crinkles, a drop lands as a burst and floods the light, and the
/// strobe sits on the downbeat.
pub fn default_ferro() -> Self {
use ferro::*;
use Source::*;
Graph {
nodes: Vec::new(),
image: ImageGraph::default(),
routes: vec![
Route::cont(Bass, SCALE, 0.09),
Route::cont(Gap, GAIN, -0.85),
Route::cont(Tension, SPIKE, 0.30),
Route::cont(Growl, SPIKE, 0.25),
Route::cont(Bass, FIELD, 0.60),
Route::cont(Drop, FIELD, 0.35),
Route::cont(Gap, FIELD, -0.90),
Route::cont(Kick, DOLLY, 0.25),
Route::cont(Tension, FOCAL, 0.25),
Route::cont(Wobble, TWIST, 0.20),
Route::cont(Flux, GLITCH, 0.10),
Route::cont(Novelty, GLITCH, 0.30),
Route::cont(Loud, SCANLINE, 0.04),
Route::cont(Flux, GRAIN, 0.015),
Route::cont(Drop, SWIRL_ZOOM, 0.015),
Route::cont(Wobble, SWIRL_ROT, 0.012),
Route::trig(Flux, FREEZE, 0.75),
Route::trig(Downbeat, STROBE, 0.6),
Route::trig(Drop, BURST, 0.55),
Route::cont(Growl, RIPPLE, 0.60),
Route::cont(Wobble, RIPPLE, 0.40),
Route::cont(Drop, GLOW, 0.40),
Route::cont(Loud, GLOW, 0.20),
Route::cont(Bass, CAUSTICS, 0.40),
Route::cont(Drop, CAUSTICS, 0.50),
Route::cont(Gap, CAUSTICS, -0.90),
Route::cont(Growl, HUE, 0.25),
],
}
}
}
/// Which mode's target table a graph is written against. `field` has no
/// routable targets, so it has no `GraphMode`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum GraphMode {
Sigil,
Tunnel,
Ophanim,
Ferro,
}
impl GraphMode {
pub const ALL: [GraphMode; 4] = [
GraphMode::Sigil,
GraphMode::Tunnel,
GraphMode::Ophanim,
GraphMode::Ferro,
];
/// From a `--mode` token; `None` for modes without a graph (`field`).
pub fn from_flag(mode: &str) -> Option<Self> {
match mode {
"sigil" | "sigil-tunnel" => Some(GraphMode::Sigil),
"tunnel" => Some(GraphMode::Tunnel),
"ophanim" => Some(GraphMode::Ophanim),
"ferro" => Some(GraphMode::Ferro),
_ => None,
}
}
/// The matrix columns for this mode.
pub fn targets(self) -> &'static [TargetMeta] {
match self {
GraphMode::Sigil => &sigil::TARGETS,
GraphMode::Tunnel => &tunnel::TARGETS,
GraphMode::Ophanim => &ophanim::TARGETS,
GraphMode::Ferro => &ferro::TARGETS,
}
}
/// The stock graph (what an absent `--routes` runs).
pub fn default_graph(self) -> Graph {
match self {
GraphMode::Sigil => Graph::default_sigil(),
GraphMode::Tunnel => Graph::default_tunnel(),
GraphMode::Ophanim => Graph::default_ophanim(),
GraphMode::Ferro => Graph::default_ferro(),
}
}
/// What [`Preset::Riddim`] adds on top of the stock graph: the bass line's
/// envelope throbs the form, the growl roughens it, a drop lights it up and
/// a gap (the stop before a drop) collapses it, and the strobe locks to the
/// downbeat.
fn riddim_routes(self) -> Vec<Route> {
use Source::*;
match self {
GraphMode::Sigil => vec![
Route::cont(Bass, sigil::SCALE, 0.35),
Route::cont(Gap, sigil::SCALE, -0.40),
Route::cont(Wobble, sigil::TUBE, 0.04),
Route::cont(Drop, sigil::GLOW, 0.40),
Route::cont(Gap, sigil::GLOW, -0.60),
Route::cont(Drop, sigil::DOLLY, 0.30),
Route::cont(Growl, sigil::WARP, 0.12),
Route::cont(Growl, sigil::GLITCH, 0.08),
Route::cont(Wobble, sigil::SWIRL_ROT, 0.012),
Route::trig(Downbeat, sigil::STROBE, 0.6),
],
// The bass line breathes the tunnel, the growl bends the rings,
// a drop opens the light at the end, a gap blacks the rings out
// and every downbeat sends a wave down the tunnel.
GraphMode::Tunnel => vec![
Route::cont(Bass, tunnel::RADIUS, 0.10),
Route::cont(Growl, tunnel::WOBBLE, 0.08),
Route::cont(Drop, tunnel::GLOW, 0.35),
Route::cont(Gap, tunnel::GLOW, -0.50),
Route::cont(Drop, tunnel::CORE, 0.50),
Route::cont(Drop, tunnel::SPEED, 0.50),
Route::cont(Growl, tunnel::RAILS, 0.40),
Route::cont(Wobble, tunnel::SWIRL_ROT, 0.008),
Route::trig(Downbeat, tunnel::STROBE, 0.6),
Route::trig(Downbeat, tunnel::WAVE, 0.6),
],
GraphMode::Ophanim => vec![
Route::cont(Bass, ophanim::CORE, 0.60),
Route::cont(Bass, ophanim::WING, 0.40),
Route::cont(Gap, ophanim::EYE, -0.60),
Route::cont(Gap, ophanim::GLOW, -0.50),
Route::cont(Drop, ophanim::GLOW, 0.30),
Route::cont(Drop, ophanim::RAYS, 0.60),
Route::cont(Growl, ophanim::SPIN_MID, 0.30),
Route::cont(Growl, ophanim::TILT, 0.15),
Route::cont(Wobble, ophanim::SWIRL_ROT, 0.012),
Route::trig(Downbeat, ophanim::STROBE, 0.6),
],
// The drop already rides the bass; riddim makes it harder: the
// growl sharpens the spikes, gaps black the light out.
GraphMode::Ferro => vec![
Route::cont(Growl, ferro::SPIKE, 0.30),
Route::cont(Wobble, ferro::TWIST, 0.20),
Route::cont(Gap, ferro::GLOW, -0.50),
Route::cont(Bass, ferro::GLOW, 0.20),
],
}
}
/// (scale-like, swirl-rotate, warp-like) targets the presets drive.
fn preset_targets(self) -> (u16, u16, u16) {
match self {
GraphMode::Sigil => (sigil::SCALE, sigil::SWIRL_ROT, sigil::WARP),
GraphMode::Tunnel => (tunnel::RADIUS, tunnel::SWIRL_ROT, tunnel::WOBBLE),
GraphMode::Ophanim => (ophanim::SCALE, ophanim::SWIRL_ROT, ophanim::TILT),
GraphMode::Ferro => (ferro::SCALE, ferro::SWIRL_ROT, ferro::TWIST),
}
}
}
/// Starter presets for the matrix editor — instant creative starting points.
/// `Default` reproduces the mode's stock graph; the others are transforms over
/// it. Shared by the launcher and the live overlay so both offer the same
/// buttons.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Preset {
Default,
Minimal,
Hyper,
Psychedelic,
Patched,
Trails,
Riddim,
}
impl Preset {
pub const ALL: [Preset; 7] = [
Preset::Default,
Preset::Minimal,
Preset::Hyper,
Preset::Psychedelic,
Preset::Patched,
Preset::Trails,
Preset::Riddim,
];
pub fn label(self) -> &'static str {
match self {
Preset::Default => "Default",
Preset::Minimal => "Minimal-clean",
Preset::Hyper => "Hyper-reactive",
Preset::Psychedelic => "Psychedelic",
Preset::Patched => "Patched",
Preset::Trails => "Trails",
Preset::Riddim => "Riddim",
}
}
pub fn help(self) -> &'static str {
match self {
Preset::Default => "stock behaviour — the hand-tuned mapping",
Preset::Minimal => "no audio modulation; params rest on their section bases",
Preset::Hyper => "default × 1.6, lower trigger thresholds — twitchy",
Preset::Psychedelic => "boosted screen FX + constant LFO drift on the geometry",
Preset::Patched => {
"default + control nodes: kick envelope punch, noise-drifted swirl, hat step-sequencer on warp"
}
Preset::Riddim => {
"default for bass music: half the loudness routes (a drop pins it), the bass-line envelope throbs the form, growl roughens it, drops flare, gaps collapse, strobe on the downbeat"
}
Preset::Trails => {
"default + image chain: loudness-held feedback trails that zoom on kicks, flux-driven displace, punchier colour"
}
}
}
/// The graph this preset produces for the given mode.
pub fn graph(self, mode: GraphMode) -> Graph {
let base = mode.default_graph();
let (scale, rot, warp) = mode.preset_targets();
match self {
Preset::Default => base,
Preset::Minimal => Graph::default(),
Preset::Hyper => {
let mut g = base;
for r in g.routes.iter_mut() {
if r.threshold > 0.0 {
r.threshold *= 0.8; // fire sooner
} else {
r.amount *= 1.6; // push harder
}
}
g
}
Preset::Psychedelic => {
let mut g = base;
// Effect-target id ranges (7..=11 in every mode) get pushed; the
// form gets constant LFO drift so it never sits still.
for r in g.routes.iter_mut() {
if (7..=11).contains(&r.target) {
r.amount *= 2.2;
} else if r.threshold > 0.0 {
r.threshold = 0.55;
}
}
g.routes.push(Route::cont(Source::LfoSlow, warp, 0.12));
g.routes.push(Route::cont(Source::LfoFast, rot, 0.015));
g
}
Preset::Patched => {
let mut g = base;
let via = |node: u32, target: u16, amount: f32| Route {
node: Some(node),
..Route::cont(Source::Const, target, amount)
};
// low_on → Envelope → scale (sigil) / cell (tunnel): a punch per kick.
let env = g.add_node(
Op::Env {
threshold: 0.45,
decay: 0.3,
},
[220.0, 40.0],
);
g.node_mut(env).unwrap().inputs[0] = Input::Source(Source::LowOn);
g.routes.push(via(env, scale, 0.35));
// Noise → Remap(−1..1) → swirl rotate: slow wandering spin.
let noise = g.add_node(Op::Noise, [220.0, 160.0]);
g.node_mut(noise).unwrap().inputs[0] = Input::Value(0.15);
let bi = g.add_node(
Op::Remap {
in_lo: 0.0,
in_hi: 1.0,
out_lo: -1.0,
out_hi: 1.0,
},
[420.0, 160.0],
);
g.node_mut(bi).unwrap().inputs[0] = Input::Node(noise);
g.routes.push(via(bi, rot, 0.012));
// high_on → Counter(4) → Lag → warp: warp steps with the hats.
let count = g.add_node(
Op::Counter {
threshold: 0.5,
steps: 4,
},
[220.0, 280.0],
);
g.node_mut(count).unwrap().inputs[0] = Input::Source(Source::HighOn);
let lag = g.add_node(
Op::Lag {
up: 0.08,
down: 0.08,
},
[420.0, 280.0],
);
g.node_mut(lag).unwrap().inputs[0] = Input::Node(count);
g.routes.push(via(lag, warp, 0.15));
g
}
Preset::Riddim => {
let mut g = base;
for r in g.routes.iter_mut() {
if r.source == Source::Loud && r.threshold == 0.0 {
r.amount *= 0.5;
}
}
g.routes.extend(mode.riddim_routes());
g
}
Preset::Trails => {
let mut g = base;
let remap = |g: &mut Graph, input: Input, lo: f32, hi: f32, pos: [f32; 2]| {
let id = g.add_node(
Op::Remap {
in_lo: 0.0,
in_hi: 1.0,
out_lo: lo,
out_hi: hi,
},
pos,
);
g.node_mut(id).unwrap().inputs[0] = input;
Input::Node(id)
};
// Louder = longer trails.
let decay = remap(
&mut g,
Input::Source(Source::Loud),
0.82,
0.95,
[220.0, 40.0],
);
// Kick envelope pushes the feedback zoom.
let env = g.add_node(
Op::Env {
threshold: 0.45,
decay: 0.25,
},
[20.0, 160.0],
);
g.node_mut(env).unwrap().inputs[0] = Input::Source(Source::LowOn);
let zoom = remap(&mut g, Input::Node(env), 0.004, 0.04, [220.0, 160.0]);
// Spectral flux shakes the displacement.
let amount = remap(
&mut g,
Input::Source(Source::Flux),
0.0,
0.035,
[220.0, 280.0],
);
let fb = g.add_top(TopOp::Feedback, Img::Scene, [460.0, 40.0]);
let t = g.image.top_mut(fb).unwrap();
t.params[0] = decay;
t.params[1] = zoom;
t.params[2] = Input::Value(0.004);
let dp = g.add_top(TopOp::Displace, Img::Top(fb), [660.0, 40.0]);
g.image.top_mut(dp).unwrap().params[0] = amount;
let lv = g.add_top(TopOp::Level, Img::Top(dp), [860.0, 40.0]);
let t = g.image.top_mut(lv).unwrap();
t.params[1] = Input::Value(1.1);
t.params[3] = Input::Value(1.3);
g.image.out = Some(lv);
g
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The launcher serialises a graph to RON and sigil reads it back — guard
/// that contract (enum/field representation) against silent drift.
#[test]
fn ron_round_trip() {
let g = Graph::default_sigil();
let s = ron::ser::to_string(&g).expect("serialise");
let back: Graph = ron::from_str(&s).expect("deserialise");
assert_eq!(g.routes.len(), back.routes.len());
// a representative continuous route and a trigger survive intact
let scale = back
.routes
.iter()
.find(|r| r.target == sigil::SCALE)
.unwrap();
assert_eq!(scale.source, Source::Low);
let freeze = back
.routes
.iter()
.find(|r| r.target == sigil::FREEZE)
.unwrap();
assert!((freeze.threshold - 0.62).abs() < 1e-6);
}
/// Ferro: id layout (columns in order, effects at 7..=11) and a sum.
#[test]
fn default_ferro_sums_and_layout() {
for (i, t) in ferro::TARGETS.iter().enumerate() {
assert_eq!(t.id as usize, i);
}
for id in [
ferro::GLITCH,
ferro::SCANLINE,
ferro::GRAIN,
ferro::SWIRL_ZOOM,
ferro::SWIRL_ROT,
] {
assert!((7..=11).contains(&id));
}
let mut g = Modulator::new(Graph::default_ferro());
let mut s = Sources::new();
s.set(Source::Bass, 0.5);
s.set(Source::Gap, 0.2);
let m = g.step(&s, 1.0 / 30.0);
let want = 0.6 * 0.5 - 0.9 * 0.2;
assert!((m[ferro::FIELD as usize] - want).abs() < 1e-6);
s.set(Source::Drop, 0.6);
assert!(g.fires(ferro::BURST, &s));
assert_eq!(GraphMode::from_flag("ferro"), Some(GraphMode::Ferro));
}
/// Bass-music sources survive the launcher→sigil RON hop, and the riddim
/// preset actually drives each mode from them.
#[test]
fn riddim_preset_round_trips_and_reacts() {
for m in GraphMode::ALL {
let g = Preset::Riddim.graph(m);
let back: Graph = ron::from_str(&ron::ser::to_string(&g).unwrap()).unwrap();
assert!(back.routes.iter().any(|r| r.source == Source::Growl));
let mut md = Modulator::new(back);
let mut s = Sources::new();
let quiet = md.step(&s, 1.0 / 30.0);
s.set(Source::Gap, 1.0);
let gap = md.step(&s, 1.0 / 30.0);
assert!(
quiet.iter().zip(&gap).any(|(a, b)| b < a),
"{m:?}: gap does nothing"
);
s.set(Source::Downbeat, 1.0);
assert!(
m.targets().iter().any(|t| t.trigger && md.fires(t.id, &s)),
"{m:?}: downbeat fires nothing"
);
}
for (i, s) in Source::ALL.iter().enumerate() {
assert_eq!(s.idx(), i);
}
}
/// Default graph must reproduce the old inline sums exactly (one spot-check
/// per kind) so an absent `--routes` is behaviourally unchanged.
#[test]
fn default_sums_match_old_formulas() {
let mut g = Modulator::new(Graph::default_sigil());
let mut s = Sources::new();
s.set(Source::Loud, 0.5);
s.set(Source::Flux, 0.3);
s.set(Source::Tension, 0.4);
let m = g.step(&s, 1.0 / 30.0);
// glow ← 0.45·loud + 0.40·flux + 0.35·tension
let want = 0.45 * 0.5 + 0.40 * 0.3 + 0.35 * 0.4;
assert!((m[sigil::GLOW as usize] - want).abs() < 1e-6);
}
/// Same guard for tunnel: a spot-check continuous sum + a trigger.
#[test]
fn default_tunnel_sums_and_triggers() {
let mut g = Modulator::new(Graph::default_tunnel());
let mut s = Sources::new();
s.set(Source::Loud, 0.5);
s.set(Source::Tension, 0.4);
let m = g.step(&s, 1.0 / 30.0);
// glow ← 0.45·loud + 0.25·tension
let want = 0.45 * 0.5 + 0.25 * 0.4;
assert!((m[tunnel::GLOW as usize] - want).abs() < 1e-6);
// morph fires on strong novelty, the wave on a kick
s.set(Source::Novelty, 0.8);
assert!(g.fires(tunnel::MORPH, &s));
assert!(!g.fires(tunnel::WAVE, &s));
s.set(Source::LowOn, 0.6);
assert!(g.fires(tunnel::WAVE, &s));
}
/// Ophanim: a spot-check sum, a trigger, and the id-layout invariants the
/// presets rely on (effects at 7..=11, every column in order).
#[test]
fn default_ophanim_sums_and_layout() {
let mut g = Modulator::new(Graph::default_ophanim());
let mut s = Sources::new();
s.set(Source::Kick, 0.5);
s.set(Source::Loud, 0.4);
let m = g.step(&s, 1.0 / 30.0);
let want = 0.8 * 0.5 + 0.3 * 0.4;
assert!((m[ophanim::CORE as usize] - want).abs() < 1e-6);
s.set(Source::Novelty, 0.8);
assert!(g.fires(ophanim::BLINK, &s));
for (i, t) in ophanim::TARGETS.iter().enumerate() {
assert_eq!(t.id as usize, i);
}
for id in [
ophanim::GLITCH,
ophanim::SCANLINE,
ophanim::GRAIN,
ophanim::SWIRL_ZOOM,
ophanim::SWIRL_ROT,
] {
assert!((7..=11).contains(&id));
}
for p in Preset::ALL {
for m in GraphMode::ALL {
let g = p.graph(m);
let n = m.targets().len() as u16;
assert!(g.routes.iter().all(|r| r.target < n), "{p:?} {m:?}");
}
}
}
}