this logo: 245 b

← PERIHELION v1

index.html

<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>PERIHELION</title>
<meta name=viewport content="width=device-width,initial-scale=1">
<style>html,body{margin:0;height:100%;background:#000;overflow:hidden}canvas{display:block;width:100vw;height:100vh;cursor:pointer}</style>
</head>
<body>
<canvas id=c></canvas>
<script>
/* PERIHELION - the point of an orbit nearest the Sun.
   The Sun first, in eight bands of light from the visible to x-rays, and a flare. Then out through the planets, and the years
   run: five things that came through, each on its real orbit. Halley in 1986, with its two tails and Giotto's pass of the
   nucleus. Shoemaker-Levy 9, pulled into a string of pearls by Jupiter's tide in 1992 and falling into it in 1994. ISON,
   which did not survive the Sun in 2013. 'Oumuamua, from another star, swung round the Sun's gravity well in 2017. Apophis,
   which will pass inside the geostationary ring in 2029 and leave on a different orbit. Then the years run on to 2061.
   Ray-marched bodies, a hundred thousand points placed by Kepler's equation in the vertex shader, a lens flare that knows
   how much of the Sun is showing, and a soundtrack synthesised as it plays: a piano alone, then drums, strings and a voice.
   No assets, no dependencies.
   Keys: F fullscreen. Drop an audio file to use your own music. */
(()=>{
'use strict';

/* ---------------- synth (runs inside an AudioWorklet) ---------------- */
function SYN(sr){
const TAU=6.283185307179586,T=1/sr,S16=sr*15/140,LEN=1472,mf=n=>440*2**((n-69)/12),dc=s=>Math.exp(-1/(sr*s));
let rs=22222;const rnd=()=>{rs^=rs<<13;rs^=rs>>>17;rs^=rs<<5;return(rs>>>0)/2147483648-1};
// TPT state variable filter: returns low-pass, leaves band-pass in s[2]
const svf=(s,x,fc,k)=>{const g=Math.tan(Math.PI*Math.min(fc,sr*.45)*T),h=1/(1+g*(g+k)),v3=x-s[1],v1=h*s[0]+g*h*v3,v2=s[1]+g*h*s[0]+g*g*h*v3;s[0]=2*v1-s[0];s[1]=2*v2-s[1];s[2]=v1;return v2};
const saw=(p,d)=>{let v=2*p-1;if(p<d){const t=p/d;v-=t+t-t*t-1}else if(p>1-d){const t=(p-1)/d;v-=t*t+t+t+1}return v};
// Seventy beats a minute, slow and heavy; the grid underneath runs at twice that, so a bar of the picture is half a bar of the music.
// It opens on a piano alone, one high note struck over and over; then drums and a sub-bass, strings, and at the two climaxes a voice
// that is really a saw pushed through two moving formants and overdriven. D minor. A chord lasts one bar of music:
// [bass root, four string notes]. C1 is the main cycle, C2 the darker one under Jupiter.
const C1=[[38,50,53,57,62],[34,46,50,53,58],[41,48,53,57,60],[36,48,52,55,60]],     // Dm Bb F C
 C2=[[38,50,53,57,62],[31,46,50,55,58],[34,46,50,53,58],[33,49,52,57,61]],          // Dm Gm Bb A
 HS=[0,16,24,30,36,48,52,60,62,66,74,82,84],                                         // bars of the picture where the cycle starts over
 PN=[[81,81],[77,79],[81,81],[79,76]],PM=[[81,81],[79,82],[77,74],[76,73]],          // the piano's note over each chord, and the one it turns to as the bar ends
 PR=['x.xx.x.x','x..x.xa.','x.xx.x.x','x.x.x.aa'],                                   // its rhythm in eighths: x the note, a the other
 V1=[69,0,0,72,74,0,0,0,77,0,0,0,0,74,72,0,69,0,72,0,69,67,0,0,64,0,67,0,72,0,0,74],  // the voice, an eighth at a time: a note to slide to, 0 hold, -1 let go
 V2=[74,0,77,0,81,0,0,0,79,77,0,0,74,0,0,0,72,0,77,0,81,0,0,79,76,0,0,0,74,72,0,0],
 V3=[69,0,0,0,74,0,0,0,77,0,0,0,0,0,74,0,69,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0],
 KK=[0,14,20],KH=[0,6,14,20,22],                                                     // kicks in a bar of music (32 steps); the snare answers on 8 and 24
 ZS=[[28.5,86],[46,62],[54,86],[56,81],[58,89],[70,62]],                             // a change of wavelength away from the Sun: a note for it
 IS=[[14,1],[16,.5],[24,.5],[36,.7],[44,.7],[44.5,.6],[45,.7],[45.5,.6],[46,.7],[46.5,.6],[47,.7],[47.5,.7],[52,1],[55,.9],[56,1],[60,.6],[66,.5],[74,1],[82,.8],[84,.5]],   // impacts
 WS=[[33.2,2],[39,2],[53,1.6],[67.6,2.4],[77.2,2.6]];                                 // fly-bys: [bar it starts, bars it lasts]
let pos=0,nx=0,st=-1,mg=1,
 kt=-1,kp=0,klv=1,ce=-1,clv=0,he=0,hd=.99,hl=0,hsw=0,hpe=0,
 se=0,sf=73,sft=73,sph=0,slv=0,
 pc=600,pct=600,plv=0,plt=0,
 pv=0,thk=0,
 lf=440,lft=440,lph=0,lon=0,len=0,lag=0,
 dlv=0,dlt=0,dp1=0,dp2=0,
 ckd=0,cke=0,ckp=0,
 wt=-1,wd=1,
 it=-1,ip=0,ilv=0,
 ris=0,ri=0,rph=0,
 di=0,dlp=0,drp=0;
const F=()=>new Float64Array(3),pL=F(),pR=F(),ws=F(),rz=F(),rm=F(),sn=F(),im=F(),th=F(),f1=F(),f2=F(),f3=F(),
 pf=new Float64Array([147,175,220,294,147]),pt=new Float64Array(5),pp=new Float64Array(10);
const hdo=dc(.12),hdc=dc(.022),ckc=dc(.004),sdc=dc(.75),thd=dc(.005);
// the piano: eight voices of six partials, each partial a point turning in a circle and spiralling in - no sines to compute per sample
const NV=8,NP=6,qr=new Float64Array(NV*NP),qi=new Float64Array(NV*NP),qc=new Float64Array(NV*NP),qs=new Float64Array(NV*NP),qd=new Float64Array(NV*NP),qa=new Float64Array(NV),qp=new Float64Array(NV);
const key=(n,v)=>{const f=mf(n),o=pv*NP;qa[pv]=v;qp[pv]=Math.max(-.25,Math.min(.25,(n-64)/80));pv=(pv+1)%NV;thk=Math.max(thk,v);
 for(let k=0;k<NP;k++){const K=k+1,fk=f*K*Math.sqrt(1+.0006*K*K);                   // stiff strings: the partials run a little sharp
  qr[o+k]=0;qi[o+k]=fk<sr*.45?v*(k?.7:1)/K**1.25:0;qc[o+k]=Math.cos(TAU*fk*T);qs[o+k]=Math.sin(TAU*fk*T);qd[o+k]=dc(1.3/K**.7*(440/f)**.5)}};
// stereo delay (dotted eighth of the fast grid) and a Freeverb-style reverb
const DN=Math.round(S16*3),dL=new Float32Array(DN),dR=new Float32Array(DN);
const mk=(a,o)=>a.map(n=>new Float32Array(Math.round((n+o)*sr/44100)));
const cl=[1116,1188,1277,1356,1422,1491,1557,1617],al=[556,441,341,225];
const cL=mk(cl,0),cR=mk(cl,23),aL=mk(al,0),aR=mk(al,23),ci=new Int32Array(16),ai=new Int32Array(8),cf=new Float64Array(16);
const verb=(x,C,A,o)=>{let y=0;
 for(let j=0;j<8;j++){const b=C[j],q=o*8+j,i=ci[q],v=b[i];cf[q]=v*.75+cf[q]*.25;b[i]=x+cf[q]*.9;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 trig=()=>{
 const s=st&15,bar=st>>4,x=bar+s/16;
 let k=0;while(k<12&&HS[k+1]<=bar)k++;
 let i=(bar-HS[k]>>1)&3;if(bar>=48&&bar<52)i=i+2&3;if(bar>=84&&i>1)i=0;
 const two=bar>=36&&bar<52,c=(two?C2:C1)[i],s32=((bar-HS[k])&1)*16+s,                 // where we are in the bar of music
  beat=x>=16&&x<27||x>=30&&x<36||x>=38&&x<42||x>=52&&x<58||x>=66&&x<72||x>=74&&x<82,
  heavy=x>=52&&x<58||x>=74&&x<82,thin=x>=27&&x<30||x>=36&&x<38||x>=58&&x<60,hit=x>=44&&x<48;
 mg=x>89.5?Math.max(0,(92-x)/2.5):1;
 // the Sun: a drone, a rumble and static. They come back whenever we are near it
 dlt=x<16?.55:x>=48&&x<60?.35:x>=62&&x<66?.4:.06;
 ckd=x<14?.6:x<16?5:x>=50&&x<60?2:x>=35&&x<36?9:0;
 // strings: the chord and, under it, its root
 for(let j=0;j<4;j++)pt[j]=mf(c[j+1]);pt[4]=mf(c[0]+12);
 plt=x<24?0:x<27?.6:x<44?.8:x<48?.85:x<60?1:x<62?.3:x<66?.45:x<84?heavy?1:.8:Math.max(.3,(92-x)/8);
 pct=heavy?2600:x>=44&&x<52?700*3.5**((x-44)/8):x>=84?1500*.3**((x-84)/8):x>=60&&x<66?650:1300;
 // drums: kick and snare, hats in eighths with a late sixteenth between them
 if(beat&&(heavy?KH:KK).includes(s32)||hit&&!(s&7)){kt=0;kp=0;klv=1;se=1;sft=mf(c[0])}
 if(beat&&(s32==8||s32==24)){ce=0;clv=heavy?.75:.62}
 if(x>=51&&x<52||x>=73.5&&x<74){ce=0;clv=.1+.3*(x<52?x-51:(x-73.5)*2)}
 if((beat||thin)&&!(s&1)){const g=beat?1:.55;if(s&3){hsw=Math.round(S16*.3);hpe=.22*g}else{he=.5*g;hd=beat&&s32==28?hdo:hdc}}
 // sub-bass: struck with the kick, and held where there is no kick to strike it
 if(!s32&&(thin||x>=60&&x<66||x>=82&&x<90)){se=.8;sft=mf(c[0])}
 slv=beat||hit?1:thin?.6:x>=60&&x<66||x>=82?.7:0;
 // the piano
 if(!(s&3)&&(x<44||x>=52)){const r=PR[i][s32>>2],v=x<16?.5+.02*x:x>=84?Math.max(.25,.7-.05*(x-84)):beat?.62:.72;
  if(r!='.')key((two?PM:PN)[i][r=='a'?1:0],v);
  if(!s32&&x>=8)key(c[0]+12,v*.8)}
 if(x>=12&&x<14&&!(s&1)){const j=st>>1&15;key(74+[0,3,5,7,10,12,15,17][j<8?j:15-j],.3)}        // eight wedges of light, eight notes
 if(hit&&!(s&7)){key(38,.5);key(50,.4)}                                                          // each impact
 if(x>=48&&x<52&&!(s%(x<50?4:x<51?2:1)))key(x>=51.5&&s&1?86:81,.3+.14*(x-48));                    // one note, faster and faster
 if(x>=72&&x<74&&!(s%(x<73?2:1)))key(81,.35+.2*(x-72));
 for(const z of ZS)if(z[0]*16==st){key(z[1],.6);key(z[1]-12,.4)}
 // the voice
 if(!(s&3)){const a=x>=52&&x<60?V1:x>=74&&x<82?V2:x>=84?V3:0,n=a?a[(bar-(x<60?52:x<82?74:84))*4+(s>>2)]:-1;
  if(n>0){lft=mf(n);if(lon<.5)lf=lft*.92;lon=1;lag=0}else if(n<0)lon=0}
 for(const z of IS)if(z[0]*16==st){it=0;ip=0;ilv=z[1]}
 for(const z of WS)if(Math.round(z[0]*16)==st){wt=0;wd=z[1]*240/140}
 ris=x>=14&&x<16?(x-14)*.3:x>=34.5&&x<36?(x-34.5)*.3:x>=42&&x<44?(x-42)*.3:x>=48&&x<52?(x-48)/4:x>=72&&x<74?(x-72)*.4:0;
};
return(L,R)=>{
 for(let i=0;i<L.length;i++){
  if(pos>=nx){nx+=S16;st=(st+1)%LEN;trig()}
  pos++;
  let m=0,l=0,r=0,duck=1,dly=0,rv=0;
  // kick: a thump that falls an octave and a half
  if(kt>=0){kp+=(44+90*Math.exp(-kt*16)+400*Math.exp(-kt*120))*T;m+=Math.tanh(Math.sin(TAU*kp)*Math.exp(-kt*5)*3.5)*.85*klv;duck=1-.6*klv*Math.exp(-kt*6);kt+=T;if(kt>.9)kt=-1}
  // sub-bass: a sine pushed just hard enough to be heard on small speakers
  if(se>1e-4){sf+=(sft-sf)*.002;sph+=sf*T;if(sph>=1)sph-=1;se*=sdc;m+=Math.tanh(Math.sin(TAU*sph)*se*2.4)*.42*slv}
  // hats and snare share one noise source; the off-beat hat comes a little late
  const n=rnd();hl+=(n-hl)*.4;const hh=n-hl;
  if(hsw>0&&!--hsw){he=hpe;hd=hdc}
  he*=hd;l+=hh*he*.16;r+=hh*he*.2;
  if(ce>=0){svf(sn,n,1700,.7);const c=(sn[2]*Math.exp(-ce*11)*1.5+Math.sin(TAU*(175*ce+1.5*(1-Math.exp(-ce*35))))*Math.exp(-ce*15)*.7)*clv;m+=Math.tanh(c*1.5)*.7;rv+=c*.9;ce+=T;if(ce>.7)ce=-1}
  // strings: five notes, two saws each, a slow bow and a slight vibrato, gliding from chord to chord
  plv+=(plt-plv)*.00004;pc+=(pct-pc)*.0001;
  if(plv>1e-3){let a=0,b=0;
   for(let j=0;j<5;j++){pf[j]+=(pt[j]-pf[j])*.0005;const f=pf[j]*(1+.0035*Math.sin(pos*T*(31+j*2.3)))*T;
    let p=pp[2*j]+f*1.003;if(p>=1)p-=1;pp[2*j]=p;let q=pp[2*j+1]+f*.997;if(q>=1)q-=1;pp[2*j+1]=q;
    const u=saw(p,f),v=saw(q,f);a+=u*.75+v*.25;b+=v*.75+u*.25}
   const g=plv*.075*(.6+.4*duck),xl=svf(pL,a,pc,.8)*g,xr=svf(pR,b,pc*1.06,.8)*g;
   l+=xl;r+=xr;rv+=(xl+xr)*.7}
  // piano: turn each partial of each sounding note one step
  {let a=0,b=0;
   for(let v=0;v<NV;v++){if(qa[v]<3e-4)continue;const o=v*NP;let y=0;
    for(let k=0;k<NP;k++){const j=o+k,u=qr[j],w=qi[j];qr[j]=(u*qc[j]-w*qs[j])*qd[j];qi[j]=(u*qs[j]+w*qc[j])*qd[j];y+=qr[j]}
    qa[v]*=qd[o];a+=y*(1-qp[v]);b+=y*(1+qp[v])}
   thk*=thd;const h=svf(th,n*thk,2400,1)*.5;a=(a+h)*.17;b=(b+h)*.17;
   l+=a;r+=b;rv+=(a+b)*.55;dly+=(a+b)*.12}
  // the voice: a saw and a pulse, two formants that open and close like a mouth, overdriven
  len+=((lon?1:0)-len)*(lon?.002:.00012);
  if(len>1e-3){lag+=T;lf+=(lft-lf)*.0006;lph+=lf*(1+.011*Math.min(1,lag*2)*Math.sin(TAU*5.3*pos*T))*T;if(lph>=1)lph-=1;
   const o=saw(lph,lf*T)+(lph<.32?.45:-.45),w=.5+.5*Math.sin(TAU*.31*pos*T)+.5*Math.exp(-lag*5);
   svf(f1,o,480+420*w,.22);svf(f2,o,1150+1400*w,.18);
   const y=svf(f3,Math.tanh((f1[2]*1.3+f2[2])*len*5),4200,.9)*.14;
   l+=y*.85;r+=y;dly+=y*.9;rv+=y*.8}
  // drone and rumble
  dlv+=(dlt-dlv)*.00004;
  if(dlv>1e-3){dp1+=36.71*T;if(dp1>=1)dp1-=1;dp2+=55.2*T;if(dp2>=1)dp2-=1;
   const y=(Math.sin(TAU*dp1)*.5+Math.sin(TAU*dp2)*.22*(1+.5*Math.sin(pos*T*.9))+svf(rm,n,90+40*Math.sin(pos*T*.31),.8)*1.6)*dlv;
   m+=y*.4;rv+=y*.2}
  // static: a click now and then
  if(ckd>0&&Math.abs(rnd())<ckd*.0005){cke=1;ckp=rnd()}
  if(cke>1e-3){cke*=ckc;const y=n*cke*.2;l+=y*(1-ckp);r+=y*(1+ckp);rv+=y*.4}
  // something goes past: noise, swept up and down and across
  if(wt>=0){const u=wt/wd,e=Math.sin(Math.PI*u)**3;svf(ws,n,300+2600*e*e,.5);const y=ws[2]*e*.45,p=2*u-1;l+=y*(1-.7*p);r+=y*(1+.7*p);rv+=y*.4;wt+=T;if(wt>=wd)wt=-1}
  // something hits: a falling sub and a burst
  if(it>=0){ip+=(34+70*Math.exp(-it*9))*T;
   const y=(Math.sin(TAU*ip)*Math.exp(-it*2.2)+svf(im,n,400+3000*Math.exp(-it*8),.8)*Math.exp(-it*5)*.9)*ilv;m+=Math.tanh(y*1.5)*.5;rv+=y*.5;it+=T;if(it>2.5)it=-1}
  // riser
  ri+=(ris-ri)*.0008;if(ri>.002){svf(rz,n,250*2**(ri*5.5),.35);rph+=110*2**(ri*2)*T;if(rph>=1)rph-=1;const y=(rz[2]*.3+saw(rph,.01)*.04)*ri*ri;l+=y;r+=y;rv+=y*.4}
  // delay
  {const a=dL[di],b=dR[di];dlp+=(b-dlp)*.4;drp+=(a-drp)*.4;dL[di]=dly+dlp*.45;dR[di]=drp*.45;if(++di==DN)di=0;l+=a*.6;r+=b*.6;rv+=(a+b)*.15}
  // reverb + soft clip
  l+=verb(rv*.03+1e-18,cL,aL,0)*1.4;r+=verb(rv*.03+1e-18,cR,aR,1)*1.4;
  L[i]=Math.tanh((m+l)*.9)*mg;R[i]=Math.tanh((m+r)*.9)*mg;
 }
 return pos};
}

/* ---------------- shaders ---------------- */
const VS=`#version 300 es
void main(){gl_Position=vec4(vec2(gl_VertexID&1,gl_VertexID>>1)*4.-1.,0,1);}`;

const HEAD=`#version 300 es
precision highp float;precision highp int;precision highp sampler2D;
`;

// shared by the three pictures: camera, noise, the sky, and the false colours of each band of light
const CMN=`
uniform vec2 uR;uniform float uT,uRow;uniform vec4 uA,uK;uniform sampler2D uS;out vec4 O;
uniform vec3 uCo;uniform mat3 uCm;uniform float uFv,uWp,uWl,uXp,uSt;uniform int uB0,uB1;
// uA: bass, low-mid, mid, high (FFT bands)   uK: kick env, hat env, integral of bass, integral of energy
// uCo, uCm, uFv: the camera - where, which way (columns right, up, forward), focal length
// uB0, uB1, uWp: the band of light to the right and to the left of the wipe, and where the wipe is
#define PI 3.14159265
#define TAU 6.2831853
#define sat(x) clamp(x,0.,1.)
float DI;
mat2 rot(float a){float c=cos(a),s=sin(a);return mat2(c,-s,s,c);}
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);}
vec3 h33(vec3 p){p=vec3(dot(p,vec3(127.1,311.7,74.7)),dot(p,vec3(269.5,183.3,246.1)),dot(p,vec3(113.5,271.9,124.6)));return fract(sin(p)*43758.5453);}
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 fbm(vec3 p){float a=.5,s=0.;for(int i=0;i<5;i++){s+=a*ns(p);p=p*2.03+7.1;a*=.5;}return s;}
float fb3(vec3 p){return .5*ns(p)+.25*ns(p*2.03+7.1)+.125*ns(p*4.1+3.3);}
float fft(float x){return textureLod(uS,vec2(x,uRow),0.).r;}
// stars in three layers, and the Milky Way: a band tilted sixty degrees to the planets, with dust lanes and a brighter core
vec3 stars(vec3 d){
  vec3 c=vec3(0);
  for(int i=0;i<3;i++){
    vec3 q=d*(38.+float(i)*47.),id=floor(q),h=h33(id+float(i)*17.);
    float e=length(q-id-.5-(h.yzx-.5)*.7);
    c+=step(.8,h.x)*(.2+.8*h.z*h.z*h.z)*mix(vec3(1.,.72,.5),vec3(.6,.8,1.),h.y)*exp(-e*e*220.)*(5.+6.*uA.w*h.z)/(1.+float(i)*1.4);
  }
  float b=dot(d,vec3(.503,.503,.704)),co=sat(dot(d,vec3(.81,-.58,-.165))),n=fb3(d*3.+2.),k=fb3(d*7.+5.);
  float m=exp(-b*b*16.)*(.4+n)*(1.-.85*smoothstep(.42,.62,k)*exp(-b*b*70.));
  c+=mix(vec3(.008,.011,.02),vec3(.022,.017,.012),co*co)*m*(1.+co*co*co)+vec3(.003,.004,.007)*n*n;
  return c;
}
// what each band of light is shown in. 1 hydrogen alpha, 2 helium 304, 3 iron 171, 4 iron 193, 5 iron 211, 6 iron 131, 7 x-rays, 8 heat, 9 magnetism
vec3 ramp(int b,float i){
  i=max(i,0.);
  if(b==1)return vec3(pow(i,.8)*1.25,pow(i,1.7)*.42,pow(i,3.)*.16);
  if(b==2)return vec3(pow(i,.75)*1.3,pow(i,1.8)*.3,pow(i,2.6)*.1);
  if(b==3)return vec3(pow(i,.85)*1.15,pow(i,1.15)*.82,pow(i,2.4)*.25);
  if(b==4)return vec3(pow(i,.9)*1.05,pow(i,1.1)*.7,pow(i,1.35)*.42);
  if(b==5)return vec3(pow(i,1.)*.85,pow(i,1.5)*.42,pow(i,.85)*1.1);
  if(b==6)return vec3(pow(i,2.2)*.3,pow(i,.95)*.95,pow(i,.9)*.9);
  if(b==7)return vec3(pow(i,1.9)*.45,pow(i,1.25)*.7,pow(i,.8)*1.2);
  if(b==8)return vec3(pow(i,1.3)*1.6,pow(i,2.5),.45*sin(PI*min(i*2.5,1.))*min(i*8.,1.)+.8*pow(i,4.));
  return vec3(i);
}
float lum(vec3 c){return dot(c,vec3(.3,.55,.15));}
`;

// the Sun, as a telescope sees it in one band of light. Sun-centred, radius 1.
// Six active regions carry everything: in white light they are sunspots, in hydrogen light bright plage with a dark filament
// arching over one of them, in the extreme ultraviolet bundles of loops, in x-rays almost all there is to see.
const SUNF=`
uniform vec4 uAR[6],uAM[6];           // active regions: where and how big; which way the field under them points, and how bright they are
uniform float uSr,uEr,uEw,uEb,uEs,uFa,uWv; // how far the Sun has turned; the prominence: radius, thickness, brightness, how violently it is erupting; flare; shock front
// cellular noise: distance to the nearest and second nearest of a field of slowly circling points
vec2 wor(vec3 p,float an){
  vec3 i=floor(p),f=p-i;float a=9.,b=9.;
  for(int x=-1;x<2;x++)for(int y=-1;y<2;y++)for(int z=-1;z<2;z++){
    vec3 g=vec3(x,y,z),o=g+.5+.4*sin(an+TAU*h33(i+g))-f;float d=dot(o,o);
    if(d<a){b=a;a=d;}else if(d<b)b=d;}
  return sqrt(vec2(a,b));}
// what the regions do to a point on the surface: umbra, penumbra, plage, polarity
vec4 regs(vec3 n,vec3 ps){
  vec4 v=vec4(0);
  for(int i=0;i<6;i++){
    vec3 a=uAR[i].xyz,m=uAM[i].xyz;float s=uAR[i].w,d2=dot(n-a,n-a);
    if(d2>s*s*8.)continue;
    v.z+=exp(-d2/(s*s*1.5))*min(uAM[i].w,1.5);
    float w=(ns(ps*18.+float(i)*7.)-.5)*.9;
    for(float k=-1.;k<2.;k+=2.){                          // a pair of spots, the leading one larger
      float r=s*(k<0.?.34:.24),d=length(n-normalize(a-m*s*.45*k))/r+w;
      v.x=max(v.x,smoothstep(.55,.42,d));v.y=max(v.y,smoothstep(1.,.88,d));v.w+=k*exp(-d*d*.6);
    }
  }
  return v;}
// the flare: two bright ribbons either side of the line where region 0's field changes sign
float ribb(vec3 n){
  vec3 a=uAR[0].xyz,m=uAM[0].xyz,v=n-a;float s=uAR[0].w,x=(abs(dot(v,m))/s-.2)/.12,y=dot(v,cross(m,a))/s/.5;
  return exp(-x*x-y*y);}
// white light: granulation, spots, faculae, a limb that darkens and reddens
vec3 phot(vec3 n,vec3 ps,float mu){
  vec2 w=wor(ps*70.,uT*.7);
  float g=smoothstep(.02,.3,w.y-w.x),I=.62+.38*g+.3*(fbm(ps*7.+uT*.02)-.5);
  vec4 q=regs(n,ps);
  I=mix(I,(.5+.45*ns(ps*60.+3.))*.72,q.y);I=mix(I,.09+.05*g,q.x);
  I+=q.z*(1.-q.y)*(1.-mu)*.5*g+uFa*ribb(n)*1.5;
  return vec3(1.,.8,.5)*I*pow(vec3(mu),vec3(.3,.55,.95))*1.05;}
// the layer above: a bright network, fibrils, plage round the regions, dark filaments winding between them
float chrom(vec3 n,vec3 ps,float mu,bool he){
  vec2 w=wor(ps*(he?55.:75.),uT*.3);
  float net=smoothstep(.3,0.,w.y-w.x),fib=fbm(ps*24.+2.*fb3(ps*9.));
  vec4 q=regs(n,ps);
  float I=he?.24+.28*net+.4*fib:.42+.45*fib+.06*net;
  I+=q.z*(he?.8:.5)*(.5+fib);
  I*=1.-.7*q.x;if(!he)I*=1.-.3*q.y;
  I*=1.-.8*smoothstep(.008,.003,abs(fb3(ps*1.7+11.)-.44))*smoothstep(.55,.68,ns(ps*2.4+5.));
  return I*(he?1.+.9*pow(1.-mu,3.):.75+.25*mu);}
// loops over a region. The field is that of a dipole buried under it; L (how high a line of force arches) and ph (which way it leans)
// are constant along each line, so noise in (L, ph) makes strands that follow the field
float loops(vec3 p,int i,float hot){
  vec3 a=uAR[i].xyz,m=uAM[i].xyz;float s=uAR[i].w;
  vec3 q=p-a*(1.-.3*s);float r2=dot(q,q),ax=dot(q,m),L=sqrt(r2)/max(1.-ax*ax/r2,.03)/s,ph=atan(dot(q,cross(m,a)),dot(q,a));
  float st=smoothstep(.66-.3*hot,.9,ns(vec3(L*(6.5-2.*hot),ph*6.,float(i)*9.+hot*5.)));
  return st*st*mix(smoothstep(.3,.55,L),exp(-max(L-.3,0.)*3.),hot)*smoothstep(1.5,.9,abs(ph))*smoothstep(1.9,1.1,L)*uAM[i].w;}
// the prominence over region 0: a twisted rope standing on that same line. Returns how much of it there is here
float rope(vec3 p){
  vec3 a=uAR[0].xyz,m=uAM[0].xyz,q=p-a*.9;
  float h=dot(q,m);vec3 qp=q-h*m;float l=length(qp);
  if(abs(h)>2.5*uEw||abs(l-uEr)>.2*uEr+2.5*uEw)return 0.;                                              // nowhere near it
  float an=atan(dot(qp,cross(m,a)),dot(qp,a)),                                                          // an: how far round the arch, 0 at its top
   R=uEr*(1.+min(uEs,1.)*.4*(ns(vec3(an*2.3,uT*.5,3.))-.5)),d2=(l-R)*(l-R)+h*h;                         // erupting, it buckles
  if(d2>uEw*uEw*6.)return 0.;
  float st=.3+.7*pow(.5+.5*sin(atan(h,l-R)*3.+an*(4.+2./uEr)+uT*.6),2.);
  return exp(-d2/(uEw*uEw))*st*(.5+ns(p*(6.+5./(uEr+.2))));}
vec3 sunView(vec3 ro,vec3 rd,int B){
  float b=dot(ro,rd),c=dot(ro,ro),h=b*b-c+1.;
  bool hit=h>0.&&b<0.;float tD=hit?-b-sqrt(h):1e9;
  mat2 R=rot(uSr);
  vec3 n=ro+rd*tD,ps=n;ps.xz=R*ps.xz;
  float mu=hit?max(dot(n,-rd),0.):0.;
  if(B==0)return hit?phot(n,ps,mu):vec3(0);
  // above the limb: where the line of sight comes closest to the centre
  float bi=sqrt(max(c-b*b,0.));vec3 nc=(ro-rd*b)/max(bi,1e-3),pc=nc;pc.xz=R*pc.xz;
  float I=0.,fl=hit?uFa*ribb(n):0.;
  if(B<3){
    bool he=B==2;
    if(hit)I=chrom(n,ps,mu,he)+fl*(he?14.:8.);
    else I=(he?1.5:.9)*exp(-(bi-1.)/(he?.012:.007))*(.5+ns(pc*150.))+(he?.12*exp(-(bi-1.)/.1)*(.5+fb3(pc*5.)):0.);
  }else{
    float hs=B==3?.05:B==4?.07:B==5?.08:B==6?.045:.09,K=B==3?.34:B==4?.48:B==5?.52:B==6?.2:.1,hot=B==3?0.:B<6?.45:1.,
     gn=B==3?1.:B==4?.8:B==5?.7:B==6?.35:1.8;
    vec3 nq=hit?n:nc,pq=hit?ps:pc;
    float hole=smoothstep(.6,.85,abs(nq.y)+.3*(ns(pq*2.2+4.)-.5)),dif=(1.-.92*hole)*(.5+fb3(pq*3.+1.));
    if(hit){
      vec2 w=wor(ps*50.,uT*.3);vec4 q=regs(n,ps);float net=smoothstep(.3,0.,w.y-w.x);
      I=(B==7?0.:.045+.03*net)+q.z*(.25+.3*net)*(B==7?.4:1.)+K*dif/(mu+.35)+fl*(B>5?30.:16.);
      if(uWv>0.){float ad=acos(clamp(dot(n,uAR[0].xyz),-1.,1.))-uWv;I+=.6*exp(-ad*ad*250.)*exp(-uWv*1.4)*(1.-hole);}   // the shock running out over the surface
    }else{
      I=K*dif*3.6*exp(-(bi-1.)/hs)+.05*exp(-(bi-1.)/.3)*(.4+fb3(pc*4.))*(B==7?.3:1.)
       +.5*hole*pow(ns(pc*45.),3.)*exp(-(bi-1.)/.2);                                                                  // plumes over the poles
    }
    // loops: march each region's own sphere
    for(int i=0;i<6;i++){
      vec3 a=uAR[i].xyz;float s=uAR[i].w,rr=s*1.9;
      vec3 oc=ro-a*(1.+.4*s);float bb=dot(oc,rd),hh=bb*bb-dot(oc,oc)+rr*rr;
      if(hh<=0.)continue;
      hh=sqrt(hh);float t0=max(-bb-hh,0.),t1=min(-bb+hh,tD);
      if(t1<=t0)continue;
      float dt=(t1-t0)/18.,t=t0+dt*DI,e=0.;
      for(int j=0;j<18;j++){vec3 p=ro+rd*t;if(dot(p,p)>1.)e+=loops(p,i,hot);t+=dt;}
      I+=e*dt/s*gn*3.5;
    }
  }
  // the prominence: dark against the disc in cool light, bright against the sky
  if(uEb>0.){
    vec3 oc=ro-uAR[0].xyz*.9;float rr=uEr*1.2+2.5*uEw,bb=dot(oc,rd),hh=bb*bb-dot(oc,oc)+rr*rr;
    if(hh>0.){
      hh=sqrt(hh);float t0=max(-bb-hh,0.),t1=min(-bb+hh,tD);
      if(t1>t0){
        float dt=(t1-t0)/24.,t=t0+dt*DI,e=0.;
        for(int j=0;j<24;j++){vec3 p=ro+rd*t;if(dot(p,p)>1.)e+=rope(p);t+=dt;}
        e*=dt/uEw*uEb;
        if(B<3){float a=exp(-e*2.5);I=I*a+(B==2?.75:.55)*(1.+uEs)*(1.-a);}else I+=e*(B==3?.5:.25)*(1.+uEs);
      }
    }
  }
  return ramp(B,I);}
`;

const SUN=CMN+SUNF+`
uniform float uPie;
void main(){
  vec2 uv=(gl_FragCoord.xy*2.-uR)/uR.y;
  vec3 rd=uCm*normalize(vec3(uv,uFv));
  DI=h21(gl_FragCoord.xy+fract(uT)*91.);
  float w=uv.x+.25*uv.y-uWp,sh=1.;int B=w<0.?uB1:uB0;
  if(uPie>0.){                                               // one disc, eight wedges, each in its own light
    vec3 q=-uCo*uCm;vec2 c=q.xy*uFv/q.z;
    float a=fract(atan(uv.y-c.y,uv.x-c.x)/TAU+uPie)*8.;B=int(a);sh=smoothstep(.5,.485,abs(fract(a)-.5));
  }
  vec3 col=sunView(uCo,rd,B)*uXp*sh;
  col+=vec3(.7,.85,1.)*uWl*exp(-abs(w)*uR.y*.35);
  O=vec4(col,1.);
}`;

// the planets, as lit spheres: 0 Mercury 1 Venus 2 Earth 3 Mars 4 Jupiter 5 Saturn 6 Uranus 7 Neptune 8 the Moon
const PLN=`
uniform vec4 uIm[8];uniform float uAu;     // impacts on Jupiter: longitude, age (<= 0: not yet), size; aurora over the Earth
const vec3 PT[9]=vec3[9](vec3(.62,.58,.55),vec3(.95,.85,.6),vec3(.3,.55,1.),vec3(1.,.45,.25),vec3(.92,.74,.52),vec3(.9,.8,.55),vec3(.55,.85,.9),vec3(.3,.45,1.),vec3(.6));
// Jupiter: belts and zones with ragged edges, grey poles, the red spot, and wherever a fragment has gone in, a flash and then a dark scar
vec3 jup(vec3 q,bool ir,out float em){
  float lo=atan(q.z,q.x),t=fbm(q*vec3(2.5,10.,2.5)+3.+.6*fb3(q*vec3(6.,18.,6.)));
  float y=q.y+.05*(t-.5)+.006*sin(lo*11.+q.y*50.),b=.5+.5*sin(y*23.+1.3*sin(y*7.+1.));
  vec3 c=mix(vec3(.6,.36,.22),vec3(.96,.88,.74),smoothstep(.2,.8,b+.6*(t-.5)));
  c=mix(c,vec3(.5,.47,.5),smoothstep(.7,.95,abs(q.y)));
  vec2 g=vec2(mod(lo-1.+PI,TAU)-PI,asin(q.y)+.38);float sp=smoothstep(1.,.5,g.x*g.x/.05+g.y*g.y/.011);
  c=mix(c,vec3(.78,.3,.16)*(.8+.4*t),sp);
  if(ir)c=vec3(.012+.025*b+.3*smoothstep(.7,.95,abs(q.y))+.4*sp);      // in the light methane swallows, only what is high shows
  em=0.;
  for(int i=0;i<8;i++){
    float ag=uIm[i].y;if(ag<=0.)continue;
    float d=length(q-vec3(.719*cos(uIm[i].x),-.695,.719*sin(uIm[i].x)))/uIm[i].z,gr=sat(ag*.6);
    if(ir)c+=gr*1.4*exp(-d*d*.8);
    else c*=1.-gr*(.88*smoothstep(1.,.5,d)+.45*smoothstep(2.6,1.9,d)*smoothstep(1.2,1.9,d));
    em+=exp(-d*d*2.)*exp(-ag*3.)*90.;
  }
  return c;}
// the Earth: sea with the Sun glinting in it, land, ice, cloud, air; on the night side cities and, round the pole, aurora
vec3 earth(vec3 q,vec3 n,vec3 L,vec3 V,bool ir){
  float nl=dot(n,L),nv=sat(dot(n,V)),day=smoothstep(-.1,.2,nl),la=abs(q.y);
  float h=fbm(q*1.9+vec3(3.1,1.7,5.3))+.2*fb3(q*7.+1.),land=smoothstep(.56,.59,h),ice=smoothstep(.83,.9,la+.12*h);
  vec3 w=q;w.xz=rot(uT*.012)*w.xz;
  float cl=smoothstep(.5,.8,fbm(w*3.5+1.6*fb3(w*2.+7.)+vec3(0,la*1.5,0)));
  if(ir)return ramp(8,.62+.12*day-.3*cl-.22*la*la-.1*ice+.06*land*day);
  vec3 al=mix(vec3(.012,.05,.17),mix(vec3(.07,.19,.05),vec3(.45,.36,.2),smoothstep(.6,.78,h+.25*(1.-la)-.1)),land);
  al=mix(al,vec3(.85),ice);al=mix(al,vec3(.92),cl*.92);
  vec3 c=al*sat(nl)*2.6;
  c+=(1.-land)*(1.-cl)*pow(sat(dot(reflect(-L,n),V)),50.)*5.*vec3(1.,.9,.7)*day;
  c=c*mix(vec3(1.,.45,.2),vec3(1),smoothstep(-.05,.3,nl))+vec3(.2,.45,1.)*pow(1.-nv,2.5)*day*1.3;
  float ci=land*(1.-ice)*smoothstep(.85,1.15,ns(q*110.)*ns(q*16.+2.)*2.6)*smoothstep(.75,.3,la);
  c+=vec3(1.,.68,.3)*ci*(1.-day)*(1.-cl)*1.3;
  float ov=(abs(dot(q,vec3(.168,.985,.05)))-.92)/.022;
  c+=vec3(.2,1.,.5)*exp(-ov*ov)*(.4+ns(q*vec3(30.,4.,30.)+uT*.5))*(1.-day)*uAu*1.5;
  return c;}
// Saturn's rings: how much ring there is at r planet radii
float ringd(float r){
  if(r<1.24||r>2.27)return 0.;
  float d=.22+.78*smoothstep(1.52,1.56,r);
  d*=1.-.92*smoothstep(1.94,1.955,r)*smoothstep(2.03,2.015,r);
  d*=(.75+.25*ns(vec3(r*70.,0.,0.)))*(r>2.02?.6:1.);
  return d*(1.-.8*smoothstep(2.2,2.207,r)*smoothstep(2.222,2.215,r));}
// n: surface normal, L: to the Sun, V: to the eye, sp: how far it has turned
vec3 planet(int id,vec3 n,vec3 L,vec3 V,float sp,bool ir){
  vec3 q=n;
  if(id==2)q.xy=rot(.41)*q.xy;else if(id==5)q.xy=rot(.47)*q.xy;else if(id==3)q.xy=rot(.44)*q.xy;
  q.xz=rot(sp)*q.xz;
  if(id==2)return earth(q,n,L,V,ir);
  float d=sat(dot(n,L)),nv=sat(dot(n,V)),em=0.;vec3 al;
  if(id==4)al=jup(q,ir,em);
  else if(id==5)al=mix(vec3(.8,.66,.42),vec3(.96,.88,.68),.5+.5*sin(q.y*26.+2.5*fb3(q*vec3(1.5,6.,1.5))))*mix(1.,.75,smoothstep(.6,.95,abs(q.y)));
  else if(id==0)al=vec3(.5,.47,.44)*(.5+.8*fbm(q*5.));
  else if(id==1)al=vec3(.95,.86,.62)*(.82+.25*fb3(q*vec3(2.,6.,2.)+2.));
  else if(id==3){al=mix(vec3(.8,.4,.2),vec3(.36,.18,.12),smoothstep(.4,.65,fbm(q*2.5+1.)));al=mix(al,vec3(.9),smoothstep(.88,.93,abs(q.y)+.05*ns(q*9.)));}
  else if(id==6)al=vec3(.55,.83,.87)*(.95+.05*sin(q.y*12.));
  else if(id==7)al=vec3(.2,.36,.9)*(.85+.3*fb3(q*vec3(2.,8.,2.)));
  else{al=vec3(.34)*(.55+.6*fbm(q*4.));al*=mix(1.,.5,smoothstep(.5,.6,fb3(q*1.6+4.)));}
  if(ir)return ramp(8,al.x)+em;
  return al*(id>3&&id<8?pow(d,.8)*.95+.008:d*2.2)+PT[id]*pow(1.-nv,3.)*d*(id==0||id==8?0.:.35)+em;}
`;

// the gravity view: the plane of the planets drawn as a sheet that masses dent. Shared with the particles that ride on it
const HF=`
uniform float uGr;uniform vec4 uDm[5];     // how much; what dents the sheet besides the Sun: x, z, mass, softening squared
float hf(vec2 q){float h=-2.2/sqrt(dot(q,q)+.5);for(int i=0;i<5;i++){vec2 d=q-uDm[i].xy;h-=uDm[i].z/sqrt(dot(d,d)+uDm[i].w);}return h*uGr;}
`;
// the orrery: the Sun, eight planets on their orbits, the sky. Distances are true (1 = Earth to Sun); the planets are drawn far too big
const ORR=CMN+PLN+HF+`
uniform vec4 uPl[10],uOr[8],uHa,uHb;uniform float uPs[10],uSy,uSz,uOb;uniform vec3 uHc;
// uPl: planets (8 the Moon, 9 a spare): where, and radius as drawn   uOr: their orbits: centre, radius, the planet's angle
// uHa, uHb: a glow round a comet's head in visible light and in hydrogen light   uSy, uSz: the Sun's height and drawn radius
void main(){
  vec2 uv=(gl_FragCoord.xy*2.-uR)/uR.y;vec3 ro=uCo,rd=uCm*normalize(vec3(uv,uFv));
  float px=2./(uR.y*uFv),wi=uv.x+.25*uv.y-uWp;bool uvl=(wi<0.?uB1:uB0)==10;
  vec3 col=stars(rd)*uSt;float tm=1e9;int id=-1;
  if(uvl)col*=vec3(.3,.25,.7);
  // the Sun
  vec3 sc=vec3(0,uSy,0),oc=ro-sc;float b=dot(oc,rd),bi2=dot(oc,oc)-b*b,s2=uSz*uSz;
  if(b<0.){
    col+=vec3(1.,.82,.6)*pow(s2/(bi2+s2*.2),1.2)*.6;
    if(bi2<s2){tm=-b-sqrt(s2-bi2);col=vec3(1.,.93,.82)*70.*pow(1.-bi2/s2,.2);}
  }
  // planets: a dot of light each so they can be found when too small to see, and a sphere
  for(int i=0;i<10;i++){
    vec4 p=uPl[i];if(p.w<=0.)continue;
    vec3 o=ro-p.xyz;float bb=dot(o,rd);if(bb>0.)continue;
    float d2=dot(o,o)-bb*bb,h=p.w*p.w-d2,g=-bb*px*1.4;
    if(-bb<tm)col+=PT[min(i,8)]*exp(-d2/(g*g))*.8;
    if(h>0.&&-bb-sqrt(h)<tm){tm=-bb-sqrt(h);id=i;}
  }
  if(id>=0){
    vec4 p=uPl[id];vec3 n=(ro+rd*tm-p.xyz)/p.w,L=normalize(sc-p.xyz);
    col=planet(min(id,8),n,L,-rd,uPs[id],false);
    if(id==5){float s=-dot(n,vec3(.42,.89,.17))/dot(L,vec3(.42,.89,.17));if(s>0.)col*=1.-.8*ringd(length(n+L*s));}   // the rings' shadow
  }
  // Saturn's rings
  {vec4 p=uPl[5];const vec3 N=vec3(.42,.89,.17);vec3 o=ro-p.xyz;float dn=dot(rd,N),t=-dot(o,N)/dn;
   if(p.w>0.&&t>0.&&t<tm){vec3 q=(o+rd*t)/p.w;float a=ringd(length(q));
    if(a>0.){vec3 L=normalize(sc-p.xyz);float sb=dot(q,L);
     col=mix(col,vec3(.92,.82,.64)*(.5+a)*(sb>0.||dot(q,q)-sb*sb>1.?1.6:.06)*(.5+.5*abs(dot(N,L))),a*.92);}}}
  // the plane of the planets - or, in the gravity view, the sheet they dent
  float tp=-1.;vec3 P=ro;
  if(uGr>0.){
    float t=0.;
    for(int i=0;i<80;i++){P=ro+rd*t;float d=P.y-hf(P.xz);if(d<.002*t){tp=t;break;}t+=d*.35+.002*t;if(t>90.)break;}
  }else if(ro.y*rd.y<0.){tp=-ro.y/rd.y;P=ro+rd*tp;}
  if(tp>0.&&tp<tm){
    float w=tp*px/sqrt(max(abs(rd.y),.03))*1.2;vec2 q=P.xz;
    for(int i=0;i<8;i++){
      vec2 e=q-uOr[i].xy;float d=abs(length(e)-uOr[i].z),da=mod(uOr[i].w-atan(e.y,e.x),TAU);
      col+=mix(vec3(.4,.55,.85),PT[i],.6)*exp(-d*d/(w*w))*(.1+.9*exp(-da*1.3))*uOb*min(1.,.04*uOr[i].z/w+.15);
    }
    if(uGr>0.){
      vec2 g=abs(fract(q*2.-.5)-.5)*.5;float d=min(g.x,g.y),dp=sat(-P.y*.4);
      col+=mix(vec3(.08,.25,.8),vec3(1.,.5,.15),dp)*exp(-d*d/(w*w))*(.25+1.2*dp)*uGr*exp(-dot(q,q)*.006)*smoothstep(.16,.03,w);
    }
  }
  // a comet's head: a small bright coma, or in ultraviolet a cloud of hydrogen bigger than the Sun
  vec4 ha=uvl?uHb:uHa;
  if(ha.w>0.){vec3 o=ro-ha.xyz;float bb=dot(o,rd),d=sqrt(max(dot(o,o)-bb*bb,0.));if(bb<0.)col+=(uvl?vec3(.35,.3,1.):uHc)*(exp(-d/ha.w)+.4*exp(-d*d/(ha.w*ha.w*.01)));}
  col+=vec3(.7,.85,1.)*uWl*exp(-abs(wi)*uR.y*.35);
  O=vec4(col,1.);
}`;

// close to: a small body ray-marched in front of us, and behind it the sky, a planet, or the Sun
const CLS=CMN+SUNF+PLN+`
uniform int uTy,uBg,uPi;uniform mat3 uBr;uniform vec3 uSd,uBo,uMo,uPsh;uniform float uSa,uSb,uPs,uFr,uJs,uSi;uniform vec4 uJ[4];
// uTy: what is in front: -1 nothing, 0 a comet's nucleus, 1 a shard, 2 a rubble pile, 3 a nucleus coming apart (uFr: how far gone)
// uBg: what is behind: 0 the sky, 1 a planet (uPi), one radius big at the origin of its own frame, with us at uBo; 2 the Sun, close
// uBr: the body's rotation   uSd, uSa, uSb, uSi: the Sun - direction, angular radius, brightness of the disc, strength of its light
// uJ, uJs: jets - direction in the body's frame and strength   uPsh: light off the planet   uMo: the Moon
vec3 BP,PDR;      // where a point sat in the unbroken body; direction of the planet
float smin(float a,float b,float k){float h=max(k-abs(a-b),0.)/k;return min(a,b)-h*h*k*.25;}
float ell(vec3 p,vec3 r){return (length(p/r)-1.)*min(r.x,min(r.y,r.z));}
// boulders: one rounded lump in each cell of a grid, or none
float lump(vec3 p,float sc,float sd){
  vec3 q=p/sc+sd,i=floor(q),h=h33(i);float r=.16+.3*h.x;
  if(h.y<.35)return 0.;
  float x=length(q-i-.5-(h.yzx-.5)*(1.-2.*r)*.9)/r;
  return sc*r*.75*max(0.,1.-x*x);}
// craters: a bowl with a raised rim
float crat(vec3 p,float sc,float sd){
  vec3 q=p/sc+sd,i=floor(q),h=h33(i);float r=.2+.26*h.x;
  if(h.y<.4)return 0.;
  float x=length(q-i-.5-(h.yzx-.5)*(1.-2.*r)*.9)/r;
  return sc*r*((x<1.?.45*(x*x-1.):0.)+.14*exp(-(x-1.)*(x-1.)*24.));}
float body(vec3 p){
  BP=p;
  if(uTy==1){                                   // the shard: long, faceted, a little twisted
    float bd=length(p)-2.7;if(bd>.5)return bd;
    vec3 q=p;q.xy=rot(.05*q.x)*q.xy;
    float d=ell(q,vec3(2.5,.4,.55));
    d=max(d,dot(q,vec3(.1,.88,.46))-.3);d=max(d,dot(q,vec3(-.08,-.7,.71))-.33);d=max(d,dot(q,vec3(.05,.45,-.89))-.36);
    d=max(d,dot(q,vec3(.6,-.5,-.62))-1.1);
    if(d<.3)d-=.06*fb3(q*2.5)+.015*ns(q*13.)-.035+.5*crat(q,.5,3.)+.4*lump(q.yzx,.13,5.);else d-=.07;        // far from the surface its relief need not be worked out, only allowed for
    return d*.75;
  }
  if(uTy==3){                                   // coming apart: a tilted grid of blocks, each sliced by a plane of its own, each drifting its own way
    float bd=length(p)-1.3-1.9*uFr;if(bd>.5)return bd;
    const mat3 G=mat3(.36,.48,-.8,-.8,.6,0.,.48,.64,.6);
    float D=uFr,m=.35+.3*D;vec3 b=floor(G*(p/(1.+1.1*D))/.5-.5);
    for(int i=0;i<8;i++){
      vec3 g=b+vec3(i&1,i>>1&1,i>>2),o=(g+.5)*.5,ow=o*G;
      if(dot(ow,ow)>1.7)continue;                                                              // nothing of the body was ever in this block
      vec3 h=h33(g+3.),q=p-ow*(1.+1.2*D*(.6+.6*h.x))-(h-.5)*D*.5;
      if(length(q)-.5>m)continue;                                                              // too far off to matter
      q.xy=rot(D*4.*(h.z-.5))*q.xy;q.yz=rot(D*3.*(h.x-.5))*q.yz;q+=ow;                         // each block drifts and turns
      vec3 u=G*q-o,w=abs(u)-.25*(1.-D*.12*(1.+2.*h.y))+.03;
      float e=length(max(w,0.))+min(max(w.x,max(w.y,w.z)),0.)-.03,l=length(q);
      if(e>m)continue;
      e=max(max(e,dot(u,normalize(h-.5))-.05-.12*h.y*(1.-D*.3)),max(dot(u,normalize(h.yzx-.5))-.09-.1*h.z,dot(u,normalize(.5-h.zxy))-.1-.1*h.x));
      if(l>1.3)e=max(e,l-1.1);else{float s=ell(q,vec3(1.,.74,.7));if(s>e-.1)s-=.09*(fb3(q*3.)-.45);e=max(e,s);}        // the crust only where it shows
      if(e<m){m=e;BP=q;}
    }
    return m*.85;
  }
  float bd=length(p)-1.75,d;if(bd>.5)return bd;   // two lobes: a comet's nucleus pitted and cratered, or a pile of boulders
  if(uTy==0)d=smin(ell(p-vec3(.55,0.,0.),vec3(.8,.58,.55)),ell(p+vec3(.62,.06,0.),vec3(.62,.5,.5)),.25);
  else d=smin(ell(p-vec3(.35,0.,0.),vec3(.9,.6,.62)),ell(p+vec3(.75,-.05,.05),vec3(.5,.46,.45)),.2);
  if(d<(uTy==0?.2:.4)){
    d-=.1*(fb3(p*2.2+3.)-.45);
    if(uTy==0)d-=crat(p,.7,1.3)+crat(p.yzx,.33,5.1)+lump(p.zxy,.16,2.)*.6;
    else{d-=lump(p,.42,1.)+lump(p.yzx,.2,4.)+crat(p.zxy,.6,2.)*.7;if(d<.1)d-=lump(p.zxy,.09,7.)+lump(p,.042,9.);}
  }else d-=uTy==0?.14:.33;
  return d*.72;
}
float march(vec3 ro,vec3 rd,float t,float t1){for(int i=0;i<(uTy==3?80:110);i++){float d=body(ro+rd*t);if(d<.0006*t+.0003)return t;t+=d;if(t>t1)break;}return -1.;}
float shd(vec3 p,vec3 L){float t=.02,s=1.,k=max(uSa*2.2,.02);for(int i=0;i<(uTy==3?16:28);i++){float d=body(p+L*t);s=min(s,d/(t*k));if(s<.02)return 0.;t+=clamp(d,.025,.5);if(t>5.)break;}return sat(s);}
// airless rock: no sky to fill the shadows, and like the Moon it does not darken toward its edge
vec3 shade(vec3 p,vec3 rd,vec3 L,float t,bool ir){
  vec2 e=vec2(1,-1)*max(.002,.0007*t);
  vec3 n=normalize(e.xyy*body(p+e.xyy)+e.yyx*body(p+e.yyx)+e.yxy*body(p+e.yxy)+e.xxx*body(p+e.xxx));
  vec3 bp=p;if(uTy==3){body(p);bp=BP;}
  n=normalize(n+.3*(vec3(ns(bp*45.),ns(bp*45.+17.),ns(bp*45.+31.))-.5)+.18*(vec3(ns(bp*140.),ns(bp*140.+9.),ns(bp*140.+5.))-.5));
  float f=fb3(bp*5.),g=ns(bp*40.);vec3 al;
  if(uTy==1)al=mix(vec3(.28,.12,.08),vec3(.5,.27,.2),f)*(.8+.4*g);                                 // reddened by a long time between the stars
  else if(uTy==2)al=mix(vec3(.19,.175,.16),vec3(.42,.39,.35),f*f*2.)*(.75+.5*g);
  else{al=mix(vec3(.05,.045,.04),vec3(.17,.15,.13),f)*(.7+.6*g);                                   // darker than coal
    if(uTy==3)al=mix(al,vec3(.3,.34,.42),smoothstep(.03,.12,-ell(bp,vec3(1.,.74,.7))));}          // except where it has cracked open: fresh ice
  float m0=dot(n,L),mu=max(dot(n,-rd),0.),sh=m0>0.?shd(p+n*.012,L):0.;m0=max(m0,0.);
  if(ir)return ramp(8,.1+.85*pow(m0*sh,.4)*(.8+.4*f));                                              // heat: only what the Sun is on
  return al*(uSi*sh*mix(m0,2.*m0/(m0+mu+1e-3),.5)+.015*uSi+uPsh*max(dot(n,PDR),0.));}
// jets: dust and gas leaving the sunlit side in cones
float jets(vec3 p){
  float e=0.;
  for(int i=0;i<4;i++){
    vec3 j=uJ[i].xyz,v=p-j*.6;float a=dot(v,j);if(a<0.)continue;
    float w=.05+.2*a,g=uJ[i].w*exp(-(dot(v,v)-a*a)/(w*w))/(1.+4.*a*a);
    if(g>.003)e+=g*(.4+1.2*ns(normalize(v)*12.+float(i)*3.));
  }
  return e;}
void main(){
  vec2 uv=(gl_FragCoord.xy*2.-uR)/uR.y;vec3 rd=uCm*normalize(vec3(uv,uFv));
  DI=h21(gl_FragCoord.xy+fract(uT)*91.);
  float wi=uv.x+.25*uv.y-uWp;int B=wi<0.?uB1:uB0;bool ir=B==8;
  vec3 col=vec3(0),ro=uBr*uCo,rb=uBr*rd,L=uBr*uSd;float th=-1.,b0=dot(ro,rb);
  if(uTy>=0){
    PDR=uBr*normalize(-uBo);
    float R=uTy==1?2.75:uTy==3?1.35+1.9*uFr:1.8,h=b0*b0-dot(ro,ro)+R*R;
    if(h>0.){h=sqrt(h);if(h-b0>0.)th=march(ro,rb,max(-b0-h,0.),h-b0);}
  }
  if(th>0.){vec3 c2=shade(ro+rb*th,rb,L,th,ir);col=B>0&&B<8?ramp(B,lum(c2)*1.5):c2;}
  else if(uBg==2)col=sunView(uBo,rd,B<8?B:0)*uXp;
  else{
    col=stars(rd)*uSt*(ir?vec3(.6,.3,.25):vec3(1));
    float c=dot(rd,uSd);                      // the Sun, far off: a small disc and its glare
    if(c>0.){float x=sqrt(max(1.-c*c,0.))/uSa;col+=x<1.?vec3(1.,.93,.82)*uSb*pow(1.-x*x,.25):vec3(1.,.85,.65)*uSb*.003/(x*x);}
    if(uBg==1){
      float b=dot(uBo,rd),cc=dot(uBo,uBo),h=b*b-cc+1.;
      if(b<0.){
        float tP=h>0.?-b-sqrt(h):1e9;
        if(h>0.)col=planet(uPi,uBo+rd*tP,uSd,-rd,uPs,ir);
        else if(uPi==2&&!ir){                 // air, edge on beyond the limb: blue where the Sun is on it, a ring of fire when the Sun is behind
          float x=sqrt(max(cc-b*b,0.))-1.;
          col+=(vec3(.25,.5,1.)*smoothstep(-.3,.15,dot(normalize(uBo-rd*b),uSd))+vec3(1.,.45,.15)*pow(sat(c),10.)*3.)*exp(-x/.012)*.9;
        }
        if(uPi==4){                           // fireballs rising where fragments have gone in
          for(int i=0;i<8;i++){
            float ag=uIm[i].y;if(ag<=0.||ag>6.)continue;
            vec3 ip=vec3(.719*cos(uIm[i].x),-.695,.719*sin(uIm[i].x));ip.xz=rot(-uPs)*ip.xz;
            vec3 o=ip*(1.+.07*ag*exp(-ag*.35))-uBo;float tb=dot(o,rd),w=.012+.022*ag;
            if(tb<tP)col+=mix(vec3(1.,.8,.6),vec3(1.,.4,.15),sat(ag*.5))*exp(-(dot(o,o)-tb*tb)/(w*w))*exp(-ag*.9)*(ir?30.:12.);
          }
        }
        if(uPi==2){                           // the Moon
          vec3 o=uBo-uMo;float bb=dot(o,rd),hh=bb*bb-dot(o,o)+.0745;
          if(hh>0.&&bb<0.&&-bb-sqrt(hh)<tP)col=planet(8,(o+rd*(-bb-sqrt(hh)))/.273,uSd,-rd,0.,ir);
        }
      }
    }
  }
  if(uTy>=0&&uJs>0.){                         // jets and coma, in front of whatever was found
    float h2=b0*b0-dot(ro,ro)+20.;
    if(h2>0.){
      h2=sqrt(h2);float t0=max(-b0-h2,0.),t1=th>0.?th:h2-b0;
      if(t1>t0){
        float dt=(t1-t0)/16.,t=t0+dt*DI,e=0.,cs=dot(rb,L);
        for(int j=0;j<16;j++){vec3 p=ro+rb*t;e+=jets(p)+.0015/(dot(p,p)+.3);t+=dt;}
        vec3 jc=vec3(.85,.92,1.)*e*dt*uJs*uSi*(.35+1.2*pow(sat(cs),4.)+.3*cs*cs);
        col+=B>0&&B<8?ramp(B,lum(jc)):ir?jc*vec3(.5,.2,.1):jc;
      }
    }
  }
  col+=vec3(.7,.85,1.)*uWl*exp(-abs(wi)*uR.y*.35);
  O=vec4(col,1.);
}`;

// everything small: asteroids, comet tails, orbit trails, fragments, dust. One point each, placed by the vertex shader from its number alone
const PV=`#version 300 es
precision highp float;precision highp int;
uniform int uMd,uSb;uniform mat3 uCm,uOm,uBr;uniform vec3 uCo,uSd,uBe;uniform float uFv,uAsp,uPx,uT,uYr,uN,uBk;uniform vec4 uP0,uP1,uP2,uP3;
`+HF+`
out vec4 vC;
#define TAU 6.2831853
uint pcg(uint v){uint s=v*747796405u+2891336453u,w=((s>>((s>>28u)+4u))^s)*277803737u;return (w>>22u)^w;}
float H(uint v){return float(pcg(v)>>8u)/16777216.;}
// where a body on an ellipse is: semi-major axis, eccentricity, inclination, node, argument of perihelion, mean anomaly
vec3 kep(float a,float e,float inc,float Om,float om,float M){
  float E=M+e*sin(M);for(int i=0;i<4;i++)E-=(E-e*sin(E)-M)/(1.-e*cos(E));
  vec2 p=a*vec2(cos(E)-e,sqrt(1.-e*e)*sin(E));float c=cos(om),s=sin(om);p=vec2(p.x*c-p.y*s,p.x*s+p.y*c);
  vec3 q=vec3(p.x,p.y*cos(inc),p.y*sin(inc));c=cos(Om);s=sin(Om);
  return vec3(q.x*c-q.y*s,q.z,q.x*s+q.y*c);}
// does the line from o along d (as far as d reaches, or for ever) meet the body in the way? An ellipsoid stands in for it: uBe are its half-axes
bool hitE(vec3 o,vec3 d,bool inf){
  if(uBe.x<=0.)return false;
  vec3 oo=(uBr*o)/uBe,dd=(uBr*d)/uBe;float a=dot(dd,dd),b=dot(oo,dd),h=b*b-a*(dot(oo,oo)-1.);
  if(h<0.)return false;float t=(-b-sqrt(h))/a;return t>0.&&(inf||t<1.);}
void main(){
  uint id=uint(gl_VertexID)*8u;float h0=H(id),h1=H(id+1u),h2=H(id+2u),h3=H(id+3u),h4=H(id+4u),h5=H(id+5u),fi=float(gl_VertexID)/uN;
  vec3 p=vec3(0),col=vec3(1);float sz=-1.5,br=1.,sf=.6,mx=8.;       // sz: diameter in the world's units or, if negative, in pixels
  if(uMd==0){            // the small bodies of the solar system, each on its own ellipse
    float in2=h4+h5-1.;
    if(uSb==0){float a=2.12+1.2*h0;p=kep(a,.03+.22*h3*h3,in2*.32,TAU*h1,TAU*h2,TAU*h5*7.+TAU*uYr/pow(a,1.5));col=vec3(.8,.72,.6);}
    else if(uSb==1){float M=TAU*h1;                  // Hildas: three orbits for Jupiter's two, perihelia locked to it - together they draw a triangle
      p=kep(3.969,.08+.2*h3,in2*.15,0.,.6004-M/1.5+floor(h0*3.)*TAU/3.+(h2-.5)*.25,M+TAU*uYr/7.908);col=vec3(1.,.62,.3);}
    else if(uSb==2){float w=TAU*h2;                  // Trojans: sixty degrees ahead of Jupiter and sixty behind
      p=kep(5.203,.02+.1*h3,in2*.5,0.,w,.6004+TAU*uYr/11.862+(h0<.5?1.:-1.)*1.0472+(h1+h3-1.)*.5-w);col=vec3(.5,.65,1.);}
    else{float a=39.+9.*h0;p=kep(a,.02+.2*h3*h3,in2*.3,TAU*h1,TAU*h2,TAU*h5*3.+TAU*uYr/pow(a,1.5));col=vec3(.55,.75,1.);}
    br=(.12+.88*h4*h4*h4*h4)*uP0.x;sz=uP0.y;mx=4.;
  }else if(uMd==1){      // the path of a visitor: an ellipse, a hyperbola or a parabola, drawn backward from where it is now
    float q=uP0.x,e=uP0.y,E=uP0.z-uP0.w*fi;vec2 xy;
    if(e<.999)xy=q/(1.-e)*vec2(cos(E)-e,sqrt(1.-e*e)*sin(E));
    else if(e>1.001)xy=q/(e-1.)*vec2(e-cosh(E),sqrt(e*e-1.)*sinh(E));
    else xy=q*vec2(1.-E*E,2.*E);
    p=uOm*vec3(xy,0.);if(uGr>0.)p.y=hf(p.xz)+.03;
    col=uP1.rgb;br=uP2.x+uP2.y*pow(1.-fi,2.);sz=-uP1.w;
  }else if(uMd==2){      // a comet's two tails. uP0: the nucleus and its distance from the Sun; uP1: its heading, its angular speed
    vec3 rh=normalize(uP0.xyz),th=normalize(uP1.xyz-rh*dot(uP1.xyz,rh)),nh=cross(rh,th);float r=uP0.w;
    if(h0<.7){           // dust: pushed away from the Sun by its light, and falling behind as it climbs
      float be=.1+.9*h1*h1,ta=fract(h2+uT*.04)*uP2.y,D=.5*be*uP2.x*ta*ta,lag=uP1.w*ta*.67*D/(r+D);
      p=(rh*cos(lag)-th*sin(lag))*(r+D)+(vec3(h3,h4,h5)-.5)*(.006+.12*D);
      col=vec3(1.,.88,.7);br=pow(1.-ta/uP2.y,1.5)*(.3+.7*h3);
    }else{               // ions: swept straight back by the solar wind, in kinks
      float s=fract(h2+uT*.3),k=.004+.035*s;
      p=rh*(r+uP2.z*s)+th*k*(sin(s*17.-uT*4.+floor(h1*3.)*2.)*.7+h3-.5)+nh*k*(h4-.5)*1.5;
      col=vec3(.3,.55,1.);br=pow(1.-s,1.3)*.8;
    }
    br*=uP2.w;sz=uP3.x;sf=1.;mx=uP3.y;
  }else if(uMd==3){      // Shoemaker-Levy 9: twenty-one pieces and their dust, in Jupiter's frame
    float s=((floor(h0*21.)+.5)/21.-.5)*2.;bool core=h1<.25;
    vec3 sc=(vec3(h2,h3,h4)-.5)*(core?.3:1.);
    if(uSb==0){          // rounding Jupiter on a parabola; from the closest point on, each piece runs a little early or late, more with time
      float W=1.5*uP0.y*(1.+(s+(core?0.:(h5-.5)*.25))*uP0.z*step(0.,uP0.y)),y=pow(abs(W)+sqrt(W*W+1.),.33333),D=sign(W)*(y-1./y);
      p=uOm*vec3(uP0.x*vec2(1.-D*D,2.*D),0.)+sc*uP0.w*(1.+2.*max(uP0.y,0.));
    }else if(uSb==1){    // months later: a string of pearls along the orbit, each with a tail
      float E=uP0.y+s*uP0.z,e=uP1.y;
      p=uOm*vec3(uP1.x*vec2(cos(E)-e,sqrt(1.-e*e)*sin(E)),0.)+sc*uP0.w-uSd*(core?0.:h5*h5*uP1.z);
    }else{               // falling in: eight of them, one after another, each a streak
      float dt=uP1.x+float(gl_VertexID&7)*uP1.y-uP0.y;
      if(dt<0.||dt>uP1.z)br=0.;
      core=h5<.06;p=uP2.xyz-uP3.xyz*(uP1.w*dt+h5*h5*.5)+sc*.02;
    }
    col=core?vec3(1.):vec3(.75,.85,1.);br*=(core?1.5:.35)*uP2.w;sz=core?uP3.w*1.6:uP3.w;
    if(hitE(p,uSd,true))br=0.;       // in Jupiter's shadow
  }else if(uMd==4){      // dust adrift round the camera: a box of it that wraps as the camera moves
    float B=uP0.x;p=uCo+(fract(vec3(h0,h1,h2)+uP1.xyz*uT/B-uCo/B+.5)-.5)*B;
    vec3 v=p-uCo;float dv=length(v);
    sz=uP0.y*(.3+3.*h3*h3*h3);
    br=(.4+.6*pow(.5+.5*sin(uT*(1.+3.*h4)+h5*40.),3.))*(1.+uP0.z*pow(max(dot(v/dv,uSd),0.),24.))/(1.+dot(p,p)*uP0.w)*smoothstep(B*.5,B*.35,dv);
    col=uP2.rgb;sf=.8;mx=uP2.w;
    if(hitE(uCo,v,false)||hitE(p,uSd,true))br=0.;      // behind the body, or in its shadow
  }else if(uMd==5){      // a stream of test particles falling past the Sun, all from one direction at one speed: each on its own hyperbola
    uint j=uint(gl_VertexID>>2)*8u+77u;float tr=float(gl_VertexID&3);                  // four points to a particle: itself and where it just was
    h0=H(j);h1=H(j+1u);h2=H(j+2u);
    float a=uP0.x,b=(h0*2.-1.)*uP0.z,ta=(fract(h1+uP1.y/uP0.w)-.5)*uP0.w-tr*.011;
    if(gl_VertexID<4){b=uP1.z;ta=uP1.w-tr*.011;}      // the visitor itself, among them
    float e=sqrt(1.+b*b/(a*a)),M=uP0.y*ta,F=asinh(M/e),sg=b<0.?-1.:1.;
    for(int i=0;i<5;i++)F-=(e*sinh(F)-F-M)/(e*cosh(F)-1.);
    vec2 xy=a*vec2(e-cosh(F),sg*sqrt(e*e-1.)*sinh(F));float an=uP1.x-sg*acos(1./e),c=cos(an),s=sin(an);
    xy=vec2(xy.x*c-xy.y*s,xy.x*s+xy.y*c);p=vec3(xy.x,0.,xy.y);p.y=hf(p.xz)+.03;
    col=mix(vec3(.2,.4,1.),vec3(1.,.75,.45),clamp((2.*a/length(xy)-.5)/7.,0.,1.));    // blue far out and slow, gold close in and fast
    br=(.3+.7*h2*h2)*smoothstep(.5,.42,abs(ta/uP0.w))*uP2.x*(1.-tr*.25);sz=-uP2.y;
    if(a*(e-1.)<.05)br=0.;
    if(gl_VertexID<4){col=vec3(.7,1.,.95);br=14.*(1.-tr*.25);sz=-uP2.y*(5.-tr);mx=16.;}
  }else if(uMd==7){      // a flare's spray: plasma thrown up from one spot on the Sun, and the slower part of it falling back
    vec3 a=uP0.xyz,t1=normalize(cross(a,vec3(.31,.9,.3))),t2=cross(a,t1);                // uP0: the spot, and the Sun's radius in this picture's units
    float ta=uP1.x-h5*uP1.y,an=TAU*h0;                                                   // each piece leaves at its own moment during the burst
    if(ta<0.)br=0.;
    vec3 v=normalize(a+(t1*cos(an)+t2*sin(an))*(.15+uP1.w*h1*h1))*uP1.z*(.3+1.4*h2*h2);
    p=(a*1.004+(t1*(h3-.5)+t2*(h4-.5))*.12+v*ta-a*.5*uP2.w*ta*ta)*uP0.w;
    col=uP2.rgb*(.4+.6*h4);br*=exp(-ta*uP3.x)*uP3.y;sz=uP3.z*(.5+2.*h3*h3)*uP0.w;sf=.9;mx=uP3.w;
    if(hitE(uCo,p-uCo,false))br=0.;                                                      // behind the Sun, or fallen back into it
  }else{                 // a body bursting: pieces thrown every way, then blown back by sunlight
    vec3 d=normalize(vec3(h0,h1,h2)-.5);float ta=uP0.y*(.6+.8*h5);
    if(ta<0.)br=0.;
    p=d*(.4+uP0.x*(.08+2.*h3*h3)*ta)-uSd*.5*uP0.z*h4*ta*ta;
    col=mix(vec3(1.,.9,.75),vec3(.7,.85,1.),h4)*uP2.rgb;br*=exp(-ta*uP0.w)*(.3+.7*h5);sz=uP1.x*(.4+2.5*h1*h1*h1);sf=.8;mx=uP1.y;
  }
  vec3 q=(p-uCo)*uCm;
  if(q.z<.02||br<=0.){gl_Position=vec4(2,2,2,1);gl_PointSize=0.;return;}   // outside the clip volume: never rasterised
  float k=uPx/540.,ps=sz<0.?-sz*k:sz*uFv/q.z*uPx,pc=clamp(ps,1.3*k+.3,mx*k);
  vC=vec4(col*br*min(1.,ps*ps/(pc*pc))/(1.+ps*ps*uBk),sf);                 // too small to draw: dimmer instead. Close and out of focus: fainter
  gl_Position=vec4(q.x*uFv/uAsp,q.y*uFv,0.,q.z);gl_PointSize=pc;
}`;
const PF=`#version 300 es
precision highp float;in vec4 vC;uniform vec2 uR;uniform float uWp;uniform vec3 uVa,uVb;out vec4 O;
void main(){vec2 uv=(gl_FragCoord.xy*2.-uR)/uR.y;
  O=vec4(vC.rgb*(uv.x+.25*uv.y<uWp?uVb:uVa)*smoothstep(.5,.5-.5*vC.a,length(gl_PointCoord-.5)),1);}`;

// how much of the Sun's disc can be seen: sixteen samples of the picture over it, averaged into one pixel that the lens flare then reads.
// Blended into the last answer, so the flare swells and dies smoothly as something passes in front.
const PRB=`#version 300 es
precision highp float;uniform sampler2D uC;uniform vec3 uSs;uniform vec2 uR;uniform float uRa;out vec4 O;
void main(){float v=0.;
  for(int i=0;i<16;i++){float a=float(i)*2.4,r=sqrt((float(i)+.5)/16.)*uRa;vec2 t=((uSs.xy+r*vec2(cos(a),sin(a)))*uR.y+uR)/(2.*uR);
    if(t.x<0.||t.x>1.||t.y<0.||t.y>1.)v+=1.;else{vec3 c=texture(uC,t).rgb;v+=clamp(max(c.r,max(c.g,c.b))/25.,0.,1.);}}
  O=vec4(vec3(v/16.),.3);}`;
const PRE=`#version 300 es
precision highp float;uniform sampler2D uC;uniform vec2 uR,uI;uniform float uTh;out vec4 O;
`;
// dual-filter bloom: 5-tap downsample (soft threshold on the first pass), 8-tap tent upsample
const DOWN=PRE+`void main(){vec2 v=gl_FragCoord.xy/uR;
vec3 s=texture(uC,v).rgb*4.+texture(uC,v+uI).rgb+texture(uC,v-uI).rgb+texture(uC,v+uI*vec2(1,-1)).rgb+texture(uC,v+uI*vec2(-1,1)).rgb;s*=.125;
if(uTh>0.){s=min(s,vec3(24.));s*=smoothstep(.5,1.8,max(s.r,max(s.g,s.b)));}
O=vec4(s,1);}`;
const UP=PRE+`void main(){vec2 v=gl_FragCoord.xy/uR;vec3 e=vec3(uI,0.);
vec3 s=texture(uC,v+e.xz).rgb+texture(uC,v-e.xz).rgb+texture(uC,v+e.zy).rgb+texture(uC,v-e.zy).rgb
+2.*(texture(uC,v+uI*.5).rgb+texture(uC,v-uI*.5).rgb+texture(uC,v+uI*vec2(.5,-.5)).rgb+texture(uC,v+uI*vec2(-.5,.5)).rgb);
O=vec4(s/12.,1);}`;
const COMP=`#version 300 es
precision highp float;uniform sampler2D uC,uB,uX,uS,uP;uniform vec2 uR,uXs;uniform vec3 uSs,uFc,uXc;uniform float uT,uF,uXa,uRow,uFl,uFi,uSn,uGl,uXi;out vec4 O;
vec3 aces(vec3 x){return clamp((x*(2.51*x+.03))/(x*(2.43*x+.59)+.14),0.,1.);}
float hh(vec2 p){return fract(sin(dot(p,vec2(12.9898,78.233)))*43758.5453);}
float n1(float x,float n){x=fract(x)*n;float i=floor(x),f=x-i;f=f*f*(3.-2.*f);return mix(hh(vec2(i,n)),hh(vec2(mod(i+1.,n),n)),f);}   // noise round a circle
float hx(vec2 q,float R){q=abs(q);float d=max(q.x*.866+q.y*.5,q.y)/R;return smoothstep(1.,.9,d)*(.3+.7*d*d);}                      // a ghost: a soft hexagon, brighter at its rim
// what a bright sun does inside a lens: a veil, rays, a streak, ghosts strung along the line through the middle of the frame, a halo
vec3 flare(vec2 p,vec2 s){
  vec2 d=p-s;float r=length(d),a=atan(d.y,d.x)/6.2832+s.x*.07;
  vec3 c=vec3(1.,.9,.75)*(.02/(r*r*30.+.03)+.012/(r+.03));
  c+=vec3(1.,.85,.65)*(pow(n1(a,9.)*n1(a+.3,23.),2.)*2.2+pow(abs(cos(a*18.85+.4)),80.)*1.2)*.09/(r*5.+.12)*exp(-r*1.5);
  c+=vec3(.35,.55,1.)*exp(-abs(d.y)*70.)/(1.+d.x*d.x*2.5)*.3;
  c+=vec3(.5,.8,.4)*hx(p+s*.35,.07)*.06+vec3(.3,.5,1.)*hx(p+s*.7,.12)*.05+vec3(1.,.6,.3)*hx(p+s*1.15,.05)*.09
    +vec3(.45,.3,.9)*hx(p+s*1.6,.22)*.035+vec3(.8,.9,1.)*hx(p-s*.45,.035)*.08;
  vec3 hl=(vec3(r)-vec3(.4,.42,.44))/.018;
  return c+exp(-hl*hl)*.05*n1(a,4.);}
void main(){
  vec2 v=gl_FragCoord.xy/uR,c=v-.5,p=(gl_FragCoord.xy*2.-uR)/uR.y;float r2=dot(c,c);
  if(uGl>0.){float g=hh(vec2(floor(v.y*36.),floor(uT*24.)));if(g>1.-uGl*.6)v.x+=(hh(vec2(g,3.))-.5)*.2*uGl;}   // a camera being hit: rows knocked sideways
  vec2 o=c*r2*(.012+.03*uFl);
  vec3 col=vec3(texture(uC,v-o).r,texture(uC,v).g,texture(uC,v+o).b);
  col+=texture(uB,v).rgb*.16;
  if(uFi>0.)col+=flare(p,uSs.xy)*uFc*uFi*texture(uP,vec2(.5)).r;
  if(uXi>0.){               // a flare through a telescope: the mesh in front of the detector throws a cross of light, and the brightest column bleeds
    vec2 d=(p-uXs)*mat2(.7071,-.7071,.7071,.7071);float l=length(d);
    col+=uXc*uXi*((exp(-abs(d.x)*140.)+exp(-abs(d.y)*140.))*(.6+.4*cos(l*90.))/(1.+l*5.)+.5*exp(-abs(p.x-uXs.x)*400.)/(1.+abs(p.y-uXs.y)*4.));
  }
  col*=1.-1.1*r2;
  col+=uFl*.3;
  col=pow(aces(col*1.15),vec3(.4545));
  if(uSn>0.){               // protons from the flare striking the detector: snow
    vec2 g=gl_FragCoord.xy*1080./uR.y;float f=floor(uT*20.);
    col+=step(1.-uSn*.01,hh(floor(g/3.)+f))+step(1.-uSn*.002,hh(floor(g/vec2(14.,2.5))+f+9.))*.8+step(1.-uSn*.002,hh(floor(g/vec2(2.5,12.))+f+5.))*.8;
  }
  float sp=texture(uS,vec2(abs(c.x)*2.,uRow)).r;
  col+=.35*step(gl_FragCoord.y/uR.y,.003+.035*sp)*vec3(.6,.8,1.);
  vec4 tx=texture(uX,vec2(gl_FragCoord.x/uR.x,1.-gl_FragCoord.y/uR.y));
  col=mix(col,tx.rgb,tx.a*uXa);
  col+=(hh(gl_FragCoord.xy+uT*61.)-.5)*(.035+.3*uGl);
  O=vec4(col*uF,1);
}`;

/* ---------------- GL setup ---------------- */
const C=document.getElementById('c'),gl=C.getContext('webgl2',{antialias:false,alpha:false,powerPreference:'high-performance'});
if(!gl){document.body.innerHTML='<p style="color:#fff;font:16px sans-serif;padding:2em">This demo needs WebGL2.</p>';return}
const HF16=gl.getExtension('EXT_color_buffer_float')||gl.getExtension('EXT_color_buffer_half_float');
gl.getExtension('KHR_parallel_shader_compile');
const IF=HF16?gl.RGBA16F:gl.RGBA8,TY=HF16?gl.HALF_FLOAT:gl.UNSIGNED_BYTE;
gl.bindVertexArray(gl.createVertexArray());
const tex=(unit,wrapT)=>{const t=gl.createTexture();gl.activeTexture(gl.TEXTURE0+unit);gl.bindTexture(gl.TEXTURE_2D,t);
 gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);
 gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,wrapT||gl.CLAMP_TO_EDGE);return t};
const target=(w,h)=>{const t=tex(1);gl.texImage2D(gl.TEXTURE_2D,0,IF,w,h,0,gl.RGBA,TY,null);
 const f=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,f);gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,t,0);return{t,f,w,h}};
const prog=(fs,vs)=>{const p=gl.createProgram(),sh=[];
 for(const[ty,src]of[[gl.VERTEX_SHADER,vs||VS],[gl.FRAGMENT_SHADER,fs]]){const s=gl.createShader(ty);gl.shaderSource(s,src);gl.compileShader(s);gl.attachShader(p,s);sh.push(s)}
 gl.linkProgram(p);return{p,sh,u:null}};
const errs=[];
const use=o=>{
 if(!o.u){o.u={};
  if(!gl.getProgramParameter(o.p,gl.LINK_STATUS)){const e=gl.getProgramInfoLog(o.p)+'\n'+gl.getShaderInfoLog(o.sh[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)}}
 gl.useProgram(o.p);return o.u};
// set uniforms from an object: a number is a float, {i} an int, {m} a mat3, {v3}/{v4}/{f} arrays of vec3/vec4/float, a short array a vector
const su=(u,o)=>{for(const k in o){const l=u[k],v=o[k];if(l==null)continue;
 if(typeof v=='number')gl.uniform1f(l,v);else if(v.i!=null)gl.uniform1i(l,v.i);else if(v.m)gl.uniformMatrix3fv(l,false,v.m);
 else if(v.v4)gl.uniform4fv(l,v.v4);else if(v.v3)gl.uniform3fv(l,v.v3);else if(v.f)gl.uniform1fv(l,v.f);
 else if(v.length==2)gl.uniform2fv(l,v);else if(v.length==3)gl.uniform3fv(l,v);else gl.uniform4fv(l,v)}};
const PS={sun:prog(HEAD+SUN),orr:prog(HEAD+ORR),cls:prog(HEAD+CLS)},PP=prog(PF,PV),PB=prog(PRB),PD=prog(DOWN),PU=prog(UP),PC=prog(COMP);

// spectrogram texture: 256 log-frequency bins x 128 rows of history (ring buffer)
const NB=256,HR=128,cur=new Float32Array(NB),row8=new Uint8Array(NB);
const TS=tex(0,gl.REPEAT);gl.pixelStorei(gl.UNPACK_ALIGNMENT,1);
gl.texImage2D(gl.TEXTURE_2D,0,gl.R8,NB,HR,0,gl.RED,gl.UNSIGNED_BYTE,new Uint8Array(NB*HR));
// text overlay
const TX=tex(3),XC=document.createElement('canvas'),X=XC.getContext('2d');
let W=0,H=0,sc=1,scMax=1,S=null,B=[],txt=[],txtDirty=1;
// one pixel that remembers how much of the Sun shows
gl.activeTexture(gl.TEXTURE4);const PR=target(1,1);
// draw once with every program now, so that none of them is first built in the middle of the music
gl.viewport(0,0,1,1);for(const o of[PS.sun,PS.orr,PS.cls,PB,PD,PU,PC]){use(o);gl.drawArrays(gl.TRIANGLES,0,3)}use(PP);gl.drawArrays(gl.POINTS,0,1);
gl.clearColor(0,0,0,1);gl.clear(gl.COLOR_BUFFER_BIT);
const free=o=>{if(o){gl.deleteTexture(o.t);gl.deleteFramebuffer(o.f)}};
const alloc=()=>{free(S);B.forEach(free);B=[];
 let w=Math.max(2,W*sc|0),h=Math.max(2,H*sc|0);S=target(w,h);
 for(let i=0;i<6;i++){w=Math.max(1,w>>1);h=Math.max(1,h>>1);B.push(target(w,h))}};
const resize=()=>{const d=Math.min(devicePixelRatio||1,2);W=C.width=Math.max(2,innerWidth*d|0);H=C.height=Math.max(2,innerHeight*d|0);
 scMax=Math.min(1,Math.sqrt(3.6e6/(W*H)));sc=Math.min(scMax,Math.sqrt(1.4e6/(W*H)));alloc();txtDirty=1};   // start modest, grow if there is room
addEventListener('resize',resize);resize();

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

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

/* ---------------- orbits ---------------- */
// Distances in AU, time in years, so the Sun's pull is 4 pi^2. The world is (x, north, y) of the ecliptic. A bar at 140 BPM is 12/7 s.
const D2R=Math.PI/180,TAU=2*Math.PI,MU=4*Math.PI*Math.PI,BAR=12/7,LEN=92*BAR;
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],
 dot=(a,b)=>a[0]*b[0]+a[1]*b[1]+a[2]*b[2],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]],
 len=a=>Math.hypot(a[0],a[1],a[2]),nrm=a=>mul(a,1/(len(a)||1)),lerp=(a,b,t)=>[a[0]+(b[0]-a[0])*t,a[1]+(b[1]-a[1])*t,a[2]+(b[2]-a[2])*t],
 cl=(x,a=0,b=1)=>Math.min(b,Math.max(a,x)),ss=(a,b,x)=>{x=cl((x-a)/(b-a));return x*x*(3-2*x)},
 bez=(a,b,c,u)=>[0,1,2].map(i=>(1-u)*(1-u)*a[i]+2*u*(1-u)*b[i]+u*u*c[i]),
 rotY=(v,a)=>[v[0]*Math.cos(a)+v[2]*Math.sin(a),v[1],v[2]*Math.cos(a)-v[0]*Math.sin(a)],
 sph=(la,lo,r=1)=>[r*Math.cos(la*D2R)*Math.sin(lo*D2R),r*Math.sin(la*D2R),r*Math.cos(la*D2R)*Math.cos(lo*D2R)];
