Skip to content
VibeCodeBench
Back to the app

The code

Jelly Orange Slice by Claude Opus 5.5

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

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)37.5 KB · 744 lines · loads unpkg.com/[email protected]/build/three.module.js, unpkg.com/[email protected]/examples/jsm/
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Orange Jelly Slice</title>
<style>
  html,body{margin:0;height:100%;overflow:hidden;background:#e9dcc8;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#3b2a1a;-webkit-user-select:none;user-select:none;touch-action:none;-webkit-tap-highlight-color:transparent}
  canvas#c{display:block;position:fixed;inset:0;width:100%;height:100%;touch-action:none}
  #hud{position:fixed;left:0;right:0;top:0;padding:14px 16px 0;pointer-events:none;text-align:center}
  #hud h1{margin:0;font-size:21px;letter-spacing:.3px;color:#6a3a0a;text-shadow:0 1px 0 rgba(255,255,255,.6)}
  #hint{margin-top:4px;font-size:14px;opacity:.85;transition:opacity 1.2s}
  #panel{position:fixed;left:50%;bottom:calc(12px + env(safe-area-inset-bottom));transform:translateX(-50%);display:flex;gap:10px;flex-wrap:wrap;align-items:center;justify-content:center;background:rgba(255,250,242,.84);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:10px 12px;border-radius:22px;box-shadow:0 6px 24px rgba(90,50,10,.18);width:min(580px,calc(100% - 24px));box-sizing:border-box}
  button{font:inherit;font-weight:700;font-size:17px;min-height:54px;min-width:112px;padding:0 20px;border:0;border-radius:16px;cursor:pointer;color:#fff;background:linear-gradient(#ffa22a,#f07000);box-shadow:0 3px 0 #b85200;touch-action:manipulation}
  button:active{transform:translateY(2px);box-shadow:0 1px 0 #b85200}
  button:disabled{opacity:.55}
  #reset{background:linear-gradient(#fff,#efe6da);color:#5a4020;box-shadow:0 3px 0 #c9b99f}
  .slider{display:flex;flex-direction:column;flex:1 1 180px;min-width:170px;padding:0 4px}
  .slider label{font-size:14px;font-weight:700;display:flex;justify-content:space-between}
  input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:44px;background:transparent;margin:0;touch-action:none}
  input[type=range]::-webkit-slider-runnable-track{height:10px;border-radius:5px;background:linear-gradient(90deg,#ffe0a8,#ff8a00)}
  input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:34px;height:34px;border-radius:50%;background:#fff;border:3px solid #f07000;margin-top:-12px;box-shadow:0 2px 6px rgba(0,0,0,.25)}
  input[type=range]::-moz-range-track{height:10px;border-radius:5px;background:linear-gradient(90deg,#ffe0a8,#ff8a00)}
  input[type=range]::-moz-range-thumb{width:28px;height:28px;border-radius:50%;background:#fff;border:3px solid #f07000}
  #finger{position:fixed;left:0;top:0;width:46px;height:46px;margin:-23px 0 0 -23px;border-radius:50%;background:rgba(255,255,255,.4);border:3px solid rgba(255,255,255,.95);box-shadow:0 2px 10px rgba(0,0,0,.3);pointer-events:none;opacity:0;transition:opacity .25s,transform .15s;z-index:5}
  #finger.down{transform:scale(.72)}
  #demoTag{position:fixed;right:12px;top:12px;font-size:12px;font-weight:700;background:#f07000;color:#fff;padding:5px 10px;border-radius:10px;display:none;pointer-events:none}
  #err{position:fixed;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:24px;font-size:16px;background:#e9dcc8}
</style>
<script type="importmap">
{"imports":{
  "three":"https://unpkg.com/[email protected]/build/three.module.js",
  "three/addons/":"https://unpkg.com/[email protected]/examples/jsm/"
}}
</script>
</head>
<body>
<canvas id="c"></canvas>
<div id="hud"><h1>Orange Jelly Slice</h1><div id="hint">Tap to poke &middot; drag the jelly to stretch it &middot; drag the background to look around</div></div>
<div id="panel">
  <button id="squeeze">Squeeze</button>
  <div class="slider"><label for="firm"><span>Firmness</span><span id="firmVal">Medium</span></label><input id="firm" type="range" min="0" max="1" step="0.01" value="0.5"></div>
  <button id="reset">Reset</button>
</div>
<div id="finger"></div>
<div id="demoTag">DEMO</div>
<div id="err">Sorry, this demo needs WebGL and could not start.</div>

<script type="module">
import * as THREE from 'three';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';

const $ = id => document.getElementById(id);
const canvas = $('c');
let renderer;
try {
  renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
} catch (e) { $('err').style.display = 'flex'; throw e; }
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

const scene = new THREE.Scene();
scene.background = new THREE.Color('#e9dcc8');
scene.fog = new THREE.Fog('#e9dcc8', 10, 24);
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(renderer), 0.04).texture;

const camera = new THREE.PerspectiveCamera(38, 1, 0.05, 60);
const camState = { az: 0.35, el: 0.86, dist: 5, target: new THREE.Vector3(0, 0.12, 0) };

// ---------- lights ----------
scene.add(new THREE.HemisphereLight('#fff6ea', '#b59a7a', 0.55));
const key = new THREE.DirectionalLight('#fff1dc', 2.4);
key.position.set(2.5, 6, 3);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
Object.assign(key.shadow.camera, { left: -3, right: 3, top: 3, bottom: -3, near: 1, far: 15 });
key.shadow.bias = -0.0004; key.shadow.normalBias = 0.02; key.shadow.radius = 4;
scene.add(key);
const rim = new THREE.DirectionalLight('#ffcf8a', 2.0);
rim.position.set(-3, 2.2, -4);
scene.add(rim);
const glow = new THREE.PointLight('#ffb766', 5, 7, 2);
glow.position.set(-0.6, 0.6, -1.9);
scene.add(glow);

// ---------- helpers ----------
function rng(seed) {
  return () => { seed |= 0; seed = seed + 0x6D2B79F5 | 0; let t = Math.imul(seed ^ seed >>> 15, 1 | seed); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };
}
const maxAniso = renderer.capabilities.getMaxAnisotropy();
function tex(c, srgb, repeat) {
  const t = new THREE.CanvasTexture(c);
  t.colorSpace = srgb ? THREE.SRGBColorSpace : THREE.NoColorSpace;
  t.anisotropy = maxAniso;
  if (repeat) { t.wrapS = THREE.RepeatWrapping; }
  return t;
}

// ---------- table ----------
{
  const c = document.createElement('canvas'); c.width = c.height = 512;
  const g = c.getContext('2d');
  const gr = g.createRadialGradient(256, 256, 20, 256, 256, 256);
  gr.addColorStop(0, '#f3e8d6'); gr.addColorStop(1, '#d6c3a5');
  g.fillStyle = gr; g.fillRect(0, 0, 512, 512);
  const r = rng(3);
  for (let i = 0; i < 9000; i++) { g.fillStyle = `rgba(120,90,50,${r() * 0.05})`; g.fillRect(r() * 512, r() * 512, 1 + r() * 2, 1); }
  const table = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), new THREE.MeshStandardMaterial({ map: tex(c, true), roughness: 0.92 }));
  table.rotation.x = -Math.PI / 2; table.position.y = -0.1; table.receiveShadow = true;
  scene.add(table);
}

// ---------- plate ----------
const PLATE_FLAT = 1.6;
function plateY(r) { if (r <= PLATE_FLAT) return 0; const k = Math.min(1, (r - PLATE_FLAT) / 0.68); return k * k * 0.16; }
{
  const pts = [[0, 0], [1.6, 0], [1.85, 0.028], [2.05, 0.08], [2.2, 0.13], [2.28, 0.16], [2.33, 0.158], [2.33, 0.135], [2.2, 0.1], [2.0, 0.035], [1.7, -0.04], [1.3, -0.06], [1.25, -0.1], [0, -0.1]]
    .map(p => new THREE.Vector2(p[0], p[1]));
  const geo = new THREE.LatheGeometry(pts, 128);
  const mat = new THREE.MeshPhysicalMaterial({ color: '#fbfaf6', roughness: 0.16, clearcoat: 1, clearcoatRoughness: 0.05, side: THREE.DoubleSide });
  const plate = new THREE.Mesh(geo, mat);
  plate.receiveShadow = true; plate.castShadow = true;
  scene.add(plate);
}

// ---------- textures for the citrus ----------
function makeFlesh() {
  const S = 1024, C = S / 2, RP = S / 2;
  const mk = () => { const c = document.createElement('canvas'); c.width = c.height = S; return [c, c.getContext('2d')]; };
  const [cc, g] = mk(), [tc, tg] = mk(), [bc, bg] = mk();
  const rand = rng(7);
  const circ = (ctx, r, fill) => { ctx.fillStyle = fill; ctx.beginPath(); ctx.arc(C, C, r, 0, Math.PI * 2); ctx.fill(); };
  // peel / pith / membrane base
  g.fillStyle = '#e66d00'; g.fillRect(0, 0, S, S);
  const pg = g.createRadialGradient(C, C, RP * 0.9, C, C, RP);
  pg.addColorStop(0, '#ffb23a'); pg.addColorStop(1, '#ef7400');
  circ(g, RP, pg);
  circ(g, RP * 0.957, '#fff4dc');
  circ(g, RP * 0.905, '#fde6bc');
  tg.fillStyle = '#2a2a2a'; tg.fillRect(0, 0, S, S);
  circ(tg, RP, '#6a6a6a'); circ(tg, RP * 0.957, '#3c3c3c'); circ(tg, RP * 0.905, '#a8a8a8');
  bg.fillStyle = '#808080'; bg.fillRect(0, 0, S, S);
  circ(bg, RP * 0.957, '#8c8c8c'); circ(bg, RP * 0.905, '#959595');

  const NSEG = 11;
  const ws = []; let tot = 0;
  for (let k = 0; k < NSEG; k++) { const w = 0.85 + rand() * 0.3; ws.push(w); tot += w; }
  let a = rand() * Math.PI * 2;
  for (let k = 0; k < NSEG; k++) {
    const a0 = a, a1 = a + ws[k] / tot * Math.PI * 2; a = a1;
    const mid = (a0 + a1) / 2;
    const r0 = RP * 0.085, r1 = RP * 0.885, gap = 4.5, steps = 12;
    const p = new Path2D();
    for (let s = 0; s <= steps; s++) { const r = r0 + (r1 - r0) * s / steps, an = a0 + gap / r; const x = C + r * Math.cos(an), y = C + r * Math.sin(an); s ? p.lineTo(x, y) : p.moveTo(x, y); }
    p.arc(C, C, r1, a0 + gap / r1, a1 - gap / r1);
    for (let s = steps; s >= 0; s--) { const r = r0 + (r1 - r0) * s / steps, an = a1 - gap / r; p.lineTo(C + r * Math.cos(an), C + r * Math.sin(an)); }
    p.closePath();
    const hue = 28 + rand() * 6, light = 52 + rand() * 6;
    const sg = g.createRadialGradient(C, C, r0, C, C, r1);
    sg.addColorStop(0, `hsl(${hue + 6},100%,${light + 12}%)`); sg.addColorStop(1, `hsl(${hue},100%,${light}%)`);
    g.fillStyle = sg; g.fill(p);
    tg.fillStyle = '#f2f2f2'; tg.fill(p);
    bg.fillStyle = '#727272'; bg.fill(p);
    // juice cells (vesicles)
    g.save(); g.clip(p); tg.save(); tg.clip(p); bg.save(); bg.clip(p);
    const n = 340;
    for (let i = 0; i < n; i++) {
      const rr = RP * Math.sqrt(0.012 + rand() * 0.77);
      const an = a0 + (a1 - a0) * rand();
      const rot = an + (mid - an) * 0.3;
      const f = rr / RP;
      const L = 9 + f * 27, W = 3.2 + f * 5.2;
      const x = C + rr * Math.cos(an), y = C + rr * Math.sin(an);
      for (const [ctx, kind] of [[g, 0], [tg, 1], [bg, 2]]) {
        ctx.save(); ctx.translate(x, y); ctx.rotate(rot);
        let grd = ctx.createRadialGradient(-L * 0.25, -W * 0.3, 0, 0, 0, L);
        if (kind === 0) { grd.addColorStop(0, 'rgba(255,222,135,0.95)'); grd.addColorStop(0.45, `hsla(${hue + 4},100%,${light + 4}%,0.92)`); grd.addColorStop(1, 'rgba(222,92,0,0.9)'); }
        else if (kind === 1) { grd.addColorStop(0, 'rgba(255,255,255,0.7)'); grd.addColorStop(1, 'rgba(190,190,190,0.6)'); }
        else { grd.addColorStop(0, 'rgba(225,225,225,0.95)'); grd.addColorStop(1, 'rgba(105,105,105,0.7)'); }
        ctx.fillStyle = grd; ctx.beginPath(); ctx.ellipse(0, 0, L, W, 0, 0, Math.PI * 2); ctx.fill();
        if (kind === 0) { ctx.strokeStyle = 'rgba(255,238,195,0.35)'; ctx.lineWidth = 1; ctx.stroke(); }
        ctx.restore();
      }
    }
    g.restore(); tg.restore(); bg.restore();
  }
  // core pith
  circ(g, RP * 0.085, '#fdeccb'); circ(g, RP * 0.05, '#fff6e2');
  circ(tg, RP * 0.085, '#555'); circ(bg, RP * 0.085, '#909090');
  return { map: tex(cc, true), trans: tex(tc, false), bump: tex(bc, false) };
}
function makePeel() {
  const W = 1024, H = 256;
  const mk = () => { const c = document.createElement('canvas'); c.width = W; c.height = H; return [c, c.getContext('2d')]; };
  const [cc, g] = mk(), [bc, bg] = mk();
  const gr = g.createLinearGradient(0, 0, 0, H);
  gr.addColorStop(0, '#ff9e2c'); gr.addColorStop(0.5, '#ff8a10'); gr.addColorStop(1, '#f07400');
  g.fillStyle = gr; g.fillRect(0, 0, W, H);
  bg.fillStyle = '#909090'; bg.fillRect(0, 0, W, H);
  const r = rng(11);
  for (let i = 0; i < 6000; i++) {
    const x = r() * W, y = r() * H, s = 0.7 + r() * 1.9;
    g.fillStyle = 'rgba(196,84,0,0.35)'; g.beginPath(); g.arc(x, y, s, 0, 7); g.fill();
    g.fillStyle = 'rgba(255,215,150,0.22)'; g.beginPath(); g.arc(x - s * 0.6, y - s * 0.6, s * 0.6, 0, 7); g.fill();
    bg.fillStyle = 'rgba(40,40,40,0.6)'; bg.beginPath(); bg.arc(x, y, s, 0, 7); bg.fill();
  }
  return { map: tex(cc, true, true), bump: tex(bc, false, true) };
}
const flesh = makeFlesh(), peel = makePeel();

// ---------- jelly geometry ----------
const R = 1.0, H = 0.34, BEV = 0.07, RC = R - BEV;
const verts = [], uvs = [], capIdx = [], sideIdx = [];
function addV(x, y, z, u, v) { verts.push(x, y, z); uvs.push(u, v); return verts.length / 3 - 1; }
const NRm = 22, NAm = 96;
for (const top of [true, false]) {
  const y = top ? H : 0;
  const c = addV(0, y, 0, 0.5, 0.5);
  const ring = [];
  for (let j = 1; j <= NRm; j++) {
    const row = [], rho = RC * j / NRm;
    for (let k = 0; k < NAm; k++) {
      const t = k / NAm * Math.PI * 2, x = rho * Math.cos(t), z = rho * Math.sin(t);
      row.push(addV(x, y, z, 0.5 + x / (2 * RC), 0.5 + z / (2 * RC)));
    }
    ring.push(row);
  }
  for (let k = 0; k < NAm; k++) {
    const k1 = (k + 1) % NAm, a = ring[0][k], b = ring[0][k1];
    top ? capIdx.push(c, b, a) : capIdx.push(c, a, b);
    for (let j = 0; j < NRm - 1; j++) {
      const A = ring[j][k], B = ring[j][k1], Cc = ring[j + 1][k], D = ring[j + 1][k1];
      if (top) capIdx.push(A, B, Cc, B, D, Cc); else capIdx.push(A, Cc, B, B, Cc, D);
    }
  }
}
{
  const prof = [];
  const NB = 6;
  for (let s = 0; s <= NB; s++) { const f = -Math.PI / 2 + s / NB * Math.PI / 2; prof.push([RC + BEV * Math.cos(f), BEV + BEV * Math.sin(f)]); }
  prof.push([R, H * 0.5]);
  for (let s = 0; s <= NB; s++) { const f = s / NB * Math.PI / 2; prof.push([RC + BEV * Math.cos(f), H - BEV + BEV * Math.sin(f)]); }
  const M = prof.length, grid = [];
  for (let m = 0; m < M; m++) {
    const row = [];
    for (let k = 0; k <= NAm; k++) {
      const t = k / NAm * Math.PI * 2;
      row.push(addV(prof[m][0] * Math.cos(t), prof[m][1], prof[m][0] * Math.sin(t), k / NAm * 3, m / (M - 1)));
    }
    grid.push(row);
  }
  for (let m = 0; m < M - 1; m++) for (let k = 0; k < NAm; k++) {
    const e = grid[m][k], f = grid[m][k + 1], g2 = grid[m + 1][k], h = grid[m + 1][k + 1];
    sideIdx.push(e, g2, f, f, g2, h);
  }
}
const NV = verts.length / 3;
const restV = new Float32Array(verts);
const jellyGeo = new THREE.BufferGeometry();
const posAttr = new THREE.BufferAttribute(new Float32Array(verts), 3);
posAttr.setUsage(THREE.DynamicDrawUsage);
jellyGeo.setAttribute('position', posAttr);
jellyGeo.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
jellyGeo.setIndex([...capIdx, ...sideIdx]);
jellyGeo.addGroup(0, capIdx.length, 0);
jellyGeo.addGroup(capIdx.length, sideIdx.length, 1);
jellyGeo.computeVertexNormals();

const fleshMat = new THREE.MeshPhysicalMaterial({
  map: flesh.map, transmission: 1, transmissionMap: flesh.trans, thickness: 0.35,
  attenuationColor: new THREE.Color('#ff7a00'), attenuationDistance: 0.55, ior: 1.36,
  roughness: 0.1, clearcoat: 1, clearcoatRoughness: 0.05, bumpMap: flesh.bump, bumpScale: 1.2,
  emissive: new THREE.Color('#ff6a00'), emissiveMap: flesh.trans, emissiveIntensity: 0.32, specularIntensity: 1
});
const peelMat = new THREE.MeshPhysicalMaterial({
  map: peel.map, bumpMap: peel.bump, bumpScale: 2, roughness: 0.3, clearcoat: 0.9, clearcoatRoughness: 0.12,
  transmission: 0.35, thickness: 0.15, attenuationColor: new THREE.Color('#ff6a00'), attenuationDistance: 0.4,
  emissive: new THREE.Color('#ff5a00'), emissiveIntensity: 0.12, sheen: 0.3, sheenColor: new THREE.Color('#ffb060')
});
peel.map.repeat.set(1, 1); peel.bump.repeat.set(1, 1);
const jelly = new THREE.Mesh(jellyGeo, [fleshMat, peelMat]);
jelly.castShadow = true;
scene.add(jelly);

// ---------- soft body lattice ----------
const NRING = 4, NANG = 24, NLAY = 3, PER = 1 + NRING * NANG, N = PER * NLAY;
function pid(l, i, a) { if (i === 0) return l * PER; a = ((a % NANG) + NANG) % NANG; return l * PER + 1 + (i - 1) * NANG + a; }
const rest = new Float32Array(N * 3), pos = new Float32Array(N * 3), vel = new Float32Array(N * 3), frc = new Float32Array(N * 3), Q = new Float32Array(N * 3);
for (let l = 0; l < NLAY; l++) {
  const y = l / (NLAY - 1) * H;
  rest.set([0, y, 0], pid(l, 0, 0) * 3);
  for (let i = 1; i <= NRING; i++) for (let a = 0; a < NANG; a++) {
    const t = a / NANG * Math.PI * 2, r = i / NRING * R;
    rest.set([r * Math.cos(t), y, r * Math.sin(t)], pid(l, i, a) * 3);
  }
}
{
  let cx = 0, cy = 0, cz = 0;
  for (let n = 0; n < N; n++) { cx += rest[n * 3]; cy += rest[n * 3 + 1]; cz += rest[n * 3 + 2]; }
  cx /= N; cy /= N; cz /= N;
  for (let n = 0; n < N; n++) { Q[n * 3] = rest[n * 3] - cx; Q[n * 3 + 1] = rest[n * 3 + 1] - cy; Q[n * 3 + 2] = rest[n * 3 + 2] - cz; }
}
// springs
const spA = [], spB = [], spL = [];
for (let i = 0; i < N; i++) for (let j = i + 1; j < N; j++) {
  const dx = rest[j * 3] - rest[i * 3], dy = rest[j * 3 + 1] - rest[i * 3 + 1], dz = rest[j * 3 + 2] - rest[i * 3 + 2];
  const d = Math.sqrt(dx * dx + dy * dy + dz * dz);
  if (d > 1e-5 && d < 0.42) { spA.push(i); spB.push(j); spL.push(d); }
}
const NS = spA.length;
const SA = Int32Array.from(spA), SB = Int32Array.from(spB), SL = Float32Array.from(spL);
// Aqq inverse
function inv3(m) {
  const [a, b, c, d, e, f, g, h, i] = m;
  const A = e * i - f * h, B = -(d * i - f * g), Cc = d * h - e * g, det = a * A + b * B + c * Cc, id = 1 / det;
  return [A * id, -(b * i - c * h) * id, (b * f - c * e) * id, B * id, (a * i - c * g) * id, -(a * f - c * d) * id, Cc * id, -(a * h - b * g) * id, (a * e - b * d) * id];
}
const AqqI = (() => { const m = [0, 0, 0, 0, 0, 0, 0, 0, 0]; for (let n = 0; n < N; n++) { const q = [Q[n * 3], Q[n * 3 + 1], Q[n * 3 + 2]]; for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) m[r * 3 + c] += q[r] * q[c]; } return inv3(m); })();

// skin binding: each render vertex follows 8 lattice particles
const bindI = new Int32Array(NV * 8), bindW = new Float32Array(NV * 8);
for (let v = 0; v < NV; v++) {
  const x = restV[v * 3], y = restV[v * 3 + 1], z = restV[v * 3 + 2];
  const rho = Math.hypot(x, z);
  let th = Math.atan2(z, x); if (th < 0) th += Math.PI * 2;
  const u = Math.min(rho / R * NRING, NRING), i0 = Math.min(Math.floor(u), NRING - 1), fu = u - i0;
  const av = th / (Math.PI * 2) * NANG, a0 = Math.floor(av), fa = av - a0;
  const wl = Math.min(y / H * (NLAY - 1), NLAY - 1), l0 = Math.min(Math.floor(wl), NLAY - 2), fl = wl - l0;
  let k = 0;
  for (let di = 0; di < 2; di++) for (let da = 0; da < 2; da++) for (let dl = 0; dl < 2; dl++) {
    bindI[v * 8 + k] = pid(l0 + dl, i0 + di, a0 + da);
    bindW[v * 8 + k] = (di ? fu : 1 - fu) * (da ? fa : 1 - fa) * (dl ? fl : 1 - fl);
    k++;
  }
}

// ---------- simulation parameters ----------
const P = { kS: 300, cS: 1.2, kSh: 40, damp: 1.0, pressY: Infinity, beta: 0.35 };
const GRAV = 5, FRICTION = 9, KG = 260, CG = 9;
function applyFirmness(f) {
  P.kS = 60 + 560 * f; P.kSh = 6 + 75 * f; P.cS = 0.5 + 1.6 * f; P.damp = 0.45 + 1.3 * f;
  $('firmVal').textContent = f < 0.33 ? 'Wobbly' : f < 0.67 ? 'Medium' : 'Firm';
}
const qr = [0, 0, 0, 1];
const RM = new Float64Array(9);
function extractRotation(a00, a01, a02, a10, a11, a12, a20, a21, a22) {
  for (let it = 0; it < 4; it++) {
    const [x, y, z, w] = qr;
    const r00 = 1 - 2 * (y * y + z * z), r01 = 2 * (x * y - z * w), r02 = 2 * (x * z + y * w);
    const r10 = 2 * (x * y + z * w), r11 = 1 - 2 * (x * x + z * z), r12 = 2 * (y * z - x * w);
    const r20 = 2 * (x * z - y * w), r21 = 2 * (y * z + x * w), r22 = 1 - 2 * (x * x + y * y);
    RM[0] = r00; RM[1] = r01; RM[2] = r02; RM[3] = r10; RM[4] = r11; RM[5] = r12; RM[6] = r20; RM[7] = r21; RM[8] = r22;
    // omega = sum(Rcol_i x Acol_i) / |sum(Rcol_i . Acol_i)|
    let ox = 0, oy = 0, oz = 0, dd = 0;
    const cols = [[r00, r10, r20, a00, a10, a20], [r01, r11, r21, a01, a11, a21], [r02, r12, r22, a02, a12, a22]];
    for (const [rx, ry, rz, ax, ay, az] of cols) {
      ox += ry * az - rz * ay; oy += rz * ax - rx * az; oz += rx * ay - ry * ax; dd += rx * ax + ry * ay + rz * az;
    }
    const inv = 1 / (Math.abs(dd) + 1e-9); ox *= inv; oy *= inv; oz *= inv;
    const wl = Math.sqrt(ox * ox + oy * oy + oz * oz);
    if (wl < 1e-9) break;
    const s = Math.sin(wl / 2) / wl, bx = ox * s, by = oy * s, bz = oz * s, bw = Math.cos(wl / 2);
    const nx = bw * x + bx * w + by * z - bz * y;
    const ny = bw * y - bx * z + by * w + bz * x;
    const nz = bw * z + bx * y - by * x + bz * w;
    const nw = bw * w - bx * x - by * y - bz * z;
    const nl = Math.hypot(nx, ny, nz, nw) || 1;
    qr[0] = nx / nl; qr[1] = ny / nl; qr[2] = nz / nl; qr[3] = nw / nl;
  }
  const [x, y, z, w] = qr;
  RM[0] = 1 - 2 * (y * y + z * z); RM[1] = 2 * (x * y - z * w); RM[2] = 2 * (x * z + y * w);
  RM[3] = 2 * (x * y + z * w); RM[4] = 1 - 2 * (x * x + z * z); RM[5] = 2 * (y * z - x * w);
  RM[6] = 2 * (x * z - y * w); RM[7] = 2 * (y * z + x * w); RM[8] = 1 - 2 * (x * x + y * y);
}

const grab = { active: false, ids: [], w: [], off: [], target: new THREE.Vector3(), origin: new THREE.Vector3() };
const com = new THREE.Vector3();

function step(dt) {
  frc.fill(0);
  for (let n = 0; n < N; n++) frc[n * 3 + 1] -= GRAV;
  const kS = P.kS, cS = P.cS;
  for (let s = 0; s < NS; s++) {
    const i = SA[s] * 3, j = SB[s] * 3;
    let dx = pos[j] - pos[i], dy = pos[j + 1] - pos[i + 1], dz = pos[j + 2] - pos[i + 2];
    const len = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1e-6;
    dx /= len; dy /= len; dz /= len;
    const rv = (vel[j] - vel[i]) * dx + (vel[j + 1] - vel[i + 1]) * dy + (vel[j + 2] - vel[i + 2]) * dz;
    const F = kS * (len - SL[s]) + cS * rv;
    const fx = F * dx, fy = F * dy, fz = F * dz;
    frc[i] += fx; frc[i + 1] += fy; frc[i + 2] += fz;
    frc[j] -= fx; frc[j + 1] -= fy; frc[j + 2] -= fz;
  }
  // shape matching (rotation + volume-preserving linear blend)
  let cx = 0, cy = 0, cz = 0;
  for (let n = 0; n < N; n++) { cx += pos[n * 3]; cy += pos[n * 3 + 1]; cz += pos[n * 3 + 2]; }
  cx /= N; cy /= N; cz /= N;
  com.set(cx, cy, cz);
  let a00 = 0, a01 = 0, a02 = 0, a10 = 0, a11 = 0, a12 = 0, a20 = 0, a21 = 0, a22 = 0;
  for (let n = 0; n < N; n++) {
    const k = n * 3, px = pos[k] - cx, py = pos[k + 1] - cy, pz = pos[k + 2] - cz, qx = Q[k], qy = Q[k + 1], qz = Q[k + 2];
    a00 += px * qx; a01 += px * qy; a02 += px * qz;
    a10 += py * qx; a11 += py * qy; a12 += py * qz;
    a20 += pz * qx; a21 += pz * qy; a22 += pz * qz;
  }
  extractRotation(a00, a01, a02, a10, a11, a12, a20, a21, a22);
  const I = AqqI;
  let L = [
    a00 * I[0] + a01 * I[3] + a02 * I[6], a00 * I[1] + a01 * I[4] + a02 * I[7], a00 * I[2] + a01 * I[5] + a02 * I[8],
    a10 * I[0] + a11 * I[3] + a12 * I[6], a10 * I[1] + a11 * I[4] + a12 * I[7], a10 * I[2] + a11 * I[5] + a12 * I[8],
    a20 * I[0] + a21 * I[3] + a22 * I[6], a20 * I[1] + a21 * I[4] + a22 * I[7], a20 * I[2] + a21 * I[5] + a22 * I[8]];
  const det = L[0] * (L[4] * L[8] - L[5] * L[7]) - L[1] * (L[3] * L[8] - L[5] * L[6]) + L[2] * (L[3] * L[7] - L[4] * L[6]);
  let beta = P.beta;
  if (det > 0.08 && isFinite(det)) { const s = 1 / Math.cbrt(det); for (let k = 0; k < 9; k++) L[k] *= s; } else beta = 0;
  const G = new Array(9);
  for (let k = 0; k < 9; k++) G[k] = beta * L[k] + (1 - beta) * RM[k];
  const kSh = P.kSh;
  for (let n = 0; n < N; n++) {
    const k = n * 3, qx = Q[k], qy = Q[k + 1], qz = Q[k + 2];
    frc[k] += kSh * (G[0] * qx + G[1] * qy + G[2] * qz + cx - pos[k]);
    frc[k + 1] += kSh * (G[3] * qx + G[4] * qy + G[5] * qz + cy - pos[k + 1]);
    frc[k + 2] += kSh * (G[6] * qx + G[7] * qy + G[8] * qz + cz - pos[k + 2]);
  }
  // grab
  if (grab.active) {
    for (let m = 0; m < grab.ids.length; m++) {
      const n = grab.ids[m] * 3, w = grab.w[m];
      frc[n] += (KG * (grab.target.x + grab.off[m * 3] - pos[n]) - CG * vel[n]) * w;
      frc[n + 1] += (KG * (grab.target.y + grab.off[m * 3 + 1] - pos[n + 1]) - CG * vel[n + 1]) * w;
      frc[n + 2] += (KG * (grab.target.z + grab.off[m * 3 + 2] - pos[n + 2]) - CG * vel[n + 2]) * w;
    }
  }
  // integrate + contacts
  const damp = Math.max(0, 1 - P.damp * dt), fr = Math.max(0, 1 - FRICTION * dt);
  for (let n = 0; n < N; n++) {
    const k = n * 3;
    let vx = (vel[k] + frc[k] * dt) * damp, vy = (vel[k + 1] + frc[k + 1] * dt) * damp, vz = (vel[k + 2] + frc[k + 2] * dt) * damp;
    const sp = Math.sqrt(vx * vx + vy * vy + vz * vz);
    if (sp > 18) { const s = 18 / sp; vx *= s; vy *= s; vz *= s; }
    let x = pos[k] + vx * dt, y = pos[k + 1] + vy * dt, z = pos[k + 2] + vz * dt;
    let r = Math.hypot(x, z);
    if (r > 2.2) { x *= 2.2 / r; z *= 2.2 / r; r = 2.2; }
    const floor = plateY(r);
    if (y < floor) { y = floor; if (vy < 0) vy *= -0.05; vx *= fr; vz *= fr; }
    if (y > P.pressY) { y = P.pressY; if (vy > 0) vy = 0; vx *= 0.995; vz *= 0.995; }
    pos[k] = x; pos[k + 1] = y; pos[k + 2] = z; vel[k] = vx; vel[k + 1] = vy; vel[k + 2] = vz;
  }
}

function resetBody(lift = 0.28) {
  for (let n = 0; n < N; n++) { pos[n * 3] = rest[n * 3]; pos[n * 3 + 1] = rest[n * 3 + 1] + lift; pos[n * 3 + 2] = rest[n * 3 + 2]; }
  vel.fill(0); qr[0] = qr[1] = qr[2] = 0; qr[3] = 1; grab.active = false;
}
function sane() {
  for (let k = 0; k < N * 3; k++) { const v = pos[k]; if (!(v > -6 && v < 6)) { resetBody(0.2); return; } }
}

function updateMesh() {
  const out = posAttr.array;
  for (let v = 0; v < NV; v++) {
    let dx = 0, dy = 0, dz = 0;
    const b = v * 8;
    for (let k = 0; k < 8; k++) {
      const w = bindW[b + k]; if (w === 0) continue;
      const p = bindI[b + k] * 3;
      dx += w * (pos[p] - rest[p]); dy += w * (pos[p + 1] - rest[p + 1]); dz += w * (pos[p + 2] - rest[p + 2]);
    }
    out[v * 3] = restV[v * 3] + dx; out[v * 3 + 1] = restV[v * 3 + 1] + dy; out[v * 3 + 2] = restV[v * 3 + 2] + dz;
  }
  posAttr.needsUpdate = true;
  jellyGeo.computeVertexNormals();
  jellyGeo.computeBoundingSphere();
  // thinner jelly -> more light through it
  let top = 0, bot = 0;
  for (let i = 0; i < PER; i++) { top += pos[(2 * PER + i) * 3 + 1]; bot += pos[i * 3 + 1]; }
  const ratio = Math.max(0.3, Math.min(1.4, (top - bot) / PER / H));
  fleshMat.thickness = 0.35 * ratio;
  fleshMat.emissiveIntensity = 0.32 + (1 - Math.min(1, ratio)) * 0.5;
}

// ---------- interaction ops ----------
function poke(point, dir, strength = 3.6) {
  const rad = 0.45;
  for (let n = 0; n < N; n++) {
    const k = n * 3, d = Math.hypot(pos[k] - point.x, pos[k + 1] - point.y, pos[k + 2] - point.z);
    if (d < rad) { const w = (1 - d / rad) ** 2 * strength; vel[k] += dir.x * w; vel[k + 1] += dir.y * w; vel[k + 2] += dir.z * w; }
  }
}
function grabStart(point) {
  grab.ids = []; grab.w = []; grab.off = [];
  const rad = 0.4; let best = -1, bd = 1e9;
  for (let n = 0; n < N; n++) {
    const k = n * 3, d = Math.hypot(pos[k] - point.x, pos[k + 1] - point.y, pos[k + 2] - point.z);
    if (d < bd) { bd = d; best = n; }
    if (d < rad) { grab.ids.push(n); grab.w.push(Math.max(0.15, 1 - d / rad)); grab.off.push(pos[k] - point.x, pos[k + 1] - point.y, pos[k + 2] - point.z); }
  }
  if (!grab.ids.length && best >= 0) { const k = best * 3; grab.ids.push(best); grab.w.push(1); grab.off.push(pos[k] - point.x, pos[k + 1] - point.y, pos[k + 2] - point.z); }
  grab.origin.copy(point); grab.target.copy(point); grab.active = true;
}
const tmpV = new THREE.Vector3();
function grabMove(t) {
  tmpV.copy(t).sub(grab.origin);
  const l = tmpV.length(); if (l > 1.1) tmpV.multiplyScalar(1.1 / l);
  grab.target.copy(grab.origin).add(tmpV);
  if (grab.target.y < 0.03) grab.target.y = 0.03;
}
function grabEnd() { grab.active = false; }

// ---------- press (squeeze) ----------
const press = new THREE.Group();
{
  const glass = new THREE.MeshStandardMaterial({ color: '#ffffff', transparent: true, opacity: 0.28, roughness: 0.05, metalness: 0, depthWrite: false });
  const disc = new THREE.Mesh(new THREE.CylinderGeometry(1.35, 1.35, 0.06, 64), glass);
  disc.position.y = 0.03;
  const knob = new THREE.Mesh(new THREE.CylinderGeometry(0.14, 0.18, 0.4, 32), new THREE.MeshPhysicalMaterial({ color: '#f4efe8', roughness: 0.25, clearcoat: 1 }));
  knob.position.y = 0.26;
  const cap = new THREE.Mesh(new THREE.SphereGeometry(0.2, 24, 16), knob.material);
  cap.position.y = 0.48;
  press.add(disc, knob, cap);
  press.visible = false;
  scene.add(press);
}
const sq = { on: false, t: 0, spawned: 0 };
const dropTimes = [1.05, 1.3, 1.55, 1.8, 2.05];
const ease = t => t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
function startSqueeze() { if (sq.on) return; sq.on = true; sq.t = 0; sq.spawned = 0; $('squeeze').disabled = true; }
function updateSqueeze(dt) {
  if (!sq.on) return;
  sq.t += dt;
  const t = sq.t, topY = H + 0.6, low = H * 0.52;
  let y;
  if (t < 1.0) y = topY + (low - topY) * ease(t);
  else if (t < 2.2) y = low - 0.035 * Math.sin((t - 1) / 1.2 * Math.PI);
  else if (t < 3.0) y = low + (topY - low) * ease((t - 2.2) / 0.8);
  else { sq.on = false; P.pressY = Infinity; press.visible = false; $('squeeze').disabled = false; return; }
  P.pressY = y;
  press.visible = true;
  press.position.set(com.x, y, com.z);
  while (sq.spawned < dropTimes.length && t >= dropTimes[sq.spawned]) { spawnDrop(); sq.spawned++; }
}

// ---------- juice drops ----------
const juiceMat = new THREE.MeshPhysicalMaterial({ color: '#ffa424', transmission: 0.85, roughness: 0.03, thickness: 0.06, ior: 1.34, attenuationColor: new THREE.Color('#ff8a00'), attenuationDistance: 0.1, clearcoat: 1, emissive: new THREE.Color('#ff7a00'), emissiveIntensity: 0.15 });
const dropGeo = new THREE.SphereGeometry(1, 20, 14);
const drops = [];
function camTheta() { return Math.atan2(camera.position.z - com.z, camera.position.x - com.x); }
function sidePoint(a, s, out, n) {
  const w = Math.max(0, Math.min(1, s)) * (NLAY - 1), l0 = Math.min(Math.floor(w), NLAY - 2), f = w - l0;
  const p0 = pid(l0, NRING, a) * 3, p1 = pid(l0 + 1, NRING, a) * 3;
  out.set(pos[p0] * (1 - f) + pos[p1] * f, pos[p0 + 1] * (1 - f) + pos[p1 + 1] * f, pos[p0 + 2] * (1 - f) + pos[p1 + 2] * f);
  n.set(out.x - com.x, 0, out.z - com.z).normalize();
}
function spawnDrop() {
  const th = camTheta() + (Math.random() - 0.5) * 2.0;
  let a = Math.round(th / (Math.PI * 2) * NANG);
  const r = 0.035 + Math.random() * 0.02;
  const m = new THREE.Mesh(dropGeo, juiceMat); m.castShadow = true;
  m.scale.setScalar(0.001);
  scene.add(m);
  drops.push({ mesh: m, a, r, s: 0.55 + Math.random() * 0.2, state: 'run', age: 0, p: new THREE.Vector3(), n: new THREE.Vector3(), slide: 0.15 + Math.random() * 0.15 });
}
function updateDrops(dt) {
  for (let i = drops.length - 1; i >= 0; i--) {
    const d = drops[i]; d.age += dt;
    if (d.state === 'run') {
      d.s -= dt * (d.age < 0.25 ? 0.15 : 1.25);
      sidePoint(d.a, d.s, d.p, d.n);
      const grow = Math.min(1, d.age / 0.25);
      const rr = d.r * grow;
      d.mesh.position.copy(d.p).addScaledVector(d.n, rr * 0.7);
      d.mesh.position.y = Math.max(d.mesh.position.y, rr * 0.6);
      d.mesh.scale.set(rr, rr * (d.age > 0.25 ? 1.45 : 1.1), rr);
      if (d.s <= 0) { d.state = 'pool'; d.t = 0; d.p.copy(d.mesh.position).addScaledVector(d.n, d.r * 0.6); d.p.y = 0; }
    } else {
      d.t += dt;
      const k = Math.min(1, d.t / 0.45), e = 1 - Math.pow(1 - k, 3);
      const rad = d.r * (1 + 1.9 * e);
      if (d.slide > 0) { const mv = d.slide * dt * 1.5; d.p.addScaledVector(d.n, mv); d.slide = Math.max(0, d.slide - mv); }
      const rr = Math.hypot(d.p.x, d.p.z);
      d.mesh.position.set(d.p.x, plateY(rr) + 0.001, d.p.z);
      d.mesh.scale.set(rad, d.r * (0.75 - 0.5 * e), rad * 0.92);
      if (d.age > 40) { scene.remove(d.mesh); drops.splice(i, 1); }
    }
  }
}
function clearDrops() { for (const d of drops) scene.remove(d.mesh); drops.length = 0; }

function resetAll() {
  clearDrops(); sq.on = false; P.pressY = Infinity; press.visible = false; $('squeeze').disabled = false;
  resetBody();
}

// ---------- camera ----------
function layout() {
  const w = window.innerWidth, h = window.innerHeight;
  renderer.setSize(w, h, false);
  camera.aspect = w / h; camera.updateProjectionMatrix();
  const tH = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * camera.aspect;
  camState.dist = Math.max(5.0, 1.65 / tH);
}
window.addEventListener('resize', layout);
layout();
function updateCamera() {
  const { az, el, dist, target } = camState;
  camera.position.set(target.x + dist * Math.cos(el) * Math.sin(az), target.y + dist * Math.sin(el), target.z + dist * Math.cos(el) * Math.cos(az));
  camera.lookAt(target);
}

// ---------- UI ----------
const slider = $('firm');
slider.addEventListener('input', () => applyFirmness(+slider.value));
applyFirmness(+slider.value);
$('squeeze').addEventListener('click', () => startSqueeze());
$('reset').addEventListener('click', () => { resetAll(); slider.value = 0.5; applyFirmness(0.5); });

const ray = new THREE.Raycaster(), ndc = new THREE.Vector2(), plane = new THREE.Plane();
let ptr = null;
function setRay(e) { const r = canvas.getBoundingClientRect(); ndc.set((e.clientX - r.left) / r.width * 2 - 1, -(e.clientY - r.top) / r.height * 2 + 1); ray.setFromCamera(ndc, camera); }
let hintHidden = false;
function hideHint() { if (!hintHidden) { hintHidden = true; setTimeout(() => $('hint').style.opacity = '0', 2500); } }
canvas.addEventListener('pointerdown', e => {
  if (ptr) return;
  hideHint();
  try { canvas.setPointerCapture(e.pointerId); } catch (_) {}
  setRay(e);
  const hit = ray.intersectObject(jelly, false)[0];
  ptr = { id: e.pointerId, x: e.clientX, y: e.clientY, lx: e.clientX, ly: e.clientY, moved: false, mode: hit ? 'jelly' : 'orbit' };
  if (hit) {
    ptr.point = hit.point.clone(); ptr.dir = ray.ray.direction.clone();
    plane.setFromNormalAndCoplanarPoint(camera.getWorldDirection(new THREE.Vector3()).negate(), hit.point);
  }
});
canvas.addEventListener('pointermove', e => {
  if (!ptr || e.pointerId !== ptr.id) return;
  if (!ptr.moved && Math.hypot(e.clientX - ptr.x, e.clientY - ptr.y) > 8) {
    ptr.moved = true;
    if (ptr.mode === 'jelly') grabStart(ptr.point);
  }
  if (ptr.mode === 'jelly' && ptr.moved) {
    setRay(e);
    const t = new THREE.Vector3();
    if (ray.ray.intersectPlane(plane, t)) grabMove(t);
  } else if (ptr.mode === 'orbit') {
    camState.az -= (e.clientX - ptr.lx) * 0.006;
    camState.el = Math.max(0.22, Math.min(1.4, camState.el + (e.clientY - ptr.ly) * 0.005));
  }
  ptr.lx = e.clientX; ptr.ly = e.clientY;
});
function endPtr(e) {
  if (!ptr || e.pointerId !== ptr.id) return;
  if (ptr.mode === 'jelly') { if (!ptr.moved) poke(ptr.point, ptr.dir); else grabEnd(); }
  ptr = null;
}
canvas.addEventListener('pointerup', endPtr);
canvas.addEventListener('pointercancel', endPtr);
canvas.addEventListener('contextmenu', e => e.preventDefault());

// ---------- demo mode ----------
const finger = $('finger');
const demo = { on: location.hash === '#demo', T: 0, fingerUntil: 0, fingerWorld: null, fingerScreen: null, grabDir: new THREE.Vector3(), grabOrigin: new THREE.Vector3() };
if (demo.on) $('demoTag').style.display = 'block';
function stopDemo() {
  if (!demo.on) return;
  demo.on = false; grabEnd(); finger.style.opacity = '0'; $('demoTag').style.display = 'none';
}
window.addEventListener('pointerdown', e => { if (e.isTrusted) stopDemo(); }, true);
function frontIndex() { return Math.round(camTheta() / (Math.PI * 2) * NANG); }
function particlePos(l, i, da) { const p = pid(l, i, frontIndex() + da) * 3; return new THREE.Vector3(pos[p], pos[p + 1], pos[p + 2]); }
function demoPoke(i, da) {
  const pt = particlePos(2, i, da);
  const dir = pt.clone().sub(camera.position).normalize();
  poke(pt, dir, 4.2);
  demo.fingerWorld = pt; demo.fingerScreen = null; demo.fingerUntil = demo.T + 0.45;
}
function fingerAtElement(el, frac) {
  const r = el.getBoundingClientRect();
  demo.fingerWorld = null; demo.fingerScreen = [r.left + r.width * (frac ?? 0.5), r.top + r.height / 2]; demo.fingerUntil = demo.T + 0.6;
}
function setFirm(f) { slider.value = f; applyFirmness(f); fingerAtElement(slider, f * 0.85 + 0.075); }
const demoEvents = [
  [0.02, () => { resetAll(); slider.value = 0.5; applyFirmness(0.5); }],
  [1.6, () => demoPoke(1, 0)],
  [3.0, () => demoPoke(3, 4)],
  [4.4, () => { const p = particlePos(2, 4, -3); demo.grabOrigin.copy(p); demo.grabDir.set(p.x - com.x, 0, p.z - com.z).normalize(); grabStart(p); }],
  [6.3, () => grabEnd()],
  [8.0, () => setFirm(0.12)],
  [8.8, () => demoPoke(2, 2)],
  [10.0, () => demoPoke(3, -4)],
  [11.3, () => { fingerAtElement($('squeeze')); startSqueeze(); }],
  [15.0, () => setFirm(0.92)],
  [15.7, () => demoPoke(2, 0)],
  [17.0, () => demoPoke(3, 5)],
  [18.6, () => setFirm(0.5)]
];
function runDemo(dt) {
  const prev = demo.T % 20;
  demo.T += dt;
  const loc = demo.T % 20;
  const wrapped = loc < prev;
  for (const [t, fn] of demoEvents) if ((!wrapped && prev < t && loc >= t) || (wrapped && (t > prev || t <= loc))) fn();
  if (wrapped) demo.fingerUntil = 0;
  camState.az += dt * 0.12;
  if (grab.active && loc >= 4.4 && loc < 6.3) {
    const e = ease(Math.min(1, (loc - 4.4) / 1.4));
    const t = demo.grabOrigin.clone().addScaledVector(demo.grabDir, 0.75 * e); t.y += 0.45 * e;
    grabMove(t);
    demo.fingerWorld = grab.target.clone(); demo.fingerScreen = null; demo.fingerUntil = demo.T + 0.1;
  }
}
function updateFinger() {
  if (!demo.on || demo.T > demo.fingerUntil) { finger.style.opacity = '0'; finger.classList.remove('down'); return; }
  let x, y;
  if (demo.fingerWorld) {
    const v = demo.fingerWorld.clone().project(camera);
    x = (v.x + 1) / 2 * window.innerWidth; y = (1 - v.y) / 2 * window.innerHeight;
  } else if (demo.fingerScreen) { [x, y] = demo.fingerScreen; } else return;
  finger.style.left = x + 'px'; finger.style.top = y + 'px';
  finger.style.opacity = '1'; finger.classList.add('down');
}

// ---------- loop ----------
resetBody();
let last = performance.now();
renderer.setAnimationLoop(() => {
  const now = performance.now();
  const dt = Math.min((now - last) / 1000, 1 / 30); last = now;
  if (demo.on) runDemo(dt);
  updateSqueeze(dt);
  const sub = 12, h = dt / sub;
  for (let i = 0; i < sub; i++) step(h);
  sane();
  updateMesh();
  updateDrops(dt);
  updateCamera();
  updateFinger();
  renderer.render(scene, camera);
});
</script>
</body>
</html>