this logo: 245 b

← INDIVISIBLE v1

index.html

<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>INDIVISIBLE</title>
<meta name=viewport content="width=device-width,initial-scale=1">
<style>html,body{margin:0;height:100%;background:#000;overflow:hidden}canvas{display:block;width:100vw;height:100vh;cursor:pointer}</style>
</head>
<body>
<canvas id=c></canvas>
<script>
/* INDIVISIBLE - five pictures of the prime numbers, each one turning into the next.
   A sieve strikes out the multiples; what is left is wound into Ulam's square spiral, unwound into
   Sacks' round one, then thrown out to radius p at angle p radians, where a long zoom finds 20 arms,
   then 44 spirals, then 280 rays. It ends on the Gaussian primes.
   One point per integer up to a million, placed in the vertex shader. The arpeggio plays the gaps
   between consecutive primes and the hi-hats fall on prime-numbered steps. No assets, no dependencies.
   Keys: F fullscreen. Drop an audio file to use your own music. */
(()=>{
'use strict';

/* ---------------- synth (runs inside an AudioWorklet) ---------------- */
function SYN(sr){
const TAU=6.283185307179586,T=1/sr,S16=sr/8,LEN=960,mf=n=>440*2**((n-69)/12),dc=s=>Math.exp(-1/(sr*s));
let rs=22222;const rnd=()=>{rs^=rs<<13;rs^=rs>>>17;rs^=rs<<5;return(rs>>>0)/2147483648-1};
// TPT state variable filter: returns low-pass, leaves band-pass in s[2]
const svf=(s,x,fc,k)=>{const g=Math.tan(Math.PI*Math.min(fc,sr*.45)*T),h=1/(1+g*(g+k)),v3=x-s[1],v1=h*s[0]+g*h*v3,v2=s[1]+g*h*s[0]+g*g*h*v3;s[0]=2*v1-s[0];s[1]=2*v2-s[1];s[2]=v1;return v2};
const saw=(p,d)=>{let v=2*p-1;if(p<d){const t=p/d;v-=t+t-t*t-1}else if(p>1-d){const t=(p-1)/d;v-=t*t+t+t+1}return v};
// 120 BPM, 60 bars. D minor: Dm Bb F C, as [bass root, triad]. PN: D minor pentatonic.
const CH=[[38,62,65,69],[34,62,65,70],[41,60,65,69],[36,60,64,67]],PN=[62,65,67,69,72,74,77,79,81,84];
// the primes: the arpeggio plays half the gap to the next one, the hats fall on prime-numbered steps of each two bars
const P=[],ip=new Uint8Array(9000).fill(1);for(let i=2;i<9000;i++)if(ip[i]){P.push(i);for(let j=i*i;j<9000;j+=i)ip[j]=0}
const ME=[69,0,0,74,0,0,77,0,76,0,74,0,0,0,69,0,70,0,0,74,0,0,77,0,79,0,77,0,0,0,74,0,
          72,0,0,77,0,0,81,0,79,0,77,0,0,0,72,0,76,0,0,79,0,0,84,0,81,0,79,0,76,0,0,0];
// per section of 8 bars: pad cutoff a,b, arp cutoff a,b, bass cutoff a,b, pad level, arp level, lead level
// 0 sieve, 1 Ulam, 2 unwinding, 3-5 the zoom, 6 Gaussian primes, 7 out
const AU=[[300,1500,400,1600,0,0,1,.7,.6],[1500,2500,1600,2800,80,300,.8,.7,0],[2500,4500,2800,4500,300,450,.8,.8,0],
          [4500,5000,4500,5000,420,600,.7,.9,0],[5000,5000,4500,5500,450,600,.7,.9,.8],[5000,5000,5000,5500,500,650,.7,.9,1],
          [3500,1500,3500,2000,300,200,.9,.8,0],[1500,250,2000,250,200,70,.8,.7,0]];
let pos=0,nx=0,st=-1,
 kt=-1,kp=0,
 bph=0,bf=55,be=0,ba=0,bt=0,bcut=0,
 he=0,hd=.99,hl=0,ce=-1,clv=0,cre=0,crl=0,ris=0,ri=0,
 pl=0,pr=0,pl2=0,pr2=0,pc=.02,pct=.02,plv=0,plt=0,
 aph=0,af=220,ae=0,acut=800,alv=0,ap=.3,
 lph=0,lph2=0,lf=440,lt=440,le=0,llv=0,lvt=0,
 di=0,dlp=0,drp=0;
const bs=new Float64Array(3),cs=new Float64Array(3),rz=new Float64Array(3),as=new Float64Array(3),ls=new Float64Array(3);
const pph=new Float64Array(12).map(()=>rnd()*.5+.5),pfr=new Float64Array(12),pdt=[.9936,.9977,1.0029,1.0069];
const bdc=dc(.07),bad=dc(.2),adc=dc(.11),ldc=dc(.9),crd=dc(.5),hdo=dc(.09),hdc=dc(.018);
// stereo ping-pong delay (dotted eighth) and a Freeverb-style reverb
const DN=Math.round(S16*3),dL=new Float32Array(DN),dR=new Float32Array(DN);
const mk=(a,o)=>a.map(n=>new Float32Array(Math.round((n+o)*sr/44100)));
const cl=[1116,1188,1277,1356,1422,1491,1557,1617],al=[556,441,341,225];
const cL=mk(cl,0),cR=mk(cl,23),aL=mk(al,0),aR=mk(al,23),ci=new Int32Array(16),ai=new Int32Array(8),cf=new Float64Array(16);
const verb=(x,C,A,o)=>{let y=0;
 for(let j=0;j<8;j++){const b=C[j],q=o*8+j,i=ci[q],v=b[i];cf[q]=v*.8+cf[q]*.2;b[i]=x+cf[q]*.86;ci[q]=i+1==b.length?0:i+1;y+=v}
 for(let j=0;j<4;j++){const b=A[j],q=o*4+j,i=ai[q],v=b[i];b[i]=y+v*.5;ai[q]=i+1==b.length?0:i+1;y=v-y}
 return y};
const X=(a,b,sp)=>a*(b/a)**sp;
const trig=()=>{
 const s=st&15,bar=st>>4,b8=bar&7,sec=bar>>3,sp=(b8*16+s)/(sec==7?64:128),ch=CH[(bar>>1)&3],A=AU[sec],q=st&31,
  dr=sec>0&&sec<7,full=sec>2&&sec<6;
 for(let j=0;j<12;j++)pfr[j]=mf(ch[1+(j>>2)])*pdt[j&3];
 pct=1-Math.exp(-TAU*X(A[0],A[1],sp)*T);acut=X(A[2],A[3],sp);bcut=A[4]?X(A[4],A[5],sp):0;
 plt=A[6]*(sec?1:Math.min(1,sp*4))*(sec==7?1-sp:1);alv=A[7]*(sec==7?1-sp:1);llv=A[8];
 if(dr&&!(s&3)&&(sec>1||sp>.25)){kt=0;kp=0}
 if(full&&(s==4||s==12)){ce=0;clv=.5}
 if(sec==6&&s==12){ce=0;clv=.3}
 if(sec==2&&bar>21&&(bar>22||!(s&1))){ce=0;clv=.1+.45*(((bar-22)*16+s)/32)**2}
 if(dr&&q>1&&ip[q]){he=.5*(full?1:.6);hd=q>16&&full?hdo:hdc}else if(full){he=.12;hd=hdc}
 if(bcut&&dr&&(s&3)){bf=mf(ch[0]+((s&3)==3&&(bar&1)?12:0));be=1;bt=1}
 if(sec||!(s&1)){af=mf(PN[Math.min(9,(P[st+2]-P[st+1])/2)]+(full?12:0));ae=1;ap=-ap}
 // the sieve: one note as each prime starts striking out its multiples
 if(!sec&&st>7&&st<105&&!((st-8)%12)){lt=mf(PN[(st-8)/12]+12);le=1}
 if(sec>3&&llv>0&&!(s&1)){const n=ME[b8*8+(s>>1)];if(n){lt=mf(n);le=1}}
 if(!s&&!b8&&sec){cre=1;crl=full?.45:.25}
 ris=sec==2&&b8>3?((b8-4)*16+s)/64:sec==5&&b8==7?s/16:0;
};
return(L,R)=>{
 for(let i=0;i<L.length;i++){
  if(pos>=nx){nx+=S16;st=(st+1)%LEN;trig()}
  pos++;
  let m=0,l=0,r=0,duck=1,dly=0,rv=0;
  // kick
  if(kt>=0){kp+=(46+160*Math.exp(-kt*24)+500*Math.exp(-kt*160))*T;m+=Math.tanh(Math.sin(TAU*kp)*Math.exp(-kt*6)*2.2)*.75;duck=1-.75*Math.exp(-kt*9);kt+=T;if(kt>.6)kt=-1}
  // bass
  if(bcut){bph+=bf*T;if(bph>=1)bph-=1;be*=bdc;bt*=bad;ba+=(bt-ba)*.02;
   m+=Math.tanh(svf(bs,(saw(bph,bf*T)*.7+Math.sin(TAU*bph)*.6)*ba,bcut*(1+5*be),.5)*1.6)*.42*duck}
  // hats, clap, crash, riser share one noise source
  const n=rnd();hl+=(n-hl)*.4;const hh=n-hl;he*=hd;l+=hh*he*.2;r+=hh*he*.24;
  if(ce>=0){svf(cs,n,1300,.7);const c=cs[2]*(ce<.03?1-(ce%.01)*70:Math.exp(-(ce-.03)*20))*clv*1.6;m+=c;rv+=c*.5;ce+=T;if(ce>.5)ce=-1}
  cre*=crd;{const c=hh*cre*crl;l+=c;r+=c;rv+=c*.5}
  ri+=(ris-ri)*.001;if(ri>.001){svf(rz,n,300*2**(ri*5),.4);const c=rz[2]*ri*ri*.35;m+=c;rv+=c*.3}
  // pad: 3 notes x 4 detuned saws, split left/right
  {let a=0,b=0;for(let j=0;j<12;j++){let p=pph[j]+pfr[j]*T;if(p>=1)p-=1;pph[j]=p;if(j&1)b+=p;else a+=p}
   pc+=(pct-pc)*.0005;plv+=(plt-plv)*.0002;
   pl+=((2*a-6)*.07-pl)*pc;pl2+=(pl-pl2)*pc;pr+=((2*b-6)*.07-pr)*pc;pr2+=(pr-pr2)*pc;
   const g=plv*(.35+.65*duck);l+=pl2*g;r+=pr2*g;rv+=(pl2+pr2)*g*.25}
  // arp pluck
  if(alv>0||ae>1e-4){aph+=af*T;if(aph>=1)aph-=1;ae*=adc;
   const x=svf(as,(saw(aph,af*T)+(aph<.5?.5:-.5))*ae,acut*(1+3*ae),.35)*alv*.22*(.5+.5*duck);
   l+=x*.6*(1-ap);r+=x*.6*(1+ap);dly+=x*.7;rv+=x*.3}
  // lead
  if(llv>0||le>1e-4){lf+=(lt-lf)*.002;lvt+=T;const f=lf*(1+.005*Math.sin(TAU*5.5*lvt))*T;
   lph+=f*1.004;if(lph>=1)lph-=1;lph2+=f*.996;if(lph2>=1)lph2-=1;le*=ldc;
   const x=svf(ls,(saw(lph,f)+saw(lph2,f))*le,1500+3500*le,.6)*llv*.16;m+=x;dly+=x*.8;rv+=x*.5}
  // delay
  {const a=dL[di],b=dR[di];dlp+=(b-dlp)*.4;drp+=(a-drp)*.4;dL[di]=dly+dlp*.5;dR[di]=drp*.5;if(++di==DN)di=0;l+=a*.6;r+=b*.6;rv+=(a+b)*.15}
  // reverb + soft clip
  l+=verb(rv*.03+1e-18,cL,aL,0)*1.2;r+=verb(rv*.03+1e-18,cR,aR,1)*1.2;
  L[i]=Math.tanh((m+l)*.9);R[i]=Math.tanh((m+r)*.9);
 }
 return pos};
}

/* ---------------- shaders ---------------- */
const VS=`#version 300 es
void main(){gl_Position=vec4(vec2(gl_VertexID&1,gl_VertexID>>1)*4.-1.,0,1);}`;
const VH=`#version 300 es
precision highp float;precision highp int;precision highp sampler2D;
uniform float uSA,uRot,uAsp,uPs,uRow,uFd;uniform vec4 uK;uniform sampler2D uS;out vec3 vC;
vec3 pal(float t){return .55+.45*cos(6.2832*(t+vec3(0.,.33,.67)));}
float fth(float x,float a){return textureLod(uS,vec2(x,uRow-clamp(a,0.,1.)*.98),0.).r;}   // spectrum a*2 seconds ago
`;
// one vertex per integer: gl_VertexID is the number itself
const VP=VH+`layout(location=0)in float aA;layout(location=1)in float aF;   // aA: n mod 2 pi (float32 cannot hold n radians), aF: 0 if prime, else smallest prime factor
uniform int uLA,uLB;uniform float uMix,uSB,uTau,uCmp,uHue,uSv;
int ix(int q){return q<3?0:q<5?1:q<7?2:q<11?3:q<13?4:q<17?5:q<19?6:q<23?7:q<29?8:9;}
vec2 lay(int L,int ni){
  float n=float(ni);
  if(L==0){int k=ni-1;return vec2(float(k%32)-15.5,9.5-float(k/32));}       // rows of 32
  if(L==1){                                                                  // Ulam: a square spiral
    int k=int(ceil((sqrt(n)-1.)*.5));if((2*k+1)*(2*k+1)<ni)k++;if(k>0&&(2*k-1)*(2*k-1)>=ni)k--;
    int t=2*k,m=(t+1)*(t+1);
    if(ni>=m-t)return vec2(k-(m-ni),-k);m-=t;
    if(ni>=m-t)return vec2(-k,-k+(m-ni));m-=t;
    if(ni>=m-t)return vec2(-k+(m-ni),k);
    return vec2(k,k-(m-ni-t));
  }
  if(L==2){float r=sqrt(n),t=6.2831853*r;return r*vec2(cos(t),sin(t));}      // Sacks: one turn per square
  return n*vec2(cos(aA),sin(aA));                                            // radius n, angle n radians
}
void main(){
  int ni=gl_VertexID;float n=float(ni);bool pr=aF<.5;
  if(!pr&&uCmp<.004){gl_Position=vec4(2,2,2,1);gl_PointSize=0.;return;}   // outside the clip volume: never rasterised
  float m=clamp(uMix*1.6-.6*fract(n*.61803),0.,1.);m=m*m*(3.-2.*m);
  vec2 p=mix(lay(uLA,ni)*uSA,lay(uLB,ni)*uSB,m);
  float c=cos(uRot),s=sin(uRot),sz=1.;p=mat2(c,-s,s,c)*p;
  vec3 col;
  if(uSv>.5){   // the sieve: prime number i starts at step 8+12i and sweeps down the page striking out its multiples
    int q=pr?ni:int(aF);float d=uTau-8.-12.*float(ix(q))-(pr?0.:n/640.*20.);
    if(pr)col=vec3(.6,.75,1.)*(.35+.65*smoothstep(100.,126.,uTau))+(q<24&&d>0.?pal(float(ix(q))/9.)*3.*exp(-d*.25):vec3(0));
    else{col=d<0.?vec3(.3,.34,.4):pal(float(ix(q))/9.)*2.5*exp(-d*.6)+.035;if(d>0.)sz=.6+.4*exp(-d*.6);}
    if(ni==1)col=vec3(.03);
  }else col=pr?mix(vec3(.6,.75,1.),pal(float(ni%44)/44.+.55),uHue)*(1.+2.5*fth(.07,length(p)*.4)):vec3(.2,.24,.3)*uCmp;
  if(uLA==0&&ni>640)col*=m;                       // the page of the sieve stops at 640; the rest arrive with the spiral
  vC=col*uFd;
  gl_Position=vec4(p.x/uAsp,p.y,0.,1.);
  gl_PointSize=uPs*sz*(pr?1.+.5*uK.x:.75);
}`;
// Gaussian primes: one vertex per prime a+bi
const VG=VH+`layout(location=0)in vec2 aP;
void main(){
  float r=length(aP),c=cos(uRot),s=sin(uRot);vec2 p=mat2(c,-s,s,c)*aP*uSA;
  vC=pal(atan(aP.y,aP.x)/6.2832*2.+r*.006+.55)*(.5+2.5*fth(.07,length(p)*.4)+1.5*fth(.6,length(p)*.4))*uFd;
  gl_Position=vec4(p.x/uAsp,p.y,0.,1.);
  gl_PointSize=uPs*(1.+.5*uK.x);
}`;
const FP=`#version 300 es
precision highp float;in vec3 vC;out vec4 O;
void main(){O=vec4(vC*smoothstep(.5,.1,length(gl_PointCoord-.5)),1);}`;

const PRE=`#version 300 es
precision highp float;uniform sampler2D uC;uniform vec2 uR,uI;uniform float uTh;out vec4 O;
`;
// dual-filter bloom: 5-tap downsample (soft threshold on the first pass), 8-tap tent upsample
const DOWN=PRE+`void main(){vec2 v=gl_FragCoord.xy/uR;
vec3 s=texture(uC,v).rgb*4.+texture(uC,v+uI).rgb+texture(uC,v-uI).rgb+texture(uC,v+uI*vec2(1,-1)).rgb+texture(uC,v+uI*vec2(-1,1)).rgb;s*=.125;
if(uTh>0.){s=min(s,vec3(24.));s*=smoothstep(.5,1.8,max(s.r,max(s.g,s.b)));}
O=vec4(s,1);}`;
const UP=PRE+`void main(){vec2 v=gl_FragCoord.xy/uR;vec3 e=vec3(uI,0.);
vec3 s=texture(uC,v+e.xz).rgb+texture(uC,v-e.xz).rgb+texture(uC,v+e.zy).rgb+texture(uC,v-e.zy).rgb
+2.*(texture(uC,v+uI*.5).rgb+texture(uC,v-uI*.5).rgb+texture(uC,v+uI*vec2(.5,-.5)).rgb+texture(uC,v+uI*vec2(-.5,.5)).rgb);
O=vec4(s/12.,1);}`;
const COMP=`#version 300 es
precision highp float;uniform sampler2D uC,uB,uX,uS;uniform vec2 uR;uniform float uT,uF,uXa,uRow,uFl;out vec4 O;
vec3 aces(vec3 x){return clamp((x*(2.51*x+.03))/(x*(2.43*x+.59)+.14),0.,1.);}
void main(){
  vec2 v=gl_FragCoord.xy/uR,c=v-.5;float r2=dot(c,c);
  vec2 o=c*r2*(.012+.03*uFl);
  vec3 col=vec3(texture(uC,v-o).r,texture(uC,v).g,texture(uC,v+o).b);
  col+=texture(uB,v).rgb*.16;
  col*=1.-1.1*r2;
  col+=uFl*.3;
  col=pow(aces(col*1.15),vec3(.4545));
  float sp=texture(uS,vec2(abs(c.x)*2.,uRow)).r;
  col+=.35*step(v.y,.003+.035*sp)*vec3(.6,.8,1.);
  col=mix(col,vec3(1),texture(uX,vec2(v.x,1.-v.y)).a*uXa);
  col+=(fract(sin(dot(gl_FragCoord.xy+uT*61.,vec2(12.9898,78.233)))*43758.5453)-.5)*.035;
  O=vec4(col*uF,1);
}`;

/* ---------------- GL setup ---------------- */
const C=document.getElementById('c'),gl=C.getContext('webgl2',{antialias:false,alpha:false,powerPreference:'high-performance'});
if(!gl){document.body.innerHTML='<p style="color:#fff;font:16px sans-serif;padding:2em">This demo needs WebGL2.</p>';return}
const HF=gl.getExtension('EXT_color_buffer_float')||gl.getExtension('EXT_color_buffer_half_float');
gl.getExtension('KHR_parallel_shader_compile');
const TQ=gl.getExtension('EXT_disjoint_timer_query_webgl2'),tq=TQ&&gl.createQuery();let qp=0,gms=8;
const IF=HF?gl.RGBA16F:gl.RGBA8,TY=HF?gl.HALF_FLOAT:gl.UNSIGNED_BYTE;
gl.bindVertexArray(gl.createVertexArray());
const tex=(unit,wrapT)=>{const t=gl.createTexture();gl.activeTexture(gl.TEXTURE0+unit);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,wrapT||gl.CLAMP_TO_EDGE);return t};
const target=(w,h)=>{const t=tex(1);gl.texImage2D(gl.TEXTURE_2D,0,IF,w,h,0,gl.RGBA,TY,null);
 const f=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,f);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,t,0);return{t,f,w,h}};
