Skip to content
VibeCodeBench
Back to the app

The code

Jelly Orange Slice by Claude Opus 5.5

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)26.8 KB · 392 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.module.js, cdn.jsdelivr.net/npm/[email protected]/examples/jsm/
Download
<!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,viewport-fit=cover">
<title>Jelly Orange Slice</title>
<style>
html,body{margin:0;height:100%;overflow:hidden;background:#dfe6ee;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}
canvas{display:block;touch-action:none}
#top{position:fixed;left:16px;right:16px;top:max(12px,env(safe-area-inset-top));color:#4a3420;pointer-events:none}
#top b{display:block;font-size:20px;letter-spacing:.3px}
#hint{font-size:14px;opacity:.8;transition:opacity .8s}
#badge{position:fixed;right:16px;top:max(12px,env(safe-area-inset-top));background:#ff7a00;color:#fff;font:700 13px/1 inherit;padding:9px 12px;border-radius:12px;display:none;pointer-events:none;box-shadow:0 4px 14px rgba(255,120,0,.35)}
#ui{position:fixed;left:50%;bottom:max(14px,env(safe-area-inset-bottom));transform:translateX(-50%);display:flex;gap:12px;align-items:center;flex-wrap:wrap;justify-content:center;background:rgba(255,255,255,.8);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);padding:10px 14px;border-radius:22px;box-shadow:0 8px 30px rgba(40,60,90,.18);width:min(580px,calc(100% - 32px));box-sizing:border-box}
button{font:700 17px/1 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;min-height:54px;min-width:110px;padding:0 20px;border-radius:16px;border:0;cursor:pointer;touch-action:manipulation}
#sq{background:linear-gradient(#ffb43a,#ff7600);color:#fff;box-shadow:0 4px 14px rgba(255,118,0,.35)}
#sq:active{transform:scale(.96)}
#rs{background:#eef1f5;color:#333;box-shadow:inset 0 0 0 1px #d6dce4}
#rs:active{transform:scale(.96)}
#fl{display:flex;flex-direction:column;gap:2px;flex:1 1 170px;font-size:14px;color:#555}
#fl b{color:#e46a00}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:40px;background:transparent;margin:0;touch-action:none}
input[type=range]::-webkit-slider-runnable-track{height:10px;border-radius:6px;background:linear-gradient(90deg,#ffd9a0,#ff8a12)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:34px;height:34px;margin-top:-12px;border-radius:50%;background:#fff;border:3px solid #ff7a00;box-shadow:0 2px 8px rgba(0,0,0,.2)}
input[type=range]::-moz-range-track{height:10px;border-radius:6px;background:linear-gradient(90deg,#ffd9a0,#ff8a12)}
input[type=range]::-moz-range-thumb{width:30px;height:30px;border-radius:50%;background:#fff;border:3px solid #ff7a00}
</style>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/"}}</script>
</head>
<body>
<div id="top"><b>Jelly Orange Slice</b><span id="hint">Tap to poke &middot; drag the jelly to stretch &middot; drag the background to turn</span></div>
<div id="badge">DEMO &middot; touch to take over</div>
<div id="ui">
<button id="sq">Squeeze</button>
<label id="fl"><span>Firmness <b id="fv">45</b></span><input id="firm" type="range" min="0" max="100" value="45"></label>
<button id="rs">Reset</button>
</div>
<script type="module">
import * as THREE from 'three';
import {RoomEnvironment} from 'three/addons/environments/RoomEnvironment.js';

const $=id=>document.getElementById(id);
const R=1,H=0.42,HS=0.22,BV=0.15,PAD=0.03,YB=0.006,ROT=Math.PI-0.5,ZC=4*R/(3*Math.PI);
const G=7,SUB=12,MU=0.7,PI=Math.PI;
const ease=t=>t<=0?0:t>=1?1:t*t*(3-2*t);
const plateH=r=>r<1.55?0:r<2.08?0.13*((r-1.55)/0.53)**2:0.13;

/* ---------- renderer & scene ---------- */
const renderer=new THREE.WebGLRenderer({antialias:true});
renderer.setPixelRatio(Math.min(devicePixelRatio||1,2));
renderer.setSize(innerWidth,innerHeight);
renderer.setClearColor(0xdfe6ee);
renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.05;
renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
const cv=renderer.domElement;
const scene=new THREE.Scene();
const pm=new THREE.PMREMGenerator(renderer);
scene.environment=pm.fromScene(new RoomEnvironment(),0.04).texture;
function cnv(w,h){const c=document.createElement('canvas');c.width=w;c.height=h;return c}
function tx(c,srgb){const t=new THREE.CanvasTexture(c);if(srgb)t.colorSpace=THREE.SRGBColorSpace;t.anisotropy=8;return t}
{const c=cnv(4,256),g=c.getContext('2d'),gr=g.createLinearGradient(0,0,0,256);gr.addColorStop(0,'#f6f1ea');gr.addColorStop(1,'#c9d5e0');g.fillStyle=gr;g.fillRect(0,0,4,256);scene.background=tx(c,true);}
scene.fog=new THREE.Fog(0xcdd8e2,9,20);
const camera=new THREE.PerspectiveCamera(38,innerWidth/innerHeight,0.05,60);
const tgt=new THREE.Vector3(0,-0.12,0);let az=0,el=0.66,dist=5.2;
function camUpdate(){camera.position.set(tgt.x+dist*Math.sin(az)*Math.cos(el),tgt.y+dist*Math.sin(el),tgt.z+dist*Math.cos(az)*Math.cos(el));camera.lookAt(tgt)}

scene.add(new THREE.HemisphereLight(0xfff6ea,0x8796a6,0.55));
const key=new THREE.DirectionalLight(0xfff0dc,2.4);key.position.set(-2.5,5,2.8);key.castShadow=true;
key.shadow.mapSize.set(1024,1024);Object.assign(key.shadow.camera,{left:-3,right:3,top:3,bottom:-3,near:0.5,far:15});
key.shadow.bias=-0.0006;key.shadow.normalBias=0.02;key.shadow.radius=4;scene.add(key);
const back=new THREE.DirectionalLight(0xffcf90,2.3);back.position.set(1.6,1.5,-4);scene.add(back);
const rim=new THREE.PointLight(0xffe2b8,6,8,1.5);rim.position.set(-1.8,0.8,-1.6);scene.add(rim);

const table=new THREE.Mesh(new THREE.CircleGeometry(16,72),new THREE.MeshStandardMaterial({color:0xc6d2de,roughness:0.95}));
table.rotation.x=-PI/2;table.position.y=-0.076;table.receiveShadow=true;scene.add(table);
const prof=[[0,0],[1.55,0],[1.75,0.018],[1.95,0.075],[2.08,0.13],[2.14,0.128],[2.13,0.1],[1.92,0.04],[1.45,-0.04],[1.32,-0.074],[0,-0.074]].map(p=>new THREE.Vector2(p[0],p[1]));
const plate=new THREE.Mesh(new THREE.LatheGeometry(prof,112),new THREE.MeshPhysicalMaterial({color:0xffffff,roughness:0.2,clearcoat:1,clearcoatRoughness:0.08,side:THREE.DoubleSide}));
plate.receiveShadow=true;scene.add(plate);

/* ---------- procedural citrus textures ---------- */
function rng(s){return()=>(s=s*16807%2147483647)/2147483647}
// 0 color, 1 transmission, 2 bump, 3 glow
const PAL=[
{peel:'#ff7d08',pore:'rgba(196,66,0,.42)',pith:'#fff1d6',mem:'#ffe5bd',segIn:'#ffbe50',segOut:'#ff8812',cell:'rgba(255,208,118,.55)',cellE:'rgba(212,90,0,.42)',hi:'rgba(255,255,238,.72)',core:'#fff0d2'},
{peel:'#161616',pore:'#161616',pith:'#3a3a3a',mem:'#7a7a7a',segIn:'#ffffff',segOut:'#e6e6e6',cell:'rgba(255,255,255,.3)',cellE:'rgba(140,140,140,.45)',hi:'rgba(255,255,255,.4)',core:'#4a4a4a'},
{peel:'#7a7a7a',pore:'rgba(20,20,20,.6)',pith:'#888',mem:'#b4b4b4',segIn:'#8c8c8c',segOut:'#868686',cell:'rgba(235,235,235,.55)',cellE:'rgba(50,50,50,.5)',hi:'rgba(255,255,255,.5)',core:'#909090'},
{peel:'#000',pore:'#000',pith:'#181818',mem:'#2c2c2c',segIn:'#ffffff',segOut:'#7a7a7a',cell:'rgba(255,255,255,.35)',cellE:'rgba(0,0,0,.3)',hi:'rgba(255,255,255,.6)',core:'#202020'}];
function cell(g,p,x,y,a,L,w){g.save();g.translate(x,y);g.rotate(a);g.beginPath();g.ellipse(0,0,L,w,0,0,7);g.fillStyle=p.cell;g.fill();g.lineWidth=1.3;g.strokeStyle=p.cellE;g.stroke();
 g.beginPath();g.ellipse(-L*0.2,-w*0.35,L*0.4,w*0.28,0,0,7);g.fillStyle=p.hi;g.fill();g.restore()}
function drawTop(m){
 const p=PAL[m],W=1024,S=512,c=cnv(W,S),g=c.getContext('2d'),rnd=rng(11),cx=W/2,cy=S;
 const half=(r0,r1)=>{g.beginPath();g.arc(cx,cy,r1*S,PI,2*PI);g.arc(cx,cy,r0*S,2*PI,PI,true);g.closePath()};
 g.fillStyle=p.peel;g.fillRect(0,0,W,S);
 if(m==0){const gr=g.createRadialGradient(cx,cy,0.9*S,cx,cy,S);gr.addColorStop(0,'#ffa82e');gr.addColorStop(1,'#ff6e00');half(0.9,1.02);g.fillStyle=gr;g.fill()}
 for(let i=0;i<1100;i++){const a=PI+rnd()*PI,r=(0.93+rnd()*0.07)*S,s=0.8+rnd()*1.6;g.fillStyle=p.pore;g.beginPath();g.arc(cx+Math.cos(a)*r,cy+Math.sin(a)*r,s,0,7);g.fill()}
 half(0,0.927);g.fillStyle=p.pith;g.fill();
 half(0,0.862);g.fillStyle=p.mem;g.fill();
 for(let s=0;s<6;s++){
  const a0=PI+s*PI/6,a1=a0+PI/6;
  const seg=()=>{g.beginPath();g.arc(cx,cy,0.846*S,a0+0.014,a1-0.014);g.arc(cx,cy,0.125*S,a1-0.075,a0+0.075,true);g.closePath()};
  seg();const gr=g.createRadialGradient(cx,cy,0.1*S,cx,cy,0.85*S);gr.addColorStop(0,p.segIn);gr.addColorStop(1,p.segOut);g.fillStyle=gr;g.fill();
  g.save();seg();g.clip();
  for(let k=0;k<180;k++){const r=0.13+rnd()*0.72,a=a0+0.015+rnd()*(PI/6-0.03),L=(0.02+rnd()*0.028)*S*(0.55+r*0.7),w=L*(0.2+rnd()*0.14);
   cell(g,p,cx+Math.cos(a)*r*S,cy+Math.sin(a)*r*S,a,L,w)}
  g.restore();seg();g.lineJoin='round';g.lineWidth=5;g.strokeStyle=p.mem;g.stroke();
 }
 g.beginPath();g.arc(cx,cy,0.125*S,PI,2*PI);g.closePath();g.fillStyle=p.core;g.fill();
 return c}
function drawCut(m){
 const p=PAL[m],W=1024,S=128,c=cnv(W,S),g=c.getContext('2d'),rnd=rng(23),X=x=>(x+1)/2*W;
 g.fillStyle=p.peel;g.fillRect(0,0,W,S);
 g.fillStyle=p.pith;g.fillRect(X(-0.927),0,X(0.927)-X(-0.927),S);
 const gr=g.createLinearGradient(X(-0.86),0,X(0.86),0);gr.addColorStop(0,p.segOut);gr.addColorStop(0.5,p.segIn);gr.addColorStop(1,p.segOut);
 g.fillStyle=gr;g.fillRect(X(-0.86),0,X(0.86)-X(-0.86),S);
 g.save();g.beginPath();g.rect(X(-0.86),0,X(0.86)-X(-0.86),S);g.clip();
 for(let k=0;k<520;k++){const x=X(-0.86+rnd()*1.72),y=rnd()*S,L=10+rnd()*14,w=L*(0.25+rnd()*0.15),a=(rnd()-0.5)*0.5;cell(g,p,x,y,a,L,w)}
 g.restore();
 g.fillStyle=p.core;g.fillRect(X(-0.12),0,X(0.12)-X(-0.12),S);
 if(m==0){g.fillStyle='rgba(255,244,222,.14)';g.fillRect(0,0,W,S)}
 return c}
function drawPeel(m){
 const W=1024,S=128,c=cnv(W,S),g=c.getContext('2d'),rnd=rng(5);
 if(m==0){const gr=g.createLinearGradient(0,0,0,S);gr.addColorStop(0,'#ffa52a');gr.addColorStop(0.5,'#ff8a10');gr.addColorStop(1,'#e66200');g.fillStyle=gr}else g.fillStyle='#808080';
 g.fillRect(0,0,W,S);
 for(let i=0;i<2600;i++){const x=rnd()*W,y=rnd()*S,r=0.7+rnd()*1.5,q=rnd();
  g.fillStyle=m==0?(q<0.5?'rgba(190,66,0,.35)':'rgba(255,196,96,.35)'):(q<0.5?'rgba(25,25,25,.6)':'rgba(150,150,150,.4)');
  g.beginPath();g.ellipse(x,y,r*0.6,r,0,0,7);g.fill()}
 return c}
const tTop=[0,1,2,3].map(m=>tx(drawTop(m),m==0||m==3)),tCut=[0,1,2,3].map(m=>tx(drawCut(m),m==0||m==3)),tPeel=[0,2].map(m=>tx(drawPeel(m),m==0));
const flesh=t=>new THREE.MeshPhysicalMaterial({map:t[0],transmission:1,transmissionMap:t[1],thickness:0.6,ior:1.4,attenuationColor:new THREE.Color(0xff8a1c),attenuationDistance:0.55,
 roughness:0.06,clearcoat:1,clearcoatRoughness:0.04,bumpMap:t[2],bumpScale:1.5,emissive:new THREE.Color(0xff7a10),emissiveMap:t[3],emissiveIntensity:0.38,vertexColors:true,specularIntensity:1});
const peelMat=new THREE.MeshPhysicalMaterial({map:tPeel[0],bumpMap:tPeel[1],bumpScale:2,roughness:0.22,clearcoat:1,clearcoatRoughness:0.1,transmission:0.18,thickness:0.3,
 attenuationColor:new THREE.Color(0xff6a00),attenuationDistance:0.4,emissive:new THREE.Color(0xff5a00),emissiveIntensity:0.08,vertexColors:true});

/* ---------- slice surface mesh (local frame: straight cut on z=0, arc toward +z) ---------- */
const NR=34,NA=112,NW=6,RR=[],TH=[];
for(let i=0;i<=NR;i++)RR.push(R*(1-Math.pow(1-i/NR,1.7)));
for(let j=0;j<=NA;j++){const t=j/NA;TH.push(PI*(t-0.8*Math.sin(2*PI*t)/(2*PI)))}
const topY=(r,t)=>{const d=Math.max(0,Math.min(R-r,r*Math.sin(t))),e=Math.min(d/BV,1);return HS+(H-HS)*Math.sqrt(1-(1-e)*(1-e))};
const pos=[],uvs=[],iTop=[],iArc=[],iCut=[];
const addV=(x,y,z,u,v)=>{pos.push(x,y,z);uvs.push(u,v);return pos.length/3-1};
const quad=(L,a,b,c,d)=>L.push(a,d,c,a,c,b),quadR=(L,a,b,c,d)=>L.push(a,b,c,a,c,d);
{
 const T=[],B=[];
 for(let i=0;i<=NR;i++){T.push([]);B.push([]);for(let j=0;j<=NA;j++){const r=RR[i],t=TH[j],x=r*Math.cos(t),z=r*Math.sin(t);
  T[i].push(addV(x,topY(r,t),z,(x+1)/2,z));B[i].push(addV(x,YB,z,(x+1)/2,z))}}
 for(let i=0;i<NR;i++)for(let j=0;j<NA;j++){quad(iTop,T[i][j],T[i+1][j],T[i+1][j+1],T[i][j+1]);quadR(iTop,B[i][j],B[i+1][j],B[i+1][j+1],B[i][j+1])}
}
const arcCols=[],cutCols=[];
for(let j=0;j<=NA;j++){const t=TH[j],col=[];for(let k=0;k<=NW;k++)col.push(addV(Math.cos(t)*R,YB+(HS-YB)*k/NW,Math.sin(t)*R,t/PI,k/NW));arcCols.push(col)}
for(let j=0;j<NA;j++)for(let k=0;k<NW;k++)quad(iArc,arcCols[j][k],arcCols[j+1][k],arcCols[j+1][k+1],arcCols[j][k+1]);
{
 const XS=[];for(let i=NR;i>0;i--)XS.push(-RR[i]);for(let i=0;i<=NR;i++)XS.push(RR[i]);
 const C=XS.map(x=>{const col=[];for(let k=0;k<=NW;k++)col.push(addV(x,YB+(HS-YB)*k/NW,0,(x+1)/2,k/NW));if(Math.abs(x)>0.16&&Math.abs(x)<0.8)cutCols.push(col);return col});
 for(let m=0;m<XS.length-1;m++)for(let k=0;k<NW;k++)quad(iCut,C[m][k],C[m+1][k],C[m+1][k+1],C[m][k+1]);
}
const NV=pos.length/3,LOC=new Float32Array(pos);
const geo=new THREE.BufferGeometry();
const pa=new Float32Array(NV*3),ca=new Float32Array(NV*3).fill(1);
geo.setAttribute('position',new THREE.BufferAttribute(pa,3));
geo.setAttribute('uv',new THREE.Float32BufferAttribute(uvs,2));
geo.setAttribute('color',new THREE.BufferAttribute(ca,3));
geo.setIndex(iTop.concat(iArc,iCut));
geo.addGroup(0,iTop.length,0);geo.addGroup(iTop.length,iArc.length,1);geo.addGroup(iTop.length+iArc.length,iCut.length,2);
const jelly=new THREE.Mesh(geo,[flesh(tTop),peelMat,flesh(tCut)]);
jelly.castShadow=true;jelly.frustumCulled=false;scene.add(jelly);

/* ---------- soft body: particle lattice + XPBD distance constraints + shape matching ---------- */
const NX=9,NY=3,NZ=5,X0=-R-PAD,DX=(2*R+2*PAD)/(NX-1),Z0=-PAD,DZ=(R+2*PAD)/(NZ-1),DY=H/(NY-1);
const gid=(i,j,k)=>i+NX*(j+NY*k);
const PID=new Int32Array(NX*NY*NZ).fill(-1),LP=[],cells=[];
const cellOK=(i,k)=>{const xl=X0+i*DX,xh=xl+DX,zl=Z0+k*DZ,zh=zl+DZ;return Math.hypot(Math.max(xl,Math.min(0,xh)),Math.max(zl,Math.min(0,zh)))<=R+PAD+1e-6};
for(let k=0;k<NZ-1;k++)for(let i=0;i<NX-1;i++)if(cellOK(i,k))for(let j=0;j<NY-1;j++){
 const cn=[];for(let c=0;c<8;c++){const ii=i+(c&1),jj=j+((c>>1)&1),kk=k+((c>>2)&1),g=gid(ii,jj,kk);
  if(PID[g]<0){PID[g]=LP.length/3;LP.push(X0+ii*DX,jj*DY,Z0+kk*DZ)}cn.push(PID[g])}cells.push(cn)}
const NP=LP.length/3,N3=NP*3;
const cR=Math.cos(ROT),sR=Math.sin(ROT);
const P=new Float32Array(N3),O=new Float32Array(N3),Vv=new Float32Array(N3),RS=new Float32Array(N3),Q0=new Float32Array(N3);
for(let p=0;p<NP;p++){const x=LP[p*3],y=LP[p*3+1],z=LP[p*3+2]-ZC;RS[p*3]=x*cR+z*sR;RS[p*3+1]=y;RS[p*3+2]=-x*sR+z*cR}
{let cx=0,cy=0,cz=0;for(let p=0;p<N3;p+=3){cx+=RS[p];cy+=RS[p+1];cz+=RS[p+2]}cx/=NP;cy/=NP;cz/=NP;
 for(let p=0;p<N3;p+=3){Q0[p]=RS[p]-cx;Q0[p+1]=RS[p+1]-cy;Q0[p+2]=RS[p+2]-cz}}
const seen=new Set(),CIa=[],CLa=[];
for(const cn of cells)for(let a=0;a<8;a++)for(let b=a+1;b<8;b++){const i=Math.min(cn[a],cn[b]),j=Math.max(cn[a],cn[b]),kk=i*NP+j;if(seen.has(kk))continue;seen.add(kk);
 CIa.push(i*3,j*3);CLa.push(Math.hypot(RS[i*3]-RS[j*3],RS[i*3+1]-RS[j*3+1],RS[i*3+2]-RS[j*3+2]))}
const CI=new Int32Array(CIa),CL=new Float32Array(CLa),NC=CL.length;
const CNT=new Float32Array(NP),ST=new Float32Array(NP);for(let c=0;c<NC;c++){CNT[CI[c*2]/3]++;CNT[CI[c*2+1]/3]++}
// embed surface vertices in the lattice (trilinear)
const FI=new Int32Array(NV*8),FW=new Float32Array(NV*8);
for(let v=0;v<NV;v++){
 const gx=(LOC[v*3]-X0)/DX,gy=LOC[v*3+1]/DY,gz=(LOC[v*3+2]-Z0)/DZ;
 const i=Math.max(0,Math.min(NX-2,Math.floor(gx))),j=Math.max(0,Math.min(NY-2,Math.floor(gy))),k=Math.max(0,Math.min(NZ-2,Math.floor(gz)));
 const fx=gx-i,fy=gy-j,fz=gz-k;let sum=0;
 for(let c=0;c<8;c++){const a=c&1,b=(c>>1)&1,d=(c>>2)&1;let w=(a?fx:1-fx)*(b?fy:1-fy)*(d?fz:1-fz),p=PID[gid(i+a,j+b,k+d)];if(p<0){w=0;p=0}FI[v*8+c]=p;FW[v*8+c]=w;sum+=w}
 if(Math.abs(sum)>1e-6)for(let c=0;c<8;c++)FW[v*8+c]/=sum;
}

let compl=1e-3,kShape=600,dampC=2;
const qR=new THREE.Quaternion(),qT=new THREE.Quaternion(),m4=new THREE.Matrix4(),axv=new THREE.Vector3();
function shapeMatch(k){
 let cx=0,cy=0,cz=0;for(let p=0;p<N3;p+=3){cx+=P[p];cy+=P[p+1];cz+=P[p+2]}cx/=NP;cy/=NP;cz/=NP;
 let a00=0,a10=0,a20=0,a01=0,a11=0,a21=0,a02=0,a12=0,a22=0;
 for(let p=0;p<N3;p+=3){const dx=P[p]-cx,dy=P[p+1]-cy,dz=P[p+2]-cz,qx=Q0[p],qy=Q0[p+1],qz=Q0[p+2];
  a00+=dx*qx;a10+=dy*qx;a20+=dz*qx;a01+=dx*qy;a11+=dy*qy;a21+=dz*qy;a02+=dx*qz;a12+=dy*qz;a22+=dz*qz}
 let e;
 for(let it=0;it<3;it++){m4.makeRotationFromQuaternion(qR);e=m4.elements;
  let ox=e[1]*a20-e[2]*a10+e[5]*a21-e[6]*a11+e[9]*a22-e[10]*a12,
      oy=e[2]*a00-e[0]*a20+e[6]*a01-e[4]*a21+e[10]*a02-e[8]*a22,
      oz=e[0]*a10-e[1]*a00+e[4]*a11-e[5]*a01+e[8]*a12-e[9]*a02;
  const den=Math.abs(e[0]*a00+e[1]*a10+e[2]*a20+e[4]*a01+e[5]*a11+e[6]*a21+e[8]*a02+e[9]*a12+e[10]*a22)+1e-9;
  ox/=den;oy/=den;oz/=den;const w=Math.hypot(ox,oy,oz);if(w<1e-9)break;
  axv.set(ox/w,oy/w,oz/w);qT.setFromAxisAngle(axv,w);qR.premultiply(qT).normalize()}
 m4.makeRotationFromQuaternion(qR);e=m4.elements;
 for(let p=0;p<N3;p+=3){const qx=Q0[p],qy=Q0[p+1],qz=Q0[p+2];
  P[p]+=(e[0]*qx+e[4]*qy+e[8]*qz+cx-P[p])*k;P[p+1]+=(e[1]*qx+e[5]*qy+e[9]*qz+cy-P[p+1])*k;P[p+2]+=(e[2]*qx+e[6]*qy+e[10]*qz+cz-P[p+2])*k}
}
let grab=null,pressY=Infinity;
function step(dt){
 const h=dt/SUB,a=compl/(h*h),ks=Math.min(1,kShape*h*h),dmp=Math.exp(-dampC*h),vmax=25;
 for(let s=0;s<SUB;s++){
  for(let i=0;i<N3;i+=3){Vv[i]*=dmp;Vv[i+1]=Vv[i+1]*dmp-G*h;Vv[i+2]*=dmp;O[i]=P[i];O[i+1]=P[i+1];O[i+2]=P[i+2];P[i]+=Vv[i]*h;P[i+1]+=Vv[i+1]*h;P[i+2]+=Vv[i+2]*h}
  for(let c=0;c<NC;c++){const i=CI[c*2],j=CI[c*2+1],dx=P[i]-P[j],dy=P[i+1]-P[j+1],dz=P[i+2]-P[j+2],d=Math.sqrt(dx*dx+dy*dy+dz*dz);
   if(d<1e-8)continue;const l=-(d-CL[c])/(2+a)/d;P[i]+=dx*l;P[i+1]+=dy*l;P[i+2]+=dz*l;P[j]-=dx*l;P[j+1]-=dy*l;P[j+2]-=dz*l}
  shapeMatch(ks);
  if(grab){const t=grab.target;for(let n=0;n<grab.ids.length;n++){const i=grab.ids[n],w=grab.ws[n]*0.25,o=grab.off[n];
   P[i]+=(t.x+o[0]-P[i])*w;P[i+1]+=(t.y+o[1]-P[i+1])*w;P[i+2]+=(t.z+o[2]-P[i+2])*w}}
  for(let i=0;i<N3;i+=3){
   if(P[i+1]>pressY)P[i+1]=pressY;
   const f=plateH(Math.hypot(P[i],P[i+2]));
   if(P[i+1]<f){P[i+1]=f;P[i]-=(P[i]-O[i])*MU;P[i+2]-=(P[i+2]-O[i+2])*MU}
   let vx=(P[i]-O[i])/h,vy=(P[i+1]-O[i+1])/h,vz=(P[i+2]-O[i+2])/h;const sp=Math.hypot(vx,vy,vz);
   if(sp>vmax){const q=vmax/sp;vx*=q;vy*=q;vz*=q}Vv[i]=vx;Vv[i+1]=vy;Vv[i+2]=vz}
 }
 if(!Number.isFinite(P[0]+P[N3-1]))resetAll();
}
const na=()=>geo.attributes.normal.array;
function deform(){
 ST.fill(0);
 for(let c=0;c<NC;c++){const i=CI[c*2],j=CI[c*2+1],r=Math.hypot(P[i]-P[j],P[i+1]-P[j+1],P[i+2]-P[j+2])/CL[c];ST[i/3]+=r;ST[j/3]+=r}
 for(let p=0;p<NP;p++)ST[p]/=CNT[p];
 for(let v=0;v<NV;v++){let x=0,y=0,z=0,s=0;const o=v*8;
  for(let c=0;c<8;c++){const p=FI[o+c],w=FW[o+c],p3=p*3;x+=P[p3]*w;y+=P[p3+1]*w;z+=P[p3+2]*w;s+=ST[p]*w}
  const v3=v*3;pa[v3]=x;pa[v3+1]=y;pa[v3+2]=z;
  const g=Math.max(-0.4,Math.min(0.75,(s-1)*3)); // stretched = thinner = light shines through
  ca[v3]=1+0.42*g;ca[v3+1]=1+0.34*g;ca[v3+2]=1+0.12*g}
 geo.attributes.position.needsUpdate=true;geo.attributes.color.needsUpdate=true;geo.computeVertexNormals();
}

/* ---------- juice drops, presser, marker ---------- */
const dropGeo=new THREE.SphereGeometry(1,20,14);
const dropMat=new THREE.MeshPhysicalMaterial({color:0xffb233,transmission:0.85,roughness:0.03,ior:1.34,thickness:0.15,attenuationColor:new THREE.Color(0xff8800),attenuationDistance:0.25,clearcoat:1,emissive:new THREE.Color(0xff7a00),emissiveIntensity:0.18});
const drops=[];
const v1=new THREE.Vector3(),v2=new THREE.Vector3(),v3=new THREE.Vector3();
const vtx=(i,o)=>o.set(pa[i*3],pa[i*3+1],pa[i*3+2]);
function spawnDrop(){
 const col=cutCols[(Math.random()*cutCols.length)|0],m=new THREE.Mesh(dropGeo,dropMat);scene.add(m);
 drops.push({m,col,t:0,size:0.034+Math.random()*0.02,run:0.75+Math.random()*0.5,base:null,out:null});
 if(drops.length>40){const d=drops.shift();scene.remove(d.m)}
}
function dropsUpdate(dt){
 const N=na();
 for(const d of drops){
  d.t+=dt;const s=d.size,m=d.m;
  if(d.t<0.35+d.run){
   let f;if(d.t<0.35){f=1;const g=ease(d.t/0.35);m.scale.set(s*g,s*g,s*g)}else{const u=(d.t-0.35)/d.run;f=1-u*u;m.scale.set(s*0.9,s*1.5,s*0.9)}
   const kf=f*NW,k0=Math.min(NW-1,Math.floor(kf)),fr=kf-k0,i0=d.col[k0];
   vtx(i0,v1);vtx(d.col[k0+1],v2);v1.lerp(v2,fr);v3.set(N[i0*3],0,N[i0*3+2]).normalize();
   m.position.copy(v1).addScaledVector(v3,s*0.75);
  }else{
   if(!d.base){const i0=d.col[0];d.base=vtx(i0,new THREE.Vector3());d.out=new THREE.Vector3(N[i0*3],0,N[i0*3+2]).normalize()}
   const e=ease((d.t-0.35-d.run)/1.6),sy=s*(0.9-0.72*e);
   m.position.copy(d.base).addScaledVector(d.out,s*0.8+0.13*e);
   m.position.y=plateH(Math.hypot(m.position.x,m.position.z))+sy*0.3;
   m.scale.set(s*(1.1+1.7*e),sy,s*(1.1+1.7*e));
  }
 }
}
const presser=new THREE.Mesh(new THREE.CylinderGeometry(1.2,1.2,0.07,56),new THREE.MeshPhysicalMaterial({color:0xffffff,roughness:0.04,clearcoat:1,transparent:true,opacity:0,depthWrite:false}));
presser.visible=false;scene.add(presser);
const marker=new THREE.Mesh(new THREE.SphereGeometry(0.065,16,12),new THREE.MeshBasicMaterial({color:0xffffff,transparent:true,opacity:0.85,depthTest:false}));
marker.renderOrder=10;marker.visible=false;scene.add(marker);
let sq=null;
function squeeze(){
 if(sq)return;let top=0,cx=0,cz=0;for(let p=0;p<N3;p+=3){top=Math.max(top,P[p+1]);cx+=P[p];cz+=P[p+2]}
 sq={t:0,top,cx:cx/NP,cz:cz/NP,next:[1.0,1.22,1.45,1.68,1.9].slice(0,3+((Math.random()*3)|0))};presser.visible=true;
}
function sqUpdate(dt){
 const s=sq;s.t+=dt;const t=s.t,lo=H*0.5,top=s.top;let y;
 if(t<0.35)y=top+0.5*(1-ease(t/0.35));
 else if(t<1.0)y=top+(lo-top)*ease((t-0.35)/0.65);
 else if(t<2.0)y=lo-0.012*Math.sin((t-1)*PI);
 else y=lo+(top+0.7-lo)*ease((t-2)/0.55);
 pressY=y;presser.position.set(s.cx,y+0.035,s.cz);
 presser.material.opacity=0.3*Math.min(1,t/0.25)*(t>2.2?Math.max(0,1-(t-2.2)/0.35):1);
 while(s.next.length&&t>=s.next[0]){s.next.shift();spawnDrop()}
 if(t>2.6){sq=null;pressY=Infinity;presser.visible=false}
}

/* ---------- interaction ---------- */
function resetAll(){
 for(let p=0;p<N3;p+=3){P[p]=RS[p];P[p+1]=RS[p+1]+0.28;P[p+2]=RS[p+2];O[p]=P[p];O[p+1]=P[p+1];O[p+2]=P[p+2];Vv[p]=Vv[p+1]=Vv[p+2]=0}
 qR.identity();grab=null;sq=null;pressY=Infinity;presser.visible=false;
 for(const d of drops)scene.remove(d.m);drops.length=0;
}
function setFirm(v){$('firm').value=v;updFirm()}
function updFirm(){const f=$('firm').value/100;$('fv').textContent=Math.round(f*100);
 compl=Math.pow(10,-2.3-1.9*f);kShape=120+1800*Math.pow(f,1.5);dampC=1.4+1.3*f}
$('firm').addEventListener('input',updFirm);
$('sq').addEventListener('click',squeeze);
$('rs').addEventListener('click',()=>{resetAll();setFirm(45)});

const ray=new THREE.Raycaster(),ndc=new THREE.Vector2(),camDir=new THREE.Vector3(),hitV=new THREE.Vector3();
function setRay(x,y){const r=cv.getBoundingClientRect();ndc.set((x-r.left)/r.width*2-1,-(y-r.top)/r.height*2+1);ray.setFromCamera(ndc,camera)}
function pick(x,y){setRay(x,y);geo.computeBoundingSphere();const h=ray.intersectObject(jelly,false);return h.length?h[0].point.clone():null}
function beginGrab(pt){
 const g={ids:[],ws:[],off:[],anchor:pt.clone(),target:pt.clone(),plane:new THREE.Plane()};
 camera.getWorldDirection(camDir);g.plane.setFromNormalAndCoplanarPoint(camDir,pt);
 let best=-1,bd=1e9;
 for(let p=0;p<NP;p++){const p3=p*3,d=Math.hypot(P[p3]-pt.x,P[p3+1]-pt.y,P[p3+2]-pt.z);if(d<bd){bd=d;best=p}
  if(d<0.6){const w=(1-d/0.6)**2;g.ids.push(p3);g.ws.push(w);g.off.push([P[p3]-pt.x,P[p3+1]-pt.y,P[p3+2]-pt.z])}}
 if(!g.ids.length){const p3=best*3;g.ids.push(p3);g.ws.push(1);g.off.push([P[p3]-pt.x,P[p3+1]-pt.y,P[p3+2]-pt.z])}
 grab=g;
}
function dragTo(x,y){if(!grab)return;setRay(x,y);if(ray.ray.intersectPlane(grab.plane,hitV)){hitV.sub(grab.anchor);if(hitV.length()>1.2)hitV.setLength(1.2);grab.target.copy(grab.anchor).add(hitV)}}
function poke(pt,dir){
 for(let p=0;p<N3;p+=3){const d=Math.hypot(P[p]-pt.x,P[p+1]-pt.y,P[p+2]-pt.z);if(d<0.55){const w=(1-d/0.55)**2;
  Vv[p]+=dir.x*3.6*w;Vv[p+1]+=dir.y*3.6*w;Vv[p+2]+=dir.z*3.6*w;P[p]+=dir.x*0.04*w;P[p+1]+=dir.y*0.04*w;P[p+2]+=dir.z*0.04*w}}
}
let ptr=null;
function hideHint(){$('hint').style.opacity=0}
cv.addEventListener('pointerdown',e=>{
 if(ptr)return;try{cv.setPointerCapture(e.pointerId)}catch(_){}
 const hit=pick(e.clientX,e.clientY);
 ptr={id:e.pointerId,x0:e.clientX,y0:e.clientY,x:e.clientX,y:e.clientY,hit,dir:ray.ray.direction.clone(),mode:hit?'pend':'orbit'};
});
cv.addEventListener('pointermove',e=>{
 if(!ptr||e.pointerId!==ptr.id)return;
 const dx=e.clientX-ptr.x,dy=e.clientY-ptr.y;ptr.x=e.clientX;ptr.y=e.clientY;
 if(ptr.mode==='pend'&&Math.hypot(e.clientX-ptr.x0,e.clientY-ptr.y0)>7){ptr.mode='grab';beginGrab(ptr.hit);hideHint()}
 if(ptr.mode==='grab')dragTo(e.clientX,e.clientY);
 else if(ptr.mode==='orbit'){az-=dx*0.008;el=Math.max(0.18,Math.min(1.35,el+dy*0.006))}
});
function endPtr(e){
 if(!ptr||e.pointerId!==ptr.id)return;
 if(ptr.mode==='pend'){poke(ptr.hit,ptr.dir);hideHint()}
 if(ptr.mode==='grab')grab=null;
 ptr=null;
}
cv.addEventListener('pointerup',endPtr);cv.addEventListener('pointercancel',endPtr);
cv.addEventListener('contextmenu',e=>e.preventDefault());

/* ---------- hands-free demo (#demo) ---------- */
let demo=location.hash==='#demo',dT=0,dPrev=-1,dDrag=null,markT=0;
const nearestLocal=(x,y,z)=>{let b=0,bd=1e9;for(let p=0;p<NP;p++){const d=Math.hypot(LP[p*3]-x,LP[p*3+1]-y,LP[p*3+2]-z);if(d<bd){bd=d;b=p}}return b};
const pA=nearestLocal(0.25,H,0.5),pB=nearestLocal(-0.45,H,0.35),pC=nearestLocal(0,H,0.75),pTip=nearestLocal(1,H,0),pTip2=nearestLocal(-0.7,H,0.7);
const pv=p=>new THREE.Vector3(P[p*3],P[p*3+1],P[p*3+2]);
function dPoke(p){const pt=pv(p),dir=pt.clone().sub(camera.position).normalize();poke(pt,dir);marker.position.copy(pt);marker.visible=true;markT=0.45}
function dGrabStart(p){const pt=pv(p);beginGrab(pt);let cx=0,cz=0;for(let i=0;i<N3;i+=3){cx+=P[i];cz+=P[i+2]}
 const v=new THREE.Vector3(pt.x-cx/NP,0,pt.z-cz/NP).normalize().multiplyScalar(0.75);v.y=0.35;dDrag={t0:dT,v}}
function dGrabEnd(){grab=null;dDrag=null;marker.visible=false}
const DEMO=[[0.05,()=>{resetAll();setFirm(45)}],[1.8,()=>dPoke(pA)],[3.0,()=>dPoke(pB)],[4.3,()=>dGrabStart(pTip)],[6.5,dGrabEnd],
 [8.4,()=>setFirm(10)],[9.0,()=>dPoke(pA)],[10.4,()=>dPoke(pC)],[12.0,()=>{setFirm(45);squeeze()}],[15.0,()=>setFirm(85)],
 [15.4,()=>dGrabStart(pTip2)],[17.2,dGrabEnd],[18.4,()=>dPoke(pB)]];
function demoUpdate(dt){
 dPrev=dT;dT+=dt;if(dT>=20){dT-=20;dPrev=-1}
 for(const [t,f] of DEMO)if(t>dPrev&&t<=dT)f();
 if(dDrag&&grab){const k=ease((dT-dDrag.t0)/1.5);grab.target.copy(grab.anchor).addScaledVector(dDrag.v,k);marker.position.copy(grab.target);marker.visible=true}
 if(markT>0){markT-=dt;if(markT<=0&&!dDrag)marker.visible=false}
 az=0.35*Math.sin(dT/20*PI*2);
}
function endDemo(){if(!demo)return;demo=false;$('badge').style.display='none';if(dDrag){grab=null;dDrag=null}marker.visible=false}
window.addEventListener('pointerdown',e=>{if(e.isTrusted&&demo)endDemo()},true);
if(demo){$('badge').style.display='block';hideHint()}

/* ---------- loop ---------- */
function resize(){const w=innerWidth,h=innerHeight;renderer.setSize(w,h);camera.aspect=w/h;camera.updateProjectionMatrix();
 dist=Math.max(5.0,1.45/(Math.tan(19*PI/180)*camera.aspect))}
addEventListener('resize',resize);resize();
updFirm();resetAll();
let last=performance.now();
function frame(now){
 const dt=Math.min(Math.max((now-last)/1000,0.001),1/30);last=now;
 if(demo)demoUpdate(dt);
 if(sq)sqUpdate(dt);
 step(dt);deform();dropsUpdate(dt);
 camUpdate();renderer.render(scene,camera);
 requestAnimationFrame(frame);
}
deform();requestAnimationFrame(frame);
</script>
</body>
</html>