Back to the app
The code
Jelly Orange Slice by Claude Haiku 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.)<!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">
<meta name="color-scheme" content="light dark">
<title>Orange Jelly Slice</title>
<meta name="description" content="A soft-body jelly orange slice on a white plate. Poke it, stretch it, squeeze out the juice and tune its firmness.">
<style>
:root{--bg:#f3efe6;--ink:#2b1a0a;--panel:rgba(255,255,255,.88);--btn:#b83c00;--btnink:#ffffff;--line:#b83c00}
@media (prefers-color-scheme: dark){
:root:not([data-theme="light"]){--bg:#1d1812;--ink:#f7eee2;--panel:rgba(44,33,24,.9);--btn:#e0681f;--btnink:#1d1208;--line:#e0681f}
}
:root[data-theme="dark"]{--bg:#1d1812;--ink:#f7eee2;--panel:rgba(44,33,24,.9);--btn:#e0681f;--btnink:#1d1208;--line:#e0681f}
html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);font-family:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;overflow:hidden;touch-action:none;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}
#scene{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none}
#top{position:fixed;top:0;left:0;right:0;padding:14px 16px;text-align:center;font-size:16px;line-height:1.4;pointer-events:none}
#ui{position:fixed;left:0;right:0;bottom:0;padding:12px 16px calc(14px + env(safe-area-inset-bottom,0px));display:flex;flex-direction:column;align-items:center;gap:12px;background:var(--panel);border-radius:22px 22px 0 0}
.row{display:flex;gap:12px;flex-wrap:wrap;justify-content:center;width:100%}
.btn{min-height:56px;min-width:150px;padding:0 24px;border:0;border-radius:16px;background:var(--btn);color:var(--btnink);font:700 18px/1 system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;cursor:pointer}
.btn.ghost{background:transparent;color:var(--ink);box-shadow:inset 0 0 0 2px var(--line)}
.btn:disabled{opacity:.45;cursor:default}
label.fw{display:flex;flex-direction:column;align-items:center;gap:6px;width:min(420px,92vw);font-size:16px}
input[type=range]{width:100%;height:44px;margin:0;accent-color:var(--line)}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="top"><span id="hint"></span></div>
<div id="ui">
<label class="fw">Firmness <b id="fv">50</b>
<input id="firm" type="range" min="0" max="100" step="1" value="50" aria-label="Firmness">
</label>
<div class="row">
<button id="squeeze" class="btn" type="button">Squeeze</button>
<button id="reset" class="btn ghost" type="button">Reset</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script>
(function () {
'use strict';
const T = window.THREE;
const cv = document.getElementById('scene');
const hintEl = document.getElementById('hint');
const firmEl = document.getElementById('firm');
const fvEl = document.getElementById('fv');
const squeezeBtn = document.getElementById('squeeze');
const resetBtn = document.getElementById('reset');
const setHint = function (t) { hintEl.textContent = t; };
if (!T) { setHint('The 3D library did not load. Check the connection and reload.'); return; }
let renderer = null;
try { renderer = new T.WebGLRenderer({ canvas: cv, antialias: true }); }
catch (err) { setHint('This view needs WebGL, which is not available here.'); return; }
renderer.outputEncoding = T.sRGBEncoding;
// ---------- soft body: a polar lattice of particles ----------
const NA = 40, NJ = 10, NK = 3; // 40 columns (10 wedges x 4), 10 rings, 3 layers
const RR = [0, 0.14, 0.28, 0.42, 0.56, 0.70, 0.82, 0.90, 0.96, 1.0];
const THICK = 0.36, YBASE = THICK / 2 + 0.02;
const P = 3 + NK * 9 * NA; // centre particles + rings 1..9
const RVN = P + NK * NJ; // extra render-only copies at the texture seam
const MASS = 0.02, INV_M = 1 / MASS, G = 9.8, DAMP = 1.4;
const H_FIX = 1 / 240, MAX_STEPS = 6, ITER = 8, WALL = 1.7, SQ_K = 300;
const ID = function (i, j, k) {
if (j === 0) return k;
const ii = ((i % NA) + NA) % NA;
return 3 + ((k * 9 + (j - 1)) * NA + ii);
};
const RV = function (i, j, k) {
if (i < NA) return ID(i, j, k);
return j === 0 ? k : P + k * NJ + j;
};
const edgeScale = function (j) {
const r = RR[j];
if (r <= 0.84) return 1;
const t = (r - 0.84) / 0.16;
return Math.max(0.3, Math.sqrt(Math.max(0, 1 - t * t)));
};
const REST = new Float64Array(P * 3);
for (let k = 0; k < NK; k++) for (let j = 0; j < NJ; j++) for (let i = 0; i < NA; i++) {
if (j === 0 && i > 0) continue;
const p = ID(i, j, k), th = i / NA * Math.PI * 2, r = RR[j];
REST[p * 3] = Math.cos(th) * r;
REST[p * 3 + 1] = YBASE + (k - 1) * THICK / 2 * edgeScale(j);
REST[p * 3 + 2] = Math.sin(th) * r;
}
// distance constraints (structure, shear, hoop, vertical)
const cA = [], cB = [], cL = [], seen = new Set();
const addPair = function (a, b) {
if (a === b) return;
const key = Math.min(a, b) * P + Math.max(a, b);
if (seen.has(key)) return;
seen.add(key);
cA.push(a); cB.push(b);
const dx = REST[a * 3] - REST[b * 3], dy = REST[a * 3 + 1] - REST[b * 3 + 1], dz = REST[a * 3 + 2] - REST[b * 3 + 2];
cL.push(Math.sqrt(dx * dx + dy * dy + dz * dz));
};
for (let k = 0; k < NK; k++) for (let i = 0; i < NA; i++) {
for (let j = 0; j < NJ - 1; j++) {
addPair(ID(i, j, k), ID(i, j + 1, k));
addPair(ID(i, j, k), ID(i + 1, j + 1, k));
addPair(ID(i + 1, j, k), ID(i, j + 1, k));
}
for (let j = 1; j < NJ; j++) addPair(ID(i, j, k), ID(i + 1, j, k));
if (k < NK - 1) for (let j = 0; j < NJ; j++) addPair(ID(i, j, k), ID(i, j, k + 1));
}
const NC = cA.length;
const CA = Int32Array.from(cA), CB = Int32Array.from(cB), CL = Float64Array.from(cL);
const lam = new Float64Array(NC);
const topMask = new Uint8Array(P);
for (let i = 0; i < NA; i++) for (let j = 0; j <= 8; j++) topMask[ID(i, j, 2)] = 1;
const pos = new Float64Array(P * 3), prv = new Float64Array(P * 3), vel = new Float64Array(P * 3);
const invM = new Float64Array(P);
const grabT = new Float64Array(3);
let grabP = -1, squeezeDepth = 0, alphaC = 0.0055; // alphaC = compliance, set by Firmness
const resetParticles = function () {
for (let n = 0; n < P * 3; n++) { pos[n] = REST[n]; prv[n] = REST[n]; vel[n] = 0; }
for (let p = 0; p < P; p++) invM[p] = INV_M;
grabP = -1;
};
// XPBD step: gravity, damping, distance constraints, floor and plate limits
const step = function (h) {
const damp = Math.exp(-DAMP * h);
const kG = Math.min(1, 30 * h);
for (let p = 0; p < P; p++) {
const b = p * 3;
prv[b] = pos[b]; prv[b + 1] = pos[b + 1]; prv[b + 2] = pos[b + 2];
if (p === grabP) {
pos[b] += (grabT[0] - pos[b]) * kG;
pos[b + 1] += (Math.max(0.02, grabT[1]) - pos[b + 1]) * kG;
pos[b + 2] += (grabT[2] - pos[b + 2]) * kG;
continue;
}
if (invM[p] === 0) continue;
let vx = vel[b] * damp, vy = vel[b + 1] * damp - G * h, vz = vel[b + 2] * damp;
if (squeezeDepth > 0 && topMask[p]) vy += (REST[b + 1] - squeezeDepth - pos[b + 1]) * SQ_K * h;
const s2 = vx * vx + vy * vy + vz * vz;
if (s2 > 36) { const s = 6 / Math.sqrt(s2); vx *= s; vy *= s; vz *= s; }
vel[b] = vx; vel[b + 1] = vy; vel[b + 2] = vz;
pos[b] += vx * h; pos[b + 1] += vy * h; pos[b + 2] += vz * h;
}
const at = alphaC / (h * h);
lam.fill(0);
for (let it = 0; it < ITER; it++) {
for (let c = 0; c < NC; c++) {
const ia = CA[c], ib = CB[c];
const wa = invM[ia], wb = invM[ib], wsum = wa + wb;
if (wsum === 0) continue;
const a = ia * 3, b = ib * 3;
const dx = pos[b] - pos[a], dy = pos[b + 1] - pos[a + 1], dz = pos[b + 2] - pos[a + 2];
const len = Math.sqrt(dx * dx + dy * dy + dz * dz) + 1e-9;
const C = len - CL[c];
const nx = dx / len, ny = dy / len, nz = dz / len;
const dl = (-C - at * lam[c]) / (wsum + at);
lam[c] += dl;
pos[a] -= wa * dl * nx; pos[a + 1] -= wa * dl * ny; pos[a + 2] -= wa * dl * nz;
pos[b] += wb * dl * nx; pos[b + 1] += wb * dl * ny; pos[b + 2] += wb * dl * nz;
}
}
for (let p = 0; p < P; p++) {
const b = p * 3;
const rr = Math.sqrt(pos[b] * pos[b] + pos[b + 2] * pos[b + 2]);
if (rr > WALL) { const s = WALL / rr; pos[b] *= s; pos[b + 2] *= s; }
if (pos[b + 1] < 0) {
pos[b + 1] = 0;
pos[b] = prv[b] + (pos[b] - prv[b]) * 0.6;
pos[b + 2] = prv[b + 2] + (pos[b + 2] - prv[b + 2]) * 0.6;
}
}
const ih = 1 / h;
for (let p = 0; p < P; p++) {
const b = p * 3;
vel[b] = (pos[b] - prv[b]) * ih;
vel[b + 1] = (pos[b + 1] - prv[b + 1]) * ih;
vel[b + 2] = (pos[b + 2] - prv[b + 2]) * ih;
}
};
const impulseAt = function (x, y, z, dirY, radius, strength) {
for (let p = 0; p < P; p++) {
const b = p * 3;
const dx = pos[b] - x, dy = pos[b + 1] - y, dz = pos[b + 2] - z;
const d = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (d < radius) vel[b + 1] += dirY * strength * (1 - d / radius);
}
};
const pickNearest = function (x, y, z) {
let best = -1, bd = Infinity;
for (let p = 0; p < P; p++) {
const b = p * 3;
const dx = pos[b] - x, dy = pos[b + 1] - y, dz = pos[b + 2] - z;
const d = dx * dx + dy * dy + dz * dz;
if (d < bd) { bd = d; best = p; }
}
return best;
};
const grabEnd = function () {
if (grabP >= 0) { invM[grabP] = INV_M; grabP = -1; }
};
const grabStart = function (x, y, z) {
grabEnd();
const p = pickNearest(x, y, z);
if (p < 0) return;
grabP = p; invM[p] = 0;
grabT[0] = pos[p * 3]; grabT[1] = pos[p * 3 + 1]; grabT[2] = pos[p * 3 + 2];
};
const grabMove = function (x, y, z) {
if (grabP < 0) return;
grabT[0] = x; grabT[1] = y; grabT[2] = z;
};
// ---------- scene ----------
const scene = new T.Scene();
scene.background = new T.Color(0xf3efe6);
const camera = new T.PerspectiveCamera(36, 1, 0.05, 60);
scene.add(new T.HemisphereLight(0xffffff, 0xffe6c8, 0.9));
const keyLight = new T.DirectionalLight(0xffffff, 1.0);
keyLight.position.set(2.5, 5, 3);
scene.add(keyLight);
const backLight = new T.DirectionalLight(0xffb060, 1.3); // warm light from behind: glows through thin parts
backLight.position.set(-2, 1.2, -3);
scene.add(backLight);
const plate = new T.Mesh(new T.CylinderGeometry(1.75, 1.68, 0.08, 96),
new T.MeshStandardMaterial({ color: 0xffffff, roughness: 0.3 }));
plate.position.y = -0.04;
scene.add(plate);
const sCan = document.createElement('canvas');
sCan.width = 256; sCan.height = 256;
const sCtx = sCan.getContext('2d');
const sGrad = sCtx.createRadialGradient(128, 128, 8, 128, 128, 128);
sGrad.addColorStop(0, 'rgba(120,60,10,0.38)');
sGrad.addColorStop(1, 'rgba(120,60,10,0)');
sCtx.fillStyle = sGrad;
sCtx.fillRect(0, 0, 256, 256);
const blob = new T.Mesh(new T.PlaneGeometry(2.4, 2.4),
new T.MeshBasicMaterial({ map: new T.CanvasTexture(sCan), transparent: true, depthWrite: false }));
blob.rotation.x = -Math.PI / 2;
blob.position.y = 0.003;
scene.add(blob);
// procedural flesh: 10 wedges, juice vesicles, white membranes between wedges
function makeFleshTex() {
const c = document.createElement('canvas');
c.width = 512; c.height = 512;
const g = c.getContext('2d');
const base = g.createLinearGradient(0, 0, 0, 512);
base.addColorStop(0, '#ffc25a');
base.addColorStop(1, '#ff9a2a');
g.fillStyle = base;
g.fillRect(0, 0, 512, 512);
let seed = 12345;
const rnd = function () { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
const W = 512 / 10;
for (let w = 0; w < 10; w++) {
const x0 = w * W;
for (let n = 0; n < 80; n++) {
const r = 3 + rnd() * 6;
const x = x0 + 6 + rnd() * (W - 12);
const y = 6 + rnd() * 500;
const grd = g.createRadialGradient(x - r * 0.3, y - r * 0.3, r * 0.1, x, y, r);
grd.addColorStop(0, 'rgba(255,248,200,0.95)');
grd.addColorStop(0.6, 'rgba(255,186,60,0.9)');
grd.addColorStop(1, 'rgba(232,96,18,0.85)');
g.fillStyle = grd;
g.beginPath(); g.arc(x, y, r, 0, Math.PI * 2); g.fill();
g.fillStyle = 'rgba(255,255,255,0.75)';
g.beginPath(); g.arc(x - r * 0.35, y - r * 0.35, r * 0.22, 0, Math.PI * 2); g.fill();
}
g.fillStyle = 'rgba(255,250,236,0.95)';
g.fillRect(x0 - 1.5, 0, 3, 512);
}
const tex = new T.CanvasTexture(c);
tex.encoding = T.sRGBEncoding;
return tex;
}
// one indexed surface: flesh (rings 0-6), pith (ring 7), peel (ring 8 and the rim)
const geo = new T.BufferGeometry();
const posArr = new Float32Array(RVN * 3);
const uvArr = new Float32Array(RVN * 2);
geo.setAttribute('position', new T.BufferAttribute(posArr, 3));
geo.setAttribute('uv', new T.BufferAttribute(uvArr, 2));
for (let k = 0; k < NK; k++) for (let j = 0; j < NJ; j++) {
for (let i = 0; i < NA; i++) {
if (j === 0 && i > 0) continue;
const p = ID(i, j, k);
uvArr[p * 2] = i / NA; uvArr[p * 2 + 1] = RR[j];
}
if (j > 0) { const d = P + k * NJ + j; uvArr[d * 2] = 1; uvArr[d * 2 + 1] = RR[j]; }
}
const triFlesh = [], triPith = [], triPeel = [];
const addTri = function (list, a, b, c) { if (a !== b && b !== c && a !== c) list.push(a, b, c); };
for (let i = 0; i < NA; i++) {
const i1 = i + 1;
for (let j = 0; j < NJ - 1; j++) {
const list = j <= 6 ? triFlesh : (j === 7 ? triPith : triPeel);
const a0 = ID(i, j, 2), a1 = RV(i1, j, 2), a2 = RV(i1, j + 1, 2), a3 = ID(i, j + 1, 2);
addTri(list, a0, a1, a2); addTri(list, a0, a2, a3);
const b0 = ID(i, j, 0), b1 = RV(i1, j, 0), b2 = RV(i1, j + 1, 0), b3 = ID(i, j + 1, 0);
addTri(list, b0, b2, b1); addTri(list, b0, b3, b2);
}
for (let k = 0; k < NK - 1; k++) {
const w0 = ID(i, 9, k), w1 = RV(i1, 9, k), w2 = RV(i1, 9, k + 1), w3 = ID(i, 9, k + 1);
addTri(triPeel, w0, w2, w1); addTri(triPeel, w0, w3, w2);
}
}
const indices = new Uint16Array(triFlesh.length + triPith.length + triPeel.length);
indices.set(triFlesh, 0);
indices.set(triPith, triFlesh.length);
indices.set(triPeel, triFlesh.length + triPith.length);
geo.setIndex(new T.BufferAttribute(indices, 1));
geo.addGroup(0, triFlesh.length, 0);
geo.addGroup(triFlesh.length, triPith.length, 1);
geo.addGroup(triFlesh.length + triPith.length, triPeel.length, 2);
const fleshMat = new T.MeshPhysicalMaterial({
map: makeFleshTex(), transmission: 0.55, thickness: 0.6, ior: 1.33,
roughness: 0.15, clearcoat: 0.8, clearcoatRoughness: 0.1,
emissive: 0xff7a1a, emissiveIntensity: 0.14, side: T.DoubleSide
});
const pithMat = new T.MeshStandardMaterial({ color: 0xfff3dc, roughness: 0.6 });
const peelMat = new T.MeshPhysicalMaterial({
color: 0xff7414, roughness: 0.35, clearcoat: 0.6, clearcoatRoughness: 0.2,
emissive: 0xff6a00, emissiveIntensity: 0.12
});
const jelly = new T.Mesh(geo, [fleshMat, pithMat, peelMat]);
jelly.frustumCulled = false;
scene.add(jelly);
const posAttr = geo.getAttribute('position');
function syncMesh() {
const arr = posAttr.array;
for (let n = 0; n < P * 3; n++) arr[n] = pos[n];
for (let k = 0; k < NK; k++) for (let j = 1; j < NJ; j++) {
const s = ID(0, j, k) * 3, d = (P + k * NJ + j) * 3;
arr[d] = pos[s]; arr[d + 1] = pos[s + 1]; arr[d + 2] = pos[s + 2];
}
posAttr.needsUpdate = true;
geo.computeVertexNormals();
const na = geo.getAttribute('normal').array;
for (let k = 0; k < NK; k++) for (let j = 1; j < NJ; j++) {
const s = ID(0, j, k) * 3, d = (P + k * NJ + j) * 3;
let nx = na[s] + na[d], ny = na[s + 1] + na[d + 1], nz = na[s + 2] + na[d + 2];
const L = Math.sqrt(nx * nx + ny * ny + nz * nz) || 1;
nx /= L; ny /= L; nz /= L;
na[s] = nx; na[d] = nx; na[s + 1] = ny; na[d + 1] = ny; na[s + 2] = nz; na[d + 2] = nz;
}
geo.getAttribute('normal').needsUpdate = true;
geo.computeBoundingSphere();
}
// ---------- squeeze drops ----------
const dropGeo = new T.SphereGeometry(0.035, 18, 12);
const dropMat = new T.MeshPhysicalMaterial({ color: 0xffa51f, roughness: 0.05, clearcoat: 1, clearcoatRoughness: 0.05, transparent: true, opacity: 0.92 });
let drops = [];
let sq = null, juiceLeft = true;
const SQ_START = 0.3, SQ_GAP = 1.2, SQ_LEN = 0.8, SQ_DROPS = 4;
function spawnDrop() {
const th = Math.random() * Math.PI * 2;
const m = new T.Mesh(dropGeo, dropMat);
m.position.set(Math.cos(th) * 0.98, YBASE, Math.sin(th) * 0.98);
scene.add(m);
drops.push({ m: m, vx: Math.cos(th) * 0.9, vy: 0.5, vz: Math.sin(th) * 0.9, down: false });
}
function dropsTick(dt) {
for (let i = 0; i < drops.length; i++) {
const d = drops[i];
if (d.down) continue;
d.vy -= G * dt;
d.m.position.x += d.vx * dt;
d.m.position.y += d.vy * dt;
d.m.position.z += d.vz * dt;
if (d.m.position.y <= 0.02) { d.m.position.y = 0.012; d.down = true; d.m.scale.set(1.6, 0.25, 1.6); }
}
}
function updateButtons() {
if (!juiceLeft) { squeezeBtn.textContent = 'Out of juice'; squeezeBtn.disabled = true; }
else if (sq) { squeezeBtn.textContent = 'Squeezing...'; squeezeBtn.disabled = true; }
else { squeezeBtn.textContent = 'Squeeze'; squeezeBtn.disabled = false; }
}
function startSqueeze() {
if (sq || !juiceLeft) return;
sq = { t: 0, spawned: 0 };
updateButtons();
}
function squeezeTick(dt) {
if (!sq) { squeezeDepth = 0; return; }
sq.t += dt;
let depth = 0;
for (let k = 0; k < SQ_DROPS; k++) {
const u = (sq.t - SQ_START - k * SQ_GAP) / SQ_LEN;
if (u >= 0 && u <= 1) depth = Math.max(depth, 0.085 * Math.sin(Math.PI * u));
}
if (sq.spawned < SQ_DROPS && sq.t >= SQ_START + sq.spawned * SQ_GAP + SQ_LEN * 0.5) {
sq.spawned++;
spawnDrop();
}
squeezeDepth = depth;
if (sq.spawned >= SQ_DROPS && sq.t >= SQ_START + (SQ_DROPS - 1) * SQ_GAP + SQ_LEN) {
sq = null; squeezeDepth = 0; juiceLeft = false;
updateButtons();
}
}
// ---------- firmness, reset ----------
function setFirm(v) {
v = Math.max(0, Math.min(100, Math.round(v)));
firmEl.value = String(v);
fvEl.textContent = String(v);
alphaC = 0.0025 * Math.pow(4.8, 1 - v / 100); // soft 0.012 ... firm 0.0025
}
function resetAll() {
grabEnd();
sq = null; squeezeDepth = 0; juiceLeft = true;
for (let i = 0; i < drops.length; i++) scene.remove(drops[i].m);
drops = [];
resetParticles();
setFirm(50);
updateButtons();
}
// ---------- size ----------
function resize() {
const w = window.innerWidth, h = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(w, h, false);
camera.aspect = w / h;
const pull = camera.aspect < 0.9 ? 2.2 : 1;
camera.position.set(0, 2.5 * pull, 4.4 * pull);
camera.lookAt(0, -0.05, 0);
camera.updateProjectionMatrix();
}
// ---------- pointer: poke, drag, let go ----------
const ray = new T.Raycaster();
const ndc = new T.Vector2();
const camDir = new T.Vector3();
const dragPlane = new T.Plane();
const hitPt = new T.Vector3();
const dragAnchor = new T.Vector3();
let dragging = false, dragId = -1, moved = false, downX = 0, downY = 0, downTime = 0;
function setRayFromEvent(e) {
const r = cv.getBoundingClientRect();
ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
ray.setFromCamera(ndc, camera);
}
cv.addEventListener('pointerdown', function (e) {
e.preventDefault();
if (dragging) return;
setRayFromEvent(e);
const hits = ray.intersectObject(jelly, false);
if (!hits.length) return;
dragging = true; dragId = e.pointerId; moved = false;
downX = e.clientX; downY = e.clientY; downTime = performance.now();
dragAnchor.copy(hits[0].point);
grabStart(dragAnchor.x, dragAnchor.y, dragAnchor.z);
grabMove(dragAnchor.x, dragAnchor.y, dragAnchor.z);
try { cv.setPointerCapture(e.pointerId); } catch (err) { /* capture is optional */ }
});
cv.addEventListener('pointermove', function (e) {
if (!dragging || e.pointerId !== dragId) return;
if (Math.hypot(e.clientX - downX, e.clientY - downY) > 10) moved = true;
setRayFromEvent(e);
camera.getWorldDirection(camDir);
dragPlane.setFromNormalAndCoplanarPoint(camDir, dragAnchor);
if (ray.ray.intersectPlane(dragPlane, hitPt)) grabMove(hitPt.x, hitPt.y, hitPt.z);
});
const endDrag = function (e) {
if (!dragging || e.pointerId !== dragId) return;
dragging = false;
grabEnd();
if (!moved && performance.now() - downTime < 450) {
impulseAt(dragAnchor.x, dragAnchor.y, dragAnchor.z, -1, 0.3, 1.8); // a tap is a poke
}
};
cv.addEventListener('pointerup', endDrag);
cv.addEventListener('pointercancel', endDrag);
cv.addEventListener('contextmenu', function (e) { e.preventDefault(); });
// ---------- demo mode (#demo): a 20 s hands-free loop, any real touch ends it ----------
let demo = /#demo$/i.test(location.href);
let demoT = 0, demoPrev = -1;
const demoEvents = [
[0.8, function () { impulseAt(0.2, 0.38, 0.2, -1, 0.3, 1.8); }],
[2.4, function () { grabStart(0.55, 0.38, -0.25); grabMove(0.55, 0.38, -0.25); }],
[4.4, function () { grabEnd(); }],
[6.0, function () { startSqueeze(); }],
[11.5, function () { setFirm(10); }],
[14.0, function () { setFirm(90); }],
[16.5, function () { setFirm(50); }],
[18.8, function () { resetAll(); }]
];
function demoTick(dt) {
demoT += dt;
const t = demoT % 20;
if (t < demoPrev) demoPrev = -1;
for (let n = 0; n < demoEvents.length; n++) {
if (demoPrev < demoEvents[n][0] && t >= demoEvents[n][0]) demoEvents[n][1]();
}
demoPrev = t;
if (grabP >= 0 && t >= 2.4 && t < 4.4) {
const s = (t - 2.4) / 2, e = s * s * (3 - 2 * s);
grabMove(0.55 - 0.3 * e, 0.38 + 0.25 * Math.sin(Math.PI * s), -0.25 + 0.6 * e);
}
}
document.addEventListener('pointerdown', function () {
if (!demo) return;
demo = false;
grabEnd();
setHint('Your turn. Poke it, drag it, squeeze it, or change the firmness.');
}, true);
squeezeBtn.addEventListener('click', function () { startSqueeze(); });
resetBtn.addEventListener('click', function () { resetAll(); });
firmEl.addEventListener('input', function () { setFirm(Number(firmEl.value)); });
// ---------- main loop: fixed physics step, independent of frame rate ----------
let last = performance.now(), acc = 0;
function frame(now) {
requestAnimationFrame(frame);
const dt = Math.min(0.05, Math.max(0, (now - last) / 1000));
last = now;
if (demo) demoTick(dt);
squeezeTick(dt);
acc += dt;
let steps = 0;
while (acc >= H_FIX && steps < MAX_STEPS) { step(H_FIX); acc -= H_FIX; steps++; }
if (steps >= MAX_STEPS) acc = 0;
dropsTick(dt);
syncMesh();
renderer.render(scene, camera);
}
resetParticles();
setFirm(50);
resize();
syncMesh();
updateButtons();
window.addEventListener('resize', resize);
setHint(demo ? 'Demo: touch the jelly to take over.' : 'Poke it, or drag to stretch it. Let go and it jiggles.');
requestAnimationFrame(frame);
})();
</script>
</body>
</html>