const prog=(fs,vs)=>{const p=gl.createProgram(),sh=[];
 for(const[ty,src]of[[gl.VERTEX_SHADER,vs||VS],[gl.FRAGMENT_SHADER,fs]]){const s=gl.createShader(ty);gl.shaderSource(s,src);gl.compileShader(s);gl.attachShader(p,s);sh.push(s)}
 gl.linkProgram(p);return{p,sh,u:null}};
const errs=[];
const use=o=>{
 if(!o.u){o.u={};
  if(!gl.getProgramParameter(o.p,gl.LINK_STATUS)){const e=gl.getProgramInfoLog(o.p)+'\n'+gl.getShaderInfoLog(o.sh[1]);errs.push(e);console.error('shader',e)}
  for(let i=0,n=gl.getProgramParameter(o.p,gl.ACTIVE_UNIFORMS);i<n;i++){const a=gl.getActiveUniform(o.p,i);o.u[a.name]=gl.getUniformLocation(o.p,a.name)}}
 gl.useProgram(o.p);return o.u};
const PD=prog(DOWN),PU=prog(UP),PC=prog(COMP);

// spectrogram texture: 256 log-frequency bins x 128 rows of history (ring buffer)
const NB=256,HR=128,cur=new Float32Array(NB),row8=new Uint8Array(NB);
const TS=tex(0,gl.REPEAT);gl.pixelStorei(gl.UNPACK_ALIGNMENT,1);
gl.texImage2D(gl.TEXTURE_2D,0,gl.R8,NB,HR,0,gl.RED,gl.UNSIGNED_BYTE,new Uint8Array(NB*HR));
// text overlay
const TX=tex(3),XC=document.createElement('canvas'),X=XC.getContext('2d');
let W=0,H=0,sc=1,scMax=1,S=null,B=[],txt=['','',''],txtDirty=1;
const free=o=>{if(o){gl.deleteTexture(o.t);gl.deleteFramebuffer(o.f)}};
const alloc=()=>{free(S);B.forEach(free);B=[];
 let w=Math.max(2,W*sc|0),h=Math.max(2,H*sc|0);S=target(w,h);
 for(let i=0;i<6;i++){w=Math.max(1,w>>1);h=Math.max(1,h>>1);B.push(target(w,h))}};
