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.)46.7 KB · 1,028 lines · loads cdn.jsdelivr.net/npm/three@0.160.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">
<meta name="theme-color" content="#fffaf3">
<title>Orange Jelly · Pulp Studio</title>
<style>
  :root {
    color-scheme: light;
    --ink: #302015;
    --muted: #705849;
    --accent: #bc430d;
    --line: #ebdacc;
    font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
    background: #fffaf3;
    color: var(--ink);
  }
  * { box-sizing: border-box; }
  body { margin: 0; background: radial-gradient(ellipse at 15% 0%, #fffdf9, #fffaf3 67%); min-height: 100vh; }
  button, input { font: inherit; }
  button { cursor: pointer; touch-action: manipulation; }
  button:disabled, input:disabled { cursor: default; opacity: .58; }
  button:focus-visible, input:focus-visible { outline: 3px solid #a93f12; outline-offset: 4px; }
  .shell { width: min(1200px, calc(100% - 96px)); margin: auto; }
  header { display: flex; justify-content: space-between; align-items: center; min-height: 77px; border-bottom: 1px solid var(--line); gap: 12px; }
  .brand { display: flex; align-items: center; gap: 10px; font-weight: 750; font-size: 16px; letter-spacing: -.025em; }
  .brand canvas { width: 34px; height: 34px; }
  .demo { display: flex; align-items: center; justify-content: center; gap: 9px; min-height: 44px; padding: 0 16px; border: 1px solid #e6d4c4; border-radius: 30px; color: #563620; background: #fffefa; font-size: 13px; font-weight: 700; }
  .demo:hover, .reset:hover { background: #fff4e8; }
  .play-icon { width: 0; height: 0; border-top: 5px solid transparent; border-bottom: 5px solid transparent; border-left: 8px solid var(--accent); }
  .demo[aria-pressed="true"] .play-icon { width: 8px; height: 8px; border: 0; background: var(--accent); border-radius: 1px; }
  main { padding: 42px 0 42px; }
  h1 { margin: 0; font: 400 clamp(55px, 6.5vw, 92px)/.99 Georgia, "Times New Roman", serif; letter-spacing: -.074em; }
  h1 span { color: var(--accent); }
  .intro { margin: 13px 0 27px; color: var(--muted); font-size: 15px; line-height: 1.5; }
  .workspace { display: grid; grid-template-columns: minmax(0, 1fr) 274px; gap: 19px; align-items: start; }
  .stage { position: relative; isolation: isolate; overflow: hidden; height: clamp(430px, 59vh, 580px); border-radius: 24px; border: 1px solid #efddc1; background: radial-gradient(ellipse at 43% 24%, #fff8ea 0%, #f9e9cf 62%, #f1dabb 100%); box-shadow: 0 10px 30px #6d37080d, inset 0 1px 0 #fffaf3; touch-action: none; user-select: none; cursor: grab; }
  .stage.grabbing { cursor: grabbing; }
  .stage > canvas { display: block; width: 100%; height: 100%; }
  .state, .hint { position: absolute; z-index: 2; pointer-events: none; }
  .state { display: flex; align-items: center; gap: 7px; top: 17px; left: 17px; padding: 7px 11px; border: 1px solid #ffffffb8; border-radius: 20px; background: #fffaf1db; color: #624735; font-weight: 650; font-size: 12px; }
  .state-dot { width: 7px; height: 7px; border-radius: 50%; background: #648646; }
  .state[data-active="true"] .state-dot { background: #d85a14; box-shadow: 0 0 0 3px #e7712622; }
  .hint { bottom: 13px; left: 0; width: 100%; text-align: center; color: #624835; font-weight: 600; font-size: 12px; }
  .hint span { padding: 0 7px; opacity: .62; }
  .ping { position: absolute; z-index: 3; pointer-events: none; border: 2px solid #fff8e4; box-shadow: 0 0 0 1px #bd4d2247; border-radius: 50%; width: 26px; height: 26px; animation: ripple .46s ease-out both; }
  @keyframes ripple { from { transform: translate(-50%, -50%) scale(.45); opacity: .95; } to { transform: translate(-50%, -50%) scale(2); opacity: 0; } }
  .load { position: absolute; z-index: 2; inset: 0; display: grid; place-items: center; padding: 28px; text-align: center; font-size: 14px; color: var(--muted); pointer-events: none; }
  .load[hidden] { display: none; }
  .controls { border: 1px solid var(--line); border-radius: 22px; background: #fffdfa; padding: 23px 22px 20px; box-shadow: 0 8px 24px #6d370807; }
  .controls h2 { font-weight: 710; font-size: 19px; letter-spacing: -.035em; margin: 0 0 23px; }
  .firm-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
  .firm-head label { font-size: 14px; font-weight: 680; }
  output { color: #a63d11; font-size: 12px; font-weight: 750; font-variant-numeric: tabular-nums; background: #fff0e3; border-radius: 6px; padding: 4px 7px; }
  input[type="range"] { display: block; width: 100%; height: 34px; margin: 4px 0 0; appearance: none; background: transparent; cursor: pointer; --firm: 52%; }
  input[type="range"]::-webkit-slider-runnable-track { height: 5px; border-radius: 5px; background: linear-gradient(to right, #d65b1f var(--firm), #eddfd2 var(--firm)); }
  input[type="range"]::-moz-range-track { height: 5px; border-radius: 5px; background: linear-gradient(to right, #d65b1f var(--firm), #eddfd2 var(--firm)); }
  input[type="range"]::-webkit-slider-thumb { appearance: none; width: 21px; height: 21px; margin-top: -8px; border: 2px solid #fffaf4; border-radius: 50%; background: #d35419; box-shadow: 0 1px 5px #86350955; }
  input[type="range"]::-moz-range-thumb { width: 17px; height: 17px; border: 2px solid #fffaf4; border-radius: 50%; background: #d35419; box-shadow: 0 1px 5px #86350955; }
  .range-labels { display: flex; justify-content: space-between; color: var(--muted); font-size: 12px; margin-top: -2px; }
  .actions { display: grid; gap: 9px; margin-top: 21px; padding-top: 20px; border-top: 1px solid #f0e4d9; }
  .actions button { display: flex; align-items: center; justify-content: center; gap: 9px; min-height: 48px; border-radius: 11px; font-size: 14px; font-weight: 750; }
  .squeeze { border: 1px solid #b7400c; background: #c54b13; color: #fff; box-shadow: inset 0 1px 0 #fff2, 0 3px 6px #a7411920; }
  .squeeze:hover { background: #b83f0b; }
  .squeeze[aria-pressed="true"] { background: #99320b; box-shadow: inset 0 2px 5px #68220855; }
  .drop-icon { display: block; width: 10px; height: 10px; border: 1.5px solid currentColor; border-radius: 75% 10% 72% 68%; transform: rotate(-45deg); }
  .reset { border: 1px solid #ead9c8; background: #fffdfa; color: #674735; }
  .action-hint { margin: 13px 0 0; color: var(--muted); font-size: 12px; text-align: center; line-height: 1.4; }
  @media (max-width: 960px) {
    .shell { width: calc(100% - 52px); }
    .workspace { grid-template-columns: minmax(0, 1fr) 234px; gap: 13px; }
    .controls { padding-inline: 17px; }
  }
  @media (max-width: 700px) {
    .shell { width: calc(100% - 32px); }
    header { min-height: 62px; }
    main { padding: 25px 0 25px; }
    h1 { font-size: clamp(49px, 12.5vw, 78px); }
    .intro { font-size: 14px; margin: 9px 0 16px; }
    .workspace { grid-template-columns: 1fr; gap: 11px; }
    .stage { height: clamp(278px, 46vh, 410px); border-radius: 18px; }
    .state { top: 11px; left: 11px; }
    .hint { bottom: 9px; }
    .controls { border-radius: 17px; padding: 14px 15px 12px; }
    .controls h2 { margin-bottom: 11px; font-size: 17px; }
    .actions { grid-template-columns: 1.35fr 1fr; margin-top: 12px; padding-top: 12px; }
    .action-hint { margin-top: 8px; }
  }
</style>
</head>
<body>
<div class="shell">
  <header>
    <div class="brand"><canvas id="mark" width="68" height="68" aria-hidden="true"></canvas>Pulp Studio</div>
    <button id="demoToggle" class="demo" type="button" aria-pressed="false" disabled><span class="play-icon" aria-hidden="true"></span><span id="demoText">Play demo</span></button>
  </header>
  <main>
    <h1>Orange <span>jelly</span></h1>
    <p class="intro">An interactive soft-body citrus slice.</p>
    <div class="workspace">
      <section class="stage" id="stage" aria-label="Interactive orange jelly on a white plate" aria-describedby="touchHint">
        <div class="state" id="state" role="status"><span class="state-dot" aria-hidden="true"></span><span id="stateText">Loading</span></div>
        <div class="load" id="loading">Preparing the slice…</div>
        <div class="hint" id="touchHint">Tap or click to poke <span aria-hidden="true">·</span> Drag to stretch</div>
      </section>
      <aside class="controls" aria-labelledby="controlsHeading">
        <h2 id="controlsHeading">Jelly controls</h2>
        <div class="firm-head"><label for="firmness">Firmness</label><output for="firmness" id="firmValue">52%</output></div>
        <input type="range" id="firmness" min="0" max="100" value="52" disabled>
        <div class="range-labels" aria-hidden="true"><span>Soft</span><span>Firm</span></div>
        <div class="actions">
          <button class="squeeze" id="squeeze" type="button" aria-pressed="false" disabled><span class="drop-icon" aria-hidden="true"></span>Squeeze</button>
          <button class="reset" id="reset" type="button" disabled>Reset</button>
        </div>
        <p class="action-hint">Hold Squeeze to press longer.</p>
      </aside>
    </div>
  </main>
</div>
<script type="module">
const byId = id => document.getElementById(id);
const mark = byId('mark').getContext('2d');
mark.fillStyle = '#c34b14';
mark.beginPath();
mark.arc(34, 34, 32, 0, Math.PI * 2);
mark.fill();
mark.strokeStyle = '#fff4dd';
mark.lineWidth = 2.7;
mark.beginPath();
mark.arc(34, 34, 22, 0, Math.PI * 2);
mark.stroke();
for (let i = 0; i < 8; i++) {
  const angle = (i + .37) * Math.PI / 4;
  mark.beginPath();
  mark.moveTo(34 + 2 * Math.cos(angle), 34 + 2 * Math.sin(angle));
  mark.lineTo(34 + 21 * Math.cos(angle), 34 + 21 * Math.sin(angle));
  mark.stroke();
}

try {
  const THREE = await import('https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js');
  start(THREE);
} catch (error) {
  byId('loading').textContent = 'The 3D slice could not load. It needs WebGL and access to the three.js library.';
  byId('stateText').textContent = '3D unavailable';
  console.error(error);
}

function start(T) {
  const stage = byId('stage');
  const slider = byId('firmness');
  const squeezeButton = byId('squeeze');
  const resetButton = byId('reset');
  const demoButton = byId('demoToggle');
  const TAU = Math.PI * 2;
  const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
  const mix = (a, b, t) => a + (b - a) * t;
  let seed = 32291;
  const random = () => {
    seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
    return seed / 4294967296;
  };
  function canvas(width, height) {
    const result = document.createElement('canvas');
    result.width = width;
    result.height = height;
    return result;
  }
  function texture(source, srgb = true) {
    const result = new T.CanvasTexture(source);
    if (srgb) result.colorSpace = T.SRGBColorSpace;
    result.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
    return result;
  }
  const renderer = new T.WebGLRenderer({ alpha: true, antialias: true, powerPreference: 'high-performance' });
  renderer.setClearColor(0x000000, 0);
  renderer.toneMapping = T.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.04;
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.65));
  renderer.domElement.setAttribute('aria-hidden', 'true');
  stage.prepend(renderer.domElement);
  const scene = new T.Scene();
  const camera = new T.OrthographicCamera(-4, 4, 3, -3, .1, 50);
  camera.position.set(3.85, 7.0, 7.7);
  camera.lookAt(0, .23, 0);
  camera.updateMatrixWorld();
  function resize() {
    const width = Math.max(1, stage.clientWidth);
    const height = Math.max(1, stage.clientHeight);
    const aspect = width / height;
    const vertical = Math.max(4.92, 6.26 / aspect);
    camera.left = -vertical * aspect / 2;
    camera.right = -camera.left;
    camera.top = vertical / 2;
    camera.bottom = -camera.top;
    camera.updateProjectionMatrix();
    renderer.setSize(width, height, false);
  }
  resize();
  new ResizeObserver(resize).observe(stage);

  // A synthesized high dynamic range light rig gives curved, wet highlights.
  const lamps = [
    [new T.Vector3(-.57, .77, .33).normalize(), 31, 5.2, [1, .91, .74]],
    [new T.Vector3(.64, .69, -.39).normalize(), 47, 6.8, [1, .77, .46]],
    [new T.Vector3(-.61, .42, -.67).normalize(), 15, 2.9, [.74, .85, 1]],
    [new T.Vector3(.21, .60, .77).normalize(), 67, 2.6, [1, .96, .89]]
  ];
  const envW = 256, envH = 128;
  const pixels = new Float32Array(envW * envH * 4);
  for (let y = 0; y < envH; y++) {
    const lat = ((y + .5) / envH - .5) * Math.PI;
    const dy = Math.sin(lat), flat = Math.cos(lat);
    for (let x = 0; x < envW; x++) {
      const angle = ((x + .5) / envW - .5) * TAU;
      const dx = flat * Math.cos(angle), dz = flat * Math.sin(angle);
      const i = (y * envW + x) * 4;
      const base = .25 + .29 * Math.max(dy, 0);
      pixels.set([base, base * .89, base * .75, 1], i);
      for (const [direction, sharpness, power, color] of lamps) {
        const dot = dx * direction.x + dy * direction.y + dz * direction.z;
        const energy = power * Math.exp((dot - 1) * sharpness);
        for (let c = 0; c < 3; c++) pixels[i + c] += energy * color[c];
      }
    }
  }
  const hdr = new T.DataTexture(pixels, envW, envH, T.RGBAFormat, T.FloatType);
  hdr.mapping = T.EquirectangularReflectionMapping;
  hdr.needsUpdate = true;
  const pmrem = new T.PMREMGenerator(renderer);
  scene.environment = pmrem.fromEquirectangular(hdr).texture;
  pmrem.dispose();
  hdr.dispose();
  scene.add(new T.HemisphereLight(0xfff5de, 0xbb8153, 1.32));
  function light(color, intensity, x, y, z) {
    const source = new T.DirectionalLight(color, intensity);
    source.position.set(x, y, z);
    scene.add(source);
  }
  light(0xffefd7, 2.25, -4, 7, 4);
  light(0xffb653, 1.56, 4, 3, -5);
  light(0xf3f6ff, .6, -3, 2, -3);

  function geometry(vertices, uvs, indices) {
    const result = new T.BufferGeometry();
    result.setAttribute('position', new T.Float32BufferAttribute(vertices, 3));
    if (uvs) result.setAttribute('uv', new T.Float32BufferAttribute(uvs, 2));
    result.setIndex(indices);
    result.computeVertexNormals();
    return result;
  }
  const contour = angle => 1 + .009 * Math.sin(5 * angle + .4) + .006 * Math.sin(9 * angle - .9) + .003 * Math.cos(17 * angle);
  function revolve(profile, sides, textured, irregular = false) {
    const verts = [], uv = [], faces = [];
    for (let j = 0; j < profile.length; j++) {
      for (let i = 0; i <= sides; i++) {
        const theta = i / sides * TAU;
        const [radius, y] = profile[j];
        const r = radius * (irregular ? contour(theta) : 1);
        const x = Math.cos(theta) * r, z = Math.sin(theta) * r;
        verts.push(x, y, z);
        if (textured === 'top') uv.push(.5 + x / 4.18, .5 + z / 4.18);
        else uv.push(i / sides, j / (profile.length - 1));
        if (j < profile.length - 1 && i < sides) {
          const a = j * (sides + 1) + i, b = a + sides + 1;
          faces.push(a, b, a + 1, a + 1, b, b + 1);
        }
      }
    }
    const result = geometry(verts, uv, faces);
    result.userData.seam = { width: sides + 1, rows: profile.length };
    smoothSeam(result);
    return result;
  }
  function smoothSeam(geo) {
    const seam = geo.userData.seam;
    if (!seam) return;
    const n = geo.attributes.normal;
    for (let row = 0; row < seam.rows; row++) {
      const first = row * seam.width;
      const last = first + seam.width - 1;
      const x = n.getX(first) + n.getX(last);
      const y = n.getY(first) + n.getY(last);
      const z = n.getZ(first) + n.getZ(last);
      const length = Math.hypot(x, y, z) || 1;
      n.setXYZ(first, x / length, y / length, z / length);
      n.setXYZ(last, x / length, y / length, z / length);
    }
    n.needsUpdate = true;
  }
  const plate = new T.Mesh(revolve([
    [.001, -.161], [1.63, -.161], [1.69, -.179], [1.79, -.18], [1.83, -.127],
    [2.10, -.098], [2.37, -.061], [2.58, -.012], [2.70, .044], [2.753, .088],
    [2.761, .117], [2.738, .140], [2.694, .145], [2.58, .129], [2.46, .105],
    [2.34, .063], [2.24, .030], [2.13, .012], [1.98, .007], [.001, .007]
  ], 160), new T.MeshPhysicalMaterial({
    color: 0xfffbf6, roughness: .26, clearcoat: .61, clearcoatRoughness: .2, envMapIntensity: .73
  }));
  scene.add(plate);
  function shadow(radius, y, rgb, opacity, inner, outer) {
    const bitmap = canvas(128, 128), context = bitmap.getContext('2d');
    const gradient = context.createRadialGradient(64, 64, 0, 64, 64, 64);
    gradient.addColorStop(0, 'rgba(' + rgb + ',' + opacity + ')');
    gradient.addColorStop(inner, 'rgba(' + rgb + ',' + opacity * .88 + ')');
    gradient.addColorStop(outer, 'rgba(' + rgb + ',' + opacity * .19 + ')');
    gradient.addColorStop(1, 'rgba(' + rgb + ',0)');
    context.fillStyle = gradient;
    context.fillRect(0, 0, 128, 128);
    const material = new T.MeshBasicMaterial({ map: texture(bitmap), transparent: true, depthWrite: false, toneMapped: false });
    const mesh = new T.Mesh(new T.PlaneGeometry(radius * 2, radius * 2), material);
    mesh.rotation.x = -Math.PI / 2;
    mesh.position.y = y;
    scene.add(mesh);
    return mesh;
  }
  const plateShadow = shadow(3.6, -.19, '111,60,30', .29, .35, .81);
  plateShadow.position.set(.18, -.19, .27);
  plateShadow.scale.set(1.05, .95, 1);
  shadow(2.94, -.184, '106,59,38', .20, .48, .91);
  const contactShadow = shadow(2.30, .014, '169,74,23', .43, .61, .91);

  const widths = [.87, 1.04, .96, 1.12, .91, 1.04, .97, 1.1, .99, 1.0];
  const cuts = [-.36];
  const widthSum = widths.reduce((a, b) => a + b, 0);
  for (const width of widths) cuts.push(cuts[cuts.length - 1] + width / widthSum * TAU);
  const pithImage = canvas(768, 768), pith = pithImage.getContext('2d');
  const mid = pithImage.width / 2, pithScale = pithImage.width / 4.18;
  const pithColor = pith.createRadialGradient(mid, mid, 0, mid, mid, mid);
  pithColor.addColorStop(0, '#fff3d5');
  pithColor.addColorStop(.083, '#ffe5ac');
  pithColor.addColorStop(.144, '#ffc866');
  pithColor.addColorStop(.81, '#ffbf57');
  pithColor.addColorStop(.873, '#ffdf9b');
  pithColor.addColorStop(.938, '#fff5d9');
  pithColor.addColorStop(1, '#f6d599');
  pith.fillStyle = pithColor;
  pith.fillRect(0, 0, mid * 2, mid * 2);
  for (let i = 0; i < cuts.length - 1; i++) {
    const angle = cuts[i];
    pith.beginPath();
    for (let j = 0; j <= 45; j++) {
      const r = j / 45 * 1.87;
      const a = angle + .012 * Math.sin(r * 12 + i * .3) * r / 2;
      pith.lineTo(mid + r * pithScale * Math.cos(a), mid - r * pithScale * Math.sin(a));
    }
    pith.lineWidth = 5;
    pith.strokeStyle = '#ffe6ae';
    pith.stroke();
    pith.lineWidth = 1.2;
    pith.strokeStyle = '#fff2d6b0';
    pith.stroke();
  }
  for (let i = 0; i < 3900; i++) {
    const a = random() * TAU, r = 1.68 + random() * .32;
    pith.fillStyle = random() < .57 ? '#f5a74228' : '#fffceb95';
    pith.fillRect(mid + r * pithScale * Math.cos(a), mid - r * pithScale * Math.sin(a), 1 + random() * 1.7, .7 + random() * 1.5);
  }

  const peelImage = canvas(1024, 256), peelHeight = canvas(1024, 256);
  const peel = peelImage.getContext('2d'), peelBump = peelHeight.getContext('2d');
  const peelColor = peel.createLinearGradient(0, 0, 0, 256);
  peelColor.addColorStop(0, '#ffc266');
  peelColor.addColorStop(.18, '#ff9a21');
  peelColor.addColorStop(.50, '#ec6b0a');
  peelColor.addColorStop(.84, '#d64d09');
  peelColor.addColorStop(1, '#b84008');
  peel.fillStyle = peelColor;
  peel.fillRect(0, 0, 1024, 256);
  peelBump.fillStyle = '#ababab';
  peelBump.fillRect(0, 0, 1024, 256);
  for (let i = 0; i < 3900; i++) {
    const x = random() * 1024, y = random() * 256, rx = 1 + random() * 2.5, ry = 1.2 + random() * 3;
    peel.fillStyle = random() < .57 ? '#96260037' : '#ffcf5738';
    peelBump.fillStyle = random() < .8 ? '#6161616b' : '#dedede91';
    for (const context of [peel, peelBump]) {
      context.beginPath();
      context.ellipse(x, y, rx, ry, 0, 0, TAU);
      context.fill();
    }
  }

  const juiceImage = canvas(1024, 1024), juiceHeight = canvas(1024, 1024);
  const juice = juiceImage.getContext('2d'), bump = juiceHeight.getContext('2d');
  const center = 512, unit = 1024 / 4.18;
  const pigment = juice.createRadialGradient(center, center, 15, center, center, 494);
  pigment.addColorStop(0, '#ffb442');
  pigment.addColorStop(.26, '#f68b1d');
  pigment.addColorStop(.75, '#ef7610');
  pigment.addColorStop(1, '#fa9a22');
  juice.fillStyle = pigment;
  juice.fillRect(0, 0, 1024, 1024);
  bump.fillStyle = '#6d6d6d';
  bump.fillRect(0, 0, 1024, 1024);
  function vesicle(context) {
    context.beginPath();
    context.moveTo(-1, 0);
    context.bezierCurveTo(-.63, -.42, .08, -1.14, .68, -.82);
    context.bezierCurveTo(1.14, -.56, 1.14, .36, .73, .74);
    context.bezierCurveTo(.16, 1.16, -.63, .48, -1, 0);
    context.closePath();
  }
  for (let row = 0; row < 39; row++) {
    const radius = .085 + row * .049;
    const count = Math.ceil(TAU * radius / .066);
    const offset = random();
    for (let k = 0; k < count; k++) {
      const angle = TAU * (k + offset + random() * .72) / count;
      const r = radius + (random() - .5) * .059;
      const x = center + r * unit * Math.cos(angle), y = center - r * unit * Math.sin(angle);
      const long = 7 + random() * 11, wide = 3 + random() * 5.3;
      const rotation = -angle + (random() - .5) * .64;
      const hue = 23 + random() * 19, brightness = 39 + random() * 20;
      for (const context of [juice, bump]) {
        context.save();
        context.translate(x, y);
        context.rotate(rotation);
        context.scale(long, wide);
        const gleam = context.createRadialGradient(.24, -.25, .09, .01, 0, 1.08);
        if (context === juice) {
          gleam.addColorStop(0, 'hsl(' + (hue + 7) + ' 99% ' + (brightness + 19) + '% / .93)');
          gleam.addColorStop(.60, 'hsl(' + hue + ' 94% ' + (brightness + 5) + '% / .89)');
          gleam.addColorStop(1, 'hsl(' + (hue - 5) + ' 91% ' + (brightness - 11) + '% / .68)');
        } else {
          gleam.addColorStop(0, '#e3e3e3');
          gleam.addColorStop(.6, '#bcbcbc');
          gleam.addColorStop(1, '#7272726a');
        }
        vesicle(context);
        context.fillStyle = gleam;
        context.fill();
        context.restore();
      }
    }
  }
  for (let i = 0; i < 1250; i++) {
    const r = .14 + Math.sqrt(random()) * 1.75, a = random() * TAU;
    juice.fillStyle = i % 4 === 0 ? '#fff19d80' : '#ffd26a48';
    juice.fillRect(center + r * unit * Math.cos(a), center - r * unit * Math.sin(a), .6 + random() * 1.9, .65 + random());
  }

  const baseMaterial = new T.MeshPhysicalMaterial({
    map: texture(pithImage), roughness: .38, clearcoat: .45, envMapIntensity: .54
  });
  const peelMaterial = new T.MeshPhysicalMaterial({
    map: texture(peelImage), bumpMap: texture(peelHeight, false), bumpScale: .067,
    roughness: .28, clearcoat: .55, clearcoatRoughness: .24, envMapIntensity: .76
  });
  const gel = new T.MeshPhysicalMaterial({
    map: texture(juiceImage), bumpMap: texture(juiceHeight, false), bumpScale: .060,
    color: 0xffb464, roughness: .21, transmission: .45, ior: 1.39, thickness: .125,
    attenuationColor: new T.Color(0xff9828), attenuationDistance: .49,
    clearcoat: .70, clearcoatRoughness: .20, envMapIntensity: .84
  });
  gel.onBeforeCompile = shader => {
    shader.fragmentShader = shader.fragmentShader.replace('#include <emissivemap_fragment>',
      '#include <emissivemap_fragment>\n' +
      'float glow = pow(1.0 - clamp(dot(normal, normalize(vViewPosition)), 0.0, 1.0), 2.3);\n' +
      'totalEmissiveRadiance += vec3(1.0, 0.28, 0.023) * (0.023 + glow * 0.20);');
  };

  // Three layers of nodes form a tetrahedral solid. Render vertices share its displacement field.
  const spokes = 36, radii = [0, .48, .96, 1.49, 2.04], layers = [.038, .280, .557];
  const layerSize = 1 + (radii.length - 1) * spokes;
  const nodeCount = layerSize * layers.length;
  const rest = new Float64Array(nodeCount * 3);
  const position = new Float64Array(rest.length);
  const previous = new Float64Array(rest.length);
  const velocity = new Float64Array(rest.length);
  const surfaceNodes = [];
  const node = (layer, ring, sector) => layer * layerSize + (ring === 0 ? 0 : 1 + (ring - 1) * spokes + (sector + spokes) % spokes);
  for (let layer = 0; layer < layers.length; layer++) {
    rest[3 * node(layer, 0, 0) + 1] = layers[layer];
    for (let ring = 1; ring < radii.length; ring++) {
      for (let sector = 0; sector < spokes; sector++) {
        const angle = sector * TAU / spokes, index = node(layer, ring, sector) * 3;
        rest[index] = radii[ring] * Math.cos(angle);
        rest[index + 1] = layers[layer];
        rest[index + 2] = radii[ring] * Math.sin(angle);
      }
    }
  }
  position.set(rest);
  for (let n = layerSize * 2; n < nodeCount; n++) surfaceNodes.push(n * 3);

  const edgeKeys = new Set(), edges = [], volumes = [];
  function edge(a, b, bend = false) {
    const key = Math.min(a, b) * nodeCount + Math.max(a, b);
    if (edgeKeys.has(key)) return;
    edgeKeys.add(key);
    a *= 3;
    b *= 3;
    edges.push({ a, b, length: Math.hypot(rest[a] - rest[b], rest[a + 1] - rest[b + 1], rest[a + 2] - rest[b + 2]), bend, lambda: 0 });
  }
  function tetra(a, b, c, d) {
    edge(a, b); edge(a, c); edge(a, d); edge(b, c); edge(b, d); edge(c, d);
    a *= 3; b *= 3; c *= 3; d *= 3;
    const x1 = rest[b] - rest[a], y1 = rest[b + 1] - rest[a + 1], z1 = rest[b + 2] - rest[a + 2];
    const x2 = rest[c] - rest[a], y2 = rest[c + 1] - rest[a + 1], z2 = rest[c + 2] - rest[a + 2];
    const x3 = rest[d] - rest[a], y3 = rest[d + 1] - rest[a + 1], z3 = rest[d + 2] - rest[a + 2];
    const determinant = x1 * (y2 * z3 - z2 * y3) + y1 * (z2 * x3 - x2 * z3) + z1 * (x2 * y3 - y2 * x3);
    volumes.push({ a, b, c, d, determinant });
  }
  function prism(layer, vertices) {
    const [a, b, c] = vertices.sort((x, y) => x - y).map(n => n + layer * layerSize);
    const d = a + layerSize, e = b + layerSize, f = c + layerSize;
    tetra(a, b, c, f);
    tetra(a, b, e, f);
    tetra(a, d, e, f);
  }
  for (let layer = 0; layer < 2; layer++) {
    for (let sector = 0; sector < spokes; sector++) {
      prism(layer, [0, node(0, 1, sector), node(0, 1, sector + 1)]);
      for (let ring = 1; ring < radii.length - 1; ring++) {
        const a = node(0, ring, sector), b = node(0, ring, sector + 1);
        const c = node(0, ring + 1, sector), d = node(0, ring + 1, sector + 1);
        prism(layer, [a, b, c]);
        prism(layer, [b, c, d]);
      }
    }
  }
  for (let layer = 0; layer < layers.length; layer++) {
    for (let sector = 0; sector < spokes; sector++) {
      for (let ring = 1; ring < radii.length; ring++) edge(node(layer, ring, sector), node(layer, ring, sector + 2), true);
    }
  }
  for (let n = 0; n < layerSize; n++) edge(n, 2 * layerSize + n, true);

  function attachment(vertices) {
    const bindings = new Uint16Array(vertices.length / 3 * 8);
    const weights = new Float32Array(bindings.length);
    for (let i = 0; i < vertices.length; i += 3) {
      const x = vertices[i], y = vertices[i + 1], z = vertices[i + 2];
      const r = clamp(Math.hypot(x, z), 0, radii[radii.length - 1]);
      const angle = ((Math.atan2(z, x) + TAU) % TAU) / TAU * spokes;
      const sector = Math.floor(angle), t = angle - sector;
      let ring = 0;
      while (ring < radii.length - 2 && r > radii[ring + 1]) ring++;
      const f = (r - radii[ring]) / (radii[ring + 1] - radii[ring]);
      const level = y < layers[1] ? 0 : 1;
      const h = clamp((y - layers[level]) / (layers[level + 1] - layers[level]), 0, 1);
      let j = i / 3 * 8;
      for (let l = 0; l < 2; l++) {
        for (let k = 0; k < 2; k++) {
          for (let s = 0; s < 2; s++) {
            bindings[j] = node(level + l, ring + k, sector + s) * 3;
            weights[j] = (l ? h : 1 - h) * (k ? f : 1 - f) * (s ? t : 1 - t);
            j++;
          }
        }
      }
    }
    return { bindings, weights, original: Float32Array.from(vertices) };
  }
  function deform(binding, target) {
    const { bindings, weights, original } = binding;
    for (let i = 0, j = 0; i < original.length; i += 3) {
      let x = original[i], y = original[i + 1], z = original[i + 2];
      const end = j + 8;
      for (; j < end; j++) {
        const n = bindings[j], weight = weights[j];
        x += (position[n] - rest[n]) * weight;
        y += (position[n + 1] - rest[n + 1]) * weight;
        z += (position[n + 2] - rest[n + 2]) * weight;
      }
      target[i] = x;
      target[i + 1] = Math.max(.024, y);
      target[i + 2] = z;
    }
  }
  const skins = [], pickables = [];
  function skin(geo, material) {
    const mesh = new T.Mesh(geo, material);
    const attribute = geo.attributes.position;
    attribute.setUsage(T.DynamicDrawUsage);
    geo.boundingSphere = new T.Sphere(new T.Vector3(0, .35, 0), 3.3);
    mesh.frustumCulled = false;
    scene.add(mesh);
    skins.push({ geo, binding: attachment(attribute.array) });
    pickables.push(mesh);
    return mesh;
  }
  skin(revolve([
    [1.71, .032], [1.88, .032], [1.96, .051], [2.001, .098], [2.025, .167],
    [2.032, .245], [2.030, .326], [2.016, .401], [1.997, .463], [1.969, .509], [1.937, .526]
  ], 144, 'side', true), peelMaterial);
  skin(revolve([
    [1.958, .505], [1.941, .525], [1.916, .527], [1.890, .521], [1.861, .509],
    [1.824, .492], [1.77, .485], [1.62, .483], [1.36, .485], [1.08, .486],
    [.81, .484], [.54, .486], [.27, .488], [.142, .493], [.064, .497], [.001, .497]
  ], 144, 'top', true), baseMaterial);

  function wedgePoint(wedge, s, t) {
    const start = cuts[wedge], end = cuts[wedge + 1];
    const inner = .118 + .037 * Math.sin(wedge * 1.17 + 1.4);
    const r = mix(inner, 1.862, s);
    const margin = Math.min((end - start) * .24, .017 / r) + .032 * Math.pow(Math.abs(2 * s - 1), 9);
    const angle = mix(start + margin, end - margin, t) + .009 * Math.sin(r * 10.8 + wedge * .55) * s;
    const rounded = r * contour(angle) - .059 * Math.pow(Math.abs(t * 2 - 1), 7) * Math.pow(s, 9);
    const rise = Math.pow(Math.max(0, Math.sin(Math.PI * s) * Math.sin(Math.PI * t)), .43);
    const y = .498 + .086 * rise + .006 * Math.sin(s * 22 + wedge * 1.9) * rise;
    return [Math.cos(angle) * rounded, y, Math.sin(angle) * rounded];
  }
  const cellOrigins = [], cellShapes = [];
  for (let w = 0; w < widths.length; w++) {
    const verts = [], uv = [], faces = [];
    const radial = 21, angular = 17;
    for (let j = 0; j <= radial; j++) {
      for (let i = 0; i <= angular; i++) {
        const [x, y, z] = wedgePoint(w, j / radial, i / angular);
        verts.push(x, y, z);
        uv.push(.5 + x / 4.18, .5 + z / 4.18);
        if (j < radial && i < angular) {
          const a = j * (angular + 1) + i, b = a + angular + 1;
          faces.push(a, a + 1, b, a + 1, b + 1, b);
        }
      }
    }
    skin(geometry(verts, uv, faces), gel).renderOrder = 2;
    for (let i = 0; i < 37; i++) {
      const [x, y, z] = wedgePoint(w, .2 + Math.sqrt(random()) * .72, .09 + random() * .82);
      cellOrigins.push(x, y - .035, z);
      cellShapes.push({
        rotation: -Math.atan2(z, x) + (random() - .5) * .43,
        x: .022 + random() * .039, y: .005 + random() * .010, z: .010 + random() * .020,
        color: new T.Color().setHSL(.058 + random() * .060, .90, .40 + random() * .24, T.SRGBColorSpace)
      });
    }
  }
  const cells = new T.InstancedMesh(new T.SphereGeometry(1, 8, 6), new T.MeshStandardMaterial({
    color: 0xffffff, roughness: .27, envMapIntensity: .68
  }), cellShapes.length);
  cells.instanceMatrix.setUsage(T.DynamicDrawUsage);
  cells.frustumCulled = false;
  scene.add(cells);
  const cellBinding = attachment(cellOrigins);
  const cellPositions = new Float32Array(cellOrigins.length);
  const cellTransform = new T.Object3D();
  for (let i = 0; i < cellShapes.length; i++) cells.setColorAt(i, cellShapes[i].color);

  function updateSkin() {
    for (const { geo, binding } of skins) {
      deform(binding, geo.attributes.position.array);
      geo.attributes.position.needsUpdate = true;
      geo.computeVertexNormals();
      smoothSeam(geo);
    }
    deform(cellBinding, cellPositions);
    for (let i = 0; i < cellShapes.length; i++) {
      const shape = cellShapes[i];
      cellTransform.position.fromArray(cellPositions, i * 3);
      cellTransform.rotation.y = shape.rotation;
      cellTransform.scale.set(shape.x, shape.y, shape.z);
      cellTransform.updateMatrix();
      cells.setMatrixAt(i, cellTransform.matrix);
    }
    cells.instanceMatrix.needsUpdate = true;
    const middle = layerSize * 3;
    contactShadow.position.x = position[middle] * .56;
    contactShadow.position.z = position[middle + 2] * .56;
  }

  const step = 1 / 120;
  let firmness = .52, clock = 0, pressure = 0;
  let squeezeStart = -10, held = false, burst = 4, burstStart = Infinity;
  let jiggleUntil = -1, pokeForce = null, grab = null, pointer = null;
  const drops = [];
  const dropGeometry = new T.SphereGeometry(1, 18, 12);
  const dropMaterial = new T.MeshPhysicalMaterial({
    color: 0xffa322, transmission: .53, thickness: .066, ior: 1.36, roughness: .13,
    clearcoat: 1, clearcoatRoughness: .13, attenuationColor: new T.Color(0xffa627), attenuationDistance: .18
  });
  function plateHeight(r) {
    if (r < 2.15) return .010;
    return .010 + Math.min(.117, (r - 2.15) * .235);
  }
  function spawnDrop(index) {
    if (drops.length >= 24) scene.remove(drops.shift().mesh);
    const angle = .80 + index * .31 + (random() - .5) * .20;
    const a = Math.cos(angle), b = Math.sin(angle);
    const sector = Math.round(angle / TAU * spokes);
    const n = node(1, radii.length - 1, sector) * 3;
    const start = Math.max(2.02, position[n] * a + position[n + 2] * b) + .017;
    const size = .030 + random() * .027;
    const mesh = new T.Mesh(dropGeometry, dropMaterial);
    mesh.position.set(a * start, .128 + random() * .079, b * start);
    mesh.scale.setScalar(size);
    mesh.renderOrder = 3;
    const speed = .48 + random() * .46;
    drops.push({ mesh, size, a, b, vx: a * speed, vy: .16 + random() * .23, vz: b * speed, spread: 0 });
    scene.add(mesh);
  }
  function updateDrops() {
    if (burst < 4 && clock > burstStart + burst * .095) spawnDrop(burst++);
    for (const drop of drops) {
      const p = drop.mesh.position;
      p.x += drop.vx * step;
      p.y += drop.vy * step;
      p.z += drop.vz * step;
      drop.vy -= 4.6 * step;
      const r = Math.hypot(p.x, p.z);
      const floor = plateHeight(r) + drop.size * mix(.88, .34, drop.spread);
      if (p.y <= floor) {
        p.y = floor;
        drop.vy = 0;
        drop.spread = Math.min(1, drop.spread + step * 4.1);
        drop.vx *= .964;
        drop.vz *= .964;
      }
      if (r > 2.59) {
        p.x *= 2.59 / r;
        p.z *= 2.59 / r;
        drop.vx = 0;
        drop.vz = 0;
      }
      drop.mesh.scale.set(drop.size * (1 + drop.spread * .53), drop.size * (1 - drop.spread * .61), drop.size * (1 + drop.spread * .41));
    }
  }
  function solveVolume(v, strength) {
    const { a, b, c, d, determinant } = v;
    const x1 = position[b] - position[a], y1 = position[b + 1] - position[a + 1], z1 = position[b + 2] - position[a + 2];
    const x2 = position[c] - position[a], y2 = position[c + 1] - position[a + 1], z2 = position[c + 2] - position[a + 2];
    const x3 = position[d] - position[a], y3 = position[d + 1] - position[a + 1], z3 = position[d + 2] - position[a + 2];
    const bx = y2 * z3 - z2 * y3, by = z2 * x3 - x2 * z3, bz = x2 * y3 - y2 * x3;
    const cx = y3 * z1 - z3 * y1, cy = z3 * x1 - x3 * z1, cz = x3 * y1 - y3 * x1;
    const dx = y1 * z2 - z1 * y2, dy = z1 * x2 - x1 * z2, dz = x1 * y2 - y1 * x2;
    const ax = -(bx + cx + dx), ay = -(by + cy + dy), az = -(bz + cz + dz);
    const error = x1 * bx + y1 * by + z1 * bz - determinant;
    const norm = ax * ax + ay * ay + az * az + bx * bx + by * by + bz * bz +
      cx * cx + cy * cy + cz * cz + dx * dx + dy * dy + dz * dz;
    const s = -strength * error / (norm + .00018);
    position[a] += ax * s; position[a + 1] += ay * s; position[a + 2] += az * s;
    position[b] += bx * s; position[b + 1] += by * s; position[b + 2] += bz * s;
    position[c] += cx * s; position[c + 1] += cy * s; position[c + 2] += cz * s;
    position[d] += dx * s; position[d + 1] += dy * s; position[d + 2] += dz * s;
  }
  function simulate() {
    clock += step;
    const pressing = held || clock - squeezeStart < .59;
    const target = pressing ? 1 : 0;
    pressure += (target - pressure) * (1 - Math.exp(-step * (pressing ? 10 : 8)));
    if (pressure > .72 && burstStart === Infinity && burst < 4) burstStart = clock;
    const pressHeight = .58 - pressure * .264;
    const drag = Math.exp(-step * mix(2.5, 5.0, firmness));
    const compliance = mix(1.18, .045, firmness);
    const volumeStrength = mix(.29, .57, firmness);
    previous.set(position);
    for (let i = 0; i < position.length; i += 3) {
      velocity[i] *= drag;
      velocity[i + 1] = velocity[i + 1] * drag - 6.7 * step;
      velocity[i + 2] *= drag;
      position[i] += velocity[i] * step;
      position[i + 1] += velocity[i + 1] * step;
      position[i + 2] += velocity[i + 2] * step;
    }
    const pokeAmount = pokeForce ? Math.max(0, 1 - (clock - pokeForce.time) / .145) : 0;
    if (pokeForce && pokeAmount === 0) pokeForce = null;
    for (const e of edges) e.lambda = 0;
    for (let pass = 0; pass < 5; pass++) {
      if (pokeAmount > 0) {
        for (const [i, weight] of pokeForce.nodes) position[i + 1] -= pokeAmount * weight * .0085;
      }
      if (grab) {
        for (const g of grab.nodes) {
          const strength = g.weight * .52;
          position[g.i] += (g.x + grab.dx * g.amount - position[g.i]) * strength;
          position[g.i + 1] += (g.y + grab.dy * g.amount - position[g.i + 1]) * strength;
          position[g.i + 2] += (g.z + grab.dz * g.amount - position[g.i + 2]) * strength;
        }
      }
      for (const e of edges) {
        const { a, b } = e;
        const x = position[b] - position[a], y = position[b + 1] - position[a + 1], z = position[b + 2] - position[a + 2];
        const length = Math.sqrt(x * x + y * y + z * z);
        if (length < 1e-8) continue;
        const alpha = e.bend ? compliance * 2.8 + .36 : compliance;
        const increment = (e.length - length - alpha * e.lambda) / (2 + alpha);
        e.lambda += increment;
        const s = increment / length;
        position[a] -= x * s; position[a + 1] -= y * s; position[a + 2] -= z * s;
        position[b] += x * s; position[b + 1] += y * s; position[b + 2] += z * s;
      }
      for (const v of volumes) solveVolume(v, volumeStrength);
      if (pressure > .01) {
        for (const i of surfaceNodes) {
          if (position[i + 1] > pressHeight) position[i + 1] = mix(position[i + 1], pressHeight, .77);
        }
      }
      for (let i = 0; i < position.length; i += 3) {
        if (i < layerSize * 3) {
          const tether = mix(.035, .081, firmness);
          position[i] += (rest[i] - position[i]) * tether;
          position[i + 2] += (rest[i + 2] - position[i + 2]) * tether;
        }
        const radius = Math.hypot(position[i], position[i + 2]);
        if (radius > 2.52) {
          const scale = 2.52 / radius;
          position[i] *= scale;
          position[i + 2] *= scale;
        }
        position[i + 1] = clamp(position[i + 1], plateHeight(Math.min(radius, 2.52)) + .019, 1.06);
      }
    }
    for (let i = 0; i < position.length; i += 3) {
      const floor = plateHeight(Math.hypot(position[i], position[i + 2])) + .019;
      const friction = position[i + 1] <= floor + .001 ? .67 : 1;
      velocity[i] = clamp((position[i] - previous[i]) / step, -5, 5) * friction;
      velocity[i + 1] = clamp((position[i + 1] - previous[i + 1]) / step, -5, 5);
      velocity[i + 2] = clamp((position[i + 2] - previous[i + 2]) / step, -5, 5) * friction;
    }
    updateDrops();
  }

  const raycaster = new T.Raycaster();
  const ndc = new T.Vector2(), dragPlane = new T.Plane(), projected = new T.Vector3();
  function ray(event) {
    const rect = stage.getBoundingClientRect();
    ndc.set((event.clientX - rect.left) / rect.width * 2 - 1, 1 - (event.clientY - rect.top) / rect.height * 2);
    raycaster.setFromCamera(ndc, camera);
  }
  function ping(point) {
    const projectedPoint = point.clone().project(camera);
    const ring = document.createElement('i');
    ring.className = 'ping';
    ring.style.left = ((projectedPoint.x + 1) * 50) + '%';
    ring.style.top = ((1 - projectedPoint.y) * 50) + '%';
    stage.append(ring);
    setTimeout(() => ring.remove(), 500);
  }
  function poke(point) {
    const nodes = [];
    for (const i of surfaceNodes) {
      const dx = position[i] - point.x, dz = position[i + 2] - point.z;
      const distance = Math.hypot(dx, dz);
      const weight = Math.max(0, 1 - distance / 1.09) ** 1.4;
      if (weight > 0) {
        velocity[i] += (dx * .8 - point.x * .22) * weight;
        velocity[i + 1] -= mix(4.35, 3.15, firmness) * weight;
        velocity[i + 2] += (dz * .8 - point.z * .22) * weight;
        nodes.push([i, weight]);
      }
    }
    pokeForce = { nodes, time: clock };
    jiggleUntil = clock + mix(1.78, 1.07, firmness);
    ping(point);
  }
  function beginGrab(point) {
    const nodes = [];
    for (let i = layerSize * 3; i < position.length; i += 3) {
      const distance = Math.hypot(position[i] - point.x, position[i + 2] - point.z);
      const top = i >= layerSize * 6;
      const weight = Math.max(0, 1 - distance / 1.18) ** 1.38 * (top ? 1 : .44);
      if (weight > 0) nodes.push({
        i, weight, x: position[i], y: position[i + 1], z: position[i + 2],
        amount: mix(.43, 1, weight)
      });
    }
    grab = { nodes, dx: 0, dy: 0, dz: 0 };
  }
  function stretch(dx, dy, dz) {
    if (!grab) return;
    const maximum = mix(.98, .75, firmness);
    const scale = Math.min(1, maximum / Math.max(.0001, Math.hypot(dx, dz)));
    grab.dx = dx * scale;
    grab.dy = clamp(dy, -.29, .55);
    grab.dz = dz * scale;
  }
  function release() {
    if (grab) jiggleUntil = clock + mix(2.35, 1.29, firmness);
    grab = null;
  }
  stage.addEventListener('pointerdown', event => {
    if (pointer || event.button !== 0) return;
    ray(event);
    const hit = raycaster.intersectObjects(pickables, false)[0];
    if (!hit) return;
    event.preventDefault();
    const point = hit.point;
    pointer = { id: event.pointerId, x: event.clientX, y: event.clientY, point };
    dragPlane.setFromNormalAndCoplanarPoint(camera.getWorldDirection(new T.Vector3()), point);
    stage.setPointerCapture(event.pointerId);
    stage.classList.add('grabbing');
    poke(point);
  });
  stage.addEventListener('pointermove', event => {
    if (!pointer || event.pointerId !== pointer.id) return;
    if (!grab && Math.hypot(event.clientX - pointer.x, event.clientY - pointer.y) < 6) return;
    if (!grab) beginGrab(pointer.point);
    ray(event);
    if (raycaster.ray.intersectPlane(dragPlane, projected)) {
      stretch(projected.x - pointer.point.x, projected.y - pointer.point.y, projected.z - pointer.point.z);
    }
  });
  function endPointer(event) {
    if (!pointer || event.pointerId !== pointer.id) return;
    pointer = null;
    stage.classList.remove('grabbing');
    release();
  }
  for (const event of ['pointerup', 'pointercancel', 'lostpointercapture']) stage.addEventListener(event, endPointer);

  function setFirmness(value) {
    firmness = value / 100;
    slider.value = value;
    slider.style.setProperty('--firm', value + '%');
    byId('firmValue').value = value + '%';
  }
  slider.addEventListener('input', () => setFirmness(Number(slider.value)));
  function squeeze(hold) {
    held = hold;
    squeezeStart = clock;
    burstStart = Infinity;
    burst = 0;
    jiggleUntil = clock + 2.1;
  }
  squeezeButton.addEventListener('pointerdown', event => {
    if (event.button !== 0) return;
    squeezeButton.setPointerCapture(event.pointerId);
    squeeze(true);
  });
  for (const name of ['pointerup', 'pointercancel', 'lostpointercapture']) {
    squeezeButton.addEventListener(name, () => {
      if (held) jiggleUntil = clock + 1.38;
      held = false;
    });
  }
  squeezeButton.addEventListener('click', event => {
    if (event.detail === 0) squeeze(false);
  });
  function resetJelly() {
    position.set(rest);
    velocity.fill(0);
    for (const drop of drops) scene.remove(drop.mesh);
    drops.length = 0;
    pressure = 0;
    squeezeStart = -10;
    held = false;
    burstStart = Infinity;
    burst = 4;
    jiggleUntil = -1;
    grab = null;
    pokeForce = null;
    if (pointer && stage.hasPointerCapture(pointer.id)) stage.releasePointerCapture(pointer.id);
    pointer = null;
    stage.classList.remove('grabbing');
    setFirmness(52);
    updateSkin();
  }
  resetButton.addEventListener('click', resetJelly);

  let demo = false, demoStart = 0, cue = 0;
  function setDemo(active) {
    demo = active;
    demoButton.setAttribute('aria-pressed', String(active));
    byId('demoText').textContent = active ? 'Stop demo' : 'Play demo';
    if (active) {
      resetJelly();
      demoStart = clock;
      cue = 0;
    } else release();
  }
  demoButton.addEventListener('click', () => setDemo(!demo));
  document.addEventListener('pointerdown', event => {
    if (demo && !demoButton.contains(event.target)) setDemo(false);
  }, { capture: true });
  document.addEventListener('keydown', event => {
    if (demo && !demoButton.contains(event.target) && event.key !== 'Tab') setDemo(false);
  }, { capture: true });
  window.addEventListener('hashchange', () => setDemo(location.hash.toLowerCase() === '#demo'));
  const demoGrab = new T.Vector3(-1.21, .55, .76);
  const cues = [
    [1.18, () => poke(new T.Vector3(.63, .57, .50))],
    [2.68, () => poke(new T.Vector3(-.48, .56, -.38))],
    [4.25, () => { ping(demoGrab); beginGrab(demoGrab); }],
    [7.50, release],
    [9.45, () => squeeze(true)],
    [11.0, () => { held = false; jiggleUntil = clock + 1.5; }],
    [13.12, () => setFirmness(14)],
    [13.73, () => poke(new T.Vector3(.31, .58, .71))],
    [16.10, () => setFirmness(88)],
    [16.82, () => poke(new T.Vector3(.31, .58, .71))],
    [19.15, resetJelly]
  ];
  function advanceDemo() {
    let elapsed = clock - demoStart;
    if (elapsed >= 20) {
      elapsed -= 20;
      demoStart = clock - elapsed;
      cue = 0;
    }
    while (cue < cues.length && elapsed >= cues[cue][0]) cues[cue++][1]();
    if (grab) {
      const lift = Math.sin(clamp((elapsed - 4.25) / 2.6, 0, .78) * Math.PI / 2);
      stretch(-.97 * lift, .56 * lift, .49 * lift);
    }
  }
  let status = '', lastTime = performance.now(), accumulator = 0;
  function frame(now) {
    accumulator += Math.min(.045, (now - lastTime) / 1000);
    lastTime = now;
    let changed = false;
    while (accumulator >= step) {
      if (demo) advanceDemo();
      simulate();
      changed = true;
      accumulator -= step;
    }
    if (changed) updateSkin();
    const next = grab ? 'Stretching' : pressure > .07 ? 'Squeezing' : clock < jiggleUntil ? 'Jiggling' : 'Settled';
    if (next !== status) {
      byId('stateText').textContent = next;
      byId('state').dataset.active = String(next !== 'Settled');
      squeezeButton.setAttribute('aria-pressed', String(next === 'Squeezing'));
      status = next;
    }
    renderer.render(scene, camera);
    requestAnimationFrame(frame);
  }
  updateSkin();
  renderer.render(scene, camera);
  byId('loading').hidden = true;
  for (const control of [slider, squeezeButton, resetButton, demoButton]) control.disabled = false;
  if (location.hash.toLowerCase() === '#demo') setDemo(true);
  requestAnimationFrame(frame);
}
</script>
</body>
</html>