{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"ray-traced-glass-cabochon-button-over-a-fashion-print-that-splits-colour-throws-caustics-and-drops-when-pressed","type":"registry:component","title":"Ray-Traced Glass Cabochon Button Over a Fashion Print That Splits Colour, Throws Caustics and Drops When Pressed","description":"Glass button traced in a WebGL shader: a dome over a photo print splits colour at its rim, pools light and drops when pressed. Free React and HTML code.","dependencies":[],"files":[{"path":"components/we-inc/ray-traced-glass-cabochon-button-over-a-fashion-print-that-splits-colour-throws-caustics-and-drops-when-pressed.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\n\n// Everything a visitor is likely to change sits here.\nconst LABEL = \"Open the issue\";\nconst MASTHEAD = \"Chroma\";\nconst FOLIO = [\"Issue 14\", \"The colour issue\"];\nconst CAPTION = \"Solid glass, traced ray by ray. Press it.\";\nconst PLATE = \"Plate 03  /  Glass on colour print\";\nconst HEAD_FROM = 0.44; // the subject starts this far across the photo; left of it the masthead always prints\nconst PHOTO = \"https://images.pexels.com/photos/7515722/pexels-photo-7515722.jpeg?auto=compress&cs=tinysrgb&w=1600\";\nconst PHOTO_ALT = \"Profile of a woman with slicked-back dark hair in a red zip collar against a yellow wall, blue fabric out of focus beside her\";\nconst SPOT = { u: 0.30, v: 0.70 }; // where on the print the glass sits (0 to 1 across, 0 to 1 down)\nconst MAST_SIZE = 274; // masthead size on a print 2048 wide\nconst PRINT_WIDTH = 8.6; // print width in glass-widths (the pill is 1 wide and 3 long)\nconst IOR = 1.52; // how strongly the glass bends light\nconst SPREAD = 0.085; // how far red and violet separate; 0 is colourless glass\nconst HOVER = 0.135; // resting height above the paper\nconst TINT = [0.16, 0.035, 0.07]; // what the glass absorbs per unit of thickness (red, green, blue)\nconst LAMP: [number, number, number] = [-4.5, 7, -3.4]; // where the lamp stands: left, up, back\nconst SERIF = '\"Canela\", \"Tiempos Headline\", \"Didot\", \"Bodoni 72\", \"Playfair Display\", \"Iowan Old Style\", Georgia, serif';\nconst GROTESK = '\"Inter Tight\", \"Inter\", ui-sans-serif, system-ui, -apple-system, \"Helvetica Neue\", Arial, sans-serif';\n\n// Shape of the glass: half length of the spine, half width, height of the dome.\nconst A = 1, R = 0.5, H = 0.4;\n\nconst SHAPE = `\nuniform vec3 uPos; uniform mat3 uRot;\nconst float A=${A.toFixed(2)}, R=${R.toFixed(2)}, H=${H.toFixed(2)}, K=R/H, BIG=1e5;\nvec3 squash(vec3 p){ return vec3(p.x,p.y*K,p.z); }\n// First hit from outside on the dome (a capsule squashed in height), or -1.\nfloat domeNear(vec3 ro, vec3 rd, float r){\n  float a=rd.y*rd.y+rd.z*rd.z+1e-7, b=ro.y*rd.y+ro.z*rd.z, c=ro.y*ro.y+ro.z*ro.z-r*r, h=b*b-a*c;\n  if(h<0.) return -1.;\n  float t=(-b-sqrt(h))/a, x=ro.x+t*rd.x;\n  if(abs(x)<=A) return t;\n  vec3 oc=ro-vec3(sign(x)*A,0.,0.);\n  float a2=dot(rd,rd), b2=dot(oc,rd), c2=dot(oc,oc)-r*r, h2=b2*b2-a2*c2;\n  if(h2<0.) return -1.;\n  return (-b2-sqrt(h2))/a2;\n}\n// Where a ray that is already inside leaves the dome.\nfloat domeFar(vec3 ro, vec3 rd){\n  float a=rd.y*rd.y+rd.z*rd.z+1e-7, b=ro.y*rd.y+ro.z*rd.z, c=ro.y*ro.y+ro.z*ro.z-R*R, h=max(b*b-a*c,0.);\n  float t=(-b+sqrt(h))/a, x=ro.x+t*rd.x;\n  if(abs(x)<=A) return t;\n  vec3 oc=ro-vec3(sign(x)*A,0.,0.);\n  float a2=dot(rd,rd), b2=dot(oc,rd), c2=dot(oc,oc)-R*R, h2=max(b2*b2-a2*c2,0.);\n  return (-b2+sqrt(h2))/a2;\n}\nvec3 domeNormal(vec3 p){\n  vec3 s=squash(p); vec3 n=s-vec3(clamp(s.x,-A,A),0.,0.);\n  return normalize(vec3(n.x,n.y*K,n.z));\n}\n// Carry a ray through the solid: out of the flat base or the dome, bouncing when the angle is too shallow to escape.\n// pass is the share of light that makes it out through the last surface; it falls to nothing as the angle nears that limit.\nbool through(inout vec3 o, inout vec3 d, float ior, out float len, out float pass){\n  len=0.; pass=0.;\n  for(int i=0;i<4;i++){\n    float tb=d.y<-1e-5 ? -o.y/d.y : BIG;\n    float td=domeFar(squash(o),squash(d));\n    vec3 n; float t;\n    if(tb<td){ t=tb; n=vec3(0.,1.,0.); } else { t=td; n=-domeNormal(o+d*td); }\n    o+=d*t; len+=t;\n    vec3 r=refract(d,n,ior);\n    if(dot(r,r)>0.){ pass=1.-(.043+.957*pow(1.-max(-dot(r,n),0.),5.)); d=r; return true; }\n    d=reflect(d,n); o+=n*2e-4;\n  }\n  return false;\n}`;\n\n// Pass one: a sheet of light rays is laid over the dome, pushed through the glass and drawn where it lands. Where the sheet bunches up, the paper gets brighter.\nconst CAUSTIC_VS = `#version 300 es\nprecision highp float;\nlayout(location=0) in vec2 aG;\n${SHAPE}\nuniform vec2 uCausO, uCausS; uniform vec3 uLight; uniform float uIor, uSoak;\nout vec2 vOld; out vec2 vLabel; out float vGain; out float vOk;\nvoid main(){\n  float a=aG.x*2.-1., b=clamp(aG.y*2.-1.,-.9995,.9995);\n  vec3 p=vec3(a*(A+R*sqrt(1.-b*b)),0.,b*R);\n  float q=length(vec2(max(abs(p.x)-A,0.),p.z))/R;\n  p.y=H*sqrt(max(1.-q*q,0.));\n  mat3 rt=transpose(uRot);\n  vec3 rd=rt*(-uLight), n=domeNormal(p);\n  vec3 pw=uRot*p+uPos;\n  vec3 land=pw-uLight*(pw.y/uLight.y);\n  vOld=land.xz; vOk=0.; vGain=0.; vLabel=vec2(p.x/(2.*(A+R))+.5, p.z/(2.*R)+.5);\n  float c=dot(-rd,n);\n  if(c>0.){\n    float f=.043+.957*pow(1.-c,5.);\n    vec3 d=refract(rd,n,1./uIor); vec3 o=p; float len, pass;\n    if(through(o,d,uIor,len,pass)){\n      vec3 wd=uRot*d, wo=uRot*o+uPos;\n      if(wd.y<-.03){ land=wo+wd*(-wo.y/wd.y); vGain=(1.-f)*pass*exp(-uSoak*len); vOk=1.; }\n    }\n  }\n  gl_Position=vec4((land.xz-uCausO)/uCausS*2.-1.,0.,1.);\n}`;\nconst CAUSTIC_FS = `#version 300 es\nprecision highp float;\nin vec2 vOld; in vec2 vLabel; in float vGain; in float vOk;\nuniform sampler2D uLabel; uniform float uCell, uScale; uniform vec3 uHue;\nout vec4 o;\nvoid main(){\n  if(vOk<.999) discard;\n  vec2 dx=dFdx(vOld), dy=dFdy(vOld);\n  float bunch=abs(dx.x*dy.y-dx.y*dy.x)/uCell;\n  float ink=textureLod(uLabel,vLabel,1.5).a;\n  o=vec4(uHue*(min(bunch,9.)*vGain*(1.-.92*ink)*uScale),1.);\n}`;\n\n// The camera's last touches, shared by both ways of finishing a frame: darker corners, a film curve and grain.\nconst FILM = `\nvec3 film(vec3 col, vec2 fc, vec2 res, float time){\n  vec2 v=fc/res-.5;\n  col*=(1.-dot(v,v)*.85)*1.32;\n  col=clamp((col*(2.51*col+.03))/(col*(2.43*col+.59)+.14),0.,1.);\n  col=pow(col,vec3(1./2.2));\n  vec2 g=fract(fc*vec2(.1234,.4562)+fract(time)*7.13); g+=dot(g,g+45.32);\n  return col+(fract(g.x*g.y)-.5)*.024;\n}`;\nconst SCENE_VS = `#version 300 es\nvoid main(){ vec2 p=vec2(gl_VertexID==1?3.:-1., gl_VertexID==2?3.:-1.); gl_Position=vec4(p,0.,1.); }`;\n// Pass two: the picture. One ray per pixel (four on the glass), split into six colours inside the glass.\nconst SCENE_FS = `#version 300 es\nprecision highp float;\n${SHAPE}\nuniform vec2 uRes; uniform float uTime, uTan, uFocus, uAper, uCausScale, uIor, uSpread; uniform int uAA;\nuniform vec3 uCam, uF, uR, uU, uLight, uTint;\nuniform vec4 uPrint; uniform vec2 uCausO, uCausS;\nuniform sampler2D uTex, uCaus, uLabel; uniform bool uDirect;\nout vec4 frag;\n${FILM}\n// Colour of one slice of the spectrum, 0 at red to 1 at violet, scaled so the whole run adds up to white.\nvec3 hue(float t){ return vec3((max(0.,1.-abs(t-.08)/.42)+.35*max(0.,1.-abs(t-1.)/.2))/.317, max(0.,1.-abs(t-.5)/.36)/.36, max(0.,1.-abs(t-.85)/.38)/.31); }\nfloat hash(vec2 p){ p=fract(p*vec2(123.34,456.21)); p+=dot(p,p+45.32); return fract(p.x*p.y); }\nfloat vnoise(vec2 p){ vec2 i=floor(p), f=fract(p); f=f*f*(3.-2.*f); return mix(mix(hash(i),hash(i+vec2(1,0)),f.x),mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),f.x),f.y); }\nfloat card(vec2 p, vec2 c, vec2 h, float s){ vec2 q=abs(p-c)-h; float d=length(max(q,0.))+min(max(q.x,q.y),0.); return 1.-smoothstep(-s,s,d); }\n// The studio: one hard strip lamp high behind the glass (it makes the shadows and the focus line), a long soft card low on the back wall\n// (it makes the highlight along the far shoulder), a warm strip to one side and a dim fill behind the camera. s spreads them for rough surfaces.\nvec3 env(vec3 d, float s, float lamp){\n  vec3 c=mix(vec3(.010,.010,.012),vec3(.035,.037,.045),smoothstep(-.1,.9,d.y));\n  vec3 q=d-uLight; float r=.03+lamp*1.6;\n  c+=vec3(1.,.97,.92)*(1.1/(r*(r+.25)))*smoothstep(r*1.3,r*.5,length(q.yz))*smoothstep(.3+r,.2+r*.5,abs(q.x));\n  if(d.z<-.02){ vec2 p=d.xy*(-10./d.z); c+=vec3(.86,.92,1.)*5.*card(p,vec2(-1.,3.6),vec2(6.5,1.9),.7+s*12.); }\n  if(d.x>.02){ vec2 p=d.zy*(9./d.x); c+=vec3(1.,.70,.42)*4.*card(p,vec2(-1.5,3.6),vec2(.65,2.8),.2+s*9.); }\n  if(d.z>.02){ vec2 p=d.xy*(10./d.z); c+=vec3(1.,.96,.9)*.6*card(p,vec2(-1.,5.),vec2(6.,3.),1.5+s*10.); }\n  return c;\n}\n// How much of the lamp a point on the paper can see past the glass: 0 behind it, 1 clear of it.\nfloat clearOf(vec3 P){\n  mat3 rt=transpose(uRot);\n  vec3 ro=squash(rt*(P-uPos)), rd=squash(rt*uLight); rd=normalize(rd);\n  float b=rd.x, dd=dot(rd,ro), t=(ro.x*b-dd)/max(1.-b*b,1e-4), sx=clamp(ro.x+t*b,-A,A);\n  t=sx*b-dd;\n  float m=length(ro+rd*t-vec3(sx,0.,0.))-R;\n  float out_=domeFar(ro,rd);\n  float up=smoothstep(-.03,.05,(ro.y+rd.y*out_)/K);\n  return 1.-smoothstep(.035,-.035,m)*(m<0. ? up : 1.);\n}\nvec3 poolOfLight(vec2 xz, float lod){\n  vec2 uv=(xz-uCausO)/uCausS;\n  vec2 e=smoothstep(vec2(0.),vec2(.05),uv)*smoothstep(vec2(0.),vec2(.05),1.-uv);\n  float k=e.x*e.y; if(k<=0.) return vec3(1.);\n  vec2 px=exp2(lod)/vec2(textureSize(uCaus,0));\n  vec3 c=textureLod(uCaus,uv,lod).rgb*.4+(textureLod(uCaus,uv+px*vec2(.7,.3),lod).rgb+textureLod(uCaus,uv+px*vec2(-.3,.7),lod).rgb+textureLod(uCaus,uv+px*vec2(-.7,-.3),lod).rgb+textureLod(uCaus,uv+px*vec2(.3,-.7),lod).rgb)*.15;\n  c*=uCausScale*k;\n  return vec3(clearOf(vec3(xz.x,0.,xz.y)))+1.6*(1.-exp(-c/1.6));\n}\n// Paper print on a dark stone table. gx and gy say how much ground one pixel covers, which is also how the lens blur gets in.\nvec3 ground(vec3 P, vec3 V, vec2 gx, vec2 gy, float blur){\n  vec2 q=P.xz-uPrint.xy, hs=uPrint.zw;\n  float fw=.5*(length(gx)+length(gy))+blur;\n  vec2 dd=abs(q)-hs; float d=length(max(dd,0.))+min(max(dd.x,dd.y),0.);\n  float inP=1.-smoothstep(-fw,fw,d);\n  vec2 uv=q/(2.*hs)+.5;\n  vec2 ux=gx/(2.*hs), uy=gy/(2.*hs);\n  vec3 alb;\n  if(blur>0.){\n    // Out-of-focus paper: four spread taps, each already softened, so the blur stays smooth instead of blocky.\n    vec2 o=vec2(blur)/(2.*hs); ux+=vec2(o.x*.7,0.); uy+=vec2(0.,o.y*.7);\n    alb=(textureGrad(uTex,uv+o*vec2(.62,.25),ux,uy).rgb+textureGrad(uTex,uv+o*vec2(-.25,.62),ux,uy).rgb+textureGrad(uTex,uv+o*vec2(-.62,-.25),ux,uy).rgb+textureGrad(uTex,uv+o*vec2(.25,-.62),ux,uy).rgb)*.25;\n  } else alb=textureGrad(uTex,uv,ux,uy).rgb;\n  alb=pow(alb,vec3(2.2));\n  float soft=clamp(1.-fw*30.,0.,1.);\n  alb*=1.+soft*.035*(vnoise(P.xz*190.)-.5);\n  float sp=vnoise(P.xz*2.3)*.25+vnoise(P.xz*23.)*.3+vnoise(P.xz*140.)*.45*soft;\n  vec3 slab=vec3(.036,.034,.034)*(.72+.56*sp);\n  // The print is mounted on board: its near edge shows, and it throws a thin shadow on the stone.\n  float side=(1.-smoothstep(-fw,fw,abs(q.x)-hs.x))*smoothstep(-fw,fw,q.y-hs.y)*(1.-smoothstep(-fw,fw,q.y-hs.y-.036));\n  vec2 sq=abs(q-uLight.xz/uLight.y*.045)-hs;\n  float thrown=1.-(1.-inP)*(1.-side)*.8*(1.-smoothstep(-.012,.02+fw,length(max(sq,0.))+min(max(sq.x,sq.y),0.)));\n  vec3 base=mix(mix(slab,vec3(.5,.49,.46),side),alb,inP);\n  vec3 pool=poolOfLight(P.xz,1.+log2(1.+fw*60.));\n  vec2 k=P.xz-vec2(.5,-.4);\n  float fall=.22+.78*exp(-dot(k,k)*.028);\n  // Where the glass comes down on the paper the gap closes and goes dark.\n  vec3 po=transpose(uRot)*(P-uPos);\n  float foot=length(vec2(max(abs(po.x)-A,0.),po.z))-R;\n  float gap=max(-po.y,0.);\n  float occ=1.-.5*exp(-gap*22.)*smoothstep(.06,-.03,abs(foot)-.02)-.22*exp(-gap*9.)*smoothstep(.1,-.3,foot);\n  vec3 col=base*(vec3(.23,.24,.26)+vec3(1.46,1.4,1.32)*pool*fall*uLight.y)*occ;\n  vec3 r=reflect(V,vec3(0.,1.,0.));\n  float fr=.04+.96*pow(1.-max(-V.y,0.),5.);\n  float rough=mix(.05,.16,inP);\n  col+=env(r,rough,rough)*fr*mix(.5,.16,inP)*min(pool.g+.25,1.)*occ;\n  col*=mix(.6+.4*smoothstep(-.01,.14+fw,d),1.,max(inP,side))*thrown;\n  return col;\n}\nvec3 glass(vec3 p, vec3 od, vec3 rd, float t, float jit){\n  vec3 n=domeNormal(p), nw=uRot*n;\n  float c=max(dot(-od,n),0.), F=.043+.957*pow(1.-c,5.);\n  vec3 rw=reflect(rd,nw);\n  vec3 refl;\n  if(rw.y>0.) refl=env(rw,.012,0.);\n  else { vec3 wp=uRot*p+uPos; float tt=-wp.y/rw.y; refl=ground(wp+rw*tt,rw,vec2(.12,0.),vec2(0.,.12),0.); }\n  float e=.006+t*.0009;\n  vec3 tr=vec3(0.);\n  for(int i=0;i<6;i++){\n    float w=(float(i)+jit)/6., ior=uIor+uSpread*(w-.5);\n    vec3 d=refract(od,n,1./ior), o=p; float len, pass; vec3 col=vec3(.01);\n    if(through(o,d,ior,len,pass)){\n      vec3 wd=uRot*d, wo=uRot*o+uPos;\n      if(wd.y<-1e-3){ float tt=-wo.y/wd.y; col=ground(wo+wd*tt,wd,vec2(e,0.),vec2(0.,e),0.); } else col=env(wd,.03,.03);\n      col*=exp(-uTint*len)*pass;\n    }\n    tr+=col*hue(w)/6.;\n  }\n  // White lettering fired onto the top of the glass, and a ground band where the dome meets its base.\n  vec2 luv=vec2(p.x/(2.*(A+R))+.5, p.z/(2.*R)+.5);\n  float ink=textureLod(uLabel,luv,max(0.,log2(t*uTan*2./uRes.y*340.))).a;\n  float lit=max(dot(nw,uLight),0.);\n  tr=mix(tr,vec3(.93,.93,.91)*(.30+1.25*lit),ink*.94);\n  float band=smoothstep(.034,.012,p.y);\n  tr=mix(tr,tr*.55+vec3(.55,.58,.57)*(.18+.9*lit),band*.7);\n  return tr*(1.-F)+refl*F;\n}\nvec3 ray(vec2 fc){ vec2 s=(fc*2.-uRes)/uRes.y; return normalize(uF+uR*s.x*uTan+uU*s.y*uTan); }\nvec3 shade(vec2 fc, float jit){\n  vec3 rd=ray(fc);\n  float tg=-uCam.y/rd.y;\n  mat3 rt=transpose(uRot);\n  vec3 oo=rt*(uCam-uPos), od=rt*rd;\n  float t=domeNear(squash(oo),squash(od),R);\n  if(t>0.&&t<tg){ vec3 p=oo+od*t; if(p.y>0.) return glass(p,od,rd,t,jit); }\n  vec3 P=uCam+rd*tg;\n  vec3 rx=ray(fc+vec2(1.,0.)), ry=ray(fc+vec2(0.,1.));\n  vec2 gx=(uCam+rx*(-uCam.y/rx.y)).xz-P.xz, gy=(uCam+ry*(-uCam.y/ry.y)).xz-P.xz;\n  float b=uAper*abs(tg-uFocus)/uFocus;\n  return ground(P,rd,gx,gy,b);\n}\nconst vec2 JIT[4]=vec2[4](vec2(.125,.375),vec2(-.375,.125),vec2(.375,-.125),vec2(-.125,-.375));\nvoid main(){\n  vec3 rd=ray(gl_FragCoord.xy);\n  mat3 rt=transpose(uRot);\n  float near=domeNear(squash(rt*(uCam-uPos)),squash(rt*rd),R+.03);\n  int n=near>0. ? uAA : 1;\n  vec3 col=vec3(0.);\n  // Each sample starts its six colours at a different point in the spectrum, so sharp edges fan out smoothly instead of in six steps.\n  float dith=fract(52.9829189*fract(dot(gl_FragCoord.xy,vec2(.06711056,.00583715))));\n  for(int s=0;s<4;s++){ if(s>=n) break; col+=shade(gl_FragCoord.xy+(n>1?JIT[s]:vec2(0.)),fract(dith+float(s)*.25+.125)); }\n  col/=float(n);\n  // With a float buffer the frame is kept unfinished and its too-bright part is noted, so the lens glow can be added before the film curve.\n  if(uDirect) frag=vec4(film(col,gl_FragCoord.xy,uRes,uTime),1.);\n  else { col=min(col,vec3(30.)); frag=vec4(col,max(dot(col,vec3(.3,.55,.15))-1.5,0.)); }\n}`;\n\n// Pass three: lens glow. Smaller copies of the frame spread whatever was brighter than white into a soft halo.\nconst LENS_FS = `#version 300 es\nprecision highp float;\nuniform sampler2D uScene; uniform vec2 uRes; uniform float uTime;\nout vec4 frag;\n${FILM}\nvec3 halo(vec2 uv, float lod){\n  vec2 px=exp2(lod)/uRes*.75; vec4 c=vec4(0.);\n  c+=textureLod(uScene,uv+px*vec2(1.,.4),lod); c+=textureLod(uScene,uv+px*vec2(-.4,1.),lod);\n  c+=textureLod(uScene,uv+px*vec2(-1.,-.4),lod); c+=textureLod(uScene,uv+px*vec2(.4,-1.),lod);\n  c*=.25;\n  return c.rgb*c.a/(dot(c.rgb,vec3(.3,.55,.15))+.02);\n}\nvoid main(){\n  vec2 uv=gl_FragCoord.xy/uRes;\n  vec3 col=textureLod(uScene,uv,0.).rgb;\n  float k=log2(uRes.y/700.);\n  col+=halo(uv,1.5+k)*.22+halo(uv,3.+k)*.2+halo(uv,4.5+k)*.16;\n  frag=vec4(film(col,gl_FragCoord.xy,uRes,uTime),1.);\n}`;\n\ntype V3 = [number, number, number];\nconst sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];\nconst dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\nconst cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\nconst unit = (a: V3): V3 => { const l = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };\n\nexport default function RayTracedGlassCabochonButton() {\n  const root = useRef<HTMLDivElement>(null);\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const photo = useRef<HTMLImageElement>(null);\n  const button = useRef<HTMLButtonElement>(null);\n  const [live, setLive] = useState(false);\n  const [count, setCount] = useState(0);\n\n  useEffect(() => {\n    const el = root.current, cv = canvas.current, img = photo.current, btn = button.current;\n    if (!el || !cv || !img || !btn) return;\n    const gl = cv.getContext(\"webgl2\", { antialias: false, alpha: false, powerPreference: \"high-performance\" });\n    if (!gl) return;\n    const reduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n\n    const compile = (type: number, src: string) => { const s = gl.createShader(type)!; gl.shaderSource(s, src); gl.compileShader(s); return s; };\n    const link = (vs: string, fs: string) => {\n      const p = gl.createProgram()!;\n      gl.attachShader(p, compile(gl.VERTEX_SHADER, vs)); gl.attachShader(p, compile(gl.FRAGMENT_SHADER, fs)); gl.linkProgram(p);\n      if (!gl.getProgramParameter(p, gl.LINK_STATUS)) return null;\n      const at = new Map<string, WebGLUniformLocation | null>();\n      return { p, u: (n: string) => { if (!at.has(n)) at.set(n, gl.getUniformLocation(p, n)); return at.get(n)!; } };\n    };\n    const caus = link(CAUSTIC_VS, CAUSTIC_FS), scene = link(SCENE_VS, SCENE_FS), lens = link(SCENE_VS, LENS_FS);\n    if (!caus || !scene || !lens) return;\n\n    // The print: the photograph with a white margin and its type, painted once to a canvas and used as the paper's surface.\n    const TW = 2048, TH = 1366;\n    const sheet = document.createElement(\"canvas\"); sheet.width = TW; sheet.height = TH;\n    const paintPrint = (withPhoto: boolean) => {\n      const x = sheet.getContext(\"2d\")! as CanvasRenderingContext2D & { letterSpacing: string };\n      const m = 72, w = TW - m * 2, h = TH - m * 2;\n      x.globalAlpha = 1; x.fillStyle = \"#f3f0e8\"; x.fillRect(0, 0, TW, TH);\n      const g = x.createLinearGradient(m, 0, TW - m, 0);\n      g.addColorStop(0, \"#1c6fb4\"); g.addColorStop(0.3, \"#1c6fb4\"); g.addColorStop(0.36, \"#e9b616\"); g.addColorStop(1, \"#e2a80f\");\n      x.fillStyle = g; x.fillRect(m, m, w, h);\n      const word = document.createElement(\"canvas\"); word.width = TW; word.height = TH;\n      const wx = word.getContext(\"2d\")! as CanvasRenderingContext2D & { letterSpacing: string };\n      wx.fillStyle = \"#fbf8f1\"; wx.textBaseline = \"alphabetic\"; wx.letterSpacing = \"-9px\"; wx.font = `400 ${MAST_SIZE}px ${SERIF}`;\n      wx.fillText(MASTHEAD, m + 44, m + MAST_SIZE * 0.98);\n      if (withPhoto) {\n        const sc = Math.max(w / img.naturalWidth, h / img.naturalHeight), dw = img.naturalWidth * sc, dh = img.naturalHeight * sc;\n        x.save(); x.beginPath(); x.rect(m, m, w, h); x.clip();\n        x.drawImage(img, m + (w - dw) / 2, m + (h - dh) / 2, dw, dh);\n        x.restore();\n        // A quarter-size copy is keyed on the yellow wall and blue cloth, so the masthead prints on the backdrop and passes behind the head.\n        const kw = Math.round(w / 4), kh = Math.round(h / 4);\n        const key = document.createElement(\"canvas\"); key.width = kw; key.height = kh;\n        const kx = key.getContext(\"2d\", { willReadFrequently: true })!;\n        kx.drawImage(sheet, m, m, w, h, 0, 0, kw, kh);\n        const px = kx.getImageData(0, 0, kw, kh), d = px.data;\n        const sm = (a: number, b: number, v: number) => { const t = Math.min(1, Math.max(0, (v - a) / (b - a))); return t * t * (3 - 2 * t); };\n        for (let i = 0; i < d.length; i += 4) {\n          const r = d[i] + 1, gg = d[i + 1], b = d[i + 2], mx = Math.max(r, gg, b), sat = (mx - Math.min(r, gg, b)) / mx;\n          const wall = sm(0.42, 0.28, b / r) * sm(0.56, 0.66, gg / r), cloth = sm(1.15, 1.5, b / r) * sm(0.35, 0.55, sat);\n          d[i + 3] = 255 * Math.max(sm(HEAD_FROM + 0.02, HEAD_FROM - 0.02, ((i >> 2) % kw) / kw), sm(0.4, 0.8, Math.min(1, wall + cloth)));\n        }\n        kx.putImageData(px, 0, 0);\n        wx.globalCompositeOperation = \"destination-in\"; wx.imageSmoothingQuality = \"high\";\n        wx.drawImage(key, m, m, w, h);\n      }\n      x.drawImage(word, 0, 0);\n      x.fillStyle = \"#fbf8f1\"; x.textBaseline = \"alphabetic\"; x.letterSpacing = \"6px\"; x.font = `600 25px ${GROTESK}`;\n      x.fillText(FOLIO[0].toUpperCase(), m + 62, m + MAST_SIZE * 0.98 + 78);\n      x.globalAlpha = 0.8; x.fillText(FOLIO[1].toUpperCase(), m + 62, m + MAST_SIZE * 0.98 + 116); x.globalAlpha = 1;\n      // Plate marks in the white margin, the way a lab labels a print.\n      x.fillStyle = \"#2a2926\"; x.letterSpacing = \"5px\"; x.font = `600 23px ${GROTESK}`; x.textBaseline = \"middle\";\n      x.textAlign = \"center\"; x.fillText(CAPTION.toUpperCase(), m + w * SPOT.u, TH - m / 2 + 1);\n      x.textAlign = \"right\"; x.fillText(`${MASTHEAD} ${FOLIO[0]}`.toUpperCase(), TW - m, TH - m / 2 + 1); x.textAlign = \"left\";\n      x.save(); x.translate(m / 2, TH - m - 40); x.rotate(-Math.PI / 2); x.fillText(PLATE.toUpperCase(), 0, 1); x.restore();\n    };\n    // The lettering on the glass, as a mask.\n    const LW = 1200, LH = 400;\n    const paintLabel = () => {\n      const c = document.createElement(\"canvas\"); c.width = LW; c.height = LH;\n      const x = c.getContext(\"2d\")! as CanvasRenderingContext2D & { letterSpacing: string };\n      x.letterSpacing = \"-2.5px\"; x.font = `600 104px ${GROTESK}`; x.textBaseline = \"middle\"; x.fillStyle = \"#fff\";\n      const w = x.measureText(LABEL).width, gap = 34, arrow = 74, x0 = (LW - (w + gap + arrow)) / 2;\n      x.fillText(LABEL, x0, LH / 2 + 5);\n      const ax = x0 + w + gap, ay = LH / 2 + 3;\n      x.lineWidth = 11; x.lineCap = \"round\"; x.lineJoin = \"round\"; x.strokeStyle = \"#fff\";\n      x.beginPath(); x.moveTo(ax, ay); x.lineTo(ax + arrow, ay); x.moveTo(ax + arrow - 28, ay - 28); x.lineTo(ax + arrow, ay); x.lineTo(ax + arrow - 28, ay + 28); x.stroke();\n      return c;\n    };\n\n    const tex = (unit_: number, src: TexImageSource) => {\n      const t = gl.createTexture();\n      gl.activeTexture(gl.TEXTURE0 + unit_); gl.bindTexture(gl.TEXTURE_2D, t);\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, src);\n      gl.generateMipmap(gl.TEXTURE_2D);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);\n      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);\n      const an = gl.getExtension(\"EXT_texture_filter_anisotropic\");\n      if (an) gl.texParameterf(gl.TEXTURE_2D, an.TEXTURE_MAX_ANISOTROPY_EXT, 8);\n      return t;\n    };\n    let printTex: WebGLTexture | null = null;\n    const loadPrint = () => {\n      if (printTex) gl.deleteTexture(printTex);\n      // A photo host that forbids pixel reads throws here; the print then keeps its two flat colour fields.\n      try { paintPrint(img.complete && img.naturalWidth > 0); printTex = tex(0, sheet); }\n      catch { paintPrint(false); printTex = tex(0, sheet); }\n    };\n    loadPrint();\n    tex(1, paintLabel());\n\n    // The light map the first pass draws into. Half-float where the browser allows it, so bright focus lines keep their headroom.\n    const MW = 768, MH = 512;\n    const float = !!gl.getExtension(\"EXT_color_buffer_float\") || !!gl.getExtension(\"EXT_color_buffer_half_float\");\n    const mapScale = float ? 1 : 0.16;\n    const map = gl.createTexture();\n    gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, map);\n    if (float) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, MW, MH, 0, gl.RGBA, gl.HALF_FLOAT, null);\n    else gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, MW, MH, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);\n    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);\n    const fbo = gl.createFramebuffer();\n    gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, map, 0);\n    if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); return; }\n    gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n    // The unfinished frame, kept in a float buffer for the lens glow. Without float buffers the scene pass finishes the picture itself.\n    const shot = float ? gl.createTexture() : null, shotFbo = float ? gl.createFramebuffer() : null;\n    let shotW = 0, shotH = 0;\n    const fitShot = () => {\n      if (!shot || (shotW === W && shotH === Hh)) return;\n      shotW = W; shotH = Hh;\n      gl.activeTexture(gl.TEXTURE3); gl.bindTexture(gl.TEXTURE_2D, shot);\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, W, Hh, 0, gl.RGBA, gl.HALF_FLOAT, null);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);\n      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);\n      gl.bindFramebuffer(gl.FRAMEBUFFER, shotFbo);\n      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, shot, 0);\n    };\n\n    const GX = 320, GY = 128;\n    const pts = new Float32Array((GX + 1) * (GY + 1) * 2), idx = new Uint32Array(GX * GY * 6);\n    for (let j = 0, k = 0; j <= GY; j++) for (let i = 0; i <= GX; i++) { pts[k++] = i / GX; pts[k++] = j / GY; }\n    for (let j = 0, k = 0; j < GY; j++) for (let i = 0; i < GX; i++) { const a = j * (GX + 1) + i, b = a + GX + 1; idx[k++] = a; idx[k++] = a + 1; idx[k++] = b; idx[k++] = a + 1; idx[k++] = b + 1; idx[k++] = b; }\n    const vao = gl.createVertexArray(); gl.bindVertexArray(vao);\n    gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, pts, gl.STATIC_DRAW);\n    gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.STATIC_DRAW);\n    const plain = gl.createVertexArray();\n\n    // The same spectrum the scene shader uses, cut into six slices that add up to white.\n    const tri = (t: number, c: number, w: number) => Math.max(0, 1 - Math.abs(t - c) / w);\n    const BANDS = Array.from({ length: 6 }, (_, i) => { const t = (i + 0.5) / 6; return [t, [(tri(t, 0.08, 0.42) + 0.35 * tri(t, 1, 0.2)) / 0.317 / 6, tri(t, 0.5, 0.36) / 0.36 / 6, tri(t, 0.85, 0.38) / 0.31 / 6]] as [number, number[]]; });\n    const LIGHT = unit(LAMP);\n    const printD = PRINT_WIDTH * TH / TW;\n    const print = [PRINT_WIDTH * (0.5 - SPOT.u), printD * (0.5 - SPOT.v), PRINT_WIDTH / 2, printD / 2];\n    const TAN = Math.tan((13.5 * Math.PI) / 180);\n\n    // y is height above the paper; tilt and lean are the two ways it can rock, yaw is the twist it picks up when it lands off-centre.\n    const s = { y: HOVER, vy: 0, tilt: 0, vt: 0, lean: 0, vl: 0, yaw: 0, vw: 0, held: false, tx: 0, tz: 0, px: 0, pz: 0, cx: 0, cz: 0 };\n    let W = 0, Hh = 0, quality = 1, aa = 4, raf = 0, last = 0, start = 0, seen = true, touched = -1e9, nextDemo = 3300, demoUp = 0, slow = 0;\n\n    const size = () => {\n      const b = el.getBoundingClientRect();\n      const k = Math.min(Math.max(window.devicePixelRatio || 1, 0.5), 1.5) * quality;\n      W = Math.max(2, Math.round(b.width * k)); Hh = Math.max(2, Math.round(b.height * k));\n      if (cv.width !== W || cv.height !== Hh) { cv.width = W; cv.height = Hh; }\n    };\n\n    const draw = (time: number) => {\n      const asp = W / Hh;\n      // Longer lens and a further camera on tall screens, so the glass keeps its share of the frame.\n      const frac = Math.min(0.8, Math.max(0.4, 0.97 - 0.3 * asp));\n      const dist = (2 * (A + R)) / (2 * TAN * asp * frac);\n      // Tall screens look down more steeply, so the print fills the height instead of leaving bare table.\n      const el0 = ((asp > 1.2 ? 50 : 54) * Math.PI) / 180 - s.cz * 0.035, az = s.cx * 0.05;\n      const target: V3 = [asp > 1.2 ? 0.6 : 0.1, 0.1, asp > 1.2 ? -0.72 : -0.55];\n      const cam: V3 = [target[0] + dist * Math.cos(el0) * Math.sin(az), target[1] + dist * Math.sin(el0), target[2] + dist * Math.cos(el0) * Math.cos(az)];\n      const F = unit(sub(target, cam)), Rv = unit(cross(F, [0, 1, 0])), U = cross(Rv, F);\n\n      // Rocking lifts the middle, because a flat base can only pivot on its own edge.\n      const lift = Math.max(0, s.y) + Math.abs(Math.sin(s.tilt)) * (A + R) + Math.abs(Math.sin(s.lean)) * R;\n      const pos: V3 = [0, lift, 0];\n      const cy = Math.cos(s.yaw), sy = Math.sin(s.yaw), ct = Math.cos(s.tilt), st = Math.sin(s.tilt), cl = Math.cos(s.lean), sl = Math.sin(s.lean);\n      // Column-major: turn about the vertical, then tilt end to end, then lean side to side.\n      const rz = [ct, st, 0, -st, ct, 0, 0, 0, 1], rx = [1, 0, 0, 0, cl, sl, 0, -sl, cl], ry = [cy, 0, -sy, 0, 1, 0, sy, 0, cy];\n      const mul = (a: number[], b: number[]) => { const o = new Array(9).fill(0); for (let c = 0; c < 3; c++) for (let r = 0; r < 3; r++) for (let k = 0; k < 3; k++) o[c * 3 + r] += a[k * 3 + r] * b[c * 3 + k]; return o; };\n      const rot = mul(ry, mul(rz, rx));\n\n      const off = (lift + H * 0.4) / LIGHT[1];\n      const cs = [5.1, 3.4], co = [-LIGHT[0] * off - cs[0] / 2, -LIGHT[2] * off - cs[1] / 2];\n\n      // Light map: six slices of the spectrum, each bent a little differently and added together.\n      gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); gl.viewport(0, 0, MW, MH);\n      gl.clearColor(0, 0, 0, 1); gl.colorMask(true, true, true, true); gl.clear(gl.COLOR_BUFFER_BIT);\n      gl.useProgram(caus.p); gl.bindVertexArray(vao);\n      gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE);\n      gl.uniform3fv(caus.u(\"uPos\"), pos); gl.uniformMatrix3fv(caus.u(\"uRot\"), false, rot);\n      gl.uniform2fv(caus.u(\"uCausO\"), co); gl.uniform2fv(caus.u(\"uCausS\"), cs); gl.uniform3fv(caus.u(\"uLight\"), LIGHT);\n      gl.uniform1f(caus.u(\"uCell\"), (cs[0] / MW) * (cs[1] / MH)); gl.uniform1f(caus.u(\"uScale\"), mapScale); gl.uniform1i(caus.u(\"uLabel\"), 1);\n      for (const [w, hue] of BANDS) {\n        gl.uniform1f(caus.u(\"uIor\"), IOR + SPREAD * (w - 0.5)); gl.uniform3fv(caus.u(\"uHue\"), hue);\n        gl.uniform1f(caus.u(\"uSoak\"), (TINT[0] * hue[0] + TINT[1] * hue[1] + TINT[2] * hue[2]) / (hue[0] + hue[1] + hue[2]));\n        gl.drawElements(gl.TRIANGLES, idx.length, gl.UNSIGNED_INT, 0);\n      }\n      gl.disable(gl.BLEND);\n      gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, map); gl.generateMipmap(gl.TEXTURE_2D);\n\n      fitShot();\n      gl.bindFramebuffer(gl.FRAMEBUFFER, shotFbo); gl.viewport(0, 0, W, Hh);\n      gl.useProgram(scene.p); gl.bindVertexArray(plain); gl.uniform1i(scene.u(\"uDirect\"), shot ? 0 : 1);\n      gl.uniform2f(scene.u(\"uRes\"), W, Hh); gl.uniform1f(scene.u(\"uTime\"), time); gl.uniform1f(scene.u(\"uTan\"), TAN);\n      gl.uniform1f(scene.u(\"uFocus\"), dist); gl.uniform1f(scene.u(\"uAper\"), 0.1); gl.uniform1f(scene.u(\"uCausScale\"), 1 / mapScale);\n      gl.uniform1f(scene.u(\"uIor\"), IOR); gl.uniform1f(scene.u(\"uSpread\"), SPREAD); gl.uniform1i(scene.u(\"uAA\"), aa);\n      gl.uniform3fv(scene.u(\"uCam\"), cam); gl.uniform3fv(scene.u(\"uF\"), F); gl.uniform3fv(scene.u(\"uR\"), Rv); gl.uniform3fv(scene.u(\"uU\"), U);\n      gl.uniform3fv(scene.u(\"uLight\"), LIGHT); gl.uniform3fv(scene.u(\"uTint\"), TINT);\n      gl.uniform3fv(scene.u(\"uPos\"), pos); gl.uniformMatrix3fv(scene.u(\"uRot\"), false, rot);\n      gl.uniform4fv(scene.u(\"uPrint\"), print); gl.uniform2fv(scene.u(\"uCausO\"), co); gl.uniform2fv(scene.u(\"uCausS\"), cs);\n      gl.uniform1i(scene.u(\"uTex\"), 0); gl.uniform1i(scene.u(\"uLabel\"), 1); gl.uniform1i(scene.u(\"uCaus\"), 2);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n      if (shot) {\n        gl.activeTexture(gl.TEXTURE3); gl.bindTexture(gl.TEXTURE_2D, shot); gl.generateMipmap(gl.TEXTURE_2D);\n        gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n        gl.useProgram(lens.p); gl.uniform1i(lens.u(\"uScene\"), 3); gl.uniform2f(lens.u(\"uRes\"), W, Hh); gl.uniform1f(lens.u(\"uTime\"), time);\n        gl.drawArrays(gl.TRIANGLES, 0, 3);\n      }\n\n      // Keep the real button exactly over the glass, so focus, taps and screen readers land on it.\n      const b = el.getBoundingClientRect();\n      let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;\n      for (const [px, pz] of [[-(A + R), 0], [A + R, 0], [0, -R], [0, R], [-A, -R], [A, -R], [-A, R], [A, R]]) {\n        const v = sub([px, lift + H * 0.5, pz], cam), z = dot(v, F);\n        const sx = (dot(v, Rv) / (z * TAN * asp) + 1) * 0.5 * b.width, sy2 = (1 - dot(v, U) / (z * TAN)) * 0.5 * b.height;\n        x0 = Math.min(x0, sx); x1 = Math.max(x1, sx); y0 = Math.min(y0, sy2); y1 = Math.max(y1, sy2);\n      }\n      btn.style.left = `${x0.toFixed(1)}px`; btn.style.top = `${(y0 - 6).toFixed(1)}px`; btn.style.width = `${(x1 - x0).toFixed(1)}px`; btn.style.height = `${(y1 - y0 + 12).toFixed(1)}px`;\n    };\n\n    const step = (dt: number, t: number) => {\n      if (s.held) s.vy -= 40 * dt; // a finger: one steady push, so it gathers speed all the way down\n      else { const goal = HOVER + (reduce ? 0 : 0.018 * Math.sin(t / 1400)); s.vy += (140 * (goal - s.y) - 8.2 * s.vy) * dt; } // let go: it floats back up and overshoots once\n      s.y += s.vy * dt;\n      if (s.y < 0) {\n        // It lands on the paper: most of the speed is lost and the rest goes into rocking on its edges.\n        const hit = -s.vy; s.y = 0; s.vy = hit > 0.9 ? hit * 0.2 : 0;\n        if (hit > 0.9) { s.vt += (s.px >= 0 ? 1 : -1) * (0.3 + 0.5 * Math.abs(s.px)) * hit * 0.55; s.vl += (s.pz >= 0 ? 1 : -1) * (0.3 + 0.5 * Math.abs(s.pz)) * hit * 0.5; s.vw += s.px * hit * 0.1; }\n      }\n      const idle = t - touched > 2600 && !reduce;\n      const down = s.y < 0.012;\n      const tt = down ? 0 : s.tx + (idle ? 0.022 * Math.sin(t / 2300) : 0);\n      const tl = down ? 0 : s.tz + (idle ? 0.045 * Math.sin(t / 3100 + 1) : 0);\n      // On the paper it rattles quickly and dies out; in the air it sways slowly.\n      const k = down ? 360 : 120, c = down ? 5 : 7;\n      s.vt += (k * (tt - s.tilt) - c * s.vt) * dt; s.tilt += s.vt * dt;\n      s.vl += (k * 1.5 * (tl - s.lean) - c * 1.2 * s.vl) * dt; s.lean += s.vl * dt;\n      s.vw += (70 * ((reduce ? 0 : 0.035 * Math.sin(t / 4700)) - s.yaw) - 6 * s.vw) * dt; s.yaw += s.vw * dt;\n      const ease = Math.min(1, dt * 3);\n      s.cx += ((idle ? 0.5 * Math.sin(t / 5200) : s.tx * 14) - s.cx) * ease; s.cz += ((idle ? 0.4 * Math.sin(t / 6100) : s.tz * 9) - s.cz) * ease;\n    };\n\n    const frame = (now: number) => {\n      raf = 0;\n      if (!start) { start = now; last = now; }\n      const raw = now - last, dt = Math.min(0.032, raw / 1000); last = now;\n      const t = now - start;\n      if (t - touched > 2600) {\n        if (t > nextDemo && !s.held) { s.held = true; s.px = 0.5; s.pz = 0.4; demoUp = t + 300; nextDemo = t + 5200; }\n        if (demoUp && t > demoUp) { demoUp = 0; s.held = false; s.vt -= 0.25; s.vl -= 0.3; }\n      }\n      // Four small steps keep the landing and the rattle stable at low frame rates.\n      for (let i = 0; i < 4; i++) step(dt / 4, t);\n      size(); draw(t / 1000);\n      // If frames run long, first drop the extra samples on the glass, then the resolution.\n      if (t > 1500) { slow = raw > 24 ? slow + 1 : Math.max(0, slow - 0.25); if (slow > 24) { slow = 0; if (aa > 2) aa = 2; else if (quality > 0.6) quality *= 0.85; else aa = 1; } }\n      if (seen && !document.hidden) raf = requestAnimationFrame(frame);\n    };\n    const still = () => { size(); draw(0); };\n    const wake = () => { if (reduce) { still(); return; } if (!raf) { last = performance.now(); raf = requestAnimationFrame(frame); } };\n\n    still(); setLive(true); wake();\n    const onPhoto = () => { loadPrint(); if (reduce) still(); };\n    if (!(img.complete && img.naturalWidth > 0)) img.addEventListener(\"load\", onPhoto);\n\n    const mark = () => { touched = start ? performance.now() - start : 0; demoUp = 0; };\n    const onMove = (e: PointerEvent) => {\n      const b = btn.getBoundingClientRect(), r = el.getBoundingClientRect();\n      const dx = (e.clientX - (b.left + b.width / 2)) / r.width, dz = (e.clientY - (b.top + b.height / 2)) / r.height;\n      s.tx = Math.max(-0.045, Math.min(0.045, -dx * 0.1)); s.tz = Math.max(-0.11, Math.min(0.11, dz * 0.28));\n      mark(); if (reduce) { s.tilt = s.tx; s.lean = s.tz; still(); }\n    };\n    const down = (px: number, pz: number) => { mark(); s.held = true; s.px = px; s.pz = pz; if (reduce) { s.y = 0; s.tilt = 0; s.lean = 0; still(); } };\n    const up = () => { if (!s.held) return; mark(); s.held = false; s.vt -= s.px * 0.5; s.vl -= s.pz * 0.7; if (reduce) { s.y = HOVER; s.vt = 0; s.vl = 0; still(); } };\n    const onDown = (e: PointerEvent) => { const b = btn.getBoundingClientRect(); down(((e.clientX - b.left) / b.width) * 2 - 1, ((e.clientY - b.top) / b.height) * 2 - 1); };\n    const onKeyDown = (e: KeyboardEvent) => { if ((e.key === \" \" || e.key === \"Enter\") && !e.repeat) down(0.4, 0.3); };\n    const onKeyUp = (e: KeyboardEvent) => { if (e.key === \" \" || e.key === \"Enter\") up(); };\n    const onLeave = () => { s.tx = 0; s.tz = 0; };\n    const onLost = (e: Event) => { e.preventDefault(); cancelAnimationFrame(raf); raf = -1; for (const k of [\"left\", \"top\", \"width\", \"height\"]) btn.style.removeProperty(k); setLive(false); };\n    el.addEventListener(\"pointermove\", onMove); el.addEventListener(\"pointerleave\", onLeave);\n    btn.addEventListener(\"pointerdown\", onDown); window.addEventListener(\"pointerup\", up); window.addEventListener(\"pointercancel\", up);\n    btn.addEventListener(\"keydown\", onKeyDown); btn.addEventListener(\"keyup\", onKeyUp); btn.addEventListener(\"blur\", up);\n    cv.addEventListener(\"webglcontextlost\", onLost);\n    const ro = new ResizeObserver(() => { if (reduce || !raf) still(); });\n    ro.observe(el);\n    const io = new IntersectionObserver(([entry]) => { seen = entry.isIntersecting; if (seen && raf !== -1) wake(); });\n    io.observe(el);\n    const onVis = () => { if (!document.hidden && raf !== -1) wake(); };\n    document.addEventListener(\"visibilitychange\", onVis);\n\n    return () => {\n      cancelAnimationFrame(raf);\n      img.removeEventListener(\"load\", onPhoto);\n      el.removeEventListener(\"pointermove\", onMove); el.removeEventListener(\"pointerleave\", onLeave);\n      btn.removeEventListener(\"pointerdown\", onDown); window.removeEventListener(\"pointerup\", up); window.removeEventListener(\"pointercancel\", up);\n      btn.removeEventListener(\"keydown\", onKeyDown); btn.removeEventListener(\"keyup\", onKeyUp); btn.removeEventListener(\"blur\", up);\n      cv.removeEventListener(\"webglcontextlost\", onLost);\n      gl.getExtension(\"WEBGL_lose_context\")?.loseContext(); // hand the textures and buffers back at once\n      ro.disconnect(); io.disconnect();\n      document.removeEventListener(\"visibilitychange\", onVis);\n    };\n  }, []);\n\n  return (\n    <div ref={root} className=\"relative h-[620px] w-full overflow-hidden bg-[#0b0b0c] sm:h-[700px]\">\n      {/* Shown until the traced picture is ready, and kept when the browser cannot trace it: the same print and glass, built from plain layers. */}\n      <div aria-hidden={live} className={`absolute inset-0 ${live ? \"opacity-0\" : \"opacity-100\"}`} style={{ perspective: \"1500px\", perspectiveOrigin: \"50% 30%\" }}>\n        <div className=\"absolute left-0 top-[46%] w-[172%] max-w-none [transform:translate(-1%,-50%)_rotateX(30deg)] sm:left-1/2 sm:top-[46%] sm:w-[112%] sm:[transform:translate(-27%,-50%)_rotateX(38deg)]\">\n          <div className=\"relative bg-[#f3f0e8] p-[3.4%] shadow-[0_60px_90px_rgba(0,0,0,0.7)]\">\n            <div className=\"relative aspect-[3/2] overflow-hidden bg-[#e2a80f]\">\n              <img ref={photo} src={PHOTO} alt={PHOTO_ALT} crossOrigin=\"anonymous\" width={1600} height={1067} className=\"absolute inset-0 h-full w-full object-cover\" />\n              <p className=\"absolute left-[2.5%] top-[2%] text-[23vw] leading-none tracking-[-0.035em] text-[#fbf8f1] sm:text-[14.5vw]\" style={{ fontFamily: SERIF }}>{MASTHEAD}</p>\n              <p className=\"absolute left-[3.4%] top-[25.5%] text-[2.6vw] font-semibold uppercase leading-[1.7] tracking-[0.22em] text-[#fbf8f1] sm:text-[1.25vw]\" style={{ fontFamily: GROTESK }}>{FOLIO[0]}<br />{FOLIO[1]}</p>\n              <div className=\"absolute inset-0 bg-gradient-to-b from-black/15 via-transparent to-black/20\" />\n            </div>\n          </div>\n        </div>\n        <div className=\"absolute left-1/2 top-[53%] h-[88px] w-[290px] -translate-x-1/2 -translate-y-1/2 sm:left-[40.6%] sm:top-[60%] sm:h-[140px] sm:w-[540px]\">\n          <span className=\"absolute inset-x-4 -bottom-7 h-10 translate-x-6 rounded-full bg-black/55 blur-xl\" />\n          <span className=\"absolute inset-0 rounded-full border border-white/45 bg-[#0a1a3a]/25 shadow-[inset_0_14px_20px_-6px_rgba(255,255,255,0.5),inset_0_-30px_26px_-12px_rgba(255,255,255,0.75),inset_0_-3px_0_rgba(255,255,255,0.9),inset_0_0_0_1px_rgba(10,20,40,0.35),0_14px_26px_rgba(0,0,0,0.4)] backdrop-blur-[5px] backdrop-brightness-90 backdrop-saturate-150\" />\n          <span className=\"absolute inset-x-[9%] top-[7%] h-[9%] rounded-full bg-gradient-to-b from-white/75 to-white/0 blur-[1.5px]\" />\n        </div>\n      </div>\n\n      <canvas ref={canvas} role=\"img\" aria-label={`${PHOTO_ALT}, printed with a white margin and lying on a dark table under a bar of clear glass.`} className={`absolute inset-0 h-full w-full ${live ? \"opacity-100\" : \"opacity-0\"}`} />\n\n      <h2 className=\"sr-only\">{MASTHEAD}. {FOLIO.join(\". \")}. {CAPTION}</h2>\n      <button\n        ref={button}\n        type=\"button\"\n        onClick={() => setCount((c) => c + 1)}\n        style={{ fontFamily: GROTESK }}\n        className={`absolute left-1/2 top-[53%] flex h-[88px] w-[290px] touch-manipulation select-none items-center justify-center gap-3 rounded-full text-[22px] font-semibold tracking-[-0.02em] outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 focus-visible:ring-offset-black/50 sm:left-[40.6%] sm:top-[60%] sm:h-[140px] sm:w-[540px] sm:text-[38px] ${live ? \"text-transparent\" : \"-translate-x-1/2 -translate-y-[62%] text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.55)]\"}`}\n      >\n        {LABEL}\n        <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" className=\"h-6 w-6 sm:h-9 sm:w-9\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.4\" strokeLinecap=\"round\" strokeLinejoin=\"round\"><path d=\"M4 12h16M13 5l7 7-7 7\" /></svg>\n      </button>\n\n      <p className=\"sr-only\" aria-live=\"polite\">{count > 0 ? `Issue 14 opened ${count} ${count === 1 ? \"time\" : \"times\"}.` : \"\"}</p>\n    </div>\n  );\n}\n"}]}
