Skip to content
VibeCodeBench
Back to the app

The code

Jelly Orange Slice by GPT-6.1 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.)46.5 KB · 561 lines · loads cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js
Download
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#f5f1e8">
<title>Jelly — a little slice of sunshine</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Cpath d='M6 26a26 26 0 0 0 52 0Z' fill='%23f58a20'/%3E%3Cpath d='M12 28a20 20 0 0 0 40 0Z' fill='%23fff0c5'/%3E%3Cpath d='M16 30a16 16 0 0 0 32 0Z' fill='%23ffb339'/%3E%3C/svg%3E">
<style>
:root{--paper:#f5f1e8;--ink:#353b2f;--muted:#8c8c7a;--orange:#ed761c;--line:rgba(81,76,51,.13);--serif:Georgia,'Times New Roman',serif;--sans:Arial,Helvetica,sans-serif}
*{box-sizing:border-box}html,body{width:100%;height:100%;margin:0}body{overflow:hidden;background:radial-gradient(ellipse at 66% 41%,#fffdf6 0%,#f5f1e8 57%,#efebdf 100%);color:var(--ink);font-family:var(--sans);-webkit-font-smoothing:antialiased}button,input{-webkit-tap-highlight-color:transparent}button{font:inherit}button:focus-visible,input:focus-visible{outline:3px solid #bf7f38;outline-offset:5px}button{cursor:pointer}button:disabled{cursor:wait}svg{display:block}button svg{flex-shrink:0}[hidden]{display:none!important}
.grain{position:fixed;inset:0;z-index:9;pointer-events:none;opacity:.035;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='180' height='180'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' opacity='.6' filter='url(%23n)'/%3E%3C/svg%3E")}
.masthead{position:absolute;inset:0 0 auto;z-index:5;display:flex;align-items:center;justify-content:space-between;padding:35px 6.2vw}.brand{display:flex;align-items:center;gap:13px}.brand-mark{width:35px;height:35px;transform:rotate(-14deg)}.wordmark{font-family:var(--serif);font-size:35px;font-weight:400;letter-spacing:-1.7px;line-height:1}.brand-separator{height:22px;width:1px;background:var(--line);margin:0 5px 0 10px}.brand-description{font-size:10px;line-height:1.6;letter-spacing:1.4px;text-transform:uppercase;color:#81816f}.top-right{display:flex;align-items:center;gap:27px}.edition{font-size:10px;letter-spacing:1.8px;color:#858572}.live-badge{display:flex;align-items:center;gap:8px;padding:10px 13px;border:1px solid #dcded0;border-radius:100px;font-size:9px;letter-spacing:1.3px;background:#ffffff35}.live-dot{width:6px;height:6px;border-radius:50%;background:#7f9663;box-shadow:0 0 0 3px #8d9a7010}
.intro{position:absolute;top:24.5%;left:7.1%;z-index:3;pointer-events:none;max-width:440px}.eyebrow{display:flex;align-items:center;gap:10px;font-size:10px;letter-spacing:2.4px;color:#93907a;margin:0 0 23px}.eyebrow:before{content:'';display:block;width:23px;height:1px;background:#c3bba2}h1{font-family:var(--serif);font-weight:400;font-size:clamp(57px,5.55vw,88px);line-height:1.035;letter-spacing:-3.8px;margin:0}h1 em{font-weight:400;color:var(--orange);letter-spacing:-3.5px}.intro-copy{font-size:14px;line-height:1.85;color:#8a8978;margin:25px 0 0}.intro-instruction{display:flex;align-items:center;gap:10px;margin-top:34px;font-size:11px;color:#6f7561;letter-spacing:.1px}.intro-instruction svg{color:#8b9777}.margin-note{position:absolute;z-index:3;left:7.1%;bottom:6.5%;display:flex;align-items:center;gap:16px;color:#96937f;font-size:10px;letter-spacing:1.3px}.margin-note .number{font-family:var(--serif);font-size:36px;font-style:italic;color:#a7a18a;line-height:1}.margin-note .rule{width:29px;height:1px;background:#cac4b0}.margin-note span:last-child{line-height:1.9}
#stage{position:absolute;z-index:1;left:26%;right:0;top:6%;height:81%;touch-action:none}#world{display:block;width:100%;height:100%;outline:0;cursor:grab;touch-action:none}#world.dragging{cursor:grabbing}.scene-note{position:absolute;bottom:5.5%;left:51%;transform:translateX(-50%);white-space:nowrap;display:flex;align-items:center;gap:10px;pointer-events:none;color:#92907b;font-size:10px;letter-spacing:.35px;transition:opacity .4s}.scene-note .sparkle{color:#c59954;font-size:17px}.annotation{position:absolute;top:21%;left:62%;pointer-events:none;color:#99967f;font-family:var(--serif);font-size:17px;font-style:italic;transform:rotate(-8deg);transition:opacity 1s}.annotation svg{position:absolute;top:25px;left:10px;width:52px;height:46px;opacity:.55}.annotation.dismissed{opacity:0}.pointer-ring{position:absolute;z-index:4;left:0;top:0;width:38px;height:38px;margin:-19px;border:1px solid #e7963f;border-radius:50%;pointer-events:none;opacity:0}.pointer-ring.pulse{animation:poke-ring .6s ease-out forwards}@keyframes poke-ring{0%{opacity:.8;transform:scale(.3)}100%{opacity:0;transform:scale(2)}}
.controls{position:absolute;z-index:6;right:6.2%;bottom:5.7%;width:min(650px,55vw);padding:21px 23px 15px;border:1px solid #ffffffbd;border-radius:23px;background:rgba(255,254,249,.83);box-shadow:0 12px 45px #6a56200c,0 1px 3px #6a562005;backdrop-filter:blur(15px);-webkit-backdrop-filter:blur(15px)}.control-main{display:grid;grid-template-columns:160px 1fr 65px;gap:25px;align-items:center}.squeeze{height:58px;border:0;border-radius:15px;display:flex;align-items:center;justify-content:center;gap:11px;color:#fffdf4;background:var(--orange);box-shadow:0 5px 13px #db741521,inset 0 1px 0 #ffffff29;transition:background .2s,transform .2s,box-shadow .2s;font-size:13px;letter-spacing:.2px}.squeeze:hover{background:#df6a14}.squeeze:active,.squeeze.is-squeezing{transform:scale(.97);background:#d96d16;box-shadow:inset 0 2px 6px #a44a1426}.squeeze svg{width:21px;height:21px}.firmness{min-width:0}.range-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:3px;font-size:11px}.range-heading output{font-size:10px;color:#96927c;font-variant-numeric:tabular-nums}.range-wrap{height:30px;display:flex;align-items:center}input[type=range]{--fill:42%;width:100%;height:26px;margin:0;appearance:none;-webkit-appearance:none;background:transparent;cursor:pointer;touch-action:pan-y}input[type=range]::-webkit-slider-runnable-track{height:3px;background:linear-gradient(to right,#b5b99b 0%,#b5b99b var(--fill),#e8e6d9 var(--fill),#e8e6d9 100%);border-radius:5px}input[type=range]::-moz-range-track{height:3px;background:#e8e6d9;border-radius:5px}input[type=range]::-moz-range-progress{height:3px;background:#b5b99b;border-radius:5px}input[type=range]::-webkit-slider-thumb{appearance:none;-webkit-appearance:none;height:18px;width:18px;margin-top:-7.5px;background:#fffefa;border:1px solid #b6b99c;border-radius:50%;box-shadow:0 2px 5px #585f3920}input[type=range]::-moz-range-thumb{height:17px;width:17px;background:#fffefa;border:1px solid #b6b99c;border-radius:50%;box-shadow:0 2px 5px #585f3920}.range-ends{display:flex;justify-content:space-between;font-size:8px;letter-spacing:1.2px;color:#a29f89;margin-top:-1px}.reset{border:0;border-left:1px solid var(--line);background:transparent;color:#848571;display:flex;flex-direction:column;align-items:center;gap:7px;padding:5px 0 5px 18px;font-size:10px;transition:color .2s}.reset:hover{color:#d67123}.reset svg{width:20px;height:20px}.control-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;border-top:1px solid #e8e6da;margin-top:17px;padding-top:12px;color:#92907b;font-size:10px;letter-spacing:.2px}.state{display:flex;align-items:center;gap:7px}.state-dot{height:5px;width:5px;border-radius:50%;background:#91a071;transition:background .3s}.state-dot.active{background:#e8953c}.physics-note{font-size:8px;letter-spacing:1.4px;color:#aaa590}.demo-badge{position:absolute;top:91px;right:6.2%;z-index:7;background:#fff9ed;border:1px solid #ead6b6;padding:12px 15px 15px;border-radius:13px;overflow:hidden;box-shadow:0 4px 14px #98742208;display:flex;align-items:center;gap:9px;color:#9f753b;font-size:9px;letter-spacing:1.3px}.demo-badge .demo-dot{width:5px;height:5px;border-radius:50%;background:#e38c2e}.demo-badge small{font-size:9px;letter-spacing:0;color:#a79c86;margin-left:8px}.demo-track{position:absolute;left:0;bottom:0;height:2px;background:#e8ac59;width:100%;transform-origin:left;transform:scaleX(0)}
.loader,.fallback{position:absolute;top:45%;left:50%;transform:translate(-50%,-50%);text-align:center;color:#93876e;font-size:12px;line-height:1.8;max-width:300px;pointer-events:none}.loader{transition:opacity .4s}.loader-circle{height:25px;width:25px;border:1px solid #d9ccb2;border-top-color:var(--orange);border-radius:50%;margin:0 auto 14px;animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.fallback strong{font-family:var(--serif);font-size:27px;font-weight:400;color:#655a43}.fallback p{font-size:12px}.ready .loader{opacity:0}.ready #world{animation:appear .8s ease-out both}@keyframes appear{from{opacity:0}to{opacity:1}}
@media(min-width:1600px){.intro{top:26%}.controls{bottom:7%;right:9%}#stage{left:25%;right:3%}.masthead{padding-top:43px}.scene-note{bottom:8%}}
@media(max-width:1100px) and (min-width:701px){.brand-description,.brand-separator{display:none}.intro{left:6%;top:25%;max-width:350px}h1{font-size:62px;letter-spacing:-3px}.intro-copy{font-size:12px}.controls{width:58vw;right:5%;padding:20px}.control-main{grid-template-columns:133px 1fr 48px;gap:19px}.reset{padding-left:12px}#stage{left:24%;top:10%;height:74%}.annotation{left:65%;top:17%;font-size:15px}.margin-note{left:6%}.edition{display:none}}
@media(max-width:700px){.masthead{padding:23px 23px}.wordmark{font-size:31px}.brand-mark{width:29px;height:29px}.brand{gap:10px}.brand-description,.brand-separator,.edition{display:none}.live-badge{padding:8px 10px;font-size:8px;letter-spacing:1px}.top-right{gap:0}.intro{left:26px;top:13.1%;max-width:360px}.eyebrow{font-size:8px;letter-spacing:1.9px;margin-bottom:14px}.eyebrow:before{width:17px}h1{font-size:clamp(40px,11.5vw,57px);letter-spacing:-2.3px;line-height:1.04}h1 em{letter-spacing:-2.5px}.intro-copy,.intro-instruction,.margin-note{display:none}#stage{left:0;right:0;top:25%;height:54%}.annotation{top:18%;left:66%;font-size:14px}.annotation svg{width:36px;height:36px;top:18px;left:7px}.scene-note{bottom:1%;left:50%;font-size:10px;gap:7px}.controls{left:17px;right:17px;bottom:max(20px,env(safe-area-inset-bottom));width:auto;padding:18px 17px 14px;border-radius:21px}.control-main{grid-template-columns:118px minmax(90px,1fr) 43px;gap:16px}.squeeze{height:54px;font-size:12px;gap:7px;border-radius:13px}.squeeze svg{width:18px;height:18px}.reset{padding-left:11px;font-size:9px;gap:5px}.reset svg{width:18px;height:18px}.range-heading{font-size:10px}.range-heading output{font-size:9px}.range-ends{font-size:7px;letter-spacing:1px}.control-foot{margin-top:14px;padding-top:11px;font-size:9px}.physics-note{font-size:7px;letter-spacing:.9px}.demo-badge{top:76px;right:23px;padding:9px 10px 12px;font-size:8px;gap:6px}.demo-badge small{display:none}}
@media(max-height:700px) and (max-width:700px){.masthead{padding-top:16px}.intro{top:15%}.eyebrow{margin-bottom:9px}h1{font-size:40px}#stage{top:27%;height:49%}.controls{bottom:12px;padding-top:14px;padding-bottom:11px}.control-foot{margin-top:10px;padding-top:9px}.annotation{display:none}.scene-note{bottom:-1%}.demo-badge{top:64px}}
@media(prefers-reduced-motion:reduce){.ready #world{animation:none}.pointer-ring.pulse{animation:none}.loader-circle{animation-duration:2s}*{scroll-behavior:auto!important}}
</style>
</head>
<body>
<div class="grain" aria-hidden="true"></div>
<header class="masthead">
  <div class="brand" aria-label="Jelly, a sensory playground">
    <svg class="brand-mark" viewBox="0 0 40 40" aria-hidden="true"><path d="M3 16a17 17 0 0 0 34 0Z" fill="#ed861f"/><path d="M6.5 17a13.5 13.5 0 0 0 27 0Z" fill="#fff0c5"/><path d="M9 18a11 11 0 0 0 22 0Z" fill="#f4b144"/><path d="m20 18-6.5 8M20 18v11m0-11 6.5 8" stroke="#fff1c9" stroke-width="1.2"/></svg>
    <span class="wordmark">jelly.</span><span class="brand-separator"></span><span class="brand-description">a sensory<br>playground</span>
  </div>
  <div class="top-right"><span class="edition">THE CITRUS STUDY &nbsp; / &nbsp; 01</span><span class="live-badge"><i class="live-dot"></i>LIVE PHYSICS</span></div>
</header>
<main>
  <section class="intro" aria-labelledby="title"><p class="eyebrow">A SMALL EXPERIMENT IN SOFTNESS</p><h1 id="title">A little slice<br>of <em>sunshine.</em></h1><p class="intro-copy">All the glow of a fresh orange.<br>A delightfully different kind of squeeze.</p><p class="intro-instruction"><svg width="20" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 12V5a1.5 1.5 0 0 1 3 0v6-2a1.5 1.5 0 0 1 3 0v3-1a1.5 1.5 0 0 1 3 0v3-1a1.5 1.5 0 0 1 3 0v4c0 4-2.5 6-6 6-2.5 0-4-1-5.5-3L6 16a1.5 1.5 0 0 1 2-2l2 2"/><path d="M5 5 3 4m3 5H3m5-7L7 0"/></svg>Poke, pull, and enjoy the little wobble.</p></section>
  <div id="stage">
    <canvas id="world" aria-label="Interactive 3D orange jelly on a porcelain plate. Touch or click to poke; drag to stretch and release to jiggle."></canvas>
    <div class="annotation" id="annotation" aria-hidden="true">a soft spot for citrus<svg viewBox="0 0 60 50" fill="none" stroke="currentColor" stroke-width="1"><path d="M45 3C48 23 36 39 10 39M17 31l-8 8 11 5"/></svg></div>
    <div class="scene-note" id="sceneNote"><span class="sparkle" aria-hidden="true">✳</span><span id="sceneNoteText">Poke it. Pull it. Let it wobble.</span></div>
    <div class="pointer-ring" id="pointerRing" aria-hidden="true"></div>
    <div class="loader" id="loader"><div class="loader-circle"></div>Setting the table…</div>
    <div class="fallback" id="fallback" hidden><strong>A small pause.</strong><p id="errorText">The 3D scene needs WebGL and a connection to the three.js library. Please reload when they’re available.</p></div>
  </div>
  <section class="controls" aria-label="Jelly controls">
    <div class="control-main">
      <button class="squeeze" id="squeeze" type="button" disabled aria-label="Squeeze the orange jelly to release a few drops of juice"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 10h10M9 7l3 3 3-3M12 3v7M5 15c0-1.7 3.1-3 7-3s7 1.3 7 3v3c0 1.7-3.1 3-7 3s-7-1.3-7-3Z"/><path d="M5 15c0 1.7 3.1 3 7 3s7-1.3 7-3"/></svg><span id="squeezeLabel">Squeeze</span></button>
      <div class="firmness"><div class="range-heading"><label for="firmness">Firmness</label><output for="firmness" id="firmnessValue">42%</output></div><div class="range-wrap"><input type="range" id="firmness" min="0" max="100" value="42" aria-label="Jelly firmness" disabled></div><div class="range-ends" aria-hidden="true"><span>SOFT</span><span>FIRM</span></div></div>
      <button class="reset" id="reset" type="button" disabled aria-label="Reset the jelly and clear the juice"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 10a8 8 0 1 1 1.8 8.2M4 4v6h6"/></svg><span>Reset</span></button>
    </div>
    <div class="control-foot"><span class="state" role="status" aria-live="polite"><i class="state-dot" id="stateDot"></i><span id="stateText">Preparing your slice</span></span><span class="physics-note">A MOMENT OF PLAY</span></div>
  </section>
  <div class="margin-note" aria-hidden="true"><span class="number">01</span><span class="rule"></span><span>ORANGE JELLY<br>FRESH FROM THE SIMULATION</span></div>
  <div class="demo-badge" id="demoBadge" hidden><i class="demo-dot"></i>GUIDED DEMO<small>touch to take over</small><div class="demo-track" id="demoProgress"></div></div>
</main>
<noscript><p style="position:fixed;bottom:170px;left:20px;right:20px;text-align:center">Enable JavaScript to play with the jelly.</p></noscript>
<script type="module">
const $ = id => document.getElementById(id);
function showFailure(error) {
  $('loader').hidden = true;
  $('fallback').hidden = false;
  $('stateText').textContent = '3D is taking a little pause';
  console.error('Unable to prepare the jelly:', error);
}
import('https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js').then(boot).catch(showFailure);

function boot(THREE) {
  'use strict';
  const canvas = $('world'), stage = $('stage');
  const mobile = matchMedia('(max-width: 700px)').matches;
  const renderer = new THREE.WebGLRenderer({canvas, antialias:true, alpha:true, powerPreference:'high-performance'});
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, mobile ? 1.7 : 2));
  renderer.setClearColor(0x000000, 0);
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.13;
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(33, 1, .1, 100);
  const viewDirection = new THREE.Vector3(3.65, 8.8, 10.8).normalize();
  const lookAt = new THREE.Vector3(0, .34, -.12);

  // All visual assets, including reflections and textures, are synthesized here.
  let seed = 74191;
  function random() {seed = (Math.imul(seed, 1664525) + 1013904223) | 0; return (seed >>> 0) / 4294967296;}
  const clamp = (v,a,b) => Math.max(a,Math.min(b,v));
  const smooth = v => {v=clamp(v,0,1);return v*v*(3-2*v);};
  function makeCanvas(w,h) {const c=document.createElement('canvas');c.width=w;c.height=h;return c;}
  function canvasTexture(c) {const t=new THREE.CanvasTexture(c);t.colorSpace=THREE.SRGBColorSpace;t.anisotropy=Math.min(8,renderer.capabilities.getMaxAnisotropy());return t;}

  const envCanvas=makeCanvas(1024,512), ec=envCanvas.getContext('2d');
  const sky=ec.createLinearGradient(0,0,0,512);
  sky.addColorStop(0,'#dcd9cf');sky.addColorStop(.4,'#f6f1e4');sky.addColorStop(.6,'#b6ae99');sky.addColorStop(1,'#aaa18e');
  ec.fillStyle=sky;ec.fillRect(0,0,1024,512);
  ec.fillStyle='#ffffff';ec.fillRect(95,55,240,190);ec.fillRect(700,92,105,220);
  ec.fillStyle='#fff9e8';ec.fillRect(420,36,155,112);
  ec.fillStyle='#e5dfd2';ec.fillRect(0,290,1024,13);
  const envTexture=canvasTexture(envCanvas);envTexture.mapping=THREE.EquirectangularReflectionMapping;
  const pmrem=new THREE.PMREMGenerator(renderer);pmrem.compileEquirectangularShader();
  const envMap=pmrem.fromEquirectangular(envTexture).texture;
  scene.environment=envMap;envTexture.dispose();pmrem.dispose();
  scene.add(new THREE.HemisphereLight(0xfffbef,0xc7a476,2.0));
  const key=new THREE.DirectionalLight(0xfff7e8,3.4);key.position.set(-3.5,8,5);key.castShadow=true;
  key.shadow.mapSize.set(mobile?1024:2048,mobile?1024:2048);
  Object.assign(key.shadow.camera,{left:-5,right:5,top:5,bottom:-5,near:.5,far:20});
  key.shadow.bias=-.0003;key.shadow.normalBias=.017;key.shadow.radius=4;scene.add(key);
  const backlight=new THREE.DirectionalLight(0xffe6af,3.1);backlight.position.set(1,4,-5);scene.add(backlight);
  const fill=new THREE.DirectionalLight(0xffffff,1.1);fill.position.set(6,3,4);scene.add(fill);

  const floor=new THREE.Mesh(new THREE.PlaneGeometry(200,200),new THREE.ShadowMaterial({color:0x806b4b,opacity:.14}));
  floor.rotation.x=-Math.PI/2;floor.position.y=-.018;floor.receiveShadow=true;scene.add(floor);
  const profile=[[0,.035],[1.5,.035],[2.1,.055],[2.7,.10],[3.15,.18],[3.43,.25],[3.49,.30],[3.46,.333],[3.38,.35],[3.24,.335],[3.13,.307],[2.85,.242],[2.50,.205],[0,.205]].map(p=>new THREE.Vector2(...p));
  const plate=new THREE.Mesh(new THREE.LatheGeometry(profile,128),new THREE.MeshPhysicalMaterial({color:0xfffefa,roughness:.20,metalness:0,clearcoat:1,clearcoatRoughness:.16,ior:1.48}));
  plate.castShadow=true;plate.receiveShadow=true;scene.add(plate);
  const rim=new THREE.Mesh(new THREE.TorusGeometry(3.34,.009,6,160),new THREE.MeshStandardMaterial({color:0xf8f7ed,roughness:.27}));
  rim.rotation.x=Math.PI/2;rim.position.y=.348;scene.add(rim);
  const shadowCanvas=makeCanvas(128,128), sc=shadowCanvas.getContext('2d');
  const sg=sc.createRadialGradient(64,64,8,64,64,64);sg.addColorStop(0,'rgba(105,55,11,.23)');sg.addColorStop(.5,'rgba(123,68,16,.13)');sg.addColorStop(1,'rgba(123,68,16,0)');sc.fillStyle=sg;sc.fillRect(0,0,128,128);
  const contact=new THREE.Mesh(new THREE.PlaneGeometry(5.4,3.8),new THREE.MeshBasicMaterial({map:canvasTexture(shadowCanvas),transparent:true,depthWrite:false,opacity:.72}));
  contact.rotation.x=-Math.PI/2;contact.position.set(0,.210,-.25);scene.add(contact);

  // Tetrahedral XPBD: edge elasticity and signed-volume constraints, gravity,
  // unilateral plate contact, friction, and physical local drag constraints.
  const R=2.19, Z0=.64, BASE=.235, TOP=.985, A=32, RAD=6, LAYERS=3;
  const PER_LAYER=1+RAD*(A+1), COUNT=PER_LAYER*LAYERS;
  const rest=new Float32Array(COUNT*3), pos=new Float32Array(COUNT*3);
  const old=new Float32Array(COUNT*3), vel=new Float32Array(COUNT*3);
  const pid=(l,r,a)=>l*PER_LAYER+(r===0?0:1+(r-1)*(A+1)+a);
  for(let l=0;l<LAYERS;l++){
    const y=BASE+(TOP-BASE)*l/(LAYERS-1);
    rest.set([0,y,Z0],pid(l,0,0)*3);
    for(let r=1;r<=RAD;r++) for(let a=0;a<=A;a++){
      const theta=a/A*Math.PI, radius=r/RAD*R;
      rest.set([radius*Math.cos(theta),y,Z0-radius*Math.sin(theta)],pid(l,r,a)*3);
    }
  }
  pos.set(rest);old.set(rest);
  const triangles=[];
  for(let a=0;a<A;a++) triangles.push([0,pid(0,1,a),pid(0,1,a+1)]);
  for(let r=1;r<RAD;r++) for(let a=0;a<A;a++){
    const p=pid(0,r,a),q=pid(0,r+1,a),s=pid(0,r,a+1),t=pid(0,r+1,a+1);
    triangles.push([p,q,s],[q,t,s]);
  }
  const tetList=[];
  for(let l=0;l<LAYERS-1;l++) for(const tri of triangles){
    const [a,b,c]=[...tri].sort((x,y)=>x-y).map(v=>v+l*PER_LAYER);
    const ap=a+PER_LAYER,bp=b+PER_LAYER,cp=c+PER_LAYER;
    tetList.push([a,b,c,cp],[a,b,bp,cp],[a,ap,bp,cp]);
  }
  function signedVolume(arr,a,b,c,d){
    a*=3;b*=3;c*=3;d*=3;
    const bx=arr[b]-arr[a],by=arr[b+1]-arr[a+1],bz=arr[b+2]-arr[a+2];
    const cx=arr[c]-arr[a],cy=arr[c+1]-arr[a+1],cz=arr[c+2]-arr[a+2];
    const dx=arr[d]-arr[a],dy=arr[d+1]-arr[a+1],dz=arr[d+2]-arr[a+2];
    return (bx*(cy*dz-cz*dy)+by*(cz*dx-cx*dz)+bz*(cx*dy-cy*dx))/6;
  }
  const tets=new Uint16Array(tetList.length*4), volumes=new Float32Array(tetList.length), volumeLambda=new Float32Array(tetList.length);
  const uniqueEdges=new Set(), edgeList=[];
  tetList.forEach((tet,i)=>{
    if(signedVolume(rest,...tet)<0) [tet[1],tet[2]]=[tet[2],tet[1]];
    tets.set(tet,i*4);volumes[i]=signedVolume(rest,...tet);
    for(let j=0;j<4;j++) for(let k=j+1;k<4;k++){
      const a=Math.min(tet[j],tet[k]),b=Math.max(tet[j],tet[k]),key=a*COUNT+b;
      if(!uniqueEdges.has(key)){uniqueEdges.add(key);edgeList.push([a,b]);}
    }
  });
  const edges=new Uint16Array(edgeList.length*2), lengths=new Float32Array(edgeList.length), edgeLambda=new Float32Array(edgeList.length);
  edgeList.forEach(([a,b],i)=>{edges.set([a,b],i*2);lengths[i]=Math.hypot(rest[a*3]-rest[b*3],rest[a*3+1]-rest[b*3+1],rest[a*3+2]-rest[b*3+2]);});

  let firmness=.42, grip=null, pointer=null, pressure=0, squeezeStart=-100, squeezeDrops=0, nextDrop=0;
  let now=0, averageSpeed=0, lastStatus='', noteUntil=0;
  const fixedDT=1/120;
  function plateHeight(x,z){
    const r=Math.hypot(x,z);
    if(r<=2.5)return .205;
    if(r<2.85)return .205+(r-2.5)/.35*.037;
    if(r<3.13)return .242+(r-2.85)/.28*.065;
    return .307+clamp((r-3.13)/.25,0,1)*.043;
  }
  function collide(){
    const ceiling=TOP-.255*pressure;
    for(let i=0;i<COUNT;i++){
      const j=i*3;
      const radius=Math.hypot(pos[j],pos[j+2]);
      if(radius>3.23){const s=3.23/radius;pos[j]*=s;pos[j+2]*=s;}
      const h=plateHeight(pos[j],pos[j+2])+.014;
      if(pos[j+1]<h)pos[j+1]=h;
      if(pressure>.002 && pos[j+1]>ceiling)pos[j+1]=Math.max(h,ceiling+(pos[j+1]-ceiling)*.08);
      pos[j+1]=Math.min(3.0,pos[j+1]);
    }
  }
  function solveEdges(dt){
    const alpha=(.00062*Math.pow(1-firmness,2)+.000009)/(dt*dt);
    for(let e=0;e<lengths.length;e++){
      const a=edges[e*2]*3,b=edges[e*2+1]*3;
      const dx=pos[a]-pos[b],dy=pos[a+1]-pos[b+1],dz=pos[a+2]-pos[b+2];
      const len=Math.sqrt(dx*dx+dy*dy+dz*dz);
      if(len<1e-8)continue;
      let dl=(-(len-lengths[e])-alpha*edgeLambda[e])/(2+alpha);
      dl=clamp(dl,-.045,.045);edgeLambda[e]+=dl;
      const s=dl/len,x=dx*s,y=dy*s,z=dz*s;
      pos[a]+=x;pos[a+1]+=y;pos[a+2]+=z;pos[b]-=x;pos[b+1]-=y;pos[b+2]-=z;
    }
  }
  function solveVolumes(dt){
    const normalAlpha=2.5e-8/(dt*dt);
    for(let t=0;t<volumes.length;t++){
      const a=tets[t*4]*3,b=tets[t*4+1]*3,c=tets[t*4+2]*3,d=tets[t*4+3]*3;
      const bx=pos[b]-pos[a],by=pos[b+1]-pos[a+1],bz=pos[b+2]-pos[a+2];
      const cx=pos[c]-pos[a],cy=pos[c+1]-pos[a+1],cz=pos[c+2]-pos[a+2];
      const dx=pos[d]-pos[a],dy=pos[d+1]-pos[a+1],dz=pos[d+2]-pos[a+2];
      const gbx=(cy*dz-cz*dy)/6,gby=(cz*dx-cx*dz)/6,gbz=(cx*dy-cy*dx)/6;
      const gcx=(dy*bz-dz*by)/6,gcy=(dz*bx-dx*bz)/6,gcz=(dx*by-dy*bx)/6;
      const gdx=(by*cz-bz*cy)/6,gdy=(bz*cx-bx*cz)/6,gdz=(bx*cy-by*cx)/6;
      const gax=-gbx-gcx-gdx,gay=-gby-gcy-gdy,gaz=-gbz-gcz-gdz;
      const v=bx*gbx+by*gby+bz*gbz;
      const alpha=v<volumes[t]*.25?1e-10/(dt*dt):normalAlpha;
      const sum=gax*gax+gay*gay+gaz*gaz+gbx*gbx+gby*gby+gbz*gbz+gcx*gcx+gcy*gcy+gcz*gcz+gdx*gdx+gdy*gdy+gdz*gdz;
      let dl=(-(v-volumes[t])-alpha*volumeLambda[t])/(sum+alpha+1e-12);
      const maxG=Math.max(Math.hypot(gax,gay,gaz),Math.hypot(gbx,gby,gbz),Math.hypot(gcx,gcy,gcz),Math.hypot(gdx,gdy,gdz),.00001);
      dl=clamp(dl,-.032/maxG,.032/maxG);volumeLambda[t]+=dl;
      pos[a]+=dl*gax;pos[a+1]+=dl*gay;pos[a+2]+=dl*gaz;
      pos[b]+=dl*gbx;pos[b+1]+=dl*gby;pos[b+2]+=dl*gbz;
      pos[c]+=dl*gcx;pos[c+1]+=dl*gcy;pos[c+2]+=dl*gcz;
      pos[d]+=dl*gdx;pos[d+1]+=dl*gdy;pos[d+2]+=dl*gdz;
    }
  }
  function simulate(dt){
    old.set(pos);edgeLambda.fill(0);volumeLambda.fill(0);
    const damping=Math.exp(-(1.55+firmness*.8)*dt);
    for(let i=0;i<COUNT;i++){
      const j=i*3;
      vel[j]*=damping;vel[j+1]=(vel[j+1]-5.8*dt)*damping;vel[j+2]*=damping;
      const speed=Math.hypot(vel[j],vel[j+1],vel[j+2]);
      if(speed>7){const s=7/speed;vel[j]*=s;vel[j+1]*=s;vel[j+2]*=s;}
      pos[j]+=vel[j]*dt;pos[j+1]+=vel[j+1]*dt;pos[j+2]+=vel[j+2]*dt;
    }
    for(let it=0;it<5;it++){
      solveEdges(dt);solveVolumes(dt);
      if(grip){
        for(const g of grip.points){
          const j=g.i*3,s=.28*g.w;
          pos[j]+=clamp((grip.target.x+g.ox-pos[j])*s,-.06,.06);
          pos[j+1]+=clamp((grip.target.y+g.oy-pos[j+1])*s,-.06,.06);
          pos[j+2]+=clamp((grip.target.z+g.oz-pos[j+2])*s,-.06,.06);
        }
      }
      collide();
    }
    let energy=0;
    for(let i=0;i<COUNT;i++){
      const j=i*3;
      vel[j]=(pos[j]-old[j])/dt;vel[j+1]=(pos[j+1]-old[j+1])/dt;vel[j+2]=(pos[j+2]-old[j+2])/dt;
      if(pos[j+1]<plateHeight(pos[j],pos[j+2])+.018){vel[j]*=.86;vel[j+2]*=.86;if(vel[j+1]<0)vel[j+1]=0;}
      energy+=vel[j]*vel[j]+vel[j+1]*vel[j+1]+vel[j+2]*vel[j+2];
    }
    averageSpeed=energy/COUNT;
  }

  function binding(x,y,z){
    const radius=clamp(Math.hypot(x,z-Z0),0,R);
    const theta=clamp(Math.atan2(Math.max(0,Z0-z),x),0,Math.PI);
    const rf=radius/R*RAD, r0=Math.min(RAD-1,Math.floor(rf)),rt=rf-r0;
    const af=theta/Math.PI*A,a0=Math.min(A-1,Math.floor(af)),at=af-a0;
    const lf=clamp((y-BASE)/(TOP-BASE)*(LAYERS-1),0,LAYERS-1),l0=Math.min(LAYERS-2,Math.floor(lf)),lt=lf-l0;
    const ids=[],weights=[];
    let rx=0,ry=0,rz=0;
    for(let l=0;l<2;l++)for(let r=0;r<2;r++)for(let a=0;a<2;a++){
      const i=pid(l0+l,r0+r,a0+a),w=(l?lt:1-lt)*(r?rt:1-rt)*(a?at:1-at);
      ids.push(i);weights.push(w);rx+=rest[i*3]*w;ry+=rest[i*3+1]*w;rz+=rest[i*3+2]*w;
    }
    return {ids,weights,offset:[x-rx,y-ry,z-rz]};
  }
  function sample(b,out){
    let x=b.offset[0],y=b.offset[1],z=b.offset[2];
    for(let k=0;k<8;k++){const j=b.ids[k]*3,w=b.weights[k];x+=pos[j]*w;y+=pos[j+1]*w;z+=pos[j+2]*w;}
    out.set(x,y,z);return out;
  }
  const deformables=[],pickMeshes=[];
  function bindMesh(geometry,material,pickable=true){
    const mesh=new THREE.Mesh(geometry,material);mesh.castShadow=true;mesh.receiveShadow=true;
    const attr=geometry.attributes.position,n=attr.count;
    const ids=new Uint16Array(n*8),weights=new Float32Array(n*8),offsets=new Float32Array(n*3);
    for(let i=0;i<n;i++){
      const b=binding(attr.getX(i),attr.getY(i),attr.getZ(i));ids.set(b.ids,i*8);weights.set(b.weights,i*8);offsets.set(b.offset,i*3);
    }
    attr.setUsage(THREE.DynamicDrawUsage);geometry.computeBoundingSphere();
    mesh.frustumCulled=false;deformables.push({mesh,ids,weights,offsets});scene.add(mesh);if(pickable)pickMeshes.push(mesh);return mesh;
  }
  function sector(r0,r1,a0,a1,y0,y1,nr,na,dome=0){
    const p=[],uv=[],ind=[];
    function vertex(r,a,y,u,v){const x=r*Math.cos(a),z=Z0-r*Math.sin(a);p.push(x,y,z);uv.push(u===undefined ? .5+x/(R*2) : u,v===undefined ? .5-(z-Z0)/(R*2) : v);return p.length/3-1;}
    const cols=na+1,sideCount=(nr+1)*cols;
    for(let side=0;side<2;side++)for(let r=0;r<=nr;r++)for(let a=0;a<=na;a++){
      const rr=r0+(r1-r0)*r/nr,aa=a0+(a1-a0)*a/na;
      vertex(rr,aa,side?y0:y1+dome*Math.sin(Math.PI*r/nr)*Math.sin(Math.PI*a/na));
    }
    for(let side=0;side<2;side++)for(let r=0;r<nr;r++)for(let a=0;a<na;a++){
      const b=side*sideCount+r*cols+a,c=b+cols;
      if(side===0)ind.push(b,c,b+1,c,c+1,b+1);else ind.push(b,b+1,c,c,b+1,c+1);
    }
    function wall(points,reverse){
      const start=p.length/3;
      points.forEach(([r,a],i)=>{vertex(r,a,y0,i/(points.length-1),0);vertex(r,a,y1,i/(points.length-1),1);});
      for(let i=0;i<points.length-1;i++){const b=start+i*2;if(reverse)ind.push(b,b+2,b+1,b+1,b+2,b+3);else ind.push(b,b+1,b+2,b+1,b+3,b+2);}
    }
    wall(Array.from({length:na+1},(_,a)=>[r1,a0+(a1-a0)*a/na]),false);
    wall(Array.from({length:na+1},(_,a)=>[r0,a0+(a1-a0)*a/na]),true);
    wall(Array.from({length:nr+1},(_,r)=>[r0+(r1-r0)*r/nr,a0]),false);
    wall(Array.from({length:nr+1},(_,r)=>[r0+(r1-r0)*r/nr,a1]),true);
    const g=new THREE.BufferGeometry();g.setAttribute('position',new THREE.Float32BufferAttribute(p,3));g.setAttribute('uv',new THREE.Float32BufferAttribute(uv,2));g.setIndex(ind);g.computeVertexNormals();return g;
  }

  const pulpCanvas=makeCanvas(1024,1024),pc=pulpCanvas.getContext('2d');
  pc.fillStyle='#ffc15a';pc.fillRect(0,0,1024,1024);
  for(let s=0;s<8;s++)for(let i=0;i<250;i++){
    const theta=(s+.045+random()*.91)/8*Math.PI,r=.12+Math.sqrt(random())*(R-.36);
    const px=(.5+r*Math.cos(theta)/(R*2))*1024,py=(.5-r*Math.sin(theta)/(R*2))*1024;
    const length=5+random()*11,width=2.1+random()*3.2;
    pc.save();pc.translate(px,py);pc.rotate(-theta);
    const cell=pc.createRadialGradient(0,0,1,0,0,length);
    cell.addColorStop(0,random()>.4?'#ffd583':'#ffb33e');cell.addColorStop(.7,'#ffbf4d');cell.addColorStop(1,'#ffe7a0');
    pc.fillStyle=cell;pc.beginPath();pc.ellipse(0,0,length,width,0,0,Math.PI*2);pc.fill();
    pc.strokeStyle='rgba(255,246,185,.50)';pc.lineWidth=.65;pc.stroke();
    pc.beginPath();pc.ellipse(-length*.15,-width*.3,length*.55,.45,0,0,Math.PI*2);pc.fillStyle='rgba(255,251,215,.32)';pc.fill();pc.restore();
  }
  const pulpTexture=canvasTexture(pulpCanvas);
  const rindCanvas=makeCanvas(256,256),rc=rindCanvas.getContext('2d');
  rc.fillStyle='#ff9d18';rc.fillRect(0,0,256,256);
  for(let i=0;i<4500;i++){
    const x=random()*256,y=random()*256,r=.35+random()*1.25;
    rc.fillStyle=random()>.55?'rgba(190,85,4,.23)':'rgba(255,223,86,.50)';rc.beginPath();rc.ellipse(x,y,r,r*.75,0,0,Math.PI*2);rc.fill();
  }
  const rindTexture=canvasTexture(rindCanvas);rindTexture.wrapS=rindTexture.wrapT=THREE.RepeatWrapping;rindTexture.repeat.set(4,1.3);
  const pithCanvas=makeCanvas(128,128),wc=pithCanvas.getContext('2d');wc.fillStyle='#fff5d9';wc.fillRect(0,0,128,128);
  for(let i=0;i<1600;i++){wc.fillStyle=random()>.5?'#f1dfb9':'#fffce9';wc.fillRect(random()*128,random()*128,.6+random(),.6+random()*2);}
  const pithTexture=canvasTexture(pithCanvas);
  const pithMaterial=new THREE.MeshPhysicalMaterial({color:0xfff5d8,map:pithTexture,bumpMap:pithTexture,bumpScale:.008,roughness:.38,transmission:.17,thickness:.12,ior:1.34,clearcoat:.25,side:THREE.DoubleSide});
  const rindMaterial=new THREE.MeshPhysicalMaterial({color:0xffffff,map:rindTexture,bumpMap:rindTexture,bumpScale:.024,roughness:.30,transmission:.12,thickness:.16,ior:1.38,clearcoat:.78,clearcoatRoughness:.22,side:THREE.DoubleSide});
  const peelProfile=[[R-.125,TOP-.015],[R-.075,TOP+.008],[R-.022,TOP-.010],[R+.006,TOP-.065],[R+.008,BASE+.075],[R-.018,BASE+.020],[R-.075,BASE+.008],[R-.125,BASE+.025]];
  const peelP=[],peelUV=[],peelI=[],peelSteps=64;
  for(let a=0;a<=peelSteps;a++)for(let k=0;k<peelProfile.length;k++){
    const theta=a/peelSteps*Math.PI,[r,y]=peelProfile[k];peelP.push(r*Math.cos(theta),y,Z0-r*Math.sin(theta));peelUV.push(a/peelSteps,k/(peelProfile.length-1));
  }
  for(let a=0;a<peelSteps;a++)for(let k=0;k<peelProfile.length;k++){
    const n=(k+1)%peelProfile.length,b=a*peelProfile.length+k,c=a*peelProfile.length+n,d=(a+1)*peelProfile.length+k,e=(a+1)*peelProfile.length+n;
    peelI.push(b,d,c,c,d,e);
  }
  const peelG=new THREE.BufferGeometry();peelG.setAttribute('position',new THREE.Float32BufferAttribute(peelP,3));peelG.setAttribute('uv',new THREE.Float32BufferAttribute(peelUV,2));peelG.setIndex(peelI);peelG.computeVertexNormals();bindMesh(peelG,rindMaterial);
  bindMesh(sector(R-.222,R-.117,0,Math.PI,BASE+.014,TOP-.003,2,48,.004),pithMaterial);
  bindMesh(sector(.012,.145,0,Math.PI,BASE+.02,TOP+.012,2,24,.005),pithMaterial);
  for(let s=0;s<=8;s++){
    const a=s/8*Math.PI,gap=.006;
    bindMesh(sector(.115,R-.205,Math.max(0,a-gap),Math.min(Math.PI,a+gap),BASE+.018,TOP+.003,6,1,0),pithMaterial);
  }
  for(let s=0;s<8;s++){
    const material=new THREE.MeshPhysicalMaterial({color:new THREE.Color().setHSL(.105+s%3*.004,.94,.90),map:pulpTexture,bumpMap:pulpTexture,bumpScale:.010,roughness:.145,metalness:0,transmission:.61,thickness:.55,attenuationColor:new THREE.Color(0xffb02d),attenuationDistance:1.3,ior:1.355,clearcoat:1,clearcoatRoughness:.10,emissive:0xd86a00,emissiveIntensity:.025,side:THREE.DoubleSide});
    const a0=s/8*Math.PI+.011,a1=(s+1)/8*Math.PI-.011;
    bindMesh(sector(.15,R-.229,a0,a1,BASE+.025,TOP,7,6,.025),material);
  }
  // Individual juice vesicles, embedded beneath the glossy segment membrane.
  const CELL_COUNT=mobile?490:730;
  const cellGeometry=new THREE.SphereGeometry(1,7,5);
  const cellMaterial=new THREE.MeshPhysicalMaterial({color:0xfff3d4,roughness:.21,transmission:.24,thickness:.10,ior:1.34,clearcoat:1,clearcoatRoughness:.10,attenuationColor:0xffbc40,attenuationDistance:.5});
  const cells=new THREE.InstancedMesh(cellGeometry,cellMaterial,CELL_COUNT);cells.instanceMatrix.setUsage(THREE.DynamicDrawUsage);cells.frustumCulled=false;cells.castShadow=false;scene.add(cells);
  const cellData=[],dummy=new THREE.Object3D(),c1=new THREE.Vector3(),c2=new THREE.Vector3(),axis=new THREE.Vector3(0,0,1),direction=new THREE.Vector3();
  for(let i=0;i<CELL_COUNT;i++){
    const s=i%8,theta=(s+.065+random()*.87)/8*Math.PI,r=.23+Math.sqrt(random())*(R-.54);
    const y=TOP-.029+(random()-.5)*.037,x=r*Math.cos(theta),z=Z0-r*Math.sin(theta);
    const len=.042+random()*.048,width=.018+random()*.018,height=.024+random()*.020;
    cellData.push({b:binding(x,y,z),along:binding(x+.09*Math.cos(theta),y,z-.09*Math.sin(theta)),width,height,len});
    cells.setColorAt(i,new THREE.Color().setHSL(.085+random()*.033,.88,.57+random()*.15));
  }
  if(cells.instanceColor)cells.instanceColor.needsUpdate=true;

  const drops=[],dropGeometry=new THREE.SphereGeometry(1,12,9);
  const dropMaterial=new THREE.MeshPhysicalMaterial({color:0xffb22f,roughness:.10,transmission:.64,thickness:.09,ior:1.34,clearcoat:1,attenuationColor:0xffa41a,attenuationDistance:.35});
  const dropPoint=new THREE.Vector3();
  function emitDrop(){
    const x=(random()-.5)*2.8,y=TOP-.15,z=Z0+.022;
    sample(binding(x,y,z),dropPoint);
    const mesh=new THREE.Mesh(dropGeometry,dropMaterial.clone()),size=.035+random()*.018;
    mesh.position.copy(dropPoint);mesh.position.z+=.045;mesh.scale.set(size*.8,size*1.3,size*.8);mesh.castShadow=true;scene.add(mesh);
    drops.push({mesh,size,vx:(random()-.5)*.18,vy:-.08,vz:.09+random()*.07,age:0,landed:false});
    if(drops.length>35){const drop=drops.shift();scene.remove(drop.mesh);drop.mesh.material.dispose();}
  }
  function updateDrops(dt){
    for(let i=drops.length-1;i>=0;i--){
      const d=drops[i];d.age+=dt;
      if(!d.landed){
        d.vy-=3.7*dt;d.mesh.position.x+=d.vx*dt;d.mesh.position.y+=d.vy*dt;d.mesh.position.z+=d.vz*dt;
        d.mesh.scale.set(d.size*.76,d.size*(1.2+Math.min(.8,-d.vy*.3)),d.size*.76);
        const h=plateHeight(d.mesh.position.x,d.mesh.position.z)+.008;
        if(d.mesh.position.y<h+d.size*.15){d.mesh.position.y=h;d.landed=true;d.landAge=d.age;}
      }else{
        const spread=1-Math.exp(-(d.age-d.landAge)*12);
        d.mesh.scale.set(d.size*(.8+spread*1.5),d.size*(.35-spread*.22),d.size*(.8+spread*1.15));
        const life=clamp((12-d.age)/2,0,1);d.mesh.scale.multiplyScalar(life);
      }
      if(d.age>12){scene.remove(d.mesh);d.mesh.material.dispose();drops.splice(i,1);}
    }
  }

  function updateVisuals(){
    for(const d of deformables){
      const g=d.mesh.geometry,arr=g.attributes.position.array,n=arr.length/3;
      for(let i=0;i<n;i++){
        let x=d.offsets[i*3],y=d.offsets[i*3+1],z=d.offsets[i*3+2];
        for(let k=0;k<8;k++){const j=d.ids[i*8+k]*3,w=d.weights[i*8+k];x+=pos[j]*w;y+=pos[j+1]*w;z+=pos[j+2]*w;}
        arr[i*3]=x;arr[i*3+1]=y;arr[i*3+2]=z;
      }
      g.attributes.position.needsUpdate=true;g.computeVertexNormals();g.computeBoundingSphere();
    }
    for(let i=0;i<CELL_COUNT;i++){
      const c=cellData[i];sample(c.b,c1);sample(c.along,c2);direction.subVectors(c2,c1).normalize();
      dummy.position.copy(c1);dummy.quaternion.setFromUnitVectors(axis,direction);dummy.scale.set(c.width,c.height*(1-pressure*.23),c.len);dummy.updateMatrix();cells.setMatrixAt(i,dummy.matrix);
    }
    cells.instanceMatrix.needsUpdate=true;
  }
  function setNote(text,duration=2.8){$('sceneNoteText').textContent=text;noteUntil=now+duration;}
  function dismissAnnotation(){$('annotation').classList.add('dismissed');}
  function poke(point,strength=1){
    for(let i=0;i<COUNT;i++){
      const j=i*3,dx=pos[j]-point.x,dy=pos[j+1]-point.y,dz=pos[j+2]-point.z;
      const falloff=Math.exp(-(dx*dx+dz*dz+dy*dy*.6)/.28);
      vel[j+1]-=1.9*falloff*strength;vel[j]+=dx*.6*falloff*strength;vel[j+2]+=dz*.6*falloff*strength;
    }
    dismissAnnotation();
  }
  function makeGrip(point){
    const nearest=[];
    for(let i=0;i<COUNT;i++){const j=i*3,dx=pos[j]-point.x,dy=pos[j+1]-point.y,dz=pos[j+2]-point.z;nearest.push({i,d:dx*dx+dy*dy+dz*dz});}
    nearest.sort((a,b)=>a.d-b.d);
    const points=nearest.slice(0,18).map(({i,d})=>({i,w:Math.max(.12,Math.exp(-d/.20)),ox:pos[i*3]-point.x,oy:pos[i*3+1]-point.y,oz:pos[i*3+2]-point.z}));
    return {points,target:point.clone(),origin:point.clone()};
  }
  function squeeze(){
    if(now-squeezeStart<1.8)return;
    grip=null;squeezeStart=now;squeezeDrops=0;nextDrop=now+.38;dismissAnnotation();setNote('A little squeeze. A few drops of sunshine.',3.5);
  }
  function setFirmness(value){
    firmness=clamp(value/100,0,1);$('firmness').value=String(Math.round(value));$('firmnessValue').value=Math.round(value)+'%';$('firmness').style.setProperty('--fill',value+'%');
  }
  function resetSlice(withNote=true){
    pos.set(rest);old.set(rest);vel.fill(0);edgeLambda.fill(0);volumeLambda.fill(0);grip=null;pointer=null;pressure=0;squeezeStart=-100;squeezeDrops=0;averageSpeed=0;
    canvas.classList.remove('dragging');
    for(const d of drops){scene.remove(d.mesh);d.mesh.material.dispose();}drops.length=0;
    setFirmness(42);
    if(withNote){setNote('Fresh slice. A fresh start.');dismissAnnotation();}
  }
  $('firmness').addEventListener('input',e=>{setFirmness(Number(e.target.value));dismissAnnotation();setNote(firmness<.34?'Extra soft. Extra wobble.':firmness>.7?'A firmer little slice.':'Just the right amount of jelly.');});
  $('squeeze').addEventListener('click',squeeze);
  $('reset').addEventListener('click',()=>resetSlice());

  const raycaster=new THREE.Raycaster(),ndc=new THREE.Vector2(),dragPlane=new THREE.Plane(),planeNormal=new THREE.Vector3(),dragPoint=new THREE.Vector3(),dragDelta=new THREE.Vector3();
  function setRay(e){const rect=canvas.getBoundingClientRect();ndc.set((e.clientX-rect.left)/rect.width*2-1,-(e.clientY-rect.top)/rect.height*2+1);raycaster.setFromCamera(ndc,camera);}
  function hitAt(e){setRay(e);scene.updateMatrixWorld(true);return raycaster.intersectObjects(pickMeshes,false)[0];}
  canvas.addEventListener('pointerdown',e=>{
    if(e.pointerType==='mouse' && e.button!==0)return;
    if(pointer)return;
    const hit=hitAt(e);if(!hit)return;
    e.preventDefault();canvas.setPointerCapture(e.pointerId);
    pointer={id:e.pointerId,x:e.clientX,y:e.clientY,hit:hit.point.clone(),moved:false};
    camera.getWorldDirection(planeNormal);dragPlane.setFromNormalAndCoplanarPoint(planeNormal,hit.point);
    poke(hit.point);setNote('That’s the soft spot.');
    const rect=stage.getBoundingClientRect(),ring=$('pointerRing');ring.style.left=(e.clientX-rect.left)+'px';ring.style.top=(e.clientY-rect.top)+'px';ring.classList.remove('pulse');void ring.offsetWidth;ring.classList.add('pulse');
  });
  canvas.addEventListener('pointermove',e=>{
    if(!pointer){if(e.pointerType==='mouse')canvas.style.cursor=hitAt(e)?'grab':'default';return;}
    if(pointer.id!==e.pointerId)return;
    e.preventDefault();
    if(!pointer.moved && Math.hypot(e.clientX-pointer.x,e.clientY-pointer.y)>5){pointer.moved=true;grip=makeGrip(pointer.hit);canvas.classList.add('dragging');canvas.style.cursor='grabbing';setNote('Pull a little. Then let go.',5);}
    if(grip){
      setRay(e);
      if(raycaster.ray.intersectPlane(dragPlane,dragPoint)){
        dragDelta.subVectors(dragPoint,pointer.hit);if(dragDelta.length()>1.45)dragDelta.setLength(1.45);
        grip.target.copy(pointer.hit).add(dragDelta);grip.target.y=clamp(grip.target.y,.28,2.55);
        const r=Math.hypot(grip.target.x,grip.target.z);if(r>2.95){grip.target.x*=2.95/r;grip.target.z*=2.95/r;}
      }
    }
  });
  function release(e){
    if(!pointer || pointer.id!==e.pointerId)return;
    const stretched=pointer.moved;grip=null;pointer=null;canvas.classList.remove('dragging');canvas.style.cursor='grab';
    if(canvas.hasPointerCapture(e.pointerId))canvas.releasePointerCapture(e.pointerId);
    if(stretched)setNote('And… let it wobble.',3);
  }
  canvas.addEventListener('pointerup',release);canvas.addEventListener('pointercancel',release);canvas.addEventListener('lostpointercapture',e=>{if(pointer&&pointer.id===e.pointerId){grip=null;pointer=null;canvas.classList.remove('dragging');}});
  window.addEventListener('blur',()=>{grip=null;pointer=null;canvas.classList.remove('dragging');});

  let demo=window.location.hash.toLowerCase()==='#demo',demoStart=0,demoFlags=new Set();
  $('demoBadge').hidden=!demo;
  function stopDemo(){if(!demo)return;demo=false;grip=null;$('demoBadge').hidden=true;setNote('Your turn. Find a soft spot.',3);}
  document.addEventListener('pointerdown',e=>{if(e.isTrusted)stopDemo();},{capture:true});
  document.addEventListener('keydown',e=>{if(e.isTrusted)stopDemo();},{capture:true});
  function demoEvent(key,t,time,fn){if(t>=time&&!demoFlags.has(key)){demoFlags.add(key);fn();}}
  function playDemo(){
    let t=now-demoStart;
    if(t>=20){resetSlice(false);demoStart=now;demoFlags.clear();t=0;}
    $('demoProgress').style.transform='scaleX('+clamp(t/20,0,1)+')';
    demoEvent('poke',t,1.7,()=>{poke(new THREE.Vector3(.65,TOP,Z0-.6));setNote('First, a gentle poke.',2.6);});
    demoEvent('pull',t,5,()=>{grip=makeGrip(new THREE.Vector3(-1.08,TOP,Z0-.58));setNote('Stretch it. It remembers its shape.',3);});
    if(t>=5&&t<7.2&&grip){const f=smooth((t-5)/1.05);grip.target.copy(grip.origin).add(new THREE.Vector3(-.38*f,.92*f,.2*f));}
    demoEvent('release',t,7.2,()=>{grip=null;setNote('Release. Watch the real physics settle.',2.5);});
    demoEvent('squeeze',t,9.5,squeeze);
    demoEvent('firm',t,14,()=>{setFirmness(82);setNote('Turn up the firmness. Try another poke.',3);});
    demoEvent('firmPoke',t,14.5,()=>poke(new THREE.Vector3(.8,TOP,Z0-.7),1.2));
    demoEvent('reset',t,18.3,()=>{resetSlice(false);setNote('A fresh start. Touch anywhere to take over.',2);});
  }

  function resize(){
    const w=stage.clientWidth,h=stage.clientHeight;if(!w||!h)return;
    renderer.setSize(w,h,false);camera.aspect=w/h;
    const neededHeight=Math.max(6.75,7.95/camera.aspect),distance=neededHeight/(2*Math.tan(THREE.MathUtils.degToRad(camera.fov/2)));
    camera.position.copy(lookAt).addScaledVector(viewDirection,distance);camera.lookAt(lookAt);camera.updateProjectionMatrix();
  }
  new ResizeObserver(resize).observe(stage);resize();
  canvas.addEventListener('webglcontextlost',e=>{e.preventDefault();showFailure('WebGL context lost');});
  canvas.addEventListener('webglcontextrestored',()=>{$('errorText').textContent='The graphics connection is back. Reload to prepare a fresh slice.';});
  document.addEventListener('visibilitychange',()=>{last=performance.now();accumulator=0;});

  let last=performance.now(),elapsed=0,accumulator=0,lastUI=-1;
  function frame(ms){
    const dt=Math.min((ms-last)/1000,.0334);last=ms;elapsed+=dt;now=elapsed;
    if(demo)playDemo();
    const st=now-squeezeStart;
    let targetPressure=0;
    if(st>=0&&st<.55)targetPressure=smooth(st/.55);
    else if(st>=.55&&st<1.07)targetPressure=1;
    else if(st>=1.07&&st<1.8)targetPressure=1-smooth((st-1.07)/.73);
    pressure+=(targetPressure-pressure)*(1-Math.exp(-dt*19));
    accumulator+=dt;
    let steps=0;
    while(accumulator>=fixedDT&&steps<4){simulate(fixedDT);accumulator-=fixedDT;steps++;}
    if(steps===4)accumulator=Math.min(accumulator,fixedDT);
    // Emit juice only after the simulated top has actually compressed.
    if(pressure>.55 && squeezeDrops<5 && now>nextDrop){
      let topHeight=0;for(let i=(LAYERS-1)*PER_LAYER;i<COUNT;i++)topHeight+=pos[i*3+1];topHeight/=PER_LAYER;
      if(TOP-topHeight>.095){emitDrop();squeezeDrops++;nextDrop=now+.12;}
    }
    updateDrops(dt);updateVisuals();renderer.render(scene,camera);
    if(now-lastUI>.14){
      lastUI=now;
      const squeezing=pressure>.08;
      $('squeeze').classList.toggle('is-squeezing',squeezing);$('squeezeLabel').textContent=squeezing?'Squeezing…':'Squeeze';
      const state=squeezing?'A little pressure, a little juice':grip?'Feeling a little stretchy':averageSpeed>.025?'Just a little wobble':'Settled. Ready when you are.';
      if(state!==lastStatus){$('stateText').textContent=state;lastStatus=state;}
      $('stateDot').classList.toggle('active',squeezing||!!grip||averageSpeed>.025);
      if(noteUntil>0&&now>noteUntil){$('sceneNoteText').textContent='Poke it. Pull it. Let it wobble.';noteUntil=0;}
    }
    requestAnimationFrame(frame);
  }
  updateVisuals();renderer.render(scene,camera);
  document.body.classList.add('ready');$('loader').setAttribute('aria-hidden','true');
  $('squeeze').disabled=false;$('firmness').disabled=false;$('reset').disabled=false;
  $('stateText').textContent='Settled. Ready when you are.';
  requestAnimationFrame(frame);
}
</script>
</body>
</html>