Skip to content
VibeCodeBench
Back to the app

The code

Build a Cell, Part by Part 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.)28.0 KB · 695 lines · loads cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
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">
<title>3D Animal Cell</title>
<style>
  html, body { margin: 0; height: 100%; overflow: hidden; background: #070b14; color: #eaf6ff; font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
  #scene { position: fixed; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; outline: none; }
  #labels { position: fixed; inset: 0; pointer-events: none; overflow: hidden; }
  .tag { position: absolute; left: 0; top: 0; display: none; padding: 3px 9px; border-radius: 999px; font: 600 12px/1.2 system-ui, sans-serif; white-space: nowrap; background: rgba(5, 10, 20, .75); border: 1px solid rgba(160, 220, 255, .45); color: #eaf6ff; will-change: transform; }
  #top { position: fixed; top: 0; left: 0; right: 0; padding: 12px 14px 26px; background: linear-gradient(rgba(7, 11, 20, .88), rgba(7, 11, 20, 0)); pointer-events: none; }
  #top > * { pointer-events: auto; }
  h1 { margin: 0 0 8px; font-size: 20px; font-weight: 700; letter-spacing: .2px; }
  .row { display: flex; flex-wrap: wrap; gap: 8px; }
  button.big { min-height: 48px; min-width: 48px; padding: 0 16px; border-radius: 12px; border: 1px solid rgba(160, 220, 255, .35); background: #17304a; color: #eaf6ff; font: 600 16px system-ui, sans-serif; cursor: pointer; touch-action: manipulation; }
  button.big[aria-checked="true"] { background: #2fbf9b; border-color: #7ee8c7; color: #04140f; }
  button.big:active { transform: scale(.97); }
  #demoBadge { position: fixed; top: 12px; right: 14px; padding: 8px 12px; border-radius: 999px; background: rgba(255, 209, 102, .18); border: 1px solid #ffd166; color: #ffe9a8; font: 600 14px system-ui, sans-serif; }
  #demoBadge[hidden] { display: none; }
  #bottom { position: fixed; left: 0; right: 0; bottom: 0; padding: 26px 14px calc(14px + env(safe-area-inset-bottom)); background: linear-gradient(rgba(7, 11, 20, 0), rgba(7, 11, 20, .94)); pointer-events: none; }
  #bottom > * { pointer-events: auto; }
  #card { max-width: 560px; margin: 0 auto; padding: 12px 16px; border-radius: 16px; background: rgba(8, 14, 26, .88); border: 1px solid rgba(160, 220, 255, .22); }
  #cardCount { font-size: 13px; color: #7ee8c7; font-weight: 700; text-transform: uppercase; letter-spacing: .6px; }
  #cardName { margin: 4px 0; font-size: 20px; }
  #cardText { margin: 0; font-size: 16px; line-height: 1.45; }
  .scrubRow { max-width: 560px; margin: 10px auto 0; display: flex; align-items: center; gap: 10px; }
  .scrubRow span { font-size: 15px; white-space: nowrap; }
  #scrub { flex: 1; -webkit-appearance: none; appearance: none; height: 44px; background: transparent; margin: 0; }
  #scrub::-webkit-slider-runnable-track { height: 8px; border-radius: 4px; background: #29415e; }
  #scrub::-webkit-slider-thumb { -webkit-appearance: none; width: 32px; height: 32px; margin-top: -12px; border-radius: 50%; background: #7ee8c7; border: 3px solid #04140f; }
  #scrub::-moz-range-track { height: 8px; border-radius: 4px; background: #29415e; }
  #scrub::-moz-range-thumb { width: 28px; height: 28px; border-radius: 50%; background: #7ee8c7; border: 3px solid #04140f; }
  #status { max-width: 560px; margin: 8px auto 0; font-size: 14px; color: #b9d7ea; text-align: center; min-height: 1.2em; }
  @media (max-width: 480px) {
    h1 { font-size: 18px; }
    #cardName { font-size: 18px; }
    #cardText { font-size: 15px; }
    button.big { font-size: 15px; padding: 0 12px; }
  }
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D animal cell. Drag to turn, pinch or scroll to zoom, tap a part to read about it."></canvas>
<div id="labels" aria-hidden="true"></div>

<header id="top">
  <h1>Animal cell</h1>
  <div class="row">
    <button class="big" id="btnCut" role="switch" aria-checked="false">Cut open: off</button>
    <button class="big" id="btnRebuild">Rebuild</button>
    <button class="big" id="btnLabels" aria-checked="true">Labels: on</button>
  </div>
</header>

<div id="demoBadge" hidden>Demo: touch the cell to take over</div>

<footer id="bottom">
  <div id="card">
    <div id="cardCount"></div>
    <h2 id="cardName"></h2>
    <p id="cardText"></p>
  </div>
  <div class="scrubRow">
    <span>Build</span>
    <input id="scrub" type="range" min="0" max="1000" step="1" value="0" aria-label="Scrub through the build">
  </div>
  <p id="status"></p>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function () {
  'use strict';

  var statusEl = document.getElementById('status');
  if (typeof THREE === 'undefined') {
    statusEl.textContent = 'The 3D library did not load. Check your connection and reload the page.';
    return;
  }

  var canvas = document.getElementById('scene');
  var labelLayer = document.getElementById('labels');
  var demoBadge = document.getElementById('demoBadge');
  var cardCount = document.getElementById('cardCount');
  var cardName = document.getElementById('cardName');
  var cardText = document.getElementById('cardText');
  var scrub = document.getElementById('scrub');
  var btnCut = document.getElementById('btnCut');
  var btnRebuild = document.getElementById('btnRebuild');
  var btnLabels = document.getElementById('btnLabels');

  var renderer;
  try {
    renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
  } catch (err) {
    statusEl.textContent = 'This browser could not start 3D graphics.';
    return;
  }
  renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
  renderer.localClippingEnabled = true;
  renderer.setClearColor(0x070b14, 1);

  var scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2(0x070b14, 0.012);
  var camera = new THREE.PerspectiveCamera(45, 1, 0.1, 500);

  scene.add(new THREE.HemisphereLight(0xdff3ff, 0x101820, 0.9));
  var sun = new THREE.DirectionalLight(0xffffff, 0.8);
  sun.position.set(10, 14, 12);
  scene.add(sun);
  var glow = new THREE.PointLight(0x7ee8c7, 0.6, 60);
  glow.position.set(-12, -6, -8);
  scene.add(glow);

  // ---------- helpers ----------
  function clamp(v, a, b) { return v < a ? a : (v > b ? b : v); }
  function easeOutBack(t) {
    var c1 = 1.4, c3 = c1 + 1;
    return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);
  }
  function easeInOut(t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; }
  function makeRand(a) {
    return function () {
      a = (a + 0x6D2B79F5) | 0;
      var t = a;
      t = Math.imul(t ^ (t >>> 15), t | 1);
      t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
      return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
    };
  }
  var rand = makeRand(20261122); // fixed seed: the same cell every time
  function rr(a, b) { return a + (b - a) * rand(); }
  function randDir() {
    var u = rr(-1, 1), th = rr(0, Math.PI * 2), s = Math.sqrt(1 - u * u);
    return new THREE.Vector3(s * Math.cos(th), u, s * Math.sin(th));
  }

  var NUC = new THREE.Vector3(-0.6, 0.3, 0);
  var NUC_R = 2.9;
  var CELL_R = 9;
  // random spot inside maxR, outside the nucleus (plus a clearance)
  function spot(maxR, clear) {
    var p = null;
    for (var k = 0; k < 80; k++) {
      p = randDir().multiplyScalar(maxR * Math.cbrt(rand()));
      if (p.distanceTo(NUC) > NUC_R + clear) break;
    }
    return p;
  }

  // One shared clipping plane does the "Cut open" slice.
  // Clipped when x < -constant. constant 11 = nothing cut; 0 = half the cell removed.
  var CUT_START = 11;
  var cutPlane = new THREE.Plane(new THREE.Vector3(1, 0, 0), CUT_START);
  function mat(Kind, params) {
    var m = new Kind(params);
    m.clippingPlanes = [cutPlane];
    return m;
  }

  // ---------- membrane (starts alone, see-through) ----------
  var cell = new THREE.Group();
  scene.add(cell);
  var membrane = new THREE.Group();
  cell.add(membrane);
  membrane.add(new THREE.Mesh(
    new THREE.SphereGeometry(CELL_R, 40, 28),
    mat(THREE.MeshPhongMaterial, { color: 0x6fd6ff, transparent: true, opacity: 0.12, depthWrite: false, side: THREE.DoubleSide, shininess: 60 })
  ));
  membrane.add(new THREE.LineSegments(
    new THREE.WireframeGeometry(new THREE.SphereGeometry(CELL_R, 24, 16)),
    mat(THREE.LineBasicMaterial, { color: 0x9be9ff, transparent: true, opacity: 0.22 })
  ));

  // ---------- parts, in build order ----------
  var PARTS = [
    { id: 'nucleus', name: 'Nucleus', phase: 0.2, flyR: 11, dy: -18,
      text: "The control center: it keeps the cell's DNA safe inside a double-layered envelope.",
      build: function (p) {
        p.base.copy(NUC);
        p.group.add(new THREE.Mesh(new THREE.SphereGeometry(NUC_R, 36, 24),
          mat(THREE.MeshPhongMaterial, { color: 0x8e6cff, transparent: true, opacity: 0.5, depthWrite: false, shininess: 40 })));
        var poreMat = mat(THREE.MeshPhongMaterial, { color: 0xd9c9ff, emissive: 0x2a1a55 });
        for (var i = 0; i < 14; i++) {
          var pore = new THREE.Mesh(new THREE.SphereGeometry(0.16, 8, 6), poreMat);
          pore.position.copy(randDir().multiplyScalar(NUC_R));
          p.group.add(pore);
        }
      } },

    { id: 'nucleolus', name: 'Nucleolus', phase: 0.2, flyR: 6, dy: 14,
      text: 'A dense spot inside the nucleus where the parts of ribosomes are assembled.',
      build: function (p) {
        p.base.copy(NUC).add(new THREE.Vector3(0.6, 0.5, 0.4));
        p.group.add(new THREE.Mesh(new THREE.SphereGeometry(1.1, 24, 16),
          mat(THREE.MeshPhongMaterial, { color: 0x3b1f7a, emissive: 0x1a0b40, shininess: 20 })));
      } },

    { id: 'rough-er', name: 'Rough endoplasmic reticulum', phase: 1.4, flyR: 10, dy: 0,
      text: 'A folded network studded with ribosomes that helps build and fold new proteins.',
      build: function (p) {
        p.base.set(3.6, 0.2, -0.6);
        var ringMat = mat(THREE.MeshPhongMaterial, { color: 0xff8fb1, emissive: 0x3a0f1c, shininess: 30 });
        var dotMat = mat(THREE.MeshPhongMaterial, { color: 0xfff3c4 });
        var dotGeo = new THREE.SphereGeometry(0.13, 8, 6);
        for (var i = 0; i < 5; i++) {
          var R = rr(1.0, 1.5);
          var ring = new THREE.Mesh(new THREE.TorusGeometry(R, 0.13, 10, 40), ringMat);
          ring.position.set(rr(-1.5, 1.5), rr(-1, 1), rr(-1.2, 1.2));
          ring.rotation.set(rr(0, 3), rr(0, 3), rr(0, 3));
          for (var k = 0; k < 12; k++) {
            var a = k / 12 * Math.PI * 2;
            var dot = new THREE.Mesh(dotGeo, dotMat);
            dot.position.set(Math.cos(a) * R, Math.sin(a) * R, 0.1);
            ring.add(dot);
          }
          p.group.add(ring);
        }
      } },

    { id: 'smooth-er', name: 'Smooth endoplasmic reticulum', phase: 2.6, flyR: 12, dy: 0,
      text: 'A network of tubes with no ribosomes that makes fats and helps clean up harmful chemicals.',
      build: function (p) {
        var tubeMat = mat(THREE.MeshPhongMaterial, { color: 0xffd166, emissive: 0x2a2000, shininess: 30 });
        for (var i = 0; i < 6; i++) {
          var cur = new THREE.Vector3(rr(-6, -2.5), rr(-4, -0.5), rr(-2.5, 3));
          var pts = [];
          for (var k = 0; k < 5; k++) {
            pts.push(cur.clone());
            cur.add(new THREE.Vector3(rr(-1.4, 1.4), rr(-1.4, 1.4), rr(-1.4, 1.4)));
            if (cur.length() > 7) cur.setLength(7);
          }
          if (i === 0) p.focus = pts[2].clone();
          p.group.add(new THREE.Mesh(
            new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 40, 0.18, 8, false), tubeMat));
        }
      } },

    { id: 'ribosomes', name: 'Ribosomes', phase: 4.1, flyR: 15, dy: 0,
      text: 'Tiny protein factories that read a genetic message and link amino acids into chains.',
      build: function (p) {
        var inst = new THREE.InstancedMesh(new THREE.SphereGeometry(0.13, 8, 6),
          mat(THREE.MeshPhongMaterial, { color: 0xffe066, emissive: 0x2a2208 }), 240);
        var dummy = new THREE.Object3D();
        for (var i = 0; i < 240; i++) {
          dummy.position.copy(spot(7.2, 0.8));
          dummy.updateMatrix();
          inst.setMatrixAt(i, dummy.matrix);
        }
        inst.instanceMatrix.needsUpdate = true;
        p.group.add(inst);
      } },

    { id: 'golgi', name: 'Golgi apparatus', phase: 0.9, flyR: 9, dy: 0,
      text: "The cell's post office: it sorts, packages and ships proteins and fats.",
      build: function (p) {
        p.base.set(4.6, 2.4, -0.8);
        var m = mat(THREE.MeshPhongMaterial, { color: 0x7ef0a0, emissive: 0x0a2a14, shininess: 50 });
        for (var i = 0; i < 5; i++) {
          var arc = new THREE.Mesh(new THREE.TorusGeometry(1.2 - i * 0.12, 0.14, 8, 28, Math.PI * 1.3), m);
          arc.rotation.set(Math.PI / 2, 0, i * 0.35);
          arc.position.set(0, (i - 2) * 0.34, 0);
          p.group.add(arc);
        }
      } },

    { id: 'mito', name: 'Mitochondria', phase: 3.3, flyR: 10, dy: 0,
      text: 'The power plants: they turn food energy into ATP, the fuel the cell runs on.',
      build: function (p) {
        var outer = mat(THREE.MeshPhongMaterial, { color: 0xff7a59, emissive: 0x3a1408, shininess: 40 });
        var inner = mat(THREE.MeshPhongMaterial, { color: 0xffc2a8, emissive: 0x2a0c04 });
        for (var i = 0; i < 6; i++) {
          var mg = new THREE.Group();
          var body = new THREE.Mesh(new THREE.SphereGeometry(1, 20, 14), outer);
          body.scale.set(1.5, 0.75, 0.75);
          mg.add(body);
          var crista = new THREE.Mesh(new THREE.TorusGeometry(0.5, 0.07, 6, 20), inner);
          crista.rotation.y = Math.PI / 2;
          mg.add(crista);
          mg.position.copy(spot(7, 1.2));
          mg.rotation.set(rr(0, 3), rr(0, 3), rr(0, 3));
          p.group.add(mg);
          if (i === 0) p.focus = mg.position.clone();
        }
      } },

    { id: 'lysosomes', name: 'Lysosomes', phase: 5.0, flyR: 14, dy: 0,
      text: 'The recycling center: they break down old parts and waste with digestive enzymes.',
      build: function (p) {
        var m = mat(THREE.MeshPhongMaterial, { color: 0x9dff5c, emissive: 0x1c3a08, shininess: 30 });
        for (var i = 0; i < 9; i++) {
          var s = new THREE.Mesh(new THREE.SphereGeometry(rr(0.36, 0.5), 14, 10), m);
          s.position.copy(spot(7, 1));
          p.group.add(s);
          if (i === 0) p.focus = s.position.clone();
        }
      } },

    { id: 'vesicles', name: 'Vesicles', phase: 2.2, flyR: 12, dy: 0,
      text: 'Small bubbles that carry packages between parts of the cell and out through the membrane.',
      build: function (p) {
        var m = mat(THREE.MeshPhongMaterial, { color: 0x9ad8ff, transparent: true, opacity: 0.6, emissive: 0x0a2a3a, shininess: 80 });
        p.items = [];
        for (var i = 0; i < 12; i++) {
          var s = new THREE.Mesh(new THREE.SphereGeometry(rr(0.28, 0.38), 12, 9), m);
          p.group.add(s);
          p.items.push({ mesh: s, c: spot(6.2, 0.6), r: rr(1.2, 2.6), sp: rr(0.4, 0.9), ph: rr(0, 6.28) });
        }
        p.focus = p.items[0].c.clone();
      } },

    { id: 'centrioles', name: 'Centrioles', phase: 3.9, flyR: 6, dy: 0,
      text: 'A pair of tiny cylinders near the nucleus that help organize cell division.',
      build: function (p) {
        p.base.set(-4.4, 2.6, 2.0);
        var m = mat(THREE.MeshPhongMaterial, { color: 0xc0ffb0, emissive: 0x143010, shininess: 40 });
        var geo = new THREE.CylinderGeometry(0.2, 0.2, 1.6, 14);
        for (var i = 0; i < 2; i++) {
          var a = new THREE.Mesh(geo, m);
          a.position.set(i * 0.9, 0, 0);
          var b = new THREE.Mesh(geo, m);
          b.position.set(i * 0.9, 0, 0);
          b.rotation.x = Math.PI / 2;
          p.group.add(a);
          p.group.add(b);
        }
      } },

    { id: 'cytoskeleton', name: 'Cytoskeleton', phase: 6.0, flyR: 16, dy: 0,
      text: 'A scaffold of protein fibers that gives the cell its shape and helps it move things around.',
      build: function (p) {
        var m = mat(THREE.MeshPhongMaterial, { color: 0xe6ecff, transparent: true, opacity: 0.45, shininess: 10 });
        for (var i = 0; i < 16; i++) {
          var pts = [];
          for (var k = 0; k < 5; k++) pts.push(spot(7.4, 0));
          p.group.add(new THREE.Mesh(
            new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 48, 0.07, 6, false), m));
        }
        p.focus = new THREE.Vector3(0, 0, 0);
      } }
  ];

  var N = PARTS.length;
  var parts = [];
  var partById = {};
  var labelVec = new THREE.Vector3();
  PARTS.forEach(function (def) {
    var p = {
      def: def, idx: parts.length, phase: def.phase, flyR: def.flyR,
      group: new THREE.Group(), base: new THREE.Vector3(), offset: new THREE.Vector3(),
      focus: null, reveal: 0, items: null, label: document.createElement('div')
    };
    p.group.userData.partId = def.id;
    def.build(p);
    if (!p.focus) p.focus = p.base.clone();
    cell.add(p.group);
    p.label.className = 'tag';
    p.label.textContent = def.name;
    labelLayer.appendChild(p.label);
    parts.push(p);
    partById[def.id] = p;
  });

  // ---------- camera and state ----------
  var orbitTheta = -0.9, orbitPhi = 1.15;   // camera starts on the open (cut) side
  var target = new THREE.Vector3();
  var focusNow = new THREE.Vector3();
  var flyFrom = new THREE.Vector3();
  var flyT = 1;
  var followPart = null;
  var radius = 26, radiusGoal = 26, baseRadius = 26;
  var MIN_R = 5, MAX_R = 70;
  var progress = 0, autoBuild = true, clock = 0;
  var BUILD_SECONDS = 2.2;
  var cutT = 0, cutGoal = 0;
  var labelsOn = true;
  var cardKey = null;
  var demoOn = (location.hash === '#demo');
  var demoT = 0;
  var DEMO_LEN = 20;
  var demoFired = {};
  var DEMO_EVENTS = [
    { t: 0, id: 'loop-start', run: function () { target.set(0, 0, 0); followPart = null; flyT = 1; radiusGoal = baseRadius; } },
    { t: 8.5, id: 'mito', run: function () { selectPart(partById.mito); } },
    { t: 10.5, id: 'cut-on', run: function () { cutGoal = 1; refreshButtons(); } },
    { t: 14.0, id: 'cut-off', run: function () { cutGoal = 0; refreshButtons(); } },
    { t: 14.8, id: 'nucleus', run: function () { selectPart(partById.nucleus); } }
  ];

  function fitRadius() {
    var vTan = Math.tan(camera.fov * Math.PI / 360);
    var hTan = vTan * camera.aspect;
    return Math.min(MAX_R, 10.5 / Math.min(vTan, hTan));
  }

  function resize() {
    var w = window.innerWidth, h = window.innerHeight;
    renderer.setSize(w, h, false);
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
    baseRadius = Math.max(20, fitRadius());
  }

  // ---------- card and buttons ----------
  function showCard(i) {
    var d = PARTS[i];
    cardCount.textContent = 'Part ' + (i + 1) + ' of ' + N;
    cardName.textContent = d.name;
    cardText.textContent = d.text;
  }
  function showIntro() {
    cardCount.textContent = 'Start';
    cardName.textContent = 'An empty membrane';
    cardText.textContent = 'Every cell is wrapped in a thin, see-through skin called the membrane. Watch the parts fill in one at a time.';
  }
  function showDone() {
    cardCount.textContent = 'Complete';
    cardName.textContent = 'Explore your cell';
    cardText.textContent = 'Drag to turn it, pinch or scroll to zoom, and tap any part to fly to it and read what it does.';
  }
  function refreshButtons() {
    btnCut.textContent = 'Cut open: ' + (cutGoal ? 'on' : 'off');
    btnCut.setAttribute('aria-checked', cutGoal ? 'true' : 'false');
    btnLabels.textContent = 'Labels: ' + (labelsOn ? 'on' : 'off');
    btnLabels.setAttribute('aria-checked', labelsOn ? 'true' : 'false');
  }

  function stopDemo() {
    if (!demoOn) return;
    demoOn = false;
    demoBadge.hidden = true;
    followPart = null;
    flyT = 1;
    autoBuild = progress < N;
  }

  function selectPart(part) {
    followPart = part;
    flyFrom.copy(target);
    flyT = 0;
    radiusGoal = part.flyR;
    showCard(part.idx);
  }

  // ---------- picking ----------
  var raycaster = new THREE.Raycaster();
  var ndc = new THREE.Vector2();
  function ownerId(obj) {
    while (obj) {
      if (obj.userData && obj.userData.partId) return obj.userData.partId;
      obj = obj.parent;
    }
    return null;
  }
  function pickAt(clientX, clientY) {
    var rect = canvas.getBoundingClientRect();
    ndc.set(((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1);
    raycaster.setFromCamera(ndc, camera);
    var hits = raycaster.intersectObjects(cell.children, true);
    for (var i = 0; i < hits.length; i++) {
      if (cutPlane.distanceToPoint(hits[i].point) < 0) continue; // hidden behind the cut
      var id = ownerId(hits[i].object);
      if (!id) continue;
      var part = partById[id];
      if (part && part.reveal > 0.5) return part;
    }
    return null;
  }

  // ---------- touch and mouse ----------
  var pointers = new Map();
  var tap = null;
  var pinchDist = 0;
  function pinchDistance() {
    var pts = Array.from(pointers.values());
    return Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y);
  }

  canvas.addEventListener('pointerdown', function (e) {
    pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
    try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ }
    if (pointers.size === 1) {
      tap = { x: e.clientX, y: e.clientY, t: performance.now(), moved: false };
    } else {
      tap = null;
      pinchDist = pinchDistance();
    }
  });

  canvas.addEventListener('pointermove', function (e) {
    var prev = pointers.get(e.pointerId);
    if (!prev) return;
    pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
    if (pointers.size === 1) {
      if (tap && Math.hypot(e.clientX - tap.x, e.clientY - tap.y) > 10) {
        tap.moved = true;
        followPart = null;
        flyT = 1;
      }
      orbitTheta -= (e.clientX - prev.x) * 0.008;
      orbitPhi = clamp(orbitPhi - (e.clientY - prev.y) * 0.008, 0.2, Math.PI - 0.2);
    } else if (pointers.size === 2) {
      var d = pinchDistance();
      if (pinchDist > 0 && d > 0) radiusGoal = clamp(radiusGoal * pinchDist / d, MIN_R, MAX_R);
      pinchDist = d;
    }
  });

  function endPointer(e) {
    var wasOnlyOne = pointers.size === 1 && pointers.has(e.pointerId);
    var quick = tap && !tap.moved && (performance.now() - tap.t) < 400;
    pointers.delete(e.pointerId);
    if (e.type === 'pointerup' && wasOnlyOne && quick) {
      var part = pickAt(e.clientX, e.clientY);
      if (part) selectPart(part);
    }
    if (pointers.size === 0) tap = null;
    if (pointers.size < 2) pinchDist = 0;
  }
  canvas.addEventListener('pointerup', endPointer);
  canvas.addEventListener('pointercancel', endPointer);

  canvas.addEventListener('wheel', function (e) {
    e.preventDefault();
    radiusGoal = clamp(radiusGoal * (e.deltaY > 0 ? 1.12 : 0.89), MIN_R, MAX_R);
  }, { passive: false });
  canvas.addEventListener('touchmove', function (e) { e.preventDefault(); }, { passive: false });
  canvas.addEventListener('contextmenu', function (e) { e.preventDefault(); });

  // any real touch or click ends the demo
  window.addEventListener('pointerdown', stopDemo, true);
  window.addEventListener('touchstart', stopDemo, { capture: true, passive: true });

  // ---------- controls ----------
  btnCut.addEventListener('click', function () {
    stopDemo();
    cutGoal = cutGoal ? 0 : 1;
    refreshButtons();
  });
  btnLabels.addEventListener('click', function () {
    stopDemo();
    labelsOn = !labelsOn;
    refreshButtons();
  });
  btnRebuild.addEventListener('click', function () {
    stopDemo();
    followPart = null;
    flyT = 1;
    progress = 0;
    autoBuild = true;
    cardKey = null;
  });
  scrub.addEventListener('input', function () {
    stopDemo();
    autoBuild = false;
    progress = clamp(Number(scrub.value) / 1000 * N, 0, N);
  });

  // ---------- frame update ----------
  function update(dt) {
    clock += dt;

    if (demoOn) {
      demoT += dt;
      if (demoT >= DEMO_LEN) { demoT -= DEMO_LEN; demoFired = {}; }
      progress = N * Math.min(1, demoT / 7.5);
      for (var e = 0; e < DEMO_EVENTS.length; e++) {
        var ev = DEMO_EVENTS[e];
        if (!demoFired[ev.id] && demoT >= ev.t) {
          demoFired[ev.id] = true;
          ev.run();
        }
      }
      orbitTheta += dt * 0.2;
    } else if (autoBuild) {
      progress += dt / BUILD_SECONDS;
      if (progress >= N) { progress = N; autoBuild = false; }
    }

    cutT += (cutGoal - cutT) * Math.min(1, dt * 3);
    if (Math.abs(cutGoal - cutT) < 0.001) cutT = cutGoal;
    cutPlane.constant = CUT_START * (1 - cutT);

    membrane.scale.setScalar(1 + 0.008 * Math.sin(clock * 1.1));

    // parts: reveal, pop-in, pulse and gentle drift
    parts.forEach(function (p) {
      var r = clamp(progress - p.idx, 0, 1);
      p.reveal = r;
      p.offset.set(
        0.12 * Math.sin(clock * 0.7 + p.phase),
        0.12 * Math.sin(clock * 0.5 + p.phase * 1.3),
        0.12 * Math.cos(clock * 0.6 + p.phase));
      p.group.position.copy(p.base).add(p.offset);
      if (r <= 0.001) {
        p.group.visible = false;
        return;
      }
      p.group.visible = true;
      var pulse = 1 + 0.035 * Math.sin(clock * 2.2 + p.phase);
      p.group.scale.setScalar(Math.max(0.001, easeOutBack(r) * pulse));
      if (p.items) {
        p.items.forEach(function (it) {
          var a = clock * it.sp + it.ph;
          it.mesh.position.set(
            it.c.x + it.r * Math.cos(a),
            it.c.y + it.r * 0.4 * Math.sin(a * 1.3),
            it.c.z + it.r * Math.sin(a));
        });
      }
      if (p.def.id === 'cytoskeleton') p.group.rotation.y = clock * 0.03;
    });

    // card: intro, current part while building, or complete
    var key = progress < 0.02 ? 'intro'
      : (progress >= N ? 'done' : 'p' + Math.min(N - 1, Math.floor(progress)));
    if (key !== cardKey) {
      cardKey = key;
      if (key === 'intro') showIntro();
      else if (key === 'done') showDone();
      else showCard(Number(key.slice(1)));
    }

    // status line
    var built = Math.min(N, Math.floor(progress + 1e-6));
    var text;
    if (demoOn) text = 'Demo running. Touch anywhere to take over.';
    else if (progress < N) text = 'Built ' + built + ' of ' + N + ' parts. Let it build, or drag the slider to scrub.';
    else text = 'Complete. Drag to turn, pinch or scroll to zoom, and tap any part.';
    if (statusEl.textContent !== text) statusEl.textContent = text;

    // slider follows the build
    var sv = Math.round(progress / N * 1000);
    if (Number(scrub.value) !== sv) scrub.value = String(sv);

    // camera: follow a tapped part, or stay where the user left it
    if (followPart) {
      focusNow.copy(followPart.focus).add(followPart.offset);
      if (flyT < 1) {
        flyT = Math.min(1, flyT + dt / 1.3);
        target.lerpVectors(flyFrom, focusNow, easeInOut(flyT));
      } else {
        target.copy(focusNow);
      }
    }
    radius += (radiusGoal - radius) * Math.min(1, dt * 4);
    var sinP = Math.sin(orbitPhi);
    camera.position.set(
      target.x + radius * sinP * Math.sin(orbitTheta),
      target.y + radius * Math.cos(orbitPhi),
      target.z + radius * sinP * Math.cos(orbitTheta));
    camera.lookAt(target);
    camera.updateMatrixWorld();

    // floating labels for finished parts
    var W = window.innerWidth, H = window.innerHeight;
    parts.forEach(function (p) {
      var el = p.label;
      if (!labelsOn || p.reveal < 0.9) { el.style.display = 'none'; return; }
      labelVec.copy(p.focus).add(p.offset);
      if (cutPlane.distanceToPoint(labelVec) < 0) { el.style.display = 'none'; return; }
      labelVec.project(camera);
      if (labelVec.z > 1 || labelVec.z < -1) { el.style.display = 'none'; return; }
      var x = (labelVec.x * 0.5 + 0.5) * W;
      var y = (-labelVec.y * 0.5 + 0.5) * H + (p.def.dy || 0);
      el.style.display = 'block';
      el.style.transform = 'translate(' + x.toFixed(1) + 'px,' + y.toFixed(1) + 'px) translate(-50%, -50%)';
    });
  }

  // ---------- start ----------
  resize();
  radius = radiusGoal = baseRadius;
  window.addEventListener('resize', function () {
    resize();
    if (radiusGoal > MAX_R) radiusGoal = MAX_R;
  });
  refreshButtons();
  demoBadge.hidden = !demoOn;
  autoBuild = !demoOn;

  var last = performance.now();
  function frame(now) {
    var dt = Math.min(0.05, Math.max(0, (now - last) / 1000));
    last = now;
    update(dt);
    renderer.render(scene, camera);
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>