const resize=()=>{const d=Math.min(devicePixelRatio||1,2);W=C.width=Math.max(2,innerWidth*d|0);H=C.height=Math.max(2,innerHeight*d|0);
 scMax=sc=Math.min(1,Math.sqrt(5e6/(W*H)));alloc();txtDirty=1};
addEventListener('resize',resize);resize();
const drawText=()=>{txtDirty=0;
 const w=XC.width=Math.min(W,1600),h=XC.height=Math.max(1,Math.round(w*H/W));X.clearRect(0,0,w,h);X.fillStyle='#fff';X.textBaseline='middle';
 const sans='"Helvetica Neue",Helvetica,Arial,sans-serif',mono='ui-monospace,Menlo,Consolas,monospace';
 if(txt[0]){X.textAlign='center';X.font=`200 ${h*.15}px ${sans}`;try{X.letterSpacing=h*.045+'px'}catch(e){}X.fillText(txt[0],w/2+h*.022,h*.47)}
 try{X.letterSpacing=h*.008+'px'}catch(e){}
 if(txt[1]){X.textAlign='center';X.font=`400 ${h*.026}px ${mono}`;X.fillText(txt[1],w/2,h*.61)}
 if(txt[2]){X.textAlign='left';X.font=`400 ${h*.024}px ${mono}`;X.fillText(txt[2],h*.06,h*.9)}
 gl.activeTexture(gl.TEXTURE3);gl.bindTexture(gl.TEXTURE_2D,TX);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,XC)};