// a camera looking from co at ta: columns right, up, forward
const look=(co,ta,up,roll)=>{const f=nrm(sub(ta,co));let r=nrm(cross(up,f)),u=cross(f,r);
 if(roll){const c=Math.cos(roll),s=Math.sin(roll),q=add(mul(r,c),mul(u,s));u=add(mul(u,c),mul(r,-s));r=q}
 return[...r,...u,...f]};
// world to body: a turn of -a about axis k
const rotm=(k,a)=>{k=nrm(k);const c=Math.cos(a),s=-Math.sin(a),t=1-c,[x,y,z]=k;
 return[t*x*x+c,t*x*y+s*z,t*x*z-s*y,t*x*y-s*z,t*y*y+c,t*y*z+s*x,t*x*z+s*y,t*y*z-s*x,t*z*z+c]};
// the planets: semi-major axis, eccentricity, longitude of perihelion, mean longitude at 2000.0, period, radius as drawn, turns per second as drawn
const PL=[[.387,.2056,77.46,252.25,.2408,.03,.05],[.723,.0068,131.6,181.98,.6152,.055,.03],[1,.0167,102.94,100.46,1,.06,.5],[1.524,.0934,336.04,355.45,1.8809,.045,.5],
 [5.203,.0484,14.73,34.4,11.862,.2,.8],[9.537,.0539,92.6,49.95,29.457,.17,.7],[19.19,.0473,170.95,313.24,84.011,.11,.4],[30.07,.0086,44.96,304.88,164.79,.105,.4]];
