Back to the app
The code
The Flan Test by Claude Fable 5.1
Exactly as the AI wrote it. Shown as text, so nothing runs on this page.
Try 1 · index.html
worksshown<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Wobbly Caramel Flan</title>
<style>
:root{--ink:#3a2a1a;--panel:rgba(255,250,243,.92);--accent:#c9711a;--accent2:#8a4a0c}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;overflow:hidden;background:#e8dccd;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:var(--ink)}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none;cursor:grab}
#hud{position:fixed;inset:0;pointer-events:none;display:flex;flex-direction:column;justify-content:space-between}
.card{pointer-events:auto;background:var(--panel);border-radius:14px;padding:10px 14px;margin:12px;box-shadow:0 4px 18px rgba(60,30,0,.15);max-width:min(340px,calc(100vw - 24px))}
.card b{font-size:17px}
#count{font-weight:600;color:var(--accent2);margin-top:2px}
.hint{font-size:12px;opacity:.75;margin-top:4px;line-height:1.35}
#bar{pointer-events:auto;display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:10px 12px;margin:0 12px 12px;background:var(--panel);border-radius:16px;box-shadow:0 4px 18px rgba(60,30,0,.15)}
button{min-height:44px;min-width:44px;padding:0 14px;border:0;border-radius:12px;background:#f1e4d0;color:var(--ink);font:600 14px system-ui,sans-serif;cursor:pointer;box-shadow:inset 0 -2px 0 rgba(0,0,0,.08)}
button.on,button.press{background:var(--accent);color:#fff}
button:active{transform:translateY(1px)}
label{display:flex;align-items:center;gap:6px;font-size:13px;font-weight:600;min-height:44px}
input[type=range]{width:110px;height:44px;accent-color:var(--accent)}
#cursor{position:fixed;left:0;top:0;width:30px;height:30px;margin:-15px 0 0 -15px;border-radius:50%;border:3px solid #fff;background:rgba(201,113,26,.75);box-shadow:0 2px 10px rgba(0,0,0,.35);pointer-events:none;display:none;z-index:5;transition:transform .08s}
#cursor.down{transform:scale(.7);background:rgba(138,74,12,.95)}
#demoTag{position:fixed;top:12px;right:12px;background:var(--accent2);color:#fff;padding:8px 12px;border-radius:10px;font-size:13px;font-weight:600;pointer-events:none;z-index:5;display:none}
@media (max-width:520px){input[type=range]{width:90px}.card b{font-size:15px}.hint{display:none}}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="hud">
<div><div class="card"><b>Wobbly Caramel Flan</b><div id="count">Pieces: 1</div>
<div class="hint">Drag the flan to stretch it, tap it to poke. Pick the Spoon and tap to scoop. Drag empty space to orbit, pinch or scroll to zoom.</div></div></div>
<div id="bar">
<button id="bHand" class="on" title="Hand tool (H)">Hand</button>
<button id="bSpoon" title="Spoon tool (P)">Spoon</button>
<button id="bShake" title="Shake (S)">Shake the plate</button>
<button id="bReset" title="Reset (R)">Reset</button>
<button id="bMute" title="Mute (M)">Mute</button>
<label>Firmness <input id="sFirm" type="range" min="0" max="100" value="45"></label>
<label>Damping <input id="sDamp" type="range" min="0" max="100" value="35"></label>
</div>
</div>
<div id="cursor"></div>
<div id="demoTag">Demo - touch or press any key to take over</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function(){
'use strict';
/* ---------- seeded randomness ---------- */
function mulberry(s){return function(){s|=0;s=s+0x6D2B79F5|0;let t=Math.imul(s^s>>>15,1|s);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}
const rndT=mulberry(20260930); // textures / static look
let rnd=mulberry(1337); // simulation (re-seeded on reset)
/* ---------- lattice definition ---------- */
const S=3,R=16,L=5,FH=0.74,RB=1.05,RT=0.82;
const DRIP=[];for(let r=0;r<R;r++)DRIP.push(1+Math.floor(rndT()*3));
function key(s,r,l){if(s===0)return'0,0,'+l;return s+','+((r%R+R)%R)+','+l;}
function restPos(s,r,l){const t=l/L,rad=(RB+(RT-RB)*t)*(s/S),a=r/R*Math.PI*2;return[Math.cos(a)*rad,t*FH,Math.sin(a)*rad];}
function cornerKeys(s,r,l){return[key(s-1,r,l),key(s,r,l),key(s,r+1,l),key(s-1,r+1,l),key(s-1,r,l+1),key(s,r,l+1),key(s,r+1,l+1),key(s-1,r+1,l+1)];}
const EDGES=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7],[0,2],[1,3],[4,6],[5,7],[1,6],[2,5],[0,7],[3,4],[0,5],[1,4],[2,7],[3,6]];
const ALL_CELLS=[];for(let s=1;s<=S;s++)for(let r=0;r<R;r++)for(let l=0;l<L;l++)ALL_CELLS.push([s,r,l]);
/* ---------- parameters ---------- */
const params={K:200,damp:2.5,cs:0.45};
const G=4.0,H_DT=1/120;
const shake={t:0,accel:0};
let grab=null,tool='hand',muted=false;
/* ---------- renderer / scene ---------- */
const canvas=document.getElementById('c');
const renderer=new THREE.WebGLRenderer({canvas:canvas,antialias:true});
renderer.outputEncoding=THREE.sRGBEncoding;renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.05;
renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;
const scene=new THREE.Scene();scene.background=new THREE.Color(0xe6d9c8);
const camera=new THREE.PerspectiveCamera(38,1,0.1,100);
const cam={theta:0.6,phi:1.08,dist:4.6,target:new THREE.Vector3(0,0.3,0)};
function resetCam(){cam.theta=0.6;cam.phi=1.08;cam.dist=4.6;}
function updateCamera(){const sp=Math.sin(cam.phi);camera.position.set(cam.target.x+cam.dist*sp*Math.sin(cam.theta),cam.target.y+cam.dist*Math.cos(cam.phi),cam.target.z+cam.dist*sp*Math.cos(cam.theta));camera.lookAt(cam.target);}
scene.add(new THREE.HemisphereLight(0xfff6e8,0x7a6a58,0.55));
const sun=new THREE.DirectionalLight(0xfff2e0,1.15);sun.position.set(3,6.5,3.5);sun.castShadow=true;
sun.shadow.mapSize.set(1024,1024);sun.shadow.camera.left=-4;sun.shadow.camera.right=4;sun.shadow.camera.top=4;sun.shadow.camera.bottom=-4;sun.shadow.camera.near=1;sun.shadow.camera.far=20;sun.shadow.bias=-0.002;sun.shadow.radius=3;
scene.add(sun);
const fill=new THREE.PointLight(0xdfe8ff,0.5,30);fill.position.set(-4,3,-2);scene.add(fill);
const rim=new THREE.PointLight(0xffd9a8,0.6,30);rim.position.set(1,2.5,-5);scene.add(rim);
/* tablecloth (procedural gingham) */
function makeCloth(){const c=document.createElement('canvas');c.width=c.height=256;const g=c.getContext('2d');g.fillStyle='#f4eee6';g.fillRect(0,0,256,256);g.fillStyle='rgba(112,146,196,0.5)';for(let i=0;i<4;i++){g.fillRect(i*64,0,32,256);g.fillRect(0,i*64,256,32);}g.fillStyle='rgba(80,110,170,0.35)';for(let i=0;i<4;i++)for(let j=0;j<4;j++)g.fillRect(i*64,j*64,32,32);const img=g.getImageData(0,0,256,256),d=img.data;for(let i=0;i<d.length;i+=4){const n=(rndT()-0.5)*22;d[i]+=n;d[i+1]+=n;d[i+2]+=n;}g.putImageData(img,0,0);const t=new THREE.CanvasTexture(c);t.wrapS=t.wrapT=THREE.RepeatWrapping;t.repeat.set(12,12);t.encoding=THREE.sRGBEncoding;t.anisotropy=4;return t;}
const table=new THREE.Mesh(new THREE.PlaneGeometry(40,40),new THREE.MeshStandardMaterial({map:makeCloth(),roughness:0.95}));
table.rotation.x=-Math.PI/2;table.position.y=-0.125;table.receiveShadow=true;scene.add(table);
/* plate + caramel pool (grouped so the shake moves both) */
const plateGroup=new THREE.Group();scene.add(plateGroup);
const prof=[[0,-0.12],[1.9,-0.12],[2.35,-0.04],[2.75,0.14],[2.82,0.2],[2.74,0.23],[2.3,0.05],[1.85,0.0],[0,0.0]].map(p=>new THREE.Vector2(p[0],p[1]));
const plate=new THREE.Mesh(new THREE.LatheGeometry(prof,64),new THREE.MeshPhysicalMaterial({color:0xfbfaf6,roughness:0.25,clearcoat:0.8,clearcoatRoughness:0.15,side:THREE.DoubleSide}));
plate.receiveShadow=true;plate.castShadow=true;plateGroup.add(plate);
const caramelMat=new THREE.MeshPhysicalMaterial({color:0xb85a0c,emissive:0x3a1800,emissiveIntensity:0.35,roughness:0.12,clearcoat:1,clearcoatRoughness:0.08,transparent:true,opacity:0.94});
const custardMat=new THREE.MeshPhysicalMaterial({color:0xf5d98f,emissive:0x2a1a04,emissiveIntensity:0.25,roughness:0.5,clearcoat:0.35,clearcoatRoughness:0.45,transparent:true,opacity:0.95});
const poolMat=new THREE.MeshPhysicalMaterial({color:0xa9500a,emissive:0x2a1200,emissiveIntensity:0.3,roughness:0.08,clearcoat:1,clearcoatRoughness:0.05,transparent:true,opacity:0.85});
(function(){const sh=new THREE.Shape();const N=72,ph1=rndT()*6.28,ph2=rndT()*6.28;for(let i=0;i<N;i++){const a=i/N*Math.PI*2;const rad=RB*1.32+0.14*Math.sin(a*5+ph1)+0.08*Math.sin(a*9+ph2)+0.05*Math.sin(a*2);const x=Math.cos(a)*rad,y=Math.sin(a)*rad;if(i===0)sh.moveTo(x,y);else sh.lineTo(x,y);}sh.closePath();const m=new THREE.Mesh(new THREE.ShapeGeometry(sh,8),poolMat);m.rotation.x=-Math.PI/2;m.position.y=0.006;m.receiveShadow=true;plateGroup.add(m);})();
/* spoon */
const spoon=new THREE.Group();
(function(){const sm=new THREE.MeshStandardMaterial({color:0xd9dde2,metalness:0.9,roughness:0.22});const bowl=new THREE.Mesh(new THREE.SphereGeometry(0.24,20,14,0,Math.PI*2,0,Math.PI/2),sm);bowl.scale.set(1,0.5,1.35);bowl.rotation.x=Math.PI;bowl.material.side=THREE.DoubleSide;bowl.castShadow=true;spoon.add(bowl);const h=new THREE.Mesh(new THREE.CylinderGeometry(0.035,0.05,1.1,10),sm);h.rotation.z=Math.PI/2;h.rotation.y=0.0;h.position.set(0.72,0.12,0);h.castShadow=true;spoon.add(h);})();
spoon.visible=false;scene.add(spoon);
let spoonAnim=null;
/* ---------- soft-body piece ---------- */
const pieces=[];
class Piece{
constructor(cellList,src,offset,vel0){
this.cellList=cellList;this.cells=new Set(cellList.map(c=>c.join(',')));
const idx=new Map(),pos=[],rest=[];this.idx=idx;
const get=(s,r,l)=>{const k=key(s,r,l);let i=idx.get(k);if(i===undefined){i=pos.length/3;idx.set(k,i);const rp=restPos(s,r,l);rest.push(rp[0],rp[1],rp[2]);let p=null;if(src){const j=src.idx.get(k);if(j!==undefined)p=[src.pos[3*j],src.pos[3*j+1],src.pos[3*j+2]];}if(!p)p=rp;pos.push(p[0]+offset[0],p[1]+offset[1],p[2]+offset[2]);}return i;};
const cons=new Map();const addC=(a,b)=>{if(a===b)return;const k=a<b?a+'_'+b:b+'_'+a;if(!cons.has(k))cons.set(k,[a,b]);};
const cust=[],car=[];
for(const cl of cellList){const s=cl[0],r=cl[1],l=cl[2];
const c=[get(s-1,r,l),get(s,r,l),get(s,r+1,l),get(s-1,r+1,l),get(s-1,r,l+1),get(s,r,l+1),get(s,r+1,l+1),get(s-1,r+1,l+1)];
EDGES.forEach(e=>addC(c[e[0]],c[e[1]]));
let ccx=0,ccy=0,ccz=0;for(let i=0;i<8;i++){ccx+=rest[3*c[i]];ccy+=rest[3*c[i]+1];ccz+=rest[3*c[i]+2];}ccx/=8;ccy/=8;ccz/=8;
const faces=[[[0,1,2,3],[s,r,l-1],0],[[4,5,6,7],[s,r,l+1],1],[[1,2,6,5],[s+1,r,l],2],[[0,3,7,4],s>1?[s-1,r,l]:null,3],[[0,1,5,4],[s,r-1,l],4],[[3,2,6,7],[s,r+1,l],5]];
for(const f of faces){if(!f[1])continue;const nk=f[1];if(this.cells.has(nk[0]+','+((nk[1]%R+R)%R)+','+nk[2]))continue;
const q=f[0].map(i=>c[i]);const isCar=(f[2]===1&&l+1===L)||(f[2]===2&&s===S&&l>=L-DRIP[r]);
let fx=0,fy=0,fz=0;for(let i=0;i<4;i++){fx+=rest[3*q[i]];fy+=rest[3*q[i]+1];fz+=rest[3*q[i]+2];}fx=fx/4-ccx;fy=fy/4-ccy;fz=fz/4-ccz;
const ax=rest[3*q[1]]-rest[3*q[0]],ay=rest[3*q[1]+1]-rest[3*q[0]+1],az=rest[3*q[1]+2]-rest[3*q[0]+2];
const bx=rest[3*q[2]]-rest[3*q[0]],by=rest[3*q[2]+1]-rest[3*q[0]+1],bz=rest[3*q[2]+2]-rest[3*q[0]+2];
const nx=ay*bz-az*by,ny=az*bx-ax*bz,nz=ax*by-ay*bx;
const flip=(nx*fx+ny*fy+nz*fz)<0;
const out=isCar?car:cust;
const tri=(a,b,d)=>{if(a===b||b===d||a===d)return;if(flip)out.push(a,d,b);else out.push(a,b,d);};
tri(q[0],q[1],q[2]);tri(q[0],q[2],q[3]);}
}
this.n=pos.length/3;this.pos=new Float32Array(pos);this.rest=new Float32Array(rest);this.prev=new Float32Array(this.n*3);this.vel=new Float32Array(this.n*3);
if(vel0)for(let i=0;i<this.n;i++){const k=[...idx.keys()][i];let v=null;if(src){const j=src.idx.get(k);if(j!==undefined)v=[src.vel[3*j],src.vel[3*j+1],src.vel[3*j+2]];}this.vel[3*i]=(v?v[0]:0)+vel0[0];this.vel[3*i+1]=(v?v[1]:0)+vel0[1];this.vel[3*i+2]=(v?v[2]:0)+vel0[2];}
const ca=[...cons.values()];this.cons=new Int32Array(ca.length*2);this.clen=new Float32Array(ca.length);
ca.forEach((e,i)=>{this.cons[2*i]=e[0];this.cons[2*i+1]=e[1];const dx=rest[3*e[0]]-rest[3*e[1]],dy=rest[3*e[0]+1]-rest[3*e[1]+1],dz=rest[3*e[0]+2]-rest[3*e[1]+2];this.clen[i]=Math.sqrt(dx*dx+dy*dy+dz*dz);});
let rx=0,ry=0,rz=0;for(let i=0;i<this.n;i++){rx+=rest[3*i];ry+=rest[3*i+1];rz+=rest[3*i+2];}this.rc=[rx/this.n,ry/this.n,rz/this.n];
this.tris=new Uint16Array(cust.concat(car));
this.V0=this.volume(this.rest);
const geo=new THREE.BufferGeometry();this.attr=new THREE.BufferAttribute(this.pos,3);this.attr.setUsage(THREE.DynamicDrawUsage);
geo.setAttribute('position',this.attr);geo.setIndex(new THREE.BufferAttribute(this.tris,1));geo.addGroup(0,cust.length,0);geo.addGroup(cust.length,car.length,1);
geo.computeVertexNormals();this.geo=geo;
this.mesh=new THREE.Mesh(geo,[custardMat,caramelMat]);this.mesh.castShadow=true;this.mesh.receiveShadow=true;this.mesh.frustumCulled=false;this.mesh.userData.piece=this;
scene.add(this.mesh);
}
volume(p){const I=this.tris;let V=0;for(let t=0;t<I.length;t+=3){const a=I[t]*3,b=I[t+1]*3,c=I[t+2]*3;const ax=p[a],ay=p[a+1],az=p[a+2],bx=p[b],by=p[b+1],bz=p[b+2],cx=p[c],cy=p[c+1],cz=p[c+2];V+=ax*(by*cz-bz*cy)-ay*(bx*cz-bz*cx)+az*(bx*cy-by*cx);}return Math.abs(V/6);}
centroid(){const p=this.pos,n=this.n;let x=0,y=0,z=0;for(let i=0;i<n;i++){x+=p[3*i];y+=p[3*i+1];z+=p[3*i+2];}return new THREE.Vector3(x/n,y/n,z/n);}
cellCenter(cl){const ks=cornerKeys(cl[0],cl[1],cl[2]);let x=0,y=0,z=0;for(const k of ks){const i=this.idx.get(k);x+=this.pos[3*i];y+=this.pos[3*i+1];z+=this.pos[3*i+2];}return new THREE.Vector3(x/8,y/8,z/8);}
step(dt){
const n=this.n,p=this.pos,v=this.vel,rs=this.rest,pr=this.prev;
let cx=0,cy=0,cz=0;for(let i=0;i<n;i++){cx+=p[3*i];cy+=p[3*i+1];cz+=p[3*i+2];}cx/=n;cy/=n;cz/=n;
const K=params.K,dmp=Math.exp(-params.damp*dt),ox=cx-this.rc[0],oy=cy-this.rc[1],oz=cz-this.rc[2];
for(let i=0;i<n;i++){const j=3*i;v[j]+=(rs[j]+ox-p[j])*K*dt;v[j+1]+=(rs[j+1]+oy-p[j+1])*K*dt-G*dt;v[j+2]+=(rs[j+2]+oz-p[j+2])*K*dt;v[j]*=dmp;v[j+1]*=dmp;v[j+2]*=dmp;}
if(shake.t>0){const a=shake.accel;for(let i=0;i<n;i++)if(p[3*i+1]<0.1)v[3*i]+=a*dt;}
if(grab&&grab.piece===this){const g=grab;for(let q=0;q<g.ids.length;q++){const i=g.ids[q],w=g.w[q],j=3*i;const tx=g.target.x+g.off[3*q],ty=g.target.y+g.off[3*q+1],tz=g.target.z+g.off[3*q+2];v[j]+=(tx-p[j])*w*450*dt;v[j+1]+=(ty-p[j+1])*w*450*dt;v[j+2]+=(tz-p[j+2])*w*450*dt;const d=Math.exp(-w*28*dt);v[j]*=d;v[j+1]*=d;v[j+2]*=d;}}
for(let i=0;i<n*3;i++){pr[i]=p[i];p[i]+=v[i]*dt;}
const C=this.cons,CL=this.clen,cs=params.cs;
for(let it=0;it<2;it++){
for(let c=0;c<CL.length;c++){const a=C[2*c]*3,b=C[2*c+1]*3;let dx=p[b]-p[a],dy=p[b+1]-p[a+1],dz=p[b+2]-p[a+2];const l=Math.sqrt(dx*dx+dy*dy+dz*dz)||1e-6;const k=(l-CL[c])/l*0.5*cs;dx*=k;dy*=k;dz*=k;p[a]+=dx;p[a+1]+=dy;p[a+2]+=dz;p[b]-=dx;p[b+1]-=dy;p[b+2]-=dz;}
for(let i=0;i<n;i++)if(p[3*i+1]<0)p[3*i+1]=0;
}
const V=this.volume(p);
if(V>1e-5){let s=Math.cbrt(this.V0/V);s=1+(s-1)*0.5;s=Math.max(0.9,Math.min(1.1,s));
if(Math.abs(s-1)>1e-4){cx=0;cy=0;cz=0;for(let i=0;i<n;i++){cx+=p[3*i];cy+=p[3*i+1];cz+=p[3*i+2];}cx/=n;cy/=n;cz/=n;
for(let i=0;i<n;i++){const j=3*i;p[j]=cx+(p[j]-cx)*s;p[j+1]=cy+(p[j+1]-cy)*s;p[j+2]=cz+(p[j+2]-cz)*s;if(p[j+1]<0)p[j+1]=0;}}}
const idt=1/dt;
for(let i=0;i<n;i++){const j=3*i;v[j]=(p[j]-pr[j])*idt;v[j+1]=(p[j+1]-pr[j+1])*idt;v[j+2]=(p[j+2]-pr[j+2])*idt;if(p[j+1]<=0.0005){v[j]*=0.8;v[j+2]*=0.8;if(v[j+1]<0)v[j+1]=0;}}
}
sync(){this.attr.needsUpdate=true;this.geo.computeVertexNormals();}
dispose(){scene.remove(this.mesh);this.geo.dispose();}
}
function updateCount(){document.getElementById('count').textContent='Pieces: '+pieces.length;}
function resetSim(){rnd=mulberry(1337);pieces.forEach(p=>p.dispose());pieces.length=0;pieces.push(new Piece(ALL_CELLS,null,[0,0,0],null));grab=null;shake.t=0;spoonAnim=null;resetCam();updateCount();}
resetSim();
/* ---------- audio (starts only after a real tap) ---------- */
let actx=null;
function unlockAudio(){if(!actx){try{actx=new(window.AudioContext||window.webkitAudioContext)();}catch(e){actx=null;}}if(actx&&actx.state==='suspended')actx.resume();}
function blip(f0,f1,dur,vol,type){if(!actx||muted)return;try{const o=actx.createOscillator(),g=actx.createGain(),t=actx.currentTime;o.type=type||'sine';o.frequency.setValueAtTime(f0,t);o.frequency.exponentialRampToValueAtTime(f1,t+dur);g.gain.setValueAtTime(0.0001,t);g.gain.exponentialRampToValueAtTime(vol,t+0.012);g.gain.exponentialRampToValueAtTime(0.0001,t+dur);o.connect(g);g.connect(actx.destination);o.start(t);o.stop(t+dur+0.03);}catch(e){}}
/* ---------- picking / interactions ---------- */
const ray=new THREE.Raycaster(),ndc=new THREE.Vector2();
function pick(x,y){ndc.set(x/innerWidth*2-1,-(y/innerHeight)*2+1);ray.setFromCamera(ndc,camera);pieces.forEach(p=>p.geo.computeBoundingSphere());const hits=ray.intersectObjects(pieces.map(p=>p.mesh));if(!hits.length)return null;return{point:hits[0].point,piece:hits[0].object.userData.piece,dir:ray.ray.direction.clone()};}
function startGrab(hit,x,y){const pc=hit.piece,hp=hit.point,ids=[],w=[],off=[];for(let i=0;i<pc.n;i++){const dx=pc.pos[3*i]-hp.x,dy=pc.pos[3*i+1]-hp.y,dz=pc.pos[3*i+2]-hp.z;const d=Math.sqrt(dx*dx+dy*dy+dz*dz);if(d<0.55){const u=1-d/0.55;ids.push(i);w.push(u*u*(3-2*u));off.push(dx,dy,dz);}}
const nrm=new THREE.Vector3();camera.getWorldDirection(nrm);const plane=new THREE.Plane().setFromNormalAndCoplanarPoint(nrm,hp);
grab={piece:pc,ids:ids,w:w,off:off,target:hp.clone(),plane:plane,hit:hit,x0:x,y0:y,t0:performance.now(),moved:false};}
function moveGrab(x,y){if(!grab)return;if(Math.hypot(x-grab.x0,y-grab.y0)>8)grab.moved=true;ndc.set(x/innerWidth*2-1,-(y/innerHeight)*2+1);ray.setFromCamera(ndc,camera);const t=new THREE.Vector3();if(ray.ray.intersectPlane(grab.plane,t))grab.target.copy(t);}
function poke(hit){const pc=hit.piece,hp=hit.point,d=hit.dir;for(let i=0;i<pc.n;i++){const dx=pc.pos[3*i]-hp.x,dy=pc.pos[3*i+1]-hp.y,dz=pc.pos[3*i+2]-hp.z;const dist=Math.sqrt(dx*dx+dy*dy+dz*dz);if(dist<0.45){const w=1-dist/0.45;pc.vel[3*i]+=d.x*3*w;pc.vel[3*i+1]+=d.y*3*w;pc.vel[3*i+2]+=d.z*3*w;}}blip(330,140,0.16,0.18,'sine');}
function scoop(hit){const src=hit.piece,hp=hit.point;if(src.cellList.length<=4){blip(200,180,0.1,0.08,'triangle');return;}
const ds=src.cellList.map(c=>({c:c,d:src.cellCenter(c).distanceTo(hp)})).sort((a,b)=>a.d-b.d);
let sel=ds.filter(o=>o.d<0.47).map(o=>o.c);if(!sel.length)sel=[ds[0].c];const maxSel=src.cellList.length-3;if(sel.length>maxSel)sel=sel.slice(0,maxSel);
const selSet=new Set(sel.map(c=>c.join(',')));const rem=src.cellList.filter(c=>!selSet.has(c.join(',')));
const cen=src.centroid();let dx=hp.x-cen.x,dz=hp.z-cen.z;const l=Math.hypot(dx,dz)||1;dx/=l;dz/=l;
const chunk=new Piece(sel,src,[dx*0.6,0.55,dz*0.6],[dx*1.2+(rnd()-0.5)*0.4,2.2,dz*1.2+(rnd()-0.5)*0.4]);
const rest=new Piece(rem,src,[0,0,0],[0,0,0]);
src.dispose();pieces.splice(pieces.indexOf(src),1);pieces.push(rest,chunk);updateCount();
spoonAnim={t:0,from:hp.clone(),dir:new THREE.Vector3(dx,0,dz)};blip(220,70,0.28,0.2,'triangle');}
function doShake(){shake.t=0.75;blip(70,38,0.6,0.1,'sawtooth');}
function setTool(t){tool=t;document.getElementById('bHand').classList.toggle('on',t==='hand');document.getElementById('bSpoon').classList.toggle('on',t==='spoon');canvas.style.cursor=t==='spoon'?'crosshair':'grab';}
function setMuted(m){muted=m;document.getElementById('bMute').textContent=muted?'Unmute':'Mute';}
let drag=null;
function onDown(x,y){const hit=pick(x,y);
if(hit){if(tool==='spoon'){scoop(hit);drag=null;}else{startGrab(hit,x,y);drag={type:'grab'};}}
else drag={type:'orbit',x:x,y:y};}
function onMove(x,y){if(!drag)return;if(drag.type==='orbit'){cam.theta-=(x-drag.x)*0.006;cam.phi-=(y-drag.y)*0.006;cam.phi=Math.max(0.25,Math.min(1.45,cam.phi));drag.x=x;drag.y=y;}else moveGrab(x,y);}
function onUp(){if(drag&&drag.type==='grab'&&grab){if(!grab.moved&&performance.now()-grab.t0<350){const h=pick(grab.x0,grab.y0);if(h)poke(h);}grab=null;}drag=null;}
/* real pointer events */
const pointers=new Map();let pinch=0;
canvas.addEventListener('pointerdown',e=>{e.preventDefault();stopDemo();unlockAudio();try{canvas.setPointerCapture(e.pointerId);}catch(err){}pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
if(pointers.size===2){onUp();grab=null;drag=null;const a=[...pointers.values()];pinch=Math.hypot(a[0].x-a[1].x,a[0].y-a[1].y);return;}
if(pointers.size>2)return;onDown(e.clientX,e.clientY);});
canvas.addEventListener('pointermove',e=>{if(!pointers.has(e.pointerId))return;pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});
if(pointers.size===2){const a=[...pointers.values()];const d=Math.hypot(a[0].x-a[1].x,a[0].y-a[1].y);if(pinch>0&&d>0){cam.dist=Math.max(2.2,Math.min(10,cam.dist*pinch/d));}pinch=d;return;}
onMove(e.clientX,e.clientY);});
function endPointer(e){if(pointers.has(e.pointerId)){pointers.delete(e.pointerId);onUp();pinch=0;}}
canvas.addEventListener('pointerup',endPointer);canvas.addEventListener('pointercancel',endPointer);
canvas.addEventListener('wheel',e=>{e.preventDefault();stopDemo();cam.dist=Math.max(2.2,Math.min(10,cam.dist*Math.exp(e.deltaY*0.0012)));},{passive:false});
window.addEventListener('keydown',e=>{stopDemo();const k=e.key.toLowerCase();if(k==='r')resetSim();else if(k==='s')doShake();else if(k==='h'||k==='1')setTool('hand');else if(k==='p'||k==='2')setTool('spoon');else if(k==='m')setMuted(!muted);});
/* UI buttons */
const $=id=>document.getElementById(id);
$('bHand').addEventListener('click',()=>setTool('hand'));$('bSpoon').addEventListener('click',()=>setTool('spoon'));
$('bShake').addEventListener('click',()=>{unlockAudio();doShake();});$('bReset').addEventListener('click',()=>{resetSim();});
$('bMute').addEventListener('click',()=>{unlockAudio();setMuted(!muted);});
function applySliders(){const f=$('sFirm').value/100,d=$('sDamp').value/100;params.K=40+f*380;params.cs=0.2+f*0.55;params.damp=0.4+d*7;}
$('sFirm').addEventListener('input',applySliders);$('sDamp').addEventListener('input',applySliders);applySliders();
document.getElementById('hud').addEventListener('pointerdown',()=>{stopDemo();unlockAudio();});
/* ---------- demo mode ---------- */
const cursorEl=$('cursor'),demoTag=$('demoTag');
let demo=null;
function scr(v){const p=v.clone().project(camera);return{x:(p.x+1)/2*innerWidth,y:(1-p.y)/2*innerHeight};}
function btnPos(id){const r=$(id).getBoundingClientRect();return{x:r.left+r.width/2,y:r.top+r.height/2};}
function flash(id){$(id).classList.add('press');setTimeout(()=>$(id).classList.remove('press'),180);}
function cursorTo(x,y){cursorEl.style.left=x+'px';cursorEl.style.top=y+'px';demo.cx=x;demo.cy=y;}
function lerpTo(from,to,u){const e=u<0.5?2*u*u:-1+(4-2*u)*u;cursorTo(from.x+(to.x-from.x)*e,from.y+(to.y-from.y)*e);}
function press(){cursorEl.classList.add('down');}function release(){cursorEl.classList.remove('down');}
function world(x,y,z){return new THREE.Vector3(x,y,z);}
const demoSegs=[
{s:0.2,e:1.2,begin:d=>{d.a={x:innerWidth*0.5,y:innerHeight*0.9};d.b=scr(world(0.45,0.55,0.4));},f:(d,u)=>lerpTo(d.a,d.b,u)},
{s:1.2,e:2.5,begin:d=>{press();onDown(d.cx,d.cy);d.a={x:d.cx,y:d.cy};},f:(d,u)=>{const t=Math.sin(u*Math.PI);cursorTo(d.a.x+t*150,d.a.y-t*50);onMove(d.cx,d.cy);},end:d=>{onUp();release();}},
{s:2.6,e:3.8,begin:d=>{d.a={x:d.cx,y:d.cy};d.b=scr(world(0,FH,0.05));},f:(d,u)=>lerpTo(d.a,d.b,u)},
{s:3.8,e:4.05,begin:d=>{press();onDown(d.cx,d.cy);},end:d=>{onUp();release();}},
{s:4.4,e:5.4,begin:d=>{d.a={x:d.cx,y:d.cy};d.b=btnPos('bSpoon');},f:(d,u)=>lerpTo(d.a,d.b,u),end:d=>{press();flash('bSpoon');setTool('spoon');setTimeout(release,150);}},
{s:5.6,e:6.8,begin:d=>{d.a={x:d.cx,y:d.cy};d.b=scr(world(0.95*Math.sin(cam.theta),0.5,0.95*Math.cos(cam.theta)));},f:(d,u)=>lerpTo(d.a,d.b,u),end:d=>{press();onDown(d.cx,d.cy);onUp();setTimeout(release,150);}},
{s:7.2,e:8.4,begin:d=>{d.a={x:d.cx,y:d.cy};d.b=btnPos('bShake');},f:(d,u)=>lerpTo(d.a,d.b,u),end:d=>{press();flash('bShake');doShake();setTimeout(release,150);}},
{s:9.0,e:10.0,begin:d=>{d.a={x:d.cx,y:d.cy};d.b=btnPos('bHand');},f:(d,u)=>lerpTo(d.a,d.b,u),end:d=>{press();flash('bHand');setTool('hand');setTimeout(release,150);}},
{s:10.2,e:11.0,begin:d=>{d.a={x:d.cx,y:d.cy};d.b={x:innerWidth*0.12,y:innerHeight*0.55};},f:(d,u)=>lerpTo(d.a,d.b,u)},
{s:11.0,e:13.2,begin:d=>{press();drag={type:'orbit',x:d.cx,y:d.cy};d.a={x:d.cx,y:d.cy};},f:(d,u)=>{cursorTo(d.a.x+u*innerWidth*0.45,d.a.y-Math.sin(u*Math.PI)*40);onMove(d.cx,d.cy);},end:d=>{onUp();release();}},
{s:13.4,e:14.4,begin:d=>{d.a={x:d.cx,y:d.cy};d.b=btnPos('bSpoon');},f:(d,u)=>lerpTo(d.a,d.b,u),end:d=>{press();flash('bSpoon');setTool('spoon');setTimeout(release,150);}},
{s:14.6,e:15.6,begin:d=>{d.a={x:d.cx,y:d.cy};d.b=scr(world(-0.35,FH,0.2));},f:(d,u)=>lerpTo(d.a,d.b,u),end:d=>{press();onDown(d.cx,d.cy);onUp();setTimeout(release,150);setTool('hand');flash('bHand');}},
{s:16.0,e:16.8,begin:d=>{d.a={x:d.cx,y:d.cy};d.b=scr(world(0.3,0.45,-0.5));},f:(d,u)=>lerpTo(d.a,d.b,u)},
{s:16.8,e:18.0,begin:d=>{press();onDown(d.cx,d.cy);d.a={x:d.cx,y:d.cy};},f:(d,u)=>{const t=Math.sin(u*Math.PI);cursorTo(d.a.x-t*120,d.a.y-t*90);onMove(d.cx,d.cy);},end:d=>{onUp();release();}},
{s:18.4,e:19.4,begin:d=>{d.a={x:d.cx,y:d.cy};d.b=btnPos('bReset');},f:(d,u)=>lerpTo(d.a,d.b,u),end:d=>{press();flash('bReset');resetSim();setTimeout(release,150);}}
];
function startDemo(){demo={t:0,cx:innerWidth/2,cy:innerHeight/2,done:new Set(),started:new Set()};cursorEl.style.display='block';demoTag.style.display='block';cursorTo(innerWidth/2,innerHeight*0.9);}
function stopDemo(){if(!demo)return;onUp();grab=null;drag=null;release();demo=null;cursorEl.style.display='none';demoTag.style.display='none';}
function demoTick(dt){const d=demo;d.t+=dt;demoSegs.forEach((sg,i)=>{if(d.t>=sg.s&&d.t<sg.e){if(!d.started.has(i)){d.started.add(i);if(sg.begin)sg.begin(d);}if(sg.f)sg.f(d,(d.t-sg.s)/(sg.e-sg.s));}else if(d.t>=sg.e&&d.started.has(i)&&!d.done.has(i)){d.done.add(i);if(sg.f)sg.f(d,1);if(sg.end)sg.end(d);}});
if(d.t>=20){d.t=0;d.started.clear();d.done.clear();}}
if(location.hash==='#demo')startDemo();
/* ---------- adaptive quality ---------- */
let quality=3,fAcc=0,fN=0;
function applyQuality(){const dpr=window.devicePixelRatio||1;renderer.setPixelRatio([0.6,0.8,1,Math.min(dpr,2)][quality]);const sh=quality>=2;if(renderer.shadowMap.enabled!==sh){renderer.shadowMap.enabled=sh;scene.traverse(o=>{if(o.material){(Array.isArray(o.material)?o.material:[o.material]).forEach(m=>m.needsUpdate=true);}});}}
function fpsTrack(dt){fAcc+=dt;fN++;if(fN>=90){const avg=fAcc/fN;fAcc=0;fN=0;if(avg>1/38&&quality>0){quality--;applyQuality();}}}
function resize(){const w=innerWidth,h=innerHeight;renderer.setSize(w,h,false);camera.aspect=w/h;camera.updateProjectionMatrix();}
window.addEventListener('resize',resize);resize();applyQuality();
/* ---------- main loop ---------- */
let last=performance.now(),acc=0,ready=false,simT=0;
function stepAll(dt){simT+=dt;if(shake.t>0){shake.t-=dt;const env=Math.min(1,shake.t/0.75);shake.accel=-Math.sin(simT*42)*85*env;plateGroup.position.x=Math.sin(simT*42)*0.045*env;if(shake.t<=0){shake.t=0;shake.accel=0;plateGroup.position.x=0;}}
for(const p of pieces)p.step(dt);}
function updateSpoon(dt){if(spoonAnim){const a=spoonAnim;a.t+=dt;const u=Math.min(1,a.t/0.7);spoon.visible=true;spoon.position.set(a.from.x+a.dir.x*u*0.5,a.from.y+u*u*1.1,a.from.z+a.dir.z*u*0.5);spoon.rotation.set(0,Math.atan2(a.dir.x,a.dir.z)+Math.PI/2,-0.35+u*0.9);if(a.t>0.9)spoonAnim=null;}
else if(tool==='spoon'){spoon.visible=true;spoon.position.set(1.95,0.02,0.6);spoon.rotation.set(0,-0.5,0);}else spoon.visible=false;}
function frame(now){requestAnimationFrame(frame);let dt=Math.min(0.05,(now-last)/1000);last=now;fpsTrack(dt);if(demo)demoTick(dt);
acc+=dt;let n=0;while(acc>=H_DT&&n<6){stepAll(H_DT);acc-=H_DT;n++;}if(n===6)acc=0;
for(const p of pieces)p.sync();updateSpoon(dt);updateCamera();renderer.render(scene,camera);
if(!ready){ready=true;try{parent.postMessage({vcb:'ready'},'*');}catch(e){}}}
requestAnimationFrame(frame);
})();
</script>
</body>
</html>
Try 2 · index.html
works<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Wobbly Caramel Flan</title>
<style>
:root { --panel: rgba(255,250,243,0.93); --ink:#4a2e14; --accent:#c2691c; }
html,body{margin:0;height:100%;overflow:hidden;background:#e9dfcf;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:var(--ink);-webkit-user-select:none;user-select:none;}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none;}
#title{position:fixed;top:10px;left:12px;font-weight:700;font-size:15px;letter-spacing:.3px;pointer-events:none;text-shadow:0 1px 0 #fff8;}
#title small{display:block;font-weight:400;font-size:12px;opacity:.8}
#hint{position:fixed;top:10px;right:12px;font-size:12px;line-height:1.35;background:var(--panel);padding:6px 10px;border-radius:10px;max-width:46vw;pointer-events:none;box-shadow:0 2px 10px #0002}
#ui{position:fixed;left:8px;right:8px;bottom:8px;background:var(--panel);border-radius:14px;padding:8px;box-shadow:0 6px 24px #0002;display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:center;}
button{min-height:44px;min-width:44px;padding:0 14px;border:0;border-radius:10px;background:#fff;color:var(--ink);font-size:14px;font-weight:600;box-shadow:0 1px 3px #0003;cursor:pointer;touch-action:manipulation;font-family:inherit}
button.on{background:var(--accent);color:#fff;}
button:active{transform:translateY(1px);}
.sl{display:flex;flex-direction:column;font-size:11px;font-weight:700;min-width:130px;gap:0;}
.sl input{width:100%;height:44px;margin:0;accent-color:var(--accent);}
#count{font-size:13px;font-weight:700;padding:0 6px;white-space:nowrap;min-width:70px;text-align:center}
#fake{position:fixed;left:0;top:0;width:28px;height:28px;border-radius:50%;border:3px solid #fff;background:rgba(194,105,28,.8);box-shadow:0 2px 8px #0006;transform:translate(-50%,-50%);pointer-events:none;display:none;z-index:9;transition:width .12s,height .12s,background .12s}
#fake.down{width:18px;height:18px;background:#6b2e06}
#demoTag{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:#0007;color:#fff;padding:6px 12px;border-radius:999px;font-size:12px;display:none;pointer-events:none;z-index:8}
@media (max-width:560px){#hint{display:none}.sl{min-width:100px}button{padding:0 10px;font-size:13px}#ui{gap:6px;padding:6px}}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="title">Wobbly Caramel Flan<small>soft-body custard, hand-rolled physics</small></div>
<div id="hint">Drag the flan to stretch it. Tap to poke. Spoon tool: tap to scoop. Drag empty space to orbit, scroll or pinch to zoom.</div>
<div id="ui">
<button id="bSpoon" aria-pressed="false">Spoon</button>
<button id="bShake">Shake the plate</button>
<button id="bReset">Reset</button>
<button id="bMute" aria-pressed="false">Sound: on</button>
<label class="sl">Firmness <input id="sFirm" type="range" min="0" max="100" value="55"></label>
<label class="sl">Damping <input id="sDamp" type="range" min="0" max="100" value="25"></label>
<div id="count">1 piece</div>
<button id="bDemo">Demo</button>
</div>
<div id="fake"></div>
<div id="demoTag">Demo mode: touch anything to take over</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function(){
'use strict';
// ---------- seeded randomness ----------
let _s = 1337;
function rnd(){ _s |= 0; _s = _s + 0x6D2B79F5 | 0; let t = Math.imul(_s ^ _s >>> 15, 1 | _s); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }
function smooth(a,b,x){ const t=Math.min(1,Math.max(0,(x-a)/(b-a))); return t*t*(3-2*t); }
function clamp(v,a,b){ return v<a?a:v>b?b:v; }
// ---------- lattice (cylindrical hexahedral cells) ----------
const M=4, A=20, NY=5, RB=1.0, RT=0.8, H=0.85, LH=H/NY;
const PER=1+M*A, NV=PER*(NY+1);
const REST=new Float32Array(NV*3), CW=new Float32Array(NV);
function rcone(y){ return RB+(RT-RB)*(y/H); }
function gid(m,a,j){ return j*PER+(m===0?0:1+(m-1)*A+((a%A)+A)%A); }
const drip=[]; for(let a=0;a<A;a++) drip.push(0.18+0.62*rnd());
for(let j=0;j<=NY;j++){
const y=j*LH, r=rcone(y);
let g=gid(0,0,j); REST[g*3]=0; REST[g*3+1]=y; REST[g*3+2]=0; CW[g]=(j===NY)?1:0;
for(let m=1;m<=M;m++) for(let a=0;a<A;a++){
g=gid(m,a,j); const th=a/A*Math.PI*2; const rr=r*(m/M)*((m===M&&j===NY)?0.94:1);
REST[g*3]=rr*Math.cos(th); REST[g*3+1]=y; REST[g*3+2]=rr*Math.sin(th);
let w=0; if(j===NY) w=1; else if(m===M){ const y0=H*(1-drip[a]); w=smooth(y0-0.16,y0+0.05,y); }
CW[g]=w;
}
}
function cid(m,a,j){ return (j*A+((a%A)+A)%A)*M+(m-1); }
function cellM(id){ return id%M+1; } function cellA(id){ return Math.floor(id/M)%A; } function cellJ(id){ return Math.floor(id/(M*A)); }
function cellVerts(id){ const m=cellM(id), a=cellA(id), j=cellJ(id);
return [gid(m-1,a,j),gid(m,a,j),gid(m,a+1,j),gid(m-1,a+1,j),gid(m-1,a,j+1),gid(m,a,j+1),gid(m,a+1,j+1),gid(m-1,a+1,j+1)]; }
function neighbor(id,f){ const m=cellM(id), a=cellA(id), j=cellJ(id);
switch(f){ case 0: return j>0?cid(m,a,j-1):-1; case 1: return j<NY-1?cid(m,a,j+1):-1;
case 2: return m>1?cid(m-1,a,j):-1; case 3: return m<M?cid(m+1,a,j):-1;
case 4: return cid(m,a-1,j); default: return cid(m,a+1,j); } }
// outward faces for (radial, angle, up) which is left-handed -> reversed windings
let FACES=[[1,2,3,0],[7,6,5,4],[3,7,4,0],[5,6,2,1],[4,5,1,0],[2,6,7,3]];
const EDGES=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7],[0,2],[4,6],[0,7],[1,6],[0,5],[3,6],[0,6],[1,7],[2,4],[3,5]];
const ALL_CELLS=[]; for(let j=0;j<NY;j++) for(let a=0;a<A;a++) for(let m=1;m<=M;m++) ALL_CELLS.push(cid(m,a,j));
const CUST=[0.93,0.72,0.36], CARA=[0.30,0.075,0.008];
let custardMat;
class Piece{
constructor(cells, pinned, src){
this.cells=cells; this.pinned=pinned; this.cellSet=new Set(cells);
const map=new Map(), gids=[]; const loc=g=>{ let l=map.get(g); if(l===undefined){ l=gids.length; map.set(g,l); gids.push(g);} return l; };
this.cellLoc=cells.map(id=>cellVerts(id).map(loc));
const n=this.n=gids.length; this.gids=gids;
this.p=new Float32Array(n*3); this.pp=new Float32Array(n*3); this.r0=new Float32Array(n*3); this.w=new Float32Array(n); this.grad=new Float32Array(n*3);
const col=new Float32Array(n*3);
for(let i=0;i<n;i++){ const g=gids[i]; const s=src||REST;
for(let k=0;k<3;k++){ this.p[i*3+k]=this.pp[i*3+k]=s[g*3+k]; this.r0[i*3+k]=REST[g*3+k]; }
this.w[i]=(pinned&&g<PER)?0:1;
const cw=CW[g]; for(let k=0;k<3;k++) col[i*3+k]=CUST[k]*(1-cw)+CARA[k]*cw; }
// constraints (edges, face diagonals, body diagonals), rest lengths from the undeformed shape
const cset=new Set(), ca=[], cb=[], cl=[];
for(const cv of this.cellLoc) for(const e of EDGES){ const a=cv[e[0]], b=cv[e[1]]; if(a===b) continue; const key=a<b?a*n+b:b*n+a; if(cset.has(key)) continue; cset.add(key);
const dx=this.r0[a*3]-this.r0[b*3], dy=this.r0[a*3+1]-this.r0[b*3+1], dz=this.r0[a*3+2]-this.r0[b*3+2]; const d=Math.sqrt(dx*dx+dy*dy+dz*dz); if(d<1e-4) continue; ca.push(a); cb.push(b); cl.push(d); }
this.ca=Uint16Array.from(ca); this.cb=Uint16Array.from(cb); this.cl=Float32Array.from(cl);
// exposed faces -> triangles
const tri=[];
cells.forEach((id,ci)=>{ const cv=this.cellLoc[ci]; for(let f=0;f<6;f++){ const nb=neighbor(id,f); if(nb>=0&&this.cellSet.has(nb)) continue; const q=FACES[f].map(k=>cv[k]);
if(q[0]!==q[1]&&q[1]!==q[2]&&q[0]!==q[2]) tri.push(q[0],q[1],q[2]); if(q[0]!==q[2]&&q[2]!==q[3]&&q[0]!==q[3]) tri.push(q[0],q[2],q[3]); } });
this.tri=Uint16Array.from(tri);
this.V0=this.volume(this.r0);
const geo=new THREE.BufferGeometry();
geo.setAttribute('position',new THREE.BufferAttribute(this.p,3).setUsage(THREE.DynamicDrawUsage));
geo.setAttribute('color',new THREE.BufferAttribute(col,3));
geo.setIndex(new THREE.BufferAttribute(this.tri,1));
geo.computeVertexNormals();
this.mesh=new THREE.Mesh(geo,custardMat); this.mesh.castShadow=true; this.mesh.receiveShadow=true; this.mesh.frustumCulled=false; this.mesh.userData.piece=this;
}
volume(p){ const t=this.tri; let V=0; for(let i=0;i<t.length;i+=3){ const a=t[i]*3,b=t[i+1]*3,c=t[i+2]*3;
V+=p[a]*(p[b+1]*p[c+2]-p[b+2]*p[c+1])+p[a+1]*(p[b+2]*p[c]-p[b]*p[c+2])+p[a+2]*(p[b]*p[c+1]-p[b+1]*p[c]); } return V/6; }
solveVolume(k){ const p=this.p, t=this.tri, g=this.grad, w=this.w; g.fill(0); let V=0;
for(let i=0;i<t.length;i+=3){ const a=t[i]*3,b=t[i+1]*3,c=t[i+2]*3;
const ax=p[a],ay=p[a+1],az=p[a+2],bx=p[b],by=p[b+1],bz=p[b+2],cx=p[c],cy=p[c+1],cz=p[c+2];
const nx=by*cz-bz*cy, ny=bz*cx-bx*cz, nz=bx*cy-by*cx; V+=ax*nx+ay*ny+az*nz;
g[a]+=nx; g[a+1]+=ny; g[a+2]+=nz;
g[b]+=cy*az-cz*ay; g[b+1]+=cz*ax-cx*az; g[b+2]+=cx*ay-cy*ax;
g[c]+=ay*bz-az*by; g[c+1]+=az*bx-ax*bz; g[c+2]+=ax*by-ay*bx; }
V/=6; const C=V-this.V0; let S=0; for(let i=0;i<this.n;i++){ if(w[i]===0) continue; const x=g[i*3],y=g[i*3+1],z=g[i*3+2]; S+=x*x+y*y+z*z; }
S/=36; if(S<1e-9) return; const lam=-C/S*k/6; for(let i=0;i<this.n;i++){ const wi=w[i]; if(wi===0) continue; p[i*3]+=lam*wi*g[i*3]; p[i*3+1]+=lam*wi*g[i*3+1]; p[i*3+2]+=lam*wi*g[i*3+2]; } }
solveDist(k){ const p=this.p,w=this.w,ca=this.ca,cb=this.cb,cl=this.cl; for(let i=0;i<ca.length;i++){ const a=ca[i],b=cb[i]; const wa=w[a],wb=w[b],ws=wa+wb; if(ws===0) continue;
const a3=a*3,b3=b*3; const dx=p[b3]-p[a3],dy=p[b3+1]-p[a3+1],dz=p[b3+2]-p[a3+2]; const d=Math.sqrt(dx*dx+dy*dy+dz*dz); if(d<1e-7) continue;
const corr=(d-cl[i])/d/ws*k; p[a3]+=wa*corr*dx; p[a3+1]+=wa*corr*dy; p[a3+2]+=wa*corr*dz; p[b3]-=wb*corr*dx; p[b3+1]-=wb*corr*dy; p[b3+2]-=wb*corr*dz; } }
cellCenter(ci,out){ const cv=this.cellLoc[ci]; out.set(0,0,0); for(const l of cv){ out.x+=this.p[l*3]; out.y+=this.p[l*3+1]; out.z+=this.p[l*3+2]; } out.multiplyScalar(1/8); return out; }
refresh(){ const geo=this.mesh.geometry; geo.attributes.position.needsUpdate=true; geo.computeVertexNormals(); geo.computeBoundingSphere(); }
}
// ---------- renderer / scene ----------
const canvas=document.getElementById('c');
const renderer=new THREE.WebGLRenderer({canvas,antialias:true,powerPreference:'high-performance'});
renderer.outputEncoding=THREE.sRGBEncoding; renderer.toneMapping=THREE.ACESFilmicToneMapping; renderer.toneMappingExposure=1.05;
renderer.shadowMap.enabled=true; renderer.shadowMap.type=THREE.PCFSoftShadowMap;
const isSmall=Math.min(innerWidth,innerHeight)<600;
let quality=0; let pr=Math.min(devicePixelRatio||1,isSmall?1.5:2); renderer.setPixelRatio(pr);
const scene=new THREE.Scene(); scene.background=new THREE.Color(0xe7ddcc); scene.fog=new THREE.Fog(0xe7ddcc,9,22);
const camera=new THREE.PerspectiveCamera(42,1,0.1,60);
const cam={target:new THREE.Vector3(0,0.3,0),radius:4.1,theta:0.55,phi:1.05};
function updateCamera(){ cam.phi=clamp(cam.phi,0.25,1.45); cam.radius=clamp(cam.radius,2.2,9);
const sp=Math.sin(cam.phi); camera.position.set(cam.target.x+cam.radius*sp*Math.sin(cam.theta),cam.target.y+cam.radius*Math.cos(cam.phi),cam.target.z+cam.radius*sp*Math.cos(cam.theta)); camera.lookAt(cam.target); }
function resize(){ const w=innerWidth,h=innerHeight; renderer.setSize(w,h,false); camera.aspect=w/h; camera.updateProjectionMatrix(); }
addEventListener('resize',resize); resize();
// environment for glossy reflections (procedural soft-box studio)
(function(){ const pm=new THREE.PMREMGenerator(renderer); const es=new THREE.Scene(); es.background=new THREE.Color(0x8a8378);
const add=(x,y,z,sx,sy,sz,c)=>{ const m=new THREE.Mesh(new THREE.BoxGeometry(sx,sy,sz),new THREE.MeshBasicMaterial({color:c})); m.position.set(x,y,z); es.add(m); };
add(0,6,0,6,0.3,6,0xffffff); add(-6,3,2,0.3,4,5,0xfff2e0); add(6,2,-3,0.3,3,4,0xdfe8ff); add(0,2,-7,6,3,0.3,0xffffff); add(0,-4,0,12,0.3,12,0x6b5a48);
scene.environment=pm.fromScene(es,0.04).texture; pm.dispose(); })();
// lights
scene.add(new THREE.HemisphereLight(0xfff4e6,0x8a7a66,0.55));
const key=new THREE.DirectionalLight(0xfff1dd,1.15); key.position.set(3,6,2.5); key.castShadow=true; key.shadow.mapSize.set(1024,1024);
key.shadow.camera.left=-4; key.shadow.camera.right=4; key.shadow.camera.top=4; key.shadow.camera.bottom=-4; key.shadow.camera.near=1; key.shadow.camera.far=16; key.shadow.bias=-0.0015; key.shadow.radius=3; scene.add(key);
const fill=new THREE.DirectionalLight(0xdde8ff,0.35); fill.position.set(-4,3,-2); scene.add(fill);
const rim=new THREE.DirectionalLight(0xffffff,0.3); rim.position.set(0,3,-5); scene.add(rim);
// tablecloth (procedural gingham texture)
(function(){ const cv=document.createElement('canvas'); cv.width=cv.height=256; const g=cv.getContext('2d');
g.fillStyle='#f7f0e3'; g.fillRect(0,0,256,256); g.fillStyle='rgba(196,74,64,0.32)';
for(let i=0;i<2;i++){ g.fillRect(i*128,0,64,256); g.fillRect(0,i*128,256,64); }
g.fillStyle='rgba(196,74,64,0.22)'; for(let i=0;i<2;i++) for(let k=0;k<2;k++) g.fillRect(i*128,k*128,64,64);
for(let i=0;i<2600;i++){ const x=rnd()*256,y=rnd()*256; g.fillStyle=rnd()<0.5?'rgba(255,255,255,0.18)':'rgba(90,50,30,0.08)'; g.fillRect(x,y,1.5,1.5); }
const tex=new THREE.CanvasTexture(cv); tex.wrapS=tex.wrapT=THREE.RepeatWrapping; tex.repeat.set(14,14); tex.encoding=THREE.sRGBEncoding; tex.anisotropy=Math.min(4,renderer.capabilities.getMaxAnisotropy());
const cloth=new THREE.Mesh(new THREE.PlaneGeometry(40,40),new THREE.MeshStandardMaterial({map:tex,roughness:0.95})); cloth.rotation.x=-Math.PI/2; cloth.position.y=-0.1; cloth.receiveShadow=true; scene.add(cloth); })();
// plate + caramel pool (move together when shaken)
const plateGroup=new THREE.Group(); scene.add(plateGroup);
(function(){ const pm=new THREE.MeshStandardMaterial({color:0xfbf8f2,roughness:0.28,metalness:0,envMapIntensity:0.7});
const base=new THREE.Mesh(new THREE.CylinderGeometry(1.9,1.65,0.1,72),pm); base.position.y=-0.05; base.receiveShadow=true; base.castShadow=true; plateGroup.add(base);
const lip=new THREE.Mesh(new THREE.TorusGeometry(1.86,0.065,14,96),pm); lip.rotation.x=Math.PI/2; lip.position.y=0.02; lip.castShadow=true; lip.receiveShadow=true; plateGroup.add(lip);
const ph=[rnd()*6,rnd()*6,rnd()*6]; const shape=new THREE.Shape(); const N=84;
for(let i=0;i<N;i++){ const t=i/N*Math.PI*2; const r=1.32+0.17*Math.sin(3*t+ph[0])+0.11*Math.sin(5*t+ph[1])+0.06*Math.sin(9*t+ph[2]); const x=r*Math.cos(t),y=r*Math.sin(t); if(i===0) shape.moveTo(x,y); else shape.lineTo(x,y); } shape.closePath();
const pool=new THREE.Mesh(new THREE.ShapeGeometry(shape,2),new THREE.MeshPhysicalMaterial({color:0x8f3f08,roughness:0.12,metalness:0,clearcoat:1,clearcoatRoughness:0.08,transparent:true,opacity:0.86,envMapIntensity:1.2}));
pool.rotation.x=-Math.PI/2; pool.position.y=0.004; pool.receiveShadow=true; plateGroup.add(pool);
const inner=new THREE.Mesh(new THREE.CircleGeometry(1.08,64),new THREE.MeshPhysicalMaterial({color:0x5a2204,roughness:0.15,clearcoat:1,transparent:true,opacity:0.8}));
inner.rotation.x=-Math.PI/2; inner.position.y=0.006; plateGroup.add(inner); })();
custardMat=new THREE.MeshPhysicalMaterial({vertexColors:true,roughness:0.36,metalness:0,clearcoat:0.6,clearcoatRoughness:0.3,envMapIntensity:0.9,transparent:true,opacity:0.965,side:THREE.DoubleSide});
// spoon
const spoon=new THREE.Group(); spoon.visible=false; scene.add(spoon);
(function(){ const mat=new THREE.MeshStandardMaterial({color:0xd9dde2,metalness:0.95,roughness:0.22,side:THREE.DoubleSide});
const bowl=new THREE.Mesh(new THREE.SphereGeometry(0.26,24,14,0,Math.PI*2,Math.PI/2,Math.PI/2),mat); bowl.scale.set(1,0.55,0.78); bowl.castShadow=true; spoon.add(bowl);
const handle=new THREE.Mesh(new THREE.CylinderGeometry(0.03,0.045,1.0,10),mat); handle.position.set(-0.58,0.22,0); handle.rotation.z=Math.PI/2-0.35; handle.castShadow=true; spoon.add(handle); })();
let spoonAnim=null;
// ---------- simulation state ----------
let pieces=[]; const pieceRoot=new THREE.Group(); scene.add(pieceRoot);
const plateOff=new THREE.Vector3(), prevPlateOff=new THREE.Vector3();
let stiff=0.2, damp=0.985, iters=8;
let grab=null, shake=null, spoonOn=false;
const sFirm=document.getElementById('sFirm'), sDamp=document.getElementById('sDamp'), countEl=document.getElementById('count');
function applySliders(){ const f=sFirm.value/100, d=sDamp.value/100; stiff=0.04+0.5*f*f; damp=1-(0.002+0.05*d); }
sFirm.addEventListener('input',applySliders); sDamp.addEventListener('input',applySliders); applySliders();
function addPiece(pc){ pieces.push(pc); pieceRoot.add(pc.mesh); }
function removePiece(pc){ pieces.splice(pieces.indexOf(pc),1); pieceRoot.remove(pc.mesh); pc.mesh.geometry.dispose(); }
function updateCount(){ countEl.textContent=pieces.length+(pieces.length===1?' piece':' pieces'); }
function resetAll(){ while(pieces.length) removePiece(pieces[0]); grab=null; shake=null; spoonAnim=null; spoon.visible=false; plateOff.set(0,0,0); prevPlateOff.set(0,0,0); plateGroup.position.set(0,0,0);
let main=new Piece(ALL_CELLS,true,null); if(main.V0<0){ FACES=FACES.map(f=>f.slice().reverse()); main=new Piece(ALL_CELLS,true,null); } addPiece(main); updateCount(); }
resetAll();
function step(dt){
const gy=-20*dt*dt; const dpx=plateOff.x-prevPlateOff.x, dpz=plateOff.z-prevPlateOff.z; const hasMain=pieces.some(p=>p.pinned);
for(const pc of pieces){ const p=pc.p,pp=pc.pp,w=pc.w,r0=pc.r0,n=pc.n;
for(let i=0;i<n;i++){ const i3=i*3; if(w[i]===0){ p[i3]=pp[i3]=r0[i3]+plateOff.x; p[i3+1]=pp[i3+1]=r0[i3+1]; p[i3+2]=pp[i3+2]=r0[i3+2]+plateOff.z; continue; }
const vx=(p[i3]-pp[i3])*damp, vy=(p[i3+1]-pp[i3+1])*damp, vz=(p[i3+2]-pp[i3+2])*damp; pp[i3]=p[i3]; pp[i3+1]=p[i3+1]; pp[i3+2]=p[i3+2];
p[i3]+=vx; p[i3+1]+=vy+gy; p[i3+2]+=vz; }
if(grab&&grab.piece===pc){ const ax=grab.anchor.x+grab.delta.x, ay=grab.anchor.y+grab.delta.y, az=grab.anchor.z+grab.delta.z;
for(const it of grab.items){ const i3=it.i*3; const s=it.wt*0.35; p[i3]+=(ax+it.ox-p[i3])*s; p[i3+1]+=(ay+it.oy-p[i3+1])*s; p[i3+2]+=(az+it.oz-p[i3+2])*s; } }
for(let k=0;k<iters;k++){ pc.solveDist(stiff); pc.solveVolume(0.8);
for(let i=0;i<n;i++){ if(w[i]===0) continue; const i3=i*3;
if(p[i3+1]<0){ p[i3+1]=0; p[i3]+=(pp[i3]-p[i3])*0.5+dpx; p[i3+2]+=(pp[i3+2]-p[i3+2])*0.5+dpz; }
const rx=p[i3]-plateOff.x, rz=p[i3+2]-plateOff.z; const rr=Math.sqrt(rx*rx+rz*rz);
if(rr>1.78){ const s=1.78/rr; p[i3]=plateOff.x+rx*s; p[i3+2]=plateOff.z+rz*s; }
if(hasMain&&!pc.pinned&&p[i3+1]<H+0.02&&rr>1e-6){ const rc=rcone(clamp(p[i3+1],0,H))+0.05; if(rr<rc){ const s=rc/rr; p[i3]=plateOff.x+rx*s; p[i3+2]=plateOff.z+rz*s; } } } }
}
}
// ---------- interactions ----------
const raycaster=new THREE.Raycaster(); const _v=new THREE.Vector3(), _v2=new THREE.Vector3(), _plane=new THREE.Plane();
function ndc(x,y){ return new THREE.Vector2(x/innerWidth*2-1,-(y/innerHeight)*2+1); }
function pick(x,y){ raycaster.setFromCamera(ndc(x,y),camera); const hits=raycaster.intersectObjects(pieces.map(p=>p.mesh)); if(!hits.length) return null; const h=hits[0];
const nrm=h.face?h.face.normal.clone():new THREE.Vector3(0,1,0); if(nrm.dot(raycaster.ray.direction)>0) nrm.negate(); return {piece:h.object.userData.piece,point:h.point.clone(),normal:nrm,dir:raycaster.ray.direction.clone()}; }
function beginGrab(hit){ const pc=hit.piece, R=0.48, items=[]; for(let i=0;i<pc.n;i++){ if(pc.w[i]===0) continue; const dx=pc.p[i*3]-hit.point.x,dy=pc.p[i*3+1]-hit.point.y,dz=pc.p[i*3+2]-hit.point.z; const d=Math.sqrt(dx*dx+dy*dy+dz*dz); if(d<R){ const t=1-d/R; items.push({i,ox:dx,oy:dy,oz:dz,wt:t*t}); } }
if(!items.length) return; camera.getWorldDirection(_v); _plane.setFromNormalAndCoplanarPoint(_v,hit.point); grab={piece:pc,anchor:hit.point.clone(),delta:new THREE.Vector3(),items,hit}; }
function updateGrab(x,y){ if(!grab) return; raycaster.setFromCamera(ndc(x,y),camera); if(raycaster.ray.intersectPlane(_plane,_v2)){ grab.delta.copy(_v2).sub(grab.anchor); if(grab.delta.length()>1.3) grab.delta.setLength(1.3); } }
function endGrab(){ if(grab){ if(grab.delta.length()>0.15) blip(150,0.7); grab=null; } }
function poke(hit){ const pc=hit.piece, R=0.4; for(let i=0;i<pc.n;i++){ if(pc.w[i]===0) continue; const dx=pc.p[i*3]-hit.point.x,dy=pc.p[i*3+1]-hit.point.y,dz=pc.p[i*3+2]-hit.point.z; const d=Math.sqrt(dx*dx+dy*dy+dz*dz); if(d<R){ const t=(1-d/R)*0.2; pc.p[i*3]+=hit.dir.x*t; pc.p[i*3+1]+=hit.dir.y*t; pc.p[i*3+2]+=hit.dir.z*t; } } blip(240,0.5); }
function components(cells){ const set=new Set(cells), seen=new Set(), out=[]; for(const id of cells){ if(seen.has(id)) continue; const comp=[], st=[id]; seen.add(id);
while(st.length){ const c=st.pop(); comp.push(c); for(let f=0;f<6;f++){ const nb=neighbor(c,f); if(nb>=0&&set.has(nb)&&!seen.has(nb)){ seen.add(nb); st.push(nb); } } } out.push(comp); } return out; }
function doScoop(hit){ const pc=hit.piece; const c=hit.point.clone().addScaledVector(hit.normal,-0.1); const R=0.36; const chunk=[], rest=[]; const cc=new THREE.Vector3(); let best=-1,bd=1e9;
pc.cells.forEach((id,ci)=>{ pc.cellCenter(ci,cc); const d=cc.distanceTo(c); if(d<bd){bd=d;best=ci;} if(d<R) chunk.push(id); else rest.push(id); });
if(!chunk.length){ chunk.push(pc.cells[best]); rest.splice(rest.indexOf(pc.cells[best]),1); }
if(!rest.length) return;
const cur=new Float32Array(REST); for(let i=0;i<pc.n;i++){ const g=pc.gids[i]; cur[g*3]=pc.p[i*3]; cur[g*3+1]=pc.p[i*3+1]; cur[g*3+2]=pc.p[i*3+2]; }
if(grab&&grab.piece===pc) grab=null; removePiece(pc);
for(const comp of components(rest)) addPiece(new Piece(comp,pc.pinned&&comp.some(id=>cellJ(id)===0),cur));
for(const comp of components(chunk)){ const np=new Piece(comp,false,cur); let ox=c.x-plateOff.x, oz=c.z-plateOff.z; let l=Math.hypot(ox,oz); if(l<1e-3){ ox=1; oz=0; l=1; } ox/=l; oz/=l;
const vx=ox*2.3, vy=2.6, vz=oz*2.3, dt=1/120; for(let i=0;i<np.n;i++){ np.pp[i*3]=np.p[i*3]-vx*dt; np.pp[i*3+1]=np.p[i*3+1]-vy*dt; np.pp[i*3+2]=np.p[i*3+2]-vz*dt; } addPiece(np);
spoonAnim={t:0,from:c.clone().add(new THREE.Vector3(ox*0.3,1.1,oz*0.3)),mid:c.clone().add(new THREE.Vector3(0,0.05,0)),to:c.clone().add(new THREE.Vector3(ox*1.3,0.9,oz*1.3)),ang:Math.atan2(oz,ox)}; }
updateCount(); blip(330,0.35,'triangle'); }
function doShake(){ shake={t:0}; blip(85,0.9); }
function setSpoon(on){ spoonOn=on; const b=document.getElementById('bSpoon'); b.classList.toggle('on',on); b.setAttribute('aria-pressed',on?'true':'false'); }
const ptrs=new Map(); let mode=null, downInfo=null, pinchD=0;
function pdist(){ const a=[...ptrs.values()]; return Math.hypot(a[0].x-a[1].x,a[0].y-a[1].y); }
function onDown(x,y,id){ ensureAudio(); ptrs.set(id,{x,y});
if(ptrs.size===2){ endGrab(); mode='pinch'; pinchD=pdist(); return; } if(ptrs.size>2) return;
const hit=pick(x,y);
if(hit){ if(spoonOn){ doScoop(hit); mode=null; return; } beginGrab(hit); mode='grab'; downInfo={x,y,t:performance.now(),moved:false,hit}; }
else { mode='orbit'; downInfo={x,y}; } }
function onMove(x,y,id){ const p=ptrs.get(id); if(!p) return; const dx=x-p.x, dy=y-p.y; p.x=x; p.y=y;
if(mode==='pinch'&&ptrs.size===2){ const d=pdist(); if(d>1){ cam.radius*=pinchD/d; pinchD=d; } return; }
if(mode==='orbit'){ cam.theta-=dx*0.006; cam.phi-=dy*0.006; }
else if(mode==='grab'){ if(downInfo&&Math.hypot(x-downInfo.x,y-downInfo.y)>8) downInfo.moved=true; updateGrab(x,y); } }
function onUp(id){ if(!ptrs.has(id)) return; ptrs.delete(id);
if(mode==='grab'){ if(downInfo&&!downInfo.moved&&performance.now()-downInfo.t<350) poke(downInfo.hit); endGrab(); }
if(ptrs.size===0) mode=null; else if(ptrs.size===1&&mode==='pinch') mode=null; }
canvas.addEventListener('pointerdown',e=>{ stopDemo(); try{canvas.setPointerCapture(e.pointerId);}catch(err){} onDown(e.clientX,e.clientY,e.pointerId); });
canvas.addEventListener('pointermove',e=>{ onMove(e.clientX,e.clientY,e.pointerId); });
canvas.addEventListener('pointerup',e=>onUp(e.pointerId)); canvas.addEventListener('pointercancel',e=>onUp(e.pointerId));
canvas.addEventListener('wheel',e=>{ e.preventDefault(); stopDemo(); cam.radius*=Math.exp(e.deltaY*0.0012); },{passive:false});
addEventListener('keydown',e=>{ stopDemo(); const k=e.key.toLowerCase(); if(k==='s') setSpoon(!spoonOn); else if(k==='k') doShake(); else if(k==='r') resetAll(); else if(k==='m') toggleMute(); else if(k==='+'||k==='=') cam.radius*=0.9; else if(k==='-') cam.radius*=1.1; });
document.getElementById('bSpoon').addEventListener('click',()=>{ stopDemo(); ensureAudio(); setSpoon(!spoonOn); });
document.getElementById('bShake').addEventListener('click',()=>{ stopDemo(); ensureAudio(); doShake(); });
document.getElementById('bReset').addEventListener('click',()=>{ stopDemo(); ensureAudio(); resetAll(); });
document.getElementById('bMute').addEventListener('click',()=>{ stopDemo(); ensureAudio(); toggleMute(); });
document.getElementById('bDemo').addEventListener('click',()=>{ if(demo) stopDemo(); else startDemo(); });
// ---------- sound (synthesized, starts only after a user gesture) ----------
let actx=null, master=null, muted=false;
function ensureAudio(){ if(actx) return; try{ const AC=window.AudioContext||window.webkitAudioContext; if(!AC) return; actx=new AC(); master=actx.createGain(); master.gain.value=muted?0:0.45; master.connect(actx.destination); }catch(e){ actx=null; } }
function blip(f0,dur,type){ if(!actx||muted) return; try{ if(actx.state==='suspended') actx.resume(); const t=actx.currentTime; const o=actx.createOscillator(), g=actx.createGain(), l=actx.createOscillator(), lg=actx.createGain();
l.frequency.value=6.5; lg.gain.value=f0*0.3; l.connect(lg); lg.connect(o.frequency); o.type=type||'sine';
o.frequency.setValueAtTime(f0,t); o.frequency.exponentialRampToValueAtTime(f0*0.55,t+dur);
g.gain.setValueAtTime(0.0001,t); g.gain.exponentialRampToValueAtTime(0.6,t+0.02); g.gain.exponentialRampToValueAtTime(0.0001,t+dur);
o.connect(g); g.connect(master); o.start(t); l.start(t); o.stop(t+dur+0.05); l.stop(t+dur+0.05); }catch(e){} }
function toggleMute(){ muted=!muted; if(master) master.gain.value=muted?0:0.45; const b=document.getElementById('bMute'); b.textContent=muted?'Sound: off':'Sound: on'; b.setAttribute('aria-pressed',muted?'true':'false'); }
// ---------- demo mode ----------
let demo=null; const fake=document.getElementById('fake'), demoTag=document.getElementById('demoTag');
function proj(x,y,z){ _v.set(x,y,z).project(camera); return {x:(_v.x+1)/2*innerWidth,y:(1-_v.y)/2*innerHeight}; }
function btnPos(id){ const r=document.getElementById(id).getBoundingClientRect(); return {x:r.left+r.width/2,y:r.top+r.height/2}; }
function dmove(target,dur){ demo.from={x:demo.pos.x,y:demo.pos.y}; demo.to=target; demo.t0m=demo.now; demo.dur=dur; }
function dpress(){ fake.classList.add('down'); } function drelease(){ fake.classList.remove('down'); }
function dclick(id,fn){ dpress(); setTimeout(()=>{ if(demo){ drelease(); fn(); } },140); }
const DEMO=[
[0.0,()=>{ demo.spin=0.55; }],
[2.4,()=>{ demo.spin=0; dmove(proj(0.55,0.62,0.35),0.6); }],
[3.1,()=>{ dpress(); onDown(demo.pos.x,demo.pos.y,'demo'); demo.grabbing=true; dmove({x:demo.pos.x+130,y:demo.pos.y-70},0.8); }],
[4.0,()=>{ dmove({x:demo.pos.x-110,y:demo.pos.y+60},0.7); }],
[4.8,()=>{ demo.grabbing=false; onUp('demo'); drelease(); }],
[5.5,()=>{ dmove(proj(-0.15,H,0.12),0.6); }],
[6.2,()=>{ dpress(); onDown(demo.pos.x,demo.pos.y,'demo'); }],
[6.35,()=>{ onUp('demo'); drelease(); }],
[7.0,()=>{ dmove(btnPos('bSpoon'),0.7); }],
[7.8,()=>{ dclick('bSpoon',()=>setSpoon(true)); }],
[8.3,()=>{ dmove(proj(0.45,0.68,-0.42),0.7); }],
[9.1,()=>{ dpress(); onDown(demo.pos.x,demo.pos.y,'demo'); }],
[9.25,()=>{ onUp('demo'); drelease(); }],
[9.9,()=>{ dmove(proj(-0.5,0.55,0.35),0.6); }],
[10.6,()=>{ dpress(); onDown(demo.pos.x,demo.pos.y,'demo'); }],
[10.75,()=>{ onUp('demo'); drelease(); }],
[11.3,()=>{ dmove(btnPos('bSpoon'),0.6); }],
[12.0,()=>{ dclick('bSpoon',()=>setSpoon(false)); }],
[12.4,()=>{ dmove(btnPos('bShake'),0.6); }],
[13.1,()=>{ dclick('bShake',doShake); }],
[14.0,()=>{ demo.spin=0.6; demo.zoom=-0.25; dmove({x:innerWidth*0.5,y:innerHeight*0.45},0.8); }],
[16.8,()=>{ demo.spin=0; demo.zoom=0; dmove(btnPos('bReset'),0.7); }],
[17.6,()=>{ dclick('bReset',resetAll); }],
[18.3,()=>{ demo.spin=-0.5; demo.zoom=0.25; dmove({x:innerWidth*0.5,y:innerHeight*0.4},0.6); }],
[20.3,()=>{ demo.spin=0; demo.zoom=0; startDemo(); }]
];
function startDemo(){ onUp('demo'); demo={start:performance.now(),now:0,step:0,pos:{x:innerWidth/2,y:innerHeight/2},from:null,to:null,spin:0,zoom:0,grabbing:false};
fake.style.display='block'; demoTag.style.display='block'; document.getElementById('bDemo').classList.add('on'); }
function stopDemo(){ if(!demo) return; demo=null; drelease(); fake.style.display='none'; demoTag.style.display='none'; document.getElementById('bDemo').classList.remove('on'); onUp('demo'); }
function updateDemo(dt){ if(!demo) return; demo.now=(performance.now()-demo.start)/1000;
while(demo&&demo.step<DEMO.length&&DEMO[demo.step][0]<=demo.now){ const fn=DEMO[demo.step][1]; demo.step++; fn(); } if(!demo) return;
if(demo.to){ const t=clamp((demo.now-demo.t0m)/demo.dur,0,1), e=t*t*(3-2*t); demo.pos.x=demo.from.x+(demo.to.x-demo.from.x)*e; demo.pos.y=demo.from.y+(demo.to.y-demo.from.y)*e; }
fake.style.left=demo.pos.x+'px'; fake.style.top=demo.pos.y+'px';
if(demo.grabbing) onMove(demo.pos.x,demo.pos.y,'demo');
cam.theta+=demo.spin*dt; cam.radius*=Math.exp(demo.zoom*dt*0.3); }
if(location.hash==='#demo') startDemo();
addEventListener('hashchange',()=>{ if(location.hash==='#demo') startDemo(); });
// ---------- main loop with adaptive quality ----------
let last=performance.now(), acc=0, readySent=false, fpsFrames=0, fpsTime=0, warm=0;
function lowerQuality(){ quality++; if(quality===1){ pr=1; renderer.setPixelRatio(1); key.shadow.mapSize.set(512,512); key.shadow.map&&key.shadow.map.dispose(); key.shadow.map=null; iters=6; }
else if(quality===2){ renderer.shadowMap.enabled=false; iters=5; custardMat.clearcoat=0; custardMat.needsUpdate=true; } }
function animate(now){ requestAnimationFrame(animate); let dt=(now-last)/1000; last=now; if(dt>0.05) dt=0.05; if(dt<0) dt=0;
updateDemo(dt);
// plate shake
prevPlateOff.copy(plateOff);
if(shake){ shake.t+=dt; const t=shake.t, env=Math.exp(-t*2.3); plateOff.set(0.2*Math.sin(t*23)*env,0,0.09*Math.sin(t*17+1)*env); if(t>2.2){ shake=null; plateOff.set(0,0,0); } }
plateGroup.position.copy(plateOff);
// physics substeps
acc+=dt; const sub=1/120; let n=0; while(acc>=sub&&n<6){ step(sub); acc-=sub; n++; if(n===1) prevPlateOff.copy(plateOff); } if(acc>sub*2) acc=0;
for(const pc of pieces) pc.refresh();
// spoon animation
if(spoonAnim){ spoonAnim.t+=dt; const t=spoonAnim.t; spoon.visible=true; let p;
if(t<0.25){ const u=t/0.25; p=spoonAnim.from.clone().lerp(spoonAnim.mid,u*u); } else { const u=clamp((t-0.25)/0.55,0,1); p=spoonAnim.mid.clone().lerp(spoonAnim.to,u*(2-u)); }
spoon.position.copy(p); spoon.rotation.set(0,-spoonAnim.ang,t<0.25?-0.5:0.35*(t-0.25)); if(t>0.8){ spoonAnim=null; spoon.visible=false; } }
updateCamera(); renderer.render(scene,camera);
if(!readySent){ readySent=true; try{ parent.postMessage({vcb:'ready'},'*'); }catch(e){} }
// fps monitor
warm+=dt; fpsFrames++; fpsTime+=dt; if(fpsTime>=2){ const fps=fpsFrames/fpsTime; fpsFrames=0; fpsTime=0; if(warm>3&&fps<30&&quality<2) lowerQuality(); }
}
requestAnimationFrame(animate);
})();
</script>
</body>
</html>