/* ---------------- the numbers ---------------- */
// smallest prime factor of everything up to a million; the primes; and each n reduced mod 2 pi in double precision
const N=1e6,spf=new Uint32Array(N+1),PR=[],aA=new Float32Array(N+1),aF=new Uint8Array(N+1);
for(let i=2;i<=N;i++){if(!spf[i]){PR.push(i);for(let j=i;j<=N;j+=i)if(!spf[j])spf[j]=i}aA[i]=i%(2*Math.PI);aF[i]=spf[i]==i?0:Math.min(255,spf[i])}
aA[1]=1;aF[1]=255;
const abuf=(loc,data,size,type)=>{gl.bindBuffer(gl.ARRAY_BUFFER,gl.createBuffer());gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);gl.enableVertexAttribArray(loc);gl.vertexAttribPointer(loc,size,type,false,0,0)};
const VAP=gl.createVertexArray();gl.bindVertexArray(VAP);abuf(0,aA,1,gl.FLOAT);abuf(1,aF,1,gl.UNSIGNED_BYTE);
// Gaussian primes a+bi: a^2+b^2 is prime, or one part is zero and the other is a prime of the form 4k+3
const gpts=[];
for(let a=-150;a<=150;a++)for(let b=-150;b<=150;b++){const m=Math.abs(a)+Math.abs(b);if(a&&b?spf[a*a+b*b]==a*a+b*b:m>1&&spf[m]==m&&m%4==3)gpts.push(a,b)}
const VAG=gl.createVertexArray();gl.bindVertexArray(VAG);abuf(0,new Int16Array(gpts),2,gl.SHORT);
const PP=prog(FP,VP),PG=prog(FP,VG);