const plan=(k,y)=>{const[a,e,w,L,P]=PL[k],M=(L-w)*D2R+TAU*(y-2000)/P,v=M+2*e*Math.sin(M)+1.25*e*e*Math.sin(2*M),r=a*(1-e*e)/(1+e*Math.cos(v)),th=v+w*D2R;
 return[r*Math.cos(th),0,r*Math.sin(th)]};
// an orbit's own axes in the world: toward perihelion, and a quarter turn on. From node, inclination and argument of perihelion in degrees
const orient=(Om,i,w)=>{Om*=D2R;i*=D2R;w*=D2R;const cO=Math.cos(Om),sO=Math.sin(Om),ci=Math.cos(i),si=Math.sin(i),cw=Math.cos(w),sw=Math.sin(w);
 return[[cO*cw-sO*sw*ci,sw*si,sO*cw+cO*sw*ci],[-cO*sw-sO*cw*ci,cw*si,-sO*sw+cO*cw*ci]]};
// a point on a conic of perihelion distance q: ellipse by eccentric anomaly, hyperbola by its counterpart, parabola by tan(v/2)
const conic=(q,e,E)=>e<.999?[q/(1-e)*(Math.cos(E)-e),q/(1-e)*Math.sqrt(1-e*e)*Math.sin(E)]:
 e>1.001?[q/(e-1)*(e-Math.cosh(E)),q/(e-1)*Math.sqrt(e*e-1)*Math.sinh(E)]:[q*(1-E*E),2*q*E];
