~ knotless Search/
↑↓ move↵ open⇧↵ all results

cameron.stream/prism

Audio-reactive WebGL visualizer for OBS streams

0
0
main
113 lines · 10.4 KB Raw History
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Prism</title><style>html,body{margin:0;overflow:hidden;background:#000;height:100%;cursor:none}canvas{display:block;width:100%;height:100%}</style></head><body><canvas aria-label="Audio-reactive sculptural prism ring"></canvas><script>
'use strict';
const canvas=document.querySelector('canvas');const gl=canvas.getContext('webgl',{alpha:false,antialias:false,powerPreference:'high-performance'});if(!gl)throw Error('WebGL unavailable');
const vertex=`attribute vec2 p;varying vec2 uv;void main(){uv=p*.5+.5;gl_Position=vec4(p,0.,1.);}`;
const scene=`precision highp float;
varying vec2 uv;uniform vec2 resolution;uniform sampler2D previous,history;uniform float time,energy,peak,beat,travel,dt;
#define TAU 6.28318530718
#define PI 3.14159265359
vec2 rotate(vec2 p,float a){return mat2(cos(a),-sin(a),sin(a),cos(a))*p;}
float hash(float x){return fract(sin(x*127.1+41.7)*43758.5453);}
float wave(float x){return texture2D(history,vec2(clamp(x,.002,.998),.5)).r;}
vec3 splitColor(float x){return mix(vec3(.96,.025,.06),vec3(.015,.72,.95),smoothstep(-.35,.35,sin(x)));}
float buckle(float a){
 float pressure=energy*.035+beat*.023;
 float fold=sin(a*5.+travel*.6)*sin(a*3.-travel*.27);
 return pressure*fold+.005*sin(a*2.+travel*.13);
}
vec3 filaments(vec2 p,float lane){
 float a=atan(p.y,p.x),r=length(p);
 float radius=.278+energy*.04+buckle(a);
 radius+=lane*(.0065+peak*.002)*sin(a*2.+travel*.17+lane*.2);
 radius+=wave(fract(a/TAU+.5))*.011*sin(a*17.-travel*.7);
 float dispersion=.001+peak*.005+beat*.003;
 vec3 d=vec3(length(p+vec2(dispersion,0.)),r,length(p-vec2(dispersion,0.)))-radius;
 float width=.00065+.00065*energy;
 return vec3(width*width)/(d*d+width*width)+exp(-abs(d)*230.)*.025;
}
void main(){
 vec2 p=(uv*resolution-.5*resolution)/min(resolution.x,resolution.y);
 vec2 raw=p;p=rotate(p,.07*sin(time*.07));p.y*=1.+.04*sin(time*.09);
 float r=length(p),a=atan(p.y,p.x);
 vec2 memoryUV=(uv-.5)*(1.+dt*(.025+energy*.035))+.5;
 vec3 memory=texture2D(previous,memoryUV).rgb*exp(-dt*9.);
 vec3 color=vec3(0.);
 // Polygonal pressure fronts: spatially sparse and low-luminance, never a full-screen flash.
 float angular=cos(mod(a+PI/8.+travel*.025,TAU/8.)-PI/8.);
 float polygon=r*angular;
 float outside=smoothstep(.30,.40,r)*(1.-smoothstep(.72,1.05,r));
 for(int i=0;i<3;i++){
  float offset=float(i)/3.;float phase=fract(travel*.105+offset);
  float front=.34+phase*.60;
  float envelope=wave(phase*.7);
  float line=exp(-abs(polygon-front)*650.);
  float broken=pow(max(0.,sin(a*7.+offset*19.+travel*.19)),4.);
  color+=splitColor(a*2.+offset*13.)*line*broken*outside*envelope*energy*(1.-phase)*.20;
 }
 // Narrow, angular splinters. Deterministic trajectories, not random frame flicker.
 float sector=floor((a+PI)/TAU*48.);
 float local=fract((a+PI)/TAU*48.)-.5;
 float seed=hash(sector);float flight=fract(travel*(.10+seed*.09)+seed*5.);
 float shardR=.35+flight*.42;
 float shardAngle=local-(flight-.5)*.16*sin(sector);
 float shard=exp(-abs(shardAngle)*140.)*exp(-abs(r-shardR)*100.);
 float shardPower=pow(peak,2.)*(.2+beat*.8)*step(.65,seed)*(1.-flight);
 color+=splitColor(sector*2.1)*shard*shardPower*.75;
 // Broad dark chamber walls, visible only where audio presses against the ring.
 float walls=pow(max(0.,cos(a*4.+.4)),16.)*exp(-abs(r-.46)*22.);
 color+=splitColor(a*2.)*walls*energy*.007;
 if(r>.18&&r<.43){
  vec2 q=rotate(p,.0872665);
  for(int i=0;i<8;i++){
   float lane=(float(i)-3.5)*1.35;
   vec3 f=filaments(q,lane);
   float spec=pow(max(0.,cos(a*3.+lane*.27+travel*.18)),12.);
   vec3 metal=mix(vec3(.27,.30,.34),vec3(.8,.86,.92),spec);
   vec3 edge=splitColor(a+lane*.38+travel*.13);
   vec3 tint=mix(metal,edge,.23+peak*.17);
   color+=f*tint*(.008+energy*.65+peak*.25)*(.4+spec*1.7);
  }
  float center=.278+energy*.04+buckle(a);
  float halfWidth=.027+peak*.008;
  float d=r-center;float mask=1.-smoothstep(halfWidth,halfWidth+.003,abs(d));
  float normal=sqrt(max(0.,1.-pow(d/halfWidth,2.)));
  float reflection=pow(max(0.,sin(normal*5.+a*3.+travel*.2)),16.);
  color+=vec3(.6,.67,.75)*mask*reflection*(.005+energy*.23);
  float rim=exp(-abs(abs(d)-halfWidth)*850.);
  color+=splitColor(a+travel*.12)*rim*(.006+energy*.21);
  // Audio-only segmented crescent stays legible beneath the more violent material.
  float witness=exp(-abs(r-center-halfWidth-.009)*800.)*pow(max(0.,-sin(a)),20.);
  color+=vec3(.02,.7,.95)*witness*energy*.6;
 }
 // Silence collapses new light to black; residual trails dissipate, never add up.
 color=min(color,vec3(2.));color=max(color,memory);
 gl_FragColor=vec4(color,1.);
}`;
const post=`precision highp float;varying vec2 uv;uniform sampler2D image;uniform vec2 resolution;
vec3 sampleAt(vec2 d){return texture2D(image,uv+d/resolution).rgb;}
void main(){vec3 c=sampleAt(vec2(0));vec3 glow=vec3(0.);
 glow+=sampleAt(vec2(4,0))+sampleAt(vec2(-4,0))+sampleAt(vec2(0,4))+sampleAt(vec2(0,-4));
 glow+=sampleAt(vec2(10,10))+sampleAt(vec2(-10,10))+sampleAt(vec2(10,-10))+sampleAt(vec2(-10,-10));
 glow+=sampleAt(vec2(23,0))+sampleAt(vec2(-23,0))+sampleAt(vec2(0,23))+sampleAt(vec2(0,-23));
 c+=glow*.028;c=1.-exp(-c*1.65);c=pow(c,vec3(1.04));gl_FragColor=vec4(c,1.);}`;
function makeProgram(src){function compile(type,code){const s=gl.createShader(type);gl.shaderSource(s,code);gl.compileShader(s);if(!gl.getShaderParameter(s,gl.COMPILE_STATUS))throw Error(gl.getShaderInfoLog(s));return s}const p=gl.createProgram();gl.attachShader(p,compile(gl.VERTEX_SHADER,vertex));gl.attachShader(p,compile(gl.FRAGMENT_SHADER,src));gl.linkProgram(p);if(!gl.getProgramParameter(p,gl.LINK_STATUS))throw Error(gl.getProgramInfoLog(p));return p}
const sceneProgram=makeProgram(scene),postProgram=makeProgram(post),buffer=gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,buffer);gl.bufferData(gl.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),gl.STATIC_DRAW);
function use(p){gl.useProgram(p);const a=gl.getAttribLocation(p,'p');gl.enableVertexAttribArray(a);gl.vertexAttribPointer(a,2,gl.FLOAT,false,0,0)}
function texture(){const t=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,t);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);return t}
const historyTexture=texture(),historyPixels=new Uint8Array(256);gl.texImage2D(gl.TEXTURE_2D,0,gl.LUMINANCE,256,1,0,gl.LUMINANCE,gl.UNSIGNED_BYTE,historyPixels);let targets=[],width=0,height=0;
function resize(){const scale=Math.min(devicePixelRatio||1,1280/innerWidth,720/innerHeight,1.5);width=canvas.width=Math.round(innerWidth*scale);height=canvas.height=Math.round(innerHeight*scale);for(const t of targets){gl.deleteTexture(t.texture);gl.deleteFramebuffer(t.framebuffer)}targets=[];for(let i=0;i<2;i++){const t=texture();gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,width,height,0,gl.RGBA,gl.UNSIGNED_BYTE,null);const f=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,f);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,t,0);if(gl.checkFramebufferStatus(gl.FRAMEBUFFER)!==gl.FRAMEBUFFER_COMPLETE)throw Error('Framebuffer unavailable');gl.clearColor(0,0,0,1);gl.clear(gl.COLOR_BUFFER_BIT);targets.push({texture:t,framebuffer:f})}gl.bindFramebuffer(gl.FRAMEBUFFER,null)}addEventListener('resize',resize);resize();
const u={};for(const n of ['resolution','previous','history','time','energy','peak','beat','travel','dt'])u[n]=gl.getUniformLocation(sceneProgram,n);const postU={image:gl.getUniformLocation(postProgram,'image'),resolution:gl.getUniformLocation(postProgram,'resolution')};
let target=0,peakTarget=0,energy=0,peak=0,beat=0,travel=0,lastSample=-Infinity,lastRms=0,samples=0,source=null,status='waiting';
function ingest(v){if(v.status!=='audio')return;const rms=Number(v.rms),pk=Number(v.peak);if(!Number.isFinite(rms)||!Number.isFinite(pk))return;lastSample=performance.now();samples++;source=v.source;status='audio';lastRms=Math.max(0,rms);
 // Fixed dB mapping, not auto-gain: silence stays silent and dynamics stay legible.
 const db=20*Math.log10(Math.max(1e-7,rms));target=Math.pow(Math.max(0,Math.min(1,(db+58)/48)),1.35);peakTarget=Math.max(0,Math.min(1,(20*Math.log10(Math.max(pk,1e-7))+55)/50));}