/* ---------------- audio + FFT ---------------- */
let ctx=null,an=null,node=null,t0=null,ext=null,extT=0,fb=null,lo=null,hi=null,mode='';
const start=async()=>{
 if(ctx){ctx.resume();return}
 ctx=new(window.AudioContext||window.webkitAudioContext)({latencyHint:'playback'});ctx.resume();
 an=ctx.createAnalyser();an.fftSize=2048;an.smoothingTimeConstant=.35;an.minDecibels=-85;an.maxDecibels=-18;an.connect(ctx.destination);
 fb=new Uint8Array(1024);
 const hz=ctx.sampleRate/2048;lo=new Float32Array(NB);hi=new Float32Array(NB);
 for(let i=0;i<NB;i++){lo[i]=35*2**(i/NB*8.8)/hz;hi[i]=35*2**((i+1)/NB*8.8)/hz}
 try{ // data: URL, because Blob URL worklets fail to load from file:// in Chrome
  await ctx.audioWorklet.addModule('data:text/javascript;charset=utf-8,'+encodeURIComponent(SYN+';registerProcessor("s",class extends AudioWorkletProcessor{constructor(){super();this.f=SYN(sampleRate);this.n=0}process(i,o){const p=this.f(o[0][0],o[0][1]);if(!(this.n++&31))this.port.postMessage([p,currentTime]);return true}})'));
  node=new AudioWorkletNode(ctx,'s',{numberOfInputs:0,outputChannelCount:[2]});
  node.port.onmessage=e=>{t0=e.data[1]-(e.data[0]-128)/ctx.sampleRate};mode='worklet';
 }catch(e){ // no worklet: same synth on the main thread
  const f=SYN(ctx.sampleRate);node=ctx.createScriptProcessor(2048,0,2);
  node.onaudioprocess=e=>{const b=e.outputBuffer,p=f(b.getChannelData(0),b.getChannelData(1));t0=e.playbackTime-(p-2048)/ctx.sampleRate};mode='scriptprocessor: '+e;
 }
 if(!ext)node.connect(an);
};
// your own music: drop a file, the FFT does the rest
const play=async file=>{
 await start();
 const buf=await ctx.decodeAudioData(await file.arrayBuffer());
 if(ext)ext.stop();else node.disconnect();
 ext=ctx.createBufferSource();ext.buffer=buf;ext.loop=true;ext.connect(an);ext.start();extT=ctx.currentTime;
};
addEventListener('dragover',e=>e.preventDefault());
addEventListener('drop',e=>{e.preventDefault();const f=e.dataTransfer.files[0];if(f)play(f).catch(e=>console.error(e))});
addEventListener('pointerdown',start);
addEventListener('keydown',e=>{
 if(e.key=='f'||e.key=='F'){try{(document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen()).catch(()=>{})}catch(e){}}

 start()});

