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.)59.2 KB · 1,610 lines · loads cdn.jsdelivr.net/npm/[email protected]/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="#f8f3e9">
<title>Citrus Jelly | Jelly Lab</title>
<style>
  :root {
    color-scheme: light;
    --paper: #f8f3e9;
    --ink: #2b281f;
    --muted: #63594a;
    --line: #ded3c1;
    --accent: #b64422;
    font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
    color: var(--ink);
    background: var(--paper);
  }

  * { box-sizing: border-box; }
  body { margin: 0; min-width: 280px; }
  button, input { font: inherit; }
  button { cursor: pointer; -webkit-tap-highlight-color: transparent; }
  button:focus-visible, input:focus-visible {
    outline: 2px solid #813c26;
    outline-offset: 5px;
  }

  .shell { width: min(1312px, calc(100% - 104px)); margin-inline: auto; }
  .masthead {
    height: 77px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid var(--line);
  }

  .brand { display: inline-flex; align-items: center; gap: 11px; }
  .brand svg { width: 34px; height: 34px; flex: none; }
  .brand span { font-size: 14px; font-weight: 750; letter-spacing: .045em; }

  .demo {
    min-height: 44px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 0 15px;
    border-radius: 50px;
    border: 1px solid var(--line);
    background: #fff9ef;
    color: #47382b;
    font-size: 13px;
    font-weight: 650;
  }
  .demo svg { width: 15px; height: 15px; }
  .demo .pause-icon, .demo[aria-pressed="true"] .play-icon { display: none; }
  .demo[aria-pressed="true"] .pause-icon { display: block; }

  .workbench {
    display: grid;
    grid-template-columns: minmax(250px, .385fr) minmax(0, 1fr);
    grid-template-rows: auto 1fr;
    grid-template-areas: "intro stage" "controls stage";
    column-gap: clamp(33px, 5.05vw, 76px);
    align-items: start;
    padding-block: 43px 52px;
  }

  .intro { grid-area: intro; padding-top: clamp(27px, 5.1vw, 73px); }
  h1 {
    margin: 0;
    font-family: Georgia, "Times New Roman", serif;
    font-size: clamp(72px, 8.35vw, 122px);
    font-weight: 400;
    line-height: .85;
    letter-spacing: -.075em;
  }
  h1 em { color: var(--accent); font-weight: 400; }
  .intro p {
    color: var(--muted);
    font-size: 16px;
    line-height: 1.62;
    margin: 27px 0 0;
    max-width: 29ch;
    text-wrap: pretty;
  }

  .controls {
    grid-area: controls;
    margin-top: 37px;
    padding-top: 22px;
    border-top: 1px solid var(--line);
  }
  .field-head, .range-labels { display: flex; align-items: center; justify-content: space-between; }
  .field-head label { font-size: 15px; font-weight: 710; }
  .field-head output {
    padding: 4px 8px;
    background: #f0e6d8;
    color: #644733;
    border-radius: 7px;
    font-size: 12px;
    font-weight: 700;
    line-height: 1.2;
    font-variant-numeric: tabular-nums;
  }
  input[type="range"] {
    --fill: 52%;
    display: block;
    appearance: none;
    width: 100%;
    height: 36px;
    margin: 3px 0 0;
    border-radius: 5px;
    background: transparent;
    cursor: pointer;
    touch-action: pan-y;
  }
  input[type="range"]::-webkit-slider-runnable-track {
    height: 5px;
    border-radius: 10px;
    background: linear-gradient(to right, var(--accent) var(--fill), #e1d6c6 var(--fill));
  }
  input[type="range"]::-moz-range-track {
    height: 5px;
    border-radius: 10px;
    background: linear-gradient(to right, var(--accent) var(--fill), #e1d6c6 var(--fill));
  }
  input[type="range"]::-webkit-slider-thumb {
    appearance: none;
    width: 23px;
    height: 23px;
    margin-top: -9px;
    border: 2px solid #fff8eb;
    border-radius: 50%;
    background: var(--accent);
    box-shadow: 0 0 0 1px #ad4427, 0 2px 4px #6b291733;
  }
  input[type="range"]::-moz-range-thumb {
    width: 19px;
    height: 19px;
    border: 2px solid #fff8eb;
    border-radius: 50%;
    background: var(--accent);
    box-shadow: 0 0 0 1px #ad4427, 0 2px 4px #6b291733;
  }
  .range-labels { color: #746656; font-size: 12px; margin-top: -1px; }

  .actions { display: grid; grid-template-columns: 1.36fr 1fr; gap: 10px; margin-top: 24px; }
  .action {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 9px;
    min-height: 52px;
    border: 1px solid var(--line);
    border-radius: 13px;
    padding: 0 13px;
    color: var(--ink);
    background: #fff9ef;
    font-size: 14px;
    font-weight: 680;
  }
  .action svg { width: 17px; height: 17px; flex: none; }
  .primary {
    color: #fff8ee;
    background: var(--accent);
    border-color: var(--accent);
    box-shadow: 0 3px 7px #722c171b, inset 0 1px #ffffff24;
  }
  .primary.is-pressing, .primary:active { background: #91351b; }
  .action:active, .demo:active { transform: translateY(1px); }
  @media (hover: hover) {
    .demo:hover, .action:not(.primary):hover { background: #f1e8db; }
    .primary:hover { background: #a33a1d; }
  }

  .stage {
    grid-area: stage;
    isolation: isolate;
    overflow: hidden;
    position: relative;
    height: clamp(543px, 73vh, 735px);
    border: 1px solid #d8a478;
    border-radius: 25px;
    background:
      radial-gradient(ellipse at 30% 9%, #ffe8c8 0%, #f8d6af 33%, transparent 72%),
      radial-gradient(ellipse at 71% 47%, #f8d0a0, #e8b187 83%);
    box-shadow: inset 0 1px 0 #fff3dc9e, 0 12px 28px -22px #6c391d8a;
  }
  .grain, .stage canvas, .loading { position: absolute; inset: 0; width: 100%; height: 100%; }
  .grain { pointer-events: none; mix-blend-mode: multiply; }
  .stage canvas { display: block; touch-action: none; cursor: grab; -webkit-tap-highlight-color: transparent; }
  .stage.is-holding canvas { cursor: grabbing; }
  .loading {
    display: grid;
    place-items: center;
    padding: 28px;
    text-align: center;
    font-size: 14px;
    font-weight: 600;
    color: #63432d;
    pointer-events: none;
  }
  .loading[hidden] { display: none; }
  .status {
    position: absolute;
    left: 20px;
    bottom: 19px;
    display: flex;
    align-items: center;
    gap: 8px;
    min-height: 34px;
    padding: 0 11px;
    border: 1px solid #fff2da;
    border-radius: 40px;
    background: #fff5e4df;
    color: #624330;
    box-shadow: 0 2px 7px #9b5f3216;
    font-size: 12px;
    font-weight: 650;
    pointer-events: none;
  }
  .status-dot { width: 7px; height: 7px; border-radius: 50%; background: #bd532d; }
  .demo-marker {
    position: absolute;
    top: 0;
    left: 0;
    width: 28px;
    height: 28px;
    border: 2px solid #fff7e5;
    border-radius: 50%;
    box-shadow: 0 0 0 1px #a64826, inset 0 0 0 1px #a64826, 0 2px 7px #61281058;
    pointer-events: none;
  }
  .demo-marker::after {
    content: "";
    position: absolute;
    inset: 9px;
    background: #fff7e5;
    border-radius: 50%;
  }
  [hidden] { display: none; }

  @media (max-width: 1050px) {
    .shell { width: calc(100% - 66px); }
    .workbench { column-gap: 32px; }
    h1 { font-size: clamp(69px, 9vw, 96px); }
  }
  @media (max-width: 790px) {
    .shell { width: min(598px, calc(100% - 36px)); }
    .masthead { height: 63px; }
    .workbench {
      grid-template-columns: 1fr;
      grid-template-rows: auto;
      grid-template-areas: "intro" "stage" "controls";
      gap: 20px;
      padding-block: 25px 30px;
    }
    .intro { padding-top: 0; }
    h1 { font-size: clamp(55px, 11.8vw, 88px); line-height: .95; }
    h1 br { display: none; }
    .intro p { margin-top: 11px; max-width: 42ch; font-size: 14px; line-height: 1.45; }
    .stage { height: clamp(300px, 80vw, 495px); border-radius: 19px; }
    .controls { margin-top: 0; padding-top: 1px; border: 0; }
    .status { left: 12px; bottom: 12px; }
    .actions { margin-top: 17px; }
  }
</style>
</head>
<body>
<header class="masthead shell">
  <div class="brand">
    <svg viewBox="0 0 36 36" fill="none" aria-hidden="true">
      <circle cx="18" cy="18" r="16" fill="#b64422"/>
      <circle cx="18" cy="18" r="11.4" stroke="#fff2d9" stroke-width="1.35"/>
      <path d="M18 7v22M8.5 12.5l19 11m0-11-19 11" stroke="#fff2d9" stroke-width="1.35" stroke-linecap="round"/>
      <circle cx="18" cy="18" r="2" fill="#fff2d9"/>
    </svg>
    <span>Jelly Lab</span>
  </div>
  <button class="demo" id="demo" type="button" aria-pressed="false" disabled>
    <svg class="play-icon" viewBox="0 0 18 18" fill="none" aria-hidden="true">
      <path d="M6 3.8 14 9l-8 5.2V3.8Z" fill="currentColor" stroke="currentColor" stroke-linejoin="round"/>
    </svg>
    <svg class="pause-icon" viewBox="0 0 18 18" fill="none" aria-hidden="true">
      <path d="M6.4 4.4v9.2m5.2-9.2v9.2" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
    </svg>
    <span id="demo-label">Play demo</span>
  </button>
</header>

<main class="workbench shell">
  <section class="intro" aria-labelledby="title">
    <h1 id="title">Citrus<br> <em>jelly.</em></h1>
    <p id="instructions">Poke the slice to make it jiggle, or drag it to stretch it. Let go and watch it settle.</p>
  </section>

  <div class="stage" id="stage">
    <div class="grain" id="grain" aria-hidden="true"></div>
    <canvas id="view" role="img" aria-label="A 3D orange jelly slice on a white plate" aria-describedby="instructions"></canvas>
    <div class="loading" id="loading" role="status">Setting the plate…</div>
    <div class="status" id="status" hidden>
      <span class="status-dot" aria-hidden="true"></span>
      <span id="status-label">At rest</span>
    </div>
    <div class="demo-marker" id="demo-marker" aria-hidden="true" hidden></div>
  </div>

  <section class="controls" aria-label="Jelly controls">
    <div class="field-head">
      <label for="firmness">Firmness</label>
      <output id="firmness-value" for="firmness">52%</output>
    </div>
    <input id="firmness" type="range" 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="action primary" id="squeeze" type="button" disabled>
        <svg viewBox="0 0 20 20" fill="none" aria-hidden="true">
          <path d="M10 2.3c-2.3 3.6-5.5 6.4-5.5 9.6a5.5 5.5 0 1 0 11 0c0-3.2-3.2-6-5.5-9.6Z" stroke="currentColor" stroke-width="1.55" stroke-linejoin="round"/>
          <path d="M7 12.4c.15 1.1.88 1.83 1.95 2.1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
        </svg>
        Squeeze
      </button>
      <button class="action" id="reset" type="button" disabled>
        <svg viewBox="0 0 20 20" fill="none" aria-hidden="true">
          <path d="M4.2 7.1a6.3 6.3 0 1 1-.15 5.5M4 3.7v3.9h3.9" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        Reset
      </button>
    </div>
  </section>
</main>

<script>
"use strict";

const loading = document.getElementById("loading");

async function loadJelly() {
  try {
    const THREE = await import("https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js");
    createJelly(THREE);
  } catch (error) {
    loading.hidden = false;
    loading.textContent = "The 3D scene couldn’t start. Reload with WebGL and access to the graphics library.";
    console.error(error);
  }
}

function createJelly(THREE) {
  const stage = document.getElementById("stage");
  const canvas = document.getElementById("view");
  const firmnessInput = document.getElementById("firmness");
  const firmnessValue = document.getElementById("firmness-value");
  const squeezeButton = document.getElementById("squeeze");
  const resetButton = document.getElementById("reset");
  const demoButton = document.getElementById("demo");
  const demoLabel = document.getElementById("demo-label");
  const status = document.getElementById("status");
  const statusLabel = document.getElementById("status-label");
  const demoMarker = document.getElementById("demo-marker");

  const TAU = Math.PI * 2;
  const STEP = 1 / 120;
  const DEFAULT_FIRMNESS = 52;
  const clamp = (x, low, high) => Math.min(high, Math.max(low, x));
  const mix = (a, b, t) => a + (b - a) * t;
  function smooth(a, b, value) {
    const t = clamp((value - a) / (b - a), 0, 1);
    return t * t * (3 - 2 * t);
  }
  function randomSource(seed) {
    let state = seed >>> 0;
    return function () {
      state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
      return state / 4294967296;
    };
  }

  const renderer = new THREE.WebGLRenderer({
    canvas, alpha: true, antialias: true, powerPreference: "high-performance"
  });
  renderer.setClearColor(0x000000, 0);
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.03;
  renderer.transmissionResolutionScale = .8;

  const scene = new THREE.Scene();
  const camera = new THREE.OrthographicCamera(-4, 4, 3, -3, .1, 45);
  camera.position.set(2.85, 8.05, 8.95);
  camera.lookAt(0, .28, 0);
  camera.updateMatrixWorld();

  function paintedCanvas(width, height) {
    const image = document.createElement("canvas");
    image.width = width;
    image.height = height;
    return image.getContext("2d");
  }
  function texture(context, color = true, repeat = false) {
    const map = new THREE.CanvasTexture(context.canvas);
    if (color) map.colorSpace = THREE.SRGBColorSpace;
    if (repeat) map.wrapS = THREE.RepeatWrapping;
    map.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
    return map;
  }

  const grain = paintedCanvas(140, 140);
  const paperNoise = randomSource(327);
  const paperPixels = grain.createImageData(140, 140);
  for (let i = 0; i < paperPixels.data.length; i += 4) {
    paperPixels.data[i] = 95;
    paperPixels.data[i + 1] = 57;
    paperPixels.data[i + 2] = 37;
    paperPixels.data[i + 3] = Math.floor(paperNoise() * 23);
  }
  grain.putImageData(paperPixels, 0, 0);
  document.getElementById("grain").style.backgroundImage = 'url("' + grain.canvas.toDataURL() + '")';

  // A painted studio panorama supplies the soft reflections on the glaze.
  const panorama = paintedCanvas(768, 384);
  const studio = panorama.createLinearGradient(0, 0, 0, 384);
  studio.addColorStop(0, "#e5d5c8");
  studio.addColorStop(.37, "#9c887a");
  studio.addColorStop(.56, "#57453e");
  studio.addColorStop(1, "#9c7257");
  panorama.fillStyle = studio;
  panorama.fillRect(0, 0, 768, 384);
  function softbox(x, y, width, height, color) {
    panorama.save();
    panorama.shadowBlur = 21;
    panorama.shadowColor = color;
    panorama.fillStyle = color;
    panorama.fillRect(x, y, width, height);
    panorama.restore();
  }
  softbox(35, 67, 107, 51, "#fff7e7");
  softbox(150, 67, 27, 51, "#f6e6ce");
  softbox(374, 81, 135, 38, "#fff5da");
  softbox(606, 110, 87, 62, "#ffe1b4");
  const panoramaMap = texture(panorama);
  panoramaMap.mapping = THREE.EquirectangularReflectionMapping;
  const pmrem = new THREE.PMREMGenerator(renderer);
  const environment = pmrem.fromEquirectangular(panoramaMap);
  scene.environment = environment.texture;
  panoramaMap.dispose();
  pmrem.dispose();

  scene.add(new THREE.HemisphereLight(0xfff8ee, 0xc78959, 1.04));
  function addLight(color, power, x, y, z) {
    const light = new THREE.DirectionalLight(color, power);
    light.position.set(x, y, z);
    scene.add(light);
  }
  addLight(0xfff9f1, 2.42, -4, 7.3, 2.1);
  addLight(0xffcf90, 1.52, 3, 3.7, -5.4);
  addLight(0xfff8ed, .53, 5, 2.5, 5);

  const plateTop = [
    [0, .084], [1.68, .084], [2.12, .086], [2.25, .100], [2.36, .124],
    [2.49, .165], [2.63, .212], [2.77, .254], [2.90, .275],
    [3.00, .277], [3.09, .263], [3.132, .235], [3.142, .203]
  ];
  const plateProfile = [
    [0, -.105], [1.62, -.105], [1.75, -.132], [1.89, -.147],
    [2.02, -.121], [2.16, -.080], [2.32, -.054], [2.57, -.010],
    [2.82, .049], [3.03, .115], [3.12, .158], ...plateTop.slice().reverse()
  ];
  function plateHeight(radius) {
    for (let i = 1; i < plateTop.length; i++) {
      const [r1, y1] = plateTop[i];
      if (radius <= r1) {
        const [r0, y0] = plateTop[i - 1];
        return mix(y0, y1, (radius - r0) / (r1 - r0));
      }
    }
    return plateTop[plateTop.length - 1][1];
  }

  // The render meshes share a deformable, volume-constrained particle lattice.
  const SIDE = 7;
  const LAYERS = 3;
  const HALF = 2.34;
  const BOTTOM = .110;
  const TOP = .956;
  const PITCH = HALF * 2 / (SIDE - 1);
  const RISE = (TOP - BOTTOM) / (LAYERS - 1);
  const COUNT = SIDE * SIDE * LAYERS;
  const rest = new Float32Array(COUNT * 3);
  const position = new Float32Array(COUNT * 3);
  const prior = new Float32Array(COUNT * 3);
  const velocity = new Float32Array(COUNT * 3);
  const displacement = new Float32Array(COUNT * 3);
  const weight = new Float32Array(COUNT);
  const layer = new Uint8Array(COUNT);
  const floor = new Float32Array(COUNT);
  const edges = [];
  const volumes = [];
  const skins = [];
  const targets = [];

  function node(x, y, z) { return (y * SIDE + z) * SIDE + x; }

  for (let y = 0; y < LAYERS; y++) {
    for (let z = 0; z < SIDE; z++) {
      for (let x = 0; x < SIDE; x++) {
        const i = node(x, y, z);
        const j = i * 3;
        rest[j] = x * PITCH - HALF;
        rest[j + 1] = BOTTOM + y * RISE;
        rest[j + 2] = z * PITCH - HALF;
        weight[i] = [.32, .71, 1][y];
        layer[i] = y;
      }
    }
  }
  position.set(rest);

  for (let y = 0; y < LAYERS; y++) {
    for (let z = 0; z < SIDE; z++) {
      for (let x = 0; x < SIDE; x++) {
        for (let dy = 0; dy <= 1; dy++) {
          for (let dz = -1; dz <= 1; dz++) {
            for (let dx = -1; dx <= 1; dx++) {
              if (dy === 0 && (dz < 0 || (dz === 0 && dx <= 0))) continue;
              if (x + dx < 0 || x + dx >= SIDE || y + dy >= LAYERS || z + dz < 0 || z + dz >= SIDE) continue;
              const a = node(x, y, z);
              const b = node(x + dx, y + dy, z + dz);
              edges.push({
                a: a * 3, b: b * 3, wa: weight[a], wb: weight[b],
                length: Math.hypot(dx * PITCH, dy * RISE, dz * PITCH),
                shear: Math.abs(dx) + dy + Math.abs(dz) > 1,
                lambda: 0
              });
            }
          }
        }
      }
    }
  }
  function addVolume(a, b, c, d) {
    const wa = weight[a], wb = weight[b], wc = weight[c], wd = weight[d];
    a *= 3; b *= 3; c *= 3; d *= 3;
    const ux = rest[b] - rest[a], uy = rest[b + 1] - rest[a + 1], uz = rest[b + 2] - rest[a + 2];
    const vx = rest[c] - rest[a], vy = rest[c + 1] - rest[a + 1], vz = rest[c + 2] - rest[a + 2];
    const wx = rest[d] - rest[a], wy = rest[d + 1] - rest[a + 1], wz = rest[d + 2] - rest[a + 2];
    const volume = ux * (vy * wz - vz * wy) + uy * (vz * wx - vx * wz) + uz * (vx * wy - vy * wx);
    volumes.push({ a, b, c, d, wa, wb, wc, wd, volume, lambda: 0 });
  }
  for (let y = 0; y < LAYERS - 1; y++) {
    for (let z = 0; z < SIDE - 1; z++) {
      for (let x = 0; x < SIDE - 1; x++) {
        const a = node(x, y, z);
        const b = node(x + 1, y, z), c = node(x + 1, y + 1, z);
        const d = node(x, y + 1, z), e = node(x, y + 1, z + 1);
        const f = node(x, y, z + 1), g = node(x + 1, y, z + 1);
        const h = node(x + 1, y + 1, z + 1);
        addVolume(a, b, c, h);
        addVolume(a, c, d, h);
        addVolume(a, d, e, h);
        addVolume(a, e, f, h);
        addVolume(a, f, g, h);
        addVolume(a, g, b, h);
      }
    }
  }

  function embed(x, y, z, ids, factors, offset) {
    const gx = clamp((x + HALF) / PITCH, 0, SIDE - 1);
    const gy = clamp((y - BOTTOM) / RISE, 0, LAYERS - 1);
    const gz = clamp((z + HALF) / PITCH, 0, SIDE - 1);
    const ix = Math.min(SIDE - 2, Math.floor(gx));
    const iy = Math.min(LAYERS - 2, Math.floor(gy));
    const iz = Math.min(SIDE - 2, Math.floor(gz));
    const fx = gx - ix, fy = gy - iy, fz = gz - iz;
    for (let dy = 0; dy <= 1; dy++) {
      for (let dz = 0; dz <= 1; dz++) {
        for (let dx = 0; dx <= 1; dx++) {
          ids[offset] = node(ix + dx, iy + dy, iz + dz) * 3;
          factors[offset] = (dx ? fx : 1 - fx) * (dy ? fy : 1 - fy) * (dz ? fz : 1 - fz);
          offset++;
        }
      }
    }
  }

  function geometryData() { return { xyz: [], uv: [], rgb: [], ids: [] }; }
  function vtx(data, x, y, z, u, v, color) {
    const index = data.xyz.length / 3;
    data.xyz.push(x, y, z);
    data.uv.push(u, v);
    if (color) data.rgb.push(color.r, color.g, color.b);
    return index;
  }
  function quad(data, a, b, c, d) { data.ids.push(a, b, c, a, c, d); }

  function makeMesh(data, material, elastic = false, touchable = false) {
    const geo = new THREE.BufferGeometry();
    const attribute = new THREE.Float32BufferAttribute(data.xyz, 3);
    geo.setAttribute("position", attribute);
    geo.setAttribute("uv", new THREE.Float32BufferAttribute(data.uv, 2));
    if (data.rgb.length) geo.setAttribute("color", new THREE.Float32BufferAttribute(data.rgb, 3));
    geo.setIndex(data.ids);
    geo.computeVertexNormals();
    const mesh = new THREE.Mesh(geo, material);
    if (elastic) {
      attribute.setUsage(THREE.DynamicDrawUsage);
      geo.attributes.normal.setUsage(THREE.DynamicDrawUsage);
      geo.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, .35, 0), 4.05);
      const xyz = attribute.array.slice();
      const ids = new Uint16Array(attribute.count * 8);
      const factors = new Float32Array(ids.length);
      for (let i = 0; i < attribute.count; i++) {
        embed(xyz[i * 3], xyz[i * 3 + 1], xyz[i * 3 + 2], ids, factors, i * 8);
      }
      skins.push({ geo, xyz, ids, factors });
      mesh.userData.restShape = xyz;
    }
    if (touchable) targets.push(mesh);
    scene.add(mesh);
    return mesh;
  }

  function rindWave(angle) {
    return .019 * Math.sin(3 * angle + .43) + .019 * Math.sin(5 * angle - 1.1)
      + .008 * Math.sin(11 * angle + .61) + .004 * Math.cos(17 * angle);
  }
  function rimLift(angle) {
    return .012 * Math.sin(4 * angle + .1) + .006 * Math.cos(9 * angle);
  }
  function ring(profile, slices, organic = false) {
    const data = geometryData();
    const stride = slices + 1;
    for (let j = 0; j < profile.length; j++) {
      const [radius, height] = profile[j];
      for (let i = 0; i <= slices; i++) {
        const angle = TAU * i / slices;
        const r = Math.max(.0001, radius + (organic ? rindWave(angle) : 0));
        const y = height + (organic ? rimLift(angle) * smooth(.13, .76, height) : 0);
        vtx(data, r * Math.cos(angle), y, r * Math.sin(angle), i / slices,
          organic ? clamp((height - .11) / .73, 0, 1) : j / (profile.length - 1));
        if (j < profile.length - 1 && i < slices) {
          const a = j * stride + i;
          quad(data, a, a + stride, a + stride + 1, a + 1);
        }
      }
    }
    return data;
  }

  const whiteGlaze = new THREE.MeshPhysicalMaterial({
    color: 0xfffaf4, roughness: .25, clearcoat: .47, clearcoatRoughness: .20,
    envMapIntensity: .81
  });
  makeMesh(ring(plateProfile, 144), whiteGlaze);

  function gradientMap(stops) {
    const context = paintedCanvas(128, 128);
    const gradient = context.createRadialGradient(64, 64, 0, 64, 64, 64);
    for (const [stop, color] of stops) gradient.addColorStop(stop, color);
    context.fillStyle = gradient;
    context.fillRect(0, 0, 128, 128);
    return texture(context);
  }
  function shadowPlane(map, width, depth, x, y, z) {
    const material = new THREE.MeshBasicMaterial({
      map, transparent: true, depthWrite: false, toneMapped: false,
      polygonOffset: true, polygonOffsetFactor: -1
    });
    const plane = new THREE.Mesh(new THREE.PlaneGeometry(width, depth), material);
    plane.rotation.x = -Math.PI / 2;
    plane.position.set(x, y, z);
    scene.add(plane);
    return plane;
  }
  shadowPlane(gradientMap([
    [0, "#5d321e70"], [.52, "#62351f50"], [.76, "#6b382223"], [1, "#6b382200"]
  ]), 8.0, 7.3, .32, -.151, .36);
  shadowPlane(gradientMap([
    [0, "#532b206e"], [.55, "#532b2042"], [.82, "#793e231d"], [1, "#793e2300"]
  ]), 6.18, 5.98, .09, -.150, .19);

  function disc(radius, rings, sides, surface, uvRadius) {
    const data = geometryData();
    const stride = sides + 1;
    for (let j = 0; j <= rings; j++) {
      for (let i = 0; i <= sides; i++) {
        const a = TAU * i / sides;
        const r = Math.max(.0001, radius * j / rings);
        const p = surface(r, a);
        vtx(data, p[0], p[1], p[2], .5 + p[0] / (2 * uvRadius), .5 - p[2] / (2 * uvRadius));
        if (j < rings && i < sides) {
          const k = j * stride + i;
          quad(data, k, k + 1, k + stride + 1, k + stride);
        }
      }
    }
    return data;
  }

  const contactRadius = 2.72;
  const contactMaterial = new THREE.MeshBasicMaterial({
    transparent: true, depthWrite: false, toneMapped: false,
    map: gradientMap([
      [0, "#b84f216b"], [.69, "#b54b2155"], [.80, "#b8532750"],
      [.845, "#ed9b433a"], [.91, "#dc862215"], [1, "#dc862200"]
    ])
  });
  makeMesh(disc(contactRadius, 27, 100, (r, a) =>
    [r * Math.cos(a) + .026, plateHeight(r) + .006, r * Math.sin(a) + .019],
    contactRadius), contactMaterial);

  function makePeelMaps() {
    const width = 1024, height = 192;
    const col = paintedCanvas(width, height);
    const bump = paintedCanvas(width, height);
    const gradient = col.createLinearGradient(0, 0, 0, height);
    gradient.addColorStop(0, "#ffbc48");
    gradient.addColorStop(.19, "#fb8e20");
    gradient.addColorStop(.54, "#ef7310");
    gradient.addColorStop(.83, "#d15d0d");
    gradient.addColorStop(1, "#bd4c0a");
    col.fillStyle = gradient;
    col.fillRect(0, 0, width, height);
    bump.fillStyle = "#a1a1a1";
    bump.fillRect(0, 0, width, height);
    const random = randomSource(180);
    for (let i = 0; i < 10200; i++) {
      const x = random() * width;
      const y = random() * height;
      const radius = .28 + Math.pow(random(), 2.4) * 2.0;
      col.fillStyle = random() < .68 ? "#8e30104c" : "#ffd16e66";
      col.beginPath();
      col.ellipse(x, y, radius, radius * (.45 + random() * .5), random() * 3, 0, TAU);
      col.fill();
      bump.fillStyle = random() < .8 ? "#464646b3" : "#d3d3d3a1";
      bump.beginPath();
      bump.ellipse(x, y, radius, radius * .72, 0, 0, TAU);
      bump.fill();
    }
    return { color: texture(col, true, true), bump: texture(bump, false, true) };
  }

  const peelMaps = makePeelMaps();
  const peelMaterial = new THREE.MeshPhysicalMaterial({
    color: 0xffffff, map: peelMaps.color, bumpMap: peelMaps.bump, bumpScale: .043,
    roughness: .40, clearcoat: .46, clearcoatRoughness: .31, envMapIntensity: .8
  });
  makeMesh(ring([
    [1.943, .135], [2.024, .115], [2.092, .123], [2.142, .159],
    [2.174, .222], [2.198, .334], [2.206, .465], [2.204, .589],
    [2.191, .686], [2.168, .759], [2.132, .806], [2.092, .826],
    [2.053, .821], [2.023, .796], [2.018, .745]
  ], 144, true), peelMaterial, true, true);

  const pithPaint = paintedCanvas(640, 128);
  pithPaint.fillStyle = "#ffefd4";
  pithPaint.fillRect(0, 0, 640, 128);
  const fiberRandom = randomSource(272);
  for (let i = 0; i < 3700; i++) {
    const x = fiberRandom() * 640, y = fiberRandom() * 128;
    pithPaint.strokeStyle = i % 3 ? "#d7a67528" : "#ffffff6a";
    pithPaint.lineWidth = .35 + fiberRandom();
    pithPaint.beginPath();
    pithPaint.moveTo(x, y);
    pithPaint.quadraticCurveTo(x + 1, y + 2, x + .5 - 2 * fiberRandom(), y + 2 + fiberRandom() * 6);
    pithPaint.stroke();
  }
  const pithMaterial = new THREE.MeshStandardMaterial({
    map: texture(pithPaint, true, true), roughness: .65, envMapIntensity: .55
  });
  makeMesh(ring([
    [1.922, .684], [2.028, .719], [2.076, .786], [2.073, .825],
    [2.050, .834], [2.017, .829], [1.984, .811], [1.952, .788],
    [1.921, .762], [1.908, .732], [1.916, .707]
  ], 144, true), pithMaterial, true, true);

  const ATLAS_RADIUS = 2.23;
  function cellOutline(ctx, l, w, skew) {
    ctx.beginPath();
    ctx.moveTo(-l, 0);
    ctx.bezierCurveTo(-l * .89, -w * .58, -l * .28, -w * (1 + skew), l * .35, -w * .79);
    ctx.bezierCurveTo(l * .86, -w * .64, l * 1.08, -w * .18, l, w * .14);
    ctx.bezierCurveTo(l * .78, w * .91, l * .18, w * (1 - skew), -l * .44, w * .59);
    ctx.quadraticCurveTo(-l * .85, w * .39, -l, 0);
    ctx.closePath();
  }

  function makeCellMaps(seed) {
    const size = 1024;
    const col = paintedCanvas(size, size);
    const bump = paintedCanvas(size, size);
    const center = size / 2;
    const scale = size / (ATLAS_RADIUS * 2);
    const random = randomSource(seed);
    const amber = col.createRadialGradient(center, center, 16, center, center, center);
    amber.addColorStop(0, "#ffbf52");
    amber.addColorStop(.37, "#f69823");
    amber.addColorStop(.78, "#f28516");
    amber.addColorStop(1, "#ffb044");
    col.fillStyle = amber;
    col.fillRect(0, 0, size, size);
    bump.fillStyle = "#707070";
    bump.fillRect(0, 0, size, size);

    for (let row = 0; row < 28; row++) {
      const radius = .19 + row * .068;
      const count = Math.max(14, Math.round(TAU * radius / .060));
      for (let i = 0; i < count; i++) {
        const a = TAU * (i + .46 * (row % 2) + (random() - .5) * .84) / count;
        const r = radius + (random() - .5) * .067;
        const x = center + Math.cos(a) * scale * r;
        const y = center + Math.sin(a) * scale * r;
        const angle = a + (random() - .5) * .81;
        const long = scale * (.029 + .044 * random());
        const wide = scale * (.014 + .021 * random());
        const skew = (random() - .5) * .53;
        const hue = 23 + random() * 18;
        const light = 43 + random() * 17;

        col.save();
        col.translate(x, y);
        col.rotate(angle);
        const paint = col.createLinearGradient(-long * .39, -wide, long * .12, wide);
        paint.addColorStop(0, "hsla(" + (hue + 4) + ",100%," + (light + 16) + "%,.76)");
        paint.addColorStop(.34, "hsla(" + hue + ",94%," + (light + 7) + "%,.84)");
        paint.addColorStop(.68, "hsla(" + hue + ",95%," + light + "%,.82)");
        paint.addColorStop(1, "hsla(" + (hue - 6) + ",89%," + (light - 8) + "%,.69)");
        col.fillStyle = paint;
        cellOutline(col, long, wide, skew);
        col.fill();
        col.strokeStyle = "#b9511356";
        col.lineWidth = .75;
        col.stroke();
        if (random() < .31) {
          col.strokeStyle = "#fff0bb75";
          col.lineWidth = .65 + random() * .57;
          col.beginPath();
          col.moveTo(-long * .55, -wide * .18);
          col.quadraticCurveTo(-long * .18, -wide * .61, long * .37, -wide * .45);
          col.stroke();
        }
        col.restore();

        bump.save();
        bump.translate(x, y);
        bump.rotate(angle);
        const height = bump.createLinearGradient(0, -wide, 0, wide);
        height.addColorStop(0, "#747474");
        height.addColorStop(.47, "#c9c9c9");
        height.addColorStop(1, "#767676");
        bump.fillStyle = height;
        cellOutline(bump, long, wide, skew);
        bump.fill();
        bump.restore();
      }
    }
    for (let i = 0; i < 380; i++) {
      const a = TAU * random();
      const r = Math.sqrt(random()) * 2.06;
      const x = center + Math.cos(a) * scale * r;
      const y = center + Math.sin(a) * scale * r;
      const radius = .45 + Math.pow(random(), 2) * 3.25;
      col.strokeStyle = "#9c42164d";
      col.lineWidth = .7;
      col.beginPath();
      col.ellipse(x, y, radius, radius * .72, a, 0, TAU);
      col.stroke();
      col.fillStyle = "#fff3bd86";
      col.fillRect(x - radius * .38, y - radius * .46, radius * .48, Math.max(.5, radius * .26));
    }
    return { color: texture(col), bump: texture(bump, false) };
  }

  const pulpMaps = makeCellMaps(6503);
  const tissueMaterial = new THREE.MeshStandardMaterial({
    color: 0xffcc85, map: pulpMaps.color, roughness: .56,
    emissive: 0xec6909, emissiveIntensity: .19, envMapIntensity: .42
  });
  makeMesh(disc(2.04, 15, 96, (r, a) =>
    [r * Math.cos(a), .613 + .020 * Math.sin(9 * a + r * 8) * r / 2, r * Math.sin(a)],
    ATLAS_RADIUS), tissueMaterial, true);

  const crystalData = geometryData();
  const vesicle = new THREE.SphereGeometry(1, 7, 5);
  const vesiclePositions = vesicle.attributes.position.array;
  const vesicleIndices = vesicle.index.array;
  const crystalRandom = randomSource(3415);
  const honey = new THREE.Color(0xffbc48), ochre = new THREE.Color(0xe47a13);
  for (let i = 0; i < 124; i++) {
    const angle = crystalRandom() * TAU;
    const r = .32 + Math.sqrt(crystalRandom()) * 1.61;
    const c = Math.cos(angle), s = Math.sin(angle);
    const lx = .030 + crystalRandom() * .052;
    const lz = .018 + crystalRandom() * .025;
    const ly = .013 + crystalRandom() * .012;
    const y = .636 + crystalRandom() * .062;
    const shade = honey.clone().lerp(ochre, crystalRandom() * .85);
    const offset = crystalData.xyz.length / 3;
    for (let j = 0; j < vesiclePositions.length; j += 3) {
      const dx = vesiclePositions[j] * lx, dz = vesiclePositions[j + 2] * lz;
      vtx(crystalData, (r + dx) * c - dz * s, y + vesiclePositions[j + 1] * ly,
        (r + dx) * s + dz * c, 0, 0, shade);
    }
    for (const index of vesicleIndices) crystalData.ids.push(offset + index);
  }
  vesicle.dispose();
  makeMesh(crystalData, new THREE.MeshStandardMaterial({
    vertexColors: true, roughness: .34, emissive: 0xeb850e, emissiveIntensity: .10
  }), true);

  const SEGMENTS = 10;
  const segmentRandom = randomSource(927);
  const seams = Array.from({ length: SEGMENTS }, (_, i) =>
    i * TAU / SEGMENTS - .14 + (segmentRandom() - .5) * .132);
  function seam(index, t) {
    const i = index % SEGMENTS;
    return seams[i] + (index === SEGMENTS ? TAU : 0)
      + Math.sin(Math.PI * t) * (.025 * Math.sin(8.1 * i + 3.7 * t) + .013 * Math.cos(i + 12 * t));
  }

  const membraneMaterial = new THREE.MeshStandardMaterial({
    color: 0xffdfaa, roughness: .57, envMapIntensity: .52,
    emissive: 0xf5a34c, emissiveIntensity: .07
  });
  const membranes = geometryData();
  const radialSteps = 32;
  for (let lane = 0; lane < SEGMENTS; lane++) {
    const start = membranes.xyz.length / 3;
    for (let j = 0; j <= radialSteps; j++) {
      const t = j / radialSteps;
      const radius = mix(.116, 1.988, t);
      const a = seam(lane, t);
      const width = .022 + .014 * Math.pow(t, 4) + .004 * Math.sin(t * 27 + lane * 5);
      for (let k = -1; k <= 1; k++) {
        const u = a + width * k / radius;
        const y = .741 + .014 * Math.sin(Math.PI * t) + .013 * t
          + (k === 0 ? .009 : -.005) + .005 * Math.sin(14 * t + lane);
        vtx(membranes, radius * Math.cos(u), y, radius * Math.sin(u), t, (k + 1) / 2);
      }
      if (j < radialSteps) {
        for (let k = 0; k < 2; k++) {
          const q = start + j * 3 + k;
          quad(membranes, q, q + 1, q + 4, q + 3);
        }
      }
    }
  }
  makeMesh(membranes, membraneMaterial, true, true);
  makeMesh(disc(.237, 8, 70, (r, a) => {
    const f = r / .237;
    const shape = 1 + .14 * Math.sin(3 * a + .5) + .088 * Math.cos(7 * a + 1.4);
    const y = .759 + .058 * Math.sin(Math.PI * f * .87) - .009 * f
      + .012 * Math.sin(5 * a + .7) * f;
    return [r * shape * Math.cos(a), y, r * shape * Math.sin(a)];
  }, .26), pithMaterial, true, true);

  const pulpMaterial = new THREE.MeshPhysicalMaterial({
    vertexColors: true, map: pulpMaps.color, bumpMap: pulpMaps.bump, bumpScale: .038,
    color: 0xffffff, transmission: .52, thickness: .38, ior: 1.36,
    attenuationColor: new THREE.Color(0xffa542), attenuationDistance: .89,
    roughness: .27, clearcoat: .84, clearcoatRoughness: .14, envMapIntensity: .93,
    emissive: 0xff7b15, emissiveMap: pulpMaps.color, emissiveIntensity: .20
  });
  const pulp = geometryData();
  const along = 23, across = 15, stride = across + 1;
  for (let sector = 0; sector < SEGMENTS; sector++) {
    const start = pulp.xyz.length / 3;
    const tip = .169 + segmentRandom() * .042;
    const swell = .098 + segmentRandom() * .049;
    const tone = new THREE.Color().setRGB(1, .79 + segmentRandom() * .18, .77 + segmentRandom() * .15);
    const litEdge = new THREE.Color().setRGB(1, 1, .95);
    const surfaceColor = new THREE.Color();
    const direction = (seam(sector, .5) + seam(sector + 1, .5)) / 2;
    for (let j = 0; j <= along; j++) {
      const t = j / along;
      const approxRadius = mix(tip, 1.97, t);
      const startAngle = seam(sector, t), endAngle = seam(sector + 1, t);
      const gutter = .018 / approxRadius + .006;
      for (let i = 0; i <= across; i++) {
        const s = i / across;
        const a = mix(startAngle + gutter, endAngle - gutter, s);
        const corner = Math.pow(Math.abs(2 * s - 1), 5);
        const inner = tip + .105 * corner;
        const outer = 1.988 + .67 * rindWave(a) - .060 * corner;
        const r = mix(inner, outer, t);
        const dome = Math.pow(Math.max(0, Math.sin(Math.PI * t) * Math.sin(Math.PI * s)), .58);
        const y = .750 + .018 * t + swell * dome
          + .010 * Math.sin(25 * t + sector + s * 4) * dome + rimLift(a) * t * .52;
        const x = r * Math.cos(a), z = r * Math.sin(a);
        surfaceColor.copy(tone).lerp(litEdge, .64 * (1 - dome) + .11 * t);
        vtx(pulp, x, y, z, .5 + x / (2 * ATLAS_RADIUS), .5 - z / (2 * ATLAS_RADIUS), surfaceColor);
        if (j < along && i < across) {
          const q = start + j * stride + i;
          quad(pulp, q, q + 1, q + stride + 1, q + stride);
        }
      }
    }
    const perimeter = [];
    for (let i = 0; i < across; i++) perimeter.push(start + i);
    for (let j = 0; j < along; j++) perimeter.push(start + j * stride + across);
    for (let i = across; i > 0; i--) perimeter.push(start + along * stride + i);
    for (let j = along; j > 0; j--) perimeter.push(start + j * stride);
    const end = pulp.xyz.length / 3;
    for (const vertex of perimeter) {
      const j = vertex * 3;
      const x = mix(pulp.xyz[j], Math.cos(direction) * 1.05, .026);
      const z = mix(pulp.xyz[j + 2], Math.sin(direction) * 1.05, .026);
      vtx(pulp, x, .623, z, .5 + x / (2 * ATLAS_RADIUS), .5 - z / (2 * ATLAS_RADIUS), litEdge);
    }
    for (let i = 0; i < perimeter.length; i++) {
      const j = (i + 1) % perimeter.length;
      quad(pulp, perimeter[i], end + i, end + j, perimeter[j]);
    }
  }
  makeMesh(pulp, pulpMaterial, true, true);

  let firmness = DEFAULT_FIRMNESS / 100;
  let awake = true;
  let activity = false;
  let quietFor = 0;
  let dirty = true;
  let squeezeAge = -1;
  let shedCount = 0;
  let grab = null;
  let pointer = null;
  let pokes = [];
  const drops = [];
  const randomDrops = randomSource(4754);

  const dropGeometry = new THREE.SphereGeometry(1, 24, 15);
  const dropMaterial = new THREE.MeshPhysicalMaterial({
    color: 0xffad39, roughness: .15, transmission: .29,
    thickness: .14, ior: 1.36, attenuationColor: new THREE.Color(0xf68117),
    attenuationDistance: .31, clearcoat: 1, clearcoatRoughness: .095,
    envMapIntensity: 1.15, emissive: 0xc8640a, emissiveIntensity: .09
  });
  const dropShadowGeometry = new THREE.PlaneGeometry(1, 1);
  const dropShadowMap = gradientMap([
    [0, "#9d40168f"], [.55, "#b755232f"], [1, "#b7552300"]
  ]);
  const sampleIds = new Uint16Array(8);
  const sampleWeights = new Float32Array(8);
  function deformedPoint(x, y, z, target) {
    embed(x, y, z, sampleIds, sampleWeights, 0);
    let dx = 0, dy = 0, dz = 0;
    for (let i = 0; i < 8; i++) {
      const j = sampleIds[i], w = sampleWeights[i];
      dx += (position[j] - rest[j]) * w;
      dy += (position[j + 1] - rest[j + 1]) * w;
      dz += (position[j + 2] - rest[j + 2]) * w;
    }
    return target.set(x + dx, y + dy, z + dz);
  }

  function wake() {
    quietFor = 0;
    awake = true;
    dirty = true;
  }
  function setFirmness(value) {
    firmnessInput.value = String(value);
    firmness = Number(firmnessInput.value) / 100;
    firmnessValue.value = firmnessInput.value + "%";
    firmnessInput.style.setProperty("--fill", firmnessInput.value + "%");
    wake();
  }

  function poke(point, strength = 1) {
    const x = point.x, z = point.z;
    const influence = new Float32Array(COUNT);
    for (let i = 0; i < COUNT; i++) {
      const j = i * 3, dx = rest[j] - x, dz = rest[j + 2] - z;
      const w = Math.exp(-(dx * dx + dz * dz) / .64) * [.06, .49, 1][layer[i]];
      influence[i] = w;
      velocity[j] += dx * w * .74 * strength;
      velocity[j + 1] -= w * (2.64 - firmness * .74) * strength;
      velocity[j + 2] += dz * w * .74 * strength;
    }
    if (pokes.length >= 6) pokes.shift();
    pokes.push({ influence, time: 0, strength });
    activity = true;
    wake();
  }

  function startGrab(point) {
    const influence = new Float32Array(COUNT);
    const height = clamp((point.y - BOTTOM) / (TOP - BOTTOM), 0, 1);
    for (let i = 0; i < COUNT; i++) {
      const j = i * 3;
      const dx = rest[j] - point.x, dz = rest[j + 2] - point.z;
      const vertical = [.09, .65 - .19 * height, .64 + .36 * height][layer[i]];
      influence[i] = vertical * Math.exp(-(dx * dx + dz * dz) / .94);
    }
    grab = { influence, origin: position.slice(), delta: new THREE.Vector3() };
    activity = true;
    wake();
  }

  function squeeze() {
    if (squeezeAge >= 0) return;
    squeezeAge = 0;
    shedCount = 0;
    squeezeButton.classList.add("is-pressing");
    activity = true;
    wake();
  }

  function removeDrop(drop) {
    scene.remove(drop.mesh, drop.shadow);
    drop.shadow.material.dispose();
  }
  function shedDrop(index) {
    if (drops.length >= 22) removeDrop(drops.shift());
    const angle = [.98, 1.52, .55, 1.84, 1.20][index];
    const size = [.083, .107, .074, .093, .062][index];
    const x = Math.cos(angle), z = Math.sin(angle);
    const radius = 2.199 + rindWave(angle);
    const born = deformedPoint(x * radius, .385 - .031 * (index % 3), z * radius, new THREE.Vector3());
    const mesh = new THREE.Mesh(dropGeometry, dropMaterial);
    const shadow = new THREE.Mesh(dropShadowGeometry, new THREE.MeshBasicMaterial({
      map: dropShadowMap, transparent: true, depthWrite: false, toneMapped: false
    }));
    shadow.rotation.x = -Math.PI / 2;
    const speed = 1.56 + randomDrops() * .42;
    const motion = new THREE.Vector3(x * speed, -.12 - randomDrops() * .26, z * speed);
    mesh.position.copy(born);
    mesh.scale.setScalar(size);
    drops.push({ mesh, shadow, motion, size, landed: false, still: false });
    scene.add(mesh, shadow);
  }

  const dropUp = new THREE.Vector3(0, 1, 0);
  const dropDirection = new THREE.Vector3();
  function updateDrops(dt) {
    for (const drop of drops) {
      if (drop.still) continue;
      const { mesh, shadow, motion, size } = drop;
      motion.y -= 8.9 * dt;
      mesh.position.addScaledVector(motion, dt);
      const origin = mesh.position;
      let r = Math.hypot(origin.x, origin.z);
      if (r > 2.98) {
        const ux = origin.x / r, uz = origin.z / r;
        origin.x = ux * 2.98;
        origin.z = uz * 2.98;
        const speedOut = motion.x * ux + motion.z * uz;
        if (speedOut > 0) {
          motion.x -= speedOut * ux * 1.55;
          motion.z -= speedOut * uz * 1.55;
        }
        r = 2.98;
      }
      const ground = plateHeight(r);
      const atPlate = ground + size * (drop.landed ? .47 : .65);
      if (origin.y <= atPlate) {
        origin.y = atPlate;
        if (!drop.landed && motion.y < -1.2) {
          motion.y *= -.14;
        } else {
          motion.y = 0;
        }
        drop.landed = true;
        const drag = Math.exp(-8.5 * dt);
        motion.x *= drag;
        motion.z *= drag;
      }
      if (drop.landed) {
        mesh.quaternion.identity();
        mesh.scale.set(size * 1.14, size * .51, size * 1.07);
        drop.still = Math.hypot(motion.x, motion.z) < .024 && motion.y === 0;
      } else {
        dropDirection.copy(motion).normalize();
        mesh.quaternion.setFromUnitVectors(dropUp, dropDirection);
        mesh.scale.set(size * .85, size * 1.26, size * .85);
      }
      shadow.position.set(origin.x, ground + .007, origin.z);
      shadow.scale.set(size * 3.6, size * 3.4, 1);
      shadow.material.opacity = clamp(1.19 - (origin.y - ground) * 2.45, .18, .87);
    }
  }

  function solveEdges(compliance) {
    for (const edge of edges) {
      const { a, b, wa, wb } = edge;
      const dx = position[b] - position[a], dy = position[b + 1] - position[a + 1];
      const dz = position[b + 2] - position[a + 2];
      const length = Math.sqrt(dx * dx + dy * dy + dz * dz);
      if (length < .00001) continue;
      const alpha = compliance * (edge.shear ? 1.85 : 1);
      const correction = (edge.length - length - alpha * edge.lambda) / (wa + wb + alpha);
      edge.lambda += correction;
      const scale = correction / length;
      const x = dx * scale, y = dy * scale, z = dz * scale;
      position[a] -= wa * x; position[a + 1] -= wa * y; position[a + 2] -= wa * z;
      position[b] += wb * x; position[b + 1] += wb * y; position[b + 2] += wb * z;
    }
  }

  function solveVolumes(alpha) {
    for (const tet of volumes) {
      const { a, b, c, d, wa, wb, wc, wd } = tet;
      const ux = position[b] - position[a], uy = position[b + 1] - position[a + 1], uz = position[b + 2] - position[a + 2];
      const vx = position[c] - position[a], vy = position[c + 1] - position[a + 1], vz = position[c + 2] - position[a + 2];
      const wx = position[d] - position[a], wy = position[d + 1] - position[a + 1], wz = position[d + 2] - position[a + 2];
      const bx = vy * wz - vz * wy, by = vz * wx - vx * wz, bz = vx * wy - vy * wx;
      const cx = wy * uz - wz * uy, cy = wz * ux - wx * uz, cz = wx * uy - wy * ux;
      const dx = uy * vz - uz * vy, dy = uz * vx - ux * vz, dz = ux * vy - uy * vx;
      const ax = -bx - cx - dx, ay = -by - cy - dy, az = -bz - cz - dz;
      const v = ux * bx + uy * by + uz * bz;
      const mass = wa * (ax * ax + ay * ay + az * az) + wb * (bx * bx + by * by + bz * bz)
        + wc * (cx * cx + cy * cy + cz * cz) + wd * (dx * dx + dy * dy + dz * dz);
      const correction = (tet.volume - v - alpha * tet.lambda) / (mass + alpha);
      tet.lambda += correction;
      position[a] += correction * wa * ax; position[a + 1] += correction * wa * ay; position[a + 2] += correction * wa * az;
      position[b] += correction * wb * bx; position[b + 1] += correction * wb * by; position[b + 2] += correction * wb * bz;
      position[c] += correction * wc * cx; position[c + 1] += correction * wc * cy; position[c + 2] += correction * wc * cz;
      position[d] += correction * wd * dx; position[d + 1] += correction * wd * dy; position[d + 2] += correction * wd * dz;
    }
  }

  function solveContact() {
    for (let i = 0; i < COUNT; i++) {
      const j = i * 3;
      const dx = position[j] - rest[j], dz = position[j + 2] - rest[j + 2];
      const limit = [.45, .71, .86][layer[i]];
      const d2 = dx * dx + dz * dz;
      if (d2 > limit * limit) {
        const scale = limit / Math.sqrt(d2);
        position[j] = rest[j] + dx * scale;
        position[j + 2] = rest[j + 2] + dz * scale;
      }
      floor[i] = BOTTOM;
      if (rest[j] * rest[j] + rest[j + 2] * rest[j + 2] < 4.96) {
        floor[i] = Math.max(BOTTOM, plateHeight(Math.hypot(position[j], position[j + 2])) + .011);
      }
      position[j + 1] = clamp(position[j + 1], floor[i], rest[j + 1] + .73);
    }
  }

  const shedTimes = [.40, .50, .61, .71, .84];
  function physicsStep(dt) {
    let pressure = 0;
    if (squeezeAge >= 0) {
      squeezeAge += dt;
      pressure = smooth(0, .53, squeezeAge) * (1 - smooth(.66, 1.28, squeezeAge));
      while (shedCount < shedTimes.length && squeezeAge >= shedTimes[shedCount]) {
        shedDrop(shedCount++);
      }
      if (squeezeAge >= 1.30) {
        squeezeAge = -1;
        squeezeButton.classList.remove("is-pressing");
      }
    }
    for (const tap of pokes) tap.time += dt;
    pokes = pokes.filter(tap => tap.time < .15);

    prior.set(position);
    const drag = Math.exp(-dt * (3.45 + firmness * 1.68));
    const bodySpring = 24 + firmness * 60;
    const handSpring = 223 - 67 * firmness;
    for (let i = 0; i < COUNT; i++) {
      const j = i * 3;
      const yLayer = layer[i];
      const support = bodySpring + (2 - yLayer) * 29;
      let ax = (rest[j] - position[j]) * support;
      let ay = (rest[j + 1] - position[j + 1]) * (bodySpring + 25) - 1.45;
      let az = (rest[j + 2] - position[j + 2]) * support;

      for (const tap of pokes) {
        ay -= tap.influence[i] * tap.strength * (1 - tap.time / .15) * (93 - firmness * 35);
      }
      if (grab) {
        const k = grab.influence[i] * handSpring;
        const damping = grab.influence[i] * 7.1;
        ax += (grab.origin[j] + grab.delta.x - position[j]) * k - velocity[j] * damping;
        ay += (grab.origin[j + 1] + grab.delta.y - position[j + 1]) * k - velocity[j + 1] * damping;
        az += (grab.origin[j + 2] + grab.delta.z - position[j + 2]) * k - velocity[j + 2] * damping;
      }
      if (pressure > 0) {
        const k = pressure * (218 - 55 * firmness) * [.15, .69, 1][yLayer];
        const targetX = rest[j] * (1 - .44 * pressure);
        const targetY = rest[j + 1] + .23 * pressure * yLayer / 2;
        const targetZ = rest[j + 2] * (1 + .132 * pressure);
        ax += k * (targetX - position[j]);
        ay += k * (targetY - position[j + 1]);
        az += k * (targetZ - position[j + 2]);
      }

      velocity[j] = (velocity[j] + ax * dt) * drag;
      velocity[j + 1] = (velocity[j + 1] + ay * dt) * drag;
      velocity[j + 2] = (velocity[j + 2] + az * dt) * drag;
      position[j] += velocity[j] * dt;
      position[j + 1] += velocity[j + 1] * dt;
      position[j + 2] += velocity[j + 2] * dt;
    }

    for (const edge of edges) edge.lambda = 0;
    for (const tet of volumes) tet.lambda = 0;
    const compliance = mix(2.35, .61, firmness);
    const volumeCompliance = mix(.27, .109, firmness);
    for (let iteration = 0; iteration < 4; iteration++) {
      solveEdges(compliance);
      solveVolumes(volumeCompliance);
      solveContact();
    }

    let speed = 0;
    for (let i = 0; i < COUNT; i++) {
      const j = i * 3;
      const grounded = position[j + 1] <= floor[i] + .0002;
      const friction = grounded ? .81 : 1;
      velocity[j] = clamp((position[j] - prior[j]) * friction / dt, -8, 8);
      velocity[j + 1] = clamp((position[j + 1] - prior[j + 1]) / dt, grounded ? 0 : -8, 8);
      velocity[j + 2] = clamp((position[j + 2] - prior[j + 2]) * friction / dt, -8, 8);
      speed = Math.max(speed, Math.abs(velocity[j]), Math.abs(velocity[j + 1]), Math.abs(velocity[j + 2]));
    }

    updateDrops(dt);
    if (speed < .018 && !grab && squeezeAge < 0 && !pokes.length && drops.every(drop => drop.still)) {
      quietFor += dt;
      if (quietFor > .46) {
        awake = false;
        velocity.fill(0);
      }
    } else {
      quietFor = 0;
    }
  }

  function deformSurfaces() {
    for (let i = 0; i < displacement.length; i++) displacement[i] = position[i] - rest[i];
    for (const { geo, xyz, ids, factors } of skins) {
      const attr = geo.attributes.position;
      const values = attr.array;
      for (let i = 0; i < attr.count; i++) {
        const j = i * 3, end = i * 8 + 8;
        let x = xyz[j], y = xyz[j + 1], z = xyz[j + 2];
        for (let k = i * 8; k < end; k++) {
          const id = ids[k], factor = factors[k];
          x += displacement[id] * factor;
          y += displacement[id + 1] * factor;
          z += displacement[id + 2] * factor;
        }
        if (y < .296) y = Math.max(y, plateHeight(Math.sqrt(x * x + z * z)) + .013);
        values[j] = x; values[j + 1] = y; values[j + 2] = z;
      }
      attr.needsUpdate = true;
      geo.computeVertexNormals();
    }
  }

  function resetJelly() {
    if (pointer && canvas.hasPointerCapture(pointer.id)) canvas.releasePointerCapture(pointer.id);
    grab = null;
    pointer = null;
    stage.classList.remove("is-holding");
    position.set(rest);
    prior.set(rest);
    velocity.fill(0);
    pokes = [];
    squeezeAge = -1;
    squeezeButton.classList.remove("is-pressing");
    while (drops.length) removeDrop(drops.pop());
    activity = false;
    setFirmness(DEFAULT_FIRMNESS);
    deformSurfaces();
  }

  const raycaster = new THREE.Raycaster();
  const ndc = new THREE.Vector2();
  const planeNormal = new THREE.Vector3();
  const planePoint = new THREE.Vector3();
  const vA = new THREE.Vector3(), vB = new THREE.Vector3(), vC = new THREE.Vector3();
  const bary = new THREE.Vector3();

  function pointerRay(event) {
    const rect = canvas.getBoundingClientRect();
    ndc.set(2 * (event.clientX - rect.left) / rect.width - 1,
      1 - 2 * (event.clientY - rect.top) / rect.height);
    raycaster.setFromCamera(ndc, camera);
  }
  function undeformedHit(hit) {
    const { a, b, c } = hit.face;
    const shape = hit.object.userData.restShape;
    const attr = hit.object.geometry.attributes.position;
    vA.fromBufferAttribute(attr, a);
    vB.fromBufferAttribute(attr, b);
    vC.fromBufferAttribute(attr, c);
    THREE.Triangle.getBarycoord(hit.point, vA, vB, vC, bary);
    return new THREE.Vector3(
      shape[3 * a] * bary.x + shape[3 * b] * bary.y + shape[3 * c] * bary.z,
      shape[3 * a + 1] * bary.x + shape[3 * b + 1] * bary.y + shape[3 * c + 1] * bary.z,
      shape[3 * a + 2] * bary.x + shape[3 * b + 2] * bary.y + shape[3 * c + 2] * bary.z
    );
  }

  canvas.addEventListener("pointerdown", event => {
    if (pointer || event.button !== 0) return;
    stopDemo();
    pointerRay(event);
    const hit = raycaster.intersectObjects(targets, false)[0];
    if (!hit) return;
    event.preventDefault();
    const point = undeformedHit(hit);
    camera.getWorldDirection(planeNormal);
    pointer = {
      id: event.pointerId, x: event.clientX, y: event.clientY,
      hit: hit.point.clone(), point,
      plane: new THREE.Plane().setFromNormalAndCoplanarPoint(planeNormal, hit.point),
      dragging: false
    };
    canvas.setPointerCapture(event.pointerId);
    stage.classList.add("is-holding");
    poke(point);
  });
  canvas.addEventListener("pointermove", event => {
    if (!pointer || event.pointerId !== pointer.id) return;
    if (!pointer.dragging) {
      if (Math.hypot(event.clientX - pointer.x, event.clientY - pointer.y) < 4) return;
      pointer.dragging = true;
      startGrab(pointer.point);
    }
    pointerRay(event);
    if (raycaster.ray.intersectPlane(pointer.plane, planePoint)) {
      grab.delta.copy(planePoint).sub(pointer.hit).clampLength(0, 1.39);
      grab.delta.y += Math.min(.18, Math.hypot(grab.delta.x, grab.delta.z) * .14);
      grab.delta.y = clamp(grab.delta.y, -.57, .85);
      wake();
    }
  });
  function endPointer(event) {
    if (!pointer || event.pointerId !== pointer.id) return;
    pointer = null;
    grab = null;
    stage.classList.remove("is-holding");
    wake();
  }
  for (const type of ["pointerup", "pointercancel", "lostpointercapture"]) {
    canvas.addEventListener(type, endPointer);
  }

  let demoOn = false;
  let demoStart = 0;
  let demoNext = 0;
  let demoCaption = "Poke";
  let demoMarkUntil = 0;
  let swallowDemoClick = false;
  const demoTarget = new THREE.Vector3();
  const projectedDemo = new THREE.Vector3();
  const demoRest = new THREE.Vector3(-1.22, .855, .57);

  function demoPoke(x, z, time, force = 1) {
    demoTarget.set(x, .85, z);
    demoMarkUntil = demoStart + (time + .56) * 1000;
    poke(demoTarget, force);
  }
  const demoCues = [
    [1.10, () => demoPoke(-.72, .62, 1.10)],
    [2.64, () => demoPoke(.91, .83, 2.64, 1.09)],
    [4.00, () => { demoCaption = "Stretch"; startGrab(demoRest); }],
    [6.58, () => { grab = null; wake(); }],
    [8.15, () => { demoCaption = "Soft"; setFirmness(17); }],
    [8.82, () => demoPoke(-.57, .70, 8.82)],
    [10.84, () => { demoCaption = "Firm"; setFirmness(88); }],
    [11.49, () => demoPoke(-.57, .70, 11.49)],
    [13.71, () => { demoCaption = "Squeeze"; setFirmness(45); squeeze(); }],
    [18.18, () => { demoCaption = "Reset"; resetJelly(); }]
  ];

  function startDemo(now) {
    resetJelly();
    demoOn = true;
    demoStart = now;
    demoCaption = "Poke";
    demoNext = 0;
    demoMarkUntil = 0;
    demoButton.setAttribute("aria-pressed", "true");
    demoLabel.textContent = "Stop demo";
  }
  function stopDemo() {
    if (!demoOn) return;
    demoOn = false;
    grab = null;
    demoMarker.hidden = true;
    demoButton.setAttribute("aria-pressed", "false");
    demoLabel.textContent = "Play demo";
    wake();
  }
  function advanceDemo(now) {
    const elapsed = (now - demoStart) / 1000;
    if (elapsed >= 20) {
      startDemo(demoStart + Math.floor(elapsed / 20) * 20000);
      return;
    }
    while (demoNext < demoCues.length && elapsed >= demoCues[demoNext][0]) {
      demoCues[demoNext][1]();
      demoNext++;
    }
    if (elapsed >= 4 && elapsed < 6.58 && grab) {
      const pull = smooth(4, 5.63, elapsed);
      grab.delta.set(-1.09 * pull, .57 * pull, .20 * pull);
    }
  }
  function drawDemoMarker(now) {
    if (!demoOn) return;
    const stretching = demoCaption === "Stretch" && grab;
    const show = stretching || now < demoMarkUntil;
    demoMarker.hidden = !show;
    if (!show) return;
    const target = stretching ? demoRest : demoTarget;
    deformedPoint(target.x, target.y, target.z, projectedDemo).project(camera);
    const x = (projectedDemo.x + 1) * canvas.clientWidth / 2;
    const y = (1 - projectedDemo.y) * canvas.clientHeight / 2;
    demoMarker.style.transform = "translate3d(" + x + "px," + y + "px,0) translate(-50%,-50%)";
  }

  window.addEventListener("pointerdown", event => {
    if (!event.isTrusted) return;
    swallowDemoClick = demoOn && demoButton.contains(event.target);
    stopDemo();
  }, true);

  demoButton.addEventListener("click", event => {
    if (swallowDemoClick && event.detail !== 0) {
      swallowDemoClick = false;
      return;
    }
    if (demoOn) stopDemo();
    else startDemo(performance.now());
  });
  squeezeButton.addEventListener("click", () => { stopDemo(); squeeze(); });
  resetButton.addEventListener("click", () => { stopDemo(); resetJelly(); });
  firmnessInput.addEventListener("input", () => {
    stopDemo();
    setFirmness(Number(firmnessInput.value));
  });
  window.addEventListener("hashchange", () => {
    if (location.hash === "#demo") startDemo(performance.now());
    else stopDemo();
  });

  function resize() {
    const w = Math.max(1, canvas.clientWidth), h = Math.max(1, canvas.clientHeight);
    const aspect = w / h;
    const height = Math.max(5.71, 7.57 / aspect);
    camera.top = height / 2;
    camera.bottom = -height / 2;
    camera.left = -height * aspect / 2;
    camera.right = height * aspect / 2;
    camera.updateProjectionMatrix();
    renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.75));
    renderer.setSize(w, h, false);
    dirty = true;
  }
  if (typeof ResizeObserver === "function") new ResizeObserver(resize).observe(stage);
  window.addEventListener("resize", resize);
  resize();

  let last = performance.now();
  let accumulator = 0;
  function frame(now) {
    const dt = clamp((now - last) / 1000, 0, .05);
    last = now;
    if (demoOn) advanceDemo(now);
    if (awake) {
      accumulator = Math.min(accumulator + dt, STEP * 6);
      let stepped = false;
      while (accumulator >= STEP && awake) {
        physicsStep(STEP);
        accumulator -= STEP;
        stepped = true;
      }
      if (stepped) {
        deformSurfaces();
        dirty = true;
      }
    } else {
      accumulator = 0;
    }
    if (dirty) {
      renderer.render(scene, camera);
      dirty = false;
    }
    drawDemoMarker(now);
    let label = "At rest";
    if (demoOn) label = "Demo · " + demoCaption;
    else if (squeezeAge >= 0) label = "Squeezing";
    else if (grab) label = "Stretching";
    else if (awake && activity) label = "Jiggling";
    if (statusLabel.textContent !== label) statusLabel.textContent = label;
    requestAnimationFrame(frame);
  }

  setFirmness(DEFAULT_FIRMNESS);
  renderer.render(scene, camera);
  loading.hidden = true;
  status.hidden = false;
  for (const control of [firmnessInput, squeezeButton, resetButton, demoButton]) control.disabled = false;
  if (location.hash === "#demo") startDemo(performance.now());
  requestAnimationFrame(frame);
}

loadJelly();
</script>
</body>
</html>