// that parameter, dt years after perihelion: Kepler's equation by Newton, Barker's in closed form
const kepH=(e,M)=>{let F=Math.asinh(M/e);for(let i=0;i<60;i++){const d=(e*Math.sinh(F)-F-M)/(e*Math.cosh(F)-1);F-=d;if(Math.abs(d)<1e-13)break}return F};
const barker=Mp=>{const W=1.5*Mp,y=Math.cbrt(W+Math.hypot(W,1));return y-1/y};
const anom=(q,e,dt)=>{
 if(e<.999){const a=q/(1-e),M=Math.sqrt(MU/a**3)*dt,m=((M+Math.PI)%TAU+TAU)%TAU-Math.PI;let E=e<.8?m:Math.PI*Math.sign(m||1);
  for(let i=0;i<60;i++){const d=(E-e*Math.sin(E)-m)/(1-e*Math.cos(E));E-=d;if(Math.abs(d)<1e-13)break}return E+M-m}
 if(e>1.001)return kepH(e,Math.sqrt(MU*((e-1)/q)**3)*dt);
 return barker(Math.sqrt(MU/(2*q**3))*dt)};
// where a visitor is in year y: parameter, position, distance, heading, angular speed
const vis=(o,y)=>{const E=anom(o.q,o.e,y-o.T),f=E=>{const[x,z]=conic(o.q,o.e,E);return add(mul(o.o[0],x),mul(o.o[1],z))},p=f(E),r=len(p);
 return{E,p,r,v:nrm(sub(f(E+1e-3),f(E-1e-3))),w:Math.sqrt(MU*o.q*(1+o.e))/(r*r)}};
