Skip to content
VibeCodeBench
Back to the app

The code

Jelly Orange Slice by Claude Sonnet 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.)42.6 KB · 1,100 lines · loads cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js, cdn.jsdelivr.net/npm/three@0.160.0/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>Jelly Orange Slice</title>
<style>
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;overflow:hidden;color:#fff;font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-user-select:none;user-select:none;overscroll-behavior:none}
body{background:radial-gradient(ellipse at 50% 26%,#4a6a80 0%,#27394a 48%,#101a23 100%)}
#stage{position:fixed;inset:0}
#stage canvas{display:block;width:100%;height:100%;touch-action:none;cursor:grab}
#title{position:fixed;left:16px;top:calc(12px + env(safe-area-inset-top));pointer-events:none;z-index:4}
#title b{display:block;font-size:20px;letter-spacing:.2px;text-shadow:0 2px 8px rgba(0,0,0,.45)}
#title span{display:block;font-size:13px;opacity:.78;margin-top:3px;transition:opacity .8s}
#cap{position:fixed;left:50%;top:calc(64px + env(safe-area-inset-top));transform:translateX(-50%);padding:9px 18px;border-radius:22px;background:rgba(10,18,26,.66);border:1px solid rgba(255,255,255,.18);font-size:16px;font-weight:600;text-align:center;max-width:calc(100vw - 24px);pointer-events:none;opacity:0;transition:opacity .35s;z-index:4}
#cap.on{opacity:1}
#finger{position:fixed;left:0;top:0;width:54px;height:54px;border-radius:50%;border:3px solid #fff;background:rgba(255,255,255,.22);box-shadow:0 0 0 6px rgba(255,170,40,.28);pointer-events:none;opacity:0;transition:opacity .2s;z-index:6}
#panel{position:fixed;left:50%;bottom:calc(10px + env(safe-area-inset-bottom));transform:translateX(-50%);width:min(580px,calc(100vw - 20px));display:grid;grid-template-columns:1fr 1fr;gap:10px;padding:12px;border-radius:28px;background:rgba(10,18,26,.66);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,.15);z-index:5}
button{font:inherit;font-size:19px;font-weight:800;min-height:58px;border-radius:29px;border:2px solid transparent;cursor:pointer;color:#fff;touch-action:manipulation}
#squeeze{background:linear-gradient(180deg,#ffd447,#ff9b12);color:#3a1d00;box-shadow:0 4px 14px rgba(255,140,0,.38)}
#squeeze.busy{opacity:.55}
#reset{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.45)}
button:active{transform:scale(.97)}
#firm{grid-column:1 / -1;display:block;padding:0 4px}
#firm .row{display:flex;justify-content:space-between;font-size:15px;font-weight:700;margin-bottom:2px}
#firm .row span{opacity:.85;font-weight:600}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:46px;background:transparent;margin:0;display:block}
input[type=range]::-webkit-slider-runnable-track{height:12px;border-radius:6px;background:linear-gradient(90deg,#ffe29a,#ff7a00)}
input[type=range]::-moz-range-track{height:12px;border-radius:6px;background:linear-gradient(90deg,#ffe29a,#ff7a00)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:36px;height:36px;margin-top:-12px;border-radius:50%;background:#fff;border:4px solid #ff8a00;box-shadow:0 2px 8px rgba(0,0,0,.45)}
input[type=range]::-moz-range-thumb{width:28px;height:28px;border-radius:50%;background:#fff;border:4px solid #ff8a00;box-shadow:0 2px 8px rgba(0,0,0,.45)}
#msg{position:fixed;left:50%;top:40%;transform:translateX(-50%);width:min(440px,90vw);padding:18px;border-radius:16px;background:rgba(0,0,0,.7);text-align:center;z-index:9;font-size:16px}
@media (max-width:420px){#title b{font-size:17px}button{font-size:17px;min-height:54px}}
</style>
<script type="importmap">
{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"}}
</script>
</head>
<body>
<div id="stage"></div>
<div id="title"><b>Jelly Orange Slice</b><span id="hint">Tap to poke it. Drag to stretch, then let go.</span></div>
<div id="cap"></div>
<div id="finger"></div>
<div id="panel">
  <button id="squeeze" type="button">Squeeze</button>
  <button id="reset" type="button">Reset</button>
  <label id="firm"><div class="row">Firmness <span id="fv">Medium</span></div><input id="slider" type="range" min="0" max="100" value="50"></label>
</div>
<div id="msg" hidden></div>
<script>
(function(){
  function showMsg(){var m=document.getElementById('msg');if(m){m.hidden=false;m.textContent='Could not start the 3D view. This page needs WebGL and an internet connection to load three.js.';}}
  window.addEventListener('error',function(){if(!window.__ready)showMsg();});
  setTimeout(function(){if(!window.__ready)showMsg();},9000);
})();
</script>
<script type="module">
import * as THREE from 'three';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';

const $ = id => document.getElementById(id);
const clamp = (x, a, b) => Math.min(b, Math.max(a, x));
const lerp = (a, b, t) => a + (b - a) * t;
const smooth = t => t * t * (3 - 2 * t);

/* ------------------------------------------------------------------ renderer */
const stageEl = $('stage');
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x000000, 0);
stageEl.appendChild(renderer.domElement);
const canvas = renderer.domElement;
canvas.addEventListener('contextmenu', e => e.preventDefault());

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(34, 1, 0.1, 80);
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;

const sun = new THREE.DirectionalLight(0xfff0dc, 1.7);
sun.position.set(-5, 10, 6);
scene.add(sun);
scene.add(new THREE.HemisphereLight(0xdfeaff, 0x806a58, 0.3));

const panelEl = $('panel'), sliderEl = $('slider'), fvEl = $('fv'), btnSq = $('squeeze'), btnReset = $('reset');
const capEl = $('cap'), fingerEl = $('finger'), hintEl = $('hint');

/* ------------------------------------------------------------------ shaders */
const GLSL_COMMON = `
vec3 toLin(vec3 c){ return pow(c, vec3(2.2)); }
vec3 enc(vec3 c){ return pow(clamp(c, 0.0, 1.0), vec3(0.4545)); }
vec2 hash22(vec2 p){
  p = vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)));
  return fract(sin(p) * 43758.5453123);
}
float hash12(vec2 p){ return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
vec3 voro(vec2 p){
  vec2 ip = floor(p);
  vec2 fp = fract(p);
  float d1 = 9.0;
  float d2 = 9.0;
  vec2 cid = vec2(0.0);
  for(int j = -1; j <= 1; j++){
    for(int i = -1; i <= 1; i++){
      vec2 g = vec2(float(i), float(j));
      vec2 o = hash22(ip + g);
      o = 0.5 + 0.38 * sin(6.2831 * o);
      vec2 r = g + o - fp;
      float d = dot(r, r);
      if(d < d1){ d2 = d1; d1 = d; cid = ip + g; }
      else if(d < d2){ d2 = d; }
    }
  }
  return vec3(sqrt(d1), sqrt(d2), hash12(cid));
}
vec3 envFake(vec3 R){
  float up = clamp(R.y * 0.5 + 0.5, 0.0, 1.0);
  vec3 sky = mix(vec3(0.20, 0.22, 0.26), vec3(0.95, 1.0, 1.08), pow(up, 1.5));
  float b1 = smoothstep(0.93, 0.975, dot(R, normalize(vec3(-0.45, 0.85, 0.45))));
  float b2 = smoothstep(0.95, 0.985, dot(R, normalize(vec3(0.85, 0.45, -0.25))));
  float b3 = smoothstep(0.94, 0.98, dot(R, normalize(vec3(0.1, 0.5, 0.9))));
  return sky + vec3(12.0) * b1 + vec3(5.0, 5.2, 6.0) * b2 + vec3(4.0) * b3;
}
vec3 perturb(vec3 N, vec3 pos, float h){
  vec3 sx = dFdx(pos);
  vec3 sy = dFdy(pos);
  float dbx = dFdx(h);
  float dby = dFdy(h);
  vec3 r1 = cross(sy, N);
  vec3 r2 = cross(N, sx);
  float det = dot(sx, r1);
  vec3 grad = sign(det) * (dbx * r1 + dby * r2);
  vec3 res = abs(det) * N - grad;
  return length(res) > 1e-12 ? normalize(res) : N;
}
`;

const VS_JELLY = `
attribute vec3 aRest;
attribute float aThick;
varying vec3 vPos;
varying vec3 vN;
varying vec3 vRest;
varying float vThick;
void main(){
  vPos = position;
  vN = normal;
  vRest = aRest;
  vThick = aThick;
  gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
}
`;

const FS_JELLY = `
uniform float uBack;
varying vec3 vPos;
varying vec3 vN;
varying vec3 vRest;
varying float vThick;
` + GLSL_COMMON + `
vec3 pat(vec2 q, float sc, float off){
  float rr = length(q);
  float ang = atan(q.y, q.x);
  return voro(vec2(ang * 11.0 * sc + off, rr * 7.0 * sc + off * 0.37));
}
void main(){
  vec3 V = normalize(cameraPosition - vPos);
  vec3 N = normalize(vN);
  if(uBack > 0.5) N = -N;
  float thin = 1.0 - smoothstep(0.03, 0.30, vThick);
  float deep = smoothstep(0.10, 0.46, vThick);

  vec2 rp = vRest.xz;
  vec3 c1 = pat(rp, 1.0, 0.0);
  vec2 sh = -V.xz / max(abs(V.y), 0.4) * 0.12;
  vec3 c2 = pat(rp + sh, 0.78, 7.7);
  float bead1 = 1.0 - smoothstep(0.0, 0.62, c1.x);
  float wall1 = 1.0 - smoothstep(0.0, 0.17, c1.y - c1.x);
  float bead2 = 1.0 - smoothstep(0.0, 0.62, c2.x);
  float wall2 = 1.0 - smoothstep(0.0, 0.17, c2.y - c2.x);
  N = perturb(N, vPos, bead1 * 0.0055 - wall1 * 0.0018);

  vec3 cJuice = toLin(vec3(1.0, 0.64, 0.06));
  vec3 cDeep  = toLin(vec3(0.97, 0.36, 0.0));
  vec3 cPale  = toLin(vec3(1.0, 0.85, 0.40));
  vec3 s1 = mix(cDeep, cJuice, 0.35 + 0.65 * bead1) * (0.82 + 0.36 * c1.z);
  s1 = mix(s1, cPale, wall1 * 0.5);
  vec3 s2 = mix(cDeep, cJuice, 0.2 + 0.6 * bead2) * (0.7 + 0.4 * c2.z);
  s2 = mix(s2, cPale * 0.9, wall2 * 0.35);
  vec3 body = mix(s2, s1, 0.55);
  body = mix(body, cDeep * 0.9, deep * 0.25);
  body = mix(body, cPale * 1.2, thin * 0.5);

  vec3 L1 = normalize(vec3(-0.5, 1.0, 0.6));
  vec3 L2 = normalize(vec3(0.7, 0.4, -0.6));
  float ndl = max(dot(N, L1), 0.0);
  float lit = 0.66 + 0.5 * ndl + 0.12 * max(dot(N, L2), 0.0);
  float rim = pow(1.0 - max(dot(N, V), 0.0), 3.0);
  vec3 col = body * lit + cPale * (0.30 * thin + 0.22 * rim);

  vec3 R = reflect(-V, N);
  float F = 0.045 + 0.955 * pow(1.0 - max(dot(N, V), 0.0), 5.0);
  vec3 spec = envFake(R) * F;
  vec3 H1 = normalize(L1 + V);
  vec3 H2 = normalize(L2 + V);
  float sp = pow(max(dot(N, H1), 0.0), 220.0) * 3.0 + pow(max(dot(N, H2), 0.0), 160.0) * 1.0;
  spec += vec3(sp);

  float alpha = mix(0.46, 0.82, deep) + wall1 * 0.10 - thin * 0.08;
  if(uBack > 0.5){ alpha *= 0.65; col *= 0.85; spec *= 0.5; }
  alpha = clamp(alpha, 0.0, 1.0);
  gl_FragColor = vec4(enc(col) * alpha + enc(spec), alpha);
}
`;

const VS_SOLID = `
attribute vec3 aRest;
varying vec3 vPos;
varying vec3 vN;
varying vec3 vRest;
void main(){
  vPos = position;
  vN = normal;
  vRest = aRest;
  gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
}
`;

const FS_SOLID = `
varying vec3 vPos;
varying vec3 vN;
varying vec3 vRest;
` + GLSL_COMMON + `
void main(){
  vec3 V = normalize(cameraPosition - vPos);
  vec3 N = normalize(vN);
  if(!gl_FrontFacing) N = -N;
  float rr = length(vRest.xz);
  float ang = atan(vRest.z, vRest.x);
  float isPeel = smoothstep(0.93, 0.942, rr);
  float topness = smoothstep(0.55, 0.85, abs(N.y));
  float vc = mix(vRest.y * 36.0, rr * 36.0, topness);
  vec3 pv = voro(vec2(ang * 36.0, vc));
  float pore = 1.0 - smoothstep(0.0, 0.3, pv.x);
  vec3 peel = mix(toLin(vec3(1.0, 0.47, 0.0)), toLin(vec3(1.0, 0.66, 0.05)), 0.3 + 0.45 * pv.z);
  peel = mix(peel, toLin(vec3(0.88, 0.30, 0.0)), pore * 0.55);
  vec3 pith = toLin(vec3(1.0, 0.97, 0.90)) * (0.94 + 0.06 * hash12(vec2(floor(ang * 90.0), floor(rr * 50.0))));
  vec3 base = mix(pith, peel, isPeel);
  N = perturb(N, vPos, pore * 0.0035 * isPeel);

  vec3 L1 = normalize(vec3(-0.5, 1.0, 0.6));
  vec3 L2 = normalize(vec3(0.7, 0.4, -0.6));
  float ndl = max(dot(N, L1), 0.0);
  vec3 amb = mix(vec3(0.36, 0.34, 0.33), vec3(0.64, 0.68, 0.76), N.y * 0.5 + 0.5);
  vec3 col = base * (amb + vec3(0.8) * ndl + vec3(0.2) * max(dot(N, L2), 0.0));
  col += pith * (1.0 - isPeel) * 0.10;

  vec3 R = reflect(-V, N);
  float F = 0.05 + 0.95 * pow(1.0 - max(dot(N, V), 0.0), 5.0);
  vec3 spec = envFake(R) * F * (0.25 + 0.75 * isPeel);
  vec3 H1 = normalize(L1 + V);
  spec += vec3(pow(max(dot(N, H1), 0.0), 120.0) * 1.6 * (0.3 + 0.7 * isPeel));
  gl_FragColor = vec4(enc(col + spec), 1.0);
}
`;

const matSolid = new THREE.ShaderMaterial({ vertexShader: VS_SOLID, fragmentShader: FS_SOLID, side: THREE.DoubleSide });
const matJellyBack = new THREE.ShaderMaterial({
  vertexShader: VS_JELLY, fragmentShader: FS_JELLY, uniforms: { uBack: { value: 1 } },
  transparent: true, depthWrite: false, side: THREE.BackSide, premultipliedAlpha: true
});
const matJellyFront = new THREE.ShaderMaterial({
  vertexShader: VS_JELLY, fragmentShader: FS_JELLY, uniforms: { uBack: { value: 0 } },
  transparent: true, depthWrite: false, side: THREE.FrontSide, premultipliedAlpha: true
});

/* ------------------------------------------------------------------ plate, decals */
function radialTex(stops, size) {
  const c = document.createElement('canvas');
  c.width = c.height = size;
  const g = c.getContext('2d');
  const gr = g.createRadialGradient(size / 2, size / 2, 0, size / 2, size / 2, size / 2);
  stops.forEach(s => gr.addColorStop(s[0], s[1]));
  g.fillStyle = gr;
  g.fillRect(0, 0, size, size);
  const t = new THREE.CanvasTexture(c);
  t.colorSpace = THREE.SRGBColorSpace;
  return t;
}

const plateProf = [[0, -0.075], [0.85, -0.075], [0.88, -0.04], [1.15, -0.035], [1.32, -0.03], [1.44, -0.012], [1.54, 0.02], [1.62, 0.062], [1.665, 0.10], [1.70, 0.12], [1.712, 0.14], [1.70, 0.155], [1.675, 0.14], [1.62, 0.10], [1.54, 0.058], [1.44, 0.022], [1.32, 0.004], [1.15, 0.0], [0, 0]].map(p => new THREE.Vector2(p[0], p[1]));
const plate = new THREE.Mesh(
  new THREE.LatheGeometry(plateProf, 96),
  new THREE.MeshPhysicalMaterial({ color: 0xf3f3f1, roughness: 0.2, clearcoat: 0.8, clearcoatRoughness: 0.1, metalness: 0, envMapIntensity: 0.75, side: THREE.DoubleSide })
);
scene.add(plate);

const shadowDecal = new THREE.Mesh(
  new THREE.PlaneGeometry(5.4, 5.4),
  new THREE.MeshBasicMaterial({ map: radialTex([[0, 'rgba(0,0,0,0.6)'], [0.55, 'rgba(0,0,0,0.38)'], [1, 'rgba(0,0,0,0)']], 256), transparent: true, depthWrite: false })
);
shadowDecal.rotation.x = -Math.PI / 2;
shadowDecal.position.y = -0.078;
shadowDecal.renderOrder = -2;
scene.add(shadowDecal);

const causticDecal = new THREE.Mesh(
  new THREE.PlaneGeometry(2.7, 2.7),
  new THREE.MeshBasicMaterial({ map: radialTex([[0, 'rgba(255,140,20,0.62)'], [0.6, 'rgba(255,120,10,0.48)'], [0.84, 'rgba(255,150,40,0.20)'], [1, 'rgba(255,150,40,0)']], 256), transparent: true, depthWrite: false })
);
causticDecal.rotation.x = -Math.PI / 2;
causticDecal.position.y = 0.004;
causticDecal.renderOrder = 0;
scene.add(causticDecal);

function plateTop(x, z) {
  const r = Math.sqrt(x * x + z * z);
  if (r < 1.36) return 0;
  if (r > 1.72) return -0.08;
  const d = (r - 1.36) / 0.34;
  return 0.15 * d * d;
}

/* ------------------------------------------------------------------ soft body lattice */
const HS = 0.16, NH = 8, NXZ = 2 * NH + 1, NYL = 4, YC = 0.222, HL = 0.24, YB = YC - HL;
const RACT = 1.0 + 1.5 * HS;
const idMap = new Int32Array(NXZ * NXZ * NYL).fill(-1);
const nodeFlat = [];
for (let ix = 0; ix < NXZ; ix++) {
  for (let iz = 0; iz < NXZ; iz++) {
    const x = (ix - NH) * HS, z = (iz - NH) * HS;
    if (Math.hypot(x, z) <= RACT) {
      for (let iy = 0; iy < NYL; iy++) {
        idMap[(ix * NXZ + iz) * NYL + iy] = nodeFlat.length / 3;
        nodeFlat.push(x, YB + iy * HS, z);
      }
    }
  }
}
const NN = nodeFlat.length / 3, NN3 = NN * 3;
const REST = Float32Array.from(nodeFlat);
const P = new Float32Array(NN3), Q = new Float32Array(NN3), Vl = new Float32Array(NN3), Gl = new Float32Array(NN3);
P.set(REST); Q.set(REST); Gl.set(REST);
const floorFlag = new Uint8Array(NN);
function nodeId(ix, iz, iy) { return idMap[(ix * NXZ + iz) * NYL + iy]; }

const saTmp = [], sbTmp = [], slTmp = [];
for (let ix = 0; ix < NXZ; ix++) {
  for (let iz = 0; iz < NXZ; iz++) {
    for (let iy = 0; iy < NYL; iy++) {
      const a = nodeId(ix, iz, iy);
      if (a < 0) continue;
      for (let dx = -1; dx <= 1; dx++) {
        for (let dy = -1; dy <= 1; dy++) {
          for (let dz = -1; dz <= 1; dz++) {
            if (!((dx > 0) || (dx === 0 && dy > 0) || (dx === 0 && dy === 0 && dz > 0))) continue;
            const jx = ix + dx, jz = iz + dz, jy = iy + dy;
            if (jx < 0 || jx >= NXZ || jz < 0 || jz >= NXZ || jy < 0 || jy >= NYL) continue;
            const b = nodeId(jx, jz, jy);
            if (b < 0) continue;
            saTmp.push(a * 3); sbTmp.push(b * 3);
            slTmp.push(HS * Math.sqrt(dx * dx + dy * dy + dz * dz));
          }
        }
      }
    }
  }
}
const SA = Int32Array.from(saTmp), SB = Int32Array.from(sbTmp), SL = Float32Array.from(slTmp);
const M = SA.length;

const SUB = 8, GRAV = 12, KGRAB = 0.3;
const par = { kDist: 760, kTeth: 340, damp: 3.1, visc: 0.045, poke: 5.5 };
let pressY = 3, sqS = 0, sq = null, goalS = -1;

function setFirmness(v) {
  const t = clamp(v / 100, 0, 1);
  par.kDist = 220 * Math.pow(12, t);
  par.kTeth = 120 * Math.pow(8, t);
  par.damp = 1.8 + 2.6 * t;
  par.visc = 0.03 + 0.03 * t;
  par.poke = 3.2 * (1 + 1.6 * t);
  fvEl.textContent = (t < 0.34 ? 'Soft' : (t < 0.67 ? 'Medium' : 'Firm')) + ' ' + Math.round(v);
}

function updateGoal(s) {
  if (s === goalS) return;
  goalS = s;
  const sx = 1 + 0.22 * s, sy = 1 - 0.46 * s;
  for (let i = 0; i < NN3; i += 3) {
    Gl[i] = REST[i] * sx;
    Gl[i + 1] = YB + (REST[i + 1] - YB) * sy;
    Gl[i + 2] = REST[i + 2] * sx;
  }
}

const grab = {
  active: false, n: 0, idx: new Int32Array(NN), w: new Float32Array(NN), s: new Float32Array(NN3),
  ox: 0, oy: 0, oz: 0, tgt: new THREE.Vector3(), off: new THREE.Vector3(), base: new THREE.Vector3(),
  normal: new THREE.Vector3(), center: new THREE.Vector3()
};

function simFrame(dt) {
  const h = dt / SUB;
  const at = 1 / (par.kDist * h * h);
  const comp = 1 / (2 + at);
  const kg = Math.min(0.4, par.kTeth * h * h);
  const gdt = GRAV * h;
  const damp = Math.exp(-par.damp * h);
  const fric = Math.exp(-10 * h);
  const vmax = 14, vmax2 = vmax * vmax;
  const pressOn = pressY < 0.5;
  const gOn = grab.active;
  for (let st = 0; st < SUB; st++) {
    for (let i = 0; i < NN3; i += 3) {
      Vl[i + 1] -= gdt;
      Q[i] = P[i]; Q[i + 1] = P[i + 1]; Q[i + 2] = P[i + 2];
      P[i] += Vl[i] * h; P[i + 1] += Vl[i + 1] * h; P[i + 2] += Vl[i + 2] * h;
    }
    for (let j = 0; j < M; j++) {
      const a = SA[j], b = SB[j];
      const dx = P[a] - P[b], dy = P[a + 1] - P[b + 1], dz = P[a + 2] - P[b + 2];
      const len = Math.sqrt(dx * dx + dy * dy + dz * dz);
      if (len < 1e-7) continue;
      const c = (len - SL[j]) * comp / len;
      P[a] -= dx * c; P[a + 1] -= dy * c; P[a + 2] -= dz * c;
      P[b] += dx * c; P[b + 1] += dy * c; P[b + 2] += dz * c;
    }
    for (let i = 0; i < NN3; i++) P[i] += (Gl[i] - P[i]) * kg;
    if (gOn) {
      const ox = grab.ox, oy = grab.oy, oz = grab.oz;
      for (let q = 0; q < grab.n; q++) {
        const i = grab.idx[q], w = grab.w[q] * KGRAB, q3 = q * 3;
        P[i] += (grab.s[q3] + ox - P[i]) * w;
        P[i + 1] += (grab.s[q3 + 1] + oy - P[i + 1]) * w;
        P[i + 2] += (grab.s[q3 + 2] + oz - P[i + 2]) * w;
      }
    }
    for (let i = 0; i < NN3; i += 3) {
      let x = P[i], y = P[i + 1], z = P[i + 2];
      const rr = x * x + z * z;
      if (rr > 2.56) { const f = 1.6 / Math.sqrt(rr); x *= f; z *= f; }
      if (pressOn && y > pressY) y = pressY;
      const fl = plateTop(x, z) - 0.018;
      if (y <= fl + 0.002) { if (y < fl) y = fl; floorFlag[i / 3] = 1; } else floorFlag[i / 3] = 0;
      P[i] = x; P[i + 1] = y; P[i + 2] = z;
    }
    for (let i = 0; i < NN3; i += 3) {
      let vx = (P[i] - Q[i]) / h, vy = (P[i + 1] - Q[i + 1]) / h, vz = (P[i + 2] - Q[i + 2]) / h;
      const sp = vx * vx + vy * vy + vz * vz;
      if (sp > vmax2) { const f = vmax / Math.sqrt(sp); vx *= f; vy *= f; vz *= f; }
      vx *= damp; vy *= damp; vz *= damp;
      if (floorFlag[i / 3]) { vx *= fric; vz *= fric; }
      Vl[i] = vx; Vl[i + 1] = vy; Vl[i + 2] = vz;
    }
  }
  const kv = par.visc;
  for (let j = 0; j < M; j++) {
    const a = SA[j], b = SB[j];
    const dvx = (Vl[b] - Vl[a]) * kv, dvy = (Vl[b + 1] - Vl[a + 1]) * kv, dvz = (Vl[b + 2] - Vl[a + 2]) * kv;
    Vl[a] += dvx; Vl[a + 1] += dvy; Vl[a + 2] += dvz;
    Vl[b] -= dvx; Vl[b + 1] -= dvy; Vl[b + 2] -= dvz;
  }
}

/* ------------------------------------------------------------------ render geometry bound to the lattice */
const skins = [];
const group = new THREE.Group();
scene.add(group);

function bindVerts(rest) {
  const V = rest.length / 3, idx = new Int32Array(V * 8), wt = new Float32Array(V * 8);
  for (let v = 0; v < V; v++) {
    const fx = rest[3 * v] / HS + NH, fz = rest[3 * v + 2] / HS + NH, fy = (rest[3 * v + 1] - YB) / HS;
    const ix = Math.min(Math.max(Math.floor(fx), 0), NXZ - 2);
    const iz = Math.min(Math.max(Math.floor(fz), 0), NXZ - 2);
    const iy = Math.min(Math.max(Math.floor(fy), 0), NYL - 2);
    const tx = clamp(fx - ix, 0, 1), tz = clamp(fz - iz, 0, 1), ty = clamp(fy - iy, 0, 1);
    let sum = 0;
    for (let c = 0; c < 8; c++) {
      const dx = c & 1, dy = (c >> 1) & 1, dz = (c >> 2) & 1;
      const id = nodeId(ix + dx, iz + dz, iy + dy);
      const w = (dx ? tx : 1 - tx) * (dy ? ty : 1 - ty) * (dz ? tz : 1 - tz);
      if (id >= 0 && w > 0) { idx[v * 8 + c] = id; wt[v * 8 + c] = w; sum += w; }
    }
    if (sum < 1e-6) {
      let best = 0, bd = 1e9;
      for (let k = 0; k < NN; k++) {
        const ddx = REST[3 * k] - rest[3 * v], ddy = REST[3 * k + 1] - rest[3 * v + 1], ddz = REST[3 * k + 2] - rest[3 * v + 2];
        const d = ddx * ddx + ddy * ddy + ddz * ddz;
        if (d < bd) { bd = d; best = k; }
      }
      idx[v * 8] = best; wt[v * 8] = 1;
    } else if (sum < 0.9999) {
      for (let c = 0; c < 8; c++) wt[v * 8 + c] /= sum;
    }
  }
  return { idx, wt };
}

function orient(pos, idx, ctrFn) {
  for (let t = 0; t < idx.length; t += 3) {
    const a = idx[t] * 3, b = idx[t + 1] * 3, c = idx[t + 2] * 3;
    const ux = pos[b] - pos[a], uy = pos[b + 1] - pos[a + 1], uz = pos[b + 2] - pos[a + 2];
    const vx = pos[c] - pos[a], vy = pos[c + 1] - pos[a + 1], vz = pos[c + 2] - pos[a + 2];
    const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
    const cx = (pos[a] + pos[b] + pos[c]) / 3, cy = (pos[a + 1] + pos[b + 1] + pos[c + 1]) / 3, cz = (pos[a + 2] + pos[b + 2] + pos[c + 2]) / 3;
    const o = ctrFn(cx, cy, cz);
    if (nx * (cx - o[0]) + ny * (cy - o[1]) + nz * (cz - o[2]) < 0) {
      const tmp = idx[t + 1]; idx[t + 1] = idx[t + 2]; idx[t + 2] = tmp;
    }
  }
}

function addSkinned(rest, indices, mats, orders, thickCount) {
  const geo = new THREE.BufferGeometry();
  const posA = new THREE.BufferAttribute(Float32Array.from(rest), 3);
  posA.setUsage(THREE.DynamicDrawUsage);
  geo.setAttribute('position', posA);
  geo.setAttribute('aRest', new THREE.BufferAttribute(Float32Array.from(rest), 3));
  geo.setIndex(new THREE.BufferAttribute(Uint32Array.from(indices), 1));
  let thick = null;
  if (thickCount) {
    const ta = new THREE.BufferAttribute(new Float32Array(rest.length / 3), 1);
    ta.setUsage(THREE.DynamicDrawUsage);
    geo.setAttribute('aThick', ta);
    thick = { attr: ta, count: thickCount };
  }
  geo.computeVertexNormals();
  const b = bindVerts(rest);
  const skin = { geo, idx: b.idx, wt: b.wt, thick };
  skins.push(skin);
  mats.forEach((m, i) => {
    const mesh = new THREE.Mesh(geo, m);
    mesh.frustumCulled = false;
    mesh.renderOrder = orders[i];
    group.add(mesh);
  });
  return skin;
}

function skinAll() {
  for (let s = 0; s < skins.length; s++) {
    const sk = skins[s];
    const pa = sk.geo.attributes.position.array, idx = sk.idx, wt = sk.wt;
    const V = pa.length / 3;
    for (let v = 0, o = 0; v < V; v++, o += 8) {
      let x = 0, y = 0, z = 0;
      for (let k = 0; k < 8; k++) {
        const w = wt[o + k];
        if (w === 0) continue;
        const n = idx[o + k] * 3;
        x += P[n] * w; y += P[n + 1] * w; z += P[n + 2] * w;
      }
      pa[3 * v] = x; pa[3 * v + 1] = y; pa[3 * v + 2] = z;
    }
    sk.geo.attributes.position.needsUpdate = true;
    if (sk.thick) {
      const ta = sk.thick.attr.array, cnt = sk.thick.count;
      for (let i = 0; i < cnt; i++) {
        const a = 3 * i, b = 3 * (i + cnt);
        const dx = pa[a] - pa[b], dy = pa[a + 1] - pa[b + 1], dz = pa[a + 2] - pa[b + 2];
        const t = Math.sqrt(dx * dx + dy * dy + dz * dz);
        ta[i] = t; ta[i + cnt] = t;
      }
      sk.thick.attr.needsUpdate = true;
    }
    sk.geo.computeVertexNormals();
  }
}

/* segments (juicy translucent wedges) */
const NSEG = 10, R0 = 0.18, R1 = 0.835, WG = 0.026, TH = 0.22, BEV = 0.1, SNU = 12, SNV = 18;
function buildSegment(k) {
  const ac = Math.PI + (k + 0.5) * 2 * Math.PI / NSEG;
  const pos = [], idx = [];
  for (let side = 0; side < 2; side++) {
    const sg = side === 0 ? 1 : -1;
    for (let iv = 0; iv < SNV; iv++) {
      const vc = 0.5 - 0.5 * Math.cos(Math.PI * iv / (SNV - 1));
      const r = R0 + (R1 - R0) * vc;
      const halfA = Math.PI / NSEG - Math.asin(Math.min(0.9, WG / r));
      for (let iu = 0; iu < SNU; iu++) {
        const uc = 0.5 - 0.5 * Math.cos(Math.PI * iu / (SNU - 1));
        const phi = ac + (2 * uc - 1) * halfA;
        const dAng = Math.min(uc, 1 - uc) * 2 * halfA * r;
        const dRad = Math.min(vc, 1 - vc) * (R1 - R0);
        const m = Math.min(1, Math.min(dAng, dRad) / BEV);
        const pill = Math.sqrt(Math.max(0, 1 - (1 - m) * (1 - m)));
        const dome = 1 + 0.06 * (4 * uc * (1 - uc)) * (4 * vc * (1 - vc));
        pos.push(r * Math.cos(phi), YC + sg * TH * pill * dome, r * Math.sin(phi));
      }
    }
  }
  for (let side = 0; side < 2; side++) {
    const base = side * SNU * SNV;
    for (let iv = 0; iv < SNV - 1; iv++) {
      for (let iu = 0; iu < SNU - 1; iu++) {
        const a = base + iv * SNU + iu, b = a + 1, c = a + SNU, d = c + 1;
        idx.push(a, b, c, b, d, c);
      }
    }
  }
  const cx = 0.5 * Math.cos(ac), cz = 0.5 * Math.sin(ac);
  orient(pos, idx, () => [cx, YC, cz]);
  addSkinned(pos, idx, [matJellyBack, matJellyFront], [1, 2], SNU * SNV);
}

/* membranes (white pith walls between segments) */
function buildMembrane(k) {
  const th = Math.PI + k * 2 * Math.PI / NSEG;
  const cs = Math.cos(th), sn = Math.sin(th);
  const NR = 14, W = 0.02, HM = 0.19, RE = 0.86;
  const corners = [[-W, -HM], [W, -HM], [W, HM], [-W, HM]];
  const pos = [], idx = [];
  for (let ir = 0; ir <= NR; ir++) {
    const r = RE * ir / NR;
    for (let c = 0; c < 4; c++) {
      const l = corners[c][0], yy = corners[c][1];
      pos.push(r * cs - l * sn, YC + yy, r * sn + l * cs);
    }
  }
  for (let ir = 0; ir < NR; ir++) {
    for (let c = 0; c < 4; c++) {
      const c2 = (c + 1) % 4;
      const a = ir * 4 + c, b = ir * 4 + c2, a2 = (ir + 1) * 4 + c, b2 = (ir + 1) * 4 + c2;
      idx.push(a, b, a2, b, b2, a2);
    }
  }
  idx.push(0, 1, 2, 0, 2, 3);
  const e = NR * 4;
  idx.push(e, e + 1, e + 2, e, e + 2, e + 3);
  orient(pos, idx, (x, y, z) => {
    const along = clamp(x * cs + z * sn, 0.08, 0.78);
    return [along * cs, YC, along * sn];
  });
  addSkinned(pos, idx, [matSolid], [0], 0);
}

function revolve(prof, NT) {
  const pos = [], idx = [], PL = prof.length;
  for (let it = 0; it < NT; it++) {
    const th = 2 * Math.PI * it / NT, c = Math.cos(th), s = Math.sin(th);
    for (let p = 0; p < PL; p++) pos.push(prof[p][0] * c, YC + prof[p][1], prof[p][0] * s);
  }
  for (let it = 0; it < NT; it++) {
    const it2 = (it + 1) % NT;
    for (let p = 0; p < PL; p++) {
      const p2 = (p + 1) % PL;
      const a = it * PL + p, b = it2 * PL + p, c = it * PL + p2, d = it2 * PL + p2;
      idx.push(a, b, c, b, d, c);
    }
  }
  return { pos, idx };
}

for (let k = 0; k < NSEG; k++) { buildSegment(k); buildMembrane(k); }

{
  const hub = revolve([[0, 0.205], [0.12, 0.205], [0.17, 0.19], [0.17, -0.19], [0.12, -0.205], [0, -0.205]], 32);
  orient(hub.pos, hub.idx, () => [0, YC, 0]);
  addSkinned(hub.pos, hub.idx, [matSolid], [0], 0);
}

const RIND_NT = 96;
const rindProf = [[0.84, 0.22], [0.89, 0.22], [0.936, 0.22], [0.97, 0.22], [0.993, 0.21], [1.0, 0.19], [1.0, 0.0], [1.0, -0.19], [0.993, -0.21], [0.97, -0.22], [0.936, -0.22], [0.89, -0.22], [0.84, -0.22], [0.84, 0.0]];
const RIND_PR = rindProf.length, RIND_WALL = 6;
let rindSkin;
{
  const rd = revolve(rindProf, RIND_NT);
  orient(rd.pos, rd.idx, (x, y, z) => {
    const th = Math.atan2(z, x);
    return [0.92 * Math.cos(th), YC, 0.92 * Math.sin(th)];
  });
  rindSkin = addSkinned(rd.pos, rd.idx, [matSolid], [0], 0);
}
const _rp = new THREE.Vector3();
function rimPoint(it, out) {
  const pa = rindSkin.geo.attributes.position.array;
  const o = 3 * (((it % RIND_NT) + RIND_NT) % RIND_NT * RIND_PR + RIND_WALL);
  out.set(pa[o], pa[o + 1], pa[o + 2]);
  return out;
}

/* ------------------------------------------------------------------ squeeze press */
const press = new THREE.Group();
{
  const glass = new THREE.MeshPhysicalMaterial({ color: 0xbfe4ff, transparent: true, opacity: 0.32, roughness: 0.05, metalness: 0, clearcoat: 1, envMapIntensity: 1.3, depthWrite: false });
  const disc = new THREE.Mesh(new THREE.CylinderGeometry(1.5, 1.5, 0.06, 64), glass);
  const metal = new THREE.MeshStandardMaterial({ color: 0xdddddd, metalness: 0.9, roughness: 0.25, envMapIntensity: 1 });
  const ring = new THREE.Mesh(new THREE.TorusGeometry(1.5, 0.03, 10, 64), metal);
  ring.rotation.x = Math.PI / 2;
  const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.09, 1.2, 20), metal);
  stem.position.y = 0.65;
  const knob = new THREE.Mesh(new THREE.SphereGeometry(0.19, 24, 16), metal);
  knob.position.y = 1.3;
  press.add(disc, ring, stem, knob);
  press.children.forEach(c => { c.renderOrder = 6; });
  press.visible = false;
  scene.add(press);
}

/* ------------------------------------------------------------------ juice drops */
const drops = [];
const dropGeo = new THREE.SphereGeometry(1, 16, 12);
const dropMat = new THREE.MeshPhysicalMaterial({ color: 0xff9a12, roughness: 0.04, metalness: 0, transparent: true, opacity: 0.86, clearcoat: 1, clearcoatRoughness: 0.03, emissive: 0xff5a00, emissiveIntensity: 0.22, envMapIntensity: 1.5 });
const DROP_TIMES = [1.2, 1.45, 1.75, 2.05, 2.35, 2.65];

function removeDrop(i) {
  scene.remove(drops[i].mesh);
  drops.splice(i, 1);
}
function spawnDrop() {
  const k = Math.floor(Math.random() * NSEG);
  const ang = Math.PI + (k + 0.5 + (Math.random() - 0.5) * 0.6) * 2 * Math.PI / NSEG;
  const it = (((Math.round(ang / (2 * Math.PI) * RIND_NT)) % RIND_NT) + RIND_NT) % RIND_NT;
  rimPoint(it, _rp);
  const rd = 0.04 + Math.random() * 0.035;
  const mesh = new THREE.Mesh(dropGeo, dropMat);
  mesh.renderOrder = 3;
  mesh.scale.set(rd, rd, rd);
  const y0 = _rp.y + 0.04 + Math.random() * 0.06;
  mesh.position.set(_rp.x, y0, _rp.z);
  scene.add(mesh);
  drops.push({ mesh, it, rd, y: y0, vy: -0.1, state: 0, age: 0, t: 0, px: 0, pz: 0 });
  if (drops.length > 26) removeDrop(0);
}
function updateDrops(dt) {
  for (let i = drops.length - 1; i >= 0; i--) {
    const d = drops[i];
    d.age += dt;
    if (d.state === 0) {
      d.vy -= GRAV * 0.35 * dt;
      d.y += d.vy * dt;
      rimPoint(d.it, _rp);
      const rr = Math.hypot(_rp.x, _rp.z) || 1;
      const ox = _rp.x / rr, oz = _rp.z / rr;
      const px = _rp.x + ox * d.rd * 0.7, pz = _rp.z + oz * d.rd * 0.7;
      d.mesh.position.set(px, d.y, pz);
      const stretch = 1 + Math.min(1.2, -d.vy * 0.9);
      d.mesh.scale.set(d.rd, d.rd * stretch, d.rd);
      if (d.y <= plateTop(px, pz) + d.rd * 0.4) {
        d.state = 1; d.t = 0;
        d.px = _rp.x + ox * d.rd * 1.8; d.pz = _rp.z + oz * d.rd * 1.8;
      }
    } else {
      d.t += dt;
      const g = smooth(clamp(d.t / 0.5, 0, 1));
      let fade = 1;
      if (d.age > 14) fade = clamp(1 - (d.age - 14) / 3, 0, 1);
      const sx = lerp(d.rd, d.rd * 2.7, g) * fade, sy = lerp(d.rd, d.rd * 0.28, g) * fade;
      d.mesh.scale.set(sx, Math.max(sy, 0.0001), sx);
      d.mesh.position.set(d.px, plateTop(d.px, d.pz) + sy * 0.45, d.pz);
      if (fade <= 0) removeDrop(i);
    }
  }
}

/* ------------------------------------------------------------------ squeeze logic */
function pressYAt(t) {
  if (t < 0.5) { return lerp(2.4, 0.52, smooth(t / 0.5)); }
  if (t < 1.25) { return lerp(0.52, 0.24, smooth((t - 0.5) / 0.75)); }
  if (t < 2.85) { return 0.24; }
  if (t < 3.35) { return lerp(0.24, 0.52, smooth((t - 2.85) / 0.5)); }
  return lerp(0.52, 2.4, smooth(clamp((t - 3.35) / 0.45, 0, 1)));
}
function startSqueeze() {
  if (sq) return;
  endGrab();
  sq = { t: 0, next: 0 };
  btnSq.classList.add('busy');
}
function updateSqueeze(dt) {
  if (!sq) {
    pressY = 3; sqS = 0; press.visible = false;
    return;
  }
  sq.t += dt;
  const t = sq.t;
  if (t >= 3.8) {
    sq = null; pressY = 3; sqS = 0; press.visible = false;
    btnSq.classList.remove('busy');
    return;
  }
  pressY = pressYAt(t);
  sqS = clamp((0.462 - pressY) / 0.222, 0, 1);
  while (sq.next < DROP_TIMES.length && t >= DROP_TIMES[sq.next]) { spawnDrop(); sq.next++; }
  press.visible = pressY < 2.8;
  press.position.y = pressY + 0.03;
}

/* ------------------------------------------------------------------ interaction */
const raycaster = new THREE.Raycaster();
const ndc = new THREE.Vector2();
const UP = new THREE.Vector3(0, 1, 0);
const _f = new THREE.Vector3(), _r = new THREE.Vector3(), _u = new THREE.Vector3(), _t = new THREE.Vector3();

function rayFromXY(cx, cy) {
  const rect = canvas.getBoundingClientRect();
  ndc.set(((cx - rect.left) / rect.width) * 2 - 1, -((cy - rect.top) / rect.height) * 2 + 1);
  raycaster.setFromCamera(ndc, camera);
  return raycaster.ray;
}
function pickNode(ray) {
  const o = ray.origin, d = ray.direction;
  let best = -1, bt = 1e9;
  for (let k = 0; k < NN; k++) {
    const wx = P[3 * k] - o.x, wy = P[3 * k + 1] - o.y, wz = P[3 * k + 2] - o.z;
    const t = wx * d.x + wy * d.y + wz * d.z;
    if (t <= 0 || t >= bt) continue;
    const d2 = wx * wx + wy * wy + wz * wz - t * t;
    if (d2 < 0.05) { bt = t; best = k; }
  }
  return best;
}
function nearestNode(x, y, z) {
  let best = 0, bd = 1e9;
  for (let k = 0; k < NN; k++) {
    const dx = P[3 * k] - x, dy = P[3 * k + 1] - y, dz = P[3 * k + 2] - z;
    const d = dx * dx + dy * dy + dz * dz;
    if (d < bd) { bd = d; best = k; }
  }
  return best;
}
function pokeNode(i, dx, dy, dz) {
  const len = Math.hypot(dx, dy, dz) || 1;
  dx /= len; dy /= len; dz /= len;
  const cx = P[3 * i], cy = P[3 * i + 1], cz = P[3 * i + 2];
  for (let k = 0; k < NN; k++) {
    const ex = P[3 * k] - cx, ey = P[3 * k + 1] - cy, ez = P[3 * k + 2] - cz;
    const d2 = ex * ex + ey * ey + ez * ez;
    if (d2 > 0.3) continue;
    const w = Math.exp(-d2 / 0.1) * par.poke;
    Vl[3 * k] += dx * w; Vl[3 * k + 1] += dy * w; Vl[3 * k + 2] += dz * w;
  }
}
function beginGrab(i) {
  const cx = P[3 * i], cy = P[3 * i + 1], cz = P[3 * i + 2];
  let n = 0;
  for (let k = 0; k < NN; k++) {
    const dx = P[3 * k] - cx, dy = P[3 * k + 1] - cy, dz = P[3 * k + 2] - cz;
    const d2 = dx * dx + dy * dy + dz * dz;
    if (d2 < 0.2) {
      const w = Math.exp(-d2 / 0.11);
      if (w > 0.04) {
        grab.idx[n] = 3 * k; grab.w[n] = w;
        grab.s[3 * n] = P[3 * k]; grab.s[3 * n + 1] = P[3 * k + 1]; grab.s[3 * n + 2] = P[3 * k + 2];
        n++;
      }
    }
  }
  grab.n = n;
  grab.center.set(cx, cy, cz);
  grab.tgt.set(0, 0, 0); grab.off.set(0, 0, 0);
  grab.ox = grab.oy = grab.oz = 0;
  camera.getWorldDirection(grab.normal);
  grab.active = true;
}
function endGrab() { grab.active = false; }
function planePoint(ray, out) {
  const den = ray.direction.dot(grab.normal);
  if (Math.abs(den) < 1e-5) return false;
  const t = _t.copy(grab.center).sub(ray.origin).dot(grab.normal) / den;
  out.copy(ray.origin).addScaledVector(ray.direction, t);
  return true;
}
const _pp = new THREE.Vector3();
function updateGrab(dt) {
  if (!grab.active) return;
  grab.off.lerp(grab.tgt, 1 - Math.exp(-16 * dt));
  if (grab.off.length() > 1.15) grab.off.setLength(1.15);
  grab.ox = grab.off.x; grab.oy = grab.off.y; grab.oz = grab.off.z;
}

let az = 0.28, el = 0.82, camDistBase = 5.5;
let ptr = null;

function hideHint() { hintEl.style.opacity = 0; }

window.addEventListener('pointerdown', e => { if (e.isTrusted && demo.on) endDemo(); }, true);

canvas.addEventListener('pointerdown', e => {
  if (!e.isPrimary || ptr) return;
  try { canvas.setPointerCapture(e.pointerId); } catch (err) {}
  const ray = rayFromXY(e.clientX, e.clientY);
  const hit = sq ? -1 : pickNode(ray);
  ptr = { id: e.pointerId, x0: e.clientX, y0: e.clientY, x: e.clientX, y: e.clientY, hit, mode: hit >= 0 ? 'poke' : 'orbit' };
  if (hit >= 0) pokeNode(hit, ray.direction.x, ray.direction.y, ray.direction.z);
  hideHint();
});
canvas.addEventListener('pointermove', e => {
  if (!ptr || e.pointerId !== ptr.id) return;
  const dx = e.clientX - ptr.x, dy = e.clientY - ptr.y;
  ptr.x = e.clientX; ptr.y = e.clientY;
  if (ptr.mode === 'poke') {
    if (Math.hypot(e.clientX - ptr.x0, e.clientY - ptr.y0) > 12) {
      const ray = rayFromXY(e.clientX, e.clientY);
      beginGrab(ptr.hit);
      grab.base.copy(grab.center);
      if (planePoint(ray, _pp)) grab.base.copy(_pp);
      ptr.mode = 'grab';
    }
  } else if (ptr.mode === 'grab') {
    const ray = rayFromXY(e.clientX, e.clientY);
    if (grab.active && planePoint(ray, _pp)) grab.tgt.copy(_pp).sub(grab.base);
  } else {
    az -= dx * 0.008;
    el = clamp(el + dy * 0.006, 0.3, 1.38);
  }
});
function pointerEnd(e) {
  if (!ptr || e.pointerId !== ptr.id) return;
  if (ptr.mode === 'grab') endGrab();
  ptr = null;
}
canvas.addEventListener('pointerup', pointerEnd);
canvas.addEventListener('pointercancel', pointerEnd);

/* ------------------------------------------------------------------ UI */
sliderEl.addEventListener('input', () => { setFirmness(+sliderEl.value); });
btnSq.addEventListener('click', () => { startSqueeze(); hideHint(); });
btnReset.addEventListener('click', () => { resetAll(true); });

function resetAll(full) {
  endGrab();
  sq = null; pressY = 3; sqS = 0;
  press.visible = false;
  btnSq.classList.remove('busy');
  goalS = -1; updateGoal(0);
  P.set(REST); Q.set(REST); Vl.fill(0);
  for (let i = drops.length - 1; i >= 0; i--) removeDrop(i);
  if (full) {
    sliderEl.value = 50; setFirmness(50);
    az = 0.28; el = 0.82;
  }
}

function resize() {
  const w = window.innerWidth, h = window.innerHeight;
  renderer.setSize(w, h, false);
  camera.aspect = w / h;
  const ph = panelEl.getBoundingClientRect().height + 20;
  const tv = Math.tan(camera.fov * Math.PI / 360);
  const availH = Math.max(160, h - ph);
  camDistBase = Math.max(2.9 * h / (2 * tv * availH), 3.7 / (2 * tv * camera.aspect));
  camera.setViewOffset(w, h, 0, Math.round(ph * 0.42), w, h);
  camera.updateProjectionMatrix();
}
window.addEventListener('resize', resize);
window.addEventListener('orientationchange', () => setTimeout(resize, 150));

function updateCamera() {
  const a = az + (demo.on ? 0.55 * Math.sin(demo.t * 0.35) : 0);
  const d = camDistBase;
  camera.position.set(Math.sin(a) * Math.cos(el) * d, 0.15 + Math.sin(el) * d, Math.cos(a) * Math.cos(el) * d);
  camera.lookAt(0, 0.15, 0);
  camera.updateMatrixWorld();
}
function camAxes() {
  camera.getWorldDirection(_f);
  _r.crossVectors(_f, UP).normalize();
  _u.crossVectors(_r, _f).normalize();
}

/* ------------------------------------------------------------------ hands-free demo (#demo) */
const demo = { on: false, t: 0, i: 0, ev: [], drag: null, sl: null, fp: new THREE.Vector3(), fT: 0, restart: false };
function cap(text) {
  capEl.textContent = text;
  capEl.classList.toggle('on', !!text);
}
function showFinger(v) {
  _t.copy(v).project(camera);
  const x = (_t.x * 0.5 + 0.5) * window.innerWidth, y = (-_t.y * 0.5 + 0.5) * window.innerHeight;
  fingerEl.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%)';
  fingerEl.style.opacity = 1;
}
function dPoke(x, z) {
  const i = nearestNode(x, 0.46, z);
  pokeNode(i, 0, -1, 0.1);
  demo.fp.set(P[3 * i], P[3 * i + 1], P[3 * i + 2]);
  demo.fT = demo.t + 0.55;
}
function dGrab(x, z, sx, sy) {
  const i = nearestNode(x, 0.46, z);
  beginGrab(i);
  demo.drag = { from: demo.t, dur: 1.4, sx, sy };
}
function dGrabEnd() { endGrab(); demo.drag = null; }
function dSlider(v) { demo.sl = { from: demo.t, dur: 0.8, a: +sliderEl.value, b: v }; }

(function buildDemo() {
  const at = (t, f) => demo.ev.push({ t, f });
  at(0.0, () => cap('Real soft-body jelly. Hands-free demo'));
  at(1.0, () => { cap('Poke it'); dPoke(0.15, 0.1); });
  at(2.5, () => dPoke(-0.45, -0.3));
  at(3.8, () => { cap('Drag to stretch...'); dGrab(0.7, 0.15, 1.0, 0.35); });
  at(5.6, () => { cap('...let go: it jiggles, then settles'); dGrabEnd(); });
  at(8.0, () => { cap('Softer jelly wobbles more'); dSlider(10); });
  at(9.0, () => dPoke(0.2, 0.2));
  at(10.4, () => { cap('Stretch it upward'); dGrab(-0.5, -0.2, -0.3, 0.9); });
  at(12.0, () => dGrabEnd());
  at(13.0, () => { cap('Firmer jelly: stiff and quick'); dSlider(92); });
  at(13.9, () => dPoke(0.1, 0.0));
  at(15.0, () => { cap('Squeeze: a few drops of juice run out'); startSqueeze(); });
  at(20.2, () => { demo.restart = true; });
})();

function startDemo() {
  demo.on = true; demo.t = 0; demo.i = 0; demo.drag = null; demo.sl = null; demo.restart = false;
  resetAll(true);
  hideHint();
}
function endDemo() {
  if (!demo.on) return;
  demo.on = false; demo.drag = null; demo.sl = null;
  endGrab();
  fingerEl.style.opacity = 0;
  cap('');
}
function updateDemo(dt) {
  if (!demo.on) return;
  demo.t += dt;
  while (demo.i < demo.ev.length && demo.ev[demo.i].t <= demo.t && !demo.restart) {
    demo.ev[demo.i].f();
    demo.i++;
  }
  if (demo.restart) {
    demo.restart = false; demo.t = 0; demo.i = 0; demo.drag = null; demo.sl = null;
    resetAll(true);
    return;
  }
  if (demo.drag && grab.active) {
    const u = clamp((demo.t - demo.drag.from) / demo.drag.dur, 0, 1), e = smooth(u);
    camAxes();
    grab.tgt.set(0, 0, 0).addScaledVector(_r, demo.drag.sx * e).addScaledVector(_u, demo.drag.sy * e);
  }
  if (demo.sl) {
    const u = clamp((demo.t - demo.sl.from) / demo.sl.dur, 0, 1);
    const v = lerp(demo.sl.a, demo.sl.b, smooth(u));
    sliderEl.value = Math.round(v);
    setFirmness(v);
    if (u >= 1) demo.sl = null;
  }
  if (grab.active) {
    _pp.copy(grab.center).add(grab.off);
    showFinger(_pp);
  } else if (demo.t < demo.fT) {
    showFinger(demo.fp);
  } else {
    fingerEl.style.opacity = 0;
  }
}
function checkDemo() {
  if (location.hash.toLowerCase() === '#demo') { if (!demo.on) startDemo(); }
  else if (demo.on) endDemo();
}
window.addEventListener('hashchange', checkDemo);

/* ------------------------------------------------------------------ main loop */
setFirmness(50);
resize();
updateGoal(0);
updateCamera();
skinAll();
window.__ready = true;
checkDemo();

let last = performance.now(), acc = 0;
function frame(now) {
  requestAnimationFrame(frame);
  let dt = (now - last) / 1000;
  last = now;
  if (!(dt > 0)) dt = 1 / 60;
  dt = Math.min(dt, 0.05);

  updateDemo(dt);
  updateSqueeze(dt);
  updateGoal(Math.round(sqS * 1000) / 1000);
  updateGrab(dt);

  acc += dt;
  let n = 0;
  while (acc >= 1 / 60 && n < 3) {
    simFrame(1 / 60);
    acc -= 1 / 60;
    n++;
  }
  if (acc > 1 / 60) acc = 0;

  skinAll();
  updateDrops(dt);
  causticDecal.scale.setScalar(1 + 0.2 * sqS);
  updateCamera();
  renderer.render(scene, camera);
}
requestAnimationFrame(frame);
</script>
</body>
</html>