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.)<!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:#e9dfd2;font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#3b2a1a;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}
#c{position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none}
#top{position:fixed;top:max(10px,env(safe-area-inset-top));left:0;right:0;text-align:center;pointer-events:none;padding:0 12px}
h1{font-size:19px;margin:0;font-weight:800;letter-spacing:.02em;color:#6b3a0e}
#hint{font-size:13.5px;opacity:.8;margin-top:3px;transition:opacity .6s}
#panel{position:fixed;left:50%;transform:translateX(-50%);bottom:max(12px,env(safe-area-inset-bottom));width:min(560px,calc(100% - 24px));box-sizing:border-box;background:rgba(255,251,245,.8);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);border-radius:22px;padding:12px 14px;box-shadow:0 8px 30px rgba(80,50,20,.18);display:flex;flex-direction:column;gap:8px}
.row{display:flex;gap:10px;align-items:center}
button{flex:1;min-height:56px;font-size:18px;font-weight:800;border:none;border-radius:16px;cursor:pointer;touch-action:manipulation;font-family:inherit}
#squeeze{background:linear-gradient(#ffb44a,#ff7a00);color:#fff;box-shadow:0 4px 0 #c45700;text-shadow:0 1px 1px rgba(0,0,0,.2)}
#squeeze:active{transform:translateY(2px);box-shadow:0 2px 0 #c45700}
#squeeze:disabled{opacity:.55}
#reset{flex:.62;background:#fff;color:#7a4a1c;box-shadow:0 4px 0 #dccbb7,inset 0 0 0 2px #ecdcc8}
#reset:active{transform:translateY(2px);box-shadow:0 2px 0 #dccbb7,inset 0 0 0 2px #ecdcc8}
label{font-weight:800;font-size:15px;min-width:72px;color:#6b3a0e}
#val{min-width:64px;text-align:right;font-size:14px;font-weight:700;color:#9a5a1c}
input[type=range]{-webkit-appearance:none;appearance:none;flex:1;height:46px;background:transparent;margin:0;touch-action:pan-x}
input[type=range]::-webkit-slider-runnable-track{height:10px;border-radius:6px;background:linear-gradient(90deg,#ffe0b5,#ff8a1a)}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:32px;height:32px;border-radius:50%;background:#fff;border:3px solid #ff8a1a;margin-top:-11px;box-shadow:0 2px 6px rgba(0,0,0,.25)}
input[type=range]::-moz-range-track{height:10px;border-radius:6px;background:linear-gradient(90deg,#ffe0b5,#ff8a1a)}
input[type=range]::-moz-range-thumb{width:26px;height:26px;border-radius:50%;background:#fff;border:3px solid #ff8a1a}
#badge{position:fixed;top:max(64px,calc(env(safe-area-inset-top) + 54px));left:50%;transform:translateX(-50%);background:rgba(60,30,5,.72);color:#fff;font-size:13px;font-weight:700;padding:6px 12px;border-radius:20px;display:none;pointer-events:none}
#finger{position:fixed;left:0;top:0;width:46px;height:46px;margin:-23px 0 0 -23px;border-radius:50%;background:rgba(255,255,255,.42);border:3px solid rgba(255,255,255,.95);box-shadow:0 2px 12px rgba(0,0,0,.28);pointer-events:none;opacity:0;transition:opacity .15s}
#err{position:fixed;inset:0;display:none;align-items:center;justify-content:center;text-align:center;padding:24px;font-size:16px}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="top"><h1>Orange Jelly Slice</h1><div id="hint">Poke or drag the jelly · drag the plate to turn</div></div>
<div id="badge">Demo · touch to take over</div>
<div id="finger"></div>
<div id="panel">
<div class="row">
<button id="squeeze">Squeeze</button>
<button id="reset">Reset</button>
</div>
<div class="row">
<label for="firm">Firmness</label>
<input id="firm" type="range" min="0" max="100" value="50">
<span id="val">Medium</span>
</div>
</div>
<div id="err">Sorry, this needs WebGL to run.</div>
<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>
<script type="module">
import * as THREE from 'three';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
const canvas = document.getElementById('c');
const panel = document.getElementById('panel');
const hintEl = document.getElementById('hint');
const badge = document.getElementById('badge');
const finger = document.getElementById('finger');
const slider = document.getElementById('firm');
const valEl = document.getElementById('val');
const btnSq = document.getElementById('squeeze');
const btnReset = document.getElementById('reset');
let renderer;
try {
renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
} catch (e) {
document.getElementById('err').style.display = 'flex';
throw e;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.0;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
const BG = new THREE.Color(0xe9dfd2);
scene.background = BG;
scene.fog = new THREE.Fog(BG, 9, 24);
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
const camera = new THREE.PerspectiveCamera(34, 1, 0.05, 80);
// ---------------- lights ----------------
const hemi = new THREE.HemisphereLight(0xfff4e6, 0xa88f70, 0.75);
scene.add(hemi);
const keyPos = new THREE.Vector3(-2.5, 4.5, 2.5);
const key = new THREE.DirectionalLight(0xfff1df, 1.3);
key.position.copy(keyPos);
scene.add(key);
const backPos = new THREE.Vector3(1.2, 2.6, -4.2);
const back = new THREE.DirectionalLight(0xffe2b8, 1.8);
back.position.copy(backPos).multiplyScalar(1.3);
back.castShadow = true;
back.shadow.mapSize.set(1024, 1024);
const sc = back.shadow.camera;
sc.left = -2.6; sc.right = 2.6; sc.top = 2.6; sc.bottom = -2.6; sc.near = 0.5; sc.far = 16;
back.shadow.bias = -0.0004;
back.shadow.normalBias = 0.02;
scene.add(back);
// ---------------- textures ----------------
function linenTex() {
const c = document.createElement('canvas'); c.width = c.height = 512;
const g = c.getContext('2d');
g.fillStyle = '#d6c8b4'; g.fillRect(0, 0, 512, 512);
for (let i = 0; i < 2600; i++) {
const a = 0.03 + Math.random() * 0.05;
g.fillStyle = Math.random() < 0.5 ? `rgba(255,248,235,${a})` : `rgba(120,95,70,${a})`;
if (i % 2) g.fillRect(0, Math.random() * 512, 512, 1); else g.fillRect(Math.random() * 512, 0, 1, 512);
}
const t = new THREE.CanvasTexture(c);
t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(9, 9);
t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 4;
return t;
}
function radialTex(stops) {
const c = document.createElement('canvas'); c.width = c.height = 256;
const g = c.getContext('2d');
const grd = g.createRadialGradient(128, 128, 0, 128, 128, 128);
for (const [o, col] of stops) grd.addColorStop(o, col);
g.fillStyle = grd; g.fillRect(0, 0, 256, 256);
const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace;
return t;
}
// ---------------- table & plate ----------------
const table = new THREE.Mesh(new THREE.PlaneGeometry(50, 50), new THREE.MeshStandardMaterial({ map: linenTex(), roughness: 0.92, metalness: 0 }));
table.rotation.x = -Math.PI / 2; table.position.y = -0.076; table.receiveShadow = true;
scene.add(table);
const RF = 1.3, RRIM = 1.86, HRIM = 0.17;
function plateH(x, z) {
const r = Math.hypot(x, z);
if (r <= RF) return 0;
const t = Math.min(1, (r - RF) / (RRIM - RF));
return HRIM * t * t + Math.max(0, r - RRIM) * 2;
}
{
const pts = [new THREE.Vector2(0, 0)];
for (let i = 0; i <= 10; i++) { const t = i / 10; pts.push(new THREE.Vector2(RF + t * (RRIM - RF), HRIM * t * t)); }
pts.push(new THREE.Vector2(1.9, 0.174), new THREE.Vector2(1.93, 0.163), new THREE.Vector2(1.925, 0.146), new THREE.Vector2(1.88, 0.132));
for (let i = 10; i >= 0; i--) { const t = i / 10; pts.push(new THREE.Vector2(RF + t * (RRIM - RF) - 0.03, HRIM * t * t - 0.04)); }
pts.push(new THREE.Vector2(1.1, -0.045), new THREE.Vector2(1.06, -0.075), new THREE.Vector2(0.98, -0.075), new THREE.Vector2(0.96, -0.052), new THREE.Vector2(0, -0.052));
const plateGeo = new THREE.LatheGeometry(pts, 120);
const plateMat = new THREE.MeshPhysicalMaterial({ color: 0xfbfaf6, roughness: 0.3, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.06, envMapIntensity: 0.7, side: THREE.DoubleSide });
const plate = new THREE.Mesh(plateGeo, plateMat);
plate.castShadow = true; plate.receiveShadow = true;
scene.add(plate);
}
// contact shadow + orange light glow decals
const aoMesh = new THREE.Mesh(new THREE.PlaneGeometry(2.5, 1.45), new THREE.MeshBasicMaterial({
map: radialTex([[0, 'rgba(40,20,5,0.55)'], [0.55, 'rgba(40,20,5,0.28)'], [1, 'rgba(40,20,5,0)']]),
transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, fog: false
}));
aoMesh.rotation.x = -Math.PI / 2; aoMesh.renderOrder = -2; scene.add(aoMesh);
const glowMesh = new THREE.Mesh(new THREE.PlaneGeometry(2.4, 1.6), new THREE.MeshBasicMaterial({
map: radialTex([[0, 'rgba(255,140,30,1)'], [0.5, 'rgba(255,120,20,0.45)'], [1, 'rgba(255,110,10,0)']]),
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, opacity: 0.42, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -3, fog: false
}));
glowMesh.rotation.x = -Math.PI / 2; glowMesh.renderOrder = -1; scene.add(glowMesh);
// ---------------- jelly geometry ----------------
const R = 1.0, T = 0.34, BEV = 0.075, BEVB = 0.045, DOME = 0.022, LIFT = 0.006, ZOFF = 0.45;
const TOPY = LIFT + T + DOME + 0.012;
const YWT = LIFT + T - BEV, YWB = LIFT + BEVB;
function sstep(a, b, x) { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); }
function edgeD(u, v) { return Math.max(0, Math.min(R - Math.hypot(u, v), v)); }
function rnd(d, b) { const s = Math.min(d / b, 1); return Math.sqrt(Math.max(0, 1 - (1 - s) * (1 - s))); }
function yTop(u, v) { const d = edgeD(u, v); return YWT + BEV * rnd(d, BEV) + DOME * sstep(0, 0.45, d); }
function yBot(u, v) { const d = edgeD(u, v); return LIFT + BEVB * (1 - rnd(d, BEVB)); }
const NR = 34, NA = 112, NW = 4;
const ring = [], ang = [];
for (let k = 0; k <= NR; k++) { const t = k / NR; ring.push(R * (1.5 * t - 0.5 * t * t)); }
for (let m = 0; m <= NA; m++) { const s = m / NA; ang.push(Math.PI * (s - 0.25 * Math.sin(2 * Math.PI * s) / (2 * Math.PI))); }
const posA = [], restA = [], index = [];
function addV(u, y, v) { restA.push(u, y, v); posA.push(u, y, ZOFF - v); return restA.length / 3 - 1; }
function tri(a, b, c, ex, ey, ez) {
const ax = posA[a * 3], ay = posA[a * 3 + 1], az = posA[a * 3 + 2];
const e1x = posA[b * 3] - ax, e1y = posA[b * 3 + 1] - ay, e1z = posA[b * 3 + 2] - az;
const e2x = posA[c * 3] - ax, e2y = posA[c * 3 + 1] - ay, e2z = posA[c * 3 + 2] - az;
const nx = e1y * e2z - e1z * e2y, ny = e1z * e2x - e1x * e2z, nz = e1x * e2y - e1y * e2x;
if (Math.hypot(nx, ny, nz) < 1e-11) return;
if (nx * ex + ny * ey + nz * ez >= 0) index.push(a, b, c); else index.push(a, c, b);
}
function surface(yf, sign) {
const base = restA.length / 3;
for (let k = 0; k <= NR; k++) for (let m = 0; m <= NA; m++) {
const u = ring[k] * Math.cos(ang[m]), v = Math.max(0, ring[k] * Math.sin(ang[m]));
addV(u, yf(u, v), v);
}
for (let k = 0; k < NR; k++) for (let m = 0; m < NA; m++) {
const a = base + k * (NA + 1) + m, b = a + (NA + 1), c = b + 1, d = a + 1;
tri(a, b, c, 0, sign, 0); tri(a, c, d, 0, sign, 0);
}
}
surface(yTop, 1);
surface(yBot, -1);
{ // outer peel wall
const base = restA.length / 3;
for (let h = 0; h <= NW; h++) { const y = YWB + (YWT - YWB) * h / NW; for (let m = 0; m <= NA; m++) addV(Math.cos(ang[m]), y, Math.max(0, Math.sin(ang[m]))); }
for (let h = 0; h < NW; h++) for (let m = 0; m < NA; m++) {
const a = base + h * (NA + 1) + m, b = a + 1, c = a + (NA + 1) + 1, d = a + (NA + 1);
const tm = (ang[m] + ang[m + 1]) / 2, ex = Math.cos(tm), ez = -Math.sin(tm);
tri(a, b, c, ex, 0, ez); tri(a, c, d, ex, 0, ez);
}
}
{ // flat cut wall along the diameter
const us = [];
for (let k = NR; k >= 1; k--) us.push(-ring[k]);
us.push(0);
for (let k = 1; k <= NR; k++) us.push(ring[k]);
const L = us.length, base = restA.length / 3;
for (let h = 0; h <= NW; h++) { const y = YWB + (YWT - YWB) * h / NW; for (let q = 0; q < L; q++) addV(us[q], y, 0); }
for (let h = 0; h < NW; h++) for (let q = 0; q < L - 1; q++) {
const a = base + h * L + q, b = a + 1, c = a + L + 1, d = a + L;
tri(a, b, c, 0, 0, 1); tri(a, c, d, 0, 0, 1);
}
}
const posArr = new Float32Array(posA);
const nV = posArr.length / 3;
const geo = new THREE.BufferGeometry();
const posAttr = new THREE.BufferAttribute(posArr, 3); posAttr.setUsage(THREE.DynamicDrawUsage);
geo.setAttribute('position', posAttr);
geo.setAttribute('aRest', new THREE.Float32BufferAttribute(restA, 3));
geo.setIndex(index);
geo.computeVertexNormals();
// ---------------- soft body lattice ----------------
const NX = 12, NZ = 6, NY = 2;
const HX = 2 * R / NX, HZ = R / NZ, HY = TOPY / NY, X0 = -R, Z0 = ZOFF - R;
const NNX = NX + 1, NNY = NY + 1, NNZ = NZ + 1;
const colActive = new Uint8Array(NX * NZ);
for (let k = 0; k < NZ; k++) for (let i = 0; i < NX; i++) {
let act = false;
for (let a = 0; a <= 5 && !act; a++) for (let b = 0; b <= 5; b++) {
const x = X0 + (i + a / 5) * HX, z = Z0 + (k + b / 5) * HZ, u = x, v = ZOFF - z;
if (v >= -1e-6 && u * u + v * v <= R * R + 1e-6) { act = true; break; }
}
if (act) colActive[i + NX * k] = 1;
}
const clampi = (v, a, b) => v < a ? a : (v > b ? b : v);
for (let n = 0; n < nV; n++) {
const i = clampi(Math.floor((posArr[n * 3] - X0) / HX), 0, NX - 1);
const k = clampi(Math.floor((posArr[n * 3 + 2] - Z0) / HZ), 0, NZ - 1);
colActive[i + NX * k] = 1;
}
const nid = (i, j, k) => i + NNX * (j + NNY * k);
const nodeP = new Int32Array(NNX * NNY * NNZ).fill(-1);
const pI = [], pJ = [], pK = [];
let nP = 0;
for (let k = 0; k <= NZ; k++) for (let j = 0; j <= NY; j++) for (let i = 0; i <= NX; i++) {
let act = false;
for (let di = -1; di <= 0; di++) for (let dk = -1; dk <= 0; dk++) {
const ci = i + di, ck = k + dk;
if (ci >= 0 && ci < NX && ck >= 0 && ck < NZ && colActive[ci + NX * ck]) act = true;
}
if (act) { nodeP[nid(i, j, k)] = nP++; pI.push(i); pJ.push(j); pK.push(k); }
}
const REST = new Float64Array(nP * 3), X = new Float64Array(nP * 3), P = new Float64Array(nP * 3), V = new Float64Array(nP * 3);
for (let p = 0; p < nP; p++) { REST[p * 3] = X0 + pI[p] * HX; REST[p * 3 + 1] = pJ[p] * HY; REST[p * 3 + 2] = Z0 + pK[p] * HZ; }
// skin weights (trilinear)
const skinI = new Int32Array(nV * 8), skinW = new Float32Array(nV * 8);
for (let n = 0; n < nV; n++) {
const x = posArr[n * 3], y = posArr[n * 3 + 1], z = posArr[n * 3 + 2];
let fx = (x - X0) / HX, fy = y / HY, fz = (z - Z0) / HZ;
const i = clampi(Math.floor(fx), 0, NX - 1), j = clampi(Math.floor(fy), 0, NY - 1), k = clampi(Math.floor(fz), 0, NZ - 1);
fx = Math.min(1, Math.max(0, fx - i)); fy = Math.min(1, Math.max(0, fy - j)); fz = Math.min(1, Math.max(0, fz - k));
let sw = 0;
for (let c = 0; c < 8; c++) {
const di = c & 1, dj = (c >> 1) & 1, dk = c >> 2;
let p = nodeP[nid(i + di, j + dj, k + dk)];
let w = (di ? fx : 1 - fx) * (dj ? fy : 1 - fy) * (dk ? fz : 1 - fz);
if (p < 0) { p = 0; w = 0; }
skinI[n * 8 + c] = p; skinW[n * 8 + c] = w; sw += w;
}
if (sw > 0) for (let c = 0; c < 8; c++) skinW[n * 8 + c] /= sw;
}
// overlapping shape-matching regions (lattice shape matching)
const regOff = new Int32Array(nP + 1);
const memL = [], qL = [];
const cnt = new Float64Array(nP);
for (let a = 0; a < nP; a++) {
regOff[a] = memL.length;
const mem = [];
for (let dk = -1; dk <= 1; dk++) for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) {
const i = pI[a] + di, j = pJ[a] + dj, k = pK[a] + dk;
if (i < 0 || i > NX || j < 0 || j > NY || k < 0 || k > NZ) continue;
const b = nodeP[nid(i, j, k)];
if (b >= 0) mem.push(b);
}
let cx = 0, cy = 0, cz = 0;
for (const b of mem) { cx += REST[b * 3]; cy += REST[b * 3 + 1]; cz += REST[b * 3 + 2]; }
cx /= mem.length; cy /= mem.length; cz /= mem.length;
for (const b of mem) { memL.push(b); qL.push(REST[b * 3] - cx, REST[b * 3 + 1] - cy, REST[b * 3 + 2] - cz); cnt[b]++; }
}
regOff[nP] = memL.length;
const regMem = new Int32Array(memL), regQ = new Float64Array(qL);
const regQuat = new Float64Array(nP * 4);
const goal = new Float64Array(nP * 3);
function shapeMatch(alpha, sx, sy, sz) {
goal.fill(0);
for (let r = 0; r < nP; r++) {
const a = regOff[r], b = regOff[r + 1], m = b - a;
let cx = 0, cy = 0, cz = 0;
for (let t = a; t < b; t++) { const j = regMem[t] * 3; cx += P[j]; cy += P[j + 1]; cz += P[j + 2]; }
cx /= m; cy /= m; cz /= m;
let a00 = 0, a01 = 0, a02 = 0, a10 = 0, a11 = 0, a12 = 0, a20 = 0, a21 = 0, a22 = 0;
for (let t = a; t < b; t++) {
const j = regMem[t] * 3;
const dx = P[j] - cx, dy = P[j + 1] - cy, dz = P[j + 2] - cz;
const qx = regQ[t * 3] * sx, qy = regQ[t * 3 + 1] * sy, qz = regQ[t * 3 + 2] * sz;
a00 += dx * qx; a01 += dx * qy; a02 += dx * qz;
a10 += dy * qx; a11 += dy * qy; a12 += dy * qz;
a20 += dz * qx; a21 += dz * qy; a22 += dz * qz;
}
// robust rotation extraction (iterative quaternion, warm-started)
let qx = regQuat[r * 4], qy = regQuat[r * 4 + 1], qz = regQuat[r * 4 + 2], qw = regQuat[r * 4 + 3];
let r00, r01, r02, r10, r11, r12, r20, r21, r22;
for (let it = 0; it < 5; it++) {
r00 = 1 - 2 * (qy * qy + qz * qz); r01 = 2 * (qx * qy - qz * qw); r02 = 2 * (qx * qz + qy * qw);
r10 = 2 * (qx * qy + qz * qw); r11 = 1 - 2 * (qx * qx + qz * qz); r12 = 2 * (qy * qz - qx * qw);
r20 = 2 * (qx * qz - qy * qw); r21 = 2 * (qy * qz + qx * qw); r22 = 1 - 2 * (qx * qx + qy * qy);
let ox = (r10 * a20 - r20 * a10) + (r11 * a21 - r21 * a11) + (r12 * a22 - r22 * a12);
let oy = (r20 * a00 - r00 * a20) + (r21 * a01 - r01 * a21) + (r22 * a02 - r02 * a22);
let oz = (r00 * a10 - r10 * a00) + (r01 * a11 - r11 * a01) + (r02 * a12 - r12 * a02);
const den = Math.abs(r00 * a00 + r10 * a10 + r20 * a20 + r01 * a01 + r11 * a11 + r21 * a21 + r02 * a02 + r12 * a12 + r22 * a22) + 1e-9;
ox /= den; oy /= den; oz /= den;
const w = Math.sqrt(ox * ox + oy * oy + oz * oz);
if (w < 1e-8) break;
const h = w * 0.5, s = Math.sin(h) / w, c = Math.cos(h);
const dx = ox * s, dy = oy * s, dz = oz * s, dw = c;
const nx = dw * qx + dx * qw + dy * qz - dz * qy;
const ny = dw * qy - dx * qz + dy * qw + dz * qx;
const nz = dw * qz + dx * qy - dy * qx + dz * qw;
const nw = dw * qw - dx * qx - dy * qy - dz * qz;
const l = 1 / Math.sqrt(nx * nx + ny * ny + nz * nz + nw * nw);
qx = nx * l; qy = ny * l; qz = nz * l; qw = nw * l;
}
regQuat[r * 4] = qx; regQuat[r * 4 + 1] = qy; regQuat[r * 4 + 2] = qz; regQuat[r * 4 + 3] = qw;
r00 = 1 - 2 * (qy * qy + qz * qz); r01 = 2 * (qx * qy - qz * qw); r02 = 2 * (qx * qz + qy * qw);
r10 = 2 * (qx * qy + qz * qw); r11 = 1 - 2 * (qx * qx + qz * qz); r12 = 2 * (qy * qz - qx * qw);
r20 = 2 * (qx * qz - qy * qw); r21 = 2 * (qy * qz + qx * qw); r22 = 1 - 2 * (qx * qx + qy * qy);
for (let t = a; t < b; t++) {
const j = regMem[t] * 3;
const qx2 = regQ[t * 3] * sx, qy2 = regQ[t * 3 + 1] * sy, qz2 = regQ[t * 3 + 2] * sz;
goal[j] += cx + r00 * qx2 + r01 * qy2 + r02 * qz2;
goal[j + 1] += cy + r10 * qx2 + r11 * qy2 + r12 * qz2;
goal[j + 2] += cz + r20 * qx2 + r21 * qy2 + r22 * qz2;
}
}
for (let p = 0; p < nP; p++) {
const inv = 1 / cnt[p], j = p * 3;
P[j] += alpha * (goal[j] * inv - P[j]);
P[j + 1] += alpha * (goal[j + 1] * inv - P[j + 1]);
P[j + 2] += alpha * (goal[j + 2] * inv - P[j + 2]);
}
}
// ---------------- simulation state ----------------
const G = 10, DT = 1 / 240, MAXSUB = 8, DAMP = 3.0;
let firm = 0.5;
let pressY = 99, Sy = 1;
const grab = { active: false, dragging: false, idx: [], w: [], p0: [], hit: new THREE.Vector3(), plane: new THREE.Plane(), delta: new THREE.Vector3(), center: new THREE.Vector3() };
function alphaFromFirm() { const f = 5 + 13 * firm; const w = 2 * Math.PI * f; return Math.min(0.5, w * w * DT * DT); }
function step(dt) {
const alpha = alphaFromFirm();
const damp = Math.exp(-DAMP * dt);
for (let p = 0; p < nP; p++) {
const j = p * 3;
V[j + 1] -= G * dt;
P[j] = X[j] + V[j] * dt; P[j + 1] = X[j + 1] + V[j + 1] * dt; P[j + 2] = X[j + 2] + V[j + 2] * dt;
}
const sxz = 1 / Math.sqrt(Sy);
shapeMatch(alpha, sxz, Sy, sxz);
if (grab.active && grab.dragging) {
const d = grab.delta;
for (let n = 0; n < grab.idx.length; n++) {
const j = grab.idx[n] * 3, w = grab.w[n], s = Math.min(1, 0.3 * w), o = grab.p0;
const tx = o[n * 3] + d.x * w, ty = o[n * 3 + 1] + d.y * w, tz = o[n * 3 + 2] + d.z * w;
P[j] += (tx - P[j]) * s; P[j + 1] += (ty - P[j + 1]) * s; P[j + 2] += (tz - P[j + 2]) * s;
}
}
if (pressY < 5) {
for (let p = 0; p < nP; p++) {
const j = p * 3;
if (P[j + 1] > pressY) { P[j + 1] = pressY; P[j] = X[j] + (P[j] - X[j]) * 0.85; P[j + 2] = X[j + 2] + (P[j + 2] - X[j + 2]) * 0.85; }
}
}
for (let p = 0; p < nP; p++) {
const j = p * 3;
const h = plateH(P[j], P[j + 2]);
if (P[j + 1] < h) { P[j + 1] = h; P[j] = X[j] + (P[j] - X[j]) * 0.4; P[j + 2] = X[j + 2] + (P[j + 2] - X[j + 2]) * 0.4; }
}
const inv = 1 / dt;
for (let p = 0; p < nP; p++) {
const j = p * 3;
let vx = (P[j] - X[j]) * inv * damp, vy = (P[j + 1] - X[j + 1]) * inv * damp, vz = (P[j + 2] - X[j + 2]) * inv * damp;
const sp = Math.sqrt(vx * vx + vy * vy + vz * vz);
if (sp > 25) { const k = 25 / sp; vx *= k; vy *= k; vz *= k; }
V[j] = vx; V[j + 1] = vy; V[j + 2] = vz;
X[j] = P[j]; X[j + 1] = P[j + 1]; X[j + 2] = P[j + 2];
}
}
function resetJelly(dropH = 0.18) {
for (let p = 0; p < nP; p++) {
X[p * 3] = REST[p * 3]; X[p * 3 + 1] = REST[p * 3 + 1] + dropH; X[p * 3 + 2] = REST[p * 3 + 2];
V[p * 3] = V[p * 3 + 1] = V[p * 3 + 2] = 0;
regQuat[p * 4] = regQuat[p * 4 + 1] = regQuat[p * 4 + 2] = 0; regQuat[p * 4 + 3] = 1;
}
releaseGrab();
}
function deformPoint(x, y, z, out) {
let fx = (x - X0) / HX, fy = y / HY, fz = (z - Z0) / HZ;
const i = clampi(Math.floor(fx), 0, NX - 1), j = clampi(Math.floor(fy), 0, NY - 1), k = clampi(Math.floor(fz), 0, NZ - 1);
fx = Math.min(1, Math.max(0, fx - i)); fy = Math.min(1, Math.max(0, fy - j)); fz = Math.min(1, Math.max(0, fz - k));
let sx = 0, sy = 0, sz = 0, sw = 0;
for (let c = 0; c < 8; c++) {
const di = c & 1, dj = (c >> 1) & 1, dk = c >> 2;
const p = nodeP[nid(i + di, j + dj, k + dk)];
if (p < 0) continue;
const w = (di ? fx : 1 - fx) * (dj ? fy : 1 - fy) * (dk ? fz : 1 - fz);
sx += w * X[p * 3]; sy += w * X[p * 3 + 1]; sz += w * X[p * 3 + 2]; sw += w;
}
if (sw < 1e-9) return out.set(x, y, z);
return out.set(sx / sw, sy / sw, sz / sw);
}
function poke(pt, dir, strength = 3.6) {
for (let p = 0; p < nP; p++) {
const j = p * 3;
const dx = X[j] - pt.x, dy = X[j + 1] - pt.y, dz = X[j + 2] - pt.z;
const d2 = dx * dx + dy * dy + dz * dz;
if (d2 < 0.36) {
const w = Math.exp(-d2 / 0.0625) * strength;
V[j] += dir.x * w; V[j + 1] += dir.y * w; V[j + 2] += dir.z * w;
}
}
}
function beginGrab(pt) {
grab.idx = []; grab.w = []; grab.p0 = [];
let best = -1, bd = 1e9;
for (let p = 0; p < nP; p++) {
const j = p * 3;
const dx = X[j] - pt.x, dy = X[j + 1] - pt.y, dz = X[j + 2] - pt.z;
const d2 = dx * dx + dy * dy + dz * dz;
if (d2 < bd) { bd = d2; best = p; }
if (d2 < 0.5) {
const w = Math.exp(-d2 / 0.09);
if (w > 0.02) { grab.idx.push(p); grab.w.push(w); grab.p0.push(X[j], X[j + 1], X[j + 2]); }
}
}
if (!grab.idx.length && best >= 0) { grab.idx.push(best); grab.w.push(1); grab.p0.push(X[best * 3], X[best * 3 + 1], X[best * 3 + 2]); }
grab.hit.copy(pt); grab.center.copy(pt);
const n = new THREE.Vector3(); camera.getWorldDirection(n);
grab.plane.setFromNormalAndCoplanarPoint(n, pt);
grab.delta.set(0, 0, 0);
grab.active = true; grab.dragging = false;
}
function setGrabDelta(d) { grab.delta.copy(d); if (grab.delta.length() > 0.75) grab.delta.setLength(0.75); grab.dragging = true; }
function releaseGrab() { grab.active = false; grab.dragging = false; }
// ---------------- jelly material (procedural citrus) ----------------
const vert = `
attribute vec3 aRest;
varying vec3 vRest; varying vec3 vW; varying vec3 vN;
void main(){
vRest = aRest;
vec4 w = modelMatrix * vec4(position, 1.0);
vW = w.xyz;
vN = normalize(mat3(modelMatrix) * normal);
gl_Position = projectionMatrix * viewMatrix * w;
}`;
const frag = `
uniform vec3 uL1; uniform vec3 uC1; uniform vec3 uL2; uniform vec3 uC2; uniform vec3 uL3; uniform vec3 uC3;
uniform float uBack;
varying vec3 vRest; varying vec3 vW; varying vec3 vN;
#define PI 3.14159265
#define RR 1.0
vec3 hash33(vec3 p3){ p3 = fract(p3 * vec3(.1031, .1030, .0973)); p3 += dot(p3, p3.yxz + 33.33); return fract((p3.xxy + p3.yxx) * p3.zyx); }
float hash13(vec3 p3){ p3 = fract(p3 * .1031); p3 += dot(p3, p3.zyx + 31.32); return fract((p3.x + p3.y) * p3.z); }
vec3 voro(vec3 x){
vec3 n = floor(x); vec3 f = fract(x);
float f1 = 8.0, f2 = 8.0, id = 0.0;
for (int k = -1; k <= 1; k++) for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
vec3 g = vec3(float(i), float(j), float(k));
vec3 o = hash33(n + g);
vec3 rr = g + 0.15 + 0.7 * o - f;
float d = dot(rr, rr);
if (d < f1) { f2 = f1; f1 = d; id = hash13(n + g); } else if (d < f2) { f2 = d; }
}
return vec3(sqrt(f1), sqrt(f2), id);
}
void lightUp(vec3 L, vec3 C, vec3 N, vec3 Ng, vec3 V, vec3 alb, vec3 sss, float thin, float transmit, float gm, inout vec3 col, inout vec3 spec){
float ndl = dot(N, L);
col += alb * C * max(0.0, (ndl + 0.3) / 1.3) * 0.8;
vec3 Lt = normalize(L + N * 0.4);
float tr = pow(max(0.0, dot(V, -Lt)), 2.5);
col += sss * alb * C * (tr * (0.5 + 2.2 * thin) + thin * 0.35 * max(0.0, -ndl)) * transmit;
vec3 H = normalize(L + V);
float nh = max(0.0, dot(N, H));
spec += C * (pow(nh, 260.0) * 3.0 + pow(nh, 48.0) * 0.12);
spec += C * pow(max(0.0, dot(Ng, H)), 420.0) * 2.2 * gm;
}
void main(){
vec3 N = normalize(vN);
if (!gl_FrontFacing) N = -N;
vec3 V = normalize(cameraPosition - vW);
vec2 uv = vRest.xz;
float r = length(uv);
float th = r > 1e-4 ? atan(max(uv.y, 0.0), uv.x) : 1.5708;
float y = vRest.y;
float segA = PI / 5.0;
float sth = th / segA + 0.5;
float si = floor(sth);
float sf = fract(sth) - 0.5;
float rPeel = RR - 0.072;
float rPith = rPeel - 0.04;
float segOuter = rPith - 0.055 * pow(abs(sf) * 2.0, 2.5);
float memD = (0.5 - abs(sf)) * segA * r;
float memW = 0.005 + 0.016 * (1.0 - smoothstep(0.0, 0.7, r));
float mem = 1.0 - smoothstep(memW, memW + 0.008, memD);
float core = 1.0 - smoothstep(0.045, 0.085, r);
float pith = max(smoothstep(segOuter - 0.006, segOuter + 0.004, r), core);
float peel = smoothstep(rPeel - 0.003, rPeel + 0.003, r);
float zest = smoothstep(RR - 0.024, RR - 0.012, r);
vec3 vc = vec3(0.35, 0.7, 0.5);
if (uBack < 0.5 && pith < 0.999) {
vec3 cp = vec3(r * 6.5 + si * 3.7, sf * segA * r * 25.0, y * 23.0 + si * 1.7);
vc = voro(cp);
}
float edge = vc.y - vc.x;
float cwall = 1.0 - smoothstep(0.02, 0.15, edge);
float ctr = 1.0 - smoothstep(0.0, 0.55, vc.x);
vec3 deep = vec3(0.90, 0.22, 0.010);
vec3 bright = vec3(1.0, 0.47, 0.035);
vec3 wallC = vec3(1.0, 0.64, 0.25);
vec3 alb = mix(deep, bright, clamp(ctr * 0.85 + (vc.z - 0.5) * 0.5, 0.0, 1.0));
alb = mix(alb, wallC, cwall * 0.5);
float alpha = 0.78;
alb = mix(alb, vec3(1.0, 0.80, 0.50), mem * 0.9);
alpha = mix(alpha, 0.86, mem);
alb = mix(alb, vec3(0.98, 0.90, 0.72), pith);
alpha = mix(alpha, 0.94, pith);
float gland = 1.0;
if (peel > 0.001 && uBack < 0.5) {
vec3 pv = voro(vec3(th * 40.0, y * 40.0, r * 40.0));
gland = 0.8 + 0.32 * smoothstep(0.05, 0.42, pv.x);
}
vec3 peelC = mix(vec3(1.0, 0.30, 0.010), vec3(0.80, 0.15, 0.004), zest * 0.7) * gland;
alb = mix(alb, peelC, peel);
alpha = mix(alpha, 0.98, peel);
float dEdge = max(0.0, min(RR - r, uv.y));
float thin = 1.0 - smoothstep(0.015, 0.2, dEdge);
float transmit = (1.0 - peel * 0.5) * (1.0 - pith * 0.35);
vec3 sss = vec3(1.0, 0.52, 0.09);
float gm = ctr * (1.0 - pith) * (1.0 - peel) * (1.0 - mem);
vec3 Ng = normalize(N + (hash33(vec3(vc.z * 97.0, vc.z * 13.0, 7.0)) - 0.5) * 0.5);
vec3 col = alb * vec3(0.30, 0.27, 0.25) * (0.75 + 0.25 * N.y);
vec3 spec = vec3(0.0);
lightUp(uL1, uC1, N, Ng, V, alb, sss, thin, transmit, gm, col, spec);
lightUp(uL2, uC2, N, Ng, V, alb, sss, thin, transmit, gm, col, spec);
lightUp(uL3, uC3, N, Ng, V, alb, sss, thin, transmit, gm, col, spec);
col += alb * sss * 0.13 * (1.0 - pith) * (1.0 - peel);
vec3 Rv = reflect(-V, N);
float ndv = max(dot(N, V), 0.0);
float fres = 0.035 + 0.965 * pow(1.0 - ndv, 5.0);
vec3 env = mix(vec3(0.42, 0.36, 0.30), vec3(1.0, 0.97, 0.93), smoothstep(-0.15, 0.6, Rv.y));
env += vec3(2.6) * smoothstep(0.90, 0.975, dot(Rv, normalize(vec3(-0.45, 0.8, 0.4))));
env += vec3(2.0) * smoothstep(0.93, 0.985, dot(Rv, normalize(vec3(-0.25, 0.6, -0.76))));
env += vec3(1.3) * smoothstep(0.92, 0.985, dot(Rv, normalize(vec3(0.7, 0.45, -0.55))));
float gloss = mix(1.0, 0.55, peel);
col += env * fres * gloss + spec * gloss;
alpha = clamp(alpha + fres * 0.5 + dot(spec, vec3(0.33)), 0.0, 1.0);
if (uBack > 0.5) {
vec3 bc = alb * vec3(0.22, 0.2, 0.18) + sss * alb * (0.25 + 0.6 * thin);
gl_FragColor = vec4(bc, 0.5);
} else {
gl_FragColor = vec4(col, alpha);
}
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`;
function makeJellyMat(isBack) {
const c1 = new THREE.Color(1.0, 0.95, 0.88).multiplyScalar(1.0);
const c2 = new THREE.Color(1.0, 0.86, 0.66).multiplyScalar(1.35);
const c3 = new THREE.Color(0.55, 0.6, 0.7).multiplyScalar(0.45);
return new THREE.ShaderMaterial({
vertexShader: vert, fragmentShader: frag,
uniforms: {
uL1: { value: keyPos.clone().normalize() }, uC1: { value: new THREE.Vector3(c1.r, c1.g, c1.b) },
uL2: { value: backPos.clone().normalize() }, uC2: { value: new THREE.Vector3(c2.r, c2.g, c2.b) },
uL3: { value: new THREE.Vector3(3, 1.2, 2).normalize() }, uC3: { value: new THREE.Vector3(c3.r, c3.g, c3.b) },
uBack: { value: isBack ? 1 : 0 }
},
transparent: true,
side: isBack ? THREE.BackSide : THREE.FrontSide,
depthWrite: !isBack
});
}
const jellyBack = new THREE.Mesh(geo, makeJellyMat(true));
jellyBack.renderOrder = 1; jellyBack.frustumCulled = false;
const jellyFront = new THREE.Mesh(geo, makeJellyMat(false));
jellyFront.renderOrder = 2; jellyFront.frustumCulled = false; jellyFront.castShadow = true;
scene.add(jellyBack, jellyFront);
function updateMesh() {
const pa = posArr;
for (let v = 0, o = 0; v < nV; v++) {
let x = 0, y = 0, z = 0;
for (let c = 0; c < 8; c++, o++) {
const w = skinW[o]; if (w === 0) continue;
const p = skinI[o] * 3;
x += w * X[p]; y += w * X[p + 1]; z += w * X[p + 2];
}
pa[v * 3] = x; pa[v * 3 + 1] = y; pa[v * 3 + 2] = z;
}
posAttr.needsUpdate = true;
geo.computeVertexNormals();
geo.computeBoundingSphere();
}
// ---------------- presser & juice ----------------
const glassMat = new THREE.MeshPhysicalMaterial({ color: 0xeef6ff, transparent: true, opacity: 0.3, roughness: 0.04, metalness: 0, clearcoat: 1, envMapIntensity: 1.6, depthWrite: false });
const rimMat = new THREE.MeshPhysicalMaterial({ color: 0xffffff, transparent: true, opacity: 0.6, roughness: 0.1, clearcoat: 1, envMapIntensity: 1.4, depthWrite: false });
const knobMat = new THREE.MeshPhysicalMaterial({ color: 0xfaf6f0, transparent: true, opacity: 1, roughness: 0.35, clearcoat: 0.6 });
const presser = new THREE.Group();
{
const disc = new THREE.Mesh(new THREE.CylinderGeometry(1.22, 1.22, 0.05, 72), glassMat);
disc.position.y = 0.025;
const rim = new THREE.Mesh(new THREE.TorusGeometry(1.22, 0.026, 10, 72), rimMat);
rim.rotation.x = Math.PI / 2; rim.position.y = 0.025;
const knob = new THREE.Mesh(new THREE.CylinderGeometry(0.12, 0.17, 0.38, 32), knobMat);
knob.position.y = 0.24;
const cap = new THREE.Mesh(new THREE.SphereGeometry(0.16, 24, 16), knobMat);
cap.position.y = 0.44;
presser.add(disc, rim, knob, cap);
presser.traverse(o => { o.renderOrder = 5; });
}
presser.visible = false;
scene.add(presser);
const juiceMat = new THREE.MeshPhysicalMaterial({ color: 0xff8a14, roughness: 0.04, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.03, transparent: true, opacity: 0.8, envMapIntensity: 1.3 });
const puddleMat = new THREE.MeshPhysicalMaterial({ color: 0xff8a14, roughness: 0.03, metalness: 0, clearcoat: 1, clearcoatRoughness: 0.02, transparent: true, opacity: 0.62, envMapIntensity: 1.3, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1 });
const dropGeo = new THREE.SphereGeometry(1, 22, 14);
const drops = [], puddles = [];
const tmpV = new THREE.Vector3();
function spawnDrop() {
const m = new THREE.Mesh(dropGeo, juiceMat);
m.renderOrder = 3;
m.scale.setScalar(0.001);
scene.add(m);
drops.push({ m, u: (Math.random() * 2 - 1) * 0.72, y: YWT - 0.02 - Math.random() * 0.07, phase: 0, t: 0, sp: 0, rad: 0.024 + Math.random() * 0.012, px: 0, pz: 0, vz: 0, pud: null });
}
function makePuddle(x, z) {
const m = new THREE.Mesh(dropGeo, puddleMat);
m.renderOrder = 0;
m.position.set(x, 0, z);
m.scale.set(0.001, 0.004, 0.001);
scene.add(m);
const p = { m, target: 0.07 + Math.random() * 0.05, ex: 0.85 + Math.random() * 0.3, r: 0 };
puddles.push(p);
while (puddles.length > 40) { const o = puddles.shift(); scene.remove(o.m); }
return p;
}
function clearJuice() {
for (const d of drops) scene.remove(d.m);
for (const p of puddles) scene.remove(p.m);
drops.length = 0; puddles.length = 0;
}
function updateDrops(dt) {
for (let i = drops.length - 1; i >= 0; i--) {
const d = drops[i];
d.t += dt;
if (d.phase < 2) {
if (d.phase === 0) { if (d.t > 0.45) d.phase = 1; }
else { d.sp = Math.min(0.5, d.sp + dt * 1.1); d.y -= d.sp * dt; }
deformPoint(d.u, Math.max(d.y, YWB), ZOFF, tmpV);
const g = d.phase === 0 ? Math.min(1, d.t / 0.4) : 1;
const s = d.rad * (0.3 + 0.7 * g);
d.m.position.set(tmpV.x, tmpV.y, tmpV.z + s * 0.6);
if (d.phase === 0) d.m.scale.set(s, s * 0.9, s * 0.8); else d.m.scale.set(s * 0.85, s * 1.35, s * 0.8);
if (d.phase === 1 && d.y <= YWB) {
d.phase = 2; d.t = 0; d.px = tmpV.x; d.pz = tmpV.z + s * 0.9; d.vz = d.sp + 0.15;
d.pud = makePuddle(d.px, d.pz);
}
} else {
d.pz += d.vz * dt; d.vz *= Math.exp(-3.5 * dt);
const k = Math.min(1, d.t / 0.6);
d.m.position.set(d.px, 0.004 + d.rad * 0.7 * (1 - k), d.pz);
d.m.scale.set(d.rad * (1 + k * 0.5), d.rad * (1 - k) * 0.9 + 0.004, d.rad * (1 + k * 0.8));
const p = d.pud;
p.r = p.target * sstep(0, 1, k * 1.1);
p.m.position.set(d.px, 0, d.pz - p.r * 0.2);
p.m.scale.set(Math.max(0.001, p.r * p.ex), 0.0065, Math.max(0.001, p.r * 1.25));
if (k >= 1) { scene.remove(d.m); drops.splice(i, 1); }
}
}
}
const SQ = { active: false, t: 0, cx: 0, cz: 0, next: 0 };
const SQ_DOWN = 0.9, SQ_HOLD = 2.6, SQ_END = 3.4, PTOP = 1.5, PMIN = TOPY * 0.56;
const SQ_DROPS = [0.75, 1.05, 1.4, 1.75, 2.15];
const easeIO = t => t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
function startSqueeze() {
if (SQ.active) return;
SQ.active = true; SQ.t = 0; SQ.next = 0;
const c = centroid();
SQ.cx = c.x; SQ.cz = c.z;
presser.visible = true;
btnSq.disabled = true;
}
function stopSqueeze() {
SQ.active = false; pressY = 99; presser.visible = false; btnSq.disabled = false;
}
function updateSqueeze(dt) {
let SyT = 1;
if (SQ.active) {
SQ.t += dt;
const t = SQ.t;
let y;
if (t < SQ_DOWN) y = PTOP + (PMIN - PTOP) * easeIO(t / SQ_DOWN);
else if (t < SQ_HOLD) y = PMIN - 0.03 * sstep(SQ_DOWN, SQ_HOLD, t);
else if (t < SQ_END) y = (PMIN - 0.03) + (PTOP - PMIN + 0.03) * easeIO((t - SQ_HOLD) / (SQ_END - SQ_HOLD));
else { stopSqueeze(); y = 99; }
if (SQ.active) {
pressY = y;
presser.position.set(SQ.cx, y - 0.012, SQ.cz);
const vis = Math.min(1, (PTOP - y) / 0.5 + 0.25);
glassMat.opacity = 0.3 * vis; rimMat.opacity = 0.6 * vis; knobMat.opacity = vis;
while (SQ.next < SQ_DROPS.length && t >= SQ_DROPS[SQ.next]) { spawnDrop(); SQ.next++; }
const cr = Math.min(1, Math.max(0.5, pressY / TOPY));
SyT = 1 - 0.75 * (1 - cr);
}
}
Sy += (SyT - Sy) * Math.min(1, dt * 12);
}
function centroid() {
let x = 0, y = 0, z = 0;
for (let p = 0; p < nP; p++) { x += X[p * 3]; y += X[p * 3 + 1]; z += X[p * 3 + 2]; }
return tmpC.set(x / nP, y / nP, z / nP);
}
const tmpC = new THREE.Vector3();
// ---------------- camera & view ----------------
let az = 0, el = 0.56, zoom = 1, baseDist = 4.4;
const target = new THREE.Vector3(0, 0.12, 0.05);
function onResize() {
const W = window.innerWidth, H = window.innerHeight;
renderer.setSize(W, H);
const a = W / H;
camera.aspect = a;
camera.fov = a < 0.8 ? 42 : 34;
const t = Math.tan(camera.fov * Math.PI / 360);
baseDist = Math.max(4.2, 1.6 / (t * a));
const ph = panel.offsetHeight + 24;
const off = Math.round(Math.max(0, ph - 56) * 0.5);
camera.setViewOffset(W, H, 0, off, W, H);
camera.updateProjectionMatrix();
}
window.addEventListener('resize', onResize);
function updateCamera() {
const d = baseDist * zoom;
camera.position.set(target.x + d * Math.sin(az) * Math.cos(el), target.y + d * Math.sin(el), target.z + d * Math.cos(az) * Math.cos(el));
camera.lookAt(target);
}
// ---------------- input ----------------
const raycaster = new THREE.Raycaster();
const ndc = new THREE.Vector2();
function setRay(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);
}
function pick(cx, cy) {
setRay(cx, cy);
const hits = raycaster.intersectObject(jellyFront, false);
return hits.length ? hits[0] : null;
}
const pointers = new Map();
let mode = null, activeId = null, downX = 0, downY = 0, lastX = 0, lastY = 0, pinchD0 = 1, zoom0 = 1;
let hintHidden = false;
function hideHint() { if (!hintHidden) { hintHidden = true; hintEl.style.opacity = '0'; } }
canvas.addEventListener('pointerdown', e => {
e.preventDefault();
try { canvas.setPointerCapture(e.pointerId); } catch (_) {}
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
hideHint();
if (pointers.size === 2) {
releaseGrab(); mode = 'pinch';
const [a, b] = [...pointers.values()];
pinchD0 = Math.max(10, Math.hypot(a.x - b.x, a.y - b.y)); zoom0 = zoom;
return;
}
if (pointers.size > 2) return;
activeId = e.pointerId;
downX = lastX = e.clientX; downY = lastY = e.clientY;
const hit = pick(e.clientX, e.clientY);
if (hit) {
mode = 'jelly';
const dir = raycaster.ray.direction.clone().normalize();
poke(hit.point, dir);
beginGrab(hit.point);
} else {
mode = 'orbit';
}
});
canvas.addEventListener('pointermove', e => {
if (!pointers.has(e.pointerId)) return;
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
if (mode === 'pinch' && pointers.size === 2) {
const [a, b] = [...pointers.values()];
const d = Math.max(10, Math.hypot(a.x - b.x, a.y - b.y));
zoom = Math.min(1.7, Math.max(0.55, zoom0 * pinchD0 / d));
return;
}
if (e.pointerId !== activeId) return;
if (mode === 'jelly' && grab.active) {
if (!grab.dragging && Math.hypot(e.clientX - downX, e.clientY - downY) < 6) return;
setRay(e.clientX, e.clientY);
const pt = new THREE.Vector3();
if (raycaster.ray.intersectPlane(grab.plane, pt)) setGrabDelta(pt.sub(grab.hit));
} else if (mode === 'orbit') {
const dx = e.clientX - lastX, dy = e.clientY - lastY;
az -= dx * 0.008;
el = Math.min(1.3, Math.max(0.2, el + dy * 0.006));
}
lastX = e.clientX; lastY = e.clientY;
});
function endPointer(e) {
if (!pointers.has(e.pointerId)) return;
pointers.delete(e.pointerId);
if (e.pointerId === activeId) { if (mode === 'jelly') releaseGrab(); activeId = null; }
if (pointers.size === 0) mode = null;
else if (mode === 'pinch' && pointers.size === 1) mode = null;
}
canvas.addEventListener('pointerup', endPointer);
canvas.addEventListener('pointercancel', endPointer);
canvas.addEventListener('lostpointercapture', endPointer);
canvas.addEventListener('wheel', e => { e.preventDefault(); zoom = Math.min(1.7, Math.max(0.55, zoom * Math.exp(e.deltaY * 0.001))); }, { passive: false });
canvas.addEventListener('contextmenu', e => e.preventDefault());
function firmLabel() {
valEl.textContent = firm < 0.33 ? 'Soft' : (firm < 0.67 ? 'Medium' : 'Firm');
}
function setFirm(f) { firm = Math.min(1, Math.max(0, f)); slider.value = String(Math.round(firm * 100)); firmLabel(); }
slider.addEventListener('input', () => { firm = Number(slider.value) / 100; firmLabel(); });
btnSq.addEventListener('click', () => { hideHint(); startSqueeze(); });
function resetAll() {
stopSqueeze(); Sy = 1; clearJuice(); resetJelly(0.18);
}
btnReset.addEventListener('click', () => { hideHint(); resetAll(); az = 0; el = 0.56; zoom = 1; });
// ---------------- demo mode ----------------
let demo = location.hash === '#demo';
let demoT = 0, demoIdx = 0, demoDrag = null, firmTween = null, fingerUntil = 0;
const DEMO_LEN = 20;
function restTop(u, v) { return new THREE.Vector3(u, yTop(u, v), ZOFF - v); }
function surfacePoint(u, v) { const r = restTop(u, v); return deformPoint(r.x, r.y, r.z, new THREE.Vector3()); }
function showFinger(pt, pressed) {
const p = pt.clone().project(camera);
finger.style.transform = `translate(${(p.x + 1) / 2 * window.innerWidth}px, ${(1 - p.y) / 2 * window.innerHeight}px) scale(${pressed ? 0.8 : 1})`;
finger.style.opacity = '1';
}
function demoPoke(u, v) {
const pt = surfacePoint(u, v);
const dir = pt.clone().sub(camera.position).normalize();
poke(pt, dir);
showFinger(pt, true);
fingerUntil = demoT + 0.35;
}
function demoDragStart(u, v, delta, dur) {
const pt = surfacePoint(u, v);
beginGrab(pt);
demoDrag = { start: demoT, dur, delta, pt };
}
function tweenFirm(to) { firmTween = { from: firm, to, t0: demoT, dur: 0.7 }; }
const demoScript = [
[0.0, () => { resetAll(); setFirm(0.5); }],
[1.6, () => demoPoke(-0.38, 0.32)],
[2.5, () => demoPoke(0.42, 0.28)],
[3.3, () => demoPoke(0.05, 0.62)],
[4.5, () => demoDragStart(0.0, 0.86, new THREE.Vector3(0, 0.42, -0.3), 1.4)],
[7.3, () => tweenFirm(0.12)],
[8.2, () => demoPoke(0.0, 0.35)],
[9.2, () => demoDragStart(0.78, 0.12, new THREE.Vector3(0.45, 0.22, 0.2), 1.2)],
[11.5, () => tweenFirm(0.5)],
[12.2, () => startSqueeze()],
[16.0, () => tweenFirm(0.9)],
[16.5, () => demoPoke(-0.3, 0.4)],
[17.3, () => demoPoke(0.35, 0.5)],
[18.6, () => tweenFirm(0.5)]
];
function updateDemo(dt) {
demoT += dt;
if (demoT >= DEMO_LEN) { demoT -= DEMO_LEN; demoIdx = 0; demoDrag = null; firmTween = null; }
while (demoIdx < demoScript.length && demoT >= demoScript[demoIdx][0]) { demoScript[demoIdx][1](); demoIdx++; }
if (demoDrag) {
const tau = demoT - demoDrag.start;
const k = easeIO(Math.min(1, tau / (demoDrag.dur * 0.75)));
const d = demoDrag.delta.clone().multiplyScalar(k);
setGrabDelta(d);
showFinger(demoDrag.pt.clone().add(d), true);
if (tau > demoDrag.dur) { releaseGrab(); demoDrag = null; finger.style.opacity = '0'; }
} else if (demoT > fingerUntil) {
finger.style.opacity = '0';
}
if (firmTween) {
const k = Math.min(1, (demoT - firmTween.t0) / firmTween.dur);
setFirm(firmTween.from + (firmTween.to - firmTween.from) * easeIO(k));
if (k >= 1) firmTween = null;
}
az = 0.38 * Math.sin(demoT / DEMO_LEN * Math.PI * 2);
el = 0.56 + 0.06 * Math.sin(demoT / DEMO_LEN * Math.PI * 4);
}
function stopDemo() {
if (!demo) return;
demo = false; badge.style.display = 'none'; finger.style.opacity = '0';
demoDrag = null; firmTween = null; releaseGrab();
}
if (demo) { badge.style.display = 'block'; hideHint(); }
const endDemoOnTouch = e => { if (e.isTrusted) stopDemo(); };
window.addEventListener('pointerdown', endDemoOnTouch, true);
window.addEventListener('touchstart', endDemoOnTouch, { capture: true, passive: true });
// ---------------- main loop ----------------
onResize();
setFirm(0.5);
resetJelly(0.18);
updateCamera();
updateMesh();
let last = performance.now(), acc = 0;
function frame(now) {
const dt = Math.min(0.05, Math.max(0, (now - last) / 1000));
last = now;
if (demo) updateDemo(dt);
updateSqueeze(dt);
acc += dt;
let n = 0;
while (acc >= DT && n < MAXSUB) { step(DT); acc -= DT; n++; }
if (n === MAXSUB) acc = 0;
if (!Number.isFinite(X[0]) || !Number.isFinite(X[X.length - 1])) resetJelly(0.1);
updateMesh();
updateDrops(dt);
const c = centroid();
aoMesh.position.set(c.x, 0.0015, c.z + 0.02);
glowMesh.position.set(c.x - 0.12, 0.002, c.z + 0.45);
updateCamera();
renderer.render(scene, camera);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
</body>
</html>