const om3=o=>[...o.o[0],...o.o[1],0,0,0];
// the visitors, with their real orbits
const apo=(a,e,Om,i,w,nu)=>{const E=2*Math.atan(Math.sqrt((1-e)/(1+e))*Math.tan(nu*D2R/2)),M=E-e*Math.sin(E);return{q:a*(1-e),e,T:2029.281-M/Math.sqrt(MU/a**3),o:orient(Om,i,w)}};
const HAL={q:.5871,e:.96712,T:1986.108,o:orient(58.86,162.24,111.87)},      // 1P/Halley: period 75.4 years, back at the end of July 2061
 ISO={q:.01244,e:1,T:2013.908,o:orient(295.65,62.4,345.56)},                 // C/2012 S1 ISON: a parabola to 1.2 million km above the Sun
 OUM={q:.25534,e:1.1995,T:2017.689,o:orient(24.6,122.69,241.7)},             // 1I/'Oumuamua: a hyperbola - unbound
 AP1=apo(.9224,.1911,204,3.34,126.7,-126.7),AP2=apo(1.1032,.1893,203.9,2.19,70.2,-70.2);   // 99942 Apophis before and after 13 April 2029: it meets the Earth at its node
const MN=['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'],ML=[31,28,31,30,31,30,31,31,30,31,30,31];
const date=y=>{const Y=Math.floor(y);let d=Math.floor((y-Y)*365),m=0;while(d>=ML[m]){d-=ML[m];m++}return Y+' '+MN[m]+' '+String(d+1).padStart(2,'0')};
// the Sun's active regions: latitude, longitude, size, tilt of the field under them
const ARS=[[16,95,.2,-.25],[-13,-18,.25,.25],[21,24,.15,-.15],[-22,52,.13,.3],[10,-62,.14,.2],[-17,-105,.2,-.2]];
const AR4=new Float32Array(24),AM4=new Float32Array(24),PL4=new Float32Array(40),OR4=new Float32Array(32),PSP=new Float32Array(10),DM4=new Float32Array(20),
 IM4=new Float32Array(32),J4=new Float32Array(16),I3=[1,0,0,0,1,0,0,0,1];
