diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..24d3960
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,42 @@
+
+
+
+
+
+Perlines
+
+
+
+
+
+ Open audio file
+ Microphone
+ Demo (silent, synthetic)
+
+ 1 Aurora disk
+ 2 Burning water
+ 3 Vector trails
+ Fullscreen (F)
+
+Perlines Drop an audio file anywhere, or use the microphone. Keys: 1 2 3 scenes, F fullscreen, H HUD.
+Nothing leaves your browser: audio is analysed locally.
+
+
+
+
+
+
diff --git a/web/src/analysis.js b/web/src/analysis.js
new file mode 100644
index 0000000..4b52e47
--- /dev/null
+++ b/web/src/analysis.js
@@ -0,0 +1,88 @@
+// Turns a frame of dB spectrum into the shared state every scene reads: log-spaced smoothed bands,
+// band levels, onset events, chroma, key and the tint colour derived from the key.
+import { dbToLinear, OnsetDetector, KeyEstimator } from './dsp.js';
+
+export const NB = 128; // log-spaced display bands
+export const HIST = 128; // history rows (spectrum texture height)
+
+function hslToRgb(h, s, l) {
+ const f = n => { const k = (n + h * 12) % 12, a = s * Math.min(l, 1 - l); return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)); };
+ return [f(0), f(8), f(4)];
+}
+
+export class Analysis {
+ constructor(sampleRate, binCount) {
+ this.sampleRate = sampleRate; this.binCount = binCount;
+ this.lin = new Float32Array(binCount);
+ this.onsets = new OnsetDetector({ maxBin: Math.min(binCount, Math.round(8000 / (sampleRate / 2 / binCount))) });
+ this.keyEst = new KeyEstimator(sampleRate, binCount);
+ this.bands = new Float32Array(NB);
+ this.row = new Uint8Array(NB); // newest row, as texture bytes
+ this.bass = 0; this.mid = 0; this.treble = 0; this.level = 0;
+ this.onset = { count: 0, strength: 0, time: -1 }; // count increments per onset; scenes diff it
+ this.flux = 0;
+ this.key = this.keyEst.key;
+ this.hue = 0.6; this.tint = hslToRgb(0.6, 0.7, 0.55);
+ this.time = 0; this.dt = 1 / 60;
+ // band -> bin edges, log spaced 40 Hz .. 16 kHz
+ const hz = sampleRate / 2 / binCount, lo = 40, hi = Math.min(16000, sampleRate / 2 - hz);
+ this.edges = Array.from({ length: NB + 1 }, (_, i) => Math.min(binCount - 1, Math.round(lo * Math.pow(hi / lo, i / NB) / hz)));
+ }
+
+ /** db: Float32Array in decibels (AnalyserNode.getFloatFrequencyData); t: seconds. */
+ update(db, t) {
+ const dt = Math.min(0.1, Math.max(1e-3, t - this.time || 1 / 60));
+ this.time = t; this.dt = dt;
+ const lin = dbToLinear(db, this.lin);
+
+ const o = this.onsets.push(lin, t);
+ this.flux = this.onsets.flux;
+ if (o) { this.onset.count++; this.onset.strength = o.strength; this.onset.time = t; }
+
+ // bands: peak of dB inside each band, mapped -90..-25 dB to 0..1, fast attack / slow release
+ let b = 0, m = 0, tr = 0, nb = 0, nm = 0, nt = 0;
+ for (let i = 0; i < NB; i++) {
+ const a = this.edges[i], z = Math.max(a + 1, this.edges[i + 1]);
+ let pk = -160;
+ for (let k = a; k < z; k++) if (db[k] > pk) pk = db[k];
+ const v = Math.max(0, Math.min(1, (pk + 90) / 65));
+ const cur = this.bands[i];
+ this.bands[i] = v > cur ? cur + (v - cur) * 0.8 : cur + (v - cur) * (1 - Math.pow(0.02, dt));
+ this.row[i] = Math.round(this.bands[i] * 255);
+ if (i < NB * 0.2) { b += this.bands[i]; nb++; } else if (i < NB * 0.6) { m += this.bands[i]; nm++; } else { tr += this.bands[i]; nt++; }
+ }
+ this.bass = b / nb; this.mid = m / nm; this.treble = tr / nt;
+ this.level = (this.bass + this.mid + this.treble) / 3;
+
+ const key = this.keyEst.push(lin, dt);
+ this.key = key;
+ // tint: hue walks the circle of fifths so related keys sit near each other; confidence gates the move
+ const target = ((key.tonic * 7) % 12) / 12;
+ let d = target - this.hue; d -= Math.round(d);
+ this.hue = (this.hue + d * Math.min(1, dt * (0.15 + key.confidence * 0.8)) + 1) % 1;
+ const major = key.mode === 'major';
+ this.tint = hslToRgb(this.hue, major ? 0.8 : 0.6, major ? 0.58 : 0.5);
+ return this;
+ }
+}
+
+/** Synthetic spectrum for demo mode and benchmarks: a 120 bpm kick/hat pattern over an A-minor pad. */
+export class DemoFeed {
+ constructor(sampleRate, binCount) { this.sr = sampleRate; this.n = binCount; this.db = new Float32Array(binCount); }
+ frame(t) {
+ const { db, n, sr } = this, hz = sr / 2 / n, beat = 0.5;
+ const ph = t % beat, kick = Math.exp(-ph * 9), hat = Math.exp(-((t + beat / 2) % beat) * 40) * ((Math.floor(t / (beat / 2)) % 2) ? 1 : 0.4);
+ const snare = Math.floor(t / beat) % 2 ? Math.exp(-ph * 14) : 0;
+ const chord = [220, 261.63, 329.63, 440, 523.25, 659.25];
+ for (let k = 0; k < n; k++) {
+ const f = k * hz + 1;
+ let v = -105 + 12 * Math.sin(k * 12.9898 + t * 3) * 0.3;
+ v += 62 * kick * Math.exp(-Math.pow(Math.log2(f / 55), 2) * 1.5);
+ v += 52 * snare * Math.exp(-Math.pow(Math.log2(f / 1800), 2) * 0.35);
+ v += 45 * hat * Math.exp(-Math.pow(Math.log2(f / 9000), 2) * 0.5);
+ for (const c of chord) v += 55 * Math.exp(-Math.pow((f - c) / (hz * 0.8 + c * 0.01), 2));
+ db[k] = v;
+ }
+ return db;
+ }
+}
diff --git a/web/src/audio.js b/web/src/audio.js
new file mode 100644
index 0000000..aeaacc2
--- /dev/null
+++ b/web/src/audio.js
@@ -0,0 +1,50 @@
+// Audio inputs. All go through one AnalyserNode; the analysis code reads dB frames from it.
+// File playback uses an element (streams, no full decode); the mic is never routed to the speakers.
+
+export class AudioInput {
+ constructor() {
+ this.ctx = null; this.analyser = null; this.db = null; this.source = null; this.stream = null; this.mode = 'none';
+ this.el = null;
+ }
+ async ensure() {
+ if (!this.ctx) {
+ const AC = window.AudioContext || window.webkitAudioContext;
+ this.ctx = new AC({ latencyHint: 'interactive' });
+ this.analyser = this.ctx.createAnalyser();
+ this.analyser.fftSize = 2048;
+ this.analyser.smoothingTimeConstant = 0; // onset detection needs the raw frame, scenes smooth for themselves
+ this.analyser.minDecibels = -120; this.analyser.maxDecibels = 0;
+ this.db = new Float32Array(this.analyser.frequencyBinCount);
+ }
+ if (this.ctx.state !== 'running') await this.ctx.resume();
+ }
+ disconnect() {
+ if (this.source) { try { this.source.disconnect(); } catch {} this.source = null; }
+ if (this.stream) { this.stream.getTracks().forEach(t => t.stop()); this.stream = null; }
+ if (this.el) { this.el.pause(); }
+ }
+ async useFile(file, audioEl) {
+ await this.ensure(); this.disconnect();
+ this.el = audioEl;
+ if (this._url) URL.revokeObjectURL(this._url);
+ this._url = URL.createObjectURL(file);
+ audioEl.src = this._url;
+ if (!this._elSource) this._elSource = this.ctx.createMediaElementSource(audioEl);
+ this.source = this._elSource;
+ this.source.connect(this.analyser);
+ this.analyser.connect(this.ctx.destination);
+ await audioEl.play().catch(() => {}); // a click already happened; if play is refused the controls are visible
+ this.mode = 'file';
+ }
+ async useMic() {
+ await this.ensure(); this.disconnect();
+ try { this.analyser.disconnect(this.ctx.destination); } catch {}
+ this.stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false } });
+ this.source = this.ctx.createMediaStreamSource(this.stream);
+ this.source.connect(this.analyser);
+ this.mode = 'mic';
+ }
+ stop() { this.disconnect(); this.mode = 'none'; }
+ get sampleRate() { return this.ctx ? this.ctx.sampleRate : 48000; }
+ frame() { this.analyser.getFloatFrequencyData(this.db); return this.db; }
+}
diff --git a/web/src/gl.js b/web/src/gl.js
new file mode 100644
index 0000000..9781ace
--- /dev/null
+++ b/web/src/gl.js
@@ -0,0 +1,119 @@
+// Small WebGL2 helpers: programs, a fullscreen triangle, a feedback (persistence) target, mat4.
+
+export function program(gl, vs, fs) {
+ const mk = (type, src) => {
+ const s = gl.createShader(type);
+ gl.shaderSource(s, src); gl.compileShader(s);
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s) + '\n' + src);
+ return s;
+ };
+ const p = gl.createProgram();
+ gl.attachShader(p, mk(gl.VERTEX_SHADER, vs)); gl.attachShader(p, mk(gl.FRAGMENT_SHADER, fs));
+ gl.linkProgram(p);
+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
+ const u = {}, n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS);
+ for (let i = 0; i < n; i++) { const a = gl.getActiveUniform(p, i), name = a.name.replace(/\[0\]$/, ''); u[name] = gl.getUniformLocation(p, a.name); }
+ return { p, u };
+}
+
+export const GLSL_HEAD = '#version 300 es\nprecision highp float;\n';
+
+// Hash-based gradient-free value noise + fbm, enough for shader-side flow; the CPU paths use real Perlin.
+export const GLSL_NOISE = `
+float hash31(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
+float vnoise(vec3 x){
+ vec3 i = floor(x), f = fract(x); f = f*f*(3.0-2.0*f);
+ return mix(mix(mix(hash31(i), hash31(i+vec3(1,0,0)), f.x), mix(hash31(i+vec3(0,1,0)), hash31(i+vec3(1,1,0)), f.x), f.y),
+ mix(mix(hash31(i+vec3(0,0,1)), hash31(i+vec3(1,0,1)), f.x), mix(hash31(i+vec3(0,1,1)), hash31(i+vec3(1,1,1)), f.x), f.y), f.z);
+}
+float fbm(vec3 p){ float a = 0.5, s = 0.0; for (int i = 0; i < 4; i++){ s += a * vnoise(p); p = p * 2.03 + 11.7; a *= 0.5; } return s; }
+`;
+
+export function fullscreen(gl) {
+ const vao = gl.createVertexArray(); gl.bindVertexArray(vao);
+ const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b);
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
+ gl.bindVertexArray(null);
+ return vao;
+}
+
+/**
+ * Persistence: scenes draw into one of two textures; each frame the previous texture is copied
+ * forward multiplied by a decay (trails), the scene adds on top, and the result is blitted to screen.
+ */
+export class Feedback {
+ constructor(gl) {
+ this.gl = gl; this.w = 0; this.h = 0; this.i = 0; this.tex = []; this.fbo = [];
+ this.tri = fullscreen(gl);
+ this.copy = program(gl, GLSL_HEAD + 'layout(location=0) in vec2 p; out vec2 uv; void main(){ uv = p*0.5+0.5; gl_Position = vec4(p,0,1); }',
+ GLSL_HEAD + 'uniform sampler2D t; uniform float decay; uniform vec2 px; in vec2 uv; out vec4 o; void main(){ vec3 c = texture(t, uv).rgb; vec3 g = texture(t, uv + px).rgb * 0.5 + texture(t, uv - px).rgb * 0.5; o = vec4(mix(c, g, 0.35) * decay, 1.0); }');
+ this.blit = program(gl, GLSL_HEAD + 'layout(location=0) in vec2 p; out vec2 uv; void main(){ uv = p*0.5+0.5; gl_Position = vec4(p,0,1); }',
+ GLSL_HEAD + 'uniform sampler2D t; in vec2 uv; out vec4 o; void main(){ vec3 c = texture(t, uv).rgb; c = 1.0 - exp(-c * 1.4); o = vec4(pow(c, vec3(0.9)), 1.0); }');
+ }
+ resize(w, h) {
+ const gl = this.gl;
+ if (w === this.w && h === this.h) return;
+ this.w = w; this.h = h;
+ for (let k = 0; k < 2; k++) {
+ if (this.tex[k]) { gl.deleteTexture(this.tex[k]); gl.deleteFramebuffer(this.fbo[k]); }
+ const t = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, t);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ const f = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, f);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, t, 0);
+ gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT);
+ this.tex[k] = t; this.fbo[k] = f;
+ }
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ }
+ /** Fade the previous frame into the next target and bind it; the scene then draws additively. */
+ begin(decay) {
+ const gl = this.gl, prev = this.i, next = 1 - this.i;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo[next]);
+ gl.viewport(0, 0, this.w, this.h);
+ gl.disable(gl.BLEND); gl.disable(gl.DEPTH_TEST);
+ gl.useProgram(this.copy.p);
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.tex[prev]);
+ gl.uniform1i(this.copy.u.t, 0); gl.uniform1f(this.copy.u.decay, decay); gl.uniform2f(this.copy.u.px, 0.6 / this.w, 0.6 / this.h);
+ gl.bindVertexArray(this.tri); gl.drawArrays(gl.TRIANGLES, 0, 3);
+ this.i = next;
+ gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE);
+ }
+ present() {
+ const gl = this.gl;
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.viewport(0, 0, this.w, this.h);
+ gl.disable(gl.BLEND); gl.disable(gl.DEPTH_TEST);
+ gl.useProgram(this.blit.p);
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.tex[this.i]);
+ gl.uniform1i(this.blit.u.t, 0);
+ gl.bindVertexArray(this.tri); gl.drawArrays(gl.TRIANGLES, 0, 3);
+ }
+ clear() {
+ const gl = this.gl;
+ for (const f of this.fbo) { gl.bindFramebuffer(gl.FRAMEBUFFER, f); gl.clearColor(0, 0, 0, 1); gl.clear(gl.COLOR_BUFFER_BIT); }
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ }
+}
+
+// column-major mat4
+export const mat4 = {
+ perspective(fovy, aspect, n, f) {
+ const t = 1 / Math.tan(fovy / 2), m = new Float32Array(16);
+ m[0] = t / aspect; m[5] = t; m[10] = (f + n) / (n - f); m[11] = -1; m[14] = 2 * f * n / (n - f);
+ return m;
+ },
+ mul(a, b) {
+ const o = new Float32Array(16);
+ for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) {
+ let s = 0; for (let k = 0; k < 4; k++) s += a[k * 4 + r] * b[c * 4 + k];
+ o[c * 4 + r] = s;
+ }
+ return o;
+ },
+ rotX(a) { const c = Math.cos(a), s = Math.sin(a); return new Float32Array([1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1]); },
+ rotY(a) { const c = Math.cos(a), s = Math.sin(a); return new Float32Array([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1]); },
+ translate(x, y, z) { return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]); },
+};
diff --git a/web/src/main.js b/web/src/main.js
new file mode 100644
index 0000000..7753351
--- /dev/null
+++ b/web/src/main.js
@@ -0,0 +1,156 @@
+import { AudioInput } from './audio.js';
+import { Analysis, DemoFeed, NB, HIST } from './analysis.js';
+import { Feedback } from './gl.js';
+import { AuroraDisk } from './scenes/aurora.js';
+import { BurningWater } from './scenes/water.js';
+import { VectorTrails } from './scenes/trails.js';
+
+const q = new URLSearchParams(location.search);
+const $ = id => document.getElementById(id);
+const canvas = $('c'), hudEl = $('hud'), msg = $('msg'), ui = $('ui');
+const gl = canvas.getContext('webgl2', { antialias: false, alpha: false, powerPreference: 'high-performance' });
+if (!gl) { msg.textContent = 'WebGL2 is not available in this browser.'; throw new Error('no webgl2'); }
+
+const bench = q.has('bench');
+const fixed = q.has('w') ? [+q.get('w'), +q.get('h') || 720] : null;
+const dpr = Math.min(window.devicePixelRatio || 1, +(q.get('dpr') || 1.5));
+
+// spectrum history: NB x HIST, one byte per texel, newest row written each frame
+const hist = { tex: gl.createTexture(), row: 0, newest: 0 };
+gl.bindTexture(gl.TEXTURE_2D, hist.tex);
+gl.texStorage2D(gl.TEXTURE_2D, 1, gl.R8, NB, HIST);
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
+gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
+
+const fb = new Feedback(gl);
+const scenes = [new AuroraDisk(gl), new BurningWater(gl), new VectorTrails(gl)];
+let sceneIdx = Math.min(2, Math.max(0, +(q.get('scene') || 0)));
+
+const audio = new AudioInput();
+let analysis = new Analysis(48000, 1024);
+let demo = null;
+const BINS = 1024;
+
+function setScene(i) {
+ sceneIdx = i; fb.clear();
+ document.querySelectorAll('[data-scene]').forEach(b => b.classList.toggle('on', +b.dataset.scene === i));
+}
+function startDemo() {
+ audio.stop(); demo = new DemoFeed(48000, BINS); analysis = new Analysis(48000, BINS); msg.classList.add('hide');
+}
+async function useFile(f) {
+ if (!f) return;
+ await audio.useFile(f, $('audio')); demo = null; analysis = new Analysis(audio.sampleRate, audio.analyser.frequencyBinCount); msg.classList.add('hide');
+}
+async function useMic() {
+ try { await audio.useMic(); } catch (e) { msg.classList.remove('hide'); msg.textContent = 'Microphone unavailable: ' + e.message; return; }
+ demo = null; analysis = new Analysis(audio.sampleRate, audio.analyser.frequencyBinCount); msg.classList.add('hide');
+}
+
+$('file').onchange = e => useFile(e.target.files[0]);
+$('mic').onclick = useMic;
+$('demo').onclick = startDemo;
+$('full').onclick = () => document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen();
+document.querySelectorAll('[data-scene]').forEach(b => b.onclick = () => setScene(+b.dataset.scene));
+addEventListener('keydown', e => {
+ if (e.key >= '1' && e.key <= '3') setScene(+e.key - 1);
+ else if (e.key === 'f' || e.key === 'F') $('full').click();
+ else if (e.key === 'h' || e.key === 'H') hudEl.style.display = hudEl.style.display === 'none' ? '' : 'none';
+});
+addEventListener('dragover', e => e.preventDefault());
+addEventListener('drop', e => { e.preventDefault(); useFile(e.dataTransfer.files[0]); });
+let idleT = 0;
+addEventListener('pointermove', () => { ui.classList.remove('idle'); idleT = performance.now(); });
+
+function resize() {
+ const w = fixed ? fixed[0] : Math.max(2, Math.floor(canvas.clientWidth * dpr));
+ const h = fixed ? fixed[1] : Math.max(2, Math.floor(canvas.clientHeight * dpr));
+ if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
+ fb.resize(w, h);
+}
+
+// ---- frame-time bookkeeping: rolling window for the HUD, full record for the bench
+const ring = new Float32Array(240); let ri = 0, rn = 0, last = 0, cpuMs = 0, gpuMs = 0;
+const timer = gl.getExtension('EXT_disjoint_timer_query_webgl2');
+let pendingQ = [];
+function pct(a, n, p) { const s = Array.from(a.subarray(0, n)).sort((x, y) => x - y); return s[Math.min(n - 1, Math.floor(p * n))] || 0; }
+
+const record = { scenes: [] };
+let benchScene = -1, benchStart = 0, benchDt = [], benchCpu = [], benchGpu = [];
+const BENCH_MS = +(q.get('ms') || 6000), WARM_MS = 1000;
+const sync = q.has('sync');
+
+function frame(now) {
+ const t0 = performance.now();
+ resize();
+ const t = now / 1000;
+ let db;
+ if (demo) db = demo.frame(t);
+ else if (audio.mode !== 'none') db = audio.frame();
+ else { db = new Float32Array(BINS).fill(-140); }
+ const A = analysis.update(db, t);
+ hist.row = (hist.row + 1) % HIST; hist.newest = (hist.row + 0.5) / HIST;
+ gl.bindTexture(gl.TEXTURE_2D, hist.tex);
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, hist.row, NB, 1, gl.RED, gl.UNSIGNED_BYTE, A.row);
+
+ const sc = scenes[sceneIdx];
+ let qy = null;
+ if (timer && bench) { qy = gl.createQuery(); gl.beginQuery(timer.TIME_ELAPSED_EXT, qy); }
+ fb.begin(sc.persistence);
+ sc.draw(gl, A, canvas.width, canvas.height, hist);
+ fb.present();
+ if (qy) { gl.endQuery(timer.TIME_ELAPSED_EXT); pendingQ.push(qy); }
+ if (sync) gl.finish();
+ cpuMs = performance.now() - t0;
+
+ const dt = last ? now - last : 16.7; last = now;
+ if (!document.hidden) { ring[ri] = dt; ri = (ri + 1) % ring.length; rn = Math.min(ring.length, rn + 1); }
+
+ // resolve finished GPU timer queries without stalling
+ while (pendingQ.length) {
+ const p = pendingQ[0];
+ if (!gl.getQueryParameter(p, gl.QUERY_RESULT_AVAILABLE)) break;
+ if (!gl.getParameter(timer.GPU_DISJOINT_EXT)) { gpuMs = gl.getQueryParameter(p, gl.QUERY_RESULT) / 1e6; if (bench && benchScene >= 0) benchGpu.push(gpuMs); }
+ gl.deleteQuery(p); pendingQ.shift();
+ }
+
+ if (bench) stepBench(now, dt, cpuMs);
+ if (now - idleT > 3000 && (demo || audio.mode !== 'none')) ui.classList.add('idle');
+
+ if ((ri & 7) === 0) {
+ const k = analysis.key;
+ hudEl.textContent =
+ `${sc.name} ${canvas.width}x${canvas.height}\n` +
+ `frame ${(rn ? pct(ring, rn, 0.5) : 0).toFixed(1)} ms p50 ${pct(ring, rn, 0.95).toFixed(1)} p95 (budget 16.7) cpu ${cpuMs.toFixed(2)} ms` +
+ (timer && gpuMs ? ` gpu ${gpuMs.toFixed(2)} ms` : '') + '\n' +
+ `key ${k.name}${k.mode === 'minor' ? '' : ''} (${(k.confidence * 100) | 0}%) onsets ${analysis.onset.count} flux ${analysis.flux.toFixed(2)} ` +
+ `source ${demo ? 'synthetic demo' : audio.mode}`;
+ }
+ requestAnimationFrame(frame);
+}
+
+function stepBench(now, dt, cpu) {
+ if (benchScene < 0) { benchScene = 0; benchStart = now; setScene(0); }
+ const el = now - benchStart;
+ if (el > WARM_MS) { benchDt.push(sync ? cpu : dt); benchCpu.push(cpu); }
+ if (el > BENCH_MS + WARM_MS) {
+ const stat = a => { const s = a.slice().sort((x, y) => x - y); return a.length ? { n: a.length, mean: a.reduce((x, y) => x + y, 0) / a.length, p50: s[s.length >> 1], p95: s[Math.floor(s.length * 0.95)], p99: s[Math.floor(s.length * 0.99)], max: s[s.length - 1] } : null; };
+ record.scenes.push({ scene: scenes[sceneIdx].name, frameMs: stat(benchDt), cpuMs: stat(benchCpu), gpuMs: stat(benchGpu), over16_7: benchDt.filter(x => x > 16.7 * 1.2).length });
+ benchDt = []; benchCpu = []; benchGpu = [];
+ if (sceneIdx < 2) { setScene(sceneIdx + 1); benchStart = now; }
+ else {
+ record.canvas = [canvas.width, canvas.height]; record.sync = sync; record.gpuTimer = !!timer; record.ua = navigator.userAgent;
+ record.renderer = (() => { const e = gl.getExtension('WEBGL_debug_renderer_info'); return e ? gl.getParameter(e.UNMASKED_RENDERER_WEBGL) : 'unknown'; })();
+ const out = JSON.stringify(record, null, 1);
+ $('bench').style.display = 'block'; $('bench').textContent = out;
+ console.log('PERLINES_BENCH ' + JSON.stringify(record));
+ benchScene = 99;
+ }
+ }
+}
+
+setScene(sceneIdx);
+if (bench || q.has('demo')) startDemo();
+requestAnimationFrame(frame);
+window.__perlines = { setScene, startDemo, analysis: () => analysis };
diff --git a/web/src/noise.js b/web/src/noise.js
new file mode 100644
index 0000000..71ba7c7
--- /dev/null
+++ b/web/src/noise.js
@@ -0,0 +1,43 @@
+// Perlin gradient noise (3D) and a divergence-free curl field in 2D, for the CPU-side trail paths.
+// Permutation table from a seeded LCG shuffle; gradients are the 12 cube-edge vectors.
+
+const G = [[1,1,0],[-1,1,0],[1,-1,0],[-1,-1,0],[1,0,1],[-1,0,1],[1,0,-1],[-1,0,-1],[0,1,1],[0,-1,1],[0,1,-1],[0,-1,-1]];
+
+export function makeNoise(seed = 1) {
+ const p = new Uint8Array(512), base = Array.from({ length: 256 }, (_, i) => i);
+ let s = seed >>> 0 || 1;
+ for (let i = 255; i > 0; i--) {
+ s = (s * 1664525 + 1013904223) >>> 0;
+ const j = s % (i + 1);
+ [base[i], base[j]] = [base[j], base[i]];
+ }
+ for (let i = 0; i < 512; i++) p[i] = base[i & 255];
+ const fade = t => t * t * t * (t * (t * 6 - 15) + 10);
+ const dot = (g, x, y, z) => g[0] * x + g[1] * y + g[2] * z;
+
+ /** Perlin noise in [-1, 1]-ish. */
+ function noise3(x, y, z) {
+ const X = Math.floor(x), Y = Math.floor(y), Z = Math.floor(z);
+ x -= X; y -= Y; z -= Z;
+ const xi = X & 255, yi = Y & 255, zi = Z & 255;
+ const u = fade(x), v = fade(y), w = fade(z);
+ const A = p[xi] + yi, AA = p[A] + zi, AB = p[A + 1] + zi;
+ const B = p[xi + 1] + yi, BA = p[B] + zi, BB = p[B + 1] + zi;
+ const l = (a, b, t) => a + t * (b - a);
+ return l(
+ l(l(dot(G[p[AA] % 12], x, y, z), dot(G[p[BA] % 12], x - 1, y, z), u),
+ l(dot(G[p[AB] % 12], x, y - 1, z), dot(G[p[BB] % 12], x - 1, y - 1, z), u), v),
+ l(l(dot(G[p[AA + 1] % 12], x, y, z - 1), dot(G[p[BA + 1] % 12], x - 1, y, z - 1), u),
+ l(dot(G[p[AB + 1] % 12], x, y - 1, z - 1), dot(G[p[BB + 1] % 12], x - 1, y - 1, z - 1), u), v), w);
+ }
+
+ /** Curl of a scalar noise potential: a divergence-free 2D velocity, written into out[0..1]. */
+ function curl2(x, y, t, out) {
+ const e = 0.01;
+ const dx = (noise3(x + e, y, t) - noise3(x - e, y, t)) / (2 * e);
+ const dy = (noise3(x, y + e, t) - noise3(x, y - e, t)) / (2 * e);
+ out[0] = dy; out[1] = -dx;
+ return out;
+ }
+ return { noise3, curl2 };
+}
diff --git a/web/src/scenes/aurora.js b/web/src/scenes/aurora.js
new file mode 100644
index 0000000..1ac2c55
--- /dev/null
+++ b/web/src/scenes/aurora.js
@@ -0,0 +1,76 @@
+// Aurora disk: the spectrum history extruded into a polar mesh.
+// Angle = frequency (mirrored, bass at the seam), radius = age (centre newest), height = band level.
+import { program, GLSL_HEAD, GLSL_NOISE, mat4 } from '../gl.js';
+
+const RINGS = 112, SEGS = 224;
+
+const VS = GLSL_HEAD + GLSL_NOISE + `
+layout(location=0) in vec2 pr; // x = ring 0..1, y = segment 0..1
+uniform sampler2D hist; uniform float newest, time, kick, spin; uniform mat4 mvp;
+out float h; out float ring; out float seg;
+void main(){
+ float ang = pr.y * 6.2831853;
+ float f = abs(pr.y * 2.0 - 1.0); // mirrored frequency coordinate
+ float age = pr.x * 0.92;
+ float row = fract(newest - age);
+ float v = texture(hist, vec2(f, row)).r;
+ float n = vnoise(vec3(cos(ang) * 1.6, sin(ang) * 1.6, pr.x * 3.0 - time * 0.35));
+ h = v * (0.55 + 0.9 * n) * (1.0 - 0.6 * pr.x);
+ float rad = 0.12 + pr.x * 1.45 * (1.0 + 0.05 * kick);
+ ang += spin;
+ vec3 p = vec3(cos(ang) * rad, h * 0.9 + 0.1 * sin(pr.x * 18.0 - time * 2.0) * v, sin(ang) * rad);
+ ring = pr.x; seg = pr.y;
+ gl_Position = mvp * vec4(p, 1.0);
+}`;
+
+const FS = GLSL_HEAD + `
+in float h; in float ring; in float seg;
+uniform vec3 tint; uniform float kick; uniform float time;
+out vec4 o;
+void main(){
+ // curtain gradient: tint at the base, shifting toward cyan/green-white at the crest, like auroral oxygen/nitrogen lines
+ vec3 base = tint;
+ vec3 crest = mix(tint.gbr, vec3(0.8, 1.0, 0.9), 0.55);
+ vec3 c = mix(base, crest, smoothstep(0.1, 0.9, h));
+ float lines = 0.55 + 0.45 * smoothstep(0.82, 1.0, abs(sin(seg * 256.0 * 3.14159)));
+ float fade = (1.0 - ring) * (1.0 - ring) * 0.9 + 0.05;
+ float a = (0.02 + h * h * 0.75) * lines * fade * (1.0 + 1.5 * kick);
+ o = vec4(c * a, 1.0);
+}`;
+
+export class AuroraDisk {
+ constructor(gl) {
+ this.name = 'Aurora disk'; this.persistence = 0.82;
+ this.prog = program(gl, VS, FS);
+ const pr = new Float32Array(RINGS * (SEGS + 1) * 2);
+ let k = 0;
+ for (let r = 0; r < RINGS; r++) for (let s = 0; s <= SEGS; s++) { pr[k++] = r / (RINGS - 1); pr[k++] = s / SEGS; }
+ const idx = new Uint32Array((RINGS - 1) * SEGS * 6); k = 0;
+ for (let r = 0; r < RINGS - 1; r++) for (let s = 0; s < SEGS; s++) {
+ const a = r * (SEGS + 1) + s, b = a + SEGS + 1;
+ idx.set([a, b, a + 1, a + 1, b, b + 1], k); k += 6;
+ }
+ this.count = idx.length;
+ this.vao = gl.createVertexArray(); gl.bindVertexArray(this.vao);
+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, pr, gl.STATIC_DRAW);
+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.STATIC_DRAW);
+ gl.bindVertexArray(null);
+ this.kick = 0; this.spin = 0; this.seen = 0;
+ }
+ draw(gl, A, w, h, hist) {
+ if (A.onset.count !== this.seen) { this.seen = A.onset.count; this.kick = Math.max(this.kick, 0.4 + 0.6 * A.onset.strength); }
+ this.kick *= Math.pow(0.0008, A.dt);
+ this.spin += A.dt * (0.05 + 0.4 * this.kick + 0.2 * A.bass);
+ const proj = mat4.perspective(0.9, w / h, 0.1, 20);
+ const view = mat4.mul(mat4.translate(0, -0.15, -2.6), mat4.mul(mat4.rotX(0.62 + 0.04 * Math.sin(A.time * 0.2)), mat4.rotY(0)));
+ const P = this.prog;
+ gl.useProgram(P.p);
+ gl.uniformMatrix4fv(P.u.mvp, false, mat4.mul(proj, view));
+ gl.uniform1f(P.u.newest, hist.newest); gl.uniform1f(P.u.time, A.time); gl.uniform1f(P.u.kick, this.kick); gl.uniform1f(P.u.spin, this.spin);
+ gl.uniform3fv(P.u.tint, A.tint);
+ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, hist.tex); gl.uniform1i(P.u.hist, 1);
+ gl.bindVertexArray(this.vao);
+ gl.drawElements(gl.TRIANGLES, this.count, gl.UNSIGNED_INT, 0);
+ }
+}
diff --git a/web/src/scenes/trails.js b/web/src/scenes/trails.js
new file mode 100644
index 0000000..cfa38f3
--- /dev/null
+++ b/web/src/scenes/trails.js
@@ -0,0 +1,90 @@
+// Vector trails: heads ride a divergence-free Perlin curl field, one head per spectrum lane;
+// onsets kick speed and respawn a spray of heads from the centre. Each head leaves a polyline trail.
+import { program, GLSL_HEAD } from '../gl.js';
+import { makeNoise } from '../noise.js';
+import { NB } from '../analysis.js';
+
+const HEADS = 96, LEN = 72;
+
+const VS = GLSL_HEAD + `
+layout(location=0) in vec2 a; // trail point; slot 0 is the head
+uniform float aspect; out float al; out float lane;
+void main(){
+ al = 1.0 - float(gl_VertexID % ${LEN}) / ${LEN - 1}.0;
+ lane = float(gl_VertexID / ${LEN}) / ${HEADS}.0;
+ gl_Position = vec4(a.x / aspect, a.y, 0.0, 1.0);
+}`;
+const FS = GLSL_HEAD + `
+in float al; in float lane; uniform vec3 tint; uniform float level; out vec4 o;
+void main(){
+ vec3 c = mix(tint, tint.brg * 0.8 + 0.2, lane);
+ c = mix(c, vec3(1.0), pow(al, 6.0) * 0.6);
+ o = vec4(c * pow(al, 1.6) * (0.35 + level), 1.0);
+}`;
+
+export class VectorTrails {
+ constructor(gl) {
+ this.name = 'Vector trails'; this.persistence = 0.9;
+ this.prog = program(gl, VS, FS);
+ this.noise = makeNoise(2013);
+ this.pos = new Float32Array(HEADS * 2); // head positions
+ this.vel = new Float32Array(HEADS * 2);
+ this.trail = new Float32Array(HEADS * LEN * 2); // x, y per point
+ this.energy = new Float32Array(HEADS);
+ this.life = new Float32Array(HEADS);
+ this.scratch = new Float32Array(2);
+ for (let i = 0; i < HEADS; i++) this.respawn(i, 0.2 + Math.random() * 1.0);
+ const idx = new Uint16Array(HEADS * (LEN - 1) * 2); let k = 0;
+ for (let h = 0; h < HEADS; h++) for (let s = 0; s < LEN - 1; s++) { idx[k++] = h * LEN + s; idx[k++] = h * LEN + s + 1; }
+ this.count = idx.length;
+ this.vao = gl.createVertexArray(); gl.bindVertexArray(this.vao);
+ this.buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.buf);
+ gl.bufferData(gl.ARRAY_BUFFER, this.trail, gl.DYNAMIC_DRAW);
+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.STATIC_DRAW);
+ gl.bindVertexArray(null);
+ this.seen = 0; this.kick = 0;
+ }
+ respawn(i, radius) {
+ const a = Math.random() * Math.PI * 2;
+ this.pos[i * 2] = Math.cos(a) * radius * 0.2; this.pos[i * 2 + 1] = Math.sin(a) * radius * 0.2;
+ this.vel[i * 2] = Math.cos(a) * radius; this.vel[i * 2 + 1] = Math.sin(a) * radius;
+ this.life[i] = 4 + Math.random() * 6;
+ const base = i * LEN * 2;
+ for (let s = 0; s < LEN; s++) { this.trail[base + s * 2] = this.pos[i * 2]; this.trail[base + s * 2 + 1] = this.pos[i * 2 + 1]; }
+ }
+ draw(gl, A, w, h) {
+ const dt = A.dt, t = A.time, n = this.noise, c = this.scratch;
+ if (A.onset.count !== this.seen) {
+ this.seen = A.onset.count; this.kick = Math.min(1.5, this.kick + 0.5 + A.onset.strength);
+ const spray = Math.round(8 + 24 * A.onset.strength);
+ for (let j = 0; j < spray; j++) this.respawn((Math.random() * HEADS) | 0, 1.2 + 2.2 * A.onset.strength);
+ }
+ this.kick *= Math.pow(0.02, dt);
+ for (let i = 0; i < HEADS; i++) {
+ const band = Math.min(NB - 1, Math.floor(Math.pow(i / HEADS, 1.3) * NB * 0.85));
+ const e = A.bands[band]; this.energy[i] += (e - this.energy[i]) * 0.3;
+ const x = this.pos[i * 2], y = this.pos[i * 2 + 1];
+ n.curl2(x * 0.9 + i * 0.13, y * 0.9, t * 0.18, c);
+ const speed = 0.25 + 1.2 * this.energy[i] + 1.4 * this.kick;
+ // steer velocity toward the flow; spray velocity decays toward it, so heads start as a burst and then drift
+ const k = 1 - Math.pow(0.15, dt);
+ this.vel[i * 2] += (c[0] * speed * 0.55 - this.vel[i * 2]) * k;
+ this.vel[i * 2 + 1] += (c[1] * speed * 0.55 - this.vel[i * 2 + 1]) * k;
+ let nx = x + this.vel[i * 2] * dt, ny = y + this.vel[i * 2 + 1] * dt;
+ this.life[i] -= dt;
+ if (this.life[i] <= 0 || Math.abs(nx) > 3 || Math.abs(ny) > 1.6) { this.respawn(i, 0.3 + this.energy[i]); continue; }
+ this.pos[i * 2] = nx; this.pos[i * 2 + 1] = ny;
+ const base = i * LEN * 2;
+ this.trail.copyWithin(base + 2, base, base + (LEN - 1) * 2);
+ this.trail[base] = nx; this.trail[base + 1] = ny;
+ }
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.buf);
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.trail);
+ const P = this.prog;
+ gl.useProgram(P.p);
+ gl.uniform1f(P.u.aspect, w / h); gl.uniform3fv(P.u.tint, A.tint); gl.uniform1f(P.u.level, A.level * 0.8 + this.kick * 0.3);
+ gl.bindVertexArray(this.vao);
+ gl.drawElements(gl.LINES, this.count, gl.UNSIGNED_SHORT, 0);
+ }
+}
diff --git a/web/src/scenes/water.js b/web/src/scenes/water.js
new file mode 100644
index 0000000..490fa49
--- /dev/null
+++ b/web/src/scenes/water.js
@@ -0,0 +1,120 @@
+// Burning water: a flame-lit ripple plane, with an onset-driven spray of embers lofted off the surface.
+// Particles are stateless: the CPU only writes (birth, seed, strength, lane) into a ring buffer on onsets;
+// the vertex shader computes every position from age, so the per-frame cost is one point draw.
+import { program, fullscreen, GLSL_HEAD, GLSL_NOISE } from '../gl.js';
+
+const MAX = 6144;
+
+const SURF_FS = GLSL_HEAD + GLSL_NOISE + `
+in vec2 uv; uniform vec2 res; uniform float time, bass, level; uniform vec3 tint;
+uniform vec4 ripples[8]; // x, y (surface coords), birth time, strength
+out vec4 o;
+void main(){
+ vec2 p = (uv * 2.0 - 1.0) * vec2(res.x / res.y, 1.0);
+ // horizon at y = 0.1, plane below it
+ float d = p.y - 0.1;
+ if (d > -0.01) { o = vec4(0.0, 0.0, 0.0, 1.0); return; }
+ float depth = 0.55 / -d; // distance along the plane
+ vec2 s = vec2(p.x * depth, depth); // surface coords
+ float hgt = fbm(vec3(s * 0.9, time * 0.25)) * 0.7;
+ vec2 g = vec2(0.0);
+ for (int i = 0; i < 8; i++) {
+ float age = time - ripples[i].z;
+ if (age < 0.0 || age > 3.0) continue;
+ float r = length(s - ripples[i].xy);
+ float front = age * 2.4;
+ float w = exp(-pow((r - front) * 2.2, 2.0)) * exp(-age * 1.1) * ripples[i].w;
+ hgt += w * sin((r - front) * 9.0) * 0.6;
+ }
+ float e = 0.04;
+ float hx = fbm(vec3((s + vec2(e, 0)) * 0.9, time * 0.25)) * 0.7;
+ float hy = fbm(vec3((s + vec2(0, e)) * 0.9, time * 0.25)) * 0.7;
+ vec3 n = normalize(vec3((hgt - hx) / e * 0.5, 1.0, (hgt - hy) / e * 0.5));
+ float flame = pow(max(0.0, n.x * 0.6 + n.z * 0.8 + 0.3) , 2.0) + hgt * 0.8;
+ vec3 hot = mix(vec3(1.0, 0.35, 0.05), vec3(1.0, 0.9, 0.5), smoothstep(0.5, 1.4, flame + level));
+ vec3 cold = tint * 0.6;
+ vec3 c = mix(cold, hot, smoothstep(0.2, 0.9, flame + bass)) * (0.25 + 0.75 * exp(-depth * 0.12));
+ c *= mix(0.35, 1.0, tint.b + 0.2) ;
+ o = vec4(c * (0.15 + 0.5 * level + 0.35 * bass) * 0.22, 1.0);
+}`;
+
+const PVS = GLSL_HEAD + `
+layout(location=0) in vec4 a; // birth, seed, strength, lane
+uniform float time; uniform vec2 res;
+out float life; out float heat;
+float h1(float x){ return fract(sin(x * 127.1) * 43758.5453); }
+void main(){
+ float age = time - a.x;
+ if (a.x < 0.0 || age < 0.0 || age > 2.6) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); gl_PointSize = 0.0; return; }
+ float s = a.y, str = a.z;
+ float vx = (h1(s) - 0.5) * 1.4 * (0.5 + str) + (a.w - 0.5) * 0.7;
+ float vy = (1.2 + 2.6 * h1(s + 3.0) * str + 0.8 * str);
+ float x = (a.w * 2.0 - 1.0) * 0.95 + vx * age + 0.08 * sin(age * 7.0 + s * 40.0);
+ float y = -0.1 + vy * age - 1.9 * age * age;
+ if (y < -0.1 && age > 0.1) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); gl_PointSize = 0.0; return; }
+ life = 1.0 - age / 2.6; heat = life * (0.4 + str);
+ gl_Position = vec4(x / (res.x / res.y), y, 0.0, 1.0);
+ gl_PointSize = (2.0 + 9.0 * h1(s + 7.0) * str) * (0.4 + life) * res.y / 900.0;
+}`;
+const PFS = GLSL_HEAD + `
+in float life; in float heat; uniform vec3 tint; out vec4 o;
+void main(){
+ vec2 q = gl_PointCoord * 2.0 - 1.0; float r = dot(q, q); if (r > 1.0) discard;
+ vec3 fire = mix(vec3(0.9, 0.12, 0.02), vec3(1.0, 0.85, 0.4), heat);
+ fire = mix(fire, tint * 1.3, 0.25 * (1.0 - heat));
+ o = vec4(fire * (1.0 - r) * life * 0.9, 1.0);
+}`;
+
+export class BurningWater {
+ constructor(gl) {
+ this.name = 'Burning water'; this.persistence = 0.78;
+ this.surf = program(gl, GLSL_HEAD + 'layout(location=0) in vec2 p; out vec2 uv; void main(){ uv = p*0.5+0.5; gl_Position = vec4(p,0,1); }', SURF_FS);
+ this.part = program(gl, PVS, PFS);
+ this.tri = fullscreen(gl);
+ this.data = new Float32Array(MAX * 4).fill(-1);
+ this.vao = gl.createVertexArray(); gl.bindVertexArray(this.vao);
+ this.buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.buf);
+ gl.bufferData(gl.ARRAY_BUFFER, this.data, gl.DYNAMIC_DRAW);
+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 4, gl.FLOAT, false, 0, 0);
+ gl.bindVertexArray(null);
+ this.head = 0; this.seen = 0; this.ripples = new Float32Array(32).fill(0); this.rhead = 0; this.dirty = [0, 0];
+ for (let i = 0; i < 8; i++) this.ripples[i * 4 + 2] = -10;
+ this.seed = 1; this.acc = 0;
+ }
+ spawn(n, t, strength) {
+ const d = this.data;
+ const first = this.head;
+ for (let i = 0; i < n; i++) {
+ const j = this.head; this.head = (this.head + 1) % MAX;
+ this.seed += 1.618;
+ d[j * 4] = t; d[j * 4 + 1] = this.seed; d[j * 4 + 2] = strength * (0.5 + 0.5 * Math.random()); d[j * 4 + 3] = Math.random();
+ }
+ return first;
+ }
+ draw(gl, A, w, h) {
+ const t = A.time;
+ if (A.onset.count !== this.seen) {
+ this.seen = A.onset.count;
+ const s = A.onset.strength;
+ this.spawn(Math.round(80 + 520 * s), t, 0.35 + 0.65 * s);
+ const r = this.rhead; this.rhead = (this.rhead + 1) % 8;
+ this.ripples.set([(Math.random() - 0.5) * 6, 1.5 + Math.random() * 4, t, 0.5 + s], r * 4);
+ }
+ // a thin continuous simmer follows the bass so quiet passages are not dead
+ this.acc += A.dt * A.bass * 90;
+ if (this.acc >= 1) { this.spawn(Math.floor(this.acc), t, 0.15 + 0.3 * A.level); this.acc %= 1; }
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.buf);
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.data); // 96 KB; simplest correct upload, measured in the frame-time HUD
+
+ let P = this.surf;
+ gl.useProgram(P.p);
+ gl.uniform2f(P.u.res, w, h); gl.uniform1f(P.u.time, t); gl.uniform1f(P.u.bass, A.bass); gl.uniform1f(P.u.level, A.level);
+ gl.uniform3fv(P.u.tint, A.tint); gl.uniform4fv(P.u.ripples, this.ripples);
+ gl.bindVertexArray(this.tri); gl.drawArrays(gl.TRIANGLES, 0, 3);
+
+ P = this.part;
+ gl.useProgram(P.p);
+ gl.uniform1f(P.u.time, t); gl.uniform2f(P.u.res, w, h); gl.uniform3fv(P.u.tint, A.tint);
+ gl.bindVertexArray(this.vao); gl.drawArrays(gl.POINTS, 0, MAX);
+ }
+}
diff --git a/web/tools/serve.mjs b/web/tools/serve.mjs
new file mode 100644
index 0000000..d18447f
--- /dev/null
+++ b/web/tools/serve.mjs
@@ -0,0 +1,17 @@
+// Dev server: `node tools/serve.mjs [port]`, serves web/ over http://localhost (mic needs a secure context; localhost qualifies).
+import http from 'node:http';
+import { readFile } from 'node:fs/promises';
+import { extname, join, normalize } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = join(fileURLToPath(new URL('.', import.meta.url)), '..');
+const types = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json' };
+const port = +(process.argv[2] || 8080);
+http.createServer(async (req, res) => {
+ const p = normalize(decodeURIComponent(new URL(req.url, 'http://x').pathname)).replace(/^(\.\.[/\\])+/, '');
+ try {
+ const f = join(root, p.endsWith('/') ? p + 'index.html' : p);
+ if (!f.startsWith(root)) throw new Error('outside root');
+ res.writeHead(200, { 'content-type': types[extname(f)] || 'application/octet-stream' }).end(await readFile(f));
+ } catch { res.writeHead(404).end('not found'); }
+}).listen(port, '127.0.0.1', () => console.log(`Perlines on http://localhost:${port}/`));