Skip to content
VibeCodeBench
Back to the app

The code

Build a Cell, Part by Part by GPT-6.2 Sol

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.)63.5 KB · 1,363 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.module.js
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#0a121b">
<link rel="icon" href="data:,">
<title>Cell Lab · Inside an animal cell</title>
<style>
:root {
  color-scheme: dark;
  --bg: #0a121b;
  --panel: #111d29;
  --line: #253847;
  --text: #eef5f8;
  --muted: #a2b6c3;
  --dim: #88a1af;
  --mint: #a5ebcd;
  --part: #77e1c8;
  --part-wash: #77e1c81a;
  font-family: "Aptos", "Segoe UI", system-ui, sans-serif;
}
* { box-sizing: border-box; }
body { margin: 0; color: var(--text); background: var(--bg); }
button, input { font: inherit; }
button { cursor: pointer; color: inherit; }
button:focus-visible, input:focus-visible { outline: 2px solid var(--mint); outline-offset: 4px; }
button, input { -webkit-tap-highlight-color: transparent; }
svg { display: block; flex: none; }
[hidden] { display: none !important; }
.wrap { width: min(1320px, calc(100% - 88px)); margin-inline: auto; }
.topbar { border-bottom: 1px solid #203140; background: #0c1620; }
.topbar .wrap { min-height: 64px; display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.brand { display: flex; align-items: center; gap: 11px; font-size: 1.08rem; font-weight: 700; letter-spacing: -.025em; }
.brand-mark { width: 34px; height: 34px; display: grid; place-items: center; border: 1px solid #366352; border-radius: 10px; color: var(--mint); background: #172e2e; }
.quiet { min-height: 42px; display: inline-flex; align-items: center; gap: 8px; padding: 0 9px; border: 0; border-radius: 8px; background: transparent; color: var(--muted); font-size: .86rem; font-weight: 600; }
.quiet:hover { background: #172633; color: var(--text); }
main { padding-block: 30px 34px; }
.intro { display: flex; align-items: flex-end; justify-content: space-between; gap: 24px; margin-bottom: 23px; }
h1 { margin: 0; font-size: clamp(2.25rem, 4.2vw, 3.65rem); font-weight: 690; line-height: 1.02; letter-spacing: -.059em; }
.intro p { margin: 10px 0 0; color: var(--muted); font-size: clamp(.95rem, 1.4vw, 1.07rem); }
.actions { display: flex; gap: 9px; flex: none; padding-bottom: 2px; }
.action { min-height: 46px; display: inline-flex; align-items: center; justify-content: center; gap: 10px; padding: 0 15px; border: 1px solid #304452; border-radius: 10px; background: #14222e; font-size: .91rem; font-weight: 650; white-space: nowrap; transition: background .18s, border-color .18s; }
.action:hover { border-color: #62858a; background: #1d303c; }
.action.primary { border-color: var(--mint); background: var(--mint); color: #102c27; }
.action.primary:hover { background: #c5f7e1; }
.toggle { width: 33px; height: 19px; border: 1px solid #59717d; border-radius: 20px; background: #243947; position: relative; transition: background .18s; }
.toggle::before { content: ""; position: absolute; left: 3px; top: 3px; width: 11px; height: 11px; border-radius: 50%; background: #c9d9e2; transition: transform .2s, background .2s; }
[aria-checked="true"] .toggle { border-color: var(--mint); background: var(--mint); }
[aria-checked="true"] .toggle::before { transform: translateX(14px); background: #183b33; }
.layout { display: grid; grid-template-columns: minmax(0, 1fr) 322px; gap: 16px; align-items: stretch; }
.main-column { min-width: 0; }
.stage, .timeline, .sidebar { border: 1px solid var(--line); border-radius: 17px; }
.stage {
  height: clamp(479px, 59vh, 580px);
  position: relative;
  isolation: isolate;
  overflow: hidden;
  touch-action: none;
  user-select: none;
  background:
    radial-gradient(ellipse at 51% 47%, #193642cf 0%, #102336d9 40%, #0b1723 78%),
    #0d1b28;
}
.stage::before {
  content: ""; position: absolute; inset: 0; pointer-events: none;
  background: radial-gradient(circle, #90bfc658 1px, transparent 1.15px) center / 23px 23px;
  mask-image: radial-gradient(ellipse, #0009, #0003 68%, transparent);
}
.stage::after {
  content: ""; position: absolute; inset: 58px 17px 56px; pointer-events: none;
  background:
    linear-gradient(#6b9aaa80,#6b9aaa80) top left / 12px 1px,
    linear-gradient(#6b9aaa80,#6b9aaa80) top left / 1px 12px,
    linear-gradient(#6b9aaa80,#6b9aaa80) top right / 12px 1px,
    linear-gradient(#6b9aaa80,#6b9aaa80) top right / 1px 12px,
    linear-gradient(#6b9aaa80,#6b9aaa80) bottom left / 12px 1px,
    linear-gradient(#6b9aaa80,#6b9aaa80) bottom left / 1px 12px,
    linear-gradient(#6b9aaa80,#6b9aaa80) bottom right / 12px 1px,
    linear-gradient(#6b9aaa80,#6b9aaa80) bottom right / 1px 12px;
  background-repeat: no-repeat;
  opacity: .55;
}
.model { position: absolute; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; touch-action: none; }
.stage.dragging .model { cursor: grabbing; }
.stage-ui { position: absolute; z-index: 3; }
.status { top: 16px; left: 17px; display: flex; align-items: center; gap: 8px; padding: 7px 10px; border: 1px solid #34505d; border-radius: 7px; color: #c0d4da; background: #101d29da; font-size: .74rem; font-weight: 650; letter-spacing: .015em; pointer-events: none; }
.status i { width: 7px; height: 7px; border-radius: 50%; background: var(--mint); box-shadow: 0 0 8px #a5ebcd65; }
.status.paused i { background: #a0adbb; box-shadow: none; }
.hint { left: 17px; bottom: 16px; display: flex; align-items: center; gap: 7px; pointer-events: none; color: #a6bdc9; font-size: .76rem; }
.hint svg { color: #83a8b3; }
.touch-hint { display: none; }
.zoom { right: 16px; bottom: 14px; display: flex; gap: 3px; padding: 3px; border: 1px solid #344b5c; border-radius: 10px; background: #12222edb; }
.zoom button { width: 39px; height: 39px; border: 0; border-radius: 6px; background: transparent; display: grid; place-items: center; color: #e2eef1; }
.zoom button + button { box-shadow: -1px 0 0 #2c414f; }
.zoom button:hover { background: #243b48; color: var(--mint); }
.annotation { position: absolute; z-index: 2; inset: 0; pointer-events: none; }
.anchor { position: absolute; width: 12px; height: 12px; border: 2px solid var(--part); border-radius: 50%; background: #102131; transform: translate(-50%, -50%); box-shadow: 0 0 0 4px var(--part-wash), 0 0 14px var(--part); z-index: 1; }
.leader { position: absolute; height: 1px; background: var(--part); opacity: .7; transform-origin: left center; }
.tag { position: absolute; display: flex; align-items: center; gap: 7px; padding: 7px 10px; border: 1px solid #405666; border-radius: 7px; background: #0d1926ed; box-shadow: 0 5px 20px #050c1690; color: #e9f3f6; font-size: .76rem; font-weight: 650; white-space: nowrap; }
.tag i { width: 6px; height: 6px; flex: none; border-radius: 100%; background: var(--part); }
.timeline { margin-top: 13px; padding: 12px 16px; min-height: 88px; display: flex; gap: 14px; align-items: center; background: var(--panel); }
.play { width: 46px; height: 46px; display: grid; place-items: center; flex: none; border: 0; border-radius: 11px; background: var(--mint); color: #13342e; }
.play:hover { background: #ccf8e4; }
.timeline-content { flex: 1; min-width: 0; }
.timeline-meta, .ends { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
.timeline-meta label { font-size: .9rem; font-weight: 650; }
.timeline-meta span { color: var(--mint); font-size: .77rem; font-weight: 650; font-variant-numeric: tabular-nums; }
.ends { font-size: .72rem; color: var(--dim); }
#scrub { --fill: 0%; display: block; appearance: none; width: 100%; height: 26px; margin: 0; cursor: pointer; background: transparent; touch-action: none; }
#scrub::-webkit-slider-runnable-track { height: 5px; border-radius: 10px; background: linear-gradient(to right, var(--mint) var(--fill), #344858 var(--fill)); }
#scrub::-webkit-slider-thumb { appearance: none; width: 16px; height: 16px; border: 3px solid #d6fbeb; border-radius: 50%; background: #5fae95; margin-top: -5.5px; }
#scrub::-moz-range-track { height: 5px; border-radius: 10px; background: #344858; }
#scrub::-moz-range-progress { height: 5px; border-radius: 10px; background: var(--mint); }
#scrub::-moz-range-thumb { width: 10px; height: 10px; border: 3px solid #d6fbeb; border-radius: 50%; background: #5fae95; }
.sidebar { overflow: hidden; background: var(--panel); }
.detail { min-height: 160px; display: grid; grid-template-columns: 43px minmax(0, 1fr); align-items: start; gap: 12px; padding: 20px 17px 18px; border-bottom: 1px solid var(--line); background: radial-gradient(ellipse at 0% 0%, var(--part-wash), transparent 75%), #142230; }
.detail-icon { width: 43px; height: 43px; display: grid; place-items: center; color: var(--part); background: var(--part-wash); border: 1px solid color-mix(in srgb, var(--part) 34%, #273947); border-radius: 10px; }
.detail-kicker { margin: 0 0 4px; color: var(--part); font-size: .67rem; font-weight: 700; letter-spacing: .11em; text-transform: uppercase; }
.detail h2 { margin: 0; font-size: 1.24rem; line-height: 1.1; letter-spacing: -.035em; }
.detail p:last-child { margin: 8px 0 0; color: #b8cad4; font-size: .88rem; line-height: 1.42; }
.list-area { padding: 12px 10px 12px; }
.list-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 0 7px 7px; min-height: 35px; }
.list-head h2 { margin: 0; font-size: .91rem; font-weight: 700; letter-spacing: -.015em; }
.list-head span { color: var(--dim); font-size: .74rem; font-variant-numeric: tabular-nums; }
.parts { list-style: none; padding: 0; margin: 0; }
.part-row { width: 100%; min-height: 38px; display: flex; gap: 9px; align-items: center; padding: 5px 7px; border: 1px solid transparent; border-radius: 7px; color: #9db1bf; background: transparent; text-align: left; font-size: .83rem; line-height: 1.15; }
.part-row:hover { background: #1a2b39; color: var(--text); }
.part-row.built { color: #d2e0e7; }
.part-row[aria-current="true"] { color: #f2f8fb; background: var(--row-wash); border-color: color-mix(in srgb, var(--row-color) 23%, #293d4a); }
.row-icon { display: grid; place-items: center; width: 23px; height: 23px; flex: none; border-radius: 6px; color: var(--row-color); background: var(--row-wash); }
.part-row:not(.built) .row-icon { opacity: .66; }
.row-arrow { color: var(--row-color); margin-left: auto; opacity: 0; }
.part-row:hover .row-arrow, .part-row[aria-current="true"] .row-arrow { opacity: 1; }
@media (pointer: coarse) {
  .desktop-hint { display: none; }
  .touch-hint { display: inline; }
  .part-row { min-height: 44px; }
  .zoom button { width: 43px; height: 43px; }
}
@media (max-width: 1000px) {
  .wrap { width: calc(100% - 48px); }
  .layout { grid-template-columns: minmax(0, 1fr) 285px; gap: 13px; }
}
@media (max-width: 760px) {
  .wrap { width: calc(100% - 28px); }
  .topbar .wrap { min-height: 55px; }
  main { padding-block: 21px 24px; }
  .intro { align-items: flex-start; flex-direction: column; gap: 14px; margin-bottom: 13px; }
  .actions { padding-bottom: 0; }
  .layout { grid-template-columns: minmax(0, 1fr); }
  .stage { height: clamp(292px, 88vw, 478px); }
  .status { left: 11px; top: 11px; }
  .stage::after { inset: 49px 11px 55px; }
  .hint { left: 10px; bottom: 19px; gap: 5px; font-size: .69rem; }
  .zoom { right: 9px; bottom: 9px; }
  .timeline { margin-top: 10px; padding-inline: 11px; gap: 11px; }
  .detail { min-height: 110px; }
  .part-row { min-height: 44px; }
}
@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after { transition-duration: .01ms !important; }
}
</style>
</head>
<body>
<header class="topbar">
  <div class="wrap">
    <div class="brand"><span class="brand-mark" data-icon="cell"></span><span>Cell Lab</span></div>
    <button id="reset" class="quiet" type="button"><span data-icon="target"></span>Reset view</button>
  </div>
</header>
<main class="wrap">
  <div class="intro">
    <div>
      <h1>Inside an animal cell</h1>
      <p>Watch a living cell take shape, one part at a time.</p>
    </div>
    <div class="actions">
      <button class="action" id="cut" type="button" role="switch" aria-checked="false"><span class="toggle" aria-hidden="true"></span>Cut open</button>
      <button class="action primary" id="rebuild" type="button"><span data-icon="rebuild"></span>Rebuild</button>
    </div>
  </div>
  <div class="layout">
    <div class="main-column">
      <div class="stage" id="stage" role="region" aria-label="Interactive 3D animal cell">
        <canvas class="model" id="preview" aria-hidden="true"></canvas>
        <div class="stage-ui status" id="status"><i aria-hidden="true"></i><span id="statusText">Building cell</span></div>
        <div class="annotation" id="annotation" aria-hidden="true">
          <div class="leader" id="leader"></div><div class="anchor" id="anchor"></div><div class="tag" id="tag"><i></i><span id="tagText">Cell membrane</span></div>
        </div>
        <div class="stage-ui hint"><span data-icon="gesture"></span><span class="desktop-hint">Drag to orbit · Scroll to zoom</span><span class="touch-hint">Drag to orbit · Pinch to zoom</span></div>
        <div class="stage-ui zoom">
          <button id="zoomIn" type="button" aria-label="Zoom in" data-icon="plus"></button>
          <button id="zoomOut" type="button" aria-label="Zoom out" data-icon="minus"></button>
        </div>
      </div>
      <div class="timeline">
        <button id="play" class="play" type="button" aria-label="Pause build"></button>
        <div class="timeline-content">
          <div class="timeline-meta"><label for="scrub">Build timeline</label><span id="counter">0 / 11 parts</span></div>
          <input id="scrub" type="range" min="0" max="11" value="0" step="1">
          <div class="ends" aria-hidden="true"><span>Membrane</span><span>Fully built</span></div>
        </div>
      </div>
    </div>
    <aside class="sidebar" aria-label="Cell part guide">
      <div class="detail">
        <div class="detail-icon" id="detailIcon"></div>
        <div aria-live="polite" aria-atomic="true">
          <p class="detail-kicker" id="detailKicker">Cell boundary</p>
          <h2 id="detailName">Cell membrane</h2>
          <p id="detailText">This thin skin controls what goes in and out of the cell.</p>
        </div>
      </div>
      <div class="list-area">
        <div class="list-head"><h2>Cell parts</h2><span id="tally">0 of 11 built</span></div>
        <ol class="parts" id="parts"></ol>
      </div>
    </aside>
  </div>
</main>
<script type="x-shader/x-vertex" id="shellVertex">
uniform float clockTime;
uniform float pulse;
varying vec3 worldPoint;
varying vec3 surface;
varying vec3 viewNormal;
varying vec3 toEye;
void main() {
  vec3 p = position * (1.0 + pulse * sin(clockTime * 1.42 + position.x * 2.3 + position.y));
  vec4 eyePoint = modelViewMatrix * vec4(p, 1.0);
  worldPoint = (modelMatrix * vec4(p, 1.0)).xyz;
  surface = p;
  viewNormal = normalize(normalMatrix * normal);
  toEye = -eyePoint.xyz;
  gl_Position = projectionMatrix * eyePoint;
}
</script>
<script type="x-shader/x-fragment" id="shellFragment">
uniform vec3 tint;
uniform float baseOpacity;
uniform float rimOpacity;
uniform float slice;
uniform float clockTime;
varying vec3 worldPoint;
varying vec3 surface;
varying vec3 viewNormal;
varying vec3 toEye;
void main() {
  if (worldPoint.z > slice) discard;
  vec3 n = normalize(viewNormal);
  float angle = abs(dot(n, normalize(toEye)));
  float edge = pow(1.0 - angle, 2.15);
  float lip = pow(1.0 - angle, 6.0);
  vec3 spots = sin(surface * 19.0 + vec3(surface.y, surface.z, surface.x) * 3.0);
  float pores = pow(abs(spots.x * spots.y * spots.z), 10.0);
  float ripples = 0.5 + 0.5 * sin(surface.y * 6.0 + surface.x * 3.0 + sin(surface.z * 4.0) + clockTime * 0.52);
  vec3 color = tint * (0.16 + 0.67 * edge + 0.21 * ripples) + lip * vec3(0.18, 0.30, 0.28);
  color += pores * tint * 0.32;
  gl_FragColor = vec4(color, baseOpacity + edge * rimOpacity + pores * 0.105);
  #include <tonemapping_fragment>
  #include <colorspace_fragment>
}
</script>
<script>
(() => {
  "use strict";

  const $ = id => document.getElementById(id);
  const stage = $("stage");
  const preview = $("preview");
  const ctx = preview.getContext("2d");
  const rows = [];
  const paths = {
    cell: '<path d="M20.8 11.4c.6 4.8-3.1 8.7-8.4 8.9-5.6.2-9.5-3-9.3-7.9C3.3 7.4 7 4.5 11.8 4c4.9-.6 8.4 2.3 9 7.4Z"/><circle cx="12" cy="12" r="3.3"/><path d="M6.4 13.7h.1M16.8 8.8h.1M16.4 15.9h.1"/>',
    target: '<circle cx="12" cy="12" r="6.5"/><path d="M12 2v4M12 18v4M2 12h4M18 12h4"/><circle cx="12" cy="12" r="1.5"/>',
    rebuild: '<path d="M4 10a8 8 0 1 1 1.5 6.7M4 4v6h6"/>',
    plus: '<path d="M5 12h14M12 5v14"/>',
    minus: '<path d="M5 12h14"/>',
    gesture: '<rect x="6" y="3" width="12" height="18" rx="6"/><path d="M12 7v3"/>',
    arrow: '<path d="m9 5 7 7-7 7"/>',
    play: '<path fill="currentColor" stroke="none" d="M8 5.3a.7.7 0 0 0-1 .6v12.2a.7.7 0 0 0 1 .6l10-6.1a.7.7 0 0 0 0-1.2Z"/>',
    pause: '<path stroke-width="3.2" d="M9 6v12M15 6v12"/>',
    nucleus: '<circle cx="12" cy="12" r="8.1"/><circle cx="12.4" cy="12" r="3.3"/><path d="M7.4 9.4h.1M15.8 16h.1M9 17h.1"/>',
    nucleolus: '<path d="M20 11.7c0 4.5-3.8 8-8.2 8S4 16.3 4 11.9 7.6 4 12.2 4c4.1 0 7.8 3.3 7.8 7.7Z"/><path d="M8.5 10.1h.1M12.9 7.9h.1M14.8 12.7h.1M10.5 15h.1"/>',
    rough: '<path d="M4 6c4.5 0 5.2 3.7 10.4 3 2.3-.3 3.6-1.4 5.6-2.4M4 11c4.5 0 5.2 3.7 10.4 3 2.3-.3 3.6-1.4 5.6-2.4M4 16c4.5 0 5.2 3.7 10.4 3 2.3-.3 3.6-1.4 5.6-2.4"/><path d="M9 5h.1M14 6h.1M18 4h.1"/>',
    smooth: '<path d="M4 16c4 0 3.3-8 7.2-8 3 0 1.9 6 4.3 6 2 0 2.2-3 4.5-3M5 7c5 0 3.8 12 8.4 12 3.2 0 2.2-3.1 6.6-3.1M12 8l2-4h5"/>',
    ribosome: '<circle cx="8" cy="7" r="2.6"/><circle cx="16" cy="10" r="2.6"/><circle cx="9.9" cy="16.8" r="2.7"/><path d="M18 17h.1M5 12.5h.1"/>',
    golgi: '<path d="M4 6c4.4 4.6 11.5 5 16 1M4 10c4.7 4.8 11 5.2 15.6 1.4M5 14.5c3.9 4 9.5 4.5 13.9 1.3M7 19c3 2 6.4 2.3 9.8.9"/>',
    mito: '<path d="M5 16.5c-2.9-2.2-2.7-5.7.5-7.6C8.8 7 13.4 6.7 17 5.8c3.4-.8 4.9 1.6 3.4 4.1-2.7 4.6-10.7 10-15.4 6.6Z"/><path d="M6.5 13.2c2 3 2.1-3.4 4.2-2.6 1.6.7.7 3.2 2.4 2.2 1.6-.8.9-3.3 3-3.5"/>',
    lyso: '<circle cx="12" cy="12" r="7.7"/><path d="M8 11h.1M10 15.5h.1M13.3 8.8h.1M15.5 13.4h.1"/>',
    vesicle: '<circle cx="9" cy="13.5" r="5.5"/><circle cx="17.4" cy="7.2" r="3.3"/><path d="M17.8 17h.1"/>',
    centriole: '<path d="m4 6 7-2 2 8-7 2-2-8Zm6 10 8-5 3 5-8 5-3-5Z"/><path d="m7 5.3 2 8m3.8 1 3 5m-.2-7 3 5"/>',
    skeleton: '<path d="m4 5 7 4 8-4M11 9l2 6 7 3M13 15l-7 5m-2-8 7-3m2 6 6-4M6 20l-2-8"/>'
  };

  function icon(name, size = 19) {
    return '<svg aria-hidden="true" width="' + size + '" height="' + size + '" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round">' + paths[name] + '</svg>';
  }

  const parts = [
    { name: "Cell membrane", mark: "cell", color: "#77e1c8", home: [-2.42, 1.34, .38], text: "This thin skin controls what goes in and out of the cell." },
    { name: "Nucleus", mark: "nucleus", color: "#b39cff", home: [-.47, .19, -.38], tip: [-.32, .43, .39], text: "It holds DNA, the instructions that tell the cell how to work." },
    { name: "Nucleolus", mark: "nucleolus", color: "#f58acc", home: [-.31, .28, .09], tip: [0, 0, .19], text: "It makes the pieces that snap together to form ribosomes." },
    { name: "Rough endoplasmic reticulum", mark: "rough", color: "#a9a6ff", home: [-1.64, .22, -.19], tip: [-.62, .43, .12], text: "Its ribosomes make proteins that it helps fold and move." },
    { name: "Smooth endoplasmic reticulum", mark: "smooth", color: "#64e5c7", home: [.98, 1.01, -.36], tip: [.23, .09, .15], text: "It makes fats for the cell and helps break down harmful chemicals." },
    { name: "Ribosomes", mark: "ribosome", color: "#f6ae81", home: [.01, -.98, .02], text: "They put small building blocks together to make proteins." },
    { name: "Golgi apparatus", mark: "golgi", color: "#ff91af", home: [1.39, -.27, -.34], tip: [.17, .06, .25], text: "It sorts and packages proteins and fats for delivery." },
    { name: "Mitochondria", mark: "mito", color: "#ffc17b", home: [-1.62, -1.19, -.12], tip: [.12, .02, .20], text: "They turn energy from food into a form the cell can use." },
    { name: "Lysosomes", mark: "lyso", color: "#c5ec81", home: [2.38, -.62, -.23], tip: [0, 0, .14], text: "They break down waste and recycle worn-out cell parts." },
    { name: "Vesicles", mark: "vesicle", color: "#81d9ff", home: [2.26, .16, .04], text: "These tiny bubbles carry materials from one place to another." },
    { name: "Centrioles", mark: "centriole", color: "#f6dc79", home: [.48, -.67, .02], tip: [.14, 0, .07], text: "They help organize the fibers that pull chromosomes apart when a cell divides." },
    { name: "Cytoskeleton", mark: "skeleton", color: "#78d9bc", home: [0, 0, 0], tip: [2.12, 1.11, -.21], text: "A network of fibers holds the cell's shape and helps things move inside it." }
  ];
  const last = parts.length - 1;
  const mitochondria = [[...parts[7].home, -.33, 1], [2.15, .86, -.21, .68, .91], [1.04, -1.42, -.22, .31, .82]];
  const lysosomes = [[...parts[8].home, .235], [-2.05, 1.22, -.28, .22], [-.14, -1.58, -.31, .195], [-2.53, -.47, -.37, .15]];
  const vesicles = [[...parts[9].home, .15], [1.88, .40, .21, .11], [2.49, .29, -.20, .10], [1.94, -.84, .21, .135], [2.63, .61, -.27, .093], [-1.53, 1.62, -.31, .116], [.43, 1.79, -.53, .123], [.97, -.91, .76, .125]];
  const ribosomeClusters = [parts[5].home, [-1.08, -.70, .56], [2.34, 1.16, -.28], [-2.26, .29, -.39], [.01, 1.43, -.62], [1.53, -1.43, -.47], [-1.12, .53, -.98]];
  const sliceZ = .16;
  const fov = 38;
  const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
  const startCamera = { yaw: -.16, pitch: .13, zoom: 1, x: 0, y: .04, z: 0 };
  const camera = { ...startCamera };
  const goal = { ...startCamera };
  const levels = Array(parts.length).fill(0);
  const pointers = new Map();
  const clamp = (x, low, high) => Math.min(high, Math.max(low, x));
  const mix = (a, b, t) => a + (b - a) * t;
  let width = 1, height = 1, pixelRatio = 1;
  let slice = 3.6, built = 0, selected = 0, playing = true, cut = false;
  let now = performance.now(), nextStep = now + 980, tap = null;
  let demoStart = location.hash === "#demo" ? now : null;
  let demoPhase = 0;
  let model = null;
  let tagWidth = 1;
  const fallbackHits = [];

  document.querySelectorAll("[data-icon]").forEach(el => { el.innerHTML = icon(el.dataset.icon); });
  parts.slice(1).forEach((part, offset) => {
    const li = document.createElement("li");
    const button = document.createElement("button");
    button.className = "part-row";
    button.type = "button";
    button.style.setProperty("--row-color", part.color);
    button.style.setProperty("--row-wash", part.color + "20");
    button.innerHTML = '<span class="row-icon">' + icon(part.mark, 17) + '</span><span>' + part.name + '</span><span class="row-arrow">' + icon("arrow", 13) + '</span>';
    button.addEventListener("click", () => selectPart(offset + 1));
    li.append(button);
    $("parts").append(li);
    rows.push(button);
  });

  function refreshStatus() {
    $("play").innerHTML = icon(playing ? "pause" : "play", 23);
    $("play").setAttribute("aria-label", playing ? "Pause build" : built === last ? "Replay build" : "Play build");
    $("statusText").textContent = demoStart !== null ? "Live demo" : playing ? "Building cell" : built === last ? "Cell assembled" : "Build paused";
    $("status").classList.toggle("paused", !playing && built !== last && demoStart === null);
  }

  function showPart(index) {
    selected = index;
    const part = parts[index];
    document.documentElement.style.setProperty("--part", part.color);
    document.documentElement.style.setProperty("--part-wash", part.color + "20");
    $("detailIcon").innerHTML = icon(part.mark, 27);
    $("detailKicker").textContent = index ? "Part " + index + " of " + last : "Cell boundary";
    $("detailName").textContent = part.name;
    $("detailText").textContent = part.text;
    $("tagText").textContent = part.name;
    $("annotation").hidden = false;
    tagWidth = $("tag").offsetWidth;
    rows.forEach((row, i) => row.setAttribute("aria-current", String(i + 1 === index)));
  }

  function setStep(index) {
    built = index;
    $("scrub").value = String(index);
    $("scrub").style.setProperty("--fill", (index / last * 100) + "%");
    $("scrub").setAttribute("aria-valuetext", index + " of " + last + " parts built. " + parts[index].name);
    $("counter").textContent = index + " / " + last + " parts";
    $("tally").textContent = index + " of " + last + " built";
    rows.forEach((row, i) => row.classList.toggle("built", i < index));
    showPart(index);
  }

  function setPlaying(value) {
    if (playing === value) return;
    playing = value;
    if (value) nextStep = performance.now() + (built ? 1250 : 980);
    refreshStatus();
  }

  function resetView() {
    Object.assign(goal, startCamera);
    goal.yaw += Math.round((camera.yaw - goal.yaw) / (2 * Math.PI)) * (2 * Math.PI);
    if (cut) goal.yaw += .61;
  }

  function setCut(on, frame = true) {
    cut = on;
    $("cut").setAttribute("aria-checked", String(on));
    if (on && frame) resetView();
  }

  function rebuild() {
    setCut(false);
    resetView();
    levels.fill(0);
    setStep(0);
    playing = true;
    nextStep = performance.now() + 980;
    refreshStatus();
  }

  function stopDemo() {
    if (demoStart === null) return;
    demoStart = null;
    setPlaying(false);
    refreshStatus();
  }

  function partPosition(index, time) {
    const p = parts[index].home;
    if (!index || still) return p;
    return [
      p[0] + .036 * Math.sin(time * .85 + index * 1.7),
      p[1] + .045 * Math.sin(time * 1.02 + index * 2.1),
      p[2] + .039 * Math.cos(time * .85 + index)
    ];
  }

  function focusPart(index) {
    if (!index || index === last) {
      resetView();
      return;
    }
    const [x, y, z] = parts[index].home;
    goal.x = x;
    goal.y = y;
    goal.z = cut ? Math.min(z, sliceZ - .04) : z;
    goal.zoom = index === 1 ? .68 : .59;
  }

  function selectPart(index, fromDemo = false) {
    if (!fromDemo) stopDemo();
    setPlaying(false);
    if (index > built) setStep(index);
    else showPart(index);
    focusPart(index);
  }

  function runDemo(time) {
    let seconds = (time - demoStart) / 1000;
    if (seconds >= 20.4) {
      demoStart = time;
      demoPhase = 0;
      rebuild();
      seconds = 0;
    }
    if (seconds < 10.9) {
      const target = clamp(Math.floor((seconds - .58) / .94) + 1, 0, last);
      if (target !== built) setStep(target);
      goal.yaw = startCamera.yaw + seconds * .030;
      return;
    }
    const phase = seconds < 12.9 ? 1 : seconds < 14.9 ? 2 : seconds < 17.3 ? 3 : seconds < 18.8 ? 4 : seconds < 19.5 ? 5 : 6;
    if (phase === demoPhase) return;
    demoPhase = phase;
    if (phase === 1) {
      setStep(last);
      setPlaying(false);
      goal.yaw = .83;
      goal.pitch = .30;
    } else if (phase === 2) {
      setCut(true);
    } else if (phase === 3) {
      selectPart(7, true);
    } else if (phase === 4) {
      setCut(false);
      resetView();
      setStep(5);
    } else if (phase === 5) {
      setStep(8);
    } else {
      setStep(last);
    }
  }

  function distance() {
    return Math.max(9.45, 11.25 * height / width) * camera.zoom;
  }

  function projection(point) {
    const [x, y, z] = [point[0] - camera.x, point[1] - camera.y, point[2] - camera.z];
    const sy = Math.sin(camera.yaw), cy = Math.cos(camera.yaw);
    const sp = Math.sin(camera.pitch), cp = Math.cos(camera.pitch);
    const radial = x * sy + z * cy;
    const depth = distance() - (radial * cp + y * sp);
    const scale = height / (2 * Math.tan(fov * Math.PI / 360) * Math.max(.07, depth));
    return { x: width / 2 + (x * cy - z * sy) * scale, y: height / 2 - (y * cp - radial * sp) * scale, depth, scale };
  }

  function positionLabel(time) {
    const part = parts[selected];
    const p = partPosition(selected, time);
    const tip = part.tip || [0, 0, 0];
    const point = projection([p[0] + tip[0], p[1] + tip[1], Math.min(p[2] + tip[2], slice - .02)]);
    const visible = point.depth > 0 && point.x > 8 && point.x < width - 8 && point.y > 9 && point.y < height - 9;
    $("annotation").style.visibility = visible ? "visible" : "hidden";
    if (!visible) return;
    const tag = $("tag");
    const toRight = point.x + 35 + tagWidth < width - 13 || point.x < width / 2;
    const left = clamp(toRight ? point.x + 34 : point.x - tagWidth - 34, 10, width - tagWidth - 10);
    const top = clamp(point.y - 39, 49, height - 78);
    const endX = toRight ? left : left + tagWidth;
    const endY = top + 15;
    const dx = endX - point.x, dy = endY - point.y;
    tag.style.transform = "translate(" + left + "px," + top + "px)";
    $("anchor").style.left = point.x + "px";
    $("anchor").style.top = point.y + "px";
    $("leader").style.width = Math.hypot(dx, dy) + "px";
    $("leader").style.transform = "translate(" + point.x + "px," + point.y + "px) rotate(" + Math.atan2(dy, dx) + "rad)";
  }

  function zoomBy(amount) {
    goal.zoom = clamp(goal.zoom * amount, .39, 1.86);
  }

  function resize() {
    width = Math.max(1, stage.clientWidth);
    height = Math.max(1, stage.clientHeight);
    pixelRatio = Math.min(window.devicePixelRatio || 1, 1.8);
    preview.width = Math.round(width * pixelRatio);
    preview.height = Math.round(height * pixelRatio);
    if (model) model.resize();
    tagWidth = $("tag").offsetWidth;
  }

  function chooseAt(x, y) {
    let index = model ? model.pick(x, y) : null;
    if (!model) {
      const hit = fallbackHits.slice().reverse().find(p => Math.hypot(p.x - x, p.y - y) <= p.r);
      if (hit) index = hit.index;
    }
    if (index === null) {
      let best = 22;
      for (let i = 1; i <= built; i++) {
        const p = partPosition(i, now / 1000);
        const tip = parts[i].tip || [0, 0, 0];
        const screen = projection([p[0] + tip[0], p[1] + tip[1], Math.min(slice, p[2] + tip[2])]);
        const delta = Math.hypot(x - screen.x, y - screen.y);
        if (delta < best && screen.depth > .1) {
          best = delta;
          index = i;
        }
      }
    }
    if (index !== null) selectPart(index);
    else if (Math.hypot((x - width / 2) / .85, y - height / 2) < Math.min(height * .40, width * .53)) selectPart(0);
  }

  document.addEventListener("pointerdown", stopDemo, true);
  document.addEventListener("wheel", stopDemo, { capture: true, passive: true });
  document.addEventListener("keydown", stopDemo);
  $("reset").addEventListener("click", resetView);
  $("rebuild").addEventListener("click", rebuild);
  $("cut").addEventListener("click", () => setCut(!cut));
  $("zoomIn").addEventListener("click", () => zoomBy(.82));
  $("zoomOut").addEventListener("click", () => zoomBy(1.22));
  $("play").addEventListener("click", () => {
    if (playing) setPlaying(false);
    else if (built === last) rebuild();
    else setPlaying(true);
  });
  $("scrub").addEventListener("input", event => {
    stopDemo();
    setPlaying(false);
    setStep(Number(event.currentTarget.value));
    goal.x = 0;
    goal.y = startCamera.y;
    goal.z = 0;
    goal.zoom = 1;
    refreshStatus();
  });

  stage.addEventListener("pointerdown", event => {
    if (!event.target.classList.contains("model") || (event.pointerType === "mouse" && event.button !== 0)) return;
    stage.setPointerCapture(event.pointerId);
    pointers.set(event.pointerId, [event.clientX, event.clientY]);
    if (pointers.size === 1) tap = { id: event.pointerId, x: event.clientX, y: event.clientY };
    else tap = null;
    stage.classList.add("dragging");
  });

  stage.addEventListener("pointermove", event => {
    const previous = pointers.get(event.pointerId);
    if (!previous) return;
    const current = [event.clientX, event.clientY];
    pointers.set(event.pointerId, current);
    if (pointers.size > 1) {
      const other = Array.from(pointers).find(([id]) => id !== event.pointerId)[1];
      const before = Math.hypot(previous[0] - other[0], previous[1] - other[1]);
      const after = Math.hypot(current[0] - other[0], current[1] - other[1]);
      if (before > 3 && after > 3) zoomBy(before / after);
      return;
    }
    if (tap && Math.hypot(current[0] - tap.x, current[1] - tap.y) < 6) return;
    tap = null;
    goal.yaw -= (current[0] - previous[0]) * .008;
    goal.pitch = clamp(goal.pitch + (current[1] - previous[1]) * .008, -1.18, 1.18);
  });

  function endPointer(event) {
    if (!pointers.delete(event.pointerId)) return;
    if (tap && tap.id === event.pointerId && event.type === "pointerup" && Math.hypot(event.clientX - tap.x, event.clientY - tap.y) < 8) {
      const bounds = stage.getBoundingClientRect();
      chooseAt(event.clientX - bounds.left - stage.clientLeft, event.clientY - bounds.top - stage.clientTop);
    }
    tap = null;
    if (!pointers.size) stage.classList.remove("dragging");
  }

  stage.addEventListener("pointerup", endPointer);
  stage.addEventListener("pointercancel", endPointer);
  stage.addEventListener("lostpointercapture", endPointer);
  stage.addEventListener("wheel", event => {
    event.preventDefault();
    const movement = event.deltaY * (event.deltaMode === 1 ? 15 : event.deltaMode === 2 ? 160 : 1);
    zoomBy(Math.exp(clamp(movement, -160, 160) * .0017));
  }, { passive: false });

  function randomSource(seed) {
    return () => {
      seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
      return seed / 4294967296;
    };
  }

  function cellPoint(x, y, z) {
    const swell = 1 + .062 * Math.sin(x * 3.9 + y * 3.2) * Math.cos(z * 3.8 - y * 2.0) + .036 * Math.cos(y * 5.8 - z * 3.4 - .7);
    return [x * 3.22 * swell - .18 * y + .14 * y * y, y * 2.23 * swell + .21 * x - .07 * x * x, z * 1.87 * swell + .11 * y];
  }

  function sectionOutline(depth, count = 110) {
    return Array.from({ length: count }, (_, i) => {
      const angle = i / count * 2 * Math.PI;
      let lower = -1, upper = 1, point;
      for (let j = 0; j < 15; j++) {
        const z = (lower + upper) * .5;
        const ring = Math.sqrt(1 - z * z);
        point = cellPoint(Math.cos(angle) * ring, Math.sin(angle) * ring, z);
        if (point[2] > depth) upper = z;
        else lower = z;
      }
      return [point[0], point[1], depth];
    });
  }

  const outline = sectionOutline(sliceZ);
  const membraneSamples = [];
  for (let j = 0; j <= 22; j++) {
    const angle = Math.PI * j / 22;
    for (let i = 0; i < 40; i++) {
      const turn = Math.PI * 2 * i / 40;
      membraneSamples.push(cellPoint(Math.cos(turn) * Math.sin(angle), Math.cos(angle), Math.sin(turn) * Math.sin(angle)));
    }
  }
  const fallbackRandom = randomSource(91);
  const ribosomePoints = ribosomeClusters.flatMap(cluster => Array.from({ length: 12 }, () => [
    cluster[0] + (fallbackRandom() - .5) * .58,
    cluster[1] + (fallbackRandom() - .5) * .46,
    cluster[2] + (fallbackRandom() - .5) * .45,
    .025 + fallbackRandom() * .027
  ]));
  const fiberPaths = Array.from({ length: 21 }, (_, i) => {
    const a = (i + .18) / 21 * Math.PI * 2;
    const b = a + 1.8 + fallbackRandom() * 2.30;
    const start = cellPoint(.88 * Math.cos(a), .88 * Math.sin(a), -.24);
    const finish = cellPoint(.87 * Math.cos(b), .87 * Math.sin(b), -.19 + (fallbackRandom() - .5) * .5);
    const inner = .43 + fallbackRandom() * .45;
    return [start, [mix(start[0], finish[0], .25) * inner, mix(start[1], finish[1], .25) + .38 * Math.sin(i), -.62 + fallbackRandom() * .58],
      [mix(start[0], finish[0], .72) * inner, mix(start[1], finish[1], .72) + .33 * Math.cos(i), -.74 + fallbackRandom() * .53], finish];
  });

  function hull(points) {
    points.sort((a, b) => a.x - b.x || a.y - b.y);
    const cross = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
    const half = order => {
      const result = [];
      for (const p of order) {
        while (result.length > 1 && cross(result[result.length - 2], result[result.length - 1], p) <= 0) result.pop();
        result.push(p);
      }
      result.pop();
      return result;
    };
    return half(points).concat(half(points.reverse()));
  }

  function canvasPath(points) {
    ctx.beginPath();
    points.forEach((p, i) => i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y));
    ctx.closePath();
  }

  function ellipse(x, y, rx, ry) {
    ctx.beginPath();
    ctx.ellipse(x, y, rx, ry, 0, 0, 2 * Math.PI);
  }

  function drawPreview(time) {
    if (!ctx) return;
    ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
    ctx.clearRect(0, 0, width, height);
    fallbackHits.length = 0;
    const sectionStrength = clamp(1 - Math.abs(slice - sliceZ) * 4, 0, 1);
    const ring = outline.map(projection).filter(p => p.depth > .08);
    const surface = membraneSamples.filter(p => p[2] <= slice).map(projection).filter(p => p.depth > .08);
    const edge = hull(surface.concat(sectionStrength ? ring : []));
    if (edge.length < 3) return;
    const center = projection([0, 0, -.2]);
    const glow = ctx.createRadialGradient(center.x, center.y, 0, center.x, center.y, Math.max(5, 3.3 * center.scale));
    glow.addColorStop(0, "#2f635128");
    glow.addColorStop(.65, "#28686e23");
    glow.addColorStop(1, "#67ead857");
    canvasPath(edge);
    ctx.fillStyle = glow;
    ctx.fill();
    ctx.strokeStyle = "#6bd8c673";
    ctx.lineWidth = 4;
    ctx.shadowColor = "#6de2ca";
    ctx.shadowBlur = 16;
    ctx.stroke();
    ctx.shadowBlur = 0;

    if (built === last || levels[last] > .03) {
      ctx.strokeStyle = "#67cfbe";
      ctx.globalAlpha = .35 * levels[last];
      ctx.lineWidth = 1.15;
      fiberPaths.forEach(path => {
        const [a, b, c, d] = path.map(projection);
        ctx.beginPath();
        ctx.moveTo(a.x, a.y);
        ctx.bezierCurveTo(b.x, b.y, c.x, c.y, d.x, d.y);
        ctx.stroke();
      });
      ctx.globalAlpha = 1;
    }

    const sprites = [];
    const clusters = { 5: ribosomePoints, 7: mitochondria, 8: lysosomes, 9: vesicles };
    for (let i = 1; i < last; i++) {
      if (levels[i] < .035) continue;
      const pos = partPosition(i, time);
      const delta = pos.map((value, j) => value - parts[i].home[j]);
      (clusters[i] || [parts[i].home]).forEach(item => {
        const p = item.slice(0, 3).map((value, j) => value + delta[j]);
        if (p[2] - (i === 1 ? .5 : .12) > slice) return;
        const screen = projection(p);
        if (screen.depth > .08) sprites.push({ ...screen, index: i, a: item[3], b: item[4] });
      });
    }
    sprites.sort((a,b) => (b.depth + (b.index === 1 ? .5 : 0)) - (a.depth + (a.index === 1 ? .5 : 0)));
    for (const p of sprites) {
      const i = p.index;
      const color = parts[i].color;
      const s = p.scale * (.76 + .24 * levels[i]);
      ctx.save();
      ctx.translate(p.x, p.y);
      ctx.scale(s, s);
      ctx.globalAlpha = Math.min(1, levels[i] * 1.8);
      const light = ctx.createRadialGradient(-.19, -.24, .01, 0, 0, 1);
      light.addColorStop(0, color);
      light.addColorStop(.7, color + "8e");
      light.addColorStop(1, color + "32");
      ctx.fillStyle = light;
      ctx.strokeStyle = color;
      ctx.lineWidth = .023;
      const wave = (offset, span, bend) => {
        ctx.beginPath();
        ctx.moveTo(-span, offset);
        ctx.bezierCurveTo(-span * .55, offset + bend, span * .10, offset - bend, span, offset + bend * .32);
        ctx.stroke();
      };
      let radius = .55;
      if (i === 1) {
        ellipse(0, 0, 1.13, .97);
        ctx.fill();
        ctx.stroke();
        ctx.strokeStyle = color + "6d";
        ellipse(0, 0, 1.02, .86);
        ctx.stroke();
        radius = .96;
      } else if (i === 2) {
        ellipse(0, 0, .38, .33);
        ctx.fill();
        ctx.stroke();
        radius = .38;
      } else if (i === 3 || i === 4 || i === 6) {
        ctx.rotate(i === 3 ? -1.1 : i === 6 ? .18 : -.18);
        ctx.lineWidth = i === 4 ? .057 : .075;
        ctx.lineCap = "round";
        const count = i === 4 ? 4 : 6;
        for (let j = 0; j < count; j++) {
          const offset = (j - (count - 1) / 2) * .135;
          const span = (i === 3 ? .65 : .62) - Math.abs(offset) * .43;
          ctx.strokeStyle = j % 2 ? color : color + "a0";
          wave(offset, span, i === 6 ? .19 : .40);
          if (i === 3) {
            ctx.fillStyle = "#f0c9ff";
            for (let k = 0; k < 8; k++) {
              const t = k / 7;
              ellipse((t * 2 - 1) * span, offset + .08 * Math.sin(t * 5.8), .020, .020);
              ctx.fill();
            }
          }
        }
        radius = .63;
      } else if (i === 7) {
        ctx.rotate(p.a);
        ctx.scale(p.b, p.b);
        ellipse(0, 0, .65, .30);
        ctx.fill();
        ctx.stroke();
        ctx.beginPath();
        for (let j = 0; j < 55; j++) {
          const u = j / 54;
          const x = (u - .5) * 1.04;
          const y = Math.sin(u * Math.PI * 10) * .17 * Math.sin(u * Math.PI);
          if (j) ctx.lineTo(x, y);
          else ctx.moveTo(x, y);
        }
        ctx.lineWidth = .044;
        ctx.stroke();
        radius = .53 * p.b;
      } else if (i === 10) {
        for (let j = 0; j < 2; j++) {
          ctx.save();
          ctx.translate(j ? .16 : -.12, j ? -.02 : .11);
          ctx.rotate(j ? .65 : -1.02);
          ctx.fillStyle = color + "59";
          ctx.fillRect(-.23, -.12, .46, .24);
          for (let k = -2; k <= 2; k++) {
            ctx.beginPath();
            ctx.moveTo(-.23, k * .056);
            ctx.lineTo(.23, k * .056);
            ctx.stroke();
          }
          ctx.restore();
        }
        radius = .37;
      } else {
        radius = p.a;
        const bubble = ctx.createRadialGradient(-radius * .35, -radius * .47, 0, 0, 0, radius);
        bubble.addColorStop(0, "#fff4db");
        bubble.addColorStop(.28, color);
        bubble.addColorStop(1, color + "44");
        ctx.fillStyle = bubble;
        ellipse(0, 0, radius, radius * .94);
        ctx.fill();
        if (i !== 5) ctx.stroke();
      }
      ctx.restore();
      if (i <= built) fallbackHits.push({ x: p.x, y: p.y, r: Math.max(i === 5 ? 5 : 12, radius * s), index: i });
    }

    if (sectionStrength && ring.length > 3) {
      ctx.globalAlpha = sectionStrength;
      canvasPath(ring);
      ctx.fillStyle = "#5bd5bb17";
      ctx.fill();
      ctx.strokeStyle = "#a0f3dfd4";
      ctx.lineWidth = 1.9;
      ctx.stroke();
      ctx.globalAlpha = 1;
    }

    ctx.fillStyle = "#a2efdb";
    for (let i = 0; i < membraneSamples.length; i += 7) {
      const p = membraneSamples[i];
      if (p[2] > slice) continue;
      const dot = projection(p);
      if (dot.depth < .08) continue;
      ctx.globalAlpha = .17 + .11 * Math.sin(i * 3);
      ellipse(dot.x, dot.y, 1.10, 1.10);
      ctx.fill();
    }
    ctx.globalAlpha = 1;
    canvasPath(edge);
    ctx.strokeStyle = "#a4f2dcbd";
    ctx.lineWidth = 1.15;
    ctx.stroke();
  }

  function createModel(T) {
    const element = document.createElement("canvas");
    const options = { alpha: true, antialias: true, powerPreference: "high-performance" };
    const context = element.getContext("webgl2", options) || element.getContext("webgl", options);
    if (!context) return null;

    element.className = "model";
    element.setAttribute("aria-hidden", "true");
    const renderer = new T.WebGLRenderer({ canvas: element, context, ...options });
    renderer.setClearColor(0x000000, 0);
    renderer.localClippingEnabled = true;
    renderer.outputColorSpace = T.SRGBColorSpace;
    renderer.toneMapping = T.ACESFilmicToneMapping;
    renderer.toneMappingExposure = 1.09;
    const scene = new T.Scene();
    const cam = new T.PerspectiveCamera(fov, 1, .08, 70);
    const V = (x, y, z) => new T.Vector3(x, y, z);
    const vector = p => new T.Vector3(...p);
    const plane = new T.Plane(V(0, 0, -1), slice);
    const planes = [plane];
    const noise = randomSource(253);
    const sharedTime = { value: 0 };
    const sharedSlice = { value: slice };
    const unitSphere = new T.SphereGeometry(1, 30, 22);
    const beadGeometry = new T.IcosahedronGeometry(1, 1);
    const yAxis = V(0, 1, 0);
    const zAxis = V(0, 0, 1);
    const parts3D = parts.map((_, index) => {
      const group = new T.Group();
      group.userData.part = index;
      group.position.fromArray(parts[index].home);
      if (index) scene.add(group);
      return group;
    });

    scene.add(new T.HemisphereLight(0xc4eeff, 0x493055, 1.76));
    [[0xffeddd, 2.55, -4, 5, 7], [0x78dfeb, 1.68, 4, 3, -5], [0xc092ff, .73, 2, -4, 3]].forEach(([color, power, x, y, z]) => {
      const light = new T.DirectionalLight(color, power);
      light.position.set(x, y, z);
      scene.add(light);
    });

    function deform(geometry, transform) {
      const position = geometry.attributes.position;
      for (let i = 0; i < position.count; i++) {
        position.setXYZ(i, ...transform(position.getX(i), position.getY(i), position.getZ(i)));
      }
      geometry.computeVertexNormals();
      geometry.computeBoundingSphere();
      return geometry;
    }

    function material(color, settings = {}) {
      return new T.MeshStandardMaterial({ color, roughness: .44, metalness: .05, clippingPlanes: planes, ...settings });
    }

    function shell(color, baseOpacity, rimOpacity, pulse) {
      return new T.ShaderMaterial({
        vertexShader: $("shellVertex").textContent,
        fragmentShader: $("shellFragment").textContent,
        uniforms: { tint: { value: new T.Color(color) }, clockTime: sharedTime, slice: sharedSlice,
          baseOpacity: { value: baseOpacity }, rimOpacity: { value: rimOpacity }, pulse: { value: pulse } },
        transparent: true,
        depthWrite: false,
        side: T.DoubleSide,
        forceSinglePass: true
      });
    }

    function mesh(parent, geometry, mat, p = [0, 0, 0], scale = [1, 1, 1]) {
      const result = new T.Mesh(geometry, mat);
      result.position.fromArray(p);
      result.scale.fromArray(scale);
      parent.add(result);
      return result;
    }

    function ball(parent, mat, p, scale) {
      return mesh(parent, unitSphere, mat, p, scale);
    }

    function tube(parent, points, radius, mat, closed = false, segments = 36) {
      const curve = new T.CatmullRomCurve3(points.map(p => Array.isArray(p) ? vector(p) : p), closed);
      return mesh(parent, new T.TubeGeometry(curve, segments, radius, 7, closed), mat);
    }

    function dots(parent, items, mat) {
      const cloud = new T.InstancedMesh(beadGeometry, mat, items.length);
      const transform = new T.Object3D();
      for (let i = 0; i < items.length; i++) {
        const [x, y, z, size, color] = items[i];
        transform.position.set(x, y, z);
        transform.scale.setScalar(size);
        transform.updateMatrix();
        cloud.setMatrixAt(i, transform.matrix);
        cloud.setColorAt(i, new T.Color(color));
      }
      cloud.instanceMatrix.needsUpdate = true;
      cloud.computeBoundingSphere();
      parent.add(cloud);
      return cloud;
    }

    function band(parent, at, axis, breadth, thickness, mat) {
      const length = 47, round = 12;
      const vertices = [], indices = [];
      for (let i = 0; i <= length; i++) {
        const t = i / length;
        const center = at(t);
        const direction = at(Math.min(1, t + .004)).sub(at(Math.max(0, t - .004))).normalize();
        const lateral = new T.Vector3().crossVectors(direction, axis).normalize();
        const normal = new T.Vector3().crossVectors(lateral, direction).normalize();
        const taper = .04 + .96 * Math.pow(Math.sin(Math.PI * t), .45);
        for (let j = 0; j < round; j++) {
          const a = j / round * Math.PI * 2;
          const p = center.clone().addScaledVector(lateral, Math.cos(a) * breadth * taper)
            .addScaledVector(normal, Math.sin(a) * thickness * Math.sqrt(taper));
          vertices.push(p.x, p.y, p.z);
          if (i < length) {
            const first = i * round + j;
            const second = i * round + (j + 1) % round;
            indices.push(first, first + round, second, second, first + round, second + round);
          }
        }
      }
      const geom = new T.BufferGeometry();
      geom.setAttribute("position", new T.Float32BufferAttribute(vertices, 3));
      geom.setIndex(indices);
      geom.computeVertexNormals();
      return mesh(parent, geom, mat);
    }

    function local(point, index) {
      return point.slice(0, 3).map((value, axis) => value - parts[index].home[axis]);
    }

    const membrane = mesh(scene, deform(new T.SphereGeometry(1, 112, 76), cellPoint), shell("#5fdfc8", .035, .79, still ? 0 : .008));
    membrane.renderOrder = 7;
    const innerMembrane = mesh(scene, membrane.geometry, shell("#6cbbdb", .011, .30, still ? 0 : .006), [0, 0, 0], [.980, .980, .980]);
    innerMembrane.renderOrder = 6;

    const previewRing = outline.map(vector);
    const rim = tube(scene, previewRing, .022, new T.MeshBasicMaterial({ color: "#7ff0d5", transparent: true, depthWrite: false }), true, outline.length);
    rim.renderOrder = 8;
    const innerRim = tube(scene, previewRing.map(p => V(p.x * .983, p.y * .983, sliceZ - .006)), .010,
      new T.MeshBasicMaterial({ color: "#83d8d5", transparent: true, depthWrite: false }), true, outline.length);
    innerRim.renderOrder = 8;
    const crossSection = new T.Shape();
    outline.forEach(([x, y], i) => i ? crossSection.lineTo(x, y) : crossSection.moveTo(x, y));
    crossSection.closePath();
    const face = mesh(scene, new T.ShapeGeometry(crossSection), new T.MeshBasicMaterial({ color: "#57bba8", side: T.DoubleSide, transparent: true, depthWrite: false }), [0, 0, sliceZ - .005]);
    face.renderOrder = 5;

    const sprite = document.createElement("canvas");
    sprite.width = sprite.height = 32;
    const paint = sprite.getContext("2d");
    const halo = paint.createRadialGradient(16, 16, 1, 16, 16, 16);
    halo.addColorStop(0, "#ffffff");
    halo.addColorStop(.31, "#ffffffb8");
    halo.addColorStop(1, "#ffffff00");
    paint.fillStyle = halo;
    paint.fillRect(0, 0, 32, 32);
    const pointMap = new T.CanvasTexture(sprite);
    const shellDust = [];
    const outsideDust = [];
    for (let i = 0; i < 290; i++) {
      const y = noise() * 2 - 1;
      const a = noise() * Math.PI * 2;
      const r = Math.sqrt(1 - y * y);
      shellDust.push(...cellPoint(Math.cos(a) * r, y, Math.sin(a) * r).map(n => n * .994));
      if (i < 65) outsideDust.push((noise() - .5) * 11.8, (noise() - .5) * 7, -3.8 - noise() * 4.3);
    }

    function points(vertices, settings) {
      const geometry = new T.BufferGeometry();
      geometry.setAttribute("position", new T.Float32BufferAttribute(vertices, 3));
      const cloud = new T.Points(geometry, new T.PointsMaterial({ transparent: true, depthWrite: false, map: pointMap, ...settings }));
      scene.add(cloud);
      return cloud;
    }

    const particles = points(shellDust, { color: "#9df9e1", size: .042, opacity: .59, clippingPlanes: planes });
    particles.renderOrder = 5;
    const ambientDust = points(outsideDust, { color: "#a0b8cb", size: .032, opacity: .4 });

    const nucleus = parts3D[1];
    const nuclearSurface = deform(new T.SphereGeometry(1, 55, 38), (x, y, z) => {
      const d = 1 + .043 * Math.sin(4 * x + 1.8 * y) * Math.cos(4.5 * z - y);
      return [x * 1.16 * d, y * .99 * d, z * .88 * d];
    });
    const nuclearEnvelope = mesh(nucleus, nuclearSurface, shell("#a88cfa", .155, .68, still ? 0 : .009));
    nuclearEnvelope.renderOrder = 4;
    const innerEnvelope = mesh(nucleus, nuclearSurface, shell("#a99cfa", .049, .31, 0), [0, 0, 0], [.948, .948, .948]);
    innerEnvelope.renderOrder = 3;
    const pores = Array.from({ length: 125 }, () => {
      const y = noise() * 2 - 1, a = noise() * Math.PI * 2, r = Math.sqrt(1 - y * y);
      return [Math.cos(a) * r * 1.15, y * .982, Math.sin(a) * r * .872, .012 + noise() * .022, "#b7a0fd"];
    });
    dots(nucleus, pores, material("#ffffff", { roughness: .65, transparent: true, opacity: .48, depthWrite: false }));
    const chromatin = material("#8b6dc7", { transparent: true, opacity: .38, depthWrite: false, roughness: .76 });
    for (let j = 0; j < 5; j++) {
      const coords = Array.from({ length: 23 }, (_, i) => {
        const a = i / 22 * Math.PI * 2.4 + j * .73;
        return [.78 * Math.cos(a) * (.94 + .09 * Math.sin(i)), .55 * Math.sin(a) + .07 * (j - 2), -.31 + .17 * Math.sin(2.7 * a + j)];
      });
      tube(nucleus, coords, .014, chromatin);
    }

    const nucleolus = parts3D[2];
    const nucleolarBody = deform(new T.SphereGeometry(1, 42, 28), (x, y, z) => {
      const d = 1 + .084 * Math.cos(x * 8 + y * 5) * Math.sin(z * 9 - y * 5) + .025 * Math.sin(y * 17);
      return [x * .39 * d, y * .347 * d, z * .326 * d];
    });
    mesh(nucleolus, nucleolarBody, material("#df64b5", { roughness: .53, emissive: "#5a174a", emissiveIntensity: .27 }));
    const granules = Array.from({ length: 78 }, () => {
      const y = noise() * 2 - 1, a = noise() * Math.PI * 2, r = Math.sqrt(1 - y * y);
      return [Math.cos(a) * r * .377, y * .338, Math.sin(a) * r * .317, .009 + noise() * .020, noise() > .42 ? "#f284c3" : "#903578"];
    });
    dots(nucleolus, granules, material("#ffffff", { roughness: .68 }));

    const rough = parts3D[3];
    const erDots = [];
    for (let j = 0; j < 5; j++) {
      const at = t => {
        const a = 1.86 + t * (2.15 + j * .065);
        const r = 1.09 + j * .174 + .059 * Math.sin(t * 18 + j);
        return V(1.15 + r * Math.cos(a), .04 + .80 * r * Math.sin(a), -.17 + .10 * Math.sin(t * 8 + j) + .052 * j);
      };
      const shade = ["#8179d2", "#8e85dd", "#968ce8", "#a399ee", "#a59bf5"][j];
      band(rough, at, zAxis, .106, .048, material(shade, { roughness: .46 }));
      for (let k = 0; k < 27; k++) {
        const p = at(.04 + noise() * .92);
        erDots.push([p.x + (noise() - .5) * .135, p.y + (noise() - .5) * .135, p.z + .039 + noise() * .035, .016 + noise() * .021, noise() > .4 ? "#c7b7ff" : "#a277d0"]);
      }
    }
    dots(rough, erDots, material("#ffffff", { roughness: .58 }));

    const smooth = parts3D[4];
    const smoothPaths = [
      [[-.61,.21,-.23],[-.40,.53,-.15],[-.09,.48,-.02],[.05,.19,.15],[.31,.09,.14],[.62,.29,.08],[.82,.29,-.11]],
      [[-.63,.02,.03],[-.29,.09,.12],[-.12,.23,.23],[.20,.29,.19],[.43,.42,.05],[.69,.45,-.12]],
      [[-.31,.10,.12],[-.11,-.14,.13],[.08,-.29,.04],[.31,-.22,-.06],[.48,-.06,.04],[.75,-.11,.17]],
      [[-.44,.52,-.15],[-.26,.64,-.24],[.11,.62,-.20],[.36,.52,-.09],[.43,.42,.05]],
      [[.29,.10,.14],[.26,.02,.33],[.48,-.12,.29],[.61,-.28,.13],[.68,-.34,-.14]],
      [[-.12,-.15,.13],[-.23,-.32,.03],[-.38,-.23,-.13],[-.56,-.09,-.15],[-.63,.02,.03]],
      [[.34,.51,-.10],[.43,.30,-.18],[.55,.15,-.13],[.77,.06,-.17],[.89,.11,-.27]],
      [[-.15,.48,-.04],[-.15,.31,-.19],[.08,.06,-.17],[.31,-.22,-.06]]
    ];
    const smoothMats = ["#40adab", "#55cbb7", "#65d3bf"].map(color => material(color, { roughness: .41 }));
    smoothPaths.forEach((path, index) => {
      const mat = smoothMats[index % smoothMats.length];
      const radius = .055 + (index % 3) * .011;
      tube(smooth, path, radius, mat, false, 33);
      ball(smooth, mat, path[0], [radius, radius, radius]);
      ball(smooth, mat, path[path.length - 1], [radius, radius, radius]);
    });

    const ribosomeBeads = [];
    ribosomePoints.forEach(([x, y, z, size]) => {
      const p = local([x, y, z], 5);
      ribosomeBeads.push([...p, size, "#e7a477"], [p[0] + size * .72, p[1] - size * .37, p[2] + size * .34, size * .73, "#ffd2aa"]);
    });
    dots(parts3D[5], ribosomeBeads, material("#ffffff", { roughness: .63 }));

    const golgi = parts3D[6];
    const buds = [];
    ["#c56393", "#db719d", "#e87ca6", "#ed90b0", "#f09ab3", "#f6acb4"].forEach((color, j) => {
      const at = t => {
        const u = 2 * t - 1;
        const span = .71 - Math.abs(j - 2.5) * .064;
        return V(u * span + .036 * j, .144 * (j - 2.5) + .21 * u * u + .045 * Math.sin(t * 6 + j), -.11 + j * .063 + .14 * u);
      };
      band(golgi, at, yAxis, .26 - Math.abs(j - 2.5) * .025, .042 + j * .0025, material(color, { roughness: .43 }));
      [at(.045), at(.955)].forEach(p => {
        buds.push([p.x + (noise() - .5) * .13, p.y + .05, p.z + .03, .038 + noise() * .028, color]);
      });
    });
    dots(golgi, buds, material("#ffffff", { roughness: .48 }));

    const bean = deform(new T.SphereGeometry(1, 48, 30), (x, y, z) => [x * .69, y * .315 + .16 * x * x - .073, z * .321 + .044 * x]);
    const beanCore = material("#c66a34", { roughness: .48, emissive: "#853617", emissiveIntensity: .28 });
    const folds = material("#ffb16c", { roughness: .38, emissive: "#963c24", emissiveIntensity: .25 });
    const mitoSkin = shell("#f9aa68", .115, .59, .005);
    mitochondria.forEach(point => {
      const node = new T.Group();
      parts3D[7].add(node);
      node.position.fromArray(local(point, 7));
      node.rotation.set(.16, point[3] * .52, point[3]);
      node.scale.setScalar(point[4]);
      mesh(node, bean, beanCore, [0, 0, -.10], [.92, .90, .67]);
      const cover = mesh(node, bean, mitoSkin);
      cover.renderOrder = 3;
      const cristae = Array.from({ length: 58 }, (_, i) => {
        const t = i / 57, u = t * 2 - 1;
        return [u * .59, .191 * Math.sin(t * Math.PI * 11) * Math.pow(Math.sin(Math.PI * t), .48) + .11 * u * u - .066, .056 + .15 * (1 - u * u)];
      });
      tube(node, cristae, .039, folds, false, 80);
      const border = Array.from({ length: 45 }, (_, i) => {
        const a = i / 45 * Math.PI * 2;
        return [.633 * Math.cos(a), .281 * Math.sin(a) + .142 * Math.cos(a) ** 2 - .071, .102 + .04 * Math.cos(a)];
      });
      tube(node, border, .016, material("#ee9155", { roughness: .43 }), true, 54);
    });

    const lysoShell = shell("#bde560", .16, .72, .005);
    const lysoCore = material("#7da342", { roughness: .52, emissive: "#334a1a", emissiveIntensity: .21 });
    const enzyme = material("#ffffff", { roughness: .57 });
    lysosomes.forEach(point => {
      const p = local(point, 8), r = point[3];
      const cover = ball(parts3D[8], lysoShell, p, [r, r * .96, r]);
      cover.renderOrder = 3;
      ball(parts3D[8], lysoCore, [p[0], p[1], p[2] - r * .30], [r * .75, r * .71, r * .56]);
      const enzymes = Array.from({ length: 13 }, () => {
        const angle = noise() * 2 * Math.PI, radius = Math.sqrt(noise()) * r * .77;
        return [p[0] + Math.cos(angle) * radius, p[1] + Math.sin(angle) * radius, p[2] + (1 - radius / r) * r * .49, r * (.095 + noise() * .063), noise() > .3 ? "#d8ed91" : "#a6c764"];
      });
      dots(parts3D[8], enzymes, enzyme);
    });

    const vesicleShell = shell("#76d5ff", .14, .73, .007);
    const cargo = material("#8dccdc", { roughness: .39, emissive: "#24546d", emissiveIntensity: .40 });
    vesicles.forEach(point => {
      const p = local(point, 9), r = point[3];
      const cover = ball(parts3D[9], vesicleShell, p, [r, r, r * .96]);
      cover.renderOrder = 3;
      ball(parts3D[9], cargo, [p[0] - .19 * r, p[1] - .10 * r, p[2] - .35 * r], [r * .37, r * .32, r * .37]);
    });

    const rodGeom = new T.CylinderGeometry(.022, .024, .43, 10);
    const barrel = new T.TorusGeometry(.118, .017, 7, 24);
    const rodMat = material("#ffffff", { roughness: .40 });
    const ringMat = material("#dcaa54", { roughness: .45 });
    for (let j = 0; j < 2; j++) {
      const node = new T.Group();
      node.position.set(j ? .15 : -.115, j ? -.035 : .085, j ? -.067 : .07);
      node.rotation.set(j ? -.39 : .30, j ? -.25 : .50, j ? -1.09 : .36);
      parts3D[10].add(node);
      const rods = new T.InstancedMesh(rodGeom, rodMat, 27);
      const transform = new T.Object3D();
      for (let k = 0; k < 27; k++) {
        const angle = (Math.floor(k / 3) + ((k % 3) - 1) * .19) / 9 * Math.PI * 2;
        const rad = k % 3 === 1 ? .140 : .122;
        transform.position.set(rad * Math.cos(angle), 0, rad * Math.sin(angle));
        transform.updateMatrix();
        rods.setMatrixAt(k, transform.matrix);
        rods.setColorAt(k, new T.Color(k % 3 === 1 ? "#f8d675" : "#dfac57"));
      }
      node.add(rods);
      [-.192, .192].forEach(y => { mesh(node, barrel, ringMat, [0,y,0]).rotation.x = Math.PI / 2; });
    }

    ["#76c4b5", "#599eab", "#82d1ae", "#8b9ace"].forEach((color, j) => {
      const mat = new T.MeshBasicMaterial({ color, transparent: true, opacity: .39, depthWrite: false, clippingPlanes: planes });
      fiberPaths.forEach((path, index) => {
        if (index % 4 !== j) return;
        tube(parts3D[11], path, index % 4 === 0 ? .018 : .012, mat, false, 37);
      });
    });

    const ray = new T.Raycaster();
    const cursor = new T.Vector2();
    const renderState = {
      resize() {
        cam.aspect = width / height;
        cam.updateProjectionMatrix();
        renderer.setPixelRatio(pixelRatio);
        renderer.setSize(width, height, false);
      },
      draw(time) {
        sharedTime.value = still ? 0 : time;
        sharedSlice.value = slice;
        plane.constant = slice;
        const alpha = clamp(1 - Math.abs(slice - sliceZ) * 4.2, 0, 1);
        rim.visible = innerRim.visible = face.visible = alpha > .01;
        rim.material.opacity = .93 * alpha;
        innerRim.material.opacity = .60 * alpha;
        face.material.opacity = .094 * alpha;
        ambientDust.rotation.z = still ? 0 : Math.sin(time * .16) * .035;
        const radius = distance();
        cam.position.set(camera.x + radius * Math.cos(camera.pitch) * Math.sin(camera.yaw),
          camera.y + radius * Math.sin(camera.pitch), camera.z + radius * Math.cos(camera.pitch) * Math.cos(camera.yaw));
        cam.lookAt(camera.x, camera.y, camera.z);
        for (let i = 1; i < parts3D.length; i++) {
          const group = parts3D[i];
          group.visible = levels[i] > .027;
          if (!group.visible) continue;
          group.position.fromArray(partPosition(i, time));
          group.scale.setScalar(levels[i] * (still ? 1 : 1 + .017 * Math.sin(time * 1.75 + i * .82)));
          group.rotation.z = still ? 0 : .022 * Math.sin(time * .73 + i);
          group.rotation.y = still ? 0 : .025 * Math.cos(time * .85 + i);
        }
        renderer.render(scene, cam);
      },
      pick(x, y) {
        cursor.set(x / width * 2 - 1, 1 - y / height * 2);
        ray.setFromCamera(cursor, cam);
        const hits = ray.intersectObjects(parts3D.slice(1, built + 1).filter(group => group.visible), true)
          .filter(hit => hit.point.z <= slice + .008).map(hit => {
            let item = hit.object;
            while (item.userData.part === undefined) item = item.parent;
            return { index: item.userData.part, distance: hit.distance };
          });
        if (!hits.length) return null;
        const hit = hits[0];
        const solid = hit.index === last ? hits.find(item => item.index !== last && item.distance - hit.distance < .39) || hit : hit;
        if (solid.index === 1) {
          const inner = hits.find(item => item.index === 2 && item.distance - solid.distance < 1.25);
          if (inner) return 2;
        }
        return solid.index;
      }
    };

    element.addEventListener("webglcontextlost", event => {
      event.preventDefault();
      model = null;
      element.hidden = true;
      preview.hidden = false;
    });
    element.addEventListener("webglcontextrestored", () => {
      model = renderState;
      renderState.resize();
      element.hidden = false;
      preview.hidden = true;
    });
    stage.insertBefore(element, preview);
    renderState.resize();
    preview.hidden = true;
    return renderState;
  }

  function animate(time) {
    const dt = clamp((time - now) / 1000, 0, .05);
    now = time;
    if (demoStart !== null) {
      runDemo(time);
    } else if (playing && time >= nextStep) {
      setStep(Math.min(last, built + 1));
      nextStep = time + 1420;
      if (built === last) setPlaying(false);
    }
    const ease = 1 - Math.exp(-dt * (still ? 25 : 8.1));
    for (const key of Object.keys(camera)) camera[key] = mix(camera[key], goal[key], ease);
    slice = mix(slice, cut ? sliceZ : 3.6, 1 - Math.exp(-dt * 9.5));
    for (let i = 1; i <= last; i++) levels[i] = mix(levels[i], Number(i <= built), ease);
    if (model) model.draw(time / 1000);
    else drawPreview(time / 1000);
    positionLabel(time / 1000);
    requestAnimationFrame(animate);
  }

  setStep(0);
  refreshStatus();
  resize();
  if (typeof ResizeObserver !== "undefined") new ResizeObserver(resize).observe(stage);
  else window.addEventListener("resize", resize);
  requestAnimationFrame(animate);

  import("https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js").then(three => {
    model = createModel(three);
  }).catch(() => {
    preview.hidden = false;
  });
})();
</script>
</body>
</html>