// turn the Sun by sr and say where its regions are now
const suns=sr=>ARS.map(([la,lo,s,ti],i)=>{
 const a=sph(la,lo),e=nrm(cross([0,1,0],a)),n=cross(a,e),m=add(mul(e,Math.cos(ti)),mul(n,Math.sin(ti))),c=Math.cos(sr),q=Math.sin(sr),
  R=v=>[c*v[0]-q*v[2],v[1],q*v[0]+c*v[2]],aw=R(a),mw=R(m);
 AR4.set([...aw,s],i*4);AM4.set([...mw,1],i*4);return aw});
// the sheet of the gravity view, as the shaders compute it
const hfj=(x,z,g)=>{let h=-2.2/Math.sqrt(x*x+z*z+.5);for(let i=0;i<5;i++){const dx=x-DM4[i*4],dz=z-DM4[i*4+1];h-=DM4[i*4+2]/Math.sqrt(dx*dx+dz*dz+DM4[i*4+3])}return h*g};

/* ---------------- timeline ---------------- */
// the bands of light: what the label says, and where on the spectrum it sits (log10 of the wavelength in metres)
const BN=[['VISIBLE LIGHT · 400–700 nm','the surface · 5 800 K',-6.26],['HYDROGEN ALPHA · 656 nm','the chromosphere · 10 000 K',-6.18],
 ['EXTREME ULTRAVIOLET · 304 Å','helium · 50 000 K',-7.52],['EXTREME ULTRAVIOLET · 171 Å','iron · 600 000 K',-7.77],
 ['EXTREME ULTRAVIOLET · 193 Å','iron · 1.5 million K',-7.71],['EXTREME ULTRAVIOLET · 211 Å','iron · 2 million K',-7.68],
 ['EXTREME ULTRAVIOLET · 131 Å','iron · 10 million K',-7.88],['X-RAYS · 1–8 Å','flares · 20 million K',-9.4],
 ['THERMAL INFRARED · 10 µm','heat: what the Sun has warmed',-5],['INFRARED · 2.3 µm','methane swallows it: only what is high shows',-5.64],
 ['ULTRAVIOLET · 121.6 nm','hydrogen, Lyman alpha',-6.92],['GRAVITY','the dent the Sun makes',0],['EIGHT WAYS OF SEEING ONE STAR','from 5 800 K to 20 million K',0],['VISIBLE LIGHT · 400–700 nm','sunlight on dust and gas',-6.26]],
 BC=[[1,1,1],[1,.35,.12],[1,.3,.1],[1,.8,.3],[1,.7,.42],[.8,.45,1],[.3,.9,.85],[.45,.7,1],[1,.45,.2]];   // what colour a band's picture is
let flash=0,fade=0,lt=0,ft=1/60,hold=0,frames=0,lsh=-1,dbg=-1,tmin=.05,pdt=.05,cap=1,capT=0,kf=1,bpNow=0,mk=-6.26,nimp=0;
const drawText=()=>{txtDirty=0;
 const w=XC.width=Math.min(W,1600),h=XC.height=Math.max(1,Math.round(w*H/W));X.clearRect(0,0,w,h);X.fillStyle='#fff';X.textBaseline='middle';X.shadowColor='rgba(0,0,0,.85)';X.shadowBlur=h*.014;
 const sans='"Helvetica Neue",Helvetica,Arial,sans-serif',mono='ui-monospace,Menlo,Consolas,monospace',[big,sub,l1,l2,l3,bl]=txt,sp=v=>{try{X.letterSpacing=h*v+'px'}catch(e){}};
 if(big){X.textAlign='center';X.font=`200 ${h*.12}px ${sans}`;sp(.05);X.fillText(big,w/2+h*.025,h*.47)}
 sp(.008);
 if(sub){X.textAlign='center';X.font=`400 ${h*.026}px ${mono}`;X.fillText(sub,w/2,h*.6)}
 X.textAlign='left';
 if(l1){X.font=`300 ${h*.058}px ${mono}`;X.fillText(l1,h*.06,h*.09)}                                    // the date
 if(l2){X.font=`400 ${h*.026}px ${mono}`;X.fillText(l2,h*.062,h*.148)}                                  // who is passing
 if(l3){X.font=`400 ${h*.023}px ${mono}`;X.globalAlpha=.8;X.fillText(l3,h*.062,h*.185);X.globalAlpha=1}  // and a line about it
 if(bl>=0){const b=BN[bl],x0=h*.062,y0=h*.925,bw=h*.62,bh=h*.007;                                       // which light we are seeing by
  X.font=`400 ${h*.024}px ${mono}`;X.fillText(b[0],x0,h*.845);X.font=`400 ${h*.02}px ${mono}`;X.globalAlpha=.8;X.fillText(b[1],x0,h*.88);
  if(b[2]){                                                                                             // and where that is: x-rays on the left, heat on the right, the eye's sliver between
   const g=X.createLinearGradient(x0,0,x0+bw,0);
   [[0,'#b8c8ff'],[.36,'#8f84ff'],[.56,'#8a5cff'],[.654,'#7a00ff'],[.664,'#2040ff'],[.673,'#00c8ff'],[.682,'#00e060'],[.69,'#f0f000'],[.695,'#ff8000'],[.7,'#ff1010'],[.82,'#a01818'],[1,'#501010']].forEach(s=>g.addColorStop(s[0],s[1]));
   X.globalAlpha=.7;X.fillStyle=g;X.fillRect(x0,y0,bw,bh);X.fillStyle='#fff';X.globalAlpha=1;
   const mx=x0+bw*(mk+10)/5.5;X.fillRect(mx-h*.0015,y0-h*.012,h*.003,bh+h*.024);
   X.globalAlpha=.6;X.font=`400 ${h*.014}px ${mono}`;[['X-RAY',0],['EXTREME UV',.3],['UV',.555],['VISIBLE',.64],['INFRARED',.84]].forEach(s=>X.fillText(s[0],x0+bw*s[1],y0+h*.028))}
  X.globalAlpha=1}
 gl.activeTexture(gl.TEXTURE3);gl.bindTexture(gl.TEXTURE_2D,TX);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,XC)};

