<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>LAMINAR</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;position:absolute;left:0;top:50%;transform:translateY(-50%);width:100vw;height:min(100vh,56.25vw);cursor:pointer}
#h{position:fixed;top:0;right:0;box-sizing:border-box;max-width:100vw;min-width:64px;min-height:40px;padding:7px 10px;font:min(13px,3vw)/1.45 ui-monospace,Menlo,Consolas,monospace;color:#fff;text-align:right;white-space:pre-wrap;cursor:pointer;-webkit-user-select:none;user-select:none}</style>
</head>
<body>
<canvas id=c></canvas><div id=h></div>
<script>
/* LAMINAR - one sheet of water, and the equation that moves it.
The water is real: the Navier-Stokes equations for a flat flow that cannot be squeezed, solved as the picture is drawn -
a grid of 1024 by 512 cells, sixty steps a second (on a slow graphics card fewer and longer steps, and on the slowest a grid half
as fine: the card is timed before the start), the vorticity carried along and the stream function found by multigrid.
The surface stands where the pressure says it should, so every vortex is a dimple. Ink shows where the water has been.
Seven passages, one for each thing in the equation, in one unbroken take of a pond at dawn with a stone in it:
STILL nothing moves, and what falls stays where it fell
VISCOSITY the stone turns in thick water and turns back, and what was stirred in is stirred out again
PRESSURE a drop on every beat; each pushes all the others outwards, because water cannot be squeezed
INERTIA a stream: behind the stone two captive eddies, then a street of vortices in time with the slow drum
FORCE under water: one layer sliding over another, and warm ink rising through them
TURBULENCE a rake is drawn through; hundreds of small eddies merge into a few great slow ones
LAMINAR the stream again, in order; and a sheet of paper takes the ink off the water
Petals fall on each, and when its water comes to rest they are lying in the letters of its name. Nothing moves them but the
water: each passage is run through once beforehand, behind the ones before it, to learn where and when each petal has to fall.
The soundtrack is synthesised as it plays: 106 beats a minute, a bass drum with a hard kick, a snare, hi-hats, a low bass and
a fuzzed one, stabs, scratches, and a voice of saws that says each name. No assets, no dependencies.
Keys: F fullscreen; M more of the meter in the corner, or none (a tap on it does the same); C the sound's clock as it comes, or evened out. */
(()=>{
'use strict';
/* ---------------- synth (runs inside an AudioWorklet) ---------------- */
function SYN(sr,b0,b1,solo){
// The piece in bars, for the picture to read. SEC: where the seven passages begin. WORD: the bar in which the voice says the name
// of each passage - the drums stop for it, and the petals have just spelt it.
const BPM=106,NBAR=96,SEC=[0,8,24,40,56,72,88,96],WORD=[7,23,39,55,71,87,95];
if(!sr)return{BPM,NBAR,SEC,WORD};
// b0, b1: play from bar b0, and at bar b1 go round to b0 again. solo is for the test: only the parts whose bits are set are heard
// (1 kick, 2 snare and clap, 4 hats, 8 cowbell, congas, toms, 16 the low bass, 32 the fuzz bass, 64 stabs, 128 the voice, 256 scratches
// and crackle; 1024 no echo and no reverb; 2048 before the master).
b0=b0||0;b1=b1||NBAR;
const TAU=6.283185307179586,T=1/sr,S16=sr*15/BPM,SW=.1,mf=n=>440*2**((n-69)/12),dc=s=>Math.exp(-T/s),lag=s=>1-Math.exp(-T/s),lg32=s=>1-Math.exp(-32*T/s),
on=b=>solo&&!(solo&b)?0:1,MK=on(1),MS=on(2),MH=on(4),MC=on(8),MB=on(16),MF=on(32),MT=on(64),MV=on(128),MX=on(256),DRY=solo&1024,RAW=solo&2048;
let rs=19980714;const rnd=()=>{rs^=rs<<13;rs^=rs>>>17;rs^=rs<<5;return(rs>>>0)/2147483648-1};
// a filter that returns its low-pass and leaves its band-pass in s[2]; fs sets where it turns and how sharply. hp: what is left above
const F=()=>new Float64Array(7),
fs=(s,fc,k)=>{const g=Math.tan(Math.PI*Math.min(fc,sr*.45)*T);s[3]=1/(1+g*(g+k));s[4]=g*s[3];s[5]=g*s[4];s[6]=k;return s},
fl=(s,x)=>{const v3=x-s[1],v1=s[3]*s[0]+s[4]*v3,v2=s[1]+s[4]*s[0]+s[5]*v3;s[0]=2*v1-s[0];s[1]=2*v2-s[1];s[2]=v1;return v2},
hp=(s,x)=>{const y=fl(s,x);return x-s[6]*s[2]-y},
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};
// A hundred and six beats a minute, in G minor, in the manner of a late-nineties record made on old machines: a bass drum with
// a hard kick to it, a snare that cracks, hi-hats, all with a little swing in the sixteenths, a low bass that is a sine held long after each kick, a second bass an octave up
// that is all fuzz, chords of saws hit once and choked (the "orchestra"), a record scratched back and forth, a cowbell - and a
// voice made of a flat chord pushed through the shapes of a mouth, which says the name of each passage. Nothing sings above it.
// The low bass, two bars at a time: step, note, how many steps. R1 the plain one, R2 the busy one. Z1, Z2: the fuzz, an octave up.
const R1=[0,31,7,8,31,2,10,34,5, 16,36,7,24,34,2,26,31,5],R2=[0,31,3,3,31,3,8,34,2,10,36,2,11,36,3, 16,38,3,19,36,3,24,34,2,26,31,5],
Z1=[3,43,2,6,46,2, 19,48,2,22,46,2,30,43,2],Z2=[3,43,1,6,46,1,14,43,2, 19,50,1,22,48,1,27,46,1,30,43,2],
// what the voice says: for each sound the three resonances of the mouth, how much voice, how much hiss and where the hiss sits
PH={IY:[270,2290,3010,1,0,0],IH:[390,1990,2550,1,0,0],EH:[530,1840,2480,1,0,0],AE:[660,1720,2410,1,0,0],AA:[730,1090,2440,1,0,0],AO:[570,840,2410,1,0,0],
UH:[440,1020,2240,1,0,0],ER:[490,1350,1690,1,0,0],AX:[500,1500,2500,.9,0,0],L:[360,1300,2700,.7,0,0],R:[310,1060,1380,.7,0,0],M:[250,1100,2400,.5,0,0],N:[250,1700,2600,.5,0,0],
V:[300,1400,2400,.5,.15,3000],S:[400,1800,2600,0,.5,6000],SH:[400,1800,2600,0,.55,2800],F:[400,1800,2600,0,.3,4500],_:[400,1500,2500,0,0,0],
T:[400,1800,2600,0,.6,4200],K:[400,1500,2500,0,.6,2000],P:[400,1000,2400,0,.5,900],B:[300,1000,2400,.5,.2,700]},
// the seven names: sound, seconds
WD=[['S',.12,'_',.05,'T',.025,'IH',.17,'L',.24],
['V',.06,'IH',.1,'S',.09,'_',.04,'K',.03,'AA',.15,'S',.09,'IH',.08,'_',.04,'T',.025,'IY',.22],
['_',.02,'P',.02,'R',.07,'EH',.14,'SH',.13,'ER',.26],
['IH',.1,'N',.08,'ER',.19,'SH',.12,'AX',.24],
['F',.12,'AO',.2,'R',.12,'S',.18],
['_',.02,'T',.025,'ER',.17,'_',.04,'B',.02,'IY',.05,'UH',.1,'L',.08,'AX',.09,'N',.08,'S',.18],
['L',.09,'AE',.15,'M',.08,'IH',.09,'N',.08,'AA',.1,'R',.22]];
let pos=0,nx=0,st=b0*16-1,
kt=-1,kp=0,kv=1,kd=9,duck=0,dks=0,
se=0,sne=0,sp=0,sv=1,sst=0,ct=-1,cv=0,
he=0,hd=.99,hv=0,ce=0,cp1=0,cp2=0,
gt=-1,gf=300,gp=0,gv=1,gpn=0,tt=-1,tf=200,tp=0,tv=1,
bf=49,bp=0,be=0,bg=0,bv=1,bsl=0,
zf=98,zp=0,zq=0,zg=0,ze=0,zfe=0,zv=1,
ste=0,stv=1,
sct=-1,scd=1,scp=0,scm=0,
vw=null,vi=0,vt=0,va=0,vn=0,vat=0,vnt=0,vp1=0,vp2=0,vp3=0,vf1=400,vf2=1500,vf3=2500,vg1=400,vg2=1500,vg3=2500,vnf=3000,
ckl=0,ckt=0,cke=0,ckp=0,
uwl=Math.log(2e4),uwt=2e4,uwm=1,
rec=0,play=0,rc=0,pc=0,
di=0,ea=0,eb=0,cenv=0,cg=1;
const snb=fs(F(),1900,.8),snh=fs(F(),5200,1.1),clb=fs(F(),1250,.6),hf=fs(F(),6800,.9),cbf=fs(F(),900,.6),
zl1=fs(F(),600,.7),zl2=fs(F(),600,1.1),stl=fs(F(),2000,.9),sc1=fs(F(),900,.3),sc2=fs(F(),1800,.35),
v1=fs(F(),400,.11),v2=fs(F(),1500,.1),v3=fs(F(),2500,.1),vnb=fs(F(),3000,.5),ckf=fs(F(),3000,.6),
uwL=fs(F(),2e4,1.2),uwR=fs(F(),2e4,1.2),sf=new Float64Array(4),sph=new Float64Array(8),hq=[205.3,304.4,369.6,522.7,540,800].map(f=>f*1.46*T),hph=new Float64Array(6),hb=fs(F(),9500,.5);
const sdn=dc(.07),sdt=dc(.12),hdc=dc(.02),hdo=dc(.14),cdd=dc(.045),dkd=dc(.12),dka=lag(.003),bat=lag(.003),brl=dc(.05),
zat=lag(.004),zrl=dc(.035),zfd=dc(.09),std=dc(.11),vlf=lag(.022),vla=lag(.008),ckc=dc(.004),cat=lag(.012),crl=lag(.2),cu=lg32(.05);
// eight bars of the stabs and the fuzz, kept to be played backwards
const RL=Math.round(128*S16),RB=new Float32Array(RL*2);
// stereo echo (a dotted eighth) and a Freeverb-style reverb, kept short: a room
const DN=Math.round(S16*3),eL=new Float32Array(DN),eR=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*.7+cf[q]*.3;b[i]=x+cf[q]*.8;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 kick=(v,long)=>{kt=0;kp=0;kv=v;kd=long?4.5:9;duck=Math.max(duck,v)},
snare=v=>{se=1;sne=1;sp=0;sst=0;sv=v},
clap=v=>{ct=0;cv=v},
hat=(v,open)=>{he=1;hv=v;hd=open?hdo:hdc},
cow=v=>{ce=v},
conga=(f,v,pan)=>{gt=0;gf=f;gp=0;gv=v;gpn=pan},
tom=(f,v)=>{tt=0;tf=f;tp=0;tv=v},
bass=(n,len,v)=>{bf=mf(n);bg=Math.round(len*S16);bv=v;bsl=1;bp=0},
fuzz=(n,len,v)=>{zf=mf(n);zg=Math.round(len*S16);zv=v;zfe=1},
stab=(v,up)=>{const c=[43,46,50,55];for(let j=0;j<4;j++)sf[j]=mf(c[j]+(up||0));ste=1;stv=v},
scratch=(len,mode)=>{sct=0;scd=len*S16*T;scm=mode||0},
say=k=>{vw=WD[k];vi=-2;vt=0};
const riff=(R,c,f)=>{for(let i=0;i<R.length;i+=3)if(R[i]==c)f(R[i+1],R[i+2],1)};
const trig=()=>{
const s=st&15,bar=st>>4,two=bar&1,c=two*16+s,ev=!(s&1),q=!(s&3),wb=WORD.indexOf(bar),uw=bar>=56&&bar<61,
// how the drums go: 0 not at all, 1 a kick on the one, 2 the beat, 3 a kick on every beat, 4 the beat at its hardest
dm=wb>=0?0:bar<4?0:bar<8?1:bar<24?2:bar<40?3:bar<54?2:bar<55?1:bar<72?2:bar<84?4:bar<86?2:bar<87?1:bar<92?2:bar<93?1:0;
// the stabs and the fuzz of bars 8 to 16 are kept, and come back backwards through bars 16 to 24
if(st==128)rc=0;if(st==256)pc=0;rec=st>=128&&st<256;play=st>=256&&st<368;
uwt=uw?(bar<57?2e4*Math.pow(.016,s*s/256):320*2**((bar-57+s/16)*1.5)):bar<8?(bar<4?2e4:260*2**((bar-4+s/16)*1.6)):2e4; // under water through bar 56, and coming clear; and at the start the beat comes up out of the deep
ckt=bar<8||bar>=92?1:0;
// the name of the passage, on the first beat of its last bar, with one hit under it; and a run of the snare into the next
if(wb>=0){if(s==0){say(wb);kick(1,1);bass(31,10,1);stab(.8)}if(wb<6){if(s==12||s==14||s==15)snare(.55+.03*s);if(s==8)scratch(3,1)}}
// drums
if(dm==1){if(s==0)kick(.9,1);if(bar==54&&s==8)kick(.8,1)}
if(dm==2){if(s==0||s==8)kick(1);if(s==10)kick(.85);if(s==3&&two)kick(.6);if(s==4||s==12)snare(1);if(s==7&&!two||s==15&&two)snare(.3);if(ev)hat(q?.5:.36,s==14&&two);else if(s==13&&two||s==5&&(bar&3)==2)hat(.26)}
if(dm==3){if(q)kick(1);if(s==4||s==12){clap(1);if(bar>=32)snare(.6)}hat(ev?(q?.48:.36):.24,(s&3)==2&&bar>=28);if(bar>=28&&(s==0||s==3||s==6||s==8||s==11||s==14))cow(s==0||s==8?.9:.6)}
if(dm==4){if(s==0||s==8||s==10||s==3||s==11&&two||s==6&&!two)kick(s==3||s==6?.7:1);if(s==4||s==12)snare(1);if(s==7||s==15&&two)snare(.35);hat(ev?(q?.52:.38):.26,s==14||s==6&&two);if(bar==75||bar==79||bar==83){if(s>=12)tom([196,165,130.8,98][s-12],.9)}}
if((bar==15||bar==31||bar==47||bar==63)&&s>=13)snare(.4+.1*(s-13));
// the congas that are the drops: one to every beat while the rings are made, low and lower by turns; and the single drops of the still passages
if(bar>=24&&bar<32&&q)conga(s&4?300:392,1,s&4?.35:-.35);
if(bar==0&&s==0||bar==2&&s==8||bar==4&&s==4||bar==6&&s==8||bar==92&&s==8)conga(bar==0?330:262,1,rnd()*.4);
// scratches: before the turn-round a long one back; and wherever the record is being worried
if(bar==15&&s==8)scratch(7,2);
if((bar>=32&&bar<38||bar>=64&&bar<70||bar>=72&&bar<86)&&two&&(s==6||s==14))scratch(1.6,0);
if((bar==3||bar==6)&&s==12)scratch(3,0);
// the low bass, and the fuzz above it
if(dm==2||dm==3){if(bar>=8)riff(R1,c,bass)}else if(dm==4)riff(R2,c,bass);
if(dm==1&&s==0)bass(31,12,.9);
if(bar>=12&&bar<16||bar>=32&&bar<38||bar>=44&&bar<54||bar>=62&&bar<70)riff(Z1,c,fuzz);else if(bar>=72&&bar<86)riff(Z2,c,fuzz);
// stabs: one at the head of every four bars, and in the turbulence two in a row
if(dm>1&&s==0&&!(bar&3))stab(1);
if(dm==4&&two&&(s==0||s==3))stab(s?.7:1,s?-2:0);
if(bar==0&&s==0)stab(.5);
if(bar==1&&s==8)say(6); // and before anything else, the name of the whole
};
// the slow things, thirty-two samples at a time
const ctl=()=>{
uwl+=(Math.log(uwt)-uwl)*cu;const c=Math.exp(uwl);fs(uwL,c,1.2);fs(uwR,c,1.2);uwm=Math.min(1,Math.max(0,(c-7000)/6000));uwm*=uwm*(3-2*uwm);
const fz=zf*1.5+250+2600*zfe*zv;fs(zl1,fz,.7);fs(zl2,fz,1);
fs(stl,300+5200*ste*ste,.8);
vf1+=(vg1-vf1)*.32;vf2+=(vg2-vf2)*.32;vf3+=(vg3-vf3)*.32;fs(v1,vf1,.11);fs(v2,vf2,.1);fs(v3,vf3,.1);
ckl+=(ckt-ckl)*.002;
if(sct>=0){const u=sct/scd,a=Math.abs(Math.sin(TAU*sct*(scm==2?1.2:6)));fs(sc1,400+1300*a,.3);fs(sc2,800+2300*a,.35)}
};
const f=(L,R)=>{
for(let i=0;i<L.length;i++,pos++){
if(pos>=nx){st++;if(st>=b1*16)st=b0*16;nx+=S16*(st&1?1-SW:1+SW);trig()}
if(!(pos&31))ctl();
const n=rnd(),n2=rnd();let l=0,r=0,m=0,rv=0,dly=0,kp_=0;
// kick: a click, and a sine falling fast from it to its note, driven hard. Everything low leans back while it sounds
if(kt>=0){kp+=(50+150*Math.exp(-kt*44)+420*Math.exp(-kt*380))*T;
const y=Math.sin(TAU*kp)*Math.min(1,kt*3000)*Math.exp(-kt*kd)+n*Math.exp(-kt*600)*.3;m+=Math.tanh(y*kv*3.2)*.86*MK;if((kt+=T)>.8)kt=-1}
duck*=dkd;dks+=(duck-dks)*dka;
// snare: two notes of the skin, the wires, and its top; no room to speak of
if(se>.0005){sst+=T;sp+=(190+90*Math.exp(-sst*70))*T;sne*=sdn;se*=sdt;fl(snb,n);
const y=Math.tanh(((Math.sin(TAU*sp)+.5*Math.sin(TAU*sp*1.79))*sne*.8+(snb[2]*1.7+hp(snh,n)*.5)*se)*Math.min(1,sst*4000)*sv*1.7)*MS;l+=y*.8;r+=y*.75;rv+=y*.32}
// clap: three slaps and a tail
if(ct>=0){const e=(ct<.03?Math.exp(-(ct%.01)*300):Math.exp(-(ct-.03)*26))*cv;fl(clb,n2);const y=clb[2]*e*.8*MS;l+=y*.9;r+=y;rv+=y*.35;if((ct+=T)>.35)ct=-1}
// hats; and the cowbell: two squares that do not agree
if(he>.0005){he*=hd;let o=0;for(let j=0;j<6;j++){hph[j]+=hq[j];if(hph[j]>=1)hph[j]-=1;o+=hph[j]<.5?1:-1}
fl(hb,o*.3+n*.5);const y=hp(hf,hb[2]*1.4+n*.25)*he*hv*.46*MH;l+=y*.85;r+=y}
if(ce>.001){ce*=.99955;cp1+=540*T;cp2+=800*T;if(cp1>=1)cp1-=1;if(cp2>=1)cp2-=1;fl(cbf,(cp1<.5?1:-1)+(cp2<.5?1:-1));const y=cbf[2]*ce*ce*.16*MC;l+=y*.6;r+=y;rv+=y*.15}
// congas (the drops: each slides up a little as it dies, as a drop does) and toms
if(gt>=0){gp+=gf*(1+.25*gt*8/(1+gt*8)+.6*Math.exp(-gt*90))*T;const y=Math.sin(TAU*gp)*Math.exp(-gt*11)*Math.min(1,gt*2500)*.32*gv*MC;l+=y*(1-gpn);r+=y*(1+gpn);rv+=y*.45;dly+=y*.2;if((gt+=T)>.5)gt=-1}
if(tt>=0){tp+=tf*(1+.8*Math.exp(-tt*28))*T;const y=Math.sin(TAU*tp)*Math.exp(-tt*8)*Math.min(1,tt*2000)*.6*tv*MC,p=(tf-140)/160;l+=y*(1-p);r+=y*(1+p);rv+=y*.25;if((tt+=T)>.6)tt=-1}
// the low bass: a sine that drops a shade as it starts and is held, pushed into a soft ceiling so that small speakers get its overtones
if(bg>0||be>.0005){if(bg>0){bg--;be+=(bv-be)*bat}else be*=brl;bsl*=.9993;
bp+=bf*(1+.5*bsl*bsl*bsl)*T;if(bp>=1)bp-=1;const s=Math.sin(TAU*bp);m+=Math.tanh((s+.25*Math.sin(2*TAU*bp))*be*2.4)*.44*(1-.6*dks)*MB}
// the fuzz: two saws an octave above it, a filter that snaps shut, and far too much gain
let z=0;
if(zg>0||ze>.0005){if(zg>0){zg--;ze+=(zv-ze)*zat}else ze*=zrl;zfe*=zfd;
zp+=zf*T;if(zp>=1)zp-=1;zq+=zf*1.008*T;if(zq>=1)zq-=1;
z=Math.tanh(fl(zl2,fl(zl1,saw(zp,zf*T)+saw(zq,zf*T)))*6*ze)*.3*(1-.4*dks)*MF}
// stabs: four saws struck together and choked
let sb=0;
if(ste>.001){ste*=std;let o=0;for(let j=0;j<4;j++){sph[j]+=sf[j]*T;if(sph[j]>=1)sph[j]-=1;sph[j+4]+=sf[j]*1.007*T;if(sph[j+4]>=1)sph[j+4]-=1;o+=saw(sph[j],sf[j]*T)+saw(sph[j+4],sf[j]*T)}
sb=Math.tanh(fl(stl,o+n*ste*2)*.9)*ste*stv*.55*MT}
// those two are kept for eight bars and then given back backwards, over the beat
let xl=z+sb,xr=z*.8+sb;
if(rec){if(rc<RL){RB[rc*2]=xl;RB[rc*2+1]=xr;rc++}}
else if(play){const q=RL-1-pc++;if(q>=0){xl+=RB[q*2]*.9;xr+=RB[q*2+1]*.9}}
l+=xl;r+=xr;rv+=sb*.5+z*.1;dly+=sb*.25;
// a record pulled back and forth under the needle (mode 2: one long pull back)
if(sct>=0){const u=sct/scd,v=Math.sin(TAU*sct*(scm==2?1.2:6)),a=Math.abs(v);scp+=(scm==2?520*(1-u)+60:150+420*a)*T;if(scp>=1)scp-=1;const x=saw(scp,.01)*.6+n*.5;
fl(sc1,x);fl(sc2,x);const y=(sc1[2]+sc2[2])*Math.sqrt(scm==2?1-u*.5:a)*Math.sin(Math.PI*Math.min(1,u*8))*Math.min(1,(1-u)*12)*.3*MX;l+=y;r+=y*.7;rv+=y*.2;sct+=T;if(sct>=scd)sct=-1}
// the crackle of the record, where little else is going on
if(ckl>.01&&Math.abs(n2)<ckl*.00035){cke=1;ckp=rnd()}
if(cke>.001){cke*=ckc;fl(ckf,n);const y=ckf[2]*cke*.35*MX;l+=y*(1-ckp);r+=y*(1+ckp)}
// the voice: a flat chord of saws through three resonances that move from one shape of the mouth to the next, and hiss for
// the sounds that have no voice in them
if(vw){if(vt<=0){vi+=2;if(vi>=vw.length){vw=null;vat=vnt=0}else{const p=PH[vw[vi]];vg1=p[0];vg2=p[1];vg3=p[2];vat=p[3];vnt=p[4];if(p[5])fs(vnb,p[5],.5);vt=vw[vi+1]}}vt-=T}
va+=(vat-va)*vla;vn+=(vnt-vn)*vla;
if(va>.001||vn>.001){vp1+=98*T;if(vp1>=1)vp1-=1;vp2+=146.83*T;if(vp2>=1)vp2-=1;vp3+=196.6*T;if(vp3>=1)vp3-=1;
const x=saw(vp1,98*T)+.55*saw(vp2,147*T)+.75*saw(vp3,197*T);fl(v1,x);fl(v2,x);fl(v3,x);fl(vnb,n);
const y=Math.tanh((v1[2]+v2[2]*.8+v3[2]*.45)*va*.55+vnb[2]*vn*.7)*.62*MV;l+=y*.95;r+=y;rv+=y*.3;dly+=y*.3}
// echo
{const a=eL[di],b=eR[di];ea+=(b-ea)*.4;eb+=(a-eb)*.4;eL[di]=dly+ea*.35;eR[di]=eb*.35;if(++di==DN)di=0;if(!DRY){l+=a*.5;r+=b*.5;rv+=(a+b)*.1}}
// the room; under water everything is muffled and further off
if(!DRY){l+=verb(rv*.03+1e-18,cL,aL,0)*1.2;r+=verb(rv*.03+1e-18,cR,aR,1)*1.2}
let oL=m+l,oR=m+r;
{const a=fl(uwL,oL),b=fl(uwR,oR),k=.75+.25*uwm;oL=(a+(oL-a)*uwm)*k;oR=(b+(oR-b)*uwm)*k}
// the whole held together: when it is loud it is turned down a little and let up again slowly; then a soft ceiling
{const pk=Math.max(Math.abs(oL),Math.abs(oR));cenv+=(pk-cenv)*(pk>cenv?cat:crl);const t=cenv>.7?(.7+(cenv-.7)*.5)/cenv:1;cg+=(t-cg)*.002}
if(RAW){L[i]=oL;R[i]=oR}else{L[i]=Math.tanh(oL*cg*.9)*.98;R[i]=Math.tanh(oR*cg*.9)*.98}
}
return pos};
return f;
}
/* ---------------- the water: shaders ---------------- */
// The flow is flat and cannot be squeezed, so one number per cell holds all of it: the vorticity w, how fast the water there is
// turning. A step is: (1) find the stream function psi whose Laplacian is -w (multigrid); the velocity is the gradient of psi
// turned a quarter turn, plus the stream itself. (2) Where there is a stone, make the water move as the stone does: that leaves a
// sheet of vorticity on its skin, which is how a wake is born. Add what a breath on the surface, or warmth, does. (3) Carry w
// along the flow. (4) Let it spread: that is viscosity.
// Positions are in cells: cell (i,j) has its middle at (i+.5, j+.5). A step is 1/60 s (or 1/30, or 1/20, on a slow graphics card); speeds are cells per step.
// On the slowest cards the grid that is solved on has cells twice as big (uH = 2): everything is still laid out, and said, in the cells of the fine one.
const VS=`#version 300 es
void main(){gl_Position=vec4(vec2(gl_VertexID&1,gl_VertexID>>1)*4.-1.,0,1);}`;
const SIM=`#version 300 es
precision highp float;precision highp int;precision highp sampler2D;
out vec4 O;
#define NS 9
#define sat(x) clamp(x,0.,1.)
uniform int uWy,uNs; // uWy - across the stream: 0 the top edge joins the bottom, 1 banks (psi and w are zero on them). Along it, the ends always join.
uniform vec4 uSt[NS]; // stones (and the tines of a rake): where, how big round, and how fast each is turning
uniform vec2 uSv[NS]; // and how fast each is being moved through the water
uniform vec2 uUi; // the stream itself, the same everywhere
uniform vec3 uSp; // the far end, where whatever arrives is quietly removed: from x, to x, how much a step
uniform vec4 uSo; // a drop being poured in: where, and how much of it a step (as an area)
uniform float uH; // how many cells, as everything is laid out, to a cell of the grid being solved on
// a cell of a field. Along the stream the ends join (the textures are set to repeat that way); beyond a bank lies the last row, turned over.
float G(sampler2D s,ivec2 p){ivec2 n=textureSize(s,0);float g=1.;
if(p.y<0||p.y>=n.y){if(uWy>0)g=-1.;else p.y=(p.y+n.y)%n.y;}
return g*texture(s,(vec2(p)+.5)/vec2(n)).x;}
float chi(vec2 x){float m=0.;for(int i=0;i<uNs;i++)m=max(m,1.-smoothstep(-uH,uH,length(x-uSt[i].xy)-uSt[i].z));return m;} // 1 inside a stone
vec3 sol(vec2 x){vec3 r=vec3(0);for(int i=0;i<uNs;i++){vec2 q=x-uSt[i].xy;float m=1.-smoothstep(-uH,uH,length(q)-uSt[i].z);if(m>r.x)r=vec3(m,m*(uSv[i]+uSt[i].w*vec2(-q.y,q.x)));}return r;} // the same, and with it the stone's own velocity there
vec2 pour(vec2 x){vec2 q=x-uSo.xy;return uSo.z*.159155*q/(dot(q,q)+9.);} // what a drop does as it spreads: it pushes everything outwards, less with distance
float spg(float x){return uSp.z*smoothstep(uSp.x,uSp.y,x);}
vec4 cw(float f){return vec4(-f*(f-1.)*(f-2.)/6.,(f+1.)*(f-1.)*(f-2.)*.5,-(f+1.)*f*(f-2.)*.5,(f+1.)*f*(f-1.)/6.);} // the cubic through four points
`;
// --- multigrid for the Laplacian: smooth, pass what is left to a grid half as fine, bring its answer back.
// A pass costs more than the arithmetic in it, so each does two sweeps at once (with the pair of weights that damps the fine
// detail most), and the coarsest grid is not swept at all: it is multiplied by the inverse of its matrix, worked out beforehand.
const SMH=SIM+`uniform sampler2D uX,uB;uniform float uH2,uSg;const float W1=1.389,W2=.5617;
float dg(ivec2 q,ivec2 n){return uWy>0?4.+float(q.y==0)+float(q.y==n.y-1):4.;}`;
const SM2=SMH+`
float j1(ivec2 q){ivec2 n=textureSize(uX,0);float g=1.;if(uWy>0&&(q.y<0||q.y>=n.y)){q.y=clamp(q.y,0,n.y-1);g=-1.;} // one sweep, at a cell (or at its mirror image beyond a bank)
float c=G(uX,q);return g*(c+W1/dg(q,n)*(G(uX,q+ivec2(1,0))+G(uX,q-ivec2(1,0))+G(uX,q+ivec2(0,1))+G(uX,q-ivec2(0,1))-4.*c-uH2*uSg*G(uB,q)));}
void main(){ivec2 p=ivec2(gl_FragCoord.xy);float c=j1(p);
O=vec4(c+W2/dg(p,textureSize(uX,0))*(j1(p+ivec2(1,0))+j1(p-ivec2(1,0))+j1(p+ivec2(0,1))+j1(p-ivec2(0,1))-4.*c-uH2*uSg*texelFetch(uB,p,0).x));}`;
// the same two sweeps when the guess to start from is nothing
const SM0=SMH+`
float j1(ivec2 q){ivec2 n=textureSize(uB,0);float g=1.;if(uWy>0&&(q.y<0||q.y>=n.y)){q.y=clamp(q.y,0,n.y-1);g=-1.;}return -g*W1/dg(q,n)*uH2*uSg*G(uB,q);}
void main(){ivec2 p=ivec2(gl_FragCoord.xy);float c=j1(p);
O=vec4(c+W2/dg(p,textureSize(uB,0))*(j1(p+ivec2(1,0))+j1(p-ivec2(1,0))+j1(p+ivec2(0,1))+j1(p-ivec2(0,1))-4.*c-uH2*uSg*texelFetch(uB,p,0).x));}`;
const DIR=`#version 300 es
precision highp float;precision highp int;precision highp sampler2D;uniform sampler2D uM,uB;out vec4 O;
void main(){ivec2 p=ivec2(gl_FragCoord.xy),s=textureSize(uB,0);int r=p.y*s.x+p.x,n=s.x*s.y;float a=0.;
for(int c=0;c<n;c++)a+=texelFetch(uM,ivec2(c,r),0).x*texelFetch(uB,ivec2(c%s.x,c/s.x),0).x;
O=vec4(a);}`;
const RES=SIM+`uniform sampler2D uX,uB;uniform float uH2,uSg;
float res(ivec2 p){return uSg*texelFetch(uB,p,0).x-(G(uX,p+ivec2(1,0))+G(uX,p-ivec2(1,0))+G(uX,p+ivec2(0,1))+G(uX,p-ivec2(0,1))-4.*texelFetch(uX,p,0).x)/uH2;}
void main(){ivec2 p=ivec2(gl_FragCoord.xy)*2;O=vec4(.25*(res(p)+res(p+ivec2(1,0))+res(p+ivec2(0,1))+res(p+ivec2(1,1))));}`;
const PRO=SIM+`uniform sampler2D uX,uC;
void main(){ivec2 p=ivec2(gl_FragCoord.xy),q=p>>1,d=(p&1)*2-1;
O=vec4(texelFetch(uX,p,0).x+(9.*G(uC,q)+3.*(G(uC,q+ivec2(d.x,0))+G(uC,q+ivec2(0,d.y)))+G(uC,q+d))/16.);}`;
// --- the velocity, from psi (and from a drop, if one is spreading); inside a stone it is the stone's.
// Kept without the stream, which is added where it is read.
const VEL=SIM+`uniform sampler2D uP;
void main(){ivec2 p=ivec2(gl_FragCoord.xy);vec2 x=gl_FragCoord.xy*uH;
vec2 u=vec2(G(uP,p+ivec2(0,1))-G(uP,p-ivec2(0,1)),G(uP,p-ivec2(1,0))-G(uP,p+ivec2(1,0)))*(.5/uH);
vec3 k=sol(x);O=vec4((1.-k.x)*(u+uUi+pour(x))+k.yz-uUi,0,1);}`;
// the same for water so thick that it has no inertia at all, round a stone that is turning: this is known exactly
// (each ring of water turns at a rate that falls off as the square of its distance), so nothing has to be solved
const ROT=SIM+`void main(){vec2 q=gl_FragCoord.xy*uH-uSt[0].xy;float R=uSt[0].z;O=vec4(uSt[0].w*R*R/max(dot(q,q),R*R)*vec2(-q.y,q.x),0,1);}`;
// --- forces. The stones: inside them the water is made to move as the stone does (which is not at all, or a slight turning, or
// the stone being drawn through it); what that does to the vorticity is the curl of the change. A breath on the surface: the curl
// of a push. And under water, warmth: warm ink is lighter, and where it lies beside cooler water the water starts to turn.
const FRC=SIM+`uniform sampler2D uW,uP,uTm;uniform vec4 uGu;uniform vec2 uGd;uniform float uBy;
void main(){ivec2 p=ivec2(gl_FragCoord.xy);vec2 x=gl_FragCoord.xy*uH;float w=texelFetch(uW,p,0).x,h=.5*uH;
vec3 e=sol(x+vec2(h,0)),v=sol(x-vec2(h,0)),n=sol(x+vec2(0,h)),s=sol(x-vec2(0,h));
if(e.x+v.x+n.x+s.x>0.){float c=texelFetch(uP,p,0).x;
w+=((e.x*(G(uP,p+ivec2(1,0))-c)-v.x*(c-G(uP,p-ivec2(1,0)))+n.x*(G(uP,p+ivec2(0,1))-c)-s.x*(c-G(uP,p-ivec2(0,1))))/uH+uUi.x*(n.x-s.x)-uUi.y*(e.x-v.x)+e.z-v.z-n.y+s.y)/uH;}
if(uGu.z!=0.){vec2 q=(x-uGu.xy)/uGu.w;w+=uGu.z*2./uGu.w*exp(-dot(q,q))*(uGd.x*q.y-uGd.y*q.x);}
if(uBy!=0.)w+=uBy*.5/uH*(G(uTm,ivec2(p.x+1,p.y))-G(uTm,ivec2(p.x-1,p.y)));
O=vec4(w);}`;
// --- carried along: look back along the flow to where this water was a step ago, and read the vorticity there
const ADV=SIM+`uniform sampler2D uW,uU;uniform float uDt,uDr;
vec2 vel(vec2 x){return texture(uU,x/(vec2(textureSize(uU,0))*uH)).xy+uUi;}
float cub(sampler2D s,vec2 x){x-=.5;vec2 f=fract(x);ivec2 p=ivec2(floor(x));vec4 wx=cw(f.x),wy=cw(f.y);float r=0.,lo=1e9,hi=-1e9;
for(int j=0;j<4;j++){float a=0.;for(int i=0;i<4;i++){float v=G(s,p+ivec2(i-1,j-1));a+=wx[i]*v;if(i>0&&i<3&&j>0&&j<3){lo=min(lo,v);hi=max(hi,v);}}r+=wy[j]*a;}
return clamp(r,lo,hi);} // never beyond the four values round it: no ringing
void main(){vec2 x=gl_FragCoord.xy*uH,n=vec2(textureSize(uW,0));x=(x-uDt*vel(x-.5*uDt*vel(x)))/uH;
if(uWy>0)x.y=clamp(x.y,.5,n.y-.5);
O=vec4(cub(uW,x)*(1.-spg(gl_FragCoord.x*uH))*(1.-uDr));}`; // (uDr: the drag of the bed, which is what brings a stream to rest)
// --- warmth: carried along like everything else, fed from warm places on the bed (uHt: where, how wide, how much), and slowly lost (uTf)
const TMP=SIM+`uniform sampler2D uTm,uU;uniform vec4 uHt[4];uniform int uNh;uniform float uTf;
vec2 vel(vec2 x){return texture(uU,x/(vec2(textureSize(uU,0))*uH)).xy+uUi;}
float gt(ivec2 p){return texture(uTm,(vec2(p)+.5)/vec2(textureSize(uTm,0))).x;}
void main(){vec2 x=gl_FragCoord.xy*uH,n=vec2(textureSize(uTm,0));x=(x-vel(x-.5*vel(x)))/uH;x.y=clamp(x.y,.5,n.y-.5);x-=.5;vec2 f=fract(x);ivec2 p=ivec2(floor(x));vec4 wx=cw(f.x),wy=cw(f.y);float r=0.,lo=1e9,hi=-1e9;
for(int j=0;j<4;j++){float a=0.;for(int i=0;i<4;i++){float v=gt(p+ivec2(i-1,j-1));a+=wx[i]*v;if(i>0&&i<3&&j>0&&j<3){lo=min(lo,v);hi=max(hi,v);}}r+=wy[j]*a;}
r=clamp(r,lo,hi)*uTf;
for(int i=0;i<uNh;i++){vec2 q=(gl_FragCoord.xy*uH-uHt[i].xy)/uHt[i].z;r+=uHt[i].w*exp(-dot(q,q));}
O=vec4(r);}`;
// --- viscosity: one pass of spreading, along the stream and across it at once (stable up to uK = .5)
const DIF=SIM+`uniform sampler2D uW;uniform float uK;
void main(){ivec2 p=ivec2(gl_FragCoord.xy);float a=1.-2.*uK,r=0.;
for(int j=-1;j<2;j++)for(int i=-1;i<2;i++)r+=(i==0?a:uK)*(j==0?a:uK)*G(uW,p+ivec2(i,j));
O=vec4(r);}`;
// For water grown very thick the spreading is done on a coarser grid (what is being spread so far is smooth anyway): averaged down, each
// cell from four; spread there, in far fewer passes; and brought back, each cell from the four coarse ones nearest it.
const DWN=SIM+`uniform sampler2D uW;
void main(){ivec2 p=ivec2(gl_FragCoord.xy)*2;O=vec4(.25*(texelFetch(uW,p,0).x+texelFetch(uW,p+ivec2(1,0),0).x+texelFetch(uW,p+ivec2(0,1),0).x+texelFetch(uW,p+ivec2(1,1),0).x));}`;
const UPS=SIM+`uniform sampler2D uC;
void main(){ivec2 p=ivec2(gl_FragCoord.xy),q=p>>1,d=(p&1)*2-1;O=vec4((9.*G(uC,q)+3.*(G(uC,q+ivec2(d.x,0))+G(uC,q+ivec2(0,d.y)))+G(uC,q+d))/16.);}`;
// --- a sheet of vorticity to begin from: water above sliding over water below (uA: how strong, how high up, how thick, how uneven)
const INI=SIM+`uniform vec4 uA;
void main(){vec2 x=gl_FragCoord.xy*uH;float e=(x.y-uA.y)/uA.z;
O=vec4(-uA.x*exp(-e*e)*(1.+uA.w*(sin(x.x*.0491+1.)+sin(x.x*.0859+2.)+sin(x.x*.1227+4.)+sin(x.x*.0245+5.))));}`;
// --- pressure, which is what lifts and dimples the surface. Its Laplacian is twice the determinant of the second derivatives of psi
// (positive where the water turns, negative where it is strained), plus what the stones do by stopping the flow.
const PRH=SIM+`uniform sampler2D uP,uU;
float rh(ivec2 p){vec2 x=vec2(p)+.5,n=vec2(textureSize(uU,0));
float c=texelFetch(uP,p,0).x,xx=G(uP,p+ivec2(1,0))+G(uP,p-ivec2(1,0))-2.*c,yy=G(uP,p+ivec2(0,1))+G(uP,p-ivec2(0,1))-2.*c,
xy=(G(uP,p+ivec2(1,1))-G(uP,p+ivec2(-1,1))-G(uP,p+ivec2(1,-1))+G(uP,p+ivec2(-1,-1)))*.25;
float dv=(texture(uU,(x+vec2(1,0))/n).x-texture(uU,(x-vec2(1,0))/n).x+texture(uU,(x+vec2(0,1))/n).y-texture(uU,(x-vec2(0,1))/n).y)*.5;
return 2.*(xx*yy-xy*xy)/(uH*uH*uH*uH)+dv/uH;}
void main(){ivec2 p=ivec2(gl_FragCoord.xy)*2;O=vec4(.25*(rh(p)+rh(p+ivec2(1,0))+rh(p+ivec2(0,1))+rh(p+ivec2(1,1))));}`; // (it is solved on a grid half as fine: it is smooth)
// what the picture reads: the slope of the pressure, the pressure, and its curvature
const SRF=SIM+`uniform sampler2D uP,uB;
void main(){ivec2 p=ivec2(gl_FragCoord.xy);
O=vec4((G(uP,p+ivec2(1,0))-G(uP,p-ivec2(1,0)))*(.25/uH),(G(uP,p+ivec2(0,1))-G(uP,p-ivec2(0,1)))*(.25/uH),texelFetch(uP,p,0).x,texelFetch(uB,p,0).x);}`;
// between one finding of the surface and the next: what the picture is shown meanwhile
const MIX=`#version 300 es
precision highp float;precision highp sampler2D;uniform sampler2D uA,uB;uniform float uF;out vec4 O;
void main(){ivec2 p=ivec2(gl_FragCoord.xy);O=mix(texelFetch(uA,p,0),texelFetch(uB,p,0),uF);}`;
// --- ink. Four of them, a channel each. It is carried exactly as the vorticity is, on a finer grid (uDs cells of ink to a cell of water).
// Where it comes from: threads across the upstream end, each with a bead on it for every beat; the pores of the stone; the tines
// of the rake, each its own colour; a drop as it spreads (ink, or clear water); warm places on the bed; a line laid along a level.
const DYE=SIM+`uniform sampler2D uD,uU;uniform float uDt,uDs,uIn,uLs,uBt,uBs,uFd,uSi,uSj,uK6;uniform vec4 uTh,uSc[NS],uDp,uDc,uHt[4],uHc[4];uniform vec3 uLn;uniform int uNh;
vec2 vel(vec2 x){return texture(uU,x/(vec2(textureSize(uU,0))*uH)).xy+uUi;}
vec4 gd(ivec2 p){ivec2 n=textureSize(uD,0);if(uWy==0)p.y=(p.y+n.y)%n.y;return texture(uD,(vec2(p)+.5)/vec2(n));}
vec4 cub(vec2 x){x-=.5;vec2 f=fract(x);ivec2 p=ivec2(floor(x));vec4 wx=cw(f.x),wy=cw(f.y),r=vec4(0),lo=vec4(1e9),hi=vec4(-1e9);
for(int j=0;j<4;j++){vec4 a=vec4(0);for(int i=0;i<4;i++){vec4 v=gd(p+ivec2(i-1,j-1));a+=wx[i]*v;if(i>0&&i<3&&j>0&&j<3){lo=min(lo,v);hi=max(hi,v);}}r+=wy[j]*a;}
return clamp(r,lo,hi);}
void main(){
vec2 g=gl_FragCoord.xy/uDs,b=g-uDt*vel(g-.5*uDt*vel(g));vec4 d;
if(uIn>0.&&b.x<uIn&&g.x>=uIn){ // this water has just come in: it carries the threads
float k=b.y/uLs,i=floor(k),f=(k-i-.5)*uLs,a=exp(-f*f*1.6),h=fract(i*.381966);
float bt=uBt-(g.x-uIn)/max(uUi.x,.01)*uBs,bead=.5+.5*exp(-fract(bt)*5.);
float ny=float(textureSize(uU,0).y)*uH,e=(b.y-.5*ny)/(.3*ny);a*=exp(-e*e)*smoothstep(0.,.12,b.y/ny)*(1.-smoothstep(.88,1.,b.y/ny)); // brightest in mid-stream, dying away towards the banks
d=a*bead*uTh*vec4(h<.7?1.:0.,0,0,h<.7?0.:1.);
}else d=cub(b*uDs);
d*=uFd*(1.-spg(g.x))*(1.-chi(g));
for(int i=0;i<uNs;i++){vec2 q=g-uSt[i].xy;float e=length(q)-uSt[i].z,s=exp(-e*e*.4)*step(-1.5,e),n=uDt*uK6; // (n: how many sixtieths of a second this is for)
if(uSt[i].z>12.){s=1.-pow(1.-sat(s*uSi*pow(.5+.5*cos(atan(q.y,q.x)*9.),3.)*(.35+.65*exp(-fract(uBt)*3.))),n); // the stone: gold from one flank, rose from the other, a pulse to each beat
d.y=mix(d.y,max(d.y,1.),s*smoothstep(-2.,2.,q.y));d.z=mix(d.z,max(d.z,1.),s*(1.-smoothstep(-2.,2.,q.y)));}
else d=mix(d,max(d,uSc[i]),1.-pow(1.-sat(s*uSj),n));} // a tine of the rake
if(uDp.z>0.)d=mix(d,uDc,1.-smoothstep(uDp.z-1.5,uDp.z,length(g-uDp.xy)));
for(int i=0;i<uNh;i++){vec2 q=(g-uHt[i].xy)/uHt[i].z;d+=uHc[i]*uHt[i].w*uDt*exp(-dot(q,q));}
if(uLn.z>0.){float e=(g.y-uLn.x)/uLn.y;d.w+=uLn.z*exp(-e*e);}
O=max(d,0.);}`;
// --- rings on the surface: the plain equation for a wave, on a grid half as fine. Whatever lands gives the water a push.
const RPL=`#version 300 es
precision highp float;precision highp int;precision highp sampler2D;uniform sampler2D uH;uniform vec4 uDp[8];uniform int uNd;uniform float uRc;uniform vec3 uRw;out vec4 O;
// (uRc: cells of the layout to a cell of this grid. uRw: the square of how far a wave goes in a step, in cells of this grid; and how much of its speed, and of its height, is left after a step)
vec2 T(ivec2 p){return texelFetch(uH,clamp(p,ivec2(0),textureSize(uH,0)-1),0).xy;}
void main(){ivec2 p=ivec2(gl_FragCoord.xy);vec2 c=T(p),n=vec2(textureSize(uH,0)),e=min(gl_FragCoord.xy,n-gl_FragCoord.xy);
float v=(c.y+uRw.x*(T(p+ivec2(1,0)).x+T(p-ivec2(1,0)).x+T(p+ivec2(0,1)).x+T(p-ivec2(0,1)).x-4.*c.x))*uRw.y;
for(int i=0;i<uNd;i++){vec2 q=(gl_FragCoord.xy*uRc-uDp[i].xy)/uDp[i].w;v-=uDp[i].z*exp(-dot(q,q));}
O=vec4((c.x+v)*uRw.z,v,0,1)*smoothstep(0.,24./uRc,min(e.x,e.y));}`;
const RSF=`#version 300 es
precision highp float;precision highp int;precision highp sampler2D;uniform sampler2D uH;uniform float uRc;out vec4 O;
float T(ivec2 p){return texelFetch(uH,clamp(p,ivec2(0),textureSize(uH,0)-1),0).x;}
void main(){ivec2 p=ivec2(gl_FragCoord.xy);O=vec4((T(p+ivec2(1,0))-T(p-ivec2(1,0)))*.5/uRc,(T(p+ivec2(0,1))-T(p-ivec2(0,1)))*.5/uRc,T(p),1);}`;
// --- a plain look at a field, for building this
const DBG=`#version 300 es
precision highp float;precision highp sampler2D;uniform sampler2D uD,uW,uS;uniform vec2 uR;uniform int uMd;uniform float uSc;out vec4 O;
void main(){vec2 v=gl_FragCoord.xy/uR;vec3 c;
if(uMd==1){vec4 d=texture(uD,v);c=d.r*vec3(.1,1,.7)+d.g*vec3(1,.75,.25)+d.b*vec3(1,.3,.5)+d.a*vec3(.6,.8,1);}
else if(uMd==2){float w=texelFetch(uW,ivec2(v*vec2(textureSize(uW,0))),0).x*uSc;c=vec3(max(w,0.),abs(w)*.3,max(-w,0.));}
else{vec4 s=texture(uS,v);c=vec3(.5+s.z*uSc,.5+s.x*uSc*8.,.5+s.w*uSc*8.);}
O=vec4(pow(c,vec3(.4545)),1);}`;
/* ---------------- the picture: a stream at dawn ---------------- */
// The water lies in the plane y=0. The world is 18 long (x, the way the stream runs) and 9 wide (z); a cell of the solver is CELL of it.
// What is drawn: the sky in the surface, and through the surface the ink (just under it) and the bed (deeper, so the two slide
// against each other as the camera moves). The surface is not flat: its height is the pressure the solver found, so it stands up
// in front of a stone, drops along its flanks, and every vortex is a dimple - and a dimple spreads the light that goes through it,
// which is why each one lays a dark disc with a bright rim on the bed. Rings from whatever has fallen in are added to it.
const NOI=`
const float CELL=.017578125;
const vec3 DAWN=vec3(-.9285,0.,.3714); // the way to where the sun will come up: upstream, and a little to the far bank
const vec3 JADE=vec3(.06,1.,.6)*1.7,GOLD=vec3(1.,.7,.18)*1.9,ROSE=vec3(1.,.2,.48)*1.9,PALE=vec3(.5,.78,1.)*1.3; // the four inks, as they glow
float h21(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
float h31(vec3 p){return fract(sin(dot(p,vec3(127.1,311.7,74.7)))*43758.5453);}
float n2(vec2 x){vec2 i=floor(x),f=fract(x);f=f*f*(3.-2.*f);return mix(mix(h21(i),h21(i+vec2(1,0)),f.x),mix(h21(i+vec2(0,1)),h21(i+vec2(1,1)),f.x),f.y);}
float fb2(vec2 p){return .5*n2(p)+.25*n2(p*2.03+7.1)+.125*n2(p*4.1+3.3)+.0625*n2(p*8.3+1.7);}
float ns(vec3 x){vec3 i=floor(x),f=fract(x);f=f*f*(3.-2.*f);
return mix(mix(mix(h31(i),h31(i+vec3(1,0,0)),f.x),mix(h31(i+vec3(0,1,0)),h31(i+vec3(1,1,0)),f.x),f.y),
mix(mix(h31(i+vec3(0,0,1)),h31(i+vec3(1,0,1)),f.x),mix(h31(i+vec3(0,1,1)),h31(i+vec3(1,1,1)),f.x),f.y),f.z);}
float fb3(vec3 p){return .5*ns(p)+.25*ns(p*2.03+7.1)+.125*ns(p*4.1+3.3);}
// what a mixture of the inks looks like: their average colour, kept from going grey where opposites meet, and brighter the more ink there is
vec3 inkc(vec4 d){float t=d.r+d.g+d.b+d.a;vec3 c=(d.r*JADE+d.g*GOLD+d.b*ROSE+d.a*PALE)/(t+.03);return max(mix(vec3(dot(c,vec3(.3,.5,.2))),c,1.5),0.)*(1.-exp(-t*1.25))*t*t/(t*t+.005)*1.3;} // (and the thinnest veil of it is not shown at all)
// the bed: pebbles. For each point the nearest one - how far to its middle, and a number of its own
vec2 peb(vec2 x){vec2 i=floor(x),f=x-i;float d=9.,id=0.;
for(int b=-1;b<2;b++)for(int a=-1;a<2;a++){vec2 o=vec2(a,b),h=vec2(h21(i+o),h21(i+o+7.3)),r=o+.2+.6*h-f;float e=dot(r,r);if(e<d){d=e;id=h.x+h.y;}}
return vec2(sqrt(d),fract(id*3.7));}
// a smooth read of a texture (cubic B-spline, as four reads between texels)
vec4 bsp(sampler2D s,vec2 x){vec2 n=vec2(textureSize(s,0));x-=.5;vec2 i=floor(x),f=x-i,
w0=(1.-f)*(1.-f)*(1.-f)/6.,w1=(4.-6.*f*f+3.*f*f*f)/6.,w3=f*f*f/6.,g0=w0+w1,g1=1.-g0,a=(i-.5+w1/g0)/n,b=(i+1.5+w3/g1)/n;
return g0.y*(g0.x*texture(s,a)+g1.x*texture(s,vec2(b.x,a.y)))+g1.y*(g0.x*texture(s,vec2(a.x,b.y))+g1.x*texture(s,b));}
`;
const HDR=`#version 300 es
precision highp float;precision highp int;precision highp sampler2D;
#define sat(x) clamp(x,0.,1.)
#define NS 9
`;
// The bed, drawn once before the start into a sheet that is then only read: every point of the picture used to work out its pebbles afresh
// in every frame, which was a third of the picture's cost. The sheet shows a piece of bed BEDP wide and repeats, so the pebbles are
// laid out to repeat with it. (Kept six times brighter than it is, to use the sheet's whole range.)
const BEDP=8,BED=HDR+`uniform vec2 uR;out vec4 O;
${NOI}
float n2r(vec2 x,float m){vec2 i=floor(x),f=fract(x),a=mod(i,m),b=mod(i+1.,m);f=f*f*(3.-2.*f);return mix(mix(h21(a),h21(vec2(b.x,a.y)),f.x),mix(h21(vec2(a.x,b.y)),h21(b),f.x),f.y);}
vec2 pebr(vec2 x,float m){vec2 i=floor(x),f=x-i;float d=9.,id=0.;
for(int b=-1;b<2;b++)for(int a=-1;a<2;a++){vec2 o=vec2(a,b),c=mod(i+o,m),h=vec2(h21(c),h21(c+7.3)),r=o+.2+.6*h-f;float e=dot(r,r);if(e<d){d=e;id=h.x+h.y;}}
return vec2(sqrt(d),fract(id*3.7));}
void main(){const float P=${BEDP}.;vec2 xb=gl_FragCoord.xy/uR*P;
// stones of all sizes with gravel between them, on dark sand
vec2 pw=xb+(vec2(n2r(xb*2.25,2.25*P),n2r(xb*2.25+5.,2.25*P))-.5)*.3,pq=pebr(pw*7.,7.*P),pg=pebr(pw*17.+3.,17.*P);
float r1=pq.x/(.28+.34*pq.y),r2=pg.x/(.3+.25*pg.y);
vec3 bed=mix(vec3(.014,.022,.042),mix(vec3(.04,.05,.085),vec3(.085,.08,.075),fract(pg.y*5.3))*(1.1-.5*r2*r2),(1.-smoothstep(.7,1.,r2))*.8);
bed=mix(bed,mix(vec3(.04,.055,.095),vec3(.115,.105,.095),fract(pq.y*5.3))*(1.2-.6*r1*r1),1.-smoothstep(.8,1.,r1));
O=vec4(bed*6.,1);}`;
const POND=HDR+`uniform sampler2D uD,uSf,uU,uRs,uBed;uniform vec2 uR,uGn,uUi;uniform float uT,uFv,uEx,uHs,uInk,uBd,uUw,uMist,uTau,uRk,uSa,uAt,uPy;uniform vec3 uCo;uniform mat3 uCm;
uniform vec4 uSt[NS],uMk,uAb[3];uniform int uNs,uNb;uniform float uMy;
out vec4 O;
${NOI}
// the sky before sunrise: orange along the horizon towards the dawn, rose above that, deep blue overhead, a few thin clouds lit from under
vec3 sky(vec3 d){
float h=sat(d.y),s=max(dot(normalize(vec3(d.x,0.,d.z)+1e-5),DAWN),0.);
vec3 c=mix(mix(vec3(.5,.24,.22),vec3(.27,.15,.31),smoothstep(0.,.11,h)),vec3(.02,.04,.125),smoothstep(.03,.55,h));
c+=vec3(1.,.4,.1)*pow(s,6.)*exp(-h*10.)*.55+vec3(.7,.24,.2)*s*s*exp(-h*3.2)*.3;
float cl=fb2(d.xz/(h+.12)*.9+vec2(uT*.006,3.));cl=smoothstep(.48,.8,cl)*smoothstep(0.,.07,h);
return mix(c,mix(vec3(.14,.09,.18),vec3(1.1,.42,.24),pow(s,3.)*exp(-h*4.)),cl*.6);}
vec2 grd(vec2 xz){return xz/CELL+.5*uGn;} // from the world to the solver's cells
float msk(vec2 g){return smoothstep(uMk.x,uMk.y,g.x)*(1.-smoothstep(uMk.z,uMk.w,g.x))*smoothstep(0.,uMy,g.y)*(1.-smoothstep(uGn.y-uMy,uGn.y,g.y));} // (ink is not shown where the stream comes in and goes out)
// the stone: a low dome of rough rock, standing in the water. Its waterline is the circle the solver knows. (uSa: how far it has been turned)
vec3 sc(){vec2 c=(uSt[0].xy-.5*uGn)*CELL;return vec3(c.x,-.25*uSt[0].z*CELL,c.y);}
float sdS(vec3 p){float R=uSt[0].z*CELL,c=cos(uSa),s=sin(uSa);vec3 q=(p-sc())/R;q.xz=mat2(c,-s,s,c)*q.xz;
return (length(q*vec3(1.,1.25,1.))-1.048-.1*(fb3(q*2.1)-.45)-.018*ns(q*11.))*R*.72;}
float hitS(vec3 ro,vec3 rd,float tm){if(uNb<1)return -1.;float R=uSt[0].z*CELL;vec3 oc=ro-sc();float b=dot(oc,rd),h=b*b-dot(oc,oc)+1.5*R*R;if(h<0.)return -1.;
h=sqrt(h);float t=max(-b-h,0.);tm=min(tm,-b+h);
for(int k=0;k<56;k++){float d=sdS(ro+rd*t);if(d<.0012*t+.0004)return t;t+=d;if(t>tm)break;}
return -1.;}
vec3 stone(vec3 p,vec3 rd){float R=uSt[0].z*CELL,c=cos(uSa),s=sin(uSa);vec2 e=vec2(.004*R,0);
vec3 n=normalize(vec3(sdS(p+e.xyy)-sdS(p-e.xyy),sdS(p+e.yxy)-sdS(p-e.yxy),sdS(p+e.yyx)-sdS(p-e.yyx))),q=(p-sc())/R;q.xz=mat2(c,-s,s,c)*q.xz;
float tx=fb3(q*5.+2.),wet=1.-smoothstep(.03*R,.2*R,p.y),moss=smoothstep(.5,.85,n.y)*smoothstep(.42,.62,fb3(q*3.3+9.))*smoothstep(.12*R,.3*R,p.y);
vec3 alb=mix(vec3(.04,.038,.04),vec3(.13,.115,.1),tx*tx)*mix(1.,.4,wet);alb=mix(alb,vec3(.035,.07,.02),moss*.85);
vec3 r=reflect(rd,n);float f=.025+.6*pow(1.-max(dot(-rd,n),0.),4.);
vec3 col=alb*(vec3(.1,.14,.3)*(.4+.6*n.y)+vec3(1.3,.55,.28)*pow(max(dot(n,normalize(DAWN+vec3(0,.3,0))),0.),1.5)+vec3(.02,.03,.06))*1.6
+sky(vec3(r.x,abs(r.y)+.02,r.z))*f*mix(.18,.9,wet)*(1.-moss*.8);
return col*smoothstep(-.02*R,.06*R,p.y);} // dark where it goes under
// the tines of the rake: canes of bamboo, standing in the water (uPy: how far they have been lifted out of it)
float hitP(vec3 ro,vec3 rd,int i,float tm){vec2 c=(uSt[i].xy-.5*uGn)*CELL,o=ro.xz-c,d=rd.xz;float r=uSt[i].z*CELL,a=dot(d,d),b=dot(o,d),h=b*b-a*(dot(o,o)-r*r);if(h<0.||a<1e-7)return -1.;
float t=(-b-sqrt(h))/a,y=ro.y+rd.y*t;return t>0.&&t<tm&&y>uPy&&y<uPy+2.3?t:-1.;}
float hitB(vec3 ro,vec3 rd,float tm){if(uNs<=uNb)return -1.;vec2 c=vec2((uSt[uNb].x-.5*uGn.x)*CELL,uPy+2.3),o=ro.xy-c,d=rd.xy;float a=dot(d,d),b=dot(o,d),h=b*b-a*(dot(o,o)-.012);if(h<0.||a<1e-7)return -1.; // the bar across their tops
float t=(-b-sqrt(h))/a,z=ro.z+rd.z*t;return t>0.&&t<tm&&z>(uSt[uNb].y-.5*uGn.y)*CELL-.25&&z<(uSt[uNs-1].y-.5*uGn.y)*CELL+.25?t:-1.;}
vec3 post(vec3 p,vec3 rd,int i){vec2 c=(uSt[i].xy-.5*uGn)*CELL;vec3 n=normalize(vec3(p.x-c.x,0.,p.z-c.y));float y=p.y-uPy,jn=smoothstep(.46,.5,abs(fract(y*1.7+float(i)*.37)-.5));
vec3 alb=mix(vec3(.2,.22,.08),vec3(.36,.31,.13),fb2(vec2(atan(n.z,n.x)*2.,y*.7+float(i))))*(1.-.55*jn)*mix(.4,1.,smoothstep(0.,.3,y));
return alb*(vec3(.1,.14,.3)*.7+vec3(1.3,.55,.28)*max(dot(n,DAWN),0.)*.9+vec3(.03))*1.5;}
vec3 water(vec3 X,vec3 rd,float dist){
vec2 g=grd(X.xz);float m=msk(g);vec4 sf=bsp(uSf,g*vec2(textureSize(uSf,0))/uGn)*m;
vec2 sl=sf.xy*uHs/CELL;sl/=1.+length(sl)*1.6; // the slope of the surface (kept from standing up like a wall next to a stone)
sl+=bsp(uRs,g*vec2(textureSize(uRs,0))/uGn).xy*uRk*smoothstep(0.,150.,g.x)*(1.-smoothstep(uGn.x-150.,uGn.x,g.x))*smoothstep(0.,110.,g.y)*(1.-smoothstep(uGn.y-110.,uGn.y,g.y)); // rings (dying away towards the edge of what is solved, so that no edge shows)
// what a light air does to it: small waves going downstream with the water, in patches, and smoothed away where they are finer than a pixel
float px=dist/(uFv*uR.y*.5)/max(-rd.y,.08),gu=.35+.65*n2(X.xz*.35+vec2(uT*.05,1.));vec2 w=X.xz-vec2(uUw*uT,0.);
sl+=gu*(vec2(.8,.6)*cos(dot(w,vec2(.8,.6))*23.+uT*2.1)*.011*(1.-smoothstep(.05,.2,px))
+vec2(-.5,.87)*cos(dot(w,vec2(-.5,.87))*37.-uT*2.9)*.008*(1.-smoothstep(.03,.12,px))
+vec2(.95,-.3)*cos(dot(w,vec2(.95,-.3))*61.+uT*3.7)*.006*(1.-smoothstep(.02,.08,px))
+vec2(.3,.95)*cos(dot(w,vec2(.3,.95))*9.+uT*1.1)*.012);
vec3 n=normalize(vec3(-sl.x,1.,-sl.y));
float c=max(dot(-rd,n),0.),F=.02+.98*pow(1.-c,5.);
vec3 R=reflect(rd,n);R.y=abs(R.y)+.003;vec3 rf=sky(R);
{float t=hitS(X,R,30.);if(t>0.)rf=stone(X+R*t,R)*.85;} // the stone in the mirror, and the canes
for(int i=uNb;i<uNs;i++){float t=hitP(X,R,i,30.);if(t>0.)rf=post(X+R*t,R,i)*.8;}
if(hitB(X,R,30.)>0.)rf=vec3(.1,.085,.04);
vec3 T=refract(rd,n,.752);vec2 k=T.xz/max(-T.y,.25),xi=X.xz+k*.05,xb=X.xz+k*.55; // ink a little under the surface, the bed well under
vec2 gi=grd(xi);gi-=uTau*(texture(uU,gi/uGn).xy+uUi); // carried on by the part of a step gone by since the ink was last moved
vec4 d=max(bsp(uD,gi*vec2(textureSize(uD,0))/uGn),0.)*msk(gi);
vec3 ink=inkc(d);
if(uAb[0].w+uAb[1].w+uAb[2].w>0.){ // ink round the turning stone: where each drop has been drawn out to is known exactly
vec2 q=gi-uSt[0].xy;float RR=uSt[0].z*uSt[0].z/max(dot(q,q),1.),a=-uAt*RR,pc=px/CELL*(1.+2.*abs(uAt)*RR);
q=mat2(cos(a),sin(a),-sin(a),cos(a))*q+uSt[0].xy;
for(int i=0;i<3;i++){float e=uAb[i].z*.3+pc;ink+=uAb[i].w*(1.-smoothstep(uAb[i].z-e,uAb[i].z+e,length(q-uAb[i].xy)))*(i==0?GOLD:i==1?ROSE:JADE);}}
ink/=1.+.3*dot(ink,vec3(.3,.5,.2));
vec2 gb=grd(xb);float lap=bsp(uSf,gb*vec2(textureSize(uSf,0))/uGn).w*msk(gb)*uHs/(CELL*CELL),ca=clamp(1.-.14*lap,.55,2.5);
// the bed: read from the sheet it was drawn on, more coarsely the farther off (and too far off to tell one pebble from the next: their average)
float pf=1.-smoothstep(.05,.16,px*9.),pb=fb2(xb*1.7);
vec3 bed=textureLod(uBed,xb/${BEDP}.,log2(px*float(textureSize(uBed,0).x)/${BEDP}.)-.7).rgb/6.;
bed=mix(vec3(.03,.04,.07),bed,pf)*(.5+1.*pb*pb)*ca*uBd*exp(-vec3(1.5,1.,.7)*(.55/max(-T.y,.25)-.55)); // and the longer the look through the water, the less of the bed comes back
if(uNb>0){float e=length(xb-sc().xz)/(uSt[0].z*CELL);bed*=smoothstep(.95,1.5,e);ink*=smoothstep(.98,1.06,length(X.xz-sc().xz)/(uSt[0].z*CELL));} // the foot of the stone
bed*=exp(-(d.r+d.g+d.b+d.a)*.3);
return (bed+ink*uInk)*(1.-F)+rf*F;}
void main(){
vec2 p=(gl_FragCoord.xy*2.-uR)/uR.y;vec3 rd=normalize(uCm*vec3(p,uFv)),col;
float tw=rd.y<-1e-4?-uCo.y/rd.y:1e9,ts=hitS(uCo,rd,tw),tp=1e9;int hp=-1;
for(int i=uNb;i<uNs;i++){float t=hitP(uCo,rd,i,min(tw,tp));if(t>0.){tp=t;hp=i;}}
float tb=hitB(uCo,rd,min(tw,tp));
if(ts>0.&&ts<tp&&(tb<0.||ts<tb)){col=stone(uCo+rd*ts,rd);tw=ts;}
else if(tb>0.){vec3 q=uCo+rd*tb;float e=(q.y-uPy-2.3)/.11;col=mix(vec3(.2,.2,.07),vec3(.34,.3,.13),fb2(vec2(q.z*3.,e)))*(.5+.5*e)*vec3(.9,.75,.7);tw=tb;}
else if(hp>=0){col=post(uCo+rd*tp,rd,hp);tw=tp;}
else if(tw<1e8)col=water(uCo+rd*tw,rd,tw);
else col=sky(rd);
if(tw<1e8){float s=max(dot(normalize(vec3(rd.x,0.,rd.z)),DAWN),0.);col=mix(col,mix(vec3(.15,.12,.21),vec3(.8,.36,.2),s*s*s*s),uMist*(1.-exp(-tw*tw*.0012)));} // mist on the water, far off
O=vec4(max(col*uEx,0.),1);}`;
// --- the same water from below its surface, looking sideways. The sheet that is being solved now stands on edge at z=0: x along
// it, and up it from the bed (9 down) to the surface. Before it and beyond it, water: bluer and darker with depth, shafts of
// light slanting down from the side the dawn is on, the bed with the light moving over it, the underside of the surface.
const UND=HDR+`uniform sampler2D uD,uU;uniform vec2 uR,uGn,uUi;uniform float uT,uFv,uEx,uInk,uTau;uniform vec3 uCo;uniform mat3 uCm;
out vec4 O;
${NOI}
float mote(vec2 p,float s,float t){vec2 q=p*s+vec2(t*.11,t*.17),i=floor(q),f=q-i-.5;float h=h21(i);f-=(vec2(h21(i+3.1),h21(i+7.7))-.5)*.6;return step(.86,h)*exp(-dot(f,f)*110.)*(.5+.5*sin(t*1.3+h*40.));}
float shaft(vec3 X){float s=X.x-X.y*.55;return smoothstep(.2,.55,fb2(vec2(s*1.1,uT*.06))*1.7*fb2(vec2(s*3.7+5.,uT*.09)))*exp(X.y*.3);}
void main(){
vec2 p=(gl_FragCoord.xy*2.-uR)/uR.y;vec3 rd=normalize(uCm*vec3(p,uFv));
float ts=rd.z>1e-4?-uCo.z/rd.z:1e9,tb=rd.y<-1e-4?(-9.-uCo.y)/rd.y:1e9,tu=rd.y>1e-4?-uCo.y/rd.y:1e9,te=min(tb,tu),yv=uCo.y+rd.y*min(te,24.)*.6;
vec3 fog=mix(vec3(.045,.14,.18),vec3(.006,.02,.05),sat(-yv/9.))+vec3(.32,.15,.06)*exp(yv*.45)*(.5-.5*rd.x)*.5,col=fog;
if(te<1e8){vec3 X=uCo+rd*te;
if(tb<tu){vec2 pq=peb(X.xz*1.7),pg=peb(X.xz*4.3+3.);float r1=pq.x/(.3+.3*pq.y),r2=pg.x/(.3+.25*pg.y); // the bed
vec3 b=mix(vec3(.02,.035,.05),mix(vec3(.04,.055,.07),vec3(.09,.085,.075),fract(pg.y*5.3))*(1.1-.5*r2*r2),(1.-smoothstep(.7,1.,r2))*.8);
b=mix(b,mix(vec3(.05,.07,.09),vec3(.14,.125,.105),fract(pq.y*5.3))*(1.2-.6*r1*r1),1.-smoothstep(.8,1.,r1));
float ca=fb2(X.xz*.9+vec2(uT*.15,0.))*fb2(X.xz*1.3-vec2(0.,uT*.12)+4.);
col=mix(fog,b*(.5+7.*ca*ca),exp(-te*.085));}
else{float rp=fb2(X.xz*.8+vec2(uT*.2,0.))*.6+fb2(X.xz*2.1-vec2(0.,uT*.3))*.4; // the surface, from under it
col=mix(fog,mix(vec3(.04,.17,.21),vec3(.5,.5,.42),smoothstep(.4,.8,rp))*(.55+.7*(.5-.5*rd.x)),exp(-te*.07));}}
col+=vec3(.5,.72,.62)*(shaft(uCo+rd*ts)*.6+shaft(uCo+rd*ts*.55)*.4)*.2;
if(ts<te+.01){vec4 d=vec4(0); // the ink: three thin layers of it, so that it has some body
for(int k=-1;k<2;k++){vec3 X=uCo+rd*(ts+float(k)*.3/rd.z);vec2 g=vec2(X.x/CELL+.5*uGn.x,X.y/CELL+uGn.y);g-=uTau*(texture(uU,g/uGn).xy+uUi);
d+=max(bsp(uD,g*vec2(textureSize(uD,0))/uGn),0.)*(k==0?.5:.25)*smoothstep(0.,6.,g.y)*(1.-smoothstep(uGn.y-6.,uGn.y,g.y));}
col=col*exp(-(d.r+d.g+d.b+d.a)*.45)+inkc(d)*uInk*exp(-ts*.02);}
col+=vec3(.55,.75,.7)*(mote(p,13.,uT)*.3+mote(p,25.,uT*.7+5.)*.22); // motes in the light
O=vec4(max(col*uEx,0.),1);}`;
// --- the print: a sheet of paper laid on the water takes the ink off it. Each ink keeps its colour by what it takes out of the white.
const PRT=HDR+`uniform sampler2D uD;uniform vec2 uR,uGn;uniform float uFv,uEx;uniform vec3 uCo;uniform mat3 uCm;uniform vec4 uMk,uSt[NS];
out vec4 O;
${NOI}
void main(){vec2 p=(gl_FragCoord.xy*2.-uR)/uR.y;vec3 rd=normalize(uCm*vec3(p,uFv)),X=uCo-rd*uCo.y/min(rd.y,-1e-3);vec2 g=X.xz/CELL+.5*uGn;
vec4 d=max(bsp(uD,g*vec2(textureSize(uD,0))/uGn),0.)*smoothstep(uMk.x,uMk.y,g.x)*(1.-smoothstep(uMk.z,uMk.w,g.x))*smoothstep(0.,14.,g.y)*(1.-smoothstep(uGn.y-14.,uGn.y,g.y));
vec3 pa=vec3(.8,.77,.7)*(.9+.1*fb2(g*.11))*(1.-.1*fb2(g*vec2(.9,.04)+3.)*fb2(g*vec2(.05,1.1)+7.));
pa*=mix(.82,1.,smoothstep(.9,1.25,length(g-uSt[0].xy)/uSt[0].z)); // (where the stone stood, the paper did not touch)
O=vec4(pa*exp(-(d.r*vec3(1.5,.22,.75)+d.g*vec3(.12,.5,1.7)+d.b*vec3(.2,1.5,.7)+d.a*vec3(.8,.42,.15))*4.5)*uEx,1);}`;
// --- one picture giving way to another: plainly (uX from 0 to 1), or as the camera goes through the surface - the water's edge
// crossing the lens (uWl: how far up the frame it has got; air above it, water below)
const WMX=`#version 300 es
precision highp float;uniform sampler2D uA,uB;uniform vec2 uR,uK,uM;uniform float uWl,uT,uX;out vec4 O;
void main(){vec2 v=gl_FragCoord.xy/uR,q=min(v*uK,uM);vec3 a=texture(uA,q).rgb,b=texture(uB,q).rgb;
if(uX>=0.){O=vec4(mix(a,b,uX),1);return;}
float y=uWl+.014*sin(v.x*13.+uT*4.)+.007*sin(v.x*37.-uT*6.),e=(v.y-y)/.012;
O=vec4(mix(b,a,smoothstep(-.003,.003,v.y-y))+vec3(.5,.7,.75)*exp(-e*e)*.5,1);}`;
// --- petals. Each falls once, at a place and a step of its own (uRel: where, when, and a number), and from then on goes where the
// water goes, turning at half its vorticity, as anything small afloat does (under water they also sink, slowly: uVs).
// Kept as: where it is, which way it lies, steps afloat.
const PTU=SIM+`uniform sampler2D uQ,uRel,uU,uW;uniform float uN;uniform vec2 uVs;
vec2 vel(vec2 x){return texture(uU,x/(vec2(textureSize(uU,0))*uH)).xy+uUi+uVs;}
void main(){ivec2 p=ivec2(gl_FragCoord.xy);vec4 q=texelFetch(uQ,p,0),r=texelFetch(uRel,p,0);vec2 n=vec2(textureSize(uU,0))*uH;
if(q.w==0.)q=vec4(r.xy,6.283*r.w,0); // still in the air, over where it will land
if(uN>=r.z){q.xy+=vel(q.xy+.5*vel(q.xy));
for(int i=0;i<uNs;i++){vec2 d=q.xy-uSt[i].xy;float l=length(d),e=l-uSt[i].z-4.;if(e<0.)q.xy-=d/l*e*.25;} // turned aside by a stone, not run into it
if(uSp.z==0.)q.x=mod(q.x,n.x); // (in water with no way out, what leaves at one end comes in at the other)
q.z+=.5*texelFetch(uW,ivec2(mod(q.xy,n)/uH),0).x;q.y=clamp(q.y,2.,n.y-2.);q.w+=1.;}
O=q;}`;
// drawn as two triangles each. uMd: 0 lying on the water, 1 hanging in it (seen from under). uSk: how far a word that is done with has sunk.
const PTV=`#version 300 es
precision highp float;precision highp int;precision highp sampler2D;
uniform sampler2D uQ,uRel,uU;uniform vec3 uCo;uniform mat3 uCm;uniform float uFv,uAsp,uTp,uNf,uSk,uPs,uFl;uniform vec2 uGn,uUi;uniform int uMd;out vec2 vQ;out vec3 vP;out float vS,vA;
const float CELL=.017578125;
void main(){int id=gl_VertexID/6,k=gl_VertexID%6;ivec2 n=textureSize(uQ,0),ij=ivec2(id%n.x,id/n.x);vec4 q=texelFetch(uQ,ij,0),r=texelFetch(uRel,ij,0);
float f=clamp((r.z-uNf)/uFl,0.,1.); // 1 to 0 through the fall (uFl: how many steps it takes)
if(q.w>0.)q.xy+=uTp*(texture(uU,q.xy/uGn).xy+uUi);else q=vec4(r.xy,6.283*r.w,0);
vec2 c=vec2(k==0||k==3||k==5?-1.:1.,k==0||k==1||k==3?-1.:1.);
float s=(.042+.03*fract(r.w*7.31))*uPs,a=q.z+5.*f*f,up=1.3*f*f-.35*uSk;vec2 o=mat2(cos(a),sin(a),-sin(a),cos(a))*(c*vec2(.7*cos(f*9.+r.w*40.),1.))*s, // it turns over as it comes down
w=.3*f*vec2(sin(f*7.+r.w*50.),cos(f*6.+r.w*30.));
vec3 P=uMd==0?vec3((q.x-.5*uGn.x)*CELL+o.x+w.x,.004+up,(q.y-.5*uGn.y)*CELL+o.y+w.y):vec3((q.x-.5*uGn.x)*CELL+o.x+w.x,(q.y-uGn.y)*CELL+o.y+up,w.y),v=P-uCo;
vQ=c;vP=P;vS=r.w;vA=(1.-smoothstep(.7,1.,f))*(1.-uSk);float z=dot(v,uCm[2]);
gl_Position=r.z-uNf>uFl||uSk>=1.?vec4(2,2,2,1):vec4(dot(v,uCm[0])*uFv/uAsp,dot(v,uCm[1])*uFv,0.,z);}`;
const PTF=`#version 300 es
precision highp float;precision highp int;
uniform vec3 uCo;uniform float uEx,uTn,uPp;uniform vec4 uSt[9];uniform int uNb;uniform vec2 uGn;in vec2 vQ;in vec3 vP;in float vS,vA;out vec4 O;
const float CELL=.017578125;
void main(){
float y=vQ.y,x=abs(vQ.x)*.7,e=x-(.44+.24*y)*sqrt(max(1.-y*y,0.)),aa=fwidth(e)+1e-4; // narrow at the stem, broad towards the tip, where there is a notch
float a=(1.-smoothstep(-aa,aa,e))*smoothstep(-aa,aa,x-(y-.72)*.45)*vA;
if(a<.004)discard;
if(uNb>0){vec3 rd=vP-uCo;float R=uSt[0].z*CELL;vec2 c=(uSt[0].xy-.5*uGn)*CELL;vec3 s=vec3(1.,1.25,1.),oc=(uCo-vec3(c.x,-.25*R,c.y))*s,d=rd*s; // hidden behind the stone?
float A=dot(d,d),B=dot(oc,d),h=B*B-A*(dot(oc,oc)-1.1*R*R);if(h>0.){float t=(-B-sqrt(h))/A;if(t>0.&&t<1.)discard;}}
vec3 col=mix(vec3(.95,.42,.6),vec3(1.,.86,.92),smoothstep(-1.,.6,y))*(.82+.18*vQ.x*(fract(vS*13.7)>.5?1.:-1.))*(1.-.12*exp(-vQ.x*vQ.x*60.));
O=vec4(mix(mix(col,col*vec3(.4,.62,.8),uTn),col*col*vec3(.85,.3,.42),uPp)*.62*uEx*a,a*.96);}`; // (uTn: seen through water. uPp: pressed on paper)
/* ---------------- after the picture: glow, grading, the words ---------------- */
const PRE=`#version 300 es
precision highp float;uniform sampler2D uC;uniform vec2 uR,uI,uK,uM;uniform float uTh;out vec4 O;
#define TX(c) texture(uC,min((c)*uK,uM))
`;
// (The picture is drawn into the near corner of a sheet big enough for its largest size, so that changing its size costs nothing: uK takes a
// place in the picture to its place on the sheet, uM is the last place on the sheet that belongs to it.)
// 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=TX(v).rgb*4.+TX(v+uI).rgb+TX(v-uI).rgb+TX(v+uI*vec2(1,-1)).rgb+TX(v+uI*vec2(-1,1)).rgb;s*=.125;
if(uTh>0.){s=min(s,vec3(30.));s*=smoothstep(.35,1.6,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;precision highp int;uniform sampler2D uC,uB,uX;uniform vec2 uR,uK,uM;uniform float uT,uF,uXa,uBm;out vec4 O;
#define TX(c) texture(uC,min((c)*uK,uM))
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*.008;
vec3 col=vec3(TX(v-o).r,TX(v).g,TX(v+o).b)+texture(uB,v).rgb*uBm;
col*=1.-.85*r2;
col=pow(aces(col*1.1),vec3(.4545));
vec4 tx=texture(uX,vec2(v.x,1.-v.y));
col=mix(col,tx.rgb,tx.a*uXa);
uvec2 q=(uvec2(gl_FragCoord.xy)+uint(uT*60.)*7919u)*uvec2(1597334673u,3812015801u); // grain, from whole numbers: no pattern in it
col+=(float(((q.x^q.y)*1597334673u)>>8)/16777216.-.5)*.03;
O=vec4(col*uF,1);}`;
/* ---------------- GL setup ---------------- */
const C=document.getElementById('c'),gl=C.getContext('webgl2',{antialias:false,alpha:false,powerPreference:'high-performance'});
const XF=gl&&gl.getExtension('EXT_color_buffer_float'),XH=XF||gl&&gl.getExtension('EXT_color_buffer_half_float');
if(!XH){document.body.innerHTML='<p style="color:#fff;font:16px sans-serif;padding:2em">This demo needs WebGL2 with floating-point render targets.</p>';return}
gl.getExtension('KHR_parallel_shader_compile');
// formats: one number a cell at full precision for the solver; halves where the picture reads between texels
const F1=XF?[gl.R32F,gl.RED,gl.FLOAT]:[gl.R16F,gl.RED,gl.HALF_FLOAT],F2=[gl.RG16F,gl.RG,gl.HALF_FLOAT],F4=[gl.RGBA16F,gl.RGBA,gl.HALF_FLOAT],F4F=XF?[gl.RGBA32F,gl.RGBA,gl.FLOAT]:F4;
gl.bindVertexArray(gl.createVertexArray());
// What the graphics card was last told is remembered, and it is told again only what has changed: in some browsers every word to it is dear,
// and a step of the water is some thirty drawings with a dozen settings each.
let CP=null,AT=-1,VW=-1,VH=-1;const TB=[],raw0=()=>{gl.activeTexture(gl.TEXTURE0);AT=0;TB[0]=null}; // (raw0: before a texture is bound behind this one's back)
// a texture that can be drawn into. lin: read between texels. rep: 1 the left edge joins the right, 2 the top joins the bottom as well
const fld=(w,h,f,lin,rep)=>{const t=gl.createTexture(),fi=lin?gl.LINEAR:gl.NEAREST;raw0();gl.bindTexture(gl.TEXTURE_2D,t);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,fi);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,fi);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,rep?gl.REPEAT:gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,rep>1?gl.REPEAT:gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D,0,f[0],w,h,0,f[1],f[2],null);
const fb=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,fb);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,t,0);
return{t,f:fb,w,h,fm:f}};
const free=o=>{if(o){gl.deleteTexture(o.t);gl.deleteFramebuffer(o.f);if(o.sh)o.sh.forEach(free)}};
// a texture of numbers worked out here (four to a texel), for a shader to look things up in
const data=(w,h,a)=>{const t=gl.createTexture();raw0();gl.bindTexture(gl.TEXTURE_2D,t);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA32F,w,h,0,gl.RGBA,gl.FLOAT,a);return{t,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,c:{}}};
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[0])+'\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.replace('[0]','')]=gl.getUniformLocation(o.p,a.name)}}
if(CP!=o){gl.useProgram(o.p);CP=o}return o};
// set uniforms from an object: a number is a float, {i} an int, {m} a mat3, {t} a texture (given the next free unit), {v2} pairs, an array a vector or several of four
const same=(a,b)=>{if(!a||a.length!=b.length)return 0;for(let i=0;i<b.length;i++)if(a[i]!==b[i])return 0;return 1};
const su=(o,un,k)=>{const u=o.u,c=o.c;k=k||0;for(const n in un){const l=u[n],v=un[n];if(l==null||v==null)continue;
if(typeof v=='number'){if(c[n]!==v){gl.uniform1f(l,v);c[n]=v}}
else if(v.t){if(TB[k]!=v.t){if(AT!=k){gl.activeTexture(gl.TEXTURE0+k);AT=k}gl.bindTexture(gl.TEXTURE_2D,v.t);TB[k]=v.t}if(c[n]!==k){gl.uniform1i(l,k);c[n]=k}k++}
else if(v.i!=null){if(c[n]!==v.i){gl.uniform1i(l,v.i);c[n]=v.i}}
else{const a=v.m||v.v2||v;if(!same(c[n],a)){v.m?gl.uniformMatrix3fv(l,false,a):v.v2||a.length==2?gl.uniform2fv(l,a):a.length==3?gl.uniform3fv(l,a):gl.uniform4fv(l,a);c[n]=Array.from(a)}}}
return k};
// one full-screen draw of a program into a target (or the screen)
let W=0,H=0,burn=0;
const CA0=[gl.COLOR_ATTACHMENT0];
const vport=(w,h)=>{if(VW!=w||VH!=h){gl.viewport(0,0,w,h);VW=w;VH=h}};
const pass=(o,dst,un,keep)=>{use(o);
// (for measuring only: as if the graphics card were slower, by drawing each thing burn times more, into two sheets by turns, which are thrown away)
if(burn&&dst&&!keep){const s=dst.sh||(dst.sh=[]);for(let i=0;i<burn;i++){const d=s[i&1]||(s[i&1]=fld(dst.W||dst.w,dst.H||dst.h,dst.fm));gl.bindFramebuffer(gl.FRAMEBUFFER,d.f);vport(dst.w,dst.h);gl.invalidateFramebuffer(gl.FRAMEBUFFER,CA0);su(o,un);gl.drawArrays(gl.TRIANGLES,0,3)}}
gl.bindFramebuffer(gl.FRAMEBUFFER,dst?dst.f:null);vport(dst?dst.w:W,dst?dst.h:H);
if(dst&&!keep)gl.invalidateFramebuffer(gl.FRAMEBUFFER,CA0); // everything in it is about to be replaced: no need to fetch what was there
su(o,un);gl.drawArrays(gl.TRIANGLES,0,3)};
/* ---------------- audio ---------------- */
let ctx=null,an=null,node=null,t0=null,fb=null,mode='';
const B0=0,B1=96; // which bars are played, round and round (the whole piece is 0 to 96)
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);
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,${B0},${B1});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,B0,B1);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;
}
node.connect(an);
};
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()});
// how loud the low end and the top are just now, and their sudden rises: K[0] the kick, K[1] the ticks
const A=[0,0],K=[0,0];let pb=0,ph=0;
const analyse=dt=>{let lo=0,hi=0;
if(an&&ctx.state=='running'){an.getByteFrequencyData(fb);for(let i=1;i<6;i++)lo+=fb[i];for(let i=180;i<420;i++)hi+=fb[i];lo/=5*255;hi/=240*255}
const d=Math.exp(-dt*6);K[0]=Math.max(K[0]*d,Math.min(1,Math.max(0,lo-pb)*6));pb=lo;K[1]=Math.max(K[1]*d,Math.min(1,Math.max(0,hi-ph)*12));ph=hi;
A[0]+=(lo-A[0])*.3;A[1]+=(hi-A[1])*.3};
/* ---------------- the water: its fields, and a step ---------------- */
const NX=1024,NY=512; // cells along and across the stream
const UQ=new URLSearchParams(location.search); // (for trying things out: ?tier=3 ?sps=30 ?ds=1 ?load=4)
burn=Math.max(0,(UQ.get('load')|0)-1);
const PSM2=prog(SM2),PSM0=prog(SM0),PDIR=prog(DIR),PRES=prog(RES),PPRO=prog(PRO),PVEL=prog(VEL),PROT=prog(ROT),PFRC=prog(FRC),PADV=prog(ADV),PDIF=prog(DIF),PDWN=prog(DWN),PUPS=prog(UPS),PINI=prog(INI),PTMP=prog(TMP),
PPRH=prog(PRH),PSRF=prog(SRF),PMIX=prog(MIX),PBED=prog(BED),PDYE=prog(DYE),PRPL=prog(RPL),PRSF=prog(RSF),PDBG=prog(DBG),PPTU=prog(PTU),
PPND=prog(POND),PUND=prog(UND),PPRT=prog(PRT),PWMX=prog(WMX),PPET=prog(PTF,PTV),PD=prog(DOWN),PU=prog(UP),PC=prog(COMP);
const pair=(w,h,f,lin,rep)=>({a:fld(w,h,f,lin,rep),b:fld(w,h,f,lin,rep)}),swap=o=>{const t=o.a;o.a=o.b;o.b=t};
// The water twice over: once to be shown, and once to rehearse in. Each: vorticity, stream function, velocity, and warmth. The grid they are
// solved on has GW by GT cells, each HG cells of the layout across; with it go the multigrid's grids 1..NL, each half as fine as the one
// before, down to 16 by 8 (or 32 by 16), which is solved outright. (Made by grid(), which is called again if the graphics card turns out to be slow.)
let HG=1,GW=NX,GT=NY,NL=6,MG=[null],FA=null,FB=null,VPRE=1;
const water2=()=>({OM:pair(GW,GT,F1,0,1),PSI:pair(GW,GT,F1,0,1),UV:fld(GW,GT,F2,1,1),TM:pair(GW,GT,F1,0,1)}),
grid=(h,cg)=>{if(FA)for(const F of[FA,FB]){for(const o of[F.OM,F.PSI,F.TM]){free(o.a);free(o.b)}free(F.UV)}for(const m of MG)if(m){free(m.a);free(m.b);free(m.r)}
HG=h;GW=NX/h;GT=NY/h;NL=Math.round(Math.log2(GW/(cg||16)));MG=[null];for(let k=1;k<=NL;k++)MG.push({a:fld(GW>>k,GT>>k,F1,0,1),b:fld(GW>>k,GT>>k,F1,0,1),r:fld(GW>>k,GT>>k,F1,0,1)});FA=water2();FB=water2()};
grid(1);
const zero=o=>{gl.bindFramebuffer(gl.FRAMEBUFFER,o.f);gl.clearColor(0,0,0,0);gl.clear(gl.COLOR_BUFFER_BIT)};
const calm=F=>{for(const o of[F.OM,F.PSI,F.TM]){zero(o.a);zero(o.b)}zero(F.UV)}; // water at rest
// read numbers back: at once (the page waits for the graphics card), or later - asked for now, and collected when the card has them ready
const peek=(o,x,y,w,h)=>{const a=new Float32Array((w||1)*(h||1)*4);gl.bindFramebuffer(gl.FRAMEBUFFER,o.f);gl.readPixels(x,y,w||1,h||1,gl.RGBA,gl.FLOAT,a);return a};
const peekLater=(o,w,h,got)=>{const b=gl.createBuffer(),a=new Float32Array(w*h*4);gl.bindFramebuffer(gl.FRAMEBUFFER,o.f);gl.bindBuffer(gl.PIXEL_PACK_BUFFER,b);gl.bufferData(gl.PIXEL_PACK_BUFFER,a.byteLength,gl.STREAM_READ);
gl.readPixels(0,0,w,h,gl.RGBA,gl.FLOAT,0);gl.bindBuffer(gl.PIXEL_PACK_BUFFER,null);const s=gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE,0);gl.flush();
return()=>{if(gl.clientWaitSync(s,0,0)==gl.TIMEOUT_EXPIRED)return 0;gl.deleteSync(s);gl.bindBuffer(gl.PIXEL_PACK_BUFFER,b);gl.getBufferSubData(gl.PIXEL_PACK_BUFFER,0,a);gl.bindBuffer(gl.PIXEL_PACK_BUFFER,null);gl.deleteBuffer(b);got(a);return 1}};
// the inverse of the Laplacian on the coarsest grid, by elimination. wy: banks (1) or the top joined to the bottom (0)
const CINV=[];
const cinv=wy=>{const cw=GW>>NL,ch=GT>>NL,n=cw*ch,h2=(NX/cw)**2,key=wy+'/'+cw;if(CINV[key])return CINV[key];
const tex=m=>{const t=gl.createTexture();raw0();gl.bindTexture(gl.TEXTURE_2D,t);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D,0,gl.R32F,n,n,0,gl.RED,gl.FLOAT,Float32Array.from(m));return CINV[key]={t}};
if(n>200&&wy){ // too many cells to eliminate in good time. But along the stream the grid joins end to end, so the problem falls apart into one
// small problem across the stream for each wave along it: those are solved, and the waves put together again.
const g=new Float64Array(cw*ch*ch),m=new Float64Array(n*n);
for(let k=0;k<cw;k++){const th=2*Math.PI*k/cw,A=new Float64Array(ch*ch),I=new Float64Array(ch*ch);
for(let j=0;j<ch;j++){A[j*ch+j]=(2*Math.cos(th)-4-(j==0)-(j==ch-1))/h2;if(j)A[j*ch+j-1]=1/h2;if(j<ch-1)A[j*ch+j+1]=1/h2;I[j*ch+j]=1}
for(let c=0;c<ch;c++){const iv=1/A[c*ch+c];for(let q=0;q<ch;q++){A[c*ch+q]*=iv;I[c*ch+q]*=iv}
for(let r=0;r<ch;r++)if(r!=c){const f=A[r*ch+c];if(f)for(let q=0;q<ch;q++){A[r*ch+q]-=f*A[c*ch+q];I[r*ch+q]-=f*I[c*ch+q]}}}
for(let d=0;d<cw;d++){const w=Math.cos(th*d)/cw;for(let q=0;q<ch*ch;q++)g[d*ch*ch+q]+=w*I[q]}}
for(let j=0;j<ch;j++)for(let i=0;i<cw;i++)for(let j2=0;j2<ch;j2++)for(let i2=0;i2<cw;i2++)m[(j*cw+i)*n+j2*cw+i2]=g[((i-i2+cw)%cw)*ch*ch+j*ch+j2];
return tex(m)}
const a=new Float64Array(n*n),m=new Float64Array(n*n);
for(let j=0;j<ch;j++)for(let i=0;i<cw;i++){const r=j*cw+i;let d=-4;
for(const[di,dj]of[[1,0],[-1,0],[0,1],[0,-1]]){let q=j+dj;if(q<0||q>=ch){if(wy){d--;continue}q=(q+ch)%ch}a[r*n+q*cw+(i+di+cw)%cw]+=1/h2}
a[r*n+r]+=d/h2;m[r*n+r]=1}
if(!wy)for(let k=0;k<n*n;k++)a[k]-=1/(n*h2); // with no banks the level of the whole is not fixed by anything: pin it
for(let c=0;c<n;c++){let pv=c;for(let r=c+1;r<n;r++)if(Math.abs(a[r*n+c])>Math.abs(a[pv*n+c]))pv=r;
if(pv!=c)for(let k=0;k<n;k++){let t=a[c*n+k];a[c*n+k]=a[pv*n+k];a[pv*n+k]=t;t=m[c*n+k];m[c*n+k]=m[pv*n+k];m[pv*n+k]=t}
const iv=1/a[c*n+c];for(let k=0;k<n;k++){a[c*n+k]*=iv;m[c*n+k]*=iv}
for(let r=0;r<n;r++)if(r!=c){const f=a[r*n+c];if(f)for(let k=0;k<n;k++){a[r*n+k]-=f*a[c*n+k];m[r*n+k]-=f*m[c*n+k]}}}
return tex(m)};
// one V on Laplacian(x) = sg*b, from grid k0 (where X and b are given) down and back. On the slowest cards (VPRE off) there is no smoothing on
// the way down - what is left is passed straight on, which costs a drawing less on every grid - only on the way back up.
const vcycle=(X,b,sg,Q,k0)=>{k0=k0||0;const wy=Q.uWy,HH=HG*HG;
let l={X,r:b},s=sg;
for(let k=k0;k<NL;k++){const c=MG[k+1],U={uX:l.X.a,uB:l.r,uH2:HH*4**k,uSg:s,uWy:wy};
if(VPRE){pass(k>k0?PSM0:PSM2,l.X.b,U);swap(l.X);U.uX=l.X.a}
if(VPRE||k==k0)pass(PRES,c.r,U);else pass(PDWN,c.r,{uW:l.r});
c.up=l;c.sg=s;l={X:c,r:c.r};s=1}
pass(PDIR,l.X.a,{uM:cinv(wy.i),uB:l.r});
for(let k=NL-1;k>=k0;k--){const c=l.X,u=c.up;if(VPRE||k==k0)pass(PPRO,u.X.b,{uX:u.X.a,uC:c.a,uWy:wy});else pass(PUPS,u.X.b,{uC:c.a,uWy:wy});swap(u.X);
pass(PSM2,u.X.b,{uX:u.X.a,uB:u.r,uH2:HH*4**k,uSg:c.sg,uWy:wy});swap(u.X);l=u}
};
// Viscosity for a step: a few passes of spreading. When the water is very thick that would take many, so it is done on a grid half as fine, or
// a quarter (the multigrid's, which are idle just then). Spreading is reckoned by its variance, 2*nu a step: going down and coming back spread a
// little by themselves (1 cell squared for one grid down, 5 for two), and the passes between make up the rest, each worth 2K coarse cells squared.
const spread=(F,Q,nu)=>{nu/=HG*HG;const n=Math.ceil(nu/.45),wy={uWy:Q.uWy}; // (nu: now in cells of the grid being solved on)
if(n<6){for(let k=0;k<n;k++){pass(PDIF,F.OM.b,{uW:F.OM.a,uK:nu/n,...wy});swap(F.OM)}return}
const L=nu<10?1:2,c=4**L,v=2*nu-(L<2?1:5),m=Math.ceil(v/(.9*c)),g=MG[L];
pass(PDWN,MG[1].a,{uW:F.OM.a});if(L>1)pass(PDWN,g.a,{uW:MG[1].a});
for(let k=0;k<m;k++){pass(PDIF,g.b,{uW:g.a,uK:v/(2*m*c),...wy});swap(g)}
if(L>1){pass(PUPS,MG[1].b,{uC:g.a,...wy});swap(MG[1])}
pass(PUPS,F.OM.b,{uC:MG[1].a,...wy});swap(F.OM)};
// a step of the water F. Q is what it is being asked to do, as the shaders take it; nu the viscosity
const step=(F,Q,nu)=>{
vcycle(F.PSI,F.OM.a,-1,Q);
pass(PVEL,F.UV,{uP:F.PSI.a,...Q});
if(Q.uBy){pass(PTMP,F.TM.b,{uTm:F.TM.a,uU:F.UV,...Q});swap(F.TM)} // warmth, carried along (only where it is what drives the water)
pass(PFRC,F.OM.b,{uW:F.OM.a,uP:F.PSI.a,uTm:F.TM.a,...Q});swap(F.OM);
pass(PADV,F.OM.b,{uW:F.OM.a,uU:F.UV,uDt:1,...Q});swap(F.OM);
spread(F,Q,nu)};
/* How fast is this graphics card? Before anything is shown, some steps of the water are timed: done a few at a time, the page waiting for the
card after each few, and the least of several goes kept. From that it is settled how much will be asked of the card (TIER):
0 everything: the water moved sixty times a second, the ink on a grid twice as fine as the water's
1 the ink a little coarser, the pressure under the surface found every second step
2 also: the water moved thirty times a second, in steps twice as long (the picture goes between them)
3 also: the water solved on a grid half as fine, and moved twenty times a second; the ink coarser than the layout; and everything done in
as few drawings as will do (a shorter way round the multigrid, rings on a coarser grid, less glow): on a telephone it is the number of
drawings that costs, nearly half a millisecond each
Each bar of water does the same thing whichever it is. (What a telephone takes for a step was found to be fifteen times what the laptop
this was made on takes: hence 3.) */
const U8=new Uint8Array(4),wait=o=>{gl.finish();if(o)peek(o,0,0);else{gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.readPixels(0,0,1,1,gl.RGBA,gl.UNSIGNED_BYTE,U8)}}; // until the card has done all it was given (o: the last thing it drew into)
const timeIt=(f,o,ms)=>{f();wait(o());let z=performance.now();wait(o());wait(o());z=(performance.now()-z)/2; // (z: what the waiting itself takes)
let n=4,best=1e9;const t0=performance.now();
for(let i=0;i<8&&performance.now()-t0<(ms||100);){const t=performance.now();for(let j=0;j<n;j++)f();wait(o());const d=performance.now()-t;if(d<6&&n<32)n*=2;else{best=Math.min(best,Math.max(d-z,.2*d)/n);i++}}
return best};
const ST00=new Float32Array(36);ST00.set([260,256,24,0]);
const Q0=()=>({uWy:{i:1},uNs:{i:1},uSt:ST00,uSv:{v2:new Float32Array(18)},uUi:[1.7,0],uSp:[NX-70,NX-10,.3],uSo:[0,0,0,0],uGu:[0,0,0,1],uGd:[0,0],uBy:0,uDr:0,uH:HG});
const CS1=timeIt(()=>step(FB,Q0(),.4),()=>FB.OM.a),TIER=UQ.has('tier')?+UQ.get('tier'):CS1>9?3:CS1>3.8?2:CS1>2.6?1:0, // (CS1: ms for a step on the full grid)
SPS=+UQ.get('sps')||[60,60,30,20][TIER],DS=+UQ.get('ds')||[2,1.5,CS1>7?1:1.5,.75][TIER],SRN=[1,2,2,4][TIER], // steps of the water a second; cells of ink to a cell of the layout; steps between one finding of the pressure and the next
K60=60/SPS,RSUB=Math.round(K60); // how many sixtieths of a second a step is
if(TIER>2){VPRE=0;grid(2,32)}
// what a step takes on the grid that will be used; and, to tell what a slow card is slow at: a drawing of next to nothing, and one pass of spreading
const CST=TIER>2?timeIt(()=>step(FB,Q0(),.4),()=>FB.OM.a):CS1,
CP0=timeIt(()=>pass(PDWN,MG[NL].b,{uW:MG[NL-1].a}),()=>MG[NL].b,30),CP1=timeIt(()=>{pass(PDIF,FB.OM.b,{uW:FB.OM.a,uK:.1,uWy:{i:1}});swap(FB.OM)},()=>FB.OM.a,30);
calm(FB);
const PRS=pair(GW/2,GT/2,F1,0,1),PRB=fld(GW/2,GT/2,F1,0,1),SF=pair(GW/2,GT/2,F4,1,1),SFM=fld(GW/2,GT/2,F4,1,1),DY=pair(NX*DS,NY*DS,F4,1,1), // pressure and what it is solved from; the surface as the picture reads it (the last two, and what lies between them now); ink
RC=TIER>2?4:2,RSB=TIER>2?1:RSUB,RW=TIER>2?[.45,.9955**3,.9985**3]:[.3,.9955,.9985], // rings: cells to a cell of their grid; steps of theirs to a step of the water; how fast they go and die
RP=pair(NX/RC,NY/RC,F2),RS=fld(NX/RC,NY/RC,F4,1); // rings: height and its rate of change; and their slope, for the picture
const NPW=64,NPH=32,PTS=[pair(NPW,NPH,F4F),pair(NPW,NPH,F4F)],NCW=512,NCH=256,CT=pair(NCW,NCH,F4F); // petals: this passage's and the last one's; and the many that are tried in rehearsal
const spin=(F,Q)=>pass(PROT,F.UV,Q); // thick water round the turning stone: known exactly
const sheet=(F,A)=>{pass(PINI,F.OM.a,{uA:A,uWy:{i:1},uH:HG})}; // water above sliding over water below, to begin from
// the ink, carried through dt steps at once; the pressure, for the surface; petals; rings
const ink=(F,Q,dt,o)=>{pass(PDYE,DY.b,{uD:DY.a,uU:F.UV,uDt:dt,uDs:DS,...Q,...o});swap(DY)};
const surface=(F,Q)=>{pass(PPRH,PRB,{uP:F.PSI.a,uU:F.UV,...Q});vcycle(PRS,PRB,1,Q,1);pass(PSRF,SF.b,{uP:PRS.a,uB:PRB,...Q});swap(SF)};
const petals=(X,rel,F,Q,n)=>{pass(PPTU,X.b,{uQ:X.a,uRel:rel,uU:F.UV,uW:F.OM.a,uN:n,...Q});swap(X)}; // one step for a set of petals; n: which step this is
const RD=new Float32Array(32);
const ripple=dr=>{RD.fill(0);dr.forEach((d,i)=>RD.set(d,i*4));pass(PRPL,RP.b,{uH:RP.a,uDp:RD,uNd:{i:dr.length},uRc:RC,uRw:RW});swap(RP)},rslope=()=>pass(PRSF,RS,{uH:RP.a,uRc:RC});
/* ---------------- timeline ---------------- */
const BPM=SYN(0).BPM,BEAT=60/BPM,BAR=4*BEAT,LEN=(B1-B0)*BAR,CELL=9/NY,SPB=SPS*BAR, // SPB: steps of the water to a bar
TS=112.5/SPB,Sb=b=>Math.round(b*SPB), // The water was set going at 128 beats a minute and sixty steps a second. At another tempo, or with longer steps, everything it does in a step is scaled to match (TS), so that each bar of it looks the same. Sb: bars to steps
FL=40/K60,PJ=Math.round(12/K60); // how many steps a petal takes to fall, and a drop to be poured
const add=(a,b)=>[a[0]+b[0],a[1]+b[1],a[2]+b[2]],sub=(a,b)=>[a[0]-b[0],a[1]-b[1],a[2]-b[2]],mul=(a,s)=>[a[0]*s,a[1]*s,a[2]*s],
cross=(a,b)=>[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]],nrm=a=>mul(a,1/Math.hypot(a[0],a[1],a[2])),
mix=(a,b,t)=>a+(b-a)*t,mix3=(a,b,t)=>[mix(a[0],b[0],t),mix(a[1],b[1],t),mix(a[2],b[2],t)],
cl=(x,a,b)=>Math.max(a==null?0:a,Math.min(b==null?1:b,x)),ss=(a,b,x)=>{x=cl((x-a)/(b-a));return x*x*(3-2*x)},
look=(co,ta,up)=>{const f=nrm(sub(ta,co)),r=nrm(cross(up||[0,1,0],f)),u=cross(f,r);return[...r,...u,...f]}, // the camera's right, up and forward
g2w=(x,y)=>[(x-NX/2)*CELL,0,(y-NY/2)*CELL];
const P={U:2.134*TS,hk:.45,ink:1,bd:1,mist:.6,ex:1,bm:.5,rk:1.2}; // knobs, while building
// what every shader of the water is told, whatever the passage; and the ink
const ST0=[260,256,24],Z16=new Float32Array(16),Z36=new Float32Array(36); // the stone: where it stands, and how big it is round
const stones=(w,tn)=>{const a=new Float32Array(36),v=new Float32Array(18);a.set([ST0[0],ST0[1],ST0[2],w||0]);let n=1;
if(tn)for(const t of tn){a.set([t[0],t[1],5,0],n*4);v.set([t[2],0],n*2);n++}return{uSt:a,uSv:{v2:v},uNs:{i:n}}};
const QB=()=>({uH:HG,uWy:{i:1},uUi:[0,0],uSp:[NX-70,NX-10,0],uSo:[0,0,0,0],uGu:[0,0,0,1],uGd:[0,0],uBy:0,uDr:0,uVs:[0,0],uNh:{i:0},uHt:Z16,uTf:1});
const DQ=()=>({uIn:0,uLs:14,uBt:0,uBs:1/(SPS*BEAT),uK6:K60,uFd:1,uSi:0,uSj:0,uTh:[1,1,1,1],uSc:Z36,uDp:[0,0,0,0],uDc:[0,0,0,0],uLn:[0,1,0],uNh:{i:0},uHt:Z16,uHc:Z16});
const MKS=[8,150,NX-230,NX-60],MKC=[2,130,NX-130,NX-2]; // where ink is shown: in a stream (not at its ends), in closed water (everywhere)
// from where a word is read: over the near bank, looking down at it
const rd=(W,h,bk)=>{const c=W.arc?g2w(W.arc.cx,W.arc.cy+W.arc.r*.5):g2w((W.x0+W.x1)/2,W.yc);return{co:add(c,[0,h,-bk]),ta:add(c,[0,0,.15])}};
const still=(F,w)=>{},solve=(F,w)=>step(F,w.Q,w.nu);
/* The seven passages. Each: its bars; the word its petals are to spell and where (in cells); what the water is asked to do at
each step (water) and how that is done (flow); where and when a trial petal falls (cand), and the ones that are only passing
(amb); the ink; rings; the camera and the words on the screen (shot, by bars into the passage). */
const PS=[];
/* STILL (bars 0 to 8). Nothing moves, so what falls stays where it fell: the petals come down straight into their letters. */
const WS={t:'STILL',x0:440,x1:800,yc:256,h:104};
PS.push({n:'STILL',b0:0,b1:8,W:WS,ps:1,direct:1,stray:0,flow:still,
water:sn=>({Q:{...QB(),...stones()},nu:0,U:0,bt:sn/SPB*4}),
cand:r=>[WS.x0-10+(WS.x1-WS.x0+20)*r(),WS.yc-64+128*r(),Sb(.8+5.6*r())],
amb:r=>{const x=60+900*r(),y=40+432*r();return x>WS.x0-40&&x<WS.x1+40&&Math.abs(y-WS.yc)<90?null:[x,y,Sb(.36+6.9*r())]},nAmb:150,
drops:sn=>sn==0?[[700,170,.9,9]]:sn==Sb(2.5)?[[430,340,.6,8]]:sn==Sb(4.25)?[[840,330,.6,8]]:sn==Sb(6.5)?[[560,110,.6,8]]:null,
dye:(w,n,sn)=>sn<Sb(2.3)?{uFd:Math.exp(-n*.02*K60)}:null,
shot:b=>{const k=ss(1.2,6.4,b),v=rd(WS,5.2,3.7);
return{co:mix3([6.6,.55+.2*b,-3.3],v.co,k),ta:mix3([-4.4,.3,.3],v.ta,k),cap:b<1?'':'still water keeps what falls on it where it fell',eq:-1,re:'0',ink:1-ss(0,1.5,b)}}});
/* VISCOSITY (8 to 24). Water so thick that it has no inertia: what is stirred into it can be stirred out again. The stone turns
six slow turns and the three drops of ink beside it are drawn out into threads; then six turns back, and they are drops again
(G. I. Taylor's demonstration). The flow round a turning cylinder in such water is known exactly, so here nothing is solved.
Petals fall while it is turning; the turning back leaves them in their letters. */
const WV={t:'VISCOSITY',arc:{cx:ST0[0],cy:ST0[1],r:120},h:36};
const TH=b=>12*Math.PI*(b<8?ss(1,8,b):ss(1,8,16-b)); // how far the stone has been turned: six turns, and back
const AB=[80,200,320].map((a,i)=>[ST0[0]+52*Math.cos(a*Math.PI/180),ST0[1]+52*Math.sin(a*Math.PI/180),13,.2+.25*i]); // the three drops: where, how big, when (bars)
const abU=f=>{const a=new Float32Array(12);AB.forEach((d,i)=>a.set([d[0],d[1],d[2],f(d[3])],i*4));return a};
PS.push({n:'VISCOSITY',b0:8,b1:24,W:WV,ps:.5,cost:.2,any:1,flow:(F,w)=>spin(F,w.Q),
water:sn=>({Q:{...QB(),...stones(TH((sn+1)/SPB)-TH(sn/SPB))},nu:0,U:0,bt:sn/SPB*4}),
cand:r=>{const a=6.2832*r(),q=Math.sqrt(84*84+(160*160-84*84)*r());return[ST0[0]+q*Math.cos(a),ST0[1]+q*Math.sin(a),Sb(1.33+6.05*r())]},
amb:r=>[560+420*r(),40+432*r(),Sb(.5+11.5*r())],nAmb:60,
drops:sn=>{for(const d of AB)if(sn==Math.round(d[3]*SPB))return[[d[0],d[1],.5,7]];return null},
shot:b=>{const st=g2w(ST0[0],ST0[1]),e=.5*Math.sin(Math.PI*b/16);
return{co:add(st,[0,3.7-e*.6,-2.4+.2*e]),ta:add(st,[0,0,.4]),eq:6,re:'0.01',sa:TH(b),at:TH(b),ab:abU(t=>ss(t,t+.1,b)),bl:1.7,
cap:b<1?'thick water, and three drops of ink in it':b<8?'the stone turns, six slow turns: drops and petals are drawn out round it':b<15.2?'and six turns back. Flow this slow can be undone':'three drops again, as G. I. Taylor showed in 1967'}}});
/* PRESSURE (24 to 40). Water cannot be squeezed. A drop falls on every beat, ink and clear water by turns, and each one, as it
spreads, pushes everything already there outwards: rings. Then a breath across the surface, twice, folds them. */
const WP={t:'PRESSURE',x0:420,x1:860,yc:256,h:104},PCX=640,PCY=256,PAR=Math.PI*26*26,
pour=j=>j<0?0:j>=PJ?1:(j+1)/PJ-Math.sin(2*Math.PI*(j+1)/PJ)/(2*Math.PI); // how much of a drop has been poured, j steps after it lands
const INK4=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]];
const drop=sn=>{const k=Math.floor(sn/(SPB/4)),j=sn-Math.ceil(k*SPB/4);return{k,j,on:k<32}};
PS.push({n:'PRESSURE',b0:24,b1:40,W:WP,ps:1,flow:solve,mk:MKC,uref:1.8,
water:sn=>{const b=sn/SPB,d=drop(sn),g1=ss(9,9.3,b)*(1-ss(9.9,10.2,b)),g2=ss(11.4,11.7,b)*(1-ss(12.1,12.4,b));
return{Q:{...QB(),...stones(),uSo:[PCX,PCY,d.on?PAR*(pour(d.j)-pour(d.j-1)):0,0],uGu:g1>0?[PCX+10,130,.034*TS*TS*g1,44]:[455,268,.03*TS*TS*g2,44],uGd:g1>0?[.22,1]:[1,-.18],
uDr:.05*TS*ss(13.4,14.6,b)},nu:.12*TS*(1+8*ss(13,14.4,b)),U:0,bt:b*4}},
cand:r=>[370+540*r(),90+332*r(),Sb(.36+10.75*r())],
drops:sn=>{const d=drop(sn);return d.on&&d.j==0?[[PCX,PCY,.8,9]]:null},
dye:(w,n,sn)=>{const d=drop(sn);return{uFd:Math.exp(-n*.0003*TS),uDp:[PCX,PCY,d.on&&d.j<=PJ?Math.sqrt(PAR*pour(d.j)/Math.PI):0,0],uDc:d.k&1?[0,0,0,0]:INK4[(d.k>>1)%4]}},
shot:b=>{const c=g2w(PCX,PCY),k=ss(6.5,10.5,b),m=ss(11.5,14.4,b),v=rd(WP,5.3,3.75),f=1-ss(0,3,b);
return{co:mix3(mix3(add(c,[-.9+.12*b,2.6,-3.7]),add(c,[.2,5.7,-3.5]),k),v.co,m),ta:mix3(add(c,[0,0,.2]),v.ta,m),eq:4,re:'1',ab:abU(t=>f),at:0,bl:1.8,ink:mix(1,.36,ss(13,15,b)),
cap:b<8.4?'a drop on every beat, ink and clear water by turns: each pushes all the others outwards':b<13?'water cannot be squeezed. A breath across it folds the rings':'every push was passed on'}}});
/* INERTIA (40 to 56). The stream comes up to speed and stays there; what changes is how thick the water is. Thick (a Reynolds
number of 40), it closes behind the stone into two captive eddies. Thinned (150), the wake cannot hold still: it sways, and then
sheds a vortex from each flank in turn - one to each beat of the slow drum, because the speed is chosen so that the street's own
period is four beats, and the stone is twisted a little to and fro in that time, which holds the street in step, as real wakes
are held. Petals fall on it. Then the stream slows, the water thickens again, and everything comes to rest. */
const WI={t:'INERTIA',x0:384,x1:904,yc:256,h:104};
const thr=(w,n,si)=>({uIn:8,uBt:w.bt,uFd:Math.exp(-n*.0008*TS),uSi:si*ss(.1,.6,w.U/P.U)}); // ink for a stream: threads coming in, and the stone's pores
PS.push({n:'INERTIA',b0:40,b1:56,W:WI,ps:1,flow:solve,
water:sn=>{const b=sn/SPB,U=P.U*ss(0,1.5,b)*(1-ss(12.5,14.3,b)),nu=P.U*ST0[2]*2/(40*Math.pow(150/40,ss(4,4.6,b)))*(1+5*ss(13,14.6,b));
return{Q:{...QB(),...stones(mix(.7,.3,ss(8.5,11,b))*ss(3.75,4.25,b)*U/ST0[2]*Math.sin(Math.PI*2*(b+.04))),uUi:[U,0],uSp:[NX-70,NX-10,.3],uDr:.05*TS*ss(13.6,14.9,b)},nu,U,Re:U*ST0[2]*2/nu,bt:b*4}},
cand:HG>1?r=>[20+640*r(),96+320*r(),Sb(8.2+4.1*r())]:r=>[40+520*r(),140+232*r(),Sb(8.89+3.38*r())], // (on the coarse grid the vortices carry petals farther afield: they are let fall over more of the water, and for longer)
amb:r=>{const x=20+900*r();return[x,30+452*r(),r()<.15?0:Math.round(r()*(Sb(12.27)-(1010-x)/P.U))]},nAmb:520,
dye:(w,n)=>thr(w,n,.5),
shot:b=>{const st=g2w(ST0[0],ST0[1]),k=ss(5,11.5,b),m=ss(11.2,14.6,b),d=b/16,v=rd(WI,5.5,3.9);
let ta=mix3(add(st,[1+.4*d,0,.1]),[-1+.6*d,0,.1],k),co=mix3(add(st,[.6+1.2*d,1.9+.4*d,-3.1]),[8.3+.5*d,2.9,-4.6-.3*d],k);
co[1]+=1.6*Math.sin(Math.PI*k); // (it rises over the water on the way)
return{co:mix3(co,v.co,m),ta:mix3(ta,v.ta,m),ink:mix(1,.4,ss(13.2,15,b)),eq:2,bl:2.2,
cap:b<1?'a stream':b<4.2?'slow, thick water closes behind the stone: two captive eddies':b<8.5?'thinner water cannot hold still: the wake begins to sway':
b<12.6?'a vortex street: a vortex to every kick of the bass drum':b<14.7?'the stream slows, and comes to rest':'nothing put the petals there but the water'}}});
/* FORCE (56 to 72). Under water, looking sideways: the sheet that is solved now stands on edge, from the bed up to the surface.
Water above slides over the water below, and the edge between them rolls up into billows. Warm ink seeps from the bed; being
lighter, it rises - that push is the last term of the equation - in plumes with caps like mushrooms, into the billows.
Petals that have sunk hang in it, and go where it goes. */
const WF={t:'FORCE',x0:250,x1:774,yc:262,h:118},F0=Sb(1.25), // (F0: the step at which the camera is under and the water is set going)
HSP=[150,400,650,900],HCO=[[0,1,0,0],[0,0,1,0],[0,1,0,0],[0,0,1,0]];
const heat=(r,rad)=>{const a=new Float32Array(16);HSP.forEach((x,i)=>a.set([x,7,rad,r],i*4));return a},HCA=new Float32Array(HCO.flat());
PS.push({n:'FORCE',b0:56,b1:72,W:WF,ps:1.15,mode:1,noSt:1,stray:0,
flow:(F,w,sn)=>{if(sn==F0)sheet(F,[.1*TS,380,7,.05]);if(sn>=F0)step(F,w.Q,w.nu)},
water:sn=>{const b=sn/SPB,h=ss(2.3,2.8,b)*(1-ss(9.6,10.2,b));
return{Q:{...QB(),uSt:Z36,uSv:{v2:new Float32Array(18)},uNs:{i:0},uBy:.05*TS*TS*(1-ss(11,12.5,b)),uNh:{i:4},uHt:heat(.05*TS*h,16),uTf:Math.pow(.9993,TS),uDr:.05*TS*ss(12.6,14,b),
},nu:.12*TS*(1+10*ss(12,13.8,b)),U:0,bt:b*4}},
cand:r=>[20+984*r(),20+472*r(),Sb(1.6+9.5*r())],
dye:(w,n,sn)=>sn<F0?null:{uFd:Math.exp(-n*.0005*TS),uNh:{i:4},uHt:heat(.04*w.Q.uHt[3]/.05,13),uHc:HCA,uLn:sn<F0+3?[380,3,.5]:[0,1,0]},
shot:b=>{const e=rd(WI,5.5,3.9),k=ss(0,1.05,b),u=ss(1,3.2,b),v=ss(14.6,16,b);
return{co:mix3(e.co,[.3,.14,-6.5],k),ta:mix3(e.ta,[.3,.1,0],k),uco:mix3(mix3([.3,-.45,-6.5],[.3*Math.sin(b*.4),-4.5,-9.6],u),[0,-1.4,-8.5],v),uta:mix3(mix3([.3,-.5,0],[0,-4.5,0],u),[0,-3.6,0],v),
wl:b<.95?0:b<1.25?(b-.95)/.3:1,ink:.4*(1-ss(0,.8,b)),uink:.8*mix(1,.4,ss(13,14.6,b))*(1-ss(15.3,16,b)),eq:8,re:b<2?'0':'500',rst:stones(),
cap:b<1.3?'':b<6?'under water. Water above slides over water below: the edge between them rolls up':b<11.5?'warm ink is lighter than what is round it, so it rises: a force':b<14.3?'the warmth is spent':'sunk petals, hanging where the water left them'}}});
/* TURBULENCE (72 to 88). A rake of eight canes is drawn the length of the water: each leaves a wake, hundreds of small eddies in
all. In a sheet this thin they do not break down into smaller ones, as they would in deep water: they merge, into a few great
slow ones. */
const WT={t:'TURBULENCE',x0:330,x1:975,yc:256,h:104},TY=[58,106,154,202,310,358,406,454],TV=2.8*TS,T0=Sb(.356),T1=T0+Math.round(944/TV),
tines=sn=>TY.map(y=>[985-TV*(Math.min(sn,T1)-T0),y,sn<T1?-TV:0]),TSC=new Float32Array(36);
[0,1,2,0,1,2,0,1].forEach((c,i)=>TSC.set(INK4[c],(i+1)*4));
PS.push({n:'TURBULENCE',b0:72,b1:88,W:WT,ps:.8,flow:solve,mk:MKC,uref:3.2,
water:sn=>{const b=sn/SPB;return{Q:{...QB(),...stones(0,sn>=T0&&sn<T1?tines(sn):null),uDr:.05*TS*ss(12.8,14.2,b)},nu:.08*TS*(1+12*ss(12.4,14,b)),U:0,bt:b*4}},
cand:r=>[40+960*r(),40+432*r(),Sb(3.73+8.09*r())],
dye:(w,n,sn)=>({uFd:Math.exp(-n*.00015*TS),uSj:sn<T1?1.6:0,uSc:TSC}),
init:()=>{zero(DY.a);zero(DY.b)},
shot:b=>{const k=ss(0,.4,b),r=ss(.2,3,b),m=ss(11.5,14.2,b),v=rd(WT,6.5,4.6),sn=b*SPB;
return{co:mix3(mix3([.3,.2,-6.5],[.6,9.3,-6.4],r),v.co,m),ta:mix3(mix3([.3,.15,0],[.6,0,.3],r),v.ta,m),uco:mix3([0,-1.4,-8.5],[.3,-.3,-6.5],k),uta:mix3([0,-3.6,0],[.3,-.6,0],k),
wl:b<.1?1:b<.4?1-(b-.1)/.3:0,uink:0,ink:mix(1,.4,ss(12.6,14.6,b)),eq:'all',re:b<.4?'0':b<12.6?'10⁴':'0',rst:b<4.6&&sn>=T0?stones(0,tines(sn)):null,py:9*ss(3.4,4.6,b),
cap:b<.5?'':b<3.6?'a rake is drawn through the water: hundreds of small eddies':b<12.4?'in a sheet this thin they do not break down: they merge, into a few great slow ones':'turbulence, come to rest'}}});
/* LAMINAR (88 to 96). The stream again, slow and thick enough to keep its order: every thread and every petal stays in its own
lane. It stops; a sheet of paper is laid on the water and takes the ink off it. */
const WL={t:'LAMINAR',x0:384,x1:904,yc:256,h:104};
PS.push({n:'LAMINAR',b0:88,b1:96,W:WL,ps:1,flow:solve,
water:sn=>{const b=sn/SPB,U=P.U*ss(0,1.2,b)*(1-ss(4.3,5.8,b)),nu=P.U*ST0[2]*2/40*(1+5*ss(4.9,6.1,b));
return{Q:{...QB(),...stones(),uUi:[U,0],uSp:[NX-70,NX-10,.3],uDr:.05*TS*ss(5.3,6.3,b)},nu,U,Re:U*ST0[2]*2/nu,bt:b*4}},
cand:r=>[30+640*r(),140+232*r(),Sb(1.07+3.55*r())],
drops:sn=>sn==Sb(4.5)?[[330,400,.6,8]]:null,
dye:(w,n)=>thr(w,n,.25),
shot:b=>{const v=rd(WL,5.5,3.9),t=ss(5.8,6.9,b),c=g2w((WL.x0+WL.x1)/2,WL.yc);
return{co:mix3(v.co,[c[0],9.4,.2],t),ta:mix3(v.ta,[c[0],0,.2],t),up:nrm([0,1-t,t]),px:ss(6.5,7.15,b),eq:'all',bl:3.5,
cap:b<1?'':b<5?'the stream again, slow enough to keep its order: every petal in its own lane':b<6.6?'laminar':'in two dimensions this equation always stays smooth. In three, nobody has proved it.'}}});
PS.forEach(p=>{p.s0=Math.round(p.b0*SPB);p.s1=Math.round(p.b1*SPB);p.len=p.s1-p.s0});
// the camera does not jump between passages: each begins from where the last one left it
const view=(k,b)=>{const p=PS[k],s=p.shot(b);if(s.bl&&b<s.bl){const q=PS[(k+6)%7],e=q.shot(q.b1-q.b0),t=ss(0,s.bl,b);s.co=mix3(e.co,s.co,t);s.ta=mix3(e.ta,s.ta,t)}return s};
/* ---------------- the rehearsals ----------------
Before a passage is shown it is run through once, in a second copy of the water, with a great many petals let fall at random
places and moments. Where each has got to when the water stops is read back; those that have ended inside the letters are kept
(one to each small patch of a letter, the earliest to fall), and in the performance only those are let fall - at the same
places and the same moments. The water does the same thing twice, so they end in the same places twice. The rehearsals go on
quietly behind the passages before. */
const rng=s=>()=>{s=s+0x6D2B79F5|0;let t=Math.imul(s^s>>>15,1|s);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296};
const offS=(x,y)=>Math.hypot(x-ST0[0],y-ST0[1])>ST0[2]+5; // not on the stone
const upl=(o,a,w,h)=>{raw0();gl.bindTexture(gl.TEXTURE_2D,o.t);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA32F,w,h,0,gl.RGBA,gl.FLOAT,a)};
const CAND=new Float32Array(NCW*NCH*4),CREL=data(NCW,NCH,CAND),RELS=[data(NPW,NPH,new Float32Array(NPW*NPH*4)),data(NPW,NPH,new Float32Array(NPW*NPH*4))];
// trial petals for passage k: where and when each falls. (This, and choosing the cast, are a good many ms of work: all at once they would hold a
// frame up, so both are done a little at a time.)
const seed=function*(k){const p=PS[k],r=rng(20261127+k*7919);
for(let i=0;i<NCW*NCH;i++){let c;do c=p.cand(r);while(!p.noSt&&!offS(c[0],c[1]));const j=i*4;CAND[j]=c[0];CAND[j+1]=c[1];CAND[j+2]=c[2];CAND[j+3]=r()*.998+.001;if(!(i&4095))yield}
upl(CREL,CAND,NCW,NCH)};
// the letters, as a picture to test places against. A word stands along the stream, or round the stone on an arc
const wordMap=W=>{const s=2,cv=document.createElement('canvas'),x=cv.getContext('2d'),f=p=>{x.font=`600 ${p}px "Helvetica Neue",Helvetica,Arial,sans-serif`};let px=W.h*s/.72;
if(W.arc){const A=W.arc,R=A.r+W.h,w=cv.width=cv.height=Math.round(2*R*s),rb=(A.r-W.h*.5)*s;f(px);x.fillStyle='#fff';x.textAlign='center';x.textBaseline='alphabetic';
const ws=[...W.t].map(c=>x.measureText(c).width+px*.16);let a=-ws.reduce((u,v)=>u+v,0)/rb/2;
[...W.t].forEach((c,i)=>{a+=ws[i]/rb/2;x.save();x.translate(w/2,w/2);x.rotate(a);x.fillText(c,0,-rb);x.restore();a+=ws[i]/rb/2});
return{d:x.getImageData(0,0,w,w).data,w,h:w,s,x0:A.cx-R,y0:A.cy-R}}
const w=cv.width=(W.x1-W.x0)*s,h=cv.height=Math.round(W.h*1.5*s),g=p=>{f(p);try{x.letterSpacing=p*.14+'px'}catch(e){}};
g(px);const m=x.measureText(W.t).width;if(m>w*.97){px*=w*.97/m;g(px)}
x.fillStyle='#fff';x.textAlign='center';x.textBaseline='middle';x.fillText(W.t,w/2+px*.07,h/2+px*.04);
return{d:x.getImageData(0,0,w,h).data,w,h,s,x0:W.x0,y0:W.yc-h/(2*s)}};
const inWord=(M,x,y)=>{const cx=Math.floor((x-M.x0)*M.s),cy=M.h-1-Math.floor((y-M.y0)*M.s);return cx>=0&&cy>=0&&cx<M.w&&cy<M.h&&M.d[(cy*M.w+cx)*4+3]>127};
// choose the cast of passage k from where the trial petals ended (fin)
const TKN=new Uint16Array(600*300);let tkn=0;PS.forEach(p=>{p.M=wordMap(p.W)});
const cast=function*(k,fin){const p=PS[k],M=p.M,r=rng(7+k),A=new Float32Array(NPW*NPH*4),N=NCW*NCH;let ord=[],out=[],bs=3.5*p.ps,n=0;
for(let i=0;i<N;i++){if(fin[i*4+3]>0&&inWord(M,fin[i*4],fin[i*4+1]))ord.push(i);if(!(i&16383))yield}
if(!p.any){const key=Float64Array.from(ord,i=>CAND[i*4+2]*N+i);yield;key.sort();yield;ord=Array.from(key,v=>v%N)} // the earliest to fall have been longest in the water
for(;;bs*=1.08){if(++tkn>65535){TKN.fill(0);tkn=1}out=[];for(const i of ord){const q=Math.floor(fin[i*4]/bs)+600*Math.floor(fin[i*4+1]/bs);if(TKN[q]!=tkn){TKN[q]=tkn;out.push(i)}}yield;if(out.length<=1500)break} // one to each small patch, the patches made bigger until there are few enough
for(let j=0;j<NPW*NPH;j++)A[j*4+2]=1e9;
for(const i of out)A.set(CAND.subarray(i*4,i*4+4),4*n++);
// a few that end near by but in no letter, so that the water round the word is not swept bare
if(p.stray!==0)for(let j=0,c=0;j<6000&&c<50;j++){const i=Math.floor(r()*N),x=fin[i*4],y=fin[i*4+1];let ok=fin[i*4+3]>0&&x>M.x0-80&&x<M.x0+M.w/M.s+80&&y>M.y0-70&&y<M.y0+M.h/M.s+70;
for(let a=-1;a<2&&ok;a++)for(let e=-1;e<2;e++)if(inWord(M,x+a*14,y+e*14))ok=0;if(ok){A.set(CAND.subarray(i*4,i*4+4),4*n++);c++}}
yield;
// and the ones that are only passing
if(p.amb)for(let j=0;j<p.nAmb&&n<NPW*NPH;j++){const c=p.amb(r);if(c&&offS(c[0],c[1]))A.set([c[0],c[1],c[2],r()*.998+.001],4*n++)}
p.rel=A;p.fb=0;p.nw=out.length;p.fin=out.map(i=>[fin[i*4],fin[i*4+1]]);
p.land=[];for(let j=0;j<n;j++)p.land.push([A[j*4+2],A[j*4],A[j*4+1]]);p.land.sort((a,b)=>a[0]-b[0])}; // when and where each lands, for the rings
// A passage whose turn comes before its rehearsal is done (a slow graphics card, or a jump) goes on all the same, with petals let fall anyhow:
// they spell nothing this time round. Its rehearsal is finished later, for the next time.
const uncast=k=>{const p=PS[k],r=rng(99+k),A=new Float32Array(NPW*NPH*4);let n=0;
for(let j=0;j<NPW*NPH;j++)A[j*4+2]=1e9;
for(let j=0;j<700;j++){const c=p.cand(r);if(p.noSt||offS(c[0],c[1]))A.set([c[0],c[1],c[2],r()*.998+.001],4*n++)}
p.rel=A;p.fb=1;p.nw=0;p.fin=[];p.land=[];for(let j=0;j<n;j++)p.land.push([A[j*4+2],A[j*4],A[j*4+1]]);p.land.sort((a,b)=>a[0]-b[0])};
const TM=[0];let rk=-1,rn=0,prio=-1,nst=0,nrs=0,job=null,rdb=null,rdebt=0,cur=-1; // (nst, nrs: steps taken so far, of the water shown and of the rehearsals)
const pick=()=>{if(prio>=0&&(!PS[prio].rel||PS[prio].fb))return prio;const k=PS.findIndex(p=>!p.rel);return k<0?PS.findIndex((p,j)=>p.fb&&j!=cur):k};
// What goes with a rehearsal besides its steps - seeding it, collecting where the trial petals ended, choosing the cast - is seen to at the very
// beginning of a frame, before the card has been given anything new to do, and a few ms of it at a time.
const chore=()=>{
if(rdb){const u=performance.now();if(rdb()){rdb=null;TM.push(performance.now()-u)}}
else if(job){const t=performance.now();do{const u=performance.now();if(job.next().done){job=null;break}TM[0]=Math.max(TM[0],performance.now()-u)}while(performance.now()-t<2.5)}};
// some more of whatever is next to be rehearsed (m: how much work, in steps of the solver). True when nothing is left to rehearse.
const rehearse=m=>{
if(job||rdb)return 0;
if(rk<0){rk=pick();if(rk<0)return 1;rn=0;calm(FB);zero(CT.a);zero(CT.b);job=seed(rk);return 0}
const p=PS[rk],c=p.cost||1;
for(;m>0&&rn<p.len;m-=c,rn++,nrs++){const w=p.water(rn);p.flow(FB,w,rn);petals(CT,CREL,FB,w.Q,rn)}
if(rn>=p.len){const k=rk;rdb=peekLater(CT.a,NCW,NCH,a=>{job=(function*(){yield*cast(k,a);rk=-1})()})}
return 0};
// How fast the rehearsals must go (in steps of the solver a second) for each passage still to come to have been rehearsed five seconds before
// its turn comes. Time during which the passage being shown needs no solving counts in full, the rest for a third of that: so most of the work is
// done while the card has least else to do.
const WGT=k=>PS[k].flow==solve||k==4?.35:1,
eff=(t,d)=>{let e=0;t%=LEN;for(let i=0;i<16&&d>1e-6;i++){let j=0;while(j<6&&t*SPS>=PS[j].s1-1e-6)j++;const sp=Math.max(1e-3,Math.min(d,PS[j].s1/SPS-t));e+=sp*WGT(j);d-=sp;t+=sp;if(t>=LEN-1e-3)t=0}return e},
rate=(mt,k)=>{const L=[];PS.forEach((p,j)=>{if(!p.rel||p.fb)L.push([((p.s0/SPS-mt)%LEN+LEN)%LEN||LEN,j])});L.sort((a,b)=>a[0]-b[0]);
let u=0,r=0;for(const[d,j]of L){const p=PS[j];u+=(j==rk?p.len-rn:p.len)*(p.cost||1);r=Math.max(r,u/eff(mt,Math.max(.3,d-5)))}return r*WGT(k)};
// in still water a petal ends where it falls: no rehearsal needed for the first passage
{for(const _ of seed(0));const f=new Float32Array(CAND);for(let i=3;i<f.length;i+=4)f[i]=1;for(const _ of cast(0,f));}
/* ---------------- words ---------------- */
const TOUCH='ontouchstart' in window&&!matchMedia('(hover:hover)').matches,TXo={t:gl.createTexture()},XC=document.createElement('canvas'),X=XC.getContext('2d');
// the bed, drawn once (see BED)
const BEDT=(()=>{const n=TIER>1?1024:2048,o=fld(n,n,[gl.RGBA8,gl.RGBA,gl.UNSIGNED_BYTE],1,2);pass(PBED,o,{uR:[n,n]});raw0();gl.bindTexture(gl.TEXTURE_2D,o.t);
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_LINEAR);gl.generateMipmap(gl.TEXTURE_2D);return o})();
raw0();gl.bindTexture(gl.TEXTURE_2D,TXo.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);
// the equation: its terms, and what each is called
const EQ=[['∂u/∂t','change'],['+'],['(u·∇)u','inertia'],['='],['−∇p','pressure'],['+'],['ν∇²u','viscosity'],['+'],['f','force']];
let sc=1,scMax=1,scMin=.3,sc0=1.4,S=null,S2=null,S3=null,B=[],txt='',txtDirty=1;const ONE=[1,1];
const drawText=T=>{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=T.dk?'#222':'#fff';X.textBaseline='middle';X.shadowColor=T.dk?'rgba(255,255,255,.6)':'rgba(0,0,0,.8)';X.shadowBlur=h*.014;
let ls=0;const sans='"Helvetica Neue",Helvetica,Arial,sans-serif',mono='ui-monospace,Menlo,Consolas,monospace',serif='"Times New Roman",Times,serif',sp=v=>{ls=h*v;try{X.letterSpacing=ls+'px'}catch(e){}},
put=(s,f,x,y,a)=>{if(s){X.font=f;const m=X.measureText(s).width,mx=(X.textAlign=='left'?w-x:X.textAlign=='right'?x:w)-h*.05,k=Math.min(1,mx/m*.98),l=ls;
if(k<1){X.font=f.replace(/([\d.]+)px/,(q,z)=>z*k+'px');try{X.letterSpacing=l*k+'px'}catch(e){}} // a line too long for a narrow screen is set smaller
X.globalAlpha=a||1;X.fillText(s,x,y);X.globalAlpha=1;if(k<1)try{X.letterSpacing=l+'px'}catch(e){}}};
X.textAlign='center';sp(.09);put(T.big,`200 ${h*.13}px ${sans}`,w/2+h*.045,h*.45);
sp(.008);put(T.sub,`400 ${h*.026}px ${mono}`,w/2,h*.6);put(T.sub2,`400 ${h*.02}px ${mono}`,w/2,h*.65,.75);
X.textAlign='left';
put(T.a,`400 ${h*.024}px ${mono}`,h*.062,h*.085,.92); // a line about what the water is doing
if(T.eq!=null){sp(.002);let x=h*.062;const f=`italic 400 ${h*.036}px ${serif}`;X.font=f; // the equation, with the term this passage is about lit
for(let i=0;i<EQ.length;i++){const e=EQ[i],on=i==T.eq,m=X.measureText(e[0]).width;X.font=f;X.globalAlpha=on||T.eq=='all'?1:.36;X.fillText(e[0],x,h*.895);
if(on){X.globalAlpha=.85;X.font=`400 ${h*.017}px ${mono}`;X.textAlign='center';X.fillText(e[1],x+m/2,h*.94);X.textAlign='left';X.font=f}
x+=m+h*.016}X.globalAlpha=1}
X.textAlign='right';sp(.008);put(T.re,`300 ${h*.04}px ${mono}`,w-h*.062,h*.89);put(T.re&&'Reynolds number',`400 ${h*.017}px ${mono}`,w-h*.062,h*.94,.85);
raw0();gl.bindTexture(gl.TEXTURE_2D,TXo.t);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,XC)};
/* ---------------- measuring ----------------
A readout in the corner, brought up to date once a second: how many frames were drawn, in how many of them the picture's clock
had moved on, and how long the longest took. M, or a tap on it, opens the rest: how many steps the water took and how far it
was behind the music; what this graphics card takes for each part of the work (found once, before the first frame) and which
setting that led to; how big the picture is drawn, and how much of what the card can do is in use; how unevenly the sound's
clock comes in; and the frames a second of each passage so far. Another tap puts it all away. While the piece plays it only counts. */
const HU=document.getElementById('h'),PF=[0,0,0,0,0,0,0],PT=[0,0,0,0,0,0,0],M={t:0,n:0,w:0,js:0,st:0,rs:0,bh:0,cj:0,mv:0},CAL={},
GPU=(()=>{const e=gl.getExtension('WEBGL_debug_renderer_info');return(''+gl.getParameter(e?e.UNMASKED_RENDERER_WEBGL:gl.RENDERER)).replace(/^ANGLE \((.*)\)$/,'$1').replace(/, Unspecified Version$/,'').slice(0,52)})(),
hset=v=>{hud=v;HU.textContent='';HU.style.background=v?'rgba(0,0,0,.42)':'none'},hnext=()=>hset(hud==1?2:hud?0:1),f1=v=>v.toFixed(1); // (1 the one line, 2 all of it, 0 put away)
let hud=1,pmt=0,pa=0,LOG=null,sm=1,ck=0,dv=Math.max(1,UQ.get('div')|0),fr=0;
HU.addEventListener('pointerdown',hnext);
addEventListener('keydown',e=>{const c=e.key.toLowerCase();if(c=='m')hnext();if(c=='c')sm=!sm}); // (C: the sound's clock as it comes, or evened out - to compare)
hset(1);
/* ---------------- the frame ---------------- */
// The picture is drawn into sheets made once, big enough for its largest size: a change of size is then only a change of how much of them is used
// (making new ones each time held a frame up). Only the small ones for the glow are made again.
const alloc=()=>{let w=Math.max(2,Math.min(S.W,W*sc|0)),h=Math.max(2,Math.min(S.H,H*sc|0));for(const o of[S,S2,S3]){o.w=w;o.h=h}
B.forEach(free);B=[];for(let i=0;i<[6,6,4,2][TIER];i++){w=Math.max(1,w>>1);h=Math.max(1,h>>1);B.push(fld(w,h,F4,1))}};
const resize=()=>{const d=Math.min(devicePixelRatio||1,TIER>1?1.5:2);W=C.width=Math.max(2,(C.clientWidth||innerWidth)*d|0);H=C.height=Math.max(2,(C.clientHeight||innerHeight)*d|0); // (on a screen taller than 16:9 the picture is a band across it)
scMax=Math.min(1,Math.sqrt(3.6e6/(W*H)));scMin=Math.min(scMax,Math.max(.3,Math.sqrt((TIER>2?1.3e5:2.2e5)/(W*H))));sc=cl(Math.sqrt(sc0*1e6/(W*H)),scMin,scMax);
[S,S2,S3].forEach(free);const w=Math.max(2,Math.ceil(W*scMax)),h=Math.max(2,Math.ceil(H*scMax)),mk=()=>{const o=fld(w,h,F4,1);o.W=w;o.H=h;return o};S=mk();S2=mk();S3=mk();alloc();txtDirty=1}; // start modest (sc0: so many million points, less on a slow card), grow if there is room
addEventListener('resize',resize);resize();
const CW={};let wAvg=0,inkOn=1,simN=0,inkN=0,lp=0,pi=0,old=null,wNow=null,lt=0,frames=0,dbg=-1,freeT=null,md=0,scv=1,ft=1/60,fade=0,hold=0,tmin=.05,pdt=.05,lf=0,lfF=0,ext=0,cK=0,cK0=0,cG=.015,cG0=.015,tF=-9,kf=1,kfT=0,kfD=20,camO=null,fix=0,stdy=0,lat=0,rsDirty=0,sfT=0,sfD=1,sfL=0;
// a passage begins: the water at rest, its petals still to fall; the last passage's petals are kept, to sink
const enter=(k,seq)=>{const p=PS[k];PF[k]=PT[k]=0;
if(seq&&cur>=0)old={k:cur,X:PTS[pi],rel:RELS[pi]};else{old=null;zero(DY.a);zero(DY.b);zero(RP.a);zero(RP.b)}
pi^=1;cur=k;simN=inkN=lp=sfT=sfL=0;sfD=inkOn=1;wNow=null;calm(FA);zero(PTS[pi].a);zero(PTS[pi].b);zero(SF.a);zero(SF.b);zero(SFM);zero(PRS.a);zero(PRS.b);upl(RELS[pi],p.rel,NPW,NPH);if(p.init)p.init()};
// one step of the passage that is being shown
const one=()=>{const p=PS[cur],w=p.water(simN);p.flow(FA,w,simN);petals(PTS[pi],RELS[pi],FA,w.Q,simN);
const dr=p.drops&&p.drops(simN)||[];
if(!p.mode)for(;lp<p.land.length&&p.land[lp][0]<=simN;lp++)if(p.land[lp][0]==simN&&dr.length<8)dr.push([p.land[lp][1],p.land[lp][2],.03,4.5]);
ripple(dr);for(let i=1;i<RSB;i++)ripple([]);rsDirty=1;simN++;nst++;return w}; // (the rings move sixty times a second, whatever the water does - except on the slowest cards)
const dye=(w,n)=>{const p=PS[cur],o=p.dye&&p.dye(w,n,simN-1);if(o)ink(FA,w.Q,n,{...DQ(),...o});inkOn=o?1:0;inkN=simN};
// the petals of one set, into whatever is being drawn
const pet=(X,rel,cam,o)=>{use(PPET);gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA);su(PPET,{uQ:X.a,uRel:rel,uU:FA.UV,uAsp:W/H,uFl:FL,...cam,...o});gl.drawArrays(gl.TRIANGLES,0,NPW*NPH*6);gl.disable(gl.BLEND)};
// the picture: the water from above, or from under, or both with the surface crossing the lens, or the print; then the glow, and the words
const draw=(k,b,s,w,t,mt,run,fo,xa,tau,tp,dk)=>{const p=PS[k],q=old&&PS[old.k],sk=ss(0,1.7,b),under=s.wl>=1,both=s.wl>0&&s.wl<1,rs=s.rst||w.Q,
sets=[[PTS[pi],RELS[pi],p.mode|0,{uNf:run?simN+tp:0,uTp:tp,uSk:0,uPs:p.ps,uTn:p.mode?.35:0,uPp:0}]];
if(q&&sk<1)sets.push([old.X,old.rel,q.mode|0,{uNf:1e7,uTp:0,uSk:sk,uPs:q.ps,uTn:.6*sk+(q.mode?.35:0),uPp:0}]);
const base={uR:[S.w,S.h],uT:run?mt:t%1e3,uGn:[NX,NY],uFv:s.fv||1.9,uEx:P.ex,uU:FA.UV,uUi:w.Q.uUi,uTau:tau,uD:DY.a};
gl.disable(gl.BLEND);
if(!under){const cam={uCo:s.co,uCm:{m:look(s.co,s.ta,s.up)},uSt:rs.uSt,uNs:rs.uNs,uNb:{i:1},uMd:{i:0}};
pass(PPND,S,{...base,...cam,uSf:TIER>2&&sfL?SF.a:SFM,uRs:RS,uBed:BEDT,uRk:P.rk,uHs:P.hk/Math.max(w.U*w.U,.12*(p.uref||P.U)**2),uInk:P.ink*(s.ink==null?1:s.ink),uBd:P.bd,uUw:w.U*SPS*CELL,uMist:P.mist,
uMk:p.mk||MKS,uMy:p.mk?110:14,uSa:s.sa||0,uAt:s.at||0,uAb:s.ab||Z16,uPy:s.py||0});
for(const e of sets)if(!e[2])pet(e[0],e[1],{...base,...cam},e[3])}
if(under||both){const cam={uCo:s.uco,uCm:{m:look(s.uco,s.uta)},uSt:Z36,uNs:{i:0},uNb:{i:0},uMd:{i:1}},T2=under?S:S2;
pass(PUND,T2,{...base,...cam,uInk:P.ink*(s.uink==null?1:s.uink)});
for(const e of sets)if(e[2]){gl.bindFramebuffer(gl.FRAMEBUFFER,T2.f);pet(e[0],e[1],{...base,...cam},e[3])}}
let Hd=S;
const uK=[S.w/S.W,S.h/S.H],uM=[(S.w-.5)/S.W,(S.h-.5)/S.H];
if(both){pass(PWMX,S3,{uA:S,uB:S2,uR:[S.w,S.h],uK,uM,uWl:mix(-.08,1.08,s.wl),uT:t%1e3,uX:-1});Hd=S3}
if(s.px>0){const cam={uCo:s.co,uCm:{m:look(s.co,s.ta,s.up)},uSt:rs.uSt,uNs:rs.uNs,uNb:{i:0},uMd:{i:0}}; // the print
pass(PPRT,S2,{...base,...cam,uMk:p.mk||MKS});gl.bindFramebuffer(gl.FRAMEBUFFER,S2.f);pet(sets[0][0],sets[0][1],{...base,...cam},{...sets[0][3],uPp:1});
pass(PWMX,S3,{uA:S,uB:S2,uR:[S.w,S.h],uK,uM,uWl:0,uT:0,uX:s.px});Hd=S3}
// glow: down, then up again (adding)
let src=Hd;
for(let j=0;j<B.length;j++){const d=B[j];pass(PD,d,{uC:src,uR:[d.w,d.h],uI:[1/src.w,1/src.h],uK:j?ONE:uK,uM:j?ONE:uM,uTh:j?0:1});src=d}
gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE);
for(let j=B.length-1;j>0;j--){const d=B[j-1];pass(PU,d,{uC:B[j],uR:[d.w,d.h],uI:[1/B[j].w,1/B[j].h]},1)}
gl.disable(gl.BLEND);
pass(PC,null,{uC:Hd,uB:B[0],uX:TXo,uR:[W,H],uK,uM,uT:t%100,uF:fade*fo,uXa:xa,uBm:P.bm*(1+.3*K[0])*(1-.7*(s.px||0))});
};
const frame=now=>{
requestAnimationFrame(frame);if(++fr%(dv*kf))return;frames++; // (kf: every second refresh, or third, when the card cannot do better. dv: the same, for measuring)
const t=now/1e3,rdt=t-lt,dt=Math.min(.1,Math.max(.001,rdt)),j0=performance.now(),n0=nst,r0=nrs;lt=t;
chore();analyse(dt);
let run=0,mt=0,late=0,cj=1,fI=0,fS=0;
if(t0!=null&&ctx.state=='running'){lat+=((ctx.outputLatency||0)-lat)*(lat?.02:1); // (the latency reported wobbles: smooth it)
// The sound's clock comes in jumps, a buffer of sound at a time, so the picture does not read it directly: the frames' own clock runs on
// between the jumps, and is drawn slowly towards it. (C switches that off, to see the difference.)
const a=ctx.currentTime-t0-lat,e=a-(ck+=rdt);ck=Math.abs(e)>.25?a:ck+e*(1-Math.exp(-rdt/.7));cj=Math.abs(a-pa-rdt);pa=a;
mt=Math.max(0,sm?ck:a)%LEN;run=1}
if(freeT!=null){mt=(t-freeT)%LEN;run=1}
if(dbg>=0){mt=(dbg-B0)*BAR;run=1}
// Which passage, and how many steps into it. The water moves SPS times a second, as far as the music has. Where the display is faster
// than that the work is shared between frames - the water one frame, the ink the next - and the picture carries ink and petals on by the
// fraction of a step in between.
const G=mt*SPS+B0*SPB;let k=0;while(k<6&&G>=PS[k].s1)k++;
const p=PS[k],tgt=run?Math.floor(G)-p.s0:0;
if(k!=cur||tgt<simN-SPS/2){ // a new passage (or sent back in this one)
if(!p.rel&&dbg>=0){prio=k;late=1;rehearse(30)} // (while building, looking at one passage: its rehearsal first)
else{if(!p.rel)uncast(k);enter(k,k==(cur+1)%7&&tgt<SPS)}} // if its rehearsal is not done in time it goes on without its word
let a=0;
if(cur==k){
// The steps that are due. If the water has fallen far behind (a jump - or a card that cannot keep up) it catches up no faster than a frame allows.
const beh=tgt-simN,need=Math.ceil(SPS*tmin*kf),mx=Math.min(beh,dbg>=0?24:cl(Math.floor(1e3*tmin*kf/(1.3*CAL.step)),need,8)),sv=p.flow==solve||k==4;let w; // (need: the steps a frame must take to keep pace; more, to catch up, only if the card has time for them)
if(beh>4)late=1;
for(let j=0;j<mx;j++){w=one();a=1;if(late&&!(simN&1))dye(w,simN-inkN)}
if(a)wNow=w;
// The rest of the work - the ink, the pressure under the surface, the rehearsals of the passages to come (as fast as they must go to be
// ready in time) - is spread over the frames so that each has about the same to do: a frame takes what is most pressing, up to a little
// more than a frame's share of all that comes due (wAvg, reckoned in what each part takes on this card), and leaves the rest to the next.
// Ink and surface can wait a step or two - the picture carries them on meanwhile - but no longer.
const sfOn=sv&&(k!=4||simN>F0),r=run&&!late?rate(mt,k):0,nw=nst-n0,cs=(sfOn?CAL.step:0)+CAL.sm,ci=inkOn?CW.ik:0; // (cs, ci: what a step takes just now - little, where nothing is solved - and an inking, where there is ink)
rdebt=Math.min(6,rdebt+r*dt);
wAvg+=(nw*(cs+ci+(sfOn?CW.sf/SRN:0))+r*dt*CW.rh-wAvg)*(1-Math.exp(-dt/.4));
let used=nw*cs,nr=0;const A=Math.min(1.25*wAvg+.2*CW.st,800*tmin*kf),fits=c=>!used||used+c<=A, // (and never more than a frame has time for)
doInk=()=>{used+=ci;dye(wNow,simN-inkN);fI++},doSf=()=>{used+=CW.sf;surface(FA,wNow.Q);sfD=sfL?simN-sfT:1;sfT=simN;sfL=1;fS++};
if(inkN<simN&&(late||simN-inkN>1))doInk();
if(sfOn&&wNow&&simN-sfT>=(late?4:3*SRN))doSf();
if(frames<24); // (the first frames are left light, so that how often the display takes one can be seen)
else if(!run)rehearse(cl(Math.floor(28/(1.1*CAL.step)),1,24)); // (before the music starts: as much as leaves the title a fair picture)
else if(!late){while(rdebt>=nr+1&&(fits(CW.rh)||rdebt>=4&&!nr)){nr++;used+=CW.rh}if(nr){rdebt-=nr;rehearse(nr)}}
if(inkN<simN&&fits(ci))doInk();
if(sfOn&&wNow&&simN-sfT>=SRN&&fits(CW.sf))doSf();
if(rsDirty){rslope();rsDirty=0}
}
// what is shown lies between the last step and the next: the camera, like the petals, is carried on by the fraction of a step gone by
const w=wNow||p.water(0),tpf=run&&cur==k?cl(G-p.s0-simN,0,2):0,b=cur==k?(simN+tpf)/SPB:0,s=camO||view(k,b);
// Adaptive resolution, by frame pacing: tmin is this display's frame interval (the shortest seen that held steady for eight frames; the
// first couple of dozen frames are kept light so that it is seen at once). While frames arrive on time the picture grows a little now and
// then; when they start arriving late it shrinks. What it remembers is not a size but a load - the water's work and the picture's together,
// reckoned in what they took on this card before the start (cK: the most that is thought to fit) - so that when the water's share changes,
// as it does from passage to passage, the picture gives way at once instead of finding out by dropping frames. Late is judged over a
// second and a half (lf: the share of frames in it that came late): the odd late frame is chance, and so are the first moments.
// When frames first come late, that much is taken not to fit, the picture is made smaller, and the old size is tried for again only
// slowly. If that helps but not enough, smaller again. If it does not help - something else on the machine is making frames late - the
// lesson is mostly taken back and the picture left alone: a smaller one would be no smoother. Only when a third of the frames are late
// with the picture as small as it may be does it settle for every second refresh - evenly: a steady thirty a second looks better than
// forty-five that stumble - and it tries for more again after a while.
if(!late){if(run){ft+=(dt-ft)*.05;hold-=dt;lf+=((dt>1.5*tmin*kf?1:0)-lf)*(1-Math.exp(-dt/1.5))}if(Math.abs(dt-pdt)<.1*pdt){if(++stdy>7&&kf<2)tmin=Math.min(tmin*1.0005,pdt)}else stdy=0;pdt+=(dt-pdt)*(stdy?.2:1)}else stdy=0;
if(fix){if(sc!=Math.min(fix,scMax)){sc=Math.min(fix,scMax);alloc()}}
else if(hold<0&&frames>40&&run&&mt>4&&tmin<.04){hold=.5;if(!cK)cK=750*tmin*kf;
const tg=tmin*kf,fl=kf>1||tmin>.012?scMin:Math.max(scMin,Math.min(.5,scMax)), // (on a display faster than sixty a second, half size and every second refresh comes before anything smaller)
ppm=CAL.pic/CAL.mp,load=wAvg+ppm*S.w*S.h/1e6,fit=f=>cl(Math.sqrt(Math.max(0,f*cK-wAvg)/ppm*1e6/(W*H)),fl,scMax),lim=fit(.9),
less=()=>{cK=Math.min(cK,load);sc=Math.max(fl,Math.min(sc*.9,fit(.8)));alloc()};
if(lf>.06){const big=sc>fl*1.01;hold=1.5;
if(t-tF>4){cK0=cK;cG0=cG;ext=0;if(big){less();cG=Math.max(.001,cG*.4)}} // late, for the first time in a while
else if(big&&(lf<.7*lfF||lf>.5))less(); // still late, but less so than before - or badly: smaller again
else{if(!ext){ext=1;cK=Math.max(cK,.9*cK0);cG=cG0} // still late, and a smaller picture has not helped
if(!big&&lf>.3&&kf<2){kf++;cK*=2;cK0*=2;kfT=t+kfD;kfD=Math.min(120,kfD*2);ft=tmin*kf;pdt=ft;lf=.1}}
lfF=lf;tF=t}
else if(kf>1&&t>kfT){kf--;cK/=2;cK0/=2;sc=fl;alloc();ft=tmin*kf;pdt=ft;lf=0;hold=1.5} // (after a while, a try at the smallest picture on every refresh again)
else if(sc>lim*1.04){sc=lim;alloc();hold=1} // the water has more to do than it had: make room before frames are lost
else if(lf<.01){cG=Math.min(.015,cG*1.01);cK=Math.min(1150*tg,cK*(1+cG));if(sc<lim-.004){sc=Math.min(lim,sc*1.05);alloc();hold=1}}}
// words
const re=s.re||(w.Re==null?'':w.Re<9.95?w.Re.toFixed(w.Re<.05?0:1):''+Math.round(w.Re)),nr=PS.filter(q=>q.rel&&!q.fb).length,
T=run?{a:s.cap,eq:s.eq,re:'Re '+re,dk:s.px>.5}:{big:'LAMINAR',sub:TOUCH?'tap to start':'click to start \u00b7 F fullscreen',sub2:nr<7?'rehearsing the water '+nr+' of 7':''};
{const n=JSON.stringify(T);if(n!==txt||txtDirty){txt=n;drawText(T)}}
fade=Math.min(1,fade+dt*1.2);
const fo=run&&dbg<0?Math.min(1,(LEN-mt)/2,.1+mt/1.5):1,xa=run?.9:.8+.2*Math.sin(t*3);
if(sfL&&TIER<3)pass(PMIX,SFM,{uA:SF.b,uB:SF.a,uF:run&&cur==k?cl((G-p.s0-sfT)/sfD,0,1):1}); // the surface, between the last two findings of it (on the slowest cards: as last found)
if(md)pass(PDBG,null,{uD:DY.a,uW:FA.OM.a,uS:SFM,uR:[W,H],uMd:{i:md},uSc:scv});
else draw(k,b,s,w,t,mt,run,fo,xa,run&&cur==k?cl(G-p.s0-inkN,0,3):0,tpf);
// the readout
const js=performance.now()-j0,bh=!run||cur!=k?0:Math.max(0,tgt-simN),m=M;
if(LOG)LOG.push([t,rdt,k,simN,bh,sc,js,nst-n0,nrs-r0,mt,late,sm?1:0,kf,fI,fS,cK,wAvg,lf,ext]);
if(rdt<1){m.t+=rdt;m.n++;m.w=Math.max(m.w,rdt);m.bh=Math.max(m.bh,bh);m.st+=nst-n0;m.rs+=nrs-r0;m.js+=js;
if(run){PF[k]++;PT[k]+=rdt;if(cj<.25)m.cj=Math.max(m.cj,cj);if(mt-pmt>.002)m.mv++}
if(m.t>=1){
if(hud)HU.textContent=Math.round(m.n/m.t)+' fps drawn'+(run?', '+Math.round(m.mv/m.t)+' moved on':'')+' \u00b7 longest '+f1(m.w*1e3)+' ms'+(hud<2?'':'\n'+
'water '+Math.round(m.st/m.t)+' of '+SPS+' steps/s \u00b7 '+(m.bh>2?m.bh+' behind':'in step')+' \u00b7 rehearsed '+nr+' of 7'+(m.rs?', '+Math.round(m.rs/m.t)+'/s':'')+'\n'+
'this card: step '+f1(CAL.full)+(HG>1?' ('+f1(CAL.step)+' on the coarse grid)':'')+' \u00b7 ink '+f1(CAL.ink)+' \u00b7 surface '+f1(CAL.srf)+' \u00b7 picture '+f1(CAL.pic)+' ms at '+CAL.mp.toFixed(2)+' MP \u2192 setting '+TIER+'\n'+
'a drawing '+CAL.p0.toFixed(2)+' \u00b7 a pass of spreading '+CAL.p1.toFixed(2)+' \u00b7 petals '+f1(CAL.pet)+' + '+f1(CAL.sm)+' ms \u00b7 grid '+GW+'\u00d7'+GT+'\n'+
'picture '+S.w+'\u00d7'+S.h+' ('+Math.round(sc*100)+'%'+(kf>1?', every '+kf+' frames':'')+') \u00b7 ink \u00d7'+DS+' \u00b7 load '+(cK?Math.round(100*(wAvg+CAL.pic/CAL.mp*S.w*S.h/1e6)/cK)+'%':'-')+' \u00b7 script '+f1(m.js/m.n)+' ms\n'+
'clock '+(sm?'evened out':'as it comes')+', \u00b1'+f1(m.cj*1e3)+' ms \u00b7 sound '+(mode?mode[0]=='w'?'worklet':'main thread':'-')+(ctx?' '+ctx.sampleRate/1e3+' kHz':'')+'\n'+
'passages '+PF.map((n,i)=>PT[i]>.5?Math.round(n/PT[i]):'\u00b7').join(' ')+'\n'+GPU);
m.t=m.n=m.w=m.js=m.st=m.rs=m.bh=m.cj=m.mv=0}}
pmt=mt;
};
// Draw once with every program now, so that none of them is first built in the middle of the music; and time the other parts of the work on this card.
{const w=PS[3].water(900),Q=w.Q,w4=PS[4].water(Sb(1.1));
step(FA,{...Q,uBy:.01},.3);step(FA,Q,9);spin(FA,Q);sheet(FA,[0,1,1,0]);ink(FA,Q,1,DQ());petals(PTS[0],RELS[0],FA,Q,0);surface(FA,Q);ripple([]);rslope();pass(PMIX,SFM,{uA:SF.b,uB:SF.a,uF:1});
drawText({});draw(4,1.1,view(4,1.1),w4,0,0,1,1,0,0,0);draw(6,7,view(6,7),PS[6].water(Sb(7)),0,0,1,1,0,0,0);
CAL.step=CST;CAL.ink=timeIt(()=>ink(FB,Q,1,DQ()),()=>DY.a,70);CAL.srf=timeIt(()=>surface(FB,Q),()=>SF.a,70);CAL.pic=timeIt(()=>draw(3,8,view(3,8),w,0,0,1,1,0,0,0),()=>null);CAL.mp=S.w*S.h/1e6;
CAL.pet=timeIt(()=>petals(CT,CREL,FB,Q,0),()=>CT.a,40);CAL.sm=timeIt(()=>{petals(PTS[0],RELS[0],FA,Q,0);for(let i=0;i<RSB;i++)ripple([]);rslope()},()=>RS,40);
CAL.full=CS1;CAL.p0=CP0;CAL.p1=CP1;CW.st=CAL.step+CAL.sm;CW.ik=CAL.ink;CW.sf=CAL.srf;CW.rh=CAL.step+CAL.pet; // what a step of the water shown, an inking, a finding of the surface and a step of rehearsal each take
sc0=cl(6.5*CAL.mp/CAL.pic,.25,1.4); // a picture that takes about 6.5 ms to draw, to begin with (but no bigger than before)
calm(FA);calm(FB);for(const o of[DY,RP,PTS[0],CT,SF]){zero(o.a);zero(o.b)}zero(SFM);zero(RS);zero(PRS.a);zero(PRS.b);resize()}
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.LAM={errs,P,PS,SYN,peek:(n,x,y,w,h)=>peek({om:FA.OM.a,psi:FA.PSI.a,uv:FA.UV,sf:SFM,dy:DY.a,pr:PRS.a,pt:PTS[pi].a,rp:RP.a,tm:FA.TM.a}[n],x,y,w,h),
check(){const p=PS[cur],a=peek(PTS[pi].a,0,0,NPW,NPH);let m=0;for(let j=0;j<p.nw;j++)m=Math.max(m,Math.abs(a[j*4]-p.fin[j][0]),Math.abs(a[j*4+1]-p.fin[j][1]));return{n:p.n,nw:p.nw,maxDiff:m}},
get state(){return{cur,rk,rn,cast:PS.map(p=>p.rel?p.fb?-2:p.nw:-1),bar:cur<0?0:PS[cur].b0+simN/SPB,simN,inkN,sc,ft,tmin,kf,frames,mode,W,H,sw:S.w,ctx:ctx&&ctx.state,XF:!!XF,A:[...A],K:[...K],rdebt,cK,cG,lf,ext,wAvg}},
set seek(v){dbg=v;freeT=null},set md(v){md=v},set sc(v){scv=v},set cam(v){camO=v},set fix(v){fix=v},free(o){freeT=performance.now()/1e3-(o||0)*BAR;dbg=-1},
// measuring: hud (the readout on or off), smooth (the sound's clock evened out), div (draw only every so many frames), load (as if the card were so many times slower),
// rec (keep a line for every frame, read back with log), and bench: what each part of the work costs on this card (it spoils the water: reload after)
set hud(v){hset(v)},set smooth(v){sm=v},set div(v){dv=Math.max(1,v|0)},set load(v){burn=Math.max(0,Math.round(v)-1)},set rec(v){LOG=v?[]:null},get log(){return LOG},
get meter(){return{CAL,TIER,SPS,DS,SRN,HG,GW,GT,NL,sm,dv,burn,PF:[...PF],PT:[...PT],GPU,nst,nrs,hud,scMin,scMax,sc0,sr:ctx&&ctx.sampleRate,bl:ctx&&ctx.baseLatency,ol:ctx&&ctx.outputLatency,lat}},get ct(){return ctx?ctx.currentTime:0},
rate:(mt,k)=>rate(mt,k),TM,
// what each part of the work takes just now, in the passage being shown (go to a place with seek first): each done n times, then waited for
profile(n){n=n||16;const p=PS[cur],r={n:p.n,bar:+(simN/SPB).toFixed(2)},tm=(f,o)=>{f();wait(o());const t=performance.now();for(let i=0;i<n;i++)f();wait(o());return+((performance.now()-t)/n).toFixed(2)};let w;
r.step=tm(()=>{w=one()},()=>FA.OM.a);wNow=w;
r.ink=tm(()=>{const o=p.dye&&p.dye(w,1,simN-1);if(o)ink(FA,w.Q,1,{...DQ(),...o})},()=>DY.a);
r.surface=tm(()=>surface(FA,w.Q),()=>SF.a);
r.rehOf=rk;r.rehearsal=rk>=0&&!job&&!rdb?tm(()=>{const q=PS[rk];if(rn<q.len-1){const v=q.water(rn);q.flow(FB,v,rn);petals(CT,CREL,FB,v.Q,rn);rn++}},()=>CT.a):-1;
const b=simN/SPB,s=view(cur,b);r.picture=tm(()=>draw(cur,b,s,w,0,0,1,1,.9,0,0),()=>null);r.mp=+(S.w*S.h/1e6).toFixed(2);
return r},
bench(){const r={},F=FB,w=PS[3].water(Sb(8)),Q=w.Q,w5=PS[4].water(Sb(6)),T=(f,o)=>+timeIt(f,o).toFixed(3),om=()=>F.OM.a;
r.vcycle=T(()=>vcycle(F.PSI,F.OM.a,-1,Q),()=>F.PSI.a);r.vel=T(()=>pass(PVEL,F.UV,{uP:F.PSI.a,...Q}),()=>F.UV);
r.frc=T(()=>{pass(PFRC,F.OM.b,{uW:F.OM.a,uP:F.PSI.a,uTm:F.TM.a,...Q});swap(F.OM)},om);
r.adv=T(()=>{pass(PADV,F.OM.b,{uW:F.OM.a,uU:F.UV,uDt:1,...Q});swap(F.OM)},om);
r.dif=T(()=>spread(F,Q,.4),om);r.dif5=T(()=>spread(F,Q,2.1),om);r.thick_nu4=T(()=>spread(F,Q,4.3),om);r.thick_nu13=T(()=>spread(F,Q,13),om);r.thick_nu26=T(()=>spread(F,Q,26),om);
r.tmp=T(()=>{pass(PTMP,F.TM.b,{uTm:F.TM.a,uU:F.UV,...w5.Q});swap(F.TM)},()=>F.TM.a);
r.step=T(()=>step(F,Q,.4),om);r.step_force=T(()=>step(F,w5.Q,.1),om);r.spin=T(()=>spin(F,Q),()=>F.UV);
r.petals_131k=T(()=>petals(CT,CREL,F,Q,0),()=>CT.a);r.petals_2k=T(()=>petals(PTS[pi^1],RELS[pi^1],F,Q,0),()=>PTS[pi^1].a);
r.surface=T(()=>surface(F,Q),()=>SF.a);r.ink=T(()=>ink(F,Q,1,DQ()),()=>DY.a);r.rings=T(()=>{ripple([]);rslope()},()=>RS);
r.picture=T(()=>draw(3,8,view(3,8),w,0,0,1,1,0,0,0),()=>null);r.mp=S.w*S.h/1e6;
rk=-1;job=rdb=null;return r}};
})();
</script>
</body>
</html>