const band=[0,0,0,0],peak=[.2,.2,.2,.2],A=[0,0,0,0],K=[0,0,0,0],RG=[0,52,116,186,256];
let pb=0,ph=0,row=0,racc=0;
const analyse=dt=>{
 if(an&&ctx.state=='running'){
  an.getByteFrequencyData(fb);
  for(let i=0;i<NB;i++){
   const a=lo[i],b=hi[i];let v=0,k=a|0;
   if(b-a<1)v=fb[k]+(fb[k+1]-fb[k])*(a-k);else for(;k<b;k++)v=Math.max(v,fb[k]);
   {const x=i/NB;v=Math.max(0,v/255-.3+.14*x)/.7*(.8+1.2*x)}v=Math.min(1,v*v*1.3);
   cur[i]+=(v-cur[i])*(v>cur[i]?.7:1-Math.exp(-dt*9));
  }
 }else for(let i=0;i<NB;i++)cur[i]*=.9;
 for(let j=0;j<4;j++){
  let s=0;for(let i=RG[j];i<RG[j+1];i++)s+=cur[i];s/=RG[j+1]-RG[j];
  band[j]=s;peak[j]=Math.max(peak[j]*Math.exp(-dt*.05),s,.12);
  A[j]+=(Math.min(1,s/peak[j])-A[j])*.5;
 }
 const d=Math.exp(-dt*5);
 K[0]=Math.max(K[0]*d,Math.min(1,Math.max(0,band[0]-pb)*7));pb=band[0];
 K[1]=Math.max(K[1]*d,Math.min(1,Math.max(0,band[3]-ph)*9));ph=band[3];
 K[2]+=dt*A[0];K[3]+=dt*(A[0]+A[1]+A[2]+A[3])*.25;
 racc+=dt;
 if(racc>=1/61){racc=Math.min(racc-1/60,.02);row=(row+1)%HR;
  for(let i=0;i<NB;i++)row8[i]=cur[i]*255;
  gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,TS);gl.texSubImage2D(gl.TEXTURE_2D,0,0,row,NB,1,gl.RED,gl.UNSIGNED_BYTE,row8)}
};