const feed=new EventSource('/audio');feed.onmessage=e=>{try{const v=JSON.parse(e.data);if(v.status!=='audio')status=v.status||'error';ingest(v)}catch{}};feed.onerror=()=>status='disconnected';
let previous=performance.now(),read=0,historyTick=0,frames=0,totalDt=0;function frame(now){requestAnimationFrame(frame);const dt=Math.min(.075,(now-previous)/1000);previous=now;frames++;totalDt+=dt;if(now-lastSample>700){target=0;peakTarget=0}const old=energy;energy+=(target-energy)*(1-Math.exp(-dt*(target>energy?24:4)));peak+=(peakTarget-peak)*(1-Math.exp(-dt*(peakTarget>peak?30:6)));beat=Math.max(beat*Math.exp(-dt*5),Math.min(1,Math.max(0,energy-old)*17));travel+=dt*(.16+energy*1.6);
 historyTick+=dt;if(historyTick>=1/30){historyTick%=1/30;historyPixels.copyWithin(1,0,255);historyPixels[0]=Math.round(energy*255)}
 use(sceneProgram);gl.viewport(0,0,width,height);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,targets[read].texture);gl.uniform1i(u.previous,0);gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,historyTexture);gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,256,1,gl.LUMINANCE,gl.UNSIGNED_BYTE,historyPixels);gl.uniform1i(u.history,1);gl.uniform2f(u.resolution,width,height);for(const[n,v]of Object.entries({time:now/1000,energy,peak,beat,travel,dt}))gl.uniform1f(u[n],v);const write=1-read;gl.bindFramebuffer(gl.FRAMEBUFFER,targets[write].framebuffer);gl.drawArrays(gl.TRIANGLES,0,6);
 use(postProgram);gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,targets[write].texture);gl.uniform1i(postU.image,0);gl.uniform2f(postU.resolution,width,height);gl.drawArrays(gl.TRIANGLES,0,6);read=write;
}requestAnimationFrame(frame);
addEventListener('dblclick',()=>{if(!document.fullscreenElement)document.documentElement.requestFullscreen?.()});addEventListener('keydown',e=>{if(e.key.toLowerCase()==='f'){if(document.fullscreenElement)document.exitFullscreen?.();else document.documentElement.requestFullscreen?.()}});
window.prismHealth=()=>({ready:true,width,height,source,status,samples,lastRms,energy,peak,beat,ageMs:Math.round(performance.now()-lastSample),averageFps:Math.round(frames/totalDt)});
</script></body></html>