Skip to content
VibeCodeBench
Back to the app

The code

Jelly Orange Slice by GPT-6.2 Sol

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.)29.3 KB · 666 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.min.js
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Orange Jelly — The Texture Lab</title>
<style>
:root{color-scheme:light;--ink:#392319;--muted:#785d4e;--paper:#faf5ec;--line:#e7d9cb;--accent:#ad401c;--orange:#c64c22}
*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
button,input{font:inherit}button{cursor:pointer}button:focus-visible,input:focus-visible,#stage:focus-visible{outline:2px solid #9e391b;outline-offset:4px}
.shell{max-width:1440px;margin:auto;padding:0 clamp(20px,5vw,76px)}
.masthead{height:83px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;gap:12px}
.brand{display:flex;align-items:center;gap:10px;font-family:Georgia,serif;font-size:22px;font-weight:bold;white-space:nowrap;letter-spacing:-.65px}
.brand-mark{display:grid;place-items:center;width:24px;height:24px;border:1px solid #ad401c;border-radius:50%;color:var(--accent);font:17px/1 Georgia,serif}
.micro{font-size:10px;line-height:1.35;letter-spacing:.15em;font-weight:750;text-transform:uppercase}
.edition{color:var(--muted);text-align:right}
.layout{display:grid;grid-template-columns:minmax(260px,320px) minmax(0,1fr);grid-template-areas:"intro stage" "controls stage";grid-template-rows:auto 1fr;column-gap:clamp(30px,5vw,74px);row-gap:29px;margin:42px 0 25px}
.intro{grid-area:intro;padding-top:clamp(12px,3vw,42px)}
.kicker{display:flex;gap:10px;align-items:center;color:var(--accent)}.kicker::before{content:"";width:24px;height:1px;background:currentColor}
h1{font:normal clamp(67px,6.4vw,103px)/.82 Georgia,"Times New Roman",serif;letter-spacing:-.092em;margin:24px 0 22px}h1 em{display:block;font-weight:normal;color:var(--orange);padding-right:.17em}
.intro p{font-size:15px;line-height:1.65;color:var(--muted);max-width:264px;margin:0}
.controls{grid-area:controls;align-self:start;padding:21px 19px 19px;background:#fffaf3;border:1px solid var(--line);border-radius:16px}
.control-label{display:flex;align-items:center;justify-content:space-between;font-size:13px;font-weight:720}.control-label output{font-size:11px;color:var(--accent);font-weight:750;background:#f8e6d7;border-radius:20px;padding:4px 9px;min-width:56px;text-align:center}
input[type=range]{--fill:52%;appearance:none;width:100%;margin:11px 0 4px;background:transparent;height:27px;cursor:pointer;display:block;accent-color:var(--accent)}
input[type=range]::-webkit-slider-runnable-track{height:4px;border-radius:10px;background:linear-gradient(to right,#c6552b var(--fill),#ecdfd0 var(--fill))}
input[type=range]::-webkit-slider-thumb{appearance:none;width:18px;height:18px;border:3px solid #fffaf3;border-radius:50%;background:#c6552b;box-shadow:0 0 0 1px #c6552b;margin-top:-7px}
input[type=range]::-moz-range-track{height:4px;border-radius:10px;background:#ecdfd0}input[type=range]::-moz-range-progress{height:4px;background:#c6552b}input[type=range]::-moz-range-thumb{width:13px;height:13px;border:2px solid #fffaf3;border-radius:50%;background:#c6552b;box-shadow:0 0 0 1px #c6552b}
.range-ends{display:flex;justify-content:space-between;color:var(--muted);font-size:11px}
.actions{display:grid;grid-template-columns:1.35fr 1fr;gap:8px;margin-top:18px}
.actions button{min-height:47px;border-radius:9px;font-weight:720;font-size:13px;padding:0 8px;display:flex;align-items:center;justify-content:center;gap:7px}
.squeeze{color:#fff9f3;background:#a93c19;border:1px solid #a93c19}.squeeze:active,.squeeze[aria-pressed=true]{background:#7e2a10}
.reset{color:var(--ink);background:transparent;border:1px solid #dfcdbd}.reset:active{background:#f3e7db}.action-icon{font-size:18px;line-height:1}
#stage{grid-area:stage;position:relative;isolation:isolate;overflow:hidden;height:clamp(530px,48vw,665px);border:1px solid #ebbe9e;border-radius:23px;background:radial-gradient(ellipse at 35% 30%,#fff0d9 1%,#fbdcbe 45%,#f2b99a 100%);touch-action:none;cursor:grab}
#stage[data-grabbing=true]{cursor:grabbing}#stage canvas{position:absolute;inset:0;display:block;width:100%;height:100%}
.stage-top,.stage-bottom{z-index:1;position:absolute;left:20px;right:20px;display:flex;align-items:center;justify-content:space-between;gap:10px;pointer-events:none;color:#633b2b}
.stage-top{top:19px}.stage-bottom{bottom:18px}
.stage-status{display:flex;align-items:center;gap:7px;background:#fff2debb;padding:8px 10px;border:1px solid #fff4e3a0;border-radius:100px;white-space:nowrap}
.dot{width:6px;height:6px;border-radius:50%;background:#39704a;box-shadow:0 0 0 2px #5e956f22}
.gesture{margin:auto;display:flex;align-items:center;gap:9px;font-size:12px;font-weight:650;background:#fff4e2cc;border:1px solid #fff6e6b0;border-radius:30px;padding:9px 13px;white-space:nowrap}.gesture span{color:var(--accent);font-size:16px;line-height:1}
.stage-error{z-index:2;position:absolute;inset:40% 10% auto;text-align:center;color:#733f25}
.footer{border-top:1px solid var(--line);padding:17px 0 22px;display:flex;justify-content:space-between;gap:12px;color:var(--muted)}
@media (max-width:800px){.shell{padding:0 20px}.masthead{height:62px}.layout{grid-template-columns:1fr;grid-template-areas:"intro" "stage" "controls";row-gap:19px;margin-top:20px}.intro{padding-top:0}.intro p{max-width:32ch;font-size:14px}h1{font-size:clamp(54px,10vw,80px);margin:14px 0 12px}h1 em{display:inline;padding-right:.13em}#stage{height:clamp(330px,87vw,505px)}.controls{max-width:none}.stage-top,.stage-bottom{left:12px;right:12px}.stage-top{top:12px}.stage-bottom{bottom:13px}}
@media (max-width:355px){.shell{padding:0 13px}h1{font-size:48px}.brand{font-size:19px}.micro{letter-spacing:.11em}}
</style>
</head>
<body>
<div class="shell">
 <header class="masthead">
  <div class="brand"><span aria-hidden="true" class="brand-mark">✳</span>The Texture Lab</div>
  <div class="edition micro">Material study / 01</div>
 </header>
 <main class="layout">
  <section class="intro" aria-labelledby="title">
   <div class="kicker micro">Citrus in motion</div>
   <h1 id="title">Orange <em>jelly.</em></h1>
   <p>Poke a juicy segment or pull the slice and watch it settle back into shape.</p>
  </section>
  <section id="stage" tabindex="0" aria-label="Interactive orange jelly on a white plate. Use a pointer to poke and stretch the slice." aria-describedby="gesture">
   <div class="stage-top micro"><span>01 / Orange slice</span><span class="stage-status"><i class="dot"></i><span id="status">Live simulation</span></span></div>
   <div class="stage-bottom"><div class="gesture" id="gesture"><span aria-hidden="true">✥</span> Tap to poke · Drag to stretch</div></div>
   <div class="stage-error" id="error" hidden></div>
  </section>
  <section class="controls" aria-label="Jelly controls">
   <label class="control-label" for="firmness">Firmness <output id="firmnessValue" for="firmness">Medium</output></label>
   <input id="firmness" type="range" min="0" max="100" value="52">
   <div class="range-ends" aria-hidden="true"><span>Soft</span><span>Firm</span></div>
   <div class="actions">
    <button class="squeeze" id="squeeze" type="button" aria-pressed="false"><span class="action-icon" aria-hidden="true">↧</span> Squeeze</button>
    <button class="reset" id="reset" type="button"><span class="action-icon" aria-hidden="true">↺</span> Reset</button>
   </div>
  </section>
 </main>
 <footer class="footer micro"><span>The Texture Lab</span><span>Study 01 / Soft bodies</span></footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
(function () {
"use strict";
const stage = document.getElementById("stage");
const firmnessInput = document.getElementById("firmness");
const firmnessValue = document.getElementById("firmnessValue");
const squeezeButton = document.getElementById("squeeze");
const resetButton = document.getElementById("reset");
const status = document.getElementById("status");
let renderer;
try {
  renderer = new THREE.WebGLRenderer({antialias:true,alpha:true});
} catch (error) {
  document.getElementById("error").hidden = false;
  document.getElementById("error").textContent = "This interactive study needs WebGL and access to its 3D library.";
  status.textContent = "3D unavailable";
  return;
}
const T = THREE, TAU = Math.PI * 2;
const clamp = (n,min,max) => Math.max(min,Math.min(max,n));
const mix = (a,b,t) => a+(b-a)*t;
const polar = (r,a,y) => [r*Math.cos(a),y,r*Math.sin(a)];
const scene = new T.Scene();
const camera = new T.OrthographicCamera();
camera.position.set(.15,6.25,7.55);
camera.lookAt(0,.12,0);
renderer.setPixelRatio(Math.min(devicePixelRatio || 1,1.75));
renderer.setClearColor(0x000000,0);
renderer.toneMapping = T.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.16;
renderer.domElement.setAttribute("aria-hidden","true");
stage.prepend(renderer.domElement);
function resize() {
  const w = stage.clientWidth, h = stage.clientHeight;
  if (!w || !h) return;
  const height = Math.max(5.65,5.6*h/w);
  camera.top = height/2;
  camera.bottom = -height/2;
  camera.left = -height*w/h/2;
  camera.right = -camera.left;
  camera.near = .1;
  camera.far = 40;
  camera.updateProjectionMatrix();
  renderer.setSize(w,h,false);
}
new ResizeObserver(resize).observe(stage);
resize();

let seed = 82019;
function random() {
  seed = (Math.imul(seed,1664525)+1013904223) >>> 0;
  return seed/4294967296;
}
const hemi = new T.HemisphereLight(0xfff8ed,0xe8a486,2.0);
scene.add(hemi);
function light(color,intensity,x,y,z) {
  const source = new T.DirectionalLight(color,intensity);
  source.position.set(x,y,z);
  scene.add(source);
}
light(0xfff3dc,2.55,-3.8,6,1.8);
light(0xffbc70,2.65,2.2,2.8,-4.4);
light(0xfaf4ff,.72,4,1.6,4);
const environment = new T.Scene();
environment.background = new T.Color(0x695147);
function softbox(x,y,z,w,h,color,power) {
  const box = new T.Mesh(new T.PlaneGeometry(w,h),new T.MeshBasicMaterial({color:new T.Color(color).multiplyScalar(power),side:T.DoubleSide}));
  box.position.set(x,y,z);
  box.lookAt(0,0,0);
  environment.add(box);
}
softbox(-4,6,2,4,3.2,0xfff0db,2.8);
softbox(2,4,-5,2,4,0xffca8b,2.15);
softbox(4,2,4,2.5,5,0xffffff,1.35);
const pmrem = new T.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(environment,.07,.1,20).texture;
pmrem.dispose();

function canvasTexture(w,h,draw) {
  const canvas = document.createElement("canvas");
  canvas.width=w; canvas.height=h;
  draw(canvas.getContext("2d"),w,h);
  return new T.CanvasTexture(canvas);
}
const shadowTexture = canvasTexture(128,128,(ctx,w,h) => {
  const g=ctx.createRadialGradient(w/2,h/2,0,w/2,h/2,w/2);
  g.addColorStop(0,"rgba(89,39,19,0.51)");
  g.addColorStop(.59,"rgba(89,39,19,0.30)");
  g.addColorStop(.82,"rgba(89,39,19,0.12)");
  g.addColorStop(1,"rgba(89,39,19,0)");
  ctx.fillStyle=g; ctx.fillRect(0,0,w,h);
});
shadowTexture.colorSpace=T.SRGBColorSpace;
function shadow(w,h,x,y,z,opacity) {
  const obj = new T.Mesh(new T.PlaneGeometry(w,h),new T.MeshBasicMaterial({map:shadowTexture,transparent:true,opacity,depthWrite:false,polygonOffset:true,polygonOffsetFactor:-1}));
  obj.rotation.x=-Math.PI/2;
  obj.position.set(x,y,z);
  scene.add(obj);
  return obj;
}
shadow(6.3,5.45,.24,-.046,.23,.87);
shadow(4.9,4.68,.03,-.044,.05,.85);

function makeGeometry(positions,indices,uv,colors) {
  const geo=new T.BufferGeometry();
  geo.setAttribute("position",new T.Float32BufferAttribute(positions,3));
  if(uv) geo.setAttribute("uv",new T.Float32BufferAttribute(uv,2));
  if(colors) geo.setAttribute("color",new T.Float32BufferAttribute(colors,3));
  geo.setIndex(indices);
  geo.computeVertexNormals();
  return geo;
}
function revolve(profile,steps,irregularity=0) {
  const v=[],uv=[],faces=[];
  for(let j=0;j<profile.length;j++){
    const [r,y]=profile[j];
    for(let i=0;i<=steps;i++){
      const a=i/steps*TAU;
      const wave=(Math.sin(5*a+.3)+.45*Math.sin(9*a-.6)+.3*Math.cos(17*a))*irregularity;
      v.push(...polar(r*(1+wave),a,y+wave*r*.35));
      uv.push(i/steps,j/(profile.length-1));
      if(j<profile.length-1 && i<steps){
        const p=j*(steps+1)+i, q=p+steps+1;
        faces.push(p,q,p+1,p+1,q,q+1);
      }
    }
  }
  const geo = makeGeometry(v,faces,uv);
  smoothSeam(geo,steps+1);
  geo.userData.stride=steps+1;
  return geo;
}
function smoothSeam(geo,stride) {
  const n=geo.attributes.normal;
  for(let a=0;a<n.count;a+=stride){
    const b=a+stride-1;
    const x=n.getX(a)+n.getX(b),y=n.getY(a)+n.getY(b),z=n.getZ(a)+n.getZ(b);
    const length=Math.hypot(x,y,z)||1;
    n.setXYZ(a,x/length,y/length,z/length); n.setXYZ(b,x/length,y/length,z/length);
  }
  n.needsUpdate=true;
}
const porcelain = new T.MeshPhysicalMaterial({color:0xfff9ef,roughness:.23,clearcoat:.48,clearcoatRoughness:.2,envMapIntensity:.62});
const plateProfile=[
 [.001,.027],[1.16,.027],[1.32,.022],[1.36,-.021],[1.42,-.035],[1.58,-.035],[1.63,-.013],[1.65,.032],
 [1.9,.045],[2.13,.077],[2.32,.134],[2.46,.196],[2.49,.235],[2.487,.266],[2.468,.288],[2.42,.304],
 [2.36,.302],[2.29,.282],[2.2,.245],[2.08,.2],[1.96,.164],[1.84,.145],[1.70,.135],[1.53,.131],[.001,.131]
];
scene.add(new T.Mesh(revolve(plateProfile,128),porcelain));
const contactShadow=shadow(3.85,3.75,0,.137,.03,.68);
const floorY = .151;

const parts=[];
function attach(geo,material) {
  const mesh=new T.Mesh(geo,material);
  mesh.frustumCulled=false;
  scene.add(mesh);
  const positions=geo.attributes.position;
  const bindings=[];
  for(let i=0;i<positions.count;i++) bindings.push(bind(positions.getX(i),positions.getY(i),positions.getZ(i)));
  parts.push({mesh,bindings,base:positions.array.slice()});
  return mesh;
}

const SPOKES=24,RINGS=4,LAYERS=3,RADIUS=1.78,BOTTOM=.173,TOP=.676;
const nodes=[],links=[],nodeCount=(1+RINGS*SPOKES)*LAYERS;
function nodeIndex(layer,ring,angle=0) {
  return layer*(1+RINGS*SPOKES)+(ring ? 1+(ring-1)*SPOKES+(angle+SPOKES)%SPOKES : 0);
}
for(let l=0;l<LAYERS;l++) {
  for(let r=0;r<=RINGS;r++) {
    for(let a=0;a<(r ? SPOKES : 1);a++){
      const [x,y,z]=polar(r/RINGS*RADIUS,a/SPOKES*TAU,mix(BOTTOM,TOP,l/(LAYERS-1)));
      nodes.push({x,y,z,rx:x,ry:y,rz:z,px:x,py:y,pz:z,vx:0,vy:0,vz:0});
    }
  }
}
const pairs=new Set();
function link(a,b,flex) {
  if(a===b) return;
  const key=Math.min(a,b)*nodeCount+Math.max(a,b);
  if(pairs.has(key)) return;
  pairs.add(key);
  const p=nodes[a],q=nodes[b];
  links.push({p,q,rest:Math.hypot(p.x-q.x,p.y-q.y,p.z-q.z),flex,lambda:0});
}
for(let l=0;l<LAYERS;l++) {
  for(let r=0;r<=RINGS;r++) {
    for(let a=0;a<(r ? SPOKES : 1);a++) {
      const id=nodeIndex(l,r,a);
      if(r){
        link(id,nodeIndex(l,r,a+1),1);
        link(id,nodeIndex(l,r-1,a),1);
        if(r>1) link(id,nodeIndex(l,r-1,a-1),1.65);
      }
      if(l+1<LAYERS){
        link(id,nodeIndex(l+1,r,a),.88);
        if(r){
          link(id,nodeIndex(l+1,r-1,a),1.55);
          link(id,nodeIndex(l+1,r,a+1),1.55);
          link(nodeIndex(l+1,r,a),nodeIndex(l,r-1,a),1.55);
        }
      }
    }
  }
}
function bind(x,y,z) {
  const r=clamp(Math.hypot(x,z)/RADIUS*RINGS,0,RINGS);
  const a=(Math.atan2(z,x)/TAU*SPOKES+SPOKES)%SPOKES;
  const l=clamp((y-BOTTOM)/(TOP-BOTTOM)*(LAYERS-1),0,LAYERS-1);
  const r0=Math.min(RINGS-1,Math.floor(r)),a0=Math.floor(a),l0=Math.min(LAYERS-2,Math.floor(l));
  const dr=r-r0,da=a-a0,dl=l-l0;
  const fields=[];
  for(let h=0;h<2;h++) for(let k=0;k<2;k++) for(let j=0;j<2;j++){
    const weight=(h ? dl : 1-dl)*(k ? dr : 1-dr)*(j ? da : 1-da);
    if(weight>0) fields.push([nodes[nodeIndex(l0+h,r0+k,a0+j)],weight]);
  }
  return fields;
}
function deform(fields,target,x,y,z) {
  for(let i=0;i<fields.length;i++){
    const p=fields[i][0],w=fields[i][1];
    x+=(p.x-p.rx)*w; y+=(p.y-p.ry)*w; z+=(p.z-p.rz)*w;
  }
  target.set(x,y,z);
}
const peelMap=canvasTexture(1024,128,(ctx,w,h)=>{
  const g=ctx.createLinearGradient(0,0,0,h);
  g.addColorStop(0,"#db510c");g.addColorStop(.35,"#ff831a");g.addColorStop(.68,"#ff9b22");g.addColorStop(1,"#f18a1a");
  ctx.fillStyle=g;ctx.fillRect(0,0,w,h);
  for(let i=0;i<9500;i++){
    ctx.fillStyle=random()>.47 ? "rgba(135,43,4,.19)" : "rgba(255,217,81,.24)";
    ctx.beginPath();ctx.ellipse(random()*w,random()*h,.4+random()*2.2,.35+random()*1.6,0,0,TAU);ctx.fill();
  }
});
peelMap.colorSpace=T.SRGBColorSpace;
peelMap.anisotropy=Math.min(8,renderer.capabilities.getMaxAnisotropy());
const peel=new T.MeshPhysicalMaterial({map:peelMap,bumpMap:peelMap,bumpScale:.022,roughness:.37,clearcoat:.38,clearcoatRoughness:.29,envMapIntensity:.66});
const milk=new T.MeshPhysicalMaterial({color:0xffe6b7,roughness:.44,clearcoat:.28,emissive:0x572705,emissiveIntensity:.19});
const peelMesh=attach(revolve([
 [.001,.174],[1.49,.174],[1.64,.174],[1.72,.195],[1.757,.235],[1.78,.33],[1.783,.44],[1.774,.53],[1.753,.594],[1.722,.631],[1.686,.644],[1.651,.632],[1.64,.606],[.001,.602]
],112,.009),peel);
const pithMesh=attach(revolve([
 [.001,.587],[1.61,.587],[1.662,.61],[1.686,.632],[1.665,.647],[1.635,.648],[1.606,.627],[1.57,.612],[1.2,.609],[.001,.609]
],112,.008),milk);

const segmentCount=10;
const cuts=[0,.61,1.21,1.88,2.51,3.13,3.73,4.39,4.99,5.59,TAU].map(a=>a+.17);
const hues=[0xff8920,0xffa023,0xff8d24,0xff9725,0xff8319,0xff981c,0xffa328,0xff8c20,0xff9223,0xffa52a];
function wedgePoint(segment,u,t,bottom) {
  const a=cuts[segment], b=cuts[segment+1];
  const r=mix(.105,1.615+.012*Math.sin((a+(b-a)*t)*5),u);
  const inset=Math.min(.19,.028/r);
  const angle=mix(a+inset,b-inset,t)+.013*Math.sin(u*5.1+segment);
  const rounding=Math.min(u/.17,(1-u)/.09,t/.17,(1-t)/.17,1);
  const crown=Math.sin(Math.PI*clamp(rounding,0,1)/2);
  const y=bottom ? .584-.025*crown : .611+.062*crown+.003*Math.sin(u*16+t*6+segment)*crown;
  return polar(r,angle,y);
}
function wedge(segment) {
  const positions=[],indices=[],colors=[];
  const rows=17,cols=13,faceCount=rows*cols;
  for(let layer=0;layer<2;layer++) for(let row=0;row<rows;row++) for(let col=0;col<cols;col++){
    const u=row/(rows-1),t=col/(cols-1);
    positions.push(...wedgePoint(segment,u,t,layer===1));
    const color=new T.Color(hues[segment]);
    const edge=Math.min(t,1-t,1-u,u+.09);
    color.lerp(new T.Color(0xffba4e),.35*Math.exp(-edge*16));
    color.multiplyScalar(.86+.17*u+.07*Math.sin(u*21+t*13+segment)+random()*.075);
    colors.push(color.r,color.g,color.b);
    if(row<rows-1&&col<cols-1){
      const p=layer*faceCount+row*cols+col,q=p+cols;
      if(layer===0) indices.push(p,p+1,q,p+1,q+1,q);
      else indices.push(p,q,p+1,p+1,q,q+1);
    }
  }
  const rim=[];
  for(let c=0;c<cols;c++) rim.push(c);
  for(let r=1;r<rows;r++) rim.push(r*cols+cols-1);
  for(let c=cols-2;c>=0;c--) rim.push((rows-1)*cols+c);
  for(let r=rows-2;r>0;r--) rim.push(r*cols);
  for(let i=0;i<rim.length;i++){
    const p=rim[i],q=rim[(i+1)%rim.length];
    indices.push(q,p,p+faceCount,q,p+faceCount,q+faceCount);
  }
  return makeGeometry(positions,indices,null,colors);
}
const pulpMaterial=new T.MeshPhysicalMaterial({
  vertexColors:true,roughness:.24,metalness:0,clearcoat:.76,clearcoatRoughness:.16,transmission:.23,thickness:.27,
  ior:1.35,attenuationColor:0xffa22d,attenuationDistance:.52,emissive:0xb94404,emissiveIntensity:.17,envMapIntensity:.84
});
for(let segment=0;segment<segmentCount;segment++) attach(wedge(segment),pulpMaterial);

const cellData=[];
const cellPalette=[0xffb142,0xf78916,0xffa02a,0xf07b0f,0xffbb46,0xff9922,0xffca5a];
for(let s=0;s<segmentCount;s++){
  for(let row=0;row<17;row++){
    const u=.13+row*.049;
    const count=Math.max(2,Math.round(2+u*9));
    for(let j=0;j<count;j++){
      const t=(j+.37+random()*.26)/count;
      const us=u+(random()-.5)*.032;
      const [x,y,z]=wedgePoint(s,us,t,false);
      const height=.009+random()*.016;
      const width=.012+random()*.022;
      const length=.028+random()*.045;
      const cy=y-height*(.2+random()*.42);
      const color=new T.Color(cellPalette[Math.floor(random()*cellPalette.length)]);
      color.lerp(new T.Color(hues[s]),.35);
      cellData.push({x,y:cy,z,fields:bind(x,cy,z),angle:-Math.atan2(z,x)+(random()-.5)*.54,scale:[length,height,width],color});
    }
  }
}
const cells = new T.InstancedMesh(new T.SphereGeometry(1,8,5),new T.MeshPhysicalMaterial({
  color:0xffffff,roughness:.27,clearcoat:.52,clearcoatRoughness:.19,emissive:0x873100,emissiveIntensity:.12,envMapIntensity:.69
}),cellData.length);
cells.instanceMatrix.setUsage(T.DynamicDrawUsage);
cells.frustumCulled=false;
for(let i=0;i<cellData.length;i++) cells.setColorAt(i,cellData[i].color);
scene.add(cells);

const placement=new T.Object3D(), temp=new T.Vector3();
function updateMeshes() {
  for(const {mesh,bindings,base} of parts){
    const geo=mesh.geometry,p=geo.attributes.position;
    for(let i=0;i<bindings.length;i++){
      deform(bindings[i],temp,base[3*i],base[3*i+1],base[3*i+2]);
      p.setXYZ(i,temp.x,temp.y,temp.z);
    }
    p.needsUpdate=true;
    geo.computeVertexNormals();
    if(geo.userData.stride) smoothSeam(geo,geo.userData.stride);
    if(mesh===pithMesh || mesh===peelMesh) geo.computeBoundingSphere();
  }
  for(let i=0;i<cellData.length;i++){
    const {fields,x,y,z,angle,scale}=cellData[i];
    deform(fields,placement.position,x,y,z);
    placement.rotation.y=angle;
    placement.scale.set(...scale);
    placement.updateMatrix();
    cells.setMatrixAt(i,placement.matrix);
  }
  cells.instanceMatrix.needsUpdate=true;
}

const drops=[];
const dropMaterial=new T.MeshPhysicalMaterial({
  color:0xff9a1e,roughness:.18,clearcoat:.92,transmission:.26,ior:1.36,thickness:.12,emissive:0xab4704,emissiveIntensity:.2
});
const dropGeometry=new T.SphereGeometry(1,16,12);
function spawnDrops() {
  const angles=[.49,.78,1.11,1.59,2.23,2.56,5.91];
  for(const angle of angles){
    const p=nodes[nodeIndex(1,RINGS,Math.round(angle/TAU*SPOKES))];
    const mesh=new T.Mesh(dropGeometry,dropMaterial);
    const size=.034+random()*.028;
    mesh.position.set(p.x,p.y,p.z);
    const drop={mesh,size,vx:Math.cos(angle)*(.45+random()*.28),vy:.18+random()*.3,vz:Math.sin(angle)*(.45+random()*.28),landed:false};
    mesh.scale.set(size,size*1.26,size);
    scene.add(mesh); drops.push(drop);
  }
}
function updateDrops(dt) {
  for(const drop of drops){
    const p=drop.mesh.position;
    const r=Math.hypot(p.x,p.z);
    if(!drop.landed){
      drop.vy-=6.1*dt;
      p.x+=drop.vx*dt; p.y+=drop.vy*dt; p.z+=drop.vz*dt;
      const floor=.151+Math.max(0,(r-1.85))*.23;
      if(p.y<floor+drop.size*.32){
        p.y=floor+drop.size*.32;
        drop.landed=true;
        drop.mesh.scale.set(drop.size*1.4,drop.size*.48,drop.size*1.22);
      }
    }else{
      const friction=Math.exp(-7*dt);
      drop.vx*=friction;drop.vz*=friction;
      if(r<2.31){p.x+=drop.vx*dt;p.z+=drop.vz*dt;}
      p.y=.151+Math.max(0,(Math.hypot(p.x,p.z)-1.85))*.23+drop.size*.32;
    }
  }
}
function clearDrops(){
  for(const drop of drops) scene.remove(drop.mesh);
  drops.length=0;
}
let firmness=.52, grab=null, squeezeTime=-1, squeezedOut=false, busy=1.3;
function setFirmness(value) {
  firmness=Number(value)/100;
  firmnessInput.value=value;
  firmnessInput.style.setProperty("--fill",value+"%");
  firmnessValue.textContent=firmness<.32?"Soft":firmness>.69?"Firm":"Medium";
  firmnessInput.setAttribute("aria-valuetext",firmnessValue.textContent+" ("+value+"%)");
}
setFirmness(52);
function squeeze() {
  if(squeezeTime>=0 && squeezeTime<.77) return;
  if(drops.length>=28) clearDrops();
  squeezeTime=0;
  squeezedOut=false;
  busy=Math.max(busy,3.4);
  squeezeButton.setAttribute("aria-pressed","true");
}
function reset() {
  grab=null;stage.dataset.grabbing="false";
  clearDrops();squeezeTime=-1;
  squeezeButton.setAttribute("aria-pressed","false");
  for(const p of nodes){
    p.x=p.px=p.rx;p.y=p.py=p.ry;p.z=p.pz=p.rz;
    p.vx=p.vy=p.vz=0;
  }
  contactShadow.scale.set(1,1,1);
  busy=.15;
  updateMeshes();
}
function step(dt) {
  let press=0;
  if(squeezeTime>=0) {
    squeezeTime+=dt;
    if(squeezeTime<.53) press=Math.sin(squeezeTime/.53*Math.PI*.5);
    else if(squeezeTime<.79) press=1;
    else if(squeezeTime<1.23) press=Math.cos((squeezeTime-.79)/.44*Math.PI*.5);
    else {
      squeezeTime=-1;
      squeezeButton.setAttribute("aria-pressed","false");
    }
    if(!squeezedOut && press>.84){squeezedOut=true;spawnDrops();}
  }
  const home=mix(16,35,firmness), damping=Math.exp(-mix(3.85,6,firmness)*dt);
  for(const p of nodes){
    p.px=p.x; p.py=p.y; p.pz=p.z;
    const height=(p.ry-BOTTOM)/(TOP-BOTTOM);
    const pullX=grab ? grab.dx*p.pull : 0, pullY=grab ? grab.dy*p.pull : 0, pullZ=grab ? grab.dz*p.pull : 0;
    const targetX=p.rx*(1+.135*press)+pullX;
    const targetZ=p.rz*(1+.135*press)+pullZ;
    const targetY=p.ry-.33*press*height+pullY;
    const grip=grab ? p.pull*192 : 0;
    const planar=home+press*82+grip;
    const vertical=home+press*385*height+grip;
    p.vx=(p.vx+(targetX-p.x)*planar*dt)*damping;
    p.vy=(p.vy+(targetY-p.y)*vertical*dt)*damping;
    p.vz=(p.vz+(targetZ-p.z)*planar*dt)*damping;
    p.x+=p.vx*dt;p.y+=p.vy*dt;p.z+=p.vz*dt;
  }
  const compliance=mix(.00032,.000016,firmness)/(dt*dt);
  for(const e of links) e.lambda=0;
  for(let pass=0;pass<5;pass++){
    for(let i=0;i<links.length;i++){
      const e=links[pass%2 ? links.length-1-i : i],p=e.p,q=e.q;
      const dx=q.x-p.x,dy=q.y-p.y,dz=q.z-p.z;
      const dist=Math.sqrt(dx*dx+dy*dy+dz*dz);
      if(dist<.00001) continue;
      const alpha=compliance*e.flex*(1+press*1.7);
      const correction=(dist-e.rest-alpha*e.lambda)/(2+alpha);
      e.lambda+=correction;
      const m=correction/dist;
      p.x+=dx*m;p.y+=dy*m;p.z+=dz*m;
      q.x-=dx*m;q.y-=dy*m;q.z-=dz*m;
    }
    for(const p of nodes){
      p.y=Math.max(floorY,p.y);
      if(p.y<floorY+.015){
        p.x=mix(p.x,p.px,.024);p.z=mix(p.z,p.pz,.024);
      }
    }
  }
  for(const p of nodes){
    p.vx=clamp((p.x-p.px)/dt,-5,5);
    p.vy=clamp((p.y-p.py)/dt,-5,5);
    p.vz=clamp((p.z-p.pz)/dt,-5,5);
  }
  contactShadow.scale.set(1+.09*press,1+.09*press,1);
}
function poke(x,z,withGrab) {
  for(const p of nodes){
    const ds=(p.x-x)**2+(p.z-z)**2;
    const layer=(p.ry-BOTTOM)/(TOP-BOTTOM);
    p.pull=Math.exp(-ds/1.22)*(.28+.72*layer);
    p.vy-=2.7*Math.exp(-ds/.44)*layer;
    p.vx+=(p.x-x)*.64*Math.exp(-ds/.77)*layer;
    p.vz+=(p.z-z)*.64*Math.exp(-ds/.77)*layer;
  }
  if(withGrab) grab={dx:0,dy:-.36,dz:0};
  busy=Math.max(busy,2.7);
}
function release() {
  grab=null;
  stage.dataset.grabbing="false";
  busy=Math.max(busy,2.9);
}
const ray=new T.Raycaster(),pointer=new T.Vector2();
const dragPlane=new T.Plane(new T.Vector3(0,1,0),-TOP);
const rayStart=new T.Vector3(),rayCurrent=new T.Vector3();
let pointerId=null,downX=0,downY=0;
function setRay(event) {
  const rect=stage.getBoundingClientRect();
  pointer.set((event.clientX-rect.left)/rect.width*2-1,1-(event.clientY-rect.top)/rect.height*2);
  ray.setFromCamera(pointer,camera);
}
stage.addEventListener("pointerdown",event=>{
  if(pointerId!==null || event.button!==0) return;
  setRay(event);
  const hits=ray.intersectObjects([pithMesh,peelMesh],false);
  if(!hits.length || !ray.ray.intersectPlane(dragPlane,rayStart)) return;
  event.preventDefault();
  pointerId=event.pointerId;
  stage.setPointerCapture(pointerId);
  stage.dataset.grabbing="true";
  downX=event.clientX;downY=event.clientY;
  poke(hits[0].point.x,hits[0].point.z,true);
});
stage.addEventListener("pointermove",event=>{
  if(event.pointerId!==pointerId || !grab) return;
  setRay(event);
  if(!ray.ray.intersectPlane(dragPlane,rayCurrent)) return;
  const x=rayCurrent.x-rayStart.x,z=rayCurrent.z-rayStart.z;
  const move=Math.hypot(x,z),screenMove=Math.hypot(event.clientX-downX,event.clientY-downY);
  const stretch=Math.min(1,.98/Math.max(.001,move));
  grab.dx=x*stretch;
  grab.dz=z*stretch;
  grab.dy=mix(-.36,.34,Math.min(1,screenMove/70));
});
function endPointer(event){
  if(event.pointerId!==pointerId) return;
  pointerId=null;release();
}
stage.addEventListener("pointerup",endPointer);
stage.addEventListener("pointercancel",endPointer);
stage.addEventListener("lostpointercapture",endPointer);
firmnessInput.addEventListener("input",()=>{stopDemo();setFirmness(firmnessInput.value);});
squeezeButton.addEventListener("click",()=>{stopDemo();squeeze();});
resetButton.addEventListener("click",()=>{stopDemo();reset();setFirmness(52);});

let demo=location.hash==="#demo", demoStart=null, demoPhase=-1;
if(demo) status.textContent="Demo playing";
function stopDemo() {
  if(!demo) return;
  demo=false;
  status.textContent="Live simulation";
  if(grab) release();
}
window.addEventListener("pointerdown",event=>{if(event.isTrusted) stopDemo();},true);
function playDemo(now) {
  if(demoStart===null) demoStart=now;
  const t=(now-demoStart)/1000;
  if(t>=20) {demoStart=now;demoPhase=-1;return;}
  const phase=t<1.1?0:t<3.1?1:t<5?2:t<8.2?3:t<10.6?4:t<14?5:t<16?6:t<18.65?7:8;
  if(phase!==demoPhase){
    demoPhase=phase;
    if(phase===0){reset();setFirmness(52);}
    if(phase===1) poke(.45,.71,false);
    if(phase===2) poke(-.87,.13,false);
    if(phase===3) poke(.94,.45,true);
    if(phase===4) release();
    if(phase===5) squeeze();
    if(phase===6) setFirmness(17);
    if(phase===7) poke(-.44,.96,false);
    if(phase===8){reset();setFirmness(52);}
  }
  if(phase===3 && grab){
    const s=clamp((t-5)/1.75,0,1);
    const e=s*s*(3-2*s);
    grab.dx=.95*e;grab.dz=.44*e;grab.dy=mix(-.27,.47,e);
  }
}
const dt=1/120;
let previous=performance.now(),accumulator=0;
updateMeshes();
function frame(now){
  requestAnimationFrame(frame);
  const elapsed=clamp((now-previous)/1000,0,.05);
  previous=now;
  if(demo) playDemo(now);
  if(busy>0 || grab || squeezeTime>=0) {
    busy-=elapsed;
    accumulator+=elapsed;
    while(accumulator>=dt){
      step(dt);
      accumulator-=dt;
    }
    updateMeshes();
  }else accumulator=0;
  updateDrops(elapsed);
  renderer.render(scene,camera);
}
requestAnimationFrame(frame);
})();
</script>
</body>
</html>