/* ---------------- timeline ---------------- */
const ss=(a,b,x)=>{x=Math.min(1,Math.max(0,(x-a)/(b-a)));return x*x*(3-2*x)};
const fmt=n=>Math.round(n).toLocaleString('en-US');
const pi=x=>{let a=0,b=PR.length;while(a<b){const m=a+b>>1;if(PR[m]<=x)a=m+1;else b=m}return a};   // how many primes up to x
let flash=0,fade=0,lt=0,lbar=-1,dbg=-1,frames=0,capN=0,cap='',bpNow=0;
const frame=now=>{
 requestAnimationFrame(frame);frames++;
 const t=now/1e3,dt=Math.min(.1,Math.max(.001,t-lt));lt=t;
 analyse(dt);
 let run=0,mt=0;
 if(ext){mt=(ctx.currentTime-extT)%120;run=1}
 else if(t0!=null&&ctx.state=='running'){mt=Math.max(0,ctx.currentTime-t0-(ctx.outputLatency||0))%120;run=1}
 if(dbg>=0){mt=dbg*2;run=1}
 const bp=mt/2,bar=bp|0,tau=bp*16,pxu=S.h/2;bpNow=bp;   // 120 BPM: a bar is two seconds
 if(bar!=lbar){if(run&&lbar>=0&&bar&&!(bar&7)&&bar<56)flash=1;lbar=bar}
 // which picture is turning into which, and how far out we are (scales are 1 / numbers from the centre to the top edge)
 let LA=0,LB=0,mix=0,SA=1/12,SB=1/12;
 const us=1/(12*11**(Math.min(Math.max(bp-8,0),8)/8));
 if(bp<8);
 else if(bp<10){LB=1;mix=ss(8,10,bp);SB=us}
 else if(bp<16){LA=LB=1;SA=SB=us}
 else if(bp<20){LA=1;LB=2;mix=ss(16,19.5,bp);SA=SB=1/(132+12*(bp-16))}
 else if(bp<24){LA=2;LB=3;mix=((bp-20)/4)**3;SA=1/180;SB=1/1200}
 else{LA=LB=3;SA=SB=1/(1200*400**(Math.min(bp-24,24)/24))}
 const cmp=bp<9?1:1-ss(9,13,bp),
  fP=1-ss(48,50.5,bp),fG=ss(48.5,51.5,bp),cell=pxu*(SA+(SB-SA)*mix),
  p0=Math.min(Math.max(cell*.62,S.h*.0016),S.h*.06),p1=S.h*(.009-.0072*ss(24,42,bp)),
  ps=bp<20?p0:bp<24?p0+(p1-p0)*mix:p1,bri=bp<20?Math.min(1.6,(cell/ps)**2*3):1.25-.45*ss(40,48,bp),
  sG=1/(95-4*Math.max(0,bp-48));
 // text
 let big='',sub='';
 if(!run){big='INDIVISIBLE';sub='click to start'}
 else if(bp<2){big='INDIVISIBLE';sub='five pictures of the primes'}
 else if(bp>=56){big='INDIVISIBLE';sub='by 1 and by itself'}
 if(!(capN++%6)){const i=(tau-8)/12|0,r=1/SA;
  cap=!run?'':bp<8?'sieve of eratosthenes   '+(tau<8?'':i<9?'striking out multiples of '+[2,3,5,7,11,13,17,19,23][i]:'what is left is prime'):
   bp<16?'ulam spiral   primes below '+fmt(Math.min(N,4*r*r))+': '+fmt(pi(Math.min(N,4*r*r))):
   bp<20?'sacks spiral   one turn per square number':bp<24?'radius p   angle p radians':
   bp<48?'primes below '+fmt(r)+': '+fmt(pi(r))+'   '+(r<6e3?'20 arms':r<12e4?'44 spirals':'280 rays'):bp<56?'gaussian primes   a + bi':''}
 if(txt[0]!=big||txt[1]!=sub||txt[2]!=cap){txt=[big,sub,cap];txtDirty=1}
 if(txtDirty)drawText();
 flash*=Math.exp(-dt*5);fade=Math.min(1,fade+dt*1.5);
 const xa=run?.9:.75+.25*Math.sin(t*3),fo=run&&dbg<0?Math.min(1,(120-mt)/4):1;

 // the points, added up into the HDR target
 gl.bindFramebuffer(gl.FRAMEBUFFER,S.f);gl.viewport(0,0,S.w,S.h);gl.clearColor(0,0,0,1);gl.clear(gl.COLOR_BUFFER_BIT);
 gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE);
 let u;
 const common=(sa,rot,p,f)=>{gl.uniform1f(u.uSA,sa);gl.uniform1f(u.uRot,rot);gl.uniform1f(u.uAsp,W/H);gl.uniform1f(u.uPs,p);gl.uniform1f(u.uFd,f);
  gl.uniform1f(u.uRow,(row+.5)/HR);gl.uniform4fv(u.uK,K);gl.uniform1i(u.uS,0)};
 if(fP>0){u=use(PP);gl.bindVertexArray(VAP);common(SA,bp>24?(bp-24)*.06:0,ps,fP*bri);
  gl.uniform1i(u.uLA,LA);gl.uniform1i(u.uLB,LB);gl.uniform1f(u.uMix,mix);gl.uniform1f(u.uSB,SB);gl.uniform1f(u.uTau,run?tau:0);
  gl.uniform1f(u.uCmp,cmp);gl.uniform1f(u.uHue,ss(20,24,bp));gl.uniform1f(u.uSv,bp<8.5?1:0);
  gl.drawArrays(gl.POINTS,1,N)}
 if(fG>0){u=use(PG);gl.bindVertexArray(VAG);common(sG,(bp-48)*.03,Math.max(pxu*sG*.8,S.h*.0015),fG);gl.drawArrays(gl.POINTS,0,gpts.length/2)}
 gl.disable(gl.BLEND);
 // bloom down
 gl.activeTexture(gl.TEXTURE1);
 u=use(PD);gl.uniform1i(u.uC,1);
 let src=S;
 for(let i=0;i<B.length;i++){const d=B[i];gl.bindFramebuffer(gl.FRAMEBUFFER,d.f);gl.viewport(0,0,d.w,d.h);gl.bindTexture(gl.TEXTURE_2D,src.t);
  gl.uniform2f(u.uR,d.w,d.h);gl.uniform2f(u.uI,1/src.w,1/src.h);gl.uniform1f(u.uTh,i?0:1);gl.drawArrays(gl.TRIANGLES,0,3);src=d}
 // bloom up (additive)
 u=use(PU);gl.uniform1i(u.uC,1);gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE);
 for(let i=B.length-1;i>0;i--){const d=B[i-1];src=B[i];gl.bindFramebuffer(gl.FRAMEBUFFER,d.f);gl.viewport(0,0,d.w,d.h);gl.bindTexture(gl.TEXTURE_2D,src.t);
  gl.uniform2f(u.uR,d.w,d.h);gl.uniform2f(u.uI,1/src.w,1/src.h);gl.drawArrays(gl.TRIANGLES,0,3)}
 gl.disable(gl.BLEND);
 // composite
 u=use(PC);gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.viewport(0,0,W,H);
 gl.bindTexture(gl.TEXTURE_2D,S.t);gl.activeTexture(gl.TEXTURE2);gl.bindTexture(gl.TEXTURE_2D,B[0].t);
 gl.uniform1i(u.uC,1);gl.uniform1i(u.uB,2);gl.uniform1i(u.uX,3);gl.uniform1i(u.uS,0);
 gl.uniform2f(u.uR,W,H);gl.uniform1f(u.uT,t%100);gl.uniform1f(u.uF,fade*fo);gl.uniform1f(u.uXa,xa);gl.uniform1f(u.uRow,(row+.5)/HR);gl.uniform1f(u.uFl,flash);
 gl.drawArrays(gl.TRIANGLES,0,3);
};
requestAnimationFrame(frame);
// if this page was opened by a press (a host's start screen) audio may already be allowed: try now, else wait for a click
start().catch(()=>{});
// inspection hook
window.PRIMES={SYN,errs,get state(){return{bp:bpNow,frames,mode,A:[...A],K:[...K],t0,W,H,sw:S.w,sh:S.h,ng:gpts.length/2,np:PR.length,ctx:ctx&&ctx.state}},set seek(v){dbg=v}};
})();
</script>
</body>
</html>