const frame=now=>{
 requestAnimationFrame(frame);frames++;
 const t=now/1e3,dt=Math.min(.1,Math.max(.001,t-lt));lt=t;
 analyse(dt);
 let run=0,mt=0;
 if(ext){mt=(ctx.currentTime-extT)%LEN;run=1}
 else if(t0!=null&&ctx.state=='running'){mt=Math.max(0,ctx.currentTime-t0-(ctx.outputLatency||0))%LEN;run=1}
 if(dbg>=0){mt=dbg*BAR;run=1}
 const bp=mt/BAR,tm=run?mt:t%1e3,asp=W/H,U=(a,b)=>cl((bp-a)/(b-a));bpNow=bp;
 // what a shot may set
 let P='sun',co=[0,0,3],ta=[0,0,0],up=[0,1,0],fv=1.7,roll=0,sh=0,pcam=null,
  b0=0,b1=0,wp=-9,wl=0,xp=1,stb=1,yr=0,big='',sbt='',l1='',l2='',l3='',bl=-1,
  fi=0,fc=[1,.95,.85],sun=null,sa=.01,sn=0,gli=0,xi=0,xw=null,xo=null,xc=[1,1,1],imp=0;
 const Q={uPie:0,uGr:0,uEr:.17,uEw:.022,uEb:1,uEs:0,uFa:0,uWv:0,uAu:0,uOb:1,uHa:[0,0,0,0],uHb:[0,0,0,0],uHc:[1,1,1]},pts=[];
 const sr=.1+.012*mt,ars=suns(sr);
 for(let i=0;i<6;i++)AM4[i*4+3]=(i==1?1.25:1)*(1+.35*A[1]);
 IM4.fill(0);
 // a wipe: from bar tb the band changes from a to b, left to right, in six tenths of a bar
 const wipe=(tb,a,b)=>{if(bp>=tb){b0=b1=b;if(bp<tb+.6){b0=a;wp=(asp+.5)*(2*ss(tb,tb+.6,bp)-1);wl=1}}};
 // the orrery: planets where they are in year yr, as seen from about D away
 const orr=D=>{const rs=cl(D/7,.15,1.3);
  for(let k=0;k<8;k++){const p=plan(k,yr),[a,e,w]=PL[k],cx=-a*e*Math.cos(w*D2R),cz=-a*e*Math.sin(w*D2R);
   PL4.set([p[0],p[1],p[2],PL[k][5]*rs],k*4);OR4.set([cx,cz,a,Math.atan2(p[2]-cz,p[0]-cx)],k*4);PSP[k]=tm*PL[k][6]}
  PL4.fill(0,32);
  Q.uPl={v4:PL4};Q.uOr={v4:OR4};Q.uPs={f:PSP};Q.uSy=0;Q.uSz=Math.max(.012+.006*D,1.8*D*2/(S.h*fv));
  sun=[0,0,0];sa=Q.uSz/D;fi=1};
 // the small bodies: main belt, Hildas, Trojans, Kuiper belt
 const belt=(a,s)=>{[26000,2200,3000,6000].forEach((n,i)=>pts.push({n,u:{uMd:{i:0},uSb:{i},uP0:[a*(i?1.3:1),s||.012,0,0]}}))};
 // a visitor in the orrery: its whole path faintly, the part just travelled brightly, and if it is a comet, its tails and coma
 const visit=(o,h,c,act,full,fb)=>{
  if(full)pts.push({n:3000,u:{uMd:{i:1},uOm:{m:om3(o)},uP0:[o.q,o.e,h.E,full],uP1:[...c,1.4],uP2:[fb||.1,0,0,0]}});
  pts.push({n:900,u:{uMd:{i:1},uOm:{m:om3(o)},uP0:[o.q,o.e,h.E,o.e<.999?.55:1.6],uP1:[...c,1.8],uP2:[0,1.2,0,0]}});
  if(act>0){const k=cl(act/(h.r*h.r),0,1.6);
   pts.push({n:16000,u:{uMd:{i:2},uP0:[...h.p,h.r],uP1:[...h.v,h.w],uP2:[MU/(h.r*h.r),.14,.55*Math.min(k,1),k],uP3:[.008,3.5,0,0]}});
   Q.uHa=[...h.p,.007*Math.sqrt(k)];Q.uHc=[1.2,1.3,1.5]}};
 // close to: what is in front and what is behind
 const close=o=>{Object.assign(Q,{uTy:{i:o.ty},uBg:{i:o.bg||0},uPi:{i:o.pi||0},uBr:{m:o.br||I3},uSd:o.L,uBo:o.bo||[0,0,-1e3],uMo:o.mo||[0,0,0],uPsh:o.psh||[0,0,0],
   uSa:o.sa,uSb:o.sb||90,uPs:o.ps||0,uFr:o.fr||0,uJs:o.js||0,uSi:o.si||4,uJ:{v4:J4},uIm:{v4:IM4}});
  if(o.bg!=2){sun=add(co,mul(o.L,1e4));sa=o.sa;fi=o.fi==null?1:o.fi}};
 // a flare at region 0, tf seconds old: the flash, the prominence over it torn loose, the shock, the loops left glowing
 const flare=(tf,cap)=>{if(tf<0)return;const g=Math.min(.17+.1*tf+.2*tf*tf,cap);
  Q.uEr=g;Q.uEw=.022+.2*(g-.17);Q.uEb=(.022/Q.uEw)**.5*Math.exp(-Math.max(tf-2.6,0)*.5);Q.uEs=.4+3*Math.exp(-tf*.5);
  Q.uFa=1.3*Math.exp(-tf*1.1);Q.uWv=.45*tf;AM4[3]+=5*(1-Math.exp(-tf))};
 // and the plasma it throws up from spot a. sc: the Sun's radius in the picture's units, if it is not 1
 const spray=(a,tf,o={})=>{if(tf>=0)pts.push({n:o.n||22000,u:{uMd:{i:7},uP0:[...a,o.sc||1],uP1:[tf,o.dur||1.5,o.v||.75,o.cone||.9],
   uP2:[...(o.c||[1.6,1.6,1.6]),o.g==null?.6:o.g],uP3:[o.fade||.45,o.b||1,o.sz||.011,7],uBe:o.sc?[0,0,0]:[1,1,1]},vc:b=>BC[b]})};
 const dust=(n,B,s,fw,fo,v,c,be,br)=>pts.push({n,u:{uMd:{i:4},uP0:[B,s,fw,fo],uP1:v,uP2:[...c,60],uBe:be,uBr:{m:br||I3},uBk:.004}});

 if(!run||bp<16){                 // ---- the Sun, band by band
  P='sun';const a0=ars[0],a1=ars[1],lim=(d,o)=>rotY(a0,-(Math.acos(1/d)-o)),e=bp-14;
  if(!run||bp<4){const u=run?bp/4:.1+.1*Math.sin(t*.07);co=mul(nrm(add(a1,[.25-.2*u,.3,.2])),1.5+.1*u);ta=add(mul(a1,.9),[-.25,-.2,0]);bl=0;sh=0}
  else if(bp<8){const u=ss(4,8,bp),d=1.6+.75*u;co=mul(nrm(lerp(add(a1,[.05,.3,.2]),lim(d,.12),u)),d);ta=lerp(add(mul(a1,.9),[-.25,-.2,0]),mul(a0,1.02),u);wipe(4,0,1);wipe(6,1,2);bl=b1;sh=0}
  else if(bp<10){const u=U(8,10);co=mul(lim(2.05,.1+.05*u),2.05);ta=add(mul(a0,1.1),[0,.05*u,0]);fv=2.3;b0=b1=3;bl=3;sh=1}
  else if(bp<12){const u=ss(10,12,bp),d=2.05+2.5*u;co=mul(lim(d,.15+.5*u),d);ta=mul(a0,1.1*(1-u));fv=2.3+1*u;b0=b1=3;wipe(10,3,4);wipe(11,4,5);bl=b1;sh=1}
  else if(bp<14){const u=U(12,14);co=mul(lim(4.55,.65+.08*u),4.55-.2*u);fv=3.3;Q.uPie=.07+.06*u;bl=12;sh=2}
  else{const u=U(14,16),d=2.4+1.1*u,tf=e*BAR;co=mul(lim(d,.05),d);ta=mul(a0,1.25+.6*u);fv=1.9;b0=b1=2;wipe(15,2,3);bl=b1;sh=3;        // the flare
   flare(tf,9);spray(a0,tf);xi=Q.uFa*1.6;xw=a0;xc=BC[b1];sn=cl((tf-1.2)/1.5)}
  xp=[1,1,1,1,1,1,1.2,1.3][b1];
  if(!run){big='PERIHELION';sbt='click to start'}else if(bp<3.2)big='PERIHELION';
 }else if(bp<24){                 // ---- out through the planets
  P='orr';sh=4;const u=U(16,24),D=.3*Math.exp(u*5.1),el=(5+27*u)*D2R,az=2.3+1.1*u;
  yr=1980+5.72*u;co=[D*Math.cos(el)*Math.cos(az),D*Math.sin(el),D*Math.cos(el)*Math.sin(az)];ta=[0,-.1*D,0];
  orr(D);belt(1);
  if(bp<20)spray(nrm([-.86,.25,.52]),(bp-16)*BAR,{n:8000,sc:.02,v:26,cone:.8,g:0,sz:.35,fade:.7,b:.8,dur:1.6,c:[1.6,1.2,.7]});   // what the flare threw out, passing us on its way
  l2=u<.45?'THE SOLAR SYSTEM':'eight planets · more than a million asteroids';l3=u<.45?'':'and now and then, something passing through';
 }else if(bp<27){                 // ---- Halley, 1986
  P='orr';sh=5;const u=U(24,27);yr=1985.72+.44*u;const h=vis(HAL,yr);
  co=add(mul(h.p,.3),[-1.4+.6*u,2.4-.5*u,-3.2+.8*u]);ta=mul(h.p,.55);
  orr(4);belt(.8);visit(HAL,h,[.7,.85,1],1,TAU);l2='1P/HALLEY';l3='back every 76 years · this time a fleet of spacecraft is waiting';
 }else if(bp<30){                 // its two tails, and then in ultraviolet
  P='orr';sh=6;const u=U(27,30);yr=1986.135+.03*u;const h=vis(HAL,yr),rh=nrm(h.p),hn=nrm(cross(rh,h.v));
  co=add(h.p,add(mul(hn,.3-.05*u),add(mul(rh,.1),mul(h.v,-.06+.07*u))));ta=add(h.p,mul(rh,.1));roll=-.5;stb=1.5;
  orr(4);fi=.6;
  const k=cl(1/(h.r*h.r),0,1.6);
  pts.push({n:60000,u:{uMd:{i:2},uP0:[...h.p,h.r],uP1:[...h.v,h.w],uP2:[MU/(h.r*h.r),.1,.4,k*.5],uP3:[.0035,5,0,0]},vc:b=>b==10?[.1,.08,.3]:[1,1,1]});
  Q.uHa=[...h.p,.004];Q.uHb=[...h.p,.035];Q.uHc=[1.5,1.6,1.8];
  wipe(28.5,0,10);bl=b1||13;l2='1P/HALLEY';l3=bp<28.5?'two tails: dust, curved and pale · ions, straight and blue':'in ultraviolet, a cloud of hydrogen wider than the Sun';
 }else if(bp<36){                 // past the nucleus
  P='cls';sh=7;const u=U(30,36),L=nrm([.25,.2,1]);yr=1986.1986;
  co=bez(add(mul(L,-9),[.12,.05,0]),[3.2,.4,2.4],[1.3,2.2,5],u);roll=.3*u;fv=1.5;
  const br=rotm([.3,1,.2],.3+.12*tm);
  [[.5,.3,.8],[-.4,.5,.75],[.1,-.5,.85],[-.6,-.2,.75]].forEach((j,i)=>{j=nrm(j);J4.set([...j,cl(dot([br[0]*j[0]+br[1]*j[1]+br[2]*j[2],br[3]*j[0]+br[4]*j[1]+br[5]*j[2],br[6]*j[0]+br[7]*j[1]+br[8]*j[2]],L)+.3)*(.6+.4*i%2)],i*4)});
  close({ty:0,L,sa:.012,si:2.5,js:.6,br});
  dust(7000,14,.012,8,.03,[.05,.03,.2],[.4,.38,.34],[1.25,.6,.55],br);
  l2='GIOTTO · 596 km from the nucleus of Halley’s comet';l3='fifteen kilometres of ice and dust, darker than coal';gli=ss(35.3,36,bp);
 }else if(bp<38){                 // ---- years pass; to Jupiter
  P='orr';sh=8;const s=ss(36,38,bp);yr=1986.2+6.3*s;const J=plan(4,yr);
  co=lerp([-2,4,-6],add(J,[-.9,.45,-1.3]),s);ta=lerp([0,0,0],J,s);fv=1.7+2.5*ss(37.2,38,bp);
  orr(6);belt(.8);
 }else if(bp<42){                 // ---- Shoemaker-Levy 9 inside Jupiter's Roche limit
  P='cls';sh=9;const u=U(38,42),Mp=-2.2+5.6*u,D=barker(Mp),q=1.31;yr=1992.513+.004*u;
  const hn=nrm([.15,.55,-.82]),Pv=nrm(cross([1,0,0],hn)),Qv=cross(hn,Pv),Xp=add(mul(Pv,q*(1-D*D)),mul(Qv,2*q*D)),L=nrm(add(mul(Pv,.5),add(mul(Qv,-.6),mul(hn,.6))));   // seen from above the comet's orbit, which is steeply tilted to Jupiter's equator
  co=add(mul(hn,3.8-.5*u),add(mul(Pv,-.3),mul(Qv,-.6+1.6*u)));ta=add(mul(Xp,.45),mul(Pv,-.3));up=Pv;pcam=co;
  close({ty:-1,bg:1,pi:4,L,sa:.004,bo:co,ps:.2*tm});
  pts.push({n:12000,u:{uMd:{i:3},uSb:{i:0},uOm:{m:[...Pv,...Qv,0,0,0]},uP0:[q,Mp,.22,.012],uP2:[0,0,0,.07],uP3:[0,0,0,.014],uBe:[1,1,1],uSd:L}});
  l2='SHOEMAKER–LEVY 9';l3=Mp<0?'a comet in orbit round Jupiter, about to pass 40 000 km above the clouds':'inside the Roche limit: Jupiter’s tide pulls it into a string of pieces';
 }else if(bp<44){                 // months later: the string of pearls
  P='cls';sh=10;const u=U(42,44),E=3.7+.8*u,e=.99626;yr=1993.5+.9*u;
  const Pv=nrm([.3,.2,-1]),Qv=nrm(cross([0,1,0],Pv)),hn=cross(Pv,Qv),Xp=add(mul(Pv,350*(Math.cos(E)-e)),mul(Qv,350*Math.sqrt(1-e*e)*Math.sin(E))),L=nrm([.5,.2,.8]);
  co=add(Xp,add(mul(hn,17-3*u),mul(L,5)));ta=Xp;up=Pv;pcam=co;roll=.35;stb=1.4;
  close({ty:-1,bg:1,pi:4,L,sa:.004,bo:co,ps:.2*tm,fi:0});
  pts.push({n:20000,u:{uMd:{i:3},uSb:{i:1},uOm:{m:[...Pv,...Qv,0,0,0]},uP0:[0,E,.02+.012*u,.3],uP1:[350,e,3.5,0],uP2:[0,0,0,.3],uP3:[0,0,0,.05],uBe:[1,1,1],uSd:L}});
  l2='SHOEMAKER–LEVY 9';l3='twenty-one pieces in a line five million kilometres long, falling back';
 }else if(bp<48){                 // the impacts
  P='cls';sh=11;const u=U(44,48),tt=(bp-44)*BAR,L=nrm([1,.12,-.25]),Pi=nrm([-.16,-.695,-.7]),tn=nrm(sub([0,1,0],mul(Pi,Pi[1]))),vd=nrm(add(mul(Pi,-.7),mul(tn,.7))),ps=1+.6*tt;
  yr=1994.538+.016*u;co=[-1.1+.2*u,-1.25,-2+.3*u];ta=[.05,-.3,0];pcam=co;
  for(let k=0;k<8;k++){const ag=tt-k*BAR/2;IM4.set([Math.atan2(Pi[2],Pi[0])-1-.6*k*BAR/2,Math.max(ag,0),.06+.02*(k*7%3),0],k*4);if(ag>0)imp=k+1}
  wipe(46,0,8);bl=bp<46?-1:9;
  close({ty:-1,bg:1,pi:4,L,sa:.004,bo:co,ps});
  pts.push({n:4000,u:{uMd:{i:3},uSb:{i:2},uP0:[0,tt,0,0],uP1:[0,BAR/2,2.2,1.5],uP2:[...Pi,1],uP3:[...vd,.012],uBe:[1,1,1],uSd:L},vc:b=>b==8?[1,.5,.25]:[1,1,1]});
  l2='SHOEMAKER–LEVY 9 · 16–22 JULY';l3='at 60 km a second · each scar the size of the Earth';
 }else if(bp<52){                 // ---- years pass; ISON falls toward the Sun
  P='orr';const s=ss(48,50,bp),u=U(50,52);yr=bp<50?1994.56+19.3*s:2013.86+.0465*u;const h=vis(ISO,yr);sh=bp<50?12:13;
  if(bp<50){co=lerp([8,14,-22],add(mul(h.p,1.3),[.3,.5,-.6]),s);ta=mul(h.p,.4*s)}
  else{const d=.12+.5*h.r;co=add(mul(h.p,1+d/h.r),add(mul(nrm(cross(h.p,h.v)),.25*d),[0,.3*d,0]));ta=mul(h.p,.5)}
  orr(bp<50?12*(1-s)+1:h.r);belt(bp<50?.8:.25);visit(ISO,h,[1,.9,.75],.25,0);
  if(bp>=50){l2='C/2012 S1 ISON';l3='from the Oort cloud · due to pass 1.2 million km above the Sun'}
 }else if(bp<60){                 // ---- ISON at the Sun
  P='cls';sh=14;const u=U(52,60),tt=(bp-52)*BAR,D=-1+1.9*u,q=1.9,a0=ars[0];yr=2013.908;
  const Pv=nrm(rotY([a0[0],0,a0[2]],1.05)),Qv=nrm(add(cross([0,1,0],Pv),[0,.15,0])),bo=add(add(mul(Pv,q*(1-D*D)),mul(Qv,2*q*D)),[0,.45,0]),L=nrm(mul(bo,-1)),sd=nrm(cross(L,[0,1,0]));
  co=add(mul(L,-3.4+.5*u),add(mul(sd,2.9*Math.cos(.5+.9*u)),[0,.6+1.4*Math.sin(.9*u),0]));fv=1.5;
  wipe(54,0,3);wipe(56,3,2);wipe(58,2,0);bl=b1;imp=(bp>=55)+(bp>=56);
  {const tf=(bp-55)*BAR;flare(tf,1.25);if(tf>=0){spray(a0,tf,{n:18000});pts[pts.length-1].u.uCo=bo;xi=Q.uFa*1.6;xw=a0;xo=bo;xc=BC[b1]}}   // and behind it the Sun flares
  const fr=bp<56?0:1.15*(1-Math.exp(-(bp-56)*.75)),br=rotm([.2,1,.4],.2*tt);
  [[.5,.3,.8],[-.4,.5,.75],[.1,-.5,.85],[-.6,-.2,.75]].forEach((j,i)=>J4.set([...nrm(j),.7],i*4));
  close({ty:3,bg:2,bo,L,sa:.38,si:5,js:bp<56?.5:bp<57.5?.5*Math.exp(-(bp-56)*1.2):0,fr,br});
  dust(9000,12,.006,6,.03,mul(L,-1.5),[.5,.5,.5],[0,0,0]);pts[pts.length-1].vc=b=>BC[b];
  if(bp>=56)pts.push({n:16000,u:{uMd:{i:6},uP0:[.7,(bp-56)*BAR,.8,.2],uP1:[.007,20,0,0],uP2:[1.3,1.3,1.3,0],uSd:L,uBk:.006},vc:b=>BC[b]});
  l2='C/2012 S1 ISON · PERIHELION';l3=bp<56?'2 700 °C · the Sun’s tide and heat at work on a ball of ice':'it did not survive';
 }else if(bp<62){                 // ---- years pass
  P='orr';sh=15;const s=ss(60,62,bp);yr=2013.92+3.53*s;co=lerp([1.5,1.2,-2.5],[2.2,5.2,-7.2],s);ta=[0,-1.3*s,0];orr(3+5*s);belt(.8);
 }else if(bp<66){                 // ---- 'Oumuamua on the Sun's gravity well
  P='orr';sh=16;const u=U(62,66),g=ss(62,62.9,bp),a=.3+.5*u,tq=2017.45+.55*u-OUM.T;yr=2017.45+.55*u;
  co=[8*Math.sin(a),3.4,-8*Math.cos(a)];ta=[0,-1.9,0];
  orr(2.5);Q.uGr=g;
  [.02,.035,.04,.025,.25].forEach((m,i)=>DM4.set([PL4[i*4],PL4[i*4+2],m,[.01,.012,.012,.01,.12][i]],i*4));
  for(let k=0;k<8;k++)PL4[k*4+1]=hfj(PL4[k*4],PL4[k*4+2],g)+PL4[k*4+3];
  Q.uSy=hfj(0,0,g)+Q.uSz;sun=[0,Q.uSy,0];fi=.7;
  const ai=2.3,e=OUM.e,an=ai-Math.acos(1/e),n=Math.sqrt(MU/1.2817**3);
  pts.push({n:45000,u:{uMd:{i:5},uP0:[1.2817,n,5.5,3.2],uP1:[ai,tq,.848,tq],uP2:[g*3,2.2,0,0]}});
  pts.push({n:700,u:{uMd:{i:1},uOm:{m:[Math.cos(an),0,Math.sin(an),-Math.sin(an),0,Math.cos(an),0,0,0]},uP0:[OUM.q,e,kepH(e,n*tq),3.2],uP1:[.7,1,.95,3],uP2:[0,4*g,0,0]}});
  bl=11;l2='1I/ʻOUMUAMUA';l3='from another star · 87 km/s at the turn · too fast for the Sun to keep';
 }else if(bp<72){                 // past the shard
  P='cls';sh=17;const u=U(66,72),tt=(bp-66)*BAR,L=nrm([-.6,.5,-.3]),br=rotm([.25,1,.35],.4+.5*tt);yr=2017.79+.01*u;
  co=bez([-5,1.3,-5.5],[.6,.9,-1.5],[4.6,-.4,3.4],u);ta=[.3*Math.sin(u*3),0,0];fv=1.6;roll=-.2+.5*u;
  wipe(70,0,8);bl=bp<70?-1:8;
  close({ty:1,L,sa:.009,si:2,br});
  dust(2500,16,.008,5,.0,[.2,.05,.1],[.6,.57,.54],[2.4,.4,.5],br);pts[pts.length-1].vc=b=>b==8?[.5,.2,.1]:[1,1,1];
  l2='1I/ʻOUMUAMUA';l3='seen arriving from another star · a few hundred metres long, tumbling';
 }else if(bp<74){                 // ---- years pass; to the Earth
  P='orr';sh=18;const s=ss(72,74,bp);yr=2017.95+11.25*s;const E=plan(2,yr),h=vis(AP1,yr);
  co=lerp([0,9,-7],add(E,[-.55,.4,-.65]),s);ta=lerp([0,0,0],E,s);fv=1.7+1.8*ss(73.3,74,bp);
  orr(7-5*s);belt(.8);visit(AP1,h,[1,.55,.4],0,TAU);PL4.set([...h.p,.012],36);
 }else if(bp<82){                 // ---- Apophis passes the Earth
  P='cls';sh=19;const u=U(74,82),tt=(bp-74)*BAR,F=kepH(4.25,-6.5+11.5*u),Pe=nrm([.55,.1,-.8]),Qe=nrm(cross([0,1,0],Pe));yr=2029.2803+.0012*u;
  const bo=add(mul(Pe,1.835*(4.25-Math.cosh(F))),add(mul(Qe,1.835*4.1307*Math.sinh(F)),[0,.8,0])),Ed=nrm(mul(bo,-1)),L=nrm([.75,.22,.62]),sd=nrm(cross(Ed,[0,1,0])),br=rotm([.2,1,.1],.6+.16*tt);
  const d=6.2+3.2*(1-ss(0,.5,u))+1.6*ss(.65,1,u),a=.3-.12*u;
  co=add(mul(Ed,-d*Math.cos(a)),add(mul(sd,d*Math.sin(a)),[0,-.7+.3*u,0]));ta=[0,.2,0];fv=3.3;
  close({ty:2,bg:1,pi:2,L,sa:.0085,si:1.4,bo,br,ps:1.2+.03*tt,psh:[.05,.09,.16],mo:[38,6,44]});Q.uAu=.9;
  dust(1500,16,.007,5,0,[.1,.05,.1],[.6,.57,.54],[1.3,.62,.6],br);
  l2='99942 APOPHIS';l3='31 600 km above the Earth: inside the ring of geostationary satellites';
 }else if(bp<84){                 // its orbit, before and after
  P='orr';sh=20;const u=U(82,84);yr=2029.3+.5*u;const h=vis(AP2,yr),h0=vis(AP1,2029.281);
  co=[.5,3.6-.3*u,-1.2];ta=[0,0,-.1];orr(2.5);fi=.3;belt(.4);
  pts.push({n:3000,u:{uMd:{i:1},uOm:{m:om3(AP1)},uP0:[AP1.q,AP1.e,h0.E,TAU],uP1:[1,.25,.15,2],uP2:[.6,0,0,0]}});
  visit(AP2,h,[1,.8,.5],0,TAU,.7);PL4.set([...h.p,.012],36);
  l2='99942 APOPHIS';l3='the Earth’s pull has widened its orbit: 0.92 → 1.10 AU';
 }else{                           // ---- and the years go on, until Halley comes back
  P='orr';sh=21;const u=U(84,92),D=3.5+44*ss(0,.55,u)*(1-.82*ss(.6,1,u)),el=(26+12*u)*D2R,az=1.2+.9*u;yr=2029.9+(HAL.T+HAL.q**1.5/(1-HAL.e)**1.5-2029.9)*u;
  const h=vis(HAL,yr);co=[D*Math.cos(el)*Math.cos(az),D*Math.sin(el),D*Math.cos(el)*Math.sin(az)];ta=lerp([0,-.1*D,0],mul(h.p,.5),ss(.7,1,u));
  orr(D);belt(.8);visit(HAL,h,[.7,.85,1],1,TAU);
  l2=u>.55?'1P/HALLEY':'';l3=u>.55?'due back at perihelion on 28 July 2061':'';if(bp>88.5){big='PERIHELION';sbt='see you in 2061'}
 }
 if(P=='orr'&&run)l1=date(yr);else if(P=='cls')l1=date(yr);
 if(sh!=lsh){if(run&&lsh>=0)flash=1;lsh=sh}
 if(imp!=nimp){if(imp>nimp&&run)flash=.6;nimp=imp}
 if(bl>=0&&BN[bl][2]){const d=BN[bl][2]-mk;if(Math.abs(d)>.002){mk+=d*(1-Math.exp(-dt*9));txtDirty=1}}
 {const n=[big,sbt,l1,l2,l3,bl];if(n.some((v,i)=>v!==txt[i])){txt=n;txtDirty=1}}
 if(txtDirty)drawText();
 flash*=Math.exp(-dt*5);fade=Math.min(1,fade+dt*1.5);
 const xa=run?.92:.8+.2*Math.sin(t*3),fo=run&&dbg<0?Math.min(1,(LEN-mt)/3.5):1;

 // adaptive resolution, by frame pacing: tmin is this display's frame interval (the shortest pair of frames seen); while frames
 // arrive on time, grow a little now and then; as soon as they start arriving late, shrink, and stay below that size for a while.
 ft+=(dt-ft)*.05;tmin=Math.min((dt+pdt)/2,tmin*1.0005);pdt=dt;hold-=dt;
 // And if it is late even when small, on a fast display: settle for every second frame (kf) rather than a blur.
 if(hold<0&&t>2){hold=.5;const lim=t<capT?Math.min(scMax,cap):scMax,tg=tmin*kf;
  if(ft>1.2*tg){if(sc>.5||kf>3&&sc>.3){cap=sc*.94;capT=t+15;sc*=.88;alloc();ft=tg;hold=1}else if(kf<4){kf++;ft=tmin*kf;hold=1}}
  else if(kf>1&&ft<tmin*(kf-.5)){kf--;hold=1}
  else if(ft<1.04*tg&&sc<lim){sc=Math.min(lim,sc*1.06);alloc();hold=1.5}}

 // camera, and where the Sun falls on the screen
 const cm=look(co,ta,up,roll),pr=p=>{const d=sub(p,co),z=dot(d,cm.slice(6));return[dot(d,cm.slice(0,3))*fv/z,dot(d,cm.slice(3,6))*fv/z,z]};
 let s3=[0,0,0];
 if(sun&&fi>0){s3=pr(sun);if(s3[2]>0)fi*=1-ss(1.1,2,Math.max(Math.abs(s3[0])/asp,Math.abs(s3[1])));else fi=0}
 const xs=xw?pr(xo?add(xw,sub(co,xo)):xw):[0,0,0];

 // the picture into the HDR target
 let u=use(PS[P]);
 gl.disable(gl.BLEND);
 gl.bindFramebuffer(gl.FRAMEBUFFER,S.f);gl.viewport(0,0,S.w,S.h);
 su(u,{uR:[S.w,S.h],uT:tm,uRow:(row+.5)/HR,uA:A,uK:K,uS:{i:0},uCo:co,uCm:{m:cm},uFv:fv,uWp:wp,uWl:wl,uXp:xp,uSt:stb,uB0:{i:b0},uB1:{i:b1},uAR:{v4:AR4},uAM:{v4:AM4},uSr:sr,uDm:{v4:DM4},uIm:{v4:IM4}});
 su(u,Q);
 gl.drawArrays(gl.TRIANGLES,0,3);
 // the points on top of it
 if(pts.length){
  u=use(PP);gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE);
  for(const b of pts){
   su(u,{uCm:{m:cm},uCo:pcam||co,uFv:fv,uAsp:asp,uPx:S.h/2,uT:tm,uYr:yr-2000,uN:b.n,uBr:{m:I3},uBe:[0,0,0],uSd:[0,1,0],uBk:0,uGr:Q.uGr,uDm:{v4:DM4},
    uVa:[1,1,1],uVb:[1,1,1],uWp:wp,uR:[S.w,S.h],uSb:{i:0},uOm:{m:I3},uP0:[0,0,0,0],uP1:[0,0,0,0],uP2:[0,0,0,0],uP3:[0,0,0,0]});
   su(u,b.u);if(b.vc)su(u,{uVa:b.vc(b0),uVb:b.vc(b1)});gl.drawArrays(gl.POINTS,0,b.n)}
  gl.disable(gl.BLEND)}
 // how much of the Sun shows
 gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,S.t);
 u=use(PB);gl.bindFramebuffer(gl.FRAMEBUFFER,PR.f);gl.viewport(0,0,1,1);gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);
 su(u,{uC:{i:1},uSs:s3,uR:[S.w,S.h],uRa:Math.max(sa*fv*.75,3/S.h)});gl.drawArrays(gl.TRIANGLES,0,3);gl.disable(gl.BLEND);
 // bloom down
 u=use(PD);gl.uniform1i(u.uC,1);
 let src=S;
 for(let i=0;i<B.length;i++){const d=B[i];gl.bindFramebuffer(gl.FRAMEBUFFER,d.f);gl.viewport(0,0,d.w,d.h);gl.bindTexture(gl.TEXTURE_2D,src.t);
  gl.uniform2f(u.uR,d.w,d.h);gl.uniform2f(u.uI,1/src.w,1/src.h);gl.uniform1f(u.uTh,i?0:1);gl.drawArrays(gl.TRIANGLES,0,3);src=d}
 // bloom up (additive)
 u=use(PU);gl.uniform1i(u.uC,1);gl.enable(gl.BLEND);gl.blendFunc(gl.ONE,gl.ONE);
 for(let i=B.length-1;i>0;i--){const d=B[i-1];src=B[i];gl.bindFramebuffer(gl.FRAMEBUFFER,d.f);gl.viewport(0,0,d.w,d.h);gl.bindTexture(gl.TEXTURE_2D,src.t);
  gl.uniform2f(u.uR,d.w,d.h);gl.uniform2f(u.uI,1/src.w,1/src.h);gl.drawArrays(gl.TRIANGLES,0,3)}
 gl.disable(gl.BLEND);
 // composite
 u=use(PC);gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.viewport(0,0,W,H);
 gl.bindTexture(gl.TEXTURE_2D,S.t);gl.activeTexture(gl.TEXTURE2);gl.bindTexture(gl.TEXTURE_2D,B[0].t);gl.activeTexture(gl.TEXTURE4);gl.bindTexture(gl.TEXTURE_2D,PR.t);
 su(u,{uC:{i:1},uB:{i:2},uX:{i:3},uS:{i:0},uP:{i:4},uR:[W,H],uT:t%100,uF:fade*fo,uXa:xa,uRow:(row+.5)/HR,uFl:flash,
  uFi:fi*(1+.25*K[0]),uFc:fc,uSs:s3,uSn:sn,uGl:gli,uXi:xs[2]>0?xi:0,uXs:[xs[0],xs[1]],uXc:xc});
 gl.drawArrays(gl.TRIANGLES,0,3);
};
requestAnimationFrame(frame);
// if this page was opened by a press (a host's start screen) audio may already be allowed: try now, else wait for a click
start().catch(()=>{});
// inspection hook
window.PERI={SYN,errs,get state(){return{bp:bpNow,sc,ft,tmin,frames,mode,A:[...A],K:[...K],t0,W,H,sw:S.w,ctx:ctx&&ctx.state}},set seek(v){dbg=v}};
})();
</script>
</body>
</html>