diff --git a/config.toml.example b/config.toml.example
index 305ddacb4..05fcda42f 100644
--- a/config.toml.example
+++ b/config.toml.example
@@ -96,13 +96,14 @@ eq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# UI theme name (check ~/.config/cliamp/themes/ for available themes)
# theme = "Tokyo Night"
-# Visualizer mode: Bars, BarsDot, Rain, BarsOutline, Bricks, Columns, ClassicPeak, Wave, Scatter, Flame, Retro, Pulse, Matrix, Binary, Sakura, Firework, Bubbles, Logo, Terrain, Scope, Heartbeat, Butterfly, Ascii, Firefly, Mosaic, Sand, Geyser, ClassicLED, Stereo, Mirror, Omarchy, RedSector, YinYang, Ethereal, or None
+# Visualizer mode: Bars, BarsDot, Rain, BarsOutline, Bricks, Columns, ClassicPeak, Wave, Scatter, Flame, Retro, Pulse, Matrix, Binary, Sakura, Firework, Bubbles, Logo, Terrain, Scope, Heartbeat, Butterfly, Ascii, Firefly, Mosaic, Sand, Geyser, ClassicLED, Stereo, Mirror, Omarchy, RedSector, YinYang, Ethereal, Wormhole, or None
# Mirror draws tapered Braille bars around a persistent horizontal center axis.
# YinYang koi chase each other across a wide strip, leaving on the right
# and coming back on the left; taller panels have them circle a lily pad
# whose lotus opens with the music.
# Ethereal: Flame-style Braille clouds and stars, with no painted background.
# Follows terminal colors by default and the selected UI theme; no Omarchy needed.
+# Wormhole: wireframe tunnel that flies one ring per beat.
# visualizer = "Bars"
# Reduce CPU usage by lowering UI cadence and disabling visualization.
diff --git a/docs/configuration.md b/docs/configuration.md
index 3853b1248..f1c33ef0c 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -74,7 +74,7 @@ eq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# keeps it available, and both values are restored after restart.
# Visualizer mode (leave empty for default Bars)
-# Options: Bars, BarsDot, Rain, BarsOutline, Bricks, Columns, ClassicPeak, Wave, Scatter, Flame, Retro, Pulse, Matrix, Binary, Sakura, Firework, Bubbles, Logo, Terrain, Scope, Heartbeat, Butterfly, Ascii, Firefly, Mosaic, Sand, Geyser, ClassicLED, Stereo, Mirror, Omarchy, RedSector, YinYang, Ethereal, None
+# Options: Bars, BarsDot, Rain, BarsOutline, Bricks, Columns, ClassicPeak, Wave, Scatter, Flame, Retro, Pulse, Matrix, Binary, Sakura, Firework, Bubbles, Logo, Terrain, Scope, Heartbeat, Butterfly, Ascii, Firefly, Mosaic, Sand, Geyser, ClassicLED, Stereo, Mirror, Omarchy, RedSector, YinYang, Ethereal, Wormhole, None
# Mirror draws tapered Braille bars around a persistent horizontal center axis.
# ClassicPeak uses smooth bars and floating peak caps, with sampling aligned
# to audible playback and adaptive redraws for smooth motion.
@@ -88,6 +88,8 @@ eq = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# Inspired by Omarchy's Ethereal cosmic wallpaper.
# It follows terminal colors by default and the selected UI theme.
# Omarchy is not required.
+# Wormhole is a wireframe tunnel that flies one ring per beat. Kick, snare
+# and hi-hat each set off their own effect.
visualizer = "Bars"
# Visualizer volume linking (default: true)
diff --git a/site/index.html b/site/index.html
index 0cf0d5301..ef4a4c469 100644
--- a/site/index.html
+++ b/site/index.html
@@ -331,7 +331,7 @@
Playlists, a 10-band equalizer, 34 visualizers, synced lyrics, podcasts, remote control, and Lua plugins. Stream from Spotify, Qobuz, Tidal, Bandcamp, YouTube Music, SoundCloud, Mixcloud, NetEase Cloud Music, Yandex Music, Plex, Jellyfin, Emby, Navidrome, Lyrion, Audiobookshelf — plus podcast feeds and about 58,000 internet radio stations.
+ Playlists, a 10-band equalizer, 35 visualizers, synced lyrics, podcasts, remote control, and Lua plugins. Stream from Spotify, Qobuz, Tidal, Bandcamp, YouTube Music, SoundCloud, Mixcloud, NetEase Cloud Music, Yandex Music, Plex, Jellyfin, Emby, Navidrome, Lyrion, Audiobookshelf — plus podcast feeds and about 58,000 internet radio stations.
SYNCED LYRICS
diff --git a/ui/new_vis_smoke_test.go b/ui/new_vis_smoke_test.go
index a865f2d24..ea046bcd3 100644
--- a/ui/new_vis_smoke_test.go
+++ b/ui/new_vis_smoke_test.go
@@ -19,6 +19,7 @@ func TestCharmVisualizersRender(t *testing.T) {
"RedSector",
"YinYang",
"Ethereal",
+ "Wormhole",
}
signal := make([]float64, 2048)
diff --git a/ui/styles.go b/ui/styles.go
index 4d79fc3a0..0731f53ca 100644
--- a/ui/styles.go
+++ b/ui/styles.go
@@ -122,6 +122,7 @@ func ApplyThemeColors(t theme.Theme) {
refreshRedSectorANSI()
refreshYinYangANSI()
refreshEtherealANSI()
+ refreshWormholeANSI()
}
func contrastingTextColor(hex string) string {
diff --git a/ui/testdata/vis_golden.txt b/ui/testdata/vis_golden.txt
index 2bdcabecd..4a0ec464e 100644
--- a/ui/testdata/vis_golden.txt
+++ b/ui/testdata/vis_golden.txt
@@ -136,6 +136,10 @@ Ethereal 48x9 3fb94d5eb733b7ce
Ethereal 13x3 c0dc6b6f63118086
Ethereal 40x1 0322fc4422039a63
Ethereal 140x16 0eabe79c63ed72d9
+Wormhole 48x9 9bce12c1ac94f400
+Wormhole 13x3 bb6e118b5a7043af
+Wormhole 40x1 10c3e7f0ee69f4d1
+Wormhole 140x16 23a7b8ee3ad8de0a
None 48x9 a09d945a1cd8d6e5
None 13x3 a09d945a1cd8d6e5
None 40x1 a09d945a1cd8d6e5
diff --git a/ui/vis_registry.go b/ui/vis_registry.go
index 5f298dd54..2cf3c6605 100644
--- a/ui/vis_registry.go
+++ b/ui/vis_registry.go
@@ -40,6 +40,7 @@ const (
VisRedSector // tumbling wireframe equalizer over a drifting starfield
VisYinYang // two koi chasing round a lily pad, flicking their tails to the drums
VisEthereal // blue-violet nebula clouds and warm, twinkling starlight
+ VisWormhole // wireframe tunnel whose rings flow out of a bending mouth
VisNone // hidden — no visualizer
VisCount // sentinel for cycling
)
@@ -87,6 +88,7 @@ var visModes = [VisCount]visEntry{
VisRedSector: {"RedSector", newRedSectorDriver},
VisYinYang: {"YinYang", newYinYangDriver},
VisEthereal: {"Ethereal", newEtherealDriver},
+ VisWormhole: {"Wormhole", newWormholeDriver},
VisNone: {"None", newNoOpDriver},
}
diff --git a/ui/vis_wormhole.go b/ui/vis_wormhole.go
new file mode 100644
index 000000000..462af108b
--- /dev/null
+++ b/ui/vis_wormhole.go
@@ -0,0 +1,786 @@
+package ui
+
+import (
+ "image/color"
+ "math"
+ "slices"
+ "strings"
+ "time"
+)
+
+// Wormhole: a wireframe tunnel. Rings leave the mouth in the middle, one per
+// kick when the beat is steady, and grow past the edges. Kick, snare and
+// hi-hat each set off an effect.
+
+const (
+ // Speed in laps/s (one lap = tunnel depth). Top speed keeps a frame under
+ // 1/4 ring spacing, or the rings seem to run backwards.
+ wormholeCruise = 0.15
+ wormholeLoudGain = 0.1
+ wormholeTopSpeed = 0.45
+ wormholeSpeedRate = 2.0
+ wormholeFall = 2.5
+ wormholeLoudRate = 1.5
+
+ // Tempo: median of the last kick gaps, folded into 60..180 BPM.
+ wormholeGaps = 8
+ wormholeSureStep = 0.25
+ wormholeSureWait = 2.0 // s without a kick before the confidence fades
+ wormholeLock = 0.3 // speed change per ring of phase error
+ wormholeLockMax = 0.15
+ wormholeTwistBeat = 0.06 // rad/s of wall rotation per beat/s
+ wormholeSpiral = 0.04 // rad per unit of 1/z, per beat/s
+
+ // Rings on screen.
+ wormholeRings = 10
+ // Tunnel size at depth 1 as a share of the panel.
+ wormholeMouth = 0.12
+ wormholeFar = 0.85
+ wormholeNear = 0.08
+ wormholeInner = 1 / wormholeFar // the same span in 1/z
+ wormholeReach = 1/wormholeNear - wormholeInner
+ wormholeShown = 0.7 // rings fade in until this depth
+ wormholeBright = 0.45 // rings nearer than this are bright
+ wormholeFlat = 0.35 // min height/width
+ // A ring shows at the mouth this many ring spacings after it starts.
+ wormholeEntry = (1 - wormholeFar) * wormholeRings
+
+ // Bend of the far end and rotation of the wall.
+ wormholeBend = 0.2
+ wormholeBendRate = 0.08
+ wormholeBendLoud = 0.25
+ wormholeTwist = 0.05
+ wormholeTwistLoud = 0.15
+
+ // Spectral rings: bulge by up to this share where the band was loud.
+ wormholeSpectral = 0.3
+ wormholeShapes = wormholeRings + 2
+
+ // Cross-section: circle, hexagon, square, star.
+ wormholeForms = 4
+ wormholeToneRelax = 0.01
+ wormholeToneSpan = 0.05
+ wormholeFormRate = 0.4
+ wormholeStarDepth = 0.3
+
+ // Hyperspace: the short energy average jumps above the long one.
+ wormholeFastRate = 4.0
+ wormholeSlowRate = 0.15
+ wormholeDropRatio = 1.5
+ wormholeDropFloor = 0.12
+ wormholeDropGap = 8.0 // s between drops
+ wormholeDropWarm = 4.0 // s of music before a drop counts
+ wormholeSilence = 0.02
+ wormholeQuiet = 0.5 // s of silence before the tunnel stops and holds its bend and twist
+ wormholeWarpRise = 0.15
+ wormholeWarpFade = 0.6
+ wormholeWarpLife = 2.5
+ wormholeWarpShown = 0.05
+ wormholeWarpWiden = 0.25
+ wormholeWarpSmear = 0.8 // in 1/z
+ wormholeStars = 40
+ wormholeStarRate = 3.0 // laps/s of the star field at full warp
+ wormholeStarTail = 4.0 // in 1/z at full warp
+
+ // A hit as strong as the recent ones gets this strength.
+ wormholeHitTypical = 0.6
+ // Bass shock wave; width in 1/z.
+ wormholeWaveTime = 0.5
+ wormholeWaveWidth = 0.7
+ wormholeSwell = 0.15
+ wormholeWaveLit = 0.4
+ wormholeWaveHot = 0.75
+
+ // Snare: rock the wall, alternating sides.
+ wormholeRock = 0.1
+ // Hi-hat: sparks along the wall.
+ wormholeSparkHit = 6
+ wormholeSparkNear = 0.2
+ wormholeSparkFar = 0.5
+ wormholeSparkLife = 0.25
+ wormholeSparkTail = 0.15
+ wormholeSparkRush = 0.6
+ wormholeSparkArc = 2 * math.Pi / 3 // the top third, where the rings show the treble
+ wormholeSparks = 18
+ wormholeWaves = 4
+ wormholeMaxSteps = 512 // longest streak in dots
+
+ // Per-band min/max tracking.
+ wormholeBandRelax = 0.08
+ wormholeBandSpan = 0.12
+)
+
+const (
+ wormholeBass = iota
+ wormholeMids
+ wormholeTreble
+ wormholeParts
+)
+
+// Cell tiers, low to high; a cell shows the highest one drawn into it.
+const (
+ wormholeDim int8 = iota + 1
+ wormholeText
+ wormholeBeat
+ wormholeHot
+)
+
+const wormholeTiers = int(wormholeHot)
+
+// Rebuilt by ApplyThemeColors.
+var wormholeANSI [wormholeTiers]styleANSI
+
+func refreshWormholeANSI() {
+ for i, c := range [wormholeTiers]color.Color{ColorDim, ColorText, SpectrumMid, SpectrumHigh} {
+ wormholeANSI[i] = foregroundANSI(c)
+ }
+}
+
+func flushWormholeRun(sb, run *strings.Builder, tier int) {
+ var style styleANSI
+ if tier > 0 && tier <= len(wormholeANSI) {
+ style = wormholeANSI[tier-1]
+ }
+ writeStyledRun(sb, run, style)
+}
+
+type wormholeDriver struct {
+ spectrumDriverBase
+
+ grid brailleGrid
+ frame wormholeFrame
+ travel float64 // laps
+ speed float64 // laps/s
+ loud float64
+ lo, hi [DefaultSpectrumBands]float64
+ lastTick time.Time
+
+ bendPhase, twist float64
+ onsets [wormholeParts]wormholeOnset
+ prev [DefaultSpectrumBands]float64
+ hasPrev bool
+ typical [wormholeParts]float64 // recent hit ratios
+ clock float64 // playback seconds, frozen while paused
+
+ // Tempo: kick gaps and beat period in s (0 = none yet), confidence 0..1.
+ gaps [wormholeGaps]float64
+ counted int
+ lastKick, beat float64
+ sure, spiral float64
+
+ // Live band levels, and a snapshot per ring taken at the mouth.
+ glow [DefaultSpectrumBands]float64
+ shapes [wormholeShapes][DefaultSpectrumBands]float64
+ born int
+
+ tone, toneLo, toneHi float64
+ form, formShift, jump float64
+
+ fastE, slowE float64
+ warpAt, warp float64
+ starTravel float64
+ heard float64 // s of music since the last silence
+ quiet float64 // s of silence
+
+ waves [wormholeWaves]wormholeWave
+ nextWave int
+
+ rock, rockTo, rockSide float64
+
+ sparks [wormholeSparks]wormholeSpark
+ struck int // sparks so far, also seeds the next spark's position
+}
+
+// wormholeOnset finds a sudden rise across a share of the bands, judged
+// against how much they usually rise. Hits are at least gap ticks apart.
+type wormholeOnset struct {
+ from, to float64
+ k, floor float64
+ gap, since int
+ mean, dev float64
+}
+
+func (o *wormholeOnset) reset() {
+ o.mean, o.dev, o.since = 0.03, 0.02, o.gap
+}
+
+// step reports a hit and its strength, 1 at the threshold.
+func (o *wormholeOnset) step(bands, prev []float64) (bool, float64) {
+ n := len(bands)
+ rise := 0.0
+ for i := int(o.from * float64(n)); i < int(o.to*float64(n)) && i < len(prev); i++ {
+ rise += max(0, bands[i]-prev[i])
+ }
+ threshold := max(o.mean+o.k*o.dev, o.floor)
+ hit := rise > threshold && o.since >= o.gap
+ o.mean = o.mean*0.92 + rise*0.08
+ o.dev = o.dev*0.92 + math.Abs(rise-o.mean)*0.08
+ if hit {
+ o.since = 0
+ } else {
+ o.since++
+ }
+ return hit, rise / threshold
+}
+
+// wormholeHash returns a fixed pseudo-random value in [0, 1) for item i, a
+// different one for each slot.
+func wormholeHash(i, slot int) float64 {
+ h := uint64(i)*7919 + uint64(slot)*104729
+ h ^= h >> 16
+ h *= 0x45d9f3b37197344b
+ h ^= h >> 16
+ return float64(h%10000) / 10000
+}
+
+// wormholeFrame is the projection of the frame that Render draws.
+type wormholeFrame struct {
+ halfW, halfH float64
+ rx, ry float64 // mouth radii in dots
+ bendX, bendY float64
+ formI int // shape, and its blend into the next one
+ formF float64
+}
+
+type wormholeWave struct{ at, strength float64 } // strength 0 = unused
+
+type wormholeSpark struct{ angle, z, at, travel float64 }
+
+func newWormholeDriver() visModeDriver {
+ d := &wormholeDriver{}
+ d.OnEnter(nil)
+ return d
+}
+
+func (d *wormholeDriver) OnEnter(*Visualizer) {
+ *d = wormholeDriver{}
+ for i := range d.lo {
+ d.lo[i] = 1 // start wide open
+ }
+ d.rockSide = 1
+ // Gaps in 25 ms ticks: at most 240 kicks a minute.
+ d.onsets = [wormholeParts]wormholeOnset{
+ wormholeBass: {from: 0, to: 0.3, k: 2.0, floor: 0.05, gap: 10},
+ wormholeMids: {from: 0.3, to: 0.6, k: 2.0, floor: 0.04, gap: 8},
+ wormholeTreble: {from: 0.6, to: 1, k: 1.8, floor: 0.025, gap: 6},
+ }
+ for i := range d.onsets {
+ d.onsets[i].reset()
+ }
+ for i := range d.sparks {
+ d.sparks[i].at = math.Inf(-1)
+ }
+ d.lastKick, d.warpAt = math.Inf(-1), math.Inf(-1)
+ d.born = wormholeBorn(0)
+ d.toneLo = 1
+ d.quiet = wormholeQuiet
+}
+
+// Audible tap so the effects line up with what you hear.
+func (*wormholeDriver) AnalysisSpec(*Visualizer) VisAnalysisSpec {
+ spec := spectrumAnalysisSpec(DefaultSpectrumBands)
+ spec.Tap = VisTapAudible
+ return spec
+}
+
+func (d *wormholeDriver) pauseSettled() bool { return d.speed == 0 }
+
+// Tick twice per rendered frame, so every frame shows a fresh step.
+func (*wormholeDriver) TickInterval(_ *Visualizer, ctx VisTickContext) time.Duration {
+ if ctx.Playing && !ctx.OverlayActive {
+ return TickRawSample
+ }
+ return defaultDriverTickInterval(ctx)
+}
+
+func (*wormholeDriver) ownsCadence() {}
+
+func (d *wormholeDriver) Tick(v *Visualizer, ctx VisTickContext) {
+ defaultDriverTick(v, ctx, d.AnalysisSpec(v))
+ if ctx.OverlayActive {
+ // Suspend() also sends this while paused, so keep the speed.
+ d.lastTick = time.Time{}
+ return
+ }
+ if !ctx.Now.IsZero() && !ctx.Now.After(d.lastTick) {
+ return
+ }
+ dt := clampFrameDT(ctx.Now, d.lastTick, d.TickInterval(v, ctx)).Seconds()
+ d.lastTick = ctx.Now
+
+ switch {
+ case ctx.Paused:
+ d.speed = wormholeEase(d.speed, 0, wormholeFall, dt)
+ if d.speed < 0.01 {
+ d.speed = 0
+ }
+ case ctx.Playing:
+ bands := v.SmoothedBands()
+ d.loud = wormholeEase(d.loud, d.levels(bands, dt), wormholeLoudRate, dt)
+ d.clock += dt
+ d.hits(bands)
+ d.rock = wormholeEase(d.rock, d.rockTo, 14, dt)
+ if d.clock-d.lastKick > wormholeSureWait {
+ d.sure = max(0, d.sure-0.5*dt)
+ }
+ energy, tone, heard := wormholeTimbre(bands)
+ d.morph(tone, heard, dt)
+ d.dive(energy, dt)
+
+ d.speed = wormholeEase(d.speed, d.targetSpeed(), wormholeSpeedRate, dt)
+ beats := d.beatRate()
+ d.spiral = wormholeEase(d.spiral, wormholeSpiral*beats, 0.5, dt)
+ if d.quiet < wormholeQuiet {
+ d.bendPhase += (wormholeBendRate + wormholeBendLoud*d.loud) * dt
+ d.twist += (wormholeTwist + wormholeTwistLoud*d.loud + wormholeTwistBeat*beats) * dt
+ }
+ d.starTravel += wormholeStarRate * d.warp * dt
+ default:
+ // Stopped: ticks are too far apart to ease, just stop.
+ d.speed = 0
+ }
+ d.travel += d.speed * dt
+ d.keepShapes()
+}
+
+func wormholeEase(cur, target, rate, dt float64) float64 {
+ return easeToward(cur, target, rate, rate, dt)
+}
+
+// keepShapes snapshots the glow for each ring that reached the mouth.
+func (d *wormholeDriver) keepShapes() {
+ newest := wormholeBorn(d.travel)
+ for d.born < newest {
+ d.born++
+ d.shapes[wormholeSlot(d.born)] = d.glow
+ }
+}
+
+// beatRate is the tempo in beats/s, weighted by how sure it is.
+func (d *wormholeDriver) beatRate() float64 {
+ if d.beat == 0 {
+ return 0
+ }
+ return d.sure / d.beat
+}
+
+// targetSpeed is one ring per beat when the tempo is sure, else the cruise.
+// The tunnel stops when there is nothing to hear.
+func (d *wormholeDriver) targetSpeed() float64 {
+ if d.quiet >= wormholeQuiet {
+ return 0
+ }
+ target := wormholeCruise + wormholeLoudGain*d.loud
+ if d.beat > 0 {
+ // Phase error in rings: 0 when a ring reaches the mouth on the kick.
+ ring := d.travel*wormholeRings - wormholeEntry
+ err := ring - (d.clock-d.lastKick)/d.beat
+ err -= math.Round(err)
+ lock := max(-wormholeLockMax, min(wormholeLockMax, -wormholeLock*err)) * (1 - d.warp)
+ beat := (1 + lock) / (d.beat * wormholeRings)
+ target += (beat - target) * d.sure
+ }
+ return target + (wormholeTopSpeed-target)*d.warp
+}
+
+// hits finds kick, snare and hi-hat as rises, not levels: a louder bass
+// floor must not hide the kicks.
+func (d *wormholeDriver) hits(bands []float64) {
+ n := min(len(bands), len(d.prev))
+ prev := d.prev
+ copy(d.prev[:], bands[:n])
+ if !d.hasPrev {
+ d.hasPrev = true
+ return
+ }
+ for part := range d.onsets {
+ hit, ratio := d.onsets[part].step(bands[:n], prev[:n])
+ if !hit {
+ continue
+ }
+ // Judge the hit against the recent ones, or every kick looks hard.
+ strength := wormholeHitTypical
+ if d.typical[part] > 0 {
+ strength = min(1, wormholeHitTypical*ratio/d.typical[part])
+ d.typical[part] += (ratio - d.typical[part]) * 0.2
+ } else {
+ d.typical[part] = ratio
+ }
+ switch part {
+ case wormholeBass:
+ d.kick(strength)
+ case wormholeMids:
+ d.rockTo, d.rockSide = d.rockSide*wormholeRock, -d.rockSide
+ default:
+ d.strike(strength)
+ }
+ }
+}
+
+func (d *wormholeDriver) kick(strength float64) {
+ d.waves[d.nextWave] = wormholeWave{at: d.clock, strength: strength}
+ d.nextWave = (d.nextWave + 1) % wormholeWaves
+
+ gap := d.clock - d.lastKick
+ d.lastKick = d.clock
+ if gap < 0.25 || gap > 2 {
+ return // no beat
+ }
+ // Fold into 60..180 BPM.
+ for gap < 60.0/180 {
+ gap *= 2
+ }
+ for gap > 60.0/60 {
+ gap /= 2
+ }
+ // Confidence grows only while the kicks agree with the tempo.
+ if d.beat == 0 || math.Abs(gap-d.beat) < 0.1*d.beat {
+ d.sure = min(1, d.sure+wormholeSureStep)
+ } else {
+ d.sure = max(0, d.sure-wormholeSureStep/2)
+ }
+ d.gaps[d.counted%wormholeGaps] = gap
+ d.counted++
+ sorted := d.gaps
+ n := min(d.counted, wormholeGaps)
+ slices.Sort(sorted[:n])
+ d.beat = sorted[n/2]
+}
+
+// strike throws sparks at the top of the wall, where the rings show the
+// treble. From there they turn with the wall.
+func (d *wormholeDriver) strike(strength float64) {
+ for range max(1, int(math.Round(strength*wormholeSparkHit))) {
+ z := wormholeSparkNear + (wormholeSparkFar-wormholeSparkNear)*wormholeHash(d.struck, 1)
+ top := -math.Pi/2 + (wormholeHash(d.struck, 0)-0.5)*wormholeSparkArc
+ d.sparks[d.struck%wormholeSparks] = wormholeSpark{
+ angle: top - d.twist - d.rock - d.spiral/z,
+ z: z,
+ at: d.clock,
+ travel: d.travel,
+ }
+ d.struck++
+ }
+}
+
+// levels normalises each band against its own recent range and returns the
+// overall loudness, 0..1.
+func (d *wormholeDriver) levels(bands []float64, dt float64) (loud float64) {
+ n := min(len(bands), len(d.lo))
+ for i, b := range bands[:n] {
+ d.hi[i] = max(b, d.hi[i]-wormholeBandRelax*dt)
+ d.lo[i] = min(b, d.lo[i]+wormholeBandRelax*dt)
+ level := (b - d.lo[i]) / max(d.hi[i]-d.lo[i], wormholeBandSpan)
+ d.glow[i] = easeToward(d.glow[i], level, 12, 6, dt)
+ loud += level / float64(n)
+ }
+ return loud
+}
+
+// wormholeTimbre returns the mean level and the tone, 0 for all bass to 1 for
+// all treble. Near silence has no tone.
+func wormholeTimbre(bands []float64) (energy, tone float64, heard bool) {
+ sum, moment := 0.0, 0.0
+ for i, b := range bands {
+ sum += b
+ moment += float64(i) * b
+ }
+ energy = sum / float64(max(1, len(bands)))
+ if sum <= 1e-3 || len(bands) < 2 {
+ return energy, 0, false
+ }
+ return energy, moment / sum / float64(len(bands)-1), true
+}
+
+// morph picks the cross-section from the tone, against its recent range.
+func (d *wormholeDriver) morph(tone float64, heard bool, dt float64) {
+ if heard {
+ if d.toneHi < d.toneLo {
+ // The first sound sets the range.
+ d.tone, d.toneLo, d.toneHi = tone, tone, tone
+ }
+ d.tone = wormholeEase(d.tone, tone, 1, dt)
+ d.toneHi = max(d.tone, d.toneHi-wormholeToneRelax*dt)
+ d.toneLo = min(d.tone, d.toneLo+wormholeToneRelax*dt)
+ target := (d.tone - d.toneLo) / max(d.toneHi-d.toneLo, wormholeToneSpan) * (wormholeForms - 1)
+ d.form = wormholeEase(d.form, target, wormholeFormRate, dt)
+ }
+ d.formShift = wormholeEase(d.formShift, d.jump, 3, dt)
+}
+
+// dive finds drops in the raw energy and runs the hyperspace envelope.
+func (d *wormholeDriver) dive(energy, dt float64) {
+ if energy < wormholeSilence {
+ d.heard = 0
+ d.quiet += dt
+ } else {
+ d.quiet = 0
+ if d.heard == 0 {
+ // A track rising out of silence is no drop.
+ d.fastE, d.slowE = energy, energy
+ }
+ d.heard += dt
+ }
+ d.fastE = wormholeEase(d.fastE, energy, wormholeFastRate, dt)
+ // While warming up the long average learns the level as fast as the short one.
+ slow := wormholeSlowRate
+ if d.heard < wormholeDropWarm {
+ slow = wormholeFastRate
+ }
+ d.slowE = wormholeEase(d.slowE, energy, slow, dt)
+ drop := d.fastE > wormholeDropRatio*d.slowE && d.fastE > wormholeDropFloor
+ if drop && d.heard >= wormholeDropWarm && d.clock-d.warpAt > wormholeDropGap {
+ d.warpAt = d.clock
+ d.jump++
+ }
+ d.warp = wormholeWarpAt(d.clock - d.warpAt)
+}
+
+// wormholeWarpAt is the hyperspace envelope, age seconds after a drop.
+func wormholeWarpAt(age float64) float64 {
+ switch {
+ case age < 0 || age > wormholeWarpLife:
+ return 0
+ case age < wormholeWarpRise:
+ return age / wormholeWarpRise
+ }
+ return math.Exp(-(age - wormholeWarpRise) / wormholeWarpFade)
+}
+
+// wormholeBorn is the newest ring that has reached the mouth.
+func wormholeBorn(travel float64) int {
+ return int(math.Floor(travel*wormholeRings - wormholeEntry))
+}
+
+func wormholeSlot(ring int) int {
+ return (ring%wormholeShapes + wormholeShapes) % wormholeShapes
+}
+
+// spectrum is the bulge of the wall at screen angle sin and depth z, 0..1.
+func (d *wormholeDriver) spectrum(sin, z float64) float64 {
+ u := math.Acos(max(-1, min(1, sin))) / math.Pi * float64(DefaultSpectrumBands-1)
+ n := (z - 1 + d.travel) * wormholeRings
+ ring := math.Floor(n)
+ a, b := d.ringLevel(int(ring), u), d.ringLevel(int(ring)+1, u)
+ return a + (b-a)*(n-ring)
+}
+
+func (d *wormholeDriver) ringLevel(ring int, u float64) float64 {
+ bands := &d.glow
+ switch {
+ case ring <= d.born-wormholeShapes:
+ return 0
+ case ring <= d.born:
+ bands = &d.shapes[wormholeSlot(ring)]
+ }
+ return sampleBandLinear(bands[:], u)
+}
+
+// wormholeBlend is the radius at wall angle a of shape i mixed with the next
+// one by f, at most 1.
+func wormholeBlend(i int, f, a float64) float64 {
+ cur := wormholeShape(i, a)
+ if f == 0 {
+ return cur
+ }
+ return cur + (wormholeShape((i+1)%wormholeForms, a)-cur)*f
+}
+
+func wormholeShape(kind int, a float64) float64 {
+ switch kind {
+ case 1:
+ return wormholePolygon(6, a)
+ case 2:
+ return wormholePolygon(4, a)
+ case 3:
+ return 1 / (1 + wormholeStarDepth*(1-math.Cos(5*a)))
+ }
+ return 1
+}
+
+// wormholePolygon is the radius of a regular n-gon with corners at 1.
+func wormholePolygon(n int, a float64) float64 {
+ seg := 2 * math.Pi / float64(n)
+ return math.Cos(seg/2) / math.Cos(wormholeWrap(a, seg)-seg/2)
+}
+
+// wormholeWrap returns x modulo m in [0, m), also for a negative x.
+func wormholeWrap(x, m float64) float64 {
+ return x - m*math.Floor(x/m)
+}
+
+// swell is how much the shock waves widen the tunnel at depth z.
+func (d *wormholeDriver) swell(z float64) float64 {
+ share := 0.0
+ for _, w := range d.waves {
+ front, ok := w.front(d.clock)
+ if !ok {
+ continue
+ }
+ off := (1/z - front) / wormholeWaveWidth
+ share = max(share, w.strength*math.Exp(-off*off))
+ }
+ return wormholeSwell * share
+}
+
+// front returns the 1/z of the wave front; ok is false once it is done.
+func (w wormholeWave) front(clock float64) (invZ float64, ok bool) {
+ age := clock - w.at
+ if w.strength == 0 || age < 0 || age > wormholeWaveTime {
+ return 0, false
+ }
+ return wormholeInner + wormholeReach*age/wormholeWaveTime, true
+}
+
+// bend returns the offset of the far end as a share of the panel.
+func (d *wormholeDriver) bend() (x, y float64) {
+ reach := wormholeBend * (1 + 0.5*d.loud)
+ return reach * math.Sin(d.bendPhase), 0.6 * reach * math.Sin(0.7*d.bendPhase)
+}
+
+// at maps wall angle a and depth z to a screen dot. The spiral turns the wall
+// more the nearer it is.
+func (d *wormholeDriver) at(a, z, scale float64) (float64, float64) {
+ f := &d.frame
+ sin, cos := math.Sincos(a + d.spiral/z)
+ grow := scale * wormholeBlend(f.formI, f.formF, a) * (1 + wormholeSpectral*d.spectrum(sin, z)) / z
+ return f.halfW*(1+f.bendX*z*z) + f.rx*cos*grow, f.halfH*(1+f.bendY*z*z) + f.ry*sin*grow
+}
+
+func (d *wormholeDriver) Render(v *Visualizer) string {
+ rows, cols := v.Rows, v.columns()
+ if rows <= 0 || cols <= 0 {
+ return strings.Repeat("\n", max(0, rows-1))
+ }
+ w, h := cols*2, rows*4
+ d.grid.flush, d.grid.keepRunOnEmpty = flushWormholeRun, true
+ d.grid.ensure(h, w)
+
+ f := &d.frame
+ f.halfW, f.halfH = float64(w)/2, float64(h)/2
+ tunnelH := max(f.halfH, wormholeFlat*f.halfW)
+ // At least 5 dots, or the far rings merge in short panels.
+ mouth := max(wormholeMouth, 5/tunnelH) * (1 + wormholeWarpWiden*d.warp)
+ f.rx, f.ry = mouth*f.halfW, mouth*tunnelH
+ f.bendX, f.bendY = d.bend()
+ form := wormholeWrap(d.form+d.formShift, wormholeForms)
+ f.formI, f.formF = int(form), form-math.Floor(form)
+
+ // One wall line per 4 dot rows. Step evenly in 1/z so the dots are evenly
+ // spaced.
+ lines := max(8, min(16, h/4))
+ for line := range lines {
+ a := 2*math.Pi*float64(line)/float64(lines) + d.twist + d.rock
+ x0, y0 := d.at(a, wormholeFar, 1)
+ x1, y1 := d.at(a, wormholeNear, 1)
+ steps := int(max(math.Abs(x1-x0), math.Abs(y1-y0))) + 1
+ for s := range steps + 1 {
+ t := float64(s) / float64(steps)
+ z := 1 / (wormholeInner + wormholeReach*t)
+ x, y := d.at(a, z, 1+d.swell(z))
+ d.grid.set(int(x), int(y), wormholeDim)
+ }
+ }
+
+ // Ring n enters at the mouth when travel reaches n/wormholeRings.
+ newest := int(math.Floor(d.travel * wormholeRings))
+ for ring := newest - wormholeRings + 1; ring <= newest; ring++ {
+ z := 1 - d.travel + float64(ring)/wormholeRings
+ if z > wormholeFar || z < wormholeNear {
+ continue
+ }
+ swell := d.swell(z)
+ tier := wormholeDim
+ switch {
+ case swell > wormholeWaveHot*wormholeSwell:
+ tier = wormholeHot
+ case swell > wormholeWaveLit*wormholeSwell || d.warp > 0.5:
+ tier = wormholeBeat
+ case z < wormholeBright:
+ tier = wormholeText
+ }
+ shown := max(0, min(1, (wormholeFar-z)/(wormholeFar-wormholeShown))) // fade in at the mouth
+ d.drawRing(z, shown, tier)
+ }
+
+ // Wave fronts.
+ for _, w := range d.waves {
+ front, ok := w.front(d.clock)
+ if !ok {
+ continue
+ }
+ tier := wormholeBeat
+ if w.strength >= wormholeWaveHot {
+ tier = wormholeHot
+ }
+ d.drawRing(1/front, 1, tier)
+ }
+
+ // Sparks.
+ for _, s := range d.sparks {
+ age := d.clock - s.at
+ head := s.z - (d.travel - s.travel) - wormholeSparkRush*age
+ if age > wormholeSparkLife || head < wormholeNear {
+ continue
+ }
+ a := s.angle + d.twist + d.rock
+ tail := head + wormholeSparkTail
+ x0, y0 := d.at(a, head, 1+d.swell(head))
+ x1, y1 := d.at(a, tail, 1+d.swell(tail))
+ d.streak(x0, y0, x1, y1, wormholeText, wormholeBeat)
+ }
+
+ // Star streaks in hyperspace.
+ if d.warp > wormholeWarpShown {
+ for i := range wormholeStars {
+ head := wormholeInner + wormholeReach*math.Mod(wormholeHash(i, 2)+d.starTravel, 1)
+ tail := max(wormholeInner, head-wormholeStarTail*d.warp)
+ a := 2*math.Pi*wormholeHash(i, 3) + d.twist
+ reach := 0.4 + 0.5*wormholeHash(i, 4)
+ x0, y0 := d.at(a, 1/head, reach)
+ x1, y1 := d.at(a, 1/tail, reach)
+ d.streak(x0, y0, x1, y1, wormholeHot, wormholeBeat)
+ }
+ }
+ return d.grid.render(rows, cols)
+}
+
+// streak draws a line whose first third is tier head and the rest tier tail.
+// Capped, so a wild projection stays cheap.
+func (d *wormholeDriver) streak(x0, y0, x1, y1 float64, head, tail int8) {
+ span := max(math.Abs(x1-x0), math.Abs(y1-y0))
+ if math.IsNaN(span) || math.IsInf(span, 0) {
+ return
+ }
+ steps := min(wormholeMaxSteps, int(span)+1)
+ for i := range steps + 1 {
+ t := float64(i) / float64(steps)
+ tier := tail
+ if 3*i < steps {
+ tier = head
+ }
+ d.grid.set(int(x0+(x1-x0)*t), int(y0+(y1-y0)*t), tier)
+ }
+}
+
+// drawRing draws the fraction shown of the ring at depth z. In hyperspace
+// every few dots smear back towards the mouth.
+func (d *wormholeDriver) drawRing(z, shown float64, tier int8) {
+ swell := d.swell(z)
+ points := int(2*math.Pi*max(d.frame.rx, d.frame.ry)*(1+swell)*(1+wormholeSpectral)/z) + 8
+ smear := 1 / max(wormholeInner, 1/z-wormholeWarpSmear*d.warp)
+ for p := range points {
+ // The 7 spreads the dots that show around the ring.
+ if float64(p*7%points) >= shown*float64(points) {
+ continue
+ }
+ a := 2*math.Pi*float64(p)/float64(points) + d.twist + d.rock
+ x, y := d.at(a, z, 1+swell)
+ if d.warp <= wormholeWarpShown || p%max(1, points/16) != 0 {
+ d.grid.set(int(x), int(y), tier)
+ continue
+ }
+ x1, y1 := d.at(a, smear, 1+swell)
+ d.streak(x, y, x1, y1, tier, tier)
+ }
+}
diff --git a/ui/vis_wormhole_test.go b/ui/vis_wormhole_test.go
new file mode 100644
index 000000000..fe8db519e
--- /dev/null
+++ b/ui/vis_wormhole_test.go
@@ -0,0 +1,574 @@
+package ui
+
+import (
+ "fmt"
+ "image/color"
+ "math"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "charm.land/lipgloss/v2"
+
+ "github.com/bjarneo/cliamp/theme"
+)
+
+var wormholePlaying = VisTickContext{Playing: true}
+
+func newWormholeTest(cols, rows int) (*wormholeDriver, *Visualizer) {
+ v := NewVisualizer(44100)
+ v.Cols, v.Rows = cols, rows
+ return newWormholeDriver().(*wormholeDriver), v
+}
+
+// wormholeTick sets raw and smoothed bands and ticks n times.
+func wormholeTick(d *wormholeDriver, v *Visualizer, ctx VisTickContext, ticks int, bands []float64) {
+ copy(v.bands, bands)
+ v.smoothedBands = append(v.smoothedBands[:0], bands...)
+ for range ticks {
+ d.Tick(v, ctx)
+ }
+}
+
+// wormholeMix: bands 0-2 bass, 3-5 mids, rest treble.
+func wormholeMix(bass, mids, treble float64) []float64 {
+ bands := uniformBands(treble)
+ for i := range 6 {
+ bands[i] = mids
+ if i < 3 {
+ bands[i] = bass
+ }
+ }
+ return bands
+}
+
+func wormholeBands(bass, rest float64) []float64 { return wormholeMix(bass, rest, rest) }
+
+// wormholeKick is a loud bass on the kick and a quiet one between.
+func wormholeKick(_ float64, kick bool) []float64 {
+ if kick {
+ return wormholeBands(0.9, 0.3)
+ }
+ return wormholeBands(0.3, 0.3)
+}
+
+// wormholePlayTempo plays kicks at bpm for secs seconds, two loud ticks a beat.
+func wormholePlayTempo(d *wormholeDriver, v *Visualizer, bpm, secs float64) {
+ wormholePlay(d, v, bpm, secs, wormholeKick, nil)
+}
+
+// wormholePlay ticks for secs seconds. bands gives the levels of the tick at
+// sec and is told whether a kick at bpm falls on it; after runs after each tick.
+func wormholePlay(d *wormholeDriver, v *Visualizer, bpm, secs float64, bands func(sec float64, kick bool) []float64, after func(sec float64)) {
+ period, dt := 60/bpm, TickRawSample.Seconds()
+ for tick := range int(secs/dt + 1e-9) {
+ sec := float64(tick) * dt
+ wormholeTick(d, v, wormholePlaying, 1, bands(sec, math.Mod(sec, period) < 2*dt-1e-9))
+ if after != nil {
+ after(sec)
+ }
+ }
+}
+
+// wormholePlayBeat plays one beat at 240 BPM.
+func wormholePlayBeat(d *wormholeDriver, v *Visualizer) {
+ wormholePlayTempo(d, v, 240, 0.25)
+}
+
+// wormholeShare: distance of dot i from the centre, normalised to the panel.
+func wormholeShare(d *wormholeDriver, i int) float64 {
+ w, h := float64(d.grid.dotCols), float64(d.grid.dotRows)
+ ex := (float64(i%d.grid.dotCols) + 0.5 - w/2) / (w / 2)
+ ey := (float64(i/d.grid.dotCols) + 0.5 - h/2) / (h / 2)
+ return math.Hypot(ex, ey)
+}
+
+func wormholeWaving(d *wormholeDriver) bool {
+ return slices.Contains(d.grid.cells, wormholeBeat) || slices.Contains(d.grid.cells, wormholeHot)
+}
+
+func TestWormholeFitsPanel(t *testing.T) {
+ for _, size := range []struct{ cols, rows int }{{1, 1}, {4, 5}, {13, 3}, {76, 7}, {140, 40}} {
+ t.Run(fmt.Sprintf("%dx%d", size.cols, size.rows), func(t *testing.T) {
+ v := NewVisualizer(44100)
+ v.Cols, v.Rows, v.Mode = size.cols, size.rows, VisWormhole
+ for range 20 {
+ v.Tick(wormholePlaying)
+ }
+ out := v.Render()
+ lines := strings.Split(out, "\n")
+ if len(lines) != size.rows {
+ t.Fatalf("got %d rows, want %d", len(lines), size.rows)
+ }
+ for _, line := range lines {
+ if got := lipgloss.Width(line); got != size.cols {
+ t.Fatalf("got width %d, want %d", got, size.cols)
+ }
+ }
+ for _, r := range stripSGR(out) {
+ if r != '\n' && (r < '⠀' || r > '⣿') {
+ t.Fatalf("non-Braille glyph %q", r)
+ }
+ }
+ })
+ }
+}
+
+// After 1/10 lap every ring has moved into its neighbour's place.
+func TestWormholeRings(t *testing.T) {
+ d, v := newWormholeTest(140, 40)
+ d.travel = 2.03
+ first := d.Render(v)
+ d.travel = 2.08
+ if d.Render(v) == first {
+ t.Fatal("the rings did not move")
+ }
+ d.travel = 2.13
+ if d.Render(v) != first {
+ t.Fatal("the rings did not move on by one place in a tenth of a lap")
+ }
+}
+
+func TestWormholeMouth(t *testing.T) {
+ for _, size := range []struct{ cols, rows int }{{76, 7}, {110, 15}, {180, 40}} {
+ t.Run(fmt.Sprintf("%dx%d", size.cols, size.rows), func(t *testing.T) {
+ d, v := newWormholeTest(size.cols, size.rows)
+ d.travel = 2.53
+ d.Render(v)
+ var mouth, rim int
+ for i, tier := range d.grid.cells {
+ if tier == 0 {
+ continue
+ }
+ if r := wormholeShare(d, i); r < 0.6*wormholeMouth {
+ mouth++
+ } else if r > 0.9 {
+ rim++
+ }
+ }
+ if mouth != 0 || rim == 0 {
+ t.Fatalf("%d dots in the mouth and %d at the edge, want a dark mouth and a wall to the edge", mouth, rim)
+ }
+ })
+ }
+}
+
+func TestWormholeKick(t *testing.T) {
+ d, v := newWormholeTest(110, 15)
+ wormholeTick(d, v, wormholePlaying, 400, uniformBands(0.3))
+ last := func() wormholeWave { return d.waves[(d.nextWave+wormholeWaves-1)%wormholeWaves] }
+ // Kicks as strong as the ones before them glow, but not hot.
+ for range 8 {
+ wormholeTick(d, v, wormholePlaying, 2, wormholeBands(0.6, 0.3))
+ if s := last().strength; s == 0 || s >= wormholeWaveHot {
+ t.Fatalf("an ordinary kick sent a wave of strength %.2f, want above 0 and below %.2f", s, wormholeWaveHot)
+ }
+ d.Render(v)
+ if !wormholeWaving(d) || slices.Contains(d.grid.cells, wormholeHot) {
+ t.Fatal("the wave of an ordinary kick does not glow, or glows hot")
+ }
+ wormholeTick(d, v, wormholePlaying, 18, uniformBands(0.3))
+ }
+ // A kick that stands out glows hot.
+ wormholeTick(d, v, wormholePlaying, 2, wormholeBands(1, 0.3))
+ wave := last()
+ if wave.strength < wormholeWaveHot {
+ t.Fatalf("a hard hit sent a wave of strength %.2f, want at least %.2f", wave.strength, wormholeWaveHot)
+ }
+ d.Render(v)
+ if !slices.Contains(d.grid.cells, wormholeHot) {
+ t.Fatal("the wave of a hard hit does not glow hot")
+ }
+ if front, ok := wave.front(d.clock); !ok || front > wormholeInner+1 {
+ t.Fatalf("the front sits at inverse depth %.2f right after the beat, want it at the mouth", front)
+ }
+ wormholeTick(d, v, wormholePlaying, int(wormholeWaveTime/TickRawSample.Seconds())+2, uniformBands(0.3))
+ d.Render(v)
+ if wormholeWaving(d) {
+ t.Fatal("the wave is still there after it reached the edge")
+ }
+}
+
+func TestWormholeDrums(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ bands []float64
+ wave, rock, sparks bool
+ }{
+ {"steady", wormholeMix(0.3, 0.3, 0.3), false, false, false},
+ {"bass", wormholeMix(0.9, 0.3, 0.3), true, false, false},
+ {"snare", wormholeMix(0.3, 0.9, 0.3), false, true, false},
+ {"hi-hat", wormholeMix(0.3, 0.3, 0.9), false, false, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ d, v := newWormholeTest(110, 15)
+ wormholeTick(d, v, wormholePlaying, 400, wormholeMix(0.3, 0.3, 0.3))
+ wormholeTick(d, v, wormholePlaying, 2, tc.bands)
+ wormholeTick(d, v, wormholePlaying, 4, wormholeMix(0.3, 0.3, 0.3))
+ wave := slices.ContainsFunc(d.waves[:], func(w wormholeWave) bool { return w.strength > 0 })
+ if wave != tc.wave || (d.rockTo != 0) != tc.rock || (d.struck > 0) != tc.sparks {
+ t.Fatalf("wave %v, rock %v, sparks %v; want %v, %v, %v", wave, d.rockTo != 0, d.struck > 0, tc.wave, tc.rock, tc.sparks)
+ }
+ })
+ }
+}
+
+// Without a beat there is no tempo: a steady level, however loud, stays at
+// cruise. Silence stops the tunnel.
+func TestWormholeCruise(t *testing.T) {
+ for _, tc := range []struct{ level, want float64 }{{0, 0}, {0.5, wormholeCruise}, {0.9, wormholeCruise}} {
+ d, v := newWormholeTest(76, 7)
+ wormholeTick(d, v, wormholePlaying, 600, uniformBands(tc.level))
+ if math.Abs(d.speed-tc.want) > 0.01 || d.sure != 0 {
+ t.Fatalf("level %.1f: speed %.3f, tempo sure %.2f, want speed %.3f", tc.level, d.speed, d.sure, tc.want)
+ }
+ if still := d.twist == 0 && d.bendPhase == 0; still != (tc.level == 0) {
+ t.Fatalf("level %.1f: twist %.3f, bend phase %.3f, want them to move only with sound", tc.level, d.twist, d.bendPhase)
+ }
+ }
+}
+
+// Sparks start at the top of the wall, where the rings show the treble.
+func TestWormholeSparks(t *testing.T) {
+ d, v := newWormholeTest(110, 15)
+ wormholeTick(d, v, wormholePlaying, 400, wormholeMix(0.3, 0.3, 0.3))
+ wormholeTick(d, v, wormholePlaying, 2, wormholeMix(0.3, 0.3, 0.9))
+ d.Render(v)
+ sparks := 0
+ for i, tier := range d.grid.cells {
+ if tier != wormholeBeat {
+ continue
+ }
+ sparks++
+ if row := i / d.grid.dotCols; row >= d.grid.dotRows/2 {
+ t.Fatalf("a spark dot in row %d of %d, want the sparks in the upper half", row, d.grid.dotRows)
+ }
+ }
+ if sparks == 0 {
+ t.Fatal("a hi-hat struck no sparks")
+ }
+}
+
+func TestWormholeTempo(t *testing.T) {
+ for _, tc := range []struct{ bpm, want float64 }{
+ {70, 70}, {120, 120}, {170, 170},
+ {240, 120}, // folded down
+ {50, 100}, // folded up
+ } {
+ t.Run(fmt.Sprint(tc.bpm), func(t *testing.T) {
+ d, v := newWormholeTest(76, 7)
+ wormholePlayTempo(d, v, tc.bpm, 8)
+ if want := 60 / tc.want; math.Abs(d.beat-want) > TickRawSample.Seconds()+1e-9 || d.sure != 1 {
+ t.Fatalf("beat %.3f s (sure %.2f), want %.3f s", d.beat, d.sure, want)
+ }
+ })
+ }
+}
+
+func TestWormholeSpeed(t *testing.T) {
+ speedAt := func(bpm float64) float64 {
+ d, v := newWormholeTest(76, 7)
+ wormholePlayTempo(d, v, bpm, 8)
+ return d.speed
+ }
+ slow, mid, fast := speedAt(70), speedAt(120), speedAt(170)
+ if !(slow < mid && mid < fast) || fast < 2*slow || fast > wormholeTopSpeed {
+ t.Fatalf("speed %.3f at 70 BPM, %.3f at 120, %.3f at 170; want it to rise with the tempo, 170 at least twice 70", slow, mid, fast)
+ }
+ // One ring per beat, give or take the phase lock.
+ if want := 2.0 / wormholeRings; math.Abs(mid-want) > wormholeLockMax*want {
+ t.Fatalf("speed %.3f at 120 BPM, want about one ring per beat (%.3f)", mid, want)
+ }
+}
+
+func TestWormholeTempoFades(t *testing.T) {
+ d, v := newWormholeTest(76, 7)
+ wormholePlayTempo(d, v, 170, 8)
+ spiral := d.spiral
+ if spiral <= 0 {
+ t.Fatal("a steady beat did not twist the wall into a spiral")
+ }
+ for d.clock-d.lastKick+TickRawSample.Seconds() < wormholeSureWait {
+ wormholeTick(d, v, wormholePlaying, 1, uniformBands(0.3))
+ if d.sure != 1 {
+ t.Fatalf("the tempo faded to %.2f %.2f s after the last kick", d.sure, d.clock-d.lastKick)
+ }
+ }
+ wormholeTick(d, v, wormholePlaying, 400, uniformBands(0.3))
+ if d.sure != 0 || math.Abs(d.speed-wormholeCruise) > 0.01 || d.spiral > 0.1*spiral {
+ t.Fatalf("10 s after the kicks stopped: sure %.2f, speed %.3f, spiral %.3f; want 0, cruise and straight", d.sure, d.speed, d.spiral)
+ }
+}
+
+func TestWormholeSpectralRings(t *testing.T) {
+ d, _ := newWormholeTest(76, 7)
+ bass, treble := [DefaultSpectrumBands]float64{1, 1, 1}, [DefaultSpectrumBands]float64{}
+ for i := 6; i < DefaultSpectrumBands; i++ {
+ treble[i] = 1
+ }
+ const bottom, top = 1.0, -1.0
+ depth := func(ring int) float64 { return 1 - d.travel + float64(ring)/wormholeRings }
+
+ d.travel, d.glow = 2, bass
+ d.keepShapes()
+ old := d.born
+ if b, tp := d.spectrum(bottom, depth(old)), d.spectrum(top, depth(old)); b < 0.99 || tp > 0.01 {
+ t.Fatalf("a ring born on the bass bulges %.2f at the bottom and %.2f at the top, want 1 and 0", b, tp)
+ }
+ d.travel, d.glow = 2.3, treble
+ d.keepShapes()
+ if d.born-old != 3 {
+ t.Fatalf("%d rings born in 0.3 laps, want 3", d.born-old)
+ }
+ if b, tp := d.spectrum(bottom, depth(old)), d.spectrum(top, depth(old)); b < 0.99 || tp > 0.01 {
+ t.Fatalf("the bass ring changed shape on its way out: %.2f at the bottom, %.2f at the top", b, tp)
+ }
+ if b, tp := d.spectrum(bottom, depth(d.born)), d.spectrum(top, depth(d.born)); b > 0.01 || tp < 0.99 {
+ t.Fatalf("a ring born on the treble bulges %.2f at the bottom and %.2f at the top, want 0 and 1", b, tp)
+ }
+ // Rings behind the viewer have no shape left.
+ if got := d.ringLevel(d.born-wormholeShapes, 0); got != 0 {
+ t.Fatalf("a ring long gone bulges %.2f", got)
+ }
+}
+
+func TestWormholeOutlines(t *testing.T) {
+ // form runs 0..4 through the shapes, as Render splits it.
+ outline := func(form, a float64) float64 {
+ form = wormholeWrap(form, wormholeForms)
+ return wormholeBlend(int(form), form-math.Floor(form), a)
+ }
+ for _, tc := range []struct {
+ name string
+ form float64
+ corner, in float64 // angle of a corner, and of the narrowest point
+ narrow float64
+ }{
+ {"circle", 0, 0, math.Pi / 7, 1},
+ {"hexagon", 1, 0, math.Pi / 6, math.Cos(math.Pi / 6)},
+ {"square", 2, 0, math.Pi / 4, math.Cos(math.Pi / 4)},
+ {"star", 3, 0, math.Pi / 5, 1 / (1 + 2*wormholeStarDepth)},
+ {"circle again", 4, 0, math.Pi / 7, 1},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := outline(tc.form, tc.corner); math.Abs(got-1) > 1e-9 {
+ t.Fatalf("corner at %.3f, want 1", got)
+ }
+ if got := outline(tc.form, tc.in); math.Abs(got-tc.narrow) > 1e-9 {
+ t.Fatalf("narrowest at %.3f, want %.3f", got, tc.narrow)
+ }
+ })
+ }
+ for form := -2.0; form < 6; form += 0.37 {
+ for a := -10.0; a < 10; a += 0.41 {
+ if r := outline(form, a); r > 1+1e-9 || r < 0.5 {
+ t.Fatalf("form %.2f at angle %.2f has radius %.3f, want 0.5..1", form, a, r)
+ }
+ }
+ }
+}
+
+func TestWormholeDrop(t *testing.T) {
+ quiet, loud := uniformBands(0.08), uniformBands(0.5)
+ for _, tc := range []struct {
+ name string
+ from []float64
+ warp bool
+ }{
+ {"a steady loud song", loud, false},
+ {"a drop", quiet, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ d, v := newWormholeTest(110, 15)
+ wormholeTick(d, v, wormholePlaying, 400, tc.from)
+ peak := 0.0
+ for range int(wormholeWarpLife / TickRawSample.Seconds()) {
+ wormholeTick(d, v, wormholePlaying, 1, loud)
+ peak = max(peak, d.warp)
+ }
+ if tc.warp != (peak > 0.9) || tc.warp != (d.jump == 1) {
+ t.Fatalf("warp peaked at %.2f with %v shape jumps, want warp %v", peak, d.jump, tc.warp)
+ }
+ wormholeTick(d, v, wormholePlaying, 4, loud)
+ if d.warp != 0 || d.speed > wormholeTopSpeed {
+ t.Fatalf("warp %.2f and speed %.3f after the warp, want 0 and at most top speed", d.warp, d.speed)
+ }
+ })
+ }
+ // A second drop right after the first does not warp again.
+ d, v := newWormholeTest(110, 15)
+ wormholeTick(d, v, wormholePlaying, int(wormholeDropWarm/TickRawSample.Seconds()), quiet)
+ for range 2 {
+ wormholeTick(d, v, wormholePlaying, 40, quiet)
+ wormholeTick(d, v, wormholePlaying, 40, loud)
+ }
+ if d.jump != 1 {
+ t.Fatalf("two drops 2 s apart made %v warps, want 1", d.jump)
+ }
+}
+
+// A track that rises out of silence is no drop, the first time or after a gap.
+func TestWormholeTrackStart(t *testing.T) {
+ d, v := newWormholeTest(110, 15)
+ dt := TickRawSample.Seconds()
+ for range 2 {
+ wormholeTick(d, v, wormholePlaying, 40, uniformBands(0))
+ wormholePlay(d, v, 128, 8, func(sec float64, kick bool) []float64 {
+ rise := min(1, sec/0.3) // the smoothed bands rise out of silence
+ if kick {
+ return wormholeBands(0.9*rise, 0.3*rise)
+ }
+ return wormholeBands(0.3*rise, 0.3*rise)
+ }, nil)
+ }
+ if d.jump != 0 {
+ t.Fatalf("starting a track warped %v times, want none", d.jump)
+ }
+ // Before the averages know the song, even a real jump does not warp.
+ d, v = newWormholeTest(110, 15)
+ wormholeTick(d, v, wormholePlaying, int(wormholeDropWarm/2/dt), uniformBands(0.08))
+ wormholeTick(d, v, wormholePlaying, 40, uniformBands(0.5))
+ if d.jump != 0 {
+ t.Fatal("a jump in the first seconds of a track warped")
+ }
+}
+
+func TestWormholePause(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ ctx VisTickContext
+ atOnce bool
+ }{
+ {"a pause eases to rest", VisTickContext{Paused: true}, false},
+ {"a stop halts at once", VisTickContext{}, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ d, v := newWormholeTest(76, 7)
+ for range 3 {
+ wormholePlayBeat(d, v)
+ }
+ if d.pauseSettled() {
+ t.Fatal("a moving tunnel reported rest")
+ }
+ before, clock, phase, twist := d.speed, d.clock, d.bendPhase, d.twist
+ wormholeTick(d, v, tc.ctx, 1, wormholeBands(0.9, 0.5))
+ if tc.atOnce != (d.speed == 0) || d.speed >= before {
+ t.Fatalf("speed %.3f after one tick, from %.3f", d.speed, before)
+ }
+ wormholeTick(d, v, tc.ctx, 60, wormholeBands(0.9, 0.5))
+ if !d.pauseSettled() || d.clock != clock || d.bendPhase != phase || d.twist != twist {
+ t.Fatal("the tunnel did not come to rest, or its clock, bend or twist ran on")
+ }
+ travel, frame := d.travel, d.Render(v)
+ wormholeTick(d, v, tc.ctx, 5, wormholeBands(0.9, 0.5))
+ if d.travel != travel || d.Render(v) != frame {
+ t.Fatal("the tunnel moved at rest")
+ }
+ })
+ }
+}
+
+// Suspend() sends an overlay tick (also while paused); it must not stop the flight.
+func TestWormholeOverlay(t *testing.T) {
+ d, v := newWormholeTest(76, 7)
+ now := time.Unix(1700000000, 0)
+ ctx := wormholePlaying
+ ctx.Now = now
+ wormholeTick(d, v, ctx, 1, uniformBands(0.5))
+ speed, travel := d.speed, d.travel
+ d.Tick(v, VisTickContext{OverlayActive: true})
+ if d.speed != speed || d.travel != travel || !d.lastTick.IsZero() {
+ t.Fatal("an overlay tick changed the flight or kept the clock")
+ }
+ ctx.Now = now.Add(time.Hour)
+ wormholeTick(d, v, ctx, 1, uniformBands(0.5))
+ if flown := d.travel - travel; flown <= 0 || flown > wormholeTopSpeed*TickFast.Seconds() {
+ t.Fatalf("flew %.4f laps after the overlay, want one frame", flown)
+ }
+}
+
+func TestWormholeTheme(t *testing.T) {
+ t.Cleanup(func() { ApplyThemeColors(theme.Default()) })
+ d, v := newWormholeTest(76, 7)
+ d.travel = 2.53
+ d.clock = wormholeWaveTime / 3
+ d.waves[0] = wormholeWave{at: 0, strength: 1}
+ d.waves[1] = wormholeWave{at: d.clock / 2, strength: 0.6}
+ ApplyThemeColors(theme.Default())
+ terminalFrame := d.Render(v)
+ for _, th := range []theme.Theme{theme.Default(), testTheme, theme.Default()} {
+ t.Run(th.Name, func(t *testing.T) {
+ ApplyThemeColors(th)
+ p := PaletteFor(th)
+ for i, c := range [...]color.Color{p.Dim, p.Text, p.SpectrumMid, p.SpectrumHigh} {
+ var sb, run strings.Builder
+ run.WriteString("⠂")
+ flushWormholeRun(&sb, &run, i+1)
+ want := lipgloss.NewStyle().Foreground(c).Render("⠂")
+ if got := sb.String(); got != want {
+ t.Errorf("style [%d] = %q, want %q", i, got, want)
+ }
+ }
+ frame := d.Render(v)
+ if stripSGR(frame) != stripSGR(terminalFrame) {
+ t.Fatal("changing the theme changed the tunnel")
+ }
+ if th.IsDefault() {
+ if frame != terminalFrame {
+ t.Fatal("returning to the default theme did not restore terminal colors")
+ }
+ if strings.Contains(frame, "38;2;") {
+ t.Fatal("the default theme did not use the terminal's ANSI palette")
+ }
+ } else if frame == terminalFrame {
+ t.Fatal("changing the theme did not recolor the tunnel")
+ }
+ if strings.Contains(frame, "48;2;") || strings.Contains(frame, "48;5;") {
+ t.Fatal("the visualizer painted a background")
+ }
+ })
+ }
+}
+
+// Turning the bass up raises its floor between the kicks; the kicks must
+// still count, or the waves and the tempo vanish until the range catches up.
+func TestWormholeBassBoost(t *testing.T) {
+ d, v := newWormholeTest(110, 15)
+ kicks, last := 0, d.lastKick
+ wormholePlay(d, v, 128, 16, func(sec float64, kick bool) []float64 {
+ bass := 0.5
+ if sec > 8 {
+ bass = 1.4
+ }
+ if kick {
+ return wormholeBands(bass, 0.3)
+ }
+ return wormholeBands(0.6*bass, 0.3)
+ }, func(sec float64) {
+ if sec > 8 && d.lastKick != last {
+ kicks++
+ }
+ last = d.lastKick
+ if sec > 4 && d.sure < 1 {
+ t.Fatalf("the tempo faded to %.2f at %.1f s", d.sure, sec)
+ }
+ })
+ if want := 8 * 128 / 60; kicks < want-1 {
+ t.Fatalf("%d kicks counted in the 8 s after the boost, want %d", kicks, want)
+ }
+}
+
+func BenchmarkWormholeFrame(b *testing.B) {
+ for _, size := range []struct{ cols, rows int }{{76, 7}, {140, 40}} {
+ b.Run(fmt.Sprintf("%dx%d", size.cols, size.rows), func(b *testing.B) {
+ d, v := newWormholeTest(size.cols, size.rows)
+ d.Render(v)
+ b.ReportAllocs()
+ for b.Loop() {
+ d.Tick(v, wormholePlaying)
+ d.Render(v)
+ }
+ })
+ }
+}
diff --git a/ui/visualizer_driver_test.go b/ui/visualizer_driver_test.go
index 2ca5a4cd6..1957d7291 100644
--- a/ui/visualizer_driver_test.go
+++ b/ui/visualizer_driver_test.go
@@ -623,6 +623,7 @@ func TestModesDeclareTapAndCadence(t *testing.T) {
VisWave: true,
VisScope: true,
VisHeartbeat: true,
+ VisWormhole: true,
}
for mode := range VisCount {
t.Run(visModes[mode].name, func(t *testing.T) {
@@ -651,7 +652,7 @@ func TestModesDeclareTapAndCadence(t *testing.T) {
t.Errorf("Analyze tap = %v, want %v", tap, want)
}
}
- if got, want := v.DriverOwnsCadence(), mode == VisClassicPeak || mode == VisClassicLED; got != want {
+ if got, want := v.DriverOwnsCadence(), mode == VisClassicPeak || mode == VisClassicLED || mode == VisWormhole; got != want {
t.Errorf("DriverOwnsCadence() = %v, want %v", got, want)
}
})